openrtc 2.5.2 → 2.5.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (59) hide show
  1. package/dist/{Connection-CTpuImO-.d.ts → Connection-CovQdc8E.d.ts} +30 -5
  2. package/dist/{DelegatingRuntimeAdapter-D67Ozqo3.d.ts → DelegatingRuntimeAdapter-3ykiNvyh.d.ts} +3 -2
  3. package/dist/{IpcRuntimeAdapter-Ddx0MtSI.d.ts → IpcRuntimeAdapter-BkM_1HyL.d.ts} +12 -2
  4. package/dist/WasmBridge-UZC7G4NP.js +1 -0
  5. package/dist/{assembly-LOFcpH3S.d.ts → assembly-C235UKSS.d.ts} +3 -2
  6. package/dist/{capabilities-CmzzxSvW.d.ts → capabilities-CdZpAKvE.d.ts} +1 -1
  7. package/dist/chunk-25CN4MLA.js +2 -0
  8. package/dist/chunk-2ESWBXLF.js +1 -0
  9. package/dist/{chunk-TZLNKQNJ.js → chunk-42TNJH5S.js} +1 -1
  10. package/dist/chunk-4CC6YIGG.js +1 -0
  11. package/dist/chunk-4J4F32QT.js +1 -0
  12. package/dist/{chunk-J7NBMQQA.js → chunk-CHT46RA7.js} +1 -1
  13. package/dist/chunk-VC7TGJFS.js +2 -0
  14. package/dist/{chunk-EFTDXE6M.js → chunk-WMA4OMJL.js} +1 -1
  15. package/dist/{chunk-XTYALGJN.js → chunk-XMYBBLYK.js} +1 -1
  16. package/dist/coreClient.d.ts +3 -3
  17. package/dist/coreClient.js +1 -1
  18. package/dist/index.d.ts +5 -5
  19. package/dist/index.js +1 -1
  20. package/dist/ipcFactory-2WMR4PH6.js +1 -0
  21. package/dist/native.d.ts +5 -5
  22. package/dist/native.js +1 -1
  23. package/dist/node.d.ts +5 -5
  24. package/dist/node.js +2 -2
  25. package/dist/{openrtc-SQF7H4ZE.js → openrtc-UBIKDAZ5.js} +2 -2
  26. package/dist/openrtc_bg.wasm +0 -0
  27. package/dist/{room-A2FMQRNZ.js → room-2MUFAJ4M.js} +1 -1
  28. package/dist/runtime/WasmRuntimeAdapter.d.ts +3 -3
  29. package/dist/runtime/WasmRuntimeAdapter.js +1 -1
  30. package/dist/runtime/device-status.d.ts +1 -1
  31. package/dist/runtime/factories.d.ts +6 -5
  32. package/dist/runtime/factories.js +1 -1
  33. package/dist/runtime/index.d.ts +9 -9
  34. package/dist/runtime/index.js +1 -1
  35. package/dist/server-browser.d.ts +4 -4
  36. package/dist/server.d.ts +4 -4
  37. package/dist/server.js +1 -1
  38. package/dist/service-node.d.ts +4 -4
  39. package/dist/service-node.js +1 -1
  40. package/dist/testing/native.d.ts +4 -4
  41. package/dist/testing/native.js +1 -1
  42. package/dist/testing.d.ts +4 -4
  43. package/dist/testing.js +1 -1
  44. package/dist/transport/index.d.ts +2 -2
  45. package/dist/{types-Cyc-mPjk.d.ts → types-C6SMXBzJ.d.ts} +1 -1
  46. package/native/darwin-arm64/openrtc-node-host +0 -0
  47. package/native/darwin-arm64/openrtc-node-host.manifest.json +4 -4
  48. package/native/darwin-x64/openrtc-node-host +0 -0
  49. package/native/darwin-x64/openrtc-node-host.manifest.json +4 -4
  50. package/native/linux-x64/openrtc-node-host +0 -0
  51. package/native/linux-x64/openrtc-node-host.manifest.json +4 -4
  52. package/package.json +1 -1
  53. package/dist/WasmBridge-LWMCETW4.js +0 -1
  54. package/dist/chunk-6Q2LAXM4.js +0 -1
  55. package/dist/chunk-AAZPQQXX.js +0 -2
  56. package/dist/chunk-FB5M6GIW.js +0 -2
  57. package/dist/chunk-PLIWPC45.js +0 -1
  58. package/dist/chunk-VTYVIKTM.js +0 -1
  59. package/dist/ipcFactory-PDVLUG2W.js +0 -1
