openrtc 1.0.0 → 1.0.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 (34) hide show
  1. package/dist/{DelegatingRuntimeAdapter-By7pziBs.d.ts → DelegatingRuntimeAdapter-CjjDPy9r.d.ts} +19 -2
  2. package/dist/{IpcRuntimeAdapter-DymXAsNU.d.ts → IpcRuntimeAdapter-DxY3xSuZ.d.ts} +2 -2
  3. package/dist/auth/index.js +1 -1
  4. package/dist/auth/internal.js +1 -1
  5. package/dist/chunk-34LATQZZ.js +2 -0
  6. package/dist/chunk-5EG2FIIE.js +3 -0
  7. package/dist/chunk-ALAQEBXJ.js +1 -0
  8. package/dist/chunk-C7YN5MSV.js +1 -0
  9. package/dist/{chunk-KH227SE4.js → chunk-EPLB7YIT.js} +1 -1
  10. package/dist/chunk-LIWR2BDB.js +2 -0
  11. package/dist/chunk-QT2ASNI3.js +1 -0
  12. package/dist/chunk-R3SDPFXM.js +1 -0
  13. package/dist/{device-status-nkXepu97.d.ts → device-status-CvgzstCB.d.ts} +49 -6
  14. package/dist/{framing-BUtu0oZK.d.ts → framing-CyPwlaXh.d.ts} +4 -4
  15. package/dist/index.d.ts +15 -10
  16. package/dist/index.js +2 -2
  17. package/dist/openrtc_bg.wasm +0 -0
  18. package/dist/runtime/WasmRuntimeAdapter.d.ts +2 -2
  19. package/dist/runtime/WasmRuntimeAdapter.js +1 -1
  20. package/dist/runtime/device-status.d.ts +2 -2
  21. package/dist/runtime/index.d.ts +16 -10
  22. package/dist/runtime/index.js +1 -1
  23. package/dist/runtime/tauri.d.ts +3 -3
  24. package/dist/runtime/tauri.js +1 -1
  25. package/dist/transport/index.d.ts +7 -2
  26. package/dist/transport/index.js +1 -1
  27. package/dist/{types-CzIpGV9x.d.ts → types-ByZyADCn.d.ts} +69 -4
  28. package/package.json +2 -2
  29. package/dist/chunk-3KDNLXT6.js +0 -3
  30. package/dist/chunk-5RXNKNPH.js +0 -2
  31. package/dist/chunk-6TIOSMVJ.js +0 -1
  32. package/dist/chunk-BLOEZIFJ.js +0 -1
  33. package/dist/chunk-KYDLXXNM.js +0 -1
  34. package/dist/chunk-W5JHUOK5.js +0 -2
@@ -1,4 +1,4 @@
1
- import { D as DiscoveryMode, A as AuthMode, S as SignalingMode, E as ExplicitFileDataSendParams, I as ISignalingBackend, R as RuntimeIdentity, a as Device, b as DeviceStatusSnapshot, P as PeerSessionSnapshot, c as ResolvedPeerIdentity, M as ManagedConnectionRecord, d as SignalingEnvelope, e as DeviceEvent, f as SignalingSession, g as SessionEvent, L as LocalDeviceInfo, N as NativeManagedSessionStartResult, G as GrantScope, B as BackendPeerBiStream, h as BackendPeerUniStream, i as NativeConnectParams, j as NativeConnectResult, k as BackendConnectionState } from './types-CzIpGV9x.js';
1
+ import { D as DiscoveryMode, A as AuthMode, S as SignalingMode, E as ExplicitFileDataSendParams, I as ISignalingBackend, R as RuntimeIdentity, a as Device, b as DeviceStatusSnapshot, P as PeerSessionSnapshot, c as ResolvedPeerIdentity, M as ManagedConnectionRecord, d as SignalingEnvelope, e as DeviceEvent, f as SignalingSession, g as SessionEvent, L as LocalDeviceInfo, N as NativeManagedSessionStartResult, G as GrantScope, B as BackendPeerBiStream, h as BackendPeerUniStream, i as NativeConnectParams, j as NativeConnectResult, k as BackendConnectionState } from './types-ByZyADCn.js';
2
2
  import { A as AuthContext } from './IEngineBridge-C7OT2CRv.js';
3
3
 
4
4
  type RuntimeAdapterKind = 'browser-wasm' | 'native-ipc' | 'tauri-ipc' | 'unknown';
@@ -79,8 +79,25 @@ interface NativeRuntimeStatusSnapshot {
79
79
  };
