openrtc 3.0.3 → 3.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (55) hide show
  1. package/dist/BrowserCoordinationGatewaySignaling-GOLSTJMA.js +1 -0
  2. package/dist/WasmBridge-CJNESUGJ.js +1 -0
  3. package/dist/{chunk-TYZS5LXQ.js → chunk-2AAZFBRZ.js} +1 -1
  4. package/dist/chunk-5LNRJE6L.js +1 -0
  5. package/dist/{chunk-HL3TV2QA.js → chunk-5LO6PLWZ.js} +1 -1
  6. package/dist/{chunk-TFOFTLTV.js → chunk-CQHLD52E.js} +1 -1
  7. package/dist/chunk-FNCEVW7G.js +1 -0
  8. package/dist/chunk-FPJAUAEU.js +2 -0
  9. package/dist/chunk-LB27VQRL.js +1 -0
  10. package/dist/chunk-LCJQ7RSR.js +1 -0
  11. package/dist/{chunk-AYQSDKSK.js → chunk-LVLU4YQY.js} +1 -1
  12. package/dist/{chunk-PW2WEI6L.js → chunk-RLPWFHOY.js} +1 -1
  13. package/dist/chunk-SADNIMUO.js +2 -0
  14. package/dist/{chunk-XTMFYAIJ.js → chunk-VARKDQGM.js} +1 -1
  15. package/dist/coreClient.js +1 -1
  16. package/dist/{deviceHandle-YV5LJ5A5.js → deviceHandle-Y2XA57WF.js} +1 -1
  17. package/dist/external-broadcast.d.ts +1 -1
  18. package/dist/external-broadcast.js +1 -1
  19. package/dist/index.d.ts +4 -4
  20. package/dist/index.js +1 -1
  21. package/dist/ipcFactory-F75IXEIE.js +1 -0
  22. package/dist/native.d.ts +2 -2
  23. package/dist/native.js +1 -1
  24. package/dist/node.d.ts +2 -2
  25. package/dist/node.js +2 -2
  26. package/dist/openrtc_bg.wasm +0 -0
  27. package/dist/{room-ELXNZIYX.js → room-E4NRHQFD.js} +1 -1
  28. package/dist/runtime/WasmRuntimeAdapter.js +1 -1
  29. package/dist/runtime/factories.js +1 -1
  30. package/dist/runtime/index.d.ts +1 -1
  31. package/dist/runtime/index.js +1 -1
  32. package/dist/server-browser.d.ts +1 -1
  33. package/dist/server.d.ts +1 -1
  34. package/dist/server.js +1 -1
  35. package/dist/service-node.d.ts +1 -1
  36. package/dist/service-node.js +1 -1
  37. package/dist/testing/native.d.ts +1 -1
  38. package/dist/testing/native.js +1 -1
  39. package/dist/testing.d.ts +1 -1
  40. package/dist/testing.js +1 -1
  41. package/dist/transport/index.js +1 -1
  42. package/dist/{types-YGlXXpQA.d.ts → types-Cruu-MsF.d.ts} +43 -1
  43. package/native/darwin-arm64/openrtc-node-host +0 -0
  44. package/native/darwin-arm64/openrtc-node-host.manifest.json +4 -4
  45. package/native/darwin-x64/openrtc-node-host +0 -0
  46. package/native/darwin-x64/openrtc-node-host.manifest.json +4 -4
  47. package/native/linux-x64/openrtc-node-host +0 -0
  48. package/native/linux-x64/openrtc-node-host.manifest.json +4 -4
  49. package/package.json +1 -1
  50. package/dist/WasmBridge-L76OAD5U.js +0 -1
  51. package/dist/chunk-K32BROMJ.js +0 -2
  52. package/dist/chunk-OT7IPLZE.js +0 -1
  53. package/dist/chunk-QL4CJCV4.js +0 -1
  54. package/dist/chunk-UCNK7KB6.js +0 -2
  55. package/dist/ipcFactory-4LCCR23Q.js +0 -1
