openrtc 2.5.2 → 2.5.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{Connection-CTpuImO-.d.ts → Connection-CovQdc8E.d.ts} +30 -5
- package/dist/{DelegatingRuntimeAdapter-D67Ozqo3.d.ts → DelegatingRuntimeAdapter-3ykiNvyh.d.ts} +3 -2
- package/dist/{IpcRuntimeAdapter-Ddx0MtSI.d.ts → IpcRuntimeAdapter-BkM_1HyL.d.ts} +12 -2
- package/dist/WasmBridge-UZC7G4NP.js +1 -0
- package/dist/{assembly-LOFcpH3S.d.ts → assembly-C235UKSS.d.ts} +3 -2
- package/dist/{capabilities-CmzzxSvW.d.ts → capabilities-CdZpAKvE.d.ts} +1 -1
- package/dist/chunk-25CN4MLA.js +2 -0
- package/dist/chunk-2ESWBXLF.js +1 -0
- package/dist/{chunk-TZLNKQNJ.js → chunk-42TNJH5S.js} +1 -1
- package/dist/chunk-4CC6YIGG.js +1 -0
- package/dist/chunk-4J4F32QT.js +1 -0
- package/dist/{chunk-J7NBMQQA.js → chunk-CHT46RA7.js} +1 -1
- package/dist/chunk-VC7TGJFS.js +2 -0
- package/dist/{chunk-EFTDXE6M.js → chunk-WMA4OMJL.js} +1 -1
- package/dist/{chunk-XTYALGJN.js → chunk-XMYBBLYK.js} +1 -1
- package/dist/coreClient.d.ts +3 -3
- package/dist/coreClient.js +1 -1
- package/dist/index.d.ts +5 -5
- package/dist/index.js +1 -1
- package/dist/ipcFactory-2WMR4PH6.js +1 -0
- package/dist/native.d.ts +5 -5
- package/dist/native.js +1 -1
- package/dist/node.d.ts +5 -5
- package/dist/node.js +2 -2
- package/dist/{openrtc-SQF7H4ZE.js → openrtc-UBIKDAZ5.js} +2 -2
- package/dist/openrtc_bg.wasm +0 -0
- package/dist/{room-A2FMQRNZ.js → room-2MUFAJ4M.js} +1 -1
- package/dist/runtime/WasmRuntimeAdapter.d.ts +3 -3
- package/dist/runtime/WasmRuntimeAdapter.js +1 -1
- package/dist/runtime/device-status.d.ts +1 -1
- package/dist/runtime/factories.d.ts +6 -5
- package/dist/runtime/factories.js +1 -1
- package/dist/runtime/index.d.ts +9 -9
- package/dist/runtime/index.js +1 -1
- package/dist/server-browser.d.ts +4 -4
- package/dist/server.d.ts +4 -4
- package/dist/server.js +1 -1
- package/dist/service-node.d.ts +4 -4
- package/dist/service-node.js +1 -1
- package/dist/testing/native.d.ts +4 -4
- package/dist/testing/native.js +1 -1
- package/dist/testing.d.ts +4 -4
- package/dist/testing.js +1 -1
- package/dist/transport/index.d.ts +2 -2
- package/dist/{types-Cyc-mPjk.d.ts → types-C6SMXBzJ.d.ts} +1 -1
- package/native/darwin-arm64/openrtc-node-host +0 -0
- package/native/darwin-arm64/openrtc-node-host.manifest.json +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-LWMCETW4.js +0 -1
- package/dist/chunk-6Q2LAXM4.js +0 -1
- package/dist/chunk-AAZPQQXX.js +0 -2
- package/dist/chunk-FB5M6GIW.js +0 -2
- package/dist/chunk-PLIWPC45.js +0 -1
- package/dist/chunk-VTYVIKTM.js +0 -1
- package/dist/ipcFactory-PDVLUG2W.js +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
import {b as b$1,a as a$1}from'./chunk-ZA44REGI.js';import {b as b$3}from'./chunk-LLZT3MR6.js';import {a}from'./chunk-DUY34MGT.js';import {b as b$2,a as a$2}from'./chunk-CCCYE3XN.js';import {d as d$1,a as a$3}from'./chunk-N6LGTNUI.js';import {d,b as b$4}from'./chunk-2GX6GB6L.js';function I(o,e,t,i){let n=JSON.stringify({__openrtc:2,capability:i,kind:o,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(o){let e;try{e=o instanceof Uint8Array?JSON.parse(new TextDecoder().decode(o)):o&&typeof o=="object"?o:{};}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",ae=32,Y=16,U=4294967295,ce=/^[A-Za-z0-9][A-Za-z0-9._/+:-]{0,127}$/,le=/^([0-9a-f]{64})-([0-9a-f]{64})$/i;function A(o){let e=o?.trim()??"";if(!ce.test(e))throw new Error("[OpenRTC] stream protocol must be 1-128 safe ASCII characters.");return e}function k(o){let e=o?.trim()??"",t=le.exec(e);return t?[t[1].toLowerCase(),t[2].toLowerCase()].sort().join("-"):e}function ee(o){if(o===null||o===0)return null;if(!Number.isFinite(o)||o<0)throw new RangeError("[OpenRTC] datagram maximum age must be a non-negative finite number or null.");return Math.min(U,Math.ceil(o))}function te(o){if(!Number.isSafeInteger(o)||o<1||o>U)throw new RangeError(`[OpenRTC] datagram buffer limits must be integers from 1 to ${U}.`);return o}var L=class{constructor(e,t){this.runtime=e;this.peerId=t;this.incomingAge=null;this.outgoingAge=null;this.incomingLimit=Y;this.outgoingLimit=Y;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=ee(e),this.policy.setIncomingMaxAge(this.incomingAge??void 0,Date.now()),this.wake(this.incomingWaiters);}get outgoingMaxAge(){return this.outgoingAge}set outgoingMaxAge(e){this.outgoingAge=ee(e),this.policy.setOutgoingMaxAge(this.outgoingAge??void 0);}get incomingMaxBufferedDatagrams(){return this.incomingLimit}set incomingMaxBufferedDatagrams(e){this.incomingLimit=te(e),this.policy.setIncomingMaxBufferedDatagrams(this.incomingLimit);}get outgoingMaxBufferedDatagrams(){return this.outgoingLimit}set outgoingMaxBufferedDatagrams(e){this.outgoingLimit=te(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();}},O=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:ae});}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 O;this.incomingUni=new O;this.incomingBidirectionalStreams=this.incomingBi.readable;this.incomingUnidirectionalStreams=this.incomingUni.readable;this.closed=false;this.protocolHandlers=new Map;this.datagrams=new L(i,this.peerId);}async createBidirectionalStream(e){let t=A(e.protocol),i=await this.client.channels.openBi(this.peerId,b,{timeoutMs:e.timeoutMs,channelMetadata:{protocol:t,[a$2]:this.capabilityKey}});return {protocol:t,readable:i.readable,writable:i.writable}}async createUnidirectionalStream(e){let t=A(e.protocol);return (await this.client.channels.openUni(this.peerId,b,{timeoutMs:e.timeoutMs,channelMetadata:{protocol:t,[a$2]:this.capabilityKey}})).writable}accept(e,t){if(e.type==="bi"){let n=e.stream;if(!n.recv||!n.send)return false;let r={peerId:this.peerId,protocol:t,readable:n.recv,writable:n.send},s=this.protocolHandlers.get(t);if(s){try{s(r);}catch{r.readable.cancel("incoming-protocol-handler-failed").catch(()=>{}),r.writable.abort("incoming-protocol-handler-failed").catch(()=>{});}return true}return this.incomingBi.enqueue(r)||(r.readable.cancel("incoming-peer-stream-queue-full").catch(()=>{}),r.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=A(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();}},D=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=k(e),n=t.trim();!i||!n||this.peerIdsByConnection.set(i,n);}unbindConnection(e){this.peerIdsByConnection.delete(k(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$2]!==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=A(i);}catch{return this.declined+=1,false}let s=this.resolveExistingPeer(e.remoteNodeId,e.connectionId)?.accept(e,n)??false;return s?this.accepted+=1:this.declined+=1,s}resolveExistingPeer(e,t=""){let i=k(t);if(i){let s=this.peerIdsByConnection.get(i);if(!s)return this.lastResolution="unbound-connection",null;let a=this.peers.get(s);return a?(this.lastResolution="connection",a):(this.lastResolution="unbound-connection",null)}let n=this.peers.get(e);if(n)return this.lastResolution="remote-peer",n;let r=this.client.peers.get(e)??this.client.peers.listConnected().find(s=>[s.peerId,s.deviceId,s.deviceIdHint,s.connectionId,...s.connectionIds].some(a=>a===e));if(r){let s=new Set([r.peerId,r.deviceId,r.deviceIdHint,r.connectionId,...r.connectionIds].filter(c=>typeof c=="string"&&c.length>0)),a=[...this.peers.entries()].filter(([c])=>s.has(c)).map(([,c])=>c);if(a.length===1)return this.lastResolution="peer-alias",a[0]}return this.lastResolution="none",null}};var _={"identity.assertion.exchange":25692e-8,"identity.monthly-active-principal":110352e-9,"capability.issue":212346e-9,"device.enroll":218946e-9,"gateway.grant.issue":202146e-9,"gateway.grant.refresh":200346e-9,"security.attestation.verify":29694e-8,"room.create":388056e-9,"room.join":209946e-9,"room.leave":200346e-9,"broadcast.control":271938e-9,"broadcast.delivery":.1,"coordination.connection.open":58164e-8,"coordination.credential.refresh":367734e-9,"coordination.lease.refresh":27987e-8,"coordination.presence.upsert":27771e-8,"coordination.presence.offline":27171e-8,"coordination.signal.send":27771e-8,"coordination.managed.publish":473688e-9,"coordination.managed.keypackage.publish":271908e-9,"coordination.managed.commit.chunk":295182e-9,"coordination.managed.commit.ack":271908e-9,"coordination.managed.control":.001122582,"coordination.managed.prepare.page":26718e-8,"coordination.authority.assignment":370866e-9,"coordination.session.put":27771e-8,"coordination.session.delete":27171e-8,"coordination.usage.ingest":197088e-9};var y=new WeakMap;function de(o){let e=y.get(o);if(!e||o.closed)throw new Error("[OpenRTC] Capability runtime is unavailable or already closed.");return e}function xe(o,e){if(y.has(o))throw new Error("[OpenRTC] Capability runtime is already registered.");return y.set(o,de(e)),()=>{y.delete(o);}}function ue(o){let e=o?.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 T(o){let e=o?.trim()??"";if(!e||e.length>160||!/^[A-Za-z0-9_.:@-]+$/.test(e))throw new Error("[OpenRTC] Capability id is invalid.");return e}var z=/^[A-Za-z0-9_.:@-]{1,160}$/,he=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;function me(o){let e=typeof o=="string"?o.trim():"";if(!z.test(e))return null;let t=e.startsWith("device_")?e.slice(7):"";return he.test(t)?t:e}function pe(o){let e=`openrtc:v2:device-id:${o}`,t,i=(()=>{try{return t=globalThis.localStorage,me(t?.getItem(e))||crypto.randomUUID()}catch{return crypto.randomUUID()}})();try{t?.setItem(e,i);}catch{}return i}function ie(o){let e=typeof o=="string"?o.trim():"";if(!z.test(e))throw new Error("[OpenRTC] The native host returned an invalid durable device ID.");return e}var ne=250;function re(o){if(o===void 0)return [];if(!Array.isArray(o))throw new Error("[OpenRTC] autoConnectExcludedDeviceIds must be an array.");let e=[...new Set(o.map(t=>{let i=typeof t=="string"?t.trim().toLowerCase():"";if(!z.test(i))throw new Error("[OpenRTC] autoConnectExcludedDeviceIds contains an invalid device ID.");return i}))].sort();if(e.length>ne)throw new Error(`[OpenRTC] autoConnectExcludedDeviceIds supports at most ${ne} devices.`);return e}function oe(o){let e=b$1(o.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 N=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);}},K=class{constructor(e){this.options=e;this.total=0;this.warned=false;}get sessionCreditsUsd(){return this.total}estimate(e){let t=e.units??1,i=Number.isFinite(t)?Math.max(0,t):0;return {creditsUsd:(_[e.operation]??0)*i,estimated:true}}estimateRoom(e){let t=G(e.maxMembers,"maxMembers",1,Number.MAX_SAFE_INTEGER);if(t>50)throw f(`[OpenRTC] Room architecture is unavailable for ${t} members in this release; the limit is 50.`);let i=G(e.durationSeconds,"durationSeconds",1,744*60*60),n=G(e.maxPayloadBytes,"maxPayloadBytes",0,1048576),r=ge(e.maxMessagesPerSecond,"maxMessagesPerSecond",0,1e4),s=ve(e.architecture),a=ye(s,t,e.delivery),l=fe(a,t)*r*i*n/1e9,d=Math.floor(i/3300),u=h("capability.issue")+h("gateway.grant.issue")+h("room.join")+h("coordination.connection.open")+h("coordination.presence.upsert")+h("room.leave")+h("coordination.presence.offline")+d*h("coordination.lease.refresh"),m=t*u,v=r*i,p=Math.max(0,Math.ceil(t/4)-1),P=a==="managed"?v*h("coordination.managed.publish")+t*h("coordination.managed.keypackage.publish")+t*h("coordination.managed.commit.ack")+t*h("coordination.managed.commit.chunk")+h("coordination.managed.control")+p*h("coordination.managed.prepare.page"):a==="authority"?t*Math.ceil(i/120)*h("coordination.authority.assignment"):0,g=l*h("broadcast.delivery");return {architecture:s,effectiveArchitecture:a,creditsUsd:Math.ceil((m+P+g)*1e12)/1e12,estimated:true,expiresAtMs:Date.now()+5*6e4,assumptions:["Every declared member obtains one capability and gateway grant, joins once, publishes presence, and retires once during the quote window.",`Each continuously connected member is quoted for ${d} successful 55-minute lease renewal${d===1?"":"s"}.`,"Room-wide payload is conservatively quoted as fully hosted or relayed.","Payload delivery uses the published customer value of $0.10 per decimal GB.",a==="managed"?"Managed control assumes initial group setup, maximum-size KeyPackage paging, bounded artifact chunks, exactly one room-wide transition settlement, and one protected publish per declared message.":a==="authority"?"Authority control assumes one signed assignment per member every two minutes.":"Direct application payloads do not add hosted fanout operations.",a==="authority"?"Developer service-node hosting is external and is not included in OpenRTC credits.":"Unused reservations are released when authoritative settlement completes."]}}assertCanSpend(e,t=1){let i=this.options?.maxSessionCreditsUsd;if(i===void 0||this.total+this.estimate({operation:e,units:t}).creditsUsd<=i)return;let r={sessionCreditsUsd:this.total,operation:e,estimated:true,thresholdCreditsUsd:i,kind:"session-limit"};throw this.options?.onWarning?.(r),new Error("[OpenRTC] The client-side session credit limit was reached.")}record(e,t=1){let i=this.estimate({operation:e,units:t}).creditsUsd;this.total+=i;let n={sessionCreditsUsd:this.total,operation:e,estimated:true};this.options?.onUsage?.(n);let r=this.options?.warnAtSessionCreditsUsd;!this.warned&&r!==void 0&&this.total>=r&&(this.warned=true,this.options?.onWarning?.({...n,thresholdCreditsUsd:r,kind:"warning"}));}};function ve(o){return o??"auto"}function G(o,e,t,i){if(!Number.isSafeInteger(o)||o<t||o>i)throw new RangeError(`[OpenRTC] ${e} must be an integer from ${t} to ${i}.`);return o}function ge(o,e,t,i){if(!Number.isFinite(o)||o<t||o>i)throw new RangeError(`[OpenRTC] ${e} must be between ${t} and ${i}.`);return o}function h(o){let e=_[o];if(!Number.isFinite(e)||e<=0)throw new Error(`[OpenRTC] Room quote is unavailable because ${o} has no current customer-credit price.`);return e}function ye(o,e,t){if(o==="mesh"){if(e>16)throw f("[OpenRTC] Fixed mesh is limited to 16 members in this release.");return o}if(o==="sparse"){if(e>50)throw f("[OpenRTC] Fixed sparse is limited to 50 members in this release.");if(t!=="latest-state")throw f("[OpenRTC] Sparse room quotes require latest-state delivery.");return o}if(o==="managed")throw f("[OpenRTC] Managed room architecture is unavailable in this release.");if(o==="authority")return o;if(e<=8)return "mesh";if(t==="latest-state"&&e<=50)return "sparse";throw f(`[OpenRTC] Reliable automatic room architecture is unavailable for ${e} members in this release.`)}function f(o){return d$1(a$3.ROOM_ARCHITECTURE_UNAVAILABLE,o,{retryable:false,plane:"admission"})}function fe(o,e){if(e<=1)return 0;if(o!=="sparse")return e-1;let t=Math.min(4,e-1),i=e*t/2;return Math.max(e-1,i*2-(e-1))}function se(o){let e=o?.trim()??"";if(!e||e.length>80||!/^[A-Za-z0-9_.:@-]+$/.test(e))throw new Error("[OpenRTC] Message name is invalid.");return e}var H=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.mediaConnections=new Map;this.mediaRetirements=new Map;this.pendingRawConnections=new Map;this.connectionIdsByPeer=new Map;this.closed=false;this.peerStreams=new D(e,t),this.stopMessage=e.onMessage((n,r)=>this.receive(n,r)),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,r,s)=>{let a=B(r);!a||a.capability!==this.capabilityKey||s!==void 0&&a.name!==s||s===void 0&&a.kind!=="channel"||this.deliverEnvelope(n,a);}});}state(e){if(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=se(e);return {set:i=>{let n=I("state",t,i,this.capabilityKey);if(this.localState.set(t,n),!this.roomFanout?.publishState(t,n))for(let{activeRaw:r}of this.logicalConnections.values())r&&this.sendState(r,t,n);},watch:i=>{let n=this.stateListeners.get(t);n||this.stateListeners.set(t,n=new Set);let r=(s,a)=>i({peerId:s,value:a});n.add(r);for(let[s,a]of this.remoteState)a.has(t)&&i({peerId:s,value:a.get(t)});return ()=>n?.delete(r)}}}channel(e){let t=se(e),i=n=>I("channel",t,n,this.capabilityKey);return {send:async n=>{let r=i(n);await this.roomFanout?.sendChannel(t,r)||await Promise.all([...this.logicalConnections.values()].flatMap(({activeRaw:s})=>s?[s.send(r)]:[]));},sendTo:async(n,r)=>{this.roomFanout?.assertTargetedSendAllowed();let s=this.logicalConnections.get(n)?.activeRaw;if(s){await s.send(i(r));return}throw new Error(`[OpenRTC] Peer '${n}' has no direct authorized route; sparse broadcasts never multi-hop targeted payloads.`)},onMessage:n=>{let r=this.channelListeners.get(t);r||this.channelListeners.set(t,r=new Set);let s=(a,c)=>n({peerId:a,message:c});return r.add(s),()=>r?.delete(s)}}}onConnection(e){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)}async close(){if(this.closed)return;this.closed=true,this.stopMessage(),this.stopConnection(),this.stopDisconnection(),this.stopPeerLifecycle(),this.roomFanout?.close();let e=[...this.logicalConnections.keys()].map(t=>this.retire(t));this.pendingRawConnections.clear(),this.peerStreams.close(),this.rawConnections.clear(),this.connectionListeners.clear(),this.channelListeners.clear(),this.stateListeners.clear(),this.localState.clear(),await Promise.allSettled(e);}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 a={raw:e,peerId:i};this.pendingRawConnections.set(e.id,a),n.finally(()=>{this.closed||this.pendingRawConnections.get(e.id)!==a||(this.pendingRawConnections.delete(e.id),this.add(e));});return}this.rawConnections.set(e.id,{raw:e,peerId:i});let r=this.connectionIdsByPeer.get(i);r||this.connectionIdsByPeer.set(i,r=new Set),r.add(e.id),this.peerStreams.bindConnection(e.id,i);let s=this.logicalConnections.get(i);if(!s){let a=this.peerStreams.forPeer(i),c=new b$3(a,this.client.advanced.runtime,(d,u)=>this.peerStreams.onProtocol(i,d,u),()=>this.peerStreams.diagnostics());this.mediaConnections.set(i,c),s={activeRaw:e,rawIds:new Set,view:{id:i,peerId:i,streams:a,media:c,send:async d=>{let u=this.logicalConnections.get(i)?.activeRaw;if(!u)throw new Error(`[OpenRTC] Peer '${i}' is not connected.`);await u.send(I("raw","message",d,this.capabilityKey));},onMessage:d=>{let u=this.rawListeners.get(i);u||this.rawListeners.set(i,u=new Set);let m=d;return u.add(m),()=>u?.delete(m)},onClose:d=>{let u=this.closeListeners.get(i);return u||this.closeListeners.set(i,u=new Set),u.add(d),()=>u?.delete(d)}}},this.logicalConnections.set(i,s);}s.rawIds.add(e.id),s.activeRaw=e,this.observePeerLifecycle(this.client.peers.listConnected());for(let[a,c]of this.connectionListeners)c.has(i)||(c.add(i),a(s.view));for(let[a,c]of this.localState)this.sendState(e,a,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 a=[...n.rawIds],c=a[a.length-1];n.activeRaw=c?this.rawConnections.get(c)?.raw??null:null;}let r=this.connectionIdsByPeer.get(i);if(r?.delete(e.id),r?.size===0&&this.connectionIdsByPeer.delete(i),!n?.activeRaw){let a=this.remoteState.get(i);if(a){for(let c of a.keys())for(let l of this.stateListeners.get(c)??[])l(i,null);this.remoteState.delete(i);}}let s=this.stateSenders.get(e);if(s){for(let a of s.values())a.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(l=>l.peerId===t||l.connectionId===t||l.connectionIds.some(d=>i.has(d)));if(!n)continue;let r=n.status==="closed"&&n.logicalSessionTerminal===true&&n.routable!==true&&n.settledReady!==true;if(n.manualDisconnect||r){this.retire(t);continue}if(n.settledReady!==true||n.routable!==true)continue;let s=n.transportStableId,a=n.transportGeneration,c=n.routeGeneration;if(Number.isSafeInteger(s)&&Number(s)>0&&Number.isSafeInteger(a)&&Number(a)>0&&Number.isSafeInteger(c)&&Number(c)>=0){let l=this.mediaConnections.get(t);l&&l.observePhysicalGeneration({transportStableId:Number(s),transportGeneration:Number(a),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);for(let s of t.rawIds){let a=this.rawConnections.get(s)?.raw;if(this.rawConnections.delete(s),this.peerStreams.unbindConnection(s),!a)continue;let c=this.stateSenders.get(a);if(c){for(let l of c.values())l.close();this.stateSenders.delete(a);}}this.connectionIdsByPeer.delete(e);let i=this.remoteState.get(e);if(i){for(let s of i.keys())for(let a of this.stateListeners.get(s)??[])a(e,null);this.remoteState.delete(e);}let n=this.mediaConnections.get(e);this.mediaConnections.delete(e);let r=n?.close().catch(()=>{})??Promise.resolve();this.mediaRetirements.set(e,r),r.finally(()=>{this.mediaRetirements.get(e)===r&&this.mediaRetirements.delete(e);}),this.peerStreams.closePeer(e);for(let s of this.closeListeners.get(e)??[])s();this.closeListeners.delete(e),this.rawListeners.delete(e);for(let s of this.connectionListeners.values())s.delete(e);return r}receive(e,t){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 r of this.rawListeners.get(i)??[])r(t);return}if(n.capability===this.capabilityKey){if(n.kind==="raw"){for(let r of this.rawListeners.get(i)??[])r(n.value);return}this.deliverEnvelope(i,n);}}deliverEnvelope(e,t){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 r=n.get(t);r||(r=new a(s=>e.send(s)),n.set(t,r)),r.send(i).catch(()=>{});}},C=class{constructor(e,t,i,n,r){this.kind=e;this.id=t;this.client=i;this.onClosed=n;this.roomFanoutFactory=r;this.closed=false;y.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)}setArchitecture(e){this.roomFanoutFactory?.setArchitecture(e);}async close(){if(!this.closed){this.closed=true,await this.messages?.close();try{await this.client.advanced.runtime.shutdown();}finally{y.delete(this),this.onClosed();}}}capabilityMessages(){if(this.closed)throw new Error("[OpenRTC] Capability is closed.");return this.messages??(this.messages=new H(this.client,b$2(this.kind,this.id).key,this.roomFanoutFactory))}},w=class extends C{constructor(t,i,n,r){super("devices",t,i,n);this.roster=r;this.kind="devices";this.localId=()=>this.client.devices.localId();this.localInfo=()=>this.client.devices.localInfo();this.list=async()=>this.roster.mergeDevices(await this.client.devices.list());this.listWithStatus=async()=>this.roster.mergeStatus(await this.client.devices.listWithStatus());this.watch=t=>this.client.devices.watch(i=>t(this.roster.mergeDevices(i)));this.connect=this.client.devices.connect;this.disconnect=this.client.devices.disconnect;let s=i.devices.list,a=i.devices.listWithStatus,c=i.devices.watch,l=i.devices.watchWithStatus,d=g=>(this.roster.reconcileLiveSnapshot(g),g),u=async()=>this.roster.mergeDevices(d(await s())),m=async()=>this.roster.mergeStatus(await a()),v=g=>c(M=>g(this.roster.mergeDevices(d(M)))),p=g=>l(M=>g(this.roster.mergeStatus(M))),P=Object.create(i);Object.defineProperties(P,{listDevices:{value:u,enumerable:false},listDeviceStatus:{value:m,enumerable:false},watchDevices:{value:v,enumerable:false},watchDeviceStatus:{value:p,enumerable:false},devices:{value:{...i.devices,list:u,listWithStatus:m,watch:v,watchWithStatus:p},enumerable:true}}),y.set(this,P),this.stopRosterSync=c(d);}replaceEnrolledDevices(t){this.roster.replace(t);}removeEnrolledDevice(t){this.roster.remove(t);}retainCurrentEnrolledDevice(t){this.roster.retain(t);}async close(){this.stopRosterSync(),await super.close();}},q=class extends C{constructor(t,i,n,r){super("space",t,i,n);this.delivery=r;this.kind="space";this.leave=()=>this.close();}},W=class extends C{constructor(t,i,n,r){super("ticket",t,i,n);this.token=r;this.kind="ticket";}},E=class{constructor(e,t){this.options=e;this.internals=t;this.channels=new N;this.broadcastSessions=new Set;this.broadcastPublishers=new Set;this.handles=new Set;this.activations=new Map;this.authorityCallableIds=new WeakMap;this.nextAuthorityCallableId=1;this.closed=false;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:re(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());for(let n of this.handles)n instanceof w&&n.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=ie(e),r=await this.deviceId();await(await this.controlPlane()).revokeDevice(i,r,n);for(let s of this.handles)s instanceof w&&s.removeEnrolledDevice(n);n===r&&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();for(let n of this.handles)n instanceof w&&n.retainCurrentEnrolledDevice(i);}e.exceptCurrent!==true&&this.retireAuthCapabilities(t);}};this.spaces={join:(e,t={})=>this.activateOnce(`space:${T(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-A2FMQRNZ.js')).joinRoom(this,e,t)};this.tickets={issue:(e,t={})=>this.activateOnce(`ticket:${T(e)}`,JSON.stringify({identity:t.identity??null,maxPeers:t.maxPeers??null,advancedFanout:t.advancedFanout===true}),void 0,()=>this.issueTicket(e,t))};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,r={verificationKey:i,open:async s=>{if(n)throw new Error("[OpenRTC] Broadcast publisher is closed.");return this.assertOpen(),this.validateBroadcastGrant(s),this.wrapBroadcastSession(await t.open(s))},close:async()=>{n||(n=true,await t.close(),this.broadcastPublishers.delete(r));}};return this.broadcastPublishers.add(r),r},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,...r}=t;return i.invite(e,r,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=ue(e.apiKey),this.appTag=`app_${this.apiKey.slice(-16)}`,this.usage=new K(e.usage);}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-IIPEJ77Q.js'),e]).then(([{ControlPlane:t},i])=>new t(this.apiKey,this.internals.endpoints??a$1,i,this.options.trust?.attestation,{beforeLogicalOperation:n=>this.usage.assertCanSpend(n),onLogicalOperation:n=>this.usage.record(n),onAuthEpochChanged:n=>this.retireAuthCapabilities(n)},this.options.trust?.botVerification))}controlPlane(){return this.controlPlanePromise??(this.controlPlanePromise=this.makeControlPlane(this.internals.deviceKeyProvider?Promise.resolve(this.internals.deviceKeyProvider):import('./deviceKey-EIMDBAQS.js').then(({browserDeviceKeyProvider:e})=>e)))}sessionPlane(){return this.sessionPlanePromise??(this.sessionPlanePromise=this.makeControlPlane(import('./deviceKey-EIMDBAQS.js').then(async({createDeviceKey:e})=>{let t=await e();return {getOrCreate:async()=>t}})))}assertOpen(){if(this.closed)throw new Error("[OpenRTC] Client is closed.")}activateOnce(e,t,i,n){this.assertOpen();let r=this.activations.get(e);if(r){if(r.fingerprint!==t||r.auth!==i)throw new Error(`[OpenRTC] ${e} is already active with different options.`);return r.promise}let s={fingerprint:t,auth:i},a=n().then(c=>(s.handle=c,c)).catch(c=>{throw this.activations.get(e)===s&&this.activations.delete(e),c});return s.promise=a,this.activations.set(e,s),a}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):pe(this.appTag);return ie(e)}runtimeOptions(e){let t=this.options.transports,i=e.irohRelay&&t?.relay!==false,n=e.managedTurn&&t?.relay!==false,r=t?.privacy==="relay-only";if(r&&!i)throw new Error("[OpenRTC] transports.privacy: relay-only requires relay access.");let s=r?d(t?.priority?[...t.priority]:void 0,true):t?.priority?[...t.priority]:void 0,a=t?.webrtc,c=typeof a=="object"&&a.iceServers?.some(b$4)===true,l=!r||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,coordinationAvenueOverride:e.avenue,coordinationRoomGossipFanout:e.roomGossipFanout===true,coordinationRoomArchitecture:e.roomArchitecture,coordinationDevicePublicKeyX:e.devicePublicKeyX,coordinationDeviceSign:e.deviceSign,coordinationGateway:{endpoint:(this.internals.endpoints??a$1).gateway,environment:"production",grantProvider:e.grantProvider,testingAllowInsecureLoopback:this.internals.testingAllowInsecureLoopback},turnCredentialsProvider:n?e.turnProvider:void 0,transports:{relay:i,iroh:r?{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:l?typeof a=="object"?r?{...a,privacyMode:true,useTurn:true,useDefaultIceServers:false}:a:a===true?r?{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:s},transportPriority:s}}async activate(e){let t=e.authority?null:e.controlPlane??await this.controlPlane(),i=this.options.transports?.relay!==false,n=e.source.irohRelay&&i,r=e.source.managedTurn&&i,s={irohRelay:n,managedTurn:r,moq:n&&!!this.options.transports?.moq,ble:this.options.transports?.ble===true,advancedFanout:e.architecture==="sparse"||e.advancedFanout===true,durableMembership:e.durableMembership===true},a=e.source,c=null,l=()=>e.authority?{userId:e.principalId}:{userId:e.principalId,token:a.token,tokenProvider:async()=>a.token,expiresAtMs:a.expiresAtMs},d=e.authority?.devicePublicKeyX??String((await t.deviceSigningPublicKey()).x??""),u=this.runtimeOptions({avenue:e.source.avenue,grantProvider:e.authority?.grantProvider??t.grantProvider(e.source,{maxPeers:e.maxPeers,features:s,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 p=>{a={...a,...p},await c?.setAuth(l());}}),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:d,deviceSign:e.authority?.deviceSign??(p=>t.signDeviceBytes(p)),irohRelay:e.source.irohRelay,managedTurn:e.source.managedTurn,turnProvider:r&&t?t.turnProvider(()=>a):void 0,deviceName:e.deviceName,devicePlatform:e.devicePlatform,initialAutoConnectExcludedDeviceIds:e.initialAutoConnectExcludedDeviceIds}),[m,{wrapAssembly:v}]=await Promise.all([this.internals.runtimeFactory(u),import('./coreClient.js')]);c=v(m,this.internals.platform==="native"?"native":"web"),await c.setAuth(l()),this.channels.attach(c,e.defaultDelivery??"reliable");try{this.usage.assertCanSpend("coordination.connection.open"),await c.devices.startSession({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(p){throw this.channels.detach(c),await c.advanced.runtime.shutdown().catch(()=>{}),p}return this.usage.record("coordination.connection.open"),c}trackHandle(e){return this.handles.add(e),e}async startDevices(e={}){this.assertOpen();let t=re(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:r}=await import('./deviceProfile-CR2C7OYR.js'),s=r(e.profile,this.internals.platform==="native"?"native":"web"),a=await this.controlPlane(),c=await a.deviceCertificate(i,n,void 0,s),l=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:s.name,devicePlatform:s.platform,deviceMetadata:s.metadata}),d;try{d=await a.listEnrolledDevices(i,n);}catch(v){throw this.channels.detach(l),await l.advanced.runtime.shutdown().catch(()=>{}),v}let{AuthenticatedDeviceRoster:u}=await import('./deviceRoster-EUF6BBF5.js'),m;return m=new w(c.principalId,l,()=>{this.channels.detach(l),this.onClosed(m);},new u(d)),this.handles.add(m),m}async joinSpace(e,t={}){this.assertOpen();let i=T(e),n=await(t.identity==="session"?this.sessionPlane():this.controlPlane()),r=await n.capability("space",i,t.maxPeers,t.advancedFanout),s=String(b$1(r.token).principalId),a=await this.activate({kind:"space",id:i,source:r,principalId:s,deviceId:oe(r),maxPeers:t.maxPeers,autoConnect:true,defaultDelivery:t.payload??"reliable",advancedFanout:t.advancedFanout,controlPlane:n}),c;return c=new q(i,a,()=>{this.channels.detach(a),this.onClosed(c);},t.payload??"reliable"),this.handles.add(c),c}async openAuthorityRoom(e){return (await import('./room-A2FMQRNZ.js')).openAuthorityRoom(this,e)}async issueTicket(e,t={}){this.assertOpen();let i=T(e),n=await(t.identity==="session"?this.sessionPlane():this.controlPlane()),r=await n.capability("ticket",i,t.maxPeers,t.advancedFanout),s=String(b$1(r.token).principalId),a=await this.activate({kind:"ticket",id:i,source:r,principalId:s,deviceId:oe(r),maxPeers:t.maxPeers,autoConnect:false,advancedFanout:t.advancedFanout,controlPlane:n}),c;return c=new W(i,a,()=>{this.channels.detach(a),this.onClosed(c);},r.token),this.handles.add(c),c}async close(){if(!this.closed){this.closed=true;try{await Promise.all([...this.handles].map(e=>e.close()));}finally{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?.();}}}};function Be(o,e){return new E(o,e)}function ke(o,e){if(!(o instanceof E))throw new TypeError("[OpenRTC] ServiceNode requires a client created by this OpenRTC package.");return o.openAuthorityRoom(e)}export{I as a,B as b,de as c,xe as d,T as e,ie as f,oe as g,C as h,Be as i,ke as j};
|
|
1
|
+
import {b as b$1,a as a$1}from'./chunk-ZA44REGI.js';import {b as b$3}from'./chunk-LLZT3MR6.js';import {a}from'./chunk-DUY34MGT.js';import {b as b$2,a as a$2}from'./chunk-CCCYE3XN.js';import {d as d$1,a as a$3}from'./chunk-N6LGTNUI.js';import {d,b as b$4}from'./chunk-2GX6GB6L.js';function I(o,e,t,i){let n=JSON.stringify({__openrtc:2,capability:i,kind:o,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(o){let e;try{e=o instanceof Uint8Array?JSON.parse(new TextDecoder().decode(o)):o&&typeof o=="object"?o:{};}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",se=32,Y=16,U=4294967295,ce=/^[A-Za-z0-9][A-Za-z0-9._/+:-]{0,127}$/,le=/^([0-9a-f]{64})-([0-9a-f]{64})$/i;function A(o){let e=o?.trim()??"";if(!ce.test(e))throw new Error("[OpenRTC] stream protocol must be 1-128 safe ASCII characters.");return e}function k(o){let e=o?.trim()??"",t=le.exec(e);return t?[t[1].toLowerCase(),t[2].toLowerCase()].sort().join("-"):e}function ee(o){if(o===null||o===0)return null;if(!Number.isFinite(o)||o<0)throw new RangeError("[OpenRTC] datagram maximum age must be a non-negative finite number or null.");return Math.min(U,Math.ceil(o))}function te(o){if(!Number.isSafeInteger(o)||o<1||o>U)throw new RangeError(`[OpenRTC] datagram buffer limits must be integers from 1 to ${U}.`);return o}var L=class{constructor(e,t){this.runtime=e;this.peerId=t;this.incomingAge=null;this.outgoingAge=null;this.incomingLimit=Y;this.outgoingLimit=Y;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=ee(e),this.policy.setIncomingMaxAge(this.incomingAge??void 0,Date.now()),this.wake(this.incomingWaiters);}get outgoingMaxAge(){return this.outgoingAge}set outgoingMaxAge(e){this.outgoingAge=ee(e),this.policy.setOutgoingMaxAge(this.outgoingAge??void 0);}get incomingMaxBufferedDatagrams(){return this.incomingLimit}set incomingMaxBufferedDatagrams(e){this.incomingLimit=te(e),this.policy.setIncomingMaxBufferedDatagrams(this.incomingLimit);}get outgoingMaxBufferedDatagrams(){return this.outgoingLimit}set outgoingMaxBufferedDatagrams(e){this.outgoingLimit=te(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();}},O=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:se});}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 O;this.incomingUni=new O;this.incomingBidirectionalStreams=this.incomingBi.readable;this.incomingUnidirectionalStreams=this.incomingUni.readable;this.closed=false;this.protocolHandlers=new Map;this.datagrams=new L(i,this.peerId);}async createBidirectionalStream(e){let t=A(e.protocol),i=await this.client.channels.openBi(this.peerId,b,{timeoutMs:e.timeoutMs,channelMetadata:{protocol:t,[a$2]:this.capabilityKey}});return {protocol:t,readable:i.readable,writable:i.writable}}async createUnidirectionalStream(e){let t=A(e.protocol);return (await this.client.channels.openUni(this.peerId,b,{timeoutMs:e.timeoutMs,channelMetadata:{protocol:t,[a$2]:this.capabilityKey}})).writable}accept(e,t){if(e.type==="bi"){let n=e.stream;if(!n.recv||!n.send)return false;let r={peerId:this.peerId,protocol:t,readable:n.recv,writable:n.send},a=this.protocolHandlers.get(t);if(a){try{a(r);}catch{r.readable.cancel("incoming-protocol-handler-failed").catch(()=>{}),r.writable.abort("incoming-protocol-handler-failed").catch(()=>{});}return true}return this.incomingBi.enqueue(r)||(r.readable.cancel("incoming-peer-stream-queue-full").catch(()=>{}),r.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=A(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();}},D=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=k(e),n=t.trim();!i||!n||this.peerIdsByConnection.set(i,n);}unbindConnection(e){this.peerIdsByConnection.delete(k(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$2]!==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=A(i);}catch{return this.declined+=1,false}let a=this.resolveExistingPeer(e.remoteNodeId,e.connectionId)?.accept(e,n)??false;return a?this.accepted+=1:this.declined+=1,a}resolveExistingPeer(e,t=""){let i=k(t);if(i){let a=this.peerIdsByConnection.get(i);if(!a)return this.lastResolution="unbound-connection",null;let s=this.peers.get(a);return s?(this.lastResolution="connection",s):(this.lastResolution="unbound-connection",null)}let n=this.peers.get(e);if(n)return this.lastResolution="remote-peer",n;let r=this.client.peers.get(e)??this.client.peers.listConnected().find(a=>[a.peerId,a.deviceId,a.deviceIdHint,a.connectionId,...a.connectionIds].some(s=>s===e));if(r){let a=new Set([r.peerId,r.deviceId,r.deviceIdHint,r.connectionId,...r.connectionIds].filter(c=>typeof c=="string"&&c.length>0)),s=[...this.peers.entries()].filter(([c])=>a.has(c)).map(([,c])=>c);if(s.length===1)return this.lastResolution="peer-alias",s[0]}return this.lastResolution="none",null}};var _={"identity.assertion.exchange":25692e-8,"identity.monthly-active-principal":110352e-9,"capability.issue":212346e-9,"device.enroll":218946e-9,"gateway.grant.issue":202146e-9,"gateway.grant.refresh":200346e-9,"security.attestation.verify":29694e-8,"room.create":388056e-9,"room.join":209946e-9,"room.leave":200346e-9,"broadcast.control":271938e-9,"broadcast.delivery":.1,"coordination.connection.open":58164e-8,"coordination.credential.refresh":367734e-9,"coordination.lease.refresh":27987e-8,"coordination.presence.upsert":27771e-8,"coordination.presence.offline":27171e-8,"coordination.signal.send":27771e-8,"coordination.managed.publish":473688e-9,"coordination.managed.keypackage.publish":271908e-9,"coordination.managed.commit.chunk":295182e-9,"coordination.managed.commit.ack":271908e-9,"coordination.managed.control":.001122582,"coordination.managed.prepare.page":26718e-8,"coordination.authority.assignment":370866e-9,"coordination.session.put":27771e-8,"coordination.session.delete":27171e-8,"coordination.usage.ingest":197088e-9};var y=new WeakMap;function de(o){let e=y.get(o);if(!e||o.closed)throw new Error("[OpenRTC] Capability runtime is unavailable or already closed.");return e}function xe(o,e){if(y.has(o))throw new Error("[OpenRTC] Capability runtime is already registered.");return y.set(o,de(e)),()=>{y.delete(o);}}function ue(o){let e=o?.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 T(o){let e=o?.trim()??"";if(!e||e.length>160||!/^[A-Za-z0-9_.:@-]+$/.test(e))throw new Error("[OpenRTC] Capability id is invalid.");return e}var z=/^[A-Za-z0-9_.:@-]{1,160}$/,he=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;function me(o){let e=typeof o=="string"?o.trim():"";if(!z.test(e))return null;let t=e.startsWith("device_")?e.slice(7):"";return he.test(t)?t:e}function pe(o){let e=`openrtc:v2:device-id:${o}`,t,i=(()=>{try{return t=globalThis.localStorage,me(t?.getItem(e))||crypto.randomUUID()}catch{return crypto.randomUUID()}})();try{t?.setItem(e,i);}catch{}return i}function ie(o){let e=typeof o=="string"?o.trim():"";if(!z.test(e))throw new Error("[OpenRTC] The native host returned an invalid durable device ID.");return e}var ne=250;function re(o){if(o===void 0)return [];if(!Array.isArray(o))throw new Error("[OpenRTC] autoConnectExcludedDeviceIds must be an array.");let e=[...new Set(o.map(t=>{let i=typeof t=="string"?t.trim().toLowerCase():"";if(!z.test(i))throw new Error("[OpenRTC] autoConnectExcludedDeviceIds contains an invalid device ID.");return i}))].sort();if(e.length>ne)throw new Error(`[OpenRTC] autoConnectExcludedDeviceIds supports at most ${ne} devices.`);return e}function oe(o){let e=b$1(o.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 N=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);}},K=class{constructor(e){this.options=e;this.total=0;this.warned=false;}get sessionCreditsUsd(){return this.total}estimate(e){let t=e.units??1,i=Number.isFinite(t)?Math.max(0,t):0;return {creditsUsd:(_[e.operation]??0)*i,estimated:true}}estimateRoom(e){let t=G(e.maxMembers,"maxMembers",1,Number.MAX_SAFE_INTEGER);if(t>50)throw f(`[OpenRTC] Room architecture is unavailable for ${t} members in this release; the limit is 50.`);let i=G(e.durationSeconds,"durationSeconds",1,744*60*60),n=G(e.maxPayloadBytes,"maxPayloadBytes",0,1048576),r=ge(e.maxMessagesPerSecond,"maxMessagesPerSecond",0,1e4),a=ve(e.architecture),s=ye(a,t,e.delivery),l=fe(s,t)*r*i*n/1e9,d=Math.floor(i/3300),u=h("capability.issue")+h("gateway.grant.issue")+h("room.join")+h("coordination.connection.open")+h("coordination.presence.upsert")+h("room.leave")+h("coordination.presence.offline")+d*h("coordination.lease.refresh"),m=t*u,v=r*i,p=Math.max(0,Math.ceil(t/4)-1),P=s==="managed"?v*h("coordination.managed.publish")+t*h("coordination.managed.keypackage.publish")+t*h("coordination.managed.commit.ack")+t*h("coordination.managed.commit.chunk")+h("coordination.managed.control")+p*h("coordination.managed.prepare.page"):s==="authority"?t*Math.ceil(i/120)*h("coordination.authority.assignment"):0,g=l*h("broadcast.delivery");return {architecture:a,effectiveArchitecture:s,creditsUsd:Math.ceil((m+P+g)*1e12)/1e12,estimated:true,expiresAtMs:Date.now()+5*6e4,assumptions:["Every declared member obtains one capability and gateway grant, joins once, publishes presence, and retires once during the quote window.",`Each continuously connected member is quoted for ${d} successful 55-minute lease renewal${d===1?"":"s"}.`,"Room-wide payload is conservatively quoted as fully hosted or relayed.","Payload delivery uses the published customer value of $0.10 per decimal GB.",s==="managed"?"Managed control assumes initial group setup, maximum-size KeyPackage paging, bounded artifact chunks, exactly one room-wide transition settlement, and one protected publish per declared message.":s==="authority"?"Authority control assumes one signed assignment per member every two minutes.":"Direct application payloads do not add hosted fanout operations.",s==="authority"?"Developer service-node hosting is external and is not included in OpenRTC credits.":"Unused reservations are released when authoritative settlement completes."]}}assertCanSpend(e,t=1){let i=this.options?.maxSessionCreditsUsd;if(i===void 0||this.total+this.estimate({operation:e,units:t}).creditsUsd<=i)return;let r={sessionCreditsUsd:this.total,operation:e,estimated:true,thresholdCreditsUsd:i,kind:"session-limit"};throw this.options?.onWarning?.(r),new Error("[OpenRTC] The client-side session credit limit was reached.")}record(e,t=1){let i=this.estimate({operation:e,units:t}).creditsUsd;this.total+=i;let n={sessionCreditsUsd:this.total,operation:e,estimated:true};this.options?.onUsage?.(n);let r=this.options?.warnAtSessionCreditsUsd;!this.warned&&r!==void 0&&this.total>=r&&(this.warned=true,this.options?.onWarning?.({...n,thresholdCreditsUsd:r,kind:"warning"}));}};function ve(o){return o??"auto"}function G(o,e,t,i){if(!Number.isSafeInteger(o)||o<t||o>i)throw new RangeError(`[OpenRTC] ${e} must be an integer from ${t} to ${i}.`);return o}function ge(o,e,t,i){if(!Number.isFinite(o)||o<t||o>i)throw new RangeError(`[OpenRTC] ${e} must be between ${t} and ${i}.`);return o}function h(o){let e=_[o];if(!Number.isFinite(e)||e<=0)throw new Error(`[OpenRTC] Room quote is unavailable because ${o} has no current customer-credit price.`);return e}function ye(o,e,t){if(o==="mesh"){if(e>16)throw f("[OpenRTC] Fixed mesh is limited to 16 members in this release.");return o}if(o==="sparse"){if(e>50)throw f("[OpenRTC] Fixed sparse is limited to 50 members in this release.");if(t!=="latest-state")throw f("[OpenRTC] Sparse room quotes require latest-state delivery.");return o}if(o==="managed")throw f("[OpenRTC] Managed room architecture is unavailable in this release.");if(o==="authority")return o;if(e<=8)return "mesh";if(t==="latest-state"&&e<=50)return "sparse";throw f(`[OpenRTC] Reliable automatic room architecture is unavailable for ${e} members in this release.`)}function f(o){return d$1(a$3.ROOM_ARCHITECTURE_UNAVAILABLE,o,{retryable:false,plane:"admission"})}function fe(o,e){if(e<=1)return 0;if(o!=="sparse")return e-1;let t=Math.min(4,e-1),i=e*t/2;return Math.max(e-1,i*2-(e-1))}function ae(o){let e=o?.trim()??"";if(!e||e.length>80||!/^[A-Za-z0-9_.:@-]+$/.test(e))throw new Error("[OpenRTC] Message name is invalid.");return e}var H=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.mediaConnections=new Map;this.mediaRetirements=new Map;this.pendingRawConnections=new Map;this.connectionIdsByPeer=new Map;this.closed=false;this.peerStreams=new D(e,t),this.stopMessage=e.onMessage((n,r)=>this.receive(n,r)),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,r,a)=>{let s=B(r);!s||s.capability!==this.capabilityKey||a!==void 0&&s.name!==a||a===void 0&&s.kind!=="channel"||this.deliverEnvelope(n,s);}});}state(e){if(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=ae(e);return {set:i=>{let n=I("state",t,i,this.capabilityKey);if(this.localState.set(t,n),!this.roomFanout?.publishState(t,n))for(let{activeRaw:r}of this.logicalConnections.values())r&&this.sendState(r,t,n);},watch:i=>{let n=this.stateListeners.get(t);n||this.stateListeners.set(t,n=new Set);let r=(a,s)=>i({peerId:a,value:s});n.add(r);for(let[a,s]of this.remoteState)s.has(t)&&i({peerId:a,value:s.get(t)});return ()=>n?.delete(r)}}}channel(e){let t=ae(e),i=n=>I("channel",t,n,this.capabilityKey);return {send:async n=>{let r=i(n);await this.roomFanout?.sendChannel(t,r)||await Promise.all([...this.logicalConnections.values()].flatMap(({activeRaw:a})=>a?[a.send(r)]:[]));},sendTo:async(n,r)=>{this.roomFanout?.assertTargetedSendAllowed();let a=this.logicalConnections.get(n)?.activeRaw;if(a){await a.send(i(r));return}throw new Error(`[OpenRTC] Peer '${n}' has no direct authorized route; sparse broadcasts never multi-hop targeted payloads.`)},onMessage:n=>{let r=this.channelListeners.get(t);r||this.channelListeners.set(t,r=new Set);let a=(s,c)=>n({peerId:s,message:c});return r.add(a),()=>r?.delete(a)}}}onConnection(e){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)}async close(){if(this.closed)return;this.closed=true,this.stopMessage(),this.stopConnection(),this.stopDisconnection(),this.stopPeerLifecycle(),this.roomFanout?.close();let e=[...this.logicalConnections.keys()].map(t=>this.retire(t));this.pendingRawConnections.clear(),this.peerStreams.close(),this.rawConnections.clear(),this.connectionListeners.clear(),this.channelListeners.clear(),this.stateListeners.clear(),this.localState.clear(),await Promise.allSettled(e);}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 s={raw:e,peerId:i};this.pendingRawConnections.set(e.id,s),n.finally(()=>{this.closed||this.pendingRawConnections.get(e.id)!==s||(this.pendingRawConnections.delete(e.id),this.add(e));});return}this.rawConnections.set(e.id,{raw:e,peerId:i});let r=this.connectionIdsByPeer.get(i);r||this.connectionIdsByPeer.set(i,r=new Set),r.add(e.id),this.peerStreams.bindConnection(e.id,i);let a=this.logicalConnections.get(i);if(!a){let s=this.peerStreams.forPeer(i),c=new b$3(s,this.client.advanced.runtime,(d,u)=>this.peerStreams.onProtocol(i,d,u),()=>this.peerStreams.diagnostics());this.mediaConnections.set(i,c),a={activeRaw:e,rawIds:new Set,view:{id:i,peerId:i,streams:s,media:c,send:async d=>{let u=this.logicalConnections.get(i)?.activeRaw;if(!u)throw new Error(`[OpenRTC] Peer '${i}' is not connected.`);await u.send(I("raw","message",d,this.capabilityKey));},onMessage:d=>{let u=this.rawListeners.get(i);u||this.rawListeners.set(i,u=new Set);let m=d;return u.add(m),()=>u?.delete(m)},onClose:d=>{let u=this.closeListeners.get(i);return u||this.closeListeners.set(i,u=new Set),u.add(d),()=>u?.delete(d)}}},this.logicalConnections.set(i,a);}a.rawIds.add(e.id),a.activeRaw=e,this.observePeerLifecycle(this.client.peers.listConnected());for(let[s,c]of this.connectionListeners)c.has(i)||(c.add(i),s(a.view));for(let[s,c]of this.localState)this.sendState(e,s,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 s=[...n.rawIds],c=s[s.length-1];n.activeRaw=c?this.rawConnections.get(c)?.raw??null:null;}let r=this.connectionIdsByPeer.get(i);if(r?.delete(e.id),r?.size===0&&this.connectionIdsByPeer.delete(i),!n?.activeRaw){let s=this.remoteState.get(i);if(s){for(let c of s.keys())for(let l of this.stateListeners.get(c)??[])l(i,null);this.remoteState.delete(i);}}let a=this.stateSenders.get(e);if(a){for(let s of a.values())s.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(l=>l.peerId===t||l.connectionId===t||l.connectionIds.some(d=>i.has(d)));if(!n)continue;let r=n.status==="closed"&&n.logicalSessionTerminal===true&&n.routable!==true&&n.settledReady!==true;if(n.manualDisconnect||r){this.retire(t);continue}if(n.settledReady!==true||n.routable!==true)continue;let a=n.transportStableId,s=n.transportGeneration,c=n.routeGeneration;if(Number.isSafeInteger(a)&&Number(a)>0&&Number.isSafeInteger(s)&&Number(s)>0&&Number.isSafeInteger(c)&&Number(c)>=0){let l=this.mediaConnections.get(t);l&&l.observePhysicalGeneration({transportStableId:Number(a),transportGeneration:Number(s),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);for(let a of t.rawIds){let s=this.rawConnections.get(a)?.raw;if(this.rawConnections.delete(a),this.peerStreams.unbindConnection(a),!s)continue;let c=this.stateSenders.get(s);if(c){for(let l of c.values())l.close();this.stateSenders.delete(s);}}this.connectionIdsByPeer.delete(e);let i=this.remoteState.get(e);if(i){for(let a of i.keys())for(let s of this.stateListeners.get(a)??[])s(e,null);this.remoteState.delete(e);}let n=this.mediaConnections.get(e);this.mediaConnections.delete(e);let r=n?.close().catch(()=>{})??Promise.resolve();this.mediaRetirements.set(e,r),r.finally(()=>{this.mediaRetirements.get(e)===r&&this.mediaRetirements.delete(e);}),this.peerStreams.closePeer(e);for(let a of this.closeListeners.get(e)??[])a();this.closeListeners.delete(e),this.rawListeners.delete(e);for(let a of this.connectionListeners.values())a.delete(e);return r}receive(e,t){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 r of this.rawListeners.get(i)??[])r(t);return}if(n.capability===this.capabilityKey){if(n.kind==="raw"){for(let r of this.rawListeners.get(i)??[])r(n.value);return}this.deliverEnvelope(i,n);}}deliverEnvelope(e,t){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 r=n.get(t);r||(r=new a(a=>e.send(a)),n.set(t,r)),r.send(i).catch(()=>{});}},C=class{constructor(e,t,i,n,r){this.kind=e;this.id=t;this.client=i;this.onClosed=n;this.roomFanoutFactory=r;this.closed=false;y.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)}setArchitecture(e){this.roomFanoutFactory?.setArchitecture(e);}async close(){if(!this.closed){this.closed=true,await this.messages?.close();try{await this.client.advanced.runtime.shutdown();}finally{y.delete(this),this.onClosed();}}}capabilityMessages(){if(this.closed)throw new Error("[OpenRTC] Capability is closed.");return this.messages??(this.messages=new H(this.client,b$2(this.kind,this.id).key,this.roomFanoutFactory))}},w=class extends C{constructor(t,i,n,r){super("devices",t,i,n);this.roster=r;this.kind="devices";this.localId=()=>this.client.devices.localId();this.localInfo=()=>this.client.devices.localInfo();this.list=async()=>this.roster.mergeDevices(await this.client.devices.list());this.listWithStatus=async()=>this.roster.mergeStatus(await this.client.devices.listWithStatus());this.watch=t=>this.client.devices.watch(i=>t(this.roster.mergeDevices(i)));this.connect=this.client.devices.connect;this.disconnect=this.client.devices.disconnect;let a=i.devices.list,s=i.devices.listWithStatus,c=i.devices.watch,l=i.devices.watchWithStatus,d=g=>(this.roster.reconcileLiveSnapshot(g),g),u=async()=>this.roster.mergeDevices(d(await a())),m=async()=>this.roster.mergeStatus(await s()),v=g=>c(M=>g(this.roster.mergeDevices(d(M)))),p=g=>l(M=>g(this.roster.mergeStatus(M))),P=Object.create(i);Object.defineProperties(P,{listDevices:{value:u,enumerable:false},listDeviceStatus:{value:m,enumerable:false},watchDevices:{value:v,enumerable:false},watchDeviceStatus:{value:p,enumerable:false},devices:{value:{...i.devices,list:u,listWithStatus:m,watch:v,watchWithStatus:p},enumerable:true}}),y.set(this,P),this.stopRosterSync=c(d);}replaceEnrolledDevices(t){this.roster.replace(t);}removeEnrolledDevice(t){this.roster.remove(t);}retainCurrentEnrolledDevice(t){this.roster.retain(t);}async close(){this.stopRosterSync(),await super.close();}},q=class extends C{constructor(t,i,n,r){super("space",t,i,n);this.delivery=r;this.kind="space";this.leave=()=>this.close();}},W=class extends C{constructor(t,i,n,r){super("ticket",t,i,n);this.token=r;this.kind="ticket";}},E=class{constructor(e,t){this.options=e;this.internals=t;this.channels=new N;this.broadcastSessions=new Set;this.broadcastPublishers=new Set;this.handles=new Set;this.activations=new Map;this.authorityCallableIds=new WeakMap;this.nextAuthorityCallableId=1;this.closed=false;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:re(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());for(let n of this.handles)n instanceof w&&n.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=ie(e),r=await this.deviceId();await(await this.controlPlane()).revokeDevice(i,r,n);for(let a of this.handles)a instanceof w&&a.removeEnrolledDevice(n);n===r&&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();for(let n of this.handles)n instanceof w&&n.retainCurrentEnrolledDevice(i);}e.exceptCurrent!==true&&this.retireAuthCapabilities(t);}};this.spaces={join:(e,t={})=>this.activateOnce(`space:${T(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-2MUFAJ4M.js')).joinRoom(this,e,t)};this.tickets={issue:(e,t={})=>this.activateOnce(`ticket:${T(e)}`,JSON.stringify({identity:t.identity??null,maxPeers:t.maxPeers??null,advancedFanout:t.advancedFanout===true}),void 0,()=>this.issueTicket(e,t))};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,r={verificationKey:i,open:async a=>{if(n)throw new Error("[OpenRTC] Broadcast publisher is closed.");return this.assertOpen(),this.validateBroadcastGrant(a),this.wrapBroadcastSession(await t.open(a))},close:async()=>{n||(n=true,await t.close(),this.broadcastPublishers.delete(r));}};return this.broadcastPublishers.add(r),r},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,...r}=t;return i.invite(e,r,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=ue(e.apiKey),this.appTag=`app_${this.apiKey.slice(-16)}`,this.usage=new K(e.usage);}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-IIPEJ77Q.js'),e]).then(([{ControlPlane:t},i])=>new t(this.apiKey,this.internals.endpoints??a$1,i,this.options.trust?.attestation,{beforeLogicalOperation:n=>this.usage.assertCanSpend(n),onLogicalOperation:n=>this.usage.record(n),onAuthEpochChanged:n=>this.retireAuthCapabilities(n)},this.options.trust?.botVerification))}controlPlane(){return this.controlPlanePromise??(this.controlPlanePromise=this.makeControlPlane(this.internals.deviceKeyProvider?Promise.resolve(this.internals.deviceKeyProvider):import('./deviceKey-EIMDBAQS.js').then(({browserDeviceKeyProvider:e})=>e)))}sessionPlane(){return this.sessionPlanePromise??(this.sessionPlanePromise=this.makeControlPlane(import('./deviceKey-EIMDBAQS.js').then(async({createDeviceKey:e})=>{let t=await e();return {getOrCreate:async()=>t}})))}assertOpen(){if(this.closed)throw new Error("[OpenRTC] Client is closed.")}activateOnce(e,t,i,n){this.assertOpen();let r=this.activations.get(e);if(r){if(r.fingerprint!==t||r.auth!==i)throw new Error(`[OpenRTC] ${e} is already active with different options.`);return r.promise}let a={fingerprint:t,auth:i},s=n().then(c=>(a.handle=c,c)).catch(c=>{throw this.activations.get(e)===a&&this.activations.delete(e),c});return a.promise=s,this.activations.set(e,a),s}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):pe(this.appTag);return ie(e)}runtimeOptions(e){let t=this.options.transports,i=e.irohRelay&&t?.relay!==false,n=e.managedTurn&&t?.relay!==false,r=t?.privacy==="relay-only";if(r&&!i)throw new Error("[OpenRTC] transports.privacy: relay-only requires relay access.");let a=r?d(t?.priority?[...t.priority]:void 0,true):t?.priority?[...t.priority]:void 0,s=t?.webrtc,c=typeof s=="object"&&s.iceServers?.some(b$4)===true,l=!r||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:d=>e.nativeAuth.getAssertion(d)}:void 0,coordinationAvenueOverride:e.avenue,coordinationRoomGossipFanout:e.roomGossipFanout===true,coordinationRoomArchitecture:e.roomArchitecture,coordinationDevicePublicKeyX:e.devicePublicKeyX,coordinationDeviceSign:e.deviceSign,coordinationGateway:{endpoint:(this.internals.endpoints??a$1).gateway,environment:"production",grantProvider:e.grantProvider,testingAllowInsecureLoopback:this.internals.testingAllowInsecureLoopback},turnCredentialsProvider:n?e.turnProvider:void 0,transports:{relay:i,iroh:r?{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:l?typeof s=="object"?r?{...s,privacyMode:true,useTurn:true,useDefaultIceServers:false}:s:s===true?r?{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:a},transportPriority:a}}async activate(e){let t=e.authority?null:e.controlPlane??await this.controlPlane(),i=this.options.transports?.relay!==false,n=e.source.irohRelay&&i,r=e.source.managedTurn&&i,a={irohRelay:n,managedTurn:r,moq:n&&!!this.options.transports?.moq,ble:this.options.transports?.ble===true,advancedFanout:e.architecture==="sparse"||e.advancedFanout===true,durableMembership:e.durableMembership===true},s=e.source,c=null,l=()=>e.authority?{userId:e.principalId}:{userId:e.principalId,token:s.token,tokenProvider:async()=>s.token,expiresAtMs:s.expiresAtMs},d=e.authority?.devicePublicKeyX??String((await t.deviceSigningPublicKey()).x??""),u=this.runtimeOptions({avenue:e.source.avenue,grantProvider:e.authority?.grantProvider??t.grantProvider(e.source,{maxPeers:e.maxPeers,features:a,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 p=>{s={...s,...p},await c?.setAuth(l());}}),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:d,deviceSign:e.authority?.deviceSign??(p=>t.signDeviceBytes(p)),irohRelay:e.source.irohRelay,managedTurn:e.source.managedTurn,turnProvider:r&&t?t.turnProvider(()=>s):void 0,deviceName:e.deviceName,devicePlatform:e.devicePlatform,initialAutoConnectExcludedDeviceIds:e.initialAutoConnectExcludedDeviceIds,nativeAuth:e.nativeAuth}),[m,{wrapAssembly:v}]=await Promise.all([this.internals.runtimeFactory(u),import('./coreClient.js')]);c=v(m,this.internals.platform==="native"?"native":"web"),await c.setAuth(l()),this.channels.attach(c,e.defaultDelivery??"reliable");try{this.usage.assertCanSpend("coordination.connection.open"),await c.devices.startSession({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(p){throw this.channels.detach(c),await c.advanced.runtime.shutdown().catch(()=>{}),p}return this.usage.record("coordination.connection.open"),c}trackHandle(e){return this.handles.add(e),e}async startDevices(e={}){this.assertOpen();let t=re(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:r}=await import('./deviceProfile-CR2C7OYR.js'),a=r(e.profile,this.internals.platform==="native"?"native":"web"),s=await this.controlPlane(),c=await s.deviceCertificate(i,n,void 0,a),l=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:a.name,devicePlatform:a.platform,deviceMetadata:a.metadata,nativeAuth:i}),d=[];if(this.internals.platform!=="native")try{d=await s.listEnrolledDevices(i,n);}catch(v){throw this.channels.detach(l),await l.advanced.runtime.shutdown().catch(()=>{}),v}let{AuthenticatedDeviceRoster:u}=await import('./deviceRoster-EUF6BBF5.js'),m;return m=new w(c.principalId,l,()=>{this.channels.detach(l),this.onClosed(m);},new u(d)),this.handles.add(m),m}async joinSpace(e,t={}){this.assertOpen();let i=T(e),n=await(t.identity==="session"?this.sessionPlane():this.controlPlane()),r=await n.capability("space",i,t.maxPeers,t.advancedFanout),a=String(b$1(r.token).principalId),s=await this.activate({kind:"space",id:i,source:r,principalId:a,deviceId:oe(r),maxPeers:t.maxPeers,autoConnect:true,defaultDelivery:t.payload??"reliable",advancedFanout:t.advancedFanout,controlPlane:n}),c;return c=new q(i,s,()=>{this.channels.detach(s),this.onClosed(c);},t.payload??"reliable"),this.handles.add(c),c}async openAuthorityRoom(e){return (await import('./room-2MUFAJ4M.js')).openAuthorityRoom(this,e)}async issueTicket(e,t={}){this.assertOpen();let i=T(e),n=await(t.identity==="session"?this.sessionPlane():this.controlPlane()),r=await n.capability("ticket",i,t.maxPeers,t.advancedFanout),a=String(b$1(r.token).principalId),s=await this.activate({kind:"ticket",id:i,source:r,principalId:a,deviceId:oe(r),maxPeers:t.maxPeers,autoConnect:false,advancedFanout:t.advancedFanout,controlPlane:n}),c;return c=new W(i,s,()=>{this.channels.detach(s),this.onClosed(c);},r.token),this.handles.add(c),c}async close(){if(!this.closed){this.closed=true;try{await Promise.all([...this.handles].map(e=>e.close()));}finally{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?.();}}}};function Be(o,e){return new E(o,e)}function ke(o,e){if(!(o instanceof E))throw new TypeError("[OpenRTC] ServiceNode requires a client created by this OpenRTC package.");return o.openAuthorityRoom(e)}export{I as a,B as b,de as c,xe as d,T as e,ie as f,oe as g,C as h,Be as i,ke as j};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import {t}from'./chunk-25CN4MLA.js';var a=class{constructor(e){this.backend=e;}get currentUser(){return this.backend.currentUser}setAuthContext(e){return this.backend.setAuthContext?.(e)}async signInAnonymously(){return this.backend.signInAnonymously()}async signInWithPluto(){if(typeof this.backend.signInWithPluto!="function")throw new Error("Selected runtime adapter does not support Pluto SSO.");return this.backend.signInWithPluto()}async signOut(){return this.backend.signOut()}async stopAuthActivity(){typeof this.backend.stopAuthActivity=="function"&&await this.backend.stopAuthActivity();}usesCoordinationGateway(){return this.backend.usesCoordinationGateway?.()===true}async joinCoordinationRoom(e,t,n){if(!this.backend.joinCoordinationRoom)throw new Error("Selected runtime adapter does not support coordination rooms.");await this.backend.joinCoordinationRoom(e,t,n);}async leaveCoordinationRoom(e){if(!this.backend.leaveCoordinationRoom)throw new Error("Selected runtime adapter does not support coordination rooms.");await this.backend.leaveCoordinationRoom(e);}async getCoordinationRoomMembers(e){if(!this.backend.getCoordinationRoomMembers)throw new Error("Selected runtime adapter does not support coordination rooms.");return this.backend.getCoordinationRoomMembers(e)}watchCoordinationRoomMembers(e,t){if(!this.backend.watchCoordinationRoomMembers)throw new Error("Selected runtime adapter does not support coordination rooms.");return this.backend.watchCoordinationRoomMembers(e,t)}async getTurnCredentials(){return this.backend.getTurnCredentials()}async updatePresence(e,t,n,i,r){return this.backend.updatePresence(e,t,n,i,r)}async refreshLivePresence(e,t,n){if(typeof this.backend.refreshLivePresence!="function")throw new Error("Selected runtime adapter does not support refreshLivePresence().");return this.backend.refreshLivePresence(e,t,n)}async setOffline(e){return this.backend.setOffline(e)}async cleanupStaleDevices(){return this.backend.cleanupStaleDevices()}async searchDevices(e){return this.backend.searchDevices(e)}async listDeviceStatus(){if(typeof this.backend.listDeviceStatus!="function")throw new Error("Selected runtime adapter does not support listDeviceStatus().");return this.backend.listDeviceStatus()}async getPeerSession(e){return typeof this.backend.getPeerSession!="function"?null:this.backend.getPeerSession(e)}async listPeerSessions(){return typeof this.backend.listPeerSessions!="function"?[]:this.backend.listPeerSessions()}async waitForSettledPeer(e,t){return typeof this.backend.waitForSettledPeer!="function"?null:this.backend.waitForSettledPeer(e,t)}async waitForSettledScope(e,t){return typeof this.backend.waitForSettledScope!="function"?null:this.backend.waitForSettledScope(e,t)}async resolvePeerIdentity(e){return typeof this.backend.resolvePeerIdentity!="function"?{peerId:null,deviceId:null,deviceIdHint:null,nodeId:null}:this.backend.resolvePeerIdentity(e)}async resolvePeerRecords(e){return typeof this.backend.resolvePeerRecords!="function"?[]:this.backend.resolvePeerRecords(e)}async updateDevice(e,t){return this.backend.updateDevice(e,t)}async deleteDevice(e){return this.backend.deleteDevice(e)}onDevicesChange(e,t){return this.backend.onDevicesChange(e,t)}onAuthChange(e){return this.backend.onAuthChange(e)}async checkForSSOToken(){return this.backend.checkForSSOToken()}async waitForAuth(){return this.backend.waitForAuth()}async sendMessage(e,t,n,i){return this.backend.sendMessage(e,t,n,i)}async pollMessages(e){return this.backend.pollMessages(e)}watchFriendDevices(e,t){let n=this.backend;return n.watchFriendDevices?n.watchFriendDevices(e,t):()=>{}}async updateFriendTicket(e){let t=this.backend;t.updateFriendTicket&&await t.updateFriendTicket(e);}async subscribeDevices(e){return this.backend.subscribeDevices(e)}startAutoConnect(e,t){this.backend.startAutoConnect(e,t);}async submitDesiredPeerProjection(e,t){if(typeof this.backend.submitDesiredPeerProjection!="function")throw new Error("Selected runtime adapter does not support desired-peer projections.");await this.backend.submitDesiredPeerProjection(e,t);}async startPresenceLoop(e,t,n,i,r){await this.backend.startPresenceLoop(e,t,n,i,r);}async createSession(e){return this.backend.createSession(e)}async updateSession(e,t){return this.backend.updateSession(e,t)}async subscribeSessions(e){return this.backend.subscribeSessions(e)}forceReconnect(){this.backend.forceReconnect();}async getLocalDeviceId(){return typeof this.backend.getLocalDeviceId!="function"?null:this.backend.getLocalDeviceId()}async getLocalDeviceInfo(){return typeof this.backend.getLocalDeviceInfo!="function"?null:this.backend.getLocalDeviceInfo()}async updateDeviceName(e){return typeof this.backend.updateDeviceName!="function"?null:this.backend.updateDeviceName(e)}async startNativeSession(e){let t=this.backend;if(typeof t.startNativeSession!="function")throw new Error("Selected runtime adapter does not support startNativeSession().");return t.startNativeSession(e)}async notifyNetworkChange(e){return typeof this.backend.notifyNetworkChange!="function"?null:this.backend.notifyNetworkChange(e)}async setTransportPriority(e){if(typeof this.backend.setTransportPriority!="function")throw new Error("Selected runtime adapter does not support setTransportPriority().");await this.backend.setTransportPriority(e);}async getManagedNodeId(e){if(console.info("[DelegatingRuntimeAdapter][getManagedNodeId] enter",{hasMethod:typeof this.backend.getManagedNodeId=="function",backendCtor:this.backend.constructor?.name??null}),typeof this.backend.getManagedNodeId!="function")return null;let t=await this.backend.getManagedNodeId(e);return console.info("[DelegatingRuntimeAdapter][getManagedNodeId] resolved",{result:t}),t}async startPresence(e,t,n,i,r){let o=this.backend;if(typeof o.startPresence!="function")throw new Error("Selected runtime adapter does not support startPresence().");return o.startPresence(e,t,n,i,r)}async startAutoConnectOnce(e,t){let n=this.backend;if(typeof n.startAutoConnectOnce!="function")throw new Error("Selected runtime adapter does not support startAutoConnectOnce().");return n.startAutoConnectOnce(e,t)}async getEndpointTicket(){if(typeof this.backend.getEndpointTicket!="function")throw new Error("Selected runtime adapter does not support getEndpointTicket().");return this.backend.getEndpointTicket()}async getTicketWithToken(e,t){let n=this.backend;return typeof n.getTicketWithToken!="function"?null:n.getTicketWithToken(e,t)}async registerSessionToken(e,t,n,i){let r=this.backend;typeof r.registerSessionToken=="function"&&await r.registerSessionToken(e,t,n,i);}async revokeTokens(e){let t=this.backend;return typeof t.revokeTokens!="function"?[]:t.revokeTokens(e)}async openPeerBi(e,t){if(typeof this.backend.openPeerBi!="function")throw new Error("Selected runtime adapter does not support openPeerBi().");return this.backend.openPeerBi(e,t)}async incoming_streams(){let e=this.backend;if(typeof e.incoming_streams!="function")throw new Error("Selected runtime adapter does not support incoming_streams().");return e.incoming_streams()}async incoming_projected_streams(){let e=this.backend;if(typeof e.incoming_projected_streams!="function")throw new Error("Selected runtime adapter does not support incoming_projected_streams().");return e.incoming_projected_streams()}projectedIncomingStreamSource(){let e=this.backend;return typeof e.projectedIncomingStreamSource!="function"?{incoming_streams:()=>this.incoming_projected_streams(),isCurrentTransport:(t,n)=>this.isCurrentTransport(t,n)}:e.projectedIncomingStreamSource()}async isCurrentTransport(e,t){let n=this.backend;return typeof n.isCurrentTransport=="function"?n.isCurrentTransport(e,t):typeof n.is_current_transport_stable_id!="function"?false:n.is_current_transport_stable_id(e,t)}async openPeerBiRaw(e,t){let n=this.backend;if(typeof n.openPeerBiRaw=="function")return n.openPeerBiRaw(e,t);throw new Error("Selected runtime adapter does not support the restricted transport-only diagnostic stream.")}async openPeerUni(e,t){if(typeof this.backend.openPeerUni!="function")throw new Error("Selected runtime adapter does not support openPeerUni().");return this.backend.openPeerUni(e,t)}async beginOpenRtcMediaPublication(e){if(typeof this.backend.beginOpenRtcMediaPublication!="function")throw new Error("Selected runtime adapter does not support media publications.");return this.backend.beginOpenRtcMediaPublication(e)}async encodeOpenRtcMediaSample(e){if(typeof this.backend.encodeOpenRtcMediaSample!="function")throw new Error("Selected runtime adapter does not support media samples.");return this.backend.encodeOpenRtcMediaSample(e)}async pauseOpenRtcMediaPublication(e){if(typeof this.backend.pauseOpenRtcMediaPublication!="function")throw new Error("Selected runtime adapter does not support media publications.");await this.backend.pauseOpenRtcMediaPublication(e);}async retireOpenRtcMediaPublication(e){if(typeof this.backend.retireOpenRtcMediaPublication!="function")throw new Error("Selected runtime adapter does not support media publications.");await this.backend.retireOpenRtcMediaPublication(e);}async retireOpenRtcMediaReceiver(e,t){if(typeof this.backend.retireOpenRtcMediaReceiver!="function")throw new Error("Selected runtime adapter does not support media receivers.");await this.backend.retireOpenRtcMediaReceiver(e,t);}async decodeOpenRtcMediaChunk(e){if(typeof this.backend.decodeOpenRtcMediaChunk!="function")throw new Error("Selected runtime adapter does not support the media protocol.");return this.backend.decodeOpenRtcMediaChunk(e)}async decodeOpenRtcMediaControl(e){if(typeof this.backend.decodeOpenRtcMediaControl!="function")throw new Error("Selected runtime adapter does not support the media protocol.");return this.backend.decodeOpenRtcMediaControl(e)}async connectToDevice(e){if(typeof this.backend.connectToDevice!="function")throw new Error("Selected runtime adapter does not support connectToDevice().");return this.backend.connectToDevice(e)}async disconnectDevice(e){if(typeof this.backend.disconnectDevice!="function")throw new Error("Selected runtime adapter does not support disconnectDevice().");return this.backend.disconnectDevice(e)}async excludeAutoConnect(e,t){if(typeof this.backend.excludeAutoConnect!="function")throw new Error("Selected runtime adapter does not support excludeAutoConnect().");return this.backend.excludeAutoConnect(e,t)}async isConnected(e){return this.backend.isConnected(e)}async getConnectionStates(){return typeof this.backend.getConnectionStates!="function"?[]:this.backend.getConnectionStates()}onStateChange(e){return typeof this.backend.onStateChange!="function"?()=>{}:this.backend.onStateChange(e)}async sendExplicitFilePath(e,t,n){if(typeof this.backend.sendExplicitFilePath!="function")throw new Error("Selected runtime adapter does not support sendExplicitFilePath().");return this.backend.sendExplicitFilePath(e,t,n)}async sendExplicitFileData(e){if(typeof this.backend.sendExplicitFileData!="function")throw new Error("Selected runtime adapter does not support sendExplicitFileData().");return this.backend.sendExplicitFileData(e)}async getTransferHistory(e){return typeof this.backend.getTransferHistory!="function"?[]:this.backend.getTransferHistory(e)}async deleteTransferJob(e){if(typeof this.backend.deleteTransferJob=="function")return this.backend.deleteTransferJob(e)}async sendPeerMessage(e,t){if(typeof this.backend.sendPeerMessage!="function")throw new Error("Selected runtime adapter does not support native peer messages.");await this.backend.sendPeerMessage(e,t);}onPeerMessage(e){return typeof this.backend.onPeerMessage!="function"?()=>{}:this.backend.onPeerMessage(e)}capabilities(){let e=this.backend;return typeof e.capabilities=="function"?e.capabilities():t()}async onIncomingNativeMessage(e){let t=this.backend;return typeof t.onIncomingNativeMessage!="function"?()=>{}:t.onIncomingNativeMessage(e)}unwrap(){return this.backend}setCoreClient(e){let t=this.backend;typeof t.setCoreClient=="function"&&t.setCoreClient(e);}};export{a};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
function v(c){return [...new Set(c.capabilityKeys.filter(s=>typeof s=="string").map(s=>s.trim()).filter(Boolean))]}async function h(c,s){if(!c||typeof c!="object")return;let t=c.stream,e=[];t?.recv&&e.push(t.recv.cancel(s)),t?.send&&e.push(t.send.abort(s)),await Promise.allSettled(e);}var d=class{constructor(){this.host=null;this.consumers=new Map;this.hostReader=null;this.hostPump=null;this.consecutiveEstablishedFaults=0;this.closed=false;}register(s,t){if(this.closed)throw new Error("[OpenRTC] Native projection broker is closed.");let e=s.trim();if(!e)throw new Error("[OpenRTC] Native capability projection key is required.");if(this.consumers.has(e))throw new Error(`[OpenRTC] Native capability '${e}' is already registered.`);return this.consumers.size===0?this.host=t:this.host??(this.host=t),this.consumers.set(e,{controller:null,stream:null,stateListeners:new Set,messageListeners:new Set,deviceListeners:new Set,latestDevices:null}),{__openrtcNativeCapabilityProjection:true,capabilityKey:e,incoming_streams:()=>this.incomingStreams(e),onStateChange:i=>this.subscribeState(e,i),onPeerMessage:i=>this.subscribePeerData(e,i),onDevices:i=>this.subscribeDevices(e,i),isCurrentTransport:(i,n)=>this.currentHost().isCurrentTransport(i,n)}}unregister(s){let t=s.trim(),e=this.consumers.get(t);if(e){this.consumers.delete(t);try{e.controller?.close();}catch{}e.controller=null,e.stream=null,e.stateListeners.clear(),e.messageListeners.clear(),e.deviceListeners.clear(),e.latestDevices=null,this.consumers.size===0&&this.cancelHostReader("no active native capabilities");}}subscribeState(s,t){let e=this.requireConsumer(s);return e.stateListeners.add(t),this.ensureHostPump(),()=>{e.stateListeners.delete(t),this.cancelHostReaderIfIdle();}}subscribePeerData(s,t){let e=this.requireConsumer(s);return e.messageListeners.add(t),this.ensureHostPump(),()=>{e.messageListeners.delete(t),this.cancelHostReaderIfIdle();}}subscribeDevices(s,t){let e=this.requireConsumer(s);return e.deviceListeners.add(t),this.ensureHostPump(),e.latestDevices&&t(e.latestDevices),()=>{e.deviceListeners.delete(t),this.cancelHostReaderIfIdle();}}requireConsumer(s){if(this.closed)throw new Error("[OpenRTC] Native projection broker is closed.");let t=this.consumers.get(s);if(!t)throw new Error(`[OpenRTC] Native capability '${s}' is not registered.`);return t}currentHost(){if(this.closed)throw new Error("[OpenRTC] Native projection broker is closed.");if(!this.host)throw new Error("[OpenRTC] Native projection broker has no IPC host.");return this.host}async incomingStreams(s){if(this.closed)throw new Error("[OpenRTC] Native projection broker is closed.");let t=this.requireConsumer(s);if(t.stream)return t.stream;let e;return e=new ReadableStream({start:i=>{t.controller=i,this.ensureHostPump();},cancel:()=>{t.stream===e&&(t.controller=null,t.stream=null),this.cancelHostReaderIfIdle();}},{highWaterMark:32}),t.stream=e,e}ensureHostPump(){if(this.hostPump||this.closed)return;let s=false;this.hostPump=this.pumpHost().then(t=>{s=t;}).finally(()=>{this.hostPump=null,this.hostReader=null,s&&!this.closed&&this.hasActiveConsumers()&&this.ensureHostPump();});}async pumpHost(){let s=this.currentHost(),t=null,e=false;try{let i=await s.incoming_projected_streams();if(this.closed)return await i.cancel("OpenRTC native root client closed").catch(()=>{}),!1;for(t=i.getReader(),this.hostReader=t;!this.closed&&this.hasActiveConsumers();){let{done:n,value:o}=await t.read();if(n){if(!this.closed&&this.host!==s&&this.hasActiveConsumers())return !0;for(let r of this.consumers.values()){try{r.controller?.close();}catch{}r.controller=null,r.stream=null,r.stateListeners.clear(),r.messageListeners.clear(),r.deviceListeners.clear(),r.latestDevices=null;}return this.consecutiveEstablishedFaults=0,!1}this.consecutiveEstablishedFaults=0;let u=v(o);if(o.kind==="stream"){let r=u.length===1?u[0]:null,a=r?this.consumers.get(r):void 0;if(!a?.controller||(a.controller.desiredSize??0)<=0){await h(o.payload,r?`inactive native capability ${r}`:"ambiguous unscoped native projection");continue}a.controller.enqueue(o.payload);continue}for(let r of u){let a=this.consumers.get(r);if(a)if(o.kind==="connection-state")for(let l of a.stateListeners)l(o.payload);else if(o.kind==="devices"){a.latestDevices=o.payload.devices;for(let l of a.deviceListeners)l(o.payload.devices);}else for(let l of a.messageListeners)l(o.payload);}}return !this.closed&&this.host!==s&&this.hasActiveConsumers()}catch(i){if(!this.closed){e=t!==null&&this.consecutiveEstablishedFaults===0,e?this.consecutiveEstablishedFaults=1:this.consecutiveEstablishedFaults=0;for(let n of this.consumers.values()){try{n.controller?.error(i);}catch{}n.controller=null,n.stream=null,e||(n.stateListeners.clear(),n.messageListeners.clear(),n.deviceListeners.clear(),n.latestDevices=null);}}return e}finally{let i=t;if(this.hostReader===i&&(this.hostReader=null),i)try{i.releaseLock();}catch{}typeof s.releaseNativeProjectionSubscription=="function"&&await s.releaseNativeProjectionSubscription().catch(()=>{});}}hasActiveConsumers(){return [...this.consumers.values()].some(s=>s.controller!==null||s.stateListeners.size>0||s.messageListeners.size>0||s.deviceListeners.size>0)}cancelHostReaderIfIdle(){this.hasActiveConsumers()||this.cancelHostReader("no active native projection consumers");}async cancelHostReader(s){let t=this.hostReader;this.hostReader=null,await t?.cancel(s).catch(()=>{});}async close(){if(this.closed){await this.hostPump;return}this.closed=true;for(let s of this.consumers.values())try{s.controller?.close();}catch{}this.consumers.clear(),this.host=null,await this.cancelHostReader("OpenRTC native root client closed"),await this.hostPump;}};export{d as a};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import {j,d as d$1,c}from'./chunk-
|
|
1
|
+
import {j,d as d$1,c}from'./chunk-42TNJH5S.js';var E=/^[A-Za-z0-9_.:@-]+$/,P=/^[A-Za-z0-9_-]{43}$/,C=/^[A-Za-z0-9_.:@-]+$/,k=/^[A-Za-z0-9._-]+$/,x=120*6e4,A=new TextEncoder;function d(r,e,t=160){let n=r.trim();if(!n||n.length>t||!E.test(n))throw new TypeError(`[OpenRTC] ${e} is invalid.`);return n}function h(r,e,t=Number.MAX_SAFE_INTEGER){if(!Number.isSafeInteger(r)||r<1||r>t)throw new RangeError(`[OpenRTC] ${e} must be a positive safe integer.`);return r}function K(r){let e="";for(let t of r)e+=String.fromCharCode(t);return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,"")}async function g(r,e){let t=await r.publicJwk();if(t.kty!=="OKP"||t.crv!=="Ed25519"||typeof t.x!="string"||!P.test(t.x)||t.d!==void 0)throw new TypeError(`[OpenRTC] ${e} must return an Ed25519 public JWK.`);return {kty:"OKP",crv:"Ed25519",x:t.x}}async function y(r,e,t){let n=await r.sign(e);if(!(n instanceof Uint8Array)||n.byteLength!==64)throw new TypeError(`[OpenRTC] ${t} returned an invalid Ed25519 signature.`);return K(n)}function T(r){if(!/^pk_(?:live|test)_[A-Za-z0-9]+$/.test(r))throw new TypeError("[OpenRTC] apiKey is invalid.");return `app_${r.slice(-16)}`}function u(r){return r!==null&&typeof r=="object"&&!Array.isArray(r)?r:null}function v(r,e,t,n){if(typeof r!="string"||r.length<1||r.length>t||r!==r.trim()||n&&!n.test(r))throw new Error(`[OpenRTC] authority service grant ${e} is invalid.`);return r}function O(r){let e=v(r,"gatewayUrl",2048),t;try{t=new URL(e);}catch{throw new Error("[OpenRTC] authority service grant gatewayUrl is invalid.")}let n=t.protocol==="http:"&&["127.0.0.1","localhost","::1"].includes(t.hostname.toLowerCase());if(t.protocol!=="https:"&&!n||t.username||t.password||t.search||t.hash)throw new Error("[OpenRTC] authority service grant gatewayUrl is invalid.");return e}function N(r,e){let t=u(r),n=u(t?.avenue),i=u(t?.roomAuthority),a=u(i?.assignmentPublicKeyJwk),c=Date.now(),o=t?.expiresAtMs,s=t?.maxPeers;if(!t||t.protocolVersion!==2||t.architecture!=="authority"||n?.kind!=="room"||n.id!==e.roomId||i?.serviceId!==e.serviceId||i.generation!==e.generation||!Array.isArray(i.shardIds)||i.shardIds.length!==e.shardIds.length||i.shardIds.some((m,l)=>m!==e.shardIds[l])||a?.kty!=="OKP"||a.crv!=="Ed25519"||a.x!==e.assignmentPublicKeyX||!Number.isSafeInteger(o)||o<=c||o>c+x||!Number.isSafeInteger(s)||s<1||s>e.maxPeers)throw new Error("[OpenRTC] authority service grant response is inconsistent.");return {protocolVersion:2,gatewayUrl:O(t.gatewayUrl),routeKey:v(t.routeKey,"routeKey",256,C),token:v(t.token,"token",24e3,k),expiresAtMs:o,avenue:{kind:"room",id:e.roomId},maxPeers:s,architecture:"authority",roomAuthority:{serviceId:e.serviceId,generation:e.generation,shardIds:[...e.shardIds],assignmentPublicKeyJwk:{kty:"OKP",crv:"Ed25519",x:e.assignmentPublicKeyX}}}}var p=class{constructor(e){if(this.apiKey=e.apiKey,this.applicationTag=T(e.apiKey),typeof e.grantIssuer!="function")throw new TypeError("[OpenRTC] ServiceNode requires a browser-safe grantIssuer.");if(this.grantIssuer=e.grantIssuer,this.serviceId=d(e.serviceId,"serviceId",80),this.generation=h(e.generation,"generation"),this.shardIds=[...new Set(e.shardIds.map(t=>d(t,"shardId",80)))].sort(),this.shardIds.length<1||this.shardIds.length>64||this.shardIds.length!==e.shardIds.length)throw new RangeError("[OpenRTC] shardIds must contain 1..64 unique identifiers.");this.deviceId=d(e.deviceId,"deviceId"),this.deviceSigner=e.deviceSigner,this.assignmentSigner=e.assignmentSigner;}async requestGrant(e){let t=d(e.roomId,"roomId"),n=d(e.runtimeInstanceId,"runtimeInstanceId");if(!P.test(e.ticketFingerprint))throw new TypeError("[OpenRTC] ticketFingerprint is invalid.");e.maxPeers!==void 0&&h(e.maxPeers,"maxPeers",50);let i=await g(this.assignmentSigner,"assignmentSigner.publicJwk()"),a=await g(this.deviceSigner,"deviceSigner.publicJwk()"),c=crypto.randomUUID().replace(/-/g,""),o=Math.floor(Date.now()/1e3),s=["openrtc:v2:authority-service-grant",this.applicationTag,t,this.serviceId,String(this.generation),this.shardIds.join(","),i.x,n,c,o].join(":"),m={avenue:{kind:"room",id:t},serviceId:this.serviceId,generation:this.generation,shardIds:this.shardIds,assignmentPublicKeyJwk:i,deviceId:this.deviceId,runtimeInstanceId:n,ticketFingerprint:e.ticketFingerprint,deviceProof:{publicKeyJwk:a,nonce:c,issuedAt:o,signature:await y(this.deviceSigner,A.encode(s),"deviceSigner.sign()")},...e.maxPeers===void 0?{}:{maxPeers:e.maxPeers},...e.refreshGrant?{refreshGrant:e.refreshGrant}:{},features:e.features??{}},l=`authority_${crypto.randomUUID().replace(/-/g,"")}`,R=await this.grantIssuer({apiKey:this.apiKey,idempotencyKey:l,body:m});return N(R,{roomId:t,serviceId:this.serviceId,generation:this.generation,shardIds:this.shardIds,assignmentPublicKeyX:i.x,maxPeers:e.maxPeers??50})}async devicePublicKey(){return g(this.deviceSigner,"deviceSigner.publicJwk()")}async assignmentPublicKey(){return g(this.assignmentSigner,"assignmentSigner.publicJwk()")}async signDeviceBytes(e){return y(this.deviceSigner,e,"deviceSigner.sign()")}async signAssignment(e){let t=e.ttlMs??6e4;h(t,"ttlMs",2*6e4);let n=d(e.shardId,"shardId",80);if(!this.shardIds.includes(n))throw new RangeError("[OpenRTC] assignment shard is not owned by this service.");let i=e.priorityDeviceIds??[],a=e.relevantEntityIds??[];if(i.length>8||a.length>32)throw new RangeError("[OpenRTC] assignment exceeds the 8-edge or 32-entity bound.");let c=Date.now(),o={policyVersion:"room-authority-assignment-v1",serviceId:this.serviceId,generation:this.generation,revision:h(e.revision,"revision"),subjectDeviceId:d(e.subjectDeviceId,"subjectDeviceId"),shardId:n,priorityDeviceIds:i.map(s=>d(s,"priorityDeviceId")),relevantEntityIds:a.map(s=>d(s,"relevantEntityId")),issuedAtMs:c,expiresAtMs:c+t};if(new Set(o.priorityDeviceIds).size!==o.priorityDeviceIds.length||new Set(o.relevantEntityIds).size!==o.relevantEntityIds.length)throw new RangeError("[OpenRTC] assignment identifiers must be unique.");return {assignment:o,signature:await y(this.assignmentSigner,A.encode(JSON.stringify(o)),"assignmentSigner.sign()")}}},I=class{constructor(e,t,n){this.room=e;this.authority=t;this.onClosed=n;this.releaseRuntimeAlias=d$1(this,e);}get kind(){return this.room.kind}get id(){return this.room.id}get peers(){return this.room.peers}get channels(){return this.room.channels}get diagnostics(){return this.room.diagnostics}get closed(){return this.room.closed}get membership(){return this.room.membership}state(e){return this.room.state(e)}channel(e){return this.room.channel(e)}onConnection(e){return this.room.onConnection(e)}architecture(){return this.room.architecture()}onArchitectureChanged(e){return this.room.onArchitectureChanged(e)}authorityAssignment(){return this.room.authorityAssignment()}onAuthorityAssignmentChanged(e){return this.room.onAuthorityAssignmentChanged(e)}leave(){return this.retire(()=>this.room.leave())}close(){return this.retire(()=>this.room.close())}async publishAssignment(e){let t=await this.authority.signAssignment(e);return await c(this.room).advanced.runtime.publishAuthorityAssignment(t),t.assignment}retire(e){return this.retirement??(this.retirement=e().finally(()=>{this.releaseRuntimeAlias(),this.onClosed();}))}},S=class{constructor(e){this.options=e;this.rooms=new Map;this.connectionListeners=new Set;this.connectionCleanups=new Map;this.closed=false;if("secretKey"in e)throw new TypeError("[OpenRTC] ServiceNode never accepts secretKey; delegate short-lived grants.");this.authority=new p(e);}listen(e){if(this.closed)throw new Error("[OpenRTC] ServiceNode is closed.");let t=d(e,"roomId"),n=this.rooms.get(t);if(n)return n.promise;let i={};return i.promise=this.openRoom(t,()=>this.evictRoom(t,i)).catch(a=>{throw this.evictRoom(t,i),a}),this.rooms.set(t,i),i.promise}onConnection(e){if(this.connectionListeners.add(e),this.connectionListeners.size===1)for(let[t,n]of this.rooms)n.promise.then(i=>this.attachConnectionListener(t,i),()=>{});return ()=>{if(this.connectionListeners.delete(e),this.connectionListeners.size===0){for(let t of this.connectionCleanups.values())t();this.connectionCleanups.clear();}}}async close(){if(this.closed)return;this.closed=true;for(let t of this.connectionCleanups.values())t();this.connectionCleanups.clear();let e=await Promise.allSettled([...this.rooms.values()].map(t=>t.promise));await Promise.all(e.flatMap(t=>t.status==="fulfilled"?[t.value.close()]:[])),this.rooms.clear(),this.connectionListeners.clear();}async openRoom(e,t){let n=await this.options.client.devices.localId();if(n!==this.options.deviceId)throw new Error("[OpenRTC] ServiceNode deviceId must match the client installation.");let[i,a]=await Promise.all([this.authority.devicePublicKey(),this.authority.assignmentPublicKey()]),c=await j(this.options.client,{roomId:e,serviceId:this.options.serviceId,generation:this.options.generation,shardIds:this.options.shardIds,deviceId:n,maxPeers:this.options.maxPeers,irohRelay:this.options.irohRelay!==false,devicePublicKeyX:i.x,assignmentPublicKeyX:a.x,deviceSign:s=>this.authority.signDeviceBytes(s),grantProvider:async s=>{if(s.avenue.kind!=="room"||s.avenue.id!==e)throw new Error("[OpenRTC] ServiceNode grant request escaped its room.");if(s.deviceId!==n)throw new Error("[OpenRTC] ServiceNode grant request escaped its device.");return this.authority.requestGrant({roomId:e,runtimeInstanceId:s.runtimeInstanceId,ticketFingerprint:s.ticketFingerprint,maxPeers:this.options.maxPeers,refreshGrant:s.refreshGrant,features:{irohRelay:this.options.irohRelay!==false}})}}),o=new I(c,this.authority,t);return this.attachConnectionListener(e,o),o}evictRoom(e,t){this.rooms.get(e)===t&&(this.rooms.delete(e),this.connectionCleanups.get(e)?.(),this.connectionCleanups.delete(e));}attachConnectionListener(e,t){this.closed||this.connectionListeners.size===0||this.connectionCleanups.has(e)||this.connectionCleanups.set(e,t.onConnection(n=>{for(let i of this.connectionListeners)i({room:t,connection:n});}));}};
|
|
2
2
|
export{p as a,S as b};
|