openrtc 2.5.1 → 2.5.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +21 -1
- package/dist/{Connection-CTpuImO-.d.ts → Connection-CovQdc8E.d.ts} +30 -5
- package/dist/{DelegatingRuntimeAdapter-D67Ozqo3.d.ts → DelegatingRuntimeAdapter-3ykiNvyh.d.ts} +3 -2
- package/dist/{IpcRuntimeAdapter-Ddx0MtSI.d.ts → IpcRuntimeAdapter-BkM_1HyL.d.ts} +12 -2
- package/dist/NativeManagedBroadcastHost-WCQ6TPUU.js +1 -0
- package/dist/WasmBridge-LP7FHTHZ.js +1 -0
- package/dist/{assembly-DvfsYFCL.d.ts → assembly-C235UKSS.d.ts} +5 -3
- package/dist/{capabilities-CmzzxSvW.d.ts → capabilities-CdZpAKvE.d.ts} +1 -1
- package/dist/chunk-25CN4MLA.js +2 -0
- package/dist/chunk-42TNJH5S.js +1 -0
- package/dist/chunk-4CC6YIGG.js +1 -0
- package/dist/chunk-4J4F32QT.js +1 -0
- package/dist/chunk-CHT46RA7.js +2 -0
- package/dist/chunk-CNAW5BZ3.js +2 -0
- package/dist/chunk-P5GCLQHS.js +1 -0
- package/dist/chunk-VC7TGJFS.js +2 -0
- package/dist/{chunk-Z4KJHIV5.js → chunk-WMA4OMJL.js} +1 -1
- package/dist/{chunk-XTYALGJN.js → chunk-XMYBBLYK.js} +1 -1
- package/dist/coreClient.d.ts +3 -3
- package/dist/coreClient.js +1 -1
- package/dist/{dist-XO466BRG.js → dist-FIVA6EPA.js} +0 -18
- package/dist/index.d.ts +5 -5
- package/dist/index.js +1 -1
- package/dist/ipcFactory-2WMR4PH6.js +1 -0
- package/dist/native.d.ts +5 -5
- package/dist/native.js +1 -1
- package/dist/node.d.ts +9 -5
- package/dist/node.js +2 -2
- package/dist/openrtc-KERRTMSG.js +2 -0
- package/dist/openrtc_bg.wasm +0 -0
- package/dist/room-2MUFAJ4M.js +1 -0
- package/dist/runtime/WasmRuntimeAdapter.d.ts +3 -3
- package/dist/runtime/WasmRuntimeAdapter.js +1 -1
- package/dist/runtime/device-status.d.ts +1 -1
- package/dist/runtime/factories.d.ts +6 -5
- package/dist/runtime/factories.js +1 -1
- package/dist/runtime/index.d.ts +9 -9
- package/dist/runtime/index.js +1 -1
- package/dist/server-browser.d.ts +4 -4
- package/dist/server.d.ts +4 -4
- package/dist/server.js +1 -1
- package/dist/service-node.d.ts +5 -4
- package/dist/service-node.js +1 -1
- package/dist/testing/native.d.ts +4 -4
- package/dist/testing/native.js +1 -1
- package/dist/testing.d.ts +6 -4
- package/dist/testing.js +1 -1
- package/dist/transport/index.d.ts +2 -2
- package/dist/{types-Cyc-mPjk.d.ts → types-C6SMXBzJ.d.ts} +1 -1
- package/native/darwin-arm64/openrtc-node-host +0 -0
- package/native/darwin-arm64/openrtc-node-host.manifest.json +20 -0
- package/native/darwin-x64/openrtc-node-host +0 -0
- package/native/darwin-x64/openrtc-node-host.manifest.json +20 -0
- package/native/linux-x64/openrtc-node-host +0 -0
- package/native/linux-x64/openrtc-node-host.manifest.json +20 -0
- package/native/openrtc-node-host-signing-public.pem +3 -0
- package/package.json +3 -2
- package/dist/WasmBridge-ZXBCXBBM.js +0 -1
- package/dist/chunk-2K47N3QP.js +0 -2
- package/dist/chunk-EIJNERKZ.js +0 -1
- package/dist/chunk-FEF3DPPB.js +0 -1
- package/dist/chunk-GHAJW6SZ.js +0 -2
- package/dist/chunk-GTHSRQ7Y.js +0 -2
- package/dist/chunk-VTYVIKTM.js +0 -1
- package/dist/chunk-Z54XUIKZ.js +0 -1
- package/dist/ipcFactory-PRAJ7JP7.js +0 -1
- package/dist/openrtc-VCS6V3AN.js +0 -2
- package/dist/room-ULZ2FGWV.js +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import {t}from'./chunk-25CN4MLA.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 stopAuthActivity(){typeof this.backend.stopAuthActivity=="function"&&await this.backend.stopAuthActivity();}usesCoordinationGateway(){return this.backend.usesCoordinationGateway?.()===true}async joinCoordinationRoom(e,t,n){if(!this.backend.joinCoordinationRoom)throw new Error("Selected runtime adapter does not support coordination rooms.");await this.backend.joinCoordinationRoom(e,t,n);}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,t){if(!this.backend.watchCoordinationRoomMembers)throw new Error("Selected runtime adapter does not support coordination rooms.");return this.backend.watchCoordinationRoomMembers(e,t)}async getTurnCredentials(){return this.backend.getTurnCredentials()}async updatePresence(e,t,n,i,r){return this.backend.updatePresence(e,t,n,i,r)}async refreshLivePresence(e,t,n){if(typeof this.backend.refreshLivePresence!="function")throw new Error("Selected runtime adapter does not support refreshLivePresence().");return this.backend.refreshLivePresence(e,t,n)}async setOffline(e){return this.backend.setOffline(e)}async cleanupStaleDevices(){return this.backend.cleanupStaleDevices()}async searchDevices(e){return this.backend.searchDevices(e)}async listDeviceStatus(){if(typeof this.backend.listDeviceStatus!="function")throw new Error("Selected runtime adapter does not support listDeviceStatus().");return this.backend.listDeviceStatus()}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,t){return typeof this.backend.waitForSettledPeer!="function"?null:this.backend.waitForSettledPeer(e,t)}async waitForSettledScope(e,t){return typeof this.backend.waitForSettledScope!="function"?null:this.backend.waitForSettledScope(e,t)}async resolvePeerIdentity(e){return typeof this.backend.resolvePeerIdentity!="function"?{peerId:null,deviceId:null,deviceIdHint:null,nodeId:null}:this.backend.resolvePeerIdentity(e)}async resolvePeerRecords(e){return typeof this.backend.resolvePeerRecords!="function"?[]:this.backend.resolvePeerRecords(e)}async updateDevice(e,t){return this.backend.updateDevice(e,t)}async deleteDevice(e){return this.backend.deleteDevice(e)}onDevicesChange(e,t){return this.backend.onDevicesChange(e,t)}onAuthChange(e){return this.backend.onAuthChange(e)}async checkForSSOToken(){return this.backend.checkForSSOToken()}async waitForAuth(){return this.backend.waitForAuth()}async sendMessage(e,t,n,i){return this.backend.sendMessage(e,t,n,i)}async pollMessages(e){return this.backend.pollMessages(e)}watchFriendDevices(e,t){let n=this.backend;return n.watchFriendDevices?n.watchFriendDevices(e,t):()=>{}}async updateFriendTicket(e){let t=this.backend;t.updateFriendTicket&&await t.updateFriendTicket(e);}async subscribeDevices(e){return this.backend.subscribeDevices(e)}startAutoConnect(e,t){this.backend.startAutoConnect(e,t);}async submitDesiredPeerProjection(e,t){if(typeof this.backend.submitDesiredPeerProjection!="function")throw new Error("Selected runtime adapter does not support desired-peer projections.");await this.backend.submitDesiredPeerProjection(e,t);}async startPresenceLoop(e,t,n,i,r){await this.backend.startPresenceLoop(e,t,n,i,r);}async createSession(e){return this.backend.createSession(e)}async updateSession(e,t){return this.backend.updateSession(e,t)}async subscribeSessions(e){return this.backend.subscribeSessions(e)}forceReconnect(){this.backend.forceReconnect();}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 updateDeviceName(e){return typeof this.backend.updateDeviceName!="function"?null:this.backend.updateDeviceName(e)}async startNativeSession(e){let t=this.backend;if(typeof t.startNativeSession!="function")throw new Error("Selected runtime adapter does not support startNativeSession().");return t.startNativeSession(e)}async notifyNetworkChange(e){return typeof this.backend.notifyNetworkChange!="function"?null:this.backend.notifyNetworkChange(e)}async setTransportPriority(e){if(typeof this.backend.setTransportPriority!="function")throw new Error("Selected runtime adapter does not support setTransportPriority().");await this.backend.setTransportPriority(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 t=await this.backend.getManagedNodeId(e);return console.info("[DelegatingRuntimeAdapter][getManagedNodeId] resolved",{result:t}),t}async startPresence(e,t,n,i,r){let o=this.backend;if(typeof o.startPresence!="function")throw new Error("Selected runtime adapter does not support startPresence().");return o.startPresence(e,t,n,i,r)}async startAutoConnectOnce(e,t){let n=this.backend;if(typeof n.startAutoConnectOnce!="function")throw new Error("Selected runtime adapter does not support startAutoConnectOnce().");return n.startAutoConnectOnce(e,t)}async getEndpointTicket(){if(typeof this.backend.getEndpointTicket!="function")throw new Error("Selected runtime adapter does not support getEndpointTicket().");return this.backend.getEndpointTicket()}async getTicketWithToken(e,t){let n=this.backend;return typeof n.getTicketWithToken!="function"?null:n.getTicketWithToken(e,t)}async registerSessionToken(e,t,n,i){let r=this.backend;typeof r.registerSessionToken=="function"&&await r.registerSessionToken(e,t,n,i);}async revokeTokens(e){let t=this.backend;return typeof t.revokeTokens!="function"?[]:t.revokeTokens(e)}async openPeerBi(e,t){if(typeof this.backend.openPeerBi!="function")throw new Error("Selected runtime adapter does not support openPeerBi().");return this.backend.openPeerBi(e,t)}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 incoming_projected_streams(){let e=this.backend;if(typeof e.incoming_projected_streams!="function")throw new Error("Selected runtime adapter does not support incoming_projected_streams().");return e.incoming_projected_streams()}projectedIncomingStreamSource(){let e=this.backend;return typeof e.projectedIncomingStreamSource!="function"?{incoming_streams:()=>this.incoming_projected_streams(),isCurrentTransport:(t,n)=>this.isCurrentTransport(t,n)}:e.projectedIncomingStreamSource()}async isCurrentTransport(e,t){let n=this.backend;return typeof n.isCurrentTransport=="function"?n.isCurrentTransport(e,t):typeof n.is_current_transport_stable_id!="function"?false:n.is_current_transport_stable_id(e,t)}async openPeerBiRaw(e,t){let n=this.backend;if(typeof n.openPeerBiRaw=="function")return n.openPeerBiRaw(e,t);throw new Error("Selected runtime adapter does not support the restricted transport-only diagnostic stream.")}async openPeerUni(e,t){if(typeof this.backend.openPeerUni!="function")throw new Error("Selected runtime adapter does not support openPeerUni().");return this.backend.openPeerUni(e,t)}async beginOpenRtcMediaPublication(e){if(typeof this.backend.beginOpenRtcMediaPublication!="function")throw new Error("Selected runtime adapter does not support media publications.");return this.backend.beginOpenRtcMediaPublication(e)}async encodeOpenRtcMediaSample(e){if(typeof this.backend.encodeOpenRtcMediaSample!="function")throw new Error("Selected runtime adapter does not support media samples.");return this.backend.encodeOpenRtcMediaSample(e)}async pauseOpenRtcMediaPublication(e){if(typeof this.backend.pauseOpenRtcMediaPublication!="function")throw new Error("Selected runtime adapter does not support media publications.");await this.backend.pauseOpenRtcMediaPublication(e);}async retireOpenRtcMediaPublication(e){if(typeof this.backend.retireOpenRtcMediaPublication!="function")throw new Error("Selected runtime adapter does not support media publications.");await this.backend.retireOpenRtcMediaPublication(e);}async retireOpenRtcMediaReceiver(e,t){if(typeof this.backend.retireOpenRtcMediaReceiver!="function")throw new Error("Selected runtime adapter does not support media receivers.");await this.backend.retireOpenRtcMediaReceiver(e,t);}async decodeOpenRtcMediaChunk(e){if(typeof this.backend.decodeOpenRtcMediaChunk!="function")throw new Error("Selected runtime adapter does not support the media protocol.");return this.backend.decodeOpenRtcMediaChunk(e)}async decodeOpenRtcMediaControl(e){if(typeof this.backend.decodeOpenRtcMediaControl!="function")throw new Error("Selected runtime adapter does not support the media protocol.");return this.backend.decodeOpenRtcMediaControl(e)}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 excludeAutoConnect(e,t){if(typeof this.backend.excludeAutoConnect!="function")throw new Error("Selected runtime adapter does not support excludeAutoConnect().");return this.backend.excludeAutoConnect(e,t)}async isConnected(e){return this.backend.isConnected(e)}async getConnectionStates(){return typeof this.backend.getConnectionStates!="function"?[]:this.backend.getConnectionStates()}onStateChange(e){return typeof this.backend.onStateChange!="function"?()=>{}:this.backend.onStateChange(e)}async sendExplicitFilePath(e,t,n){if(typeof this.backend.sendExplicitFilePath!="function")throw new Error("Selected runtime adapter does not support sendExplicitFilePath().");return this.backend.sendExplicitFilePath(e,t,n)}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)}async sendPeerMessage(e,t){if(typeof this.backend.sendPeerMessage!="function")throw new Error("Selected runtime adapter does not support native peer messages.");await this.backend.sendPeerMessage(e,t);}onPeerMessage(e){return typeof this.backend.onPeerMessage!="function"?()=>{}:this.backend.onPeerMessage(e)}capabilities(){let e=this.backend;return typeof e.capabilities=="function"?e.capabilities():t()}async onIncomingNativeMessage(e){let t=this.backend;return typeof t.onIncomingNativeMessage!="function"?()=>{}:t.onIncomingNativeMessage(e)}unwrap(){return this.backend}setCoreClient(e){let t=this.backend;typeof t.setCoreClient=="function"&&t.setCoreClient(e);}};export{a};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
function v(c){return [...new Set(c.capabilityKeys.filter(s=>typeof s=="string").map(s=>s.trim()).filter(Boolean))]}async function h(c,s){if(!c||typeof c!="object")return;let t=c.stream,e=[];t?.recv&&e.push(t.recv.cancel(s)),t?.send&&e.push(t.send.abort(s)),await Promise.allSettled(e);}var d=class{constructor(){this.host=null;this.consumers=new Map;this.hostReader=null;this.hostPump=null;this.consecutiveEstablishedFaults=0;this.closed=false;}register(s,t){if(this.closed)throw new Error("[OpenRTC] Native projection broker is closed.");let e=s.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,deviceListeners:new Set,latestDevices:null}),{__openrtcNativeCapabilityProjection:true,capabilityKey:e,incoming_streams:()=>this.incomingStreams(e),onStateChange:i=>this.subscribeState(e,i),onPeerMessage:i=>this.subscribePeerData(e,i),onDevices:i=>this.subscribeDevices(e,i),isCurrentTransport:(i,n)=>this.currentHost().isCurrentTransport(i,n)}}unregister(s){let t=s.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(),e.deviceListeners.clear(),e.latestDevices=null,this.consumers.size===0&&this.cancelHostReader("no active native capabilities");}}subscribeState(s,t){let e=this.requireConsumer(s);return e.stateListeners.add(t),this.ensureHostPump(),()=>{e.stateListeners.delete(t),this.cancelHostReaderIfIdle();}}subscribePeerData(s,t){let e=this.requireConsumer(s);return e.messageListeners.add(t),this.ensureHostPump(),()=>{e.messageListeners.delete(t),this.cancelHostReaderIfIdle();}}subscribeDevices(s,t){let e=this.requireConsumer(s);return e.deviceListeners.add(t),this.ensureHostPump(),e.latestDevices&&t(e.latestDevices),()=>{e.deviceListeners.delete(t),this.cancelHostReaderIfIdle();}}requireConsumer(s){if(this.closed)throw new Error("[OpenRTC] Native projection broker is closed.");let t=this.consumers.get(s);if(!t)throw new Error(`[OpenRTC] Native capability '${s}' 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(s){if(this.closed)throw new Error("[OpenRTC] Native projection broker is closed.");let t=this.requireConsumer(s);if(t.stream)return t.stream;let e;return e=new ReadableStream({start:i=>{t.controller=i,this.ensureHostPump();},cancel:()=>{t.stream===e&&(t.controller=null,t.stream=null),this.cancelHostReaderIfIdle();}},{highWaterMark:32}),t.stream=e,e}ensureHostPump(){if(this.hostPump||this.closed)return;let s=false;this.hostPump=this.pumpHost().then(t=>{s=t;}).finally(()=>{this.hostPump=null,this.hostReader=null,s&&!this.closed&&this.hasActiveConsumers()&&this.ensureHostPump();});}async pumpHost(){let s=this.currentHost(),t=null,e=false;try{let i=await s.incoming_projected_streams();if(this.closed)return await i.cancel("OpenRTC native root client closed").catch(()=>{}),!1;for(t=i.getReader(),this.hostReader=t;!this.closed&&this.hasActiveConsumers();){let{done:n,value:o}=await t.read();if(n){if(!this.closed&&this.host!==s&&this.hasActiveConsumers())return !0;for(let r of this.consumers.values()){try{r.controller?.close();}catch{}r.controller=null,r.stream=null,r.stateListeners.clear(),r.messageListeners.clear(),r.deviceListeners.clear(),r.latestDevices=null;}return this.consecutiveEstablishedFaults=0,!1}this.consecutiveEstablishedFaults=0;let u=v(o);if(o.kind==="stream"){let r=u.length===1?u[0]:null,a=r?this.consumers.get(r):void 0;if(!a?.controller||(a.controller.desiredSize??0)<=0){await h(o.payload,r?`inactive native capability ${r}`:"ambiguous unscoped native projection");continue}a.controller.enqueue(o.payload);continue}for(let r of u){let a=this.consumers.get(r);if(a)if(o.kind==="connection-state")for(let l of a.stateListeners)l(o.payload);else if(o.kind==="devices"){a.latestDevices=o.payload.devices;for(let l of a.deviceListeners)l(o.payload.devices);}else for(let l of a.messageListeners)l(o.payload);}}return !this.closed&&this.host!==s&&this.hasActiveConsumers()}catch(i){if(!this.closed){e=t!==null&&this.consecutiveEstablishedFaults===0,e?this.consecutiveEstablishedFaults=1:this.consecutiveEstablishedFaults=0;for(let n of this.consumers.values()){try{n.controller?.error(i);}catch{}n.controller=null,n.stream=null,e||(n.stateListeners.clear(),n.messageListeners.clear(),n.deviceListeners.clear(),n.latestDevices=null);}}return e}finally{let i=t;if(this.hostReader===i&&(this.hostReader=null),i)try{i.releaseLock();}catch{}typeof s.releaseNativeProjectionSubscription=="function"&&await s.releaseNativeProjectionSubscription().catch(()=>{});}}hasActiveConsumers(){return [...this.consumers.values()].some(s=>s.controller!==null||s.stateListeners.size>0||s.messageListeners.size>0||s.deviceListeners.size>0)}cancelHostReaderIfIdle(){this.hasActiveConsumers()||this.cancelHostReader("no active native projection consumers");}async cancelHostReader(s){let t=this.hostReader;this.hostReader=null,await t?.cancel(s).catch(()=>{});}async close(){if(this.closed){await this.hostPump;return}this.closed=true;for(let s of this.consumers.values())try{s.controller?.close();}catch{}this.consumers.clear(),this.host=null,await this.cancelHostReader("OpenRTC native root client closed"),await this.hostPump;}};export{d as a};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import {j,d as d$1,c}from'./chunk-42TNJH5S.js';var E=/^[A-Za-z0-9_.:@-]+$/,P=/^[A-Za-z0-9_-]{43}$/,C=/^[A-Za-z0-9_.:@-]+$/,k=/^[A-Za-z0-9._-]+$/,x=120*6e4,A=new TextEncoder;function d(r,e,t=160){let n=r.trim();if(!n||n.length>t||!E.test(n))throw new TypeError(`[OpenRTC] ${e} is invalid.`);return n}function h(r,e,t=Number.MAX_SAFE_INTEGER){if(!Number.isSafeInteger(r)||r<1||r>t)throw new RangeError(`[OpenRTC] ${e} must be a positive safe integer.`);return r}function K(r){let e="";for(let t of r)e+=String.fromCharCode(t);return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,"")}async function g(r,e){let t=await r.publicJwk();if(t.kty!=="OKP"||t.crv!=="Ed25519"||typeof t.x!="string"||!P.test(t.x)||t.d!==void 0)throw new TypeError(`[OpenRTC] ${e} must return an Ed25519 public JWK.`);return {kty:"OKP",crv:"Ed25519",x:t.x}}async function y(r,e,t){let n=await r.sign(e);if(!(n instanceof Uint8Array)||n.byteLength!==64)throw new TypeError(`[OpenRTC] ${t} returned an invalid Ed25519 signature.`);return K(n)}function T(r){if(!/^pk_(?:live|test)_[A-Za-z0-9]+$/.test(r))throw new TypeError("[OpenRTC] apiKey is invalid.");return `app_${r.slice(-16)}`}function u(r){return r!==null&&typeof r=="object"&&!Array.isArray(r)?r:null}function v(r,e,t,n){if(typeof r!="string"||r.length<1||r.length>t||r!==r.trim()||n&&!n.test(r))throw new Error(`[OpenRTC] authority service grant ${e} is invalid.`);return r}function O(r){let e=v(r,"gatewayUrl",2048),t;try{t=new URL(e);}catch{throw new Error("[OpenRTC] authority service grant gatewayUrl is invalid.")}let n=t.protocol==="http:"&&["127.0.0.1","localhost","::1"].includes(t.hostname.toLowerCase());if(t.protocol!=="https:"&&!n||t.username||t.password||t.search||t.hash)throw new Error("[OpenRTC] authority service grant gatewayUrl is invalid.");return e}function N(r,e){let t=u(r),n=u(t?.avenue),i=u(t?.roomAuthority),a=u(i?.assignmentPublicKeyJwk),c=Date.now(),o=t?.expiresAtMs,s=t?.maxPeers;if(!t||t.protocolVersion!==2||t.architecture!=="authority"||n?.kind!=="room"||n.id!==e.roomId||i?.serviceId!==e.serviceId||i.generation!==e.generation||!Array.isArray(i.shardIds)||i.shardIds.length!==e.shardIds.length||i.shardIds.some((m,l)=>m!==e.shardIds[l])||a?.kty!=="OKP"||a.crv!=="Ed25519"||a.x!==e.assignmentPublicKeyX||!Number.isSafeInteger(o)||o<=c||o>c+x||!Number.isSafeInteger(s)||s<1||s>e.maxPeers)throw new Error("[OpenRTC] authority service grant response is inconsistent.");return {protocolVersion:2,gatewayUrl:O(t.gatewayUrl),routeKey:v(t.routeKey,"routeKey",256,C),token:v(t.token,"token",24e3,k),expiresAtMs:o,avenue:{kind:"room",id:e.roomId},maxPeers:s,architecture:"authority",roomAuthority:{serviceId:e.serviceId,generation:e.generation,shardIds:[...e.shardIds],assignmentPublicKeyJwk:{kty:"OKP",crv:"Ed25519",x:e.assignmentPublicKeyX}}}}var p=class{constructor(e){if(this.apiKey=e.apiKey,this.applicationTag=T(e.apiKey),typeof e.grantIssuer!="function")throw new TypeError("[OpenRTC] ServiceNode requires a browser-safe grantIssuer.");if(this.grantIssuer=e.grantIssuer,this.serviceId=d(e.serviceId,"serviceId",80),this.generation=h(e.generation,"generation"),this.shardIds=[...new Set(e.shardIds.map(t=>d(t,"shardId",80)))].sort(),this.shardIds.length<1||this.shardIds.length>64||this.shardIds.length!==e.shardIds.length)throw new RangeError("[OpenRTC] shardIds must contain 1..64 unique identifiers.");this.deviceId=d(e.deviceId,"deviceId"),this.deviceSigner=e.deviceSigner,this.assignmentSigner=e.assignmentSigner;}async requestGrant(e){let t=d(e.roomId,"roomId"),n=d(e.runtimeInstanceId,"runtimeInstanceId");if(!P.test(e.ticketFingerprint))throw new TypeError("[OpenRTC] ticketFingerprint is invalid.");e.maxPeers!==void 0&&h(e.maxPeers,"maxPeers",50);let i=await g(this.assignmentSigner,"assignmentSigner.publicJwk()"),a=await g(this.deviceSigner,"deviceSigner.publicJwk()"),c=crypto.randomUUID().replace(/-/g,""),o=Math.floor(Date.now()/1e3),s=["openrtc:v2:authority-service-grant",this.applicationTag,t,this.serviceId,String(this.generation),this.shardIds.join(","),i.x,n,c,o].join(":"),m={avenue:{kind:"room",id:t},serviceId:this.serviceId,generation:this.generation,shardIds:this.shardIds,assignmentPublicKeyJwk:i,deviceId:this.deviceId,runtimeInstanceId:n,ticketFingerprint:e.ticketFingerprint,deviceProof:{publicKeyJwk:a,nonce:c,issuedAt:o,signature:await y(this.deviceSigner,A.encode(s),"deviceSigner.sign()")},...e.maxPeers===void 0?{}:{maxPeers:e.maxPeers},...e.refreshGrant?{refreshGrant:e.refreshGrant}:{},features:e.features??{}},l=`authority_${crypto.randomUUID().replace(/-/g,"")}`,R=await this.grantIssuer({apiKey:this.apiKey,idempotencyKey:l,body:m});return N(R,{roomId:t,serviceId:this.serviceId,generation:this.generation,shardIds:this.shardIds,assignmentPublicKeyX:i.x,maxPeers:e.maxPeers??50})}async devicePublicKey(){return g(this.deviceSigner,"deviceSigner.publicJwk()")}async assignmentPublicKey(){return g(this.assignmentSigner,"assignmentSigner.publicJwk()")}async signDeviceBytes(e){return y(this.deviceSigner,e,"deviceSigner.sign()")}async signAssignment(e){let t=e.ttlMs??6e4;h(t,"ttlMs",2*6e4);let n=d(e.shardId,"shardId",80);if(!this.shardIds.includes(n))throw new RangeError("[OpenRTC] assignment shard is not owned by this service.");let i=e.priorityDeviceIds??[],a=e.relevantEntityIds??[];if(i.length>8||a.length>32)throw new RangeError("[OpenRTC] assignment exceeds the 8-edge or 32-entity bound.");let c=Date.now(),o={policyVersion:"room-authority-assignment-v1",serviceId:this.serviceId,generation:this.generation,revision:h(e.revision,"revision"),subjectDeviceId:d(e.subjectDeviceId,"subjectDeviceId"),shardId:n,priorityDeviceIds:i.map(s=>d(s,"priorityDeviceId")),relevantEntityIds:a.map(s=>d(s,"relevantEntityId")),issuedAtMs:c,expiresAtMs:c+t};if(new Set(o.priorityDeviceIds).size!==o.priorityDeviceIds.length||new Set(o.relevantEntityIds).size!==o.relevantEntityIds.length)throw new RangeError("[OpenRTC] assignment identifiers must be unique.");return {assignment:o,signature:await y(this.assignmentSigner,A.encode(JSON.stringify(o)),"assignmentSigner.sign()")}}},I=class{constructor(e,t,n){this.room=e;this.authority=t;this.onClosed=n;this.releaseRuntimeAlias=d$1(this,e);}get kind(){return this.room.kind}get id(){return this.room.id}get peers(){return this.room.peers}get channels(){return this.room.channels}get diagnostics(){return this.room.diagnostics}get closed(){return this.room.closed}get membership(){return this.room.membership}state(e){return this.room.state(e)}channel(e){return this.room.channel(e)}onConnection(e){return this.room.onConnection(e)}architecture(){return this.room.architecture()}onArchitectureChanged(e){return this.room.onArchitectureChanged(e)}authorityAssignment(){return this.room.authorityAssignment()}onAuthorityAssignmentChanged(e){return this.room.onAuthorityAssignmentChanged(e)}leave(){return this.retire(()=>this.room.leave())}close(){return this.retire(()=>this.room.close())}async publishAssignment(e){let t=await this.authority.signAssignment(e);return await c(this.room).advanced.runtime.publishAuthorityAssignment(t),t.assignment}retire(e){return this.retirement??(this.retirement=e().finally(()=>{this.releaseRuntimeAlias(),this.onClosed();}))}},S=class{constructor(e){this.options=e;this.rooms=new Map;this.connectionListeners=new Set;this.connectionCleanups=new Map;this.closed=false;if("secretKey"in e)throw new TypeError("[OpenRTC] ServiceNode never accepts secretKey; delegate short-lived grants.");this.authority=new p(e);}listen(e){if(this.closed)throw new Error("[OpenRTC] ServiceNode is closed.");let t=d(e,"roomId"),n=this.rooms.get(t);if(n)return n.promise;let i={};return i.promise=this.openRoom(t,()=>this.evictRoom(t,i)).catch(a=>{throw this.evictRoom(t,i),a}),this.rooms.set(t,i),i.promise}onConnection(e){if(this.connectionListeners.add(e),this.connectionListeners.size===1)for(let[t,n]of this.rooms)n.promise.then(i=>this.attachConnectionListener(t,i),()=>{});return ()=>{if(this.connectionListeners.delete(e),this.connectionListeners.size===0){for(let t of this.connectionCleanups.values())t();this.connectionCleanups.clear();}}}async close(){if(this.closed)return;this.closed=true;for(let t of this.connectionCleanups.values())t();this.connectionCleanups.clear();let e=await Promise.allSettled([...this.rooms.values()].map(t=>t.promise));await Promise.all(e.flatMap(t=>t.status==="fulfilled"?[t.value.close()]:[])),this.rooms.clear(),this.connectionListeners.clear();}async openRoom(e,t){let n=await this.options.client.devices.localId();if(n!==this.options.deviceId)throw new Error("[OpenRTC] ServiceNode deviceId must match the client installation.");let[i,a]=await Promise.all([this.authority.devicePublicKey(),this.authority.assignmentPublicKey()]),c=await j(this.options.client,{roomId:e,serviceId:this.options.serviceId,generation:this.options.generation,shardIds:this.options.shardIds,deviceId:n,maxPeers:this.options.maxPeers,irohRelay:this.options.irohRelay!==false,devicePublicKeyX:i.x,assignmentPublicKeyX:a.x,deviceSign:s=>this.authority.signDeviceBytes(s),grantProvider:async s=>{if(s.avenue.kind!=="room"||s.avenue.id!==e)throw new Error("[OpenRTC] ServiceNode grant request escaped its room.");if(s.deviceId!==n)throw new Error("[OpenRTC] ServiceNode grant request escaped its device.");return this.authority.requestGrant({roomId:e,runtimeInstanceId:s.runtimeInstanceId,ticketFingerprint:s.ticketFingerprint,maxPeers:this.options.maxPeers,refreshGrant:s.refreshGrant,features:{irohRelay:this.options.irohRelay!==false}})}}),o=new I(c,this.authority,t);return this.attachConnectionListener(e,o),o}evictRoom(e,t){this.rooms.get(e)===t&&(this.rooms.delete(e),this.connectionCleanups.get(e)?.(),this.connectionCleanups.delete(e));}attachConnectionListener(e,t){this.closed||this.connectionListeners.size===0||this.connectionCleanups.has(e)||this.connectionCleanups.set(e,t.onConnection(n=>{for(let i of this.connectionListeners)i({room:t,connection:n});}));}};
|
|
2
|
+
export{p as a,S as b};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
var N="openrtc:endpoint-ticket:v1";function I(n){let e=n.lastIndexOf(".");return {irohTicket:e>=0?n.slice(0,e):n,tokenSuffix:e>=0?n.slice(e+1):null}}function K(){return y(24)}function Y(n,e,c,a,i){return `${n}.${k(n,e,c,a,i)}`}function R(n,e){let c=A(e);return !c||!D(n,c)?null:c}function k(n,e,c,a,i){return btoa(JSON.stringify({t:e,s:c,m:a,h:S(n),...typeof i=="number"?{e:i}:{},a:N,n:L()})).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function A(n){try{let e=n.replace(/-/g,"+").replace(/_/g,"/"),c=(4-e.length%4)%4;return JSON.parse(atob(e+"=".repeat(c)))}catch{return null}}function D(n,e){return !(typeof e.h=="string"&&e.h!==S(n)||typeof e.e=="number"&&Number.isFinite(e.e)&&e.e<=Date.now()||typeof e.a=="string"&&e.a!==N||typeof e.n=="string"&&!U(e.n))}function L(){return y(16)}function y(n){let e=new Uint8Array(n);return crypto.getRandomValues(e),btoa(String.fromCharCode(...e)).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function U(n){try{let e=n.replace(/-/g,"+").replace(/_/g,"/"),c=(4-e.length%4)%4;return atob(e+"=".repeat(c)).length===16}catch{return false}}function s(n,e){return n>>>e|n<<32-e}var w=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298];function S(n){let e=new TextEncoder().encode(n),c=e.length*8,a=e.length+1;for(;a%64!==56;)a+=1;let i=new Uint8Array(a+8);i.set(e),i[e.length]=128;let p=new DataView(i.buffer);p.setUint32(a,Math.floor(c/4294967296),false),p.setUint32(a+4,c>>>0,false);let r=[1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225],o=new Array(64);for(let d=0;d<i.length;d+=64){for(let t=0;t<16;t+=1)o[t]=p.getUint32(d+t*4,false);for(let t=16;t<64;t+=1){let h=s(o[t-15],7)^s(o[t-15],18)^o[t-15]>>>3,_=s(o[t-2],17)^s(o[t-2],19)^o[t-2]>>>10;o[t]=o[t-16]+h+o[t-7]+_>>>0;}let[x,u,b,m,f,g,l,T]=r;for(let t=0;t<64;t+=1){let h=s(f,6)^s(f,11)^s(f,25),_=f&g^~f&l,E=T+h+_+w[t]+o[t]>>>0,O=s(x,2)^s(x,13)^s(x,22),C=x&u^x&b^u&b,P=O+C>>>0;T=l,l=g,g=f,f=m+E>>>0,m=b,b=u,u=x,x=E+P>>>0;}r[0]=r[0]+x>>>0,r[1]=r[1]+u>>>0,r[2]=r[2]+b>>>0,r[3]=r[3]+m>>>0,r[4]=r[4]+f>>>0,r[5]=r[5]+g>>>0,r[6]=r[6]+l>>>0,r[7]=r[7]+T>>>0;}return r.map(d=>d.toString(16).padStart(8,"0")).join("")}
|
|
2
|
+
export{I as a,K as b,Y as c,R as d};
|
|
@@ -0,0 +1 @@
|
|
|
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-25CN4MLA.js';import {c,e,d,f,b as b$1}from'./chunk-XMYBBLYK.js';import {a as a$2}from'./chunk-OT7IPLZE.js';import {a as a$3}from'./chunk-CNAW5BZ3.js';import {c as c$1}from'./chunk-CCCYE3XN.js';import {a as a$4}from'./chunk-JPBW67B3.js';function M(u){if(!u)return null;let e=2166136261;for(let t=0;t<u.length;t+=1)e^=u.charCodeAt(t),e=Math.imul(e,16777619);return `fp-${(e>>>0).toString(16).padStart(8,"0")}`}var _=class _{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(o=>this.submitDesiredPeers(o),this.currentLocalNodeId()??void 0));}wakeRustAutoConnectOwner(){return this.deps.isTicketOnlyMode()||!this.startedAutoConnectKey||this.wakeSubmission?false:(this.wakeSubmission=this.deps.waitForWasmClient(500).then(async e=>{e&&typeof e.wake_browser_auto_connect=="function"&&await e.wake_browser_auto_connect();}).finally(()=>{this.wakeSubmission=null;}),true)}submitDesiredPeers(e){if(!this.startedAutoConnectKey)return;let 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 o=this.desiredPeersByDeviceId.get(i);if(o&&(!n||!o.nodeId||o.nodeId===n))return o}return n?Array.from(this.desiredPeersByDeviceId.values()).find(o=>o.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 o=this.desiredPeerSubmissionQueue.then(async()=>{if(this.startedAutoConnectKey!==e)return;let r=await this.deps.waitForWasmClient();if(this.startedAutoConnectKey===e){if(!r||typeof r.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(c){console.warn("[WasmSignaling] failed to retain desired-peer admission token",{deviceId:s.deviceId,nodeId:s.nodeId,error:c});}})),n){if(typeof r.submit_browser_desired_peers_with_sparse_fanout!="function"){await r.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 r.submit_browser_desired_peers_with_sparse_fanout(t,JSON.stringify(i),this.deps.capabilityKey,this.localDesiredPeerDeviceId,this.deps.localDeviceKeyX,true);}else await r.submit_browser_desired_peers(t,JSON.stringify(i));}});return this.desiredPeerSubmissionQueue=o.catch(r=>{console.warn("[WasmSignaling] failed to submit browser desired peers to Rust",{revision:t,error:r});}),o}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,o){if(this.deps.isTicketOnlyMode())return;this.stopPresenceLoop();let r=this.presenceStartGeneration;this.presenceState={userId:e,localNodeId:t,ticket:n,metadata:o,deviceName:i};let s=this.deps.resolveWebLogicalDeviceId(),c=await this.deps.withWebPresenceMetadata(o,s);r!==this.presenceStartGeneration||this.presenceState===null||await this.deps.updatePresence(t,n,true,_.PRESENCE_LEASE_MS,c,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;}};_.PRESENCE_LEASE_MS=15*6e4;var R=_;function ne(){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 oe(){let u=await import('./openrtc-KERRTMSG.js');return {initWasm:e=>u.default(e??ne()),WasmClient:u.WasmClient,start:u.start}}function re(u){try{let e=u.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 se(u){let e=typeof u=="string"?u.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,o=n?re(n):null,r=o&&typeof o.t=="string"&&o.t.trim().length>0?o.t.trim():null,s=o&&typeof o.s=="string"&&o.s.trim().length>0?o.s.trim():null,c=o&&typeof o.m=="number"&&Number.isFinite(o.m)?o.m:null;return {present:true,irohFingerprint:M(i),tokenFingerprint:M(r),tokenSuffixFingerprint:M(n),scope:s,maxConnections:c}}function E(u,e,t={}){let i=typeof u.finishSend=="function"?u.finishSend.bind(u):typeof u.finish_send=="function"?u.finish_send.bind(u):null,n=typeof u.cancelSend=="function"?u.cancelSend.bind(u):typeof u.cancel_send=="function"?u.cancel_send.bind(u):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 o=e.getWriter(),r=new WritableStream({write:s=>o.write(s),async close(){await o.close(),await i();},async abort(s){await n?.(),await o.abort(s);}});return a$4(r,n)}var p=class p{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(r=false)=>this.currentUser?.getToken?.(r)??null,getAppCheckToken:async(r=false)=>{let s=this.authContext?.appCheckTokenProvider??this.options.attestationTokenProvider;return s?s(r):a().getAppCheckToken(r)},getLocalDeviceId:()=>this.resolveWebLogicalDeviceId(),getDefaultDeviceName:()=>this.getDefaultBrowserDeviceName(),getPlatformType:()=>this.options.coordinationPlatformType??"web",normalizeDevice:(r,s)=>this.normalizeDevice(r,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:(r,s)=>this.waitForWasmClient(r,s),warnMissingWasmOnce:r=>this.warnMissingWasmOnce(r),resolveWebLogicalDeviceId:()=>this.resolveWebLogicalDeviceId(),withWebPresenceMetadata:(r,s)=>this.withWebPresenceMetadata(r,s),updatePresence:(r,s,c,a,d,h)=>this.updatePresence(r,s,c,a,d,h),updateExcludedPeers:(r,s)=>this.getCoordinationSignaling().updateDevice(r,{excludedPeers:s}),getCoordinationSignaling:()=>this.getCoordinationSignaling(),rememberRouteRepairTokenFromTicket:r=>this.coreClient?.rememberRouteRepairTokenFromTicket?.(r)??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 o=a();this.app=o.getApp(),this.auth=o.getAuth(),o.onAuthStateChanged(r=>{if(this.authContext)return;if(this.isSpaceMode()){this.authListeners.forEach(a=>a(this.toRuntimeIdentity(r)));return}let s=r?.uid??null,c=this.lastObservedFirebaseUserId;this.lastObservedFirebaseUserId=s,c&&c!==s&&this.stopAuthActivity({userId:c}),this.browserCoordinationSignaling?.handleScopeChange()??this.coordinationHost.handleScopeChange(),this.authListeners.forEach(a=>a(this.toRuntimeIdentity(r)));});}async loadBrowserWasmRuntime(){return oe()}get tag(){return this.appTag}capabilities(){return t()}getDeviceIdentityStorageKey(){let e=f(this.options);return `${p.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(),o=null;try{let d=localStorage.getItem(i);o=d?JSON.parse(d):null;}catch{o=null;}let r=typeof o?.deviceId=="string"?o.deviceId.trim():"",s=typeof o?.expiresAt=="number"?o.expiresAt:void 0;if(t==="persistent"){let d=r||this.createRandomDeviceId();return localStorage.setItem(i,JSON.stringify({deviceId:d})),d}if(r&&typeof s=="number"&&s>n){let d=n+p.EPHEMERAL_DEVICE_ID_TTL_MS;return localStorage.setItem(i,JSON.stringify({deviceId:r,expiresAt:d})),r}let c=this.createRandomDeviceId(),a=n+p.EPHEMERAL_DEVICE_ID_TTL_MS;return localStorage.setItem(i,JSON.stringify({deviceId:c,expiresAt:a})),c}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(o){console.warn("[WasmBridge] ensureBrowserPlatformAuth failed (non-fatal):",o);}else if(!this.isTicketOnlyMode()&&!this.usesProviderNeutralGrant()&&!e&&t)try{await this.auth?.signOut();}catch(o){console.warn("[WasmBridge] Failed to clear injected browser auth session:",o);}finally{this.injectedBrowserAuthSessionActive=false;}this.syncWasmAuthToken(),!this.isTicketOnlyMode()&&i!==n&&await(this.browserCoordinationSignaling?.handleScopeChange()??this.coordinationHost.handleScopeChange()),this.authListeners.forEach(o=>o(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 o=await i.prepareSparseFanoutMessage(e,t),r=new Uint8Array(o.signingInput??o.signing_input??[]),s=await n(r);return new Uint8Array(await i.finalizeSparseFanoutMessage(String(o.requestId??o.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 o=await n.acceptSparseFanoutMessage(e,t,i);return {payload:new Uint8Array(o.payload??[]),authorDeviceId:String(o.authorDeviceId??o.author_device_id??""),authorPeerId:String(o.authorPeerId??o.author_peer_id??""),topologyRevision:Number(o.topologyRevision??o.topology_revision),hop:Number(o.hop),forwardPeerIds:Array.isArray(o.forwardPeerIds??o.forward_peer_ids)?(o.forwardPeerIds??o.forward_peer_ids).map(String):[],forwardPeerLimit:Number(o.forwardPeerLimit??o.forward_peer_limit),forwardQueueCapacity:Number(o.forwardQueueCapacity??o.forward_queue_capacity),...o.forward==null?{}:{forward:new Uint8Array(o.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 o=this.stabilizeConnectionState(e);this.lastDeliveredConnectionStates.set(o.connectionId,o);let s=(n??this.lastDeliveredConnectionStates).get(o.connectionId);this.sameConnectionState(s,o)||(n&&n.set(o.connectionId,o),t(o));}get browserPresenceLoopState(){return this.presenceManager.presenceLoopState}set browserPresenceLoopState(e){this.presenceManager.presenceLoopState=e;}get currentUser(){if(this.authContext?.userId){let e=this.authContext.token??null,t=this.authContext.tokenProvider;return {id:this.authContext.userId,getToken:async(i=false)=>{if(e&&(!i||!t))return e;if(t)try{let o=await t(i);if(o)return o}catch{}let 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,o,r){if(this.isTicketOnlyMode())return;let s=this.resolveWebLogicalDeviceId(),c=this.getDeviceIdPersistenceMode()==="ephemeral"?p.EPHEMERAL_DEVICE_ID_TTL_MS:n,a=await this.withWebPresenceMetadata(o,s);this.presenceManager.updatePresenceLoopState({userId:this.getCurrentUserId()??"",localNodeId:e,ticket:t,metadata:a,deviceName:r?.trim()||this.getDefaultBrowserDeviceName()}),await this.getCoordinationSignaling().updatePresence(e,t,i,c,a,r);}async refreshLivePresence(e,t,i,n){if(this.isTicketOnlyMode())return;let o=this.resolveWebLogicalDeviceId(),r=await this.withWebPresenceMetadata(i,o);this.presenceManager.updatePresenceLoopState({userId:this.getCurrentUserId()??"",localNodeId:e,ticket:t,metadata:r,deviceName:n?.trim()||this.getDefaultBrowserDeviceName()}),await this.getCoordinationSignaling().updatePresence(e,t,true,15*6e4,r,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 o=this.normalizeDeviceStatusSnapshot({...n,connectionStatus:n.online?"online":"disconnected"}),r=typeof n.nodeId=="string"?n.nodeId.trim():"";if(!r||typeof i?.iroh_path_kind!="function"||typeof i?.iroh_transport_rtt_ms!="function")return o;try{let[s,c]=await Promise.all([i.iroh_path_kind(r),i.iroh_transport_rtt_ms(r)]);if(typeof c!="number"||!Number.isFinite(c))return o;let a=Math.max(0,Math.round(c)),d={};if(s==="direct-lan")d.irohLan=a;else if(s==="direct-quic")d.iroh=a;else if(s==="ble")d.ble=a;else if(s==="relay")d.irohRelay=a;else if(s==="webrtc")d.webrtc=a;else if(s==="moq")d.moq=a;else return o;return {...o,latencyMs:a,latencyByTransport:d}}catch(s){return d$1("[WasmBridge] iroh transport latency unavailable",{deviceId:n.deviceId,error:s instanceof Error?s.message:String(s)}),o}}))}async getPeerSession(e){let t=await this.waitForWasmClient(500);if(t&&typeof t.peer_session=="function"){let i=await t.peer_session(e);return !i||typeof i!="object"?null:this.normalizePeerSessionSnapshot(i)}return this.warnMissingWasmOnce("getPeerSession"),null}async listPeerSessions(){let e=await this.waitForWasmClient(500);if(e&&typeof e.peer_sessions=="function"){let t=await e.peer_sessions();return (Array.isArray(t)?t:[]).map(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 waitForSettledScope(e,t){let i=await this.waitForWasmClient(500);if(i&&typeof i.wait_for_settled_scope=="function"){let n=await i.wait_for_settled_scope(e,t);return !n||typeof n!="object"?null:this.normalizePeerSessionSnapshot(n)}return this.warnMissingWasmOnce("waitForSettledScope"),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:E(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 o=await i.open_peer_bi_transport_only(e,t);if(!o?.recv||!o?.send)throw new Error("WASM open_peer_bi_transport_only returned an invalid bidirectional stream");return {readable:o.recv,writable:E(o,o.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),o=n?.writable??n;if(!o)throw new Error("WASM open_peer_uni returned an invalid writable stream");return {writable:E(n,o)}}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),o=n?.sendPeerDatagram;if(typeof o!="function")throw new Error("[OpenRTC] This WASM build does not include protected peer datagrams.");return await o.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 o=n;return {peerId:typeof o.peerId=="string"?o.peerId:null,deviceId:typeof o.deviceId=="string"?o.deviceId:null,deviceIdHint:typeof o.deviceIdHint=="string"?o.deviceIdHint:null,nodeId:typeof o.nodeId=="string"?o.nodeId:null}};if(typeof t.peer_session=="function")try{let n=await t.peer_session(e),o=i(n);if(o.peerId||o.deviceId||o.deviceIdHint||o.nodeId)return o}catch{}if(typeof t.peer_snapshot=="function")try{return i(await t.peer_snapshot(e))}catch{}}return this.warnMissingWasmOnce("resolvePeerIdentity"),{peerId:null,deviceId:null,deviceIdHint:null,nodeId:null}}onDevicesChange(e,t){return this.isTicketOnlyMode()?(e([]),()=>{}):this.getCoordinationSignaling().onDevicesChange(e,t)}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 o=this.stabilizeConnectionState(n);this.lastDeliveredConnectionStates.set(o.connectionId,o),e$1("[OpenRTC][route-escalation] observed Rust connection state",{connectionId:o.connectionId,deviceId:o.deviceId??o.deviceIdHint??null,remoteNodeId:o.remoteNodeId??null,state:o.state,transportGeneration:o.transportGeneration??null,routeGeneration:o.routeGeneration??null}),this.escalateManagedApplicationRoute(o);});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 o=this.authScopedRuntimeGeneration,r=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 c=await r.ensureManagedApplicationRoute({ticket:n.ticket,connectionId:e.connectionId,remoteNodeId:e.remoteNodeId??n.nodeId,expectedDeviceId:n.deviceId,timeoutMs:2e4});if(o!==this.authScopedRuntimeGeneration)return;let a=c,d=a.id?.trim()||e.connectionId,h=a.remoteNodeId?.trim()||e.remoteNodeId?.trim()||a.deviceId?.trim()||n.deviceId;if(r.hasApplicationRouteForPeer?.(d,h)!==true&&r.hasApplicationRouteForPeer?.(d,h)!==true)throw new Error(`application crypto was not ready for ${h}`)})().catch(c=>{o===this.authScopedRuntimeGeneration&&console.warn("[OpenRTC][route-escalation] Rust-managed route remains pending",{connectionId:e.connectionId,deviceId:n.deviceId,remoteNodeId:e.remoteNodeId??n.nodeId,error:c?.message??String(c)});}).finally(()=>{if(this.applicationRouteEscalations.get(e.connectionId)===s){this.applicationRouteEscalations.delete(e.connectionId);let c=this.lastDeliveredConnectionStates?.get(e.connectionId),a=c?[c.transportGeneration??0,c.routeGeneration??0].join(":"):null;c&&a!==t&&o===this.authScopedRuntimeGeneration&&queueMicrotask(()=>this.escalateManagedApplicationRoute(c));}}),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=e.endpointTicket?.trim()??"",n=e.admissionToken?.trim()??"",o=e.admissionScope?.trim()??"",r=!i,s=i;if(r&&(!e.deviceId||!n||!o||typeof t.connect_known_device_with_token!="function"))throw new Error("WASM connectToDevice requires an endpoint ticket or supported known-device admission intent.");let c=Date.now();e$1("[WasmBridge][ROUTE-ESCALATION] starting managed transport dial",{deviceId:e.deviceId??null,ticket:se(i),knownDeviceAdmission:r,hasCoreClient:!!this.coreClient});let a=r?await(async()=>{let h=Date.now(),l=Math.max(1,e.timeoutMs??3e4),m=()=>Math.max(1,l-(Date.now()-h)),y=e.admissionPeerUserId?.trim()??"";if(y){let v=(await this.getCoordinationSignaling().waitForFriendDevice(y,e.deviceId,Math.min(1e4,m()))).ticket?.trim()??"";if(!v)throw new Error(`[pluto-rtc] authorized device ${e.deviceId} did not publish an endpoint ticket.`);if(typeof t.observe_known_device_endpoint!="function")throw new Error("WASM runtime does not support provider-authorized endpoint observations.");await t.observe_known_device_endpoint(e.deviceId,v),s=a$3(v).irohTicket;}return t.connect_known_device_with_token(e.deviceId,n,o,e.admissionMaxConnections??0,e.admissionExpiresAtMs==null?null:BigInt(Math.floor(e.admissionExpiresAtMs)),Math.min(1e4,m()))})():await t.connect_device(e.deviceId??null,i);e$1("[WasmBridge][ROUTE-ESCALATION] managed transport dial completed",{deviceId:e.deviceId??null,remoteNodeId:a?.remoteNodeId??null,connectionId:a?.connectionId??null,elapsedMs:Date.now()-c});let d=s;if(d&&this.coreClient){let h=this.coreClient;try{e$1("[WasmBridge][ROUTE-ESCALATION] starting typed application connection",{deviceId:e.deviceId??null,remoteNodeId:a?.remoteNodeId??null,connectionId:a?.connectionId??null});let l=await h.ensureManagedApplicationRoute({ticket:d,connectionId:a?.connectionId??null,remoteNodeId:a?.remoteNodeId??null,expectedDeviceId:e.deviceId??null,approvedScope:a?.approvedScope??null,timeoutMs:2e4}),m=typeof l?.remoteNodeId=="string"?l.remoteNodeId.trim():"",y=typeof l?.deviceId=="string"?l.deviceId.trim():"",g=m||a?.remoteNodeId?.trim?.()||y||e.deviceId?.trim?.()||"",v=typeof h.hasApplicationRouteForPeer=="function"?h.hasApplicationRouteForPeer.bind(h):null;if(!(!!g&&v?.(l?.id??void 0,g)===!0)&&g&&typeof h.waitForApplicationCryptoForPeer=="function"&&!(!!await h.waitForApplicationCryptoForPeer(g,2e4)&&(!v||v(l?.id??void 0,g)===!0)))throw console.warn("[WasmBridge][ROUTE-ESCALATION] application route still pending after managed dial",{deviceId:e.deviceId??null,remoteNodeId:m||(a?.remoteNodeId??null),connectionId:a?.connectionId??null,peerForCrypto:g,elapsedMs:Date.now()-c}),Object.assign(new Error(`application crypto was not ready for ${g}`),{applicationCryptoNotReady:!0});e$1("[WasmBridge][ROUTE-ESCALATION] application route ready",{deviceId:e.deviceId??null,remoteNodeId:m||(a?.remoteNodeId??null),connectionId:a?.connectionId??null,elapsedMs:Date.now()-c});}catch(l){if(l?.applicationCryptoNotReady)throw l;return console.warn("[WasmBridge] Managed transport connected; TS application route escalation is still pending",{deviceId:e.deviceId??null,remoteNodeId:a?.remoteNodeId??null,connectionId:a?.connectionId??null,error:l?.message??String(l)}),a}}return a}forceReconnect(){this.isTicketOnlyMode()||!this.app||!this.auth||this.presenceManager.wakeRustAutoConnectOwner();}startPresenceLoop(e,t,i,n,o){return this.presenceManager.startPresenceLoop(e,t,i,n,o)}ensureSpaceNamespaceIdPromise(){if(this.cachedSpaceNamespaceId)return Promise.resolve(this.cachedSpaceNamespaceId);if(!this.spaceNamespaceIdPromise){let e=this.options.apiKey?.trim()??"",t=this.options.spaceKey?.trim()??"";if(!e||!t)return Promise.resolve(null);this.spaceNamespaceIdPromise=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(),o=(Array.isArray(n)?n:[]).map(r=>this.normalizeStateSnapshot(r)).filter(r=>!!r);return o.length>0&&d$1("[WasmBridge] replaying current wasm connection states",o.map(r=>({connectionId:r.connectionId,deviceId:r.deviceId??null,deviceIdHint:r.deviceIdHint??null,remoteNodeId:r.remoteNodeId??null,state:r.state,transportState:r.transportState??null,protocolState:r.protocolState??null,routable:r.routable??null}))),o}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,o=false,r=a=>{let d=a.detail,h=this.normalizeStateSnapshot(d),l=typeof d?.connectionId=="string"?d.connectionId.trim():"";if(!l||o)return;if(h&&(h.state==="closed"||h.state==="failed"||h.state==="disconnected")){this.deliverConnectionState(h,e,"rust-event-detail",t);return}let m=(i.get(l)??0)+1;i.set(l,m);let y=this.authScopedRuntimeGeneration;(async()=>{let g=await this.waitForWasmClient(500);if(!(o||y!==this.authScopedRuntimeGeneration||i.get(l)!==m)){if(g&&typeof g.connection_state=="function"){let v=await g.connection_state(l),w=this.normalizeStateSnapshot(v);if(!o&&y===this.authScopedRuntimeGeneration&&i.get(l)===m&&w){this.deliverConnectionState(w,e,"rust-event",t);return}}!o&&y===this.authScopedRuntimeGeneration&&i.get(l)===m&&h&&this.deliverConnectionState(h,e,"rust-event-detail",t);}})().catch(g=>{o||console.warn("[WasmBridge] Failed to read Rust connection state after lifecycle event",{connectionId:l,error:g});});},s=typeof window<"u"?window:null,c=typeof s?.addEventListener=="function"&&typeof s?.removeEventListener=="function";return c&&s.addEventListener("connection-state-changed",r),this.getConnectionStates().then(a=>{!o&&n===this.authScopedRuntimeGeneration&&a.forEach(d=>{i.has(d.connectionId)||this.deliverConnectionState(d,e,"replay",t);});}).catch(a=>{console.warn("[WasmBridge] Failed to replay wasm connection states after subscription:",a);}),()=>{o=true,i.clear(),c&&s.removeEventListener("connection-state-changed",r);}}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(r=>r.trim().length>0)?.trim()??"";if(!i||i==="."||i==="..")return p.FALLBACK_EXPLICIT_FILE_NAME;let n="";for(let r of i){if([...n].length>=p.MAX_EXPLICIT_FILE_NAME_CHARS)break;let s=r.charCodeAt(0);r==="/"||r==="\\"||r==="\0"||s<32||s===127?n+="_":n+=r;}let o=n.trim();return !o||o==="."||o===".."?p.FALLBACK_EXPLICIT_FILE_NAME:o}sanitizeExplicitMimeType(e){let t=typeof e=="string"?e.trim():"";if(!t)return p.FALLBACK_EXPLICIT_MIME_TYPE;let i="";for(let n of t){if(i.length>=p.MAX_EXPLICIT_MIME_TYPE_CHARS)break;let o=n.charCodeAt(0);o<33||o>126||n==='"'||n==="\\"?i+="_":i+=n;}return i.length>0?i:p.FALLBACK_EXPLICIT_MIME_TYPE}assertExplicitTransferHeaderSize(e){if(e.byteLength===0||e.byteLength>p.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,o){let r=o?.headerFrame===true?4:0,s=new Uint8Array(25+r+n.byteLength);s[0]=p.EXPLICIT_FILE_PROTOCOL_TYPE,s.set(e,1);let c=new DataView(s.buffer);c.setUint32(17,t,false),c.setUint32(21,i,false);let a=o?.headerFrame===true?29:25;return o?.headerFrame===true&&c.setUint32(25,n.byteLength,false),s.set(n,a),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 r=e.transferId&&e.transferId.trim().length>0?e.transferId:`transfer-${Date.now()}`;typeof e.receiverPlatformType=="string"?e.receiverPlatformType.trim().toLowerCase():null;let c=e.remoteNodeId?.trim()||t?.remoteNodeId?.trim()||t?.deviceId?.trim();if(e$1("[WasmBridge] sendExplicitFileData start",{connectionId:e.connectionId??null,connectionRemoteNodeId:t?.remoteNodeId??null,remoteNodeId:c??null,fileName:i.name,fileSize:i.size,transferId:r}),!c)throw new Error("Web explicit transfer requires an active connection with a resolved remote node ID");let a=await this.waitForWasmClient();if(!a)throw new Error("WASM explicit transfer requires an initialized WASM client");let d=new TextEncoder,h={transfer_id:r,filename:this.sanitizeExplicitFileName(i.name),size:i.size,mime_type:this.sanitizeExplicitMimeType(i.type)},l=d.encode(JSON.stringify(h));this.assertExplicitTransferHeaderSize(l);let m=new Uint8Array(4);new DataView(m.buffer).setUint32(0,l.byteLength,false);let y=new Uint8Array(m.byteLength+l.byteLength);y.set(m,0),y.set(l,m.byteLength);let g=async()=>{let v=a.open_peer_bi_explicit_file_sender;if(typeof v!="function")return false;let w=await v.call(a,c,5e3),S=w?.writable??w?.send;if(!S||typeof S.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:c,transferId:e.transferId??null,applicationCryptoWrapped:w.applicationCryptoWrapped===true});let C=E(w,S,{requireFinish:true}).getWriter(),T=false;try{await C.write(y);let P=new Uint8Array(await i.arrayBuffer());for(let b=0;b<P.byteLength;b+=p.EXPLICIT_FILE_CHUNK_SIZE_BYTES){let ie=P.slice(b,Math.min(b+p.EXPLICIT_FILE_CHUNK_SIZE_BYTES,P.byteLength));await C.write(ie);}}catch(P){throw T=true,P}finally{try{await C.close();}catch(P){if(!T)throw P}finally{C.releaseLock();}}return true};try{if(await g())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:c,transferId:r,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);}};p.EXPLICIT_FILE_PROTOCOL_TYPE=2,p.EXPLICIT_FILE_CHUNK_SIZE_BYTES=64*1024,p.MAX_EXPLICIT_TRANSFER_HEADER_BYTES=64*1024,p.FALLBACK_EXPLICIT_FILE_NAME="openrtc-transfer.bin",p.MAX_EXPLICIT_FILE_NAME_CHARS=180,p.FALLBACK_EXPLICIT_MIME_TYPE="application/octet-stream",p.MAX_EXPLICIT_MIME_TYPE_CHARS=255,p.WEB_DEVICE_ID_STORAGE_PREFIX="pluto_rtc_web_device_identity",p.EPHEMERAL_DEVICE_ID_TTL_MS=o.browserIdentity.ephemeralDeviceIdTtlMs;var te=p;export{oe as a,te as b};
|