openrtc 2.5.2 → 2.5.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (59) hide show
  1. package/dist/{Connection-CTpuImO-.d.ts → Connection-CovQdc8E.d.ts} +30 -5
  2. package/dist/{DelegatingRuntimeAdapter-D67Ozqo3.d.ts → DelegatingRuntimeAdapter-3ykiNvyh.d.ts} +3 -2
  3. package/dist/{IpcRuntimeAdapter-Ddx0MtSI.d.ts → IpcRuntimeAdapter-BkM_1HyL.d.ts} +12 -2
  4. package/dist/WasmBridge-UZC7G4NP.js +1 -0
  5. package/dist/{assembly-LOFcpH3S.d.ts → assembly-C235UKSS.d.ts} +3 -2
  6. package/dist/{capabilities-CmzzxSvW.d.ts → capabilities-CdZpAKvE.d.ts} +1 -1
  7. package/dist/chunk-25CN4MLA.js +2 -0
  8. package/dist/chunk-2ESWBXLF.js +1 -0
  9. package/dist/{chunk-TZLNKQNJ.js → chunk-42TNJH5S.js} +1 -1
  10. package/dist/chunk-4CC6YIGG.js +1 -0
  11. package/dist/chunk-4J4F32QT.js +1 -0
  12. package/dist/{chunk-J7NBMQQA.js → chunk-CHT46RA7.js} +1 -1
  13. package/dist/chunk-VC7TGJFS.js +2 -0
  14. package/dist/{chunk-EFTDXE6M.js → chunk-WMA4OMJL.js} +1 -1
  15. package/dist/{chunk-XTYALGJN.js → chunk-XMYBBLYK.js} +1 -1
  16. package/dist/coreClient.d.ts +3 -3
  17. package/dist/coreClient.js +1 -1
  18. package/dist/index.d.ts +5 -5
  19. package/dist/index.js +1 -1
  20. package/dist/ipcFactory-2WMR4PH6.js +1 -0
  21. package/dist/native.d.ts +5 -5
  22. package/dist/native.js +1 -1
  23. package/dist/node.d.ts +5 -5
  24. package/dist/node.js +2 -2
  25. package/dist/{openrtc-SQF7H4ZE.js → openrtc-UBIKDAZ5.js} +2 -2
  26. package/dist/openrtc_bg.wasm +0 -0
  27. package/dist/{room-A2FMQRNZ.js → room-2MUFAJ4M.js} +1 -1
  28. package/dist/runtime/WasmRuntimeAdapter.d.ts +3 -3
  29. package/dist/runtime/WasmRuntimeAdapter.js +1 -1
  30. package/dist/runtime/device-status.d.ts +1 -1
  31. package/dist/runtime/factories.d.ts +6 -5
  32. package/dist/runtime/factories.js +1 -1
  33. package/dist/runtime/index.d.ts +9 -9
  34. package/dist/runtime/index.js +1 -1
  35. package/dist/server-browser.d.ts +4 -4
  36. package/dist/server.d.ts +4 -4
  37. package/dist/server.js +1 -1
  38. package/dist/service-node.d.ts +4 -4
  39. package/dist/service-node.js +1 -1
  40. package/dist/testing/native.d.ts +4 -4
  41. package/dist/testing/native.js +1 -1
  42. package/dist/testing.d.ts +4 -4
  43. package/dist/testing.js +1 -1
  44. package/dist/transport/index.d.ts +2 -2
  45. package/dist/{types-Cyc-mPjk.d.ts → types-C6SMXBzJ.d.ts} +1 -1
  46. package/native/darwin-arm64/openrtc-node-host +0 -0
  47. package/native/darwin-arm64/openrtc-node-host.manifest.json +4 -4
  48. package/native/darwin-x64/openrtc-node-host +0 -0
  49. package/native/darwin-x64/openrtc-node-host.manifest.json +4 -4
  50. package/native/linux-x64/openrtc-node-host +0 -0
  51. package/native/linux-x64/openrtc-node-host.manifest.json +4 -4
  52. package/package.json +1 -1
  53. package/dist/WasmBridge-LWMCETW4.js +0 -1
  54. package/dist/chunk-6Q2LAXM4.js +0 -1
  55. package/dist/chunk-AAZPQQXX.js +0 -2
  56. package/dist/chunk-FB5M6GIW.js +0 -2
  57. package/dist/chunk-PLIWPC45.js +0 -1
  58. package/dist/chunk-VTYVIKTM.js +0 -1
  59. package/dist/ipcFactory-PDVLUG2W.js +0 -1