80
80
  }
81
81
  declare const BROWSER_WASM_RUNTIME_CAPABILITIES: RuntimeCapabilities;
82
+ /**
83
+ * The small host surface that browser WebRTC capability reporting needs.
84
+ *
85
+ * This is deliberately a feature check only: capability reporting must not
86
+ * create a peer connection, probe ICE, or influence route ownership.
87
+ */
88
+ interface BrowserRuntimeCapabilityHost {
89
+ RTCPeerConnection?: unknown;
90
+ }
82
91
  declare const NATIVE_IPC_RUNTIME_CAPABILITIES: RuntimeCapabilities;
83
92
  declare function cloneRuntimeCapabilities(capabilities: RuntimeCapabilities): RuntimeCapabilities;
93
+ /**
94
+ * Returns browser/WASM capabilities for a concrete JavaScript host.
95
+ *
96
+ * The static browser baseline describes package support. WebRTC additionally
97
+ * requires the browser primitive to exist at runtime. Passing the host keeps
98
+ * the resolver deterministic in SSR and test environments.
99
+ */
100
+ declare function runtimeCapabilitiesForBrowserHost(host?: BrowserRuntimeCapabilityHost | null | undefined): RuntimeCapabilities;
84
101
  declare function runtimeCapabilitiesFromNativeStatus(status: NativeRuntimeStatusSnapshot | null | undefined, allowWasmFallback?: boolean): RuntimeCapabilities;
85
102
  declare function runtimeCapabilityProfile(capabilities: RuntimeCapabilities): RuntimeCapabilityProfile;
86
103
 
@@ -198,4 +215,4 @@ declare abstract class DelegatingRuntimeAdapter implements ISignalingBackend {
198
215
  setCoreClient(client: unknown): void;
199
216
  }
200
217
 
201
- export { BROWSER_WASM_RUNTIME_CAPABILITIES as B, DelegatingRuntimeAdapter as D, NATIVE_IPC_RUNTIME_CAPABILITIES as N, type RuntimeCapabilities as R, type WasmBridgeOptions as W, type RuntimeCapabilityProfile as a, type RuntimeAdapterKind as b, type NativeRuntimeStatusSnapshot as c, type NativeRuntimeTransportFeatureStatus as d, cloneRuntimeCapabilities as e, runtimeCapabilityProfile as f, runtimeCapabilitiesFromNativeStatus as r };
218
+ export { BROWSER_WASM_RUNTIME_CAPABILITIES as B, DelegatingRuntimeAdapter as D, NATIVE_IPC_RUNTIME_CAPABILITIES as N, type RuntimeCapabilities as R, type WasmBridgeOptions as W, type RuntimeCapabilityProfile as a, type RuntimeAdapterKind as b, type BrowserRuntimeCapabilityHost as c, type NativeRuntimeStatusSnapshot as d, type NativeRuntimeTransportFeatureStatus as e, cloneRuntimeCapabilities as f, runtimeCapabilitiesFromNativeStatus as g, runtimeCapabilityProfile as h, runtimeCapabilitiesForBrowserHost as r };
@@ -1,5 +1,5 @@
1
- import { C as ClientOptions } from './types-CzIpGV9x.js';
2
- import { W as WasmBridgeOptions, D as DelegatingRuntimeAdapter } from './DelegatingRuntimeAdapter-By7pziBs.js';
1
+ import { C as ClientOptions } from './types-ByZyADCn.js';
2
+ import { W as WasmBridgeOptions, D as DelegatingRuntimeAdapter } from './DelegatingRuntimeAdapter-CjjDPy9r.js';
3
3
 
4
4
  type PlutoIpcUnlisten = () => void | Promise<void>;
