openrtc 2.0.0-rc.7 → 2.0.0-rc.9
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{WasmBridge-227YXBG7.js → WasmBridge-B7NTRYN5.js} +1 -1
- package/dist/chunk-23XC6TGK.js +2 -0
- package/dist/{chunk-NRO64VRR.js → chunk-A7AMB23L.js} +1 -1
- package/dist/{chunk-6KCPRIB5.js → chunk-C6PAXO3N.js} +1 -1
- package/dist/chunk-D45U2NXV.js +1 -0
- package/dist/{chunk-LBRXS637.js → chunk-DZCZLRM5.js} +1 -1
- package/dist/chunk-EUNCYGJD.js +1 -0
- package/dist/{chunk-PEBFQ4CL.js → chunk-IAIGT5G3.js} +1 -1
- package/dist/chunk-JIVVHBCB.js +2 -0
- package/dist/{chunk-BY3EPIAB.js → chunk-KWXAZUAZ.js} +1 -1
- package/dist/{chunk-QHWMILLL.js → chunk-NCL672QJ.js} +1 -1
- package/dist/{chunk-CA6HLY7T.js → chunk-O3D7S5MD.js} +1 -1
- package/dist/factories-TLUZAXUG.js +1 -0
- package/dist/index.d.ts +2 -2
- package/dist/index.js +1 -1
- package/dist/ipcFactory-QOAZVE56.js +1 -0
- package/dist/native.d.ts +2 -2
- package/dist/native.js +1 -1
- package/dist/{openrtc-UU4BBJLG.js → openrtc-C53CKZUM.js} +1 -1
- package/dist/openrtc_bg.wasm +0 -0
- package/dist/runtime/WasmRuntimeAdapter.js +1 -1
- package/dist/runtime/index.d.ts +1 -1
- package/dist/runtime/index.js +1 -1
- package/dist/runtime/legacy.js +1 -1
- package/dist/runtime/tauri.js +1 -1
- package/dist/testing.d.ts +1 -1
- package/dist/testing.js +1 -1
- package/dist/{types-ZdRrnIRw.d.ts → types-byWIP-WI.d.ts} +7 -0
- package/package.json +1 -1
- package/dist/chunk-IAEGDK4P.js +0 -2
- package/dist/chunk-JUHDH6K4.js +0 -2
- package/dist/chunk-VGMSLZH5.js +0 -1
- package/dist/chunk-XDYCWI5Z.js +0 -1
- package/dist/factories-JWIRMXCV.js +0 -1
- package/dist/ipcFactory-UAVK2YED.js +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
export{w as WasmBridge}from'./chunk-
|
|
1
|
+
export{w as WasmBridge}from'./chunk-JIVVHBCB.js';import'./chunk-VK6KX433.js';import'./chunk-NT5YHZQH.js';import'./chunk-N26S7V4N.js';import'./chunk-NB4H5TP3.js';import'./chunk-RD3JEGGF.js';import'./chunk-C7YN5MSV.js';
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
var T=new Map;function P(a){let e=new Uint8Array(a),t="";for(let i of e)t+=String.fromCharCode(i);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function V(a){let e=JSON.stringify({crv:a.crv,kty:a.kty,x:a.x});return P(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(e)))}function q(){return P(crypto.getRandomValues(new Uint8Array(24)).buffer)}async function O(){return typeof indexedDB>"u"?null:new Promise((a,e)=>{let t=indexedDB.open("openrtc-v2-device-keys",1);t.onupgradeneeded=()=>{t.result.objectStoreNames.contains("keys")||t.result.createObjectStore("keys");},t.onsuccess=()=>a(t.result),t.onerror=()=>e(t.error);})}async function W(a){let e=await O().catch(()=>null);if(!e)return T.get(a)??null;try{return await new Promise((t,i)=>{let n=e.transaction("keys","readonly").objectStore("keys").get(a);n.onsuccess=()=>t(n.result??null),n.onerror=()=>i(n.error);})}finally{e.close();}}async function B(a,e){let t=await O().catch(()=>null);if(!t){T.set(a,e);return}try{await new Promise((i,n)=>{let r=t.transaction("keys","readwrite").objectStore("keys").put(e,a);r.onsuccess=()=>i(),r.onerror=()=>n(r.error);});}finally{t.close();}}async function z(a){T.delete(a);let e=await O().catch(()=>null);if(e)try{await new Promise((t,i)=>{let n=e.transaction("keys","readwrite").objectStore("keys").delete(a);n.onsuccess=()=>t(),n.onerror=()=>i(n.error);});}finally{e.close();}}async function Z(a){let e=await W(a);if(e)return e;let t=await crypto.subtle.generateKey({name:"Ed25519"},false,["sign","verify"]);return await B(a,t),t}var J={async getOrCreate(a){let e=await Z(a),t=await crypto.subtle.exportKey("jwk",e.publicKey),i=await V(t);return {publicKeyJwk:t,thumbprint:i,async proof(n){let r=q(),o=Math.floor(Date.now()/1e3),s=await crypto.subtle.sign({name:"Ed25519"},e.privateKey,new TextEncoder().encode(n(r,o)));return {publicKeyJwk:t,signature:P(s),nonce:r,issuedAt:o}}}},delete:z};var N={"identity.assertion.exchange":25692e-8,"identity.monthly-active-principal":110352e-9,"capability.issue":212346e-9,"device.enroll":218946e-9,"gateway.grant.issue":202146e-9,"gateway.grant.refresh":200346e-9,"security.attestation.verify":29694e-8,"room.create":388056e-9,"room.join":209946e-9,"room.leave":200346e-9,"coordination.connection.open":287514e-9,"coordination.credential.refresh":259662e-9,"coordination.presence.offline":253638e-9,"coordination.signal.send":259638e-9,"coordination.session.put":259638e-9,"coordination.session.delete":253638e-9,"coordination.usage.ingest":197088e-9};var R={controlPlane:"https://api.openrtc.app",gateway:"https://gateway.openrtc.app"},j=1440*6e4,f=class extends Error{constructor(t,i){super(t);this.status=i;this.name="OpenRTCV2HttpError";}};function k(a,e,t){return `openrtc:v2:device-certificate:${a}:${e}:${t}`}function A(a,e){return `openrtc:v2:device-session:${a}:${e}`}async function X(a,e,t){let i=new TextEncoder().encode(`openrtc:v2:session\0${a}\0${e}\0${t}`),n=new Uint8Array(await crypto.subtle.digest("SHA-256",i)),r="";for(let o of n)r+=String.fromCharCode(o);return btoa(r).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,"")}function U(a){let e=a.replace(/-/g,"+").replace(/_/g,"/"),t=e.padEnd(Math.ceil(e.length/4)*4,"="),i=atob(t);return Uint8Array.from(i,n=>n.charCodeAt(0))}async function F(a,e,t,i,n){if(typeof a.token!="string"||typeof a.expiresAtMs!="number"||a.expiresAtMs<=Date.now()+j||!a.signingPublicJwk||a.signingPublicJwk.kty!=="OKP"||a.signingPublicJwk.crv!=="Ed25519"||typeof a.signingPublicJwk.x!="string")return null;let r=a.token.split(".");if(r.length!==3)return null;let o,s;try{o=JSON.parse(new TextDecoder().decode(U(r[0]))),s=v(a.token);}catch{return null}if(o.alg!=="EdDSA"||a.signingPublicJwk.kid&&o.kid!==a.signingPublicJwk.kid)return null;try{let u=await crypto.subtle.importKey("jwk",a.signingPublicJwk,{name:"Ed25519"},!1,["verify"]);if(!await crypto.subtle.verify({name:"Ed25519"},u,U(r[2]),new TextEncoder().encode(`${r[0]}.${r[1]}`)))return null}catch{return null}let c=typeof s.principalId=="string"?s.principalId:"",l=Number(s.iat),d=Number(s.exp);return s.iss!=="openrtc"||s.aud!=="openrtc:v2:gateway-grant"||s.typ!=="device-certificate"||s.appTag!==e||!c||n!==void 0&&c!==n||typeof s.principalKey!="string"||s.principalKey.length===0||s.deviceId!==t||s.deviceKeyThumbprint!==i||typeof s.jti!="string"||s.jti.length===0||!Number.isSafeInteger(l)||!Number.isSafeInteger(d)||l>=d||d*1e3!==a.expiresAtMs?null:{token:a.token,expiresAtMs:a.expiresAtMs,principalId:c,signingPublicJwk:a.signingPublicJwk,enrolled:false}}async function Q(a,e,t,i){try{let n=globalThis.localStorage?.getItem(k(a,e,t));if(!n)return null;let r=JSON.parse(n),o=await F(r,a,t,i,e);return o?{token:o.token,expiresAtMs:o.expiresAtMs,principalId:e,signingPublicJwk:o.signingPublicJwk}:null}catch{return null}}async function Y(a,e,t,i){try{let n=globalThis.localStorage?.getItem(A(a,t));return n?await F(JSON.parse(n),e,t,i):null}catch{return null}}function ee(a,e,t,i){try{globalThis.localStorage?.setItem(k(a,e,t),JSON.stringify(i));}catch{}}function te(a,e,t){try{globalThis.localStorage?.setItem(A(a,e),JSON.stringify({token:t.token,expiresAtMs:t.expiresAtMs,principalId:t.principalId,signingPublicJwk:t.signingPublicJwk}));}catch{}}function $(a,e,t,i){try{globalThis.localStorage?.removeItem(k(a,e,t)),i&&globalThis.localStorage?.removeItem(A(i,t));}catch{}}function ie(a){return `${a}_${crypto.randomUUID()}`}async function ne(a,e){let t=new TextEncoder().encode(`${a}:${e}`);return [...new Uint8Array(await crypto.subtle.digest("SHA-256",t))].map(n=>n.toString(16).padStart(2,"0")).join("")}function v(a){let e=a.split(".")[1];if(!e)throw new Error("OpenRTC returned a malformed credential.");let t=e.replace(/-/g,"+").replace(/_/g,"/"),i=t.padEnd(Math.ceil(t.length/4)*4,"=");return JSON.parse(atob(i))}var C=class{constructor(e,t,i,n,r={},o){this.apiKey=e;this.endpoints=t;this.keyProvider=i;this.attestation=n;this.events=r;this.botVerification=o;this.keyPromise=null;this.authEpochs=new Map;this.appTag=`app_${e.slice(-16)}`;}record(e){this.events.onLogicalOperation?.(e);}before(e){this.events.beforeLogicalOperation?.(e);}authEpoch(e){let t=this.authEpochs.get(e);if(t)return t;let i={generation:0,devices:new Map};return this.authEpochs.set(e,i),e.subscribe&&(i.unsubscribe=e.subscribe(n=>{n?.type==="principal-changed"&&(i.generation+=1,i.devices.clear(),i.sessionKeyHash=void 0,this.events.onAuthEpochChanged?.(e));})),i}dispose(){for(let e of this.authEpochs.values())e.unsubscribe?.();this.authEpochs.clear();}key(){return this.keyPromise??(this.keyPromise=this.keyProvider.getOrCreate(this.appTag))}async post(e,t){let i=ie("request"),n=JSON.stringify({apiKey:this.apiKey,...t}),r=null;for(let o=0;o<2;o+=1)try{let s=await fetch(`${this.endpoints.controlPlane}${e}`,{method:"POST",headers:{"Content-Type":"application/json","X-OpenRTC-Idempotency-Key":i},body:n,signal:AbortSignal.timeout(15e3)});if(s.ok)return s.json();let c=`OpenRTC request failed (${s.status}).`;try{let d=await s.json();typeof d.error=="string"&&(c=d.error.slice(0,256));}catch{}let l=new f(c,s.status);if(r=l,o===0&&[502,503,504].includes(s.status))continue;throw l}catch(s){if(r=s,o===0&&s instanceof TypeError)continue;throw s}throw r instanceof Error?r:new Error("OpenRTC request failed.")}async capability(e,t,i,n=false){this.before("capability.issue");let r=e==="space"?await ne(this.apiKey,t):t,s=await(await this.key()).proof((u,p)=>["openrtc:v2:capability",this.apiKey,e,r,u,p].join(":")),c=this.botVerification?await this.botVerification.getToken({action:"openrtc_capability",apiKey:this.apiKey}):void 0,l=await this.post("/v2/capabilities",{avenue:{kind:e,id:r},deviceProof:s,...i?{maxPeers:i}:{},...n?{advancedFanout:true}:{},...c?{turnstileToken:c}:{}});this.record("capability.issue");let d={type:"capability",token:l.capability,avenue:e==="ticket"?{kind:"session",id:r}:l.avenue,expiresAtMs:l.expiresAt*1e3};return d.renew=()=>this.capability(e,t,i,n),d}async deviceCertificate(e,t,i){let n=this.authEpoch(e),r=n.devices.get(t)??{};if(n.devices.set(t,r),r.current&&r.current.expiresAtMs>Date.now()+j)return this.deviceCertificateResult(e,t,i,{...r.current,enrolled:false});if(!r.inFlight){let s=n.generation;r.inFlight=this.resolveAuthenticatedDevice(e,t,n).then(c=>{if(n.generation!==s)throw new Error("The OpenRTC authentication identity changed during enrollment.");return r.current=c,c}).finally(()=>{r.inFlight=void 0;});}let o=await r.inFlight;return this.deviceCertificateResult(e,t,i,o)}async resolveAuthenticatedDevice(e,t,i){let n=await this.key();if(e.getSessionKey){let r=await e.getSessionKey();if(!r)throw new Error("The OpenRTC auth provider has no active principal.");let o=await X(this.appTag,n.thumbprint,r);i.sessionKeyHash=o;let s=await Y(o,this.appTag,t,n.thumbprint);if(s)return s}return this.enrollAuthenticatedDevice(e,t,i.sessionKeyHash)}deviceCertificateResult(e,t,i,n){let r={type:"device-certificate",token:n.token,avenue:i??{kind:"user",id:n.principalId},expiresAtMs:n.expiresAtMs};return r.renew=async()=>(await this.deviceCertificate(e,t,i)).source,{principalId:n.principalId,source:r,enrolled:n.enrolled}}async enrollAuthenticatedDevice(e,t,i){this.before("identity.assertion.exchange"),this.before("identity.monthly-active-principal");let n=async p=>{let h=await e.getAssertion({audience:"https://api.openrtc.app/v2/assertions/exchange",forceRefresh:p,deviceId:t});if(!h)throw new Error("The OpenRTC auth provider returned no assertion.");return this.post("/v2/assertions/exchange",{assertion:h,...e.providerId?{providerId:e.providerId}:{}})},r;try{r=await n(!1);}catch(p){if(!(p instanceof f)||p.status!==401)throw p;r=await n(true);}this.record("identity.assertion.exchange"),this.record("identity.monthly-active-principal");let o=await this.key(),s=await Q(this.appTag,r.principalId,t,o.thumbprint);if(s)return {...s,principalId:r.principalId,enrolled:false};this.before("device.enroll"),this.attestation&&this.before("security.attestation.verify");let c=await o.proof((p,h)=>["openrtc:v2:device-enroll",this.appTag,r.principalId,t,p,h].join(":")),l=this.attestation?{kind:this.attestation.kind,...await this.attestation.getEvidence({challenge:`openrtc:v2:attestation:${this.appTag}:${r.principalId}:${t}:${c.nonce}`,apiKey:this.apiKey})}:void 0,d=await this.post("/v2/devices/enroll",{identitySession:r.identitySession,deviceId:t,deviceProof:c,...l?{attestation:l}:{}});this.record("device.enroll"),l&&this.record("security.attestation.verify");let u={principalId:r.principalId,token:d.deviceCertificate,expiresAtMs:d.expiresAt*1e3,signingPublicJwk:d.signingPublicJwk,enrolled:true};return ee(this.appTag,r.principalId,t,{token:u.token,expiresAtMs:u.expiresAtMs,signingPublicJwk:u.signingPublicJwk}),i&&te(i,t,u),u}async listEnrolledDevices(e,t){let i=await this.deviceCertificate(e,t);return (await this.deviceManagement(i.source,t,"list")).devices??[]}async revokeDevice(e,t,i){let n=await this.deviceCertificate(e,t);if(await this.deviceManagement(n.source,t,"revoke",i),i===t){let r=this.authEpoch(e);$(this.appTag,n.principalId,t,r.sessionKeyHash),r.devices.delete(t),await this.deleteDeviceKey();}}async revokeAllDevices(e,t,i){let n=await this.deviceCertificate(e,t);await this.deviceManagement(n.source,t,"revoke-all",void 0,i);let r=this.authEpoch(e);$(this.appTag,n.principalId,t,r.sessionKeyHash),r.devices.delete(t),i?await this.deviceCertificate(e,t):(r.devices.clear(),await this.deleteDeviceKey());}async deleteDeviceKey(){this.keyPromise=null,await this.keyProvider.delete?.(this.appTag);}async deviceManagement(e,t,i,n,r=false){if(e.type!=="device-certificate")throw new Error("Device management requires an authenticated device certificate.");let o=v(e.token),s=String(o.jti??""),l=await(await this.key()).proof((p,h)=>["openrtc:v2:device-management",s,i,n??"",r?"except-current":"include-current",p,h].join(":")),d=i==="revoke"?"device.revoke":i==="revoke-all"?"identity.revoke-all":null;d&&this.before(d);let u=await this.post("/v2/devices/manage",{action:i,deviceCertificate:e.token,currentDeviceId:t,...n?{targetDeviceId:n}:{},...r?{exceptCurrent:true}:{},deviceProof:l});return d&&this.record(d),u}async durableRoomMembership(e,t,i){if(e.type!=="device-certificate")throw new Error("Durable rooms require a device certificate.");this.before(i==="join"?"room.join":"room.leave");let n=v(e.token),r=String(n.jti??""),s=await(await this.key()).proof((c,l)=>["openrtc:v2:room-membership",r,i,t,c,l].join(":"));await this.post("/v2/rooms/memberships",{action:i,roomId:t,deviceCertificate:e.token,deviceProof:s}),this.record(i==="join"?"room.join":"room.leave");}grantProvider(e,t={}){let i=null,n=e;return async r=>{if(i)return i;let o=(async()=>{let s=false;n.expiresAtMs<=Date.now()+5*6e4&&n.renew&&(n=await n.renew(),s=true);let c=r.refreshGrant?"gateway.grant.refresh":"gateway.grant.issue";this.before(c),r.refreshGrant&&this.before("coordination.credential.refresh");let l=v(n.token),d=String(l.jti??""),p=await(await this.key()).proof((y,b)=>["openrtc:v2:gateway-grant",d,r.avenue.kind,r.avenue.id,r.runtimeInstanceId,y,b].join(":")),h=await this.post("/v2/gateway/grants",{credentialType:n.type,credential:n.token,avenue:r.avenue,runtimeInstanceId:r.runtimeInstanceId,ticketFingerprint:r.ticketFingerprint,deviceProof:p,...r.refreshGrant?{refreshGrant:r.refreshGrant}:{},...t.maxPeers?{maxPeers:t.maxPeers}:{},...t.features?{features:t.features}:{}});return this.record(c),r.refreshGrant&&this.record("coordination.credential.refresh"),s&&await t.onSourceRenewed?.({token:n.token,expiresAtMs:n.expiresAtMs}),h})();i=o;try{return await o}finally{i===o&&(i=null);}}}};var I=new WeakMap;function ye(a){let e=I.get(a);if(!e)throw new Error("[OpenRTC] Capability runtime is unavailable or already closed.");return e}function re(a){let e=a?.trim()??"";if(!/^pk_(?:live|test)_[0-9a-f]{40}$/.test(e))throw new Error("[OpenRTC] apiKey must be a public pk_live_ or pk_test_ key.");return e}function g(a){let e=a?.trim()??"";if(!e||e.length>160||!/^[A-Za-z0-9_.:@-]+$/.test(e))throw new Error("[OpenRTC] Capability id is invalid.");return e}function ae(a){let e=a?.trim();if(e){if(new TextEncoder().encode(e).byteLength>4*1024)throw new Error("[OpenRTC] Device profile metadata must not exceed 4 KiB.");return e}}var G=/^[A-Za-z0-9_.:@-]{1,160}$/,se=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;function L(a){let e=typeof a=="string"?a.trim():"";if(!G.test(e))return null;let t=e.startsWith("device_")?e.slice(7):"";return se.test(t)?t:e}function oe(a,e){try{let t=a.getItem(`pluto_rtc_web_device_identity_${e}`);if(!t)return null;let i=JSON.parse(t);return L(i?.deviceId)}catch{return null}}function ce(a){let e=`openrtc:v2:device-id:${a}`,t=`pluto_rtc_web_device_identity_${a}`,i,n=(()=>{try{return i=globalThis.localStorage,i&&oe(i,a)||L(i?.getItem(e))||crypto.randomUUID()}catch{return crypto.randomUUID()}})();try{i?.setItem(e,n),i?.setItem(t,JSON.stringify({deviceId:n}));}catch{}return n}function H(a){let e=typeof a=="string"?a.trim():"";if(!G.test(e))throw new Error("[OpenRTC] The native host returned an invalid durable device ID.");return e}function S(a){let e=v(a.token),t=typeof e.deviceKeyThumbprint=="string"?e.deviceKeyThumbprint.trim():"";if(!/^[A-Za-z0-9_-]{43}$/.test(t))throw new Error("[OpenRTC] Anonymous capability is missing its device-key binding.");return `anon_${t.slice(0,32)}`}var x=class{constructor(){this.descriptors=new Map;this.targets=new Map;}register(e){if(!e?.id?.trim())throw new Error("[OpenRTC] Channel id is required.");this.descriptors.set(e.id,{...e});for(let[t,i]of this.targets)t.channels.register({...e,delivery:e.delivery??i});return ()=>{this.descriptors.delete(e.id);for(let t of this.targets.keys())t.channels.unregister(e.id);}}list(){return [...this.descriptors.values()].map(e=>({...e}))}attach(e,t){this.targets.set(e,t);for(let i of this.descriptors.values())e.channels.register({...i,delivery:i.delivery??t});}detach(e){this.targets.delete(e);}},D=class{constructor(e){this.options=e;this.total=0;this.warned=false;}get sessionCreditsUsd(){return this.total}estimate(e){let t=Math.max(0,Math.floor(e.units??1));return {creditsUsd:(N[e.operation]??0)*t,estimated:true}}assertCanSpend(e,t=1){let i=this.options?.maxSessionCreditsUsd;if(i===void 0||this.total+this.estimate({operation:e,units:t}).creditsUsd<=i)return;let r={sessionCreditsUsd:this.total,operation:e,estimated:true,thresholdCreditsUsd:i,kind:"session-limit"};throw this.options?.onWarning?.(r),new Error("[OpenRTC] The client-side session credit limit was reached.")}record(e,t=1){let i=this.estimate({operation:e,units:t}).creditsUsd;this.total+=i;let n={sessionCreditsUsd:this.total,operation:e,estimated:true};this.options?.onUsage?.(n);let r=this.options?.warnAtSessionCreditsUsd;!this.warned&&r!==void 0&&this.total>=r&&(this.warned=true,this.options?.onWarning?.({...n,thresholdCreditsUsd:r,kind:"warning"}));}},m=class{constructor(e,t,i,n){this.kind=e;this.id=t;this.client=i;this.onClosed=n;this.closed=false;I.set(this,i);}get peers(){return this.client.peers}get channels(){return this.client.channels}get diagnostics(){return this.client.diagnostics}async retireDeviceIfPresent(e){(await this.client.devices.list()).some(i=>i.deviceId===e)&&await this.client.devices.delete(e);}async retireAllOtherDevices(e){let t=await this.client.devices.list();for(let i of t)i.deviceId!==e&&await this.client.devices.delete(i.deviceId);}async close(){if(!this.closed){this.closed=true;try{await this.client.advanced.runtime.shutdown();}finally{I.delete(this),this.onClosed();}}}},E=class extends m{constructor(t,i,n){super("devices",t,i,n);this.kind="devices";this.localId=()=>this.client.devices.localId();this.localInfo=()=>this.client.devices.localInfo();this.list=()=>this.client.devices.list();this.listWithStatus=()=>this.client.devices.listWithStatus();this.watch=this.client.devices.watch;this.connect=this.client.devices.connect;this.disconnect=this.client.devices.disconnect;}},K=class extends m{constructor(t,i,n,r){super("space",t,i,n);this.delivery=r;this.kind="space";this.leave=()=>this.close();}},w=class extends m{constructor(t,i,n,r,o){super("room",t,i,n);this.membership=r;this.onLeave=o;this.kind="room";this.left=false;}async leave(){this.left||(this.left=true,await this.onLeave?.()),await this.close();}},M=class extends m{constructor(t,i,n,r){super("ticket",t,i,n);this.token=r;this.kind="ticket";}},_=class{constructor(e,t){this.options=e;this.internals=t;this.channels=new x;this.handles=new Set;this.activations=new Map;this.closed=false;this.devices={start:(e={})=>{let t=e.auth??this.options.auth;return this.activateOnce("devices",JSON.stringify({autoConnect:e.autoConnect??"online",maxPeers:e.maxPeers??null,advancedFanout:e.advancedFanout===true,profile:e.profile??null}),t,()=>this.startDevices(e))},listEnrolled:async(e={})=>{this.assertOpen();let t=e.auth??this.options.auth;if(!t)throw new Error("[OpenRTC] devices.listEnrolled() requires an auth provider.");return this.controlPlane.listEnrolledDevices(t,await this.deviceId())},revoke:async(e,t={})=>{this.assertOpen();let i=t.auth??this.options.auth;if(!i)throw new Error("[OpenRTC] devices.revoke() requires an auth provider.");let n=H(e),r=await this.deviceId();await this.controlPlane.revokeDevice(i,r,n),await Promise.allSettled([...this.handles].map(o=>o.retireDeviceIfPresent(n))),n===r&&this.retireAuthCapabilities(i);},revokeAll:async(e={})=>{this.assertOpen();let t=e.auth??this.options.auth;if(!t)throw new Error("[OpenRTC] devices.revokeAll() requires an auth provider.");if(await this.controlPlane.revokeAllDevices(t,await this.deviceId(),e.exceptCurrent===true),e.exceptCurrent===true){let i=await this.deviceId();await Promise.allSettled([...this.handles].map(n=>n.retireAllOtherDevices(i)));}e.exceptCurrent!==true&&this.retireAuthCapabilities(t);}};this.spaces={join:(e,t={})=>this.activateOnce(`space:${g(e)}`,JSON.stringify({payload:t.payload??"reliable",maxPeers:t.maxPeers??null,advancedFanout:t.advancedFanout===true}),void 0,()=>this.joinSpace(e,t))};this.rooms={join:(e,t={})=>{let i=t.access??"capability";return this.activateOnce(`room:${g(e)}`,JSON.stringify({access:i,membership:t.membership??"ephemeral",maxPeers:t.maxPeers??null,advancedFanout:t.advancedFanout===true}),i==="authenticated"?t.auth??this.options.auth:void 0,()=>this.joinRoom(e,t))}};this.tickets={issue:(e,t={})=>this.activateOnce(`ticket:${g(e)}`,JSON.stringify({maxPeers:t.maxPeers??null,advancedFanout:t.advancedFanout===true}),void 0,()=>this.issueTicket(e,t))};this.onClosed=e=>{this.handles.delete(e);for(let[t,i]of this.activations)i.handle===e&&this.activations.delete(t);};this.apiKey=re(e.apiKey),this.usage=new D(e.usage),this.controlPlane=new C(this.apiKey,t.endpoints??R,t.deviceKeyProvider??J,e.trust?.attestation,{beforeLogicalOperation:i=>this.usage.assertCanSpend(i),onLogicalOperation:i=>this.usage.record(i),onAuthEpochChanged:i=>this.retireAuthCapabilities(i)},e.trust?.botVerification);}assertOpen(){if(this.closed)throw new Error("[OpenRTC] Client is closed.")}activateOnce(e,t,i,n){this.assertOpen();let r=this.activations.get(e);if(r){if(r.fingerprint!==t||r.auth!==i)throw new Error(`[OpenRTC] ${e} is already active with different options.`);return r.promise}let o={fingerprint:t,auth:i},s=n().then(c=>(o.handle=c,c)).catch(c=>{throw this.activations.get(e)===o&&this.activations.delete(e),c});return o.promise=s,this.activations.set(e,o),s}retireAuthCapabilities(e){for(let t of this.activations.values())t.auth===e&&t.promise.then(i=>i.close()).catch(()=>{});}async deviceId(){let e=this.internals.deviceIdProvider?await this.internals.deviceIdProvider(this.controlPlane.appTag):ce(this.controlPlane.appTag);return H(e)}runtimeOptions(e){let t=this.options.transports,i=t?.privacy==="relay-only";if(i&&t?.relay!==true)throw new Error("[OpenRTC] transports.privacy: relay-only requires transports.relay: true.");return {apiKey:this.apiKey,authMode:"external",discoveryMode:e.avenue?.kind==="user"?"user-scoped":"space",space:e.avenue?.id,localDeviceId:e.deviceId,deviceIdPersistence:"persistent",endpointIdPersistence:this.internals.platform==="native"?"persistent":"ephemeral",deviceName:e.deviceName?.trim()||void 0,nativeApplicationStreamConsumer:this.internals.platform==="native"&&t?.nativeHostProtocols===true?"host":"runtime",coordinationAvenueOverride:e.avenue,coordinationGateway:{endpoint:(this.internals.endpoints??R).gateway,environment:"production",grantProvider:e.grantProvider,testingAllowInsecureLoopback:this.internals.testingAllowInsecureLoopback},transports:{iroh:i?{relayOnly:true,relayTransportPolicy:"websocketRequired",localDiscovery:false,persistenceMode:this.internals.platform==="native"?"persistent":"ephemeral",...this.internals.irohTestRelayUrl?{testRelayUrl:this.internals.irohTestRelayUrl}:{}}:this.internals.irohTestRelayUrl?{testRelayUrl:this.internals.irohTestRelayUrl,persistenceMode:this.internals.platform==="native"?"persistent":"ephemeral"}:t?.iroh??true,webrtc:t?.webrtc===true?i?{privacyMode:true,useTurn:true,useDefaultIceServers:false}:true:false,ble:t?.ble??false,moq:t?.moq??false},transportPriority:t?.priority}}async activate(e){let t={relay:this.options.transports?.relay===true,moq:this.options.transports?.moq===true,ble:this.options.transports?.ble===true,advancedFanout:e.advancedFanout===true,durableMembership:e.durableMembership===true},i=e.source,n=null,r=()=>({userId:e.principalId,token:i.token,tokenProvider:async()=>i.token,expiresAtMs:i.expiresAtMs}),o=this.runtimeOptions({avenue:e.source.avenue,grantProvider:this.controlPlane.grantProvider(e.source,{maxPeers:e.maxPeers,features:t,onSourceRenewed:async l=>{i={...i,...l},await n?.setAuth(r());}}),deviceId:e.deviceId,userId:e.principalId,deviceName:e.deviceName}),[s,{wrapAssembly:c}]=await Promise.all([this.internals.runtimeFactory(o),import('./OpenRTCShared-TKAQLONA.js')]);n=c(s,this.internals.platform==="native"?"native":"web"),await n.setAuth(r()),this.channels.attach(n,e.defaultDelivery??"reliable");try{this.usage.assertCanSpend("coordination.connection.open"),await n.devices.startSession({sessionKind:e.kind==="devices"?"app-user-device":"scoped-guest",scope:`v2:${e.kind}:${e.id}`,userId:e.principalId,localDeviceId:e.deviceId,metadata:e.deviceMetadata,autoConnectPolicy:e.autoConnect?"enabled":"disabled",presencePolicy:"online"});}catch(l){throw this.channels.detach(n),await n.advanced.runtime.shutdown().catch(()=>{}),l}return this.usage.record("coordination.connection.open"),n}async startDevices(e={}){this.assertOpen();let t=e.auth??this.options.auth;if(!t)throw new Error("[OpenRTC] devices.start() requires an auth provider.");let i=await this.deviceId(),n=await this.controlPlane.deviceCertificate(t,i),r=await this.activate({kind:"devices",id:n.principalId,source:n.source,principalId:n.principalId,deviceId:i,maxPeers:e.maxPeers,autoConnect:e.autoConnect!=="none",advancedFanout:e.advancedFanout,deviceName:e.profile?.name,deviceMetadata:ae(e.profile?.metadata)}),o;return o=new E(n.principalId,r,()=>{this.channels.detach(r),this.onClosed(o);}),this.handles.add(o),o}async joinSpace(e,t={}){this.assertOpen();let i=g(e),n=await this.controlPlane.capability("space",i,t.maxPeers,t.advancedFanout),r=String(v(n.token).principalId),o=await this.activate({kind:"space",id:i,source:n,principalId:r,deviceId:S(n),maxPeers:t.maxPeers,autoConnect:true,defaultDelivery:t.payload??"reliable",advancedFanout:t.advancedFanout}),s;return s=new K(i,o,()=>{this.channels.detach(o),this.onClosed(s);},t.payload??"reliable"),this.handles.add(s),s}async joinRoom(e,t={}){this.assertOpen();let i=g(e),n=t.membership??"ephemeral",r=t.access??"capability";if(n==="durable"&&r!=="authenticated")throw new Error("[OpenRTC] Durable room membership requires access: authenticated.");if(r==="authenticated"){let d=t.auth??this.options.auth;if(!d)throw new Error("[OpenRTC] Authenticated rooms require an auth provider.");let u=await this.deviceId(),p=await this.controlPlane.deviceCertificate(d,u,{kind:"room",id:i});n==="durable"&&await this.controlPlane.durableRoomMembership(p.source,i,"join");let h;try{h=await this.activate({kind:"room",id:i,source:p.source,principalId:p.principalId,deviceId:u,maxPeers:t.maxPeers,autoConnect:!0,durableMembership:n==="durable",advancedFanout:t.advancedFanout});}catch(b){throw n==="durable"&&await this.controlPlane.durableRoomMembership(p.source,i,"leave").catch(()=>{}),b}let y;return y=new w(i,h,()=>{this.channels.detach(h),this.onClosed(y);},n,n==="durable"?async()=>{await this.controlPlane.durableRoomMembership(p.source,i,"leave");}:void 0),this.handles.add(y),y}let o=await this.controlPlane.capability("room",i,t.maxPeers,t.advancedFanout),s=String(v(o.token).principalId),c=await this.activate({kind:"room",id:i,source:o,principalId:s,deviceId:S(o),maxPeers:t.maxPeers,autoConnect:true,advancedFanout:t.advancedFanout}),l;return l=new w(i,c,()=>{this.channels.detach(c),this.onClosed(l);},"ephemeral"),this.handles.add(l),l}async issueTicket(e,t={}){this.assertOpen();let i=g(e),n=await this.controlPlane.capability("ticket",i,t.maxPeers,t.advancedFanout),r=String(v(n.token).principalId),o=await this.activate({kind:"ticket",id:i,source:n,principalId:r,deviceId:S(n),maxPeers:t.maxPeers,autoConnect:false,advancedFanout:t.advancedFanout}),s;return s=new M(i,o,()=>{this.channels.detach(o),this.onClosed(s);},n.token),this.handles.add(s),s}async close(){if(!this.closed){this.closed=true;try{await Promise.all([...this.handles].map(e=>e.close()));}finally{this.controlPlane.dispose(),this.activations.clear();}}}};function ge(a,e){return new _(a,e)}
|
|
2
|
+
export{V as a,ye as b,ge as c};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import {a as a$1}from'./chunk-6KCPRIB5.js';import {o,u,w,s,h as h$1,g,j as j$2,k as k$1,l,m,n}from'./chunk-JUHDH6K4.js';import {c as c$1,b as b$1}from'./chunk-VK6KX433.js';import {c,d as d$1,b}from'./chunk-K37WVIZL.js';import {a as a$2}from'./chunk-BXFXPIXO.js';import {c as c$2,b as b$2}from'./chunk-N26S7V4N.js';import {d,a}from'./chunk-NB4H5TP3.js';import {d as d$2,j as j$1}from'./chunk-RD3JEGGF.js';var H="relay-only endpoint ticket unavailable",Q=12e3,X=250,Z=1500;function ee(g){return String(g?.message??g??"").toLowerCase().includes(H)}async function E(g,e={}){let t=e.windowMs??Q,i=e.minDelayMs??X,a$1=e.maxDelayMs??Z,n=Date.now(),s=0,o=null;for(;e.isActive?.()??true;){s+=1;try{return await g()}catch(c){if(o=c,!ee(c))throw c;let d$1=Date.now()-n;if(d$1>=t)throw c;let r=Math.min(d(s,i,a$1),Math.max(0,t-d$1));r>0&&await a(r);}}throw o||new Error("endpoint ticket minting stopped before a ticket was available")}function Y(g){let e=g?.split(".")[1];if(!e)return null;try{let t=e.replace(/-/g,"+").replace(/_/g,"/"),i=(4-t.length%4)%4,a=atob(t+"=".repeat(i)),n=JSON.parse(a);return n&&typeof n=="object"&&!Array.isArray(n)?n:null}catch{return null}}function k(g,e){let t=g?.[e];return typeof t=="string"&&t.trim()?t.trim():null}function j(g,e,t){let i=k(g,"namespaceId")===e||k(g,"appTag")===`space::${e}`,a=k(g,"developerAppTag");return i&&!!a&&(!t||a===t)}function ae(g){let e=k(g,"developerAppTag");if(e)return e;let t=k(g,"appTag");return t&&!t.startsWith("space::")?t:null}var h=class h{constructor(e){this.subscriptionNonce=0;this.lastSyncedAuthToken=null;this.cachedLocalDeviceId=null;this.cachedLocalDeviceName=null;this.tauriCoreAvailability=null;this.tauriCoreAvailabilityValue=null;this.tauriCoreAvailabilityCheckedAtMs=0;this.authSyncInFlight=null;this.nativeTrustTokenUnsubscribe=null;this.nativeTrustRelayQueue=Promise.resolve();this.nativeTrustRelayError=null;this.nativeRuntimeCapabilitiesSyncInFlight=null;this.gatewayDesiredPeersCleanup=null;this.gatewayDesiredPeerRelayKey=null;this.gatewayDesiredPeerRelayGeneration=0;this.gatewayDesiredPeerRevision=0;this.gatewayDesiredPeerSubmission=Promise.resolve();this.gatewayDesiredPeerLifecycle=Promise.resolve();this.gatewayExcludedPeers=new Set;this.lastNativeAuthSyncAtMs=0;this.runtimeCapabilities=u(null,false);this.fallback=new w({...e,coordinationPlatformType:"desktop"}),this.app=this.fallback.app,this.auth=this.fallback.auth,this.appTag=this.fallback.tag,this.options=this.fallback.getResolvedOptions(),this.transportOptions=e.transports,this.strictMode=e.strictMode===true,this.turnCredentialsProvider=e.turnCredentialsProvider,this.allowWasmFallback=e.allowWasmFallback??false,this.ipcBridge=c(e.ipcBridge??d$1(),"NativeIpcBridge"),this.runtimeCapabilities=u(null,this.allowWasmFallback),this.syncNativeRuntimeCapabilities("constructor");}get currentUser(){return this.fallback.currentUser}get tag(){return this.fallback.tag}getRuntimeCapabilities(){let e=s(this.runtimeCapabilities);return e.fallback.wasm=this.allowWasmFallback,e}usesCoordinationGateway(){return this.fallback.usesCoordinationGateway()}assertManagedCoordinationGateway(){if(!this.usesCoordinationGateway())throw new Error("[OpenRTC] Native managed coordination requires coordinationGateway; the legacy native Firebase data plane has been removed.")}async joinCoordinationRoom(e,t,i){await this.syncCoordinationDeviceIdentity(),await this.fallback.joinCoordinationRoom(e,t,i);}leaveCoordinationRoom(e){return this.fallback.leaveCoordinationRoom(e)}getCoordinationRoomMembers(e){return this.fallback.getCoordinationRoomMembers(e)}watchCoordinationRoomMembers(e,t){return this.fallback.watchCoordinationRoomMembers(e,t)}async syncCoordinationDeviceIdentity(){if(!this.usesCoordinationGateway())return;let e=await this.getLocalDeviceInfo().catch(()=>null),t=e?.deviceId||await this.resolveLocalDeviceId();this.fallback.setCoordinationLocalDeviceId(t),this.fallback.setCoordinationPlatformType(this.normalizeNativeCoordinationPlatform(e?.platformType));}setWasmClient(e){if(!this.allowWasmFallback){let t="[NativeIpcBridge][NATIVE-GUARD] Refusing WasmClient attachment because native IPC is authoritative and WASM fallback is disabled.";throw console.error(t,{capabilities:this.getRuntimeCapabilities()}),new Error(t)}this.fallback.setWasmClient(e);}onAuthChange(e){return this.fallback.onAuthChange(e)}checkForSSOToken(){return this.fallback.checkForSSOToken()}waitForAuth(){return this.fallback.waitForAuth()}signInAnonymously(){return this.fallback.signInAnonymously()}getTurnCredentials(){return this.fallback.getTurnCredentials()}cleanupStaleDevices(){return this.fallback.cleanupStaleDevices()}sendMessage(e,t,i,a){return this.fallback.sendMessage(e,t,i,a)}pollMessages(e){return this.fallback.pollMessages(e)}watchFriendDevices(e,t){return this.assertManagedCoordinationGateway(),this.fallback.watchFriendDevices(e,t)}async updateFriendTicket(e){this.assertManagedCoordinationGateway(),await this.syncCoordinationDeviceIdentity(),await this.fallback.updateFriendTicket(e);}createSession(e){return this.fallback.createSession(e)}updateSession(e,t){return this.fallback.updateSession(e,t)}async openPeerBi(e,t){return await this.canUseTauriIpc()?this.openPeerBiViaIpc("open_peer_bi_stream",{peerId:e,timeoutMs:t??null}):this.fallback.openPeerBi(e,t)}async openPeerBiTransportOnly(e,t){return await this.canUseTauriIpc()?this.openPeerBiViaIpc("open_peer_bi_transport_only_stream",{peerId:e,timeoutMs:t??null},{fallbackCommand:"open_peer_bi_stream"}):this.fallback.openPeerBiTransportOnly(e,t)}async openPeerNativeBi(e,t,i){return await this.canUseTauriIpc()?this.openPeerBiViaIpc("open_peer_native_bi_stream",{peerId:e,label:t,timeoutMs:i??null},{fallbackCommand:"open_peer_bi_stream",fallbackArgs:{peerId:e,timeoutMs:i??null}}):this.fallback.openPeerNativeBi(e,t,i)}async incoming_streams(){if(!await this.canUseTauriIpc()){let n=this.fallback;if(typeof n.incoming_streams=="function")return n.incoming_streams();throw new Error("Native incoming stream bridge is unavailable")}let e=`native-incoming-${Date.now()}-${++this.subscriptionNonce}`,t=null,i=false,a=async()=>{i=true;let n=t;t=null,await Promise.allSettled([n?Promise.resolve(n()):Promise.resolve(),this.invokeIpc("stop_rtc_subscription",{requestId:e},{timeoutMs:null}).catch(()=>{})]);};return new ReadableStream({start:async n=>{try{t=await this.listenIpc("openrtc://peer-bi-stream/incoming",s=>{if(i)return;let o=s.payload,c=typeof o?.requestId=="string"?o.requestId:typeof o?.request_id=="string"?o.request_id:"";if(c!==e){c$1("[NativeIpcBridge][incoming-application-stream] ignored request id",{expectedRequestId:e,eventRequestId:c});return}let d=typeof o?.streamId=="string"?o.streamId.trim():typeof o?.stream_id=="string"?o.stream_id.trim():"";if(!d)return;let r=typeof o?.remoteNodeId=="string"?o.remoteNodeId.trim():typeof o?.remote_node_id=="string"?o.remote_node_id.trim():"",l=Number.isSafeInteger(o?.transportStableId)?Number(o.transportStableId):Number.isSafeInteger(o?.transport_stable_id)?Number(o.transport_stable_id):0;if(!r||l<=0){c$1("[NativeIpcBridge][incoming-application-stream] ignored invalid generation",{requestId:e,remoteNodeId:r,transportStableId:l});return}c$1("[NativeIpcBridge][incoming-application-stream] accepted event",{requestId:e,remoteNodeId:r,transportStableId:l});let u=this.peerBiStreamFromId(d,{startReadAfterListeners:!0});n.enqueue({type:"bi",stream:{send:u.writable,recv:u.readable,endpoint_id:r},endpointId:r,transportStableId:l,protocolHint:"unknown",channel:null});}),await this.invokeIpc("start_incoming_peer_bi_streams",{requestId:e},{timeoutMs:null});}catch(s){i=true,n.error(s),await a();}},cancel:async()=>{await a();}})}async is_current_transport_stable_id(e,t){if(!await this.canUseTauriIpc()){let i=this.fallback;return typeof i.is_current_transport_stable_id=="function"?i.is_current_transport_stable_id(e,t):false}return !e.trim()||t<=0n||t>BigInt(Number.MAX_SAFE_INTEGER)?false:this.invokeIpc("is_current_transport_stable_id",{endpointId:e.trim(),transportStableId:Number(t)})}openPeerUni(e,t){return this.fallback.openPeerUni(e,t)}isConnected(e){return this.fallback.isConnected(e)}getAuthContext(){return this.fallback.getAuthContext()}resolveNativeAuthScopedUserId(e){return this.currentUser?.id??this.getAuthContext()?.userId??e??null}resolveConfiguredSpaceKey(){let e=this.options.spaceKey??this.options.space;return typeof e=="string"?e.trim():""}usesAnonymousSpaceMode(){return this.options.authMode==="anonymous"&&this.resolveConfiguredSpaceKey().length>0}requiresNativeAuthToken(){return !this.usesAnonymousSpaceMode()||typeof this.options.spaceTokenProvider=="function"}async nativeAuthTokenMatchesExpectedScope(e){if(!this.usesAnonymousSpaceMode())return true;let t=typeof this.options.apiKey=="string"?this.options.apiKey.trim():"",i=this.resolveConfiguredSpaceKey();if(!t||!i)return true;let a=await d$2(t,i).catch(()=>null);return a?j(Y(e),a):true}resolveNativeSignalingUserId(e){return this.usesAnonymousSpaceMode()?(typeof e=="string"?e.trim():"")||this.resolveConfiguredSpaceKey()||null:this.resolveNativeAuthScopedUserId(e)}getCurrentUserId(){return this.resolveNativeSignalingUserId(this.fallback.getCurrentUserIdForScope())}nativeAuthWaitMs(){return this.requiresNativeAuthToken()?h.AUTH_REQUIRED_WAIT_MS:0}resolveWebLogicalDeviceId(){return this.fallback.getResolvedWebLogicalDeviceId()}normalizeDevice(e,t){return this.fallback.normalizeDeviceRecord(e,t)}matchesTag(e){return this.fallback.matchesLegacyOrCurrentTag(e)}nativeRosterTagDisposition(e){let t=h$1(e);if(this.matchesTag(t))return {keep:true,classification:"match"};let i=typeof t.appTag=="string"&&t.appTag.trim().length>0?t.appTag.trim():typeof t.tag=="string"&&t.tag.trim().length>0?t.tag.trim():void 0;return i===void 0?{keep:true,classification:"untagged"}:{keep:false,classification:"foreign",foreignTag:i}}filterNativeRosterByTag(e,t){let i=new Set,a=e.filter(n=>{let s=this.nativeRosterTagDisposition(n);return !s.keep&&s.foreignTag&&i.add(s.foreignTag),s.keep});return e.length>0&&a.length===0&&i.size>0?console.warn(`[NativeIpcBridge] ${t}: dropped ALL ${e.length} native device(s) as foreign-app \u2014 this is the app-tag drift signature (empty native device list). The native Rust OpenRTC app tag does not match the SDK app tag; check that the desktop binary and the web bundle use the same VITE_PLUTO_OPENRTC_API_KEY / VITE_PLUTO_OPENRTC_APP_TAG for this environment lane.`,{sdkAppTag:this.appTag,foreignTags:Array.from(i),droppedCount:e.length}):i.size>0&&c$1(`[NativeIpcBridge] ${t}: filtered ${e.length-a.length} foreign-app device(s) from the native roster`,{sdkAppTag:this.appTag,foreignTags:Array.from(i)}),a}normalizeNativeIceServer(e){let t=e.urls,i=Array.isArray(t)?t.filter(a=>typeof a=="string"&&a.trim().length>0):typeof t=="string"&&t.trim().length>0?[t]:[];return i.length===0?null:{urls:i,username:typeof e.username=="string"&&e.username.trim().length>0?e.username:void 0,credential:typeof e.credential=="string"&&e.credential.trim().length>0?e.credential:void 0}}filterNativeStunServers(e){return e.map(t=>({...t,urls:t.urls.filter(i=>!i.startsWith("stun:"))})).filter(t=>t.urls.length>0)}nativeIceServerHasTurnUrl(e){return e.urls.some(t=>t.startsWith("turn:")||t.startsWith("turns:"))}async loadNativeTurnIceServers(){if(typeof this.turnCredentialsProvider!="function")return [];let e=await this.turnCredentialsProvider().catch(t=>(console.warn("[NativeIpcBridge] TURN credential provider failed:",t),null));return !e||!Array.isArray(e.iceServers)?[]:e.iceServers.map(t=>this.normalizeNativeIceServer(t)).filter(t=>!!t)}async buildNativeTransportConfigPayload(){let e=this.transportOptions;if(!e&&!this.strictMode)return null;let t;!this.strictMode&&e?.iroh&&(typeof e.iroh=="object"&&e.iroh.localDiscovery===false?t=null:t={enabled:true,advertise:typeof e.iroh!="object"||e.iroh.localDiscoveryMode!=="passive"});let i=null;if(e?.webrtc===true||e?.webrtc&&typeof e.webrtc=="object"){let d=e.webrtc===true?null:e.webrtc,r=d?.useDefaultIceServers!==false,l=Array.isArray(d?.iceServers)&&d.iceServers.length>0?d.iceServers.map(y=>this.normalizeNativeIceServer(y)).filter(y=>!!y):r?j$1.map(y=>this.normalizeNativeIceServer(y)).filter(y=>!!y):[],u=this.strictMode||d?.privacyMode===true;(this.strictMode||d?.privacyMode===true||d?.useTurn===true)&&(l=[...l,...await this.loadNativeTurnIceServers()]),u&&(l=this.filterNativeStunServers(l));let m=l.some(y=>this.nativeIceServerHasTurnUrl(y)),v=u&&m;u&&!m&&console.warn("[NativeIpcBridge] Relay-only WebRTC requested, but no TURN servers are configured; native WebRTC override disabled");let _=d?.lanMode===true;(l.length>0||v||_||!r)&&(i={iceServers:l.length>0||!r?l:void 0,privacyMode:v,lanMode:_||void 0});}let a=null;if(e?.moq&&typeof e.moq=="object"){let d=typeof e.moq.relayUrl=="string"&&e.moq.relayUrl.trim().length>0?e.moq.relayUrl:void 0;if(d){let r=typeof e.moq.accessToken=="string"&&e.moq.accessToken.trim().length>0?e.moq.accessToken.trim():void 0;a={relayUrl:d,accessToken:r};}}let n=null;if(!this.strictMode&&(e?.ble===true||e?.ble&&typeof e.ble=="object")){let d=e.ble===true?null:e.ble,r=Number(d?.connectTimeoutMs);n={enabled:d?.enabled!==false,connectTimeoutMs:Number.isFinite(r)&&r>0?Math.round(r):void 0};}let s=this.strictMode||e?.iroh&&typeof e.iroh=="object"&&e.iroh.relayOnly===true,o=e?.iroh&&typeof e.iroh=="object"?e.iroh.relayTransportPolicy:void 0,c=this.strictMode?o??"auto":o;return !s&&!c&&!i&&!a&&!t&&!n?null:{irohRelayOnly:s||void 0,irohRelayTransportPolicy:c,...t!==void 0?{irohLan:t}:{},webrtc:i,moq:a,ble:n}}isTauriEnv(){return c$2()}nextConnectionEventRetryDelayMs(e){return d(e,h.CONNECTION_EVENT_RETRY_MIN_DELAY_MS,h.CONNECTION_EVENT_RETRY_MAX_DELAY_MS)}async clearNativeAuthRelay(e){if(await this.canUseTauriIpc())try{typeof this.options.coordinationGateway?.grantProvider=="function"?await this.invokeIpc("openrtc_v2_set_identity_credential",{identityCredential:null}):await this.invokeIpc("desktop_set_pluto_auth_token",{authToken:null,refreshToken:null}),this.lastSyncedAuthToken=null,this.lastNativeAuthSyncAtMs=0,c$1(`[NativeIpcBridge] cleared native auth relay (${e})`);}catch(t){console.warn(`[NativeIpcBridge] failed clearing native auth relay (${e}):`,t);}}async clearNativeTrustRelay(e){if(this.nativeTrustTokenUnsubscribe?.(),this.nativeTrustTokenUnsubscribe=null,this.nativeTrustRelayError=null,this.fallback.invalidateCoordinationNativeTrustToken(),typeof this.options.coordinationGateway?.grantProvider!="function"&&await this.canUseTauriIpc())try{await this.invokeIpc("openrtc_set_native_trust_token",{trustToken:null,expiresAtMs:null}),c$1(`[NativeIpcBridge] cleared native trust relay (${e})`);}catch(t){b(t)||console.warn(`[NativeIpcBridge] failed clearing native trust relay (${e}):`,t);}}relayNativeTrustToken(e,t){let i=async()=>{await this.canUseTauriIpc()&&(await this.invokeIpc("openrtc_set_native_trust_token",{trustToken:e?.token??null,expiresAtMs:e?.expiresAtMs??null}),c$1(`[NativeIpcBridge] native trust token ${e?"relayed":"cleared"} (${t})`));},a=this.nativeTrustRelayQueue.then(i,i);return this.nativeTrustRelayQueue=a.catch(()=>{}),a}async ensureNativeTrustRelay(e=false){if(!this.usesCoordinationGateway()||typeof this.options.coordinationGateway?.grantProvider=="function")return true;if(typeof this.options.coordinationGateway?.nativeTrustTokenProvider!="function")return false;if(!await this.canUseTauriIpc())return true;try{let t=await this.fallback.getCoordinationNativeTrustToken(e);return await this.relayNativeTrustToken(t,"auth-ready"),this.nativeTrustRelayError=null,this.nativeTrustTokenUnsubscribe||(this.nativeTrustTokenUnsubscribe=this.fallback.subscribeCoordinationNativeTrustToken(i=>{this.relayNativeTrustToken(i,"provider-refresh").catch(a=>{console.warn("[NativeIpcBridge] native trust token refresh relay failed:",a);});},{emitCurrent:!1})),!0}catch(t){return this.nativeTrustRelayError=(t instanceof Error?t.message:String(t)).trim().slice(0,300)||"unknown provider failure",console.warn("[NativeIpcBridge] native trust token unavailable:",t),false}}async relayNativeAuthToken(e,t,i,a){if(!await this.canUseTauriIpc())return true;if(!await this.nativeAuthTokenMatchesExpectedScope(e))return c$1(`[NativeIpcBridge] auth sync deferred (${i}): token claims do not match configured space`),false;if(e===this.lastSyncedAuthToken)return true;try{typeof this.options.coordinationGateway?.grantProvider=="function"?await this.invokeIpc("openrtc_v2_set_identity_credential",{identityCredential:e}):await this.invokeIpc("desktop_set_pluto_auth_token",{authToken:e,refreshToken:t??null});}catch(n){return b(n)?console.warn(`[NativeIpcBridge] desktop auth relay unavailable (${i}); install/register openrtc-tauri-plugin and include its default permission set.`,n):console.warn(`[NativeIpcBridge] desktop auth relay failed (${i}):`,n),false}return this.lastSyncedAuthToken=e,this.lastNativeAuthSyncAtMs=Date.now(),c$1(`[NativeIpcBridge] auth token relayed to native runtime (${i}) user_id=${a??this.currentUser?.id??"unknown"}`),true}async relayExplicitNativeAuthContext(e){let t=this.authSyncInFlight,i=(async()=>(await t?.catch(()=>{}),this.relayNativeAuthToken(e.token,e.refreshToken,"setAuthContext",e.userId)))();this.authSyncInFlight=i;try{return await i}finally{this.authSyncInFlight===i&&(this.authSyncInFlight=null);}}applyNativeRuntimeStatus(e){this.runtimeCapabilities=u(e,this.allowWasmFallback);}syncNativeRuntimeCapabilities(e){return this.ipcBridge?this.nativeRuntimeCapabilitiesSyncInFlight?this.nativeRuntimeCapabilitiesSyncInFlight:(this.nativeRuntimeCapabilitiesSyncInFlight=(async()=>{try{let t=await this.invokeIpc("rtc_native_status",void 0,{timeoutMs:h.NATIVE_STATUS_IPC_TIMEOUT_MS});this.applyNativeRuntimeStatus(t),c$1(`[NativeIpcBridge] refreshed native runtime capabilities (${e})`);}catch(t){b$1("[NativeIpcBridge] native runtime capability refresh skipped",t);}})().finally(()=>{this.nativeRuntimeCapabilitiesSyncInFlight=null;}),this.nativeRuntimeCapabilitiesSyncInFlight):Promise.resolve()}async canUseTauriIpc(){if(this.ipcBridge){let e=typeof this.ipcBridge.isAvailable=="function"?!!await this.ipcBridge.isAvailable():true;return e&&this.syncNativeRuntimeCapabilities("ipc-available"),e}return typeof window>"u"?false:this.tauriCoreAvailabilityValue===true?true:this.tauriCoreAvailabilityValue===false&&Date.now()-this.tauriCoreAvailabilityCheckedAtMs<h.TAURI_IPC_NEGATIVE_CACHE_MS?false:(this.tauriCoreAvailability||(this.tauriCoreAvailability=(async()=>{try{if(this.isTauriEnv())return this.tauriCoreAvailabilityValue=!0,this.tauriCoreAvailabilityCheckedAtMs=Date.now(),this.syncNativeRuntimeCapabilities("tauri-env"),!0;try{let e=await this.invokeIpc("rtc_native_status");return this.applyNativeRuntimeStatus(e),c$1("[NativeIpcBridge] Resolved Tauri IPC via rtc_native_status probe"),this.tauriCoreAvailabilityValue=!0,this.tauriCoreAvailabilityCheckedAtMs=Date.now(),!0}catch(e){let t=String(e?.message??e??"");return t.includes("__TAURI_INTERNALS__")||t.includes("Cannot read properties of undefined")||t.includes("window is not defined")?(this.tauriCoreAvailabilityValue=!1,this.tauriCoreAvailabilityCheckedAtMs=Date.now(),!1):(c$1("[NativeIpcBridge] Tauri IPC probe reached native layer (command-level error acceptable)"),this.tauriCoreAvailabilityValue=!0,this.tauriCoreAvailabilityCheckedAtMs=Date.now(),!0)}}catch{return this.tauriCoreAvailabilityValue=false,this.tauriCoreAvailabilityCheckedAtMs=Date.now(),false}})().finally(()=>{this.tauriCoreAvailability=null;})),this.tauriCoreAvailability)}async invokeIpc(e,t,i){let a=this.ipcBridge.invoke(e,t),n=i&&Object.prototype.hasOwnProperty.call(i,"timeoutMs")?i.timeoutMs:h.DEFAULT_BOUNDED_IPC_TIMEOUT_MS;return n==null||n<=0?a:a$2(a,n,()=>new Error(`${e} timeout after ${n}ms`))}async listenIpc(e,t){return this.ipcBridge.listen(e,i=>{t({payload:i});})}async openPeerBiViaIpc(e,t,i){let a=await this.invokePeerBiOpen(e,t,i),n=typeof a?.streamId=="string"?a.streamId.trim():typeof a?.stream_id=="string"?a.stream_id.trim():"";if(!n)throw new Error(`${e} returned no streamId`);return this.peerBiStreamFromId(n)}peerBiStreamFromId(e,t={}){let i=this,a=null,n=null,s=false,o=null,c=null,d=async()=>{let m=[a,n];a=null,n=null,await Promise.allSettled(m.filter(v=>typeof v=="function").map(v=>Promise.resolve(v())));},r=(async()=>{a=await this.listenIpc("openrtc://peer-bi-stream/chunk",m=>{let v=m.payload;if((typeof v?.streamId=="string"?v.streamId:typeof v?.stream_id=="string"?v.stream_id:"")!==e||s||!o)return;let f=v?.bytes;f instanceof Uint8Array?o.enqueue(f):Array.isArray(f)&&o.enqueue(new Uint8Array(f));}),n=await this.listenIpc("openrtc://peer-bi-stream/closed",m=>{let v=m.payload;if((typeof v?.streamId=="string"?v.streamId:typeof v?.stream_id=="string"?v.stream_id:"")!==e||s||!o)return;s=true;let f=typeof v?.error=="string"?v.error.trim():"";f?o.error(new Error(f)):o.close(),d();}),t.startReadAfterListeners&&await this.invokeIpc("start_peer_bi_stream_read",{streamId:e},{timeoutMs:null});})().catch(m=>{c=m,o&&!s&&(s=true,o.error(m));}),l=async()=>{await this.invokeIpc("close_peer_bi_stream",{streamId:e},{timeoutMs:null}).catch(()=>{}),await d();},u=new ReadableStream({async start(m){o=m,await r,c&&!s&&(s=true,m.error(c));},async cancel(){s=true,await l();}}),I=new WritableStream({write:async m=>{await i.invokeIpc("write_peer_bi_stream",{streamId:e,bytes:Array.from(m)},{timeoutMs:null});},close:l,abort:l});return {readable:u,writable:I}}async invokePeerBiOpen(e,t,i){try{return await this.invokeIpc(e,t)}catch(a){if(!i?.fallbackCommand||!this.isMissingNativeCommandError(a))throw a;return this.invokeIpc(i.fallbackCommand,i.fallbackArgs??t)}}isMissingNativeCommandError(e){let t=e instanceof Error?e.message:String(e??"");return t.includes("Command")&&t.includes("not found")}async shouldUseTauriSignaling(){if(await this.canUseTauriIpc())return true;if(this.allowWasmFallback)return false;throw new Error("[pluto-rtc] Tauri runtime adapter requires native IPC, but it is unavailable.")}async signInWithPluto(){if(!await this.canUseTauriIpc()){await this.fallback.signInWithPluto();return}let e=await this.invokeIpc("rtc_sign_in_with_pluto"),t=typeof e?.customToken=="string"?e.customToken.trim():"";if(!t)throw new Error("[pluto-rtc] Native Pluto SSO did not return a custom token.");await b$2().signInWithCustomTokenValue(t),await this.ensureNativeAuth("pluto-sso",{requireToken:true,maxWaitMs:1e4});}async setAuthContext(e){let t=this.getAuthContext()?.userId??null,i=typeof e?.userId=="string"&&e.userId.trim()||null,a=this.fallback.setAuthContext(e);if(t&&i&&t!==i&&await this.stopNativeAuthScopedActivity(t),await a,!e?.token)await this.clearNativeAuthRelay("setAuthContext"),await this.clearNativeTrustRelay("setAuthContext");else {if(!await this.relayExplicitNativeAuthContext(e))throw new Error("Native auth token unavailable for setAuthContext");if(!await this.ensureNativeTrustRelay())throw new Error(`Native trust token unavailable for setAuthContext: ${this.nativeTrustRelayError??"unknown provider failure"}`)}}async signOut(){await this.fallback.signOut(),await Promise.all([this.clearNativeAuthRelay("signOut"),this.clearNativeTrustRelay("signOut")]);}async stopAuthScopedActivity(e){let t=this.resolveNativeSignalingUserId(e?.userId??null);await this.stopNativeAuthScopedActivity(t);}async stopNativeAuthScopedActivity(e){await this.stopGatewayDesiredPeerRelay(),this.gatewayExcludedPeers.clear();let t=await this.shouldUseTauriSignaling();if(g("NativeIpcBridge.stopAuthScopedActivity",{userId:e,useTauri:t}),t)try{await Promise.allSettled([this.revokeSessionTokensByScope("user-device"),this.invokeIpc("stop_rtc_presence_loop"),this.invokeIpc("stop_rtc_auto_connect")]);}catch(i){console.warn("[NativeIpcBridge] Failed to stop native auth-scoped RTC activity:",i);}await this.fallback.stopAuthScopedActivity({userId:e});}async ensureNativeAuthOnce(e,t){if(!await this.canUseTauriIpc())return true;if(this.authSyncInFlight)return this.authSyncInFlight;let i=(async()=>{try{if(!this.currentUser)return c$1(`[NativeIpcBridge] auth sync deferred (${e}): no current user`),!t;let a=Date.now()-this.lastNativeAuthSyncAtMs>=480*1e3,n=this.currentUser?.getToken?await this.currentUser.getToken(a):null,o=this.getAuthContext()?.refreshToken??this.auth?.currentUser?.refreshToken??null;return n?this.relayNativeAuthToken(n,o,e,this.currentUser?.id):(c$1(`[NativeIpcBridge] auth sync deferred (${e}): missing token for user ${this.currentUser?.id}`),!t)}catch(a){return console.error("[NativeIpcBridge] auth sync failed:",a),false}})();this.authSyncInFlight=i;try{return await i}finally{this.authSyncInFlight===i&&(this.authSyncInFlight=null);}}async ensureNativeAuth(e="runtime",t){if(!await this.canUseTauriIpc())return true;let i=t?.requireToken??false,a$1=t?.maxWaitMs??(i?h.AUTH_REQUIRED_WAIT_MS:0),n=t?.pollMs??250,s=Date.now()+Math.max(0,a$1);for(;;){if(await this.ensureNativeAuthOnce(e,i))return true;if(!i||Date.now()>=s)return false;await a(n);}}decodeNativeDeviceIdentity(e){let t=e?.systemInfo??e?.system_info??null,i=typeof e?.deviceId=="string"?e.deviceId.trim():typeof e?.device_id=="string"?e.device_id.trim():"",a=typeof e?.deviceName=="string"?e.deviceName.trim():typeof e?.device_name=="string"?e.device_name.trim():"",n=typeof e?.platformType=="string"?e.platformType.trim():typeof e?.platform_type=="string"?e.platform_type.trim():typeof t?.platformType=="string"?t.platformType.trim():typeof t?.platform_type=="string"?t.platform_type.trim():"";return {deviceId:i,deviceName:a,platformType:n}}async resolveLocalDeviceId(){if(this.cachedLocalDeviceId)return this.cachedLocalDeviceId;if(await this.canUseTauriIpc())try{let t=await this.invokeIpc("get_rtc_local_device_info"),{deviceId:i,deviceName:a}=this.decodeNativeDeviceIdentity(t);if(i)return this.cachedLocalDeviceId=i,a&&(this.cachedLocalDeviceName=a),i}catch(t){console.warn("[NativeIpcBridge] get_rtc_local_device_info failed:",t);}let e=this.resolveWebLogicalDeviceId();return this.cachedLocalDeviceId=e,e}async resolveLocalDeviceName(){if(this.cachedLocalDeviceName)return this.cachedLocalDeviceName;if(await this.canUseTauriIpc())try{let e=await this.invokeIpc("get_rtc_local_device_info"),{deviceName:t}=this.decodeNativeDeviceIdentity(e);if(t){let i=this.normalizeNativeDeviceName(t);return this.cachedLocalDeviceName=i,i}}catch(e){console.warn("[NativeIpcBridge] get_rtc_local_device_info failed:",e);}return this.defaultDeviceNameFallback()}normalizeNativeDeviceName(e){let t=e.trim();if(!t)return this.defaultDeviceNameFallback();if(t==="Desktop Device"){let i=this.defaultDeviceNameFallback();if(i!=="Desktop Device")return i}return t}defaultDeviceNameFallback(){if(typeof window>"u"||typeof navigator>"u")return "Desktop Device";let e=navigator.userAgent||"";return /iPhone|iPad|iPod/i.test(e)?"iPhone":/Android/i.test(e)?"Android":"Desktop Device"}inferNativePlatformTypeFallback(){if(typeof window>"u"||typeof navigator>"u")return "desktop";if(!this.isTauriEnv())return "web";let e=navigator.userAgent||"";return /iPhone|iPad|iPod|Android|Mobile/i.test(e)?"mobile":"desktop"}normalizeNativeCoordinationPlatform(e){let t=e?.trim().toLowerCase()??"";return t==="mobile"||t==="ios"||t==="android"||t.includes("iphone")||t.includes("ipad")||this.inferNativePlatformTypeFallback()==="mobile"?"mobile":"desktop"}withPresenceMetadata(e,t){try{let i=e?JSON.parse(e):{};return JSON.stringify({...i,deviceId:t,plutoVersion:"0.1.0-desktop"})}catch{return JSON.stringify({deviceId:t,plutoVersion:"0.1.0-desktop",rawMetadata:e})}}async searchDevices(e){return this.assertManagedCoordinationGateway(),this.fallback.searchDevices(e)}async listDevicesWithStatus(){return this.assertManagedCoordinationGateway(),(await this.fallback.searchDevices()).map(e=>j$2(e))}async getPeerSession(e){if(await this.shouldUseTauriSignaling()){let t=await this.invokeIpc("get_rtc_peer_session",{id:e});return !t||typeof t!="object"?null:k$1(t)}return this.fallback.getPeerSession(e)}async listPeerSessions(){if(await this.shouldUseTauriSignaling()){let e=await this.invokeIpc("list_rtc_peer_sessions");return (Array.isArray(e)?e:[]).map(t=>k$1(t))}return this.fallback.listPeerSessions()}async waitForSettledPeer(e,t){if(await this.shouldUseTauriSignaling()){let i=typeof t=="number"?Math.max(h.DEFAULT_BOUNDED_IPC_TIMEOUT_MS,t+1e3):h.DEFAULT_BOUNDED_IPC_TIMEOUT_MS,a=await this.invokeIpc("wait_for_rtc_settled_peer",{id:e,timeoutMs:t},{timeoutMs:i});return !a||typeof a!="object"?null:k$1(a)}return this.fallback.waitForSettledPeer(e,t)}async resolvePeerConnectionRecords(e){if(await this.shouldUseTauriSignaling()){let t=await this.invokeIpc("resolve_rtc_peer_connection_records",{id:e});return (Array.isArray(t)?t:[]).map(i=>l(i))}return this.fallback.resolvePeerConnectionRecords(e)}async resolvePeerIdentity(e){if(await this.shouldUseTauriSignaling()){let t=await this.invokeIpc("resolve_rtc_peer_identity",{id:e});return m(t)}return this.fallback.resolvePeerIdentity(e)}async setOffline(e){return this.assertManagedCoordinationGateway(),this.fallback.setOffline(e)}async updateDevice(e,t){return this.assertManagedCoordinationGateway(),await this.syncCoordinationDeviceIdentity(),this.fallback.updateDevice(e,t)}async deleteDevice(e){return this.assertManagedCoordinationGateway(),await this.syncCoordinationDeviceIdentity(),this.fallback.deleteDevice(e)}async getLocalDeviceInfo(){if(!await this.canUseTauriIpc()){let e=await this.getLocalDeviceId?.();return e?{deviceId:e,deviceName:this.defaultDeviceNameFallback(),platformType:this.inferNativePlatformTypeFallback()}:null}try{let e=await this.invokeIpc("get_rtc_local_device_info"),t=this.decodeNativeDeviceIdentity(e),{deviceId:i}=t;return i?{deviceId:i,deviceName:this.normalizeNativeDeviceName(t.deviceName),platformType:t.platformType||this.inferNativePlatformTypeFallback(),capabilities:e?.capabilities??void 0,lastSeenAt:typeof e?.last_seen_at=="string"?e.last_seen_at:void 0}:null}catch(e){return console.warn("[NativeIpcBridge] getLocalDeviceInfo failed:",e),null}}async updateLocalDeviceName(e){if(!await this.canUseTauriIpc())return null;try{let t=await this.invokeIpc("update_rtc_local_device_name",{deviceName:e}),i=this.decodeNativeDeviceIdentity(t),{deviceId:a}=i;return a?(this.cachedLocalDeviceName=this.normalizeNativeDeviceName(e),{deviceId:a,deviceName:this.cachedLocalDeviceName,platformType:i.platformType||this.inferNativePlatformTypeFallback(),capabilities:t?.capabilities??void 0,lastSeenAt:typeof t?.last_seen_at=="string"?t.last_seen_at:void 0}):null}catch(t){return console.warn("[NativeIpcBridge] updateLocalDeviceName failed:",t),null}}async startManagedSessionNative(e){if(this.assertManagedCoordinationGateway(),!await this.shouldUseTauriSignaling())throw new Error("[pluto-rtc] Native IPC unavailable for startManagedSessionNative().");if(!await this.ensureNativeAuth("startManagedSessionNative",{requireToken:this.requiresNativeAuthToken(),maxWaitMs:this.nativeAuthWaitMs()}))throw new Error("Native auth token unavailable for startManagedSessionNative");let i=this.resolveNativeSignalingUserId(e.userId);if(!i)throw new Error("Native managed session startup requires a runtime auth-scoped user id.");i!==e.userId&&console.info("[NativeIpcBridge][managed-session][user-id-remap]",{requestedUserId:e.userId,runtimeUserId:this.currentUser?.id??this.getAuthContext()?.userId??null,effectiveUserId:i}),console.info("[NativeIpcBridge][managed-session][start-request]",{requestedUserId:e.userId,runtimeUserId:this.currentUser?.id??this.getAuthContext()?.userId??null,effectiveUserId:i,deviceName:e.deviceName??null,localDeviceId:e.localDeviceId??null,presence:e.presence!==false,autoConnect:e.autoConnect!==false,hasMetadata:typeof e.metadata=="string"&&e.metadata.trim().length>0});let a=await this.buildNativeTransportConfigPayload(),n={userId:i,deviceName:e.deviceName??null,localDeviceId:e.localDeviceId??null,metadata:e.metadata??null,...a?{transports:a}:{},autoConnect:false,presence:false},s=await this.invokeIpc("start_rtc_managed_session",n,{timeoutMs:null});this.syncNativeRuntimeCapabilities("managed-session-started");let o=typeof s?.ticket=="string"&&s.ticket.trim().length>0?s.ticket.trim():null,c=s?.localDevice&&typeof s.localDevice=="object"?s.localDevice:s?.local_device&&typeof s.local_device=="object"?s.local_device:null,d=c?{deviceId:typeof c.deviceId=="string"?c.deviceId:typeof c.device_id=="string"?c.device_id:"",deviceName:this.normalizeNativeDeviceName(typeof c.deviceName=="string"?c.deviceName:typeof c.device_name=="string"?c.device_name:""),platformType:typeof c.platformType=="string"?c.platformType:typeof c.platform_type=="string"?c.platform_type:"desktop",capabilities:c.capabilities??void 0,lastSeenAt:typeof c.lastSeenAt=="string"?c.lastSeenAt:typeof c.last_seen_at=="string"?c.last_seen_at:void 0}:null,r={localNodeId:typeof s?.localNodeId=="string"?s.localNodeId:typeof s?.local_node_id=="string"?s.local_node_id:null,ticket:o,ticketScope:typeof s?.ticketScope=="string"?s.ticketScope:typeof s?.ticket_scope=="string"?s.ticket_scope:null,presenceStarted:typeof s?.presenceStarted=="boolean"?s.presenceStarted:!!s?.presence_started,autoConnectStarted:typeof s?.autoConnectStarted=="boolean"?s.autoConnectStarted:!!s?.auto_connect_started,localDevice:d?.deviceId?d:null};if(this.usesCoordinationGateway()){e.presence!==false&&!r.ticket&&(r.ticket=await this.getEndpointTicketWithToken("user-device",0),r.ticketScope=r.ticket?"user-device":null);let l=r.localDevice?.deviceId||e.localDeviceId?.trim()||await this.resolveLocalDeviceId();if(l&&this.fallback.setCoordinationLocalDeviceId(l),this.fallback.setCoordinationPlatformType(this.normalizeNativeCoordinationPlatform(r.localDevice?.platformType)),e.presence!==false){if(!r.localNodeId||!r.ticket)throw new Error("Native managed session did not return the node identity required for gateway presence.");await this.fallback.updatePresence(r.localNodeId,r.ticket,true,3e5,e.metadata,r.localDevice?.deviceName||e.deviceName),r.presenceStarted=true;}else r.presenceStarted=false;e.autoConnect!==false&&l?(await this.startGatewayAutoConnect(i,l),r.autoConnectStarted=true):r.autoConnectStarted=false;}return console.info("[NativeIpcBridge][managed-session][ipc-started]",{requestedUserId:e.userId,runtimeUserId:this.currentUser?.id??this.getAuthContext()?.userId??null,effectiveUserId:i,localNodeId:r.localNodeId,ticketScope:r.ticketScope,presenceStarted:r.presenceStarted,autoConnectStarted:r.autoConnectStarted,localDeviceId:r.localDevice?.deviceId??null}),r}async reconcileNativeManagedSession(e){return this.assertManagedCoordinationGateway(),await this.fallback.reconnectCoordinationAfterHostResume(),console.info("[NativeIpcBridge] reattached gateway coordination after host resume.",{reason:e?.reason??"frontend"}),null}async notifyNetworkChange(e){return await this.canUseTauriIpc()?(c$1("[NativeIpcBridge] forwarding host network-change hint",{reason:e?.reason??"host"}),this.invokeIpc("notify_rtc_network_change")):null}async getManagedNodeId(e){let t=e?.initializeIfMissing??true;console.info("[NativeIpcBridge][getManagedNodeId] enter",{initializeIfMissing:t});let i=await this.canUseTauriIpc();if(console.info("[NativeIpcBridge][getManagedNodeId] canUseTauriIpc",{canUse:i}),!i)return null;try{console.info("[NativeIpcBridge][getManagedNodeId] invoking get_iroh_node_id");let a=await this.invokeIpc("get_iroh_node_id");if(console.info("[NativeIpcBridge][getManagedNodeId] get_iroh_node_id returned",{existing:a}),a||!t)return a;console.info("[NativeIpcBridge][getManagedNodeId] invoking start_iroh_node");let n=await this.invokeIpc("start_iroh_node");return console.info("[NativeIpcBridge][getManagedNodeId] start_iroh_node returned",{started:n}),n}catch(a){if(console.warn("[NativeIpcBridge] getManagedNodeId failed:",a),!t)return null;throw a}}async getEndpointTicket(){if(!await this.canUseTauriIpc())throw new Error("[pluto-rtc] getEndpointTicket requires native IPC in Tauri runtime.");return E(()=>this.invokeIpc("get_iroh_endpoint_ticket"))}async connectToDevice(e){if(!await this.canUseTauriIpc())throw new Error("[pluto-rtc] connectToDevice requires native IPC in Tauri runtime.");this.options.authMode!=="anonymous"?await this.ensureNativeAuth("connectToDevice",{requireToken:true,maxWaitMs:h.AUTH_REQUIRED_WAIT_MS}):c$1("[NativeIpcBridge] connectToDevice using anonymous native ticket path");let t=Math.max(1,Math.floor(e.timeoutMs??h.DEFAULT_BOUNDED_IPC_TIMEOUT_MS));return this.invokeIpc("connect_to_device",{deviceId:e.deviceId??null,endpointTicket:e.endpointTicket,timeoutMs:t},{timeoutMs:t+1e3})}async registerSessionToken(e,t,i){await this.canUseTauriIpc()&&await this.invokeIpc("register_session_token",{token:e,scope:t,maxConnections:i});}async getEndpointTicketWithToken(e,t){if(!await this.canUseTauriIpc())return null;try{return await E(()=>this.invokeIpc("get_endpoint_ticket_with_token",{scope:e,maxConnections:t}))}catch{return null}}async validateSessionToken(e,t){if(!await this.canUseTauriIpc())return null;try{return await this.invokeIpc("validate_session_token",{token:e,connectionId:t??null})}catch{return null}}async revokeSessionTokensByScope(e){if(g("NativeIpcBridge.revokeSessionTokensByScope",{grantScope:e}),!await this.canUseTauriIpc())return [];try{return await this.invokeIpc("revoke_session_tokens_by_scope",{scope:e})}catch{return []}}async disconnectDevice(e){if(!await this.canUseTauriIpc())throw new Error("[pluto-rtc] disconnectDevice requires native IPC in Tauri runtime.");await this.invokeIpc("disconnect_device",{deviceId:e});}async setAutoConnectExcluded(e,t){if(!await this.canUseTauriIpc())return;let i=e.trim().toLowerCase();i&&(this.usesCoordinationGateway()&&(t?this.gatewayExcludedPeers.add(i):this.gatewayExcludedPeers.delete(i)),await this.invokeIpc(this.usesCoordinationGateway()?"set_rtc_external_auto_connect_excluded":"set_auto_connect_excluded",{deviceId:e,excluded:t}),this.usesCoordinationGateway()&&await this.fallback.setCoordinationExcludedPeers([...this.gatewayExcludedPeers].sort()));}onDevicesChange(e,t){return this.assertManagedCoordinationGateway(),this.fallback.onDevicesChange(e,t)}async subscribeDevices(e){return this.assertManagedCoordinationGateway(),this.fallback.subscribeDevices(e)}async subscribeSessions(e){return this.assertManagedCoordinationGateway(),this.fallback.subscribeSessions(e)}async getLocalDeviceId(){return this.resolveLocalDeviceId()}async updatePresence(e,t,i=true,a=3e5,n){return this.assertManagedCoordinationGateway(),await this.syncCoordinationDeviceIdentity(),this.fallback.updatePresence(e,t,i,a,n)}startAutoConnect(e,t){this.assertManagedCoordinationGateway(),this.startGatewayAutoConnect(e,t).catch(i=>{console.warn("[NativeIpcBridge] gateway auto-connect failed:",i);});}forceReconnectSnapshot(){this.assertManagedCoordinationGateway(),this.fallback.forceReconnectSnapshot();}startPresenceLoop(e,t,i,a,n){this.assertManagedCoordinationGateway(),this.syncCoordinationDeviceIdentity().then(()=>this.fallback.startPresenceLoop(e,t,i,a,n)).catch(s=>{console.warn("[NativeIpcBridge] gateway presence failed:",s);});}async startAutoConnectOnce(e,t){this.assertManagedCoordinationGateway(),await this.startGatewayAutoConnect(e,t);}async clearGatewayDesiredPeerRelay(){let e=this.gatewayDesiredPeerSubmission;this.gatewayDesiredPeerRelayGeneration+=1,this.gatewayDesiredPeersCleanup?.(),this.gatewayDesiredPeersCleanup=null,this.gatewayDesiredPeerRelayKey=null,this.gatewayDesiredPeerRevision=0,this.gatewayDesiredPeerSubmission=Promise.resolve(),await e;}serializeGatewayDesiredPeerLifecycle(e){let t=this.gatewayDesiredPeerLifecycle.then(e);return this.gatewayDesiredPeerLifecycle=t.catch(()=>{}),t}stopGatewayDesiredPeerRelay(){return this.serializeGatewayDesiredPeerLifecycle(async()=>{await this.clearGatewayDesiredPeerRelay();})}startGatewayAutoConnect(e,t){return this.serializeGatewayDesiredPeerLifecycle(()=>this.startGatewayAutoConnectSerialized(e,t))}async startGatewayAutoConnectSerialized(e,t){if(!await this.shouldUseTauriSignaling())throw new Error("[openrtc] Native IPC unavailable for coordination gateway auto-connect.");if(!await this.ensureNativeAuth("startGatewayAutoConnect",{requireToken:this.requiresNativeAuthToken(),maxWaitMs:this.nativeAuthWaitMs()}))throw new Error("Native auth token unavailable for coordination gateway auto-connect");let a=this.resolveNativeSignalingUserId(e);if(!a)throw new Error("Coordination gateway auto-connect requires an authenticated user id.");let n=await this.resolveLocalDeviceId()||t.trim();if(!n)throw new Error("Coordination gateway auto-connect requires a local device id.");let s=JSON.stringify([a,n]);this.fallback.setCoordinationLocalDeviceId(n);let o=this.gatewayDesiredPeerRelayKey===s&&this.gatewayDesiredPeersCleanup;if(o||(await this.clearGatewayDesiredPeerRelay(),this.gatewayDesiredPeerRelayKey=s),await this.invokeIpc("start_rtc_external_auto_connect",{userId:a,localDeviceId:n}),o)return;let c=this.gatewayDesiredPeerRelayGeneration;this.gatewayDesiredPeersCleanup=this.fallback.onDevicesChange(d=>{let r=d.map(u=>({deviceId:String(u.deviceId??"").trim(),nodeId:typeof u.nodeId=="string"&&u.nodeId.trim()||null,ticket:typeof u.ticket=="string"&&u.ticket.trim()||null,online:u.online===true,sessionId:typeof u.sessionId=="string"&&u.sessionId.trim()||null,excludedPeers:Array.isArray(u.excludedPeers)?[...new Set(u.excludedPeers.map(I=>String(I??"").trim().toLowerCase()).filter(Boolean))].sort():[]})).filter(u=>u.deviceId.length>0&&u.deviceId!==n).sort((u,I)=>u.deviceId.localeCompare(I.deviceId)),l=++this.gatewayDesiredPeerRevision;this.gatewayDesiredPeerSubmission=this.gatewayDesiredPeerSubmission.then(async()=>{this.gatewayDesiredPeerRelayGeneration!==c||this.gatewayDesiredPeerRelayKey!==s||await this.invokeIpc("submit_rtc_desired_peers",{revision:l,peersJson:JSON.stringify(r)});}).catch(u=>{console.warn("[NativeIpcBridge] failed to relay gateway desired peers to Rust:",{revision:l,error:u});});},n);}async startPresenceLoopOnce(e,t,i,a,n){this.assertManagedCoordinationGateway(),await this.syncCoordinationDeviceIdentity(),await this.fallback.startPresenceLoop(e,t,i,a,n);}shouldUseResolvedDeviceName(e){let t=e.trim();return t.length===0||t==="Unknown Device"||t==="Desktop Device"}async sendExplicitFilePath(e,t,i=""){if(c$1("[NativeIpcBridge] sendExplicitFilePath start",{connectionId:e,filePath:t,transferId:i||null,authMode:this.options.authMode}),await this.canUseTauriIpc()){this.options.authMode!=="anonymous"?await this.ensureNativeAuth("sendExplicitFilePath"):c$1("[NativeIpcBridge] sendExplicitFilePath using anonymous native path");let a=await this.invokeIpc("send_file",{connectionId:e,filePath:t,transferId:i});return c$1("[NativeIpcBridge] sendExplicitFilePath completed",{connectionId:e,transferId:i||null,result:a}),a}return this.fallback.sendExplicitFilePath(e,t,i)}async sendExplicitFileData(e){c$1("[NativeIpcBridge] sendExplicitFileData start",{connectionId:e.connectionId??null,connectionRemoteNodeId:e.connection?.remoteNodeId??null,remoteNodeId:e.remoteNodeId??null,transferId:e.transferId??null,fileName:e.file.name,fileSize:e.file.size,authMode:this.options.authMode});let t=e.applicationCrypto??this.options.applicationCrypto;if(await this.canUseTauriIpc()){this.options.authMode!=="anonymous"?await this.ensureNativeAuth("sendExplicitFileData"):c$1("[NativeIpcBridge] sendExplicitFileData using anonymous native path");let i=e.connectionId||e.connection?.deviceId||e.connection?.remoteNodeId||e.remoteNodeId||"";if(!i)throw new Error("sendExplicitFileData requires a settled peer identifier in native runtime");let a=new Uint8Array(await e.file.arrayBuffer());await this.invokeIpc("send_file_data",{connectionId:i,filename:e.file.name,data:Array.from(a),transferId:e.transferId}),c$1("[NativeIpcBridge] sendExplicitFileData completed",{connectionId:i,transferId:e.transferId??null,fileName:e.file.name,fileSize:e.file.size});return}return this.fallback.sendExplicitFileData({...e,applicationCrypto:t})}async getConnectionStates(){if(await this.canUseTauriIpc())try{this.options.authMode!=="anonymous"&&await this.ensureNativeAuth("getConnectionStates");let e=await this.invokeIpc("list_rtc_connection_states");return (Array.isArray(e)?e:[]).map(t=>n(t)).filter(t=>!!t)}catch(e){return b(e)?c$1("[NativeIpcBridge] native connection-state replay unavailable; continuing without replay. Install/register openrtc-tauri-plugin default permissions to enable it."):console.warn("[NativeIpcBridge] Failed to fetch native connection states:",e),[]}return []}async getConnectionState(e){let t=e.trim();if(!t||!await this.canUseTauriIpc())return null;try{return this.options.authMode!=="anonymous"&&await this.ensureNativeAuth("getConnectionState"),n(await this.invokeIpc("get_rtc_connection_state",{connectionId:t}))}catch(i){return console.warn("[NativeIpcBridge] Failed to fetch native connection state:",{connectionId:t,error:i}),null}}async onConnectionStateChange(e){let t=false,i=null,a$1=new Map,n$1=Date.now(),s=0,o=()=>{let r=i;r&&Promise.resolve(r());},c=async()=>{try{let r=await this.getConnectionStates();r.length>0&&(b$1("[NativeIpcBridge] replaying current native connection states",r.map(l=>({connectionId:l.connectionId,deviceId:l.deviceId??null,deviceIdHint:l.deviceIdHint??null,remoteNodeId:l.remoteNodeId??null,state:l.state,transportState:l.transportState??null,protocolState:l.protocolState??null,routable:l.routable??null}))),r.forEach(l=>e(l)));}catch(r){console.warn("[NativeIpcBridge] Failed to replay native connection states after event subscription:",r);}},d=async r=>{let l=(a$1.get(r)??0)+1;a$1.set(r,l);let u=await this.getConnectionState(r);if(!u||t||a$1.get(r)!==l)return;if(["closed","failed","disconnected"].includes(String(u.state??"").trim().toLowerCase())){if(await a(h.CONNECTION_TERMINAL_CONFIRMATION_MS),t||a$1.get(r)!==l)return;u=await this.getConnectionState(r)??u;}!t&&a$1.get(r)===l&&e(u);};for(;!t&&Date.now()-n$1<=h.CONNECTION_EVENT_SUBSCRIBE_WINDOW_MS;){if(s+=1,!await this.canUseTauriIpc()){await a(this.nextConnectionEventRetryDelayMs(s));continue}return i=await this.listenIpc("connection-state-changed",r=>{let l=n(r?.payload);l&&(b$1("[NativeIpcBridge] connection-state-changed trigger",{connectionId:l.connectionId}),d(l.connectionId));}),await c(),()=>{t=true,o();}}return ()=>{t=true,o();}}async onIncomingNativeMessage(e){if(!await this.canUseTauriIpc())return ()=>{};let t=await this.listenIpc("iroh://message",i=>{if(i?.payload?.data&&i.payload.streamId==="main")try{let a=new Uint8Array(i.payload.data);if(a.length<2||a[0]!==0)return;let s=a.slice(1),o=new TextDecoder().decode(s),c=JSON.parse(o);e(i.payload.connectionId,i.payload.remoteNodeId??null,c);}catch{}});return typeof t=="function"?t:()=>{}}async getTransferHistory(e=50){return await this.canUseTauriIpc()?this.invokeIpc("get_transfer_history",{limit:e}):[]}async deleteTransferJob(e){await this.canUseTauriIpc()&&await this.invokeIpc("delete_transfer_job",{jobId:e});}};h.AUTH_REQUIRED_WAIT_MS=o.nativeIpc.authRequiredWaitMs,h.DEFAULT_BOUNDED_IPC_TIMEOUT_MS=o.nativeIpc.defaultBoundedCommandTimeoutMs,h.CONNECTION_EVENT_SUBSCRIBE_WINDOW_MS=o.nativeIpc.connectionEventSubscribeWindowMs,h.CONNECTION_EVENT_RETRY_MIN_DELAY_MS=o.nativeIpc.connectionEventRetryMinDelayMs,h.CONNECTION_EVENT_RETRY_MAX_DELAY_MS=o.nativeIpc.connectionEventRetryMaxDelayMs,h.CONNECTION_TERMINAL_CONFIRMATION_MS=1500,h.TAURI_IPC_NEGATIVE_CACHE_MS=o.nativeIpc.tauriIpcNegativeCacheMs,h.NATIVE_STATUS_IPC_TIMEOUT_MS=2500;var M=h;var J=class extends a$1{constructor(e){let t=c(e.bridge,"IpcRuntimeAdapter");super(new M({...e,ipcBridge:t,allowWasmFallback:e.allowWasmFallback??false}));}};
|
|
1
|
+
import {a as a$1}from'./chunk-C6PAXO3N.js';import {o,u,w,s,h as h$1,g,j as j$2,k as k$1,l,m,n}from'./chunk-JIVVHBCB.js';import {c as c$1,b as b$1}from'./chunk-VK6KX433.js';import {c,d as d$1,b}from'./chunk-K37WVIZL.js';import {a as a$2}from'./chunk-BXFXPIXO.js';import {c as c$2,b as b$2}from'./chunk-N26S7V4N.js';import {d,a}from'./chunk-NB4H5TP3.js';import {d as d$2,j as j$1}from'./chunk-RD3JEGGF.js';var H="relay-only endpoint ticket unavailable",Q=12e3,X=250,Z=1500;function ee(g){return String(g?.message??g??"").toLowerCase().includes(H)}async function E(g,e={}){let t=e.windowMs??Q,i=e.minDelayMs??X,a$1=e.maxDelayMs??Z,n=Date.now(),s=0,o=null;for(;e.isActive?.()??true;){s+=1;try{return await g()}catch(c){if(o=c,!ee(c))throw c;let d$1=Date.now()-n;if(d$1>=t)throw c;let r=Math.min(d(s,i,a$1),Math.max(0,t-d$1));r>0&&await a(r);}}throw o||new Error("endpoint ticket minting stopped before a ticket was available")}function Y(g){let e=g?.split(".")[1];if(!e)return null;try{let t=e.replace(/-/g,"+").replace(/_/g,"/"),i=(4-t.length%4)%4,a=atob(t+"=".repeat(i)),n=JSON.parse(a);return n&&typeof n=="object"&&!Array.isArray(n)?n:null}catch{return null}}function k(g,e){let t=g?.[e];return typeof t=="string"&&t.trim()?t.trim():null}function j(g,e,t){let i=k(g,"namespaceId")===e||k(g,"appTag")===`space::${e}`,a=k(g,"developerAppTag");return i&&!!a&&(!t||a===t)}function ae(g){let e=k(g,"developerAppTag");if(e)return e;let t=k(g,"appTag");return t&&!t.startsWith("space::")?t:null}var h=class h{constructor(e){this.subscriptionNonce=0;this.lastSyncedAuthToken=null;this.cachedLocalDeviceId=null;this.cachedLocalDeviceName=null;this.tauriCoreAvailability=null;this.tauriCoreAvailabilityValue=null;this.tauriCoreAvailabilityCheckedAtMs=0;this.authSyncInFlight=null;this.nativeTrustTokenUnsubscribe=null;this.nativeTrustRelayQueue=Promise.resolve();this.nativeTrustRelayError=null;this.nativeRuntimeCapabilitiesSyncInFlight=null;this.gatewayDesiredPeersCleanup=null;this.gatewayDesiredPeerRelayKey=null;this.gatewayDesiredPeerRelayGeneration=0;this.gatewayDesiredPeerRevision=0;this.gatewayDesiredPeerSubmission=Promise.resolve();this.gatewayDesiredPeerLifecycle=Promise.resolve();this.gatewayExcludedPeers=new Set;this.lastNativeAuthSyncAtMs=0;this.runtimeCapabilities=u(null,false);this.fallback=new w({...e,coordinationPlatformType:"desktop"}),this.app=this.fallback.app,this.auth=this.fallback.auth,this.appTag=this.fallback.tag,this.options=this.fallback.getResolvedOptions(),this.transportOptions=e.transports,this.strictMode=e.strictMode===true,this.turnCredentialsProvider=e.turnCredentialsProvider,this.allowWasmFallback=e.allowWasmFallback??false,this.ipcBridge=c(e.ipcBridge??d$1(),"NativeIpcBridge"),this.runtimeCapabilities=u(null,this.allowWasmFallback),this.syncNativeRuntimeCapabilities("constructor");}get currentUser(){return this.fallback.currentUser}get tag(){return this.fallback.tag}getRuntimeCapabilities(){let e=s(this.runtimeCapabilities);return e.fallback.wasm=this.allowWasmFallback,e}usesCoordinationGateway(){return this.fallback.usesCoordinationGateway()}assertManagedCoordinationGateway(){if(!this.usesCoordinationGateway())throw new Error("[OpenRTC] Native managed coordination requires coordinationGateway; the legacy native Firebase data plane has been removed.")}async joinCoordinationRoom(e,t,i){await this.syncCoordinationDeviceIdentity(),await this.fallback.joinCoordinationRoom(e,t,i);}leaveCoordinationRoom(e){return this.fallback.leaveCoordinationRoom(e)}getCoordinationRoomMembers(e){return this.fallback.getCoordinationRoomMembers(e)}watchCoordinationRoomMembers(e,t){return this.fallback.watchCoordinationRoomMembers(e,t)}async syncCoordinationDeviceIdentity(){if(!this.usesCoordinationGateway())return;let e=await this.getLocalDeviceInfo().catch(()=>null),t=e?.deviceId||await this.resolveLocalDeviceId();this.fallback.setCoordinationLocalDeviceId(t),this.fallback.setCoordinationPlatformType(this.normalizeNativeCoordinationPlatform(e?.platformType));}setWasmClient(e){if(!this.allowWasmFallback){let t="[NativeIpcBridge][NATIVE-GUARD] Refusing WasmClient attachment because native IPC is authoritative and WASM fallback is disabled.";throw console.error(t,{capabilities:this.getRuntimeCapabilities()}),new Error(t)}this.fallback.setWasmClient(e);}onAuthChange(e){return this.fallback.onAuthChange(e)}checkForSSOToken(){return this.fallback.checkForSSOToken()}waitForAuth(){return this.fallback.waitForAuth()}signInAnonymously(){return this.fallback.signInAnonymously()}getTurnCredentials(){return this.fallback.getTurnCredentials()}cleanupStaleDevices(){return this.fallback.cleanupStaleDevices()}sendMessage(e,t,i,a){return this.fallback.sendMessage(e,t,i,a)}pollMessages(e){return this.fallback.pollMessages(e)}watchFriendDevices(e,t){return this.assertManagedCoordinationGateway(),this.fallback.watchFriendDevices(e,t)}async updateFriendTicket(e){this.assertManagedCoordinationGateway(),await this.syncCoordinationDeviceIdentity(),await this.fallback.updateFriendTicket(e);}createSession(e){return this.fallback.createSession(e)}updateSession(e,t){return this.fallback.updateSession(e,t)}async openPeerBi(e,t){return await this.canUseTauriIpc()?this.openPeerBiViaIpc("open_peer_bi_stream",{peerId:e,timeoutMs:t??null}):this.fallback.openPeerBi(e,t)}async openPeerBiTransportOnly(e,t){return await this.canUseTauriIpc()?this.openPeerBiViaIpc("open_peer_bi_transport_only_stream",{peerId:e,timeoutMs:t??null},{fallbackCommand:"open_peer_bi_stream"}):this.fallback.openPeerBiTransportOnly(e,t)}async openPeerNativeBi(e,t,i){return await this.canUseTauriIpc()?this.openPeerBiViaIpc("open_peer_native_bi_stream",{peerId:e,label:t,timeoutMs:i??null},{fallbackCommand:"open_peer_bi_stream",fallbackArgs:{peerId:e,timeoutMs:i??null}}):this.fallback.openPeerNativeBi(e,t,i)}async incoming_streams(){if(!await this.canUseTauriIpc()){let n=this.fallback;if(typeof n.incoming_streams=="function")return n.incoming_streams();throw new Error("Native incoming stream bridge is unavailable")}let e=`native-incoming-${Date.now()}-${++this.subscriptionNonce}`,t=null,i=false,a=async()=>{i=true;let n=t;t=null,await Promise.allSettled([n?Promise.resolve(n()):Promise.resolve(),this.invokeIpc("stop_rtc_subscription",{requestId:e},{timeoutMs:null}).catch(()=>{})]);};return new ReadableStream({start:async n=>{try{t=await this.listenIpc("openrtc://peer-bi-stream/incoming",s=>{if(i)return;let o=s.payload,c=typeof o?.requestId=="string"?o.requestId:typeof o?.request_id=="string"?o.request_id:"";if(c!==e){c$1("[NativeIpcBridge][incoming-application-stream] ignored request id",{expectedRequestId:e,eventRequestId:c});return}let d=typeof o?.streamId=="string"?o.streamId.trim():typeof o?.stream_id=="string"?o.stream_id.trim():"";if(!d)return;let r=typeof o?.remoteNodeId=="string"?o.remoteNodeId.trim():typeof o?.remote_node_id=="string"?o.remote_node_id.trim():"",l=Number.isSafeInteger(o?.transportStableId)?Number(o.transportStableId):Number.isSafeInteger(o?.transport_stable_id)?Number(o.transport_stable_id):0;if(!r||l<=0){c$1("[NativeIpcBridge][incoming-application-stream] ignored invalid generation",{requestId:e,remoteNodeId:r,transportStableId:l});return}c$1("[NativeIpcBridge][incoming-application-stream] accepted event",{requestId:e,remoteNodeId:r,transportStableId:l});let u=this.peerBiStreamFromId(d,{startReadAfterListeners:!0});n.enqueue({type:"bi",stream:{send:u.writable,recv:u.readable,endpoint_id:r},endpointId:r,transportStableId:l,protocolHint:"unknown",channel:null});}),await this.invokeIpc("start_incoming_peer_bi_streams",{requestId:e},{timeoutMs:null});}catch(s){i=true,n.error(s),await a();}},cancel:async()=>{await a();}})}async is_current_transport_stable_id(e,t){if(!await this.canUseTauriIpc()){let i=this.fallback;return typeof i.is_current_transport_stable_id=="function"?i.is_current_transport_stable_id(e,t):false}return !e.trim()||t<=0n||t>BigInt(Number.MAX_SAFE_INTEGER)?false:this.invokeIpc("is_current_transport_stable_id",{endpointId:e.trim(),transportStableId:Number(t)})}openPeerUni(e,t){return this.fallback.openPeerUni(e,t)}isConnected(e){return this.fallback.isConnected(e)}getAuthContext(){return this.fallback.getAuthContext()}resolveNativeAuthScopedUserId(e){return this.currentUser?.id??this.getAuthContext()?.userId??e??null}resolveConfiguredSpaceKey(){let e=this.options.spaceKey??this.options.space;return typeof e=="string"?e.trim():""}usesAnonymousSpaceMode(){return this.options.authMode==="anonymous"&&this.resolveConfiguredSpaceKey().length>0}requiresNativeAuthToken(){return !this.usesAnonymousSpaceMode()||typeof this.options.spaceTokenProvider=="function"}async nativeAuthTokenMatchesExpectedScope(e){if(!this.usesAnonymousSpaceMode())return true;let t=typeof this.options.apiKey=="string"?this.options.apiKey.trim():"",i=this.resolveConfiguredSpaceKey();if(!t||!i)return true;let a=await d$2(t,i).catch(()=>null);return a?j(Y(e),a):true}resolveNativeSignalingUserId(e){return this.usesAnonymousSpaceMode()?(typeof e=="string"?e.trim():"")||this.resolveConfiguredSpaceKey()||null:this.resolveNativeAuthScopedUserId(e)}getCurrentUserId(){return this.resolveNativeSignalingUserId(this.fallback.getCurrentUserIdForScope())}nativeAuthWaitMs(){return this.requiresNativeAuthToken()?h.AUTH_REQUIRED_WAIT_MS:0}resolveWebLogicalDeviceId(){return this.fallback.getResolvedWebLogicalDeviceId()}normalizeDevice(e,t){return this.fallback.normalizeDeviceRecord(e,t)}matchesTag(e){return this.fallback.matchesLegacyOrCurrentTag(e)}nativeRosterTagDisposition(e){let t=h$1(e);if(this.matchesTag(t))return {keep:true,classification:"match"};let i=typeof t.appTag=="string"&&t.appTag.trim().length>0?t.appTag.trim():typeof t.tag=="string"&&t.tag.trim().length>0?t.tag.trim():void 0;return i===void 0?{keep:true,classification:"untagged"}:{keep:false,classification:"foreign",foreignTag:i}}filterNativeRosterByTag(e,t){let i=new Set,a=e.filter(n=>{let s=this.nativeRosterTagDisposition(n);return !s.keep&&s.foreignTag&&i.add(s.foreignTag),s.keep});return e.length>0&&a.length===0&&i.size>0?console.warn(`[NativeIpcBridge] ${t}: dropped ALL ${e.length} native device(s) as foreign-app \u2014 this is the app-tag drift signature (empty native device list). The native Rust OpenRTC app tag does not match the SDK app tag; check that the desktop binary and the web bundle use the same VITE_PLUTO_OPENRTC_API_KEY / VITE_PLUTO_OPENRTC_APP_TAG for this environment lane.`,{sdkAppTag:this.appTag,foreignTags:Array.from(i),droppedCount:e.length}):i.size>0&&c$1(`[NativeIpcBridge] ${t}: filtered ${e.length-a.length} foreign-app device(s) from the native roster`,{sdkAppTag:this.appTag,foreignTags:Array.from(i)}),a}normalizeNativeIceServer(e){let t=e.urls,i=Array.isArray(t)?t.filter(a=>typeof a=="string"&&a.trim().length>0):typeof t=="string"&&t.trim().length>0?[t]:[];return i.length===0?null:{urls:i,username:typeof e.username=="string"&&e.username.trim().length>0?e.username:void 0,credential:typeof e.credential=="string"&&e.credential.trim().length>0?e.credential:void 0}}filterNativeStunServers(e){return e.map(t=>({...t,urls:t.urls.filter(i=>!i.startsWith("stun:"))})).filter(t=>t.urls.length>0)}nativeIceServerHasTurnUrl(e){return e.urls.some(t=>t.startsWith("turn:")||t.startsWith("turns:"))}async loadNativeTurnIceServers(){if(typeof this.turnCredentialsProvider!="function")return [];let e=await this.turnCredentialsProvider().catch(t=>(console.warn("[NativeIpcBridge] TURN credential provider failed:",t),null));return !e||!Array.isArray(e.iceServers)?[]:e.iceServers.map(t=>this.normalizeNativeIceServer(t)).filter(t=>!!t)}async buildNativeTransportConfigPayload(){let e=this.transportOptions;if(!e&&!this.strictMode)return null;let t;!this.strictMode&&e?.iroh&&(typeof e.iroh=="object"&&e.iroh.localDiscovery===false?t=null:t={enabled:true,advertise:typeof e.iroh!="object"||e.iroh.localDiscoveryMode!=="passive"});let i=null;if(e?.webrtc===true||e?.webrtc&&typeof e.webrtc=="object"){let d=e.webrtc===true?null:e.webrtc,r=d?.useDefaultIceServers!==false,l=Array.isArray(d?.iceServers)&&d.iceServers.length>0?d.iceServers.map(y=>this.normalizeNativeIceServer(y)).filter(y=>!!y):r?j$1.map(y=>this.normalizeNativeIceServer(y)).filter(y=>!!y):[],u=this.strictMode||d?.privacyMode===true;(this.strictMode||d?.privacyMode===true||d?.useTurn===true)&&(l=[...l,...await this.loadNativeTurnIceServers()]),u&&(l=this.filterNativeStunServers(l));let m=l.some(y=>this.nativeIceServerHasTurnUrl(y)),v=u&&m;u&&!m&&console.warn("[NativeIpcBridge] Relay-only WebRTC requested, but no TURN servers are configured; native WebRTC override disabled");let _=d?.lanMode===true;(l.length>0||v||_||!r)&&(i={iceServers:l.length>0||!r?l:void 0,privacyMode:v,lanMode:_||void 0});}let a=null;if(e?.moq&&typeof e.moq=="object"){let d=typeof e.moq.relayUrl=="string"&&e.moq.relayUrl.trim().length>0?e.moq.relayUrl:void 0;if(d){let r=typeof e.moq.accessToken=="string"&&e.moq.accessToken.trim().length>0?e.moq.accessToken.trim():void 0;a={relayUrl:d,accessToken:r};}}let n=null;if(!this.strictMode&&(e?.ble===true||e?.ble&&typeof e.ble=="object")){let d=e.ble===true?null:e.ble,r=Number(d?.connectTimeoutMs);n={enabled:d?.enabled!==false,connectTimeoutMs:Number.isFinite(r)&&r>0?Math.round(r):void 0};}let s=this.strictMode||e?.iroh&&typeof e.iroh=="object"&&e.iroh.relayOnly===true,o=e?.iroh&&typeof e.iroh=="object"?e.iroh.relayTransportPolicy:void 0,c=this.strictMode?o??"auto":o;return !s&&!c&&!i&&!a&&!t&&!n?null:{irohRelayOnly:s||void 0,irohRelayTransportPolicy:c,...t!==void 0?{irohLan:t}:{},webrtc:i,moq:a,ble:n}}isTauriEnv(){return c$2()}nextConnectionEventRetryDelayMs(e){return d(e,h.CONNECTION_EVENT_RETRY_MIN_DELAY_MS,h.CONNECTION_EVENT_RETRY_MAX_DELAY_MS)}async clearNativeAuthRelay(e){if(await this.canUseTauriIpc())try{typeof this.options.coordinationGateway?.grantProvider=="function"?await this.invokeIpc("openrtc_v2_set_identity_credential",{identityCredential:null}):await this.invokeIpc("desktop_set_pluto_auth_token",{authToken:null,refreshToken:null}),this.lastSyncedAuthToken=null,this.lastNativeAuthSyncAtMs=0,c$1(`[NativeIpcBridge] cleared native auth relay (${e})`);}catch(t){console.warn(`[NativeIpcBridge] failed clearing native auth relay (${e}):`,t);}}async clearNativeTrustRelay(e){if(this.nativeTrustTokenUnsubscribe?.(),this.nativeTrustTokenUnsubscribe=null,this.nativeTrustRelayError=null,this.fallback.invalidateCoordinationNativeTrustToken(),typeof this.options.coordinationGateway?.grantProvider!="function"&&await this.canUseTauriIpc())try{await this.invokeIpc("openrtc_set_native_trust_token",{trustToken:null,expiresAtMs:null}),c$1(`[NativeIpcBridge] cleared native trust relay (${e})`);}catch(t){b(t)||console.warn(`[NativeIpcBridge] failed clearing native trust relay (${e}):`,t);}}relayNativeTrustToken(e,t){let i=async()=>{await this.canUseTauriIpc()&&(await this.invokeIpc("openrtc_set_native_trust_token",{trustToken:e?.token??null,expiresAtMs:e?.expiresAtMs??null}),c$1(`[NativeIpcBridge] native trust token ${e?"relayed":"cleared"} (${t})`));},a=this.nativeTrustRelayQueue.then(i,i);return this.nativeTrustRelayQueue=a.catch(()=>{}),a}async ensureNativeTrustRelay(e=false){if(!this.usesCoordinationGateway()||typeof this.options.coordinationGateway?.grantProvider=="function")return true;if(typeof this.options.coordinationGateway?.nativeTrustTokenProvider!="function")return false;if(!await this.canUseTauriIpc())return true;try{let t=await this.fallback.getCoordinationNativeTrustToken(e);return await this.relayNativeTrustToken(t,"auth-ready"),this.nativeTrustRelayError=null,this.nativeTrustTokenUnsubscribe||(this.nativeTrustTokenUnsubscribe=this.fallback.subscribeCoordinationNativeTrustToken(i=>{this.relayNativeTrustToken(i,"provider-refresh").catch(a=>{console.warn("[NativeIpcBridge] native trust token refresh relay failed:",a);});},{emitCurrent:!1})),!0}catch(t){return this.nativeTrustRelayError=(t instanceof Error?t.message:String(t)).trim().slice(0,300)||"unknown provider failure",console.warn("[NativeIpcBridge] native trust token unavailable:",t),false}}async relayNativeAuthToken(e,t,i,a){if(!await this.canUseTauriIpc())return true;if(!await this.nativeAuthTokenMatchesExpectedScope(e))return c$1(`[NativeIpcBridge] auth sync deferred (${i}): token claims do not match configured space`),false;if(e===this.lastSyncedAuthToken)return true;try{typeof this.options.coordinationGateway?.grantProvider=="function"?await this.invokeIpc("openrtc_v2_set_identity_credential",{identityCredential:e}):await this.invokeIpc("desktop_set_pluto_auth_token",{authToken:e,refreshToken:t??null});}catch(n){return b(n)?console.warn(`[NativeIpcBridge] desktop auth relay unavailable (${i}); install/register openrtc-tauri-plugin and include its default permission set.`,n):console.warn(`[NativeIpcBridge] desktop auth relay failed (${i}):`,n),false}return this.lastSyncedAuthToken=e,this.lastNativeAuthSyncAtMs=Date.now(),c$1(`[NativeIpcBridge] auth token relayed to native runtime (${i}) user_id=${a??this.currentUser?.id??"unknown"}`),true}async relayExplicitNativeAuthContext(e){let t=this.authSyncInFlight,i=(async()=>(await t?.catch(()=>{}),this.relayNativeAuthToken(e.token,e.refreshToken,"setAuthContext",e.userId)))();this.authSyncInFlight=i;try{return await i}finally{this.authSyncInFlight===i&&(this.authSyncInFlight=null);}}applyNativeRuntimeStatus(e){this.runtimeCapabilities=u(e,this.allowWasmFallback);}syncNativeRuntimeCapabilities(e){return this.ipcBridge?this.nativeRuntimeCapabilitiesSyncInFlight?this.nativeRuntimeCapabilitiesSyncInFlight:(this.nativeRuntimeCapabilitiesSyncInFlight=(async()=>{try{let t=await this.invokeIpc("rtc_native_status",void 0,{timeoutMs:h.NATIVE_STATUS_IPC_TIMEOUT_MS});this.applyNativeRuntimeStatus(t),c$1(`[NativeIpcBridge] refreshed native runtime capabilities (${e})`);}catch(t){b$1("[NativeIpcBridge] native runtime capability refresh skipped",t);}})().finally(()=>{this.nativeRuntimeCapabilitiesSyncInFlight=null;}),this.nativeRuntimeCapabilitiesSyncInFlight):Promise.resolve()}async canUseTauriIpc(){if(this.ipcBridge){let e=typeof this.ipcBridge.isAvailable=="function"?!!await this.ipcBridge.isAvailable():true;return e&&this.syncNativeRuntimeCapabilities("ipc-available"),e}return typeof window>"u"?false:this.tauriCoreAvailabilityValue===true?true:this.tauriCoreAvailabilityValue===false&&Date.now()-this.tauriCoreAvailabilityCheckedAtMs<h.TAURI_IPC_NEGATIVE_CACHE_MS?false:(this.tauriCoreAvailability||(this.tauriCoreAvailability=(async()=>{try{if(this.isTauriEnv())return this.tauriCoreAvailabilityValue=!0,this.tauriCoreAvailabilityCheckedAtMs=Date.now(),this.syncNativeRuntimeCapabilities("tauri-env"),!0;try{let e=await this.invokeIpc("rtc_native_status");return this.applyNativeRuntimeStatus(e),c$1("[NativeIpcBridge] Resolved Tauri IPC via rtc_native_status probe"),this.tauriCoreAvailabilityValue=!0,this.tauriCoreAvailabilityCheckedAtMs=Date.now(),!0}catch(e){let t=String(e?.message??e??"");return t.includes("__TAURI_INTERNALS__")||t.includes("Cannot read properties of undefined")||t.includes("window is not defined")?(this.tauriCoreAvailabilityValue=!1,this.tauriCoreAvailabilityCheckedAtMs=Date.now(),!1):(c$1("[NativeIpcBridge] Tauri IPC probe reached native layer (command-level error acceptable)"),this.tauriCoreAvailabilityValue=!0,this.tauriCoreAvailabilityCheckedAtMs=Date.now(),!0)}}catch{return this.tauriCoreAvailabilityValue=false,this.tauriCoreAvailabilityCheckedAtMs=Date.now(),false}})().finally(()=>{this.tauriCoreAvailability=null;})),this.tauriCoreAvailability)}async invokeIpc(e,t,i){let a=this.ipcBridge.invoke(e,t),n=i&&Object.prototype.hasOwnProperty.call(i,"timeoutMs")?i.timeoutMs:h.DEFAULT_BOUNDED_IPC_TIMEOUT_MS;return n==null||n<=0?a:a$2(a,n,()=>new Error(`${e} timeout after ${n}ms`))}async listenIpc(e,t){return this.ipcBridge.listen(e,i=>{t({payload:i});})}async openPeerBiViaIpc(e,t,i){let a=await this.invokePeerBiOpen(e,t,i),n=typeof a?.streamId=="string"?a.streamId.trim():typeof a?.stream_id=="string"?a.stream_id.trim():"";if(!n)throw new Error(`${e} returned no streamId`);return this.peerBiStreamFromId(n)}peerBiStreamFromId(e,t={}){let i=this,a=null,n=null,s=false,o=null,c=null,d=async()=>{let m=[a,n];a=null,n=null,await Promise.allSettled(m.filter(v=>typeof v=="function").map(v=>Promise.resolve(v())));},r=(async()=>{a=await this.listenIpc("openrtc://peer-bi-stream/chunk",m=>{let v=m.payload;if((typeof v?.streamId=="string"?v.streamId:typeof v?.stream_id=="string"?v.stream_id:"")!==e||s||!o)return;let f=v?.bytes;f instanceof Uint8Array?o.enqueue(f):Array.isArray(f)&&o.enqueue(new Uint8Array(f));}),n=await this.listenIpc("openrtc://peer-bi-stream/closed",m=>{let v=m.payload;if((typeof v?.streamId=="string"?v.streamId:typeof v?.stream_id=="string"?v.stream_id:"")!==e||s||!o)return;s=true;let f=typeof v?.error=="string"?v.error.trim():"";f?o.error(new Error(f)):o.close(),d();}),t.startReadAfterListeners&&await this.invokeIpc("start_peer_bi_stream_read",{streamId:e},{timeoutMs:null});})().catch(m=>{c=m,o&&!s&&(s=true,o.error(m));}),l=async()=>{await this.invokeIpc("close_peer_bi_stream",{streamId:e},{timeoutMs:null}).catch(()=>{}),await d();},u=new ReadableStream({async start(m){o=m,await r,c&&!s&&(s=true,m.error(c));},async cancel(){s=true,await l();}}),I=new WritableStream({write:async m=>{await i.invokeIpc("write_peer_bi_stream",{streamId:e,bytes:Array.from(m)},{timeoutMs:null});},close:l,abort:l});return {readable:u,writable:I}}async invokePeerBiOpen(e,t,i){try{return await this.invokeIpc(e,t)}catch(a){if(!i?.fallbackCommand||!this.isMissingNativeCommandError(a))throw a;return this.invokeIpc(i.fallbackCommand,i.fallbackArgs??t)}}isMissingNativeCommandError(e){let t=e instanceof Error?e.message:String(e??"");return t.includes("Command")&&t.includes("not found")}async shouldUseTauriSignaling(){if(await this.canUseTauriIpc())return true;if(this.allowWasmFallback)return false;throw new Error("[pluto-rtc] Tauri runtime adapter requires native IPC, but it is unavailable.")}async signInWithPluto(){if(!await this.canUseTauriIpc()){await this.fallback.signInWithPluto();return}let e=await this.invokeIpc("rtc_sign_in_with_pluto"),t=typeof e?.customToken=="string"?e.customToken.trim():"";if(!t)throw new Error("[pluto-rtc] Native Pluto SSO did not return a custom token.");await b$2().signInWithCustomTokenValue(t),await this.ensureNativeAuth("pluto-sso",{requireToken:true,maxWaitMs:1e4});}async setAuthContext(e){let t=this.getAuthContext()?.userId??null,i=typeof e?.userId=="string"&&e.userId.trim()||null,a=this.fallback.setAuthContext(e);if(t&&i&&t!==i&&await this.stopNativeAuthScopedActivity(t),await a,!e?.token)await this.clearNativeAuthRelay("setAuthContext"),await this.clearNativeTrustRelay("setAuthContext");else {if(!await this.relayExplicitNativeAuthContext(e))throw new Error("Native auth token unavailable for setAuthContext");if(!await this.ensureNativeTrustRelay())throw new Error(`Native trust token unavailable for setAuthContext: ${this.nativeTrustRelayError??"unknown provider failure"}`)}}async signOut(){await this.fallback.signOut(),await Promise.all([this.clearNativeAuthRelay("signOut"),this.clearNativeTrustRelay("signOut")]);}async stopAuthScopedActivity(e){let t=this.resolveNativeSignalingUserId(e?.userId??null);await this.stopNativeAuthScopedActivity(t);}async stopNativeAuthScopedActivity(e){await this.stopGatewayDesiredPeerRelay(),this.gatewayExcludedPeers.clear();let t=await this.shouldUseTauriSignaling();if(g("NativeIpcBridge.stopAuthScopedActivity",{userId:e,useTauri:t}),t)try{await Promise.allSettled([this.revokeSessionTokensByScope("user-device"),this.invokeIpc("stop_rtc_presence_loop"),this.invokeIpc("stop_rtc_auto_connect")]);}catch(i){console.warn("[NativeIpcBridge] Failed to stop native auth-scoped RTC activity:",i);}await this.fallback.stopAuthScopedActivity({userId:e});}async ensureNativeAuthOnce(e,t){if(!await this.canUseTauriIpc())return true;if(this.authSyncInFlight)return this.authSyncInFlight;let i=(async()=>{try{if(!this.currentUser)return c$1(`[NativeIpcBridge] auth sync deferred (${e}): no current user`),!t;let a=Date.now()-this.lastNativeAuthSyncAtMs>=480*1e3,n=this.currentUser?.getToken?await this.currentUser.getToken(a):null,o=this.getAuthContext()?.refreshToken??this.auth?.currentUser?.refreshToken??null;return n?this.relayNativeAuthToken(n,o,e,this.currentUser?.id):(c$1(`[NativeIpcBridge] auth sync deferred (${e}): missing token for user ${this.currentUser?.id}`),!t)}catch(a){return console.error("[NativeIpcBridge] auth sync failed:",a),false}})();this.authSyncInFlight=i;try{return await i}finally{this.authSyncInFlight===i&&(this.authSyncInFlight=null);}}async ensureNativeAuth(e="runtime",t){if(!await this.canUseTauriIpc())return true;let i=t?.requireToken??false,a$1=t?.maxWaitMs??(i?h.AUTH_REQUIRED_WAIT_MS:0),n=t?.pollMs??250,s=Date.now()+Math.max(0,a$1);for(;;){if(await this.ensureNativeAuthOnce(e,i))return true;if(!i||Date.now()>=s)return false;await a(n);}}decodeNativeDeviceIdentity(e){let t=e?.systemInfo??e?.system_info??null,i=typeof e?.deviceId=="string"?e.deviceId.trim():typeof e?.device_id=="string"?e.device_id.trim():"",a=typeof e?.deviceName=="string"?e.deviceName.trim():typeof e?.device_name=="string"?e.device_name.trim():"",n=typeof e?.platformType=="string"?e.platformType.trim():typeof e?.platform_type=="string"?e.platform_type.trim():typeof t?.platformType=="string"?t.platformType.trim():typeof t?.platform_type=="string"?t.platform_type.trim():"";return {deviceId:i,deviceName:a,platformType:n}}async resolveLocalDeviceId(){if(this.cachedLocalDeviceId)return this.cachedLocalDeviceId;if(await this.canUseTauriIpc())try{let t=await this.invokeIpc("get_rtc_local_device_info"),{deviceId:i,deviceName:a}=this.decodeNativeDeviceIdentity(t);if(i)return this.cachedLocalDeviceId=i,a&&(this.cachedLocalDeviceName=a),i}catch(t){console.warn("[NativeIpcBridge] get_rtc_local_device_info failed:",t);}let e=this.resolveWebLogicalDeviceId();return this.cachedLocalDeviceId=e,e}async resolveLocalDeviceName(){if(this.cachedLocalDeviceName)return this.cachedLocalDeviceName;if(await this.canUseTauriIpc())try{let e=await this.invokeIpc("get_rtc_local_device_info"),{deviceName:t}=this.decodeNativeDeviceIdentity(e);if(t){let i=this.normalizeNativeDeviceName(t);return this.cachedLocalDeviceName=i,i}}catch(e){console.warn("[NativeIpcBridge] get_rtc_local_device_info failed:",e);}return this.defaultDeviceNameFallback()}normalizeNativeDeviceName(e){let t=e.trim();if(!t)return this.defaultDeviceNameFallback();if(t==="Desktop Device"){let i=this.defaultDeviceNameFallback();if(i!=="Desktop Device")return i}return t}defaultDeviceNameFallback(){if(typeof window>"u"||typeof navigator>"u")return "Desktop Device";let e=navigator.userAgent||"";return /iPhone|iPad|iPod/i.test(e)?"iPhone":/Android/i.test(e)?"Android":"Desktop Device"}inferNativePlatformTypeFallback(){if(typeof window>"u"||typeof navigator>"u")return "desktop";if(!this.isTauriEnv())return "web";let e=navigator.userAgent||"";return /iPhone|iPad|iPod|Android|Mobile/i.test(e)?"mobile":"desktop"}normalizeNativeCoordinationPlatform(e){let t=e?.trim().toLowerCase()??"";return t==="mobile"||t==="ios"||t==="android"||t.includes("iphone")||t.includes("ipad")||this.inferNativePlatformTypeFallback()==="mobile"?"mobile":"desktop"}withPresenceMetadata(e,t){try{let i=e?JSON.parse(e):{};return JSON.stringify({...i,deviceId:t,plutoVersion:"0.1.0-desktop"})}catch{return JSON.stringify({deviceId:t,plutoVersion:"0.1.0-desktop",rawMetadata:e})}}async searchDevices(e){return this.assertManagedCoordinationGateway(),this.fallback.searchDevices(e)}async listDevicesWithStatus(){return this.assertManagedCoordinationGateway(),(await this.fallback.searchDevices()).map(e=>j$2(e))}async getPeerSession(e){if(await this.shouldUseTauriSignaling()){let t=await this.invokeIpc("get_rtc_peer_session",{id:e});return !t||typeof t!="object"?null:k$1(t)}return this.fallback.getPeerSession(e)}async listPeerSessions(){if(await this.shouldUseTauriSignaling()){let e=await this.invokeIpc("list_rtc_peer_sessions");return (Array.isArray(e)?e:[]).map(t=>k$1(t))}return this.fallback.listPeerSessions()}async waitForSettledPeer(e,t){if(await this.shouldUseTauriSignaling()){let i=typeof t=="number"?Math.max(h.DEFAULT_BOUNDED_IPC_TIMEOUT_MS,t+1e3):h.DEFAULT_BOUNDED_IPC_TIMEOUT_MS,a=await this.invokeIpc("wait_for_rtc_settled_peer",{id:e,timeoutMs:t},{timeoutMs:i});return !a||typeof a!="object"?null:k$1(a)}return this.fallback.waitForSettledPeer(e,t)}async resolvePeerConnectionRecords(e){if(await this.shouldUseTauriSignaling()){let t=await this.invokeIpc("resolve_rtc_peer_connection_records",{id:e});return (Array.isArray(t)?t:[]).map(i=>l(i))}return this.fallback.resolvePeerConnectionRecords(e)}async resolvePeerIdentity(e){if(await this.shouldUseTauriSignaling()){let t=await this.invokeIpc("resolve_rtc_peer_identity",{id:e});return m(t)}return this.fallback.resolvePeerIdentity(e)}async setOffline(e){return this.assertManagedCoordinationGateway(),this.fallback.setOffline(e)}async updateDevice(e,t){return this.assertManagedCoordinationGateway(),await this.syncCoordinationDeviceIdentity(),this.fallback.updateDevice(e,t)}async deleteDevice(e){return this.assertManagedCoordinationGateway(),await this.syncCoordinationDeviceIdentity(),this.fallback.deleteDevice(e)}async getLocalDeviceInfo(){if(!await this.canUseTauriIpc()){let e=await this.getLocalDeviceId?.();return e?{deviceId:e,deviceName:this.defaultDeviceNameFallback(),platformType:this.inferNativePlatformTypeFallback()}:null}try{let e=await this.invokeIpc("get_rtc_local_device_info"),t=this.decodeNativeDeviceIdentity(e),{deviceId:i}=t;return i?{deviceId:i,deviceName:this.normalizeNativeDeviceName(t.deviceName),platformType:t.platformType||this.inferNativePlatformTypeFallback(),capabilities:e?.capabilities??void 0,lastSeenAt:typeof e?.last_seen_at=="string"?e.last_seen_at:void 0}:null}catch(e){return console.warn("[NativeIpcBridge] getLocalDeviceInfo failed:",e),null}}async updateLocalDeviceName(e){if(!await this.canUseTauriIpc())return null;try{let t=await this.invokeIpc("update_rtc_local_device_name",{deviceName:e}),i=this.decodeNativeDeviceIdentity(t),{deviceId:a}=i;return a?(this.cachedLocalDeviceName=this.normalizeNativeDeviceName(e),{deviceId:a,deviceName:this.cachedLocalDeviceName,platformType:i.platformType||this.inferNativePlatformTypeFallback(),capabilities:t?.capabilities??void 0,lastSeenAt:typeof t?.last_seen_at=="string"?t.last_seen_at:void 0}):null}catch(t){return console.warn("[NativeIpcBridge] updateLocalDeviceName failed:",t),null}}async startManagedSessionNative(e){if(this.assertManagedCoordinationGateway(),!await this.shouldUseTauriSignaling())throw new Error("[pluto-rtc] Native IPC unavailable for startManagedSessionNative().");if(!await this.ensureNativeAuth("startManagedSessionNative",{requireToken:this.requiresNativeAuthToken(),maxWaitMs:this.nativeAuthWaitMs()}))throw new Error("Native auth token unavailable for startManagedSessionNative");let i=this.resolveNativeSignalingUserId(e.userId);if(!i)throw new Error("Native managed session startup requires a runtime auth-scoped user id.");i!==e.userId&&console.info("[NativeIpcBridge][managed-session][user-id-remap]",{requestedUserId:e.userId,runtimeUserId:this.currentUser?.id??this.getAuthContext()?.userId??null,effectiveUserId:i}),console.info("[NativeIpcBridge][managed-session][start-request]",{requestedUserId:e.userId,runtimeUserId:this.currentUser?.id??this.getAuthContext()?.userId??null,effectiveUserId:i,deviceName:e.deviceName??null,localDeviceId:e.localDeviceId??null,presence:e.presence!==false,autoConnect:e.autoConnect!==false,hasMetadata:typeof e.metadata=="string"&&e.metadata.trim().length>0});let a=await this.buildNativeTransportConfigPayload(),n={userId:i,deviceName:e.deviceName??null,localDeviceId:e.localDeviceId??null,metadata:e.metadata??null,...a?{transports:a}:{},autoConnect:false,presence:false},s=await this.invokeIpc("start_rtc_managed_session",n,{timeoutMs:null});this.syncNativeRuntimeCapabilities("managed-session-started");let o=typeof s?.ticket=="string"&&s.ticket.trim().length>0?s.ticket.trim():null,c=s?.localDevice&&typeof s.localDevice=="object"?s.localDevice:s?.local_device&&typeof s.local_device=="object"?s.local_device:null,d=c?{deviceId:typeof c.deviceId=="string"?c.deviceId:typeof c.device_id=="string"?c.device_id:"",deviceName:this.normalizeNativeDeviceName(typeof c.deviceName=="string"?c.deviceName:typeof c.device_name=="string"?c.device_name:""),platformType:typeof c.platformType=="string"?c.platformType:typeof c.platform_type=="string"?c.platform_type:"desktop",capabilities:c.capabilities??void 0,lastSeenAt:typeof c.lastSeenAt=="string"?c.lastSeenAt:typeof c.last_seen_at=="string"?c.last_seen_at:void 0}:null,r={localNodeId:typeof s?.localNodeId=="string"?s.localNodeId:typeof s?.local_node_id=="string"?s.local_node_id:null,ticket:o,ticketScope:typeof s?.ticketScope=="string"?s.ticketScope:typeof s?.ticket_scope=="string"?s.ticket_scope:null,presenceStarted:typeof s?.presenceStarted=="boolean"?s.presenceStarted:!!s?.presence_started,autoConnectStarted:typeof s?.autoConnectStarted=="boolean"?s.autoConnectStarted:!!s?.auto_connect_started,localDevice:d?.deviceId?d:null};if(this.usesCoordinationGateway()){e.presence!==false&&!r.ticket&&(r.ticket=await this.getEndpointTicketWithToken("user-device",0),r.ticketScope=r.ticket?"user-device":null);let l=r.localDevice?.deviceId||e.localDeviceId?.trim()||await this.resolveLocalDeviceId();if(l&&this.fallback.setCoordinationLocalDeviceId(l),this.fallback.setCoordinationPlatformType(this.normalizeNativeCoordinationPlatform(r.localDevice?.platformType)),e.presence!==false){if(!r.localNodeId||!r.ticket)throw new Error("Native managed session did not return the node identity required for gateway presence.");await this.fallback.updatePresence(r.localNodeId,r.ticket,true,3e5,e.metadata,r.localDevice?.deviceName||e.deviceName),r.presenceStarted=true;}else r.presenceStarted=false;e.autoConnect!==false&&l?(await this.startGatewayAutoConnect(i,l),r.autoConnectStarted=true):r.autoConnectStarted=false;}return console.info("[NativeIpcBridge][managed-session][ipc-started]",{requestedUserId:e.userId,runtimeUserId:this.currentUser?.id??this.getAuthContext()?.userId??null,effectiveUserId:i,localNodeId:r.localNodeId,ticketScope:r.ticketScope,presenceStarted:r.presenceStarted,autoConnectStarted:r.autoConnectStarted,localDeviceId:r.localDevice?.deviceId??null}),r}async reconcileNativeManagedSession(e){return this.assertManagedCoordinationGateway(),await this.fallback.reconnectCoordinationAfterHostResume(),console.info("[NativeIpcBridge] reattached gateway coordination after host resume.",{reason:e?.reason??"frontend"}),null}async notifyNetworkChange(e){return await this.canUseTauriIpc()?(c$1("[NativeIpcBridge] forwarding host network-change hint",{reason:e?.reason??"host"}),this.invokeIpc("notify_rtc_network_change")):null}async getManagedNodeId(e){let t=e?.initializeIfMissing??true;console.info("[NativeIpcBridge][getManagedNodeId] enter",{initializeIfMissing:t});let i=await this.canUseTauriIpc();if(console.info("[NativeIpcBridge][getManagedNodeId] canUseTauriIpc",{canUse:i}),!i)return null;try{console.info("[NativeIpcBridge][getManagedNodeId] invoking get_iroh_node_id");let a=await this.invokeIpc("get_iroh_node_id");if(console.info("[NativeIpcBridge][getManagedNodeId] get_iroh_node_id returned",{existing:a}),a||!t)return a;console.info("[NativeIpcBridge][getManagedNodeId] invoking start_iroh_node");let n=await this.invokeIpc("start_iroh_node");return console.info("[NativeIpcBridge][getManagedNodeId] start_iroh_node returned",{started:n}),n}catch(a){if(console.warn("[NativeIpcBridge] getManagedNodeId failed:",a),!t)return null;throw a}}async getEndpointTicket(){if(!await this.canUseTauriIpc())throw new Error("[pluto-rtc] getEndpointTicket requires native IPC in Tauri runtime.");return E(()=>this.invokeIpc("get_iroh_endpoint_ticket"))}async connectToDevice(e){if(!await this.canUseTauriIpc())throw new Error("[pluto-rtc] connectToDevice requires native IPC in Tauri runtime.");this.options.authMode!=="anonymous"?await this.ensureNativeAuth("connectToDevice",{requireToken:true,maxWaitMs:h.AUTH_REQUIRED_WAIT_MS}):c$1("[NativeIpcBridge] connectToDevice using anonymous native ticket path");let t=Math.max(1,Math.floor(e.timeoutMs??h.DEFAULT_BOUNDED_IPC_TIMEOUT_MS));return this.invokeIpc("connect_to_device",{deviceId:e.deviceId??null,endpointTicket:e.endpointTicket,timeoutMs:t},{timeoutMs:t+1e3})}async registerSessionToken(e,t,i){await this.canUseTauriIpc()&&await this.invokeIpc("register_session_token",{token:e,scope:t,maxConnections:i});}async getEndpointTicketWithToken(e,t){if(!await this.canUseTauriIpc())return null;try{return await E(()=>this.invokeIpc("get_endpoint_ticket_with_token",{scope:e,maxConnections:t}))}catch{return null}}async validateSessionToken(e,t){if(!await this.canUseTauriIpc())return null;try{return await this.invokeIpc("validate_session_token",{token:e,connectionId:t??null})}catch{return null}}async revokeSessionTokensByScope(e){if(g("NativeIpcBridge.revokeSessionTokensByScope",{grantScope:e}),!await this.canUseTauriIpc())return [];try{return await this.invokeIpc("revoke_session_tokens_by_scope",{scope:e})}catch{return []}}async disconnectDevice(e){if(!await this.canUseTauriIpc())throw new Error("[pluto-rtc] disconnectDevice requires native IPC in Tauri runtime.");await this.invokeIpc("disconnect_device",{deviceId:e});}async setAutoConnectExcluded(e,t){if(!await this.canUseTauriIpc())return;let i=e.trim().toLowerCase();i&&(this.usesCoordinationGateway()&&(t?this.gatewayExcludedPeers.add(i):this.gatewayExcludedPeers.delete(i)),await this.invokeIpc(this.usesCoordinationGateway()?"set_rtc_external_auto_connect_excluded":"set_auto_connect_excluded",{deviceId:e,excluded:t}),this.usesCoordinationGateway()&&await this.fallback.setCoordinationExcludedPeers([...this.gatewayExcludedPeers].sort()));}onDevicesChange(e,t){return this.assertManagedCoordinationGateway(),this.fallback.onDevicesChange(e,t)}async subscribeDevices(e){return this.assertManagedCoordinationGateway(),this.fallback.subscribeDevices(e)}async subscribeSessions(e){return this.assertManagedCoordinationGateway(),this.fallback.subscribeSessions(e)}async getLocalDeviceId(){return this.resolveLocalDeviceId()}async updatePresence(e,t,i=true,a=3e5,n){return this.assertManagedCoordinationGateway(),await this.syncCoordinationDeviceIdentity(),this.fallback.updatePresence(e,t,i,a,n)}startAutoConnect(e,t){this.assertManagedCoordinationGateway(),this.startGatewayAutoConnect(e,t).catch(i=>{console.warn("[NativeIpcBridge] gateway auto-connect failed:",i);});}forceReconnectSnapshot(){this.assertManagedCoordinationGateway(),this.fallback.forceReconnectSnapshot();}startPresenceLoop(e,t,i,a,n){this.assertManagedCoordinationGateway(),this.syncCoordinationDeviceIdentity().then(()=>this.fallback.startPresenceLoop(e,t,i,a,n)).catch(s=>{console.warn("[NativeIpcBridge] gateway presence failed:",s);});}async startAutoConnectOnce(e,t){this.assertManagedCoordinationGateway(),await this.startGatewayAutoConnect(e,t);}async clearGatewayDesiredPeerRelay(){let e=this.gatewayDesiredPeerSubmission;this.gatewayDesiredPeerRelayGeneration+=1,this.gatewayDesiredPeersCleanup?.(),this.gatewayDesiredPeersCleanup=null,this.gatewayDesiredPeerRelayKey=null,this.gatewayDesiredPeerRevision=0,this.gatewayDesiredPeerSubmission=Promise.resolve(),await e;}serializeGatewayDesiredPeerLifecycle(e){let t=this.gatewayDesiredPeerLifecycle.then(e);return this.gatewayDesiredPeerLifecycle=t.catch(()=>{}),t}stopGatewayDesiredPeerRelay(){return this.serializeGatewayDesiredPeerLifecycle(async()=>{await this.clearGatewayDesiredPeerRelay();})}startGatewayAutoConnect(e,t){return this.serializeGatewayDesiredPeerLifecycle(()=>this.startGatewayAutoConnectSerialized(e,t))}async startGatewayAutoConnectSerialized(e,t){if(!await this.shouldUseTauriSignaling())throw new Error("[openrtc] Native IPC unavailable for coordination gateway auto-connect.");if(!await this.ensureNativeAuth("startGatewayAutoConnect",{requireToken:this.requiresNativeAuthToken(),maxWaitMs:this.nativeAuthWaitMs()}))throw new Error("Native auth token unavailable for coordination gateway auto-connect");let a=this.resolveNativeSignalingUserId(e);if(!a)throw new Error("Coordination gateway auto-connect requires an authenticated user id.");let n=await this.resolveLocalDeviceId()||t.trim();if(!n)throw new Error("Coordination gateway auto-connect requires a local device id.");let s=JSON.stringify([a,n]);this.fallback.setCoordinationLocalDeviceId(n);let o=this.gatewayDesiredPeerRelayKey===s&&this.gatewayDesiredPeersCleanup;if(o||(await this.clearGatewayDesiredPeerRelay(),this.gatewayDesiredPeerRelayKey=s),await this.invokeIpc("start_rtc_external_auto_connect",{userId:a,localDeviceId:n}),o)return;let c=this.gatewayDesiredPeerRelayGeneration;this.gatewayDesiredPeersCleanup=this.fallback.onDevicesChange(d=>{let r=d.map(u=>({deviceId:String(u.deviceId??"").trim(),nodeId:typeof u.nodeId=="string"&&u.nodeId.trim()||null,ticket:typeof u.ticket=="string"&&u.ticket.trim()||null,online:u.online===true,sessionId:typeof u.sessionId=="string"&&u.sessionId.trim()||null,excludedPeers:Array.isArray(u.excludedPeers)?[...new Set(u.excludedPeers.map(I=>String(I??"").trim().toLowerCase()).filter(Boolean))].sort():[]})).filter(u=>u.deviceId.length>0&&u.deviceId!==n).sort((u,I)=>u.deviceId.localeCompare(I.deviceId)),l=++this.gatewayDesiredPeerRevision;this.gatewayDesiredPeerSubmission=this.gatewayDesiredPeerSubmission.then(async()=>{this.gatewayDesiredPeerRelayGeneration!==c||this.gatewayDesiredPeerRelayKey!==s||await this.invokeIpc("submit_rtc_desired_peers",{revision:l,peersJson:JSON.stringify(r)});}).catch(u=>{console.warn("[NativeIpcBridge] failed to relay gateway desired peers to Rust:",{revision:l,error:u});});},n);}async startPresenceLoopOnce(e,t,i,a,n){this.assertManagedCoordinationGateway(),await this.syncCoordinationDeviceIdentity(),await this.fallback.startPresenceLoop(e,t,i,a,n);}shouldUseResolvedDeviceName(e){let t=e.trim();return t.length===0||t==="Unknown Device"||t==="Desktop Device"}async sendExplicitFilePath(e,t,i=""){if(c$1("[NativeIpcBridge] sendExplicitFilePath start",{connectionId:e,filePath:t,transferId:i||null,authMode:this.options.authMode}),await this.canUseTauriIpc()){this.options.authMode!=="anonymous"?await this.ensureNativeAuth("sendExplicitFilePath"):c$1("[NativeIpcBridge] sendExplicitFilePath using anonymous native path");let a=await this.invokeIpc("send_file",{connectionId:e,filePath:t,transferId:i});return c$1("[NativeIpcBridge] sendExplicitFilePath completed",{connectionId:e,transferId:i||null,result:a}),a}return this.fallback.sendExplicitFilePath(e,t,i)}async sendExplicitFileData(e){c$1("[NativeIpcBridge] sendExplicitFileData start",{connectionId:e.connectionId??null,connectionRemoteNodeId:e.connection?.remoteNodeId??null,remoteNodeId:e.remoteNodeId??null,transferId:e.transferId??null,fileName:e.file.name,fileSize:e.file.size,authMode:this.options.authMode});let t=e.applicationCrypto??this.options.applicationCrypto;if(await this.canUseTauriIpc()){this.options.authMode!=="anonymous"?await this.ensureNativeAuth("sendExplicitFileData"):c$1("[NativeIpcBridge] sendExplicitFileData using anonymous native path");let i=e.connectionId||e.connection?.deviceId||e.connection?.remoteNodeId||e.remoteNodeId||"";if(!i)throw new Error("sendExplicitFileData requires a settled peer identifier in native runtime");let a=new Uint8Array(await e.file.arrayBuffer());await this.invokeIpc("send_file_data",{connectionId:i,filename:e.file.name,data:Array.from(a),transferId:e.transferId}),c$1("[NativeIpcBridge] sendExplicitFileData completed",{connectionId:i,transferId:e.transferId??null,fileName:e.file.name,fileSize:e.file.size});return}return this.fallback.sendExplicitFileData({...e,applicationCrypto:t})}async getConnectionStates(){if(await this.canUseTauriIpc())try{this.options.authMode!=="anonymous"&&await this.ensureNativeAuth("getConnectionStates");let e=await this.invokeIpc("list_rtc_connection_states");return (Array.isArray(e)?e:[]).map(t=>n(t)).filter(t=>!!t)}catch(e){return b(e)?c$1("[NativeIpcBridge] native connection-state replay unavailable; continuing without replay. Install/register openrtc-tauri-plugin default permissions to enable it."):console.warn("[NativeIpcBridge] Failed to fetch native connection states:",e),[]}return []}async getConnectionState(e){let t=e.trim();if(!t||!await this.canUseTauriIpc())return null;try{return this.options.authMode!=="anonymous"&&await this.ensureNativeAuth("getConnectionState"),n(await this.invokeIpc("get_rtc_connection_state",{connectionId:t}))}catch(i){return console.warn("[NativeIpcBridge] Failed to fetch native connection state:",{connectionId:t,error:i}),null}}async onConnectionStateChange(e){let t=false,i=null,a$1=new Map,n$1=Date.now(),s=0,o=()=>{let r=i;r&&Promise.resolve(r());},c=async()=>{try{let r=await this.getConnectionStates();r.length>0&&(b$1("[NativeIpcBridge] replaying current native connection states",r.map(l=>({connectionId:l.connectionId,deviceId:l.deviceId??null,deviceIdHint:l.deviceIdHint??null,remoteNodeId:l.remoteNodeId??null,state:l.state,transportState:l.transportState??null,protocolState:l.protocolState??null,routable:l.routable??null}))),r.forEach(l=>e(l)));}catch(r){console.warn("[NativeIpcBridge] Failed to replay native connection states after event subscription:",r);}},d=async r=>{let l=(a$1.get(r)??0)+1;a$1.set(r,l);let u=await this.getConnectionState(r);if(!u||t||a$1.get(r)!==l)return;if(["closed","failed","disconnected"].includes(String(u.state??"").trim().toLowerCase())){if(await a(h.CONNECTION_TERMINAL_CONFIRMATION_MS),t||a$1.get(r)!==l)return;u=await this.getConnectionState(r)??u;}!t&&a$1.get(r)===l&&e(u);};for(;!t&&Date.now()-n$1<=h.CONNECTION_EVENT_SUBSCRIBE_WINDOW_MS;){if(s+=1,!await this.canUseTauriIpc()){await a(this.nextConnectionEventRetryDelayMs(s));continue}return i=await this.listenIpc("connection-state-changed",r=>{let l=n(r?.payload);l&&(b$1("[NativeIpcBridge] connection-state-changed trigger",{connectionId:l.connectionId}),d(l.connectionId));}),await c(),()=>{t=true,o();}}return ()=>{t=true,o();}}async onIncomingNativeMessage(e){if(!await this.canUseTauriIpc())return ()=>{};let t=await this.listenIpc("iroh://message",i=>{if(i?.payload?.data&&i.payload.streamId==="main")try{let a=new Uint8Array(i.payload.data);if(a.length<2||a[0]!==0)return;let s=a.slice(1),o=new TextDecoder().decode(s),c=JSON.parse(o);e(i.payload.connectionId,i.payload.remoteNodeId??null,c);}catch{}});return typeof t=="function"?t:()=>{}}async getTransferHistory(e=50){return await this.canUseTauriIpc()?this.invokeIpc("get_transfer_history",{limit:e}):[]}async deleteTransferJob(e){await this.canUseTauriIpc()&&await this.invokeIpc("delete_transfer_job",{jobId:e});}};h.AUTH_REQUIRED_WAIT_MS=o.nativeIpc.authRequiredWaitMs,h.DEFAULT_BOUNDED_IPC_TIMEOUT_MS=o.nativeIpc.defaultBoundedCommandTimeoutMs,h.CONNECTION_EVENT_SUBSCRIBE_WINDOW_MS=o.nativeIpc.connectionEventSubscribeWindowMs,h.CONNECTION_EVENT_RETRY_MIN_DELAY_MS=o.nativeIpc.connectionEventRetryMinDelayMs,h.CONNECTION_EVENT_RETRY_MAX_DELAY_MS=o.nativeIpc.connectionEventRetryMaxDelayMs,h.CONNECTION_TERMINAL_CONFIRMATION_MS=1500,h.TAURI_IPC_NEGATIVE_CACHE_MS=o.nativeIpc.tauriIpcNegativeCacheMs,h.NATIVE_STATUS_IPC_TIMEOUT_MS=2500;var M=h;var J=class extends a$1{constructor(e){let t=c(e.bridge,"IpcRuntimeAdapter");super(new M({...e,ipcBridge:t,allowWasmFallback:e.allowWasmFallback??false}));}};
|
|
2
2
|
export{Y as a,k as b,j as c,ae as d,E as e,J as f};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import {t}from'./chunk-
|
|
1
|
+
import {t}from'./chunk-JIVVHBCB.js';var a=class{constructor(e){this.backend=e;}get currentUser(){return this.backend.currentUser}setAuthContext(e){return this.backend.setAuthContext?.(e)}async signInAnonymously(){return this.backend.signInAnonymously()}async signInWithPluto(){if(typeof this.backend.signInWithPluto!="function")throw new Error("Selected runtime adapter does not support Pluto SSO.");return this.backend.signInWithPluto()}async signOut(){return this.backend.signOut()}async stopAuthScopedActivity(){typeof this.backend.stopAuthScopedActivity=="function"&&await this.backend.stopAuthScopedActivity();}usesCoordinationGateway(){return this.backend.usesCoordinationGateway?.()===true}async joinCoordinationRoom(e,n,t){if(!this.backend.joinCoordinationRoom)throw new Error("Selected runtime adapter does not support coordination rooms.");await this.backend.joinCoordinationRoom(e,n,t);}async leaveCoordinationRoom(e){if(!this.backend.leaveCoordinationRoom)throw new Error("Selected runtime adapter does not support coordination rooms.");await this.backend.leaveCoordinationRoom(e);}async getCoordinationRoomMembers(e){if(!this.backend.getCoordinationRoomMembers)throw new Error("Selected runtime adapter does not support coordination rooms.");return this.backend.getCoordinationRoomMembers(e)}watchCoordinationRoomMembers(e,n){if(!this.backend.watchCoordinationRoomMembers)throw new Error("Selected runtime adapter does not support coordination rooms.");return this.backend.watchCoordinationRoomMembers(e,n)}async getTurnCredentials(){return this.backend.getTurnCredentials()}async updatePresence(e,n,t,i,r){return this.backend.updatePresence(e,n,t,i,r)}async refreshLivePresence(e,n,t){if(typeof this.backend.refreshLivePresence!="function")throw new Error("Selected runtime adapter does not support refreshLivePresence().");return this.backend.refreshLivePresence(e,n,t)}async setOffline(e){return this.backend.setOffline(e)}async cleanupStaleDevices(){return this.backend.cleanupStaleDevices()}async searchDevices(e){return this.backend.searchDevices(e)}async listDevicesWithStatus(){if(typeof this.backend.listDevicesWithStatus!="function")throw new Error("Selected runtime adapter does not support listDevicesWithStatus().");return this.backend.listDevicesWithStatus()}async getPeerSession(e){return typeof this.backend.getPeerSession!="function"?null:this.backend.getPeerSession(e)}async listPeerSessions(){return typeof this.backend.listPeerSessions!="function"?[]:this.backend.listPeerSessions()}async waitForSettledPeer(e,n){return typeof this.backend.waitForSettledPeer!="function"?null:this.backend.waitForSettledPeer(e,n)}async resolvePeerIdentity(e){return typeof this.backend.resolvePeerIdentity!="function"?{peerId:null,deviceId:null,deviceIdHint:null,nodeId:null}:this.backend.resolvePeerIdentity(e)}async resolvePeerConnectionRecords(e){return typeof this.backend.resolvePeerConnectionRecords!="function"?[]:this.backend.resolvePeerConnectionRecords(e)}async updateDevice(e,n){return this.backend.updateDevice(e,n)}async deleteDevice(e){return this.backend.deleteDevice(e)}onDevicesChange(e,n){return this.backend.onDevicesChange(e,n)}onAuthChange(e){return this.backend.onAuthChange(e)}async checkForSSOToken(){return this.backend.checkForSSOToken()}async waitForAuth(){return this.backend.waitForAuth()}async sendMessage(e,n,t,i){return this.backend.sendMessage(e,n,t,i)}async pollMessages(e){return this.backend.pollMessages(e)}watchFriendDevices(e,n){let t=this.backend;return t.watchFriendDevices?t.watchFriendDevices(e,n):()=>{}}async updateFriendTicket(e){let n=this.backend;n.updateFriendTicket&&await n.updateFriendTicket(e);}async subscribeDevices(e){return this.backend.subscribeDevices(e)}startAutoConnect(e,n){this.backend.startAutoConnect(e,n);}async submitDesiredPeerProjection(e,n){if(typeof this.backend.submitDesiredPeerProjection!="function")throw new Error("Selected runtime adapter does not support desired-peer projections.");await this.backend.submitDesiredPeerProjection(e,n);}startPresenceLoop(e,n,t,i,r){this.backend.startPresenceLoop(e,n,t,i,r);}async createSession(e){return this.backend.createSession(e)}async updateSession(e,n){return this.backend.updateSession(e,n)}async subscribeSessions(e){return this.backend.subscribeSessions(e)}forceReconnectSnapshot(){this.backend.forceReconnectSnapshot();}async getLocalDeviceId(){return typeof this.backend.getLocalDeviceId!="function"?null:this.backend.getLocalDeviceId()}async getLocalDeviceInfo(){return typeof this.backend.getLocalDeviceInfo!="function"?null:this.backend.getLocalDeviceInfo()}async updateLocalDeviceName(e){return typeof this.backend.updateLocalDeviceName!="function"?null:this.backend.updateLocalDeviceName(e)}async startManagedSessionNative(e){let n=this.backend;if(typeof n.startManagedSessionNative!="function")throw new Error("Selected runtime adapter does not support startManagedSessionNative().");return n.startManagedSessionNative(e)}async notifyNetworkChange(e){return typeof this.backend.notifyNetworkChange!="function"?null:this.backend.notifyNetworkChange(e)}async getManagedNodeId(e){if(console.info("[DelegatingRuntimeAdapter][getManagedNodeId] enter",{hasMethod:typeof this.backend.getManagedNodeId=="function",backendCtor:this.backend.constructor?.name??null}),typeof this.backend.getManagedNodeId!="function")return null;let n=await this.backend.getManagedNodeId(e);return console.info("[DelegatingRuntimeAdapter][getManagedNodeId] resolved",{result:n}),n}async startPresenceLoopOnce(e,n,t,i,r){let o=this.backend;if(typeof o.startPresenceLoopOnce!="function")throw new Error("Selected runtime adapter does not support startPresenceLoopOnce().");return o.startPresenceLoopOnce(e,n,t,i,r)}async startAutoConnectOnce(e,n){let t=this.backend;if(typeof t.startAutoConnectOnce!="function")throw new Error("Selected runtime adapter does not support startAutoConnectOnce().");return t.startAutoConnectOnce(e,n)}async getEndpointTicket(){if(typeof this.backend.getEndpointTicket!="function")throw new Error("Selected runtime adapter does not support getEndpointTicket().");return this.backend.getEndpointTicket()}async getEndpointTicketWithToken(e,n){let t=this.backend;return typeof t.getEndpointTicketWithToken!="function"?null:t.getEndpointTicketWithToken(e,n)}async registerSessionToken(e,n,t){let i=this.backend;typeof i.registerSessionToken=="function"&&await i.registerSessionToken(e,n,t);}async revokeSessionTokensByScope(e){let n=this.backend;return typeof n.revokeSessionTokensByScope!="function"?[]:n.revokeSessionTokensByScope(e)}async openPeerBi(e,n){if(typeof this.backend.openPeerBi!="function")throw new Error("Selected runtime adapter does not support openPeerBi().");return this.backend.openPeerBi(e,n)}async incoming_streams(){let e=this.backend;if(typeof e.incoming_streams!="function")throw new Error("Selected runtime adapter does not support incoming_streams().");return e.incoming_streams()}async is_current_transport_stable_id(e,n){let t=this.backend;return typeof t.is_current_transport_stable_id!="function"?false:t.is_current_transport_stable_id(e,n)}async openPeerNativeBi(e,n,t){let i=this.backend;if(typeof i.openPeerNativeBi!="function")throw new Error("Selected runtime adapter does not support openPeerNativeBi().");return i.openPeerNativeBi(e,n,t)}async openPeerBiTransportOnly(e,n){let t=this.backend;return typeof t.openPeerBiTransportOnly=="function"?t.openPeerBiTransportOnly(e,n):this.openPeerBi(e,n)}async openPeerUni(e,n){if(typeof this.backend.openPeerUni!="function")throw new Error("Selected runtime adapter does not support openPeerUni().");return this.backend.openPeerUni(e,n)}async connectToDevice(e){if(typeof this.backend.connectToDevice!="function")throw new Error("Selected runtime adapter does not support connectToDevice().");return this.backend.connectToDevice(e)}async disconnectDevice(e){if(typeof this.backend.disconnectDevice!="function")throw new Error("Selected runtime adapter does not support disconnectDevice().");return this.backend.disconnectDevice(e)}async setAutoConnectExcluded(e,n){if(typeof this.backend.setAutoConnectExcluded!="function")throw new Error("Selected runtime adapter does not support setAutoConnectExcluded().");return this.backend.setAutoConnectExcluded(e,n)}async isConnected(e){return this.backend.isConnected(e)}async getConnectionStates(){return typeof this.backend.getConnectionStates!="function"?[]:this.backend.getConnectionStates()}onConnectionStateChange(e){return typeof this.backend.onConnectionStateChange!="function"?()=>{}:this.backend.onConnectionStateChange(e)}async sendExplicitFilePath(e,n,t){if(typeof this.backend.sendExplicitFilePath!="function")throw new Error("Selected runtime adapter does not support sendExplicitFilePath().");return this.backend.sendExplicitFilePath(e,n,t)}async sendExplicitFileData(e){if(typeof this.backend.sendExplicitFileData!="function")throw new Error("Selected runtime adapter does not support sendExplicitFileData().");return this.backend.sendExplicitFileData(e)}async getTransferHistory(e){return typeof this.backend.getTransferHistory!="function"?[]:this.backend.getTransferHistory(e)}async deleteTransferJob(e){if(typeof this.backend.deleteTransferJob=="function")return this.backend.deleteTransferJob(e)}getRuntimeCapabilities(){let e=this.backend;return typeof e.getRuntimeCapabilities=="function"?e.getRuntimeCapabilities():t()}async onIncomingNativeMessage(e){let n=this.backend;return typeof n.onIncomingNativeMessage!="function"?()=>{}:n.onIncomingNativeMessage(e)}unwrap(){return this.backend}setCoreClient(e){let n=this.backend;typeof n.setCoreClient=="function"&&n.setCoreClient(e);}};export{a};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import {a as a$1}from'./chunk-IAIGT5G3.js';import {a as a$2}from'./chunk-NCL672QJ.js';import {f}from'./chunk-A7AMB23L.js';import {c}from'./chunk-RD3JEGGF.js';var s=false;function a(){s||(s=true,a$2(async()=>{let t=await import('./openrtc-C53CKZUM.js');return {initWasm:t.default,WasmClient:t.WasmClient,start:t.start}}));}async function d(t){a();let e=c(t),{WasmBridge:i}=await import('./WasmBridge-B7NTRYN5.js');return a$1(e,new i(e))}function y(t,e){let i=c(t);return a$1(i,new f({...i,bridge:e}))}export{d as a,y as b};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import {b as b$1,a as a$2}from'./chunk-2QHDEGVX.js';import {a as a$1}from'./chunk-
|
|
1
|
+
import {b as b$1,a as a$2}from'./chunk-2QHDEGVX.js';import {a as a$1}from'./chunk-D45U2NXV.js';import {a as a$3}from'./chunk-EUNCYGJD.js';import {b}from'./chunk-N4SX7C3W.js';import {d}from'./chunk-K37WVIZL.js';import {a}from'./chunk-N26S7V4N.js';async function c(t){return a(b),b$1(await a$1(a$2(t)),"web")}c.native=function(t,a$1=d()){return a(b),b$1(a$3(a$2(t),a$1),"native")};export{c as a};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import {a}from'./chunk-IAIGT5G3.js';import {f}from'./chunk-A7AMB23L.js';import {c}from'./chunk-RD3JEGGF.js';function s(i,r){let t=c(i);return a(t,new f({...t,bridge:r}))}export{s as a};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import {t}from'./chunk-
|
|
1
|
+
import {t}from'./chunk-NCL672QJ.js';import {b}from'./chunk-N26S7V4N.js';function v(i,d){let t$1=new t(i,d),a=i.spaceKey??i.space,l=(i.discoveryMode===void 0||i.discoveryMode==="space")&&typeof i.apiKey=="string"&&i.apiKey.trim().length>0&&typeof a=="string"&&a.trim().length>0,s={runtime:t$1,async setAuthContext(e){await t$1.setAuthContext(e);},async syncPlutoAuth(e){if(l)return;let n=b(),c=n.getCurrentUser(),r=(typeof e?.userId=="string"?e.userId.trim():"")||c?.uid||null;if(!r){await s.setAuthContext(null);return}let h=await n.getIdToken({forceRefresh:e?.forceRefresh??false}).catch(()=>null),m=n.getCurrentUser()?.refreshToken??null,g=n.getCurrentUser()?.stsTokenManager?.expirationTime??null;await s.setAuthContext({userId:r,token:h,refreshToken:m,tokenProvider:async y=>n.getIdToken({forceRefresh:y??false}),expiresAtMs:g});},bindPlutoAuthHost(){let e=b();return s.syncPlutoAuth({userId:e.getCurrentUser()?.uid??null,forceRefresh:false}),e.onIdTokenChanged(n=>{s.syncPlutoAuth({userId:n?.uid??null,forceRefresh:false});})},signInWithPluto:()=>t$1.signInWithPluto(),signOut:()=>t$1.signOut(),stopManagedSession:()=>t$1.stopManagedSession(),startManagedSession:e=>t$1.startManagedSession(e),onAuthChange:e=>t$1.onIdentityChange(e),getManagedNodeId:e=>t$1.getManagedNodeId(e),getRuntimeStatus:()=>t$1.getRuntimeStatus(),listDevicesWithStatus:()=>t$1.listDevicesWithStatus(),watchDevicesWithStatus:e=>t$1.watchDevicesWithStatus(e),connectDevice:(e,n)=>t$1.connectDevice(e,n),setAutoConnectExcluded:(e,n)=>t$1.setAutoConnectExcluded(e,n)};return Object.defineProperty(s,"identity",{get:()=>t$1.identity,enumerable:true}),s}export{v as a};
|