openrtc 2.0.0-rc.2 → 2.0.0-rc.21

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (72) hide show
  1. package/README.md +11 -1
  2. package/dist/DelegatingRuntimeAdapter-7Y3gss5D.d.ts +134 -0
  3. package/dist/OpenRTCShared-LDKG5RPN.js +1 -0
  4. package/dist/WasmBridge-T5XMT6FH.js +1 -0
  5. package/dist/chunk-5OHYIHPT.js +1 -0
  6. package/dist/chunk-DA3HSI3K.js +2 -0
  7. package/dist/chunk-FAPRYEWI.js +2 -0
  8. package/dist/chunk-HTAWPIP2.js +2 -0
  9. package/dist/chunk-PPZRTJHE.js +3 -0
  10. package/dist/chunk-PQK5SJ47.js +1 -0
  11. package/dist/{chunk-RD3JEGGF.js → chunk-QHSM5NFZ.js} +2 -2
  12. package/dist/{chunk-7Z6N46RB.js → chunk-RRMBD5OL.js} +1 -1
  13. package/dist/{chunk-A3IAG6EL.js → chunk-WWC767HK.js} +1 -1
  14. package/dist/chunk-Z2WVSXPW.js +1 -0
  15. package/dist/deviceManagement-PHY5TIOS.js +1 -0
  16. package/dist/deviceProfile-3BEQZLJF.js +2 -0
  17. package/dist/deviceRoster-GHF6MWXF.js +1 -0
  18. package/dist/dist-FIVA6EPA.js +277 -0
  19. package/dist/factories-SMMQHXUH.js +1 -0
  20. package/dist/index.d.ts +4 -6
  21. package/dist/index.js +1 -1
  22. package/dist/ipcFactory-AR3VIBM4.js +1 -0
  23. package/dist/native.d.ts +4 -7
  24. package/dist/native.js +1 -1
  25. package/dist/openrtc-3YHRRPAG.js +2 -0
  26. package/dist/openrtc_bg.wasm +0 -0
  27. package/dist/runtime/WasmRuntimeAdapter.d.ts +3 -3
  28. package/dist/runtime/WasmRuntimeAdapter.js +1 -1
  29. package/dist/runtime/device-status.d.ts +2 -2
  30. package/dist/runtime/index.d.ts +21 -73
  31. package/dist/runtime/index.js +1 -2
  32. package/dist/testing.d.ts +7 -17
  33. package/dist/testing.js +1 -1
  34. package/dist/transport/index.d.ts +2 -2
  35. package/dist/transport/index.js +1 -1
  36. package/dist/{types-BVJr065k.d.ts → types-BwmoJU2O.d.ts} +3 -1
  37. package/dist/{OpenRTCShared-ZQPu5LqL.d.ts → types-DE4iPkMB.d.ts} +268 -8
  38. package/dist/{types-DkgaCyqS.d.ts → types-oGGnaSW2.d.ts} +2 -2
  39. package/package.json +1 -25
  40. package/dist/DelegatingRuntimeAdapter-DqfHkjLy.d.ts +0 -373
  41. package/dist/OpenRTCShared-TKAQLONA.js +0 -1
  42. package/dist/WasmBridge-2A22U7RU.js +0 -1
  43. package/dist/auth/index.d.ts +0 -78
  44. package/dist/auth/index.js +0 -1
  45. package/dist/auth/internal.d.ts +0 -4
  46. package/dist/auth/internal.js +0 -1
  47. package/dist/chunk-2QHDEGVX.js +0 -1
  48. package/dist/chunk-3USHQ7QW.js +0 -3
  49. package/dist/chunk-5LRLWIT5.js +0 -1
  50. package/dist/chunk-6TAVJ46R.js +0 -1
  51. package/dist/chunk-BXFXPIXO.js +0 -1
  52. package/dist/chunk-F2XGNLXL.js +0 -2
  53. package/dist/chunk-GW7P3D54.js +0 -1
  54. package/dist/chunk-IEQTFQ3Q.js +0 -1
  55. package/dist/chunk-K37WVIZL.js +0 -1
  56. package/dist/chunk-N26S7V4N.js +0 -1
  57. package/dist/chunk-N4SX7C3W.js +0 -2
  58. package/dist/chunk-NB4H5TP3.js +0 -1
  59. package/dist/chunk-PODAMIL6.js +0 -2
  60. package/dist/chunk-UEYM6WTT.js +0 -2
  61. package/dist/chunk-VK6KX433.js +0 -1
  62. package/dist/chunk-YBXGNKM7.js +0 -2
  63. package/dist/chunk-YQWQDTQ3.js +0 -2
  64. package/dist/factories-SIVMTIHJ.js +0 -1
  65. package/dist/ipc-CflAVodw.d.ts +0 -11
  66. package/dist/ipcFactory-QY44OIKA.js +0 -1
  67. package/dist/runtime/legacy.d.ts +0 -18
  68. package/dist/runtime/legacy.js +0 -1
  69. package/dist/runtime/tauri.d.ts +0 -6
  70. package/dist/runtime/tauri.js +0 -1
  71. package/dist/tauri-Cz9n17g8.d.ts +0 -33
  72. package/dist/types-DNl4KHHY.d.ts +0 -195