@@ -1 +1 @@
1
- import {r}from'./chunk-FB5M6GIW.js';import {a}from'./chunk-AAZPQQXX.js';function v(i,d){let t=new r(i,d),a$1=i.spaceKey??i.space,l=(i.discoveryMode===void 0||i.discoveryMode==="space")&&typeof i.apiKey=="string"&&i.apiKey.trim().length>0&&typeof a$1=="string"&&a$1.trim().length>0,o={runtime:t,async setAuthContext(e){await t.setAuthContext(e);},async syncPlutoAuth(e){if(l)return;let n=a(),c=n.getCurrentUser(),r=(typeof e?.userId=="string"?e.userId.trim():"")||c?.uid||null;if(!r){await o.setAuthContext(null);return}let m=await n.getIdToken({forceRefresh:e?.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=a();return o.syncPlutoAuth({userId:e.getCurrentUser()?.uid??null,forceRefresh:false}),e.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 {r}from'./chunk-VC7TGJFS.js';import {a}from'./chunk-25CN4MLA.js';function v(i,d){let t=new r(i,d),a$1=i.spaceKey??i.space,l=(i.discoveryMode===void 0||i.discoveryMode==="space")&&typeof i.apiKey=="string"&&i.apiKey.trim().length>0&&typeof a$1=="string"&&a$1.trim().length>0,o={runtime:t,async setAuthContext(e){await t.setAuthContext(e);},async syncPlutoAuth(e){if(l)return;let n=a(),c=n.getCurrentUser(),r=(typeof e?.userId=="string"?e.userId.trim():"")||c?.uid||null;if(!r){await o.setAuthContext(null);return}let m=await n.getIdToken({forceRefresh:e?.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=a();return o.syncPlutoAuth({userId:e.getCurrentUser()?.uid??null,forceRefresh:false}),e.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,2 +1,2 @@
1
- import {d}from'./chunk-OWKAJPOI.js';import {a as a$1,d as d$1,c}from'./chunk-2GX6GB6L.js';var v=new Set;function p(e,t){v.has(e)||(v.add(e),console.warn(t));}function x(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 x(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 P(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"?P(e.storagePrefix):"";return t||P(u(e))||"default"}var M={devicesPerUser:100,maxRooms:1e4,maxMembersPerRoom:50,maxPersonalDevices:25e3},G=M;var T=[{urls:"stun:stun.l.google.com:19302"},{urls:"stun:stun.cloudflare.com:3478"}],f={iceServers:T};var A=/^[A-Za-z0-9._-]+$/,O="[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 z(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 W(e,t){let r=e instanceof Error?`${e.name}: ${e.message}`:String(e),n=t?.trim();return n?r.split(n).join(O):r}var h=[...d];function g(e){let t=e.spaceKey??e.space;return {...e,...t!==void 0?{spaceKey:t}:{}}}function C(e){return {...e,iceServers:e.iceServers?e.iceServers.map(t=>({...t})):e.iceServers}}function D(e){return {...e}}function w(e){return {...e}}function k(e){if(e)return {iroh:typeof e.iroh=="object"?w(e.iroh):e.iroh,webrtc:typeof e.webrtc=="object"?C(e.webrtc):e.webrtc,ble:typeof e.ble=="object"?{...e.ble}:e.ble,moq:typeof e.moq=="object"?D(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=C(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=S(o),y=(o.discoveryMode??"space")==="space"?"client-open":"client-auth";return {appTag:r,authMode:n,configuredPersistenceMode:s,options:o,roomCreationMode:y}}function S(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:S(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)}}
1
+ import {d}from'./chunk-OWKAJPOI.js';import {a as a$1,d as d$1,c}from'./chunk-2GX6GB6L.js';var v=new Set;function p(e,t){v.has(e)||(v.add(e),console.warn(t));}function x(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 x(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 P(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"?P(e.storagePrefix):"";return t||P(u(e))||"default"}var M={devicesPerUser:100,maxRooms:1e4,maxMembersPerRoom:50,maxPersonalDevices:25e3},G=M;var T=[{urls:"stun:stun.l.google.com:19302"},{urls:"stun:stun.cloudflare.com:3478"}],f={iceServers:T};var A=/^[A-Za-z0-9._-]+$/,O="[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 z(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 W(e,t){let r=e instanceof Error?`${e.name}: ${e.message}`:String(e),n=t?.trim();return n?r.split(n).join(O):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 D(e){return {...e}}function w(e){return {...e}}function k(e){if(e)return {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"?D(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
2
  export{oe as a,F as b,u as c,a as d,K as e,j as f,G as g,T as h,f as i,z as j,W as k,g as l,Z as m,ee as n,te as o};
@@ -1,6 +1,6 @@
1
- import { P as PolicySnapshot, a as PeerReconciliationStats, R as RuntimeClient, b as PlutoRuntimeAssembly } from './assembly-LOFcpH3S.js';
2
- import { h as RuntimePeerState, i as PeerConnectOptions, j as Connection, k as PeerSessionSnapshot, l as PeerReadiness, m as RuntimePeerHealth, n as ResolvedPeerIdentity, C as ChannelDescriptor, o as PeerStreamOptions, I as IncomingStream, S as ScopedChannelOptions, p as RuntimeDevice, q as ScopedLogicalChannel, r as ConnectionState, s as ReadinessOptions, t as ConnectionEvent, M as ManagedOptions, u as ManagedSession, D as DeviceStatus, v as DeviceConnectOptions, w as ConnectDeviceResult, x as ConnectDeviceHooks, y as ConnectDeviceOptions, L as LocalDeviceInfo, z as DeviceProfile, A as RawConnection, J as JoinRoomOptions, B as RuntimeRoomMember, G as GrantScope, F as AuthContext, H as RuntimeClientOptions } from './Connection-CTpuImO-.js';
3
- import { R as RuntimeCapabilities, C as CapabilityProfile } from './capabilities-CmzzxSvW.js';
1
+ import { P as PolicySnapshot, a as PeerReconciliationStats, R as RuntimeClient, b as PlutoRuntimeAssembly } from './assembly-C235UKSS.js';
2
+ import { h as RuntimePeerState, i as PeerConnectOptions, j as Connection, k as PeerSessionSnapshot, l as PeerReadiness, m as RuntimePeerHealth, n as ResolvedPeerIdentity, C as ChannelDescriptor, o as PeerStreamOptions, I as IncomingStream, S as ScopedChannelOptions, p as RuntimeDevice, q as ScopedLogicalChannel, r as ConnectionState, s as ReadinessOptions, t as ConnectionEvent, M as ManagedOptions, u as ManagedSession, D as DeviceStatus, v as DeviceConnectOptions, w as ConnectDeviceResult, x as ConnectDeviceHooks, y as ConnectDeviceOptions, L as LocalDeviceInfo, z as DeviceProfile, A as RawConnection, J as JoinRoomOptions, B as RuntimeRoomMember, G as GrantScope, F as AuthContext, H as RuntimeClientOptions } from './Connection-CovQdc8E.js';
3
+ import { R as RuntimeCapabilities, C as CapabilityProfile } from './capabilities-CdZpAKvE.js';
4
4
 
5
5
  type ChannelConnectOptions = Omit<ScopedChannelOptions, 'scope' | 'deviceId' | 'ticket'> & {
6
6
  /**
@@ -1 +1 @@
1
- import {l}from'./chunk-XTYALGJN.js';import'./chunk-OWKAJPOI.js';import'./chunk-2GX6GB6L.js';function I(o){let s=l({...o});if("auth"in o&&!o.authMode){let n=o.auth;s.authMode=n==="none"?"anonymous":n;}if("identity"in o){let n=o.identity,r=n==="temporary"?"ephemeral":n;!o.deviceIdPersistence&&!o.nodeIdPersistence&&(s.deviceIdPersistence=r),!o.endpointIdPersistence&&!o.nodeIdPersistence&&(s.endpointIdPersistence=r);}return "namespace"in o&&!o.storagePrefix&&(s.storagePrefix=o.namespace),"privacy"in o&&o.strictMode===void 0&&(s.strictMode=!!o.privacy),s}function D(o,s){let n=o.runtime,r=Object.create(n),d=async e=>{if(typeof e!="string")return e;let i=(await n.listDevices()).find(c=>c.deviceId===e);if(!i)throw new Error(`OpenRTC device '${e}' is not currently discoverable.`);return i},u=async e=>({...e,localDeviceId:e?.localDeviceId??await n.getLocalDeviceId()??""}),g=async e=>{let{device:t,scope:i,...c}=e,a=c.deviceId??(typeof t=="string"?t:t?.deviceId)??null,l=c.ticket??(typeof t=="string"?void 0:t?.ticket);a&&!l&&(l=(await d(a).catch(()=>null))?.ticket);let m={...c,scope:i??"session"};return a&&(m.deviceId=a),l&&(m.ticket=l),m},v={list:()=>n.listDevices(),startSession:(e={})=>n.startManagedSession({...e,platform:e.platform??s}),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 u(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)},P={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()},C={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 g(e)),connectScoped:e=>n.connectScopedChannel(e)},h={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)},S={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={status:()=>n.getRuntimeStatus(),policy:()=>n.getRuntimePolicy(),capabilities:()=>n.capabilities(),capabilityProfile:()=>n.getCapabilityProfile(),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()},f={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(r,{devices:{get:()=>v,enumerable:true},peers:{get:()=>P,enumerable:true},channels:{get:()=>C,enumerable:true},rooms:{get:()=>h,enumerable:true},tickets:{get:()=>S,enumerable:true},diagnostics:{get:()=>b,enumerable:true},advanced:{get:()=>f,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}}),r}export{I as resolveOptions,D as wrapAssembly};
1
+ import {l}from'./chunk-XMYBBLYK.js';import'./chunk-OWKAJPOI.js';import'./chunk-2GX6GB6L.js';function I(o){let s=l({...o});if("auth"in o&&!o.authMode){let n=o.auth;s.authMode=n==="none"?"anonymous":n;}if("identity"in o){let n=o.identity,r=n==="temporary"?"ephemeral":n;!o.deviceIdPersistence&&!o.nodeIdPersistence&&(s.deviceIdPersistence=r),!o.endpointIdPersistence&&!o.nodeIdPersistence&&(s.endpointIdPersistence=r);}return "namespace"in o&&!o.storagePrefix&&(s.storagePrefix=o.namespace),"privacy"in o&&o.strictMode===void 0&&(s.strictMode=!!o.privacy),s}function D(o,s){let n=o.runtime,r=Object.create(n),d=async e=>{if(typeof e!="string")return e;let i=(await n.listDevices()).find(c=>c.deviceId===e);if(!i)throw new Error(`OpenRTC device '${e}' is not currently discoverable.`);return i},u=async e=>({...e,localDeviceId:e?.localDeviceId??await n.getLocalDeviceId()??""}),g=async e=>{let{device:t,scope:i,...c}=e,a=c.deviceId??(typeof t=="string"?t:t?.deviceId)??null,l=c.ticket??(typeof t=="string"?void 0:t?.ticket);a&&!l&&(l=(await d(a).catch(()=>null))?.ticket);let m={...c,scope:i??"session"};return a&&(m.deviceId=a),l&&(m.ticket=l),m},v={list:()=>n.listDevices(),startSession:(e={})=>n.startManagedSession({...e,platform:e.platform??s}),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 u(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)},P={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()},C={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 g(e)),connectScoped:e=>n.connectScopedChannel(e)},h={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)},S={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={status:()=>n.getRuntimeStatus(),policy:()=>n.getRuntimePolicy(),capabilities:()=>n.capabilities(),capabilityProfile:()=>n.getCapabilityProfile(),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()},f={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(r,{devices:{get:()=>v,enumerable:true},peers:{get:()=>P,enumerable:true},channels:{get:()=>C,enumerable:true},rooms:{get:()=>h,enumerable:true},tickets:{get:()=>S,enumerable:true},diagnostics:{get:()=>b,enumerable:true},advanced:{get:()=>f,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}}),r}export{I as resolveOptions,D as wrapAssembly};
package/dist/index.d.ts CHANGED
@@ -1,10 +1,10 @@
1
1
  import { P as PlutoIpcBridge } from './ipc-DgzKqHH3.js';
2
- import { O as Options, C as Client } from './types-Cyc-mPjk.js';
3
- export { a as AttestationProvider, b as AuthProvider, c as Avenue, e as BroadcastGrant, i as BroadcastPublisher, j as BroadcastRole, k as BroadcastSession, l as BroadcastSource, m as BroadcastState, n as BroadcastStats, o as BroadcastTrackEvent, p as Channel, r as Connection, s as DeviceOptions, t as DeviceProfile, u as Devices, E as EnrolledDevice, N as Offline, P as OfflineAssurance, Q as OfflineEnrollmentRequest, R as OfflineRuntimeSupport, X as Room, Y as RoomOptions, $ as Space, a0 as SpaceOptions, a1 as State, a2 as Ticket, a3 as TicketOptions, a4 as Transports, a6 as UsageUpdate, a7 as UsageWarning } from './types-Cyc-mPjk.js';
2
+ import { O as Options, C as Client } from './types-C6SMXBzJ.js';
3
+ export { a as AttestationProvider, b as AuthProvider, c as Avenue, e as BroadcastGrant, i as BroadcastPublisher, j as BroadcastRole, k as BroadcastSession, l as BroadcastSource, m as BroadcastState, n as BroadcastStats, o as BroadcastTrackEvent, p as Channel, r as Connection, s as DeviceOptions, t as DeviceProfile, u as Devices, E as EnrolledDevice, N as Offline, P as OfflineAssurance, Q as OfflineEnrollmentRequest, R as OfflineRuntimeSupport, X as Room, Y as RoomOptions, $ as Space, a0 as SpaceOptions, a1 as State, a2 as Ticket, a3 as TicketOptions, a4 as Transports, a6 as UsageUpdate, a7 as UsageWarning } from './types-C6SMXBzJ.js';
4
4
  import './coreClient.js';
5
- import './assembly-LOFcpH3S.js';
6
- import './Connection-CTpuImO-.js';
7
- import './capabilities-CmzzxSvW.js';
5
+ import './assembly-C235UKSS.js';
6
+ import './Connection-CovQdc8E.js';
7
+ import './capabilities-CdZpAKvE.js';
8
8
 
9
9
  /**
10
10
  * 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-VFDCIEP6.js';import {a}from'./chunk-VTYVIKTM.js';import {d}from'./chunk-72NEEJQG.js';import'./chunk-NDR2ANQB.js';import {i}from'./chunk-TZLNKQNJ.js';import'./chunk-ZA44REGI.js';import'./chunk-LLZT3MR6.js';import'./chunk-DUY34MGT.js';import'./chunk-CCCYE3XN.js';export{a as ERROR_CODES,b as RTCError,e as classifyError,d as createError,c as projectError}from'./chunk-N6LGTNUI.js';import'./chunk-JPBW67B3.js';import'./chunk-2GX6GB6L.js';function y(a){return i(a,{platform:"web",broadcastHostFactory:async e=>{let[{BrowserManagedBroadcastHost:o},{loadBrowserWasmRuntimeModule:t}]=await Promise.all([import('./BrowserManagedBroadcastHost-ARCP5MGJ.js'),import('./WasmBridge-LWMCETW4.js')]),r=t().then(async n=>(await n.initWasm(),n.start(),new n.WasmClient(e.apiKey)));return new o({resolve:e.resolve,manage:e.manage,deviceId:e.deviceId,defaultAuth:e.defaultAuth,loadWasm:()=>r})},runtimeFactory:async e=>{let{createWasmClient:o}=await import('./runtime/factories.js');return o(e)}})}y.native=function(a$2,e=d()){let o=new a;return i(a$2,{platform:"native",broadcastHostFactory:async t=>{let{NativeManagedBroadcastHost:r}=await import('./NativeManagedBroadcastHost-WCQ6TPUU.js');return new r(e,t)},offlineSupport:()=>e.invoke("openrtc_offline_runtime_support"),createOfflineEnrollmentRequest:async t=>{let r=await e.invoke("start_iroh_node");return e.invoke("openrtc_create_offline_enrollment_request",{trustDomain:t.trustDomain,deviceId:t.deviceId,endpointId:r,enrollmentNonce:crypto.randomUUID(),requestedRoles:t.requestedRoles})},close:()=>o.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:r}=await import('./ipcFactory-PDVLUG2W.js');return r(t,e,o)}})};export{y as OpenRTC};
1
+ import {a as a$1}from'./chunk-VFDCIEP6.js';import {a}from'./chunk-4J4F32QT.js';import {d}from'./chunk-72NEEJQG.js';import'./chunk-NDR2ANQB.js';import {i}from'./chunk-42TNJH5S.js';import'./chunk-ZA44REGI.js';import'./chunk-LLZT3MR6.js';import'./chunk-DUY34MGT.js';import'./chunk-CCCYE3XN.js';export{a as ERROR_CODES,b as RTCError,e as classifyError,d as createError,c as projectError}from'./chunk-N6LGTNUI.js';import'./chunk-JPBW67B3.js';import'./chunk-2GX6GB6L.js';function y(a){return i(a,{platform:"web",broadcastHostFactory:async e=>{let[{BrowserManagedBroadcastHost:o},{loadBrowserWasmRuntimeModule:t}]=await Promise.all([import('./BrowserManagedBroadcastHost-ARCP5MGJ.js'),import('./WasmBridge-UZC7G4NP.js')]),r=t().then(async n=>(await n.initWasm(),n.start(),new n.WasmClient(e.apiKey)));return new o({resolve:e.resolve,manage:e.manage,deviceId:e.deviceId,defaultAuth:e.defaultAuth,loadWasm:()=>r})},runtimeFactory:async e=>{let{createWasmClient:o}=await import('./runtime/factories.js');return o(e)}})}y.native=function(a$2,e=d()){let o=new a;return i(a$2,{platform:"native",broadcastHostFactory:async t=>{let{NativeManagedBroadcastHost:r}=await import('./NativeManagedBroadcastHost-WCQ6TPUU.js');return new r(e,t)},offlineSupport:()=>e.invoke("openrtc_offline_runtime_support"),createOfflineEnrollmentRequest:async t=>{let r=await e.invoke("start_iroh_node");return e.invoke("openrtc_create_offline_enrollment_request",{trustDomain:t.trustDomain,deviceId:t.deviceId,endpointId:r,enrollmentNonce:crypto.randomUUID(),requestedRoles:t.requestedRoles})},close:()=>o.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:r}=await import('./ipcFactory-2WMR4PH6.js');return r(t,e,o)}})};export{y as OpenRTC};
@@ -0,0 +1 @@
1
+ import {a as a$2}from'./chunk-WMA4OMJL.js';import {s}from'./chunk-VC7TGJFS.js';import'./chunk-BGWJHPBC.js';import'./chunk-4CC6YIGG.js';import'./chunk-25CN4MLA.js';import {a as a$1}from'./chunk-XMYBBLYK.js';import'./chunk-TYZS5LXQ.js';import'./chunk-OT7IPLZE.js';import'./chunk-OWKAJPOI.js';import {a}from'./chunk-4J4F32QT.js';import'./chunk-72NEEJQG.js';import'./chunk-CNAW5BZ3.js';import'./chunk-DUY34MGT.js';import'./chunk-CCCYE3XN.js';import'./chunk-N6LGTNUI.js';import'./chunk-JPBW67B3.js';import'./chunk-2GX6GB6L.js';function l(p,n,m=new a){let t=a$1(p);return a$2(t,new s({...t,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-Cyc-mPjk.js';
2
- export { A as AccessMode, a as AttestationProvider, b as AuthProvider, c as Avenue, B as BotVerificationProvider, d as BroadcastCreateOptions, e as BroadcastGrant, f as BroadcastInvite, g as BroadcastInviteOptions, h as BroadcastMedia, i as BroadcastPublisher, j as BroadcastRole, k as BroadcastSession, l as BroadcastSource, m as BroadcastState, n as BroadcastStats, o as BroadcastTrackEvent, p as Channel, q as Channels, r as Connection, D as Delivery, s as DeviceOptions, t as DeviceProfile, u as Devices, E as EnrolledDevice, I as IncomingPeerBidirectionalStream, v as IncomingPeerUnidirectionalStream, M as MediaConnection, w as MediaIncomingDemuxStats, x as MediaKind, y as MediaLatencySummary, z as MediaReceiver, F as MediaReceiverStats, G as MediaSender, H as MediaSenderStats, J as MediaStats, K as MediaTrackEvent, L as MediaTrackOptions, N as Offline, P as OfflineAssurance, Q as OfflineEnrollmentRequest, R as OfflineRuntimeSupport, S as PeerBidirectionalStream, T as PeerDatagramDuplexStream, U as PeerDatagramStats, V as PeerStreamOptions, W as PeerStreamTransport, X as Room, Y as RoomOptions, Z as RoomUsageEstimate, _ as RoomUsageEstimateInput, $ as Space, a0 as SpaceOptions, a1 as State, a2 as Ticket, a3 as TicketOptions, a4 as Transports, a5 as Usage, a6 as UsageUpdate, a7 as UsageWarning } from './types-Cyc-mPjk.js';
1
+ import { O as Options, C as Client } from './types-C6SMXBzJ.js';
2
+ export { A as AccessMode, a as AttestationProvider, b as AuthProvider, c as Avenue, B as BotVerificationProvider, d as BroadcastCreateOptions, e as BroadcastGrant, f as BroadcastInvite, g as BroadcastInviteOptions, h as BroadcastMedia, i as BroadcastPublisher, j as BroadcastRole, k as BroadcastSession, l as BroadcastSource, m as BroadcastState, n as BroadcastStats, o as BroadcastTrackEvent, p as Channel, q as Channels, r as Connection, D as Delivery, s as DeviceOptions, t as DeviceProfile, u as Devices, E as EnrolledDevice, I as IncomingPeerBidirectionalStream, v as IncomingPeerUnidirectionalStream, M as MediaConnection, w as MediaIncomingDemuxStats, x as MediaKind, y as MediaLatencySummary, z as MediaReceiver, F as MediaReceiverStats, G as MediaSender, H as MediaSenderStats, J as MediaStats, K as MediaTrackEvent, L as MediaTrackOptions, N as Offline, P as OfflineAssurance, Q as OfflineEnrollmentRequest, R as OfflineRuntimeSupport, S as PeerBidirectionalStream, T as PeerDatagramDuplexStream, U as PeerDatagramStats, V as PeerStreamOptions, W as PeerStreamTransport, X as Room, Y as RoomOptions, Z as RoomUsageEstimate, _ as RoomUsageEstimateInput, $ as Space, a0 as SpaceOptions, a1 as State, a2 as Ticket, a3 as TicketOptions, a4 as Transports, a5 as Usage, a6 as UsageUpdate, a7 as UsageWarning } from './types-C6SMXBzJ.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 } from './Connection-CTpuImO-.js';
4
+ export { E as EffectiveRoomArchitecture, R as RoomArchitectureMode, a as RoomArchitectureReason, b as RoomArchitectureSnapshot, c as RoomAuthorityAssignment } from './Connection-CovQdc8E.js';
5
5
  import './coreClient.js';
6
- import './assembly-LOFcpH3S.js';
7
- import './capabilities-CmzzxSvW.js';
6
+ import './assembly-C235UKSS.js';
7
+ import './capabilities-CdZpAKvE.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 as a$1}from'./chunk-VFDCIEP6.js';import {a}from'./chunk-VTYVIKTM.js';import {d}from'./chunk-72NEEJQG.js';import'./chunk-NDR2ANQB.js';import {i}from'./chunk-TZLNKQNJ.js';import'./chunk-ZA44REGI.js';import'./chunk-LLZT3MR6.js';import'./chunk-DUY34MGT.js';import'./chunk-CCCYE3XN.js';import'./chunk-N6LGTNUI.js';import'./chunk-JPBW67B3.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-WCQ6TPUU.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-PDVLUG2W.js');return o(e,t,r)}})}export{u as OpenRTC};
1
+ import {a as a$1}from'./chunk-VFDCIEP6.js';import {a}from'./chunk-4J4F32QT.js';import {d}from'./chunk-72NEEJQG.js';import'./chunk-NDR2ANQB.js';import {i}from'./chunk-42TNJH5S.js';import'./chunk-ZA44REGI.js';import'./chunk-LLZT3MR6.js';import'./chunk-DUY34MGT.js';import'./chunk-CCCYE3XN.js';import'./chunk-N6LGTNUI.js';import'./chunk-JPBW67B3.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-WCQ6TPUU.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-2WMR4PH6.js');return o(e,t,r)}})}export{u as OpenRTC};
package/dist/node.d.ts CHANGED
@@ -1,11 +1,11 @@
1
- import { O as Options, C as Client } from './types-Cyc-mPjk.js';
2
- export { A as AccessMode, a as AttestationProvider, b as AuthProvider, c as Avenue, B as BotVerificationProvider, d as BroadcastCreateOptions, e as BroadcastGrant, f as BroadcastInvite, g as BroadcastInviteOptions, h as BroadcastMedia, i as BroadcastPublisher, j as BroadcastRole, k as BroadcastSession, l as BroadcastSource, m as BroadcastState, n as BroadcastStats, o as BroadcastTrackEvent, p as Channel, q as Channels, r as Connection, D as Delivery, s as DeviceOptions, t as DeviceProfile, u as Devices, E as EnrolledDevice, I as IncomingPeerBidirectionalStream, v as IncomingPeerUnidirectionalStream, M as MediaConnection, w as MediaIncomingDemuxStats, x as MediaKind, y as MediaLatencySummary, z as MediaReceiver, F as MediaReceiverStats, G as MediaSender, H as MediaSenderStats, J as MediaStats, K as MediaTrackEvent, L as MediaTrackOptions, N as Offline, P as OfflineAssurance, Q as OfflineEnrollmentRequest, R as OfflineRuntimeSupport, S as PeerBidirectionalStream, T as PeerDatagramDuplexStream, U as PeerDatagramStats, V as PeerStreamOptions, W as PeerStreamTransport, X as Room, Y as RoomOptions, Z as RoomUsageEstimate, _ as RoomUsageEstimateInput, $ as Space, a0 as SpaceOptions, a1 as State, a2 as Ticket, a3 as TicketOptions, a4 as Transports, a5 as Usage, a6 as UsageUpdate, a7 as UsageWarning } from './types-Cyc-mPjk.js';
1
+ import { O as Options, C as Client } from './types-C6SMXBzJ.js';
2
+ export { A as AccessMode, a as AttestationProvider, b as AuthProvider, c as Avenue, B as BotVerificationProvider, d as BroadcastCreateOptions, e as BroadcastGrant, f as BroadcastInvite, g as BroadcastInviteOptions, h as BroadcastMedia, i as BroadcastPublisher, j as BroadcastRole, k as BroadcastSession, l as BroadcastSource, m as BroadcastState, n as BroadcastStats, o as BroadcastTrackEvent, p as Channel, q as Channels, r as Connection, D as Delivery, s as DeviceOptions, t as DeviceProfile, u as Devices, E as EnrolledDevice, I as IncomingPeerBidirectionalStream, v as IncomingPeerUnidirectionalStream, M as MediaConnection, w as MediaIncomingDemuxStats, x as MediaKind, y as MediaLatencySummary, z as MediaReceiver, F as MediaReceiverStats, G as MediaSender, H as MediaSenderStats, J as MediaStats, K as MediaTrackEvent, L as MediaTrackOptions, N as Offline, P as OfflineAssurance, Q as OfflineEnrollmentRequest, R as OfflineRuntimeSupport, S as PeerBidirectionalStream, T as PeerDatagramDuplexStream, U as PeerDatagramStats, V as PeerStreamOptions, W as PeerStreamTransport, X as Room, Y as RoomOptions, Z as RoomUsageEstimate, _ as RoomUsageEstimateInput, $ as Space, a0 as SpaceOptions, a1 as State, a2 as Ticket, a3 as TicketOptions, a4 as Transports, a5 as Usage, a6 as UsageUpdate, a7 as UsageWarning } from './types-C6SMXBzJ.js';
3
3
  import { P as PlutoIpcBridge } from './ipc-DgzKqHH3.js';
4
4
  import { AuthorityAssignmentInput, AuthorityInterestAssignment } from './service-node.js';
5
- export { E as EffectiveRoomArchitecture, R as RoomArchitectureMode, a as RoomArchitectureReason, b as RoomArchitectureSnapshot, c as RoomAuthorityAssignment } from './Connection-CTpuImO-.js';
5
+ export { E as EffectiveRoomArchitecture, R as RoomArchitectureMode, a as RoomArchitectureReason, b as RoomArchitectureSnapshot, c as RoomAuthorityAssignment } from './Connection-CovQdc8E.js';
6
6
  import './coreClient.js';
7
- import './assembly-LOFcpH3S.js';
8
- import './capabilities-CmzzxSvW.js';
7
+ import './assembly-C235UKSS.js';
8
+ import './capabilities-CdZpAKvE.js';
9
9
 
10
10
  interface NodeServiceNodeOptions {
11
11
  apiKey: string;
package/dist/node.js CHANGED
@@ -1,2 +1,2 @@
1
- import {a as a$1}from'./chunk-VFDCIEP6.js';import {a}from'./chunk-VTYVIKTM.js';import {c}from'./chunk-72NEEJQG.js';import'./chunk-NDR2ANQB.js';import {i,b as b$1,a as a$2}from'./chunk-TZLNKQNJ.js';import'./chunk-ZA44REGI.js';import'./chunk-LLZT3MR6.js';import'./chunk-DUY34MGT.js';import'./chunk-CCCYE3XN.js';import'./chunk-N6LGTNUI.js';import'./chunk-JPBW67B3.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 N=1,M=24*1024,H=96*1024,I=128*1024,C=64*1024,W=256,Z=256,x=3e4,ee=/^[A-Za-z0-9_.:@-]+$/,te=/(?:^|_)(?:SECRET|TOKEN|PASSWORD|PRIVATE(?:_KEY)?|CREDENTIALS?)(?:_|$)/i,oe=1;function re(o){return Buffer.from(JSON.stringify({schema:o.schema,kind:o.kind,platform:o.platform,arch:o.arch,rustTarget:o.rustTarget,sourceCommit:o.sourceCommit,sourceDigest:o.sourceDigest,binarySha256:o.binarySha256,protocol:o.protocol,signingKeySha256:o.signingKeySha256,signatureAlgorithm:o.signatureAlgorithm}),"utf8")}async function ne(o,e,t){let[r,n,s]=await Promise.all([readFile(t),readFile(resolve(e,"openrtc-node-host.manifest.json")),readFile(resolve(o,"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 c=u=>createHash("sha256").update(u).digest("hex"),l={"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&&l!==void 0&&i.schema===oe&&i.kind==="openrtc-node-host"&&i.platform===process.platform&&i.arch===process.arch&&i.rustTarget===l&&/^[0-9a-f]{40}$/.test(i.sourceCommit)&&/^[0-9a-f]{64}$/.test(i.sourceDigest)&&i.binarySha256===c(r)&&i.signingKeySha256===c(s)&&i.signatureAlgorithm==="ed25519"&&/^[A-Za-z0-9+/]{86}==$/.test(i.signature)&&verify(null,re(i),s,Buffer.from(i.signature,"base64"))))throw new Error("[OpenRTC] Packaged Node host provenance verification failed.")}function $(o){return Object.fromEntries(Object.entries(process.env).filter(([e,t])=>!te.test(e)&&(!o||!t?.includes(o))))}function m(o,e){queueMicrotask(()=>{try{o(e);}catch{try{process.emitWarning("[OpenRTC] ServiceNode callback failed.",{code:"OPENRTC_SERVICE_CALLBACK"});}catch{}}});}function G(o){let e=/^\d{1,20}$/;return typeof o.transportStableId!="string"||!e.test(o.transportStableId)||!e.test(o.transportGeneration)||!e.test(o.routeGeneration)?null:{transportStableId:o.transportStableId,transportGeneration:o.transportGeneration,routeGeneration:o.routeGeneration}}function ie(o,e){return o.transportStableId===e.transportStableId&&o.transportGeneration===e.transportGeneration&&o.routeGeneration===e.routeGeneration}function f(o,e,t=160){let r=o.trim();if(!r||r.length>t||!ee.test(r))throw new TypeError(`[OpenRTC] ${e} is invalid.`);return r}function v(o,e,t=Number.MAX_SAFE_INTEGER){if(!Number.isSafeInteger(o)||o<1||o>t)throw new RangeError(`[OpenRTC] ${e} must be a positive safe integer.`);return o}function se(o){if(!/^pk_(?:live|test)_[A-Za-z0-9]+$/.test(o.apiKey))throw new TypeError("[OpenRTC] apiKey is invalid.");if(!/^sk_(?:live|test)_[A-Za-z0-9_-]+$/.test(o.secretKey)||o.secretKey.length>128)throw new TypeError("[OpenRTC] secretKey is invalid.");let e=[...o.shardIds].map(t=>f(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(o.stateDirectory))throw new TypeError("[OpenRTC] stateDirectory must be absolute.");return o.maxPeers!==void 0&&v(o.maxPeers,"maxPeers",50),o.startupTimeoutMs!==void 0&&v(o.startupTimeoutMs,"startupTimeoutMs",12e4),{...o,serviceId:f(o.serviceId,"serviceId",80),generation:v(o.generation,"generation"),shardIds:e,deviceId:f(o.deviceId,"deviceId"),deviceName:o.deviceName?.trim()||"OpenRTC Node service"}}async function y(o){try{return await access(o,process.platform==="win32"?constants.F_OK:constants.X_OK),!0}catch{return false}}async function L(o,e,t,r,n){return new Promise((s,i)=>{let c=spawn(o,e,{cwd:t,env:$(n),stdio:["ignore","pipe","pipe"]}),d=Buffer.alloc(0),l=Buffer.alloc(0),a=(p,F)=>Buffer.concat([p,F]).subarray(-I);c.stdout.on("data",p=>{d=a(d,p);}),c.stderr.on("data",p=>{l=a(l,p);});let u=setTimeout(()=>{c.kill(),i(new Error(`[OpenRTC] Node host command timed out: ${o}.`));},r);c.once("error",p=>{clearTimeout(u),i(p);}),c.once("exit",p=>{clearTimeout(u),p===0?s(d.toString("utf8")):i(new Error(`[OpenRTC] Node host command failed (${p??"signal"}): ${l.toString("utf8").trim().slice(-4096)}`));});})}async function q(o){let e=o.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:[...o.binaryArgs??[]]}}if(o.buildFromSource){let s=o.sourceRoot||process.env.OPENRTC_SOURCE_ROOT;if(!s||!isAbsolute(s))throw new Error("[OpenRTC] buildFromSource requires an absolute sourceRoot or OPENRTC_SOURCE_ROOT.");let i=resolve(s,"crates/openrtc/Cargo.toml"),c=resolve(s,"target");await L("cargo",["build","--locked","--manifest-path",i,"--features","node-host","--bin","openrtc-node-host","--target-dir",c],s,12e4,o.secretKey);let d=resolve(c,"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)),".."),r=resolve(t,"native",`${process.platform}-${process.arch}`),n=resolve(r,`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 ne(t,r,n),{command:n,args:[]}}async function U(o,e){let t=await L(o.command,[...o.args,"--protocol-info"],process.cwd(),12e4,e),r=JSON.parse(t);if(r.protocolVersion!==N||r.lifecycleOwner!=="rust-peer-session"||r.maxConfigBytes!==M||r.maxCommandBytes!==H||r.maxApplicationPayloadBytes!==C)throw new Error("[OpenRTC] Node host protocol is incompatible.");return r}var S=class{constructor(e,t,r){this.options=e;this.roomId=t;this.onEvent=r;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 q(this.options),t=await U(e,this.options.secretKey),r=new Promise((n,s)=>{let i=spawn(e.command,[...e.args],{env:$(this.options.secretKey),stdio:["pipe","pipe","pipe"]});this.child=i,this.childClosed=new Promise(l=>i.once("close",()=>l()));let c=setTimeout(()=>{s(this.failure("Node host startup timed out")),i.kill();},this.options.startupTimeoutMs??x),d=l=>{clearTimeout(c),s(this.failure(l.message)),this.failAll(this.failure(l.message));};i.once("error",d),i.stderr.on("data",l=>{this.stderr=Buffer.concat([this.stderr,l]).subarray(-4096);}),i.stdout.on("data",l=>{try{for(let a of this.parse(l)){if(t.testLane&&process.env.OPENRTC_NODE_HOST_LOCAL_TRACE==="1"&&a.type==="connection-state"&&console.error("[openrtc-local-node]",this.options.deviceId,{connectionId:a.snapshot.connectionId,deviceId:a.snapshot.deviceId,state:a.snapshot.state,routable:a.snapshot.routable,transportStableId:a.transportStableId,transportGeneration:a.transportGeneration,routeGeneration:a.routeGeneration}),a.type==="ready"){if(a.protocolVersion!==N||a.roomId!==this.roomId||a.deviceId!==this.options.deviceId||!isDeepStrictEqual(a.testLane,t.testLane))throw new Error("Node host returned inconsistent readiness metadata");clearTimeout(c),n();}this.dispatch(a);}}catch(a){d(a instanceof Error?a:new Error(String(a))),i.kill();}}),i.once("exit",(l,a)=>{clearTimeout(c),this.stopped=true;let u=this.failure(`Node host exited (${l??a??"unknown"})`);this.onEvent({type:"host-exit",error:u}),d(u);});});await this.writeLine({protocolVersion:N,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!==false},M),await r;}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>=W)throw new Error("[OpenRTC] Node host has too many pending requests.");let r=randomUUID(),n=new Promise((s,i)=>{let c=setTimeout(()=>{this.pending.delete(r),i(new Error(`[OpenRTC] Node host ${e} response timed out.`));},x);this.pending.set(r,{resolve:s,reject:i,timer:c});});try{await this.writeLine({type:e,id:r,...t},H);}catch(s){let i=this.pending.get(r);throw i&&clearTimeout(i.timer),this.pending.delete(r),this.failure(s instanceof Error?s.message:String(s))}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),r=setTimeout(()=>e.kill("SIGKILL"),4e3);try{await this.childClosed;}finally{clearTimeout(t),clearTimeout(r);}}}parse(e){if(this.output=Buffer.concat([this.output,e]),this.output.length>I&&!this.output.includes(10))throw new Error("Node host output line exceeded its byte limit");let t=[];for(;;){let r=this.output.indexOf(10);if(r<0)break;if(r>I)throw new Error("Node host output line exceeded its byte limit");let n=this.output.subarray(0,r).toString("utf8").trim();this.output=this.output.subarray(r+1),n&&t.push(JSON.parse(n));}return t}writeLine(e,t){let r=`${JSON.stringify(e)}
2
- `;if(Buffer.byteLength(r,"utf8")-1>t)return Promise.reject(new Error("Node host input line exceeded its byte limit"));let n=this.writeQueue.then(()=>new Promise((s,i)=>{if(!this.child||this.stopped||!this.child.stdin.writable){i(new Error("Node host is closed"));return}this.child.stdin.write(r,c=>{c?i(c):s();});}));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")));}failure(e){let t=s=>s.split(this.options.secretKey).join("[REDACTED]"),r=t(e),n=t(this.stderr.toString("utf8")).trim();return new Error(`[OpenRTC] ${r}.${n?` Host stderr: ${n}`:""}`)}failAll(e){for(let t of this.pending.values())clearTimeout(t.timer),t.reject(e);this.pending.clear();}},E=class{constructor(e,t,r,n,s){this.id=e;this.peerId=t;this.host=r;this.nativeGeneration=n;this.capabilityKey=s;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=ae(e instanceof Uint8Array||e instanceof ArrayBuffer?e:a$2("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 r of this.queued.splice(0))m(t,r);return ()=>this.messages.delete(t)}onClose(e){return this.isClosed?m(e,void 0):this.closeListeners.add(e),()=>this.closeListeners.delete(e)}receive(e){if(!this.isClosed){if(this.messages.size===0){this.queued.length===Z&&this.queued.shift(),this.queued.push(e);return}for(let t of this.messages)m(t,e);}}close(){if(!this.isClosed){this.isClosed=true,this.queued.length=0;for(let e of this.closeListeners)m(e,void 0);this.messages.clear(),this.closeListeners.clear();}}accepts(e){return ie(e,this.nativeGeneration)}replaceGeneration(e){this.nativeGeneration=e;}},T=class{constructor(e,t){this.id=e;this.host=t;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=>f(n,"priorityDeviceId")),r=(e.relevantEntityIds??[]).map(n=>f(n,"relevantEntityId"));return t.length>8||r.length>32||new Set(t).size!==t.length||new Set(r).size!==r.length?Promise.reject(new Error("[OpenRTC] Authority assignment identifiers are invalid.")):this.host.request("publish-assignment",{revision:v(e.revision,"revision"),subjectDeviceId:f(e.subjectDeviceId,"subjectDeviceId"),shardId:f(e.shardId,"shardId",80),priorityDeviceIds:t,relevantEntityIds:r,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())m(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==="peer-message"){let d=this.connections.get(e.connectionId),l=G(e);if(d&&l&&d.accepts(l)){let a=ce(e.payloadBase64),u=b$1(a);u?u.capability===`room:${this.id}`&&u.kind==="raw"&&d.receive(u.value):d.receive(a);}return}if(e.type!=="connection-state")return;let t=e.snapshot,r=G(e);if(typeof t.connectionId!="string"||!r)return;let n=this.connections.get(t.connectionId);if(typeof t.state=="string"&&["closed","failed"].includes(t.state.toLowerCase())){n?.accepts(r)&&(n.close(),this.connections.delete(t.connectionId));return}if(n){t.routable===true&&n.replaceGeneration(r);return}let i=typeof t.remoteNodeId=="string"?t.remoteNodeId:null;if(t.routable!==true||!i)return;let c=new E(t.connectionId,i,this.host,r,`room:${this.id}`);this.connections.set(c.id,c);for(let d of this.listeners)m(d,c);}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 ae(o){let e;if(o instanceof Uint8Array)e=Buffer.from(o);else if(o instanceof ArrayBuffer)e=Buffer.from(o);else if(typeof o=="string")e=Buffer.from(o,"utf8");else {let t=JSON.stringify(o);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 ce(o){let e=Buffer.from(o,"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=se(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=f(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,r=new S(this.options,e,n=>t?.project(n));t=new T(e,r);try{return await r.start(),t.onConnection(n=>{for(let s of this.listeners)m(s,{room:t,connection:n});}),t}catch(n){throw await r.close().catch(()=>{}),this.roomPromise=null,this.roomId=null,n}}};async function de(o){let e=await q(o);return U(e)}function Ee(o,e){let t=c(e,"openrtc/node"),r=new a;return i(o,{platform:"native",broadcastHostFactory:async n=>{let{NativeManagedBroadcastHost:s}=await import('./NativeManagedBroadcastHost-WCQ6TPUU.js');return new s(t,n)},offlineSupport:()=>t.invoke("openrtc_offline_runtime_support"),createOfflineEnrollmentRequest:async n=>{let s=await t.invoke("start_iroh_node");return t.invoke("openrtc_create_offline_enrollment_request",{trustDomain:n.trustDomain,deviceId:n.deviceId,endpointId:s,enrollmentNonce:crypto.randomUUID(),requestedRoles:n.requestedRoles})},close:()=>r.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:s}=await import('./ipcFactory-PDVLUG2W.js');return s(n,t,r)}})}export{Ee as OpenRTC,b as ServiceNode,de as inspectNodeHost};
1
+ import {a as a$1}from'./chunk-VFDCIEP6.js';import {a}from'./chunk-4J4F32QT.js';import {c}from'./chunk-72NEEJQG.js';import'./chunk-NDR2ANQB.js';import {i,b as b$1,a as a$2}from'./chunk-42TNJH5S.js';import'./chunk-ZA44REGI.js';import'./chunk-LLZT3MR6.js';import'./chunk-DUY34MGT.js';import'./chunk-CCCYE3XN.js';import'./chunk-N6LGTNUI.js';import'./chunk-JPBW67B3.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 N=1,M=24*1024,H=96*1024,I=128*1024,C=64*1024,W=256,Z=256,x=3e4,ee=/^[A-Za-z0-9_.:@-]+$/,te=/(?:^|_)(?:SECRET|TOKEN|PASSWORD|PRIVATE(?:_KEY)?|CREDENTIALS?)(?:_|$)/i,oe=1;function re(o){return Buffer.from(JSON.stringify({schema:o.schema,kind:o.kind,platform:o.platform,arch:o.arch,rustTarget:o.rustTarget,sourceCommit:o.sourceCommit,sourceDigest:o.sourceDigest,binarySha256:o.binarySha256,protocol:o.protocol,signingKeySha256:o.signingKeySha256,signatureAlgorithm:o.signatureAlgorithm}),"utf8")}async function ne(o,e,t){let[r,n,s]=await Promise.all([readFile(t),readFile(resolve(e,"openrtc-node-host.manifest.json")),readFile(resolve(o,"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 c=u=>createHash("sha256").update(u).digest("hex"),l={"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&&l!==void 0&&i.schema===oe&&i.kind==="openrtc-node-host"&&i.platform===process.platform&&i.arch===process.arch&&i.rustTarget===l&&/^[0-9a-f]{40}$/.test(i.sourceCommit)&&/^[0-9a-f]{64}$/.test(i.sourceDigest)&&i.binarySha256===c(r)&&i.signingKeySha256===c(s)&&i.signatureAlgorithm==="ed25519"&&/^[A-Za-z0-9+/]{86}==$/.test(i.signature)&&verify(null,re(i),s,Buffer.from(i.signature,"base64"))))throw new Error("[OpenRTC] Packaged Node host provenance verification failed.")}function $(o){return Object.fromEntries(Object.entries(process.env).filter(([e,t])=>!te.test(e)&&(!o||!t?.includes(o))))}function m(o,e){queueMicrotask(()=>{try{o(e);}catch{try{process.emitWarning("[OpenRTC] ServiceNode callback failed.",{code:"OPENRTC_SERVICE_CALLBACK"});}catch{}}});}function G(o){let e=/^\d{1,20}$/;return typeof o.transportStableId!="string"||!e.test(o.transportStableId)||!e.test(o.transportGeneration)||!e.test(o.routeGeneration)?null:{transportStableId:o.transportStableId,transportGeneration:o.transportGeneration,routeGeneration:o.routeGeneration}}function ie(o,e){return o.transportStableId===e.transportStableId&&o.transportGeneration===e.transportGeneration&&o.routeGeneration===e.routeGeneration}function f(o,e,t=160){let r=o.trim();if(!r||r.length>t||!ee.test(r))throw new TypeError(`[OpenRTC] ${e} is invalid.`);return r}function v(o,e,t=Number.MAX_SAFE_INTEGER){if(!Number.isSafeInteger(o)||o<1||o>t)throw new RangeError(`[OpenRTC] ${e} must be a positive safe integer.`);return o}function se(o){if(!/^pk_(?:live|test)_[A-Za-z0-9]+$/.test(o.apiKey))throw new TypeError("[OpenRTC] apiKey is invalid.");if(!/^sk_(?:live|test)_[A-Za-z0-9_-]+$/.test(o.secretKey)||o.secretKey.length>128)throw new TypeError("[OpenRTC] secretKey is invalid.");let e=[...o.shardIds].map(t=>f(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(o.stateDirectory))throw new TypeError("[OpenRTC] stateDirectory must be absolute.");return o.maxPeers!==void 0&&v(o.maxPeers,"maxPeers",50),o.startupTimeoutMs!==void 0&&v(o.startupTimeoutMs,"startupTimeoutMs",12e4),{...o,serviceId:f(o.serviceId,"serviceId",80),generation:v(o.generation,"generation"),shardIds:e,deviceId:f(o.deviceId,"deviceId"),deviceName:o.deviceName?.trim()||"OpenRTC Node service"}}async function y(o){try{return await access(o,process.platform==="win32"?constants.F_OK:constants.X_OK),!0}catch{return false}}async function L(o,e,t,r,n){return new Promise((s,i)=>{let c=spawn(o,e,{cwd:t,env:$(n),stdio:["ignore","pipe","pipe"]}),d=Buffer.alloc(0),l=Buffer.alloc(0),a=(p,F)=>Buffer.concat([p,F]).subarray(-I);c.stdout.on("data",p=>{d=a(d,p);}),c.stderr.on("data",p=>{l=a(l,p);});let u=setTimeout(()=>{c.kill(),i(new Error(`[OpenRTC] Node host command timed out: ${o}.`));},r);c.once("error",p=>{clearTimeout(u),i(p);}),c.once("exit",p=>{clearTimeout(u),p===0?s(d.toString("utf8")):i(new Error(`[OpenRTC] Node host command failed (${p??"signal"}): ${l.toString("utf8").trim().slice(-4096)}`));});})}async function q(o){let e=o.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:[...o.binaryArgs??[]]}}if(o.buildFromSource){let s=o.sourceRoot||process.env.OPENRTC_SOURCE_ROOT;if(!s||!isAbsolute(s))throw new Error("[OpenRTC] buildFromSource requires an absolute sourceRoot or OPENRTC_SOURCE_ROOT.");let i=resolve(s,"crates/openrtc/Cargo.toml"),c=resolve(s,"target");await L("cargo",["build","--locked","--manifest-path",i,"--features","node-host","--bin","openrtc-node-host","--target-dir",c],s,12e4,o.secretKey);let d=resolve(c,"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)),".."),r=resolve(t,"native",`${process.platform}-${process.arch}`),n=resolve(r,`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 ne(t,r,n),{command:n,args:[]}}async function U(o,e){let t=await L(o.command,[...o.args,"--protocol-info"],process.cwd(),12e4,e),r=JSON.parse(t);if(r.protocolVersion!==N||r.lifecycleOwner!=="rust-peer-session"||r.maxConfigBytes!==M||r.maxCommandBytes!==H||r.maxApplicationPayloadBytes!==C)throw new Error("[OpenRTC] Node host protocol is incompatible.");return r}var S=class{constructor(e,t,r){this.options=e;this.roomId=t;this.onEvent=r;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 q(this.options),t=await U(e,this.options.secretKey),r=new Promise((n,s)=>{let i=spawn(e.command,[...e.args],{env:$(this.options.secretKey),stdio:["pipe","pipe","pipe"]});this.child=i,this.childClosed=new Promise(l=>i.once("close",()=>l()));let c=setTimeout(()=>{s(this.failure("Node host startup timed out")),i.kill();},this.options.startupTimeoutMs??x),d=l=>{clearTimeout(c),s(this.failure(l.message)),this.failAll(this.failure(l.message));};i.once("error",d),i.stderr.on("data",l=>{this.stderr=Buffer.concat([this.stderr,l]).subarray(-4096);}),i.stdout.on("data",l=>{try{for(let a of this.parse(l)){if(t.testLane&&process.env.OPENRTC_NODE_HOST_LOCAL_TRACE==="1"&&a.type==="connection-state"&&console.error("[openrtc-local-node]",this.options.deviceId,{connectionId:a.snapshot.connectionId,deviceId:a.snapshot.deviceId,state:a.snapshot.state,routable:a.snapshot.routable,transportStableId:a.transportStableId,transportGeneration:a.transportGeneration,routeGeneration:a.routeGeneration}),a.type==="ready"){if(a.protocolVersion!==N||a.roomId!==this.roomId||a.deviceId!==this.options.deviceId||!isDeepStrictEqual(a.testLane,t.testLane))throw new Error("Node host returned inconsistent readiness metadata");clearTimeout(c),n();}this.dispatch(a);}}catch(a){d(a instanceof Error?a:new Error(String(a))),i.kill();}}),i.once("exit",(l,a)=>{clearTimeout(c),this.stopped=true;let u=this.failure(`Node host exited (${l??a??"unknown"})`);this.onEvent({type:"host-exit",error:u}),d(u);});});await this.writeLine({protocolVersion:N,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!==false},M),await r;}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>=W)throw new Error("[OpenRTC] Node host has too many pending requests.");let r=randomUUID(),n=new Promise((s,i)=>{let c=setTimeout(()=>{this.pending.delete(r),i(new Error(`[OpenRTC] Node host ${e} response timed out.`));},x);this.pending.set(r,{resolve:s,reject:i,timer:c});});try{await this.writeLine({type:e,id:r,...t},H);}catch(s){let i=this.pending.get(r);throw i&&clearTimeout(i.timer),this.pending.delete(r),this.failure(s instanceof Error?s.message:String(s))}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),r=setTimeout(()=>e.kill("SIGKILL"),4e3);try{await this.childClosed;}finally{clearTimeout(t),clearTimeout(r);}}}parse(e){if(this.output=Buffer.concat([this.output,e]),this.output.length>I&&!this.output.includes(10))throw new Error("Node host output line exceeded its byte limit");let t=[];for(;;){let r=this.output.indexOf(10);if(r<0)break;if(r>I)throw new Error("Node host output line exceeded its byte limit");let n=this.output.subarray(0,r).toString("utf8").trim();this.output=this.output.subarray(r+1),n&&t.push(JSON.parse(n));}return t}writeLine(e,t){let r=`${JSON.stringify(e)}
2
+ `;if(Buffer.byteLength(r,"utf8")-1>t)return Promise.reject(new Error("Node host input line exceeded its byte limit"));let n=this.writeQueue.then(()=>new Promise((s,i)=>{if(!this.child||this.stopped||!this.child.stdin.writable){i(new Error("Node host is closed"));return}this.child.stdin.write(r,c=>{c?i(c):s();});}));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")));}failure(e){let t=s=>s.split(this.options.secretKey).join("[REDACTED]"),r=t(e),n=t(this.stderr.toString("utf8")).trim();return new Error(`[OpenRTC] ${r}.${n?` Host stderr: ${n}`:""}`)}failAll(e){for(let t of this.pending.values())clearTimeout(t.timer),t.reject(e);this.pending.clear();}},E=class{constructor(e,t,r,n,s){this.id=e;this.peerId=t;this.host=r;this.nativeGeneration=n;this.capabilityKey=s;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=ae(e instanceof Uint8Array||e instanceof ArrayBuffer?e:a$2("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 r of this.queued.splice(0))m(t,r);return ()=>this.messages.delete(t)}onClose(e){return this.isClosed?m(e,void 0):this.closeListeners.add(e),()=>this.closeListeners.delete(e)}receive(e){if(!this.isClosed){if(this.messages.size===0){this.queued.length===Z&&this.queued.shift(),this.queued.push(e);return}for(let t of this.messages)m(t,e);}}close(){if(!this.isClosed){this.isClosed=true,this.queued.length=0;for(let e of this.closeListeners)m(e,void 0);this.messages.clear(),this.closeListeners.clear();}}accepts(e){return ie(e,this.nativeGeneration)}replaceGeneration(e){this.nativeGeneration=e;}},T=class{constructor(e,t){this.id=e;this.host=t;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=>f(n,"priorityDeviceId")),r=(e.relevantEntityIds??[]).map(n=>f(n,"relevantEntityId"));return t.length>8||r.length>32||new Set(t).size!==t.length||new Set(r).size!==r.length?Promise.reject(new Error("[OpenRTC] Authority assignment identifiers are invalid.")):this.host.request("publish-assignment",{revision:v(e.revision,"revision"),subjectDeviceId:f(e.subjectDeviceId,"subjectDeviceId"),shardId:f(e.shardId,"shardId",80),priorityDeviceIds:t,relevantEntityIds:r,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())m(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==="peer-message"){let d=this.connections.get(e.connectionId),l=G(e);if(d&&l&&d.accepts(l)){let a=ce(e.payloadBase64),u=b$1(a);u?u.capability===`room:${this.id}`&&u.kind==="raw"&&d.receive(u.value):d.receive(a);}return}if(e.type!=="connection-state")return;let t=e.snapshot,r=G(e);if(typeof t.connectionId!="string"||!r)return;let n=this.connections.get(t.connectionId);if(typeof t.state=="string"&&["closed","failed"].includes(t.state.toLowerCase())){n?.accepts(r)&&(n.close(),this.connections.delete(t.connectionId));return}if(n){t.routable===true&&n.replaceGeneration(r);return}let i=typeof t.remoteNodeId=="string"?t.remoteNodeId:null;if(t.routable!==true||!i)return;let c=new E(t.connectionId,i,this.host,r,`room:${this.id}`);this.connections.set(c.id,c);for(let d of this.listeners)m(d,c);}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 ae(o){let e;if(o instanceof Uint8Array)e=Buffer.from(o);else if(o instanceof ArrayBuffer)e=Buffer.from(o);else if(typeof o=="string")e=Buffer.from(o,"utf8");else {let t=JSON.stringify(o);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 ce(o){let e=Buffer.from(o,"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=se(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=f(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,r=new S(this.options,e,n=>t?.project(n));t=new T(e,r);try{return await r.start(),t.onConnection(n=>{for(let s of this.listeners)m(s,{room:t,connection:n});}),t}catch(n){throw await r.close().catch(()=>{}),this.roomPromise=null,this.roomId=null,n}}};async function de(o){let e=await q(o);return U(e)}function Ee(o,e){let t=c(e,"openrtc/node"),r=new a;return i(o,{platform:"native",broadcastHostFactory:async n=>{let{NativeManagedBroadcastHost:s}=await import('./NativeManagedBroadcastHost-WCQ6TPUU.js');return new s(t,n)},offlineSupport:()=>t.invoke("openrtc_offline_runtime_support"),createOfflineEnrollmentRequest:async n=>{let s=await t.invoke("start_iroh_node");return t.invoke("openrtc_create_offline_enrollment_request",{trustDomain:n.trustDomain,deviceId:n.deviceId,endpointId:s,enrollmentNonce:crypto.randomUUID(),requestedRoles:n.requestedRoles})},close:()=>r.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:s}=await import('./ipcFactory-2WMR4PH6.js');return s(n,t,r)}})}export{Ee as OpenRTC,b as ServiceNode,de as inspectNodeHost};