openrtc 3.0.3 → 3.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/BrowserCoordinationGatewaySignaling-GOLSTJMA.js +1 -0
- package/dist/WasmBridge-3HYLCY5Y.js +1 -0
- package/dist/{chunk-TYZS5LXQ.js → chunk-2AAZFBRZ.js} +1 -1
- package/dist/{chunk-AYQSDKSK.js → chunk-AZ74VBU2.js} +1 -1
- package/dist/{chunk-TFOFTLTV.js → chunk-CQHLD52E.js} +1 -1
- package/dist/chunk-FNCEVW7G.js +1 -0
- package/dist/chunk-FPJAUAEU.js +2 -0
- package/dist/{chunk-PW2WEI6L.js → chunk-IVNXIG7J.js} +1 -1
- package/dist/chunk-KN7DF3NH.js +1 -0
- package/dist/chunk-LB27VQRL.js +1 -0
- package/dist/chunk-LCJQ7RSR.js +1 -0
- package/dist/chunk-M4KL5XZU.js +2 -0
- package/dist/{chunk-HL3TV2QA.js → chunk-PA4WT4QM.js} +1 -1
- package/dist/{chunk-XTMFYAIJ.js → chunk-TSMMRR5V.js} +1 -1
- package/dist/chunk-WTOA6B2A.js +2 -0
- package/dist/coreClient.js +1 -1
- package/dist/{deviceHandle-YV5LJ5A5.js → deviceHandle-URNIFFXC.js} +1 -1
- package/dist/external-broadcast.d.ts +1 -1
- package/dist/external-broadcast.js +1 -1
- package/dist/index.d.ts +4 -4
- package/dist/index.js +1 -1
- package/dist/ipcFactory-6XD3J2UU.js +1 -0
- package/dist/native.d.ts +2 -2
- package/dist/native.js +1 -1
- package/dist/node.d.ts +2 -2
- package/dist/node.js +2 -2
- package/dist/openrtc_bg.wasm +0 -0
- package/dist/{room-ELXNZIYX.js → room-7ZEAAY7Z.js} +1 -1
- package/dist/runtime/WasmRuntimeAdapter.js +1 -1
- package/dist/runtime/factories.js +1 -1
- package/dist/runtime/index.d.ts +1 -1
- package/dist/runtime/index.js +1 -1
- package/dist/server-browser.d.ts +1 -1
- package/dist/server.d.ts +1 -1
- package/dist/server.js +1 -1
- package/dist/service-node.d.ts +1 -1
- package/dist/service-node.js +1 -1
- package/dist/testing/native.d.ts +1 -1
- package/dist/testing/native.js +1 -1
- package/dist/testing.d.ts +1 -1
- package/dist/testing.js +1 -1
- package/dist/transport/index.js +1 -1
- package/dist/{types-YGlXXpQA.d.ts → types-Cruu-MsF.d.ts} +43 -1
- package/native/darwin-arm64/openrtc-node-host +0 -0
- package/native/darwin-arm64/openrtc-node-host.manifest.json +4 -4
- package/native/darwin-x64/openrtc-node-host +0 -0
- package/native/darwin-x64/openrtc-node-host.manifest.json +4 -4
- package/native/linux-x64/openrtc-node-host +0 -0
- package/native/linux-x64/openrtc-node-host.manifest.json +4 -4
- package/package.json +1 -1
- package/dist/WasmBridge-L76OAD5U.js +0 -1
- package/dist/chunk-K32BROMJ.js +0 -2
- package/dist/chunk-L4HWDDXL.js +0 -2
- package/dist/chunk-OT7IPLZE.js +0 -1
- package/dist/chunk-QL4CJCV4.js +0 -1
- package/dist/chunk-UCNK7KB6.js +0 -2
- package/dist/ipcFactory-4LCCR23Q.js +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export{a as BrowserCoordinationGatewaySignaling}from'./chunk-FPJAUAEU.js';import'./chunk-LB27VQRL.js';import'./chunk-TPF643LU.js';import'./chunk-ZA44REGI.js';import'./chunk-L7N4T2PX.js';import'./chunk-72MN7BNQ.js';
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export{b as WasmBridge,a as loadBrowserWasmRuntimeModule}from'./chunk-PA4WT4QM.js';import'./chunk-AYHD4X2R.js';import'./chunk-LCJQ7RSR.js';import'./chunk-FPJAUAEU.js';import'./chunk-WTOA6B2A.js';import'./chunk-FNCEVW7G.js';import'./chunk-LB27VQRL.js';import'./chunk-OWKAJPOI.js';import'./chunk-TPF643LU.js';import'./chunk-L2ZZXECX.js';import'./chunk-CCCYE3XN.js';import'./chunk-JPBW67B3.js';import'./chunk-ZA44REGI.js';import'./chunk-L7N4T2PX.js';import'./chunk-72MN7BNQ.js';import'./chunk-2GX6GB6L.js';
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import {c}from'./chunk-
|
|
1
|
+
import {c}from'./chunk-LB27VQRL.js';import {b,a}from'./chunk-OWKAJPOI.js';import {xchacha20poly1305}from'@noble/ciphers/chacha.js';import {x25519}from'@noble/curves/ed25519.js';import {hkdf}from'@noble/hashes/hkdf.js';import {sha256}from'@noble/hashes/sha2.js';var m=new Uint8Array([79,82,84,67,69,49]),P=2,h=8,A=24,O=32,q=3,N=16*1024*1024,Y=4096;function k(e,t){if(e.byteLength<t.byteLength)return false;let r=0;for(let o=0;o<t.byteLength;o+=1)r|=e[o]^t[o];return r===0}function F(e){let t=new Uint8Array(e),r=globalThis.crypto;if(!r||typeof r.getRandomValues!="function")throw new Error("[OpenRTC] application payload crypto requires crypto.getRandomValues");return r.getRandomValues(t),t}function M(e,t){let r="";for(let o of t)r+=o.toString(16).padStart(2,"0");return `${e}:${r}`}function _(e){if(!k(e,m))return null;let t=e[m.byteLength];return t===P?t:null}function D(e){return _(e)===P&&e.byteLength>m.byteLength+1+h+A}function Z(e,t={}){if(!(e instanceof Uint8Array)||e.byteLength!==O)throw new Error(`[OpenRTC] application payload crypto key must be ${O} bytes`);let r=new Uint8Array(e),o=t.requireEncrypted??true,i=t.randomBytes??F,u=t.replayProtection??true,l=0,a=new Set,b=[];return {requireEncrypted:o,protectPayload(d,n){let c=i(A);if(!(c instanceof Uint8Array)||c.byteLength!==A)throw new Error(`[OpenRTC] application payload crypto nonce must be ${A} bytes`);let f=new Uint8Array(1+n.byteLength);f[0]=d,f.set(n,1);let p=xchacha20poly1305(r,c).encrypt(f);if(!u)throw new Error("[OpenRTC] ORTCE1 v1 envelopes are not supported; replay protection is required");let y=new Uint8Array(m.byteLength+1+h+c.byteLength+p.byteLength),s=0;y.set(m,s),s+=m.byteLength,y[s]=P,s+=1;let w=l;return l+=1,new DataView(y.buffer,y.byteOffset+s,h).setBigUint64(0,BigInt(w),false),s+=h,y.set(c,s),s+=c.byteLength,y.set(p,s),y},openPayload(d,n){if(!D(n))return o?null:n;if(_(n)!==P)return null;let f=m.byteLength+1,p=Number(new DataView(n.buffer,n.byteOffset+f,h).getBigUint64(0,false));if(!Number.isFinite(p))return null;let y=f+h,s=y+A,w=n.slice(y,s),g=u?M(p,w):null;if(g&&a.has(g))return null;let I=n.slice(s),E;try{E=xchacha20poly1305(r,w).decrypt(I);}catch{return null}if(E.byteLength<1||E[0]!==d)return null;if(g)for(a.add(g),b.push(g);b.length>Y;){let R=b.shift();R&&a.delete(R);}return E.slice(1)}}}function V(e){let t=new Uint8Array(4+e.byteLength);return new DataView(t.buffer,t.byteOffset,t.byteLength).setUint32(0,e.byteLength,false),t.set(e,4),t}function ee(e,t={}){let r=t.typeId??q,o=t.maxFrameBytes??N;if(!Number.isInteger(r)||r<0||r>255)throw new Error("[OpenRTC] raw application crypto stream typeId must be an integer from 0 to 255");if(!Number.isInteger(o)||o<=0)throw new Error("[OpenRTC] raw application crypto maxFrameBytes must be a positive integer");let i=n=>e.protectPayload(r,n),u=n=>e.openPayload(r,n),l=()=>new TransformStream({transform(n,c){c.enqueue(V(i(new Uint8Array(n))));}}),a=()=>{let n=new Uint8Array(0);return new TransformStream({transform(c$1,f){for(n=c([n,new Uint8Array(c$1)]);n.byteLength>=4;){let p=new DataView(n.buffer,n.byteOffset,n.byteLength).getUint32(0,false);if(p===0||p>o)throw new Error("[OpenRTC] invalid encrypted raw stream frame length");if(n.byteLength<4+p)return;let y=n.slice(4,4+p);n=n.slice(4+p);let s=u(y);if(!s)throw new Error("[OpenRTC] encrypted raw stream frame failed authentication");f.enqueue(s);}},flush(){if(n.byteLength!==0)throw new Error("[OpenRTC] encrypted raw stream ended mid-frame")}})},b=n=>n.pipeThrough(a()),d=n=>{let c=l();return c.readable.pipeTo(n).catch(()=>{}),c.writable};return {typeId:r,protectFrame:i,openFrame:u,outboundTransform:l,inboundTransform:a,wrapReadable:b,wrapWritable:d,wrapBiStream(n){return {...n,send:d(n.send),recv:b(n.recv)}}}}var $={iroh:{available:false,reason:"iroh is constructed by the OpenRTC runtime."},"iroh-quic":{available:false,reason:"iroh-quic is a path label, not a standalone transport."},"iroh-relay":{available:false,reason:"iroh-relay is a path label, not a standalone transport."},"iroh-lan":{available:false,reason:"iroh-lan is a path label, not a standalone transport."},ble:{available:false,reason:"ble requires a separately licensed native host companion and current physical-device evidence."},webrtc:{available:false,reason:"webrtc is an Iroh carrier owned by the OpenRTC runtime, not a standalone transport."},moq:{available:false,reason:"moq is an Iroh carrier owned by the OpenRTC runtime, not a standalone transport."}};function G(e){return e.implementation==="core"?"native":"path-label"}var H=Object.fromEntries(b.map(e=>[e.id,{...e,preferredRank:a[e.id],routeImplementation:e.implementation,implementation:G(e),protocol:e.id,...$[e.id]}]));function W(e){return {...H[e]}}function oe(){return Object.fromEntries(b.map(e=>[e.id,W(e.id)]))}function ae(e={}){let t=e.runtime??"any",r=e.includePathLabels??true;return b.filter(o=>r||o.implementation!=="path-label").filter(o=>t==="browser"?o.browser:t==="native"?o.native:o.browser||o.native).sort((o,i)=>o.defaultRank-i.defaultRank).map(o=>o.id)}var T=32,B="openrtc:x25519-hkdf:v1",C=new TextEncoder().encode("openrtc:application-crypto:v1");function L(e,t){if(!(t instanceof Uint8Array)||t.byteLength!==T)throw new Error(`[OpenRTC] ${e} must be ${T} bytes`)}function Q(e,t){let[r,o]=e<=t?[e,t]:[t,e],i=new TextEncoder().encode(r),u=new TextEncoder().encode(o),l=new Uint8Array(C.byteLength+1+i.byteLength+1+u.byteLength),a=0;return l.set(C,a),a+=C.byteLength,l[a]=0,a+=1,l.set(i,a),a+=i.byteLength,l[a]=0,a+=1,l.set(u,a),l}function ye(e=t=>{let r=new Uint8Array(t);return globalThis.crypto.getRandomValues(r),r}){let t=e(T);return L("key agreement secret",t),{publicKey:x25519.getPublicKey(t),secretKey:t}}function pe(e,t,r,o){L("key agreement local secret",e),L("key agreement remote public key",t);let i=x25519.getSharedSecret(e,t);return hkdf(sha256,i,void 0,Q(r,o),32)}function ue(e){L("key agreement public key",e);let t="";for(let o=0;o<e.byteLength;o+=1)t+=String.fromCharCode(e[o]);let r=btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"");return {algorithm:B,publicKey:r}}function fe(e){if(!e||e.algorithm!==B)return null;let t=typeof e.publicKey=="string"?e.publicKey.trim():"";if(!t)return null;let r=t.replace(/-/g,"+").replace(/_/g,"/"),o=r.length%4===0?r:r+"=".repeat(4-r.length%4),i=Uint8Array.from(atob(o),u=>u.charCodeAt(0));return i.byteLength!==T?null:i}
|
|
2
2
|
export{D as a,Z as b,ee as c,oe as d,ae as e,T as f,B as g,ye as h,pe as i,ue as j,fe as k};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import {j,d as d$1,c}from'./chunk-
|
|
1
|
+
import {j,d as d$1,c}from'./chunk-KN7DF3NH.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
|
-
import {x}from'./chunk-UCNK7KB6.js';var a=class{constructor(e){this.backend=e;}get currentUser(){return this.backend.currentUser}setAuthContext(e){return this.backend.setAuthContext?.(e)}async signInAnonymously(){return this.backend.signInAnonymously()}async signInWithPluto(){if(typeof this.backend.signInWithPluto!="function")throw new Error("Selected runtime adapter does not support Pluto SSO.");return this.backend.signInWithPluto()}async signOut(){return this.backend.signOut()}async stopAuthActivity(){typeof this.backend.stopAuthActivity=="function"&&await this.backend.stopAuthActivity();}usesCoordinationGateway(){return this.backend.usesCoordinationGateway?.()===true}async joinCoordinationRoom(e,t,n){if(!this.backend.joinCoordinationRoom)throw new Error("Selected runtime adapter does not support coordination rooms.");await this.backend.joinCoordinationRoom(e,t,n);}async leaveCoordinationRoom(e){if(!this.backend.leaveCoordinationRoom)throw new Error("Selected runtime adapter does not support coordination rooms.");await this.backend.leaveCoordinationRoom(e);}async getCoordinationRoomMembers(e){if(!this.backend.getCoordinationRoomMembers)throw new Error("Selected runtime adapter does not support coordination rooms.");return this.backend.getCoordinationRoomMembers(e)}watchCoordinationRoomMembers(e,t){if(!this.backend.watchCoordinationRoomMembers)throw new Error("Selected runtime adapter does not support coordination rooms.");return this.backend.watchCoordinationRoomMembers(e,t)}async getTurnCredentials(){return this.backend.getTurnCredentials()}async updatePresence(e,t,n,i,r){return this.backend.updatePresence(e,t,n,i,r)}async refreshLivePresence(e,t,n){if(typeof this.backend.refreshLivePresence!="function")throw new Error("Selected runtime adapter does not support refreshLivePresence().");return this.backend.refreshLivePresence(e,t,n)}async setOffline(e){return this.backend.setOffline(e)}async cleanupStaleDevices(){return this.backend.cleanupStaleDevices()}async searchDevices(e){return this.backend.searchDevices(e)}async listDeviceStatus(){if(typeof this.backend.listDeviceStatus!="function")throw new Error("Selected runtime adapter does not support listDeviceStatus().");return this.backend.listDeviceStatus()}async getPeerSession(e){return typeof this.backend.getPeerSession!="function"?null:this.backend.getPeerSession(e)}async listPeerSessions(){return typeof this.backend.listPeerSessions!="function"?[]:this.backend.listPeerSessions()}async waitForSettledPeer(e,t){return typeof this.backend.waitForSettledPeer!="function"?null:this.backend.waitForSettledPeer(e,t)}async waitForSettledScope(e,t){return typeof this.backend.waitForSettledScope!="function"?null:this.backend.waitForSettledScope(e,t)}async resolvePeerIdentity(e){return typeof this.backend.resolvePeerIdentity!="function"?{peerId:null,deviceId:null,deviceIdHint:null,nodeId:null}:this.backend.resolvePeerIdentity(e)}async resolvePeerRecords(e){return typeof this.backend.resolvePeerRecords!="function"?[]:this.backend.resolvePeerRecords(e)}async updateDevice(e,t){return this.backend.updateDevice(e,t)}async deleteDevice(e){return this.backend.deleteDevice(e)}onDevicesChange(e,t){return this.backend.onDevicesChange(e,t)}onAuthChange(e){return this.backend.onAuthChange(e)}async checkForSSOToken(){return this.backend.checkForSSOToken()}async waitForAuth(){return this.backend.waitForAuth()}async sendMessage(e,t,n,i){return this.backend.sendMessage(e,t,n,i)}async pollMessages(e){return this.backend.pollMessages(e)}watchFriendDevices(e,t){let n=this.backend;return n.watchFriendDevices?n.watchFriendDevices(e,t):()=>{}}async updateFriendTicket(e){let t=this.backend;t.updateFriendTicket&&await t.updateFriendTicket(e);}async subscribeDevices(e){return this.backend.subscribeDevices(e)}async requestTransferPeer(e){if(typeof this.backend?.requestTransferPeer!="function")throw new Error("Transfer peer demand requires a capable OpenRTC runtime. Upgrade the runtime.");return this.backend.requestTransferPeer(e)}async transferPeerDemandStatus(e,t){if(typeof this.backend?.transferPeerDemandStatus!="function")throw new Error("Transfer peer demand requires a capable OpenRTC runtime. Upgrade the runtime.");return this.backend.transferPeerDemandStatus(e,t)}async releaseTransferPeer(e,t){if(typeof this.backend?.releaseTransferPeer!="function")throw new Error("Transfer peer demand requires a capable OpenRTC runtime. Upgrade the runtime.");return this.backend.releaseTransferPeer(e,t)}async setTransferPeerBudget(e,t){if(typeof this.backend?.setTransferPeerBudget!="function")throw new Error("Transfer peer demand requires a capable OpenRTC runtime. Upgrade the runtime.");return this.backend.setTransferPeerBudget(e,t)}async startPeerObservation(e,t){if(typeof this.backend.startPeerObservation!="function")throw new Error("Device observation requires an intent-aware OpenRTC runtime. Upgrade the runtime.");await this.backend.startPeerObservation(e,t);}startAutoConnect(e,t){this.backend.startAutoConnect(e,t);}async submitDesiredPeerProjection(e,t){if(typeof this.backend.submitDesiredPeerProjection!="function")throw new Error("Selected runtime adapter does not support desired-peer projections.");await this.backend.submitDesiredPeerProjection(e,t);}async startPresenceLoop(e,t,n,i,r){await this.backend.startPresenceLoop(e,t,n,i,r);}async createSession(e){return this.backend.createSession(e)}async updateSession(e,t){return this.backend.updateSession(e,t)}async subscribeSessions(e){return this.backend.subscribeSessions(e)}forceReconnect(){this.backend.forceReconnect();}async getLocalDeviceId(){return typeof this.backend.getLocalDeviceId!="function"?null:this.backend.getLocalDeviceId()}async getLocalDeviceInfo(){return typeof this.backend.getLocalDeviceInfo!="function"?null:this.backend.getLocalDeviceInfo()}async updateDeviceName(e){return typeof this.backend.updateDeviceName!="function"?null:this.backend.updateDeviceName(e)}async startNativeSession(e){let t=this.backend;if(typeof t.startNativeSession!="function")throw new Error("Selected runtime adapter does not support startNativeSession().");return t.startNativeSession(e)}async notifyNetworkChange(e){return typeof this.backend.notifyNetworkChange!="function"?null:this.backend.notifyNetworkChange(e)}async setTransportPriority(e){if(typeof this.backend.setTransportPriority!="function")throw new Error("Selected runtime adapter does not support setTransportPriority().");await this.backend.setTransportPriority(e);}async getManagedNodeId(e){if(console.info("[DelegatingRuntimeAdapter][getManagedNodeId] enter",{hasMethod:typeof this.backend.getManagedNodeId=="function",backendCtor:this.backend.constructor?.name??null}),typeof this.backend.getManagedNodeId!="function")return null;let t=await this.backend.getManagedNodeId(e);return console.info("[DelegatingRuntimeAdapter][getManagedNodeId] resolved",{result:t}),t}async startPresence(e,t,n,i,r){let s=this.backend;if(typeof s.startPresence!="function")throw new Error("Selected runtime adapter does not support startPresence().");return s.startPresence(e,t,n,i,r)}async startAutoConnectOnce(e,t){let n=this.backend;if(typeof n.startAutoConnectOnce!="function")throw new Error("Selected runtime adapter does not support startAutoConnectOnce().");return n.startAutoConnectOnce(e,t)}async getEndpointTicket(){if(typeof this.backend.getEndpointTicket!="function")throw new Error("Selected runtime adapter does not support getEndpointTicket().");return this.backend.getEndpointTicket()}async getTicketWithToken(e,t){let n=this.backend;return typeof n.getTicketWithToken!="function"?null:n.getTicketWithToken(e,t)}async issueTicketInvite(e,t,n){let i=this.backend;if(typeof i.issueTicketInvite!="function")throw new Error("Selected runtime adapter does not support ticket invitations.");return i.issueTicketInvite(e,t,n)}async issueTicketMesh(e,t,n){let i=this.backend;if(typeof i.issueTicketMesh!="function")throw new Error("Selected runtime adapter does not support ticket meshes.");return i.issueTicketMesh(e,t,n)}async joinTicketMesh(e,t){let n=this.backend;if(typeof n.joinTicketMesh!="function")throw new Error("Selected runtime adapter does not support ticket meshes.");return n.joinTicketMesh(e,t)}async onTicketMeshInvite(e,t){let n=this.backend;if(typeof n.onTicketMeshInvite!="function")throw new Error("Selected runtime adapter does not support ticket mesh invitation updates.");return n.onTicketMeshInvite(e,t)}async onTicketMeshPeers(e,t){let n=this.backend;if(!n.onTicketMeshPeers)throw new Error("Selected runtime adapter does not support ticket peer readiness.");return n.onTicketMeshPeers(e,t)}async receiveTicketMeshFrame(e,t,n){let i=this.backend;if(typeof i.receiveTicketMeshFrame!="function")throw new Error("Selected runtime adapter does not support ticket mesh frames.");await i.receiveTicketMeshFrame(e,t,n);}async ticketMeshIssuerNode(e){let t=this.backend;if(typeof t.ticketMeshIssuerNode!="function")throw new Error("Selected runtime adapter does not support ticket mesh issuer lookup.");return t.ticketMeshIssuerNode(e)}async closeTicketMesh(e){let t=this.backend;if(typeof t.closeTicketMesh!="function")throw new Error("Selected runtime adapter does not support ticket mesh teardown.");await t.closeTicketMesh(e);}async registerSessionToken(e,t,n,i){let r=this.backend;typeof r.registerSessionToken=="function"&&await r.registerSessionToken(e,t,n,i);}async revokeTokens(e){let t=this.backend;return typeof t.revokeTokens!="function"?[]:t.revokeTokens(e)}async openPeerBi(e,t){if(typeof this.backend.openPeerBi!="function")throw new Error("Selected runtime adapter does not support openPeerBi().");return this.backend.openPeerBi(e,t)}async incoming_streams(){let e=this.backend;if(typeof e.incoming_streams!="function")throw new Error("Selected runtime adapter does not support incoming_streams().");return e.incoming_streams()}async incoming_projected_streams(){let e=this.backend;if(typeof e.incoming_projected_streams!="function")throw new Error("Selected runtime adapter does not support incoming_projected_streams().");return e.incoming_projected_streams()}projectedIncomingStreamSource(){let e=this.backend;return typeof e.projectedIncomingStreamSource!="function"?{incoming_streams:()=>this.incoming_projected_streams(),isCurrentTransport:(t,n)=>this.isCurrentTransport(t,n)}:e.projectedIncomingStreamSource()}async isCurrentTransport(e,t){let n=this.backend;return typeof n.isCurrentTransport=="function"?n.isCurrentTransport(e,t):typeof n.is_current_transport_stable_id!="function"?false:n.is_current_transport_stable_id(e,t)}async openPeerBiRaw(e,t){let n=this.backend;if(typeof n.openPeerBiRaw=="function")return n.openPeerBiRaw(e,t);throw new Error("Selected runtime adapter does not support the restricted transport-only diagnostic stream.")}async openPeerUni(e,t){if(typeof this.backend.openPeerUni!="function")throw new Error("Selected runtime adapter does not support openPeerUni().");return this.backend.openPeerUni(e,t)}async beginOpenRtcMediaPublication(e){if(typeof this.backend.beginOpenRtcMediaPublication!="function")throw new Error("Selected runtime adapter does not support media publications.");return this.backend.beginOpenRtcMediaPublication(e)}async encodeOpenRtcMediaSample(e){if(typeof this.backend.encodeOpenRtcMediaSample!="function")throw new Error("Selected runtime adapter does not support media samples.");return this.backend.encodeOpenRtcMediaSample(e)}async pauseOpenRtcMediaPublication(e){if(typeof this.backend.pauseOpenRtcMediaPublication!="function")throw new Error("Selected runtime adapter does not support media publications.");await this.backend.pauseOpenRtcMediaPublication(e);}async retireOpenRtcMediaPublication(e){if(typeof this.backend.retireOpenRtcMediaPublication!="function")throw new Error("Selected runtime adapter does not support media publications.");await this.backend.retireOpenRtcMediaPublication(e);}async retireOpenRtcMediaReceiver(e,t){if(typeof this.backend.retireOpenRtcMediaReceiver!="function")throw new Error("Selected runtime adapter does not support media receivers.");await this.backend.retireOpenRtcMediaReceiver(e,t);}async decodeOpenRtcMediaChunk(e){if(typeof this.backend.decodeOpenRtcMediaChunk!="function")throw new Error("Selected runtime adapter does not support the media protocol.");return this.backend.decodeOpenRtcMediaChunk(e)}async decodeOpenRtcMediaControl(e){if(typeof this.backend.decodeOpenRtcMediaControl!="function")throw new Error("Selected runtime adapter does not support the media protocol.");return this.backend.decodeOpenRtcMediaControl(e)}async connectToDevice(e){if(typeof this.backend.connectToDevice!="function")throw new Error("Selected runtime adapter does not support connectToDevice().");return this.backend.connectToDevice(e)}async disconnectDevice(e){if(typeof this.backend.disconnectDevice!="function")throw new Error("Selected runtime adapter does not support disconnectDevice().");return this.backend.disconnectDevice(e)}async excludeAutoConnect(e,t){if(typeof this.backend.excludeAutoConnect!="function")throw new Error("Selected runtime adapter does not support excludeAutoConnect().");return this.backend.excludeAutoConnect(e,t)}async isConnected(e){return this.backend.isConnected(e)}async getConnectionStates(){return typeof this.backend.getConnectionStates!="function"?[]:this.backend.getConnectionStates()}onStateChange(e){return typeof this.backend.onStateChange!="function"?()=>{}:this.backend.onStateChange(e)}async sendExplicitFilePath(e,t,n){if(typeof this.backend.sendExplicitFilePath!="function")throw new Error("Selected runtime adapter does not support sendExplicitFilePath().");return this.backend.sendExplicitFilePath(e,t,n)}async sendExplicitFileData(e){if(typeof this.backend.sendExplicitFileData!="function")throw new Error("Selected runtime adapter does not support sendExplicitFileData().");return this.backend.sendExplicitFileData(e)}async getTransferHistory(e){return typeof this.backend.getTransferHistory!="function"?[]:this.backend.getTransferHistory(e)}async deleteTransferJob(e){if(typeof this.backend.deleteTransferJob=="function")return this.backend.deleteTransferJob(e)}async sendPeerMessage(e,t){if(typeof this.backend.sendPeerMessage!="function")throw new Error("Selected runtime adapter does not support native peer messages.");await this.backend.sendPeerMessage(e,t);}onPeerMessage(e){return typeof this.backend.onPeerMessage!="function"?()=>{}:this.backend.onPeerMessage(e)}capabilities(){let e=this.backend;return typeof e.capabilities=="function"?e.capabilities():x()}async onIncomingNativeMessage(e){let t=this.backend;return typeof t.onIncomingNativeMessage!="function"?()=>{}:t.onIncomingNativeMessage(e)}unwrap(){return this.backend}setCoreClient(e){let t=this.backend;typeof t.setCoreClient=="function"&&t.setCoreClient(e);}};export{a};
|
|
1
|
+
import {x}from'./chunk-LCJQ7RSR.js';var a=class{constructor(e){this.backend=e;}get currentUser(){return this.backend.currentUser}setAuthContext(e){return this.backend.setAuthContext?.(e)}async signInAnonymously(){return this.backend.signInAnonymously()}async signInWithPluto(){if(typeof this.backend.signInWithPluto!="function")throw new Error("Selected runtime adapter does not support Pluto SSO.");return this.backend.signInWithPluto()}async signOut(){return this.backend.signOut()}async stopAuthActivity(){typeof this.backend.stopAuthActivity=="function"&&await this.backend.stopAuthActivity();}usesCoordinationGateway(){return this.backend.usesCoordinationGateway?.()===true}async joinCoordinationRoom(e,t,n){if(!this.backend.joinCoordinationRoom)throw new Error("Selected runtime adapter does not support coordination rooms.");await this.backend.joinCoordinationRoom(e,t,n);}async leaveCoordinationRoom(e){if(!this.backend.leaveCoordinationRoom)throw new Error("Selected runtime adapter does not support coordination rooms.");await this.backend.leaveCoordinationRoom(e);}async getCoordinationRoomMembers(e){if(!this.backend.getCoordinationRoomMembers)throw new Error("Selected runtime adapter does not support coordination rooms.");return this.backend.getCoordinationRoomMembers(e)}watchCoordinationRoomMembers(e,t){if(!this.backend.watchCoordinationRoomMembers)throw new Error("Selected runtime adapter does not support coordination rooms.");return this.backend.watchCoordinationRoomMembers(e,t)}async getTurnCredentials(){return this.backend.getTurnCredentials()}async updatePresence(e,t,n,i,r){return this.backend.updatePresence(e,t,n,i,r)}async refreshLivePresence(e,t,n){if(typeof this.backend.refreshLivePresence!="function")throw new Error("Selected runtime adapter does not support refreshLivePresence().");return this.backend.refreshLivePresence(e,t,n)}async setOffline(e){return this.backend.setOffline(e)}async cleanupStaleDevices(){return this.backend.cleanupStaleDevices()}async searchDevices(e){return this.backend.searchDevices(e)}async listDeviceStatus(){if(typeof this.backend.listDeviceStatus!="function")throw new Error("Selected runtime adapter does not support listDeviceStatus().");return this.backend.listDeviceStatus()}async getPeerSession(e){return typeof this.backend.getPeerSession!="function"?null:this.backend.getPeerSession(e)}async listPeerSessions(){return typeof this.backend.listPeerSessions!="function"?[]:this.backend.listPeerSessions()}async waitForSettledPeer(e,t){return typeof this.backend.waitForSettledPeer!="function"?null:this.backend.waitForSettledPeer(e,t)}async waitForSettledScope(e,t){return typeof this.backend.waitForSettledScope!="function"?null:this.backend.waitForSettledScope(e,t)}async resolvePeerIdentity(e){return typeof this.backend.resolvePeerIdentity!="function"?{peerId:null,deviceId:null,deviceIdHint:null,nodeId:null}:this.backend.resolvePeerIdentity(e)}async resolvePeerRecords(e){return typeof this.backend.resolvePeerRecords!="function"?[]:this.backend.resolvePeerRecords(e)}async updateDevice(e,t){return this.backend.updateDevice(e,t)}async deleteDevice(e){return this.backend.deleteDevice(e)}onDevicesChange(e,t){return this.backend.onDevicesChange(e,t)}onAuthChange(e){return this.backend.onAuthChange(e)}async checkForSSOToken(){return this.backend.checkForSSOToken()}async waitForAuth(){return this.backend.waitForAuth()}async sendMessage(e,t,n,i){return this.backend.sendMessage(e,t,n,i)}async pollMessages(e){return this.backend.pollMessages(e)}watchFriendDevices(e,t){let n=this.backend;return n.watchFriendDevices?n.watchFriendDevices(e,t):()=>{}}async updateFriendTicket(e){let t=this.backend;t.updateFriendTicket&&await t.updateFriendTicket(e);}async subscribeDevices(e){return this.backend.subscribeDevices(e)}async requestTransferPeer(e){if(typeof this.backend?.requestTransferPeer!="function")throw new Error("Transfer peer demand requires a capable OpenRTC runtime. Upgrade the runtime.");return this.backend.requestTransferPeer(e)}async transferPeerDemandStatus(e,t){if(typeof this.backend?.transferPeerDemandStatus!="function")throw new Error("Transfer peer demand requires a capable OpenRTC runtime. Upgrade the runtime.");return this.backend.transferPeerDemandStatus(e,t)}async releaseTransferPeer(e,t){if(typeof this.backend?.releaseTransferPeer!="function")throw new Error("Transfer peer demand requires a capable OpenRTC runtime. Upgrade the runtime.");return this.backend.releaseTransferPeer(e,t)}async setTransferPeerBudget(e,t){if(typeof this.backend?.setTransferPeerBudget!="function")throw new Error("Transfer peer demand requires a capable OpenRTC runtime. Upgrade the runtime.");return this.backend.setTransferPeerBudget(e,t)}async startPeerObservation(e,t){if(typeof this.backend.startPeerObservation!="function")throw new Error("Device observation requires an intent-aware OpenRTC runtime. Upgrade the runtime.");await this.backend.startPeerObservation(e,t);}startAutoConnect(e,t){this.backend.startAutoConnect(e,t);}async submitDesiredPeerProjection(e,t){if(typeof this.backend.submitDesiredPeerProjection!="function")throw new Error("Selected runtime adapter does not support desired-peer projections.");await this.backend.submitDesiredPeerProjection(e,t);}async startPresenceLoop(e,t,n,i,r){await this.backend.startPresenceLoop(e,t,n,i,r);}async createSession(e){return this.backend.createSession(e)}async updateSession(e,t){return this.backend.updateSession(e,t)}async subscribeSessions(e){return this.backend.subscribeSessions(e)}forceReconnect(){this.backend.forceReconnect();}async getLocalDeviceId(){return typeof this.backend.getLocalDeviceId!="function"?null:this.backend.getLocalDeviceId()}async getLocalDeviceInfo(){return typeof this.backend.getLocalDeviceInfo!="function"?null:this.backend.getLocalDeviceInfo()}async updateDeviceName(e){return typeof this.backend.updateDeviceName!="function"?null:this.backend.updateDeviceName(e)}async startNativeSession(e){let t=this.backend;if(typeof t.startNativeSession!="function")throw new Error("Selected runtime adapter does not support startNativeSession().");return t.startNativeSession(e)}async notifyNetworkChange(e){return typeof this.backend.notifyNetworkChange!="function"?null:this.backend.notifyNetworkChange(e)}async setTransportPriority(e){if(typeof this.backend.setTransportPriority!="function")throw new Error("Selected runtime adapter does not support setTransportPriority().");await this.backend.setTransportPriority(e);}async getManagedNodeId(e){if(console.info("[DelegatingRuntimeAdapter][getManagedNodeId] enter",{hasMethod:typeof this.backend.getManagedNodeId=="function",backendCtor:this.backend.constructor?.name??null}),typeof this.backend.getManagedNodeId!="function")return null;let t=await this.backend.getManagedNodeId(e);return console.info("[DelegatingRuntimeAdapter][getManagedNodeId] resolved",{result:t}),t}async startPresence(e,t,n,i,r){let s=this.backend;if(typeof s.startPresence!="function")throw new Error("Selected runtime adapter does not support startPresence().");return s.startPresence(e,t,n,i,r)}async startAutoConnectOnce(e,t){let n=this.backend;if(typeof n.startAutoConnectOnce!="function")throw new Error("Selected runtime adapter does not support startAutoConnectOnce().");return n.startAutoConnectOnce(e,t)}async getEndpointTicket(){if(typeof this.backend.getEndpointTicket!="function")throw new Error("Selected runtime adapter does not support getEndpointTicket().");return this.backend.getEndpointTicket()}async getTicketWithToken(e,t){let n=this.backend;return typeof n.getTicketWithToken!="function"?null:n.getTicketWithToken(e,t)}async issueTicketInvite(e,t,n){let i=this.backend;if(typeof i.issueTicketInvite!="function")throw new Error("Selected runtime adapter does not support ticket invitations.");return i.issueTicketInvite(e,t,n)}async issueTicketMesh(e,t,n){let i=this.backend;if(typeof i.issueTicketMesh!="function")throw new Error("Selected runtime adapter does not support ticket meshes.");return i.issueTicketMesh(e,t,n)}async joinTicketMesh(e,t){let n=this.backend;if(typeof n.joinTicketMesh!="function")throw new Error("Selected runtime adapter does not support ticket meshes.");return n.joinTicketMesh(e,t)}async onTicketMeshInvite(e,t){let n=this.backend;if(typeof n.onTicketMeshInvite!="function")throw new Error("Selected runtime adapter does not support ticket mesh invitation updates.");return n.onTicketMeshInvite(e,t)}async onTicketMeshPeers(e,t){let n=this.backend;if(!n.onTicketMeshPeers)throw new Error("Selected runtime adapter does not support ticket peer readiness.");return n.onTicketMeshPeers(e,t)}async receiveTicketMeshFrame(e,t,n){let i=this.backend;if(typeof i.receiveTicketMeshFrame!="function")throw new Error("Selected runtime adapter does not support ticket mesh frames.");await i.receiveTicketMeshFrame(e,t,n);}async ticketMeshIssuerNode(e){let t=this.backend;if(typeof t.ticketMeshIssuerNode!="function")throw new Error("Selected runtime adapter does not support ticket mesh issuer lookup.");return t.ticketMeshIssuerNode(e)}async closeTicketMesh(e){let t=this.backend;if(typeof t.closeTicketMesh!="function")throw new Error("Selected runtime adapter does not support ticket mesh teardown.");await t.closeTicketMesh(e);}async registerSessionToken(e,t,n,i){let r=this.backend;typeof r.registerSessionToken=="function"&&await r.registerSessionToken(e,t,n,i);}async revokeTokens(e){let t=this.backend;return typeof t.revokeTokens!="function"?[]:t.revokeTokens(e)}async openPeerBi(e,t){if(typeof this.backend.openPeerBi!="function")throw new Error("Selected runtime adapter does not support openPeerBi().");return this.backend.openPeerBi(e,t)}async incoming_streams(){let e=this.backend;if(typeof e.incoming_streams!="function")throw new Error("Selected runtime adapter does not support incoming_streams().");return e.incoming_streams()}async incoming_projected_streams(){let e=this.backend;if(typeof e.incoming_projected_streams!="function")throw new Error("Selected runtime adapter does not support incoming_projected_streams().");return e.incoming_projected_streams()}projectedIncomingStreamSource(){let e=this.backend;return typeof e.projectedIncomingStreamSource!="function"?{incoming_streams:()=>this.incoming_projected_streams(),isCurrentTransport:(t,n)=>this.isCurrentTransport(t,n)}:e.projectedIncomingStreamSource()}async isCurrentTransport(e,t){let n=this.backend;return typeof n.isCurrentTransport=="function"?n.isCurrentTransport(e,t):typeof n.is_current_transport_stable_id!="function"?false:n.is_current_transport_stable_id(e,t)}async openPeerBiRaw(e,t){let n=this.backend;if(typeof n.openPeerBiRaw=="function")return n.openPeerBiRaw(e,t);throw new Error("Selected runtime adapter does not support the restricted transport-only diagnostic stream.")}async openPeerUni(e,t){if(typeof this.backend.openPeerUni!="function")throw new Error("Selected runtime adapter does not support openPeerUni().");return this.backend.openPeerUni(e,t)}async beginOpenRtcMediaPublication(e){if(typeof this.backend.beginOpenRtcMediaPublication!="function")throw new Error("Selected runtime adapter does not support media publications.");return this.backend.beginOpenRtcMediaPublication(e)}async encodeOpenRtcMediaSample(e){if(typeof this.backend.encodeOpenRtcMediaSample!="function")throw new Error("Selected runtime adapter does not support media samples.");return this.backend.encodeOpenRtcMediaSample(e)}async pauseOpenRtcMediaPublication(e){if(typeof this.backend.pauseOpenRtcMediaPublication!="function")throw new Error("Selected runtime adapter does not support media publications.");await this.backend.pauseOpenRtcMediaPublication(e);}async retireOpenRtcMediaPublication(e){if(typeof this.backend.retireOpenRtcMediaPublication!="function")throw new Error("Selected runtime adapter does not support media publications.");await this.backend.retireOpenRtcMediaPublication(e);}async retireOpenRtcMediaReceiver(e,t){if(typeof this.backend.retireOpenRtcMediaReceiver!="function")throw new Error("Selected runtime adapter does not support media receivers.");await this.backend.retireOpenRtcMediaReceiver(e,t);}async decodeOpenRtcMediaChunk(e){if(typeof this.backend.decodeOpenRtcMediaChunk!="function")throw new Error("Selected runtime adapter does not support the media protocol.");return this.backend.decodeOpenRtcMediaChunk(e)}async decodeOpenRtcMediaControl(e){if(typeof this.backend.decodeOpenRtcMediaControl!="function")throw new Error("Selected runtime adapter does not support the media protocol.");return this.backend.decodeOpenRtcMediaControl(e)}async connectToDevice(e){if(typeof this.backend.connectToDevice!="function")throw new Error("Selected runtime adapter does not support connectToDevice().");return this.backend.connectToDevice(e)}async disconnectDevice(e){if(typeof this.backend.disconnectDevice!="function")throw new Error("Selected runtime adapter does not support disconnectDevice().");return this.backend.disconnectDevice(e)}async excludeAutoConnect(e,t){if(typeof this.backend.excludeAutoConnect!="function")throw new Error("Selected runtime adapter does not support excludeAutoConnect().");return this.backend.excludeAutoConnect(e,t)}async isConnected(e){return this.backend.isConnected(e)}async getConnectionStates(){return typeof this.backend.getConnectionStates!="function"?[]:this.backend.getConnectionStates()}onStateChange(e){return typeof this.backend.onStateChange!="function"?()=>{}:this.backend.onStateChange(e)}async sendExplicitFilePath(e,t,n){if(typeof this.backend.sendExplicitFilePath!="function")throw new Error("Selected runtime adapter does not support sendExplicitFilePath().");return this.backend.sendExplicitFilePath(e,t,n)}async sendExplicitFileData(e){if(typeof this.backend.sendExplicitFileData!="function")throw new Error("Selected runtime adapter does not support sendExplicitFileData().");return this.backend.sendExplicitFileData(e)}async getTransferHistory(e){return typeof this.backend.getTransferHistory!="function"?[]:this.backend.getTransferHistory(e)}async deleteTransferJob(e){if(typeof this.backend.deleteTransferJob=="function")return this.backend.deleteTransferJob(e)}async sendPeerMessage(e,t){if(typeof this.backend.sendPeerMessage!="function")throw new Error("Selected runtime adapter does not support native peer messages.");await this.backend.sendPeerMessage(e,t);}onPeerMessage(e){return typeof this.backend.onPeerMessage!="function"?()=>{}:this.backend.onPeerMessage(e)}capabilities(){let e=this.backend;return typeof e.capabilities=="function"?e.capabilities():x()}async onIncomingNativeMessage(e){let t=this.backend;return typeof t.onIncomingNativeMessage!="function"?()=>{}:t.onIncomingNativeMessage(e)}unwrap(){return this.backend}setCoreClient(e){let t=this.backend;typeof t.setCoreClient=="function"&&t.setCoreClient(e);}};export{a};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import {c as c$1,e}from'./chunk-OWKAJPOI.js';var a=c$1,c=new Set(a);function t(r){if(typeof r!="string")return;let o=r.trim().toLowerCase();return c.has(o)?o:void 0}function s(r){let o=t(r);return o?e(o).baseProtocol==="iroh":false}function u(r){let o=t(r);if(!o)return false;let e$1=e(o);return e$1.baseProtocol==="iroh"&&(e$1.locality==="nearby"||e$1.locality==="direct-internet")}function d(r){return t(r)==="webrtc"}function p(r){let o=t(r);if(!o)return false;let e$1=e(o);return e$1.baseProtocol==="iroh"&&e$1.implementation==="carrier-adapter"}export{a,t as b,s as c,u as d,d as e,p as f};
|
|
@@ -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};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var w="3.
|
|
1
|
+
var w="3.1.1";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};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import {b as b$3}from'./chunk-FKAQDDUM.js';import {b as b$6,a as a$4,c}from'./chunk-IVNXIG7J.js';import {a as a$1,b as b$4}from'./chunk-IUU6JCLK.js';import {b as b$2,a as a$3}from'./chunk-CCCYE3XN.js';import {b as b$1,a as a$2}from'./chunk-ZA44REGI.js';import {d,a,e}from'./chunk-L7N4T2PX.js';import {d as d$1,b as b$5}from'./chunk-2GX6GB6L.js';function R(a,e,t,i){let n=JSON.stringify({__openrtc:2,capability:i,kind:a,name:e,value:t});if(n===void 0||!n.includes('"value":'))throw new Error("[OpenRTC] Messages must be JSON-serializable values.");return new TextEncoder().encode(n)}function B(a){let e;try{e=a instanceof Uint8Array?JSON.parse(new TextDecoder().decode(a)):a&&typeof a=="object"?a:{};}catch{return null}return e!=null&&e.__openrtc===2&&typeof e.capability=="string"&&e.capability.length>0&&e.capability.length<=192&&/^(?:devices|space|room|ticket):[A-Za-z0-9_.:@-]+$/.test(e.capability)&&(e.kind==="raw"||e.kind==="channel"||e.kind==="state")&&typeof e.name=="string"&&e.name.length>0&&e.name.length<=80&&/^[A-Za-z0-9_.:@-]+$/.test(e.name)&&Object.prototype.hasOwnProperty.call(e,"value")?e:null}var b="openrtc-peer-stream/1",de=32,ee=16,L=4294967295,he=/^[A-Za-z0-9][A-Za-z0-9._/+:-]{0,127}$/,ue=/^([0-9a-f]{64})-([0-9a-f]{64})$/i;function S(a){let e=a?.trim()??"";if(!he.test(e))throw new Error("[OpenRTC] stream protocol must be 1-128 safe ASCII characters.");return e}function x(a){let e=a?.trim()??"",t=ue.exec(e);return t?[t[1].toLowerCase(),t[2].toLowerCase()].sort().join("-"):e}function te(a){if(a===null||a===0)return null;if(!Number.isFinite(a)||a<0)throw new RangeError("[OpenRTC] datagram maximum age must be a non-negative finite number or null.");return Math.min(L,Math.ceil(a))}function ie(a){if(!Number.isSafeInteger(a)||a<1||a>L)throw new RangeError(`[OpenRTC] datagram buffer limits must be integers from 1 to ${L}.`);return a}var _=class{constructor(e,t){this.runtime=e;this.peerId=t;this.incomingAge=null;this.outgoingAge=null;this.incomingLimit=ee;this.outgoingLimit=ee;this.policyInstance=null;this.incomingWaiters=new Set;this.outgoingWaiters=new Set;this.outgoingAvailable=new Set;this.incomingError=null;this.receiveLoopStarted=false;this.sendLoop=null;this.closed=false;this.incomingClosed=false;this.outgoingClosed=false;this.maxDatagramSize=e.peerDatagramMaxSize?.()??1024,this.readable=new ReadableStream({pull:i=>this.pullIncoming(i),cancel:()=>this.closeIncoming()},{highWaterMark:0}),this.writable=new WritableStream({write:i=>this.enqueueOutgoing(i),close:async()=>{this.outgoingClosed=true,await this.sendLoop;},abort:()=>{this.outgoingClosed=true,this.policyInstance?.closeOutgoing(),this.wake(this.outgoingWaiters),this.wake(this.outgoingAvailable);}},{highWaterMark:1});}get incomingMaxAge(){return this.incomingAge}set incomingMaxAge(e){this.incomingAge=te(e),this.policy.setIncomingMaxAge(this.incomingAge??void 0,Date.now()),this.wake(this.incomingWaiters);}get outgoingMaxAge(){return this.outgoingAge}set outgoingMaxAge(e){this.outgoingAge=te(e),this.policy.setOutgoingMaxAge(this.outgoingAge??void 0);}get incomingMaxBufferedDatagrams(){return this.incomingLimit}set incomingMaxBufferedDatagrams(e){this.incomingLimit=ie(e),this.policy.setIncomingMaxBufferedDatagrams(this.incomingLimit);}get outgoingMaxBufferedDatagrams(){return this.outgoingLimit}set outgoingMaxBufferedDatagrams(e){this.outgoingLimit=ie(e),this.policy.setOutgoingMaxBufferedDatagrams(this.outgoingLimit),this.wake(this.outgoingWaiters);}getStats(){return this.policy.getStats(Date.now())}get policy(){if(!this.policyInstance){let e=this.runtime.createPeerDatagramPolicy;if(!e)throw new Error("[OpenRTC] Shared protected-datagram policy is unavailable in this runtime.");this.policyInstance=e();}return this.policyInstance}close(){this.closed||(this.closed=true,this.closeIncoming(),this.outgoingClosed=true,this.policyInstance?.closeOutgoing(),this.wake(this.outgoingWaiters),this.wake(this.outgoingAvailable));}async pullIncoming(e){for(this.receiveLoopStarted||(this.receiveLoopStarted=true,this.pumpIncoming());;){let t=this.policy.popIncoming(Date.now());if(t){e.enqueue(new Uint8Array(t));return}if(this.incomingError){e.error(this.incomingError);return}if(this.incomingClosed){e.close();return}await new Promise(i=>this.incomingWaiters.add(i));}}async pumpIncoming(){let e=this.runtime.receivePeerDatagram;if(!e){this.incomingError=new Error("[OpenRTC] Protected peer datagrams are unavailable in this runtime."),this.wake(this.incomingWaiters);return}try{for(;!this.incomingClosed;){let t=new Uint8Array(await e(this.peerId));if(this.incomingClosed)return;this.policy.pushIncoming(t,Date.now()),this.wake(this.incomingWaiters);}}catch(t){this.incomingClosed||(this.incomingError=t,this.wake(this.incomingWaiters));}}async enqueueOutgoing(e){if(this.closed||this.outgoingClosed)throw new Error("[OpenRTC] peer datagram stream is closed.");if(!(e instanceof Uint8Array)||e.byteLength>this.maxDatagramSize)throw new Error(`[OpenRTC] peer datagrams must be Uint8Array values up to ${this.maxDatagramSize} bytes.`);for(;!this.policy.pushOutgoing(e,Date.now())&&!this.closed;)await new Promise(t=>this.outgoingWaiters.add(t));if(this.closed||this.outgoingClosed)throw new Error("[OpenRTC] peer datagram stream is closed.");this.startSendLoop(),this.wake(this.outgoingAvailable);}startSendLoop(){this.sendLoop||this.closed||(this.sendLoop=this.pumpOutgoing());}async pumpOutgoing(){let e=this.runtime.sendPeerDatagram;if(!e){this.policy.closeOutgoing();return}for(;!this.closed;){let t=this.policy.popOutgoing(Date.now());if(!t){if(this.wake(this.outgoingWaiters),this.outgoingClosed)return;await new Promise(n=>this.outgoingAvailable.add(n));continue}this.wake(this.outgoingWaiters);let i=new Uint8Array(t.payload);try{await e(this.peerId,i,t.remainingMaxAgeMs??void 0)===!1?this.policy.recordExpiredOutgoing():this.policy.recordSent(i.byteLength);}catch{this.policy.recordSendFailure();}this.wake(this.outgoingWaiters);}}closeIncoming(){this.incomingClosed||(this.incomingClosed=true,this.policyInstance?.closeIncoming(),this.wake(this.incomingWaiters));}wake(e){for(let t of e)t();e.clear();}},A=class{constructor(){this.controller=null;this.closed=false;this.readable=new ReadableStream({start:e=>{this.controller=e;},cancel:()=>{this.closed=true,this.controller=null;}},{highWaterMark:de});}enqueue(e){return this.closed||!this.controller||(this.controller.desiredSize??0)<=0?false:(this.controller.enqueue(e),true)}close(){this.closed||(this.closed=true,this.controller?.close(),this.controller=null);}},F=class{constructor(e,t,i,n){this.client=e;this.peerId=t;this.capabilityKey=n;this.incomingBi=new A;this.incomingUni=new A;this.incomingBidirectionalStreams=this.incomingBi.readable;this.incomingUnidirectionalStreams=this.incomingUni.readable;this.closed=false;this.protocolHandlers=new Map;this.datagrams=new _(i,this.peerId);}async createBidirectionalStream(e){let t=S(e.protocol),i=await this.client.channels.openBi(this.peerId,b,{timeoutMs:e.timeoutMs,channelMetadata:{protocol:t,[a$3]:this.capabilityKey}});return {protocol:t,readable:i.readable,writable:i.writable}}async createUnidirectionalStream(e){let t=S(e.protocol);return (await this.client.channels.openUni(this.peerId,b,{timeoutMs:e.timeoutMs,channelMetadata:{protocol:t,[a$3]:this.capabilityKey}})).writable}accept(e,t){if(e.type==="bi"){let n=e.stream;if(!n.recv||!n.send)return false;let s={peerId:this.peerId,protocol:t,readable:n.recv,writable:n.send},r=this.protocolHandlers.get(t);if(r){try{r(s);}catch{s.readable.cancel("incoming-protocol-handler-failed").catch(()=>{}),s.writable.abort("incoming-protocol-handler-failed").catch(()=>{});}return true}return this.incomingBi.enqueue(s)||(s.readable.cancel("incoming-peer-stream-queue-full").catch(()=>{}),s.writable.abort("incoming-peer-stream-queue-full").catch(()=>{})),true}let i=e.stream;return !i||typeof i.getReader!="function"?false:(this.incomingUni.enqueue({peerId:this.peerId,protocol:t,readable:i})||i.cancel("incoming-peer-stream-queue-full").catch(()=>{}),true)}onProtocol(e,t){let i=S(e);if(this.protocolHandlers.has(i))throw new Error(`[OpenRTC] stream protocol '${i}' already has an owning consumer.`);return this.protocolHandlers.set(i,t),()=>{this.protocolHandlers.get(i)===t&&this.protocolHandlers.delete(i);}}close(){this.closed=true,this.datagrams.close(),this.protocolHandlers.clear(),this.incomingBi.close(),this.incomingUni.close();}},O=class{constructor(e,t){this.client=e;this.capabilityKey=t;this.peers=new Map;this.peerIdsByConnection=new Map;this.registered=false;this.observed=0;this.accepted=0;this.declined=0;this.lastResolution="none";try{e.channels.register({id:b,kind:"application-stream",ownership:"shared",peerModel:"device-first",routing:"stream-envelope",readiness:"settled-peer",promotionPolicy:"never",signalingPolicy:"hosted",delivery:"reliable",description:"Transport-agnostic protected peer streams"}),this.stopIncoming=e.channels.onIncomingChannel(b,i=>this.accept(i)),this.registered=!0;}catch{this.stopIncoming=()=>{};}}forPeer(e){let t=this.peers.get(e);return t||(t=new F(this.client,e,this.client.advanced.runtime,this.capabilityKey),this.peers.set(e,t)),t}onProtocol(e,t,i){return this.forPeer(e).onProtocol(t,i)}bindConnection(e,t){let i=x(e),n=t.trim();!i||!n||this.peerIdsByConnection.set(i,n);}unbindConnection(e){this.peerIdsByConnection.delete(x(e));}diagnostics(){return {registered:this.registered,peers:this.peers.size,boundConnections:this.peerIdsByConnection.size,observed:this.observed,accepted:this.accepted,declined:this.declined,lastResolution:this.lastResolution}}closePeer(e){let t=this.peers.get(e);if(t){t.close(),this.peers.delete(e);for(let[i,n]of this.peerIdsByConnection)n===e&&this.peerIdsByConnection.delete(i);}}close(){this.stopIncoming();for(let e of this.peers.values())e.close();this.peers.clear(),this.peerIdsByConnection.clear(),this.registered&&this.client.channels.unregister(b);}accept(e){if(this.observed+=1,e.channel?.metadata?.[a$3]!==this.capabilityKey)return this.declined+=1,false;let i=e.channel?.metadata?.protocol;if(typeof i!="string")return this.declined+=1,false;let n;try{n=S(i);}catch{return this.declined+=1,false}let r=this.resolveExistingPeer(e.remoteNodeId,e.connectionId)?.accept(e,n)??false;return r?this.accepted+=1:this.declined+=1,r}resolveExistingPeer(e,t=""){let i=x(t);if(i){let r=this.peerIdsByConnection.get(i);if(!r)return this.lastResolution="unbound-connection",null;let o=this.peers.get(r);return o?(this.lastResolution="connection",o):(this.lastResolution="unbound-connection",null)}let n=this.peers.get(e);if(n)return this.lastResolution="remote-peer",n;let s=this.client.peers.get(e)??this.client.peers.listConnected().find(r=>[r.peerId,r.deviceId,r.deviceIdHint,r.connectionId,...r.connectionIds].some(o=>o===e));if(s){let r=new Set([s.peerId,s.deviceId,s.deviceIdHint,s.connectionId,...s.connectionIds].filter(c=>typeof c=="string"&&c.length>0)),o=[...this.peers.entries()].filter(([c])=>r.has(c)).map(([,c])=>c);if(o.length===1)return this.lastResolution="peer-alias",o[0]}return this.lastResolution="none",null}};var w=new WeakMap;function pe(a){let e=w.get(a);if(!e||a.closed)throw new Error("[OpenRTC] Capability runtime is unavailable or already closed.");return e}function Be(a,e){if(w.has(a))throw new Error("[OpenRTC] Capability runtime is already registered.");return w.set(a,pe(e)),()=>{w.delete(a);}}function me(a){let e=a?.trim()??"";if(!/^pk_(?:live|test)_[0-9a-f]{40}$/.test(e))throw new Error("[OpenRTC] apiKey must be a public pk_live_ or pk_test_ key.");return e}function y(a){let e=a?.trim()??"";if(!e||e.length>160||!/^[A-Za-z0-9_.:@-]+$/.test(e))throw new Error("[OpenRTC] Capability id is invalid.");return e}var q=/^[A-Za-z0-9_.:@-]{1,160}$/,ve=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,ne=2,U=8,ge=U;function fe(a){let e=typeof a=="string"?a.trim():"";if(!q.test(e))return null;let t=e.startsWith("device_")?e.slice(7):"";return ve.test(t)?t:e}function ye(a){let e=`openrtc:v2:device-id:${a}`,t,i=(()=>{try{return t=globalThis.localStorage,fe(t?.getItem(e))||crypto.randomUUID()}catch{return crypto.randomUUID()}})();try{t?.setItem(e,i);}catch{}return i}function re(a){let e=typeof a=="string"?a.trim():"";if(!q.test(e))throw new Error("[OpenRTC] The native host returned an invalid durable device ID.");return e}var se=250;function oe(a){if(a===void 0)return [];if(!Array.isArray(a))throw new Error("[OpenRTC] autoConnectExcludedDeviceIds must be an array.");let e=[...new Set(a.map(t=>{let i=typeof t=="string"?t.trim().toLowerCase():"";if(!q.test(i))throw new Error("[OpenRTC] autoConnectExcludedDeviceIds contains an invalid device ID.");return i}))].sort();if(e.length>se)throw new Error(`[OpenRTC] autoConnectExcludedDeviceIds supports at most ${se} devices.`);return e}function N(a){let e=b$1(a.token),t=typeof e.deviceKeyThumbprint=="string"?e.deviceKeyThumbprint.trim():"";if(!/^[A-Za-z0-9_-]{43}$/.test(t))throw new Error("[OpenRTC] Anonymous capability is missing its device-key binding.");return `anon_${t.slice(0,32)}`}var H=class{constructor(){this.descriptors=new Map;this.targets=new Map;}register(e){if(!e?.id?.trim())throw new Error("[OpenRTC] Channel id is required.");this.descriptors.set(e.id,{...e});for(let[t,i]of this.targets)t.channels.register({...e,delivery:e.delivery??i});return ()=>{this.descriptors.delete(e.id);for(let t of this.targets.keys())t.channels.unregister(e.id);}}list(){return [...this.descriptors.values()].map(e=>({...e}))}attach(e,t){this.targets.set(e,t);for(let i of this.descriptors.values())e.channels.register({...i,delivery:i.delivery??t});}detach(e){this.targets.delete(e);}};function ae(a$1){return d(a.TICKET_MESH_ALREADY_ACTIVE,`[OpenRTC] ticket:${a$1} is already active with different options.`,{retryable:false,plane:"admission"})}function le(a){return a.mesh===true?a.maxPeers??ge:a.maxPeers}function we(a){return JSON.stringify({identity:a.identity??(a.mesh===true?"session":null),maxPeers:le(a)??null,mesh:a.mesh===true,advancedFanout:a.advancedFanout===true})}function ce(a){let e=a?.trim()??"";if(!e||e.length>80||!/^[A-Za-z0-9_.:@-]+$/.test(e))throw new Error("[OpenRTC] Message name is invalid.");return e}var G=class{constructor(e,t,i){this.client=e;this.capabilityKey=t;this.rawConnections=new Map;this.logicalConnections=new Map;this.connectionListeners=new Map;this.rawListeners=new Map;this.closeListeners=new Map;this.channelListeners=new Map;this.stateListeners=new Map;this.remoteState=new Map;this.localState=new Map;this.stateSenders=new Map;this.stateReadyGenerations=new Map;this.mediaConnections=new Map;this.mediaRetirements=new Map;this.pendingRawConnections=new Map;this.connectionIdsByPeer=new Map;this.closed=false;this.cleanupComplete=false;this.closeAttempt=null;this.pendingStops=null;this.peerStreams=new O(e,t),this.stopMessage=e.onMessage((n,s)=>this.receive(n,s)),this.stopConnection=e.onConnection(n=>this.add(n)),this.stopDisconnection=e.onDisconnection(n=>this.remove(n)),e.getConnections().forEach(n=>this.add(n)),this.stopPeerLifecycle=e.peers.watchLifecycle(n=>this.observePeerLifecycle(n)),this.roomFanout=i?.create({client:e,capabilityKey:t,connections:()=>[...this.logicalConnections.values()].flatMap(({activeRaw:n})=>n?[n]:[]),deliver:(n,s,r)=>{let o=B(s);!o||o.capability!==this.capabilityKey||r!==void 0&&o.name!==r||r===void 0&&o.kind!=="channel"||this.deliverEnvelope(n,o);}});}state(e){if(this.assertOpen(),this.roomFanout?.isSparse())throw new Error("[OpenRTC] state() is not available in sparse gossip rooms; use a named channel with application-owned latest-state revisions.");let t=ce(e);return {set:i=>{this.assertOpen();let n=R("state",t,i,this.capabilityKey);if(this.localState.set(t,n),!this.roomFanout?.publishState(t,n))for(let{activeRaw:s}of this.logicalConnections.values())s&&this.sendState(s,t,n);},watch:i=>{this.assertOpen();let n=this.stateListeners.get(t);n||this.stateListeners.set(t,n=new Set);let s=(r,o)=>i({peerId:r,value:o});n.add(s);for(let[r,o]of this.remoteState)o.has(t)&&i({peerId:r,value:o.get(t)});return ()=>n?.delete(s)}}}channel(e){this.assertOpen();let t=ce(e),i=n=>R("channel",t,n,this.capabilityKey);return {send:async n=>{this.assertOpen();let s=i(n);await this.roomFanout?.sendChannel(t,s)||(this.assertOpen(),await Promise.all([...this.logicalConnections.values()].flatMap(({activeRaw:r})=>r?[this.sendPayload(r,s)]:[])));},sendTo:async(n,s)=>{this.assertOpen(),this.roomFanout?.assertTargetedSendAllowed();let r=this.logicalConnections.get(n)?.activeRaw;if(r){await this.sendPayload(r,i(s));return}throw d(a.DELIVERY_NOT_READY,`[OpenRTC] Peer '${n}' has no direct authorized route; sparse broadcasts never multi-hop targeted payloads.`,{retryable:true,plane:"delivery"})},onMessage:n=>{this.assertOpen();let s=this.channelListeners.get(t);s||this.channelListeners.set(t,s=new Set);let r=(o,c)=>n({peerId:o,message:c});return s.add(r),()=>s?.delete(r)}}}async sendPayload(e$1,t){try{await e$1.send(t);}catch(i){throw e(i)}}onConnection(e){this.assertOpen();let t=new Set;this.connectionListeners.set(e,t);for(let[i,n]of this.logicalConnections)n.activeRaw&&(t.add(i),e(n.view));return ()=>this.connectionListeners.delete(e)}assertOpen(){if(this.closed)throw new Error("[OpenRTC] Capability messages are closed.")}fence(){this.closed=true;}close(){if(this.cleanupComplete)return Promise.resolve();if(this.closeAttempt)return this.closeAttempt;this.closed=true;let e=this.releaseMessages();return this.closeAttempt=e,e.then(()=>{this.closeAttempt===e&&(this.closeAttempt=null);},()=>{this.closeAttempt===e&&(this.closeAttempt=null);}),e}async releaseMessages(){let e=[];this.pendingStops??(this.pendingStops=[()=>this.stopMessage(),()=>this.stopConnection(),()=>this.stopDisconnection(),()=>this.stopPeerLifecycle(),()=>this.roomFanout?.close()]),this.pendingStops=this.pendingStops.filter(i=>{try{return i(),!1}catch(n){return e.push(n),true}});let t=[];for(let i of this.logicalConnections.keys())try{t.push(this.retire(i));}catch(n){e.push(n);}this.pendingRawConnections.clear();try{this.peerStreams.close();}catch(i){e.push(i);}this.rawConnections.clear(),this.logicalConnections.clear(),this.connectionListeners.clear(),this.channelListeners.clear(),this.stateListeners.clear(),this.localState.clear(),this.remoteState.clear(),this.stateReadyGenerations.clear(),this.rawListeners.clear(),this.closeListeners.clear();for(let i of await Promise.allSettled(t))i.status==="rejected"&&e.push(i.reason);if(e.length===1)throw e[0];if(e.length)throw d(a.INTERNAL,"[OpenRTC] Capability message cleanup failed.",{cause:e,retryable:true,plane:"internal"});this.cleanupComplete=true;}add(e){if(this.closed)return;let t=this.rawConnections.get(e.id);if(t?.raw===e)return;t&&this.remove(t.raw);let i=e.remoteNodeId||e.id,n=this.mediaRetirements.get(i);if(n){let o={raw:e,peerId:i};this.pendingRawConnections.set(e.id,o),n.finally(()=>{this.closed||this.pendingRawConnections.get(e.id)!==o||(this.pendingRawConnections.delete(e.id),this.add(e));});return}this.rawConnections.set(e.id,{raw:e,peerId:i});let s=this.connectionIdsByPeer.get(i);s||this.connectionIdsByPeer.set(i,s=new Set),s.add(e.id),this.peerStreams.bindConnection(e.id,i);let r=this.logicalConnections.get(i);if(!r){let o=this.peerStreams.forPeer(i),c=new b$3(o,this.client.advanced.runtime,(h,l)=>this.peerStreams.onProtocol(i,h,l),()=>this.peerStreams.diagnostics());this.mediaConnections.set(i,c),r={activeRaw:e,rawIds:new Set,view:{id:i,peerId:i,streams:o,media:c,send:async h=>{let l=this.logicalConnections.get(i)?.activeRaw;if(!l)throw d(a.DELIVERY_NOT_READY,`[OpenRTC] Peer '${i}' is not connected.`,{retryable:true,plane:"delivery"});await this.sendPayload(l,R("raw","message",h,this.capabilityKey));},onMessage:h=>{let l=this.rawListeners.get(i);l||this.rawListeners.set(i,l=new Set);let u=h;return l.add(u),()=>l?.delete(u)},onClose:h=>{let l=this.closeListeners.get(i);return l||this.closeListeners.set(i,l=new Set),l.add(h),()=>l?.delete(h)}}},this.logicalConnections.set(i,r);}r.rawIds.add(e.id),r.activeRaw=e,this.observePeerLifecycle(this.client.peers.listConnected());for(let[o,c]of this.connectionListeners)c.has(i)||(c.add(i),o(r.view));for(let[o,c]of this.localState)this.sendState(e,o,c);}remove(e){if(this.pendingRawConnections.get(e.id)?.raw===e){this.pendingRawConnections.delete(e.id);return}let t=this.rawConnections.get(e.id);if(!t||t.raw!==e)return;this.rawConnections.delete(e.id),this.peerStreams.unbindConnection(e.id);let i=t.peerId,n=this.logicalConnections.get(i);if(n?.rawIds.delete(e.id),n?.activeRaw?.id===e.id){let o=[...n.rawIds],c=o[o.length-1];n.activeRaw=c?this.rawConnections.get(c)?.raw??null:null;}let s=this.connectionIdsByPeer.get(i);if(s?.delete(e.id),s?.size===0&&this.connectionIdsByPeer.delete(i),!n?.activeRaw){let o=this.remoteState.get(i);if(o){for(let c of o.keys())for(let d of this.stateListeners.get(c)??[])d(i,null);this.remoteState.delete(i);}}let r=this.stateSenders.get(e);if(r){for(let o of r.values())o.close();this.stateSenders.delete(e);}}observePeerLifecycle(e){for(let t of this.logicalConnections.keys()){let i=this.connectionIdsByPeer.get(t)??new Set,n=e.find(d=>d.peerId===t||d.connectionId===t||d.connectionIds.some(h=>i.has(h)));if(!n)continue;let s=n.status==="closed"&&n.logicalSessionTerminal===true&&n.routable!==true&&n.settledReady!==true;if(n.manualDisconnect||s){this.retire(t);continue}if(n.settledReady!==true||n.routable!==true){this.stateReadyGenerations.delete(t);continue}let r=n.transportStableId,o=n.transportGeneration,c=n.routeGeneration;if(Number.isSafeInteger(r)&&Number(r)>0&&Number.isSafeInteger(o)&&Number(o)>0&&Number.isSafeInteger(c)&&Number(c)>=0){let d=JSON.stringify([n.connectionId,n.generation,r,o,c]);if(this.stateReadyGenerations.get(t)!==d){this.stateReadyGenerations.set(t,d);let l=this.logicalConnections.get(t)?.activeRaw;if(l)for(let[u,p]of this.localState)this.sendState(l,u,p);}let h=this.mediaConnections.get(t);h&&h.observePhysicalGeneration({transportStableId:Number(r),transportGeneration:Number(o),routeGeneration:Number(c)}).catch(()=>{});}}}retire(e){let t=this.logicalConnections.get(e);if(!t)return this.mediaRetirements.get(e)??Promise.resolve();this.logicalConnections.delete(e),this.stateReadyGenerations.delete(e);for(let r of t.rawIds){let o=this.rawConnections.get(r)?.raw;if(this.rawConnections.delete(r),this.peerStreams.unbindConnection(r),!o)continue;let c=this.stateSenders.get(o);if(c){for(let d of c.values())d.close();this.stateSenders.delete(o);}}this.connectionIdsByPeer.delete(e);let i=this.remoteState.get(e);if(i){for(let r of i.keys())for(let o of this.stateListeners.get(r)??[])o(e,null);this.remoteState.delete(e);}let n=this.mediaConnections.get(e);this.mediaConnections.delete(e);let s=n?.close().catch(()=>{})??Promise.resolve();this.mediaRetirements.set(e,s),s.finally(()=>{this.mediaRetirements.get(e)===s&&this.mediaRetirements.delete(e);}),this.peerStreams.closePeer(e);for(let r of this.closeListeners.get(e)??[])r();this.closeListeners.delete(e),this.rawListeners.delete(e);for(let r of this.connectionListeners.values())r.delete(e);return s}receive(e,t){if(this.closed)return;this.add(e);let i=this.rawConnections.get(e.id)?.peerId??e.remoteNodeId??e.id;if(this.roomFanout?.receive(e,i,t))return;let n=B(t);if(!n){for(let s of this.rawListeners.get(i)??[])s(t);return}if(n.capability===this.capabilityKey){if(n.kind==="raw"){for(let s of this.rawListeners.get(i)??[])s(n.value);return}this.deliverEnvelope(i,n);}}deliverEnvelope(e,t){if(this.closed)return;if(t.kind==="raw"){for(let n of this.rawListeners.get(e)??[])n(t.value);return}if(t.kind==="channel"){for(let n of this.channelListeners.get(t.name)??[])n(e,t.value);return}let i=this.remoteState.get(e);i||this.remoteState.set(e,i=new Map),i.set(t.name,t.value);for(let n of this.stateListeners.get(t.name)??[])n(e,t.value);}sendState(e,t,i){let n=this.stateSenders.get(e);n||this.stateSenders.set(e,n=new Map);let s=n.get(t);s||(s=new a$1(r=>e.send(r)),n.set(t,s)),s.send(i).catch(()=>{});}},T=class{constructor(e,t,i,n,s){this.kind=e;this.id=t;this.client=i;this.onClosed=n;this.roomFanoutFactory=s;this.closed=false;this.retired=false;this.shutdownAttempt=null;w.set(this,i);}get peers(){return this.client.peers}get channels(){return this.client.channels}get diagnostics(){return this.client.diagnostics}state(e){return this.capabilityMessages().state(e)}channel(e){return this.capabilityMessages().channel(e)}onConnection(e){return this.capabilityMessages().onConnection(e)}projectRuntime(e){w.set(this,e);}setArchitecture(e){this.roomFanoutFactory?.setArchitecture(e);}close(){if(this.retired)return Promise.resolve();if(this.shutdownAttempt)return this.shutdownAttempt;this.fenceProductAccess();let e=this.releaseCapability();return this.shutdownAttempt=e,e.then(()=>{this.shutdownAttempt===e&&(this.shutdownAttempt=null);},()=>{this.shutdownAttempt===e&&(this.shutdownAttempt=null);}),e}beforeRuntimeShutdown(){}fenceProductAccess(){this.closed=true,this.messages?.fence();}async releaseCapability(){let e=[];try{this.beforeRuntimeShutdown();}catch(t){e.push(t);}try{await this.messages?.close();}catch(t){e.push(t);}try{await this.client.advanced.runtime.shutdown();}catch(t){e.push(t);}if(e.length===1)throw e[0];if(e.length)throw d(a.INTERNAL,"[OpenRTC] Capability cleanup failed.",{cause:e,retryable:true,plane:"internal"});this.onClosed(),w.delete(this),this.retired=true;}capabilityMessages(){if(this.closed)throw new Error("[OpenRTC] Capability is closed.");return this.messages??(this.messages=new G(this.client,b$2(this.kind,this.id).key,this.roomFanoutFactory))}},K=class extends T{constructor(t,i,n,s){super("space",t,i,n);this.delivery=s;this.kind="space";this.leave=()=>this.close();}},E=class extends T{constructor(t,i,n,s,r,o){super("ticket",t,i,n);this.token=s;this.ownsMesh=o;this.kind="ticket";this.closing=null;this.inviteListeners=new Set;this.stopInviteWatch=()=>{};this.meshStopped=false;if(this.currentInvite=r,o){let c=i.advanced.runtime;this.stopInviteWatch=c.watchTicketMeshInvite?.(t,d=>{this.closed||(this.currentInvite=d,this.inviteListeners.forEach(h=>h(d)));})??this.stopInviteWatch;}}get invite(){return this.closed?null:this.currentInvite}watchInvite(t){return this.closed?(t(null),()=>{}):(this.inviteListeners.add(t),t(this.currentInvite),()=>this.inviteListeners.delete(t))}async issuerNode(){if(this.closed)throw new Error("[OpenRTC] Capability is closed.");if(!this.ownsMesh)throw new Error("[OpenRTC] This ticket is not a mesh.");return this.client.advanced.runtime.ticketMeshIssuerNode(this.id)}get peers(){if(this.scopedPeers)return this.scopedPeers;let t=this.client.peers,i=`ticket:${this.id}`,n=r=>!this.closed&&r.scopes.includes(i)&&r.status==="connected"&&r.settledReady===true&&r.routable!==false&&r.logicalSessionTerminal!==true&&(!this.ownsMesh||this.client.advanced.runtime.isTicketMeshPeerReady(this.id,r)),s=(r,o)=>{let c=[],d=this.ownsMesh?this.client.advanced.runtime.watchTicketMeshPeers(this.id,()=>o(c.filter(n))):()=>{},h=t[r](l=>{c=l,o(l.filter(n));});return ()=>{h(),d();}};return this.scopedPeers={...t,watch:r=>s("watch",r),watchLifecycle:r=>s("watchLifecycle",r),get:r=>{let o=t.get(r);return o&&n(o)?o:void 0},listConnected:()=>t.listConnected().filter(n)}}get diagnostics(){if(this.scopedDiagnostics)return this.scopedDiagnostics;let t=this.client.diagnostics,i=`ticket:${this.id}`;return this.scopedDiagnostics={...t,capture:n=>c(s=>this.client.advanced.runtime.watchPeerStates(r=>s(this.closed?[]:r.filter(o=>o.scopes.includes(i)))),n),watchConnectionMetrics:n=>t.watchConnectionMetrics(s=>{n(this.closed?[]:s.filter(r=>r.scopes?.includes(i)));})}}close(){if(this.retired)return Promise.resolve();if(this.closing)return this.closing;this.fenceProductAccess();let t=this.closeOnce();return this.closing=t,t.catch(()=>{!this.retired&&this.closing===t&&(this.closing=null);}),t}async closeOnce(){this.ownsMesh&&!this.meshStopped&&(await this.client.advanced.runtime.closeTicketMesh(this.id),this.meshStopped=true),await super.close();}beforeRuntimeShutdown(){try{this.stopInviteWatch(),this.stopInviteWatch=()=>{};}finally{this.inviteListeners.clear();}}},k=class k{constructor(e,t){this.options=e;this.internals=t;this.diagnosticClientRef=++k.nextDiagnosticClient;this.nextDiagnosticOperation=0;this.channels=new H;this.broadcastSessions=new Set;this.broadcastPublishers=new Set;this.handles=new Set;this.activations=new Map;this.pendingCapabilityShutdowns=new Map;this.authorityCallableIds=new WeakMap;this.nextAuthorityCallableId=1;this.closed=false;this.closing=null;this.offline={support:async()=>(this.assertOpen(),this.internals.offlineSupport?.()??{provisioning:false,localMesh:false,cloudRequired:false,reason:"Browser-only OpenRTC cannot host the native LAN/Iroh offline runtime."}),createEnrollmentRequest:async e=>{if(this.assertOpen(),!this.internals.createOfflineEnrollmentRequest)throw new Error("[OpenRTC] Offline enrollment request signing requires a native Rust host.");return this.internals.createOfflineEnrollmentRequest({trustDomain:e.trustDomain,deviceId:await this.deviceId(),requestedRoles:e.requestedRoles})}};this.devices={localId:()=>(this.assertOpen(),this.deviceId()),start:(e={})=>{let t=e.auth??this.options.auth;return this.activateOnce("devices",JSON.stringify({autoConnect:e.autoConnect??"online",autoConnectExcludedDeviceIds:oe(e.autoConnectExcludedDeviceIds),maxPeers:e.maxPeers??null,advancedFanout:e.advancedFanout===true,profile:e.profile??null}),t,()=>this.startDevices(e))},listEnrolled:async(e={})=>{this.assertOpen();let t=e.auth??this.options.auth;if(!t)throw new Error("[OpenRTC] devices.listEnrolled() requires an auth provider.");let i=await(await this.controlPlane()).listEnrolledDevices(t,await this.deviceId()),{DeviceHandle:n}=await import('./deviceHandle-URNIFFXC.js');for(let s of this.handles)s instanceof n&&s.replaceEnrolledDevices(i);return i},revoke:async(e,t={})=>{this.assertOpen();let i=t.auth??this.options.auth;if(!i)throw new Error("[OpenRTC] devices.revoke() requires an auth provider.");let n=re(e),s=await this.deviceId();await(await this.controlPlane()).revokeDevice(i,s,n);let{DeviceHandle:r}=await import('./deviceHandle-URNIFFXC.js');for(let o of this.handles)o instanceof r&&o.removeEnrolledDevice(n);n===s&&this.retireAuthCapabilities(i);},revokeAll:async(e={})=>{this.assertOpen();let t=e.auth??this.options.auth;if(!t)throw new Error("[OpenRTC] devices.revokeAll() requires an auth provider.");if(await(await this.controlPlane()).revokeAllDevices(t,await this.deviceId(),e.exceptCurrent===true),e.exceptCurrent===true){let i=await this.deviceId(),{DeviceHandle:n}=await import('./deviceHandle-URNIFFXC.js');for(let s of this.handles)s instanceof n&&s.retainCurrentEnrolledDevice(i);}e.exceptCurrent!==true&&this.retireAuthCapabilities(t);}};this.spaces={join:(e,t={})=>this.activateOnce(`space:${y(e)}`,JSON.stringify({payload:t.payload??"reliable",identity:t.identity??null,maxPeers:t.maxPeers??null,advancedFanout:t.advancedFanout===true}),void 0,()=>this.joinSpace(e,t))};this.rooms={join:async(e,t={})=>(await import('./room-7ZEAAY7Z.js')).joinRoom(this,e,t)};this.tickets={issue:(e,t={})=>this.activateOnce(`ticket:${y(e)}`,we(t),void 0,()=>this.issueTicket(e,t),t.mesh===true?()=>ae(y(e)):void 0),join:e=>{let t=b$4(e);return t.mesh?this.activateOnce(`ticket:${y(t.id)}`,`join:${e}`,void 0,()=>this.joinTicket(e),()=>ae(y(t.id))):Promise.reject(d(a.TICKET_INVITE_INVALID,"[OpenRTC] This invitation does not describe a ticket mesh.",{retryable:false,plane:"admission"}))}};this.liveSession=null;this.liveRetirementConfirmed=false;this.liveOpening=null;this.live={open:async e=>{if(this.assertOpen(),this.liveOpening||this.liveSession&&!this.liveRetirementConfirmed)throw new Error("[OpenRTC] A live session is already active on this root.");if(!e||typeof e.credentials!="function"||!this.internals.liveHostFactory)throw new Error("[OpenRTC] Live coordination requires an app credential provider and a supported host.");let t={canceled:false,retirementUnconfirmed:false,host:void 0};this.liveOpening=t;try{let i=new URL("/v3/live",(this.internals.endpoints??a$2).gateway).toString(),n=await this.internals.liveHostFactory(i,this.internals.testingAllowInsecureLoopback===!0);if(t.host=n,t.canceled)throw await n.close(),new Error("[OpenRTC] Live activation was closed.");if(await n.open(e),t.canceled)throw await n.close(),new Error("[OpenRTC] Live activation was closed.");let s=new Set,r=new Set,o=l=>{try{l();}catch{}},c=n.onEvent(l=>{if(l.type==="message")for(let u of s)o(()=>u(Object.freeze({channel:l.channel,from:l.from,data:l.data})));if(l.type==="closed"){this.liveSession===h&&(this.liveRetirementConfirmed=!0);for(let u of r)o(u);s.clear(),r.clear();}}),d=l=>{if(typeof l!="string"||!/^[A-Za-z0-9_.:@/-]{1,128}$/.test(l))throw new Error("[OpenRTC] Invalid live channel.");return l},h={get closed(){return n.closed},renew:()=>n.renew(),subscribe:async l=>{await n.request({type:"subscribe",channel:d(l)});},unsubscribe:async l=>{await n.request({type:"unsubscribe",channel:d(l)});},publish:async(l,u)=>{if(typeof u!="string"||new TextEncoder().encode(u).byteLength>65536)throw new Error("[OpenRTC] Live publication exceeds 64 KiB.");let p=await n.request({type:"publish",channel:d(l),data:u});if(!Number.isSafeInteger(p.units)||p.units<1)throw new Error("[OpenRTC] Invalid live publication receipt.");return {units:p.units}},onMessage:l=>(n.closed||s.add(l),()=>{s.delete(l);}),onClose:l=>(n.closed?o(l):r.add(l),()=>{r.delete(l);}),close:async()=>{await n.close(),this.liveSession===h&&(this.liveRetirementConfirmed=!0),c(),s.clear(),r.clear();}};return this.liveSession=h,this.liveRetirementConfirmed=!1,h}catch(i){try{await t.host?.close();}catch(n){throw t.retirementUnconfirmed=true,n}throw i}finally{this.liveOpening===t&&!t.retirementUnconfirmed&&(this.liveOpening=null);}}};this.broadcasts={create:async e=>{this.assertOpen();let t=await this.broadcastHost();if(!t?.create)throw new Error("[OpenRTC] Managed broadcast creation is unavailable.");return t.create(e)},open:async e=>{this.assertOpen(),this.validateBroadcastGrant(e);let t=await this.broadcastHost();if(!t)throw new Error("[OpenRTC] Broadcast hosting is unavailable in this runtime.");return this.wrapBroadcastSession(await t.open(e))},subscribe:async e=>{this.assertOpen(),this.validateBroadcastGrant(e);let t=await this.broadcastHost();if(!t)throw new Error("[OpenRTC] Broadcast viewing is unavailable.");return this.wrapBroadcastSession(await t.open(e))},preparePublisher:async()=>{this.assertOpen();let e=await this.broadcastHost();if(!e?.preparePublisher)throw new Error("[OpenRTC] Broadcast publishing is unavailable in this runtime.");let t=await e.preparePublisher(),i=t.verificationKey.slice();if(i.byteLength!==32)throw await t.close(),new Error("[OpenRTC] Broadcast publisher key is invalid.");let n=false,s={verificationKey:i,open:async r=>{if(n)throw new Error("[OpenRTC] Broadcast publisher is closed.");return this.assertOpen(),this.validateBroadcastGrant(r),this.wrapBroadcastSession(await t.open(r))},close:async()=>{n||(n=true,await t.close(),this.broadcastPublishers.delete(s));}};return this.broadcastPublishers.add(s),s},renew:async(e,t={})=>{this.validateBroadcastGrant(e);let i=await this.broadcastHost();if(!i?.renew)throw new Error("[OpenRTC] Broadcast renewal is unavailable.");return i.renew(e,t.auth)},invite:async(e,t)=>{this.validateBroadcastGrant(e);let i=await this.broadcastHost();if(!i?.invite)throw new Error("[OpenRTC] Broadcast invitations are unavailable.");let{auth:n,...s}=t;return i.invite(e,s,n)},accept:async(e,t={})=>{if(!/^obi1\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/.test(e))throw new Error("[OpenRTC] Broadcast invitation is invalid.");let i=await this.broadcastHost();if(!i?.accept)throw new Error("[OpenRTC] Broadcast invitation acceptance is unavailable.");return i.accept(e,t.auth)},revoke:async(e,t)=>{if(this.validateBroadcastGrant(e),!/^obi1\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/.test(t.invite))throw new Error("[OpenRTC] Broadcast invitation is invalid.");let i=await this.broadcastHost();if(!i?.revoke)throw new Error("[OpenRTC] Broadcast revocation is unavailable.");await i.revoke(e,t.invite,t.auth);},leave:async(e,t={})=>{this.validateBroadcastGrant(e);let i=await this.broadcastHost();if(!i?.leave)throw new Error("[OpenRTC] Broadcast leave is unavailable.");await i.leave(e,t.auth);},close:async(e,t={})=>{this.validateBroadcastGrant(e);let i=await this.broadcastHost();if(!i?.closeGrant)throw new Error("[OpenRTC] Broadcast close is unavailable.");await i.closeGrant(e,t.auth);}};this.onClosed=e=>{this.handles.delete(e);for(let[t,i]of this.activations)i.handle===e&&this.activations.delete(t);};this.apiKey="profile"in e&&e.profile==="live"?"":me(e.apiKey??"");let i=e.trust?.browserPersistence??"session";if(i!=="session"&&i!=="persistent")throw new Error("[OpenRTC] Invalid browser identity persistence policy.");this.browserPersistence=i,this.appTag=this.apiKey?`app_${this.apiKey.slice(-16)}`:"";}validateBroadcastGrant(e){if(typeof e!="string"||e.length<16||e.length>32768)throw new Error("[OpenRTC] Broadcast grant is invalid.")}broadcastHost(){return this.internals.broadcastHost?Promise.resolve(this.internals.broadcastHost):this.internals.broadcastHostFactory?this.broadcastHostPromise??(this.broadcastHostPromise=this.controlPlane().then(e=>this.internals.broadcastHostFactory({apiKey:this.apiKey,resolve:(t,i)=>e.resolveBroadcastAccess(t,i),manage:e.manageBroadcast.bind(e),deviceId:()=>this.deviceId(),defaultAuth:this.options.auth}))):Promise.resolve(void 0)}wrapBroadcastSession(e){let t=false,i={get id(){return e.id},get role(){return e.role},get state(){return e.state},media:e.media,getStats:()=>e.getStats(),close:async()=>{t||(t=true,this.broadcastSessions.delete(i),await e.close());}};return this.broadcastSessions.add(i),i}makeControlPlane(e){return Promise.all([import('./controlPlane-45AU3CSM.js'),e]).then(([{ControlPlane:t},i])=>new t(this.apiKey,this.internals.endpoints??a$2,i,this.options.trust?.attestation,{onAuthEpochChanged:n=>this.retireAuthCapabilities(n)},this.options.trust?.botVerification))}controlPlane(){if("profile"in this.options&&this.options.profile==="live")throw new Error("[OpenRTC] This live-only root does not activate managed devices, rooms or peers.");return this.controlPlanePromise??(this.controlPlanePromise=this.makeControlPlane(this.internals.deviceKeyProvider?Promise.resolve(this.internals.deviceKeyProvider):import('./deviceKey-2NTRYCSR.js').then(({browserDeviceKeyProvider:e,createSessionDeviceKeyProvider:t})=>this.internals.platform!=="native"&&this.browserPersistence!=="persistent"?t():e)))}sessionPlane(){if("profile"in this.options&&this.options.profile==="live")throw new Error("[OpenRTC] This live-only root does not activate managed devices, rooms or peers.");return this.sessionPlanePromise??(this.sessionPlanePromise=this.makeControlPlane(import('./deviceKey-2NTRYCSR.js').then(({createSessionDeviceKeyProvider:e})=>e())))}assertOpen(){if(this.closed)throw new Error("[OpenRTC] Client is closed.");if(this.closing)throw new Error("[OpenRTC] Client is closing.")}activateOnce(e,t,i,n,s){this.assertOpen();let r=this.activations.get(e);if(r){if(r.handle?.closed)throw new Error(`[OpenRTC] ${e} is closing; retry close() to finish retirement.`);if(r.fingerprint!==t||r.auth!==i)throw s?s():new Error(`[OpenRTC] ${e} is already active with different options.`);return r.promise}let o={fingerprint:t,auth:i},c=this.options.diagnostics?.logger,d=c?performance.now():0,h=c?++this.nextDiagnosticOperation:0,l=e.split(":",1)[0],u=["devices","space","room","ticket"].includes(l)?l:"custom",p=f=>{c&&b$6(c,Object.freeze({sdkVersion:a$4,clientRef:this.diagnosticClientRef,name:"capability.activation",operationRef:h,avenue:u,outcome:f,timestampMs:Date.now(),elapsedMs:performance.now()-d}));},g;try{g=this.pendingCapabilityShutdowns.has(e)?this.settlePendingCapabilityShutdown(e).then(n):n();}catch(f){throw p("started"),p("failed"),f}let z=g.then(f=>(o.handle=f,p("succeeded"),f)).catch(f=>{throw p("failed"),this.activations.get(e)===o&&this.activations.delete(e),f});return o.promise=z,this.activations.set(e,o),p("started"),z}retainPendingCapabilityShutdown(e,t){this.pendingCapabilityShutdowns.has(e)||this.pendingCapabilityShutdowns.set(e,t);}async settlePendingCapabilityShutdown(e){let t=this.pendingCapabilityShutdowns.get(e);t&&(await t(),this.pendingCapabilityShutdowns.get(e)===t&&this.pendingCapabilityShutdowns.delete(e));}authorityCallableId(e){let t=this.authorityCallableIds.get(e);if(t)return t;let i=this.nextAuthorityCallableId++;return this.authorityCallableIds.set(e,i),i}retireAuthCapabilities(e){for(let t of this.activations.values())t.auth===e&&t.promise.then(i=>i.close()).catch(()=>{});}async deviceId(){let e=this.internals.deviceIdProvider?await this.internals.deviceIdProvider(this.appTag):this.internals.platform!=="native"&&this.browserPersistence==="session"?this.sessionDeviceId??(this.sessionDeviceId=crypto.randomUUID()):ye(this.appTag);return re(e)}runtimeOptions(e){let t=this.options.transports,i=e.irohRelay&&t?.relay!==false,n=e.managedTurn&&t?.relay!==false,s=t?.privacy==="relay-only";if(s&&!i)throw new Error("[OpenRTC] transports.privacy: relay-only requires relay access.");let r=s?d$1(t?.priority?[...t.priority]:void 0,true):t?.priority?[...t.priority]:void 0,o=t?.webrtc,c=typeof o=="object"&&o.iceServers?.some(b$5)===true,d=!s||n||c;return {apiKey:this.apiKey,authMode:"external",discoveryMode:e.avenue?.kind==="user"?"user-scoped":"space",space:e.avenue?.id,localDeviceId:e.deviceId,deviceIdPersistence:"persistent",endpointIdPersistence:this.internals.platform==="native"?"persistent":"ephemeral",deviceName:e.deviceName?.trim()||void 0,coordinationPlatformType:e.devicePlatform?.trim()||void 0,initialAutoConnectExcludedDeviceIds:e.initialAutoConnectExcludedDeviceIds,nativeIdentityProvider:this.internals.platform==="native"&&e.nativeAuth?{providerId:e.nativeAuth.providerId,getSessionKey:async()=>e.nativeAuth.getSessionKey?.()??null,getAssertion:h=>e.nativeAuth.getAssertion(h)}:void 0,coordinationAvenueOverride:e.avenue,coordinationRoomGossipFanout:e.roomGossipFanout===true,coordinationRoomArchitecture:e.roomArchitecture,coordinationDevicePublicKeyX:e.devicePublicKeyX,coordinationDeviceSign:e.deviceSign,coordinationGateway:{endpoint:(this.internals.endpoints??a$2).gateway,environment:"production",grantProvider:e.grantProvider,onServiceError:this.options.onServiceError,testingAllowInsecureLoopback:this.internals.testingAllowInsecureLoopback},turnCredentialsProvider:n?e.turnProvider:void 0,transports:{relay:i,iroh:s?{relayOnly:true,relayTransportPolicy:"websocketRequired",localDiscovery:false,persistenceMode:this.internals.platform==="native"?"persistent":"ephemeral",...this.internals.irohTestRelayUrl?{testRelayUrl:this.internals.irohTestRelayUrl}:{}}:this.internals.irohTestRelayUrl?{testRelayUrl:this.internals.irohTestRelayUrl,persistenceMode:this.internals.platform==="native"?"persistent":"ephemeral"}:t?.iroh??true,webrtc:d?typeof o=="object"?s?{...o,privacyMode:true,useTurn:true,useDefaultIceServers:false}:o:o===true?s?{privacyMode:true,useTurn:true,useDefaultIceServers:false}:true:false:false,ble:t?.ble??false,moq:i?t?.moq??false:false,privacy:t?.privacy??"direct",optimizeFor:t?.optimizeFor??"balanced",priority:r},transportPriority:r}}async activate(e){let t=e.authority?null:e.controlPlane??await this.controlPlane(),i=this.options.transports?.relay!==false,n=e.source.irohRelay&&i,s=e.source.managedTurn&&i,r={irohRelay:n,managedTurn:s,moq:n&&!!this.options.transports?.moq,ble:this.options.transports?.ble===true,advancedFanout:e.architecture==="sparse"||e.advancedFanout===true,durableMembership:e.durableMembership===true},o=e.source,c=null,d=()=>e.authority?{userId:e.principalId}:{userId:e.principalId,token:o.token,tokenProvider:async()=>o.token,expiresAtMs:o.expiresAtMs},h=e.authority?.devicePublicKeyX??String((await t.deviceSigningPublicKey()).x??""),l=this.runtimeOptions({avenue:e.source.avenue,grantProvider:e.authority?.grantProvider??t.grantProvider(e.source,{maxPeers:e.maxPeers,features:r,architecture:e.architecture,roomDelivery:e.kind==="room"?e.defaultDelivery:void 0,deviceProfile:e.deviceName&&e.devicePlatform?{name:e.deviceName,platform:e.devicePlatform}:void 0,onSourceRenewed:async g=>{o={...o,...g},await c?.setAuth(d());}}),deviceId:e.deviceId,userId:e.principalId,roomGossipFanout:(e.kind==="room"||e.kind==="space")&&(e.architecture==="sparse"||e.advancedFanout===true),roomArchitecture:e.kind==="room"?e.architecture:void 0,devicePublicKeyX:h,deviceSign:e.authority?.deviceSign??(g=>t.signDeviceBytes(g)),irohRelay:e.source.irohRelay,managedTurn:e.source.managedTurn,turnProvider:s&&t?t.turnProvider(()=>o):void 0,deviceName:e.deviceName,devicePlatform:e.devicePlatform,initialAutoConnectExcludedDeviceIds:e.initialAutoConnectExcludedDeviceIds,nativeAuth:e.nativeAuth}),[u,{wrapAssembly:p}]=await Promise.all([this.internals.runtimeFactory(l),import('./coreClient.js')]);c=p(u,this.internals.platform==="native"?"native":"web"),await c.setAuth(d()),this.channels.attach(c,e.defaultDelivery??"reliable");try{await c.devices.startSession({browserTrustPersistence:this.browserPersistence,sessionKind:e.kind==="devices"?"app-user-device":"scoped-guest",scope:`v2:${e.kind}:${e.id}`,userId:e.principalId,localDeviceId:e.deviceId,metadata:e.deviceMetadata,autoConnectPolicy:e.autoConnect?"enabled":"disabled",presencePolicy:"online"});}catch(g){throw this.channels.detach(c),await c.advanced.runtime.shutdown().catch(()=>{}),g}return c}trackHandle(e){return this.handles.add(e),e}async startDevices(e={}){this.assertOpen();let t=oe(e.autoConnectExcludedDeviceIds),i=e.auth??this.options.auth;if(!i)throw new Error("[OpenRTC] devices.start() requires an auth provider.");let n=await this.deviceId(),{resolveDeviceProfile:s}=await import('./deviceProfile-CR2C7OYR.js'),r=s(e.profile,this.internals.platform==="native"?"native":"web"),o=await this.controlPlane(),c=await o.deviceCertificate(i,n,void 0,r),d=await this.activate({kind:"devices",id:c.principalId,source:c.source,principalId:c.principalId,deviceId:n,maxPeers:e.maxPeers,autoConnect:e.autoConnect!=="none",initialAutoConnectExcludedDeviceIds:t,advancedFanout:e.advancedFanout,deviceName:r.name,devicePlatform:r.platform,deviceMetadata:r.metadata,nativeAuth:i}),h=[];if(this.internals.platform!=="native")try{h=await o.listEnrolledDevices(i,n);}catch(g){throw this.channels.detach(d),await d.advanced.runtime.shutdown().catch(()=>{}),g}let{AuthenticatedDeviceRoster:l}=await import('./deviceRoster-EUF6BBF5.js'),{DeviceHandle:u}=await import('./deviceHandle-URNIFFXC.js'),p;return p=new u(c.principalId,d,()=>{this.channels.detach(d),this.onClosed(p);},new l(h)),this.handles.add(p),p}async joinSpace(e,t={}){this.assertOpen();let i=y(e),n=await(t.identity==="session"?this.sessionPlane():this.controlPlane()),s=await n.capability("space",i,t.maxPeers,t.advancedFanout),r=String(b$1(s.token).principalId),o=await this.activate({kind:"space",id:i,source:s,principalId:r,deviceId:N(s),maxPeers:t.maxPeers,autoConnect:true,defaultDelivery:t.payload??"reliable",advancedFanout:t.advancedFanout,controlPlane:n}),c;return c=new K(i,o,()=>{this.channels.detach(o),this.onClosed(c);},t.payload??"reliable"),this.handles.add(c),c}async openAuthorityRoom(e){return (await import('./room-7ZEAAY7Z.js')).openAuthorityRoom(this,e)}async issueTicket(e,t={}){this.assertOpen();let i=y(e);if(t.mesh===true&&t.advancedFanout===true)throw d(a.TICKET_MESH_INVALID_OPTIONS,"[OpenRTC] Ticket mesh cannot use advancedFanout.",{retryable:false,plane:"admission"});let n=le(t);if(t.mesh===true&&(!Number.isSafeInteger(n)||n<ne||n>U))throw d(a.TICKET_MESH_INVALID_OPTIONS,`[OpenRTC] Ticket mesh maxPeers must be an integer between ${ne} and ${U}.`,{retryable:false,plane:"admission"});let s=await(t.identity==="session"||t.mesh===true?this.sessionPlane():this.controlPlane()),r=await s.capability("ticket",i,n,t.advancedFanout),o=String(b$1(r.token).principalId),c=await this.activate({kind:"ticket",id:i,source:r,principalId:o,deviceId:N(r),maxPeers:n,autoConnect:false,advancedFanout:t.advancedFanout,controlPlane:s}),d$1=null;if(t.mesh===true)try{d$1=await c.advanced.runtime.issueTicketMesh(i,n);}catch(l){await this.shutdownFailedTicketActivation(i,c,l);}let h;return h=new E(i,c,()=>{this.channels.detach(c),this.onClosed(h);},r.token,d$1,t.mesh===true),this.handles.add(h),h}async joinTicket(e){this.assertOpen();let t=b$4(e);if(!t.mesh)throw d(a.TICKET_INVITE_INVALID,"[OpenRTC] This invitation does not describe a ticket mesh.",{retryable:false,plane:"admission"});let i=y(t.id),n=await this.sessionPlane(),s=await n.capability("ticket",i,t.maxPeers,false),r=String(b$1(s.token).principalId),o=await this.activate({kind:"ticket",id:i,source:s,principalId:r,deviceId:N(s),maxPeers:t.maxPeers,autoConnect:false,advancedFanout:false,controlPlane:n});try{await o.advanced.runtime.joinTicketMesh(e);}catch(d){await this.shutdownFailedTicketActivation(i,o,d);}let c;return c=new E(i,o,()=>{this.channels.detach(o),this.onClosed(c);},s.token,e,true),this.handles.add(c),c}async shutdownFailedTicketActivation(e,t,i){this.channels.detach(t);try{await t.advanced.runtime.shutdown();}catch(n){throw this.retainPendingCapabilityShutdown(`ticket:${e}`,()=>t.advanced.runtime.shutdown()),d(a.TICKET_MESH_UNAVAILABLE,"[OpenRTC] Ticket mesh startup failed and runtime teardown was not confirmed.",{retryable:true,plane:"coordination",cause:{startError:i,shutdownError:n}})}throw i}async close(){if(this.closed)return;if(this.closing)return this.closing;let e=this.closeOnce();this.closing=e;try{await e;}finally{this.closing===e&&(this.closing=null);}}async closeOnce(){if(this.liveOpening){let e=this.liveOpening;e.canceled=true,await e.host?.close(),this.liveOpening===e&&(this.liveOpening=null);}await this.liveSession?.close(),await Promise.allSettled([...this.activations.values()].map(({promise:e})=>e)),await Promise.all([...this.handles].map(e=>e.close())),await Promise.all([...this.pendingCapabilityShutdowns.keys()].map(e=>this.settlePendingCapabilityShutdown(e))),await Promise.all([...this.broadcastSessions].map(e=>e.close())),await Promise.all([...this.broadcastPublishers].map(e=>e.close())),await Promise.all([this.controlPlanePromise,this.sessionPlanePromise].map(e=>e?.then(t=>t.dispose(),()=>{}))),this.activations.clear(),this.broadcastSessions.clear(),this.broadcastPublishers.clear(),await this.broadcastHostPromise?.then(e=>e?.close?.(),()=>{}),await this.internals.broadcastHost?.close?.(),await this.internals.close?.(),this.closed=true;}};k.nextDiagnosticClient=0;var D=k;function xe(a,e){return new D(a,e)}function Le(a,e){if(!(a instanceof D))throw new TypeError("[OpenRTC] ServiceNode requires a client created by this OpenRTC package.");return a.openAuthorityRoom(e)}export{R as a,B as b,pe as c,Be as d,y as e,re as f,N as g,T as h,xe as i,Le as j};
|
|
@@ -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};
|