openrtc 2.2.0 → 2.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/dist/{DelegatingRuntimeAdapter-BkLR3TNN.d.ts → DelegatingRuntimeAdapter-DE4LTGAJ.d.ts} +3 -3
  2. package/dist/{ITransport-yaruAmx3.d.ts → ITransport-CjxCQ6q7.d.ts} +3 -4
  3. package/dist/{IpcRuntimeAdapter-DDKeQ6UC.d.ts → IpcRuntimeAdapter-CE0va9Tr.d.ts} +2 -2
  4. package/dist/WasmBridge-75F6GKHG.js +1 -0
  5. package/dist/{assembly-BTzwQuwI.d.ts → assembly-Bmi65-tK.d.ts} +3 -3
  6. package/dist/{capabilities-BwzPe51I.d.ts → capabilities-BPuynml5.d.ts} +1 -1
  7. package/dist/{chunk-SUWCBTBQ.js → chunk-2L6ULC32.js} +1 -1
  8. package/dist/{chunk-LN4ALFT6.js → chunk-2SUSPEC4.js} +1 -1
  9. package/dist/{chunk-FKEKINIM.js → chunk-7BJKDBLP.js} +1 -1
  10. package/dist/chunk-HEAJ7ZUR.js +1 -0
  11. package/dist/{chunk-GND6UW37.js → chunk-KRJECX7X.js} +1 -1
  12. package/dist/chunk-Q6KXVTSH.js +2 -0
  13. package/dist/{chunk-F4BJ72HN.js → chunk-R35AWMNY.js} +1 -1
  14. package/dist/chunk-UILOGUOU.js +1 -0
  15. package/dist/chunk-WA434EWD.js +2 -0
  16. package/dist/chunk-XAL4T6TB.js +3 -0
  17. package/dist/{chunk-OUFHVLDQ.js → chunk-Z2IS6NH2.js} +1 -1
  18. package/dist/{controlPlane-JJFURVOX.js → controlPlane-KVFZ7BR5.js} +1 -1
  19. package/dist/coreClient.d.ts +4 -4
  20. package/dist/coreClient.js +1 -1
  21. package/dist/{deviceEnrollment-Z2EHP2EX.js → deviceEnrollment-VACC64CQ.js} +2 -2
  22. package/dist/index.d.ts +6 -6
  23. package/dist/index.js +1 -1
  24. package/dist/ipcFactory-32R47AVK.js +1 -0
  25. package/dist/openrtc-4EZPCHWM.js +2 -0
  26. package/dist/openrtc_bg.wasm +0 -0
  27. package/dist/runtime/WasmRuntimeAdapter.d.ts +4 -4
  28. package/dist/runtime/WasmRuntimeAdapter.js +1 -1
  29. package/dist/runtime/device-status.d.ts +2 -2
  30. package/dist/runtime/factories.d.ts +6 -6
  31. package/dist/runtime/factories.js +1 -1
  32. package/dist/runtime/index.d.ts +10 -10
  33. package/dist/runtime/index.js +1 -1
  34. package/dist/testing.d.ts +10 -5
  35. package/dist/testing.js +1 -1
  36. package/dist/transport/index.d.ts +2 -2
  37. package/dist/transport/index.js +1 -1
  38. package/dist/{types-C4TIUgOJ.d.ts → types--jQzenZR.d.ts} +3 -2
  39. package/dist/{types-D67HlF0p.d.ts → types-DDhMQkK8.d.ts} +1 -1
  40. package/package.json +1 -1
  41. package/dist/WasmBridge-DVQ2YPRB.js +0 -1
  42. package/dist/chunk-2IRNZN3N.js +0 -1
  43. package/dist/chunk-DI5VSZ2T.js +0 -2
  44. package/dist/chunk-NRXEG5GQ.js +0 -1
  45. package/dist/chunk-NXM5ZGHD.js +0 -2
  46. package/dist/chunk-UGZJJQPM.js +0 -3
  47. package/dist/ipcFactory-DQFK65VE.js +0 -1
  48. package/dist/openrtc-INQDCF23.js +0 -2
@@ -0,0 +1,3 @@
1
+ import {c as c$2,d,b as b$3}from'./chunk-HUG5AX7R.js';import {a}from'./chunk-DUY34MGT.js';import {a as a$1}from'./chunk-R35AWMNY.js';import {q,v,x,i,k as k$1,w as w$1,z,u,j,b as b$2,a as a$2,l,m,n,o as o$1,y,p as p$2,c as c$5,h as h$2,d as d$3,e as e$3,f as f$1,g as g$2}from'./chunk-Z2IS6NH2.js';import {c as c$3,e as e$1}from'./chunk-AJQVMVYW.js';import {g as g$1,o,p,q as q$1,b as b$1,h as h$1,c as c$4,j as j$1,k as k$2,m as m$1,l as l$1,f as f$3,i as i$1}from'./chunk-WA434EWD.js';import {d as d$1,e as e$2,f}from'./chunk-HEAJ7ZUR.js';import {f as f$2,j as j$2,h as h$3,g as g$3,e as e$4,b as b$4,i as i$3,a as a$3}from'./chunk-7BJKDBLP.js';import {g,h,c as c$1,e,p as p$1,s,q as q$2,t,b,d as d$2,z as z$1,y as y$1,x as x$1,i as i$2,u as u$1,j as j$3,l as l$2,v as v$1,k as k$3,m as m$2,n as n$1}from'./chunk-2L6ULC32.js';import {c}from'./chunk-2SUSPEC4.js';import*as $e from'@moq/net';var Po=Symbol.for("openrtc.wasm-runtime-loader");function ja(r){globalThis[Po]=r;}async function Ro(){let r=globalThis[Po];if(!r)throw new Error("[OpenRTC] Browser WASM runtime is not installed. Native applications should use `OpenRTC.native(...)`.");return r()}var yt=class{constructor(e,t,n=()=>{}){this.client=e;this.backend=t;this.onLifecycleMutation=n;}async connectToDevice(e){let t=this.backend;if(!t||typeof t.connectToDevice!="function")throw new Error("Selected runtime adapter does not support connectToDevice().");return e.deviceId&&(this.clearManualDisconnectProjection(e.deviceId),await t.excludeAutoConnect?.(e.deviceId,false)),t.connectToDevice(e)}async connectRaw(e){return this.client.connectRaw(e.ticket,e.timeoutMs)}async openBi(e){return this.client.openBi(e)}async openUni(e){return this.client.openUni(e)}async isConnected(e){return this.client.isConnected(e)}async disconnectNode(e){try{await this.client.disconnectNode(e);}finally{this.onLifecycleMutation();}}async disconnectDevice(e){let t=this.backend,n=null;try{await t?.excludeAutoConnect?.(e,!0);}catch(i){n=i;}try{try{t&&typeof t.disconnectDevice=="function"&&await t.disconnectDevice(e);}finally{await this.client.forceDisconnectPeer(e);}}finally{this.onLifecycleMutation();}if(n)throw n}async excludeAutoConnect(e,t){let n=this.backend;n&&typeof n.excludeAutoConnect=="function"&&await n.excludeAutoConnect(e,t),t||this.clearManualDisconnectProjection(e);}async disconnectPeer(e,t){try{await this.client.disconnectPeer(e,t);}finally{this.onLifecycleMutation();}}async forceDisconnectPeer(e){try{await this.client.forceDisconnectPeer(e);}finally{this.onLifecycleMutation();}}clearManualDisconnectProjection(e){let t=this.client.clearManualDisconnectProjection;typeof t=="function"&&t.call(this.client,e);}};var wo={classifyScope(r){return r.startsWith("drive-grant:")?{sessionKind:"drive-grant-guest",grantId:r.slice(12),scope:r}:r==="user-device"?{sessionKind:"app-user-device",scope:r}:{scope:r}}},Ns=[["sessionKind","session_kind"],["grantId","grant_id"],["scope","scope"],["peerNodeId","peer_node_id"],["connectionId","connection_id"],["transportEpoch","transport_epoch"],["channel","channel"],["tokenFp","token_fp"]];function Ms(r){let e=[];for(let[t,n]of Ns){let i=r[t];i==null||i===""||e.push(`${n}=${i}`);}return e.join(" ")}function Ds(r,e,t=wo){let n=t.classifyScope(r);return {...{sessionKind:n.sessionKind,grantId:n.grantId,scope:n.scope??r},...e??{}}}function Ge(r,e){return Ds(r,e,wo)}function Y(r,e,t,...n){let i=Ms(e),o=Es(t,n);console.log(i&&o?`${r} ${i} ${o}`:i?`${r} ${i}`:o?`${r} ${o}`:r);}function Es(r,e){if(!r)return "";if(e.length===0)return r;if(/\{\}/.test(r)){let n=0;return r.replace(/\{\}/g,()=>{let i=n<e.length?e[n]:"";return n+=1,To(i)})}return [r,...e.map(To)].join(" ")}function To(r){if(r==null)return String(r);if(typeof r=="string")return r;if(typeof r=="number"||typeof r=="boolean")return String(r);try{return JSON.stringify(r)}catch{return String(r)}}var ue=class extends Error{constructor(e,t){super(t),this.kind=e,this.name="DriveGrantActorError";}};function si(r,e){return {scope:r,peerNodeId:e}}function ri(r){return `${r.scope}@${r.peerNodeId}`}var Ke=class{constructor(e){this.state="idle";this.inFlight=null;this.key=e.key,this.dial=e.dial,this.close=e.close??(async()=>{});}isReady(){return this.state==="base-ready"||this.state==="protocol-ready"}isClosed(){return this.state==="closed"}getState(){return this.state}getPreferredTransport(){return this.state==="closed"||this.state==="idle"||this.state==="dialing"?"none":"base"}markProtocolReady(){this.state!=="closed"&&(this.state="protocol-ready",Y("[drive-grant-actor][state]",this.correlation(),"state=protocol-ready"));}markDegraded(){this.state!=="closed"&&(this.state="degraded",Y("[drive-grant-actor][state]",this.correlation(),"state=degraded"));}correlation(e){return Ge(this.key.scope,{peerNodeId:this.key.peerNodeId,...e??{}})}async ensureReady(){if(this.state==="closed")throw new ue("shutdown","drive-grant actor: already shut down");if(!this.isReady())return this.inFlight?this.inFlight:(this.state="dialing",Y("[drive-grant-actor][dial]",this.correlation(),"begin"),this.inFlight=this.dial(this.key).then(()=>{this.state!=="closed"&&(this.state="base-ready",this.inFlight=null,Y("[drive-grant-actor][dial]",this.correlation(),"ready_first"));},e=>{this.state!=="closed"&&(this.state="idle"),this.inFlight=null;let t=e instanceof Error?e.message:String(e);throw Y("[drive-grant-actor][dial]",this.correlation(),"failed error={}",t),e instanceof ue?e:new ue("dial-failed",`drive-grant actor: dial failed: ${t}`)}),this.inFlight)}async openLogicalChannel(e){if(this.state==="closed")throw new ue("shutdown","drive-grant actor: already shut down");if(!this.isReady())throw new ue("not-ready","drive-grant actor: ensureReady() must resolve before openLogicalChannel");return Y("[drive-grant-actor][channel]",this.correlation({channel:e}),"open"),{label:e}}async shutdown(){if(this.state!=="closed"){this.state="closed",this.inFlight=null,Y("[drive-grant-actor][shutdown]",this.correlation(),"begin");try{await this.close(this.key);}catch{}Y("[drive-grant-actor][shutdown]",this.correlation(),"complete");}}},ze=class{constructor(e){this.actors=new Map;this.factory=e;}getOrSpawn(e,t){let n=ri(e),i=this.actors.get(n);if(i&&!i.isClosed())return i;let o=(t??this.factory)(e);return this.actors.set(n,o),o}get(e){return this.actors.get(ri(e))??null}async shutdownAll(){let e=[...this.actors.values()];this.actors.clear(),await Promise.all(e.map(t=>t.shutdown()));}size(){return this.actors.size}};var _s=new TextEncoder,xs=new TextDecoder;function ai(r){let e=new Uint8Array(4+r.byteLength);return new DataView(e.buffer,e.byteOffset,e.byteLength).setUint32(0,r.byteLength,false),e.set(r,4),e}function Ls(r){let e=new Uint8Array(0);return t=>{for(e=ci(e,t);e.byteLength>=4;){let n=li(e,0);if(e.byteLength<4+n)break;r(e.slice(4,4+n)),e=e.slice(4+n);}}}function Bs(r){return _s.encode(JSON.stringify(r))}function Fs(r){return JSON.parse(xs.decode(r))}function Xa(r){return ai(Bs(r))}function Za(r,e={}){return Ls(t=>{try{r(Fs(t),t);}catch(n){if(e.onInvalidJson){e.onInvalidJson(n,t);return}throw n}})}function ci(r,e){return g([r,e])}function li(r,e){return (r[e]<<24|r[e+1]<<16|r[e+2]<<8|r[e+3])>>>0}var Ce=class{constructor(e,t){this.appTag=c$4(e),this.backend=t;}get tag(){return this.appTag}async waitForAuth(){return this.backend.waitForAuth()}get currentUser(){return this.backend.currentUser}usesCoordinationGateway(){return this.backend.usesCoordinationGateway?.()===true}async joinCoordinationRoom(e,t,n){if(!this.backend.joinCoordinationRoom)throw new Error("The active signaling provider does not support coordination rooms.");await this.backend.joinCoordinationRoom(e,t,n);}async leaveCoordinationRoom(e){this.backend.leaveCoordinationRoom&&await this.backend.leaveCoordinationRoom(e);}async getCoordinationRoomMembers(e){if(!this.backend.getCoordinationRoomMembers)throw new Error("The active signaling provider does not support coordination rooms.");return this.backend.getCoordinationRoomMembers(e)}watchCoordinationRoomMembers(e,t){if(!this.backend.watchCoordinationRoomMembers)throw new Error("The active signaling provider does not support coordination rooms.");return this.backend.watchCoordinationRoomMembers(e,t)}onAuthChange(e){return this.backend.onAuthChange(e)}async signInAnonymously(){await this.backend.signInAnonymously();}async signInWithPluto(){if(typeof this.backend.signInWithPluto=="function"){await this.backend.signInWithPluto();return}await a$2().signInWithPluto();}async signOut(){await this.backend.signOut();}async stopAuthActivity(){typeof this.backend.stopAuthActivity=="function"&&await this.backend.stopAuthActivity();}setCoordinationHostAvailability(e){this.backend.setCoordinationHostAvailability?.(e);}capabilities(){return this.backend.capabilities?.()}async getTurnCredentials(){return this.backend.getTurnCredentials()}async updatePresence(e,t,n=true,i=300*1e3,o){await this.backend.updatePresence(e,t,n,i,o);}async setOffline(e){await this.backend.setOffline(e);}async cleanupStaleDevices(){await this.backend.cleanupStaleDevices();}async sendMessage(e,t,n,i){return this.backend.sendMessage(e,t,n,i)}async pollMessages(e){return this.backend.pollMessages(e)}async subscribeSessions(e,t){let i=(await this.backend.subscribeSessions(e)).getReader(),o=false;return (async()=>{try{for(;!o;){let{done:a,value:c}=await i.read();if(a)break;if(c)for(let d of c)"session"in d&&d.session&&await t(d.session);}}catch(a){o||console.error("[Signaling] Session stream error:",a);}})(),()=>{o=true,i.cancel();}}async getLocalDeviceId(){return typeof this.backend.getLocalDeviceId!="function"?null:this.backend.getLocalDeviceId()}async searchDevices(e){return this.backend.searchDevices(e)}async updateDevice(e,t){await this.backend.updateDevice(e,t);}async deleteDevice(e){await this.backend.deleteDevice(e);}onDevicesChange(e,t){return this.backend.onDevicesChange(e,t)}startAutoConnect(e,t){this.backend.startAutoConnect(e,t);}async submitDesiredPeerProjection(e,t){if(typeof this.backend.submitDesiredPeerProjection!="function")throw new Error("The active signaling provider does not support desired-peer projections.");await this.backend.submitDesiredPeerProjection(e,t);}notifyDisconnectRequested(e){typeof this.backend.notifyDisconnectRequested=="function"&&this.backend.notifyDisconnectRequested(e);}startPresenceLoop(e,t,n,i,o){this.backend.startPresenceLoop(e,t,n,i,o);}forceReconnect(){this.backend.forceReconnect();}async isConnected(e){return this.backend.isConnected(e)}async getConnectionStates(){return typeof this.backend.getConnectionStates=="function"?this.backend.getConnectionStates():[]}onStateChange(e){return typeof this.backend.onStateChange=="function"?this.backend.onStateChange(e):()=>{}}supportsRustPeerLifecycleProjection(){return typeof this.backend.listPeerSessions=="function"||typeof this.backend.getPeerSession=="function"||typeof this.backend.waitForSettledPeer=="function"||typeof this.backend.getConnectionStates=="function"}setWasmClient(e){let t=this.backend;t&&typeof t.setWasmClient=="function"&&t.setWasmClient(e);}};function Ae(r){let e=r?.split(".")[1];if(!e)return null;try{let t=e.replace(/-/g,"+").replace(/_/g,"/"),n=(4-t.length%4)%4,i=atob(t+"=".repeat(n)),o=JSON.parse(i);return o&&typeof o=="object"&&!Array.isArray(o)?o:null}catch{return null}}function ge(r,e){let t=r?.[e];return typeof t=="string"&&t.trim()?t.trim():null}function vt(r,e,t){let n=ge(r,"namespaceId")===e||ge(r,"appTag")===`space::${e}`,i=ge(r,"developerAppTag");return n&&!!i&&(!t||i===t)}function Ao(r){let e=ge(r,"developerAppTag");if(e)return e;let t=ge(r,"appTag");return t&&!t.startsWith("space::")?t:null}function ko(r){return {get wasmClient(){return r.wasmClient},get roomCreationMode(){return r.roomCreationMode},get appLimits(){return r.appLimits},ensureAuthenticated:e=>r.ensureAuthenticated(e),getTicketWithToken:(e,t)=>r.getTicketWithToken(e,t),getNodeId:()=>r.getNodeId(),connect:(e,t)=>r.connect(e,t),refreshHostedAppSettings:e=>r.refreshHostedAppSettings(e),getRoomBackendTag:()=>r.getRoomBackendTag()}}var ke=class{constructor(e,t){this.client=e,this.signaling=t;}usesCoordinationGateway(){return this.signaling.usesCoordinationGateway?.()===true}requireCoordinationGateway(){if(!this.usesCoordinationGateway())throw new Error("[OpenRTC] Rooms require the managed coordination gateway; the direct Firebase room data plane has been removed.")}get roomBackendTag(){return this.client.getRoomBackendTag()}resolveRoomUserId(e){return a$2().getCurrentUser?.()?.uid??this.signaling.currentUser?.id??e??"anonymous"}async resolveControlPlaneAppTag(){let e=await a$2().getIdToken({forceRefresh:false}).catch(()=>null),t=Ao(Ae(e));if(t)return t;let n=this.signaling.tag;if(!n.startsWith("space::"))return n;throw new Error("[OpenRTC] The scoped space identity is missing developer-app attribution. Mint a fresh space token before using room APIs.")}async invokeRoomCallable(e,t){let{httpsCallable:n}=await import('./dist-FIVA6EPA.js'),i=a$2().getFunctions();if(!t||typeof t!="object")throw new Error(`${e} requires an object request payload.`);if(typeof globalThis.crypto?.randomUUID!="function")throw new Error(`Secure request identity is unavailable for ${e}.`);let o={...t,idempotencyKey:`${e}:${globalThis.crypto.randomUUID()}`};return (await n(i,e)(o)).data}isAlreadyExistsError(e){if(!e||typeof e!="object")return false;let t="code"in e&&typeof e.code=="string"?e.code:"",n="message"in e&&typeof e.message=="string"?e.message:"";return t.includes("already-exists")||n.toLowerCase().includes("already exists")}normalizeRoomId(e){return e.trim().toUpperCase()}async getMembersInternal(e,t){this.requireCoordinationGateway();let n=await this.signaling.getCoordinationRoomMembers(e);return t?n.filter(i=>i.nodeId!==t):n}async createRoom(e){if(await this.client.ensureAuthenticated("room-op"),!this.client.wasmClient)throw new Error("WASM Client not loaded");this.requireCoordinationGateway();let t=await this.client.getNodeId(),n=await this.resolveControlPlaneAppTag();if(await this.client.refreshHostedAppSettings(),this.client.roomCreationMode==="server-only")throw new Error("This app uses server-only room creation. Create the room on your backend with your sk_live_... key, then call joinRoom(roomId) on the client.");let i="",o=false,s="",a=typeof e=="string"&&e.trim().length>0?e.trim().toUpperCase():"",c=a?1:3;for(let d=0;d<c;d+=1){if(a)i=a;else {let p=new Uint8Array(6);crypto.getRandomValues(p),i=Array.from(p,u=>u.toString(36).padStart(2,"0")).join("").substring(0,6).toUpperCase();}let l=await this.client.getTicketWithToken(`room:${i}`,0);try{await this.invokeRoomCallable("createClientRoom",{appTag:n,roomId:i,nodeId:t,ticket:l}),o=!0,s=l;break}catch(p){if(this.isAlreadyExistsError(p)){if(a)throw p;continue}throw p}}if(!o)throw new Error(a?`Failed to create requested room "${a}".`:"Failed to create room after multiple attempts (ID collisions).");return await this.signaling.joinCoordinationRoom(i,t,s),i}async joinRoom(e,t={}){if(await this.client.ensureAuthenticated("room-op"),!this.client.wasmClient)throw new Error("WASM Client not loaded");if(this.requireCoordinationGateway(),typeof e!="string"||e.length===0||e.length>64)throw new Error("roomId must be a non-empty string of at most 64 characters");if(e!=="demo"&&!/^[a-zA-Z0-9_-]+$/.test(e))throw new Error("roomId must contain only alphanumeric characters, hyphens, or underscores");let n=await this.client.getNodeId(),i=this.resolveRoomUserId(n),o=await this.resolveControlPlaneAppTag(),s=this.normalizeRoomId(e),a=await this.client.getTicketWithToken(`room:${s}`,0);console.log("[RoomManager] joinRoom request",{roomId:e,normalizedId:s,targetRoomId:s,tag:this.roomBackendTag,userId:i,myNodeId:n,hasTicket:!!a,ticketLength:a?.length||0});try{await this.client.refreshHostedAppSettings(),await this.invokeRoomCallable("joinClientRoom",{appTag:o,roomId:s,nodeId:n,ticket:a}),await this.signaling.joinCoordinationRoom(s,n,a),console.log(`Joined room: ${s}`);}catch(d){throw c$1("[RoomManager] joinRoom failed",d),d}let c=[];if(t.bootstrapPeers!==false){let l=(await this.getMembersInternal(s,n)).map(async u=>{let h=false,m=Date.now();if(u.expiresAt)u.expiresAt<m&&(h=true);else {let f=u.lastSeenAt||u.joinedAt||0;m-f>300*1e3&&(h=true);}if(h)return null;if(u.ticket)try{console.log(`Bootstrapping: Connecting to peer ${u.nodeId}...`);let f=await this.client.connect(u.ticket,5e3);return f.send({type:"chat",text:`Use ${i} joined the room.`}).catch(v=>{c$1("[RoomManager] join notification send skipped",{roomId:s,peerNodeId:u.nodeId,error:v});}),f}catch(f){return console.warn(`Failed to connect to peer ${u.nodeId}:`,f),null}return null});(await Promise.allSettled(l)).forEach(u=>{u.status==="fulfilled"&&u.value&&c.push(u.value);});}return c}async leaveRoom(e){this.requireCoordinationGateway(),await this.client.ensureAuthenticated("room-op");let t=await this.client.getNodeId();if(!t)return;let n=this.normalizeRoomId(e),i=await this.resolveControlPlaneAppTag();console.log(`Leaving room ${n}...`),await this.signaling.leaveCoordinationRoom(n);try{await this.invokeRoomCallable("leaveClientRoom",{appTag:i,roomId:n,nodeId:t}),console.log(`Left room: ${n}`);}catch(o){throw console.warn("Leave room failed:",o),o}}async getRoomMembers(e){await this.client.ensureAuthenticated("room-op");let t=this.normalizeRoomId(e);return this.getMembersInternal(t)}watchRoom(e,t){let n=false,i=null;return (async()=>{try{if(await this.client.ensureAuthenticated("room-op"),n)return;this.requireCoordinationGateway();let o=this.normalizeRoomId(e);i=this.signaling.watchCoordinationRoomMembers(o,t),n&&(i(),i=null);}catch(o){n||console.warn("[RoomManager] watchRoom listener failed:",o);}})(),()=>{n=true,i?.(),i=null;}}stopHeartbeat(e){}};function Ws(r,e){let t=r.trim();if(!t)throw new Error("Channel envelope requires a non-empty channel id.");let n=new TextEncoder,i=n.encode(t),o=e?n.encode(JSON.stringify(e)):new Uint8Array(0),s=new Uint8Array(6+i.byteLength+o.byteLength),a=new DataView(s.buffer);return s[0]=127,s[1]=1,a.setUint16(2,i.byteLength,false),a.setUint16(4,o.byteLength,false),s.set(i,6),s.set(o,6+i.byteLength),s}function No(r,e,t){let n=Ws(e,t),i=r.getWriter(),o=false,s=async()=>{o||(o=true,await i.write(n));};return new WritableStream({write:async a=>{await s(),await i.write(a);},close:async()=>{await s();try{await i.close();}finally{i.releaseLock();}},abort:async a=>{try{await i.abort(a);}finally{i.releaseLock();}}})}var di=[0,300,600,1e3,1500,2e3,2500,3e3,3500,3500,3500,3500,3500,3500,3500],Mo=2e3,Ct=0,It="main",St=64,Do=4*1024*1024,Eo=1,_o="openrtc:native-main-message",xo=15e3,Lo=16,Bo=3e4,Fo=250,Wo=250,Oo=2e3,Uo=600,Ho=2e3,qo=120,jo=1e3,Go=6e4,Ko=8,pi="system/peer-default",Os="share/explicit-file",Us="share/explicit-control",zo=[{id:pi,kind:"system",ownership:"shared",peerModel:"device-first",routing:"session-default",readiness:"settled-peer",promotionPolicy:"eligible",signalingPolicy:"hosted",description:"Default trusted device/runtime traffic"},{id:Os,kind:"share",ownership:"shared",peerModel:"anonymous-ticket",routing:"stream-envelope",readiness:"transport-only",promotionPolicy:"never",signalingPolicy:"ticket-only",description:"Explicit file transfer channel for share/ticket traffic"},{id:Us,kind:"share",ownership:"shared",peerModel:"anonymous-ticket",routing:"stream-envelope",readiness:"transport-only",promotionPolicy:"never",signalingPolicy:"ticket-only",description:"Explicit control channel for share/ticket traffic"}];function Qo(r){return {get registry(){return r.getRegistry()},get wasmClient(){return r.getWasmClient()},get node(){return r.getNode()},get discoveryMode(){return r.getDiscoveryMode()},get localNodeId(){return r.getLocalNodeId()},get deviceId(){return r.getDeviceId()},registerDisposer:e=>r.registerDisposer(e)}}var Vo="openrtc:endpoint-ticket:v1";function ee(r){let e=r.lastIndexOf(".");return {irohTicket:e>=0?r.slice(0,e):r,tokenSuffix:e>=0?r.slice(e+1):null}}function $o(){return Yo(24)}function bt(r,e,t,n,i){return `${r}.${Hs(r,e,t,n,i)}`}function se(r,e){let t=qs(e);return !t||!js(r,t)?null:t}function Hs(r,e,t,n,i){return btoa(JSON.stringify({t:e,s:t,m:n,h:Jo(r),...typeof i=="number"?{e:i}:{},a:Vo,n:Gs()})).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function qs(r){try{let e=r.replace(/-/g,"+").replace(/_/g,"/"),t=(4-e.length%4)%4;return JSON.parse(atob(e+"=".repeat(t)))}catch{return null}}function js(r,e){return !(typeof e.h=="string"&&e.h!==Jo(r)||typeof e.e=="number"&&Number.isFinite(e.e)&&e.e<=Date.now()||typeof e.a=="string"&&e.a!==Vo||typeof e.n=="string"&&!Ks(e.n))}function Gs(){return Yo(16)}function Yo(r){let e=new Uint8Array(r);return crypto.getRandomValues(e),btoa(String.fromCharCode(...e)).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function Ks(r){try{let e=r.replace(/-/g,"+").replace(/_/g,"/"),t=(4-e.length%4)%4;return atob(e+"=".repeat(t)).length===16}catch{return false}}function ne(r,e){return r>>>e|r<<32-e}var zs=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298];function Jo(r){let e=new TextEncoder().encode(r),t=e.length*8,n=e.length+1;for(;n%64!==56;)n+=1;let i=new Uint8Array(n+8);i.set(e),i[e.length]=128;let o=new DataView(i.buffer);o.setUint32(n,Math.floor(t/4294967296),false),o.setUint32(n+4,t>>>0,false);let s=[1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225],a=new Array(64);for(let c=0;c<i.length;c+=64){for(let y=0;y<16;y+=1)a[y]=o.getUint32(c+y*4,false);for(let y=16;y<64;y+=1){let C=ne(a[y-15],7)^ne(a[y-15],18)^a[y-15]>>>3,I=ne(a[y-2],17)^ne(a[y-2],19)^a[y-2]>>>10;a[y]=a[y-16]+C+a[y-7]+I>>>0;}let[d,l,p,u,h,m,f,v]=s;for(let y=0;y<64;y+=1){let C=ne(h,6)^ne(h,11)^ne(h,25),I=h&m^~h&f,b=v+C+I+zs[y]+a[y]>>>0,P=ne(d,2)^ne(d,13)^ne(d,22),A=d&l^d&p^l&p,S=P+A>>>0;v=f,f=m,m=h,h=u+b>>>0,u=p,p=l,l=d,d=b+S>>>0;}s[0]=s[0]+d>>>0,s[1]=s[1]+l>>>0,s[2]=s[2]+p>>>0,s[3]=s[3]+u>>>0,s[4]=s[4]+h>>>0,s[5]=s[5]+m>>>0,s[6]=s[6]+f>>>0,s[7]=s[7]+v>>>0;}return s.map(c=>c.toString(16).padStart(8,"0")).join("")}function O(r,e,t){let n;return new Promise((i,o)=>{n=setTimeout(()=>{if(n=void 0,typeof t=="function"){o(t());return}let s=t?`${t} timed out`:"timeout";o(new Error(`${s} after ${e}ms`));},e),r.then(s=>{n!==void 0&&clearTimeout(n),i(s);},s=>{n!==void 0&&clearTimeout(n),o(s);});})}var Pt=class{constructor(e,t,n){this.ctx=e;this.options=t;this.deps=n;this.appliedAuthSessionToken=null;this.authSyncUnsubscribe=null;this.publicAuthChangeUnsubscribes=new Set;this.lastWasmAuthSyncUserId=null;this.lastWasmAuthSyncToken=null;this.disposed=false;this.ctx.registerDisposer(()=>this.dispose());}dispose(){if(this.disposed)return;this.disposed=true;let e=this.authSyncUnsubscribe;if(this.authSyncUnsubscribe=null,e)try{e();}catch(t){console.warn("[Client][WASM-AUTH] auth-change unsubscribe failed",t);}for(let t of Array.from(this.publicAuthChangeUnsubscribes))try{t();}catch(n){console.warn("[Client][AUTH] public auth-change unsubscribe failed",n);}this.publicAuthChangeUnsubscribes.clear();}assertActive(){if(this.disposed)throw new Error("[Client][AUTH] Auth coordinator is disposed")}isSpaceWithSpaceKey(){let e=this.options.spaceKey??this.options.space;return (this.options.discoveryMode===void 0||this.options.discoveryMode==="space")&&typeof e=="string"&&e.trim().length>0}async ensureAuthenticated(e){if(this.assertActive(),this.deps.usesTicketOnlySignalingMode())return;if(typeof this.options.coordinationGateway?.grantProvider=="function"){if(!this.deps.getCurrentUser())throw new Error("[OpenRTC] A v2 capability must install its provider-neutral identity before runtime activation.");return}let t=this.options.authMode??"anonymous",n=e!=="discovery";if(this.isSpaceWithSpaceKey()){let d=typeof this.options.apiKey=="string"?this.options.apiKey.trim():"",l=this.options.spaceKey??this.options.space,p=typeof l=="string"?l.trim():"",u=d&&p?await b$1(d,p).catch(()=>null):null;if(this.assertActive(),a$2().getCurrentUser()){let C=await a$2().getIdToken({forceRefresh:false}).catch(()=>null);this.assertActive();let I=Ae(C);if(u&&vt(I,u)){await O(this.deps.waitForAuth(),5e3),this.assertActive(),n&&d$2(`[Client][AUTH] Space scoped token already authenticated (${e})`);return}n&&d$2("[Client][AUTH] Existing Firebase user is not scoped to this space; minting scoped token",{reason:e,expectedNamespaceId:u?.slice(0,12)??null,actualNamespaceId:ge(I,"namespaceId")?.slice(0,12)??null,actualDeveloperAppTag:ge(I,"developerAppTag")});}let m=this.options.spaceTokenProvider;if(!m)throw new Error("[Client][AUTH] space discovery requires spaceTokenProvider (use spaceToken for static sites)");let f=await m(),v=typeof f?.customToken=="string"?f.customToken.trim():"";if(!v)throw new Error("[Client][AUTH] spaceTokenProvider returned no customToken");this.assertActive(),await a$2().signInWithCustomTokenValue(v),this.assertActive(),await O(this.deps.waitForAuth(),5e3),this.assertActive();let y=await a$2().getIdToken({forceRefresh:false}).catch(()=>null);this.assertActive(),this.setWasmAuthToken(y??v,y?"space-id-token":"space-token"),this.assertActive(),n&&d$2(`[Client][AUTH] Space scoped token authenticated (${e})`);return}let o=typeof this.options.sessionToken=="string"?this.options.sessionToken.trim():"";if(o&&this.appliedAuthSessionToken!==o){this.assertActive(),await a$2().signInWithCustomTokenValue(o),this.assertActive(),this.appliedAuthSessionToken=o,await O(this.deps.waitForAuth(),5e3),this.assertActive(),n&&d$2(`[Client][AUTH] Session token authenticated (${e})`);return}try{await O(this.deps.waitForAuth(),5e3);}catch(d){this.assertActive(),n&&console.warn(`[Client][AUTH] waitForAuth timed out (${e})`,d);}this.assertActive();let s=this.deps.getCurrentUser(),a=s?.id??s?.uid??null,c=this.options.discoveryMode==="user-scoped"&&typeof a=="string"&&a.startsWith("space_");if(s&&!c){n&&d$2(`[Client][AUTH] Authenticated (${e}) as ${a??"current-user"}`);return}if(c&&n&&d$2("[Client][AUTH] Ignoring space-scoped user for anonymous user-scoped discovery"),t==="external"||t==="required")throw new Error(`[Client][AUTH] ${t} auth mode requires host-provided auth before ${e}`);n&&d$2(`[Client][AUTH] No user (${e}); attempting anonymous sign-in...`),await O(this.deps.signInAnonymously(),8e3),this.assertActive();try{await O(this.deps.waitForAuth(),5e3);}catch{}if(this.assertActive(),!this.deps.getCurrentUser())throw new Error("[Client][AUTH] Anonymous sign-in did not produce an authenticated user");n&&d$2(`[Client][AUTH] Anonymous sign-in success (${e})`);}setWasmAuthToken(e,t){let n=this.ctx.wasmClient,i=typeof e=="string"&&e.trim().length>0?e:null,o=n?.setIdentityCredential??n?.set_auth_token;if(!n||typeof o!="function"){console.warn("[Client][WASM-IDENTITY] Wasm identity credential setter is unavailable");return}let s=i?"token":null;if(!(this.lastWasmAuthSyncUserId===s&&this.lastWasmAuthSyncToken===i)){if(this.lastWasmAuthSyncUserId=s,this.lastWasmAuthSyncToken=i,d$2(`[Client][WASM-AUTH] Sync token (${t}) hasToken=${!!i} tokenLen=${i?.length??0}`),i===null&&typeof n.clearIdentityCredential=="function"){n.clearIdentityCredential();return}o.call(n,i);}}installAuthTokenSync(){if(this.disposed||this.isSpaceWithSpaceKey()||this.authSyncUnsubscribe)return;let e=this.deps.onAuthChange(()=>{this.disposed||this.syncAuthTokenToWasm("auth-change").catch(t=>{this.disposed||console.warn("[Client][WASM-AUTH] Failed syncing auth token on auth change:",t);});});this.authSyncUnsubscribe=e;}async syncAuthTokenToWasm(e,t=false){if(this.disposed||this.isSpaceWithSpaceKey())return;let n=this.deps.getCurrentUser(),i=n&&n.getToken?await n.getToken(t):null;if(this.disposed)return;let o=!!i,s=i?.length||0,a=n?.id||null;this.lastWasmAuthSyncUserId===a&&this.lastWasmAuthSyncToken===i||(d$2(`[Client][WASM-AUTH] Sync token (${e}) hasToken=${o} tokenLen=${s} uid=${a||"none"} forceRefresh=${t}`),!this.disposed&&this.setWasmAuthToken(i,e));}async refreshRuntimeAuthToken(e="runtime-start"){this.disposed||this.deps.usesTicketOnlySignalingMode()||(await this.ensureAuthenticated("discovery"),!this.disposed&&(this.isSpaceWithSpaceKey()||await this.syncAuthTokenToWasm("auth-change",e==="managed-session")));}get currentUser(){return this.deps.getCurrentUser()}onAuthChange(e){if(this.disposed)return ()=>{};let t=true,n=this.deps.onAuthChange(o=>{!t||this.disposed||e(o);}),i=()=>{if(t){t=false;try{n();}finally{this.publicAuthChangeUnsubscribes.delete(i);}}};return this.publicAuthChangeUnsubscribes.add(i),i}async signInAnonymously(){return this.assertActive(),this.deps.signInAnonymously()}async signInWithPluto(){return this.assertActive(),this.deps.signInWithPluto()}async signOut(){if(!this.disposed&&(this.deps.beforeSignOut(),await this.deps.stopAuthActivity(),!this.disposed))return this.deps.signOut()}};var Rt=class{constructor(e,t){this.ctx=e;this.deps=t;this.devicesById=new Map;this.deviceIdsByNodeId=new Map;this.activeScanningStops=new Set;this.activeSubscriptionStops=new Set;this.disposed=false;this.ctx.registerDisposer(()=>this.dispose());}dispose(){if(!this.disposed){this.disposed=true;for(let e of Array.from(this.activeScanningStops))try{e();}catch(t){console.warn("[Client] active device scanning unsubscribe failed",t);}this.activeScanningStops.clear();for(let e of Array.from(this.activeSubscriptionStops))try{e();}catch(t){console.warn("[Client] device directory subscription unsubscribe failed",t);}this.activeSubscriptionStops.clear();}}get byIdMap(){return this.devicesById}set byIdMap(e){this.devicesById=e instanceof Map?e:new Map;}get byNodeIdMap(){return this.deviceIdsByNodeId}set byNodeIdMap(e){this.deviceIdsByNodeId=e instanceof Map?e:new Map;}remember(e){if(!this.disposed&&e?.deviceId){if(this.devicesById.set(e.deviceId,e),typeof e.nodeId=="string"&&e.nodeId.trim()){let t=e.nodeId.trim();this.deviceIdsByNodeId.set(t,e.deviceId);}this.deps.onDeviceRemembered(e);}}getKnownDevice(e,t){let n=typeof e=="string"?e.trim():"";if(n){let o=this.devicesById.get(n);if(o)return o}let i=typeof t=="string"?t.trim():"";if(i){let o=this.deviceIdsByNodeId.get(i);if(o)return this.devicesById.get(o)??null}return null}getKnownDeviceIdForNode(e){let t=typeof e=="string"?e.trim():"";return t?this.deviceIdsByNodeId.get(t)??null:null}getKnownDeviceNodeId(e){let t=typeof e=="string"?e.trim():"";return t&&this.devicesById.get(t)?.nodeId?.trim()||null}rememberKnownDeviceForNode(e,t){if(this.disposed)return;let n=e.trim(),i=t.trim();!n||!i||this.deviceIdsByNodeId.set(n,i);}getKnownDevicePlatform(e,t){let n=this.getKnownDevice(e,t),i=typeof n?.platformType=="string"?n.platformType:typeof n?.platform_type=="string"?n.platform_type:null;return i?String(i).trim().toLowerCase():null}async refreshKnownDeviceCache(){if(this.disposed||!this.deps.requiresManagedTransportTrust())return;let e=await this.searchDevices().catch(()=>[]);this.disposed||e.forEach(t=>this.remember(t));}async searchDevices(){if(this.disposed)return [];if(await this.deps.ensureSignalingReadyForDiscovery("search"),this.disposed)return [];let e=await this.deps.searchDevices();return this.disposed?[]:(e.forEach(t=>{this.remember(t),this.deps.applyDiscoveredDevice(t);}),e)}async updateDevice(e,t){this.disposed||(await this.deps.ensureSignalingReadyForDiscovery("search"),!this.disposed&&await this.deps.updateDevice(e,t));}async deleteDevice(e){this.disposed||(await this.deps.ensureSignalingReadyForDiscovery("search"),!this.disposed&&await this.deps.deleteDevice(e));}async cleanupStaleDevices(){this.disposed||(await this.deps.ensureSignalingReadyForDiscovery("search"),!this.disposed&&await this.deps.cleanupStaleDevices());}onDevicesChange(e){if(this.disposed)return ()=>{};let t=true,n=null,i=()=>{if(!(!t&&!n)){if(t=false,n)try{n();}finally{n=null;}this.activeSubscriptionStops.delete(i);}};return this.activeSubscriptionStops.add(i),(async()=>{await this.deps.ensureSignalingReadyForDiscovery("watch"),!(!t||this.disposed)&&(n=this.deps.onDevicesChange(o=>{!t||this.disposed||(o.forEach(s=>{this.remember(s),this.deps.applyDiscoveredDevice(s);}),e(o));}),(!t||this.disposed)&&i());})().catch(o=>{if(!(!t||this.disposed)){console.warn("[Client] Failed to initialize onDevicesChange listener:",o);try{e([]);}finally{i();}}}),i}async subscribeSessions(e,t){if(this.disposed)return ()=>{};if(await this.deps.ensureSignalingReadyForDiscovery("sessions"),this.disposed)return ()=>{};let n=true,i=await this.deps.subscribeSessions(e,s=>{if(n&&!this.disposed)return t(s)});if(this.disposed)return i(),()=>{};let o=()=>{if(n){n=false;try{i();}finally{this.activeSubscriptionStops.delete(o);}}};return this.activeSubscriptionStops.add(o),o}async startScanningLoop(e){if(this.disposed)return {stop:()=>{}};let t=new Set,n=false,i=null,o=null,s=e.localDeviceId;try{let c=await this.deps.getLocalDeviceId();if(this.disposed)return {stop:()=>{}};c&&(s=c);}catch{}i=this.onDevicesChange(c=>{n||this.disposed||e.onDevices?.(c);});let a=()=>{n=true,i&&(i(),i=null),o&&(o(),o=null),this.activeScanningStops.delete(a);};this.activeScanningStops.add(a);try{(e.onIncomingSession||e.acceptIncomingSession)&&(o=await this.subscribeSessions(s,async c=>{if(n||this.disposed)return;let d=c.sessionId||c.connectionId;if(!(!d||t.has(d))&&c.targetDeviceId===s&&c.initiatorDeviceId!==s&&!(c.state==="connected"||c.state==="closed"||c.state==="failed")){t.add(d);try{if(this.disposed)return;if(e.onIncomingSession){await e.onIncomingSession(c);return}(this.deps.getPeerStatus(c.initiatorDeviceId)==="connected"||e.isConnected?.(c.initiatorDeviceId))&&(this.deps.hasPeerScopes(c.initiatorDeviceId)||(e.hasProtectedConnectionIntent?.(c.initiatorDeviceId)??!1)||await this.deps.forceDisconnectPeer(c.initiatorDeviceId).catch(async()=>{await e.cleanupStaleConnection?.(c.initiatorDeviceId);})),c.initiatorNodeId&&await e.allowIncomingNodeId?.(c.initiatorNodeId);let p=await e.acceptIncomingSession?.(d,c.initiatorDeviceId);if(!p?.success)throw new Error(p?.error||"Failed to accept incoming signaling session");await e.onIncomingSessionAccepted?.(c);}catch(l){throw t.delete(d),l}}}));}catch(c){throw a(),c}return {stop:a}}};var Qs="relay-only endpoint ticket unavailable",Vs=12e3,$s=250,Ys=1500;function Js(r){return String(r?.message??r??"").toLowerCase().includes(Qs)}async function ae(r,e$1={}){let t=e$1.windowMs??Vs,n=e$1.minDelayMs??$s,i=e$1.maxDelayMs??Ys,o=Date.now(),s=0,a=null;for(;e$1.isActive?.()??true;){s+=1;try{return await r()}catch(c){if(a=c,!Js(c))throw c;let d=Date.now()-o;if(d>=t)throw c;let l=Math.min(h(s,n,i),Math.max(0,t-d));l>0&&await e(l);}}throw a||new Error("endpoint ticket minting stopped before a ticket was available")}var Tt=class{constructor(e,t,n){this.ctx=e;this.options=t;this.deps=n;this.managedPresenceGrant=null;this.disposed=false;this.activePresenceDescriptor=null;this.ctx.registerDisposer(()=>this.dispose());}dispose(){if(this.disposed)return;this.disposed=true,this.managedPresenceGrant=null;let e=this.activePresenceDescriptor;this.activePresenceDescriptor=null,!(!e||!this.ctx.localNodeId)&&this.markOfflineDuringDispose(this.ctx.localNodeId);}markOfflineDuringDispose(e){let t=n=>{console.warn("[Client][PRESENCE] failed to mark offline during dispose",n);};try{Promise.resolve(this.deps.setOffline(e)).catch(t);}catch(n){t(n);}}assertActive(){if(this.disposed)throw new Error("[Client][PRESENCE] Presence controller is disposed")}resolvePresenceUserId(){let e=(this.options.discoveryMode===void 0||this.options.discoveryMode==="space")&&typeof this.options.spaceKey=="string"&&this.options.spaceKey.trim().length>0;return this.deps.getCurrentUser()?.id??(e?this.ctx.localNodeId:null)}startSignalingPresenceLoop(e){if(this.disposed)return;let t=this.activePresenceDescriptor,n=(t?.metadata??"")===(e.metadata??"");t&&t.userId===e.userId&&t.nodeId===e.nodeId&&t.deviceName===e.deviceName&&t.ticket===e.ticket&&n||(this.deps.startPresenceLoop(e.userId,e.nodeId,e.deviceName,e.ticket,e.metadata),this.activePresenceDescriptor=e);}notifySignalingBackendChanged(){this.activePresenceDescriptor=null;}setManagedPresenceTicket(e){if(this.disposed)return;let t=e?.trim()||"";if(!t){this.managedPresenceGrant=null;return}let{irohTicket:n,tokenSuffix:i}=this.deps.splitCompoundTicket(t),o=i?this.deps.decodeCompoundTicketPayload(n,i):null;if(!o?.t||!o?.s)throw new Error("Managed presence ticket must be a compound ticket with an embedded token payload");this.managedPresenceGrant={scope:o.s,token:o.t,maxConnections:typeof o.m=="number"?o.m:0,compoundTicket:t,irohTicket:n};let s=this.ctx.wasmClient;s&&typeof s.register_session_token=="function"&&s.register_session_token(o.t,o.s,typeof o.m=="number"?o.m:0);}clearManagedPresenceTicket(){this.managedPresenceGrant=null;}async resolvePresenceTicket(e){this.assertActive();let t=e?.trim();if(t)return t;if(this.managedPresenceGrant)return this.refreshManagedPresenceTicketIfNeeded();let n=this.options.ticket?.trim();return n||this.deps.getTicket()}async refreshManagedPresenceTicketIfNeeded(){let e=this.managedPresenceGrant;if(!e)return this.deps.getTicket();let t=e.irohTicket;try{t=await this.deps.getTicket();}catch{return e.compoundTicket}if(t===e.irohTicket)return e.compoundTicket;let n=this.ctx.wasmClient;if(n&&typeof n.endpoint_ticket_with_token=="function"){let i=n.endpoint_ticket_with_token.bind(n),o=await ae(()=>i(e.scope,e.maxConnections),{isActive:()=>!this.disposed}),{irohTicket:s,tokenSuffix:a}=this.deps.splitCompoundTicket(o),c=a?this.deps.decodeCompoundTicketPayload(s,a):null;return e.irohTicket=s,e.compoundTicket=o,c?.t&&c?.s&&(e.token=c.t,e.scope=c.s,e.maxConnections=typeof c.m=="number"?c.m:0),c$1("[Client][PRESENCE] reminted managed compound ticket through Rust",{grantScope:e.scope}),e.compoundTicket}if(e.scope==="user-device")throw new Error("Managed user-device presence refresh requires Rust/WASM endpoint_ticket_with_token support.");return e.irohTicket=t,e.compoundTicket=this.deps.buildCompoundTicketWithPayload(t,e.token,e.scope,e.maxConnections),c$1("[Client][PRESENCE] rebuilt managed compound ticket after endpoint change",{grantScope:e.scope}),e.compoundTicket}async startPresenceLoop(e){this.assertActive(),await this.deps.ensureWasmRuntimeForP2P(),this.assertActive();let t=this.ctx.localNodeId;if(!t)throw new Error("startPresenceLoop requires an initialized node");let n=this.resolvePresenceUserId();if(!n)throw new Error("startPresenceLoop requires an authenticated user");let i=await this.resolvePresenceTicket(e?.ticket);if(this.assertActive(),!i||!i.trim())throw new Error("startPresenceLoop requires a valid endpoint ticket");this.startSignalingPresenceLoop({userId:n,nodeId:t,deviceName:e?.deviceName||this.options.deviceName||"Unknown Device",ticket:i,metadata:e?.metadata});}async startPresenceLoopForListen(){if(this.disposed)return;let e=this.ctx.localNodeId,t=this.resolvePresenceUserId();if(!t||!e)return;let n=await this.resolvePresenceTicket();this.disposed||this.startSignalingPresenceLoop({userId:t,nodeId:e,deviceName:this.options.deviceName||"Unknown Device",ticket:n,metadata:""});}async setOffline(){this.disposed||(this.activePresenceDescriptor=null,this.ctx.localNodeId&&await this.deps.setOffline(this.ctx.localNodeId));}async updatePresence(e=true,t=3e5,n,i){if(this.disposed||!this.ctx.wasmClient)return;let o=(this.options.discoveryMode===void 0||this.options.discoveryMode==="space")&&typeof this.options.spaceKey=="string"&&this.options.spaceKey.trim().length>0;if(o&&(await this.deps.ensureAuthenticated("discovery"),this.disposed)||!this.deps.getCurrentUser()?.id&&!o)return;let a=this.ctx.localNodeId;if(!a)return;let c=await this.resolvePresenceTicket(i);if(this.disposed)return;if(!c||!c.trim())throw new Error("updatePresence requires a valid endpoint ticket");let d=n,l=await this.deps.getLocalDeviceId()||this.ctx.deviceId;if(this.disposed)return;if(!l)throw new Error("updatePresence requires a stable local device ID");try{let u=n?JSON.parse(n):{};u.deviceId||(u.deviceId=l,d=JSON.stringify(u));}catch{d=JSON.stringify({deviceId:l,rawMetadata:n});}let p=await g$2(d);await this.deps.updatePresence(a,c,e,t,p);}};var wt=class{constructor(e,t){this.ctx=e;this.deps=t;this.hostedAppSettingsLoaded=false;this.hostedAppSettingsLoad=null;this.backendConnectionStateUnsubscribe=null;this.signalingBackend=null;this.subscriptionGeneration=0;this.disposed=false;this.ctx.registerDisposer(()=>this.dispose());}async refreshHostedAppSettings(e=false){if(this.disposed||this.deps.usesTicketOnlySignalingMode()||this.deps.getOptions().coordinationGateway||this.hostedAppSettingsLoaded&&!e)return;if(this.hostedAppSettingsLoad)return this.hostedAppSettingsLoad;let t=this.loadHostedAppSettings();this.hostedAppSettingsLoad=t;try{await t;}finally{this.hostedAppSettingsLoad===t&&(this.hostedAppSettingsLoad=null);}}async loadHostedAppSettings(){try{let{httpsCallable:e}=await import('./dist-FIVA6EPA.js');if(this.disposed)return;let t=a$2().getFunctions(),i=await e(t,"validateApiKey")({apiKey:this.deps.getApiKey()});if(this.disposed)return;let o=i.data;o.warning&&console.warn("[pluto-rtc]",o.warning),this.deps.setAppLimits(o.limits),o.discoveryMode&&this.deps.setDiscoveryMode(o.discoveryMode),this.deps.setRoomCreationMode(o.roomCreationMode??((this.deps.getOptions().discoveryMode??"space")==="space"?"client-open":"client-auth")),this.hostedAppSettingsLoaded=!0;}catch(e){if(this.disposed)return;console.warn("[pluto-rtc] Could not fetch hosted app settings, using local defaults.",e);}}setSignalingBackend(e){if(this.disposed)return;this.disposeBackendConnectionSubscription();let t=this.subscriptionGeneration,n=this.deps.getCurrentSignaling();this.deps.stopRoomLiveness(),this.stopAuthActivityBestEffort(n);let i=this.deps.createSignaling(e);this.signalingBackend=e,this.deps.installBackend(i,e),this.deps.onSignalingBackendChanged();let o=e.setCoreClient;typeof o=="function"&&o.call(e,this.deps.getCoreClientHost());try{Promise.resolve(e.checkForSSOToken()).catch(a=>{console.warn("[Client] backend SSO token check failed:",a);});}catch(a){console.warn("[Client] backend SSO token check failed:",a);}b("[Client] subscribing to backend connection state changes",{backendType:e?.constructor?.name??"unknown",hasGetConnectionStates:typeof e.getConnectionStates=="function",hasOnConnectionStateChange:typeof e.onStateChange=="function"});let s;try{s=i.onStateChange(a=>{this.disposed||t!==this.subscriptionGeneration||(this.deps.onBackendConnectionState(a),this.schedulePeerReconciliationBestEffort("backend-state"));});}catch(a){if(this.disposed||t!==this.subscriptionGeneration)return;console.warn("[Client] Failed to subscribe to backend connection state changes:",a);return}if(typeof s=="function"){let a=s;if(this.disposed||t!==this.subscriptionGeneration){this.callBackendConnectionStateUnsubscribe(a);return}this.backendConnectionStateUnsubscribe=a,b("[Client] backend connection state subscription established synchronously");}else s&&typeof s.then=="function"&&s.then(a=>{if(this.disposed||t!==this.subscriptionGeneration){this.callBackendConnectionStateUnsubscribe(a);return}this.backendConnectionStateUnsubscribe=a,b("[Client] backend connection state subscription established asynchronously");}).catch(a=>{this.disposed||t!==this.subscriptionGeneration||console.warn("[Client] Failed to subscribe to backend connection state changes:",a);});}async getLocalDeviceId(){return this.disposed?null:this.deps.getCurrentSignaling().getLocalDeviceId()}async getTurnCredentials(){return this.disposed?null:this.deps.getCurrentSignaling().getTurnCredentials()}setWasmClient(e){this.disposed||this.deps.getCurrentSignaling().setWasmClient(e);}getCurrentUser(){return this.disposed?null:this.deps.getCurrentSignaling().currentUser}async waitForAuth(){this.disposed||await this.deps.getCurrentSignaling().waitForAuth();}onAuthChange(e){return this.disposed?()=>{}:this.deps.getCurrentSignaling().onAuthChange(e)}async signInAnonymously(){if(!this.disposed)return this.deps.getCurrentSignaling().signInAnonymously()}async signInWithPluto(){if(!this.disposed)return this.deps.getCurrentSignaling().signInWithPluto()}async signOut(){if(!this.disposed)return this.deps.getCurrentSignaling().signOut()}capabilities(){if(!this.disposed)return this.deps.getCurrentSignaling().capabilities?.()}startAutoConnect(e,t){this.disposed||this.deps.getCurrentSignaling().startAutoConnect(e,t);}async isConnected(e){return this.disposed?false:this.deps.getCurrentSignaling().isConnected(e)}notifyDisconnectRequested(e){this.disposed||this.deps.getCurrentSignaling().notifyDisconnectRequested(e);}forceReconnect(){this.disposed||this.deps.getCurrentSignaling().forceReconnect();}startPresenceLoop(e,t,n,i,o){this.disposed||this.deps.getCurrentSignaling().startPresenceLoop(e,t,n,i,o);}async setOffline(e){this.disposed||await this.deps.getCurrentSignaling().setOffline(e);}async updatePresence(e,t,n,i,o){this.disposed||await this.deps.getCurrentSignaling().updatePresence(e,t,n,i,o);}async searchDevices(){return this.disposed?[]:this.deps.getCurrentSignaling().searchDevices()}async updateDevice(e,t){this.disposed||await this.deps.getCurrentSignaling().updateDevice(e,t);}async deleteDevice(e){this.disposed||await this.deps.getCurrentSignaling().deleteDevice(e);}async cleanupStaleDevices(){this.disposed||await this.deps.getCurrentSignaling().cleanupStaleDevices();}onDevicesChange(e){return this.disposed?()=>{}:this.deps.getCurrentSignaling().onDevicesChange(e)}async subscribeSessions(e,t){return this.disposed?()=>{}:this.deps.getCurrentSignaling().subscribeSessions(e,t)}async stopAuthActivity(){this.disposed||(this.deps.stopRoomLiveness(),await this.stopAuthActivityFor(this.deps.getCurrentSignaling()));}dispose(){if(this.disposed)return;this.disposed=true,this.disposeBackendConnectionSubscription(),this.deps.stopRoomLiveness();let e=this.deps.getCurrentSignaling();this.stopAuthActivityBestEffort(e);}async stopAuthActivityFor(e){if(e&&typeof e.stopAuthActivity=="function")try{await e.stopAuthActivity();}catch(t){if(this.disposed)return;console.warn("[Client] signaling auth-scoped teardown failed",t);}}stopAuthActivityBestEffort(e){try{this.stopAuthActivityFor(e);}catch{}}schedulePeerReconciliationBestEffort(e){if(!this.disposed)try{Promise.resolve(this.deps.schedulePeerReconciliation(e)).catch(()=>{});}catch{}}disposeBackendConnectionSubscription(){this.subscriptionGeneration+=1,this.callBackendConnectionStateUnsubscribe(this.backendConnectionStateUnsubscribe),this.backendConnectionStateUnsubscribe=null;}callBackendConnectionStateUnsubscribe(e){if(e)try{e();}catch(t){console.warn("[Client] backend connection-state unsubscribe failed",t);}}};function Xs(r){if(["closed","failed","disconnected"].includes(r.state.trim().toLowerCase()))return true;let e=r.activeTransport?.trim().toLowerCase();if(!(e==="iroh-webrtc"||e==="iroh-moq"))return false;let n=(r.error??r.readinessReason??"").trim().toLowerCase();return r.replacementInProgress===true||n==="locally-closed"}function Zs(r){return r.lastDisconnectReason??r.error??r.readinessReason}function Xo(r){return new ui({getContext:()=>r.getClientContext(),getOptions:()=>r.options,getApiKey:()=>r.options.apiKey,getCurrentSignaling:()=>r.signaling,createSignaling:e=>new Ce(p(r.options),e),stopRoomLiveness:()=>r.rooms.stopHeartbeat(),installBackend:e=>{r.setSignaling(e),r.setRooms(new ke(r.roomClientHost,e));},setAppLimits:e=>{r.setAppLimits(e);},setDiscoveryMode:e=>{r.options.discoveryMode=e;},setRoomCreationMode:e=>{r.setRoomCreationMode(e);},getCoreClientHost:()=>({connect:(e,t,n,i,o)=>r.connectionDialer.connect(e,t,n,i,o),ensureManagedApplicationRoute:e=>r.ensureManagedApplicationRoute(e),waitForApplicationCryptoForPeer:(e,t)=>r.waitForApplicationCryptoForPeer(e,t),hasApplicationRouteForPeer:(e,t)=>r.hasApplicationRouteForPeer(e,t),rememberRouteRepairTokenFromTicket:e=>r.sessionTokens.rememberRouteRepairTokenFromTicket(e)}),schedulePeerReconciliation:e=>r.peerProjection.schedule(e),onBackendConnectionState:e=>{if(r.peerProjection.applyBackendConnectionState(e),Xs(e)){r.transportServices.retireBrowserIrohWebRtcCarrierConnection(e.connectionId,Zs(e));return}if(e.transportState!=="connected"||e.replacementInProgress===true)return;let t=r.registry.get(e.connectionId);if(!t||t.isClosed||e.remoteNodeId&&e.remoteNodeId.trim()!==t.remoteNodeId)return;let n=e.transportStableId,i=e.transportGeneration;if(!Number.isSafeInteger(n)||Number(n)<=0||!Number.isSafeInteger(i)||Number(i)<=0){c$1("[Client] connected backend state lacks physical-generation authority",{connectionId:t.id,remoteNodeId:t.remoteNodeId,transportStableId:n??null,transportGeneration:i??null});return}let o=()=>{t.handleBaseTransportAvailable("rust-backend-state",{transportState:e.transportState??e.state,transportGeneration:i,transportStableId:n});};r.managedTransportDialer.repairAdmissionForTransportGeneration(t.remoteNodeId,Number(n)).then(s=>{!s||t.isClosed||r.sessionTokens.applyTrustApproval(t,s,"managed-transport-generation-repair");}).catch(s=>{if(r.managedTransportDialer.isTerminalSessionTokenRejection(s)){let a=s instanceof Error?s.message:String(s);t.handleSessionAdmissionRejected(a),c$1("[Client][AUTH] current-generation admission rejected terminally",{connectionId:t.id,remoteNodeId:t.remoteNodeId,transportStableId:n,reason:a});return}c$1("[Client][AUTH] current-generation admission repair deferred",{connectionId:t.id,remoteNodeId:t.remoteNodeId,transportStableId:n,error:s instanceof Error?s.message:String(s)});}).finally(o);},beforeSignOut:()=>r.prepareStreamListenForSignOutIfExists(),usesTicketOnlySignalingMode:()=>r.runtimeStatus.usesTicketOnlySignalingMode(),ensureWasmRuntimeForP2P:()=>r.runtimeReadiness.ensureWasmRuntimeForP2P(),getTicket:()=>r.runtimeIdentity.getTicket(),ensureSignalingReadyForDiscovery:e=>r.runtimeReadiness.ensureSignalingReadyForDiscovery(e),requiresManagedTransportTrust:()=>r.runtimeStatus.requiresManagedTransportTrust(r.discoveryMode),onDeviceRemembered:e=>{r.applicationCrypto.reindexDevice(e);},applyDiscoveredDevice:e=>{r.peerServices.applyDiscoveredDevice(e);},getPeerStatus:e=>r.peerServices.getPeerStatus(e),hasPeerScopes:e=>r.peerServices.hasPeerScopes(e),forceDisconnectPeer:e=>r.peerServices.forceDisconnectPeer(e)})}var ui=class{constructor(e){this.host=e;}get auth(){return this._auth||(this._auth=new Pt(this.host.getContext(),this.host.getOptions(),{usesTicketOnlySignalingMode:()=>this.host.usesTicketOnlySignalingMode(),getCurrentUser:()=>this.backend.getCurrentUser(),waitForAuth:()=>this.backend.waitForAuth(),onAuthChange:e=>this.backend.onAuthChange(e),signInAnonymously:()=>this.backend.signInAnonymously(),signInWithPluto:()=>this.backend.signInWithPluto(),signOut:()=>this.backend.signOut(),beforeSignOut:()=>this.host.beforeSignOut(),stopAuthActivity:()=>this.backend.stopAuthActivity()})),this._auth}get backend(){return this._backend||(this._backend=new wt(this.host.getContext(),{getOptions:()=>this.host.getOptions(),getApiKey:()=>this.host.getApiKey(),usesTicketOnlySignalingMode:()=>this.host.usesTicketOnlySignalingMode(),getCurrentSignaling:()=>this.host.getCurrentSignaling(),createSignaling:e=>this.host.createSignaling(e),stopRoomLiveness:()=>this.host.stopRoomLiveness(),installBackend:(e,t)=>this.host.installBackend(e,t),setAppLimits:e=>this.host.setAppLimits(e),setDiscoveryMode:e=>this.host.setDiscoveryMode(e),setRoomCreationMode:e=>this.host.setRoomCreationMode(e),getCoreClientHost:()=>this.host.getCoreClientHost(),onBackendConnectionState:e=>this.host.onBackendConnectionState(e),schedulePeerReconciliation:e=>this.host.schedulePeerReconciliation(e),onSignalingBackendChanged:()=>{this._presence?.notifySignalingBackendChanged();}})),this._backend}get presence(){return this._presence||(this._presence=new Tt(this.host.getContext(),this.host.getOptions(),{ensureWasmRuntimeForP2P:()=>this.host.ensureWasmRuntimeForP2P(),ensureAuthenticated:e=>this.auth.ensureAuthenticated(e),getTicket:()=>this.host.getTicket(),getLocalDeviceId:()=>this.backend.getLocalDeviceId(),getCurrentUser:()=>this.backend.getCurrentUser(),startPresenceLoop:(e,t,n,i,o)=>this.backend.startPresenceLoop(e,t,n,i,o),setOffline:e=>this.backend.setOffline(e),updatePresence:(e,t,n,i,o)=>this.backend.updatePresence(e,t,n,i,o),splitCompoundTicket:e=>ee(e),decodeCompoundTicketPayload:(e,t)=>se(e,t),buildCompoundTicketWithPayload:(e,t,n,i)=>bt(e,t,n,i)})),this._presence}get devices(){return this._devices||(this._devices=new Rt(this.host.getContext(),{ensureSignalingReadyForDiscovery:e=>this.host.ensureSignalingReadyForDiscovery(e),searchDevices:()=>this.backend.searchDevices(),updateDevice:(e,t)=>this.backend.updateDevice(e,t),deleteDevice:e=>this.backend.deleteDevice(e),cleanupStaleDevices:()=>this.backend.cleanupStaleDevices(),onDevicesChange:e=>this.backend.onDevicesChange(e),subscribeSessions:(e,t)=>this.backend.subscribeSessions(e,t),requiresManagedTransportTrust:()=>this.host.requiresManagedTransportTrust(),onDeviceRemembered:e=>this.host.onDeviceRemembered(e),applyDiscoveredDevice:e=>this.host.applyDiscoveredDevice(e),getPeerStatus:e=>this.host.getPeerStatus(e),hasPeerScopes:e=>this.host.hasPeerScopes(e),forceDisconnectPeer:e=>this.host.forceDisconnectPeer(e),getLocalDeviceId:()=>this.backend.getLocalDeviceId()})),this._devices}clearManagedPresenceTicketIfExists(){this._presence?.clearManagedPresenceTicket();}};var At=class{constructor(e){this.localTerminalConnectionIds=new Set;this.connections=e??new Map;}get(e){return this.connections.get(e)}has(e){return this.connections.has(e)}set(e,t){this.connections.set(e,t);}delete(e){return this.connections.delete(e)}values(){return this.connections.values()}forEach(e){this.connections.forEach(e);}[Symbol.iterator](){return this.connections[Symbol.iterator]()}get size(){return this.connections.size}all(){return Array.from(this.connections.values())}applicationReady(e={}){return this.all().filter(t=>typeof t.isPayloadReady=="function"?t.isPayloadReady(e):!t.isClosed)}get backingMap(){return this.connections}set backingMap(e){this.connections=e instanceof Map?e:new Map;}getForPeer(e,t){for(let n of this.connections.values())if(e&&n.id===e||t&&(n.remoteNodeId===t||n.deviceId===t))return n;return null}markLocalTerminalClose(e){this.localTerminalConnectionIds.add(e);}clearLocalTerminalClose(e){this.localTerminalConnectionIds.delete(e);}hasLocalTerminalClose(e){return !!e&&this.localTerminalConnectionIds.has(e)&&!this.connections.has(e)}};function Qe(){return BigInt(Date.now())}function kt(r,e){let t=new ArrayBuffer(17),n=new DataView(t);return n.setUint8(0,3),n.setBigUint64(1,r,false),n.setBigInt64(9,e,false),new Uint8Array(t)}function Zo(r,e){let t=new ArrayBuffer(25),n=new DataView(t);return n.setUint8(0,4),n.setBigUint64(1,r.seq,false),n.setBigInt64(9,r.senderUnixMs,false),n.setBigInt64(17,e,false),new Uint8Array(t)}function er(r){if(r.byteLength<17||r[0]!==3)return null;let e=new DataView(r.buffer,r.byteOffset,r.byteLength);return {seq:e.getBigUint64(1,false),senderUnixMs:e.getBigInt64(9,false)}}function tr(r){if(r.byteLength<25||r[0]!==4)return null;let e=new DataView(r.buffer,r.byteOffset,r.byteLength);return {seq:e.getBigUint64(1,false),senderUnixMs:e.getBigInt64(9,false),recvUnixMs:e.getBigInt64(17,false)}}function gi(r,e){let t=import.meta.env??{};if(!(String(t.VITE_E2E??"").toLowerCase()==="true"))return e;let i=r==="VITE_OPENRTC_E2E_WEBRTC_HEARTBEAT_TICK_MS"?t.VITE_OPENRTC_E2E_WEBRTC_HEARTBEAT_TICK_MS:r==="VITE_OPENRTC_E2E_WEBRTC_HEARTBEAT_SUSPECT_MS"?t.VITE_OPENRTC_E2E_WEBRTC_HEARTBEAT_SUSPECT_MS:r==="VITE_OPENRTC_E2E_WEBRTC_HEARTBEAT_STALE_MS"?t.VITE_OPENRTC_E2E_WEBRTC_HEARTBEAT_STALE_MS:void 0,o=Number(i);return Number.isFinite(o)&&o>0?o:e}var Ve={tickIntervalMs:gi("VITE_OPENRTC_E2E_WEBRTC_HEARTBEAT_TICK_MS",5e3),suspectAfterMs:gi("VITE_OPENRTC_E2E_WEBRTC_HEARTBEAT_SUSPECT_MS",1e4),staleAfterMs:gi("VITE_OPENRTC_E2E_WEBRTC_HEARTBEAT_STALE_MS",3e4)},Nt=class{constructor(e,t,n=Ve){this.seq=0n;this.pendingPings=new Map;this.lastPongAtMs=null;this.firstPingSentAtMs=null;this.currentHealth="unknown";this.lastLatencyMs=null;this.tickTimer=null;this.stopped=false;this.probeWaiters=new Map;this.probeLatencyWaiters=new Map;this.probeTimers=new Map;this.probeLatencyTimers=new Map;this.sendFn=e,this.onHealthChange=t,this.config=n;}start(){this.tickTimer!==null||this.stopped||(this.tickTimer=setInterval(()=>{this.tick();},this.config.tickIntervalMs),this.tick());}stop(){this.stopped=true,this.tickTimer!==null&&(clearInterval(this.tickTimer),this.tickTimer=null);for(let e of this.probeWaiters.values())e(false);this.probeWaiters.clear();for(let e of this.probeTimers.values())clearTimeout(e);this.probeTimers.clear();for(let e of this.probeLatencyWaiters.values())e(null);this.probeLatencyWaiters.clear();for(let e of this.probeLatencyTimers.values())clearTimeout(e);this.probeLatencyTimers.clear(),this.pendingPings.clear();}handleIncoming(e){if(!e||e.byteLength===0)return false;let t=e[0];if(t===3){let n=er(e);if(n){c$1("[TransportHeartbeat] ping received from peer, sending pong",{seq:n.seq.toString()});let i=Zo(n,Qe());this.sendFn(i).catch(o=>console.warn("[TransportHeartbeat] pong send failed",o));}else console.warn("[TransportHeartbeat] ping decode failed",{byteLength:e.byteLength});return true}if(t===4){let n=tr(e);if(n){let i=this.pendingPings.get(n.seq),o=i!==void 0,s=null;c$1("[TransportHeartbeat] pong received",{seq:n.seq.toString(),wasPending:o,pendingCount:this.pendingPings.size}),o&&(this.pendingPings.delete(n.seq),this.lastPongAtMs=Date.now(),s=Math.max(0,this.lastPongAtMs-i),this.lastLatencyMs=s,this.evaluateHealth());let a=this.probeWaiters.get(n.seq);a&&(this.probeWaiters.delete(n.seq),a(true));let c=this.probeLatencyWaiters.get(n.seq);c&&(this.probeLatencyWaiters.delete(n.seq),c(s));}else console.warn("[TransportHeartbeat] pong decode failed",{byteLength:e.byteLength});return true}return false}async tick(){if(this.stopped)return;let e=Date.now(),t=e-this.config.staleAfterMs;for(let[o,s]of this.pendingPings)s<=t&&this.pendingPings.delete(o);this.seq++;let n=this.seq,i=kt(n,Qe());try{await this.sendFn(i),this.firstPingSentAtMs===null&&(this.firstPingSentAtMs=e),this.pendingPings.set(n,e),c$1("[TransportHeartbeat] ping sent",{seq:n.toString(),pendingCount:this.pendingPings.size,lastPongAtMs:this.lastPongAtMs,silenceSinceLastPongMs:this.lastPongAtMs?e-this.lastPongAtMs:null});}catch(o){console.warn("[TransportHeartbeat] ping send failed",{seq:n.toString(),error:o});}this.evaluateHealth();}evaluateHealth(){let e=this.computeHealth();if(e!==this.currentHealth){c$1("[TransportHeartbeat] health transition",{from:this.currentHealth,to:e,lastPongAtMs:this.lastPongAtMs,firstPingSentAtMs:this.firstPingSentAtMs,silenceMs:this.lastPongAtMs?Date.now()-this.lastPongAtMs:this.firstPingSentAtMs?Date.now()-this.firstPingSentAtMs:null,pendingCount:this.pendingPings.size}),this.currentHealth=e;try{this.onHealthChange(e);}catch{}}}computeHealth(){let e=Date.now();if(this.firstPingSentAtMs===null)return "unknown";if(this.lastPongAtMs!==null){let n=e-this.lastPongAtMs;return n>=this.config.staleAfterMs?"stale":n>=this.config.suspectAfterMs?"suspect":"healthy"}let t=e-this.firstPingSentAtMs;return t>=this.config.staleAfterMs?"stale":t>=this.config.suspectAfterMs?"suspect":"unknown"}get health(){return this.currentHealth}get latencyMs(){return this.lastLatencyMs}async probe(e){if(this.stopped)return false;this.seq++;let t=this.seq,n=kt(t,Qe()),i=Date.now();return this.pendingPings.set(t,i),this.firstPingSentAtMs===null&&(this.firstPingSentAtMs=i),await new Promise(o=>{let s=setTimeout(()=>{this.probeTimers.delete(t),this.probeWaiters.delete(t)&&(this.pendingPings.delete(t),o(false));},e);this.probeTimers.set(t,s),this.probeWaiters.set(t,a=>{let c=this.probeTimers.get(t);c&&(clearTimeout(c),this.probeTimers.delete(t)),o(a);}),this.sendFn(n).catch(()=>{let a=this.probeTimers.get(t);a&&(clearTimeout(a),this.probeTimers.delete(t)),this.pendingPings.delete(t),this.probeWaiters.delete(t)&&o(false);});})}async probeLatency(e){if(this.stopped)return null;this.seq++;let t=this.seq,n=kt(t,Qe()),i=Date.now();return this.pendingPings.set(t,i),this.firstPingSentAtMs===null&&(this.firstPingSentAtMs=i),await new Promise(o=>{let s=setTimeout(()=>{this.probeLatencyTimers.delete(t),this.probeLatencyWaiters.delete(t)&&(this.pendingPings.delete(t),o(null));},e);this.probeLatencyTimers.set(t,s),this.probeLatencyWaiters.set(t,a=>{let c=this.probeLatencyTimers.get(t);c&&(clearTimeout(c),this.probeLatencyTimers.delete(t)),o(a);}),this.sendFn(n).catch(()=>{let a=this.probeLatencyTimers.get(t);a&&(clearTimeout(a),this.probeLatencyTimers.delete(t)),this.pendingPings.delete(t),this.probeLatencyWaiters.delete(t)&&o(null);});})}};var w=class w{constructor(e,t,n,i,o,s={}){this.listeners=[];this.pendingMessages=[];this.pendingEncryptedApplicationPayloads=[];this.lastApplicationPayloadTransport=null;this.webrtcBinaryHandlers=[];this.closeListeners=[];this.upgradeStateListeners=[];this.writer=null;this.reader=null;this._isClosed=false;this.receiveBuffer=new Uint8Array(0);this.writeMutex=Promise.resolve();this.applicationCryptoWaiters=[];this.applicationKeyAgreementObservationEpoch=0;this.nativeSignalSender=null;this.webrtcTransport=null;this.webRtcApplicationRouteReadyTransport=null;this.webRtcApplicationRouteReadyNegotiationId=null;this.upgradeState="none";this.upgradeRequested=false;this.negotiationSwitchCount=0;this.nativeNegotiationSwitchCount=0;this.upgradeAttemptActive=false;this.upgradeRetryCount=0;this.lastBaseTransportGeneration=null;this.lastBaseTransportStableId=null;this.lastNativeSessionAdmissionRecoveryGeneration=null;this.upgradeReDriveCount=0;this.upgradeReDriveTimer=null;this.upgradeRetryTimer=null;this.inboundSignalRetryBypassUsed=false;this.upgradeAttemptTimeoutTimer=null;this.lastReportedTransportStatus=null;this.pendingTransportStatusReport=null;this.transportStatusReportInFlight=false;this.applicationRouteMissingNotified=false;this.upgradeTerminalFailure=false;this.pendingSignals=[];this.activeNegotiationId=null;this.pendingAvailabilityHint=null;this.webrtcHeartbeat=null;this.webRtcHeartbeatProbeInFlight=false;this.webRtcApplicationRouteProbeInFlight=false;this.pendingWebRtcApplicationRouteProof=null;this.webRtcHeartbeatConsecutiveProbeFailures=0;this.irohHealthListeners=[];this.webrtcHealthListeners=[];this.lastWebRtcHeartbeatOkAt=null;this.lastWebRtcDataChannelOpenAt=null;this.lastApplicationRouteReadyReportAt=null;this.lastForegroundAt=null;this.webRtcDisconnectedGraceTimer=null;this.preferredWebRtcRole=null;this.lastWebRtcLocalCandidateType=null;this.lastWebRtcRemoteCandidateType=null;this._peerMoQReady=false;this._remoteSupportsWebRTC=false;this.mediaListeners=[];this.trackListeners=[];this.warnedSrtpApplicationCryptoBoundary=false;this.id=e,this.localNodeId=t,this.remoteNodeId=n,this.deviceId=n,this.writer=i,this.reader=o,this.options=s,this.readLoop(),this.options.rtcConfig?.lanMode&&this.options.rtcConfig&&queueMicrotask(()=>this.requestWebRTCUpgrade("lan-mode"));}get isClosed(){return this._isClosed}setApplicationCrypto(e){this.options={...this.options,applicationCrypto:e},e?(this.applicationRouteMissingNotified=false,this.resolveApplicationCryptoWaiters(),this.flushPendingEncryptedApplicationPayloads(),!this.isCurrentWebRtcTransportApplicationRouteReady()&&this.webrtcTransport&&this.upgradeState==="upgraded"&&this.startWebRtcApplicationRouteProbe(this.webrtcTransport,"application-crypto-ready"),this.options.transportContext?.requestMoQApplicationRouteProof?.()):this.options.transportContext?.clearMoQApplicationRouteProof?.();}markKeyAgreement(){return this.applicationKeyAgreementObservationEpoch+=1,this.applicationKeyAgreementObservationEpoch}getKeyAgreementEpoch(){return this.applicationKeyAgreementObservationEpoch}requireApplicationCrypto(){this.options={...this.options,requireApplicationCrypto:true};}isApplicationCryptoRequired(){return this.options.requireApplicationCrypto===true}isPayloadReady(e={}){if(this.isClosed||!this.hasRequiredApplicationCrypto())return false;let t$1=e.preferredTransports??[],n=this.getTransportStatus().activeTransport;return t$1.length===0?this.isTransportAvailableForApplicationPayload(n):t$1.includes(n)||t(n)&&t$1.includes("webrtc")?this.isTransportAvailableForApplicationPayload(n):e.allowFallback===true&&this.upgradeState==="failed"&&this.isTransportAvailableForApplicationPayload(n)}payloadTransports(e={}){if(!this.isPayloadReady(e))return [];let t=this.getTransportStatus(),n=[t.activeTransport];return e.includeFallbackTransports===true&&t.parallelTransport&&t.parallelTransport!==t.activeTransport&&this.isTransportAvailableForApplicationPayload(t.parallelTransport)&&n.push(t.parallelTransport),n}isTransportAvailableForApplicationPayload(e){return this._isClosed||!this.hasRequiredApplicationCrypto()?false:t(e)?this.isWebRtcApplicationRouteReady():e==="moq"?this.isMoQApplicationRouteReady():e==="iroh"||e==="iroh-relay"||e==="iroh-quic"||e==="iroh-lan"||e==="iroh-webrtc"||e==="iroh-moq"||e==="ble"?this.hasBaseApplicationRoute():false}resolveApplicationCryptoWaiters(){let e=this.applicationCryptoWaiters.splice(0);for(let t of e)t.timer&&clearTimeout(t.timer),t.resolve();}rejectApplicationCryptoWaiters(e){let t=this.applicationCryptoWaiters.splice(0);for(let n of t)n.timer&&clearTimeout(n.timer),n.reject(e);}async waitForRequiredApplicationCrypto(){if(!this.options.requireApplicationCrypto||this.options.applicationCrypto)return;if(this.isClosed)throw new Error("[Connection] Application crypto is required but the connection is closed.");let e=this.options.applicationCryptoWaitMs??w.DEFAULT_APPLICATION_CRYPTO_WAIT_MS;if(e<=0)throw new Error("[Connection] Application crypto is required before sending app payloads.");await new Promise((t,n)=>{let i={resolve:t,reject:n,timer:null};i.timer=setTimeout(()=>{this.applicationCryptoWaiters=this.applicationCryptoWaiters.filter(o=>o!==i),n(new Error("[Connection] Application crypto negotiation timed out before sending app payloads."));},e),this.applicationCryptoWaiters.push(i);});}requestWebRTCUpgrade(e="peer-capable"){if(!this.options.rtcConfig){this.traceLifecycle("webrtc-request-skipped",{reason:e,skipReason:"missing-rtc-config"});return}let t=this.getDeterministicWebRtcRole();this.upgradeState==="upgrading"&&this.preferredWebRtcRole==="responder"||(this.preferredWebRtcRole=t);let n=this.getControlFrameMode()==="native-main"&&!this.isWebRtcApplicationRouteReady()&&t==="initiator";this.traceLifecycle("webrtc-requested",{reason:e,requestedRole:t,forceRenegotiate:n}),this.beginWebRtcRecovery(e,{forceRenegotiate:n,replaceExisting:n&&!!this.webrtcTransport,resetRetryBudget:true,skipIfAlreadyUpgrading:true});}admissionReady(e="session-token-trust-applied"){this.options.transportContext?.requestIrohCarrier?.();let t=this.lastBaseTransportGeneration,n=this.getControlFrameMode()==="native-main"&&t!==null&&this.lastNativeSessionAdmissionRecoveryGeneration!==t&&this.upgradeState==="upgrading";if(t!==null&&(this.lastNativeSessionAdmissionRecoveryGeneration=t),!n){this.requestWebRTCUpgrade(e);return}let i=this.getDeterministicWebRtcRole();this.preferredWebRtcRole!=="responder"&&(this.preferredWebRtcRole=i),this.traceLifecycle("webrtc-session-admission-recovery",{reason:e,requestedRole:i,transportGeneration:t,transportStableId:this.lastBaseTransportStableId}),this.beginWebRtcRecovery(e,{forceRenegotiate:true,replaceExisting:!!this.webrtcTransport,resetRetryBudget:true,skipIfAlreadyUpgrading:false});}isWebRtcRouteHeartbeatLive(){if(!this.isWebRtcDataChannelOpen())return false;let e=this.lastWebRtcHeartbeatOkAt===null?null:Date.now()-this.lastWebRtcHeartbeatOkAt;if(e!==null&&e<=w.WEBRTC_RENEGOTIATE_LIVENESS_WINDOW_MS)return true;let t=this.lastWebRtcDataChannelOpenAt===null?null:Date.now()-this.lastWebRtcDataChannelOpenAt;return t!==null&&t<=w.WEBRTC_RENEGOTIATE_LIVENESS_WINDOW_MS}requestTransportRecovery(e,t={}){!this.options.rtcConfig||this._isClosed||this.beginWebRtcRecovery(e,{forceRenegotiate:!!t.forceRenegotiate,replaceExisting:!!t.replaceExisting,resetRetryBudget:false,skipIfAlreadyUpgrading:false});}handleAppForeground(){if(this.lastForegroundAt=Date.now(),this._isClosed||!this.options.rtcConfig||!this.upgradeRequested||!this.hasRecoverableBasePath())return;if(this.upgradeState==="upgrading"&&this.upgradeAttemptActive&&this.activeNegotiationId){this.pendingAvailabilityHint={negotiationId:this.activeNegotiationId,source:"app-foreground"},this.traceLifecycle("webrtc-availability-hint-deferred",{negotiationId:this.activeNegotiationId});return}let e=this.webrtcTransport,t=e?.getNativeTransport?.(),n=e?.getDataChannelReadyState?.()??null,i=typeof t?.connectionState=="string"?t.connectionState:null,o=typeof t?.iceConnectionState=="string"?t.iceConnectionState:null;if(this.upgradeState!=="upgraded"||n!=="open"||i==="failed"||i==="disconnected"||o==="failed"||o==="disconnected"){this.requestTransportRecovery("app-foreground",{forceRenegotiate:true,replaceExisting:!!e||this.upgradeState==="failed"||this.upgradeState==="upgraded"});return}let a=this.webrtcHeartbeat,c=this.lastWebRtcHeartbeatOkAt===null?null:Date.now()-this.lastWebRtcHeartbeatOkAt;!(c!==null&&c>=Ve.suspectAfterMs)||!a||a.probe(w.FOREGROUND_PROBE_TIMEOUT_MS).then(l=>{l||this._isClosed||this.webrtcTransport===e&&this.requestTransportRecovery("app-foreground-probe-failed",{forceRenegotiate:true,replaceExisting:true});});}handleBaseTransportAvailable(e,t){if(t.transportState&&t.transportState!=="connected")return;let n=Number.isSafeInteger(t.transportGeneration)&&Number(t.transportGeneration)>0?Number(t.transportGeneration):null,i=Number.isSafeInteger(t.transportStableId)&&Number(t.transportStableId)>0?Number(t.transportStableId):null;if(n===null||i===null){this.traceLifecycle("base-transport-availability-ignored",{source:e,transportGeneration:t.transportGeneration??null,transportStableId:t.transportStableId??null,reason:"missing-generation-authority"});return}let o=false;this.lastBaseTransportGeneration!==null&&n<this.lastBaseTransportGeneration||n!==this.lastBaseTransportGeneration&&(o=this.lastBaseTransportGeneration!==null,this.lastBaseTransportGeneration=n,this.lastBaseTransportStableId=i,!(this._isClosed||!this.options.rtcConfig||!this.upgradeRequested||this.upgradeState==="upgrading"&&!o)&&(this.traceLifecycle("base-transport-available",{source:e,transportGeneration:n,transportStableId:i,replacedBaseTransport:o}),this.beginWebRtcRecovery(`base-transport-available:${e}`,{forceRenegotiate:true,replaceExisting:!!this.webrtcTransport,resetRetryBudget:true,skipIfAlreadyUpgrading:!o})));}beginWebRtcRecovery(e,t){if(!this.options.rtcConfig||this._isClosed)return;let n=t.forceRenegotiate,i=t.replaceExisting,o=t.resetRetryBudget;if(t.skipIfAlreadyUpgrading&&(this.upgradeState==="upgrading"||this.upgradeState==="upgraded")){let s=this.isWebRtcApplicationRouteReady();if(!(this.upgradeState==="upgraded"&&!s&&!this.isWebRtcRouteHeartbeatLive()&&this.getDeterministicWebRtcRole()==="initiator")){c$1("[Connection] WebRTC recovery request ignored: attempt already active",{connectionId:this.id,remoteNodeId:this.remoteNodeId,reason:e,currentState:this.upgradeState,routeAlreadyProven:s});return}c$1("[Connection] WebRTC recovery replacing a stale upgraded route (heartbeat not live)",{connectionId:this.id,remoteNodeId:this.remoteNodeId,reason:e}),this.stopWebRtcHeartbeat(),this.pendingSignals=[],this.teardownWebRTCTransport(`recovery-replace-stale:${e}`),this.setUpgradeState("none");}c$1("[Connection] beginWebRtcRecovery called",{connectionId:this.id,remoteNodeId:this.remoteNodeId,reason:e,replaceExisting:i,forceRenegotiate:n,resetRetryBudget:o,currentState:this.upgradeState,caller:new Error().stack?.split(`
2
+ `).slice(1,4).join(" | ")}),this.upgradeRequested=true,this.upgradeAttemptActive=false,this.upgradeTerminalFailure=false,this.clearUpgradeRetryTimer(),this.clearUpgradeReDriveTimer(),this.clearUpgradeAttemptTimeoutTimer(),o&&(this.upgradeRetryCount=0,this.upgradeReDriveCount=0),i&&(this.stopWebRtcHeartbeat(),this.pendingSignals=[],this.teardownWebRTCTransport(`recovery-replace-existing:${e}`)),this.attemptUpgrade({forceRenegotiate:n,replaceExisting:i});}getUpgradeState(){return this.upgradeState}isCurrentSignal(e){let t=e?.content;if(t?.transport!=="webrtc"||!["sdp","candidate","renegotiate"].includes(t?.type))return !this._isClosed;let n=this.normalizeNegotiationId(t?.negotiationId);return n?!this._isClosed&&n===this.activeNegotiationId:!this._isClosed}updateRTCConfig(e){this.options.rtcConfig=e;}onUpgradeStateChange(e){this.upgradeStateListeners.push(e);}async getTransportDiagnostics(){return this.collectTransportDiagnostics(false)}async collectTransportDiagnostics(e){let{activeTransport:t,parallelTransport:n}=this.getTransportStatus(),i={activeTransport:t,parallelTransport:n,usesRelay:null,relaySource:null,webrtc:null},o=this.webrtcTransport,s=o?.getNativeTransport?.();if(!o||!s)return i;try{let a=typeof s.getStats=="function"?await s.getStats():null,c=null;typeof a?.forEach=="function"&&(a.forEach(D=>{if(c||D?.type!=="transport")return;let _=D?.selectedCandidatePairId;!_||typeof a.get!="function"||(c=a.get(_)??null);}),c||a.forEach(D=>{c||D?.type==="candidate-pair"&&D?.selected===!0&&(c=D);}));let d=c?.localCandidateId&&typeof a?.get=="function"?a.get(c.localCandidateId):null,l=c?.remoteCandidateId&&typeof a?.get=="function"?a.get(c.remoteCandidateId):null,p=s?.sctp?.transport?.iceTransport,u=null;try{u=typeof p?.getSelectedCandidatePair=="function"?p.getSelectedCandidatePair():null;}catch{}let h=u?.local??d??null,m=u?.remote??l??null,f=typeof h?.candidateType=="string"?h.candidateType:typeof h?.type=="string"?h.type:null,v=typeof m?.candidateType=="string"?m.candidateType:typeof m?.type=="string"?m.type:null,y=typeof h?.protocol=="string"?h.protocol:null,C=typeof m?.protocol=="string"?m.protocol:null,I=!!(f&&v),b=I?f==="relay"||v==="relay":null,P=I?`${f??"unknown"}<->${v??"unknown"}`:null;if(this._isClosed||this.webrtcTransport!==o||this.upgradeState!=="upgraded")return {...i,relaySource:"webrtc-stats-stale"};let A=this.webRtcTransportLabel();e&&I&&(this.lastWebRtcLocalCandidateType=f,this.lastWebRtcRemoteCandidateType=v);let S=this.getTransportStatus();return e&&A!==this.webRtcTransportLabel()&&this.isWebRtcApplicationRouteReadyForTransport(o)&&this.reportTransportStatusIfChanged(),{...i,...S,usesRelay:b,relaySource:b==null?null:b?"webrtc-candidate-relay":"webrtc-candidate-direct",webrtc:{iceConnectionState:typeof s.iceConnectionState=="string"?s.iceConnectionState:null,iceGatheringState:typeof s.iceGatheringState=="string"?s.iceGatheringState:null,localCandidateType:f,remoteCandidateType:v,localProtocol:y,remoteProtocol:C,candidateTypeSummary:P}}}catch{return {...i,relaySource:"webrtc-stats-unavailable"}}}refreshWebRtcCandidatePairObservation(e){this._isClosed||this.webrtcTransport!==e||this.collectTransportDiagnostics(true).catch(t=>{c$1("[Connection] WebRTC selected candidate-pair observation failed",{connectionId:this.id,remoteNodeId:this.remoteNodeId,negotiationId:e.getNegotiationId?.()??null,error:t});});}clearWebRtcCandidatePairObservation(){this.lastWebRtcLocalCandidateType=null,this.lastWebRtcRemoteCandidateType=null;}webRtcTransportLabel(){let e=this.options.rtcConfig,t=e?.lanMode===true&&e.useDefaultIceServers===false&&Array.isArray(e.iceServers)&&e.iceServers.length===0;return v$1(this.lastWebRtcLocalCandidateType,this.lastWebRtcRemoteCandidateType,t)}get transportType(){return this.isWebRtcApplicationRouteReady()?this.webRtcTransportLabel():this.isMoQApplicationRouteReady()?"moq":"iroh-relay"}get peerMoQReady(){return this._peerMoQReady}set peerMoQReady(e){this._peerMoQReady!==e&&(this._peerMoQReady=e,e?this.options.transportContext?.requestMoQApplicationRouteProof?.():this.options.transportContext?.clearMoQApplicationRouteProof?.(),this.reportTransportStatusIfChanged());}get remoteSupportsWebRTC(){return this._remoteSupportsWebRTC}set remoteSupportsWebRTC(e){this._remoteSupportsWebRTC=e;}async send(e,t={}){return this.sendTyped(0,e,{requireApplicationCrypto:true,useApplicationPayloadRoute:true,routeOptions:t})}async sendMedia(e,t){let n=e==="video"?1:2;return this.sendTyped(n,t,{requireApplicationCrypto:true})}async sendOnTransport(e,t){return this.sendTypedOnTransport(e,0,t,{requireApplicationCrypto:true})}lastPayloadTransport(){return this.lastApplicationPayloadTransport}async sendControl(e){return this.sendTyped(0,e,{requireApplicationCrypto:false,protectApplicationPayload:false})}async sendRawIrohFrame(e){if(this.isClosed||!this.writer)throw new Error("[Connection] Requested transport unavailable: iroh");let t=this.writeMutex,n;this.writeMutex=new Promise(i=>{n=i;});try{if(await t,!this.writer)throw new Error("[Connection] Requested transport unavailable: iroh");await this.writer.write(e);}catch(i){throw this.preserveWebRtcConnectionAfterBaseTransportLoss(`Iroh Send Error: ${i}`)||(console.error("[Connection] Iroh Send error:",i),this.close(`Send Error: ${i}`)),i}finally{n();}}getAvailableTransports(){let e=[],{activeTransport:t,parallelTransport:n}=this.getTransportStatus();this.isWebRtcApplicationRouteReady()&&e.push(this.webRtcTransportLabel());this.options.transportContext;if(this.isMoQApplicationRouteReady()&&e.push("moq"),this.hasBaseApplicationRoute()){let o=t==="iroh-lan"||t==="iroh-quic"||t==="iroh-relay"||t==="ble"?t:n;e.push(o??"iroh-relay");}return e}onWebRTCBinaryMessage(e){this.webrtcBinaryHandlers.push(e);}dispatchWebRtcBinaryHandlers(e){for(let t of this.webrtcBinaryHandlers)if(t(e))return true;return false}getWebRTCTransport(){return this.isWebRtcApplicationRouteReady()?this.webrtcTransport:null}async sendOnWebRTC(e){if(!this.webrtcTransport||!this.isWebRtcApplicationRouteReady())throw new Error("[Connection] WebRTC transport unavailable");await this.waitForRequiredApplicationCrypto(),await this.webrtcTransport.send(this.protectApplicationPayload(0,e));}encodePayload(e){return typeof e=="string"?new TextEncoder().encode(e):e instanceof Uint8Array?e:e instanceof ArrayBuffer?new Uint8Array(e):new TextEncoder().encode(JSON.stringify(e))}protectApplicationPayload(e,t){return this.options.applicationCrypto?.protectPayload(e,t)??t}protectRequiredApplicationPayload(e,t){let n=this.options.applicationCrypto;return n?n.protectPayload(e,t):null}openApplicationPayload(e,t){let n=this.options.applicationCrypto;return n?n.openPayload(e,t):x$1(t)?(this.queueEncryptedApplicationPayload(e,t),null):this.options.requireApplicationCrypto===true&&!this.isPlaintextBootstrapPayload(t)?null:t}openUntypedApplicationPayload(e){if(!x$1(e))return this.options.requireApplicationCrypto===true?null:e;let t=this.options.applicationCrypto;return t?t.openPayload(0,e)??t.openPayload(3,e):(this.queueEncryptedApplicationPayload("untyped",e),null)}isPlaintextBootstrapPayload(e){try{return JSON.parse(w.textDecoder.decode(e))?.type==="handshake"}catch{return false}}queueEncryptedApplicationPayload(e,t){this._isClosed||(this.pendingEncryptedApplicationPayloads.push({typeId:e,payload:new Uint8Array(t)}),this.pendingEncryptedApplicationPayloads.length>w.MAX_PENDING_ENCRYPTED_APPLICATION_PAYLOADS&&this.pendingEncryptedApplicationPayloads.splice(0,this.pendingEncryptedApplicationPayloads.length-w.MAX_PENDING_ENCRYPTED_APPLICATION_PAYLOADS));}flushPendingEncryptedApplicationPayloads(){let e=this.options.applicationCrypto;if(!e||this.pendingEncryptedApplicationPayloads.length===0)return;let t=this.pendingEncryptedApplicationPayloads.splice(0),n=[];for(let i of t){let o=i.typeId==="untyped"?e.openPayload(0,i.payload)??e.openPayload(3,i.payload):e.openPayload(i.typeId,i.payload);if(o){i.typeId===1?this.emitMedia("video",o):i.typeId===2?this.emitMedia("audio",o):this.processDataPayload(o);continue}x$1(i.payload)&&n.push(i);}n.length>w.MAX_PENDING_ENCRYPTED_APPLICATION_PAYLOADS&&n.splice(0,n.length-w.MAX_PENDING_ENCRYPTED_APPLICATION_PAYLOADS),this.pendingEncryptedApplicationPayloads=n;}buildFrame(e,t){let n=5+t.length,i=new Uint8Array(n);return new DataView(i.buffer).setUint32(0,1+t.length,false),i[4]=e,i.set(t,5),i}async sendOverIroh(e,t,n){let i=this.options.transportContext;if(i?.disableIrohFallback&&e!==0)return console.warn(`[Connection] Iroh disabled for ${n}; dropping packet.`),false;if(this.isClosed)return false;if(!this.writer&&i?.sendIrohApplicationFrame)return await i.sendIrohApplicationFrame(t),true;if(!this.writer)return false;let o=this.writeMutex,s;this.writeMutex=new Promise(a=>{s=a;});try{return await o,this.writer?(await this.writer.write(t),!0):!1}catch(a){if(this.preserveWebRtcConnectionAfterBaseTransportLoss(`Iroh Send Error: ${a}`))return false;throw console.error("[Connection] Iroh Send error:",a),this.close(`Send Error: ${a}`),a}finally{s();}}async sendUsingTransport(e,t,n,i,o,s){let a=this.options.transportContext;return e==="webrtc-lan"||e==="webrtc-turn"?this.transportType!==e||!this.webrtcTransport||!this.isWebRtcApplicationRouteReady()||t!==0?false:(await this.webrtcTransport.send(o),this.reportApplicationRouteReady("webrtc-application-send"),true):e==="webrtc"?!this.webrtcTransport||!this.isWebRtcApplicationRouteReady()||t!==0?false:(await this.webrtcTransport.send(o),this.reportApplicationRouteReady("webrtc-application-send"),true):e==="moq"?a&&a.isMoQReady()&&this.peerMoQReady&&this.isMoQDataRouteReady(a)?(await a.sendMoQ(s,{alreadyProtected:true}),true):false:e==="iroh-lan"||e==="ble"?this.transportType!==e?false:this.sendOverIroh(t,s,"explicit transport send"):e==="iroh"||e==="iroh-relay"||e==="iroh-quic"||e==="iroh-webrtc"||e==="iroh-moq"?this.sendOverIroh(t,s,"explicit transport send"):false}async sendTypedOnTransport(e,t,n,i={}){i.requireApplicationCrypto&&await this.waitForRequiredApplicationCrypto();let o=this.encodePayload(n),s=i.protectApplicationPayload===false?o:this.protectApplicationPayload(t,o),a=this.buildFrame(t,o),c=this.buildFrame(t,s);if(!await this.sendUsingTransport(e,t,n,a,s,c))throw new Error(`[Connection] Requested transport unavailable: ${e}`);this.lastApplicationPayloadTransport=e;}async sendTyped(e,t,n={}){this.options.transportContext;n.requireApplicationCrypto&&await this.waitForRequiredApplicationCrypto();let o=this.encodePayload(t),s=n.protectApplicationPayload===false?o:this.protectApplicationPayload(e,o),a=this.buildFrame(e,o),c=this.buildFrame(e,s),d=n.useApplicationPayloadRoute&&e===0?this.payloadTransports(n.routeOptions??{}):this.getSendTransportPriorities(n);if(d.length===0)throw new Error("[Connection] Application payload route is not ready.");let l=null;for(let u of d)try{if(await this.sendUsingTransport(u,e,t,a,s,c)){this.lastApplicationPayloadTransport=u;return}}catch(h){l=h,console.warn(`[Connection] ${u} Send Failed:`,h);}let p=d.join(", ");throw l instanceof Error?new Error(`[Connection] Failed to send app payload on route(s): ${p}. Last error: ${l.message}`):new Error(`[Connection] Failed to send app payload on route(s): ${p}.`)}getSendTransportPriorities(e){let t=["webrtc","moq","iroh"],n=this.options.transportContext?.priorities??t,i=n.length>0?n:t,o=this.options.transportContext?.rankRoutes?.(i)??i;return e.requireApplicationCrypto===false||e.protectApplicationPayload===false?["iroh",...o.filter(a=>a!=="iroh"&&a!=="iroh-relay"&&a!=="iroh-quic"&&a!=="iroh-lan")]:o}async disconnect(){this.close("Explicit Disconnect");}handleSessionAdmissionRejected(e){this.close(`Session Admission Rejected: ${e}`);}onMessage(e){if(this.listeners.push(e),this.pendingMessages.length!==0)for(let t of this.pendingMessages)e(t);}onMedia(e){this.mediaListeners.push(e);}onDisconnect(e){this.closeListeners.push(e);}close(e){if(this._isClosed)return;if(this._isClosed=true,this.upgradeRequested=false,this.upgradeAttemptActive=false,this.activeNegotiationId=null,this.pendingAvailabilityHint=null,this.pendingSignals=[],this.clearUpgradeRetryTimer(),this.clearUpgradeReDriveTimer(),this.clearUpgradeAttemptTimeoutTimer(),this.clearWebRtcDisconnectedGraceTimer(),this.teardownWebRTCTransport(`connection-close:${e??"unspecified"}`),this.setUpgradeState("none"),this.rejectApplicationCryptoWaiters(new Error("[Connection] Application crypto negotiation stopped because the connection closed.")),this.pendingEncryptedApplicationPayloads=[],this.writer?.close().catch(()=>{}),(this.options.transportContext?.readerCloseStrategy??"cancel")==="release-lock")try{this.reader?.releaseLock();}catch{}else this.reader?.cancel().catch(()=>{});this.writer=null,this.reader=null,this.closeListeners.forEach(n=>n());}preserveWebRtcConnectionAfterBaseTransportLoss(e){let t=this.getControlFrameMode()==="native-main"&&!!this.nativeSignalSender,n=!!this.webrtcTransport&&(this.upgradeState==="upgraded"||this.upgradeState==="upgrading"&&!!this.nativeSignalSender);if(!t&&!n)return false;c$1("[Connection] Base transport closed while a control/WebRTC route remains usable; preserving connection",{connectionId:this.id,remoteNodeId:this.remoteNodeId,reason:e,transportStatus:this.getTransportStatus(),upgradeState:this.upgradeState}),this.clearUpgradeRetryTimer();try{this.reader?.releaseLock();}catch{}try{this.writer?.releaseLock();}catch{}return this.reader=null,this.writer=null,this.reportApplicationRouteReady("base-transport-loss-preserved"),this.reportTransportStatusIfChanged(),true}async readLoop(){if(this.reader)try{for(;!this.isClosed;){let{done:e,value:t}=await this.reader.read();if(e){if(this.preserveWebRtcConnectionAfterBaseTransportLoss("Read Done (Remote Closed)"))break;this.close("Read Done (Remote Closed)");break}t&&this.handleData(t);}}catch(e){let t=`Read Error: ${e}`;if(this.preserveWebRtcConnectionAfterBaseTransportLoss(t))return;console.error("[Connection] Read loop error:",e),this.close(t);}}injectData(e){this.handleData(e);}handleData(e){let t=new Uint8Array(this.receiveBuffer.length+e.length);for(t.set(this.receiveBuffer),t.set(e,this.receiveBuffer.length),this.receiveBuffer=t;!(this.receiveBuffer.length<4);){let i=new DataView(this.receiveBuffer.buffer,this.receiveBuffer.byteOffset,this.receiveBuffer.byteLength).getUint32(0,false);if(this.receiveBuffer.length<4+i)break;let o=this.receiveBuffer.slice(4,4+i);this.receiveFrameBody(o),this.receiveBuffer=this.receiveBuffer.slice(4+i);}}receiveFrameBody(e){if(e.length===0)return;let t=e[0],n=e.slice(1);if(w.isUntypedDataFrame(e)){let i=this.openUntypedApplicationPayload(e);i&&this.processDataPayload(i);}else if(t===3)this.sendIrohHeartbeatPong(n);else if(t===4)this.irohHealthListeners.forEach(i=>i("healthy"));else if(t===1){let i=this.openApplicationPayload(t,n);i&&this.emitMedia("video",i);}else if(t===2){let i=this.openApplicationPayload(t,n);i&&this.emitMedia("audio",i);}else {if(t===0&&this.tryHandlePlaintextNativeSignal(n))return;let i=this.openApplicationPayload(t,n);i&&this.processDataPayload(i);}}tryHandlePlaintextNativeSignal(e){let t;try{t=JSON.parse(w.textDecoder.decode(e));}catch{return false}return !t||typeof t!="object"||t.type!=="#pluto-signal"?false:(this.handleInternalSignal(t),true)}static isUntypedDataFrame(e){let t=e[0];return t===123||t===91||x$1(e)?true:e.length>=4&&e[0]===68&&e[1]===86&&e[2]===67&&e[3]===72}processDataPayload(e){if(x$1(e)){let t=this.openUntypedApplicationPayload(e);t&&t!==e&&this.processDataPayload(t);return}try{let t=w.textDecoder.decode(e);if(!this.isLikelyTextPayload(e,t)){this.emitMessage(e);return}let n=JSON.parse(t);if(this.tryHandleWebRtcApplicationRouteProofPayload(n,null))return;if(n&&typeof n=="object"&&n.type==="#pluto-signal"){this.handleInternalSignal(n);return}typeof n=="object"&&n!==null?this.emitMessage(n):this.emitMessage(t);}catch{try{let t=w.textDecoder.decode(e);if(this.isLikelyTextPayload(e,t)){this.emitMessage(t);return}}catch{}this.emitMessage(e);}}isLikelyTextPayload(e,t){try{for(let i=0;i<t.length;i+=1){let o=t.charCodeAt(i);if(o<32&&o!==9&&o!==10&&o!==13)return !1}let n=w.textEncoder.encode(t);if(n.byteLength!==e.byteLength)return !1;for(let i=0;i<n.byteLength;i+=1)if(n[i]!==e[i])return !1;return !0}catch{return false}}emitMedia(e,t){this.mediaListeners.forEach(n=>n(e,t));}emitMessage(e){this.pendingMessages.push(e),this.pendingMessages.length>w.MAX_PENDING_MESSAGES&&this.pendingMessages.splice(0,this.pendingMessages.length-w.MAX_PENDING_MESSAGES),this.listeners.length!==0&&this.listeners.forEach(t=>t(e));}receiveMessage(e){this.emitMessage(e);}receiveDataPayload(e){this.processDataPayload(e);}warnSrtpApplicationCryptoBoundary(e){!this.options.applicationCrypto||this.warnedSrtpApplicationCryptoBoundary||(this.warnedSrtpApplicationCryptoBoundary=true,console.warn(`[Connection] ${e} uses WebRTC DTLS-SRTP media encryption, not the ORTCE1 applicationCrypto envelope. Use sendMedia() for ORTCE1-protected app-encoded media chunks.`));}addTrack(e){let t=this.webrtcTransport?.getNativeTransport?.();return t&&typeof t.addTrack=="function"?(this.warnSrtpApplicationCryptoBoundary("addTrack"),t.addTrack(e)):null}addTransceiver(e,t){let n=this.webrtcTransport?.getNativeTransport?.();return n&&typeof n.addTransceiver=="function"?(this.warnSrtpApplicationCryptoBoundary("addTransceiver"),n.addTransceiver(e,t)):null}onTrack(e){this.trackListeners.push(e);}hasRecoverableBasePath(){return !!this.nativeSignalSender||this.hasBaseApplicationRoute()}hasBaseApplicationRoute(){return this.options.hasBaseApplicationStream===false?false:!!this.writer||this.getControlFrameMode()==="native-main"&&!!this.nativeSignalSender&&typeof this.options.transportContext?.sendIrohApplicationFrame=="function"}isWebRtcDataChannelOpen(){return this.upgradeState==="upgraded"&&!!this.webrtcTransport&&this.webrtcTransport.getDataChannelReadyState?.()==="open"}clearWebRtcDisconnectedGraceTimer(){this.webRtcDisconnectedGraceTimer&&(clearTimeout(this.webRtcDisconnectedGraceTimer),this.webRtcDisconnectedGraceTimer=null);}transportStillLikelyAlive(e){let t=e.getDataChannelReadyState?.()??null,n=e.getNativeTransport?.()??null,i=typeof n?.connectionState=="string"?n.connectionState:null,o=typeof n?.iceConnectionState=="string"?n.iceConnectionState:null;return t==="closed"||t==="closing"?false:t==="open"?true:i==="connected"||i==="connecting"||o==="connected"||o==="completed"||o==="checking"}handleUnhealthyWebRtcTransportStateWithGrace(e,t){let n=e.getDataChannelReadyState?.()??null;if(n==="closed"||n==="closing"){if(c$1("[Connection] WebRTC unhealthy with closed DataChannel; failing upgraded transport immediately",{connectionId:this.id,remoteNodeId:this.remoteNodeId,state:t,dcReadyState:n}),!this.hasBaseApplicationRoute()&&!this.isMoQApplicationRouteReady()){this.close(`all-application-routes-closed:${t}`);return}this.stopWebRtcHeartbeat(),this.handleUpgradeFailure(`transport-state-${t}-dc-closed`);return}this.webRtcDisconnectedGraceTimer||(c$1("[Connection] WebRTC transport reported unhealthy; applying grace window before fallback",{connectionId:this.id,remoteNodeId:this.remoteNodeId,state:t}),this.webRtcDisconnectedGraceTimer=setTimeout(()=>{if(this.webRtcDisconnectedGraceTimer=null,!(this._isClosed||this.webrtcTransport!==e)){if(this.transportStillLikelyAlive(e)){c$1("[Connection] WebRTC unhealthy grace expired but transport appears alive; suppressing fallback",{connectionId:this.id,remoteNodeId:this.remoteNodeId,state:t});return}this.stopWebRtcHeartbeat(),this.handleUpgradeFailure(`transport-state-${t}-grace-expired`);}},w.WEBRTC_DISCONNECTED_GRACE_MS));}async attemptUpgrade(e){if(this._isClosed||!this.upgradeRequested||!this.options.rtcConfig||this.upgradeState==="failed"&&this.upgradeRetryTimer&&this.inboundSignalRetryBypassUsed)return;let t=typeof e=="object"&&e!==null?e:{preferredNegotiationId:e??null},n=t.preferredNegotiationId,i=!!t.forceRenegotiate;if(!!!t.replaceExisting&&(this.upgradeAttemptActive||this.upgradeState==="upgraded"))return;this.upgradeAttemptActive=true,this.teardownWebRTCTransport("upgrade-attempt-replacement"),this.clearWebRtcCandidatePairObservation(),this.applicationRouteMissingNotified=false;let s=this.normalizeNegotiationId(n)??this.createNegotiationId();this.activeNegotiationId=s,this.setUpgradeState("upgrading"),this.startUpgradeAttemptTimeout(s),(i||this.upgradeRetryCount>0)&&this.sendInternalSignal({transport:"webrtc",type:"renegotiate",negotiationId:s}).catch(()=>{});try{this.webrtcTransport=b$4.createTransport("webrtc");}catch(l){this.upgradeAttemptActive=false,c$1("[Connection] WebRTC upgrade unavailable",l),this.handleUpgradeFailure("transport-create-error");return}let a=this.webrtcTransport;typeof a.setSignalSender=="function"&&a.setSignalSender(l=>this.webrtcTransport!==a?(c$1("[Connection] Dropping WebRTC signal from retired transport",{connectionId:this.id,remoteNodeId:this.remoteNodeId,signalType:l?.type??null,signalNegotiationId:this.normalizeNegotiationId(l?.negotiationId),activeNegotiationId:this.activeNegotiationId}),Promise.resolve()):this.sendInternalSignal(l)),a.onMessage(l=>{if(l instanceof Uint8Array&&l.byteLength>0){if(this.webrtcHeartbeat?.handleIncoming(l)){l[0]===4&&this.refreshWebRtcCandidatePairObservation(a);return}let u=x$1(l),h=this.openApplicationPayload(0,l);if(!h||u&&this.tryHandleWebRtcApplicationRouteProofBytes(a,h)||this.dispatchWebRtcBinaryHandlers(h))return;this.processDataPayload(h);return}let p=this.openApplicationPayload(0,l);p&&this.processDataPayload(p);}),a.onStateChange(l=>{if(!(this._isClosed||this.webrtcTransport!==a)){if(d$2(`[Connection] WebRTC transport state changed: ${l}`),l==="connected"){this.pendingAvailabilityHint=null,this.clearWebRtcDisconnectedGraceTimer(),this.clearUpgradeAttemptTimeoutTimer(),this.upgradeAttemptActive=false,this.upgradeRetryCount=0,this.clearUpgradeRetryTimer(),this.lastWebRtcDataChannelOpenAt=Date.now(),this.setUpgradeState("upgraded"),this.startWebRtcHeartbeat(a),this.startWebRtcApplicationRouteProbe(a,"transport-connected");return}if(l==="failed"||l==="disconnected"){if(this.clearUpgradeAttemptTimeoutTimer(),this.upgradeAttemptActive=false,this.upgradeState==="upgraded"&&(l==="disconnected"||this.isWebRtcApplicationRouteReadyForTransport(a))){this.handleUnhealthyWebRtcTransportStateWithGrace(a,l);return}if(this.clearWebRtcDisconnectedGraceTimer(),a.isTerminalFailure?.()){let p=this.pendingAvailabilityHint,u=!!p&&p.negotiationId===this.activeNegotiationId;this.pendingAvailabilityHint=null,this.upgradeTerminalFailure=!u,u&&this.traceLifecycle("webrtc-terminal-failure-retry-after-availability",{negotiationId:this.activeNegotiationId,source:p?.source??null});}this.stopWebRtcHeartbeat(),this.handleUpgradeFailure(`transport-state-${l}`);}}});try{await a.init(this.localNodeId,this.deviceId,{rtcConfig:this.options.rtcConfig,negotiationId:s,forceRole:this.preferredWebRtcRole??void 0});}catch(l){this.upgradeAttemptActive=false,this.clearUpgradeAttemptTimeoutTimer(),c$1("[Connection] WebRTC init failed",l),this.handleUpgradeFailure("init-error");return}if(this.webrtcTransport!==a){this.upgradeAttemptActive=false;return}let c=a.getNegotiationId?.();if(c&&(this.activeNegotiationId=this.normalizeNegotiationId(c)??s),this.pendingSignals.length>0){let l=this.pendingSignals.splice(0);for(let p of l)a.handleSignalingMessage?.(p);}let d=a.getNativeTransport?.();d&&d.ontrack!==void 0&&(d.ontrack=l=>{d$2(`[Connection] Peer track received: ${l.track.kind}`),this.trackListeners.forEach(p=>p(l));});}setUpgradeState(e){this.upgradeState!==e&&(this.upgradeState=e,this.reportTransportStatusIfChanged(),this.upgradeStateListeners.forEach(t=>{try{t(e);}catch(n){c$1("[Connection] Upgrade state listener failed",n);}}));}handleUpgradeFailure(e){if(this._isClosed||!this.upgradeRequested)return;this.clearUpgradeAttemptTimeoutTimer();let t=this.upgradeTerminalFailure,n=!t&&this.shouldRetryUpgrade();this.upgradeAttemptActive=false,this.setUpgradeState("failed");let i={connectionId:this.id,remoteNodeId:this.remoteNodeId,retryCount:this.upgradeRetryCount,maxRetries:w.MAX_UPGRADE_RETRIES,terminal:t,willRetry:n};if(n?c$1(`[Connection] WebRTC upgrade retry scheduled after failure: ${e}`,i):console.warn(`[Connection] WebRTC upgrade failed: ${e}`,i),t&&console.warn("[Connection] WebRTC upgrade is terminal \u2014 not retrying. Both peers may be on the same page (same-context loopback)."),c$1(`[Connection] WebRTC upgrade fallback: ${e}`),n){this.scheduleUpgradeRetry();return}this.clearUpgradeRetryTimer(),this.teardownWebRTCTransport(`upgrade-failed:${e}`),!t&&this.upgradeRequested&&!this._isClosed&&this.upgradeRetryCount>=w.MAX_UPGRADE_RETRIES&&this.hasRecoverableBasePath()&&this.scheduleUpgradeReDrive();}scheduleUpgradeReDrive(){this.clearUpgradeReDriveTimer(),this.upgradeReDriveCount=Math.min(this.upgradeReDriveCount+1,Number.MAX_SAFE_INTEGER);let e=this.upgradeReDriveCount,t=Math.min(e-1,w.UPGRADE_REDRIVE_DELAYS_MS.length-1),n=w.UPGRADE_REDRIVE_DELAYS_MS[t];this.upgradeReDriveTimer=setTimeout(()=>{this.upgradeReDriveTimer=null,!(this._isClosed||!this.upgradeRequested||this.upgradeAttemptActive)&&(this.isWebRtcApplicationRouteReady()||!this.hasRecoverableBasePath()||(this.upgradeRetryCount=0,this.upgradeTerminalFailure=false,d$2(`[Connection] Re-driving WebRTC upgrade round ${e} after ${n}ms because the retry budget was exhausted on a healthy base route`),this.attemptUpgrade({forceRenegotiate:true})));},n);}clearUpgradeReDriveTimer(){this.upgradeReDriveTimer&&(clearTimeout(this.upgradeReDriveTimer),this.upgradeReDriveTimer=null);}shouldRetryUpgrade(){return !(this._isClosed||!this.upgradeRequested||this.upgradeTerminalFailure||!this.options.rtcConfig||!this.hasRecoverableBasePath()||this.upgradeRetryCount>=w.MAX_UPGRADE_RETRIES)}scheduleUpgradeRetry(){this.clearUpgradeRetryTimer(),this.upgradeRetryCount+=1;let e=this.upgradeRetryCount;this.upgradeRetryTimer=setTimeout(()=>{this.upgradeRetryTimer=null,this.inboundSignalRetryBypassUsed=false,!(this._isClosed||!this.upgradeRequested||this.upgradeAttemptActive)&&(d$2(`[Connection] Retrying WebRTC upgrade ${e}/${w.MAX_UPGRADE_RETRIES}`),this.attemptUpgrade());},w.UPGRADE_RETRY_DELAY_MS);}clearUpgradeRetryTimer(){this.upgradeRetryTimer&&(clearTimeout(this.upgradeRetryTimer),this.upgradeRetryTimer=null);}startUpgradeAttemptTimeout(e){this.clearUpgradeAttemptTimeoutTimer(),this.upgradeAttemptTimeoutTimer=setTimeout(()=>{this.upgradeAttemptTimeoutTimer=null,!(this._isClosed||!this.upgradeRequested)&&this.upgradeState==="upgrading"&&this.activeNegotiationId===e&&(this.upgradeAttemptActive=false,c$1("[Connection] WebRTC upgrade attempt timed out",{connectionId:this.id,remoteNodeId:this.remoteNodeId,negotiationId:e}),this.handleUpgradeFailure("upgrade-attempt-timeout"));},w.WEBRTC_UPGRADE_ATTEMPT_TIMEOUT_MS);}clearUpgradeAttemptTimeoutTimer(){this.upgradeAttemptTimeoutTimer&&(clearTimeout(this.upgradeAttemptTimeoutTimer),this.upgradeAttemptTimeoutTimer=null);}teardownWebRTCTransport(e){this.pendingAvailabilityHint=null,this.clearWebRtcDisconnectedGraceTimer(),this.clearUpgradeAttemptTimeoutTimer(),this.clearWebRtcCandidatePairObservation();let t=this.webrtcTransport;if(!t)return;let n=t.getNativeTransport?.();this.traceLifecycle("webrtc-transport-teardown",{reason:e,negotiationId:this.activeNegotiationId,dataChannelReadyState:t.getDataChannelReadyState?.()??null,peerConnectionState:n?.connectionState??null,iceConnectionState:n?.iceConnectionState??null}),this.webrtcTransport=null,this.clearWebRtcApplicationRouteReady(),this.cancelWebRtcApplicationRouteProofForTransport(t,`teardown:${e}`),this.applicationRouteMissingNotified=false,this.stopWebRtcHeartbeat();try{t.close();}catch(i){c$1("[Connection] WebRTC transport close failed",i);}this.reportTransportStatusIfChanged();}startWebRtcHeartbeat(e){this.stopWebRtcHeartbeat();let t=Date.now();c$1("[Connection] WebRTC heartbeat starting",{connectionId:this.id,startedAt:t,config:Ve});let n=new Nt(async i=>{c$1("[Connection] WebRTC heartbeat send",{connectionId:this.id,byteLength:i.byteLength,typeId:i[0]}),await e.send(i);},i=>{let o=Date.now()-t;if(c$1("[Connection] WebRTC heartbeat health callback",{connectionId:this.id,health:i,elapsedSinceStartMs:o}),i==="healthy"&&(this.lastWebRtcHeartbeatOkAt=Date.now(),this.webRtcHeartbeatConsecutiveProbeFailures=0,this.isWebRtcApplicationRouteReadyForTransport(e)?this.reportApplicationRouteReady("webrtc-heartbeat-healthy"):this.hasRequiredApplicationCrypto()?this.webrtcTransport===e?this.startWebRtcApplicationRouteProbe(e,"webrtc-heartbeat-healthy"):this.traceLifecycle("webrtc-route-proof-ignored",{reason:"stale-transport",negotiationId:e.getNegotiationId?.()??null,activeNegotiationId:this.activeNegotiationId}):this.notifyWebRtcApplicationRouteMissing("webrtc-heartbeat-before-crypto")),this.webrtcHealthListeners.forEach(s=>s(i)),i==="stale"){if(this.webRtcHeartbeatProbeInFlight)return;this.webRtcHeartbeatProbeInFlight=true,d$2("[Connection] WebRTC heartbeat stale \u2014 probing transport before fallback"),n.probe(4e3).then(s=>{if(this._isClosed||this.webrtcTransport!==e)return;if(s){this.lastWebRtcHeartbeatOkAt=Date.now(),this.webRtcHeartbeatConsecutiveProbeFailures=0,d$2("[Connection] WebRTC heartbeat probe succeeded \u2014 keeping upgraded transport");return}if(this.webRtcHeartbeatConsecutiveProbeFailures+=1,this.transportStillLikelyAlive(e)){this.lastWebRtcHeartbeatOkAt=Date.now(),d$2("[Connection] WebRTC heartbeat probe failed but transport appears alive \u2014 suppressing fallback",{connectionId:this.id,remoteNodeId:this.remoteNodeId,consecutiveFailures:this.webRtcHeartbeatConsecutiveProbeFailures});return}if(this.webRtcHeartbeatConsecutiveProbeFailures<2){d$2("[Connection] WebRTC heartbeat probe failed \u2014 awaiting one more failure before fallback",{connectionId:this.id,remoteNodeId:this.remoteNodeId,consecutiveFailures:this.webRtcHeartbeatConsecutiveProbeFailures});return}if(!this.hasRecoverableBasePath()){this.lastWebRtcHeartbeatOkAt=Date.now(),d$2("[Connection] WebRTC heartbeat probe failed but no base recovery path exists \u2014 keeping transport",{connectionId:this.id,remoteNodeId:this.remoteNodeId});return}d$2("[Connection] WebRTC heartbeat probe failed consecutively \u2014 triggering upgrade fallback"),this.stopWebRtcHeartbeat(),this.handleUpgradeFailure("heartbeat-stale-probe-failed");}).finally(()=>{this.webRtcHeartbeatProbeInFlight=false;});}},Ve);this.webrtcHeartbeat=n,n.start();}stopWebRtcHeartbeat(){this.webRtcHeartbeatProbeInFlight=false,this.webRtcHeartbeatConsecutiveProbeFailures=0,this.webrtcHeartbeat&&(this.webrtcHeartbeat.stop(),this.webrtcHeartbeat=null);}notifyWebRtcApplicationRouteMissing(e){this.applicationRouteMissingNotified||(this.applicationRouteMissingNotified=true,this.traceLifecycle("webrtc-route-proved-application-crypto-missing",{negotiationId:this.activeNegotiationId,reason:e}),this.options.onApplicationRouteMissing?.({connectionId:this.id,remoteNodeId:this.remoteNodeId,reason:e,negotiationId:this.activeNegotiationId}));}currentWebRtcNegotiationId(e){return this.normalizeNegotiationId(e.getNegotiationId?.())??this.normalizeNegotiationId(this.activeNegotiationId)}createWebRtcApplicationRouteProofId(){let e=new Uint8Array(8);try{globalThis.crypto?.getRandomValues?.(e);}catch{for(let n=0;n<e.byteLength;n+=1)e[n]=Math.floor(Math.random()*256);}let t=Array.from(e).map(n=>n.toString(16).padStart(2,"0")).join("");return `${Date.now().toString(36)}-${t}`}isCurrentWebRtcApplicationRouteProof(e){return !e.cancelled&&this.pendingWebRtcApplicationRouteProof===e&&!this._isClosed&&this.webrtcTransport===e.transport&&this.upgradeState==="upgraded"&&this.currentWebRtcNegotiationId(e.transport)===e.negotiationId}cancelWebRtcApplicationRouteProofForTransport(e,t){let n=this.pendingWebRtcApplicationRouteProof;n?.transport===e&&this.cancelWebRtcApplicationRouteProof(n,t);}cancelWebRtcApplicationRouteProof(e,t){!e||e.cancelled||(e.cancelled=true,e.timer&&(clearTimeout(e.timer),e.timer=null),this.pendingWebRtcApplicationRouteProof===e&&(this.pendingWebRtcApplicationRouteProof=null,this.webRtcApplicationRouteProbeInFlight=false),this.traceLifecycle("webrtc-application-route-proof-cancelled",{reason:t,negotiationId:e.negotiationId,probeId:e.probeId}));}completeWebRtcApplicationRouteProofAck(e){if(!this.isCurrentWebRtcApplicationRouteProof(e)){this.traceLifecycle("webrtc-route-proof-ignored",{reason:"stale-proof",negotiationId:e.negotiationId,probeId:e.probeId,activeNegotiationId:this.activeNegotiationId});return}this.cancelWebRtcApplicationRouteProof(e,"ack-received"),this.markWebRtcApplicationRouteReady(e.transport);}async sendWebRtcApplicationRouteProofFrame(e,t,n={}){if(this._isClosed||this.webrtcTransport!==e||this.upgradeState!=="upgraded"||n.requireLocalNegotiation===true&&this.currentWebRtcNegotiationId(e)!==t.negotiationId)throw new Error("[Connection] WebRTC route proof cannot be sent on a stale transport");let i=w.textEncoder.encode(JSON.stringify(t)),o=this.protectRequiredApplicationPayload(0,i);if(!o)throw new Error("[Connection] WebRTC route proof requires application crypto");await e.send(o);}tryHandleWebRtcApplicationRouteProofBytes(e,t){try{let n=JSON.parse(w.textDecoder.decode(t));return this.tryHandleWebRtcApplicationRouteProofPayload(n,e)}catch{return false}}tryHandleWebRtcApplicationRouteProofPayload(e,t){if(!this.isWebRtcApplicationRouteProofFrame(e))return false;if(!t)return this.traceLifecycle("webrtc-route-proof-ignored",{reason:"missing-webrtc-transport-context",negotiationId:e.negotiationId,probeId:e.probeId,role:e.role}),true;if(this._isClosed||this.webrtcTransport!==t||this.upgradeState!=="upgraded")return this.traceLifecycle("webrtc-route-proof-ignored",{reason:"stale-transport",negotiationId:e.negotiationId,probeId:e.probeId,role:e.role,activeNegotiationId:this.activeNegotiationId}),true;if(e.role==="probe")return this.sendWebRtcApplicationRouteProofFrame(t,{type:"#openrtc-webrtc-route-proof",version:1,role:"ack",negotiationId:e.negotiationId,probeId:e.probeId}).catch(i=>{c$1("[Connection] WebRTC application route proof ACK failed",{connectionId:this.id,remoteNodeId:this.remoteNodeId,negotiationId:e.negotiationId,probeId:e.probeId,error:i});}),true;if(this.currentWebRtcNegotiationId(t)!==e.negotiationId)return this.traceLifecycle("webrtc-route-proof-ignored",{reason:"stale-negotiation",negotiationId:e.negotiationId,probeId:e.probeId,role:e.role,activeNegotiationId:this.activeNegotiationId}),true;let n=this.pendingWebRtcApplicationRouteProof;return n&&n.transport===t&&n.negotiationId===e.negotiationId&&n.probeId===e.probeId?(this.completeWebRtcApplicationRouteProofAck(n),true):(this.traceLifecycle("webrtc-route-proof-ignored",{reason:"unexpected-ack",negotiationId:e.negotiationId,probeId:e.probeId,activeNegotiationId:this.activeNegotiationId,expectedProbeId:n?.probeId??null}),true)}isWebRtcApplicationRouteProofFrame(e){if(!e||typeof e!="object")return false;let t=e;return t.type==="#openrtc-webrtc-route-proof"&&t.version===1&&(t.role==="probe"||t.role==="ack")&&typeof t.probeId=="string"&&t.probeId.length>0&&t.probeId.length<=w.WEBRTC_APPLICATION_ROUTE_PROOF_MAX_ID_LENGTH&&typeof t.negotiationId=="string"&&t.negotiationId.length>0&&t.negotiationId.length<=w.WEBRTC_APPLICATION_ROUTE_PROOF_MAX_ID_LENGTH}startWebRtcApplicationRouteProbe(e$1,t){if(this.webRtcApplicationRouteProbeInFlight||this._isClosed||this.webrtcTransport!==e$1||this.upgradeState!=="upgraded"||this.isWebRtcApplicationRouteReadyForTransport(e$1))return;let n=this.currentWebRtcNegotiationId(e$1);if(!n){this.traceLifecycle("webrtc-application-route-probe-deferred",{reason:t,skipReason:"missing-negotiation-id"});return}if(!this.options.applicationCrypto){this.notifyWebRtcApplicationRouteMissing("webrtc-heartbeat-before-crypto");return}let i=this.createWebRtcApplicationRouteProofId(),o={transport:e$1,negotiationId:n,probeId:i,reason:t,timer:null,cancelled:false};o.timer=setTimeout(()=>{this.cancelWebRtcApplicationRouteProof(o,"timeout"),this.traceLifecycle("webrtc-application-route-probe-deferred",{reason:t,negotiationId:n,probeId:i,skipReason:"ack-timeout"});},w.WEBRTC_APPLICATION_ROUTE_PROOF_TIMEOUT_MS),this.pendingWebRtcApplicationRouteProof=o,this.webRtcApplicationRouteProbeInFlight=true,this.traceLifecycle("webrtc-application-route-probe-start",{reason:t,negotiationId:n,probeId:i}),(async()=>{for(let s of w.WEBRTC_APPLICATION_ROUTE_PROOF_DELAYS_MS){if(!this.isCurrentWebRtcApplicationRouteProof(o)||this.isWebRtcApplicationRouteReadyForTransport(e$1)||s>0&&(await e(s),!this.isCurrentWebRtcApplicationRouteProof(o)||this.isWebRtcApplicationRouteReadyForTransport(e$1)))return;try{await this.sendWebRtcApplicationRouteProofFrame(e$1,{type:"#openrtc-webrtc-route-proof",version:1,role:"probe",negotiationId:n,probeId:i},{requireLocalNegotiation:!0});}catch(a){if(!this.isCurrentWebRtcApplicationRouteProof(o))return;c$1("[Connection] WebRTC application route proof send failed",{connectionId:this.id,remoteNodeId:this.remoteNodeId,negotiationId:n,probeId:i,error:a});}}})().finally(()=>{this.pendingWebRtcApplicationRouteProof===o&&(this.webRtcApplicationRouteProbeInFlight=false);});}async sendIrohHeartbeatPong(e){if(e.byteLength<16||!this.writer)return;let t=new DataView(e.buffer,e.byteOffset,e.byteLength),n=t.getBigUint64(0,false),i=t.getBigInt64(8,false),o=BigInt(Date.now()),s=new ArrayBuffer(29),a=new DataView(s);a.setUint32(0,25,false),a.setUint8(4,4),a.setBigUint64(5,n,false),a.setBigInt64(13,i,false),a.setBigInt64(21,o,false);let c=this.writeMutex,d;this.writeMutex=new Promise(l=>{d=l;});try{await c,this.writer&&await this.writer.write(new Uint8Array(s));}catch{}finally{d();}}onWebRtcHeartbeatHealth(e){this.webrtcHealthListeners.push(e);}onIrohHeartbeatHealth(e){this.irohHealthListeners.push(e);}reportTransportStatusIfChanged(){if(this._isClosed)return;let{activeTransport:e,parallelTransport:t}=this.getTransportStatus(),n=`${e}:${t??""}`;this.lastReportedTransportStatus!==n&&this.pendingTransportStatusReport?.fingerprint!==n&&(this.pendingTransportStatusReport={fingerprint:n,status:{activeTransport:e,parallelTransport:t??null},retryCount:0},this.drainTransportStatusReports());}drainTransportStatusReports(){this.transportStatusReportInFlight||this._isClosed||(this.transportStatusReportInFlight=true,(async()=>{for(;!this._isClosed&&this.pendingTransportStatusReport;){let e=this.pendingTransportStatusReport;if(this.pendingTransportStatusReport=null,this.lastReportedTransportStatus===e.fingerprint)continue;let t=true;try{t=await this.options.onTransportStatusChange?.(e.status)!==!1;}catch(o){t=false,c$1("[Connection] Transport status projection failed",{connectionId:this.id,remoteNodeId:this.remoteNodeId,...e.status,error:o});}if(this._isClosed)return;if(t){this.lastReportedTransportStatus=e.fingerprint;continue}let n=this.getTransportStatus(),i=`${n.activeTransport}:${n.parallelTransport??""}`;i===e.fingerprint&&!this.pendingTransportStatusReport&&e.retryCount<1&&(this.pendingTransportStatusReport={fingerprint:i,status:{activeTransport:n.activeTransport,parallelTransport:n.parallelTransport??null},retryCount:e.retryCount+1},await Promise.resolve());}})().finally(()=>{this.transportStatusReportInFlight=false,!this._isClosed&&this.pendingTransportStatusReport&&this.drainTransportStatusReports();}));}reportApplicationRouteReady(e){if(this._isClosed||!this.isWebRtcApplicationRouteReady())return;let t=Date.now();if(e!=="webrtc-route-ready"&&this.lastApplicationRouteReadyReportAt!==null&&t-this.lastApplicationRouteReadyReportAt<1e3)return;this.lastApplicationRouteReadyReportAt=t;let{activeTransport:n,parallelTransport:i}=this.getTransportStatus();this.options.onApplicationRouteReady?.({connectionId:this.id,remoteNodeId:this.remoteNodeId,activeTransport:n,parallelTransport:i,reason:e});}getTransportStatus(){let e=this.transportType;return {activeTransport:e,parallelTransport:this.resolveParallelTransport(e)}}getLatencySnapshot(){let e=this.webrtcHeartbeat?.latencyMs??null;if(e===null)return {};let t={},{activeTransport:n,parallelTransport:i}=this.getTransportStatus();for(let o of [n,i])o==="webrtc-lan"?t.webrtcLan=e:o==="webrtc-turn"?t.webrtcTurn=e:o==="webrtc"&&(t.webrtc=e);return t}resolveParallelTransport(e){if(this._isClosed)return null;let t$1=q$2(e);return !t$1&&this.writer||!t$1&&t(e)&&this.hasRecoverableBasePath()?"iroh-relay":t$1&&this.isWebRtcDataChannelOpen()?this.webRtcTransportLabel():null}setNativeSignalSender(e){this.nativeSignalSender=e;}traceLifecycle(e,t={}){let n={event:e,connectionId:this.id,localNodeId:this.localNodeId,remoteNodeId:this.remoteNodeId,upgradeState:this.upgradeState,upgradeRequested:this.upgradeRequested,upgradeAttemptActive:this.upgradeAttemptActive,upgradeRetryCount:this.upgradeRetryCount,activeNegotiationId:this.activeNegotiationId,preferredWebRtcRole:this.preferredWebRtcRole,hasWriter:!!this.writer,hasNativeSignalSender:!!this.nativeSignalSender,isClosed:this._isClosed,...t};c$1("[OpenRTC][lifecycle]",n);try{c$1(`[OpenRTC][lifecycle-json] ${JSON.stringify(n)}`);}catch{}}getControlFrameMode(){return this.options.controlFrameMode??"typed"}async sendNativeControlEnvelope(e){return this.getControlFrameMode()!=="native-main"||!this.nativeSignalSender?false:(await this.nativeSignalSender(e),true)}useNativeControl(e){this.options={...this.options,controlFrameMode:"native-main"},this.nativeSignalSender=e,this.traceLifecycle("native-main-control-route-promoted");}hasRequiredApplicationCrypto(){return this.options.requireApplicationCrypto!==true||!!this.options.applicationCrypto}clearWebRtcApplicationRouteReady(){this.webRtcApplicationRouteReadyTransport=null,this.webRtcApplicationRouteReadyNegotiationId=null;}isCurrentWebRtcTransportApplicationRouteReady(){return !!this.webrtcTransport&&this.isWebRtcApplicationRouteReadyForTransport(this.webrtcTransport)}isWebRtcApplicationRouteReadyForTransport(e){return this.webRtcApplicationRouteReadyTransport===e&&this.webRtcApplicationRouteReadyNegotiationId===(e.getNegotiationId?.()??this.activeNegotiationId)}markWebRtcApplicationRouteReady(e){if(this.isWebRtcApplicationRouteReadyForTransport(e)||!this.hasRequiredApplicationCrypto()){this.hasRequiredApplicationCrypto()||this.traceLifecycle("webrtc-route-promotion-skipped",{reason:"missing-application-crypto",negotiationId:e.getNegotiationId?.()??this.activeNegotiationId});return}if(this.webrtcTransport!==e){this.traceLifecycle("webrtc-route-promotion-skipped",{reason:"stale-transport",negotiationId:e.getNegotiationId?.()??null,activeNegotiationId:this.activeNegotiationId});return}this.webRtcApplicationRouteReadyTransport=e,this.webRtcApplicationRouteReadyNegotiationId=e.getNegotiationId?.()??this.activeNegotiationId,this.negotiationSwitchCount=0,this.nativeNegotiationSwitchCount=0,this.upgradeReDriveCount=0,this.clearUpgradeReDriveTimer(),this.traceLifecycle("webrtc-application-route-ready",{negotiationId:this.webRtcApplicationRouteReadyNegotiationId}),this.reportTransportStatusIfChanged(),this.refreshWebRtcCandidatePairObservation(e),this.reportApplicationRouteReady("webrtc-route-ready");}isWebRtcApplicationRouteReady(){return this.isCurrentWebRtcTransportApplicationRouteReady()&&this.upgradeState==="upgraded"&&!!this.webrtcTransport&&this.hasRequiredApplicationCrypto()}isMoQApplicationRouteReady(){let e=this.options.transportContext;return !this._isClosed&&!!e&&e.isMoQReady()&&this.peerMoQReady&&this.isMoQDataRouteReady(e)&&e.isMoQApplicationRouteProven?.()===true&&this.hasRequiredApplicationCrypto()}isMoQDataRouteReady(e){return typeof e.isMoQDataReady=="function"?e.isMoQDataReady():true}async sendInternalSignal(e){let t=e&&(e.transport==="webrtc"||!e.transport)?{...e,transport:"webrtc",negotiationId:this.normalizeNegotiationId(e.negotiationId)??this.activeNegotiationId??void 0}:e,n={type:"#pluto-signal",content:t};if(this.getControlFrameMode()==="native-main"){if(this.nativeSignalSender)try{await this.nativeSignalSender(n),d$2("[Connection] Sent internal signal via native sender",{connectionId:this.id,remoteNodeId:this.remoteNodeId,signalType:t?.type??null});return}catch(i){console.warn("[Connection] Native signal sender failed, falling back to own native-main stream",{connectionId:this.id,remoteNodeId:this.remoteNodeId,signalType:t?.type??null,error:i});}if(this.writer&&typeof this.sendRawIrohFrame=="function")try{let i=new TextEncoder().encode(JSON.stringify(n)),o=new Uint8Array(1+i.byteLength);o[0]=0,o.set(i,1);let s=new ArrayBuffer(4+o.byteLength),a=new DataView(s),c=new Uint8Array(s);a.setUint32(0,o.byteLength,!1),c.set(o,4),await this.sendRawIrohFrame(c),d$2("[Connection] Sent internal signal over own native-main stream",{connectionId:this.id,remoteNodeId:this.remoteNodeId,signalType:t?.type??null});return}catch(i){console.warn("[Connection] Own native-main stream signal send failed; falling back to typed iroh",{connectionId:this.id,remoteNodeId:this.remoteNodeId,signalType:t?.type??null,error:i});}}try{if((t?.type==="sdp"||t?.type==="candidate"||t?.type==="renegotiate")&&c$1("[Connection][WebRTC][signal][send]",{connectionId:this.id,remoteNodeId:this.remoteNodeId,negotiationId:t?.negotiationId??null,signalType:t?.type??null,sdpType:t?.sdp?.type??null,hasSdp:!!t?.sdp?.sdp,hasCandidate:!!t?.candidate}),this.writer&&typeof this.sendRawIrohFrame=="function"){let i=new TextEncoder().encode(JSON.stringify(n)),o=new Uint8Array(1+i.byteLength);o[0]=0,o.set(i,1);let s=new ArrayBuffer(4+o.byteLength),a=new DataView(s),c=new Uint8Array(s);a.setUint32(0,o.byteLength,!1),c.set(o,4),await this.sendRawIrohFrame(c),d$2("[Connection] Sent internal signal over native-main iroh frame",{connectionId:this.id,remoteNodeId:this.remoteNodeId,signalType:t?.type??null});return}await this.sendTypedOnTransport("iroh",0,n,{requireApplicationCrypto:!1}),d$2("[Connection] Sent internal signal over iroh (typed-frame fallback)",{connectionId:this.id,remoteNodeId:this.remoteNodeId,signalType:t?.type??null});}catch(i){throw console.warn("[Connection] Failed to send internal signal over iroh",{connectionId:this.id,remoteNodeId:this.remoteNodeId,signalType:t?.type??null,error:i}),i}}receiveInternalSignal(e){this._isClosed||!e||typeof e!="object"||this.handleInternalSignal({type:"#pluto-signal",content:e});}handleInternalSignal(e){if(!(e.content&&(e.content.transport==="webrtc"||!e.content.transport)))return;let n=e.content,i=typeof n?.type=="string"?n.type:null,o=n?.sdp&&typeof n.sdp=="object"&&typeof n.sdp.type=="string"?n.sdp.type:null,s=i==="sdp"&&o==="offer",a=this.normalizeNegotiationId(n?.negotiationId),c=i==="renegotiate"&&!!a&&a!==this.activeNegotiationId&&a.startsWith(`conn-${this.id}-`)&&this.getDeterministicWebRtcRole()==="responder";if((i==="sdp"||i==="candidate"||i==="renegotiate")&&c$1("[Connection][WebRTC][signal][recv]",{connectionId:this.id,remoteNodeId:this.remoteNodeId,negotiationId:a??null,signalType:i,sdpType:o,hasSdp:!!n?.sdp?.sdp,hasCandidate:!!n?.candidate,upgradeState:this.upgradeState}),this.upgradeState==="failed"&&this.upgradeRetryTimer){if(this.inboundSignalRetryBypassUsed)return;this.inboundSignalRetryBypassUsed=true,this.clearUpgradeRetryTimer();}if(i==="renegotiate"){let I=this.lastWebRtcHeartbeatOkAt===null?null:Date.now()-this.lastWebRtcHeartbeatOkAt,b=this.lastWebRtcDataChannelOpenAt===null?null:Date.now()-this.lastWebRtcDataChannelOpenAt,P=I!==null&&I<=w.WEBRTC_RENEGOTIATE_LIVENESS_WINDOW_MS||this.isWebRtcDataChannelOpen()&&b!==null&&b<=w.WEBRTC_RENEGOTIATE_LIVENESS_WINDOW_MS;if(this.isWebRtcDataChannelOpen()||this.upgradeState==="upgraded"){let D=!!a&&a!==this.activeNegotiationId&&a.startsWith("conn-")&&!a.startsWith(`conn-${this.id}-`)&&this.getDeterministicWebRtcRole()==="responder";if(P&&!D){c$1("[Connection] Ignoring WebRTC renegotiate request; route is provably live",{connectionId:this.id,remoteNodeId:this.remoteNodeId,signalNegotiationId:a,activeNegotiationId:this.activeNegotiationId,heartbeatSilenceMs:I,dataChannelOpenForMs:b});return}c$1("[Connection] Honoring WebRTC renegotiate by tearing down the current route",{connectionId:this.id,remoteNodeId:this.remoteNodeId,signalNegotiationId:a,activeNegotiationId:this.activeNegotiationId,priorState:this.upgradeState,heartbeatSilenceMs:I,dataChannelOpenForMs:b,reason:D?"fresh-remote-generation":"stale-route"}),this.clearUpgradeRetryTimer(),this.upgradeAttemptActive=false,this.upgradeRetryCount=0,this.upgradeTerminalFailure=false,this.pendingSignals=[],this.stopWebRtcHeartbeat(),this.teardownWebRTCTransport(D?"inbound-renegotiate-fresh-generation":"inbound-renegotiate-stale-route"),this.setUpgradeState("none");}else if(this.upgradeState==="upgrading"&&this.webrtcTransport)if(!!a&&a!==this.activeNegotiationId&&a.startsWith("native-")){if(this.nativeNegotiationSwitchCount>=w.MAX_NATIVE_NEGOTIATION_SWITCHES){c$1("[Connection] Ignoring fresh native WebRTC renegotiate: negotiation switch budget exhausted",{connectionId:this.id,remoteNodeId:this.remoteNodeId,signalNegotiationId:a,activeNegotiationId:this.activeNegotiationId,switchBudget:w.MAX_NATIVE_NEGOTIATION_SWITCHES});return}this.nativeNegotiationSwitchCount+=1,c$1("[Connection] Honoring fresh native WebRTC renegotiate during in-flight upgrade",{connectionId:this.id,remoteNodeId:this.remoteNodeId,signalNegotiationId:a,activeNegotiationId:this.activeNegotiationId,switchCount:this.nativeNegotiationSwitchCount}),this.clearUpgradeRetryTimer(),this.upgradeAttemptActive=false,this.upgradeRetryCount=0,this.upgradeTerminalFailure=false,this.pendingSignals=[],this.stopWebRtcHeartbeat(),this.teardownWebRTCTransport("inbound-native-renegotiate-while-upgrading"),this.setUpgradeState("none"),this.preferredWebRtcRole=this.getDeterministicWebRtcRole();}else if(c)c$1("[Connection] Adopting fresh initiator renegotiate while responder upgrade is in flight",{connectionId:this.id,remoteNodeId:this.remoteNodeId,signalNegotiationId:a,activeNegotiationId:this.activeNegotiationId,switchCount:this.negotiationSwitchCount});else {c$1("[Connection] Ignoring WebRTC renegotiate request while an upgrade is already in flight",{connectionId:this.id,remoteNodeId:this.remoteNodeId,signalNegotiationId:a,activeNegotiationId:this.activeNegotiationId});return}}let d=!!a&&!!this.activeNegotiationId&&a!==this.activeNegotiationId;if(d&&(i==="sdp"||i==="candidate")&&(this.isWebRtcDataChannelOpen()||this.upgradeState==="upgraded")){c$1("[Connection] Ignoring delayed WebRTC signal for a non-active generation",{connectionId:this.id,remoteNodeId:this.remoteNodeId,signalType:i,signalNegotiationId:a,activeNegotiationId:this.activeNegotiationId});return}let l=i==="sdp"&&s||i==="renegotiate"&&(this.upgradeState!=="upgrading"||c)&&this.upgradeState!=="upgraded";if(d&&!l){c$1("[Connection] Ignoring stale WebRTC signal from a previous negotiation",{connectionId:this.id,remoteNodeId:this.remoteNodeId,signalType:i,signalNegotiationId:a,activeNegotiationId:this.activeNegotiationId});return}let p=!!this.activeNegotiationId?.startsWith("native-"),u=!!a?.startsWith("native-"),h=s&&!!a?.startsWith(`conn-${this.id}-`);if(d&&l&&this.upgradeState==="upgrading"&&this.preferredWebRtcRole==="responder"&&p&&h){c$1("[Connection] Ignoring reflected WebRTC offer during active native negotiation",{connectionId:this.id,remoteNodeId:this.remoteNodeId,signalNegotiationId:a,activeNegotiationId:this.activeNegotiationId});return}let m=s&&!!a?.startsWith(`conn-${this.id}-`),f=i==="renegotiate"&&!!a?.startsWith(`conn-${this.id}-`);if(d&&l&&m&&!p&&this.getDeterministicWebRtcRole()==="initiator"&&(this.upgradeState==="upgrading"||this.upgradeAttemptActive)){c$1("[Connection] Ignoring competing inbound WebRTC offer as glare-impolite initiator",{connectionId:this.id,remoteNodeId:this.remoteNodeId,signalNegotiationId:a,activeNegotiationId:this.activeNegotiationId});return}let v=(m||f)&&!u,y=s&&u;if(d&&l&&(v&&this.negotiationSwitchCount>=w.MAX_NEGOTIATION_SWITCHES||y&&this.nativeNegotiationSwitchCount>=w.MAX_NATIVE_NEGOTIATION_SWITCHES)){c$1("[Connection] Ignoring competing inbound WebRTC offer: negotiation switch budget exhausted",{connectionId:this.id,remoteNodeId:this.remoteNodeId,signalNegotiationId:a,activeNegotiationId:this.activeNegotiationId,switchBudget:y?w.MAX_NATIVE_NEGOTIATION_SWITCHES:w.MAX_NEGOTIATION_SWITCHES});return}d&&l&&(v&&(this.negotiationSwitchCount+=1),y&&(this.nativeNegotiationSwitchCount+=1),c$1("[Connection] Switching to a fresh inbound WebRTC negotiation",{connectionId:this.id,remoteNodeId:this.remoteNodeId,priorNegotiationId:this.activeNegotiationId,nextNegotiationId:a,priorState:this.upgradeState,signalType:i,switchCount:this.negotiationSwitchCount,budgetedNegotiationSwitch:v,nativeSwitchCount:this.nativeNegotiationSwitchCount,budgetedNativeNegotiationSwitch:y}),this.clearUpgradeRetryTimer(),this.upgradeAttemptActive=false,this.upgradeRetryCount=0,this.upgradeTerminalFailure=false,this.pendingSignals=[],this.stopWebRtcHeartbeat(),this.teardownWebRTCTransport("inbound-negotiation-switch")),a&&(!this.activeNegotiationId||d)&&(this.activeNegotiationId=a);let C=!this.webrtcTransport||this.upgradeState==="failed"||d&&this.upgradeState!=="upgrading";if(l&&C&&this.options.rtcConfig&&!this._isClosed){c$1("[Connection] Auto-requesting WebRTC upgrade from incoming signal",{connectionId:this.id,remoteNodeId:this.remoteNodeId,currentState:this.upgradeState,signalType:i,sdpType:o,signalNegotiationId:a,preferredRole:s?"responder":this.preferredWebRtcRole}),s?this.preferredWebRtcRole="responder":i==="renegotiate"&&a?.startsWith("native-")&&(this.preferredWebRtcRole=this.getDeterministicWebRtcRole()),this.upgradeRequested=true,this.upgradeTerminalFailure=false,this.pendingSignals=[n],this.attemptUpgrade(a);return}n.transport||(n.transport="webrtc"),this.webrtcTransport?.handleSignalingMessage?this.webrtcTransport.handleSignalingMessage(n):(!a||!this.activeNegotiationId||a===this.activeNegotiationId)&&this.pendingSignals.push(n);}createNegotiationId(){return `conn-${this.id}-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`}getDeterministicWebRtcRole(){return this.localNodeId>this.remoteNodeId?"initiator":"responder"}normalizeNegotiationId(e){if(typeof e!="string")return null;let t=e.trim();return t.length>0?t:null}};w.textDecoder=new TextDecoder("utf-8",{fatal:true}),w.textEncoder=new TextEncoder,w.UPGRADE_RETRY_DELAY_MS=1e3,w.MAX_UPGRADE_RETRIES=5,w.UPGRADE_REDRIVE_DELAYS_MS=[5e3,1e4,15e3],w.WEBRTC_DISCONNECTED_GRACE_MS=4e3,w.MAX_PENDING_MESSAGES=256,w.DEFAULT_APPLICATION_CRYPTO_WAIT_MS=1e4,w.WEBRTC_UPGRADE_ATTEMPT_TIMEOUT_MS=a$3+3e3,w.MAX_PENDING_ENCRYPTED_APPLICATION_PAYLOADS=256,w.WEBRTC_APPLICATION_ROUTE_PROOF_TIMEOUT_MS=6500,w.WEBRTC_APPLICATION_ROUTE_PROOF_DELAYS_MS=[0,250,750,1500,3e3],w.WEBRTC_APPLICATION_ROUTE_PROOF_MAX_ID_LENGTH=256,w.WEBRTC_RENEGOTIATE_LIVENESS_WINDOW_MS=12e3,w.MAX_NEGOTIATION_SWITCHES=6,w.MAX_NATIVE_NEGOTIATION_SWITCHES=16,w.FOREGROUND_PROBE_TIMEOUT_MS=2e3;var ie=w;async function oe(r,e,t){await l$2(r,e)&&c$1("[Client][CONNECT] Closed unused bi stream after adopting existing connection",{remoteNodeId:t??null,reason:e});}async function ir(r){try{await r.refreshApplicationRouteHandshake(r.connection,r.reason,{forceReciprocal:!0});return}catch(e){let t=r.wasmClient.is_remote_admitted;if(!r.hasCompoundTicketToken||typeof t!="function")throw e;let n;try{n=await t.call(r.wasmClient,r.ticket),r.assertActive();}catch{throw e}if(n)throw e;c$1("[Client][AUTH] repairing admission after physical replacement",{nodeId:r.nodeId,connectionId:r.connection.id,reason:r.reason}),await r.representTicket(`${r.reason}:current-generation-admission-repair`),r.assertActive(),await r.refreshApplicationRouteHandshake(r.connection,`${r.reason}:after-current-generation-admission-repair`,{forceReciprocal:true});}}function Ne(){return new Error("Transport-only ticket-only channels do not expose a main message stream.")}var hi=class extends ie{constructor(t){let n=new WritableStream({write(){throw Ne()}}).getWriter(),i=new ReadableStream().getReader();super(t.connectionId,t.localNodeId,t.remoteNodeId,n,i,{...t.options,controlFrameMode:"native-main",hasBaseApplicationStream:false});this.input=t;this.transportDisconnectStarted=false;}async send(){throw Ne()}async sendMedia(){throw Ne()}async sendControl(){throw Ne()}async sendOnTransport(t,n){throw Ne()}async sendRawIrohFrame(){throw Ne()}async disconnect(){await super.disconnect(),!this.transportDisconnectStarted&&(this.transportDisconnectStarted=true,await this.disconnectNodeTransportBestEffort());}async disconnectForMainStreamReplacement(){await super.disconnect();}async disconnectNodeTransportBestEffort(){try{await this.input.disconnectNodeTransport(this.remoteNodeId);}catch{}}};function or(r){return new hi(r)}var Dt=class{constructor(e,t){this.ctx=e;this.deps=t;this.disposed=false;this.ctx.registerDisposer(()=>this.dispose());}dispose(){this.disposed=true;}async connect(e,t=2e4,n,i,o){if(this.assertActive(),await this.deps.ensureWasmRuntimeForP2P(),this.assertActive(),!e||!e.trim())throw new Error("connect requires a non-empty endpoint ticket");let s=e.trim(),{irohTicket:a,tokenSuffix:c}=ee(s),d=this.deps.getWasmClient(),l;try{l=await d.endpoint_id_from_ticket(a);}catch(T){throw new Error(`connect requires a valid endpoint ticket: ${T?.message||T}`)}this.assertActive();let p=null;if(c){let T=se(a,c);typeof T?.t=="string"&&(p=T.t,this.deps.rememberRouteRepairTokenForNode(l,T.t,c));}let u=this.deps.getDeterministicConnectionId(l),h=this.deps.getRegisteredChannel(i??null),m=this.deps.isTransportOnlyChannel(i);c$1("[Client][CONNECT] resolved ticket target",{nodeId:l,connectionId:u,channelId:i??null,registeredChannel:h?{id:h.id,readiness:h.readiness,promotionPolicy:h.promotionPolicy,signalingPolicy:h.signalingPolicy}:null,transportOnlyChannel:m,hasCompoundTicketToken:!!p});let f=this.ctx.registry.get(u);if(f&&!p){let T=this.deps.resolveExpectedDeviceIdForSessionTokenScope(n,o?.approvedScope??null,p,f);return T&&this.deps.initializeConnectionTrust(f,T),await this.deps.refreshApplicationRouteHandshake(f,"connect-existing"),this.assertActive(),f}let v=c?se(a,c):null,y=o?.approvedScope??null;!y&&typeof v?.s=="string"&&v.s.trim()&&(y=v.s.trim());let C=async T=>{d$2(`Initiating managed transport dial to ${l} (${T})...`);let M=await this.deps.ensureWasmManagedTransport(s,n??null,{skipIfConnected:o?.admissionAlreadyPresented===true,admissionAlreadyPresented:o?.admissionAlreadyPresented===true,timeoutMs:t});if(this.assertActive(),M.approvedScope)y=M.approvedScope,this.deps.setSessionTokenApprovedScope(u,M.approvedScope);else if(p&&!y){await this.schedulePeerReconciliationBestEffort("managed-dial-scope-lookup"),this.assertActive();let L=this.deps.getSessionTokenApprovedScope(u);if(typeof L=="string"&&L.trim())y=L.trim();else {let X=this.deps.getPeerState(n??l)?.scopes?.[0];typeof X=="string"&&X.trim()&&(y=X.trim());}}},I=async(T,M)=>ir({connection:T,reason:M,nodeId:l,ticket:s,hasCompoundTicketToken:!!p,wasmClient:d,assertActive:()=>this.assertActive(),refreshApplicationRouteHandshake:(L,W,X)=>this.deps.refreshApplicationRouteHandshake(L,W,X),representTicket:C});try{await C("initial");}catch(T){if(this.deps.isLocalIrohRuntimeNotInitializedError(T)){let M=await this.deps.recoverLocalIrohRuntime("connect-managed-dial");if(this.assertActive(),!M)throw new Error(`Failed to initiate managed transport dial to ${l}: ${T?.message||T}`);try{await C("after-local-runtime-recovery");}catch(L){throw new Error(`Failed to initiate managed transport dial to ${l} after local Iroh runtime recovery: ${L?.message||L}`)}}else throw T}if(this.assertActive(),p){let T=y??o?.approvedScope??null,M=this.ctx.registry.get(u);if(M&&!M.isClosed){let L=this.deps.resolveExpectedDeviceIdForSessionTokenScope(n,T,p,M);this.deps.assignConnectionChannel(M,i),this.deps.initializeConnectionTrust(M,L),L&&this.deps.bindConnectionDeviceIdInRust(M,L),this.deps.approveSessionTokenNode(l),this.deps.approveSessionTokenConnection(M.id),this.deps.applySessionTokenTrustApproval(M,T,"dialer-compound-ticket-existing-connection"),this.deps.announceConnectionWhenStable(M),c$1("[Client][AUTH] adopted token-approved existing connection",{nodeId:l,connectionId:M.id,localNodeId:M.localNodeId,remoteNodeId:M.remoteNodeId,approvalScope:y||null});let W=M.disconnectForMainStreamReplacement;if(!m&&typeof W=="function")this.deps.cleanupReplacedConnection(M.id),await W.call(M),this.assertActive();else return await I(M,"dialer-compound-ticket-existing-connection"),this.assertActive(),M}}if(m){let T;T=or({connectionId:u,localNodeId:this.ctx.localNodeId,remoteNodeId:l,options:{rtcConfig:this.deps.getRTCConfig(),transportContext:this.deps.createTransportContext(l),applicationCrypto:this.deps.getOptions()?.applicationCrypto,requireApplicationCrypto:this.deps.shouldNegotiateApplicationKeyAgreement(),onTransportStatusChange:W=>this.deps.handleConnectionTransportStatus(T,W.activeTransport,W.parallelTransport),onApplicationRouteReady:W=>{this.deps.handleConnectionApplicationRouteReady(T,W);},onApplicationRouteMissing:W=>{this.deps.handleConnectionApplicationRouteMissing(u,W);}},disconnectNodeTransport:W=>this.deps.disconnectNodeTransport(W)});let M=y??o?.approvedScope??null,L=this.deps.resolveExpectedDeviceIdForSessionTokenScope(n,M,p,T);return this.deps.assignConnectionChannel(T,i),this.deps.initializeConnectionTrust(T,L),this.deps.registerConnection(T),L&&this.deps.bindConnectionDeviceIdInRust(T,L),p&&(this.deps.approveSessionTokenNode(l),this.deps.approveSessionTokenConnection(T.id),this.deps.applySessionTokenTrustApproval(T,M,"dialer-compound-ticket-transport-only")),this.deps.announceConnectionWhenStable(T),c$1("[Client][AUTH] using transport-only channel connection",{nodeId:l,connectionId:T.id,channelId:i??null,signalingMode:this.deps.getOptions().signalingMode??"hosted",hasCompoundTicketToken:!!p}),T}let b=await this.openMainBiStream(l,t);this.disposed&&(await oe(b,"dial-coordinator-disposed-after-open",l),this.assertActive());let P=this.ctx.registry.get(u);if(P&&!P.isClosed){let T=y??o?.approvedScope??null,M=this.deps.resolveExpectedDeviceIdForSessionTokenScope(n,T,p,P);return await oe(b,"late-dial-adopted-existing-connection",l),this.deps.assignConnectionChannel(P,i),this.deps.initializeConnectionTrust(P,M),M&&this.deps.bindConnectionDeviceIdInRust(P,M),p&&(this.deps.approveSessionTokenNode(l),this.deps.approveSessionTokenConnection(P.id),this.deps.applySessionTokenTrustApproval(P,T,"dialer-compound-ticket-late-existing-connection")),this.deps.announceConnectionWhenStable(P),c$1("[Client][CONNECT] adopted existing connection after async dial completed",{nodeId:l,connectionId:P.id,channelId:i??null,approvalScope:y||null,upgradeState:typeof P.getUpgradeState=="function"?P.getUpgradeState():null}),await I(P,"late-dial-adopted-existing-connection"),this.assertActive(),P}let A=this.deps.shouldUseNativeMainFramingForPeer(l,this.deps.resolveExpectedDeviceIdForSessionTokenScope(n,y??o?.approvedScope??null,p,null),!!p);A&&(await O(this.deps.writeNativeMainLabelHeaderOnBiStream(b,l),4e3,"writeNativeMainLabelHeaderOnBiStream"),this.disposed&&(await oe(b,"dial-coordinator-disposed-after-native-label",l),this.assertActive()));let S=this.createConnection({connId:u,nodeId:l,biStream:b,useNativeMainFraming:A});this.deps.assignConnectionChannel(S,i);let D=y??o?.approvedScope??null,_=this.deps.resolveExpectedDeviceIdForSessionTokenScope(n,D,p,S);if(this.deps.initializeConnectionTrust(S,_),this.disposed&&(await this.disconnectConnectionBestEffort(S),this.assertActive()),this.deps.registerConnection(S),_&&this.deps.bindConnectionDeviceIdInRust(S,_),p){await this.schedulePeerReconciliationBestEffort("compound-ticket-connect"),this.assertActive();let T=this.deps.getPeerState(S.id)??this.deps.getPeerState(l),M=this.deps.consumePendingSessionTokenTrustApproval(S.id);M.approved?this.deps.applySessionTokenTrustApproval(S,M.scope??D,"dialer-compound-ticket-pending"):T?.admissionState==="admitted"&&this.deps.applySessionTokenTrustApproval(S,D,"dialer-compound-ticket-rust-admitted"),c$1("[Client][AUTH] token-approved connection registered locally",{nodeId:l,connectionId:S.id,localNodeId:S.localNodeId,remoteNodeId:S.remoteNodeId,rustAdmissionState:T?.admissionState??null,pendingApproval:M.approved});}return this.deps.announceConnectionWhenStable(S),c$1("[Client][HANDSHAKE] sending hello (dial path)",{connectionId:S.id,remoteNodeId:S.remoteNodeId}),this.sendDialHelloInBackground(S),S}async connectPeer(e){this.assertActive();let t=e.scope??"persistent";if(!e.ticket)throw new Error("connectPeer requires a ticket.");c$1("[Client][connectPeer] starting",{scope:t,channelId:e.channelId??null,hasDeviceId:!!e.deviceId,ticketLength:e.ticket.length});let n=ee(e.ticket).tokenSuffix!==null;if(!n&&!this.deps.sessionTokenScopeAllowsDeviceBinding(t))throw new Error(`connectPeer requires a compound ticket with a session token for restricted scope '${t}'.`);if(e.keepManualDisconnect&&this.hasManualDisconnectProjection(e.deviceId))throw new Error(`connectPeer suppressed by manual disconnect for device ${e.deviceId}`);e.deviceId&&!n&&!e.keepManualDisconnect&&this.deps.clearManualDisconnectProjection(e.deviceId);let i=await this.connect(e.ticket,Math.max(1,e.timeoutMs??2e4),e.deviceId,e.channelId);this.assertActive();let o=this.deps.getSessionTokenApprovedScope(i.id),s=[...o?[o]:[],...this.deps.getPeerScopes(i.id)].filter((u,h,m)=>m.indexOf(u)===h),a=s.length>0?s:[t],d=s.length===0||a.some(u=>this.deps.sessionTokenScopeAllowsDeviceBinding(u))?e.deviceId:void 0,l=this.deps.resolvePromotionEligibility({connectionId:i.id,nodeId:i.remoteNodeId,deviceId:d??void 0}),p=d||i.remoteNodeId||i.deviceId||i.id;d&&n&&this.deps.clearManualDisconnectProjection(d),this.deps.hasRustPeerLifecycleProjection()?this.schedulePeerReconciliationInBackground("connect-peer"):this.deps.dispatchLiveConnectionProjection(i,{trustProjection:null,promotionEligible:l,peerId:p,deviceId:d,ticket:e.ticket,scopes:a,applicationRouteReady:this.deps.hasApplicationRouteForConnection(i),webRtcApplicationRouteReady:this.deps.isWebRtcApplicationRouteReadyForConnection(i)});for(let u of a)this.deps.addPeerScope(p,u);return i}hasManualDisconnectProjection(e){let t=typeof e=="string"?e.trim():"";if(!t)return false;let n=this.deps.getWasmClient();if(n&&typeof n.is_auto_connect_excluded=="function"&&n.is_auto_connect_excluded(t)===true)return true;let i=this.deps.getPeerState(t);if(!i)return false;if(i.manualDisconnect===true)return true;let o=i,s=[i.error,o.lastDisconnectReason].filter(a=>typeof a=="string"&&a.length>0).join(" ");return /manual disconnect/i.test(s)}async openMainBiStream(e$1,t){this.assertActive();let n=null,i=0,o=500,s=Math.ceil(t/o),a=this.deps.getWasmClient(),c=a.open_native_main_control_bi;if(typeof c!="function")throw new Error("[Client][NATIVE-MAIN] open_native_main_control_bi is unavailable on this WASM build; the admission and key-agreement control plane cannot use a protected application stream. Rebuild the OpenRTC WASM runtime.");for(;i<s;){this.assertActive();try{n=await O(c.call(a,e$1),2500,"wasmClient.open_native_main_control_bi"),this.disposed&&(await oe(n,"dial-coordinator-disposed-during-open",e$1),this.assertActive());break}catch(d){if(this.disposed)throw d;i++,await e(o);}}if(!n)throw new Error(`Failed to establish connection to ${e$1} after ${t} ms`);return n}assertActive(){if(this.disposed)throw new Error("Connection dial cancelled because the client was disposed.")}createConnection(e){let{connId:t,nodeId:n,biStream:i,useNativeMainFraming:o}=e,s;if(s=new ie(t,this.deps.getLocalNodeId(),n,i.send.getWriter(),i.recv.getReader(),{rtcConfig:this.deps.getRTCConfig(),transportContext:this.deps.createTransportContext(n),applicationCrypto:this.deps.getOptions()?.applicationCrypto,requireApplicationCrypto:this.deps.shouldNegotiateApplicationKeyAgreement(),controlFrameMode:o?"native-main":"typed",onTransportStatusChange:a=>this.deps.handleConnectionTransportStatus(s,a.activeTransport,a.parallelTransport),onApplicationRouteReady:a=>{this.deps.handleConnectionApplicationRouteReady(s,a);},onApplicationRouteMissing:a=>{this.deps.handleConnectionApplicationRouteMissing(t,a);}}),o&&this.deps.getWasmClient()){let a=this.deps.getWasmClient();s.setNativeSignalSender(async c=>{await this.deps.sendNativeSignalEnvelope(s,n,c,a);}),c$1("[Client][NATIVE-MAIN] Attached native signal sender to dial-path connection",{connectionId:s.id,remoteNodeId:n});}return s}sendDialHelloInBackground(e){let t=n=>{this.disposed||console.warn("[Client][TRUST] Failed to send outgoing handshake",{connectionId:e.id,remoteNodeId:e.remoteNodeId,error:n});};try{Promise.resolve(this.deps.sendTransportHandshake(e,"hello")).then(()=>{this.disposed||this.deps.requestProtectedWebRTCUpgradeIfInitiator(e,"protected-hello:dial");}).catch(t);}catch(n){t(n);}}schedulePeerReconciliationBestEffort(e){try{return Promise.resolve(this.deps.schedulePeerReconciliation(e)).catch(()=>[])}catch{return Promise.resolve([])}}schedulePeerReconciliationInBackground(e){if(!this.disposed)try{this.schedulePeerReconciliationBestEffort(e);}catch{}}disconnectConnectionBestEffort(e){try{return Promise.resolve(e.disconnect()).catch(()=>{})}catch{return Promise.resolve()}}};var Et=class{constructor(e){this.deps=e;this.connectionListeners=[];this.disconnectionListeners=[];this.announcedConnections=new Set;this.stabilityWaitEpochs=new Map;this.disposed=false;this.deps.registerDisposer(()=>this.dispose());}dispose(){this.disposed||(this.disposed=true,this.connectionListeners=[],this.disconnectionListeners=[],this.announcedConnections.clear(),this.stabilityWaitEpochs.clear());}findLiveConnectionForRemoteNode(e,t){let n=this.deps.registry.get(t);if(n&&!n.isClosed)return n;for(let i of this.deps.registry.values())if(i.remoteNodeId===e&&!i.isClosed)return i;return null}cleanupReplacedConnection(e){this.disposed||(this.deps.registry.delete(e),this.forgetAnnouncedConnection(e));}healOrphanTsConnection(e){if(this.disposed)return;let t=this.deps.registry.get(e);!t||t.isClosed||c$1("[Client][PEER-RECONCILE] observed orphan TS connection",{connectionId:e});}registerConnection(e){if(this.disposed)return;let t=this.deps.registry;t.clearLocalTerminalClose(e.id);let n=t.get(e.id);if(t.set(e.id,e),n&&n!==e&&!n.isClosed&&this.disconnectBestEffort(n),typeof e.setApplicationCrypto=="function"){let s=this.deps.resolveApplicationCryptoForPeer(e.remoteNodeId,e);s&&e.setApplicationCrypto(s);}this.flushPendingNativeMainHandshakesBestEffort(e.remoteNodeId,"connection-registered"),this.flushPendingNativeMainSignalsBestEffort(e.remoteNodeId,"connection-registered");let i=this.deps.getConnectionTrustState(e.id),o=i?.verifiedDeviceId??i?.expectedDeviceId??this.deps.getKnownDeviceIdByNodeId(e.remoteNodeId)??null;o?this.deps.bindConnectionDeviceIdInRust(e,o):this.lookupConnectionDeviceBindingInBackground(e),i?.verified&&o&&this.deps.retireSupersededConnections(e,o,"registered-trusted-replacement"),typeof e.onUpgradeStateChange=="function"&&e.onUpgradeStateChange(()=>{this.disposed||!t.has(e.id)||e.isClosed||this.deps.hasRustPeerLifecycleProjection()||this.deps.applyConnectionTrustProjection(e);}),this.deps.hasRustPeerLifecycleProjection()?this.schedulePeerReconciliationBestEffort("register-connection"):this.deps.applyConnectionTrustProjection(e),typeof e.reportTransportStatusIfChanged=="function"&&e.reportTransportStatusIfChanged(),typeof e.onWebRTCBinaryMessage=="function"&&e.onWebRTCBinaryMessage(s=>this.disposed?false:this.deps.maybeHandleWebRTCExplicitFileEnvelope(e,s)),e.onMessage(s=>{if(!this.disposed)try{Promise.resolve(this.deps.handleMessage(e,s)).catch(a=>{this.disposed||console.warn("[Client] connection message handler failed",{connectionId:e.id,remoteNodeId:e.remoteNodeId,error:a});});}catch(a){this.disposed||console.warn("[Client] connection message handler failed",{connectionId:e.id,remoteNodeId:e.remoteNodeId,error:a});}}),e.onDisconnect(()=>{if(this.disposed||(e.peerMoQReady=false,t.get(e.id)!==e))return;let s=this.deps.hasRustPeerLifecycleProjection();s||t.markLocalTerminalClose(e.id);let a=this.deps.getExistingPeerProjectionForDisconnect(e);t.delete(e.id),this.deps.cleanupConnectionState(e.id,s?"physical-route":"logical-terminal"),s?this.schedulePeerReconciliationBestEffort("connection-disconnect"):this.deps.dispatchLiveConnectionProjection(e,{trustProjection:null,promotionEligible:this.deps.resolvePromotionEligibility({connectionId:e.id,nodeId:e.remoteNodeId}),existingProjection:a,terminalTransportClose:true,applicationRouteReady:false,webRtcApplicationRouteReady:false}),this.announcedConnections.delete(e.id)&&this.emitDisconnection(e);});}announceConnectionWhenStable(e){let t=(this.stabilityWaitEpochs.get(e.id)??0)+1;this.stabilityWaitEpochs.set(e.id,t),(async()=>{if(this.disposed)return;let n=await this.waitForStableConnection(e);if(!this.disposed&&this.deps.registry.get(e.id)===e&&this.stabilityWaitEpochs.get(e.id)===t){if(!n){if(!e.isClosed){let i=this.deps.getConnectionTrustState(e.id);console.warn(`[Client] Suppressing unstable connection ${e.id}`,{deviceId:e.deviceId,upgradeState:e.getUpgradeState?.()??null,transportStatus:typeof e.getTransportStatus=="function"?e.getTransportStatus():null,trustRequired:i?.required??null,trustVerified:i?.verified??null,trustFailed:i?.failed??null,trustFailureReason:i?.failureReason??null});}return}this.announcedConnections.has(e.id)||(this.announcedConnections.add(e.id),this.emitConnection(e));}})();}async waitForStableConnection(e$1){if(this.disposed)return false;let t=this.deps.initializeConnectionTrust(e$1),n=false,i=false,o=this.deps.hasApplicationRouteForConnection(e$1),s=this.deps.allowsTransportOnlyStability(e$1),a=null,c=this.deps.getWasmClient(),d=c&&typeof c.wait_for_peer=="function"?c.wait_for_peer:null;if(d)try{let u=await d.call(c,e$1.deviceId,this.deps.stableTimeoutMs),h=e$1.getUpgradeState;if(a=typeof h=="function"?h.call(e$1):null,o=this.deps.hasApplicationRouteForConnection(e$1),u?.settledReady&&(!t.required||t.verified)&&(o||s))return !0;if(t.required&&t.failed)return console.warn("[Client][STABILITY] trust failed during settled-peer gate",{connectionId:e$1.id,deviceId:e$1.deviceId,settledReady:u?.settledReady??null,trustRequired:t.required,trustVerified:t.verified,trustFailed:t.failed,trustFailureReason:t.failureReason??null,upgradeState:a}),!1}catch{}let l=Date.now(),p=null;for(;Date.now()-l<this.deps.stableTimeoutMs;){if(this.disposed||e$1.isClosed||t.required&&t.failed)return false;let u=await this.deps.isCoreConnectionHealthy(e$1.deviceId);if(this.disposed)return false;let h=e$1.getUpgradeState;a=typeof h=="function"?h.call(e$1):null;let m=a==="upgraded";if(n=u,i=m,o=this.deps.hasApplicationRouteForConnection(e$1),u||m){if(p===null&&(p=Date.now()),Date.now()-p>=this.deps.stableWindowMs&&(!t.required||t.verified)&&(o||s))return true}else p=null;await e(this.deps.stablePollMs);}return console.warn("[Client][STABILITY] connection did not become stable before timeout",{connectionId:e$1.id,deviceId:e$1.deviceId,trustRequired:t.required,trustVerified:t.verified,trustFailed:t.failed,trustFailureReason:t.failureReason??null,lastCoreHealthy:n,lastUpgradedTransportHealthy:i,lastApplicationRouteReady:o,lastUpgradeState:a,transportStatus:typeof e$1.getTransportStatus=="function"?e$1.getTransportStatus():null}),false}onConnection(e){return this.disposed?()=>{}:(this.connectionListeners.push(e),()=>{this.connectionListeners=this.connectionListeners.filter(t=>t!==e);})}onDisconnection(e){return this.disposed?()=>{}:(this.disconnectionListeners.push(e),()=>{this.disconnectionListeners=this.disconnectionListeners.filter(t=>t!==e);})}isConnectionAnnounced(e){return this.announcedConnections.has(e)}forgetAnnouncedConnection(e){this.announcedConnections.delete(e);}emitConnection(e){for(let t of [...this.connectionListeners])try{t(e);}catch(n){console.warn("[Client] connection listener failed",n);}}emitDisconnection(e){for(let t of [...this.disconnectionListeners])try{t(e);}catch(n){console.warn("[Client] disconnection listener failed",n);}}disconnectBestEffort(e){try{Promise.resolve(e.disconnect()).catch(()=>{});}catch{}}flushPendingNativeMainHandshakesBestEffort(e,t){if(!this.disposed)try{Promise.resolve(this.deps.flushPendingNativeMainHandshakesForNode(e,t)).catch(()=>{});}catch{}}flushPendingNativeMainSignalsBestEffort(e,t){if(!this.disposed)try{Promise.resolve(this.deps.flushPendingNativeMainSignalsForNode(e,t)).catch(()=>{});}catch{}}schedulePeerReconciliationBestEffort(e){if(!this.disposed)try{Promise.resolve(this.deps.schedulePeerReconciliation(e)).catch(()=>{});}catch{}}lookupConnectionDeviceBindingInBackground(e){try{Promise.resolve(this.deps.searchDevices()).then(()=>{if(this.disposed)return;let t=this.deps.getKnownDeviceIdByNodeId(e.remoteNodeId);t&&this.deps.bindConnectionDeviceIdInRust(e,t);}).catch(()=>{});}catch{}}};var _t=class{constructor(e){this.deps=e;this.disposed=false;this.deps.registerDisposer(()=>this.dispose());}dispose(){this.disposed=true;}async handleMessage(e,t){if(this.disposed)return;let n=!!t&&typeof t=="object"&&t.type==="handshake",i=this.deps.requiresManagedTransportTrust()||this.deps.usesTicketOnlySignalingMode(),o=!i||this.deps.isSessionTokenApproved(e.id,e.remoteNodeId)||this.deps.getConnectionTrustState(e.id)?.verified===true;if(!(!n&&o&&await(this.deps.handleIrohCarrierControl?.(e,t)??false))){if(n){if(!await this.handleHandshake(e,t)||this.disposed)return}else if(i&&!this.deps.isSessionTokenApproved(e.id,e.remoteNodeId)){console.warn("[Client][SESSION-TOKEN] Dropping application message before admission",{connectionId:e.id,remoteNodeId:e.remoteNodeId}),this.disconnectBestEffort(e);return}this.deps.dispatchMessage(e,t);}}async handleHandshake(e,t){if(this.disposed)return false;let n=t.action??"hello",i=t.capabilities&&typeof t.capabilities=="object"?t.capabilities:void 0,o=!!i&&Object.prototype.hasOwnProperty.call(i,"webrtc"),s=!!i&&Object.prototype.hasOwnProperty.call(i,"moq"),a=typeof t.moq=="boolean",c=o&&i.webrtc===true,d=i?.webrtcExternal===true||i?.webrtcExternal===void 0&&c,l=i?.webrtcIrohCarrier===true,p=i?.moqIrohCarrier===true,u=s?i.moq===true:!!t.moq,h=this.deps.isWebRTCTransportEnabled(),m=this.deps.requiresManagedTransportTrust(),f=C=>{if(this.disposed||e.isClosed||!d||!h)return;let I=this.deps.getLocalNodeId();this.deps.usesTicketOnlySignalingMode()&&I&&e.remoteNodeId&&I.localeCompare(e.remoteNodeId)<0||(c$1("[Client][HANDSHAKE] requesting WebRTC upgrade from handshake",{connectionId:e.id,remoteNodeId:e.remoteNodeId,action:n,reason:C}),e.requestWebRTCUpgrade(C));};if(n==="hello"){let C=await this.deps.validateIncomingSessionTokenWithRetry(t.sessionToken??"",e.id,{remoteNodeId:e.remoteNodeId,source:"handshake-hello",tokenPayload:typeof t.sessionTokenPayload=="string"?t.sessionTokenPayload:void 0});if(this.disposed)return false;if(!C.ok)return console.warn("[Client][SESSION-TOKEN] Rejecting connection \u2014 invalid session token",{connectionId:e.id,remoteNodeId:e.remoteNodeId,reason:C.reason,hasToken:!!t.sessionToken}),this.disconnectBestEffort(e),false;t.sessionToken&&this.deps.applySessionTokenTrustApproval(e,C.scope??null,"handshake-hello");}let v=await this.deps.handleApplicationKeyAgreement(e,t).catch(C=>this.disposed?{remotePublicChanged:false,cryptoReady:false,replyAction:null,replyClaimId:null}:(console.warn("[Client][KEY-AGREEMENT] Handshake key agreement failed; closing connection",{connectionId:e.id,remoteNodeId:e.remoteNodeId,error:C}),this.disconnectBestEffort(e),{remotePublicChanged:false,cryptoReady:false,replyAction:null,replyClaimId:null}));if(this.disposed)return false;c$1("[Client][HANDSHAKE] received",{action:n,connectionId:e.id,remoteNodeId:e.remoteNodeId,channelId:t.channelId??this.deps.getConnectionChannelId(e.id)??null,remoteSupportsWebRTC:c,remoteSupportsWebRTCExternal:d,remoteSupportsWebRTCIrohCarrier:l,remoteSupportsMoQIrohCarrier:p,remoteSupportsMoQ:u,localWebRTCEnabled:h,hasSessionToken:!!t.sessionToken,hasTransportTrust:!!t.transportTrust});let y=t.capabilities?.applicationKeyAgreement===true&&v.cryptoReady?v.replyAction:null;return y&&this.sendHandshakeWithRecoveryInBackground(e,y,null,"application-key-agreement-confirmation","[Client][KEY-AGREEMENT] Failed to advance reciprocal key agreement",v.replyClaimId?()=>this.deps.releaseApplicationKeyAgreementReply(e.id,y,v.replyClaimId):void 0),o&&(e.remoteSupportsWebRTC=d),!m&&h&&d&&(n==="hello"||n==="capability-update"||n==="response"&&!t.transportTrust)&&f(`handshake:${n}`),(s||a)&&(u&&this.deps.getMoQState()==="ready"?(d$2(`[Client] Peer ${e.deviceId.substring(0,6)} supports MoQ. Upgrading...`),this.deps.enableMoQForConnection(e)):u||(e.peerMoQReady=false,this.deps.forgetMoQPeerSubscription(e.id))),this.deps.assignConnectionChannel(e,t.channelId??null),t.transportTrust||m?this.handleTransportTrustHandshakeInBackground(e,t,n,m,f):(t.action==="hello"||!t.action)&&t.sessionToken&&y!=="response"&&this.sendHandshakeWithRecoveryInBackground(e,"response",null,"session-token-response","[Client][SESSION-TOKEN] Failed to send response handshake"),true}disconnectBestEffort(e){try{Promise.resolve(e.disconnect()).catch(()=>{});}catch{}}sendHandshakeInBackground(e,t,n){let i=o=>{this.disposed||console.warn(n,{connectionId:e.id,remoteNodeId:e.remoteNodeId,error:o});};try{Promise.resolve(this.deps.sendTransportHandshake(e,t)).catch(i);}catch(o){i(o);}}sendHandshakeWithRecoveryInBackground(e,t,n,i,o,s){let a=c=>{s?.(),!this.disposed&&console.warn(o,{connectionId:e.id,remoteNodeId:e.remoteNodeId,error:c});};try{Promise.resolve(this.deps.sendTransportHandshakeWithRecovery(e,t,n,i)).catch(a);}catch(c){a(c);}}handleTransportTrustHandshakeInBackground(e,t,n,i,o){let s=a=>{this.disposed||console.warn("[Client][TRUST] Handshake processing failed",{connectionId:e.id,remoteNodeId:e.remoteNodeId,error:a});};try{Promise.resolve(this.handleTransportTrustHandshake(e,t,n,i,o)).catch(s);}catch(a){s(a);}}async handleTransportTrustHandshake(e,t,n,i,o){try{if(this.disposed)return;let s=n,a=t.transportTrust??null,c=this.deps.initializeConnectionTrust(e);if(a?.deviceId&&!c.expectedDeviceId&&this.deps.getKnownDevice(a.deviceId,e.remoteNodeId)&&(c.expectedDeviceId=a.deviceId),s==="hello"){let d=typeof a?.challenge=="string"?a.challenge:null;if(!d&&c.required)if(this.deps.isSessionTokenApproved(e.id,e.remoteNodeId)){let l=this.deps.getSessionTokenApprovedScope(e.id);c.required=!1,c.verified=!0,c.failed=!1,c.failureReason=void 0,c.issuedChallenge=null,this.deps.applyConnectionTrustProjection(e);let p=typeof a?.deviceId=="string"&&a.deviceId.trim()?a.deviceId.trim():c.expectedDeviceId??this.deps.getKnownDeviceIdForNode(e.remoteNodeId)??null;p&&this.deps.sessionTokenScopeAllowsDeviceBinding(l)&&this.deps.bindConnectionDeviceIdInRust(e,p),c$1("[Client][TRUST] Skipping challenge enforcement for session-token-approved connection",{connectionId:e.id,remoteNodeId:e.remoteNodeId,action:s});}else c.failureReason="missing-transport-trust-challenge",this.deps.applyConnectionTrustProjection(e),c$1("[Client][TRUST] Deferring missing hello challenge enforcement pending response/ack or session-token approval",{connectionId:e.id,remoteNodeId:e.remoteNodeId,action:s});if(await this.deps.sendTransportHandshakeWithRecovery(e,"response",d,`trust-${s}-response`),this.disposed)return}else if(s==="response"||s==="ack"){let d=await this.deps.verifyRemoteTransportTrust(e,a);if(this.disposed)return;if(!d.verified){if(d.stale){c$1("[Client][TRUST] Ignoring stale transport proof and requesting current challenge",{connectionId:e.id,remoteNodeId:e.remoteNodeId,action:s,reason:d.reason??"stale-transport-trust-response"}),await this.deps.sendTransportHandshakeWithRecovery(e,"hello",null,"stale-trust-response-rechallenge");return}if(this.deps.isSessionTokenApproved(e.id,e.remoteNodeId)){this.deps.applySessionTokenTrustApproval(e,null,"handshake-proof-bypass-after-session-token");return}if(d.reason==="missing-transport-trust-payload"||d.reason==="missing-signed-transport-challenge"){c.failureReason=d.reason,this.deps.applyConnectionTrustProjection(e),c$1("[Client][TRUST] Deferring absent optional transport proof pending session-token admission",{connectionId:e.id,remoteNodeId:e.remoteNodeId,action:s});return}c.required&&await this.deps.enforceConnectionTrustFailure(e,d.reason??"remote-transport-proof-invalid");return}if(this.deps.markConnectionTrustVerified(e,d.deviceId),s==="response"&&o(`handshake:${s}:trust-verified`),s==="response"&&typeof a?.challenge=="string"&&(await this.deps.sendTransportHandshakeWithRecovery(e,"ack",a.challenge,"trust-response-ack"),this.disposed))return}else s==="capability-update"&&(this.deps.isSessionTokenApproved(e.id,e.remoteNodeId)||this.deps.getConnectionTrustState(e.id)?.verified)&&o("capability-update:trust-reused");}catch(s){console.warn("[Client][TRUST] Handshake processing failed",{connectionId:e.id,remoteNodeId:e.remoteNodeId,error:s});}finally{let s=t.capabilities?.webrtcIrohCarrier===true||t.capabilities?.moqIrohCarrier===true,a=!i||this.deps.isSessionTokenApproved(e.id,e.remoteNodeId)||this.deps.getConnectionTrustState(e.id)?.verified===true;!this.disposed&&s&&(a?await this.deps.observeIrohCarrierHandshake?.(e,t.capabilities):await this.deps.observeIrohCarrierHandshake?.(e,t.capabilities,false));}}};var Lt=class Lt{constructor(e){this.deps=e;this.disposed=false;this.deps.registerDisposer(()=>this.dispose());}dispose(){this.disposed=true;}async handleUnhandledIncomingStreamEvent(e){if(await this.closeIfDisposed(e,"incoming-acceptor-disposed"))return;let{type:t,stream:n,remoteNodeId:i,traceId:o}=e,s=e.protocolHint;if(t==="bi"&&s==="native-main"&&(s=this.deps.normalizeAuthoritativeIncomingProtocolHint("native-main",i,o)??"native-main",e={...e,protocolHint:s}),!e.invalid){if(t==="bi"&&e.channel?.channelId===pi){await this.receiveDefaultPeerStream(e);return}if(t==="bi"&&e.channel?.channelId){await oe(n,"unclaimed-named-channel",i);return}if(t==="uni"){if(!this.deps.shouldSkipIncomingStreamProbe()&&await this.deps.tryHandleNativeMainUniStream(n,i,o))return;await this.deps.cancelUnhandledIncomingUniStream(n,i);return}if(t==="bi"&&s==="native-main"){c$1("[Client][INCOMING] Handling native desktop main stream",{remoteNodeId:i,traceId:o||null}),this.handleNativeMainStreamInBackground(n,i,e.transportStableId,o,"[Client][NATIVE-MAIN] Background handler crashed");return}if(this.deps.shouldTreatIncomingStreamAsTransportOnly(e)){this.deps.logIncomingDiagnostic("bi:drop-unhandled-ticket-flow",{remoteNodeId:i||"unknown",traceId:o||null,protocolHint:s,channelId:e.channel?.channelId??null});return}t==="bi"&&s!=="explicit"&&await this.acceptIncomingBiStream(e);}}async receiveDefaultPeerStream(e){let t=e.stream,n=e.remoteNodeId,i=this.deps.getDeterministicConnectionId(n),o=this.deps.getConnection(i);if(!o||o.isClosed||!i$2(t)){await oe(t,"peer-default-without-live-connection",n);return}let s=t.recv.getReader(),a=t.send.getWriter(),c=new Uint8Array(0);try{for(;;){let{done:d,value:l}=await s.read();if(d)break;if(!l||l.byteLength===0)continue;let p=new Uint8Array(c.byteLength+l.byteLength);for(p.set(c),p.set(l,c.byteLength),c=p;c.byteLength>=4;){let u=new DataView(c.buffer,c.byteOffset,c.byteLength).getUint32(0,!1);if(u===0||u>Lt.MAX_PEER_MESSAGE_FRAME_BYTES)throw new Error(`invalid peer-default frame length ${u}`);if(c.byteLength<4+u)break;o.receiveFrameBody(c.slice(4,4+u)),c=c.slice(4+u);}}if(c.byteLength!==0)throw new Error(`truncated peer-default frame (${c.byteLength} bytes)`)}catch(d){this.deps.logIncomingDiagnostic("peer-default:receive-failed",{connectionId:i,remoteNodeId:n,traceId:e.traceId??null,error:d});}finally{try{await a.close();}catch{}try{s.releaseLock();}catch{}try{a.releaseLock();}catch{}}}async acceptIncomingBiStream(e){if(await this.closeIfDisposed(e,"incoming-acceptor-disposed-before-accept"))return;let{stream:t,remoteNodeId:n,traceId:i}=e,o=e.protocolHint,s=this.deps.getDeterministicConnectionId(n),a=this.deps.getKnownDevice(null,n),c=typeof a?.platformType=="string"?String(a.platformType).toLowerCase():typeof a?.platform_type=="string"?String(a.platform_type).toLowerCase():null;if(!this.deps.usesTicketOnlySignalingMode()&&(c==="desktop"||c==="mobile")){c$1("[Client][INCOMING] Routing unhinted native peer stream through native-main handler",{connectionId:s,remoteNodeId:n,traceId:i||null,protocolHint:o,knownRemotePlatform:c}),this.handleNativeMainStreamInBackground(t,n,e.transportStableId,i,"[Client][NATIVE-MAIN] Unhinted native peer stream handler crashed");return}let d=this.deps.getConnection(s);if(d&&!d.isClosed){let f=d.getUpgradeState(),v=await this.deps.isCoreConnectionHealthy(n).catch(()=>false);if(await this.closeIfDisposed(e,"incoming-acceptor-disposed-after-core-health"))return;let y=typeof d.getControlFrameMode=="function"&&d.getControlFrameMode()==="native-main";if(v){if(!y){c$1("[Client][INCOMING] Closing auxiliary bi stream while typed connection is upgrading/upgraded",{connectionId:s,remoteNodeId:n,traceId:i||null,existingUpgradeState:f,protocolHint:o}),await oe(t,"typed-connection-auxiliary-stream",n);return}c$1("[Client][INCOMING] Routing auxiliary bi stream to native-main handler while connection is upgrading/upgraded",{connectionId:s,remoteNodeId:n,traceId:i||null,existingUpgradeState:f,protocolHint:o}),this.handleNativeMainStreamInBackground(t,n,e.transportStableId,i,"[Client][NATIVE-MAIN] Auxiliary stream handler crashed");return}if((f==="upgrading"||f==="upgraded")&&c$1("[Client][INCOMING] Replacing upgraded connection due to stale core transport",{connectionId:s,remoteNodeId:n,traceId:i||null,existingUpgradeState:f,coreTransportConnected:v}),c$1("[Client][INCOMING] Replacing existing connection main stream",{connectionId:s,remoteNodeId:n,traceId:i||null}),this.deps.cleanupReplacedConnection(s),await this.disconnectConnection(d),await this.closeIfDisposed(e,"incoming-acceptor-disposed-after-existing-disconnect"))return}let l=t;if(!i$2(l)){console.error("[Client][INCOMING] Unable to construct connection from invalid bi stream",{remoteNodeId:n});return}let p,u;try{p=l.send.getWriter(),u=l.recv.getReader();}catch(f){console.error("[Client][INCOMING] Failed to acquire incoming stream reader/writer",{remoteNodeId:n,error:f});return}let h;h=new ie(s,this.deps.getLocalNodeId(),n,p,u,{rtcConfig:this.deps.getRTCConfig(),transportContext:this.deps.createTransportContext(n),applicationCrypto:this.deps.getOptions()?.applicationCrypto,requireApplicationCrypto:this.deps.shouldNegotiateApplicationKeyAgreement(),controlFrameMode:"typed",onTransportStatusChange:f=>this.deps.handleConnectionTransportStatus(h,f.activeTransport,f.parallelTransport),onApplicationRouteReady:f=>{this.deps.handleConnectionApplicationRouteReady(h,f);},onApplicationRouteMissing:f=>{this.deps.handleConnectionApplicationRouteMissing(s,f);}});let m=this.deps.getKnownDeviceIdForNode(n);if(this.deps.initializeConnectionTrust(h,m),this.disposed){await this.disconnectConnection(h);return}this.deps.registerConnection(h),m?this.deps.bindConnectionDeviceIdInRust(h,m):this.lookupAcceptedDeviceBindingInBackground(h,n),this.deps.announceConnectionWhenStable(h),c$1("[Client][HANDSHAKE] sending hello (incoming connection path)",{connectionId:h.id,remoteNodeId:h.remoteNodeId}),this.sendIncomingHelloInBackground(h);}handleNativeMainStreamInBackground(e,t,n,i,o){let s=a=>{this.disposed||console.error(o,{remoteNodeId:t,traceId:i||null,error:a});};try{let a=Number.isSafeInteger(n)&&Number(n)>0?this.deps.handleNativeMainStream(e,t,n):this.deps.handleNativeMainStream(e,t);Promise.resolve(a).catch(s);}catch(a){s(a);}}lookupAcceptedDeviceBindingInBackground(e,t){let n=i=>{this.disposed||console.warn("[Client][BIND] Accept-side searchDevices fallback failed",{connectionId:e.id,remoteNodeId:t,error:i});};try{Promise.resolve(this.deps.searchDevices()).then(()=>{if(this.disposed)return;let i=this.deps.getKnownDeviceIdForNode(t);i?this.deps.bindConnectionDeviceIdInRust(e,i):console.warn("[Client][BIND] Accept-side directory lookup found no deviceId for remote node",{connectionId:e.id,remoteNodeId:t});}).catch(n);}catch(i){n(i);}}sendIncomingHelloInBackground(e){let t=n=>{this.disposed||console.warn("[Client][TRUST] Failed to send incoming handshake",{connectionId:e.id,remoteNodeId:e.remoteNodeId,error:n});};try{Promise.resolve(this.deps.sendTransportHandshake(e,"hello")).then(()=>{this.disposed||this.deps.requestProtectedWebRTCUpgradeIfInitiator(e,"protected-hello:incoming");}).catch(t);}catch(n){t(n);}}async disconnectConnection(e){try{await Promise.resolve(e.disconnect());}catch{}}async closeIfDisposed(e,t){return this.disposed?(e.type==="bi"?await oe(e.stream,t,e.remoteNodeId):e.type==="uni"&&await this.deps.cancelUnhandledIncomingUniStream(e.stream,e.remoteNodeId),true):false}};Lt.MAX_PEER_MESSAGE_FRAME_BYTES=4*1024*1024;var xt=Lt;function rr(r){return r==="desktop"||r==="mobile"||r==="native"}function sr(r,e,t=false){return true}function ar(r){return !r}function Bt(r,e,t){return r}var mi={ready:false,phase:"frame-start",expectedFrameLength:0,consumedBytes:0,payloadBytes:new Uint8Array};function cr(r,e){let t=new TextEncoder().encode(JSON.stringify(r)),n=new TextEncoder().encode(e.label),i=new Uint8Array(5+n.byteLength+4+t.byteLength),o=new DataView(i.buffer),s=0;return i[s]=e.protocolByte,s+=1,o.setUint32(s,n.byteLength,false),s+=4,i.set(n,s),s+=n.byteLength,o.setUint32(s,t.byteLength,false),s+=4,i.set(t,s),i}async function lr(r,e,t,n,i=8e3){if(typeof window>"u"||typeof window.dispatchEvent!="function")return null;let o=[],s=c=>{o.push(Promise.resolve(c));};if(window.dispatchEvent(new CustomEvent(r,{detail:{remoteNodeId:e,remoteDeviceId:t,message:n,respondWith:s}})),o.length===0)return null;let a;try{let c=await Promise.race([Promise.allSettled(o),new Promise(d=>{a=setTimeout(()=>d([]),i);})]);for(let d of c)if(d.status==="fulfilled"&&d.value!==void 0&&d.value!==null)return d.value}finally{a&&clearTimeout(a);}return null}function dr(r,e){if(r.byteLength===0)return mi;if(r[0]===e.protocolByte){if(r.byteLength<5)return mi;let i=new DataView(r.buffer,r.byteOffset,r.byteLength),o=i.getUint32(1,false);if(o>0&&o<=e.maxLabelBytes&&r.byteLength>=5+o&&new TextDecoder().decode(r.slice(5,5+o))===e.label){let a=5+o+4;if(r.byteLength<a)return {ready:false,phase:"frame-body",expectedFrameLength:0,consumedBytes:0,payloadBytes:new Uint8Array};let c=i.getUint32(5+o,false);if(c>e.maxFrameBytes)throw new Error(`native-main frame too large: ${c}`);return r.byteLength<a+c?{ready:false,phase:"frame-body",expectedFrameLength:c,consumedBytes:0,payloadBytes:new Uint8Array}:{ready:true,phase:"frame-body",expectedFrameLength:c,consumedBytes:a+c,payloadBytes:r.slice(a,a+c)}}}if(r.byteLength<4)return mi;let n=new DataView(r.buffer,r.byteOffset,r.byteLength).getUint32(0,false);if(n>e.maxFrameBytes)throw new Error(`legacy native-main frame too large: ${n}`);return r.byteLength<4+n?{ready:false,phase:"frame-body",expectedFrameLength:n,consumedBytes:0,payloadBytes:new Uint8Array}:{ready:true,phase:"frame-body",expectedFrameLength:n,consumedBytes:4+n,payloadBytes:r.slice(4,4+n)}}function pr(r){let{host:e,transports:t,trustServices:n}=r;return new Dt(e.getContext(),{ensureWasmRuntimeForP2P:()=>e.ensureWasmRuntimeForP2P(),getOptions:()=>e.getOptions(),getWasmClient:()=>e.getWasmClient(),getLocalNodeId:()=>e.getLocalNodeId(),getDeterministicConnectionId:i=>t.peerIdentity.getDeterministicConnectionId(i),getRegisteredChannel:i=>e.getRegisteredChannel(i),isTransportOnlyChannel:i=>n.channelPolicy.isTransportOnlyChannel(i),rememberRouteRepairTokenForNode:(i,o,s)=>e.rememberRouteRepairTokenForNode(i,o,s),resolveExpectedDeviceIdForSessionTokenScope:(i,o,s,a)=>n.trust.resolveExpectedDeviceIdForSessionTokenScope(i,o,s,a),initializeConnectionTrust:(i,o)=>n.trust.initialize(i,o),refreshApplicationRouteHandshake:(i,o,s)=>t.upgrade.refreshApplicationRouteHandshake(i,o,s),ensureWasmManagedTransport:(i,o,s)=>e.ensureWasmManagedTransport(i,o,s),isLocalIrohRuntimeNotInitializedError:i=>e.isLocalIrohRuntimeNotInitializedError(i),recoverLocalIrohRuntime:i=>e.recoverLocalIrohRuntime(i),getSessionTokenApprovedScope:i=>e.getSessionTokenApprovedScope(i),setSessionTokenApprovedScope:(i,o)=>e.setSessionTokenApprovedScope(i,o),getPeerState:i=>e.getPeerState(i),assignConnectionChannel:(i,o)=>n.channelPolicy.assign(i,o),bindConnectionDeviceIdInRust:(i,o)=>n.deviceBinder.bindConnectionDeviceIdInRust(i,o),approveSessionTokenNode:i=>e.approveSessionTokenNode(i),approveSessionTokenConnection:i=>e.approveSessionTokenConnection(i),applySessionTokenTrustApproval:(i,o,s)=>e.applySessionTokenTrustApproval(i,o,s),announceConnectionWhenStable:i=>r.getLifecycle().announceConnectionWhenStable(i),disconnectNodeTransport:i=>t.health.disconnectNodeTransport(i),shouldUseNativeMainFramingForPeer:(i,o,s)=>sr(i,o,s),writeNativeMainLabelHeaderOnBiStream:(i,o)=>e.writeNativeMainLabelHeaderOnBiStream(i,o),getRTCConfig:()=>t.getRTCConfig(),createTransportContext:i=>t.contexts.create(i),shouldNegotiateApplicationKeyAgreement:()=>e.shouldNegotiateApplicationKeyAgreement(),handleConnectionTransportStatus:(i,o,s)=>t.health.handleCurrentConnectionTransportStatus(i,o,s),handleConnectionApplicationRouteReady:(i,o)=>t.health.handleCurrentConnectionApplicationRouteReady(i,o),handleConnectionApplicationRouteMissing:(i,o)=>t.upgrade.handleApplicationRouteMissing(i,o),sendNativeSignalEnvelope:(i,o,s,a)=>e.sendNativeSignalEnvelope(i,o,s,a),registerConnection:i=>r.getLifecycle().registerConnection(i),cleanupReplacedConnection:i=>r.getLifecycle().cleanupReplacedConnection(i),schedulePeerReconciliation:i=>e.schedulePeerReconciliation(i),consumePendingSessionTokenTrustApproval:i=>e.consumePendingSessionTokenTrustApproval(i),sendTransportHandshake:(i,o)=>t.handshake.sendTransportHandshake(i,o),requestProtectedWebRTCUpgradeIfInitiator:(i,o)=>t.handshake.requestProtectedWebRTCUpgradeIfInitiator(i,o),clearManualDisconnectProjection:i=>e.clearManualDisconnectProjection(i),getPeerScopes:i=>e.getPeerScopes(i),sessionTokenScopeAllowsDeviceBinding:i=>n.trust.sessionTokenScopeAllowsDeviceBinding(i),resolvePromotionEligibility:i=>n.channelPolicy.resolvePromotionEligibility(i),hasRustPeerLifecycleProjection:()=>e.hasRustPeerLifecycleProjection(),dispatchLiveConnectionProjection:(i,o)=>e.dispatchLiveConnectionProjection(i,o),hasApplicationRouteForConnection:i=>t.upgrade.hasApplicationRouteForConnection(i),isWebRtcApplicationRouteReadyForConnection:i=>t.upgrade.isWebRtcApplicationRouteReadyForConnection(i),addPeerScope:(i,o)=>e.addPeerScope(i,o)})}function ur(r){let{host:e,transports:t,trustServices:n}=r;return new _t({registerDisposer:i=>e.registerDisposer(i),resolveApplicationCryptoForPeer:(i,o)=>e.resolveApplicationCryptoForPeer(i,o),handleApplicationKeyAgreement:(i,o)=>e.handleApplicationKeyAgreement(i,o),releaseApplicationKeyAgreementReply:(i,o,s)=>e.releaseApplicationKeyAgreementReply(i,o,s),isWebRTCTransportEnabled:()=>d$1(e.getOptions()),handleIrohCarrierControl:(i,o)=>t.browserIrohWebRtcCarrier.handleControl(i,o),observeIrohCarrierHandshake:(i,o,s)=>t.handshake.observeIrohCarrierHandshake(i,o,s),requiresManagedTransportTrust:()=>e.requiresManagedTransportTrust(e.getDiscoveryMode()),usesTicketOnlySignalingMode:()=>e.usesTicketOnlySignalingMode(),getLocalNodeId:()=>e.getLocalNodeId(),validateIncomingSessionTokenWithRetry:(i,o,s)=>e.validateIncomingSessionTokenWithRetry(i,o,s),applySessionTokenTrustApproval:(i,o,s)=>e.applySessionTokenTrustApproval(i,o,s),getConnectionChannelId:i=>n.channelPolicy.getConnectionChannelId(i),sendTransportHandshake:(i,o)=>t.handshake.sendTransportHandshake(i,o),getMoQState:()=>e.getMoQState(),enableMoQForConnection:i=>e.enableMoQForConnection(i),forgetMoQPeerSubscription:i=>e.forgetMoQPeerSubscription(i),assignConnectionChannel:(i,o)=>n.channelPolicy.assign(i,o),initializeConnectionTrust:i=>n.trust.initialize(i),getKnownDevice:(i,o)=>e.getKnownDevice(i,o),isSessionTokenApproved:(i,o)=>e.isSessionTokenApproved(i,o),getSessionTokenApprovedScope:i=>e.getSessionTokenApprovedScope(i),sessionTokenScopeAllowsDeviceBinding:i=>n.trust.sessionTokenScopeAllowsDeviceBinding(i),applyConnectionTrustProjection:i=>e.applyConnectionTrustProjection(i),getKnownDeviceIdForNode:i=>e.getKnownDeviceIdForNode(i),bindConnectionDeviceIdInRust:(i,o)=>n.deviceBinder.bindConnectionDeviceIdInRust(i,o),sendTransportHandshakeWithRecovery:(i,o,s,a)=>t.handshake.sendTransportHandshakeWithRecovery(i,o,s,a),verifyRemoteTransportTrust:(i,o)=>n.trust.verifyRemoteTransportTrust(i,o),enforceConnectionTrustFailure:(i,o)=>n.trust.enforceFailure(i,o),markConnectionTrustVerified:(i,o)=>n.trust.markVerified(i,o),getConnectionTrustState:i=>n.trust.getStateByConnectionId(i),dispatchMessage:(i,o)=>e.dispatchIncomingMessage(i,o)})}function gr(r){let{host:e,registry:t,transports:n,trustServices:i}=r;return new xt({registerDisposer:o=>e.registerDisposer(o),normalizeAuthoritativeIncomingProtocolHint:(o,s,a)=>Bt(o),shouldSkipIncomingStreamProbe:()=>e.shouldSkipIncomingStreamProbe(),tryHandleNativeMainUniStream:(o,s,a)=>e.tryHandleNativeMainUniStream(o,s,a),cancelUnhandledIncomingUniStream:(o,s)=>e.cancelUnhandledIncomingUniStream(o,s,(a,c)=>e.logIncomingDiagnostic(a,c)),handleNativeMainStream:(o,s,a)=>Number.isSafeInteger(a)&&Number(a)>0?e.handleNativeMainStream(o,s,a):e.handleNativeMainStream(o,s),shouldTreatIncomingStreamAsTransportOnly:o=>e.shouldTreatIncomingStreamAsTransportOnly(o),logIncomingDiagnostic:(o,s)=>e.logIncomingDiagnostic(o,s),getDeterministicConnectionId:o=>n.peerIdentity.getDeterministicConnectionId(o),getKnownDevice:(o,s)=>e.getKnownDevice(o,s),usesTicketOnlySignalingMode:()=>e.usesTicketOnlySignalingMode(),getConnection:o=>t.get(o),isCoreConnectionHealthy:o=>n.health.isCoreConnectionHealthy(o),cleanupReplacedConnection:o=>r.getLifecycle().cleanupReplacedConnection(o),getLocalNodeId:()=>e.getLocalNodeId(),getRTCConfig:()=>n.getRTCConfig(),createTransportContext:o=>n.contexts.create(o),getOptions:()=>e.getOptions(),shouldNegotiateApplicationKeyAgreement:()=>e.shouldNegotiateApplicationKeyAgreement(),handleConnectionTransportStatus:(o,s,a)=>n.health.handleCurrentConnectionTransportStatus(o,s,a),handleConnectionApplicationRouteReady:(o,s)=>n.health.handleCurrentConnectionApplicationRouteReady(o,s),handleConnectionApplicationRouteMissing:(o,s)=>n.upgrade.handleApplicationRouteMissing(o,s),getKnownDeviceIdForNode:o=>e.getKnownDeviceIdForNode(o),initializeConnectionTrust:(o,s)=>i.trust.initialize(o,s),registerConnection:o=>r.getLifecycle().registerConnection(o),bindConnectionDeviceIdInRust:(o,s)=>i.deviceBinder.bindConnectionDeviceIdInRust(o,s),searchDevices:()=>e.searchDevices(),announceConnectionWhenStable:o=>r.getLifecycle().announceConnectionWhenStable(o),sendTransportHandshake:(o,s)=>n.handshake.sendTransportHandshake(o,s),requestProtectedWebRTCUpgradeIfInitiator:(o,s)=>n.handshake.requestProtectedWebRTCUpgradeIfInitiator(o,s)})}function hr(r){let{host:e,registry:t,transports:n,trustServices:i}=r;return new Et({registerDisposer:o=>e.registerDisposer(o),registry:t,resolveApplicationCryptoForPeer:(o,s)=>e.resolveApplicationCryptoForPeer(o,s),flushPendingNativeMainHandshakesForNode:(o,s)=>e.flushPendingNativeMainHandshakesForNode(o,s),flushPendingNativeMainSignalsForNode:(o,s)=>e.flushPendingNativeMainSignalsForNode(o,s),getConnectionTrustState:o=>i.trust.getStateByConnectionId(o),getKnownDeviceIdByNodeId:o=>e.getKnownDeviceIdForNode(o),bindConnectionDeviceIdInRust:(o,s)=>i.deviceBinder.bindConnectionDeviceIdInRust(o,s),searchDevices:()=>e.searchDevices(),retireSupersededConnections:(o,s,a)=>i.deviceBinder.retireSupersededConnections(o,s,a),hasRustPeerLifecycleProjection:()=>e.hasRustPeerLifecycleProjection(),applyConnectionTrustProjection:o=>e.applyConnectionTrustProjection(o),schedulePeerReconciliation:o=>e.schedulePeerReconciliation(o),maybeHandleWebRTCExplicitFileEnvelope:(o,s)=>e.maybeHandleWebRTCExplicitFileEnvelope(o,s),handleMessage:(o,s)=>r.getMessageHandler().handleMessage(o,s),getExistingPeerProjectionForDisconnect:o=>e.getPeerState(o.id)||e.getPeerProjectionList().find(s=>s.connectionIds.includes(o.id)||s.nodeId===o.deviceId),cleanupConnectionState:(o,s)=>{e.forgetMoQPeerSubscription(o),s!=="physical-route"&&(n.retireBrowserIrohWebRtcCarrierConnection(o),e.clearApplicationCryptoForConnection(o),i.trust.clearForConnection(o),i.channelPolicy.forget(o),e.clearSessionTokenConnectionApproval(o));},dispatchLiveConnectionProjection:(o,s)=>e.dispatchLiveConnectionProjection(o,s),resolvePromotionEligibility:o=>i.channelPolicy.resolvePromotionEligibility(o),enforceConnectionTrustFailure:(o,s)=>i.trust.enforceFailure(o,s),initializeConnectionTrust:o=>i.trust.initialize(o),getWasmClient:()=>e.getWasmClient(),isCoreConnectionHealthy:o=>n.health.isCoreConnectionHealthy(o),hasApplicationRouteForConnection:o=>n.upgrade.hasApplicationRouteForConnection(o),allowsTransportOnlyStability:o=>i.channelPolicy.allowsTransportOnlyStability(o),stableWindowMs:Uo,stableTimeoutMs:Ho,stablePollMs:qo})}function mr(r){return new fi({getContext:()=>r.getClientContext(),getOptions:()=>r.options,getWasmClient:()=>r.wasmClient,getLocalNodeId:()=>r.localNodeId,getDiscoveryMode:()=>r.discoveryMode,registerDisposer:e=>r.lifecycleScope.register(e),getTransportServices:()=>r.transportServices,getTrustServices:()=>r.trustServices,ensureWasmRuntimeForP2P:()=>r.runtimeReadiness.ensureWasmRuntimeForP2P(),ensureWasmManagedTransport:(e,t,n)=>r.managedTransportDialer.ensureWasmManagedTransport(e,t,n),isLocalIrohRuntimeNotInitializedError:e=>r.managedTransportDialer.isLocalIrohRuntimeNotInitializedError(e),recoverLocalIrohRuntime:e=>r.runtimeBootstrap.recoverLocalIrohRuntime(e),requiresManagedTransportTrust:e=>r.runtimeStatus.requiresManagedTransportTrust(e??r.discoveryMode),usesTicketOnlySignalingMode:()=>r.runtimeStatus.usesTicketOnlySignalingMode(),getRegisteredChannel:e=>r.incomingStreamRouter.getRegisteredChannel(e),maybeHandleWebRTCExplicitFileEnvelope:(e,t)=>r.incomingStreamRouter.maybeHandleWebRTCExplicitFileEnvelope(e,t),dispatchIncomingMessage:(e,t)=>r.incomingStreamRouter.dispatchMessage(e,t),shouldSkipIncomingStreamProbe:()=>r.incomingDiagnostics.shouldSkipIncomingStreamProbe(),cancelUnhandledIncomingUniStream:(e,t,n)=>r.incomingDiagnostics.cancelUnhandledIncomingUniStream(e,t,n),logIncomingDiagnostic:(e,t)=>r.incomingDiagnostics.logIncomingDiagnostic(e,t),shouldTreatIncomingStreamAsTransportOnly:e=>r.applicationIncomingStreams.shouldTreatIncomingStreamAsTransportOnly(e),tryHandleNativeMainUniStream:(e,t,n)=>r.nativeMain.tryHandleNativeMainUniStream(e,t??"",n),handleNativeMainStream:(e,t,n)=>Number.isSafeInteger(n)&&Number(n)>0?r.nativeMain.handleNativeMainStream(e,t??"",n):r.nativeMain.handleNativeMainStream(e,t??""),flushPendingNativeMainHandshakesForNode:(e,t)=>r.nativeMain.flushPendingHandshakesForNode(e,t),flushPendingNativeMainSignalsForNode:(e,t)=>r.nativeMain.flushPendingSignalsForNode(e,t),writeNativeMainLabelHeaderOnBiStream:(e,t)=>r.nativeMain.writeLabelHeaderOnBiStream(e,t),sendNativeSignalEnvelope:(e,t,n,i)=>r.nativeMain.sendSignalEnvelope(e,t,n,i),resolveApplicationCryptoForPeer:(e,t)=>r.applicationCrypto.resolveForPeer(e,t),resyncApplicationCryptoToNative:e=>r.applicationCrypto.resyncConnectionKeyToNative(e),clearApplicationCryptoForConnection:e=>r.applicationCrypto.clearConnection(e),handleApplicationKeyAgreement:(e,t)=>r.applicationCrypto.handleKeyAgreement(e,t),releaseApplicationKeyAgreementReply:(e,t,n)=>r.applicationCrypto.releaseReplyClaim(e,t,n),shouldNegotiateApplicationKeyAgreement:()=>r.applicationCrypto.shouldNegotiateKeyAgreement(),rememberRouteRepairTokenForNode:(e,t,n)=>r.sessionTokens.rememberRouteRepairTokenForNode(e,t,n),getSessionTokenApprovedScope:e=>r.sessionTokens.getApprovedScope(e),setSessionTokenApprovedScope:(e,t)=>r.sessionTokens.setApprovedScope(e,t),approveSessionTokenNode:e=>r.sessionTokens.approveNode(e),approveSessionTokenConnection:e=>r.sessionTokens.approveConnection(e),applySessionTokenTrustApproval:(e,t,n)=>r.sessionTokens.applyTrustApproval(e,t,n),consumePendingSessionTokenTrustApproval:e=>r.sessionTokens.consumePendingTrustApproval(e),validateIncomingSessionTokenWithRetry:(e,t,n)=>r.sessionTokens.validateIncomingSessionTokenWithRetry(e,t,n),isSessionTokenApproved:(e,t)=>r.sessionTokens.isApproved(e,t),clearSessionTokenConnectionApproval:e=>r.sessionTokens.clearConnectionApproval(e),getPeerState:e=>r.peerServices.getPeerState(e),getPeerScopes:e=>r.peerServices.getPeerScopes(e),addPeerScope:(e,t)=>r.peerServices.addPeerScope(e,t),clearManualDisconnectProjection:e=>r.peerServices.clearManualDisconnectProjection(e),getPeerProjectionList:()=>r.peerServices.listPeerStates(),hasRustPeerLifecycleProjection:()=>r.hasRustPeerLifecycleProjection(),applyConnectionTrustProjection:e=>r.peerProjection.applyConnectionTrustProjection(e),schedulePeerReconciliation:e=>r.peerProjection.schedule(e),dispatchLiveConnectionProjection:(e,t)=>r.peerProjection.dispatchLiveConnectionProjection(e,t),getKnownDevice:(e,t)=>r.deviceDirectory.getKnownDevice(e,t),getKnownDeviceIdForNode:e=>r.deviceDirectory.getKnownDeviceIdForNode(e),searchDevices:()=>r.deviceDirectory.searchDevices(),getMoQState:()=>r.moqServices.state,enableMoQForConnection:e=>r.moqServices.enableForConnection(e),forgetMoQPeerSubscription:e=>r.moqServices.forgetPeerSubscription(e)})}var fi=class{constructor(e){this.host=e;this.registry=new At;}get transports(){return this.host.getTransportServices()}get trustServices(){return this.host.getTrustServices()}get factoryHost(){return {host:this.host,registry:this.registry,transports:this.transports,trustServices:this.trustServices,getLifecycle:()=>this.lifecycle,getMessageHandler:()=>this.messageHandler}}get dialer(){return this._dialer??(this._dialer=pr(this.factoryHost))}get messageHandler(){return this._messageHandler??(this._messageHandler=ur(this.factoryHost))}get incomingAcceptor(){return this._incomingAcceptor??(this._incomingAcceptor=gr(this.factoryHost))}get lifecycle(){return this._lifecycle??(this._lifecycle=hr(this.factoryHost))}async ensureManagedApplicationRoute(e){let t=Math.max(1,e.timeoutMs??2e4),n=await this.dialer.connect(e.ticket,t,e.expectedDeviceId,void 0,{admissionAlreadyPresented:true}),i=this.registry.getForPeer(e.connectionId??void 0,e.remoteNodeId??n.remoteNodeId)??n,o=typeof e.approvedScope=="string"&&e.approvedScope.trim()?e.approvedScope.trim():null;if(o&&this.host.applySessionTokenTrustApproval(i,o,"managed-transport-adoption"),await this.host.resyncApplicationCryptoToNative?.(i),await this.transports.upgrade.refreshApplicationRouteHandshake(i,"managed-transport-adoption",{forceReciprocal:true}),!await this.transports.upgrade.waitForApplicationRouteForConnection(i,t,50))throw new Error(`[Client][HANDSHAKE] application route was not ready for current connection ${i.id}`);return i}};var Ft=class{constructor(){this.wasmClient=null;this.node=null;this.localNodeId="";this.deviceId=null;}};var Wt=class{constructor(e=(t,n)=>{console.warn(t,n);}){this.logError=e;this.disposers=[];this.destroyed=false;}get isDestroyed(){return this.destroyed}register(e){if(this.destroyed){try{e();}catch(t){this.logError("[Client] late disposer failed",t);}return}this.disposers.push(e);}destroy(){if(!this.destroyed){this.destroyed=true;for(let e of this.disposers.splice(0).reverse())try{e();}catch(t){this.logError("[Client] disposer failed during destroy",t);}}}};var Ot=class{constructor(e,t={}){this.session=e;this.namespaces=new Map;this.activePublishers=new Map;this.closed=false;this.maxNamespaces=t.maxPendingAnnounces??64,this.maxSubscribedTracks=t.maxSubscribedTracks??256,this.maxActivePublishers=t.maxActivePublishers??256,this.maxTrackIdChars=t.maxTrackIdChars??512,this.maxObjectPayloadBytes=t.maxObjectPayloadBytes??4*1024*1024;}async announce(e){let t=e.trim();if(!t)throw new Error("MoQ announce namespace must be non-empty");if(this.namespaces.has(t))throw new Error(`MoQ namespace is already announced: ${t}`);if(this.namespaces.size>=this.maxNamespaces)throw new Error(`MoQ namespace limit exceeded (${this.maxNamespaces})`);let n=new $e.Broadcast,i={broadcast:n,subscribers:new Map};this.namespaces.set(t,i),this.session.requireConnection().publish($e.Path.from(t),n),d$2(`[MoQ] Draft 14 namespace published: ${t}`),this.acceptTrackRequests(t,i);}hasNamespace(e){return this.namespaces.has(e.trim())}hasTrackSubscriber(e,t){return (this.namespaces.get(e.trim())?.subscribers.get(t)?.size??0)>0}async createTrack(e,t){let n=this.resolveTrackId(e,t);if(!n)throw new Error("MoQ track namespace and name must be non-empty and within length limits");let i=this.activePublishers.get(n);if(i)return i;if(this.activePublishers.size>=this.maxActivePublishers)throw new Error(`MoQ active publisher limit exceeded (${this.maxActivePublishers})`);let o=e.trim(),s={close:()=>this.activePublishers.delete(n),push:async a=>{if(this.closed)throw new Error("MoQ publisher closed");if(a.byteLength>this.maxObjectPayloadBytes)throw new Error(`MoQ object payload length exceeds limit: ${a.byteLength}`);let c=this.namespaces.get(o)?.subscribers.get(t);if(!c?.size)throw new Error(`MoQ track lost all subscribers: ${n}`);let d=[],l=0,p=null;for(let u of c)try{u.writeFrame(a.slice()),l+=1;}catch(h){d.push(u),p=h;}for(let u of d)c.delete(u);if(l===0){let u=p instanceof Error?`: ${p.message}`:"";throw new Error(`MoQ track write failed for every subscriber: ${n}${u}`)}}};return this.activePublishers.set(n,s),s}close(){if(!this.closed){this.closed=true;for(let e of this.namespaces.values()){for(let t of e.subscribers.values())for(let n of t)n.close();e.broadcast.close();}this.namespaces.clear(),this.activePublishers.clear();}}async acceptTrackRequests(e,t){try{for(;!this.closed;){let n=await t.broadcast.requested();if(!n)return;if(!this.resolveTrackId(e,n.track.name)||this.totalSubscriberCount()>=this.maxSubscribedTracks){n.track.close(new Error("track subscription rejected"));continue}let o=t.subscribers.get(n.track.name);o||(o=new Set,t.subscribers.set(n.track.name,o)),o.add(n.track);let s=o;n.track.closed.finally(()=>{s.delete(n.track),s.size===0&&t.subscribers.delete(n.track.name);});}}catch(n){this.closed||console.warn("[MoQ] Draft 14 publisher loop failed",n);}}totalSubscriberCount(){let e=0;for(let t of this.namespaces.values())for(let n of t.subscribers.values())e+=n.size;return e}resolveTrackId(e,t){if(typeof e!="string"||typeof t!="string")return null;let n=e.trim();if(!n||!t.trim())return null;let i=`${n}/${t}`;return i.length<=this.maxTrackIdChars?i:null}};var Ht=class{constructor(e,t,n={}){this.session=e;this.onObject=t;this.subscriptions=new Map;this.closed=false;this.maxSubscriptions=n.maxPendingSubscriptions??128,this.maxSubscribeRetries=n.maxSubscribeRetries??120,this.subscribeRetryDelayMs=n.subscribeRetryDelayMs??250,this.maxObjectPayloadBytes=n.maxObjectPayloadBytes??4*1024*1024,this.onSubscriptionTerminated=n.onSubscriptionTerminated;}async subscribe(e,t){let n=e.trim();if(!n||!t.trim())throw new Error("MoQ subscribe namespace and name must be non-empty");let i=`${n}\0${t}`;if(this.subscriptions.has(i))return;if(this.subscriptions.size>=this.maxSubscriptions)throw new Error(`MoQ subscription limit exceeded (${this.maxSubscriptions})`);let o={broadcast:null,track:null,cancelled:false};this.subscriptions.set(i,o),d$2(`[MoQ] Draft 14 subscription opened: ${n}/${t}`),this.consume(i,n,t,o);}close(){if(!this.closed){this.closed=true;for(let e of this.subscriptions.values())e.cancelled=true,e.track?.close(),e.broadcast?.close();this.subscriptions.clear();}}async consume(e,t,n,i){let o=0,s=null;for(;!this.closed&&!i.cancelled;){let a=this.session.requireConnection().consume($e.Path.from(t)),c=a.subscribe(n,0);i.broadcast=a,i.track=c;try{for(;!this.closed&&!i.cancelled;){let d=await c.readFrameSequence();if(!d)throw new Error("MoQ Draft 14 subscription closed");if(o=0,d.data.byteLength>this.maxObjectPayloadBytes)throw new Error(`MoQ object payload length exceeds limit: ${d.data.byteLength}`);this.onObject(t,n,d.data,{groupId:d.group,objectId:d.frame});}}catch(d){o+=1;let l=d instanceof Error&&/payload length exceeds limit/i.test(d.message);if(this.closed||i.cancelled||l||o>this.maxSubscribeRetries){!this.closed&&!i.cancelled&&(console.warn("[MoQ] Draft 14 subscription failed",d),s=d);break}d$2(`[MoQ] Draft 14 subscription retry ${o}/${this.maxSubscribeRetries}: ${t}/${n}`);}finally{c.close(),a.close(),i.track===c&&(i.track=null),i.broadcast===a&&(i.broadcast=null);}!this.closed&&!i.cancelled&&await new Promise(d=>setTimeout(d,this.subscribeRetryDelayMs));}if(this.subscriptions.get(e)===i&&this.subscriptions.delete(e),s!==null&&!this.closed&&!i.cancelled)try{this.onSubscriptionTerminated?.(t,n,s);}catch(a){console.warn("[MoQ] Subscription termination observer failed",a);}}};var Me=class{constructor(e,t=()=>{},n=3,i=new URL("https://localhost/"),o={}){this.transport=e;this.relayUrl=i;this.setupComplete=false;this.connection=null;this.closeListeners=[];this.closed=false;this.closeEmitted=false;this.setupResolve=null;if(n!==3)throw new Error("MoQ Draft 14 adapter requires the bidirectional publisher/subscriber role");this.setupPromise=new Promise(s=>{this.setupResolve=s;}),this.publisher=new Ot(this),this.subscriber=new Ht(this,t,{onSubscriptionTerminated:o.onSubscriptionTerminated});}requireConnection(){if(this.closed||!this.connection||!this.setupComplete)throw new Error("MoQ Draft 14 session is not ready");return this.connection}async openDatagramDuplex(e,t,n){let i=e.trim(),o=t.trim(),s=n.trim();if(!i||!o||!s)throw new Error("MoQ carrier namespaces and track name must be non-empty");let a=this.requireConnection();if(typeof a.openDatagramDuplex!="function")throw new Error("MoQ Draft 14 object datagrams are unavailable in this build");return a.openDatagramDuplex($e.Path.from(i),$e.Path.from(o),s)}async init(){if(this.closed)throw new Error("MoQ session closed");if(this.connection)return;await this.transport.ready;let e=await $e.Connection.connect(this.relayUrl,{transport:this.transport,websocket:{enabled:false}});if(e.version!=="moq-transport-14")throw e.close(),new Error(`MoQ relay negotiated unsupported protocol ${e.version}`);if(this.closed){e.close();return}this.connection=e,this.setupComplete=true,this.setupResolve?.(),this.setupResolve=null,e.closed.then(()=>this.emitClose("relay-session-closed"),t=>this.emitClose(t));}waitForSetup(){return this.setupPromise}onClose(e){return this.closeListeners.push(e),()=>{this.closeListeners=this.closeListeners.filter(t=>t!==e);}}close(){if(!this.closed){this.closed=true,this.publisher.close(),this.subscriber.close();try{this.connection?.close();}catch{}this.connection=null;try{this.transport.close();}catch{}this.emitClose("local-close");}}emitClose(e){if(!this.closeEmitted){this.closeEmitted=true,this.closed=true,this.setupComplete=false,this.publisher.close(),this.subscriber.close(),this.connection=null;for(let t of [...this.closeListeners])try{t(e);}catch{}}}};var yr="#openrtc-moq-route-proof",vr=1,ta=512,na=750,ia=8;function Cr(r){if(r.byteLength===0||r.byteLength>ta)return null;try{let e=JSON.parse(new TextDecoder().decode(r));return e.type!==yr||e.version!==vr||e.role!=="probe"&&e.role!=="ack"||typeof e.probeId!="string"||!/^[A-Za-z0-9_-]{8,64}$/.test(e.probeId)||typeof e.senderId!="string"||e.senderId.length===0||e.senderId.length>128||typeof e.recipientId!="string"||e.recipientId.length===0||e.recipientId.length>128?null:e}catch{return null}}function oa(r){return new TextEncoder().encode(JSON.stringify(r))}function ra(){if(typeof globalThis.crypto?.randomUUID=="function")return globalThis.crypto.randomUUID().replace(/-/g,"");let r=new Uint8Array(16);return globalThis.crypto?.getRandomValues?.(r),r.some(e=>e!==0)?Array.from(r,e=>e.toString(16).padStart(2,"0")).join(""):`${Date.now().toString(36)}${Math.random().toString(36).slice(2,18)}`}var qt=class{constructor(e){this.deps=e;this.states=new Map;}request(e){let t=this.deps.getCurrentSession(),n=this.deps.getLocalNodeId();if(!t||!this.deps.isCurrentSession(t)||!n||e.isClosed||!e.peerMoQReady)return;let i=this.states.get(e.id);(!i||i.session!==t||i.peerId!==e.remoteNodeId||i.connection!==e)&&(this.clear(e.id),i=this.createState(e,t,e.remoteNodeId)),!i.proven&&!i.inFlight&&!i.retryTimer&&this.schedule(e,i,0);}requestForPeer(e){let t=this.deps.getConnectionById(this.deps.getDeterministicConnectionId(e));t&&this.request(t);}isProven(e){let t=this.deps.getDeterministicConnectionId(e),n=this.states.get(t),i=this.deps.getConnectionById(t);return !!n&&n.proven&&n.peerId===e&&n.connection===i&&this.deps.isCurrentSession(n.session)}handle(e,t,n,i){let o=this.deps.getLocalNodeId();if(!(!o||i.senderId!==t||i.recipientId!==o)){if(i.role==="ack"){let s=this.states.get(n.id);s&&s.session===e&&s.connection===n&&s.peerId===t&&s.probeId===i.probeId&&this.markProven(n,s,"matching-protected-ack");return}this.ensureState(n,e,t),this.send(n,e,{...i,role:"ack",senderId:o,recipientId:t}).catch(s=>{c$1("[Client] MoQ protected route ACK failed",{connectionId:n.id,error:s});});}}clearForPeer(e){this.clear(this.deps.getDeterministicConnectionId(e));}clear(e){let t=this.states.get(e);t?.retryTimer&&clearTimeout(t.retryTimer),this.states.delete(e);}clearAll(){for(let e of [...this.states.keys()])this.clear(e);}createState(e,t,n){let i={session:t,connection:e,peerId:n,probeId:ra(),attempts:0,inFlight:false,proven:false,retryTimer:null};return this.states.set(e.id,i),i}ensureState(e,t,n){let i=this.states.get(e.id);return i&&i.session===t&&i.connection===e&&i.peerId===n?i:(this.clear(e.id),this.createState(e,t,n))}schedule(e,t,n){t.retryTimer||t.proven||t.attempts>=ia||(t.retryTimer=setTimeout(()=>{t.retryTimer=null,this.sendProbe(e,t);},n));}async sendProbe(e,t){if(t.inFlight||t.proven||e.isClosed||!e.peerMoQReady||this.states.get(e.id)!==t||!this.deps.isCurrentSession(t.session))return;let n=this.deps.getLocalNodeId();if(n){t.inFlight=true,t.attempts+=1;try{await this.send(e,t.session,{type:yr,version:vr,role:"probe",probeId:t.probeId,senderId:n,recipientId:e.remoteNodeId});}catch(i){c$1("[Client] MoQ protected route probe failed",{connectionId:e.id,attempt:t.attempts,error:i});}finally{t.inFlight=false;}!t.proven&&this.states.get(e.id)===t&&this.deps.isCurrentSession(t.session)&&this.schedule(e,t,na);}}async send(e,t,n){if(!this.deps.isCurrentSession(t))throw new Error("MoQ route proof session was replaced");let i=this.deps.protectDirectPayload(oa(n),e.remoteNodeId,e);if(!x$1(i))throw new Error("MoQ route proof requires application crypto");if(await this.deps.sendProtectedData(e.remoteNodeId,i),!this.deps.isCurrentSession(t))throw new Error("MoQ route proof session changed during send")}markProven(e,t,n){if(t.proven||t.connection!==e||this.deps.getConnectionById(e.id)!==e||this.states.get(e.id)!==t)return;let i=e.getTransportStatus();t.proven=true,t.retryTimer&&(clearTimeout(t.retryTimer),t.retryTimer=null),c$1("[Client] MoQ application route proven",{connectionId:e.id,reason:n}),this.deps.publishTransportStatus(e,"moq",i.activeTransport==="moq"?i.parallelTransport??null:i.activeTransport);}};var sa=5e3,aa=125,ca=8;function jt(r,e){return `${r.trim()}/${e.trim()}`}function la(r,e){let t=r.trim(),i=`/${e.trim()}`;return t.endsWith(i)?t.slice(0,-i.length).trim()||null:t||null}var Gt=class{constructor(e,t){this.ctx=e;this.deps=t;this.session=null;this.state="none";this.readyListeners=[];this.failedListeners=[];this.objectListeners=[];this.reconnectTimer=null;this.reconnectAttempts=0;this.reconnectCircuitOpen=false;this.peerSubscriptions=new Set;this.disposed=false;this.routeProofController=new qt({getLocalNodeId:()=>this.ctx.localNodeId,getCurrentSession:()=>this.session,isCurrentSession:n=>this.isCurrentSession(n),getDeterministicConnectionId:n=>this.deps.getDeterministicConnectionId(n),getConnectionById:n=>this.deps.getConnectionById(n),protectDirectPayload:(n,i,o)=>this.deps.protectDirectPayload(n,i,o),sendProtectedData:(n,i)=>this.sendDataInternal(n,i,{alreadyProtected:true,allowUnprovenRoute:true}),publishTransportStatus:(n,i,o)=>this.deps.handleCurrentConnectionTransportStatus(n,i,o)}),this.ctx.registerDisposer(()=>this.dispose());}get bundle(){return this.state!=="ready"||!this.session?null:{session:this.session,publisher:this.session.publisher,subscriber:this.session.subscriber}}onReady(e){return this.disposed?()=>{}:(this.readyListeners.push(e),()=>{this.readyListeners=this.readyListeners.filter(t=>t!==e);})}onFailed(e){return this.disposed?()=>{}:(this.failedListeners.push(e),()=>{this.failedListeners=this.failedListeners.filter(t=>t!==e);})}onObject(e){return this.disposed?()=>{}:(this.objectListeners.push(e),()=>{this.objectListeners=this.objectListeners.filter(t=>t!==e);})}clearReconnectTimer(){this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null);}closeSession(e){let t=this.session;if(this.session=null,this.peerSubscriptions.clear(),this.routeProofController.clearAll(),!!t)try{t.close();}catch(n){c$1("[Client] MoQ session close failed",{reason:e,error:this.redactedDiagnostic(n)});}}dispose(){this.disposed=true,this.clearReconnectTimer(),this.closeSession("client-dispose"),this.state="none",this.readyListeners=[],this.failedListeners=[],this.objectListeners=[];}handleSessionClosed(e,t){this.disposed||this.session===e&&(this.session=null,this.state="failed",this.peerSubscriptions.clear(),this.routeProofController.clearAll(),this.emitFailed(),c$1("[Client] MoQ session closed; evaluating bounded reconnect",{reason:this.redactedDiagnostic(t)}),this.scheduleReconnect(t));}scheduleReconnect(e){if(this.disposed||!this.deps.getMoQConfig()||this.reconnectTimer)return;if(this.reconnectAttempts>=this.deps.maxReconnectAttempts){this.reconnectCircuitOpen||(this.reconnectCircuitOpen=true,c$1("[Client] MoQ reconnect circuit opened",{attempts:this.reconnectAttempts,reason:this.redactedDiagnostic(e)}));return}let t=Math.min(this.deps.initialReconnectDelayMs*Math.max(1,2**this.reconnectAttempts),this.deps.maxReconnectDelayMs);this.reconnectAttempts+=1;let n=(this.reconnectAttempts*17%21-10)/100,i=Math.max(this.deps.initialReconnectDelayMs,Math.trunc(t+t*n));this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=null,!(this.disposed||!this.deps.getMoQConfig()||this.state==="ready"||this.state==="connecting")&&(d$2(`[Client] Reconnecting MoQ relay after ${i}ms`,this.redactedDiagnostic(e)),this.init());},i);}enableForConnection(e){this.state!=="ready"||!this.bundle||(e.peerMoQReady=true,this.subscribePeer(e));}subscribePeer(e){this.subscribePeerNode(e.remoteNodeId,e.id,()=>e.isClosed),this.routeProofController.request(e);}forgetPeerSubscription(e){this.peerSubscriptions.delete(e),this.routeProofController.clear(e);}isApplicationRouteProven(e){return this.routeProofController.isProven(e)}requestApplicationRouteProofForPeer(e){this.routeProofController.requestForPeer(e);}clearApplicationRouteProofForPeer(e){this.routeProofController.clearForPeer(e);}subscribePeerNode(e,t=e,n){if(this.disposed)return;let i=this.bundle,o=e?.trim(),s=t?.trim()||o;!i||!this.ctx.localNodeId||!o||!s||n?.()||this.peerSubscriptions.has(s)||(this.peerSubscriptions.add(s),this.subscribePeerNodeInBackground(i,o,s));}resubscribePeers(){this.peerSubscriptions.clear(),this.ctx.registry.forEach(e=>{!e.isClosed&&e.peerMoQReady&&this.subscribePeer(e);});}async init(){if(this.disposed||!this.deps.getMoQConfig()||this.state==="ready"||this.state==="connecting")return;this.clearReconnectTimer(),this.closeSession("init"),this.state="connecting";let e=this.deps.getMoQConfig(),t=e&&typeof e=="object"?{...this.deps.getDefaultMoQConfig(),...e}:{...this.deps.getDefaultMoQConfig()},n=t.relayUrl?.trim();if(!n){this.state="failed",this.emitFailed(),console.warn("[Client] MoQ is enabled without a relay URL; configure transports.moq.relayUrl explicitly.");return}let i=t.serverCertificateHashes?.length?{serverCertificateHashes:t.serverCertificateHashes}:void 0,o;try{o=k$2(n,t.accessToken);}catch(c){this.state="failed",this.emitFailed(),console.warn("[Client] MoQ configuration rejected:",m$1(c,t.accessToken));return}let s=l$1(n),a=null;try{let c=new WebTransport(o,i);if(await c.ready,this.disposed){try{c.close?.();}catch{}return}let d;if(d=new Me(c,(l,p,u,h)=>{this.handleObject(d,l,p,u,h);},3,new URL(n),{onSubscriptionTerminated:(l,p,u)=>this.handleSubscriptionTerminated(d,l,p,u)}),a=d,this.session=a,a.onClose(l=>this.handleSessionClosed(a,l)),await a.init(),this.disposed){a.close();return}if(await a.waitForSetup(),this.disposed||this.session!==a){a.close();return}if(await a.publisher.announce(this.ctx.localNodeId),this.disposed||this.session!==a){a.close();return}if(await this.createDataTracks(),this.disposed||this.session!==a){a.close();return}this.state="ready",this.reconnectAttempts=0,this.reconnectCircuitOpen=!1,this.peerSubscriptions.clear(),d$2(`[Client] MoQ Session Ready: Pub/Sub via ${s}`),this.emitReady(),this.resubscribePeers(),this.broadcastReadyCapabilityInBackground();}catch(c){if(this.disposed){a&&this.session===a&&(this.session=null),a?.close();return}console.warn("[Client] MoQ init failed:",m$1(c,t.accessToken)),this.session===a&&(this.session=null),a?.close(),this.state="failed",this.emitFailed(),this.scheduleReconnect(c);}}redactedDiagnostic(e){let t=this.deps.getMoQConfig(),n=t&&typeof t=="object"?t.accessToken:void 0;return m$1(e,n)}async createDataTracks(){if(!this.disposed&&!(!this.session||!this.ctx.localNodeId))try{await this.session.publisher.createTrack(this.ctx.localNodeId,"data/broadcast"),d$2("[Client] MoQ Data Track created: data / broadcast");}catch(e){console.warn("Failed to create MoQ broadcast track",e);}}isDataReady(e){let t=this.bundle;if(!t||!this.ctx.localNodeId)return false;let n=e?`data / ${e} `:"data / broadcast",i=e?jt(this.ctx.localNodeId,e):this.ctx.localNodeId;return t.publisher.hasTrackSubscriber(i,n)}async sendData(e,t,n={}){return this.sendDataInternal(e,t,n)}async sendDataInternal(e,t,n={}){if(this.disposed)throw new Error("MoQ not ready");let i=this.bundle;if(!i)throw new Error("MoQ not ready");if(e&&n.allowUnprovenRoute!==true&&!this.isApplicationRouteProven(e))throw this.requestApplicationRouteProofForPeer(e),new Error(`MoQ application route is not proven for peer: ${e}`);let o=e?`data / ${e} `:"data / broadcast";if(!await this.waitForStableDataReady(e,i.session))throw this.isCurrentSession(i.session)?new Error(`MoQ data track is not subscribed: ${o}`):new Error("MoQ not ready");if(!this.isCurrentSession(i.session))throw new Error("MoQ not ready");let s=e?jt(this.ctx.localNodeId,e):this.ctx.localNodeId,a=await i.publisher.createTrack(s,o);if(!a)return;if(!this.isCurrentSession(i.session))throw new Error("MoQ not ready");let c=Date.now(),d=n.alreadyProtected?t:this.deps.protectDirectPayload(t,e??void 0),l=e?this.deps.getConnectionById(this.deps.getDeterministicConnectionId(e)):void 0;try{await a.push(d,{isKey:!0,timestamp:c,closeAfterPush:!0});}catch(p){if(e&&this.isCurrentSession(i.session)&&(this.routeProofController.clearForPeer(e),l&&!l.isClosed)){let u=l.getTransportStatus();this.deps.handleCurrentConnectionTransportStatus(l,u.activeTransport,u.parallelTransport??null);}throw p}if(this.isCurrentSession(i.session)&&l&&!l.isClosed&&this.isApplicationRouteProven(e)){let p=typeof l.getTransportStatus=="function"?l.getTransportStatus():null;this.deps.handleCurrentConnectionTransportStatus(l,"moq",p?.parallelTransport??null);}}async waitForStableDataReady(e$1,t){let n=Date.now(),i=0;for(;this.isCurrentSession(t);){if(this.isDataReady(e$1)){if(i+=1,i>=ca)return true}else i=0;if(Date.now()-n>=sa)return false;await e(aa);}return false}isCurrentSession(e){return !this.disposed&&this.state==="ready"&&this.session===e}handleSubscriptionTerminated(e,t,n,i){this.isCurrentSession(e)&&(c$1("[Client] MoQ subscription exhausted; replacing relay session",{namespace:t,name:n,error:i}),e.close(),this.session===e&&this.handleSessionClosed(e,i));}extractTrackPeerId(e){let t=e.replace(/\s+/g,"");if(!t.startsWith("data/"))return;let n=t.slice(5);if(!(!n||n==="broadcast"))return n}handleObject(e,t,n,i,o){if(!this.isCurrentSession(e))return;let s=la(t,this.ctx.localNodeId??"");if(!s)return;let a=this.deps.getConnectionById(this.deps.getDeterministicConnectionId(s)),c=this.deps.openDirectPayload(i,s);if(!c.encrypted||!c.payload)return;let d=c.proofEligible?Cr(c.payload):null;if(d){a&&!a.isClosed&&this.routeProofController.handle(e,s,a,d);return}a&&!a.isClosed&&typeof a.receiveDataPayload=="function"&&a.receiveDataPayload(c.payload),this.emitObject(s,n,c.payload,o);}emitReady(){for(let e of [...this.readyListeners])try{e();}catch(t){console.warn("[Client] MoQ ready listener failed",t);}}subscribePeerNodeInBackground(e,t,n){let i=()=>{this.peerSubscriptions.delete(n);};try{let o=this.ctx.localNodeId,s=jt(o,t),a=jt(t,o);(async()=>{e.publisher.hasNamespace(s)||await e.publisher.announce(s),await e.subscriber.subscribe(a,`data / ${o} `);})().then(()=>{this.disposed;}).catch(()=>{i();});}catch{i();}}broadcastReadyCapabilityInBackground(){try{Promise.resolve(this.deps.broadcastTransportCapabilityUpdate("moq-ready")).catch(e=>{this.disposed||c$1("[Client] Late MoQ capability update failed",e);});}catch(e){if(this.disposed)return;c$1("[Client] Late MoQ capability update failed",e);}}emitFailed(){for(let e of [...this.failedListeners])try{e();}catch(t){console.warn("[Client] MoQ failed listener failed",t);}}emitObject(e,t,n,i){for(let o of [...this.objectListeners])try{o(e,t,n,i);}catch(s){console.warn("[Client] MoQ object listener failed",s);}}};function Ir(r){return new yi({getContext:()=>r.getClientContext(),getOptions:()=>r.options,getDeterministicConnectionId:e=>r.peerIdentity.getDeterministicConnectionId(e),getConnectionById:e=>r.registry.get(e),protectDirectPayload:(e,t,n)=>r.applicationCrypto.protectDirectMoQPayload(e,t,n),openDirectPayload:(e,t,n)=>r.applicationCrypto.openDirectMoQPayload(e,t,n),handleCurrentConnectionTransportStatus:(e,t,n)=>r.transportHealth.handleCurrentConnectionTransportStatus(e,t,n),broadcastTransportCapabilityUpdate:e=>r.transportHandshake.broadcastTransportCapabilityUpdate(e)})}var yi=class{constructor(e){this.host=e;}get controller(){return this._controller||(this._controller=new Gt(this.host.getContext(),{getMoQConfig:()=>this.host.getOptions()?.transports?.moq,getDefaultMoQConfig:()=>({...j$1}),getDeterministicConnectionId:e=>this.host.getDeterministicConnectionId(e),getConnectionById:e=>this.host.getConnectionById(e),protectDirectPayload:(e,t,n)=>this.host.protectDirectPayload(e,t,n),openDirectPayload:(e,t,n)=>this.host.openDirectPayload(e,t,n),handleCurrentConnectionTransportStatus:(e,t,n)=>this.host.handleCurrentConnectionTransportStatus(e,t,n),broadcastTransportCapabilityUpdate:e=>this.host.broadcastTransportCapabilityUpdate(e),initialReconnectDelayMs:jo,maxReconnectDelayMs:Go,maxReconnectAttempts:Ko})),this._controller}get state(){return this._controller?.state??"none"}get bundle(){return this._controller?.bundle??null}init(){return this.controller.init()}onReady(e){return this.controller.onReady(e)}onFailed(e){return this.controller.onFailed(e)}onObject(e){return this.controller.onObject(e)}isReady(){return this._controller?.state==="ready"}isDataReady(e){return this._controller?.isDataReady(e)??false}isApplicationRouteProven(e){return this._controller?.isApplicationRouteProven(e)??false}requestApplicationRouteProof(e){this._controller?.requestApplicationRouteProofForPeer(e);}clearApplicationRouteProof(e){this._controller?.clearApplicationRouteProofForPeer(e);}enableForConnection(e){this.controller.enableForConnection(e);}subscribePeerNode(e,t){this.controller.subscribePeerNode(e,t);}forgetPeerSubscription(e){this._controller?.forgetPeerSubscription(e);}sendData(e,t,n){return this.controller.sendData(e,t,n)}};function ce(){if(typeof navigator>"u")return false;let r=navigator.userAgent||"",e=navigator.userAgentData?.platform||navigator.platform||"";return /iPhone|iPad|iPod|Android|Mobile|CriOS|FxiOS/i.test(`${r} ${e}`)}function Kt(){return typeof window>"u"?false:new URLSearchParams(window.location.search).has("ticket")}function zt(r){return r?r.routing==="stream-envelope"&&r.readiness==="transport-only":false}function Ye(r){let e=r.signalingMode??"hosted",t=ce(),n=Kt(),i=e==="ticket-only",o=i&&t;return {flow:i?"ticket-only":"default",signalingMode:e,mobileBrowser:t,ticketQueryPresent:n,diagnosticsMode:o,skipIncomingBiProbe:o,skipIncomingChannelEnvelopeInspection:o,readerCloseStrategy:o?"release-lock":"cancel"}}var Vt=class Vt{constructor(e){this.deps=e;this.pendingReciprocalAdmissions=new Map;this.reciprocalConfirmationsInFlight=new Set;this.legacyReciprocalPresentationsInFlight=new Set;this.disposed=false;}dispose(){this.disposed=true,this.retirePendingReciprocalAdmissions("dispose"),this.legacyReciprocalPresentationsInFlight.clear();}retirePendingReciprocalAdmissions(e){this.pendingReciprocalAdmissions.size>0&&c$1("[Client][AUTH] retiring pending reciprocal admissions",{reason:e,count:this.pendingReciprocalAdmissions.size}),this.pendingReciprocalAdmissions.clear(),this.reciprocalConfirmationsInFlight.clear();}async acceptNativeMessage(e,t,n){if(this.disposed||!t)return false;let i=this.deps.getDeterministicConnectionId(t),o=this.deps.getConnection(i);if(o){try{Promise.resolve(this.deps.handleMessage(o,n)).catch(s=>{this.disposed||console.warn("[Client][NATIVE-MAIN] Existing connection message handling failed",{remoteNodeId:t,connectionId:o.id,error:s});});}catch(s){this.disposed||console.warn("[Client][NATIVE-MAIN] Existing connection message handling failed",{remoteNodeId:t,connectionId:o.id,error:s});}return false}if(n&&typeof n=="object"&&n.type==="handshake"&&(n.action==="hello"||!n.action)){let s=await this.deps.validateIncomingSessionToken(n.sessionToken??"",e??void 0,{remoteNodeId:t,source:"accept-native-message",tokenPayload:typeof n.sessionTokenPayload=="string"?n.sessionTokenPayload:void 0});if(this.disposed)return false;if(!s.ok)return console.warn("[Client][SESSION-TOKEN] Rejecting native connection \u2014 invalid session token",{remoteNodeId:t,reason:s.reason,hasToken:!!n.sessionToken}),true}return false}async resolveLocalHandshakePayload(){let e=await this.deps.getLocalDeviceId().catch(()=>null)||this.deps.getFallbackLocalDeviceId();if(!e)throw new Error("Local device id unavailable for native handshake response");let t=this.deps.isNativeRuntime(),n=t?this.deps.isLikelyMobileBrowser()?"mobile":"desktop":"web",i=t?{canHost:true,canSync:true,readOnly:false}:{canHost:false,canSync:true,readOnly:false},o=n==="mobile"?"Mobile Device":n==="desktop"?"Desktop Device":"Browser Device";return {deviceId:e,deviceName:this.deps.getConfiguredDeviceName()||o,platformType:n,capabilities:i,protocolVersion:this.deps.getNativeMainProtocolVersion(),timestamp:Date.now()}}async handleHandshakeRequest(e,t,n){if(this.disposed)return;let i=await this.resolveLocalHandshakePayload();this.disposed||(await this.deps.writeNativeMainMessage(e,{channel:"handshake",action:"response",requestId:n.requestId,payload:{accepted:true,...i},timestamp:Date.now()}),!this.disposed&&(this.schedulePeerReconciliationBestEffort("native-main-handshake"),c$1("[Client][NATIVE-MAIN] Responded to desktop handshake",{remoteNodeId:t,requestId:n.requestId??null,localDeviceId:i.deviceId})));}async handleSessionTokenRequest(e,t,n,i,o){if(this.disposed)return;let s=this.deps.getSessionTokenRejectionCooldown(t),a=this.deps.getNativeMainConnectionId(t);if(s!==void 0&&Date.now()-s<Vt.TOKEN_REJECTION_COOLDOWN_MS){await this.deps.writeNativeMainMessage(e,{channel:"session-token",action:"response",requestId:n.requestId,payload:{approved:false,reason:"session-token-rejection-cooldown",connectionId:a},timestamp:Date.now()}),console.warn("[Client][AUTH] session-token presentation during rejection cooldown \u2014 wrote rejection for dialer",{remoteNodeId:t,connectionId:a});return}let c=n.payload&&typeof n.payload.token=="string"?n.payload.token.trim():"",d=n.payload&&typeof n.payload.tokenPayload=="string"?n.payload.tokenPayload.trim():void 0,l=await this.deps.validateIncomingSessionToken(c,a,{remoteNodeId:t,source:"native-main-session-token",tokenPayload:d||void 0});if(this.disposed)return;let p,u=n.payload?.reciprocalRequested===true,h=u&&n.payload?.reciprocalMode==="inline-v1"&&Number.isSafeInteger(i)&&Number(i)>0&&typeof o=="string"&&o.trim().length>0;if(l.ok&&h){let m=n.payload?.streamContract==="persistent-control"?"persistent-control":"one-shot-admission";try{let f=this.createPresentationId();p={...await this.deps.getReciprocalSessionAdmission(t,m,Number(i),o,f),presentationId:f};}catch(f){this.disposed||console.warn("[Client][AUTH] reciprocal session admission unavailable",{remoteNodeId:t,connectionId:a,error:f});}}if(!this.disposed&&(await this.deps.writeNativeMainMessage(e,l.ok?{channel:"session-token",action:"response",requestId:n.requestId,payload:{approved:true,scope:l.scope??null,connectionId:a,...p?{reciprocalPresentation:p}:{},...p?{reciprocalMode:"inline-v1"}:{}},timestamp:Date.now()}:{channel:"session-token",action:"response",requestId:n.requestId,payload:{approved:false,reason:l.reason??"session-token-rejected",connectionId:a},timestamp:Date.now()}),!this.disposed)){if(l.ok&&p&&i){for(let[m,f]of this.pendingReciprocalAdmissions)f.remoteNodeId===t&&f.transportStableId===i&&this.pendingReciprocalAdmissions.delete(m);this.pendingReciprocalAdmissions.set(p.presentationId,{connectionId:a,remoteNodeId:t,transportStableId:i,streamInstanceId:o,presentationId:p.presentationId});}if(l.ok){let m=this.deps.getConnection(a);m&&!m.isClosed?this.deps.applySessionTokenTrustApproval(m,l.scope??null,"native-main-session-token"):(this.deps.rememberPendingSessionTokenTrustApproval(a,l.scope??null),this.deps.markSessionTokenApprovedNode(t),this.deps.markSessionTokenApprovedConnection(a)),this.deps.clearSessionTokenRejectionCooldown(t),this.deps.clearTrustFailureCooldown(t),c$1("[Client][AUTH] host approved managed session token",{remoteNodeId:t,connectionId:a,scope:l.scope??null}),this.schedulePeerReconciliationBestEffort("session-token-approval"),u&&(!h||!p)&&this.scheduleLegacyReciprocalSessionAdmission(t,a),(!m||m.isClosed)&&this.kickstartApprovedControlConnection(t,a);return}console.warn("[Client][AUTH] host rejected managed session token",{remoteNodeId:t,connectionId:a,reason:l.reason??"session-token-rejected",hasToken:c.length>0}),this.deps.setSessionTokenRejectionCooldown(t,Date.now()),this.deps.disconnectRemoteNode(t);}}async handleSessionTokenResponseAck(e,t,n,i){let o=typeof t.payload?.reciprocalPresentationId=="string"?t.payload.reciprocalPresentationId.trim():"";if(!o||!Number.isSafeInteger(n)||Number(n)<=0)return false;let s=this.pendingReciprocalAdmissions.get(o);if(!s||s.remoteNodeId!==e||s.transportStableId!==n||s.streamInstanceId!==i||t.payload?.connectionId!==s.connectionId)return console.warn("[Client][AUTH] ignored stale reciprocal admission ACK",{remoteNodeId:e,transportStableId:n??null,presentationId:o}),false;if(this.reciprocalConfirmationsInFlight.has(o))return true;this.reciprocalConfirmationsInFlight.add(o);let a=t.payload?.reciprocalAccepted===true,c=typeof t.payload?.reciprocalScope=="string"&&t.payload.reciprocalScope.trim()||null,d=false;try{d=await this.deps.confirmReciprocalSessionAdmission(e,n,s.streamInstanceId,s.presentationId,a,c);}catch(l){console.warn("[Client][AUTH] reciprocal admission confirmation failed",{remoteNodeId:e,transportStableId:n,presentationId:o,error:l});}finally{this.reciprocalConfirmationsInFlight.delete(o);}return d&&this.pendingReciprocalAdmissions.delete(o),a?d?(c$1("[Client][AUTH] reciprocal admission committed",{remoteNodeId:e,transportStableId:n,presentationId:o,approvalScope:c}),this.schedulePeerReconciliationBestEffort("reciprocal-session-admission-committed"),true):(console.warn("[Client][AUTH] reciprocal admission ACK failed generation-bound confirmation",{remoteNodeId:e,transportStableId:n,presentationId:o}),this.schedulePeerReconciliationBestEffort("reciprocal-session-admission-stale"),true):(console.warn("[Client][AUTH] reciprocal admission was not committed by peer",{remoteNodeId:e,transportStableId:n,presentationId:o,reason:t.payload?.reciprocalReason??"rejected"}),this.schedulePeerReconciliationBestEffort("reciprocal-session-admission-rejected"),true)}handleNativeMainStreamClosed(e,t,n){if(!(!Number.isSafeInteger(t)||Number(t)<=0))for(let[i,o]of this.pendingReciprocalAdmissions)o.remoteNodeId===e&&o.transportStableId===t&&o.streamInstanceId===n&&(this.pendingReciprocalAdmissions.delete(i),this.reciprocalConfirmationsInFlight.delete(i));}createPresentationId(){let e=globalThis.crypto?.randomUUID;return typeof e=="function"?e.call(globalThis.crypto):`reciprocal-${Date.now()}-${Math.random().toString(36).slice(2)}`}scheduleLegacyReciprocalSessionAdmission(e,t){this.disposed||this.legacyReciprocalPresentationsInFlight.has(t)||(this.legacyReciprocalPresentationsInFlight.add(t),queueMicrotask(()=>{if(this.disposed){this.legacyReciprocalPresentationsInFlight.delete(t);return}this.deps.presentLegacyReciprocalSessionAdmission(e).catch(n=>{this.disposed||console.warn("[Client][AUTH] legacy reciprocal session admission failed",{remoteNodeId:e,connectionId:t,error:n});}).finally(()=>{this.legacyReciprocalPresentationsInFlight.delete(t);});}));}kickstartApprovedControlConnection(e,t){let n=i=>{this.disposed||console.warn("[Client][AUTH] post-approval kickstart error",{remoteNodeId:e,connectionId:t,error:i});};try{Promise.resolve(this.deps.ensureIncomingConnectionForRemoteNode(e)).then(i=>{this.disposed||(i?c$1("[Client][AUTH] post-approval kickstart opened control connection",{remoteNodeId:e,connectionId:i.id}):console.warn("[Client][AUTH] post-approval kickstart failed to open control connection",{remoteNodeId:e,connectionId:t}));}).catch(n);}catch(i){n(i);}}schedulePeerReconciliationBestEffort(e){if(!this.disposed)try{Promise.resolve(this.deps.schedulePeerReconciliation(e)).catch(()=>{});}catch{}}};Vt.TOKEN_REJECTION_COOLDOWN_MS=5e3;var Qt=Vt;var $t=class{constructor(e){this.deps=e;this.pendingConnections=new Map;this.disposed=false;}dispose(){this.disposed=true,this.pendingConnections.clear();}async ensureIncomingConnectionForRemoteNode(e){if(this.disposed)return null;let t=this.deps.getDeterministicConnectionId(e),n=this.deps.getConnection(t);if(n&&!n.isClosed)return this.attachNativeSignalSenderIfEligible(n,e),n;let i=this.pendingConnections.get(t);if(i)return i;let o=this.deps.getTrustFailureCooldown(e),s=this.deps.getTrustFailureCooldownMs();if(o!==void 0&&Date.now()-o<s&&!this.deps.isSessionTokenApprovedNode(e))return c$1("[Client][TRUST] Skipping connection rebuild for node in trust-failure cooldown",{remoteNodeId:e,cooldownRemainingMs:s-(Date.now()-o)}),null;let a=this.createIncomingConnection(t,e);this.pendingConnections.set(t,a);try{return await a}finally{this.pendingConnections.delete(t);}}attachNativeSignalSenderIfEligible(e,t){let n=typeof e.getControlFrameMode=="function"?e.getControlFrameMode():"typed";c$1("[Client][NATIVE-MAIN] Reusing existing control connection",{connectionId:e.id,remoteNodeId:t,upgradeState:typeof e.getUpgradeState=="function"?e.getUpgradeState():null,controlFrameMode:n});let i=this.deps.getKnownDevicePlatform(this.deps.getKnownDeviceIdForNode(t),t);if(!this.deps.isNativeMainPeerPlatform(i)&&!this.deps.isSessionTokenApprovedNode(t))return;let o=this.deps.getWasmClient();if(!o||typeof o.open_bi!="function")return;let s=async a=>{await this.deps.sendNativeSignalEnvelope(e,t,a,o);};n!=="native-main"&&typeof e.useNativeControl=="function"?(e.useNativeControl(s),c$1("[Client][NATIVE-MAIN] Promoted bootstrap connection to native control route",{connectionId:e.id,remoteNodeId:t})):n==="native-main"&&e.setNativeSignalSender(s);}async createIncomingConnection(e,t){if(this.disposed)return null;let n=this.deps.getWasmClient();if(!n||typeof n.open_bi!="function")return null;let i=this.deps.getKnownDeviceIdForNode(t);if(!this.deps.getKnownDevicePlatform(i,t)&&!this.deps.isSessionTokenApprovedNode(t))return c$1("[Client][NATIVE-MAIN] Deferring native-main connection creation until peer platform is known",{remoteNodeId:t,connectionId:e,knownDeviceId:i}),null;let s;try{s=await this.deps.openNativeSignalBiStream(n,t);}catch(c){return console.warn("[Client][NATIVE-MAIN] Failed to open control stream for native signal routing",{remoteNodeId:t,connectionId:e,error:c}),null}if(this.disposed)return await l$2(s,"native-main-connection-disposed-after-open"),null;try{await this.deps.writeNativeMainLabelHeaderOnBiStream(s,t);}catch(c){return console.warn("[Client][NATIVE-MAIN] Failed to write label header on control stream",{remoteNodeId:t,connectionId:e,error:c}),null}if(this.disposed)return await l$2(s,"native-main-connection-disposed-after-label"),null;let a;return a=new ie(e,this.deps.getLocalNodeId(),t,s.send.getWriter(),s.recv.getReader(),{rtcConfig:this.deps.getRTCConfig(),transportContext:this.deps.createTransportContext(t),applicationCrypto:this.deps.getApplicationCrypto(),requireApplicationCrypto:this.deps.shouldNegotiateApplicationKeyAgreement(),controlFrameMode:"native-main",onTransportStatusChange:c=>this.deps.handleConnectionTransportStatus(a,c.activeTransport,c.parallelTransport),onApplicationRouteMissing:c=>{this.deps.handleConnectionApplicationRouteMissing(e,c);}}),a.setNativeSignalSender(async c=>{await this.deps.sendNativeSignalEnvelope(a,t,c,n);}),this.deps.initializeConnectionTrust(a,i),this.deps.markConnectionTrustVerified(a,i),this.deps.registerConnection(a),this.deps.announceConnectionWhenStable(a),c$1("[Client][HANDSHAKE] sending hello (native signal routing path)",{connectionId:a.id,remoteNodeId:a.remoteNodeId}),this.sendNativeRoutingHelloInBackground(a),c$1("[Client][NATIVE-MAIN] Created control connection for native signal routing",{connectionId:a.id,remoteNodeId:t,channelId:this.deps.getConnectionChannelId(a.id)??null,rtcEnabled:this.deps.isWebRTCTransportEnabled()}),a}sendNativeRoutingHelloInBackground(e){let t=n=>{this.disposed||console.warn("[Client][TRUST] Failed to send outgoing handshake for native signal routing",{connectionId:e.id,remoteNodeId:e.remoteNodeId,error:n});};try{Promise.resolve(this.deps.sendTransportHandshake(e,"hello")).then(()=>{this.disposed||this.deps.requestProtectedWebRTCUpgradeIfInitiator(e,"protected-hello:native-signal-routing");}).catch(t);}catch(n){t(n);}}};var Yt=class{constructor(e,t,n=[0,250,1e3,2500]){this.maxPerNode=e;this.ttlMs=t;this.retryDelaysMs=n;this.pendingByNodeId=new Map;this.retryTimers=new Set;this.disposed=false;}queue(e,t,n,i,o){if(this.disposed)return;let s=this.pendingByNodeId.get(e)??[];s.push({message:t,source:n,traceId:i??null,receivedAtMs:Date.now()}),s.length>this.maxPerNode&&s.splice(0,s.length-this.maxPerNode),this.pendingByNodeId.set(e,s),c$1("[Client][NATIVE-MAIN] Queued TS handshake until control connection is registered",{remoteNodeId:e,action:t.action??"hello",source:n,traceId:i||null,pendingCount:s.length});for(let a of this.retryDelaysMs){let c=setTimeout(()=>{this.retryTimers.delete(c),!this.disposed&&o(e,`queued-handshake-retry:${a}`);},a);this.retryTimers.add(c);}}dispose(){if(!this.disposed){this.disposed=true;for(let e of this.retryTimers)clearTimeout(e);this.retryTimers.clear(),this.pendingByNodeId.clear();}}async flush(e,t,n){if(this.disposed)return false;let i=this.pendingByNodeId.get(e);if(!i||i.length===0)return false;let o=n.findManualDisconnectProjectionForNativeNode(e);if(o)return this.pendingByNodeId.delete(e),c$1("[Client][NATIVE-MAIN] Dropped queued TS handshakes for manually disconnected peer",{remoteNodeId:e,peerId:o.peerId,droppedCount:i.length,trigger:t}),false;let s=n.findLiveConnectionForRemoteNode(e);if(s||(s=await n.ensureIncomingConnectionForRemoteNode(e).catch(()=>null)),this.disposed)return false;if(!s){let a=Date.now(),c=i.filter(d=>a-d.receivedAtMs<=this.ttlMs);return c.length===0?(this.pendingByNodeId.delete(e),console.warn("[Client][NATIVE-MAIN] Dropping queued TS handshakes after control connection did not appear",{remoteNodeId:e,trigger:t,droppedCount:i.length})):c.length!==i.length&&this.pendingByNodeId.set(e,c),false}this.pendingByNodeId.delete(e),c$1("[Client][NATIVE-MAIN] Replaying queued TS handshakes to Connection",{remoteNodeId:e,connectionId:s.id,trigger:t,count:i.length});for(let a of i){if(this.disposed)return false;await n.handleMessage(s,a.message);}return true}};var da="main",pa="signal";function Sr(r){let e=new TextEncoder().encode(r),t=new ArrayBuffer(5+e.byteLength),n=new Uint8Array(t);return n[0]=0,new DataView(t).setUint32(1,e.byteLength,false),n.set(e,5),n}function vi(){return Sr(da)}function br(){return Sr(pa)}function Ie(r){let e=JSON.stringify(r),t=new TextEncoder().encode(e),n=new Uint8Array(1+t.byteLength);return n[0]=0,n.set(t,1),n}function le(r){let e=new ArrayBuffer(4+r.byteLength);new DataView(e).setUint32(0,r.byteLength,false);let n=new Uint8Array(e);return n.set(r,4),n}var Jt=class{constructor(e,t){this.config=e;this.deps=t;}protocolConfig(){return {protocolByte:this.config.protocolByte,label:this.config.label,maxLabelBytes:this.config.maxLabelBytes,maxFrameBytes:this.config.maxFrameBytes}}encodeFrame(e){return cr(e,this.protocolConfig())}async dispatchMessage(e,t){return lr(this.config.eventName,e,this.deps.getRemoteDeviceId(e),t)}async writeAck(e,t,n=null){let i=this.deps.getReceiverDeviceId();await this.writeMessage(e,{channel:"native-main",action:"ack",requestId:t.requestId,payload:{received:true,channel:t.channel,action:t.action,...i?{receiverDeviceId:i}:{},...n!==null?{handlerResponse:n}:{}},timestamp:Date.now(),from:"web"});}async writeMessage(e,t){await e.write(this.encodeFrame(t));}async writeLabeledMessage(e,t){await e.write(vi()),await e.write(le(new TextEncoder().encode(JSON.stringify(t))));}async writeLabelHeaderOnBiStream(e,t){let n=e.send.getWriter();try{await n.write(vi());}catch(i){throw console.warn("[Client][NATIVE-MAIN] Label header write failed",{remoteNodeId:t,error:i}),i}finally{try{n.releaseLock();}catch{}}}};var Xt=class{constructor(e){this.deps=e;this.disposed=false;this.activeReaders=new Set;}dispose(){if(!this.disposed){this.disposed=true;for(let e of this.activeReaders)this.cancelReaderBestEffort(e);this.activeReaders.clear();}}async handleNativeMainStream(e,t,n){if(this.disposed||!i$2(e))return;let i,o,s=false;try{i=e.recv.getReader(),o=e.send.getWriter();}catch(h){console.warn("[Client][NATIVE-MAIN] Unable to acquire stream handles",{remoteNodeId:t,error:h});return}this.activeReaders.add(i);let a=this.createStreamInstanceId(),c=e.native_signal_only===true,d=new Uint8Array(0),l="stream-active",p=0,u=()=>{c||s||(this.deps.registerInboundNativeMainWriter(t,o,n),s=true);};try{for(;!this.disposed;){let h=this.tryExtractNativeMainPayload(d);for(;!h.ready&&!this.disposed;){let{done:f,value:v}=await i.read();if(this.disposed)return;if(f){l=h.phase==="frame-start"?p>0?"remote-closed-after-frame":"remote-closed-before-frame-length":"remote-closed-mid-frame",!c&&(p===0||h.phase!=="frame-start")&&this.schedulePeerReconciliationBestEffort("native-main-stream-close"),h.phase==="frame-start"?c$1("[Client][NATIVE-MAIN] Remote closed native main stream",{remoteNodeId:t,handledFrameCount:p}):console.warn("[Client][NATIVE-MAIN] Native main stream ended mid-frame",{remoteNodeId:t,messageLen:h.expectedFrameLength,bufferedBytes:d.byteLength});return}v&&v.byteLength>0&&(d=g([d,new Uint8Array(v)]));try{h=this.tryExtractNativeMainPayload(d);}catch(y){l="invalid-native-main-frame",console.warn("[Client][NATIVE-MAIN] Invalid native main frame",{remoteNodeId:t,error:y});return}}if(h.expectedFrameLength===0){d=d.slice(h.consumedBytes);continue}let m=h.payloadBytes;d=d.slice(h.consumedBytes),p+=1,await this.handleNativeMainPayloadBytes(m,t,o,void 0,"bi",u,n,a);}}catch(h){if(this.disposed)return;l="handler-error",this.schedulePeerReconciliationBestEffort("native-main-handler-error"),console.error("[Client][NATIVE-MAIN] Native main stream handler failed",{remoteNodeId:t,error:h});}finally{this.deps.handleNativeMainStreamClosed(t,n,a),s&&this.deps.clearInboundNativeMainWriter(t,o,l),this.activeReaders.delete(i);try{o.releaseLock();}catch{}try{i.releaseLock();}catch{}}}tryExtractNativeMainPayload(e){return dr(e,this.deps.getProtocolConfig())}async tryHandleNativeMainUniStream(e,t,n){if(this.disposed||!e||typeof e.getReader!="function")return false;let i;try{i=e.getReader();}catch{return false}this.activeReaders.add(i);let o=new Uint8Array(0),s=false;try{for(;!this.disposed;){let a=this.tryExtractNativeMainPayload(o);for(;!a.ready&&!this.disposed;){let{done:c,value:d}=await i.read();if(this.disposed||c)return s;d&&d.byteLength>0&&(o=g([o,new Uint8Array(d)])),a=this.tryExtractNativeMainPayload(o);}s=!0,o=o.slice(a.consumedBytes),await this.handleNativeMainPayloadBytes(a.payloadBytes,t,null,n,"uni");}return s}catch(a){return this.disposed?s:s?(console.warn("[Client][NATIVE-MAIN] Read-only native main uni handler failed",{remoteNodeId:t,traceId:n||null,error:a}),true):false}finally{this.activeReaders.delete(i);try{i.releaseLock();}catch{}}}async handleNativeMainPayloadBytes(e,t,n,i,o,s,a,c){if(this.disposed)return;let d=e.byteLength>1&&e[0]===0?e.slice(1):e,l;try{l=JSON.parse(new TextDecoder().decode(d));}catch(m){let f=await this.deps.ensureIncomingConnectionForRemoteNode(t);if(this.disposed)return;f?f.receiveDataPayload(d):console.warn("[Client][NATIVE-MAIN] Dropping binary app payload: no control connection",{remoteNodeId:t,traceId:i||null,source:o,error:m});return}let p=this.deps.findManualDisconnectProjectionForNativeNode(t);if(this.isHandshakeMessage(l)){if(s?.(),p){c$1("[Client][NATIVE-MAIN] Dropping TS handshake for manually disconnected peer",{remoteNodeId:t,peerId:p.peerId,action:l.action??"hello",source:o});return}let m=await this.deps.ensureIncomingConnectionForRemoteNode(t);if(this.disposed)return;if(!m){this.deps.queuePendingNativeMainHandshake(t,l,o,i||null);return}c$1("[Client][NATIVE-MAIN] Routed TS handshake to Connection",{remoteNodeId:t,connectionId:m.id,action:l.action??"hello",source:o}),await this.deps.handleMessage(m,l);return}if(this.isNativeSignalEnvelope(l)){if(s?.(),c$1("[Client][NATIVE-MAIN] Received #pluto-signal envelope",{remoteNodeId:t,signalType:l.content?.type??null,transport:l.content?.transport??null,source:o}),p){c$1("[Client][NATIVE-MAIN] Dropping native WebRTC signal for manually disconnected peer",{remoteNodeId:t,peerId:p.peerId,signalType:l.content?.type??null,source:o});return}let m=await this.deps.ensureIncomingConnectionForRemoteNode(t);if(this.disposed)return;if(!m){this.deps.queuePendingNativeMainSignal(t,l.content,o,i||null);return}if(l.content?.transport==="iroh-webrtc"){await this.deps.handleMessage(m,l);return}m.receiveInternalSignal(l.content),c$1("[Client][NATIVE-MAIN] Routed #pluto-signal to Connection",{remoteNodeId:t,connectionId:m.id,signalType:l.content?.type??null,source:o});return}if(this.isIrohCarrierControlFrame(l)){if(s?.(),p){c$1("[Client][NATIVE-MAIN] Dropping Iroh carrier control for manually disconnected peer",{remoteNodeId:t,peerId:p.peerId,carrier:l.carrier,action:l.action,source:o});return}let m=await this.deps.ensureIncomingConnectionForRemoteNode(t);if(this.disposed)return;if(!m){console.warn("[Client][NATIVE-MAIN] Dropping Iroh carrier control: no admitted connection",{remoteNodeId:t,carrier:l.carrier,action:l.action,source:o}),this.schedulePeerReconciliationBestEffort("iroh-carrier-control-without-connection");return}await this.deps.handleMessage(m,l);return}let u=l;if(c$1("[Client][NATIVE-MAIN] Received native main message",{remoteNodeId:t,channel:u.channel,action:u.action,requestId:u.requestId??null,source:o}),u.channel==="handshake"&&u.action==="request"){n&&await this.deps.handleNativeHandshakeRequest(n,t,u);return}if(u.channel==="session-token"&&u.action==="request"){n&&await this.deps.handleNativeSessionTokenRequest(n,t,u,a,c);return}if(u.channel==="session-token"&&u.action==="event"&&u.payload?.responseAck===true){await this.deps.handleNativeSessionTokenResponseAck(t,u,a,c);return}if(!u.channel&&!u.action&&!u.requestId){s?.();let m=await this.deps.ensureIncomingConnectionForRemoteNode(t);if(this.disposed)return;if(!m){console.warn("[Client][NATIVE-MAIN] Dropping app payload: no control connection",{remoteNodeId:t,traceId:i||null,source:o});return}m.receiveMessage(l);return}let h=await this.deps.dispatchNativeMainMessage(t,u);this.disposed||n&&await this.writeReceiveAckBestEffort(n,u,h,t,o);}isNativeSignalEnvelope(e){if(!e||typeof e!="object")return false;let t=e;return t.type==="#pluto-signal"&&typeof t.content=="object"&&t.content!==null}isIrohCarrierControlFrame(e){if(!e||typeof e!="object")return false;let t=e;return t.type==="#openrtc-iroh-carrier"&&(t.carrier==="web-rtc"||t.carrier==="moq-draft14")&&typeof t.action=="string"}isHandshakeMessage(e){return !e||typeof e!="object"?false:e.type==="handshake"}cancelReaderBestEffort(e){try{Promise.resolve(e.cancel("native-main-payload-router-disposed")).catch(()=>{});}catch{}}createStreamInstanceId(){let e=globalThis.crypto?.randomUUID;return typeof e=="function"?e.call(globalThis.crypto):`native-main-stream-${Date.now()}-${Math.random().toString(36).slice(2)}`}schedulePeerReconciliationBestEffort(e){if(!this.disposed)try{Promise.resolve(this.deps.schedulePeerReconciliation(e)).catch(()=>{});}catch{}}async writeReceiveAckBestEffort(e,t,n,i,o){if(!this.disposed)try{await this.deps.writeNativeMainReceiveAck(e,t,n);}catch(s){if(this.disposed)return;console.warn("[Client][NATIVE-MAIN] Failed to ack native main message",{remoteNodeId:i,channel:t.channel,action:t.action,source:o,error:s});}}};var Zt=class{constructor(e,t,n=[0,250,1e3,2500]){this.maxPerNode=e;this.ttlMs=t;this.retryDelaysMs=n;this.pendingByNodeId=new Map;this.retryTimers=new Set;this.disposed=false;}queue(e,t,n,i,o){if(this.disposed)return;let s=this.pendingByNodeId.get(e)??[];s.push({content:t,source:n,traceId:i??null,receivedAtMs:Date.now()}),s.length>this.maxPerNode&&s.splice(0,s.length-this.maxPerNode),this.pendingByNodeId.set(e,s),c$1("[Client][NATIVE-MAIN] Queued native WebRTC signal until control connection is registered",{remoteNodeId:e,signalType:t?.type??null,source:n,traceId:i||null,pendingCount:s.length});for(let a of this.retryDelaysMs){let c=setTimeout(()=>{this.retryTimers.delete(c),!this.disposed&&o(e,`queued-signal-retry:${a}`);},a);this.retryTimers.add(c);}}dispose(){if(!this.disposed){this.disposed=true;for(let e of this.retryTimers)clearTimeout(e);this.retryTimers.clear(),this.pendingByNodeId.clear();}}async flush(e,t,n){if(this.disposed)return false;let i=this.pendingByNodeId.get(e);if(!i||i.length===0)return false;let o=n.findManualDisconnectProjectionForNativeNode(e);if(o)return this.pendingByNodeId.delete(e),c$1("[Client][NATIVE-MAIN] Dropped queued native WebRTC signals for manually disconnected peer",{remoteNodeId:e,peerId:o.peerId,droppedCount:i.length,trigger:t}),false;let s=n.findLiveConnectionForRemoteNode(e);if(s||(s=await n.ensureIncomingConnectionForRemoteNode(e).catch(()=>null)),this.disposed)return false;if(!s){let a=Date.now(),c=i.filter(d=>a-d.receivedAtMs<=this.ttlMs);return c.length===0?(this.pendingByNodeId.delete(e),console.warn("[Client][NATIVE-MAIN] Dropping queued native WebRTC signals after control connection did not appear",{remoteNodeId:e,trigger:t,droppedCount:i.length})):c.length!==i.length&&this.pendingByNodeId.set(e,c),false}this.pendingByNodeId.delete(e),c$1("[Client][NATIVE-MAIN] Replaying queued native WebRTC signals to Connection",{remoteNodeId:e,connectionId:s.id,trigger:t,count:i.length});for(let a of i){if(this.disposed)return false;s.receiveInternalSignal(a.content);}return true}};var en=class{constructor(e){this.deps=e;this.disposed=false;}dispose(){this.disposed=true;}assertActive(){if(this.disposed)throw new Error("Native main signal sender is disposed")}isCurrent(e,t){return e.isCurrentSignal(t)}async openNativeSignalBiStream(e,t){this.assertActive();let n=e.open_native_main_control_bi;if(typeof n=="function"){let i=await n.call(e,t);return this.assertActive(),i}throw new Error("[Client][NATIVE-MAIN] open_native_main_control_bi is unavailable on this WASM build; native-main signaling cannot open a control stream under mandatory application crypto. Rebuild the openrtc WASM (pnpm --filter openrtc build:wasm).")}async sendViaDedicatedStream(e,t,n,i){if(this.assertActive(),!this.isCurrent(n,i))return;let o=le(Ie(i)),s=e.send_native_main_control_frame;if(typeof s=="function"){await s.call(e,t,o),this.assertActive();return}let a=await this.openNativeSignalBiStream(e,t);if(this.assertActive(),!this.isCurrent(n,i))return;let c=a.send.getWriter();try{if(await c.write(br()),this.disposed||!this.isCurrent(n,i))return;await c.write(o),await c.close();}catch(d){throw console.warn("[Client][NATIVE-MAIN] Dedicated-stream signal send failed",{remoteNodeId:t,signalType:i?.content?.type??null,error:d}),d}finally{try{c.releaseLock();}catch{}}}async sendEnvelope(e,t,n,i){if(this.disposed)return;if(!this.isCurrent(e,n)){c$1("[Client][NATIVE-MAIN] Dropping signal from retired negotiation generation",{connectionId:e.id,remoteNodeId:t,signalType:n?.content?.type??null,negotiationId:n?.content?.negotiationId??null});return}let o=n?.content?.transport??null,s=n?.content?.type??null,a=o==="webrtc"&&(s==="sdp"||s==="candidate"||s==="renegotiate"),c=n?.type==="handshake",d=n?.type==="#openrtc-iroh-carrier"||n?.type==="#pluto-signal"&&n?.content?.transport==="iroh-webrtc",l=a&&e.getUpgradeState()==="upgrading"||c,p=this.deps.isSessionTokenApprovedNode(t)&&this.deps.isSessionTokenApprovedConnection(e.id),u=p;if(d&&u&&this.deps.shouldUseDedicatedCarrierControl?.(t,e.id)===true)try{if(await this.sendViaDedicatedStream(i,t,e,n),this.disposed||!this.isCurrent(e,n))return;c$1("[Client][NATIVE-MAIN] Signal route=dedicated-carrier-control",{connectionId:e.id,remoteNodeId:t,signalType:n?.content?.type??null,negotiationId:n?.content?.negotiationId??null});return}catch(v){console.warn("[Client][NATIVE-MAIN] Dedicated carrier-control send failed; falling back",{connectionId:e.id,remoteNodeId:t,signalType:n?.content?.type??null,error:v});}let h=this.deps.isSessionTokenApprovedNode(t),m=this.deps.isSessionTokenApprovedConnection(e.id),f=await this.deps.sendViaInboundControlStream(t,n,{ignoreCooldown:l,isCurrent:()=>this.isCurrent(e,n)});if(!(this.disposed||!this.isCurrent(e,n))){if(f.sent){c$1("[Client][NATIVE-MAIN] Sent native signal over inbound control stream",{connectionId:e.id,remoteNodeId:t,signalType:n?.content?.type??null,writerId:f.writerId,writerAgeMs:f.writerAgeMs}),c$1("[Client][NATIVE-MAIN] Signal route=inbound-control",{connectionId:e.id,remoteNodeId:t,signalType:n?.content?.type??null,negotiationId:n?.content?.negotiationId??null,writerId:f.writerId,writerAgeMs:f.writerAgeMs}),c$1("[SIGNAL-STREAM][TS] reply-on-persistent-writer",{connectionId:e.id,remoteNodeId:t,signalType:n?.content?.type??null,writerId:f.writerId,writerAgeMs:f.writerAgeMs});return}if(c$1("[Client][NATIVE-MAIN] Signal route=inbound-control-unavailable",{connectionId:e.id,remoteNodeId:t,signalType:n?.content?.type??null,negotiationId:n?.content?.negotiationId??null,reason:f.reason,writerId:f.writerId,writerAgeMs:f.writerAgeMs,inboundError:f.error,hasApprovedNode:h,hasApprovedConnectionId:m,hasApprovedDedicatedStream:p,preferDedicatedSignalPath:l,canUseDedicatedStream:u}),u)try{if(await this.sendViaDedicatedStream(i,t,e,n),this.disposed)return;c$1("[Client][NATIVE-MAIN] Sent native signal over dedicated stream",{connectionId:e.id,remoteNodeId:t,signalType:n?.content?.type??null}),c$1("[Client][NATIVE-MAIN] Signal route=dedicated-open_bi",{connectionId:e.id,remoteNodeId:t,signalType:n?.content?.type??null,negotiationId:n?.content?.negotiationId??null,inboundFallbackReason:f.reason});return}catch(v){console.warn("[Client][NATIVE-MAIN] Dedicated-stream signal send failed; falling back to control stream",{connectionId:e.id,remoteNodeId:t,signalType:n?.content?.type??null,error:v});}try{if(this.disposed||!this.isCurrent(e,n)||(await e.sendRawIrohFrame(le(Ie(n))),this.disposed))return;c$1("[Client][NATIVE-MAIN] Sent native signal over control stream",{connectionId:e.id,remoteNodeId:t,signalType:n?.content?.type??null}),c$1("[Client][NATIVE-MAIN] Signal route=cached-control-writer",{connectionId:e.id,remoteNodeId:t,signalType:n?.content?.type??null,negotiationId:n?.content?.negotiationId??null,inboundFallbackReason:f.reason});return}catch(v){if(console.warn("[Client][NATIVE-MAIN] Control-stream signal send failed",{connectionId:e.id,remoteNodeId:t,signalType:n?.content?.type??null,error:v}),!u)throw v}this.disposed||(await this.sendViaDedicatedStream(i,t,e,n),!this.disposed&&(c$1("[Client][NATIVE-MAIN] Sent native signal over dedicated stream",{connectionId:e.id,remoteNodeId:t,signalType:n?.content?.type??null}),c$1("[Client][NATIVE-MAIN] Signal route=dedicated-open_bi-fallback",{connectionId:e.id,remoteNodeId:t,signalType:n?.content?.type??null,negotiationId:n?.content?.negotiationId??null,inboundFallbackReason:f.reason})));}}};var tn=class{constructor(){this.writers=new Map;this.writeMutexes=new Map;this.writerMeta=new Map;this.standbyWriters=new Map;this.bypassUntilMs=new Map;this.writerSeq=0;this.disposed=false;}dispose(){if(!this.disposed){this.disposed=true;for(let e of this.writers.values())try{e.releaseLock();}catch{}for(let e of this.standbyWriters.values())for(let t of e)try{t.writer.releaseLock();}catch{}this.writers.clear(),this.writeMutexes.clear(),this.writerMeta.clear(),this.standbyWriters.clear(),this.bypassUntilMs.clear();}}registerInboundWriter(e,t,n){if(this.disposed){try{t.releaseLock();}catch{}return}let i=this.writers instanceof Map?this.writers:null,o=this.writerMeta instanceof Map?this.writerMeta:null,s=this.standbyWriters instanceof Map?this.standbyWriters:null;if(!i||!e||!t)return;let a=i.get(e),c=o?.get(e);this.writerSeq+=1;let d=this.writerSeq,l=Number.isSafeInteger(n)&&Number(n)>0?Number(n):null,p={id:d,registeredAtMs:Date.now(),transportStableId:l};if(a&&a!==t&&l!==null&&c?.transportStableId===l){let u=s?.get(e)??[];u.push({writer:t,meta:p}),s?.set(e,u),c$1("[Client][NATIVE-MAIN] Same-generation control writer deferred",{remoteNodeId:e,writerId:d,activeWriterId:c.id,transportStableId:l}),c$1("[SIGNAL-STREAM][TS] writer-deferred",{remoteNodeId:e,writerId:d,activeWriterId:c.id,transportStableId:l});return}i.set(e,t),o?.set(e,p),this.bypassUntilMs instanceof Map&&this.bypassUntilMs.delete(e),c$1("[Client][NATIVE-MAIN] Inbound control writer registered",{remoteNodeId:e,writerId:d,replacedExistingWriter:!!a&&a!==t,transportStableId:l}),c$1("[SIGNAL-STREAM][TS] writer-registered",{remoteNodeId:e,writerId:d,replacedExistingWriter:!!a&&a!==t,transportStableId:l});}clearInboundWriter(e,t,n,i="stream-finalize"){if(this.disposed)return;let o=this.writers instanceof Map?this.writers:null,s=this.writeMutexes instanceof Map?this.writeMutexes:null,a=this.writerMeta instanceof Map?this.writerMeta:null,c=this.standbyWriters instanceof Map?this.standbyWriters:null;if(!o||!s)return;let d=o.get(e),l=a?.get(e),p=c?.get(e)??[],u=p.filter(h=>h.writer!==t);if(d===t){o.delete(e),a?.delete(e);let h=u.findIndex(f=>f.meta.transportStableId===l?.transportStableId),m=h>=0?u.splice(h,1)[0]:void 0;u.length>0?c?.set(e,u):c?.delete(e),m?(o.set(e,m.writer),a?.set(e,m.meta),this.bypassUntilMs.delete(e)):(this.bypassUntilMs.set(e,Date.now()+n),s.delete(e)),c$1("[Client][NATIVE-MAIN] Inbound control writer cleared",{remoteNodeId:e,writerId:l?.id??null,ageMs:l?Date.now()-l.registeredAtMs:null,reason:i,promotedWriterId:m?.meta.id??null}),c$1("[SIGNAL-STREAM][TS] writer-cleared",{remoteNodeId:e,writerId:l?.id??null,ageMs:l?Date.now()-l.registeredAtMs:null,reason:i,promotedWriterId:m?.meta.id??null});}else u.length>0?c?.set(e,u):c?.delete(e),c$1("[Client][NATIVE-MAIN] Inbound control writer clear skipped (mismatch)",{remoteNodeId:e,activeWriterId:l?.id??null,reason:i,removedStandby:u.length!==p.length});}async sendViaInboundControlStream(e,t,n,i={}){if(this.disposed)return {sent:false,reason:"writer-registry-disposed",writerId:null,writerAgeMs:null,error:null};let o=this.writers instanceof Map?this.writers:null,s=this.writeMutexes instanceof Map?this.writeMutexes:null,a=this.writerMeta instanceof Map?this.writerMeta:null;if(!o||!s)return {sent:false,reason:"writer-or-mutex-map-unavailable",writerId:null,writerAgeMs:null,error:null};let c=a?.get(e),d=this.bypassUntilMs instanceof Map?this.bypassUntilMs:null,l=d?.get(e)??0;if(!i.ignoreCooldown&&l>Date.now())return {sent:false,reason:"inbound-writer-cooldown",writerId:c?.id??null,writerAgeMs:c?Date.now()-c.registeredAtMs:null,error:null};let p=o.get(e),u=c?.id??null,h=c?Date.now()-c.registeredAtMs:null;if(!p)return d?.set(e,Date.now()+n),{sent:false,reason:"no-inbound-writer",writerId:u,writerAgeMs:h,error:null};let m=le(Ie(t)),f=s.get(e)??Promise.resolve(),v,y=new Promise(C=>{v=C;});s.set(e,y);try{return await f.catch(()=>{}),i.isCurrent&&!i.isCurrent()?{sent:!1,reason:"retired-negotiation-generation",writerId:u,writerAgeMs:h,error:null}:(await p.write(m),{sent:!0,reason:"sent",writerId:u,writerAgeMs:h,error:null})}catch(C){return d?.set(e,Date.now()+n),console.warn("[Client][NATIVE-MAIN] Inbound control-stream signal send failed",{remoteNodeId:e,signalType:t?.content?.type??null,writerId:u,writerAgeMs:h,error:C}),{sent:false,reason:"inbound-writer-write-failed",writerId:u,writerAgeMs:h,error:C?.message??String(C)}}finally{v(),s.get(e)===y&&s.delete(e);}}};var ua=new Set(["desktop","mobile","native","macos","windows","linux","ios","android"]),nn=class{constructor(e,t,n){this.deps=e;this.protocolConfig=t;this.timingConfig=n;this.writers=new tn;this.disposed=false;this.messageIO=new Jt({eventName:t.eventName,protocolByte:t.protocolByte,label:t.label,maxLabelBytes:t.maxLabelBytes,maxFrameBytes:t.maxFrameBytes},{getReceiverDeviceId:()=>e.getReceiverDeviceId(),getRemoteDeviceId:i=>e.getKnownDeviceIdForNode(i)}),this.handshakeQueue=new Yt(n.pendingHandshakeMaxPerNode,n.pendingHandshakeTtlMs),this.signalQueue=new Zt(n.pendingHandshakeMaxPerNode,n.pendingHandshakeTtlMs),this.deps.registerDisposer(()=>this.dispose());}get writerRegistry(){return this.writers}get connectionController(){return this.getConnections()}get handshakeQueueController(){return this.handshakeQueue}get messageIOController(){return this.messageIO}get payloadRouterController(){return this.getPayloadRouter()}dispose(){this.disposed=true,this.handshakeQueue.dispose(),this.signalQueue.dispose(),this.admission?.dispose(),this.connections?.dispose(),this.payloadRouter?.dispose(),this.writers.dispose(),this.signalSender?.dispose();}retirePendingReciprocalAdmissions(e){this.admission?.retirePendingReciprocalAdmissions(e);}async acceptNativeMessage(e,t,n){return this.disposed?false:this.getAdmission().acceptNativeMessage(e,t,n)}tryHandleNativeMainUniStream(e,t,n){return this.disposed?Promise.resolve(false):this.getPayloadRouter().tryHandleNativeMainUniStream(e,t,n)}handleNativeMainStream(e,t,n){return this.disposed?Promise.resolve():Number.isSafeInteger(n)&&Number(n)>0?this.getPayloadRouter().handleNativeMainStream(e,t,n):this.getPayloadRouter().handleNativeMainStream(e,t)}writeLabelHeaderOnBiStream(e,t){return this.disposed?Promise.resolve():this.messageIO.writeLabelHeaderOnBiStream(e,t)}openSignalBiStream(e,t){return this.disposed?Promise.reject(new Error("Native main controller is disposed")):this.getSignalSender().openNativeSignalBiStream(e,t)}async sendSignalEnvelope(e,t,n,i){this.disposed||await this.getSignalSender().sendEnvelope(e,t,n,i);}ensureIncomingConnectionForRemoteNode(e){return this.disposed?Promise.resolve(null):this.getConnections().ensureIncomingConnectionForRemoteNode(e)}flushPendingHandshakesForNode(e,t){return this.disposed?Promise.resolve(false):this.handshakeQueue.flush(e,t,{findManualDisconnectProjectionForNativeNode:n=>this.deps.findManualDisconnectProjectionForNativeNode(n),findLiveConnectionForRemoteNode:n=>this.deps.findLiveConnectionForRemoteNode(n),ensureIncomingConnectionForRemoteNode:n=>this.deps.ensureIncomingConnectionForRemoteNode(n),handleMessage:(n,i)=>Promise.resolve(this.deps.handleMessage(n,i))})}flushPendingSignalsForNode(e,t){return this.disposed?Promise.resolve(false):this.signalQueue.flush(e,t,{findManualDisconnectProjectionForNativeNode:n=>this.deps.findManualDisconnectProjectionForNativeNode(n),findLiveConnectionForRemoteNode:n=>this.deps.findLiveConnectionForRemoteNode(n),ensureIncomingConnectionForRemoteNode:n=>this.deps.ensureIncomingConnectionForRemoteNode(n)})}getSignalSender(){return this.signalSender||(this.signalSender=new en({isSessionTokenApprovedNode:e=>this.deps.isSessionTokenApprovedNode(e),isSessionTokenApprovedConnection:e=>this.deps.isSessionTokenApprovedConnection(e),shouldUseDedicatedCarrierControl:(e,t)=>{if(this.deps.getConnectionChannelId(t)==="drive-view")return false;let n=this.deps.getKnownDeviceIdForNode(e),i=this.deps.getKnownDevicePlatform(n,e)?.trim().toLowerCase();return !i||!ua.has(i)},sendViaInboundControlStream:(e,t,n)=>this.writers.sendViaInboundControlStream(e,t,this.timingConfig.inboundWriterRetryCooldownMs,n)}),this.disposed&&this.signalSender.dispose()),this.signalSender}getConnections(){return this.connections||(this.connections=new $t({getDeterministicConnectionId:e=>this.deps.getDeterministicConnectionId(e),getConnection:e=>this.deps.getConnection(e),getWasmClient:()=>this.deps.getWasmClient(),getLocalNodeId:()=>this.deps.getLocalNodeId(),getKnownDeviceIdForNode:e=>this.deps.getKnownDeviceIdForNode(e),getKnownDevicePlatform:(e,t)=>this.deps.getKnownDevicePlatform(e,t),isNativeMainPeerPlatform:e=>this.deps.isNativeMainPeerPlatform(e),getTrustFailureCooldown:e=>this.deps.getTrustFailureCooldown(e),getTrustFailureCooldownMs:()=>this.timingConfig.trustFailureCooldownMs,isSessionTokenApprovedNode:e=>this.deps.isSessionTokenApprovedNode(e),openNativeSignalBiStream:(e,t)=>this.openSignalBiStream(e,t),writeNativeMainLabelHeaderOnBiStream:(e,t)=>this.writeLabelHeaderOnBiStream(e,t),sendNativeSignalEnvelope:(e,t,n,i)=>this.sendSignalEnvelope(e,t,n,i),getRTCConfig:()=>this.deps.getRTCConfig(),createTransportContext:e=>this.deps.createTransportContext(e),getApplicationCrypto:()=>this.deps.getApplicationCrypto(),shouldNegotiateApplicationKeyAgreement:()=>this.deps.shouldNegotiateApplicationKeyAgreement(),handleConnectionTransportStatus:(e,t,n)=>this.deps.handleConnectionTransportStatus(e,t,n??null),handleConnectionApplicationRouteMissing:(e,t)=>this.deps.handleConnectionApplicationRouteMissing(e,t),initializeConnectionTrust:(e,t)=>{this.deps.initializeConnectionTrust(e,t);},markConnectionTrustVerified:(e,t)=>{this.deps.markConnectionTrustVerified(e,t);},registerConnection:e=>this.deps.registerConnection(e),announceConnectionWhenStable:e=>this.deps.announceConnectionWhenStable(e),sendTransportHandshake:(e,t)=>this.deps.sendTransportHandshake(e,t),requestProtectedWebRTCUpgradeIfInitiator:(e,t)=>this.deps.requestProtectedWebRTCUpgradeIfInitiator(e,t),getConnectionChannelId:e=>this.deps.getConnectionChannelId(e),isWebRTCTransportEnabled:()=>this.deps.isWebRTCTransportEnabled()}),this.disposed&&this.connections.dispose()),this.connections}getAdmission(){return this.admission||(this.admission=new Qt({getDeterministicConnectionId:e=>this.deps.getDeterministicConnectionId(e),getNativeMainConnectionId:e=>this.deps.getNativeMainConnectionId(e),getConnection:e=>this.deps.getConnection(e),handleMessage:(e,t)=>this.deps.handleMessage(e,t),getLocalDeviceId:()=>this.deps.getLocalDeviceId(),getFallbackLocalDeviceId:()=>this.deps.getFallbackLocalDeviceId(),getConfiguredDeviceName:()=>this.deps.getConfiguredDeviceName(),getNativeMainProtocolVersion:()=>this.protocolConfig.protocolVersion,isNativeRuntime:()=>this.deps.isNativeRuntime(),isLikelyMobileBrowser:()=>this.deps.isLikelyMobileBrowser(),writeNativeMainMessage:(e,t)=>this.messageIO.writeLabeledMessage(e,t),validateIncomingSessionToken:(e,t,n)=>this.deps.validateIncomingSessionToken(e,t,n),applySessionTokenTrustApproval:(e,t,n)=>this.deps.applySessionTokenTrustApproval(e,t,n),rememberPendingSessionTokenTrustApproval:(e,t)=>this.deps.rememberPendingSessionTokenTrustApproval(e,t),markSessionTokenApprovedNode:e=>this.deps.markSessionTokenApprovedNode(e),markSessionTokenApprovedConnection:e=>this.deps.markSessionTokenApprovedConnection(e),clearSessionTokenRejectionCooldown:e=>this.deps.clearSessionTokenRejectionCooldown(e),getSessionTokenRejectionCooldown:e=>this.deps.getSessionTokenRejectionCooldown(e),setSessionTokenRejectionCooldown:(e,t)=>this.deps.setSessionTokenRejectionCooldown(e,t),clearTrustFailureCooldown:e=>{this.deps.clearTrustFailureCooldown(e);},schedulePeerReconciliation:e=>this.deps.schedulePeerReconciliation(e),ensureIncomingConnectionForRemoteNode:e=>this.deps.ensureIncomingConnectionForRemoteNode(e),getReciprocalSessionAdmission:(e,t,n,i,o)=>this.deps.getReciprocalSessionAdmission(e,t,n,i,o),presentLegacyReciprocalSessionAdmission:e=>this.deps.presentLegacyReciprocalSessionAdmission(e),confirmReciprocalSessionAdmission:(e,t,n,i,o,s)=>this.deps.confirmReciprocalSessionAdmission(e,t,n,i,o,s),disconnectRemoteNode:e=>this.deps.disconnectRemoteNode(e)}),this.disposed&&this.admission.dispose()),this.admission}getPayloadRouter(){return this.payloadRouter||(this.payloadRouter=new Xt({getProtocolConfig:()=>this.messageIO.protocolConfig(),registerInboundNativeMainWriter:(e,t,n)=>this.writers.registerInboundWriter(e,t,n),clearInboundNativeMainWriter:(e,t,n)=>this.writers.clearInboundWriter(e,t,this.timingConfig.inboundWriterRetryCooldownMs,n),schedulePeerReconciliation:e=>this.deps.schedulePeerReconciliation(e),ensureIncomingConnectionForRemoteNode:e=>this.deps.ensureIncomingConnectionForRemoteNode(e),queuePendingNativeMainHandshake:(e,t,n,i)=>this.handshakeQueue.queue(e,t,n,i,(o,s)=>{this.flushPendingHandshakesForNode(o,s);}),queuePendingNativeMainSignal:(e,t,n,i)=>this.signalQueue.queue(e,t,n,i,(o,s)=>{this.flushPendingSignalsForNode(o,s);}),findManualDisconnectProjectionForNativeNode:e=>this.deps.findManualDisconnectProjectionForNativeNode(e),handleMessage:(e,t)=>this.deps.handleMessage(e,t),handleNativeHandshakeRequest:(e,t,n)=>this.getAdmission().handleHandshakeRequest(e,t,n),handleNativeSessionTokenRequest:(e,t,n,i,o)=>this.getAdmission().handleSessionTokenRequest(e,t,n,i,o),handleNativeSessionTokenResponseAck:(e,t,n,i)=>this.getAdmission().handleSessionTokenResponseAck(e,t,n,i),handleNativeMainStreamClosed:(e,t,n)=>this.getAdmission().handleNativeMainStreamClosed(e,t,n),dispatchNativeMainMessage:(e,t)=>this.messageIO.dispatchMessage(e,t),writeNativeMainReceiveAck:(e,t,n)=>this.messageIO.writeAck(e,t,n)}),this.disposed&&this.payloadRouter.dispose()),this.payloadRouter}};function Pr(r){let{host:e}=r;return new nn({registerDisposer:t=>e.registerDisposer(t),getDeterministicConnectionId:t=>e.getDeterministicConnectionId(t),getNativeMainConnectionId:t=>e.getNativeMainConnectionId(t),getConnection:t=>e.getConnection(t),getWasmClient:()=>e.getWasmClient(),getLocalNodeId:()=>e.getLocalNodeId(),getReceiverDeviceId:()=>e.getDeviceId()??e.getOptions().localDeviceId??null,getKnownDeviceIdForNode:t=>e.getKnownDeviceIdForNode(t),getKnownDevicePlatform:(t,n)=>e.getKnownDevicePlatform(t,n),isNativeMainPeerPlatform:t=>rr(t),getTrustFailureCooldown:t=>e.getTrustFailureCooldown(t),isSessionTokenApprovedNode:t=>e.isSessionTokenApprovedNode(t),isSessionTokenApprovedConnection:t=>e.isSessionTokenApprovedConnection(t),getRTCConfig:()=>e$2(e.getOptions(),t=>c$1(t)),createTransportContext:t=>e.createTransportContext(t),getApplicationCrypto:()=>e.getApplicationCrypto(),shouldNegotiateApplicationKeyAgreement:()=>e.shouldNegotiateApplicationKeyAgreement(),handleConnectionTransportStatus:(t,n,i)=>e.handleConnectionTransportStatus(t,n,i??null),handleConnectionApplicationRouteMissing:(t,n)=>e.handleConnectionApplicationRouteMissing(t,n),initializeConnectionTrust:(t,n)=>{e.initializeConnectionTrust(t,n);},markConnectionTrustVerified:(t,n)=>{e.markConnectionTrustVerified(t,n);},registerConnection:t=>e.registerConnection(t),announceConnectionWhenStable:t=>e.announceConnectionWhenStable(t),sendTransportHandshake:(t,n)=>e.sendTransportHandshake(t,n),requestProtectedWebRTCUpgradeIfInitiator:(t,n)=>e.requestProtectedWebRTCUpgradeIfInitiator(t,n),getConnectionChannelId:t=>e.getConnectionChannelId(t),isWebRTCTransportEnabled:()=>d$1(e.getOptions()),getLocalDeviceId:()=>e.getLocalDeviceId(),getFallbackLocalDeviceId:()=>e.getDeviceId()||e.getOptions().localDeviceId||null,getConfiguredDeviceName:()=>e.getOptions().deviceName,isNativeRuntime:()=>typeof window<"u"&&typeof window.__TAURI__<"u",isLikelyMobileBrowser:()=>ce(),validateIncomingSessionToken:(t,n,i)=>e.validateIncomingSessionToken(t,n,i),applySessionTokenTrustApproval:(t,n,i)=>e.applySessionTokenTrustApproval(t,n,i),rememberPendingSessionTokenTrustApproval:(t,n)=>e.rememberPendingSessionTokenTrustApproval(t,n),markSessionTokenApprovedNode:t=>e.markSessionTokenApprovedNode(t),markSessionTokenApprovedConnection:t=>e.markSessionTokenApprovedConnection(t),clearSessionTokenRejectionCooldown:t=>e.clearSessionTokenRejectionCooldown(t),getSessionTokenRejectionCooldown:t=>e.getSessionTokenRejectionCooldown(t),setSessionTokenRejectionCooldown:(t,n)=>e.setSessionTokenRejectionCooldown(t,n),clearTrustFailureCooldown:t=>{e.clearTrustFailureCooldown(t);},schedulePeerReconciliation:t=>e.schedulePeerReconciliation(t),ensureIncomingConnectionForRemoteNode:t=>r.getController().ensureIncomingConnectionForRemoteNode(t),getReciprocalSessionAdmission:async(t,n,i,o,s)=>{let a=e.getRouteRepairSessionTokenForNode(t),c=e.getRouteRepairSessionTokenPayloadForNode(t);if(!a||!c)throw new Error("pending reciprocal session token is unavailable");let d=await e.getLocalDeviceId().catch(()=>null);if(!d)throw new Error("local device identity is unavailable for reciprocal admission");let l=e.getWasmClient();if(typeof l?.prepare_reciprocal_admission!="function")throw new Error("WASM runtime does not support inline reciprocal admission");return await l.prepare_reciprocal_admission(t,BigInt(i),o,s,a,c,d,n),{token:a,tokenPayload:c,deviceId:d,streamContract:n}},presentLegacyReciprocalSessionAdmission:async t=>{let n=e.getWasmClient(),i=e.getRouteRepairSessionTokenForNode(t),o=e.getRouteRepairSessionTokenPayloadForNode(t);if(!i||!o)throw new Error("pending reciprocal session token is unavailable");let s=await e.getLocalDeviceId().catch(()=>null);if(typeof n?.present_session_token=="function"){await n.present_session_token(t,i,o,s);return}throw new Error("WASM runtime does not support legacy reciprocal session admission")},confirmReciprocalSessionAdmission:async(t,n,i,o,s,a)=>{let c=e.getWasmClient();return typeof c?.confirm_reciprocal_admission!="function"?false:c.confirm_reciprocal_admission(t,BigInt(n),i,o,s,a)},disconnectRemoteNode:t=>e.disconnectRemoteNode(t),findManualDisconnectProjectionForNativeNode:t=>e.findManualDisconnectProjectionForNativeNode(t),findLiveConnectionForRemoteNode:t=>e.findLiveConnectionForRemoteNode(t),handleMessage:(t,n)=>e.handleMessage(t,n)},{eventName:_o,protocolByte:Ct,label:It,maxLabelBytes:St,maxFrameBytes:Do,protocolVersion:Eo},{trustFailureCooldownMs:Bo,inboundWriterRetryCooldownMs:Fo,pendingHandshakeTtlMs:xo,pendingHandshakeMaxPerNode:Lo})}function Rr(r){return new Ci({registerDisposer:e=>r.lifecycleScope.register(e),getOptions:()=>r.options,getWasmClient:()=>r.wasmClient,getLocalNodeId:()=>r.localNodeId,getDeviceId:()=>r.deviceId,getDeterministicConnectionId:e=>r.peerIdentity.getDeterministicConnectionId(e),getNativeMainConnectionId:e=>r.peerIdentity.getNativeMainConnectionId(e),getConnection:e=>r.registry.get(e),getKnownDeviceIdForNode:e=>r.deviceDirectory.getKnownDeviceIdForNode(e),getKnownDevicePlatform:(e,t)=>r.deviceDirectory.getKnownDevicePlatform(e,t),getTrustFailureCooldown:e=>r.connectionTrust.getFailureCooldown(e),getRouteRepairSessionTokenForNode:e=>r.sessionTokens.getRouteRepairTokenForNode(e),getRouteRepairSessionTokenPayloadForNode:e=>r.sessionTokens.getRouteRepairTokenPayloadForNode(e),isSessionTokenApprovedNode:e=>r.sessionTokens.isApprovedNode(e),isSessionTokenApprovedConnection:e=>r.sessionTokens.isApprovedConnection(e),createTransportContext:e=>r.transportContexts.create(e),getApplicationCrypto:()=>r.options?.applicationCrypto,shouldNegotiateApplicationKeyAgreement:()=>r.applicationCrypto.shouldNegotiateKeyAgreement(),handleConnectionTransportStatus:(e,t,n)=>r.transportHealth.handleCurrentConnectionTransportStatus(e,t,n),handleConnectionApplicationRouteMissing:(e,t)=>r.transportUpgrade.handleApplicationRouteMissing(e,t),initializeConnectionTrust:(e,t)=>{r.connectionTrust.initialize(e,t);},markConnectionTrustVerified:(e,t)=>{r.connectionTrust.markVerified(e,t);},registerConnection:e=>r.connectionLifecycle.registerConnection(e),announceConnectionWhenStable:e=>r.connectionLifecycle.announceConnectionWhenStable(e),sendTransportHandshake:(e,t)=>r.transportHandshake.sendTransportHandshake(e,t),requestProtectedWebRTCUpgradeIfInitiator:(e,t)=>r.transportHandshake.requestProtectedWebRTCUpgradeIfInitiator(e,t),getConnectionChannelId:e=>r.connectionChannelPolicy.getConnectionChannelId(e),getLocalDeviceId:()=>r.signalingBackendController.getLocalDeviceId(),validateIncomingSessionToken:(e,t,n)=>r.sessionTokens.validateIncomingSessionTokenWithRetry(e,t,n),applySessionTokenTrustApproval:(e,t,n)=>r.sessionTokens.applyTrustApproval(e,t,n),rememberPendingSessionTokenTrustApproval:(e,t)=>r.sessionTokens.rememberPendingTrustApproval(e,t),markSessionTokenApprovedNode:e=>r.sessionTokens.approveNode(e),markSessionTokenApprovedConnection:e=>r.sessionTokens.approveConnection(e),clearSessionTokenRejectionCooldown:e=>r.sessionTokens.clearRejectionCooldown(e),getSessionTokenRejectionCooldown:e=>r.sessionTokens.getRejectionCooldown(e),setSessionTokenRejectionCooldown:(e,t)=>r.sessionTokens.setRejectionCooldown(e,t),clearTrustFailureCooldown:e=>{r.connectionTrust.clearFailureCooldown(e);},schedulePeerReconciliation:e=>r.peerProjection.schedule(e),disconnectRemoteNode:e=>r.runtimeConnections.disconnectNodeBestEffort(e),findManualDisconnectProjectionForNativeNode:e=>r.peerIdentity.findManualDisconnectProjectionForNativeNode(e),findLiveConnectionForRemoteNode:e=>{let t=r.peerIdentity.getDeterministicConnectionId(e);return r.connectionLifecycle.findLiveConnectionForRemoteNode(e,t)},handleMessage:(e,t)=>r.connectionMessageHandler.handleMessage(e,t)})}var Ci=class{constructor(e){this.host=e;}get factoryHost(){return {host:this.host,getController:()=>this.controller}}get controller(){return this._controller??(this._controller=Pr(this.factoryHost))}writeLabelHeaderOnBiStream(e,t){return this.controller.writeLabelHeaderOnBiStream(e,t)}flushPendingHandshakesForNode(e,t){return this.controller.flushPendingHandshakesForNode(e,t)}flushPendingSignalsForNode(e,t){return this.controller.flushPendingSignalsForNode(e,t)}};var on=class{constructor(e,t){this.peerLifecycle=e;this.deps=t;this.disposed=false;this.deps.registerDisposer(()=>this.dispose());}dispose(){this.disposed=true;}watchPeerStates(e){return this.peerLifecycle.watch(e)}getPeerState(e){return this.peerLifecycle.get(e)}listConnectedPeers(){return this.peerLifecycle.listConnected()}isPeerPromotionEligible(e){return this.deps.resolvePromotionEligibility(e)}addPeerScope(e,t="persistent"){let n=this.deps.getWasmClient();return n&&typeof n.add_peer_scope=="function"?(n.add_peer_scope(e,t).then(()=>{this.disposed||this.deps.scheduleRefreshPeerSnapshot();}).catch(()=>{}),this.peerLifecycle.get(e)):this.peerLifecycle.addScope(e,t)}releasePeerScope(e,t){let n=this.deps.getWasmClient();return n&&typeof n.release_peer_scope=="function"?(n.release_peer_scope(e,t??null).then(()=>{this.disposed||this.deps.scheduleRefreshPeerSnapshot();}).catch(()=>{}),this.peerLifecycle.get(e)):this.peerLifecycle.releaseScope(e,t)}getPeerScopes(e){return this.peerLifecycle.get(e)?.scopes??[]}isSamePeer(e,t){let n=this.peerLifecycle.get(e),i=this.peerLifecycle.get(t);return n&&i?n.peerId===i.peerId:false}clearManualDisconnectProjection(e){let t=this.peerLifecycle.get(e);this.peerLifecycle.dispatch({type:"ManualDisconnectCleared",peerId:t?.peerId??e,deviceId:t?.deviceId??e,deviceIdHint:t?.deviceIdHint,nodeId:t?.nodeId,connectionId:t?.connectionId});}async disconnectPeer(e,t="persistent"){let n=this.peerLifecycle.releaseScope(e,t);n&&n.scopes.length>0||await this.forceDisconnectPeer(e);}async forceDisconnectPeer(e){let t=this.peerLifecycle.releaseScope(e),n=this.getPeerCandidates(t?.peerId||e);if(await Promise.allSettled(Array.from(n).map(async i=>{let o=Array.from(this.deps.getConnections()).filter(a=>{let c=a.id.trim().toLowerCase(),d=a.deviceId.trim().toLowerCase();return i===d||i===c||c.includes(i)});await Promise.allSettled(o.map(a=>a.disconnect()));let s=t?.nodeId||(o[0]?.deviceId??null);s&&i===s.trim().toLowerCase()&&await this.deps.disconnectNode(s).catch(()=>{});})),this.deps.hasRustPeerLifecycleProjection()){if(this.disposed)return;await this.deps.schedulePeerReconciliation("disconnect-node").catch(()=>{});}this.disposed||this.peerLifecycle.dispatch({type:"ManualDisconnect",peerId:t?.peerId??e,deviceId:t?.deviceId,deviceIdHint:t?.deviceIdHint,nodeId:t?.nodeId,connectionId:t?.connectionId});}async getPeerHealth(e){let t=this.peerLifecycle.get(e);return t?t.health:"unknown"}getPeerCandidates(e){let t=this.peerLifecycle.get(e),n=new Set;return [e,t?.peerId,t?.deviceId,t?.nodeId,t?.connectionId,...t?.connectionIds??[]].forEach(o=>{if(!o)return;let s=o.trim().toLowerCase();s&&n.add(s);}),n}};function Se(r){if(!r)return null;let e=r.trim();return e?e.toLowerCase():null}function Ii(r){return r.deviceId||r.deviceIdHint||r.peerId||null}function rn(r){return [...r].sort()}function De(r,e){return r?r.peerId===e.peerId&&(r.deviceId??null)===(e.deviceId??null)&&(r.deviceIdHint??null)===(e.deviceIdHint??null)&&(r.nodeId??null)===(e.nodeId??null)&&(r.connectionId??null)===(e.connectionId??null)&&(r.ticket??null)===(e.ticket??null)&&!!r.online==!!e.online&&(r.deviceName??null)===(e.deviceName??null)&&(r.platformType??null)===(e.platformType??null)&&r.status===e.status&&r.health===e.health&&(r.lifecycleStage??null)===(e.lifecycleStage??null)&&(r.generation??null)===(e.generation??null)&&(r.baseTransportState??null)===(e.baseTransportState??null)&&(r.admissionState??null)===(e.admissionState??null)&&(r.transportState??null)===(e.transportState??null)&&(r.protocolState??null)===(e.protocolState??null)&&(r.webrtcState??null)===(e.webrtcState??null)&&!!r.routable==!!e.routable&&(r.transportStableId??null)===(e.transportStableId??null)&&(r.transportGeneration??null)===(e.transportGeneration??null)&&(r.routeGeneration??null)===(e.routeGeneration??null)&&(r.activeTransport??null)===(e.activeTransport??null)&&(r.fallbackTransport??null)===(e.fallbackTransport??null)&&(r.parallelTransport??null)===(e.parallelTransport??null)&&!!r.manualDisconnect==!!e.manualDisconnect&&(r.lastAuthoritativeEventAt??null)===(e.lastAuthoritativeEventAt??null)&&(r.lastTransientEventAt??null)===(e.lastTransientEventAt??null)&&(r.promotionEligible??true)===(e.promotionEligible??true)&&(r.error??null)===(e.error??null)&&JSON.stringify(rn(r.connectionIds))===JSON.stringify(rn(e.connectionIds))&&JSON.stringify(rn(r.scopes))===JSON.stringify(rn(e.scopes)):false}function Ee(r){return r==="closed"||r==="disconnected"||r==="failed"}function Tr(r){let{status:e,health:t,lifecycleStage:n,generation:i,baseTransportState:o,admissionState:s,transportState:a,protocolState:c,webrtcState:d,routable:l,transportStableId:p,transportGeneration:u,routeGeneration:h,activeTransport:m,fallbackTransport:f,parallelTransport:v,connectionId:y,error:C,...I}=r;return I}function kr(r){if(Ee(r.status))return "closed";let e=(r.transportState??"").trim().toLowerCase();return e==="connected"||r.connectionId||r.activeTransport?"connected":e==="connecting"||r.status==="connecting"?"connecting":e==="failed"||e==="degraded"?"degraded":"unknown"}function Je(r){return Ee(r.status)||r.webrtcState!=="ready"||!r.connectionId||r.transportStableId===null||r.transportStableId===void 0||r.health!=="healthy"||r.transportState!=="connected"?false:[r.activeTransport,r.parallelTransport].filter(t=>typeof t=="string").some(t)}function wr(r){return t(r)}function Si(r){return Ee(r.status)?"closed":Je(r)?"ready":r.webrtcState?r.webrtcState:[r.activeTransport,r.parallelTransport].filter(t=>typeof t=="string").some(t)?r.transportState==="connected"?"transport-open":"connecting":"unknown"}function ga(r){if(r.manualDisconnect||Ee(r.status))return "closed";let e=Si(r);if(e==="ready")return "webrtc-ready";if(e==="connecting"||e==="transport-open"||e==="route-probing")return "upgrading";if(r.routable===true||r.protocolState==="routable")return "protocol-ready";if(r.admissionState==="admitted")return "admitted";let t=r.baseTransportState??kr(r);return t==="connected"?"base-connected":t==="degraded"||r.health==="suspect"||r.health==="stale"?"degraded":r.status==="connecting"?"dialing":"discovered"}function ha(r){return Ee(r.status)?r.status:r.routable===true||r.protocolState==="routable"||Je(r)?"connected":r.status}function Ar(r){return {peerId:r.peerId,deviceId:r.deviceId??null,deviceIdHint:r.deviceIdHint??null,nodeId:r.nodeId??null,connectionId:r.connectionId??null,status:r.status,health:r.health,lifecycleStage:r.lifecycleStage??null,generation:r.generation??null,baseTransportState:r.baseTransportState??null,admissionState:r.admissionState??null,transportState:r.transportState??null,protocolState:r.protocolState??null,webrtcState:r.webrtcState??null,routable:r.routable??null,transportStableId:r.transportStableId??null,transportGeneration:r.transportGeneration??null,routeGeneration:r.routeGeneration??null,activeTransport:r.activeTransport??null,parallelTransport:r.parallelTransport??null,manualDisconnect:r.manualDisconnect??false,scopes:r.scopes,error:r.error??null}}function ma(r,e,t){let n={event:r,before:e?Ar(e):null,after:Ar(t)};c$1("[OpenRTC][projection]",n);}var sn=class{constructor(){this.peers=new Map;this.aliases=new Map;this.watchers=new Set;this.disposed=false;}resolveCanonicalPeerId(e){let t=[e.deviceId,e.deviceIdHint,e.nodeId,e.peerId,e.connectionId];for(let n of t){let i=Se(n);if(!i)continue;let o=this.aliases.get(i);if(o)return o}return Ii(e)}setAlias(e,t){let n=Se(e);n&&this.aliases.set(n,t);}snapshot(e){let t=Je(e),n=e.baseTransportState??kr(e),i=Si(e),o=e.routable,s=e.protocolState;return {peerId:e.peerId,deviceId:e.deviceId,deviceIdHint:e.deviceIdHint,nodeId:e.nodeId,connectionId:e.connectionId,connectionIds:Array.from(e.connectionIds.values()),ticket:e.ticket,online:e.online,deviceName:e.deviceName,platformType:e.platformType,status:ha(e),health:e.health,lifecycleStage:e.lifecycleStage??ga(e),generation:e.generation??e.transportGeneration,baseTransportState:n,admissionState:e.admissionState,transportState:e.transportState,protocolState:s,settledReady:o===true,readinessState:o===true?"routable":s,readinessReason:o===true?"peer-projection-routable":e.error,webrtcState:i,routable:o,transportStableId:e.transportStableId,transportGeneration:e.transportGeneration,routeGeneration:e.routeGeneration,activeTransport:e.activeTransport,fallbackTransport:e.fallbackTransport,parallelTransport:e.parallelTransport,manualDisconnect:e.manualDisconnect,lastAuthoritativeEventAt:e.lastAuthoritativeEventAt,lastTransientEventAt:e.lastTransientEventAt,promotionEligible:e.promotionEligible,scopes:Array.from(e.scopes.values()),lastSeenAt:e.lastSeenAt,error:t?void 0:e.error}}emit(){if(this.disposed)return;let e=this.list();this.watchers.forEach(t=>t(e));}rekeyPeer(e,t){let n=this.peers.get(e);if(!n)throw new Error(`Cannot rekey missing peer ${e}`);if(e===t)return n;this.peers.delete(e),n.peerId=t,this.peers.set(t,n);for(let[i,o]of this.aliases.entries())o===e&&this.aliases.set(i,t);return n}upsert(e){let t=e,n=this.resolveCanonicalPeerId(t)??Ii(t);if(!n)throw new Error("Peer projection upsert requires a device-keyed identifier.");let i=Ii(t)??n,o=this.peers.get(n),s=!!o;o||(o={peerId:n,connectionIds:new Set,status:t.status??"disconnected",health:t.health??"unknown",scopes:new Set},this.peers.set(n,o));let a=s?this.snapshot(o):void 0;if(i!==o.peerId){let A=t.deviceId||o.deviceId||t.deviceIdHint||o.deviceIdHint||t.nodeId||o.nodeId||o.peerId;A&&A!==o.peerId&&(o=this.rekeyPeer(o.peerId,A));}s&&typeof t.transportGeneration=="number"&&typeof o.transportGeneration=="number"&&t.transportGeneration<o.transportGeneration&&t.manualDisconnect!==true&&(t=Tr(t)),s&&typeof t.routeGeneration=="number"&&typeof o.routeGeneration=="number"&&(typeof t.transportGeneration!="number"||typeof o.transportGeneration!="number"||t.transportGeneration===o.transportGeneration)&&t.routeGeneration<o.routeGeneration&&t.manualDisconnect!==true&&(t=Tr(t)),t.deviceId&&(o.deviceId=t.deviceId),t.deviceIdHint!==void 0&&(o.deviceIdHint=t.deviceIdHint),t.nodeId&&(o.nodeId=t.nodeId);let c={generation:o.generation,lifecycleStage:o.lifecycleStage,protocolState:o.protocolState,webrtcState:o.webrtcState,routable:o.routable,transportStableId:o.transportStableId,transportGeneration:o.transportGeneration,routeGeneration:o.routeGeneration,activeTransport:o.activeTransport,fallbackTransport:o.fallbackTransport,parallelTransport:o.parallelTransport},d=Je(o)||Si(o)==="ready",p=(t.connectionId===void 0||o.connectionId===void 0||t.connectionId===o.connectionId)&&(t.transportGeneration===void 0||o.transportGeneration===void 0||t.transportGeneration===o.transportGeneration)&&(t.transportStableId===void 0||o.transportStableId===void 0||o.transportStableId===null||t.transportStableId===o.transportStableId),u=t.connectionId!==void 0&&o.connectionId!==void 0&&t.connectionId!==o.connectionId||t.transportGeneration!==void 0&&o.transportGeneration!==void 0&&t.transportGeneration>o.transportGeneration||t.transportStableId!==void 0&&t.transportStableId!==null&&o.transportStableId!==void 0&&o.transportStableId!==null&&t.transportStableId!==o.transportStableId,h=t.activeTransport!==void 0||t.parallelTransport!==void 0||t.transportStableId!==void 0||t.transportGeneration!==void 0||t.routeGeneration!==void 0||t.transportState!==void 0,m=wr(t.activeTransport)||wr(t.parallelTransport)||t.webrtcState==="ready"||t.webrtcState==="connecting",f=t.webrtcState==="closed"||t.webrtcState==="failed"||t.lifecycleStage==="closed"||t.status==="closed"||t.status==="disconnected"||t.status==="failed"||t.manualDisconnect===true,v=t.routable===true||t.protocolState==="routable",y=d&&p&&h&&v&&!m&&!f;u&&(o.generation=void 0,o.lifecycleStage=void 0,o.webrtcState=void 0,o.fallbackTransport=null,o.parallelTransport=null),t.connectionId&&(o.connectionId=t.connectionId,o.connectionIds.add(t.connectionId)),t.ticket!==void 0&&(o.ticket=t.ticket),t.online!==void 0&&(o.online=t.online),t.deviceName!==void 0&&(o.deviceName=t.deviceName),t.platformType!==void 0&&(o.platformType=t.platformType);let C=s&&(o.manualDisconnect===true||Ee(o.status)&&typeof o.error=="string"&&o.error.toLowerCase().includes("manual disconnect")),I=t.status==="connected"||t.status==="connecting"||t.routable===true||t.protocolState==="routable"||t.transportState==="connected"||t.activeTransport!==void 0||t.parallelTransport!==void 0;if(C&&I){let A=this.snapshot(o);return De(a,A)||this.emit(),A}if(I&&(o.lifecycleStage==="closed"&&t.lifecycleStage===void 0&&(o.lifecycleStage=void 0),o.baseTransportState==="closed"&&t.baseTransportState===void 0&&(o.baseTransportState=void 0),o.webrtcState==="closed"&&t.webrtcState===void 0&&(o.webrtcState=void 0),o.transportState==="closed"&&t.transportState===void 0&&(o.transportState=void 0),o.protocolState==="closed"&&t.protocolState===void 0&&(o.protocolState=void 0)),t.status&&(o.status=t.status),t.health&&(o.health=t.health),t.lifecycleStage!==void 0&&(o.lifecycleStage=t.lifecycleStage),t.generation!==void 0&&(o.generation=t.generation),t.baseTransportState!==void 0&&(o.baseTransportState=t.baseTransportState),t.admissionState!==void 0&&(o.admissionState=t.admissionState),t.transportState!==void 0&&(o.transportState=t.transportState),t.protocolState!==void 0&&(o.protocolState=t.protocolState),t.webrtcState!==void 0&&(o.webrtcState=t.webrtcState),t.routable!==void 0&&(o.routable=t.routable),t.transportStableId!==void 0&&(o.transportStableId=t.transportStableId),t.transportGeneration!==void 0&&(o.transportGeneration=t.transportGeneration),t.routeGeneration!==void 0&&(o.routeGeneration=t.routeGeneration),t.activeTransport!==void 0&&(o.activeTransport=t.activeTransport),t.fallbackTransport!==void 0&&(o.fallbackTransport=t.fallbackTransport),t.parallelTransport!==void 0&&(o.parallelTransport=t.parallelTransport),t.manualDisconnect!==void 0&&(o.manualDisconnect=t.manualDisconnect),t.lastAuthoritativeEventAt!==void 0&&(o.lastAuthoritativeEventAt=t.lastAuthoritativeEventAt),t.lastTransientEventAt!==void 0&&(o.lastTransientEventAt=t.lastTransientEventAt),t.promotionEligible!==void 0&&(o.promotionEligible=t.promotionEligible),(t.transportState!==void 0||t.transportStableId!==void 0||t.activeTransport!==void 0||t.parallelTransport!==void 0)&&!v&&!Je(o)&&(o.routable=false,o.protocolState==="routable"&&(o.protocolState=o.transportState==="connected"?"transport-only":o.transportState)),y&&(o.generation=c.generation,o.lifecycleStage=c.lifecycleStage,o.protocolState=c.protocolState,o.webrtcState=c.webrtcState,o.routable=c.routable,o.transportStableId=c.transportStableId,o.transportGeneration=c.transportGeneration,o.routeGeneration=c.routeGeneration,o.activeTransport=c.activeTransport,o.fallbackTransport=c.fallbackTransport,o.parallelTransport=c.parallelTransport),t.clearError?(o.error=void 0,t.manualDisconnect!==true&&(o.manualDisconnect=false)):t.error!==void 0&&(o.error=t.error,t.error.toLowerCase().includes("manual disconnect")&&(o.manualDisconnect=true)),t.lastSeenAt!==void 0&&(o.lastSeenAt=t.lastSeenAt),t.scopes)for(let A of t.scopes)o.scopes.add(A);(o.status==="closed"||o.status==="failed"||o.status==="disconnected")&&(o.routable=false,o.transportStableId=null,o.activeTransport=void 0,o.fallbackTransport=null,o.parallelTransport=null,o.webrtcState="closed",o.baseTransportState="closed",o.lifecycleStage="closed",(!o.transportState||o.transportState==="connected")&&(o.transportState="closed"),(!o.protocolState||o.protocolState==="routable")&&(o.protocolState="closed")),this.setAlias(o.peerId,o.peerId),this.setAlias(o.deviceId,o.peerId),this.setAlias(o.deviceIdHint,o.peerId),this.setAlias(o.nodeId,o.peerId),this.setAlias(o.connectionId,o.peerId);for(let A of o.connectionIds)this.setAlias(A,o.peerId);let P=this.snapshot(o);return De(a,P)||(ma(s?"upsert":"create",a??null,P),this.emit()),P}dispatch(e){let t={peerId:e.peerId,deviceId:e.deviceId,deviceIdHint:e.deviceIdHint,nodeId:e.nodeId,connectionId:e.connectionId};switch(e.type){case "ConnectionStateProjected":{let{type:n,...i}=e;return this.upsert(i)}case "ManualDisconnectCleared":return this.upsert({...t,status:"disconnected",health:"unknown",manualDisconnect:false,clearError:true,lastSeenAt:Date.now()});case "RosterDeviceDiscovered":return this.upsert({...t,deviceName:e.deviceName,platformType:e.platformType,ticket:e.ticket,online:e.online??true,scopes:e.scopes,lastSeenAt:e.lastSeenAt??Date.now()});case "PresenceOnline":return this.upsert({...t,online:true,lastSeenAt:e.lastSeenAt??Date.now()});case "PresenceOffline":return this.upsert({...t,online:false});case "DialStarted":return this.get(this.targetLookupId(t))?.status==="connected"?this.get(this.targetLookupId(t)):this.upsert({...t,status:"connecting"});case "BaseTransportConnected":return this.upsert({...t,status:this.get(this.targetLookupId(t))?.status==="connected"?void 0:"connecting",transportState:"connected",baseTransportState:"connected",transportGeneration:e.transportGeneration});case "AdmissionAccepted":return this.upsert({...t,admissionState:"admitted"});case "AdmissionRejected":return this.upsert({...t,admissionState:"rejected",error:e.reason});case "WebRtcNegotiationStarted":return this.upsert({...t,webrtcState:"connecting",generation:e.generation,transportGeneration:e.generation});case "WebRtcFailed":return this.upsert({...t,webrtcState:"failed",transportGeneration:e.transportGeneration});case "ControlPathClosed":return this.upsert({...t,status:"disconnected"});case "HealthObserved":return this.updateHealth(this.targetLookupId(t),e.health);case "ManualDisconnect":return this.upsert({...t,status:"closed",health:"stale",manualDisconnect:true,error:"manual disconnect"});case "ExplicitUnshare":return this.upsert({...t,status:"closed",manualDisconnect:true,error:"explicit unshare"})}}targetLookupId(e){return e.deviceId||e.deviceIdHint||e.peerId||e.nodeId||e.connectionId||""}upsertDevice(e){return this.upsert({deviceId:e.deviceId,nodeId:e.nodeId,ticket:e.ticket,online:e.online,deviceName:e.deviceName,platformType:e.platformType,lastSeenAt:typeof e.updatedAt=="number"?e.updatedAt:typeof e.lastSeenAt=="number"?e.lastSeenAt:Date.now()})}watch(e){return this.disposed?()=>{}:(this.watchers.add(e),e(this.list()),()=>{this.watchers.delete(e);})}dispose(){this.disposed=true,this.watchers.clear();}get(e){let t=Se(e),n=t?this.aliases.get(t):void 0,i=n&&this.peers.get(n)||this.peers.get(e);return i?this.snapshot(i):void 0}list(){return Array.from(this.peers.values()).map(e=>this.snapshot(e)).sort((e,t)=>{let n=e.lastSeenAt??0,i=t.lastSeenAt??0;return n!==i?i-n:e.peerId.localeCompare(t.peerId)})}listConnected(){return this.list().filter(e=>e.status==="connected")}addScope(e,t="persistent"){let n=this.resolveRecord(e);if(!n)return;let i=this.snapshot(n);n.scopes.add(t);let o=this.snapshot(n);return De(i,o)||this.emit(),o}releaseScope(e,t){let n=this.resolveRecord(e);if(!n)return;let i=this.snapshot(n);t?n.scopes.delete(t):n.scopes.clear();let o=this.snapshot(n);return De(i,o)||this.emit(),o}hasScopes(e){return (this.resolveRecord(e)?.scopes.size??0)>0}removeConnection(e){let t=this.resolveRecord(e);if(!t)return;let n=this.snapshot(t),i=Se(e);if(i){let s=Array.from(t.connectionIds).find(a=>Se(a)===i);s&&t.connectionIds.delete(s);}t.connectionId&&Se(t.connectionId)===i&&(t.connectionId=Array.from(t.connectionIds)[0]),t.connectionIds.size===0&&t.status==="connected"&&(t.status="closed",t.routable=false,t.transportState="closed",t.protocolState="closed");let o=this.snapshot(t);return De(n,o)||this.emit(),o}updateHealth(e,t,n){let i=this.resolveRecord(e);if(!i)return;let o=this.snapshot(i);i.health=t,n&&(i.status=n),i.lastSeenAt=Date.now();let s=this.snapshot(i);return De(o,s)||this.emit(),s}resolveRecord(e){let t=Se(e),n=t?this.aliases.get(t):void 0;return n&&this.peers.get(n)||this.peers.get(e)}};function bi(r){return r.webRtcDataPlaneLive&&!r.routeReady?{activeTransport:r.parallelTransport??"iroh-relay",fallbackTransport:"webrtc",parallelTransport:"webrtc"}:{activeTransport:r.activeTransport??void 0,fallbackTransport:r.parallelTransport??null,parallelTransport:r.parallelTransport??null}}function Nr(r){return r.settledReady?"routable":r.hasActiveConnection?"transport-only":r.rustStatusIsConnecting?"connecting":"closed"}function Mr(r){return r.hasActiveConnection?"connected":r.rustStatusIsConnecting?"connecting":r.mappedStatusIsTerminal?"closed":"unknown"}function Dr(r){return r.routeReady?"ready":r.webRtcDataPlaneLive?"route-probing":r.anyWebRtcTransportLabel?"connecting":"unknown"}function Er(r){return r.terminal?"closed":r.activeIsWebRtc?r.routeReady?"ready":"route-probing":r.parallelIsWebRtc?"route-probing":"unknown"}function fa(r,e){let t=p$1(r)??"",n=[r,e].map(p$1).filter(i=>!!i);return {activeTransportLabel:t,labels:n}}function an(r){let{activeTransportLabel:e,labels:t$1}=fa(r.activeTransport,r.parallelTransport),n=t$1.some(t);return {webRtcDataPlaneLive:r.source==="rust-session"?!!r.activeConnectionId&&r.transportStableId!==null&&r.transportStableId!==void 0&&(r.sessionStatusNormalized==="connected"||r.sessionStatusNormalized==="connecting")&&r.mappedHealth==="healthy"&&t(e):t(r.activeTransport),routeReady:r.routeReady,anyWebRtcTransportLabel:n}}function ya(r){if(r.isClosed)return "closed";let e=r.getUpgradeState();return e==="upgraded"?"webrtc":e==="upgrading"?"webrtc-upgrading":e==="failed"?"iroh-fallback":"connected"}function _r(r){let{connection:e,trustProjection:t,existingProjection:n,terminalTransportClose:i}=r;if(i){let c=n?.peerId??r.peerId??r.deviceId??r.deviceIdHint??e.id;return !c&&!r.deviceId&&!r.deviceIdHint?null:{event:{type:"ConnectionStateProjected",peerId:c,deviceId:n?.deviceId??r.deviceId,deviceIdHint:n?.deviceIdHint??r.deviceIdHint,nodeId:n?.nodeId??e.deviceId,connectionId:e.id,status:"closed",health:"stale",baseTransportState:"closed",transportState:"closed",protocolState:"closed",routable:false,promotionEligible:r.promotionEligible,lastSeenAt:Date.now()}}}if(t)return {event:{type:"ConnectionStateProjected",peerId:t.deviceId??e.remoteNodeId??e.id,deviceId:t.deviceId??void 0,deviceIdHint:t.deviceId??e.remoteNodeId??void 0,nodeId:e.remoteNodeId||e.deviceId,connectionId:e.id,status:e.isClosed?"closed":"connected",health:t.health,transportState:ya(e),activeTransport:e.getTransportStatus().activeTransport,protocolState:t.protocolState,routable:t.routable,promotionEligible:r.promotionEligible,error:t.error,lastSeenAt:Date.now()}};if(r.peerId||r.deviceId)return {event:{type:"ConnectionStateProjected",peerId:r.peerId??r.deviceId??e.remoteNodeId??e.id,deviceId:r.deviceId,nodeId:e.deviceId,connectionId:e.id,ticket:r.ticket,status:e.isClosed?"closed":"connected",health:"healthy",activeTransport:e.getTransportStatus().activeTransport,promotionEligible:r.promotionEligible,scopes:r.scopes,lastSeenAt:Date.now()}};let o=n?.peerId||n?.deviceId||n?.deviceIdHint,s=n?.deviceId,a=n?.deviceIdHint;return !o&&!s&&!a?null:{event:{type:"ConnectionStateProjected",peerId:o,deviceId:s,deviceIdHint:a,nodeId:e.deviceId,connectionId:e.id,status:e.isClosed?"closed":"connected",health:e.isClosed?"stale":"healthy",activeTransport:e.getTransportStatus().activeTransport,promotionEligible:r.promotionEligible,lastSeenAt:Date.now()}}}function xr(r,e){let t=r.activeConnectionId||r.candidates?.[0]||void 0,n=e.mapRustPeerStatus(r.status),i=String(n).trim().toLowerCase(),o=typeof r.readinessState=="string"&&r.readinessState.trim().length>0,s=e.mapRustPeerHealth(r.health),a=e.localTerminalClosed===true&&!!t,c=an({source:"rust-session",activeConnectionId:t,transportStableId:r.transportStableId,sessionStatusNormalized:i,mappedHealth:s,activeTransport:r.activeTransport,parallelTransport:r.parallelTransport,routeReady:e.webRtcApplicationRouteReady}),d=o?r.readinessState==="routable":!!r.settledReady,l=d,p=e.applicationRouteFailed&&!l,u=a?l:e.trustProjection?e.trustProjection.routable&&d:d,h=r.status==="connecting",m=Nr({settledReady:u,hasActiveConnection:!!t,rustStatusIsConnecting:h}),f=c.webRtcDataPlaneLive&&!c.routeReady,v=u&&!f,y=f&&m==="routable"?"transport-only":m,C=bi({webRtcDataPlaneLive:c.webRtcDataPlaneLive,routeReady:c.routeReady,activeTransport:r.activeTransport,parallelTransport:r.parallelTransport});return {event:{type:"ConnectionStateProjected",peerId:r.peerId??e.transientPeerId??e.anonymousSpacePeerId,deviceId:e.trustProjection?.deviceId??r.deviceId??void 0,deviceIdHint:r.deviceIdHint,nodeId:r.nodeId,connectionId:t,status:a&&!l?"closed":p?"failed":v?"connected":n,health:a&&!l||p?"stale":e.trustProjection?.health??s,generation:r.transportGeneration,baseTransportState:a&&!l?"closed":Mr({hasActiveConnection:!!t,rustStatusIsConnecting:h,mappedStatusIsTerminal:n==="closed"||n==="failed"||n==="disconnected"}),admissionState:a&&!l?"unknown":u||t?"admitted":"unknown",transportState:a&&!l?"closed":t?"connected":r.status==="connecting"?"connecting":"closed",protocolState:a&&!l?"closed":y,routable:v,transportStableId:a&&!l?void 0:r.transportStableId??void 0,transportGeneration:r.transportGeneration,routeGeneration:r.routeGeneration,activeTransport:a&&!l?void 0:C.activeTransport,fallbackTransport:a&&!l?void 0:C.fallbackTransport,parallelTransport:a&&!l?void 0:C.parallelTransport,webrtcState:a&&!l?"closed":Dr({routeReady:c.routeReady,webRtcDataPlaneLive:c.webRtcDataPlaneLive,anyWebRtcTransportLabel:c.anyWebRtcTransportLabel}),promotionEligible:e.promotionEligible,scopes:e.sessionScopes,error:a&&!l?"local-transport-closed":p?"application-route-timeout":e.trustProjection?.error??(v?void 0:r.error??void 0),clearError:v,lastSeenAt:r.lastSeenAtMs},clearApplicationRouteFailure:l&&t?t:void 0}}function va(r){return !(!r.projectedDeviceId&&!r.projectedDeviceIdHint&&!r.existingProjection&&!r.anonymousTerminalProjectionAllowed&&!r.localTerminalClosed)}function Lr(r,e){if(!va(e))return null;let t$1=e.localTerminalClosed===true,n=an({source:"backend-state",activeTransport:r.activeTransport,parallelTransport:r.parallelTransport,routeReady:e.webRtcApplicationRouteReady}),i=u$1(r.activeTransport)?r.routable===true:e.liveConnection?e.applicationRouteReady:r.routable===true&&(!n.webRtcDataPlaneLive||n.routeReady),o=r.routable===true&&i&&!e.terminalState,s=t$1&&!o,a=e.terminalState||s,c=a?false:e.trustProjection?e.trustProjection.routable:r.routable,d=c&&i,l=s?"closed":e.terminalState?r.protocolState??"closed":d?"routable":r.transportState==="connected"?"transport-only":e.trustProjection?.protocolState??r.protocolState,p=a?s?"local-transport-closed":r.error??r.lastDisconnectReason??e.trustProjection?.error:e.trustProjection?.error??r.error,u=a?"stale":e.trustProjection?.health??(d||r.transportState==="connected"?"healthy":r.state==="failed"||r.state==="closed"?"stale":"unknown"),h=bi({webRtcDataPlaneLive:n.webRtcDataPlaneLive,routeReady:n.routeReady,activeTransport:r.activeTransport,parallelTransport:r.parallelTransport});return {event:{type:"ConnectionStateProjected",peerId:e.existingProjection?.peerId??(e.anonymousTerminalProjectionAllowed?r.remoteNodeId??r.connectionId:void 0),deviceId:e.projectedDeviceId,deviceIdHint:e.projectedDeviceIdHint,nodeId:r.remoteNodeId??e.existingProjection?.nodeId??void 0,connectionId:r.connectionId,status:s?"closed":r.state==="connected"?"connected":r.state==="connecting"||r.state==="new"?"connecting":r.state==="failed"?"failed":r.state==="closed"?"closed":"disconnected",health:u,generation:r.transportGeneration,baseTransportState:a?"closed":r.transportState==="connected"?"connected":r.transportState==="connecting"||r.state==="connecting"||r.state==="new"?"connecting":r.transportState==="failed"?"degraded":"unknown",admissionState:c||r.readinessState==="routable"?"admitted":a?"unknown":"pending",transportState:s?"closed":r.transportState,protocolState:l,webrtcState:Er({terminal:a,activeIsWebRtc:n.webRtcDataPlaneLive,routeReady:n.routeReady,parallelIsWebRtc:t(r.parallelTransport)}),routable:d,transportStableId:s?void 0:r.transportStableId??void 0,transportGeneration:r.transportGeneration,routeGeneration:r.routeGeneration,activeTransport:s?void 0:h.activeTransport,fallbackTransport:s?void 0:h.fallbackTransport,parallelTransport:s?void 0:h.parallelTransport,error:p,lastAuthoritativeEventAt:r.updatedAt??Date.now(),lastSeenAt:r.updatedAt??Date.now()}}}function Br(r,e,t){let n=Ca(e,{status:r.status,health:r.health,routable:r.routable,protocolState:r.protocolState},t);return n?{...r,...n}:r}function Ca(r,e,t$1){if(!r||r.isClosed)return null;let{activeTransport:n,parallelTransport:i}=r.getTransportStatus(),o=t(n)||t(i);if(!o||!r.getWebRTCTransport()||e.status==="closed"||e.status==="failed"||e.status==="disconnected")return null;let c=t$1.applicationRouteReady&&(e.routable===true||e.protocolState==="routable"),d=t$1.webRtcApplicationRouteReady;return {status:e.status==="connected"||c?"connected":e.status,health:e.health==="stale"?"healthy":e.health,baseTransportState:"connected",transportState:"connected",protocolState:c?"routable":o&&!d?"transport-only":e.protocolState,webrtcState:d?"ready":"route-probing",routable:c,activeTransport:d?n:"iroh-relay",fallbackTransport:i,parallelTransport:d?i:"webrtc",clearError:c&&d,lastTransientEventAt:Date.now()}}var Pi=2e3,Ri=3e3,cn=class{constructor(e=Pi,t=Ri){this.tsGraceMs=e;this.rustGraceMs=t;this.tsOrphanSince=new Map;this.rustOrphanSince=new Map;this.reportedRustOrphans=new Set;}evaluateTsOrphans(e,t){let n=new Set(e);for(let o of [...this.tsOrphanSince.keys()])n.has(o)||this.tsOrphanSince.delete(o);for(let o of n)this.tsOrphanSince.has(o)||this.tsOrphanSince.set(o,t);let i=[];for(let o of n){let s=this.tsOrphanSince.get(o);s!==void 0&&t-s>=this.tsGraceMs&&i.push(o);}return {toDisconnect:i}}evaluateRustOrphans(e,t){let n=new Set(e);for(let o of [...this.rustOrphanSince.keys()])n.has(o)||(this.rustOrphanSince.delete(o),this.reportedRustOrphans.delete(o));for(let o of n)this.rustOrphanSince.has(o)||this.rustOrphanSince.set(o,t);let i=[];for(let o of n){let s=this.rustOrphanSince.get(o);s!==void 0&&t-s>=this.rustGraceMs&&!this.reportedRustOrphans.has(o)&&(this.reportedRustOrphans.add(o),i.push(o));}return {toReport:i}}clear(){this.tsOrphanSince.clear(),this.rustOrphanSince.clear(),this.reportedRustOrphans.clear();}};function Fr(r){let e=String(r??"").trim().toLowerCase();return e==="connected"||e==="connecting"||e==="new"}function Ia(r){let e=String(r.state??"").trim().toLowerCase();return e==="connected"||e==="connecting"||e==="new"}function Ti(r){return r.activeConnectionId||r.candidates?.[0]||void 0}function Sa(r,e,t){return e.some(i=>Ti(i)===r&&Fr(i.status))?true:t.some(i=>i.connectionId===r&&Ia(i))}function ba(r,e){return r.routable===true&&(r.connectionId===e||r.connectionIds.includes(e))}function Pa(r){let e=[],t=[];if(r.hasRustProjection)for(let[n,i]of r.connections)i.isClosed||Sa(n,r.rustSessions,r.backendStates)||e.push(n);for(let n of r.rustSessions){let i=Ti(n);if(!i||!Fr(n.status)||!(n.settledReady===true||n.readinessState==="routable"||r.peerStates.some(a=>ba(a,i))))continue;let s=r.connections.get(i);(!s||s.isClosed)&&t.push(i);}return {orphanTsConnectionIds:e,orphanRustRecordConnectionIds:t}}function Ra(r,e,t,n=Date.now()){if(!r.hasRustPeerLifecycleProjection())return t.clear(),{reportedDrift:{orphanTsConnectionIds:[],orphanRustRecordConnectionIds:[]},closedTsConnectionIds:[]};t.evaluateTsOrphans(e.orphanTsConnectionIds,n);let{toReport:i}=t.evaluateRustOrphans(e.orphanRustRecordConnectionIds,n);return {reportedDrift:{orphanTsConnectionIds:e.orphanTsConnectionIds,orphanRustRecordConnectionIds:i},closedTsConnectionIds:[]}}var ln=class{constructor(e){this.run=e;this.inFlight=null;this.queuedReason=null;this.disposed=false;this.stats={scheduled:0,coalesced:0,ran:0,orphanTsConnection:0,orphanRustRecord:0,orphanTsConnectionHealed:0};}getStats(){return this.stats}dispose(){this.disposed=true,this.queuedReason=null;}recordDrift(e){e.orphanTsConnectionIds.length>0&&(this.stats.orphanTsConnection+=e.orphanTsConnectionIds.length,b("[Client][PEER-RECONCILE] orphan_ts_connection",{count:e.orphanTsConnectionIds.length,connectionIds:e.orphanTsConnectionIds})),e.orphanRustRecordConnectionIds.length>0&&(this.stats.orphanRustRecord+=e.orphanRustRecordConnectionIds.length,b("[Client][PEER-RECONCILE] orphan_rust_record",{count:e.orphanRustRecordConnectionIds.length,connectionIds:e.orphanRustRecordConnectionIds}));}recordSelfHeal(e){e.closedTsConnectionIds.length>0&&(this.stats.orphanTsConnectionHealed+=e.closedTsConnectionIds.length,b("[Client][PEER-RECONCILE] orphan_ts_connection_healed",{count:e.closedTsConnectionIds.length,connectionIds:e.closedTsConnectionIds})),this.recordDrift(e.reportedDrift);}schedule(e){return this.disposed?Promise.resolve([]):(this.stats.scheduled+=1,this.inFlight?(this.stats.coalesced+=1,this.queuedReason=e,b("[Client][PEER-RECONCILE] coalesced",{reason:e}),this.inFlight):(b("[Client][PEER-RECONCILE] started",{reason:e}),this.inFlight=this.executeRun(e),this.inFlight))}async executeRun(e){let t=e;try{for(;;){this.stats.ran+=1;let n=await this.run(t);b("[Client][PEER-RECONCILE] finished",{reason:t,stats:this.getStats()});let i=this.queuedReason;if(this.queuedReason=null,this.disposed)return [];if(!i)return n;t=i,b("[Client][PEER-RECONCILE] rerun",{reason:t});}}finally{this.inFlight=null;}}};async function Wr(r,e){let t=r.hasRustPeerLifecycleProjection(),n=false,i=[];if(r.wasmClient&&typeof r.wasmClient.peer_sessions=="function"){let l=await r.wasmClient.peer_sessions();if(Array.isArray(l)){i=l;for(let p of l){let u=Ti(p);if(!r.hasResolvablePeerIdentity({deviceId:p.deviceId,deviceIdHint:p.deviceIdHint,nodeId:p.nodeId,connectionId:u})){b("[Client][PEER-SNAPSHOT] skipping rust session without identity",{status:p.status,health:p.health,settledReady:p.settledReady});continue}r.applyComposedRustSession(p),n=true;}}}(await r.searchDevices().catch(()=>[])).forEach(l=>{if(!r.hasResolvablePeerIdentity({deviceId:l.deviceId??null,nodeId:l.nodeId??null})){b("[Client][PEER-SNAPSHOT] skipping device projection without identity",{deviceName:l.deviceName??null,online:l.online??null});return}r.peerLifecycle.upsertDevice(l);}),t||r.connections.forEach(l=>{r.syncConnectionPeerLifecycle(l);});let s=await r.signaling.getConnectionStates().catch(()=>[]);s.forEach(l=>{r.applyBackendConnectionState(l);});let a=r.peerLifecycle.list(),c=Pa({hasRustProjection:t,connections:r.connections,rustSessions:i,backendStates:s,peerStates:a}),d=r.getOrphanDriftTracker?.();if(d){let l=Ra(r,c,d);r.recordReconciliationSelfHeal?.(l);}else r.recordReconciliationDrift?.(c);return t&&!n&&s.length===0,a}function wi(r,e){return r&&typeof r.supportsRustPeerLifecycleProjection=="function"&&r.supportsRustPeerLifecycleProjection()?true:!!(e&&typeof e.peer_sessions=="function")}var dn=class{constructor(e,t){this.ctx=e;this.deps=t;this.disposed=false;this.orphanDriftTracker=new cn(t.orphanReconciliationGrace?.tsConnectionMs??Pi,t.orphanReconciliationGrace?.rustRecordMs??Ri),this.scheduler=new ln(n=>Wr(this.asReconciliationHost())),this.ctx.registerDisposer(()=>this.dispose());}schedule(e){return this.scheduler.schedule(e)}dispose(){this.disposed=true,this.scheduler.dispose(),this.orphanDriftTracker.clear();}getStats(){return this.scheduler.getStats()}hasRustPeerLifecycleProjection(){return wi(this.deps.getSignaling(),this.getPeerSessionReader())}dispatchLiveConnectionProjection(e,t){if(this.disposed)return;let n=_r({connection:e,...t});n&&this.dispatchComposedConnectionState(n.event,e,{applicationRouteReady:t.applicationRouteReady,webRtcApplicationRouteReady:t.webRtcApplicationRouteReady});}applyConnectionTrustProjection(e){if(this.disposed||this.hasRustPeerLifecycleProjection())return;let t=this.deps.resolvePromotionEligibility({connectionId:e.id,nodeId:e.remoteNodeId}),n=this.deps.getConnectionTrustProjection({connectionId:e.id,nodeId:e.remoteNodeId}),i=this.deps.hasApplicationRouteForConnection(e),o=this.deps.isWebRtcApplicationRouteReadyForConnection(e);if(!n){this.syncConnectionPeerLifecycle(e);return}this.dispatchLiveConnectionProjection(e,{trustProjection:n,promotionEligible:t,applicationRouteReady:i,webRtcApplicationRouteReady:o});}applyBackendConnectionState(e){if(this.disposed||!e?.connectionId)return;let t=this.deps.getConnectionTrustProjection({connectionId:e.connectionId,deviceId:e.deviceId??void 0,deviceIdHint:e.deviceIdHint??void 0,nodeId:e.remoteNodeId??void 0}),n=this.getPeerState(e.connectionId)??(e.remoteNodeId?this.getPeerState(e.remoteNodeId):void 0),i=e.deviceId??t?.deviceId??n?.deviceId??void 0,o=e.deviceIdHint??n?.deviceIdHint??void 0,s=e.state==="closed"||e.state==="failed"||e.state==="disconnected",a=this.deps.hasLocalTerminalConnectionClose(e.connectionId),c=(s||a)&&!!(e.connectionId||e.remoteNodeId);if(!i&&!o&&!n&&!c)return;b("[Client] applyBackendConnectionState",{connectionId:e.connectionId,deviceId:i??null,deviceIdHint:o??null,remoteNodeId:e.remoteNodeId??null,state:e.state,transportState:e.transportState??null,protocolState:e.protocolState??null,routable:e.routable??null,updatedAt:e.updatedAt??null,error:e.error??null,mappedPeerId:n?.peerId??null});let d=this.ctx.registry.get(e.connectionId)??(e.remoteNodeId?this.deps.getConnectionForPeer(void 0,e.remoteNodeId):null),l=this.deps.hasApplicationRouteForConnection(d),p=this.deps.isWebRtcApplicationRouteReadyForConnection(d),u=Lr(e,{trustProjection:t,existingProjection:n,liveConnection:d,applicationRouteReady:l,webRtcApplicationRouteReady:p,terminalState:s,localTerminalClosed:a,anonymousTerminalProjectionAllowed:c,projectedDeviceId:i,projectedDeviceIdHint:o});u&&this.dispatchComposedConnectionState(u.event,d,{applicationRouteReady:l,webRtcApplicationRouteReady:p});}applyComposedRustSession(e){if(this.disposed)return;let t=e.activeConnectionId||e.candidates?.[0],n=this.deps.hasLocalTerminalConnectionClose(t),i=e.scopes??[],o=!!e.nodeId&&this.deps.sessionTokenApprovedNodes().has(e.nodeId)||!!t&&this.deps.sessionTokenApprovedConnectionIds().has(t),s=!e.peerId&&!e.deviceId&&!e.deviceIdHint&&o?`session-token:${i[0]??"unscoped"}:${e.nodeId??t}`:void 0,a=!e.peerId&&!e.deviceId&&!e.deviceIdHint&&this.ctx.discoveryMode==="space"?e.nodeId??t:void 0,c=this.deps.resolvePromotionEligibility({connectionId:t||void 0,deviceId:e.deviceId??void 0,deviceIdHint:e.deviceIdHint??void 0,nodeId:e.nodeId??void 0}),d=this.deps.getConnectionTrustProjection({connectionId:t||void 0,deviceId:e.deviceId??void 0,deviceIdHint:e.deviceIdHint??void 0,nodeId:e.nodeId??void 0}),l=this.deps.getConnectionForPeer(t||void 0,e.nodeId??void 0),p=this.deps.hasApplicationRouteForConnection(l),u=!!t&&!p&&this.deps.hasApplicationRouteFailure(t),h=String(this.mapRustPeerStatus(e.status)).trim().toLowerCase(),f=an({source:"rust-session",activeConnectionId:t,transportStableId:e.transportStableId,sessionStatusNormalized:h,mappedHealth:this.mapRustPeerHealth(e.health),activeTransport:e.activeTransport,parallelTransport:e.parallelTransport,routeReady:false}).webRtcDataPlaneLive&&this.deps.isWebRtcApplicationRouteReadyForConnection(l),v=xr(e,{trustProjection:d,promotionEligible:c,liveConnection:l,applicationRouteReady:p,webRtcApplicationRouteReady:f,applicationRouteFailed:u,localTerminalClosed:n,mapRustPeerStatus:y=>this.mapRustPeerStatus(y),mapRustPeerHealth:y=>this.mapRustPeerHealth(y),peerId:e.peerId,transientPeerId:s,anonymousSpacePeerId:a,sessionScopes:i});v.clearApplicationRouteFailure&&this.deps.clearApplicationRouteFailure(v.clearApplicationRouteFailure),this.dispatchComposedConnectionState(v.event,l,{applicationRouteReady:p,webRtcApplicationRouteReady:f});}syncConnectionPeerLifecycle(e){if(this.disposed)return;let t=this.deps.resolvePromotionEligibility({connectionId:e.id,nodeId:e.remoteNodeId}),n=this.getPeerState(e.id)||this.listPeerStates().find(i=>i.connectionIds.includes(e.id)||i.nodeId===e.deviceId);this.dispatchLiveConnectionProjection(e,{trustProjection:null,promotionEligible:t,existingProjection:n,applicationRouteReady:this.deps.hasApplicationRouteForConnection(e),webRtcApplicationRouteReady:this.deps.isWebRtcApplicationRouteReadyForConnection(e)});}mapRustPeerStatus(e){switch((e||"").toLowerCase()){case "connected":return "connected";case "connecting":case "pending":return "connecting";case "failed":return "failed";case "closing":case "closed":return "closed";default:return "disconnected"}}mapRustPeerHealth(e){switch((e||"").toLowerCase()){case "healthy":return "healthy";case "suspect":return "suspect";case "stale":return "stale";default:return "unknown"}}asReconciliationHost(){return {hasRustPeerLifecycleProjection:()=>this.hasRustPeerLifecycleProjection(),wasmClient:this.getPeerSessionReader(),signaling:this.deps.getSignaling(),peerLifecycle:this.deps.peerLifecycle,connections:this.ctx.registry,discoveryMode:this.ctx.discoveryMode,sessionTokenApprovedNodes:this.deps.sessionTokenApprovedNodes(),sessionTokenApprovedConnectionIds:this.deps.sessionTokenApprovedConnectionIds(),hasResolvablePeerIdentity:e=>this.hasResolvablePeerIdentity(e),applyComposedRustSession:e=>this.applyComposedRustSession(e),applyBackendConnectionState:e=>this.applyBackendConnectionState(e),searchDevices:()=>this.deps.searchDevices(),syncConnectionPeerLifecycle:e=>this.syncConnectionPeerLifecycle(e),getOrphanDriftTracker:()=>this.orphanDriftTracker,recordReconciliationSelfHeal:e=>this.scheduler.recordSelfHeal(e),recordReconciliationDrift:e=>this.scheduler.recordDrift(e)}}getPeerSessionReader(){return this.ctx.wasmClient&&typeof this.ctx.wasmClient=="object"?this.ctx.wasmClient:null}hasResolvablePeerIdentity(e){if(e.deviceId||e.deviceIdHint)return true;let t=[e.nodeId,e.connectionId].map(o=>typeof o=="string"?o.trim():"").filter(o=>o.length>0);if(this.ctx.discoveryMode==="space"&&t.length>0)return true;let n=this.deps.sessionTokenApprovedNodes(),i=this.deps.sessionTokenApprovedConnectionIds();return t.some(o=>!!this.getPeerState(o)||n.has(o)||i.has(o))}dispatchComposedConnectionState(e,t,n){let i=Br(e,t,n);this.deps.peerLifecycle.dispatch(i);}getPeerState(e){let t=this.deps.peerLifecycle;return typeof t.get=="function"?t.get(e):void 0}listPeerStates(){let e=this.deps.peerLifecycle;return typeof e.list=="function"?e.list():[]}};function Or(r){return new Ai({getContext:()=>r.getClientContext(),getWasmClient:()=>r.wasmClient,getSignaling:()=>r.signaling,getConnections:()=>r.registry.values(),disconnectNode:e=>r.runtimeConnections.disconnectNode(e),registerDisposer:e=>r.lifecycleScope.register(e),hasRustPeerLifecycleProjection:()=>r.hasRustPeerLifecycleProjection(),getOrphanReconciliationGrace:()=>r.options?.orphanReconciliationGrace,getSessionTokenApprovedNodes:()=>r.sessionTokens.getApprovedNodes(),getSessionTokenApprovedConnectionIds:()=>r.sessionTokens.getApprovedConnectionIds(),resolvePromotionEligibility:e=>r.connectionChannelPolicy.resolvePromotionEligibility(e),getConnectionTrustProjection:e=>r.connectionTrust.getProjection(e),getConnectionForPeer:(e,t)=>r.registry.getForPeer(e??void 0,t??void 0),hasApplicationRouteForConnection:e=>r.transportServices.hasApplicationRouteForConnectionSnapshot(e,e?.id,e?.remoteNodeId),isWebRtcApplicationRouteReadyForConnection:e=>r.transportServices.isWebRtcReady(e),hasLocalTerminalConnectionClose:e=>r.registry.hasLocalTerminalClose(e),hasApplicationRouteFailure:e=>r.transportServices.hasApplicationRouteFailure(e),clearApplicationRouteFailure:e=>r.transportServices.clearApplicationRouteFailure(e),searchDevices:()=>r.deviceDirectory.searchDevices(),healOrphanTsConnection:e=>r.connectionLifecycle.healOrphanTsConnection(e)})}var Ai=class{constructor(e){this.host=e;this.store=new sn;this.host.registerDisposer(()=>{this.store.dispose();});}get projection(){return this._projection||(this._projection=new dn(this.host.getContext(),{orphanReconciliationGrace:this.host.getOrphanReconciliationGrace(),sessionTokenApprovedNodes:()=>this.host.getSessionTokenApprovedNodes(),sessionTokenApprovedConnectionIds:()=>this.host.getSessionTokenApprovedConnectionIds(),resolvePromotionEligibility:e=>this.host.resolvePromotionEligibility(e),getConnectionTrustProjection:e=>this.host.getConnectionTrustProjection(e),getConnectionForPeer:(e,t)=>this.host.getConnectionForPeer(e,t),hasApplicationRouteForConnection:e=>this.host.hasApplicationRouteForConnection(e),isWebRtcApplicationRouteReadyForConnection:e=>this.host.isWebRtcApplicationRouteReadyForConnection(e),hasLocalTerminalConnectionClose:e=>this.host.hasLocalTerminalConnectionClose(e),hasApplicationRouteFailure:e=>this.host.hasApplicationRouteFailure(e),clearApplicationRouteFailure:e=>this.host.clearApplicationRouteFailure(e),searchDevices:()=>this.host.searchDevices(),healOrphanTsConnection:e=>this.host.healOrphanTsConnection(e),getSignaling:()=>this.host.getSignaling(),peerLifecycle:this.store})),this._projection}get client(){return this._client||(this._client=new on(this.store,{getWasmClient:()=>this.host.getWasmClient(),getConnections:()=>this.host.getConnections(),disconnectNode:e=>this.host.disconnectNode(e),hasRustPeerLifecycleProjection:()=>this.host.hasRustPeerLifecycleProjection(),schedulePeerReconciliation:e=>this.projection.schedule(e),scheduleRefreshPeerSnapshot:()=>this.projection.schedule("peer-lifecycle-client").then(()=>{}),registerDisposer:e=>this.host.registerDisposer(e),resolvePromotionEligibility:e=>this.host.resolvePromotionEligibility(e)})),this._client}getProjectionStats(){return this._projection?.getStats()}watchPeerStates(e){return this.store.watch?.(e)??(()=>{})}getPeerState(e){return this.store.get?.(e)}listConnectedPeers(){return this.store.listConnected?.()??[]}listPeerStates(){return this.store.list?.()??[]}getPeerScopes(e){return this.getPeerState(e)?.scopes??[]}getPeerStatus(e){return this.getPeerState(e)?.status}hasPeerScopes(e){return this.store.hasScopes?.(e)??this.getPeerScopes(e).length>0}isSamePeer(e,t){let n=this.getPeerState(e),i=this.getPeerState(t);return !!n&&!!i&&n.peerId===i.peerId}getPeerHealth(e){return this.getPeerState(e)?.health??"unknown"}isPeerPromotionEligible(e){return this.client.isPeerPromotionEligible(e)}addPeerScope(e,t="persistent"){return this.client.addPeerScope(e,t)}releasePeerScope(e,t){return this.client.releasePeerScope(e,t)}clearManualDisconnectProjection(e){this.client.clearManualDisconnectProjection(e);}disconnectPeer(e,t="persistent"){return this.client.disconnectPeer(e,t)}forceDisconnectPeer(e){return this.client.forceDisconnectPeer(e)}applyDiscoveredDevice(e){this.store.upsertDevice?.(e);}};function Ta(r){return ko({get wasmClient(){return r.getWasmClient()},get roomCreationMode(){return r.getRoomCreationMode()},get appLimits(){return r.getAppLimits()},ensureAuthenticated:e=>r.ensureAuthenticated(e),getTicketWithToken:(e,t)=>r.getTicketWithToken(e,t),getNodeId:()=>r.getNodeId(),connect:(e,t)=>r.connect(e,t),refreshHostedAppSettings:e=>r.refreshHostedAppSettings(e),getRoomBackendTag:()=>r.getRoomBackendTag()})}function Ur(r){return Ta({getWasmClient:()=>r.wasmClient,getRoomCreationMode:()=>r.getRoomCreationMode(),getAppLimits:()=>r.getAppLimits(),ensureAuthenticated:e=>r.auth.ensureAuthenticated(e),getTicketWithToken:(e,t)=>r.sessionTokens.getTicketWithToken(e,t),getNodeId:()=>r.runtimeIdentity.getNodeId(),connect:(e,t)=>r.connectionDialer.connect(e,t),refreshHostedAppSettings:e=>r.signalingBackendController.refreshHostedAppSettings(e),getRoomBackendTag:()=>r.runtimeStatus.getRoomBackendTag()})}var pn=class{constructor(e,t={}){this.ctx=e;this.deps=t;this.browserBackgrounded=false;this.disposed=false;this.removeBrowserListeners=null;this.ctx.registerDisposer(()=>this.dispose());}dispose(){this.disposed||(this.disposed=true,this.removeBrowserListeners?.(),this.removeBrowserListeners=null);}installListeners(){if(this.disposed||this.removeBrowserListeners||typeof document>"u"||typeof window>"u")return;let e=()=>{if(this.disposed)return;let o=document.visibilityState==="hidden";this.handleBackgroundState(o,"visibilitychange");},t=()=>{this.disposed||this.handleBackgroundState(false,"pageshow");},n=()=>{this.disposed||(this.syncCoordinationAvailability("online"),this.reconcileConnectionsAfterAvailabilityHint("online"));},i=()=>{this.disposed||this.syncCoordinationAvailability("offline");};e(),document.addEventListener("visibilitychange",e),window.addEventListener("pageshow",t),window.addEventListener("online",n),window.addEventListener("offline",i),this.removeBrowserListeners=()=>{document.removeEventListener("visibilitychange",e),window.removeEventListener("pageshow",t),window.removeEventListener("online",n),window.removeEventListener("offline",i);};}async handleBackgroundState(e,t){if(this.disposed)return;let n=this.browserBackgrounded!==e;this.browserBackgrounded=e,this.syncCoordinationAvailability(t);let i=this.ctx.wasmClient;if(i&&typeof i.set_app_backgrounded=="function")try{await i.set_app_backgrounded(e);}catch(o){console.warn("[Client][APP] Failed to propagate background state to wasm runtime",{backgrounded:e,source:t,error:o});}this.disposed||!e&&n&&this.reconcileConnectionsAfterAvailabilityHint(t);}reconcileConnectionsAfterForeground(e){this.reconcileConnectionsAfterAvailabilityHint(e);}syncCoordinationAvailability(e){this.deps.setCoordinationHostAvailability?.({available:!this.browserBackgrounded&&(typeof navigator>"u"||navigator.onLine!==false),reason:e});}reconcileConnectionsAfterAvailabilityHint(e){if(!this.disposed)for(let t of this.ctx.registry.values()){if(t.isClosed)continue;let n=t.getUpgradeState();c$1("[Client][APP] Availability recovery reconcile",{source:e,connectionId:t.id,remoteNodeId:t.remoteNodeId,upgradeState:n}),t.handleAppForeground();}}};var un=class{constructor(e,t){this.ctx=e;this.deps=t;this.disposed=false;this.admissionRepairInFlight=new Map;this.repairedAdmissionByNode=new Map;this.ctx.registerDisposer(()=>this.dispose());}dispose(){this.disposed=true,this.admissionRepairInFlight.clear(),this.repairedAdmissionByNode.clear();}assertActive(){if(this.disposed)throw new Error("Managed transport dialer is disposed")}async repairAdmissionForTransportGeneration(e,t){if(this.assertActive(),!e||!Number.isSafeInteger(t)||t<=0)return null;let n=this.deps.getRouteRepairTokenForNode?.(e)?.trim()??"",i=this.deps.getRouteRepairTokenPayloadForNode?.(e)?.trim()??"";if(!n||!i)return null;let o=`${n.length}:${n}:${i}`,s=this.repairedAdmissionByNode.get(e);if(s?.transportStableId===t&&s.credentialKey===o)return s.approvedScope;let a=this.admissionRepairInFlight.get(e);if(a?.transportStableId===t&&a.credentialKey===o)return a.promise;let c=this.performAdmissionRepair(e,t,n,i);this.admissionRepairInFlight.set(e,{transportStableId:t,credentialKey:o,promise:c});try{let d=await c,l=this.admissionRepairInFlight.get(e);return l?.promise!==c||l.transportStableId!==t||l.credentialKey!==o||!this.isCurrentRouteRepairCredential(e,n,i)?null:(this.repairedAdmissionByNode.set(e,{transportStableId:t,credentialKey:o,approvedScope:d}),d)}finally{this.admissionRepairInFlight.get(e)?.promise===c&&this.admissionRepairInFlight.delete(e);}}async performAdmissionRepair(e,t,n,i){let o=this.ctx.wasmClient;if(!o)return null;let s=(await this.deps.getLocalDeviceId().catch(()=>null))?.trim()||this.deps.getFallbackLocalDeviceId()?.trim()||null;this.assertActive();let a=4;for(let c=1;c<=a;c+=1){if(!this.isCurrentRouteRepairCredential(e,n,i))return null;try{let d=await this.presentSessionTokenToHost(o,e,n,i,s,2e4);return this.assertActive(),this.isCurrentRouteRepairCredential(e,n,i)?(c$1("[ManagedTransportDialer] repaired admission for physical generation",{remoteNodeId:e,transportStableId:t,attempt:c}),d):null}catch(d){if(this.isTerminalSessionTokenRejection(d))throw this.deps.forgetRouteRepairTokenForNode?.(e,n,i),this.repairedAdmissionByNode.delete(e),d;if(!this.isCurrentRouteRepairCredential(e,n,i))return null;if(!this.isTransientSessionTokenPresentationError(d)||c>=a)throw d;console.warn("[ManagedTransportDialer] current-generation admission repair lost transiently; retrying",{remoteNodeId:e,transportStableId:t,attempt:c,nextAttempt:c+1,error:d instanceof Error?d.message:String(d)}),await this.sleepSessionTokenRetry(c),this.assertActive();}}return null}isCurrentRouteRepairCredential(e,t,n){return this.deps.getRouteRepairTokenForNode?.(e)?.trim()===t&&this.deps.getRouteRepairTokenPayloadForNode?.(e)?.trim()===n}normalizeConnectResult(e,t,n,i){let o=e&&typeof e=="object"?e:{},s=typeof o.connectionId=="string"&&o.connectionId.trim()?o.connectionId.trim():t,a=typeof o.remoteNodeId=="string"&&o.remoteNodeId.trim()?o.remoteNodeId.trim():n,c=typeof o.deviceId=="string"&&o.deviceId.trim()?o.deviceId.trim():i??null,d=typeof o.deviceIdHint=="string"&&o.deviceIdHint.trim()?o.deviceIdHint.trim():c,l=typeof o.state=="string"&&o.state.trim()?o.state.trim():"connected",p=typeof o.approvedScope=="string"&&o.approvedScope.trim()?o.approvedScope.trim():typeof o.approved_scope=="string"&&o.approved_scope.trim()?o.approved_scope.trim():null;return {connectionId:s,deviceId:c,deviceIdHint:d,remoteNodeId:a,state:l,approvedScope:p}}async ensureWasmManagedTransport(e,t,n){this.assertActive();let i=this.ctx.wasmClient;if(!i||typeof i.connect_device!="function")throw new Error("[Client] WASM managed transport requires connect_device()");let o=n?.timeoutMs??2e4,s=e.trim(),{irohTicket:a,tokenSuffix:c}=ee(s),d=c===null?s:a,l=c!==null?se(a,c):null;if(c!==null&&!l)throw new Error("invalid compound ticket payload for endpoint ticket");let p=typeof l?.t=="string"&&l.t.trim()?l.t.trim():null;if(c!==null&&!p)throw new Error("invalid compound ticket payload for endpoint ticket");let u=await i.endpoint_id_from_ticket(a);this.assertActive(),p&&c&&this.deps.rememberRouteRepairTokenForNode(u,p,c);let h=this.deps.getDeterministicConnectionId(u),m=p?await this.deps.getLocalDeviceId().catch(()=>null):null,f=p&&(m?.trim()||this.deps.getFallbackLocalDeviceId()?.trim())||null;if(this.assertActive(),n?.skipIfConnected&&typeof i.is_connected=="function")try{let b=await i.is_connected(u);if(this.assertActive(),b){let P=c===null?this.deps.getApprovedScope(h):null;if(!(c!==null&&!P&&!n?.admissionAlreadyPresented))return {connectionId:h,deviceId:t??null,deviceIdHint:t??null,remoteNodeId:u,state:"connected",approvedScope:P}}}catch(b){if(this.disposed)throw b}let v=await O(i.connect_device(t??null,d),o,"wasmClient.connect_device");this.assertActive();let y=this.normalizeConnectResult(v,h,u,t??null),C=y.approvedScope??(c===null?this.deps.getApprovedScope(y.connectionId):null);if(c!==null&&!C&&!n?.admissionAlreadyPresented){let A=0,S=0,D=0;for(;!C;)try{if(C=await this.presentSessionTokenToHost(i,u,p,c,f,o),!C&&(D+=1,D>=4))break}catch(_){if(this.isAuthoritativeDeviceBindingPendingError(_)){if(S+=1,S>=6)throw _;console.warn("[ManagedTransportDialer] waiting for authoritative directory binding before retrying admission",{nodeId:u,remoteDeviceId:t??null,claimedLocalDeviceId:f,attempt:S,nextAttempt:S+1,error:_ instanceof Error?_.message:String(_)}),await this.sleepAuthoritativeBindingRetry(S),this.assertActive();continue}if(A+=1,!this.isTransientSessionTokenPresentationError(_)||A>=4)throw _;console.warn("[ManagedTransportDialer] session-token presentation lost transiently; redialing over iroh",{nodeId:u,remoteDeviceId:t??null,claimedLocalDeviceId:f,attempt:A,nextAttempt:A+1,error:_ instanceof Error?_.message:String(_)}),await this.sleepSessionTokenRetry(A),v=await O(i.connect_device(t??null,d),o,`wasmClient.connect_device(session-token-retry-${A})`),this.assertActive(),y=this.normalizeConnectResult(v,h,u,t??null),C=y.approvedScope??(c===null?this.deps.getApprovedScope(y.connectionId):null);}this.assertActive();}let I=C?{...y,approvedScope:C}:y;if(c!==null&&!I.approvedScope&&!n?.admissionAlreadyPresented)throw new Error("Failed to present session token: session token admission failed");return I}async presentSessionTokenToHost(e,t,n,i,o,s){try{if(typeof e.present_session_token=="function"){let a=await O(e.present_session_token(t,n,i,o),s,"wasmClient.present_session_token");return this.normalizeApprovedScope(a)}}catch(a){let c=a instanceof Error?a.message:String(a);throw new Error(`Failed to present session token: ${c}`)}return null}normalizeApprovedScope(e){return typeof e=="string"&&e.trim()?e.trim():null}isTransientSessionTokenPresentationError(e){if(this.isTerminalSessionTokenRejection(e))return false;let t=e instanceof Error?e.message:typeof e=="string"?e:String(e?.message??e??"");return /session-token-response|missing connection for session-token presentation|failed to open bi-stream|connection lost|stream finished early|0 bytes read|locallyclosed|connection closed|stream closed|reset/i.test(t)}isTerminalSessionTokenRejection(e){let t=e instanceof Error?e.message:typeof e=="string"?e:String(e?.message??e??"");return /\[session-token-response:rejected\]/i.test(t)}isAuthoritativeDeviceBindingPendingError(e){let t=e instanceof Error?e.message:typeof e=="string"?e:String(e?.message??e??"");return /authoritative-device-binding-pending/i.test(t)}isLocalIrohRuntimeNotInitializedError(e){let t=e instanceof Error?e.message:typeof e=="string"?e:String(e?.message??e??"");return /\bIroh node not initialized\b|\bNode not initialized\b/i.test(t)}sleepSessionTokenRetry(e$1){let t=Math.min(500,100*Math.max(1,e$1));return e(t)}sleepAuthoritativeBindingRetry(e$1){return e(h(e$1,200,1500))}};function wa(){if(!(typeof window>"u"))try{if(new URL(import.meta.url).pathname.includes("/node_modules/.vite/deps/"))return new URL("/node_modules/openrtc/dist/openrtc_bg.wasm",window.location.origin)}catch{}}function Aa(r){let t=(Array.isArray(r.urls)?r.urls:[r.urls]).filter(n=>typeof n=="string"&&!n.startsWith("stun:"));return t.length===0?null:{...r,urls:Array.isArray(r.urls)?t:t[0]}}function ka(r){let t=(Array.isArray(r.urls)?r.urls:[r.urls]).filter(n=>{let i=typeof n=="string"?n.trim().toLowerCase():"";return !i.startsWith("turn:")&&!i.startsWith("turns:")});return t.length===0?null:{...r,urls:Array.isArray(r.urls)?t:t[0]}}function Na(r){return r?.map(e=>ka(e)).filter(e=>e!==null)}function Hr(r){if(r)return r.map(e=>Aa(e)).filter(e=>e!==null)}async function qr(r,e$1,t){for(let n=0;n<e$1;n+=1){if(await r().catch(()=>false))return true;n<e$1-1&&await e(t);}return false}function ki(r){return !!r?.signaling?.nativeIpc&&r?.transport?.wasm===false&&r?.fallback?.wasm===false}var gn=class{constructor(e){this.host=e;this.wasmLoaded=false;this.initPromise=null;this.initPendingTimer=null;this.disposed=false;this.host.registerDisposer(()=>this.dispose());}dispose(){this.disposed=true,this.initPromise=null,this.clearInitPendingTimer();}clearInitPendingTimer(){this.initPendingTimer&&(clearInterval(this.initPendingTimer),this.initPendingTimer=null);}async bootstrapRuntime(e){let t=e.initializeClient??true;if(e.platform==="web")return await e.initializeWeb?.(),t&&await this.init(),{ready:true,mode:"web"};let n=e.quickPollAttempts??5,i=e.quickPollIntervalMs??300,o=e.retryPollAttempts??8,s=e.retryPollIntervalMs??300,a=e.nativeInitEventTimeoutMs??4e3;if(!e.isNativeReady)return console.warn("[Client][INIT] No isNativeReady callback provided for native platform; treating runtime as not ready"),{ready:false,mode:"native"};if(!await qr(e.isNativeReady,n,i)){await e.retryNativeInit?.();let[d,l]=await Promise.all([e.waitForNativeInitEvent?.(a)??Promise.resolve(false),qr(e.isNativeReady,o,s)]);if(!(d||l))return {ready:false,mode:"native"}}return t&&await this.init(),{ready:true,mode:"native"}}async init(){if(!this.disposed){if(this.initPromise)return this.initPromise;if(!(this.wasmLoaded&&this.host.wasmClient&&this.host.localNodeId)){if(this.usesNativeIpcOnly())throw this.nativeWasmInitForbiddenError("Client.init()");return this.initPromise=(async()=>{try{d$2("[Client][INIT] Loading WASM module...");let{initWasm:e,WasmClient:t,start:n}=await Ro();if(await e(wa()),this.disposed)return;n(),this.wasmLoaded=!0,d$2("[Client][INIT] WASM module loaded");let i=typeof this.host.options.apiKey=="string"?this.host.options.apiKey.trim():"",o=typeof this.host.options.spaceKey=="string"?this.host.options.spaceKey.trim():"",s=(this.host.options.discoveryMode===void 0||this.host.options.discoveryMode==="space")&&!!i&&!!o,a=c$4(this.host.options);if(s){let m=await b$1(i,o);if(this.disposed)return;a=`space::${m}`,d$2(`[Client][INIT] space mode: WASM rooms routed to spaces/${m.slice(0,8)}...`);}if(this.disposed)return;this.host.setEffectiveRoomBackendTag(a);let c=new t(i);if(typeof c.setRelay=="function"&&await c.setRelay(this.host.options.transports?.relay!==!1),this.disposed)return;this.host.setWasmClient(c),d$2("PlutoRTC WASM Core Initialized"),this.host.setSignalingWasmClient(c),this.host.installAppLifecycleListeners();let d=`iroh_secret_key_${f$3(this.host.options)}`,l=this.resolveIrohPersistenceMode(),p=await this.resolveIrohSecretKeyBytes(d,l);if(this.disposed||(this.host.setDeviceId(await this.host.getLocalDeviceId().catch(()=>null)),this.disposed))return;let u=Date.now();d$2(`[Client][INIT][IROH] start persistence=${l} hasSecretKey=${!!p} secretKeyLen=${p?.length||0} hasStoredDeviceId=${!!this.host.deviceId}`),this.clearInitPendingTimer(),this.initPendingTimer=setInterval(()=>{let m=Date.now()-u;console.warn(`[Client][INIT][IROH] pending elapsedMs=${m} hasWasmClient=${!!this.host.wasmClient}`);},5e3);let h="";try{let m=this.host.options.transports?.iroh&&typeof this.host.options.transports.iroh=="object"&&this.host.options.transports.iroh.testRelayUrl?.trim()||void 0;h=await O(m?c.initIrohWithTestRelay(p,m):c.init_iroh(p),2e4);}catch(m){let f=Date.now()-u;throw new Error(`[Client] init_iroh stalled or failed: ${m?.message||m}; elapsed_ms=${f}; persistence=${l}; has_secret_key=${!!p}`)}finally{this.clearInitPendingTimer();}if(this.disposed)return;if(d$2(`[Client][INIT][IROH] complete elapsedMs=${Date.now()-u} nodeId=${h}`),!h)throw new Error("[Client] init_iroh returned empty node id");if(this.host.setLocalNodeId(h),this.host.deviceId||this.host.setDeviceId(await this.host.getLocalDeviceId().catch(()=>null)),this.disposed||(this.host.setNode({initialized:!0,localNodeId:h}),l==="persistent"&&!this.host.options.secretKey&&(await this.persistCurrentIrohSecret(d,p,h),this.disposed))||(await this.configureWebRtcIceServers(),this.disposed))return;this.host.isWebRTCTransportEnabled()&&this.broadcastWebRtcReadyCapabilityInBackground();}catch(e){throw console.error("Failed to initialize PlutoRTC:",e),this.initPromise=null,e}})(),this.initPromise}}}broadcastWebRtcReadyCapabilityInBackground(){try{Promise.resolve(this.host.broadcastTransportCapabilityUpdate("webrtc-ready")).catch(e=>{this.disposed||c$1("[Client] Late WebRTC capability update failed",e);});}catch(e){if(this.disposed)return;c$1("[Client] Late WebRTC capability update failed",e);}}async recoverLocalIrohRuntime(e){if(this.disposed)return false;let t=this.host.wasmClient;if(!t||typeof t.init_iroh!="function")return false;try{let n=`iroh_secret_key_${f$3(this.host.options)}`,i=this.resolveIrohPersistenceMode(),o=await this.resolveIrohSecretKeyBytes(n,i);c$1("[Client][CONNECT] recovering local Iroh runtime",{reason:e,hadLocalNodeId:!!this.host.localNodeId,nodeInitialized:!!this.host.node?.initialized,persistenceMode:i,hasSecretKey:!!o});let s=this.host.options.transports?.iroh&&typeof this.host.options.transports.iroh=="object"&&this.host.options.transports.iroh.testRelayUrl?.trim()||void 0,a=await O(s?t.initIrohWithTestRelay(o,s):t.init_iroh(o),2e4);return this.disposed||typeof a!="string"||!a?!1:(this.host.setLocalNodeId(a),this.host.setNode({initialized:!0,localNodeId:a}),i==="persistent"&&!this.host.options.secretKey&&await this.persistCurrentIrohSecret(n,o,a),!0)}catch(n){return c$1("[Client][CONNECT] local Iroh runtime recovery failed",{reason:e,error:n instanceof Error?n.message:String(n)}),false}}usesNativeIpcOnly(){return ki(this.host.capabilities())}nativeWasmInitForbiddenError(e){let t=this.host.capabilities(),n=`[Client][NATIVE-GUARD] Refusing WASM runtime init during ${e}. This OpenRTC client is using the native IPC runtime with WASM fallback disabled; desktop/Tauri must initialize Iroh through the Rust backend only.`;return console.error(n,{capabilities:t}),new Error(n)}async resolveIrohSecretKeyBytes(e,t){if(this.host.options.secretKey){let o=this.host.options.secretKey.match(/.{1,2}/g);return o?new Uint8Array(o.map(s=>parseInt(s,16))):void 0}if(t!=="persistent")return;let i=(await this.loadPersistedIrohSecretHex(e))?.match(/.{1,2}/g);return i?new Uint8Array(i.map(o=>parseInt(o,16))):void 0}async persistCurrentIrohSecret(e,t,n){let i=t??(typeof this.host.wasmClient?.iroh_secret_key=="function"?await this.host.wasmClient.iroh_secret_key().catch(()=>{}):void 0);if(i&&i.length>0){let o=Array.from(i).map(s=>Number(s).toString(16).padStart(2,"0")).join("");await this.persistIrohSecretHex(e,o),d$2(`[Client][INIT][IROH] persisted secret key bytes=${i.length} nodeId=${n}`);}else console.warn(`[Client][INIT][IROH] unable to persist secret key for nodeId=${n}`);}resolveIrohPersistenceMode(){return this.host.options.endpointIdPersistence??this.host.options.nodeIdPersistence??(typeof this.host.options.transports?.iroh=="object"?this.host.options.transports.iroh.persistenceMode:void 0)??"ephemeral"}getTauriInvoke(){if(typeof window>"u")return null;let e=window.__TAURI_INTERNALS__;return !e||typeof e.invoke!="function"?null:e.invoke.bind(e)}async loadPersistedIrohSecretHex(e){let t=b$2()?this.getTauriInvoke():null;if(t){let n=await t("openrtc_load_iroh_secret",{namespaceKey:e}).catch(()=>null);if(typeof n=="string"&&n.trim().length>0)return n.trim()}if(typeof sessionStorage<"u"){let n=sessionStorage.getItem(e);if(n)return n}if(typeof localStorage<"u"){let n=localStorage.getItem(e);if(n)return typeof sessionStorage<"u"&&sessionStorage.setItem(e,n),localStorage.removeItem(e),n}return null}async persistIrohSecretHex(e,t){let n=b$2()?this.getTauriInvoke():null;if(n){await n("openrtc_save_iroh_secret",{namespaceKey:e,secretHex:t}),typeof localStorage<"u"&&localStorage.removeItem(e);return}typeof sessionStorage<"u"&&sessionStorage.setItem(e,t),typeof localStorage<"u"&&localStorage.removeItem(e);}async getTurnCredentialsForTransportConfig(){return typeof this.host.options.turnCredentialsProvider=="function"?await this.host.options.turnCredentialsProvider()??null:await this.host.getTurnCredentials()??null}async configureWebRtcIceServers(){let e=this.host.options.transports?.webrtc,t=e&&typeof e=="object"?e:void 0,n=this.host.options.transports?.relay!==false,i=n&&!!t&&(t.useTurn===true||t.privacyMode===true||this.host.options.strictMode===true);if(!n&&t&&(t.iceServers=Na(t.iceServers),t.useTurn=false,t.privacyMode=false,t.iceTransportPolicy="all"),i)try{let o=await this.getTurnCredentialsForTransportConfig();if(this.disposed)return;if(o&&o.iceServers){let s=Array.isArray(o.iceServers)?o.iceServers:[o.iceServers];t?.privacyMode||this.host.options.strictMode?(s=Hr(s)??[],d$2(`[Client] Strict / Privacy Mode: Filtered STUN servers. Remaining=${s.length}`)):d$2(`[Client] Automatically fetched ${s.length} TURN servers.`),this.host.options.transports||(this.host.options.transports={}),this.host.options.transports.webrtc||(this.host.options.transports.webrtc={});let a=this.host.options.transports.webrtc||i$1;a.iceServers||(a.iceServers=[]),(this.host.options.strictMode||a.privacyMode)&&(a.iceServers=Hr(a.iceServers)??[]),a.iceServers.push(...s);}}catch(o){console.warn("[Client] Failed to auto-fetch TURN credentials:",o);}if(!this.host.options.strictMode&&!t?.privacyMode){if(this.disposed)return;let o=this.host.options.transports?.webrtc;o&&o.useDefaultIceServers!==false&&(!o.iceServers||Array.isArray(o.iceServers)&&o.iceServers.length===0)&&(d$2("[Client] No ICE servers provided. Using default public STUN servers."),o.iceServers=[...h$1]);}}};var hn=class{constructor(e,t){this.ctx=e;this.deps=t;this.disposed=false;this.ctx.registerDisposer(()=>this.dispose());}dispose(){this.disposed=true;}assertActive(){if(this.disposed)throw new Error("Runtime connection service is disposed")}async connectRaw(e,t=2e4){this.assertActive(),await this.deps.ensureWasmRuntimeForP2P(),this.assertActive();let n=await this.deps.ensureWasmManagedTransport(e,null,{timeoutMs:t});return this.assertActive(),{connectionId:n.connectionId,localNodeId:this.ctx.localNodeId??"",remoteNodeId:n.remoteNodeId??n.deviceId??""}}async startAutoConnect(e){if(this.disposed||(await this.deps.ensureSignalingReadyForDiscovery("watch"),this.disposed))return;let t=this.deps.getCurrentUserId();if(!t)throw new Error("startAutoConnect requires an authenticated user");let n=e||await this.deps.getLocalDeviceId()||this.deps.getFallbackDeviceId();if(!this.disposed){if(!n)throw new Error("startAutoConnect requires a local device identity");this.deps.startAutoConnect(t,n);}}async isConnected(e){if(this.disposed||(await this.deps.ensureWasmRuntimeForP2P(),this.disposed)||!e||!e.trim())return false;let t=this.ctx.wasmClient;if(t&&typeof t.is_connected=="function"){let i=await t.is_connected(e);if(this.disposed)return false;if(i)return true}let n=await this.deps.isConnected(e);return this.disposed?false:!!n}async disconnectNode(e){if(this.disposed||!e||!e.trim())return;let t=Array.from(this.ctx.registry.values()).filter(n=>n.deviceId===e);await Promise.allSettled(t.map(n=>this.disconnectConnectionBestEffort(n))),!this.disposed&&await this.deps.disconnectNodeTransport(e);}disconnectNodeBestEffort(e){try{this.disconnectNode(e).catch(()=>{});}catch{}}disconnectConnectionBestEffort(e){try{return Promise.resolve(e.disconnect()).catch(()=>{})}catch{return Promise.resolve()}}};var mn=class{constructor(e,t){this.ctx=e;this.deps=t;this.disposed=false;this.ctx.registerDisposer(()=>this.dispose());}dispose(){this.disposed=true;}assertActive(){if(this.disposed)throw new Error("Runtime identity service is disposed")}async getTicket(){this.assertActive(),await this.deps.ensureWasmRuntimeForP2P(),this.assertActive();let e=await ae(()=>this.ctx.wasmClient.endpoint_ticket(),{isActive:()=>!this.disposed});return this.assertActive(),e}async getNodeId(){return this.assertActive(),await this.deps.ensureWasmRuntimeForP2P(),this.assertActive(),this.ctx.localNodeId??""}async getNodeIdFromTicket(e){if(this.disposed)return null;let t=e.trim();if(!t)return null;let{irohTicket:n}=ee(t),i=this.ctx.wasmClient;if(!i||typeof i.endpoint_id_from_ticket!="function")return null;try{let o=await i.endpoint_id_from_ticket(n);return this.disposed?null:o}catch{return null}}};var fn=class{constructor(e,t){this.ctx=e;this.deps=t;this.loggedNativeDiscoveryWasmSkip=false;this.disposed=false;this.ctx.registerDisposer(()=>this.dispose());}dispose(){this.disposed=true;}assertActive(){if(this.disposed)throw new Error("Runtime readiness service is disposed")}async ensureWasmRuntimeForP2P(){if(this.assertActive(),!(this.ctx.wasmClient&&this.ctx.localNodeId)&&(await this.deps.init(),this.assertActive(),!this.ctx.wasmClient||!this.ctx.localNodeId))throw new Error("Node not initialized")}async ensureSignalingReadyForDiscovery(e){if(this.disposed||this.deps.usesTicketOnlySignalingMode())return;let t=this.deps.usesNativeIpcOnly();if(!this.deps.getWasmLoaded()&&t)this.loggedNativeDiscoveryWasmSkip||(this.loggedNativeDiscoveryWasmSkip=true,c$1(`[Client][NATIVE-GUARD] Discovery ${e} is using native IPC readiness; skipped WASM init.`));else if(!this.deps.getWasmLoaded()&&!(this.ctx.wasmClient&&this.ctx.localNodeId)&&(await this.deps.init(),this.disposed))return;try{await this.deps.ensureAuthenticated("discovery");}catch(n){console.warn(`[Client][AUTH] ensureAuthenticated failed for ${e}:`,n);}this.disposed;}};var Ma={scheduled:0,coalesced:0,ran:0,orphanTsConnection:0,orphanRustRecord:0,orphanTsConnectionHealed:0},yn=class{constructor(e){this.deps=e;}usesTicketOnlySignalingMode(){return (this.deps.getOptions()?.signalingMode??"hosted")==="ticket-only"}getRoomBackendTag(){return this.deps.getEffectiveRoomBackendTag()}requiresManagedTransportTrust(e){return !this.usesTicketOnlySignalingMode()&&e!=="space"&&!!this.deps.getSignalingCurrentUser()?.id}getSignalingTelemetry(){return {transport:"runtime-bridge",wasmLoaded:this.deps.getWasmLoaded(),peerReconciliation:this.reconciliationStats()}}reconciliationStats(){return this.deps.reconciliationStats()??Ma}getProtocolCapabilities(){let e=b$4.getProtocolCapabilities(),t=this.deps.capabilities(),n=this.deps.getOptions().transports,i=n?.iroh!==false,o=!!n?.webrtc,s=n?.ble===true||typeof n?.ble=="object"&&n.ble.enabled!==false,a=typeof n?.moq=="object"&&typeof n.moq.relayUrl=="string"&&n.moq.relayUrl.trim().length>0;for(let d of Object.values(e)){if(d.routeImplementation==="path-label"){d.configured=void 0;continue}d.configured=d.baseProtocol==="iroh"?i:d.baseProtocol==="webrtc"?o:a;}e.ble.configured=s;let c=(d,l,p)=>{e[d].configured=l,e[d].available=l&&p,l?p||(e[d].reason=`The running host did not report '${d}' as available.`):e[d].reason=`Protocol '${d}' is not enabled in ClientOptions.transports.`;};return c("iroh",i,t?.transport.irohQuic===true||t?.adapter==="browser-wasm"),c("webrtc",o,t?.transport.webRtcUpgrade===true||t?.transport.nativeWebRtc===true),c("moq",a,t?.transport.moq===true),e.ble.available=s&&t?.transport.ble===true,s?t?.transport.ble!==true&&(e.ble.reason="The running host did not report 'ble' as compiled and enabled."):e.ble.reason="Protocol 'ble' is not enabled in ClientOptions.transports.",e}async getRuntimeStatus(){let e="unknown";return typeof window<"u"&&(e=window.__TAURI__?"tauri":"browser"),{runtime:e,wasmLoaded:this.deps.getWasmLoaded(),localNodeId:this.deps.getLocalNodeId()||void 0,userId:this.deps.getSignalingCurrentUser()?.id??void 0}}};function jr(r){let{host:e}=r;return new gn({get options(){return e.getOptions()},get wasmClient(){return e.getWasmClient()},get node(){return e.getNode()},get localNodeId(){return e.getLocalNodeId()},get deviceId(){return e.getDeviceId()},setWasmClient:t=>e.setWasmClient(t),setSignalingWasmClient:t=>e.setSignalingWasmClient(t),setNode:t=>e.setNode(t),setLocalNodeId:t=>e.setLocalNodeId(t),setDeviceId:t=>e.setDeviceId(t),setEffectiveRoomBackendTag:t=>e.setEffectiveRoomBackendTag(t),usesTicketOnlySignalingMode:()=>r.getStatus().usesTicketOnlySignalingMode(),ensureAuthenticated:t=>e.ensureAuthenticated(t),syncAuthTokenToWasm:(t,n)=>e.syncAuthTokenToWasm(t,n),installAuthTokenSync:()=>e.installAuthTokenSync(),installAppLifecycleListeners:()=>r.getAppLifecycle().installListeners(),initMoQ:()=>e.initMoQ(),isWebRTCTransportEnabled:()=>e.isWebRTCTransportEnabled(),getLocalDeviceId:()=>e.getLocalDeviceId(),getTurnCredentials:()=>e.getTurnCredentials(),capabilities:()=>e.capabilities(),broadcastTransportCapabilityUpdate:t=>e.broadcastTransportCapabilityUpdate(t),registerDisposer:t=>e.registerDisposer(t)})}function Gr(r){let{host:e}=r;return new hn(e.getContext(),{ensureWasmRuntimeForP2P:()=>r.getReadiness().ensureWasmRuntimeForP2P(),ensureSignalingReadyForDiscovery:t=>r.getReadiness().ensureSignalingReadyForDiscovery(t),ensureWasmManagedTransport:(t,n,i)=>r.getManagedDialer().ensureWasmManagedTransport(t,n,i),getCurrentUserId:()=>e.getCurrentUserId(),getLocalDeviceId:()=>e.getLocalDeviceId(),getFallbackDeviceId:()=>e.getDeviceId(),startAutoConnect:(t,n)=>e.startAutoConnect(t,n),isConnected:t=>e.isConnected(t),disconnectNodeTransport:t=>e.disconnectNodeTransport(t)})}function Kr(r){return new un(r.getContext(),{getDeterministicConnectionId:e=>r.getDeterministicConnectionId(e),getApprovedScope:e=>r.getApprovedScope(e),getLocalDeviceId:()=>r.getLocalDeviceId(),getFallbackLocalDeviceId:()=>r.getDeviceId()??r.getOptions().localDeviceId??null,rememberRouteRepairTokenForNode:(e,t,n)=>r.rememberRouteRepairTokenForNode(e,t,n),forgetRouteRepairTokenForNode:(e,t,n)=>r.forgetRouteRepairTokenForNode?.(e,t,n),getRouteRepairTokenForNode:e=>r.getRouteRepairTokenForNode?.(e),getRouteRepairTokenPayloadForNode:e=>r.getRouteRepairTokenPayloadForNode?.(e)})}function zr(r){return new mn(r.host.getContext(),{ensureWasmRuntimeForP2P:()=>r.getReadiness().ensureWasmRuntimeForP2P()})}function Qr(r){let{host:e}=r;return new fn(e.getContext(),{init:()=>r.getBootstrap().init(),usesTicketOnlySignalingMode:()=>r.getStatus().usesTicketOnlySignalingMode(),usesNativeIpcOnly:()=>ki(e.capabilities()),getWasmLoaded:()=>r.getBootstrapWasmLoaded(),ensureAuthenticated:t=>e.ensureAuthenticated(t),syncAuthTokenToWasm:t=>e.syncAuthTokenToWasm(t)})}function Vr(r){let{host:e}=r;return new yn({getEffectiveRoomBackendTag:()=>e.getEffectiveRoomBackendTag(),getLocalNodeId:()=>e.getLocalNodeId(),getOptions:()=>e.getOptions(),reconciliationStats:()=>e.reconciliationStats(),capabilities:()=>e.capabilities(),getSignalingCurrentUser:()=>({id:e.getCurrentUserId()}),getWasmLoaded:()=>r.getBootstrapWasmLoaded()})}function $r(r){return new pn(r.getContext(),{setCoordinationHostAvailability:e=>r.setCoordinationHostAvailability(e)})}function Yr(r){return new Ni({getContext:()=>r.getClientContext(),getOptions:()=>r.options,getWasmClient:()=>r.wasmClient,setWasmClient:e=>{r.wasmClient=e;},getNode:()=>r.node,setNode:e=>{r.node=e;},getLocalNodeId:()=>r.localNodeId,setLocalNodeId:e=>{r.localNodeId=e;},getDeviceId:()=>r.deviceId,setDeviceId:e=>{r.deviceId=e;},setEffectiveRoomBackendTag:e=>{r.setEffectiveRoomBackendTag(e);},getEffectiveRoomBackendTag:()=>r.getEffectiveRoomBackendTag(),reconciliationStats:()=>r.getExistingPeerReconciliationStats(),getCurrentUserId:()=>r.signalingBackendController.getCurrentUser()?.id??null,capabilities:()=>r.signalingBackendController.capabilities(),getLocalDeviceId:()=>r.signalingBackendController.getLocalDeviceId(),getTurnCredentials:()=>r.signalingBackendController.getTurnCredentials(),setSignalingWasmClient:e=>r.signalingBackendController.setWasmClient(e),startAutoConnect:(e,t)=>r.signalingBackendController.startAutoConnect(e,t),isConnected:e=>r.signalingBackendController.isConnected(e),disconnectNodeTransport:e=>r.transportHealth.disconnectNodeTransport(e),getDeterministicConnectionId:e=>r.peerIdentity.getDeterministicConnectionId(e),getApprovedScope:e=>r.sessionTokens.getApprovedScope(e),rememberRouteRepairTokenForNode:(e,t,n)=>r.sessionTokens.rememberRouteRepairTokenForNode(e,t,n),forgetRouteRepairTokenForNode:(e,t,n)=>r.sessionTokens.forgetRouteRepairTokenForNode(e,t,n),getRouteRepairTokenForNode:e=>r.sessionTokens.getRouteRepairTokenForNode(e),getRouteRepairTokenPayloadForNode:e=>r.sessionTokens.getRouteRepairTokenPayloadForNode(e),ensureAuthenticated:e=>r.auth.ensureAuthenticated(e),syncAuthTokenToWasm:(e,t)=>r.auth.syncAuthTokenToWasm(e,t),installAuthTokenSync:()=>r.auth.installAuthTokenSync(),initMoQ:()=>r.moqServices.init(),isWebRTCTransportEnabled:()=>d$1(r.options),broadcastTransportCapabilityUpdate:e=>r.transportHandshake.broadcastTransportCapabilityUpdate(e),setCoordinationHostAvailability:e=>r.signaling.setCoordinationHostAvailability?.(e),registerDisposer:e=>r.lifecycleScope.register(e)})}var Ni=class{constructor(e){this.host=e;}get factoryHost(){return {host:this.host,getBootstrap:()=>this.bootstrap,getBootstrapWasmLoaded:()=>this._bootstrap?.wasmLoaded??false,getManagedDialer:()=>this.managedDialer,getReadiness:()=>this.readiness,getStatus:()=>this.status,getAppLifecycle:()=>this.appLifecycle}}get bootstrap(){return this._bootstrap??(this._bootstrap=jr(this.factoryHost))}get connections(){return this._connections??(this._connections=Gr(this.factoryHost))}get managedDialer(){return this._managedDialer??(this._managedDialer=Kr(this.host))}get identity(){return this._identity??(this._identity=zr(this.factoryHost))}get readiness(){return this._readiness??(this._readiness=Qr(this.factoryHost))}get status(){return this._status??(this._status=Vr(this.factoryHost))}get appLifecycle(){return this._appLifecycle??(this._appLifecycle=$r(this.host))}};var vn=class{constructor(e,t){this.ctx=e;this.deps=t;this.connectionKeyAgreementById=new Map;this.connectionKeyAgreementRemotePublicById=new Map;this.negotiatedByConnectionId=new Map;this.negotiatedByPeerId=new Map;this.negotiatedFingerprintByCrypto=new WeakMap;this.waiters=[];this.disposed=false;this.ctx.registerDisposer(()=>this.dispose());}getApplicationCrypto(e){return e?this.deps.getConfiguredApplicationCrypto()??this.negotiatedByConnectionId.get(e.id):this.deps.getConfiguredApplicationCrypto()}getNegotiatedForPeer(e){let t=typeof e=="string"?e.trim():"";if(!t)return;let n=Array.from(this.ctx.registry.values()).reverse().find(d=>!d.isClosed&&(d.id===t||d.remoteNodeId===t));if(n)return this.negotiatedByConnectionId.get(n.id);let i=this.deps.getKnownDeviceNodeId(t),o=[this.deps.getPeerState(t),i?this.deps.getPeerState(i):void 0].filter(d=>!!d);for(let d of o){let l=d.connectionId?.trim();if(l)return this.negotiatedByConnectionId.get(l);for(let p of [...d.connectionIds??[]].reverse()){let u=p?.trim();if(!u)continue;let h=this.negotiatedByConnectionId.get(u);if(h)return h}}let a=Array.from(this.ctx.registry.values()).filter(d=>{let l=this.deps.getKnownDeviceIdForNode(d.remoteNodeId);return d.id===t||d.remoteNodeId===t||d.deviceId===t||i&&d.remoteNodeId===i||l===t}).filter(d=>!d.isClosed).reverse(),c=a.find(d=>d.id===t||d.remoteNodeId===t)??a.find(d=>!!i&&d.remoteNodeId===i)??a[0];return c?this.negotiatedByConnectionId.get(c.id):this.negotiatedByPeerId.get(t)}resolveForPeer(e,t){let n=this.deps.getConfiguredApplicationCrypto();if(n)return n;if(t)return this.negotiatedByConnectionId.get(t.id);if(e)return this.getNegotiatedForPeer(e)}waitForPeer(e,t=1e4){let n=this.resolveForPeer(e);return n||!e||t<=0||this.disposed?Promise.resolve(n):new Promise(i=>{let o={peerId:e,resolve:i,timer:setTimeout(()=>{this.waiters=this.waiters.filter(s=>s!==o),i(void 0);},t)};this.waiters.push(o);})}dispose(){if(this.disposed)return;this.disposed=true;let e=this.waiters.splice(0);for(let t of e)clearTimeout(t.timer),t.resolve(void 0);this.connectionKeyAgreementById.clear(),this.connectionKeyAgreementRemotePublicById.clear(),this.negotiatedByConnectionId.clear(),this.negotiatedByPeerId.clear();}clearConnection(e){let t=this.negotiatedByConnectionId.get(e),n=this.wasmClient;try{n?.clearConnectionApplicationCryptoKey?.(e);}catch(i){console.warn("[Client][KEY-AGREEMENT] Failed to retire native application crypto",{connectionId:e,error:i});}if(this.connectionKeyAgreementById.delete(e),this.connectionKeyAgreementRemotePublicById.delete(e),this.negotiatedByConnectionId.delete(e),!(!t||Array.from(this.negotiatedByConnectionId.values()).includes(t)))for(let[i,o]of this.negotiatedByPeerId)o===t&&this.negotiatedByPeerId.delete(i);}notifyWaiters(){if(this.waiters.length===0)return;let e=[];for(let t of this.waiters){let n=this.resolveForPeer(t.peerId);if(!n){e.push(t);continue}clearTimeout(t.timer),t.resolve(n);}this.waiters=e;}resolveStreamTools(e,t){let n=this.resolveForPeer(e,t);return n&&c$1("[Client][KEY-AGREEMENT] Resolved application stream crypto",{peerId:e??null,connectionId:t?.id??null,keyFingerprint:this.negotiatedFingerprintByCrypto.get(n)??"configured"}),n?z$1(n):void 0}shouldNegotiateKeyAgreement(){return !this.deps.getConfiguredApplicationCrypto()}async ensureConnectionKeyAgreementState(e){let t=this.connectionKeyAgreementById.get(e.id);if(t)return t;let n=f$2();return this.connectionKeyAgreementById.set(e.id,n),n}async handleKeyAgreement(e,t){if(!this.shouldNegotiateKeyAgreement())return {remotePublicChanged:false,cryptoReady:false,replyAction:null,replyClaimId:null};await this.ensureConnectionKeyAgreementState(e);let n=j$2(t.applicationKeyAgreement),i=t.capabilities?.applicationKeyAgreement===true||!!n;if(!n||!i||!this.ctx.localNodeId){if((typeof e.getControlFrameMode=="function"?e.getControlFrameMode():"typed")==="native-main"&&!i&&!n)return {remotePublicChanged:false,cryptoReady:false,replyAction:null,replyClaimId:null};throw new Error("Peer does not support mandatory application key agreement")}let o=this.connectionKeyAgreementById.get(e.id);if(!o)return {remotePublicChanged:false,cryptoReady:false,replyAction:null,replyClaimId:null};let s=t.applicationKeyAgreement?.publicKey?.trim()??"",a=h$3(n),c=this.connectionKeyAgreementRemotePublicById.get(e.id)??null,d=!!s&&c!==s;e.markKeyAgreement();let l=this.negotiatedByConnectionId.get(e.id);if(l&&s&&c===s){let v=g$3(o.secretKey,n,this.ctx.localNodeId,e.remoteNodeId);await this.syncKeyToNative(e.id,v),e.setApplicationCrypto(l);let y=this.ctx.registry.get(e.id);y&&y!==e&&!y.isClosed&&y.setApplicationCrypto(l),this.deps.notifyApplicationRouteReady(e,`key-agreement:${t.action??"hello"}:unchanged`),c$1("[Client][KEY-AGREEMENT] Reused unchanged application crypto",{connectionId:e.id,remoteNodeId:e.remoteNodeId,action:t.action??"hello"});let C=this.claimReplyAction(e.id,t.action,a);return {remotePublicChanged:false,cryptoReady:true,replyAction:C?.action??null,replyClaimId:C?.claimId??null}}let p=g$3(o.secretKey,n,this.ctx.localNodeId,e.remoteNodeId);s&&this.connectionKeyAgreementRemotePublicById.set(e.id,s);let u=y$1(p,{requireEncrypted:true,replayProtection:true}),h=h$3(p);this.negotiatedFingerprintByCrypto.set(u,h),this.index(e,u),e.setApplicationCrypto(u);let m=this.ctx.registry.get(e.id);m&&m!==e&&!m.isClosed&&typeof m.setApplicationCrypto=="function"&&m.setApplicationCrypto(u),await this.syncKeyToNative(e.id,p),this.notifyWaiters(),this.deps.notifyApplicationRouteReady(e,`key-agreement:${t.action??"hello"}`),c$1("[Client][KEY-AGREEMENT] Application crypto ready",{connectionId:e.id,remoteNodeId:e.remoteNodeId,action:t.action??"hello",remoteSupports:i,remotePublicChanged:d,keyFingerprint:h,localPublicFingerprint:h$3(o.publicKey),remotePublicFingerprint:h$3(n)});let f=this.claimReplyAction(e.id,t.action,a);return {remotePublicChanged:d,cryptoReady:true,replyAction:f?.action??null,replyClaimId:f?.claimId??null}}async resyncConnectionKeyToNative(e){let t=this.negotiatedByConnectionId.get(e.id),n=this.connectionKeyAgreementById.get(e.id),i=this.connectionKeyAgreementRemotePublicById.get(e.id),o=i?j$2({algorithm:e$4,publicKey:i}):null;if(!t||!n||!o||!this.ctx.localNodeId)return false;let s=g$3(n.secretKey,o,this.ctx.localNodeId,e.remoteNodeId);return await this.syncKeyToNative(e.id,s),e.setApplicationCrypto(t),true}claimReplyAction(e,t,n){return !n||t==="ack"?null:{action:t==="response"?"ack":"response",claimId:n}}releaseReplyClaim(e,t,n){}index(e,t){this.negotiatedByConnectionId.set(e.id,t);let n=new Set([e.id,e.remoteNodeId,e.deviceId,this.deps.getKnownDeviceIdForNode(e.remoteNodeId)??""]);for(let i of n){let o=typeof i=="string"?i.trim():"";o&&this.negotiatedByPeerId.set(o,t);}}getForConnectionOrPeer(e,t){return this.negotiatedByConnectionId.get(e)??this.negotiatedByPeerId.get(t)}indexPeer(e,t){let n=typeof e=="string"?e.trim():"";n&&this.negotiatedByPeerId.set(n,t);}reindexDevice(e){let t=typeof e.nodeId=="string"?e.nodeId.trim():"";if(!t||!e.deviceId)return;let n=this.getNegotiatedForPeer(t);n&&this.negotiatedByPeerId.set(e.deviceId,n);}async syncRequiredToNative(e){let t=this.wasmClient;!t||typeof t.setConnectionApplicationCryptoRequired!="function"||await t.setConnectionApplicationCryptoRequired(e);}async syncKeyToNative(e,t){let n=this.wasmClient;if(!(!n||typeof n.setConnectionApplicationCryptoKey!="function")){await this.syncRequiredToNative(e);try{await n.setConnectionApplicationCryptoKey(e,Array.from(t));}catch(i){let o=this.ctx.registry.get(e);throw o&&typeof o.requireApplicationCrypto=="function"&&o.requireApplicationCrypto(),console.error("[Client][KEY-AGREEMENT] Failed to sync derived key to native runtime",{connectionId:e,error:i}),i}}}markRequired(e){typeof e.requireApplicationCrypto=="function"&&e.requireApplicationCrypto(),this.syncRequiredToNative(e.id).catch(t=>{console.warn("[Client][KEY-AGREEMENT] Failed to sync required-crypto flag to native runtime",{connectionId:e.id,error:t});});}hydrateAdoptedConnection(e,t){if(e.isClosed||this.resolveForPeer(e.remoteNodeId,e))return false;let n=this.getNegotiatedForPeer(e.remoteNodeId);return n?(this.negotiatedByConnectionId.set(e.id,n),e.setApplicationCrypto(n),this.notifyWaiters(),this.deps.notifyApplicationRouteReady(e,t),c$1("[Client][HANDSHAKE] hydrated adopted connection application crypto from peer index",{connectionId:e.id,remoteNodeId:e.remoteNodeId,reason:t}),true):false}openWebRTCExplicitTransferPayload(e,t){let n=this.resolveForPeer(t?.remoteNodeId,t);return n?z$1(n).openFrame(e):e}protectDirectMoQPayload(e,t,n){return this.resolveForPeer(t,n)?.protectPayload(3,e)??e}openDirectMoQPayload(e,t,n){let i=this.resolveForPeer(t,n);if(!i||!x$1(e))return {payload:null,encrypted:false,proofEligible:false};let o=i.openPayload(3,e);return o?{payload:o,encrypted:true,proofEligible:true}:{payload:i.openPayload(0,e),encrypted:true,proofEligible:false}}get wasmClient(){return this.ctx.wasmClient}};var Ea=15e3,_a=2,xa=150,Cn=class{constructor(e,t){this.ctx=e;this.deps=t;this.pendingTrustApprovals=new Map;this.pendingTrustApprovalScopes=new Map;this.rejectionCooldowns=new Map;this.approvedNodes=new Set;this.approvedConnectionIds=new Set;this.approvedScopesByConnectionId=new Map;this.routeRepairTokenByNodeId=new Map;this.routeRepairTokenPayloadByNodeId=new Map;this.disposed=false;this.ctx.registerDisposer(()=>this.dispose());}dispose(){if(this.disposed)return;this.disposed=true,this.deps.retirePendingReciprocalAdmissions("session-token-service-dispose"),this.deps.clearManagedPresenceTicket(),this.clearInMemoryState();let e=this.wasmClient;e&&typeof e.clear_session_tokens=="function"&&e.clear_session_tokens();}async getTicketWithToken(e,t=0){if(this.disposed)throw new Error("Session token service is disposed");await this.deps.ensureWasmRuntimeForP2P();let n=this.wasmClient;if(n&&typeof n.endpoint_ticket_with_token=="function"){let o=n.endpoint_ticket_with_token.bind(n);return await ae(()=>o(e,t),{isActive:()=>!this.disposed})}if(e.trim()==="user-device")throw new Error("Managed user-device admission requires Rust/WASM endpoint_ticket_with_token support.");let i=await this.deps.getTicket();return this.buildCompoundTicketWithToken(i,e,t)}buildCompoundTicketWithToken(e,t,n=0){if(this.disposed)throw new Error("Session token service is disposed");let i=$o(),o=t.trim()==="user-device"?void 0:Date.now()+9e5,s=this.wasmClient;return s&&typeof s.register_session_token=="function"&&(typeof o=="number"&&typeof s.register_token_until=="function"?s.register_token_until(i,t,n,o):s.register_session_token(i,t,n)),bt(e,i,t,n,o)}registerSessionToken(e,t,n,i){if(this.disposed)return;let o=this.wasmClient;if(o&&typeof o.register_session_token=="function")if(typeof i=="number"){if(typeof o.register_token_until!="function")throw new Error("This OpenRTC WASM runtime cannot enforce admission-token expiry.");o.register_token_until(e,t,n,i);}else o.register_session_token(e,t,n);}revokeSessionToken(e){if(this.disposed)return;i("Client.revokeSessionToken",{tokenLength:e.length}),this.deps.retirePendingReciprocalAdmissions("session-token-revoke");let t=this.wasmClient;if(t&&typeof t.revoke_session_token=="function"){let n=t.revoke_session_token(e),i=Array.isArray(n)?n.filter(o=>typeof o=="string"&&!!o.trim()):[];for(let o of i){let s=this.ctx.registry.get(o);this.clearConnectionApproval(o),s&&(this.approvedNodes.delete(s.remoteNodeId),this.disconnectConnectionBestEffort(s));}}}async revokeTokensByScope(e){if(this.disposed)return [];i("Client.revokeTokensByScope",{grantScope:e}),this.deps.retirePendingReciprocalAdmissions(`session-token-scope-revoke:${e}`);let t=e.trim(),n=Array.from(this.ctx.registry.values()).filter(u=>this.deps.getPeerScopes(u.id).some(h=>h===t)),i$1=Array.from(new Set([...Array.from(this.approvedScopesByConnectionId.entries()).filter(([,u])=>u===t).map(([u])=>u),...n.map(u=>u.id)])),o=new Map(Array.from(this.ctx.registry.values()).map(u=>[u.id,u])),s=Array.from(new Set([...n,...i$1.map(u=>o.get(u)).filter(u=>!!u)]));if(await this.deps.ensureWasmRuntimeForP2P(),this.disposed)return [];let a=this.wasmClient,c=a&&typeof a.revoke_tokens_by_scope=="function"?await a.revoke_tokens_by_scope(e):[],d=Array.from(new Set([...Array.isArray(c)?c:[],...i$1]));if(d.length===0)return [];let l=Array.from(new Set([...s,...d.map(u=>o.get(u)??this.ctx.registry.get(u)).filter(u=>!!u)])),p=new Set(l.map(u=>u.remoteNodeId?.trim()).filter(u=>!!u));for(let u of d)this.clearConnectionApproval(u);for(let u of p)this.approvedNodes.delete(u),this.routeRepairTokenByNodeId.delete(u),this.routeRepairTokenPayloadByNodeId.delete(u);return await Promise.allSettled(l.map(u=>this.disconnectConnectionBestEffort(u))),d}async clearSessionTokens(){if(i("Client.clearSessionTokens",{}),this.deps.retirePendingReciprocalAdmissions("session-token-clear"),this.disposed){this.clearInMemoryState();return}if(await this.deps.ensureWasmRuntimeForP2P(),this.deps.clearManagedPresenceTicket(),this.disposed){this.clearInMemoryState();return}this.clearInMemoryState();let e=this.wasmClient;e&&typeof e.clear_session_tokens=="function"&&e.clear_session_tokens();}async validateIncomingSessionToken(e,t,n){if(this.disposed)return {ok:false,reason:"session-token-service-disposed"};let i=this.wasmClient;if(!i||typeof i.validate_session_token!="function")return e.trim()?{ok:false,reason:"session-token-validator-unavailable"}:{ok:true};try{let o="";return t&&typeof i.validate_connection_token=="function"?o=n===void 0?await i.validate_connection_token(e,t):await i.validate_connection_token(e,t,n):o=i.validate_session_token(e),{ok:!0,scope:o||void 0}}catch(o){return {ok:false,reason:o?.message||`${o}`}}}async validateIncomingSessionTokenWithRetry(e$1,t,n){if(this.disposed)return {ok:false,reason:"session-token-service-disposed"};let i=await this.validateIncomingSessionToken(e$1,t,n?.tokenPayload);if(i.ok||!e$1||!(i.reason??"").toLowerCase().includes("unknown session token"))return i;for(let s=1;s<=_a;s+=1){if(await e(xa*s),this.disposed)return {ok:false,reason:"session-token-service-disposed"};if(i=await this.validateIncomingSessionToken(e$1,t,n?.tokenPayload),i.ok)return c$1("[Client][SESSION-TOKEN] validation recovered after retry",{source:n?.source??"unknown",remoteNodeId:n?.remoteNodeId??null,connectionId:t??null,attempt:s}),i}return i}rememberPendingTrustApproval(e,t){if(this.disposed||!e)return;this.pendingTrustApprovals.set(e,Date.now());let n=typeof t=="string"?t.trim():"";n?this.pendingTrustApprovalScopes.set(e,n):this.pendingTrustApprovalScopes.delete(e);}consumePendingTrustApproval(e){if(this.disposed)return {approved:false};let t=this.pendingTrustApprovals.get(e);if(!t)return {approved:false};let n=this.pendingTrustApprovalScopes.get(e)??null;return this.pendingTrustApprovals.delete(e),this.pendingTrustApprovalScopes.delete(e),Date.now()-t>Ea?{approved:false}:{approved:true,scope:n}}applyTrustApproval(e,t,n="session-token"){if(this.disposed||!e||e.isClosed)return;let o=(typeof t=="string"?t.trim():"")||this.approvedScopesByConnectionId.get(e.id)||"";this.rememberPendingTrustApproval(e.id,o),this.rejectionCooldowns.delete(e.remoteNodeId),this.deps.clearTrustFailureCooldown(e.remoteNodeId),this.approvedNodes.add(e.remoteNodeId),this.approvedConnectionIds.add(e.id),o&&this.approvedScopesByConnectionId.set(e.id,o);let s=this.deps.sessionTokenScopeAllowsDeviceBinding(o),a=s?this.deps.getKnownDeviceIdForNode(e.remoteNodeId):null,c=this.deps.initializeConnectionTrust(e,a);c.required=false,c.verified=true,c.failed=false,c.failureReason=void 0,c.issuedChallenge=null,s?c.verifiedDeviceId=c.verifiedDeviceId??c.expectedDeviceId??a??null:(c.verifiedDeviceId=null,c.expectedDeviceId=null),this.deps.applyConnectionTrustProjection(e);let d=s?c.verifiedDeviceId??c.expectedDeviceId??a??null:null;d&&this.deps.bindConnectionDeviceIdInRust(e,d),o&&this.deps.addPeerScope(e.id,o),c$1("[Client][AUTH] session-token approval applied to connection trust",{connectionId:e.id,remoteNodeId:e.remoteNodeId,scope:t??null,source:n}),e.admissionReady?.("session-token-trust-applied");}clearConnectionApproval(e){this.disposed||(this.approvedConnectionIds.delete(e),this.approvedScopesByConnectionId.delete(e),this.pendingTrustApprovals.delete(e),this.pendingTrustApprovalScopes.delete(e));}approveNode(e){this.disposed||this.approvedNodes.add(e);}approveConnection(e){this.disposed||this.approvedConnectionIds.add(e);}isApproved(e,t){return this.approvedConnectionIds.has(e)||this.approvedNodes.has(t)}isApprovedNode(e){return this.approvedNodes.has(e)}isApprovedConnection(e){return this.approvedConnectionIds.has(e)}getApprovedNodes(){return this.approvedNodes}getApprovedConnectionIds(){return this.approvedConnectionIds}clearRejectionCooldown(e){this.rejectionCooldowns.delete(e);}getRejectionCooldown(e){return this.rejectionCooldowns.get(e)}setRejectionCooldown(e,t){this.disposed||this.rejectionCooldowns.set(e,t);}getApprovedScope(e){return this.approvedScopesByConnectionId.get(e)??null}setApprovedScope(e,t){this.disposed||this.approvedScopesByConnectionId.set(e,t);}rememberRouteRepairTokenForNode(e,t,n){this.disposed||(this.routeRepairTokenByNodeId.set(e,t),this.routeRepairTokenPayloadByNodeId.set(e,n));}forgetRouteRepairTokenForNode(e,t,n){this.routeRepairTokenByNodeId.get(e)!==t||this.routeRepairTokenPayloadByNodeId.get(e)!==n||(this.routeRepairTokenByNodeId.delete(e),this.routeRepairTokenPayloadByNodeId.delete(e));}async rememberRouteRepairTokenFromTicket(e){if(this.disposed)return false;let t=e.trim();if(!t)return false;let{irohTicket:n,tokenSuffix:i}=ee(t);if(!i)return false;let o=se(n,i),s=typeof o?.t=="string"?o.t.trim():"",a=this.wasmClient;if(!s||typeof a?.endpoint_id_from_ticket!="function")return false;let c=String(await a.endpoint_id_from_ticket(n)).trim();return !c||this.disposed?false:(this.rememberRouteRepairTokenForNode(c,s,i),true)}getRouteRepairTokenForNode(e){return this.routeRepairTokenByNodeId.get(e)}getRouteRepairTokenPayloadForNode(e){return this.routeRepairTokenPayloadByNodeId.get(e)}clearInMemoryState(){this.routeRepairTokenByNodeId.clear(),this.routeRepairTokenPayloadByNodeId.clear(),this.pendingTrustApprovals.clear(),this.pendingTrustApprovalScopes.clear(),this.rejectionCooldowns.clear(),this.approvedNodes.clear(),this.approvedConnectionIds.clear(),this.approvedScopesByConnectionId.clear();}get wasmClient(){return this.ctx.wasmClient}disconnectConnectionBestEffort(e){try{return Promise.resolve(e.disconnect()).catch(()=>{})}catch{return Promise.resolve()}}};function Jr(r){return new Mi({getContext:()=>r.getClientContext(),getOptions:()=>r.options,ensureWasmRuntimeForP2P:()=>r.runtimeReadiness.ensureWasmRuntimeForP2P(),getTicket:()=>r.runtimeIdentity.getTicket(),clearManagedPresenceTicketIfExists:()=>r.accessServices.clearManagedPresenceTicketIfExists(),retirePendingReciprocalAdmissionsIfExists:e=>r.retirePendingReciprocalAdmissionsIfExists(e),clearTrustFailureCooldown:e=>{r.connectionTrust.clearFailureCooldown(e);},sessionTokenScopeAllowsDeviceBinding:e=>r.connectionTrust.sessionTokenScopeAllowsDeviceBinding(e),getKnownDeviceIdForNode:e=>r.deviceDirectory.getKnownDeviceIdForNode(e),initializeConnectionTrust:(e,t)=>r.connectionTrust.initialize(e,t),applyConnectionTrustProjection:e=>r.peerProjection.applyConnectionTrustProjection(e),bindConnectionDeviceIdInRust:(e,t)=>r.connectionDeviceBinder.bindConnectionDeviceIdInRust(e,t),addPeerScope:(e,t)=>{r.peerServices.addPeerScope(e,t);},getPeerScopes:e=>r.peerServices.getPeerScopes(e),getConfiguredApplicationCrypto:()=>r.options?.applicationCrypto,getKnownDeviceNodeId:e=>r.deviceDirectory.getKnownDeviceNodeId(e),getPeerState:e=>r.peerServices.getPeerState(e),notifyApplicationRouteReady:(e,t)=>r.transportUpgrade.notifyApplicationRouteReady(e,t)})}var Mi=class{constructor(e){this.host=e;}get sessionTokens(){return this._sessionTokens||(this._sessionTokens=new Cn(this.host.getContext(),{ensureWasmRuntimeForP2P:()=>this.host.ensureWasmRuntimeForP2P(),getTicket:()=>this.host.getTicket(),clearManagedPresenceTicket:()=>this.host.clearManagedPresenceTicketIfExists(),retirePendingReciprocalAdmissions:e=>this.host.retirePendingReciprocalAdmissionsIfExists(e),clearTrustFailureCooldown:e=>this.host.clearTrustFailureCooldown(e),sessionTokenScopeAllowsDeviceBinding:e=>this.host.sessionTokenScopeAllowsDeviceBinding(e),getKnownDeviceIdForNode:e=>this.host.getKnownDeviceIdForNode(e),initializeConnectionTrust:(e,t)=>this.host.initializeConnectionTrust(e,t),applyConnectionTrustProjection:e=>this.host.applyConnectionTrustProjection(e),bindConnectionDeviceIdInRust:(e,t)=>this.host.bindConnectionDeviceIdInRust(e,t),addPeerScope:(e,t)=>this.host.addPeerScope(e,t),getPeerScopes:e=>this.host.getPeerScopes(e)})),this._sessionTokens}get applicationCrypto(){return this._applicationCrypto||(this._applicationCrypto=new vn(this.host.getContext(),{getConfiguredApplicationCrypto:()=>this.host.getConfiguredApplicationCrypto(),getKnownDeviceNodeId:e=>this.host.getKnownDeviceNodeId(e),getKnownDeviceIdForNode:e=>this.host.getKnownDeviceIdForNode(e),getPeerState:e=>this.host.getPeerState(e),notifyApplicationRouteReady:(e,t)=>this.host.notifyApplicationRouteReady(e,t)})),this._applicationCrypto}resolveExistingApplicationCryptoForPeer(e,t){return this._applicationCrypto?.resolveForPeer(e,t)}getApplicationCrypto(e){return this.host.getConfiguredApplicationCrypto()||!e?this.host.getConfiguredApplicationCrypto():this.applicationCrypto.getApplicationCrypto(e)}resolveApplicationCryptoForPeer(e,t){return this.host.getConfiguredApplicationCrypto()||!e&&!t?this.host.getConfiguredApplicationCrypto():this.applicationCrypto.resolveForPeer(e,t)}clearApplicationCryptoForConnection(e){this._applicationCrypto?.clearConnection(e);}releaseApplicationKeyAgreementReply(e,t,n){this._applicationCrypto?.releaseReplyClaim(e,t,n);}waitForApplicationCryptoForPeer(e,t=0){return this.host.getConfiguredApplicationCrypto()||!e||t<=0?Promise.resolve(this.host.getConfiguredApplicationCrypto()):this.applicationCrypto.waitForPeer(e,t)}};var In=class{constructor(e){this.deps=e;this.disposed=false;this.deps.registerDisposer(()=>this.dispose());}dispose(){this.disposed=true;}buildApplicationIncomingStreamEvent(e){if(this.disposed)return e;if((e.protocolHint==="explicit"||!!e.channel?.channelId)&&!this.deps.isManagedApplicationStreamAuthorized(e.remoteNodeId))return this.deps.logIncomingDiagnostic("session-token:drop-unadmitted-application-stream",{remoteNodeId:e.remoteNodeId||"unknown",traceId:e.traceId||null,protocolHint:e.protocolHint??null,channelId:e.channel?.channelId??null}),{...e,invalid:true};if(this.shouldTreatIncomingStreamAsTransportOnly(e))return e;let n=this.deps.resolveCryptoStreams(e.remoteNodeId);if(!n||e.invalid||e.protocolHint==="explicit"||e.protocolHint==="native-main")return e;try{if(e.type==="uni"){let i=e.stream;return !i||typeof i.getReader!="function"?e:i.applicationCryptoWrapped===!0?{...e,applicationCrypto:n}:{...e,stream:n.wrapReadable(i),applicationCrypto:n}}if(e.type==="bi"&&i$2(e.stream)){let i=e.stream;return i?.applicationCryptoWrapped===!0?{...e,applicationCrypto:n}:e.protocolHint==="control"?{...e,applicationCrypto:n}:{...e,stream:{...i,send:n.wrapWritable(i.send),recv:n.wrapReadable(i.recv)},applicationCrypto:n}}}catch(i){this.deps.logIncomingDiagnostic("application-crypto:wrap-listener-stream-failed",{remoteNodeId:e.remoteNodeId||"unknown",traceId:e.traceId||null,protocolHint:e.protocolHint??null,error:i});}return e}shouldTreatIncomingStreamAsTransportOnly(e){if(this.disposed||e.type!=="bi")return false;let t=e.channel?.channelId;return t?this.deps.isTransportOnlyChannel(t):e.protocolHint!=="explicit"?false:this.deps.usesTicketOnlySignalingMode()?true:this.deps.hasTransportOnlyConnectionForRemoteNode(e.remoteNodeId)}dispatchSyntheticExplicitIncomingStream(e,t){if(this.disposed)return;if(!this.deps.isManagedApplicationStreamAuthorized(e.remoteNodeId)){this.deps.logIncomingDiagnostic("session-token:drop-unadmitted-webrtc-explicit-stream",{connectionId:e.id,remoteNodeId:e.remoteNodeId});return}c$1("[Client][WebRTC][transfer] Dispatching synthetic explicit stream from WebRTC datachannel",{connectionId:e.id,remoteNodeId:e.remoteNodeId,payloadBytes:t.byteLength});let n={send:new WritableStream({write(){}}),recv:new ReadableStream({start(a){a.enqueue(t),a.close();}}),endpoint_id:e.remoteNodeId},i=this.deps.getConnectionChannelId(e.id),o={type:"bi",stream:n,remoteNodeId:e.remoteNodeId,protocolHint:"explicit",traceId:`webrtc-explicit-${Date.now()}`,channel:i?{channelId:i}:null};if(this.deps.dispatchIncomingChannelListeners(o)||this.disposed)return;this.deps.dispatchIncomingGenericListeners(o)||this.handleSyntheticExplicitFallbackInBackground(e,o);}handleSyntheticExplicitFallbackInBackground(e,t){let n=i=>{this.disposed||c$1("[Client][INCOMING] Failed to process synthetic explicit stream",{connectionId:e.id,remoteNodeId:e.remoteNodeId,error:i});};try{Promise.resolve(this.deps.handleUnhandledIncomingStreamEvent(t)).catch(n);}catch(i){n(i);}}};var Sn=class{constructor(e,t){this.ctx=e;this.deps=t;this.disposed=false;this.ctx.registerDisposer(()=>this.dispose());}dispose(){this.disposed=true;}assertActive(){if(this.disposed)throw new Error("Application stream controller is disposed")}async closeWritableBestEffort(e){if(e)try{let t=e.getWriter?.();if(!t)return;try{await t.close();}catch{}finally{try{t.releaseLock();}catch{}}}catch{}}async openBi(e){this.assertActive(),await this.deps.ensureWasmRuntimeForP2P(),this.assertActive();let t=this.ctx.wasmClient;c$1("[Client][OPEN-BI] Opening bidirectional application stream",{peerId:e,hasOpenPeerBi:typeof t.open_peer_bi=="function"});let n=typeof t.open_peer_bi=="function"?await t.open_peer_bi(e,5e3):await t.open_bi(e);this.disposed&&(await l$2(n,"application-stream-controller-disposed-after-open-bi"),this.assertActive()),c$1("[Client][OPEN-BI] Bidirectional application stream opened",{peerId:e,endpointId:n?.endpoint_id??n?.endpointId??null,applicationCryptoWrapped:n?.applicationCryptoWrapped===true});let i=this.deps.getApplicationCryptoForPeer(e),o=n?.applicationCryptoWrapped===true;if(i&&!o){let s=z$1(i);return {readable:s.wrapReadable(n.recv),writable:s.wrapWritable(n.send)}}return {readable:n.recv,writable:n.send}}async openUni(e){this.assertActive(),await this.deps.ensureWasmRuntimeForP2P(),this.assertActive();let t=this.deps.getApplicationCryptoForPeer(e),n=(a,c)=>!t||c?a:z$1(t).wrapWritable(a),i=this.ctx.wasmClient;if(typeof i.open_peer_uni=="function"){let a=await i.open_peer_uni(e,5e3),c=a?.writable??a;return this.disposed&&(await this.closeWritableBestEffort(c),this.assertActive()),n(c,a?.applicationCryptoWrapped===true)}let o=await i.open_uni(e),s=o?.writable??o;return this.disposed&&(await this.closeWritableBestEffort(s),this.assertActive()),n(s,o?.applicationCryptoWrapped===true)}async sendFrame(e,t){this.assertActive(),await this.deps.ensureWasmRuntimeForP2P(),this.assertActive();let n=this.ctx.wasmClient;if(typeof n.send_peer_application_frame=="function"){await n.send_peer_application_frame(e,t,5e3),this.assertActive();return}let i=await this.openBi(e),o=i.writable.getWriter();try{await o.write(t),await o.close();}finally{try{o.releaseLock();}catch{}try{await i.readable.cancel("one-shot application frame sent");}catch{}}}};function Xe(r){try{let e=r?.type;return typeof e=="string"?e:"unknown"}catch{return "unknown"}}function xe(r){try{let e=r?.endpointId;if(typeof e=="string"&&e.trim().length>0)return e}catch{}try{let e=r?.endpoint_id;if(typeof e=="string"&&e.trim().length>0)return e}catch{}return "unknown"}function Di(r){try{let e=r?.transportStableId??r?.transport_stable_id;if(Number.isSafeInteger(e)&&Number(e)>0)return Number(e)}catch{}return null}function Xr(r){try{let e=r?.protocolHint;if(e==="control"||e==="explicit"||e==="native-main")return e}catch{}return null}function Zr(r){try{if(!r||!("channel"in r))return {present:!1,channel:null};let e=r.channel;if(e==null)return {present:!0,channel:null};if(typeof e!="object")return {present:!1,channel:null};let t=typeof e.channelId=="string"?e.channelId.trim():"";if(!t)return {present:!1,channel:null};let n=e.metadata&&typeof e.metadata=="object"&&!Array.isArray(e.metadata)?e.metadata:null;return {present:!0,channel:{channelId:t,metadata:n}}}catch{return {present:false,channel:null}}}var _e=class _e{constructor(e){this.wasmClient=e;this.clients=new Set;this.listenLoopTask=null;this.activeDispatches=new Set;}addClient(e){this.clients.has(e)||(this.clients.add(e),this.ensureListening());}removeClient(e){this.clients.delete(e);}dispatchIncomingAsync(e,t){let n=xe(e),i=performance.now(),o=this.dispatchIncoming(e).then(()=>{let s=performance.now()-i;s>50&&console.warn(`[PERFORMANCE] handleIncomingStream loop took abnormally long: ${Math.round(s)}ms`,{endpointId:n,type:t});}).catch(s=>{console.error("[Client][INCOMING] Failed to handle incoming stream via shared hub",{remoteNodeId:n,type:t,error:s instanceof Error?s.message:String(s)});}).finally(()=>{this.activeDispatches.delete(o);});this.activeDispatches.add(o);}ensureListening(){this.listenLoopTask||(this.listenLoopTask=this.listenLoop().finally(()=>{this.listenLoopTask=null,this.clients.size>0&&this.ensureListening();}));}getPrimaryClient(){let e=this.clients.values().next();return e.done?null:e.value}getChannelTargetClients(e){return Array.from(this.clients).reverse().filter(t=>t.hasIncomingChannelListener(e))}async dispatchIncoming(e){let t=this.getPrimaryClient();if(!t)return;let n=Array.from(this.clients).some(a=>a.shouldInspectIncomingChannelEnvelope()),i=await t.normalizeIncomingStreamEvent(e,{inspectChannelEnvelope:n}),o=i.channel?.channelId?.trim();if(o&&t.isInternalSessionChannel(o)){await t.handleUnhandledIncomingStreamEvent(i);return}if(o){for(let a of this.getChannelTargetClients(o))if(a.dispatchIncomingChannelListeners(i))return}let s=this.getPrimaryClient();if(s){if(i.protocolHint==="native-main"){await s.handleUnhandledIncomingStreamEvent(i);return}s.dispatchIncomingGenericListeners(i)||await s.handleUnhandledIncomingStreamEvent(i);}}async listenLoop(){let e$1=0;for(;;){if(this.clients.size===0)return;let t=null;try{let i=(await this.wasmClient.incoming_streams()).getReader();for(t=i,e$1=0,ce()&&Kt()&&c$1("[Client][INCOMING][MOBILE] shared-hub reader acquired",{sharedHubClients:this.clients.size});this.clients.size>0;){let{done:o,value:s}=await i.read();if(o)throw new Error("incoming stream reader closed unexpectedly");if(!s)continue;let a=Xe(s);a!=="uni"&&c$1("[Client][INCOMING] Received stream from WASM node",{type:a,endpointId:xe(s),sharedHubClients:this.clients.size}),this.dispatchIncomingAsync(s,a);}}catch(n){if(this.clients.size===0)return;e$1+=1;let i=h(e$1,_e.RETRY_MIN_DELAY_MS,_e.RETRY_MAX_DELAY_MS);console.warn("[Client][INCOMING] Shared listen loop restarting after stream failure",{attempt:e$1,delayMs:i,mobile:ce(),error:n}),await e(i);}finally{if(t)try{t.releaseLock(),ce()&&Kt()&&c$1("[Client][INCOMING][MOBILE] shared-hub reader released",{sharedHubClients:this.clients.size});}catch{}}}}};_e.RETRY_MIN_DELAY_MS=250,_e.RETRY_MAX_DELAY_MS=2e3;var bn=_e;var Ze=class Ze{constructor(e,t){this.ctx=e;this.deps=t;this.listening=false;this.presenceStarted=false;this.listenLoopTask=null;this.hubClient={hasIncomingChannelListener:n=>this.deps.hasIncomingChannelListener(n),hasAnyIncomingChannelListeners:()=>this.deps.hasAnyIncomingChannelListeners(),shouldInspectIncomingChannelEnvelope:()=>this.deps.shouldInspectIncomingChannelEnvelope(),isInternalSessionChannel:n=>this.deps.isInternalSessionChannel(n),normalizeIncomingStreamEvent:(n,i)=>this.deps.normalizeIncomingStreamEvent(n,i),dispatchIncomingChannelListeners:n=>this.deps.dispatchIncomingChannelListeners(n),dispatchIncomingGenericListeners:n=>this.deps.dispatchIncomingGenericListeners(n),handleUnhandledIncomingStreamEvent:n=>this.deps.handleUnhandledIncomingStreamEvent(n)},this.ctx.registerDisposer(()=>this.stop());}async start(e={}){if(this.listening)return;await this.deps.ensureWasmRuntimeForP2P();let t=false;this.markListening(false);try{let n=this.getSharedIncomingStreamHub();n?(n.addClient(this.hubClient),t=!0):this.listenLoopTask||(this.listenLoopTask=this.listenLoop().finally(()=>{this.listenLoopTask=null;})),e.startPresence!==!1&&(await this.deps.startPresenceForListen(),this.presenceStarted=!0);}catch(n){throw this.markStopped(),this.presenceStarted=false,t&&this.getSharedIncomingStreamHub()?.removeClient(this.hubClient),n}}stop(){let e=this.listening;if(this.markStopped(),e)for(let t of Array.from(this.ctx.registry.values()))t.isClosed||this.disconnectBestEffort(t);this.getSharedIncomingStreamHub()?.removeClient(this.hubClient),e&&this.presenceStarted&&this.deps.setOfflinePresence(),this.presenceStarted=false;}prepareForSignOut(){this.markStopped(),this.presenceStarted=false;}isListening(){return this.listening}markListening(e=true){this.listening=true,this.presenceStarted=e;}markStopped(){this.listening=false;}getSharedIncomingStreamHub(){let e=this.ctx.wasmClient;if(!e||typeof e.incoming_streams!="function")return null;let t=e,n=Ze.incomingStreamHubs.get(t);return n||(n=new bn(e),Ze.incomingStreamHubs.set(t,n)),n}async listenLoop(){await this.deps.getIncomingStreamRouter().listenLoop({isListening:()=>this.listening,getWasmClient:()=>this.ctx.wasmClient,handleIncomingStream:e=>this.handleIncomingStream(e),shouldVerboseIncomingDiagnostics:()=>this.deps.shouldVerboseIncomingDiagnostics(),getLocalNodeId:()=>this.ctx.localNodeId||null,retryMinDelayMs:this.deps.retryMinDelayMs,retryMaxDelayMs:this.deps.retryMaxDelayMs});}async handleIncomingStream(e){return this.deps.handleIncomingStream(e)}shouldInspectIncomingChannelEnvelope(){return this.deps.shouldInspectIncomingChannelEnvelope()}normalizeIncomingStreamEvent(e,t={}){return this.deps.normalizeIncomingStreamEvent(e,t)}dispatchIncomingChannelListeners(e){return this.deps.dispatchIncomingChannelListeners(e)}dispatchIncomingGenericListeners(e){return this.deps.dispatchIncomingGenericListeners(e)}handleUnhandledIncomingStreamEvent(e){return this.deps.handleUnhandledIncomingStreamEvent(e)}disconnectBestEffort(e){try{Promise.resolve(e.disconnect()).catch(()=>{});}catch{}}};Ze.incomingStreamHubs=new WeakMap;var Pn=Ze;var Rn=class{constructor(e){this.deps=e;this.traceSequence=0;}getRuntimeSafetyProfile(){return this.deps.getRuntimeSafetyProfileOverride()??Ye(this.deps.getOptions()??{})}shouldVerboseIncomingDiagnostics(){return this.getRuntimeSafetyProfile().diagnosticsMode}shouldInspectIncomingChannelEnvelope(){return this.getRuntimeSafetyProfile().skipIncomingChannelEnvelopeInspection?false:this.deps.hasAnyIncomingChannelListeners()||this.deps.requiresIncomingChannelEnvelopeInspection()}nextIncomingTraceId(e,t){Number.isFinite(this.traceSequence)||(this.traceSequence=0),this.traceSequence+=1;let n=t&&t.length>0?t.slice(0,8):"unknown";return `${e}-${n}-${this.traceSequence.toString(36)}`}logIncomingDiagnostic(e,t){this.shouldVerboseIncomingDiagnostics()&&c$1(`[Client][INCOMING][MOBILE] ${e}`,t);}safeReleaseReaderLock(e,t,n,i=(o,s)=>this.logIncomingDiagnostic(o,s)){try{e.releaseLock(),i("releaseLock:ok",{context:t,traceId:n||null});}catch(o){console.warn("[Client][INCOMING] releaseLock failed",{context:t,traceId:n||null,error:o});}}async cancelUnhandledIncomingUniStream(e,t,n=(i,o)=>this.logIncomingDiagnostic(i,o)){if(!(!e||typeof e!="object")){if(this.shouldVerboseIncomingDiagnostics()){n("uni:drop-unhandled",{remoteNodeId:t||"unknown"});return}try{let i=e;if(typeof i.cancel=="function")return;if(typeof i.getReader=="function"){let o=i.getReader();try{await o.read().catch(()=>{});}finally{try{o.releaseLock();}catch{}}d$2("[Client][INCOMING] Released unhandled uni stream reader",{remoteNodeId:t});}}catch(i){console.warn("[Client][INCOMING] Failed to cancel unhandled uni stream",{remoteNodeId:t,error:i});}}}shouldSkipIncomingStreamProbe(){return this.getRuntimeSafetyProfile().skipIncomingBiProbe===true}};var Tn=class{constructor(e,t){this.config=e;this.deps=t;}async normalize(e,t){return this.deps.router.normalizeIncomingStreamEvent(e,t,this.normalizationDeps())}async extractIncomingChannelEnvelope(e,t,n){return this.deps.router.extractIncomingChannelEnvelope(e,t,this.channelInspectionDeps(),n)}async classifyBiIncomingStream(e,t){return this.deps.router.classifyBiIncomingStream(e,this.channelInspectionDeps(),t)}async maybeOpenEncryptedExplicitBiStream(e,t,n){return this.deps.router.maybeOpenEncryptedExplicitBiStream(e,this.cryptoProbeConfig(),this.cryptoProbeDeps(),t,n)}wrapIncomingBi(e,t,n){return this.deps.router.wrapIncomingBi(e,this.cryptoProbeDeps(),t,n)}async maybeOpenEncryptedControlBiStream(e,t,n){return this.deps.router.maybeOpenEncryptedControlBiStream(e,this.cryptoProbeConfig(),this.cryptoProbeDeps(),t,n)}async detectNativeMainStream(e,t,n){return this.deps.router.detectNativeMainStream(e,t,{nativeMainProtocolByte:this.config.nativeMainProtocolByte,explicitProtocolByte:this.config.explicitProtocolByte,label:this.config.nativeMainLabel,maxLabelBytes:this.config.nativeMainMaxLabelBytes},this.channelInspectionDeps(),n)}channelInspectionDeps(){return {logIncomingDiagnostic:(e,t)=>this.deps.logIncomingDiagnostic(e,t),releaseReaderLock:(e,t,n)=>this.deps.releaseReaderLock(e,t,n)}}cryptoProbeConfig(){return {explicitProtocolByte:this.config.explicitProtocolByte,maxEncryptedFrameBytes:this.config.maxEncryptedFrameBytes,probeDeadlineMs:this.config.probeDeadlineMs}}cryptoProbeDeps(){return {...this.channelInspectionDeps(),resolveApplicationCryptoForPeer:e=>this.deps.resolveApplicationCryptoForPeer(e),waitForApplicationCryptoForPeer:e=>this.deps.waitForApplicationCryptoForPeer(e,this.config.explicitApplicationCryptoWaitMs),resolveCryptoStreams:e=>this.deps.resolveCryptoStreams(e)}}normalizationDeps(){return {...this.cryptoProbeDeps(),nextIncomingTraceId:(e,t)=>this.deps.nextIncomingTraceId(e,t),normalizeAuthoritativeIncomingProtocolHint:(e,t,n)=>Bt(e),shouldStripIncomingMainLabel:()=>ar(this.deps.shouldSkipIncomingStreamProbe()),shouldSkipIncomingBiProbeForRemoteNode:e=>this.deps.shouldSkipIncomingBiProbeForRemoteNode(e),inferTicketFlowBiProtocolHint:e=>this.deps.inferTicketFlowBiProtocolHint(e),shouldSkipIncomingStreamProbe:()=>this.deps.shouldSkipIncomingStreamProbe(),isTransportOnlyChannel:e=>this.deps.isTransportOnlyChannel(e),detectNativeMainStream:(e,t,n)=>this.detectNativeMainStream(e,t,n),extractIncomingChannelEnvelope:(e,t,n)=>this.extractIncomingChannelEnvelope(e,t,n),classifyBiIncomingStream:(e,t)=>this.classifyBiIncomingStream(e,t),wrapIncomingBi:(e,t,n)=>this.wrapIncomingBi(e,t,n),maybeOpenEncryptedExplicitBiStream:(e,t,n)=>this.maybeOpenEncryptedExplicitBiStream(e,t,n),maybeOpenEncryptedControlBiStream:(e,t,n)=>this.maybeOpenEncryptedControlBiStream(e,t,n)}}};var et=class extends Error{},wn=class{wrapIncomingBi(e,t,n,i){if(!i$2(e)||e?.applicationCryptoWrapped===true)return e;let o=t.resolveCryptoStreams(n);if(!o)return e;try{return {...e,send:o.wrapWritable(e.send),recv:o.wrapReadable(e.recv),applicationCryptoWrapped:!0}}catch(s){return t.logIncomingDiagnostic("application-crypto:early-wrap-incoming-bi-failed",{remoteNodeId:n||"unknown",traceId:i||null,error:s}),e}}async maybeOpenEncryptedExplicitBiStream(e,t,n,i,o){let s=n.resolveApplicationCryptoForPeer(o);if(!i$2(e))return e;let a;try{a=e.recv.getReader();}catch{return e}let c=(v,y,C=null)=>m$2(a,v,{context:y,traceId:i,pendingRead:C,release:I=>n.releaseReaderLock(a,`${y}:${I}`,i),log:(I,b)=>n.logIncomingDiagnostic(I,b)}),d=v=>k$3(e,v),l=[],p=new Uint8Array(0),u=null,h=Date.now()+t.probeDeadlineMs,m=async()=>{let v=await n$1(a,h);return v.status==="timeout"?(u=v.pendingRead??null,false):v.status==="done"?false:(v.value&&v.value.byteLength>0&&(l.push(v.value),p=g(l)),true)},f=()=>u?(n.logIncomingDiagnostic("explicit-crypto:probe-deadline",{traceId:i||null,endpointId:o||"unknown",bufferedBytes:p.byteLength}),d(c(p,"explicit-crypto:probe-deadline",u))):null;try{for(;p.byteLength<5&&await m(););let v=f();if(v)return v;if(p.byteLength<5||p[0]!==t.explicitProtocolByte)return d(c(p,"explicit-crypto:not-probeable"));let y=new DataView(p.buffer,p.byteOffset+1,p.byteLength-1).getUint32(0,!1);if(y===0||y>t.maxEncryptedFrameBytes){let A=p.slice(1);return this.looksLikeApplicationCryptoEnvelope(A)?(s||(n.logIncomingDiagnostic("explicit-crypto:await-key",{traceId:i||null,endpointId:o||"unknown"}),s=await n.waitForApplicationCryptoForPeer(o)),s?(n.logIncomingDiagnostic("explicit-crypto:unframed-encrypted-body",{traceId:i||null,endpointId:o||"unknown"}),d(this.unframedEncryptedExplicitReadable(a,A,s,t.explicitProtocolByte,n,i))):this.rejectEncryptedStreamWithoutCrypto(a,n,i,o,"explicit-crypto:unframed-encrypted-body-missing-key")):d(c(p,"explicit-crypto:not-encrypted-length"))}let C=5+y;for(;p.byteLength<C&&await m(););let I=f();if(I)return I;if(p.byteLength<C)return d(c(p,"explicit-crypto:truncated-probe"));let b=p.slice(5,C);if(!x$1(b))return d(c(p,"explicit-crypto:legacy-plaintext"));if(s||(n.logIncomingDiagnostic("explicit-crypto:await-key",{traceId:i||null,endpointId:o||"unknown"}),s=await n.waitForApplicationCryptoForPeer(o)),!s)return n.logIncomingDiagnostic("explicit-crypto:encrypted-body-missing-key",{traceId:i||null,endpointId:o||"unknown"}),this.rejectEncryptedStreamWithoutCrypto(a,n,i,o,"explicit-crypto:encrypted-body-missing-key");let P=c(p.slice(1),"explicit-crypto:encrypted-body");return d(this.encryptedExplicitReadable(P,s,t.explicitProtocolByte,n,i))}catch(v){if(v instanceof et)throw v;return n.logIncomingDiagnostic("explicit-crypto:probe-error",{traceId:i||null,error:v?.message||String(v)}),d(c(p,"explicit-crypto:probe-error"))}}async maybeOpenEncryptedControlBiStream(e,t,n,i,o){if(!i$2(e)||e?.applicationCryptoWrapped===true)return e;let s;try{s=e.recv.getReader();}catch{return e}let a=(f,v,y=null)=>m$2(s,f,{context:v,traceId:i,pendingRead:y,release:C=>n.releaseReaderLock(s,`${v}:${C}`,i),log:(C,I)=>n.logIncomingDiagnostic(C,I)}),c=f=>k$3(e,f),d=[],l=new Uint8Array(0),p=null,u=Date.now()+t.probeDeadlineMs,h=async()=>{let f=await n$1(s,u);return f.status==="timeout"?(p=f.pendingRead??null,false):f.status==="done"?false:(f.value&&f.value.byteLength>0&&(d.push(f.value),l=g(d)),true)},m=()=>p?(n.logIncomingDiagnostic("control-crypto:probe-deadline",{traceId:i||null,endpointId:o||"unknown",bufferedBytes:l.byteLength}),c(a(l,"control-crypto:probe-deadline",p))):null;try{for(;l.byteLength<4&&await h(););let f=m();if(f)return f;if(l.byteLength<4)return c(a(l,"control-crypto:not-probeable"));let v=new DataView(l.buffer,l.byteOffset,l.byteLength).getUint32(0,!1);if(v===0||v>t.maxEncryptedFrameBytes)return c(a(l,"control-crypto:plaintext-length"));let y=4+Math.min(v,7);for(;l.byteLength<y&&await h(););let C=m();if(C)return C;if(l.byteLength<y)return c(a(l,"control-crypto:truncated-probe"));let I=l.slice(4,y);if(!this.looksLikeApplicationCryptoEnvelope(I))return c(a(l,"control-crypto:plaintext-frame"));let b=n.resolveApplicationCryptoForPeer(o);if(b||(n.logIncomingDiagnostic("control-crypto:await-key",{traceId:i||null,endpointId:o||"unknown"}),b=await n.waitForApplicationCryptoForPeer(o)),!b)return n.logIncomingDiagnostic("control-crypto:encrypted-body-missing-key",{traceId:i||null,endpointId:o||"unknown"}),this.rejectEncryptedStreamWithoutCrypto(s,n,i,o,"control-crypto:encrypted-body-missing-key");n.logIncomingDiagnostic("control-crypto:encrypted-frame",{traceId:i||null,endpointId:o||"unknown",frameLength:v});let P=z$1(b);return {...e,send:P.wrapWritable(e.send),recv:P.wrapReadable(a(l,"control-crypto:encrypted-frame")),applicationCryptoWrapped:!0}}catch(f){if(f instanceof et)throw f;return n.logIncomingDiagnostic("control-crypto:probe-error",{traceId:i||null,endpointId:o||"unknown",error:f?.message||String(f)}),c(a(l,"control-crypto:probe-error"))}}encryptedExplicitReadable(e,t,n,i,o){let a=z$1(t).wrapReadable(e).getReader(),c=false;return new ReadableStream({async pull(d){if(!c){c=true,d.enqueue(new Uint8Array([n]));return}try{let{done:l,value:p}=await a.read();if(l){d.close(),a.releaseLock();return}p&&d.enqueue(p);}catch(l){d.error(l);try{a.releaseLock();}catch{}}},async cancel(d){try{await a.cancel(d);}catch{}try{a.releaseLock();}catch{}i.logIncomingDiagnostic("explicit-crypto:cancel",{traceId:o||null});}})}unframedEncryptedExplicitReadable(e,t,n,i,o,s){let a=false,c=false;return new ReadableStream({async pull(d){if(!a){a=true,d.enqueue(new Uint8Array([i]));return}if(c){d.close();return}c=true;let l=[t];try{for(;;){let{done:h,value:m}=await e.read();if(h)break;m&&m.byteLength>0&&l.push(new Uint8Array(m));}let p=g(l),u=n.openPayload(3,p);if(!u)throw new Error("[OpenRTC] encrypted explicit body failed authentication");d.enqueue(u),d.close();}catch(p){d.error(p);}finally{try{e.releaseLock();}catch{}}},async cancel(d){try{await e.cancel(d);}catch{}try{e.releaseLock();}catch{}o.logIncomingDiagnostic("explicit-crypto:unframed-cancel",{traceId:s||null});}})}looksLikeApplicationCryptoEnvelope(e){return e.byteLength>=7&&e[0]===79&&e[1]===82&&e[2]===84&&e[3]===67&&e[4]===69&&e[5]===49}async rejectEncryptedStreamWithoutCrypto(e,t,n,i,o){let s=new et(`[OpenRTC] rejected encrypted stream without negotiated application crypto (${o})`);try{await e.cancel(s);}catch{}throw t.releaseReaderLock(e,o,n),t.logIncomingDiagnostic("application-crypto:stream-rejected",{traceId:n||null,endpointId:i||"unknown",context:o}),s}};var Le=class{async extractIncomingUniChannelEnvelope(e,t,n,i){let o={send:new WritableStream,recv:e,endpoint_id:t},s=await this.extractIncomingChannelEnvelope(o,t,n,i);return {stream:s.stream.recv,channel:s.channel}}async extractIncomingChannelEnvelope(e,t,n,i){if(!i$2(e))return {stream:e,channel:null};let o;try{o=e.recv.getReader(),n.logIncomingDiagnostic("channel-envelope:reader-acquired",{traceId:i||null,remoteNodeId:t||"unknown"});}catch(S){return console.warn("[Client][CHANNEL] Incoming stream recv reader unavailable; skipping channel envelope inspection",{remoteNodeId:t,traceId:i||null,error:S}),{stream:e,channel:null}}let s=(S,D)=>m$2(o,S,{context:D,traceId:i,release:_=>n.releaseReaderLock(o,`${D}:${_}`,i),log:(_,T)=>n.logIncomingDiagnostic(_,T)}),a=S=>k$3(e,S),c=[],d=0;try{for(;d<6;){let{done:S,value:D}=await o.read();if(S)break;if(!D||D.byteLength===0)continue;let _=new Uint8Array(D);c.push(_),d+=_.byteLength;}}catch(S){return console.warn("[Client][CHANNEL] Failed reading incoming channel envelope prefix",{remoteNodeId:t,traceId:i||null,error:S}),n.releaseReaderLock(o,"extractIncomingChannelEnvelope:read-prefix-failed",i),{stream:e,channel:null}}let l=g(c);if(l.byteLength<6||l[0]!==127||l[1]!==1)return c$1("[Client][CHANNEL] Incoming stream did not start with channel envelope",{remoteNodeId:t,traceId:i||null,bufferedBytes:l.byteLength,firstBytes:Array.from(l.slice(0,Math.min(l.byteLength,8))).map(S=>S.toString(16).padStart(2,"0")).join(" ")}),{stream:a(s(l,"extractIncomingChannelEnvelope:not-envelope")),channel:null};let p=new DataView(l.buffer,l.byteOffset,l.byteLength),u=p.getUint16(2,false),h=p.getUint16(4,false),m=6+u+h,f=l;if(f.byteLength<m)try{for(;f.byteLength<m;){let{done:S,value:D}=await o.read();if(S)break;!D||D.byteLength===0||(f=g([f,new Uint8Array(D)]));}}catch(S){console.warn("[Client][CHANNEL] Failed extending incoming channel envelope read",{remoteNodeId:t,error:S});}if(f.byteLength<m||u===0)return {stream:a(s(f,"extractIncomingChannelEnvelope:truncated-envelope")),channel:null};let v=6,y=v+u,C=y+h,I=new TextDecoder,b=I.decode(f.slice(v,y)).trim(),P=null;if(h>0)try{let S=JSON.parse(I.decode(f.slice(y,C)));S&&typeof S=="object"&&!Array.isArray(S)&&(P=S);}catch(S){console.warn("[Client][CHANNEL] Failed to parse incoming channel metadata",{remoteNodeId:t,channelId:b,error:S});}if(!b)return {stream:a(s(f,"extractIncomingChannelEnvelope:empty-channel-id")),channel:null};let A=a(s(f.slice(m),"extractIncomingChannelEnvelope:channel-envelope-consumed"));return c$1("[Client][CHANNEL] Incoming channel envelope consumed",{remoteNodeId:t,traceId:i||null,channelId:b,metadata:P?Object.keys(P):[],bufferedBytes:f.byteLength,remainingBytes:Math.max(0,f.byteLength-m)}),{stream:A,channel:{channelId:b,metadata:P}}}async classifyBiIncomingStream(e,t,n,i){if(!i$2(e))return {stream:e,protocolHint:"unknown"};let o;try{o=e.recv.getReader();}catch{return {stream:e,protocolHint:"unknown"}}let s;try{s=await o.read();}catch{return n.releaseReaderLock(o,"classifyBiIncomingStream:read-failed",i),{stream:e,protocolHint:"unknown"}}if(s.done||!s.value||s.value.byteLength===0)return n.releaseReaderLock(o,"classifyBiIncomingStream:empty-first-read",i),c$1("[Client][INCOMING] classifyBiIncomingStream: empty read",{traceId:i||null,done:s.done,hasValue:!!s.value,byteLength:s.value?.byteLength}),{stream:e,protocolHint:"unknown"};let a=new Uint8Array(s.value),c=a[0];c$1("[Client][INCOMING] classifyBiIncomingStream: first byte",{traceId:i||null,firstByte:"0x"+c.toString(16),EXPLICIT_PROTOCOL_BYTE:"0x"+t.toString(16),isExplicit:c===t,chunkLength:a.length});let d=k$3(e,m$2(o,a,{context:"classifyBiIncomingStream:first-chunk",traceId:i,release:l=>n.releaseReaderLock(o,`classifyBiIncomingStream:first-chunk:${l}`,i),log:(l,p)=>n.logIncomingDiagnostic(l,p)}));return c===t?{stream:d,protocolHint:"explicit"}:{stream:d,protocolHint:"control"}}async detectNativeMainStream(e,t,n,i,o){if(!i$2(e))return {handled:false,stream:e,protocolHint:"unknown"};let s;try{s=e.recv.getReader();}catch(P){return console.warn("[Client][NATIVE-MAIN] Incoming stream recv reader unavailable",{remoteNodeId:t,traceId:o||null,error:P}),{handled:false,stream:e,protocolHint:"control"}}let a=(P,A)=>m$2(s,P,{context:A,traceId:o,release:S=>i.releaseReaderLock(s,`${A}:${S}`,o),log:(S,D)=>i.logIncomingDiagnostic(S,D)}),c=P=>k$3(e,P),d=[],l=0,p=5,u=false;try{for(;l<p;){let{done:P,value:A}=await s.read();if(P){u=!0;break}!A||A.byteLength===0||(d.push(new Uint8Array(A)),l+=A.byteLength);}}catch(P){return console.warn("[Client][NATIVE-MAIN] Failed reading incoming prefix",{remoteNodeId:t,traceId:o||null,error:P}),i.releaseReaderLock(s,"detectNativeMainStream:read-prefix-failed",o),{handled:false,stream:e,protocolHint:"control"}}let h=g(d);if(h.byteLength<p||h[0]!==n.nativeMainProtocolByte)return {handled:false,stream:c(a(h,"detectNativeMainStream:not-native-main")),protocolHint:h[0]===n.explicitProtocolByte?"explicit":"control"};let m=new DataView(h.buffer,h.byteOffset,h.byteLength).getUint32(1,false);if(m===0||m>n.maxLabelBytes)return {handled:false,stream:c(a(h,"detectNativeMainStream:invalid-label-length")),protocolHint:"control"};let f=5+m,v=h;if(v.byteLength<f&&!u){let P=[v],A=v.byteLength;try{for(;A<f;){let{done:S,value:D}=await s.read();if(S){u=!0;break}if(!D||D.byteLength===0)continue;let _=new Uint8Array(D);P.push(_),A+=_.byteLength;}}catch(S){console.warn("[Client][NATIVE-MAIN] Failed extending prefix read",{remoteNodeId:t,error:S});}v=g(P);}if(v.byteLength<f)return {handled:false,stream:c(a(v,"detectNativeMainStream:truncated-label")),protocolHint:"control"};let y=v.slice(5,f),C=new TextDecoder().decode(y),I=C==="signal";if(C!==n.label&&!I)return {handled:false,stream:c(a(v,"detectNativeMainStream:label-mismatch")),protocolHint:"control"};let b=c(a(v.slice(f),"detectNativeMainStream:label-consumed"));return I&&(b.native_signal_only=true),c$1("[Client][NATIVE-MAIN] Detected desktop native main stream",{remoteNodeId:t,traceId:o||null,label:C,nativeSignalOnly:I}),{handled:true,stream:b,protocolHint:"native-main"}}};var An=class{constructor(){this.transfers=new Map;}clear(){this.transfers.clear();}maybeHandle(e,t,n){if(t.byteLength<25||t[0]!==n.explicitProtocolByte)return false;let i=t.slice(1,17),o=Array.from(i).map(u=>u.toString(16).padStart(2,"0")).join(""),s=`${e.id}:${o}`,a=new DataView(t.buffer,t.byteOffset,t.byteLength),c=a.getUint32(17,false),d=a.getUint32(21,false);if(c===4294967295){if(t.byteLength<29)return true;let u=a.getUint32(25,false),h=29,m=h+u;if(m>t.byteLength)return true;let f=n.openWebRTCExplicitTransferPayload(t.slice(h,m),e);return f?(this.transfers.set(s,{headerBytes:f,chunks:new Map,total:0,received:0}),c$1("[Client][WebRTC][transfer] Incoming WebRTC explicit transfer header received",{connectionId:e.id,remoteNodeId:e.remoteNodeId,transferIdKey:o,headerBytes:u}),true):(this.transfers.delete(s),true)}let l=this.transfers.get(s);if(!l)return true;if(l.total===0)l.total=d;else if(l.total!==d)return this.transfers.delete(s),true;if(l.chunks.has(c))return true;let p=n.openWebRTCExplicitTransferPayload(t.slice(25),e);if(!p)return this.transfers.delete(s),true;if(l.chunks.set(c,p),l.received+=1,l.total>0&&l.received>=l.total){let u=this.reassemble(l,n.explicitProtocolByte);this.transfers.delete(s),u&&(c$1("[Client][WebRTC][transfer] Incoming WebRTC transfer assembled in browser",{connectionId:e.id,remoteNodeId:e.remoteNodeId,transferIdKey:o,chunks:l.total,payloadBytes:u.byteLength}),n.dispatchSyntheticExplicitIncomingStream(e,u));}return true}reassemble(e,t){let n=[],i=0;for(let a=0;a<e.total;a+=1){let c=e.chunks.get(a);if(!c)return null;n.push(c),i+=c.byteLength;}let o=new Uint8Array(5+e.headerBytes.byteLength+i);o[0]=t,new DataView(o.buffer).setUint32(1,e.headerBytes.byteLength,false),o.set(e.headerBytes,5);let s=5+e.headerBytes.byteLength;for(let a of n)o.set(a,s),s+=a.byteLength;return o}};var kn=class{constructor(){this.protocolInspector=new Le;}async normalize(e,t,n){let i=n.resolveCryptoStreams(t.endpointId),o=!!i,s=i?i.wrapReadable(e):e,a=t.authoritativeChannel;if(!a&&t.inspectChannelEnvelope){let c=await this.protocolInspector.extractIncomingUniChannelEnvelope(s,t.endpointId,n,t.traceId);s=c.stream,a=c.channel;}return o&&Object.defineProperty(s,"applicationCryptoWrapped",{configurable:true,value:true}),{stream:s,channel:a}}};var Nn=class{constructor(e){this.deps=e;this.messageListeners=[];this.roomRequestListeners=[];this.streamListeners=[];this.channelStreamListeners=new Map;this.registeredChannels=new Map;this.protocolInspector=new Le;this.cryptoProbe=new wn;this.uniStreamNormalizer=new kn;this.transferAssembler=new An;this.disposed=false;this.deps?.registerDisposer(()=>this.dispose());for(let t of this.deps?.defaultChannels??[])this.registerChannel(t);}dispose(){this.disposed||(this.disposed=true,this.messageListeners=[],this.roomRequestListeners=[],this.streamListeners=[],this.channelStreamListeners.clear(),this.registeredChannels.clear(),this.transferAssembler.clear());}get webrtcIncomingExplicitTransfers(){return this.transferAssembler.transfers}set webrtcIncomingExplicitTransfers(e){this.transferAssembler.transfers=e;}onMessage(e){return this.disposed?()=>{}:(this.messageListeners.push(e),()=>{this.messageListeners=this.messageListeners.filter(t=>t!==e);})}dispatchMessage(e,t){if(!this.disposed)for(let n of [...this.messageListeners])try{n(e,t);}catch(i){console.warn("[Client] message listener failed",i);}}onIncomingStream(e){return this.disposed?()=>{}:(this.streamListeners.push(e),()=>{this.streamListeners=this.streamListeners.filter(t=>t!==e);})}hasIncomingStreamListeners(){return this.streamListeners.length>0}getRegisteredChannel(e){let t=typeof e=="string"?e.trim():"";return t?this.registeredChannels.get(t)??null:null}registerChannel(e){if(this.disposed)return;let t=e.id.trim();if(!t)throw new Error("Channel registration requires a non-empty channel id.");this.registeredChannels.set(t,{...e,id:t});}unregisterChannel(e){let t=e.trim();t&&(this.registeredChannels.delete(t),this.channelStreamListeners.delete(t));}listChannels(){return Array.from(this.registeredChannels.values())}onChannelStream(e,t){if(this.disposed)return ()=>{};let n=e.trim();if(!n)throw new Error("Channel stream listener requires a non-empty channel id.");let i=this.channelStreamListeners.get(n)??new Set;return i.add(t),this.channelStreamListeners.set(n,i),()=>{let o=this.channelStreamListeners.get(n);o&&(o.delete(t),o.size===0&&this.channelStreamListeners.delete(n));}}hasIncomingChannelListener(e){let t=e.trim();return t?(this.channelStreamListeners.get(t)?.size??0)>0:false}hasAnyIncomingChannelListeners(){for(let e of this.channelStreamListeners.values())if(e.size>0)return true;return false}requiresIncomingChannelEnvelopeInspection(){for(let e of this.registeredChannels.values())if(e.kind==="system"&&e.routing==="session-default")return true;return false}isInternalSessionChannel(e){let t=this.getRegisteredChannel(e);return t?.kind==="system"&&t.routing==="session-default"}dispatchIncomingChannelListeners(e){let t=e.channel?.channelId?.trim();if(!t)return false;let n=this.channelStreamListeners.get(t);if(!n)return false;for(let i of [...n])try{if(i(e)===!0)return !0}catch(o){console.warn("[Client] incoming channel stream listener failed",o);}return false}dispatchIncomingGenericListeners(e){for(let t of [...this.streamListeners])try{if(t(e)===!0)return !0}catch(n){console.warn("[Client] incoming stream listener failed",n);}return false}onRoomJoinRequest(e){return this.disposed?()=>{}:(this.roomRequestListeners.push(e),()=>{this.roomRequestListeners=this.roomRequestListeners.filter(t=>t!==e);})}async listenLoop(e$1){let t=0;for(;e$1.isListening();){let n=e$1.getWasmClient();if(!n||typeof n.incoming_streams!="function"){console.warn("[Client][INCOMING] incoming_streams is unavailable; stopping listen loop");return}let i=null;try{i=(await n.incoming_streams()).getReader();let s=i;for(t=0,e$1.shouldVerboseIncomingDiagnostics()&&c$1("[Client][INCOMING][MOBILE] direct listen reader acquired",{localNodeId:e$1.getLocalNodeId()});e$1.isListening();){let{done:a,value:c}=await s.read();if(a)throw new Error("incoming stream reader closed unexpectedly");if(!c)continue;let d=Xe(c);d!=="uni"&&c$1("[Client][INCOMING] Received stream from WASM node",{type:d,endpointId:xe(c)});try{await e$1.handleIncomingStream(c);}catch(l){let p=c,u=Xe(p),h=xe(p);console.error("[Client][INCOMING] Failed to handle incoming stream",{remoteNodeId:h,type:u,error:l});}}}catch(o){if(!e$1.isListening())break;t+=1;let s=h(t,e$1.retryMinDelayMs,e$1.retryMaxDelayMs);console.warn("[Client][INCOMING] Listen loop restarting after stream failure",{attempt:t,delayMs:s,mobile:ce(),error:o}),await e(s);}finally{if(i)try{i.releaseLock(),e$1.shouldVerboseIncomingDiagnostics()&&c$1("[Client][INCOMING][MOBILE] direct listen reader released",{localNodeId:e$1.getLocalNodeId()});}catch{}}}}async handleIncomingStream(e,t){let n=await t.normalizeIncomingStreamEvent(e,{inspectChannelEnvelope:t.shouldInspectIncomingChannelEnvelope()}),i=t.buildApplicationIncomingStreamEvent(n);if(!n.invalid&&i.invalid)return;if(this.isInternalSessionChannel(i.channel?.channelId)){await t.handleUnhandledIncomingStreamEvent(i);return}if(this.dispatchIncomingChannelListeners(i))return;if(n.protocolHint==="native-main"){await t.handleUnhandledIncomingStreamEvent(n);return}this.dispatchIncomingGenericListeners(i)||await t.handleUnhandledIncomingStreamEvent(n);}async normalizeIncomingStreamEvent(e,t,n){let i="bi",o=e,s="",a=null,c=null,d=null,l={present:false,channel:null},p=false;try{p="type"in e;}catch{p=false;}if(p){i=Xe(e);try{o=e.stream;}catch{o=null;}let v=xe(e);s=v==="unknown"?"":v,a=Di(e),d=Xr(e),l=Zr(e);}else {try{s=e.endpoint_id??"";}catch{s="";}a=Di(e);}let u=n.nextIncomingTraceId("incoming",s);d=n.normalizeAuthoritativeIncomingProtocolHint(d,s,u);let h=l.present&&l.channel!==null;n.logIncomingDiagnostic("normalize:start",{traceId:u,hasType:p,type:i,endpointId:s||"unknown",inspectChannelEnvelope:!!t?.inspectChannelEnvelope,authoritativeProtocolHint:d??null,authoritativeChannel:h}),i!=="uni"&&c$1("[Client][INCOMING] handleIncomingStream called",{hasType:p,type:i,endpointId:s});let m="unknown",f=d===null&&!!t?.inspectChannelEnvelope;if(i==="bi"){let v=j$3(o,s,a);if(!v||!i$2(v)){let I=false,b=false;try{I=!!o?.send;}catch{}try{b=!!o?.recv;}catch{}return console.error("[Client][INCOMING] Invalid bidirectional stream payload",{remoteNodeId:s,...a?{transportStableId:a}:{},hasSend:I,hasRecv:b}),{type:"bi",stream:o,remoteNodeId:s,...a?{transportStableId:a}:{},traceId:u,protocolHint:"unknown",channel:null,applicationCrypto:n.resolveCryptoStreams(s),invalid:true}}o=v,a=v.transport_stable_id??a;let y=false;if(d===null&&!h&&n.shouldStripIncomingMainLabel()){let I=await n.detectNativeMainStream(o,s,u);o=I.stream,y=true,m=I.protocolHint;}else d==="native-main"&&(m="native-main");if(m!=="native-main"){if(h)c=l.channel;else if(f){let P=await n.extractIncomingChannelEnvelope(o,s,u);o=P.stream,c=P.channel;}if(!(d==="explicit"||d==="control"||d==="native-main")&&!n.isTransportOnlyChannel(c?.channelId)&&(d!==null||h||c)&&(o=n.wrapIncomingBi(o,s,u)),d!==null)m=d,n.logIncomingDiagnostic("bi:use-authoritative-metadata",{traceId:u,endpointId:s||"unknown",protocolHint:m,hasChannelEnvelope:!!c});else if(n.shouldSkipIncomingBiProbeForRemoteNode(s)){let P=n.inferTicketFlowBiProtocolHint(s);if(m=P.protocolHint,n.logIncomingDiagnostic("bi:skip-probe-ticket-flow",{traceId:u,endpointId:s||"unknown",inferredProtocolHint:m,hasExistingConnection:P.hasExistingConnection,hasMagicLinkScope:P.hasMagicLinkScope}),!c&&!y&&n.shouldStripIncomingMainLabel()){let A=await n.detectNativeMainStream(o,s,u);o=A.stream,m=A.protocolHint;}}else {let P=await n.classifyBiIncomingStream(o,u);if(o=P.stream,m=P.protocolHint,m!=="explicit"&&!y&&n.shouldStripIncomingMainLabel()){let A=await n.detectNativeMainStream(o,s,u);o=A.stream,m=A.protocolHint;}}}let C=!n.shouldSkipIncomingStreamProbe()&&!n.isTransportOnlyChannel(c?.channelId);if(C&&m==="explicit"&&o?.applicationCryptoWrapped!==true)o=await n.maybeOpenEncryptedExplicitBiStream(o,u,s);else if(C&&m==="control"&&o?.applicationCryptoWrapped!==true&&(o=await n.maybeOpenEncryptedControlBiStream(o,u,s),o?.applicationCryptoWrapped===true)){let I=await n.classifyBiIncomingStream(o,u);o=I.stream,m=I.protocolHint,n.logIncomingDiagnostic("bi:reclassify-decrypted-stream",{traceId:u,endpointId:s||"unknown",protocolHint:m});}if(!c&&f&&o?.applicationCryptoWrapped===true){let I=await n.extractIncomingChannelEnvelope(o,s,u);o=I.stream,c=I.channel;}}else if(i==="uni"&&o&&typeof o.getReader=="function"){let v=await this.uniStreamNormalizer.normalize(o,{endpointId:s,traceId:u,inspectChannelEnvelope:f,authoritativeChannel:h?l.channel:null},n);o=v.stream,c=v.channel;}return n.logIncomingDiagnostic("normalize:done",{traceId:u,endpointId:s||"unknown",type:i,protocolHint:m,hasChannelEnvelope:!!c}),{type:i,stream:o,remoteNodeId:s,...a?{transportStableId:a}:{},traceId:u,protocolHint:m,channel:c,applicationCrypto:n.resolveCryptoStreams(s)}}async extractIncomingChannelEnvelope(e,t,n,i){return this.protocolInspector.extractIncomingChannelEnvelope(e,t,n,i)}async classifyBiIncomingStream(e,t,n){let i=this.deps?.explicitProtocolByte??0;return this.protocolInspector.classifyBiIncomingStream(e,i,t,n)}wrapIncomingBi(e,t,n,i){return this.cryptoProbe.wrapIncomingBi(e,t,n,i)}async maybeOpenEncryptedExplicitBiStream(e,t,n,i,o){return this.cryptoProbe.maybeOpenEncryptedExplicitBiStream(e,t,n,i,o)}async maybeOpenEncryptedControlBiStream(e,t,n,i,o){return this.cryptoProbe.maybeOpenEncryptedControlBiStream(e,t,n,i,o)}async detectNativeMainStream(e,t,n,i,o){return this.protocolInspector.detectNativeMainStream(e,t,n,i,o)}maybeHandleWebRTCExplicitFileEnvelope(e,t){return this.disposed||!this.deps?false:this.transferAssembler.maybeHandle(e,t,this.deps)}};function ns(r){let{host:e}=r;return new Nn({explicitProtocolByte:2,defaultChannels:zo,registerDisposer:t=>e.registerDisposer(t),openWebRTCExplicitTransferPayload:(t,n)=>e.openWebRTCExplicitTransferPayload(t,n),dispatchSyntheticExplicitIncomingStream:(t,n)=>r.getApplicationIncoming().dispatchSyntheticExplicitIncomingStream(t,n)})}function is(r){let{host:e}=r,t=e.getPresenceForIncomingListen();return new Pn(e.getContext(),{ensureWasmRuntimeForP2P:()=>e.ensureWasmRuntimeForP2P(),startPresenceForListen:()=>t.startPresenceLoopForListen(),setOfflinePresence:()=>{t.setOffline();},shouldInspectIncomingChannelEnvelope:()=>r.getDiagnostics().shouldInspectIncomingChannelEnvelope(),handleIncomingStream:n=>r.getRouter().handleIncomingStream(n,{shouldInspectIncomingChannelEnvelope:()=>r.getDiagnostics().shouldInspectIncomingChannelEnvelope(),normalizeIncomingStreamEvent:(i,o)=>r.getNormalizer().normalize(i,o),buildApplicationIncomingStreamEvent:i=>r.getApplicationIncoming().buildApplicationIncomingStreamEvent(i),handleUnhandledIncomingStreamEvent:i=>e.handleUnhandledIncomingStreamEvent(i)}),hasIncomingChannelListener:n=>r.getRouter().hasIncomingChannelListener(n),hasAnyIncomingChannelListeners:()=>r.getRouter().hasAnyIncomingChannelListeners(),isInternalSessionChannel:n=>r.getRouter().isInternalSessionChannel(n),normalizeIncomingStreamEvent:(n,i)=>r.getNormalizer().normalize(n,i),dispatchIncomingChannelListeners:n=>r.getRouter().dispatchIncomingChannelListeners(n),dispatchIncomingGenericListeners:n=>r.getRouter().dispatchIncomingGenericListeners(n),handleUnhandledIncomingStreamEvent:n=>e.handleUnhandledIncomingStreamEvent(n),shouldVerboseIncomingDiagnostics:()=>r.getDiagnostics().shouldVerboseIncomingDiagnostics(),getIncomingStreamRouter:()=>r.getRouter(),retryMinDelayMs:Wo,retryMaxDelayMs:Oo})}function os(r,e){return new Rn({getOptions:()=>r.getOptions(),getRuntimeSafetyProfileOverride:()=>r.getRuntimeSafetyProfile(),hasAnyIncomingChannelListeners:()=>e().hasAnyIncomingChannelListeners(),requiresIncomingChannelEnvelopeInspection:()=>e().requiresIncomingChannelEnvelopeInspection()})}function rs(r){let{host:e}=r;return new Tn({explicitProtocolByte:2,maxEncryptedFrameBytes:16777216,probeDeadlineMs:Mo,nativeMainProtocolByte:Ct,nativeMainLabel:It,nativeMainMaxLabelBytes:St,explicitApplicationCryptoWaitMs:1500},{router:r.getRouter(),nextIncomingTraceId:(t,n)=>r.getDiagnostics().nextIncomingTraceId(t,n),logIncomingDiagnostic:(t,n)=>r.getDiagnostics().logIncomingDiagnostic(t,n),releaseReaderLock:(t,n,i)=>r.getDiagnostics().safeReleaseReaderLock(t,n,i),shouldSkipIncomingStreamProbe:()=>r.getDiagnostics().shouldSkipIncomingStreamProbe(),shouldSkipIncomingBiProbeForRemoteNode:t=>e.shouldSkipIncomingBiProbeForRemoteNode(t),inferTicketFlowBiProtocolHint:t=>e.inferTicketFlowBiProtocolHint(t),isTransportOnlyChannel:t=>e.isTransportOnlyChannel(t),resolveApplicationCryptoForPeer:t=>e.resolveApplicationCryptoForPeer(t),waitForApplicationCryptoForPeer:(t,n)=>e.waitForApplicationCryptoForPeer(t,n),resolveCryptoStreams:t=>e.resolveCryptoStreams(t)})}function ss(r){let{host:e}=r;return new In({registerDisposer:t=>e.registerDisposer(t),resolveCryptoStreams:t=>e.resolveCryptoStreams(t),logIncomingDiagnostic:(t,n)=>r.getDiagnostics().logIncomingDiagnostic(t,n),isTransportOnlyChannel:t=>e.isTransportOnlyChannel(t),usesTicketOnlySignalingMode:()=>e.usesTicketOnlySignalingMode(),hasTransportOnlyConnectionForRemoteNode:t=>e.hasTransportOnlyConnectionForRemoteNode(t),isManagedApplicationStreamAuthorized:t=>e.isManagedApplicationStreamAuthorized(t),getConnectionChannelId:t=>e.getConnectionChannelId(t),dispatchIncomingChannelListeners:t=>r.getRouter().dispatchIncomingChannelListeners(t),dispatchIncomingGenericListeners:t=>r.getRouter().dispatchIncomingGenericListeners(t),handleUnhandledIncomingStreamEvent:t=>e.handleUnhandledIncomingStreamEvent(t)})}function as(r){return new Sn(r.getContext(),{ensureWasmRuntimeForP2P:()=>r.ensureWasmRuntimeForP2P(),getApplicationCryptoForPeer:e=>r.resolveApplicationCryptoForPeer(e)})}function cs(r){return new _i({getContext:()=>r.getClientContext(),getOptions:()=>r.options,getRuntimeSafetyProfile:()=>r.runtimeSafetyProfile,registerDisposer:e=>r.lifecycleScope.register(e),ensureWasmRuntimeForP2P:()=>r.runtimeReadiness.ensureWasmRuntimeForP2P(),getPresenceForIncomingListen:()=>r.presence,openWebRTCExplicitTransferPayload:(e,t)=>r.applicationCrypto.openWebRTCExplicitTransferPayload(e,t),dispatchSyntheticExplicitIncomingStream:(e,t)=>r.applicationIncomingStreams.dispatchSyntheticExplicitIncomingStream(e,t),handleUnhandledIncomingStreamEvent:e=>r.incomingConnectionAcceptor.handleUnhandledIncomingStreamEvent(e),shouldSkipIncomingBiProbeForRemoteNode:e=>r.transportHealth.shouldSkipIncomingBiProbeForRemoteNode(e),inferTicketFlowBiProtocolHint:e=>r.peerIdentity.inferTicketFlowBiProtocolHint(e),isTransportOnlyChannel:e=>r.connectionChannelPolicy.isTransportOnlyChannel(e),hasTransportOnlyConnectionForRemoteNode:e=>r.transportHealth.hasTransportOnlyConnectionForRemoteNode(e),isManagedApplicationStreamAuthorized:e=>{if(!(r.runtimeStatus.usesTicketOnlySignalingMode()||r.runtimeStatus.requiresManagedTransportTrust(r.discoveryMode)))return true;let n=e?.trim();return n?r.sessionTokens.isApproved(r.peerIdentity.getDeterministicConnectionId(n),n):false},getConnectionChannelId:e=>r.connectionChannelPolicy.getConnectionChannelId(e),usesTicketOnlySignalingMode:()=>r.runtimeStatus.usesTicketOnlySignalingMode(),resolveApplicationCryptoForPeer:e=>r.applicationCrypto.resolveForPeer(e),waitForApplicationCryptoForPeer:(e,t)=>r.applicationCrypto.waitForPeer(e,t),resolveCryptoStreams:e=>r.applicationCrypto.resolveStreamTools(e)})}var _i=class{constructor(e){this.host=e;}get factoryHost(){return {host:this.host,getRouter:()=>this.router,getDiagnostics:()=>this.diagnostics,getNormalizer:()=>this.normalizer,getApplicationIncoming:()=>this.applicationIncoming}}get router(){return this._router??(this._router=ns(this.factoryHost))}get listen(){return this._listen??(this._listen=is(this.factoryHost))}get diagnostics(){return this._diagnostics??(this._diagnostics=os(this.host,()=>this.router))}get normalizer(){if(this._normalizer||(this._normalizer=rs(this.factoryHost)),!this._generationFencedNormalizer){let e=this._normalizer;this._generationFencedNormalizer=new Proxy(e,{get:(t,n)=>{if(n==="normalize")return async(o,s)=>(await this.assertCurrentIncomingTransport(o),e.normalize(o,s));let i=Reflect.get(e,n,e);return typeof i=="function"?i.bind(e):i}});}return this._generationFencedNormalizer}async assertCurrentIncomingTransport(e){let t=e,n;try{n=t.type;}catch{return}if(n!=="bi"&&n!=="uni")return;let i,o;try{i=t.endpointId??t.endpoint_id,o=t.transportStableId??t.transport_stable_id;}catch{throw new Error("Rejected incoming WASM stream with unreadable transport generation")}if(typeof i!="string"||i.trim().length===0||!Number.isSafeInteger(o)||Number(o)<=0)throw new Error("Rejected incoming WASM stream without a valid transport generation");let s=this.host.getContext().wasmClient;if(!s||typeof s.is_current_transport_stable_id!="function")throw new Error("Rejected incoming WASM stream because generation validation is unavailable");if(!await s.is_current_transport_stable_id(i.trim(),BigInt(Number(o))))throw new Error("Rejected incoming WASM stream from a retired transport generation")}get applicationIncoming(){return this._applicationIncoming??(this._applicationIncoming=ss(this.factoryHost))}get applicationStreams(){return this._applicationStreams??(this._applicationStreams=as(this.host))}prepareListenForSignOut(){this._listen?.prepareForSignOut();}stopListenIfExists(){this._listen?.stop();}};function Mn(r,e,t,n){if(!r||r.isClosed)return false;if(!(typeof r.isApplicationCryptoRequired=="function"?r.isApplicationCryptoRequired():false))return true;let o=n??r.remoteNodeId??t??r.deviceId;return !!e(o,r)}function xi(r){return !r||r.isClosed?false:typeof r.isWebRtcApplicationRouteReady=="function"?r.isWebRtcApplicationRouteReady():false}var Dn=class{constructor(e,t){this.ctx=e;this.deps=t;this.recoveryInFlight=new Set;this.failedConnectionIds=new Set;this.disposed=false;this.ctx.registerDisposer(()=>this.dispose());}dispose(){this.disposed=true,this.recoveryInFlight.clear(),this.failedConnectionIds.clear();}hasApplicationRouteForPeer(e,t){let n=this.deps.getConnectionForPeer(e,t);return Mn(n,this.deps.resolveApplicationCryptoForPeer,e,t)}hasApplicationRouteForConnection(e){return Mn(e,this.deps.resolveApplicationCryptoForPeer,e?.id,e?.remoteNodeId)}notifyApplicationRouteReady(e,t){this.disposed||e.isClosed||!this.hasApplicationRouteForConnection(e)||(this.failedConnectionIds.delete(e.id),c$1("[Client][HANDSHAKE] application route ready",{connectionId:e.id,remoteNodeId:e.remoteNodeId,reason:t}),this.deps.hasRustPeerLifecycleProjection()?(this.deps.reportApplicationRouteReady(e,t),this.schedulePeerReconciliationBestEffort("application-route-ready")):this.deps.applyConnectionTrustProjection(e),this.deps.isConnectionAnnounced(e.id)||this.deps.announceConnectionWhenStable(e));}async waitForApplicationRouteForConnection(e$1,t,n){let i=Date.now()+t;for(;!e$1.isClosed;){if(this.disposed)return false;if(this.hasApplicationRouteForConnection(e$1))return true;if(Date.now()>=i)return false;await e(n);}return false}async waitForReciprocalKeyAgreementObservation(e$1,t,n){let i=Date.now()+n;for(;!e$1.isClosed;){if(this.disposed||this.ctx.registry.get(e$1.id)!==e$1)return false;if(e$1.getKeyAgreementEpoch()>t)return true;if(Date.now()>=i)return false;await e(Math.min(50,Math.max(1,n)));}return false}isWebRtcApplicationRouteReadyForConnection(e){return xi(e)}async sendApplicationRouteHandshakeAttempt(e,t,n,i,o,s="capability-update"){if(!this.disposed){c$1("[Client][HANDSHAKE] refreshing application route handshake",{connectionId:e.id,remoteNodeId:e.remoteNodeId,reason:t,action:s,attempt:n+1,maxAttempts:i,preferNativeSignalRoute:o});try{o?await this.deps.sendTransportHandshake(e,s,null,{preferNativeSignalRoute:!0}):await this.deps.sendTransportHandshake(e,s);}catch(a){if(this.disposed)return;console.warn("[Client][HANDSHAKE] application route handshake send failed",{connectionId:e.id,remoteNodeId:e.remoteNodeId,reason:t,action:s,attempt:n+1,error:a});}}}async refreshApplicationRouteHandshake(e$1,t,n={}){if(this.disposed||e$1.isClosed||!this.deps.shouldNegotiateApplicationKeyAgreement())return;let i=this.deps.resolveApplicationCryptoForPeer(e$1.remoteNodeId,e$1);i&&e$1.setApplicationCrypto(i);let o=this.hasApplicationRouteForConnection(e$1);if(o&&!n.forceReciprocal){this.notifyApplicationRouteReady(e$1,t);return}if(o&&n.forceReciprocal){let c=Math.min(3,this.deps.maxRecoveryAttempts);for(let d=0;d<c;d+=1){let l=e$1.getKeyAgreementEpoch();if(await this.sendApplicationRouteHandshakeAttempt(e$1,t,d,c,true,"response"),await this.waitForReciprocalKeyAgreementObservation(e$1,l,this.deps.attemptWaitMs)){this.notifyApplicationRouteReady(e$1,`${t}:reciprocal-confirmed`);return}if(this.disposed||e$1.isClosed||this.ctx.registry.get(e$1.id)!==e$1)return;let p=this.deps.backoffMs[Math.min(d,this.deps.backoffMs.length-1)]??0;p>0&&await e(p);}throw this.failedConnectionIds.add(e$1.id),this.schedulePeerReconciliationBestEffort("application-route-reciprocal-handshake-exhausted"),new Error(`[Client][HANDSHAKE] reciprocal application key agreement timed out for ${e$1.id}`)}if(this.recoveryInFlight.has(e$1.id))return;this.failedConnectionIds.delete(e$1.id);let s=this.deps.getConnectionControlFrameMode(e$1),a=t==="connect-existing"?"hello":"capability-update";if(await this.sendApplicationRouteHandshakeAttempt(e$1,t,0,this.deps.maxRecoveryAttempts,false,a),!this.disposed){if(await this.waitForApplicationRouteForConnection(e$1,this.deps.attemptWaitMs,50)){this.notifyApplicationRouteReady(e$1,t);return}if(!this.disposed){if(this.deps.hydrateAdoptedConnectionApplicationCrypto(e$1,t)){this.failedConnectionIds.delete(e$1.id);return}if(s==="native-main"&&!e$1.isClosed&&!this.hasApplicationRouteForConnection(e$1)){if(await this.sendApplicationRouteHandshakeAttempt(e$1,t,1,this.deps.maxRecoveryAttempts,true,a),this.disposed)return;if(await this.waitForApplicationRouteForConnection(e$1,this.deps.attemptWaitMs,50)){this.notifyApplicationRouteReady(e$1,t);return}if(this.disposed)return;if(this.deps.hydrateAdoptedConnectionApplicationCrypto(e$1,t)){this.failedConnectionIds.delete(e$1.id);return}}e$1.isClosed||this.hasApplicationRouteForConnection(e$1)||this.driveApplicationRouteRecoveryInBackground(e$1,t);}}}handleApplicationRouteMissing(e,t){if(this.disposed)return;let n=this.ctx.registry.get(e);!n||n.isClosed||n.id!==t.connectionId||n.remoteNodeId===t.remoteNodeId&&(c$1("[Client][HANDSHAKE] WebRTC route proof is waiting on application crypto; refreshing handshake",{connectionId:e,remoteNodeId:t.remoteNodeId,reason:t.reason,negotiationId:t.negotiationId??null}),this.refreshRouteAfterProof(n,t));}refreshRouteAfterProof(e,t){let n=i=>{this.disposed||console.warn("[Client][HANDSHAKE] application route refresh after WebRTC proof failed",{connectionId:t.connectionId,remoteNodeId:t.remoteNodeId,reason:t.reason,error:i});};try{Promise.resolve(this.refreshApplicationRouteHandshake(e,t.reason)).catch(n);}catch(i){n(i);}}async driveApplicationRouteRecovery(e$1,t){if(this.disposed||this.recoveryInFlight.has(e$1.id))return;this.recoveryInFlight.add(e$1.id);let n=this.deps.getConnectionControlFrameMode(e$1),i=this.deps.maxRecoveryAttempts;try{for(let o=2;o<i;o+=1){if(this.disposed||e$1.isClosed)return;if(this.hasApplicationRouteForConnection(e$1)){this.notifyApplicationRouteReady(e$1,t);return}let s=this.deps.backoffMs[Math.min(o,this.deps.backoffMs.length-1)];if(s>0){if(await e(s),this.disposed)return;if(e$1.isClosed||this.hasApplicationRouteForConnection(e$1)){e$1.isClosed||this.notifyApplicationRouteReady(e$1,t);return}}let a=n==="native-main"&&o%2===1;if(await this.sendApplicationRouteHandshakeAttempt(e$1,t,o,i,a),this.disposed)return;if(await this.waitForApplicationRouteForConnection(e$1,this.deps.attemptWaitMs,50)){this.notifyApplicationRouteReady(e$1,t);return}if(this.disposed)return;if(this.deps.hydrateAdoptedConnectionApplicationCrypto(e$1,t)){this.failedConnectionIds.delete(e$1.id);return}}if(e$1.isClosed||this.hasApplicationRouteForConnection(e$1)){e$1.isClosed||this.notifyApplicationRouteReady(e$1,t);return}this.failedConnectionIds.add(e$1.id),console.warn("[Client][HANDSHAKE] application route recovery exhausted; marking route failed",{connectionId:e$1.id,remoteNodeId:e$1.remoteNodeId,reason:t,controlFrameMode:n,attempts:i}),this.schedulePeerReconciliationBestEffort("application-route-handshake-exhausted");}finally{this.recoveryInFlight.delete(e$1.id);}}clearFailure(e){let t=typeof e=="string"?e.trim():"";t&&this.failedConnectionIds.delete(t);}hasFailure(e){let t=typeof e=="string"?e.trim():"";return !!t&&this.failedConnectionIds.has(t)}driveApplicationRouteRecoveryInBackground(e,t){if(!this.disposed)try{Promise.resolve(this.driveApplicationRouteRecovery(e,t)).catch(()=>{});}catch{}}schedulePeerReconciliationBestEffort(e){if(!this.disposed)try{Promise.resolve(this.deps.schedulePeerReconciliation(e)).catch(()=>{});}catch{}}};var En=class{constructor(e,t){this.ctx=e;this.deps=t;}getDeterministicConnectionId(e){return this.ctx.localNodeId?this.ctx.localNodeId<=e?`${this.ctx.localNodeId}-${e}`:`${e}-${this.ctx.localNodeId}`:`native-main-${e}`}getNativeMainConnectionId(e){return this.getDeterministicConnectionId(e)}findManualDisconnectProjectionForNativeNode(e){let t=typeof e=="string"?e.trim().toLowerCase():"";if(!t)return null;let n=this.getNativeMainConnectionId(e).trim().toLowerCase(),i=o=>{if(!o)return false;let s=String(o.status??"").toLowerCase(),a=String(o.error??"").toLowerCase();return (s==="closed"||s==="disconnected"||s==="failed")&&a.includes("manual disconnect")};for(let o of [e,n]){let s=this.deps.getPeerState(o);if(i(s))return s}return this.deps.listPeerStates().find(o=>{if(!i(o))return false;let s=String(o.nodeId??"").trim().toLowerCase(),a=String(o.connectionId??"").trim().toLowerCase(),c=Array.isArray(o.connectionIds)?o.connectionIds.map(d=>String(d??"").trim().toLowerCase()):[];return s===t||a===n||a.endsWith(`-${t}`)||c.includes(n)||c.some(d=>d.endsWith(`-${t}`))})??null}hasKnownConnectionForRemoteNode(e){let t=typeof e=="string"?e.trim():"";if(!t)return false;if(this.ctx.registry.has(this.getDeterministicConnectionId(t)))return true;for(let n of this.ctx.registry.values()){let i=n;if(i.id===t||i.remoteNodeId===t||i.deviceId===t)return true}return false}inferTicketFlowBiProtocolHint(e){let t=typeof e=="string"?e.trim():"",n=this.hasKnownConnectionForRemoteNode(t),i=false;try{let o=this.deps.getPeerState(t);i=Array.isArray(o?.scopes)&&o.scopes.includes("magic-link");}catch{i=false;}return {protocolHint:this.deps.hasAnyIncomingChannelListeners()||this.deps.hasIncomingStreamListeners()||i?"explicit":"control",hasExistingConnection:n,hasMagicLinkScope:i}}};var _n=class{constructor(e,t){this.ctx=e;this.deps=t;this.disposed=false;this.ctx.registerDisposer(()=>this.dispose());}dispose(){this.disposed=true;}hasTransportOnlyConnectionForRemoteNode(e){if(this.disposed)return false;let t=typeof e=="string"?e.trim():"";if(!t)return false;for(let n of this.ctx.registry.values())if(n.remoteNodeId===t&&this.deps.isTransportOnlyConnectionId(n.id))return true;return false}shouldSkipIncomingBiProbeForRemoteNode(e){return this.disposed||!this.deps.getRuntimeSafetyProfile().skipIncomingBiProbe?false:this.deps.usesTicketOnlySignalingMode()?true:this.hasTransportOnlyConnectionForRemoteNode(e)}async disconnectNodeTransport(e){if(this.disposed||!e||!e.trim())return;let t=this.ctx.wasmClient;if(t&&typeof t.disconnect=="function")try{await t.disconnect(e);}catch{}this.disposed||this.deps.notifyDisconnectRequested(e);}async isCoreConnectionHealthy(e){if(this.disposed||!e)return false;let t=this.ctx.wasmClient;if(t&&typeof t.is_connected=="function")try{let n=!!await t.is_connected(e);return this.disposed?!1:n}catch{}try{let n=await this.deps.isConnected(e);return this.disposed?!1:n}catch{return false}}handleConnectionTransportStatus(e,t,n){this.disposed||this.reportConnectionTransportStatus(e,t,n);}handleCurrentConnectionTransportStatus(e,t,n){return this.disposed?Promise.resolve(false):this.reportCurrentConnectionTransportStatus(e,t,n).then(i=>i!==null)}async reportCurrentConnectionTransportStatus(e,t,n){if(this.disposed||!this.matchesCurrentConnectionIdentityRoute(e,t,n))return null;let i=await this.readCurrentGenerationSnapshot(e.id);return !i||!this.matchesCurrentConnectionIdentityRoute(e,t,n)?null:this.reportConnectionTransportStatus(e.id,t,n,i.transportStableId,i.transportGeneration,i.routeGeneration)}handleConnectionApplicationRouteReady(e,t){this.disposed||this.reportConnectionApplicationRouteReady(e,t);}handleCurrentConnectionApplicationRouteReady(e,t){this.disposed||this.reportCurrentConnectionApplicationRouteReady(e,t);}async reportConnectionTransportStatus(e,t,n,i,o,s,a=true){if(this.disposed||!this.matchesCurrentConnectionRoute(e,t,n))return null;let c=await this.readCurrentGenerationObservation(e,i,o,s);if(!c||!this.matchesCurrentConnectionRoute(e,t,n))return null;let d=this.ctx.wasmClient;if(!d||typeof d.report_transport_status!="function")return null;try{let l=await d.report_transport_status(e,t,n??null,BigInt(c.transportStableId),BigInt(c.transportGeneration),BigInt(c.routeGeneration));return this.disposed||l==null?null:(a&&this.deps.hasRustPeerLifecycleProjection()&&this.schedulePeerReconciliationBestEffort("transport-status-report"),this.generationObservationFromSnapshot(l))}catch(l){return this.disposed||c$1("[Client] Failed to report active transport to Rust",{connectionId:e,activeTransport:t,parallelTransport:n??null,error:l}),null}}async reportConnectionApplicationRouteReady(e,t){if(this.disposed)return;let n=await this.reportConnectionTransportStatus(e,t.activeTransport,t.parallelTransport??null,t.transportStableId,t.transportGeneration,t.routeGeneration,false);n&&await this.settleConnectionApplicationRoute(e,t.activeTransport,t.parallelTransport??null,n);}async reportCurrentConnectionApplicationRouteReady(e,t){if(this.disposed||!this.matchesCurrentConnectionIdentityRoute(e,t.activeTransport,t.parallelTransport))return false;let n=null;for(let i=0;i<2&&!n;i+=1){let o=await this.readCurrentGenerationSnapshot(e.id);if(!o||!this.matchesCurrentConnectionIdentityRoute(e,t.activeTransport,t.parallelTransport))return false;n=await this.reportConnectionTransportStatus(e.id,t.activeTransport,t.parallelTransport??null,o.transportStableId,o.transportGeneration,o.routeGeneration,false),!n&&i===0&&await Promise.resolve();}return !n||!this.matchesCurrentConnectionIdentityRoute(e,t.activeTransport,t.parallelTransport)?false:this.settleConnectionApplicationRoute(e.id,t.activeTransport,t.parallelTransport??null,n)}async settleConnectionApplicationRoute(e,t,n,i){if(this.disposed||!this.matchesCurrentConnectionRoute(e,t,n))return false;let o=this.ctx.wasmClient;if(!o||typeof o.report_managed_connection_settled!="function")return false;try{let s=await o.report_managed_connection_settled(e,!0,null,BigInt(i.transportStableId),BigInt(i.transportGeneration),BigInt(i.routeGeneration));return this.disposed||s==null||!this.matchesCurrentConnectionRoute(e,t,n)?!1:(this.deps.hasRustPeerLifecycleProjection()&&this.schedulePeerReconciliationBestEffort("application-route-ready"),!0)}catch(s){return this.disposed||c$1("[Client] Failed to settle proven application route in Rust",{connectionId:e,activeTransport:t,parallelTransport:n,error:s}),false}}async readCurrentGenerationObservation(e,t,n,i){if(!Number.isSafeInteger(t)||Number(t)<=0||!Number.isSafeInteger(n)||Number(n)<=0||!Number.isSafeInteger(i)||Number(i)<0)return null;let o=await this.readCurrentGenerationSnapshot(e);return !o||t!==o.transportStableId||n!==o.transportGeneration||i!==o.routeGeneration?null:o}async readCurrentGenerationSnapshot(e){let t=this.ctx.wasmClient;if(!t||typeof t.connection_state!="function")return null;try{let n=await t.connection_state(e);if(this.disposed||!n||typeof n!="object")return null;let i=n,o=typeof i.transportStableId=="number"?i.transportStableId:i.activeTransportStableId??i.active_transport_stable_id,s=typeof i.transportGeneration=="number"?i.transportGeneration:i.transport_generation,a=typeof i.routeGeneration=="number"?i.routeGeneration:i.route_generation;return !Number.isSafeInteger(o)||Number(o)<=0||!Number.isSafeInteger(s)||Number(s)<=0||!Number.isSafeInteger(a)||Number(a)<0?null:{transportStableId:Number(o),transportGeneration:Number(s),routeGeneration:Number(a)}}catch{return null}}generationObservationFromSnapshot(e){if(!e||typeof e!="object")return null;let t=e,n=t.transportStableId??t.activeTransportStableId??t.active_transport_stable_id,i=t.transportGeneration??t.transport_generation,o=t.routeGeneration??t.route_generation;return !Number.isSafeInteger(n)||Number(n)<=0||!Number.isSafeInteger(i)||Number(i)<=0||!Number.isSafeInteger(o)||Number(o)<0?null:{transportStableId:Number(n),transportGeneration:Number(i),routeGeneration:Number(o)}}matchesCurrentConnectionRoute(e,t,n){let i=this.ctx.registry.get(e);if(!i||i.isClosed||typeof i.getTransportStatus!="function")return false;let o=i.getTransportStatus();return o.activeTransport===t&&(o.parallelTransport??null)===(n??null)}matchesCurrentConnectionIdentityRoute(e,t,n){return this.ctx.registry.get(e.id)===e&&this.matchesCurrentConnectionRoute(e.id,t,n)}schedulePeerReconciliationBestEffort(e){if(!this.disposed)try{Promise.resolve(this.deps.schedulePeerReconciliation(e)).catch(()=>{});}catch{}}};var Ba=[...c];function ls({transportPriority:r,rankRoutes:e,disableIrohFallback:t,runtimeSafetyProfile:n,isMoQReady:i,isMoQDataReady:o,isMoQApplicationRouteProven:s,requestMoQApplicationRouteProof:a,clearMoQApplicationRouteProof:c,requestIrohCarrier:d,sendMoQ:l,sendIrohApplicationFrame:p}){let u=r||Ba;return {priorities:u,rankRoutes:e?h=>e(u,h):void 0,disableIrohFallback:t||false,isMoQReady:i,isMoQDataReady:o,isMoQApplicationRouteProven:s,requestMoQApplicationRouteProof:a,clearMoQApplicationRouteProof:c,requestIrohCarrier:d,sendMoQ:l,sendIrohApplicationFrame:p,runtimeFlow:n.flow,readerCloseStrategy:n.readerCloseStrategy}}var xn=class{constructor(e){this.deps=e;}create(e){let t=this.deps.getOptions();return ls({transportPriority:t?.transportPriority,rankRoutes:(n,i)=>this.deps.rankRoutes(n,i),disableIrohFallback:t?.disableIrohFallback,runtimeSafetyProfile:this.deps.getRuntimeSafetyProfile(),isMoQReady:()=>this.deps.isMoQReady(),isMoQDataReady:()=>this.deps.isMoQDataReady(e),isMoQApplicationRouteProven:()=>this.deps.isMoQApplicationRouteProven(e),requestMoQApplicationRouteProof:()=>this.deps.requestMoQApplicationRouteProof(e),clearMoQApplicationRouteProof:()=>this.deps.clearMoQApplicationRouteProof(e),requestIrohCarrier:()=>this.deps.requestIrohCarrier(e),sendMoQ:(n,i)=>this.deps.sendMoQ(e,n,i),sendIrohApplicationFrame:n=>this.deps.sendIrohApplicationFrame(e,n)})}};var Ln=class{constructor(e){this.deps=e;this.disposed=false;this.deps.registerDisposer(()=>this.dispose());}dispose(){this.disposed=true;}getConnectionControlFrameMode(e){return typeof e.getControlFrameMode=="function"?e.getControlFrameMode():"typed"}async observeIrohCarrierHandshake(e,t,n=true){this.disposed||await this.deps.observeIrohCarrierHandshake?.(e,t,n);}async sendConnectionControlEnvelope(e,t,n={}){if(this.disposed)return;if(this.getConnectionControlFrameMode(e)==="native-main"){if(n.preferNativeSignalRoute&&(typeof e.sendNativeControlEnvelope=="function"?await e.sendNativeControlEnvelope(t):false))return;try{await e.sendRawIrohFrame(le(Ie(t)));return}catch(o){if(typeof e.sendNativeControlEnvelope=="function"?await e.sendNativeControlEnvelope(t):false)return;throw o}}if(typeof e.sendControl=="function"){await e.sendControl(t);return}await e.send(t);}async sendTransportHandshake(e,t,n,i={}){if(this.disposed)return;let o=this.deps.shouldNegotiateApplicationKeyAgreement()?await this.deps.ensureConnectionKeyAgreementState(e):null;if(this.disposed)return;let s=this.deps.isWebRTCExternalCapabilityEnabled?.()??this.deps.isWebRTCTransportEnabled(),a=this.deps.isIrohWebRTCCarrierEnabled?.()??false,c=this.deps.isMoQExternalCapabilityEnabled?.()??this.deps.isMoQReady(),d=this.deps.isIrohMoQCarrierEnabled?.()??false,l={webrtc:s,webrtcExternal:s,webrtcIrohCarrier:a,moq:c,moqExternal:c,moqIrohCarrier:d,ble:this.deps.isBleTransportEnabled(),scopedWebRtcSignalStream:this.deps.supportsScopedWebRtcSignalStream(),...o?{applicationKeyAgreement:true}:{}},p=t==="hello"?this.deps.getPendingSessionToken(e.remoteNodeId):void 0,u=t==="hello"?this.deps.getPendingSessionTokenPayload(e.remoteNodeId):void 0;c$1("[Client][HANDSHAKE] sending",{action:t,connectionId:e.id,remoteNodeId:e.remoteNodeId,channelId:this.deps.getConnectionChannelId(e.id)??null,capabilities:l,hasSessionToken:!!p,hasSessionTokenPayload:!!u,hasChallengeToSign:!!n});let h={type:"handshake",action:t,capabilities:l,moq:l.moq,channelId:this.deps.getConnectionChannelId(e.id)??void 0,...p?{sessionToken:p}:{},...p&&u?{sessionTokenPayload:u}:{},...o?{applicationKeyAgreement:i$3(o.publicKey)}:{}},m=await this.deps.buildLocalTransportTrustPayload(e,n);if(!this.disposed){if(c$1("[Client][HANDSHAKE] local trust payload status",{action:t,connectionId:e.id,remoteNodeId:e.remoteNodeId,hasTransportTrustPayload:!!m,hasChallengeInPayload:!!m?.challenge}),!m){if(this.deps.requiresManagedTransportTrust()){let f=this.deps.initializeConnectionTrust(e);f.failed=true,f.failureReason="local-trusted-identity-unavailable",console.warn("[Client][TRUST] Unable to attach local transport trust payload for managed trust handshake",{connectionId:e.id,remoteNodeId:e.remoteNodeId,action:t});}await this.sendConnectionControlEnvelope(e,h,i),o&&this.deps.markConnectionApplicationCryptoRequired(e);return}await this.sendConnectionControlEnvelope(e,{...h,transportTrust:m},i),o&&this.deps.markConnectionApplicationCryptoRequired(e),c$1("[Client][HANDSHAKE] sent OK",{action:t,connectionId:e.id,remoteNodeId:e.remoteNodeId});}}async sendTransportHandshakeWithRecovery(e$1,t,n,i){for(let o=0;o<this.deps.maxRecoveryAttempts;o+=1){if(this.disposed)return;if(e$1.isClosed)throw new Error("[Client][HANDSHAKE] connection closed before handshake recovery completed");let s=this.getConnectionControlFrameMode(e$1)==="native-main"&&o%2===1;try{await this.sendTransportHandshake(e$1,t,n,{preferNativeSignalRoute:s}),t==="ack"&&!s&&this.getConnectionControlFrameMode(e$1)==="native-main"&&await this.sendTransportHandshake(e$1,t,n,{preferNativeSignalRoute:!0});return}catch(a){let c=o>=this.deps.maxRecoveryAttempts-1;if(console.warn("[Client][HANDSHAKE] control handshake send failed; retrying if budget remains",{connectionId:e$1.id,remoteNodeId:e$1.remoteNodeId,action:t,reason:i,attempt:o+1,maxAttempts:this.deps.maxRecoveryAttempts,preferNativeSignalRoute:s,finalAttempt:c,error:a}),c)throw a;let d=this.deps.recoveryBackoffMs[Math.min(o,this.deps.recoveryBackoffMs.length-1)]??0;if(d>0&&(await e(d),this.disposed))return}}}async broadcastTransportCapabilityUpdate(e){if(this.disposed)return;if(this.deps.isWebRTCTransportEnabled()){let o=this.deps.getRTCConfig();for(let s of this.deps.getConnections()){if(this.disposed)return;s.updateRTCConfig(o);}}if(this.disposed)return;let t=Array.from(this.deps.getConnections()).filter(o=>!o.isClosed).map(async o=>{await this.sendTransportHandshake(o,"capability-update");}),i=(await Promise.allSettled(t)).filter(o=>o.status==="rejected");i.length>0&&c$1("[Client] Some transport capability updates failed",{reason:e,failures:i.length});}requestProtectedWebRTCUpgradeIfInitiator(e,t){if(this.disposed)return;let n=this.deps.isSessionTokenApproved(e.id,e.remoteNodeId),i=this.deps.getLocalNodeId();!this.deps.usesTicketOnlySignalingMode()&&!n||!this.deps.isWebRTCTransportEnabled()||!i||!e.remoteNodeId||i.localeCompare(e.remoteNodeId)<=0||e.requestWebRTCUpgrade(t);}};function Fa(r){let e=r.transports?.ble;return e===true||!!e&&typeof e=="object"&&e.enabled!==false}function ds(r,e){return Fa(r)&&e?.transport.ble===true}function Li(r){return r.transports?.moq}function Fn(r){return !!Li(r)}var Bn=class{constructor(e){this.deps=e;this.attempts=new Map;}isAvailable(){if(!Fn(this.deps.getOptions())||typeof WebTransport>"u")return false;let e=this.deps.getWasmClient();return typeof e?.__beginIrohMoqCarrier=="function"&&typeof e?.__handleIrohCarrierControl=="function"&&typeof e?.__attachIrohMoqCarrier=="function"}async configureWasm(e){if(typeof e.__configureIrohMoqCarrier!="function")return;let t=Li(this.deps.getOptions());await e.__configureIrohMoqCarrier(!!t,t&&typeof t=="object"?t.relayUrl:void 0);}async prepare(e){this.retire(e.connectionId);let t={action:e,session:null,duplex:null,attached:false,failed:false,selected:false};this.attempts.set(e.connectionId,t);let n=Li(this.deps.getOptions());if(!n||typeof n!="object"||!n.relayUrl?.trim()){await this.fail(t,"relay-failed");return}let i;try{i=k$2(n.relayUrl,n.accessToken);}catch(s){console.warn("[OpenRTC][Iroh MoQ carrier] relay configuration rejected",m$1(s,n.accessToken)),await this.fail(t,"relay-failed");return}let o=n.serverCertificateHashes?.length?{serverCertificateHashes:n.serverCertificateHashes}:void 0;try{let s=new WebTransport(i,o);if(await O(s.ready,15e3,"MoQ carrier relay connection"),!this.isCurrent(t)){s.close();return}let a=new Me(s,()=>{},3,new URL(n.relayUrl));if(t.session=a,a.onClose(()=>{this.isCurrent(t)&&!t.selected&&this.fail(t,"relay-failed");}),await O(a.init(),1e4,"MoQ Draft 14 carrier setup"),await O(a.waitForSetup(),5e3,"MoQ Draft 14 carrier setup"),!this.isCurrent(t))return;let c=await this.deps.ensureBound();if(!this.isCurrent(t))return;await c.__irohMoqCarrierPrepared(e.connectionId,e.upgradeId);}catch{await this.fail(t,"relay-failed");}}async activate(e,t){let n=this.attempts.get(e);if(!(!n||n.action.upgradeId!==t||!n.session||n.attached))try{let i=await O(n.session.openDatagramDuplex(n.action.publishNamespace,n.action.subscribeNamespace,n.action.trackName),12e3,"MoQ Draft 14 object-datagram track");if(!this.isCurrent(n)){i.close();return}n.duplex=i,n.attached=!0,await(await this.deps.ensureBound()).__attachIrohMoqCarrier(n.action.connectionId,n.action.remoteEndpointId,i,n.action.upgradeId);}catch(i){n.attached=false,console.warn("[OpenRTC][Iroh MoQ carrier] Draft 14 duplex attachment failed",i),await this.fail(n,"draft14-datagram-unavailable");}}markSelected(e,t){let n=this.attempts.get(e);n?.action.upgradeId===t&&(n.selected=true);}currentUpgradeId(e){return this.attempts.get(e)?.action.upgradeId??null}async failCurrent(e,t){let n=this.attempts.get(e);n&&await this.fail(n,t);}retire(e,t){let n=this.attempts.get(e);if(!(!n||t&&n.action.upgradeId!==t)){this.attempts.delete(e);try{n.duplex?.close();}catch{}try{n.session?.close();}catch{}n.duplex=null,n.session=null;}}dispose(){for(let e of [...this.attempts.keys()])this.retire(e);}async fail(e,t){!this.isCurrent(e)||e.failed||(e.failed=true,await this.deps.reportFailure(e.action.connectionId,e.action.upgradeId,t));}isCurrent(e){return this.attempts.get(e.action.connectionId)===e&&!e.failed}};function us(r){return r.transports?.webrtc}function ps(r){return !!us(r)}var Wn=class{constructor(e){this.deps=e;this.attempts=new Map;this.carrierCaps=new Map;this.disposed=false;this.boundWasm=null;this.actionQueue=Promise.resolve();this.moqMechanism=new Bn({getOptions:()=>this.deps.getOptions(),getWasmClient:()=>this.deps.getWasmClient(),ensureBound:()=>this.ensureBound(),reportFailure:(t,n,i)=>this.reportMoqFailure(t,n,i)}),this.deps.registerDisposer(()=>this.dispose());}isCarrierAvailable(){if(!ps(this.deps.getOptions())||typeof RTCPeerConnection>"u")return false;let e=this.deps.getWasmClient();return typeof e?.__beginIrohWebRtcCarrier=="function"&&typeof e?.__handleIrohCarrierControl=="function"&&typeof e?.__attachIrohWebRtcCarrier=="function"}isMoqCarrierAvailable(){return !Fn(this.deps.getOptions())||typeof WebTransport>"u"?false:this.moqMechanism.isAvailable()}async observeHandshake(e,t,n=true){if(this.disposed||((t?.webrtcIrohCarrier||t?.moqIrohCarrier)&&this.carrierCaps.set(e.id,t),!n))return;let i=this.isCarrierAvailable(),o=this.isMoqCarrierAvailable(),s=t?.webrtcIrohCarrier&&i,a=t?.moqIrohCarrier&&o;if(c$1("[OpenRTC][Iroh carrier] observed trusted capability",{connectionId:e.id,remoteEndpointId:e.remoteNodeId,remoteWebRtc:t?.webrtcIrohCarrier===true,localWebRtc:i,remoteMoq:t?.moqIrohCarrier===true,localMoq:o}),!s&&!a)return;let c=await this.ensureBound();if(typeof c.__beginPreferredIrohCarrier=="function"){await c.__beginPreferredIrohCarrier(e.id,e.remoteNodeId,s===true,t?.webrtcExternal===true||t?.webrtcExternal===void 0&&t?.webrtc===true,a===true,t?.moqExternal===true||t?.moqExternal===void 0&&t?.moq===true);return}s&&await c.__beginIrohWebRtcCarrier(e.id,e.remoteNodeId,t.webrtcExternal===true||t.webrtcExternal===void 0&&t.webrtc===true),a&&await c.__beginIrohMoqCarrier(e.id,e.remoteNodeId,t.moqExternal===true||t.moqExternal===void 0&&t.moq===true);}async revisit(e){let t=this.carrierCaps.get(e.id);t&&await this.observeHandshake(e,t);}async handleControl(e,t){if(this.disposed||!this.isInternalCarrierFrame(t))return false;let n=t,o=!!await(await this.ensureBound()).__handleIrohCarrierControl(e.id,e.remoteNodeId,t);return c$1("[OpenRTC][Iroh carrier] control handled",{connectionId:e.id,frameType:n.type??null,carrier:n.carrier??n.content?.type??null,action:n.action??n.content?.type??null,upgradeId:n.upgradeId??n.content?.negotiationId??null,handled:o}),o}async retireConnection(e,t){this.carrierCaps.delete(e);let n=this.deps.getWasmClient();typeof n?.__retireIrohWebRtcCarrier=="function"&&await n.__retireIrohWebRtcCarrier(e,t),typeof n?.__retireIrohMoqCarrier=="function"&&await n.__retireIrohMoqCarrier(e,t),this.closeAttempt(e),this.moqMechanism.retire(e);}dispose(){if(this.disposed)return;this.disposed=true;let e=[...this.attempts.keys()];for(let t of e)this.retireConnection(t).catch(()=>this.closeAttempt(t));this.moqMechanism.dispose(),this.carrierCaps.clear(),this.boundWasm&&typeof this.boundWasm.__setIrohCarrierActionHandler=="function"&&this.boundWasm.__setIrohCarrierActionHandler(void 0),this.boundWasm=null;}async ensureBound(){let e=this.deps.getWasmClient();if(!e)throw new Error("WASM runtime is unavailable for the Iroh WebRTC carrier");if(this.boundWasm!==e){if(typeof e.__setIrohCarrierActionHandler!="function"||ps(this.deps.getOptions())&&typeof e.__configureIrohWebRtcCarrier!="function"||Fn(this.deps.getOptions())&&typeof e.__configureIrohMoqCarrier!="function")throw new Error("WASM build does not expose the requested Iroh carrier actor");e.__setIrohCarrierActionHandler(n=>{this.actionQueue=this.actionQueue.then(()=>this.handleAction(n)).catch(i=>{console.warn("[OpenRTC][Iroh WebRTC carrier] action failed",{action:n?.type,connectionId:"connectionId"in n?n.connectionId:null,error:i});});}),this.boundWasm=e;}let t=this.deps.getOptions().transports?.privacy==="relay-only"||this.deps.getOptions().strictMode===true;return typeof e.__configureIrohRoutePolicy=="function"&&await e.__configureIrohRoutePolicy(t,this.deps.getOptions().transports?.optimizeFor??"balanced",this.deps.getOptions().transports?.priority??[]),typeof e.__configureIrohWebRtcCarrier=="function"&&await e.__configureIrohWebRtcCarrier(!!us(this.deps.getOptions()),t),await this.moqMechanism.configureWasm(e),e}isInternalCarrierFrame(e){if(!e||typeof e!="object")return false;let t=e;return t.type==="#openrtc-iroh-carrier"&&(t.carrier==="web-rtc"||t.carrier==="moq-draft14")||t.type==="#pluto-signal"&&t.content?.transport==="iroh-webrtc"}async handleAction(e){if(!this.disposed)switch(c$1("[OpenRTC][Iroh carrier] applying Rust-owned action",{action:e.type,connectionId:"connectionId"in e?e.connectionId:null,upgradeId:"upgradeId"in e?e.upgradeId:null,failureCode:"failureCode"in e?e.failureCode:null}),e.type){case "prepare-webrtc":await this.prepare(e);return;case "prepare-moq":await this.moqMechanism.prepare(e);return;case "activate-moq":await this.moqMechanism.activate(e.connectionId,e.upgradeId);return;case "send-control":{let t=this.deps.getConnection(e.connectionId,e.remoteEndpointId);if(!t||t.isClosed){await this.reportControlFailure(e);return}try{await this.deps.sendControl(t,e.envelope);}catch{await this.reportControlFailure(e);}return}case "start-webrtc":await this.start(e.connectionId,e.upgradeId);return;case "apply-webrtc-signal":await this.applySignal(e);return;case "retire-webrtc":this.closeAttempt(e.connectionId,e.upgradeId);return;case "retire-moq":this.moqMechanism.retire(e.connectionId,e.upgradeId);return;case "advance-carrier":{let t=await this.ensureBound();typeof t.__advancePreferredIrohCarrier=="function"&&await t.__advancePreferredIrohCarrier(e.connectionId,e.remoteEndpointId,e.failedRoute);return}case "selected":{if(e.carrier==="webrtc"){let t=this.attempts.get(e.connectionId);t?.action.upgradeId===e.upgradeId&&(t.selected=true);}else this.moqMechanism.markSelected(e.connectionId,e.upgradeId);return}}}async prepare(e){this.closeAttempt(e.connectionId);let t=this.deps.getRTCConfig()??{},n=new RTCPeerConnection(t),i={action:e,peerConnection:n,dataChannel:null,pendingCandidates:[],pendingLocalCandidates:[],localDescriptionSent:false,signalChain:Promise.resolve(),attached:false,failed:false,selected:false};this.attempts.set(e.connectionId,i),n.onicecandidate=s=>{if(!s.candidate||!this.isCurrent(i))return;let a=s.candidate.toJSON();if(!i.localDescriptionSent){i.pendingLocalCandidates.push(a);return}this.queueSignal(i,{type:"candidate",candidate:a});},n.onconnectionstatechange=()=>{!this.isCurrent(i)||i.selected||n.connectionState==="failed"&&this.reportFailure(e.connectionId,e.upgradeId,"ice-failed");},this.installDataChannel(i,n.createDataChannel("openrtc-iroh-packets-v1",{negotiated:true,id:1,ordered:false,maxRetransmits:0,protocol:"openrtc-iroh-packets-v1"}));let o=await this.ensureBound();this.isCurrent(i)&&await o.__irohWebRtcCarrierPrepared(e.connectionId,e.upgradeId);}installDataChannel(e,t){e.dataChannel=t,t.binaryType="arraybuffer",t.onopen=()=>{if(!this.isCurrent(e)||e.attached)return;e.attached=true;let n=this.deps.getWasmClient();Promise.resolve(n.__attachIrohWebRtcCarrier(e.action.connectionId,e.action.remoteEndpointId,t,e.action.upgradeId)).catch(()=>(e.attached=false,this.reportFailure(e.action.connectionId,e.action.upgradeId,"data-channel-failed")));},t.onerror=()=>{e.selected||this.reportFailure(e.action.connectionId,e.action.upgradeId,"data-channel-failed");},t.onclose=()=>{e.selected||this.reportFailure(e.action.connectionId,e.action.upgradeId,"data-channel-failed");};}async start(e,t){let n=this.attempts.get(e);if(!(!n||n.action.upgradeId!==t))try{let i=await n.peerConnection.createOffer();if(!this.isCurrent(n))return;await n.peerConnection.setLocalDescription(i),await this.sendLocalDescription(n,i);}catch{await this.reportFailure(e,t,"signaling-failed");}}async applySignal(e){let t=this.attempts.get(e.connectionId);if(!t||t.action.upgradeId!==e.upgradeId)return;let n=e.signal.content;try{if(n?.type==="sdp"&&n.sdp){if(await t.peerConnection.setRemoteDescription(n.sdp),!this.isCurrent(t))return;for(let i of t.pendingCandidates.splice(0))await t.peerConnection.addIceCandidate(i);if(n.sdp.type==="offer"){let i=await t.peerConnection.createAnswer();await t.peerConnection.setLocalDescription(i),await this.sendLocalDescription(t,i);}}else n?.type==="candidate"&&n.candidate&&(t.peerConnection.remoteDescription?await t.peerConnection.addIceCandidate(n.candidate):t.pendingCandidates.push(n.candidate));}catch{await this.reportFailure(e.connectionId,e.upgradeId,"signaling-failed");}}async sendLocalDescription(e,t){if(await this.queueSignal(e,{type:"sdp",sdp:e.peerConnection.localDescription?.toJSON()??t}),!!this.isCurrent(e)){e.localDescriptionSent=true;for(let n of e.pendingLocalCandidates.splice(0))await this.queueSignal(e,{type:"candidate",candidate:n});}}queueSignal(e,t){let n=e.signalChain.then(async()=>{let i=this.deps.getConnection(e.action.connectionId,e.action.remoteEndpointId);if(!i||i.isClosed||!this.isCurrent(e))throw new Error("carrier control connection is unavailable");await this.deps.sendControl(i,{type:"#pluto-signal",content:{transport:"iroh-webrtc",negotiationId:e.action.upgradeId,...t}});});return e.signalChain=n.catch(()=>{}),n}async reportFailure(e,t,n){let i=this.attempts.get(e);if(!i||i.action.upgradeId!==t||i.failed)return;i.failed=true;let o=this.deps.getWasmClient();typeof o?.__irohWebRtcCarrierFailed=="function"&&await o.__irohWebRtcCarrierFailed(e,t,n);}async reportMoqFailure(e,t,n){let i=this.deps.getWasmClient();typeof i?.__irohMoqCarrierFailed=="function"&&await i.__irohMoqCarrierFailed(e,t,n);}async reportControlFailure(e){if(e.envelope.carrier==="moq-draft14"){await this.moqMechanism.failCurrent(e.connectionId,"relay-failed");return}let n=this.attempts.get(e.connectionId);n&&await this.reportFailure(e.connectionId,n.action.upgradeId,"signaling-failed");}isCurrent(e){return this.attempts.get(e.action.connectionId)===e&&!e.failed&&!this.disposed}closeAttempt(e,t){let n=this.attempts.get(e);!n||t&&n.action.upgradeId!==t||(this.attempts.delete(e),n.peerConnection.onicecandidate=null,n.peerConnection.onconnectionstatechange=null,n.peerConnection.ondatachannel=null,n.dataChannel&&(n.dataChannel.onopen=null,n.dataChannel.onerror=null,n.dataChannel.onclose=null,n.dataChannel.close()),n.peerConnection.close());}};function hs(r){let{host:e}=r;return new Dn(e.getContext(),{getConnectionForPeer:(t,n)=>e.getConnectionForPeer(t,n)??null,resolveApplicationCryptoForPeer:(t,n)=>e.resolveApplicationCryptoForPeer(t,n),shouldNegotiateApplicationKeyAgreement:()=>e.shouldNegotiateApplicationKeyAgreement(),hydrateAdoptedConnectionApplicationCrypto:(t,n)=>e.hydrateAdoptedConnectionApplicationCrypto(t,n),sendTransportHandshake:(t,n,i,o)=>r.getHandshake().sendTransportHandshake(t,n,i,o),getConnectionControlFrameMode:t=>r.getHandshake().getConnectionControlFrameMode(t),reportApplicationRouteReady:(t,n)=>{let i=t.getTransportStatus();r.getHealth().handleCurrentConnectionApplicationRouteReady(t,{...i,reason:n});},applyConnectionTrustProjection:t=>e.applyConnectionTrustProjection(t),announceConnectionWhenStable:t=>e.announceConnectionWhenStable(t),isConnectionAnnounced:t=>e.isConnectionAnnounced(t),hasRustPeerLifecycleProjection:()=>e.hasRustPeerLifecycleProjection(),schedulePeerReconciliation:t=>e.schedulePeerReconciliation(t),maxRecoveryAttempts:15,attemptWaitMs:1e3,backoffMs:di})}function ms(r){let{host:e}=r;return new Ln({shouldNegotiateApplicationKeyAgreement:()=>e.shouldNegotiateApplicationKeyAgreement(),ensureConnectionKeyAgreementState:t=>e.ensureConnectionKeyAgreementState(t),isWebRTCTransportEnabled:()=>d$1(e.getOptions()),isWebRTCExternalCapabilityEnabled:()=>false,isIrohWebRTCCarrierEnabled:()=>r.getBrowserIrohWebRtcCarrier().isCarrierAvailable(),isMoQExternalCapabilityEnabled:()=>false,isIrohMoQCarrierEnabled:()=>r.getBrowserIrohWebRtcCarrier().isMoqCarrierAvailable(),observeIrohCarrierHandshake:(t,n,i)=>r.getBrowserIrohWebRtcCarrier().observeHandshake(t,n,i),isMoQReady:()=>e.isMoQReady(),isBleTransportEnabled:()=>ds(e.getOptions(),e.capabilities()),supportsScopedWebRtcSignalStream:()=>e.capabilities()?.adapter==="browser-wasm",getConnectionChannelId:t=>e.getConnectionChannelId(t),getPendingSessionToken:t=>e.getPendingSessionToken(t),getPendingSessionTokenPayload:t=>e.getPendingSessionTokenPayload(t),buildLocalTransportTrustPayload:(t,n)=>e.buildLocalTransportTrustPayload(t,n),requiresManagedTransportTrust:()=>e.requiresManagedTransportTrust(e.getDiscoveryMode()),initializeConnectionTrust:t=>e.initializeConnectionTrust(t),markConnectionApplicationCryptoRequired:t=>e.markConnectionApplicationCryptoRequired(t),getRTCConfig:()=>r.getRTCConfig(),getConnections:()=>e.getConnections(),usesTicketOnlySignalingMode:()=>e.usesTicketOnlySignalingMode(),isSessionTokenApproved:(t,n)=>e.isSessionTokenApproved(t,n),getLocalNodeId:()=>e.getLocalNodeId()||null,maxRecoveryAttempts:15,recoveryBackoffMs:di,registerDisposer:t=>e.registerDisposer(t)})}function fs(r){let{host:e}=r;return new Wn({getOptions:()=>e.getOptions(),getWasmClient:()=>e.getWasmClient(),getConnection:(t,n)=>e.getConnectionForPeer(t,n),getRTCConfig:()=>f(e.getOptions(),t=>c$1(t)),sendControl:(t,n)=>r.getHandshake().sendConnectionControlEnvelope(t,n,{preferNativeSignalRoute:true}),registerDisposer:t=>e.registerDisposer(t)})}function ys(r){return new _n(r.getContext(),{getRuntimeSafetyProfile:()=>r.getRuntimeSafetyProfile(),usesTicketOnlySignalingMode:()=>r.usesTicketOnlySignalingMode(),isTransportOnlyConnectionId:e=>r.isTransportOnlyConnectionId(e),notifyDisconnectRequested:e=>r.notifyDisconnectRequested(e),isConnected:e=>r.isBackendConnected(e),hasRustPeerLifecycleProjection:()=>r.hasRustPeerLifecycleProjection(),schedulePeerReconciliation:e=>r.schedulePeerReconciliation(e)})}function vs(r,e){return new xn({getOptions:()=>r.getOptions(),getRuntimeSafetyProfile:()=>r.getRuntimeSafetyProfile(),rankRoutes:(t,n)=>{let i=r.getWasmClient(),o=i?.rankRoutes??i?.rank_routes;if(typeof o!="function")return [...n];try{let s=o.call(i,t,n);return Array.isArray(s)?s:[...n]}catch(s){return c$1("[OpenRTC][route-policy] Rust ranking unavailable; preserving candidate order",{error:s instanceof Error?s.message:String(s)}),[...n]}},isMoQReady:()=>r.isMoQReady(),isMoQDataReady:t=>r.isMoQDataReady(t),isMoQApplicationRouteProven:t=>r.isMoQApplicationRouteProven(t),requestMoQApplicationRouteProof:t=>r.requestMoQApplicationRouteProof(t),clearMoQApplicationRouteProof:t=>r.clearMoQApplicationRouteProof(t),requestIrohCarrier:e,sendMoQ:(t,n,i)=>r.sendMoQData(t,n,i),sendIrohApplicationFrame:(t,n)=>r.sendIrohApplicationFrame(t,n)})}function Cs(r){return new En(r.getContext(),{getPeerState:e=>r.getPeerState(e),listPeerStates:()=>r.listPeerStates(),hasAnyIncomingChannelListeners:()=>r.hasAnyIncomingChannelListeners(),hasIncomingStreamListeners:()=>r.hasIncomingStreamListeners()})}function Is(r){return new Bi({getContext:()=>r.getClientContext(),getOptions:()=>r.options,getRuntimeSafetyProfile:()=>r.runtimeSafetyProfile,capabilities:()=>r.signalingBackendController.capabilities(),getWasmClient:()=>r.wasmClient,registerDisposer:e=>r.lifecycleScope.register(e),getLocalNodeId:()=>r.localNodeId,getDiscoveryMode:()=>r.discoveryMode,hasRustPeerLifecycleProjection:()=>r.hasRustPeerLifecycleProjection(),getPeerState:e=>r.peerServices.getPeerState(e),listPeerStates:()=>r.peerServices.listPeerStates(),getConnectionForPeer:(e,t)=>r.registry.getForPeer(e,t),getConnections:()=>r.registry.values(),getConnectionChannelId:e=>r.connectionChannelPolicy.getConnectionChannelId(e),isTransportOnlyConnectionId:e=>r.connectionChannelPolicy.isTransportOnlyConnectionId(e),getConnectionTrustState:e=>r.connectionTrust.getStateByConnectionId(e),buildLocalTransportTrustPayload:(e,t)=>r.connectionTrust.buildLocalTransportTrustPayload(e,t),initializeConnectionTrust:e=>r.connectionTrust.initialize(e),resolveApplicationCryptoForPeer:(e,t)=>r.applicationCrypto.resolveForPeer(e,t),resolveExistingApplicationCryptoForPeer:(e,t)=>r.securityServices.resolveExistingApplicationCryptoForPeer(e,t),getConfiguredApplicationCrypto:()=>r.options?.applicationCrypto,shouldNegotiateApplicationKeyAgreement:()=>r.applicationCrypto.shouldNegotiateKeyAgreement(),hydrateAdoptedConnectionApplicationCrypto:(e,t)=>r.applicationCrypto.hydrateAdoptedConnection(e,t),ensureConnectionKeyAgreementState:e=>r.applicationCrypto.ensureConnectionKeyAgreementState(e),markConnectionApplicationCryptoRequired:e=>r.applicationCrypto.markRequired(e),applyConnectionTrustProjection:e=>r.peerProjection.applyConnectionTrustProjection(e),announceConnectionWhenStable:e=>r.connectionLifecycle.announceConnectionWhenStable(e),isConnectionAnnounced:e=>r.connectionLifecycle.isConnectionAnnounced(e),schedulePeerReconciliation:e=>r.peerProjection.schedule(e),isMoQReady:()=>r.moqServices.isReady(),initMoQ:()=>r.moqServices.init(),isMoQDataReady:e=>r.moqServices.isDataReady(e),isMoQApplicationRouteProven:e=>r.moqServices.isApplicationRouteProven(e),requestMoQApplicationRouteProof:e=>r.moqServices.requestApplicationRouteProof(e),clearMoQApplicationRouteProof:e=>r.moqServices.clearApplicationRouteProof(e),sendMoQData:(e,t,n)=>r.moqServices.sendData(e,t,n),sendIrohApplicationFrame:(e,t)=>r.applicationStreams.sendFrame(e,t),getPendingSessionToken:e=>r.sessionTokens.getRouteRepairTokenForNode(e)??void 0,getPendingSessionTokenPayload:e=>r.sessionTokens.getRouteRepairTokenPayloadForNode(e)??void 0,requiresManagedTransportTrust:e=>r.runtimeStatus.requiresManagedTransportTrust(e??r.discoveryMode),isSessionTokenApproved:(e,t)=>r.sessionTokens.isApproved(e,t),usesTicketOnlySignalingMode:()=>r.runtimeStatus.usesTicketOnlySignalingMode(),notifyDisconnectRequested:e=>r.signalingBackendController.notifyDisconnectRequested(e),isBackendConnected:e=>r.signalingBackendController.isConnected(e),hasAnyIncomingChannelListeners:()=>r.incomingStreamRouter.hasAnyIncomingChannelListeners(),hasIncomingStreamListeners:()=>r.incomingStreamRouter.hasIncomingStreamListeners()})}var Bi=class{constructor(e){this.host=e;}get factoryHost(){return {host:this.host,getHandshake:()=>this.handshake,getHealth:()=>this.health,getRTCConfig:()=>this.getRTCConfig(),getBrowserIrohWebRtcCarrier:()=>this.browserIrohWebRtcCarrier}}get upgrade(){return this._upgrade??(this._upgrade=hs(this.factoryHost))}get handshake(){return this._handshake??(this._handshake=ms(this.factoryHost))}get health(){return this._health??(this._health=ys(this.host))}get contexts(){return this._contexts??(this._contexts=vs(this.host,e=>{let t=this.host.getConnectionForPeer(void 0,e);t&&this.browserIrohWebRtcCarrier.revisit(t).catch(n=>{c$1("[OpenRTC][Iroh carrier] admission revisit failed",{connectionId:t.id,error:n instanceof Error?n.message:String(n)});});}))}get peerIdentity(){return this._peerIdentity??(this._peerIdentity=Cs(this.host))}get browserIrohWebRtcCarrier(){return this._browserIrohWebRtcCarrier??(this._browserIrohWebRtcCarrier=fs(this.factoryHost))}retireBrowserIrohWebRtcCarrierConnection(e,t){let n=this._browserIrohWebRtcCarrier;n&&n.retireConnection(e,t).catch(i=>{c$1("[OpenRTC][Iroh WebRTC carrier] logical retirement failed",{connectionId:e,terminalReason:t??null,error:i instanceof Error?i.message:String(i)});});}getRTCConfig(){return e$2(this.host.getOptions(),e=>c$1(e))}hasApplicationRouteForConnectionSnapshot(e,t,n){return Mn(e,(i,o)=>this.host.getConfiguredApplicationCrypto()??this.host.resolveExistingApplicationCryptoForPeer(i,o),t,n)}hasApplicationRouteForPeer(e,t){return this.hasApplicationRouteForConnectionSnapshot(this.host.getConnectionForPeer(e,t),e,t)}isWebRtcReady(e){return xi(e)}hasApplicationRouteFailure(e){return this._upgrade?.hasFailure(e)??false}clearApplicationRouteFailure(e){this._upgrade?.clearFailure(e);}};var On=class{constructor(e){this.deps=e;this.channelIds=new Map;this.disposed=false;this.deps.registerDisposer(()=>this.dispose());}dispose(){this.disposed||(this.disposed=true,this.channelIds.clear());}isChannelPromotionEligible(e){let t=this.deps.getRegisteredChannel(e);return t?t.promotionPolicy!=="never":true}isTransportOnlyChannel(e){return zt(this.deps.getRegisteredChannel(e))}getConnectionChannelId(e){if(this.disposed)return null;let t=typeof e=="string"?e.trim():"";return t?this.channelIds.get(t)??null:null}isTransportOnlyConnectionId(e){return this.isTransportOnlyChannel(this.getConnectionChannelId(e))}allowsTransportOnlyStability(e){let t=this.getConnectionChannelId(e.id);return t?this.isTransportOnlyChannel(t):this.deps.usesTicketOnlySignalingMode()}resolvePromotionEligibility(e){if(this.disposed)return false;let t=this.getConnectionChannelId(e.connectionId);if(t)return this.isChannelPromotionEligible(t);let n=typeof e.nodeId=="string"?e.nodeId.trim():"";for(let i of this.deps.getConnections()){if(e.connectionId&&i.id===e.connectionId)return this.isChannelPromotionEligible(this.getConnectionChannelId(i.id));if(n&&i.remoteNodeId===n)return this.isChannelPromotionEligible(this.getConnectionChannelId(i.id))}return true}assign(e,t){if(this.disposed)return;let n=typeof t=="string"?t.trim():"";if(!n)return;this.channelIds.set(e.id,n);let i=this.deps.getConnectionTrustState(e.id);if(i&&!this.isChannelPromotionEligible(n)&&(i.required=false,i.verified=true,i.failed=false,i.failureReason=void 0,i.issuedChallenge=null,i.verifiedDeviceId||(i.verifiedDeviceId=i.expectedDeviceId||this.deps.getKnownDeviceIdByNodeId(e.remoteNodeId)||null)),this.deps.hasRustPeerLifecycleProjection())this.schedulePeerReconciliationBestEffort("session-token-trust-approved");else for(let o of this.deps.getConnections())if(o.id===e.id){this.deps.applyConnectionTrustProjection(o);break}}forget(e){if(this.disposed)return;let t=typeof e=="string"?e.trim():"";t&&this.channelIds.delete(t);}schedulePeerReconciliationBestEffort(e){if(!this.disposed)try{Promise.resolve(this.deps.schedulePeerReconciliation(e)).catch(()=>{});}catch{}}};var Un=class{constructor(e,t){this.ctx=e;this.deps=t;this.disposed=false;this.ctx.registerDisposer(()=>this.dispose());}dispose(){this.disposed=true;}bindConnectionDeviceIdInRust(e,t){if(this.disposed)return;let n=t.trim();if(!n)return;let i=this.deps.getSessionTokenApprovedScope(e.id);if(i&&!this.deps.sessionTokenScopeAllowsDeviceBinding(i)){c$1("[Client][BIND] skipped transient session device binding",{connectionId:e.id,remoteNodeId:e.remoteNodeId,scope:i});return}let o=this.ctx.wasmClient,s=!!o&&typeof o.bind_connection_device_id=="function";c$1("[Client][BIND] bindConnectionDeviceIdInRust entered",{connectionId:e.id,remoteNodeId:e.remoteNodeId,deviceId:n,hasWasmClient:!!o,hasMethod:s}),this.deps.rememberKnownDeviceForNode(e.remoteNodeId,n);let a=this.deps.getApplicationCryptoForConnectionOrPeer(e.id,e.remoteNodeId);if(a&&this.deps.indexApplicationCryptoForPeer(n,a),!!s)try{Promise.resolve(o.bind_connection_device_id(e.id,n)).then(()=>{this.disposed||c$1("[Client][BIND] bind_connection_device_id resolved",{connectionId:e.id,deviceId:n});}).catch(c=>{this.disposed||console.warn("[Client][TRUST] Failed to bind deviceId on Rust connection record",{connectionId:e.id,remoteNodeId:e.remoteNodeId,deviceId:n,error:c});});}catch(c){if(this.disposed)return;console.warn("[Client][TRUST] Failed to bind deviceId on Rust connection record",{connectionId:e.id,remoteNodeId:e.remoteNodeId,deviceId:n,error:c});}}async rejectConnectionInRust(e,t){if(this.disposed)return;let n=this.ctx.wasmClient;if(!(!n||typeof n.reject_connection_admission!="function"))try{await n.reject_connection_admission(e.id,t);}catch(i){if(this.disposed)return;console.warn("[Client][TRUST] Failed to reject connection on Rust admission authority",{connectionId:e.id,remoteNodeId:e.remoteNodeId,reason:t,error:i});}}retireSupersededConnections(e,t,n){if(this.disposed)return;let i=t.trim();if(i)for(let o of this.ctx.registry.values())o.id===e.id||o.isClosed||this.deps.getLogicalDeviceIdForConnection(o.id)===i&&(c$1("[Client][CONNECTION] Retiring superseded connection for logical device",{keptConnectionId:e.id,retiredConnectionId:o.id,logicalDeviceId:i,reason:n}),this.disconnectBestEffort(o));}disconnectBestEffort(e){try{Promise.resolve(e.disconnect()).catch(()=>{});}catch{}}};var Hn=class{constructor(e,t){this.ctx=e;this.deps=t;this.states=new Map;this.failureCooldowns=new Map;this.disposed=false;this.ctx.registerDisposer(()=>this.dispose());}dispose(){this.disposed||(this.disposed=true,this.states.clear(),this.failureCooldowns.clear());}initialize(e,t){if(this.disposed)return {required:false,verified:false,failed:true,failureReason:"connection-trust-manager-disposed",expectedDeviceId:t??null,verifiedDeviceId:null,issuedChallenge:null};let n=this.states.get(e.id);if(n)return t&&!n.expectedDeviceId&&(n.expectedDeviceId=t),n;let i=this.deps.resolvePromotionEligibility({connectionId:e.id,nodeId:e.remoteNodeId,deviceId:t??void 0}),o=this.deps.consumePendingSessionTokenTrustApproval(e.id),s=this.deps.getSessionTokenApprovedScope(e.id),a=o.scope??s,c=o.approved||!!s,d=this.deps.getKnownDeviceIdForNode(e.remoteNodeId),l=!c&&i&&this.deps.requiresManagedTransportTrust(),p={required:l,verified:!l,failed:false,expectedDeviceId:t||d||null,verifiedDeviceId:l?null:t||d||null,issuedChallenge:l?c$5():null};return this.states.set(e.id,p),a&&this.deps.addPeerScope(e.id,a),p}sessionTokenScopeAllowsDeviceBinding(e){let t=typeof e=="string"?e.trim():"";return t==="user-device"||t==="persistent"||t==="trusted-device"||t.startsWith("trusted-device:")}resolveExpectedDeviceIdForSessionTokenScope(e,t,n,i){let o=typeof e=="string"?e.trim():"";if(!o)return null;if(!n)return o;let s=new Set,a=c=>{let d=typeof c=="string"?c.trim():"";d&&s.add(d);};if(a(t),i){a(this.deps.getSessionTokenApprovedScope(i.id));for(let c of this.deps.getPeerScopes(i.id))a(c);for(let c of this.deps.getPeerScopes(i.remoteNodeId))a(c);}return Array.from(s).some(c=>this.sessionTokenScopeAllowsDeviceBinding(c))?o:null}getState(e){if(this.disposed)return null;let t=typeof e.connectionId=="string"?e.connectionId.trim():"";if(t)return this.states.get(t)??null;for(let[n,i]of this.states.entries())if(i.verifiedDeviceId&&(i.verifiedDeviceId===e.deviceId||i.verifiedDeviceId===e.deviceIdHint)||i.expectedDeviceId&&(i.expectedDeviceId===e.deviceId||i.expectedDeviceId===e.deviceIdHint))return this.states.get(n)??null;return null}getProjection(e){if(this.disposed)return null;let t=this.getState(e);if(!t)return null;let n=t.verified&&!t.failed,i=typeof e.connectionId=="string"&&e.connectionId.trim()||Array.from(this.states.entries()).find(([,a])=>a===t)?.[0]||"",o=i?this.deps.getSessionTokenApprovedScope(i):null,s=!o||this.sessionTokenScopeAllowsDeviceBinding(o);return n?{routable:true,protocolState:"routable",health:"healthy",deviceId:s?t.verifiedDeviceId??t.expectedDeviceId??e.deviceId??null:null}:t.required?{routable:false,protocolState:"unverified",health:t.failed?"stale":"unknown",error:t.failureReason??"trusted-device-proof-pending",deviceId:s?t.expectedDeviceId??e.deviceId??e.deviceIdHint??null:null}:null}async buildLocalTransportTrustPayload(e,t){if(this.disposed)return null;let n=await h$2().catch(()=>null),i=await this.deps.getLocalDeviceId().catch(()=>null)||this.ctx.deviceId||this.deps.getFallbackLocalDeviceId()||null;if(!n||!i)return null;let o=this.initialize(e),s={version:1,deviceId:i,identityFingerprint:n.fingerprint,challenge:o.issuedChallenge??void 0};if(t&&(s.signedChallenge=await n.signChallenge(t),s.signedChallengeFor=t,!await d$3(t,s.signedChallenge,e$3(n.publicKey))))throw new Error("local-transport-trust-signature-self-check-failed");return s}async verifyRemoteTransportTrust(e,t){if(this.disposed)return {verified:false,reason:"connection-trust-manager-disposed"};let n=this.initialize(e);if(!n.required)return {verified:true,deviceId:t?.deviceId??n.expectedDeviceId??null};if(!t)return {verified:false,reason:"missing-transport-trust-payload"};let i=typeof t.deviceId=="string"?t.deviceId.trim():"";if(!i)return {verified:false,reason:"missing-remote-device-id"};if(n.expectedDeviceId&&n.expectedDeviceId!==i)return {verified:false,reason:`expected-device-mismatch:${n.expectedDeviceId}:${i}`};let o=this.deps.getKnownDevice(i,e.remoteNodeId);if(!o){if(await this.deps.refreshKnownDeviceCache(),this.disposed)return {verified:false,reason:"connection-trust-manager-disposed"};o=this.deps.getKnownDevice(i,e.remoteNodeId);}if(!o)return {verified:false,reason:`unknown-trusted-device:${i}`};let s=f$1(o.metadata);if(!s)return {verified:false,reason:`missing-trusted-device-metadata:${i}`};if(t.identityFingerprint&&s.identityFingerprint!==t.identityFingerprint)return {verified:false,reason:`trusted-device-fingerprint-mismatch:${i}`};let a=n.issuedChallenge;return !a||!t.signedChallenge?{verified:false,reason:"missing-signed-transport-challenge"}:typeof t.signedChallengeFor!="string"?{verified:false,reason:"unbound-transport-trust-response"}:t.signedChallengeFor!==a?{verified:false,stale:true,reason:"stale-transport-trust-response"}:await d$3(a,t.signedChallenge,s.identityPublicKey)?{verified:true,deviceId:i}:{verified:false,reason:`invalid-transport-proof-bound:${i}`}}async enforceFailure(e,t){if(this.disposed)return;let n=this.initialize(e);n.failed=true,n.verified=false,n.failureReason=t,await this.deps.rejectConnectionInRust(e,t),!this.disposed&&(this.deps.applyConnectionTrustProjection(e),console.warn("[Client][TRUST] Disconnecting unverified connection",{connectionId:e.id,remoteNodeId:e.remoteNodeId,reason:t}),this.failureCooldowns.set(e.remoteNodeId,Date.now()),await Promise.allSettled([this.disconnectConnectionBestEffort(e),this.disconnectNodeBestEffort(e.remoteNodeId)]));}markVerified(e,t){if(this.disposed)return;this.failureCooldowns.delete(e.remoteNodeId);let n=this.deps.getSessionTokenApprovedScope(e.id),i=!n||this.sessionTokenScopeAllowsDeviceBinding(n),o=i?t:null,s=this.initialize(e,o);s.verified=true,s.failed=false,s.failureReason=void 0,i?(s.verifiedDeviceId=o||s.verifiedDeviceId||s.expectedDeviceId||null,o&&!s.expectedDeviceId&&(s.expectedDeviceId=o)):(s.verifiedDeviceId=null,s.expectedDeviceId=null),this.deps.applyConnectionTrustProjection(e);let a=s.verifiedDeviceId??s.expectedDeviceId??o??null;a&&(this.deps.bindConnectionDeviceIdInRust(e,a),this.deps.retireSupersededConnections(e,a,"trusted-device-replacement"));}clearForConnection(e){this.disposed||this.states.delete(e);}getStateByConnectionId(e){if(!this.disposed)return this.states.get(e)}getLogicalDeviceIdForConnection(e){let t=this.states.get(e);return t?.verifiedDeviceId??t?.expectedDeviceId??null}clearFailureCooldown(e){this.disposed||this.failureCooldowns.delete(e);}getFailureCooldown(e){if(!this.disposed)return this.failureCooldowns.get(e)}shouldSuppressConnectionRebuild(e,t,n,i=Date.now()){if(this.disposed)return {suppress:false,remainingMs:0};let o=this.failureCooldowns.get(e);return o===void 0||i-o>=t||n?{suppress:false,remainingMs:0}:{suppress:true,remainingMs:t-(i-o)}}logConnectionRebuildSuppressed(e,t){this.disposed||c$1("[Client][TRUST] Skipping connection rebuild for node in trust-failure cooldown",{remoteNodeId:e,cooldownRemainingMs:t});}disconnectConnectionBestEffort(e){try{return Promise.resolve(e.disconnect()).catch(()=>{})}catch{return Promise.resolve()}}disconnectNodeBestEffort(e){try{return Promise.resolve(this.deps.disconnectNode(e)).catch(()=>{})}catch{return Promise.resolve()}}};function Ss(r){return new Fi({getContext:()=>r.getClientContext(),getOptions:()=>r.options,getDeviceId:()=>r.deviceId,getDiscoveryMode:()=>r.discoveryMode,registerDisposer:e=>r.lifecycleScope.register(e),getRegisteredChannel:e=>r.incomingStreamRouter.getRegisteredChannel(e),getConnections:()=>r.registry.values(),requiresManagedTransportTrust:e=>r.runtimeStatus.requiresManagedTransportTrust(e??r.discoveryMode),consumePendingSessionTokenTrustApproval:e=>r.sessionTokens.consumePendingTrustApproval(e),getSessionTokenApprovedScope:e=>r.sessionTokens.getApprovedScope(e),addPeerScope:(e,t)=>r.peerServices.addPeerScope(e,t),getPeerScopes:e=>r.peerServices.getPeerScopes(e),getKnownDeviceIdForNode:e=>r.deviceDirectory.getKnownDeviceIdForNode(e),getKnownDevice:(e,t)=>r.deviceDirectory.getKnownDevice(e,t),refreshKnownDeviceCache:()=>r.deviceDirectory.refreshKnownDeviceCache(),getLocalDeviceId:()=>r.signalingBackendController.getLocalDeviceId(),applyConnectionTrustProjection:e=>r.peerProjection.applyConnectionTrustProjection(e),disconnectRuntimeNode:e=>r.runtimeConnections.disconnectNode(e),rememberKnownDeviceForNode:(e,t)=>r.deviceDirectory.rememberKnownDeviceForNode(e,t),getApplicationCryptoForConnectionOrPeer:(e,t)=>r.applicationCrypto.getForConnectionOrPeer(e,t),indexApplicationCryptoForPeer:(e,t)=>r.applicationCrypto.indexPeer(e,t),hasRustPeerLifecycleProjection:()=>r.hasRustPeerLifecycleProjection(),schedulePeerReconciliation:e=>r.peerProjection.schedule(e),usesTicketOnlySignalingMode:()=>r.runtimeStatus.usesTicketOnlySignalingMode()})}var Fi=class{constructor(e){this.host=e;}get trust(){return this._trust||(this._trust=new Hn(this.host.getContext(),{requiresManagedTransportTrust:()=>this.host.requiresManagedTransportTrust(this.host.getDiscoveryMode()),resolvePromotionEligibility:e=>this.channelPolicy.resolvePromotionEligibility(e),consumePendingSessionTokenTrustApproval:e=>this.host.consumePendingSessionTokenTrustApproval(e),getSessionTokenApprovedScope:e=>this.host.getSessionTokenApprovedScope(e),addPeerScope:(e,t)=>this.host.addPeerScope(e,t),getPeerScopes:e=>this.host.getPeerScopes(e),getKnownDeviceIdForNode:e=>this.host.getKnownDeviceIdForNode(e),getKnownDevice:(e,t)=>this.host.getKnownDevice(e,t),refreshKnownDeviceCache:()=>this.host.refreshKnownDeviceCache(),getLocalDeviceId:()=>this.host.getLocalDeviceId(),getFallbackLocalDeviceId:()=>this.host.getDeviceId()??this.host.getOptions()?.localDeviceId??null,applyConnectionTrustProjection:e=>this.host.applyConnectionTrustProjection(e),bindConnectionDeviceIdInRust:(e,t)=>this.deviceBinder.bindConnectionDeviceIdInRust(e,t),rejectConnectionInRust:(e,t)=>this.deviceBinder.rejectConnectionInRust(e,t),retireSupersededConnections:(e,t,n)=>this.deviceBinder.retireSupersededConnections(e,t,n),disconnectNode:e=>this.host.disconnectRuntimeNode(e)})),this._trust}get deviceBinder(){return this._deviceBinder||(this._deviceBinder=new Un(this.host.getContext(),{rememberKnownDeviceForNode:(e,t)=>this.host.rememberKnownDeviceForNode(e,t),getApplicationCryptoForConnectionOrPeer:(e,t)=>this.host.getApplicationCryptoForConnectionOrPeer(e,t),indexApplicationCryptoForPeer:(e,t)=>{this.host.indexApplicationCryptoForPeer(e,t);},getLogicalDeviceIdForConnection:e=>this.trust.getLogicalDeviceIdForConnection(e),getSessionTokenApprovedScope:e=>this.host.getSessionTokenApprovedScope(e),sessionTokenScopeAllowsDeviceBinding:e=>this.trust.sessionTokenScopeAllowsDeviceBinding(e)})),this._deviceBinder}get channelPolicy(){return this._channelPolicy||(this._channelPolicy=new On({registerDisposer:e=>this.host.registerDisposer(e),getRegisteredChannel:e=>this.host.getRegisteredChannel(e),getConnections:()=>this.host.getConnections(),getConnectionTrustState:e=>this.trust.getStateByConnectionId(e),getKnownDeviceIdByNodeId:e=>this.host.getKnownDeviceIdForNode(e),hasRustPeerLifecycleProjection:()=>this.host.hasRustPeerLifecycleProjection(),applyConnectionTrustProjection:e=>this.host.applyConnectionTrustProjection(e),schedulePeerReconciliation:e=>this.host.schedulePeerReconciliation(e),usesTicketOnlySignalingMode:()=>this.host.usesTicketOnlySignalingMode()})),this._channelPolicy}};var qn=class{constructor(e){this.host=e;this.kernelHandles=new Ft;this.lifecycleScope=new Wt;}get wasmClient(){return this.kernelHandles.wasmClient}set wasmClient(e){this.kernelHandles.wasmClient=e;}get node(){return this.kernelHandles.node}set node(e){this.kernelHandles.node=e;}get localNodeId(){return this.kernelHandles.localNodeId}set localNodeId(e){this.kernelHandles.localNodeId=e;}get deviceId(){return this.kernelHandles.deviceId}set deviceId(e){this.kernelHandles.deviceId=e;}get runtimeServices(){return this._runtimeServices??(this._runtimeServices=Yr(this))}get runtimeBootstrap(){return this.runtimeServices.bootstrap}get runtimeConnections(){return this.runtimeServices.connections}get managedTransportDialer(){return this.runtimeServices.managedDialer}get runtimeIdentity(){return this.runtimeServices.identity}get runtimeReadiness(){return this.runtimeServices.readiness}get runtimeStatus(){return this.runtimeServices.status}get connectionServices(){return this._connectionServices??(this._connectionServices=mr(this))}get moqServices(){return this._moqServices??(this._moqServices=Ir(this))}get transportServices(){return this._transportServices??(this._transportServices=Is(this))}get trustServices(){return this._trustServices??(this._trustServices=Ss(this))}get registry(){return this.connectionServices.registry}get connectionDialer(){return this.connectionServices.dialer}get connectionMessageHandler(){return this.connectionServices.messageHandler}get incomingConnectionAcceptor(){return this.connectionServices.incomingAcceptor}get appLifecycle(){return this.runtimeServices.appLifecycle}get roomClientHost(){return this._roomClientHost??(this._roomClientHost=Ur(this))}get accessServices(){return this._accessServices??(this._accessServices=Xo(this))}get auth(){return this.accessServices.auth}get signalingBackendController(){return this.accessServices.backend}get peerServices(){return this._peerServices??(this._peerServices=Or(this))}get peerProjection(){return this.peerServices.projection}get connectionLifecycle(){return this.connectionServices.lifecycle}get streamServices(){return this._streamServices??(this._streamServices=cs(this))}get incomingStreamRouter(){return this.streamServices.router}get incomingListen(){return this.streamServices.listen}get incomingDiagnostics(){return this.streamServices.diagnostics}get incomingStreamNormalizer(){return this.streamServices.normalizer}get applicationIncomingStreams(){return this.streamServices.applicationIncoming}get applicationStreams(){return this.streamServices.applicationStreams}get deviceDirectory(){return this.accessServices.devices}get connectionTrust(){return this.trustServices.trust}get connectionDeviceBinder(){return this.trustServices.deviceBinder}get connectionChannelPolicy(){return this.trustServices.channelPolicy}get nativeMainServices(){return this._nativeMainServices??(this._nativeMainServices=Rr(this))}get nativeMain(){return this.nativeMainServices.controller}get presence(){return this.accessServices.presence}retirePendingReciprocalAdmissionsIfExists(e){this._nativeMainServices?.controller.retirePendingReciprocalAdmissions(e);}get securityServices(){return this._securityServices??(this._securityServices=Jr(this))}get sessionTokens(){return this.securityServices.sessionTokens}get applicationCrypto(){return this.securityServices.applicationCrypto}get transportUpgrade(){return this.transportServices.upgrade}get transportHandshake(){return this.transportServices.handshake}get transportHealth(){return this.transportServices.health}get transportContexts(){return this.transportServices.contexts}get peerIdentity(){return this.transportServices.peerIdentity}get options(){return this.host.getOptions()}get runtimeSafetyProfile(){return this.host.getRuntimeSafetyProfile()}get discoveryMode(){return this.options.discoveryMode??"space"}get signaling(){return this.host.getSignaling()}get rooms(){return this.host.getRooms()}getRoomCreationMode(){return this.host.getRoomCreationMode()}getAppLimits(){return this.host.getAppLimits()}setSignaling(e){this.host.setSignaling(e);}setRooms(e){this.host.setRooms(e);}setAppLimits(e){this.host.setAppLimits(e);}setRoomCreationMode(e){this.host.setRoomCreationMode(e);}prepareStreamListenForSignOutIfExists(){this._streamServices?.prepareListenForSignOut();}getEffectiveRoomBackendTag(){return this.host.getEffectiveRoomBackendTag()}setEffectiveRoomBackendTag(e){this.host.setEffectiveRoomBackendTag(e);}getExistingPeerReconciliationStats(){return this._peerServices?.getProjectionStats()}hasRustPeerLifecycleProjection(){return wi(this.signaling,this.wasmClient)}getClientContext(){return this._clientContext||(this._clientContext=Qo({getRegistry:()=>this.registry,getWasmClient:()=>this.wasmClient,getNode:()=>this.node,getDiscoveryMode:()=>this.discoveryMode,getLocalNodeId:()=>this.localNodeId,getDeviceId:()=>this.deviceId,registerDisposer:e=>this.lifecycleScope.register(e)})),this._clientContext}getApplicationCrypto(e){return this.securityServices.getApplicationCrypto(e)}resolveApplicationCryptoForPeer(e,t){return this.securityServices.resolveApplicationCryptoForPeer(e,t)}clearApplicationCryptoForConnection(e){this._securityServices?.clearApplicationCryptoForConnection(e);}releaseApplicationKeyAgreementReply(e,t,n){this._securityServices?.releaseApplicationKeyAgreementReply(e,t,n);}waitForApplicationCryptoForPeer(e,t=0){return this.securityServices.waitForApplicationCryptoForPeer(e,t)}stopListenIfExists(){this._streamServices?.stopListenIfExists();}hasApplicationRouteForPeer(e,t){return this.transportServices.hasApplicationRouteForPeer(e,t)}ensureManagedApplicationRoute(e){return this.connectionServices.ensureManagedApplicationRoute(e)}};function Wi(){return new Proxy({},{get(){}})}function Oa(){let r=globalThis,e=r.process?.env;return e?.NODE_ENV==="test"||e?.VITEST==="true"||typeof e?.VITEST_WORKER_ID=="string"||typeof r.__vitest_worker__<"u"||typeof r.__vitest_index__<"u"}function k(r){return r.services}var bs={localNodeId:{get(){return k(this).localNodeId},set(r){k(this).localNodeId=r;}},deviceId:{get(){return k(this).deviceId},set(r){k(this).deviceId=r;}},registry:{get(){return k(this).registry}},__registry:{get(){return k(this).registry}},runtimeBootstrap:{get(){return k(this).runtimeBootstrap}},runtimeConnections:{get(){return k(this).runtimeConnections}},runtimeIdentity:{get(){return k(this).runtimeIdentity}},runtimeReadiness:{get(){return k(this).runtimeReadiness}},runtimeStatus:{get(){return k(this).runtimeStatus}},connectionDialer:{get(){return k(this).connectionDialer}},connectionMessageHandler:{get(){return k(this).connectionMessageHandler},set(r){k(this).connectionServices._messageHandler=r;}},connectionLifecycle:{get(){return k(this).connectionLifecycle}},transportUpgrade:{get(){return k(this).transportUpgrade}},transportHandshake:{get(){return k(this).transportHandshake}},transportHealth:{get(){return k(this).transportHealth}},transportContexts:{get(){return k(this).transportContexts}},peerIdentity:{get(){return k(this).peerIdentity}},peerProjection:{get(){return k(this).peerProjection}},peerLifecycle:{get(){return k(this).peerServices.store},set(r){k(this).peerServices.store=r;}},peerLifecycleClient:{get(){return k(this).peerServices.client}},connectionTrust:{get(){return k(this).connectionTrust}},connectionDeviceBinder:{get(){return k(this).connectionDeviceBinder}},connectionChannelPolicy:{get(){return k(this).connectionChannelPolicy}},incomingListen:{get(){return k(this).incomingListen}},incomingStreamRouter:{get(){return k(this).incomingStreamRouter}},incomingDiagnostics:{get(){return k(this).incomingDiagnostics}},incomingStreamNormalizer:{get(){return k(this).incomingStreamNormalizer}},applicationIncomingStreams:{get(){return k(this).applicationIncomingStreams}},applicationCrypto:{get(){return k(this).applicationCrypto}},sessionTokens:{get(){return k(this).sessionTokens}},nativeMain:{get(){return k(this).nativeMain}},auth:{get(){return k(this).auth}},deviceDirectory:{get(){return k(this).deviceDirectory}},presence:{get(){return k(this).presence}},appLifecycle:{get(){return k(this).appLifecycle}},moqController:{get(){return k(this).moqServices.controller}},_runtimeBootstrap:{get(){return k(this)._runtimeServices?._bootstrap}},_auth:{get(){return k(this)._accessServices?._auth}},_presence:{get(){return k(this)._accessServices?._presence}},_peerProjection:{get(){return k(this)._peerServices?._projection},set(r){k(this).peerServices._projection=r;}},_peerLifecycleClient:{get(){return k(this)._peerServices?._client}},_incomingListen:{get(){return k(this)._streamServices?._listen}},_connectionDialer:{get(){return k(this)._connectionServices?._dialer}},_connectionMessageHandler:{get(){return k(this)._connectionServices?._messageHandler},set(r){k(this).connectionServices._messageHandler=r;}},_transportUpgrade:{get(){return k(this)._transportServices?._upgrade}},_applicationCrypto:{get(){return k(this)._securityServices?._applicationCrypto},set(r){k(this).securityServices._applicationCrypto=r;}},_transportContexts:{set(r){k(this).transportServices._contexts=r;}}};function Ps(r){if(Oa()){for(let e of Object.values(bs))e.configurable=true;Object.defineProperties(r.prototype,bs);}}var tt=class{constructor(e){this.appLimits={...g$1};this.roomCreationMode="client-open";let t=o(e);this.options=t.options,this.runtimeSafetyProfile=Ye(this.options),this.effectiveRoomBackendTag=t.appTag,this.roomCreationMode=t.roomCreationMode,this.signaling=new Ce(p(t),Wi()),this._services=this.createServiceGraph(),this.rooms=new ke(this.services.roomClientHost,this.signaling),this.services.signalingBackendController;}get services(){return this._services??(this._services=this.createServiceGraph())}createServiceGraph(){let e=()=>({...this.options??{},apiKey:this.options?.apiKey??"test"});return new qn({getOptions:()=>this.options??e(),getRuntimeSafetyProfile:()=>this.runtimeSafetyProfile??Ye(e()),getSignaling:()=>this.signaling??(this.signaling=new Ce(p(e()),Wi())),setSignaling:t=>{this.signaling=t;},getRooms:()=>this.rooms,setRooms:t=>{this.rooms=t;},getAppLimits:()=>this.appLimits??(this.appLimits={...g$1}),setAppLimits:t=>{this.appLimits=t;},getRoomCreationMode:()=>this.roomCreationMode??"client-open",setRoomCreationMode:t=>{this.roomCreationMode=t;},getEffectiveRoomBackendTag:()=>this.effectiveRoomBackendTag??"openrtc",setEffectiveRoomBackendTag:t=>{this.effectiveRoomBackendTag=t;}})}get wasmClient(){return this.services.wasmClient}set wasmClient(e){this.services.wasmClient=e;}get node(){return this.services.node}set node(e){this.services.node=e;}attachIncomingStreamSource(e,t){this.services.wasmClient=e,this.services.localNodeId=t;}getApplicationCrypto(e){return this.services.getApplicationCrypto(e)}resolveApplicationCryptoForPeer(e,t){return this.services.resolveApplicationCryptoForPeer(e,t)}releaseApplicationKeyAgreementReply(e,t,n){this.services.releaseApplicationKeyAgreementReply(e,t,n);}waitForApplicationCryptoForPeer(e,t=1500){return this.services.waitForApplicationCryptoForPeer(e,t)}destroy(){this.services.lifecycleScope.destroy();}dispose(){this.destroy();}get apiKey(){return this.options.apiKey}get discoveryMode(){return this.options.discoveryMode??"space"}getRoomBackendTag(){return this.services.runtimeStatus.getRoomBackendTag()}async refreshHostedAppSettings(e=false){return this.services.signalingBackendController.refreshHostedAppSettings(e)}setSignalingBackend(e){this.services.signalingBackendController.setSignalingBackend(e);}get currentUser(){return this.services.signalingBackendController.getCurrentUser()??null}onAuthChange(e){return this.services.auth.onAuthChange(e)}async signInAnonymously(){return this.services.auth.signInAnonymously()}async signInWithPluto(){return this.services.auth.signInWithPluto()}async signOut(){return this.services.auth.signOut()}getSignalingTelemetry(){return this.services.runtimeStatus.getSignalingTelemetry()}reconciliationStats(){return this.services.runtimeStatus.reconciliationStats()}getProtocolCapabilities(){return this.services.runtimeStatus.getProtocolCapabilities()}async getRuntimeStatus(){return this.services.runtimeStatus.getRuntimeStatus()}async searchDevices(){return this.services.deviceDirectory.searchDevices()}async updateDevice(e,t){return this.services.deviceDirectory.updateDevice(e,t)}async deleteDevice(e){return this.services.deviceDirectory.deleteDevice(e)}async cleanupStaleDevices(){return this.services.deviceDirectory.cleanupStaleDevices()}onDevicesChange(e){return this.services.deviceDirectory.onDevicesChange(e)}async subscribeSessions(e,t){return this.services.deviceDirectory.subscribeSessions(e,t)}async startScanningLoop(e){return this.services.deviceDirectory.startScanningLoop(e)}async bootstrapRuntime(e){return this.services.runtimeBootstrap.bootstrapRuntime(e)}updateTransportConfig(e){q$1(this.options,e);}async init(){return this.services.runtimeBootstrap.init()}async ensureAuthenticated(e){return this.services.auth.ensureAuthenticated(e)}async refreshRuntimeAuthToken(e="runtime-start"){return this.services.auth.refreshRuntimeAuthToken(e)}get moqState(){return this.services.moqServices.state}get moq(){return this.services.moqServices.bundle}onMoQReady(e){return this.services.moqServices.onReady(e)}onMoQFailed(e){return this.services.moqServices.onFailed(e)}refreshTransportCapabilities(e="client-request"){return this.services.transportHandshake.broadcastTransportCapabilityUpdate(e)}onMoQObject(e){return this.services.moqServices.onObject(e)}subscribeMoQPeer(e){this.services.moqServices.enableForConnection(e);}subscribeMoQPeerNode(e,t){this.services.moqServices.subscribePeerNode(e,t);}async connect(e,t=2e4,n,i,o){return this.services.connectionDialer.connect(e,t,n,i,o)}async connectRaw(e,t=2e4){return this.services.runtimeConnections.connectRaw(e,t)}async startAutoConnect(e){return this.services.runtimeConnections.startAutoConnect(e)}async openBi(e){return this.services.applicationStreams.openBi(e)}async openUni(e){return this.services.applicationStreams.openUni(e)}getConnections(){return this.services.registry.all()}readyConnections(e={}){return this.services.registry.applicationReady(e)}getConnectionForPeer(e,t){return this.services.registry.getForPeer(e,t)}hasApplicationRouteForPeer(e,t){return this.services.hasApplicationRouteForPeer(e,t)}ensureManagedApplicationRoute(e){return this.services.ensureManagedApplicationRoute(e)}watchPeerStates(e){return this.services.peerServices.watchPeerStates(e)}getPeerState(e){return this.services.peerServices.getPeerState(e)}listConnectedPeers(){return this.services.peerServices.listConnectedPeers()}isPeerPromotionEligible(e){return this.services.peerServices.isPeerPromotionEligible(e)}addPeerScope(e,t="persistent"){return this.services.peerServices.addPeerScope(e,t)}releasePeerScope(e,t){return this.services.peerServices.releasePeerScope(e,t)}getPeerScopes(e){return this.services.peerServices.getPeerScopes(e)}isSamePeer(e,t){return this.services.peerServices.isSamePeer(e,t)}async refreshPeerSnapshot(){return this.services.peerProjection.schedule("refresh")}async connectPeer(e){return this.services.connectionDialer.connectPeer(e)}clearManualDisconnectProjection(e){this.services.peerServices.clearManualDisconnectProjection(e);}async disconnectPeer(e,t="persistent"){await this.services.peerServices.disconnectPeer(e,t);}async forceDisconnectPeer(e){await this.services.peerServices.forceDisconnectPeer(e);}async getPeerHealth(e){return this.services.peerServices.getPeerHealth(e)}async getTicket(){return this.services.runtimeIdentity.getTicket()}async getNodeId(){return this.services.runtimeIdentity.getNodeId()}async getNodeIdFromTicket(e){return this.services.runtimeIdentity.getNodeIdFromTicket(e)}async getTicketWithToken(e,t=0){return this.services.sessionTokens.getTicketWithToken(e,t)}buildCompoundTicketWithToken(e,t,n=0){return this.services.sessionTokens.buildCompoundTicketWithToken(e,t,n)}setManagedPresenceTicket(e){this.services.presence.setManagedPresenceTicket(e);}clearManagedPresenceTicket(){this.services.presence.clearManagedPresenceTicket();}registerSessionToken(e,t,n,i){this.services.sessionTokens.registerSessionToken(e,t,n,i);}revokeSessionToken(e){this.services.sessionTokens.revokeSessionToken(e);}async revokeTokensByScope(e){return this.services.sessionTokens.revokeTokensByScope(e)}async clearSessionTokens(){return this.services.sessionTokens.clearSessionTokens()}async startPresenceLoop(e){return this.services.presence.startPresenceLoop(e)}async setOffline(){return this.services.presence.setOffline()}async isConnected(e){return this.services.runtimeConnections.isConnected(e)}async disconnectNode(e){return this.services.runtimeConnections.disconnectNode(e)}async getLocalDeviceId(){return this.services.signalingBackendController.getLocalDeviceId()}async acceptNativeMessage(e,t,n){return this.services.nativeMain.acceptNativeMessage(e,t,n)}async startListening(e){return this.services.incomingListen.start(e)}stopListening(){this.services.stopListenIfExists();}forceReconnect(){this.services.signalingBackendController.forceReconnect();}wrapChannelWritable(e,t,n){return No(e,t,n)}async updatePresence(e=true,t=3e5,n,i){return this.services.presence.updatePresence(e,t,n,i)}onConnection(e){return this.services.connectionLifecycle.onConnection(e)}onDisconnection(e){return this.services.connectionLifecycle.onDisconnection(e)}onMessage(e){return this.services.incomingStreamRouter.onMessage(e)}onIncomingStream(e){return this.services.incomingStreamRouter.onIncomingStream(e)}registerChannel(e){this.services.incomingStreamRouter.registerChannel(e);}unregisterChannel(e){this.services.incomingStreamRouter.unregisterChannel(e);}listChannels(){return this.services.incomingStreamRouter.listChannels()}onChannelStream(e,t){return this.services.incomingStreamRouter.onChannelStream(e,t)}onRoomJoinRequest(e){return this.services.incomingStreamRouter.onRoomJoinRequest(e)}isMoQDataReady(e){return this.services.moqServices.isDataReady(e)}async sendMoQData(e,t,n={}){return this.services.moqServices.sendData(e,t,n)}};Ps(tt);var jn=class{constructor(e,t){this._disposed=false;this.cleanups=[];this.runtime=e,this.scope=t.scope,this.allowAllPeers=t.allowAllPeers??false,this.allowedPeerIds=new Set(t.allowPeers??[]);}get disposed(){return this._disposed}matchesPeer(e){if(this.allowAllPeers||e.scopes?.includes(this.scope))return true;if(this.allowedPeerIds.size>0){let t=[e.peerId,e.deviceId,e.deviceIdHint,e.connectionId];for(let n of t)if(n&&this.allowedPeerIds.has(n))return true}return false}matchesConnectionState(e){if(this.allowAllPeers)return true;let t=e.scopes;if(Array.isArray(t)&&t.includes(this.scope))return true;if(this.allowedPeerIds.size>0){let n=[e.connectionId,e.deviceId,e.deviceIdHint,e.remoteNodeId];for(let i of n)if(i&&this.allowedPeerIds.has(i))return true}return false}matchesStream(e){if(this.allowAllPeers)return true;let t=e.scopes;return !!(Array.isArray(t)&&t.includes(this.scope)||this.allowedPeerIds.size>0&&this.allowedPeerIds.has(e.remoteNodeId))}watchPeerStates(e){this.assertNotDisposed();let t=this.runtime.watchPeerStates(n=>{if(this._disposed)return;let i=this.allowAllPeers?n:n.filter(o=>this.matchesPeer(o));e(i);});return this.cleanups.push(t),t}onStateChange(e){this.assertNotDisposed();let t=o=>{this._disposed||this.matchesConnectionState(o)&&e(o);},n=this.runtime.onStateChange(t);return typeof n=="function"?(this.cleanups.push(n),n):n.then(o=>this._disposed?(o(),()=>{}):(this.cleanups.push(o),o))}listConnectedPeers(){this.assertNotDisposed();let e=this.runtime.listConnectedPeers();return this.allowAllPeers?e:e.filter(t=>this.matchesPeer(t))}async getPeerReadiness(e){return this.assertNotDisposed(),this.runtime.getPeerReadiness(e)}connectPeer(e){return this.assertNotDisposed(),this.runtime.connectPeer({...e,scope:e.scope??this.scope})}async disconnectPeer(e){return this.assertNotDisposed(),this.runtime.disconnectPeer(e,this.scope)}onIncomingStream(e){this.assertNotDisposed();let t=this.runtime.onIncomingStream(n=>{this._disposed||this.matchesStream(n)&&e(n);});return this.cleanups.push(t),t}dispose(){if(!this._disposed){this._disposed=true;for(let e of this.cleanups)try{e();}catch{}this.cleanups.length=0,this.releaseScopedPeersOnDispose();}}releaseScopedPeersOnDispose(){let e;try{e=this.runtime.listConnectedPeers();}catch{return}for(let t of e){if(!t.scopes?.includes(this.scope))continue;let n=t.peerId||t.connectionId||t.deviceId||t.deviceIdHint;n&&this.runtime.disconnectPeer(n,this.scope).catch(()=>{});}}assertNotDisposed(){if(this._disposed)throw new Error(`[Session] Session '${this.scope}' has been disposed.`)}};var nt=class nt{constructor(e){this.locallyDeletedDeviceIds=new Set;this.deviceStatusRefreshWakeups=new Set;this.client=e.client,this.backend=e.backend,this.peerApi=e.peerApi,this.connectToDevice=e.connectToDevice,this.startManagedReconciliation=e.startManagedReconciliation,this.deviceStatusRefreshDebounceMs=e.deviceStatusRefreshDebounceMs;}deviceStatusSnapshotKey(e){return JSON.stringify([...e].map(t=>({deviceId:t.deviceId,deviceName:t.deviceName??null,platformType:t.platformType??null,online:!!t.online,presenceStatus:t.presenceStatus??null,presenceUpdatedAt:t.presenceUpdatedAt??null,presenceExpiresAt:t.presenceExpiresAt??null,connectable:t.connectable??null,connectionStatus:t.connectionStatus??null,settledReady:!!t.settledReady,readinessState:t.readinessState??null,readinessReason:t.readinessReason??null,peerHealth:t.peerHealth??null,peerId:t.peerId??null,promotionEligible:t.promotionEligible??true,connectionId:t.connectionId??null,deviceIdHint:t.deviceIdHint??null,nodeId:t.nodeId??null,ticket:t.ticket??null,transportStableId:t.transportStableId??null,transportGeneration:t.transportGeneration??null,routeGeneration:t.routeGeneration??null,activeTransport:t.activeTransport??null,parallelTransport:t.parallelTransport??null,latencyMs:t.latencyMs??null,latencyByTransport:t.latencyByTransport??null,scopes:[...t.scopes??[]].sort()})).sort((t,n)=>t.deviceId.localeCompare(n.deviceId)))}normalizeLookupKey(e){return typeof e=="string"?e.trim().toLowerCase():""}isLocallyDeletedDevice(e){let t=this.normalizeLookupKey(e);return !!t&&this.locallyDeletedDeviceIds.has(t)}filterLocallyDeletedDevices(e){return (e??[]).filter(t=>!this.isLocallyDeletedDevice(t.deviceId))}isDurableUserDevicePeer(e){return (e.scopes??[]).some(t=>t==="user-device")}matchItem(e,t){let n=this.normalizeLookupKey(t.deviceId),i=this.normalizeLookupKey(t.nodeId),o=this.normalizeLookupKey(t.connectionId),s=new Set([n,this.normalizeLookupKey(t.deviceIdHint),i,o,this.normalizeLookupKey(t.peerId)].filter(Boolean)),a=null,c=null;for(let d of e){let l=this.normalizeLookupKey(d.deviceId),p=this.normalizeLookupKey(d.deviceIdHint),u=this.normalizeLookupKey(d.nodeId),h=this.normalizeLookupKey(d.peerId),m=this.normalizeLookupKey(d.activeConnectionId??d.connectionId);if(![l,p,u,h,m].filter(Boolean).some(L=>s.has(L))||i&&u&&u!==i)continue;let v=i&&u===i?5:n&&l===n?4:n&&h===n?3:n&&p===n?2:o&&m===o?1:0,y=String(d.status??"").trim().toLowerCase(),C=y==="closed"||y==="disconnected"||y==="failed",b=(d.settledReady===true||d.routable===true||String(d.readinessState??d.protocolState??"").trim().toLowerCase()==="routable")&&!C?4:y==="connected"&&d.health==="healthy"?3:!C&&y==="connected"?2:C?0:1,P=d.replacementPending===true?0:1,A=d.transportGeneration??d.generation??0,S=d.routeGeneration??0,D=d.lastSeenAtMs??d.lastAuthoritativeEventAt??0,_=[v,b,P,A,S,D],T=c,M=T===null;if(T){for(let L=0;L<_.length;L+=1)if(_[L]!==T[L]){M=_[L]>T[L];break}}M&&(a=d,c=_);}return a}peerIsCompatibleWithSession(e,t){let n=this.normalizeLookupKey(t.nodeId),i=this.normalizeLookupKey(e.nodeId);if(n&&i&&n!==i)return false;let o=this.normalizeLookupKey(t.activeConnectionId),s=[e.connectionId,...e.connectionIds??[]].map(a=>this.normalizeLookupKey(a)).filter(Boolean);return !(o&&s.length>0&&!s.includes(o))}shouldIgnoreTerminalPeerForRoutableSession(e,t){if(!e||!t)return false;let n=String(e.status??"").trim().toLowerCase(),i=n==="closed"||n==="disconnected"||n==="failed",o=t.settledReady===true||String(t.readinessState??"").trim().toLowerCase()==="routable",s=this.isManualDisconnectPeer(e);return i&&!s&&o&&!!t.activeConnectionId}applyCompatibleOptionalTransportFacet(e,t,n){if(!t||!this.isRoutableDeviceStatus(e)||n&&!this.peerIsCompatibleWithSession(t,n))return e;let i=String(t.status??"").trim().toLowerCase();if(!(t.routable===true||t.protocolState==="routable")||i==="closed"||i==="disconnected"||i==="failed"||t.transportGeneration!==void 0&&e.transportGeneration!==void 0&&t.transportGeneration!==e.transportGeneration||t.routeGeneration!==void 0&&e.routeGeneration!==void 0&&t.routeGeneration!==e.routeGeneration)return e;let s$1=p$1(t.activeTransport),a=p$1(t.parallelTransport),c=[s$1,a].find(s);if(!c)return e;let d=[e.activeTransport,e.parallelTransport,s$1,a].map(p$1).find(q$2),l=s$1===c;return {...e,activeTransport:l?c:d??c,parallelTransport:l?d??null:c}}latencyForTransport(e,t){let n=p$1(e);return n==="webrtc-lan"?t.webrtcLan??null:n==="webrtc-turn"?t.webrtcTurn??null:n==="webrtc"?t.webrtc??null:n==="iroh-lan"?t.irohLan??null:n==="iroh-relay"?t.irohRelay??null:n==="iroh-webrtc"?t.irohWebrtc??null:n==="iroh-moq"?t.irohMoq??null:n==="iroh"||n==="iroh-quic"?t.iroh??null:n==="ble"?t.ble??null:n==="moq"?t.moq??null:null}applyLocalTransportLatency(e){if(!this.isRoutableDeviceStatus(e))return {...e,latencyMs:null,latencyByTransport:void 0};let t=this.client.getConnectionForPeer,i=(typeof t=="function"?t.call(this.client,e.connectionId,e.nodeId??e.peerId):null)?.getLatencySnapshot()??{},o={...e.latencyByTransport??{},...Object.fromEntries(Object.entries(i).filter(([,d])=>d!=null))},s=Object.values(o).some(d=>d!=null)?o:void 0,c=(s?this.latencyForTransport(e.activeTransport,s)??this.latencyForTransport(e.parallelTransport,s):null)??e.latencyMs??null;return {...e,latencyMs:c,latencyByTransport:s}}isManualDisconnectPeer(e){let t=String(e?.error??"").trim().toLowerCase();return t.includes("manual disconnect")||e?.manualDisconnect===true&&t.length>0}buildFinalDeviceStatusSnapshots(e,t,n,i={}){let o=this.filterLocallyDeletedDevices(e).map(c=>{let d=this.matchItem(t,c),l=this.matchItem(n,c),p=(c.connectionStatus==="closed"||c.connectionStatus==="disconnected"||c.connectionStatus==="failed")&&String(c.readinessReason??"").trim().toLowerCase().includes("manual disconnect"),u=d?.settledReady===true||String(d?.readinessState??"").trim().toLowerCase()==="routable",h=this.isManualDisconnectPeer(l)&&!this.isRoutableDeviceStatus(c)&&!u,m=p||h,f=k$1({device:c,session:m?null:d,peer:h?l:null,isPromotionEligible:v=>this.client.isPeerPromotionEligible(v)});return m?f:this.applyCompatibleOptionalTransportFacet(f,l,d)}),s=new Set(o.map(c=>this.normalizeLookupKey(c.deviceId))),a=new Set(o.flatMap(c=>[c.deviceId,c.deviceIdHint,c.nodeId,c.peerId,c.connectionId].map(d=>this.normalizeLookupKey(d)).filter(Boolean)));for(let c of n){if(!this.isDurableUserDevicePeer(c))continue;let d=this.statusDeviceFromPeer(c),l=this.normalizeLookupKey(d?.deviceId),p=[c.deviceId,c.deviceIdHint,c.nodeId,c.peerId,c.connectionId].map(u=>this.normalizeLookupKey(u)).filter(Boolean);if(!(!d||!l||s.has(l)||p.some(u=>a.has(u))||this.isLocallyDeletedDevice(l))){s.add(l);for(let u of p)a.add(u);o.push(k$1({device:d,session:this.matchItem(t,d),peer:c,isPromotionEligible:u=>this.client.isPeerPromotionEligible(u)}));}}return o.map(c=>this.applyLocalTransportLatency(c))}applyTerminalPeerTransportState(e,t){if(this.isRoutableDeviceStatus(e))return e;let n=String(t?.status??"").trim().toLowerCase();return n!=="closed"&&n!=="disconnected"&&n!=="failed"?e:{...e,transportStableId:null,activeTransport:void 0,parallelTransport:void 0}}statusDeviceFromPeer(e){let t=e.deviceId?.trim()||e.deviceIdHint?.trim(),n=String(e.status??"").trim().toLowerCase();return !t||n==="closed"||n==="disconnected"||n==="failed"?null:{deviceId:t,deviceName:e.deviceName?.trim()||"Unknown Device",online:e.online??true,ticket:e.ticket??"",nodeId:e.nodeId,platformType:e.platformType,presenceStatus:e.online===false?"offline":"online",connectable:!!e.ticket,connectionStatus:e.status,settledReady:e.routable===true||e.protocolState==="routable",readinessState:e.protocolState,peerHealth:e.health,peerId:e.peerId,scopes:[...e.scopes??[]],connectionId:e.connectionId,deviceIdHint:e.deviceIdHint,transportStableId:e.transportStableId,transportGeneration:e.transportGeneration,routeGeneration:e.routeGeneration,activeTransport:e.activeTransport,parallelTransport:e.parallelTransport}}runtimeDeviceToStatusSnapshot(e){return k$1({device:e})}isRoutableDeviceStatus(e){return e.settledReady===true||String(e.readinessState??"").trim().toLowerCase()==="routable"}mergeWatchedDevicesIntoStatusSnapshots(e,t){if(!e)return t;let n=new Map(t.map(c=>[c.deviceId,c])),i=this.filterLocallyDeletedDevices(e),o=new Set(i.map(c=>this.normalizeLookupKey(c.deviceId))),s=this.filterLocallyDeletedDevices(t.filter(c=>!o.has(this.normalizeLookupKey(c.deviceId))));return [...i.map(c=>{let d=this.runtimeDeviceToStatusSnapshot(c),l=n.get(c.deviceId);if(!l)return d;let{connectionStatus:p,settledReady:u,readinessState:h,readinessReason:m,peerHealth:f,peerId:v,promotionEligible:y,connectionId:C,transportStableId:I,transportGeneration:b,routeGeneration:P,activeTransport:A,parallelTransport:S,presenceStatus:D,presenceUpdatedAt:_,presenceExpiresAt:T,connectable:M,...L}=l,{connectionStatus:W,settledReady:X,readinessState:he,readinessReason:be,peerHealth:Be,peerId:Qn,promotionEligible:it,connectionId:Vn,transportStableId:Fe,transportGeneration:$n,routeGeneration:We,activeTransport:Yn,parallelTransport:Jn,presenceStatus:Pe,presenceUpdatedAt:Oe,presenceExpiresAt:ot,connectable:Xn,latencyMs:R,latencyByTransport:E,deviceIdHint:F,scopes:B,...G}=d,Re=l.presenceUpdatedAt,te=Oe,Zn=te!==void 0&&Re!==void 0&&te===Re&&Pe==="online"&&l.presenceStatus!=="online",me=Pe!==void 0&&te!==void 0&&(Re===void 0||te>Re||Zn);return k$1({device:{...L,...G,connectionStatus:l.connectionStatus,settledReady:l.settledReady,readinessState:l.readinessState,readinessReason:l.readinessReason,peerHealth:l.peerHealth,peerId:l.peerId,promotionEligible:l.promotionEligible,connectionId:l.connectionId,transportStableId:l.transportStableId,transportGeneration:l.transportGeneration,routeGeneration:l.routeGeneration,activeTransport:l.activeTransport,parallelTransport:l.parallelTransport,latencyMs:l.latencyMs,latencyByTransport:l.latencyByTransport,online:me?d.online:l.online,presenceStatus:me?Pe:l.presenceStatus,presenceUpdatedAt:me?Oe:l.presenceUpdatedAt,presenceExpiresAt:me?ot:l.presenceExpiresAt,connectable:me?Xn:l.connectable,platformType:l.platformType??d.platformType,deviceIdHint:F??l.deviceIdHint,scopes:l.scopes}})}),...s]}async listDevices(){return this.filterLocallyDeletedDevices(await this.client.searchDevices())}async listDeviceStatus(){let e=this.backend;if(e&&typeof e.listDeviceStatus=="function"){let t$1=await e.listDeviceStatus(),[n,i]=await Promise.allSettled([typeof e.listPeerSessions=="function"?e.listPeerSessions():Promise.resolve([]),this.peerApi.refreshPeerSnapshot().catch(d=>{let l=this.peerApi.listConnectedPeers();return console.warn(`[RuntimeClient] refreshPeerSnapshot failed during listDeviceStatus(); using ${l.length} cached connected peers`,d),l})]),o=n.status==="fulfilled"?n.value:[],s=i.status==="fulfilled"?i.value:[],a=this.filterLocallyDeletedDevices(this.buildFinalDeviceStatusSnapshots(t$1,o,s,{preserveRoutableInputLifecycle:true}));return (a.some(d=>t(d.activeTransport))||o.some(d=>t(d.activeTransport))||s.some(d=>t(d.activeTransport)))&&b("[RuntimeClient] device status snapshot with transport labels",{devices:a.map(d=>({deviceId:d.deviceId,connectionStatus:d.connectionStatus,settledReady:!!d.settledReady,activeTransport:d.activeTransport??null,parallelTransport:d.parallelTransport??null,connectionId:d.connectionId??null})),peerSessions:o.map(d=>({peerId:d.peerId,deviceId:d.deviceId??null,activeConnectionId:d.activeConnectionId??null,status:d.status,activeTransport:d.activeTransport??null,parallelTransport:d.parallelTransport??null})),peers:s.map(d=>({peerId:d.peerId,deviceId:d.deviceId??null,connectionId:d.connectionId??null,status:d.status,activeTransport:d.activeTransport??null,parallelTransport:d.parallelTransport??null}))}),a}throw new Error("[pluto-rtc] listDeviceStatus() requires a Rust-backed runtime adapter that implements listDeviceStatus().")}async updateDevice(e,t){await this.client.updateDevice(e,t);}async deleteDevice(e){let t=this.normalizeLookupKey(e);await this.client.deleteDevice(e),t&&this.locallyDeletedDeviceIds.add(t);}watchDevices(e){return this.client.onDevicesChange(t=>e(this.filterLocallyDeletedDevices(t)))}watchDeviceStatus(e){let t=this.backend;if(!t||typeof t.listDeviceStatus!="function")throw new Error("[pluto-rtc] watchDeviceStatus() requires a Rust-backed runtime adapter that implements listDeviceStatus().");let n=true,i=null,o=null,s=null,a=null,c=false,d=false,l=I=>{let b=this.filterLocallyDeletedDevices(I);u(b);let P=this.deviceStatusSnapshotKey(b);P!==i&&(i=P,e(b));},p=()=>{a&&(clearTimeout(a),a=null);},u=I=>{if(p(),!n)return;let b=Date.now(),P=I.filter(S=>S.presenceStatus==="online").map(S=>typeof S.presenceUpdatedAt=="number"?S.presenceUpdatedAt+3e5:null).filter(S=>typeof S=="number"&&Number.isFinite(S)).sort((S,D)=>S-D)[0];if(P===void 0)return;let A=Math.max(25,P-b+5);a=setTimeout(()=>{a=null,f();},A);},h=()=>{c=false,!(!n||!d)&&(d=false,f());},m=()=>{if(n){if(c){d=true;return}c=true,this.listDeviceStatus().then(I=>{n&&l(this.mergeWatchedDevicesIntoStatusSnapshots(o,I));}).catch(I=>{console.warn("[RuntimeDeviceManager] device-status refresh failed",I);}).finally(()=>h());}},f=()=>{!n||s||(s=setTimeout(()=>{s=null,m();},this.deviceStatusRefreshDebounceMs));};this.deviceStatusRefreshWakeups.add(f);let v=this.client.onDevicesChange(I=>{Array.isArray(I)&&(o=this.filterLocallyDeletedDevices(I)),f();}),y=this.peerApi.watchPeerStates(()=>{f();}),C=this.startManagedReconciliation(()=>f());return m(),()=>{n=false,s&&clearTimeout(s),p(),this.deviceStatusRefreshWakeups.delete(f),C(),v(),y();}}notifyLifecycleMutation(){for(let e of this.deviceStatusRefreshWakeups)e();}async connectWithRetry(e,t,n){return this.connectDevice(e,{localDeviceId:n.localDeviceId,targetUserId:n.targetUserId,onConnected:t.onConnected})}async connectDevice(e,t){let n=e,i=typeof e.ticket=="string"?e.ticket.trim():"";if(!i){let u=(await this.listDeviceStatus().catch(()=>this.listDevices().catch(()=>[]))).find(h=>h.deviceId===e.deviceId);u&&(n={...e,...u},i=typeof u.ticket=="string"?u.ticket.trim():"");}if(!i){let p=`Cannot connect to ${e.deviceId}: missing endpoint ticket`,u=c$3(p);return {success:false,error:p,errorCode:u.errorCode,retryable:u.retryable,errorPlane:u.errorPlane,attempts:1}}let o=this.peerApi.getPeerState(e.deviceId),s=o?.status,a=this.client.hasApplicationRouteForPeer?.(o?.connectionId??void 0)??false;if(s==="connected"&&a)return {success:true,skipped:"already-connecting",attempts:0};this.client.clearManualDisconnectProjection?.(n.deviceId);let c=this.backend;await c.excludeAutoConnect?.(n.deviceId,false);let d=Date.now(),l=()=>Math.max(1,nt.EXPLICIT_CONNECT_SETTLE_TIMEOUT_MS-(Date.now()-d));try{let p=await this.connectToDevice({deviceId:n.deviceId,endpointTicket:i,timeoutMs:nt.EXPLICIT_CONNECT_SETTLE_TIMEOUT_MS});if(c&&typeof c.waitForSettledPeer=="function"){let u=l();if(!(await c.waitForSettledPeer(p.deviceId??n.deviceId??p.remoteNodeId??p.connectionId,u))?.settledReady)throw new Error(`Connection to ${n.deviceId} did not become application-routable`)}return await this.peerApi.refreshPeerSnapshot().catch(()=>{}),this.notifyLifecycleMutation(),await t.onConnected?.(n),{success:!0,attempts:1}}catch(p){let u=p instanceof Error?p.message:`Cannot connect to ${e.deviceId}`,h=e$1(p);return {success:false,error:u,errorCode:h.code,retryable:h.retryable,errorPlane:h.plane,attempts:1}}}};nt.EXPLICIT_CONNECT_SETTLE_TIMEOUT_MS=3e4;var Gn=nt;var Kn=class{constructor(e,t){this.client=e;this.backend=t;}normalizeUiConnectionStatus(e){switch((e||"disconnected").trim().toLowerCase()){case "connected":return "connected";case "connecting":return "connecting";case "failed":return "failed";default:return "disconnected"}}buildLookup(e,t){let n=new Map,i=(o,s)=>{let a=typeof o=="string"?o.trim():"";!a||n.has(a)||n.set(a,s);};for(let o of e)for(let s of t(o))i(s,o);return n}uniqueLookupIds(...e){let t=new Set,n=[];for(let i of e){let o=typeof i=="string"?i.trim():"";!o||t.has(o)||(t.add(o),n.push(o));}return n}matchSessionByLookupId(e,t){if(!e.length||!t.length)return null;let n=this.buildLookup(e,i=>[i.peerId,i.deviceId,i.deviceIdHint,i.nodeId,i.activeConnectionId]);for(let i of t){let o=n.get(i);if(o)return o}return null}matchLocalPeerState(e,t){let n=this.uniqueLookupIds(...e,t.peerId,t.deviceId,t.deviceIdHint,t.nodeId,t.activeConnectionId);for(let o of n){let s=this.client.getPeerState(o);if(s)return s}let i=this.buildLookup(this.client.listConnectedPeers(),o=>[o.peerId,o.deviceId,o.deviceIdHint,o.nodeId,o.connectionId,...o.connectionIds??[]]);for(let o of n){let s=i.get(o);if(s)return s}return null}async resolvePeerLookupIds(e,t){let n=typeof t.resolvePeerIdentity=="function"?await t.resolvePeerIdentity(e).catch(()=>null):null,i=this.uniqueLookupIds(e,n?.peerId,n?.deviceId,n?.deviceIdHint,n?.nodeId);if(typeof t.listPeerSessions!="function")return i;let o=this.matchSessionByLookupId(await t.listPeerSessions().catch(()=>[]),i);return this.uniqueLookupIds(...i,o?.peerId,o?.deviceId,o?.deviceIdHint,o?.nodeId,o?.activeConnectionId)}async resolvePeerRecords(e){let t=this.backend;if(!t||typeof t.resolvePeerRecords!="function")throw new Error("[pluto-rtc] resolvePeerRecords() requires a Rust-backed runtime adapter that implements resolvePeerRecords().");return t.resolvePeerRecords(e)}async getPeerSession(e){let t=this.backend;if(!t||typeof t.getPeerSession!="function")throw new Error("[pluto-rtc] getPeerSession() requires a Rust-backed runtime adapter that implements getPeerSession().");let n=await this.resolvePeerLookupIds(e,t);for(let i of n){let o=await t.getPeerSession(i);if(o)return o}return typeof t.listPeerSessions=="function"?this.matchSessionByLookupId(await t.listPeerSessions(),n):null}async listPeerSessions(){let e=this.backend;if(!e||typeof e.listPeerSessions!="function")throw new Error("[pluto-rtc] listPeerSessions() requires a Rust-backed runtime adapter that implements listPeerSessions().");return e.listPeerSessions()}async waitForConnectedPeer(e,t){let n=this.backend;if(!n||typeof n.waitForSettledPeer!="function")throw new Error("[pluto-rtc] waitForConnectedPeer() requires a Rust-backed runtime adapter that implements waitForSettledPeer().");let i=typeof n.resolvePeerIdentity=="function"?await n.resolvePeerIdentity(e).catch(()=>null):null,o=this.uniqueLookupIds(i?.peerId,i?.deviceId,i?.deviceIdHint,i?.nodeId,e),s=o[0]??e,a=Date.now(),c=await n.waitForSettledPeer(s,t);if(!c?.settledReady)return c;let d=typeof t=="number"?Math.max(0,t):5e3;for(;;){let l=this.matchLocalPeerState(o,c);if(!l||l.routable===true||l.protocolState==="routable")return c;if(Date.now()-a>=d)return {...c,settledReady:false,readinessState:l.protocolState??"transport-only",readinessReason:l.error??"application-route-not-ready"};await new Promise(p=>setTimeout(p,50));}}async getPeerReadiness(e,t){let n=this.client.getPeerState(e)??null,i=typeof t=="number"?await this.waitForConnectedPeer(e,t).catch(()=>null):await this.getPeerSession(e).catch(()=>null),o=this.normalizeUiConnectionStatus(i?.status??n?.status??"disconnected"),s=n?.routable===false&&n?.protocolState==="unverified";return {requestedId:e,connected:o==="connected",settledReady:s?false:!!i?.settledReady,status:o,health:i?.health??n?.health??"unknown",deviceId:i?.deviceId??n?.deviceId??null,deviceIdHint:i?.deviceIdHint??n?.deviceIdHint??null,activeConnectionId:i?.activeConnectionId??n?.connectionId??null,readinessState:s?n?.protocolState:i?.readinessState??n?.protocolState,readinessReason:s?n?.error:i?.readinessReason??n?.error,scopes:[...i?.scopes??n?.scopes??[]]}}async resolvePeerIdentity(e){let t=this.backend;if(!t||typeof t.resolvePeerIdentity!="function")throw new Error("[pluto-rtc] resolvePeerIdentity() requires a Rust-backed runtime adapter that implements resolvePeerIdentity().");return t.resolvePeerIdentity(e)}async resolveStreamPeer(e){return this.resolvePeerIdentity(e)}addPeerScope(e,t){return this.client.addPeerScope(e,t)}releasePeerScope(e,t){return this.client.releasePeerScope(e,t)}getPeerScopes(e){return this.client.getPeerScopes(e)}isSamePeer(e,t){return this.client.isSamePeer(e,t)}};var As="drive-view.",Oi=[68,86,67,72],Ua=new TextDecoder;function Ui(r){if(r.byteLength>=Oi.length){let e=true;for(let t=0;t<Oi.length;t+=1)if(r[t]!==Oi[t]){e=false;break}if(e)return true}try{let e=JSON.parse(Ua.decode(r));return typeof e.t=="string"&&e.t.startsWith(As)}catch{return false}}function Rs(r){return !!r&&!r.isClosed&&typeof r.send=="function"&&(typeof r.isPayloadReady!="function"||r.isPayloadReady())}var Ts=new WeakMap;function Ha(r){if(r instanceof Uint8Array)return Ui(r)?r:null;if(r instanceof ArrayBuffer){let e=new Uint8Array(r);return Ui(e)?e:null}return r&&typeof r=="object"&&typeof r.t=="string"&&r.t.startsWith(As)?new TextEncoder().encode(JSON.stringify(r)):null}function qa(r,e){let t=Ts.get(r);if(!t){t={receivers:new Set([e])},Ts.set(r,t);let n=i=>{let o=false;for(let s of [...t.receivers])try{o=s(i)||o;}catch(a){c$1("[RuntimeClient][connectScopedChannel] route-scoped receiver failed",{connectionId:r.id,error:String(a)});}return o};return typeof r.onWebRTCBinaryMessage=="function"&&r.onWebRTCBinaryMessage(i=>n(i)),typeof r.onMessage=="function"&&r.onMessage(i=>{let o=Ha(i);o&&n(o);}),()=>t?.receivers.delete(e)}return t.receivers.add(e),()=>t?.receivers.delete(e)}var U=class U{constructor(e,t){this.managedSessionKey=null;this.managedSessionUserId=null;this.managedSessionOptions=null;this.managedSessionTransition=Promise.resolve();this.managedSessionStartInFlight=new Map;this.terminalShutdown=null;this.managedReconciliationTasks=new Set;this.managedReconciliationFollowupTimers=new Set;this.scopedConnectionActorRegistry=null;this.client=new tt(e),this.backend=t??null,this.nativeStreamConsumer=e.nativeStreamConsumer??"runtime",t&&this.client.setSignalingBackend(t),this.peerManager=new Kn(this.client,this.backend),this.connectionController=new yt(this.client,this.backend,()=>this.deviceManager.notifyLifecycleMutation()),this.deviceManager=new Gn({client:this.client,backend:this.backend,peerApi:{watchPeerStates:n=>this.client.watchPeerStates(n),refreshPeerSnapshot:()=>this.client.refreshPeerSnapshot(),listConnectedPeers:()=>this.client.listConnectedPeers(),getPeerState:n=>this.client.getPeerState(n)},connectToDevice:n=>this.connectionController.connectToDevice(n),startManagedReconciliation:n=>this.startManagedReconciliation(n),deviceStatusRefreshDebounceMs:U.DEVICE_STATUS_REFRESH_DEBOUNCE_MS});}static describeTicketForLogs(e){let t=typeof e=="string"?e.trim():"";if(!t)return {hasTicket:false,isCompound:false,scope:null};let n=t.indexOf(".");if(n<0)return {hasTicket:true,isCompound:false,scope:null};try{let i=t.slice(n+1).replace(/-/g,"+").replace(/_/g,"/"),o=(4-i.length%4)%4,s=JSON.parse(atob(i+"=".repeat(o)));return {hasTicket:!0,isCompound:!0,scope:typeof s?.s=="string"?s.s:null}}catch{return {hasTicket:true,isCompound:true,scope:null}}}async serializeManagedSessionOperation(e,t){let n=Date.now(),i=this.managedSessionTransition,o,s=new Promise(c=>{o=c;});this.managedSessionTransition=s,console.info("[RuntimeClient][managed-session][operation-queued]",{label:e,managedSessionUserId:this.managedSessionUserId,hasManagedSession:this.managedSessionKey!==null}),await i.catch(()=>{});let a=Date.now();console.info("[RuntimeClient][managed-session][operation-started]",{label:e,queueWaitMs:a-n,managedSessionUserId:this.managedSessionUserId,hasManagedSession:this.managedSessionKey!==null});try{return await t()}finally{console.info("[RuntimeClient][managed-session][operation-finished]",{label:e,queueWaitMs:a-n,operationMs:Date.now()-a,managedSessionUserId:this.managedSessionUserId,hasManagedSession:this.managedSessionKey!==null}),o(),this.managedSessionTransition===s&&(this.managedSessionTransition=Promise.resolve());}}get identity(){return this.client.currentUser}resolveManagedSessionUserId(e,t){let n=this.identity?.id??null;return n?(t&&t!==n&&console.warn("[RuntimeClient][managed-session][user-id-override]",{requestedUserId:t,runtimeIdentityUserId:n}),n):t??null}resolveManagedAutoConnectEnabled(e){return e.autoConnectPolicy==="disabled"?false:e.autoConnectPolicy==="enabled"?true:e.autoConnectPolicy==="scoped-only"?false:e.autoConnect!==false}resolveManagedPresenceEnabled(e){return e.presencePolicy==="disabled"?false:e.presencePolicy==="online"?true:e.presence!==false}getEffectiveRuntimeUserId(){return this.identity?.id??this.managedSessionUserId??this.managedSessionOptions?.userId??null}async fetchAndApplyAppLimits(){try{await this.client.refreshHostedAppSettings();}catch(e){console.warn("[pluto-rtc] Could not fetch app limits, using technical safety defaults.",e);}}async resolvePeerStreamTarget(e){let t=this.client.getPeerState(e)??null,n=await this.getPeerSession(e).catch(()=>null),i=n?.activeConnectionId?.trim()||null,o=(i?this.client.getConnections().find(a=>!a.isClosed&&a.id===i):void 0)??null,s=n?.nodeId?.trim()||o?.remoteNodeId?.trim()||t?.nodeId?.trim()||null;return {peer:t,session:n,connection:o,remoteNodeId:s}}compatPeerConnectionFromTarget(e,t){let n=e.session?.activeConnectionId?.trim()||`peer-stream:${t}`,i=e.remoteNodeId||t;return {id:n,deviceId:i,remoteNodeId:i,isClosed:false}}isTransportOnlyStreamChannel(e){let t=typeof e=="string"?e.trim():"";if(!t)return false;let n=this.client.listChannels().find(i=>i.id.trim()===t);return zt(n??null)}nextNativeStartRetryDelayMs(e){return h(e,U.NATIVE_START_RETRY_MIN_DELAY_MS,U.NATIVE_START_RETRY_MAX_DELAY_MS)}hasManagedSession(){return !!(this.managedSessionKey||this.managedSessionUserId)}usesNativeIpcBackend(){let t=this.backend?.capabilities?.();return t?.adapter==="native-ipc"||t?.adapter==="tauri-ipc"||t?.signaling.nativeIpc===true}startManagedReconciliation(e){return this.managedReconciliationTasks.add(e),()=>{this.managedReconciliationTasks.delete(e);}}scheduleManagedReconciliationFollowups(){this.notifyManagedReconciliation();for(let e of this.managedReconciliationFollowupTimers)clearTimeout(e);this.managedReconciliationFollowupTimers.clear();for(let e of [1500,5e3]){let t=setTimeout(()=>{this.managedReconciliationFollowupTimers.delete(t),this.notifyManagedReconciliation();},e);this.managedReconciliationFollowupTimers.add(t);}}stopManagedReconciliation(){for(let e of this.managedReconciliationFollowupTimers)clearTimeout(e);this.managedReconciliationFollowupTimers.clear(),this.managedReconciliationTasks.clear();}notifyManagedReconciliation(){this.hasManagedSession()&&this.managedReconciliationTasks.forEach(e=>{if(this.hasManagedSession())try{e();}catch{}});}async syncNativeSession(e="frontend"){let t=this.backend;t&&typeof t.syncNativeSession=="function"&&await t.syncNativeSession({reason:e}),await this.refreshPeerSnapshot().catch(()=>[]),this.scheduleManagedReconciliationFollowups();}async notifyNetworkChange(e="host"){let t=this.backend;typeof t.notifyNetworkChange=="function"&&await t.notifyNetworkChange({reason:e});}connectionStateSnapshotKey(e){return JSON.stringify({connectionId:e.connectionId,deviceId:e.deviceId??null,deviceIdHint:e.deviceIdHint??null,remoteNodeId:e.remoteNodeId??null,state:e.state,transportState:e.transportState??null,protocolState:e.protocolState??null,routable:e.routable??null,readinessState:e.readinessState??null,readinessReason:e.readinessReason??null,transportGeneration:e.transportGeneration??null,routeGeneration:e.routeGeneration??null,activeTransport:e.activeTransport??null,parallelTransport:e.parallelTransport??null,replacementInProgress:e.replacementInProgress??null,error:e.error??null,updatedAt:e.updatedAt??null})}async runNativeStartLoop(e$1){let t=Date.now(),n=0;for(;Date.now()-t<=U.NATIVE_START_RETRY_WINDOW_MS;){n+=1;try{await e$1.start(),n>1&&c$1(`[RuntimeClient] ${e$1.label} recovered after ${n} attempts`);return}catch(i){if(this.isUnsupportedRuntimeAdapterError(i,e$1.label))throw i;let o=this.nextNativeStartRetryDelayMs(n);console.warn(`[RuntimeClient] ${e$1.label} failed attempt=${n} retry_in_ms=${o}:`,i),await e(o);}}throw new Error(e$1.exhaustedMessage)}isUnsupportedRuntimeAdapterError(e,t){if(!(e instanceof Error))return false;let n=e.message||"",i=t==="startPresenceLoop"?"startPresence":t==="startAutoConnect"?"startAutoConnectOnce":null;return !!i&&n.includes(`does not support ${i}`)}onIdentityChange(e){return this.client.onAuthChange(e)}async signInAnonymously(){await this.client.signInAnonymously();}async signInWithPluto(){await this.client.signInWithPluto();}async setAuthContext(e){let t=this.backend;if(!t||typeof t.setAuthContext!="function")throw new Error("RuntimeClient auth context requires a runtime adapter that supports setAuthContext().");let n=typeof e?.userId=="string"&&e.userId.trim()||null,i=this.managedSessionUserId;i&&i!==n&&(console.info("[RuntimeClient][auth-context][managed-session-replace]",{previousUserId:i,nextUserId:n}),await this.stopManagedSession()),await t.setAuthContext(e);}async signOut(){await this.stopManagedSession().catch(()=>{}),await this.client.signOut();}async initialize(){if(this.usesNativeIpcBackend()){console.info("[RuntimeClient][native] initialize() skipped; native IPC backend owns runtime startup");return}await this.client.init();}async getRuntimeStatus(){return this.client.getRuntimeStatus()}reconciliationStats(){return this.client.reconciliationStats()}getRuntimePolicy(){return q}capabilities(){let e=this.backend;return typeof e?.capabilities=="function"?e.capabilities():v()}getCapabilityProfile(){return x(this.capabilities())}async start(e){if(this.usesNativeIpcBackend()){let t=await this.getManagedNodeId({initializeIfMissing:true});if(!t)throw new Error("Native runtime started without a node id for the admitted application-stream queue.");if(this.nativeStreamConsumer==="host"){console.info("[RuntimeClient][native] host owns the admitted application-stream queue",{nativeNodeId:t});return}this.client.attachIncomingStreamSource(this.backend,t),await this.client.startListening({startPresence:false});return}e?.clearSessionTokens!==false&&await this.client.clearSessionTokens().catch(()=>{}),await this.client.refreshRuntimeAuthToken("runtime-start"),await this.client.startListening();}stop(){this.client.stopListening();}async getNodeId(){if(this.usesNativeIpcBackend()){let e=await this.getManagedNodeId({initializeIfMissing:true});if(!e)throw new Error("Native node id unavailable from IPC backend");return e}return this.client.getNodeId()}async getNodeIdFromTicket(e){return this.client.getNodeIdFromTicket(e)}async getLocalDeviceId(){return this.client.getLocalDeviceId()}async getLocalDeviceInfo(){let e=this.backend;return !e||typeof e.getLocalDeviceInfo!="function"?null:e.getLocalDeviceInfo()}async localDeviceProfile(e){let t=await this.getLocalDeviceInfo().catch(()=>null),n=e?.localDeviceId??t?.deviceId??await this.getLocalDeviceId().catch(()=>null)??null,i=await this.getRuntimeStatus().catch(()=>({runtime:"unknown",wasmLoaded:false,localNodeId:void 0,userId:void 0})),o=e?.platform??(i.runtime==="tauri"?"native":"web");return {deviceId:n,deviceName:e?.deviceName||t?.deviceName||"Unknown Device",platformType:t?.platformType||(o==="native"?"desktop":"web"),userId:e?.userId??this.identity?.id??i.userId??null,capabilities:t?.capabilities??{can_host:o==="native",can_sync:o==="native",read_only:o!=="native"},lastSeenAt:t?.lastSeenAt||new Date().toISOString(),localNodeId:i.localNodeId||null}}async updateDeviceName(e){let t=this.backend;return !t||typeof t.updateDeviceName!="function"?null:t.updateDeviceName(e)}async getManagedNodeId(e){let t=this.backend;if(console.info("[RuntimeClient][getManagedNodeId] enter",{hasBackend:!!t,hasMethod:!!(t&&typeof t.getManagedNodeId=="function"),backendCtor:t?.constructor?.name??null}),!t||typeof t.getManagedNodeId!="function")return null;let n=await t.getManagedNodeId(e);return console.info("[RuntimeClient][getManagedNodeId] resolved",{result:n}),n}async initIrohProtocols(e){await this.persistentIrohProtocolBackend().initializePersistentIrohProtocols(e);}async createIrohNamespace(e={}){let t=e.generation??0,n=e.shareRevision??0;return this.assertProtocolCounter(t,"generation"),this.assertProtocolCounter(n,"shareRevision"),this.persistentIrohProtocolBackend().createPersistentIrohNamespace(t,n)}async importIrohTicket(e,t={}){let n=t.generation??0,i=t.shareRevision??0;if(this.assertProtocolCounter(n,"generation"),this.assertProtocolCounter(i,"shareRevision"),!e.trim())throw new Error("Iroh document ticket is required.");return this.persistentIrohProtocolBackend().importPersistentIrohTicket(e,n,i)}async shareIrohNamespace(e,t){return this.persistentIrohProtocolBackend().sharePersistentIrohNamespace(e,t?.writable===true)}async removeIrohNamespace(e,t={}){let n=t.generation??0,i=t.shareRevision??0;this.assertProtocolCounter(n,"generation"),this.assertProtocolCounter(i,"shareRevision"),await this.persistentIrohProtocolBackend().removePersistentIrohNamespace(e,n,i);}async putIrohBytes(e,t,n){return this.persistentIrohProtocolBackend().putPersistentIrohBytes(e,t,n)}async setIrohHash(e,t,n,i){return this.assertProtocolCounter(i,"contentLength"),this.persistentIrohProtocolBackend().setPersistentIrohHash(e,t,n,i)}async deleteIrohPrefix(e,t){return this.persistentIrohProtocolBackend().deletePersistentIrohPrefix(e,t)}async queryIrohNamespace(e,t=new Uint8Array){return this.persistentIrohProtocolBackend().queryPersistentIrohNamespace(e,t)}async hydrateIrohBlob(e){await this.persistentIrohProtocolBackend().hydratePersistentIrohBlob(e);}async acknowledgeOutbox(e){await this.persistentIrohProtocolBackend().acknowledgePersistentIrohOutbox(e);}async flushIrohProtocols(){await this.persistentIrohProtocolBackend().flushPersistentIrohProtocols();}persistentIrohProtocolBackend(){let e=this.backend;if(!e||typeof e.initializePersistentIrohProtocols!="function")throw new Error("Persistent Iroh protocols require the browser WASM runtime.");return e}assertProtocolCounter(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative safe integer.`)}async getTicket(){return this.usesNativeIpcBackend()?this.getEndpointTicket():this.client.getTicket()}async getTicketWithToken(e,t=0){let n=this.backend;if(n?.getTicketWithToken)try{let i=await n.getTicketWithToken(e,t);if(i)return i}catch(i){if(this.usesNativeIpcBackend())throw i}if(this.usesNativeIpcBackend())throw new Error("Native endpoint ticket with token unavailable from IPC backend");return this.client.getTicketWithToken(e,t)}async registerToken(e){let t=e.token.trim(),n=e.scope.trim(),i=e.maxConnections??0;if(!t)throw new Error("Admission token is required.");if(!n)throw new Error("Admission scope is required.");if(!Number.isSafeInteger(i)||i<0)throw new Error("maxConnections must be a non-negative safe integer.");if(e.expiresAtMs!==void 0&&(!Number.isSafeInteger(e.expiresAtMs)||e.expiresAtMs<=Date.now()))throw new Error("Admission token expiry must be a future epoch millisecond.");let o=this.backend;if(o?.registerSessionToken){await o.registerSessionToken(t,n,i,e.expiresAtMs);return}if(this.usesNativeIpcBackend())throw new Error("Native admission-token registration is unavailable from the IPC backend.");this.client.registerSessionToken(t,n,i,e.expiresAtMs);}async revokeTokensByScope(e){return this.revokeTokensByScopeInternal(e,{rotateManagedScopeIfActive:true})}async revokeTokensByScopeInternal(e,t){i("revokeTokensByScopeInternal",{grantScope:e,rotateManagedScopeIfActive:t?.rotateManagedScopeIfActive!==false,hasManagedSessionOptions:!!this.managedSessionOptions});let n=this.usesNativeIpcBackend(),i$1=n?[]:await this.client.revokeTokensByScope(e),o=this.backend,s=[];if(o?.revokeTokens)s=await o.revokeTokens(e).catch(()=>[]);else if(n)throw new Error("Native token revoke requires revokeTokens() on the IPC backend.");let a=Array.from(new Set([...i$1,...s]));return t?.rotateManagedScopeIfActive!==false&&e===U.MANAGED_USER_DEVICE_SCOPE&&this.managedSessionOptions&&this.managedSessionOptions.presence!==false&&await this.rotateManagedUserDeviceGrant(),a}revokeSessionToken(e){this.client.revokeSessionToken(e);}watchFriendDevices(e,t){let n=this.backend;return n?.watchFriendDevices?n.watchFriendDevices(e,t):()=>{}}async getFriendTicket(e=0){return this.getTicketWithToken(U.MANAGED_FRIEND_SCOPE,e)}async revokeFriendTokens(){return this.revokeTokensByScope(U.MANAGED_FRIEND_SCOPE)}async updateFriendTicket(e){let t=this.backend;t?.updateFriendTicket&&await t.updateFriendTicket(e);}async getEndpointTicket(){let e=this.backend;if(e&&typeof e.getEndpointTicket=="function")try{return await e.getEndpointTicket()}catch(t){if(this.usesNativeIpcBackend())throw t}if(this.usesNativeIpcBackend())throw new Error("Native endpoint ticket unavailable from IPC backend");return this.client.getTicket()}async startManagedSession(e){let t=this.resolveManagedSessionUserId(e.platform,e.userId??null),n=JSON.stringify({platform:e.platform,sessionKind:e.sessionKind??"app-user-device",scope:e.scope??null,userId:t,autoConnect:this.resolveManagedAutoConnectEnabled(e),autoConnectPolicy:e.autoConnectPolicy??null,presence:this.resolveManagedPresenceEnabled(e),presencePolicy:e.presencePolicy??null}),i$1=this.managedSessionStartInFlight.get(n);if(i$1)return i$1;let o=this.serializeManagedSessionOperation("start",async()=>{if(this.managedSessionKey===n){if(e.platform==="native"&&t){let d=this.backend;if(d&&typeof d.startNativeSession=="function")try{let l=await d.startNativeSession({userId:t,deviceName:e.deviceName,localDeviceId:e.localDeviceId??null,metadata:e.metadata,autoConnect:this.resolveManagedAutoConnectEnabled(e),presence:this.resolveManagedPresenceEnabled(e)});console.info("[RuntimeClient][managed-session][native-replayed]",{userId:t,localNodeId:l.localNodeId,presenceStarted:l.presenceStarted,autoConnectStarted:l.autoConnectStarted,localDeviceId:l.localDevice?.deviceId??null});}catch(l){console.warn("[RuntimeClient][managed-session][native-replay-failed]",{userId:t,message:l instanceof Error?l.message:String(l)});}}let c=await this.localDeviceProfile({deviceName:e.deviceName,localDeviceId:e.localDeviceId??null,platform:e.platform,userId:t});return {mode:e.platform,device:c,stop:async()=>this.stopManagedSession()}}i("managed-session-replace",{previousSessionKey:this.managedSessionKey,nextSessionKey:n}),await this.stopManagedSessionInternal(),this.managedSessionKey=n,this.managedSessionUserId=t,this.managedSessionOptions={...e,userId:t};let s=null,a=null;console.info("[RuntimeClient][managed-session][start]",{platform:e.platform,requestedUserId:e.userId??null,runtimeUserId:this.identity?.id??null,effectiveUserId:this.managedSessionUserId,sessionKind:e.sessionKind??"app-user-device",scope:e.scope??null,localDeviceId:e.localDeviceId??null,deviceName:e.deviceName??null,presence:this.resolveManagedPresenceEnabled(e),presencePolicy:e.presencePolicy??null,autoConnect:this.resolveManagedAutoConnectEnabled(e),autoConnectPolicy:e.autoConnectPolicy??null});try{if(e.platform==="web")await this.initialize(),this.resolveManagedPresenceEnabled(e)?(await this.client.clearSessionTokens().catch(()=>{}),s=await this.getTicketWithToken(U.MANAGED_USER_DEVICE_SCOPE,0),this.client.setManagedPresenceTicket(s),await this.start({clearSessionTokens:!1})):(this.client.clearManagedPresenceTicket(),await this.start());else {if(!this.managedSessionUserId)throw new Error("Native managed session startup requires an authenticated user id.");await this.client.ensureAuthenticated("discovery");let d=this.backend;if(!d||typeof d.startNativeSession!="function")throw new Error("Native managed session startup requires a native backend-owned startNativeSession() surface.");a=await d.startNativeSession({userId:this.managedSessionUserId,deviceName:e.deviceName,localDeviceId:e.localDeviceId??null,metadata:e.metadata,autoConnect:this.resolveManagedAutoConnectEnabled(e),presence:this.resolveManagedPresenceEnabled(e)}),console.info("[RuntimeClient][managed-session][native-started]",{userId:this.managedSessionUserId,localNodeId:a.localNodeId,ticketScope:a.ticketScope??null,presenceStarted:a.presenceStarted,autoConnectStarted:a.autoConnectStarted,localDeviceId:a.localDevice?.deviceId??null});let l=a.localNodeId??await this.getManagedNodeId({initializeIfMissing:!1});if(!l)throw new Error("Native managed session started without a node id for the admitted application-stream queue.");this.nativeStreamConsumer==="runtime"?(this.client.attachIncomingStreamSource(this.backend,l),await this.client.startListening({startPresence:!1})):console.info("[RuntimeClient][managed-session] native host owns the admitted application-stream queue",{nativeNodeId:l});}this.fetchAndApplyAppLimits();let c=await this.localDeviceProfile({deviceName:e.deviceName,localDeviceId:e.localDeviceId??null,platform:e.platform,userId:this.managedSessionUserId});return e.platform==="native"?(this.resolveManagedPresenceEnabled(e)&&!a?.presenceStarted&&console.warn("[RuntimeClient][managed-session][native-presence-missing]",{userId:this.managedSessionUserId,deviceId:c.deviceId}),this.resolveManagedAutoConnectEnabled(e)&&c.deviceId&&!a?.autoConnectStarted&&console.warn("[RuntimeClient][managed-session][native-auto-connect-missing]",{userId:this.managedSessionUserId,deviceId:c.deviceId})):this.resolveManagedPresenceEnabled(e)&&(console.info("[RuntimeClient][managed-session][start-presence]",{platform:e.platform,sessionKind:e.sessionKind??"app-user-device",scope:e.scope??null,userId:this.managedSessionUserId,deviceId:c.deviceId,deviceName:c.deviceName,ticketScope:U.describeTicketForLogs(s).scope}),await this.startPresenceLoop({deviceName:c.deviceName,ticket:s,metadata:e.metadata}),console.info("[RuntimeClient][managed-session][presence-started]",{platform:e.platform,userId:this.managedSessionUserId,deviceId:c.deviceId})),e.platform!=="native"&&this.resolveManagedAutoConnectEnabled(e)&&c.deviceId&&(await this.startAutoConnect(c.deviceId),console.info("[RuntimeClient][managed-session][auto-connect-started]",{platform:e.platform,sessionKind:e.sessionKind??"app-user-device",scope:e.scope??null,userId:this.managedSessionUserId,deviceId:c.deviceId})),await this.refreshPeerSnapshot().catch(()=>[]),this.scheduleManagedReconciliationFollowups(),{mode:e.platform,device:c,stop:async()=>this.stopManagedSession()}}catch(c){throw console.warn("[RuntimeClient][managed-session][start-failed-cleanup]",{platform:e.platform,requestedUserId:e.userId??null,runtimeUserId:this.identity?.id??null,effectiveUserId:this.managedSessionUserId,message:c instanceof Error?c.message:String(c)}),await this.stopManagedSessionInternal().catch(()=>{}),c}});this.managedSessionStartInFlight.set(n,o);try{return await o}finally{this.managedSessionStartInFlight.delete(n);}}async stopManagedSession(e){return this.serializeManagedSessionOperation(e?.preserveBackendSession?"stop-preserve-backend":"stop",()=>this.stopManagedSessionInternal(e))}async stopManagedSessionInternal(e){if(!this.managedSessionKey&&!this.managedSessionUserId)return;let t=!!e?.preserveBackendSession;i("stopManagedSessionInternal",{preserveBackendSession:t,managedSessionKey:this.managedSessionKey,managedSessionUserId:this.managedSessionUserId??null});let n=this.backend;this.managedSessionOptions;let o=Date.now();if(console.info("[RuntimeClient][managed-session][stop-stage]",{stage:"local-invalidate",elapsedMs:0,managedSessionUserId:this.managedSessionUserId,preserveBackendSession:t}),this.client.clearManagedPresenceTicket(),t?console.info("[RuntimeClient] Preserving native backend-managed session across frontend teardown",{userId:this.managedSessionUserId??this.identity?.id??null,scope:U.MANAGED_USER_DEVICE_SCOPE}):(console.info("[RuntimeClient][managed-session][stop-stage]",{stage:"revoke-user-device-grants",elapsedMs:Date.now()-o,managedSessionUserId:this.managedSessionUserId}),await this.revokeTokensByScopeInternal(U.MANAGED_USER_DEVICE_SCOPE,{rotateManagedScopeIfActive:false}).catch(()=>[]),this.stop(),n&&typeof n.stopAuthActivity=="function"?(console.info("[RuntimeClient][managed-session][stop-stage]",{stage:"stop-backend-auth-scope",elapsedMs:Date.now()-o,managedSessionUserId:this.managedSessionUserId}),await n.stopAuthActivity({userId:this.managedSessionUserId??this.identity?.id??null})):await this.setOffline().catch(()=>{})),t){this.notifyManagedReconciliation();return}await this.scopedConnectionActorRegistry?.shutdownAll().catch(s=>{console.warn("[RuntimeClient] scoped connection actor shutdown failed",s);}),this.scopedConnectionActorRegistry=null,this.managedSessionKey=null,this.managedSessionUserId=null,this.managedSessionOptions=null,console.info("[RuntimeClient][managed-session][stop-stage]",{stage:"complete",elapsedMs:Date.now()-o,managedSessionUserId:null});}async rotateManagedUserDeviceGrant(){let e=this.managedSessionOptions;if(!e||!this.resolveManagedPresenceEnabled(e))return;if(e.platform==="native"){let o=this.backend;if(!o||typeof o.startNativeSession!="function")throw new Error("Native managed ticket rotation requires a native backend-owned startNativeSession() surface.");let s=this.managedSessionUserId??e.userId??this.identity?.id??null;if(!s)throw new Error("Native managed ticket rotation requires an authenticated user id.");await o.startNativeSession({userId:s,deviceName:e.deviceName,localDeviceId:e.localDeviceId??null,metadata:e.metadata,autoConnect:this.resolveManagedAutoConnectEnabled(e),presence:this.resolveManagedPresenceEnabled(e)}),console.info("[RuntimeClient][managed-ticket][rotate]",{scope:U.MANAGED_USER_DEVICE_SCOPE,platform:e.platform,userId:s});return}let t=await this.getTicketWithToken(U.MANAGED_USER_DEVICE_SCOPE,0),n=this.managedSessionUserId??e.userId??this.identity?.id??null;this.client.setManagedPresenceTicket(t);let i=await this.localDeviceProfile({deviceName:e.deviceName,localDeviceId:e.localDeviceId??null,platform:e.platform,userId:e.userId??null});await this.startPresenceLoop({deviceName:i.deviceName,ticket:t,metadata:e.metadata}),console.info("[RuntimeClient][managed-ticket][rotate]",{scope:U.MANAGED_USER_DEVICE_SCOPE,platform:e.platform,userId:n});}async listDevices(){return this.deviceManager.listDevices()}async listDeviceStatus(){return this.deviceManager.listDeviceStatus()}async updateDevice(e,t){await this.deviceManager.updateDevice(e,t);}async deleteDevice(e){await this.deviceManager.deleteDevice(e);}watchDevices(e){return this.deviceManager.watchDevices(e)}watchDeviceStatus(e){return this.deviceManager.watchDeviceStatus(e)}async connectWithRetry(e,t,n){return this.deviceManager.connectWithRetry(e,t,n)}async connectDevice(e,t){return this.deviceManager.connectDevice(e,t)}watchPeerStates(e){return this.client.watchPeerStates(e)}watchPeerLifecycle(e){return this.watchPeerStates(e)}getPeerState(e){return this.client.getPeerState(e)}async resolvePeerRecords(e){return this.peerManager.resolvePeerRecords(e)}async getPeerSession(e){return this.peerManager.getPeerSession(e)}async listPeerSessions(){return this.peerManager.listPeerSessions()}async waitForConnectedPeer(e,t){return this.peerManager.waitForConnectedPeer(e,t)}async getPeerReadiness(e,t){return this.peerManager.getPeerReadiness(e,t)}async resolvePeerIdentity(e){return this.peerManager.resolvePeerIdentity(e)}async resolveStreamPeer(e){return this.peerManager.resolveStreamPeer(e)}listConnectedPeers(){return this.client.listConnectedPeers()}addPeerScope(e,t){return this.peerManager.addPeerScope(e,t)}releasePeerScope(e,t){return this.peerManager.releasePeerScope(e,t)}getPeerScopes(e){return this.peerManager.getPeerScopes(e)}isSamePeer(e,t){return this.peerManager.isSamePeer(e,t)}async refreshPeerSnapshot(){return this.client.refreshPeerSnapshot()}async subscribeSessions(e,t){return this.client.subscribeSessions(e,t)}getAppLimits(){return this.client.appLimits}async createRoom(e){return this.client.rooms.createRoom(e)}async joinRoom(e,t){return this.client.rooms.joinRoom(e,t)}async leaveRoom(e){return this.client.rooms.leaveRoom(e)}async getRoomMembers(e){return this.client.rooms.getRoomMembers(e)}watchRoom(e,t){return this.client.rooms.watchRoom(e,t)}async connectByTicket(e){return this.client.connect(e.ticket,e.timeoutMs)}async connectPeer(e){return this.client.connectPeer(e)}async connectScopedChannel(e$1){let t=e$1.timeoutMs===void 0?void 0:Math.max(1,e$1.timeoutMs),n=t===void 0?void 0:Date.now()+t,i=R=>{if(n===void 0||t===void 0)return;let E=n-Date.now();if(E<=0)throw new Error(`connectScopedChannel timeout after ${t}ms during ${R}`);return Math.max(1,E)},o=e$1.scope,s=e$1.channelId.trim();if(!s)throw new Error("connectScopedChannel requires a channelId");let a$1=e$1.peerId??e$1.peerNodeId??e$1.deviceId??(e$1.ticket?await this.getNodeIdFromTicket(e$1.ticket).catch(()=>null):null);if(!a$1)throw new Error("connectScopedChannel requires peerId, peerNodeId, deviceId, or a ticket with an embedded node id");let c=this.client.getConnections().find(R=>!R.isClosed&&(R.remoteNodeId===a$1||R.deviceId===a$1))??null,d=c?[c.id,c.remoteNodeId,c.deviceId,a$1,e$1.deviceId].map(R=>typeof R=="string"?R.trim():"").filter(Boolean).map(R=>this.client.getPeerState(R)).find(R=>R!==void 0):void 0,l=c?await this.resolvePeerRecords(e$1.deviceId??a$1).catch(()=>[]):[],p=this.usesNativeIpcBackend()?await this.getPeerSession(e$1.deviceId??a$1).catch(()=>null):null,u=l.some(R=>R.state.toLowerCase()==="connected"&&R.transportStableId!==null&&R.transportStableId!==void 0),h=d?.status==="connected"&&d.lifecycleStage!=="closed"&&d.baseTransportState!=="closed"&&d.routable!==false,m=c!==null&&(typeof c.isPayloadReady!="function"||c.isPayloadReady()),f=e$1.existingRouteOnly===true?m:(l.length>0?u:h)&&d?.scopes.includes(o)===true,v=p?.status==="connected"&&p.settledReady===true&&p.scopes.includes(o);c$1("[RuntimeClient][connectScopedChannel] existing route decision",{peerId:a$1,scope:o,hasWrapper:c!==null,projectedStatus:d?.status??null,projectedScopes:d?.scopes??[],managedRecords:l.map(R=>({connectionId:R.connectionId,state:R.state,transportStableId:R.transportStableId??null})),nativeSession:p?{peerId:p.peerId,deviceId:p.deviceId??null,nodeId:p.nodeId??null,status:p.status,settledReady:p.settledReady===true,scopes:p.scopes}:null,reuse:f||v,existingRouteOnly:e$1.existingRouteOnly===true});let y=f?c:null,C=null,I=v?p?.nodeId??a$1:null;if(!y){if(e$1.existingRouteOnly===true)throw new Error(`Capability-owned channel '${s}' has no application-ready route for '${a$1}'`);if(this.usesNativeIpcBackend()){if(!v)if(e$1.ticket){let R=o===U.MANAGED_USER_DEVICE_SCOPE?e$1.deviceId:null,E=await this.connectToDevice({endpointTicket:e$1.ticket,deviceId:R,timeoutMs:i("native peer dial")}),F=E.remoteNodeId??E.deviceId??E.deviceIdHint??a$1,B=await this.waitForConnectedPeer(F,i("native scoped peer settle"));if(!B?.settledReady||!B.scopes.includes(o))throw new Error(`native scoped peer '${F}' did not admit '${o}' before channel open`);I=B.nodeId??F,y=this.client.getConnections().find(G=>!G.isClosed&&(G.id===E.connectionId||G.remoteNodeId===F||G.deviceId===F||G.deviceId===e$1.deviceId))??null;}else throw new Error("native connectScopedChannel requires an endpoint ticket when no connection exists")}else C=this.connectionActor({scope:o,peerNodeId:a$1},{ticket:e$1.ticket,timeoutMs:i("scoped peer actor"),channelId:s,dial:async()=>{y=await this.connectPeer({ticket:e$1.ticket,deviceId:e$1.deviceId??a$1,scope:o,channelId:s,timeoutMs:i("browser peer dial"),keepManualDisconnect:e$1.keepManualDisconnect??true});}}),await C.ensureReady();}y||(this.usesNativeIpcBackend()?y=this.client.getConnections().find(R=>!R.isClosed&&(R.remoteNodeId===(I??a$1)||R.deviceId===a$1))??null:y=await this.connectPeer({ticket:e$1.ticket,deviceId:e$1.deviceId??a$1,scope:o,channelId:s,timeoutMs:i("peer dial fallback"),keepManualDisconnect:e$1.keepManualDisconnect??true}));let b=y?.remoteNodeId??I??a$1,P=y,A=e$1.nativeLabel===true,S=e$1.framing??"raw",D=async()=>{if(A)try{let E=await this.openPeerNativeBi(b,s,{timeoutMs:i("native labelled stream open"),scope:o});return {connection:E.connection,readable:E.readable,writer:E.writable.getWriter(),openedWithNativeLabel:!0}}catch(E){c$1("[RuntimeClient][connectScopedChannel] native-labelled stream open failed; falling back",{peerId:b,channelId:s,error:String(E)});let F=await this.openPeerBi(b,{timeoutMs:i("scoped stream fallback"),scope:o,channelId:s});return {connection:F.connection,readable:F.readable,writer:F.writable.getWriter(),openedWithNativeLabel:true}}let R=await this.openPeerBi(b,{timeoutMs:i("scoped stream open"),scope:o,channelId:s});return {connection:R.connection,readable:R.readable,writer:R.writable.getWriter(),openedWithNativeLabel:false}},_=await D();y=P??_.connection;let T=_.writer,M=_.openedWithNativeLabel,L=new Set,W=false,X=false,he=0,be=null,Be=null,Qn=Promise.resolve(),it=null,Vn=null,Fe=null,$n=R=>{s!=="drive-view"||!R||R===Vn||typeof R.onWebRTCBinaryMessage!="function"&&typeof R.onMessage!="function"||(Fe?.(),Fe=qa(R,E=>{if(W||!Ui(E))return false;for(let F of [...L])F(E);return true}),Vn=R);},We=()=>{let R=new Set([y?.id,y?.remoteNodeId,y?.deviceId,b,a$1,e$1.deviceId,e$1.peerId,e$1.peerNodeId].map(B=>typeof B=="string"?B.trim():"").filter(Boolean)),E=this.client.getConnections().filter(B=>!B.isClosed&&(R.has(B.id)||R.has(B.remoteNodeId)||R.has(B.deviceId??""))),F=E.find(B=>Rs(B))??E.find(B=>typeof B.sendOnWebRTC=="function"||typeof B.getWebRTCTransport=="function")??E[0]??null;if(F&&F!==y&&(y=F),!y)throw new Error(`Scoped channel '${s}' has no active connection`);return $n(y),y};$n(y);let Yn=R=>{let E=R.getReader(),F=++he,B=new Uint8Array(0);be=E,X=false,(async()=>{try{for(;!W&&F===he;){let{value:G,done:Re}=await E.read();if(Re)break;if(!(!G||G.byteLength===0)){if(S==="raw"){for(let te of [...L])te(G);continue}for(B=ci(B,G);B.byteLength>=4;){let te=li(B,0);if(B.byteLength<4+te)break;let Zn=B.slice(4,4+te);B=B.slice(4+te);for(let me of [...L])me(Zn);}}}}catch(G){!W&&F===he&&c$1("[RuntimeClient][connectScopedChannel] physical stream read loop ended with error",{peerId:b,channelId:s,error:String(G)});}finally{F===he&&(X=true,be===E&&(be=null));try{E.releaseLock();}catch{}}})();};Yn(_.readable);let Jn=async()=>{X&&(Be||(Be=(async()=>{let R=T,E=await D();if(W){try{await E.readable.cancel("scoped channel closed during physical stream reopen");}catch{}try{await E.writer.abort("scoped channel closed during physical stream reopen");}catch{}try{E.writer.releaseLock();}catch{}throw new Error(`Scoped channel '${s}' is closed`)}y=E.connection??y,T=E.writer,M=M||E.openedWithNativeLabel,Yn(E.readable);try{await R.abort("scoped channel physical stream replaced");}catch{}try{R.releaseLock();}catch{}})().finally(()=>{Be=null;})),await Be);},Pe=async R=>{let E=Qn.then(async()=>{if(W)throw new Error(`Scoped channel '${s}' is closed`);let F=We();if(s==="drive-view"&&Rs(F))try{await F.send(R),it=F.lastPayloadTransport?.()??F.getTransportStatus?.().activeTransport??null;return}catch(G){c$1("[RuntimeClient][connectScopedChannel] current-route scoped-channel send failed; falling back to stream",{peerId:b,channelId:s,error:String(G)});}let B=S==="u32be"?ai(R):R;await Jn();try{await T.write(B);}catch(G){if(W)throw G;X=true,await Jn(),await T.write(B);}it="stream";});Qn=E.catch(()=>{}),await E;},Oe=this.client.listChannels().find(R=>R.id===s)?.delivery??"reliable",ot=Oe==="latest-state"?new a(Pe):null,Xn=R=>ot?.send(R)??Pe(R);if(!this.usesNativeIpcBackend()){let R=Math.max(1,Math.min(i("application route settlement")??5e3,5e3)),E=Date.now();for(;;){let F=We();if(typeof F.isPayloadReady!="function"||F.isPayloadReady())break;if(Date.now()-E>=R){W=true,he+=1;let B=be;try{await B?.cancel("scoped channel application route timeout");}catch{}try{await T.abort("scoped channel application route timeout");}catch{}try{T.releaseLock();}catch{}throw await C?.shutdown().catch(()=>{}),new Error(`Scoped channel '${s}' timed out waiting for an application payload route`)}await e(20);}}return {channelId:s,peerId:b,get connection(){return We()},send:Xn,onMessage(R){return L.add(R),()=>L.delete(R)},async close(){if(!W){W=true,ot?.close(new Error(`Scoped channel '${s}' is closed`)),he+=1,L.clear(),Fe?.(),Fe=null;try{await be?.cancel("scoped channel closed");}catch{}try{await T.abort("scoped channel closed");}catch{}try{T.releaseLock();}catch{}await C?.shutdown().catch(()=>{});}},diagnostics:()=>{let R=We();return {connectionId:R.id??null,remoteNodeId:R.remoteNodeId??null,transports:R.getAvailableTransports?.()??[],hasSendOnWebRTC:typeof R.sendOnWebRTC=="function",hasWebRTCTransport:typeof R.getWebRTCTransport=="function"?R.getWebRTCTransport()!==null:false,lastSendTransport:it,framing:S,nativeLabel:M||A,delivery:Oe}}}}connectionActor(e,t){let n=a=>{let c=t?.ticket,d=t?.channelId,l=t?.dial;return new Ke({key:a,dial:async p=>{if(this.assertScopedDialAllowed(p),l){await l(p);return}await this.connectPeer({deviceId:p.peerNodeId,ticket:c,scope:p.scope,channelId:d,keepManualDisconnect:true});},close:async()=>{}})};this.scopedConnectionActorRegistry||(this.scopedConnectionActorRegistry=new ze(n));let i=si(e.scope,e.peerNodeId),o=this.scopedConnectionActorRegistry.get(i),s=this.scopedConnectionActorRegistry.getOrSpawn(i,n);return (o===null||o!==null&&o!==s)&&Y("[runtime-client][scoped-connection-actor]",Ge(i.scope,{peerNodeId:i.peerNodeId}),"spawn"),s}assertScopedDialAllowed(e){let t=this.scopedDialCandidateIds(e).find(n=>this.hasManualDisconnectSuppression(n));if(t)throw Y("[runtime-client][scoped-connection-actor]",Ge(e.scope,{peerNodeId:e.peerNodeId}),"dial_suppressed_manual_disconnect peerId={}",t),new Error(`scoped connection dial suppressed by manual disconnect for peer ${t}`)}scopedDialCandidateIds(e){let t=new Set,n=e.peerNodeId.trim();n&&t.add(n);let i=e.scope.trim();if(i.startsWith("trusted-device:")){let o=i.slice(15).split(":")[0]?.trim();o&&t.add(o);}return [...t]}hasManualDisconnectSuppression(e){let t=this.client.getPeerState(e);if(!t)return false;if(t.manualDisconnect===true)return true;let n=t,i=[t.error,n.lastDisconnectReason].filter(o=>typeof o=="string"&&o.length>0).join(" ");return /manual disconnect/i.test(i)}async shutdownActors(){if(!this.scopedConnectionActorRegistry)return;let e=this.scopedConnectionActorRegistry.size();Y("[runtime-client][scoped-connection-actor]",{sessionKind:"drive-grant-guest"},"shutdown_all count={}",e),await this.scopedConnectionActorRegistry.shutdownAll();}async openPeerBi(e,t){let n=this.backend;if(n&&typeof n.openPeerBi=="function"){await this.waitForBrowserApplicationCrypto(e,t?.timeoutMs);let i=await n.openPeerBi(e,t?.timeoutMs),o=await this.resolvePeerStreamTarget(e);return {connection:o.connection??this.compatPeerConnectionFromTarget(o,e),readable:i.readable,writable:t?.channelId?this.client.wrapChannelWritable(i.writable,t.channelId):i.writable}}throw new Error("[pluto-rtc] openPeerBi() requires a Rust-backed runtime adapter that implements openPeerBi().")}async openPeerNativeBi(e,t,n){let i=this.backend;if(i&&typeof i.openPeerNativeBi=="function"){await this.waitForBrowserApplicationCrypto(e,n?.timeoutMs);let o=await i.openPeerNativeBi(e,t,n?.timeoutMs),s=await this.resolvePeerStreamTarget(e);return {connection:s.connection??this.compatPeerConnectionFromTarget(s,e),readable:o.readable,writable:o.writable}}throw new Error("[pluto-rtc] openPeerNativeBi() requires a Rust-backed runtime adapter that implements openPeerNativeBi().")}async openPeerBiRaw(e,t){let n=this.backend;if(n&&typeof n.openPeerBiRaw=="function"){let i=await n.openPeerBiRaw(e,t?.timeoutMs),o=await this.resolvePeerStreamTarget(e);return {connection:o.connection??this.compatPeerConnectionFromTarget(o,e),readable:i.readable,writable:t?.channelId?this.client.wrapChannelWritable(i.writable,t.channelId):i.writable}}return this.openPeerBi(e,t)}async openPeerUni(e,t){let n=this.backend;if(n&&typeof n.openPeerUni=="function"){await this.waitForBrowserApplicationCrypto(e,t?.timeoutMs);let i=await n.openPeerUni(e,t?.timeoutMs),o=await this.resolvePeerStreamTarget(e);return {connection:o.connection??this.compatPeerConnectionFromTarget(o,e),writable:t?.channelId?this.client.wrapChannelWritable(i.writable,t.channelId):i.writable}}throw new Error("[pluto-rtc] openPeerUni() requires a Rust-backed runtime adapter that implements openPeerUni().")}async waitForBrowserApplicationCrypto(e,t){if(this.usesNativeIpcBackend())return;let n=Math.max(1,t??1e4);if(!await this.client.waitForApplicationCryptoForPeer(e,n))throw new Error(`[OpenRTC] protected application stream to '${e}' timed out waiting for application crypto`)}async connectToDevice(e){return this.connectionController.connectToDevice(e)}async connectRaw(e){return this.connectionController.connectRaw(e)}async openBi(e){return this.connectionController.openBi(e)}async openUni(e){return this.connectionController.openUni(e)}onIncomingStream(e){return this.client.onIncomingStream(e)}registerChannel(e){this.client.registerChannel(e);}unregisterChannel(e){this.client.unregisterChannel(e);}listChannels(){return this.client.listChannels()}onChannelStream(e,t){return this.client.onChannelStream(e,t)}async sendExplicitFilePath(e,t,n){let i=this.backend;if(!i||typeof i.sendExplicitFilePath!="function")throw new Error("Selected runtime adapter does not support sendExplicitFilePath().");return i.sendExplicitFilePath(e,t,n)}async sendExplicitFileData(e){let t=this.backend;if(!t||typeof t.sendExplicitFileData!="function")throw new Error("Selected runtime adapter does not support sendExplicitFileData().");let n=this.client.getConnectionForPeer(e.connectionId,e.remoteNodeId),i=e.requireApplicationCrypto??(typeof n?.isApplicationCryptoRequired=="function"?n.isApplicationCryptoRequired():void 0),o=e.remoteNodeId??n?.remoteNodeId??e.connectionId??n?.deviceId,s=e.applicationCrypto??this.client.getApplicationCrypto(n??void 0)??this.client.resolveApplicationCryptoForPeer(o,n??void 0)??(i?await this.client.waitForApplicationCryptoForPeer(o):void 0),a=e.receiverPlatformType;if(a===void 0){let d=new Set([e.remoteNodeId,n?.remoteNodeId,n?.deviceId,e.connectionId].map(l=>typeof l=="string"?l.trim():"").filter(l=>l.length>0));if(d.size>0){let p=(await this.listDeviceStatus().catch(()=>[])).find(u=>d.has(String(u.deviceId??""))||d.has(String(u.peerId??""))||d.has(String(u.nodeId??""))||d.has(String(u.connectionId??"")));a=typeof p?.platformType=="string"&&p.platformType.trim().length>0?p.platformType:null;}}let c={...e,connection:e.connection??n,remoteNodeId:e.remoteNodeId??n?.remoteNodeId,receiverPlatformType:a,applicationCrypto:s,requireApplicationCrypto:i};return t.sendExplicitFileData(c)}async getTransferHistory(e){let t=this.backend;return !t||typeof t.getTransferHistory!="function"?[]:t.getTransferHistory(e)}async deleteTransferJob(e){let t=this.backend;if(!(!t||typeof t.deleteTransferJob!="function"))return t.deleteTransferJob(e)}async startPresenceLoop(e){let t=this.backend;if(this.usesNativeIpcBackend()&&t&&typeof t.startPresence=="function"){let n=this.getEffectiveRuntimeUserId();if(!n){await this.client.startPresenceLoop(e);return}let i=await this.getManagedNodeId({initializeIfMissing:true}).catch(()=>null),o=i||await this.getNodeId(),s=e?.ticket||await this.getEndpointTicket(),a=await this.localDeviceProfile({deviceName:e?.deviceName,platform:"native",userId:n}),c=U.describeTicketForLogs(s);console.info("[RuntimeClient][native-presence][start]",{userId:n,localNodeId:o,nodeSource:i?"native-managed":"client-getNodeId-fallback",deviceId:a.deviceId,deviceName:e?.deviceName||a.deviceName,ticketScope:c.scope,isCompoundTicket:c.isCompound});try{await this.runNativeStartLoop({label:"startPresenceLoop",exhaustedMessage:`[RuntimeClient] startPresenceLoop exhausted retries user_id=${n} local_node_id=${o}`,start:()=>t.startPresence(n,o,e?.deviceName||a.deviceName,s,e?.metadata)});}catch(d){if(!this.isUnsupportedRuntimeAdapterError(d,"startPresenceLoop"))throw d;await this.client.startPresenceLoop(e);return}console.info("[RuntimeClient][native-presence][started]",{userId:n,localNodeId:o,nodeSource:i?"native-managed":"client-getNodeId-fallback",deviceId:a.deviceId});return}await this.client.startPresenceLoop(e);}async updatePresence(e){await this.client.updatePresence(e?.isOnline,e?.ttlMs,e?.metadata,e?.ticket);}async refreshLivePresence(e){let t=this.backend;if(!t||typeof t.refreshLivePresence!="function"){await this.updatePresence(e);return}let n=await this.getNodeId(),i=e?.ticket||await this.getEndpointTicket();await t.refreshLivePresence(n,i,e?.metadata);}async setOffline(){await this.client.setOffline();}async cleanupStaleDevices(){await this.client.cleanupStaleDevices();}async startAutoConnect(e){await this.client.refreshRuntimeAuthToken("runtime-start");let t=this.backend;if(t&&typeof t.startAutoConnectOnce=="function"){let n=this.getEffectiveRuntimeUserId();if(!n)throw new Error("startAutoConnect requires an authenticated user");let i=e||await this.getLocalDeviceId();if(!i)throw new Error("startAutoConnect requires a local device id");try{await this.runNativeStartLoop({label:"startAutoConnect",exhaustedMessage:`[RuntimeClient] startAutoConnect exhausted retries user_id=${n} local_device_id=${i}`,start:()=>t.startAutoConnectOnce(n,i)});}catch(o){if(!this.isUnsupportedRuntimeAdapterError(o,"startAutoConnect"))throw o;await this.client.startAutoConnect(e);return}return}await this.client.startAutoConnect(e);}async isConnected(e){return this.connectionController.isConnected(e)}async disconnectNode(e){await this.connectionController.disconnectNode(e);}async disconnectDevice(e){return this.connectionController.disconnectDevice(e)}async excludeAutoConnect(e,t){await this.connectionController.excludeAutoConnect(e,t);}async disconnectPeer(e,t){await this.connectionController.disconnectPeer(e,t);}async forceDisconnectPeer(e){await this.connectionController.forceDisconnectPeer(e);}async getPeerHealth(e){return this.client.getPeerHealth(e)}async getConnectionStates(){return this.client.signaling.getConnectionStates()}onStateChange(e){let t=true,n=new Map,i=c=>{if(!t)return;let d=this.connectionStateSnapshotKey(c);n.get(c.connectionId)!==d&&(n.set(c.connectionId,d),e(c));},o=()=>{t&&this.getConnectionStates().then(c=>{c.forEach(d=>i(d));}).catch(()=>{});},s=c=>()=>{t=false,c?.();},a=this.client.signaling.onStateChange(c=>i(c));return o(),typeof a=="function"?s(a):Promise.resolve(a).then(c=>s(typeof c=="function"?c:null))}getConnections(){return this.client.getConnections()}readyConnections(e={}){return this.client.readyConnections(e)}onConnection(e){return this.client.onConnection(e)}onDisconnection(e){return this.client.onDisconnection(e)}onMessage(e){return this.client.onMessage(e)}onConnectionEvent(e){let t=this.client.onConnection(i=>{let{activeTransport:o}=i.getTransportStatus();e({type:"connected",connectionId:i.id,localNodeId:i.localNodeId,remoteNodeId:i.remoteNodeId,transport:o});}),n=this.client.onDisconnection(i=>{let{activeTransport:o}=i.getTransportStatus();e({type:"disconnected",connectionId:i.id,localNodeId:i.localNodeId,remoteNodeId:i.remoteNodeId,transport:o});});return ()=>{t(),n();}}forceReconnect(){this.client.forceReconnect();}async connect(){await this.initialize(),await this.start();}disconnect(){this.stop();}async shutdown(){return this.terminalShutdown?this.terminalShutdown:(this.terminalShutdown=(async()=>{this.stopManagedReconciliation(),this.hasManagedSession()?await this.stopManagedSession():(this.stop(),await this.backend?.stopAuthActivity?.(),await this.scopedConnectionActorRegistry?.shutdownAll(),this.scopedConnectionActorRegistry=null),await this.backend?.shutdownPersistentIrohProtocols?.(),this.destroy();})(),this.terminalShutdown)}destroy(){this.stopManagedReconciliation(),this.stop();let e=this.client;e&&typeof e.destroy=="function"&&e.destroy();}dispose(){this.destroy();}onAuthChange(e){return this.onIdentityChange(e)}async setAuth(e){return this.setAuthContext(e)}async signIn(){return this.signInWithPluto()}async getDevices(){return this.listDevices()}onDevices(e,t){return t?.status?this.watchDeviceStatus(e):this.watchDevices(e)}async getInvite(){return this.getTicket()}async connectTo(e){return this.connectPeer(e)}async waitFor(e,t){return this.waitForConnectedPeer(e,t)}async openStream(e,t){if(t?.direction==="send")return this.openPeerUni(e,t);if(this.isTransportOnlyStreamChannel(t?.channelId))try{return await this.openPeerBiRaw(e,t)}catch(n){let i=n instanceof Error?n.message:String(n);if(!/application crypto/i.test(i))throw n;c$1("[RuntimeClient] transport-only channel requires encrypted peer stream; falling back",{peerId:e,channelId:t?.channelId??null});}return this.openPeerBi(e,t)}async openChannelStream(e,t,n){return this.openStream(t,{...n,channelId:e})}onStream(e){return this.onIncomingStream(e)}onRoomChange(e,t){return this.watchRoom(e,t)}createSession(e){return new jn(this,e)}};U.NATIVE_START_RETRY_WINDOW_MS=q.managedSession.nativeStartRetryWindowMs,U.NATIVE_START_RETRY_MIN_DELAY_MS=q.managedSession.nativeStartRetryMinDelayMs,U.NATIVE_START_RETRY_MAX_DELAY_MS=q.managedSession.nativeStartRetryMaxDelayMs,U.DEVICE_STATUS_REFRESH_DEBOUNCE_MS=q.managedSession.deviceStatusRefreshDebounceMs,U.MANAGED_USER_DEVICE_SCOPE="user-device",U.MANAGED_FRIEND_SCOPE="friend";var ws=U;var H=class H{constructor(e){this.subscriptionNonce=0;this.lastSyncedAuthToken=null;this.cachedLocalDeviceId=null;this.cachedLocalDeviceName=null;this.tauriCoreAvailability=null;this.tauriCoreAvailabilityValue=null;this.tauriCoreAvailabilityCheckedAtMs=0;this.authSyncInFlight=null;this.nativeTrustTokenUnsubscribe=null;this.nativeTrustRelayQueue=Promise.resolve();this.nativeTrustRelayError=null;this.nativeRuntimeCapabilitiesSyncInFlight=null;this.gatewayDesiredPeersCleanup=null;this.gatewayDesiredPeerRelayKey=null;this.gatewayDesiredPeerRelayGeneration=0;this.gatewayDesiredPeerRevision=0;this.gatewayDesiredPeerSubmission=Promise.resolve();this.gatewayDesiredPeerLifecycle=Promise.resolve();this.gatewayExcludedPeers=new Set;this.lastNativeAuthSyncAtMs=0;this.runtimeCapabilities=w$1(null,false);this.fallback=new z({...e,coordinationPlatformType:e.coordinationPlatformType??"desktop"}),this.app=this.fallback.app,this.auth=this.fallback.auth,this.appTag=this.fallback.tag,this.options=this.fallback.getResolvedOptions(),this.transportOptions=e.transports,this.strictMode=e.strictMode===true,this.turnCredentialsProvider=e.turnCredentialsProvider,this.allowWasmFallback=e.allowWasmFallback??false,this.ipcBridge=c$2(e.ipcBridge??d(),"NativeIpcBridge"),this.runtimeCapabilities=w$1(null,this.allowWasmFallback),this.syncNativeRuntimeCapabilities("constructor");}get currentUser(){return this.fallback.currentUser}get tag(){return this.fallback.tag}capabilities(){let e=u(this.runtimeCapabilities);return e.fallback.wasm=this.allowWasmFallback,e}usesCoordinationGateway(){return this.fallback.usesCoordinationGateway()}setCoordinationHostAvailability(e){this.fallback.setCoordinationHostAvailability(e);}assertManagedCoordinationGateway(){if(!this.usesCoordinationGateway())throw new Error("[OpenRTC] Native managed coordination requires coordinationGateway; the legacy native Firebase data plane has been removed.")}async joinCoordinationRoom(e,t,n){await this.syncCoordinationDeviceIdentity(),await this.fallback.joinCoordinationRoom(e,t,n);}leaveCoordinationRoom(e){return this.fallback.leaveCoordinationRoom(e)}getCoordinationRoomMembers(e){return this.fallback.getCoordinationRoomMembers(e)}watchCoordinationRoomMembers(e,t){return this.fallback.watchCoordinationRoomMembers(e,t)}async syncCoordinationDeviceIdentity(){if(!this.usesCoordinationGateway())return;let e=await this.getLocalDeviceInfo().catch(()=>null),t=e?.deviceId||await this.resolveLocalDeviceId();this.fallback.setCoordinationLocalDeviceId(t),this.fallback.setCoordinationPlatformType(this.normalizeNativeCoordinationPlatform(e?.platformType));}setWasmClient(e){if(!this.allowWasmFallback){let t="[NativeIpcBridge][NATIVE-GUARD] Refusing WasmClient attachment because native IPC is authoritative and WASM fallback is disabled.";throw console.error(t,{capabilities:this.capabilities()}),new Error(t)}this.fallback.setWasmClient(e);}onAuthChange(e){return this.fallback.onAuthChange(e)}checkForSSOToken(){return this.fallback.checkForSSOToken()}waitForAuth(){return this.fallback.waitForAuth()}signInAnonymously(){return this.fallback.signInAnonymously()}getTurnCredentials(){return this.fallback.getTurnCredentials()}cleanupStaleDevices(){return this.fallback.cleanupStaleDevices()}sendMessage(e,t,n,i){return this.fallback.sendMessage(e,t,n,i)}pollMessages(e){return this.fallback.pollMessages(e)}watchFriendDevices(e,t){return this.assertManagedCoordinationGateway(),this.fallback.watchFriendDevices(e,t)}async updateFriendTicket(e){this.assertManagedCoordinationGateway(),await this.syncCoordinationDeviceIdentity(),await this.fallback.updateFriendTicket(e);}createSession(e){return this.fallback.createSession(e)}updateSession(e,t){return this.fallback.updateSession(e,t)}async openPeerBi(e,t){return await this.canUseTauriIpc()?this.openPeerBiViaIpc("open_peer_bi_stream",{peerId:e,timeoutMs:t??null}):this.fallback.openPeerBi(e,t)}async openPeerBiRaw(e,t){return await this.canUseTauriIpc()?this.openPeerBiViaIpc("open_peer_bi_transport_only_stream",{peerId:e,timeoutMs:t??null},{fallbackCommand:"open_peer_bi_stream"}):this.fallback.openPeerBiRaw(e,t)}async openPeerNativeBi(e,t,n){return await this.canUseTauriIpc()?this.openPeerBiViaIpc("open_peer_native_bi_stream",{peerId:e,label:t,timeoutMs:n??null},{fallbackCommand:"open_peer_bi_stream",fallbackArgs:{peerId:e,timeoutMs:n??null}}):this.fallback.openPeerNativeBi(e,t,n)}async incoming_streams(){if(!await this.canUseTauriIpc()){let o=this.fallback;if(typeof o.incoming_streams=="function")return o.incoming_streams();throw new Error("Native incoming stream bridge is unavailable")}let e=`native-incoming-${Date.now()}-${++this.subscriptionNonce}`,t=null,n=false,i=async()=>{n=true;let o=t;t=null,await Promise.allSettled([o?Promise.resolve(o()):Promise.resolve(),this.invokeIpc("stop_rtc_subscription",{requestId:e},{timeoutMs:null}).catch(()=>{})]);};return new ReadableStream({start:async o=>{try{t=await this.listenIpc("openrtc://peer-bi-stream/incoming",s=>{if(n)return;let a=s.payload,c=typeof a?.requestId=="string"?a.requestId:typeof a?.request_id=="string"?a.request_id:"";if(c!==e){c$1("[NativeIpcBridge][incoming-application-stream] ignored request id",{expectedRequestId:e,eventRequestId:c});return}let d=typeof a?.streamId=="string"?a.streamId.trim():typeof a?.stream_id=="string"?a.stream_id.trim():"";if(!d)return;let l=typeof a?.remoteNodeId=="string"?a.remoteNodeId.trim():typeof a?.remote_node_id=="string"?a.remote_node_id.trim():"",p=Number.isSafeInteger(a?.transportStableId)?Number(a.transportStableId):Number.isSafeInteger(a?.transport_stable_id)?Number(a.transport_stable_id):0;if(!l||p<=0){c$1("[NativeIpcBridge][incoming-application-stream] ignored invalid generation",{requestId:e,remoteNodeId:l,transportStableId:p});return}c$1("[NativeIpcBridge][incoming-application-stream] accepted event",{requestId:e,remoteNodeId:l,transportStableId:p});let u=this.peerBiStreamFromId(d,{startReadAfterListeners:!0});o.enqueue({type:"bi",stream:{send:u.writable,recv:u.readable,endpoint_id:l},endpointId:l,transportStableId:p,protocolHint:"unknown",channel:null});}),await this.invokeIpc("start_incoming_peer_bi_streams",{requestId:e},{timeoutMs:null});}catch(s){n=true,o.error(s),await i();}},cancel:async()=>{await i();}})}async isCurrentTransport(e,t){if(!await this.canUseTauriIpc()){let n=this.fallback;return typeof n.is_current_transport_stable_id=="function"?n.is_current_transport_stable_id(e,t):false}return !e.trim()||t<=0n||t>BigInt(Number.MAX_SAFE_INTEGER)?false:this.invokeIpc("is_current_transport_stable_id",{endpointId:e.trim(),transportStableId:Number(t)})}openPeerUni(e,t){return this.fallback.openPeerUni(e,t)}isConnected(e){return this.fallback.isConnected(e)}getAuthContext(){return this.fallback.getAuthContext()}resolveNativeAuthScopedUserId(e){return this.currentUser?.id??this.getAuthContext()?.userId??e??null}resolveConfiguredSpaceKey(){let e=this.options.spaceKey??this.options.space;return typeof e=="string"?e.trim():""}usesAnonymousSpaceMode(){return this.options.authMode==="anonymous"&&this.resolveConfiguredSpaceKey().length>0}requiresNativeAuthToken(){return !this.usesAnonymousSpaceMode()||typeof this.options.spaceTokenProvider=="function"}async nativeAuthTokenMatchesExpectedScope(e){if(!this.usesAnonymousSpaceMode())return true;let t=typeof this.options.apiKey=="string"?this.options.apiKey.trim():"",n=this.resolveConfiguredSpaceKey();if(!t||!n)return true;let i=await b$1(t,n).catch(()=>null);return i?vt(Ae(e),i):true}resolveNativeSignalingUserId(e){return this.usesAnonymousSpaceMode()?(typeof e=="string"?e.trim():"")||this.resolveConfiguredSpaceKey()||null:this.resolveNativeAuthScopedUserId(e)}getCurrentUserId(){return this.resolveNativeSignalingUserId(this.fallback.getCurrentUserIdForScope())}nativeAuthWaitMs(){return this.requiresNativeAuthToken()?H.AUTH_REQUIRED_WAIT_MS:0}resolveWebLogicalDeviceId(){return this.fallback.getResolvedWebLogicalDeviceId()}normalizeDevice(e,t){return this.fallback.normalizeDeviceRecord(e,t)}matchesTag(e){return this.fallback.matchesLegacyOrCurrentTag(e)}nativeRosterTagDisposition(e){let t=j(e);if(this.matchesTag(t))return {keep:true,classification:"match"};let n=typeof t.appTag=="string"&&t.appTag.trim().length>0?t.appTag.trim():typeof t.tag=="string"&&t.tag.trim().length>0?t.tag.trim():void 0;return n===void 0?{keep:true,classification:"untagged"}:{keep:false,classification:"foreign",foreignTag:n}}filterNativeRosterByTag(e,t){let n=new Set,i=e.filter(o=>{let s=this.nativeRosterTagDisposition(o);return !s.keep&&s.foreignTag&&n.add(s.foreignTag),s.keep});return e.length>0&&i.length===0&&n.size>0?console.warn(`[NativeIpcBridge] ${t}: dropped ALL ${e.length} native device(s) as foreign-app \u2014 this is the app-tag drift signature (empty native device list). The native Rust OpenRTC app tag does not match the SDK app tag; check that the desktop binary and the web bundle use the same VITE_PLUTO_OPENRTC_API_KEY / VITE_PLUTO_OPENRTC_APP_TAG for this environment lane.`,{sdkAppTag:this.appTag,foreignTags:Array.from(n),droppedCount:e.length}):n.size>0&&c$1(`[NativeIpcBridge] ${t}: filtered ${e.length-i.length} foreign-app device(s) from the native roster`,{sdkAppTag:this.appTag,foreignTags:Array.from(n)}),i}normalizeNativeIceServer(e){let t=e.urls,n=Array.isArray(t)?t.filter(i=>typeof i=="string"&&i.trim().length>0):typeof t=="string"&&t.trim().length>0?[t]:[];return n.length===0?null:{urls:n,username:typeof e.username=="string"&&e.username.trim().length>0?e.username:void 0,credential:typeof e.credential=="string"&&e.credential.trim().length>0?e.credential:void 0}}filterNativeStunServers(e){return e.map(t=>({...t,urls:t.urls.filter(n=>!n.startsWith("stun:"))})).filter(t=>t.urls.length>0)}stripTurnServers(e){return e.map(t=>({...t,urls:t.urls.filter(n=>{let i=n.trim().toLowerCase();return !i.startsWith("turn:")&&!i.startsWith("turns:")})})).filter(t=>t.urls.length>0)}nativeIceServerHasTurnUrl(e){return e.urls.some(t=>t.startsWith("turn:")||t.startsWith("turns:"))}async loadNativeTurnIceServers(){if(typeof this.turnCredentialsProvider!="function")return [];let e=await this.turnCredentialsProvider().catch(t=>(console.warn("[NativeIpcBridge] TURN credential provider failed:",t),null));return !e||!Array.isArray(e.iceServers)?[]:e.iceServers.map(t=>this.normalizeNativeIceServer(t)).filter(t=>!!t)}async buildNativeTransportConfigPayload(){let e=this.transportOptions;if(!e&&!this.strictMode)return null;let t=e?.relay!==false,n;!this.strictMode&&e?.iroh&&(typeof e.iroh=="object"&&e.iroh.localDiscovery===false?n=null:n={enabled:true,advertise:typeof e.iroh!="object"||e.iroh.localDiscoveryMode!=="passive"});let i=null;if(e?.webrtc===true||e?.webrtc&&typeof e.webrtc=="object"){let p=e.webrtc===true?null:e.webrtc,u=p?.useDefaultIceServers!==false,h=Array.isArray(p?.iceServers)&&p.iceServers.length>0?p.iceServers.map(b=>this.normalizeNativeIceServer(b)).filter(b=>!!b):u?h$1.map(b=>this.normalizeNativeIceServer(b)).filter(b=>!!b):[],m=t&&(this.strictMode||e?.privacy==="relay-only"||p?.privacyMode===true);t&&(m||p?.useTurn===true)&&(h=[...h,...await this.loadNativeTurnIceServers()]),m&&(h=this.filterNativeStunServers(h)),t||(h=this.stripTurnServers(h));let v=h.some(b=>this.nativeIceServerHasTurnUrl(b)),y=m&&v;m&&!v&&console.warn("[NativeIpcBridge] Relay-only WebRTC requested, but no TURN servers are configured; native WebRTC override disabled");let C=p?.lanMode===true;(h.length>0||y||C||!u)&&(i={iceServers:h.length>0||!u?h:void 0,privacyMode:y,lanMode:C||void 0});}let o=null;if(t&&e?.moq&&typeof e.moq=="object"){let p=typeof e.moq.relayUrl=="string"&&e.moq.relayUrl.trim().length>0?e.moq.relayUrl:void 0;if(p){let u=typeof e.moq.accessToken=="string"&&e.moq.accessToken.trim().length>0?e.moq.accessToken.trim():void 0;o={relayUrl:p,accessToken:u};}}let s=null;if(!this.strictMode&&(e?.ble===true||e?.ble&&typeof e.ble=="object")){let p=e.ble===true?null:e.ble,u=Number(p?.connectTimeoutMs);s={enabled:p?.enabled!==false,connectTimeoutMs:Number.isFinite(u)&&u>0?Math.round(u):void 0};}let a=t&&(this.strictMode||e?.privacy==="relay-only"),c=t&&(a||!!(e?.iroh&&typeof e.iroh=="object"&&e.iroh.relayOnly===true));c&&(n=null,s=null);let d=e?.iroh&&typeof e.iroh=="object"?e.iroh.relayTransportPolicy:void 0,l=this.strictMode?d??"auto":d;return !c&&!l&&!i&&!o&&!n&&!s?null:{relay:t,privacyMode:a||void 0,irohRelayOnly:c||void 0,irohRelayTransportPolicy:l,...n!==void 0?{irohLan:n}:{},webrtc:i,moq:o,ble:s,routePriority:e?.priority,optimizeFor:e?.optimizeFor}}isTauriEnv(){return b$2()}nextConnectionEventRetryDelayMs(e){return h(e,H.CONNECTION_EVENT_RETRY_MIN_DELAY_MS,H.CONNECTION_EVENT_RETRY_MAX_DELAY_MS)}async clearNativeAuthRelay(e){if(await this.canUseTauriIpc())try{typeof this.options.coordinationGateway?.grantProvider=="function"?await this.invokeIpc("openrtc_set_identity_credential",{identityCredential:null}):await this.invokeIpc("desktop_set_pluto_auth_token",{authToken:null,refreshToken:null}),this.lastSyncedAuthToken=null,this.lastNativeAuthSyncAtMs=0,c$1(`[NativeIpcBridge] cleared native auth relay (${e})`);}catch(t){console.warn(`[NativeIpcBridge] failed clearing native auth relay (${e}):`,t);}}async clearNativeTrustRelay(e){if(this.nativeTrustTokenUnsubscribe?.(),this.nativeTrustTokenUnsubscribe=null,this.nativeTrustRelayError=null,this.fallback.invalidateCoordinationNativeTrustToken(),typeof this.options.coordinationGateway?.grantProvider!="function"&&await this.canUseTauriIpc())try{await this.invokeIpc("openrtc_set_native_trust_token",{trustToken:null,expiresAtMs:null}),c$1(`[NativeIpcBridge] cleared native trust relay (${e})`);}catch(t){b$3(t)||console.warn(`[NativeIpcBridge] failed clearing native trust relay (${e}):`,t);}}relayNativeTrustToken(e,t){let n=async()=>{await this.canUseTauriIpc()&&(await this.invokeIpc("openrtc_set_native_trust_token",{trustToken:e?.token??null,expiresAtMs:e?.expiresAtMs??null}),c$1(`[NativeIpcBridge] native trust token ${e?"relayed":"cleared"} (${t})`));},i=this.nativeTrustRelayQueue.then(n,n);return this.nativeTrustRelayQueue=i.catch(()=>{}),i}async ensureNativeTrustRelay(e=false){if(!this.usesCoordinationGateway()||typeof this.options.coordinationGateway?.grantProvider=="function")return true;if(typeof this.options.coordinationGateway?.nativeTrustTokenProvider!="function")return false;if(!await this.canUseTauriIpc())return true;try{let t=await this.fallback.getCoordinationNativeTrustToken(e);return await this.relayNativeTrustToken(t,"auth-ready"),this.nativeTrustRelayError=null,this.nativeTrustTokenUnsubscribe||(this.nativeTrustTokenUnsubscribe=this.fallback.subscribeCoordinationNativeTrustToken(n=>{this.relayNativeTrustToken(n,"provider-refresh").catch(i=>{console.warn("[NativeIpcBridge] native trust token refresh relay failed:",i);});},{emitCurrent:!1})),!0}catch(t){return this.nativeTrustRelayError=(t instanceof Error?t.message:String(t)).trim().slice(0,300)||"unknown provider failure",console.warn("[NativeIpcBridge] native trust token unavailable:",t),false}}async relayNativeAuthToken(e,t,n,i){if(!await this.canUseTauriIpc())return true;if(!await this.nativeAuthTokenMatchesExpectedScope(e))return c$1(`[NativeIpcBridge] auth sync deferred (${n}): token claims do not match configured space`),false;if(e===this.lastSyncedAuthToken)return true;try{typeof this.options.coordinationGateway?.grantProvider=="function"?await this.invokeIpc("openrtc_set_identity_credential",{identityCredential:e}):await this.invokeIpc("desktop_set_pluto_auth_token",{authToken:e,refreshToken:t??null});}catch(o){return b$3(o)?console.warn(`[NativeIpcBridge] desktop auth relay unavailable (${n}); install/register openrtc-tauri-plugin and include its default permission set.`,o):console.warn(`[NativeIpcBridge] desktop auth relay failed (${n}):`,o),false}return this.lastSyncedAuthToken=e,this.lastNativeAuthSyncAtMs=Date.now(),c$1(`[NativeIpcBridge] auth token relayed to native runtime (${n}) user_id=${i??this.currentUser?.id??"unknown"}`),true}async relayExplicitNativeAuthContext(e){let t=this.authSyncInFlight,n=(async()=>(await t?.catch(()=>{}),this.relayNativeAuthToken(e.token,e.refreshToken,"setAuthContext",e.userId)))();this.authSyncInFlight=n;try{return await n}finally{this.authSyncInFlight===n&&(this.authSyncInFlight=null);}}applyNativeRuntimeStatus(e){this.runtimeCapabilities=w$1(e,this.allowWasmFallback);}syncNativeRuntimeCapabilities(e){return this.ipcBridge?this.nativeRuntimeCapabilitiesSyncInFlight?this.nativeRuntimeCapabilitiesSyncInFlight:(this.nativeRuntimeCapabilitiesSyncInFlight=(async()=>{try{let t=await this.invokeIpc("rtc_native_status",void 0,{timeoutMs:H.NATIVE_STATUS_IPC_TIMEOUT_MS});this.applyNativeRuntimeStatus(t),c$1(`[NativeIpcBridge] refreshed native runtime capabilities (${e})`);}catch(t){b("[NativeIpcBridge] native runtime capability refresh skipped",t);}})().finally(()=>{this.nativeRuntimeCapabilitiesSyncInFlight=null;}),this.nativeRuntimeCapabilitiesSyncInFlight):Promise.resolve()}async canUseTauriIpc(){if(this.ipcBridge){let e=typeof this.ipcBridge.isAvailable=="function"?!!await this.ipcBridge.isAvailable():true;return e&&this.syncNativeRuntimeCapabilities("ipc-available"),e}return typeof window>"u"?false:this.tauriCoreAvailabilityValue===true?true:this.tauriCoreAvailabilityValue===false&&Date.now()-this.tauriCoreAvailabilityCheckedAtMs<H.TAURI_IPC_NEGATIVE_CACHE_MS?false:(this.tauriCoreAvailability||(this.tauriCoreAvailability=(async()=>{try{if(this.isTauriEnv())return this.tauriCoreAvailabilityValue=!0,this.tauriCoreAvailabilityCheckedAtMs=Date.now(),this.syncNativeRuntimeCapabilities("tauri-env"),!0;try{let e=await this.invokeIpc("rtc_native_status");return this.applyNativeRuntimeStatus(e),c$1("[NativeIpcBridge] Resolved Tauri IPC via rtc_native_status probe"),this.tauriCoreAvailabilityValue=!0,this.tauriCoreAvailabilityCheckedAtMs=Date.now(),!0}catch(e){let t=String(e?.message??e??"");return t.includes("__TAURI_INTERNALS__")||t.includes("Cannot read properties of undefined")||t.includes("window is not defined")?(this.tauriCoreAvailabilityValue=!1,this.tauriCoreAvailabilityCheckedAtMs=Date.now(),!1):(c$1("[NativeIpcBridge] Tauri IPC probe reached native layer (command-level error acceptable)"),this.tauriCoreAvailabilityValue=!0,this.tauriCoreAvailabilityCheckedAtMs=Date.now(),!0)}}catch{return this.tauriCoreAvailabilityValue=false,this.tauriCoreAvailabilityCheckedAtMs=Date.now(),false}})().finally(()=>{this.tauriCoreAvailability=null;})),this.tauriCoreAvailability)}async invokeIpc(e,t,n){let i=this.ipcBridge.invoke(e,t),o=n&&Object.prototype.hasOwnProperty.call(n,"timeoutMs")?n.timeoutMs:H.DEFAULT_BOUNDED_IPC_TIMEOUT_MS;return o==null||o<=0?i:O(i,o,()=>new Error(`${e} timeout after ${o}ms`))}async listenIpc(e,t){return this.ipcBridge.listen(e,n=>{t({payload:n});})}async openPeerBiViaIpc(e,t,n){let i=await this.invokePeerBiOpen(e,t,n),o=typeof i?.streamId=="string"?i.streamId.trim():typeof i?.stream_id=="string"?i.stream_id.trim():"";if(!o)throw new Error(`${e} returned no streamId`);return this.peerBiStreamFromId(o)}peerBiStreamFromId(e,t={}){let n=this,i=null,o=null,s=false,a=null,c=null,d=async()=>{let m=[i,o];i=null,o=null,await Promise.allSettled(m.filter(f=>typeof f=="function").map(f=>Promise.resolve(f())));},l=(async()=>{i=await this.listenIpc("openrtc://peer-bi-stream/chunk",m=>{let f=m.payload;if((typeof f?.streamId=="string"?f.streamId:typeof f?.stream_id=="string"?f.stream_id:"")!==e||s||!a)return;let y=f?.bytes;y instanceof Uint8Array?a.enqueue(y):Array.isArray(y)&&a.enqueue(new Uint8Array(y));}),o=await this.listenIpc("openrtc://peer-bi-stream/closed",m=>{let f=m.payload;if((typeof f?.streamId=="string"?f.streamId:typeof f?.stream_id=="string"?f.stream_id:"")!==e||s||!a)return;s=true;let y=typeof f?.error=="string"?f.error.trim():"";y?a.error(new Error(y)):a.close(),d();}),t.startReadAfterListeners&&await this.invokeIpc("start_peer_bi_stream_read",{streamId:e},{timeoutMs:null});})().catch(m=>{c=m,a&&!s&&(s=true,a.error(m));}),p=async()=>{await this.invokeIpc("close_peer_bi_stream",{streamId:e},{timeoutMs:null}).catch(()=>{}),await d();},u=new ReadableStream({async start(m){a=m,await l,c&&!s&&(s=true,m.error(c));},async cancel(){s=true,await p();}}),h=new WritableStream({write:async m=>{await n.invokeIpc("write_peer_bi_stream",{streamId:e,bytes:Array.from(m)},{timeoutMs:null});},close:p,abort:p});return {readable:u,writable:h}}async invokePeerBiOpen(e,t,n){try{return await this.invokeIpc(e,t)}catch(i){if(!n?.fallbackCommand||!this.isMissingNativeCommandError(i))throw i;return this.invokeIpc(n.fallbackCommand,n.fallbackArgs??t)}}isMissingNativeCommandError(e){let t=e instanceof Error?e.message:String(e??"");return t.includes("Command")&&t.includes("not found")}async shouldUseTauriSignaling(){if(await this.canUseTauriIpc())return true;if(this.allowWasmFallback)return false;throw new Error("[pluto-rtc] Tauri runtime adapter requires native IPC, but it is unavailable.")}async signInWithPluto(){if(!await this.canUseTauriIpc()){await this.fallback.signInWithPluto();return}let e=await this.invokeIpc("rtc_sign_in_with_pluto"),t=typeof e?.customToken=="string"?e.customToken.trim():"";if(!t)throw new Error("[pluto-rtc] Native Pluto SSO did not return a custom token.");await a$2().signInWithCustomTokenValue(t),await this.ensureNativeAuth("pluto-sso",{requireToken:true,maxWaitMs:1e4});}async setAuthContext(e){let t=this.getAuthContext()?.userId??null,n=typeof e?.userId=="string"&&e.userId.trim()||null,i=this.fallback.setAuthContext(e);if(t&&n&&t!==n&&await this.stopNativeAuthScopedActivity(t),await i,!e?.token)await this.clearNativeAuthRelay("setAuthContext"),await this.clearNativeTrustRelay("setAuthContext");else {if(!await this.relayExplicitNativeAuthContext(e))throw new Error("Native auth token unavailable for setAuthContext");if(!await this.ensureNativeTrustRelay())throw new Error(`Native trust token unavailable for setAuthContext: ${this.nativeTrustRelayError??"unknown provider failure"}`)}}async signOut(){await this.fallback.signOut(),await Promise.all([this.clearNativeAuthRelay("signOut"),this.clearNativeTrustRelay("signOut")]);}async stopAuthActivity(e){let t=this.resolveNativeSignalingUserId(e?.userId??null);await this.stopNativeAuthScopedActivity(t);}async stopNativeAuthScopedActivity(e){await this.stopGatewayDesiredPeerRelay(),this.gatewayExcludedPeers.clear();let t=await this.shouldUseTauriSignaling();if(i("NativeIpcBridge.stopAuthActivity",{userId:e,useTauri:t}),t)try{await Promise.allSettled([this.revokeTokens("user-device"),this.invokeIpc("stop_rtc_presence_loop"),this.invokeIpc("stop_rtc_auto_connect")]);}catch(n){console.warn("[NativeIpcBridge] Failed to stop native auth-scoped RTC activity:",n);}await this.fallback.stopAuthActivity({userId:e});}async ensureNativeAuthOnce(e,t){if(!await this.canUseTauriIpc())return true;if(this.authSyncInFlight)return this.authSyncInFlight;let n=(async()=>{try{if(!this.currentUser)return c$1(`[NativeIpcBridge] auth sync deferred (${e}): no current user`),!t;let i=Date.now()-this.lastNativeAuthSyncAtMs>=480*1e3,o=this.currentUser?.getToken?await this.currentUser.getToken(i):null,a=this.getAuthContext()?.refreshToken??this.auth?.currentUser?.refreshToken??null;return o?this.relayNativeAuthToken(o,a,e,this.currentUser?.id):(c$1(`[NativeIpcBridge] auth sync deferred (${e}): missing token for user ${this.currentUser?.id}`),!t)}catch(i){return console.error("[NativeIpcBridge] auth sync failed:",i),false}})();this.authSyncInFlight=n;try{return await n}finally{this.authSyncInFlight===n&&(this.authSyncInFlight=null);}}async ensureNativeAuth(e$1="runtime",t){if(!await this.canUseTauriIpc())return true;let n=t?.requireToken??false,i=t?.maxWaitMs??(n?H.AUTH_REQUIRED_WAIT_MS:0),o=t?.pollMs??250,s=Date.now()+Math.max(0,i);for(;;){if(await this.ensureNativeAuthOnce(e$1,n))return true;if(!n||Date.now()>=s)return false;await e(o);}}decodeNativeDeviceIdentity(e){let t=e?.systemInfo??e?.system_info??null,n=typeof e?.deviceId=="string"?e.deviceId.trim():typeof e?.device_id=="string"?e.device_id.trim():"",i=typeof e?.deviceName=="string"?e.deviceName.trim():typeof e?.device_name=="string"?e.device_name.trim():"",o=typeof e?.platformType=="string"?e.platformType.trim():typeof e?.platform_type=="string"?e.platform_type.trim():typeof t?.platformType=="string"?t.platformType.trim():typeof t?.platform_type=="string"?t.platform_type.trim():"";return {deviceId:n,deviceName:i,platformType:o}}async resolveLocalDeviceId(){if(this.cachedLocalDeviceId)return this.cachedLocalDeviceId;if(await this.canUseTauriIpc())try{let t=await this.invokeIpc("get_rtc_local_device_info"),{deviceId:n,deviceName:i}=this.decodeNativeDeviceIdentity(t);if(n)return this.cachedLocalDeviceId=n,i&&(this.cachedLocalDeviceName=i),n}catch(t){console.warn("[NativeIpcBridge] get_rtc_local_device_info failed:",t);}let e=this.resolveWebLogicalDeviceId();return this.cachedLocalDeviceId=e,e}async resolveLocalDeviceName(){if(this.cachedLocalDeviceName)return this.cachedLocalDeviceName;if(await this.canUseTauriIpc())try{let e=await this.invokeIpc("get_rtc_local_device_info"),{deviceName:t}=this.decodeNativeDeviceIdentity(e);if(t){let n=this.normalizeNativeDeviceName(t);return this.cachedLocalDeviceName=n,n}}catch(e){console.warn("[NativeIpcBridge] get_rtc_local_device_info failed:",e);}return this.defaultDeviceNameFallback()}normalizeNativeDeviceName(e){let t=e.trim();if(!t)return this.defaultDeviceNameFallback();if(t==="Desktop Device"){let n=this.defaultDeviceNameFallback();if(n!=="Desktop Device")return n}return t}defaultDeviceNameFallback(){if(typeof window>"u"||typeof navigator>"u")return "Desktop Device";let e=navigator.userAgent||"";return /iPhone|iPad|iPod/i.test(e)?"iPhone":/Android/i.test(e)?"Android":"Desktop Device"}inferNativePlatformTypeFallback(){if(typeof window>"u"||typeof navigator>"u")return "desktop";if(!this.isTauriEnv())return "web";let e=navigator.userAgent||"";return /iPhone|iPad|iPod|Android|Mobile/i.test(e)?"mobile":"desktop"}normalizeNativeCoordinationPlatform(e){let t=this.options.coordinationPlatformType?.trim().toLowerCase()??"";if(t&&t!=="desktop"&&t!=="mobile"&&t!=="web")return t;let n=e?.trim().toLowerCase()??"";return n||(t==="mobile"||t==="desktop"?t:this.inferNativePlatformTypeFallback()==="mobile"?"mobile":"desktop")}withPresenceMetadata(e,t){try{let n=e?JSON.parse(e):{};return JSON.stringify({...n,deviceId:t,plutoVersion:"0.1.0-desktop"})}catch{return JSON.stringify({deviceId:t,plutoVersion:"0.1.0-desktop",rawMetadata:e})}}async searchDevices(e){return this.assertManagedCoordinationGateway(),this.fallback.searchDevices(e)}async listDeviceStatus(){return this.assertManagedCoordinationGateway(),(await this.fallback.searchDevices()).map(e=>l(e))}async getPeerSession(e){if(await this.shouldUseTauriSignaling()){let t=await this.invokeIpc("get_rtc_peer_session",{id:e});return !t||typeof t!="object"?null:m(t)}return this.fallback.getPeerSession(e)}async listPeerSessions(){if(await this.shouldUseTauriSignaling()){let e=await this.invokeIpc("list_rtc_peer_sessions");return (Array.isArray(e)?e:[]).map(t=>m(t))}return this.fallback.listPeerSessions()}async waitForSettledPeer(e,t){if(await this.shouldUseTauriSignaling()){let n=typeof t=="number"?Math.max(H.DEFAULT_BOUNDED_IPC_TIMEOUT_MS,t+1e3):H.DEFAULT_BOUNDED_IPC_TIMEOUT_MS,i=await this.invokeIpc("wait_for_rtc_settled_peer",{id:e,timeoutMs:t},{timeoutMs:n});return !i||typeof i!="object"?null:m(i)}return this.fallback.waitForSettledPeer(e,t)}async resolvePeerRecords(e){if(await this.shouldUseTauriSignaling()){let t=await this.invokeIpc("resolve_rtc_peer_connection_records",{id:e});return (Array.isArray(t)?t:[]).map(n$1=>n(n$1))}return this.fallback.resolvePeerRecords(e)}async resolvePeerIdentity(e){if(await this.shouldUseTauriSignaling()){let t=await this.invokeIpc("resolve_rtc_peer_identity",{id:e});return o$1(t)}return this.fallback.resolvePeerIdentity(e)}async setOffline(e){return this.assertManagedCoordinationGateway(),this.fallback.setOffline(e)}async updateDevice(e,t){return this.assertManagedCoordinationGateway(),await this.syncCoordinationDeviceIdentity(),this.fallback.updateDevice(e,t)}async deleteDevice(e){return this.assertManagedCoordinationGateway(),await this.syncCoordinationDeviceIdentity(),this.fallback.deleteDevice(e)}async getLocalDeviceInfo(){if(!await this.canUseTauriIpc()){let e=await this.getLocalDeviceId?.();return e?{deviceId:e,deviceName:this.defaultDeviceNameFallback(),platformType:this.inferNativePlatformTypeFallback()}:null}try{let e=await this.invokeIpc("get_rtc_local_device_info"),t=this.decodeNativeDeviceIdentity(e),{deviceId:n}=t;return n?{deviceId:n,deviceName:this.normalizeNativeDeviceName(t.deviceName),platformType:t.platformType||this.inferNativePlatformTypeFallback(),capabilities:e?.capabilities??void 0,lastSeenAt:typeof e?.last_seen_at=="string"?e.last_seen_at:void 0}:null}catch(e){return console.warn("[NativeIpcBridge] getLocalDeviceInfo failed:",e),null}}async updateDeviceName(e){if(!await this.canUseTauriIpc())return null;try{let t=await this.invokeIpc("update_rtc_local_device_name",{deviceName:e}),n=this.decodeNativeDeviceIdentity(t),{deviceId:i}=n;return i?(this.cachedLocalDeviceName=this.normalizeNativeDeviceName(e),{deviceId:i,deviceName:this.cachedLocalDeviceName,platformType:n.platformType||this.inferNativePlatformTypeFallback(),capabilities:t?.capabilities??void 0,lastSeenAt:typeof t?.last_seen_at=="string"?t.last_seen_at:void 0}):null}catch(t){return console.warn("[NativeIpcBridge] updateDeviceName failed:",t),null}}async startNativeSession(e){if(this.assertManagedCoordinationGateway(),!await this.shouldUseTauriSignaling())throw new Error("[pluto-rtc] Native IPC unavailable for startNativeSession().");if(!await this.ensureNativeAuth("startNativeSession",{requireToken:this.requiresNativeAuthToken(),maxWaitMs:this.nativeAuthWaitMs()}))throw new Error("Native auth token unavailable for startNativeSession");let n=this.resolveNativeSignalingUserId(e.userId);if(!n)throw new Error("Native managed session startup requires a runtime auth-scoped user id.");n!==e.userId&&console.info("[NativeIpcBridge][managed-session][user-id-remap]",{requestedUserId:e.userId,runtimeUserId:this.currentUser?.id??this.getAuthContext()?.userId??null,effectiveUserId:n}),console.info("[NativeIpcBridge][managed-session][start-request]",{requestedUserId:e.userId,runtimeUserId:this.currentUser?.id??this.getAuthContext()?.userId??null,effectiveUserId:n,deviceName:e.deviceName??null,localDeviceId:e.localDeviceId??null,presence:e.presence!==false,autoConnect:e.autoConnect!==false,hasMetadata:typeof e.metadata=="string"&&e.metadata.trim().length>0});let i=await this.buildNativeTransportConfigPayload(),o={userId:n,deviceName:e.deviceName??null,localDeviceId:e.localDeviceId??null,metadata:e.metadata??null,...i?{transports:i}:{},autoConnect:false,presence:false},s=await this.invokeIpc("start_rtc_managed_session",o,{timeoutMs:null});this.syncNativeRuntimeCapabilities("managed-session-started");let a=typeof s?.ticket=="string"&&s.ticket.trim().length>0?s.ticket.trim():null,c=s?.localDevice&&typeof s.localDevice=="object"?s.localDevice:s?.local_device&&typeof s.local_device=="object"?s.local_device:null,d=c?{deviceId:typeof c.deviceId=="string"?c.deviceId:typeof c.device_id=="string"?c.device_id:"",deviceName:this.normalizeNativeDeviceName(typeof c.deviceName=="string"?c.deviceName:typeof c.device_name=="string"?c.device_name:""),platformType:typeof c.platformType=="string"?c.platformType:typeof c.platform_type=="string"?c.platform_type:"desktop",capabilities:c.capabilities??void 0,lastSeenAt:typeof c.lastSeenAt=="string"?c.lastSeenAt:typeof c.last_seen_at=="string"?c.last_seen_at:void 0}:null,l={localNodeId:typeof s?.localNodeId=="string"?s.localNodeId:typeof s?.local_node_id=="string"?s.local_node_id:null,ticket:a,ticketScope:typeof s?.ticketScope=="string"?s.ticketScope:typeof s?.ticket_scope=="string"?s.ticket_scope:null,presenceStarted:typeof s?.presenceStarted=="boolean"?s.presenceStarted:!!s?.presence_started,autoConnectStarted:typeof s?.autoConnectStarted=="boolean"?s.autoConnectStarted:!!s?.auto_connect_started,localDevice:d?.deviceId?d:null};if(this.usesCoordinationGateway()){e.presence!==false&&!l.ticket&&(l.ticket=await this.getTicketWithToken("user-device",0),l.ticketScope=l.ticket?"user-device":null);let p=l.localDevice?.deviceId||e.localDeviceId?.trim()||await this.resolveLocalDeviceId();if(p&&this.fallback.setCoordinationLocalDeviceId(p),this.fallback.setCoordinationPlatformType(this.normalizeNativeCoordinationPlatform(l.localDevice?.platformType)),e.presence!==false){if(!l.localNodeId||!l.ticket)throw new Error("Native managed session did not return the node identity required for gateway presence.");await this.fallback.updatePresence(l.localNodeId,l.ticket,true,3e5,e.metadata,l.localDevice?.deviceName||e.deviceName),l.presenceStarted=true;}else l.presenceStarted=false;e.autoConnect!==false&&p?(await this.startGatewayAutoConnect(n,p),l.autoConnectStarted=true):l.autoConnectStarted=false;}return console.info("[NativeIpcBridge][managed-session][ipc-started]",{requestedUserId:e.userId,runtimeUserId:this.currentUser?.id??this.getAuthContext()?.userId??null,effectiveUserId:n,localNodeId:l.localNodeId,ticketScope:l.ticketScope,presenceStarted:l.presenceStarted,autoConnectStarted:l.autoConnectStarted,localDeviceId:l.localDevice?.deviceId??null}),l}async syncNativeSession(e){return this.assertManagedCoordinationGateway(),await this.fallback.reconnectCoordinationAfterHostResume(),console.info("[NativeIpcBridge] reattached gateway coordination after host resume.",{reason:e?.reason??"frontend"}),null}async notifyNetworkChange(e){return await this.canUseTauriIpc()?(c$1("[NativeIpcBridge] forwarding host network-change hint",{reason:e?.reason??"host"}),this.invokeIpc("notify_rtc_network_change")):null}async getManagedNodeId(e){let t=e?.initializeIfMissing??true;console.info("[NativeIpcBridge][getManagedNodeId] enter",{initializeIfMissing:t});let n=await this.canUseTauriIpc();if(console.info("[NativeIpcBridge][getManagedNodeId] canUseTauriIpc",{canUse:n}),!n)return null;try{console.info("[NativeIpcBridge][getManagedNodeId] invoking get_iroh_node_id");let i=await this.invokeIpc("get_iroh_node_id");if(console.info("[NativeIpcBridge][getManagedNodeId] get_iroh_node_id returned",{existing:i}),i||!t)return i;console.info("[NativeIpcBridge][getManagedNodeId] invoking start_iroh_node");let o=await this.invokeIpc("start_iroh_node");return console.info("[NativeIpcBridge][getManagedNodeId] start_iroh_node returned",{started:o}),o}catch(i){if(console.warn("[NativeIpcBridge] getManagedNodeId failed:",i),!t)return null;throw i}}async getEndpointTicket(){if(!await this.canUseTauriIpc())throw new Error("[pluto-rtc] getEndpointTicket requires native IPC in Tauri runtime.");return ae(()=>this.invokeIpc("get_iroh_endpoint_ticket"))}async connectToDevice(e){if(!await this.canUseTauriIpc())throw new Error("[pluto-rtc] connectToDevice requires native IPC in Tauri runtime.");this.options.authMode!=="anonymous"?await this.ensureNativeAuth("connectToDevice",{requireToken:true,maxWaitMs:H.AUTH_REQUIRED_WAIT_MS}):c$1("[NativeIpcBridge] connectToDevice using anonymous native ticket path");let t=Math.max(1,Math.floor(e.timeoutMs??H.DEFAULT_BOUNDED_IPC_TIMEOUT_MS));return this.invokeIpc("connect_to_device",{deviceId:e.deviceId??null,endpointTicket:e.endpointTicket,timeoutMs:t},{timeoutMs:t+1e3})}async registerSessionToken(e,t,n,i){await this.canUseTauriIpc()&&await this.invokeIpc("register_session_token",{token:e,scope:t,maxConnections:n,expiresAtMs:i??null});}async getTicketWithToken(e,t){if(!await this.canUseTauriIpc())return null;try{return await ae(()=>this.invokeIpc("get_endpoint_ticket_with_token",{scope:e,maxConnections:t}))}catch{return null}}async validateSessionToken(e,t){if(!await this.canUseTauriIpc())return null;try{return await this.invokeIpc("validate_session_token",{token:e,connectionId:t??null})}catch{return null}}async revokeTokens(e){if(i("NativeIpcBridge.revokeTokens",{grantScope:e}),!await this.canUseTauriIpc())return [];try{return await this.invokeIpc("revoke_session_tokens_by_scope",{scope:e})}catch{return []}}async disconnectDevice(e){if(!await this.canUseTauriIpc())throw new Error("[pluto-rtc] disconnectDevice requires native IPC in Tauri runtime.");await this.invokeIpc("disconnect_device",{deviceId:e});}async excludeAutoConnect(e,t){if(!await this.canUseTauriIpc())return;let n=e.trim().toLowerCase();n&&(this.usesCoordinationGateway()&&(t?this.gatewayExcludedPeers.add(n):this.gatewayExcludedPeers.delete(n)),await this.invokeIpc(this.usesCoordinationGateway()?"set_rtc_external_auto_connect_excluded":"set_auto_connect_excluded",{deviceId:e,excluded:t}),this.usesCoordinationGateway()&&await this.fallback.setCoordinationExcludedPeers([...this.gatewayExcludedPeers].sort()));}onDevicesChange(e,t){return this.assertManagedCoordinationGateway(),this.fallback.onDevicesChange(e,t)}async subscribeDevices(e){return this.assertManagedCoordinationGateway(),this.fallback.subscribeDevices(e)}async subscribeSessions(e){return this.assertManagedCoordinationGateway(),this.fallback.subscribeSessions(e)}async getLocalDeviceId(){return this.resolveLocalDeviceId()}async updatePresence(e,t,n=true,i=3e5,o){return this.assertManagedCoordinationGateway(),await this.syncCoordinationDeviceIdentity(),this.fallback.updatePresence(e,t,n,i,o)}startAutoConnect(e,t){this.assertManagedCoordinationGateway(),this.startGatewayAutoConnect(e,t).catch(n=>{console.warn("[NativeIpcBridge] gateway auto-connect failed:",n);});}forceReconnect(){this.assertManagedCoordinationGateway(),this.fallback.forceReconnect();}startPresenceLoop(e,t,n,i,o){this.assertManagedCoordinationGateway(),this.syncCoordinationDeviceIdentity().then(()=>this.fallback.startPresenceLoop(e,t,n,i,o)).catch(s=>{console.warn("[NativeIpcBridge] gateway presence failed:",s);});}async startAutoConnectOnce(e,t){this.assertManagedCoordinationGateway(),await this.startGatewayAutoConnect(e,t);}async clearGatewayDesiredPeerRelay(){let e=this.gatewayDesiredPeerSubmission;this.gatewayDesiredPeerRelayGeneration+=1,this.gatewayDesiredPeersCleanup?.(),this.gatewayDesiredPeersCleanup=null,this.gatewayDesiredPeerRelayKey=null,this.gatewayDesiredPeerRevision=0,this.gatewayDesiredPeerSubmission=Promise.resolve(),await e;}serializeGatewayDesiredPeerLifecycle(e){let t=this.gatewayDesiredPeerLifecycle.then(e);return this.gatewayDesiredPeerLifecycle=t.catch(()=>{}),t}stopGatewayDesiredPeerRelay(){return this.serializeGatewayDesiredPeerLifecycle(async()=>{await this.clearGatewayDesiredPeerRelay();})}startGatewayAutoConnect(e,t){return this.serializeGatewayDesiredPeerLifecycle(()=>this.startGatewayAutoConnectSerialized(e,t))}async startGatewayAutoConnectSerialized(e,t){if(!await this.shouldUseTauriSignaling())throw new Error("[openrtc] Native IPC unavailable for coordination gateway auto-connect.");if(!await this.ensureNativeAuth("startGatewayAutoConnect",{requireToken:this.requiresNativeAuthToken(),maxWaitMs:this.nativeAuthWaitMs()}))throw new Error("Native auth token unavailable for coordination gateway auto-connect");let i=this.resolveNativeSignalingUserId(e);if(!i)throw new Error("Coordination gateway auto-connect requires an authenticated user id.");let o=await this.resolveLocalDeviceId()||t.trim();if(!o)throw new Error("Coordination gateway auto-connect requires a local device id.");let s=JSON.stringify([i,o]);this.fallback.setCoordinationLocalDeviceId(o);let a=this.gatewayDesiredPeerRelayKey===s&&this.gatewayDesiredPeersCleanup;if(a||(await this.clearGatewayDesiredPeerRelay(),this.gatewayDesiredPeerRelayKey=s),await this.invokeIpc("start_rtc_external_auto_connect",{userId:i,localDeviceId:o}),a)return;let c=this.gatewayDesiredPeerRelayGeneration;this.gatewayDesiredPeersCleanup=this.fallback.onDevicesChange(d=>{let l=d.map(h=>({deviceId:String(h.deviceId??"").trim(),nodeId:typeof h.nodeId=="string"&&h.nodeId.trim()||null,ticket:typeof h.ticket=="string"&&h.ticket.trim()||null,online:h.online===true,sessionId:typeof h.sessionId=="string"&&h.sessionId.trim()||null,excludedPeers:Array.isArray(h.excludedPeers)?[...new Set(h.excludedPeers.map(m=>String(m??"").trim().toLowerCase()).filter(Boolean))].sort():[]})).filter(h=>h.deviceId.length>0&&h.deviceId!==o).sort((h,m)=>h.deviceId.localeCompare(m.deviceId)),p=this.options.coordinationRoomGossipFanout?y(l,o):l,u=++this.gatewayDesiredPeerRevision;this.gatewayDesiredPeerSubmission=this.gatewayDesiredPeerSubmission.then(async()=>{this.gatewayDesiredPeerRelayGeneration!==c||this.gatewayDesiredPeerRelayKey!==s||await this.invokeIpc("submit_rtc_desired_peers",{revision:u,peersJson:JSON.stringify(p)});}).catch(h=>{console.warn("[NativeIpcBridge] failed to relay gateway desired peers to Rust:",{revision:u,error:h});});},o);}async startPresence(e,t,n,i,o){this.assertManagedCoordinationGateway(),await this.syncCoordinationDeviceIdentity(),await this.fallback.startPresenceLoop(e,t,n,i,o);}shouldUseResolvedDeviceName(e){let t=e.trim();return t.length===0||t==="Unknown Device"||t==="Desktop Device"}async sendExplicitFilePath(e,t,n=""){if(c$1("[NativeIpcBridge] sendExplicitFilePath start",{connectionId:e,filePath:t,transferId:n||null,authMode:this.options.authMode}),await this.canUseTauriIpc()){this.options.authMode!=="anonymous"?await this.ensureNativeAuth("sendExplicitFilePath"):c$1("[NativeIpcBridge] sendExplicitFilePath using anonymous native path");let i=await this.invokeIpc("send_file",{connectionId:e,filePath:t,transferId:n});return c$1("[NativeIpcBridge] sendExplicitFilePath completed",{connectionId:e,transferId:n||null,result:i}),i}return this.fallback.sendExplicitFilePath(e,t,n)}async sendExplicitFileData(e){c$1("[NativeIpcBridge] sendExplicitFileData start",{connectionId:e.connectionId??null,connectionRemoteNodeId:e.connection?.remoteNodeId??null,remoteNodeId:e.remoteNodeId??null,transferId:e.transferId??null,fileName:e.file.name,fileSize:e.file.size,authMode:this.options.authMode});let t=e.applicationCrypto??this.options.applicationCrypto;if(await this.canUseTauriIpc()){this.options.authMode!=="anonymous"?await this.ensureNativeAuth("sendExplicitFileData"):c$1("[NativeIpcBridge] sendExplicitFileData using anonymous native path");let n=e.connectionId||e.connection?.deviceId||e.connection?.remoteNodeId||e.remoteNodeId||"";if(!n)throw new Error("sendExplicitFileData requires a settled peer identifier in native runtime");let i=new Uint8Array(await e.file.arrayBuffer());await this.invokeIpc("send_file_data",{connectionId:n,filename:e.file.name,data:Array.from(i),transferId:e.transferId}),c$1("[NativeIpcBridge] sendExplicitFileData completed",{connectionId:n,transferId:e.transferId??null,fileName:e.file.name,fileSize:e.file.size});return}return this.fallback.sendExplicitFileData({...e,applicationCrypto:t})}async getConnectionStates(){if(await this.canUseTauriIpc())try{this.options.authMode!=="anonymous"&&await this.ensureNativeAuth("getConnectionStates");let e=await this.invokeIpc("list_rtc_connection_states");return (Array.isArray(e)?e:[]).map(t=>p$2(t)).filter(t=>!!t)}catch(e){return b$3(e)?c$1("[NativeIpcBridge] native connection-state replay unavailable; continuing without replay. Install/register openrtc-tauri-plugin default permissions to enable it."):console.warn("[NativeIpcBridge] Failed to fetch native connection states:",e),[]}return []}async getConnectionState(e){let t=e.trim();if(!t||!await this.canUseTauriIpc())return null;try{return this.options.authMode!=="anonymous"&&await this.ensureNativeAuth("getConnectionState"),p$2(await this.invokeIpc("get_rtc_connection_state",{connectionId:t}))}catch(n){return console.warn("[NativeIpcBridge] Failed to fetch native connection state:",{connectionId:t,error:n}),null}}async onStateChange(e$1){let t=false,n=null,i=new Map,o=Date.now(),s=0,a=()=>{let l=n;l&&Promise.resolve(l());},c=async()=>{try{let l=await this.getConnectionStates();l.length>0&&(b("[NativeIpcBridge] replaying current native connection states",l.map(p=>({connectionId:p.connectionId,deviceId:p.deviceId??null,deviceIdHint:p.deviceIdHint??null,remoteNodeId:p.remoteNodeId??null,state:p.state,transportState:p.transportState??null,protocolState:p.protocolState??null,routable:p.routable??null}))),l.forEach(p=>e$1(p)));}catch(l){console.warn("[NativeIpcBridge] Failed to replay native connection states after event subscription:",l);}},d=async l=>{let p=(i.get(l)??0)+1;i.set(l,p);let u=await this.getConnectionState(l);if(!u||t||i.get(l)!==p)return;if(["closed","failed","disconnected"].includes(String(u.state??"").trim().toLowerCase())){if(await e(H.CONNECTION_TERMINAL_CONFIRMATION_MS),t||i.get(l)!==p)return;u=await this.getConnectionState(l)??u;}!t&&i.get(l)===p&&e$1(u);};for(;!t&&Date.now()-o<=H.CONNECTION_EVENT_SUBSCRIBE_WINDOW_MS;){if(s+=1,!await this.canUseTauriIpc()){await e(this.nextConnectionEventRetryDelayMs(s));continue}return n=await this.listenIpc("connection-state-changed",l=>{let p=p$2(l?.payload);p&&(b("[NativeIpcBridge] connection-state-changed trigger",{connectionId:p.connectionId}),d(p.connectionId));}),await c(),()=>{t=true,a();}}return ()=>{t=true,a();}}async onIncomingNativeMessage(e){if(!await this.canUseTauriIpc())return ()=>{};let t=await this.listenIpc("iroh://message",n=>{if(n?.payload?.data&&n.payload.streamId==="main")try{let i=new Uint8Array(n.payload.data);if(i.length<2||i[0]!==0)return;let s=i.slice(1),a=new TextDecoder().decode(s),c=JSON.parse(a);e(n.payload.connectionId,n.payload.remoteNodeId??null,c);}catch{}});return typeof t=="function"?t:()=>{}}async getTransferHistory(e=50){return await this.canUseTauriIpc()?this.invokeIpc("get_transfer_history",{limit:e}):[]}async deleteTransferJob(e){await this.canUseTauriIpc()&&await this.invokeIpc("delete_transfer_job",{jobId:e});}};H.AUTH_REQUIRED_WAIT_MS=q.nativeIpc.authRequiredWaitMs,H.DEFAULT_BOUNDED_IPC_TIMEOUT_MS=q.nativeIpc.defaultBoundedCommandTimeoutMs,H.CONNECTION_EVENT_SUBSCRIBE_WINDOW_MS=q.nativeIpc.connectionEventSubscribeWindowMs,H.CONNECTION_EVENT_RETRY_MIN_DELAY_MS=q.nativeIpc.connectionEventRetryMinDelayMs,H.CONNECTION_EVENT_RETRY_MAX_DELAY_MS=q.nativeIpc.connectionEventRetryMaxDelayMs,H.CONNECTION_TERMINAL_CONFIRMATION_MS=1500,H.TAURI_IPC_NEGATIVE_CACHE_MS=q.nativeIpc.tauriIpcNegativeCacheMs,H.NATIVE_STATUS_IPC_TIMEOUT_MS=2500;var zn=H;var ks=class extends a$1{constructor(e){let t=c$2(e.bridge,"IpcRuntimeAdapter");super(new zn({...e,ipcBridge:t,allowWasmFallback:e.allowWasmFallback??false}));}};
3
+ export{ja as a,yt as b,Ms as c,Ge as d,Y as e,ue as f,si as g,ri as h,Ke as i,ze as j,ai as k,Ls as l,Bs as m,Fs as n,Xa as o,Za as p,ci as q,li as r,ws as s,ks as t};