5
5
  interface PlutoIpcBridge {
@@ -1 +1 @@
1
- export{H as authHost,G as getAuthHost,F as registerDesktopAuthRelay}from'../chunk-W5JHUOK5.js';
1
+ export{H as authHost,G as getAuthHost,F as registerDesktopAuthRelay}from'../chunk-34LATQZZ.js';import'../chunk-C7YN5MSV.js';
@@ -1 +1 @@
1
- export{F as registerDesktopAuthRelay}from'../chunk-W5JHUOK5.js';
1
+ export{F as registerDesktopAuthRelay}from'../chunk-34LATQZZ.js';import'../chunk-C7YN5MSV.js';
@@ -0,0 +1,2 @@
1
+ import {c as c$1}from'./chunk-C7YN5MSV.js';import {getApps,initializeApp}from'firebase/app';import {getFunctions,connectFunctionsEmulator,httpsCallable}from'firebase/functions';import {browserLocalPersistence,inMemoryPersistence,browserPopupRedirectResolver,initializeAuth,getAuth,connectAuthEmulator,setPersistence,onIdTokenChanged,getIdToken,signInWithCustomToken,onAuthStateChanged,signInAnonymously,signInWithEmailAndPassword,createUserWithEmailAndPassword,signOut,deleteUser,updateProfile,GoogleAuthProvider,OAuthProvider,signInWithCredential,signInWithPopup,signInWithRedirect,getRedirectResult}from'firebase/auth';function N(){return typeof window>"u"?false:!!(window.__TAURI_IPC__||window.__TAURI_INTERNALS__||window.__TAURI__||window.location.protocol==="tauri:"||window.location.hostname==="tauri.localhost")}var E=new Set;function S(e,t){E.has(e)||(E.add(e),console.warn(t));}function oe(e){return /^pk_(live|test)_[0-9a-f]{40}$/.test(e)}async function He(e,t){let n=`${e}:${t}`,o=new TextEncoder().encode(n),i=await crypto.subtle.digest("SHA-256",o);return Array.from(new Uint8Array(i)).map(d=>d.toString(16).padStart(2,"0")).join("")}function I(e){let t=typeof e.apiKey=="string"?e.apiKey.trim():"";if(t)return oe(t)||S(`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 T(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||S("default-auth-mode","[pluto-rtc] `authMode` is not set; defaulting to `anonymous` for compatibility."),"anonymous")}function Be(e){let t=typeof e.projectId=="string"?e.projectId.trim():"";return t||(S("default-project-id","[pluto-rtc] `projectId` is not set; defaulting to the built-in PlutoRTC Firebase project."),P)}function L(e){return e.trim().replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"")}function Fe(e){let t="storagePrefix"in e&&typeof e.storagePrefix=="string"?L(e.storagePrefix):"";return t||L(I(e))||"default"}var We={devicesPerUser:2,maxRooms:10,maxMembersPerRoom:5,maxPersonalDevices:25};var ie=[{urls:"stun:stun.l.google.com:19302"},{urls:"stun:stun.cloudflare.com:3478"}],H={iceServers:ie},Ke={};var B=["iroh-relay","iroh","moq"];function ae(e){return (Array.isArray(e.urls)?e.urls:[e.urls]).some(n=>typeof n=="string"&&(n.startsWith("turn:")||n.startsWith("turns:")))}function se(e){let n=(Array.isArray(e.urls)?e.urls:[e.urls]).filter(r=>typeof r=="string"&&!r.startsWith("stun:"));return n.length===0?null:{...e,urls:Array.isArray(e.urls)?n:n[0]}}function R(e){if(e)return e.map(t=>se(t)).filter(t=>t!==null)}function F(e,t){let n=new Set(["iroh-relay","iroh","moq"]);t&&n.add("webrtc");let r=(e??B).filter(o=>n.has(o));return r.length>0?r:[...B]}function Ge(e){return !!e?.transports?.webrtc}function ze(e,t){let n=e?.transports?.webrtc||void 0;if(n)return e?.strictMode||n.privacyMode?{...n,iceServers:R(n.iceServers),iceTransportPolicy:"relay"}:n.iceTransportPolicy==="relay"&&!(Array.isArray(n.iceServers)&&n.iceServers.some(o=>ae(o)))?(t?.("[Client] Overriding relay-only ICE policy to all because no TURN servers are configured"),{...n,iceTransportPolicy:"all"}):n}var ce=/^[A-Za-z0-9._-]+$/,le="[redacted]";function q(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 C(e){return q(e.trim()).toString()}function $e(e,t){let n=q(e.trim());if(t!==void 0){let r=t.trim();if(!r)throw new Error("[OpenRTC] transports.moq.accessToken must not be empty when provided.");if(new TextEncoder().encode(r).byteLength>16384)throw new Error("[OpenRTC] transports.moq.accessToken exceeds the maximum supported size.");if(!ce.test(r))throw new Error("[OpenRTC] transports.moq.accessToken must be a URL-safe JWT.");n.searchParams.append("jwt",r);}return n.toString()}function Ye(e){try{let t=new URL(e);return t.search="",t.hash="",t.toString()}catch{return "invalid-moq-relay-url"}}function Ve(e,t){let n=e instanceof Error?`${e.name}: ${e.message}`:String(e),r=t?.trim();return r?n.split(r).join(le):n}var de=[...c$1];function A(e){let t=e.spaceKey??e.space;return {...e,...t!==void 0?{spaceKey:t}:{}}}function W(e){return {...e,iceServers:e.iceServers?e.iceServers.map(t=>({...t})):e.iceServers}}function ue(e){return {...e}}function pe(e){return {...e}}function me(e){if(e)return {iroh:typeof e.iroh=="object"?pe(e.iroh):e.iroh,webrtc:typeof e.webrtc=="object"?W(e.webrtc):e.webrtc,ble:typeof e.ble=="object"?{...e.ble}:e.ble,moq:typeof e.moq=="object"?ue(e.moq):e.moq}}function ge(e){if(e.strictMode&&!e.transports&&(e.transports={iroh:{relayOnly:true}}),!!e.transports){if(e.transports.webrtc===true?e.transports.webrtc=W(H):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,n=t.relayUrl?.trim(),r=t.accessToken;if(r!==void 0&&!r.trim())throw new Error("[OpenRTC] transports.moq.accessToken must not be empty when provided.");e.transports.moq={...t,...n?{relayUrl:C(n)}:{},...r!==void 0?{accessToken:r.trim()}:{}};}e.transports.iroh===true?e.transports.iroh={}:e.transports.iroh===false&&(e.transports.iroh=void 0);}}function ye(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.ble=void 0;let n=e.transports.webrtc;n&&typeof n=="object"&&(e.transports.webrtc={...n,privacyMode:true,lanMode:false,iceServers:R(n.iceServers)??[],iceTransportPolicy:"relay"});let r=e.transports.moq;if(r&&typeof r=="object"){let o=r.relayUrl?.trim();if(!o)throw new Error("[OpenRTC] strictMode requires an explicit transports.moq.relayUrl.");e.transports.moq={...r,relayUrl:C(o)};}}function rt(e){let t=A(e),n=I(t),r=T(t),o={strictMode:false,disableIrohFallback:false,transportPriority:[...de],...t,authMode:r,transports:me(t.transports)};ge(o),ye(o),o.strictMode&&(o.transportPriority=F(t.transportPriority,!!o.transports?.webrtc));let i=K(o),a=(o.discoveryMode??"space")==="space"?"client-open":"client-auth";return {appTag:n,authMode:r,configuredPersistenceMode:i,options:o,roomCreationMode:a}}function K(e){let t=e.transports?.iroh;return e.endpointIdPersistence??e.nodeIdPersistence??(typeof t=="object"?t.persistenceMode:void 0)??"ephemeral"}function ot(e){return "options"in e&&"configuredPersistenceMode"in e?{apiKey:e.options.apiKey,authMode:T(e.options),projectId:e.options.projectId,storagePrefix:e.options.storagePrefix,nodeIdPersistence:e.configuredPersistenceMode}:{apiKey:e.apiKey,authMode:T(e),projectId:e.projectId,storagePrefix:e.storagePrefix,nodeIdPersistence:K(e)}}function it(e,t){t&&(e.transports={...e.transports||{},...t});}var P="pluto-rtc-prod",j={apiKey:"AIzaSyA62Krj-7ZYFT5xjrTUq7mXana41Ahj_mM",authDomain:"api.openrtc.app",projectId:P,storageBucket:"pluto-rtc-prod.firebasestorage.app",messagingSenderId:"607066575224",appId:"1:607066575224:web:ed3f51825ba228db92b88d"};function ct(e){let t=A(e),n=typeof t.projectId=="string"&&t.projectId.trim()?t.projectId.trim():P;return {...t,projectId:n}}function G(e){return new Promise(t=>setTimeout(t,e))}function dt(e){let t=new Uint8Array(e.byteLength);return t.set(e),t}function ut(e){let t=e.reduce((o,i)=>o+i.byteLength,0),n=new Uint8Array(t),r=0;for(let o of e)n.set(o,r),r+=o.byteLength;return n}function pt(e,t,n){let r=t*Math.pow(2,Math.max(0,e-1));return Math.min(n,r)}function mt(e){try{let t=e;return !!t&&!!t.send&&typeof t.send.getWriter=="function"&&!!t.recv&&typeof t.recv.getReader=="function"}catch{return false}}function gt(e,t,n){let r=e;if(!r)return null;try{let o=r.send,i=r.recv;if(!o||typeof o.getWriter!="function"||!i||typeof i.getReader!="function")return null;let a=typeof r.endpoint_id=="string"&&r.endpoint_id.trim().length>0?r.endpoint_id:t,l=Number.isSafeInteger(r.transport_stable_id)&&Number(r.transport_stable_id)>0?Number(r.transport_stable_id):void 0,d=Number.isSafeInteger(n)&&Number(n)>0?Number(n):void 0;if(l!==void 0&&d!==void 0&&l!==d)return null;let s=l??d;return {send:o,recv:i,endpoint_id:a,...s?{transport_stable_id:s}:{}}}catch{return null}}function yt(e,t){let n={send:e.send,recv:t,endpoint_id:typeof e.endpoint_id=="string"?e.endpoint_id:"",...Number.isSafeInteger(e.transport_stable_id)&&Number(e.transport_stable_id)>0?{transport_stable_id:Number(e.transport_stable_id)}:{}};return e?.applicationCryptoWrapped===true&&(n.applicationCryptoWrapped=true),n}async function ft(e,t){if(!e)return false;try{let n=e.send?.getWriter?.();if(n)try{await n.close();}catch{}finally{try{n.releaseLock();}catch{}}}catch{}try{let n=e.recv?.getReader?.();if(n)try{await n.cancel(t);}catch{}finally{try{n.releaseLock();}catch{}}}catch{}return true}function ht(e,t,n={}){let r=n.context??"prependBytesToReader",o=n.traceId,i=t.byteLength===0,a=n.pendingRead??null,l=s=>n.release?.(s),d=(s,p)=>n.log?.(s,p);return new ReadableStream({async pull(s){if(!i){i=true,s.enqueue(t);return}if(a){let u=a;a=null;let m;try{m=await u;}catch(y){s.error(y),l("pending-read-error"),d("prepend-bytes:pending-read-error",{context:r,traceId:o||null,error:y?.message||String(y)});return}if(m.done){s.close(),l("pending-done");return}m.value&&s.enqueue(m.value);return}let p;try{p=await e.read();}catch(u){s.error(u),l("read-error"),d("prepend-bytes:read-error",{context:r,traceId:o||null,error:u?.message||String(u)});return}let{done:v,value:b}=p;if(v){s.close(),l("done");return}b&&s.enqueue(b);},async cancel(s){l("cancel");}})}async function bt(e,t){let n=e.read(),r=t-Date.now();if(r<=0)return {status:"timeout",pendingRead:n};let o=Symbol("probe-timeout"),i,a=new Promise(l=>{i=setTimeout(()=>l(o),r);});try{let l=await Promise.race([n,a]);if(l===o)return {status:"timeout",pendingRead:n};let{done:d,value:s}=l;return d?{status:"done"}:{status:"data",value:s&&s.byteLength>0?new Uint8Array(s):new Uint8Array(0)}}finally{i&&clearTimeout(i);}}function z(e,t,n){let r;return new Promise((o,i)=>{r=setTimeout(()=>{if(r=void 0,typeof n=="function"){i(n());return}let a=n?`${n} timed out`:"timeout";i(new Error(`${a} after ${t}ms`));},t),e.then(a=>{r!==void 0&&clearTimeout(r),o(a);},a=>{r!==void 0&&clearTimeout(r),i(a);});})}var X="pluto-rtc-auth",M=null;function _e(){if(typeof globalThis<"u"&&globalThis.__OPENRTC_DEBUG__===true)return true;if(typeof localStorage<"u")try{return localStorage.getItem("openrtc:debug")==="1"}catch{return false}return false}function c(e,t){if(_e()){if(typeof t>"u"){console.log(e);return}console.log(e,t);}}function Dt(e){M=e;}function De(){return N()}function ne(){return typeof navigator>"u"?false:/iPhone|iPad|iPod|Android/i.test(navigator.userAgent||"")}function Z(){return De()&&ne()}function g(e,t,n){return z(e,t,()=>new Error(`${n} timeout after ${t}ms`))}function ee(e){let t="0123456789ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvwxyz-._",n=new Uint8Array(e);window.crypto.getRandomValues(n);let r="";for(let o=0;o<e;o+=1)r+=t[n[o]%t.length];return r}async function te(e){let n=new TextEncoder().encode(e),r=await crypto.subtle.digest("SHA-256",n);return Array.from(new Uint8Array(r)).map(i=>i.toString(16).padStart(2,"0")).join("")}var _=class{constructor(){this.redirectResultPromise=null;this.redirectResultConsumed=false;this.lastRelayedToken=null;this.lastRelayedRefreshToken=null;this.desktopTokenRefreshIntervalId=null;let t=getApps().find(o=>o.name===X);this.app=t||initializeApp(j,X);let n=ne(),r=Z();if(n)try{let o=r?{persistence:[browserLocalPersistence,inMemoryPersistence]}:{persistence:[browserLocalPersistence,inMemoryPersistence],popupRedirectResolver:browserPopupRedirectResolver};this.auth=initializeAuth(this.app,o),c("[PLUTO-RTC][AUTH-HOST] Using mobile-safe Firebase auth initialization",{appName:this.app.name,persistence:"browserLocalPersistence->inMemoryPersistence",redirectResolver:r?"disabled-for-tauri-mobile":"browserPopupRedirectResolver",tauriMobile:r});}catch{this.auth=getAuth(this.app),console.warn("[PLUTO-RTC][AUTH-HOST] Mobile-safe auth initialization unavailable; falling back to default getAuth");}else this.auth=getAuth(this.app);this.functions=getFunctions(this.app);try{let o=typeof globalThis<"u"?String(globalThis.__OPENRTC_AUTH_EMULATOR_HOST__??"").trim():"",i=typeof globalThis<"u"?String(globalThis.__OPENRTC_FUNCTIONS_EMULATOR_HOST__??"").trim():"",a=typeof import.meta<"u"?import.meta.env:null;if(!!o||!!i||!!a&&String(a.VITE_USE_EMULATORS)==="true"&&(a.DEV||String(a.VITE_E2E)==="true")){let d=String(a?.VITE_OPENRTC_EMULATOR_HOST??"127.0.0.1").trim()||"127.0.0.1",[s,p]=o.split(":"),[v,b]=i.split(":"),u=(s??"").trim()||d,m=(v??"").trim()||d,y=Number(p??a?.VITE_OPENRTC_AUTH_EMULATOR_PORT??9100),re=Number(b??a?.VITE_OPENRTC_FUNCTIONS_EMULATOR_PORT??5002);try{connectAuthEmulator(this.auth,`http://${u}:${y}`,{disableWarnings:!0});}catch{}try{connectFunctionsEmulator(this.functions,m,re);}catch{}}}catch{}n?this.persistenceReady=Promise.resolve():this.persistenceReady=setPersistence(this.auth,browserLocalPersistence).catch(o=>{console.warn("[PLUTO-RTC][AUTH-HOST] Failed to set auth persistence",{message:o?.message});}),c("[PLUTO-RTC][AUTH-HOST] Initialized auth host",{appName:this.app.name,mobileSafeAuth:n}),onIdTokenChanged(this.auth,o=>{c("[PLUTO-RTC][AUTH-HOST] Firebase ID token changed",{hasUser:!!o,uid:o?.uid,providerDataCount:o?.providerData?.length||0}),this.syncDesktopAuthToken(o);}),this.desktopTokenRefreshIntervalId||(this.desktopTokenRefreshIntervalId=setInterval(()=>{this.syncDesktopAuthToken(this.auth.currentUser,true);},600*1e3));}async syncDesktopAuthToken(t,n=false){if(!M)return;let r=t?await getIdToken(t,n).catch(()=>null):null,o=t?t.refreshToken??null:null;if(r===this.lastRelayedToken&&o===this.lastRelayedRefreshToken)return;this.lastRelayedToken=r,this.lastRelayedRefreshToken=o;let i=await Promise.allSettled([Promise.resolve(M({authToken:r,refreshToken:o}))]);i[0]?.status==="rejected"&&console.warn("[PLUTO-RTC][AUTH-HOST] Failed to relay auth token to desktop backend",{message:i[0].reason?.message});}getApp(){return this.app}getCurrentUser(){return this.auth.currentUser}getAuth(){return this.auth}onAuthStateChanged(t){return c("[PLUTO-RTC][AUTH-HOST] onAuthStateChanged listener registered (via onIdTokenChanged)"),onIdTokenChanged(this.auth,t)}onIdTokenChanged(t){return c("[PLUTO-RTC][AUTH-HOST] onIdTokenChanged listener registered"),onIdTokenChanged(this.auth,t)}async getIdToken(t){return this.auth.currentUser?getIdToken(this.auth.currentUser,t?.forceRefresh??true):null}async checkForSSOToken(){if(typeof window>"u")return;let t=new URLSearchParams(window.location.search),n=new URLSearchParams(window.location.hash.startsWith("#")?window.location.hash.slice(1):window.location.hash),r=t.get("token")||n.get("token")||(t.get("custom_token")==="true"||n.get("custom_token")==="true"?t.get("id_token")||n.get("id_token"):null);if(r)try{await this.persistenceReady,await signInWithCustomToken(this.auth,r),window.history.replaceState({},document.title,window.location.pathname);}catch(o){console.error("[PLUTO-RTC][AUTH-HOST] SSO sign-in failed:",o);}}async signInWithCustomTokenValue(t){return await this.persistenceReady,(await signInWithCustomToken(this.auth,t)).user}async signInWithPluto(t){if(typeof window>"u")throw new Error("Pluto SSO requires a browser environment.");let n=t?.redirectUri||window.location.href,r=t?.authorizeBaseUrl||"https://pluto.openrtc.app/sso/authorize",o=new URL(r);o.searchParams.set("redirect_uri",n),window.location.assign(o.toString());}async waitForAuth(){if(await this.persistenceReady,!this.auth.currentUser)return new Promise(t=>{let n=onAuthStateChanged(this.auth,r=>{r&&(n(),t());});})}async signInAnonymously(){await signInAnonymously(this.auth);}async signIn(t,n){return (await signInWithEmailAndPassword(this.auth,t,n)).user}async signUp(t,n){return (await createUserWithEmailAndPassword(this.auth,t,n)).user}async signOut(){await signOut(this.auth);}async deleteAccount(){if(!this.auth.currentUser)throw new Error("No user signed in");await deleteUser(this.auth.currentUser);}async signInWithCredential(t){let n=Date.now();if(c("[PLUTO-RTC][AUTH-HOST] signInWithCredential start",{callbackId:t.callbackId,provider:t.provider,hasIdToken:!!t.idToken,hasAccessToken:!!t.accessToken,hasNonce:!!t.nonce}),t.isCustomToken){c("[PLUTO-RTC][AUTH-HOST] signInWithCredential: custom token detected, using signInWithCustomToken");try{if(Z())c("[PLUTO-RTC][AUTH-HOST] Skipping authStateReady before custom token sign-in on Tauri mobile",{callbackId:t.callbackId});else {c("[PLUTO-RTC][AUTH-HOST] Awaiting authStateReady...");try{await g(this.auth.authStateReady(),5e3,"authStateReady"),c("[PLUTO-RTC][AUTH-HOST] Auth state ready, signing in with custom token...");}catch(a){console.warn("[PLUTO-RTC][AUTH-HOST] authStateReady did not resolve in time; continuing custom token sign-in",{callbackId:t.callbackId,message:a?.message});}}let i;try{i=await g(signInWithCustomToken(this.auth,t.idToken),25e3,"signInWithCustomToken (custom token path)");}catch(a){console.warn("[PLUTO-RTC][AUTH-HOST] First custom token sign-in attempt failed; retrying once",{callbackId:t.callbackId,message:a?.message,code:a?.code}),await G(250),i=await g(signInWithCustomToken(this.auth,t.idToken),25e3,"signInWithCustomToken (custom token path retry)");}if(c("[PLUTO-RTC][AUTH-HOST] signInWithCustomToken success",{callbackId:t.callbackId,provider:t.provider,uid:i.user?.uid,elapsedMs:Date.now()-n}),i.user&&(t.displayName||t.photoURL))try{await updateProfile(i.user,{displayName:t.displayName||i.user.displayName||void 0,photoURL:t.photoURL||i.user.photoURL||void 0});}catch(a){console.warn("[PLUTO-RTC][AUTH-HOST] Failed to update custom-token user profile",{callbackId:t.callbackId,message:a?.message});}return i.user}catch(o){throw console.error("[PLUTO-RTC][AUTH-HOST] signInWithCustomToken failed",{callbackId:t.callbackId,error:o?.message,code:o?.code,stack:o?.stack,elapsedMs:Date.now()-n}),o}}let r;t.provider==="google"?r=GoogleAuthProvider.credential(t.idToken,t.accessToken):r=new OAuthProvider("apple.com").credential({idToken:t.idToken,rawNonce:t.nonce,accessToken:t.accessToken});try{let o=await g(signInWithCredential(this.auth,r),1e4,"firebase signInWithCredential");return c("[PLUTO-RTC][AUTH-HOST] signInWithCredential success",{callbackId:t.callbackId,provider:t.provider,uid:o.user?.uid,elapsedMs:Date.now()-n}),o.user}catch(o){console.warn("[PLUTO-RTC][AUTH-HOST] signInWithCredential primary path failed; trying custom token fallback",{callbackId:t.callbackId,provider:t.provider,elapsedMs:Date.now()-n,code:o?.code,message:o?.message});let i=await g(this.mintSessionTokenFromProviderToken(t),15e3,"mintSessionTokenFromProviderToken"),a=await g(signInWithCustomToken(this.auth,i),15e3,"signInWithCustomToken");return c("[PLUTO-RTC][AUTH-HOST] signInWithCustomToken fallback success",{callbackId:t.callbackId,provider:t.provider,uid:a.user?.uid,elapsedMs:Date.now()-n}),a.user}}async mintSessionTokenFromProviderToken(t){let n=httpsCallable(this.functions,"mintSessionToken");c("[PLUTO-RTC][AUTH-HOST] mintSessionToken fallback request start",{provider:t.provider,hasIdToken:!!t.idToken,hasNonce:!!t.nonce});let o=(await n({provider:t.provider,idToken:t.idToken,nonce:t.nonce})).data?.token;if(!o)throw new Error("mintSessionToken did not return a token for provider exchange");return c("[PLUTO-RTC][AUTH-HOST] mintSessionToken fallback request success",{provider:t.provider}),o}async signInWithPopup(t){if(t==="google"){let i=new GoogleAuthProvider;i.addScope("email"),i.addScope("profile"),i.setCustomParameters({prompt:"select_account"});let a=await signInWithPopup(this.auth,i);return {idToken:await getIdToken(a.user,true),refreshToken:a.user.refreshToken}}let n=new OAuthProvider("apple.com");n.addScope("email"),n.addScope("name");let r=ee(32);typeof sessionStorage<"u"&&sessionStorage.setItem("apple_auth_nonce",r),n.setCustomParameters({nonce:await te(r)});let o=await signInWithPopup(this.auth,n);return {idToken:await getIdToken(o.user,true),refreshToken:o.user.refreshToken}}async signInWithRedirect(t,n){if(t==="google"){let i=new GoogleAuthProvider;i.addScope("email"),i.addScope("profile"),i.setCustomParameters({prompt:"select_account"}),await signInWithRedirect(this.auth,i);return}let r=new OAuthProvider("apple.com");r.addScope("email"),r.addScope("name");let o=n?.nonce||ee(32);typeof sessionStorage<"u"&&sessionStorage.setItem("apple_auth_nonce",o),r.setCustomParameters({nonce:await te(o)}),await signInWithRedirect(this.auth,r);}async consumeRedirectResult(){return this.redirectResultConsumed?(c("[PLUTO-RTC][AUTH-HOST] consumeRedirectResult skipped (already consumed)"),null):this.redirectResultPromise?this.redirectResultPromise:(this.redirectResultPromise=(async()=>{try{c("[PLUTO-RTC][AUTH-HOST] consumeRedirectResult start");let t=await getRedirectResult(this.auth);if(!t)return c("[PLUTO-RTC][AUTH-HOST] consumeRedirectResult: no redirect result"),{fromRedirect:!1,user:null};this.redirectResultConsumed=!0;let n=await getIdToken(t.user,!0).catch(()=>null),r=t.providerId||t.user.providerData?.[0]?.providerId||null;return c("[PLUTO-RTC][AUTH-HOST] consumeRedirectResult success",{uid:t.user.uid,providerId:r,hasIdToken:!!n}),{fromRedirect:!0,user:t.user,providerId:r,idToken:n}}finally{this.redirectResultPromise=null;}})(),this.redirectResultPromise)}async startGoogleSignIn(){await this.signInWithRedirect("google");}async startAppleSignIn(){await this.signInWithRedirect("apple");}async mintSessionToken(){let r=(await httpsCallable(this.functions,"mintSessionToken")()).data;if(!r?.token)throw new Error("mintSessionToken did not return a token");return r.token}},O=null;function Ne(){return O||(O=new _),O}var Nt=new Proxy({},{get(e,t,n){let r=Ne(),o=r[t];return typeof o=="function"?o.bind(r):o}});
2
+ export{yt as A,ft as B,ht as C,bt as D,z as E,Dt as F,Ne as G,Nt as H,N as a,He as b,I as c,T as d,Be as e,Fe as f,We as g,ie as h,H as i,Ke as j,Ge as k,ze as l,$e as m,Ye as n,Ve as o,A as p,rt as q,ot as r,it as s,ct as t,G as u,dt as v,ut as w,pt as x,mt as y,gt as z};