openrtc 1.0.24 → 1.0.26
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{DelegatingRuntimeAdapter-B9j_lTDM.d.ts → DelegatingRuntimeAdapter-Cg3jFk1b.d.ts} +1 -1
- package/dist/{assembly-Ddq1o4NV.d.ts → assembly-CscFVHYK.d.ts} +2 -2
- package/dist/auth/index.js +1 -1
- package/dist/auth/internal.js +1 -1
- package/dist/chunk-2W2YWRIZ.js +1 -0
- package/dist/{chunk-2QFNPBOZ.js → chunk-BW6OKBHV.js} +1 -1
- package/dist/chunk-D4JYPV6F.js +2 -0
- package/dist/{chunk-A4BFI5PF.js → chunk-DIBUXEEO.js} +1 -1
- package/dist/{chunk-OVGVNSEH.js → chunk-DXJZDB7Q.js} +3 -3
- package/dist/chunk-OCSZA6PK.js +2 -0
- package/dist/chunk-PPGIC6DR.js +2 -0
- package/dist/{chunk-FCQUZYLO.js → chunk-QBAVJDN2.js} +1 -1
- package/dist/index.d.ts +84 -8
- package/dist/index.js +1 -1
- package/dist/native.d.ts +5 -5
- package/dist/native.js +1 -1
- package/dist/openrtc_bg.wasm +0 -0
- package/dist/runtime/WasmRuntimeAdapter.d.ts +2 -2
- package/dist/runtime/WasmRuntimeAdapter.js +1 -1
- package/dist/runtime/device-status.d.ts +2 -2
- package/dist/runtime/index.d.ts +8 -8
- package/dist/runtime/index.js +1 -1
- package/dist/runtime/tauri.d.ts +3 -3
- package/dist/runtime/tauri.js +1 -1
- package/dist/{spaceTokens-DyOOxC7x.d.ts → spaceTokens-CiwcKKr2.d.ts} +3 -3
- package/dist/{tauri-DZJ_ZEfB.d.ts → tauri-BpsecNrp.d.ts} +2 -2
- package/dist/transport/index.d.ts +2 -2
- package/dist/{types-BAwo8biA.d.ts → types-BJU2GoVb.d.ts} +1 -1
- package/dist/{types-CL4Da0BR.d.ts → types-zT2QwuCv.d.ts} +21 -0
- package/package.json +1 -1
- package/dist/chunk-57H5EZJI.js +0 -2
- package/dist/chunk-AXC2ODLP.js +0 -1
- package/dist/chunk-G22CDATK.js +0 -2
- package/dist/chunk-SY6YGCXA.js +0 -2
package/dist/{DelegatingRuntimeAdapter-B9j_lTDM.d.ts → DelegatingRuntimeAdapter-Cg3jFk1b.d.ts}
RENAMED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { D as DiscoveryMode, A as AuthMode, d as SignalingMode, e as ClientOptions, E as ExplicitFileDataSendParams, I as ISignalingBackend, f as RuntimeIdentity, g as RoomMember, h as Device, i as DeviceStatusSnapshot, P as PeerSessionSnapshot, R as ResolvedPeerIdentity, M as ManagedConnectionRecord, j as SignalingEnvelope, k as DeviceEvent, l as DesiredPeerProjection, m as SignalingSession, n as SessionEvent, L as LocalDeviceInfo, N as NativeManagedSessionStartResult, G as GrantScope, B as BackendPeerBiStream, o as BackendPeerUniStream, p as NativeConnectParams, q as NativeConnectResult, r as BackendConnectionState } from './types-
|
|
1
|
+
import { D as DiscoveryMode, A as AuthMode, d as SignalingMode, e as ClientOptions, E as ExplicitFileDataSendParams, I as ISignalingBackend, f as RuntimeIdentity, g as RoomMember, h as Device, i as DeviceStatusSnapshot, P as PeerSessionSnapshot, R as ResolvedPeerIdentity, M as ManagedConnectionRecord, j as SignalingEnvelope, k as DeviceEvent, l as DesiredPeerProjection, m as SignalingSession, n as SessionEvent, L as LocalDeviceInfo, N as NativeManagedSessionStartResult, G as GrantScope, B as BackendPeerBiStream, o as BackendPeerUniStream, p as NativeConnectParams, q as NativeConnectResult, r as BackendConnectionState } from './types-zT2QwuCv.js';
|
|
2
2
|
import { A as AuthContext } from './IEngineBridge-BbsT8hof.js';
|
|
3
3
|
import { R as RuntimeCapabilities } from './capabilities-CaqXOIUU.js';
|
|
4
4
|
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { A as AuthContext } from './IEngineBridge-BbsT8hof.js';
|
|
2
|
-
import { G as GrantScope, I as ISignalingBackend, b as ConnectDeviceHooks, c as ConnectDeviceOptions, C as ConnectDeviceResult, M as ManagedConnectionRecord, P as PeerSessionSnapshot, R as ResolvedPeerIdentity, Y as AppLimits, p as NativeConnectParams, q as NativeConnectResult, E as ExplicitFileDataSendParams } from './types-
|
|
3
|
-
import { h as RuntimePeerState, s as RuntimeConnectionStateSnapshot, j as RuntimePeerReadinessSnapshot, i as RuntimePeerConnectOptions, C as Connection, n as RuntimeIncomingStream, R as RuntimeClientOptions, H as RuntimeAuthIdentity, f as RuntimeLocalDeviceInfo, g as RuntimeLocalDeviceProfile, c as RuntimeDevice, a as RuntimeManagedSessionOptions, b as RuntimeManagedSession, d as RuntimeDeviceStatusSnapshot, e as RuntimeDeviceConnectOptions, X as RuntimeSession, q as RuntimeJoinRoomOptions, r as RuntimeRoomMember, K as RuntimeConnectionTarget, o as RuntimeScopedChannelOptions, p as RuntimeScopedLogicalChannel, m as RuntimePeerStreamOptions, v as RuntimeRawConnection, l as RuntimeChannelDescriptor, V as RuntimePresenceLoopOptions, k as RuntimePeerHealth, t as RuntimeApplicationPayloadReadinessOptions, u as RuntimeConnectionEvent } from './types-
|
|
2
|
+
import { G as GrantScope, I as ISignalingBackend, b as ConnectDeviceHooks, c as ConnectDeviceOptions, C as ConnectDeviceResult, M as ManagedConnectionRecord, P as PeerSessionSnapshot, R as ResolvedPeerIdentity, Y as AppLimits, p as NativeConnectParams, q as NativeConnectResult, E as ExplicitFileDataSendParams } from './types-zT2QwuCv.js';
|
|
3
|
+
import { h as RuntimePeerState, s as RuntimeConnectionStateSnapshot, j as RuntimePeerReadinessSnapshot, i as RuntimePeerConnectOptions, C as Connection, n as RuntimeIncomingStream, R as RuntimeClientOptions, H as RuntimeAuthIdentity, f as RuntimeLocalDeviceInfo, g as RuntimeLocalDeviceProfile, c as RuntimeDevice, a as RuntimeManagedSessionOptions, b as RuntimeManagedSession, d as RuntimeDeviceStatusSnapshot, e as RuntimeDeviceConnectOptions, X as RuntimeSession, q as RuntimeJoinRoomOptions, r as RuntimeRoomMember, K as RuntimeConnectionTarget, o as RuntimeScopedChannelOptions, p as RuntimeScopedLogicalChannel, m as RuntimePeerStreamOptions, v as RuntimeRawConnection, l as RuntimeChannelDescriptor, V as RuntimePresenceLoopOptions, k as RuntimePeerHealth, t as RuntimeApplicationPayloadReadinessOptions, u as RuntimeConnectionEvent } from './types-BJU2GoVb.js';
|
|
4
4
|
import { R as RuntimeCapabilities, a as RuntimeCapabilityProfile } from './capabilities-CaqXOIUU.js';
|
|
5
5
|
|
|
6
6
|
/**
|
package/dist/auth/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export{H as authHost,G as getAuthHost,F as registerDesktopAuthRelay}from'../chunk-
|
|
1
|
+
export{H as authHost,G as getAuthHost,F as registerDesktopAuthRelay}from'../chunk-OCSZA6PK.js';import'../chunk-C7YN5MSV.js';
|
package/dist/auth/internal.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export{F as registerDesktopAuthRelay}from'../chunk-
|
|
1
|
+
export{F as registerDesktopAuthRelay}from'../chunk-OCSZA6PK.js';import'../chunk-C7YN5MSV.js';
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import {J,I}from'./chunk-D4JYPV6F.js';var n=class extends J{constructor(e){super(new I(e));}setWasmClient(e){this.unwrap().setWasmClient(e);}};export{n as a};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import {o,G}from'./chunk-
|
|
1
|
+
import {o,G}from'./chunk-OCSZA6PK.js';function A(t){let i=o({...t});if("auth"in t&&!t.authMode){let n=t.auth;i.authMode=n==="none"?"anonymous":n;}if("identity"in t){let n=t.identity,s=n==="temporary"?"ephemeral":n;!t.deviceIdPersistence&&!t.nodeIdPersistence&&(i.deviceIdPersistence=s),!t.endpointIdPersistence&&!t.nodeIdPersistence&&(i.endpointIdPersistence=s);}return "namespace"in t&&!t.storagePrefix&&(i.storagePrefix=t.namespace),"privacy"in t&&t.strictMode===void 0&&(i.strictMode=!!t.privacy),i}function N(t,i){let n=t.runtime,s=Object.create(n),r=async e=>{if(typeof e!="string")return e;let a=(await n.listDevices()).find(d=>d.deviceId===e);if(!a)throw new Error(`OpenRTC device '${e}' is not currently discoverable.`);return a},c=async e=>({...e,localDeviceId:e?.localDeviceId??await n.getLocalDeviceId()??""}),m=async e=>{let{device:o,scope:a,...d}=e,h=d.deviceId??(typeof o=="string"?o:o?.deviceId)??null,v=d.ticket??(typeof o=="string"?void 0:o?.ticket);h&&!v&&(v=(await r(h).catch(()=>null))?.ticket);let P={...d,scope:a??"session"};return h&&(P.deviceId=h),v&&(P.ticket=v),P},u={list:()=>n.listDevices(),startSession:(e={})=>n.startManagedSession({...e,platform:e.platform??i}),stopSession:e=>n.stopManagedSession(e),listWithStatus:()=>n.listDevicesWithStatus(),watch:e=>n.watchDevices(e),watchWithStatus:e=>n.watchDevicesWithStatus(e),connect:async(e,o)=>n.connectDevice(await r(e),await c(o)),connectWithRetry:async(e,o,a)=>n.connectDeviceWithRetry(await r(e),o,a),disconnect:e=>n.disconnectDevice(e),update:(e,o)=>n.updateDevice(e,o),delete:e=>n.deleteDevice(e),localId:()=>n.getLocalDeviceId(),localInfo:()=>n.getLocalDeviceInfo(),localProfile:e=>n.getLocalDeviceProfile(e),updateLocalName:e=>n.updateLocalDeviceName(e)},l={watch:e=>n.watchPeerStates(e),watchLifecycle:e=>n.watchPeerLifecycle(e),get:e=>n.getPeerState(e),listConnected:()=>n.listConnectedPeers(),connect:e=>n.connectPeer(e),disconnect:(e,o)=>n.disconnectPeer(e,o),forceDisconnect:e=>n.forceDisconnectPeer(e),session:e=>n.getPeerSession(e),sessions:()=>n.listPeerSessions(),waitConnected:(e,o)=>n.waitForConnectedPeer(e,o),readiness:(e,o)=>n.getPeerReadiness(e,o),health:e=>n.getPeerHealth(e),identity:e=>n.resolvePeerIdentity(e),addScope:(e,o)=>n.addPeerScope(e,o),releaseScope:(e,o)=>n.releasePeerScope(e,o),scopes:e=>n.getPeerScopes(e),refresh:()=>n.refreshPeerSnapshot()},g={register:e=>n.registerChannel(e),unregister:e=>n.unregisterChannel(e),list:()=>n.listChannels(),openBi:(e,o,a)=>n.openPeerBi(e,{...a,channelId:o}),openUni:(e,o,a)=>n.openPeerUni(e,{...a,channelId:o}),onIncoming:e=>n.onIncomingStream(e),onIncomingChannel:(e,o)=>n.onIncomingChannelStream(e,a=>{if(a.channel)return o(a)}),connect:async e=>n.connectScopedChannel(await m(e)),connectScoped:e=>n.connectScopedChannel(e)},p={create:e=>n.createRoom(e),join:(e,o)=>n.joinRoom(e,o),leave:e=>n.leaveRoom(e),watch:(e,o)=>n.watchRoom(e,o),members:e=>n.getRoomMembers(e)},R={raw:()=>n.getInvite(),share:e=>n.getTicketWithToken("share",e?.maxConnections??1),grant:(e,o)=>n.getTicketWithToken(e,o?.maxConnections??0),revoke:e=>n.revokeTokensByScope(e)},C={status:()=>n.getRuntimeStatus(),policy:()=>n.getRuntimePolicy(),capabilities:()=>n.getRuntimeCapabilities(),capabilityProfile:()=>n.getCapabilityProfile(),connectionStates:()=>n.getConnectionStates(),onConnectionStateChange:e=>n.onConnectionStateChange(e),connections:()=>n.getConnections(),applicationReadyConnections:e=>n.getApplicationReadyConnections(e),onConnection:e=>n.onConnection(e),onDisconnection:e=>n.onDisconnection(e),onConnectionEvent:e=>n.onConnectionEvent(e),forceReconnectSnapshot:()=>n.forceReconnectSnapshot(),peerReconciliation:()=>n.getPeerReconciliationStats()},k={runtime:n,assembly:t,nodeId:()=>n.getNodeId(),nodeIdFromTicket:e=>n.getNodeIdFromTicket(e),endpointTicket:()=>n.getEndpointTicket(),connectRaw:e=>n.connectRaw(e),openBi:e=>n.openBi(e),openUni:e=>n.openUni(e),isConnected:e=>n.isConnected(e),disconnectNode:e=>n.disconnectNode(e),setAutoConnectExcluded:(e,o)=>n.setAutoConnectExcluded(e,o),notifyNetworkChange:e=>n.notifyNetworkChange(e)};return Object.defineProperties(s,{devices:{get:()=>u,enumerable:true},peers:{get:()=>l,enumerable:true},channels:{get:()=>g,enumerable:true},rooms:{get:()=>p,enumerable:true},tickets:{get:()=>R,enumerable:true},diagnostics:{get:()=>C,enumerable:true},advanced:{get:()=>k,enumerable:true},setAuth:{value:e=>t.setAuthContext(e),enumerable:true,writable:true,configurable:true},setAuthContext:{value:e=>t.setAuthContext(e),enumerable:true,writable:true,configurable:true},syncPlutoAuth:{value:e=>t.syncPlutoAuth(e),enumerable:true,writable:true,configurable:true},bindPlutoAuthHost:{value:()=>t.bindPlutoAuthHost(),enumerable:true,writable:true,configurable:true},signIn:{value:()=>t.signInWithPluto(),enumerable:true,writable:true,configurable:true},signOut:{value:()=>t.signOut(),enumerable:true,writable:true,configurable:true},runtime:{get:()=>n,enumerable:false},_assembly:{get:()=>t,enumerable:false}}),s}var O="https://api.openrtc.app";function S(t){if(typeof globalThis.crypto?.randomUUID!="function")throw new Error(`Secure request identity is unavailable for ${t}.`);return `${t}:${globalThis.crypto.randomUUID()}`}async function E(t,i,n){let s=t.replace(/\/$/,""),r=await fetch(`${s}/v1/spaces/${encodeURIComponent(n)}/scoped-auth`,{method:"POST",headers:{Authorization:`Bearer ${i}`,"Content-Type":"application/json","X-OpenRTC-Idempotency-Key":S("enable-space-auth")},body:"{}"}),c=await r.json().catch(()=>({}));if(!r.ok){let m=typeof c?.error=="string"?c.error:`enableSpaceAuth failed (${r.status})`;throw new Error(m)}return c}async function L(t,i,n){let s=await fetch(t,{method:"POST",headers:{Authorization:`Bearer ${i}`,"Content-Type":"application/json","X-OpenRTC-Idempotency-Key":S("mint-space-token")},body:JSON.stringify(n)}),r=await s.json().catch(()=>({}));if(!s.ok){let c=typeof r?.error=="string"?r.error:`mintSpaceToken failed (${s.status})`;throw new Error(c)}if(typeof r?.token!="string"||!r.token.trim())throw new Error("mintSpaceToken response missing token");return r}function f(t){let i=t.apiKey.trim(),n=(t.spaceKey??t.space??"").trim(),s=I(t.sandboxAppId),r=(t.endpointUrl??O).replace(/\/$/,""),c=t.memberIdStorageKey??`openrtc:space-member:${n}${s?`:sandbox:${s}`:""}`;return async()=>{if(!i||!n)throw new Error("spaceToken requires apiKey and space");let m=null;typeof sessionStorage<"u"?(m=sessionStorage.getItem(c),m||(m=globalThis.crypto?.randomUUID?.()??`member-${Date.now()}`,sessionStorage.setItem(c,m))):m=`member-${Date.now()}`;let u=await G().getAppCheckToken(),l=await fetch(`${r}/v1SpacePublicTokens`,{method:"POST",headers:{"Content-Type":"application/json","X-OpenRTC-Idempotency-Key":S("mint-public-space-token"),...u?{"X-Firebase-AppCheck":u}:{}},body:JSON.stringify({apiKey:i,spaceKey:n,memberId:m,...s?{sandboxAppId:s}:{}})}),{text:g,payload:p}=await T(l);if(!l.ok){let C=typeof p?.error=="string"?p.error:g.trim()?g.trim().slice(0,240):`public space token mint failed (${l.status})`;throw new Error(C)}let R=typeof p?.token=="string"?p.token.trim():"";if(!R)throw new Error("public space token response missing token");return {customToken:R}}}function w(t){if(!t.trim())return {};try{let i=JSON.parse(t);return i&&typeof i=="object"?i:{}}catch{return {}}}async function T(t){let i=t.text;if(typeof i=="function"){let s=await i.call(t).catch(()=>"");return {text:s,payload:w(s)}}let n=await t.json().catch(()=>({}));return {text:JSON.stringify(n),payload:n&&typeof n=="object"?n:{}}}function I(t){let i=t?.trim().toLowerCase()??"";if(!i)return "";if(!/^[a-z0-9][a-z0-9-]{0,47}$/.test(i))throw new Error("sandboxAppId must be 1-48 lowercase letters, numbers, or dashes.");return i}function $(t,i){let n=t.trim(),s=I(i);return s?`${n}::sandbox::${s}`:n}var W=f,K=f;
|
|
2
2
|
export{A as a,N as b,E as c,L as d,f as e,$ as f,W as g,K as h};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import {h,b as b$2}from'./chunk-QT2ASNI3.js';import {v,b as b$1,d,c,G as G$1,e,t,u as u$1,a,w as w$1,x as x$1}from'./chunk-OCSZA6PK.js';import {xchacha20poly1305}from'@noble/ciphers/chacha.js';import*as ue from'tweetnacl';function ht(){if(typeof globalThis<"u"&&globalThis.__OPENRTC_DEBUG__===true)return true;if(typeof localStorage<"u")try{return localStorage.getItem("openrtc:debug")==="1"}catch{return false}return false}function pe(n,e,t){if(ht()){if(typeof t>"u"){console[n](e);return}console[n](e,t);}}function ee(n,e){pe("debug",n,e);}function A(n,e){pe("info",n,e);}function mn(n,e){pe("log",n,e);}var W=new Uint8Array([79,82,84,67,69,49]),te=2,H=8,q=24,Oe=32,ft=3,mt=16*1024*1024,gt=4096;function yt(n,e){if(n.byteLength<e.byteLength)return false;let t=0;for(let i=0;i<e.byteLength;i+=1)t|=n[i]^e[i];return t===0}function vt(n){let e=new Uint8Array(n),t=globalThis.crypto;if(!t||typeof t.getRandomValues!="function")throw new Error("[OpenRTC] application payload crypto requires crypto.getRandomValues");return t.getRandomValues(e),e}function bt(n,e){let t="";for(let i of e)t+=i.toString(16).padStart(2,"0");return `${n}:${t}`}function Ne(n){if(!yt(n,W))return null;let e=n[W.byteLength];return e===te?e:null}function St(n){return Ne(n)===te&&n.byteLength>W.byteLength+1+H+q}function bn(n,e={}){if(!(n instanceof Uint8Array)||n.byteLength!==Oe)throw new Error(`[OpenRTC] application payload crypto key must be ${Oe} bytes`);let t=new Uint8Array(n),i=e.requireEncrypted??true,r=e.randomBytes??vt,o=e.replayProtection??true,s=0,a=new Set,d=[];return {requireEncrypted:i,protectPayload(l,c){let p=r(q);if(!(p instanceof Uint8Array)||p.byteLength!==q)throw new Error(`[OpenRTC] application payload crypto nonce must be ${q} bytes`);let h=new Uint8Array(1+c.byteLength);h[0]=l,h.set(c,1);let y=xchacha20poly1305(t,p).encrypt(h);if(!o)throw new Error("[OpenRTC] ORTCE1 v1 envelopes are not supported; replay protection is required");let v=new Uint8Array(W.byteLength+1+H+p.byteLength+y.byteLength),S=0;v.set(W,S),S+=W.byteLength,v[S]=te,S+=1;let O=s;return s+=1,new DataView(v.buffer,v.byteOffset+S,H).setBigUint64(0,BigInt(O),false),S+=H,v.set(p,S),S+=p.byteLength,v.set(y,S),v},openPayload(l,c){if(!St(c))return i?null:c;if(Ne(c)!==te)return null;let h=W.byteLength+1,y=Number(new DataView(c.buffer,c.byteOffset+h,H).getBigUint64(0,false));if(!Number.isFinite(y))return null;let v=h+H,S=v+q,O=c.slice(v,S),I=o?bt(y,O):null;if(I&&a.has(I))return null;let _=c.slice(S),R;try{R=xchacha20poly1305(t,O).decrypt(_);}catch{return null}if(R.byteLength<1||R[0]!==l)return null;if(I)for(a.add(I),d.push(I);d.length>gt;){let E=d.shift();E&&a.delete(E);}return R.slice(1)}}}function wt(n){let e=new Uint8Array(4+n.byteLength);return new DataView(e.buffer,e.byteOffset,e.byteLength).setUint32(0,n.byteLength,false),e.set(n,4),e}function xe(n,e={}){let t=e.typeId??ft,i=e.maxFrameBytes??mt;if(!Number.isInteger(t)||t<0||t>255)throw new Error("[OpenRTC] raw application crypto stream typeId must be an integer from 0 to 255");if(!Number.isInteger(i)||i<=0)throw new Error("[OpenRTC] raw application crypto maxFrameBytes must be a positive integer");let r=c=>n.protectPayload(t,c),o=c=>n.openPayload(t,c),s=()=>new TransformStream({transform(c,p){p.enqueue(wt(r(new Uint8Array(c))));}}),a=()=>{let c=new Uint8Array(0);return new TransformStream({transform(p,h){for(c=w$1([c,new Uint8Array(p)]);c.byteLength>=4;){let y=new DataView(c.buffer,c.byteOffset,c.byteLength).getUint32(0,false);if(y===0||y>i)throw new Error("[OpenRTC] invalid encrypted raw stream frame length");if(c.byteLength<4+y)return;let v=c.slice(4,4+y);c=c.slice(4+y);let S=o(v);if(!S)throw new Error("[OpenRTC] encrypted raw stream frame failed authentication");h.enqueue(S);}},flush(){if(c.byteLength!==0)throw new Error("[OpenRTC] encrypted raw stream ended mid-frame")}})},d=c=>c.pipeThrough(a()),l=c=>{let p=s();return p.readable.pipeTo(c).catch(()=>{}),p.writable};return {typeId:t,protectFrame:r,openFrame:o,createOutboundTransform:s,createInboundTransform:a,wrapReadable:d,wrapWritable:l,wrapBiStream(c){return {...c,send:l(c.send),recv:d(c.recv)}}}}var It="[OpenRTC][teardown-trace]";function Tt(){try{let n=globalThis;if(n.OPENRTC_TEARDOWN_TRACE===!0||n.localStorage?.getItem("OPENRTC_TEARDOWN_TRACE")==="1")return !0}catch{}return false}function Le(n,e={}){console.info(It,{kind:n,ts:new Date().toISOString(),...e}),Tt()&&console.info("[OpenRTC][teardown-trace:stack]",{kind:n,stack:new Error(`teardown: ${n}`).stack});}var f={AUTH_NOT_READY:"auth/not-ready",AUTH_DENIED:"auth/denied",AUTH_EXPIRED:"auth/expired",ADMISSION_DENIED:"admission/denied",ADMISSION_SCOPE_MISMATCH:"admission/scope-mismatch",BUDGET_EXCEEDED:"budget/exceeded",BUDGET_STALE:"budget/stale",BUDGET_RENEWAL_REQUIRED:"budget/renewal-required",COORDINATION_DISCONNECTED:"coordination/disconnected",COORDINATION_PROTOCOL:"coordination/protocol",COORDINATION_RATE_LIMITED:"coordination/rate-limited",TRANSPORT_DIAL_EXHAUSTED:"transport/dial-exhausted",TRANSPORT_UNAVAILABLE:"transport/unavailable",TRANSPORT_TICKET_MISSING:"transport/ticket-missing",DELIVERY_NOT_READY:"delivery/not-ready",INTERNAL:"internal/error"},D=class n extends Error{constructor(t){super(t.message);this.name="OpenRtcError";t.cause!==void 0&&(this.cause=t.cause),this.code=t.code,this.retryable=t.retryable,this.plane=t.plane,this.generation=t.generation,this.transportGeneration=t.transportGeneration,this.routeGeneration=t.routeGeneration,this.revision=t.revision;}static isOpenRtcError(t){return t instanceof n||typeof t=="object"&&t!==null&&t.name==="OpenRtcError"&&typeof t.code=="string"&&typeof t.retryable=="boolean"&&typeof t.plane=="string"}static shouldAppRetry(t){let i=ne(t);return i.retryable?i.plane==="coordination"||i.plane==="transport"||i.plane==="auth":false}toJSON(){return {name:this.name,code:this.code,message:this.message,retryable:this.retryable,plane:this.plane,generation:this.generation??null,transportGeneration:this.transportGeneration??null,routeGeneration:this.routeGeneration??null,revision:this.revision??null}}};function Be(n){let e=ne(n);return {errorCode:e.code,retryable:e.retryable,errorPlane:e.plane}}function w(n,e,t){let i=Rt(n);return new D({code:n,message:e,retryable:t.retryable??i.retryable,plane:t.plane??i.plane,cause:t.cause,generation:t.generation,transportGeneration:t.transportGeneration,routeGeneration:t.routeGeneration,revision:t.revision})}function Rt(n){switch(n){case f.AUTH_NOT_READY:case f.AUTH_EXPIRED:return {retryable:true,plane:"auth"};case f.AUTH_DENIED:return {retryable:false,plane:"auth"};case f.ADMISSION_DENIED:case f.ADMISSION_SCOPE_MISMATCH:return {retryable:false,plane:"admission"};case f.BUDGET_EXCEEDED:return {retryable:false,plane:"budget"};case f.BUDGET_STALE:case f.BUDGET_RENEWAL_REQUIRED:return {retryable:true,plane:"budget"};case f.COORDINATION_DISCONNECTED:case f.COORDINATION_RATE_LIMITED:return {retryable:true,plane:"coordination"};case f.COORDINATION_PROTOCOL:return {retryable:false,plane:"coordination"};case f.TRANSPORT_DIAL_EXHAUSTED:case f.TRANSPORT_UNAVAILABLE:case f.TRANSPORT_TICKET_MISSING:return {retryable:true,plane:"transport"};case f.DELIVERY_NOT_READY:return {retryable:true,plane:"delivery"};case f.INTERNAL:default:return {retryable:false,plane:"internal"}}}function ne(n){if(D.isOpenRtcError(n))return n instanceof D?n:new D({code:n.code,message:n.message||String(n),retryable:n.retryable,plane:n.plane,cause:n,generation:n.generation,transportGeneration:n.transportGeneration,routeGeneration:n.routeGeneration,revision:n.revision});if(typeof n=="object"&&n!==null){let t=n,i=typeof t.code=="string"?t.code:"",r=typeof t.message=="string"?t.message:n instanceof Error?n.message:String(n),o=typeof t.retryable=="boolean"?t.retryable:void 0;if(i){let s=Ct(i,r,o);if(s)return s}if(typeof t.name=="string"&&t.name==="CoordinationConnectError")return w(f.COORDINATION_DISCONNECTED,r,{retryable:o??true,plane:"coordination",cause:n});if(typeof t.name=="string"&&t.name==="CoordinationGatewayProtocolError")return w(i||f.COORDINATION_PROTOCOL,r,{retryable:o??false,plane:Fe(i),cause:n})}let e=n instanceof Error?n.message:String(n??"unknown error");return Pt(e,n)}function Ct(n,e,t){let i=n.trim().toLowerCase();return i==="unauthenticated"||i==="functions/unauthenticated"||i==="auth/unauthorized"||i.includes("permission-denied")?w(f.AUTH_DENIED,e,{retryable:false,plane:"auth"}):i==="budget-renewal-required"||i==="budget/renewal-required"?w(f.BUDGET_RENEWAL_REQUIRED,e,{retryable:t??true,plane:"budget"}):i.includes("resource-exhausted")||i.includes("budget")||i==="budget-exceeded"||i==="insufficient-budget"?i.includes("stale")||/stale-budget/i.test(e)?w(f.BUDGET_STALE,e,{retryable:t??true,plane:"budget"}):w(f.BUDGET_EXCEEDED,e,{retryable:false,plane:"budget"}):i.includes("rate-limit")||i==="rate_limited"||i==="too-many-requests"?w(f.COORDINATION_RATE_LIMITED,e,{retryable:t??true,plane:"coordination"}):i.includes("admission")||i==="permission-denied"||i==="session-token-denied"?w(f.ADMISSION_DENIED,e,{retryable:false,plane:"admission"}):i.includes("scope")?w(f.ADMISSION_SCOPE_MISMATCH,e,{retryable:false,plane:"admission"}):i.includes("disconnect")||i.includes("unavailable")||i==="aborted"?w(f.COORDINATION_DISCONNECTED,e,{retryable:t??true,plane:"coordination"}):i.startsWith("coordination/")||i.includes("protocol")?w(n,e,{retryable:t??false,plane:Fe(n)}):null}function Fe(n){let e=n.trim().toLowerCase();return e.includes("budget")?"budget":e.includes("auth")?"auth":e.includes("admission")||e.includes("scope")?"admission":(e.includes("rate"),"coordination")}function Pt(n,e){return /auth(?:entication)?\s*(?:not ready|pending|missing)/i.test(n)||/token\s*(?:not ready|pending|missing)/i.test(n)||/awaiting[- ]auth/i.test(n)?w(f.AUTH_NOT_READY,n,{retryable:true,plane:"auth",cause:e}):/missing endpoint ticket|ticket missing/i.test(n)?w(f.TRANSPORT_TICKET_MISSING,n,{retryable:true,plane:"transport",cause:e}):/dial.*(exhaust|budget)|retry budget|connection.*did not become application-routable/i.test(n)?w(f.TRANSPORT_DIAL_EXHAUSTED,n,{retryable:true,plane:"transport",cause:e}):/stale[- ]budget/i.test(n)?w(f.BUDGET_STALE,n,{retryable:true,plane:"budget",cause:e}):/budget|credit|quota|limit\s*exceeded/i.test(n)?w(f.BUDGET_EXCEEDED,n,{retryable:false,plane:"budget",cause:e}):/admission|session[- ]token.*(deny|reject)|permission[- ]denied/i.test(n)?w(f.ADMISSION_DENIED,n,{retryable:false,plane:"admission",cause:e}):/not\s+application-routable|not[- ]ready|settledReady/i.test(n)?w(f.DELIVERY_NOT_READY,n,{retryable:true,plane:"delivery",cause:e}):/gateway|coordination|websocket|signaling/i.test(n)?w(f.COORDINATION_DISCONNECTED,n,{retryable:true,plane:"coordination",cause:e}):w(f.INTERNAL,n,{retryable:false,plane:"internal",cause:e})}var he={managedSession:{nativeStartRetryWindowMs:12e4,nativeStartRetryMinDelayMs:400,nativeStartRetryMaxDelayMs:5e3,reconciliationIntervalMs:5e3,deviceStatusRefreshDebounceMs:50},browserAutoConnect:{scanDebounceMs:150,retryCooldownMs:2e3,settleGuardMs:1e4,retryMaxMs:8e3,nonInitiatorBaseGraceMs:2e3,nonInitiatorMaxGraceMs:16e3},nativeIpc:{authRequiredWaitMs:15e3,defaultBoundedCommandTimeoutMs:15e3,connectionEventSubscribeWindowMs:15e3,connectionEventRetryMinDelayMs:250,connectionEventRetryMaxDelayMs:1e3,tauriIpcNegativeCacheMs:2e3},browserIdentity:{ephemeralDeviceIdTtlMs:6e4}};function Tn(){return he}var Et={adapter:"browser-wasm",signaling:{coordinationGateway:true,nativeIpc:false,managedPresence:true},transport:{irohQuic:true,irohLan:false,webRtcUpgrade:true,webRtcLan:true,nativeWebRtc:false,moq:true,ble:false,wasm:true},nativeProtocols:{productAlpn:false,irohDocs:false,irohBlobs:false,irohGossip:false},lifecycle:{managedSession:true,autoConnect:true,manualDisconnect:true,connectionStateEvents:true,peerSessions:true},transfers:{explicitFilePath:false,explicitFileData:true,history:false},fallback:{wasm:false}},At={adapter:"native-ipc",signaling:{coordinationGateway:true,nativeIpc:true,managedPresence:true},transport:{irohQuic:true,irohLan:false,webRtcUpgrade:false,webRtcLan:false,nativeWebRtc:false,moq:false,ble:false,wasm:false},nativeProtocols:{productAlpn:true,irohDocs:true,irohBlobs:true,irohGossip:true},lifecycle:{managedSession:true,autoConnect:true,manualDisconnect:true,connectionStateEvents:true,peerSessions:true},transfers:{explicitFilePath:true,explicitFileData:true,history:true},fallback:{wasm:false}};function Ue(n){return {adapter:n.adapter,signaling:{...n.signaling},transport:{...n.transport},nativeProtocols:{...n.nativeProtocols},lifecycle:{...n.lifecycle},transfers:{...n.transfers},fallback:{...n.fallback}}}function ie(n=globalThis){let e=Ue(Et),t=typeof n?.RTCPeerConnection=="function";return e.transport.webRtcUpgrade=t,e.transport.webRtcLan=t,e}function G(n){return n?.compiled===true&&n.enabled===true}function Cn(n,e=false){let t=Ue(At),i=n?.transport;return i&&(t.transport.irohQuic=G(i.irohQuic),t.transport.irohLan=G(i.irohLan),t.transport.webRtcUpgrade=G(i.webRtc),t.transport.nativeWebRtc=G(i.webRtc),t.transport.webRtcLan=G(i.webRtcLan),t.transport.moq=G(i.moq),t.transport.ble=G(i.ble)),t.transport.wasm=false,t.fallback.wasm=e,t}function Pn(n){return {environment:n.adapter==="native-ipc"||n.adapter==="tauri-ipc"?"native":n.adapter==="browser-wasm"?"web":"unknown",transports:{quic:n.transport.irohQuic,irohRelay:n.transport.irohQuic,irohLan:n.transport.irohLan,webRtc:n.transport.webRtcUpgrade||n.transport.nativeWebRtc,webRtcLan:n.transport.webRtcLan,moq:n.transport.moq,ble:n.transport.ble},lifecycle:{...n.lifecycle},storage:{localFileSystem:n.transfers.explicitFilePath,transferHistory:n.transfers.history},nativeProtocols:{...n.nativeProtocols}}}var We=3e4,kt=3e4,Dt=12,fe=15e3,Mt=15e3,Ot=1e3,Ge=250,Nt="openrtc.v1",xt="openrtc.auth.",b=class extends D{constructor(t,i){super({code:f.COORDINATION_DISCONNECTED,message:t,retryable:i,plane:"coordination"});this.name="CoordinationConnectError";}},re=class extends D{constructor(t,i,r){let o=ne({code:t,message:i,retryable:r});super({code:o.code||t||f.COORDINATION_PROTOCOL,message:`Coordination gateway ${t}: ${i}`,retryable:r,plane:o.plane});this.name="CoordinationGatewayProtocolError";}};function He(n){return n instanceof b&&/\bstale-budget\b/i.test(n.message)}function Ke(n){let e=typeof n=="object"&&n!==null&&"code"in n?String(n.code??""):"";return ["functions/unauthenticated","functions/permission-denied","functions/invalid-argument","functions/failed-precondition","functions/resource-exhausted","unauthenticated","permission-denied","invalid-argument","failed-precondition","resource-exhausted"].includes(e)}function Lt(n){let e=new Uint32Array(1);return crypto.getRandomValues(e),Math.max(1,Math.round(n*(.75+e[0]/4294967295*.5)))}function k(n){if(typeof crypto.randomUUID=="function")return `${n}:${crypto.randomUUID()}`;let e=new Uint8Array(16);crypto.getRandomValues(e);let t=Array.from(e,i=>i.toString(16).padStart(2,"0")).join("");return `${n}:${t}`}async function Bt(n){let e=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(n)),t="";for(let i of new Uint8Array(e))t+=String.fromCharCode(i);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,"")}function Ft(n,e){let t=new URL(n);if(t.search||t.hash||t.username||t.password)throw new Error("[OpenRTC] Coordination gateway endpoint must not contain credentials, query, or fragment.");if(t.protocol==="https:")t.protocol="wss:";else if(t.protocol==="http:")t.protocol="ws:";else if(t.protocol!=="wss:"&&t.protocol!=="ws:")throw new Error("[OpenRTC] Coordination gateway endpoint must use HTTPS/WSS.");return t.pathname=`${t.pathname.replace(/\/+$/,"")}/v1/connect/${e}`,t.toString()}function je(n){let e=new URL(n);return e.protocol==="wss:"&&(e.protocol="https:"),e.protocol==="ws:"&&(e.protocol="http:"),e.origin}function Ut(n,e){let t=n.trim();if(!t)throw new Error("[OpenRTC] Firebase project ID is required for the native gateway credential.");let i=typeof globalThis>"u"?"":String(globalThis.__OPENRTC_FUNCTIONS_EMULATOR_HOST__??"").trim();if(i)return `http://${i}/${encodeURIComponent(t)}/us-central1`;let r=e.controlPlaneEndpoint?.trim()||(e.environment==="production"?"https://api.openrtc.app":"");if(!r)throw new Error("[OpenRTC] Internal staging coordination requires coordinationGateway.controlPlaneEndpoint.");let o=typeof globalThis.location?.origin=="string"?globalThis.location.origin:void 0,s=new URL(r,o);if(s.protocol!=="https:"&&s.protocol!=="http:"||s.username||s.password||s.search||s.hash)throw new Error("[OpenRTC] Coordination control-plane endpoint is invalid.");return s.toString().replace(/\/+$/,"")}function ze(n,e,t){return `${Ut(n,e)}/${encodeURIComponent(t)}`}async function qe(n){let e=`request failed with status ${n.status}`;try{let t=await n.json(),i=typeof t.error?.message=="string"?t.error.message.trim():"";return i?i.slice(0,256):e}catch{return e}}var oe=class n{constructor(e){this.options=e;this.runtimeInstanceId=k("runtime");this.socket=null;this.socketReady=false;this.connectPromise=null;this.desiredPresence=null;this.desiredExcludedPeers=[];this.devices=new Map;this.deviceListeners=new Set;this.deviceStreams=new Set;this.sessionStreams=new Set;this.pendingAcks=new Map;this.pendingMessages=[];this.roomConnections=new Map;this.friendConnections=new Map;this.reconnectTimer=null;this.authRefreshTimer=null;this.pendingAuthRefresh=null;this.budgetRenewalPromise=null;this.budgetRenewalEpoch=0;this.reconnectAttempt=0;this.reconnectCircuitOpen=false;this.hostResumeReconnectPromise=null;this.lastHostResumeReconnectAtMs=0;this.desiredPresenceRevision=0;this.appliedPresenceRevision=0;this.stopped=false;if(e.gateway.environment!=="staging"&&e.gateway.environment!=="production")throw new Error("[OpenRTC] Coordination gateway environment is invalid.");let t=new URL(e.gateway.endpoint),i=t.hostname==="127.0.0.1"||t.hostname==="localhost"||t.hostname==="[::1]",r=t.protocol==="https:"||t.protocol==="wss:",s=!!(typeof globalThis>"u"?"":String(globalThis.__OPENRTC_FUNCTIONS_EMULATOR_HOST__??"").trim())&&i&&(t.protocol==="http:"||t.protocol==="ws:");if(!r&&!s)throw new Error("[OpenRTC] Coordination gateway requires HTTPS/WSS.");if(t.username||t.password||t.search||t.hash)throw new Error("[OpenRTC] Coordination gateway credentials and parameters cannot be supplied in its URL.")}async updatePresence(e,t,i,r,o,s){let a=this.desiredPresence;this.desiredPresence={localNodeId:e,ticket:t,online:i,ttlMs:r,metadata:o,deviceName:s?.trim()||this.options.getDefaultDeviceName()},(!a||a.localNodeId!==e||a.ticket!==t||a.online!==i||a.ttlMs!==r||a.metadata!==o||a.deviceName!==this.desiredPresence.deviceName)&&(this.desiredPresenceRevision+=1,this.reconnectCircuitOpen=false,this.reconnectAttempt=0);let l=this.desiredPresenceRevision;await this.ensureConnected(),!(this.appliedPresenceRevision>=l)&&(a&&a.ticket!==t&&await this.refreshAuthentication(),await this.sendOperation({v:1,type:"presence.upsert",idempotencyKey:k("presence"),ttlMs:r,device:this.gatewayDevice(this.desiredPresence)}),this.appliedPresenceRevision=Math.max(this.appliedPresenceRevision,l));}async setOffline(e){this.desiredPresence&&(this.desiredPresence.online=false,this.socket?.readyState===WebSocket.OPEN&&await this.sendOperation({v:1,type:"presence.offline",idempotencyKey:k("offline")}));}async reconnectAfterHostResume(){if(this.desiredPresence){if(this.hostResumeReconnectPromise)return this.hostResumeReconnectPromise;if(!(Date.now()-this.lastHostResumeReconnectAtMs<Mt)){this.lastHostResumeReconnectAtMs=Date.now(),this.hostResumeReconnectPromise=(async()=>{(this.socket?.readyState===WebSocket.OPEN||this.socketReady)&&this.stopSocket(),await this.ensureConnected();})();try{await this.hostResumeReconnectPromise;}finally{this.hostResumeReconnectPromise=null;}}}}async updateDevice(e,t){if(e!==this.options.getLocalDeviceId())throw new Error("A coordination socket can update only its local device.");let i=t;if(t.excludedPeers!==void 0){let r=[...new Set(t.excludedPeers.map(o=>String(o??"").trim().toLowerCase()).filter(Boolean))].sort();if(r.length>Ge)throw new Error(`Coordination excluded-peer set exceeds ${Ge} devices.`);this.desiredExcludedPeers=r,i={...t,excludedPeers:r};}await this.ensureConnected(),await this.sendOperation({v:1,type:"device.patch",idempotencyKey:k("device-patch"),patch:i});}async deleteDevice(e){if(this.options.credentialPurpose!=="device-control"&&(!this.socketReady||this.socket?.readyState!==WebSocket.OPEN)){let t=new n({...this.options,credentialPurpose:"device-control"});try{await t.deleteDevice(e);}finally{t.stopAuthScopedActivity();}return}await this.ensureConnected();try{await this.sendOperation({v:1,type:"device.delete",idempotencyKey:k("device-delete"),targetDeviceId:e});}finally{this.options.credentialPurpose==="device-control"&&this.stopSocket();}}async cleanupStaleDevices(){}async searchDevices(e){return this.snapshot(e)}async listDevices(e){return this.snapshot(e)}onDevicesChange(e,t){let i=r=>e(t?r.filter(o=>o.nodeId!==t):r);return this.deviceListeners.add(i),i(this.snapshot()),this.desiredPresence&&this.ensureConnected(),()=>this.deviceListeners.delete(i)}async subscribeDevices(){let e=null;return new ReadableStream({start:t=>{e=t,this.deviceStreams.add(t);let i=this.snapshot().map(r=>({type:"added",device:r}));i.length>0&&t.enqueue(i);},cancel:()=>{e&&this.deviceStreams.delete(e),e=null;}})}async createSession(e){await this.ensureConnected(),await this.sendOperation({v:1,type:"session.put",idempotencyKey:k("session-put"),sessionId:e.connectionId,session:e,expiresAtMs:e.expiresAt??Date.now()+15*6e4});}async updateSession(e,t){await this.ensureConnected(),await this.sendOperation({v:1,type:"session.put",idempotencyKey:k("session-update"),sessionId:this.unscopedId(e),session:t,expiresAtMs:typeof t.expiresAt=="number"?t.expiresAt:Date.now()+15*6e4});}async subscribeSessions(e){let t=null;return new ReadableStream({start:i=>{t=i,this.sessionStreams.add(i);},cancel:()=>{t&&this.sessionStreams.delete(t),t=null;}})}async sendMessage(e,t,i,r){await this.ensureConnected();let o=k("signal");return await this.sendOperation({v:1,type:"signal.send",idempotencyKey:o,targetDeviceId:this.unscopedId(e),payload:t,state:i,replyPayload:r}),o}async pollMessages(e){return this.pendingMessages.splice(0,this.pendingMessages.length)}watchFriendDevices(e,t){let i=[...new Set(e.map(a=>a.trim()).filter(Boolean))];if(i.length>25)throw new RangeError(`watchFriendDevices accepts at most ${25} unique friend IDs per runtime.`);for(let a of i)if(a.length>128||a.includes("/"))throw new TypeError('Friend user IDs must be 1-128 characters and cannot contain "/".');let r={value:false},o=new Map,s=[];t(new Map);for(let a of i)!a||a===this.options.getCurrentUserId()||this.openFriendConnection(a).then(d=>{if(r.value){d.stopAuthScopedActivity();return}s.push(d.onDevicesChange(l=>{o.set(a,l.filter(c=>c.online)),t(new Map(o));}));}).catch(()=>{r.value||(o.set(a,[]),t(new Map(o)));});return ()=>{r.value=true;for(let a of s)a();for(let a of i)this.friendConnections.get(a)?.stopAuthScopedActivity(),this.friendConnections.delete(a);}}async updateFriendTicket(e){await this.ensureConnected(),await this.sendOperation({v:1,type:"device.patch",idempotencyKey:k("friend-ticket"),patch:{friendTicket:e??""}});}async handleScopeChange(){this.stopSocket(),this.reconnectCircuitOpen=false,this.reconnectAttempt=0,this.appliedPresenceRevision=0,this.devices.clear(),this.emitDevices();}stopAuthScopedActivity(){this.stopped=true,this.stopSocket(),this.desiredExcludedPeers=[];for(let e of this.pendingAcks.values())clearTimeout(e.timer),e.reject(new Error("Coordination session stopped."));this.pendingAcks.clear(),this.devices.clear(),this.pendingMessages.splice(0,this.pendingMessages.length),this.emitDevices();for(let e of this.roomConnections.values())e.stopAuthScopedActivity();this.roomConnections.clear();for(let e of this.friendConnections.values())e.stopAuthScopedActivity();this.friendConnections.clear();}usesCoordinationGateway(){return true}async joinCoordinationRoom(e,t,i){let r=e.trim().toUpperCase(),o=this.roomConnections.get(r);o||(o=new n({...this.options,avenueOverride:{kind:"room",id:r}}),this.roomConnections.set(r,o)),await o.updatePresence(t,i,true,5*6e4,void 0,this.options.getDefaultDeviceName());}async leaveCoordinationRoom(e){let t=e.trim().toUpperCase(),i=this.roomConnections.get(t);i&&(await i.setOffline(this.options.getLocalDeviceId()).catch(()=>{}),i.stopAuthScopedActivity(),this.roomConnections.delete(t));}async getCoordinationRoomMembers(e){return this.requireRoomConnection(e).snapshot().map(i=>this.roomMember(i))}watchCoordinationRoomMembers(e,t){return this.requireRoomConnection(e).onDevicesChange(r=>t(r.map(o=>this.roomMember(o))))}async ensureConnected(){if(this.connectPromise)return this.connectPromise;if(!(this.socket?.readyState===WebSocket.OPEN&&this.socketReady)){if(!this.desiredPresence&&this.options.credentialPurpose!=="device-control")throw new Error("Coordination presence must be initialized before the gateway can connect.");if(this.reconnectCircuitOpen)throw new b("Coordination reconnect circuit is open until presence or scope changes.",false);if(this.reconnectTimer)throw new b("Coordination reconnect is already scheduled.",true);this.stopped=false,this.connectPromise=this.connect();try{await this.connectPromise;}catch(e){throw this.scheduleReconnect(e),e}finally{this.connectPromise=null;}}}async connect(){let e=this.desiredPresence??this.controlPresence(),t=this.desiredPresenceRevision,i=async()=>{let r=await this.mintGatewayCredential(e);await new Promise((o,s)=>{let a=new WebSocket(Ft(r.gatewayUrl,r.routeKey),[Nt,`${xt}${r.token}`]);this.socket=a;let d=false,l=null,c=setTimeout(()=>{a.close(4408,"authentication timeout"),l=new b("Coordination gateway authentication timed out.",true),s(l);},fe);a.onopen=()=>{a.send(JSON.stringify({v:1,type:"auth",token:r.token,device:this.gatewayDevice(e)}));},a.onmessage=p=>{let h;try{h=JSON.parse(String(p.data));}catch{a.close(4400,"invalid gateway frame"),d||(clearTimeout(c),s(new Error("Coordination gateway returned an invalid frame.")));return}if(h.type==="ready"&&!d&&(d=true,this.socketReady=true,this.appliedPresenceRevision=Math.max(this.appliedPresenceRevision,this.desiredPresence?t:0),clearTimeout(c),this.reconnectAttempt=0,this.scheduleAuthRefresh(r.expiresAtMs),o()),h.type==="error"&&!d){l=new b(`Coordination gateway ${h.code}: ${h.message}`,h.retryable),clearTimeout(c),s(l),a.close(4403,h.code);return}this.handleFrame(h);},a.onerror=()=>{d||(clearTimeout(c),l??(l=new b("Coordination gateway connection failed.",true)),s(l));},a.onclose=p=>{clearTimeout(c),this.socket===a&&(this.socket=null,this.socketReady=false),this.rejectPendingAcks("Coordination gateway connection closed."),this.rejectPendingAuthRefresh(new b("Coordination gateway closed during credential refresh.",p.code!==4401&&p.code!==4403)),!this.stopped&&this.desiredPresence&&p.code!==1e3&&!He(l)&&this.scheduleReconnect(l??new b(`Coordination gateway closed (${p.code}).`,p.code!==4401));};});};try{await i();}catch(r){if(!He(r))throw r;await i();}}async mintGatewayCredential(e){let i={avenue:await this.resolveAvenue(),deviceId:this.options.getLocalDeviceId(),runtimeInstanceId:this.runtimeInstanceId,ticketFingerprint:await Bt(e.ticket),purpose:this.options.credentialPurpose??"presence",idempotencyKey:k("credential")},r;try{r=this.options.getPlatformType()==="web"?await this.mintBrowserCredential(i):await this.mintNativeCredential(i);}catch(s){throw s instanceof b?s:new b(s instanceof Error?s.message:"Coordination credential mint failed.",!Ke(s))}if(r.protocolVersion!==1)throw new b("Unsupported coordination gateway protocol.",false);let o=je(this.options.gateway.endpoint);if(je(r.gatewayUrl)!==o)throw new b("Coordination credential returned an unexpected gateway origin.",false);return r}async mintBrowserCredential(e){let t=async s=>{let a=await this.options.getAuthToken(s);if(!a)throw new b("[OpenRTC] Browser coordination requires an authenticated runtime.",false);let d=await this.options.getAppCheckToken(s);if(!d)throw new b("[OpenRTC] Browser coordination requires platform attestation.",false);return fetch(ze(this.options.projectId,this.options.gateway,"mintCoordinationCredential"),{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${a}`,"X-Firebase-AppCheck":d},body:JSON.stringify({data:e}),signal:AbortSignal.timeout(15e3)})},i=await t(false);if((i.status===401||i.status===403)&&(i=await t(true)),!i.ok)throw new b(`[OpenRTC] Browser coordination credential denied: ${await qe(i)}`,i.status===408||i.status===425||i.status===429||i.status>=500);let r=await i.json(),o=r.result??r.data;if(!o)throw new b("[OpenRTC] Browser coordination credential returned an invalid callable response.",false);return o}async getNativeTrustToken(e=false){return (await this.options.nativeTrustTokens.get(e)).token}async mintNativeCredential(e){let t=await this.options.getAuthToken(false);if(!t)throw new Error("[OpenRTC] Native coordination requires an authenticated runtime.");let i=async a=>{let[d,l]=await Promise.all([a?this.options.getAuthToken(true):Promise.resolve(t),this.getNativeTrustToken(a)]);if(!d)throw new Error("[OpenRTC] Native coordination requires an authenticated runtime.");return fetch(ze(this.options.projectId,this.options.gateway,"mintNativeCoordinationCredential"),{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${d}`,"X-Firebase-AppCheck":l},body:JSON.stringify({data:e}),signal:AbortSignal.timeout(15e3)})},r=await i(false);if((r.status===401||r.status===403)&&(this.options.nativeTrustTokens.invalidate(),r=await i(true)),!r.ok)throw new b(`[OpenRTC] Native coordination credential denied: ${await qe(r)}`,r.status===408||r.status===425||r.status===429||r.status>=500);let o=await r.json(),s=o.result??o.data;if(!s)throw new Error("[OpenRTC] Native coordination credential returned an invalid callable response.");return s}handleFrame(e){if(e.type==="auth.refreshed"){let t=this.pendingAuthRefresh;t&&(clearTimeout(t.timer),this.pendingAuthRefresh=null,this.scheduleAuthRefresh(e.expiresAtMs),t.resolve());}else if(e.type==="roster.snapshot"){this.devices.clear();for(let t of e.devices)this.devices.set(t.deviceId,this.toDevice(t));this.emitDevices();}else if(e.type==="presence.changed"){if(e.operation==="delete")this.devices.delete(e.device.deviceId),this.emitDeviceEvents([{type:"removed",deviceId:e.device.deviceId}]);else {let t=this.devices.has(e.device.deviceId),i=this.toDevice(e.device);this.devices.set(i.deviceId,i),this.emitDeviceEvents([{type:t?"modified":"added",device:i}]);}this.emitDevices();}else if(e.type==="signal.received")this.pendingMessages.length>=Ot&&this.pendingMessages.shift(),this.pendingMessages.push({senderId:e.senderDeviceId,targetId:this.options.getLocalDeviceId(),payload:e.payload,state:e.state,replyPayload:e.replyPayload,timestamp:e.createdAtMs,appTag:this.options.appTag});else if(e.type==="session.changed"){let t=e.operation==="delete"?[{type:"removed",sessionId:e.sessionId}]:[{type:"modified",session:{...e.session??{},connectionId:e.sessionId}}];for(let i of this.sessionStreams)i.enqueue(t);}else if(e.type==="ack"){let t=this.pendingAcks.get(e.idempotencyKey);t&&(clearTimeout(t.timer),this.pendingAcks.delete(e.idempotencyKey),t.resolve());}else if(e.type==="error"){if(!e.idempotencyKey&&this.pendingAuthRefresh){let i=this.pendingAuthRefresh;clearTimeout(i.timer),this.pendingAuthRefresh=null,i.reject(new b(`Coordination gateway ${e.code}: ${e.message}`,e.retryable));return}let t=e.idempotencyKey?this.pendingAcks.get(e.idempotencyKey):null;t&&(clearTimeout(t.timer),this.pendingAcks.delete(e.idempotencyKey),t.reject(new re(e.code,e.message,e.retryable)));}}async sendOperation(e){this.budgetRenewalPromise&&await this.budgetRenewalPromise;let t=this.budgetRenewalEpoch;try{await this.sendOperationOnce(e);}catch(i){if(!(i instanceof re)||i.code!=="budget-renewal-required"&&i.code!==f.BUDGET_RENEWAL_REQUIRED||!i.retryable)throw i;this.budgetRenewalEpoch===t&&await this.renewBudget(),await this.sendOperationOnce(e);}}async sendOperationOnce(e){let t=this.socket;if(!t||t.readyState!==WebSocket.OPEN||!this.socketReady)throw new Error("Coordination gateway is not connected.");await new Promise((i,r)=>{let o=setTimeout(()=>{this.pendingAcks.delete(e.idempotencyKey),r(new Error("Coordination gateway acknowledgement timed out."));},fe);this.pendingAcks.set(e.idempotencyKey,{resolve:i,reject:r,timer:o}),t.send(JSON.stringify(e));});}async renewBudget(){if(this.budgetRenewalPromise)return this.budgetRenewalPromise;let e=this.refreshAuthentication().then(()=>{this.budgetRenewalEpoch+=1;});this.budgetRenewalPromise=e;try{await e;}finally{this.budgetRenewalPromise===e&&(this.budgetRenewalPromise=null);}}async resolveAvenue(){if(this.options.avenueOverride)return this.options.avenueOverride;if((this.options.discoveryMode??"space")==="space"){let t=await this.options.resolveSpaceNamespaceId();if(!t)throw new Error("Space namespace is not available for coordination.");return {kind:"space",id:t}}let e=this.options.getCurrentUserId();if(!e)throw new Error("Authenticated user is required for coordination.");return {kind:"user",id:e}}gatewayDevice(e){return {deviceId:this.options.getLocalDeviceId(),runtimeInstanceId:this.runtimeInstanceId,nodeId:e.localNodeId,deviceName:e.deviceName,platformType:this.options.getPlatformType(),ticket:e.ticket,metadata:e.metadata,excludedPeers:this.desiredExcludedPeers,online:e.online}}controlPresence(){if(this.options.credentialPurpose!=="device-control")throw new Error("Coordination presence must be initialized before the gateway can connect.");return {localNodeId:this.options.getLocalDeviceId(),ticket:`openrtc-device-control:${this.runtimeInstanceId}`,online:false,ttlMs:0,deviceName:this.options.getDefaultDeviceName()}}toDevice(e){return this.options.normalizeDevice({...e,appTag:this.options.appTag,lastSeenAt:e.updatedAtMs,expiresAt:e.expiresAtMs},e.deviceId)}snapshot(e){return [...this.devices.values()].filter(t=>!e||t.nodeId!==e).sort((t,i)=>t.deviceId.localeCompare(i.deviceId))}emitDevices(){let e=this.snapshot();for(let t of this.deviceListeners)t(e);}emitDeviceEvents(e){for(let t of this.deviceStreams)t.enqueue(e);}scheduleAuthRefresh(e){this.authRefreshTimer&&clearTimeout(this.authRefreshTimer);let t=e-Date.now(),i=t>We+1e3;this.authRefreshTimer=setTimeout(()=>{if(this.authRefreshTimer=null,!this.stopped){if(!i){this.stopSocket(false),this.scheduleReconnect(new b("Coordination credential crossed a billing boundary.",true));return}this.refreshAuthentication().catch(r=>{this.stopSocket(false),this.scheduleReconnect(r);});}},i?t-We:Math.max(1e3,t+1e3));}async refreshAuthentication(){let e=this.socket,t=this.desiredPresence;if(!e||e.readyState!==WebSocket.OPEN||!this.socketReady||!t)throw new b("Coordination socket is unavailable for credential refresh.",true);if(this.pendingAuthRefresh)return this.pendingAuthRefresh.promise;let i=await this.mintGatewayCredential(t),r,o,s=new Promise((d,l)=>{r=d,o=l;}),a=setTimeout(()=>{this.pendingAuthRefresh?.timer===a&&(this.pendingAuthRefresh=null),o(new b("Coordination credential refresh timed out.",true));},fe);this.pendingAuthRefresh={promise:s,resolve:r,reject:o,timer:a},e.send(JSON.stringify({v:1,type:"auth.refresh",token:i.token})),await s;}scheduleReconnect(e){if(this.reconnectTimer||this.reconnectCircuitOpen||this.stopped)return;if(!(e instanceof b?e.retryable:!Ke(e))||this.reconnectAttempt>=Dt){this.reconnectCircuitOpen=true;return}let i=Lt(x$1(this.reconnectAttempt++,250,kt));this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=null,this.ensureConnected().catch(r=>this.scheduleReconnect(r));},i);}stopSocket(e=true){e&&this.reconnectTimer&&clearTimeout(this.reconnectTimer),this.authRefreshTimer&&clearTimeout(this.authRefreshTimer),this.reconnectTimer=null,this.authRefreshTimer=null,this.rejectPendingAuthRefresh(new b("Coordination credential refresh was canceled.",true));let t=this.socket;this.socket=null,this.socketReady=false,t?.close(1e3,"coordination session stopped");}rejectPendingAuthRefresh(e){let t=this.pendingAuthRefresh;t&&(clearTimeout(t.timer),this.pendingAuthRefresh=null,t.reject(e));}rejectPendingAcks(e){for(let t of this.pendingAcks.values())clearTimeout(t.timer),t.reject(new Error(e));this.pendingAcks.clear();}unscopedId(e){let t=e.split("::");return t.length===2?t[1]:e}requireRoomConnection(e){let t=e.trim().toUpperCase(),i=this.roomConnections.get(t);if(!i)throw new Error(`Room ${t} is not joined through the coordination gateway.`);return i}async openFriendConnection(e){let t=this.friendConnections.get(e);if(t||(t=new n({...this.options,avenueOverride:{kind:"user",id:e}}),this.friendConnections.set(e,t)),!t.desiredPresence){if(!this.desiredPresence)throw new Error("Local coordination presence must start before friend discovery.");t.desiredPresence={...this.desiredPresence};}return await t.ensureConnected(),t}roomMember(e){return {nodeId:e.nodeId??e.deviceId,userId:e.userId??"",ticket:e.ticket,joinedAt:Number(e.createdAt??e.lastSeenAt??Date.now()),lastSeenAt:Number(e.lastSeenAt??Date.now()),expiresAt:typeof e.expiresAt=="number"?e.expiresAt:void 0}}};var se=class{constructor(e){this.provider=e;this.cached=null;this.inFlight=null;this.refreshTimer=null;this.refreshRetryUsed=false;this.listeners=new Set;}async get(e=false){if(!this.provider)throw new Error("[OpenRTC] Native coordination requires coordinationGateway.nativeTrustTokenProvider; obtain tokens through a trusted backend without shipping the developer secret.");let t=Date.now();if(!e&&this.cached&&this.cached.expiresAtMs>t+3e4)return this.cached;if(this.inFlight)return this.inFlight;let i=(async()=>{let r=await this.provider(e),o=r?.token?.trim()??"",s=Number(r?.expiresAtMs),a=Date.now();if(!o||!Number.isFinite(s)||s<=a+3e4)throw new Error("[OpenRTC] Native trust token provider returned no usable short-lived token.");let d={token:o,expiresAtMs:s};return this.cached=d,this.refreshRetryUsed=false,this.notify(d),this.scheduleRefresh(d),d})();this.inFlight=i;try{return await i}finally{this.inFlight===i&&(this.inFlight=null);}}invalidate(){this.cached=null,this.clearRefreshTimer(),this.notify(null);}clear(){this.invalidate(),this.listeners.clear();}subscribe(e,t){return this.listeners.add(e),this.cached&&this.cached.expiresAtMs>Date.now()&&(t?.emitCurrent!==false&&e(this.cached),this.scheduleRefresh(this.cached)),()=>{this.listeners.delete(e),this.listeners.size===0&&this.clearRefreshTimer();}}notify(e){for(let t of this.listeners)t(e);}scheduleRefresh(e){if(this.clearRefreshTimer(),this.listeners.size===0)return;let t=Math.max(0,e.expiresAtMs-Date.now()-3e4);this.refreshTimer=setTimeout(()=>{this.refreshTimer=null,this.get(true).catch(()=>{if(this.listeners.size===0||this.refreshRetryUsed){this.invalidate();return}this.refreshRetryUsed=true,this.refreshTimer=setTimeout(()=>{this.refreshTimer=null,this.get(true).catch(()=>this.invalidate());},15e3);});},t);}clearRefreshTimer(){this.refreshTimer&&(clearTimeout(this.refreshTimer),this.refreshTimer=null);}};function ae(n){if(!n)return null;let e=2166136261;for(let t=0;t<n.length;t+=1)e^=n.charCodeAt(t),e=Math.imul(e,16777619);return `fp-${(e>>>0).toString(16).padStart(8,"0")}`}var T=class T{constructor(e){this.deps=e;this.startedAutoConnectKey=null;this.browserAutoConnectUnsubscribe=null;this.desiredPeerRevision=0;this.desiredPeerSignature=null;this.desiredPeerSubmission=null;this.desiredPeerSubmissionQueue=Promise.resolve();this.queuedDesiredPeers=null;this.desiredPeersByDeviceId=new Map;this.wakeSubmission=null;this.presenceState=null;this.presenceStartGeneration=0;this.durablePresenceRetryTimer=null;this.durablePresenceRetryAttempt=0;this.localExcludedPeers=new Set;}stop(){this.stopAutoConnect(),this.stopPresenceLoop();}get autoConnectKey(){return this.startedAutoConnectKey}set autoConnectKey(e){this.startedAutoConnectKey=e;}get presenceLoopState(){return this.presenceState}set presenceLoopState(e){this.presenceState=e;}stopPresence(){this.stopPresenceLoop();}updatePresenceLoopState(e){this.presenceState=e;}startAutoConnect(e,t){if(this.deps.isTicketOnlyMode())return;let i=t.trim()||this.deps.resolveWebLogicalDeviceId(),r=`${e}::${i}`;this.startedAutoConnectKey===r&&this.browserAutoConnectUnsubscribe||(this.stopAutoConnect(),this.startedAutoConnectKey=r,this.browserAutoConnectUnsubscribe=this.deps.getCoordinationSignaling().onDevicesChange(o=>this.submitDesiredPeers(o),this.currentLocalNodeId()??void 0));}wakeRustAutoConnectOwner(){return this.deps.isTicketOnlyMode()||!this.startedAutoConnectKey||this.wakeSubmission?false:(this.wakeSubmission=this.deps.waitForWasmClient(500).then(async e=>{e&&typeof e.wake_browser_auto_connect=="function"&&await e.wake_browser_auto_connect();}).finally(()=>{this.wakeSubmission=null;}),true)}submitDesiredPeers(e){if(!this.startedAutoConnectKey)return;let t=this.normalizeDesiredPeers(e);this.desiredPeersByDeviceId=new Map(t.map(r=>[r.deviceId,r]));let i=JSON.stringify(t);i!==this.desiredPeerSignature&&(this.desiredPeerSignature=i,this.deps.onDesiredPeersChanged?.(),this.queuedDesiredPeers=t,this.flushDesiredPeerSubmission());}async submitDesiredPeerProjection(e,t){if(!Number.isSafeInteger(e)||e<=0)throw new Error("Desired-peer projection revision must be a positive safe integer.");let i=this.startedAutoConnectKey;if(!i)throw new Error("Cannot submit a desired-peer projection before managed auto-connect starts.");let r=this.normalizeDesiredPeers(t),o=JSON.stringify(r),s=o!==this.desiredPeerSignature;this.desiredPeerSignature=o,this.desiredPeersByDeviceId=new Map(r.map(a=>[a.deviceId,a])),this.queuedDesiredPeers=null,this.desiredPeerRevision=Math.max(this.desiredPeerRevision,e),s&&this.deps.onDesiredPeersChanged?.(),await this.enqueueDesiredPeerSubmission(i,e,r);}resolveDesiredPeer(e,t){let i=typeof e=="string"?e.trim():"",r=typeof t=="string"?t.trim():"";if(i){let o=this.desiredPeersByDeviceId.get(i);if(o&&(!r||!o.nodeId||o.nodeId===r))return o}return r?Array.from(this.desiredPeersByDeviceId.values()).find(o=>o.nodeId===r)??null:null}flushDesiredPeerSubmission(){if(this.desiredPeerSubmission||!this.queuedDesiredPeers||!this.startedAutoConnectKey)return;let e=this.startedAutoConnectKey,t=this.queuedDesiredPeers,i=++this.desiredPeerRevision;this.queuedDesiredPeers=null,this.desiredPeerSubmission=this.enqueueDesiredPeerSubmission(e,i,t).catch(()=>{}).finally(()=>{this.desiredPeerSubmission=null,this.flushDesiredPeerSubmission();});}normalizeDesiredPeers(e){return (Array.isArray(e)?e:[]).map(t=>({deviceId:String(t?.deviceId??"").trim(),nodeId:typeof t?.nodeId=="string"&&t.nodeId.trim()||null,ticket:typeof t?.ticket=="string"&&t.ticket.trim()||null,online:t?.online===true,sessionId:typeof t?.sessionId=="string"&&t.sessionId.trim()||null,excludedPeers:Array.isArray(t?.excludedPeers)?[...new Set(t.excludedPeers.map(i=>String(i??"").trim().toLowerCase()).filter(Boolean))].sort():[]})).filter(t=>t.deviceId.length>0).sort((t,i)=>t.deviceId.localeCompare(i.deviceId))}enqueueDesiredPeerSubmission(e,t,i){let r=this.desiredPeerSubmissionQueue.then(async()=>{if(this.startedAutoConnectKey!==e)return;let o=await this.deps.waitForWasmClient();if(this.startedAutoConnectKey===e){if(!o||typeof o.submit_browser_desired_peers!="function"){this.deps.warnMissingWasmOnce("submitBrowserDesiredPeers");return}await Promise.all(i.map(async s=>{if(s.ticket)try{await this.deps.rememberRouteRepairTokenFromTicket(s.ticket);}catch(a){console.warn("[WasmSignaling] failed to retain desired-peer admission token",{deviceId:s.deviceId,nodeId:s.nodeId,error:a});}})),await o.submit_browser_desired_peers(t,JSON.stringify(i));}});return this.desiredPeerSubmissionQueue=r.catch(o=>{console.warn("[WasmSignaling] failed to submit browser desired peers to Rust",{revision:t,error:o});}),r}async setAutoConnectExcluded(e,t){let i=await this.deps.waitForWasmClient();i&&typeof i.set_auto_connect_excluded=="function"&&await i.set_auto_connect_excluded(e,t),await this.recordAutoConnectExcludedForPresence(e,t);}async recordAutoConnectExcludedForPresence(e,t){let i=e.trim().toLowerCase();if(!i)return;t?this.localExcludedPeers.add(i):this.localExcludedPeers.delete(i);let r=this.deps.resolveWebLogicalDeviceId();r&&await this.deps.updateExcludedPeers(r,this.currentExcludedPeersSnapshot());}startPresenceLoop(e,t,i,r,o){if(this.deps.isTicketOnlyMode())return;this.stopPresenceLoop();let s=++this.presenceStartGeneration;this.presenceState={userId:e,localNodeId:t,ticket:r,metadata:o,deviceName:i};let a=this.deps.resolveWebLogicalDeviceId();(async()=>{let l=await this.deps.withWebPresenceMetadata(o,a);if(!(s===this.presenceStartGeneration&&this.presenceState!==null))return;let p=false,h=null,y=(v,S)=>{this.scheduleDurableRosterRetry(a,s,T.PRESENCE_LEASE_MS,v,S);};h=setTimeout(()=>{p||y("initial coordination presence write timed out");},T.INITIAL_PRESENCE_WRITE_TIMEOUT_MS),this.deps.updatePresence(t,r,true,T.PRESENCE_LEASE_MS,l,i).then(()=>{p=true,h&&(clearTimeout(h),h=null),this.clearDurablePresenceRetryTimer(),this.durablePresenceRetryAttempt=0;}).catch(v=>{h&&(clearTimeout(h),h=null),y("initial coordination presence write failed",v);});})();}clearDurablePresenceRetryTimer(){this.durablePresenceRetryTimer&&(clearTimeout(this.durablePresenceRetryTimer),this.durablePresenceRetryTimer=null);}scheduleDurableRosterRetry(e,t,i,r,o){if(t!==this.presenceStartGeneration||this.presenceState===null||this.durablePresenceRetryTimer||this.isPermanentProviderError(o))return;let s=this.durablePresenceRetryAttempt+1;if(s>T.PRESENCE_RETRY_LIMIT){console.warn(`[WasmBridge] ${r}; durable roster retry circuit opened after ${T.PRESENCE_RETRY_LIMIT} attempts`,o);return}this.durablePresenceRetryAttempt=s;let a=Math.min(T.PRESENCE_RETRY_MIN_DELAY_MS*2**Math.min(8,s-1),T.PRESENCE_RETRY_MAX_DELAY_MS),d=(s*17%21-10)/100,l=Math.max(T.PRESENCE_RETRY_MIN_DELAY_MS,Math.trunc(a+a*d));console.warn(`[WasmBridge] ${r}; retrying coordination presence in ${l}ms`,o),this.durablePresenceRetryTimer=setTimeout(()=>{this.durablePresenceRetryTimer=null,!(t!==this.presenceStartGeneration||this.presenceState===null)&&(async()=>{if(this.presenceState===null)return;let c=await this.deps.withWebPresenceMetadata(this.presenceState.metadata,e);t!==this.presenceStartGeneration||this.presenceState===null||await this.deps.updatePresence(this.presenceState.localNodeId,this.presenceState.ticket,true,i,c,this.presenceState.deviceName);})().then(()=>{this.durablePresenceRetryAttempt=0,this.clearDurablePresenceRetryTimer();}).catch(c=>{this.scheduleDurableRosterRetry(e,t,i,"durable roster registration retry failed",c);});},l);}isPermanentProviderError(e){let i=(e&&typeof e=="object"&&"code"in e?String(e.code??""):"").toLowerCase().replace(/^functions\//,"");return ["auth/invalid-user-token","auth/user-token-expired","auth/user-disabled","permission-denied","unauthenticated","invalid-argument","failed-precondition"].some(r=>i===r||i.endsWith(`/${r}`))}stopAutoConnect(){this.browserAutoConnectUnsubscribe?.(),this.browserAutoConnectUnsubscribe=null,this.startedAutoConnectKey=null,this.desiredPeerSignature=null,this.queuedDesiredPeers=null,this.desiredPeersByDeviceId.clear(),this.wakeSubmission=null;}currentExcludedPeersSnapshot(){return Array.from(this.localExcludedPeers).sort()}currentLocalNodeId(){let e=this.presenceState?.localNodeId;return typeof e=="string"&&e.trim()||null}stopPresenceLoop(){this.presenceStartGeneration+=1,this.clearDurablePresenceRetryTimer(),this.durablePresenceRetryAttempt=0,this.presenceState=null;}};T.INITIAL_PRESENCE_WRITE_TIMEOUT_MS=5e3,T.PRESENCE_RETRY_MIN_DELAY_MS=2e3,T.PRESENCE_RETRY_MAX_DELAY_MS=6e4,T.PRESENCE_RETRY_LIMIT=8,T.PRESENCE_LEASE_MS=15*6e4;var ce=T;var le="trustedDevice",Wt="plutonium:e2ee:identity:v1",Gt="plutonium:e2ee:identity:session:v1",Ht="openrtc-trust",K="identity",Ye="transport-trust:v1",Kt=1,P=null,Y=null;function M(n){let e=atob(n),t=new Uint8Array(e.length);for(let i=0;i<e.length;i+=1)t[i]=e.charCodeAt(i);return t}function $(n){let e="";for(let t=0;t<n.length;t+=1)e+=String.fromCharCode(n[t]);return btoa(e)}async function $e(n){let e=await crypto.subtle.digest("SHA-256",n),t=new Uint8Array(e);return Array.from(t).map(i=>i.toString(16).padStart(2,"0")).join("")}function jt(){return typeof sessionStorage>"u"?null:sessionStorage}function zt(){if(!(typeof localStorage>"u"))try{localStorage.removeItem(Wt);}catch{}}var de=null;async function Xe(){return de||(de=(async()=>{let n=globalThis.crypto?.subtle;if(!n||typeof n.generateKey!="function")return false;try{let e=await n.generateKey({name:"Ed25519"},!1,["sign","verify"]);return !!(e&&e.privateKey&&e.publicKey)}catch{return false}})(),de)}async function qt(n){let e=await crypto.subtle.exportKey("raw",n);return new Uint8Array(e)}function Yt(){try{return typeof indexedDB<"u"?indexedDB:null}catch{return null}}function Ve(){let n=Yt();return n?new Promise(e=>{let t;try{t=n.open(Ht,1);}catch{e(null);return}t.onupgradeneeded=()=>{let i=t.result;i.objectStoreNames.contains(K)||i.createObjectStore(K);},t.onsuccess=()=>e(t.result),t.onerror=()=>e(null),t.onblocked=()=>e(null);}):Promise.resolve(null)}async function $t(){let n=await Ve();if(!n)return null;try{return await new Promise(e=>{let r=n.transaction(K,"readonly").objectStore(K).get(Ye);r.onsuccess=()=>{let o=r.result;e(o&&o.privateKey&&o.publicKey?o:null);},r.onerror=()=>e(null);})}catch{return null}finally{n.close();}}async function Xt(n){let e=await Ve();if(!e)return false;try{return await new Promise(t=>{let i=e.transaction(K,"readwrite");i.objectStore(K).put(n,Ye),i.oncomplete=()=>t(!0),i.onerror=()=>t(!1),i.onabort=()=>t(!1);})}catch{return false}finally{e.close();}}async function Je(n,e){let t=await qt(n.publicKey),i=await $e(t),r=n.privateKey;return {publicKey:t,fingerprint:i,backend:"webcrypto-nonextractable",durable:e,privateKey:r,async signChallenge(o){let s=await crypto.subtle.sign({name:"Ed25519"},r,M(o));return $(new Uint8Array(s))}}}function Vt(n,e,t){let i=n.secretKey;return {publicKey:n.publicKey,secretKey:i,fingerprint:e,backend:"tweetnacl",durable:t,async signChallenge(r){return Jt(r,i)}}}function Ln(n=32){let e=crypto.getRandomValues(new Uint8Array(n));return $(e)}function Jt(n,e){let t=ue.sign.detached(M(n),e);return $(t)}function Qt(n,e,t){try{return ue.sign.detached.verify(M(n),M(e),M(t))}catch{return false}}async function Bn(n,e,t){let i=globalThis.crypto?.subtle;if(i&&typeof i.importKey=="function"&&typeof i.verify=="function")try{let r=await i.importKey("raw",M(t),{name:"Ed25519"},!1,["verify"]);return await i.verify({name:"Ed25519"},r,M(e),M(n))}catch{}return Qt(n,e,t)}function Fn(n){return $(n)}function Un(n){if(!n||!n.trim())return null;try{let e=JSON.parse(n),t=e&&typeof e=="object"&&!Array.isArray(e)?e[le]:null;if(!t||typeof t!="object"||Array.isArray(t))return null;let i=t,r=typeof i.version=="number"?i.version:null,o=typeof i.identityPublicKey=="string"?i.identityPublicKey:null,s=typeof i.identityFingerprint=="string"?i.identityFingerprint:null;return !r||!o||!s?null:{version:r,identityPublicKey:o,identityFingerprint:s}}catch{return null}}async function Zt(){let n=await on().catch(()=>null);return n?{version:Kt,identityPublicKey:$(n.publicKey),identityFingerprint:n.fingerprint}:null}async function me(n){let e=await Zt();if(!e)return n??void 0;let t=typeof n=="string"?n.trim():"";if(!t)return JSON.stringify({[le]:e});try{let i=JSON.parse(t);if(i&&typeof i=="object"&&!Array.isArray(i))return JSON.stringify({...i,[le]:e})}catch{}return JSON.stringify({metadata:n,[le]:e})}function en(){if(typeof window>"u")return null;let n=window.__TAURI_INTERNALS__;return !n||typeof n.invoke!="function"?null:n.invoke.bind(n)}async function tn(){if(!t()||typeof window>"u")return null;let n=en();if(!n)return null;try{let e=await n("openrtc_get_transport_trust_identity");return {publicKey:M(e.publicKeyBase64),fingerprint:e.fingerprint,backend:"native-provider",durable:!0,async signChallenge(i){return n("openrtc_sign_transport_trust_challenge",{challenge:i})}}}catch{return null}}function nn(){let n=jt();n&&n.removeItem(Gt);}async function rn(){if(zt(),nn(),P)return P;let n=await tn();if(n)return P=n,P;if(await Xe()){let e=await $t();if(e)return P=await Je(e,true),P}return null}async function on(n={}){let e=await rn();if(e)return e;if(Y)return Y;let t=sn(n);Y=t;try{return await t}finally{Y===t&&(Y=null);}}async function sn(n){if(P)return P;let e=n.ephemeral===true;if(await Xe())try{let t=await crypto.subtle.generateKey({name:"Ed25519"},!1,["sign","verify"]),i=!1;return e||(i=await Xt(t)),P=await Je(t,i),P}catch{}if(!e)return console.warn("[OpenRTC][TRUST] Managed transport trust requires WebCrypto Ed25519 or native keychain; refusing extractable fallback storage"),null;try{let t=ue.sign.keyPair(),i=await $e(v(t.publicKey));return P=Vt(t,i,!1),P}catch{return null}}function Qe(n){if(n.errorCode)return n;let e=n.error||n.readinessReason;if(!e)return n;let t=Be(e);return {...n,errorCode:t.errorCode,retryable:t.retryable,errorPlane:t.errorPlane}}function j(n){return !n||typeof n!="object"?{}:n instanceof Map?Object.fromEntries(n):n}function ge(n){let e=j(n),t=j(e.device);if(!Object.keys(t).length)return e;let i={...t,...e};return delete i.device,i}function u(n,...e){for(let t of e){let i=n[t];if(typeof i=="string"&&i.trim().length>0)return i}}function x(n,...e){for(let t of e){let i=n[t];if(typeof i=="boolean")return i}}function m(n,...e){for(let t of e){let i=n[t];if(typeof i=="number"&&Number.isFinite(i))return i}}function L(n){if(typeof n=="number"&&Number.isFinite(n))return n;if(n instanceof Date){let e=n.getTime();return Number.isFinite(e)?e:void 0}if(typeof n=="string"){let e=Date.parse(n);return Number.isFinite(e)?e:void 0}if(n&&typeof n=="object"){let e=n;if(typeof e.toMillis=="function"){let i=e.toMillis();return Number.isFinite(i)?i:void 0}let t=typeof e.seconds=="number"?e.seconds:typeof e._seconds=="number"?e._seconds:void 0;if(t!==void 0&&Number.isFinite(t)){let i=typeof e.nanoseconds=="number"?e.nanoseconds:typeof e._nanoseconds=="number"?e._nanoseconds:0;return t*1e3+Math.floor((Number.isFinite(i)?i:0)/1e6)}}}function ye(...n){let e=n.map(L).filter(t=>typeof t=="number"&&Number.isFinite(t));return e.length?Math.max(...e):void 0}function ve(n){if(typeof n!="string")return;let e=n.trim().toLowerCase();return e==="online"||e==="idle"||e==="offline"?e:void 0}function Ze(n){let e=ve("presenceStatus"in n?n.presenceStatus:void 0),t="presenceUpdatedAt"in n?L(n.presenceUpdatedAt):void 0,i="presenceExpiresAt"in n?L(n.presenceExpiresAt):void 0,r=t??ye(n.lastSeenAt,n.updatedAt,n.createdAt),o=i??L(n.expiresAt),s=e;s||(n.online?r!==void 0&&r+3e5<=Date.now()?s="idle":s="online":s="offline");let a=typeof n.ticket=="string"?n.ticket.trim():"",d="connectable"in n&&typeof n.connectable=="boolean"?n.connectable:s==="online"&&a.length>0;return {presenceStatus:s,presenceUpdatedAt:r,presenceExpiresAt:o,connectable:d}}function et(n){return b$2(n)}function z(n,...e){return et(u(n,...e))}function V(n){if(!Array.isArray(n))return;let e=Array.from(new Set(n.map(et).filter(t=>!!t)));return e.length?e:void 0}function tt(n){let e=j(n),t={webrtc:m(e,"webrtc"),webrtcLan:m(e,"webrtcLan","webrtc_lan"),webrtcTurn:m(e,"webrtcTurn","webrtc_turn"),iroh:m(e,"iroh"),irohLan:m(e,"irohLan","iroh_lan"),irohRelay:m(e,"irohRelay","iroh_relay"),ble:m(e,"ble"),moq:m(e,"moq")};return Object.values(t).some(i=>i!==void 0)?t:void 0}function nt(n){return (n.discoveryMode??"space")==="space"&&typeof n.apiKey=="string"&&n.apiKey.trim().length>0&&typeof n.spaceKey=="string"&&n.spaceKey.trim().length>0}function it(n,e,t){return t?true:(typeof n.appTag=="string"?n.appTag:typeof n.tag=="string"?n.tag:void 0)===e}function be(n,e){let t=ge(n),i=u(t,"deviceId","device_id")||e||"",r=u(t,"nodeId","node_id")||"",o=u(t,"ticket")||"";return {deviceId:i,deviceName:u(t,"deviceName","device_name")||"Unknown Device",online:!!t.online,ticket:o,friendTicket:u(t,"friendTicket","friend_ticket"),presenceStatus:ve(u(t,"presenceStatus","presence_status","livenessStatus","liveness_status")),presenceUpdatedAt:m(t,"presenceUpdatedAt","presence_updated_at")??ye(t.presenceUpdatedAt,t.presence_updated_at,t.lastSeenAt,t.last_seen_at,t.updatedAt,t.updated_at,t.createdAt,t.created_at),presenceExpiresAt:m(t,"presenceExpiresAt","presence_expires_at")??L(t.presenceExpiresAt??t.presence_expires_at)??L(t.expiresAt??t.expires_at),connectable:x(t,"connectable"),kind:u(t,"kind"),nodeId:r||void 0,platformType:u(t,"platformType","platform_type"),capabilities:t.capabilities||void 0,sessionId:u(t,"sessionId","session_id"),userId:u(t,"userId","user_id"),lastSeenAt:t.lastSeenAt??t.last_seen_at,expiresAt:t.expiresAt??t.expires_at,createdAt:t.createdAt??t.created_at,updatedAt:t.updatedAt??t.updated_at,metadata:u(t,"metadata"),excludedPeers:Se(t.excludedPeers??t.excluded_peers),availableTransports:V(t.availableTransports??t.available_transports),transports:V(t.transports)}}function Se(n){return Array.isArray(n)?n.filter(e=>typeof e=="string"):[]}function an(n){let e=Ze(n);return {...n,...e,connectionStatus:"connectionStatus"in n&&typeof n.connectionStatus=="string"?n.connectionStatus:n.online?"online":"disconnected",settledReady:"settledReady"in n&&typeof n.settledReady=="boolean"?n.settledReady:false,readinessState:"readinessState"in n&&typeof n.readinessState=="string"?n.readinessState:void 0,readinessReason:"readinessReason"in n&&typeof n.readinessReason=="string"?n.readinessReason:void 0,peerHealth:"peerHealth"in n&&typeof n.peerHealth=="string"?n.peerHealth:"unknown",peerId:"peerId"in n&&typeof n.peerId=="string"?n.peerId:void 0,promotionEligible:"promotionEligible"in n&&typeof n.promotionEligible=="boolean"?n.promotionEligible:true,scopes:"scopes"in n?Se(n.scopes):[],connectionId:"connectionId"in n&&typeof n.connectionId=="string"?n.connectionId:void 0,deviceIdHint:"deviceIdHint"in n&&typeof n.deviceIdHint=="string"?n.deviceIdHint:void 0,activeTransportStableId:"activeTransportStableId"in n&&typeof n.activeTransportStableId=="number"?n.activeTransportStableId:"activeTransportStableId"in n?n.activeTransportStableId??null:void 0,transportGeneration:"transportGeneration"in n&&typeof n.transportGeneration=="number"?n.transportGeneration:void 0,routeGeneration:"routeGeneration"in n&&typeof n.routeGeneration=="number"?n.routeGeneration:void 0,activeTransport:"activeTransport"in n?n.activeTransport:void 0,parallelTransport:"parallelTransport"in n?n.parallelTransport:void 0,availableTransports:"availableTransports"in n?V(n.availableTransports):"transports"in n?V(n.transports):void 0,latencyMs:"latencyMs"in n&&typeof n.latencyMs=="number"?n.latencyMs:void 0,latencyByTransport:"latencyByTransport"in n?tt(n.latencyByTransport):void 0}}function X(n,e){return e===void 0?true:e===null?n==null:n==null||n===e}function rt(n,e){let t=X(n.connectionId,e.connectionId)&&X(n.nodeId,e.nodeId)&&X(n.activeTransportStableId,e.activeTransportStableId)&&X(n.transportGeneration,e.transportGeneration)&&X(n.routeGeneration,e.routeGeneration),i=(r,o)=>r!==void 0?r:t?o:void 0;return {inheritsSnapshot:t,fields:{connectionId:i(e.connectionId??void 0,n.connectionId),activeTransportStableId:i(e.activeTransportStableId,n.activeTransportStableId),transportGeneration:i(e.transportGeneration,n.transportGeneration),routeGeneration:i(e.routeGeneration,n.routeGeneration),activeTransport:i(e.activeTransport,n.activeTransport),parallelTransport:i(e.parallelTransport,n.parallelTransport),latencyMs:t?n.latencyMs:void 0,latencyByTransport:t?n.latencyByTransport:void 0}}}var cn={connectionId:void 0,activeTransportStableId:null,transportGeneration:void 0,routeGeneration:void 0,activeTransport:void 0,parallelTransport:void 0,latencyMs:void 0,latencyByTransport:void 0};function dn(n,e,t){let i=rt(n,{connectionId:e.activeConnectionId,nodeId:e.nodeId,activeTransportStableId:e.activeTransportStableId,transportGeneration:e.transportGeneration,routeGeneration:e.routeGeneration,activeTransport:e.activeTransport,parallelTransport:e.parallelTransport}),r=t?t({connectionId:e.activeConnectionId??void 0,deviceId:e.deviceId??void 0,deviceIdHint:e.deviceIdHint??void 0,nodeId:e.nodeId??void 0}):n.promotionEligible??true;if(!r)return {...n,peerHealth:e.health??n.peerHealth,peerId:e.peerId??n.peerId,promotionEligible:r,scopes:e.scopes?.length?[...e.scopes]:n.scopes,nodeId:e.nodeId===void 0?n.nodeId:e.nodeId??void 0,deviceIdHint:e.deviceIdHint??n.deviceIdHint,...i.fields,readinessReason:e.readinessReason??n.readinessReason};let o=e.status??n.connectionStatus,s=typeof o=="string"?o.trim().toLowerCase():"",a=s==="failed"||s==="closed"||s==="disconnected",l=typeof e.readinessState=="string"&&e.readinessState.trim().length>0?e.readinessState==="routable":e.settledReady===true,c=n.settledReady===true||n.readinessState==="routable";if(i.inheritsSnapshot&&c&&!a&&!l)return {...n,peerHealth:e.health??n.peerHealth,peerId:e.peerId??n.peerId,promotionEligible:r,scopes:e.scopes?.length?[...e.scopes]:n.scopes,nodeId:e.nodeId===void 0?n.nodeId:e.nodeId??void 0,deviceIdHint:e.deviceIdHint??n.deviceIdHint,...i.fields,readinessReason:e.readinessReason??n.readinessReason};let p=a?false:l,h=l&&!a&&(s==="connecting"||s==="connected")?"connected":o,y=l?"routable":e.readinessState??(i.inheritsSnapshot?n.readinessState:void 0),v=p?e.readinessReason??"peer-session-settled":e.readinessReason??(i.inheritsSnapshot?n.readinessReason:void 0);return {...n,connectionStatus:h,settledReady:p,readinessState:y,readinessReason:v,peerHealth:e.health??n.peerHealth,peerId:e.peerId??n.peerId,promotionEligible:r,scopes:e.scopes?.length?[...e.scopes]:n.scopes,nodeId:e.nodeId===void 0?n.nodeId:e.nodeId??void 0,deviceIdHint:e.deviceIdHint??n.deviceIdHint,...i.fields}}function ln(n,e){let t=rt(n,{connectionId:e.connectionId,nodeId:e.nodeId,activeTransportStableId:e.activeTransportStableId,transportGeneration:e.transportGeneration,routeGeneration:e.routeGeneration,activeTransport:e.activeTransport,parallelTransport:e.parallelTransport});if(e.promotionEligible===false)return {...n,peerHealth:e.health??n.peerHealth,peerId:e.peerId??n.peerId,promotionEligible:false,nodeId:e.nodeId??n.nodeId,deviceIdHint:e.deviceIdHint??n.deviceIdHint,...t.fields,scopes:e.scopes?.length?[...e.scopes]:n.scopes};let i=e.status??n.connectionStatus,r=typeof i=="string"?i.trim().toLowerCase():"",o=r==="failed"||r==="closed"||r==="disconnected",s=n.settledReady===true||n.readinessState==="routable",a=e.routable===false;if(t.inheritsSnapshot&&s&&o&&!a)return {...n,peerHealth:n.peerHealth??e.health,peerId:n.peerId??e.peerId,promotionEligible:e.promotionEligible??n.promotionEligible??true,connectionId:n.connectionId??e.connectionId,deviceIdHint:n.deviceIdHint??e.deviceIdHint,scopes:n.scopes?.length?n.scopes:e.scopes??n.scopes};if(s&&o)return {...n,connectionStatus:i,settledReady:false,readinessState:void 0,readinessReason:e.error??n.readinessReason,peerHealth:e.health??n.peerHealth,peerId:e.peerId??n.peerId,promotionEligible:e.promotionEligible??n.promotionEligible??true,deviceIdHint:e.deviceIdHint??n.deviceIdHint,...cn,scopes:e.scopes?.length?[...e.scopes]:n.scopes};let d=e.routable===true||e.protocolState==="routable";if(t.inheritsSnapshot&&s&&!o&&!d)return {...n,peerHealth:n.peerHealth??e.health,peerId:n.peerId??e.peerId,promotionEligible:e.promotionEligible??n.promotionEligible??true,connectionId:n.connectionId??e.connectionId,deviceIdHint:n.deviceIdHint??e.deviceIdHint,activeTransportStableId:n.activeTransportStableId??e.activeTransportStableId,transportGeneration:n.transportGeneration??e.transportGeneration,routeGeneration:n.routeGeneration??e.routeGeneration,activeTransport:n.activeTransport??e.activeTransport,parallelTransport:n.parallelTransport===void 0?e.parallelTransport:n.parallelTransport,scopes:n.scopes?.length?n.scopes:e.scopes??n.scopes};let l=e.transportState==="connected"&&e.health==="healthy",c=o?false:d,p=!o&&(d||l)&&(r==="connecting"||r==="connected"||e.transportState==="connected")?"connected":i,h=c?"routable":(e.routable===false&&e.protocolState?e.protocolState:void 0)??(t.inheritsSnapshot?n.readinessState:void 0)??(e.status==="connecting"?e.transportState==="connected"?"transport-only":"connecting":void 0),y=c?(t.inheritsSnapshot?n.readinessReason:void 0)??(e.routable===true?"peer-projection-routable":void 0):(e.routable===false&&e.error?e.error:void 0)??(t.inheritsSnapshot?n.readinessReason:void 0)??(e.status==="connecting"?e.transportState==="connected"?"peer-projection-transport-ready":"peer-projection-connecting":void 0);return {...n,connectionStatus:p,settledReady:c,readinessState:h,readinessReason:y,peerHealth:e.health??n.peerHealth,peerId:e.peerId??n.peerId,promotionEligible:e.promotionEligible??n.promotionEligible??true,nodeId:e.nodeId??n.nodeId,deviceIdHint:e.deviceIdHint??n.deviceIdHint,...t.fields,scopes:e.scopes?.length?[...e.scopes]:n.scopes}}function un(n){let{device:e,session:t=null,peer:i=null,isPromotionEligible:r}=n,o=an(e);return t&&(o=dn(o,t,r)),i&&(o=ln(o,i)),Qe(o)}function ot(n){let e=ge(n),t=be(e),i=ve(u(e,"presenceStatus","presence_status","livenessStatus","liveness_status")),r=Ze({...t,...i?{presenceStatus:i}:{},presenceUpdatedAt:m(e,"presenceUpdatedAt","presence_updated_at")??ye(e.presenceUpdatedAt,e.presence_updated_at,e.lastSeenAt,e.last_seen_at,e.updatedAt,e.updated_at,e.createdAt,e.created_at),presenceExpiresAt:m(e,"presenceExpiresAt","presence_expires_at")??L(e.presenceExpiresAt??e.presence_expires_at)??L(e.expiresAt??e.expires_at),connectable:x(e,"connectable")}),o={...t,...r,connectionStatus:u(e,"connectionStatus","connection_status")||"disconnected",settledReady:x(e,"settledReady","settled_ready")??false,readinessState:u(e,"readinessState","readiness_state")??void 0,readinessReason:u(e,"readinessReason","readiness_reason")??void 0,peerHealth:u(e,"peerHealth","peer_health")||"unknown",peerId:u(e,"peerId","peer_id"),scopes:Se(e.scopes),connectionId:u(e,"connectionId","connection_id"),deviceIdHint:u(e,"deviceIdHint","device_id_hint"),activeTransportStableId:m(e,"activeTransportStableId","active_transport_stable_id")??void 0,transportGeneration:m(e,"transportGeneration","transport_generation")??void 0,routeGeneration:m(e,"routeGeneration","route_generation")??void 0,activeTransport:z(e,"activeTransport","active_transport"),parallelTransport:z(e,"parallelTransport","parallel_transport")??null,availableTransports:V(e.availableTransports??e.available_transports),latencyMs:m(e,"latencyMs","latency_ms"),latencyByTransport:tt(e.latencyByTransport??e.latency_by_transport)};return un({device:o})}function st(n){let e=ge(n);return Qe({peerId:u(e,"peerId","peer_id")||"",deviceId:u(e,"deviceId","device_id"),deviceIdHint:u(e,"deviceIdHint","device_id_hint"),nodeId:u(e,"nodeId","node_id"),activeConnectionId:u(e,"activeConnectionId","active_connection_id"),candidateConnectionIds:Array.isArray(e.candidateConnectionIds)?e.candidateConnectionIds.filter(t=>typeof t=="string"):Array.isArray(e.candidate_connection_ids)?e.candidate_connection_ids.filter(t=>typeof t=="string"):[],status:u(e,"status")||"disconnected",health:u(e,"health")||"unknown",settledReady:x(e,"settledReady","settled_ready")??false,readinessState:u(e,"readinessState","readiness_state")??void 0,activeTransportStableId:m(e,"activeTransportStableId","active_transport_stable_id")??void 0,transportGeneration:m(e,"transportGeneration","transport_generation")??void 0,routeGeneration:m(e,"routeGeneration","route_generation")??void 0,activeTransport:z(e,"activeTransport","active_transport"),parallelTransport:z(e,"parallelTransport","parallel_transport")??null,replacementPending:x(e,"replacementPending","replacement_pending")??void 0,lastLifecycleTransitionAtMs:m(e,"lastLifecycleTransitionAtMs","last_lifecycle_transition_at_ms")??void 0,readinessReason:u(e,"readinessReason","readiness_reason")??void 0,transitionCount:m(e,"transitionCount","transition_count")??void 0,connectingTransitionCount:m(e,"connectingTransitionCount","connecting_transition_count")??void 0,replacementCount:m(e,"replacementCount","replacement_count")??void 0,retireCount:m(e,"retireCount","retire_count")??void 0,lastDisconnectReason:u(e,"lastDisconnectReason","last_disconnect_reason")??void 0,lastReconnectReason:u(e,"lastReconnectReason","last_reconnect_reason")??void 0,scopes:Array.isArray(e.scopes)?e.scopes.filter(t=>typeof t=="string"):[],lastSeenAtMs:typeof e.lastSeenAtMs=="number"?e.lastSeenAtMs:typeof e.last_seen_at_ms=="number"?e.last_seen_at_ms:0,error:u(e,"error"),errorCode:u(e,"errorCode","error_code")??void 0,retryable:x(e,"retryable")??void 0,errorPlane:u(e,"errorPlane","error_plane")??void 0})}function jn(n){let e=j(n);return {connectionId:typeof e.connectionId=="string"?e.connectionId:"",nodeId:typeof e.nodeId=="string"?e.nodeId:null,deviceId:typeof e.deviceId=="string"?e.deviceId:null,deviceIdHint:typeof e.deviceIdHint=="string"?e.deviceIdHint:null,endpointId:typeof e.endpointId=="string"?e.endpointId:null,transportGeneration:typeof e.transportGeneration=="number"?e.transportGeneration:0,routeGeneration:typeof e.routeGeneration=="number"?e.routeGeneration:void 0,transportStableId:typeof e.transportStableId=="number"?e.transportStableId:null,transportSource:typeof e.transportSource=="string"?e.transportSource:null,lastTransportChangeAtMs:typeof e.lastTransportChangeAtMs=="number"?e.lastTransportChangeAtMs:0,lastRouteChangeAtMs:typeof e.lastRouteChangeAtMs=="number"?e.lastRouteChangeAtMs:void 0,state:typeof e.state=="string"?e.state:"pending",statusReason:typeof e.statusReason=="string"?e.statusReason:null,transitionCount:typeof e.transitionCount=="number"?e.transitionCount:void 0,connectingTransitionCount:typeof e.connectingTransitionCount=="number"?e.connectingTransitionCount:void 0,replacementCount:typeof e.replacementCount=="number"?e.replacementCount:void 0,retireCount:typeof e.retireCount=="number"?e.retireCount:void 0,lastDisconnectReason:typeof e.lastDisconnectReason=="string"?e.lastDisconnectReason:void 0,lastReconnectReason:typeof e.lastReconnectReason=="string"?e.lastReconnectReason:void 0,createdAtMs:typeof e.createdAtMs=="number"?e.createdAtMs:0,updatedAtMs:typeof e.updatedAtMs=="number"?e.updatedAtMs:0}}function zn(n){let e=j(n);return {peerId:typeof e.peerId=="string"?e.peerId:null,deviceId:typeof e.deviceId=="string"?e.deviceId:null,deviceIdHint:typeof e.deviceIdHint=="string"?e.deviceIdHint:null,nodeId:typeof e.nodeId=="string"?e.nodeId:null}}function pn(n){switch(n){case "connected":return "connected";case "connecting":return "connecting";case "failed":return "failed";default:return "closed"}}function at(n){let e=n.activeConnectionId||n.candidateConnectionIds[0]||null;if(!e)return null;let t=pn(n.status),i=t==="connected"?"connected":t==="connecting"?"connecting":"closed",r=t==="connected"?n.settledReady?"routable":"transport-only":t==="connecting"?"connecting":"closed";return {connectionId:e,deviceId:n.deviceId??null,deviceIdHint:n.deviceIdHint??null,remoteNodeId:n.nodeId??null,state:t,transportState:i,protocolState:r,routable:!!n.settledReady,readinessState:n.readinessState,readinessReason:n.readinessReason,transportGeneration:n.transportGeneration,routeGeneration:n.routeGeneration,activeTransportStableId:n.activeTransportStableId,activeTransport:n.activeTransport,parallelTransport:n.parallelTransport??null,replacementInProgress:n.replacementPending,lastLifecycleTransitionAtMs:n.lastLifecycleTransitionAtMs,transitionCount:n.transitionCount,connectingTransitionCount:n.connectingTransitionCount,replacementCount:n.replacementCount,retireCount:n.retireCount,lastDisconnectReason:n.lastDisconnectReason??void 0,lastReconnectReason:n.lastReconnectReason??void 0,updatedAt:n.lastSeenAtMs,error:n.error??void 0}}function ct(n){let e=j(n),t=u(e,"connectionId","connection_id");if(!t)return null;let i=u(e,"state")||"connecting",r=m(e,"createdAt","created_at")??m(e,"updatedAt","updated_at")??Date.now(),o=m(e,"updatedAt","updated_at")??r;return {connectionId:t,deviceId:u(e,"deviceId","device_id"),deviceIdHint:u(e,"deviceIdHint","device_id_hint"),remoteNodeId:u(e,"remoteNodeId","remote_node_id"),state:i,transportState:u(e,"transportState","transport_state")??(i==="connected"?"connected":i==="connecting"?"connecting":"closed"),protocolState:u(e,"protocolState","protocol_state")??(i==="connected"?"routable":i==="connecting"?"connecting":"closed"),routable:x(e,"routable")??false,readinessState:u(e,"readinessState","readiness_state")??void 0,readinessReason:u(e,"readinessReason","readiness_reason")??void 0,transportGeneration:m(e,"transportGeneration","transport_generation")??void 0,routeGeneration:m(e,"routeGeneration","route_generation")??void 0,activeTransportStableId:m(e,"activeTransportStableId","active_transport_stable_id")??void 0,activeTransport:z(e,"activeTransport","active_transport"),parallelTransport:z(e,"parallelTransport","parallel_transport")??null,replacementInProgress:x(e,"replacementInProgress","replacement_in_progress")??void 0,lastLifecycleTransitionAtMs:m(e,"lastLifecycleTransitionAtMs","last_lifecycle_transition_at_ms")??void 0,transitionCount:m(e,"transitionCount","transition_count")??void 0,connectingTransitionCount:m(e,"connectingTransitionCount","connecting_transition_count")??void 0,replacementCount:m(e,"replacementCount","replacement_count")??void 0,retireCount:m(e,"retireCount","retire_count")??void 0,lastDisconnectReason:u(e,"lastDisconnectReason","last_disconnect_reason")??void 0,lastReconnectReason:u(e,"lastReconnectReason","last_reconnect_reason")??void 0,error:u(e,"error")??void 0,createdAt:r,updatedAt:o}}function dt(n,e){return n?n.connectionId===e.connectionId&&(n.deviceId??null)===(e.deviceId??null)&&(n.deviceIdHint??null)===(e.deviceIdHint??null)&&(n.remoteNodeId??null)===(e.remoteNodeId??null)&&n.state===e.state&&(n.transportState??null)===(e.transportState??null)&&(n.protocolState??null)===(e.protocolState??null)&&!!n.routable==!!e.routable&&(n.activeTransport??null)===(e.activeTransport??null)&&(n.parallelTransport??null)===(e.parallelTransport??null)&&(n.activeTransportStableId??null)===(e.activeTransportStableId??null)&&(n.transportGeneration??null)===(e.transportGeneration??null)&&(n.routeGeneration??null)===(e.routeGeneration??null)&&!!n.replacementInProgress==!!e.replacementInProgress&&(n.transitionCount??null)===(e.transitionCount??null)&&(n.connectingTransitionCount??null)===(e.connectingTransitionCount??null)&&(n.replacementCount??null)===(e.replacementCount??null)&&(n.retireCount??null)===(e.retireCount??null)&&(n.lastDisconnectReason??null)===(e.lastDisconnectReason??null)&&(n.lastReconnectReason??null)===(e.lastReconnectReason??null)&&(n.error??null)===(e.error??null):false}function hn(n){try{let e=n.replace(/-/g,"+").replace(/_/g,"/"),t=(4-e.length%4)%4,i=e+"=".repeat(t);if(typeof atob=="function")return JSON.parse(atob(i));let r=globalThis.Buffer;if(r)return JSON.parse(r.from(i,"base64").toString("utf8"))}catch{return null}return null}function fn(n){let e=typeof n=="string"?n.trim():"";if(!e)return {present:false};let t=e.lastIndexOf("."),i=t>=0?e.slice(0,t):e,r=t>=0?e.slice(t+1):null,o=r?hn(r):null,s=o&&typeof o.t=="string"&&o.t.trim().length>0?o.t.trim():null,a=o&&typeof o.s=="string"&&o.s.trim().length>0?o.s.trim():null,d=o&&typeof o.m=="number"&&Number.isFinite(o.m)?o.m:null;return {present:true,irohFingerprint:ae(i),tokenFingerprint:ae(s),tokenSuffixFingerprint:ae(r),scope:a,maxConnections:d}}function J(n,e,t={}){let i=typeof n.finishSend=="function"?n.finishSend.bind(n):typeof n.finish_send=="function"?n.finish_send.bind(n):null;if(!i){if(t.requireFinish===true)throw new Error("WASM peer stream is missing finishSend(); rebuild the current OpenRTC WASM before sending application data");return e}let r=e.getWriter();return new WritableStream({write:o=>r.write(o),async close(){await r.close(),await i();},abort:o=>r.abort(o)})}var g=class g{constructor(e){this.spaceNamespaceIdPromise=null;this.cachedSpaceNamespaceId=null;this.authListeners=[];this.wasmClient=null;this.createdAtMs=Date.now();this.missingWasmWarnings=new Set;this.wasmReadyWarningDelayMs=15e3;this.browserCoordinationSignaling=null;this.lastObservedFirebaseUserId=null;this.sessionReaders=new Set;this.authContext=null;this.injectedBrowserAuthSessionActive=false;this.hasSyncedAuthToWasmClient=false;this.lastWasmAuthUserId=null;this.lastWasmAuthToken=null;this.lastDeliveredConnectionStates=new Map;this.authScopedRuntimeGeneration=0;this.coreClient=null;this.applicationRouteEscalations=new Map;this.applicationRouteEscalationUnsubscribe=null;this.applicationRouteEscalationSubscriptionGeneration=-1;this.applicationRouteEscalationSubscriptionEpoch=0;if(this.appTag=b$1(e),this.options={...e,appTag:this.appTag,authMode:c(e),projectId:d(e)},this.nativeTrustTokens=this.options.coordinationGateway?new se(this.options.coordinationGateway.nativeTrustTokenProvider):null,this.presenceManager=new ce({isTicketOnlyMode:()=>this.isTicketOnlyMode(),waitForWasmClient:(i,r)=>this.waitForWasmClient(i,r),warnMissingWasmOnce:i=>this.warnMissingWasmOnce(i),resolveWebLogicalDeviceId:()=>this.resolveWebLogicalDeviceId(),withWebPresenceMetadata:(i,r)=>this.withWebPresenceMetadata(i,r),updatePresence:(i,r,o,s,a,d)=>this.updatePresence(i,r,o,s,a,d),updateExcludedPeers:(i,r)=>this.getCoordinationSignaling().updateDevice(i,{excludedPeers:r}),getCoordinationSignaling:()=>this.getCoordinationSignaling(),rememberRouteRepairTokenFromTicket:i=>this.coreClient?.rememberRouteRepairTokenFromTicket?.(i)??Promise.resolve(false),onDesiredPeersChanged:()=>this.retryManagedApplicationRouteEscalations()}),this.persistenceReady=Promise.resolve(),this.isTicketOnlyMode()){this.app=null,this.auth=null;return}let t=G$1();this.app=t.getApp(),this.auth=t.getAuth(),t.onAuthStateChanged(i=>{if(this.authContext)return;if(this.isSpaceMode()){this.authListeners.forEach(s=>s(this.toRuntimeIdentity(i)));return}let r=i?.uid??null,o=this.lastObservedFirebaseUserId;this.lastObservedFirebaseUserId=r,o&&o!==r&&this.stopAuthScopedActivity({userId:o}),this.browserCoordinationSignaling?.handleScopeChange(),this.authListeners.forEach(s=>s(this.toRuntimeIdentity(i)));});}get tag(){return this.appTag}getRuntimeCapabilities(){return ie()}getDeviceIdentityStorageKey(){let e$1=e(this.options);return `${g.WEB_DEVICE_ID_STORAGE_PREFIX}_${e$1}`}getDeviceIdPersistenceMode(){return this.options.deviceIdPersistence??this.options.nodeIdPersistence??"persistent"}isTicketOnlyMode(){return this.options.signalingMode==="ticket-only"}createRandomDeviceId(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`web-${Date.now()}-${Math.random().toString(36).slice(2,10)}`}resolveWebLogicalDeviceId(){let e=this.options.localDeviceId?.trim();if(e)return e;let t=this.getDeviceIdPersistenceMode();if(typeof localStorage>"u")return this.createRandomDeviceId();let i=this.getDeviceIdentityStorageKey(),r=Date.now(),o=null;try{let c=localStorage.getItem(i);o=c?JSON.parse(c):null;}catch{o=null;}let s=typeof o?.deviceId=="string"?o.deviceId.trim():"",a=typeof o?.expiresAt=="number"?o.expiresAt:void 0;if(t==="persistent"){let c=s||this.createRandomDeviceId();return localStorage.setItem(i,JSON.stringify({deviceId:c})),c}if(s&&typeof a=="number"&&a>r){let c=r+g.EPHEMERAL_DEVICE_ID_TTL_MS;return localStorage.setItem(i,JSON.stringify({deviceId:s,expiresAt:c})),s}let d=this.createRandomDeviceId(),l=r+g.EPHEMERAL_DEVICE_ID_TTL_MS;return localStorage.setItem(i,JSON.stringify({deviceId:d,expiresAt:l})),d}getDefaultBrowserDeviceName(){return this.options.deviceName?.trim()||(this.options.storagePrefix?`Web (${this.options.storagePrefix.replace(/_$/,"")})`:"Web Browser")}getCoordinationSignaling(){if(this.isTicketOnlyMode())throw new Error('[openrtc] Browser signaling is disabled when signalingMode="ticket-only".');if(!this.options.coordinationGateway)throw new Error("[OpenRTC] Managed coordination requires coordinationGateway; the legacy direct Firebase data plane has been removed.");return this.browserCoordinationSignaling||(this.browserCoordinationSignaling=new oe({projectId:this.options.projectId,gateway:this.options.coordinationGateway,appTag:this.appTag,discoveryMode:this.options.discoveryMode,resolveSpaceNamespaceId:()=>this.ensureSpaceNamespaceIdPromise(),getCurrentUserId:()=>this.getCurrentUserId(),getAuthToken:async(e=false)=>{let t=this.currentUser;return t?.getToken?t.getToken(e):null},getAppCheckToken:async(e=false)=>{let t=this.authContext?.appCheckTokenProvider??this.options.platformAttestationTokenProvider;return t?t(e):G$1().getAppCheckToken(e)},getLocalDeviceId:()=>this.resolveWebLogicalDeviceId(),getDefaultDeviceName:()=>this.getDefaultBrowserDeviceName(),getPlatformType:()=>this.options.coordinationPlatformType??"web",normalizeDevice:(e,t)=>this.normalizeDevice(e,t),nativeTrustTokens:this.nativeTrustTokens})),this.browserCoordinationSignaling}usesCoordinationGateway(){return !!this.options.coordinationGateway}async reconnectCoordinationAfterHostResume(){await this.browserCoordinationSignaling?.reconnectAfterHostResume?.();}async getCoordinationNativeTrustToken(e=false){if(!this.nativeTrustTokens)throw new Error("[OpenRTC] Native trust tokens require a coordination gateway.");return this.nativeTrustTokens.get(e)}invalidateCoordinationNativeTrustToken(){this.nativeTrustTokens?.invalidate();}subscribeCoordinationNativeTrustToken(e,t){return this.nativeTrustTokens?this.nativeTrustTokens.subscribe(e,t):()=>{}}setCoordinationLocalDeviceId(e){if(!this.options.coordinationGateway)return;let t=e.trim();t&&(this.options.localDeviceId=t);}setCoordinationPlatformType(e){this.options.coordinationGateway&&(this.options.coordinationPlatformType=e);}async setCoordinationExcludedPeers(e){let t=this.resolveWebLogicalDeviceId();if(!t)throw new Error("The local device must be known before publishing peer exclusions.");await this.getCoordinationSignaling().updateDevice(t,{excludedPeers:e});}async joinCoordinationRoom(e,t,i){let r=this.getCoordinationSignaling();if(!r.joinCoordinationRoom)throw new Error("The active coordination provider does not support rooms.");await r.joinCoordinationRoom(e,t,i);}async leaveCoordinationRoom(e){await this.getCoordinationSignaling().leaveCoordinationRoom?.(e);}async getCoordinationRoomMembers(e){let t=this.getCoordinationSignaling();if(!t.getCoordinationRoomMembers)throw new Error("The active coordination provider does not support rooms.");return t.getCoordinationRoomMembers(e)}watchCoordinationRoomMembers(e,t){let i=this.getCoordinationSignaling();if(!i.watchCoordinationRoomMembers)throw new Error("The active coordination provider does not support rooms.");return i.watchCoordinationRoomMembers(e,t)}async withWebPresenceMetadata(e,t){let i;if(!e||!e.trim())i=JSON.stringify({deviceId:t});else {try{let r=JSON.parse(e);if(r&&typeof r=="object"&&!Array.isArray(r))return i=JSON.stringify({...r,deviceId:t}),await me(i)??i}catch{}i=JSON.stringify({deviceId:t,metadata:e});}return await me(i)??i}async setAuthContext(e){let t$1=this.injectedBrowserAuthSessionActive;if(this.authContext=e,!this.isTicketOnlyMode()&&e?.customToken?.trim()&&!(t()&&this.options.authMode==="external"&&typeof e.tokenProvider=="function"))try{await this.ensureBrowserPlatformAuth(e.userId,e.customToken.trim());}catch(i){console.warn("[WasmBridge] ensureBrowserPlatformAuth failed (non-fatal):",i);}else if(!this.isTicketOnlyMode()&&!e&&t$1)try{await this.auth?.signOut();}catch(i){console.warn("[WasmBridge] Failed to clear injected browser auth session:",i);}finally{this.injectedBrowserAuthSessionActive=false;}this.syncWasmAuthToken(),this.isTicketOnlyMode()||await this.browserCoordinationSignaling?.handleScopeChange(),this.authListeners.forEach(i=>i(this.currentUser));}async ensureBrowserPlatformAuth(e,t){if((this.auth?.currentUser?.uid??null)===e){this.injectedBrowserAuthSessionActive=true;return}await G$1().signInWithCustomTokenValue(t),this.injectedBrowserAuthSessionActive=true;}syncWasmAuthToken(){if(!this.wasmClient||typeof this.wasmClient.set_auth_token!="function"||!this.authContext&&this.isSpaceMode())return;let e=this.authContext?.userId??null,t=this.authContext?.token??null;this.hasSyncedAuthToWasmClient&&this.lastWasmAuthUserId===e&&this.lastWasmAuthToken===t||(this.lastWasmAuthUserId=e,this.lastWasmAuthToken=t,this.hasSyncedAuthToWasmClient=true,this.wasmClient.set_auth_token(t));}toRuntimeIdentity(e){return e?{id:e.uid,email:e.email,displayName:e.displayName,isAnonymous:e.isAnonymous,getToken:async(t=false)=>{try{return await e.getIdToken(t)}catch{return null}}}:null}getCurrentUserId(){return this.authContext?.userId?this.authContext.userId:this.isTicketOnlyMode()?null:this.auth?.currentUser?.uid??null}getCurrentUserIdForScope(){return this.getCurrentUserId()}getAuthContext(){return this.authContext}isSpaceMode(){return nt(this.options)}getResolvedOptions(){return this.options}getDiscoveryScopeId(){if(this.isTicketOnlyMode())return null;let e=this.getCurrentUserId();return e||(this.isSpaceMode()?this.resolveWebLogicalDeviceId():null)}matchesTag(e){return it(e,this.appTag,this.isSpaceMode())}matchesLegacyOrCurrentTag(e){return this.matchesTag(e)}async stopSessionSubscriptions(){let e=Array.from(this.sessionReaders);this.sessionReaders.clear(),await Promise.allSettled(e.map(async t=>{try{await t.cancel();}catch{}}));}async stopRuntimeAuthScopedLoops(){let e=await this.waitForWasmClient(250);if(e)try{typeof e.stop_auth_scoped_activity=="function"?await e.stop_auth_scoped_activity():(typeof e.stop_presence_loop=="function"&&await e.stop_presence_loop(),typeof e.stop_auto_connect=="function"&&await e.stop_auto_connect());}catch(t){console.warn("[WasmSignaling] Failed to stop auth-scoped runtime loops:",t);}}async stopAuthScopedActivity(e){Le("WasmBridge.stopAuthScopedActivity",{userId:e?.userId??null}),this.authScopedRuntimeGeneration+=1,this.stopApplicationRouteEscalationSubscription();let t=await this.waitForWasmClient(500);if(t&&typeof t.revoke_tokens_by_scope=="function")try{await t.revoke_tokens_by_scope("user-device");}catch(i){console.warn("[WasmBridge] user-device revoke during auth-scoped shutdown failed:",i);}this.presenceManager.stop(),this.browserCoordinationSignaling?.stopAuthScopedActivity(),await this.stopSessionSubscriptions(),this.lastDeliveredConnectionStates.clear(),this.applicationRouteEscalations?.clear(),await this.stopRuntimeAuthScopedLoops();}setWasmClient(e){this.wasmClient=e,this.hasSyncedAuthToWasmClient=false,this.lastDeliveredConnectionStates.clear(),this.applicationRouteEscalations?.clear(),this.syncWasmAuthToken();}warnMissingWasmOnce(e){!this.wasmClient&&Date.now()-this.createdAtMs<this.wasmReadyWarningDelayMs||this.missingWasmWarnings.has(e)||(this.missingWasmWarnings.add(e),console.warn(`[WasmSignaling] ${e} skipped: wasm client is not ready.`));}async waitForWasmClient(e=4e3,t=50){if(this.wasmClient)return this.wasmClient;let i=Date.now();for(;!this.wasmClient&&Date.now()-i<e;)await u$1(t);return this.wasmClient??null}normalizeDevice(e,t){return be(e,t)}normalizeDeviceRecord(e,t){return this.normalizeDevice(e,t)}getResolvedWebLogicalDeviceId(){return this.resolveWebLogicalDeviceId()}normalizeDeviceStatusSnapshot(e){return ot(e)}normalizePeerSessionSnapshot(e){return st(e)}toBackendConnectionStateFromPeerSession(e){return at(e)}normalizeConnectionStateSnapshot(e){return ct(e)}stabilizeConnectionState(e){let t=this.lastDeliveredConnectionStates.get(e.connectionId);return {...e,deviceId:e.deviceId??t?.deviceId??null,deviceIdHint:e.deviceIdHint??t?.deviceIdHint??null,remoteNodeId:e.remoteNodeId??t?.remoteNodeId??null,createdAt:e.createdAt??t?.createdAt,updatedAt:e.updatedAt??t?.updatedAt}}sameConnectionState(e,t){return dt(e,t)}deliverConnectionState(e,t,i,r){let o=this.stabilizeConnectionState(e);this.escalateManagedApplicationRoute(o),this.lastDeliveredConnectionStates.set(o.connectionId,o);let a=(r??this.lastDeliveredConnectionStates).get(o.connectionId);this.sameConnectionState(a,o)||(r&&r.set(o.connectionId,o),t(o));}get browserPresenceLoopState(){return this.presenceManager.presenceLoopState}set browserPresenceLoopState(e){this.presenceManager.presenceLoopState=e;}get currentUser(){if(this.authContext?.userId){let e=this.authContext.token??null,t=this.authContext.tokenProvider;return {id:this.authContext.userId,getToken:async(i=false)=>{if(e&&(!i||!t))return e;if(t)try{let o=await t(i);if(o)return o}catch{}let r=this.isTicketOnlyMode()?null:this.auth?.currentUser??null;if(r&&r.uid===this.authContext?.userId)try{return await r.getIdToken(i)}catch{return null}return null}}}return this.isTicketOnlyMode()?null:this.toRuntimeIdentity(this.auth?.currentUser??null)}onAuthChange(e){return this.authListeners.push(e),e(this.currentUser),()=>{this.authListeners=this.authListeners.filter(t=>t!==e);}}async checkForSSOToken(){this.isTicketOnlyMode()||await G$1().checkForSSOToken();}async waitForAuth(){this.isTicketOnlyMode()||this.isSpaceMode()||this.authContext?.userId||this.auth?.currentUser||await G$1().waitForAuth();}async signInAnonymously(){if(!this.isTicketOnlyMode()){if(this.options.authMode!=="anonymous")throw new Error(`[pluto-rtc] Anonymous sign-in is disabled when authMode=${this.options.authMode}.`);await G$1().signInAnonymously();}}async signInWithPluto(){if(this.isTicketOnlyMode())throw new Error('[openrtc] Pluto sign-in is unavailable when signalingMode="ticket-only".');await G$1().signInWithPluto();}async signOut(){let e=this.getCurrentUserId();await this.stopAuthScopedActivity({userId:e}),this.authContext=null,this.hasSyncedAuthToWasmClient=false,this.syncWasmAuthToken(),this.isTicketOnlyMode()||await this.auth?.signOut(),this.authListeners.forEach(t=>t(this.currentUser));}async getTurnCredentials(){return this.isTicketOnlyMode()||!this.auth?.currentUser?null:typeof this.options.turnCredentialsProvider=="function"?await this.options.turnCredentialsProvider()??null:null}async updatePresence(e,t,i=true,r=3e5,o,s){if(this.isTicketOnlyMode())return;let a=this.resolveWebLogicalDeviceId(),d=this.getDeviceIdPersistenceMode()==="ephemeral"?g.EPHEMERAL_DEVICE_ID_TTL_MS:r,l=await this.withWebPresenceMetadata(o,a);this.presenceManager.updatePresenceLoopState({userId:this.getCurrentUserId()??"",localNodeId:e,ticket:t,metadata:l,deviceName:s?.trim()||this.getDefaultBrowserDeviceName()}),await this.getCoordinationSignaling().updatePresence(e,t,i,d,l,s);}async refreshLivePresence(e,t,i,r){if(this.isTicketOnlyMode())return;let o=this.resolveWebLogicalDeviceId(),s=await this.withWebPresenceMetadata(i,o);this.presenceManager.updatePresenceLoopState({userId:this.getCurrentUserId()??"",localNodeId:e,ticket:t,metadata:s,deviceName:r?.trim()||this.getDefaultBrowserDeviceName()}),await this.getCoordinationSignaling().updatePresence(e,t,true,15*6e4,s,r);}async setOffline(e){this.presenceManager.stopPresence(),!this.isTicketOnlyMode()&&await this.getCoordinationSignaling().setOffline(e);}async updateDevice(e,t){if(!e?.trim())throw new Error("updateDevice requires a deviceId");this.isTicketOnlyMode()||await this.getCoordinationSignaling().updateDevice(e,t);}async deleteDevice(e){if(!e?.trim())throw new Error("deleteDevice requires a deviceId");this.isTicketOnlyMode()||await this.getCoordinationSignaling().deleteDevice(e);}async cleanupStaleDevices(){this.isTicketOnlyMode()||await this.getCoordinationSignaling().cleanupStaleDevices();}async sendMessage(e,t,i,r){if(this.isTicketOnlyMode())throw new Error('[openrtc] sendMessage() is unavailable when signalingMode="ticket-only".');return this.getCoordinationSignaling().sendMessage(e,t,i,r)}async pollMessages(e){return this.isTicketOnlyMode()?[]:this.getCoordinationSignaling().pollMessages(e)}async searchDevices(e){return this.isTicketOnlyMode()?[]:this.getCoordinationSignaling().searchDevices(e)}async listDevicesWithStatus(){if(this.isTicketOnlyMode())return [];if(!this.getDiscoveryScopeId())return [];let t=await this.getCoordinationSignaling().listDevices(),i=this.wasmClient;return Promise.all(t.map(async r=>{let o=this.normalizeDeviceStatusSnapshot({...r,connectionStatus:r.online?"online":"disconnected"}),s=typeof r.nodeId=="string"?r.nodeId.trim():"";if(!s||typeof i?.iroh_path_kind!="function"||typeof i?.iroh_transport_rtt_ms!="function")return o;try{let[a,d]=await Promise.all([i.iroh_path_kind(s),i.iroh_transport_rtt_ms(s)]);if(typeof d!="number"||!Number.isFinite(d))return o;let l=Math.max(0,Math.round(d)),c={};if(a==="direct-lan")c.irohLan=l;else if(a==="direct-quic")c.iroh=l;else if(a==="ble")c.ble=l;else if(a==="relay")c.irohRelay=l;else return o;return {...o,latencyMs:l,latencyByTransport:c}}catch(a){return ee("[WasmBridge] iroh transport latency unavailable",{deviceId:r.deviceId,error:a instanceof Error?a.message:String(a)}),o}}))}async getPeerSession(e){let t=await this.waitForWasmClient(500);if(t&&typeof t.peer_session=="function"){let i=await t.peer_session(e);return !i||typeof i!="object"?null:this.normalizePeerSessionSnapshot(i)}return this.warnMissingWasmOnce("getPeerSession"),null}async listPeerSessions(){let e=await this.waitForWasmClient(500);if(e&&typeof e.peer_sessions=="function"){let t=await e.peer_sessions();return (Array.isArray(t)?t:[]).map(r=>this.normalizePeerSessionSnapshot(r)).filter(r=>!!(r.peerId||r.deviceId||r.deviceIdHint||r.nodeId||r.activeConnectionId))}return this.warnMissingWasmOnce("listPeerSessions"),[]}async waitForSettledPeer(e,t){let i=await this.waitForWasmClient(500);if(i&&typeof i.wait_for_settled_peer=="function"){let r=await i.wait_for_settled_peer(e,t);return !r||typeof r!="object"?null:this.normalizePeerSessionSnapshot(r)}return this.warnMissingWasmOnce("waitForSettledPeer"),null}async openPeerBi(e,t){let i=await this.waitForWasmClient(500);if(i&&typeof i.open_peer_bi=="function"){let r=await i.open_peer_bi(e,t);if(!r?.recv||!r?.send)throw new Error("WASM open_peer_bi returned an invalid bidirectional stream");return {readable:r.recv,writable:J(r,r.send)}}throw this.warnMissingWasmOnce("openPeerBi"),new Error("WASM runtime does not support open_peer_bi()")}async openPeerNativeBi(e,t,i){let r=await this.waitForWasmClient(500),o=r&&r.open_peer_native_bi;if(typeof o=="function"){let s=await o.call(r,e,t,i);if(!s?.recv||!s?.send)throw new Error("WASM open_peer_native_bi returned an invalid bidirectional stream");return {readable:s.recv,writable:J(s,s.send)}}throw this.warnMissingWasmOnce("openPeerNativeBi"),new Error("WASM runtime does not support open_peer_native_bi()")}async openPeerBiTransportOnly(e,t){if(this.options.applicationCrypto?.requireEncrypted)throw new Error("[WasmBridge] openPeerBiTransportOnly is debug-only and cannot be used when application crypto is required");let i=await this.waitForWasmClient(500),r=i&&typeof i.open_peer_bi_transport_only=="function";if(console.debug("[WasmBridge] openPeerBiTransportOnly",{peerId:e,hasWasmClient:!!i,hasTransportOnly:r,timeoutMs:t}),r){let o=await i.open_peer_bi_transport_only(e,t);if(!o?.recv||!o?.send)throw new Error("WASM open_peer_bi_transport_only returned an invalid bidirectional stream");return {readable:o.recv,writable:J(o,o.send)}}return console.debug("[WasmBridge] openPeerBiTransportOnly falling back to openPeerBi",{peerId:e}),this.openPeerBi(e,t)}async openPeerUni(e,t){let i=await this.waitForWasmClient(500);if(i&&typeof i.open_peer_uni=="function"){let r=await i.open_peer_uni(e,t),o=r?.writable??r;if(!o)throw new Error("WASM open_peer_uni returned an invalid writable stream");return {writable:J(r,o)}}throw this.warnMissingWasmOnce("openPeerUni"),new Error("WASM runtime does not support open_peer_uni()")}async resolvePeerConnectionRecords(e){let t=await this.waitForWasmClient(500);if(t&&typeof t.resolve_peer_connection_records=="function"){let i=await t.resolve_peer_connection_records(e);return (Array.isArray(i)?i:[]).map(r=>({connectionId:typeof r.connectionId=="string"?r.connectionId:"",nodeId:typeof r.nodeId=="string"?r.nodeId:null,deviceId:typeof r.deviceId=="string"?r.deviceId:null,deviceIdHint:typeof r.deviceIdHint=="string"?r.deviceIdHint:null,endpointId:typeof r.endpointId=="string"?r.endpointId:null,transportGeneration:typeof r.transportGeneration=="number"?r.transportGeneration:0,routeGeneration:typeof r.routeGeneration=="number"?r.routeGeneration:void 0,transportStableId:typeof r.transportStableId=="number"?r.transportStableId:null,transportSource:typeof r.transportSource=="string"?r.transportSource:null,lastTransportChangeAtMs:typeof r.lastTransportChangeAtMs=="number"?r.lastTransportChangeAtMs:0,lastRouteChangeAtMs:typeof r.lastRouteChangeAtMs=="number"?r.lastRouteChangeAtMs:void 0,state:typeof r.state=="string"?r.state:"pending",statusReason:typeof r.statusReason=="string"?r.statusReason:null,createdAtMs:typeof r.createdAtMs=="number"?r.createdAtMs:0,updatedAtMs:typeof r.updatedAtMs=="number"?r.updatedAtMs:0}))}return this.warnMissingWasmOnce("resolvePeerConnectionRecords"),[]}async resolvePeerIdentity(e){let t=await this.waitForWasmClient(500);if(t){let i=r=>{if(!r||typeof r!="object")return {peerId:null,deviceId:null,deviceIdHint:null,nodeId:null};let o=r;return {peerId:typeof o.peerId=="string"?o.peerId:null,deviceId:typeof o.deviceId=="string"?o.deviceId:null,deviceIdHint:typeof o.deviceIdHint=="string"?o.deviceIdHint:null,nodeId:typeof o.nodeId=="string"?o.nodeId:null}};if(typeof t.peer_session=="function")try{let r=await t.peer_session(e),o=i(r);if(o.peerId||o.deviceId||o.deviceIdHint||o.nodeId)return o}catch{}if(typeof t.peer_snapshot=="function")try{return i(await t.peer_snapshot(e))}catch{}}return this.warnMissingWasmOnce("resolvePeerIdentity"),{peerId:null,deviceId:null,deviceIdHint:null,nodeId:null}}onDevicesChange(e,t){return this.isTicketOnlyMode()?(e([]),()=>{}):this.getCoordinationSignaling().onDevicesChange(e,t)}async subscribeDevices(e){return this.isTicketOnlyMode()?new ReadableStream({start(t){t.close();}}):this.getCoordinationSignaling().subscribeDevices()}async startAutoConnect(e,t){if(this.isTicketOnlyMode())return;this.startApplicationRouteEscalationSubscription();let i=this.authScopedRuntimeGeneration;try{let r=await this.waitForWasmClient();if(i!==this.authScopedRuntimeGeneration||!r||typeof r.start_auto_connect!="function")return;await r.start_auto_connect(e,t),i===this.authScopedRuntimeGeneration&&this.presenceManager.startAutoConnect(e,t);}catch(r){console.warn("[WasmBridge] failed to initialize WASM auto-connect context",{userId:e,localDeviceId:t,error:r});}}async startAutoConnectOnce(e,t){await this.startAutoConnect(e,t),this.forceReconnectSnapshot();}notifyDisconnectRequested(e){this.presenceManager.wakeRustAutoConnectOwner();}async setAutoConnectExcluded(e,t){await this.presenceManager.setAutoConnectExcluded(e,t);}async disconnectDevice(e){let t=await this.waitForWasmClient();if(!t||typeof t.disconnect_device!="function"){this.warnMissingWasmOnce("disconnectDevice"),await this.presenceManager.setAutoConnectExcluded(e,true).catch(()=>{});return}try{await t.disconnect_device(e,null),await this.presenceManager.recordAutoConnectExcludedForPresence(e,!0).catch(()=>{});}catch(i){throw console.warn("[WasmBridge] disconnect_device failed",{deviceId:e,error:i?.message??String(i)}),i}}async submitDesiredPeerProjection(e,t){return this.presenceManager.submitDesiredPeerProjection(e,t)}setCoreClient(e){e&&typeof e.connect=="function"?(this.coreClient=e,this.startApplicationRouteEscalationSubscription(),this.retryManagedApplicationRouteEscalations()):(this.coreClient=null,this.stopApplicationRouteEscalationSubscription());}startApplicationRouteEscalationSubscription(){if(this.applicationRouteEscalationUnsubscribe&&this.applicationRouteEscalationSubscriptionGeneration===this.authScopedRuntimeGeneration)return;this.stopApplicationRouteEscalationSubscription();let e=this.authScopedRuntimeGeneration,t=this.applicationRouteEscalationSubscriptionEpoch,i=this.onConnectionStateChange(()=>{});this.applicationRouteEscalationUnsubscribe=()=>{},this.applicationRouteEscalationSubscriptionGeneration=e,Promise.resolve(i).then(r=>{if(!this.coreClient||e!==this.authScopedRuntimeGeneration||t!==this.applicationRouteEscalationSubscriptionEpoch){r();return}this.applicationRouteEscalationUnsubscribe=r,this.applicationRouteEscalationSubscriptionGeneration=e;});}stopApplicationRouteEscalationSubscription(){this.applicationRouteEscalationSubscriptionEpoch+=1,this.applicationRouteEscalationUnsubscribe?.(),this.applicationRouteEscalationUnsubscribe=null,this.applicationRouteEscalationSubscriptionGeneration=-1;}retryManagedApplicationRouteEscalations(){for(let e of this.lastDeliveredConnectionStates.values())this.escalateManagedApplicationRoute(e);}escalateManagedApplicationRoute(e){if(!this.coreClient||!["connected","connecting"].includes(e.state)||this.applicationRouteEscalations.has(e.connectionId)||e.remoteNodeId&&this.coreClient.hasApplicationRouteForPeer?.(e.connectionId,e.remoteNodeId)===true)return;let t=this.presenceManager.resolveDesiredPeer(e.deviceId??e.deviceIdHint,e.remoteNodeId);if(!t?.ticket)return;let i=this.authScopedRuntimeGeneration,r=this.coreClient,o;o=(async()=>{let s=typeof r.ensureManagedApplicationRoute=="function"?await r.ensureManagedApplicationRoute({ticket:t.ticket,connectionId:e.connectionId,remoteNodeId:e.remoteNodeId??t.nodeId,expectedDeviceId:t.deviceId,timeoutMs:2e4}):await r.connect(t.ticket,2e4,t.deviceId,void 0,{admissionAlreadyPresented:true});if(i!==this.authScopedRuntimeGeneration)return;let a=s,d=a.id?.trim()||e.connectionId,l=a.remoteNodeId?.trim()||e.remoteNodeId?.trim()||a.deviceId?.trim()||t.deviceId;if(r.hasApplicationRouteForPeer?.(d,l)!==true&&r.hasApplicationRouteForPeer?.(d,l)!==true)throw new Error(`application crypto was not ready for ${l}`)})().catch(s=>{i===this.authScopedRuntimeGeneration&&console.warn("[WasmBridge][ROUTE-ESCALATION] Rust-managed route remains pending",{connectionId:e.connectionId,deviceId:t.deviceId,remoteNodeId:e.remoteNodeId??t.nodeId,error:s?.message??String(s)});}).finally(()=>{this.applicationRouteEscalations.get(e.connectionId)===o&&this.applicationRouteEscalations.delete(e.connectionId);}),this.applicationRouteEscalations.set(e.connectionId,o);}async connectToDevice(e){let t=await this.waitForWasmClient();if(!t||typeof t.connect_device!="function")throw this.warnMissingWasmOnce("connectToDevice"),new Error("WASM runtime does not support connect_device()");let i=Date.now();A("[WasmBridge][ROUTE-ESCALATION] starting managed transport dial",{deviceId:e.deviceId??null,ticket:fn(e.endpointTicket),hasCoreClient:!!this.coreClient});let r=await t.connect_device(e.deviceId??null,e.endpointTicket);A("[WasmBridge][ROUTE-ESCALATION] managed transport dial completed",{deviceId:e.deviceId??null,remoteNodeId:r?.remoteNodeId??null,connectionId:r?.connectionId??null,elapsedMs:Date.now()-i});let o=e.endpointTicket;if(o&&this.coreClient){let s=this.coreClient;try{A("[WasmBridge][ROUTE-ESCALATION] starting typed application connection",{deviceId:e.deviceId??null,remoteNodeId:r?.remoteNodeId??null,connectionId:r?.connectionId??null});let a=typeof s.ensureManagedApplicationRoute=="function"?await s.ensureManagedApplicationRoute({ticket:o,connectionId:r?.connectionId??null,remoteNodeId:r?.remoteNodeId??null,expectedDeviceId:e.deviceId??null,approvedScope:r?.approvedScope??null,timeoutMs:2e4}):await s.connect(o,2e4,e.deviceId??null,void 0,{admissionAlreadyPresented:!0,approvedScope:r?.approvedScope??null}),d=typeof a?.remoteNodeId=="string"?a.remoteNodeId.trim():"",l=typeof a?.deviceId=="string"?a.deviceId.trim():"",c=d||r?.remoteNodeId?.trim?.()||l||e.deviceId?.trim?.()||"",p=typeof s.hasApplicationRouteForPeer=="function"?s.hasApplicationRouteForPeer.bind(s):null;if(!(!!c&&p?.(a?.id??void 0,c)===!0)&&c&&typeof s.waitForApplicationCryptoForPeer=="function"&&!(!!await s.waitForApplicationCryptoForPeer(c,2e4)&&(!p||p(a?.id??void 0,c)===!0)))throw console.warn("[WasmBridge][ROUTE-ESCALATION] application route still pending after managed dial",{deviceId:e.deviceId??null,remoteNodeId:d||(r?.remoteNodeId??null),connectionId:r?.connectionId??null,peerForCrypto:c,elapsedMs:Date.now()-i}),Object.assign(new Error(`application crypto was not ready for ${c}`),{applicationCryptoNotReady:!0});A("[WasmBridge][ROUTE-ESCALATION] application route ready",{deviceId:e.deviceId??null,remoteNodeId:d||(r?.remoteNodeId??null),connectionId:r?.connectionId??null,elapsedMs:Date.now()-i});}catch(a){if(a?.applicationCryptoNotReady)throw a;return console.warn("[WasmBridge] Managed transport connected; TS application route escalation is still pending",{deviceId:e.deviceId??null,remoteNodeId:r?.remoteNodeId??null,connectionId:r?.connectionId??null,error:a?.message??String(a)}),r}}return r}forceReconnectSnapshot(){this.isTicketOnlyMode()||!this.app||!this.auth||this.presenceManager.wakeRustAutoConnectOwner();}startPresenceLoop(e,t,i,r,o){this.presenceManager.startPresenceLoop(e,t,i,r,o);}ensureSpaceNamespaceIdPromise(){if(this.cachedSpaceNamespaceId)return Promise.resolve(this.cachedSpaceNamespaceId);if(!this.spaceNamespaceIdPromise){let e=this.options.apiKey?.trim()??"",t=this.options.spaceKey?.trim()??"";if(!e||!t)return Promise.resolve(null);this.spaceNamespaceIdPromise=a(e,t).then(i=>(this.cachedSpaceNamespaceId=i,i)).catch(()=>null);}return this.spaceNamespaceIdPromise}async createSession(e){if(this.isTicketOnlyMode())throw new Error('[openrtc] createSession() is unavailable when signalingMode="ticket-only".');let t=this.getCurrentUserId();if(!t&&!e.initiator&&!e.target&&!this.isSpaceMode())throw new Error("createSession requires user scope");let i={...e,appTag:e.appTag??this.appTag,initiator:e.initiator??t??void 0,target:e.target??t??void 0};await this.getCoordinationSignaling().createSession(i);}async updateSession(e,t){if(this.isTicketOnlyMode())throw new Error('[openrtc] updateSession() is unavailable when signalingMode="ticket-only".');await this.getCoordinationSignaling().updateSession(e,t);}async subscribeSessions(e){return this.isTicketOnlyMode()?new ReadableStream({start(t){t.close();}}):this.getCoordinationSignaling().subscribeSessions(e)}async getLocalDeviceId(){return this.resolveWebLogicalDeviceId()}async isConnected(e){let t=await this.waitForWasmClient();return t&&typeof t.is_connected=="function"&&await t.is_connected(e)?true:this.hasConnectedIndependentPeerRoute(t,e)}async hasConnectedIndependentPeerRoute(e,t){if(!e||typeof t!="string"||t.trim().length===0)return false;let i=t.trim(),r=[];if(typeof e.peer_session=="function")try{let o=await e.peer_session(i);o&&typeof o=="object"&&r.push(this.normalizePeerSessionSnapshot(o));}catch{}if(typeof e.peer_sessions=="function")try{let o=await e.peer_sessions();Array.isArray(o)&&r.push(...o.filter(s=>!!s&&typeof s=="object").map(s=>this.normalizePeerSessionSnapshot(s)));}catch{}return r.some(o=>{let s=typeof o.peerId=="string"?o.peerId.trim():"",a=typeof o.deviceId=="string"?o.deviceId.trim():"",d=typeof o.deviceIdHint=="string"?o.deviceIdHint.trim():"",l=typeof o.nodeId=="string"?o.nodeId.trim():"";return (i===s||i===a||i===d||i===l)&&o.status==="connected"&&o.settledReady===true&&o.replacementPending!==true&&h(o.activeTransport)})}async getConnectionStates(){let e=await this.waitForWasmClient(500);if(e&&typeof e.connection_states=="function"){let r=await e.connection_states(),o=(Array.isArray(r)?r:[]).map(s=>this.normalizeConnectionStateSnapshot(s)).filter(s=>!!s);return o.length>0&&ee("[WasmBridge] replaying current wasm connection states",o.map(s=>({connectionId:s.connectionId,deviceId:s.deviceId??null,deviceIdHint:s.deviceIdHint??null,remoteNodeId:s.remoteNodeId??null,state:s.state,transportState:s.transportState??null,protocolState:s.protocolState??null,routable:s.routable??null}))),o}let i=(await this.listPeerSessions().catch(()=>[])).map(r=>this.toBackendConnectionStateFromPeerSession(r)).filter(r=>!!r);return i.length>0&&ee("[WasmBridge] replaying current wasm connection states",i.map(r=>({connectionId:r.connectionId,deviceId:r.deviceId??null,deviceIdHint:r.deviceIdHint??null,remoteNodeId:r.remoteNodeId??null,state:r.state,transportState:r.transportState??null,protocolState:r.protocolState??null,routable:r.routable??null}))),i}onConnectionStateChange(e){let t=new Map,i=new Map,r=this.authScopedRuntimeGeneration,o=false,s=l=>{let c=l.detail,p=typeof c?.connectionId=="string"?c.connectionId.trim():"";if(!p||o)return;let h=(i.get(p)??0)+1;i.set(p,h);let y=this.authScopedRuntimeGeneration;(async()=>{let v=this.normalizeConnectionStateSnapshot(c),S=await this.waitForWasmClient(500);if(!(o||y!==this.authScopedRuntimeGeneration||i.get(p)!==h)){if(S&&typeof S.connection_state=="function"){let O=await S.connection_state(p),I=this.normalizeConnectionStateSnapshot(O);if(!o&&y===this.authScopedRuntimeGeneration&&i.get(p)===h&&I){this.deliverConnectionState(I,e,"rust-event",t);return}}!o&&y===this.authScopedRuntimeGeneration&&i.get(p)===h&&v&&this.deliverConnectionState(v,e,"rust-event-detail",t);}})().catch(v=>{o||console.warn("[WasmBridge] Failed to read Rust connection state after lifecycle event",{connectionId:p,error:v});});},a=typeof window<"u"?window:null,d=typeof a?.addEventListener=="function"&&typeof a?.removeEventListener=="function";return d&&a.addEventListener("connection-state-changed",s),this.getConnectionStates().then(l=>{!o&&r===this.authScopedRuntimeGeneration&&l.forEach(c=>{i.has(c.connectionId)||this.deliverConnectionState(c,e,"replay",t);});}).catch(l=>{console.warn("[WasmBridge] Failed to replay wasm connection states after subscription:",l);}),()=>{o=true,i.clear(),d&&a.removeEventListener("connection-state-changed",s);}}async sendExplicitFilePath(e,t,i=""){throw new Error("sendExplicitFilePath is native-only. Use sendExplicitFileData in web/wasm runtime.")}sanitizeExplicitFileName(e){let i=(typeof e=="string"?e.replace(/\\/g,"/"):"").split("/").reverse().find(s=>s.trim().length>0)?.trim()??"";if(!i||i==="."||i==="..")return g.FALLBACK_EXPLICIT_FILE_NAME;let r="";for(let s of i){if([...r].length>=g.MAX_EXPLICIT_FILE_NAME_CHARS)break;let a=s.charCodeAt(0);s==="/"||s==="\\"||s==="\0"||a<32||a===127?r+="_":r+=s;}let o=r.trim();return !o||o==="."||o===".."?g.FALLBACK_EXPLICIT_FILE_NAME:o}sanitizeExplicitMimeType(e){let t=typeof e=="string"?e.trim():"";if(!t)return g.FALLBACK_EXPLICIT_MIME_TYPE;let i="";for(let r of t){if(i.length>=g.MAX_EXPLICIT_MIME_TYPE_CHARS)break;let o=r.charCodeAt(0);o<33||o>126||r==='"'||r==="\\"?i+="_":i+=r;}return i.length>0?i:g.FALLBACK_EXPLICIT_MIME_TYPE}assertExplicitTransferHeaderSize(e){if(e.byteLength===0||e.byteLength>g.MAX_EXPLICIT_TRANSFER_HEADER_BYTES)throw new Error(`Explicit transfer header is too large: ${e.byteLength} bytes`)}createWebRTCExplicitTransferId(){let e=new Uint8Array(16),t=globalThis.crypto;if(t&&typeof t.getRandomValues=="function")return t.getRandomValues(e),e;for(let i=0;i<e.byteLength;i+=1)e[i]=Math.floor(Math.random()*256);return e}createWebRTCExplicitTransferFrame(e,t,i,r,o){let s=o?.headerFrame===true?4:0,a=new Uint8Array(25+s+r.byteLength);a[0]=g.EXPLICIT_FILE_PROTOCOL_TYPE,a.set(e,1);let d=new DataView(a.buffer);d.setUint32(17,t,false),d.setUint32(21,i,false);let l=o?.headerFrame===true?29:25;return o?.headerFrame===true&&d.setUint32(25,r.byteLength,false),a.set(r,l),a}async sendExplicitFileData(e){let t=e.connection,i=e.file,r=e.applicationCrypto??this.options.applicationCrypto;if((e.requireApplicationCrypto===true||t?.requireApplicationCrypto===true)&&!r)throw new Error("[WasmBridge] Explicit transfer requires application crypto but none is available for this connection");let s=e.transferId&&e.transferId.trim().length>0?e.transferId:`transfer-${Date.now()}`,a=typeof e.receiverPlatformType=="string"?e.receiverPlatformType.trim().toLowerCase():null,d=e.remoteNodeId?.trim()||t?.remoteNodeId?.trim()||t?.deviceId?.trim();if(A("[WasmBridge] sendExplicitFileData start",{connectionId:e.connectionId??null,connectionRemoteNodeId:t?.remoteNodeId??null,remoteNodeId:d??null,fileName:i.name,fileSize:i.size,transferId:s}),!d)throw new Error("Web explicit transfer requires an active connection with a resolved remote node ID");let l=await this.waitForWasmClient();if(!l)throw new Error("WASM explicit transfer requires an initialized WASM client");let c=new TextEncoder,p={transfer_id:s,filename:this.sanitizeExplicitFileName(i.name),size:i.size,mime_type:this.sanitizeExplicitMimeType(i.type)},h=c.encode(JSON.stringify(p));this.assertExplicitTransferHeaderSize(h);let y=new Uint8Array(4);new DataView(y.buffer).setUint32(0,h.byteLength,false);let v=new Uint8Array(y.byteLength+h.byteLength);v.set(y,0),v.set(h,y.byteLength);let S=async()=>{if(a!=="web"||!t||typeof t.sendOnWebRTC!="function"||typeof t.isWebRtcApplicationRouteReady!="function"||t.isWebRtcApplicationRouteReady()!==true)return a&&a!=="web"&&typeof t?.isWebRtcApplicationRouteReady=="function"&&t.isWebRtcApplicationRouteReady()===true&&A("[WasmBridge] sendExplicitFileData kept on Iroh for non-browser receiver",{remoteNodeId:d,transferId:s,receiverPlatformType:a}),false;let I=r?xe(r):null,_=U=>I?I.protectFrame(U):U,R=new Uint8Array(await i.arrayBuffer()),E=this.createWebRTCExplicitTransferId(),B=Math.max(1,Math.ceil(R.byteLength/g.EXPLICIT_FILE_CHUNK_SIZE_BYTES)),C=typeof t.getWebRTCTransport=="function"?t.getWebRTCTransport():null,F=async()=>{C&&typeof C.getBufferedAmount=="function"&&typeof C.waitForDrain=="function"&&C.getBufferedAmount()>g.EXPLICIT_FILE_CHUNK_SIZE_BYTES*4&&await C.waitForDrain(g.EXPLICIT_FILE_CHUNK_SIZE_BYTES*2);};if(await t.sendOnWebRTC(this.createWebRTCExplicitTransferFrame(E,4294967295,B,_(h),{headerFrame:true})),await F(),R.byteLength===0)return await t.sendOnWebRTC(this.createWebRTCExplicitTransferFrame(E,0,B,_(new Uint8Array(0)))),true;let Q=0;for(let U=0;U<R.byteLength;U+=g.EXPLICIT_FILE_CHUNK_SIZE_BYTES){let pt=R.slice(U,Math.min(U+g.EXPLICIT_FILE_CHUNK_SIZE_BYTES,R.byteLength));await t.sendOnWebRTC(this.createWebRTCExplicitTransferFrame(E,Q,B,_(pt))),Q+=1,await F();}return A("[WasmBridge] sendExplicitFileData sent over WebRTC explicit route",{connectionId:e.connectionId??null,remoteNodeId:d,transferId:s,chunks:B,encrypted:!!I}),true},O=async()=>{let I=l.open_peer_bi_explicit_file_sender;if(typeof I!="function")return false;let _=await I.call(l,d,5e3),R=_?.writable??_?.send;if(!R||typeof R.getWriter!="function")throw new Error("WASM explicit peer stream returned an invalid writable stream");A("[WasmBridge] sendExplicitFileData open_peer_bi_explicit_file_sender resolved",{remoteNodeId:d,transferId:e.transferId??null,applicationCryptoWrapped:_.applicationCryptoWrapped===true});let E=J(_,R,{requireFinish:true}).getWriter(),B=false;try{await E.write(v);let C=new Uint8Array(await i.arrayBuffer());for(let F=0;F<C.byteLength;F+=g.EXPLICIT_FILE_CHUNK_SIZE_BYTES){let Q=C.slice(F,Math.min(F+g.EXPLICIT_FILE_CHUNK_SIZE_BYTES,C.byteLength));await E.write(Q);}}catch(C){throw B=true,C}finally{try{await E.close();}catch(C){if(!B)throw C}finally{E.releaseLock();}}return true};try{try{if(await S())return}catch(I){A("[WasmBridge] sendExplicitFileData WebRTC explicit route failed; falling back",{remoteNodeId:d,transferId:s,error:I instanceof Error?I.message:String(I)});}if(await O())return;throw new Error("[WasmBridge] Explicit transfer requires the generation-fenced open_peer_bi_explicit_file_sender path, but it is unavailable on this WASM build. Rebuild the current OpenRTC WASM; raw open_bi fallback is intentionally unsupported for application data.")}finally{A("[WasmBridge] sendExplicitFileData completed",{remoteNodeId:d,transferId:s,fileName:i.name,fileSize:i.size});}}async getTransferHistory(e=50){return []}async deleteTransferJob(e){}watchFriendDevices(e,t){return this.isTicketOnlyMode()?()=>{}:this.getCoordinationSignaling().watchFriendDevices(e,t)}async updateFriendTicket(e){this.isTicketOnlyMode()||await this.getCoordinationSignaling().updateFriendTicket(e);}};g.EXPLICIT_FILE_PROTOCOL_TYPE=2,g.EXPLICIT_FILE_CHUNK_SIZE_BYTES=64*1024,g.MAX_EXPLICIT_TRANSFER_HEADER_BYTES=64*1024,g.FALLBACK_EXPLICIT_FILE_NAME="openrtc-transfer.bin",g.MAX_EXPLICIT_FILE_NAME_CHARS=180,g.FALLBACK_EXPLICIT_MIME_TYPE="application/octet-stream",g.MAX_EXPLICIT_MIME_TYPE_CHARS=255,g.WEB_DEVICE_ID_STORAGE_PREFIX="pluto_rtc_web_device_identity",g.EPHEMERAL_DEVICE_ID_TTL_MS=he.browserIdentity.ephemeralDeviceIdTtlMs;var lt=g;var ut=class{constructor(e){this.backend=e;}get currentUser(){return this.backend.currentUser}setAuthContext(e){return this.backend.setAuthContext?.(e)}async signInAnonymously(){return this.backend.signInAnonymously()}async signInWithPluto(){if(typeof this.backend.signInWithPluto!="function")throw new Error("Selected runtime adapter does not support Pluto SSO.");return this.backend.signInWithPluto()}async signOut(){return this.backend.signOut()}async stopAuthScopedActivity(){typeof this.backend.stopAuthScopedActivity=="function"&&await this.backend.stopAuthScopedActivity();}usesCoordinationGateway(){return this.backend.usesCoordinationGateway?.()===true}async joinCoordinationRoom(e,t,i){if(!this.backend.joinCoordinationRoom)throw new Error("Selected runtime adapter does not support coordination rooms.");await this.backend.joinCoordinationRoom(e,t,i);}async leaveCoordinationRoom(e){if(!this.backend.leaveCoordinationRoom)throw new Error("Selected runtime adapter does not support coordination rooms.");await this.backend.leaveCoordinationRoom(e);}async getCoordinationRoomMembers(e){if(!this.backend.getCoordinationRoomMembers)throw new Error("Selected runtime adapter does not support coordination rooms.");return this.backend.getCoordinationRoomMembers(e)}watchCoordinationRoomMembers(e,t){if(!this.backend.watchCoordinationRoomMembers)throw new Error("Selected runtime adapter does not support coordination rooms.");return this.backend.watchCoordinationRoomMembers(e,t)}async getTurnCredentials(){return this.backend.getTurnCredentials()}async updatePresence(e,t,i,r,o){return this.backend.updatePresence(e,t,i,r,o)}async refreshLivePresence(e,t,i){if(typeof this.backend.refreshLivePresence!="function")throw new Error("Selected runtime adapter does not support refreshLivePresence().");return this.backend.refreshLivePresence(e,t,i)}async setOffline(e){return this.backend.setOffline(e)}async cleanupStaleDevices(){return this.backend.cleanupStaleDevices()}async searchDevices(e){return this.backend.searchDevices(e)}async listDevicesWithStatus(){if(typeof this.backend.listDevicesWithStatus!="function")throw new Error("Selected runtime adapter does not support listDevicesWithStatus().");return this.backend.listDevicesWithStatus()}async getPeerSession(e){return typeof this.backend.getPeerSession!="function"?null:this.backend.getPeerSession(e)}async listPeerSessions(){return typeof this.backend.listPeerSessions!="function"?[]:this.backend.listPeerSessions()}async waitForSettledPeer(e,t){return typeof this.backend.waitForSettledPeer!="function"?null:this.backend.waitForSettledPeer(e,t)}async resolvePeerIdentity(e){return typeof this.backend.resolvePeerIdentity!="function"?{peerId:null,deviceId:null,deviceIdHint:null,nodeId:null}:this.backend.resolvePeerIdentity(e)}async resolvePeerConnectionRecords(e){return typeof this.backend.resolvePeerConnectionRecords!="function"?[]:this.backend.resolvePeerConnectionRecords(e)}async updateDevice(e,t){return this.backend.updateDevice(e,t)}async deleteDevice(e){return this.backend.deleteDevice(e)}onDevicesChange(e,t){return this.backend.onDevicesChange(e,t)}onAuthChange(e){return this.backend.onAuthChange(e)}async checkForSSOToken(){return this.backend.checkForSSOToken()}async waitForAuth(){return this.backend.waitForAuth()}async sendMessage(e,t,i,r){return this.backend.sendMessage(e,t,i,r)}async pollMessages(e){return this.backend.pollMessages(e)}watchFriendDevices(e,t){let i=this.backend;return i.watchFriendDevices?i.watchFriendDevices(e,t):()=>{}}async updateFriendTicket(e){let t=this.backend;t.updateFriendTicket&&await t.updateFriendTicket(e);}async subscribeDevices(e){return this.backend.subscribeDevices(e)}startAutoConnect(e,t){this.backend.startAutoConnect(e,t);}async submitDesiredPeerProjection(e,t){if(typeof this.backend.submitDesiredPeerProjection!="function")throw new Error("Selected runtime adapter does not support desired-peer projections.");await this.backend.submitDesiredPeerProjection(e,t);}startPresenceLoop(e,t,i,r,o){this.backend.startPresenceLoop(e,t,i,r,o);}async createSession(e){return this.backend.createSession(e)}async updateSession(e,t){return this.backend.updateSession(e,t)}async subscribeSessions(e){return this.backend.subscribeSessions(e)}forceReconnectSnapshot(){this.backend.forceReconnectSnapshot();}async getLocalDeviceId(){return typeof this.backend.getLocalDeviceId!="function"?null:this.backend.getLocalDeviceId()}async getLocalDeviceInfo(){return typeof this.backend.getLocalDeviceInfo!="function"?null:this.backend.getLocalDeviceInfo()}async updateLocalDeviceName(e){return typeof this.backend.updateLocalDeviceName!="function"?null:this.backend.updateLocalDeviceName(e)}async startManagedSessionNative(e){let t=this.backend;if(typeof t.startManagedSessionNative!="function")throw new Error("Selected runtime adapter does not support startManagedSessionNative().");return t.startManagedSessionNative(e)}async notifyNetworkChange(e){return typeof this.backend.notifyNetworkChange!="function"?null:this.backend.notifyNetworkChange(e)}async getManagedNodeId(e){if(console.info("[DelegatingRuntimeAdapter][getManagedNodeId] enter",{hasMethod:typeof this.backend.getManagedNodeId=="function",backendCtor:this.backend.constructor?.name??null}),typeof this.backend.getManagedNodeId!="function")return null;let t=await this.backend.getManagedNodeId(e);return console.info("[DelegatingRuntimeAdapter][getManagedNodeId] resolved",{result:t}),t}async startPresenceLoopOnce(e,t,i,r,o){let s=this.backend;if(typeof s.startPresenceLoopOnce!="function")throw new Error("Selected runtime adapter does not support startPresenceLoopOnce().");return s.startPresenceLoopOnce(e,t,i,r,o)}async startAutoConnectOnce(e,t){let i=this.backend;if(typeof i.startAutoConnectOnce!="function")throw new Error("Selected runtime adapter does not support startAutoConnectOnce().");return i.startAutoConnectOnce(e,t)}async getEndpointTicket(){if(typeof this.backend.getEndpointTicket!="function")throw new Error("Selected runtime adapter does not support getEndpointTicket().");return this.backend.getEndpointTicket()}async getEndpointTicketWithToken(e,t){let i=this.backend;return typeof i.getEndpointTicketWithToken!="function"?null:i.getEndpointTicketWithToken(e,t)}async registerSessionToken(e,t,i){let r=this.backend;typeof r.registerSessionToken=="function"&&await r.registerSessionToken(e,t,i);}async revokeSessionTokensByScope(e){let t=this.backend;return typeof t.revokeSessionTokensByScope!="function"?[]:t.revokeSessionTokensByScope(e)}async openPeerBi(e,t){if(typeof this.backend.openPeerBi!="function")throw new Error("Selected runtime adapter does not support openPeerBi().");return this.backend.openPeerBi(e,t)}async incoming_streams(){let e=this.backend;if(typeof e.incoming_streams!="function")throw new Error("Selected runtime adapter does not support incoming_streams().");return e.incoming_streams()}async is_current_transport_stable_id(e,t){let i=this.backend;return typeof i.is_current_transport_stable_id!="function"?false:i.is_current_transport_stable_id(e,t)}async openPeerNativeBi(e,t,i){let r=this.backend;if(typeof r.openPeerNativeBi!="function")throw new Error("Selected runtime adapter does not support openPeerNativeBi().");return r.openPeerNativeBi(e,t,i)}async openPeerBiTransportOnly(e,t){let i=this.backend;return typeof i.openPeerBiTransportOnly=="function"?i.openPeerBiTransportOnly(e,t):this.openPeerBi(e,t)}async openPeerUni(e,t){if(typeof this.backend.openPeerUni!="function")throw new Error("Selected runtime adapter does not support openPeerUni().");return this.backend.openPeerUni(e,t)}async connectToDevice(e){if(typeof this.backend.connectToDevice!="function")throw new Error("Selected runtime adapter does not support connectToDevice().");return this.backend.connectToDevice(e)}async disconnectDevice(e){if(typeof this.backend.disconnectDevice!="function")throw new Error("Selected runtime adapter does not support disconnectDevice().");return this.backend.disconnectDevice(e)}async setAutoConnectExcluded(e,t){if(typeof this.backend.setAutoConnectExcluded!="function")throw new Error("Selected runtime adapter does not support setAutoConnectExcluded().");return this.backend.setAutoConnectExcluded(e,t)}async isConnected(e){return this.backend.isConnected(e)}async getConnectionStates(){return typeof this.backend.getConnectionStates!="function"?[]:this.backend.getConnectionStates()}onConnectionStateChange(e){return typeof this.backend.onConnectionStateChange!="function"?()=>{}:this.backend.onConnectionStateChange(e)}async sendExplicitFilePath(e,t,i){if(typeof this.backend.sendExplicitFilePath!="function")throw new Error("Selected runtime adapter does not support sendExplicitFilePath().");return this.backend.sendExplicitFilePath(e,t,i)}async sendExplicitFileData(e){if(typeof this.backend.sendExplicitFileData!="function")throw new Error("Selected runtime adapter does not support sendExplicitFileData().");return this.backend.sendExplicitFileData(e)}async getTransferHistory(e){return typeof this.backend.getTransferHistory!="function"?[]:this.backend.getTransferHistory(e)}async deleteTransferJob(e){if(typeof this.backend.deleteTransferJob=="function")return this.backend.deleteTransferJob(e)}getRuntimeCapabilities(){let e=this.backend;return typeof e.getRuntimeCapabilities=="function"?e.getRuntimeCapabilities():ie()}async onIncomingNativeMessage(e){let t=this.backend;return typeof t.onIncomingNativeMessage!="function"?()=>{}:t.onIncomingNativeMessage(e)}unwrap(){return this.backend}setCoreClient(e){let t=this.backend;typeof t.setCoreClient=="function"&&t.setCoreClient(e);}};
|
|
2
|
+
export{he as A,Tn as B,Et as C,At as D,Ue as E,ie as F,Cn as G,Pn as H,lt as I,ut as J,ht as a,ee as b,A as c,mn as d,Ln as e,Bn as f,Fn as g,Un as h,me as i,on as j,St as k,bn as l,xe as m,Le as n,f as o,D as p,Be as q,w as r,ne as s,ge as t,un as u,ot as v,st as w,jn as x,zn as y,ct as z};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import {g,h}from'./chunk-
|
|
1
|
+
import {g,h}from'./chunk-PPGIC6DR.js';function c(){return g()}var i=class extends h{constructor(r){super({...r,bridge:g(),allowWasmFallback:r.allowWasmFallback??false});}};export{c as a,i as b};
|