openrtc 3.1.0 → 3.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (67) hide show
  1. package/dist/{Connection-BGVBMbWg.d.ts → Connection-U3fEt8_4.d.ts} +35 -1
  2. package/dist/{DelegatingRuntimeAdapter-JmhmwKTC.d.ts → DelegatingRuntimeAdapter-Coo5BVM2.d.ts} +2 -2
  3. package/dist/{IpcRuntimeAdapter-DMQoN2XL.d.ts → IpcRuntimeAdapter-D188hRAr.d.ts} +2 -2
  4. package/dist/{WasmBridge-CJNESUGJ.js → WasmBridge-3HYLCY5Y.js} +1 -1
  5. package/dist/{assembly-DGrOqsLW.d.ts → assembly-CtrHmP4j.d.ts} +2 -2
  6. package/dist/{capabilities-DsKud7Sw.d.ts → capabilities-Dxb0XOti.d.ts} +1 -1
  7. package/dist/chunk-5336XOTL.js +2 -0
  8. package/dist/chunk-KI7XXVXH.js +1 -0
  9. package/dist/chunk-M2QMGAL2.js +2 -0
  10. package/dist/{chunk-SADNIMUO.js → chunk-M4KL5XZU.js} +1 -1
  11. package/dist/{chunk-5LO6PLWZ.js → chunk-PA4WT4QM.js} +1 -1
  12. package/dist/{chunk-5LNRJE6L.js → chunk-RUOVYQ2P.js} +1 -1
  13. package/dist/{chunk-RLPWFHOY.js → chunk-SSBR3IHA.js} +1 -1
  14. package/dist/{chunk-VARKDQGM.js → chunk-TSMMRR5V.js} +1 -1
  15. package/dist/chunk-V57WKJSB.js +2 -0
  16. package/dist/chunk-WTOA6B2A.js +2 -0
  17. package/dist/chunk-XNJI6KCI.js +2 -0
  18. package/dist/controlPlane-HOFWXQJW.js +1 -0
  19. package/dist/{coreClient-ByXs38IP.d.ts → coreClient-AVGEwlhT.d.ts} +3 -3
  20. package/dist/coreClient.d.ts +4 -4
  21. package/dist/coreClient.js +1 -1
  22. package/dist/{deviceHandle-Y2XA57WF.js → deviceHandle-DFG3CCY3.js} +1 -1
  23. package/dist/deviceKey-4DLS246L.js +1 -0
  24. package/dist/external-broadcast.d.ts +5 -5
  25. package/dist/external-broadcast.js +1 -1
  26. package/dist/index.d.ts +7 -7
  27. package/dist/index.js +1 -1
  28. package/dist/{ipcFactory-F75IXEIE.js → ipcFactory-6XD3J2UU.js} +1 -1
  29. package/dist/native.d.ts +6 -6
  30. package/dist/native.js +1 -1
  31. package/dist/node.d.ts +7 -7
  32. package/dist/node.js +2 -2
  33. package/dist/openrtc_bg.wasm +0 -0
  34. package/dist/{room-E4NRHQFD.js → room-ZQU7JFRG.js} +1 -1
  35. package/dist/runtime/WasmRuntimeAdapter.d.ts +3 -3
  36. package/dist/runtime/WasmRuntimeAdapter.js +1 -1
  37. package/dist/runtime/device-status.d.ts +1 -1
  38. package/dist/runtime/factories.d.ts +5 -5
  39. package/dist/runtime/factories.js +1 -1
  40. package/dist/runtime/index.d.ts +10 -10
  41. package/dist/runtime/index.js +1 -1
  42. package/dist/server-browser.d.ts +5 -5
  43. package/dist/server.d.ts +5 -5
  44. package/dist/server.js +1 -1
  45. package/dist/service-node.d.ts +8 -7
  46. package/dist/service-node.js +1 -1
  47. package/dist/testing/native.d.ts +5 -5
  48. package/dist/testing/native.js +1 -1
  49. package/dist/testing.d.ts +7 -36
  50. package/dist/testing.js +1 -1
  51. package/dist/transport/index.d.ts +2 -2
  52. package/dist/{types-Cruu-MsF.d.ts → types-DvZvz4EL.d.ts} +2 -2
  53. package/native/darwin-arm64/openrtc-node-host +0 -0
  54. package/native/darwin-arm64/openrtc-node-host.manifest.json +4 -4
  55. package/native/darwin-x64/openrtc-node-host +0 -0
  56. package/native/darwin-x64/openrtc-node-host.manifest.json +4 -4
  57. package/native/linux-x64/openrtc-node-host +0 -0
  58. package/native/linux-x64/openrtc-node-host.manifest.json +4 -4
  59. package/package.json +1 -1
  60. package/dist/chunk-2Q75GXGE.js +0 -2
  61. package/dist/chunk-GMPEZXPD.js +0 -2
  62. package/dist/chunk-IAYQJZQQ.js +0 -1
  63. package/dist/chunk-L4HWDDXL.js +0 -2
  64. package/dist/chunk-LVLU4YQY.js +0 -2
  65. package/dist/chunk-NS32P65Z.js +0 -2
  66. package/dist/controlPlane-45AU3CSM.js +0 -1
  67. package/dist/deviceKey-2NTRYCSR.js +0 -1
@@ -1 +1 @@
1
- import {s}from'./chunk-SADNIMUO.js';import {e}from'./chunk-LCJQ7RSR.js';function v(i,d){let t=new s(i,d),a=i.spaceKey??i.space,l=(i.discoveryMode===void 0||i.discoveryMode==="space")&&typeof i.apiKey=="string"&&i.apiKey.trim().length>0&&typeof a=="string"&&a.trim().length>0,o={runtime:t,async setAuthContext(e){await t.setAuthContext(e);},async syncPlutoAuth(e$1){if(l)return;let n=e(),c=n.getCurrentUser(),r=(typeof e$1?.userId=="string"?e$1.userId.trim():"")||c?.uid||null;if(!r){await o.setAuthContext(null);return}let m=await n.getIdToken({forceRefresh:e$1?.forceRefresh??false}).catch(()=>null),g=n.getCurrentUser()?.refreshToken??null,h=n.getCurrentUser()?.stsTokenManager?.expirationTime??null;await o.setAuthContext({userId:r,token:m,refreshToken:g,tokenProvider:async y=>n.getIdToken({forceRefresh:y??false}),expiresAtMs:h});},bindPlutoAuthHost(){let e$1=e();return o.syncPlutoAuth({userId:e$1.getCurrentUser()?.uid??null,forceRefresh:false}),e$1.onIdTokenChanged(n=>{o.syncPlutoAuth({userId:n?.uid??null,forceRefresh:false});})},signInWithPluto:()=>t.signInWithPluto(),signOut:()=>t.signOut(),stopManagedSession:()=>t.stopManagedSession(),startManagedSession:e=>t.startManagedSession(e),onAuthChange:e=>t.onIdentityChange(e),getManagedNodeId:e=>t.getManagedNodeId(e),getRuntimeStatus:()=>t.getRuntimeStatus(),listDeviceStatus:()=>t.listDeviceStatus(),watchDeviceStatus:e=>t.watchDeviceStatus(e),connectDevice:(e,n)=>t.connectDevice(e,n),excludeAutoConnect:(e,n)=>t.excludeAutoConnect(e,n)};return Object.defineProperty(o,"identity",{get:()=>t.identity,enumerable:true}),o}export{v as a};
1
+ import {s}from'./chunk-M4KL5XZU.js';import {e}from'./chunk-LCJQ7RSR.js';function v(i,d){let t=new s(i,d),a=i.spaceKey??i.space,l=(i.discoveryMode===void 0||i.discoveryMode==="space")&&typeof i.apiKey=="string"&&i.apiKey.trim().length>0&&typeof a=="string"&&a.trim().length>0,o={runtime:t,async setAuthContext(e){await t.setAuthContext(e);},async syncPlutoAuth(e$1){if(l)return;let n=e(),c=n.getCurrentUser(),r=(typeof e$1?.userId=="string"?e$1.userId.trim():"")||c?.uid||null;if(!r){await o.setAuthContext(null);return}let m=await n.getIdToken({forceRefresh:e$1?.forceRefresh??false}).catch(()=>null),g=n.getCurrentUser()?.refreshToken??null,h=n.getCurrentUser()?.stsTokenManager?.expirationTime??null;await o.setAuthContext({userId:r,token:m,refreshToken:g,tokenProvider:async y=>n.getIdToken({forceRefresh:y??false}),expiresAtMs:h});},bindPlutoAuthHost(){let e$1=e();return o.syncPlutoAuth({userId:e$1.getCurrentUser()?.uid??null,forceRefresh:false}),e$1.onIdTokenChanged(n=>{o.syncPlutoAuth({userId:n?.uid??null,forceRefresh:false});})},signInWithPluto:()=>t.signInWithPluto(),signOut:()=>t.signOut(),stopManagedSession:()=>t.stopManagedSession(),startManagedSession:e=>t.startManagedSession(e),onAuthChange:e=>t.onIdentityChange(e),getManagedNodeId:e=>t.getManagedNodeId(e),getRuntimeStatus:()=>t.getRuntimeStatus(),listDeviceStatus:()=>t.listDeviceStatus(),watchDeviceStatus:e=>t.watchDeviceStatus(e),connectDevice:(e,n)=>t.connectDevice(e,n),excludeAutoConnect:(e,n)=>t.excludeAutoConnect(e,n)};return Object.defineProperty(o,"identity",{get:()=>t.identity,enumerable:true}),o}export{v as a};
@@ -0,0 +1,2 @@
1
+ import {g,b,d as d$1,c}from'./chunk-XNJI6KCI.js';import {j,d as d$2,c as c$1}from'./chunk-RUOVYQ2P.js';var N=/^[A-Za-z0-9_.:@-]+$/,k=/^[A-Za-z0-9_-]{43}$/,_=/^[A-Za-z0-9_.:@-]+$/,G=/^[A-Za-z0-9._-]+$/,U=120*6e4,E=new TextEncoder;function d(r,e,t=160){let n=r.trim();if(!n||n.length>t||!N.test(n))throw new TypeError(`[OpenRTC] ${e} is invalid.`);return n}function u(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 M(r){let e="";for(let t of r)e+=String.fromCharCode(t);return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,"")}async function m(r,e){let t=await r.publicJwk();if(t.kty!=="OKP"||t.crv!=="Ed25519"||typeof t.x!="string"||!k.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 M(n)}function J(r){if(!/^pk_(?:live|test)_[A-Za-z0-9]+$/.test(r))throw new TypeError("[OpenRTC] apiKey is invalid.");return `app_${r.slice(-16)}`}function l(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 L(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 $(r,e){let t=l(r),n=l(t?.avenue),i=l(t?.roomAuthority),a=l(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((g,h)=>g!==e.shardIds[h])||a?.kty!=="OKP"||a.crv!=="Ed25519"||a.x!==e.assignmentPublicKeyX||!Number.isSafeInteger(o)||o<=c||o>c+U||!Number.isSafeInteger(s)||s<1||s>e.maxPeers)throw new Error("[OpenRTC] authority service grant response is inconsistent.");return {protocolVersion:2,gatewayUrl:L(t.gatewayUrl),routeKey:v(t.routeKey,"routeKey",256,_),token:v(t.token,"token",24e3,G),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=J(e.apiKey),this.rootClientKey=g().getOrCreate(this.applicationTag),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=u(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(!k.test(e.ticketFingerprint))throw new TypeError("[OpenRTC] ticketFingerprint is invalid.");e.maxPeers!==void 0&&u(e.maxPeers,"maxPeers",50);let i=await m(this.assignmentSigner,"assignmentSigner.publicJwk()"),a=await m(this.deviceSigner,"deviceSigner.publicJwk()"),c$1=crypto.randomUUID().replace(/-/g,""),o=Math.floor(Date.now()/1e3),s=["authority-service-grant",this.applicationTag,t,this.serviceId,String(this.generation),this.shardIds.join(","),String(i.x),this.deviceId,n,e.ticketFingerprint],g=e.rootProof===void 0?await this.rootClientKey:void 0,h=e.rootProof??(g?await b(g,s):void 0),f=h?await d$1(h.publicKeyJwk):void 0,x=f?c(s,f,c$1,o):["openrtc:v2:authority-service-grant",this.applicationTag,t,this.serviceId,String(this.generation),this.shardIds.join(","),i.x,n,c$1,o].join(":"),T={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$1,issuedAt:o,signature:await y(this.deviceSigner,E.encode(x),"deviceSigner.sign()")},...e.maxPeers===void 0?{}:{maxPeers:e.maxPeers},...e.refreshGrant?{refreshGrant:e.refreshGrant}:{},...h?{rootProof:h}:{},features:e.features??{}},O=`authority_${crypto.randomUUID().replace(/-/g,"")}`,D=await this.grantIssuer({apiKey:this.apiKey,idempotencyKey:O,body:T});return $(D,{roomId:t,serviceId:this.serviceId,generation:this.generation,shardIds:this.shardIds,assignmentPublicKeyX:i.x,maxPeers:e.maxPeers??50})}async devicePublicKey(){return m(this.deviceSigner,"deviceSigner.publicJwk()")}async assignmentPublicKey(){return m(this.assignmentSigner,"assignmentSigner.publicJwk()")}async signDeviceBytes(e){return y(this.deviceSigner,e,"deviceSigner.sign()")}async signAssignment(e){let t=e.ttlMs??6e4;u(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:u(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,E.encode(JSON.stringify(o)),"assignmentSigner.sign()")}}},I=class{constructor(e,t,n){this.room=e;this.authority=t;this.onClosed=n;this.releaseRuntimeAlias=d$2(this,e);}get kind(){return this.room.kind}get id(){return this.room.id}get peers(){return this.room.peers}get channels(){return this.room.channels}get diagnostics(){return this.room.diagnostics}get closed(){return this.room.closed}get membership(){return this.room.membership}get members(){return this.room.members}state(e){return this.room.state(e)}channel(e){return this.room.channel(e)}onConnection(e){return this.room.onConnection(e)}architecture(){return this.room.architecture()}onArchitectureChanged(e){return this.room.onArchitectureChanged(e)}authorityAssignment(){return this.room.authorityAssignment()}onAuthorityAssignmentChanged(e){return this.room.onAuthorityAssignmentChanged(e)}leave(){return this.retire(()=>this.room.leave())}close(){return this.retire(()=>this.room.close())}async publishAssignment(e){let t=await this.authority.signAssignment(e);return await c$1(this.room).advanced.runtime.publishAuthorityAssignment(t),t.assignment}retire(e){return this.retirement??(this.retirement=e().finally(()=>{this.releaseRuntimeAlias(),this.onClosed();}))}},K=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,rootProof:s.rootProof,maxPeers:this.options.maxPeers,refreshGrant:s.refreshGrant,features:{irohRelay:this.options.irohRelay!==false}})}}),o=new I(c,this.authority,t);return this.attachConnectionListener(e,o),o}evictRoom(e,t){this.rooms.get(e)===t&&(this.rooms.delete(e),this.connectionCleanups.get(e)?.(),this.connectionCleanups.delete(e));}attachConnectionListener(e,t){this.closed||this.connectionListeners.size===0||this.connectionCleanups.has(e)||this.connectionCleanups.set(e,t.onConnection(n=>{for(let i of this.connectionListeners)i({room:t,connection:n});}));}};
2
+ export{p as a,K as b};
@@ -0,0 +1,2 @@
1
+ import {d}from'./chunk-OWKAJPOI.js';import {a as a$1,d as d$1,c}from'./chunk-2GX6GB6L.js';var P=new Set;function p(e,t){P.has(e)||(P.add(e),console.warn(t));}function T(e){return /^pk_(live|test)_[0-9a-f]{40}$/.test(e)}async function F(e,t){let r=`${e}:${t}`,o=new TextEncoder().encode(r),s=await crypto.subtle.digest("SHA-256",o);return Array.from(new Uint8Array(s)).map(R=>R.toString(16).padStart(2,"0")).join("")}function u(e){let t=typeof e.apiKey=="string"?e.apiKey.trim():"";if(t)return T(t)||p(`invalid-api-key:${t.slice(0,10)}`,"[pluto-rtc] The provided `apiKey` does not match the expected format (pk_live_... or pk_test_...). Create an app at https://api.openrtc.app/developer."),`app_${t.slice(-16)}`;throw new Error("[openrtc] `apiKey` is required. Create an app at https://api.openrtc.app/developer.")}function a(e){return e.authMode?e.authMode:("apiKey"in e&&typeof e.apiKey=="string"&&e.apiKey.trim().length>0&&typeof(e.spaceKey??e.space)=="string"&&(e.spaceKey??e.space).trim().length>0||p("default-auth-mode","[pluto-rtc] `authMode` is not set; defaulting to `anonymous` for compatibility."),"anonymous")}function K(e){let t=typeof e.projectId=="string"?e.projectId.trim():"";return t||(p("default-project-id","[pluto-rtc] `projectId` is not set; defaulting to the built-in PlutoRTC Firebase project."),i)}function v(e){return e.trim().replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"")}function j(e){let t="storagePrefix"in e&&typeof e.storagePrefix=="string"?v(e.storagePrefix):"";return t||v(u(e))||"default"}var x={devicesPerUser:100,maxRooms:1e4,maxMembersPerRoom:50,maxPersonalDevices:25e3},G=x;var M=[{urls:"stun:stun.l.google.com:19302"},{urls:"stun:stun.cloudflare.com:3478"}],f={iceServers:M};var A=/^[A-Za-z0-9._-]+$/,D="[redacted]";function I(e){let t;try{t=new URL(e);}catch{throw new Error("[OpenRTC] transports.moq.relayUrl must be a valid HTTPS URL.")}if(t.protocol!=="https:")throw new Error("[OpenRTC] transports.moq.relayUrl must use HTTPS/WebTransport.");if(t.hash)throw new Error("[OpenRTC] transports.moq.relayUrl must not contain a fragment.");if(t.searchParams.has("jwt"))throw new Error("[OpenRTC] transports.moq.relayUrl must not contain a jwt query parameter; use transports.moq.accessToken.");return t}function m(e){return I(e.trim()).toString()}function Q(e,t){let r=I(e.trim());if(t!==void 0){let n=t.trim();if(!n)throw new Error("[OpenRTC] transports.moq.accessToken must not be empty when provided.");if(new TextEncoder().encode(n).byteLength>16384)throw new Error("[OpenRTC] transports.moq.accessToken exceeds the maximum supported size.");if(!A.test(n))throw new Error("[OpenRTC] transports.moq.accessToken must be a URL-safe JWT.");r.searchParams.append("jwt",n);}return r.toString()}function z(e,t){let r=e instanceof Error?`${e.name}: ${e.message}`:String(e),n=t?.trim();return n?r.split(n).join(D):r}var h=[...d];function g(e){let t=e.spaceKey??e.space;return {...e,...t!==void 0?{spaceKey:t}:{}}}function S(e){return {...e,iceServers:e.iceServers?e.iceServers.map(t=>({...t})):e.iceServers}}function O(e){return {...e}}function w(e){return {...e}}function k(e){if(e)return {relay:e.relay,iroh:typeof e.iroh=="object"?w(e.iroh):e.iroh,webrtc:typeof e.webrtc=="object"?S(e.webrtc):e.webrtc,ble:typeof e.ble=="object"?{...e.ble}:e.ble,moq:typeof e.moq=="object"?O(e.moq):e.moq,privacy:e.privacy,optimizeFor:e.optimizeFor,priority:a$1(e.priority)}}function N(e){if(e.strictMode&&!e.transports&&(e.transports={iroh:{relayOnly:true}}),!!e.transports){if(e.transports.webrtc===true?e.transports.webrtc=S(f):e.transports.webrtc===false&&(e.transports.webrtc=void 0),e.transports.moq===true)throw new Error("[OpenRTC] transports.moq=true is ambiguous because no anonymous MoQ relay is available; provide transports.moq.relayUrl explicitly.");if(e.transports.moq===false)e.transports.moq=void 0;else if(e.transports.moq&&typeof e.transports.moq=="object"){let t=e.transports.moq,r=t.relayUrl?.trim(),n=t.accessToken;if(n!==void 0&&!n.trim())throw new Error("[OpenRTC] transports.moq.accessToken must not be empty when provided.");e.transports.moq={...t,...r?{relayUrl:m(r)}:{},...n!==void 0?{accessToken:n.trim()}:{}};}if(e.transports.iroh===true?e.transports.iroh={}:e.transports.iroh===false&&(e.transports.iroh=void 0),e.transports.privacy==="relay-only"){let t=e.transports.iroh&&typeof e.transports.iroh=="object"?e.transports.iroh:{};e.transports.iroh={...t,relayOnly:true,localDiscovery:false,localDiscoveryMode:void 0},e.transports.ble=void 0;let r=e.transports.webrtc;r&&typeof r=="object"&&(e.transports.webrtc={...r,privacyMode:true,lanMode:false,iceServers:c(r.iceServers)??[],iceTransportPolicy:"relay"}),e.transports.priority=d$1(e.transports.priority,!!e.transports.webrtc);}}}function E(e){if(!e.strictMode||!e.transports)return;let t=e.transports.iroh&&typeof e.transports.iroh=="object"?e.transports.iroh:{};e.transports.iroh={...t,relayOnly:true,relayTransportPolicy:t.relayTransportPolicy??"websocketRequired",localDiscovery:false,localDiscoveryMode:void 0},e.transports.privacy="relay-only",e.transports.ble=void 0;let r=e.transports.webrtc;r&&typeof r=="object"&&(e.transports.webrtc={...r,privacyMode:true,lanMode:false,iceServers:c(r.iceServers)??[],iceTransportPolicy:"relay"});let n=e.transports.moq;if(n&&typeof n=="object"){let o=n.relayUrl?.trim();if(!o)throw new Error("[OpenRTC] strictMode requires an explicit transports.moq.relayUrl.");e.transports.moq={...n,relayUrl:m(o)};}}function Z(e){let t=g(e),r=u(t),n=a(t),o={strictMode:false,disableIrohFallback:false,transportPriority:[...h],...t,authMode:n,transports:k(t.transports)};N(o),E(o),o.transportPriority=a$1(t.transportPriority??o.transports?.priority)??[...h],(o.strictMode||o.transports?.privacy==="relay-only")&&(o.transportPriority=d$1(t.transportPriority??o.transports?.priority,!!o.transports?.webrtc));let s=C(o),y=(o.discoveryMode??"space")==="space"?"client-open":"client-auth";return {appTag:r,authMode:n,configuredPersistenceMode:s,options:o,roomCreationMode:y}}function C(e){let t=e.transports?.iroh;return e.endpointIdPersistence??e.nodeIdPersistence??(typeof t=="object"?t.persistenceMode:void 0)??"ephemeral"}function ee(e){return "options"in e&&"configuredPersistenceMode"in e?{apiKey:e.options.apiKey,authMode:a(e.options),projectId:e.options.projectId,storagePrefix:e.options.storagePrefix,nodeIdPersistence:e.configuredPersistenceMode}:{apiKey:e.apiKey,authMode:a(e),projectId:e.projectId,storagePrefix:e.storagePrefix,nodeIdPersistence:C(e)}}function te(e,t){t&&(e.transports={...e.transports||{},...t});}var i="pluto-rtc-prod",U="https://api.openrtc.app",_="https://gateway.openrtc.app";function oe(e){let t=g(e),n=(typeof t.projectId=="string"&&t.projectId.trim()?t.projectId.trim():void 0)??i,o=n===i;return {...t,projectId:n,coordinationGateway:t.coordinationGateway??(o?{endpoint:_,controlPlaneEndpoint:U,environment:"production"}:void 0)}}
2
+ export{oe as a,F as b,u as c,a as d,K as e,j as f,G as g,M as h,f as i,Q as j,z as k,g as l,Z as m,ee as n,te as o};
@@ -0,0 +1,2 @@
1
+ import d from'tweetnacl';function w(t,r,e){return JSON.stringify(["openrtc:root-client:v1",t,r,e])}async function k(t,r){let e=await t.proof((n,o)=>w(r,n,o));return {...e,publicKeyJwk:{kty:"OKP",crv:"Ed25519",x:e.publicKeyJwk.x}}}function C(t,r,e,n){return JSON.stringify(["openrtc:device-root-binding:v1",t,r,e,n])}function c(t){let r=t instanceof Uint8Array?t:new Uint8Array(t),e="";for(let n of r)e+=String.fromCharCode(n);return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function g(t){let r=JSON.stringify({crv:t.crv,kty:t.kty,x:t.x});return c(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(r)))}function p(){return c(crypto.getRandomValues(new Uint8Array(24)).buffer)}async function y(){return typeof indexedDB>"u"?null:new Promise((t,r)=>{let e=indexedDB.open("openrtc-v2-device-keys",1);e.onupgradeneeded=()=>{e.result.objectStoreNames.contains("keys")||e.result.createObjectStore("keys");},e.onsuccess=()=>t(e.result),e.onerror=()=>r(e.error);})}async function v(t){let r=await y().catch(()=>null);if(!r)throw new Error("[OpenRTC] Persistent browser identity storage is unavailable.");try{return await new Promise((e,n)=>{let o=r.transaction("keys","readonly").objectStore("keys").get(t);o.onsuccess=()=>e(o.result??null),o.onerror=()=>n(o.error);})}finally{r.close();}}async function K(t,r){let e=await y().catch(()=>null);if(!e)throw new Error("[OpenRTC] Persistent browser identity storage is unavailable.");try{return await new Promise((n,o)=>{let i=e.transaction("keys","readwrite"),s=r;i.oncomplete=()=>n(s),i.onabort=()=>o(i.error??new Error("[OpenRTC] Persistent browser identity storage transaction aborted."));let u=i.objectStore("keys"),a=u.get(t);a.onerror=()=>o(a.error),a.onsuccess=()=>{if(a.result!==void 0&&a.result!==null){s=a.result;return}let l=u.put(r,t);l.onerror=()=>o(l.error);};})}finally{e.close();}}async function P(t){let r=await y().catch(()=>null);if(r)try{await new Promise((e,n)=>{let o=r.transaction("keys","readwrite").objectStore("keys").delete(t);o.onsuccess=()=>e(),o.onerror=()=>n(o.error);});}finally{r.close();}}async function b(t){let r=await v(t);if(r)return r;let e=await crypto.subtle.generateKey({name:"Ed25519"},false,["sign","verify"]);return K(t,e)}async function f(t){let r=await crypto.subtle.exportKey("jwk",t.publicKey),e=await g(r);return {publicKeyJwk:r,thumbprint:e,async sign(n){return c(await crypto.subtle.sign({name:"Ed25519"},t.privateKey,n))},async proof(n){let o=p(),i=Math.floor(Date.now()/1e3),s=await crypto.subtle.sign({name:"Ed25519"},t.privateKey,new TextEncoder().encode(n(o,i)));return {publicKeyJwk:r,signature:c(s),nonce:o,issuedAt:i}}}}async function m(){return f(await crypto.subtle.generateKey({name:"Ed25519"},false,["sign","verify"]))}async function D(){try{return await m()}catch(o){if(!(o instanceof Error)||o.name!=="NotSupportedError")throw o}let t=d.sign.keyPair(),r={kty:"OKP",crv:"Ed25519",x:c(t.publicKey)},e=await g(r),n=async o=>c(d.sign.detached(o,t.secretKey));return {publicKeyJwk:r,thumbprint:e,sign:n,async proof(o){let i=p(),s=Math.floor(Date.now()/1e3);return {publicKeyJwk:r,signature:await n(new TextEncoder().encode(o(i,s))),nonce:i,issuedAt:s}}}}var S={persistence:"persistent",async getOrCreate(t){return f(await b(t))},delete:P};function h(){let t=new Map,r=new Map;return {persistence:"session",getOrCreate(e){let n=t.get(e);return n||(n=D(),t.set(e,n)),n},async delete(e){t.delete(e),r.delete(e);},async readSecureRecord(e,n){return r.get(e)?.get(n)??null},async writeSecureRecord(e,n,o){let i=r.get(e);i||(i=new Map,r.set(e,i)),i.set(n,o);},async deleteSecureRecord(e,n){r.get(e)?.delete(n);}}}
2
+ export{w as a,k as b,C as c,g as d,m as e,S as f,h as g};
@@ -0,0 +1 @@
1
+ export{a as ControlPlane}from'./chunk-M2QMGAL2.js';import'./chunk-XNJI6KCI.js';export{a as PRODUCTION_ENDPOINTS,b as decodeClaims}from'./chunk-ZA44REGI.js';import'./chunk-L7N4T2PX.js';import'./chunk-72MN7BNQ.js';
@@ -1,6 +1,6 @@
1
- import { P as PolicySnapshot, a as PeerReconciliationStats, R as RuntimeClient, b as PlutoRuntimeAssembly } from './assembly-DGrOqsLW.js';
2
- import { k as RuntimePeerState, l as PeerConnectOptions, m as Connection, n as PeerSessionSnapshot, o as PeerReadiness, p as RuntimePeerHealth, q as ResolvedPeerIdentity, C as ChannelDescriptor, r as PeerStreamOptions, I as IncomingStream, s as ScopedChannelOptions, t as RuntimeDevice, u as ScopedLogicalChannel, v as ConnectionState, w as ReadinessOptions, x as ConnectionEvent, d as TransferPeerDemandRequest, f as TransferPeerDemandStatus, M as ManagedOptions, y as ManagedSession, D as DeviceStatus, z as DeviceConnectOptions, A as ConnectDeviceResult, B as ConnectDeviceHooks, F as ConnectDeviceOptions, L as LocalDeviceInfo, G as DeviceProfile, H as RawConnection, J as JoinRoomOptions, K as RuntimeRoomMember, N as GrantScope, O as AuthContext, Q as RuntimeClientOptions } from './Connection-BGVBMbWg.js';
3
- import { R as RuntimeCapabilities, C as CapabilityProfile } from './capabilities-DsKud7Sw.js';
1
+ import { P as PolicySnapshot, a as PeerReconciliationStats, R as RuntimeClient, b as PlutoRuntimeAssembly } from './assembly-CtrHmP4j.js';
2
+ import { o as RuntimePeerState, p as PeerConnectOptions, q as Connection, r as PeerSessionSnapshot, s as PeerReadiness, t as RuntimePeerHealth, u as ResolvedPeerIdentity, C as ChannelDescriptor, v as PeerStreamOptions, I as IncomingStream, w as ScopedChannelOptions, x as RuntimeDevice, y as ScopedLogicalChannel, z as ConnectionState, A as ReadinessOptions, B as ConnectionEvent, d as TransferPeerDemandRequest, f as TransferPeerDemandStatus, M as ManagedOptions, F as ManagedSession, G as DeviceStatus, H as DeviceConnectOptions, J as ConnectDeviceResult, K as ConnectDeviceHooks, L as ConnectDeviceOptions, N as LocalDeviceInfo, O as DeviceProfile, Q as RawConnection, U as JoinRoomOptions, V as RuntimeRoomMember, W as GrantScope, X as AuthContext, Y as RuntimeClientOptions } from './Connection-U3fEt8_4.js';
3
+ import { R as RuntimeCapabilities, C as CapabilityProfile } from './capabilities-Dxb0XOti.js';
4
4
 