@@ -0,0 +1,2 @@
1
+ import {d}from'./chunk-LB27VQRL.js';import {a}from'./chunk-TPF643LU.js';import {b}from'./chunk-ZA44REGI.js';import {a as a$1,b as b$1,e}from'./chunk-L7N4T2PX.js';import {d as d$1}from'./chunk-72MN7BNQ.js';var re="openrtc-trust";var $="identity",P="managed-room-keys",M="managed-room-state";function se(){if(typeof globalThis.indexedDB>"u")throw new Error("[OpenRTC] Managed rooms require durable IndexedDB storage.");return globalThis.indexedDB}function oe(){return new Promise((d,e)=>{let t=se().open(re,2);t.onupgradeneeded=()=>{let i=t.result;i.objectStoreNames.contains($)||i.createObjectStore($),i.objectStoreNames.contains(P)||i.createObjectStore(P),i.objectStoreNames.contains(M)||i.createObjectStore(M);},t.onsuccess=()=>d(t.result),t.onerror=()=>e(t.error??new Error("managed room database failed")),t.onblocked=()=>e(new Error("managed room database upgrade is blocked"));})}function K(d){return new Promise((e,t)=>{d.onsuccess=()=>e(d.result),d.onerror=()=>t(d.error??new Error("managed room storage failed"));})}function C(d){return new Promise((e,t)=>{d.oncomplete=()=>e(),d.onerror=()=>t(d.error??new Error("managed room storage failed")),d.onabort=()=>t(d.error??new Error("managed room storage aborted"));})}function ae(d,e,t){return `${d}:${e}:${t}`}function ce(d,e){return `${d}:${e}`}function H(d){return new TextEncoder().encode(`openrtc-managed-room-state-v1:${d}`)}async function de(d,e){let t=d.transaction(P,"readonly"),i=C(t),n=await K(t.objectStore(P).get(e));if(await i,n)return n;let r=await crypto.subtle.generateKey({name:"AES-GCM",length:256},false,["encrypt","decrypt"]),s=d.transaction(P,"readwrite"),c=C(s);s.objectStore(P).add(r,e);try{return await c,r}catch{let a=d.transaction(P,"readonly"),o=C(a),p=await K(a.objectStore(P).get(e));if(await o,!p)throw new Error("[OpenRTC] Managed room wrapping key could not be persisted.");return p}}function he(d){let e=d;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 z(d,e,t){let i=await oe(),n=ae(d,e,t);try{let r=await de(i,ce(d,e)),s=i.transaction(M,"readonly"),c=C(s),a=he(await K(s.objectStore(M).get(n)));await c;let o,p;if(a){let l=await crypto.subtle.decrypt({name:"AES-GCM",iv:a.wrappingNonce,additionalData:H(n)},r,a.wrappedKey).catch(()=>{throw new Error("[OpenRTC] Managed room state key authentication failed.")});if(o=new Uint8Array(l),o.byteLength!==32)throw new Error("[OpenRTC] Managed room state key is invalid.");p=a;}else {o=crypto.getRandomValues(new Uint8Array(32));let l=crypto.getRandomValues(new Uint8Array(12)),y=new Uint8Array(await crypto.subtle.encrypt({name:"AES-GCM",iv:l,additionalData:H(n)},r,o));p={schemaVersion:1,wrappingNonce:l,wrappedKey:y};let h=i.transaction(M,"readwrite"),b=C(h);h.objectStore(M).add(p,n),await b;}return {wrappingKey:o,sealedState:p.sealedState,async persist(l){if(!(l instanceof Uint8Array)||l.byteLength===0)throw new Error("[OpenRTC] Managed room sealed state is invalid.");let y=i.transaction(M,"readwrite"),h=C(y);y.objectStore(M).put({...p,sealedState:l},n),await h,p={...p,sealedState:l};},close(){o.fill(0),i.close();}}}catch(r){throw i.close(),r}}var le=3e4,ue=5*6e4,ge=3e4,x=100,D=48*1024,ve=50,q=64*1024,V=12,me=10*6e4,ye=5*6e4,E=15e3,fe=15e3,J=1e3,Q=250;function Z(d){let e=[...new Set(d.map(t=>String(t??"").trim().toLowerCase()).filter(Boolean))].sort();if(e.length>Q)throw new Error(`Coordination excluded-peer set exceeds ${Q} devices.`);return e}var we="openrtc.v2",be="openrtc.auth.";function ne(d){try{let e=d.split(".")[1];if(!e)return null;let t=e.replace(/-/g,"+").replace(/_/g,"/").padEnd(Math.ceil(e.length/4)*4,"="),i=JSON.parse(globalThis.atob(t));return i!==null&&typeof i=="object"&&!Array.isArray(i)?i:null}catch{return null}}function Y(d){let e=ne(d)?.jti;return typeof e=="string"&&e.length>0?e:null}var g=class extends b$1{constructor(t,i,n,r={}){super({code:a$1.COORDINATION_DISCONNECTED,plane:"coordination",...d$1(n)?e({...r,code:n,message:t,retryable:i}):{},message:t,retryable:i});this.gatewayCode=n;this.name="CoordinationConnectError";}},I=class extends b$1{constructor(t,i,n,r={}){let s=e({...r,code:t,message:i,retryable:n});super({...s,retryable:n,message:`Coordination gateway ${t}: ${i}`});this.name="CoordinationGatewayProtocolError";this.gatewayCode=t;}};function X(d){return d instanceof g&&/\bstale-budget\b/i.test(d.message)}function T(d){if(!d||typeof d!="object")return false;let e=d;return e.gatewayCode==="credential-revoked"||e.code==="credential-revoked"||e.reason==="device-certificate-revoked"}function ee(d){if(T(d))return true;if(typeof d!="object"||d===null)return false;let e=d;if(e.retryable===false)return true;let t=e.status??e.statusCode,i=typeof t=="number"?t:Number.NaN;if(Number.isInteger(i)&&i>=400&&i<500&&![408,425,429].includes(i))return true;let n=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(n)}function Ae(d){let e=new Uint32Array(1);return crypto.getRandomValues(e),Math.max(1,Math.round(d*(.75+e[0]/4294967295*.5)))}function A(d){if(typeof crypto.randomUUID=="function")return `${d}:${crypto.randomUUID()}`;let e=new Uint8Array(16);crypto.getRandomValues(e);let t=Array.from(e,i=>i.toString(16).padStart(2,"0")).join("");return `${d}:${t}`}async function Re(d){let e=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(d)),t="";for(let i of new Uint8Array(e))t+=String.fromCharCode(i);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,"")}function U(d){if(!/^[A-Za-z0-9_-]+$/.test(d))throw new Error("[OpenRTC] Managed room payload encoding is invalid.");let e=d.replace(/-/g,"+").replace(/_/g,"/"),t=atob(e.padEnd(Math.ceil(e.length/4)*4,"=")),i=new Uint8Array(t.length);for(let n=0;n<t.length;n+=1)i[n]=t.charCodeAt(n);return i}function Se(d,e,t){let i=new URL(d);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${t}/connect/${e}`,i.toString()}function te(d){let e=new URL(d);return e.protocol==="wss:"&&(e.protocol="https:"),e.protocol==="ws:"&&(e.protocol="http:"),e.origin}var ie=class d$1{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=z;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=Z(e.initialExcludedPeers??[]),this.desiredExcludedPeers=[...this.initialExcludedPeers],e.gateway.environment!=="staging"&&e.gateway.environment!=="production")throw new Error("[OpenRTC] Coordination gateway environment is invalid.");let t=new URL(e.gateway.endpoint),i=t.hostname==="127.0.0.1"||t.hostname==="localhost"||t.hostname==="[::1]",n=t.protocol==="https:"||t.protocol==="wss:",r=e.gateway.testingAllowInsecureLoopback===true&&i&&(t.protocol==="http:"||t.protocol==="ws:");if(!n&&!r)throw new Error("[OpenRTC] Coordination gateway requires HTTPS/WSS.");if(t.username||t.password||t.search||t.hash)throw new Error("[OpenRTC] Coordination gateway credentials and parameters cannot be supplied in its URL.")}static live(e,t=false){return new W(e,t)}async updatePresence(e,t,i,n,r,s){let c=this.desiredPresence;if(i&&this.options.roomArchitecture==="authority"){let p=this.options.avenueOverride;if(p?.kind!=="room"||!this.peerAdmissionRuntime)throw new Error("[OpenRTC] Authority rooms require Rust peer admission support.");let l=`v2:room:${p.id}`;this.peerAdmissionRuntime.__requireScopePeerAdmission(l),this.peerAdmissionScope=l;}this.desiredPresence={localNodeId:e,ticket:t,online:i,ttlMs:n,metadata:r,deviceName:s?.trim()||this.options.getDefaultDeviceName()},(!c||c.localNodeId!==e||c.ticket!==t||c.online!==i||c.ttlMs!==n||c.metadata!==r||c.deviceName!==this.desiredPresence.deviceName)&&(this.desiredPresenceRevision+=1,this.reconnectCircuitOpen=false,this.reconnectAttempt=0,this.reconnectOutageStartedAtMs=null);for(let p of this.friendConnections.values())p.updatePresence(e,t,i,n,r,this.desiredPresence.deviceName).catch(()=>{});let o=this.desiredPresenceRevision;try{await this.ensureConnected();}catch(p){if(!(p instanceof g)||!p.retryable)throw p;await this.waitForConnectionReady();}this.appliedPresenceRevision>=o||(c&&c.ticket!==t&&await this.refreshAuthentication(),await this.sendOperation({v:1,type:"presence.upsert",idempotencyKey:A("presence"),ttlMs:n,device:this.gatewayDevice(this.desiredPresence)}),this.appliedPresenceRevision=Math.max(this.appliedPresenceRevision,o));}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<fe)){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 t=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}t&&this.desiredPresence&&!this.socketReady&&!this.connectPromise&&!this.reconnectCircuitOpen&&!this.stopped&&this.ensureConnected().catch(i=>this.scheduleReconnect(i));}async updateDevice(e,t){if(e!==this.options.getLocalDeviceId())throw new Error("A coordination socket can update only its local device.");let i=t;if(t.excludedPeers!==void 0){let n=Z(t.excludedPeers);this.desiredExcludedPeers=n,i={...t,excludedPeers:n};}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 t=new d$1({...this.options,credentialPurpose:"device-control"});try{await t.deleteDevice(e);}finally{t.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,t){let i=n=>e(t?n.filter(r=>r.nodeId!==t):n);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,z);}setManagedRoomRuntime(e,t){let i=e;this.peerAdmissionRuntime=i&&typeof i.__requireScopePeerAdmission=="function"&&typeof i.__updateScopePeerAdmission=="function"?i:null;let n=e;this.managedWasmClient=n&&typeof n.__initManagedRoomGroup=="function"&&typeof n.__handleManagedRoomPreparePage=="function"&&typeof n.__applyManagedRoomAuthority=="function"&&typeof n.__handleManagedRoomArtifactChunk=="function"&&typeof n.__sealManagedRoomPayload=="function"&&typeof n.__openManagedRoomPayload=="function"&&typeof n.__forgetManagedRoomGroup=="function"?n:null,this.managedStateProvider=t,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((t,i)=>{if(this.stopped||this.managedPublishQueue.length>=J){i(new Error("[OpenRTC] Managed room publication queue is unavailable."));return}this.managedPublishQueue.push({input:e,resolve:t,reject:i}),this.scheduleManagedPublish();})}async subscribeDevices(){let e=null;return new ReadableStream({start:t=>{e=t,this.deviceStreams.add(t);let i=this.snapshot().map(n=>({type:"added",device:n}));i.length>0&&t.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,t){await this.ensureConnected(),await this.sendOperation({v:1,type:"session.put",idempotencyKey:A("session-update"),sessionId:this.unscopedId(e),session:t,expiresAtMs:typeof t.expiresAt=="number"?t.expiresAt:Date.now()+15*6e4});}async subscribeSessions(e){let t=null;return new ReadableStream({start:i=>{t=i,this.sessionStreams.add(i);},cancel:()=>{t&&this.sessionStreams.delete(t),t=null;}})}async sendMessage(e,t,i,n){let r=this.serviceObservationGeneration;if(await this.ensureConnected(),r!==this.serviceObservationGeneration||!this.socket)throw new g("Signal connection retired before dispatch.",false);let s={socket:this.socket,generation:r};this.assertSignalCurrent(s);let c=Object.freeze({targetDeviceId:this.unscopedId(e),payload:t,state:i,replyPayload:n});if(this.signalBatchMode!=="ordered-v1"){let a=A("signal");return await this.sendOperation({v:1,type:"signal.send",idempotencyKey:a,...c},o=>this.assertSignalCurrent(s,o)),this.assertSignalCurrent(s,false),a}return new Promise((a,o)=>{this.pendingSignalQueue.push({input:c,binding:s,resolve:a,reject:o}),!this.signalFlushScheduled&&(this.signalFlushScheduled=s,queueMicrotask(()=>{this.signalFlushScheduled===s&&(this.signalFlushScheduled=null,this.flushSignalQueue());}));})}assertSignalCurrent(e,t=true){if(e.generation!==this.serviceObservationGeneration||this.socket!==e.socket||e.socket.readyState!==WebSocket.OPEN||!this.socketReady||this.stopped||this.credentialRevoked||t&&(!Number.isSafeInteger(this.activeGrantExpiresAtMs)||this.activeGrantExpiresAtMs<=Date.now()))throw new g("Signal connection retired before completion.",false)}rejectQueuedSignals(e){this.signalFlushScheduled=null;for(let t of this.pendingSignalQueue.splice(0))t.reject(e);}flushSignalQueue(){let e=this.pendingSignalQueue.splice(0);for(;e.length>0;){let t=e.shift();try{this.assertSignalCurrent(t.binding);}catch(a){t.reject(a);continue}let i=[t],n=A("signal-batch"),r=a=>({v:1,type:"signal.send.batch",idempotencyKey:n,signals:a.map(o=>o.input)});for(;i.length<ve&&e.length>0;){let a=e[0];if(a.binding.socket!==t.binding.socket||a.binding.generation!==t.binding.generation||new TextEncoder().encode(JSON.stringify(r([...i,a]))).byteLength>q)break;i.push(e.shift());}let s=i.length>1,c=Object.freeze(s?{...r(i),signals:Object.freeze(i.map(a=>a.input))}:{v:1,type:"signal.send",idempotencyKey:A("signal"),...t.input});if(new TextEncoder().encode(JSON.stringify(c)).byteLength>q){t.reject(new Error("Signaling frame exceeds 64 KiB."));continue}this.dispatchSignalFrame(c,t.binding,i,s);}}async dispatchSignalFrame(e,t,i,n){try{await this.sendOperation(e,r=>this.assertSignalCurrent(t,r)),this.assertSignalCurrent(t,!1),i.forEach((r,s)=>r.resolve(n?`${e.idempotencyKey}:${s}`:e.idempotencyKey));}catch(r){for(let s of i)s.reject(r);}}async pollMessages(e){return this.pendingMessages.splice(0,this.pendingMessages.length)}watchFriendDevices(e,t){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 n={value:false},r=new Map,s=[];t(new Map);for(let c of i){if(!c||c===this.options.getCurrentUserId())continue;let a=this.friendConnection(c);s.push(a.onDevicesChange(o=>{if(n.value)return;let p=o.filter(l=>l.online);r.set(c,p),t(new Map(r));}));}return ()=>{n.value=true;for(let c of s)c();for(let c of i)this.friendConnections.get(c)?.stopAuthActivity(),this.friendConnections.delete(c);}}waitForFriendDevice(e,t,i=1e4){let n=e.trim(),r=t.trim();return !n||!r?Promise.reject(new Error("Capability-authorized device observation requires user and device ids.")):new Promise((s,c)=>{let a=()=>{},o=false,p=h=>{o||(o=true,clearTimeout(l),a(),h.error?c(h.error):s(h.device));},l=setTimeout(()=>p({error:new Error(`Timed out waiting for capability-authorized device ${r}`)}),Math.max(1,i));a=this.watchFriendDevices([n],h=>{let b=(h.get(n)??[]).find(f=>f.deviceId===r&&f.online&&typeof f.ticket=="string"&&f.ticket.trim().startsWith("endpoint"));b&&p({device:b});}),o&&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 t of this.friendConnections.values())this.activateFriendConnection(t,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,t,i){let n=e.trim().toUpperCase(),r=this.roomConnections.get(n);r||(r=new d$1({...this.options,avenueOverride:{kind:"room",id:n}}),r.setHostAvailability({available:this.hostAvailable,reason:"parent-avenue-created"}),this.roomConnections.set(n,r));try{await r.updatePresence(t,i,!0,5*6e4,void 0,this.options.getDefaultDeviceName());}catch(s){if(!(s instanceof g)||!s.retryable)throw s;await r.waitForConnectionReady();}}async leaveCoordinationRoom(e){let t=e.trim().toUpperCase(),i=this.roomConnections.get(t);i&&(await i.setOffline(this.options.getLocalDeviceId()).catch(()=>{}),i.stopAuthActivity(),this.roomConnections.delete(t));}async getCoordinationRoomMembers(e){return this.requireRoomConnection(e).snapshot().map(i=>this.roomMember(i))}watchCoordinationRoomMembers(e,t){return this.requireRoomConnection(e).onDevicesChange(n=>t(n.map(r=>this.roomMember(r))))}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,t=this.connect();this.connectPromise=t;try{await t;}catch(i){throw e===this.serviceObservationGeneration&&this.connectPromise===t&&this.scheduleReconnect(i),i}finally{this.connectPromise===t&&(this.connectPromise=null);}}async connect(){let e=this.serviceObservationGeneration,t=this.desiredPresence??this.controlPresence(),i=this.desiredPresenceRevision,n=()=>{if(e!==this.serviceObservationGeneration||this.stopped||this.credentialRevoked)throw new g("Coordination connection retired while minting an admission credential.",false)},r=async()=>{n();let s=await this.mintGatewayCredential(t,false);n(),await new Promise((c,a)=>{let o=new WebSocket(Se(s.gatewayUrl,s.routeKey,s.protocolVersion),[we,`${be}${s.token}`]);this.signalBatchMode="off",this.rejectQueuedSignals(new g("Signal connection replaced before dispatch.",false)),this.socket=o,this.pendingRosterPageSnapshot=null;let p=false,l=false,y=null,h=()=>{l||o.readyState!==WebSocket.OPEN||(l=true,this.socketReady=true,this.appliedPresenceRevision=Math.max(this.appliedPresenceRevision,this.desiredPresence?i:0),clearTimeout(b),this.reconnectAttempt=0,this.reconnectOutageStartedAtMs=null,this.scheduleAuthRefresh(s.expiresAtMs,s.protocolVersion),this.resolveConnectionReadyWaiters(),c());},b=setTimeout(()=>{o.close(4408,"authentication timeout"),y=new g("Coordination gateway authentication timed out.",true),a(y);},E);o.onopen=()=>{o.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(t)}));},o.onmessage=f=>{if(this.stopped||this.socket!==o||f.data==="pong")return;let u;try{u=JSON.parse(String(f.data));}catch{o.close(4400,"invalid gateway frame"),l||(clearTimeout(b),a(new Error("Coordination gateway returned an invalid frame.")));return}if(u.type==="roster.page"&&new TextEncoder().encode(String(f.data)).byteLength>64*1024){o.close(4400,"oversized roster page");return}if(u.type==="error"&&e===this.serviceObservationGeneration&&this.observeServiceError(u,s.avenue),this.stopped||this.socket!==o)return;if(u.type==="ready"&&!p&&this.socket===o&&(this.activeGrantToken=s.token,this.refillCredential={grant:s,ticket:t.ticket},this.activeGrantJti=Y(s.token),this.activeAvenue=s.avenue,this.activeGrantExpiresAtMs=s.expiresAtMs,this.activeGrantProtocolVersion=s.protocolVersion,this.leaseRefreshMode=u.leaseRefreshMode??"off",this.signalBatchMode=u.signalBatchMode==="ordered-v1"?"ordered-v1":"off",p=true,this.keepaliveTimer&&clearInterval(this.keepaliveTimer),this.keepaliveTimer=setInterval(()=>{if(this.socket===o&&o.readyState===WebSocket.OPEN)try{o.send("ping");}catch{o.close(4408,"gateway keepalive failed");}},3e4)),u.type==="error"&&!l){y=new g(`Coordination gateway ${u.code}: ${u.message}`,u.retryable,u.code,u),clearTimeout(b),a(y),o.close(4403,u.code);return}this.handleFrame(u,o);let R=u.type==="roster.snapshot"||u.type==="roster.page"&&this.pendingRosterPageSnapshot===null||u.type==="membership.snapshot"||u.type==="membership.page"&&this.pendingMembershipPageSnapshot===null;p&&(this.options.credentialPurpose==="device-control"||R)&&h();},o.onerror=()=>{this.socket===o&&(this.signalBatchMode="off",this.rejectQueuedSignals(new g("Signal connection failed before dispatch.",false))),l||(clearTimeout(b),y??(y=new g("Coordination gateway connection failed.",true)),a(y));},o.onclose=f=>{clearTimeout(b);let u=this.socket===o,R=f.code===4429&&f.reason==="coordination-work-limit",v=f.code!==4400&&f.code!==4401&&f.code!==4403&&!R;R&&(y??(y=new g("Included coordination work limit reached. Review account usage before reconnecting.",false,"coordination-work-limit"))),u&&this.keepaliveTimer&&(clearInterval(this.keepaliveTimer),this.keepaliveTimer=null),u&&f.code===4403&&(!y||T(y))&&this.stopForCredentialRevocation(new g("Coordination credential revoked.",false,"credential-revoked")),l||(y??(y=new g(`Coordination gateway closed (${f.code}) before its initial projection.`,v)),a(y)),this.socket===o&&(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.",o),this.rejectPendingAuthRefresh(new g("Coordination gateway closed during credential refresh.",v),o),u&&!this.stopped&&this.desiredPresence&&f.code!==1e3&&!X(y)&&this.scheduleReconnect(y??new g(`Coordination gateway closed (${f.code}).`,v));};});};try{await r();}catch(s){if(!X(s))throw s;await r();}}async mintGatewayCredential(e,t){let i=this.serviceObservationGeneration,n=await this.resolveAvenue(),r={avenue:n,deviceId:this.options.getLocalDeviceId(),runtimeInstanceId:this.runtimeInstanceId,ticketFingerprint:await Re(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({...r,...t&&this.activeGrantToken?{refreshGrant:this.activeGrantToken}:{}});}catch(a){throw i===this.serviceObservationGeneration&&this.observeServiceError(a,n),a instanceof g?a:new g(a instanceof Error?a.message:"Coordination credential mint failed.",!ee(a),T(a)?"credential-revoked":void 0)}if(s.protocolVersion!==2)throw new g("Unsupported coordination gateway protocol.",false);let c=te(this.options.gateway.endpoint);if(te(s.gatewayUrl)!==c)throw new g("Coordination credential returned an unexpected gateway origin.",false);return s}observeServiceError(e,t){if(this.stopped||!this.options.gateway.onServiceError)return;let i=a(e,t);if(i)try{Promise.resolve(this.options.gateway.onServiceError(i)).catch(()=>{});}catch{}}handleFrame(e,t=this.socket){if(!(t&&t!==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,t?.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,t??void 0),this.rejectPendingAuthRefresh(i,t??void 0),this.stopForCredentialRevocation(i);return}if(e.type==="auth.refreshed"){let i=this.pendingAuthRefresh;i&&i.socket===t&&(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===t&&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),t);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(r=>r&&typeof r.deviceId=="string"&&/^[A-Za-z0-9_.:@-]{1,160}$/.test(r.deviceId))&&new Set(e.devices.map(r=>r.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 n=this.pendingRosterPageSnapshot;if(!i||!n||n.snapshotId!==e.snapshotId||n.nextPageIndex!==e.pageIndex||n.pageCount!==e.pageCount||n.deviceCount!==e.deviceCount||n.devices.size+e.devices.length>n.deviceCount||e.devices.some(r=>n.devices.has(r.deviceId))){this.pendingRosterPageSnapshot=null,t?.close(4400,"invalid roster page");return}for(let r of e.devices)n.devices.set(r.deviceId,this.toDevice(r));if(n.nextPageIndex+=1,n.nextPageIndex===n.pageCount){if(n.devices.size!==n.deviceCount){this.pendingRosterPageSnapshot=null,t?.close(4400,"incomplete roster pages");return}this.sparseMembers.clear(),this.sparseRoutes.clear(),this.sparseTopologyRevision=0;let r=[...this.devices.keys()].filter(s=>!n.devices.has(s)).map(s=>({type:"removed",deviceId:s}));for(let[s,c]of n.devices)r.push({type:this.devices.has(s)?"modified":"added",device:c});this.devices.clear();for(let[s,c]of n.devices)this.devices.set(s,c);this.pendingRosterPageSnapshot=null,this.emitDeviceEvents(r),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 n=this.pendingMembershipPageSnapshot;if(!(i&&n!==null&&n.snapshotId===e.snapshotId&&n.nextPageIndex===e.pageIndex&&n.pageCount===e.pageCount&&n.memberCount===e.memberCount&&e.members.every(s=>s.deviceId.length>0&&!n.members.has(s.deviceId)))||!n){t?.close(4400,"invalid membership page");return}for(let s of e.members)n.members.set(s.deviceId,s);if(n.nextPageIndex+=1,n.nextPageIndex===n.pageCount){if(n.members.size!==n.memberCount){t?.close(4400,"incomplete membership pages");return}this.sparseMembers.clear(),this.sparseRoutes.clear(),this.sparseTopologyRevision=0;for(let s of n.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()=>{t!==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),n=this.toDevice(e.device);this.devices.set(n.deviceId,n),this.emitDeviceEvents([{type:i?"modified":"added",device:n}]);}this.emitDevices();}else if(e.type==="signal.received")this.pendingMessages.length>=J&&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,t);else if(e.type==="managed.prepare.page"||e.type==="managed.commit.chunk.received")this.enqueueManagedWork(async()=>{t!==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 n of this.sessionStreams)n.enqueue(i);}else if(e.type==="ack"){let i=this.pendingAcks.get(e.idempotencyKey);i&&i.socket===t&&(clearTimeout(i.timer),this.pendingAcks.delete(e.idempotencyKey),i.resolve());}else if(e.type==="error"){if(this.pendingAuthRefresh?.socket===t&&(!e.idempotencyKey||e.idempotencyKey===this.pendingLeaseRefreshKey)){let n=this.pendingAuthRefresh;clearTimeout(n.timer),this.pendingAuthRefresh=null,this.pendingLeaseRefreshKey=null,n.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===t&&(clearTimeout(i.timer),this.pendingAcks.delete(e.idempotencyKey),i.reject(new I(e.code,e.message,e.retryable,e)));}}}enqueueManagedWork(e){this.managedReceiveTail=null;let t=this.serviceObservationGeneration,i=this.socket,n=()=>t===this.serviceObservationGeneration&&i===this.socket,r=this.managedActions.then(()=>n()?e():void 0);this.managedActions=r.catch(s=>{n()&&(console.error("[OpenRTC] Managed room owner rejected a gateway frame:",s),this.socket?.close(4400,"managed room state invalid"));});}enqueueManagedReceive(e,t){let i=x+1,n=D+1;try{i=Math.max(1,e.batch.length),n=e.batch.reduce((a,o)=>a+o.ciphertext.length,0);}catch{}let r=this.serviceObservationGeneration,s=this.managedReceiveTail;if(s&&s.socket===t&&s.generation===r&&s.messages+i<=x&&s.ciphertextChars+n<=D){s.frames.push(e),s.messages+=i,s.ciphertextChars+=n;return}let c={frames:[e],messages:i,ciphertextChars:n,socket:t,generation:r};this.enqueueManagedWork(async()=>{this.managedReceiveTail===c&&(this.managedReceiveTail=null);let a=()=>!this.stopped&&this.socket===t&&this.serviceObservationGeneration===r;if(a())try{await this.handleManagedReceivedFrames(c.frames,a);}catch(o){if(a())throw o}}),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(l){for(let y of this.managedPublishQueue.splice(0))y.reject(l);throw l}if(this.roomArchitectureSnapshot?.phase==="preparing")return;let e=this.managedPublishQueue.splice(0,x),t={pending:new Set(e),socket:this.socket,generation:this.serviceObservationGeneration};this.activeManagedPublication=t;let i=this.roomArchitectureSnapshot,n=this.roomEncryptionEpoch,r=this.sparseTopologyRevision,s=new Error("[OpenRTC] Managed publication connection retired."),c=new Error("[OpenRTC] Managed publication authority changed before dispatch."),a=()=>this.activeManagedPublication===t&&!this.stopped&&t.socket===this.socket&&t.generation===this.serviceObservationGeneration,o=()=>this.roomArchitectureSnapshot?.effective==="managed"&&this.roomArchitectureSnapshot.phase==="settled"&&this.roomArchitectureSnapshot.epoch===i?.epoch&&this.roomEncryptionEpoch===n,p=l=>{if(this.activeManagedPublication!==t)return;let y=a();if(this.activeManagedPublication=null,y&&(l===c||l instanceof I&&l.gatewayCode==="managed-lease-stale"&&l.retryable))this.managedPublishQueue.unshift(...t.pending),this.managedPublishAwaitingLease=!(this.roomArchitectureSnapshot?.phase==="settled"&&this.sparseTopologyRevision>r);else if(l||!y){for(let h of t.pending)h.reject(l??s);if(y)throw l}this.scheduleManagedPublish();};try{let l=this.managedWasmClient,y=this.managedState;if(!i||i.effective!=="managed"||i.phase!=="settled"||n<1||!l||!y)throw new Error("[OpenRTC] Managed room encryption is not settled.");let h=[],b=this.managedAvenueKey();try{for(let m of e){let w=await l.__sealManagedRoomPayload(b,BigInt(i.epoch),BigInt(n),m.input.messageId,m.input.channel,m.input.priority,m.input.zoneId,m.input.payload);h.push({item:m,sealedState:w.sealedState,envelope:{messageId:m.input.messageId,channel:m.input.channel,priority:m.input.priority,scope:m.input.zoneId?{kind:"zone",zoneId:m.input.zoneId}:{kind:"global"},ciphertext:w.payload}});}await this.persistManagedCheckpoint(b,y,l,h[h.length-1].sealedState);}catch(m){throw await this.retireFailedManagedCheckpoint(b,y,l,m),m}if(!a())throw s;let f=[],u=[],R=0;for(let m of h){let w=m.envelope.ciphertext.length;u.length>0&&R+w>D&&(f.push(u),u=[],R=0),u.push(m),R+=w;}u.length>0&&f.push(u);let v=()=>{if(!a()){p(s);return}if(!o()){p(c);return}let m=f.shift();if(!m){p();return}this.sendOperation({v:1,type:"managed.publish",idempotencyKey:A("managed-publish"),architectureEpoch:i.epoch,encryptionEpoch:n,batch:m.map(({envelope:w})=>w)},w=>{if(!a())throw s;if(w!==!1&&!o())throw c}).then(()=>this.enqueueManagedWork(async()=>{if(!a()){p(s);return}for(let{item:w}of m)t.pending.delete(w),w.resolve();f.length===0?p():v();}),w=>this.enqueueManagedWork(async()=>{p(w);}));};v();}catch(l){p(l);}}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 t=this.managedAvenueKey(),i=(async()=>{let n=await this.managedStateProvider(this.options.appTag,this.options.getLocalDeviceId(),t),r=await e.__initManagedRoomGroup(t,this.options.getLocalDeviceId(),n.wrappingKey,n.sealedState);this.managedState=n,await this.executeManagedGroupActions([r]);})();this.managedInitialization=i;try{await i;}finally{this.managedInitialization===i&&(this.managedInitialization=null);}}async executeManagedGroupActions(e){let t=this.managedState,i=this.managedWasmClient,n=this.managedAvenueKey();for(let r of e){if(t!==this.managedState||i!==this.managedWasmClient)return;try{if(r.type==="migration-status")this.managedMigrationPending=r.pending;else if(r.type==="publish-recovery-key-package")await this.sendOperation({v:1,type:"managed.key-package.publish",idempotencyKey:r.idempotencyKey,keyPackageHash:r.keyPackageHash,keyPackage:r.keyPackage,recovery:r.recovery});else if(r.type==="persist-state"){if(!t||!i)throw new Error("[OpenRTC] Managed room state store is unavailable.");await this.persistManagedCheckpoint(n,t,i,r.sealedState);}else r.type==="publish-key-package"?await this.sendOperation({v:1,type:"managed.key-package.publish",idempotencyKey:A("managed-key-package"),keyPackageHash:r.keyPackageHash,keyPackage:r.keyPackage}):r.type==="request-prepare-page"?await this.sendOperation({v:1,type:"managed.prepare.page.request",idempotencyKey:A("managed-prepare-page"),preparationId:r.preparationId,pageIndex:r.pageIndex}):r.type==="send-artifact-chunk"?await this.sendOperation({v:1,type:"managed.commit.chunk",idempotencyKey:r.idempotencyKey,...r.chunk}):r.type==="acknowledge-commit"&&await this.sendOperation({v:1,type:"managed.commit.ack",idempotencyKey:r.idempotencyKey,preparationId:r.preparationId,encryptionEpoch:r.encryptionEpoch,groupIdHash:r.groupIdHash});}catch(s){if(s instanceof I&&s.gatewayCode==="managed-preparation-stale"&&s.retryable&&r.type!=="persist-state"&&r.type!=="publish-key-package")return;throw s}}}async handleManagedFrame(e){await this.ensureManagedGroupInitialized();let t=this.managedWasmClient;if(!t)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 t.__handleManagedRoomPreparePage(i,e));return}if(e.type==="managed.commit.chunk.received"){await this.executeManagedGroupActions(await t.__handleManagedRoomArtifactChunk(i,e));return}}async handleManagedReceivedFrames(e,t){if(await this.ensureManagedGroupInitialized(),!t())return;let i=this.managedWasmClient,n=this.managedState;if(!i||!n)throw new Error("[OpenRTC] Managed room encryption is unavailable.");let r=this.managedAvenueKey(),s=()=>this.managedState===n&&this.managedWasmClient===i,c=async u=>{await this.retireFailedManagedCheckpoint(r,n,i,u);},a=this.roomArchitectureSnapshot,o=[],p=null,l=false,y,h=[],b=[];try{for(let u of e){if(!a||a.effective!=="managed"||a.phase!=="settled"||u.architectureEpoch!==a.epoch||u.encryptionEpoch!==this.roomEncryptionEpoch)throw new Error("[OpenRTC] Managed room delivery uses a stale room lease.");let R={architectureEpoch:u.architectureEpoch,encryptionEpoch:u.encryptionEpoch,batch:u.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}))};b.push(R),h.push(u);}}catch(u){l=true,y=u;}let f=(u,R,v)=>{let m=u.batch[R],w=m.scope.kind==="zone"?m.scope.zoneId:void 0;return {senderId:u.senderDeviceId,messageId:m.messageId,channel:m.channel,priority:m.priority,...w?{zoneId:w}:{},payload:U(v)}};try{let u=b.reduce((v,m)=>v+m.batch.length,0),R=b.reduce((v,m)=>v+m.batch.reduce((w,k)=>w+k.ciphertext.length,0),0);if(i.__openManagedRoomPayloadFrames&&u>1&&u<=x&&b.every(v=>v.batch.length>0)&&R<=D){let v=await i.__openManagedRoomPayloadFrames(r,b);if(!s())return;if(!Array.isArray(v.frames)||v.frames.length>h.length||v.frames.some((w,k)=>!Array.isArray(w)||w.length!==h[k].batch.length)||v.frames.length>0&&(typeof v.sealedState!="string"||!v.sealedState)||!v.failure&&v.frames.length!==h.length)throw new Error("[OpenRTC] Managed room checkpoint returned an invalid frame prefix.");let m=v.frames.flatMap((w,k)=>w.map((S,O)=>f(h[k],O,S)));p=v.sealedState,o.push(...m),v.failure&&(l=!0,y=new Error(v.failure));}else for(let v of h){let m=[],w=null;for(let[k,S]of v.batch.entries()){let O=await i.__openManagedRoomPayload(r,BigInt(v.architectureEpoch),BigInt(v.encryptionEpoch),S.messageId,S.channel,S.priority,S.scope.kind==="zone"?S.scope.zoneId:void 0,U(S.ciphertext));if(!s())return;m.push(f(v,k,O.payload)),w=O.sealedState;}if(m.length&&(typeof w!="string"||!w))throw new Error("[OpenRTC] Managed room checkpoint is missing.");w&&(p=w),o.push(...m);}}catch(u){l=true,y=u;}if(s()){p&&await this.persistManagedCheckpoint(r,n,i,p);try{e:for(let u of o)for(let R of this.managedMessageListeners){if(!t()||!s())break e;R(u);}}finally{l&&await c(y);}if(l)throw y}}async persistManagedCheckpoint(e,t,i,n){if(t!==this.managedState||i!==this.managedWasmClient)throw new Error("[OpenRTC] Managed room crypto owner retired.");try{if(typeof n!="string"||!n)throw new Error("[OpenRTC] Managed room checkpoint is missing.");await t.persist(U(n));}catch(r){throw await this.retireFailedManagedCheckpoint(e,t,i,r),r}}async retireFailedManagedCheckpoint(e,t,i,n){if(!(t!==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 r of this.managedPublishQueue.splice(0))r.reject(n);this.managedState=null,this.managedInitialization=null;try{await i?.__forgetManagedRoomGroup(e);}finally{t.close();}}}async sendOperation(e,t){this.budgetRenewalPromise&&await this.budgetRenewalPromise,t?.();let i=this.budgetRenewalEpoch;try{await this.sendOperationOnce(e);}catch(n){if(t?.(false),!(n instanceof I)||n.code!=="budget-renewal-required"&&n.code!==a$1.BUDGET_RENEWAL_REQUIRED||!n.retryable)throw n;this.budgetRenewalEpoch===i&&await this.renewBudget(),t?.(),await this.sendOperationOnce(e);}}async sendOperationOnce(e){let t=this.socket;if(!t||t.readyState!==WebSocket.OPEN||!this.socketReady)throw new Error("Coordination gateway is not connected.");await new Promise((i,n)=>{let r=setTimeout(()=>{this.pendingAcks.get(e.idempotencyKey)?.timer===r&&this.pendingAcks.delete(e.idempotencyKey),n(new Error("Coordination gateway acknowledgement timed out."));},E);this.pendingAcks.set(e.idempotencyKey,{socket:t,resolve:i,reject:n,timer:r});try{t.send(JSON.stringify(e));}catch(s){clearTimeout(r),this.pendingAcks.delete(e.idempotencyKey),n(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 t=await this.options.resolveSpaceNamespaceId();if(!t)throw new Error("Space namespace is not available for coordination.");return {kind:"space",id:t}}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 t=this.sparseRoutes.get(e.deviceId),i=t?{...e,...t}:{...e,runtimeInstanceId:"",nodeId:"",ticket:""};this.devices.set(e.deviceId,this.toDevice(i));}this.emitDevices();}async acceptTopologyLease(e,t={grantJti:this.activeGrantJti,expiresAtMs:this.activeGrantExpiresAtMs,avenue:this.activeAvenue}){let i=this.socket;if(e.topologyRevision<=this.sparseTopologyRevision)return;let n=t.avenue,r=[...e.active,...e.backups],s=r.map(h=>h.deviceId),c=e.schemaVersion===1||this.validArchitectureLease(e.architecture),a=e.schemaVersion===1||this.validGroupEncryptionLease(e.groupEncryption,e.architecture),o=e.schemaVersion===2&&e.architecture.effectiveMode==="authority",p=e.schemaVersion===2?e.admissionPeers:void 0,l=!o||this.peerAdmissionScope!==null&&this.peerAdmissionRuntime!==null&&Array.isArray(p)&&p.length<=50&&new Set(p.map(h=>h.deviceId)).size===p.length&&p.every(h=>this.sparseMembers.get(h.deviceId)?.online&&h.deviceId!==this.options.getLocalDeviceId()&&/^[0-9a-f]{64}$/.test(h.nodeId));if(!((e.schemaVersion===1||e.schemaVersion===2)&&c&&a&&l&&Number.isSafeInteger(e.topologyRevision)&&e.topologyRevision>0&&(this.sparseTopologyRevision===0?e.previousTopologyRevision===void 0:e.previousTopologyRevision===this.sparseTopologyRevision)&&e.grantJti===t.grantJti&&n!==null&&e.avenue.kind===n.kind&&e.avenue.id===n.id&&Number.isSafeInteger(e.expiresAtMs)&&e.expiresAtMs>Date.now()&&e.expiresAtMs<=t.expiresAtMs&&e.active.length<=16&&e.backups.length<=4&&r.length<=20&&new Set(s).size===s.length&&r.every(h=>h.online&&this.sparseMembers.has(h.deviceId)&&h.deviceId!==this.options.getLocalDeviceId()&&h.nodeId.trim().length>0&&h.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 h=e.groupEncryption,b=await this.managedWasmClient.__applyManagedRoomAuthority(this.managedAvenueKey(),{...h?{preparationId:h.preparationId,memberSetHash:h.memberSetHash,groupIdHash:h.groupIdHash,previousEncryptionEpoch:h.previousEncryptionEpoch??0,encryptionEpoch:h.epoch}:{},...e.managedRecovery?{recovery:{...e.managedRecovery,expiresAtMs:e.expiresAtMs}}:{}},h?.phase==="settled",h?.previousPreparation);if(await this.executeManagedGroupActions(b),i!==this.socket||this.stopped)return}if(o)try{this.peerAdmissionRuntime.__updateScopePeerAdmission(this.peerAdmissionScope,++this.peerAdmissionRevision,e.expiresAtMs,JSON.stringify(p.map(h=>h.nodeId)));}catch{this.socket?.close(4400,"invalid peer admission lease");return}if(e.schemaVersion===2){e.groupEncryption&&(this.roomEncryptionEpoch=e.groupEncryption.epoch);let h={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},b=JSON.stringify(h)!==JSON.stringify(this.roomArchitectureSnapshot);if(this.roomArchitectureSnapshot=h,b)for(let f of this.architectureListeners)f({...h});if(h.effective!=="authority"&&this.roomAuthorityAssignment){this.roomAuthorityAssignmentExpiry&&(clearTimeout(this.roomAuthorityAssignmentExpiry),this.roomAuthorityAssignmentExpiry=null),this.roomAuthorityAssignment=null;for(let f of this.authorityAssignmentListeners)f(null);}h.effective==="managed"&&(h.phase==="settled"&&(this.managedPublishAwaitingLease=false),this.enqueueManagedWork(()=>this.ensureManagedGroupInitialized()),this.scheduleManagedPublish());}this.sparseTopologyRevision=e.topologyRevision,this.sparseRoutes.clear();for(let h of e.active)this.sparseRoutes.set(h.deviceId,{...h,topologyRole:"active",topologyRevision:e.topologyRevision});for(let h of e.backups)this.sparseRoutes.set(h.deviceId,{...h,topologyRole:"backup",topologyRevision:e.topologyRevision});this.rebuildSparseDevices();}acceptAuthorityAssignment(e,t){let i=this.roomAuthorityAssignment,n=this.options.getLocalDeviceId(),r=[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===n&&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&&r.every(a=>/^[A-Za-z0-9_.:@-]{1,160}$/.test(a))&&/^[A-Za-z0-9_-]{86}$/.test(t)&&(!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 t=this.roomArchitectureSnapshot?.epoch??0,i=new Set(["auto","mesh","sparse","managed","authority"]),n=new Set(["mesh","sparse","managed","authority"]),r=new Set(["size","traffic","latency","cost","capacity","manual","recovery"]);return e.policyVersion==="room-architecture-v1"&&Number.isSafeInteger(e.epoch)&&e.epoch>0&&e.epoch>=t&&(e.epoch===t||t===0||e.previousArchitectureEpoch===t)&&i.has(e.requestedMode)&&n.has(e.effectiveMode)&&(e.phase==="settled"||e.phase==="preparing")&&r.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,t){if(!e)return t.effectiveMode!=="managed"||t.phase==="preparing";let i=this.managedMigrationPending?0:this.roomEncryptionEpoch,n=e.previousPreparation;return (n===void 0||n!==null&&typeof n=="object"&&/^[A-Za-z0-9_.:@-]{1,160}$/.test(n.preparationId)&&/^[A-Za-z0-9_-]{43}$/.test(n.memberSetHash)&&n.groupIdHash===e.groupIdHash&&Number.isSafeInteger(n.previousEncryptionEpoch)&&n.previousEncryptionEpoch>=0&&Number.isSafeInteger(n.encryptionEpoch)&&n.encryptionEpoch===n.previousEncryptionEpoch+1&&n.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")&&(t.effectiveMode!=="managed"||t.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(t=>!e||t.nodeId!==e).sort((t,i)=>t.deviceId.localeCompare(i.deviceId))}emitDevices(){let e=this.snapshot();for(let t of this.deviceListeners)t(e);}emitDeviceEvents(e){for(let t of this.deviceStreams)t.enqueue(e);}updateLocalDeviceExpiry(e){let t=this.options.getLocalDeviceId(),i=this.devices.get(t);if(!i||i.expiresAt===e)return;let n={...i,expiresAt:e};this.devices.set(t,n),this.emitDeviceEvents([{type:"modified",device:n}]),this.emitDevices();}scheduleAuthRefresh(e,t){this.authRefreshTimer&&clearTimeout(this.authRefreshTimer);let i=e-Date.now(),n=t===2?ue:le,r=i>n+1e3;this.authRefreshTimer=setTimeout(()=>{if(this.authRefreshTimer=null,this.stopped)return;if(!r){this.stopSocket(false),this.scheduleReconnect(new g("Coordination credential crossed a billing boundary.",true));return}(t===2&&this.leaseRefreshMode==="active"?this.refreshLease():this.refreshAuthentication()).catch(c=>{this.stopSocket(false),this.scheduleReconnect(c);});},r?i-n:Math.max(1e3,i+1e3));}refreshAuthentication(e=false,t=false){let i=`${t?"refill":e?"issue":"refresh"}\0${this.desiredPresence?.ticket??""}`,n=this.authenticationRefreshes.get(i);if(n)return n;let r=this.authenticationRefreshTail.catch(()=>{}).then(()=>this.performAuthenticationRefresh(e,t));this.authenticationRefreshTail=r,this.authenticationRefreshes.set(i,r);let s=()=>{this.authenticationRefreshes.get(i)===r&&this.authenticationRefreshes.delete(i);};return r.then(s,s),r}currentRefillCredential(e){let t=this.refillCredential;if(!t||t.ticket!==e||t.grant.token!==this.activeGrantToken||t.grant.protocolVersion!==2||t.grant.expiresAtMs<this.activeGrantExpiresAtMs)return null;let i=ne(t.grant.token);return i?.budget?.controlFunding?.recipeVersion!=="coordination-provider-control-v3"||!Number.isSafeInteger(i?.exp)||!Number.isSafeInteger(t.grant.expiresAtMs)||Math.min(t.grant.expiresAtMs,Number(i?.exp)*1e3)<=Date.now()+E?null:t.grant}async performAuthenticationRefresh(e,t=false){let i=this.socket,n=this.desiredPresence;if(!i||i.readyState!==WebSocket.OPEN||!this.socketReady||!n)throw new g("Coordination socket is unavailable for credential refresh.",true);if(this.pendingAuthRefresh)return this.pendingAuthRefresh.promise;let r=(t?this.currentRefillCredential(n.ticket):null)??await this.mintGatewayCredential(n,!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((p,l)=>{s=p,c=l;}),o=setTimeout(()=>{this.pendingAuthRefresh?.timer===o&&(this.pendingAuthRefresh=null),c(new g("Coordination credential refresh timed out.",true));},E);this.pendingAuthRefresh={socket:i,promise:a,resolve:s,reject:c,timer:o};try{i.send(JSON.stringify({v:1,type:"auth.refresh",token:r.token}));}catch(p){this.rejectPendingAuthRefresh(new g(p instanceof Error?p.message:"Coordination credential refresh send failed.",true),i);}await a,this.activeGrantToken=r.token,this.refillCredential={grant:r,ticket:n.ticket},this.activeGrantJti=Y(r.token),this.activeAvenue=r.avenue,this.activeGrantExpiresAtMs=r.expiresAtMs,this.activeGrantProtocolVersion=r.protocolVersion;}refreshLease(){let e=`lease\0${this.desiredPresence?.ticket??""}`,t=this.authenticationRefreshes.get(e);if(t)return t;let i=this.authenticationRefreshTail.catch(()=>{}).then(()=>this.performLeaseRefresh());this.authenticationRefreshTail=i,this.authenticationRefreshes.set(e,i);let n=()=>{this.authenticationRefreshes.get(e)===i&&this.authenticationRefreshes.delete(e);};return i.then(n,n),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 t=A("lease"),i,n,r=new Promise((c,a)=>{i=c,n=a;}),s=setTimeout(()=>{this.pendingAuthRefresh?.timer===s&&(this.pendingAuthRefresh=null,this.pendingLeaseRefreshKey=null),n(new g("Coordination lease refresh timed out.",true));},E);this.pendingLeaseRefreshKey=t,this.pendingAuthRefresh={socket:e,promise:r,resolve:i,reject:n,timer:s};try{e.send(JSON.stringify({v:1,type:"lease.refresh",idempotencyKey:t}));}catch(c){this.rejectPendingAuthRefresh(new g(c instanceof Error?c.message:"Coordination lease refresh send failed.",true),e);}try{await r;}catch(c){if(this.stopped||T(c))throw c;await this.performAuthenticationRefresh(true);}}stopForCredentialRevocation(e){return T(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:!ee(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,V),n=Date.now()-this.reconnectOutageStartedAtMs>=me,r=Ae(n?ye:d(i,250,ge));this.reconnectAttempt=Math.min(i+1,V),this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=null,this.ensureConnected().catch(s=>this.scheduleReconnect(s));},r);}stopSocket(e=true){this.managedReceiveTail=null,this.serviceObservationGeneration+=1;let t=this.activeManagedPublication;if(this.activeManagedPublication=null,t)for(let n of t.pending)n.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,t)=>{this.connectionReadyWaiters.add({resolve:e,reject:t});})}resolveConnectionReadyWaiters(){for(let e of this.connectionReadyWaiters)e.resolve();this.connectionReadyWaiters.clear();}rejectConnectionReadyWaiters(e){for(let t of this.connectionReadyWaiters)t.reject(e);this.connectionReadyWaiters.clear();}rejectPendingAuthRefresh(e,t){let i=this.pendingAuthRefresh;!i||t&&i.socket!==t||(clearTimeout(i.timer),this.pendingAuthRefresh=null,this.pendingLeaseRefreshKey=null,i.reject(e));}rejectPendingAcks(e,t){for(let[i,n]of this.pendingAcks)t&&n.socket!==t||(clearTimeout(n.timer),n.reject(new Error(e)),this.pendingAcks.delete(i));}unscopedId(e){let t=e.split("::");return t.length===2?t[1]:e}requireRoomConnection(e){let t=e.trim().toUpperCase(),i=this.activeAvenue??this.options.avenueOverride;if(i?.kind==="room"&&i.id.trim().toUpperCase()===t)return this;let n=this.roomConnections.get(t);if(!n)throw new Error(`Room ${t} is not joined through the coordination gateway.`);return n}friendConnection(e){let t=this.friendConnections.get(e);t||(t=new d$1({...this.options,avenueOverride:{kind:"user",id:e}}),t.setHostAvailability({available:this.hostAvailable,reason:"parent-avenue-created"}),this.friendConnections.set(e,t));let i=this.desiredPresence??this.friendObservationPresence;return !t.desiredPresence&&i&&this.activateFriendConnection(t,i),t}activateFriendConnection(e,t){e.updatePresence(t.localNodeId,t.ticket,t.online,t.ttlMs,t.metadata,t.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}}},W=class{constructor(e,t){this.socket=null;this.retired=false;this.opened=false;this.abort=new AbortController;this.listeners=new Set;this.pending=new Map;this.certificate="";this.certificateExpiresAt=0;this.lastRenewed=0;this.lastObserved=0;this.expiresAt=0;let i=new URL(e);if(i.username||i.password||i.search||i.hash||i.pathname!=="/v3/live"||!["https:","wss:"].includes(i.protocol)&&!(t&&["localhost","127.0.0.1","[::1]"].includes(i.hostname)&&["http:","ws:"].includes(i.protocol)))throw new Error("[OpenRTC] Invalid live coordination endpoint.");i.protocol=i.protocol==="https:"||i.protocol==="wss:"?"wss:":"ws:",this.endpoint=i.toString();}get closed(){return this.retired}onEvent(e){return this.listeners.add(e),()=>{this.listeners.delete(e);}}emit(e){for(let t of this.listeners)try{t(e);}catch{}}async credentials(e){if(this.retired)throw new Error("[OpenRTC] Live session is closed.");let t,i=new Promise((r,s)=>{t=()=>s(new Error("[OpenRTC] Live credential request was closed.")),this.abort.signal.aborted?t():this.abort.signal.addEventListener("abort",t,{once:true});}),n;try{n=await Promise.race([this.options.credentials({forceRefresh:e,signal:this.abort.signal}),i]);}finally{this.abort.signal.removeEventListener("abort",t);}if(this.retired)throw new Error("[OpenRTC] Live session is closed.");if(!n||typeof n.certificate!="string"||n.certificate.length>8192||typeof n.session!="string"||n.session.length>24e3||!/^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/.test(n.certificate)||!/^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/.test(n.session))throw new Error("[OpenRTC] Invalid app-issued live credentials.");return n}async open(e){if(this.opened||this.retired)throw new Error("[OpenRTC] Live session already opened or closed.");this.opened=true,this.options=e;try{let t=await this.credentials(!1);this.certificate=t.certificate;let i=b(this.certificate).exp;if(!Number.isSafeInteger(i)||Number(i)*1e3<=Date.now())throw new Error("[OpenRTC] Invalid live certificate expiry.");this.certificateExpiresAt=Number(i)*1e3,await new Promise((n,r)=>{let s=new WebSocket(this.endpoint,["openrtc.live.v1",`openrtc.cert.${t.certificate}`,`openrtc.session.${t.session}`]);this.socket=s;let c=setTimeout(()=>{r(new Error("[OpenRTC] Live admission timed out.")),this.close().catch(()=>{});},E);this.cancelOpening=()=>{clearTimeout(c),r(new Error("[OpenRTC] Live admission was closed."));},s.onopen=()=>{if(this.retired||this.socket!==s){s.close();return}if(s.protocol!=="openrtc.live.v1"){r(new Error("[OpenRTC] Live protocol was not negotiated.")),this.close().catch(()=>{});return}clearTimeout(c),this.cancelOpening=void 0,this.lastRenewed=this.lastObserved=Date.now(),this.keepalive=setInterval(()=>{if(Date.now()>=this.expiresAt||Date.now()-this.lastObserved>=9e4){this.close().catch(()=>{});return}try{s.send("openrtc.live.ping");}catch{this.close().catch(()=>{});}},3e4);try{this.scheduleRenewal(t.session),n();}catch{r(new Error("[OpenRTC] Invalid live credential expiry.")),this.close().catch(()=>{});}},s.onmessage=a=>{if(!(this.retired||this.socket!==s)&&(this.lastObserved=Date.now(),a.data!=="openrtc.live.pong"))try{if(typeof a.data!="string"||a.data.length>65536*6+4096)throw Error();let o=JSON.parse(a.data);if(o.type==="accepted"&&typeof o.id=="string"){let p=this.pending.get(o.id);if(!p)return;clearTimeout(p.timer),this.pending.delete(o.id),p.resolve({units:o.units});}else if(o.type==="message"&&typeof o.channel=="string"&&typeof o.from=="string"&&typeof o.data=="string")this.emit({type:"message",channel:o.channel,from:o.from,data:o.data});else {if(o.type==="error"&&typeof o.code=="string"&&/^[A-Za-z0-9_.:-]{1,128}$/.test(o.code)){for(let p of this.pending.values())clearTimeout(p.timer),p.reject(new Error(`[OpenRTC] Live service rejected the operation: ${o.code}.`));this.pending.clear();}throw Error()}}catch{this.close().catch(()=>{});}},s.onerror=()=>{r(new Error("[OpenRTC] Live connection failed.")),this.close().catch(()=>{});},s.onclose=()=>{r(new Error("[OpenRTC] Live connection closed.")),this.close().catch(()=>{});};});}catch(t){throw await this.close(),t}}scheduleRenewal(e){clearTimeout(this.refresh);let t=b(e).exp;if(!Number.isSafeInteger(t)||Number(t)*1e3<=Date.now())throw new Error("Expired live session.");let i=Number(t)*1e3;this.expiresAt=i;let n=i>=this.certificateExpiresAt,r=n?i:Math.max(i-6e4,this.lastRenewed+18e5);this.refresh=setTimeout(()=>{if(n||r>=i){this.close().catch(()=>{});return}this.renew().catch(()=>this.close());},Math.max(0,Math.min(r,i)-Date.now()));}async renew(){if(this.renewal)return this.renewal;if(this.expiresAt>=this.certificateExpiresAt)throw new Error("live-certificate-expiry");let e=this.renewOnce();this.renewal=e;try{await e;}catch(t){throw await this.close(),t}finally{this.renewal===e&&(this.renewal=void 0);}}async renewOnce(){clearTimeout(this.refresh),this.refresh=setTimeout(()=>{this.close().catch(()=>{});},Math.max(0,this.expiresAt-Date.now()));let e=await this.credentials(true);if(e.certificate!==this.certificate)throw new Error("[OpenRTC] Live term changed; open a new session.");await this.request({type:"renew",token:e.session}),!this.retired&&(this.lastRenewed=Date.now(),this.scheduleRenewal(e.session));}async request(e){let t=this.socket;if(this.retired||Date.now()>=this.expiresAt||!t||t.readyState!==WebSocket.OPEN)throw new Error("[OpenRTC] Live session is closed.");if(this.pending.size>=64)throw new Error("[OpenRTC] Too many outstanding live operations.");let i=crypto.randomUUID();return new Promise((n,r)=>{let s=setTimeout(()=>{this.pending.delete(i),r(new Error("[OpenRTC] Live acceptance is unknown.")),this.close().catch(()=>{});},E);this.pending.set(i,{resolve:n,reject:r,timer:s});try{t.send(JSON.stringify({...e,id:i}));}catch{clearTimeout(s),this.pending.delete(i),r(new Error("[OpenRTC] Live send failed.")),this.close().catch(()=>{});}})}async close(){if(this.closing)return this.closing;if(this.retired&&!this.socket)return;this.retired=true,this.abort.abort(),this.cancelOpening?.(),this.cancelOpening=void 0,clearInterval(this.keepalive),clearTimeout(this.refresh);for(let i of this.pending.values())clearTimeout(i.timer),i.reject(new Error("[OpenRTC] Live session is closed; acceptance may be unknown."));this.pending.clear();let e=this.socket,t=e&&e.readyState!==WebSocket.CLOSED?new Promise((i,n)=>{let r=e.onclose,s=setTimeout(()=>n(new Error("[OpenRTC] Live socket close was not confirmed.")),E);e.onclose=c=>{clearTimeout(s),i(),r?.call(e,c);};try{e.close(1e3,"live session closed");}catch{clearTimeout(s),n(new Error("[OpenRTC] Live socket close failed."));}}):Promise.resolve();this.closing=t;try{await t,this.socket=null,this.emit({type:"closed"}),this.listeners.clear();}finally{this.closing===t&&(this.closing=void 0);}}};
2
+ export{ie as a};
@@ -0,0 +1 @@
1
+ function b(e){return new Promise(r=>setTimeout(r,e))}function g(e){let r=new Uint8Array(e.byteLength);return r.set(e),r}function R(e){let r=e.reduce((i,o)=>i+o.byteLength,0),t=new Uint8Array(r),n=0;for(let i of e)t.set(i,n),n+=i.byteLength;return t}function S(e,r,t){let n=r*Math.pow(2,Math.max(0,e-1));return Math.min(t,n)}function A(e){try{let r=e;return !!r&&!!r.send&&typeof r.send.getWriter=="function"&&!!r.recv&&typeof r.recv.getReader=="function"}catch{return false}}function B(e,r,t){let n=e;if(!n)return null;try{let i=n.send,o=n.recv;if(!i||typeof i.getWriter!="function"||!o||typeof o.getReader!="function")return null;let s=typeof n.endpoint_id=="string"&&n.endpoint_id.trim().length>0?n.endpoint_id:r,d=Number.isSafeInteger(n.transport_stable_id)&&Number(n.transport_stable_id)>0?Number(n.transport_stable_id):void 0,u=Number.isSafeInteger(t)&&Number(t)>0?Number(t):void 0;if(d!==void 0&&u!==void 0&&d!==u)return null;let a=d??u,c={send:i,recv:o,endpoint_id:s,...a?{transport_stable_id:a}:{}};return n.applicationCryptoWrapped===!0&&(c.applicationCryptoWrapped=!0),c}catch{return null}}function h(e,r){let t={send:e.send,recv:r,endpoint_id:typeof e.endpoint_id=="string"?e.endpoint_id:"",...Number.isSafeInteger(e.transport_stable_id)&&Number(e.transport_stable_id)>0?{transport_stable_id:Number(e.transport_stable_id)}:{}};return e?.applicationCryptoWrapped===true&&(t.applicationCryptoWrapped=true),t}async function U(e,r){if(!e)return false;try{let t=e.send?.getWriter?.();if(t)try{await t.close();}catch{}finally{try{t.releaseLock();}catch{}}}catch{}try{let t=e.recv?.getReader?.();if(t)try{await t.cancel(r);}catch{}finally{try{t.releaseLock();}catch{}}}catch{}return true}function _(e,r,t={}){let n=t.context??"prependBytesToReader",i=t.traceId,o=r.byteLength===0,s=t.pendingRead??null,d=a=>t.release?.(a),u=(a,c)=>t.log?.(a,c);return new ReadableStream({async pull(a){if(!o){o=true,a.enqueue(r);return}if(s){let l=s;s=null;let y;try{y=await l;}catch(p){a.error(p),d("pending-read-error"),u("prepend-bytes:pending-read-error",{context:n,traceId:i||null,error:p?.message||String(p)});return}if(y.done){a.close(),d("pending-done");return}y.value&&a.enqueue(y.value);return}let c;try{c=await e.read();}catch(l){a.error(l),d("read-error"),u("prepend-bytes:read-error",{context:n,traceId:i||null,error:l?.message||String(l)});return}let{done:m,value:f}=c;if(m){a.close(),d("done");return}f&&a.enqueue(f);},async cancel(a){d("cancel");}})}async function w(e,r){let t=e.read(),n=r-Date.now();if(n<=0)return {status:"timeout",pendingRead:t};let i=Symbol("probe-timeout"),o,s=new Promise(d=>{o=setTimeout(()=>d(i),n);});try{let d=await Promise.race([t,s]);if(d===i)return {status:"timeout",pendingRead:t};let{done:u,value:a}=d;return u?{status:"done"}:{status:"data",value:a&&a.byteLength>0?new Uint8Array(a):new Uint8Array(0)}}finally{o&&clearTimeout(o);}}export{b as a,g as b,R as c,S as d,A as e,B as f,h as g,U as h,_ as i,w as j};
@@ -0,0 +1 @@
1
+ import {a}from'./chunk-FPJAUAEU.js';import {b as b$2}from'./chunk-FNCEVW7G.js';import {b as b$1}from'./chunk-LB27VQRL.js';import {c}from'./chunk-L7N4T2PX.js';import*as I from'tweetnacl';function U(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 ie(t){if(!Number.isSafeInteger(t)||t<=0)throw new Error("Invalid transfer peer demand generation.")}function ae(t){if(!t||typeof t!="object")throw new Error("Invalid transfer peer demand request.");if(U(t.id),U(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 Ue(t,e,n=false){if(typeof t!="string"||new TextEncoder().encode(t).byteLength>2048)throw new Error("Invalid transfer peer demand response.");let r=JSON.parse(t);if(r===null&&n)return null;if(!r||typeof r!="object")throw new Error("Invalid transfer peer demand response.");let o=r;if(ae({id:o.id,deviceId:o.deviceId,purpose:o.purpose}),ie(o.generation),o.id!==e.id||e.generation!==void 0&&o.generation!==e.generation||e.deviceId!==void 0&&o.deviceId!==e.deviceId||e.purpose!==void 0&&o.purpose!==e.purpose||!["waitingForPeer","queued","admitted"].includes(o.state))throw new Error("Invalid transfer peer demand response.");return o}function qe(){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 C=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 r=(async()=>{let o=await this.provider(e),a=o?.token?.trim()??"",c=Number(o?.expiresAtMs),p=Date.now();if(!a||!Number.isFinite(c)||c<=p+3e4)throw new Error("[OpenRTC] Native trust token provider returned no usable short-lived token.");let d={token:a,expiresAtMs:c};return this.cached=d,this.refreshRetryUsed=false,this.notify(d),this.scheduleRefresh(d),d})();this.inFlight=r;try{return await r}finally{this.inFlight===r&&(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 q=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 C(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 a({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 se(){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 x(t,e,n){if(se()){if(typeof n>"u"){console[t](e);return}console[t](e,n);}}function Ve(t,e){x("debug",t,e);}function $e(t,e){x("info",t,e);}function Xe(t,e){x("log",t,e);}function z(){return typeof window>"u"?false:!!(window.__TAURI_IPC__||window.__TAURI_INTERNALS__||window.__TAURI__||window.location.protocol==="tauri:"||window.location.hostname==="tauri.localhost")}var ce="[OpenRTC][teardown-trace]";function le(){try{let t=globalThis;if(t.OPENRTC_TEARDOWN_TRACE===!0||t.localStorage?.getItem("OPENRTC_TEARDOWN_TRACE")==="1")return !0}catch{}return false}function tt(t,e={}){console.info(ce,{kind:t,ts:new Date().toISOString(),...e}),le()&&console.info("[OpenRTC][teardown-trace:stack]",{kind:t,stack:new Error(`teardown: ${t}`).stack});}var M="trustedDevice",de="plutonium:e2ee:identity:v1",ue="plutonium:e2ee:identity:session:v1",pe="openrtc-trust",b="identity",Q="transport-trust:v1",fe=2,W="managed-room-keys",J="managed-room-state",ye=1,l=null,T=null;function f(t){let e=atob(t),n=new Uint8Array(e.length);for(let r=0;r<e.length;r+=1)n[r]=e.charCodeAt(r);return n}function h(t){let e="";for(let n=0;n<t.length;n+=1)e+=String.fromCharCode(t[n]);return btoa(e)}async function N(t){let e=await crypto.subtle.digest("SHA-256",t),n=new Uint8Array(e);return Array.from(n).map(r=>r.toString(16).padStart(2,"0")).join("")}function ge(){return typeof sessionStorage>"u"?null:sessionStorage}function me(){if(!(typeof localStorage>"u"))try{localStorage.removeItem(de);}catch{}}var P=null;async function Y(){return P||(P=(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}})(),P)}async function be(t){let e=await crypto.subtle.exportKey("raw",t);return new Uint8Array(e)}function Se(){try{return typeof indexedDB<"u"?indexedDB:null}catch{return null}}function V(){let t=Se();return t?new Promise(e=>{let n;try{n=t.open(pe,fe);}catch{e(null);return}n.onupgradeneeded=()=>{let r=n.result;r.objectStoreNames.contains(b)||r.createObjectStore(b),r.objectStoreNames.contains(W)||r.createObjectStore(W),r.objectStoreNames.contains(J)||r.createObjectStore(J);},n.onsuccess=()=>e(n.result),n.onerror=()=>e(null),n.onblocked=()=>e(null);}):Promise.resolve(null)}async function ve(){let t=await V();if(!t)return null;try{return await new Promise(e=>{let o=t.transaction(b,"readonly").objectStore(b).get(Q);o.onsuccess=()=>{let a=o.result;e(a&&a.privateKey&&a.publicKey?a:null);},o.onerror=()=>e(null);})}catch{return null}finally{t.close();}}async function Te(t){let e=await V();if(!e)return false;try{return await new Promise(n=>{let r=e.transaction(b,"readwrite");r.objectStore(b).put(t,Q),r.oncomplete=()=>n(!0),r.onerror=()=>n(!1),r.onabort=()=>n(!1);})}catch{return false}finally{e.close();}}async function $(t,e){let n=await be(t.publicKey),r=await N(n),o=t.privateKey;return {publicKey:n,fingerprint:r,backend:"webcrypto-nonextractable",durable:e,privateKey:o,async signChallenge(a){let c=await crypto.subtle.sign({name:"Ed25519"},o,f(a));return h(new Uint8Array(c))}}}function Ie(t,e,n){let r=t.secretKey;return {publicKey:t.publicKey,secretKey:r,fingerprint:e,backend:"tweetnacl",durable:n,async signChallenge(o){return he(o,r)}}}function it(t=32){let e=crypto.getRandomValues(new Uint8Array(t));return h(e)}function he(t,e){let n=I.sign.detached(f(t),e);return h(n)}function Re(t,e,n){try{return I.sign.detached.verify(f(t),f(e),f(n))}catch{return false}}async function at(t,e,n){let r=globalThis.crypto?.subtle;if(r&&typeof r.importKey=="function"&&typeof r.verify=="function")try{let o=await r.importKey("raw",f(n),{name:"Ed25519"},!1,["verify"]);return await r.verify({name:"Ed25519"},o,f(e),f(t))}catch{}return Re(t,e,n)}function st(t){return h(t)}function ct(t){if(!t||!t.trim())return null;try{let e=JSON.parse(t),n=e&&typeof e=="object"&&!Array.isArray(e)?e[M]:null;if(!n||typeof n!="object"||Array.isArray(n))return null;let r=n,o=typeof r.version=="number"?r.version:null,a=typeof r.identityPublicKey=="string"?r.identityPublicKey:null,c=typeof r.identityFingerprint=="string"?r.identityFingerprint:null;return !o||!a||!c?null:{version:o,identityPublicKey:a,identityFingerprint:c}}catch{return null}}async function _e(){let t=await Me().catch(()=>null);return t?{version:ye,identityPublicKey:h(t.publicKey),identityFingerprint:t.fingerprint}:null}async function lt(t){let e=await _e();if(!e)return t??void 0;let n=typeof t=="string"?t.trim():"";if(!n)return JSON.stringify({[M]:e});try{let r=JSON.parse(n);if(r&&typeof r=="object"&&!Array.isArray(r))return JSON.stringify({...r,[M]:e})}catch{}return JSON.stringify({metadata:t,[M]:e})}function we(){if(typeof window>"u")return null;let t=window.__TAURI_INTERNALS__;return !t||typeof t.invoke!="function"?null:t.invoke.bind(t)}async function Ae(){if(typeof window>"u")return null;let t=we();if(!z()&&!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=f(e.publicKeyBase64);if(n.byteLength!==I.sign.publicKeyLength)throw new Error("native transport trust public key has an invalid length");let r=await N(n);if(e.fingerprint!==r)throw new Error("native transport trust fingerprint does not match its public key");return {publicKey:n,fingerprint:r,backend:"native-provider",durable:!0,async signChallenge(o){return t("openrtc_sign_transport_trust_challenge",{challenge:o})}}}catch(e){let n=new Error("[OpenRTC] native transport trust provider failed; refusing WebCrypto fallback in Tauri.");throw n.cause=e,n}}function Ce(){let t=ge();t&&t.removeItem(ue);}async function Pe(){if(me(),Ce(),l)return l;let t=await Ae();if(t)return l=t,l;if(await Y()){let e=await ve();if(e)return l=await $(e,true),l}return null}async function Me(t={}){let e=r=>{if(t.ephemeral===true&&r?.durable)throw new Error("Cannot replace an active durable transport identity with an ephemeral identity.");if(t.ephemeral===false&&r&&!r.durable)throw new Error("Persistent transport identity requires durable storage before session startup.");return r};if(l)return e(l);if(T)return e(await T);let n=(async()=>{if(t.ephemeral!==true){let r=await Pe();if(r)return r}return ke(t)})();T=n;try{return e(await n)}finally{T===n&&(T=null);}}async function ke(t){if(l)return l;let e=t.ephemeral===true;if(await Y())try{let n=await crypto.subtle.generateKey({name:"Ed25519"},!1,["sign","verify"]),r=!1;return e||(r=await Te(n)),l=await $(n,r),l}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=I.sign.keyPair(),r=await N(b$1(n.publicKey));return l=Ie(n,r,!1),l}catch{return null}}var Ee={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 ut(){return Ee}var De={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}},xe={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 X(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 ft(t=globalThis){let e=X(De),n=typeof t?.RTCPeerConnection=="function";return e.transport.webRtc=n,e}function R(t){return t?.compiled===true&&t.enabled===true}function yt(t,e=false){let n=X(xe),r=t?.transport;return n.productMaturity={...n.productMaturity,...t?.productMaturity},r&&(n.transport.irohQuic=R(r.irohQuic),n.transport.irohLan=R(r.irohLan),n.transport.webRtc=R(r.webRtc),n.transport.moq=R(r.moq),n.transport.ble=R(r.ble)),n.transport.wasm=false,n.fallback.wasm=e,n}function gt(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 Z(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 S(t){return !t||typeof t!="object"?{}:t instanceof Map?Object.fromEntries(t):t}function G(t){let e=S(t),n=S(e.device);if(!Object.keys(n).length)return e;let r={...n,...e};return delete r.device,r}function i(t,...e){for(let n of e){let r=t[n];if(typeof r=="string"&&r.trim().length>0)return r}}function u(t,...e){for(let n of e){let r=t[n];if(typeof r=="boolean")return r}}function s(t,...e){for(let n of e){let r=t[n];if(typeof r=="number"&&Number.isFinite(r))return r}}function y(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 r=e.toMillis();return Number.isFinite(r)?r: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 r=typeof e.nanoseconds=="number"?e.nanoseconds:typeof e._nanoseconds=="number"?e._nanoseconds:0;return n*1e3+Math.floor((Number.isFinite(r)?r:0)/1e6)}}}function H(...t){let e=t.map(y).filter(n=>typeof n=="number"&&Number.isFinite(n));return e.length?Math.max(...e):void 0}function O(t){if(typeof t!="string")return;let e=t.trim().toLowerCase();return e==="online"||e==="idle"||e==="offline"?e:void 0}function ee(t){let e=O("presenceStatus"in t?t.presenceStatus:void 0),n="presenceUpdatedAt"in t?y(t.presenceUpdatedAt):void 0,r="presenceExpiresAt"in t?y(t.presenceExpiresAt):void 0,o=n??H(t.lastSeenAt,t.updatedAt,t.createdAt),a=r??y(t.expiresAt),c=e;c||(t.online?o!==void 0&&o+3e5<=Date.now()?c="idle":c="online":c="offline");let p=typeof t.ticket=="string"?t.ticket.trim():"",d="connectable"in t&&typeof t.connectable=="boolean"?t.connectable:c==="online"&&p.length>0;return {presenceStatus:c,presenceUpdatedAt:o,presenceExpiresAt:a,connectable:d}}function te(t){return b$2(t)}function g(t,...e){return te(i(t,...e))}function w(t){if(!Array.isArray(t))return;let e=Array.from(new Set(t.map(te).filter(n=>!!n)));return e.length?e:void 0}function ne(t){let e=S(t),n={webrtc:s(e,"webrtc"),iroh:s(e,"iroh"),irohLan:s(e,"irohLan","iroh_lan"),irohRelay:s(e,"irohRelay","iroh_relay"),ble:s(e,"ble"),moq:s(e,"moq")};return Object.values(n).some(r=>r!==void 0)?n:void 0}function Tt(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 It(t,e,n){return n?true:(typeof t.appTag=="string"?t.appTag:typeof t.tag=="string"?t.tag:void 0)===e}function Ne(t,e){let n=G(t),r=i(n,"deviceId","device_id")||e||"",o=i(n,"nodeId","node_id")||"",a=i(n,"ticket")||"";return {deviceId:r,deviceName:i(n,"deviceName","device_name")||"Unknown Device",online:!!n.online,ticket:a,friendTicket:i(n,"friendTicket","friend_ticket"),presenceStatus:O(i(n,"presenceStatus","presence_status","livenessStatus","liveness_status")),presenceUpdatedAt:s(n,"presenceUpdatedAt","presence_updated_at")??H(n.presenceUpdatedAt,n.presence_updated_at,n.lastSeenAt,n.last_seen_at,n.updatedAt,n.updated_at,n.createdAt,n.created_at),presenceExpiresAt:s(n,"presenceExpiresAt","presence_expires_at")??y(n.presenceExpiresAt??n.presence_expires_at)??y(n.expiresAt??n.expires_at),connectable:u(n,"connectable"),kind:i(n,"kind"),nodeId:o||void 0,devicePublicKeyJwk:n.devicePublicKeyJwk??n.device_public_key_jwk,platformType:i(n,"platformType","platform_type"),capabilities:n.capabilities||void 0,sessionId:i(n,"sessionId","session_id"),userId:i(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:i(n,"metadata"),excludedPeers:k(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 k(t){return Array.isArray(t)?[...new Set(t.filter(e=>typeof e=="string").map(e=>e.trim()).filter(Boolean))]:[]}function Ge(t){let e=ee(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?k(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?ne(t.latencyByTransport):void 0}}function _(t,e){return e===void 0?true:e===null?t==null:t==null||t===e}function re(t,e){let n=_(t.connectionId,e.connectionId)&&_(t.nodeId,e.nodeId)&&_(t.transportStableId,e.transportStableId)&&_(t.transportGeneration,e.transportGeneration)&&_(t.routeGeneration,e.routeGeneration),r=(o,a)=>o!==void 0?o:n?a:void 0;return {inheritsSnapshot:n,fields:{connectionId:r(e.connectionId??void 0,t.connectionId),transportStableId:r(e.transportStableId,t.transportStableId),transportGeneration:r(e.transportGeneration,t.transportGeneration),routeGeneration:r(e.routeGeneration,t.routeGeneration),activeTransport:r(e.activeTransport,t.activeTransport),parallelTransport:r(e.parallelTransport,t.parallelTransport),latencyMs:n?t.latencyMs:void 0,latencyByTransport:n?t.latencyByTransport:void 0}}}var He={connectionId:void 0,transportStableId:null,transportGeneration:void 0,routeGeneration:void 0,activeTransport:void 0,parallelTransport:void 0,latencyMs:void 0,latencyByTransport:void 0};function Oe(t,e,n){let r=re(t,{connectionId:e.activeConnectionId,nodeId:e.nodeId,transportStableId:e.transportStableId,transportGeneration:e.transportGeneration,routeGeneration:e.routeGeneration,activeTransport:e.activeTransport,parallelTransport:e.parallelTransport}),o=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(!o)return {...t,peerHealth:e.health??t.peerHealth,peerId:e.peerId??t.peerId,promotionEligible:o,scopes:e.scopes?.length?[...e.scopes]:t.scopes,nodeId:e.nodeId===void 0?t.nodeId:e.nodeId??void 0,deviceIdHint:e.deviceIdHint??t.deviceIdHint,...r.fields,readinessReason:e.readinessReason??t.readinessReason};let a=e.status??t.connectionStatus,c=typeof a=="string"?a.trim().toLowerCase():"",p=c==="failed"||c==="closed"||c==="disconnected",m=typeof e.readinessState=="string"&&e.readinessState.trim().length>0?e.readinessState==="routable":e.settledReady===true,v=t.settledReady===true||t.readinessState==="routable";if(r.inheritsSnapshot&&v&&!p&&!m)return {...t,peerHealth:e.health??t.peerHealth,peerId:e.peerId??t.peerId,promotionEligible:o,scopes:e.scopes?.length?[...e.scopes]:t.scopes,nodeId:e.nodeId===void 0?t.nodeId:e.nodeId??void 0,deviceIdHint:e.deviceIdHint??t.deviceIdHint,...r.fields,readinessReason:e.readinessReason??t.readinessReason};let A=p?false:m,E=m&&!p&&(c==="connecting"||c==="connected")?"connected":a,D=m?"routable":e.readinessState??(r.inheritsSnapshot?t.readinessState:void 0),oe=A?e.readinessReason??"peer-session-settled":e.readinessReason??(r.inheritsSnapshot?t.readinessReason:void 0);return {...t,connectionStatus:E,settledReady:A,readinessState:D,readinessReason:oe,peerHealth:e.health??t.peerHealth,peerId:e.peerId??t.peerId,promotionEligible:o,scopes:e.scopes?.length?[...e.scopes]:t.scopes,nodeId:e.nodeId===void 0?t.nodeId:e.nodeId??void 0,deviceIdHint:e.deviceIdHint??t.deviceIdHint,...r.fields}}function Be(t,e){let n=re(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 r=e.status??t.connectionStatus,o=typeof r=="string"?r.trim().toLowerCase():"",a=o==="failed"||o==="closed"||o==="disconnected",c=t.settledReady===true||t.readinessState==="routable",p=e.routable===false;if(n.inheritsSnapshot&&c&&a&&!p)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(c&&a)return {...t,connectionStatus:r,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,...He,scopes:e.scopes?.length?[...e.scopes]:t.scopes};let d=e.routable===true||e.protocolState==="routable";if(n.inheritsSnapshot&&c&&!a&&!d)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 m=e.transportState==="connected"&&e.health==="healthy",v=a?false:d,A=!a&&(d||m)&&(o==="connecting"||o==="connected"||e.transportState==="connected")?"connected":r,E=v?"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),D=v?(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:A,settledReady:v,readinessState:E,readinessReason:D,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 Ke(t){let{device:e,session:n=null,peer:r=null,isPromotionEligible:o}=t,a=Ge(e);return n&&(a=Oe(a,n,o)),r&&(a=Be(a,r)),Z(a)}function ht(t){let e=G(t),n=Ne(e),r=O(i(e,"presenceStatus","presence_status","livenessStatus","liveness_status")),o=ee({...n,...r?{presenceStatus:r}:{},presenceUpdatedAt:s(e,"presenceUpdatedAt","presence_updated_at")??H(e.presenceUpdatedAt,e.presence_updated_at,e.lastSeenAt,e.last_seen_at,e.updatedAt,e.updated_at,e.createdAt,e.created_at),presenceExpiresAt:s(e,"presenceExpiresAt","presence_expires_at")??y(e.presenceExpiresAt??e.presence_expires_at)??y(e.expiresAt??e.expires_at),connectable:u(e,"connectable")}),a={...n,...o,connectionStatus:i(e,"connectionStatus","connection_status")||"disconnected",settledReady:u(e,"settledReady","settled_ready")??false,readinessState:i(e,"readinessState","readiness_state")??void 0,readinessReason:i(e,"readinessReason","readiness_reason")??void 0,peerHealth:i(e,"peerHealth","peer_health")||"unknown",peerId:i(e,"peerId","peer_id"),scopes:k(e.scopes),connectionId:i(e,"connectionId","connection_id"),deviceIdHint:i(e,"deviceIdHint","device_id_hint"),transportStableId:s(e,"transportStableId","activeTransportStableId","active_transport_stable_id")??void 0,transportGeneration:s(e,"transportGeneration","transport_generation")??void 0,routeGeneration:s(e,"routeGeneration","route_generation")??void 0,activeTransport:g(e,"activeTransport","active_transport"),parallelTransport:g(e,"parallelTransport","parallel_transport")??null,availableTransports:w(e.availableTransports??e.available_transports),latencyMs:s(e,"latencyMs","latency_ms"),latencyByTransport:ne(e.latencyByTransport??e.latency_by_transport)};return Ke({device:a})}function Rt(t){let e=G(t);return Z({peerId:i(e,"peerId","peer_id")||"",deviceId:i(e,"deviceId","device_id"),deviceIdHint:i(e,"deviceIdHint","device_id_hint"),nodeId:i(e,"nodeId","node_id"),activeConnectionId:i(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:i(e,"status")||"disconnected",health:i(e,"health")||"unknown",settledReady:u(e,"settledReady","settled_ready")??false,readinessState:i(e,"readinessState","readiness_state")??void 0,transportStableId:s(e,"transportStableId","activeTransportStableId","active_transport_stable_id")??void 0,transportGeneration:s(e,"transportGeneration","transport_generation")??void 0,routeGeneration:s(e,"routeGeneration","route_generation")??void 0,activeTransport:g(e,"activeTransport","active_transport"),parallelTransport:g(e,"parallelTransport","parallel_transport")??null,replacementPending:u(e,"replacementPending","replacement_pending")??void 0,logicalSessionTerminal:u(e,"logicalSessionTerminal","logical_session_terminal")??false,lastTransitionAtMs:s(e,"lastTransitionAtMs","lastLifecycleTransitionAtMs","last_lifecycle_transition_at_ms")??void 0,readinessReason:i(e,"readinessReason","readiness_reason")??void 0,transitionCount:s(e,"transitionCount","transition_count")??void 0,connectTransitions:s(e,"connectTransitions","connectingTransitionCount","connecting_transition_count")??void 0,replacementCount:s(e,"replacementCount","replacement_count")??void 0,retireCount:s(e,"retireCount","retire_count")??void 0,lastDisconnectReason:i(e,"lastDisconnectReason","last_disconnect_reason")??void 0,lastReconnectReason:i(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:i(e,"error"),errorCode:i(e,"errorCode","error_code")??void 0,retryable:u(e,"retryable")??void 0,errorPlane:i(e,"errorPlane","error_plane")??void 0})}function _t(t){let e=S(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 wt(t){let e=S(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 Le(t){switch(t){case "connected":return "connected";case "connecting":return "connecting";case "failed":return "failed";default:return "closed"}}function At(t){let e=t.activeConnectionId||t.candidates[0]||null;if(!e)return null;let n=Le(t.status),r=n==="connected"?"connected":n==="connecting"?"connecting":"closed",o=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:r,protocolState:o,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 Fe(t){if(!t||typeof t!="object")return null;let e=t;return ["acceptedWriteObjects","acceptedWriteBytes","completedReceivedObjects","completedReceivedBytes"].every(r=>typeof e[r]=="number"&&Number.isSafeInteger(e[r])&&e[r]>=0)?Object.freeze({acceptedWriteObjects:e.acceptedWriteObjects,acceptedWriteBytes:e.acceptedWriteBytes,completedReceivedObjects:e.completedReceivedObjects,completedReceivedBytes:e.completedReceivedBytes}):null}function Ct(t){let e=S(t),n=i(e,"connectionId","connection_id");if(!n)return null;let r=i(e,"state")||"connecting",o=s(e,"createdAt","created_at")??s(e,"updatedAt","updated_at")??Date.now(),a=s(e,"updatedAt","updated_at")??o;return {connectionId:n,deviceId:i(e,"deviceId","device_id"),deviceIdHint:i(e,"deviceIdHint","device_id_hint"),remoteNodeId:i(e,"remoteNodeId","remote_node_id"),state:r,transportState:i(e,"transportState","transport_state")??(r==="connected"?"connected":r==="connecting"?"connecting":"closed"),protocolState:i(e,"protocolState","protocol_state")??(r==="connected"?"routable":r==="connecting"?"connecting":"closed"),routable:u(e,"routable")??false,scopes:k(e.scopes),logicalSessionTerminal:u(e,"logicalSessionTerminal","logical_session_terminal")??false,readinessState:i(e,"readinessState","readiness_state")??void 0,readinessReason:i(e,"readinessReason","readiness_reason")??void 0,transportGeneration:s(e,"transportGeneration","transport_generation")??void 0,routeGeneration:s(e,"routeGeneration","route_generation")??void 0,transportStableId:s(e,"transportStableId","activeTransportStableId","active_transport_stable_id")??void 0,activeTransport:g(e,"activeTransport","active_transport"),parallelTransport:g(e,"parallelTransport","parallel_transport")??null,latencyMs:s(e,"latencyMs","latency_ms")??null,carrier:g(e,"carrier")??null,metricsSampledAtMs:s(e,"metricsSampledAtMs","metrics_sampled_at_ms")??null,moqObjectQuantities:Fe(e.moqObjectQuantities??e.moq_object_quantities),replacementInProgress:u(e,"replacementInProgress","replacement_in_progress")??void 0,lastTransitionAtMs:s(e,"lastTransitionAtMs","lastLifecycleTransitionAtMs","last_lifecycle_transition_at_ms")??void 0,transitionCount:s(e,"transitionCount","transition_count")??void 0,connectTransitions:s(e,"connectTransitions","connectingTransitionCount","connecting_transition_count")??void 0,replacementCount:s(e,"replacementCount","replacement_count")??void 0,retireCount:s(e,"retireCount","retire_count")??void 0,lastDisconnectReason:i(e,"lastDisconnectReason","last_disconnect_reason")??void 0,lastReconnectReason:i(e,"lastReconnectReason","last_reconnect_reason")??void 0,error:i(e,"error")??void 0,createdAt:o,updatedAt:a}}function Pt(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}export{G as A,Tt as B,It as C,Ne as D,Ke as E,ht as F,Rt as G,_t as H,wt as I,At as J,Ct as K,Pt as L,U as a,ie as b,ae as c,Ue as d,qe as e,q as f,se as g,Ve as h,$e as i,Xe as j,z as k,tt as l,it as m,at as n,st as o,ct as p,lt as q,Me as r,Ee as s,ut as t,De as u,xe as v,X as w,ft as x,yt as y,gt as z};
@@ -1,2 +1,2 @@
1
- import {j,d as d$1,c}from'./chunk-QL4CJCV4.js';var E=/^[A-Za-z0-9_.:@-]+$/,P=/^[A-Za-z0-9_-]{43}$/,C=/^[A-Za-z0-9_.:@-]+$/,k=/^[A-Za-z0-9._-]+$/,x=120*6e4,A=new TextEncoder;function d(r,e,t=160){let n=r.trim();if(!n||n.length>t||!E.test(n))throw new TypeError(`[OpenRTC] ${e} is invalid.`);return n}function h(r,e,t=Number.MAX_SAFE_INTEGER){if(!Number.isSafeInteger(r)||r<1||r>t)throw new RangeError(`[OpenRTC] ${e} must be a positive safe integer.`);return r}function K(r){let e="";for(let t of r)e+=String.fromCharCode(t);return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,"")}async function g(r,e){let t=await r.publicJwk();if(t.kty!=="OKP"||t.crv!=="Ed25519"||typeof t.x!="string"||!P.test(t.x)||t.d!==void 0)throw new TypeError(`[OpenRTC] ${e} must return an Ed25519 public JWK.`);return {kty:"OKP",crv:"Ed25519",x:t.x}}async function y(r,e,t){let n=await r.sign(e);if(!(n instanceof Uint8Array)||n.byteLength!==64)throw new TypeError(`[OpenRTC] ${t} returned an invalid Ed25519 signature.`);return K(n)}function T(r){if(!/^pk_(?:live|test)_[A-Za-z0-9]+$/.test(r))throw new TypeError("[OpenRTC] apiKey is invalid.");return `app_${r.slice(-16)}`}function u(r){return r!==null&&typeof r=="object"&&!Array.isArray(r)?r:null}function v(r,e,t,n){if(typeof r!="string"||r.length<1||r.length>t||r!==r.trim()||n&&!n.test(r))throw new Error(`[OpenRTC] authority service grant ${e} is invalid.`);return r}function O(r){let e=v(r,"gatewayUrl",2048),t;try{t=new URL(e);}catch{throw new Error("[OpenRTC] authority service grant gatewayUrl is invalid.")}let n=t.protocol==="http:"&&["127.0.0.1","localhost","::1"].includes(t.hostname.toLowerCase());if(t.protocol!=="https:"&&!n||t.username||t.password||t.search||t.hash)throw new Error("[OpenRTC] authority service grant gatewayUrl is invalid.");return e}function N(r,e){let t=u(r),n=u(t?.avenue),i=u(t?.roomAuthority),a=u(i?.assignmentPublicKeyJwk),c=Date.now(),o=t?.expiresAtMs,s=t?.maxPeers;if(!t||t.protocolVersion!==2||t.architecture!=="authority"||n?.kind!=="room"||n.id!==e.roomId||i?.serviceId!==e.serviceId||i.generation!==e.generation||!Array.isArray(i.shardIds)||i.shardIds.length!==e.shardIds.length||i.shardIds.some((m,l)=>m!==e.shardIds[l])||a?.kty!=="OKP"||a.crv!=="Ed25519"||a.x!==e.assignmentPublicKeyX||!Number.isSafeInteger(o)||o<=c||o>c+x||!Number.isSafeInteger(s)||s<1||s>e.maxPeers)throw new Error("[OpenRTC] authority service grant response is inconsistent.");return {protocolVersion:2,gatewayUrl:O(t.gatewayUrl),routeKey:v(t.routeKey,"routeKey",256,C),token:v(t.token,"token",24e3,k),expiresAtMs:o,avenue:{kind:"room",id:e.roomId},maxPeers:s,architecture:"authority",roomAuthority:{serviceId:e.serviceId,generation:e.generation,shardIds:[...e.shardIds],assignmentPublicKeyJwk:{kty:"OKP",crv:"Ed25519",x:e.assignmentPublicKeyX}}}}var p=class{constructor(e){if(this.apiKey=e.apiKey,this.applicationTag=T(e.apiKey),typeof e.grantIssuer!="function")throw new TypeError("[OpenRTC] ServiceNode requires a browser-safe grantIssuer.");if(this.grantIssuer=e.grantIssuer,this.serviceId=d(e.serviceId,"serviceId",80),this.generation=h(e.generation,"generation"),this.shardIds=[...new Set(e.shardIds.map(t=>d(t,"shardId",80)))].sort(),this.shardIds.length<1||this.shardIds.length>64||this.shardIds.length!==e.shardIds.length)throw new RangeError("[OpenRTC] shardIds must contain 1..64 unique identifiers.");this.deviceId=d(e.deviceId,"deviceId"),this.deviceSigner=e.deviceSigner,this.assignmentSigner=e.assignmentSigner;}async requestGrant(e){let t=d(e.roomId,"roomId"),n=d(e.runtimeInstanceId,"runtimeInstanceId");if(!P.test(e.ticketFingerprint))throw new TypeError("[OpenRTC] ticketFingerprint is invalid.");e.maxPeers!==void 0&&h(e.maxPeers,"maxPeers",50);let i=await g(this.assignmentSigner,"assignmentSigner.publicJwk()"),a=await g(this.deviceSigner,"deviceSigner.publicJwk()"),c=crypto.randomUUID().replace(/-/g,""),o=Math.floor(Date.now()/1e3),s=["openrtc:v2:authority-service-grant",this.applicationTag,t,this.serviceId,String(this.generation),this.shardIds.join(","),i.x,n,c,o].join(":"),m={avenue:{kind:"room",id:t},serviceId:this.serviceId,generation:this.generation,shardIds:this.shardIds,assignmentPublicKeyJwk:i,deviceId:this.deviceId,runtimeInstanceId:n,ticketFingerprint:e.ticketFingerprint,deviceProof:{publicKeyJwk:a,nonce:c,issuedAt:o,signature:await y(this.deviceSigner,A.encode(s),"deviceSigner.sign()")},...e.maxPeers===void 0?{}:{maxPeers:e.maxPeers},...e.refreshGrant?{refreshGrant:e.refreshGrant}:{},features:e.features??{}},l=`authority_${crypto.randomUUID().replace(/-/g,"")}`,R=await this.grantIssuer({apiKey:this.apiKey,idempotencyKey:l,body:m});return N(R,{roomId:t,serviceId:this.serviceId,generation:this.generation,shardIds:this.shardIds,assignmentPublicKeyX:i.x,maxPeers:e.maxPeers??50})}async devicePublicKey(){return g(this.deviceSigner,"deviceSigner.publicJwk()")}async assignmentPublicKey(){return g(this.assignmentSigner,"assignmentSigner.publicJwk()")}async signDeviceBytes(e){return y(this.deviceSigner,e,"deviceSigner.sign()")}async signAssignment(e){let t=e.ttlMs??6e4;h(t,"ttlMs",2*6e4);let n=d(e.shardId,"shardId",80);if(!this.shardIds.includes(n))throw new RangeError("[OpenRTC] assignment shard is not owned by this service.");let i=e.priorityDeviceIds??[],a=e.relevantEntityIds??[];if(i.length>8||a.length>32)throw new RangeError("[OpenRTC] assignment exceeds the 8-edge or 32-entity bound.");let c=Date.now(),o={policyVersion:"room-authority-assignment-v1",serviceId:this.serviceId,generation:this.generation,revision:h(e.revision,"revision"),subjectDeviceId:d(e.subjectDeviceId,"subjectDeviceId"),shardId:n,priorityDeviceIds:i.map(s=>d(s,"priorityDeviceId")),relevantEntityIds:a.map(s=>d(s,"relevantEntityId")),issuedAtMs:c,expiresAtMs:c+t};if(new Set(o.priorityDeviceIds).size!==o.priorityDeviceIds.length||new Set(o.relevantEntityIds).size!==o.relevantEntityIds.length)throw new RangeError("[OpenRTC] assignment identifiers must be unique.");return {assignment:o,signature:await y(this.assignmentSigner,A.encode(JSON.stringify(o)),"assignmentSigner.sign()")}}},I=class{constructor(e,t,n){this.room=e;this.authority=t;this.onClosed=n;this.releaseRuntimeAlias=d$1(this,e);}get kind(){return this.room.kind}get id(){return this.room.id}get peers(){return this.room.peers}get channels(){return this.room.channels}get diagnostics(){return this.room.diagnostics}get closed(){return this.room.closed}get membership(){return this.room.membership}get members(){return this.room.members}state(e){return this.room.state(e)}channel(e){return this.room.channel(e)}onConnection(e){return this.room.onConnection(e)}architecture(){return this.room.architecture()}onArchitectureChanged(e){return this.room.onArchitectureChanged(e)}authorityAssignment(){return this.room.authorityAssignment()}onAuthorityAssignmentChanged(e){return this.room.onAuthorityAssignmentChanged(e)}leave(){return this.retire(()=>this.room.leave())}close(){return this.retire(()=>this.room.close())}async publishAssignment(e){let t=await this.authority.signAssignment(e);return await c(this.room).advanced.runtime.publishAuthorityAssignment(t),t.assignment}retire(e){return this.retirement??(this.retirement=e().finally(()=>{this.releaseRuntimeAlias(),this.onClosed();}))}},S=class{constructor(e){this.options=e;this.rooms=new Map;this.connectionListeners=new Set;this.connectionCleanups=new Map;this.closed=false;if("secretKey"in e)throw new TypeError("[OpenRTC] ServiceNode never accepts secretKey; delegate short-lived grants.");this.authority=new p(e);}listen(e){if(this.closed)throw new Error("[OpenRTC] ServiceNode is closed.");let t=d(e,"roomId"),n=this.rooms.get(t);if(n)return n.promise;let i={};return i.promise=this.openRoom(t,()=>this.evictRoom(t,i)).catch(a=>{throw this.evictRoom(t,i),a}),this.rooms.set(t,i),i.promise}onConnection(e){if(this.connectionListeners.add(e),this.connectionListeners.size===1)for(let[t,n]of this.rooms)n.promise.then(i=>this.attachConnectionListener(t,i),()=>{});return ()=>{if(this.connectionListeners.delete(e),this.connectionListeners.size===0){for(let t of this.connectionCleanups.values())t();this.connectionCleanups.clear();}}}async close(){if(this.closed)return;this.closed=true;for(let t of this.connectionCleanups.values())t();this.connectionCleanups.clear();let e=await Promise.allSettled([...this.rooms.values()].map(t=>t.promise));await Promise.all(e.flatMap(t=>t.status==="fulfilled"?[t.value.close()]:[])),this.rooms.clear(),this.connectionListeners.clear();}async openRoom(e,t){let n=await this.options.client.devices.localId();if(n!==this.options.deviceId)throw new Error("[OpenRTC] ServiceNode deviceId must match the client installation.");let[i,a]=await Promise.all([this.authority.devicePublicKey(),this.authority.assignmentPublicKey()]),c=await j(this.options.client,{roomId:e,serviceId:this.options.serviceId,generation:this.options.generation,shardIds:this.options.shardIds,deviceId:n,maxPeers:this.options.maxPeers,irohRelay:this.options.irohRelay!==false,devicePublicKeyX:i.x,assignmentPublicKeyX:a.x,deviceSign:s=>this.authority.signDeviceBytes(s),grantProvider:async s=>{if(s.avenue.kind!=="room"||s.avenue.id!==e)throw new Error("[OpenRTC] ServiceNode grant request escaped its room.");if(s.deviceId!==n)throw new Error("[OpenRTC] ServiceNode grant request escaped its device.");return this.authority.requestGrant({roomId:e,runtimeInstanceId:s.runtimeInstanceId,ticketFingerprint:s.ticketFingerprint,maxPeers:this.options.maxPeers,refreshGrant:s.refreshGrant,features:{irohRelay:this.options.irohRelay!==false}})}}),o=new I(c,this.authority,t);return this.attachConnectionListener(e,o),o}evictRoom(e,t){this.rooms.get(e)===t&&(this.rooms.delete(e),this.connectionCleanups.get(e)?.(),this.connectionCleanups.delete(e));}attachConnectionListener(e,t){this.closed||this.connectionListeners.size===0||this.connectionCleanups.has(e)||this.connectionCleanups.set(e,t.onConnection(n=>{for(let i of this.connectionListeners)i({room:t,connection:n});}));}};
1
+ import {j,d as d$1,c}from'./chunk-5LNRJE6L.js';var E=/^[A-Za-z0-9_.:@-]+$/,P=/^[A-Za-z0-9_-]{43}$/,C=/^[A-Za-z0-9_.:@-]+$/,k=/^[A-Za-z0-9._-]+$/,x=120*6e4,A=new TextEncoder;function d(r,e,t=160){let n=r.trim();if(!n||n.length>t||!E.test(n))throw new TypeError(`[OpenRTC] ${e} is invalid.`);return n}function h(r,e,t=Number.MAX_SAFE_INTEGER){if(!Number.isSafeInteger(r)||r<1||r>t)throw new RangeError(`[OpenRTC] ${e} must be a positive safe integer.`);return r}function K(r){let e="";for(let t of r)e+=String.fromCharCode(t);return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,"")}async function g(r,e){let t=await r.publicJwk();if(t.kty!=="OKP"||t.crv!=="Ed25519"||typeof t.x!="string"||!P.test(t.x)||t.d!==void 0)throw new TypeError(`[OpenRTC] ${e} must return an Ed25519 public JWK.`);return {kty:"OKP",crv:"Ed25519",x:t.x}}async function y(r,e,t){let n=await r.sign(e);if(!(n instanceof Uint8Array)||n.byteLength!==64)throw new TypeError(`[OpenRTC] ${t} returned an invalid Ed25519 signature.`);return K(n)}function T(r){if(!/^pk_(?:live|test)_[A-Za-z0-9]+$/.test(r))throw new TypeError("[OpenRTC] apiKey is invalid.");return `app_${r.slice(-16)}`}function u(r){return r!==null&&typeof r=="object"&&!Array.isArray(r)?r:null}function v(r,e,t,n){if(typeof r!="string"||r.length<1||r.length>t||r!==r.trim()||n&&!n.test(r))throw new Error(`[OpenRTC] authority service grant ${e} is invalid.`);return r}function O(r){let e=v(r,"gatewayUrl",2048),t;try{t=new URL(e);}catch{throw new Error("[OpenRTC] authority service grant gatewayUrl is invalid.")}let n=t.protocol==="http:"&&["127.0.0.1","localhost","::1"].includes(t.hostname.toLowerCase());if(t.protocol!=="https:"&&!n||t.username||t.password||t.search||t.hash)throw new Error("[OpenRTC] authority service grant gatewayUrl is invalid.");return e}function N(r,e){let t=u(r),n=u(t?.avenue),i=u(t?.roomAuthority),a=u(i?.assignmentPublicKeyJwk),c=Date.now(),o=t?.expiresAtMs,s=t?.maxPeers;if(!t||t.protocolVersion!==2||t.architecture!=="authority"||n?.kind!=="room"||n.id!==e.roomId||i?.serviceId!==e.serviceId||i.generation!==e.generation||!Array.isArray(i.shardIds)||i.shardIds.length!==e.shardIds.length||i.shardIds.some((m,l)=>m!==e.shardIds[l])||a?.kty!=="OKP"||a.crv!=="Ed25519"||a.x!==e.assignmentPublicKeyX||!Number.isSafeInteger(o)||o<=c||o>c+x||!Number.isSafeInteger(s)||s<1||s>e.maxPeers)throw new Error("[OpenRTC] authority service grant response is inconsistent.");return {protocolVersion:2,gatewayUrl:O(t.gatewayUrl),routeKey:v(t.routeKey,"routeKey",256,C),token:v(t.token,"token",24e3,k),expiresAtMs:o,avenue:{kind:"room",id:e.roomId},maxPeers:s,architecture:"authority",roomAuthority:{serviceId:e.serviceId,generation:e.generation,shardIds:[...e.shardIds],assignmentPublicKeyJwk:{kty:"OKP",crv:"Ed25519",x:e.assignmentPublicKeyX}}}}var p=class{constructor(e){if(this.apiKey=e.apiKey,this.applicationTag=T(e.apiKey),typeof e.grantIssuer!="function")throw new TypeError("[OpenRTC] ServiceNode requires a browser-safe grantIssuer.");if(this.grantIssuer=e.grantIssuer,this.serviceId=d(e.serviceId,"serviceId",80),this.generation=h(e.generation,"generation"),this.shardIds=[...new Set(e.shardIds.map(t=>d(t,"shardId",80)))].sort(),this.shardIds.length<1||this.shardIds.length>64||this.shardIds.length!==e.shardIds.length)throw new RangeError("[OpenRTC] shardIds must contain 1..64 unique identifiers.");this.deviceId=d(e.deviceId,"deviceId"),this.deviceSigner=e.deviceSigner,this.assignmentSigner=e.assignmentSigner;}async requestGrant(e){let t=d(e.roomId,"roomId"),n=d(e.runtimeInstanceId,"runtimeInstanceId");if(!P.test(e.ticketFingerprint))throw new TypeError("[OpenRTC] ticketFingerprint is invalid.");e.maxPeers!==void 0&&h(e.maxPeers,"maxPeers",50);let i=await g(this.assignmentSigner,"assignmentSigner.publicJwk()"),a=await g(this.deviceSigner,"deviceSigner.publicJwk()"),c=crypto.randomUUID().replace(/-/g,""),o=Math.floor(Date.now()/1e3),s=["openrtc:v2:authority-service-grant",this.applicationTag,t,this.serviceId,String(this.generation),this.shardIds.join(","),i.x,n,c,o].join(":"),m={avenue:{kind:"room",id:t},serviceId:this.serviceId,generation:this.generation,shardIds:this.shardIds,assignmentPublicKeyJwk:i,deviceId:this.deviceId,runtimeInstanceId:n,ticketFingerprint:e.ticketFingerprint,deviceProof:{publicKeyJwk:a,nonce:c,issuedAt:o,signature:await y(this.deviceSigner,A.encode(s),"deviceSigner.sign()")},...e.maxPeers===void 0?{}:{maxPeers:e.maxPeers},...e.refreshGrant?{refreshGrant:e.refreshGrant}:{},features:e.features??{}},l=`authority_${crypto.randomUUID().replace(/-/g,"")}`,R=await this.grantIssuer({apiKey:this.apiKey,idempotencyKey:l,body:m});return N(R,{roomId:t,serviceId:this.serviceId,generation:this.generation,shardIds:this.shardIds,assignmentPublicKeyX:i.x,maxPeers:e.maxPeers??50})}async devicePublicKey(){return g(this.deviceSigner,"deviceSigner.publicJwk()")}async assignmentPublicKey(){return g(this.assignmentSigner,"assignmentSigner.publicJwk()")}async signDeviceBytes(e){return y(this.deviceSigner,e,"deviceSigner.sign()")}async signAssignment(e){let t=e.ttlMs??6e4;h(t,"ttlMs",2*6e4);let n=d(e.shardId,"shardId",80);if(!this.shardIds.includes(n))throw new RangeError("[OpenRTC] assignment shard is not owned by this service.");let i=e.priorityDeviceIds??[],a=e.relevantEntityIds??[];if(i.length>8||a.length>32)throw new RangeError("[OpenRTC] assignment exceeds the 8-edge or 32-entity bound.");let c=Date.now(),o={policyVersion:"room-authority-assignment-v1",serviceId:this.serviceId,generation:this.generation,revision:h(e.revision,"revision"),subjectDeviceId:d(e.subjectDeviceId,"subjectDeviceId"),shardId:n,priorityDeviceIds:i.map(s=>d(s,"priorityDeviceId")),relevantEntityIds:a.map(s=>d(s,"relevantEntityId")),issuedAtMs:c,expiresAtMs:c+t};if(new Set(o.priorityDeviceIds).size!==o.priorityDeviceIds.length||new Set(o.relevantEntityIds).size!==o.relevantEntityIds.length)throw new RangeError("[OpenRTC] assignment identifiers must be unique.");return {assignment:o,signature:await y(this.assignmentSigner,A.encode(JSON.stringify(o)),"assignmentSigner.sign()")}}},I=class{constructor(e,t,n){this.room=e;this.authority=t;this.onClosed=n;this.releaseRuntimeAlias=d$1(this,e);}get kind(){return this.room.kind}get id(){return this.room.id}get peers(){return this.room.peers}get channels(){return this.room.channels}get diagnostics(){return this.room.diagnostics}get closed(){return this.room.closed}get membership(){return this.room.membership}get members(){return this.room.members}state(e){return this.room.state(e)}channel(e){return this.room.channel(e)}onConnection(e){return this.room.onConnection(e)}architecture(){return this.room.architecture()}onArchitectureChanged(e){return this.room.onArchitectureChanged(e)}authorityAssignment(){return this.room.authorityAssignment()}onAuthorityAssignmentChanged(e){return this.room.onAuthorityAssignmentChanged(e)}leave(){return this.retire(()=>this.room.leave())}close(){return this.retire(()=>this.room.close())}async publishAssignment(e){let t=await this.authority.signAssignment(e);return await c(this.room).advanced.runtime.publishAuthorityAssignment(t),t.assignment}retire(e){return this.retirement??(this.retirement=e().finally(()=>{this.releaseRuntimeAlias(),this.onClosed();}))}},S=class{constructor(e){this.options=e;this.rooms=new Map;this.connectionListeners=new Set;this.connectionCleanups=new Map;this.closed=false;if("secretKey"in e)throw new TypeError("[OpenRTC] ServiceNode never accepts secretKey; delegate short-lived grants.");this.authority=new p(e);}listen(e){if(this.closed)throw new Error("[OpenRTC] ServiceNode is closed.");let t=d(e,"roomId"),n=this.rooms.get(t);if(n)return n.promise;let i={};return i.promise=this.openRoom(t,()=>this.evictRoom(t,i)).catch(a=>{throw this.evictRoom(t,i),a}),this.rooms.set(t,i),i.promise}onConnection(e){if(this.connectionListeners.add(e),this.connectionListeners.size===1)for(let[t,n]of this.rooms)n.promise.then(i=>this.attachConnectionListener(t,i),()=>{});return ()=>{if(this.connectionListeners.delete(e),this.connectionListeners.size===0){for(let t of this.connectionCleanups.values())t();this.connectionCleanups.clear();}}}async close(){if(this.closed)return;this.closed=true;for(let t of this.connectionCleanups.values())t();this.connectionCleanups.clear();let e=await Promise.allSettled([...this.rooms.values()].map(t=>t.promise));await Promise.all(e.flatMap(t=>t.status==="fulfilled"?[t.value.close()]:[])),this.rooms.clear(),this.connectionListeners.clear();}async openRoom(e,t){let n=await this.options.client.devices.localId();if(n!==this.options.deviceId)throw new Error("[OpenRTC] ServiceNode deviceId must match the client installation.");let[i,a]=await Promise.all([this.authority.devicePublicKey(),this.authority.assignmentPublicKey()]),c=await j(this.options.client,{roomId:e,serviceId:this.options.serviceId,generation:this.options.generation,shardIds:this.options.shardIds,deviceId:n,maxPeers:this.options.maxPeers,irohRelay:this.options.irohRelay!==false,devicePublicKeyX:i.x,assignmentPublicKeyX:a.x,deviceSign:s=>this.authority.signDeviceBytes(s),grantProvider:async s=>{if(s.avenue.kind!=="room"||s.avenue.id!==e)throw new Error("[OpenRTC] ServiceNode grant request escaped its room.");if(s.deviceId!==n)throw new Error("[OpenRTC] ServiceNode grant request escaped its device.");return this.authority.requestGrant({roomId:e,runtimeInstanceId:s.runtimeInstanceId,ticketFingerprint:s.ticketFingerprint,maxPeers:this.options.maxPeers,refreshGrant:s.refreshGrant,features:{irohRelay:this.options.irohRelay!==false}})}}),o=new I(c,this.authority,t);return this.attachConnectionListener(e,o),o}evictRoom(e,t){this.rooms.get(e)===t&&(this.rooms.delete(e),this.connectionCleanups.get(e)?.(),this.connectionCleanups.delete(e));}attachConnectionListener(e,t){this.closed||this.connectionListeners.size===0||this.connectionCleanups.has(e)||this.connectionCleanups.set(e,t.onConnection(n=>{for(let i of this.connectionListeners)i({room:t,connection:n});}));}};
2
2
  export{p as a,S as b};
@@ -1 +1 @@
1
- var w="3.0.3";function R(t,o){if(t)try{Promise.resolve(t(o)).catch(()=>{});}catch{}}var y=new Set(["transport-healthy","missing-active-transport","native-main-route-pending","session-admission-pending","application-crypto-key-pending","application-crypto-confirmation-pending","bounded-health-confirmation-pending","authoritative-device-binding-pending","device-offline","manual-disconnect","waiting-for-transport","transport-attached-awaiting-readiness-confirmation","transport-connected-health-check-pending","readiness-confirmation-timed-out","transport-closed","connection-failed"]),_=new Set(["user-device","persistent","trusted-device","ticket","room","space","share","drive-grant"]),O=new Set(["connected","connecting","disconnected","failed","closed"]),P=new Set(["unknown","pending","admitted","rejected","expired"]),x=new Set(["iroh","iroh-quic","iroh-lan","iroh-relay","webrtc","moq","ble"]),g=t=>Number.isSafeInteger(t)&&t>=0?t:null;function k(t,o={}){let a=o.maxEvents??256;if(!Number.isInteger(a)||a<1||a>1024)throw new RangeError("Diagnostic maxEvents must be an integer between 1 and 1024");let h=Date.now(),S=performance.now(),r=new Map,c=new Map,d=[],D=0,f=0,p=false,v=false,b=(s,n)=>{let e=Object.freeze({sequence:++D,timestampMs:Date.now(),elapsedMs:performance.now()-S,level:n.hasError||n.state==="failed"?"warn":n.ready?"info":"debug",name:s,peer:Object.freeze({...n,scopeKinds:Object.freeze([...n.scopeKinds])})});d.length===a&&(d.shift(),f++),d.push(e),R(o.logger,e);},E=t(s=>{if(p)return;let n=new Map;for(let e of s){let i=r.get(e.peerId);if(!i){if(r.size===64){v=true;continue}i=`peer-${r.size+1}`,r.set(e.peerId,i);}let m=e.readinessReason==="manual disconnect"?"manual-disconnect":e.readinessReason,l={peerRef:i,state:O.has(e.status)?e.status:"unknown",admission:e.admissionState&&P.has(e.admissionState)?e.admissionState:"unknown",ready:e.settledReady===true,readinessCode:m&&y.has(m)?m:"unclassified",scopeKinds:[...new Set(e.scopes.map(u=>u.split(":",1)[0]).map(u=>_.has(u)?u:"custom"))].sort(),transportGeneration:g(e.transportGeneration),routeGeneration:g(e.routeGeneration),transportStableId:g(e.transportStableId??void 0),transport:e.activeTransport&&x.has(e.activeTransport)?e.activeTransport:"unknown",hasError:!!e.error};n.set(i,l),JSON.stringify(c.get(i))!==JSON.stringify(l)&&b("peer.changed",l);}for(let[e,i]of c)n.has(e)||b("peer.removed",{...i,ready:false,state:"disconnected"});c=n;});return {snapshot:()=>({schemaVersion:1,sdkVersion:w,startedAtMs:h,stopped:p,droppedEvents:f,peerLimitReached:v,events:d.map(s=>({...s,peer:{...s.peer,scopeKinds:[...s.peer.scopeKinds]}}))}),stop:()=>{p||(p=true,E(),r.clear(),c.clear());}}}export{w as a,R as b,k as c};
1
+ var w="3.1.0";function R(t,o){if(t)try{Promise.resolve(t(o)).catch(()=>{});}catch{}}var y=new Set(["transport-healthy","missing-active-transport","native-main-route-pending","session-admission-pending","application-crypto-key-pending","application-crypto-confirmation-pending","bounded-health-confirmation-pending","authoritative-device-binding-pending","device-offline","manual-disconnect","waiting-for-transport","transport-attached-awaiting-readiness-confirmation","transport-connected-health-check-pending","readiness-confirmation-timed-out","transport-closed","connection-failed"]),_=new Set(["user-device","persistent","trusted-device","ticket","room","space","share","drive-grant"]),O=new Set(["connected","connecting","disconnected","failed","closed"]),P=new Set(["unknown","pending","admitted","rejected","expired"]),x=new Set(["iroh","iroh-quic","iroh-lan","iroh-relay","webrtc","moq","ble"]),g=t=>Number.isSafeInteger(t)&&t>=0?t:null;function k(t,o={}){let a=o.maxEvents??256;if(!Number.isInteger(a)||a<1||a>1024)throw new RangeError("Diagnostic maxEvents must be an integer between 1 and 1024");let h=Date.now(),S=performance.now(),r=new Map,c=new Map,d=[],D=0,f=0,p=false,v=false,b=(s,n)=>{let e=Object.freeze({sequence:++D,timestampMs:Date.now(),elapsedMs:performance.now()-S,level:n.hasError||n.state==="failed"?"warn":n.ready?"info":"debug",name:s,peer:Object.freeze({...n,scopeKinds:Object.freeze([...n.scopeKinds])})});d.length===a&&(d.shift(),f++),d.push(e),R(o.logger,e);},E=t(s=>{if(p)return;let n=new Map;for(let e of s){let i=r.get(e.peerId);if(!i){if(r.size===64){v=true;continue}i=`peer-${r.size+1}`,r.set(e.peerId,i);}let m=e.readinessReason==="manual disconnect"?"manual-disconnect":e.readinessReason,l={peerRef:i,state:O.has(e.status)?e.status:"unknown",admission:e.admissionState&&P.has(e.admissionState)?e.admissionState:"unknown",ready:e.settledReady===true,readinessCode:m&&y.has(m)?m:"unclassified",scopeKinds:[...new Set(e.scopes.map(u=>u.split(":",1)[0]).map(u=>_.has(u)?u:"custom"))].sort(),transportGeneration:g(e.transportGeneration),routeGeneration:g(e.routeGeneration),transportStableId:g(e.transportStableId??void 0),transport:e.activeTransport&&x.has(e.activeTransport)?e.activeTransport:"unknown",hasError:!!e.error};n.set(i,l),JSON.stringify(c.get(i))!==JSON.stringify(l)&&b("peer.changed",l);}for(let[e,i]of c)n.has(e)||b("peer.removed",{...i,ready:false,state:"disconnected"});c=n;});return {snapshot:()=>({schemaVersion:1,sdkVersion:w,startedAtMs:h,stopped:p,droppedEvents:f,peerLimitReached:v,events:d.map(s=>({...s,peer:{...s.peer,scopeKinds:[...s.peer.scopeKinds]}}))}),stop:()=>{p||(p=true,E(),r.clear(),c.clear());}}}export{w as a,R as b,k as c};