@@ -1 +0,0 @@
1
- import {a as a$1}from'./chunk-AYHD4X2R.js';import {o,b,a,t,m,g,x,y,h,z,B,C,F,G,H,d as d$1,e as e$1}from'./chunk-AAZPQQXX.js';import {c,e,d,f,b as b$1}from'./chunk-XTYALGJN.js';import {a as a$2}from'./chunk-OT7IPLZE.js';import {c as c$1}from'./chunk-CCCYE3XN.js';import {a as a$3}from'./chunk-JPBW67B3.js';function A(l){if(!l)return null;let e=2166136261;for(let t=0;t<l.length;t+=1)e^=l.charCodeAt(t),e=Math.imul(e,16777619);return `fp-${(e>>>0).toString(16).padStart(8,"0")}`}var M=class M{constructor(e){this.deps=e;this.startedAutoConnectKey=null;this.browserAutoConnectUnsubscribe=null;this.desiredPeerRevision=0;this.desiredPeerSignature=null;this.desiredPeerSubmission=null;this.desiredPeerSubmissionQueue=Promise.resolve();this.queuedDesiredPeers=null;this.desiredPeersByDeviceId=new Map;this.wakeSubmission=null;this.presenceState=null;this.presenceStartGeneration=0;this.localExcludedPeers=new Set;this.localDesiredPeerDeviceId=null;for(let t of e.initialExcludedPeers??[]){let i=t.trim().toLowerCase();i&&this.localExcludedPeers.add(i);}}stop(){this.stopAutoConnect(),this.stopPresenceLoop();}get autoConnectKey(){return this.startedAutoConnectKey}set autoConnectKey(e){this.startedAutoConnectKey=e;}get presenceLoopState(){return this.presenceState}set presenceLoopState(e){this.presenceState=e;}stopPresence(){this.stopPresenceLoop();}updatePresenceLoopState(e){this.presenceState=e;}startAutoConnect(e,t){if(this.deps.isTicketOnlyMode())return;let i=t.trim()||this.deps.resolveWebLogicalDeviceId(),n=`${e}::${i}`;this.startedAutoConnectKey===n&&this.browserAutoConnectUnsubscribe||(this.stopAutoConnect(),this.localDesiredPeerDeviceId=i,this.startedAutoConnectKey=n,this.browserAutoConnectUnsubscribe=this.deps.getCoordinationSignaling().onDevicesChange(r=>this.submitDesiredPeers(r),this.currentLocalNodeId()??void 0));}wakeRustAutoConnectOwner(){return this.deps.isTicketOnlyMode()||!this.startedAutoConnectKey||this.wakeSubmission?false:(this.wakeSubmission=this.deps.waitForWasmClient(500).then(async e=>{e&&typeof e.wake_browser_auto_connect=="function"&&await e.wake_browser_auto_connect();}).finally(()=>{this.wakeSubmission=null;}),true)}submitDesiredPeers(e){if(!this.startedAutoConnectKey)return;let i=this.normalizeDesiredPeers(e);this.rememberDesiredPeers(i)&&(this.queuedDesiredPeers=i,this.flushDesiredPeerSubmission());}observeDesiredPeerProjection(e){this.rememberDesiredPeers(this.normalizeDesiredPeers(e));}async submitDesiredPeerProjection(e,t){if(!Number.isSafeInteger(e)||e<=0)throw new Error("Desired-peer projection revision must be a positive safe integer.");let i=this.startedAutoConnectKey;if(!i)throw new Error("Cannot submit a desired-peer projection before managed auto-connect starts.");let n=this.normalizeDesiredPeers(t);this.rememberDesiredPeers(n),this.queuedDesiredPeers=null,this.desiredPeerRevision=Math.max(this.desiredPeerRevision,e),await this.enqueueDesiredPeerSubmission(i,e,n);}async handleRoomArchitectureChange(){let e=this.startedAutoConnectKey;if(this.deps.isTicketOnlyMode()||!e)return false;let t=Array.from(this.desiredPeersByDeviceId.values());this.queuedDesiredPeers=null;let i=++this.desiredPeerRevision;return await this.enqueueDesiredPeerSubmission(e,i,t),true}rememberDesiredPeers(e){this.desiredPeersByDeviceId=new Map(e.map(i=>[i.deviceId,i]));let t=JSON.stringify(e);return t===this.desiredPeerSignature?false:(this.desiredPeerSignature=t,this.deps.onDesiredPeersChanged?.(),true)}resolveDesiredPeer(e,t){let i=typeof e=="string"?e.trim():"",n=typeof t=="string"?t.trim():"";if(i){let r=this.desiredPeersByDeviceId.get(i);if(r&&(!n||!r.nodeId||r.nodeId===n))return r}return n?Array.from(this.desiredPeersByDeviceId.values()).find(r=>r.nodeId===n)??null:null}flushDesiredPeerSubmission(){if(this.desiredPeerSubmission||!this.queuedDesiredPeers||!this.startedAutoConnectKey)return;let e=this.startedAutoConnectKey,t=this.queuedDesiredPeers,i=++this.desiredPeerRevision;this.queuedDesiredPeers=null,this.desiredPeerSubmission=this.enqueueDesiredPeerSubmission(e,i,t).catch(()=>{}).finally(()=>{this.desiredPeerSubmission=null,this.flushDesiredPeerSubmission();});}normalizeDesiredPeers(e){return (Array.isArray(e)?e:[]).map(t=>({deviceId:String(t?.deviceId??"").trim(),nodeId:typeof t?.nodeId=="string"&&t.nodeId.trim()||null,ticket:typeof t?.ticket=="string"&&t.ticket.trim()||null,online:t?.online===true,sessionId:typeof t?.sessionId=="string"&&t.sessionId.trim()||null,excludedPeers:Array.isArray(t?.excludedPeers)?[...new Set(t.excludedPeers.map(i=>String(i??"").trim().toLowerCase()).filter(Boolean))].sort():[],devicePublicKeyJwk:t?.devicePublicKeyJwk,topologyRole:t?.topologyRole,topologyRevision:t?.topologyRevision})).filter(t=>t.deviceId.length>0).sort((t,i)=>t.deviceId.localeCompare(i.deviceId))}enqueueDesiredPeerSubmission(e,t,i,n=this.roomGossipFanoutEnabled()){let r=this.desiredPeerSubmissionQueue.then(async()=>{if(this.startedAutoConnectKey!==e)return;let o=await this.deps.waitForWasmClient();if(this.startedAutoConnectKey===e){if(!o||typeof o.submit_browser_desired_peers!="function"){this.deps.warnMissingWasmOnce("submitBrowserDesiredPeers");return}if(await Promise.all(i.map(async s=>{if(s.ticket)try{await this.deps.rememberRouteRepairTokenFromTicket(s.ticket);}catch(a){console.warn("[WasmSignaling] failed to retain desired-peer admission token",{deviceId:s.deviceId,nodeId:s.nodeId,error:a});}})),n){if(typeof o.submit_browser_desired_peers_with_sparse_fanout!="function"){await o.submit_browser_desired_peers(t,JSON.stringify([])),this.deps.warnMissingWasmOnce("submitBrowserDesiredPeersWithSparseFanout");return}if(!this.deps.capabilityKey)throw new Error("Sparse fanout requires an explicit capability avenue.");await o.submit_browser_desired_peers_with_sparse_fanout(t,JSON.stringify(i),this.deps.capabilityKey,this.localDesiredPeerDeviceId,this.deps.localDeviceKeyX,true);}else await o.submit_browser_desired_peers(t,JSON.stringify(i));}});return this.desiredPeerSubmissionQueue=r.catch(o=>{console.warn("[WasmSignaling] failed to submit browser desired peers to Rust",{revision:t,error:o});}),r}roomGossipFanoutEnabled(){return typeof this.deps.roomGossipFanout=="function"?this.deps.roomGossipFanout():this.deps.roomGossipFanout===true}async excludeAutoConnect(e,t){let i=await this.deps.waitForWasmClient();i&&typeof i.set_auto_connect_excluded=="function"&&await i.set_auto_connect_excluded(e,t),await this.recordAutoConnectExcludedForPresence(e,t);}async installInitialAutoConnectExclusions(e){if(typeof e?.set_auto_connect_excluded=="function")for(let t of this.currentExcludedPeersSnapshot())await e.set_auto_connect_excluded(t,true);}async recordAutoConnectExcludedForPresence(e,t){let i=e.trim().toLowerCase();if(!i)return;t?this.localExcludedPeers.add(i):this.localExcludedPeers.delete(i);let n=this.deps.resolveWebLogicalDeviceId();n&&await this.deps.updateExcludedPeers(n,this.currentExcludedPeersSnapshot());}async startPresenceLoop(e,t,i,n,r){if(this.deps.isTicketOnlyMode())return;this.stopPresenceLoop();let o=this.presenceStartGeneration;this.presenceState={userId:e,localNodeId:t,ticket:n,metadata:r,deviceName:i};let s=this.deps.resolveWebLogicalDeviceId(),a=await this.deps.withWebPresenceMetadata(r,s);o!==this.presenceStartGeneration||this.presenceState===null||await this.deps.updatePresence(t,n,true,M.PRESENCE_LEASE_MS,a,i);}stopAutoConnect(){this.browserAutoConnectUnsubscribe?.(),this.browserAutoConnectUnsubscribe=null,this.startedAutoConnectKey=null,this.localDesiredPeerDeviceId=null,this.desiredPeerSignature=null,this.queuedDesiredPeers=null,this.desiredPeersByDeviceId.clear(),this.wakeSubmission=null;}currentExcludedPeersSnapshot(){return Array.from(this.localExcludedPeers).sort()}currentLocalNodeId(){let e=this.presenceState?.localNodeId;return typeof e=="string"&&e.trim()||null}stopPresenceLoop(){this.presenceStartGeneration+=1,this.presenceState=null;}};M.PRESENCE_LEASE_MS=15*6e4;var R=M;function ie(){if(!(typeof window>"u"))try{if(new URL(import.meta.url).pathname.includes("/node_modules/.vite/deps/"))return new URL("/node_modules/openrtc/dist/openrtc_bg.wasm",window.location.origin)}catch{}}async function ne(){let l=await import('./openrtc-SQF7H4ZE.js');return {initWasm:e=>l.default(e??ie()),WasmClient:l.WasmClient,start:l.start}}function re(l){try{let e=l.replace(/-/g,"+").replace(/_/g,"/"),t=(4-e.length%4)%4,i=e+"=".repeat(t);if(typeof atob=="function")return JSON.parse(atob(i));let n=globalThis.Buffer;if(n)return JSON.parse(n.from(i,"base64").toString("utf8"))}catch{return null}return null}function oe(l){let e=typeof l=="string"?l.trim():"";if(!e)return {present:false};let t=e.lastIndexOf("."),i=t>=0?e.slice(0,t):e,n=t>=0?e.slice(t+1):null,r=n?re(n):null,o=r&&typeof r.t=="string"&&r.t.trim().length>0?r.t.trim():null,s=r&&typeof r.s=="string"&&r.s.trim().length>0?r.s.trim():null,a=r&&typeof r.m=="number"&&Number.isFinite(r.m)?r.m:null;return {present:true,irohFingerprint:A(i),tokenFingerprint:A(o),tokenSuffixFingerprint:A(n),scope:s,maxConnections:a}}function _(l,e,t={}){let i=typeof l.finishSend=="function"?l.finishSend.bind(l):typeof l.finish_send=="function"?l.finish_send.bind(l):null,n=typeof l.cancelSend=="function"?l.cancelSend.bind(l):typeof l.cancel_send=="function"?l.cancel_send.bind(l):null;if(!i){if(t.requireFinish===true)throw new Error("WASM peer stream is missing finishSend(); rebuild the current OpenRTC WASM before sending application data");return e}let r=e.getWriter(),o=new WritableStream({write:s=>r.write(s),async close(){await r.close(),await i();},async abort(s){await n?.(),await r.abort(s);}});return a$3(o,n)}var u=class u{constructor(e$1){this.spaceNamespaceIdPromise=null;this.cachedSpaceNamespaceId=null;this.authListeners=[];this.wasmClient=null;this.createdAtMs=Date.now();this.missingWasmWarnings=new Set;this.wasmReadyWarningDelayMs=15e3;this.browserCoordinationSignaling=null;this.effectiveRoomArchitecture="mesh";this.lastObservedFirebaseUserId=null;this.sessionReaders=new Set;this.authContext=null;this.injectedBrowserAuthSessionActive=false;this.hasSyncedAuthToWasmClient=false;this.lastWasmAuthUserId=null;this.lastWasmAuthToken=null;this.lastDeliveredConnectionStates=new Map;this.authScopedRuntimeGeneration=0;this.coreClient=null;this.applicationRouteEscalations=new Map;this.applicationRouteEscalationAttemptKeys=new Map;this.applicationRouteEscalationUnsubscribe=null;this.routeSubscriptionGeneration=-1;this.applicationRouteEscalationSubscriptionEpoch=0;this.appTag=c(e$1),this.options={...e$1,appTag:this.appTag,authMode:d(e$1),projectId:e(e$1)},this.effectiveRoomArchitecture=e$1.coordinationRoomArchitecture==="sparse"||e$1.coordinationRoomGossipFanout===true?"sparse":"mesh",this.coordinationHost=new b({appTag:this.appTag,projectId:this.options.projectId,discoveryMode:this.options.discoveryMode,signalingMode:this.options.signalingMode,gateway:this.options.coordinationGateway,avenueOverride:this.options.coordinationAvenueOverride,roomArchitecture:this.options.coordinationRoomArchitecture,initialExcludedPeers:this.options.initialAutoConnectExcludedDeviceIds,resolveSpaceNamespaceId:()=>this.ensureSpaceNamespaceIdPromise(),getCurrentUserId:()=>this.getCurrentUserId(),getAuthToken:async(o=false)=>this.currentUser?.getToken?.(o)??null,getAppCheckToken:async(o=false)=>{let s=this.authContext?.appCheckTokenProvider??this.options.attestationTokenProvider;return s?s(o):a().getAppCheckToken(o)},getLocalDeviceId:()=>this.resolveWebLogicalDeviceId(),getDefaultDeviceName:()=>this.getDefaultBrowserDeviceName(),getPlatformType:()=>this.options.coordinationPlatformType??"web",normalizeDevice:(o,s)=>this.normalizeDevice(o,s)});let n=this.options.coordinationRoomGossipFanout===true||this.options.coordinationRoomArchitecture==="auto"||this.options.coordinationRoomArchitecture==="sparse"?c$1(this.options.coordinationAvenueOverride).key:void 0;if(this.presenceManager=new R({isTicketOnlyMode:()=>this.isTicketOnlyMode(),waitForWasmClient:(o,s)=>this.waitForWasmClient(o,s),warnMissingWasmOnce:o=>this.warnMissingWasmOnce(o),resolveWebLogicalDeviceId:()=>this.resolveWebLogicalDeviceId(),withWebPresenceMetadata:(o,s)=>this.withWebPresenceMetadata(o,s),updatePresence:(o,s,a,c,d,p)=>this.updatePresence(o,s,a,c,d,p),updateExcludedPeers:(o,s)=>this.getCoordinationSignaling().updateDevice(o,{excludedPeers:s}),getCoordinationSignaling:()=>this.getCoordinationSignaling(),rememberRouteRepairTokenFromTicket:o=>this.coreClient?.rememberRouteRepairTokenFromTicket?.(o)??Promise.resolve(false),onDesiredPeersChanged:()=>this.retryManagedApplicationRouteEscalations(),roomGossipFanout:()=>this.effectiveRoomArchitecture==="sparse",capabilityKey:n,localDeviceKeyX:this.options.coordinationDevicePublicKeyX,initialExcludedPeers:this.options.initialAutoConnectExcludedDeviceIds}),this.persistenceReady=Promise.resolve(),this.isTicketOnlyMode()||this.usesProviderNeutralGrant()){this.app=null,this.auth=null;return}let r=a();this.app=r.getApp(),this.auth=r.getAuth(),r.onAuthStateChanged(o=>{if(this.authContext)return;if(this.isSpaceMode()){this.authListeners.forEach(c=>c(this.toRuntimeIdentity(o)));return}let s=o?.uid??null,a=this.lastObservedFirebaseUserId;this.lastObservedFirebaseUserId=s,a&&a!==s&&this.stopAuthActivity({userId:a}),this.browserCoordinationSignaling?.handleScopeChange()??this.coordinationHost.handleScopeChange(),this.authListeners.forEach(c=>c(this.toRuntimeIdentity(o)));});}async loadBrowserWasmRuntime(){return ne()}get tag(){return this.appTag}capabilities(){return t()}getDeviceIdentityStorageKey(){let e=f(this.options);return `${u.WEB_DEVICE_ID_STORAGE_PREFIX}_${e}`}getDeviceIdPersistenceMode(){return this.options.deviceIdPersistence??this.options.nodeIdPersistence??"persistent"}isTicketOnlyMode(){return this.options.signalingMode==="ticket-only"}usesProviderNeutralGrant(){return typeof this.options.coordinationGateway?.grantProvider=="function"}createRandomDeviceId(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`web-${Date.now()}-${Math.random().toString(36).slice(2,10)}`}resolveWebLogicalDeviceId(){let e=this.options.localDeviceId?.trim();if(e)return e;let t=this.getDeviceIdPersistenceMode();if(typeof localStorage>"u")return this.createRandomDeviceId();let i=this.getDeviceIdentityStorageKey(),n=Date.now(),r=null;try{let d=localStorage.getItem(i);r=d?JSON.parse(d):null;}catch{r=null;}let o=typeof r?.deviceId=="string"?r.deviceId.trim():"",s=typeof r?.expiresAt=="number"?r.expiresAt:void 0;if(t==="persistent"){let d=o||this.createRandomDeviceId();return localStorage.setItem(i,JSON.stringify({deviceId:d})),d}if(o&&typeof s=="number"&&s>n){let d=n+u.EPHEMERAL_DEVICE_ID_TTL_MS;return localStorage.setItem(i,JSON.stringify({deviceId:o,expiresAt:d})),o}let a=this.createRandomDeviceId(),c=n+u.EPHEMERAL_DEVICE_ID_TTL_MS;return localStorage.setItem(i,JSON.stringify({deviceId:a,expiresAt:c})),a}getDefaultBrowserDeviceName(){return this.options.deviceName?.trim()||(this.options.storagePrefix?`Web (${this.options.storagePrefix.replace(/_$/,"")})`:"Web Browser")}async getLocalDeviceInfo(){return {deviceId:this.resolveWebLogicalDeviceId(),deviceName:this.getDefaultBrowserDeviceName(),platformType:this.options.coordinationPlatformType??"web"}}getCoordinationSignaling(){return this.browserCoordinationSignaling??this.coordinationHost.getSignaling()}usesCoordinationGateway(){return this.coordinationHost.usesGateway()}setCoordinationHostAvailability(e){this.coordinationHost.setHostAvailability(e),this.browserCoordinationSignaling?.setHostAvailability?.(e);}async reconnectCoordinationAfterHostResume(){let e=this.browserCoordinationSignaling;if(e?.reconnectAfterHostResume){await e.reconnectAfterHostResume();return}await this.coordinationHost?.reconnectAfterHostResume();}async getCoordinationNativeTrustToken(e=false){return this.coordinationHost.getNativeTrustToken(e)}invalidateCoordinationNativeTrustToken(){this.coordinationHost.invalidateNativeTrustToken();}subscribeCoordinationNativeTrustToken(e,t){return this.coordinationHost.subscribeNativeTrustToken(e,t)}setCoordinationLocalDeviceId(e){if(!this.options.coordinationGateway)return;let t=e.trim();t&&(this.options.localDeviceId=t);}setCoordinationPlatformType(e){this.options.coordinationGateway&&(this.options.coordinationPlatformType=e);}async setCoordinationExcludedPeers(e){let t=this.resolveWebLogicalDeviceId();if(!t)throw new Error("The local device must be known before publishing peer exclusions.");await this.getCoordinationSignaling().updateDevice(t,{excludedPeers:e});}async joinCoordinationRoom(e,t,i){let n=this.getCoordinationSignaling();if(!n.joinCoordinationRoom)throw new Error("The active coordination provider does not support rooms.");await n.joinCoordinationRoom(e,t,i);}async leaveCoordinationRoom(e){await this.getCoordinationSignaling().leaveCoordinationRoom?.(e);}async getCoordinationRoomMembers(e){let t=this.getCoordinationSignaling();if(!t.getCoordinationRoomMembers)throw new Error("The active coordination provider does not support rooms.");return t.getCoordinationRoomMembers(e)}watchCoordinationRoomMembers(e,t){let i=this.getCoordinationSignaling();if(!i.watchCoordinationRoomMembers)throw new Error("The active coordination provider does not support rooms.");return i.watchCoordinationRoomMembers(e,t)}async withWebPresenceMetadata(e,t){let i;if(!e||!e.trim())i=JSON.stringify({deviceId:t});else {try{let n=JSON.parse(e);if(n&&typeof n=="object"&&!Array.isArray(n))return i=JSON.stringify({...n,deviceId:t}),await m(i)??i}catch{}i=JSON.stringify({deviceId:t,metadata:e});}return await m(i)??i}async setAuthContext(e){let t=this.injectedBrowserAuthSessionActive,i=this.authContext?.userId??null,n=e?.userId??null;if(this.authContext=e,!this.isTicketOnlyMode()&&!this.usesProviderNeutralGrant()&&e?.customToken?.trim()&&!(g()&&this.options.authMode==="external"&&typeof e.tokenProvider=="function"))try{await this.ensureBrowserPlatformAuth(e.userId,e.customToken.trim());}catch(r){console.warn("[WasmBridge] ensureBrowserPlatformAuth failed (non-fatal):",r);}else if(!this.isTicketOnlyMode()&&!this.usesProviderNeutralGrant()&&!e&&t)try{await this.auth?.signOut();}catch(r){console.warn("[WasmBridge] Failed to clear injected browser auth session:",r);}finally{this.injectedBrowserAuthSessionActive=false;}this.syncWasmAuthToken(),!this.isTicketOnlyMode()&&i!==n&&await(this.browserCoordinationSignaling?.handleScopeChange()??this.coordinationHost.handleScopeChange()),this.authListeners.forEach(r=>r(this.currentUser));}async ensureBrowserPlatformAuth(e,t){if((this.auth?.currentUser?.uid??null)===e){this.injectedBrowserAuthSessionActive=true;return}await a().signInWithCustomTokenValue(t),this.injectedBrowserAuthSessionActive=true;}syncWasmAuthToken(){let e=this.wasmClient?.setIdentityCredential??this.wasmClient?.set_auth_token;if(!this.wasmClient||typeof e!="function"||!this.authContext&&this.isSpaceMode())return;let t=this.authContext?.userId??null,i=this.authContext?.token,n=typeof i=="string"&&i.trim().length>0?i:null;if(!(this.hasSyncedAuthToWasmClient&&this.lastWasmAuthUserId===t&&this.lastWasmAuthToken===n)){if(this.lastWasmAuthUserId=t,this.lastWasmAuthToken=n,this.hasSyncedAuthToWasmClient=true,n===null&&typeof this.wasmClient.clearIdentityCredential=="function"){this.wasmClient.clearIdentityCredential();return}e.call(this.wasmClient,n);}}toRuntimeIdentity(e){return e?{id:e.uid,email:e.email,displayName:e.displayName,isAnonymous:e.isAnonymous,getToken:async(t=false)=>{try{return await e.getIdToken(t)}catch{return null}}}:null}getCurrentUserId(){return this.authContext?.userId?this.authContext.userId:this.isTicketOnlyMode()?null:this.auth?.currentUser?.uid??null}getCurrentUserIdForScope(){return this.getCurrentUserId()}getAuthContext(){return this.authContext}isSpaceMode(){return x(this.options)}getResolvedOptions(){return this.options}getDiscoveryScopeId(){if(this.isTicketOnlyMode())return null;let e=this.getCurrentUserId();return e||(this.isSpaceMode()?this.resolveWebLogicalDeviceId():null)}matchesTag(e){return y(e,this.appTag,this.isSpaceMode())}matchesLegacyOrCurrentTag(e){return this.matchesTag(e)}async stopSessionSubscriptions(){let e=Array.from(this.sessionReaders);this.sessionReaders.clear(),await Promise.allSettled(e.map(async t=>{try{await t.cancel();}catch{}}));}async stopRuntimeAuthScopedLoops(){let e=await this.waitForWasmClient(250);if(e)try{typeof e.stop_auth_scoped_activity=="function"?await e.stop_auth_scoped_activity():(typeof e.stop_presence_loop=="function"&&await e.stop_presence_loop(),typeof e.stop_auto_connect=="function"&&await e.stop_auto_connect());}catch(t){console.warn("[WasmSignaling] Failed to stop auth-scoped runtime loops:",t);}}async stopAuthActivity(e){h("WasmBridge.stopAuthActivity",{userId:e?.userId??null}),this.authScopedRuntimeGeneration+=1,this.stopApplicationRouteEscalationSubscription();let t=await this.waitForWasmClient(500);if(t&&typeof t.revoke_tokens_by_scope=="function")try{await t.revoke_tokens_by_scope("user-device");}catch(i){console.warn("[WasmBridge] user-device revoke during auth-scoped shutdown failed:",i);}this.presenceManager.stop(),this.browserCoordinationSignaling?.stopAuthActivity(),this.coordinationHost?.stopAuthActivity(),await this.stopSessionSubscriptions(),this.lastDeliveredConnectionStates.clear(),this.applicationRouteEscalations?.clear(),this.applicationRouteEscalationAttemptKeys?.clear(),await this.stopRuntimeAuthScopedLoops();}setWasmClient(e){this.wasmClient=e,this.coordinationHost.setWasmClient(e),this.lastWasmAuthUserId=null,this.lastWasmAuthToken=null,this.hasSyncedAuthToWasmClient=this.authContext===null,this.lastDeliveredConnectionStates.clear(),this.applicationRouteEscalations?.clear(),this.applicationRouteEscalationAttemptKeys?.clear(),this.syncWasmAuthToken();}async createBroadcastPublisher(){let e=await this.waitForWasmClient();if(!e)throw new Error("WASM broadcast publisher runtime is unavailable");return a$1.create(e)}async initializePersistentIrohProtocols(e){let t=await this.waitForWasmClient(),i=t?.__initPersistentIrohProtocols;if(typeof i!="function")throw new Error("This OpenRTC WASM host was built without persistent Iroh protocols");await i.call(t,e);}async createPersistentIrohNamespace(e,t){return (await this.requirePersistentProtocolHost()).__createPersistentIrohNamespace(BigInt(e),BigInt(t))}async importPersistentIrohTicket(e,t,i){return (await this.requirePersistentProtocolHost()).__importPersistentIrohTicket(e,BigInt(t),BigInt(i))}async sharePersistentIrohNamespace(e,t){return (await this.requirePersistentProtocolHost()).__sharePersistentIrohNamespace(e,t)}async removePersistentIrohNamespace(e,t,i){await(await this.requirePersistentProtocolHost()).__removePersistentIrohNamespace(e,BigInt(t),BigInt(i));}async putPersistentIrohBytes(e,t,i){return (await this.requirePersistentProtocolHost()).__putPersistentIrohBytes(e,t,i)}async setPersistentIrohHash(e,t,i,n){return (await this.requirePersistentProtocolHost()).__setPersistentIrohHash(e,t,i,BigInt(n))}async deletePersistentIrohPrefix(e,t){return (await this.requirePersistentProtocolHost()).__deletePersistentIrohPrefix(e,t)}async queryPersistentIrohNamespace(e,t){return (await this.requirePersistentProtocolHost()).__queryPersistentIrohNamespace(e,t)}async hydratePersistentIrohBlob(e){await(await this.requirePersistentProtocolHost()).__hydratePersistentIrohBlob(e);}async acknowledgePersistentIrohOutbox(e){await(await this.requirePersistentProtocolHost()).__acknowledgePersistentIrohOutbox(e);}async flushPersistentIrohProtocols(){await(await this.waitForWasmClient(500))?.__flushPersistentIrohProtocols?.();}async shutdownPersistentIrohProtocols(){await(await this.waitForWasmClient(500))?.__shutdownPersistentIrohProtocols?.();}async requirePersistentProtocolHost(){let e=await this.waitForWasmClient();if(!e||typeof e.__queryPersistentIrohNamespace!="function")throw new Error("This OpenRTC WASM host was built without persistent Iroh protocols");return e}warnMissingWasmOnce(e){!this.wasmClient&&Date.now()-this.createdAtMs<this.wasmReadyWarningDelayMs||this.missingWasmWarnings.has(e)||(this.missingWasmWarnings.add(e),console.warn(`[WasmSignaling] ${e} skipped: wasm client is not ready.`));}async waitForWasmClient(e=4e3,t=50){if(this.wasmClient)return this.wasmClient;let i=Date.now();for(;!this.wasmClient&&Date.now()-i<e;)await a$2(t);return this.wasmClient??null}normalizeDevice(e,t){return z(e,t)}normalizeDeviceRecord(e,t){return this.normalizeDevice(e,t)}getResolvedWebLogicalDeviceId(){return this.resolveWebLogicalDeviceId()}async encodeSparseFanoutMessage(e,t){let i=await this.waitForWasmClient(),n=this.options.coordinationDeviceSign;if(!i?.prepareSparseFanoutMessage||!i?.finalizeSparseFanoutMessage||!n)throw new Error("[OpenRTC] Browser sparse fanout signer is unavailable.");let r=await i.prepareSparseFanoutMessage(e,t),o=new Uint8Array(r.signingInput??r.signing_input??[]),s=await n(o);return new Uint8Array(await i.finalizeSparseFanoutMessage(String(r.requestId??r.request_id??""),s))}async acceptSparseFanoutMessage(e,t,i){let n=await this.waitForWasmClient();if(!n?.acceptSparseFanoutMessage)throw new Error("[OpenRTC] Browser sparse fanout verifier is unavailable.");let r=await n.acceptSparseFanoutMessage(e,t,i);return {payload:new Uint8Array(r.payload??[]),authorDeviceId:String(r.authorDeviceId??r.author_device_id??""),authorPeerId:String(r.authorPeerId??r.author_peer_id??""),topologyRevision:Number(r.topologyRevision??r.topology_revision),hop:Number(r.hop),forwardPeerIds:Array.isArray(r.forwardPeerIds??r.forward_peer_ids)?(r.forwardPeerIds??r.forward_peer_ids).map(String):[],forwardPeerLimit:Number(r.forwardPeerLimit??r.forward_peer_limit),forwardQueueCapacity:Number(r.forwardQueueCapacity??r.forward_queue_capacity),...r.forward==null?{}:{forward:new Uint8Array(r.forward)}}}async recordSparseFanoutForwardQueueDrop(e,t){let i=await this.waitForWasmClient();i?.recordSparseFanoutForwardQueueDrop&&await i.recordSparseFanoutForwardQueueDrop(e,t);}normalizeDeviceStatusSnapshot(e){return B(e)}normalizePeerSessionSnapshot(e){return C(e)}toBackendConnectionStateFromPeerSession(e){return F(e)}normalizeStateSnapshot(e){return G(e)}stabilizeConnectionState(e){let t=this.lastDeliveredConnectionStates.get(e.connectionId);return {...e,deviceId:e.deviceId??t?.deviceId??null,deviceIdHint:e.deviceIdHint??t?.deviceIdHint??null,remoteNodeId:e.remoteNodeId??t?.remoteNodeId??null,createdAt:e.createdAt??t?.createdAt,updatedAt:e.updatedAt??t?.updatedAt}}sameConnectionState(e,t){return H(e,t)}deliverConnectionState(e,t,i,n){let r=this.stabilizeConnectionState(e);this.lastDeliveredConnectionStates.set(r.connectionId,r);let s=(n??this.lastDeliveredConnectionStates).get(r.connectionId);this.sameConnectionState(s,r)||(n&&n.set(r.connectionId,r),t(r));}get browserPresenceLoopState(){return this.presenceManager.presenceLoopState}set browserPresenceLoopState(e){this.presenceManager.presenceLoopState=e;}get currentUser(){if(this.authContext?.userId){let e=this.authContext.token??null,t=this.authContext.tokenProvider;return {id:this.authContext.userId,getToken:async(i=false)=>{if(e&&(!i||!t))return e;if(t)try{let r=await t(i);if(r)return r}catch{}let n=this.isTicketOnlyMode()?null:this.auth?.currentUser??null;if(n&&n.uid===this.authContext?.userId)try{return await n.getIdToken(i)}catch{return null}return null}}}return this.isTicketOnlyMode()?null:this.toRuntimeIdentity(this.auth?.currentUser??null)}onAuthChange(e){return this.authListeners.push(e),e(this.currentUser),()=>{this.authListeners=this.authListeners.filter(t=>t!==e);}}async checkForSSOToken(){this.isTicketOnlyMode()||this.usesProviderNeutralGrant()||await a().checkForSSOToken();}async waitForAuth(){this.isTicketOnlyMode()||this.usesProviderNeutralGrant()||this.isSpaceMode()||this.authContext?.userId||this.auth?.currentUser||await a().waitForAuth();}async signInAnonymously(){if(!this.isTicketOnlyMode()){if(this.options.authMode!=="anonymous")throw new Error(`[pluto-rtc] Anonymous sign-in is disabled when authMode=${this.options.authMode}.`);await a().signInAnonymously();}}async signInWithPluto(){if(this.isTicketOnlyMode())throw new Error('[openrtc] Pluto sign-in is unavailable when signalingMode="ticket-only".');await a().signInWithPluto();}async signOut(){let e=this.getCurrentUserId();await this.stopAuthActivity({userId:e}),this.authContext=null,this.syncWasmAuthToken(),this.isTicketOnlyMode()||await this.auth?.signOut(),this.authListeners.forEach(t=>t(this.currentUser));}async getTurnCredentials(){return this.isTicketOnlyMode()||!this.auth?.currentUser?null:typeof this.options.turnCredentialsProvider=="function"?await this.options.turnCredentialsProvider()??null:null}async updatePresence(e,t,i=true,n=3e5,r,o){if(this.isTicketOnlyMode())return;let s=this.resolveWebLogicalDeviceId(),a=this.getDeviceIdPersistenceMode()==="ephemeral"?u.EPHEMERAL_DEVICE_ID_TTL_MS:n,c=await this.withWebPresenceMetadata(r,s);this.presenceManager.updatePresenceLoopState({userId:this.getCurrentUserId()??"",localNodeId:e,ticket:t,metadata:c,deviceName:o?.trim()||this.getDefaultBrowserDeviceName()}),await this.getCoordinationSignaling().updatePresence(e,t,i,a,c,o);}async refreshLivePresence(e,t,i,n){if(this.isTicketOnlyMode())return;let r=this.resolveWebLogicalDeviceId(),o=await this.withWebPresenceMetadata(i,r);this.presenceManager.updatePresenceLoopState({userId:this.getCurrentUserId()??"",localNodeId:e,ticket:t,metadata:o,deviceName:n?.trim()||this.getDefaultBrowserDeviceName()}),await this.getCoordinationSignaling().updatePresence(e,t,true,15*6e4,o,n);}async setOffline(e){this.presenceManager.stopPresence(),!this.isTicketOnlyMode()&&await this.getCoordinationSignaling().setOffline(e);}async updateDevice(e,t){if(!e?.trim())throw new Error("updateDevice requires a deviceId");this.isTicketOnlyMode()||await this.getCoordinationSignaling().updateDevice(e,t);}async deleteDevice(e){if(!e?.trim())throw new Error("deleteDevice requires a deviceId");this.isTicketOnlyMode()||await this.getCoordinationSignaling().deleteDevice(e);}async cleanupStaleDevices(){this.isTicketOnlyMode()||await this.getCoordinationSignaling().cleanupStaleDevices();}async sendMessage(e,t,i,n){if(this.isTicketOnlyMode())throw new Error('[openrtc] sendMessage() is unavailable when signalingMode="ticket-only".');return this.getCoordinationSignaling().sendMessage(e,t,i,n)}async pollMessages(e){return this.isTicketOnlyMode()?[]:this.getCoordinationSignaling().pollMessages(e)}async searchDevices(e){return this.isTicketOnlyMode()?[]:this.getCoordinationSignaling().searchDevices(e)}async listDeviceStatus(){if(this.isTicketOnlyMode())return [];if(!this.getDiscoveryScopeId())return [];let t=await this.getCoordinationSignaling().listDevices(),i=this.wasmClient;return Promise.all(t.map(async n=>{let r=this.normalizeDeviceStatusSnapshot({...n,connectionStatus:n.online?"online":"disconnected"}),o=typeof n.nodeId=="string"?n.nodeId.trim():"";if(!o||typeof i?.iroh_path_kind!="function"||typeof i?.iroh_transport_rtt_ms!="function")return r;try{let[s,a]=await Promise.all([i.iroh_path_kind(o),i.iroh_transport_rtt_ms(o)]);if(typeof a!="number"||!Number.isFinite(a))return r;let c=Math.max(0,Math.round(a)),d={};if(s==="direct-lan")d.irohLan=c;else if(s==="direct-quic")d.iroh=c;else if(s==="ble")d.ble=c;else if(s==="relay")d.irohRelay=c;else if(s==="webrtc")d.webrtc=c;else if(s==="moq")d.moq=c;else return r;return {...r,latencyMs:c,latencyByTransport:d}}catch(s){return d$1("[WasmBridge] iroh transport latency unavailable",{deviceId:n.deviceId,error:s instanceof Error?s.message:String(s)}),r}}))}async getPeerSession(e){let t=await this.waitForWasmClient(500);if(t&&typeof t.peer_session=="function"){let i=await t.peer_session(e);return !i||typeof i!="object"?null:this.normalizePeerSessionSnapshot(i)}return this.warnMissingWasmOnce("getPeerSession"),null}async listPeerSessions(){let e=await this.waitForWasmClient(500);if(e&&typeof e.peer_sessions=="function"){let t=await e.peer_sessions();return (Array.isArray(t)?t:[]).map(n=>this.normalizePeerSessionSnapshot(n)).filter(n=>!!(n.peerId||n.deviceId||n.deviceIdHint||n.nodeId||n.activeConnectionId))}return this.warnMissingWasmOnce("listPeerSessions"),[]}async waitForSettledPeer(e,t){let i=await this.waitForWasmClient(500);if(i&&typeof i.wait_for_peer=="function"){let n=await i.wait_for_peer(e,t);return !n||typeof n!="object"?null:this.normalizePeerSessionSnapshot(n)}return this.warnMissingWasmOnce("waitForSettledPeer"),null}async openPeerBi(e,t){let i=await this.waitForWasmClient(500);if(i&&typeof i.open_peer_bi=="function"){let n=await i.open_peer_bi(e,t);if(!n?.recv||!n?.send)throw new Error("WASM open_peer_bi returned an invalid bidirectional stream");return {readable:n.recv,writable:_(n,n.send)}}throw this.warnMissingWasmOnce("openPeerBi"),new Error("WASM runtime does not support open_peer_bi()")}async openPeerBiRaw(e,t){if(this.options.applicationCrypto?.requireEncrypted)throw new Error("[WasmBridge] openPeerBiRaw is debug-only and cannot be used when application crypto is required");let i=await this.waitForWasmClient(500),n=i&&typeof i.open_peer_bi_transport_only=="function";if(console.debug("[WasmBridge] openPeerBiRaw",{peerId:e,hasWasmClient:!!i,hasTransportOnly:n,timeoutMs:t}),n){let r=await i.open_peer_bi_transport_only(e,t);if(!r?.recv||!r?.send)throw new Error("WASM open_peer_bi_transport_only returned an invalid bidirectional stream");return {readable:r.recv,writable:_(r,r.send)}}throw new Error("WASM runtime does not support the restricted transport-only diagnostic stream")}async openPeerUni(e,t){let i=await this.waitForWasmClient(500);if(i&&typeof i.open_peer_uni=="function"){let n=await i.open_peer_uni(e,t),r=n?.writable??n;if(!r)throw new Error("WASM open_peer_uni returned an invalid writable stream");return {writable:_(n,r)}}throw this.warnMissingWasmOnce("openPeerUni"),new Error("WASM runtime does not support open_peer_uni()")}beginOpenRtcMediaPublication(e){let t=this.wasmClient?.__beginOpenRtcMediaPublication;if(typeof t!="function")throw new Error("[OpenRTC] This WASM build does not include Rust-owned media sessions.");let i=t.call(this.wasmClient,e.publicationId||void 0,e.kind,e.codec,e.clockRate,e.codedWidth,e.codedHeight,e.channels);return {...i,control:new Uint8Array(i.control)}}encodeOpenRtcMediaSample(e){let t=this.wasmClient?.__encodeOpenRtcMediaSample;if(typeof t!="function")throw new Error("[OpenRTC] This WASM build does not include Rust-owned media sessions.");return new Uint8Array(t.call(this.wasmClient,e.publicationId,e.timestampUs,e.durationUs,e.keyframe,e.discardable,e.payload))}pauseOpenRtcMediaPublication(e){let t=this.wasmClient?.__pauseOpenRtcMediaPublication;if(typeof t!="function")throw new Error("[OpenRTC] This WASM build does not include Rust-owned media sessions.");t.call(this.wasmClient,e);}retireOpenRtcMediaPublication(e){let t=this.wasmClient?.__retireOpenRtcMediaPublication;if(typeof t!="function")throw new Error("[OpenRTC] This WASM build does not include Rust-owned media sessions.");t.call(this.wasmClient,e);}retireOpenRtcMediaReceiver(e,t){let i=this.wasmClient?.__retireOpenRtcMediaReceiver;if(typeof i!="function")throw new Error("[OpenRTC] This WASM build does not include Rust-owned media sessions.");i.call(this.wasmClient,e,t);}decodeOpenRtcMediaChunk(e){let t=this.wasmClient?.__decodeOpenRtcMediaChunk;if(typeof t!="function")throw new Error("[OpenRTC] This WASM build does not include the shared media protocol.");let i=t.call(this.wasmClient,e);return {...i,payload:new Uint8Array(i.payload)}}decodeOpenRtcMediaControl(e){let t=this.wasmClient?.__decodeOpenRtcMediaControl;if(typeof t!="function")throw new Error("[OpenRTC] This WASM build does not include the shared media protocol.");return t.call(this.wasmClient,e)}async sendPeerDatagram(e,t,i){let n=await this.waitForWasmClient(500),r=n?.sendPeerDatagram;if(typeof r!="function")throw new Error("[OpenRTC] This WASM build does not include protected peer datagrams.");return await r.call(n,e,t,i)!==false}async receivePeerDatagram(e){let t=await this.waitForWasmClient(500),i=t?.receivePeerDatagram;if(typeof i!="function")throw new Error("[OpenRTC] This WASM build does not include protected peer datagrams.");return new Uint8Array(await i.call(t,e))}peerDatagramMaxSize(){let e=this.wasmClient?.peerDatagramMaxSize?.();return Number.isSafeInteger(e)&&e>0?e:1024}createPeerDatagramPolicy(){let e=this.wasmClient?.createPeerDatagramPolicy;if(typeof e!="function")throw new Error("[OpenRTC] This WASM build does not include shared datagram policy.");return e.call(this.wasmClient)}async resolvePeerRecords(e){let t=await this.waitForWasmClient(500);if(t&&typeof t.resolve_peer_connection_records=="function"){let i=await t.resolve_peer_connection_records(e);return (Array.isArray(i)?i:[]).map(n=>({connectionId:typeof n.connectionId=="string"?n.connectionId:"",nodeId:typeof n.nodeId=="string"?n.nodeId:null,deviceId:typeof n.deviceId=="string"?n.deviceId:null,deviceIdHint:typeof n.deviceIdHint=="string"?n.deviceIdHint:null,endpointId:typeof n.endpointId=="string"?n.endpointId:null,transportGeneration:typeof n.transportGeneration=="number"?n.transportGeneration:0,routeGeneration:typeof n.routeGeneration=="number"?n.routeGeneration:void 0,transportStableId:typeof n.transportStableId=="number"?n.transportStableId:null,transportSource:typeof n.transportSource=="string"?n.transportSource:null,lastTransportChangeAtMs:typeof n.lastTransportChangeAtMs=="number"?n.lastTransportChangeAtMs:0,lastRouteChangeAtMs:typeof n.lastRouteChangeAtMs=="number"?n.lastRouteChangeAtMs:void 0,state:typeof n.state=="string"?n.state:"pending",statusReason:typeof n.statusReason=="string"?n.statusReason:null,createdAtMs:typeof n.createdAtMs=="number"?n.createdAtMs:0,updatedAtMs:typeof n.updatedAtMs=="number"?n.updatedAtMs:0}))}return this.warnMissingWasmOnce("resolvePeerRecords"),[]}async resolvePeerIdentity(e){let t=await this.waitForWasmClient(500);if(t){let i=n=>{if(!n||typeof n!="object")return {peerId:null,deviceId:null,deviceIdHint:null,nodeId:null};let r=n;return {peerId:typeof r.peerId=="string"?r.peerId:null,deviceId:typeof r.deviceId=="string"?r.deviceId:null,deviceIdHint:typeof r.deviceIdHint=="string"?r.deviceIdHint:null,nodeId:typeof r.nodeId=="string"?r.nodeId:null}};if(typeof t.peer_session=="function")try{let n=await t.peer_session(e),r=i(n);if(r.peerId||r.deviceId||r.deviceIdHint||r.nodeId)return r}catch{}if(typeof t.peer_snapshot=="function")try{return i(await t.peer_snapshot(e))}catch{}}return this.warnMissingWasmOnce("resolvePeerIdentity"),{peerId:null,deviceId:null,deviceIdHint:null,nodeId:null}}onDevicesChange(e,t){return this.isTicketOnlyMode()?(e([]),()=>{}):this.getCoordinationSignaling().onDevicesChange(e,t)}onRoomArchitectureChange(e){return this.getCoordinationSignaling().onRoomArchitectureChange?.(t=>{let i=this.effectiveRoomArchitecture!==t.effective;this.effectiveRoomArchitecture=t.effective,i&&this.presenceManager.handleRoomArchitectureChange().catch(n=>{console.warn("[WasmSignaling] failed to replay desired peers after room architecture change",{effectiveArchitecture:t.effective,epoch:t.epoch,error:n});}),e(t);})??(()=>{})}onRoomAuthorityAssignmentChange(e){return this.getCoordinationSignaling().onRoomAuthorityAssignmentChange?.(e)??(()=>{})}async publishAuthorityAssignment(e){let t=this.getCoordinationSignaling();if(!t.publishAuthorityAssignment)throw new Error("[OpenRTC] Authority assignment publication is unavailable.");await t.publishAuthorityAssignment(e);}async publishManagedRoomMessage(e){let t=this.getCoordinationSignaling().publishManagedRoomMessage;if(!t)throw new Error("[OpenRTC] Managed room fanout is unavailable.");await t.call(this.getCoordinationSignaling(),e);}onManagedRoomMessage(e){return this.getCoordinationSignaling().onManagedRoomMessage?.(e)??(()=>{})}async subscribeDevices(e){return this.isTicketOnlyMode()?new ReadableStream({start(t){t.close();}}):this.getCoordinationSignaling().subscribeDevices()}async startAutoConnect(e,t){if(this.isTicketOnlyMode())return;this.startApplicationRouteEscalationSubscription();let i=this.authScopedRuntimeGeneration;try{let n=await this.waitForWasmClient();if(i!==this.authScopedRuntimeGeneration||!n||typeof n.start_auto_connect!="function")return;await this.presenceManager.installInitialAutoConnectExclusions(n),await n.start_auto_connect(e,t),i===this.authScopedRuntimeGeneration&&this.presenceManager.startAutoConnect(e,t);}catch(n){console.warn("[WasmBridge] failed to initialize WASM auto-connect context",{userId:e,localDeviceId:t,error:n});}}async startAutoConnectOnce(e,t){await this.startAutoConnect(e,t),this.forceReconnect();}notifyDisconnectRequested(e){this.presenceManager.wakeRustAutoConnectOwner();}async excludeAutoConnect(e,t){await this.presenceManager.excludeAutoConnect(e,t);}async disconnectDevice(e){let t=await this.waitForWasmClient();if(!t||typeof t.disconnect_device!="function"){this.warnMissingWasmOnce("disconnectDevice"),await this.presenceManager.excludeAutoConnect(e,true).catch(()=>{});return}try{await t.disconnect_device(e,null),await this.presenceManager.recordAutoConnectExcludedForPresence(e,!0).catch(()=>{});}catch(i){throw console.warn("[WasmBridge] disconnect_device failed",{deviceId:e,error:i?.message??String(i)}),i}}async submitDesiredPeerProjection(e,t){return this.presenceManager.submitDesiredPeerProjection(e,t)}observeManagedDesiredPeers(e){this.presenceManager.observeDesiredPeerProjection(e),e$1("[OpenRTC][route-escalation] observed managed desired peers",{peerCount:e.length,peersWithTickets:e.filter(t=>typeof t.ticket=="string"&&t.ticket.trim()).length,deviceIds:e.map(t=>t.deviceId)});}setCoreClient(e){e&&typeof e.ensureManagedApplicationRoute=="function"?(this.coreClient=e,e$1("[OpenRTC][route-escalation] attached shared core client"),this.startApplicationRouteEscalationSubscription(),this.retryManagedApplicationRouteEscalations()):(this.coreClient=null,e$1("[OpenRTC][route-escalation] detached shared core client"),this.stopApplicationRouteEscalationSubscription());}startApplicationRouteEscalationSubscription(){if(this.applicationRouteEscalationUnsubscribe&&this.routeSubscriptionGeneration===this.authScopedRuntimeGeneration)return;this.stopApplicationRouteEscalationSubscription();let e=this.authScopedRuntimeGeneration,t=this.applicationRouteEscalationSubscriptionEpoch,i=this.onStateChange(n=>{let r=this.stabilizeConnectionState(n);this.lastDeliveredConnectionStates.set(r.connectionId,r),e$1("[OpenRTC][route-escalation] observed Rust connection state",{connectionId:r.connectionId,deviceId:r.deviceId??r.deviceIdHint??null,remoteNodeId:r.remoteNodeId??null,state:r.state,transportGeneration:r.transportGeneration??null,routeGeneration:r.routeGeneration??null}),this.escalateManagedApplicationRoute(r);});this.applicationRouteEscalationUnsubscribe=()=>{},this.routeSubscriptionGeneration=e,Promise.resolve(i).then(n=>{if(!this.coreClient||e!==this.authScopedRuntimeGeneration||t!==this.applicationRouteEscalationSubscriptionEpoch){n();return}this.applicationRouteEscalationUnsubscribe=n,this.routeSubscriptionGeneration=e;});}stopApplicationRouteEscalationSubscription(){this.applicationRouteEscalationSubscriptionEpoch+=1,this.applicationRouteEscalationUnsubscribe?.(),this.applicationRouteEscalationUnsubscribe=null,this.routeSubscriptionGeneration=-1;}retryManagedApplicationRouteEscalations(){for(let e of this.lastDeliveredConnectionStates.values())this.escalateManagedApplicationRoute(e);}escalateManagedApplicationRoute(e){if(!this.coreClient||!["connected","connecting"].includes(e.state))return;let t=[e.transportGeneration??0,e.routeGeneration??0].join(":"),i=this.applicationRouteEscalationAttemptKeys??(this.applicationRouteEscalationAttemptKeys=new Map);if(i.get(e.connectionId)===t||this.applicationRouteEscalations.has(e.connectionId))return;let n=this.presenceManager.resolveDesiredPeer(e.deviceId??e.deviceIdHint,e.remoteNodeId);if(!n?.ticket){e$1("[OpenRTC][route-escalation] awaiting matching desired-peer ticket",{connectionId:e.connectionId,deviceId:e.deviceId??e.deviceIdHint??null,remoteNodeId:e.remoteNodeId??null});return}let r=this.authScopedRuntimeGeneration,o=this.coreClient;i.set(e.connectionId,t),e$1("[OpenRTC][route-escalation] adopting Rust-managed generation",{connectionId:e.connectionId,deviceId:n.deviceId,remoteNodeId:e.remoteNodeId??n.nodeId??null,transportGeneration:e.transportGeneration??null,routeGeneration:e.routeGeneration??null});let s;s=(async()=>{let a=await o.ensureManagedApplicationRoute({ticket:n.ticket,connectionId:e.connectionId,remoteNodeId:e.remoteNodeId??n.nodeId,expectedDeviceId:n.deviceId,timeoutMs:2e4});if(r!==this.authScopedRuntimeGeneration)return;let c=a,d=c.id?.trim()||e.connectionId,p=c.remoteNodeId?.trim()||e.remoteNodeId?.trim()||c.deviceId?.trim()||n.deviceId;if(o.hasApplicationRouteForPeer?.(d,p)!==true&&o.hasApplicationRouteForPeer?.(d,p)!==true)throw new Error(`application crypto was not ready for ${p}`)})().catch(a=>{r===this.authScopedRuntimeGeneration&&console.warn("[OpenRTC][route-escalation] Rust-managed route remains pending",{connectionId:e.connectionId,deviceId:n.deviceId,remoteNodeId:e.remoteNodeId??n.nodeId,error:a?.message??String(a)});}).finally(()=>{if(this.applicationRouteEscalations.get(e.connectionId)===s){this.applicationRouteEscalations.delete(e.connectionId);let a=this.lastDeliveredConnectionStates?.get(e.connectionId),c=a?[a.transportGeneration??0,a.routeGeneration??0].join(":"):null;a&&c!==t&&r===this.authScopedRuntimeGeneration&&queueMicrotask(()=>this.escalateManagedApplicationRoute(a));}}),this.applicationRouteEscalations.set(e.connectionId,s);}async connectToDevice(e){let t=await this.waitForWasmClient();if(!t||typeof t.connect_device!="function")throw this.warnMissingWasmOnce("connectToDevice"),new Error("WASM runtime does not support connect_device()");let i=Date.now();e$1("[WasmBridge][ROUTE-ESCALATION] starting managed transport dial",{deviceId:e.deviceId??null,ticket:oe(e.endpointTicket),hasCoreClient:!!this.coreClient});let n=await t.connect_device(e.deviceId??null,e.endpointTicket);e$1("[WasmBridge][ROUTE-ESCALATION] managed transport dial completed",{deviceId:e.deviceId??null,remoteNodeId:n?.remoteNodeId??null,connectionId:n?.connectionId??null,elapsedMs:Date.now()-i});let r=e.endpointTicket;if(r&&this.coreClient){let o=this.coreClient;try{e$1("[WasmBridge][ROUTE-ESCALATION] starting typed application connection",{deviceId:e.deviceId??null,remoteNodeId:n?.remoteNodeId??null,connectionId:n?.connectionId??null});let s=await o.ensureManagedApplicationRoute({ticket:r,connectionId:n?.connectionId??null,remoteNodeId:n?.remoteNodeId??null,expectedDeviceId:e.deviceId??null,approvedScope:n?.approvedScope??null,timeoutMs:2e4}),a=typeof s?.remoteNodeId=="string"?s.remoteNodeId.trim():"",c=typeof s?.deviceId=="string"?s.deviceId.trim():"",d=a||n?.remoteNodeId?.trim?.()||c||e.deviceId?.trim?.()||"",p=typeof o.hasApplicationRouteForPeer=="function"?o.hasApplicationRouteForPeer.bind(o):null;if(!(!!d&&p?.(s?.id??void 0,d)===!0)&&d&&typeof o.waitForApplicationCryptoForPeer=="function"&&!(!!await o.waitForApplicationCryptoForPeer(d,2e4)&&(!p||p(s?.id??void 0,d)===!0)))throw console.warn("[WasmBridge][ROUTE-ESCALATION] application route still pending after managed dial",{deviceId:e.deviceId??null,remoteNodeId:a||(n?.remoteNodeId??null),connectionId:n?.connectionId??null,peerForCrypto:d,elapsedMs:Date.now()-i}),Object.assign(new Error(`application crypto was not ready for ${d}`),{applicationCryptoNotReady:!0});e$1("[WasmBridge][ROUTE-ESCALATION] application route ready",{deviceId:e.deviceId??null,remoteNodeId:a||(n?.remoteNodeId??null),connectionId:n?.connectionId??null,elapsedMs:Date.now()-i});}catch(s){if(s?.applicationCryptoNotReady)throw s;return console.warn("[WasmBridge] Managed transport connected; TS application route escalation is still pending",{deviceId:e.deviceId??null,remoteNodeId:n?.remoteNodeId??null,connectionId:n?.connectionId??null,error:s?.message??String(s)}),n}}return n}forceReconnect(){this.isTicketOnlyMode()||!this.app||!this.auth||this.presenceManager.wakeRustAutoConnectOwner();}startPresenceLoop(e,t,i,n,r){return this.presenceManager.startPresenceLoop(e,t,i,n,r)}ensureSpaceNamespaceIdPromise(){if(this.cachedSpaceNamespaceId)return Promise.resolve(this.cachedSpaceNamespaceId);if(!this.spaceNamespaceIdPromise){let e=this.options.apiKey?.trim()??"",t=this.options.spaceKey?.trim()??"";if(!e||!t)return Promise.resolve(null);this.spaceNamespaceIdPromise=b$1(e,t).then(i=>(this.cachedSpaceNamespaceId=i,i)).catch(()=>null);}return this.spaceNamespaceIdPromise}async createSession(e){if(this.isTicketOnlyMode())throw new Error('[openrtc] createSession() is unavailable when signalingMode="ticket-only".');let t=this.getCurrentUserId();if(!t&&!e.initiator&&!e.target&&!this.isSpaceMode())throw new Error("createSession requires user scope");let i={...e,appTag:e.appTag??this.appTag,initiator:e.initiator??t??void 0,target:e.target??t??void 0};await this.getCoordinationSignaling().createSession(i);}async updateSession(e,t){if(this.isTicketOnlyMode())throw new Error('[openrtc] updateSession() is unavailable when signalingMode="ticket-only".');await this.getCoordinationSignaling().updateSession(e,t);}async subscribeSessions(e){return this.isTicketOnlyMode()?new ReadableStream({start(t){t.close();}}):this.getCoordinationSignaling().subscribeSessions(e)}async getLocalDeviceId(){return this.resolveWebLogicalDeviceId()}async isConnected(e){let t=await this.waitForWasmClient();return t&&typeof t.is_connected=="function"?t.is_connected(e):false}async getConnectionStates(){let e=await this.waitForWasmClient(500);if(e&&typeof e.connection_states=="function"){let n=await e.connection_states(),r=(Array.isArray(n)?n:[]).map(o=>this.normalizeStateSnapshot(o)).filter(o=>!!o);return r.length>0&&d$1("[WasmBridge] replaying current wasm connection states",r.map(o=>({connectionId:o.connectionId,deviceId:o.deviceId??null,deviceIdHint:o.deviceIdHint??null,remoteNodeId:o.remoteNodeId??null,state:o.state,transportState:o.transportState??null,protocolState:o.protocolState??null,routable:o.routable??null}))),r}let i=(await this.listPeerSessions().catch(()=>[])).map(n=>this.toBackendConnectionStateFromPeerSession(n)).filter(n=>!!n);return i.length>0&&d$1("[WasmBridge] replaying current wasm connection states",i.map(n=>({connectionId:n.connectionId,deviceId:n.deviceId??null,deviceIdHint:n.deviceIdHint??null,remoteNodeId:n.remoteNodeId??null,state:n.state,transportState:n.transportState??null,protocolState:n.protocolState??null,routable:n.routable??null}))),i}onStateChange(e){let t=new Map,i=new Map,n=this.authScopedRuntimeGeneration,r=false,o=c=>{let d=c.detail,p=this.normalizeStateSnapshot(d),h=typeof d?.connectionId=="string"?d.connectionId.trim():"";if(!h||r)return;if(p&&(p.state==="closed"||p.state==="failed"||p.state==="disconnected")){this.deliverConnectionState(p,e,"rust-event-detail",t);return}let g=(i.get(h)??0)+1;i.set(h,g);let f=this.authScopedRuntimeGeneration;(async()=>{let v=await this.waitForWasmClient(500);if(!(r||f!==this.authScopedRuntimeGeneration||i.get(h)!==g)){if(v&&typeof v.connection_state=="function"){let P=await v.connection_state(h),w=this.normalizeStateSnapshot(P);if(!r&&f===this.authScopedRuntimeGeneration&&i.get(h)===g&&w){this.deliverConnectionState(w,e,"rust-event",t);return}}!r&&f===this.authScopedRuntimeGeneration&&i.get(h)===g&&p&&this.deliverConnectionState(p,e,"rust-event-detail",t);}})().catch(v=>{r||console.warn("[WasmBridge] Failed to read Rust connection state after lifecycle event",{connectionId:h,error:v});});},s=typeof window<"u"?window:null,a=typeof s?.addEventListener=="function"&&typeof s?.removeEventListener=="function";return a&&s.addEventListener("connection-state-changed",o),this.getConnectionStates().then(c=>{!r&&n===this.authScopedRuntimeGeneration&&c.forEach(d=>{i.has(d.connectionId)||this.deliverConnectionState(d,e,"replay",t);});}).catch(c=>{console.warn("[WasmBridge] Failed to replay wasm connection states after subscription:",c);}),()=>{r=true,i.clear(),a&&s.removeEventListener("connection-state-changed",o);}}async sendExplicitFilePath(e,t,i=""){throw new Error("sendExplicitFilePath is native-only. Use sendExplicitFileData in web/wasm runtime.")}sanitizeExplicitFileName(e){let i=(typeof e=="string"?e.replace(/\\/g,"/"):"").split("/").reverse().find(o=>o.trim().length>0)?.trim()??"";if(!i||i==="."||i==="..")return u.FALLBACK_EXPLICIT_FILE_NAME;let n="";for(let o of i){if([...n].length>=u.MAX_EXPLICIT_FILE_NAME_CHARS)break;let s=o.charCodeAt(0);o==="/"||o==="\\"||o==="\0"||s<32||s===127?n+="_":n+=o;}let r=n.trim();return !r||r==="."||r===".."?u.FALLBACK_EXPLICIT_FILE_NAME:r}sanitizeExplicitMimeType(e){let t=typeof e=="string"?e.trim():"";if(!t)return u.FALLBACK_EXPLICIT_MIME_TYPE;let i="";for(let n of t){if(i.length>=u.MAX_EXPLICIT_MIME_TYPE_CHARS)break;let r=n.charCodeAt(0);r<33||r>126||n==='"'||n==="\\"?i+="_":i+=n;}return i.length>0?i:u.FALLBACK_EXPLICIT_MIME_TYPE}assertExplicitTransferHeaderSize(e){if(e.byteLength===0||e.byteLength>u.MAX_EXPLICIT_TRANSFER_HEADER_BYTES)throw new Error(`Explicit transfer header is too large: ${e.byteLength} bytes`)}createWebRTCExplicitTransferId(){let e=new Uint8Array(16),t=globalThis.crypto;if(t&&typeof t.getRandomValues=="function")return t.getRandomValues(e),e;for(let i=0;i<e.byteLength;i+=1)e[i]=Math.floor(Math.random()*256);return e}createWebRTCExplicitTransferFrame(e,t,i,n,r){let o=r?.headerFrame===true?4:0,s=new Uint8Array(25+o+n.byteLength);s[0]=u.EXPLICIT_FILE_PROTOCOL_TYPE,s.set(e,1);let a=new DataView(s.buffer);a.setUint32(17,t,false),a.setUint32(21,i,false);let c=r?.headerFrame===true?29:25;return r?.headerFrame===true&&a.setUint32(25,n.byteLength,false),s.set(n,c),s}async sendExplicitFileData(e){let t=e.connection,i=e.file,n=e.applicationCrypto??this.options.applicationCrypto;if((e.requireApplicationCrypto===true||t?.requireApplicationCrypto===true)&&!n)throw new Error("[WasmBridge] Explicit transfer requires application crypto but none is available for this connection");let o=e.transferId&&e.transferId.trim().length>0?e.transferId:`transfer-${Date.now()}`;typeof e.receiverPlatformType=="string"?e.receiverPlatformType.trim().toLowerCase():null;let a=e.remoteNodeId?.trim()||t?.remoteNodeId?.trim()||t?.deviceId?.trim();if(e$1("[WasmBridge] sendExplicitFileData start",{connectionId:e.connectionId??null,connectionRemoteNodeId:t?.remoteNodeId??null,remoteNodeId:a??null,fileName:i.name,fileSize:i.size,transferId:o}),!a)throw new Error("Web explicit transfer requires an active connection with a resolved remote node ID");let c=await this.waitForWasmClient();if(!c)throw new Error("WASM explicit transfer requires an initialized WASM client");let d=new TextEncoder,p={transfer_id:o,filename:this.sanitizeExplicitFileName(i.name),size:i.size,mime_type:this.sanitizeExplicitMimeType(i.type)},h=d.encode(JSON.stringify(p));this.assertExplicitTransferHeaderSize(h);let g=new Uint8Array(4);new DataView(g.buffer).setUint32(0,h.byteLength,false);let f=new Uint8Array(g.byteLength+h.byteLength);f.set(g,0),f.set(h,g.byteLength);let v=async()=>{let P=c.open_peer_bi_explicit_file_sender;if(typeof P!="function")return false;let w=await P.call(c,a,5e3),E=w?.writable??w?.send;if(!E||typeof E.getWriter!="function")throw new Error("WASM explicit peer stream returned an invalid writable stream");e$1("[WasmBridge] sendExplicitFileData open_peer_bi_explicit_file_sender resolved",{remoteNodeId:a,transferId:e.transferId??null,applicationCryptoWrapped:w.applicationCryptoWrapped===true});let C=_(w,E,{requireFinish:true}).getWriter(),T=false;try{await C.write(f);let I=new Uint8Array(await i.arrayBuffer());for(let S=0;S<I.byteLength;S+=u.EXPLICIT_FILE_CHUNK_SIZE_BYTES){let te=I.slice(S,Math.min(S+u.EXPLICIT_FILE_CHUNK_SIZE_BYTES,I.byteLength));await C.write(te);}}catch(I){throw T=true,I}finally{try{await C.close();}catch(I){if(!T)throw I}finally{C.releaseLock();}}return true};try{if(await v())return;throw new Error("[WasmBridge] Explicit transfer requires the generation-fenced open_peer_bi_explicit_file_sender path, but it is unavailable on this WASM build. Rebuild the current OpenRTC WASM; raw open_bi fallback is intentionally unsupported for application data.")}finally{e$1("[WasmBridge] sendExplicitFileData completed",{remoteNodeId:a,transferId:o,fileName:i.name,fileSize:i.size});}}async getTransferHistory(e=50){return []}async deleteTransferJob(e){}watchFriendDevices(e,t){return this.isTicketOnlyMode()?()=>{}:this.getCoordinationSignaling().watchFriendDevices(e,t)}async updateFriendTicket(e){this.isTicketOnlyMode()||await this.getCoordinationSignaling().updateFriendTicket(e);}};u.EXPLICIT_FILE_PROTOCOL_TYPE=2,u.EXPLICIT_FILE_CHUNK_SIZE_BYTES=64*1024,u.MAX_EXPLICIT_TRANSFER_HEADER_BYTES=64*1024,u.FALLBACK_EXPLICIT_FILE_NAME="openrtc-transfer.bin",u.MAX_EXPLICIT_FILE_NAME_CHARS=180,u.FALLBACK_EXPLICIT_MIME_TYPE="application/octet-stream",u.MAX_EXPLICIT_MIME_TYPE_CHARS=255,u.WEB_DEVICE_ID_STORAGE_PREFIX="pluto_rtc_web_device_identity",u.EPHEMERAL_DEVICE_ID_TTL_MS=o.browserIdentity.ephemeralDeviceIdTtlMs;var ee=u;export{ne as a,ee as b};
@@ -1 +0,0 @@
1
- function d(o){return [...new Set(o.capabilityKeys.filter(r=>typeof r=="string").map(r=>r.trim()).filter(Boolean))]}async function m(o,r){if(!o||typeof o!="object")return;let t=o.stream,e=[];t?.recv&&e.push(t.recv.cancel(r)),t?.send&&e.push(t.send.abort(r)),await Promise.allSettled(e);}var u=class{constructor(){this.host=null;this.consumers=new Map;this.hostReader=null;this.hostPump=null;this.closed=false;}register(r,t){if(this.closed)throw new Error("[OpenRTC] Native projection broker is closed.");let e=r.trim();if(!e)throw new Error("[OpenRTC] Native capability projection key is required.");if(this.consumers.has(e))throw new Error(`[OpenRTC] Native capability '${e}' is already registered.`);return this.consumers.size===0?this.host=t:this.host??(this.host=t),this.consumers.set(e,{controller:null,stream:null,stateListeners:new Set,messageListeners:new Set}),{__openrtcNativeCapabilityProjection:true,capabilityKey:e,incoming_streams:()=>this.incomingStreams(e),onStateChange:s=>this.subscribeState(e,s),onPeerMessage:s=>this.subscribePeerData(e,s),isCurrentTransport:(s,n)=>this.currentHost().isCurrentTransport(s,n)}}unregister(r){let t=r.trim(),e=this.consumers.get(t);if(e){this.consumers.delete(t);try{e.controller?.close();}catch{}e.controller=null,e.stream=null,e.stateListeners.clear(),e.messageListeners.clear(),this.consumers.size===0&&this.cancelHostReader("no active native capabilities");}}subscribeState(r,t){let e=this.requireConsumer(r);return e.stateListeners.add(t),this.ensureHostPump(),()=>{e.stateListeners.delete(t),this.cancelHostReaderIfIdle();}}subscribePeerData(r,t){let e=this.requireConsumer(r);return e.messageListeners.add(t),this.ensureHostPump(),()=>{e.messageListeners.delete(t),this.cancelHostReaderIfIdle();}}requireConsumer(r){if(this.closed)throw new Error("[OpenRTC] Native projection broker is closed.");let t=this.consumers.get(r);if(!t)throw new Error(`[OpenRTC] Native capability '${r}' is not registered.`);return t}currentHost(){if(this.closed)throw new Error("[OpenRTC] Native projection broker is closed.");if(!this.host)throw new Error("[OpenRTC] Native projection broker has no IPC host.");return this.host}async incomingStreams(r){if(this.closed)throw new Error("[OpenRTC] Native projection broker is closed.");let t=this.requireConsumer(r);if(t.stream)return t.stream;let e;return e=new ReadableStream({start:s=>{t.controller=s,this.ensureHostPump();},cancel:()=>{t.stream===e&&(t.controller=null,t.stream=null),this.cancelHostReaderIfIdle();}},{highWaterMark:32}),t.stream=e,e}ensureHostPump(){this.hostPump||this.closed||(this.hostPump=this.pumpHost().finally(()=>{this.hostPump=null,this.hostReader=null,!this.closed&&this.hasActiveConsumers()&&this.ensureHostPump();}));}async pumpHost(){let r=this.currentHost(),t=null;try{let e=await r.incoming_projected_streams();if(this.closed){await e.cancel("OpenRTC native root client closed").catch(()=>{});return}for(t=e.getReader(),this.hostReader=t;!this.closed&&this.hasActiveConsumers();){let{done:s,value:n}=await t.read();if(s)return;let c=d(n);if(n.kind==="stream"){let a=c.length===1?c[0]:null,i=a?this.consumers.get(a):void 0;if(!i?.controller||(i.controller.desiredSize??0)<=0){await m(n.payload,a?`inactive native capability ${a}`:"ambiguous unscoped native projection");continue}i.controller.enqueue(n.payload);continue}for(let a of c){let i=this.consumers.get(a);if(i)if(n.kind==="connection-state")for(let l of i.stateListeners)l(n.payload);else for(let l of i.messageListeners)l(n.payload);}}}catch(e){if(!this.closed)for(let s of this.consumers.values()){try{s.controller?.error(e);}catch{}s.controller=null,s.stream=null,s.stateListeners.clear(),s.messageListeners.clear();}}finally{let e=t;if(this.hostReader===e&&(this.hostReader=null),e)try{e.releaseLock();}catch{}typeof r.releaseNativeProjectionSubscription=="function"&&await r.releaseNativeProjectionSubscription().catch(()=>{});}}hasActiveConsumers(){return [...this.consumers.values()].some(r=>r.controller!==null||r.stateListeners.size>0||r.messageListeners.size>0)}cancelHostReaderIfIdle(){this.hasActiveConsumers()||this.cancelHostReader("no active native projection consumers");}async cancelHostReader(r){let t=this.hostReader;this.hostReader=null,await t?.cancel(r).catch(()=>{});}async close(){if(this.closed){await this.hostPump;return}this.closed=true;for(let r of this.consumers.values())try{r.controller?.close();}catch{}this.consumers.clear(),this.host=null,await this.cancelHostReader("OpenRTC native root client closed"),await this.hostPump;}};export{u as a};
@@ -1 +0,0 @@
1
- import {a as a$2}from'./chunk-EFTDXE6M.js';import {s}from'./chunk-FB5M6GIW.js';import'./chunk-BGWJHPBC.js';import'./chunk-6Q2LAXM4.js';import'./chunk-AAZPQQXX.js';import {a as a$1}from'./chunk-XTYALGJN.js';import'./chunk-TYZS5LXQ.js';import'./chunk-OT7IPLZE.js';import'./chunk-OWKAJPOI.js';import {a}from'./chunk-VTYVIKTM.js';import'./chunk-72NEEJQG.js';import'./chunk-CNAW5BZ3.js';import'./chunk-DUY34MGT.js';import'./chunk-CCCYE3XN.js';import'./chunk-N6LGTNUI.js';import'./chunk-JPBW67B3.js';import'./chunk-2GX6GB6L.js';function l(p,n,m=new a){let t=a$1(p);return a$2(t,new s({...t,bridge:n,projectionBroker:m}))}export{l as createIpcClient};