@@ -1 +0,0 @@
1
- import {f}from'./chunk-F2XGNLXL.js';import {d}from'./chunk-K37WVIZL.js';function c(){return d()}var i=class extends f{constructor(r){super({...r,bridge:d(),allowWasmFallback:r.allowWasmFallback??false});}};export{c as a,i as b};
@@ -1 +0,0 @@
1
- import {u}from'./chunk-3USHQ7QW.js';import {f}from'./chunk-F2XGNLXL.js';import {c}from'./chunk-RD3JEGGF.js';function s(i,r){let t=c(i);return u(t,new f({...t,bridge:r}))}export{s as a};
@@ -1 +0,0 @@
1
- function m(o,u,t){let e;return new Promise((f,n)=>{e=setTimeout(()=>{if(e=void 0,typeof t=="function"){n(t());return}let i=t?`${t} timed out`:"timeout";n(new Error(`${i} after ${u}ms`));},u),o.then(i=>{e!==void 0&&clearTimeout(e),f(i);},i=>{e!==void 0&&clearTimeout(e),n(i);});})}export{m as a};
@@ -1,2 +0,0 @@
1
- import {a as a$1}from'./chunk-A3IAG6EL.js';import {o,u,w,s,h as h$1,g,j as j$2,k as k$1,l,m,n}from'./chunk-YBXGNKM7.js';import {c as c$1,b as b$1}from'./chunk-VK6KX433.js';import {c,d as d$1,b}from'./chunk-K37WVIZL.js';import {a as a$2}from'./chunk-BXFXPIXO.js';import {c as c$2,b as b$2}from'./chunk-N26S7V4N.js';import {d,a}from'./chunk-NB4H5TP3.js';import {d as d$2,j as j$1}from'./chunk-RD3JEGGF.js';var H="relay-only endpoint ticket unavailable",Q=12e3,X=250,Z=1500;function ee(g){return String(g?.message??g??"").toLowerCase().includes(H)}async function E(g,e={}){let t=e.windowMs??Q,i=e.minDelayMs??X,a$1=e.maxDelayMs??Z,n=Date.now(),s=0,o=null;for(;e.isActive?.()??true;){s+=1;try{return await g()}catch(c){if(o=c,!ee(c))throw c;let d$1=Date.now()-n;if(d$1>=t)throw c;let r=Math.min(d(s,i,a$1),Math.max(0,t-d$1));r>0&&await a(r);}}throw o||new Error("endpoint ticket minting stopped before a ticket was available")}function Y(g){let e=g?.split(".")[1];if(!e)return null;try{let t=e.replace(/-/g,"+").replace(/_/g,"/"),i=(4-t.length%4)%4,a=atob(t+"=".repeat(i)),n=JSON.parse(a);return n&&typeof n=="object"&&!Array.isArray(n)?n:null}catch{return null}}function k(g,e){let t=g?.[e];return typeof t=="string"&&t.trim()?t.trim():null}function j(g,e,t){let i=k(g,"namespaceId")===e||k(g,"appTag")===`space::${e}`,a=k(g,"developerAppTag");return i&&!!a&&(!t||a===t)}function ae(g){let e=k(g,"developerAppTag");if(e)return e;let t=k(g,"appTag");return t&&!t.startsWith("space::")?t:null}var h=class h{constructor(e){this.subscriptionNonce=0;this.lastSyncedAuthToken=null;this.cachedLocalDeviceId=null;this.cachedLocalDeviceName=null;this.tauriCoreAvailability=null;this.tauriCoreAvailabilityValue=null;this.tauriCoreAvailabilityCheckedAtMs=0;this.authSyncInFlight=null;this.nativeTrustTokenUnsubscribe=null;this.nativeTrustRelayQueue=Promise.resolve();this.nativeTrustRelayError=null;this.nativeRuntimeCapabilitiesSyncInFlight=null;this.gatewayDesiredPeersCleanup=null;this.gatewayDesiredPeerRelayKey=null;this.gatewayDesiredPeerRelayGeneration=0;this.gatewayDesiredPeerRevision=0;this.gatewayDesiredPeerSubmission=Promise.resolve();this.gatewayDesiredPeerLifecycle=Promise.resolve();this.gatewayExcludedPeers=new Set;this.lastNativeAuthSyncAtMs=0;this.runtimeCapabilities=u(null,false);this.fallback=new w({...e,coordinationPlatformType:"desktop"}),this.app=this.fallback.app,this.auth=this.fallback.auth,this.appTag=this.fallback.tag,this.options=this.fallback.getResolvedOptions(),this.transportOptions=e.transports,this.strictMode=e.strictMode===true,this.turnCredentialsProvider=e.turnCredentialsProvider,this.allowWasmFallback=e.allowWasmFallback??false,this.ipcBridge=c(e.ipcBridge??d$1(),"NativeIpcBridge"),this.runtimeCapabilities=u(null,this.allowWasmFallback),this.syncNativeRuntimeCapabilities("constructor");}get currentUser(){return this.fallback.currentUser}get tag(){return this.fallback.tag}getRuntimeCapabilities(){let e=s(this.runtimeCapabilities);return e.fallback.wasm=this.allowWasmFallback,e}usesCoordinationGateway(){return this.fallback.usesCoordinationGateway()}assertManagedCoordinationGateway(){if(!this.usesCoordinationGateway())throw new Error("[OpenRTC] Native managed coordination requires coordinationGateway; the legacy native Firebase data plane has been removed.")}async joinCoordinationRoom(e,t,i){await this.syncCoordinationDeviceIdentity(),await this.fallback.joinCoordinationRoom(e,t,i);}leaveCoordinationRoom(e){return this.fallback.leaveCoordinationRoom(e)}getCoordinationRoomMembers(e){return this.fallback.getCoordinationRoomMembers(e)}watchCoordinationRoomMembers(e,t){return this.fallback.watchCoordinationRoomMembers(e,t)}async syncCoordinationDeviceIdentity(){if(!this.usesCoordinationGateway())return;let e=await this.getLocalDeviceInfo().catch(()=>null),t=e?.deviceId||await this.resolveLocalDeviceId();this.fallback.setCoordinationLocalDeviceId(t),this.fallback.setCoordinationPlatformType(this.normalizeNativeCoordinationPlatform(e?.platformType));}setWasmClient(e){if(!this.allowWasmFallback){let t="[NativeIpcBridge][NATIVE-GUARD] Refusing WasmClient attachment because native IPC is authoritative and WASM fallback is disabled.";throw console.error(t,{capabilities:this.getRuntimeCapabilities()}),new Error(t)}this.fallback.setWasmClient(e);}onAuthChange(e){return this.fallback.onAuthChange(e)}checkForSSOToken(){return this.fallback.checkForSSOToken()}waitForAuth(){return this.fallback.waitForAuth()}signInAnonymously(){return this.fallback.signInAnonymously()}getTurnCredentials(){return this.fallback.getTurnCredentials()}cleanupStaleDevices(){return this.fallback.cleanupStaleDevices()}sendMessage(e,t,i,a){return this.fallback.sendMessage(e,t,i,a)}pollMessages(e){return this.fallback.pollMessages(e)}watchFriendDevices(e,t){return this.assertManagedCoordinationGateway(),this.fallback.watchFriendDevices(e,t)}async updateFriendTicket(e){this.assertManagedCoordinationGateway(),await this.syncCoordinationDeviceIdentity(),await this.fallback.updateFriendTicket(e);}createSession(e){return this.fallback.createSession(e)}updateSession(e,t){return this.fallback.updateSession(e,t)}async openPeerBi(e,t){return await this.canUseTauriIpc()?this.openPeerBiViaIpc("open_peer_bi_stream",{peerId:e,timeoutMs:t??null}):this.fallback.openPeerBi(e,t)}async openPeerBiTransportOnly(e,t){return await this.canUseTauriIpc()?this.openPeerBiViaIpc("open_peer_bi_transport_only_stream",{peerId:e,timeoutMs:t??null},{fallbackCommand:"open_peer_bi_stream"}):this.fallback.openPeerBiTransportOnly(e,t)}async openPeerNativeBi(e,t,i){return await this.canUseTauriIpc()?this.openPeerBiViaIpc("open_peer_native_bi_stream",{peerId:e,label:t,timeoutMs:i??null},{fallbackCommand:"open_peer_bi_stream",fallbackArgs:{peerId:e,timeoutMs:i??null}}):this.fallback.openPeerNativeBi(e,t,i)}async incoming_streams(){if(!await this.canUseTauriIpc()){let n=this.fallback;if(typeof n.incoming_streams=="function")return n.incoming_streams();throw new Error("Native incoming stream bridge is unavailable")}let e=`native-incoming-${Date.now()}-${++this.subscriptionNonce}`,t=null,i=false,a=async()=>{i=true;let n=t;t=null,await Promise.allSettled([n?Promise.resolve(n()):Promise.resolve(),this.invokeIpc("stop_rtc_subscription",{requestId:e},{timeoutMs:null}).catch(()=>{})]);};return new ReadableStream({start:async n=>{try{t=await this.listenIpc("openrtc://peer-bi-stream/incoming",s=>{if(i)return;let o=s.payload,c=typeof o?.requestId=="string"?o.requestId:typeof o?.request_id=="string"?o.request_id:"";if(c!==e){c$1("[NativeIpcBridge][incoming-application-stream] ignored request id",{expectedRequestId:e,eventRequestId:c});return}let d=typeof o?.streamId=="string"?o.streamId.trim():typeof o?.stream_id=="string"?o.stream_id.trim():"";if(!d)return;let r=typeof o?.remoteNodeId=="string"?o.remoteNodeId.trim():typeof o?.remote_node_id=="string"?o.remote_node_id.trim():"",l=Number.isSafeInteger(o?.transportStableId)?Number(o.transportStableId):Number.isSafeInteger(o?.transport_stable_id)?Number(o.transport_stable_id):0;if(!r||l<=0){c$1("[NativeIpcBridge][incoming-application-stream] ignored invalid generation",{requestId:e,remoteNodeId:r,transportStableId:l});return}c$1("[NativeIpcBridge][incoming-application-stream] accepted event",{requestId:e,remoteNodeId:r,transportStableId:l});let u=this.peerBiStreamFromId(d,{startReadAfterListeners:!0});n.enqueue({type:"bi",stream:{send:u.writable,recv:u.readable,endpoint_id:r},endpointId:r,transportStableId:l,protocolHint:"unknown",channel:null});}),await this.invokeIpc("start_incoming_peer_bi_streams",{requestId:e},{timeoutMs:null});}catch(s){i=true,n.error(s),await a();}},cancel:async()=>{await a();}})}async is_current_transport_stable_id(e,t){if(!await this.canUseTauriIpc()){let i=this.fallback;return typeof i.is_current_transport_stable_id=="function"?i.is_current_transport_stable_id(e,t):false}return !e.trim()||t<=0n||t>BigInt(Number.MAX_SAFE_INTEGER)?false:this.invokeIpc("is_current_transport_stable_id",{endpointId:e.trim(),transportStableId:Number(t)})}openPeerUni(e,t){return this.fallback.openPeerUni(e,t)}isConnected(e){return this.fallback.isConnected(e)}getAuthContext(){return this.fallback.getAuthContext()}resolveNativeAuthScopedUserId(e){return this.currentUser?.id??this.getAuthContext()?.userId??e??null}resolveConfiguredSpaceKey(){let e=this.options.spaceKey??this.options.space;return typeof e=="string"?e.trim():""}usesAnonymousSpaceMode(){return this.options.authMode==="anonymous"&&this.resolveConfiguredSpaceKey().length>0}requiresNativeAuthToken(){return !this.usesAnonymousSpaceMode()||typeof this.options.spaceTokenProvider=="function"}async nativeAuthTokenMatchesExpectedScope(e){if(!this.usesAnonymousSpaceMode())return true;let t=typeof this.options.apiKey=="string"?this.options.apiKey.trim():"",i=this.resolveConfiguredSpaceKey();if(!t||!i)return true;let a=await d$2(t,i).catch(()=>null);return a?j(Y(e),a):true}resolveNativeSignalingUserId(e){return this.usesAnonymousSpaceMode()?(typeof e=="string"?e.trim():"")||this.resolveConfiguredSpaceKey()||null:this.resolveNativeAuthScopedUserId(e)}getCurrentUserId(){return this.resolveNativeSignalingUserId(this.fallback.getCurrentUserIdForScope())}nativeAuthWaitMs(){return this.requiresNativeAuthToken()?h.AUTH_REQUIRED_WAIT_MS:0}resolveWebLogicalDeviceId(){return this.fallback.getResolvedWebLogicalDeviceId()}normalizeDevice(e,t){return this.fallback.normalizeDeviceRecord(e,t)}matchesTag(e){return this.fallback.matchesLegacyOrCurrentTag(e)}nativeRosterTagDisposition(e){let t=h$1(e);if(this.matchesTag(t))return {keep:true,classification:"match"};let i=typeof t.appTag=="string"&&t.appTag.trim().length>0?t.appTag.trim():typeof t.tag=="string"&&t.tag.trim().length>0?t.tag.trim():void 0;return i===void 0?{keep:true,classification:"untagged"}:{keep:false,classification:"foreign",foreignTag:i}}filterNativeRosterByTag(e,t){let i=new Set,a=e.filter(n=>{let s=this.nativeRosterTagDisposition(n);return !s.keep&&s.foreignTag&&i.add(s.foreignTag),s.keep});return e.length>0&&a.length===0&&i.size>0?console.warn(`[NativeIpcBridge] ${t}: dropped ALL ${e.length} native device(s) as foreign-app \u2014 this is the app-tag drift signature (empty native device list). The native Rust OpenRTC app tag does not match the SDK app tag; check that the desktop binary and the web bundle use the same VITE_PLUTO_OPENRTC_API_KEY / VITE_PLUTO_OPENRTC_APP_TAG for this environment lane.`,{sdkAppTag:this.appTag,foreignTags:Array.from(i),droppedCount:e.length}):i.size>0&&c$1(`[NativeIpcBridge] ${t}: filtered ${e.length-a.length} foreign-app device(s) from the native roster`,{sdkAppTag:this.appTag,foreignTags:Array.from(i)}),a}normalizeNativeIceServer(e){let t=e.urls,i=Array.isArray(t)?t.filter(a=>typeof a=="string"&&a.trim().length>0):typeof t=="string"&&t.trim().length>0?[t]:[];return i.length===0?null:{urls:i,username:typeof e.username=="string"&&e.username.trim().length>0?e.username:void 0,credential:typeof e.credential=="string"&&e.credential.trim().length>0?e.credential:void 0}}filterNativeStunServers(e){return e.map(t=>({...t,urls:t.urls.filter(i=>!i.startsWith("stun:"))})).filter(t=>t.urls.length>0)}nativeIceServerHasTurnUrl(e){return e.urls.some(t=>t.startsWith("turn:")||t.startsWith("turns:"))}async loadNativeTurnIceServers(){if(typeof this.turnCredentialsProvider!="function")return [];let e=await this.turnCredentialsProvider().catch(t=>(console.warn("[NativeIpcBridge] TURN credential provider failed:",t),null));return !e||!Array.isArray(e.iceServers)?[]:e.iceServers.map(t=>this.normalizeNativeIceServer(t)).filter(t=>!!t)}async buildNativeTransportConfigPayload(){let e=this.transportOptions;if(!e&&!this.strictMode)return null;let t;!this.strictMode&&e?.iroh&&(typeof e.iroh=="object"&&e.iroh.localDiscovery===false?t=null:t={enabled:true,advertise:typeof e.iroh!="object"||e.iroh.localDiscoveryMode!=="passive"});let i=null;if(e?.webrtc===true||e?.webrtc&&typeof e.webrtc=="object"){let d=e.webrtc===true?null:e.webrtc,r=d?.useDefaultIceServers!==false,l=Array.isArray(d?.iceServers)&&d.iceServers.length>0?d.iceServers.map(y=>this.normalizeNativeIceServer(y)).filter(y=>!!y):r?j$1.map(y=>this.normalizeNativeIceServer(y)).filter(y=>!!y):[],u=this.strictMode||d?.privacyMode===true;(this.strictMode||d?.privacyMode===true||d?.useTurn===true)&&(l=[...l,...await this.loadNativeTurnIceServers()]),u&&(l=this.filterNativeStunServers(l));let m=l.some(y=>this.nativeIceServerHasTurnUrl(y)),v=u&&m;u&&!m&&console.warn("[NativeIpcBridge] Relay-only WebRTC requested, but no TURN servers are configured; native WebRTC override disabled");let _=d?.lanMode===true;(l.length>0||v||_||!r)&&(i={iceServers:l.length>0||!r?l:void 0,privacyMode:v,lanMode:_||void 0});}let a=null;if(e?.moq&&typeof e.moq=="object"){let d=typeof e.moq.relayUrl=="string"&&e.moq.relayUrl.trim().length>0?e.moq.relayUrl:void 0;if(d){let r=typeof e.moq.accessToken=="string"&&e.moq.accessToken.trim().length>0?e.moq.accessToken.trim():void 0;a={relayUrl:d,accessToken:r};}}let n=null;if(!this.strictMode&&(e?.ble===true||e?.ble&&typeof e.ble=="object")){let d=e.ble===true?null:e.ble,r=Number(d?.connectTimeoutMs);n={enabled:d?.enabled!==false,connectTimeoutMs:Number.isFinite(r)&&r>0?Math.round(r):void 0};}let s=this.strictMode||e?.iroh&&typeof e.iroh=="object"&&e.iroh.relayOnly===true,o=e?.iroh&&typeof e.iroh=="object"?e.iroh.relayTransportPolicy:void 0,c=this.strictMode?o??"auto":o;return !s&&!c&&!i&&!a&&!t&&!n?null:{irohRelayOnly:s||void 0,irohRelayTransportPolicy:c,...t!==void 0?{irohLan:t}:{},webrtc:i,moq:a,ble:n}}isTauriEnv(){return c$2()}nextConnectionEventRetryDelayMs(e){return d(e,h.CONNECTION_EVENT_RETRY_MIN_DELAY_MS,h.CONNECTION_EVENT_RETRY_MAX_DELAY_MS)}async clearNativeAuthRelay(e){if(await this.canUseTauriIpc())try{typeof this.options.coordinationGateway?.grantProvider=="function"?await this.invokeIpc("openrtc_v2_set_identity_credential",{identityCredential:null}):await this.invokeIpc("desktop_set_pluto_auth_token",{authToken:null,refreshToken:null}),this.lastSyncedAuthToken=null,this.lastNativeAuthSyncAtMs=0,c$1(`[NativeIpcBridge] cleared native auth relay (${e})`);}catch(t){console.warn(`[NativeIpcBridge] failed clearing native auth relay (${e}):`,t);}}async clearNativeTrustRelay(e){if(this.nativeTrustTokenUnsubscribe?.(),this.nativeTrustTokenUnsubscribe=null,this.nativeTrustRelayError=null,this.fallback.invalidateCoordinationNativeTrustToken(),typeof this.options.coordinationGateway?.grantProvider!="function"&&await this.canUseTauriIpc())try{await this.invokeIpc("openrtc_set_native_trust_token",{trustToken:null,expiresAtMs:null}),c$1(`[NativeIpcBridge] cleared native trust relay (${e})`);}catch(t){b(t)||console.warn(`[NativeIpcBridge] failed clearing native trust relay (${e}):`,t);}}relayNativeTrustToken(e,t){let i=async()=>{await this.canUseTauriIpc()&&(await this.invokeIpc("openrtc_set_native_trust_token",{trustToken:e?.token??null,expiresAtMs:e?.expiresAtMs??null}),c$1(`[NativeIpcBridge] native trust token ${e?"relayed":"cleared"} (${t})`));},a=this.nativeTrustRelayQueue.then(i,i);return this.nativeTrustRelayQueue=a.catch(()=>{}),a}async ensureNativeTrustRelay(e=false){if(!this.usesCoordinationGateway()||typeof this.options.coordinationGateway?.grantProvider=="function")return true;if(typeof this.options.coordinationGateway?.nativeTrustTokenProvider!="function")return false;if(!await this.canUseTauriIpc())return true;try{let t=await this.fallback.getCoordinationNativeTrustToken(e);return await this.relayNativeTrustToken(t,"auth-ready"),this.nativeTrustRelayError=null,this.nativeTrustTokenUnsubscribe||(this.nativeTrustTokenUnsubscribe=this.fallback.subscribeCoordinationNativeTrustToken(i=>{this.relayNativeTrustToken(i,"provider-refresh").catch(a=>{console.warn("[NativeIpcBridge] native trust token refresh relay failed:",a);});},{emitCurrent:!1})),!0}catch(t){return this.nativeTrustRelayError=(t instanceof Error?t.message:String(t)).trim().slice(0,300)||"unknown provider failure",console.warn("[NativeIpcBridge] native trust token unavailable:",t),false}}async relayNativeAuthToken(e,t,i,a){if(!await this.canUseTauriIpc())return true;if(!await this.nativeAuthTokenMatchesExpectedScope(e))return c$1(`[NativeIpcBridge] auth sync deferred (${i}): token claims do not match configured space`),false;if(e===this.lastSyncedAuthToken)return true;try{typeof this.options.coordinationGateway?.grantProvider=="function"?await this.invokeIpc("openrtc_v2_set_identity_credential",{identityCredential:e}):await this.invokeIpc("desktop_set_pluto_auth_token",{authToken:e,refreshToken:t??null});}catch(n){return b(n)?console.warn(`[NativeIpcBridge] desktop auth relay unavailable (${i}); install/register openrtc-tauri-plugin and include its default permission set.`,n):console.warn(`[NativeIpcBridge] desktop auth relay failed (${i}):`,n),false}return this.lastSyncedAuthToken=e,this.lastNativeAuthSyncAtMs=Date.now(),c$1(`[NativeIpcBridge] auth token relayed to native runtime (${i}) user_id=${a??this.currentUser?.id??"unknown"}`),true}async relayExplicitNativeAuthContext(e){let t=this.authSyncInFlight,i=(async()=>(await t?.catch(()=>{}),this.relayNativeAuthToken(e.token,e.refreshToken,"setAuthContext",e.userId)))();this.authSyncInFlight=i;try{return await i}finally{this.authSyncInFlight===i&&(this.authSyncInFlight=null);}}applyNativeRuntimeStatus(e){this.runtimeCapabilities=u(e,this.allowWasmFallback);}syncNativeRuntimeCapabilities(e){return this.ipcBridge?this.nativeRuntimeCapabilitiesSyncInFlight?this.nativeRuntimeCapabilitiesSyncInFlight:(this.nativeRuntimeCapabilitiesSyncInFlight=(async()=>{try{let t=await this.invokeIpc("rtc_native_status",void 0,{timeoutMs:h.NATIVE_STATUS_IPC_TIMEOUT_MS});this.applyNativeRuntimeStatus(t),c$1(`[NativeIpcBridge] refreshed native runtime capabilities (${e})`);}catch(t){b$1("[NativeIpcBridge] native runtime capability refresh skipped",t);}})().finally(()=>{this.nativeRuntimeCapabilitiesSyncInFlight=null;}),this.nativeRuntimeCapabilitiesSyncInFlight):Promise.resolve()}async canUseTauriIpc(){if(this.ipcBridge){let e=typeof this.ipcBridge.isAvailable=="function"?!!await this.ipcBridge.isAvailable():true;return e&&this.syncNativeRuntimeCapabilities("ipc-available"),e}return typeof window>"u"?false:this.tauriCoreAvailabilityValue===true?true:this.tauriCoreAvailabilityValue===false&&Date.now()-this.tauriCoreAvailabilityCheckedAtMs<h.TAURI_IPC_NEGATIVE_CACHE_MS?false:(this.tauriCoreAvailability||(this.tauriCoreAvailability=(async()=>{try{if(this.isTauriEnv())return this.tauriCoreAvailabilityValue=!0,this.tauriCoreAvailabilityCheckedAtMs=Date.now(),this.syncNativeRuntimeCapabilities("tauri-env"),!0;try{let e=await this.invokeIpc("rtc_native_status");return this.applyNativeRuntimeStatus(e),c$1("[NativeIpcBridge] Resolved Tauri IPC via rtc_native_status probe"),this.tauriCoreAvailabilityValue=!0,this.tauriCoreAvailabilityCheckedAtMs=Date.now(),!0}catch(e){let t=String(e?.message??e??"");return t.includes("__TAURI_INTERNALS__")||t.includes("Cannot read properties of undefined")||t.includes("window is not defined")?(this.tauriCoreAvailabilityValue=!1,this.tauriCoreAvailabilityCheckedAtMs=Date.now(),!1):(c$1("[NativeIpcBridge] Tauri IPC probe reached native layer (command-level error acceptable)"),this.tauriCoreAvailabilityValue=!0,this.tauriCoreAvailabilityCheckedAtMs=Date.now(),!0)}}catch{return this.tauriCoreAvailabilityValue=false,this.tauriCoreAvailabilityCheckedAtMs=Date.now(),false}})().finally(()=>{this.tauriCoreAvailability=null;})),this.tauriCoreAvailability)}async invokeIpc(e,t,i){let a=this.ipcBridge.invoke(e,t),n=i&&Object.prototype.hasOwnProperty.call(i,"timeoutMs")?i.timeoutMs:h.DEFAULT_BOUNDED_IPC_TIMEOUT_MS;return n==null||n<=0?a:a$2(a,n,()=>new Error(`${e} timeout after ${n}ms`))}async listenIpc(e,t){return this.ipcBridge.listen(e,i=>{t({payload:i});})}async openPeerBiViaIpc(e,t,i){let a=await this.invokePeerBiOpen(e,t,i),n=typeof a?.streamId=="string"?a.streamId.trim():typeof a?.stream_id=="string"?a.stream_id.trim():"";if(!n)throw new Error(`${e} returned no streamId`);return this.peerBiStreamFromId(n)}peerBiStreamFromId(e,t={}){let i=this,a=null,n=null,s=false,o=null,c=null,d=async()=>{let m=[a,n];a=null,n=null,await Promise.allSettled(m.filter(v=>typeof v=="function").map(v=>Promise.resolve(v())));},r=(async()=>{a=await this.listenIpc("openrtc://peer-bi-stream/chunk",m=>{let v=m.payload;if((typeof v?.streamId=="string"?v.streamId:typeof v?.stream_id=="string"?v.stream_id:"")!==e||s||!o)return;let f=v?.bytes;f instanceof Uint8Array?o.enqueue(f):Array.isArray(f)&&o.enqueue(new Uint8Array(f));}),n=await this.listenIpc("openrtc://peer-bi-stream/closed",m=>{let v=m.payload;if((typeof v?.streamId=="string"?v.streamId:typeof v?.stream_id=="string"?v.stream_id:"")!==e||s||!o)return;s=true;let f=typeof v?.error=="string"?v.error.trim():"";f?o.error(new Error(f)):o.close(),d();}),t.startReadAfterListeners&&await this.invokeIpc("start_peer_bi_stream_read",{streamId:e},{timeoutMs:null});})().catch(m=>{c=m,o&&!s&&(s=true,o.error(m));}),l=async()=>{await this.invokeIpc("close_peer_bi_stream",{streamId:e},{timeoutMs:null}).catch(()=>{}),await d();},u=new ReadableStream({async start(m){o=m,await r,c&&!s&&(s=true,m.error(c));},async cancel(){s=true,await l();}}),I=new WritableStream({write:async m=>{await i.invokeIpc("write_peer_bi_stream",{streamId:e,bytes:Array.from(m)},{timeoutMs:null});},close:l,abort:l});return {readable:u,writable:I}}async invokePeerBiOpen(e,t,i){try{return await this.invokeIpc(e,t)}catch(a){if(!i?.fallbackCommand||!this.isMissingNativeCommandError(a))throw a;return this.invokeIpc(i.fallbackCommand,i.fallbackArgs??t)}}isMissingNativeCommandError(e){let t=e instanceof Error?e.message:String(e??"");return t.includes("Command")&&t.includes("not found")}async shouldUseTauriSignaling(){if(await this.canUseTauriIpc())return true;if(this.allowWasmFallback)return false;throw new Error("[pluto-rtc] Tauri runtime adapter requires native IPC, but it is unavailable.")}async signInWithPluto(){if(!await this.canUseTauriIpc()){await this.fallback.signInWithPluto();return}let e=await this.invokeIpc("rtc_sign_in_with_pluto"),t=typeof e?.customToken=="string"?e.customToken.trim():"";if(!t)throw new Error("[pluto-rtc] Native Pluto SSO did not return a custom token.");await b$2().signInWithCustomTokenValue(t),await this.ensureNativeAuth("pluto-sso",{requireToken:true,maxWaitMs:1e4});}async setAuthContext(e){let t=this.getAuthContext()?.userId??null,i=typeof e?.userId=="string"&&e.userId.trim()||null,a=this.fallback.setAuthContext(e);if(t&&i&&t!==i&&await this.stopNativeAuthScopedActivity(t),await a,!e?.token)await this.clearNativeAuthRelay("setAuthContext"),await this.clearNativeTrustRelay("setAuthContext");else {if(!await this.relayExplicitNativeAuthContext(e))throw new Error("Native auth token unavailable for setAuthContext");if(!await this.ensureNativeTrustRelay())throw new Error(`Native trust token unavailable for setAuthContext: ${this.nativeTrustRelayError??"unknown provider failure"}`)}}async signOut(){await this.fallback.signOut(),await Promise.all([this.clearNativeAuthRelay("signOut"),this.clearNativeTrustRelay("signOut")]);}async stopAuthScopedActivity(e){let t=this.resolveNativeSignalingUserId(e?.userId??null);await this.stopNativeAuthScopedActivity(t);}async stopNativeAuthScopedActivity(e){await this.stopGatewayDesiredPeerRelay(),this.gatewayExcludedPeers.clear();let t=await this.shouldUseTauriSignaling();if(g("NativeIpcBridge.stopAuthScopedActivity",{userId:e,useTauri:t}),t)try{await Promise.allSettled([this.revokeSessionTokensByScope("user-device"),this.invokeIpc("stop_rtc_presence_loop"),this.invokeIpc("stop_rtc_auto_connect")]);}catch(i){console.warn("[NativeIpcBridge] Failed to stop native auth-scoped RTC activity:",i);}await this.fallback.stopAuthScopedActivity({userId:e});}async ensureNativeAuthOnce(e,t){if(!await this.canUseTauriIpc())return true;if(this.authSyncInFlight)return this.authSyncInFlight;let i=(async()=>{try{if(!this.currentUser)return c$1(`[NativeIpcBridge] auth sync deferred (${e}): no current user`),!t;let a=Date.now()-this.lastNativeAuthSyncAtMs>=480*1e3,n=this.currentUser?.getToken?await this.currentUser.getToken(a):null,o=this.getAuthContext()?.refreshToken??this.auth?.currentUser?.refreshToken??null;return n?this.relayNativeAuthToken(n,o,e,this.currentUser?.id):(c$1(`[NativeIpcBridge] auth sync deferred (${e}): missing token for user ${this.currentUser?.id}`),!t)}catch(a){return console.error("[NativeIpcBridge] auth sync failed:",a),false}})();this.authSyncInFlight=i;try{return await i}finally{this.authSyncInFlight===i&&(this.authSyncInFlight=null);}}async ensureNativeAuth(e="runtime",t){if(!await this.canUseTauriIpc())return true;let i=t?.requireToken??false,a$1=t?.maxWaitMs??(i?h.AUTH_REQUIRED_WAIT_MS:0),n=t?.pollMs??250,s=Date.now()+Math.max(0,a$1);for(;;){if(await this.ensureNativeAuthOnce(e,i))return true;if(!i||Date.now()>=s)return false;await a(n);}}decodeNativeDeviceIdentity(e){let t=e?.systemInfo??e?.system_info??null,i=typeof e?.deviceId=="string"?e.deviceId.trim():typeof e?.device_id=="string"?e.device_id.trim():"",a=typeof e?.deviceName=="string"?e.deviceName.trim():typeof e?.device_name=="string"?e.device_name.trim():"",n=typeof e?.platformType=="string"?e.platformType.trim():typeof e?.platform_type=="string"?e.platform_type.trim():typeof t?.platformType=="string"?t.platformType.trim():typeof t?.platform_type=="string"?t.platform_type.trim():"";return {deviceId:i,deviceName:a,platformType:n}}async resolveLocalDeviceId(){if(this.cachedLocalDeviceId)return this.cachedLocalDeviceId;if(await this.canUseTauriIpc())try{let t=await this.invokeIpc("get_rtc_local_device_info"),{deviceId:i,deviceName:a}=this.decodeNativeDeviceIdentity(t);if(i)return this.cachedLocalDeviceId=i,a&&(this.cachedLocalDeviceName=a),i}catch(t){console.warn("[NativeIpcBridge] get_rtc_local_device_info failed:",t);}let e=this.resolveWebLogicalDeviceId();return this.cachedLocalDeviceId=e,e}async resolveLocalDeviceName(){if(this.cachedLocalDeviceName)return this.cachedLocalDeviceName;if(await this.canUseTauriIpc())try{let e=await this.invokeIpc("get_rtc_local_device_info"),{deviceName:t}=this.decodeNativeDeviceIdentity(e);if(t){let i=this.normalizeNativeDeviceName(t);return this.cachedLocalDeviceName=i,i}}catch(e){console.warn("[NativeIpcBridge] get_rtc_local_device_info failed:",e);}return this.defaultDeviceNameFallback()}normalizeNativeDeviceName(e){let t=e.trim();if(!t)return this.defaultDeviceNameFallback();if(t==="Desktop Device"){let i=this.defaultDeviceNameFallback();if(i!=="Desktop Device")return i}return t}defaultDeviceNameFallback(){if(typeof window>"u"||typeof navigator>"u")return "Desktop Device";let e=navigator.userAgent||"";return /iPhone|iPad|iPod/i.test(e)?"iPhone":/Android/i.test(e)?"Android":"Desktop Device"}inferNativePlatformTypeFallback(){if(typeof window>"u"||typeof navigator>"u")return "desktop";if(!this.isTauriEnv())return "web";let e=navigator.userAgent||"";return /iPhone|iPad|iPod|Android|Mobile/i.test(e)?"mobile":"desktop"}normalizeNativeCoordinationPlatform(e){let t=e?.trim().toLowerCase()??"";return t==="mobile"||t==="ios"||t==="android"||t.includes("iphone")||t.includes("ipad")||this.inferNativePlatformTypeFallback()==="mobile"?"mobile":"desktop"}withPresenceMetadata(e,t){try{let i=e?JSON.parse(e):{};return JSON.stringify({...i,deviceId:t,plutoVersion:"0.1.0-desktop"})}catch{return JSON.stringify({deviceId:t,plutoVersion:"0.1.0-desktop",rawMetadata:e})}}async searchDevices(e){return this.assertManagedCoordinationGateway(),this.fallback.searchDevices(e)}async listDevicesWithStatus(){return this.assertManagedCoordinationGateway(),(await this.fallback.searchDevices()).map(e=>j$2(e))}async getPeerSession(e){if(await this.shouldUseTauriSignaling()){let t=await this.invokeIpc("get_rtc_peer_session",{id:e});return !t||typeof t!="object"?null:k$1(t)}return this.fallback.getPeerSession(e)}async listPeerSessions(){if(await this.shouldUseTauriSignaling()){let e=await this.invokeIpc("list_rtc_peer_sessions");return (Array.isArray(e)?e:[]).map(t=>k$1(t))}return this.fallback.listPeerSessions()}async waitForSettledPeer(e,t){if(await this.shouldUseTauriSignaling()){let i=typeof t=="number"?Math.max(h.DEFAULT_BOUNDED_IPC_TIMEOUT_MS,t+1e3):h.DEFAULT_BOUNDED_IPC_TIMEOUT_MS,a=await this.invokeIpc("wait_for_rtc_settled_peer",{id:e,timeoutMs:t},{timeoutMs:i});return !a||typeof a!="object"?null:k$1(a)}return this.fallback.waitForSettledPeer(e,t)}async resolvePeerConnectionRecords(e){if(await this.shouldUseTauriSignaling()){let t=await this.invokeIpc("resolve_rtc_peer_connection_records",{id:e});return (Array.isArray(t)?t:[]).map(i=>l(i))}return this.fallback.resolvePeerConnectionRecords(e)}async resolvePeerIdentity(e){if(await this.shouldUseTauriSignaling()){let t=await this.invokeIpc("resolve_rtc_peer_identity",{id:e});return m(t)}return this.fallback.resolvePeerIdentity(e)}async setOffline(e){return this.assertManagedCoordinationGateway(),this.fallback.setOffline(e)}async updateDevice(e,t){return this.assertManagedCoordinationGateway(),await this.syncCoordinationDeviceIdentity(),this.fallback.updateDevice(e,t)}async deleteDevice(e){return this.assertManagedCoordinationGateway(),await this.syncCoordinationDeviceIdentity(),this.fallback.deleteDevice(e)}async getLocalDeviceInfo(){if(!await this.canUseTauriIpc()){let e=await this.getLocalDeviceId?.();return e?{deviceId:e,deviceName:this.defaultDeviceNameFallback(),platformType:this.inferNativePlatformTypeFallback()}:null}try{let e=await this.invokeIpc("get_rtc_local_device_info"),t=this.decodeNativeDeviceIdentity(e),{deviceId:i}=t;return i?{deviceId:i,deviceName:this.normalizeNativeDeviceName(t.deviceName),platformType:t.platformType||this.inferNativePlatformTypeFallback(),capabilities:e?.capabilities??void 0,lastSeenAt:typeof e?.last_seen_at=="string"?e.last_seen_at:void 0}:null}catch(e){return console.warn("[NativeIpcBridge] getLocalDeviceInfo failed:",e),null}}async updateLocalDeviceName(e){if(!await this.canUseTauriIpc())return null;try{let t=await this.invokeIpc("update_rtc_local_device_name",{deviceName:e}),i=this.decodeNativeDeviceIdentity(t),{deviceId:a}=i;return a?(this.cachedLocalDeviceName=this.normalizeNativeDeviceName(e),{deviceId:a,deviceName:this.cachedLocalDeviceName,platformType:i.platformType||this.inferNativePlatformTypeFallback(),capabilities:t?.capabilities??void 0,lastSeenAt:typeof t?.last_seen_at=="string"?t.last_seen_at:void 0}):null}catch(t){return console.warn("[NativeIpcBridge] updateLocalDeviceName failed:",t),null}}async startManagedSessionNative(e){if(this.assertManagedCoordinationGateway(),!await this.shouldUseTauriSignaling())throw new Error("[pluto-rtc] Native IPC unavailable for startManagedSessionNative().");if(!await this.ensureNativeAuth("startManagedSessionNative",{requireToken:this.requiresNativeAuthToken(),maxWaitMs:this.nativeAuthWaitMs()}))throw new Error("Native auth token unavailable for startManagedSessionNative");let i=this.resolveNativeSignalingUserId(e.userId);if(!i)throw new Error("Native managed session startup requires a runtime auth-scoped user id.");i!==e.userId&&console.info("[NativeIpcBridge][managed-session][user-id-remap]",{requestedUserId:e.userId,runtimeUserId:this.currentUser?.id??this.getAuthContext()?.userId??null,effectiveUserId:i}),console.info("[NativeIpcBridge][managed-session][start-request]",{requestedUserId:e.userId,runtimeUserId:this.currentUser?.id??this.getAuthContext()?.userId??null,effectiveUserId:i,deviceName:e.deviceName??null,localDeviceId:e.localDeviceId??null,presence:e.presence!==false,autoConnect:e.autoConnect!==false,hasMetadata:typeof e.metadata=="string"&&e.metadata.trim().length>0});let a=await this.buildNativeTransportConfigPayload(),n={userId:i,deviceName:e.deviceName??null,localDeviceId:e.localDeviceId??null,metadata:e.metadata??null,...a?{transports:a}:{},autoConnect:false,presence:false},s=await this.invokeIpc("start_rtc_managed_session",n,{timeoutMs:null});this.syncNativeRuntimeCapabilities("managed-session-started");let o=typeof s?.ticket=="string"&&s.ticket.trim().length>0?s.ticket.trim():null,c=s?.localDevice&&typeof s.localDevice=="object"?s.localDevice:s?.local_device&&typeof s.local_device=="object"?s.local_device:null,d=c?{deviceId:typeof c.deviceId=="string"?c.deviceId:typeof c.device_id=="string"?c.device_id:"",deviceName:this.normalizeNativeDeviceName(typeof c.deviceName=="string"?c.deviceName:typeof c.device_name=="string"?c.device_name:""),platformType:typeof c.platformType=="string"?c.platformType:typeof c.platform_type=="string"?c.platform_type:"desktop",capabilities:c.capabilities??void 0,lastSeenAt:typeof c.lastSeenAt=="string"?c.lastSeenAt:typeof c.last_seen_at=="string"?c.last_seen_at:void 0}:null,r={localNodeId:typeof s?.localNodeId=="string"?s.localNodeId:typeof s?.local_node_id=="string"?s.local_node_id:null,ticket:o,ticketScope:typeof s?.ticketScope=="string"?s.ticketScope:typeof s?.ticket_scope=="string"?s.ticket_scope:null,presenceStarted:typeof s?.presenceStarted=="boolean"?s.presenceStarted:!!s?.presence_started,autoConnectStarted:typeof s?.autoConnectStarted=="boolean"?s.autoConnectStarted:!!s?.auto_connect_started,localDevice:d?.deviceId?d:null};if(this.usesCoordinationGateway()){e.presence!==false&&!r.ticket&&(r.ticket=await this.getEndpointTicketWithToken("user-device",0),r.ticketScope=r.ticket?"user-device":null);let l=r.localDevice?.deviceId||e.localDeviceId?.trim()||await this.resolveLocalDeviceId();if(l&&this.fallback.setCoordinationLocalDeviceId(l),this.fallback.setCoordinationPlatformType(this.normalizeNativeCoordinationPlatform(r.localDevice?.platformType)),e.presence!==false){if(!r.localNodeId||!r.ticket)throw new Error("Native managed session did not return the node identity required for gateway presence.");await this.fallback.updatePresence(r.localNodeId,r.ticket,true,3e5,e.metadata,r.localDevice?.deviceName||e.deviceName),r.presenceStarted=true;}else r.presenceStarted=false;e.autoConnect!==false&&l?(await this.startGatewayAutoConnect(i,l),r.autoConnectStarted=true):r.autoConnectStarted=false;}return console.info("[NativeIpcBridge][managed-session][ipc-started]",{requestedUserId:e.userId,runtimeUserId:this.currentUser?.id??this.getAuthContext()?.userId??null,effectiveUserId:i,localNodeId:r.localNodeId,ticketScope:r.ticketScope,presenceStarted:r.presenceStarted,autoConnectStarted:r.autoConnectStarted,localDeviceId:r.localDevice?.deviceId??null}),r}async reconcileNativeManagedSession(e){return this.assertManagedCoordinationGateway(),await this.fallback.reconnectCoordinationAfterHostResume(),console.info("[NativeIpcBridge] reattached gateway coordination after host resume.",{reason:e?.reason??"frontend"}),null}async notifyNetworkChange(e){return await this.canUseTauriIpc()?(c$1("[NativeIpcBridge] forwarding host network-change hint",{reason:e?.reason??"host"}),this.invokeIpc("notify_rtc_network_change")):null}async getManagedNodeId(e){let t=e?.initializeIfMissing??true;console.info("[NativeIpcBridge][getManagedNodeId] enter",{initializeIfMissing:t});let i=await this.canUseTauriIpc();if(console.info("[NativeIpcBridge][getManagedNodeId] canUseTauriIpc",{canUse:i}),!i)return null;try{console.info("[NativeIpcBridge][getManagedNodeId] invoking get_iroh_node_id");let a=await this.invokeIpc("get_iroh_node_id");if(console.info("[NativeIpcBridge][getManagedNodeId] get_iroh_node_id returned",{existing:a}),a||!t)return a;console.info("[NativeIpcBridge][getManagedNodeId] invoking start_iroh_node");let n=await this.invokeIpc("start_iroh_node");return console.info("[NativeIpcBridge][getManagedNodeId] start_iroh_node returned",{started:n}),n}catch(a){if(console.warn("[NativeIpcBridge] getManagedNodeId failed:",a),!t)return null;throw a}}async getEndpointTicket(){if(!await this.canUseTauriIpc())throw new Error("[pluto-rtc] getEndpointTicket requires native IPC in Tauri runtime.");return E(()=>this.invokeIpc("get_iroh_endpoint_ticket"))}async connectToDevice(e){if(!await this.canUseTauriIpc())throw new Error("[pluto-rtc] connectToDevice requires native IPC in Tauri runtime.");this.options.authMode!=="anonymous"?await this.ensureNativeAuth("connectToDevice",{requireToken:true,maxWaitMs:h.AUTH_REQUIRED_WAIT_MS}):c$1("[NativeIpcBridge] connectToDevice using anonymous native ticket path");let t=Math.max(1,Math.floor(e.timeoutMs??h.DEFAULT_BOUNDED_IPC_TIMEOUT_MS));return this.invokeIpc("connect_to_device",{deviceId:e.deviceId??null,endpointTicket:e.endpointTicket,timeoutMs:t},{timeoutMs:t+1e3})}async registerSessionToken(e,t,i){await this.canUseTauriIpc()&&await this.invokeIpc("register_session_token",{token:e,scope:t,maxConnections:i});}async getEndpointTicketWithToken(e,t){if(!await this.canUseTauriIpc())return null;try{return await E(()=>this.invokeIpc("get_endpoint_ticket_with_token",{scope:e,maxConnections:t}))}catch{return null}}async validateSessionToken(e,t){if(!await this.canUseTauriIpc())return null;try{return await this.invokeIpc("validate_session_token",{token:e,connectionId:t??null})}catch{return null}}async revokeSessionTokensByScope(e){if(g("NativeIpcBridge.revokeSessionTokensByScope",{grantScope:e}),!await this.canUseTauriIpc())return [];try{return await this.invokeIpc("revoke_session_tokens_by_scope",{scope:e})}catch{return []}}async disconnectDevice(e){if(!await this.canUseTauriIpc())throw new Error("[pluto-rtc] disconnectDevice requires native IPC in Tauri runtime.");await this.invokeIpc("disconnect_device",{deviceId:e});}async setAutoConnectExcluded(e,t){if(!await this.canUseTauriIpc())return;let i=e.trim().toLowerCase();i&&(this.usesCoordinationGateway()&&(t?this.gatewayExcludedPeers.add(i):this.gatewayExcludedPeers.delete(i)),await this.invokeIpc(this.usesCoordinationGateway()?"set_rtc_external_auto_connect_excluded":"set_auto_connect_excluded",{deviceId:e,excluded:t}),this.usesCoordinationGateway()&&await this.fallback.setCoordinationExcludedPeers([...this.gatewayExcludedPeers].sort()));}onDevicesChange(e,t){return this.assertManagedCoordinationGateway(),this.fallback.onDevicesChange(e,t)}async subscribeDevices(e){return this.assertManagedCoordinationGateway(),this.fallback.subscribeDevices(e)}async subscribeSessions(e){return this.assertManagedCoordinationGateway(),this.fallback.subscribeSessions(e)}async getLocalDeviceId(){return this.resolveLocalDeviceId()}async updatePresence(e,t,i=true,a=3e5,n){return this.assertManagedCoordinationGateway(),await this.syncCoordinationDeviceIdentity(),this.fallback.updatePresence(e,t,i,a,n)}startAutoConnect(e,t){this.assertManagedCoordinationGateway(),this.startGatewayAutoConnect(e,t).catch(i=>{console.warn("[NativeIpcBridge] gateway auto-connect failed:",i);});}forceReconnectSnapshot(){this.assertManagedCoordinationGateway(),this.fallback.forceReconnectSnapshot();}startPresenceLoop(e,t,i,a,n){this.assertManagedCoordinationGateway(),this.syncCoordinationDeviceIdentity().then(()=>this.fallback.startPresenceLoop(e,t,i,a,n)).catch(s=>{console.warn("[NativeIpcBridge] gateway presence failed:",s);});}async startAutoConnectOnce(e,t){this.assertManagedCoordinationGateway(),await this.startGatewayAutoConnect(e,t);}async clearGatewayDesiredPeerRelay(){let e=this.gatewayDesiredPeerSubmission;this.gatewayDesiredPeerRelayGeneration+=1,this.gatewayDesiredPeersCleanup?.(),this.gatewayDesiredPeersCleanup=null,this.gatewayDesiredPeerRelayKey=null,this.gatewayDesiredPeerRevision=0,this.gatewayDesiredPeerSubmission=Promise.resolve(),await e;}serializeGatewayDesiredPeerLifecycle(e){let t=this.gatewayDesiredPeerLifecycle.then(e);return this.gatewayDesiredPeerLifecycle=t.catch(()=>{}),t}stopGatewayDesiredPeerRelay(){return this.serializeGatewayDesiredPeerLifecycle(async()=>{await this.clearGatewayDesiredPeerRelay();})}startGatewayAutoConnect(e,t){return this.serializeGatewayDesiredPeerLifecycle(()=>this.startGatewayAutoConnectSerialized(e,t))}async startGatewayAutoConnectSerialized(e,t){if(!await this.shouldUseTauriSignaling())throw new Error("[openrtc] Native IPC unavailable for coordination gateway auto-connect.");if(!await this.ensureNativeAuth("startGatewayAutoConnect",{requireToken:this.requiresNativeAuthToken(),maxWaitMs:this.nativeAuthWaitMs()}))throw new Error("Native auth token unavailable for coordination gateway auto-connect");let a=this.resolveNativeSignalingUserId(e);if(!a)throw new Error("Coordination gateway auto-connect requires an authenticated user id.");let n=await this.resolveLocalDeviceId()||t.trim();if(!n)throw new Error("Coordination gateway auto-connect requires a local device id.");let s=JSON.stringify([a,n]);this.fallback.setCoordinationLocalDeviceId(n);let o=this.gatewayDesiredPeerRelayKey===s&&this.gatewayDesiredPeersCleanup;if(o||(await this.clearGatewayDesiredPeerRelay(),this.gatewayDesiredPeerRelayKey=s),await this.invokeIpc("start_rtc_external_auto_connect",{userId:a,localDeviceId:n}),o)return;let c=this.gatewayDesiredPeerRelayGeneration;this.gatewayDesiredPeersCleanup=this.fallback.onDevicesChange(d=>{let r=d.map(u=>({deviceId:String(u.deviceId??"").trim(),nodeId:typeof u.nodeId=="string"&&u.nodeId.trim()||null,ticket:typeof u.ticket=="string"&&u.ticket.trim()||null,online:u.online===true,sessionId:typeof u.sessionId=="string"&&u.sessionId.trim()||null,excludedPeers:Array.isArray(u.excludedPeers)?[...new Set(u.excludedPeers.map(I=>String(I??"").trim().toLowerCase()).filter(Boolean))].sort():[]})).filter(u=>u.deviceId.length>0&&u.deviceId!==n).sort((u,I)=>u.deviceId.localeCompare(I.deviceId)),l=++this.gatewayDesiredPeerRevision;this.gatewayDesiredPeerSubmission=this.gatewayDesiredPeerSubmission.then(async()=>{this.gatewayDesiredPeerRelayGeneration!==c||this.gatewayDesiredPeerRelayKey!==s||await this.invokeIpc("submit_rtc_desired_peers",{revision:l,peersJson:JSON.stringify(r)});}).catch(u=>{console.warn("[NativeIpcBridge] failed to relay gateway desired peers to Rust:",{revision:l,error:u});});},n);}async startPresenceLoopOnce(e,t,i,a,n){this.assertManagedCoordinationGateway(),await this.syncCoordinationDeviceIdentity(),await this.fallback.startPresenceLoop(e,t,i,a,n);}shouldUseResolvedDeviceName(e){let t=e.trim();return t.length===0||t==="Unknown Device"||t==="Desktop Device"}async sendExplicitFilePath(e,t,i=""){if(c$1("[NativeIpcBridge] sendExplicitFilePath start",{connectionId:e,filePath:t,transferId:i||null,authMode:this.options.authMode}),await this.canUseTauriIpc()){this.options.authMode!=="anonymous"?await this.ensureNativeAuth("sendExplicitFilePath"):c$1("[NativeIpcBridge] sendExplicitFilePath using anonymous native path");let a=await this.invokeIpc("send_file",{connectionId:e,filePath:t,transferId:i});return c$1("[NativeIpcBridge] sendExplicitFilePath completed",{connectionId:e,transferId:i||null,result:a}),a}return this.fallback.sendExplicitFilePath(e,t,i)}async sendExplicitFileData(e){c$1("[NativeIpcBridge] sendExplicitFileData start",{connectionId:e.connectionId??null,connectionRemoteNodeId:e.connection?.remoteNodeId??null,remoteNodeId:e.remoteNodeId??null,transferId:e.transferId??null,fileName:e.file.name,fileSize:e.file.size,authMode:this.options.authMode});let t=e.applicationCrypto??this.options.applicationCrypto;if(await this.canUseTauriIpc()){this.options.authMode!=="anonymous"?await this.ensureNativeAuth("sendExplicitFileData"):c$1("[NativeIpcBridge] sendExplicitFileData using anonymous native path");let i=e.connectionId||e.connection?.deviceId||e.connection?.remoteNodeId||e.remoteNodeId||"";if(!i)throw new Error("sendExplicitFileData requires a settled peer identifier in native runtime");let a=new Uint8Array(await e.file.arrayBuffer());await this.invokeIpc("send_file_data",{connectionId:i,filename:e.file.name,data:Array.from(a),transferId:e.transferId}),c$1("[NativeIpcBridge] sendExplicitFileData completed",{connectionId:i,transferId:e.transferId??null,fileName:e.file.name,fileSize:e.file.size});return}return this.fallback.sendExplicitFileData({...e,applicationCrypto:t})}async getConnectionStates(){if(await this.canUseTauriIpc())try{this.options.authMode!=="anonymous"&&await this.ensureNativeAuth("getConnectionStates");let e=await this.invokeIpc("list_rtc_connection_states");return (Array.isArray(e)?e:[]).map(t=>n(t)).filter(t=>!!t)}catch(e){return b(e)?c$1("[NativeIpcBridge] native connection-state replay unavailable; continuing without replay. Install/register openrtc-tauri-plugin default permissions to enable it."):console.warn("[NativeIpcBridge] Failed to fetch native connection states:",e),[]}return []}async getConnectionState(e){let t=e.trim();if(!t||!await this.canUseTauriIpc())return null;try{return this.options.authMode!=="anonymous"&&await this.ensureNativeAuth("getConnectionState"),n(await this.invokeIpc("get_rtc_connection_state",{connectionId:t}))}catch(i){return console.warn("[NativeIpcBridge] Failed to fetch native connection state:",{connectionId:t,error:i}),null}}async onConnectionStateChange(e){let t=false,i=null,a$1=new Map,n$1=Date.now(),s=0,o=()=>{let r=i;r&&Promise.resolve(r());},c=async()=>{try{let r=await this.getConnectionStates();r.length>0&&(b$1("[NativeIpcBridge] replaying current native connection states",r.map(l=>({connectionId:l.connectionId,deviceId:l.deviceId??null,deviceIdHint:l.deviceIdHint??null,remoteNodeId:l.remoteNodeId??null,state:l.state,transportState:l.transportState??null,protocolState:l.protocolState??null,routable:l.routable??null}))),r.forEach(l=>e(l)));}catch(r){console.warn("[NativeIpcBridge] Failed to replay native connection states after event subscription:",r);}},d=async r=>{let l=(a$1.get(r)??0)+1;a$1.set(r,l);let u=await this.getConnectionState(r);if(!u||t||a$1.get(r)!==l)return;if(["closed","failed","disconnected"].includes(String(u.state??"").trim().toLowerCase())){if(await a(h.CONNECTION_TERMINAL_CONFIRMATION_MS),t||a$1.get(r)!==l)return;u=await this.getConnectionState(r)??u;}!t&&a$1.get(r)===l&&e(u);};for(;!t&&Date.now()-n$1<=h.CONNECTION_EVENT_SUBSCRIBE_WINDOW_MS;){if(s+=1,!await this.canUseTauriIpc()){await a(this.nextConnectionEventRetryDelayMs(s));continue}return i=await this.listenIpc("connection-state-changed",r=>{let l=n(r?.payload);l&&(b$1("[NativeIpcBridge] connection-state-changed trigger",{connectionId:l.connectionId}),d(l.connectionId));}),await c(),()=>{t=true,o();}}return ()=>{t=true,o();}}async onIncomingNativeMessage(e){if(!await this.canUseTauriIpc())return ()=>{};let t=await this.listenIpc("iroh://message",i=>{if(i?.payload?.data&&i.payload.streamId==="main")try{let a=new Uint8Array(i.payload.data);if(a.length<2||a[0]!==0)return;let s=a.slice(1),o=new TextDecoder().decode(s),c=JSON.parse(o);e(i.payload.connectionId,i.payload.remoteNodeId??null,c);}catch{}});return typeof t=="function"?t:()=>{}}async getTransferHistory(e=50){return await this.canUseTauriIpc()?this.invokeIpc("get_transfer_history",{limit:e}):[]}async deleteTransferJob(e){await this.canUseTauriIpc()&&await this.invokeIpc("delete_transfer_job",{jobId:e});}};h.AUTH_REQUIRED_WAIT_MS=o.nativeIpc.authRequiredWaitMs,h.DEFAULT_BOUNDED_IPC_TIMEOUT_MS=o.nativeIpc.defaultBoundedCommandTimeoutMs,h.CONNECTION_EVENT_SUBSCRIBE_WINDOW_MS=o.nativeIpc.connectionEventSubscribeWindowMs,h.CONNECTION_EVENT_RETRY_MIN_DELAY_MS=o.nativeIpc.connectionEventRetryMinDelayMs,h.CONNECTION_EVENT_RETRY_MAX_DELAY_MS=o.nativeIpc.connectionEventRetryMaxDelayMs,h.CONNECTION_TERMINAL_CONFIRMATION_MS=1500,h.TAURI_IPC_NEGATIVE_CACHE_MS=o.nativeIpc.tauriIpcNegativeCacheMs,h.NATIVE_STATUS_IPC_TIMEOUT_MS=2500;var M=h;var J=class extends a$1{constructor(e){let t=c(e.bridge,"IpcRuntimeAdapter");super(new M({...e,ipcBridge:t,allowWasmFallback:e.allowWasmFallback??false}));}};
2
- export{Y as a,k as b,j as c,ae as d,E as e,J as f};
@@ -1 +0,0 @@
1
- import {a}from'./chunk-A3IAG6EL.js';import {w}from'./chunk-YBXGNKM7.js';var n=class extends a{constructor(e){super(new w(e));}setWasmClient(e){this.unwrap().setWasmClient(e);}};export{n as a};
@@ -1 +0,0 @@
1
- import {b as b$1,a as a$2}from'./chunk-2QHDEGVX.js';import {a as a$3}from'./chunk-6TAVJ46R.js';import {b}from'./chunk-N4SX7C3W.js';import {a as a$1}from'./chunk-YQWQDTQ3.js';import {d}from'./chunk-K37WVIZL.js';import {a}from'./chunk-N26S7V4N.js';async function c(t){return a(b),b$1(await a$1(a$2(t)),"web")}c.native=function(t,a$1=d()){return a(b),b$1(a$3(a$2(t),a$1),"native")};export{c as a};
@@ -1 +0,0 @@
1
- function a(n){let e=String(n?.message??n??"").toLowerCase();return e?e.includes("__tauri_internals__")||e.includes("window is not defined")||e.includes("cannot read properties of undefined")?"runtime-unavailable":e.includes("timeout after")?"timeout":e.includes("not found")||e.includes("not allowed")||e.includes("unknown command")||e.includes("plugin not found")||e.includes("plugin:openrtc-tauri-plugin")||e.includes("plugin:openrtc")?"command-unavailable":"unknown":"unknown"}function s(n){return a(n)==="command-unavailable"}function u(n,e="native runtime"){if(!n||typeof n!="object")throw new Error(`[openrtc] ${e} requires a valid IPC bridge object.`);if(typeof n.invoke!="function")throw new Error(`[openrtc] ${e} IPC bridge is missing invoke(command, args).`);if(typeof n.listen!="function")throw new Error(`[openrtc] ${e} IPC bridge is missing listen(event, handler).`);return n}var t=null;async function l(){return t||(t=(async()=>{let n="openrtc-tauri",e="../../../tauri/src/runtime/ipc";try{return await import(n)}catch(r){try{return await import(e)}catch(i){let o=new Error("[openrtc] Native support now lives in the first-party `openrtc-tauri` package. Install `openrtc-tauri` (and `@tauri-apps/api`) or pass an explicit IPC bridge to OpenRTC.native(...).");throw o.cause={packageError:r,workspaceError:i},o}}})()),t}function c(){let n=null,e=async()=>(n||(n=l().then(r=>u(r.createTauriIpcBridge(),"openrtc-tauri"))),n);return {async invoke(r,i){return (await e()).invoke(r,i)},async listen(r,i){return (await e()).listen(r,i)},async isAvailable(){try{let r=await e();return typeof r.isAvailable=="function"?!!await r.isAvailable():!0}catch{return false}}}}export{a,s as b,u as c,c as d};
@@ -1 +0,0 @@
1
- var n=null;function o(t){n=t;}function e(){if(!n)throw new Error("[OpenRTC] The rollback-only Firebase auth host is not installed. OpenRTC 2.0 applications must supply an OpenRTCAuthProvider; legacy runtimes must import openrtc/auth explicitly.");return n()}function i(){return typeof window>"u"?false:!!(window.__TAURI_IPC__||window.__TAURI_INTERNALS__||window.__TAURI__||window.location.protocol==="tauri:"||window.location.hostname==="tauri.localhost")}export{o as a,e as b,i as c};
@@ -1,2 +0,0 @@
1
- import {a as a$3}from'./chunk-BXFXPIXO.js';import {c,a as a$4}from'./chunk-N26S7V4N.js';import {a as a$2}from'./chunk-NB4H5TP3.js';import {b,a as a$1}from'./chunk-RD3JEGGF.js';import {getApps,initializeApp}from'firebase/app';import {getToken,initializeAppCheck,ReCaptchaEnterpriseProvider}from'firebase/app-check';import {getFunctions,connectFunctionsEmulator,httpsCallable}from'firebase/functions';import {browserLocalPersistence,inMemoryPersistence,browserPopupRedirectResolver,initializeAuth,getAuth,connectAuthEmulator,setPersistence,onIdTokenChanged,getIdToken,signInWithCustomToken,onAuthStateChanged,signInAnonymously,signInWithEmailAndPassword,createUserWithEmailAndPassword,signOut,deleteUser,updateProfile,GoogleAuthProvider,OAuthProvider,signInWithCredential,signInWithPopup,signInWithRedirect,getRedirectResult}from'firebase/auth';var I="pluto-rtc-auth";function le(o){return o?.DEV===true||String(o?.VITE_E2E??"").trim().toLowerCase()==="true"}function de(o=c){return o()}function he(o){if(de())return null;let e=typeof import.meta<"u"?import.meta.env:null,n=String(e?.VITE_OPENRTC_APP_CHECK_SITE_KEY??globalThis.__OPENRTC_APP_CHECK_SITE_KEY__??b.recaptchaSiteKey??"").trim(),r=String(e?.VITE_OPENRTC_APP_CHECK_MODE??globalThis.__OPENRTC_APP_CHECK_MODE__??"monitor").trim().toLowerCase();if(!n)return r==="enforce"&&console.error("[PLUTO-RTC][APP-CHECK] Enforcement requested without VITE_OPENRTC_APP_CHECK_SITE_KEY"),null;let t=String(e?.VITE_OPENRTC_APP_CHECK_DEBUG_TOKEN??"").trim();t&&!le(e)?console.error("[PLUTO-RTC][APP-CHECK] Debug tokens are allowed only in development or explicit E2E builds"):t&&typeof self<"u"&&(self.FIREBASE_APPCHECK_DEBUG_TOKEN=t==="true"?true:t);try{return initializeAppCheck(o,{provider:new ReCaptchaEnterpriseProvider(n),isTokenAutoRefreshEnabled:!0})}catch(s){let i=s instanceof Error?s.message:String(s);return i.toLowerCase().includes("already exists")||console.warn("[PLUTO-RTC][APP-CHECK] Initialization failed",{message:i}),null}}var k=null;function Te(){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 a(o,e){if(Te()){if(typeof e>"u"){console.log(o);return}console.log(o,e);}}function Ee(o){k=o;}function pe(){return c()}function L(){return typeof navigator>"u"?false:/iPhone|iPad|iPod|Android/i.test(navigator.userAgent||"")}function E(){return pe()&&L()}function u(o,e,n){return a$3(o,e,()=>new Error(`${n} timeout after ${e}ms`))}function H(o){let e="0123456789ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvwxyz-._",n=new Uint8Array(o);window.crypto.getRandomValues(n);let r="";for(let t=0;t<o;t+=1)r+=e[n[t]%e.length];return r}async function _(o){let n=new TextEncoder().encode(o),r=await crypto.subtle.digest("SHA-256",n);return Array.from(new Uint8Array(r)).map(s=>s.toString(16).padStart(2,"0")).join("")}var P=class{constructor(){this.redirectResultPromise=null;this.redirectResultConsumed=false;this.lastRelayedToken=null;this.lastRelayedRefreshToken=null;let e=getApps().find(t=>t.name===I);this.app=e||initializeApp(b,I),this.appCheck=he(this.app);let n=L(),r=E();if(n)try{let t=r?{persistence:[browserLocalPersistence,inMemoryPersistence]}:{persistence:[browserLocalPersistence,inMemoryPersistence],popupRedirectResolver:browserPopupRedirectResolver};this.auth=initializeAuth(this.app,t),a("[PLUTO-RTC][AUTH-HOST] Using mobile-safe Firebase auth initialization",{appName:this.app.name,persistence:"browserLocalPersistence->inMemoryPersistence",redirectResolver:r?"disabled-for-tauri-mobile":"browserPopupRedirectResolver",tauriMobile:r});}catch{this.auth=getAuth(this.app),console.warn("[PLUTO-RTC][AUTH-HOST] Mobile-safe auth initialization unavailable; falling back to default getAuth");}else this.auth=getAuth(this.app);this.functions=getFunctions(this.app,a$1);try{let t=typeof globalThis<"u"?String(globalThis.__OPENRTC_AUTH_EMULATOR_HOST__??"").trim():"",s=typeof globalThis<"u"?String(globalThis.__OPENRTC_FUNCTIONS_EMULATOR_HOST__??"").trim():"",i=typeof import.meta<"u"?import.meta.env:null;if(!!t||!!s||!!i&&String(i.VITE_USE_EMULATORS)==="true"&&(i.DEV||String(i.VITE_E2E)==="true")){let R=String(i?.VITE_OPENRTC_EMULATOR_HOST??"127.0.0.1").trim()||"127.0.0.1",[D,F]=t.split(":"),[W,K]=s.split(":"),M=(D??"").trim()||R,V=(W??"").trim()||R,x=Number(F??i?.VITE_OPENRTC_AUTH_EMULATOR_PORT??9100),z=Number(K??i?.VITE_OPENRTC_FUNCTIONS_EMULATOR_PORT??5002);try{connectAuthEmulator(this.auth,`http://${M}:${x}`,{disableWarnings:!0});}catch{}try{connectFunctionsEmulator(this.functions,V,z);}catch{}}}catch{}n?this.persistenceReady=Promise.resolve():this.persistenceReady=setPersistence(this.auth,browserLocalPersistence).catch(t=>{console.warn("[PLUTO-RTC][AUTH-HOST] Failed to set auth persistence",{message:t?.message});}),a("[PLUTO-RTC][AUTH-HOST] Initialized auth host",{appName:this.app.name,mobileSafeAuth:n}),onIdTokenChanged(this.auth,t=>{a("[PLUTO-RTC][AUTH-HOST] Firebase ID token changed",{hasUser:!!t,uid:t?.uid,providerDataCount:t?.providerData?.length||0}),this.syncDesktopAuthToken(t);});}async syncDesktopAuthToken(e,n=false){if(!k)return;let r=e?await getIdToken(e,n).catch(()=>null):null,t=e?e.refreshToken??null:null;if(r===this.lastRelayedToken&&t===this.lastRelayedRefreshToken)return;this.lastRelayedToken=r,this.lastRelayedRefreshToken=t;let s=await Promise.allSettled([Promise.resolve(k({authToken:r,refreshToken:t}))]);s[0]?.status==="rejected"&&console.warn("[PLUTO-RTC][AUTH-HOST] Failed to relay auth token to desktop backend",{message:s[0].reason?.message});}getApp(){return this.app}getFunctions(){return this.functions}async getAppCheckToken(e=false){if(!this.appCheck)return null;try{return (await getToken(this.appCheck,e)).token?.trim()||null}catch(n){let r=n instanceof Error?n.message:String(n);return console.warn("[PLUTO-RTC][APP-CHECK] Token acquisition failed",{message:r}),null}}getCurrentUser(){return this.auth.currentUser}getAuth(){return this.auth}onAuthStateChanged(e){return a("[PLUTO-RTC][AUTH-HOST] onAuthStateChanged listener registered (via onIdTokenChanged)"),onIdTokenChanged(this.auth,e)}onIdTokenChanged(e){return a("[PLUTO-RTC][AUTH-HOST] onIdTokenChanged listener registered"),onIdTokenChanged(this.auth,e)}async getIdToken(e){return this.auth.currentUser?getIdToken(this.auth.currentUser,e?.forceRefresh??false):null}async checkForSSOToken(){if(typeof window>"u")return;let e=new URLSearchParams(window.location.search),n=new URLSearchParams(window.location.hash.startsWith("#")?window.location.hash.slice(1):window.location.hash),r=e.get("token")||n.get("token")||(e.get("custom_token")==="true"||n.get("custom_token")==="true"?e.get("id_token")||n.get("id_token"):null);if(r)try{await this.persistenceReady,await signInWithCustomToken(this.auth,r),window.history.replaceState({},document.title,window.location.pathname);}catch(t){console.error("[PLUTO-RTC][AUTH-HOST] SSO sign-in failed:",t);}}async signInWithCustomTokenValue(e){return await this.persistenceReady,(await signInWithCustomToken(this.auth,e)).user}async signInWithPluto(e){if(typeof window>"u")throw new Error("Pluto SSO requires a browser environment.");let n=e?.redirectUri||window.location.href,r=e?.authorizeBaseUrl||"https://pluto.openrtc.app/sso/authorize",t=new URL(r);t.searchParams.set("redirect_uri",n),window.location.assign(t.toString());}async waitForAuth(){if(await this.persistenceReady,!this.auth.currentUser)return new Promise(e=>{let n=onAuthStateChanged(this.auth,r=>{r&&(n(),e());});})}async signInAnonymously(){await signInAnonymously(this.auth);}async signIn(e,n){return (await signInWithEmailAndPassword(this.auth,e,n)).user}async signUp(e,n){return (await createUserWithEmailAndPassword(this.auth,e,n)).user}async signOut(){await signOut(this.auth);}async deleteAccount(){if(!this.auth.currentUser)throw new Error("No user signed in");await deleteUser(this.auth.currentUser);}async signInWithCredential(e){let n=Date.now();if(a("[PLUTO-RTC][AUTH-HOST] signInWithCredential start",{callbackId:e.callbackId,provider:e.provider,hasIdToken:!!e.idToken,hasAccessToken:!!e.accessToken,hasNonce:!!e.nonce}),e.isCustomToken){a("[PLUTO-RTC][AUTH-HOST] signInWithCredential: custom token detected, using signInWithCustomToken");try{if(E())a("[PLUTO-RTC][AUTH-HOST] Skipping authStateReady before custom token sign-in on Tauri mobile",{callbackId:e.callbackId});else {a("[PLUTO-RTC][AUTH-HOST] Awaiting authStateReady...");try{await u(this.auth.authStateReady(),5e3,"authStateReady"),a("[PLUTO-RTC][AUTH-HOST] Auth state ready, signing in with custom token...");}catch(i){console.warn("[PLUTO-RTC][AUTH-HOST] authStateReady did not resolve in time; continuing custom token sign-in",{callbackId:e.callbackId,message:i?.message});}}let s;try{s=await u(signInWithCustomToken(this.auth,e.idToken),25e3,"signInWithCustomToken (custom token path)");}catch(i){console.warn("[PLUTO-RTC][AUTH-HOST] First custom token sign-in attempt failed; retrying once",{callbackId:e.callbackId,message:i?.message,code:i?.code}),await a$2(250),s=await u(signInWithCustomToken(this.auth,e.idToken),25e3,"signInWithCustomToken (custom token path retry)");}if(a("[PLUTO-RTC][AUTH-HOST] signInWithCustomToken success",{callbackId:e.callbackId,provider:e.provider,uid:s.user?.uid,elapsedMs:Date.now()-n}),s.user&&(e.displayName||e.photoURL))try{await updateProfile(s.user,{displayName:e.displayName||s.user.displayName||void 0,photoURL:e.photoURL||s.user.photoURL||void 0});}catch(i){console.warn("[PLUTO-RTC][AUTH-HOST] Failed to update custom-token user profile",{callbackId:e.callbackId,message:i?.message});}return s.user}catch(t){throw console.error("[PLUTO-RTC][AUTH-HOST] signInWithCustomToken failed",{callbackId:e.callbackId,error:t?.message,code:t?.code,stack:t?.stack,elapsedMs:Date.now()-n}),t}}let r;e.provider==="google"?r=GoogleAuthProvider.credential(e.idToken,e.accessToken):r=new OAuthProvider("apple.com").credential({idToken:e.idToken,rawNonce:e.nonce,accessToken:e.accessToken});try{let t=await u(signInWithCredential(this.auth,r),1e4,"firebase signInWithCredential");return a("[PLUTO-RTC][AUTH-HOST] signInWithCredential success",{callbackId:e.callbackId,provider:e.provider,uid:t.user?.uid,elapsedMs:Date.now()-n}),t.user}catch(t){console.warn("[PLUTO-RTC][AUTH-HOST] signInWithCredential primary path failed; trying custom token fallback",{callbackId:e.callbackId,provider:e.provider,elapsedMs:Date.now()-n,code:t?.code,message:t?.message});let s=await u(this.mintSessionTokenFromProviderToken(e),15e3,"mintSessionTokenFromProviderToken"),i=await u(signInWithCustomToken(this.auth,s),15e3,"signInWithCustomToken");return a("[PLUTO-RTC][AUTH-HOST] signInWithCustomToken fallback success",{callbackId:e.callbackId,provider:e.provider,uid:i.user?.uid,elapsedMs:Date.now()-n}),i.user}}async mintSessionTokenFromProviderToken(e){let n=httpsCallable(this.functions,"mintSessionToken");a("[PLUTO-RTC][AUTH-HOST] mintSessionToken fallback request start",{provider:e.provider,hasIdToken:!!e.idToken,hasNonce:!!e.nonce});let t=(await n({provider:e.provider,idToken:e.idToken,nonce:e.nonce,idempotencyKey:`provider-token:${e.callbackId}`})).data?.token;if(!t)throw new Error("mintSessionToken did not return a token for provider exchange");return a("[PLUTO-RTC][AUTH-HOST] mintSessionToken fallback request success",{provider:e.provider}),t}async signInWithPopup(e){if(e==="google"){let s=new GoogleAuthProvider;s.addScope("email"),s.addScope("profile"),s.setCustomParameters({prompt:"select_account"});let i=await signInWithPopup(this.auth,s);return {idToken:await getIdToken(i.user,true),refreshToken:i.user.refreshToken}}let n=new OAuthProvider("apple.com");n.addScope("email"),n.addScope("name");let r=H(32);typeof sessionStorage<"u"&&sessionStorage.setItem("apple_auth_nonce",r),n.setCustomParameters({nonce:await _(r)});let t=await signInWithPopup(this.auth,n);return {idToken:await getIdToken(t.user,true),refreshToken:t.user.refreshToken}}async signInWithRedirect(e,n){if(e==="google"){let s=new GoogleAuthProvider;s.addScope("email"),s.addScope("profile"),s.setCustomParameters({prompt:"select_account"}),await signInWithRedirect(this.auth,s);return}let r=new OAuthProvider("apple.com");r.addScope("email"),r.addScope("name");let t=n?.nonce||H(32);typeof sessionStorage<"u"&&sessionStorage.setItem("apple_auth_nonce",t),r.setCustomParameters({nonce:await _(t)}),await signInWithRedirect(this.auth,r);}async consumeRedirectResult(){return this.redirectResultConsumed?(a("[PLUTO-RTC][AUTH-HOST] consumeRedirectResult skipped (already consumed)"),null):this.redirectResultPromise?this.redirectResultPromise:(this.redirectResultPromise=(async()=>{try{a("[PLUTO-RTC][AUTH-HOST] consumeRedirectResult start");let e=await getRedirectResult(this.auth);if(!e)return a("[PLUTO-RTC][AUTH-HOST] consumeRedirectResult: no redirect result"),{fromRedirect:!1,user:null};this.redirectResultConsumed=!0;let n=await getIdToken(e.user,!0).catch(()=>null),r=e.providerId||e.user.providerData?.[0]?.providerId||null;return a("[PLUTO-RTC][AUTH-HOST] consumeRedirectResult success",{uid:e.user.uid,providerId:r,hasIdToken:!!n}),{fromRedirect:!0,user:e.user,providerId:r,idToken:n}}finally{this.redirectResultPromise=null;}})(),this.redirectResultPromise)}async startGoogleSignIn(){await this.signInWithRedirect("google");}async startAppleSignIn(){await this.signInWithRedirect("apple");}async mintSessionToken(){let e=httpsCallable(this.functions,"mintSessionToken");if(typeof globalThis.crypto?.randomUUID!="function")throw new Error("Secure request identity is unavailable for token minting.");let r=(await e({idempotencyKey:`hosted-token:${globalThis.crypto.randomUUID()}`})).data;if(!r?.token)throw new Error("mintSessionToken did not return a token");return r.token}},f=null;function N(){return f||(f=new P),f}function He(){a$4(N);}var _e=new Proxy({},{get(o,e,n){let r=N(),t=r[e];return typeof t=="function"?t.bind(r):t}});
2
- export{Ee as a,N as b,He as c,_e as d};
@@ -1 +0,0 @@
1
- function b(e){return new Promise(t=>setTimeout(t,e))}function g(e){let t=new Uint8Array(e.byteLength);return t.set(e),t}function R(e){let t=e.reduce((i,o)=>i+o.byteLength,0),r=new Uint8Array(t),n=0;for(let i of e)r.set(i,n),n+=i.byteLength;return r}function S(e,t,r){let n=t*Math.pow(2,Math.max(0,e-1));return Math.min(r,n)}function A(e){try{let t=e;return !!t&&!!t.send&&typeof t.send.getWriter=="function"&&!!t.recv&&typeof t.recv.getReader=="function"}catch{return false}}function B(e,t,r){let n=e;if(!n)return null;try{let i=n.send,o=n.recv;if(!i||typeof i.getWriter!="function"||!o||typeof o.getReader!="function")return null;let s=typeof n.endpoint_id=="string"&&n.endpoint_id.trim().length>0?n.endpoint_id:t,d=Number.isSafeInteger(n.transport_stable_id)&&Number(n.transport_stable_id)>0?Number(n.transport_stable_id):void 0,u=Number.isSafeInteger(r)&&Number(r)>0?Number(r):void 0;if(d!==void 0&&u!==void 0&&d!==u)return null;let a=d??u;return {send:i,recv:o,endpoint_id:s,...a?{transport_stable_id:a}:{}}}catch{return null}}function h(e,t){let r={send:e.send,recv:t,endpoint_id:typeof e.endpoint_id=="string"?e.endpoint_id:"",...Number.isSafeInteger(e.transport_stable_id)&&Number(e.transport_stable_id)>0?{transport_stable_id:Number(e.transport_stable_id)}:{}};return e?.applicationCryptoWrapped===true&&(r.applicationCryptoWrapped=true),r}async function U(e,t){if(!e)return false;try{let r=e.send?.getWriter?.();if(r)try{await r.close();}catch{}finally{try{r.releaseLock();}catch{}}}catch{}try{let r=e.recv?.getReader?.();if(r)try{await r.cancel(t);}catch{}finally{try{r.releaseLock();}catch{}}}catch{}return true}function _(e,t,r={}){let n=r.context??"prependBytesToReader",i=r.traceId,o=t.byteLength===0,s=r.pendingRead??null,d=a=>r.release?.(a),u=(a,l)=>r.log?.(a,l);return new ReadableStream({async pull(a){if(!o){o=true,a.enqueue(t);return}if(s){let c=s;s=null;let y;try{y=await c;}catch(p){a.error(p),d("pending-read-error"),u("prepend-bytes:pending-read-error",{context:n,traceId:i||null,error:p?.message||String(p)});return}if(y.done){a.close(),d("pending-done");return}y.value&&a.enqueue(y.value);return}let l;try{l=await e.read();}catch(c){a.error(c),d("read-error"),u("prepend-bytes:read-error",{context:n,traceId:i||null,error:c?.message||String(c)});return}let{done:m,value:f}=l;if(m){a.close(),d("done");return}f&&a.enqueue(f);},async cancel(a){d("cancel");}})}async function w(e,t){let r=e.read(),n=t-Date.now();if(n<=0)return {status:"timeout",pendingRead:r};let i=Symbol("probe-timeout"),o,s=new Promise(d=>{o=setTimeout(()=>d(i),n);});try{let d=await Promise.race([r,s]);if(d===i)return {status:"timeout",pendingRead:r};let{done:u,value:a}=d;return u?{status:"done"}:{status:"data",value:a&&a.byteLength>0?new Uint8Array(a):new Uint8Array(0)}}finally{o&&clearTimeout(o);}}export{b as a,g as b,R as c,S as d,A as e,B as f,h as g,U as h,_ as i,w as j};
@@ -1,2 +0,0 @@
1
- var E=new Map;function O(a){let e=new Uint8Array(a),t="";for(let n of e)t+=String.fromCharCode(n);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function j(a){let e=JSON.stringify({crv:a.crv,kty:a.kty,x:a.x});return O(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(e)))}function G(){return O(crypto.getRandomValues(new Uint8Array(24)).buffer)}async function K(){return typeof indexedDB>"u"?null:new Promise((a,e)=>{let t=indexedDB.open("openrtc-v2-device-keys",1);t.onupgradeneeded=()=>{t.result.objectStoreNames.contains("keys")||t.result.createObjectStore("keys");},t.onsuccess=()=>a(t.result),t.onerror=()=>e(t.error);})}async function H(a){let e=await K().catch(()=>null);if(!e)return E.get(a)??null;try{return await new Promise((t,n)=>{let i=e.transaction("keys","readonly").objectStore("keys").get(a);i.onsuccess=()=>t(i.result??null),i.onerror=()=>n(i.error);})}finally{e.close();}}async function L(a,e){let t=await K().catch(()=>null);if(!t){E.set(a,e);return}try{await new Promise((n,i)=>{let r=t.transaction("keys","readwrite").objectStore("keys").put(e,a);r.onsuccess=()=>n(),r.onerror=()=>i(r.error);});}finally{t.close();}}async function V(a){let e=await H(a);if(e)return e;let t=await crypto.subtle.generateKey({name:"Ed25519"},false,["sign","verify"]);return await L(a,t),t}var _={async getOrCreate(a){let e=await V(a),t=await crypto.subtle.exportKey("jwk",e.publicKey),n=await j(t);return {publicKeyJwk:t,thumbprint:n,async proof(i){let r=G(),s=Math.floor(Date.now()/1e3),o=await crypto.subtle.sign({name:"Ed25519"},e.privateKey,new TextEncoder().encode(i(r,s)));return {publicKeyJwk:t,signature:O(o),nonce:r,issuedAt:s}}}}};var M={"identity.assertion.exchange":25692e-8,"identity.monthly-active-principal":110352e-9,"capability.issue":212346e-9,"device.enroll":218946e-9,"gateway.grant.issue":202146e-9,"gateway.grant.refresh":200346e-9,"security.attestation.verify":29694e-8,"room.create":388056e-9,"room.join":209946e-9,"room.leave":200346e-9,"coordination.connection.open":274614e-9,"coordination.credential.refresh":259662e-9,"coordination.presence.offline":253638e-9,"coordination.signal.send":259638e-9,"coordination.session.put":259638e-9,"coordination.session.delete":253638e-9,"coordination.usage.ingest":197088e-9};var R={controlPlane:"https://api.openrtc.app",gateway:"https://gateway.openrtc.app"},N=1440*6e4,g=class extends Error{constructor(t,n){super(t);this.status=n;this.name="OpenRTCV2HttpError";}};function U(a,e,t){return `openrtc:v2:device-certificate:${a}:${e}:${t}`}function J(a,e,t,n){try{let i=globalThis.localStorage?.getItem(U(a,e,t));if(!i)return null;let r=JSON.parse(i);if(typeof r.token!="string"||typeof r.expiresAtMs!="number"||r.expiresAtMs<=Date.now()+N)return null;let s=h(r.token);return s.typ!=="device-certificate"||s.appTag!==a||s.principalId!==e||s.deviceId!==t||s.deviceKeyThumbprint!==n||Number(s.exp)*1e3!==r.expiresAtMs?null:{token:r.token,expiresAtMs:r.expiresAtMs}}catch{return null}}function q(a,e,t,n){try{globalThis.localStorage?.setItem(U(a,e,t),JSON.stringify(n));}catch{}}function W(a){return `${a}_${crypto.randomUUID()}`}async function B(a,e){let t=new TextEncoder().encode(`${a}:${e}`);return [...new Uint8Array(await crypto.subtle.digest("SHA-256",t))].map(i=>i.toString(16).padStart(2,"0")).join("")}function h(a){let e=a.split(".")[1];if(!e)throw new Error("OpenRTC returned a malformed credential.");let t=e.replace(/-/g,"+").replace(/_/g,"/"),n=t.padEnd(Math.ceil(t.length/4)*4,"=");return JSON.parse(atob(n))}var C=class{constructor(e,t,n,i,r={},s){this.apiKey=e;this.endpoints=t;this.keyProvider=n;this.attestation=i;this.events=r;this.botVerification=s;this.keyPromise=null;this.authEpochs=new Map;this.appTag=`app_${e.slice(-16)}`;}record(e){this.events.onLogicalOperation?.(e);}before(e){this.events.beforeLogicalOperation?.(e);}authEpoch(e){let t=this.authEpochs.get(e);if(t)return t;let n={generation:0,devices:new Map};return this.authEpochs.set(e,n),e.subscribe&&(n.unsubscribe=e.subscribe(()=>{n.generation+=1,n.devices.clear(),this.events.onAuthEpochChanged?.(e);})),n}dispose(){for(let e of this.authEpochs.values())e.unsubscribe?.();this.authEpochs.clear();}key(){return this.keyPromise??(this.keyPromise=this.keyProvider.getOrCreate(this.appTag))}async post(e,t){let n=W("request"),i=JSON.stringify({apiKey:this.apiKey,...t}),r=null;for(let s=0;s<2;s+=1)try{let o=await fetch(`${this.endpoints.controlPlane}${e}`,{method:"POST",headers:{"Content-Type":"application/json","X-OpenRTC-Idempotency-Key":n},body:i,signal:AbortSignal.timeout(15e3)});if(o.ok)return o.json();let c=`OpenRTC request failed (${o.status}).`;try{let l=await o.json();typeof l.error=="string"&&(c=l.error.slice(0,256));}catch{}let d=new g(c,o.status);if(r=d,s===0&&[502,503,504].includes(o.status))continue;throw d}catch(o){if(r=o,s===0&&o instanceof TypeError)continue;throw o}throw r instanceof Error?r:new Error("OpenRTC request failed.")}async capability(e,t,n,i=false){this.before("capability.issue");let r=e==="space"?await B(this.apiKey,t):t,o=await(await this.key()).proof((u,p)=>["openrtc:v2:capability",this.apiKey,e,r,u,p].join(":")),c=this.botVerification?await this.botVerification.getToken({action:"openrtc_capability",apiKey:this.apiKey}):void 0,d=await this.post("/v2/capabilities",{avenue:{kind:e,id:r},deviceProof:o,...n?{maxPeers:n}:{},...i?{advancedFanout:true}:{},...c?{turnstileToken:c}:{}});this.record("capability.issue");let l={type:"capability",token:d.capability,avenue:e==="ticket"?{kind:"session",id:r}:d.avenue,expiresAtMs:d.expiresAt*1e3};return l.renew=()=>this.capability(e,t,n,i),l}async deviceCertificate(e,t,n){let i=this.authEpoch(e),r=i.devices.get(t)??{};if(i.devices.set(t,r),r.current&&r.current.expiresAtMs>Date.now()+N)return this.deviceCertificateResult(e,t,n,{...r.current,enrolled:false});if(!r.inFlight){let o=i.generation;r.inFlight=this.enrollAuthenticatedDevice(e,t).then(c=>{if(i.generation!==o)throw new Error("The OpenRTC authentication identity changed during enrollment.");return r.current=c,c}).finally(()=>{r.inFlight=void 0;});}let s=await r.inFlight;return this.deviceCertificateResult(e,t,n,s)}deviceCertificateResult(e,t,n,i){let r={type:"device-certificate",token:i.token,avenue:n??{kind:"user",id:i.principalId},expiresAtMs:i.expiresAtMs};return r.renew=async()=>(await this.deviceCertificate(e,t,n)).source,{principalId:i.principalId,source:r,enrolled:i.enrolled}}async enrollAuthenticatedDevice(e,t){this.before("identity.assertion.exchange"),this.before("identity.monthly-active-principal");let n=async u=>{let p=await e.getAssertion({audience:"https://api.openrtc.app/v2/assertions/exchange",forceRefresh:u});if(!p)throw new Error("The OpenRTC auth provider returned no assertion.");return this.post("/v2/assertions/exchange",{assertion:p,...e.providerId?{providerId:e.providerId}:{}})},i;try{i=await n(!1);}catch(u){if(!(u instanceof g)||u.status!==401)throw u;i=await n(true);}this.record("identity.assertion.exchange"),this.record("identity.monthly-active-principal");let r=await this.key(),s=J(this.appTag,i.principalId,t,r.thumbprint);if(s)return {...s,principalId:i.principalId,enrolled:false};this.before("device.enroll"),this.attestation&&this.before("security.attestation.verify");let o=await r.proof((u,p)=>["openrtc:v2:device-enroll",this.appTag,i.principalId,t,u,p].join(":")),c=this.attestation?{kind:this.attestation.kind,...await this.attestation.getEvidence({challenge:`openrtc:v2:attestation:${this.appTag}:${i.principalId}:${t}:${o.nonce}`,apiKey:this.apiKey})}:void 0,d=await this.post("/v2/devices/enroll",{identitySession:i.identitySession,deviceId:t,deviceProof:o,...c?{attestation:c}:{}});this.record("device.enroll"),c&&this.record("security.attestation.verify");let l={principalId:i.principalId,token:d.deviceCertificate,expiresAtMs:d.expiresAt*1e3,enrolled:true};return q(this.appTag,i.principalId,t,{token:l.token,expiresAtMs:l.expiresAtMs}),l}async durableRoomMembership(e,t,n){if(e.type!=="device-certificate")throw new Error("Durable rooms require a device certificate.");this.before(n==="join"?"room.join":"room.leave");let i=h(e.token),r=String(i.jti??""),o=await(await this.key()).proof((c,d)=>["openrtc:v2:room-membership",r,n,t,c,d].join(":"));await this.post("/v2/rooms/memberships",{action:n,roomId:t,deviceCertificate:e.token,deviceProof:o}),this.record(n==="join"?"room.join":"room.leave");}grantProvider(e,t={}){let n=null,i=e;return async r=>{if(n)return n;let s=(async()=>{let o=false;i.expiresAtMs<=Date.now()+5*6e4&&i.renew&&(i=await i.renew(),o=true);let c=r.refreshGrant?"gateway.grant.refresh":"gateway.grant.issue";this.before(c),r.refreshGrant&&this.before("coordination.credential.refresh");let d=h(i.token),l=String(d.jti??""),p=await(await this.key()).proof((v,b)=>["openrtc:v2:gateway-grant",l,r.avenue.kind,r.avenue.id,r.runtimeInstanceId,v,b].join(":")),f=await this.post("/v2/gateway/grants",{credentialType:i.type,credential:i.token,avenue:r.avenue,runtimeInstanceId:r.runtimeInstanceId,ticketFingerprint:r.ticketFingerprint,deviceProof:p,...r.refreshGrant?{refreshGrant:r.refreshGrant}:{},...t.maxPeers?{maxPeers:t.maxPeers}:{},...t.features?{features:t.features}:{}});return this.record(c),r.refreshGrant&&this.record("coordination.credential.refresh"),o&&await t.onSourceRenewed?.({token:i.token,expiresAtMs:i.expiresAtMs}),f})();n=s;try{return await s}finally{n===s&&(n=null);}}}};var P=new WeakMap;function oe(a){let e=P.get(a);if(!e)throw new Error("[OpenRTC] Capability runtime is unavailable or already closed.");return e}function z(a){let e=a?.trim()??"";if(!/^pk_(?:live|test)_[0-9a-f]{40}$/.test(e))throw new Error("[OpenRTC] apiKey must be a public pk_live_ or pk_test_ key.");return e}function y(a){let e=a?.trim()??"";if(!e||e.length>160||!/^[A-Za-z0-9_.:@-]+$/.test(e))throw new Error("[OpenRTC] Capability id is invalid.");return e}function Z(a){let e=a?.trim();if(e){if(new TextEncoder().encode(e).byteLength>4*1024)throw new Error("[OpenRTC] Device profile metadata must not exceed 4 KiB.");return e}}var F=/^[A-Za-z0-9_.:@-]{1,160}$/,X=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;function $(a){let e=typeof a=="string"?a.trim():"";if(!F.test(e))return null;let t=e.startsWith("device_")?e.slice(7):"";return X.test(t)?t:e}function Q(a,e){try{let t=a.getItem(`pluto_rtc_web_device_identity_${e}`);if(!t)return null;let n=JSON.parse(t);return $(n?.deviceId)}catch{return null}}function Y(a){let e=`openrtc:v2:device-id:${a}`,t=`pluto_rtc_web_device_identity_${a}`,n,i=(()=>{try{return n=globalThis.localStorage,n&&Q(n,a)||$(n?.getItem(e))||crypto.randomUUID()}catch{return crypto.randomUUID()}})();try{n?.setItem(e,i),n?.setItem(t,JSON.stringify({deviceId:i}));}catch{}return i}function ee(a){let e=typeof a=="string"?a.trim():"";if(!F.test(e))throw new Error("[OpenRTC] The native host returned an invalid durable device ID.");return e}function T(a){let e=h(a.token),t=typeof e.deviceKeyThumbprint=="string"?e.deviceKeyThumbprint.trim():"";if(!/^[A-Za-z0-9_-]{43}$/.test(t))throw new Error("[OpenRTC] Anonymous capability is missing its device-key binding.");return `anon_${t.slice(0,32)}`}var k=class{constructor(){this.descriptors=new Map;this.targets=new Map;}register(e){if(!e?.id?.trim())throw new Error("[OpenRTC] Channel id is required.");this.descriptors.set(e.id,{...e});for(let[t,n]of this.targets)t.channels.register({...e,delivery:e.delivery??n});return ()=>{this.descriptors.delete(e.id);for(let t of this.targets.keys())t.channels.unregister(e.id);}}list(){return [...this.descriptors.values()].map(e=>({...e}))}attach(e,t){this.targets.set(e,t);for(let n of this.descriptors.values())e.channels.register({...n,delivery:n.delivery??t});}detach(e){this.targets.delete(e);}},I=class{constructor(e){this.options=e;this.total=0;this.warned=false;}get sessionCreditsUsd(){return this.total}estimate(e){let t=Math.max(0,Math.floor(e.units??1));return {creditsUsd:(M[e.operation]??0)*t,estimated:true}}assertCanSpend(e,t=1){let n=this.options?.maxSessionCreditsUsd;if(n===void 0||this.total+this.estimate({operation:e,units:t}).creditsUsd<=n)return;let r={sessionCreditsUsd:this.total,operation:e,estimated:true,thresholdCreditsUsd:n,kind:"session-limit"};throw this.options?.onWarning?.(r),new Error("[OpenRTC] The client-side session credit limit was reached.")}record(e,t=1){let n=this.estimate({operation:e,units:t}).creditsUsd;this.total+=n;let i={sessionCreditsUsd:this.total,operation:e,estimated:true};this.options?.onUsage?.(i);let r=this.options?.warnAtSessionCreditsUsd;!this.warned&&r!==void 0&&this.total>=r&&(this.warned=true,this.options?.onWarning?.({...i,thresholdCreditsUsd:r,kind:"warning"}));}},m=class{constructor(e,t,n,i){this.kind=e;this.id=t;this.client=n;this.onClosed=i;this.closed=false;P.set(this,n);}get peers(){return this.client.peers}get channels(){return this.client.channels}get diagnostics(){return this.client.diagnostics}async close(){if(!this.closed){this.closed=true;try{await this.client.advanced.runtime.shutdown();}finally{P.delete(this),this.onClosed();}}}},x=class extends m{constructor(t,n,i){super("devices",t,n,i);this.kind="devices";this.localId=()=>this.client.devices.localId();this.localInfo=()=>this.client.devices.localInfo();this.list=()=>this.client.devices.list();this.listWithStatus=()=>this.client.devices.listWithStatus();this.watch=this.client.devices.watch;this.connect=this.client.devices.connect;this.disconnect=this.client.devices.disconnect;}},A=class extends m{constructor(t,n,i,r){super("space",t,n,i);this.delivery=r;this.kind="space";this.leave=()=>this.close();}},w=class extends m{constructor(t,n,i,r,s){super("room",t,n,i);this.membership=r;this.onLeave=s;this.kind="room";this.left=false;}async leave(){this.left||(this.left=true,await this.onLeave?.()),await this.close();}},S=class extends m{constructor(t,n,i,r){super("ticket",t,n,i);this.token=r;this.kind="ticket";}},D=class{constructor(e,t){this.options=e;this.internals=t;this.channels=new k;this.handles=new Set;this.activations=new Map;this.closed=false;this.devices={start:(e={})=>{let t=e.auth??this.options.auth;return this.activateOnce("devices",JSON.stringify({autoConnect:e.autoConnect??"online",maxPeers:e.maxPeers??null,advancedFanout:e.advancedFanout===true,profile:e.profile??null}),t,()=>this.startDevices(e))}};this.spaces={join:(e,t={})=>this.activateOnce(`space:${y(e)}`,JSON.stringify({payload:t.payload??"reliable",maxPeers:t.maxPeers??null,advancedFanout:t.advancedFanout===true}),void 0,()=>this.joinSpace(e,t))};this.rooms={join:(e,t={})=>{let n=t.access??"capability";return this.activateOnce(`room:${y(e)}`,JSON.stringify({access:n,membership:t.membership??"ephemeral",maxPeers:t.maxPeers??null,advancedFanout:t.advancedFanout===true}),n==="authenticated"?t.auth??this.options.auth:void 0,()=>this.joinRoom(e,t))}};this.tickets={issue:(e,t={})=>this.activateOnce(`ticket:${y(e)}`,JSON.stringify({maxPeers:t.maxPeers??null,advancedFanout:t.advancedFanout===true}),void 0,()=>this.issueTicket(e,t))};this.onClosed=e=>{this.handles.delete(e);for(let[t,n]of this.activations)n.handle===e&&this.activations.delete(t);};this.apiKey=z(e.apiKey),this.usage=new I(e.usage),this.controlPlane=new C(this.apiKey,t.endpoints??R,t.deviceKeyProvider??_,e.trust?.attestation,{beforeLogicalOperation:n=>this.usage.assertCanSpend(n),onLogicalOperation:n=>this.usage.record(n),onAuthEpochChanged:n=>this.retireAuthCapabilities(n)},e.trust?.botVerification);}assertOpen(){if(this.closed)throw new Error("[OpenRTC] Client is closed.")}activateOnce(e,t,n,i){this.assertOpen();let r=this.activations.get(e);if(r){if(r.fingerprint!==t||r.auth!==n)throw new Error(`[OpenRTC] ${e} is already active with different options.`);return r.promise}let s={fingerprint:t,auth:n},o=i().then(c=>(s.handle=c,c)).catch(c=>{throw this.activations.get(e)===s&&this.activations.delete(e),c});return s.promise=o,this.activations.set(e,s),o}retireAuthCapabilities(e){for(let t of this.activations.values())t.auth===e&&t.promise.then(n=>n.close()).catch(()=>{});}async deviceId(){let e=this.internals.deviceIdProvider?await this.internals.deviceIdProvider(this.controlPlane.appTag):Y(this.controlPlane.appTag);return ee(e)}runtimeOptions(e){let t=this.options.transports,n=t?.privacy==="relay-only";if(n&&t?.relay!==true)throw new Error("[OpenRTC] transports.privacy: relay-only requires transports.relay: true.");return {apiKey:this.apiKey,authMode:"external",discoveryMode:e.avenue?.kind==="user"?"user-scoped":"space",space:e.avenue?.id,localDeviceId:e.deviceId,deviceIdPersistence:"persistent",endpointIdPersistence:this.internals.platform==="native"?"persistent":"ephemeral",deviceName:e.deviceName?.trim()||void 0,nativeApplicationStreamConsumer:this.internals.platform==="native"&&t?.nativeHostProtocols===true?"host":"runtime",coordinationAvenueOverride:e.avenue,coordinationGateway:{endpoint:(this.internals.endpoints??R).gateway,environment:"production",grantProvider:e.grantProvider,testingAllowInsecureLoopback:this.internals.testingAllowInsecureLoopback},transports:{iroh:n?{relayOnly:true,localDiscovery:false,persistenceMode:this.internals.platform==="native"?"persistent":"ephemeral",...this.internals.irohTestRelayUrl?{testRelayUrl:this.internals.irohTestRelayUrl}:{}}:this.internals.irohTestRelayUrl?{testRelayUrl:this.internals.irohTestRelayUrl,persistenceMode:this.internals.platform==="native"?"persistent":"ephemeral"}:t?.iroh??true,webrtc:t?.webrtc===true?n?{privacyMode:true,useTurn:true,useDefaultIceServers:false}:true:false,ble:t?.ble??false,moq:t?.moq??false},transportPriority:t?.priority}}async activate(e){let t={relay:this.options.transports?.relay===true,moq:this.options.transports?.moq===true,ble:this.options.transports?.ble===true,advancedFanout:e.advancedFanout===true,durableMembership:e.durableMembership===true},n=e.source,i=null,r=()=>({userId:e.principalId,token:n.token,tokenProvider:async()=>n.token,expiresAtMs:n.expiresAtMs}),s=this.runtimeOptions({avenue:e.source.avenue,grantProvider:this.controlPlane.grantProvider(e.source,{maxPeers:e.maxPeers,features:t,onSourceRenewed:async d=>{n={...n,...d},await i?.setAuth(r());}}),deviceId:e.deviceId,userId:e.principalId,deviceName:e.deviceName}),[o,{wrapAssembly:c}]=await Promise.all([this.internals.runtimeFactory(s),import('./OpenRTCShared-TKAQLONA.js')]);i=c(o,this.internals.platform==="native"?"native":"web"),await i.setAuth(r()),this.channels.attach(i,e.defaultDelivery??"reliable");try{this.usage.assertCanSpend("coordination.connection.open"),await i.devices.startSession({sessionKind:e.kind==="devices"?"app-user-device":"scoped-guest",scope:`v2:${e.kind}:${e.id}`,userId:e.principalId,localDeviceId:e.deviceId,metadata:e.deviceMetadata,autoConnectPolicy:e.autoConnect?"enabled":"disabled",presencePolicy:"online"});}catch(d){throw this.channels.detach(i),await i.advanced.runtime.shutdown().catch(()=>{}),d}return this.usage.record("coordination.connection.open"),i}async startDevices(e={}){this.assertOpen();let t=e.auth??this.options.auth;if(!t)throw new Error("[OpenRTC] devices.start() requires an auth provider.");let n=await this.deviceId(),i=await this.controlPlane.deviceCertificate(t,n),r=await this.activate({kind:"devices",id:i.principalId,source:i.source,principalId:i.principalId,deviceId:n,maxPeers:e.maxPeers,autoConnect:e.autoConnect!=="none",advancedFanout:e.advancedFanout,deviceName:e.profile?.name,deviceMetadata:Z(e.profile?.metadata)}),s;return s=new x(i.principalId,r,()=>{this.channels.detach(r),this.onClosed(s);}),this.handles.add(s),s}async joinSpace(e,t={}){this.assertOpen();let n=y(e),i=await this.controlPlane.capability("space",n,t.maxPeers,t.advancedFanout),r=String(h(i.token).principalId),s=await this.activate({kind:"space",id:n,source:i,principalId:r,deviceId:T(i),maxPeers:t.maxPeers,autoConnect:true,defaultDelivery:t.payload??"reliable",advancedFanout:t.advancedFanout}),o;return o=new A(n,s,()=>{this.channels.detach(s),this.onClosed(o);},t.payload??"reliable"),this.handles.add(o),o}async joinRoom(e,t={}){this.assertOpen();let n=y(e),i=t.membership??"ephemeral",r=t.access??"capability";if(i==="durable"&&r!=="authenticated")throw new Error("[OpenRTC] Durable room membership requires access: authenticated.");if(r==="authenticated"){let l=t.auth??this.options.auth;if(!l)throw new Error("[OpenRTC] Authenticated rooms require an auth provider.");let u=await this.deviceId(),p=await this.controlPlane.deviceCertificate(l,u,{kind:"room",id:n});i==="durable"&&await this.controlPlane.durableRoomMembership(p.source,n,"join");let f;try{f=await this.activate({kind:"room",id:n,source:p.source,principalId:p.principalId,deviceId:u,maxPeers:t.maxPeers,autoConnect:!0,durableMembership:i==="durable",advancedFanout:t.advancedFanout});}catch(b){throw i==="durable"&&await this.controlPlane.durableRoomMembership(p.source,n,"leave").catch(()=>{}),b}let v;return v=new w(n,f,()=>{this.channels.detach(f),this.onClosed(v);},i,i==="durable"?async()=>{await this.controlPlane.durableRoomMembership(p.source,n,"leave");}:void 0),this.handles.add(v),v}let s=await this.controlPlane.capability("room",n,t.maxPeers,t.advancedFanout),o=String(h(s.token).principalId),c=await this.activate({kind:"room",id:n,source:s,principalId:o,deviceId:T(s),maxPeers:t.maxPeers,autoConnect:true,advancedFanout:t.advancedFanout}),d;return d=new w(n,c,()=>{this.channels.detach(c),this.onClosed(d);},"ephemeral"),this.handles.add(d),d}async issueTicket(e,t={}){this.assertOpen();let n=y(e),i=await this.controlPlane.capability("ticket",n,t.maxPeers,t.advancedFanout),r=String(h(i.token).principalId),s=await this.activate({kind:"ticket",id:n,source:i,principalId:r,deviceId:T(i),maxPeers:t.maxPeers,autoConnect:false,advancedFanout:t.advancedFanout}),o;return o=new S(n,s,()=>{this.channels.detach(s),this.onClosed(o);},i.token),this.handles.add(o),o}async close(){if(!this.closed){this.closed=true;try{await Promise.all([...this.handles].map(e=>e.close()));}finally{this.controlPlane.dispose(),this.activations.clear();}}}};function ce(a,e){return new D(a,e)}
2
- export{j as a,oe as b,ce as c};
@@ -1,2 +0,0 @@
1
- import {a}from'./chunk-PODAMIL6.js';function s(){let t=crypto.getRandomValues(new Uint8Array(24)),e="";for(let r of t)e+=String.fromCharCode(r);return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function u(t){if(!t||typeof t!="object")throw new Error("[OpenRTC] Native host returned no device public key.");let e=t;if(e.kty!=="OKP"||e.crv!=="Ed25519"||typeof e.x!="string"||!/^[A-Za-z0-9_-]{43}$/.test(e.x)||e.d!==void 0)throw new Error("[OpenRTC] Native host returned an invalid Ed25519 public key.");return {kty:"OKP",crv:"Ed25519",x:e.x}}function y(t){return {async getOrCreate(e){let r=u(await t.invoke("openrtc_v2_device_public_key",{appTag:e})),a$1=await a(r);return {publicKeyJwk:r,thumbprint:a$1,async proof(p){let n=s(),o=Math.floor(Date.now()/1e3),i=await t.invoke("openrtc_v2_sign_device_proof",{appTag:e,challenge:p(n,o)});if(!/^[A-Za-z0-9_-]{80,128}$/.test(i))throw new Error("[OpenRTC] Native host returned an invalid device proof.");return {publicKeyJwk:r,signature:i,nonce:n,issuedAt:o}}}}}}
2
- export{y as a};
@@ -1 +0,0 @@
1
- import {c}from'./chunk-NB4H5TP3.js';import {b,e}from'./chunk-C7YN5MSV.js';import {xchacha20poly1305}from'@noble/ciphers/chacha.js';function v(){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 R(t,e,r){if(v()){if(typeof r>"u"){console[t](e);return}console[t](e,r);}}function M(t,e){R("debug",t,e);}function $(t,e){R("info",t,e);}function G(t,e){R("log",t,e);}var N=b,I=new Set(N);function g(t){if(typeof t!="string")return;let e=t.trim().toLowerCase();return I.has(e)?e:void 0}function K(t){let e$1=g(t);return e$1?e(e$1).baseProtocol==="iroh":false}function Q(t){let e$1=g(t);if(!e$1)return false;let r=e(e$1);return r.baseProtocol==="iroh"&&(r.locality==="nearby"||r.locality==="direct-internet")}function j(t){let e$1=g(t);return e$1?e(e$1).family==="optional-route":false}function J(t){let e$1=g(t);return e$1?e(e$1).baseProtocol==="webrtc":false}function Z(t,e,r=false){return t==="relay"||e==="relay"?"webrtc-turn":t==="host"&&e==="host"||r&&t&&e?"webrtc-lan":"webrtc"}function ee(t){let e$1=g(t);return e$1?e(e$1).independentlyInstantiable:false}var u=new Uint8Array([79,82,84,67,69,49]),U=2,d=8,h=24,_=32,k=3,F=16*1024*1024,D=4096;function q(t,e){if(t.byteLength<e.byteLength)return false;let r=0;for(let a=0;a<e.byteLength;a+=1)r|=t[a]^e[a];return r===0}function V(t){let e=new Uint8Array(t),r=globalThis.crypto;if(!r||typeof r.getRandomValues!="function")throw new Error("[OpenRTC] application payload crypto requires crypto.getRandomValues");return r.getRandomValues(e),e}function Y(t,e){let r="";for(let a of e)r+=a.toString(16).padStart(2,"0");return `${t}:${r}`}function B(t){if(!q(t,u))return null;let e=t[u.byteLength];return e===U?e:null}function z(t){return B(t)===U&&t.byteLength>u.byteLength+1+d+h}function oe(t,e={}){if(!(t instanceof Uint8Array)||t.byteLength!==_)throw new Error(`[OpenRTC] application payload crypto key must be ${_} bytes`);let r=new Uint8Array(t),a=e.requireEncrypted??true,T=e.randomBytes??V,m=e.replayProtection??true,w=0,p=new Set,f=[];return {requireEncrypted:a,protectPayload(y,n){let i=T(h);if(!(i instanceof Uint8Array)||i.byteLength!==h)throw new Error(`[OpenRTC] application payload crypto nonce must be ${h} bytes`);let l=new Uint8Array(1+n.byteLength);l[0]=y,l.set(n,1);let c=xchacha20poly1305(r,i).encrypt(l);if(!m)throw new Error("[OpenRTC] ORTCE1 v1 envelopes are not supported; replay protection is required");let s=new Uint8Array(u.byteLength+1+d+i.byteLength+c.byteLength),o=0;s.set(u,o),o+=u.byteLength,s[o]=U,o+=1;let E=w;return w+=1,new DataView(s.buffer,s.byteOffset+o,d).setBigUint64(0,BigInt(E),false),o+=d,s.set(i,o),o+=i.byteLength,s.set(c,o),s},openPayload(y,n){if(!z(n))return a?null:n;if(B(n)!==U)return null;let l=u.byteLength+1,c=Number(new DataView(n.buffer,n.byteOffset+l,d).getBigUint64(0,false));if(!Number.isFinite(c))return null;let s=l+d,o=s+h,E=n.slice(s,o),A=m?Y(c,E):null;if(A&&p.has(A))return null;let C=n.slice(o),L;try{L=xchacha20poly1305(r,E).decrypt(C);}catch{return null}if(L.byteLength<1||L[0]!==y)return null;if(A)for(p.add(A),f.push(A);f.length>D;){let P=f.shift();P&&p.delete(P);}return L.slice(1)}}}function W(t){let e=new Uint8Array(4+t.byteLength);return new DataView(e.buffer,e.byteOffset,e.byteLength).setUint32(0,t.byteLength,false),e.set(t,4),e}function ie(t,e={}){let r=e.typeId??k,a=e.maxFrameBytes??F;if(!Number.isInteger(r)||r<0||r>255)throw new Error("[OpenRTC] raw application crypto stream typeId must be an integer from 0 to 255");if(!Number.isInteger(a)||a<=0)throw new Error("[OpenRTC] raw application crypto maxFrameBytes must be a positive integer");let T=n=>t.protectPayload(r,n),m=n=>t.openPayload(r,n),w=()=>new TransformStream({transform(n,i){i.enqueue(W(T(new Uint8Array(n))));}}),p=()=>{let n=new Uint8Array(0);return new TransformStream({transform(i,l){for(n=c([n,new Uint8Array(i)]);n.byteLength>=4;){let c=new DataView(n.buffer,n.byteOffset,n.byteLength).getUint32(0,false);if(c===0||c>a)throw new Error("[OpenRTC] invalid encrypted raw stream frame length");if(n.byteLength<4+c)return;let s=n.slice(4,4+c);n=n.slice(4+c);let o=m(s);if(!o)throw new Error("[OpenRTC] encrypted raw stream frame failed authentication");l.enqueue(o);}},flush(){if(n.byteLength!==0)throw new Error("[OpenRTC] encrypted raw stream ended mid-frame")}})},f=n=>n.pipeThrough(p()),y=n=>{let i=w();return i.readable.pipeTo(n).catch(()=>{}),i.writable};return {typeId:r,protectFrame:T,openFrame:m,createOutboundTransform:w,createInboundTransform:p,wrapReadable:f,wrapWritable:y,wrapBiStream(n){return {...n,send:y(n.send),recv:f(n.recv)}}}}export{v as a,M as b,$ as c,G as d,N as e,g as f,K as g,Q as h,j as i,J as j,Z as k,ee as l,z as m,oe as n,ie as o};
@@ -1,2 +0,0 @@
1
- import {b as b$2,c as c$1,l,o,f as f$1}from'./chunk-VK6KX433.js';import {c as c$2,a as a$1,e as e$1}from'./chunk-NT5YHZQH.js';import {b as b$1,c}from'./chunk-N26S7V4N.js';import {b,a,d as d$1}from'./chunk-NB4H5TP3.js';import {e,g as g$1,f,h,d}from'./chunk-RD3JEGGF.js';import*as U from'tweetnacl';var et=3e4,tt=5*6e4,nt=3e4,it=12,re=15e3,rt=15e3,ot=1e3,Pe=250,st="openrtc.v1",at="openrtc.auth.",g=class extends Error{constructor(t,i){super(t);this.retryable=i;this.name="CoordinationConnectError";this.code=a$1.COORDINATION_DISCONNECTED;this.plane="coordination";}},V=class extends Error{constructor(t,i,r){let o=e$1({code:t,message:i,retryable:r});super(`Coordination gateway ${t}: ${i}`);this.name="CoordinationGatewayProtocolError";this.code=o.code||t||a$1.COORDINATION_PROTOCOL,this.retryable=r,this.plane=o.plane;}};function Ae(n){return n instanceof g&&/\bstale-budget\b/i.test(n.message)}function Ee(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 ct(n){let e=new Uint32Array(1);return crypto.getRandomValues(e),Math.max(1,Math.round(n*(.75+e[0]/4294967295*.5)))}function C(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 dt(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 lt(n,e,t){let i=new URL(n);if(i.search||i.hash||i.username||i.password)throw new Error("[OpenRTC] Coordination gateway endpoint must not contain credentials, query, or fragment.");if(i.protocol==="https:")i.protocol="wss:";else if(i.protocol==="http:")i.protocol="ws:";else if(i.protocol!=="wss:"&&i.protocol!=="ws:")throw new Error("[OpenRTC] Coordination gateway endpoint must use HTTPS/WSS.");return i.pathname=`${i.pathname.replace(/\/+$/,"")}/v${t}/connect/${e}`,i.toString()}function _e(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 ke(n,e,t){return `${ut(n,e)}/${encodeURIComponent(t)}`}async function Me(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 J=class n{constructor(e){this.options=e;this.runtimeInstanceId=C("runtime");this.socket=null;this.socketReady=false;this.activeGrantToken=null;this.activeGrantProtocolVersion=1;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.connectionReadyWaiters=new Set;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:",o=e.gateway.testingAllowInsecureLoopback===true&&i&&(t.protocol==="http:"||t.protocol==="ws:");if(!r&&!o)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 d=this.desiredPresenceRevision;await this.ensureConnected(),!(this.appliedPresenceRevision>=d)&&(a&&a.ticket!==t&&await this.refreshAuthentication(),await this.sendOperation({v:1,type:"presence.upsert",idempotencyKey:C("presence"),ttlMs:r,device:this.gatewayDevice(this.desiredPresence)}),this.appliedPresenceRevision=Math.max(this.appliedPresenceRevision,d));}async setOffline(e){this.desiredPresence&&(this.desiredPresence.online=false,this.socket?.readyState===WebSocket.OPEN&&await this.sendOperation({v:1,type:"presence.offline",idempotencyKey:C("offline")}));}async reconnectAfterHostResume(){if(this.desiredPresence){if(this.hostResumeReconnectPromise)return this.hostResumeReconnectPromise;if(!(Date.now()-this.lastHostResumeReconnectAtMs<rt)){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>Pe)throw new Error(`Coordination excluded-peer set exceeds ${Pe} devices.`);this.desiredExcludedPeers=r,i={...t,excludedPeers:r};}await this.ensureConnected(),await this.sendOperation({v:1,type:"device.patch",idempotencyKey:C("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:C("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:C("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:C("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=C("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(c=>{if(r.value){c.stopAuthScopedActivity();return}s.push(c.onDevicesChange(d=>{o.set(a,d.filter(l=>l.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:C("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.rejectConnectionReadyWaiters(new g("Coordination activity stopped before room admission completed.",false)),this.desiredExcludedPeers=[];for(let e of this.pendingAcks.values())clearTimeout(e.timer),e.resolve();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));try{await o.updatePresence(t,i,!0,5*6e4,void 0,this.options.getDefaultDeviceName());}catch(s){if(!(s instanceof g)||!s.retryable)throw s;await o.waitForConnectionReady();}}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 g("Coordination reconnect circuit is open until presence or scope changes.",false);if(this.reconnectTimer)throw new g("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,false);await new Promise((o,s)=>{let a=new WebSocket(lt(r.gatewayUrl,r.routeKey,r.protocolVersion),[st,`${at}${r.token}`]);this.socket=a;let c=false,d=null,l=setTimeout(()=>{a.close(4408,"authentication timeout"),d=new g("Coordination gateway authentication timed out.",true),s(d);},re);a.onopen=()=>{a.send(JSON.stringify({v:1,type:"auth",token:r.token,device:this.gatewayDevice(e)}));},a.onmessage=f=>{let h;try{h=JSON.parse(String(f.data));}catch{a.close(4400,"invalid gateway frame"),c||(clearTimeout(l),s(new Error("Coordination gateway returned an invalid frame.")));return}if(h.type==="ready"&&!c&&(this.activeGrantToken=r.token,this.activeGrantProtocolVersion=r.protocolVersion,c=true,this.socketReady=true,this.appliedPresenceRevision=Math.max(this.appliedPresenceRevision,this.desiredPresence?t:0),clearTimeout(l),this.reconnectAttempt=0,this.scheduleAuthRefresh(r.expiresAtMs,r.protocolVersion),this.resolveConnectionReadyWaiters(),o()),h.type==="error"&&!c){d=new g(`Coordination gateway ${h.code}: ${h.message}`,h.retryable),clearTimeout(l),s(d),a.close(4403,h.code);return}this.handleFrame(h);},a.onerror=()=>{c||(clearTimeout(l),d??(d=new g("Coordination gateway connection failed.",true)),s(d));},a.onclose=f=>{clearTimeout(l),this.socket===a&&(this.socket=null,this.socketReady=false),this.rejectPendingAcks("Coordination gateway connection closed."),this.rejectPendingAuthRefresh(new g("Coordination gateway closed during credential refresh.",f.code!==4401&&f.code!==4403)),!this.stopped&&this.desiredPresence&&f.code!==1e3&&!Ae(d)&&this.scheduleReconnect(d??new g(`Coordination gateway closed (${f.code}).`,f.code!==4401));};});};try{await i();}catch(r){if(!Ae(r))throw r;await i();}}async mintGatewayCredential(e,t){let r={avenue:await this.resolveAvenue(),deviceId:this.options.getLocalDeviceId(),runtimeInstanceId:this.runtimeInstanceId,ticketFingerprint:await dt(e.ticket),purpose:this.options.credentialPurpose??"presence",idempotencyKey:C("credential")},o;try{o=this.options.gateway.grantProvider?await this.options.gateway.grantProvider({...r,...t&&this.activeGrantToken?{refreshGrant:this.activeGrantToken}:{}}):this.options.getPlatformType()==="web"?await this.mintBrowserCredential(r):await this.mintNativeCredential(r);}catch(a){throw a instanceof g?a:new g(a instanceof Error?a.message:"Coordination credential mint failed.",!Ee(a))}if(o.protocolVersion!==1&&o.protocolVersion!==2)throw new g("Unsupported coordination gateway protocol.",false);let s=_e(this.options.gateway.endpoint);if(_e(o.gatewayUrl)!==s)throw new g("Coordination credential returned an unexpected gateway origin.",false);return o}async mintBrowserCredential(e){let t=async s=>{let a=await this.options.getAuthToken(s);if(!a)throw new g("[OpenRTC] Browser coordination requires an authenticated runtime.",false);let c=await this.options.getAppCheckToken(s);if(!c)throw new g("[OpenRTC] Browser coordination requires platform attestation.",false);return fetch(ke(this.options.projectId,this.options.gateway,"mintCoordinationCredential"),{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${a}`,"X-Firebase-AppCheck":c},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 g(`[OpenRTC] Browser coordination credential denied: ${await Me(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 g("[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[c,d]=await Promise.all([a?this.options.getAuthToken(true):Promise.resolve(t),this.getNativeTrustToken(a)]);if(!c)throw new Error("[OpenRTC] Native coordination requires an authenticated runtime.");return fetch(ke(this.options.projectId,this.options.gateway,"mintNativeCoordinationCredential"),{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${c}`,"X-Firebase-AppCheck":d},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 g(`[OpenRTC] Native coordination credential denied: ${await Me(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,this.activeGrantProtocolVersion),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 g(`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 V(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 V)||i.code!=="budget-renewal-required"&&i.code!==a$1.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."));},re);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,t){this.authRefreshTimer&&clearTimeout(this.authRefreshTimer);let i=e-Date.now(),r=t===2?tt:et,o=i>r+1e3;this.authRefreshTimer=setTimeout(()=>{if(this.authRefreshTimer=null,!this.stopped){if(!o){this.stopSocket(false),this.scheduleReconnect(new g("Coordination credential crossed a billing boundary.",true));return}this.refreshAuthentication().catch(s=>{this.stopSocket(false),this.scheduleReconnect(s);});}},o?i-r:Math.max(1e3,i+1e3));}async refreshAuthentication(){let e=this.socket,t=this.desiredPresence;if(!e||e.readyState!==WebSocket.OPEN||!this.socketReady||!t)throw new g("Coordination socket is unavailable for credential refresh.",true);if(this.pendingAuthRefresh)return this.pendingAuthRefresh.promise;let i=await this.mintGatewayCredential(t,true),r,o,s=new Promise((c,d)=>{r=c,o=d;}),a=setTimeout(()=>{this.pendingAuthRefresh?.timer===a&&(this.pendingAuthRefresh=null),o(new g("Coordination credential refresh timed out.",true));},re);this.pendingAuthRefresh={promise:s,resolve:r,reject:o,timer:a},e.send(JSON.stringify({v:1,type:"auth.refresh",token:i.token})),await s,this.activeGrantToken=i.token,this.activeGrantProtocolVersion=i.protocolVersion;}scheduleReconnect(e){if(this.reconnectTimer||this.reconnectCircuitOpen||this.stopped)return;if(!(e instanceof g?e.retryable:!Ee(e))||this.reconnectAttempt>=it){this.reconnectCircuitOpen=true,this.rejectConnectionReadyWaiters(e instanceof Error?e:new g("Coordination reconnect circuit is open.",false));return}let i=ct(d$1(this.reconnectAttempt++,250,nt));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 g("Coordination credential refresh was canceled.",true));let t=this.socket;this.socket=null,this.socketReady=false,t?.close(1e3,"coordination session stopped");}waitForConnectionReady(){return this.socket?.readyState===WebSocket.OPEN&&this.socketReady?Promise.resolve():this.stopped||this.reconnectCircuitOpen?Promise.reject(new g("Coordination reconnect circuit is unavailable.",false)):new Promise((e,t)=>{this.connectionReadyWaiters.add({resolve:e,reject:t});})}resolveConnectionReadyWaiters(){for(let e of this.connectionReadyWaiters)e.resolve();this.connectionReadyWaiters.clear();}rejectConnectionReadyWaiters(e){for(let t of this.connectionReadyWaiters)t.reject(e);this.connectionReadyWaiters.clear();}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 Q=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 c={token:o,expiresAtMs:s};return this.cached=c,this.refreshRetryUsed=false,this.notify(c),this.scheduleRefresh(c),c})();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 Z(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 w=class w{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 d=await this.deps.withWebPresenceMetadata(o,a);if(!(s===this.presenceStartGeneration&&this.presenceState!==null))return;let f=false,h=null,y=(v,D)=>{this.scheduleDurableRosterRetry(a,s,w.PRESENCE_LEASE_MS,v,D);};h=setTimeout(()=>{f||y("initial coordination presence write timed out");},w.INITIAL_PRESENCE_WRITE_TIMEOUT_MS),this.deps.updatePresence(t,r,true,w.PRESENCE_LEASE_MS,d,i).then(()=>{f=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>w.PRESENCE_RETRY_LIMIT){console.warn(`[WasmBridge] ${r}; durable roster retry circuit opened after ${w.PRESENCE_RETRY_LIMIT} attempts`,o);return}this.durablePresenceRetryAttempt=s;let a=Math.min(w.PRESENCE_RETRY_MIN_DELAY_MS*2**Math.min(8,s-1),w.PRESENCE_RETRY_MAX_DELAY_MS),c=(s*17%21-10)/100,d=Math.max(w.PRESENCE_RETRY_MIN_DELAY_MS,Math.trunc(a+a*c));console.warn(`[WasmBridge] ${r}; retrying coordination presence in ${d}ms`,o),this.durablePresenceRetryTimer=setTimeout(()=>{this.durablePresenceRetryTimer=null,!(t!==this.presenceStartGeneration||this.presenceState===null)&&(async()=>{if(this.presenceState===null)return;let l=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,l,this.presenceState.deviceName);})().then(()=>{this.durablePresenceRetryAttempt=0,this.clearDurablePresenceRetryTimer();}).catch(l=>{this.scheduleDurableRosterRetry(e,t,i,"durable roster registration retry failed",l);});},d);}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;}};w.INITIAL_PRESENCE_WRITE_TIMEOUT_MS=5e3,w.PRESENCE_RETRY_MIN_DELAY_MS=2e3,w.PRESENCE_RETRY_MAX_DELAY_MS=6e4,w.PRESENCE_RETRY_LIMIT=8,w.PRESENCE_LEASE_MS=15*6e4;var ee=w;var pt="[OpenRTC][teardown-trace]";function ht(){try{let n=globalThis;if(n.OPENRTC_TEARDOWN_TRACE===!0||n.localStorage?.getItem("OPENRTC_TEARDOWN_TRACE")==="1")return !0}catch{}return false}function De(n,e={}){console.info(pt,{kind:n,ts:new Date().toISOString(),...e}),ht()&&console.info("[OpenRTC][teardown-trace:stack]",{kind:n,stack:new Error(`teardown: ${n}`).stack});}var ne="trustedDevice",ft="plutonium:e2ee:identity:v1",mt="plutonium:e2ee:identity:session:v1",gt="openrtc-trust",W="identity",Ne="transport-trust:v1",yt=1,I=null,G=null;function P(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 H(n){let e="";for(let t=0;t<n.length;t+=1)e+=String.fromCharCode(n[t]);return btoa(e)}async function oe(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 vt(){return typeof sessionStorage>"u"?null:sessionStorage}function wt(){if(!(typeof localStorage>"u"))try{localStorage.removeItem(ft);}catch{}}var te=null;async function Oe(){return te||(te=(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}})(),te)}async function St(n){let e=await crypto.subtle.exportKey("raw",n);return new Uint8Array(e)}function bt(){try{return typeof indexedDB<"u"?indexedDB:null}catch{return null}}function xe(){let n=bt();return n?new Promise(e=>{let t;try{t=n.open(gt,1);}catch{e(null);return}t.onupgradeneeded=()=>{let i=t.result;i.objectStoreNames.contains(W)||i.createObjectStore(W);},t.onsuccess=()=>e(t.result),t.onerror=()=>e(null),t.onblocked=()=>e(null);}):Promise.resolve(null)}async function It(){let n=await xe();if(!n)return null;try{return await new Promise(e=>{let r=n.transaction(W,"readonly").objectStore(W).get(Ne);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 Tt(n){let e=await xe();if(!e)return false;try{return await new Promise(t=>{let i=e.transaction(W,"readwrite");i.objectStore(W).put(n,Ne),i.oncomplete=()=>t(!0),i.onerror=()=>t(!1),i.onabort=()=>t(!1);})}catch{return false}finally{e.close();}}async function Le(n,e){let t=await St(n.publicKey),i=await oe(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,P(o));return H(new Uint8Array(s))}}}function Ct(n,e,t){let i=n.secretKey;return {publicKey:n.publicKey,secretKey:i,fingerprint:e,backend:"tweetnacl",durable:t,async signChallenge(r){return Rt(r,i)}}}function Zt(n=32){let e=crypto.getRandomValues(new Uint8Array(n));return H(e)}function Rt(n,e){let t=U.sign.detached(P(n),e);return H(t)}function Pt(n,e,t){try{return U.sign.detached.verify(P(n),P(e),P(t))}catch{return false}}async function en(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",P(t),{name:"Ed25519"},!1,["verify"]);return await i.verify({name:"Ed25519"},r,P(e),P(n))}catch{}return Pt(n,e,t)}function tn(n){return H(n)}function nn(n){if(!n||!n.trim())return null;try{let e=JSON.parse(n),t=e&&typeof e=="object"&&!Array.isArray(e)?e[ne]: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 At(){let n=await Dt().catch(()=>null);return n?{version:yt,identityPublicKey:H(n.publicKey),identityFingerprint:n.fingerprint}:null}async function se(n){let e=await At();if(!e)return n??void 0;let t=typeof n=="string"?n.trim():"";if(!t)return JSON.stringify({[ne]:e});try{let i=JSON.parse(t);if(i&&typeof i=="object"&&!Array.isArray(i))return JSON.stringify({...i,[ne]:e})}catch{}return JSON.stringify({metadata:n,[ne]:e})}function Et(){if(typeof window>"u")return null;let n=window.__TAURI_INTERNALS__;return !n||typeof n.invoke!="function"?null:n.invoke.bind(n)}async function _t(){if(typeof window>"u")return null;let n=Et();if(!c()&&!n)return null;if(!n)throw new Error("[OpenRTC] Tauri transport trust requires the native signing provider, but Tauri invoke is unavailable.");try{let e=await n("openrtc_get_transport_trust_identity"),t=P(e.publicKeyBase64);if(t.byteLength!==U.sign.publicKeyLength)throw new Error("native transport trust public key has an invalid length");let i=await oe(t);if(e.fingerprint!==i)throw new Error("native transport trust fingerprint does not match its public key");return {publicKey:t,fingerprint:i,backend:"native-provider",durable:!0,async signChallenge(r){return n("openrtc_sign_transport_trust_challenge",{challenge:r})}}}catch(e){let t=new Error("[OpenRTC] native transport trust provider failed; refusing WebCrypto fallback in Tauri.");throw t.cause=e,t}}function kt(){let n=vt();n&&n.removeItem(mt);}async function Mt(){if(wt(),kt(),I)return I;let n=await _t();if(n)return I=n,I;if(await Oe()){let e=await It();if(e)return I=await Le(e,true),I}return null}async function Dt(n={}){let e=await Mt();if(e)return e;if(G)return G;let t=Nt(n);G=t;try{return await t}finally{G===t&&(G=null);}}async function Nt(n){if(I)return I;let e=n.ephemeral===true;if(await Oe())try{let t=await crypto.subtle.generateKey({name:"Ed25519"},!1,["sign","verify"]),i=!1;return e||(i=await Tt(t)),I=await Le(t,i),I}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=U.sign.keyPair(),i=await oe(b(t.publicKey));return I=Ct(t,i,!1),I}catch{return null}}var ae={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 on(){return ae}var Ot={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}},xt={adapter:"native-ipc",signaling:{coordinationGateway:true,nativeIpc:true,managedPresence:true},transport:{irohQuic:true,irohLan:false,webRtcUpgrade:false,webRtcLan:false,nativeWebRtc:false,moq:false,ble:false,wasm:false},nativeProtocols:{productAlpn:true,irohDocs:true,irohBlobs:true,irohGossip:true},lifecycle:{managedSession:true,autoConnect:true,manualDisconnect:true,connectionStateEvents:true,peerSessions:true},transfers:{explicitFilePath:true,explicitFileData:true,history:true},fallback:{wasm:false}};function We(n){return {adapter:n.adapter,signaling:{...n.signaling},transport:{...n.transport},nativeProtocols:{...n.nativeProtocols},lifecycle:{...n.lifecycle},transfers:{...n.transfers},fallback:{...n.fallback}}}function Fe(n=globalThis){let e=We(Ot),t=typeof n?.RTCPeerConnection=="function";return e.transport.webRtcUpgrade=t,e.transport.webRtcLan=t,e}function L(n){return n?.compiled===true&&n.enabled===true}function an(n,e=false){let t=We(xt),i=n?.transport;return i&&(t.transport.irohQuic=L(i.irohQuic),t.transport.irohLan=L(i.irohLan),t.transport.webRtcUpgrade=L(i.webRtc),t.transport.nativeWebRtc=L(i.webRtc),t.transport.webRtcLan=L(i.webRtcLan),t.transport.moq=L(i.moq),t.transport.ble=L(i.ble)),t.transport.wasm=false,t.fallback.wasm=e,t}function cn(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}}}function Be(n){if(n.errorCode)return n;let e=n.error||n.readinessReason;if(!e)return n;let t=c$2(e);return {...n,errorCode:t.errorCode,retryable:t.retryable,errorPlane:t.errorPlane}}function F(n){return !n||typeof n!="object"?{}:n instanceof Map?Object.fromEntries(n):n}function ce(n){let e=F(n),t=F(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 k(n,...e){for(let t of e){let i=n[t];if(typeof i=="boolean")return i}}function p(n,...e){for(let t of e){let i=n[t];if(typeof i=="number"&&Number.isFinite(i))return i}}function M(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 de(...n){let e=n.map(M).filter(t=>typeof t=="number"&&Number.isFinite(t));return e.length?Math.max(...e):void 0}function le(n){if(typeof n!="string")return;let e=n.trim().toLowerCase();return e==="online"||e==="idle"||e==="offline"?e:void 0}function Ge(n){let e=le("presenceStatus"in n?n.presenceStatus:void 0),t="presenceUpdatedAt"in n?M(n.presenceUpdatedAt):void 0,i="presenceExpiresAt"in n?M(n.presenceExpiresAt):void 0,r=t??de(n.lastSeenAt,n.updatedAt,n.createdAt),o=i??M(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():"",c="connectable"in n&&typeof n.connectable=="boolean"?n.connectable:s==="online"&&a.length>0;return {presenceStatus:s,presenceUpdatedAt:r,presenceExpiresAt:o,connectable:c}}function Ue(n){return f$1(n)}function B(n,...e){return Ue(u(n,...e))}function z(n){if(!Array.isArray(n))return;let e=Array.from(new Set(n.map(Ue).filter(t=>!!t)));return e.length?e:void 0}function He(n){let e=F(n),t={webrtc:p(e,"webrtc"),webrtcLan:p(e,"webrtcLan","webrtc_lan"),webrtcTurn:p(e,"webrtcTurn","webrtc_turn"),iroh:p(e,"iroh"),irohLan:p(e,"irohLan","iroh_lan"),irohRelay:p(e,"irohRelay","iroh_relay"),ble:p(e,"ble"),moq:p(e,"moq")};return Object.values(t).some(i=>i!==void 0)?t:void 0}function Ke(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 ze(n,e,t){return t?true:(typeof n.appTag=="string"?n.appTag:typeof n.tag=="string"?n.tag:void 0)===e}function ue(n,e){let t=ce(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:le(u(t,"presenceStatus","presence_status","livenessStatus","liveness_status")),presenceUpdatedAt:p(t,"presenceUpdatedAt","presence_updated_at")??de(t.presenceUpdatedAt,t.presence_updated_at,t.lastSeenAt,t.last_seen_at,t.updatedAt,t.updated_at,t.createdAt,t.created_at),presenceExpiresAt:p(t,"presenceExpiresAt","presence_expires_at")??M(t.presenceExpiresAt??t.presence_expires_at)??M(t.expiresAt??t.expires_at),connectable:k(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:pe(t.excludedPeers??t.excluded_peers),availableTransports:z(t.availableTransports??t.available_transports),transports:z(t.transports)}}function pe(n){return Array.isArray(n)?n.filter(e=>typeof e=="string"):[]}function Lt(n){let e=Ge(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?pe(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?z(n.availableTransports):"transports"in n?z(n.transports):void 0,latencyMs:"latencyMs"in n&&typeof n.latencyMs=="number"?n.latencyMs:void 0,latencyByTransport:"latencyByTransport"in n?He(n.latencyByTransport):void 0}}function K(n,e){return e===void 0?true:e===null?n==null:n==null||n===e}function je(n,e){let t=K(n.connectionId,e.connectionId)&&K(n.nodeId,e.nodeId)&&K(n.activeTransportStableId,e.activeTransportStableId)&&K(n.transportGeneration,e.transportGeneration)&&K(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 Wt={connectionId:void 0,activeTransportStableId:null,transportGeneration:void 0,routeGeneration:void 0,activeTransport:void 0,parallelTransport:void 0,latencyMs:void 0,latencyByTransport:void 0};function Ft(n,e,t){let i=je(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",d=typeof e.readinessState=="string"&&e.readinessState.trim().length>0?e.readinessState==="routable":e.settledReady===true,l=n.settledReady===true||n.readinessState==="routable";if(i.inheritsSnapshot&&l&&!a&&!d)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 f=a?false:d,h=d&&!a&&(s==="connecting"||s==="connected")?"connected":o,y=d?"routable":e.readinessState??(i.inheritsSnapshot?n.readinessState:void 0),v=f?e.readinessReason??"peer-session-settled":e.readinessReason??(i.inheritsSnapshot?n.readinessReason:void 0);return {...n,connectionStatus:h,settledReady:f,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 Bt(n,e){let t=je(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,...Wt,scopes:e.scopes?.length?[...e.scopes]:n.scopes};let c=e.routable===true||e.protocolState==="routable";if(t.inheritsSnapshot&&s&&!o&&!c)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 d=e.transportState==="connected"&&e.health==="healthy",l=o?false:c,f=!o&&(c||d)&&(r==="connecting"||r==="connected"||e.transportState==="connected")?"connected":i,h=l?"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=l?(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:f,settledReady:l,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 Gt(n){let{device:e,session:t=null,peer:i=null,isPromotionEligible:r}=n,o=Lt(e);return t&&(o=Ft(o,t,r)),i&&(o=Bt(o,i)),Be(o)}function qe(n){let e=ce(n),t=ue(e),i=le(u(e,"presenceStatus","presence_status","livenessStatus","liveness_status")),r=Ge({...t,...i?{presenceStatus:i}:{},presenceUpdatedAt:p(e,"presenceUpdatedAt","presence_updated_at")??de(e.presenceUpdatedAt,e.presence_updated_at,e.lastSeenAt,e.last_seen_at,e.updatedAt,e.updated_at,e.createdAt,e.created_at),presenceExpiresAt:p(e,"presenceExpiresAt","presence_expires_at")??M(e.presenceExpiresAt??e.presence_expires_at)??M(e.expiresAt??e.expires_at),connectable:k(e,"connectable")}),o={...t,...r,connectionStatus:u(e,"connectionStatus","connection_status")||"disconnected",settledReady:k(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:pe(e.scopes),connectionId:u(e,"connectionId","connection_id"),deviceIdHint:u(e,"deviceIdHint","device_id_hint"),activeTransportStableId:p(e,"activeTransportStableId","active_transport_stable_id")??void 0,transportGeneration:p(e,"transportGeneration","transport_generation")??void 0,routeGeneration:p(e,"routeGeneration","route_generation")??void 0,activeTransport:B(e,"activeTransport","active_transport"),parallelTransport:B(e,"parallelTransport","parallel_transport")??null,availableTransports:z(e.availableTransports??e.available_transports),latencyMs:p(e,"latencyMs","latency_ms"),latencyByTransport:He(e.latencyByTransport??e.latency_by_transport)};return Gt({device:o})}function $e(n){let e=ce(n);return Be({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:k(e,"settledReady","settled_ready")??false,readinessState:u(e,"readinessState","readiness_state")??void 0,activeTransportStableId:p(e,"activeTransportStableId","active_transport_stable_id")??void 0,transportGeneration:p(e,"transportGeneration","transport_generation")??void 0,routeGeneration:p(e,"routeGeneration","route_generation")??void 0,activeTransport:B(e,"activeTransport","active_transport"),parallelTransport:B(e,"parallelTransport","parallel_transport")??null,replacementPending:k(e,"replacementPending","replacement_pending")??void 0,lastLifecycleTransitionAtMs:p(e,"lastLifecycleTransitionAtMs","last_lifecycle_transition_at_ms")??void 0,readinessReason:u(e,"readinessReason","readiness_reason")??void 0,transitionCount:p(e,"transitionCount","transition_count")??void 0,connectingTransitionCount:p(e,"connectingTransitionCount","connecting_transition_count")??void 0,replacementCount:p(e,"replacementCount","replacement_count")??void 0,retireCount:p(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:k(e,"retryable")??void 0,errorPlane:u(e,"errorPlane","error_plane")??void 0})}function hn(n){let e=F(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 fn(n){let e=F(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 Ut(n){switch(n){case "connected":return "connected";case "connecting":return "connecting";case "failed":return "failed";default:return "closed"}}function Ye(n){let e=n.activeConnectionId||n.candidateConnectionIds[0]||null;if(!e)return null;let t=Ut(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 Xe(n){let e=F(n),t=u(e,"connectionId","connection_id");if(!t)return null;let i=u(e,"state")||"connecting",r=p(e,"createdAt","created_at")??p(e,"updatedAt","updated_at")??Date.now(),o=p(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:k(e,"routable")??false,readinessState:u(e,"readinessState","readiness_state")??void 0,readinessReason:u(e,"readinessReason","readiness_reason")??void 0,transportGeneration:p(e,"transportGeneration","transport_generation")??void 0,routeGeneration:p(e,"routeGeneration","route_generation")??void 0,activeTransportStableId:p(e,"activeTransportStableId","active_transport_stable_id")??void 0,activeTransport:B(e,"activeTransport","active_transport"),parallelTransport:B(e,"parallelTransport","parallel_transport")??null,replacementInProgress:k(e,"replacementInProgress","replacement_in_progress")??void 0,lastLifecycleTransitionAtMs:p(e,"lastLifecycleTransitionAtMs","last_lifecycle_transition_at_ms")??void 0,transitionCount:p(e,"transitionCount","transition_count")??void 0,connectingTransitionCount:p(e,"connectingTransitionCount","connecting_transition_count")??void 0,replacementCount:p(e,"replacementCount","replacement_count")??void 0,retireCount:p(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 Ve(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 Ht(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 Kt(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?Ht(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,c=o&&typeof o.m=="number"&&Number.isFinite(o.m)?o.m:null;return {present:true,irohFingerprint:Z(i),tokenFingerprint:Z(s),tokenSuffixFingerprint:Z(r),scope:a,maxConnections:c}}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 m=class m{constructor(e$1){this.spaceNamespaceIdPromise=null;this.cachedSpaceNamespaceId=null;this.authListeners=[];this.wasmClient=null;this.createdAtMs=Date.now();this.missingWasmWarnings=new Set;this.wasmReadyWarningDelayMs=15e3;this.browserCoordinationSignaling=null;this.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=e(e$1),this.options={...e$1,appTag:this.appTag,authMode:f(e$1),projectId:g$1(e$1)},this.nativeTrustTokens=this.options.coordinationGateway?new Q(this.options.coordinationGateway.nativeTrustTokenProvider):null,this.presenceManager=new ee({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,c)=>this.updatePresence(i,r,o,s,a,c),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.usesProviderNeutralGrant()){this.app=null,this.auth=null;return}let t=b$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 Fe()}getDeviceIdentityStorageKey(){let e=h(this.options);return `${m.WEB_DEVICE_ID_STORAGE_PREFIX}_${e}`}getDeviceIdPersistenceMode(){return this.options.deviceIdPersistence??this.options.nodeIdPersistence??"persistent"}isTicketOnlyMode(){return this.options.signalingMode==="ticket-only"}usesProviderNeutralGrant(){return typeof this.options.coordinationGateway?.grantProvider=="function"}createRandomDeviceId(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`web-${Date.now()}-${Math.random().toString(36).slice(2,10)}`}resolveWebLogicalDeviceId(){let e=this.options.localDeviceId?.trim();if(e)return e;let t=this.getDeviceIdPersistenceMode();if(typeof localStorage>"u")return this.createRandomDeviceId();let i=this.getDeviceIdentityStorageKey(),r=Date.now(),o=null;try{let l=localStorage.getItem(i);o=l?JSON.parse(l):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 l=s||this.createRandomDeviceId();return localStorage.setItem(i,JSON.stringify({deviceId:l})),l}if(s&&typeof a=="number"&&a>r){let l=r+m.EPHEMERAL_DEVICE_ID_TTL_MS;return localStorage.setItem(i,JSON.stringify({deviceId:s,expiresAt:l})),s}let c=this.createRandomDeviceId(),d=r+m.EPHEMERAL_DEVICE_ID_TTL_MS;return localStorage.setItem(i,JSON.stringify({deviceId:c,expiresAt:d})),c}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 J({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):b$1().getAppCheckToken(e)},getLocalDeviceId:()=>this.resolveWebLogicalDeviceId(),getDefaultDeviceName:()=>this.getDefaultBrowserDeviceName(),getPlatformType:()=>this.options.coordinationPlatformType??"web",normalizeDevice:(e,t)=>this.normalizeDevice(e,t),avenueOverride:this.options.coordinationAvenueOverride,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 se(i)??i}catch{}i=JSON.stringify({deviceId:t,metadata:e});}return await se(i)??i}async setAuthContext(e){let t=this.injectedBrowserAuthSessionActive,i=this.authContext?.userId??null,r=e?.userId??null;if(this.authContext=e,!this.isTicketOnlyMode()&&!this.usesProviderNeutralGrant()&&e?.customToken?.trim()&&!(c()&&this.options.authMode==="external"&&typeof e.tokenProvider=="function"))try{await this.ensureBrowserPlatformAuth(e.userId,e.customToken.trim());}catch(o){console.warn("[WasmBridge] ensureBrowserPlatformAuth failed (non-fatal):",o);}else if(!this.isTicketOnlyMode()&&!this.usesProviderNeutralGrant()&&!e&&t)try{await this.auth?.signOut();}catch(o){console.warn("[WasmBridge] Failed to clear injected browser auth session:",o);}finally{this.injectedBrowserAuthSessionActive=false;}this.syncWasmAuthToken(),!this.isTicketOnlyMode()&&i!==r&&await this.browserCoordinationSignaling?.handleScopeChange(),this.authListeners.forEach(o=>o(this.currentUser));}async ensureBrowserPlatformAuth(e,t){if((this.auth?.currentUser?.uid??null)===e){this.injectedBrowserAuthSessionActive=true;return}await b$1().signInWithCustomTokenValue(t),this.injectedBrowserAuthSessionActive=true;}syncWasmAuthToken(){let e=this.wasmClient?.setIdentityCredential??this.wasmClient?.set_auth_token;if(!this.wasmClient||typeof e!="function"||!this.authContext&&this.isSpaceMode())return;let t=this.authContext?.userId??null,i=this.authContext?.token,r=typeof i=="string"&&i.trim().length>0?i:null;if(!(this.hasSyncedAuthToWasmClient&&this.lastWasmAuthUserId===t&&this.lastWasmAuthToken===r)){if(this.lastWasmAuthUserId=t,this.lastWasmAuthToken=r,this.hasSyncedAuthToWasmClient=true,r===null&&typeof this.wasmClient.clearIdentityCredential=="function"){this.wasmClient.clearIdentityCredential();return}e.call(this.wasmClient,r);}}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 Ke(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 ze(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){De("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.lastWasmAuthUserId=null,this.lastWasmAuthToken=null,this.hasSyncedAuthToWasmClient=this.authContext===null,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 a(t);return this.wasmClient??null}normalizeDevice(e,t){return ue(e,t)}normalizeDeviceRecord(e,t){return this.normalizeDevice(e,t)}getResolvedWebLogicalDeviceId(){return this.resolveWebLogicalDeviceId()}normalizeDeviceStatusSnapshot(e){return qe(e)}normalizePeerSessionSnapshot(e){return $e(e)}toBackendConnectionStateFromPeerSession(e){return Ye(e)}normalizeConnectionStateSnapshot(e){return Xe(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 Ve(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()||this.usesProviderNeutralGrant()||await b$1().checkForSSOToken();}async waitForAuth(){this.isTicketOnlyMode()||this.usesProviderNeutralGrant()||this.isSpaceMode()||this.authContext?.userId||this.auth?.currentUser||await b$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 b$1().signInAnonymously();}}async signInWithPluto(){if(this.isTicketOnlyMode())throw new Error('[openrtc] Pluto sign-in is unavailable when signalingMode="ticket-only".');await b$1().signInWithPluto();}async signOut(){let e=this.getCurrentUserId();await this.stopAuthScopedActivity({userId:e}),this.authContext=null,this.syncWasmAuthToken(),this.isTicketOnlyMode()||await this.auth?.signOut(),this.authListeners.forEach(t=>t(this.currentUser));}async getTurnCredentials(){return this.isTicketOnlyMode()||!this.auth?.currentUser?null:typeof this.options.turnCredentialsProvider=="function"?await this.options.turnCredentialsProvider()??null:null}async updatePresence(e,t,i=true,r=3e5,o,s){if(this.isTicketOnlyMode())return;let a=this.resolveWebLogicalDeviceId(),c=this.getDeviceIdPersistenceMode()==="ephemeral"?m.EPHEMERAL_DEVICE_ID_TTL_MS:r,d=await this.withWebPresenceMetadata(o,a);this.presenceManager.updatePresenceLoopState({userId:this.getCurrentUserId()??"",localNodeId:e,ticket:t,metadata:d,deviceName:s?.trim()||this.getDefaultBrowserDeviceName()}),await this.getCoordinationSignaling().updatePresence(e,t,i,c,d,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,c]=await Promise.all([i.iroh_path_kind(s),i.iroh_transport_rtt_ms(s)]);if(typeof c!="number"||!Number.isFinite(c))return o;let d=Math.max(0,Math.round(c)),l={};if(a==="direct-lan")l.irohLan=d;else if(a==="direct-quic")l.iroh=d;else if(a==="ble")l.ble=d;else if(a==="relay")l.irohRelay=d;else return o;return {...o,latencyMs:d,latencyByTransport:l}}catch(a){return b$2("[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,c=a.id?.trim()||e.connectionId,d=a.remoteNodeId?.trim()||e.remoteNodeId?.trim()||a.deviceId?.trim()||t.deviceId;if(r.hasApplicationRouteForPeer?.(c,d)!==true&&r.hasApplicationRouteForPeer?.(c,d)!==true)throw new Error(`application crypto was not ready for ${d}`)})().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();c$1("[WasmBridge][ROUTE-ESCALATION] starting managed transport dial",{deviceId:e.deviceId??null,ticket:Kt(e.endpointTicket),hasCoreClient:!!this.coreClient});let r=await t.connect_device(e.deviceId??null,e.endpointTicket);c$1("[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{c$1("[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}),c=typeof a?.remoteNodeId=="string"?a.remoteNodeId.trim():"",d=typeof a?.deviceId=="string"?a.deviceId.trim():"",l=c||r?.remoteNodeId?.trim?.()||d||e.deviceId?.trim?.()||"",f=typeof s.hasApplicationRouteForPeer=="function"?s.hasApplicationRouteForPeer.bind(s):null;if(!(!!l&&f?.(a?.id??void 0,l)===!0)&&l&&typeof s.waitForApplicationCryptoForPeer=="function"&&!(!!await s.waitForApplicationCryptoForPeer(l,2e4)&&(!f||f(a?.id??void 0,l)===!0)))throw console.warn("[WasmBridge][ROUTE-ESCALATION] application route still pending after managed dial",{deviceId:e.deviceId??null,remoteNodeId:c||(r?.remoteNodeId??null),connectionId:r?.connectionId??null,peerForCrypto:l,elapsedMs:Date.now()-i}),Object.assign(new Error(`application crypto was not ready for ${l}`),{applicationCryptoNotReady:!0});c$1("[WasmBridge][ROUTE-ESCALATION] application route ready",{deviceId:e.deviceId??null,remoteNodeId:c||(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=d(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():"",c=typeof o.deviceIdHint=="string"?o.deviceIdHint.trim():"",d=typeof o.nodeId=="string"?o.nodeId.trim():"";return (i===s||i===a||i===c||i===d)&&o.status==="connected"&&o.settledReady===true&&o.replacementPending!==true&&l(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&&b$2("[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&&b$2("[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=d=>{let l=d.detail,f=typeof l?.connectionId=="string"?l.connectionId.trim():"";if(!f||o)return;let h=(i.get(f)??0)+1;i.set(f,h);let y=this.authScopedRuntimeGeneration;(async()=>{let v=this.normalizeConnectionStateSnapshot(l),D=await this.waitForWasmClient(500);if(!(o||y!==this.authScopedRuntimeGeneration||i.get(f)!==h)){if(D&&typeof D.connection_state=="function"){let ie=await D.connection_state(f),S=this.normalizeConnectionStateSnapshot(ie);if(!o&&y===this.authScopedRuntimeGeneration&&i.get(f)===h&&S){this.deliverConnectionState(S,e,"rust-event",t);return}}!o&&y===this.authScopedRuntimeGeneration&&i.get(f)===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:f,error:v});});},a=typeof window<"u"?window:null,c=typeof a?.addEventListener=="function"&&typeof a?.removeEventListener=="function";return c&&a.addEventListener("connection-state-changed",s),this.getConnectionStates().then(d=>{!o&&r===this.authScopedRuntimeGeneration&&d.forEach(l=>{i.has(l.connectionId)||this.deliverConnectionState(l,e,"replay",t);});}).catch(d=>{console.warn("[WasmBridge] Failed to replay wasm connection states after subscription:",d);}),()=>{o=true,i.clear(),c&&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 m.FALLBACK_EXPLICIT_FILE_NAME;let r="";for(let s of i){if([...r].length>=m.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===".."?m.FALLBACK_EXPLICIT_FILE_NAME:o}sanitizeExplicitMimeType(e){let t=typeof e=="string"?e.trim():"";if(!t)return m.FALLBACK_EXPLICIT_MIME_TYPE;let i="";for(let r of t){if(i.length>=m.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:m.FALLBACK_EXPLICIT_MIME_TYPE}assertExplicitTransferHeaderSize(e){if(e.byteLength===0||e.byteLength>m.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]=m.EXPLICIT_FILE_PROTOCOL_TYPE,a.set(e,1);let c=new DataView(a.buffer);c.setUint32(17,t,false),c.setUint32(21,i,false);let d=o?.headerFrame===true?29:25;return o?.headerFrame===true&&c.setUint32(25,r.byteLength,false),a.set(r,d),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,c=e.remoteNodeId?.trim()||t?.remoteNodeId?.trim()||t?.deviceId?.trim();if(c$1("[WasmBridge] sendExplicitFileData start",{connectionId:e.connectionId??null,connectionRemoteNodeId:t?.remoteNodeId??null,remoteNodeId:c??null,fileName:i.name,fileSize:i.size,transferId:s}),!c)throw new Error("Web explicit transfer requires an active connection with a resolved remote node ID");let d=await this.waitForWasmClient();if(!d)throw new Error("WASM explicit transfer requires an initialized WASM client");let l=new TextEncoder,f={transfer_id:s,filename:this.sanitizeExplicitFileName(i.name),size:i.size,mime_type:this.sanitizeExplicitMimeType(i.type)},h=l.encode(JSON.stringify(f));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 D=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&&c$1("[WasmBridge] sendExplicitFileData kept on Iroh for non-browser receiver",{remoteNodeId:c,transferId:s,receiverPlatformType:a}),false;let S=r?o(r):null,A=x=>S?S.protectFrame(x):x,R=new Uint8Array(await i.arrayBuffer()),E=this.createWebRTCExplicitTransferId(),N=Math.max(1,Math.ceil(R.byteLength/m.EXPLICIT_FILE_CHUNK_SIZE_BYTES)),b=typeof t.getWebRTCTransport=="function"?t.getWebRTCTransport():null,O=async()=>{b&&typeof b.getBufferedAmount=="function"&&typeof b.waitForDrain=="function"&&b.getBufferedAmount()>m.EXPLICIT_FILE_CHUNK_SIZE_BYTES*4&&await b.waitForDrain(m.EXPLICIT_FILE_CHUNK_SIZE_BYTES*2);};if(await t.sendOnWebRTC(this.createWebRTCExplicitTransferFrame(E,4294967295,N,A(h),{headerFrame:true})),await O(),R.byteLength===0)return await t.sendOnWebRTC(this.createWebRTCExplicitTransferFrame(E,0,N,A(new Uint8Array(0)))),true;let q=0;for(let x=0;x<R.byteLength;x+=m.EXPLICIT_FILE_CHUNK_SIZE_BYTES){let Qe=R.slice(x,Math.min(x+m.EXPLICIT_FILE_CHUNK_SIZE_BYTES,R.byteLength));await t.sendOnWebRTC(this.createWebRTCExplicitTransferFrame(E,q,N,A(Qe))),q+=1,await O();}return c$1("[WasmBridge] sendExplicitFileData sent over WebRTC explicit route",{connectionId:e.connectionId??null,remoteNodeId:c,transferId:s,chunks:N,encrypted:!!S}),true},ie=async()=>{let S=d.open_peer_bi_explicit_file_sender;if(typeof S!="function")return false;let A=await S.call(d,c,5e3),R=A?.writable??A?.send;if(!R||typeof R.getWriter!="function")throw new Error("WASM explicit peer stream returned an invalid writable stream");c$1("[WasmBridge] sendExplicitFileData open_peer_bi_explicit_file_sender resolved",{remoteNodeId:c,transferId:e.transferId??null,applicationCryptoWrapped:A.applicationCryptoWrapped===true});let E=j(A,R,{requireFinish:true}).getWriter(),N=false;try{await E.write(v);let b=new Uint8Array(await i.arrayBuffer());for(let O=0;O<b.byteLength;O+=m.EXPLICIT_FILE_CHUNK_SIZE_BYTES){let q=b.slice(O,Math.min(O+m.EXPLICIT_FILE_CHUNK_SIZE_BYTES,b.byteLength));await E.write(q);}}catch(b){throw N=true,b}finally{try{await E.close();}catch(b){if(!N)throw b}finally{E.releaseLock();}}return true};try{try{if(await D())return}catch(S){c$1("[WasmBridge] sendExplicitFileData WebRTC explicit route failed; falling back",{remoteNodeId:c,transferId:s,error:S instanceof Error?S.message:String(S)});}if(await ie())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{c$1("[WasmBridge] sendExplicitFileData completed",{remoteNodeId:c,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);}};m.EXPLICIT_FILE_PROTOCOL_TYPE=2,m.EXPLICIT_FILE_CHUNK_SIZE_BYTES=64*1024,m.MAX_EXPLICIT_TRANSFER_HEADER_BYTES=64*1024,m.FALLBACK_EXPLICIT_FILE_NAME="openrtc-transfer.bin",m.MAX_EXPLICIT_FILE_NAME_CHARS=180,m.FALLBACK_EXPLICIT_MIME_TYPE="application/octet-stream",m.MAX_EXPLICIT_MIME_TYPE_CHARS=255,m.WEB_DEVICE_ID_STORAGE_PREFIX="pluto_rtc_web_device_identity",m.EPHEMERAL_DEVICE_ID_TTL_MS=ae.browserIdentity.ephemeralDeviceIdTtlMs;var Je=m;
2
- export{Zt as a,en as b,tn as c,nn as d,se as e,Dt as f,De as g,ce as h,Gt as i,qe as j,$e as k,hn as l,fn as m,Xe as n,ae as o,on as p,Ot as q,xt as r,We as s,Fe as t,an as u,cn as v,Je as w};