openrtc 0.1.3 → 0.2.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +92 -0
- package/README.md +73 -9
- package/dist/DelegatingRuntimeAdapter-BxOcVIx_.d.ts +201 -0
- package/dist/{IpcRuntimeAdapter-CT-W0Mtp.d.ts → IpcRuntimeAdapter-U5AEH0jn.d.ts} +6 -2
- package/dist/auth/index.js +1 -1
- package/dist/auth/internal.js +1 -1
- package/dist/chunk-7DN33VUQ.js +1 -0
- package/dist/chunk-BLOEZIFJ.js +1 -0
- package/dist/chunk-FQETZQPW.js +2 -0
- package/dist/chunk-IUHUYHNZ.js +1 -0
- package/dist/chunk-UBEE42VU.js +2 -0
- package/dist/chunk-UPO23UMZ.js +3 -0
- package/dist/chunk-WNJE3MJF.js +1 -0
- package/dist/{factories-0TxDPMeu.d.ts → framing-lxzHEuSr.d.ts} +479 -226
- package/dist/index.d.ts +201 -7
- package/dist/index.js +2 -1
- package/dist/openrtc_bg.wasm +0 -0
- package/dist/runtime/WasmRuntimeAdapter.d.ts +2 -1
- package/dist/runtime/WasmRuntimeAdapter.js +1 -1
- package/dist/runtime/index.d.ts +213 -392
- package/dist/runtime/index.js +1 -1
- package/dist/runtime/tauri.d.ts +5 -6
- package/dist/runtime/tauri.js +1 -1
- package/dist/transport/index.d.ts +11 -0
- package/dist/transport/index.js +1 -0
- package/dist/{DelegatingRuntimeAdapter-CW8d78dZ.d.ts → types-D0fRvUbN.d.ts} +222 -171
- package/env/index.d.ts +64 -0
- package/env/index.mjs +230 -0
- package/package.json +29 -18
- package/dist/chunk-26POO5PL.js +0 -4
- package/dist/chunk-4MH42GUI.js +0 -2
- package/dist/chunk-D54VGRRH.js +0 -1
- package/dist/chunk-DIQYFAGL.js +0 -2
- package/dist/chunk-PZ25OCVG.js +0 -2
- package/dist/chunk-UVASANPG.js +0 -1
- package/wasm/README.md +0 -64
- package/wasm/openrtc.d.ts +0 -320
- package/wasm/openrtc.js +0 -2290
- package/wasm/openrtc_bg.wasm +0 -0
- package/wasm/openrtc_bg.wasm.d.ts +0 -113
- package/wasm/package.json +0 -16
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import {q as q$1,z,v as v$1,y,u as u$1,j,d,x,c,i,l,m,n,o,p}from'./chunk-WNJE3MJF.js';import {u,r,b,a,B as B$1,D}from'./chunk-FQETZQPW.js';function te(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 B(d){return te(d)==="command-unavailable"}function S(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 U=null;async function ie(){return U||(U=(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}}})()),U}function J(){let d=null,e=async()=>(d||(d=ie().then(t=>S(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 ne="relay-only endpoint ticket unavailable",ae=12e3,re=250,se=1500;function oe(d){return String(d?.message??d??"").toLowerCase().includes(ne)}async function q(d,e={}){let t=e.windowMs??ae,i=e.minDelayMs??re,n=e.maxDelayMs??se,a=Date.now(),s=0,r$1=null;for(;e.isActive?.()??true;){s+=1;try{return await d()}catch(l){if(r$1=l,!oe(l))throw l;let o=Date.now()-a;if(o>=t)throw l;let c=Math.min(u(s,i,n),Math.max(0,t-o));c>0&&await r(c);}}throw r$1||new Error("endpoint ticket minting stopped before a ticket was available")}function X(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)),a=JSON.parse(n);return a&&typeof a=="object"&&!Array.isArray(a)?a:null}catch{return null}}function Q(d,e){let t=d?.[e];return typeof t=="string"&&t.trim()?t.trim():null}function Z(d,e){return Q(d,"namespaceId")===e||Q(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=v$1(null,false);this.nativeRtdbPresenceScope=null;this.nativeRtdbTicketVersion=0;this.lastNativePresenceTicket=null;this.nativeRtdbPresenceDisabledForSession=false;this.fallback=new y(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=S(e.ipcBridge??J(),"NativeIpcBridge"),this.runtimeCapabilities=v$1(null,this.allowWasmFallback),this.syncNativeRuntimeCapabilities("constructor");}get currentUser(){return this.fallback.currentUser}get tag(){return this.fallback.tag}getRuntimeCapabilities(){let e=u$1(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 a=this.fallback;if(typeof a.incoming_streams=="function")return a.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 a=t;t=null,await Promise.allSettled([a?Promise.resolve(a()):Promise.resolve(),this.invokeIpc("stop_rtc_subscription",{requestId:e},{timeoutMs:null}).catch(()=>{})]);};return new ReadableStream({start:async a=>{try{t=await this.listenIpc("openrtc://peer-bi-stream/incoming",s=>{if(i)return;let r=s.payload;if((typeof r?.requestId=="string"?r.requestId:typeof r?.request_id=="string"?r.request_id:"")!==e)return;let o=typeof r?.streamId=="string"?r.streamId.trim():typeof r?.stream_id=="string"?r.stream_id.trim():"";if(!o)return;let c=typeof r?.remoteNodeId=="string"?r.remoteNodeId.trim():typeof r?.remote_node_id=="string"?r.remote_node_id.trim():"",u=this.peerBiStreamFromId(o,{startReadAfterListeners:!0});a.enqueue({type:"bi",stream:{send:u.writable,recv:u.readable,endpoint_id:c},endpointId:c,protocolHint:"unknown",channel:null});}),await this.invokeIpc("start_incoming_peer_bi_streams",{requestId:e},{timeoutMs:null});}catch(s){i=true,a.error(s),await n();}},cancel:async()=>{await n();}})}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}usesAnonymousSpaceMode(){return this.options.authMode==="anonymous"&&typeof this.options.spaceKey=="string"&&this.options.spaceKey.trim().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=typeof this.options.spaceKey=="string"?this.options.spaceKey.trim():"";if(!t||!i)return true;let n=await b(t,i).catch(()=>null);return n?Z(X(e),n):true}resolveNativeSignalingUserId(e){return this.usesAnonymousSpaceMode()?(typeof e=="string"?e.trim():"")||this.options.spaceKey?.trim()||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)}matchesNativeStatusTag(e){let t=j(e);return this.matchesTag(t)}async buildNativeRtdbScope(e){return this.fallback.resolveRtdbScope(e??void 0)}async syncNativeRtdbPresenceTicket(e){if(this.nativeRtdbPresenceDisabledForSession)return;let t=await this.buildNativeRtdbScope(),i=await this.resolveLocalDeviceId();if(!(!t||!i))try{if(!this.fallback.rtdbPresence||!this.nativeRtdbPresenceScope){await this.fallback.registerRtdbPresence(t,i,this.nativeRtdbTicketVersion),this.nativeRtdbPresenceScope=t,this.lastNativePresenceTicket=e,d("[NativeIpcBridge][RTDB] registered native presence ticket state",{deviceId:i,ticketVersion:this.nativeRtdbTicketVersion,ticketFingerprint:x(e)});return}let a=this.lastNativePresenceTicket!==e;(this.nativeRtdbPresenceScope.kind!==t.kind||t.kind==="user-scoped"&&this.nativeRtdbPresenceScope.kind==="user-scoped"&&(this.nativeRtdbPresenceScope.appTag!==t.appTag||this.nativeRtdbPresenceScope.userId!==t.userId)||t.kind==="space"&&this.nativeRtdbPresenceScope.kind==="space"&&this.nativeRtdbPresenceScope.namespaceId!==t.namespaceId)&&(await this.fallback.registerRtdbPresence(t,i,this.nativeRtdbTicketVersion),this.nativeRtdbPresenceScope=t),a&&(this.nativeRtdbTicketVersion+=1,await this.fallback.rtdbPresence?.bumpTicketVersion(t,i,this.nativeRtdbTicketVersion),d("[NativeIpcBridge][RTDB] bumped native ticketVersion after managed ticket change",{deviceId:i,ticketVersion:this.nativeRtdbTicketVersion,ticketFingerprint:x(e)})),this.nativeRtdbPresenceScope=t,this.lastNativePresenceTicket=e;}catch(n){this.nativeRtdbPresenceDisabledForSession=true,this.nativeRtdbPresenceScope=null,this.lastNativePresenceTicket=null,console.warn("[NativeIpcBridge][RTDB] native RTDB presence mirror unavailable; continuing with Firestore/native presence.",n);}}async markNativeRtdbOffline(){if(!this.nativeRtdbPresenceScope)return;let e=await this.resolveLocalDeviceId();if(e)try{await this.fallback.rtdbPresence?.markOffline(this.nativeRtdbPresenceScope,e,this.nativeRtdbTicketVersion),d("[NativeIpcBridge][RTDB] marked native presence offline",{deviceId:e,ticketVersion:this.nativeRtdbTicketVersion});}catch(t){console.warn("[NativeIpcBridge][RTDB] failed to mark native presence offline:",t);}finally{this.nativeRtdbPresenceScope=null,this.nativeRtdbTicketVersion=0,this.lastNativePresenceTicket=null,this.nativeRtdbPresenceDisabledForSession=false;}}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=Array.isArray(o?.iceServers)?o.iceServers.map(y=>this.normalizeNativeIceServer(y)).filter(y=>!!y):[],u=this.strictMode||o?.privacyMode===true;(this.strictMode||o?.privacyMode===true||o?.useTurn===true)&&(c=[...c,...await this.loadNativeTurnIceServers()]),u&&(c=this.filterNativeStunServers(c));let m=c.some(y=>this.nativeIceServerHasTurnUrl(y)),p=u&&m;u&&!m&&console.warn("[NativeIpcBridge] Relay-only WebRTC requested, but no TURN servers are configured; native WebRTC override disabled");let f=o?.lanMode===true;(c.length>0||p||f)&&(i={iceServers:c.length>0?c:void 0,privacyMode:p,lanMode:f||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;o&&(n={relayUrl:o});}let a=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),u=Number(o?.retryAttempts),g=Number(o?.retryBackoffMs);a={enabled:o?.enabled!==false,connectTimeoutMs:Number.isFinite(c)&&c>0?Math.round(c):void 0,retryAttempts:Number.isFinite(u)&&u>=0?Math.round(u):void 0,retryBackoffMs:Number.isFinite(g)&&g>=0?Math.round(g):void 0};}let s=this.strictMode||e?.iroh&&typeof e.iroh=="object"&&e.iroh.relayOnly===true,r=e?.iroh&&typeof e.iroh=="object"?e.iroh.relayTransportPolicy:void 0,l=this.strictMode?r??"auto":r;return !s&&!l&&!i&&!n&&!t&&!a?null:{irohRelayOnly:s||void 0,irohRelayTransportPolicy:l,irohLan:t,webrtc:i,moq:n,ble:a}}isTauriEnv(){return a()}nextConnectionEventRetryDelayMs(e){return u(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,d(`[NativeIpcBridge] cleared native auth relay (${e})`);}catch(t){console.warn(`[NativeIpcBridge] failed clearing native auth relay (${e}):`,t);}}applyNativeRuntimeStatus(e){this.runtimeCapabilities=v$1(e,this.allowWasmFallback);}syncNativeRuntimeCapabilities(e){return this.ipcBridge?this.nativeRuntimeCapabilitiesSyncInFlight?this.nativeRuntimeCapabilitiesSyncInFlight:(this.nativeRuntimeCapabilitiesSyncInFlight=(async()=>{try{let t=await this.invokeIpc("rtc_native_status",void 0,{timeoutMs:v.NATIVE_STATUS_IPC_TIMEOUT_MS});this.applyNativeRuntimeStatus(t),d(`[NativeIpcBridge] refreshed native runtime capabilities (${e})`);}catch(t){c("[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),d("[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):(d("[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),a=i?.timeoutMs??v.MANAGED_SESSION_IPC_TIMEOUT_MS;return a===null||a<=0?n:B$1(n,a,()=>new Error(`${e} timeout after ${a}ms`))}isRetryableManagedSessionStartError(e){let t=(e instanceof Error?e.message:String(e??"")).toLowerCase();return !t||t.includes("start_rtc_managed_session")&&t.includes("timeout after")?false:!!(t.includes("callback")&&t.includes("id")||t.includes("channel closed")||t.includes("ipc channel closed"))}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),a=typeof n?.streamId=="string"?n.streamId.trim():typeof n?.stream_id=="string"?n.stream_id.trim():"";if(!a)throw new Error(`${e} returned no streamId`);return this.peerBiStreamFromId(a)}peerBiStreamFromId(e,t={}){let i=this,n=null,a=null,s=false,r=null,l=null,o=async()=>{let p=[n,a];n=null,a=null,await Promise.allSettled(p.filter(f=>typeof f=="function").map(f=>Promise.resolve(f())));},c=(async()=>{n=await this.listenIpc("openrtc://peer-bi-stream/chunk",p=>{let f=p.payload;if((typeof f?.streamId=="string"?f.streamId:typeof f?.stream_id=="string"?f.stream_id:"")!==e||s||!r)return;let y=f?.bytes;y instanceof Uint8Array?r.enqueue(y):Array.isArray(y)&&r.enqueue(new Uint8Array(y));}),a=await this.listenIpc("openrtc://peer-bi-stream/closed",p=>{let f=p.payload;if((typeof f?.streamId=="string"?f.streamId:typeof f?.stream_id=="string"?f.stream_id:"")!==e||s||!r)return;s=true;let y=typeof f?.error=="string"?f.error.trim():"";y?r.error(new Error(y)):r.close(),o();}),t.startReadAfterListeners&&await this.invokeIpc("start_peer_bi_stream_read",{streamId:e},{timeoutMs:null});})().catch(p=>{l=p,r&&!s&&(s=true,r.error(p));}),u=async()=>{await this.invokeIpc("close_peer_bi_stream",{streamId:e},{timeoutMs:null}).catch(()=>{}),await o();},g=new ReadableStream({async start(p){r=p,await c,l&&!s&&(s=true,p.error(l));},async cancel(){s=true,await u();}}),m=new WritableStream({write:async p=>{await i.invokeIpc("write_peer_bi_stream",{streamId:e,bytes:Array.from(p)},{timeoutMs:null});},close:u,abort:u});return {readable:g,writable:m}}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 D().signInWithCustomTokenValue(t),await this.ensureNativeAuth("pluto-sso",{requireToken:true,maxWaitMs:1e4});}async setAuthContext(e){if(await this.fallback.setAuthContext(e),!e?.token)await this.markNativeRtdbOffline(),await this.clearNativeAuthRelay("setAuthContext");else if(!await this.ensureNativeAuth("setAuthContext",{requireToken:true,maxWaitMs:v.AUTH_REQUIRED_WAIT_MS}))throw new Error("Native auth token unavailable for setAuthContext")}async signOut(){await this.fallback.signOut(),await this.markNativeRtdbOffline(),await this.clearNativeAuthRelay("signOut");}async stopAuthScopedActivity(e){let t=this.resolveNativeSignalingUserId(e?.userId??null),i$1=await this.shouldUseTauriSignaling();if(i("NativeIpcBridge.stopAuthScopedActivity",{userId:t,useTauri:i$1}),i$1)try{await Promise.allSettled([this.revokeSessionTokensByScope("user-device"),this.invokeIpc("stop_rtc_presence_loop"),this.invokeIpc("stop_rtc_auto_connect"),t?this.invokeIpc("set_rtc_offline",{userId:t}):Promise.resolve()]);}catch(n){console.warn("[NativeIpcBridge] Failed to stop native auth-scoped RTC activity:",n);}await this.markNativeRtdbOffline(),await this.fallback.stopAuthScopedActivity({userId:t});}async ensureNativeAuthOnce(e,t){if(!await this.canUseTauriIpc())return true;if(this.authSyncInFlight)return this.authSyncInFlight;let i=(async()=>{try{if(!this.currentUser)return d(`[NativeIpcBridge] auth sync deferred (${e}): no current user`),!t;let n=Date.now()-this.lastNativeAuthSyncAtMs>=480*1e3,a=this.currentUser?.getToken?await this.currentUser.getToken(n):null,r=this.getAuthContext()?.refreshToken??this.auth?.currentUser?.refreshToken??null;if(!a)return d(`[NativeIpcBridge] auth sync deferred (${e}): missing token for user ${this.currentUser?.id}`),!t;if(!await this.nativeAuthTokenMatchesExpectedScope(a))return d(`[NativeIpcBridge] auth sync deferred (${e}): token claims do not match configured space`),!1;if(a===this.lastSyncedAuthToken)return !0;let l=await Promise.allSettled([this.invokeIpc("desktop_set_pluto_auth_token",{authToken:a,refreshToken:r})]);return l[0]?.status==="rejected"?(B(l[0].reason)?console.warn(`[NativeIpcBridge] desktop auth relay unavailable (${e}); install/register openrtc-tauri-plugin and include its default permission set.`,l[0].reason):console.warn(`[NativeIpcBridge] desktop auth relay failed (${e}):`,l[0].reason),!1):(this.lastSyncedAuthToken=a,this.lastNativeAuthSyncAtMs=Date.now(),d(`[NativeIpcBridge] auth token relayed to native runtime (${e}) user_id=${this.currentUser?.id}`),!0)}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),a=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 r(a);}}async resolveLocalDeviceId(){if(this.cachedLocalDeviceId)return this.cachedLocalDeviceId;if(await this.canUseTauriIpc())try{let t=await this.invokeIpc("get_rtc_local_device_info"),i=typeof t?.device_id=="string"?t.device_id:"",n=typeof t?.device_name=="string"?t.device_name.trim():"";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"),t=typeof e?.device_name=="string"?e.device_name.trim():"";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(a=>this.normalizeDevice(a));return e&&(n=n.filter(a=>a.ticket!==e&&a.deviceId!==e&&a.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=i.filter(r=>this.matchesNativeStatusTag(r)).map(r=>l(r)),a=await this.resolveLocalDeviceId().catch(()=>null),s=!!a&&n.some(r=>r.deviceId===a);return c("[NativeIpcBridge] listDevicesWithStatus result",{rawCount:i.length,count:n.length,localDeviceId:a,selfIncluded:s,devices:n.map(r=>({deviceId:r.deviceId,deviceName:r.deviceName,online:!!r.online,presenceStatus:r.presenceStatus,connectable:r.connectable,connectionStatus:r.connectionStatus,settledReady:!!r.settledReady,peerHealth:r.peerHealth,scopes:r.scopes,connectionId:r.connectionId??null,deviceIdHint:r.deviceIdHint??null,nodeId:r.nodeId??null,activeTransport:r.activeTransport??null,parallelTransport:r.parallelTransport??null}))}),a&&!s&&c("[NativeIpcBridge] native status snapshot excludes local device by design",{localDeviceId:a,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:m(t)}return this.fallback.getPeerSession(e)}async listPeerSessions(){if(await this.shouldUseTauriSignaling()){let e=await this.invokeIpc("list_rtc_peer_sessions");return (Array.isArray(e)?e:[]).map(t=>m(t))}return this.fallback.listPeerSessions()}async waitForSettledPeer(e,t){if(await this.shouldUseTauriSignaling()){let i=typeof t=="number"?Math.max(v.MANAGED_SESSION_IPC_TIMEOUT_MS,t+1e3):v.MANAGED_SESSION_IPC_TIMEOUT_MS,n=await this.invokeIpc("wait_for_rtc_settled_peer",{id:e,timeoutMs:t},{timeoutMs:i});return !n||typeof n!="object"?null:m(n)}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=>n(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 o(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}),await this.markNativeRtdbOffline();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 a=this.getCurrentUserId();if(!a)throw new Error("updateDevice requires authenticated user scope");try{await this.invokeIpc("update_rtc_device",{userId:a,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(a){throw console.warn("[NativeIpcBridge] delete_rtc_device failed:",a),a instanceof Error?a:new Error(String(a))}}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=typeof e?.device_id=="string"?e.device_id.trim():"";return t?{deviceId:t,deviceName:this.normalizeNativeDeviceName(typeof e?.device_name=="string"?e.device_name:""),platformType:typeof e?.platform_type=="string"?e.platform_type: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=typeof t?.device_id=="string"?t.device_id.trim():"";return i?(this.cachedLocalDeviceName=this.normalizeNativeDeviceName(e),{deviceId:i,deviceName:this.cachedLocalDeviceName,platformType:typeof t?.platform_type=="string"?t.platform_type: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}),console.info("[NativeIpcBridge][managed-session][start-request]",{requestedUserId:e.userId,runtimeUserId:this.currentUser?.id??this.getAuthContext()?.userId??null,effectiveUserId:i,spaceKey:this.options.spaceKey?"[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 n=await this.buildNativeTransportConfigPayload(),a={userId:i,deviceName:e.deviceName??null,localDeviceId:e.localDeviceId??null,metadata:e.metadata??null,...n?{transports:n}:{},autoConnect:e.autoConnect!==false,presence:e.presence!==false,apiKey:this.options.apiKey??null,spaceKey:this.options.spaceKey??null},s=null,r$1=null;for(let g=1;g<=v.MANAGED_SESSION_IPC_MAX_ATTEMPTS;g+=1)try{s=await this.invokeIpc("start_rtc_managed_session",a,{timeoutMs:v.MANAGED_SESSION_IPC_TIMEOUT_MS}),r$1=null;break}catch(m){r$1=m;let p=this.isRetryableManagedSessionStartError(m),f=v.MANAGED_SESSION_IPC_MAX_ATTEMPTS-g;if(console.warn("[NativeIpcBridge][managed-session][ipc-attempt-failed]",{attempt:g,retryable:p,remaining:f,message:m instanceof Error?m.message:String(m)}),!p||f<=0)throw m;await this.ensureNativeAuth("startManagedSessionNative-retry",{requireToken:this.requiresNativeAuthToken(),maxWaitMs:this.requiresNativeAuthToken()?5e3:0}),await r(250*g);}if(!s&&r$1)throw r$1 instanceof Error?r$1:new Error(String(r$1));this.syncNativeRuntimeCapabilities("managed-session-started");let l=typeof s?.ticket=="string"&&s.ticket.trim().length>0?s.ticket.trim():null;l&&e.presence!==false&&await this.syncNativeRtdbPresenceTicket(l);let o=s?.localDevice&&typeof s.localDevice=="object"?s.localDevice:s?.local_device&&typeof s.local_device=="object"?s.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,u={localNodeId:typeof s?.localNodeId=="string"?s.localNodeId:typeof s?.local_node_id=="string"?s.local_node_id:null,ticket:l,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: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:u.localNodeId,ticketScope:u.ticketScope,presenceStarted:u.presenceStarted,autoConnectStarted:u.autoConnectStarted,localDeviceId:u.localDevice?.deviceId??null}),u}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 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 a=await this.invokeIpc("start_iroh_node");return console.info("[NativeIpcBridge][getManagedNodeId] start_iroh_node returned",{started:a}),a}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.");return this.options.authMode!=="anonymous"?await this.ensureNativeAuth("connectToDevice",{requireToken:true,maxWaitMs:v.AUTH_REQUIRED_WAIT_MS}):d("[NativeIpcBridge] connectToDevice using anonymous native ticket path"),this.invokeIpc("connect_to_device",{deviceId:e.deviceId??null,endpointTicket:e.endpointTicket})}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(i("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,a=null,s=false,r$1=false,l=()=>{if(r$1=false,i)return;let g=Array.from(n.values());t&&(g=g.filter(m=>m.ticket!==t&&m.deviceId!==t&&m.nodeId!==t)),e(g);},o=()=>{if(!r$1){if(r$1=true,typeof queueMicrotask=="function"){queueMicrotask(l);return}Promise.resolve().then(l);}},c=async()=>{if(!await this.shouldUseTauriSignaling()){console.warn("[NativeIpcBridge] onDevicesChange falling back to wasm signaling (Tauri IPC unavailable)"),u=this.fallback.onDevicesChange(e,t);return}for(;!i;)try{let g=this.requiresNativeAuthToken()?15e3:0,m=Date.now()+g,p=this.getCurrentUserId();for(;!i&&!p&&Date.now()<m&&(this.hasLoggedMissingAuthForDevices||(this.hasLoggedMissingAuthForDevices=!0,d("[NativeIpcBridge] onDevicesChange waiting for authenticated user before subscription")),p=this.getCurrentUserId(),!p);)await r(250);if(!p){!i&&!s&&(console.warn("[NativeIpcBridge] onDevicesChange could not resolve authenticated user; keeping subscription in retry mode"),e([]),s=!0),await r(1e3);continue}if(!await this.ensureNativeAuth("onDevicesChange",{requireToken:this.requiresNativeAuthToken(),maxWaitMs:Math.max(0,m-Date.now())})){!i&&!s&&(console.warn("[NativeIpcBridge] onDevicesChange timed out waiting for auth token; keeping subscription in retry mode"),e([]),s=!0),await r(1e3);continue}this.hasLoggedMissingAuthForDevices=!1,s=!1,d(`[NativeIpcBridge] onDevicesChange starting subscription user_id=${p}`);let N=await this.listDevicesWithStatus().catch(async w=>(d(`[NativeIpcBridge] onDevicesChange full-roster seed failed; falling back to online-only search: ${w}`),this.searchDevices(t)));n.clear();for(let w of N)w?.deviceId&&n.set(w.deviceId,w);for(o(),a=(await this.subscribeDevices(p)).getReader();!i;){let{done:w,value:O}=await a.read();if(w||!O)break;for(let _ of O){if(_.type==="removed"){n.delete(_.deviceId);continue}let W=_.device?.deviceId;if(!this.matchesTag(_.device??{})){W&&n.delete(W);continue}let R=this.normalizeDevice(_.device);R.deviceId&&n.set(R.deviceId,R);}o();}}catch(g){i||(console.error("[NativeIpcBridge] onDevicesChange stream failed; retrying subscription:",g),await r(1e3));}finally{if(a){try{await a.cancel();}catch{}a=null;}}},u=()=>{i=true,a&&(a.cancel(),a=null);};return c(),()=>u()}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,a=null,s=false,r=async()=>{if(!s&&(s=true,n&&(await Promise.resolve(n()),n=null),a)){try{await a();}catch{}a=null;}};return new ReadableStream({start:async l=>{d(`[NativeIpcBridge] subscribeDevices request start user_id=${e} request_id=${i}`),n=await this.listenIpc("rtc-device-events",o=>{if(s)return;let c$1=o.payload;if(c$1.requestId===i){if(c$1.type==="deviceEvents"){let u=Array.isArray(c$1.events)?c$1.events.length:0;c(`[NativeIpcBridge] subscribeDevices event batch request_id=${i} count=${u}`);try{l.enqueue(c$1.events);}catch{r();}}else if(c$1.type==="error"&&(console.warn(`[NativeIpcBridge] subscribeDevices stream error request_id=${i}: ${c$1.message}`),!s)){try{l.error(c$1.message);}catch{}r();}}}),a=async()=>{await this.invokeIpc("stop_rtc_subscription",{requestId:i});};try{await this.invokeIpc("start_rtc_device_subscription",{requestId:i,userId:e});}catch(o){try{l.error(o);}catch{}await r();}},cancel:async()=>{d(`[NativeIpcBridge] subscribeDevices request stop request_id=${i}`),await r();}})}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,a=null,s=null,r=false,l=async()=>{if(!r&&(r=true,a&&(await Promise.resolve(a()),a=null),s)){try{await s();}catch{}s=null;}};return new ReadableStream({start:async o=>{a=await this.listenIpc("rtc-session-events",c=>{if(r)return;let u=c.payload;if(u.requestId===i){if(u.type==="sessionEvents")try{o.enqueue(u.events);}catch{l();}else if(u.type==="error"&&!r){try{o.error(u.message);}catch{}l();}}}),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 l();}},cancel:async()=>{await l();}})}return this.fallback.subscribeSessions(e)}async getLocalDeviceId(){return this.resolveLocalDeviceId()}async updatePresence(e,t,i=true,n=3e5,a){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 r=this.resolveNativeSignalingUserId(),l=await this.resolveLocalDeviceId(),o=await this.resolveLocalDeviceName();await this.invokeIpc("update_rtc_presence",{userId:r,deviceName:o,ticket:t,metadata:this.withPresenceMetadata(a,l)}),await this.syncNativeRtdbPresenceTicket(t);return}catch(s){console.warn("[NativeIpcBridge] update_rtc_presence failed:",s);}return this.fallback.updatePresence(e,t,i,n,a)}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,a){(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,a);return}let s=await this.resolveLocalDeviceId(),r=this.shouldUseResolvedDeviceName(i)?await this.resolveLocalDeviceName():i.trim(),l=this.withPresenceMetadata(a,s);await this.startPresenceLoopOnce(e,t,r,n,l),await this.syncNativeRtdbPresenceTicket(n);}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,a){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 a=="string"&&a.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 r=this.resolveNativeSignalingUserId(e);if(!r)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:r,localNodeId:t}),await this.invokeIpc("start_rtc_presence_loop",{userId:r,localNodeId:t,deviceName:i,ticket:n,metadata:a,apiKey:this.options.apiKey??null,spaceKey:this.options.spaceKey??null}),console.info("[NativeIpcBridge][presence][ipc-started]",{requestedUserId:e,effectiveUserId:r,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(d("[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"):d("[NativeIpcBridge] sendExplicitFilePath using anonymous native path");let n=await this.invokeIpc("send_file",{connectionId:e,filePath:t,transferId:i});return d("[NativeIpcBridge] sendExplicitFilePath completed",{connectionId:e,transferId:i||null,result:n}),n}return this.fallback.sendExplicitFilePath(e,t,i)}async sendExplicitFileData(e){d("[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"):d("[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}),d("[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=>p(t)).filter(t=>!!t)}catch(e){return B(e)?d("[NativeIpcBridge] native connection-state replay unavailable; continuing without replay. Install/register openrtc-tauri-plugin default permissions to enable it."):console.warn("[NativeIpcBridge] Failed to fetch native connection states:",e),[]}return []}async getConnectionState(e){let t=e.trim();if(!t||!await this.canUseTauriIpc())return null;try{return this.options.authMode!=="anonymous"&&await this.ensureNativeAuth("getConnectionState"),p(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=Date.now(),a=0,s=()=>{let o=i;o&&Promise.resolve(o());},r$1=async()=>{try{let o=await this.getConnectionStates();o.length>0&&(c("[NativeIpcBridge] replaying current native connection states",o.map(c=>({connectionId:c.connectionId,deviceId:c.deviceId??null,deviceIdHint:c.deviceIdHint??null,remoteNodeId:c.remoteNodeId??null,state:c.state,transportState:c.transportState??null,protocolState:c.protocolState??null,routable:c.routable??null}))),o.forEach(c=>e(c)));}catch(o){console.warn("[NativeIpcBridge] Failed to replay native connection states after event subscription:",o);}},l=async o=>{let c=await this.getConnectionState(o);c&&e(c);};for(;!t&&Date.now()-n<=v.CONNECTION_EVENT_SUBSCRIBE_WINDOW_MS;){if(a+=1,!await this.canUseTauriIpc()){await r(this.nextConnectionEventRetryDelayMs(a));continue}return i=await this.listenIpc("connection-state-changed",o=>{let c$1=p(o?.payload);c$1&&(c("[NativeIpcBridge] connection-state-changed trigger",{connectionId:c$1.connectionId}),l(c$1.connectionId));}),await r$1(),()=>{t=true,s();}}return ()=>{t=true,s();}}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),r=new TextDecoder().decode(s),l=JSON.parse(r);e(i.payload.connectionId,i.payload.remoteNodeId??null,l);}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=q$1.nativeIpc.authRequiredWaitMs,v.MANAGED_SESSION_IPC_TIMEOUT_MS=q$1.nativeIpc.managedSessionIpcTimeoutMs,v.MANAGED_SESSION_IPC_MAX_ATTEMPTS=q$1.nativeIpc.managedSessionIpcMaxAttempts,v.CONNECTION_EVENT_SUBSCRIBE_WINDOW_MS=q$1.nativeIpc.connectionEventSubscribeWindowMs,v.CONNECTION_EVENT_RETRY_MIN_DELAY_MS=q$1.nativeIpc.connectionEventRetryMinDelayMs,v.CONNECTION_EVENT_RETRY_MAX_DELAY_MS=q$1.nativeIpc.connectionEventRetryMaxDelayMs,v.TAURI_IPC_NEGATIVE_CACHE_MS=q$1.nativeIpc.tauriIpcNegativeCacheMs,v.NATIVE_STATUS_IPC_TIMEOUT_MS=2500;var C=v;var ee=class extends z{constructor(e){let t=S(e.bridge,"IpcRuntimeAdapter");super(new C({...e,ipcBridge:t,allowWasmFallback:e.allowWasmFallback??false}));}};
|
|
2
|
+
export{X as a,Q as b,Z as c,q as d,te as e,B as f,J as g,ee as h};
|