openrtc 1.0.1 → 1.0.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (35) hide show
  1. package/README.md +3 -1
  2. package/dist/{DelegatingRuntimeAdapter-By7pziBs.d.ts → DelegatingRuntimeAdapter-D2_dgabz.d.ts} +20 -2
  3. package/dist/{IpcRuntimeAdapter-DymXAsNU.d.ts → IpcRuntimeAdapter-B8rkqNrq.d.ts} +2 -2
  4. package/dist/auth/index.js +1 -1
  5. package/dist/auth/internal.js +1 -1
  6. package/dist/chunk-34LATQZZ.js +2 -0
  7. package/dist/chunk-BGQX25BO.js +1 -0
  8. package/dist/chunk-C7YN5MSV.js +1 -0
  9. package/dist/chunk-L6OUJ6YN.js +2 -0
  10. package/dist/chunk-MESPJTUA.js +1 -0
  11. package/dist/chunk-NCRP5ODV.js +3 -0
  12. package/dist/chunk-QT2ASNI3.js +1 -0
  13. package/dist/{chunk-EGEA3GU2.js → chunk-RRCARL4S.js} +1 -1
  14. package/dist/{device-status-nkXepu97.d.ts → device-status-CR27Ak7c.d.ts} +53 -7
  15. package/dist/{framing-BUtu0oZK.d.ts → framing-rPdckqn5.d.ts} +10 -4
  16. package/dist/index.d.ts +15 -10
  17. package/dist/index.js +2 -2
  18. package/dist/openrtc_bg.wasm +0 -0
  19. package/dist/runtime/WasmRuntimeAdapter.d.ts +2 -2
  20. package/dist/runtime/WasmRuntimeAdapter.js +1 -1
  21. package/dist/runtime/device-status.d.ts +2 -2
  22. package/dist/runtime/index.d.ts +16 -10
  23. package/dist/runtime/index.js +1 -1
  24. package/dist/runtime/tauri.d.ts +3 -3
  25. package/dist/runtime/tauri.js +1 -1
  26. package/dist/transport/index.d.ts +7 -2
  27. package/dist/transport/index.js +1 -1
  28. package/dist/{types-CzIpGV9x.d.ts → types-ByZyADCn.d.ts} +69 -4
  29. package/package.json +2 -2
  30. package/dist/chunk-A2ENDDFR.js +0 -2
  31. package/dist/chunk-BLOEZIFJ.js +0 -1
  32. package/dist/chunk-KZ3KWQTO.js +0 -1
  33. package/dist/chunk-MA2JFAV7.js +0 -2
  34. package/dist/chunk-OCNLQID3.js +0 -1
  35. package/dist/chunk-VIPNH2BE.js +0 -3
package/README.md CHANGED
@@ -135,7 +135,9 @@ full ALPN plugin layer.
135
135
  For applications that want a reusable file protocol without making it part of
136
136
  the core runtime, install `openrtc-file-transfer`. It implements versioned,
137
137
  bounded file framing, acknowledgement, progress, cancellation, optional
138
- integrity verification, and streaming receive sinks over `client.channels`.
138
+ integrity verification, and streaming receive sinks. Modern clients send
139
+ receiver-acknowledged segments through OpenRTC's current application route;
140
+ the named-channel stream carrier remains compatibility fallback.
139
141
  Filesystem destinations, persistent queues, history, acceptance prompts, and
140
142
  product policy remain consumer-owned.
141
143
 
@@ -1,4 +1,4 @@
1
- import { D as DiscoveryMode, A as AuthMode, S as SignalingMode, E as ExplicitFileDataSendParams, I as ISignalingBackend, R as RuntimeIdentity, a as Device, b as DeviceStatusSnapshot, P as PeerSessionSnapshot, c as ResolvedPeerIdentity, M as ManagedConnectionRecord, d as SignalingEnvelope, e as DeviceEvent, f as SignalingSession, g as SessionEvent, L as LocalDeviceInfo, N as NativeManagedSessionStartResult, G as GrantScope, B as BackendPeerBiStream, h as BackendPeerUniStream, i as NativeConnectParams, j as NativeConnectResult, k as BackendConnectionState } from './types-CzIpGV9x.js';
1
+ import { D as DiscoveryMode, A as AuthMode, S as SignalingMode, E as ExplicitFileDataSendParams, I as ISignalingBackend, R as RuntimeIdentity, a as Device, b as DeviceStatusSnapshot, P as PeerSessionSnapshot, c as ResolvedPeerIdentity, M as ManagedConnectionRecord, d as SignalingEnvelope, e as DeviceEvent, f as SignalingSession, g as SessionEvent, L as LocalDeviceInfo, N as NativeManagedSessionStartResult, G as GrantScope, B as BackendPeerBiStream, h as BackendPeerUniStream, i as NativeConnectParams, j as NativeConnectResult, k as BackendConnectionState } from './types-ByZyADCn.js';
2
2
  import { A as AuthContext } from './IEngineBridge-C7OT2CRv.js';
3
3
 
4
4
  type RuntimeAdapterKind = 'browser-wasm' | 'native-ipc' | 'tauri-ipc' | 'unknown';
@@ -79,8 +79,25 @@ interface NativeRuntimeStatusSnapshot {
79
79
  };
80
80
  }
81
81
  declare const BROWSER_WASM_RUNTIME_CAPABILITIES: RuntimeCapabilities;
82
+ /**
83
+ * The small host surface that browser WebRTC capability reporting needs.
84
+ *
85
+ * This is deliberately a feature check only: capability reporting must not
86
+ * create a peer connection, probe ICE, or influence route ownership.
87
+ */
88
+ interface BrowserRuntimeCapabilityHost {
89
+ RTCPeerConnection?: unknown;
90
+ }
82
91
  declare const NATIVE_IPC_RUNTIME_CAPABILITIES: RuntimeCapabilities;
83
92
  declare function cloneRuntimeCapabilities(capabilities: RuntimeCapabilities): RuntimeCapabilities;
93
+ /**
94
+ * Returns browser/WASM capabilities for a concrete JavaScript host.
95
+ *
96
+ * The static browser baseline describes package support. WebRTC additionally
97
+ * requires the browser primitive to exist at runtime. Passing the host keeps
98
+ * the resolver deterministic in SSR and test environments.
99
+ */
100
+ declare function runtimeCapabilitiesForBrowserHost(host?: BrowserRuntimeCapabilityHost | null | undefined): RuntimeCapabilities;
84
101
  declare function runtimeCapabilitiesFromNativeStatus(status: NativeRuntimeStatusSnapshot | null | undefined, allowWasmFallback?: boolean): RuntimeCapabilities;
85
102
  declare function runtimeCapabilityProfile(capabilities: RuntimeCapabilities): RuntimeCapabilityProfile;
86
103
 
