openrtc 3.0.1 → 3.0.2
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 +31 -0
- package/dist/{Connection-BZ6piJsh.d.ts → Connection-BGVBMbWg.d.ts} +5 -0
- package/dist/{DelegatingRuntimeAdapter-s3QvVuTj.d.ts → DelegatingRuntimeAdapter-JmhmwKTC.d.ts} +2 -2
- package/dist/{IpcRuntimeAdapter-CghYNfcc.d.ts → IpcRuntimeAdapter-DMQoN2XL.d.ts} +2 -2
- package/dist/{WasmBridge-JZGJHSSU.js → WasmBridge-L76OAD5U.js} +1 -1
- package/dist/{assembly-BEMgeExQ.d.ts → assembly-DGrOqsLW.d.ts} +2 -2
- package/dist/{capabilities-fJ11v3xA.d.ts → capabilities-DsKud7Sw.d.ts} +1 -1
- package/dist/{chunk-RSQCDTS2.js → chunk-4TOWICSH.js} +1 -1
- package/dist/{chunk-W4IU7H7H.js → chunk-7MAQEBMM.js} +1 -1
- package/dist/{chunk-C3TAFNG6.js → chunk-A2TFNNXG.js} +1 -1
- package/dist/chunk-EI6PDMHI.js +2 -0
- package/dist/{chunk-LTMH2AIS.js → chunk-HL3TV2QA.js} +1 -1
- package/dist/chunk-IUU6JCLK.js +1 -0
- package/dist/{chunk-F3IZBMAT.js → chunk-NC375DSH.js} +1 -1
- package/dist/{chunk-W45XAU3I.js → chunk-TFOFTLTV.js} +1 -1
- package/dist/chunk-UCNK7KB6.js +2 -0
- package/dist/{coreClient-BYWmk_1O.d.ts → coreClient-ByXs38IP.d.ts} +3 -3
- package/dist/coreClient.d.ts +4 -4
- package/dist/coreClient.js +1 -1
- package/dist/{deviceHandle-3P46T7SV.js → deviceHandle-Y3SYSCJ6.js} +1 -1
- package/dist/external-broadcast.d.ts +5 -5
- package/dist/external-broadcast.js +1 -1
- package/dist/index.d.ts +7 -7
- package/dist/index.js +1 -1
- package/dist/ipcFactory-OJMZCIIQ.js +1 -0
- package/dist/native.d.ts +6 -6
- package/dist/native.js +1 -1
- package/dist/node.d.ts +7 -7
- package/dist/node.js +2 -2
- package/dist/openrtc-2VLRZHQ3.js +2 -0
- package/dist/openrtc_bg.wasm +0 -0
- package/dist/room-QHKIFLR7.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 +5 -5
- package/dist/runtime/factories.js +1 -1
- package/dist/runtime/index.d.ts +19 -12
- package/dist/runtime/index.js +1 -1
- package/dist/server-browser.d.ts +5 -5
- package/dist/server.d.ts +5 -5
- package/dist/server.js +1 -1
- package/dist/service-node.d.ts +5 -5
- package/dist/service-node.js +1 -1
- package/dist/testing/native.d.ts +5 -5
- package/dist/testing/native.js +1 -1
- package/dist/testing.d.ts +5 -5
- package/dist/testing.js +1 -1
- package/dist/transport/index.d.ts +2 -2
- package/dist/{types-BXYC9Q5H.d.ts → types-YGlXXpQA.d.ts} +17 -5
- package/native/darwin-arm64/openrtc-node-host +0 -0
- package/native/darwin-arm64/openrtc-node-host.manifest.json +4 -4
- package/native/darwin-x64/openrtc-node-host +0 -0
- package/native/darwin-x64/openrtc-node-host.manifest.json +4 -4
- package/native/linux-x64/openrtc-node-host +0 -0
- package/native/linux-x64/openrtc-node-host.manifest.json +4 -4
- package/package.json +1 -1
- package/dist/chunk-CAUMGKP4.js +0 -2
- package/dist/chunk-O7Z6WLGA.js +0 -1
- package/dist/chunk-R6J4PZDI.js +0 -2
- package/dist/ipcFactory-2MDPNX5M.js +0 -1
- package/dist/openrtc-6RZZ7PEN.js +0 -2
- package/dist/room-P5SHPIGF.js +0 -1
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import {b as b$1,d,l}from'./chunk-OT7IPLZE.js';import {a}from'./chunk-TPF643LU.js';import {a as a$1,c,b as b$2,e}from'./chunk-L7N4T2PX.js';import {d as d$1}from'./chunk-72MN7BNQ.js';import*as U from'tweetnacl';function fe(t){if(typeof t!="string"||!t||t.trim()!==t||new TextEncoder().encode(t).byteLength>256||/[\u0000-\u001f\u007f-\u009f]/.test(t))throw new Error("Invalid transfer peer demand identity.")}function We(t){if(!Number.isSafeInteger(t)||t<=0)throw new Error("Invalid transfer peer demand generation.")}function qe(t){if(!t||typeof t!="object")throw new Error("Invalid transfer peer demand request.");if(fe(t.id),fe(t.deviceId),!["fileTransfer","driveAccess","contentSync"].includes(t.purpose)||Object.keys(t).some(e=>!["id","deviceId","purpose"].includes(e)))throw new Error("Invalid transfer peer demand request.")}function Vt(t,e,n=false){if(typeof t!="string"||new TextEncoder().encode(t).byteLength>2048)throw new Error("Invalid transfer peer demand response.");let i=JSON.parse(t);if(i===null&&n)return null;if(!i||typeof i!="object")throw new Error("Invalid transfer peer demand response.");let r=i;if(qe({id:r.id,deviceId:r.deviceId,purpose:r.purpose}),We(r.generation),r.id!==e.id||e.generation!==void 0&&r.generation!==e.generation||e.deviceId!==void 0&&r.deviceId!==e.deviceId||e.purpose!==void 0&&r.purpose!==e.purpose||!["waitingForPeer","queued","admitted"].includes(r.state))throw new Error("Invalid transfer peer demand response.");return r}function Qt(){throw new Error("[OpenRTC] The rollback-only Firebase auth host is not installed. OpenRTC 2.0 applications must supply an AuthProvider; legacy runtimes must import openrtc/auth explicitly.");}var $e="openrtc-trust";var be="identity",k="managed-room-keys",E="managed-room-state";function Ve(){if(typeof globalThis.indexedDB>"u")throw new Error("[OpenRTC] Managed rooms require durable IndexedDB storage.");return globalThis.indexedDB}function Je(){return new Promise((t,e)=>{let n=Ve().open($e,2);n.onupgradeneeded=()=>{let i=n.result;i.objectStoreNames.contains(be)||i.createObjectStore(be),i.objectStoreNames.contains(k)||i.createObjectStore(k),i.objectStoreNames.contains(E)||i.createObjectStore(E);},n.onsuccess=()=>t(n.result),n.onerror=()=>e(n.error??new Error("managed room database failed")),n.onblocked=()=>e(new Error("managed room database upgrade is blocked"));})}function ie(t){return new Promise((e,n)=>{t.onsuccess=()=>e(t.result),t.onerror=()=>n(t.error??new Error("managed room storage failed"));})}function O(t){return new Promise((e,n)=>{t.oncomplete=()=>e(),t.onerror=()=>n(t.error??new Error("managed room storage failed")),t.onabort=()=>n(t.error??new Error("managed room storage aborted"));})}function Qe(t,e,n){return `${t}:${e}:${n}`}function Ye(t,e){return `${t}:${e}`}function we(t){return new TextEncoder().encode(`openrtc-managed-room-state-v1:${t}`)}async function Ze(t,e){let n=t.transaction(k,"readonly"),i=O(n),r=await ie(n.objectStore(k).get(e));if(await i,r)return r;let o=await crypto.subtle.generateKey({name:"AES-GCM",length:256},false,["encrypt","decrypt"]),s=t.transaction(k,"readwrite"),c=O(s);s.objectStore(k).add(o,e);try{return await c,o}catch{let a=t.transaction(k,"readonly"),d=O(a),u=await ie(a.objectStore(k).get(e));if(await d,!u)throw new Error("[OpenRTC] Managed room wrapping key could not be persisted.");return u}}function Xe(t){let e=t;return e?.schemaVersion===1&&e.wrappedKey instanceof Uint8Array&&e.wrappingNonce instanceof Uint8Array&&e.wrappingNonce.byteLength===12&&(e.sealedState===void 0||e.sealedState instanceof Uint8Array)?e:null}async function re(t,e,n){let i=await Je(),r=Qe(t,e,n);try{let o=await Ze(i,Ye(t,e)),s=i.transaction(E,"readonly"),c=O(s),a=Xe(await ie(s.objectStore(E).get(r)));await c;let d,u;if(a){let p=await crypto.subtle.decrypt({name:"AES-GCM",iv:a.wrappingNonce,additionalData:we(r)},o,a.wrappedKey).catch(()=>{throw new Error("[OpenRTC] Managed room state key authentication failed.")});if(d=new Uint8Array(p),d.byteLength!==32)throw new Error("[OpenRTC] Managed room state key is invalid.");u=a;}else {d=crypto.getRandomValues(new Uint8Array(32));let p=crypto.getRandomValues(new Uint8Array(12)),y=new Uint8Array(await crypto.subtle.encrypt({name:"AES-GCM",iv:p,additionalData:we(r)},o,d));u={schemaVersion:1,wrappingNonce:p,wrappedKey:y};let l=i.transaction(E,"readwrite"),R=O(l);l.objectStore(E).add(u,r),await R;}return {wrappingKey:d,sealedState:u.sealedState,async persist(p){if(!(p instanceof Uint8Array)||p.byteLength===0)throw new Error("[OpenRTC] Managed room sealed state is invalid.");let y=i.transaction(E,"readwrite"),l=O(y);y.objectStore(E).put({...u,sealedState:p},r),await l,u={...u,sealedState:p};},close(){d.fill(0),i.close();}}}catch(o){throw i.close(),o}}var tt=3e4,nt=5*6e4,it=3e4,$=100,V=48*1024,rt=50,Se=64*1024,Re=12,ot=10*6e4,st=5*6e4,L=15e3,at=15e3,Ie=1e3,Ae=250;function Te(t){let e=[...new Set(t.map(n=>String(n??"").trim().toLowerCase()).filter(Boolean))].sort();if(e.length>Ae)throw new Error(`Coordination excluded-peer set exceeds ${Ae} devices.`);return e}var ct="openrtc.v2",dt="openrtc.auth.";function Ee(t){try{let e=t.split(".")[1];if(!e)return null;let n=e.replace(/-/g,"+").replace(/_/g,"/").padEnd(Math.ceil(e.length/4)*4,"="),i=JSON.parse(globalThis.atob(n));return i!==null&&typeof i=="object"&&!Array.isArray(i)?i:null}catch{return null}}function Pe(t){let e=Ee(t)?.jti;return typeof e=="string"&&e.length>0?e:null}var g=class extends b$2{constructor(n,i,r,o={}){super({code:a$1.COORDINATION_DISCONNECTED,plane:"coordination",...d$1(r)?e({...o,code:r,message:n,retryable:i}):{},message:n,retryable:i});this.gatewayCode=r;this.name="CoordinationConnectError";}},G=class extends b$2{constructor(n,i,r,o={}){let s=e({...o,code:n,message:i,retryable:r});super({...s,retryable:r,message:`Coordination gateway ${n}: ${i}`});this.name="CoordinationGatewayProtocolError";this.gatewayCode=n;}};function Me(t){return t instanceof g&&/\bstale-budget\b/i.test(t.message)}function H(t){if(!t||typeof t!="object")return false;let e=t;return e.gatewayCode==="credential-revoked"||e.code==="credential-revoked"||e.reason==="device-certificate-revoked"}function Ce(t){if(H(t))return true;if(typeof t!="object"||t===null)return false;let e=t;if(e.retryable===false)return true;let n=e.status??e.statusCode,i=typeof n=="number"?n:Number.NaN;if(Number.isInteger(i)&&i>=400&&i<500&&![408,425,429].includes(i))return true;let r=String(e.code??"");return ["functions/unauthenticated","functions/permission-denied","functions/invalid-argument","functions/failed-precondition","functions/resource-exhausted","unauthenticated","permission-denied","invalid-argument","failed-precondition","resource-exhausted"].includes(r)}function lt(t){let e=new Uint32Array(1);return crypto.getRandomValues(e),Math.max(1,Math.round(t*(.75+e[0]/4294967295*.5)))}function A(t){if(typeof crypto.randomUUID=="function")return `${t}:${crypto.randomUUID()}`;let e=new Uint8Array(16);crypto.getRandomValues(e);let n=Array.from(e,i=>i.toString(16).padStart(2,"0")).join("");return `${t}:${n}`}async function ut(t){let e=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(t)),n="";for(let i of new Uint8Array(e))n+=String.fromCharCode(i);return btoa(n).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,"")}function oe(t){if(!/^[A-Za-z0-9_-]+$/.test(t))throw new Error("[OpenRTC] Managed room payload encoding is invalid.");let e=t.replace(/-/g,"+").replace(/_/g,"/"),n=atob(e.padEnd(Math.ceil(e.length/4)*4,"=")),i=new Uint8Array(n.length);for(let r=0;r<n.length;r+=1)i[r]=n.charCodeAt(r);return i}function pt(t,e,n){let i=new URL(t);if(i.search||i.hash||i.username||i.password)throw new Error("[OpenRTC] Coordination gateway endpoint must not contain credentials, query, or fragment.");if(i.protocol==="https:")i.protocol="wss:";else if(i.protocol==="http:")i.protocol="ws:";else if(i.protocol!=="wss:"&&i.protocol!=="ws:")throw new Error("[OpenRTC] Coordination gateway endpoint must use HTTPS/WSS.");return i.pathname=`${i.pathname.replace(/\/+$/,"")}/v${n}/connect/${e}`,i.toString()}function ke(t){let e=new URL(t);return e.protocol==="wss:"&&(e.protocol="https:"),e.protocol==="ws:"&&(e.protocol="http:"),e.origin}var J=class t{constructor(e){this.options=e;this.runtimeInstanceId=A("runtime");this.socket=null;this.serviceObservationGeneration=0;this.socketReady=false;this.activeGrantToken=null;this.refillCredential=null;this.activeGrantJti=null;this.activeAvenue=null;this.activeGrantExpiresAtMs=0;this.activeGrantProtocolVersion=1;this.leaseRefreshMode="off";this.signalBatchMode="off";this.pendingSignalQueue=[];this.signalFlushScheduled=null;this.pendingLeaseRefreshKey=null;this.authenticationRefreshTail=Promise.resolve();this.authenticationRefreshes=new Map;this.connectPromise=null;this.desiredPresence=null;this.friendObservationPresence=null;this.desiredExcludedPeers=[];this.devices=new Map;this.sparseMembers=new Map;this.sparseRoutes=new Map;this.pendingMembershipPageSnapshot=null;this.pendingRosterPageSnapshot=null;this.sparseTopologyRevision=0;this.roomArchitectureSnapshot=null;this.roomAuthorityAssignment=null;this.roomAuthorityAssignmentExpiry=null;this.roomEncryptionEpoch=0;this.managedWasmClient=null;this.peerAdmissionRuntime=null;this.peerAdmissionScope=null;this.peerAdmissionRevision=0;this.managedStateProvider=re;this.managedState=null;this.managedInitialization=null;this.managedActions=Promise.resolve();this.managedReceiveTail=null;this.managedPublishQueue=[];this.activeManagedPublication=null;this.managedPublishScheduled=false;this.managedMigrationPending=false;this.managedPublishAwaitingLease=false;this.managedMessageListeners=new Set;this.deviceListeners=new Set;this.architectureListeners=new Set;this.authorityAssignmentListeners=new Set;this.deviceStreams=new Set;this.sessionStreams=new Set;this.pendingAcks=new Map;this.pendingMessages=[];this.roomConnections=new Map;this.friendConnections=new Map;this.reconnectTimer=null;this.authRefreshTimer=null;this.keepaliveTimer=null;this.pendingAuthRefresh=null;this.budgetRenewalPromise=null;this.budgetRenewalEpoch=0;this.reconnectAttempt=0;this.reconnectOutageStartedAtMs=null;this.reconnectCircuitOpen=false;this.hostAvailable=true;this.connectionReadyWaiters=new Set;this.hostResumeReconnectPromise=null;this.lastHostResumeReconnectAtMs=0;this.desiredPresenceRevision=0;this.appliedPresenceRevision=0;this.stopped=false;this.credentialRevoked=false;if(this.initialExcludedPeers=Te(e.initialExcludedPeers??[]),this.desiredExcludedPeers=[...this.initialExcludedPeers],e.gateway.environment!=="staging"&&e.gateway.environment!=="production")throw new Error("[OpenRTC] Coordination gateway environment is invalid.");let n=new URL(e.gateway.endpoint),i=n.hostname==="127.0.0.1"||n.hostname==="localhost"||n.hostname==="[::1]",r=n.protocol==="https:"||n.protocol==="wss:",o=e.gateway.testingAllowInsecureLoopback===true&&i&&(n.protocol==="http:"||n.protocol==="ws:");if(!r&&!o)throw new Error("[OpenRTC] Coordination gateway requires HTTPS/WSS.");if(n.username||n.password||n.search||n.hash)throw new Error("[OpenRTC] Coordination gateway credentials and parameters cannot be supplied in its URL.")}async updatePresence(e,n,i,r,o,s){let c=this.desiredPresence;if(i&&this.options.roomArchitecture==="authority"){let u=this.options.avenueOverride;if(u?.kind!=="room"||!this.peerAdmissionRuntime)throw new Error("[OpenRTC] Authority rooms require Rust peer admission support.");let p=`v2:room:${u.id}`;this.peerAdmissionRuntime.__requireScopePeerAdmission(p),this.peerAdmissionScope=p;}this.desiredPresence={localNodeId:e,ticket:n,online:i,ttlMs:r,metadata:o,deviceName:s?.trim()||this.options.getDefaultDeviceName()},(!c||c.localNodeId!==e||c.ticket!==n||c.online!==i||c.ttlMs!==r||c.metadata!==o||c.deviceName!==this.desiredPresence.deviceName)&&(this.desiredPresenceRevision+=1,this.reconnectCircuitOpen=false,this.reconnectAttempt=0,this.reconnectOutageStartedAtMs=null);for(let u of this.friendConnections.values())u.updatePresence(e,n,i,r,o,this.desiredPresence.deviceName).catch(()=>{});let d=this.desiredPresenceRevision;try{await this.ensureConnected();}catch(u){if(!(u instanceof g)||!u.retryable)throw u;await this.waitForConnectionReady();}this.appliedPresenceRevision>=d||(c&&c.ticket!==n&&await this.refreshAuthentication(),await this.sendOperation({v:1,type:"presence.upsert",idempotencyKey:A("presence"),ttlMs:r,device:this.gatewayDevice(this.desiredPresence)}),this.appliedPresenceRevision=Math.max(this.appliedPresenceRevision,d));}async setOffline(e){this.desiredPresence&&(this.desiredPresence.online=false,this.socket?.readyState===WebSocket.OPEN&&await this.sendOperation({v:1,type:"presence.offline",idempotencyKey:A("offline")}));}async reconnectAfterHostResume(){if(this.desiredPresence){if(this.hostResumeReconnectPromise)return this.hostResumeReconnectPromise;if(!(Date.now()-this.lastHostResumeReconnectAtMs<at)){this.lastHostResumeReconnectAtMs=Date.now(),this.hostResumeReconnectPromise=(async()=>{(this.socket?.readyState===WebSocket.OPEN||this.socketReady)&&this.stopSocket(),await this.ensureConnected();})();try{await this.hostResumeReconnectPromise;}finally{this.hostResumeReconnectPromise=null;}}}}setHostAvailability(e){let n=e.available&&!this.hostAvailable;this.hostAvailable=e.available;for(let i of this.roomConnections.values())i.setHostAvailability(e);for(let i of this.friendConnections.values())i.setHostAvailability(e);if(!e.available){this.reconnectTimer&&clearTimeout(this.reconnectTimer),this.reconnectTimer=null,this.connectPromise&&!this.socketReady&&this.stopSocket();return}n&&this.desiredPresence&&!this.socketReady&&!this.connectPromise&&!this.reconnectCircuitOpen&&!this.stopped&&this.ensureConnected().catch(i=>this.scheduleReconnect(i));}async updateDevice(e,n){if(e!==this.options.getLocalDeviceId())throw new Error("A coordination socket can update only its local device.");let i=n;if(n.excludedPeers!==void 0){let r=Te(n.excludedPeers);this.desiredExcludedPeers=r,i={...n,excludedPeers:r};}await this.ensureConnected(),await this.sendOperation({v:1,type:"device.patch",idempotencyKey:A("device-patch"),patch:i});}async deleteDevice(e){if(this.options.credentialPurpose!=="device-control"&&(!this.socketReady||this.socket?.readyState!==WebSocket.OPEN)){let n=new t({...this.options,credentialPurpose:"device-control"});try{await n.deleteDevice(e);}finally{n.stopAuthActivity();}return}await this.ensureConnected();try{await this.sendOperation({v:1,type:"device.delete",idempotencyKey:A("device-delete"),targetDeviceId:e});}finally{this.options.credentialPurpose==="device-control"&&this.stopSocket();}}async cleanupStaleDevices(){}async searchDevices(e){return this.snapshot(e)}async listDevices(e){return this.snapshot(e)}onDevicesChange(e,n){let i=r=>e(n?r.filter(o=>o.nodeId!==n):r);return this.deviceListeners.add(i),i(this.snapshot()),this.desiredPresence&&this.ensureConnected().catch(()=>{}),()=>this.deviceListeners.delete(i)}onRoomArchitectureChange(e){return this.architectureListeners.add(e),this.roomArchitectureSnapshot&&e({...this.roomArchitectureSnapshot}),()=>this.architectureListeners.delete(e)}onRoomAuthorityAssignmentChange(e){return this.authorityAssignmentListeners.add(e),e(this.roomAuthorityAssignmentSnapshot()),()=>this.authorityAssignmentListeners.delete(e)}async publishAuthorityAssignment(e){await this.ensureConnected(),await this.sendOperation({v:1,type:"authority.assignment.publish",idempotencyKey:A("authority-assignment"),assignment:e.assignment,signature:e.signature});}setWasmClient(e){this.setManagedRoomRuntime(e,re);}setManagedRoomRuntime(e,n){let i=e;this.peerAdmissionRuntime=i&&typeof i.__requireScopePeerAdmission=="function"&&typeof i.__updateScopePeerAdmission=="function"?i:null;let r=e;this.managedWasmClient=r&&typeof r.__initManagedRoomGroup=="function"&&typeof r.__handleManagedRoomPreparePage=="function"&&typeof r.__applyManagedRoomAuthority=="function"&&typeof r.__handleManagedRoomArtifactChunk=="function"&&typeof r.__sealManagedRoomPayload=="function"&&typeof r.__openManagedRoomPayload=="function"&&typeof r.__forgetManagedRoomGroup=="function"?r:null,this.managedStateProvider=n,this.roomArchitectureSnapshot?.effective==="managed"&&this.enqueueManagedWork(()=>this.ensureManagedGroupInitialized());}onManagedRoomMessage(e){return this.managedMessageListeners.add(e),()=>this.managedMessageListeners.delete(e)}async publishManagedRoomMessage(e){return new Promise((n,i)=>{if(this.stopped||this.managedPublishQueue.length>=Ie){i(new Error("[OpenRTC] Managed room publication queue is unavailable."));return}this.managedPublishQueue.push({input:e,resolve:n,reject:i}),this.scheduleManagedPublish();})}async subscribeDevices(){let e=null;return new ReadableStream({start:n=>{e=n,this.deviceStreams.add(n);let i=this.snapshot().map(r=>({type:"added",device:r}));i.length>0&&n.enqueue(i);},cancel:()=>{e&&this.deviceStreams.delete(e),e=null;}})}async createSession(e){await this.ensureConnected(),await this.sendOperation({v:1,type:"session.put",idempotencyKey:A("session-put"),sessionId:e.connectionId,session:e,expiresAtMs:e.expiresAt??Date.now()+15*6e4});}async updateSession(e,n){await this.ensureConnected(),await this.sendOperation({v:1,type:"session.put",idempotencyKey:A("session-update"),sessionId:this.unscopedId(e),session:n,expiresAtMs:typeof n.expiresAt=="number"?n.expiresAt:Date.now()+15*6e4});}async subscribeSessions(e){let n=null;return new ReadableStream({start:i=>{n=i,this.sessionStreams.add(i);},cancel:()=>{n&&this.sessionStreams.delete(n),n=null;}})}async sendMessage(e,n,i,r){let o=this.serviceObservationGeneration;if(await this.ensureConnected(),o!==this.serviceObservationGeneration||!this.socket)throw new g("Signal connection retired before dispatch.",false);let s={socket:this.socket,generation:o};this.assertSignalCurrent(s);let c=Object.freeze({targetDeviceId:this.unscopedId(e),payload:n,state:i,replyPayload:r});if(this.signalBatchMode!=="ordered-v1"){let a=A("signal");return await this.sendOperation({v:1,type:"signal.send",idempotencyKey:a,...c},d=>this.assertSignalCurrent(s,d)),this.assertSignalCurrent(s,false),a}return new Promise((a,d)=>{this.pendingSignalQueue.push({input:c,binding:s,resolve:a,reject:d}),!this.signalFlushScheduled&&(this.signalFlushScheduled=s,queueMicrotask(()=>{this.signalFlushScheduled===s&&(this.signalFlushScheduled=null,this.flushSignalQueue());}));})}assertSignalCurrent(e,n=true){if(e.generation!==this.serviceObservationGeneration||this.socket!==e.socket||e.socket.readyState!==WebSocket.OPEN||!this.socketReady||this.stopped||this.credentialRevoked||n&&(!Number.isSafeInteger(this.activeGrantExpiresAtMs)||this.activeGrantExpiresAtMs<=Date.now()))throw new g("Signal connection retired before completion.",false)}rejectQueuedSignals(e){this.signalFlushScheduled=null;for(let n of this.pendingSignalQueue.splice(0))n.reject(e);}flushSignalQueue(){let e=this.pendingSignalQueue.splice(0);for(;e.length>0;){let n=e.shift();try{this.assertSignalCurrent(n.binding);}catch(a){n.reject(a);continue}let i=[n],r=A("signal-batch"),o=a=>({v:1,type:"signal.send.batch",idempotencyKey:r,signals:a.map(d=>d.input)});for(;i.length<rt&&e.length>0;){let a=e[0];if(a.binding.socket!==n.binding.socket||a.binding.generation!==n.binding.generation||new TextEncoder().encode(JSON.stringify(o([...i,a]))).byteLength>Se)break;i.push(e.shift());}let s=i.length>1,c=Object.freeze(s?{...o(i),signals:Object.freeze(i.map(a=>a.input))}:{v:1,type:"signal.send",idempotencyKey:A("signal"),...n.input});if(new TextEncoder().encode(JSON.stringify(c)).byteLength>Se){n.reject(new Error("Signaling frame exceeds 64 KiB."));continue}this.dispatchSignalFrame(c,n.binding,i,s);}}async dispatchSignalFrame(e,n,i,r){try{await this.sendOperation(e,o=>this.assertSignalCurrent(n,o)),this.assertSignalCurrent(n,!1),i.forEach((o,s)=>o.resolve(r?`${e.idempotencyKey}:${s}`:e.idempotencyKey));}catch(o){for(let s of i)s.reject(o);}}async pollMessages(e){return this.pendingMessages.splice(0,this.pendingMessages.length)}watchFriendDevices(e,n){let i=[...new Set(e.map(c=>c.trim()).filter(Boolean))];if(i.length>25)throw new RangeError(`watchFriendDevices accepts at most ${25} unique friend IDs per runtime.`);for(let c of i)if(c.length>128||c.includes("/"))throw new TypeError('Friend user IDs must be 1-128 characters and cannot contain "/".');let r={value:false},o=new Map,s=[];n(new Map);for(let c of i){if(!c||c===this.options.getCurrentUserId())continue;let a=this.friendConnection(c);s.push(a.onDevicesChange(d=>{if(r.value)return;let u=d.filter(p=>p.online);o.set(c,u),n(new Map(o));}));}return ()=>{r.value=true;for(let c of s)c();for(let c of i)this.friendConnections.get(c)?.stopAuthActivity(),this.friendConnections.delete(c);}}waitForFriendDevice(e,n,i=1e4){let r=e.trim(),o=n.trim();return !r||!o?Promise.reject(new Error("Capability-authorized device observation requires user and device ids.")):new Promise((s,c)=>{let a=()=>{},d=false,u=l=>{d||(d=true,clearTimeout(p),a(),l.error?c(l.error):s(l.device));},p=setTimeout(()=>u({error:new Error(`Timed out waiting for capability-authorized device ${o}`)}),Math.max(1,i));a=this.watchFriendDevices([r],l=>{let R=(l.get(r)??[]).find(S=>S.deviceId===o&&S.online&&typeof S.ticket=="string"&&S.ticket.trim().startsWith("endpoint"));R&&u({device:R});}),d&&a();})}setFriendObservationIdentity(e){this.friendObservationPresence={localNodeId:e.localNodeId,ticket:e.ticket,online:true,ttlMs:e.ttlMs,metadata:e.metadata,deviceName:e.deviceName?.trim()||this.options.getDefaultDeviceName()};for(let n of this.friendConnections.values())this.activateFriendConnection(n,this.friendObservationPresence);}async updateFriendTicket(e){await this.ensureConnected(),await this.sendOperation({v:1,type:"device.patch",idempotencyKey:A("friend-ticket"),patch:{friendTicket:e??""}});}async handleScopeChange(){this.stopSocket(),this.credentialRevoked=false,this.reconnectCircuitOpen=false,this.reconnectAttempt=0,this.reconnectOutageStartedAtMs=null,this.appliedPresenceRevision=0,this.devices.clear(),this.emitDevices();}stopAuthActivity(){this.stopped=true,this.friendObservationPresence=null,this.reconnectOutageStartedAtMs=null,this.stopSocket(),this.rejectConnectionReadyWaiters(new g("Coordination activity stopped before capability admission completed.",false)),this.desiredExcludedPeers=[...this.initialExcludedPeers];for(let e of this.pendingAcks.values())clearTimeout(e.timer),e.resolve();this.pendingAcks.clear(),this.managedPublishAwaitingLease=false;for(let e of this.managedPublishQueue.splice(0))e.reject(new Error("[OpenRTC] Managed room activity stopped."));if(this.devices.clear(),this.pendingMessages.splice(0,this.pendingMessages.length),this.managedState){try{this.managedWasmClient?.__forgetManagedRoomGroup(this.managedAvenueKey());}catch{}this.managedState.close(),this.managedState=null;}this.managedMigrationPending=false,this.managedInitialization=null,this.managedMessageListeners.clear(),this.roomAuthorityAssignmentExpiry&&clearTimeout(this.roomAuthorityAssignmentExpiry),this.roomAuthorityAssignmentExpiry=null,this.roomAuthorityAssignment=null,this.authorityAssignmentListeners.clear(),this.emitDevices();for(let e of this.roomConnections.values())e.stopAuthActivity();this.roomConnections.clear();for(let e of this.friendConnections.values())e.stopAuthActivity();this.friendConnections.clear();}usesCoordinationGateway(){return true}async joinCoordinationRoom(e,n,i){let r=e.trim().toUpperCase(),o=this.roomConnections.get(r);o||(o=new t({...this.options,avenueOverride:{kind:"room",id:r}}),o.setHostAvailability({available:this.hostAvailable,reason:"parent-avenue-created"}),this.roomConnections.set(r,o));try{await o.updatePresence(n,i,!0,5*6e4,void 0,this.options.getDefaultDeviceName());}catch(s){if(!(s instanceof g)||!s.retryable)throw s;await o.waitForConnectionReady();}}async leaveCoordinationRoom(e){let n=e.trim().toUpperCase(),i=this.roomConnections.get(n);i&&(await i.setOffline(this.options.getLocalDeviceId()).catch(()=>{}),i.stopAuthActivity(),this.roomConnections.delete(n));}async getCoordinationRoomMembers(e){return this.requireRoomConnection(e).snapshot().map(i=>this.roomMember(i))}watchCoordinationRoomMembers(e,n){return this.requireRoomConnection(e).onDevicesChange(r=>n(r.map(o=>this.roomMember(o))))}async ensureConnected(){if(this.credentialRevoked)throw new g("Coordination credential revoked.",false,"credential-revoked");if(this.connectPromise)return this.connectPromise;if(this.socket?.readyState===WebSocket.OPEN&&this.socketReady)return;if(!this.desiredPresence&&this.options.credentialPurpose!=="device-control")throw new Error("Coordination presence must be initialized before the gateway can connect.");if(!this.hostAvailable&&this.options.credentialPurpose!=="device-control")throw new g("Coordination reconnect is parked until the host is foregrounded and online.",true);if(this.reconnectCircuitOpen)throw new g("Coordination reconnect circuit is open until presence or scope changes.",false);if(this.reconnectTimer)throw new g("Coordination reconnect is already scheduled.",true);this.stopped=false;let e=this.serviceObservationGeneration,n=this.connect();this.connectPromise=n;try{await n;}catch(i){throw e===this.serviceObservationGeneration&&this.connectPromise===n&&this.scheduleReconnect(i),i}finally{this.connectPromise===n&&(this.connectPromise=null);}}async connect(){let e=this.serviceObservationGeneration,n=this.desiredPresence??this.controlPresence(),i=this.desiredPresenceRevision,r=()=>{if(e!==this.serviceObservationGeneration||this.stopped||this.credentialRevoked)throw new g("Coordination connection retired while minting an admission credential.",false)},o=async()=>{r();let s=await this.mintGatewayCredential(n,false);r(),await new Promise((c,a)=>{let d=new WebSocket(pt(s.gatewayUrl,s.routeKey,s.protocolVersion),[ct,`${dt}${s.token}`]);this.signalBatchMode="off",this.rejectQueuedSignals(new g("Signal connection replaced before dispatch.",false)),this.socket=d,this.pendingRosterPageSnapshot=null;let u=false,p=false,y=null,l=()=>{p||d.readyState!==WebSocket.OPEN||(p=true,this.socketReady=true,this.appliedPresenceRevision=Math.max(this.appliedPresenceRevision,this.desiredPresence?i:0),clearTimeout(R),this.reconnectAttempt=0,this.reconnectOutageStartedAtMs=null,this.scheduleAuthRefresh(s.expiresAtMs,s.protocolVersion),this.resolveConnectionReadyWaiters(),c());},R=setTimeout(()=>{d.close(4408,"authentication timeout"),y=new g("Coordination gateway authentication timed out.",true),a(y);},L);d.onopen=()=>{d.send(JSON.stringify({v:1,type:"auth",token:s.token,socketLiveness:"ping-v1",rosterDelivery:s.avenue.kind==="user"?"paged-v1":void 0,device:this.gatewayDevice(n)}));},d.onmessage=S=>{if(this.stopped||this.socket!==d||S.data==="pong")return;let h;try{h=JSON.parse(String(S.data));}catch{d.close(4400,"invalid gateway frame"),p||(clearTimeout(R),a(new Error("Coordination gateway returned an invalid frame.")));return}if(h.type==="roster.page"&&new TextEncoder().encode(String(S.data)).byteLength>64*1024){d.close(4400,"oversized roster page");return}if(h.type==="error"&&e===this.serviceObservationGeneration&&this.observeServiceError(h,s.avenue),this.stopped||this.socket!==d)return;if(h.type==="ready"&&!u&&this.socket===d&&(this.activeGrantToken=s.token,this.refillCredential={grant:s,ticket:n.ticket},this.activeGrantJti=Pe(s.token),this.activeAvenue=s.avenue,this.activeGrantExpiresAtMs=s.expiresAtMs,this.activeGrantProtocolVersion=s.protocolVersion,this.leaseRefreshMode=h.leaseRefreshMode??"off",this.signalBatchMode=h.signalBatchMode==="ordered-v1"?"ordered-v1":"off",u=true,this.keepaliveTimer&&clearInterval(this.keepaliveTimer),this.keepaliveTimer=setInterval(()=>{if(this.socket===d&&d.readyState===WebSocket.OPEN)try{d.send("ping");}catch{d.close(4408,"gateway keepalive failed");}},3e4)),h.type==="error"&&!p){y=new g(`Coordination gateway ${h.code}: ${h.message}`,h.retryable,h.code,h),clearTimeout(R),a(y),d.close(4403,h.code);return}this.handleFrame(h,d);let I=h.type==="roster.snapshot"||h.type==="roster.page"&&this.pendingRosterPageSnapshot===null||h.type==="membership.snapshot"||h.type==="membership.page"&&this.pendingMembershipPageSnapshot===null;u&&(this.options.credentialPurpose==="device-control"||I)&&l();},d.onerror=()=>{this.socket===d&&(this.signalBatchMode="off",this.rejectQueuedSignals(new g("Signal connection failed before dispatch.",false))),p||(clearTimeout(R),y??(y=new g("Coordination gateway connection failed.",true)),a(y));},d.onclose=S=>{clearTimeout(R);let h=this.socket===d,I=S.code!==4400&&S.code!==4401&&S.code!==4403;h&&this.keepaliveTimer&&(clearInterval(this.keepaliveTimer),this.keepaliveTimer=null),h&&S.code===4403&&(!y||H(y))&&this.stopForCredentialRevocation(new g("Coordination credential revoked.",false,"credential-revoked")),p||(y??(y=new g(`Coordination gateway closed (${S.code}) before its initial projection.`,I)),a(y)),this.socket===d&&(this.pendingRosterPageSnapshot=null,this.socket=null,this.socketReady=false,this.signalBatchMode="off",this.rejectQueuedSignals(new g("Signal connection closed before dispatch.",false))),this.rejectPendingAcks("Coordination gateway connection closed.",d),this.rejectPendingAuthRefresh(new g("Coordination gateway closed during credential refresh.",I),d),h&&!this.stopped&&this.desiredPresence&&S.code!==1e3&&!Me(y)&&this.scheduleReconnect(y??new g(`Coordination gateway closed (${S.code}).`,I));};});};try{await o();}catch(s){if(!Me(s))throw s;await o();}}async mintGatewayCredential(e,n){let i=this.serviceObservationGeneration,r=await this.resolveAvenue(),o={avenue:r,deviceId:this.options.getLocalDeviceId(),runtimeInstanceId:this.runtimeInstanceId,ticketFingerprint:await ut(e.ticket),purpose:this.options.credentialPurpose??"presence",idempotencyKey:A("credential")},s;if(i!==this.serviceObservationGeneration||this.stopped||this.credentialRevoked||!this.hostAvailable&&this.options.credentialPurpose!=="device-control")throw new g("Coordination credential admission retired before dispatch.",i===this.serviceObservationGeneration&&!this.stopped&&!this.credentialRevoked&&!this.hostAvailable);try{if(!this.options.gateway.grantProvider)throw new g("OpenRTC 2.0 coordination requires a v2 gateway grant provider.",!1);s=await this.options.gateway.grantProvider({...o,...n&&this.activeGrantToken?{refreshGrant:this.activeGrantToken}:{}});}catch(a){throw i===this.serviceObservationGeneration&&this.observeServiceError(a,r),a instanceof g?a:new g(a instanceof Error?a.message:"Coordination credential mint failed.",!Ce(a),H(a)?"credential-revoked":void 0)}if(s.protocolVersion!==2)throw new g("Unsupported coordination gateway protocol.",false);let c=ke(this.options.gateway.endpoint);if(ke(s.gatewayUrl)!==c)throw new g("Coordination credential returned an unexpected gateway origin.",false);return s}observeServiceError(e,n){if(this.stopped||!this.options.gateway.onServiceError)return;let i=a(e,n);if(i)try{Promise.resolve(this.options.gateway.onServiceError(i)).catch(()=>{});}catch{}}handleFrame(e,n=this.socket){if(!(n&&n!==this.socket)){if(this.pendingRosterPageSnapshot&&(e.type==="presence.changed"||e.type==="roster.snapshot"||e.type==="membership.snapshot"||e.type==="membership.page"||e.type==="membership.changed"||e.type==="topology.lease")){this.pendingRosterPageSnapshot=null,n?.close(4400,"interleaved roster snapshot");return}if(e.type==="error"&&e.code==="credential-revoked"){let i=new g(`Coordination gateway ${e.code}: ${e.message}`,false,e.code);this.rejectPendingAcks(i.message,n??void 0),this.rejectPendingAuthRefresh(i,n??void 0),this.stopForCredentialRevocation(i);return}if(e.type==="auth.refreshed"){let i=this.pendingAuthRefresh;i&&i.socket===n&&(clearTimeout(i.timer),this.pendingAuthRefresh=null,this.pendingLeaseRefreshKey=null,this.updateLocalDeviceExpiry(e.expiresAtMs),this.scheduleAuthRefresh(e.expiresAtMs,this.activeGrantProtocolVersion),i.resolve());}else if(e.type==="lease.refreshed"){let i=this.pendingAuthRefresh;if(i&&i.socket===n&&e.idempotencyKey===this.pendingLeaseRefreshKey){if(!Number.isSafeInteger(e.expiresAtMs)||e.expiresAtMs<=Date.now()){this.rejectPendingAuthRefresh(new g("Coordination lease refresh is already expired or invalid.",false),n);return}clearTimeout(i.timer),this.pendingAuthRefresh=null,this.pendingLeaseRefreshKey=null,this.activeGrantExpiresAtMs=e.expiresAtMs,this.updateLocalDeviceExpiry(e.expiresAtMs),this.scheduleAuthRefresh(e.expiresAtMs,this.activeGrantProtocolVersion),i.resolve();}}else if(e.type==="roster.snapshot"){this.sparseMembers.clear(),this.sparseRoutes.clear(),this.sparseTopologyRevision=0,this.devices.clear();for(let i of e.devices)this.devices.set(i.deviceId,this.toDevice(i));this.emitDevices();}else if(e.type==="roster.page"){let i=this.activeAvenue?.kind==="user"&&/^[A-Za-z0-9:_-]{1,160}$/.test(e.snapshotId)&&Number.isSafeInteger(e.pageIndex)&&Number.isSafeInteger(e.pageCount)&&Number.isSafeInteger(e.deviceCount)&&e.pageIndex>=0&&e.pageIndex<e.pageCount&&e.pageCount>=1&&e.pageCount<=e.deviceCount&&e.deviceCount>=1&&e.deviceCount<=500&&Array.isArray(e.devices)&&e.devices.length>=1&&e.devices.length<=100&&e.devices.every(o=>o&&typeof o.deviceId=="string"&&/^[A-Za-z0-9_.:@-]{1,160}$/.test(o.deviceId))&&new Set(e.devices.map(o=>o.deviceId)).size===e.devices.length;e.pageIndex===0&&i&&this.pendingRosterPageSnapshot===null&&(this.pendingRosterPageSnapshot={snapshotId:e.snapshotId,nextPageIndex:0,pageCount:e.pageCount,deviceCount:e.deviceCount,devices:new Map});let r=this.pendingRosterPageSnapshot;if(!i||!r||r.snapshotId!==e.snapshotId||r.nextPageIndex!==e.pageIndex||r.pageCount!==e.pageCount||r.deviceCount!==e.deviceCount||r.devices.size+e.devices.length>r.deviceCount||e.devices.some(o=>r.devices.has(o.deviceId))){this.pendingRosterPageSnapshot=null,n?.close(4400,"invalid roster page");return}for(let o of e.devices)r.devices.set(o.deviceId,this.toDevice(o));if(r.nextPageIndex+=1,r.nextPageIndex===r.pageCount){if(r.devices.size!==r.deviceCount){this.pendingRosterPageSnapshot=null,n?.close(4400,"incomplete roster pages");return}this.sparseMembers.clear(),this.sparseRoutes.clear(),this.sparseTopologyRevision=0;let o=[...this.devices.keys()].filter(s=>!r.devices.has(s)).map(s=>({type:"removed",deviceId:s}));for(let[s,c]of r.devices)o.push({type:this.devices.has(s)?"modified":"added",device:c});this.devices.clear();for(let[s,c]of r.devices)this.devices.set(s,c);this.pendingRosterPageSnapshot=null,this.emitDeviceEvents(o),this.emitDevices();}}else if(e.type==="membership.snapshot"){this.pendingMembershipPageSnapshot=null,this.sparseMembers.clear(),this.sparseRoutes.clear(),this.sparseTopologyRevision=0;for(let i of e.members)this.sparseMembers.set(i.deviceId,i);this.rebuildSparseDevices();}else if(e.type==="membership.page"){let i=/^[A-Za-z0-9:_-]{1,160}$/.test(e.snapshotId)&&Number.isSafeInteger(e.pageIndex)&&Number.isSafeInteger(e.pageCount)&&Number.isSafeInteger(e.memberCount)&&e.pageIndex>=0&&e.pageCount>=2&&e.pageCount<=50&&e.pageIndex<e.pageCount&&e.memberCount>100&&e.memberCount<=5e3&&e.members.length>0&&e.members.length<=100;e.pageIndex===0&&i&&(this.pendingMembershipPageSnapshot={snapshotId:e.snapshotId,nextPageIndex:0,pageCount:e.pageCount,memberCount:e.memberCount,members:new Map});let r=this.pendingMembershipPageSnapshot;if(!(i&&r!==null&&r.snapshotId===e.snapshotId&&r.nextPageIndex===e.pageIndex&&r.pageCount===e.pageCount&&r.memberCount===e.memberCount&&e.members.every(s=>s.deviceId.length>0&&!r.members.has(s.deviceId)))||!r){n?.close(4400,"invalid membership page");return}for(let s of e.members)r.members.set(s.deviceId,s);if(r.nextPageIndex+=1,r.nextPageIndex===r.pageCount){if(r.members.size!==r.memberCount){n?.close(4400,"incomplete membership pages");return}this.sparseMembers.clear(),this.sparseRoutes.clear(),this.sparseTopologyRevision=0;for(let s of r.members.values())this.sparseMembers.set(s.deviceId,s);this.pendingMembershipPageSnapshot=null,this.rebuildSparseDevices();}}else if(e.type==="membership.changed")e.operation==="delete"?this.sparseMembers.delete(e.member.deviceId):this.sparseMembers.set(e.member.deviceId,e.member),this.rebuildSparseDevices();else if(e.type==="topology.lease")if(e.lease.schemaVersion===2&&e.lease.architecture.effectiveMode==="managed"||this.roomArchitectureSnapshot?.effective==="managed"){let i={grantJti:this.activeGrantJti,expiresAtMs:this.activeGrantExpiresAtMs,avenue:this.activeAvenue};this.enqueueManagedWork(async()=>{n!==this.socket||this.stopped||await this.acceptTopologyLease(e.lease,i);});}else this.acceptTopologyLease(e.lease);else if(e.type==="authority.assignment")this.acceptAuthorityAssignment(e.assignment,e.signature);else if(e.type==="presence.changed"){if(e.operation==="delete")this.devices.delete(e.device.deviceId),this.emitDeviceEvents([{type:"removed",deviceId:e.device.deviceId}]);else {let i=this.devices.has(e.device.deviceId),r=this.toDevice(e.device);this.devices.set(r.deviceId,r),this.emitDeviceEvents([{type:i?"modified":"added",device:r}]);}this.emitDevices();}else if(e.type==="signal.received")this.pendingMessages.length>=Ie&&this.pendingMessages.shift(),this.pendingMessages.push({senderId:e.senderDeviceId,targetId:this.options.getLocalDeviceId(),payload:e.payload,state:e.state,replyPayload:e.replyPayload,timestamp:e.createdAtMs,appTag:this.options.appTag});else if(e.type==="managed.received")this.enqueueManagedReceive(e,n);else if(e.type==="managed.prepare.page"||e.type==="managed.commit.chunk.received")this.enqueueManagedWork(async()=>{n!==this.socket||this.stopped||await this.handleManagedFrame(e);});else if(e.type==="session.changed"){let i=e.operation==="delete"?[{type:"removed",sessionId:e.sessionId}]:[{type:"modified",session:{...e.session??{},connectionId:e.sessionId}}];for(let r of this.sessionStreams)r.enqueue(i);}else if(e.type==="ack"){let i=this.pendingAcks.get(e.idempotencyKey);i&&i.socket===n&&(clearTimeout(i.timer),this.pendingAcks.delete(e.idempotencyKey),i.resolve());}else if(e.type==="error"){if(this.pendingAuthRefresh?.socket===n&&(!e.idempotencyKey||e.idempotencyKey===this.pendingLeaseRefreshKey)){let r=this.pendingAuthRefresh;clearTimeout(r.timer),this.pendingAuthRefresh=null,this.pendingLeaseRefreshKey=null,r.reject(new g(`Coordination gateway ${e.code}: ${e.message}`,e.retryable,e.code,e));return}let i=e.idempotencyKey?this.pendingAcks.get(e.idempotencyKey):null;i&&i.socket===n&&(clearTimeout(i.timer),this.pendingAcks.delete(e.idempotencyKey),i.reject(new G(e.code,e.message,e.retryable,e)));}}}enqueueManagedWork(e){this.managedReceiveTail=null;let n=this.serviceObservationGeneration,i=this.socket,r=()=>n===this.serviceObservationGeneration&&i===this.socket,o=this.managedActions.then(()=>r()?e():void 0);this.managedActions=o.catch(s=>{r()&&(console.error("[OpenRTC] Managed room owner rejected a gateway frame:",s),this.socket?.close(4400,"managed room state invalid"));});}enqueueManagedReceive(e,n){let i=$+1,r=V+1;try{i=Math.max(1,e.batch.length),r=e.batch.reduce((a,d)=>a+d.ciphertext.length,0);}catch{}let o=this.serviceObservationGeneration,s=this.managedReceiveTail;if(s&&s.socket===n&&s.generation===o&&s.messages+i<=$&&s.ciphertextChars+r<=V){s.frames.push(e),s.messages+=i,s.ciphertextChars+=r;return}let c={frames:[e],messages:i,ciphertextChars:r,socket:n,generation:o};this.enqueueManagedWork(async()=>{this.managedReceiveTail===c&&(this.managedReceiveTail=null);let a=()=>!this.stopped&&this.socket===n&&this.serviceObservationGeneration===o;if(a())try{await this.handleManagedReceivedFrames(c.frames,a);}catch(d){if(a())throw d}}),this.managedReceiveTail=c;}scheduleManagedPublish(){this.managedPublishScheduled||this.activeManagedPublication||this.managedPublishAwaitingLease||this.managedPublishQueue.length===0||this.roomArchitectureSnapshot?.phase!=="settled"||(this.managedPublishScheduled=true,queueMicrotask(()=>{this.managedPublishScheduled=false,this.enqueueManagedWork(()=>this.flushManagedPublishBatch());}));}async flushManagedPublishBatch(){if(this.activeManagedPublication||this.managedPublishQueue.length===0||this.managedPublishAwaitingLease)return;try{await this.ensureConnected(),await this.ensureManagedGroupInitialized();}catch(p){for(let y of this.managedPublishQueue.splice(0))y.reject(p);throw p}if(this.roomArchitectureSnapshot?.phase==="preparing")return;let e=this.managedPublishQueue.splice(0,$),n={pending:new Set(e),socket:this.socket,generation:this.serviceObservationGeneration};this.activeManagedPublication=n;let i=this.roomArchitectureSnapshot,r=this.roomEncryptionEpoch,o=this.sparseTopologyRevision,s=new Error("[OpenRTC] Managed publication connection retired."),c=new Error("[OpenRTC] Managed publication authority changed before dispatch."),a=()=>this.activeManagedPublication===n&&!this.stopped&&n.socket===this.socket&&n.generation===this.serviceObservationGeneration,d=()=>this.roomArchitectureSnapshot?.effective==="managed"&&this.roomArchitectureSnapshot.phase==="settled"&&this.roomArchitectureSnapshot.epoch===i?.epoch&&this.roomEncryptionEpoch===r,u=p=>{if(this.activeManagedPublication!==n)return;let y=a();if(this.activeManagedPublication=null,y&&(p===c||p instanceof G&&p.gatewayCode==="managed-lease-stale"&&p.retryable))this.managedPublishQueue.unshift(...n.pending),this.managedPublishAwaitingLease=!(this.roomArchitectureSnapshot?.phase==="settled"&&this.sparseTopologyRevision>o);else if(p||!y){for(let l of n.pending)l.reject(p??s);if(y)throw p}this.scheduleManagedPublish();};try{let p=this.managedWasmClient,y=this.managedState;if(!i||i.effective!=="managed"||i.phase!=="settled"||r<1||!p||!y)throw new Error("[OpenRTC] Managed room encryption is not settled.");let l=[],R=this.managedAvenueKey();try{for(let f of e){let w=await p.__sealManagedRoomPayload(R,BigInt(i.epoch),BigInt(r),f.input.messageId,f.input.channel,f.input.priority,f.input.zoneId,f.input.payload);l.push({item:f,sealedState:w.sealedState,envelope:{messageId:f.input.messageId,channel:f.input.channel,priority:f.input.priority,scope:f.input.zoneId?{kind:"zone",zoneId:f.input.zoneId}:{kind:"global"},ciphertext:w.payload}});}await this.persistManagedCheckpoint(R,y,p,l[l.length-1].sealedState);}catch(f){throw await this.retireFailedManagedCheckpoint(R,y,p,f),f}if(!a())throw s;let S=[],h=[],I=0;for(let f of l){let w=f.envelope.ciphertext.length;h.length>0&&I+w>V&&(S.push(h),h=[],I=0),h.push(f),I+=w;}h.length>0&&S.push(h);let v=()=>{if(!a()){u(s);return}if(!d()){u(c);return}let f=S.shift();if(!f){u();return}this.sendOperation({v:1,type:"managed.publish",idempotencyKey:A("managed-publish"),architectureEpoch:i.epoch,encryptionEpoch:r,batch:f.map(({envelope:w})=>w)},w=>{if(!a())throw s;if(w!==!1&&!d())throw c}).then(()=>this.enqueueManagedWork(async()=>{if(!a()){u(s);return}for(let{item:w}of f)n.pending.delete(w),w.resolve();S.length===0?u():v();}),w=>this.enqueueManagedWork(async()=>{u(w);}));};v();}catch(p){u(p);}}managedAvenueKey(){let e=this.activeAvenue??this.options.avenueOverride;if(!e||e.kind!=="room"&&e.kind!=="space")throw new Error("[OpenRTC] Managed groups require an active room or space.");return `${e.kind}:${e.id}`}async ensureManagedGroupInitialized(){if(this.managedState)return;if(this.managedInitialization)return this.managedInitialization;let e=this.managedWasmClient;if(!e)throw new Error("[OpenRTC] This browser runtime has no managed-room Rust/WASM owner.");let n=this.managedAvenueKey(),i=(async()=>{let r=await this.managedStateProvider(this.options.appTag,this.options.getLocalDeviceId(),n),o=await e.__initManagedRoomGroup(n,this.options.getLocalDeviceId(),r.wrappingKey,r.sealedState);this.managedState=r,await this.executeManagedGroupActions([o]);})();this.managedInitialization=i;try{await i;}finally{this.managedInitialization===i&&(this.managedInitialization=null);}}async executeManagedGroupActions(e){let n=this.managedState,i=this.managedWasmClient,r=this.managedAvenueKey();for(let o of e){if(n!==this.managedState||i!==this.managedWasmClient)return;try{if(o.type==="migration-status")this.managedMigrationPending=o.pending;else if(o.type==="publish-recovery-key-package")await this.sendOperation({v:1,type:"managed.key-package.publish",idempotencyKey:o.idempotencyKey,keyPackageHash:o.keyPackageHash,keyPackage:o.keyPackage,recovery:o.recovery});else if(o.type==="persist-state"){if(!n||!i)throw new Error("[OpenRTC] Managed room state store is unavailable.");await this.persistManagedCheckpoint(r,n,i,o.sealedState);}else o.type==="publish-key-package"?await this.sendOperation({v:1,type:"managed.key-package.publish",idempotencyKey:A("managed-key-package"),keyPackageHash:o.keyPackageHash,keyPackage:o.keyPackage}):o.type==="request-prepare-page"?await this.sendOperation({v:1,type:"managed.prepare.page.request",idempotencyKey:A("managed-prepare-page"),preparationId:o.preparationId,pageIndex:o.pageIndex}):o.type==="send-artifact-chunk"?await this.sendOperation({v:1,type:"managed.commit.chunk",idempotencyKey:o.idempotencyKey,...o.chunk}):o.type==="acknowledge-commit"&&await this.sendOperation({v:1,type:"managed.commit.ack",idempotencyKey:o.idempotencyKey,preparationId:o.preparationId,encryptionEpoch:o.encryptionEpoch,groupIdHash:o.groupIdHash});}catch(s){if(s instanceof G&&s.gatewayCode==="managed-preparation-stale"&&s.retryable&&o.type!=="persist-state"&&o.type!=="publish-key-package")return;throw s}}}async handleManagedFrame(e){await this.ensureManagedGroupInitialized();let n=this.managedWasmClient;if(!n)throw new Error("[OpenRTC] Managed room Rust/WASM owner is unavailable.");let i=this.managedAvenueKey();if(e.type==="managed.prepare.page"){await this.executeManagedGroupActions(await n.__handleManagedRoomPreparePage(i,e));return}if(e.type==="managed.commit.chunk.received"){await this.executeManagedGroupActions(await n.__handleManagedRoomArtifactChunk(i,e));return}}async handleManagedReceivedFrames(e,n){if(await this.ensureManagedGroupInitialized(),!n())return;let i=this.managedWasmClient,r=this.managedState;if(!i||!r)throw new Error("[OpenRTC] Managed room encryption is unavailable.");let o=this.managedAvenueKey(),s=()=>this.managedState===r&&this.managedWasmClient===i,c=async h=>{await this.retireFailedManagedCheckpoint(o,r,i,h);},a=this.roomArchitectureSnapshot,d=[],u=null,p=false,y,l=[],R=[];try{for(let h of e){if(!a||a.effective!=="managed"||a.phase!=="settled"||h.architectureEpoch!==a.epoch||h.encryptionEpoch!==this.roomEncryptionEpoch)throw new Error("[OpenRTC] Managed room delivery uses a stale room lease.");let I={architectureEpoch:h.architectureEpoch,encryptionEpoch:h.encryptionEpoch,batch:h.batch.map(v=>({messageId:v.messageId,channel:v.channel,priority:v.priority,zoneId:v.scope.kind==="zone"?v.scope.zoneId:void 0,ciphertext:v.ciphertext}))};R.push(I),l.push(h);}}catch(h){p=true,y=h;}let S=(h,I,v)=>{let f=h.batch[I],w=f.scope.kind==="zone"?f.scope.zoneId:void 0;return {senderId:h.senderDeviceId,messageId:f.messageId,channel:f.channel,priority:f.priority,...w?{zoneId:w}:{},payload:oe(v)}};try{let h=R.reduce((v,f)=>v+f.batch.length,0),I=R.reduce((v,f)=>v+f.batch.reduce((w,D)=>w+D.ciphertext.length,0),0);if(i.__openManagedRoomPayloadFrames&&h>1&&h<=$&&R.every(v=>v.batch.length>0)&&I<=V){let v=await i.__openManagedRoomPayloadFrames(o,R);if(!s())return;if(!Array.isArray(v.frames)||v.frames.length>l.length||v.frames.some((w,D)=>!Array.isArray(w)||w.length!==l[D].batch.length)||v.frames.length>0&&(typeof v.sealedState!="string"||!v.sealedState)||!v.failure&&v.frames.length!==l.length)throw new Error("[OpenRTC] Managed room checkpoint returned an invalid frame prefix.");let f=v.frames.flatMap((w,D)=>w.map((C,q)=>S(l[D],q,C)));u=v.sealedState,d.push(...f),v.failure&&(p=!0,y=new Error(v.failure));}else for(let v of l){let f=[],w=null;for(let[D,C]of v.batch.entries()){let q=await i.__openManagedRoomPayload(o,BigInt(v.architectureEpoch),BigInt(v.encryptionEpoch),C.messageId,C.channel,C.priority,C.scope.kind==="zone"?C.scope.zoneId:void 0,oe(C.ciphertext));if(!s())return;f.push(S(v,D,q.payload)),w=q.sealedState;}if(f.length&&(typeof w!="string"||!w))throw new Error("[OpenRTC] Managed room checkpoint is missing.");w&&(u=w),d.push(...f);}}catch(h){p=true,y=h;}if(s()){u&&await this.persistManagedCheckpoint(o,r,i,u);try{e:for(let h of d)for(let I of this.managedMessageListeners){if(!n()||!s())break e;I(h);}}finally{p&&await c(y);}if(p)throw y}}async persistManagedCheckpoint(e,n,i,r){if(n!==this.managedState||i!==this.managedWasmClient)throw new Error("[OpenRTC] Managed room crypto owner retired.");try{if(typeof r!="string"||!r)throw new Error("[OpenRTC] Managed room checkpoint is missing.");await n.persist(oe(r));}catch(o){throw await this.retireFailedManagedCheckpoint(e,n,i,o),o}}async retireFailedManagedCheckpoint(e,n,i,r){if(!(n!==this.managedState||i!==this.managedWasmClient)){this.socket?.close(4400,"managed room state invalid"),this.stopSocket(),this.scheduleReconnect(new g("Managed room checkpoint failed.",false)),this.managedPublishScheduled=false;for(let o of this.managedPublishQueue.splice(0))o.reject(r);this.managedState=null,this.managedInitialization=null;try{await i?.__forgetManagedRoomGroup(e);}finally{n.close();}}}async sendOperation(e,n){this.budgetRenewalPromise&&await this.budgetRenewalPromise,n?.();let i=this.budgetRenewalEpoch;try{await this.sendOperationOnce(e);}catch(r){if(n?.(false),!(r instanceof G)||r.code!=="budget-renewal-required"&&r.code!==a$1.BUDGET_RENEWAL_REQUIRED||!r.retryable)throw r;this.budgetRenewalEpoch===i&&await this.renewBudget(),n?.(),await this.sendOperationOnce(e);}}async sendOperationOnce(e){let n=this.socket;if(!n||n.readyState!==WebSocket.OPEN||!this.socketReady)throw new Error("Coordination gateway is not connected.");await new Promise((i,r)=>{let o=setTimeout(()=>{this.pendingAcks.get(e.idempotencyKey)?.timer===o&&this.pendingAcks.delete(e.idempotencyKey),r(new Error("Coordination gateway acknowledgement timed out."));},L);this.pendingAcks.set(e.idempotencyKey,{socket:n,resolve:i,reject:r,timer:o});try{n.send(JSON.stringify(e));}catch(s){clearTimeout(o),this.pendingAcks.delete(e.idempotencyKey),r(s instanceof Error?s:new Error(String(s)));}});}async renewBudget(){if(this.budgetRenewalPromise)return this.budgetRenewalPromise;let e=this.refreshAuthentication(true,true).then(()=>{this.budgetRenewalEpoch+=1;});this.budgetRenewalPromise=e;try{await e;}finally{this.budgetRenewalPromise===e&&(this.budgetRenewalPromise=null);}}async resolveAvenue(){if(this.options.avenueOverride)return this.options.avenueOverride;if((this.options.discoveryMode??"space")==="space"){let n=await this.options.resolveSpaceNamespaceId();if(!n)throw new Error("Space namespace is not available for coordination.");return {kind:"space",id:n}}let e=this.options.getCurrentUserId();if(!e)throw new Error("Authenticated user is required for coordination.");return {kind:"user",id:e}}gatewayDevice(e){return {deviceId:this.options.getLocalDeviceId(),runtimeInstanceId:this.runtimeInstanceId,nodeId:e.localNodeId,deviceName:e.deviceName,platformType:this.options.getPlatformType(),ticket:e.ticket,metadata:e.metadata,excludedPeers:this.desiredExcludedPeers,online:e.online}}controlPresence(){if(this.options.credentialPurpose!=="device-control")throw new Error("Coordination presence must be initialized before the gateway can connect.");return {localNodeId:this.options.getLocalDeviceId(),ticket:`openrtc-device-control:${this.runtimeInstanceId}`,online:false,ttlMs:0,deviceName:this.options.getDefaultDeviceName()}}toDevice(e){return this.options.normalizeDevice({...e,appTag:this.options.appTag,lastSeenAt:e.updatedAtMs,expiresAt:e.expiresAtMs},e.deviceId)}rebuildSparseDevices(){this.devices.clear();for(let e of this.sparseMembers.values()){let n=this.sparseRoutes.get(e.deviceId),i=n?{...e,...n}:{...e,runtimeInstanceId:"",nodeId:"",ticket:""};this.devices.set(e.deviceId,this.toDevice(i));}this.emitDevices();}async acceptTopologyLease(e,n={grantJti:this.activeGrantJti,expiresAtMs:this.activeGrantExpiresAtMs,avenue:this.activeAvenue}){let i=this.socket;if(e.topologyRevision<=this.sparseTopologyRevision)return;let r=n.avenue,o=[...e.active,...e.backups],s=o.map(l=>l.deviceId),c=e.schemaVersion===1||this.validArchitectureLease(e.architecture),a=e.schemaVersion===1||this.validGroupEncryptionLease(e.groupEncryption,e.architecture),d=e.schemaVersion===2&&e.architecture.effectiveMode==="authority",u=e.schemaVersion===2?e.admissionPeers:void 0,p=!d||this.peerAdmissionScope!==null&&this.peerAdmissionRuntime!==null&&Array.isArray(u)&&u.length<=50&&new Set(u.map(l=>l.deviceId)).size===u.length&&u.every(l=>this.sparseMembers.get(l.deviceId)?.online&&l.deviceId!==this.options.getLocalDeviceId()&&/^[0-9a-f]{64}$/.test(l.nodeId));if(!((e.schemaVersion===1||e.schemaVersion===2)&&c&&a&&p&&Number.isSafeInteger(e.topologyRevision)&&e.topologyRevision>0&&(this.sparseTopologyRevision===0?e.previousTopologyRevision===void 0:e.previousTopologyRevision===this.sparseTopologyRevision)&&e.grantJti===n.grantJti&&r!==null&&e.avenue.kind===r.kind&&e.avenue.id===r.id&&Number.isSafeInteger(e.expiresAtMs)&&e.expiresAtMs>Date.now()&&e.expiresAtMs<=n.expiresAtMs&&e.active.length<=16&&e.backups.length<=4&&o.length<=20&&new Set(s).size===s.length&&o.every(l=>l.online&&this.sparseMembers.has(l.deviceId)&&l.deviceId!==this.options.getLocalDeviceId()&&l.nodeId.trim().length>0&&l.ticket.trim().length>0))){this.socket?.close(4400,"invalid topology lease");return}if(e.schemaVersion===2&&e.architecture.effectiveMode==="managed"){if(await this.ensureManagedGroupInitialized(),i!==this.socket||this.stopped)return;let l=e.groupEncryption,R=await this.managedWasmClient.__applyManagedRoomAuthority(this.managedAvenueKey(),{...l?{preparationId:l.preparationId,memberSetHash:l.memberSetHash,groupIdHash:l.groupIdHash,previousEncryptionEpoch:l.previousEncryptionEpoch??0,encryptionEpoch:l.epoch}:{},...e.managedRecovery?{recovery:{...e.managedRecovery,expiresAtMs:e.expiresAtMs}}:{}},l?.phase==="settled",l?.previousPreparation);if(await this.executeManagedGroupActions(R),i!==this.socket||this.stopped)return}if(d)try{this.peerAdmissionRuntime.__updateScopePeerAdmission(this.peerAdmissionScope,++this.peerAdmissionRevision,e.expiresAtMs,JSON.stringify(u.map(l=>l.nodeId)));}catch{this.socket?.close(4400,"invalid peer admission lease");return}if(e.schemaVersion===2){e.groupEncryption&&(this.roomEncryptionEpoch=e.groupEncryption.epoch);let l={requested:e.architecture.requestedMode,effective:e.architecture.effectiveMode,epoch:e.architecture.epoch,phase:this.managedMigrationPending&&e.architecture.effectiveMode==="managed"?"preparing":e.architecture.phase,reason:e.architecture.reason},R=JSON.stringify(l)!==JSON.stringify(this.roomArchitectureSnapshot);if(this.roomArchitectureSnapshot=l,R)for(let S of this.architectureListeners)S({...l});if(l.effective!=="authority"&&this.roomAuthorityAssignment){this.roomAuthorityAssignmentExpiry&&(clearTimeout(this.roomAuthorityAssignmentExpiry),this.roomAuthorityAssignmentExpiry=null),this.roomAuthorityAssignment=null;for(let S of this.authorityAssignmentListeners)S(null);}l.effective==="managed"&&(l.phase==="settled"&&(this.managedPublishAwaitingLease=false),this.enqueueManagedWork(()=>this.ensureManagedGroupInitialized()),this.scheduleManagedPublish());}this.sparseTopologyRevision=e.topologyRevision,this.sparseRoutes.clear();for(let l of e.active)this.sparseRoutes.set(l.deviceId,{...l,topologyRole:"active",topologyRevision:e.topologyRevision});for(let l of e.backups)this.sparseRoutes.set(l.deviceId,{...l,topologyRole:"backup",topologyRevision:e.topologyRevision});this.rebuildSparseDevices();}acceptAuthorityAssignment(e,n){let i=this.roomAuthorityAssignment,r=this.options.getLocalDeviceId(),o=[e.serviceId,e.subjectDeviceId,e.shardId,...e.priorityDeviceIds,...e.relevantEntityIds];if(i&&e.generation===i.generation&&e.revision===i.revision){if(JSON.stringify({serviceId:e.serviceId,generation:e.generation,revision:e.revision,shardId:e.shardId,priorityDeviceIds:e.priorityDeviceIds,relevantEntityIds:e.relevantEntityIds,issuedAtMs:e.issuedAtMs,expiresAtMs:e.expiresAtMs})===JSON.stringify(i))return;this.socket?.close(4400,"invalid authority assignment");return}if(!(e.policyVersion==="room-authority-assignment-v1"&&this.roomArchitectureSnapshot?.effective==="authority"&&e.subjectDeviceId===r&&Number.isSafeInteger(e.generation)&&e.generation>0&&Number.isSafeInteger(e.revision)&&e.revision>0&&Number.isSafeInteger(e.issuedAtMs)&&Number.isSafeInteger(e.expiresAtMs)&&e.issuedAtMs<=Date.now()+3e4&&e.expiresAtMs>Date.now()&&e.expiresAtMs-e.issuedAtMs<=12e4&&e.priorityDeviceIds.length<=8&&e.relevantEntityIds.length<=32&&new Set(e.priorityDeviceIds).size===e.priorityDeviceIds.length&&new Set(e.relevantEntityIds).size===e.relevantEntityIds.length&&o.every(a=>/^[A-Za-z0-9_.:@-]{1,160}$/.test(a))&&/^[A-Za-z0-9_-]{86}$/.test(n)&&(!i||e.generation>i.generation||e.generation===i.generation&&e.revision>i.revision))){this.socket?.close(4400,"invalid authority assignment");return}this.roomAuthorityAssignment=Object.freeze({serviceId:e.serviceId,generation:e.generation,revision:e.revision,shardId:e.shardId,priorityDeviceIds:Object.freeze([...e.priorityDeviceIds]),relevantEntityIds:Object.freeze([...e.relevantEntityIds]),issuedAtMs:e.issuedAtMs,expiresAtMs:e.expiresAtMs}),this.roomAuthorityAssignmentExpiry&&clearTimeout(this.roomAuthorityAssignmentExpiry),this.roomAuthorityAssignmentExpiry=setTimeout(()=>{if(this.roomAuthorityAssignmentExpiry=null,this.roomAuthorityAssignment?.expiresAtMs===e.expiresAtMs){this.roomAuthorityAssignment=null;for(let a of this.authorityAssignmentListeners)a(null);}},Math.max(0,e.expiresAtMs-Date.now()));for(let a of this.authorityAssignmentListeners)a(this.roomAuthorityAssignmentSnapshot());}roomAuthorityAssignmentSnapshot(){let e=this.roomAuthorityAssignment;return !e||e.expiresAtMs<=Date.now()?null:{...e,priorityDeviceIds:[...e.priorityDeviceIds],relevantEntityIds:[...e.relevantEntityIds]}}validArchitectureLease(e){let n=this.roomArchitectureSnapshot?.epoch??0,i=new Set(["auto","mesh","sparse","managed","authority"]),r=new Set(["mesh","sparse","managed","authority"]),o=new Set(["size","traffic","latency","cost","capacity","manual","recovery"]);return e.policyVersion==="room-architecture-v1"&&Number.isSafeInteger(e.epoch)&&e.epoch>0&&e.epoch>=n&&(e.epoch===n||n===0||e.previousArchitectureEpoch===n)&&i.has(e.requestedMode)&&r.has(e.effectiveMode)&&(e.phase==="settled"||e.phase==="preparing")&&o.has(e.reason)&&Number.isSafeInteger(e.heldCreditsMicrousd)&&e.heldCreditsMicrousd>=0&&Number.isSafeInteger(e.quoteExpiresAtMs)&&e.quoteExpiresAtMs>0&&(e.reservationId===void 0||/^[A-Za-z0-9:_-]{1,160}$/.test(e.reservationId))}validGroupEncryptionLease(e,n){if(!e)return n.effectiveMode!=="managed"||n.phase==="preparing";let i=this.managedMigrationPending?0:this.roomEncryptionEpoch,r=e.previousPreparation;return (r===void 0||r!==null&&typeof r=="object"&&/^[A-Za-z0-9_.:@-]{1,160}$/.test(r.preparationId)&&/^[A-Za-z0-9_-]{43}$/.test(r.memberSetHash)&&r.groupIdHash===e.groupIdHash&&Number.isSafeInteger(r.previousEncryptionEpoch)&&r.previousEncryptionEpoch>=0&&Number.isSafeInteger(r.encryptionEpoch)&&r.encryptionEpoch===r.previousEncryptionEpoch+1&&r.encryptionEpoch===e.previousEncryptionEpoch)&&e.policyVersion==="room-mls-v1"&&typeof e.preparationId=="string"&&/^[A-Za-z0-9_.:@-]{1,160}$/.test(e.preparationId)&&typeof e.memberSetHash=="string"&&/^[A-Za-z0-9_-]{43}$/.test(e.memberSetHash)&&Number.isSafeInteger(e.epoch)&&e.epoch>0&&e.epoch>=i&&(e.epoch===i||i===0||e.previousEncryptionEpoch===i)&&(e.phase==="preparing"||e.phase==="settled")&&(n.effectiveMode!=="managed"||n.phase!=="settled"||e.phase==="settled")&&/^[A-Za-z0-9_.:@-]{1,160}$/.test(e.committerDeviceId)&&/^[A-Za-z0-9_-]{43}$/.test(e.groupIdHash)}snapshot(e){return [...this.devices.values()].filter(n=>!e||n.nodeId!==e).sort((n,i)=>n.deviceId.localeCompare(i.deviceId))}emitDevices(){let e=this.snapshot();for(let n of this.deviceListeners)n(e);}emitDeviceEvents(e){for(let n of this.deviceStreams)n.enqueue(e);}updateLocalDeviceExpiry(e){let n=this.options.getLocalDeviceId(),i=this.devices.get(n);if(!i||i.expiresAt===e)return;let r={...i,expiresAt:e};this.devices.set(n,r),this.emitDeviceEvents([{type:"modified",device:r}]),this.emitDevices();}scheduleAuthRefresh(e,n){this.authRefreshTimer&&clearTimeout(this.authRefreshTimer);let i=e-Date.now(),r=n===2?nt:tt,o=i>r+1e3;this.authRefreshTimer=setTimeout(()=>{if(this.authRefreshTimer=null,this.stopped)return;if(!o){this.stopSocket(false),this.scheduleReconnect(new g("Coordination credential crossed a billing boundary.",true));return}(n===2&&this.leaseRefreshMode==="active"?this.refreshLease():this.refreshAuthentication()).catch(c=>{this.stopSocket(false),this.scheduleReconnect(c);});},o?i-r:Math.max(1e3,i+1e3));}refreshAuthentication(e=false,n=false){let i=`${n?"refill":e?"issue":"refresh"}\0${this.desiredPresence?.ticket??""}`,r=this.authenticationRefreshes.get(i);if(r)return r;let o=this.authenticationRefreshTail.catch(()=>{}).then(()=>this.performAuthenticationRefresh(e,n));this.authenticationRefreshTail=o,this.authenticationRefreshes.set(i,o);let s=()=>{this.authenticationRefreshes.get(i)===o&&this.authenticationRefreshes.delete(i);};return o.then(s,s),o}currentRefillCredential(e){let n=this.refillCredential;if(!n||n.ticket!==e||n.grant.token!==this.activeGrantToken||n.grant.protocolVersion!==2||n.grant.expiresAtMs<this.activeGrantExpiresAtMs)return null;let i=Ee(n.grant.token);return i?.budget?.controlFunding?.recipeVersion!=="coordination-provider-control-v3"||!Number.isSafeInteger(i?.exp)||!Number.isSafeInteger(n.grant.expiresAtMs)||Math.min(n.grant.expiresAtMs,Number(i?.exp)*1e3)<=Date.now()+L?null:n.grant}async performAuthenticationRefresh(e,n=false){let i=this.socket,r=this.desiredPresence;if(!i||i.readyState!==WebSocket.OPEN||!this.socketReady||!r)throw new g("Coordination socket is unavailable for credential refresh.",true);if(this.pendingAuthRefresh)return this.pendingAuthRefresh.promise;let o=(n?this.currentRefillCredential(r.ticket):null)??await this.mintGatewayCredential(r,!e);if(this.socket!==i||i.readyState!==WebSocket.OPEN||!this.socketReady)throw new g("Coordination socket changed while minting a credential refresh.",true);let s,c,a=new Promise((u,p)=>{s=u,c=p;}),d=setTimeout(()=>{this.pendingAuthRefresh?.timer===d&&(this.pendingAuthRefresh=null),c(new g("Coordination credential refresh timed out.",true));},L);this.pendingAuthRefresh={socket:i,promise:a,resolve:s,reject:c,timer:d};try{i.send(JSON.stringify({v:1,type:"auth.refresh",token:o.token}));}catch(u){this.rejectPendingAuthRefresh(new g(u instanceof Error?u.message:"Coordination credential refresh send failed.",true),i);}await a,this.activeGrantToken=o.token,this.refillCredential={grant:o,ticket:r.ticket},this.activeGrantJti=Pe(o.token),this.activeAvenue=o.avenue,this.activeGrantExpiresAtMs=o.expiresAtMs,this.activeGrantProtocolVersion=o.protocolVersion;}refreshLease(){let e=`lease\0${this.desiredPresence?.ticket??""}`,n=this.authenticationRefreshes.get(e);if(n)return n;let i=this.authenticationRefreshTail.catch(()=>{}).then(()=>this.performLeaseRefresh());this.authenticationRefreshTail=i,this.authenticationRefreshes.set(e,i);let r=()=>{this.authenticationRefreshes.get(e)===i&&this.authenticationRefreshes.delete(e);};return i.then(r,r),i}async performLeaseRefresh(){let e=this.socket;if(!e||e.readyState!==WebSocket.OPEN||!this.socketReady)throw new g("Coordination socket is unavailable for lease refresh.",true);if(this.pendingAuthRefresh)return this.pendingAuthRefresh.promise;let n=A("lease"),i,r,o=new Promise((c,a)=>{i=c,r=a;}),s=setTimeout(()=>{this.pendingAuthRefresh?.timer===s&&(this.pendingAuthRefresh=null,this.pendingLeaseRefreshKey=null),r(new g("Coordination lease refresh timed out.",true));},L);this.pendingLeaseRefreshKey=n,this.pendingAuthRefresh={socket:e,promise:o,resolve:i,reject:r,timer:s};try{e.send(JSON.stringify({v:1,type:"lease.refresh",idempotencyKey:n}));}catch(c){this.rejectPendingAuthRefresh(new g(c instanceof Error?c.message:"Coordination lease refresh send failed.",true),e);}try{await o;}catch(c){if(this.stopped||H(c))throw c;await this.performAuthenticationRefresh(true);}}stopForCredentialRevocation(e){return H(e)?(this.credentialRevoked=true,this.reconnectCircuitOpen=true,this.stopAuthActivity(),true):false}scheduleReconnect(e){if(this.stopForCredentialRevocation(e)||this.reconnectTimer||this.reconnectCircuitOpen||this.stopped)return;if(!(e instanceof g?e.retryable:!Ce(e))){this.reconnectCircuitOpen=true,this.rejectConnectionReadyWaiters(e instanceof Error?e:new g("Coordination reconnect circuit is open.",false));return}if(this.reconnectOutageStartedAtMs??(this.reconnectOutageStartedAtMs=Date.now()),!this.hostAvailable)return;let i=Math.min(this.reconnectAttempt,Re),r=Date.now()-this.reconnectOutageStartedAtMs>=ot,o=lt(r?st:d(i,250,it));this.reconnectAttempt=Math.min(i+1,Re),this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=null,this.ensureConnected().catch(s=>this.scheduleReconnect(s));},o);}stopSocket(e=true){this.managedReceiveTail=null,this.serviceObservationGeneration+=1;let n=this.activeManagedPublication;if(this.activeManagedPublication=null,n)for(let r of n.pending)r.reject(new Error("[OpenRTC] Managed room activity stopped."));this.signalBatchMode="off",this.rejectQueuedSignals(new g("Signal activity retired before dispatch.",false)),this.connectPromise=null,this.peerAdmissionScope&&this.peerAdmissionRuntime&&this.peerAdmissionRuntime.__updateScopePeerAdmission(this.peerAdmissionScope,++this.peerAdmissionRevision,0,"[]"),e&&this.reconnectTimer&&clearTimeout(this.reconnectTimer),this.authRefreshTimer&&clearTimeout(this.authRefreshTimer),this.reconnectTimer=null,this.keepaliveTimer&&clearInterval(this.keepaliveTimer),this.keepaliveTimer=null,this.authRefreshTimer=null,this.leaseRefreshMode="off",this.pendingLeaseRefreshKey=null,this.rejectPendingAuthRefresh(new g("Coordination credential refresh was canceled.",true));let i=this.socket;this.socket=null,this.socketReady=false,this.activeGrantJti=null,this.refillCredential=null,this.activeAvenue=null,this.activeGrantExpiresAtMs=0,this.sparseRoutes.clear(),this.sparseTopologyRevision=0,this.pendingMembershipPageSnapshot=null,this.pendingRosterPageSnapshot=null,this.sparseMembers.size>0&&this.rebuildSparseDevices(),i?.close(1e3,"coordination session stopped");}waitForConnectionReady(){return this.socket?.readyState===WebSocket.OPEN&&this.socketReady?Promise.resolve():this.stopped||this.reconnectCircuitOpen?Promise.reject(new g("Coordination reconnect circuit is unavailable.",false)):new Promise((e,n)=>{this.connectionReadyWaiters.add({resolve:e,reject:n});})}resolveConnectionReadyWaiters(){for(let e of this.connectionReadyWaiters)e.resolve();this.connectionReadyWaiters.clear();}rejectConnectionReadyWaiters(e){for(let n of this.connectionReadyWaiters)n.reject(e);this.connectionReadyWaiters.clear();}rejectPendingAuthRefresh(e,n){let i=this.pendingAuthRefresh;!i||n&&i.socket!==n||(clearTimeout(i.timer),this.pendingAuthRefresh=null,this.pendingLeaseRefreshKey=null,i.reject(e));}rejectPendingAcks(e,n){for(let[i,r]of this.pendingAcks)n&&r.socket!==n||(clearTimeout(r.timer),r.reject(new Error(e)),this.pendingAcks.delete(i));}unscopedId(e){let n=e.split("::");return n.length===2?n[1]:e}requireRoomConnection(e){let n=e.trim().toUpperCase(),i=this.activeAvenue??this.options.avenueOverride;if(i?.kind==="room"&&i.id.trim().toUpperCase()===n)return this;let r=this.roomConnections.get(n);if(!r)throw new Error(`Room ${n} is not joined through the coordination gateway.`);return r}friendConnection(e){let n=this.friendConnections.get(e);n||(n=new t({...this.options,avenueOverride:{kind:"user",id:e}}),n.setHostAvailability({available:this.hostAvailable,reason:"parent-avenue-created"}),this.friendConnections.set(e,n));let i=this.desiredPresence??this.friendObservationPresence;return !n.desiredPresence&&i&&this.activateFriendConnection(n,i),n}activateFriendConnection(e,n){e.updatePresence(n.localNodeId,n.ticket,n.online,n.ttlMs,n.metadata,n.deviceName).catch(()=>{});}roomMember(e){return {deviceId:e.deviceId,nodeId:e.nodeId??"",userId:e.userId??"",ticket:e.ticket,joinedAt:Number(e.createdAt??e.lastSeenAt??Date.now()),lastSeenAt:Number(e.lastSeenAt??Date.now()),expiresAt:typeof e.expiresAt=="number"?e.expiresAt:void 0}}};var Q=class{constructor(e){this.provider=e;this.cached=null;this.inFlight=null;this.refreshTimer=null;this.refreshRetryUsed=false;this.listeners=new Set;}async get(e=false){if(!this.provider)throw new Error("[OpenRTC] Native coordination requires coordinationGateway.nativeTrustTokenProvider; obtain tokens through a trusted backend without shipping the developer secret.");let n=Date.now();if(!e&&this.cached&&this.cached.expiresAtMs>n+3e4)return this.cached;if(this.inFlight)return this.inFlight;let i=(async()=>{let r=await this.provider(e),o=r?.token?.trim()??"",s=Number(r?.expiresAtMs),c=Date.now();if(!o||!Number.isFinite(s)||s<=c+3e4)throw new Error("[OpenRTC] Native trust token provider returned no usable short-lived token.");let a={token:o,expiresAtMs:s};return this.cached=a,this.refreshRetryUsed=false,this.notify(a),this.scheduleRefresh(a),a})();this.inFlight=i;try{return await i}finally{this.inFlight===i&&(this.inFlight=null);}}invalidate(){this.cached=null,this.clearRefreshTimer(),this.notify(null);}clear(){this.invalidate(),this.listeners.clear();}subscribe(e,n){return this.listeners.add(e),this.cached&&this.cached.expiresAtMs>Date.now()&&(n?.emitCurrent!==false&&e(this.cached),this.scheduleRefresh(this.cached)),()=>{this.listeners.delete(e),this.listeners.size===0&&this.clearRefreshTimer();}}notify(e){for(let n of this.listeners)n(e);}scheduleRefresh(e){if(this.clearRefreshTimer(),this.listeners.size===0)return;let n=Math.max(0,e.expiresAtMs-Date.now()-3e4);this.refreshTimer=setTimeout(()=>{this.refreshTimer=null,this.get(true).catch(()=>{if(this.listeners.size===0||this.refreshRetryUsed){this.invalidate();return}this.refreshRetryUsed=true,this.refreshTimer=setTimeout(()=>{this.refreshTimer=null,this.get(true).catch(()=>this.invalidate());},15e3);});},n);}clearRefreshTimer(){this.refreshTimer&&(clearTimeout(this.refreshTimer),this.refreshTimer=null);}};var _e=class{constructor(e){this.options=e;this.signaling=null;this.wasmClient=null;this.managedStateProvider=null;this.hostAvailability={available:true,reason:"initial"};this.nativeTrustTokens=e.gateway?new Q(e.gateway.nativeTrustTokenProvider):null;}usesGateway(){return !!this.options.gateway}getSignaling(){if(this.options.signalingMode==="ticket-only")throw new Error('[openrtc] Managed signaling is disabled when signalingMode="ticket-only".');if(!this.options.gateway)throw new Error("[OpenRTC] Managed coordination requires coordinationGateway; the legacy direct Firebase data plane has been removed.");if(!this.signaling){this.signaling=new J({projectId:this.options.projectId,gateway:this.options.gateway,appTag:this.options.appTag,discoveryMode:this.options.discoveryMode,resolveSpaceNamespaceId:this.options.resolveSpaceNamespaceId,getCurrentUserId:this.options.getCurrentUserId,getAuthToken:this.options.getAuthToken,getAppCheckToken:this.options.getAppCheckToken,getLocalDeviceId:this.options.getLocalDeviceId,getDefaultDeviceName:this.options.getDefaultDeviceName,getPlatformType:this.options.getPlatformType,normalizeDevice:this.options.normalizeDevice,avenueOverride:this.options.avenueOverride,roomArchitecture:this.options.roomArchitecture,initialExcludedPeers:this.options.initialExcludedPeers,nativeTrustTokens:this.nativeTrustTokens});let e=this.signaling;this.managedStateProvider?e.setManagedRoomRuntime(this.wasmClient,this.managedStateProvider):e.setWasmClient(this.wasmClient),this.signaling.setHostAvailability?.(this.hostAvailability);}return this.signaling}setWasmClient(e){this.wasmClient=e,this.managedStateProvider=null,this.signaling?.setWasmClient(e);}setManagedRoomRuntime(e,n){this.wasmClient=e,this.managedStateProvider=n,this.signaling?.setManagedRoomRuntime(e,n);}setHostAvailability(e){this.hostAvailability=e,this.signaling?.setHostAvailability?.(e);}async reconnectAfterHostResume(){await this.signaling?.reconnectAfterHostResume?.();}async handleScopeChange(){await this.signaling?.handleScopeChange();}stopAuthActivity(){this.signaling?.stopAuthActivity();}async getNativeTrustToken(e=false){if(!this.nativeTrustTokens)throw new Error("[OpenRTC] Native trust tokens require a coordination gateway.");return this.nativeTrustTokens.get(e)}invalidateNativeTrustToken(){this.nativeTrustTokens?.invalidate();}subscribeNativeTrustToken(e,n){return this.nativeTrustTokens?.subscribe(e,n)??(()=>{})}};function ht(){if(typeof globalThis<"u"&&globalThis.__OPENRTC_DEBUG__===true)return true;if(typeof localStorage<"u")try{return localStorage.getItem("openrtc:debug")==="1"}catch{return false}return false}function se(t,e,n){if(ht()){if(typeof n>"u"){console[t](e);return}console[t](e,n);}}function ln(t,e){se("debug",t,e);}function un(t,e){se("info",t,e);}function pn(t,e){se("log",t,e);}function De(){return typeof window>"u"?false:!!(window.__TAURI_IPC__||window.__TAURI_INTERNALS__||window.__TAURI__||window.location.protocol==="tauri:"||window.location.hostname==="tauri.localhost")}var gt="[OpenRTC][teardown-trace]";function mt(){try{let t=globalThis;if(t.OPENRTC_TEARDOWN_TRACE===!0||t.localStorage?.getItem("OPENRTC_TEARDOWN_TRACE")==="1")return !0}catch{}return false}function mn(t,e={}){console.info(gt,{kind:t,ts:new Date().toISOString(),...e}),mt()&&console.info("[OpenRTC][teardown-trace:stack]",{kind:t,stack:new Error(`teardown: ${t}`).stack});}var Z="trustedDevice",yt="plutonium:e2ee:identity:v1",ft="plutonium:e2ee:identity:session:v1",vt="openrtc-trust",N="identity",Ge="transport-trust:v1",bt=2,xe="managed-room-keys",Oe="managed-room-state",wt=1,T=null,B=null;function M(t){let e=atob(t),n=new Uint8Array(e.length);for(let i=0;i<e.length;i+=1)n[i]=e.charCodeAt(i);return n}function F(t){let e="";for(let n=0;n<t.length;n+=1)e+=String.fromCharCode(t[n]);return btoa(e)}async function ae(t){let e=await crypto.subtle.digest("SHA-256",t),n=new Uint8Array(e);return Array.from(n).map(i=>i.toString(16).padStart(2,"0")).join("")}function St(){return typeof sessionStorage>"u"?null:sessionStorage}function Rt(){if(!(typeof localStorage>"u"))try{localStorage.removeItem(yt);}catch{}}var Y=null;async function Ne(){return Y||(Y=(async()=>{let t=globalThis.crypto?.subtle;if(!t||typeof t.generateKey!="function")return false;try{let e=await t.generateKey({name:"Ed25519"},!1,["sign","verify"]);return !!(e&&e.privateKey&&e.publicKey)}catch{return false}})(),Y)}async function It(t){let e=await crypto.subtle.exportKey("raw",t);return new Uint8Array(e)}function At(){try{return typeof indexedDB<"u"?indexedDB:null}catch{return null}}function Ke(){let t=At();return t?new Promise(e=>{let n;try{n=t.open(vt,bt);}catch{e(null);return}n.onupgradeneeded=()=>{let i=n.result;i.objectStoreNames.contains(N)||i.createObjectStore(N),i.objectStoreNames.contains(xe)||i.createObjectStore(xe),i.objectStoreNames.contains(Oe)||i.createObjectStore(Oe);},n.onsuccess=()=>e(n.result),n.onerror=()=>e(null),n.onblocked=()=>e(null);}):Promise.resolve(null)}async function Tt(){let t=await Ke();if(!t)return null;try{return await new Promise(e=>{let r=t.transaction(N,"readonly").objectStore(N).get(Ge);r.onsuccess=()=>{let o=r.result;e(o&&o.privateKey&&o.publicKey?o:null);},r.onerror=()=>e(null);})}catch{return null}finally{t.close();}}async function Pt(t){let e=await Ke();if(!e)return false;try{return await new Promise(n=>{let i=e.transaction(N,"readwrite");i.objectStore(N).put(t,Ge),i.oncomplete=()=>n(!0),i.onerror=()=>n(!1),i.onabort=()=>n(!1);})}catch{return false}finally{e.close();}}async function Le(t,e){let n=await It(t.publicKey),i=await ae(n),r=t.privateKey;return {publicKey:n,fingerprint:i,backend:"webcrypto-nonextractable",durable:e,privateKey:r,async signChallenge(o){let s=await crypto.subtle.sign({name:"Ed25519"},r,M(o));return F(new Uint8Array(s))}}}function Mt(t,e,n){let i=t.secretKey;return {publicKey:t.publicKey,secretKey:i,fingerprint:e,backend:"tweetnacl",durable:n,async signChallenge(r){return Ct(r,i)}}}function bn(t=32){let e=crypto.getRandomValues(new Uint8Array(t));return F(e)}function Ct(t,e){let n=U.sign.detached(M(t),e);return F(n)}function kt(t,e,n){try{return U.sign.detached.verify(M(t),M(e),M(n))}catch{return false}}async function wn(t,e,n){let i=globalThis.crypto?.subtle;if(i&&typeof i.importKey=="function"&&typeof i.verify=="function")try{let r=await i.importKey("raw",M(n),{name:"Ed25519"},!1,["verify"]);return await i.verify({name:"Ed25519"},r,M(e),M(t))}catch{}return kt(t,e,n)}function Sn(t){return F(t)}function Rn(t){if(!t||!t.trim())return null;try{let e=JSON.parse(t),n=e&&typeof e=="object"&&!Array.isArray(e)?e[Z]:null;if(!n||typeof n!="object"||Array.isArray(n))return null;let i=n,r=typeof i.version=="number"?i.version:null,o=typeof i.identityPublicKey=="string"?i.identityPublicKey:null,s=typeof i.identityFingerprint=="string"?i.identityFingerprint:null;return !r||!o||!s?null:{version:r,identityPublicKey:o,identityFingerprint:s}}catch{return null}}async function Et(){let t=await Gt().catch(()=>null);return t?{version:wt,identityPublicKey:F(t.publicKey),identityFingerprint:t.fingerprint}:null}async function In(t){let e=await Et();if(!e)return t??void 0;let n=typeof t=="string"?t.trim():"";if(!n)return JSON.stringify({[Z]:e});try{let i=JSON.parse(n);if(i&&typeof i=="object"&&!Array.isArray(i))return JSON.stringify({...i,[Z]:e})}catch{}return JSON.stringify({metadata:t,[Z]:e})}function _t(){if(typeof window>"u")return null;let t=window.__TAURI_INTERNALS__;return !t||typeof t.invoke!="function"?null:t.invoke.bind(t)}async function Dt(){if(typeof window>"u")return null;let t=_t();if(!De()&&!t)return null;if(!t)throw new Error("[OpenRTC] Tauri transport trust requires the native signing provider, but Tauri invoke is unavailable.");try{let e=await t("openrtc_get_transport_trust_identity"),n=M(e.publicKeyBase64);if(n.byteLength!==U.sign.publicKeyLength)throw new Error("native transport trust public key has an invalid length");let i=await ae(n);if(e.fingerprint!==i)throw new Error("native transport trust fingerprint does not match its public key");return {publicKey:n,fingerprint:i,backend:"native-provider",durable:!0,async signChallenge(r){return t("openrtc_sign_transport_trust_challenge",{challenge:r})}}}catch(e){let n=new Error("[OpenRTC] native transport trust provider failed; refusing WebCrypto fallback in Tauri.");throw n.cause=e,n}}function xt(){let t=St();t&&t.removeItem(ft);}async function Ot(){if(Rt(),xt(),T)return T;let t=await Dt();if(t)return T=t,T;if(await Ne()){let e=await Tt();if(e)return T=await Le(e,true),T}return null}async function Gt(t={}){let e=i=>{if(t.ephemeral===true&&i?.durable)throw new Error("Cannot replace an active durable transport identity with an ephemeral identity.");if(t.ephemeral===false&&i&&!i.durable)throw new Error("Persistent transport identity requires durable storage before session startup.");return i};if(T)return e(T);if(B)return e(await B);let n=(async()=>{if(t.ephemeral!==true){let i=await Ot();if(i)return i}return Nt(t)})();B=n;try{return e(await n)}finally{B===n&&(B=null);}}async function Nt(t){if(T)return T;let e=t.ephemeral===true;if(await Ne())try{let n=await crypto.subtle.generateKey({name:"Ed25519"},!1,["sign","verify"]),i=!1;return e||(i=await Pt(n)),T=await Le(n,i),T}catch{}if(!e)return console.warn("[OpenRTC][TRUST] Managed transport trust requires WebCrypto Ed25519 or native keychain; refusing extractable fallback storage"),null;try{let n=U.sign.keyPair(),i=await ae(b$1(n.publicKey));return T=Mt(n,i,!1),T}catch{return null}}var Kt={managedSession:{nativeStartRetryWindowMs:12e4,nativeStartRetryMinDelayMs:400,nativeStartRetryMaxDelayMs:5e3,deviceStatusRefreshDebounceMs:50},browserAutoConnect:{scanDebounceMs:150,retryCooldownMs:2e3,settleGuardMs:1e4,retryMaxMs:8e3,nonInitiatorBaseGraceMs:2e3,nonInitiatorMaxGraceMs:16e3},nativeIpc:{authRequiredWaitMs:15e3,defaultBoundedCommandTimeoutMs:15e3,connectionEventSubscribeWindowMs:15e3,connectionEventRetryMinDelayMs:250,connectionEventRetryMaxDelayMs:1e3,tauriIpcNegativeCacheMs:2e3},browserIdentity:{ephemeralDeviceIdTtlMs:6e4}};function Tn(){return Kt}var Lt={adapter:"browser-wasm",productMaturity:{boundedRooms:"stable",serviceNodes:"preview",offlineEdge:"support-only",broadcast:"preview"},signaling:{coordinationGateway:true,nativeIpc:false,managedPresence:true},transport:{irohQuic:false,irohLan:false,webRtc:true,moq:true,ble:false,wasm:true},nativeProtocols:{productAlpn:false,irohDocs:false,irohBlobs:false,irohGossip:false},lifecycle:{managedSession:true,autoConnect:true,manualDisconnect:true,connectionStateEvents:true,peerSessions:true},transfers:{explicitFilePath:false,explicitFileData:true,history:false},fallback:{wasm:false}},Ht={adapter:"native-ipc",productMaturity:{boundedRooms:"stable",serviceNodes:"unavailable",offlineEdge:"unavailable",broadcast:"unavailable"},signaling:{coordinationGateway:true,nativeIpc:true,managedPresence:true},transport:{irohQuic:true,irohLan:false,webRtc:false,moq:false,ble:false,wasm:false},nativeProtocols:{productAlpn:true,irohDocs:true,irohBlobs:true,irohGossip:true},lifecycle:{managedSession:true,autoConnect:true,manualDisconnect:true,connectionStateEvents:true,peerSessions:true},transfers:{explicitFilePath:true,explicitFileData:true,history:true},fallback:{wasm:false}};function He(t){return {adapter:t.adapter,productMaturity:t.productMaturity?{...t.productMaturity}:void 0,signaling:{...t.signaling},transport:{...t.transport},nativeProtocols:{...t.nativeProtocols},lifecycle:{...t.lifecycle},transfers:{...t.transfers},fallback:{...t.fallback}}}function Mn(t=globalThis){let e=He(Lt),n=typeof t?.RTCPeerConnection=="function";return e.transport.webRtc=n,e}function j(t){return t?.compiled===true&&t.enabled===true}function Cn(t,e=false){let n=He(Ht),i=t?.transport;return n.productMaturity={...n.productMaturity,...t?.productMaturity},i&&(n.transport.irohQuic=j(i.irohQuic),n.transport.irohLan=j(i.irohLan),n.transport.webRtc=j(i.webRtc),n.transport.moq=j(i.moq),n.transport.ble=j(i.ble)),n.transport.wasm=false,n.fallback.wasm=e,n}function kn(t){return {environment:t.adapter==="native-ipc"||t.adapter==="tauri-ipc"?"native":t.adapter==="browser-wasm"?"web":"unknown",productMaturity:t.productMaturity?{...t.productMaturity}:void 0,transports:{quic:t.transport.irohQuic,irohRelay:t.transport.irohQuic||t.adapter==="browser-wasm",irohLan:t.transport.irohLan,webRtc:t.transport.webRtc,moq:t.transport.moq,ble:t.transport.ble},lifecycle:{...t.lifecycle},storage:{localFileSystem:t.transfers.explicitFilePath,transferHistory:t.transfers.history},nativeProtocols:{...t.nativeProtocols}}}function Be(t){if(t.errorCode)return t;let e=t.error||t.readinessReason;if(!e)return t;let n=c(e);return {...t,errorCode:n.errorCode,retryable:n.retryable,errorPlane:n.errorPlane}}function K(t){return !t||typeof t!="object"?{}:t instanceof Map?Object.fromEntries(t):t}function ce(t){let e=K(t),n=K(e.device);if(!Object.keys(n).length)return e;let i={...n,...e};return delete i.device,i}function m(t,...e){for(let n of e){let i=t[n];if(typeof i=="string"&&i.trim().length>0)return i}}function P(t,...e){for(let n of e){let i=t[n];if(typeof i=="boolean")return i}}function b(t,...e){for(let n of e){let i=t[n];if(typeof i=="number"&&Number.isFinite(i))return i}}function _(t){if(typeof t=="number"&&Number.isFinite(t))return t;if(t instanceof Date){let e=t.getTime();return Number.isFinite(e)?e:void 0}if(typeof t=="string"){let e=Date.parse(t);return Number.isFinite(e)?e:void 0}if(t&&typeof t=="object"){let e=t;if(typeof e.toMillis=="function"){let i=e.toMillis();return Number.isFinite(i)?i:void 0}let n=typeof e.seconds=="number"?e.seconds:typeof e._seconds=="number"?e._seconds:void 0;if(n!==void 0&&Number.isFinite(n)){let i=typeof e.nanoseconds=="number"?e.nanoseconds:typeof e._nanoseconds=="number"?e._nanoseconds:0;return n*1e3+Math.floor((Number.isFinite(i)?i:0)/1e6)}}}function de(...t){let e=t.map(_).filter(n=>typeof n=="number"&&Number.isFinite(n));return e.length?Math.max(...e):void 0}function le(t){if(typeof t!="string")return;let e=t.trim().toLowerCase();return e==="online"||e==="idle"||e==="offline"?e:void 0}function Ue(t){let e=le("presenceStatus"in t?t.presenceStatus:void 0),n="presenceUpdatedAt"in t?_(t.presenceUpdatedAt):void 0,i="presenceExpiresAt"in t?_(t.presenceExpiresAt):void 0,r=n??de(t.lastSeenAt,t.updatedAt,t.createdAt),o=i??_(t.expiresAt),s=e;s||(t.online?r!==void 0&&r+3e5<=Date.now()?s="idle":s="online":s="offline");let c=typeof t.ticket=="string"?t.ticket.trim():"",a="connectable"in t&&typeof t.connectable=="boolean"?t.connectable:s==="online"&&c.length>0;return {presenceStatus:s,presenceUpdatedAt:r,presenceExpiresAt:o,connectable:a}}function Fe(t){return l(t)}function x(t,...e){return Fe(m(t,...e))}function W(t){if(!Array.isArray(t))return;let e=Array.from(new Set(t.map(Fe).filter(n=>!!n)));return e.length?e:void 0}function je(t){let e=K(t),n={webrtc:b(e,"webrtc"),iroh:b(e,"iroh"),irohLan:b(e,"irohLan","iroh_lan"),irohRelay:b(e,"irohRelay","iroh_relay"),ble:b(e,"ble"),moq:b(e,"moq")};return Object.values(n).some(i=>i!==void 0)?n:void 0}function On(t){return (t.discoveryMode??"space")==="space"&&typeof t.apiKey=="string"&&t.apiKey.trim().length>0&&typeof t.spaceKey=="string"&&t.spaceKey.trim().length>0}function Gn(t,e,n){return n?true:(typeof t.appTag=="string"?t.appTag:typeof t.tag=="string"?t.tag:void 0)===e}function Bt(t,e){let n=ce(t),i=m(n,"deviceId","device_id")||e||"",r=m(n,"nodeId","node_id")||"",o=m(n,"ticket")||"";return {deviceId:i,deviceName:m(n,"deviceName","device_name")||"Unknown Device",online:!!n.online,ticket:o,friendTicket:m(n,"friendTicket","friend_ticket"),presenceStatus:le(m(n,"presenceStatus","presence_status","livenessStatus","liveness_status")),presenceUpdatedAt:b(n,"presenceUpdatedAt","presence_updated_at")??de(n.presenceUpdatedAt,n.presence_updated_at,n.lastSeenAt,n.last_seen_at,n.updatedAt,n.updated_at,n.createdAt,n.created_at),presenceExpiresAt:b(n,"presenceExpiresAt","presence_expires_at")??_(n.presenceExpiresAt??n.presence_expires_at)??_(n.expiresAt??n.expires_at),connectable:P(n,"connectable"),kind:m(n,"kind"),nodeId:r||void 0,devicePublicKeyJwk:n.devicePublicKeyJwk??n.device_public_key_jwk,platformType:m(n,"platformType","platform_type"),capabilities:n.capabilities||void 0,sessionId:m(n,"sessionId","session_id"),userId:m(n,"userId","user_id"),lastSeenAt:n.lastSeenAt??n.last_seen_at,expiresAt:n.expiresAt??n.expires_at,createdAt:n.createdAt??n.created_at,updatedAt:n.updatedAt??n.updated_at,metadata:m(n,"metadata"),excludedPeers:X(n.excludedPeers??n.excluded_peers),availableTransports:W(n.availableTransports??n.available_transports),transports:W(n.transports),topologyRole:n.topologyRole==="active"||n.topologyRole==="backup"?n.topologyRole:void 0,topologyRevision:Number.isSafeInteger(n.topologyRevision)&&Number(n.topologyRevision)>0?Number(n.topologyRevision):void 0}}function X(t){return Array.isArray(t)?[...new Set(t.filter(e=>typeof e=="string").map(e=>e.trim()).filter(Boolean))]:[]}function Ut(t){let e=Ue(t);return {...t,...e,connectionStatus:"connectionStatus"in t&&typeof t.connectionStatus=="string"?t.connectionStatus:t.online?"online":"disconnected",settledReady:"settledReady"in t&&typeof t.settledReady=="boolean"?t.settledReady:false,readinessState:"readinessState"in t&&typeof t.readinessState=="string"?t.readinessState:void 0,readinessReason:"readinessReason"in t&&typeof t.readinessReason=="string"?t.readinessReason:void 0,peerHealth:"peerHealth"in t&&typeof t.peerHealth=="string"?t.peerHealth:"unknown",peerId:"peerId"in t&&typeof t.peerId=="string"?t.peerId:void 0,promotionEligible:"promotionEligible"in t&&typeof t.promotionEligible=="boolean"?t.promotionEligible:true,scopes:"scopes"in t?X(t.scopes):[],connectionId:"connectionId"in t&&typeof t.connectionId=="string"?t.connectionId:void 0,deviceIdHint:"deviceIdHint"in t&&typeof t.deviceIdHint=="string"?t.deviceIdHint:void 0,transportStableId:"transportStableId"in t&&typeof t.transportStableId=="number"?t.transportStableId:"transportStableId"in t?t.transportStableId??null:void 0,transportGeneration:"transportGeneration"in t&&typeof t.transportGeneration=="number"?t.transportGeneration:void 0,routeGeneration:"routeGeneration"in t&&typeof t.routeGeneration=="number"?t.routeGeneration:void 0,activeTransport:"activeTransport"in t?t.activeTransport:void 0,parallelTransport:"parallelTransport"in t?t.parallelTransport:void 0,availableTransports:"availableTransports"in t?W(t.availableTransports):"transports"in t?W(t.transports):void 0,latencyMs:"latencyMs"in t&&typeof t.latencyMs=="number"?t.latencyMs:void 0,latencyByTransport:"latencyByTransport"in t?je(t.latencyByTransport):void 0}}function z(t,e){return e===void 0?true:e===null?t==null:t==null||t===e}function ze(t,e){let n=z(t.connectionId,e.connectionId)&&z(t.nodeId,e.nodeId)&&z(t.transportStableId,e.transportStableId)&&z(t.transportGeneration,e.transportGeneration)&&z(t.routeGeneration,e.routeGeneration),i=(r,o)=>r!==void 0?r:n?o:void 0;return {inheritsSnapshot:n,fields:{connectionId:i(e.connectionId??void 0,t.connectionId),transportStableId:i(e.transportStableId,t.transportStableId),transportGeneration:i(e.transportGeneration,t.transportGeneration),routeGeneration:i(e.routeGeneration,t.routeGeneration),activeTransport:i(e.activeTransport,t.activeTransport),parallelTransport:i(e.parallelTransport,t.parallelTransport),latencyMs:n?t.latencyMs:void 0,latencyByTransport:n?t.latencyByTransport:void 0}}}var Ft={connectionId:void 0,transportStableId:null,transportGeneration:void 0,routeGeneration:void 0,activeTransport:void 0,parallelTransport:void 0,latencyMs:void 0,latencyByTransport:void 0};function jt(t,e,n){let i=ze(t,{connectionId:e.activeConnectionId,nodeId:e.nodeId,transportStableId:e.transportStableId,transportGeneration:e.transportGeneration,routeGeneration:e.routeGeneration,activeTransport:e.activeTransport,parallelTransport:e.parallelTransport}),r=n?n({connectionId:e.activeConnectionId??void 0,deviceId:e.deviceId??void 0,deviceIdHint:e.deviceIdHint??void 0,nodeId:e.nodeId??void 0}):t.promotionEligible??true;if(!r)return {...t,peerHealth:e.health??t.peerHealth,peerId:e.peerId??t.peerId,promotionEligible:r,scopes:e.scopes?.length?[...e.scopes]:t.scopes,nodeId:e.nodeId===void 0?t.nodeId:e.nodeId??void 0,deviceIdHint:e.deviceIdHint??t.deviceIdHint,...i.fields,readinessReason:e.readinessReason??t.readinessReason};let o=e.status??t.connectionStatus,s=typeof o=="string"?o.trim().toLowerCase():"",c=s==="failed"||s==="closed"||s==="disconnected",d=typeof e.readinessState=="string"&&e.readinessState.trim().length>0?e.readinessState==="routable":e.settledReady===true,u=t.settledReady===true||t.readinessState==="routable";if(i.inheritsSnapshot&&u&&!c&&!d)return {...t,peerHealth:e.health??t.peerHealth,peerId:e.peerId??t.peerId,promotionEligible:r,scopes:e.scopes?.length?[...e.scopes]:t.scopes,nodeId:e.nodeId===void 0?t.nodeId:e.nodeId??void 0,deviceIdHint:e.deviceIdHint??t.deviceIdHint,...i.fields,readinessReason:e.readinessReason??t.readinessReason};let p=c?false:d,y=d&&!c&&(s==="connecting"||s==="connected")?"connected":o,l=d?"routable":e.readinessState??(i.inheritsSnapshot?t.readinessState:void 0),R=p?e.readinessReason??"peer-session-settled":e.readinessReason??(i.inheritsSnapshot?t.readinessReason:void 0);return {...t,connectionStatus:y,settledReady:p,readinessState:l,readinessReason:R,peerHealth:e.health??t.peerHealth,peerId:e.peerId??t.peerId,promotionEligible:r,scopes:e.scopes?.length?[...e.scopes]:t.scopes,nodeId:e.nodeId===void 0?t.nodeId:e.nodeId??void 0,deviceIdHint:e.deviceIdHint??t.deviceIdHint,...i.fields}}function zt(t,e){let n=ze(t,{connectionId:e.connectionId,nodeId:e.nodeId,transportStableId:e.transportStableId,transportGeneration:e.transportGeneration,routeGeneration:e.routeGeneration,activeTransport:e.activeTransport,parallelTransport:e.parallelTransport});if(e.promotionEligible===false)return {...t,peerHealth:e.health??t.peerHealth,peerId:e.peerId??t.peerId,promotionEligible:false,nodeId:e.nodeId??t.nodeId,deviceIdHint:e.deviceIdHint??t.deviceIdHint,...n.fields,scopes:e.scopes?.length?[...e.scopes]:t.scopes};let i=e.status??t.connectionStatus,r=typeof i=="string"?i.trim().toLowerCase():"",o=r==="failed"||r==="closed"||r==="disconnected",s=t.settledReady===true||t.readinessState==="routable",c=e.routable===false;if(n.inheritsSnapshot&&s&&o&&!c)return {...t,peerHealth:t.peerHealth??e.health,peerId:t.peerId??e.peerId,promotionEligible:e.promotionEligible??t.promotionEligible??true,connectionId:t.connectionId??e.connectionId,deviceIdHint:t.deviceIdHint??e.deviceIdHint,scopes:t.scopes?.length?t.scopes:e.scopes??t.scopes};if(s&&o)return {...t,connectionStatus:i,settledReady:false,readinessState:void 0,readinessReason:e.error??t.readinessReason,peerHealth:e.health??t.peerHealth,peerId:e.peerId??t.peerId,promotionEligible:e.promotionEligible??t.promotionEligible??true,deviceIdHint:e.deviceIdHint??t.deviceIdHint,...Ft,scopes:e.scopes?.length?[...e.scopes]:t.scopes};let a=e.routable===true||e.protocolState==="routable";if(n.inheritsSnapshot&&s&&!o&&!a)return {...t,peerHealth:t.peerHealth??e.health,peerId:t.peerId??e.peerId,promotionEligible:e.promotionEligible??t.promotionEligible??true,connectionId:t.connectionId??e.connectionId,deviceIdHint:t.deviceIdHint??e.deviceIdHint,transportStableId:t.transportStableId??e.transportStableId,transportGeneration:t.transportGeneration??e.transportGeneration,routeGeneration:t.routeGeneration??e.routeGeneration,activeTransport:t.activeTransport??e.activeTransport,parallelTransport:t.parallelTransport===void 0?e.parallelTransport:t.parallelTransport,scopes:t.scopes?.length?t.scopes:e.scopes??t.scopes};let d=e.transportState==="connected"&&e.health==="healthy",u=o?false:a,p=!o&&(a||d)&&(r==="connecting"||r==="connected"||e.transportState==="connected")?"connected":i,y=u?"routable":(e.routable===false&&e.protocolState?e.protocolState:void 0)??(n.inheritsSnapshot?t.readinessState:void 0)??(e.status==="connecting"?e.transportState==="connected"?"transport-only":"connecting":void 0),l=u?(n.inheritsSnapshot?t.readinessReason:void 0)??(e.routable===true?"peer-projection-routable":void 0):(e.routable===false&&e.error?e.error:void 0)??(n.inheritsSnapshot?t.readinessReason:void 0)??(e.status==="connecting"?e.transportState==="connected"?"peer-projection-transport-ready":"peer-projection-connecting":void 0);return {...t,connectionStatus:p,settledReady:u,readinessState:y,readinessReason:l,peerHealth:e.health??t.peerHealth,peerId:e.peerId??t.peerId,promotionEligible:e.promotionEligible??t.promotionEligible??true,nodeId:e.nodeId??t.nodeId,deviceIdHint:e.deviceIdHint??t.deviceIdHint,...n.fields,scopes:e.scopes?.length?[...e.scopes]:t.scopes}}function Wt(t){let{device:e,session:n=null,peer:i=null,isPromotionEligible:r}=t,o=Ut(e);return n&&(o=jt(o,n,r)),i&&(o=zt(o,i)),Be(o)}function Nn(t){let e=ce(t),n=Bt(e),i=le(m(e,"presenceStatus","presence_status","livenessStatus","liveness_status")),r=Ue({...n,...i?{presenceStatus:i}:{},presenceUpdatedAt:b(e,"presenceUpdatedAt","presence_updated_at")??de(e.presenceUpdatedAt,e.presence_updated_at,e.lastSeenAt,e.last_seen_at,e.updatedAt,e.updated_at,e.createdAt,e.created_at),presenceExpiresAt:b(e,"presenceExpiresAt","presence_expires_at")??_(e.presenceExpiresAt??e.presence_expires_at)??_(e.expiresAt??e.expires_at),connectable:P(e,"connectable")}),o={...n,...r,connectionStatus:m(e,"connectionStatus","connection_status")||"disconnected",settledReady:P(e,"settledReady","settled_ready")??false,readinessState:m(e,"readinessState","readiness_state")??void 0,readinessReason:m(e,"readinessReason","readiness_reason")??void 0,peerHealth:m(e,"peerHealth","peer_health")||"unknown",peerId:m(e,"peerId","peer_id"),scopes:X(e.scopes),connectionId:m(e,"connectionId","connection_id"),deviceIdHint:m(e,"deviceIdHint","device_id_hint"),transportStableId:b(e,"transportStableId","activeTransportStableId","active_transport_stable_id")??void 0,transportGeneration:b(e,"transportGeneration","transport_generation")??void 0,routeGeneration:b(e,"routeGeneration","route_generation")??void 0,activeTransport:x(e,"activeTransport","active_transport"),parallelTransport:x(e,"parallelTransport","parallel_transport")??null,availableTransports:W(e.availableTransports??e.available_transports),latencyMs:b(e,"latencyMs","latency_ms"),latencyByTransport:je(e.latencyByTransport??e.latency_by_transport)};return Wt({device:o})}function Kn(t){let e=ce(t);return Be({peerId:m(e,"peerId","peer_id")||"",deviceId:m(e,"deviceId","device_id"),deviceIdHint:m(e,"deviceIdHint","device_id_hint"),nodeId:m(e,"nodeId","node_id"),activeConnectionId:m(e,"activeConnectionId","active_connection_id"),candidates:Array.isArray(e.candidates)?e.candidates.filter(n=>typeof n=="string"):Array.isArray(e.candidateConnectionIds)?e.candidateConnectionIds.filter(n=>typeof n=="string"):Array.isArray(e.candidate_connection_ids)?e.candidate_connection_ids.filter(n=>typeof n=="string"):[],status:m(e,"status")||"disconnected",health:m(e,"health")||"unknown",settledReady:P(e,"settledReady","settled_ready")??false,readinessState:m(e,"readinessState","readiness_state")??void 0,transportStableId:b(e,"transportStableId","activeTransportStableId","active_transport_stable_id")??void 0,transportGeneration:b(e,"transportGeneration","transport_generation")??void 0,routeGeneration:b(e,"routeGeneration","route_generation")??void 0,activeTransport:x(e,"activeTransport","active_transport"),parallelTransport:x(e,"parallelTransport","parallel_transport")??null,replacementPending:P(e,"replacementPending","replacement_pending")??void 0,logicalSessionTerminal:P(e,"logicalSessionTerminal","logical_session_terminal")??false,lastTransitionAtMs:b(e,"lastTransitionAtMs","lastLifecycleTransitionAtMs","last_lifecycle_transition_at_ms")??void 0,readinessReason:m(e,"readinessReason","readiness_reason")??void 0,transitionCount:b(e,"transitionCount","transition_count")??void 0,connectTransitions:b(e,"connectTransitions","connectingTransitionCount","connecting_transition_count")??void 0,replacementCount:b(e,"replacementCount","replacement_count")??void 0,retireCount:b(e,"retireCount","retire_count")??void 0,lastDisconnectReason:m(e,"lastDisconnectReason","last_disconnect_reason")??void 0,lastReconnectReason:m(e,"lastReconnectReason","last_reconnect_reason")??void 0,scopes:Array.isArray(e.scopes)?e.scopes.filter(n=>typeof n=="string"):[],lastSeenAtMs:typeof e.lastSeenAtMs=="number"?e.lastSeenAtMs:typeof e.last_seen_at_ms=="number"?e.last_seen_at_ms:0,error:m(e,"error"),errorCode:m(e,"errorCode","error_code")??void 0,retryable:P(e,"retryable")??void 0,errorPlane:m(e,"errorPlane","error_plane")??void 0})}function Ln(t){let e=K(t);return {connectionId:typeof e.connectionId=="string"?e.connectionId:"",nodeId:typeof e.nodeId=="string"?e.nodeId:null,deviceId:typeof e.deviceId=="string"?e.deviceId:null,deviceIdHint:typeof e.deviceIdHint=="string"?e.deviceIdHint:null,endpointId:typeof e.endpointId=="string"?e.endpointId:null,transportGeneration:typeof e.transportGeneration=="number"?e.transportGeneration:0,routeGeneration:typeof e.routeGeneration=="number"?e.routeGeneration:void 0,transportStableId:typeof e.transportStableId=="number"?e.transportStableId:null,transportSource:typeof e.transportSource=="string"?e.transportSource:null,lastTransportChangeAtMs:typeof e.lastTransportChangeAtMs=="number"?e.lastTransportChangeAtMs:0,lastRouteChangeAtMs:typeof e.lastRouteChangeAtMs=="number"?e.lastRouteChangeAtMs:void 0,state:typeof e.state=="string"?e.state:"pending",statusReason:typeof e.statusReason=="string"?e.statusReason:null,transitionCount:typeof e.transitionCount=="number"?e.transitionCount:void 0,connectTransitions:typeof e.connectTransitions=="number"?e.connectTransitions:void 0,replacementCount:typeof e.replacementCount=="number"?e.replacementCount:void 0,retireCount:typeof e.retireCount=="number"?e.retireCount:void 0,lastDisconnectReason:typeof e.lastDisconnectReason=="string"?e.lastDisconnectReason:void 0,lastReconnectReason:typeof e.lastReconnectReason=="string"?e.lastReconnectReason:void 0,createdAtMs:typeof e.createdAtMs=="number"?e.createdAtMs:0,updatedAtMs:typeof e.updatedAtMs=="number"?e.updatedAtMs:0}}function Hn(t){let e=K(t);return {peerId:typeof e.peerId=="string"?e.peerId:null,deviceId:typeof e.deviceId=="string"?e.deviceId:null,deviceIdHint:typeof e.deviceIdHint=="string"?e.deviceIdHint:null,nodeId:typeof e.nodeId=="string"?e.nodeId:null}}function qt(t){switch(t){case "connected":return "connected";case "connecting":return "connecting";case "failed":return "failed";default:return "closed"}}function Bn(t){let e=t.activeConnectionId||t.candidates[0]||null;if(!e)return null;let n=qt(t.status),i=n==="connected"?"connected":n==="connecting"?"connecting":"closed",r=n==="connected"?t.settledReady?"routable":"transport-only":n==="connecting"?"connecting":"closed";return {connectionId:e,deviceId:t.deviceId??null,deviceIdHint:t.deviceIdHint??null,remoteNodeId:t.nodeId??null,state:n,transportState:i,protocolState:r,routable:!!t.settledReady,readinessState:t.readinessState,readinessReason:t.readinessReason,transportGeneration:t.transportGeneration,routeGeneration:t.routeGeneration,transportStableId:t.transportStableId,activeTransport:t.activeTransport,parallelTransport:t.parallelTransport??null,replacementInProgress:t.replacementPending,logicalSessionTerminal:t.logicalSessionTerminal===true,lastTransitionAtMs:t.lastTransitionAtMs,transitionCount:t.transitionCount,connectTransitions:t.connectTransitions,replacementCount:t.replacementCount,retireCount:t.retireCount,lastDisconnectReason:t.lastDisconnectReason??void 0,lastReconnectReason:t.lastReconnectReason??void 0,updatedAt:t.lastSeenAtMs,error:t.error??void 0}}function $t(t){if(!t||typeof t!="object")return null;let e=t;return ["acceptedWriteObjects","acceptedWriteBytes","completedReceivedObjects","completedReceivedBytes"].every(i=>typeof e[i]=="number"&&Number.isSafeInteger(e[i])&&e[i]>=0)?Object.freeze({acceptedWriteObjects:e.acceptedWriteObjects,acceptedWriteBytes:e.acceptedWriteBytes,completedReceivedObjects:e.completedReceivedObjects,completedReceivedBytes:e.completedReceivedBytes}):null}function Un(t){let e=K(t),n=m(e,"connectionId","connection_id");if(!n)return null;let i=m(e,"state")||"connecting",r=b(e,"createdAt","created_at")??b(e,"updatedAt","updated_at")??Date.now(),o=b(e,"updatedAt","updated_at")??r;return {connectionId:n,deviceId:m(e,"deviceId","device_id"),deviceIdHint:m(e,"deviceIdHint","device_id_hint"),remoteNodeId:m(e,"remoteNodeId","remote_node_id"),state:i,transportState:m(e,"transportState","transport_state")??(i==="connected"?"connected":i==="connecting"?"connecting":"closed"),protocolState:m(e,"protocolState","protocol_state")??(i==="connected"?"routable":i==="connecting"?"connecting":"closed"),routable:P(e,"routable")??false,scopes:X(e.scopes),logicalSessionTerminal:P(e,"logicalSessionTerminal","logical_session_terminal")??false,readinessState:m(e,"readinessState","readiness_state")??void 0,readinessReason:m(e,"readinessReason","readiness_reason")??void 0,transportGeneration:b(e,"transportGeneration","transport_generation")??void 0,routeGeneration:b(e,"routeGeneration","route_generation")??void 0,transportStableId:b(e,"transportStableId","activeTransportStableId","active_transport_stable_id")??void 0,activeTransport:x(e,"activeTransport","active_transport"),parallelTransport:x(e,"parallelTransport","parallel_transport")??null,latencyMs:b(e,"latencyMs","latency_ms")??null,carrier:x(e,"carrier")??null,metricsSampledAtMs:b(e,"metricsSampledAtMs","metrics_sampled_at_ms")??null,moqObjectQuantities:$t(e.moqObjectQuantities??e.moq_object_quantities),replacementInProgress:P(e,"replacementInProgress","replacement_in_progress")??void 0,lastTransitionAtMs:b(e,"lastTransitionAtMs","lastLifecycleTransitionAtMs","last_lifecycle_transition_at_ms")??void 0,transitionCount:b(e,"transitionCount","transition_count")??void 0,connectTransitions:b(e,"connectTransitions","connectingTransitionCount","connecting_transition_count")??void 0,replacementCount:b(e,"replacementCount","replacement_count")??void 0,retireCount:b(e,"retireCount","retire_count")??void 0,lastDisconnectReason:m(e,"lastDisconnectReason","last_disconnect_reason")??void 0,lastReconnectReason:m(e,"lastReconnectReason","last_reconnect_reason")??void 0,error:m(e,"error")??void 0,createdAt:r,updatedAt:o}}function Fn(t,e){return t?t.connectionId===e.connectionId&&(t.deviceId??null)===(e.deviceId??null)&&(t.deviceIdHint??null)===(e.deviceIdHint??null)&&(t.remoteNodeId??null)===(e.remoteNodeId??null)&&t.state===e.state&&(t.transportState??null)===(e.transportState??null)&&(t.protocolState??null)===(e.protocolState??null)&&!!t.routable==!!e.routable&&JSON.stringify(t.scopes??[])===JSON.stringify(e.scopes??[])&&(t.activeTransport??null)===(e.activeTransport??null)&&(t.parallelTransport??null)===(e.parallelTransport??null)&&(t.transportStableId??null)===(e.transportStableId??null)&&(t.transportGeneration??null)===(e.transportGeneration??null)&&(t.routeGeneration??null)===(e.routeGeneration??null)&&!!t.replacementInProgress==!!e.replacementInProgress&&!!t.logicalSessionTerminal==!!e.logicalSessionTerminal&&(t.transitionCount??null)===(e.transitionCount??null)&&(t.connectTransitions??null)===(e.connectTransitions??null)&&(t.replacementCount??null)===(e.replacementCount??null)&&(t.retireCount??null)===(e.retireCount??null)&&(t.lastDisconnectReason??null)===(e.lastDisconnectReason??null)&&(t.lastReconnectReason??null)===(e.lastReconnectReason??null)&&(t.error??null)===(e.error??null):false}
|
|
2
|
+
export{ce as A,On as B,Gn as C,Bt as D,Wt as E,Nn as F,Kn as G,Ln as H,Hn as I,Bn as J,Un as K,Fn as L,fe as a,We as b,qe as c,Vt as d,Qt as e,_e as f,ht as g,ln as h,un as i,pn as j,De as k,mn as l,bn as m,wn as n,Sn as o,Rn as p,In as q,Gt as r,Kt as s,Tn as t,Lt as u,Ht as v,He as w,Mn as x,Cn as y,kn as z};
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { P as PolicySnapshot, a as PeerReconciliationStats, R as RuntimeClient, b as PlutoRuntimeAssembly } from './assembly-
|
|
2
|
-
import { k as RuntimePeerState, l as PeerConnectOptions, m as Connection, n as PeerSessionSnapshot, o as PeerReadiness, p as RuntimePeerHealth, q as ResolvedPeerIdentity, C as ChannelDescriptor, r as PeerStreamOptions, I as IncomingStream, s as ScopedChannelOptions, t as RuntimeDevice, u as ScopedLogicalChannel, v as ConnectionState, w as ReadinessOptions, x as ConnectionEvent, d as TransferPeerDemandRequest, f as TransferPeerDemandStatus, M as ManagedOptions, y as ManagedSession, D as DeviceStatus, z as DeviceConnectOptions, A as ConnectDeviceResult, B as ConnectDeviceHooks, F as ConnectDeviceOptions, L as LocalDeviceInfo, G as DeviceProfile, H as RawConnection, J as JoinRoomOptions, K as RuntimeRoomMember, N as GrantScope, O as AuthContext, Q as RuntimeClientOptions } from './Connection-
|
|
3
|
-
import { R as RuntimeCapabilities, C as CapabilityProfile } from './capabilities-
|
|
1
|
+
import { P as PolicySnapshot, a as PeerReconciliationStats, R as RuntimeClient, b as PlutoRuntimeAssembly } from './assembly-DGrOqsLW.js';
|
|
2
|
+
import { k as RuntimePeerState, l as PeerConnectOptions, m as Connection, n as PeerSessionSnapshot, o as PeerReadiness, p as RuntimePeerHealth, q as ResolvedPeerIdentity, C as ChannelDescriptor, r as PeerStreamOptions, I as IncomingStream, s as ScopedChannelOptions, t as RuntimeDevice, u as ScopedLogicalChannel, v as ConnectionState, w as ReadinessOptions, x as ConnectionEvent, d as TransferPeerDemandRequest, f as TransferPeerDemandStatus, M as ManagedOptions, y as ManagedSession, D as DeviceStatus, z as DeviceConnectOptions, A as ConnectDeviceResult, B as ConnectDeviceHooks, F as ConnectDeviceOptions, L as LocalDeviceInfo, G as DeviceProfile, H as RawConnection, J as JoinRoomOptions, K as RuntimeRoomMember, N as GrantScope, O as AuthContext, Q as RuntimeClientOptions } from './Connection-BGVBMbWg.js';
|
|
3
|
+
import { R as RuntimeCapabilities, C as CapabilityProfile } from './capabilities-DsKud7Sw.js';
|
|
4
4
|
|
|
5
5
|
interface DiagnosticPeer {
|
|
6
6
|
/** Capture-local alias. Full user/device/node/connection IDs are excluded. */
|
package/dist/coreClient.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import './assembly-
|
|
2
|
-
import './Connection-
|
|
3
|
-
export { A as AdvancedNamespace, i as ChannelConnectOptions, C as ChannelNamespace, h as Client, a as DeviceNamespace, j as DeviceSessionOptions, D as DiagnosticsNamespace, P as PeerNamespace, R as RoomNamespace, T as TicketNamespace, r as resolveOptions, w as wrapAssembly } from './coreClient-
|
|
4
|
-
import './capabilities-
|
|
1
|
+
import './assembly-DGrOqsLW.js';
|
|
2
|
+
import './Connection-BGVBMbWg.js';
|
|
3
|
+
export { A as AdvancedNamespace, i as ChannelConnectOptions, C as ChannelNamespace, h as Client, a as DeviceNamespace, j as DeviceSessionOptions, D as DiagnosticsNamespace, P as PeerNamespace, R as RoomNamespace, T as TicketNamespace, r as resolveOptions, w as wrapAssembly } from './coreClient-ByXs38IP.js';
|
|
4
|
+
import './capabilities-DsKud7Sw.js';
|
package/dist/coreClient.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import {l}from'./chunk-L4HWDDXL.js';import'./chunk-OWKAJPOI.js';import {c}from'./chunk-
|
|
1
|
+
import {l}from'./chunk-L4HWDDXL.js';import'./chunk-OWKAJPOI.js';import {c}from'./chunk-NC375DSH.js';import'./chunk-2GX6GB6L.js';function w(o){let r=l({...o});if("auth"in o&&!o.authMode){let n=o.auth;r.authMode=n==="none"?"anonymous":n;}if("identity"in o){let n=o.identity,s=n==="temporary"?"ephemeral":n;!o.deviceIdPersistence&&!o.nodeIdPersistence&&(r.deviceIdPersistence=s),!o.endpointIdPersistence&&!o.nodeIdPersistence&&(r.endpointIdPersistence=s);}return "namespace"in o&&!o.storagePrefix&&(r.storagePrefix=o.namespace),"privacy"in o&&o.strictMode===void 0&&(r.strictMode=!!o.privacy),r}function O(o,r){let n=o.runtime,s=Object.create(n),d=async e=>{if(typeof e!="string")return e;let i=(await n.listDevices()).find(a=>a.deviceId===e);if(!i)throw new Error(`OpenRTC device '${e}' is not currently discoverable.`);return i},g=async e=>({...e,localDeviceId:e?.localDeviceId??await n.getLocalDeviceId()??""}),P=async e=>{let{device:t,scope:i,...a}=e,c=a.deviceId??(typeof t=="string"?t:t?.deviceId)??null,l=a.ticket??(typeof t=="string"?void 0:t?.ticket);c&&!l&&(l=(await d(c).catch(()=>null))?.ticket);let m={...a,scope:i??"session"};return c&&(m.deviceId=c),l&&(m.ticket=l),m},v={requestTransferPeer:e=>n.requestTransferPeer(e),transferPeerDemandStatus:(e,t)=>n.transferPeerDemandStatus(e,t),releaseTransferPeer:(e,t)=>n.releaseTransferPeer(e,t),setTransferPeerBudget:(e,t)=>n.setTransferPeerBudget(e,t),list:()=>n.listDevices(),startSession:(e={})=>n.startManagedSession({...e,platform:e.platform??r}),stopSession:e=>n.stopManagedSession(e),listWithStatus:()=>n.listDeviceStatus(),watch:e=>n.watchDevices(e),watchWithStatus:e=>n.watchDeviceStatus(e),connect:async(e,t)=>n.connectDevice(await d(e),await g(t)),connectWithRetry:async(e,t,i)=>n.connectWithRetry(await d(e),t,i),disconnect:e=>n.disconnectDevice(e),update:(e,t)=>n.updateDevice(e,t),delete:e=>n.deleteDevice(e),localId:()=>n.getLocalDeviceId(),localInfo:()=>n.getLocalDeviceInfo(),localProfile:e=>n.localDeviceProfile(e),updateLocalName:e=>n.updateDeviceName(e)},C={watch:e=>n.watchPeerStates(e),watchLifecycle:e=>typeof n.watchPeerLifecycle=="function"?n.watchPeerLifecycle(e):typeof n.watchPeerStates=="function"?n.watchPeerStates(e):()=>{},get:e=>n.getPeerState(e),listConnected:()=>n.listConnectedPeers(),connect:e=>n.connectPeer(e),disconnect:(e,t)=>n.disconnectPeer(e,t),forceDisconnect:e=>n.forceDisconnectPeer(e),session:e=>n.getPeerSession(e),sessions:()=>n.listPeerSessions(),waitConnected:(e,t)=>n.waitForConnectedPeer(e,t),readiness:(e,t)=>n.getPeerReadiness(e,t),health:e=>n.getPeerHealth(e),identity:e=>n.resolvePeerIdentity(e),addScope:(e,t)=>n.addPeerScope(e,t),releaseScope:(e,t)=>n.releasePeerScope(e,t),scopes:e=>n.getPeerScopes(e),refresh:()=>n.refreshPeerSnapshot()},h={register:e=>n.registerChannel(e),unregister:e=>n.unregisterChannel(e),list:()=>n.listChannels(),openBi:(e,t,i)=>n.openPeerBi(e,{...i,channelId:t}),openUni:(e,t,i)=>n.openPeerUni(e,{...i,channelId:t}),onIncoming:e=>n.onIncomingStream(e),onIncomingChannel:(e,t)=>n.onChannelStream(e,i=>{if(i.channel)return t(i)}),connect:async e=>n.connectScopedChannel(await P(e)),connectScoped:e=>n.connectScopedChannel(e)},S={create:e=>n.createRoom(e),join:(e,t)=>n.joinRoom(e,t),leave:e=>n.leaveRoom(e),watch:(e,t)=>n.watchRoom(e,t),members:e=>n.getRoomMembers(e)},f={raw:()=>n.getInvite(),share:e=>n.getTicketWithToken("share",e?.maxConnections??1),grant:(e,t)=>n.getTicketWithToken(e,t?.maxConnections??0),revoke:e=>n.revokeTokensByScope(e)},b={capture:e=>c(t=>n.watchPeerStates(t),e),status:()=>n.getRuntimeStatus(),policy:()=>n.getRuntimePolicy(),capabilities:()=>n.capabilities(),capabilityProfile:()=>n.getCapabilityProfile(),watchConnectionMetrics:e=>n.watchConnectionMetrics(e),connectionStates:()=>n.getConnectionStates(),onStateChange:e=>n.onStateChange(e),connections:()=>n.getConnections(),applicationReadyConnections:e=>n.readyConnections(e),onConnection:e=>n.onConnection(e),onDisconnection:e=>n.onDisconnection(e),onConnectionEvent:e=>n.onConnectionEvent(e),forceReconnect:()=>n.forceReconnect(),peerReconciliation:()=>n.reconciliationStats()},y={runtime:n,assembly:o,nodeId:()=>n.getNodeId(),nodeIdFromTicket:e=>n.getNodeIdFromTicket(e),endpointTicket:()=>n.getEndpointTicket(),connectRaw:e=>n.connectRaw(e),openBi:e=>n.openBi(e),openUni:e=>n.openUni(e),isConnected:e=>n.isConnected(e),disconnectNode:e=>n.disconnectNode(e),excludeAutoConnect:(e,t)=>n.excludeAutoConnect(e,t),notifyNetworkChange:e=>n.notifyNetworkChange(e)};return Object.defineProperties(s,{devices:{get:()=>v,enumerable:true},peers:{get:()=>C,enumerable:true},channels:{get:()=>h,enumerable:true},rooms:{get:()=>S,enumerable:true},tickets:{get:()=>f,enumerable:true},diagnostics:{get:()=>b,enumerable:true},advanced:{get:()=>y,enumerable:true},setAuth:{value:e=>o.setAuthContext(e),enumerable:true,writable:true,configurable:true},setAuthContext:{value:e=>o.setAuthContext(e),enumerable:true,writable:true,configurable:true},syncPlutoAuth:{value:e=>o.syncPlutoAuth(e),enumerable:true,writable:true,configurable:true},bindPlutoAuthHost:{value:()=>o.bindPlutoAuthHost(),enumerable:true,writable:true,configurable:true},signIn:{value:()=>o.signInWithPluto(),enumerable:true,writable:true,configurable:true},signOut:{value:()=>o.signOut(),enumerable:true,writable:true,configurable:true},runtime:{get:()=>n,enumerable:false},_assembly:{get:()=>o,enumerable:false}}),s}export{w as resolveOptions,O as wrapAssembly};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import {h as h$1}from'./chunk-
|
|
1
|
+
import {h as h$1}from'./chunk-4TOWICSH.js';import'./chunk-FKAQDDUM.js';import'./chunk-ZA44REGI.js';import'./chunk-NC375DSH.js';import'./chunk-IUU6JCLK.js';import'./chunk-CCCYE3XN.js';import'./chunk-JPBW67B3.js';import'./chunk-L7N4T2PX.js';import'./chunk-72MN7BNQ.js';import'./chunk-2GX6GB6L.js';var h=class extends h$1{constructor(e,t,u,S){super("devices",e,t,u);this.roster=S;this.kind="devices";this.rosterStopped=false;this.localId=()=>this.client.devices.localId();this.localInfo=()=>this.client.devices.localInfo();this.list=async()=>this.roster.mergeDevices(await this.client.devices.list());this.listWithStatus=async()=>this.roster.mergeStatus(await this.client.devices.listWithStatus());this.watch=e=>this.client.devices.watch(t=>e(this.roster.mergeDevices(t)));this.requestTransferPeer=async e=>{if(this.closed)throw new Error("[OpenRTC] Capability is closed.");return this.client.devices.requestTransferPeer(e)};this.transferPeerDemandStatus=async(e,t)=>{if(this.closed)throw new Error("[OpenRTC] Capability is closed.");return this.client.devices.transferPeerDemandStatus(e,t)};this.releaseTransferPeer=async(e,t)=>{if(this.closed)throw new Error("[OpenRTC] Capability is closed.");return this.client.devices.releaseTransferPeer(e,t)};this.setTransferPeerBudget=async(e,t)=>{if(this.closed)throw new Error("[OpenRTC] Capability is closed.");return this.client.devices.setTransferPeerBudget(e,t)};this.connect=this.client.devices.connect;this.disconnect=this.client.devices.disconnect;let p=t.devices.list,m=t.devices.listWithStatus,c=t.devices.watch,f=t.devices.watchWithStatus,i=s=>(this.roster.reconcileLiveSnapshot(s),s),a=async()=>this.roster.mergeDevices(i(await p())),o=async()=>this.roster.mergeStatus(await m()),n=s=>c(r=>s(this.roster.mergeDevices(i(r)))),l=s=>f(r=>s(this.roster.mergeStatus(r))),d=Object.create(t);Object.defineProperties(d,{listDevices:{value:a,enumerable:false},listDeviceStatus:{value:o,enumerable:false},watchDevices:{value:n,enumerable:false},watchDeviceStatus:{value:l,enumerable:false},devices:{value:{...t.devices,list:a,listWithStatus:o,watch:n,watchWithStatus:l},enumerable:true}}),this.projectRuntime(d),this.stopRosterSync=c(i);}replaceEnrolledDevices(e){this.roster.replace(e);}removeEnrolledDevice(e){this.roster.remove(e);}retainCurrentEnrolledDevice(e){this.roster.retain(e);}beforeRuntimeShutdown(){this.rosterStopped||(this.stopRosterSync(),this.rosterStopped=true);}};export{h as DeviceHandle};
|
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import { C as Client, e as BroadcastGrant, O as Options } from './types-
|
|
2
|
-
import './coreClient-
|
|
3
|
-
import './assembly-
|
|
4
|
-
import './Connection-
|
|
5
|
-
import './capabilities-
|
|
1
|
+
import { C as Client, e as BroadcastGrant, O as Options } from './types-YGlXXpQA.js';
|
|
2
|
+
import './coreClient-ByXs38IP.js';
|
|
3
|
+
import './assembly-DGrOqsLW.js';
|
|
4
|
+
import './Connection-BGVBMbWg.js';
|
|
5
|
+
import './capabilities-DsKud7Sw.js';
|
|
6
6
|
|
|
7
7
|
type ExternalBroadcastRelay = {
|
|
8
8
|
kind: 'sfu';
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import {a as a$1}from'./chunk-5VJXDYP6.js';import'./chunk-IXQ4KWGP.js';import'./chunk-AYHD4X2R.js';import {a}from'./chunk-IAYQJZQQ.js';import'./chunk-GMPEZXPD.js';import {i}from'./chunk-
|
|
1
|
+
import {a as a$1}from'./chunk-5VJXDYP6.js';import'./chunk-IXQ4KWGP.js';import'./chunk-AYHD4X2R.js';import {a}from'./chunk-IAYQJZQQ.js';import'./chunk-GMPEZXPD.js';import {i}from'./chunk-4TOWICSH.js';import'./chunk-FKAQDDUM.js';import'./chunk-ZA44REGI.js';import'./chunk-NC375DSH.js';import'./chunk-IUU6JCLK.js';import'./chunk-CCCYE3XN.js';import'./chunk-JPBW67B3.js';import'./chunk-L7N4T2PX.js';import'./chunk-72MN7BNQ.js';import'./chunk-2GX6GB6L.js';async function K(r,e){if(!/^pk_(?:live|test)_[0-9a-f]{40}$/.test(r)||!/^[A-Za-z0-9_-]{1,64}$/.test(e))throw new Error("[OpenRTC] External broadcast identity is invalid.");return (await a(e).getOrCreate(`app_${r.slice(-16)}`)).publicKeyJwk}function h(r){let e=new URL(r),t=["localhost","127.0.0.1","[::1]"].includes(e.hostname);if(e.protocol!=="https:"&&!(t&&e.protocol==="http:")||e.pathname!=="/"||e.username||e.password||e.search||e.hash||r!==e.origin&&r!==`${e.origin}/`)throw new Error("[OpenRTC] External broadcast service must be an exact HTTPS origin.");return e.origin}function k(r){let e=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(Math.ceil(r.length/4)*4,"=");return Uint8Array.from(atob(e),t=>t.charCodeAt(0))}function x(r){let e="";for(let t of r)e+=String.fromCharCode(t);return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function C(r,e){if(!(r.issuerPublicKey instanceof Uint8Array)||r.issuerPublicKey.length!==32)throw new Error("[OpenRTC] External broadcast issuer key must be 32 bytes.");let t=r.relay;if(t.kind==="sfu"){let a=new URL(t.controlUrl,e);if(a.origin!==e||a.protocol!==new URL(e).protocol||a.pathname==="/"||a.username||a.password||a.search||a.hash)throw new Error("[OpenRTC] External SFU control must stay on the trusted service origin.");return {issuerPublicKey:r.issuerPublicKey,relay:{kind:"sfu",controlUrl:a.href.replace(/\/$/,"")}}}else {let a=new URL(t.relayUrl);if(a.protocol!=="https:"||a.username||a.password||!t.token||!t.namespace)throw new Error("[OpenRTC] External MoQ relay access is invalid.");if(t.serverCertificateHash&&!["localhost","127.0.0.1","[::1]"].includes(a.hostname))throw new Error("[OpenRTC] Custom relay certificate hashes are limited to loopback.")}return r}function P(r,e){if(!r||typeof r.apiKey!="string"||!/^pk_(?:live|test)_[0-9a-f]{40}$/.test(r.apiKey))throw new Error("[OpenRTC] External broadcast identity is invalid.");let t=h(e.serviceOrigin);if(!/^[A-Za-z0-9_-]{1,64}$/.test(e.keyNamespace)||typeof e.resolve!="function")throw new Error("[OpenRTC] External broadcast configuration is invalid.");let a$2=a(e.keyNamespace),d=`app_${r.apiKey.slice(-16)}`,l=()=>a$2.getOrCreate(d),u=async()=>{let{loadBrowserWasmRuntimeModule:i}=await import('./WasmBridge-L76OAD5U.js'),n=await i();return await n.initWasm(),n.start(),new n.WasmClient(r.apiKey)},w,f=()=>w??(w=u()),m=new a$1({loadWasm:f,resolve:async(i,n)=>{let o=await l(),s=C(await e.resolve(i,o.publicKeyJwk,n),t),g=s.relay.kind==="sfu"?{kind:"sfu",controlUrl:s.relay.controlUrl,grant:i,bindingPublicJwk:o.publicKeyJwk,...n?{publicationVerifyingKey:x(n)}:{}}:s.relay;return {token:i,issuerPublicKey:s.issuerPublicKey,relay:g,signBindingChallenge:async b=>k(await o.sign(b))}}});return {client:i(r,{platform:"web",endpoints:{controlPlane:t,gateway:t},testingAllowInsecureLoopback:t.startsWith("http:"),deviceKeyProvider:a$2,broadcastHost:m,runtimeFactory:async i=>{let{createWasmClient:n}=await import('./runtime/factories.js');return n(i)}}),bindingPublicJwk:async()=>(await l()).publicKeyJwk}}
|
|
2
2
|
export{P as createExternalBroadcastClient,K as externalBroadcastBindingPublicJwk};
|
package/dist/index.d.ts
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
import { P as PlutoIpcBridge } from './ipc-DgzKqHH3.js';
|
|
2
|
-
import { O as Options, C as Client } from './types-
|
|
3
|
-
export { a as AttestationProvider, b as AuthProvider, c as Avenue, e as BroadcastGrant, i as BroadcastPublisher, j as BroadcastRole, k as BroadcastSession, l as BroadcastSource, m as BroadcastState, n as BroadcastStats, o as BroadcastTrackEvent, p as Channel, r as Connection, s as DeviceOptions, t as DeviceProfile, u as Devices, E as EnrolledDevice, N as Offline, P as OfflineAssurance, Q as OfflineEnrollmentRequest, R as OfflineRuntimeSupport, X as Room, Y as
|
|
4
|
-
import { am as ServiceErrorMetadata } from './Connection-
|
|
5
|
-
export { S as ServiceErrorObservation, T as TransferPeerDemandPurpose, d as TransferPeerDemandRequest, e as TransferPeerDemandState, f as TransferPeerDemandStatus } from './Connection-
|
|
6
|
-
export { c as DiagnosticBundle, d as DiagnosticCapture, e as DiagnosticCaptureOptions, f as DiagnosticEvent, b as DiagnosticOperationEvent, g as DiagnosticPeer } from './coreClient-
|
|
7
|
-
import './assembly-
|
|
8
|
-
import './capabilities-
|
|
2
|
+
import { O as Options, C as Client } from './types-YGlXXpQA.js';
|
|
3
|
+
export { a as AttestationProvider, b as AuthProvider, c as Avenue, e as BroadcastGrant, i as BroadcastPublisher, j as BroadcastRole, k as BroadcastSession, l as BroadcastSource, m as BroadcastState, n as BroadcastStats, o as BroadcastTrackEvent, p as Channel, r as Connection, s as DeviceOptions, t as DeviceProfile, u as Devices, E as EnrolledDevice, N as Offline, P as OfflineAssurance, Q as OfflineEnrollmentRequest, R as OfflineRuntimeSupport, X as Room, Y as RoomMember, Z as RoomMembers, _ as RoomOptions, $ as Space, a0 as SpaceOptions, a1 as State, a2 as Ticket, a3 as TicketOptions, a4 as Transports } from './types-YGlXXpQA.js';
|
|
4
|
+
import { am as ServiceErrorMetadata } from './Connection-BGVBMbWg.js';
|
|
5
|
+
export { S as ServiceErrorObservation, T as TransferPeerDemandPurpose, d as TransferPeerDemandRequest, e as TransferPeerDemandState, f as TransferPeerDemandStatus } from './Connection-BGVBMbWg.js';
|
|
6
|
+
export { c as DiagnosticBundle, d as DiagnosticCapture, e as DiagnosticCaptureOptions, f as DiagnosticEvent, b as DiagnosticOperationEvent, g as DiagnosticPeer } from './coreClient-ByXs38IP.js';
|
|
7
|
+
import './assembly-DGrOqsLW.js';
|
|
8
|
+
import './capabilities-DsKud7Sw.js';
|
|
9
9
|
|
|
10
10
|
/**
|
|
11
11
|
* Create a lazy OpenRTC 2.0 browser client. Construction validates only local
|
package/dist/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import {a}from'./chunk-NS32P65Z.js';import {d}from'./chunk-72NEEJQG.js';import'./chunk-GMPEZXPD.js';import {i}from'./chunk-
|
|
1
|
+
import {a}from'./chunk-NS32P65Z.js';import {d}from'./chunk-72NEEJQG.js';import'./chunk-GMPEZXPD.js';import {i}from'./chunk-4TOWICSH.js';import'./chunk-FKAQDDUM.js';import'./chunk-ZA44REGI.js';import'./chunk-NC375DSH.js';export{b as parseTicketInvite}from'./chunk-IUU6JCLK.js';import'./chunk-CCCYE3XN.js';import'./chunk-JPBW67B3.js';export{a as ERROR_CODES,b as RTCError,e as classifyError,d as createError,c as projectError}from'./chunk-L7N4T2PX.js';import'./chunk-72MN7BNQ.js';import'./chunk-2GX6GB6L.js';function c(n){return i(n,{platform:"web",broadcastHostFactory:async e=>{let[{BrowserManagedBroadcastHost:o},{loadBrowserWasmRuntimeModule:a}]=await Promise.all([import('./BrowserManagedBroadcastHost-6VGHQQMF.js'),import('./WasmBridge-L76OAD5U.js')]),t=a().then(async r=>(await r.initWasm(),r.start(),new r.WasmClient(e.apiKey)));return new o({resolve:e.resolve,manage:e.manage,deviceId:e.deviceId,defaultAuth:e.defaultAuth,loadWasm:()=>t})},runtimeFactory:async e=>{let{createWasmClient:o}=await import('./runtime/factories.js');return o(e)}})}c.native=function(n,e=d()){let o,a$1=()=>o??(o=import('./NativeProjectionBroker-Z6LCR4WB.js').then(({NativeProjectionBroker:t})=>new t));return i(n,{platform:"native",broadcastHostFactory:async t=>{let{NativeManagedBroadcastHost:r}=await import('./NativeManagedBroadcastHost-6A2QP3A7.js');return new r(e,t)},offlineSupport:()=>e.invoke("openrtc_offline_runtime_support"),createOfflineEnrollmentRequest:async t=>{let r=await e.invoke("start_iroh_node");return e.invoke("openrtc_create_offline_enrollment_request",{trustDomain:t.trustDomain,deviceId:t.deviceId,endpointId:r,enrollmentNonce:crypto.randomUUID(),requestedRoles:t.requestedRoles})},close:async()=>{o&&await(await o).close();},deviceKeyProvider:a(e),deviceIdProvider:async()=>{let t=await e.invoke("get_rtc_local_device_info");return String(t?.deviceId??"")},runtimeFactory:async t=>{let[{createIpcClient:r},y]=await Promise.all([import('./ipcFactory-OJMZCIIQ.js'),a$1()]);return r(t,e,y)}})};export{c as OpenRTC};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import {a as a$2}from'./chunk-A2TFNNXG.js';import {t}from'./chunk-EI6PDMHI.js';import'./chunk-IXQ4KWGP.js';import'./chunk-TFOFTLTV.js';import'./chunk-UCNK7KB6.js';import {a as a$1}from'./chunk-L4HWDDXL.js';import'./chunk-TYZS5LXQ.js';import'./chunk-OT7IPLZE.js';import'./chunk-OWKAJPOI.js';import {a}from'./chunk-XXZEDZUU.js';import'./chunk-TPF643LU.js';import'./chunk-72NEEJQG.js';import'./chunk-L2ZZXECX.js';import'./chunk-IUU6JCLK.js';import'./chunk-CCCYE3XN.js';import'./chunk-JPBW67B3.js';import'./chunk-L7N4T2PX.js';import'./chunk-72MN7BNQ.js';import'./chunk-2GX6GB6L.js';function l(p,n,m=new a){let t$1=a$1(p);return a$2(t$1,new t({...t$1,bridge:n,projectionBroker:m}))}export{l as createIpcClient};
|
package/dist/native.d.ts
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
import { O as Options, C as Client } from './types-
|
|
2
|
-
export { A as AccessMode, a as AttestationProvider, b as AuthProvider, c as Avenue, B as BotVerificationProvider, d as BroadcastCreateOptions, e as BroadcastGrant, f as BroadcastInvite, g as BroadcastInviteOptions, h as BroadcastMedia, i as BroadcastPublisher, j as BroadcastRole, k as BroadcastSession, l as BroadcastSource, m as BroadcastState, n as BroadcastStats, o as BroadcastTrackEvent, p as Channel, q as Channels, r as Connection, D as Delivery, s as DeviceOptions, t as DeviceProfile, u as Devices, E as EnrolledDevice, I as IncomingPeerBidirectionalStream, v as IncomingPeerUnidirectionalStream, M as MediaConnection, w as MediaIncomingDemuxStats, x as MediaKind, y as MediaLatencySummary, z as MediaReceiver, F as MediaReceiverStats, G as MediaSender, H as MediaSenderStats, J as MediaStats, K as MediaTrackEvent, L as MediaTrackOptions, N as Offline, P as OfflineAssurance, Q as OfflineEnrollmentRequest, R as OfflineRuntimeSupport, S as PeerBidirectionalStream, T as PeerDatagramDuplexStream, U as PeerDatagramStats, V as PeerStreamOptions, W as PeerStreamTransport, X as Room, Y as
|
|
1
|
+
import { O as Options, C as Client } from './types-YGlXXpQA.js';
|
|
2
|
+
export { A as AccessMode, a as AttestationProvider, b as AuthProvider, c as Avenue, B as BotVerificationProvider, d as BroadcastCreateOptions, e as BroadcastGrant, f as BroadcastInvite, g as BroadcastInviteOptions, h as BroadcastMedia, i as BroadcastPublisher, j as BroadcastRole, k as BroadcastSession, l as BroadcastSource, m as BroadcastState, n as BroadcastStats, o as BroadcastTrackEvent, p as Channel, q as Channels, r as Connection, D as Delivery, s as DeviceOptions, t as DeviceProfile, u as Devices, E as EnrolledDevice, I as IncomingPeerBidirectionalStream, v as IncomingPeerUnidirectionalStream, M as MediaConnection, w as MediaIncomingDemuxStats, x as MediaKind, y as MediaLatencySummary, z as MediaReceiver, F as MediaReceiverStats, G as MediaSender, H as MediaSenderStats, J as MediaStats, K as MediaTrackEvent, L as MediaTrackOptions, N as Offline, P as OfflineAssurance, Q as OfflineEnrollmentRequest, R as OfflineRuntimeSupport, S as PeerBidirectionalStream, T as PeerDatagramDuplexStream, U as PeerDatagramStats, V as PeerStreamOptions, W as PeerStreamTransport, X as Room, Y as RoomMember, Z as RoomMembers, _ as RoomOptions, $ as Space, a0 as SpaceOptions, a1 as State, a2 as Ticket, a3 as TicketOptions, a4 as Transports } from './types-YGlXXpQA.js';
|
|
3
3
|
import { P as PlutoIpcBridge } from './ipc-DgzKqHH3.js';
|
|
4
|
-
export { E as EffectiveRoomArchitecture, R as RoomArchitectureMode, a as RoomArchitectureReason, b as RoomArchitectureSnapshot, c as RoomAuthorityAssignment, T as TransferPeerDemandPurpose, d as TransferPeerDemandRequest, e as TransferPeerDemandState, f as TransferPeerDemandStatus } from './Connection-
|
|
5
|
-
import './coreClient-
|
|
6
|
-
import './assembly-
|
|
7
|
-
import './capabilities-
|
|
4
|
+
export { E as EffectiveRoomArchitecture, R as RoomArchitectureMode, a as RoomArchitectureReason, b as RoomArchitectureSnapshot, c as RoomAuthorityAssignment, T as TransferPeerDemandPurpose, d as TransferPeerDemandRequest, e as TransferPeerDemandState, f as TransferPeerDemandStatus } from './Connection-BGVBMbWg.js';
|
|
5
|
+
import './coreClient-ByXs38IP.js';
|
|
6
|
+
import './assembly-DGrOqsLW.js';
|
|
7
|
+
import './capabilities-DsKud7Sw.js';
|
|
8
8
|
|
|
9
9
|
/**
|
|
10
10
|
* Native-only OpenRTC entrypoint for Tauri and other IPC-backed frontends.
|
package/dist/native.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import {a}from'./chunk-XXZEDZUU.js';import'./chunk-TPF643LU.js';import {a as a$1}from'./chunk-NS32P65Z.js';import {d}from'./chunk-72NEEJQG.js';import'./chunk-GMPEZXPD.js';import {i}from'./chunk-
|
|
1
|
+
import {a}from'./chunk-XXZEDZUU.js';import'./chunk-TPF643LU.js';import {a as a$1}from'./chunk-NS32P65Z.js';import {d}from'./chunk-72NEEJQG.js';import'./chunk-GMPEZXPD.js';import {i}from'./chunk-4TOWICSH.js';import'./chunk-FKAQDDUM.js';import'./chunk-ZA44REGI.js';import'./chunk-NC375DSH.js';import'./chunk-IUU6JCLK.js';import'./chunk-CCCYE3XN.js';import'./chunk-JPBW67B3.js';import'./chunk-L7N4T2PX.js';import'./chunk-72MN7BNQ.js';import'./chunk-2GX6GB6L.js';function u(p,t=d()){let r=new a;return i(p,{platform:"native",broadcastHostFactory:async e=>{let{NativeManagedBroadcastHost:o}=await import('./NativeManagedBroadcastHost-6A2QP3A7.js');return new o(t,e)},offlineSupport:()=>t.invoke("openrtc_offline_runtime_support"),createOfflineEnrollmentRequest:async e=>{let o=await t.invoke("start_iroh_node");return t.invoke("openrtc_create_offline_enrollment_request",{trustDomain:e.trustDomain,deviceId:e.deviceId,endpointId:o,enrollmentNonce:crypto.randomUUID(),requestedRoles:e.requestedRoles})},close:()=>r.close(),deviceKeyProvider:a$1(t),deviceIdProvider:async()=>{let e=await t.invoke("get_rtc_local_device_info");return String(e?.deviceId??"")},runtimeFactory:async e=>{let{createIpcClient:o}=await import('./ipcFactory-OJMZCIIQ.js');return o(e,t,r)}})}export{u as OpenRTC};
|
package/dist/node.d.ts
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
|
-
import { O as Options, C as Client } from './types-
|
|
2
|
-
export { A as AccessMode, a as AttestationProvider, b as AuthProvider, c as Avenue, B as BotVerificationProvider, d as BroadcastCreateOptions, e as BroadcastGrant, f as BroadcastInvite, g as BroadcastInviteOptions, h as BroadcastMedia, i as BroadcastPublisher, j as BroadcastRole, k as BroadcastSession, l as BroadcastSource, m as BroadcastState, n as BroadcastStats, o as BroadcastTrackEvent, p as Channel, q as Channels, r as Connection, D as Delivery, s as DeviceOptions, t as DeviceProfile, u as Devices, E as EnrolledDevice, I as IncomingPeerBidirectionalStream, v as IncomingPeerUnidirectionalStream, M as MediaConnection, w as MediaIncomingDemuxStats, x as MediaKind, y as MediaLatencySummary, z as MediaReceiver, F as MediaReceiverStats, G as MediaSender, H as MediaSenderStats, J as MediaStats, K as MediaTrackEvent, L as MediaTrackOptions, N as Offline, P as OfflineAssurance, Q as OfflineEnrollmentRequest, R as OfflineRuntimeSupport, S as PeerBidirectionalStream, T as PeerDatagramDuplexStream, U as PeerDatagramStats, V as PeerStreamOptions, W as PeerStreamTransport, X as Room, Y as
|
|
1
|
+
import { O as Options, C as Client } from './types-YGlXXpQA.js';
|
|
2
|
+
export { A as AccessMode, a as AttestationProvider, b as AuthProvider, c as Avenue, B as BotVerificationProvider, d as BroadcastCreateOptions, e as BroadcastGrant, f as BroadcastInvite, g as BroadcastInviteOptions, h as BroadcastMedia, i as BroadcastPublisher, j as BroadcastRole, k as BroadcastSession, l as BroadcastSource, m as BroadcastState, n as BroadcastStats, o as BroadcastTrackEvent, p as Channel, q as Channels, r as Connection, D as Delivery, s as DeviceOptions, t as DeviceProfile, u as Devices, E as EnrolledDevice, I as IncomingPeerBidirectionalStream, v as IncomingPeerUnidirectionalStream, M as MediaConnection, w as MediaIncomingDemuxStats, x as MediaKind, y as MediaLatencySummary, z as MediaReceiver, F as MediaReceiverStats, G as MediaSender, H as MediaSenderStats, J as MediaStats, K as MediaTrackEvent, L as MediaTrackOptions, N as Offline, P as OfflineAssurance, Q as OfflineEnrollmentRequest, R as OfflineRuntimeSupport, S as PeerBidirectionalStream, T as PeerDatagramDuplexStream, U as PeerDatagramStats, V as PeerStreamOptions, W as PeerStreamTransport, X as Room, Y as RoomMember, Z as RoomMembers, _ as RoomOptions, $ as Space, a0 as SpaceOptions, a1 as State, a2 as Ticket, a3 as TicketOptions, a4 as Transports } from './types-YGlXXpQA.js';
|
|
3
3
|
import { P as PlutoIpcBridge } from './ipc-DgzKqHH3.js';
|
|
4
|
-
import { S as ServiceErrorObservation } from './Connection-
|
|
5
|
-
export { E as EffectiveRoomArchitecture, R as RoomArchitectureMode, a as RoomArchitectureReason, b as RoomArchitectureSnapshot, c as RoomAuthorityAssignment, T as TransferPeerDemandPurpose, d as TransferPeerDemandRequest, e as TransferPeerDemandState, f as TransferPeerDemandStatus } from './Connection-
|
|
4
|
+
import { S as ServiceErrorObservation } from './Connection-BGVBMbWg.js';
|
|
5
|
+
export { E as EffectiveRoomArchitecture, R as RoomArchitectureMode, a as RoomArchitectureReason, b as RoomArchitectureSnapshot, c as RoomAuthorityAssignment, T as TransferPeerDemandPurpose, d as TransferPeerDemandRequest, e as TransferPeerDemandState, f as TransferPeerDemandStatus } from './Connection-BGVBMbWg.js';
|
|
6
6
|
import { AuthorityAssignmentInput, AuthorityInterestAssignment } from './service-node.js';
|
|
7
|
-
import './coreClient-
|
|
8
|
-
import './assembly-
|
|
9
|
-
import './capabilities-
|
|
7
|
+
import './coreClient-ByXs38IP.js';
|
|
8
|
+
import './assembly-DGrOqsLW.js';
|
|
9
|
+
import './capabilities-DsKud7Sw.js';
|
|
10
10
|
|
|
11
11
|
interface NodeServiceNodeOptions {
|
|
12
12
|
apiKey: string;
|