5
5
  interface DiagnosticPeer {
6
6
  /** Capture-local alias. Full user/device/node/connection IDs are excluded. */
@@ -1,4 +1,4 @@
1
- import './assembly-DGrOqsLW.js';
2
- import './Connection-BGVBMbWg.js';
3
- export { A as AdvancedNamespace, i as ChannelConnectOptions, C as ChannelNamespace, h as Client, a as DeviceNamespace, j as DeviceSessionOptions, D as DiagnosticsNamespace, P as PeerNamespace, R as RoomNamespace, T as TicketNamespace, r as resolveOptions, w as wrapAssembly } from './coreClient-ByXs38IP.js';
4
- import './capabilities-DsKud7Sw.js';
1
+ import './assembly-CtrHmP4j.js';
2
+ import './Connection-U3fEt8_4.js';
3
+ export { A as AdvancedNamespace, i as ChannelConnectOptions, C as ChannelNamespace, h as Client, a as DeviceNamespace, j as DeviceSessionOptions, D as DiagnosticsNamespace, P as PeerNamespace, R as RoomNamespace, T as TicketNamespace, r as resolveOptions, w as wrapAssembly } from './coreClient-AVGEwlhT.js';
4
+ import './capabilities-Dxb0XOti.js';
@@ -1 +1 @@
1
- import {l}from'./chunk-L4HWDDXL.js';import'./chunk-OWKAJPOI.js';import {c}from'./chunk-RLPWFHOY.js';import'./chunk-2GX6GB6L.js';function w(o){let r=l({...o});if("auth"in o&&!o.authMode){let n=o.auth;r.authMode=n==="none"?"anonymous":n;}if("identity"in o){let n=o.identity,s=n==="temporary"?"ephemeral":n;!o.deviceIdPersistence&&!o.nodeIdPersistence&&(r.deviceIdPersistence=s),!o.endpointIdPersistence&&!o.nodeIdPersistence&&(r.endpointIdPersistence=s);}return "namespace"in o&&!o.storagePrefix&&(r.storagePrefix=o.namespace),"privacy"in o&&o.strictMode===void 0&&(r.strictMode=!!o.privacy),r}function O(o,r){let n=o.runtime,s=Object.create(n),d=async e=>{if(typeof e!="string")return e;let i=(await n.listDevices()).find(a=>a.deviceId===e);if(!i)throw new Error(`OpenRTC device '${e}' is not currently discoverable.`);return i},g=async e=>({...e,localDeviceId:e?.localDeviceId??await n.getLocalDeviceId()??""}),P=async e=>{let{device:t,scope:i,...a}=e,c=a.deviceId??(typeof t=="string"?t:t?.deviceId)??null,l=a.ticket??(typeof t=="string"?void 0:t?.ticket);c&&!l&&(l=(await d(c).catch(()=>null))?.ticket);let m={...a,scope:i??"session"};return c&&(m.deviceId=c),l&&(m.ticket=l),m},v={requestTransferPeer:e=>n.requestTransferPeer(e),transferPeerDemandStatus:(e,t)=>n.transferPeerDemandStatus(e,t),releaseTransferPeer:(e,t)=>n.releaseTransferPeer(e,t),setTransferPeerBudget:(e,t)=>n.setTransferPeerBudget(e,t),list:()=>n.listDevices(),startSession:(e={})=>n.startManagedSession({...e,platform:e.platform??r}),stopSession:e=>n.stopManagedSession(e),listWithStatus:()=>n.listDeviceStatus(),watch:e=>n.watchDevices(e),watchWithStatus:e=>n.watchDeviceStatus(e),connect:async(e,t)=>n.connectDevice(await d(e),await g(t)),connectWithRetry:async(e,t,i)=>n.connectWithRetry(await d(e),t,i),disconnect:e=>n.disconnectDevice(e),update:(e,t)=>n.updateDevice(e,t),delete:e=>n.deleteDevice(e),localId:()=>n.getLocalDeviceId(),localInfo:()=>n.getLocalDeviceInfo(),localProfile:e=>n.localDeviceProfile(e),updateLocalName:e=>n.updateDeviceName(e)},C={watch:e=>n.watchPeerStates(e),watchLifecycle:e=>typeof n.watchPeerLifecycle=="function"?n.watchPeerLifecycle(e):typeof n.watchPeerStates=="function"?n.watchPeerStates(e):()=>{},get:e=>n.getPeerState(e),listConnected:()=>n.listConnectedPeers(),connect:e=>n.connectPeer(e),disconnect:(e,t)=>n.disconnectPeer(e,t),forceDisconnect:e=>n.forceDisconnectPeer(e),session:e=>n.getPeerSession(e),sessions:()=>n.listPeerSessions(),waitConnected:(e,t)=>n.waitForConnectedPeer(e,t),readiness:(e,t)=>n.getPeerReadiness(e,t),health:e=>n.getPeerHealth(e),identity:e=>n.resolvePeerIdentity(e),addScope:(e,t)=>n.addPeerScope(e,t),releaseScope:(e,t)=>n.releasePeerScope(e,t),scopes:e=>n.getPeerScopes(e),refresh:()=>n.refreshPeerSnapshot()},h={register:e=>n.registerChannel(e),unregister:e=>n.unregisterChannel(e),list:()=>n.listChannels(),openBi:(e,t,i)=>n.openPeerBi(e,{...i,channelId:t}),openUni:(e,t,i)=>n.openPeerUni(e,{...i,channelId:t}),onIncoming:e=>n.onIncomingStream(e),onIncomingChannel:(e,t)=>n.onChannelStream(e,i=>{if(i.channel)return t(i)}),connect:async e=>n.connectScopedChannel(await P(e)),connectScoped:e=>n.connectScopedChannel(e)},S={create:e=>n.createRoom(e),join:(e,t)=>n.joinRoom(e,t),leave:e=>n.leaveRoom(e),watch:(e,t)=>n.watchRoom(e,t),members:e=>n.getRoomMembers(e)},f={raw:()=>n.getInvite(),share:e=>n.getTicketWithToken("share",e?.maxConnections??1),grant:(e,t)=>n.getTicketWithToken(e,t?.maxConnections??0),revoke:e=>n.revokeTokensByScope(e)},b={capture:e=>c(t=>n.watchPeerStates(t),e),status:()=>n.getRuntimeStatus(),policy:()=>n.getRuntimePolicy(),capabilities:()=>n.capabilities(),capabilityProfile:()=>n.getCapabilityProfile(),watchConnectionMetrics:e=>n.watchConnectionMetrics(e),connectionStates:()=>n.getConnectionStates(),onStateChange:e=>n.onStateChange(e),connections:()=>n.getConnections(),applicationReadyConnections:e=>n.readyConnections(e),onConnection:e=>n.onConnection(e),onDisconnection:e=>n.onDisconnection(e),onConnectionEvent:e=>n.onConnectionEvent(e),forceReconnect:()=>n.forceReconnect(),peerReconciliation:()=>n.reconciliationStats()},y={runtime:n,assembly:o,nodeId:()=>n.getNodeId(),nodeIdFromTicket:e=>n.getNodeIdFromTicket(e),endpointTicket:()=>n.getEndpointTicket(),connectRaw:e=>n.connectRaw(e),openBi:e=>n.openBi(e),openUni:e=>n.openUni(e),isConnected:e=>n.isConnected(e),disconnectNode:e=>n.disconnectNode(e),excludeAutoConnect:(e,t)=>n.excludeAutoConnect(e,t),notifyNetworkChange:e=>n.notifyNetworkChange(e)};return Object.defineProperties(s,{devices:{get:()=>v,enumerable:true},peers:{get:()=>C,enumerable:true},channels:{get:()=>h,enumerable:true},rooms:{get:()=>S,enumerable:true},tickets:{get:()=>f,enumerable:true},diagnostics:{get:()=>b,enumerable:true},advanced:{get:()=>y,enumerable:true},setAuth:{value:e=>o.setAuthContext(e),enumerable:true,writable:true,configurable:true},setAuthContext:{value:e=>o.setAuthContext(e),enumerable:true,writable:true,configurable:true},syncPlutoAuth:{value:e=>o.syncPlutoAuth(e),enumerable:true,writable:true,configurable:true},bindPlutoAuthHost:{value:()=>o.bindPlutoAuthHost(),enumerable:true,writable:true,configurable:true},signIn:{value:()=>o.signInWithPluto(),enumerable:true,writable:true,configurable:true},signOut:{value:()=>o.signOut(),enumerable:true,writable:true,configurable:true},runtime:{get:()=>n,enumerable:false},_assembly:{get:()=>o,enumerable:false}}),s}export{w as resolveOptions,O as wrapAssembly};
1
+ import {l}from'./chunk-WTOA6B2A.js';import'./chunk-OWKAJPOI.js';import {c}from'./chunk-SSBR3IHA.js';import'./chunk-2GX6GB6L.js';function w(o){let r=l({...o});if("auth"in o&&!o.authMode){let n=o.auth;r.authMode=n==="none"?"anonymous":n;}if("identity"in o){let n=o.identity,s=n==="temporary"?"ephemeral":n;!o.deviceIdPersistence&&!o.nodeIdPersistence&&(r.deviceIdPersistence=s),!o.endpointIdPersistence&&!o.nodeIdPersistence&&(r.endpointIdPersistence=s);}return "namespace"in o&&!o.storagePrefix&&(r.storagePrefix=o.namespace),"privacy"in o&&o.strictMode===void 0&&(r.strictMode=!!o.privacy),r}function O(o,r){let n=o.runtime,s=Object.create(n),d=async e=>{if(typeof e!="string")return e;let i=(await n.listDevices()).find(a=>a.deviceId===e);if(!i)throw new Error(`OpenRTC device '${e}' is not currently discoverable.`);return i},g=async e=>({...e,localDeviceId:e?.localDeviceId??await n.getLocalDeviceId()??""}),P=async e=>{let{device:t,scope:i,...a}=e,c=a.deviceId??(typeof t=="string"?t:t?.deviceId)??null,l=a.ticket??(typeof t=="string"?void 0:t?.ticket);c&&!l&&(l=(await d(c).catch(()=>null))?.ticket);let m={...a,scope:i??"session"};return c&&(m.deviceId=c),l&&(m.ticket=l),m},v={requestTransferPeer:e=>n.requestTransferPeer(e),transferPeerDemandStatus:(e,t)=>n.transferPeerDemandStatus(e,t),releaseTransferPeer:(e,t)=>n.releaseTransferPeer(e,t),setTransferPeerBudget:(e,t)=>n.setTransferPeerBudget(e,t),list:()=>n.listDevices(),startSession:(e={})=>n.startManagedSession({...e,platform:e.platform??r}),stopSession:e=>n.stopManagedSession(e),listWithStatus:()=>n.listDeviceStatus(),watch:e=>n.watchDevices(e),watchWithStatus:e=>n.watchDeviceStatus(e),connect:async(e,t)=>n.connectDevice(await d(e),await g(t)),connectWithRetry:async(e,t,i)=>n.connectWithRetry(await d(e),t,i),disconnect:e=>n.disconnectDevice(e),update:(e,t)=>n.updateDevice(e,t),delete:e=>n.deleteDevice(e),localId:()=>n.getLocalDeviceId(),localInfo:()=>n.getLocalDeviceInfo(),localProfile:e=>n.localDeviceProfile(e),updateLocalName:e=>n.updateDeviceName(e)},C={watch:e=>n.watchPeerStates(e),watchLifecycle:e=>typeof n.watchPeerLifecycle=="function"?n.watchPeerLifecycle(e):typeof n.watchPeerStates=="function"?n.watchPeerStates(e):()=>{},get:e=>n.getPeerState(e),listConnected:()=>n.listConnectedPeers(),connect:e=>n.connectPeer(e),disconnect:(e,t)=>n.disconnectPeer(e,t),forceDisconnect:e=>n.forceDisconnectPeer(e),session:e=>n.getPeerSession(e),sessions:()=>n.listPeerSessions(),waitConnected:(e,t)=>n.waitForConnectedPeer(e,t),readiness:(e,t)=>n.getPeerReadiness(e,t),health:e=>n.getPeerHealth(e),identity:e=>n.resolvePeerIdentity(e),addScope:(e,t)=>n.addPeerScope(e,t),releaseScope:(e,t)=>n.releasePeerScope(e,t),scopes:e=>n.getPeerScopes(e),refresh:()=>n.refreshPeerSnapshot()},h={register:e=>n.registerChannel(e),unregister:e=>n.unregisterChannel(e),list:()=>n.listChannels(),openBi:(e,t,i)=>n.openPeerBi(e,{...i,channelId:t}),openUni:(e,t,i)=>n.openPeerUni(e,{...i,channelId:t}),onIncoming:e=>n.onIncomingStream(e),onIncomingChannel:(e,t)=>n.onChannelStream(e,i=>{if(i.channel)return t(i)}),connect:async e=>n.connectScopedChannel(await P(e)),connectScoped:e=>n.connectScopedChannel(e)},S={create:e=>n.createRoom(e),join:(e,t)=>n.joinRoom(e,t),leave:e=>n.leaveRoom(e),watch:(e,t)=>n.watchRoom(e,t),members:e=>n.getRoomMembers(e)},f={raw:()=>n.getInvite(),share:e=>n.getTicketWithToken("share",e?.maxConnections??1),grant:(e,t)=>n.getTicketWithToken(e,t?.maxConnections??0),revoke:e=>n.revokeTokensByScope(e)},b={capture:e=>c(t=>n.watchPeerStates(t),e),status:()=>n.getRuntimeStatus(),policy:()=>n.getRuntimePolicy(),capabilities:()=>n.capabilities(),capabilityProfile:()=>n.getCapabilityProfile(),watchConnectionMetrics:e=>n.watchConnectionMetrics(e),connectionStates:()=>n.getConnectionStates(),onStateChange:e=>n.onStateChange(e),connections:()=>n.getConnections(),applicationReadyConnections:e=>n.readyConnections(e),onConnection:e=>n.onConnection(e),onDisconnection:e=>n.onDisconnection(e),onConnectionEvent:e=>n.onConnectionEvent(e),forceReconnect:()=>n.forceReconnect(),peerReconciliation:()=>n.reconciliationStats()},y={runtime:n,assembly:o,nodeId:()=>n.getNodeId(),nodeIdFromTicket:e=>n.getNodeIdFromTicket(e),endpointTicket:()=>n.getEndpointTicket(),connectRaw:e=>n.connectRaw(e),openBi:e=>n.openBi(e),openUni:e=>n.openUni(e),isConnected:e=>n.isConnected(e),disconnectNode:e=>n.disconnectNode(e),excludeAutoConnect:(e,t)=>n.excludeAutoConnect(e,t),notifyNetworkChange:e=>n.notifyNetworkChange(e)};return Object.defineProperties(s,{devices:{get:()=>v,enumerable:true},peers:{get:()=>C,enumerable:true},channels:{get:()=>h,enumerable:true},rooms:{get:()=>S,enumerable:true},tickets:{get:()=>f,enumerable:true},diagnostics:{get:()=>b,enumerable:true},advanced:{get:()=>y,enumerable:true},setAuth:{value:e=>o.setAuthContext(e),enumerable:true,writable:true,configurable:true},setAuthContext:{value:e=>o.setAuthContext(e),enumerable:true,writable:true,configurable:true},syncPlutoAuth:{value:e=>o.syncPlutoAuth(e),enumerable:true,writable:true,configurable:true},bindPlutoAuthHost:{value:()=>o.bindPlutoAuthHost(),enumerable:true,writable:true,configurable:true},signIn:{value:()=>o.signInWithPluto(),enumerable:true,writable:true,configurable:true},signOut:{value:()=>o.signOut(),enumerable:true,writable:true,configurable:true},runtime:{get:()=>n,enumerable:false},_assembly:{get:()=>o,enumerable:false}}),s}export{w as resolveOptions,O as wrapAssembly};
@@ -1 +1 @@
1
- import {h as h$1}from'./chunk-5LNRJE6L.js';import'./chunk-FKAQDDUM.js';import'./chunk-RLPWFHOY.js';import'./chunk-IUU6JCLK.js';import'./chunk-CCCYE3XN.js';import'./chunk-JPBW67B3.js';import'./chunk-ZA44REGI.js';import'./chunk-L7N4T2PX.js';import'./chunk-72MN7BNQ.js';import'./chunk-2GX6GB6L.js';var h=class extends h$1{constructor(e,t,u,S){super("devices",e,t,u);this.roster=S;this.kind="devices";this.rosterStopped=false;this.localId=()=>this.client.devices.localId();this.localInfo=()=>this.client.devices.localInfo();this.list=async()=>this.roster.mergeDevices(await this.client.devices.list());this.listWithStatus=async()=>this.roster.mergeStatus(await this.client.devices.listWithStatus());this.watch=e=>this.client.devices.watch(t=>e(this.roster.mergeDevices(t)));this.requestTransferPeer=async e=>{if(this.closed)throw new Error("[OpenRTC] Capability is closed.");return this.client.devices.requestTransferPeer(e)};this.transferPeerDemandStatus=async(e,t)=>{if(this.closed)throw new Error("[OpenRTC] Capability is closed.");return this.client.devices.transferPeerDemandStatus(e,t)};this.releaseTransferPeer=async(e,t)=>{if(this.closed)throw new Error("[OpenRTC] Capability is closed.");return this.client.devices.releaseTransferPeer(e,t)};this.setTransferPeerBudget=async(e,t)=>{if(this.closed)throw new Error("[OpenRTC] Capability is closed.");return this.client.devices.setTransferPeerBudget(e,t)};this.connect=this.client.devices.connect;this.disconnect=this.client.devices.disconnect;let p=t.devices.list,m=t.devices.listWithStatus,c=t.devices.watch,f=t.devices.watchWithStatus,i=s=>(this.roster.reconcileLiveSnapshot(s),s),a=async()=>this.roster.mergeDevices(i(await p())),o=async()=>this.roster.mergeStatus(await m()),n=s=>c(r=>s(this.roster.mergeDevices(i(r)))),l=s=>f(r=>s(this.roster.mergeStatus(r))),d=Object.create(t);Object.defineProperties(d,{listDevices:{value:a,enumerable:false},listDeviceStatus:{value:o,enumerable:false},watchDevices:{value:n,enumerable:false},watchDeviceStatus:{value:l,enumerable:false},devices:{value:{...t.devices,list:a,listWithStatus:o,watch:n,watchWithStatus:l},enumerable:true}}),this.projectRuntime(d),this.stopRosterSync=c(i);}replaceEnrolledDevices(e){this.roster.replace(e);}removeEnrolledDevice(e){this.roster.remove(e);}retainCurrentEnrolledDevice(e){this.roster.retain(e);}beforeRuntimeShutdown(){this.rosterStopped||(this.stopRosterSync(),this.rosterStopped=true);}};export{h as DeviceHandle};
1
+ import {h as h$1}from'./chunk-RUOVYQ2P.js';import'./chunk-FKAQDDUM.js';import'./chunk-SSBR3IHA.js';import'./chunk-IUU6JCLK.js';import'./chunk-CCCYE3XN.js';import'./chunk-JPBW67B3.js';import'./chunk-ZA44REGI.js';import'./chunk-L7N4T2PX.js';import'./chunk-72MN7BNQ.js';import'./chunk-2GX6GB6L.js';var h=class extends h$1{constructor(e,t,u,S){super("devices",e,t,u);this.roster=S;this.kind="devices";this.rosterStopped=false;this.localId=()=>this.client.devices.localId();this.localInfo=()=>this.client.devices.localInfo();this.list=async()=>this.roster.mergeDevices(await this.client.devices.list());this.listWithStatus=async()=>this.roster.mergeStatus(await this.client.devices.listWithStatus());this.watch=e=>this.client.devices.watch(t=>e(this.roster.mergeDevices(t)));this.requestTransferPeer=async e=>{if(this.closed)throw new Error("[OpenRTC] Capability is closed.");return this.client.devices.requestTransferPeer(e)};this.transferPeerDemandStatus=async(e,t)=>{if(this.closed)throw new Error("[OpenRTC] Capability is closed.");return this.client.devices.transferPeerDemandStatus(e,t)};this.releaseTransferPeer=async(e,t)=>{if(this.closed)throw new Error("[OpenRTC] Capability is closed.");return this.client.devices.releaseTransferPeer(e,t)};this.setTransferPeerBudget=async(e,t)=>{if(this.closed)throw new Error("[OpenRTC] Capability is closed.");return this.client.devices.setTransferPeerBudget(e,t)};this.connect=this.client.devices.connect;this.disconnect=this.client.devices.disconnect;let p=t.devices.list,m=t.devices.listWithStatus,c=t.devices.watch,f=t.devices.watchWithStatus,i=s=>(this.roster.reconcileLiveSnapshot(s),s),a=async()=>this.roster.mergeDevices(i(await p())),o=async()=>this.roster.mergeStatus(await m()),n=s=>c(r=>s(this.roster.mergeDevices(i(r)))),l=s=>f(r=>s(this.roster.mergeStatus(r))),d=Object.create(t);Object.defineProperties(d,{listDevices:{value:a,enumerable:false},listDeviceStatus:{value:o,enumerable:false},watchDevices:{value:n,enumerable:false},watchDeviceStatus:{value:l,enumerable:false},devices:{value:{...t.devices,list:a,listWithStatus:o,watch:n,watchWithStatus:l},enumerable:true}}),this.projectRuntime(d),this.stopRosterSync=c(i);}replaceEnrolledDevices(e){this.roster.replace(e);}removeEnrolledDevice(e){this.roster.remove(e);}retainCurrentEnrolledDevice(e){this.roster.retain(e);}beforeRuntimeShutdown(){this.rosterStopped||(this.stopRosterSync(),this.rosterStopped=true);}};export{h as DeviceHandle};
@@ -0,0 +1 @@
1
+ export{f as browserDeviceKeyProvider,e as createDeviceKey,g as createSessionDeviceKeyProvider,d as deviceKeyThumbprint,c as rootBoundDeviceChallenge,a as rootClientChallenge,b as rootClientProof}from'./chunk-XNJI6KCI.js';
@@ -1,8 +1,8 @@
1
- import { C as Client, e as BroadcastGrant, O as Options } from './types-Cruu-MsF.js';
2
- import './coreClient-ByXs38IP.js';
3
- import './assembly-DGrOqsLW.js';
4
- import './Connection-BGVBMbWg.js';
5
- import './capabilities-DsKud7Sw.js';
1
+ import { C as Client, e as BroadcastGrant, O as Options } from './types-DvZvz4EL.js';
2
+ import './coreClient-AVGEwlhT.js';
3
+ import './assembly-CtrHmP4j.js';
4
+ import './Connection-U3fEt8_4.js';
5
+ import './capabilities-Dxb0XOti.js';
6
6
 
7
7
  type ExternalBroadcastRelay = {
8
8
  kind: 'sfu';
@@ -1,2 +1,2 @@
1
- import {a as a$1}from'./chunk-5VJXDYP6.js';import'./chunk-IXQ4KWGP.js';import'./chunk-AYHD4X2R.js';import {a}from'./chunk-IAYQJZQQ.js';import'./chunk-GMPEZXPD.js';import {i}from'./chunk-5LNRJE6L.js';import'./chunk-FKAQDDUM.js';import'./chunk-RLPWFHOY.js';import'./chunk-IUU6JCLK.js';import'./chunk-CCCYE3XN.js';import'./chunk-JPBW67B3.js';import'./chunk-ZA44REGI.js';import'./chunk-L7N4T2PX.js';import'./chunk-72MN7BNQ.js';import'./chunk-2GX6GB6L.js';async function K(r,e){if(!/^pk_(?:live|test)_[0-9a-f]{40}$/.test(r)||!/^[A-Za-z0-9_-]{1,64}$/.test(e))throw new Error("[OpenRTC] External broadcast identity is invalid.");return (await a(e).getOrCreate(`app_${r.slice(-16)}`)).publicKeyJwk}function h(r){let e=new URL(r),t=["localhost","127.0.0.1","[::1]"].includes(e.hostname);if(e.protocol!=="https:"&&!(t&&e.protocol==="http:")||e.pathname!=="/"||e.username||e.password||e.search||e.hash||r!==e.origin&&r!==`${e.origin}/`)throw new Error("[OpenRTC] External broadcast service must be an exact HTTPS origin.");return e.origin}function k(r){let e=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(Math.ceil(r.length/4)*4,"=");return Uint8Array.from(atob(e),t=>t.charCodeAt(0))}function x(r){let e="";for(let t of r)e+=String.fromCharCode(t);return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function C(r,e){if(!(r.issuerPublicKey instanceof Uint8Array)||r.issuerPublicKey.length!==32)throw new Error("[OpenRTC] External broadcast issuer key must be 32 bytes.");let t=r.relay;if(t.kind==="sfu"){let a=new URL(t.controlUrl,e);if(a.origin!==e||a.protocol!==new URL(e).protocol||a.pathname==="/"||a.username||a.password||a.search||a.hash)throw new Error("[OpenRTC] External SFU control must stay on the trusted service origin.");return {issuerPublicKey:r.issuerPublicKey,relay:{kind:"sfu",controlUrl:a.href.replace(/\/$/,"")}}}else {let a=new URL(t.relayUrl);if(a.protocol!=="https:"||a.username||a.password||!t.token||!t.namespace)throw new Error("[OpenRTC] External MoQ relay access is invalid.");if(t.serverCertificateHash&&!["localhost","127.0.0.1","[::1]"].includes(a.hostname))throw new Error("[OpenRTC] Custom relay certificate hashes are limited to loopback.")}return r}function P(r,e){if(!r||typeof r.apiKey!="string"||!/^pk_(?:live|test)_[0-9a-f]{40}$/.test(r.apiKey))throw new Error("[OpenRTC] External broadcast identity is invalid.");let t=h(e.serviceOrigin);if(!/^[A-Za-z0-9_-]{1,64}$/.test(e.keyNamespace)||typeof e.resolve!="function")throw new Error("[OpenRTC] External broadcast configuration is invalid.");let a$2=a(e.keyNamespace),d=`app_${r.apiKey.slice(-16)}`,l=()=>a$2.getOrCreate(d),u=async()=>{let{loadBrowserWasmRuntimeModule:i}=await import('./WasmBridge-CJNESUGJ.js'),n=await i();return await n.initWasm(),n.start(),new n.WasmClient(r.apiKey)},w,f=()=>w??(w=u()),m=new a$1({loadWasm:f,resolve:async(i,n)=>{let o=await l(),s=C(await e.resolve(i,o.publicKeyJwk,n),t),g=s.relay.kind==="sfu"?{kind:"sfu",controlUrl:s.relay.controlUrl,grant:i,bindingPublicJwk:o.publicKeyJwk,...n?{publicationVerifyingKey:x(n)}:{}}:s.relay;return {token:i,issuerPublicKey:s.issuerPublicKey,relay:g,signBindingChallenge:async b=>k(await o.sign(b))}}});return {client:i(r,{platform:"web",endpoints:{controlPlane:t,gateway:t},testingAllowInsecureLoopback:t.startsWith("http:"),deviceKeyProvider:a$2,broadcastHost:m,runtimeFactory:async i=>{let{createWasmClient:n}=await import('./runtime/factories.js');return n(i)}}),bindingPublicJwk:async()=>(await l()).publicKeyJwk}}
1
+ import {a as a$1}from'./chunk-5VJXDYP6.js';import'./chunk-IXQ4KWGP.js';import'./chunk-AYHD4X2R.js';import {a}from'./chunk-KI7XXVXH.js';import'./chunk-XNJI6KCI.js';import {i}from'./chunk-RUOVYQ2P.js';import'./chunk-FKAQDDUM.js';import'./chunk-SSBR3IHA.js';import'./chunk-IUU6JCLK.js';import'./chunk-CCCYE3XN.js';import'./chunk-JPBW67B3.js';import'./chunk-ZA44REGI.js';import'./chunk-L7N4T2PX.js';import'./chunk-72MN7BNQ.js';import'./chunk-2GX6GB6L.js';async function K(r,e){if(!/^pk_(?:live|test)_[0-9a-f]{40}$/.test(r)||!/^[A-Za-z0-9_-]{1,64}$/.test(e))throw new Error("[OpenRTC] External broadcast identity is invalid.");return (await a(e).getOrCreate(`app_${r.slice(-16)}`)).publicKeyJwk}function h(r){let e=new URL(r),t=["localhost","127.0.0.1","[::1]"].includes(e.hostname);if(e.protocol!=="https:"&&!(t&&e.protocol==="http:")||e.pathname!=="/"||e.username||e.password||e.search||e.hash||r!==e.origin&&r!==`${e.origin}/`)throw new Error("[OpenRTC] External broadcast service must be an exact HTTPS origin.");return e.origin}function k(r){let e=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(Math.ceil(r.length/4)*4,"=");return Uint8Array.from(atob(e),t=>t.charCodeAt(0))}function x(r){let e="";for(let t of r)e+=String.fromCharCode(t);return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function C(r,e){if(!(r.issuerPublicKey instanceof Uint8Array)||r.issuerPublicKey.length!==32)throw new Error("[OpenRTC] External broadcast issuer key must be 32 bytes.");let t=r.relay;if(t.kind==="sfu"){let a=new URL(t.controlUrl,e);if(a.origin!==e||a.protocol!==new URL(e).protocol||a.pathname==="/"||a.username||a.password||a.search||a.hash)throw new Error("[OpenRTC] External SFU control must stay on the trusted service origin.");return {issuerPublicKey:r.issuerPublicKey,relay:{kind:"sfu",controlUrl:a.href.replace(/\/$/,"")}}}else {let a=new URL(t.relayUrl);if(a.protocol!=="https:"||a.username||a.password||!t.token||!t.namespace)throw new Error("[OpenRTC] External MoQ relay access is invalid.");if(t.serverCertificateHash&&!["localhost","127.0.0.1","[::1]"].includes(a.hostname))throw new Error("[OpenRTC] Custom relay certificate hashes are limited to loopback.")}return r}function P(r,e){if(!r||typeof r.apiKey!="string"||!/^pk_(?:live|test)_[0-9a-f]{40}$/.test(r.apiKey))throw new Error("[OpenRTC] External broadcast identity is invalid.");let t=h(e.serviceOrigin);if(!/^[A-Za-z0-9_-]{1,64}$/.test(e.keyNamespace)||typeof e.resolve!="function")throw new Error("[OpenRTC] External broadcast configuration is invalid.");let a$2=a(e.keyNamespace),d=`app_${r.apiKey.slice(-16)}`,l=()=>a$2.getOrCreate(d),u=async()=>{let{loadBrowserWasmRuntimeModule:i}=await import('./WasmBridge-3HYLCY5Y.js'),n=await i();return await n.initWasm(),n.start(),new n.WasmClient(r.apiKey)},w,f=()=>w??(w=u()),m=new a$1({loadWasm:f,resolve:async(i,n)=>{let o=await l(),s=C(await e.resolve(i,o.publicKeyJwk,n),t),g=s.relay.kind==="sfu"?{kind:"sfu",controlUrl:s.relay.controlUrl,grant:i,bindingPublicJwk:o.publicKeyJwk,...n?{publicationVerifyingKey:x(n)}:{}}:s.relay;return {token:i,issuerPublicKey:s.issuerPublicKey,relay:g,signBindingChallenge:async b=>k(await o.sign(b))}}});return {client:i(r,{platform:"web",endpoints:{controlPlane:t,gateway:t},testingAllowInsecureLoopback:t.startsWith("http:"),deviceKeyProvider:a$2,broadcastHost:m,runtimeFactory:async i=>{let{createWasmClient:n}=await import('./runtime/factories.js');return n(i)}}),bindingPublicJwk:async()=>(await l()).publicKeyJwk}}
2
2
  export{P as createExternalBroadcastClient,K as externalBroadcastBindingPublicJwk};
package/dist/index.d.ts CHANGED
@@ -1,11 +1,11 @@
1
1
  import { P as PlutoIpcBridge } from './ipc-DgzKqHH3.js';
2
- import { O as Options, z as LiveOnlyOptions, C as Client } from './types-Cruu-MsF.js';
3
- export { a as AttestationProvider, b as AuthProvider, c as Avenue, e as BroadcastGrant, i as BroadcastPublisher, j as BroadcastRole, k as BroadcastSession, l as BroadcastSource, m as BroadcastState, n as BroadcastStats, o as BroadcastTrackEvent, p as Channel, r as Connection, s as DeviceOptions, t as DeviceProfile, u as Devices, E as EnrolledDevice, T as Offline, U as OfflineAssurance, V as OfflineEnrollmentRequest, W as OfflineRuntimeSupport, a0 as Room, a1 as RoomMember, a2 as RoomMembers, a3 as RoomOptions, a4 as Space, a5 as SpaceOptions, a6 as State, a7 as Ticket, a8 as TicketOptions, a9 as Transports } from './types-Cruu-MsF.js';
4
- import { am as ServiceErrorMetadata } from './Connection-BGVBMbWg.js';
5
- export { S as ServiceErrorObservation, T as TransferPeerDemandPurpose, d as TransferPeerDemandRequest, e as TransferPeerDemandState, f as TransferPeerDemandStatus } from './Connection-BGVBMbWg.js';
6
- export { c as DiagnosticBundle, d as DiagnosticCapture, e as DiagnosticCaptureOptions, f as DiagnosticEvent, b as DiagnosticOperationEvent, g as DiagnosticPeer } from './coreClient-ByXs38IP.js';
7
- import './assembly-DGrOqsLW.js';
8
- import './capabilities-DsKud7Sw.js';
2
+ import { O as Options, z as LiveOnlyOptions, C as Client } from './types-DvZvz4EL.js';
3
+ export { a as AttestationProvider, b as AuthProvider, c as Avenue, e as BroadcastGrant, i as BroadcastPublisher, j as BroadcastRole, k as BroadcastSession, l as BroadcastSource, m as BroadcastState, n as BroadcastStats, o as BroadcastTrackEvent, p as Channel, r as Connection, s as DeviceOptions, t as DeviceProfile, u as Devices, E as EnrolledDevice, T as Offline, U as OfflineAssurance, V as OfflineEnrollmentRequest, W as OfflineRuntimeSupport, a0 as Room, a1 as RoomMember, a2 as RoomMembers, a3 as RoomOptions, a4 as Space, a5 as SpaceOptions, a6 as State, a7 as Ticket, a8 as TicketOptions, a9 as Transports } from './types-DvZvz4EL.js';
4
+ import { ar as ServiceErrorMetadata } from './Connection-U3fEt8_4.js';
5
+ export { S as ServiceErrorObservation, T as TransferPeerDemandPurpose, d as TransferPeerDemandRequest, e as TransferPeerDemandState, f as TransferPeerDemandStatus } from './Connection-U3fEt8_4.js';
6
+ export { c as DiagnosticBundle, d as DiagnosticCapture, e as DiagnosticCaptureOptions, f as DiagnosticEvent, b as DiagnosticOperationEvent, g as DiagnosticPeer } from './coreClient-AVGEwlhT.js';
7
+ import './assembly-CtrHmP4j.js';
8
+ import './capabilities-Dxb0XOti.js';
9
9
 
10
10
  /**
11
11
  * Create a lazy OpenRTC 2.0 browser client. Construction validates only local
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- import {a as a$1}from'./chunk-NS32P65Z.js';import {d as d$1}from'./chunk-72NEEJQG.js';import'./chunk-GMPEZXPD.js';import {i}from'./chunk-5LNRJE6L.js';import'./chunk-FKAQDDUM.js';import'./chunk-RLPWFHOY.js';export{b as parseTicketInvite}from'./chunk-IUU6JCLK.js';import'./chunk-CCCYE3XN.js';import'./chunk-JPBW67B3.js';import'./chunk-ZA44REGI.js';export{a as ERROR_CODES,b as RTCError,e as classifyError,d as createError,c as projectError}from'./chunk-L7N4T2PX.js';import'./chunk-72MN7BNQ.js';import'./chunk-2GX6GB6L.js';function d(n){return i(n,{platform:"web",liveHostFactory:async(e,i)=>{let{BrowserCoordinationGatewaySignaling:r}=await import('./BrowserCoordinationGatewaySignaling-GOLSTJMA.js');return r.live(e,i)},broadcastHostFactory:async e=>{let[{BrowserManagedBroadcastHost:i},{loadBrowserWasmRuntimeModule:r}]=await Promise.all([import('./BrowserManagedBroadcastHost-6VGHQQMF.js'),import('./WasmBridge-CJNESUGJ.js')]),t=r().then(async o=>(await o.initWasm(),o.start(),new o.WasmClient(e.apiKey)));return new i({resolve:e.resolve,manage:e.manage,deviceId:e.deviceId,defaultAuth:e.defaultAuth,loadWasm:()=>t})},runtimeFactory:async e=>{let{createWasmClient:i}=await import('./runtime/factories.js');return i(e)}})}d.native=function(n,e=d$1()){let i$1,r=()=>i$1??(i$1=import('./NativeProjectionBroker-Z6LCR4WB.js').then(({NativeProjectionBroker:t})=>new t));return i(n,{platform:"native",liveHostFactory:t=>new a(e,t),broadcastHostFactory:async t=>{let{NativeManagedBroadcastHost:o}=await import('./NativeManagedBroadcastHost-6A2QP3A7.js');return new o(e,t)},offlineSupport:()=>e.invoke("openrtc_offline_runtime_support"),createOfflineEnrollmentRequest:async t=>{let o=await e.invoke("start_iroh_node");return e.invoke("openrtc_create_offline_enrollment_request",{trustDomain:t.trustDomain,deviceId:t.deviceId,endpointId:o,enrollmentNonce:crypto.randomUUID(),requestedRoles:t.requestedRoles})},close:async()=>{i$1&&await(await i$1).close();},deviceKeyProvider:a$1(e),deviceIdProvider:async()=>{let t=await e.invoke("get_rtc_local_device_info");return String(t?.deviceId??"")},runtimeFactory:async t=>{let[{createIpcClient:o},l]=await Promise.all([import('./ipcFactory-F75IXEIE.js'),r()]);return o(t,e,l)}})};var a=class{constructor(e,i){this.bridge=e;this.endpoint=i;this.retired=false;this.opened=false;this.certificate="";this.abort=new AbortController;this.listeners=new Set;}get closed(){return this.retired}onEvent(e){return this.listeners.add(e),()=>{this.listeners.delete(e);}}emit(e){for(let i of this.listeners)try{i(e);}catch{}}async credentials(e){if(this.retired)throw new Error("[OpenRTC] Live session is closed.");let i,r=new Promise((t,o)=>{i=()=>o(new Error("[OpenRTC] Live credentials were closed.")),this.abort.signal.aborted?i():this.abort.signal.addEventListener("abort",i,{once:true});});try{let t=await Promise.race([this.options.credentials({forceRefresh:e,signal:this.abort.signal}),r]);if(this.retired||!t||typeof t.certificate!="string"||t.certificate.length>8192||typeof t.session!="string"||t.session.length>24e3)throw new Error("[OpenRTC] Invalid or retired live credentials.");return t}finally{this.abort.signal.removeEventListener("abort",i);}}async open(e){if(this.opened||this.retired||!this.bridge.createChannel)throw new Error("[OpenRTC] Native live coordination is unavailable.");this.opened=true,this.options=e;let i=await this.bridge.createChannel(t=>{t.type==="credentials-required"?this.retired||this.renew().catch(()=>this.close()):t.type==="closed"?(this.retired=true,this.abort.abort(),this.emit(t)):!this.retired&&t.type==="message"&&this.emit(t);}),r=await this.credentials(false);if(this.certificate=r.certificate,this.opening=this.bridge.invoke("openrtc_open_live_coordination",{endpoint:this.endpoint,credentials:r,channel:i}),this.id=await this.opening,this.retired)throw await this.close(),new Error("[OpenRTC] Native live activation was closed.")}async renew(){if(this.renewal)return this.renewal;let e=false,i=(async()=>{let r=await this.credentials(true);if(r.certificate!==this.certificate)throw new Error("[OpenRTC] Live term changed; open a new session.");try{await this.request({type:"renew",token:r.session});}catch(t){throw e=(t instanceof Error?t.message:String(t))==="live-certificate-expiry",t}})();this.renewal=i;try{await i;}catch(r){throw e||await this.close(),r}finally{this.renewal===i&&(this.renewal=void 0);}}async request(e){if(this.retired||!this.id)throw new Error("[OpenRTC] Native live session is closed.");return this.bridge.invoke("openrtc_send_live_coordination",{sessionId:this.id,frame:e})}close(){if(this.closing)return this.closing;this.retired=true,this.abort.abort();let e=(async()=>{let i=this.id??await this.opening?.catch(()=>{});i&&await this.bridge.invoke("openrtc_close_live_coordination",{sessionId:i}),this.id=void 0,this.emit({type:"closed"}),this.listeners.clear();})();return this.closing=e,e.catch(i=>{throw this.closing===e&&(this.closing=void 0),i})}};export{d as OpenRTC};
1
+ import {a as a$1}from'./chunk-5336XOTL.js';import {d as d$1}from'./chunk-72NEEJQG.js';import {i}from'./chunk-RUOVYQ2P.js';import'./chunk-FKAQDDUM.js';import'./chunk-SSBR3IHA.js';export{b as parseTicketInvite}from'./chunk-IUU6JCLK.js';import'./chunk-CCCYE3XN.js';import'./chunk-JPBW67B3.js';import'./chunk-ZA44REGI.js';export{a as ERROR_CODES,b as RTCError,e as classifyError,d as createError,c as projectError}from'./chunk-L7N4T2PX.js';import'./chunk-72MN7BNQ.js';import'./chunk-2GX6GB6L.js';function d(n){return i(n,{platform:"web",liveHostFactory:async(e,i)=>{let{BrowserCoordinationGatewaySignaling:r}=await import('./BrowserCoordinationGatewaySignaling-GOLSTJMA.js');return r.live(e,i)},broadcastHostFactory:async e=>{let[{BrowserManagedBroadcastHost:i},{loadBrowserWasmRuntimeModule:r}]=await Promise.all([import('./BrowserManagedBroadcastHost-6VGHQQMF.js'),import('./WasmBridge-3HYLCY5Y.js')]),t=r().then(async o=>(await o.initWasm(),o.start(),new o.WasmClient(e.apiKey)));return new i({resolve:e.resolve,manage:e.manage,deviceId:e.deviceId,defaultAuth:e.defaultAuth,loadWasm:()=>t})},runtimeFactory:async e=>{let{createWasmClient:i}=await import('./runtime/factories.js');return i(e)}})}d.native=function(n,e=d$1()){let i$1,r=()=>i$1??(i$1=import('./NativeProjectionBroker-Z6LCR4WB.js').then(({NativeProjectionBroker:t})=>new t));return i(n,{platform:"native",liveHostFactory:t=>new a(e,t),broadcastHostFactory:async t=>{let{NativeManagedBroadcastHost:o}=await import('./NativeManagedBroadcastHost-6A2QP3A7.js');return new o(e,t)},offlineSupport:()=>e.invoke("openrtc_offline_runtime_support"),createOfflineEnrollmentRequest:async t=>{let o=await e.invoke("start_iroh_node");return e.invoke("openrtc_create_offline_enrollment_request",{trustDomain:t.trustDomain,deviceId:t.deviceId,endpointId:o,enrollmentNonce:crypto.randomUUID(),requestedRoles:t.requestedRoles})},close:async()=>{i$1&&await(await i$1).close();},deviceKeyProvider:a$1(e),deviceIdProvider:async()=>{let t=await e.invoke("get_rtc_local_device_info");return String(t?.deviceId??"")},runtimeFactory:async t=>{let[{createIpcClient:o},l]=await Promise.all([import('./ipcFactory-6XD3J2UU.js'),r()]);return o(t,e,l)}})};var a=class{constructor(e,i){this.bridge=e;this.endpoint=i;this.retired=false;this.opened=false;this.certificate="";this.abort=new AbortController;this.listeners=new Set;}get closed(){return this.retired}onEvent(e){return this.listeners.add(e),()=>{this.listeners.delete(e);}}emit(e){for(let i of this.listeners)try{i(e);}catch{}}async credentials(e){if(this.retired)throw new Error("[OpenRTC] Live session is closed.");let i,r=new Promise((t,o)=>{i=()=>o(new Error("[OpenRTC] Live credentials were closed.")),this.abort.signal.aborted?i():this.abort.signal.addEventListener("abort",i,{once:true});});try{let t=await Promise.race([this.options.credentials({forceRefresh:e,signal:this.abort.signal}),r]);if(this.retired||!t||typeof t.certificate!="string"||t.certificate.length>8192||typeof t.session!="string"||t.session.length>24e3)throw new Error("[OpenRTC] Invalid or retired live credentials.");return t}finally{this.abort.signal.removeEventListener("abort",i);}}async open(e){if(this.opened||this.retired||!this.bridge.createChannel)throw new Error("[OpenRTC] Native live coordination is unavailable.");this.opened=true,this.options=e;let i=await this.bridge.createChannel(t=>{t.type==="credentials-required"?this.retired||this.renew().catch(()=>this.close()):t.type==="closed"?(this.retired=true,this.abort.abort(),this.emit(t)):!this.retired&&t.type==="message"&&this.emit(t);}),r=await this.credentials(false);if(this.certificate=r.certificate,this.opening=this.bridge.invoke("openrtc_open_live_coordination",{endpoint:this.endpoint,credentials:r,channel:i}),this.id=await this.opening,this.retired)throw await this.close(),new Error("[OpenRTC] Native live activation was closed.")}async renew(){if(this.renewal)return this.renewal;let e=false,i=(async()=>{let r=await this.credentials(true);if(r.certificate!==this.certificate)throw new Error("[OpenRTC] Live term changed; open a new session.");try{await this.request({type:"renew",token:r.session});}catch(t){throw e=(t instanceof Error?t.message:String(t))==="live-certificate-expiry",t}})();this.renewal=i;try{await i;}catch(r){throw e||await this.close(),r}finally{this.renewal===i&&(this.renewal=void 0);}}async request(e){if(this.retired||!this.id)throw new Error("[OpenRTC] Native live session is closed.");return this.bridge.invoke("openrtc_send_live_coordination",{sessionId:this.id,frame:e})}close(){if(this.closing)return this.closing;this.retired=true,this.abort.abort();let e=(async()=>{let i=this.id??await this.opening?.catch(()=>{});i&&await this.bridge.invoke("openrtc_close_live_coordination",{sessionId:i}),this.id=void 0,this.emit({type:"closed"}),this.listeners.clear();})();return this.closing=e,e.catch(i=>{throw this.closing===e&&(this.closing=void 0),i})}};export{d as OpenRTC};
@@ -1 +1 @@
1
- import {a as a$2}from'./chunk-VARKDQGM.js';import {t}from'./chunk-SADNIMUO.js';import'./chunk-IXQ4KWGP.js';import'./chunk-CQHLD52E.js';import'./chunk-LCJQ7RSR.js';import'./chunk-FPJAUAEU.js';import {a as a$1}from'./chunk-L4HWDDXL.js';import'./chunk-2AAZFBRZ.js';import'./chunk-FNCEVW7G.js';import'./chunk-LB27VQRL.js';import'./chunk-OWKAJPOI.js';import {a}from'./chunk-XXZEDZUU.js';import'./chunk-TPF643LU.js';import'./chunk-72NEEJQG.js';import'./chunk-L2ZZXECX.js';import'./chunk-IUU6JCLK.js';import'./chunk-CCCYE3XN.js';import'./chunk-JPBW67B3.js';import'./chunk-ZA44REGI.js';import'./chunk-L7N4T2PX.js';import'./chunk-72MN7BNQ.js';import'./chunk-2GX6GB6L.js';function l(p,n,m=new a){let t$1=a$1(p);return a$2(t$1,new t({...t$1,bridge:n,projectionBroker:m}))}export{l as createIpcClient};
1
+ import {a as a$2}from'./chunk-TSMMRR5V.js';import {t}from'./chunk-M4KL5XZU.js';import'./chunk-IXQ4KWGP.js';import'./chunk-CQHLD52E.js';import'./chunk-LCJQ7RSR.js';import'./chunk-FPJAUAEU.js';import {a as a$1}from'./chunk-WTOA6B2A.js';import'./chunk-2AAZFBRZ.js';import'./chunk-FNCEVW7G.js';import'./chunk-LB27VQRL.js';import'./chunk-OWKAJPOI.js';import {a}from'./chunk-XXZEDZUU.js';import'./chunk-TPF643LU.js';import'./chunk-72NEEJQG.js';import'./chunk-L2ZZXECX.js';import'./chunk-IUU6JCLK.js';import'./chunk-CCCYE3XN.js';import'./chunk-JPBW67B3.js';import'./chunk-ZA44REGI.js';import'./chunk-L7N4T2PX.js';import'./chunk-72MN7BNQ.js';import'./chunk-2GX6GB6L.js';function l(p,n,m=new a){let t$1=a$1(p);return a$2(t$1,new t({...t$1,bridge:n,projectionBroker:m}))}export{l as createIpcClient};
package/dist/native.d.ts CHANGED
@@ -1,10 +1,10 @@
1
- import { O as Options, C as Client } from './types-Cruu-MsF.js';
2
- export { A as AccessMode, a as AttestationProvider, b as AuthProvider, c as Avenue, B as BotVerificationProvider, d as BroadcastCreateOptions, e as BroadcastGrant, f as BroadcastInvite, g as BroadcastInviteOptions, h as BroadcastMedia, i as BroadcastPublisher, j as BroadcastRole, k as BroadcastSession, l as BroadcastSource, m as BroadcastState, n as BroadcastStats, o as BroadcastTrackEvent, p as Channel, q as Channels, r as Connection, D as Delivery, s as DeviceOptions, t as DeviceProfile, u as Devices, E as EnrolledDevice, I as IncomingPeerBidirectionalStream, v as IncomingPeerUnidirectionalStream, L as LiveCoordinationCredentials, w as LiveCoordinationMessage, x as LiveCoordinationOptions, y as LiveCoordinationSession, z as LiveOnlyOptions, M as MediaConnection, F as MediaIncomingDemuxStats, G as MediaKind, H as MediaLatencySummary, J as MediaReceiver, K as MediaReceiverStats, N as MediaSender, P as MediaSenderStats, Q as MediaStats, R as MediaTrackEvent, S as MediaTrackOptions, T as Offline, U as OfflineAssurance, V as OfflineEnrollmentRequest, W as OfflineRuntimeSupport, X as PeerBidirectionalStream, Y as PeerDatagramDuplexStream, Z as PeerDatagramStats, _ as PeerStreamOptions, $ as PeerStreamTransport, a0 as Room, a1 as RoomMember, a2 as RoomMembers, a3 as RoomOptions, a4 as Space, a5 as SpaceOptions, a6 as State, a7 as Ticket, a8 as TicketOptions, a9 as Transports } from './types-Cruu-MsF.js';
1
+ import { O as Options, C as Client } from './types-DvZvz4EL.js';
2
+ export { A as AccessMode, a as AttestationProvider, b as AuthProvider, c as Avenue, B as BotVerificationProvider, d as BroadcastCreateOptions, e as BroadcastGrant, f as BroadcastInvite, g as BroadcastInviteOptions, h as BroadcastMedia, i as BroadcastPublisher, j as BroadcastRole, k as BroadcastSession, l as BroadcastSource, m as BroadcastState, n as BroadcastStats, o as BroadcastTrackEvent, p as Channel, q as Channels, r as Connection, D as Delivery, s as DeviceOptions, t as DeviceProfile, u as Devices, E as EnrolledDevice, I as IncomingPeerBidirectionalStream, v as IncomingPeerUnidirectionalStream, L as LiveCoordinationCredentials, w as LiveCoordinationMessage, x as LiveCoordinationOptions, y as LiveCoordinationSession, z as LiveOnlyOptions, M as MediaConnection, F as MediaIncomingDemuxStats, G as MediaKind, H as MediaLatencySummary, J as MediaReceiver, K as MediaReceiverStats, N as MediaSender, P as MediaSenderStats, Q as MediaStats, R as MediaTrackEvent, S as MediaTrackOptions, T as Offline, U as OfflineAssurance, V as OfflineEnrollmentRequest, W as OfflineRuntimeSupport, X as PeerBidirectionalStream, Y as PeerDatagramDuplexStream, Z as PeerDatagramStats, _ as PeerStreamOptions, $ as PeerStreamTransport, a0 as Room, a1 as RoomMember, a2 as RoomMembers, a3 as RoomOptions, a4 as Space, a5 as SpaceOptions, a6 as State, a7 as Ticket, a8 as TicketOptions, a9 as Transports } from './types-DvZvz4EL.js';
3
3
  import { P as PlutoIpcBridge } from './ipc-DgzKqHH3.js';
4
- export { E as EffectiveRoomArchitecture, R as RoomArchitectureMode, a as RoomArchitectureReason, b as RoomArchitectureSnapshot, c as RoomAuthorityAssignment, T as TransferPeerDemandPurpose, d as TransferPeerDemandRequest, e as TransferPeerDemandState, f as TransferPeerDemandStatus } from './Connection-BGVBMbWg.js';
5
- import './coreClient-ByXs38IP.js';
6
- import './assembly-DGrOqsLW.js';
7
- import './capabilities-DsKud7Sw.js';
4
+ export { E as EffectiveRoomArchitecture, R as RoomArchitectureMode, a as RoomArchitectureReason, b as RoomArchitectureSnapshot, c as RoomAuthorityAssignment, T as TransferPeerDemandPurpose, d as TransferPeerDemandRequest, e as TransferPeerDemandState, f as TransferPeerDemandStatus } from './Connection-U3fEt8_4.js';
5
+ import './coreClient-AVGEwlhT.js';
6
+ import './assembly-CtrHmP4j.js';
7
+ import './capabilities-Dxb0XOti.js';
8
8
 
9
9
  /**
10
10
  * Native-only OpenRTC entrypoint for Tauri and other IPC-backed frontends.
package/dist/native.js CHANGED
@@ -1 +1 @@
1
- import {a}from'./chunk-XXZEDZUU.js';import'./chunk-TPF643LU.js';import {a as a$1}from'./chunk-NS32P65Z.js';import {d}from'./chunk-72NEEJQG.js';import'./chunk-GMPEZXPD.js';import {i}from'./chunk-5LNRJE6L.js';import'./chunk-FKAQDDUM.js';import'./chunk-RLPWFHOY.js';import'./chunk-IUU6JCLK.js';import'./chunk-CCCYE3XN.js';import'./chunk-JPBW67B3.js';import'./chunk-ZA44REGI.js';import'./chunk-L7N4T2PX.js';import'./chunk-72MN7BNQ.js';import'./chunk-2GX6GB6L.js';function u(p,t=d()){let r=new a;return i(p,{platform:"native",broadcastHostFactory:async e=>{let{NativeManagedBroadcastHost:o}=await import('./NativeManagedBroadcastHost-6A2QP3A7.js');return new o(t,e)},offlineSupport:()=>t.invoke("openrtc_offline_runtime_support"),createOfflineEnrollmentRequest:async e=>{let o=await t.invoke("start_iroh_node");return t.invoke("openrtc_create_offline_enrollment_request",{trustDomain:e.trustDomain,deviceId:e.deviceId,endpointId:o,enrollmentNonce:crypto.randomUUID(),requestedRoles:e.requestedRoles})},close:()=>r.close(),deviceKeyProvider:a$1(t),deviceIdProvider:async()=>{let e=await t.invoke("get_rtc_local_device_info");return String(e?.deviceId??"")},runtimeFactory:async e=>{let{createIpcClient:o}=await import('./ipcFactory-F75IXEIE.js');return o(e,t,r)}})}export{u as OpenRTC};
1
+ import {a}from'./chunk-XXZEDZUU.js';import'./chunk-TPF643LU.js';import {a as a$1}from'./chunk-5336XOTL.js';import {d}from'./chunk-72NEEJQG.js';import {i}from'./chunk-RUOVYQ2P.js';import'./chunk-FKAQDDUM.js';import'./chunk-SSBR3IHA.js';import'./chunk-IUU6JCLK.js';import'./chunk-CCCYE3XN.js';import'./chunk-JPBW67B3.js';import'./chunk-ZA44REGI.js';import'./chunk-L7N4T2PX.js';import'./chunk-72MN7BNQ.js';import'./chunk-2GX6GB6L.js';function u(p,t=d()){let r=new a;return i(p,{platform:"native",broadcastHostFactory:async e=>{let{NativeManagedBroadcastHost:o}=await import('./NativeManagedBroadcastHost-6A2QP3A7.js');return new o(t,e)},offlineSupport:()=>t.invoke("openrtc_offline_runtime_support"),createOfflineEnrollmentRequest:async e=>{let o=await t.invoke("start_iroh_node");return t.invoke("openrtc_create_offline_enrollment_request",{trustDomain:e.trustDomain,deviceId:e.deviceId,endpointId:o,enrollmentNonce:crypto.randomUUID(),requestedRoles:e.requestedRoles})},close:()=>r.close(),deviceKeyProvider:a$1(t),deviceIdProvider:async()=>{let e=await t.invoke("get_rtc_local_device_info");return String(e?.deviceId??"")},runtimeFactory:async e=>{let{createIpcClient:o}=await import('./ipcFactory-6XD3J2UU.js');return o(e,t,r)}})}export{u as OpenRTC};
package/dist/node.d.ts CHANGED
@@ -1,12 +1,12 @@
1
- import { O as Options, C as Client } from './types-Cruu-MsF.js';
2
- export { A as AccessMode, a as AttestationProvider, b as AuthProvider, c as Avenue, B as BotVerificationProvider, d as BroadcastCreateOptions, e as BroadcastGrant, f as BroadcastInvite, g as BroadcastInviteOptions, h as BroadcastMedia, i as BroadcastPublisher, j as BroadcastRole, k as BroadcastSession, l as BroadcastSource, m as BroadcastState, n as BroadcastStats, o as BroadcastTrackEvent, p as Channel, q as Channels, r as Connection, D as Delivery, s as DeviceOptions, t as DeviceProfile, u as Devices, E as EnrolledDevice, I as IncomingPeerBidirectionalStream, v as IncomingPeerUnidirectionalStream, L as LiveCoordinationCredentials, w as LiveCoordinationMessage, x as LiveCoordinationOptions, y as LiveCoordinationSession, z as LiveOnlyOptions, M as MediaConnection, F as MediaIncomingDemuxStats, G as MediaKind, H as MediaLatencySummary, J as MediaReceiver, K as MediaReceiverStats, N as MediaSender, P as MediaSenderStats, Q as MediaStats, R as MediaTrackEvent, S as MediaTrackOptions, T as Offline, U as OfflineAssurance, V as OfflineEnrollmentRequest, W as OfflineRuntimeSupport, X as PeerBidirectionalStream, Y as PeerDatagramDuplexStream, Z as PeerDatagramStats, _ as PeerStreamOptions, $ as PeerStreamTransport, a0 as Room, a1 as RoomMember, a2 as RoomMembers, a3 as RoomOptions, a4 as Space, a5 as SpaceOptions, a6 as State, a7 as Ticket, a8 as TicketOptions, a9 as Transports } from './types-Cruu-MsF.js';
1
+ import { O as Options, C as Client } from './types-DvZvz4EL.js';
2
+ export { A as AccessMode, a as AttestationProvider, b as AuthProvider, c as Avenue, B as BotVerificationProvider, d as BroadcastCreateOptions, e as BroadcastGrant, f as BroadcastInvite, g as BroadcastInviteOptions, h as BroadcastMedia, i as BroadcastPublisher, j as BroadcastRole, k as BroadcastSession, l as BroadcastSource, m as BroadcastState, n as BroadcastStats, o as BroadcastTrackEvent, p as Channel, q as Channels, r as Connection, D as Delivery, s as DeviceOptions, t as DeviceProfile, u as Devices, E as EnrolledDevice, I as IncomingPeerBidirectionalStream, v as IncomingPeerUnidirectionalStream, L as LiveCoordinationCredentials, w as LiveCoordinationMessage, x as LiveCoordinationOptions, y as LiveCoordinationSession, z as LiveOnlyOptions, M as MediaConnection, F as MediaIncomingDemuxStats, G as MediaKind, H as MediaLatencySummary, J as MediaReceiver, K as MediaReceiverStats, N as MediaSender, P as MediaSenderStats, Q as MediaStats, R as MediaTrackEvent, S as MediaTrackOptions, T as Offline, U as OfflineAssurance, V as OfflineEnrollmentRequest, W as OfflineRuntimeSupport, X as PeerBidirectionalStream, Y as PeerDatagramDuplexStream, Z as PeerDatagramStats, _ as PeerStreamOptions, $ as PeerStreamTransport, a0 as Room, a1 as RoomMember, a2 as RoomMembers, a3 as RoomOptions, a4 as Space, a5 as SpaceOptions, a6 as State, a7 as Ticket, a8 as TicketOptions, a9 as Transports } from './types-DvZvz4EL.js';
3
3
  import { P as PlutoIpcBridge } from './ipc-DgzKqHH3.js';
4
- import { S as ServiceErrorObservation } from './Connection-BGVBMbWg.js';
5
- export { E as EffectiveRoomArchitecture, R as RoomArchitectureMode, a as RoomArchitectureReason, b as RoomArchitectureSnapshot, c as RoomAuthorityAssignment, T as TransferPeerDemandPurpose, d as TransferPeerDemandRequest, e as TransferPeerDemandState, f as TransferPeerDemandStatus } from './Connection-BGVBMbWg.js';
4
+ import { S as ServiceErrorObservation } from './Connection-U3fEt8_4.js';
5
+ export { E as EffectiveRoomArchitecture, R as RoomArchitectureMode, a as RoomArchitectureReason, b as RoomArchitectureSnapshot, c as RoomAuthorityAssignment, T as TransferPeerDemandPurpose, d as TransferPeerDemandRequest, e as TransferPeerDemandState, f as TransferPeerDemandStatus } from './Connection-U3fEt8_4.js';
6
6
  import { AuthorityAssignmentInput, AuthorityInterestAssignment } from './service-node.js';
7
- import './coreClient-ByXs38IP.js';
8
- import './assembly-DGrOqsLW.js';
9
- import './capabilities-DsKud7Sw.js';
7
+ import './coreClient-AVGEwlhT.js';
8
+ import './assembly-CtrHmP4j.js';
9
+ import './capabilities-Dxb0XOti.js';
10
10
 
11
11
  interface NodeServiceNodeOptions {
12
12
  apiKey: string;
package/dist/node.js CHANGED
@@ -1,2 +1,2 @@
1
- import {a}from'./chunk-XXZEDZUU.js';import {a as a$2}from'./chunk-TPF643LU.js';import {a as a$1}from'./chunk-NS32P65Z.js';import {c}from'./chunk-72NEEJQG.js';import'./chunk-GMPEZXPD.js';import {i,b as b$2,a as a$3}from'./chunk-5LNRJE6L.js';import'./chunk-FKAQDDUM.js';import'./chunk-RLPWFHOY.js';import'./chunk-IUU6JCLK.js';import'./chunk-CCCYE3XN.js';import'./chunk-JPBW67B3.js';import'./chunk-ZA44REGI.js';import {e as e$1,b as b$3}from'./chunk-L7N4T2PX.js';import {b as b$1,d,e}from'./chunk-72MN7BNQ.js';import'./chunk-2GX6GB6L.js';import {spawn}from'child_process';import {constants}from'fs';import {access,readFile}from'fs/promises';import {isAbsolute,resolve,dirname}from'path';import {fileURLToPath}from'url';import {isDeepStrictEqual}from'util';import {randomUUID,verify,createHash}from'crypto';var E=1,F=24*1024,U=96*1024,N=128*1024,C=64*1024,ne=256,ie=256,L=3e4,se=/^[A-Za-z0-9_.:@-]+$/,ae=/(?:^|_)(?:SECRET|TOKEN|PASSWORD|PRIVATE(?:_KEY)?|CREDENTIALS?)(?:_|$)/i,ce=1;function de(r){return Buffer.from(JSON.stringify({schema:r.schema,kind:r.kind,platform:r.platform,arch:r.arch,rustTarget:r.rustTarget,sourceCommit:r.sourceCommit,sourceDigest:r.sourceDigest,binarySha256:r.binarySha256,protocol:r.protocol,signingKeySha256:r.signingKeySha256,signatureAlgorithm:r.signatureAlgorithm}),"utf8")}async function le(r,e,t){let[o,n,c]=await Promise.all([readFile(t),readFile(resolve(e,"openrtc-node-host.manifest.json")),readFile(resolve(r,"native","openrtc-node-host-signing-public.pem"))]).catch(()=>{throw new Error("[OpenRTC] Packaged Node host provenance is incomplete.")}),i;try{i=JSON.parse(n.toString("utf8"));}catch{throw new Error("[OpenRTC] Packaged Node host manifest is invalid.")}let a=s=>createHash("sha256").update(s).digest("hex"),u={"darwin-arm64":"aarch64-apple-darwin","darwin-x64":"x86_64-apple-darwin","linux-x64":"x86_64-unknown-linux-gnu"}[`${process.platform}-${process.arch}`];if(!(i!=null&&u!==void 0&&i.schema===ce&&i.kind==="openrtc-node-host"&&i.platform===process.platform&&i.arch===process.arch&&i.rustTarget===u&&/^[0-9a-f]{40}$/.test(i.sourceCommit)&&/^[0-9a-f]{64}$/.test(i.sourceDigest)&&i.binarySha256===a(o)&&i.signingKeySha256===a(c)&&i.signatureAlgorithm==="ed25519"&&/^[A-Za-z0-9+/]{86}==$/.test(i.signature)&&verify(null,de(i),c,Buffer.from(i.signature,"base64"))))throw new Error("[OpenRTC] Packaged Node host provenance verification failed.")}function z(r){return Object.fromEntries(Object.entries(process.env).filter(([e,t])=>!ae.test(e)&&(!r||!t?.includes(r))))}function f(r,e){queueMicrotask(()=>{try{let t=r(e);t&&typeof t.then=="function"&&t.catch(()=>{try{process.emitWarning("[OpenRTC] ServiceNode callback failed.",{code:"OPENRTC_SERVICE_CALLBACK"});}catch{}});}catch{try{process.emitWarning("[OpenRTC] ServiceNode callback failed.",{code:"OPENRTC_SERVICE_CALLBACK"});}catch{}}});}function $(r){let e=/^\d{1,20}$/;return typeof r.transportStableId!="string"||!e.test(r.transportStableId)||!e.test(r.transportGeneration)||!e.test(r.routeGeneration)?null:{transportStableId:r.transportStableId,transportGeneration:r.transportGeneration,routeGeneration:r.routeGeneration}}function ue(r,e){return r.transportStableId===e.transportStableId&&r.transportGeneration===e.transportGeneration&&r.routeGeneration===e.routeGeneration}function m(r,e,t=160){let o=r.trim();if(!o||o.length>t||!se.test(o))throw new TypeError(`[OpenRTC] ${e} is invalid.`);return o}function v(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 pe(r){if(!/^pk_(?:live|test)_[A-Za-z0-9]+$/.test(r.apiKey))throw new TypeError("[OpenRTC] apiKey is invalid.");if(!/^sk_(?:live|test)_[A-Za-z0-9_-]+$/.test(r.secretKey)||r.secretKey.length>128)throw new TypeError("[OpenRTC] secretKey is invalid.");let e=[...r.shardIds].map(t=>m(t,"shardId",80)).sort();if(e.length<1||e.length>64||new Set(e).size!==e.length)throw new RangeError("[OpenRTC] shardIds must contain 1..64 unique identifiers.");if(!isAbsolute(r.stateDirectory))throw new TypeError("[OpenRTC] stateDirectory must be absolute.");return r.maxPeers!==void 0&&v(r.maxPeers,"maxPeers",50),r.startupTimeoutMs!==void 0&&v(r.startupTimeoutMs,"startupTimeoutMs",12e4),{...r,serviceId:m(r.serviceId,"serviceId",80),generation:v(r.generation,"generation"),shardIds:e,deviceId:m(r.deviceId,"deviceId"),deviceName:r.deviceName?.trim()||"OpenRTC Node service"}}async function y(r){try{return await access(r,process.platform==="win32"?constants.F_OK:constants.X_OK),!0}catch{return false}}async function V(r,e,t,o,n){return new Promise((c,i)=>{let a=spawn(r,e,{cwd:t,env:z(n),stdio:["ignore","pipe","pipe"]}),d=Buffer.alloc(0),u=Buffer.alloc(0),l=(p,Y)=>Buffer.concat([p,Y]).subarray(-N);a.stdout.on("data",p=>{d=l(d,p);}),a.stderr.on("data",p=>{u=l(u,p);});let s=setTimeout(()=>{a.kill(),i(new Error(`[OpenRTC] Node host command timed out: ${r}.`));},o);a.once("error",p=>{clearTimeout(s),i(p);}),a.once("exit",p=>{clearTimeout(s),p===0?c(d.toString("utf8")):i(new Error(`[OpenRTC] Node host command failed (${p??"signal"}): ${u.toString("utf8").trim().slice(-4096)}`));});})}async function J(r){let e=r.binaryPath||process.env.OPENRTC_NODE_HOST_BINARY;if(e){if(!isAbsolute(e)||!await y(e))throw new Error("[OpenRTC] Node host binaryPath must name an executable absolute path.");return {command:e,args:[...r.binaryArgs??[]]}}if(r.buildFromSource){let c=r.sourceRoot||process.env.OPENRTC_SOURCE_ROOT;if(!c||!isAbsolute(c))throw new Error("[OpenRTC] buildFromSource requires an absolute sourceRoot or OPENRTC_SOURCE_ROOT.");let i=resolve(c,"crates/openrtc/Cargo.toml"),a=resolve(c,"target");await V("cargo",["build","--locked","--manifest-path",i,"--features","node-host","--bin","openrtc-node-host","--target-dir",a],c,12e4,r.secretKey);let d=resolve(a,"debug",`openrtc-node-host${process.platform==="win32"?".exe":""}`);if(!await y(d))throw new Error("[OpenRTC] local Node host build did not produce an executable.");return {command:d,args:[]}}let t=resolve(dirname(fileURLToPath(import.meta.url)),".."),o=resolve(t,"native",`${process.platform}-${process.arch}`),n=resolve(o,`openrtc-node-host${process.platform==="win32"?".exe":""}`);if(!await y(n))throw new Error(`[OpenRTC] This package has no Node host for ${process.platform}-${process.arch}. Install a supported OpenRTC package, set OPENRTC_NODE_HOST_BINARY, or use buildFromSource with sourceRoot.`);return await le(t,o,n),{command:n,args:[]}}async function X(r,e){let t=await V(r.command,[...r.args,"--protocol-info"],process.cwd(),12e4,e),o=JSON.parse(t);if(o.protocolVersion!==E||o.lifecycleOwner!=="rust-peer-session"||o.maxConfigBytes!==F||o.maxCommandBytes!==U||o.maxApplicationPayloadBytes!==C)throw new Error("[OpenRTC] Node host protocol is incompatible.");return o}var I=class{constructor(e,t,o){this.options=e;this.roomId=t;this.onEvent=o;this.child=null;this.childClosed=Promise.resolve();this.output=Buffer.alloc(0);this.stderr=Buffer.alloc(0);this.pending=new Map;this.writeQueue=Promise.resolve();this.stopped=false;this.closing=null;}async start(){let e=await J(this.options),t=await X(e,this.options.secretKey),o=new Promise((n,c)=>{let i=spawn(e.command,[...e.args],{env:z(this.options.secretKey),stdio:["pipe","pipe","pipe"]});this.child=i,this.childClosed=new Promise(l=>i.once("close",()=>l()));let a,d=setTimeout(()=>{c(this.failure("Node host startup timed out")),i.kill();},this.options.startupTimeoutMs??L),u=l=>{clearTimeout(d);let s=b$3.is(l)?l:this.failure(l.message);this.terminalFailure=a??s,c(s),this.failAll(s);};i.once("error",u),i.stdin.on("error",l=>{u(a??l),i.kill();}),i.stderr.on("data",l=>{this.stderr=Buffer.concat([this.stderr,l]).subarray(-4096);}),i.stdout.on("data",l=>{try{for(let s of this.parse(l)){if(s.type==="failure"){a=this.failure(s.error,s.serviceError),u(a);continue}if(t.testLane&&process.env.OPENRTC_NODE_HOST_LOCAL_TRACE==="1"&&s.type==="connection-state"&&console.error("[openrtc-local-node]",this.options.deviceId,{connectionId:s.snapshot.connectionId,deviceId:s.snapshot.deviceId,state:s.snapshot.state,routable:s.snapshot.routable,transportStableId:s.transportStableId,transportGeneration:s.transportGeneration,routeGeneration:s.routeGeneration}),s.type==="ready"){if(s.protocolVersion!==E||s.roomId!==this.roomId||s.deviceId!==this.options.deviceId||!isDeepStrictEqual(s.testLane,t.testLane))throw new Error("Node host returned inconsistent readiness metadata");clearTimeout(d),n();}this.dispatch(s);}}catch(s){u(s instanceof Error?s:new Error(String(s))),i.kill();}}),i.once("exit",(l,s)=>{clearTimeout(d),this.stopped=true;let p=a??this.failure(`Node host exited (${l??s??"unknown"})`);this.onEvent({type:"host-exit",error:p}),u(p);});});o.catch(()=>{});try{await this.writeLine({protocolVersion:E,apiKey:this.options.apiKey,secretKey:this.options.secretKey,serviceId:this.options.serviceId,generation:this.options.generation,shardIds:this.options.shardIds,deviceId:this.options.deviceId,roomId:this.roomId,deviceName:this.options.deviceName,stateDirectory:this.options.stateDirectory,maxPeers:this.options.maxPeers,irohRelay:this.options.irohRelay!==!1},F),await o;}catch(n){throw this.terminalFailure??n}}async request(e,t){if(!this.child||this.stopped||!this.child.stdin.writable)throw new Error("[OpenRTC] Node host is closed.");if(this.pending.size>=ne)throw new Error("[OpenRTC] Node host has too many pending requests.");let o=randomUUID(),n=new Promise((c,i)=>{let a=setTimeout(()=>{this.pending.delete(o),i(new Error(`[OpenRTC] Node host ${e} response timed out.`));},L);this.pending.set(o,{resolve:c,reject:i,timer:a});});n.catch(()=>{});try{await this.writeLine({type:e,id:o,...t},U);}catch(c){let i=this.pending.get(o);i&&(clearTimeout(i.timer),this.pending.delete(o),i.reject(this.terminalFailure??this.failure(c instanceof Error?c.message:String(c))));}return n}close(){return this.closing??(this.closing=this.stop())}async stop(){if(!this.child)return;let e=this.child;try{this.stopped||await this.request("shutdown",{});}finally{e.stdin.end();let t=setTimeout(()=>e.kill("SIGTERM"),2e3),o=setTimeout(()=>e.kill("SIGKILL"),4e3);try{await this.childClosed;}finally{clearTimeout(t),clearTimeout(o);}}}parse(e){if(this.output=Buffer.concat([this.output,e]),this.output.length>N&&!this.output.includes(10))throw new Error("Node host output line exceeded its byte limit");let t=[];for(;;){let o=this.output.indexOf(10);if(o<0)break;if(o>N)throw new Error("Node host output line exceeded its byte limit");let n=this.output.subarray(0,o).toString("utf8").trim();this.output=this.output.subarray(o+1),n&&t.push(JSON.parse(n));}return t}writeLine(e,t){let o=`${JSON.stringify(e)}
2
- `;if(Buffer.byteLength(o,"utf8")-1>t)return Promise.reject(new Error("Node host input line exceeded its byte limit"));let n=this.writeQueue.then(()=>new Promise((c,i)=>{if(!this.child||this.stopped||!this.child.stdin.writable){i(new Error("Node host is closed"));return}this.child.stdin.write(o,a=>{a?i(a):c();});}));return this.writeQueue=n.catch(()=>{}),n}dispatch(e){if(e.type!=="response"){this.onEvent(e);return}let t=this.pending.get(e.id);t&&(clearTimeout(t.timer),this.pending.delete(e.id),e.ok?t.resolve(e.value):t.reject(this.failure(e.error||"Node host request failed",e.serviceError)));}failure(e$2,t){let o=a=>a.split(this.options.secretKey).join("[REDACTED]"),n=o(e$2),c=o(this.stderr.toString("utf8")).trim(),i=`[OpenRTC] ${n}.${c?` Host stderr: ${c}`:""}`;if(t&&typeof t=="object"&&!Array.isArray(t)){let a=t,d$1=b$1(a.code);if(d(a.code)||d$1){let u=e(a);return e$1({...u,requestId:u.requestId?o(u.requestId):void 0,code:a.code,retryable:typeof a.retryable=="boolean"?a.retryable:!!d$1,message:i})}}return new Error(i)}failAll(e){for(let t of this.pending.values())clearTimeout(t.timer),t.reject(e);this.pending.clear();}},S=class{constructor(e,t,o,n,c){this.id=e;this.peerId=t;this.host=o;this.nativeGeneration=n;this.capabilityKey=c;this.messages=new Set;this.closeListeners=new Set;this.queued=[];this.isClosed=false;}async send(e){if(this.isClosed)throw new Error("[OpenRTC] Connection is closed.");let t=he(e instanceof Uint8Array||e instanceof ArrayBuffer?e:a$3("raw","message",e,this.capabilityKey));await this.host.request("send",{connectionId:this.id,payloadBase64:t.toString("base64")});}onMessage(e){let t=e;this.messages.add(t);for(let o of this.queued.splice(0))f(t,o);return ()=>this.messages.delete(t)}onClose(e){return this.isClosed?f(e,void 0):this.closeListeners.add(e),()=>this.closeListeners.delete(e)}receive(e){if(!this.isClosed){if(this.messages.size===0){this.queued.length===ie&&this.queued.shift(),this.queued.push(e);return}for(let t of this.messages)f(t,e);}}close(){if(!this.isClosed){this.isClosed=true,this.queued.length=0;for(let e of this.closeListeners)f(e,void 0);this.messages.clear(),this.closeListeners.clear();}}accepts(e){return ue(e,this.nativeGeneration)}replaceGeneration(e){this.nativeGeneration=e;}},T=class{constructor(e,t,o){this.id=e;this.host=t;this.onServiceError=o;this.kind="room";this.listeners=new Set;this.connections=new Map;this.closed=false;}publishAssignment(e){if(this.closed)return Promise.reject(new Error("[OpenRTC] Service room is closed."));let t=(e.priorityDeviceIds??[]).map(n=>m(n,"priorityDeviceId")),o=(e.relevantEntityIds??[]).map(n=>m(n,"relevantEntityId"));return t.length>8||o.length>32||new Set(t).size!==t.length||new Set(o).size!==o.length?Promise.reject(new Error("[OpenRTC] Authority assignment identifiers are invalid.")):this.host.request("publish-assignment",{revision:v(e.revision,"revision"),subjectDeviceId:m(e.subjectDeviceId,"subjectDeviceId"),shardId:m(e.shardId,"shardId",80),priorityDeviceIds:t,relevantEntityIds:o,ttlMs:e.ttlMs===void 0?void 0:v(e.ttlMs,"ttlMs",12e4)})}onConnection(e){this.listeners.add(e);for(let t of this.connections.values())f(e,t);return ()=>this.listeners.delete(e)}project(e){if(this.closed)return;if(e.type==="host-exit"){this.closed=true;for(let d of this.connections.values())d.close();this.connections.clear(),this.listeners.clear();return}if(e.type==="service-error"){let d=e.avenue;if(!d||typeof d!="object"||Array.isArray(d))return;let u=d;if(u.kind!=="room"||u.id!==this.id||typeof e.runtimeInstanceId!="string"||e.runtimeInstanceId.trim().length===0)return;let l=a$2(e.serviceError,{kind:"room",id:this.id});l&&this.onServiceError&&f(()=>{if(!this.closed)return this.onServiceError?.(l)},void 0);return}if(e.type==="peer-message"){let d=this.connections.get(e.connectionId),u=$(e);if(d&&u&&d.accepts(u)){let l=fe(e.payloadBase64),s=b$2(l);s?s.capability===`room:${this.id}`&&s.kind==="raw"&&d.receive(s.value):d.receive(l);}return}if(e.type!=="connection-state")return;let t=e.snapshot,o=$(e);if(typeof t.connectionId!="string"||!o)return;let n=this.connections.get(t.connectionId);if(typeof t.state=="string"&&["closed","failed"].includes(t.state.toLowerCase())){n?.accepts(o)&&(n.close(),this.connections.delete(t.connectionId));return}if(n){t.routable===true&&n.replaceGeneration(o);return}let i=typeof t.remoteNodeId=="string"?t.remoteNodeId:null;if(t.routable!==true||!i)return;let a=new S(t.connectionId,i,this.host,o,`room:${this.id}`);this.connections.set(a.id,a);for(let d of this.listeners)f(d,a);}async close(){if(this.closed)return this.host.close();this.closed=true;for(let e of this.connections.values())e.close();this.connections.clear(),this.listeners.clear(),await this.host.close();}};function he(r){let e;if(r instanceof Uint8Array)e=Buffer.from(r);else if(r instanceof ArrayBuffer)e=Buffer.from(r);else if(typeof r=="string")e=Buffer.from(r,"utf8");else {let t=JSON.stringify(r);if(t===void 0)throw new TypeError("[OpenRTC] Message must be a string, bytes, or JSON value.");e=Buffer.from(t,"utf8");}if(e.length>C)throw new RangeError("[OpenRTC] Message exceeds the Node host payload limit.");return e}function fe(r){let e=Buffer.from(r,"base64");if(e.length>C)throw new Error("[OpenRTC] Node host returned an oversized application payload.");try{let t=new TextDecoder("utf-8",{fatal:!0}).decode(e);try{return JSON.parse(t)}catch{return t}}catch{return new Uint8Array(e)}}var b=class{constructor(e){this.listeners=new Set;this.roomPromise=null;this.roomId=null;this.closed=false;this.closing=null;this.options=pe(e);}onConnection(e){if(this.closed)throw new Error("[OpenRTC] ServiceNode is closed.");return this.listeners.add(e),()=>this.listeners.delete(e)}listen(e){return this.closed?Promise.reject(new Error("[OpenRTC] ServiceNode is closed.")):(e=m(e,"roomId"),this.roomId&&this.roomId!==e?Promise.reject(new Error("[OpenRTC] A Node ServiceNode owns exactly one room.")):this.roomPromise?this.roomPromise:(this.roomId=e,this.roomPromise=this.open(e),this.roomPromise))}close(){return this.closing??(this.closing=this.stop())}async stop(){this.closed=true,await(await this.roomPromise?.catch(()=>null))?.close(),this.listeners.clear();}async open(e){let t,o=new I(this.options,e,n=>t?.project(n));t=new T(e,o,this.options.onServiceError);try{return await o.start(),t.onConnection(n=>{for(let c of this.listeners)f(c,{room:t,connection:n});}),t}catch(n){throw await o.close().catch(()=>{}),this.roomPromise=null,this.roomId=null,n}}};async function me(r){let e=await J(r);return X(e)}function ke(r,e){let t=c(e,"openrtc/node"),o=new a;return i(r,{platform:"native",broadcastHostFactory:async n=>{let{NativeManagedBroadcastHost:c}=await import('./NativeManagedBroadcastHost-6A2QP3A7.js');return new c(t,n)},offlineSupport:()=>t.invoke("openrtc_offline_runtime_support"),createOfflineEnrollmentRequest:async n=>{let c=await t.invoke("start_iroh_node");return t.invoke("openrtc_create_offline_enrollment_request",{trustDomain:n.trustDomain,deviceId:n.deviceId,endpointId:c,enrollmentNonce:crypto.randomUUID(),requestedRoles:n.requestedRoles})},close:()=>o.close(),deviceKeyProvider:a$1(t),deviceIdProvider:async()=>{let n=await t.invoke("get_rtc_local_device_info");return String(n?.deviceId??"")},runtimeFactory:async n=>{let{createIpcClient:c}=await import('./ipcFactory-F75IXEIE.js');return c(n,t,o)}})}export{ke as OpenRTC,b as ServiceNode,me as inspectNodeHost};
1
+ import {a}from'./chunk-XXZEDZUU.js';import {a as a$2}from'./chunk-TPF643LU.js';import {a as a$1}from'./chunk-5336XOTL.js';import {c}from'./chunk-72NEEJQG.js';import {i,b as b$2,a as a$3}from'./chunk-RUOVYQ2P.js';import'./chunk-FKAQDDUM.js';import'./chunk-SSBR3IHA.js';import'./chunk-IUU6JCLK.js';import'./chunk-CCCYE3XN.js';import'./chunk-JPBW67B3.js';import'./chunk-ZA44REGI.js';import {e as e$1,b as b$3}from'./chunk-L7N4T2PX.js';import {b as b$1,d,e}from'./chunk-72MN7BNQ.js';import'./chunk-2GX6GB6L.js';import {spawn}from'child_process';import {constants}from'fs';import {access,readFile}from'fs/promises';import {isAbsolute,resolve,dirname}from'path';import {fileURLToPath}from'url';import {isDeepStrictEqual}from'util';import {randomUUID,verify,createHash}from'crypto';var E=1,F=24*1024,U=96*1024,N=128*1024,C=64*1024,ne=256,ie=256,L=3e4,se=/^[A-Za-z0-9_.:@-]+$/,ae=/(?:^|_)(?:SECRET|TOKEN|PASSWORD|PRIVATE(?:_KEY)?|CREDENTIALS?)(?:_|$)/i,ce=1;function de(r){return Buffer.from(JSON.stringify({schema:r.schema,kind:r.kind,platform:r.platform,arch:r.arch,rustTarget:r.rustTarget,sourceCommit:r.sourceCommit,sourceDigest:r.sourceDigest,binarySha256:r.binarySha256,protocol:r.protocol,signingKeySha256:r.signingKeySha256,signatureAlgorithm:r.signatureAlgorithm}),"utf8")}async function le(r,e,t){let[o,n,c]=await Promise.all([readFile(t),readFile(resolve(e,"openrtc-node-host.manifest.json")),readFile(resolve(r,"native","openrtc-node-host-signing-public.pem"))]).catch(()=>{throw new Error("[OpenRTC] Packaged Node host provenance is incomplete.")}),i;try{i=JSON.parse(n.toString("utf8"));}catch{throw new Error("[OpenRTC] Packaged Node host manifest is invalid.")}let a=s=>createHash("sha256").update(s).digest("hex"),u={"darwin-arm64":"aarch64-apple-darwin","darwin-x64":"x86_64-apple-darwin","linux-x64":"x86_64-unknown-linux-gnu"}[`${process.platform}-${process.arch}`];if(!(i!=null&&u!==void 0&&i.schema===ce&&i.kind==="openrtc-node-host"&&i.platform===process.platform&&i.arch===process.arch&&i.rustTarget===u&&/^[0-9a-f]{40}$/.test(i.sourceCommit)&&/^[0-9a-f]{64}$/.test(i.sourceDigest)&&i.binarySha256===a(o)&&i.signingKeySha256===a(c)&&i.signatureAlgorithm==="ed25519"&&/^[A-Za-z0-9+/]{86}==$/.test(i.signature)&&verify(null,de(i),c,Buffer.from(i.signature,"base64"))))throw new Error("[OpenRTC] Packaged Node host provenance verification failed.")}function z(r){return Object.fromEntries(Object.entries(process.env).filter(([e,t])=>!ae.test(e)&&(!r||!t?.includes(r))))}function f(r,e){queueMicrotask(()=>{try{let t=r(e);t&&typeof t.then=="function"&&t.catch(()=>{try{process.emitWarning("[OpenRTC] ServiceNode callback failed.",{code:"OPENRTC_SERVICE_CALLBACK"});}catch{}});}catch{try{process.emitWarning("[OpenRTC] ServiceNode callback failed.",{code:"OPENRTC_SERVICE_CALLBACK"});}catch{}}});}function $(r){let e=/^\d{1,20}$/;return typeof r.transportStableId!="string"||!e.test(r.transportStableId)||!e.test(r.transportGeneration)||!e.test(r.routeGeneration)?null:{transportStableId:r.transportStableId,transportGeneration:r.transportGeneration,routeGeneration:r.routeGeneration}}function ue(r,e){return r.transportStableId===e.transportStableId&&r.transportGeneration===e.transportGeneration&&r.routeGeneration===e.routeGeneration}function m(r,e,t=160){let o=r.trim();if(!o||o.length>t||!se.test(o))throw new TypeError(`[OpenRTC] ${e} is invalid.`);return o}function v(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 pe(r){if(!/^pk_(?:live|test)_[A-Za-z0-9]+$/.test(r.apiKey))throw new TypeError("[OpenRTC] apiKey is invalid.");if(!/^sk_(?:live|test)_[A-Za-z0-9_-]+$/.test(r.secretKey)||r.secretKey.length>128)throw new TypeError("[OpenRTC] secretKey is invalid.");let e=[...r.shardIds].map(t=>m(t,"shardId",80)).sort();if(e.length<1||e.length>64||new Set(e).size!==e.length)throw new RangeError("[OpenRTC] shardIds must contain 1..64 unique identifiers.");if(!isAbsolute(r.stateDirectory))throw new TypeError("[OpenRTC] stateDirectory must be absolute.");return r.maxPeers!==void 0&&v(r.maxPeers,"maxPeers",50),r.startupTimeoutMs!==void 0&&v(r.startupTimeoutMs,"startupTimeoutMs",12e4),{...r,serviceId:m(r.serviceId,"serviceId",80),generation:v(r.generation,"generation"),shardIds:e,deviceId:m(r.deviceId,"deviceId"),deviceName:r.deviceName?.trim()||"OpenRTC Node service"}}async function y(r){try{return await access(r,process.platform==="win32"?constants.F_OK:constants.X_OK),!0}catch{return false}}async function V(r,e,t,o,n){return new Promise((c,i)=>{let a=spawn(r,e,{cwd:t,env:z(n),stdio:["ignore","pipe","pipe"]}),d=Buffer.alloc(0),u=Buffer.alloc(0),l=(p,Y)=>Buffer.concat([p,Y]).subarray(-N);a.stdout.on("data",p=>{d=l(d,p);}),a.stderr.on("data",p=>{u=l(u,p);});let s=setTimeout(()=>{a.kill(),i(new Error(`[OpenRTC] Node host command timed out: ${r}.`));},o);a.once("error",p=>{clearTimeout(s),i(p);}),a.once("exit",p=>{clearTimeout(s),p===0?c(d.toString("utf8")):i(new Error(`[OpenRTC] Node host command failed (${p??"signal"}): ${u.toString("utf8").trim().slice(-4096)}`));});})}async function J(r){let e=r.binaryPath||process.env.OPENRTC_NODE_HOST_BINARY;if(e){if(!isAbsolute(e)||!await y(e))throw new Error("[OpenRTC] Node host binaryPath must name an executable absolute path.");return {command:e,args:[...r.binaryArgs??[]]}}if(r.buildFromSource){let c=r.sourceRoot||process.env.OPENRTC_SOURCE_ROOT;if(!c||!isAbsolute(c))throw new Error("[OpenRTC] buildFromSource requires an absolute sourceRoot or OPENRTC_SOURCE_ROOT.");let i=resolve(c,"crates/openrtc/Cargo.toml"),a=resolve(c,"target");await V("cargo",["build","--locked","--manifest-path",i,"--features","node-host","--bin","openrtc-node-host","--target-dir",a],c,12e4,r.secretKey);let d=resolve(a,"debug",`openrtc-node-host${process.platform==="win32"?".exe":""}`);if(!await y(d))throw new Error("[OpenRTC] local Node host build did not produce an executable.");return {command:d,args:[]}}let t=resolve(dirname(fileURLToPath(import.meta.url)),".."),o=resolve(t,"native",`${process.platform}-${process.arch}`),n=resolve(o,`openrtc-node-host${process.platform==="win32"?".exe":""}`);if(!await y(n))throw new Error(`[OpenRTC] This package has no Node host for ${process.platform}-${process.arch}. Install a supported OpenRTC package, set OPENRTC_NODE_HOST_BINARY, or use buildFromSource with sourceRoot.`);return await le(t,o,n),{command:n,args:[]}}async function X(r,e){let t=await V(r.command,[...r.args,"--protocol-info"],process.cwd(),12e4,e),o=JSON.parse(t);if(o.protocolVersion!==E||o.lifecycleOwner!=="rust-peer-session"||o.maxConfigBytes!==F||o.maxCommandBytes!==U||o.maxApplicationPayloadBytes!==C)throw new Error("[OpenRTC] Node host protocol is incompatible.");return o}var I=class{constructor(e,t,o){this.options=e;this.roomId=t;this.onEvent=o;this.child=null;this.childClosed=Promise.resolve();this.output=Buffer.alloc(0);this.stderr=Buffer.alloc(0);this.pending=new Map;this.writeQueue=Promise.resolve();this.stopped=false;this.closing=null;}async start(){let e=await J(this.options),t=await X(e,this.options.secretKey),o=new Promise((n,c)=>{let i=spawn(e.command,[...e.args],{env:z(this.options.secretKey),stdio:["pipe","pipe","pipe"]});this.child=i,this.childClosed=new Promise(l=>i.once("close",()=>l()));let a,d=setTimeout(()=>{c(this.failure("Node host startup timed out")),i.kill();},this.options.startupTimeoutMs??L),u=l=>{clearTimeout(d);let s=b$3.is(l)?l:this.failure(l.message);this.terminalFailure=a??s,c(s),this.failAll(s);};i.once("error",u),i.stdin.on("error",l=>{u(a??l),i.kill();}),i.stderr.on("data",l=>{this.stderr=Buffer.concat([this.stderr,l]).subarray(-4096);}),i.stdout.on("data",l=>{try{for(let s of this.parse(l)){if(s.type==="failure"){a=this.failure(s.error,s.serviceError),u(a);continue}if(t.testLane&&process.env.OPENRTC_NODE_HOST_LOCAL_TRACE==="1"&&s.type==="connection-state"&&console.error("[openrtc-local-node]",this.options.deviceId,{connectionId:s.snapshot.connectionId,deviceId:s.snapshot.deviceId,state:s.snapshot.state,routable:s.snapshot.routable,transportStableId:s.transportStableId,transportGeneration:s.transportGeneration,routeGeneration:s.routeGeneration}),s.type==="ready"){if(s.protocolVersion!==E||s.roomId!==this.roomId||s.deviceId!==this.options.deviceId||!isDeepStrictEqual(s.testLane,t.testLane))throw new Error("Node host returned inconsistent readiness metadata");clearTimeout(d),n();}this.dispatch(s);}}catch(s){u(s instanceof Error?s:new Error(String(s))),i.kill();}}),i.once("exit",(l,s)=>{clearTimeout(d),this.stopped=true;let p=a??this.failure(`Node host exited (${l??s??"unknown"})`);this.onEvent({type:"host-exit",error:p}),u(p);});});o.catch(()=>{});try{await this.writeLine({protocolVersion:E,apiKey:this.options.apiKey,secretKey:this.options.secretKey,serviceId:this.options.serviceId,generation:this.options.generation,shardIds:this.options.shardIds,deviceId:this.options.deviceId,roomId:this.roomId,deviceName:this.options.deviceName,stateDirectory:this.options.stateDirectory,maxPeers:this.options.maxPeers,irohRelay:this.options.irohRelay!==!1},F),await o;}catch(n){throw this.terminalFailure??n}}async request(e,t){if(!this.child||this.stopped||!this.child.stdin.writable)throw new Error("[OpenRTC] Node host is closed.");if(this.pending.size>=ne)throw new Error("[OpenRTC] Node host has too many pending requests.");let o=randomUUID(),n=new Promise((c,i)=>{let a=setTimeout(()=>{this.pending.delete(o),i(new Error(`[OpenRTC] Node host ${e} response timed out.`));},L);this.pending.set(o,{resolve:c,reject:i,timer:a});});n.catch(()=>{});try{await this.writeLine({type:e,id:o,...t},U);}catch(c){let i=this.pending.get(o);i&&(clearTimeout(i.timer),this.pending.delete(o),i.reject(this.terminalFailure??this.failure(c instanceof Error?c.message:String(c))));}return n}close(){return this.closing??(this.closing=this.stop())}async stop(){if(!this.child)return;let e=this.child;try{this.stopped||await this.request("shutdown",{});}finally{e.stdin.end();let t=setTimeout(()=>e.kill("SIGTERM"),2e3),o=setTimeout(()=>e.kill("SIGKILL"),4e3);try{await this.childClosed;}finally{clearTimeout(t),clearTimeout(o);}}}parse(e){if(this.output=Buffer.concat([this.output,e]),this.output.length>N&&!this.output.includes(10))throw new Error("Node host output line exceeded its byte limit");let t=[];for(;;){let o=this.output.indexOf(10);if(o<0)break;if(o>N)throw new Error("Node host output line exceeded its byte limit");let n=this.output.subarray(0,o).toString("utf8").trim();this.output=this.output.subarray(o+1),n&&t.push(JSON.parse(n));}return t}writeLine(e,t){let o=`${JSON.stringify(e)}
2
+ `;if(Buffer.byteLength(o,"utf8")-1>t)return Promise.reject(new Error("Node host input line exceeded its byte limit"));let n=this.writeQueue.then(()=>new Promise((c,i)=>{if(!this.child||this.stopped||!this.child.stdin.writable){i(new Error("Node host is closed"));return}this.child.stdin.write(o,a=>{a?i(a):c();});}));return this.writeQueue=n.catch(()=>{}),n}dispatch(e){if(e.type!=="response"){this.onEvent(e);return}let t=this.pending.get(e.id);t&&(clearTimeout(t.timer),this.pending.delete(e.id),e.ok?t.resolve(e.value):t.reject(this.failure(e.error||"Node host request failed",e.serviceError)));}failure(e$2,t){let o=a=>a.split(this.options.secretKey).join("[REDACTED]"),n=o(e$2),c=o(this.stderr.toString("utf8")).trim(),i=`[OpenRTC] ${n}.${c?` Host stderr: ${c}`:""}`;if(t&&typeof t=="object"&&!Array.isArray(t)){let a=t,d$1=b$1(a.code);if(d(a.code)||d$1){let u=e(a);return e$1({...u,requestId:u.requestId?o(u.requestId):void 0,code:a.code,retryable:typeof a.retryable=="boolean"?a.retryable:!!d$1,message:i})}}return new Error(i)}failAll(e){for(let t of this.pending.values())clearTimeout(t.timer),t.reject(e);this.pending.clear();}},S=class{constructor(e,t,o,n,c){this.id=e;this.peerId=t;this.host=o;this.nativeGeneration=n;this.capabilityKey=c;this.messages=new Set;this.closeListeners=new Set;this.queued=[];this.isClosed=false;}async send(e){if(this.isClosed)throw new Error("[OpenRTC] Connection is closed.");let t=he(e instanceof Uint8Array||e instanceof ArrayBuffer?e:a$3("raw","message",e,this.capabilityKey));await this.host.request("send",{connectionId:this.id,payloadBase64:t.toString("base64")});}onMessage(e){let t=e;this.messages.add(t);for(let o of this.queued.splice(0))f(t,o);return ()=>this.messages.delete(t)}onClose(e){return this.isClosed?f(e,void 0):this.closeListeners.add(e),()=>this.closeListeners.delete(e)}receive(e){if(!this.isClosed){if(this.messages.size===0){this.queued.length===ie&&this.queued.shift(),this.queued.push(e);return}for(let t of this.messages)f(t,e);}}close(){if(!this.isClosed){this.isClosed=true,this.queued.length=0;for(let e of this.closeListeners)f(e,void 0);this.messages.clear(),this.closeListeners.clear();}}accepts(e){return ue(e,this.nativeGeneration)}replaceGeneration(e){this.nativeGeneration=e;}},T=class{constructor(e,t,o){this.id=e;this.host=t;this.onServiceError=o;this.kind="room";this.listeners=new Set;this.connections=new Map;this.closed=false;}publishAssignment(e){if(this.closed)return Promise.reject(new Error("[OpenRTC] Service room is closed."));let t=(e.priorityDeviceIds??[]).map(n=>m(n,"priorityDeviceId")),o=(e.relevantEntityIds??[]).map(n=>m(n,"relevantEntityId"));return t.length>8||o.length>32||new Set(t).size!==t.length||new Set(o).size!==o.length?Promise.reject(new Error("[OpenRTC] Authority assignment identifiers are invalid.")):this.host.request("publish-assignment",{revision:v(e.revision,"revision"),subjectDeviceId:m(e.subjectDeviceId,"subjectDeviceId"),shardId:m(e.shardId,"shardId",80),priorityDeviceIds:t,relevantEntityIds:o,ttlMs:e.ttlMs===void 0?void 0:v(e.ttlMs,"ttlMs",12e4)})}onConnection(e){this.listeners.add(e);for(let t of this.connections.values())f(e,t);return ()=>this.listeners.delete(e)}project(e){if(this.closed)return;if(e.type==="host-exit"){this.closed=true;for(let d of this.connections.values())d.close();this.connections.clear(),this.listeners.clear();return}if(e.type==="service-error"){let d=e.avenue;if(!d||typeof d!="object"||Array.isArray(d))return;let u=d;if(u.kind!=="room"||u.id!==this.id||typeof e.runtimeInstanceId!="string"||e.runtimeInstanceId.trim().length===0)return;let l=a$2(e.serviceError,{kind:"room",id:this.id});l&&this.onServiceError&&f(()=>{if(!this.closed)return this.onServiceError?.(l)},void 0);return}if(e.type==="peer-message"){let d=this.connections.get(e.connectionId),u=$(e);if(d&&u&&d.accepts(u)){let l=fe(e.payloadBase64),s=b$2(l);s?s.capability===`room:${this.id}`&&s.kind==="raw"&&d.receive(s.value):d.receive(l);}return}if(e.type!=="connection-state")return;let t=e.snapshot,o=$(e);if(typeof t.connectionId!="string"||!o)return;let n=this.connections.get(t.connectionId);if(typeof t.state=="string"&&["closed","failed"].includes(t.state.toLowerCase())){n?.accepts(o)&&(n.close(),this.connections.delete(t.connectionId));return}if(n){t.routable===true&&n.replaceGeneration(o);return}let i=typeof t.remoteNodeId=="string"?t.remoteNodeId:null;if(t.routable!==true||!i)return;let a=new S(t.connectionId,i,this.host,o,`room:${this.id}`);this.connections.set(a.id,a);for(let d of this.listeners)f(d,a);}async close(){if(this.closed)return this.host.close();this.closed=true;for(let e of this.connections.values())e.close();this.connections.clear(),this.listeners.clear(),await this.host.close();}};function he(r){let e;if(r instanceof Uint8Array)e=Buffer.from(r);else if(r instanceof ArrayBuffer)e=Buffer.from(r);else if(typeof r=="string")e=Buffer.from(r,"utf8");else {let t=JSON.stringify(r);if(t===void 0)throw new TypeError("[OpenRTC] Message must be a string, bytes, or JSON value.");e=Buffer.from(t,"utf8");}if(e.length>C)throw new RangeError("[OpenRTC] Message exceeds the Node host payload limit.");return e}function fe(r){let e=Buffer.from(r,"base64");if(e.length>C)throw new Error("[OpenRTC] Node host returned an oversized application payload.");try{let t=new TextDecoder("utf-8",{fatal:!0}).decode(e);try{return JSON.parse(t)}catch{return t}}catch{return new Uint8Array(e)}}var b=class{constructor(e){this.listeners=new Set;this.roomPromise=null;this.roomId=null;this.closed=false;this.closing=null;this.options=pe(e);}onConnection(e){if(this.closed)throw new Error("[OpenRTC] ServiceNode is closed.");return this.listeners.add(e),()=>this.listeners.delete(e)}listen(e){return this.closed?Promise.reject(new Error("[OpenRTC] ServiceNode is closed.")):(e=m(e,"roomId"),this.roomId&&this.roomId!==e?Promise.reject(new Error("[OpenRTC] A Node ServiceNode owns exactly one room.")):this.roomPromise?this.roomPromise:(this.roomId=e,this.roomPromise=this.open(e),this.roomPromise))}close(){return this.closing??(this.closing=this.stop())}async stop(){this.closed=true,await(await this.roomPromise?.catch(()=>null))?.close(),this.listeners.clear();}async open(e){let t,o=new I(this.options,e,n=>t?.project(n));t=new T(e,o,this.options.onServiceError);try{return await o.start(),t.onConnection(n=>{for(let c of this.listeners)f(c,{room:t,connection:n});}),t}catch(n){throw await o.close().catch(()=>{}),this.roomPromise=null,this.roomId=null,n}}};async function me(r){let e=await J(r);return X(e)}function ke(r,e){let t=c(e,"openrtc/node"),o=new a;return i(r,{platform:"native",broadcastHostFactory:async n=>{let{NativeManagedBroadcastHost:c}=await import('./NativeManagedBroadcastHost-6A2QP3A7.js');return new c(t,n)},offlineSupport:()=>t.invoke("openrtc_offline_runtime_support"),createOfflineEnrollmentRequest:async n=>{let c=await t.invoke("start_iroh_node");return t.invoke("openrtc_create_offline_enrollment_request",{trustDomain:n.trustDomain,deviceId:n.deviceId,endpointId:c,enrollmentNonce:crypto.randomUUID(),requestedRoles:n.requestedRoles})},close:()=>o.close(),deviceKeyProvider:a$1(t),deviceIdProvider:async()=>{let n=await t.invoke("get_rtc_local_device_info");return String(n?.deviceId??"")},runtimeFactory:async n=>{let{createIpcClient:c}=await import('./ipcFactory-6XD3J2UU.js');return c(n,t,o)}})}export{ke as OpenRTC,b as ServiceNode,me as inspectNodeHost};
Binary file
@@ -1 +1 @@
1
- import {h,e,g,f}from'./chunk-5LNRJE6L.js';import'./chunk-FKAQDDUM.js';import'./chunk-RLPWFHOY.js';import {a}from'./chunk-IUU6JCLK.js';import'./chunk-CCCYE3XN.js';import'./chunk-JPBW67B3.js';import {b}from'./chunk-ZA44REGI.js';import'./chunk-L7N4T2PX.js';import'./chunk-72MN7BNQ.js';import'./chunk-2GX6GB6L.js';function D(r){let e=r.architecture??(r.advancedFanout===true?"sparse":"auto");if(r.advancedFanout===true&&e!=="sparse")throw new Error("[OpenRTC] advancedFanout conflicts with architecture; use architecture: sparse only.");return {architecture:e,delivery:r.payload??(r.advancedFanout===true?"latest-state":"reliable")}}var R=class{constructor(e){this.mode=e==="sparse"?"sparse":"direct";}create(e){return new w(e,()=>this.mode)}setArchitecture(e){e.phase==="settled"&&(this.mode=e.effective==="sparse"?"sparse":e.effective==="managed"?"managed":"direct");}},w=class{constructor(e,t){this.host=e;this.mode=t;this.stateSenders=new Map;this.sparseForwardQueue=[];this.sparseForwardRunning=false;this.sparseForwardQueueDropsPending=0;this.sparseForwardDropReport=null;this.closed=false;let i=e.client.advanced.runtime.onManagedRoomMessage;this.stopManagedMessage=typeof i=="function"?i.call(e.client.advanced.runtime,o=>{e.deliver(o.senderId,o.payload,o.channel);}):()=>{};}isSparse(){return this.mode()==="sparse"}publishState(e,t){if(this.mode()!=="managed")return false;let i=this.stateSenders.get(e);return i||(i=new a(o=>this.publishManaged(e,o)),this.stateSenders.set(e,i)),i.send(t).catch(()=>{}),true}async sendChannel(e,t){let i=this.mode();if(i==="managed")return await this.publishManaged(e,t),true;if(i!=="sparse")return false;let o=this.host.connections();if(o.length===0)return true;let a=await this.host.client.advanced.runtime.encodeSparseFanoutMessage(this.host.capabilityKey,t);return await Promise.all(o.map(n=>n.send(a))),true}assertTargetedSendAllowed(){if(this.mode()==="managed")throw new Error("[OpenRTC] Targeted messages are not available in managed fanout rooms; use authority mode for targeted request semantics.")}receive(e,t,i){return this.mode()!=="sparse"?false:(i instanceof Uint8Array&&this.receiveSparseBroadcast(e,t,i),true)}close(){if(!this.closed){this.closed=true,this.stopManagedMessage();for(let e of this.stateSenders.values())e.close();this.stateSenders.clear(),this.sparseForwardQueue.length=0;}}publishManaged(e,t){return this.host.client.advanced.runtime.publishManagedRoomMessage({messageId:crypto.randomUUID(),channel:e,priority:1,payload:t})}async receiveSparseBroadcast(e,t,i){let o;try{o=await this.host.client.advanced.runtime.acceptSparseFanoutMessage(this.host.capabilityKey,t,i);}catch{return}if(o.forward){let a=Number.isSafeInteger(o.forwardPeerLimit)&&o.forwardPeerLimit>0?o.forwardPeerLimit:0,n=Number.isSafeInteger(o.forwardQueueCapacity)&&o.forwardQueueCapacity>0?Math.min(o.forwardQueueCapacity,64):0,d=new Set(Array.isArray(o.forwardPeerIds)?o.forwardPeerIds.slice(0,a):[]),s=this.host.connections().filter(u=>u.id!==e.id).filter(u=>d.has(u.remoteNodeId)).slice(0,a);this.enqueueSparseForward(o.forward,s,n);}this.host.deliver(o.authorDeviceId,o.payload);}enqueueSparseForward(e,t,i){if(i===0||t.length===0||this.closed)return;if(this.sparseForwardQueue.length+(this.sparseForwardRunning?1:0)>=i){this.sparseForwardQueueDropsPending+=1,this.flushSparseForwardDropReport();return}this.sparseForwardQueue.push({payload:e,targets:t}),this.sparseForwardRunning||this.drainSparseForwardQueue();}async drainSparseForwardQueue(){if(!this.sparseForwardRunning){this.sparseForwardRunning=true;try{for(;!this.closed;){let e=this.sparseForwardQueue.shift();if(!e)break;await Promise.allSettled(e.targets.map(t=>t.send(e.payload)));}}finally{this.sparseForwardRunning=false,!this.closed&&this.sparseForwardQueue.length>0&&this.drainSparseForwardQueue();}}}flushSparseForwardDropReport(){if(this.sparseForwardDropReport||this.sparseForwardQueueDropsPending===0)return;let e=this.sparseForwardQueueDropsPending;this.sparseForwardQueueDropsPending=0,this.sparseForwardDropReport=this.host.client.advanced.runtime.recordSparseFanoutForwardQueueDrop(this.host.capabilityKey,e).catch(()=>{}).finally(()=>{this.sparseForwardDropReport=null,this.flushSparseForwardDropReport();});}};function F(r){return Object.freeze(r.filter(e=>!!(e.deviceId||e.nodeId)).map(e=>Object.freeze({deviceId:e.deviceId||e.nodeId,...e.nodeId?{nodeId:e.nodeId}:{},...typeof e.userId=="string"?{userId:e.userId}:{},...Number.isFinite(e.joinedAt)?{joinedAt:e.joinedAt}:{}})))}var y=class extends h{constructor(t,i,o,a,n,d="auto"){let s=new R(d);super("room",t,i,o,s);this.membership=a;this.onLeave=n;this.kind="room";this.left=false;this.memberWatches=new Map;this.members={list:async()=>{if(this.closed)return [];let t=await this.client.rooms.members(this.id);return this.closed?[]:F(t)},watch:t=>{if(this.closed)return t([]),()=>{};let i=true,o=this.client.rooms.watch(this.id,n=>{i&&!this.closed&&t(F(n));}),a=()=>{i&&(i=false,this.memberWatches.delete(a),o());};return this.memberWatches.set(a,t),a}};this.architectureListeners=new Set;this.authorityAssignmentSnapshot=null;this.authorityAssignmentListeners=new Set;this.architectureSnapshot=Q(d);let u=i.advanced.runtime.onRoomArchitectureChange;this.stopArchitecture=typeof u=="function"?u.call(i.advanced.runtime,c=>{if(!(c.epoch<this.architectureSnapshot.epoch)){this.architectureSnapshot=Object.freeze({...c}),this.setArchitecture(c);for(let h of this.architectureListeners)h(this.architectureSnapshot);}}):()=>{};let l=i.advanced.runtime.onRoomAuthorityAssignmentChange;this.stopAuthorityAssignment=typeof l=="function"?l.call(i.advanced.runtime,c=>{this.authorityAssignmentSnapshot=c?E(c):null;for(let h of this.authorityAssignmentListeners)h(M(this.authorityAssignmentSnapshot));}):()=>{};}architecture(){return {...this.architectureSnapshot}}onArchitectureChanged(t){return this.architectureListeners.add(t),t(this.architecture()),()=>this.architectureListeners.delete(t)}authorityAssignment(){return M(this.authorityAssignmentSnapshot)}onAuthorityAssignmentChanged(t){return this.authorityAssignmentListeners.add(t),t(this.authorityAssignment()),()=>this.authorityAssignmentListeners.delete(t)}async leave(){this.left||(this.left=true,await this.onLeave?.()),await this.close();}async close(){this.fenceProductAccess();let t=[...this.memberWatches];this.memberWatches.clear();for(let[i,o]of t)i(),o([]);this.stopArchitecture(),this.stopAuthorityAssignment(),this.architectureListeners.clear(),this.authorityAssignmentListeners.clear(),await super.close();}};async function j(r,e$1,t){r.assertOpen();let i=e(e$1),o=t.access??"capability",{architecture:a,delivery:n}=D(t);return r.activateOnce(`room:${i}`,JSON.stringify({access:o,membership:t.membership??"ephemeral",identity:t.identity??null,maxPeers:t.maxPeers??null,payload:n,architecture:a,advancedFanout:t.advancedFanout===true}),o==="authenticated"?t.auth??r.options.auth:void 0,()=>x(r,i,t,a,n))}async function x(r,e,t,i,o){let a=t.membership??"ephemeral",n=t.access??"capability";if(i==="sparse"&&o!=="latest-state")throw new Error("[OpenRTC] Sparse rooms require payload: latest-state.");if(a==="durable"&&n!=="authenticated")throw new Error("[OpenRTC] Durable room membership requires access: authenticated.");if(t.identity==="session"&&n!=="capability")throw new Error("[OpenRTC] Session room identity requires access: capability.");if(n==="authenticated"){let h=t.auth??r.options.auth;if(!h)throw new Error("[OpenRTC] Authenticated rooms require an auth provider.");let A=await r.deviceId(),v=await r.controlPlane(),m=await v.deviceCertificate(h,A,{kind:"room",id:e});a==="durable"&&await v.durableRoomMembership(m.source,e,"join");let f;try{f=await r.activate({kind:"room",id:e,source:m.source,principalId:m.principalId,deviceId:A,maxPeers:t.maxPeers,autoConnect:!0,durableMembership:a==="durable",advancedFanout:t.advancedFanout,architecture:i,defaultDelivery:o});}catch(O){throw a==="durable"&&await v.durableRoomMembership(m.source,e,"leave").catch(()=>{}),O}let g;return g=new y(e,f,()=>{r.channels.detach(f),r.onClosed(g);},a,a==="durable"?async()=>{await v.durableRoomMembership(m.source,e,"leave");}:void 0,i),r.trackHandle(g)}let d=await(t.identity==="session"?r.sessionPlane():r.controlPlane()),s=await d.capability("room",e,t.maxPeers,t.advancedFanout,i,o),u=String(b(s.token).principalId),l=await r.activate({kind:"room",id:e,source:s,principalId:u,deviceId:g(s),maxPeers:t.maxPeers,autoConnect:true,advancedFanout:t.advancedFanout,architecture:i,defaultDelivery:o,controlPlane:d}),c;return c=new y(e,l,()=>{r.channels.detach(l),r.onClosed(c);},"ephemeral",void 0,i),r.trackHandle(c)}function z(r,e$1){r.assertOpen();let t=e(e$1.roomId),i=e(e$1.serviceId),o=f(e$1.deviceId);if(!Number.isSafeInteger(e$1.generation)||e$1.generation<1)throw new Error("[OpenRTC] Authority service generation is invalid.");let a=[...e$1.shardIds].map(e).sort();if(a.length<1||a.length>64||new Set(a).size!==a.length)throw new Error("[OpenRTC] Authority service shards are invalid.");if(!/^[A-Za-z0-9_-]{43}$/.test(e$1.devicePublicKeyX))throw new Error("[OpenRTC] Authority service device public key is invalid.");if(!/^[A-Za-z0-9_-]{43}$/.test(e$1.assignmentPublicKeyX))throw new Error("[OpenRTC] Authority assignment public key is invalid.");if(e$1.maxPeers!==void 0&&(!Number.isSafeInteger(e$1.maxPeers)||e$1.maxPeers<1||e$1.maxPeers>50))throw new Error("[OpenRTC] Authority service maxPeers must be within 1..50.");return r.activateOnce(`room:${t}`,JSON.stringify({architecture:"authority",serviceId:i,generation:e$1.generation,shardIds:a,deviceId:o,maxPeers:e$1.maxPeers??null,irohRelay:e$1.irohRelay,devicePublicKeyX:e$1.devicePublicKeyX,assignmentPublicKeyX:e$1.assignmentPublicKeyX,deviceSignerId:r.authorityCallableId(e$1.deviceSign),grantProviderId:r.authorityCallableId(e$1.grantProvider)}),void 0,async()=>{let n={type:"capability",token:"",avenue:{kind:"room",id:t},expiresAtMs:Number.MAX_SAFE_INTEGER,irohRelay:e$1.irohRelay,managedTurn:false},d=await r.activate({kind:"room",id:t,source:n,principalId:i,deviceId:o,maxPeers:e$1.maxPeers,autoConnect:true,architecture:"authority",defaultDelivery:"reliable",authority:{serviceId:i,generation:e$1.generation,shardIds:a,deviceId:o,irohRelay:e$1.irohRelay,devicePublicKeyX:e$1.devicePublicKeyX,assignmentPublicKeyX:e$1.assignmentPublicKeyX,deviceSign:e$1.deviceSign,grantProvider:e$1.grantProvider}}),s;return s=new y(t,d,()=>{r.channels.detach(d),r.onClosed(s);},"ephemeral",void 0,"authority"),r.trackHandle(s)})}function E(r){return Object.freeze({...r,priorityDeviceIds:Object.freeze([...r.priorityDeviceIds]),relevantEntityIds:Object.freeze([...r.relevantEntityIds])})}function M(r){return r?{...r,priorityDeviceIds:[...r.priorityDeviceIds],relevantEntityIds:[...r.relevantEntityIds]}:null}function Q(r){return {requested:r,effective:r==="sparse"?"sparse":"mesh",epoch:0,phase:r==="mesh"||r==="sparse"?"settled":"preparing",reason:r==="auto"?"size":"manual"}}export{y as RoomHandle,j as joinRoom,z as openAuthorityRoom,D as resolveRoomJoinOptions};
1
+ import {h,e,g,f}from'./chunk-RUOVYQ2P.js';import'./chunk-FKAQDDUM.js';import'./chunk-SSBR3IHA.js';import {a}from'./chunk-IUU6JCLK.js';import'./chunk-CCCYE3XN.js';import'./chunk-JPBW67B3.js';import {b}from'./chunk-ZA44REGI.js';import'./chunk-L7N4T2PX.js';import'./chunk-72MN7BNQ.js';import'./chunk-2GX6GB6L.js';function D(r){let e=r.architecture??(r.advancedFanout===true?"sparse":"auto");if(r.advancedFanout===true&&e!=="sparse")throw new Error("[OpenRTC] advancedFanout conflicts with architecture; use architecture: sparse only.");return {architecture:e,delivery:r.payload??(r.advancedFanout===true?"latest-state":"reliable")}}var R=class{constructor(e){this.mode=e==="sparse"?"sparse":"direct";}create(e){return new w(e,()=>this.mode)}setArchitecture(e){e.phase==="settled"&&(this.mode=e.effective==="sparse"?"sparse":e.effective==="managed"?"managed":"direct");}},w=class{constructor(e,t){this.host=e;this.mode=t;this.stateSenders=new Map;this.sparseForwardQueue=[];this.sparseForwardRunning=false;this.sparseForwardQueueDropsPending=0;this.sparseForwardDropReport=null;this.closed=false;let i=e.client.advanced.runtime.onManagedRoomMessage;this.stopManagedMessage=typeof i=="function"?i.call(e.client.advanced.runtime,o=>{e.deliver(o.senderId,o.payload,o.channel);}):()=>{};}isSparse(){return this.mode()==="sparse"}publishState(e,t){if(this.mode()!=="managed")return false;let i=this.stateSenders.get(e);return i||(i=new a(o=>this.publishManaged(e,o)),this.stateSenders.set(e,i)),i.send(t).catch(()=>{}),true}async sendChannel(e,t){let i=this.mode();if(i==="managed")return await this.publishManaged(e,t),true;if(i!=="sparse")return false;let o=this.host.connections();if(o.length===0)return true;let a=await this.host.client.advanced.runtime.encodeSparseFanoutMessage(this.host.capabilityKey,t);return await Promise.all(o.map(n=>n.send(a))),true}assertTargetedSendAllowed(){if(this.mode()==="managed")throw new Error("[OpenRTC] Targeted messages are not available in managed fanout rooms; use authority mode for targeted request semantics.")}receive(e,t,i){return this.mode()!=="sparse"?false:(i instanceof Uint8Array&&this.receiveSparseBroadcast(e,t,i),true)}close(){if(!this.closed){this.closed=true,this.stopManagedMessage();for(let e of this.stateSenders.values())e.close();this.stateSenders.clear(),this.sparseForwardQueue.length=0;}}publishManaged(e,t){return this.host.client.advanced.runtime.publishManagedRoomMessage({messageId:crypto.randomUUID(),channel:e,priority:1,payload:t})}async receiveSparseBroadcast(e,t,i){let o;try{o=await this.host.client.advanced.runtime.acceptSparseFanoutMessage(this.host.capabilityKey,t,i);}catch{return}if(o.forward){let a=Number.isSafeInteger(o.forwardPeerLimit)&&o.forwardPeerLimit>0?o.forwardPeerLimit:0,n=Number.isSafeInteger(o.forwardQueueCapacity)&&o.forwardQueueCapacity>0?Math.min(o.forwardQueueCapacity,64):0,d=new Set(Array.isArray(o.forwardPeerIds)?o.forwardPeerIds.slice(0,a):[]),s=this.host.connections().filter(u=>u.id!==e.id).filter(u=>d.has(u.remoteNodeId)).slice(0,a);this.enqueueSparseForward(o.forward,s,n);}this.host.deliver(o.authorDeviceId,o.payload);}enqueueSparseForward(e,t,i){if(i===0||t.length===0||this.closed)return;if(this.sparseForwardQueue.length+(this.sparseForwardRunning?1:0)>=i){this.sparseForwardQueueDropsPending+=1,this.flushSparseForwardDropReport();return}this.sparseForwardQueue.push({payload:e,targets:t}),this.sparseForwardRunning||this.drainSparseForwardQueue();}async drainSparseForwardQueue(){if(!this.sparseForwardRunning){this.sparseForwardRunning=true;try{for(;!this.closed;){let e=this.sparseForwardQueue.shift();if(!e)break;await Promise.allSettled(e.targets.map(t=>t.send(e.payload)));}}finally{this.sparseForwardRunning=false,!this.closed&&this.sparseForwardQueue.length>0&&this.drainSparseForwardQueue();}}}flushSparseForwardDropReport(){if(this.sparseForwardDropReport||this.sparseForwardQueueDropsPending===0)return;let e=this.sparseForwardQueueDropsPending;this.sparseForwardQueueDropsPending=0,this.sparseForwardDropReport=this.host.client.advanced.runtime.recordSparseFanoutForwardQueueDrop(this.host.capabilityKey,e).catch(()=>{}).finally(()=>{this.sparseForwardDropReport=null,this.flushSparseForwardDropReport();});}};function F(r){return Object.freeze(r.filter(e=>!!(e.deviceId||e.nodeId)).map(e=>Object.freeze({deviceId:e.deviceId||e.nodeId,...e.nodeId?{nodeId:e.nodeId}:{},...typeof e.userId=="string"?{userId:e.userId}:{},...Number.isFinite(e.joinedAt)?{joinedAt:e.joinedAt}:{}})))}var y=class extends h{constructor(t,i,o,a,n,d="auto"){let s=new R(d);super("room",t,i,o,s);this.membership=a;this.onLeave=n;this.kind="room";this.left=false;this.memberWatches=new Map;this.members={list:async()=>{if(this.closed)return [];let t=await this.client.rooms.members(this.id);return this.closed?[]:F(t)},watch:t=>{if(this.closed)return t([]),()=>{};let i=true,o=this.client.rooms.watch(this.id,n=>{i&&!this.closed&&t(F(n));}),a=()=>{i&&(i=false,this.memberWatches.delete(a),o());};return this.memberWatches.set(a,t),a}};this.architectureListeners=new Set;this.authorityAssignmentSnapshot=null;this.authorityAssignmentListeners=new Set;this.architectureSnapshot=Q(d);let u=i.advanced.runtime.onRoomArchitectureChange;this.stopArchitecture=typeof u=="function"?u.call(i.advanced.runtime,c=>{if(!(c.epoch<this.architectureSnapshot.epoch)){this.architectureSnapshot=Object.freeze({...c}),this.setArchitecture(c);for(let h of this.architectureListeners)h(this.architectureSnapshot);}}):()=>{};let l=i.advanced.runtime.onRoomAuthorityAssignmentChange;this.stopAuthorityAssignment=typeof l=="function"?l.call(i.advanced.runtime,c=>{this.authorityAssignmentSnapshot=c?E(c):null;for(let h of this.authorityAssignmentListeners)h(M(this.authorityAssignmentSnapshot));}):()=>{};}architecture(){return {...this.architectureSnapshot}}onArchitectureChanged(t){return this.architectureListeners.add(t),t(this.architecture()),()=>this.architectureListeners.delete(t)}authorityAssignment(){return M(this.authorityAssignmentSnapshot)}onAuthorityAssignmentChanged(t){return this.authorityAssignmentListeners.add(t),t(this.authorityAssignment()),()=>this.authorityAssignmentListeners.delete(t)}async leave(){this.left||(this.left=true,await this.onLeave?.()),await this.close();}async close(){this.fenceProductAccess();let t=[...this.memberWatches];this.memberWatches.clear();for(let[i,o]of t)i(),o([]);this.stopArchitecture(),this.stopAuthorityAssignment(),this.architectureListeners.clear(),this.authorityAssignmentListeners.clear(),await super.close();}};async function j(r,e$1,t){r.assertOpen();let i=e(e$1),o=t.access??"capability",{architecture:a,delivery:n}=D(t);return r.activateOnce(`room:${i}`,JSON.stringify({access:o,membership:t.membership??"ephemeral",identity:t.identity??null,maxPeers:t.maxPeers??null,payload:n,architecture:a,advancedFanout:t.advancedFanout===true}),o==="authenticated"?t.auth??r.options.auth:void 0,()=>x(r,i,t,a,n))}async function x(r,e,t,i,o){let a=t.membership??"ephemeral",n=t.access??"capability";if(i==="sparse"&&o!=="latest-state")throw new Error("[OpenRTC] Sparse rooms require payload: latest-state.");if(a==="durable"&&n!=="authenticated")throw new Error("[OpenRTC] Durable room membership requires access: authenticated.");if(t.identity==="session"&&n!=="capability")throw new Error("[OpenRTC] Session room identity requires access: capability.");if(n==="authenticated"){let h=t.auth??r.options.auth;if(!h)throw new Error("[OpenRTC] Authenticated rooms require an auth provider.");let A=await r.deviceId(),v=await r.controlPlane(),m=await v.deviceCertificate(h,A,{kind:"room",id:e});a==="durable"&&await v.durableRoomMembership(m.source,e,"join");let f;try{f=await r.activate({kind:"room",id:e,source:m.source,principalId:m.principalId,deviceId:A,maxPeers:t.maxPeers,autoConnect:!0,durableMembership:a==="durable",advancedFanout:t.advancedFanout,architecture:i,defaultDelivery:o});}catch(O){throw a==="durable"&&await v.durableRoomMembership(m.source,e,"leave").catch(()=>{}),O}let g;return g=new y(e,f,()=>{r.channels.detach(f),r.onClosed(g);},a,a==="durable"?async()=>{await v.durableRoomMembership(m.source,e,"leave");}:void 0,i),r.trackHandle(g)}let d=await(t.identity==="session"?r.sessionPlane():r.controlPlane()),s=await d.capability("room",e,t.maxPeers,t.advancedFanout,i,o),u=String(b(s.token).principalId),l=await r.activate({kind:"room",id:e,source:s,principalId:u,deviceId:g(s),maxPeers:t.maxPeers,autoConnect:true,advancedFanout:t.advancedFanout,architecture:i,defaultDelivery:o,controlPlane:d}),c;return c=new y(e,l,()=>{r.channels.detach(l),r.onClosed(c);},"ephemeral",void 0,i),r.trackHandle(c)}function z(r,e$1){r.assertOpen();let t=e(e$1.roomId),i=e(e$1.serviceId),o=f(e$1.deviceId);if(!Number.isSafeInteger(e$1.generation)||e$1.generation<1)throw new Error("[OpenRTC] Authority service generation is invalid.");let a=[...e$1.shardIds].map(e).sort();if(a.length<1||a.length>64||new Set(a).size!==a.length)throw new Error("[OpenRTC] Authority service shards are invalid.");if(!/^[A-Za-z0-9_-]{43}$/.test(e$1.devicePublicKeyX))throw new Error("[OpenRTC] Authority service device public key is invalid.");if(!/^[A-Za-z0-9_-]{43}$/.test(e$1.assignmentPublicKeyX))throw new Error("[OpenRTC] Authority assignment public key is invalid.");if(e$1.maxPeers!==void 0&&(!Number.isSafeInteger(e$1.maxPeers)||e$1.maxPeers<1||e$1.maxPeers>50))throw new Error("[OpenRTC] Authority service maxPeers must be within 1..50.");return r.activateOnce(`room:${t}`,JSON.stringify({architecture:"authority",serviceId:i,generation:e$1.generation,shardIds:a,deviceId:o,maxPeers:e$1.maxPeers??null,irohRelay:e$1.irohRelay,devicePublicKeyX:e$1.devicePublicKeyX,assignmentPublicKeyX:e$1.assignmentPublicKeyX,deviceSignerId:r.authorityCallableId(e$1.deviceSign),grantProviderId:r.authorityCallableId(e$1.grantProvider)}),void 0,async()=>{let n={type:"capability",token:"",avenue:{kind:"room",id:t},expiresAtMs:Number.MAX_SAFE_INTEGER,irohRelay:e$1.irohRelay,managedTurn:false},d=await r.activate({kind:"room",id:t,source:n,principalId:i,deviceId:o,maxPeers:e$1.maxPeers,autoConnect:true,architecture:"authority",defaultDelivery:"reliable",authority:{serviceId:i,generation:e$1.generation,shardIds:a,deviceId:o,irohRelay:e$1.irohRelay,devicePublicKeyX:e$1.devicePublicKeyX,assignmentPublicKeyX:e$1.assignmentPublicKeyX,deviceSign:e$1.deviceSign,grantProvider:e$1.grantProvider}}),s;return s=new y(t,d,()=>{r.channels.detach(d),r.onClosed(s);},"ephemeral",void 0,"authority"),r.trackHandle(s)})}function E(r){return Object.freeze({...r,priorityDeviceIds:Object.freeze([...r.priorityDeviceIds]),relevantEntityIds:Object.freeze([...r.relevantEntityIds])})}function M(r){return r?{...r,priorityDeviceIds:[...r.priorityDeviceIds],relevantEntityIds:[...r.relevantEntityIds]}:null}function Q(r){return {requested:r,effective:r==="sparse"?"sparse":"mesh",epoch:0,phase:r==="mesh"||r==="sparse"?"settled":"preparing",reason:r==="auto"?"size":"manual"}}export{y as RoomHandle,j as joinRoom,z as openAuthorityRoom,D as resolveRoomJoinOptions};
@@ -1,6 +1,6 @@
1
- import { D as DelegatingRuntimeAdapter, R as RuntimeBridgeOptions } from '../DelegatingRuntimeAdapter-JmhmwKTC.js';
2
- import '../Connection-BGVBMbWg.js';
3
- import '../capabilities-DsKud7Sw.js';
1
+ import { D as DelegatingRuntimeAdapter, R as RuntimeBridgeOptions } from '../DelegatingRuntimeAdapter-Coo5BVM2.js';
2
+ import '../Connection-U3fEt8_4.js';
3
+ import '../capabilities-Dxb0XOti.js';
4
4
 
5
5
  declare class WasmRuntimeAdapter extends DelegatingRuntimeAdapter {
6
6
  constructor(options: RuntimeBridgeOptions);
@@ -1 +1 @@
1
- import {b}from'../chunk-5LO6PLWZ.js';import'../chunk-AYHD4X2R.js';import {a}from'../chunk-CQHLD52E.js';import'../chunk-LCJQ7RSR.js';import'../chunk-FPJAUAEU.js';import'../chunk-L4HWDDXL.js';import'../chunk-FNCEVW7G.js';import'../chunk-LB27VQRL.js';import'../chunk-OWKAJPOI.js';import'../chunk-TPF643LU.js';import'../chunk-L2ZZXECX.js';import'../chunk-CCCYE3XN.js';import'../chunk-JPBW67B3.js';import'../chunk-ZA44REGI.js';import'../chunk-L7N4T2PX.js';import'../chunk-72MN7BNQ.js';import'../chunk-2GX6GB6L.js';var n=class extends a{constructor(e){super(new b(e));}setWasmClient(e){this.unwrap().setWasmClient(e);}};export{n as WasmRuntimeAdapter};
1
+ import {b}from'../chunk-PA4WT4QM.js';import'../chunk-AYHD4X2R.js';import {a}from'../chunk-CQHLD52E.js';import'../chunk-LCJQ7RSR.js';import'../chunk-FPJAUAEU.js';import'../chunk-WTOA6B2A.js';import'../chunk-FNCEVW7G.js';import'../chunk-LB27VQRL.js';import'../chunk-OWKAJPOI.js';import'../chunk-TPF643LU.js';import'../chunk-L2ZZXECX.js';import'../chunk-CCCYE3XN.js';import'../chunk-JPBW67B3.js';import'../chunk-ZA44REGI.js';import'../chunk-L7N4T2PX.js';import'../chunk-72MN7BNQ.js';import'../chunk-2GX6GB6L.js';var n=class extends a{constructor(e){super(new b(e));}setWasmClient(e){this.unwrap().setWasmClient(e);}};export{n as WasmRuntimeAdapter};
@@ -1,4 +1,4 @@
1
- import { t as RuntimeDevice, D as DeviceStatus } from '../Connection-BGVBMbWg.js';
1
+ import { x as RuntimeDevice, G as DeviceStatus } from '../Connection-U3fEt8_4.js';
2
2
 
3
3
  interface DeviceActiveOptions {
4
4
  now?: number;
@@ -1,8 +1,8 @@
1
- import { c as RuntimeFactoryOptions, b as PlutoRuntimeAssembly } from '../assembly-DGrOqsLW.js';
2
- import { N as NativeProjectionBroker, I as IpcRuntimeAdapter } from '../IpcRuntimeAdapter-DMQoN2XL.js';
3
- import { a0 as Device, Z as ISignalingBackend, U as DiscoveryMode, V as AuthMode, W as SignalingMode, X as ClientOptions, Y as ExplicitFileDataSendParams, ap as BrowserWasmRuntimeModule, a8 as LocalDeviceInfo, $ as RoomMember, aq as BrowserProtocolStore, ar as NamespaceDescriptor, as as IrohMutationReceipt, at as IrohDocEntry, _ as RuntimeIdentity, a3 as SignalingEnvelope, a1 as DeviceStatusSnapshot, n as PeerSessionSnapshot, ab as BackendPeerBiStream, ac as BackendPeerUniStream, ad as PortableMediaPublish, ae as PortableMediaPublicationStart, af as PortableMediaSample, ag as PortableMediaChunk, ah as PortableMediaControl, a2 as ManagedConnectionRecord, q as ResolvedPeerIdentity, b as RoomArchitectureSnapshot, c as RoomAuthorityAssignment, au as CoordinationSignalingStore, av as ManagedRoomMessage, a4 as DeviceEvent, d as TransferPeerDemandRequest, f as TransferPeerDemandStatus, a5 as DesiredPeerProjection, aw as CoreClientBridgeHost, aa as TicketMeshPeerReadiness, ai as NativeConnectParams, aj as NativeConnectResult, a6 as SignalingSession, a7 as SessionEvent, ak as BackendConnectionState } from '../Connection-BGVBMbWg.js';
4
- import { R as RuntimeCapabilities } from '../capabilities-DsKud7Sw.js';
5
- import { R as RuntimeBridgeOptions } from '../DelegatingRuntimeAdapter-JmhmwKTC.js';
1
+ import { c as RuntimeFactoryOptions, b as PlutoRuntimeAssembly } from '../assembly-CtrHmP4j.js';
2
+ import { N as NativeProjectionBroker, I as IpcRuntimeAdapter } from '../IpcRuntimeAdapter-D188hRAr.js';
3
+ import { a5 as Device, a2 as ISignalingBackend, Z as DiscoveryMode, _ as AuthMode, $ as SignalingMode, a0 as ClientOptions, a1 as ExplicitFileDataSendParams, as as BrowserWasmRuntimeModule, ad as LocalDeviceInfo, a4 as RoomMember, at as BrowserProtocolStore, au as NamespaceDescriptor, av as IrohMutationReceipt, aw as IrohDocEntry, a3 as RuntimeIdentity, a8 as SignalingEnvelope, a6 as DeviceStatusSnapshot, r as PeerSessionSnapshot, ag as BackendPeerBiStream, ah as BackendPeerUniStream, ai as PortableMediaPublish, aj as PortableMediaPublicationStart, ak as PortableMediaSample, al as PortableMediaChunk, am as PortableMediaControl, a7 as ManagedConnectionRecord, u as ResolvedPeerIdentity, b as RoomArchitectureSnapshot, c as RoomAuthorityAssignment, ax as CoordinationSignalingStore, ay as ManagedRoomMessage, a9 as DeviceEvent, d as TransferPeerDemandRequest, f as TransferPeerDemandStatus, aa as DesiredPeerProjection, az as CoreClientBridgeHost, af as TicketMeshPeerReadiness, an as NativeConnectParams, ao as NativeConnectResult, ab as SignalingSession, ac as SessionEvent, ap as BackendConnectionState } from '../Connection-U3fEt8_4.js';
4
+ import { R as RuntimeCapabilities } from '../capabilities-Dxb0XOti.js';
5
+ import { R as RuntimeBridgeOptions } from '../DelegatingRuntimeAdapter-Coo5BVM2.js';
6
6
  import { P as PlutoIpcBridge } from '../ipc-DgzKqHH3.js';
7
7
 
8
8
  interface NativeTrustToken {
@@ -1 +1 @@
1
- import {a as a$2}from'../chunk-VARKDQGM.js';import {t}from'../chunk-SADNIMUO.js';import'../chunk-IXQ4KWGP.js';import'../chunk-CQHLD52E.js';import'../chunk-LCJQ7RSR.js';import'../chunk-FPJAUAEU.js';import {a as a$1}from'../chunk-L4HWDDXL.js';import'../chunk-2AAZFBRZ.js';import'../chunk-FNCEVW7G.js';import'../chunk-LB27VQRL.js';import'../chunk-OWKAJPOI.js';import {a}from'../chunk-XXZEDZUU.js';import'../chunk-TPF643LU.js';import'../chunk-72NEEJQG.js';import'../chunk-L2ZZXECX.js';import'../chunk-IUU6JCLK.js';import'../chunk-CCCYE3XN.js';import'../chunk-JPBW67B3.js';import'../chunk-ZA44REGI.js';import'../chunk-L7N4T2PX.js';import'../chunk-72MN7BNQ.js';import'../chunk-2GX6GB6L.js';async function l(e){let t=a$1(e),{WasmBridge:o}=await import('../WasmBridge-CJNESUGJ.js');return a$2(t,new o(t))}function y(e,t$1,o=new a){let m=a$1(e);return a$2(m,new t({...m,bridge:t$1,projectionBroker:o}))}export{y as createIpcClient,l as createWasmClient};
1
+ import {a as a$2}from'../chunk-TSMMRR5V.js';import {t}from'../chunk-M4KL5XZU.js';import'../chunk-IXQ4KWGP.js';import'../chunk-CQHLD52E.js';import'../chunk-LCJQ7RSR.js';import'../chunk-FPJAUAEU.js';import {a as a$1}from'../chunk-WTOA6B2A.js';import'../chunk-2AAZFBRZ.js';import'../chunk-FNCEVW7G.js';import'../chunk-LB27VQRL.js';import'../chunk-OWKAJPOI.js';import {a}from'../chunk-XXZEDZUU.js';import'../chunk-TPF643LU.js';import'../chunk-72NEEJQG.js';import'../chunk-L2ZZXECX.js';import'../chunk-IUU6JCLK.js';import'../chunk-CCCYE3XN.js';import'../chunk-JPBW67B3.js';import'../chunk-ZA44REGI.js';import'../chunk-L7N4T2PX.js';import'../chunk-72MN7BNQ.js';import'../chunk-2GX6GB6L.js';async function l(e){let t=a$1(e),{WasmBridge:o}=await import('../WasmBridge-3HYLCY5Y.js');return a$2(t,new o(t))}function y(e,t$1,o=new a){let m=a$1(e);return a$2(m,new t({...m,bridge:t$1,projectionBroker:o}))}export{y as createIpcClient,l as createWasmClient};
@@ -1,15 +1,15 @@
1
- import { a as PeerReconciliationStats } from '../assembly-DGrOqsLW.js';
2
- export { D as ConnectionActor, d as ConnectionActorError, e as ConnectionActorErrorKind, f as ConnectionActorKey, g as ConnectionActorOptions, h as ConnectionActorState, i as ConnectionActors, j as ConnectionClose, k as ConnectionDial, l as LogicalChannel, P as PolicySnapshot, m as PreferredTransport, n as RUNTIME_POLICY, R as RuntimeClient, o as connectionActorKey, p as connectionActorKeyString, q as getRuntimePolicy } from '../assembly-DGrOqsLW.js';
3
- import { h as Client$1 } from '../coreClient-ByXs38IP.js';
4
- import { c as Avenue } from '../types-Cruu-MsF.js';
5
- import { aI as SignalingOptions, Z as ISignalingBackend, _ as RuntimeIdentity, $ as RoomMember, a3 as SignalingEnvelope, a6 as SignalingSession, a0 as Device, a5 as DesiredPeerProjection, ak as BackendConnectionState, n as PeerSessionSnapshot, aF as AppLimits, N as GrantScope, m as Connection, aJ as JoinRoomOptions, aK as ChannelMetadata, az as CryptoStreams, aL as RoomCreationMode, X as ClientOptions, ay as PayloadCrypto, U as DiscoveryMode, aM as ProtocolCapabilityMap, aN as ScanningLoopOptions, aO as ScanningLoopHandle, aP as RuntimeBootstrapOptions, aQ as RuntimeBootstrapResult, aR as ApplicationPayloadReadinessOptions, aS as ManagedApplicationRouteOptions, aT as PeerState, aU as PeerScope, aV as PeerHealth, aW as ChannelDescriptor, aX as JoinRequest, ai as NativeConnectParams, aj as NativeConnectResult, aG as ConnectionTarget, H as RawConnection } from '../Connection-BGVBMbWg.js';
6
- export { aY as AutoConnectPolicy, aq as BrowserProtocolStore, C as ChannelDescriptor, aZ as ChannelFraming, x as ConnectionEvent, v as ConnectionState, a_ as ConnectionStatus, z as DeviceConnectOptions, a$ as DevicePresence, G as DeviceProfile, D as DeviceStatus, I as IncomingStream, at as IrohDocEntry, as as IrohMutationReceipt, J as JoinRoomOptions, L as LocalDeviceInfo, M as ManagedOptions, y as ManagedSession, ar as NamespaceDescriptor, b0 as PayloadRouteOptions, l as PeerConnectOptions, b1 as PeerLifecycleStatus, o as PeerReadiness, b2 as PeerSessionSnapshot, r as PeerStreamOptions, ag as PortableMediaChunk, ah as PortableMediaControl, ae as PortableMediaPublicationStart, ad as PortableMediaPublish, af as PortableMediaSample, aH as PresenceLoopOptions, b3 as PresencePolicy, w as ReadinessOptions, b4 as RuntimeAuthContext, aD as RuntimeAuthIdentity, Q as RuntimeClientOptions, t as RuntimeDevice, p as RuntimePeerHealth, b5 as RuntimePeerScope, k as RuntimePeerState, K as RuntimeRoomMember, aE as RuntimeSession, s as ScopedChannelOptions, u as ScopedLogicalChannel, b6 as SessionKind, b7 as SessionPlatform, aa as TicketMeshPeerReadiness } from '../Connection-BGVBMbWg.js';
7
- import { R as RuntimeCapabilities } from '../capabilities-DsKud7Sw.js';
8
- export { B as BROWSER_CAPABILITIES, a as CapabilityHost, b as CapabilityMaturity, C as CapabilityProfile, N as NATIVE_CAPABILITIES, c as NativeRuntimeStatus, P as ProductCapabilityMaturity, d as RuntimeAdapterKind, T as TransportStatus, e as browserCapabilities, f as capabilityProfile, g as cloneCapabilities, s as statusCapabilities } from '../capabilities-DsKud7Sw.js';
1
+ import { a as PeerReconciliationStats } from '../assembly-CtrHmP4j.js';
2
+ export { D as ConnectionActor, d as ConnectionActorError, e as ConnectionActorErrorKind, f as ConnectionActorKey, g as ConnectionActorOptions, h as ConnectionActorState, i as ConnectionActors, j as ConnectionClose, k as ConnectionDial, l as LogicalChannel, P as PolicySnapshot, m as PreferredTransport, n as RUNTIME_POLICY, R as RuntimeClient, o as connectionActorKey, p as connectionActorKeyString, q as getRuntimePolicy } from '../assembly-CtrHmP4j.js';
3
+ import { h as Client$1 } from '../coreClient-AVGEwlhT.js';
4
+ import { c as Avenue } from '../types-DvZvz4EL.js';
5
+ import { aL as SignalingOptions, a2 as ISignalingBackend, a3 as RuntimeIdentity, a4 as RoomMember, a8 as SignalingEnvelope, ab as SignalingSession, a5 as Device, aa as DesiredPeerProjection, ap as BackendConnectionState, r as PeerSessionSnapshot, aI as AppLimits, W as GrantScope, q as Connection, aM as JoinRoomOptions, aN as ChannelMetadata, aC as CryptoStreams, aO as RoomCreationMode, a0 as ClientOptions, aB as PayloadCrypto, Z as DiscoveryMode, aP as ProtocolCapabilityMap, aQ as ScanningLoopOptions, aR as ScanningLoopHandle, aS as RuntimeBootstrapOptions, aT as RuntimeBootstrapResult, aU as ApplicationPayloadReadinessOptions, aV as ManagedApplicationRouteOptions, aW as PeerState, aX as PeerScope, aY as PeerHealth, aZ as ChannelDescriptor, a_ as JoinRequest, an as NativeConnectParams, ao as NativeConnectResult, aJ as ConnectionTarget, Q as RawConnection } from '../Connection-U3fEt8_4.js';
6
+ export { a$ as AutoConnectPolicy, at as BrowserProtocolStore, C as ChannelDescriptor, b0 as ChannelFraming, B as ConnectionEvent, z as ConnectionState, b1 as ConnectionStatus, H as DeviceConnectOptions, b2 as DevicePresence, O as DeviceProfile, G as DeviceStatus, I as IncomingStream, aw as IrohDocEntry, av as IrohMutationReceipt, U as JoinRoomOptions, N as LocalDeviceInfo, M as ManagedOptions, F as ManagedSession, au as NamespaceDescriptor, b3 as PayloadRouteOptions, p as PeerConnectOptions, b4 as PeerLifecycleStatus, s as PeerReadiness, b5 as PeerSessionSnapshot, v as PeerStreamOptions, al as PortableMediaChunk, am as PortableMediaControl, aj as PortableMediaPublicationStart, ai as PortableMediaPublish, ak as PortableMediaSample, aK as PresenceLoopOptions, b6 as PresencePolicy, A as ReadinessOptions, b7 as RuntimeAuthContext, aG as RuntimeAuthIdentity, Y as RuntimeClientOptions, x as RuntimeDevice, t as RuntimePeerHealth, b8 as RuntimePeerScope, o as RuntimePeerState, V as RuntimeRoomMember, aH as RuntimeSession, w as ScopedChannelOptions, y as ScopedLogicalChannel, b9 as SessionKind, ba as SessionPlatform, af as TicketMeshPeerReadiness } from '../Connection-U3fEt8_4.js';
7
+ import { R as RuntimeCapabilities } from '../capabilities-Dxb0XOti.js';
8
+ export { B as BROWSER_CAPABILITIES, a as CapabilityHost, b as CapabilityMaturity, C as CapabilityProfile, N as NATIVE_CAPABILITIES, c as NativeRuntimeStatus, P as ProductCapabilityMaturity, d as RuntimeAdapterKind, T as TransportStatus, e as browserCapabilities, f as capabilityProfile, g as cloneCapabilities, s as statusCapabilities } from '../capabilities-Dxb0XOti.js';
9
9
  export { DeviceActiveOptions, isDeviceActive, isDeviceConnectable, isDeviceRoutable } from './device-status.js';
10
- export { a as IpcAdapterOptions, I as IpcRuntimeAdapter } from '../IpcRuntimeAdapter-DMQoN2XL.js';
10
+ export { a as IpcAdapterOptions, I as IpcRuntimeAdapter } from '../IpcRuntimeAdapter-D188hRAr.js';
11
11
  export { P as NativeBridge, N as NativeIpcFailureKind, P as PlutoIpcBridge, a as PlutoIpcUnlisten, c as classifyIpcFailure, i as isIpcUnavailable } from '../ipc-DgzKqHH3.js';
12
- import '../DelegatingRuntimeAdapter-JmhmwKTC.js';
12
+ import '../DelegatingRuntimeAdapter-Coo5BVM2.js';
13
13
 
14
14
  declare class Signaling {
15
15
  private readonly appTag;