@@ -170,6 +187,7 @@ declare abstract class DelegatingRuntimeAdapter implements ISignalingBackend {
170
187
  revokeSessionTokensByScope(scope: GrantScope): Promise<string[]>;
171
188
  openPeerBi(id: string, timeoutMs?: number): Promise<BackendPeerBiStream>;
172
189
  incoming_streams(): Promise<ReadableStream<unknown>>;
190
+ is_current_transport_stable_id(endpointId: string, transportStableId: bigint): Promise<boolean>;
173
191
  openPeerNativeBi(id: string, label: string, timeoutMs?: number): Promise<BackendPeerBiStream>;
174
192
  openPeerBiTransportOnly(id: string, timeoutMs?: number): Promise<BackendPeerBiStream>;
175
193
  openPeerUni(id: string, timeoutMs?: number): Promise<BackendPeerUniStream>;
@@ -198,4 +216,4 @@ declare abstract class DelegatingRuntimeAdapter implements ISignalingBackend {
198
216
  setCoreClient(client: unknown): void;
199
217
  }
200
218
 
201
- export { BROWSER_WASM_RUNTIME_CAPABILITIES as B, DelegatingRuntimeAdapter as D, NATIVE_IPC_RUNTIME_CAPABILITIES as N, type RuntimeCapabilities as R, type WasmBridgeOptions as W, type RuntimeCapabilityProfile as a, type RuntimeAdapterKind as b, type NativeRuntimeStatusSnapshot as c, type NativeRuntimeTransportFeatureStatus as d, cloneRuntimeCapabilities as e, runtimeCapabilityProfile as f, runtimeCapabilitiesFromNativeStatus as r };
219
+ export { BROWSER_WASM_RUNTIME_CAPABILITIES as B, DelegatingRuntimeAdapter as D, NATIVE_IPC_RUNTIME_CAPABILITIES as N, type RuntimeCapabilities as R, type WasmBridgeOptions as W, type RuntimeCapabilityProfile as a, type RuntimeAdapterKind as b, type BrowserRuntimeCapabilityHost as c, type NativeRuntimeStatusSnapshot as d, type NativeRuntimeTransportFeatureStatus as e, cloneRuntimeCapabilities as f, runtimeCapabilitiesFromNativeStatus as g, runtimeCapabilityProfile as h, runtimeCapabilitiesForBrowserHost as r };
@@ -1,5 +1,5 @@
1
- import { C as ClientOptions } from './types-CzIpGV9x.js';
2
- import { W as WasmBridgeOptions, D as DelegatingRuntimeAdapter } from './DelegatingRuntimeAdapter-By7pziBs.js';
1
+ import { C as ClientOptions } from './types-ByZyADCn.js';
2
+ import { W as WasmBridgeOptions, D as DelegatingRuntimeAdapter } from './DelegatingRuntimeAdapter-D2_dgabz.js';
3
3
 
4
4
  type PlutoIpcUnlisten = () => void | Promise<void>;
5
5
  interface PlutoIpcBridge {
@@ -1 +1 @@
1
- export{H as authHost,G as getAuthHost,F as registerDesktopAuthRelay}from'../chunk-A2ENDDFR.js';
1
+ export{H as authHost,G as getAuthHost,F as registerDesktopAuthRelay}from'../chunk-34LATQZZ.js';import'../chunk-C7YN5MSV.js';
@@ -1 +1 @@
1
- export{F as registerDesktopAuthRelay}from'../chunk-A2ENDDFR.js';
1
+ export{F as registerDesktopAuthRelay}from'../chunk-34LATQZZ.js';import'../chunk-C7YN5MSV.js';
@@ -0,0 +1,2 @@
1
+ import {c as c$1}from'./chunk-C7YN5MSV.js';import {getApps,initializeApp}from'firebase/app';import {getFunctions,connectFunctionsEmulator,httpsCallable}from'firebase/functions';import {browserLocalPersistence,inMemoryPersistence,browserPopupRedirectResolver,initializeAuth,getAuth,connectAuthEmulator,setPersistence,onIdTokenChanged,getIdToken,signInWithCustomToken,onAuthStateChanged,signInAnonymously,signInWithEmailAndPassword,createUserWithEmailAndPassword,signOut,deleteUser,updateProfile,GoogleAuthProvider,OAuthProvider,signInWithCredential,signInWithPopup,signInWithRedirect,getRedirectResult}from'firebase/auth';function N(){return typeof window>"u"?false:!!(window.__TAURI_IPC__||window.__TAURI_INTERNALS__||window.__TAURI__||window.location.protocol==="tauri:"||window.location.hostname==="tauri.localhost")}var E=new Set;function S(e,t){E.has(e)||(E.add(e),console.warn(t));}function oe(e){return /^pk_(live|test)_[0-9a-f]{40}$/.test(e)}async function He(e,t){let n=`${e}:${t}`,o=new TextEncoder().encode(n),i=await crypto.subtle.digest("SHA-256",o);return Array.from(new Uint8Array(i)).map(d=>d.toString(16).padStart(2,"0")).join("")}function I(e){let t=typeof e.apiKey=="string"?e.apiKey.trim():"";if(t)return oe(t)||S(`invalid-api-key:${t.slice(0,10)}`,"[pluto-rtc] The provided `apiKey` does not match the expected format (pk_live_... or pk_test_...). Create an app at https://api.openrtc.app/developer."),`app_${t.slice(-16)}`;throw new Error("[openrtc] `apiKey` is required. Create an app at https://api.openrtc.app/developer.")}function T(e){return e.authMode?e.authMode:("apiKey"in e&&typeof e.apiKey=="string"&&e.apiKey.trim().length>0&&typeof(e.spaceKey??e.space)=="string"&&(e.spaceKey??e.space).trim().length>0||S("default-auth-mode","[pluto-rtc] `authMode` is not set; defaulting to `anonymous` for compatibility."),"anonymous")}function Be(e){let t=typeof e.projectId=="string"?e.projectId.trim():"";return t||(S("default-project-id","[pluto-rtc] `projectId` is not set; defaulting to the built-in PlutoRTC Firebase project."),P)}function L(e){return e.trim().replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"")}function Fe(e){let t="storagePrefix"in e&&typeof e.storagePrefix=="string"?L(e.storagePrefix):"";return t||L(I(e))||"default"}var We={devicesPerUser:2,maxRooms:10,maxMembersPerRoom:5,maxPersonalDevices:25};var ie=[{urls:"stun:stun.l.google.com:19302"},{urls:"stun:stun.cloudflare.com:3478"}],H={iceServers:ie},Ke={};var B=["iroh-relay","iroh","moq"];function ae(e){return (Array.isArray(e.urls)?e.urls:[e.urls]).some(n=>typeof n=="string"&&(n.startsWith("turn:")||n.startsWith("turns:")))}function se(e){let n=(Array.isArray(e.urls)?e.urls:[e.urls]).filter(r=>typeof r=="string"&&!r.startsWith("stun:"));return n.length===0?null:{...e,urls:Array.isArray(e.urls)?n:n[0]}}function R(e){if(e)return e.map(t=>se(t)).filter(t=>t!==null)}function F(e,t){let n=new Set(["iroh-relay","iroh","moq"]);t&&n.add("webrtc");let r=(e??B).filter(o=>n.has(o));return r.length>0?r:[...B]}function Ge(e){return !!e?.transports?.webrtc}function ze(e,t){let n=e?.transports?.webrtc||void 0;if(n)return e?.strictMode||n.privacyMode?{...n,iceServers:R(n.iceServers),iceTransportPolicy:"relay"}:n.iceTransportPolicy==="relay"&&!(Array.isArray(n.iceServers)&&n.iceServers.some(o=>ae(o)))?(t?.("[Client] Overriding relay-only ICE policy to all because no TURN servers are configured"),{...n,iceTransportPolicy:"all"}):n}var ce=/^[A-Za-z0-9._-]+$/,le="[redacted]";function q(e){let t;try{t=new URL(e);}catch{throw new Error("[OpenRTC] transports.moq.relayUrl must be a valid HTTPS URL.")}if(t.protocol!=="https:")throw new Error("[OpenRTC] transports.moq.relayUrl must use HTTPS/WebTransport.");if(t.hash)throw new Error("[OpenRTC] transports.moq.relayUrl must not contain a fragment.");if(t.searchParams.has("jwt"))throw new Error("[OpenRTC] transports.moq.relayUrl must not contain a jwt query parameter; use transports.moq.accessToken.");return t}function C(e){return q(e.trim()).toString()}function $e(e,t){let n=q(e.trim());if(t!==void 0){let r=t.trim();if(!r)throw new Error("[OpenRTC] transports.moq.accessToken must not be empty when provided.");if(new TextEncoder().encode(r).byteLength>16384)throw new Error("[OpenRTC] transports.moq.accessToken exceeds the maximum supported size.");if(!ce.test(r))throw new Error("[OpenRTC] transports.moq.accessToken must be a URL-safe JWT.");n.searchParams.append("jwt",r);}return n.toString()}function Ye(e){try{let t=new URL(e);return t.search="",t.hash="",t.toString()}catch{return "invalid-moq-relay-url"}}function Ve(e,t){let n=e instanceof Error?`${e.name}: ${e.message}`:String(e),r=t?.trim();return r?n.split(r).join(le):n}var de=[...c$1];function A(e){let t=e.spaceKey??e.space;return {...e,...t!==void 0?{spaceKey:t}:{}}}function W(e){return {...e,iceServers:e.iceServers?e.iceServers.map(t=>({...t})):e.iceServers}}function ue(e){return {...e}}function pe(e){return {...e}}function me(e){if(e)return {iroh:typeof e.iroh=="object"?pe(e.iroh):e.iroh,webrtc:typeof e.webrtc=="object"?W(e.webrtc):e.webrtc,ble:typeof e.ble=="object"?{...e.ble}:e.ble,moq:typeof e.moq=="object"?ue(e.moq):e.moq}}function ge(e){if(e.strictMode&&!e.transports&&(e.transports={iroh:{relayOnly:true}}),!!e.transports){if(e.transports.webrtc===true?e.transports.webrtc=W(H):e.transports.webrtc===false&&(e.transports.webrtc=void 0),e.transports.moq===true)throw new Error("[OpenRTC] transports.moq=true is ambiguous because no anonymous MoQ relay is available; provide transports.moq.relayUrl explicitly.");if(e.transports.moq===false)e.transports.moq=void 0;else if(e.transports.moq&&typeof e.transports.moq=="object"){let t=e.transports.moq,n=t.relayUrl?.trim(),r=t.accessToken;if(r!==void 0&&!r.trim())throw new Error("[OpenRTC] transports.moq.accessToken must not be empty when provided.");e.transports.moq={...t,...n?{relayUrl:C(n)}:{},...r!==void 0?{accessToken:r.trim()}:{}};}e.transports.iroh===true?e.transports.iroh={}:e.transports.iroh===false&&(e.transports.iroh=void 0);}}function ye(e){if(!e.strictMode||!e.transports)return;let t=e.transports.iroh&&typeof e.transports.iroh=="object"?e.transports.iroh:{};e.transports.iroh={...t,relayOnly:true,relayTransportPolicy:t.relayTransportPolicy??"websocketRequired",localDiscovery:false,localDiscoveryMode:void 0},e.transports.ble=void 0;let n=e.transports.webrtc;n&&typeof n=="object"&&(e.transports.webrtc={...n,privacyMode:true,lanMode:false,iceServers:R(n.iceServers)??[],iceTransportPolicy:"relay"});let r=e.transports.moq;if(r&&typeof r=="object"){let o=r.relayUrl?.trim();if(!o)throw new Error("[OpenRTC] strictMode requires an explicit transports.moq.relayUrl.");e.transports.moq={...r,relayUrl:C(o)};}}function rt(e){let t=A(e),n=I(t),r=T(t),o={strictMode:false,disableIrohFallback:false,transportPriority:[...de],...t,authMode:r,transports:me(t.transports)};ge(o),ye(o),o.strictMode&&(o.transportPriority=F(t.transportPriority,!!o.transports?.webrtc));let i=K(o),a=(o.discoveryMode??"space")==="space"?"client-open":"client-auth";return {appTag:n,authMode:r,configuredPersistenceMode:i,options:o,roomCreationMode:a}}function K(e){let t=e.transports?.iroh;return e.endpointIdPersistence??e.nodeIdPersistence??(typeof t=="object"?t.persistenceMode:void 0)??"ephemeral"}function ot(e){return "options"in e&&"configuredPersistenceMode"in e?{apiKey:e.options.apiKey,authMode:T(e.options),projectId:e.options.projectId,storagePrefix:e.options.storagePrefix,nodeIdPersistence:e.configuredPersistenceMode}:{apiKey:e.apiKey,authMode:T(e),projectId:e.projectId,storagePrefix:e.storagePrefix,nodeIdPersistence:K(e)}}function it(e,t){t&&(e.transports={...e.transports||{},...t});}var P="pluto-rtc-prod",j={apiKey:"AIzaSyA62Krj-7ZYFT5xjrTUq7mXana41Ahj_mM",authDomain:"api.openrtc.app",projectId:P,storageBucket:"pluto-rtc-prod.firebasestorage.app",messagingSenderId:"607066575224",appId:"1:607066575224:web:ed3f51825ba228db92b88d"};function ct(e){let t=A(e),n=typeof t.projectId=="string"&&t.projectId.trim()?t.projectId.trim():P;return {...t,projectId:n}}function G(e){return new Promise(t=>setTimeout(t,e))}function dt(e){let t=new Uint8Array(e.byteLength);return t.set(e),t}function ut(e){let t=e.reduce((o,i)=>o+i.byteLength,0),n=new Uint8Array(t),r=0;for(let o of e)n.set(o,r),r+=o.byteLength;return n}function pt(e,t,n){let r=t*Math.pow(2,Math.max(0,e-1));return Math.min(n,r)}function mt(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 gt(e,t,n){let r=e;if(!r)return null;try{let o=r.send,i=r.recv;if(!o||typeof o.getWriter!="function"||!i||typeof i.getReader!="function")return null;let a=typeof r.endpoint_id=="string"&&r.endpoint_id.trim().length>0?r.endpoint_id:t,l=Number.isSafeInteger(r.transport_stable_id)&&Number(r.transport_stable_id)>0?Number(r.transport_stable_id):void 0,d=Number.isSafeInteger(n)&&Number(n)>0?Number(n):void 0;if(l!==void 0&&d!==void 0&&l!==d)return null;let s=l??d;return {send:o,recv:i,endpoint_id:a,...s?{transport_stable_id:s}:{}}}catch{return null}}function yt(e,t){let n={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&&(n.applicationCryptoWrapped=true),n}async function ft(e,t){if(!e)return false;try{let n=e.send?.getWriter?.();if(n)try{await n.close();}catch{}finally{try{n.releaseLock();}catch{}}}catch{}try{let n=e.recv?.getReader?.();if(n)try{await n.cancel(t);}catch{}finally{try{n.releaseLock();}catch{}}}catch{}return true}function ht(e,t,n={}){let r=n.context??"prependBytesToReader",o=n.traceId,i=t.byteLength===0,a=n.pendingRead??null,l=s=>n.release?.(s),d=(s,p)=>n.log?.(s,p);return new ReadableStream({async pull(s){if(!i){i=true,s.enqueue(t);return}if(a){let u=a;a=null;let m;try{m=await u;}catch(y){s.error(y),l("pending-read-error"),d("prepend-bytes:pending-read-error",{context:r,traceId:o||null,error:y?.message||String(y)});return}if(m.done){s.close(),l("pending-done");return}m.value&&s.enqueue(m.value);return}let p;try{p=await e.read();}catch(u){s.error(u),l("read-error"),d("prepend-bytes:read-error",{context:r,traceId:o||null,error:u?.message||String(u)});return}let{done:v,value:b}=p;if(v){s.close(),l("done");return}b&&s.enqueue(b);},async cancel(s){l("cancel");}})}async function bt(e,t){let n=e.read(),r=t-Date.now();if(r<=0)return {status:"timeout",pendingRead:n};let o=Symbol("probe-timeout"),i,a=new Promise(l=>{i=setTimeout(()=>l(o),r);});try{let l=await Promise.race([n,a]);if(l===o)return {status:"timeout",pendingRead:n};let{done:d,value:s}=l;return d?{status:"done"}:{status:"data",value:s&&s.byteLength>0?new Uint8Array(s):new Uint8Array(0)}}finally{i&&clearTimeout(i);}}function z(e,t,n){let r;return new Promise((o,i)=>{r=setTimeout(()=>{if(r=void 0,typeof n=="function"){i(n());return}let a=n?`${n} timed out`:"timeout";i(new Error(`${a} after ${t}ms`));},t),e.then(a=>{r!==void 0&&clearTimeout(r),o(a);},a=>{r!==void 0&&clearTimeout(r),i(a);});})}var X="pluto-rtc-auth",M=null;function _e(){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 c(e,t){if(_e()){if(typeof t>"u"){console.log(e);return}console.log(e,t);}}function Dt(e){M=e;}function De(){return N()}function ne(){return typeof navigator>"u"?false:/iPhone|iPad|iPod|Android/i.test(navigator.userAgent||"")}function Z(){return De()&&ne()}function g(e,t,n){return z(e,t,()=>new Error(`${n} timeout after ${t}ms`))}function ee(e){let t="0123456789ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvwxyz-._",n=new Uint8Array(e);window.crypto.getRandomValues(n);let r="";for(let o=0;o<e;o+=1)r+=t[n[o]%t.length];return r}async function te(e){let n=new TextEncoder().encode(e),r=await crypto.subtle.digest("SHA-256",n);return Array.from(new Uint8Array(r)).map(i=>i.toString(16).padStart(2,"0")).join("")}var _=class{constructor(){this.redirectResultPromise=null;this.redirectResultConsumed=false;this.lastRelayedToken=null;this.lastRelayedRefreshToken=null;this.desktopTokenRefreshIntervalId=null;let t=getApps().find(o=>o.name===X);this.app=t||initializeApp(j,X);let n=ne(),r=Z();if(n)try{let o=r?{persistence:[browserLocalPersistence,inMemoryPersistence]}:{persistence:[browserLocalPersistence,inMemoryPersistence],popupRedirectResolver:browserPopupRedirectResolver};this.auth=initializeAuth(this.app,o),c("[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);try{let o=typeof globalThis<"u"?String(globalThis.__OPENRTC_AUTH_EMULATOR_HOST__??"").trim():"",i=typeof globalThis<"u"?String(globalThis.__OPENRTC_FUNCTIONS_EMULATOR_HOST__??"").trim():"",a=typeof import.meta<"u"?import.meta.env:null;if(!!o||!!i||!!a&&String(a.VITE_USE_EMULATORS)==="true"&&(a.DEV||String(a.VITE_E2E)==="true")){let d=String(a?.VITE_OPENRTC_EMULATOR_HOST??"127.0.0.1").trim()||"127.0.0.1",[s,p]=o.split(":"),[v,b]=i.split(":"),u=(s??"").trim()||d,m=(v??"").trim()||d,y=Number(p??a?.VITE_OPENRTC_AUTH_EMULATOR_PORT??9100),re=Number(b??a?.VITE_OPENRTC_FUNCTIONS_EMULATOR_PORT??5002);try{connectAuthEmulator(this.auth,`http://${u}:${y}`,{disableWarnings:!0});}catch{}try{connectFunctionsEmulator(this.functions,m,re);}catch{}}}catch{}n?this.persistenceReady=Promise.resolve():this.persistenceReady=setPersistence(this.auth,browserLocalPersistence).catch(o=>{console.warn("[PLUTO-RTC][AUTH-HOST] Failed to set auth persistence",{message:o?.message});}),c("[PLUTO-RTC][AUTH-HOST] Initialized auth host",{appName:this.app.name,mobileSafeAuth:n}),onIdTokenChanged(this.auth,o=>{c("[PLUTO-RTC][AUTH-HOST] Firebase ID token changed",{hasUser:!!o,uid:o?.uid,providerDataCount:o?.providerData?.length||0}),this.syncDesktopAuthToken(o);}),this.desktopTokenRefreshIntervalId||(this.desktopTokenRefreshIntervalId=setInterval(()=>{this.syncDesktopAuthToken(this.auth.currentUser,true);},600*1e3));}async syncDesktopAuthToken(t,n=false){if(!M)return;let r=t?await getIdToken(t,n).catch(()=>null):null,o=t?t.refreshToken??null:null;if(r===this.lastRelayedToken&&o===this.lastRelayedRefreshToken)return;this.lastRelayedToken=r,this.lastRelayedRefreshToken=o;let i=await Promise.allSettled([Promise.resolve(M({authToken:r,refreshToken:o}))]);i[0]?.status==="rejected"&&console.warn("[PLUTO-RTC][AUTH-HOST] Failed to relay auth token to desktop backend",{message:i[0].reason?.message});}getApp(){return this.app}getCurrentUser(){return this.auth.currentUser}getAuth(){return this.auth}onAuthStateChanged(t){return c("[PLUTO-RTC][AUTH-HOST] onAuthStateChanged listener registered (via onIdTokenChanged)"),onIdTokenChanged(this.auth,t)}onIdTokenChanged(t){return c("[PLUTO-RTC][AUTH-HOST] onIdTokenChanged listener registered"),onIdTokenChanged(this.auth,t)}async getIdToken(t){return this.auth.currentUser?getIdToken(this.auth.currentUser,t?.forceRefresh??true):null}async checkForSSOToken(){if(typeof window>"u")return;let t=new URLSearchParams(window.location.search),n=new URLSearchParams(window.location.hash.startsWith("#")?window.location.hash.slice(1):window.location.hash),r=t.get("token")||n.get("token")||(t.get("custom_token")==="true"||n.get("custom_token")==="true"?t.get("id_token")||n.get("id_token"):null);if(r)try{await this.persistenceReady,await signInWithCustomToken(this.auth,r),window.history.replaceState({},document.title,window.location.pathname);}catch(o){console.error("[PLUTO-RTC][AUTH-HOST] SSO sign-in failed:",o);}}async signInWithCustomTokenValue(t){return await this.persistenceReady,(await signInWithCustomToken(this.auth,t)).user}async signInWithPluto(t){if(typeof window>"u")throw new Error("Pluto SSO requires a browser environment.");let n=t?.redirectUri||window.location.href,r=t?.authorizeBaseUrl||"https://pluto.openrtc.app/sso/authorize",o=new URL(r);o.searchParams.set("redirect_uri",n),window.location.assign(o.toString());}async waitForAuth(){if(await this.persistenceReady,!this.auth.currentUser)return new Promise(t=>{let n=onAuthStateChanged(this.auth,r=>{r&&(n(),t());});})}async signInAnonymously(){await signInAnonymously(this.auth);}async signIn(t,n){return (await signInWithEmailAndPassword(this.auth,t,n)).user}async signUp(t,n){return (await createUserWithEmailAndPassword(this.auth,t,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(t){let n=Date.now();if(c("[PLUTO-RTC][AUTH-HOST] signInWithCredential start",{callbackId:t.callbackId,provider:t.provider,hasIdToken:!!t.idToken,hasAccessToken:!!t.accessToken,hasNonce:!!t.nonce}),t.isCustomToken){c("[PLUTO-RTC][AUTH-HOST] signInWithCredential: custom token detected, using signInWithCustomToken");try{if(Z())c("[PLUTO-RTC][AUTH-HOST] Skipping authStateReady before custom token sign-in on Tauri mobile",{callbackId:t.callbackId});else {c("[PLUTO-RTC][AUTH-HOST] Awaiting authStateReady...");try{await g(this.auth.authStateReady(),5e3,"authStateReady"),c("[PLUTO-RTC][AUTH-HOST] Auth state ready, signing in with custom token...");}catch(a){console.warn("[PLUTO-RTC][AUTH-HOST] authStateReady did not resolve in time; continuing custom token sign-in",{callbackId:t.callbackId,message:a?.message});}}let i;try{i=await g(signInWithCustomToken(this.auth,t.idToken),25e3,"signInWithCustomToken (custom token path)");}catch(a){console.warn("[PLUTO-RTC][AUTH-HOST] First custom token sign-in attempt failed; retrying once",{callbackId:t.callbackId,message:a?.message,code:a?.code}),await G(250),i=await g(signInWithCustomToken(this.auth,t.idToken),25e3,"signInWithCustomToken (custom token path retry)");}if(c("[PLUTO-RTC][AUTH-HOST] signInWithCustomToken success",{callbackId:t.callbackId,provider:t.provider,uid:i.user?.uid,elapsedMs:Date.now()-n}),i.user&&(t.displayName||t.photoURL))try{await updateProfile(i.user,{displayName:t.displayName||i.user.displayName||void 0,photoURL:t.photoURL||i.user.photoURL||void 0});}catch(a){console.warn("[PLUTO-RTC][AUTH-HOST] Failed to update custom-token user profile",{callbackId:t.callbackId,message:a?.message});}return i.user}catch(o){throw console.error("[PLUTO-RTC][AUTH-HOST] signInWithCustomToken failed",{callbackId:t.callbackId,error:o?.message,code:o?.code,stack:o?.stack,elapsedMs:Date.now()-n}),o}}let r;t.provider==="google"?r=GoogleAuthProvider.credential(t.idToken,t.accessToken):r=new OAuthProvider("apple.com").credential({idToken:t.idToken,rawNonce:t.nonce,accessToken:t.accessToken});try{let o=await g(signInWithCredential(this.auth,r),1e4,"firebase signInWithCredential");return c("[PLUTO-RTC][AUTH-HOST] signInWithCredential success",{callbackId:t.callbackId,provider:t.provider,uid:o.user?.uid,elapsedMs:Date.now()-n}),o.user}catch(o){console.warn("[PLUTO-RTC][AUTH-HOST] signInWithCredential primary path failed; trying custom token fallback",{callbackId:t.callbackId,provider:t.provider,elapsedMs:Date.now()-n,code:o?.code,message:o?.message});let i=await g(this.mintSessionTokenFromProviderToken(t),15e3,"mintSessionTokenFromProviderToken"),a=await g(signInWithCustomToken(this.auth,i),15e3,"signInWithCustomToken");return c("[PLUTO-RTC][AUTH-HOST] signInWithCustomToken fallback success",{callbackId:t.callbackId,provider:t.provider,uid:a.user?.uid,elapsedMs:Date.now()-n}),a.user}}async mintSessionTokenFromProviderToken(t){let n=httpsCallable(this.functions,"mintSessionToken");c("[PLUTO-RTC][AUTH-HOST] mintSessionToken fallback request start",{provider:t.provider,hasIdToken:!!t.idToken,hasNonce:!!t.nonce});let o=(await n({provider:t.provider,idToken:t.idToken,nonce:t.nonce})).data?.token;if(!o)throw new Error("mintSessionToken did not return a token for provider exchange");return c("[PLUTO-RTC][AUTH-HOST] mintSessionToken fallback request success",{provider:t.provider}),o}async signInWithPopup(t){if(t==="google"){let i=new GoogleAuthProvider;i.addScope("email"),i.addScope("profile"),i.setCustomParameters({prompt:"select_account"});let a=await signInWithPopup(this.auth,i);return {idToken:await getIdToken(a.user,true),refreshToken:a.user.refreshToken}}let n=new OAuthProvider("apple.com");n.addScope("email"),n.addScope("name");let r=ee(32);typeof sessionStorage<"u"&&sessionStorage.setItem("apple_auth_nonce",r),n.setCustomParameters({nonce:await te(r)});let o=await signInWithPopup(this.auth,n);return {idToken:await getIdToken(o.user,true),refreshToken:o.user.refreshToken}}async signInWithRedirect(t,n){if(t==="google"){let i=new GoogleAuthProvider;i.addScope("email"),i.addScope("profile"),i.setCustomParameters({prompt:"select_account"}),await signInWithRedirect(this.auth,i);return}let r=new OAuthProvider("apple.com");r.addScope("email"),r.addScope("name");let o=n?.nonce||ee(32);typeof sessionStorage<"u"&&sessionStorage.setItem("apple_auth_nonce",o),r.setCustomParameters({nonce:await te(o)}),await signInWithRedirect(this.auth,r);}async consumeRedirectResult(){return this.redirectResultConsumed?(c("[PLUTO-RTC][AUTH-HOST] consumeRedirectResult skipped (already consumed)"),null):this.redirectResultPromise?this.redirectResultPromise:(this.redirectResultPromise=(async()=>{try{c("[PLUTO-RTC][AUTH-HOST] consumeRedirectResult start");let t=await getRedirectResult(this.auth);if(!t)return c("[PLUTO-RTC][AUTH-HOST] consumeRedirectResult: no redirect result"),{fromRedirect:!1,user:null};this.redirectResultConsumed=!0;let n=await getIdToken(t.user,!0).catch(()=>null),r=t.providerId||t.user.providerData?.[0]?.providerId||null;return c("[PLUTO-RTC][AUTH-HOST] consumeRedirectResult success",{uid:t.user.uid,providerId:r,hasIdToken:!!n}),{fromRedirect:!0,user:t.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 r=(await httpsCallable(this.functions,"mintSessionToken")()).data;if(!r?.token)throw new Error("mintSessionToken did not return a token");return r.token}},O=null;function Ne(){return O||(O=new _),O}var Nt=new Proxy({},{get(e,t,n){let r=Ne(),o=r[t];return typeof o=="function"?o.bind(r):o}});
2
+ export{yt as A,ft as B,ht as C,bt as D,z as E,Dt as F,Ne as G,Nt as H,N as a,He as b,I as c,T as d,Be as e,Fe as f,We as g,ie as h,H as i,Ke as j,Ge as k,ze as l,$e as m,Ye as n,Ve as o,A as p,rt as q,ot as r,it as s,ct as t,G as u,dt as v,ut as w,pt as x,mt as y,gt as z};
@@ -0,0 +1 @@
1
+ import {F,E}from'./chunk-MESPJTUA.js';var n=class extends F{constructor(e){super(new E(e));}setWasmClient(e){this.unwrap().setWasmClient(e);}};export{n as a};
@@ -0,0 +1 @@
1
+ var t=Object.freeze([Object.freeze({id:"iroh-lan",baseProtocol:"iroh",family:"iroh-path",implementation:"path-label",locality:"nearby",maturity:"stable",defaultRank:0,browser:false,native:true,independentlyInstantiable:false}),Object.freeze({id:"webrtc-lan",baseProtocol:"webrtc",family:"optional-route",implementation:"path-label",locality:"nearby",maturity:"stable",defaultRank:1,browser:true,native:true,independentlyInstantiable:false}),Object.freeze({id:"ble",baseProtocol:"iroh",family:"iroh-physical",implementation:"host-installed",locality:"nearby",maturity:"experimental",defaultRank:2,browser:false,native:true,independentlyInstantiable:false}),Object.freeze({id:"webrtc",baseProtocol:"webrtc",family:"optional-route",implementation:"route-adapter",locality:"mixed",maturity:"stable",defaultRank:3,browser:true,native:true,independentlyInstantiable:true}),Object.freeze({id:"moq",baseProtocol:"moq",family:"optional-route",implementation:"route-adapter",locality:"relay",maturity:"experimental",defaultRank:4,browser:true,native:true,independentlyInstantiable:true}),Object.freeze({id:"iroh",baseProtocol:"iroh",family:"iroh-path",implementation:"core",locality:"mixed",maturity:"stable",defaultRank:5,browser:true,native:true,independentlyInstantiable:false}),Object.freeze({id:"iroh-quic",baseProtocol:"iroh",family:"iroh-path",implementation:"path-label",locality:"direct-internet",maturity:"stable",defaultRank:6,browser:false,native:true,independentlyInstantiable:false}),Object.freeze({id:"iroh-relay",baseProtocol:"iroh",family:"iroh-path",implementation:"path-label",locality:"relay",maturity:"stable",defaultRank:7,browser:true,native:true,independentlyInstantiable:false}),Object.freeze({id:"webrtc-turn",baseProtocol:"webrtc",family:"optional-route",implementation:"path-label",locality:"relay",maturity:"stable",defaultRank:8,browser:true,native:true,independentlyInstantiable:false})]),o=Object.freeze(Object.fromEntries(t.map(e=>[e.id,e]))),r=Object.freeze(["iroh-lan","webrtc-lan","ble","webrtc","moq","iroh","iroh-quic","iroh-relay","webrtc-turn"]),a=Object.freeze(["iroh-lan","webrtc-lan","ble","webrtc","moq","iroh"]),l=Object.freeze({iroh:80,"iroh-quic":30,"iroh-relay":70,"iroh-lan":10,ble:25,webrtc:40,"webrtc-lan":20,"webrtc-turn":60,moq:50});var i=t,n=o,b=r,s=a,m=l;function p(e){return n[e]}function u(){return i}export{i as a,b,s as c,m as d,p as e,u as f};
@@ -0,0 +1,2 @@
1
+ import {w,F,C,E,A,c,p,b as b$1,o,r,s,t,u as u$1,v as v$1}from'./chunk-MESPJTUA.js';import {x,u,b,h,a,E as E$1,G}from'./chunk-34LATQZZ.js';function ie(d){let e=String(d?.message??d??"").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 O(d){return ie(d)==="command-unavailable"}function T(d,e="native runtime"){if(!d||typeof d!="object")throw new Error(`[openrtc] ${e} requires a valid IPC bridge object.`);if(typeof d.invoke!="function")throw new Error(`[openrtc] ${e} IPC bridge is missing invoke(command, args).`);if(typeof d.listen!="function")throw new Error(`[openrtc] ${e} IPC bridge is missing listen(event, handler).`);return d}var B=null;async function ne(){return B||(B=(async()=>{let d="openrtc-tauri",e="../../../tauri/src/runtime/ipc";try{return await import(d)}catch(t){try{return await import(e)}catch(i){let n=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 n.cause={packageError:t,workspaceError:i},n}}})()),B}function Q(){let d=null,e=async()=>(d||(d=ne().then(t=>T(t.createTauriIpcBridge(),"openrtc-tauri"))),d);return {async invoke(t,i){return (await e()).invoke(t,i)},async listen(t,i){return (await e()).listen(t,i)},async isAvailable(){try{let t=await e();return typeof t.isAvailable=="function"?!!await t.isAvailable():!0}catch{return false}}}}var ae="relay-only endpoint ticket unavailable",re=12e3,se=250,oe=1500;function ce(d){return String(d?.message??d??"").toLowerCase().includes(ae)}async function q(d,e={}){let t=e.windowMs??re,i=e.minDelayMs??se,n=e.maxDelayMs??oe,r=Date.now(),s=0,a=null;for(;e.isActive?.()??true;){s+=1;try{return await d()}catch(u$1){if(a=u$1,!ce(u$1))throw u$1;let o=Date.now()-r;if(o>=t)throw u$1;let c=Math.min(x(s,i,n),Math.max(0,t-o));c>0&&await u(c);}}throw a||new Error("endpoint ticket minting stopped before a ticket was available")}function Z(d){let e=d?.split(".")[1];if(!e)return null;try{let t=e.replace(/-/g,"+").replace(/_/g,"/"),i=(4-t.length%4)%4,n=atob(t+"=".repeat(i)),r=JSON.parse(n);return r&&typeof r=="object"&&!Array.isArray(r)?r:null}catch{return null}}function X(d,e){let t=d?.[e];return typeof t=="string"&&t.trim()?t.trim():null}function ee(d,e){return X(d,"namespaceId")===e||X(d,"appTag")===`space::${e}`}var v=class v{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.nativeRuntimeCapabilitiesSyncInFlight=null;this.lastNativeAuthSyncAtMs=0;this.hasLoggedMissingAuthForDevices=false;this.runtimeCapabilities=C(null,false);this.fallback=new E(e),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=T(e.ipcBridge??Q(),"NativeIpcBridge"),this.runtimeCapabilities=C(null,this.allowWasmFallback),this.syncNativeRuntimeCapabilities("constructor");}get currentUser(){return this.fallback.currentUser}get tag(){return this.fallback.tag}getRuntimeCapabilities(){let e=A(this.runtimeCapabilities);return e.fallback.wasm=this.allowWasmFallback,e}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,n){return this.fallback.sendMessage(e,t,i,n)}pollMessages(e){return this.fallback.pollMessages(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 r=this.fallback;if(typeof r.incoming_streams=="function")return r.incoming_streams();throw new Error("Native incoming stream bridge is unavailable")}let e=`native-incoming-${Date.now()}-${++this.subscriptionNonce}`,t=null,i=false,n=async()=>{i=true;let r=t;t=null,await Promise.allSettled([r?Promise.resolve(r()):Promise.resolve(),this.invokeIpc("stop_rtc_subscription",{requestId:e},{timeoutMs:null}).catch(()=>{})]);};return new ReadableStream({start:async r=>{try{t=await this.listenIpc("openrtc://peer-bi-stream/incoming",s=>{if(i)return;let a=s.payload,u=typeof a?.requestId=="string"?a.requestId:typeof a?.request_id=="string"?a.request_id:"";if(u!==e){c("[NativeIpcBridge][incoming-application-stream] ignored request id",{expectedRequestId:e,eventRequestId:u});return}let o=typeof a?.streamId=="string"?a.streamId.trim():typeof a?.stream_id=="string"?a.stream_id.trim():"";if(!o)return;let c$1=typeof a?.remoteNodeId=="string"?a.remoteNodeId.trim():typeof a?.remote_node_id=="string"?a.remote_node_id.trim():"",l=Number.isSafeInteger(a?.transportStableId)?Number(a.transportStableId):Number.isSafeInteger(a?.transport_stable_id)?Number(a.transport_stable_id):0;if(!c$1||l<=0){c("[NativeIpcBridge][incoming-application-stream] ignored invalid generation",{requestId:e,remoteNodeId:c$1,transportStableId:l});return}c("[NativeIpcBridge][incoming-application-stream] accepted event",{requestId:e,remoteNodeId:c$1,transportStableId:l});let g=this.peerBiStreamFromId(o,{startReadAfterListeners:!0});r.enqueue({type:"bi",stream:{send:g.writable,recv:g.readable,endpoint_id:c$1},endpointId:c$1,transportStableId:l,protocolHint:"unknown",channel:null});}),await this.invokeIpc("start_incoming_peer_bi_streams",{requestId:e},{timeoutMs:null});}catch(s){i=true,r.error(s),await n();}},cancel:async()=>{await n();}})}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 n=await b(t,i).catch(()=>null);return n?ee(Z(e),n):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()?v.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=p(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,n=e.filter(r=>{let s=this.nativeRosterTagDisposition(r);return !s.keep&&s.foreignTag&&i.add(s.foreignTag),s.keep});return e.length>0&&n.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(`[NativeIpcBridge] ${t}: filtered ${e.length-n.length} foreign-app device(s) from the native roster`,{sdkAppTag:this.appTag,foreignTags:Array.from(i)}),n}normalizeNativeIceServer(e){let t=e.urls,i=Array.isArray(t)?t.filter(n=>typeof n=="string"&&n.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=null;if(!this.strictMode&&e?.iroh&&typeof e.iroh=="object"){let o=e.iroh;o.localDiscovery===true&&(t={enabled:true,advertise:o.localDiscoveryMode!=="passive"});}let i=null;if(e?.webrtc===true||e?.webrtc&&typeof e.webrtc=="object"){let o=e.webrtc===true?null:e.webrtc,c=o?.useDefaultIceServers!==false,l=Array.isArray(o?.iceServers)&&o.iceServers.length>0?o.iceServers.map(m=>this.normalizeNativeIceServer(m)).filter(m=>!!m):c?h.map(m=>this.normalizeNativeIceServer(m)).filter(m=>!!m):[],g=this.strictMode||o?.privacyMode===true;(this.strictMode||o?.privacyMode===true||o?.useTurn===true)&&(l=[...l,...await this.loadNativeTurnIceServers()]),g&&(l=this.filterNativeStunServers(l));let h$1=l.some(m=>this.nativeIceServerHasTurnUrl(m)),f=g&&h$1;g&&!h$1&&console.warn("[NativeIpcBridge] Relay-only WebRTC requested, but no TURN servers are configured; native WebRTC override disabled");let k=o?.lanMode===true;(l.length>0||f||k||!c)&&(i={iceServers:l.length>0||!c?l:void 0,privacyMode:f,lanMode:k||void 0});}let n=null;if(e?.moq&&typeof e.moq=="object"){let o=typeof e.moq.relayUrl=="string"&&e.moq.relayUrl.trim().length>0?e.moq.relayUrl:void 0;if(o){let c=typeof e.moq.accessToken=="string"&&e.moq.accessToken.trim().length>0?e.moq.accessToken.trim():void 0;n={relayUrl:o,accessToken:c};}}let r=null;if(!this.strictMode&&(e?.ble===true||e?.ble&&typeof e.ble=="object")){let o=e.ble===true?null:e.ble,c=Number(o?.connectTimeoutMs);r={enabled:o?.enabled!==false,connectTimeoutMs:Number.isFinite(c)&&c>0?Math.round(c):void 0};}let s=this.strictMode||e?.iroh&&typeof e.iroh=="object"&&e.iroh.relayOnly===true,a=e?.iroh&&typeof e.iroh=="object"?e.iroh.relayTransportPolicy:void 0,u=this.strictMode?a??"auto":a;return !s&&!u&&!i&&!n&&!t&&!r?null:{irohRelayOnly:s||void 0,irohRelayTransportPolicy:u,irohLan:t,webrtc:i,moq:n,ble:r}}isTauriEnv(){return a()}nextConnectionEventRetryDelayMs(e){return x(e,v.CONNECTION_EVENT_RETRY_MIN_DELAY_MS,v.CONNECTION_EVENT_RETRY_MAX_DELAY_MS)}async clearNativeAuthRelay(e){if(await this.canUseTauriIpc())try{await this.invokeIpc("desktop_set_pluto_auth_token",{authToken:null,refreshToken:null}),this.lastSyncedAuthToken=null,this.lastNativeAuthSyncAtMs=0,c(`[NativeIpcBridge] cleared native auth relay (${e})`);}catch(t){console.warn(`[NativeIpcBridge] failed clearing native auth relay (${e}):`,t);}}async relayNativeAuthToken(e,t,i,n){if(!await this.canUseTauriIpc())return true;if(!await this.nativeAuthTokenMatchesExpectedScope(e))return c(`[NativeIpcBridge] auth sync deferred (${i}): token claims do not match configured space`),false;if(e===this.lastSyncedAuthToken)return true;try{await this.invokeIpc("desktop_set_pluto_auth_token",{authToken:e,refreshToken:t??null});}catch(r){return O(r)?console.warn(`[NativeIpcBridge] desktop auth relay unavailable (${i}); install/register openrtc-tauri-plugin and include its default permission set.`,r):console.warn(`[NativeIpcBridge] desktop auth relay failed (${i}):`,r),false}return this.lastSyncedAuthToken=e,this.lastNativeAuthSyncAtMs=Date.now(),c(`[NativeIpcBridge] auth token relayed to native runtime (${i}) user_id=${n??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=C(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:v.NATIVE_STATUS_IPC_TIMEOUT_MS});this.applyNativeRuntimeStatus(t),c(`[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<v.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("[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("[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 n=this.ipcBridge.invoke(e,t),r=i&&Object.prototype.hasOwnProperty.call(i,"timeoutMs")?i.timeoutMs:v.DEFAULT_BOUNDED_IPC_TIMEOUT_MS;return r==null||r<=0?n:E$1(n,r,()=>new Error(`${e} timeout after ${r}ms`))}async listenIpc(e,t){return this.ipcBridge.listen(e,i=>{t({payload:i});})}async openPeerBiViaIpc(e,t,i){let n=await this.invokePeerBiOpen(e,t,i),r=typeof n?.streamId=="string"?n.streamId.trim():typeof n?.stream_id=="string"?n.stream_id.trim():"";if(!r)throw new Error(`${e} returned no streamId`);return this.peerBiStreamFromId(r)}peerBiStreamFromId(e,t={}){let i=this,n=null,r=null,s=false,a=null,u=null,o=async()=>{let h=[n,r];n=null,r=null,await Promise.allSettled(h.filter(f=>typeof f=="function").map(f=>Promise.resolve(f())));},c=(async()=>{n=await this.listenIpc("openrtc://peer-bi-stream/chunk",h=>{let f=h.payload;if((typeof f?.streamId=="string"?f.streamId:typeof f?.stream_id=="string"?f.stream_id:"")!==e||s||!a)return;let w=f?.bytes;w instanceof Uint8Array?a.enqueue(w):Array.isArray(w)&&a.enqueue(new Uint8Array(w));}),r=await this.listenIpc("openrtc://peer-bi-stream/closed",h=>{let f=h.payload;if((typeof f?.streamId=="string"?f.streamId:typeof f?.stream_id=="string"?f.stream_id:"")!==e||s||!a)return;s=true;let w=typeof f?.error=="string"?f.error.trim():"";w?a.error(new Error(w)):a.close(),o();}),t.startReadAfterListeners&&await this.invokeIpc("start_peer_bi_stream_read",{streamId:e},{timeoutMs:null});})().catch(h=>{u=h,a&&!s&&(s=true,a.error(h));}),l=async()=>{await this.invokeIpc("close_peer_bi_stream",{streamId:e},{timeoutMs:null}).catch(()=>{}),await o();},g=new ReadableStream({async start(h){a=h,await c,u&&!s&&(s=true,h.error(u));},async cancel(){s=true,await l();}}),y=new WritableStream({write:async h=>{await i.invokeIpc("write_peer_bi_stream",{streamId:e,bytes:Array.from(h)},{timeoutMs:null});},close:l,abort:l});return {readable:g,writable:y}}async invokePeerBiOpen(e,t,i){try{return await this.invokeIpc(e,t)}catch(n){if(!i?.fallbackCommand||!this.isMissingNativeCommandError(n))throw n;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 G().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,n=this.fallback.setAuthContext(e);if(t&&i&&t!==i&&await this.stopNativeAuthScopedActivity(t),await n,!e?.token)await this.clearNativeAuthRelay("setAuthContext");else if(!await this.relayExplicitNativeAuthContext(e))throw new Error("Native auth token unavailable for setAuthContext")}async signOut(){await this.fallback.signOut(),await this.clearNativeAuthRelay("signOut");}async stopAuthScopedActivity(e){let t=this.resolveNativeSignalingUserId(e?.userId??null);await this.stopNativeAuthScopedActivity(t);}async stopNativeAuthScopedActivity(e){let t=await this.shouldUseTauriSignaling();if(o("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"),e?this.invokeIpc("set_rtc_offline",{userId:e}):Promise.resolve()]);}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(`[NativeIpcBridge] auth sync deferred (${e}): no current user`),!t;let n=Date.now()-this.lastNativeAuthSyncAtMs>=480*1e3,r=this.currentUser?.getToken?await this.currentUser.getToken(n):null,a=this.getAuthContext()?.refreshToken??this.auth?.currentUser?.refreshToken??null;return r?this.relayNativeAuthToken(r,a,e,this.currentUser?.id):(c(`[NativeIpcBridge] auth sync deferred (${e}): missing token for user ${this.currentUser?.id}`),!t)}catch(n){return console.error("[NativeIpcBridge] auth sync failed:",n),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,n=t?.maxWaitMs??(i?v.AUTH_REQUIRED_WAIT_MS:0),r=t?.pollMs??250,s=Date.now()+Math.max(0,n);for(;;){if(await this.ensureNativeAuthOnce(e,i))return true;if(!i||Date.now()>=s)return false;await u(r);}}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():"",n=typeof e?.deviceName=="string"?e.deviceName.trim():typeof e?.device_name=="string"?e.device_name.trim():"",r=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:n,platformType:r}}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:n}=this.decodeNativeDeviceIdentity(t);if(i)return this.cachedLocalDeviceId=i,n&&(this.cachedLocalDeviceName=n),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"}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){if(await this.shouldUseTauriSignaling()){if(!await this.ensureNativeAuth("searchDevices",{requireToken:this.requiresNativeAuthToken(),maxWaitMs:this.nativeAuthWaitMs()}))throw new Error("Native auth token unavailable for searchDevices");let i=await this.invokeIpc("search_rtc_devices",{userId:this.getCurrentUserId()});if(Array.isArray(i?.devices)){let n=i.devices.map(r=>this.normalizeDevice(r));return e&&(n=n.filter(r=>r.ticket!==e&&r.deviceId!==e&&r.nodeId!==e)),n}throw typeof i?.message=="string"?new Error(String(i.message)):new Error("Unexpected response for search_rtc_devices")}return this.fallback.searchDevices(e)}async listDevicesWithStatus(){if(await this.shouldUseTauriSignaling()){if(!await this.ensureNativeAuth("listDevicesWithStatus",{requireToken:this.requiresNativeAuthToken(),maxWaitMs:this.nativeAuthWaitMs()}))throw new Error("Native auth token unavailable for listDevicesWithStatus");let t=await this.invokeIpc("search_rtc_devices_with_status",{userId:this.getCurrentUserId()});if(Array.isArray(t?.devices)){let i=t.devices,n=this.filterNativeRosterByTag(i,"listDevicesWithStatus").map(a=>r(a)),r$1=await this.resolveLocalDeviceId().catch(()=>null),s=!!r$1&&n.some(a=>a.deviceId===r$1);return b$1("[NativeIpcBridge] listDevicesWithStatus result",{rawCount:i.length,count:n.length,localDeviceId:r$1,selfIncluded:s,devices:n.map(a=>({deviceId:a.deviceId,deviceName:a.deviceName,online:!!a.online,presenceStatus:a.presenceStatus,connectable:a.connectable,connectionStatus:a.connectionStatus,settledReady:!!a.settledReady,peerHealth:a.peerHealth,scopes:a.scopes,connectionId:a.connectionId??null,deviceIdHint:a.deviceIdHint??null,nodeId:a.nodeId??null,activeTransport:a.activeTransport??null,parallelTransport:a.parallelTransport??null}))}),r$1&&!s&&b$1("[NativeIpcBridge] native status snapshot excludes local device by design",{localDeviceId:r$1,count:n.length}),n}throw typeof t?.message=="string"?new Error(String(t.message)):new Error("Unexpected response for search_rtc_devices_with_status")}return this.fallback.listDevicesWithStatus()}async getPeerSession(e){if(await this.shouldUseTauriSignaling()){let t=await this.invokeIpc("get_rtc_peer_session",{id:e});return !t||typeof t!="object"?null:s(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=>s(t))}return this.fallback.listPeerSessions()}async waitForSettledPeer(e,t){if(await this.shouldUseTauriSignaling()){let i=typeof t=="number"?Math.max(v.DEFAULT_BOUNDED_IPC_TIMEOUT_MS,t+1e3):v.DEFAULT_BOUNDED_IPC_TIMEOUT_MS,n=await this.invokeIpc("wait_for_rtc_settled_peer",{id:e,timeoutMs:t},{timeoutMs:i});return !n||typeof n!="object"?null:s(n)}return this.fallback.waitForSettledPeer(e,t)}async resolvePeerConnectionRecords(e){if(await this.shouldUseTauriSignaling()){let t$1=await this.invokeIpc("resolve_rtc_peer_connection_records",{id:e});return (Array.isArray(t$1)?t$1:[]).map(i=>t(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 u$1(t)}return this.fallback.resolvePeerIdentity(e)}async setOffline(e){if(await this.shouldUseTauriSignaling())try{if(!await this.ensureNativeAuth("setOffline",{requireToken:this.requiresNativeAuthToken(),maxWaitMs:this.nativeAuthWaitMs()}))throw new Error("Native auth token unavailable for setOffline");let i=this.getCurrentUserId();await this.invokeIpc("set_rtc_offline",{userId:i});return}catch(t){console.warn("[NativeIpcBridge] set_rtc_offline failed:",t);}return this.fallback.setOffline(e)}async updateDevice(e,t){if(await this.shouldUseTauriSignaling()){if(!await this.ensureNativeAuth("updateDevice",{requireToken:this.requiresNativeAuthToken(),maxWaitMs:this.nativeAuthWaitMs()}))throw new Error("Native auth token unavailable for updateDevice");let r=this.getCurrentUserId();if(!r)throw new Error("updateDevice requires authenticated user scope");try{await this.invokeIpc("update_rtc_device",{userId:r,deviceId:e,deviceName:t.deviceName??null,capabilities:t.capabilities??null,metadata:t.metadata??null});return}catch(s){throw console.warn("[NativeIpcBridge] update_rtc_device failed:",s),s instanceof Error?s:new Error(String(s))}}return this.fallback.updateDevice(e,t)}async deleteDevice(e){if(await this.shouldUseTauriSignaling()){if(!await this.ensureNativeAuth("deleteDevice",{requireToken:this.requiresNativeAuthToken(),maxWaitMs:this.nativeAuthWaitMs()}))throw new Error("Native auth token unavailable for deleteDevice");let n=this.getCurrentUserId();if(!n)throw new Error("deleteDevice requires authenticated user scope");try{await this.invokeIpc("delete_rtc_device",{userId:n,deviceId:e});return}catch(r){throw console.warn("[NativeIpcBridge] delete_rtc_device failed:",r),r instanceof Error?r:new Error(String(r))}}return 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:n}=i;return n?(this.cachedLocalDeviceName=this.normalizeNativeDeviceName(e),{deviceId:n,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(!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});let n=this.resolveConfiguredSpaceKey();console.info("[NativeIpcBridge][managed-session][start-request]",{requestedUserId:e.userId,runtimeUserId:this.currentUser?.id??this.getAuthContext()?.userId??null,effectiveUserId:i,spaceKey:n?"[configured]":null,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 r=await this.buildNativeTransportConfigPayload(),s={userId:i,deviceName:e.deviceName??null,localDeviceId:e.localDeviceId??null,metadata:e.metadata??null,...r?{transports:r}:{},autoConnect:e.autoConnect!==false,presence:e.presence!==false,apiKey:this.options.apiKey??null,spaceKey:n||null},a=await this.invokeIpc("start_rtc_managed_session",s,{timeoutMs:null});this.syncNativeRuntimeCapabilities("managed-session-started");let u=typeof a?.ticket=="string"&&a.ticket.trim().length>0?a.ticket.trim():null,o=a?.localDevice&&typeof a.localDevice=="object"?a.localDevice:a?.local_device&&typeof a.local_device=="object"?a.local_device:null,c=o?{deviceId:typeof o.deviceId=="string"?o.deviceId:typeof o.device_id=="string"?o.device_id:"",deviceName:this.normalizeNativeDeviceName(typeof o.deviceName=="string"?o.deviceName:typeof o.device_name=="string"?o.device_name:""),platformType:typeof o.platformType=="string"?o.platformType:typeof o.platform_type=="string"?o.platform_type:"desktop",capabilities:o.capabilities??void 0,lastSeenAt:typeof o.lastSeenAt=="string"?o.lastSeenAt:typeof o.last_seen_at=="string"?o.last_seen_at:void 0}:null,l={localNodeId:typeof a?.localNodeId=="string"?a.localNodeId:typeof a?.local_node_id=="string"?a.local_node_id:null,ticket:u,ticketScope:typeof a?.ticketScope=="string"?a.ticketScope:typeof a?.ticket_scope=="string"?a.ticket_scope:null,presenceStarted:typeof a?.presenceStarted=="boolean"?a.presenceStarted:!!a?.presence_started,autoConnectStarted:typeof a?.autoConnectStarted=="boolean"?a.autoConnectStarted:!!a?.auto_connect_started,localDevice:c?.deviceId?c:null};return console.info("[NativeIpcBridge][managed-session][ipc-started]",{requestedUserId:e.userId,runtimeUserId:this.currentUser?.id??this.getAuthContext()?.userId??null,effectiveUserId:i,localNodeId:l.localNodeId,ticketScope:l.ticketScope,presenceStarted:l.presenceStarted,autoConnectStarted:l.autoConnectStarted,localDeviceId:l.localDevice?.deviceId??null}),l}async reconcileNativeManagedSession(e){if(!await this.shouldUseTauriSignaling())return null;if(!await this.ensureNativeAuth("reconcileNativeManagedSession",{requireToken:this.requiresNativeAuthToken(),maxWaitMs:this.nativeAuthWaitMs()}))throw new Error("Native auth token unavailable for reconcileNativeManagedSession");return this.invokeIpc("reconcile_mobile_rtc_after_resume",{reason:e?.reason??"frontend"})}async notifyNetworkChange(e){return await this.canUseTauriIpc()?(c("[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 n=await this.invokeIpc("get_iroh_node_id");if(console.info("[NativeIpcBridge][getManagedNodeId] get_iroh_node_id returned",{existing:n}),n||!t)return n;console.info("[NativeIpcBridge][getManagedNodeId] invoking start_iroh_node");let r=await this.invokeIpc("start_iroh_node");return console.info("[NativeIpcBridge][getManagedNodeId] start_iroh_node returned",{started:r}),r}catch(n){if(console.warn("[NativeIpcBridge] getManagedNodeId failed:",n),!t)return null;throw n}}async getEndpointTicket(){if(!await this.canUseTauriIpc())throw new Error("[pluto-rtc] getEndpointTicket requires native IPC in Tauri runtime.");return q(()=>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:v.AUTH_REQUIRED_WAIT_MS}):c("[NativeIpcBridge] connectToDevice using anonymous native ticket path");let t=Math.max(1,Math.floor(e.timeoutMs??v.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 q(()=>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(o("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){await this.canUseTauriIpc()&&await this.invokeIpc("set_auto_connect_excluded",{deviceId:e,excluded:t});}onDevicesChange(e,t){let i=false,n=new Map,r=null,s=false,a=false,u$1=()=>{if(a=false,i)return;let g=Array.from(n.values());t&&(g=g.filter(y=>y.ticket!==t&&y.deviceId!==t&&y.nodeId!==t)),e(g);},o=()=>{if(!a){if(a=true,typeof queueMicrotask=="function"){queueMicrotask(u$1);return}Promise.resolve().then(u$1);}},c$1=async()=>{if(!await this.shouldUseTauriSignaling()){console.warn("[NativeIpcBridge] onDevicesChange falling back to wasm signaling (Tauri IPC unavailable)"),l=this.fallback.onDevicesChange(e,t);return}for(;!i;)try{let g=this.requiresNativeAuthToken()?15e3:0,y=Date.now()+g,h=this.getCurrentUserId();for(;!i&&!h&&Date.now()<y&&(this.hasLoggedMissingAuthForDevices||(this.hasLoggedMissingAuthForDevices=!0,c("[NativeIpcBridge] onDevicesChange waiting for authenticated user before subscription")),h=this.getCurrentUserId(),!h);)await u(250);if(!h){!i&&!s&&(console.warn("[NativeIpcBridge] onDevicesChange could not resolve authenticated user; keeping subscription in retry mode"),e([]),s=!0),await u(1e3);continue}if(!await this.ensureNativeAuth("onDevicesChange",{requireToken:this.requiresNativeAuthToken(),maxWaitMs:Math.max(0,y-Date.now())})){!i&&!s&&(console.warn("[NativeIpcBridge] onDevicesChange timed out waiting for auth token; keeping subscription in retry mode"),e([]),s=!0),await u(1e3);continue}this.hasLoggedMissingAuthForDevices=!1,s=!1,c(`[NativeIpcBridge] onDevicesChange starting subscription user_id=${h}`);let k=await this.listDevicesWithStatus().catch(async m=>(c(`[NativeIpcBridge] onDevicesChange full-roster seed failed; falling back to online-only search: ${m}`),this.searchDevices(t)));n.clear();for(let m of k)m?.deviceId&&n.set(m.deviceId,m);for(o(),r=(await this.subscribeDevices(h)).getReader();!i;){let{done:m,value:L}=await r.read();if(m||!L)break;for(let N of L){if(N.type==="removed"){n.delete(N.deviceId);continue}let M=N.device?.deviceId,R=this.nativeRosterTagDisposition(N.device??{});if(!R.keep){R.foreignTag&&c("[NativeIpcBridge] onDevicesChange dropped foreign-app device event",{sdkAppTag:this.appTag,foreignTag:R.foreignTag,deviceId:M??null}),M&&n.delete(M);continue}let E=this.normalizeDevice(N.device);E.deviceId&&n.set(E.deviceId,E);}o();}}catch(g){i||(console.error("[NativeIpcBridge] onDevicesChange stream failed; retrying subscription:",g),await u(1e3));}finally{if(r){try{await r.cancel();}catch{}r=null;}}},l=()=>{i=true,r&&(r.cancel(),r=null);};return c$1(),()=>l()}async subscribeDevices(e){if(await this.shouldUseTauriSignaling()){if(!await this.ensureNativeAuth("subscribeDevices",{requireToken:this.requiresNativeAuthToken(),maxWaitMs:this.nativeAuthWaitMs()}))throw new Error("Native auth token unavailable for subscribeDevices");let i=`sub-${Math.random().toString(36).substring(2,11)}`,n=null,r=null,s=false,a=async()=>{if(!s&&(s=true,n&&(await Promise.resolve(n()),n=null),r)){try{await r();}catch{}r=null;}};return new ReadableStream({start:async u=>{c(`[NativeIpcBridge] subscribeDevices request start user_id=${e} request_id=${i}`),n=await this.listenIpc("rtc-device-events",o=>{if(s)return;let c=o.payload;if(c.requestId===i){if(c.type==="deviceEvents"){let l=Array.isArray(c.events)?c.events.length:0;b$1(`[NativeIpcBridge] subscribeDevices event batch request_id=${i} count=${l}`);try{u.enqueue(c.events);}catch{a();}}else if(c.type==="error"&&(console.warn(`[NativeIpcBridge] subscribeDevices stream error request_id=${i}: ${c.message}`),!s)){try{u.error(c.message);}catch{}a();}}}),r=async()=>{await this.invokeIpc("stop_rtc_subscription",{requestId:i});};try{await this.invokeIpc("start_rtc_device_subscription",{requestId:i,userId:e});}catch(o){try{u.error(o);}catch{}await a();}},cancel:async()=>{c(`[NativeIpcBridge] subscribeDevices request stop request_id=${i}`),await a();}})}return this.fallback.subscribeDevices(e)}async subscribeSessions(e){if(await this.shouldUseTauriSignaling()){if(!await this.ensureNativeAuth("subscribeSessions",{requireToken:this.requiresNativeAuthToken(),maxWaitMs:this.nativeAuthWaitMs()}))throw new Error("Native auth token unavailable for subscribeSessions");let i=`sub-${Math.random().toString(36).substring(2,11)}`,n=await this.resolveLocalDeviceId()||e,r=null,s=null,a=false,u=async()=>{if(!a&&(a=true,r&&(await Promise.resolve(r()),r=null),s)){try{await s();}catch{}s=null;}};return new ReadableStream({start:async o=>{r=await this.listenIpc("rtc-session-events",c=>{if(a)return;let l=c.payload;if(l.requestId===i){if(l.type==="sessionEvents")try{o.enqueue(l.events);}catch{u();}else if(l.type==="error"&&!a){try{o.error(l.message);}catch{}u();}}}),s=async()=>{await this.invokeIpc("stop_rtc_subscription",{requestId:i});};try{await this.invokeIpc("start_rtc_session_subscription",{requestId:i,localDeviceId:n});}catch(c){try{o.error(c);}catch{}await u();}},cancel:async()=>{await u();}})}return this.fallback.subscribeSessions(e)}async getLocalDeviceId(){return this.resolveLocalDeviceId()}async updatePresence(e,t,i=true,n=3e5,r){if(await this.shouldUseTauriSignaling())try{if(!await this.ensureNativeAuth("updatePresence",{requireToken:this.requiresNativeAuthToken(),maxWaitMs:this.nativeAuthWaitMs()}))throw new Error("Native auth token unavailable for updatePresence");let a=this.resolveNativeSignalingUserId(),u=await this.resolveLocalDeviceId(),o=await this.resolveLocalDeviceName();await this.invokeIpc("update_rtc_presence",{userId:a,deviceName:o,ticket:t,metadata:this.withPresenceMetadata(r,u)});return}catch(s){console.warn("[NativeIpcBridge] update_rtc_presence failed:",s);}return this.fallback.updatePresence(e,t,i,n,r)}startAutoConnect(e,t){(async()=>{try{if(!await this.shouldUseTauriSignaling()){console.error("[NativeIpcBridge] startAutoConnect requires native Rust signaling; IPC unavailable");return}let i=await this.resolveLocalDeviceId()||t;await this.startAutoConnectOnce(e,i);}catch(i){console.warn("[NativeIpcBridge] startAutoConnect failed:",i);}})();}forceReconnectSnapshot(){(async()=>{if(!await this.shouldUseTauriSignaling()){console.error("[NativeIpcBridge] forceReconnectSnapshot requires native Rust signaling; IPC unavailable");return}try{await this.invokeIpc("force_rtc_reconnect_snapshot");}catch(e){console.warn("[NativeIpcBridge] force_rtc_reconnect_snapshot failed:",e);}})();}startPresenceLoop(e,t,i,n,r){(async()=>{try{if(!await this.shouldUseTauriSignaling()){console.warn("[NativeIpcBridge] startPresenceLoop falling back to wasm signaling (Tauri IPC unavailable)"),this.fallback.startPresenceLoop(e,t,i,n,r);return}let s=await this.resolveLocalDeviceId(),a=this.shouldUseResolvedDeviceName(i)?await this.resolveLocalDeviceName():i.trim(),u=this.withPresenceMetadata(r,s);await this.startPresenceLoopOnce(e,t,a,n,u);}catch(s){console.warn("[NativeIpcBridge] startPresenceLoop failed:",s);}})();}async startAutoConnectOnce(e,t){if(!await this.shouldUseTauriSignaling())throw new Error("[pluto-rtc] Native IPC unavailable for startAutoConnectOnce().");if(!await this.ensureNativeAuth("startAutoConnect",{requireToken:this.requiresNativeAuthToken(),maxWaitMs:this.nativeAuthWaitMs()}))throw new Error("Native auth token unavailable for startAutoConnect");let n=this.resolveNativeSignalingUserId(e);if(!n)throw new Error("Native auto-connect requires a runtime auth-scoped user id.");await this.invokeIpc("start_rtc_auto_connect",{userId:n,localDeviceId:t});}async startPresenceLoopOnce(e,t,i,n,r){if(!await this.shouldUseTauriSignaling())throw new Error("[pluto-rtc] Native IPC unavailable for startPresenceLoopOnce().");if(console.info("[NativeIpcBridge][presence][start-request]",{userId:e,localNodeId:t,deviceName:i,hasMetadata:typeof r=="string"&&r.trim().length>0,hasCompoundTicket:typeof n=="string"&&n.includes(".")}),!await this.ensureNativeAuth("startPresenceLoop",{requireToken:this.requiresNativeAuthToken(),maxWaitMs:this.nativeAuthWaitMs()}))throw new Error("Native auth token unavailable for startPresenceLoop");let a=this.resolveNativeSignalingUserId(e);if(!a)throw new Error("Native presence loop requires a runtime auth-scoped user id.");console.info("[NativeIpcBridge][presence][auth-ready]",{requestedUserId:e,runtimeUserId:this.currentUser?.id??this.getAuthContext()?.userId??null,effectiveUserId:a,localNodeId:t}),await this.invokeIpc("start_rtc_presence_loop",{userId:a,localNodeId:t,deviceName:i,ticket:n,metadata:r,apiKey:this.options.apiKey??null,spaceKey:this.resolveConfiguredSpaceKey()||null}),console.info("[NativeIpcBridge][presence][ipc-started]",{requestedUserId:e,effectiveUserId:a,localNodeId:t,deviceName:i});}shouldUseResolvedDeviceName(e){let t=e.trim();return t.length===0||t==="Unknown Device"||t==="Desktop Device"}async sendExplicitFilePath(e,t,i=""){if(c("[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("[NativeIpcBridge] sendExplicitFilePath using anonymous native path");let n=await this.invokeIpc("send_file",{connectionId:e,filePath:t,transferId:i});return c("[NativeIpcBridge] sendExplicitFilePath completed",{connectionId:e,transferId:i||null,result:n}),n}return this.fallback.sendExplicitFilePath(e,t,i)}async sendExplicitFileData(e){c("[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("[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 n=new Uint8Array(await e.file.arrayBuffer());await this.invokeIpc("send_file_data",{connectionId:i,filename:e.file.name,data:Array.from(n),transferId:e.transferId}),c("[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=>v$1(t)).filter(t=>!!t)}catch(e){return O(e)?c("[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"),v$1(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,n=new Map,r=Date.now(),s=0,a=()=>{let c=i;c&&Promise.resolve(c());},u$1=async()=>{try{let c=await this.getConnectionStates();c.length>0&&(b$1("[NativeIpcBridge] replaying current native connection states",c.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}))),c.forEach(l=>e(l)));}catch(c){console.warn("[NativeIpcBridge] Failed to replay native connection states after event subscription:",c);}},o=async c=>{let l=(n.get(c)??0)+1;n.set(c,l);let g=await this.getConnectionState(c);if(!g||t||n.get(c)!==l)return;if(["closed","failed","disconnected"].includes(String(g.state??"").trim().toLowerCase())){if(await u(v.CONNECTION_TERMINAL_CONFIRMATION_MS),t||n.get(c)!==l)return;g=await this.getConnectionState(c)??g;}!t&&n.get(c)===l&&e(g);};for(;!t&&Date.now()-r<=v.CONNECTION_EVENT_SUBSCRIBE_WINDOW_MS;){if(s+=1,!await this.canUseTauriIpc()){await u(this.nextConnectionEventRetryDelayMs(s));continue}return i=await this.listenIpc("connection-state-changed",c=>{let l=v$1(c?.payload);l&&(b$1("[NativeIpcBridge] connection-state-changed trigger",{connectionId:l.connectionId}),o(l.connectionId));}),await u$1(),()=>{t=true,a();}}return ()=>{t=true,a();}}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 n=new Uint8Array(i.payload.data);if(n.length<2||n[0]!==0)return;let s=n.slice(1),a=new TextDecoder().decode(s),u=JSON.parse(a);e(i.payload.connectionId,i.payload.remoteNodeId??null,u);}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});}};v.AUTH_REQUIRED_WAIT_MS=w.nativeIpc.authRequiredWaitMs,v.DEFAULT_BOUNDED_IPC_TIMEOUT_MS=w.nativeIpc.defaultBoundedCommandTimeoutMs,v.CONNECTION_EVENT_SUBSCRIBE_WINDOW_MS=w.nativeIpc.connectionEventSubscribeWindowMs,v.CONNECTION_EVENT_RETRY_MIN_DELAY_MS=w.nativeIpc.connectionEventRetryMinDelayMs,v.CONNECTION_EVENT_RETRY_MAX_DELAY_MS=w.nativeIpc.connectionEventRetryMaxDelayMs,v.CONNECTION_TERMINAL_CONFIRMATION_MS=1500,v.TAURI_IPC_NEGATIVE_CACHE_MS=w.nativeIpc.tauriIpcNegativeCacheMs,v.NATIVE_STATUS_IPC_TIMEOUT_MS=2500;var D=v;var te=class extends F{constructor(e){let t=T(e.bridge,"IpcRuntimeAdapter");super(new D({...e,ipcBridge:t,allowWasmFallback:e.allowWasmFallback??false}));}};
2
+ export{Z as a,X as b,ee as c,q as d,ie as e,O as f,Q as g,te as h};