openrtc 2.5.2 → 2.5.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{Connection-CTpuImO-.d.ts → Connection-CovQdc8E.d.ts} +30 -5
- package/dist/{DelegatingRuntimeAdapter-D67Ozqo3.d.ts → DelegatingRuntimeAdapter-3ykiNvyh.d.ts} +3 -2
- package/dist/{IpcRuntimeAdapter-Ddx0MtSI.d.ts → IpcRuntimeAdapter-BkM_1HyL.d.ts} +12 -2
- package/dist/WasmBridge-UZC7G4NP.js +1 -0
- package/dist/{assembly-LOFcpH3S.d.ts → assembly-C235UKSS.d.ts} +3 -2
- package/dist/{capabilities-CmzzxSvW.d.ts → capabilities-CdZpAKvE.d.ts} +1 -1
- package/dist/chunk-25CN4MLA.js +2 -0
- package/dist/chunk-2ESWBXLF.js +1 -0
- package/dist/{chunk-TZLNKQNJ.js → chunk-42TNJH5S.js} +1 -1
- package/dist/chunk-4CC6YIGG.js +1 -0
- package/dist/chunk-4J4F32QT.js +1 -0
- package/dist/{chunk-J7NBMQQA.js → chunk-CHT46RA7.js} +1 -1
- package/dist/chunk-VC7TGJFS.js +2 -0
- package/dist/{chunk-EFTDXE6M.js → chunk-WMA4OMJL.js} +1 -1
- package/dist/{chunk-XTYALGJN.js → chunk-XMYBBLYK.js} +1 -1
- package/dist/coreClient.d.ts +3 -3
- package/dist/coreClient.js +1 -1
- package/dist/index.d.ts +5 -5
- package/dist/index.js +1 -1
- package/dist/ipcFactory-2WMR4PH6.js +1 -0
- package/dist/native.d.ts +5 -5
- package/dist/native.js +1 -1
- package/dist/node.d.ts +5 -5
- package/dist/node.js +2 -2
- package/dist/{openrtc-SQF7H4ZE.js → openrtc-UBIKDAZ5.js} +2 -2
- package/dist/openrtc_bg.wasm +0 -0
- package/dist/{room-A2FMQRNZ.js → room-2MUFAJ4M.js} +1 -1
- package/dist/runtime/WasmRuntimeAdapter.d.ts +3 -3
- package/dist/runtime/WasmRuntimeAdapter.js +1 -1
- package/dist/runtime/device-status.d.ts +1 -1
- package/dist/runtime/factories.d.ts +6 -5
- package/dist/runtime/factories.js +1 -1
- package/dist/runtime/index.d.ts +9 -9
- package/dist/runtime/index.js +1 -1
- package/dist/server-browser.d.ts +4 -4
- package/dist/server.d.ts +4 -4
- package/dist/server.js +1 -1
- package/dist/service-node.d.ts +4 -4
- package/dist/service-node.js +1 -1
- package/dist/testing/native.d.ts +4 -4
- package/dist/testing/native.js +1 -1
- package/dist/testing.d.ts +4 -4
- package/dist/testing.js +1 -1
- package/dist/transport/index.d.ts +2 -2
- package/dist/{types-Cyc-mPjk.d.ts → types-C6SMXBzJ.d.ts} +1 -1
- package/native/darwin-arm64/openrtc-node-host +0 -0
- package/native/darwin-arm64/openrtc-node-host.manifest.json +4 -4
- package/native/darwin-x64/openrtc-node-host +0 -0
- package/native/darwin-x64/openrtc-node-host.manifest.json +4 -4
- package/native/linux-x64/openrtc-node-host +0 -0
- package/native/linux-x64/openrtc-node-host.manifest.json +4 -4
- package/package.json +1 -1
- package/dist/WasmBridge-LWMCETW4.js +0 -1
- package/dist/chunk-6Q2LAXM4.js +0 -1
- package/dist/chunk-AAZPQQXX.js +0 -2
- package/dist/chunk-FB5M6GIW.js +0 -2
- package/dist/chunk-PLIWPC45.js +0 -1
- package/dist/chunk-VTYVIKTM.js +0 -1
- package/dist/ipcFactory-PDVLUG2W.js +0 -1
|
@@ -184,6 +184,16 @@ interface ScopedChannelOptions {
|
|
|
184
184
|
peerNodeId?: string;
|
|
185
185
|
deviceId?: string | null;
|
|
186
186
|
ticket?: string;
|
|
187
|
+
/**
|
|
188
|
+
* Product-issued bearer for a peer already known to Rust/WASM discovery.
|
|
189
|
+
* OpenRTC binds it to the owner-cached endpoint and presents it without
|
|
190
|
+
* projecting endpoint tickets through application state.
|
|
191
|
+
*/
|
|
192
|
+
admissionToken?: string;
|
|
193
|
+
/** User avenue authorized to reveal the target device for this grant. */
|
|
194
|
+
admissionPeerUserId?: string;
|
|
195
|
+
admissionMaxConnections?: number;
|
|
196
|
+
admissionExpiresAtMs?: number;
|
|
187
197
|
scope: RuntimePeerScope;
|
|
188
198
|
channelId: string;
|
|
189
199
|
timeoutMs?: number;
|
|
@@ -354,6 +364,18 @@ interface CoordinationSignalingStore {
|
|
|
354
364
|
sendMessage(targetId: string, payload: string, state?: string, replyPayload?: string): Promise<string>;
|
|
355
365
|
pollMessages(targetId: string): Promise<SignalingEnvelope[]>;
|
|
356
366
|
watchFriendDevices(friendUserIds: string[], callback: (devices: Map<string, Device[]>) => void): () => void;
|
|
367
|
+
waitForFriendDevice(friendUserId: string, deviceId: string, timeoutMs?: number): Promise<Device>;
|
|
368
|
+
/**
|
|
369
|
+
* Supply authoritative native-session identity for read-only friend
|
|
370
|
+
* avenues when Rust owns the writable local presence socket.
|
|
371
|
+
*/
|
|
372
|
+
setFriendObservationIdentity?(input: {
|
|
373
|
+
localNodeId: string;
|
|
374
|
+
ticket: string;
|
|
375
|
+
ttlMs: number;
|
|
376
|
+
metadata?: string;
|
|
377
|
+
deviceName?: string;
|
|
378
|
+
}): void;
|
|
357
379
|
updateFriendTicket(friendTicket: string | null): Promise<void>;
|
|
358
380
|
handleScopeChange(): Promise<void>;
|
|
359
381
|
setHostAvailability?(input: {
|
|
@@ -837,7 +859,12 @@ interface NativeConnectResult {
|
|
|
837
859
|
}
|
|
838
860
|
interface NativeConnectParams {
|
|
839
861
|
deviceId?: string | null;
|
|
840
|
-
endpointTicket
|
|
862
|
+
endpointTicket?: string;
|
|
863
|
+
admissionToken?: string;
|
|
864
|
+
admissionScope?: string;
|
|
865
|
+
admissionPeerUserId?: string;
|
|
866
|
+
admissionMaxConnections?: number;
|
|
867
|
+
admissionExpiresAtMs?: number;
|
|
841
868
|
/** Total native dial/admission budget. The host command must enforce it. */
|
|
842
869
|
timeoutMs?: number;
|
|
843
870
|
}
|
|
@@ -1241,6 +1268,7 @@ interface ISignalingBackend {
|
|
|
1241
1268
|
getPeerSession?(id: string): Promise<PeerSessionSnapshot | null>;
|
|
1242
1269
|
listPeerSessions?(): Promise<PeerSessionSnapshot[]>;
|
|
1243
1270
|
waitForSettledPeer?(id: string, timeoutMs?: number): Promise<PeerSessionSnapshot | null>;
|
|
1271
|
+
waitForSettledScope?(scope: string, timeoutMs?: number): Promise<PeerSessionSnapshot | null>;
|
|
1244
1272
|
resolvePeerIdentity?(id: string): Promise<ResolvedPeerIdentity>;
|
|
1245
1273
|
resolvePeerRecords?(id: string): Promise<ManagedConnectionRecord[]>;
|
|
1246
1274
|
updateDevice(deviceId: string, updates: {
|
|
@@ -1322,10 +1350,7 @@ interface ISignalingBackend {
|
|
|
1322
1350
|
retireOpenRtcMediaReceiver?(publicationId: string, mediaGeneration: number): void | Promise<void>;
|
|
1323
1351
|
decodeOpenRtcMediaChunk?(encoded: Uint8Array): PortableMediaChunk | Promise<PortableMediaChunk>;
|
|
1324
1352
|
decodeOpenRtcMediaControl?(encoded: Uint8Array): PortableMediaControl | Promise<PortableMediaControl>;
|
|
1325
|
-
connectToDevice?(params:
|
|
1326
|
-
deviceId?: string | null;
|
|
1327
|
-
endpointTicket: string;
|
|
1328
|
-
}): Promise<NativeConnectResult>;
|
|
1353
|
+
connectToDevice?(params: NativeConnectParams): Promise<NativeConnectResult>;
|
|
1329
1354
|
/**
|
|
1330
1355
|
* Optional backchannel so a backend (e.g. WasmBridge) can access the narrow
|
|
1331
1356
|
* facade surface needed to escalate runtime transport dials into registered
|
package/dist/{DelegatingRuntimeAdapter-D67Ozqo3.d.ts → DelegatingRuntimeAdapter-3ykiNvyh.d.ts}
RENAMED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { K as DiscoveryMode, N as AuthMode, O as SignalingMode, Q as ClientOptions, T as ExplicitFileDataSendParams, U as ISignalingBackend, V as RuntimeIdentity, F as AuthContext, W as RoomMember, X as Device, Y as DeviceStatusSnapshot, k as PeerSessionSnapshot, n as ResolvedPeerIdentity, Z as ManagedConnectionRecord, _ as SignalingEnvelope, $ as DeviceEvent, a0 as DesiredPeerProjection, a1 as SignalingSession, a2 as SessionEvent, a3 as LocalDeviceInfo, a4 as NativeManagedSessionStartResult, g as ProtocolName, G as GrantScope, a5 as BackendPeerBiStream, a6 as BackendPeerUniStream, a7 as PortableMediaPublish, a8 as PortableMediaPublicationStart, a9 as PortableMediaSample, aa as PortableMediaChunk, ab as PortableMediaControl, ac as NativeConnectParams, ad as NativeConnectResult, ae as BackendConnectionState, af as NativePeerDataEvent } from './Connection-
|
|
2
|
-
import { R as RuntimeCapabilities } from './capabilities-
|
|
1
|
+
import { K as DiscoveryMode, N as AuthMode, O as SignalingMode, Q as ClientOptions, T as ExplicitFileDataSendParams, U as ISignalingBackend, V as RuntimeIdentity, F as AuthContext, W as RoomMember, X as Device, Y as DeviceStatusSnapshot, k as PeerSessionSnapshot, n as ResolvedPeerIdentity, Z as ManagedConnectionRecord, _ as SignalingEnvelope, $ as DeviceEvent, a0 as DesiredPeerProjection, a1 as SignalingSession, a2 as SessionEvent, a3 as LocalDeviceInfo, a4 as NativeManagedSessionStartResult, g as ProtocolName, G as GrantScope, a5 as BackendPeerBiStream, a6 as BackendPeerUniStream, a7 as PortableMediaPublish, a8 as PortableMediaPublicationStart, a9 as PortableMediaSample, aa as PortableMediaChunk, ab as PortableMediaControl, ac as NativeConnectParams, ad as NativeConnectResult, ae as BackendConnectionState, af as NativePeerDataEvent } from './Connection-CovQdc8E.js';
|
|
2
|
+
import { R as RuntimeCapabilities } from './capabilities-CdZpAKvE.js';
|
|
3
3
|
|
|
4
4
|
/** Host-neutral configuration shared by browser/WASM and native/IPC adapters. */
|
|
5
5
|
interface RuntimeBridgeOptions {
|
|
@@ -58,6 +58,7 @@ declare abstract class DelegatingRuntimeAdapter implements ISignalingBackend {
|
|
|
58
58
|
getPeerSession(id: string): Promise<PeerSessionSnapshot | null>;
|
|
59
59
|
listPeerSessions(): Promise<PeerSessionSnapshot[]>;
|
|
60
60
|
waitForSettledPeer(id: string, timeoutMs?: number): Promise<PeerSessionSnapshot | null>;
|
|
61
|
+
waitForSettledScope(scope: string, timeoutMs?: number): Promise<PeerSessionSnapshot | null>;
|
|
61
62
|
resolvePeerIdentity(id: string): Promise<ResolvedPeerIdentity>;
|
|
62
63
|
resolvePeerRecords(id: string): Promise<ManagedConnectionRecord[]>;
|
|
63
64
|
updateDevice(deviceId: string, updates: {
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { R as RuntimeBridgeOptions, D as DelegatingRuntimeAdapter } from './DelegatingRuntimeAdapter-
|
|
1
|
+
import { R as RuntimeBridgeOptions, D as DelegatingRuntimeAdapter } from './DelegatingRuntimeAdapter-3ykiNvyh.js';
|
|
2
2
|
import { P as PlutoIpcBridge } from './ipc-DgzKqHH3.js';
|
|
3
|
-
import { ae as BackendConnectionState, af as NativePeerDataEvent } from './Connection-
|
|
3
|
+
import { ae as BackendConnectionState, af as NativePeerDataEvent, X as Device } from './Connection-CovQdc8E.js';
|
|
4
4
|
|
|
5
5
|
interface NativeIpcBridgeOptions extends RuntimeBridgeOptions {
|
|
6
6
|
ipcBridge?: PlutoIpcBridge;
|
|
@@ -34,6 +34,7 @@ interface NativeProjectedStreamSource {
|
|
|
34
34
|
incoming_streams(): Promise<ReadableStream<unknown>>;
|
|
35
35
|
onStateChange(callback: (state: BackendConnectionState) => void): () => void;
|
|
36
36
|
onPeerMessage(callback: (event: NativePeerDataEvent) => void): () => void;
|
|
37
|
+
onDevices(callback: (devices: Device[]) => void): () => void;
|
|
37
38
|
isCurrentTransport(endpointId: string, transportStableId: bigint): Promise<boolean>;
|
|
38
39
|
}
|
|
39
40
|
type NativeRootProjectionEvent = {
|
|
@@ -48,17 +49,26 @@ type NativeRootProjectionEvent = {
|
|
|
48
49
|
kind: 'stream';
|
|
49
50
|
capabilityKeys: readonly string[];
|
|
50
51
|
payload: unknown;
|
|
52
|
+
} | {
|
|
53
|
+
kind: 'devices';
|
|
54
|
+
capabilityKeys: readonly string[];
|
|
55
|
+
payload: {
|
|
56
|
+
identityId: string;
|
|
57
|
+
devices: Device[];
|
|
58
|
+
};
|
|
51
59
|
};
|
|
52
60
|
declare class NativeProjectionBroker {
|
|
53
61
|
private host;
|
|
54
62
|
private readonly consumers;
|
|
55
63
|
private hostReader;
|
|
56
64
|
private hostPump;
|
|
65
|
+
private consecutiveEstablishedFaults;
|
|
57
66
|
private closed;
|
|
58
67
|
register(capabilityKey: string, host: NativeProjectionHost): NativeProjectedStreamSource;
|
|
59
68
|
unregister(capabilityKey: string): void;
|
|
60
69
|
private subscribeState;
|
|
61
70
|
private subscribePeerData;
|
|
71
|
+
private subscribeDevices;
|
|
62
72
|
private requireConsumer;
|
|
63
73
|
private currentHost;
|
|
64
74
|
private incomingStreams;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export{b as WasmBridge,a as loadBrowserWasmRuntimeModule}from'./chunk-2ESWBXLF.js';import'./chunk-AYHD4X2R.js';import'./chunk-25CN4MLA.js';import'./chunk-XMYBBLYK.js';import'./chunk-OT7IPLZE.js';import'./chunk-OWKAJPOI.js';import'./chunk-CNAW5BZ3.js';import'./chunk-CCCYE3XN.js';import'./chunk-N6LGTNUI.js';import'./chunk-JPBW67B3.js';import'./chunk-2GX6GB6L.js';
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { h as RuntimePeerState, r as ConnectionState, l as PeerReadiness, i as PeerConnectOptions, j as Connection, I as IncomingStream, G as GrantScope, H as RuntimeClientOptions, U as ISignalingBackend, aw as RuntimeAuthIdentity, F as AuthContext, g as ProtocolName, L as LocalDeviceInfo, z as DeviceProfile, aj as BrowserProtocolStore, ak as NamespaceDescriptor, al as IrohMutationReceipt, am as IrohDocEntry, p as RuntimeDevice, M as ManagedOptions, u as ManagedSession, D as DeviceStatus, x as ConnectDeviceHooks, y as ConnectDeviceOptions, w as ConnectDeviceResult, v as DeviceConnectOptions, Z as ManagedConnectionRecord, k as PeerSessionSnapshot, n as ResolvedPeerIdentity, ax as RuntimeSession, ay as AppLimits, J as JoinRoomOptions, B as RuntimeRoomMember, az as ConnectionTarget, S as ScopedChannelOptions, q as ScopedLogicalChannel, o as PeerStreamOptions, ac as NativeConnectParams, ad as NativeConnectResult, A as RawConnection, C as ChannelDescriptor, T as ExplicitFileDataSendParams, aA as PresenceLoopOptions, b as RoomArchitectureSnapshot, c as RoomAuthorityAssignment, m as RuntimePeerHealth, s as ReadinessOptions, t as ConnectionEvent } from './Connection-
|
|
2
|
-
import { R as RuntimeCapabilities, C as CapabilityProfile } from './capabilities-
|
|
1
|
+
import { h as RuntimePeerState, r as ConnectionState, l as PeerReadiness, i as PeerConnectOptions, j as Connection, I as IncomingStream, G as GrantScope, H as RuntimeClientOptions, U as ISignalingBackend, aw as RuntimeAuthIdentity, F as AuthContext, g as ProtocolName, L as LocalDeviceInfo, z as DeviceProfile, aj as BrowserProtocolStore, ak as NamespaceDescriptor, al as IrohMutationReceipt, am as IrohDocEntry, p as RuntimeDevice, M as ManagedOptions, u as ManagedSession, D as DeviceStatus, x as ConnectDeviceHooks, y as ConnectDeviceOptions, w as ConnectDeviceResult, v as DeviceConnectOptions, Z as ManagedConnectionRecord, k as PeerSessionSnapshot, n as ResolvedPeerIdentity, ax as RuntimeSession, ay as AppLimits, J as JoinRoomOptions, B as RuntimeRoomMember, az as ConnectionTarget, S as ScopedChannelOptions, q as ScopedLogicalChannel, o as PeerStreamOptions, ac as NativeConnectParams, ad as NativeConnectResult, A as RawConnection, C as ChannelDescriptor, T as ExplicitFileDataSendParams, aA as PresenceLoopOptions, b as RoomArchitectureSnapshot, c as RoomAuthorityAssignment, m as RuntimePeerHealth, s as ReadinessOptions, t as ConnectionEvent } from './Connection-CovQdc8E.js';
|
|
2
|
+
import { R as RuntimeCapabilities, C as CapabilityProfile } from './capabilities-CdZpAKvE.js';
|
|
3
3
|
|
|
4
4
|
/**
|
|
5
5
|
* Coalesced peer reconciliation scheduler and full reconcile orchestration.
|
|
@@ -494,6 +494,7 @@ declare class RuntimeClient {
|
|
|
494
494
|
getPeerSession(id: string): Promise<PeerSessionSnapshot | null>;
|
|
495
495
|
listPeerSessions(): Promise<PeerSessionSnapshot[]>;
|
|
496
496
|
waitForConnectedPeer(id: string, timeoutMs?: number): Promise<PeerSessionSnapshot | null>;
|
|
497
|
+
waitForConnectedScope(scope: string, timeoutMs?: number): Promise<PeerSessionSnapshot | null>;
|
|
497
498
|
getPeerReadiness(id: string, timeoutMs?: number): Promise<PeerReadiness>;
|
|
498
499
|
resolvePeerIdentity(id: string): Promise<ResolvedPeerIdentity>;
|
|
499
500
|
resolveStreamPeer(remoteNodeId: string): Promise<ResolvedPeerIdentity>;
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { g as ProtocolName, f as RouteOptimization } from './Connection-
|
|
1
|
+
import { g as ProtocolName, f as RouteOptimization } from './Connection-CovQdc8E.js';
|
|
2
2
|
|
|
3
3
|
type RuntimeAdapterKind = 'browser-wasm' | 'native-ipc' | 'tauri-ipc' | 'unknown';
|
|
4
4
|
type CapabilityMaturity = 'stable' | 'preview' | 'support-only' | 'unavailable';
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import {b as b$1,d,l}from'./chunk-OT7IPLZE.js';import {a,c,e}from'./chunk-N6LGTNUI.js';import*as x from'tweetnacl';function kt(){throw new Error("[OpenRTC] The rollback-only Firebase auth host is not installed. OpenRTC 2.0 applications must supply an AuthProvider; legacy runtimes must import openrtc/auth explicitly.");}var Me="openrtc-trust";var oe="identity",R="managed-room-keys",I="managed-room-state";function Ee(){if(typeof globalThis.indexedDB>"u")throw new Error("[OpenRTC] Managed rooms require durable IndexedDB storage.");return globalThis.indexedDB}function ke(){return new Promise((t,e)=>{let n=Ee().open(Me,2);n.onupgradeneeded=()=>{let i=n.result;i.objectStoreNames.contains(oe)||i.createObjectStore(oe),i.objectStoreNames.contains(R)||i.createObjectStore(R),i.objectStoreNames.contains(I)||i.createObjectStore(I);},n.onsuccess=()=>t(n.result),n.onerror=()=>e(n.error??new Error("managed room database failed")),n.onblocked=()=>e(new Error("managed room database upgrade is blocked"));})}function W(t){return new Promise((e,n)=>{t.onsuccess=()=>e(t.result),t.onerror=()=>n(t.error??new Error("managed room storage failed"));})}function P(t){return new Promise((e,n)=>{t.oncomplete=()=>e(),t.onerror=()=>n(t.error??new Error("managed room storage failed")),t.onabort=()=>n(t.error??new Error("managed room storage aborted"));})}function _e(t,e,n){return `${t}:${e}:${n}`}function De(t,e){return `${t}:${e}`}function se(t){return new TextEncoder().encode(`openrtc-managed-room-state-v1:${t}`)}async function xe(t,e){let n=t.transaction(R,"readonly"),i=P(n),r=await W(n.objectStore(R).get(e));if(await i,r)return r;let o=await crypto.subtle.generateKey({name:"AES-GCM",length:256},false,["encrypt","decrypt"]),a=t.transaction(R,"readwrite"),s=P(a);a.objectStore(R).add(o,e);try{return await s,o}catch{let c=t.transaction(R,"readonly"),d=P(c),l=await W(c.objectStore(R).get(e));if(await d,!l)throw new Error("[OpenRTC] Managed room wrapping key could not be persisted.");return l}}function Ne(t){let e=t;return e?.schemaVersion===1&&e.wrappedKey instanceof Uint8Array&&e.wrappingNonce instanceof Uint8Array&&e.wrappingNonce.byteLength===12&&(e.sealedState===void 0||e.sealedState instanceof Uint8Array)?e:null}async function q(t,e,n){let i=await ke(),r=_e(t,e,n);try{let o=await xe(i,De(t,e)),a=i.transaction(I,"readonly"),s=P(a),c=Ne(await W(a.objectStore(I).get(r)));await s;let d,l;if(c){let u=await crypto.subtle.decrypt({name:"AES-GCM",iv:c.wrappingNonce,additionalData:se(r)},o,c.wrappedKey).catch(()=>{throw new Error("[OpenRTC] Managed room state key authentication failed.")});if(d=new Uint8Array(u),d.byteLength!==32)throw new Error("[OpenRTC] Managed room state key is invalid.");l=c;}else {d=crypto.getRandomValues(new Uint8Array(32));let u=crypto.getRandomValues(new Uint8Array(12)),f=new Uint8Array(await crypto.subtle.encrypt({name:"AES-GCM",iv:u,additionalData:se(r)},o,d));l={schemaVersion:1,wrappingNonce:u,wrappedKey:f};let y=i.transaction(I,"readwrite"),m=P(y);y.objectStore(I).add(l,r),await m;}return {wrappingKey:d,sealedState:l.sealedState,async persist(u){if(!(u instanceof Uint8Array)||u.byteLength===0)throw new Error("[OpenRTC] Managed room sealed state is invalid.");let f=i.transaction(I,"readwrite"),y=P(f);f.objectStore(I).put({...l,sealedState:u},r),await y,l={...l,sealedState:u};},close(){d.fill(0),i.close();}}}catch(o){throw i.close(),o}}var Oe=3e4,Ke=5*6e4,Le=3e4,He=100,Ue=48*1024,ae=12,Be=10*6e4,Fe=5*6e4,H=15e3,je=15e3,ze=1e3,ce=250;function de(t){let e=[...new Set(t.map(n=>String(n??"").trim().toLowerCase()).filter(Boolean))].sort();if(e.length>ce)throw new Error(`Coordination excluded-peer set exceeds ${ce} devices.`);return e}var We="openrtc.v2",qe="openrtc.auth.";function le(t){try{let e=t.split(".")[1];if(!e)return null;let n=e.replace(/-/g,"+").replace(/_/g,"/").padEnd(Math.ceil(e.length/4)*4,"="),i=JSON.parse(globalThis.atob(n));return typeof i.jti=="string"&&i.jti.length>0?i.jti:null}catch{return null}}var h=class extends Error{constructor(n,i,r){super(n);this.retryable=i;this.gatewayCode=r;this.name="CoordinationConnectError";this.code=a.COORDINATION_DISCONNECTED;this.plane="coordination";}},U=class extends Error{constructor(n,i,r){let o=e({code:n,message:i,retryable:r});super(`Coordination gateway ${n}: ${i}`);this.name="CoordinationGatewayProtocolError";this.code=o.code||n||a.COORDINATION_PROTOCOL,this.retryable=r,this.plane=o.plane;}};function ue(t){return t instanceof h&&/\bstale-budget\b/i.test(t.message)}function _(t){if(!t||typeof t!="object")return false;let e=t;return e.gatewayCode==="credential-revoked"||e.code==="credential-revoked"||e.reason==="device-certificate-revoked"}function pe(t){if(_(t))return true;if(typeof t!="object"||t===null)return false;let e=t;if(e.retryable===false)return true;let n=e.status??e.statusCode,i=typeof n=="number"?n:Number.NaN;if(Number.isInteger(i)&&i>=400&&i<500&&![408,425,429].includes(i))return true;let r=String(e.code??"");return ["functions/unauthenticated","functions/permission-denied","functions/invalid-argument","functions/failed-precondition","functions/resource-exhausted","unauthenticated","permission-denied","invalid-argument","failed-precondition","resource-exhausted"].includes(r)}function $e(t){let e=new Uint32Array(1);return crypto.getRandomValues(e),Math.max(1,Math.round(t*(.75+e[0]/4294967295*.5)))}function v(t){if(typeof crypto.randomUUID=="function")return `${t}:${crypto.randomUUID()}`;let e=new Uint8Array(16);crypto.getRandomValues(e);let n=Array.from(e,i=>i.toString(16).padStart(2,"0")).join("");return `${t}:${n}`}async function Ve(t){let e=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(t)),n="";for(let i of new Uint8Array(e))n+=String.fromCharCode(i);return btoa(n).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,"")}function k(t){if(!/^[A-Za-z0-9_-]+$/.test(t))throw new Error("[OpenRTC] Managed room payload encoding is invalid.");let e=t.replace(/-/g,"+").replace(/_/g,"/"),n=atob(e.padEnd(Math.ceil(e.length/4)*4,"="));return Uint8Array.from(n,i=>i.charCodeAt(0))}function Je(t,e,n){let i=new URL(t);if(i.search||i.hash||i.username||i.password)throw new Error("[OpenRTC] Coordination gateway endpoint must not contain credentials, query, or fragment.");if(i.protocol==="https:")i.protocol="wss:";else if(i.protocol==="http:")i.protocol="ws:";else if(i.protocol!=="wss:"&&i.protocol!=="ws:")throw new Error("[OpenRTC] Coordination gateway endpoint must use HTTPS/WSS.");return i.pathname=`${i.pathname.replace(/\/+$/,"")}/v${n}/connect/${e}`,i.toString()}function he(t){let e=new URL(t);return e.protocol==="wss:"&&(e.protocol="https:"),e.protocol==="ws:"&&(e.protocol="http:"),e.origin}var B=class t{constructor(e){this.options=e;this.runtimeInstanceId=v("runtime");this.socket=null;this.socketReady=false;this.activeGrantToken=null;this.activeGrantJti=null;this.activeAvenue=null;this.activeGrantExpiresAtMs=0;this.activeGrantProtocolVersion=1;this.leaseRefreshMode="off";this.pendingLeaseRefreshKey=null;this.authenticationRefreshTail=Promise.resolve();this.authenticationRefreshes=new Map;this.connectPromise=null;this.desiredPresence=null;this.friendObservationPresence=null;this.desiredExcludedPeers=[];this.devices=new Map;this.sparseMembers=new Map;this.sparseRoutes=new Map;this.pendingMembershipPageSnapshot=null;this.sparseTopologyRevision=0;this.roomArchitectureSnapshot=null;this.roomAuthorityAssignment=null;this.roomAuthorityAssignmentExpiry=null;this.roomEncryptionEpoch=0;this.managedWasmClient=null;this.peerAdmissionRuntime=null;this.peerAdmissionScope=null;this.peerAdmissionRevision=0;this.managedStateProvider=q;this.managedState=null;this.managedInitialization=null;this.managedActions=Promise.resolve();this.managedPublishQueue=[];this.managedPublishScheduled=false;this.managedMessageListeners=new Set;this.deviceListeners=new Set;this.architectureListeners=new Set;this.authorityAssignmentListeners=new Set;this.deviceStreams=new Set;this.sessionStreams=new Set;this.pendingAcks=new Map;this.pendingMessages=[];this.roomConnections=new Map;this.friendConnections=new Map;this.reconnectTimer=null;this.authRefreshTimer=null;this.keepaliveTimer=null;this.pendingAuthRefresh=null;this.budgetRenewalPromise=null;this.budgetRenewalEpoch=0;this.reconnectAttempt=0;this.reconnectOutageStartedAtMs=null;this.reconnectCircuitOpen=false;this.hostAvailable=true;this.connectionReadyWaiters=new Set;this.hostResumeReconnectPromise=null;this.lastHostResumeReconnectAtMs=0;this.desiredPresenceRevision=0;this.appliedPresenceRevision=0;this.stopped=false;this.credentialRevoked=false;if(this.initialExcludedPeers=de(e.initialExcludedPeers??[]),this.desiredExcludedPeers=[...this.initialExcludedPeers],e.gateway.environment!=="staging"&&e.gateway.environment!=="production")throw new Error("[OpenRTC] Coordination gateway environment is invalid.");let n=new URL(e.gateway.endpoint),i=n.hostname==="127.0.0.1"||n.hostname==="localhost"||n.hostname==="[::1]",r=n.protocol==="https:"||n.protocol==="wss:",o=e.gateway.testingAllowInsecureLoopback===true&&i&&(n.protocol==="http:"||n.protocol==="ws:");if(!r&&!o)throw new Error("[OpenRTC] Coordination gateway requires HTTPS/WSS.");if(n.username||n.password||n.search||n.hash)throw new Error("[OpenRTC] Coordination gateway credentials and parameters cannot be supplied in its URL.")}async updatePresence(e,n,i,r,o,a){let s=this.desiredPresence;if(i&&this.options.roomArchitecture==="authority"){let l=this.options.avenueOverride;if(l?.kind!=="room"||!this.peerAdmissionRuntime)throw new Error("[OpenRTC] Authority rooms require Rust peer admission support.");let u=`v2:room:${l.id}`;this.peerAdmissionRuntime.__requireScopePeerAdmission(u),this.peerAdmissionScope=u;}this.desiredPresence={localNodeId:e,ticket:n,online:i,ttlMs:r,metadata:o,deviceName:a?.trim()||this.options.getDefaultDeviceName()},(!s||s.localNodeId!==e||s.ticket!==n||s.online!==i||s.ttlMs!==r||s.metadata!==o||s.deviceName!==this.desiredPresence.deviceName)&&(this.desiredPresenceRevision+=1,this.reconnectCircuitOpen=false,this.reconnectAttempt=0,this.reconnectOutageStartedAtMs=null);for(let l of this.friendConnections.values())l.updatePresence(e,n,i,r,o,this.desiredPresence.deviceName).catch(()=>{});let d=this.desiredPresenceRevision;try{await this.ensureConnected();}catch(l){if(!(l instanceof h)||!l.retryable)throw l;await this.waitForConnectionReady();}this.appliedPresenceRevision>=d||(s&&s.ticket!==n&&await this.refreshAuthentication(),await this.sendOperation({v:1,type:"presence.upsert",idempotencyKey:v("presence"),ttlMs:r,device:this.gatewayDevice(this.desiredPresence)}),this.appliedPresenceRevision=Math.max(this.appliedPresenceRevision,d));}async setOffline(e){this.desiredPresence&&(this.desiredPresence.online=false,this.socket?.readyState===WebSocket.OPEN&&await this.sendOperation({v:1,type:"presence.offline",idempotencyKey:v("offline")}));}async reconnectAfterHostResume(){if(this.desiredPresence){if(this.hostResumeReconnectPromise)return this.hostResumeReconnectPromise;if(!(Date.now()-this.lastHostResumeReconnectAtMs<je)){this.lastHostResumeReconnectAtMs=Date.now(),this.hostResumeReconnectPromise=(async()=>{(this.socket?.readyState===WebSocket.OPEN||this.socketReady)&&this.stopSocket(),await this.ensureConnected();})();try{await this.hostResumeReconnectPromise;}finally{this.hostResumeReconnectPromise=null;}}}}setHostAvailability(e){let n=e.available&&!this.hostAvailable;this.hostAvailable=e.available;for(let i of this.roomConnections.values())i.setHostAvailability(e);for(let i of this.friendConnections.values())i.setHostAvailability(e);if(!e.available){this.reconnectTimer&&clearTimeout(this.reconnectTimer),this.reconnectTimer=null;return}n&&this.desiredPresence&&!this.socketReady&&!this.connectPromise&&!this.reconnectCircuitOpen&&!this.stopped&&this.ensureConnected().catch(i=>this.scheduleReconnect(i));}async updateDevice(e,n){if(e!==this.options.getLocalDeviceId())throw new Error("A coordination socket can update only its local device.");let i=n;if(n.excludedPeers!==void 0){let r=de(n.excludedPeers);this.desiredExcludedPeers=r,i={...n,excludedPeers:r};}await this.ensureConnected(),await this.sendOperation({v:1,type:"device.patch",idempotencyKey:v("device-patch"),patch:i});}async deleteDevice(e){if(this.options.credentialPurpose!=="device-control"&&(!this.socketReady||this.socket?.readyState!==WebSocket.OPEN)){let n=new t({...this.options,credentialPurpose:"device-control"});try{await n.deleteDevice(e);}finally{n.stopAuthActivity();}return}await this.ensureConnected();try{await this.sendOperation({v:1,type:"device.delete",idempotencyKey:v("device-delete"),targetDeviceId:e});}finally{this.options.credentialPurpose==="device-control"&&this.stopSocket();}}async cleanupStaleDevices(){}async searchDevices(e){return this.snapshot(e)}async listDevices(e){return this.snapshot(e)}onDevicesChange(e,n){let i=r=>e(n?r.filter(o=>o.nodeId!==n):r);return this.deviceListeners.add(i),i(this.snapshot()),this.desiredPresence&&this.ensureConnected().catch(()=>{}),()=>this.deviceListeners.delete(i)}onRoomArchitectureChange(e){return this.architectureListeners.add(e),this.roomArchitectureSnapshot&&e({...this.roomArchitectureSnapshot}),()=>this.architectureListeners.delete(e)}onRoomAuthorityAssignmentChange(e){return this.authorityAssignmentListeners.add(e),e(this.roomAuthorityAssignmentSnapshot()),()=>this.authorityAssignmentListeners.delete(e)}async publishAuthorityAssignment(e){await this.ensureConnected(),await this.sendOperation({v:1,type:"authority.assignment.publish",idempotencyKey:v("authority-assignment"),assignment:e.assignment,signature:e.signature});}setWasmClient(e){this.setManagedRoomRuntime(e,q);}setManagedRoomRuntime(e,n){let i=e;this.peerAdmissionRuntime=i&&typeof i.__requireScopePeerAdmission=="function"&&typeof i.__updateScopePeerAdmission=="function"?i:null;let r=e;this.managedWasmClient=r&&typeof r.__initManagedRoomGroup=="function"&&typeof r.__handleManagedRoomPreparePage=="function"&&typeof r.__handleManagedRoomArtifactChunk=="function"&&typeof r.__sealManagedRoomPayload=="function"&&typeof r.__openManagedRoomPayload=="function"&&typeof r.__forgetManagedRoomGroup=="function"?r:null,this.managedStateProvider=n,this.roomArchitectureSnapshot?.effective==="managed"&&this.enqueueManagedWork(()=>this.ensureManagedGroupInitialized());}onManagedRoomMessage(e){return this.managedMessageListeners.add(e),()=>this.managedMessageListeners.delete(e)}async publishManagedRoomMessage(e){return new Promise((n,i)=>{this.managedPublishQueue.push({input:e,resolve:n,reject:i}),!this.managedPublishScheduled&&(this.managedPublishScheduled=true,queueMicrotask(()=>{this.managedPublishScheduled=false,this.enqueueManagedWork(()=>this.flushManagedPublishBatch());}));})}async subscribeDevices(){let e=null;return new ReadableStream({start:n=>{e=n,this.deviceStreams.add(n);let i=this.snapshot().map(r=>({type:"added",device:r}));i.length>0&&n.enqueue(i);},cancel:()=>{e&&this.deviceStreams.delete(e),e=null;}})}async createSession(e){await this.ensureConnected(),await this.sendOperation({v:1,type:"session.put",idempotencyKey:v("session-put"),sessionId:e.connectionId,session:e,expiresAtMs:e.expiresAt??Date.now()+15*6e4});}async updateSession(e,n){await this.ensureConnected(),await this.sendOperation({v:1,type:"session.put",idempotencyKey:v("session-update"),sessionId:this.unscopedId(e),session:n,expiresAtMs:typeof n.expiresAt=="number"?n.expiresAt:Date.now()+15*6e4});}async subscribeSessions(e){let n=null;return new ReadableStream({start:i=>{n=i,this.sessionStreams.add(i);},cancel:()=>{n&&this.sessionStreams.delete(n),n=null;}})}async sendMessage(e,n,i,r){await this.ensureConnected();let o=v("signal");return await this.sendOperation({v:1,type:"signal.send",idempotencyKey:o,targetDeviceId:this.unscopedId(e),payload:n,state:i,replyPayload:r}),o}async pollMessages(e){return this.pendingMessages.splice(0,this.pendingMessages.length)}watchFriendDevices(e,n){let i=[...new Set(e.map(s=>s.trim()).filter(Boolean))];if(i.length>25)throw new RangeError(`watchFriendDevices accepts at most ${25} unique friend IDs per runtime.`);for(let s of i)if(s.length>128||s.includes("/"))throw new TypeError('Friend user IDs must be 1-128 characters and cannot contain "/".');let r={value:false},o=new Map,a=[];n(new Map);for(let s of i){if(!s||s===this.options.getCurrentUserId())continue;let c=this.friendConnection(s);a.push(c.onDevicesChange(d=>{if(r.value)return;let l=d.filter(u=>u.online);o.set(s,l),n(new Map(o));}));}return ()=>{r.value=true;for(let s of a)s();for(let s of i)this.friendConnections.get(s)?.stopAuthActivity(),this.friendConnections.delete(s);}}waitForFriendDevice(e,n,i=1e4){let r=e.trim(),o=n.trim();return !r||!o?Promise.reject(new Error("Capability-authorized device observation requires user and device ids.")):new Promise((a,s)=>{let c=()=>{},d=false,l=y=>{d||(d=true,clearTimeout(u),c(),y.error?s(y.error):a(y.device));},u=setTimeout(()=>l({error:new Error(`Timed out waiting for capability-authorized device ${o}`)}),Math.max(1,i));c=this.watchFriendDevices([r],y=>{let m=(y.get(r)??[]).find(T=>T.deviceId===o&&T.online&&typeof T.ticket=="string"&&T.ticket.trim().startsWith("endpoint"));m&&l({device:m});}),d&&c();})}setFriendObservationIdentity(e){this.friendObservationPresence={localNodeId:e.localNodeId,ticket:e.ticket,online:true,ttlMs:e.ttlMs,metadata:e.metadata,deviceName:e.deviceName?.trim()||this.options.getDefaultDeviceName()};for(let n of this.friendConnections.values())this.activateFriendConnection(n,this.friendObservationPresence);}async updateFriendTicket(e){await this.ensureConnected(),await this.sendOperation({v:1,type:"device.patch",idempotencyKey:v("friend-ticket"),patch:{friendTicket:e??""}});}async handleScopeChange(){this.stopSocket(),this.credentialRevoked=false,this.reconnectCircuitOpen=false,this.reconnectAttempt=0,this.reconnectOutageStartedAtMs=null,this.appliedPresenceRevision=0,this.devices.clear(),this.emitDevices();}stopAuthActivity(){this.stopped=true,this.friendObservationPresence=null,this.reconnectOutageStartedAtMs=null,this.stopSocket(),this.rejectConnectionReadyWaiters(new h("Coordination activity stopped before capability admission completed.",false)),this.desiredExcludedPeers=[...this.initialExcludedPeers];for(let e of this.pendingAcks.values())clearTimeout(e.timer),e.resolve();this.pendingAcks.clear();for(let e of this.managedPublishQueue.splice(0))e.reject(new Error("[OpenRTC] Managed room activity stopped."));if(this.devices.clear(),this.pendingMessages.splice(0,this.pendingMessages.length),this.managedState){try{this.managedWasmClient?.__forgetManagedRoomGroup(this.managedAvenueKey());}catch{}this.managedState.close(),this.managedState=null;}this.managedInitialization=null,this.managedMessageListeners.clear(),this.roomAuthorityAssignmentExpiry&&clearTimeout(this.roomAuthorityAssignmentExpiry),this.roomAuthorityAssignmentExpiry=null,this.roomAuthorityAssignment=null,this.authorityAssignmentListeners.clear(),this.emitDevices();for(let e of this.roomConnections.values())e.stopAuthActivity();this.roomConnections.clear();for(let e of this.friendConnections.values())e.stopAuthActivity();this.friendConnections.clear();}usesCoordinationGateway(){return true}async joinCoordinationRoom(e,n,i){let r=e.trim().toUpperCase(),o=this.roomConnections.get(r);o||(o=new t({...this.options,avenueOverride:{kind:"room",id:r}}),o.setHostAvailability({available:this.hostAvailable,reason:"parent-avenue-created"}),this.roomConnections.set(r,o));try{await o.updatePresence(n,i,!0,5*6e4,void 0,this.options.getDefaultDeviceName());}catch(a){if(!(a instanceof h)||!a.retryable)throw a;await o.waitForConnectionReady();}}async leaveCoordinationRoom(e){let n=e.trim().toUpperCase(),i=this.roomConnections.get(n);i&&(await i.setOffline(this.options.getLocalDeviceId()).catch(()=>{}),i.stopAuthActivity(),this.roomConnections.delete(n));}async getCoordinationRoomMembers(e){return this.requireRoomConnection(e).snapshot().map(i=>this.roomMember(i))}watchCoordinationRoomMembers(e,n){return this.requireRoomConnection(e).onDevicesChange(r=>n(r.map(o=>this.roomMember(o))))}async ensureConnected(){if(this.credentialRevoked)throw new h("Coordination credential revoked.",false,"credential-revoked");if(this.connectPromise)return this.connectPromise;if(!(this.socket?.readyState===WebSocket.OPEN&&this.socketReady)){if(!this.desiredPresence&&this.options.credentialPurpose!=="device-control")throw new Error("Coordination presence must be initialized before the gateway can connect.");if(!this.hostAvailable&&this.options.credentialPurpose!=="device-control")throw new h("Coordination reconnect is parked until the host is foregrounded and online.",true);if(this.reconnectCircuitOpen)throw new h("Coordination reconnect circuit is open until presence or scope changes.",false);if(this.reconnectTimer)throw new h("Coordination reconnect is already scheduled.",true);this.stopped=false,this.connectPromise=this.connect();try{await this.connectPromise;}catch(e){throw this.scheduleReconnect(e),e}finally{this.connectPromise=null;}}}async connect(){let e=this.desiredPresence??this.controlPresence(),n=this.desiredPresenceRevision,i=async()=>{let r=await this.mintGatewayCredential(e,false);await new Promise((o,a)=>{let s=new WebSocket(Je(r.gatewayUrl,r.routeKey,r.protocolVersion),[We,`${qe}${r.token}`]);this.socket=s;let c=false,d=false,l=null,u=()=>{d||s.readyState!==WebSocket.OPEN||(d=true,this.socketReady=true,this.appliedPresenceRevision=Math.max(this.appliedPresenceRevision,this.desiredPresence?n:0),clearTimeout(f),this.reconnectAttempt=0,this.reconnectOutageStartedAtMs=null,this.scheduleAuthRefresh(r.expiresAtMs,r.protocolVersion),this.resolveConnectionReadyWaiters(),o());},f=setTimeout(()=>{s.close(4408,"authentication timeout"),l=new h("Coordination gateway authentication timed out.",true),a(l);},H);s.onopen=()=>{s.send(JSON.stringify({v:1,type:"auth",token:r.token,socketLiveness:"ping-v1",device:this.gatewayDevice(e)}));},s.onmessage=y=>{if(y.data==="pong")return;let m;try{m=JSON.parse(String(y.data));}catch{s.close(4400,"invalid gateway frame"),d||(clearTimeout(f),a(new Error("Coordination gateway returned an invalid frame.")));return}if(m.type==="ready"&&!c&&this.socket===s&&(this.activeGrantToken=r.token,this.activeGrantJti=le(r.token),this.activeAvenue=r.avenue,this.activeGrantExpiresAtMs=r.expiresAtMs,this.activeGrantProtocolVersion=r.protocolVersion,this.leaseRefreshMode=m.leaseRefreshMode??"off",c=true,this.keepaliveTimer&&clearInterval(this.keepaliveTimer),this.keepaliveTimer=setInterval(()=>{if(this.socket===s&&s.readyState===WebSocket.OPEN)try{s.send("ping");}catch{s.close(4408,"gateway keepalive failed");}},3e4)),m.type==="error"&&!d){l=new h(`Coordination gateway ${m.code}: ${m.message}`,m.retryable,m.code),clearTimeout(f),a(l),s.close(4403,m.code);return}this.handleFrame(m,s);let T=m.type==="roster.snapshot"||m.type==="membership.snapshot"||m.type==="membership.page"&&this.pendingMembershipPageSnapshot===null;c&&(this.options.credentialPurpose==="device-control"||T)&&u();},s.onerror=()=>{d||(clearTimeout(f),l??(l=new h("Coordination gateway connection failed.",true)),a(l));},s.onclose=y=>{clearTimeout(f);let m=this.socket===s;m&&this.keepaliveTimer&&(clearInterval(this.keepaliveTimer),this.keepaliveTimer=null),m&&y.code===4403&&(!l||_(l))&&this.stopForCredentialRevocation(new h("Coordination credential revoked.",false,"credential-revoked")),d||(l??(l=new h(`Coordination gateway closed (${y.code}) before its initial projection.`,y.code!==4401&&y.code!==4403)),a(l)),this.socket===s&&(this.socket=null,this.socketReady=false),this.rejectPendingAcks("Coordination gateway connection closed.",s),this.rejectPendingAuthRefresh(new h("Coordination gateway closed during credential refresh.",y.code!==4401&&y.code!==4403),s),m&&!this.stopped&&this.desiredPresence&&y.code!==1e3&&!ue(l)&&this.scheduleReconnect(l??new h(`Coordination gateway closed (${y.code}).`,y.code!==4401));};});};try{await i();}catch(r){if(!ue(r))throw r;await i();}}async mintGatewayCredential(e,n){let r={avenue:await this.resolveAvenue(),deviceId:this.options.getLocalDeviceId(),runtimeInstanceId:this.runtimeInstanceId,ticketFingerprint:await Ve(e.ticket),purpose:this.options.credentialPurpose??"presence",idempotencyKey:v("credential")},o;try{if(!this.options.gateway.grantProvider)throw new h("OpenRTC 2.0 coordination requires a v2 gateway grant provider.",!1);o=await this.options.gateway.grantProvider({...r,...n&&this.activeGrantToken?{refreshGrant:this.activeGrantToken}:{}});}catch(s){throw s instanceof h?s:new h(s instanceof Error?s.message:"Coordination credential mint failed.",!pe(s),_(s)?"credential-revoked":void 0)}if(o.protocolVersion!==2)throw new h("Unsupported coordination gateway protocol.",false);let a=he(this.options.gateway.endpoint);if(he(o.gatewayUrl)!==a)throw new h("Coordination credential returned an unexpected gateway origin.",false);return o}handleFrame(e,n=this.socket){if(!(n&&n!==this.socket)){if(e.type==="error"&&e.code==="credential-revoked"){let i=new h(`Coordination gateway ${e.code}: ${e.message}`,false,e.code);this.rejectPendingAcks(i.message,n??void 0),this.rejectPendingAuthRefresh(i,n??void 0),this.stopForCredentialRevocation(i);return}if(e.type==="auth.refreshed"){let i=this.pendingAuthRefresh;i&&i.socket===n&&(clearTimeout(i.timer),this.pendingAuthRefresh=null,this.pendingLeaseRefreshKey=null,this.updateLocalDeviceExpiry(e.expiresAtMs),this.scheduleAuthRefresh(e.expiresAtMs,this.activeGrantProtocolVersion),i.resolve());}else if(e.type==="lease.refreshed"){let i=this.pendingAuthRefresh;if(i&&i.socket===n&&e.idempotencyKey===this.pendingLeaseRefreshKey){if(!Number.isSafeInteger(e.expiresAtMs)||e.expiresAtMs<=Date.now()){this.rejectPendingAuthRefresh(new h("Coordination lease refresh is already expired or invalid.",false),n);return}clearTimeout(i.timer),this.pendingAuthRefresh=null,this.pendingLeaseRefreshKey=null,this.activeGrantExpiresAtMs=e.expiresAtMs,this.updateLocalDeviceExpiry(e.expiresAtMs),this.scheduleAuthRefresh(e.expiresAtMs,this.activeGrantProtocolVersion),i.resolve();}}else if(e.type==="roster.snapshot"){this.sparseMembers.clear(),this.sparseRoutes.clear(),this.sparseTopologyRevision=0,this.devices.clear();for(let i of e.devices)this.devices.set(i.deviceId,this.toDevice(i));this.emitDevices();}else if(e.type==="membership.snapshot"){this.pendingMembershipPageSnapshot=null,this.sparseMembers.clear(),this.sparseRoutes.clear(),this.sparseTopologyRevision=0;for(let i of e.members)this.sparseMembers.set(i.deviceId,i);this.rebuildSparseDevices();}else if(e.type==="membership.page"){let i=/^[A-Za-z0-9:_-]{1,160}$/.test(e.snapshotId)&&Number.isSafeInteger(e.pageIndex)&&Number.isSafeInteger(e.pageCount)&&Number.isSafeInteger(e.memberCount)&&e.pageIndex>=0&&e.pageCount>=2&&e.pageCount<=50&&e.pageIndex<e.pageCount&&e.memberCount>100&&e.memberCount<=5e3&&e.members.length>0&&e.members.length<=100;e.pageIndex===0&&i&&(this.pendingMembershipPageSnapshot={snapshotId:e.snapshotId,nextPageIndex:0,pageCount:e.pageCount,memberCount:e.memberCount,members:new Map});let r=this.pendingMembershipPageSnapshot;if(!(i&&r!==null&&r.snapshotId===e.snapshotId&&r.nextPageIndex===e.pageIndex&&r.pageCount===e.pageCount&&r.memberCount===e.memberCount&&e.members.every(a=>a.deviceId.length>0&&!r.members.has(a.deviceId)))||!r){n?.close(4400,"invalid membership page");return}for(let a of e.members)r.members.set(a.deviceId,a);if(r.nextPageIndex+=1,r.nextPageIndex===r.pageCount){if(r.members.size!==r.memberCount){n?.close(4400,"incomplete membership pages");return}this.sparseMembers.clear(),this.sparseRoutes.clear(),this.sparseTopologyRevision=0;for(let a of r.members.values())this.sparseMembers.set(a.deviceId,a);this.pendingMembershipPageSnapshot=null,this.rebuildSparseDevices();}}else if(e.type==="membership.changed")e.operation==="delete"?this.sparseMembers.delete(e.member.deviceId):this.sparseMembers.set(e.member.deviceId,e.member),this.rebuildSparseDevices();else if(e.type==="topology.lease")this.acceptTopologyLease(e.lease);else if(e.type==="authority.assignment")this.acceptAuthorityAssignment(e.assignment,e.signature);else if(e.type==="presence.changed"){if(e.operation==="delete")this.devices.delete(e.device.deviceId),this.emitDeviceEvents([{type:"removed",deviceId:e.device.deviceId}]);else {let i=this.devices.has(e.device.deviceId),r=this.toDevice(e.device);this.devices.set(r.deviceId,r),this.emitDeviceEvents([{type:i?"modified":"added",device:r}]);}this.emitDevices();}else if(e.type==="signal.received")this.pendingMessages.length>=ze&&this.pendingMessages.shift(),this.pendingMessages.push({senderId:e.senderDeviceId,targetId:this.options.getLocalDeviceId(),payload:e.payload,state:e.state,replyPayload:e.replyPayload,timestamp:e.createdAtMs,appTag:this.options.appTag});else if(e.type==="managed.prepare.page"||e.type==="managed.commit.chunk.received"||e.type==="managed.received")this.enqueueManagedWork(()=>this.handleManagedFrame(e));else if(e.type==="session.changed"){let i=e.operation==="delete"?[{type:"removed",sessionId:e.sessionId}]:[{type:"modified",session:{...e.session??{},connectionId:e.sessionId}}];for(let r of this.sessionStreams)r.enqueue(i);}else if(e.type==="ack"){let i=this.pendingAcks.get(e.idempotencyKey);i&&i.socket===n&&(clearTimeout(i.timer),this.pendingAcks.delete(e.idempotencyKey),i.resolve());}else if(e.type==="error"){if(this.pendingAuthRefresh?.socket===n&&(!e.idempotencyKey||e.idempotencyKey===this.pendingLeaseRefreshKey)){let r=this.pendingAuthRefresh;clearTimeout(r.timer),this.pendingAuthRefresh=null,this.pendingLeaseRefreshKey=null,r.reject(new h(`Coordination gateway ${e.code}: ${e.message}`,e.retryable,e.code));return}let i=e.idempotencyKey?this.pendingAcks.get(e.idempotencyKey):null;i&&i.socket===n&&(clearTimeout(i.timer),this.pendingAcks.delete(e.idempotencyKey),i.reject(new U(e.code,e.message,e.retryable)));}}}enqueueManagedWork(e){let n=this.managedActions.then(e);this.managedActions=n.catch(i=>{console.error("[OpenRTC] Managed room owner rejected a gateway frame:",i),this.socket?.close(4400,"managed room state invalid");});}async flushManagedPublishBatch(){let e=this.managedPublishQueue.splice(0,He);if(e.length!==0)try{await this.ensureConnected(),await this.ensureManagedGroupInitialized();let n=this.roomArchitectureSnapshot,i=this.managedWasmClient,r=this.managedState;if(!n||n.effective!=="managed"||n.phase!=="settled"||this.roomEncryptionEpoch<1||!i||!r)throw new Error("[OpenRTC] Managed room encryption is not settled.");let o=[];for(let d of e){let l=await i.__sealManagedRoomPayload(this.managedAvenueKey(),BigInt(n.epoch),BigInt(this.roomEncryptionEpoch),d.input.messageId,d.input.channel,d.input.priority,d.input.zoneId,d.input.payload);o.push({item:d,sealedState:l.sealedState,envelope:{messageId:d.input.messageId,channel:d.input.channel,priority:d.input.priority,scope:d.input.zoneId?{kind:"zone",zoneId:d.input.zoneId}:{kind:"global"},ciphertext:l.payload}});}await r.persist(k(o[o.length-1].sealedState));let a=[],s=0,c=async()=>{if(a.length===0)return;let d=a;a=[],s=0,await this.sendOperation({v:1,type:"managed.publish",idempotencyKey:v("managed-publish"),architectureEpoch:n.epoch,encryptionEpoch:this.roomEncryptionEpoch,batch:d.map(({envelope:l})=>l)});for(let{item:l}of d)l.resolve();};for(let d of o){let l=d.envelope.ciphertext.length;a.length>0&&s+l>Ue&&await c(),a.push(d),s+=l;}await c();}catch(n){for(let i of e)i.reject(n);throw n}finally{this.managedPublishQueue.length>0&&!this.managedPublishScheduled&&(this.managedPublishScheduled=true,queueMicrotask(()=>{this.managedPublishScheduled=false,this.enqueueManagedWork(()=>this.flushManagedPublishBatch());}));}}managedAvenueKey(){let e=this.activeAvenue??this.options.avenueOverride;if(!e||e.kind!=="room"&&e.kind!=="space")throw new Error("[OpenRTC] Managed groups require an active room or space.");return `${e.kind}:${e.id}`}async ensureManagedGroupInitialized(){if(this.managedState)return;if(this.managedInitialization)return this.managedInitialization;let e=this.managedWasmClient;if(!e)throw new Error("[OpenRTC] This browser runtime has no managed-room Rust/WASM owner.");let n=this.managedAvenueKey(),i=(async()=>{let r=await this.managedStateProvider(this.options.appTag,this.options.getLocalDeviceId(),n),o=await e.__initManagedRoomGroup(n,this.options.getLocalDeviceId(),r.wrappingKey,r.sealedState);this.managedState=r,await this.executeManagedGroupActions([o]);})();this.managedInitialization=i;try{await i;}finally{this.managedInitialization===i&&(this.managedInitialization=null);}}async executeManagedGroupActions(e){for(let n of e)if(n.type==="persist-state"){let i=this.managedState;if(!i)throw new Error("[OpenRTC] Managed room state store is unavailable.");await i.persist(k(n.sealedState));}else n.type==="publish-key-package"?await this.sendOperation({v:1,type:"managed.key-package.publish",idempotencyKey:v("managed-key-package"),keyPackageHash:n.keyPackageHash,keyPackage:n.keyPackage}):n.type==="request-prepare-page"?await this.sendOperation({v:1,type:"managed.prepare.page.request",idempotencyKey:v("managed-prepare-page"),preparationId:n.preparationId,pageIndex:n.pageIndex}):n.type==="send-artifact-chunk"?await this.sendOperation({v:1,type:"managed.commit.chunk",idempotencyKey:v("managed-artifact"),...n.chunk}):n.type==="acknowledge-commit"&&await this.sendOperation({v:1,type:"managed.commit.ack",idempotencyKey:v("managed-commit-ack"),preparationId:n.preparationId,encryptionEpoch:n.encryptionEpoch,groupIdHash:n.groupIdHash});}async handleManagedFrame(e){await this.ensureManagedGroupInitialized();let n=this.managedWasmClient;if(!n)throw new Error("[OpenRTC] Managed room Rust/WASM owner is unavailable.");let i=this.managedAvenueKey();if(e.type==="managed.prepare.page"){await this.executeManagedGroupActions(await n.__handleManagedRoomPreparePage(i,e));return}if(e.type==="managed.commit.chunk.received"){await this.executeManagedGroupActions(await n.__handleManagedRoomArtifactChunk(i,e));return}let r=this.roomArchitectureSnapshot;if(!r||r.effective!=="managed"||r.phase!=="settled"||e.architectureEpoch!==r.epoch||e.encryptionEpoch!==this.roomEncryptionEpoch)throw new Error("[OpenRTC] Managed room delivery uses a stale room lease.");let o=[],a=null;for(let s of e.batch){let c=s.scope.kind==="zone"?s.scope.zoneId:void 0,d=await n.__openManagedRoomPayload(i,BigInt(e.architectureEpoch),BigInt(e.encryptionEpoch),s.messageId,s.channel,s.priority,c,k(s.ciphertext));a=d.sealedState,o.push({senderId:e.senderDeviceId,messageId:s.messageId,channel:s.channel,priority:s.priority,...c?{zoneId:c}:{},payload:k(d.payload)});}if(a){let s=this.managedState;if(!s)throw new Error("[OpenRTC] Managed room state store is unavailable.");await s.persist(k(a));}for(let s of o)for(let c of this.managedMessageListeners)c(s);}async sendOperation(e){this.budgetRenewalPromise&&await this.budgetRenewalPromise;let n=this.budgetRenewalEpoch;try{await this.sendOperationOnce(e);}catch(i){if(!(i instanceof U)||i.code!=="budget-renewal-required"&&i.code!==a.BUDGET_RENEWAL_REQUIRED||!i.retryable)throw i;this.budgetRenewalEpoch===n&&await this.renewBudget(),await this.sendOperationOnce(e);}}async sendOperationOnce(e){let n=this.socket;if(!n||n.readyState!==WebSocket.OPEN||!this.socketReady)throw new Error("Coordination gateway is not connected.");await new Promise((i,r)=>{let o=setTimeout(()=>{this.pendingAcks.get(e.idempotencyKey)?.timer===o&&this.pendingAcks.delete(e.idempotencyKey),r(new Error("Coordination gateway acknowledgement timed out."));},H);this.pendingAcks.set(e.idempotencyKey,{socket:n,resolve:i,reject:r,timer:o});try{n.send(JSON.stringify(e));}catch(a){clearTimeout(o),this.pendingAcks.delete(e.idempotencyKey),r(a instanceof Error?a:new Error(String(a)));}});}async renewBudget(){if(this.budgetRenewalPromise)return this.budgetRenewalPromise;let e=this.refreshAuthentication(true).then(()=>{this.budgetRenewalEpoch+=1;});this.budgetRenewalPromise=e;try{await e;}finally{this.budgetRenewalPromise===e&&(this.budgetRenewalPromise=null);}}async resolveAvenue(){if(this.options.avenueOverride)return this.options.avenueOverride;if((this.options.discoveryMode??"space")==="space"){let n=await this.options.resolveSpaceNamespaceId();if(!n)throw new Error("Space namespace is not available for coordination.");return {kind:"space",id:n}}let e=this.options.getCurrentUserId();if(!e)throw new Error("Authenticated user is required for coordination.");return {kind:"user",id:e}}gatewayDevice(e){return {deviceId:this.options.getLocalDeviceId(),runtimeInstanceId:this.runtimeInstanceId,nodeId:e.localNodeId,deviceName:e.deviceName,platformType:this.options.getPlatformType(),ticket:e.ticket,metadata:e.metadata,excludedPeers:this.desiredExcludedPeers,online:e.online}}controlPresence(){if(this.options.credentialPurpose!=="device-control")throw new Error("Coordination presence must be initialized before the gateway can connect.");return {localNodeId:this.options.getLocalDeviceId(),ticket:`openrtc-device-control:${this.runtimeInstanceId}`,online:false,ttlMs:0,deviceName:this.options.getDefaultDeviceName()}}toDevice(e){return this.options.normalizeDevice({...e,appTag:this.options.appTag,lastSeenAt:e.updatedAtMs,expiresAt:e.expiresAtMs},e.deviceId)}rebuildSparseDevices(){this.devices.clear();for(let e of this.sparseMembers.values()){let n=this.sparseRoutes.get(e.deviceId),i=n?{...e,...n}:{...e,runtimeInstanceId:"",nodeId:"",ticket:""};this.devices.set(e.deviceId,this.toDevice(i));}this.emitDevices();}acceptTopologyLease(e){if(e.topologyRevision<=this.sparseTopologyRevision)return;let n=this.activeAvenue,i=[...e.active,...e.backups],r=i.map(u=>u.deviceId),o=e.schemaVersion===1||this.validArchitectureLease(e.architecture),a=e.schemaVersion===1||this.validGroupEncryptionLease(e.groupEncryption,e.architecture),s=e.schemaVersion===2&&e.architecture.effectiveMode==="authority",c=e.schemaVersion===2?e.admissionPeers:void 0,d=!s||this.peerAdmissionScope!==null&&this.peerAdmissionRuntime!==null&&Array.isArray(c)&&c.length<=50&&new Set(c.map(u=>u.deviceId)).size===c.length&&c.every(u=>this.sparseMembers.get(u.deviceId)?.online&&u.deviceId!==this.options.getLocalDeviceId()&&/^[0-9a-f]{64}$/.test(u.nodeId));if(!((e.schemaVersion===1||e.schemaVersion===2)&&o&&a&&d&&Number.isSafeInteger(e.topologyRevision)&&e.topologyRevision>0&&(this.sparseTopologyRevision===0?e.previousTopologyRevision===void 0:e.previousTopologyRevision===this.sparseTopologyRevision)&&e.grantJti===this.activeGrantJti&&n!==null&&e.avenue.kind===n.kind&&e.avenue.id===n.id&&Number.isSafeInteger(e.expiresAtMs)&&e.expiresAtMs>Date.now()&&e.expiresAtMs<=this.activeGrantExpiresAtMs&&e.active.length<=16&&e.backups.length<=4&&i.length<=20&&new Set(r).size===r.length&&i.every(u=>u.online&&this.sparseMembers.has(u.deviceId)&&u.deviceId!==this.options.getLocalDeviceId()&&u.nodeId.trim().length>0&&u.ticket.trim().length>0))){this.socket?.close(4400,"invalid topology lease");return}if(s)try{this.peerAdmissionRuntime.__updateScopePeerAdmission(this.peerAdmissionScope,++this.peerAdmissionRevision,e.expiresAtMs,JSON.stringify(c.map(u=>u.nodeId)));}catch{this.socket?.close(4400,"invalid peer admission lease");return}if(e.schemaVersion===2){e.groupEncryption&&(this.roomEncryptionEpoch=e.groupEncryption.epoch);let u={requested:e.architecture.requestedMode,effective:e.architecture.effectiveMode,epoch:e.architecture.epoch,phase:e.architecture.phase,reason:e.architecture.reason,heldCreditsUsd:e.architecture.heldCreditsMicrousd/1e6,quoteExpiresAtMs:e.architecture.quoteExpiresAtMs},f=JSON.stringify(u)!==JSON.stringify(this.roomArchitectureSnapshot);if(this.roomArchitectureSnapshot=u,f)for(let y of this.architectureListeners)y({...u});if(u.effective!=="authority"&&this.roomAuthorityAssignment){this.roomAuthorityAssignmentExpiry&&(clearTimeout(this.roomAuthorityAssignmentExpiry),this.roomAuthorityAssignmentExpiry=null),this.roomAuthorityAssignment=null;for(let y of this.authorityAssignmentListeners)y(null);}u.effective==="managed"&&this.enqueueManagedWork(()=>this.ensureManagedGroupInitialized());}this.sparseTopologyRevision=e.topologyRevision,this.sparseRoutes.clear();for(let u of e.active)this.sparseRoutes.set(u.deviceId,{...u,topologyRole:"active",topologyRevision:e.topologyRevision});for(let u of e.backups)this.sparseRoutes.set(u.deviceId,{...u,topologyRole:"backup",topologyRevision:e.topologyRevision});this.rebuildSparseDevices();}acceptAuthorityAssignment(e,n){let i=this.roomAuthorityAssignment,r=this.options.getLocalDeviceId(),o=[e.serviceId,e.subjectDeviceId,e.shardId,...e.priorityDeviceIds,...e.relevantEntityIds];if(i&&e.generation===i.generation&&e.revision===i.revision){if(JSON.stringify({serviceId:e.serviceId,generation:e.generation,revision:e.revision,shardId:e.shardId,priorityDeviceIds:e.priorityDeviceIds,relevantEntityIds:e.relevantEntityIds,issuedAtMs:e.issuedAtMs,expiresAtMs:e.expiresAtMs})===JSON.stringify(i))return;this.socket?.close(4400,"invalid authority assignment");return}if(!(e.policyVersion==="room-authority-assignment-v1"&&this.roomArchitectureSnapshot?.effective==="authority"&&e.subjectDeviceId===r&&Number.isSafeInteger(e.generation)&&e.generation>0&&Number.isSafeInteger(e.revision)&&e.revision>0&&Number.isSafeInteger(e.issuedAtMs)&&Number.isSafeInteger(e.expiresAtMs)&&e.issuedAtMs<=Date.now()+3e4&&e.expiresAtMs>Date.now()&&e.expiresAtMs-e.issuedAtMs<=12e4&&e.priorityDeviceIds.length<=8&&e.relevantEntityIds.length<=32&&new Set(e.priorityDeviceIds).size===e.priorityDeviceIds.length&&new Set(e.relevantEntityIds).size===e.relevantEntityIds.length&&o.every(c=>/^[A-Za-z0-9_.:@-]{1,160}$/.test(c))&&/^[A-Za-z0-9_-]{86}$/.test(n)&&(!i||e.generation>i.generation||e.generation===i.generation&&e.revision>i.revision))){this.socket?.close(4400,"invalid authority assignment");return}this.roomAuthorityAssignment=Object.freeze({serviceId:e.serviceId,generation:e.generation,revision:e.revision,shardId:e.shardId,priorityDeviceIds:Object.freeze([...e.priorityDeviceIds]),relevantEntityIds:Object.freeze([...e.relevantEntityIds]),issuedAtMs:e.issuedAtMs,expiresAtMs:e.expiresAtMs}),this.roomAuthorityAssignmentExpiry&&clearTimeout(this.roomAuthorityAssignmentExpiry),this.roomAuthorityAssignmentExpiry=setTimeout(()=>{if(this.roomAuthorityAssignmentExpiry=null,this.roomAuthorityAssignment?.expiresAtMs===e.expiresAtMs){this.roomAuthorityAssignment=null;for(let c of this.authorityAssignmentListeners)c(null);}},Math.max(0,e.expiresAtMs-Date.now()));for(let c of this.authorityAssignmentListeners)c(this.roomAuthorityAssignmentSnapshot());}roomAuthorityAssignmentSnapshot(){let e=this.roomAuthorityAssignment;return !e||e.expiresAtMs<=Date.now()?null:{...e,priorityDeviceIds:[...e.priorityDeviceIds],relevantEntityIds:[...e.relevantEntityIds]}}validArchitectureLease(e){let n=this.roomArchitectureSnapshot?.epoch??0,i=new Set(["auto","mesh","sparse","managed","authority"]),r=new Set(["mesh","sparse","managed","authority"]),o=new Set(["size","traffic","latency","cost","capacity","manual","recovery"]);return e.policyVersion==="room-architecture-v1"&&Number.isSafeInteger(e.epoch)&&e.epoch>0&&e.epoch>=n&&(e.epoch===n||n===0||e.previousArchitectureEpoch===n)&&i.has(e.requestedMode)&&r.has(e.effectiveMode)&&(e.phase==="settled"||e.phase==="preparing")&&o.has(e.reason)&&Number.isSafeInteger(e.heldCreditsMicrousd)&&e.heldCreditsMicrousd>=0&&Number.isSafeInteger(e.quoteExpiresAtMs)&&e.quoteExpiresAtMs>0&&(e.reservationId===void 0||/^[A-Za-z0-9:_-]{1,160}$/.test(e.reservationId))}validGroupEncryptionLease(e,n){if(!e)return n.effectiveMode!=="managed"||n.phase==="preparing";let i=this.roomEncryptionEpoch;return e.policyVersion==="room-mls-v1"&&Number.isSafeInteger(e.epoch)&&e.epoch>0&&e.epoch>=i&&(e.epoch===i||i===0||e.previousEncryptionEpoch===i)&&(e.phase==="preparing"||e.phase==="settled")&&(n.effectiveMode!=="managed"||n.phase!=="settled"||e.phase==="settled")&&/^[A-Za-z0-9_.:@-]{1,160}$/.test(e.committerDeviceId)&&/^[A-Za-z0-9_-]{43}$/.test(e.groupIdHash)}snapshot(e){return [...this.devices.values()].filter(n=>!e||n.nodeId!==e).sort((n,i)=>n.deviceId.localeCompare(i.deviceId))}emitDevices(){let e=this.snapshot();for(let n of this.deviceListeners)n(e);}emitDeviceEvents(e){for(let n of this.deviceStreams)n.enqueue(e);}updateLocalDeviceExpiry(e){let n=this.options.getLocalDeviceId(),i=this.devices.get(n);if(!i||i.expiresAt===e)return;let r={...i,expiresAt:e};this.devices.set(n,r),this.emitDeviceEvents([{type:"modified",device:r}]),this.emitDevices();}scheduleAuthRefresh(e,n){this.authRefreshTimer&&clearTimeout(this.authRefreshTimer);let i=e-Date.now(),r=n===2?Ke:Oe,o=i>r+1e3;this.authRefreshTimer=setTimeout(()=>{if(this.authRefreshTimer=null,this.stopped)return;if(!o){this.stopSocket(false),this.scheduleReconnect(new h("Coordination credential crossed a billing boundary.",true));return}(n===2&&this.leaseRefreshMode==="active"?this.refreshLease():this.refreshAuthentication()).catch(s=>{this.stopSocket(false),this.scheduleReconnect(s);});},o?i-r:Math.max(1e3,i+1e3));}refreshAuthentication(e=false){let n=`${e?"issue":"refresh"}\0${this.desiredPresence?.ticket??""}`,i=this.authenticationRefreshes.get(n);if(i)return i;let r=this.authenticationRefreshTail.catch(()=>{}).then(()=>this.performAuthenticationRefresh(e));this.authenticationRefreshTail=r,this.authenticationRefreshes.set(n,r);let o=()=>{this.authenticationRefreshes.get(n)===r&&this.authenticationRefreshes.delete(n);};return r.then(o,o),r}async performAuthenticationRefresh(e){let n=this.socket,i=this.desiredPresence;if(!n||n.readyState!==WebSocket.OPEN||!this.socketReady||!i)throw new h("Coordination socket is unavailable for credential refresh.",true);if(this.pendingAuthRefresh)return this.pendingAuthRefresh.promise;let r=await this.mintGatewayCredential(i,!e);if(this.socket!==n||n.readyState!==WebSocket.OPEN||!this.socketReady)throw new h("Coordination socket changed while minting a credential refresh.",true);let o,a,s=new Promise((d,l)=>{o=d,a=l;}),c=setTimeout(()=>{this.pendingAuthRefresh?.timer===c&&(this.pendingAuthRefresh=null),a(new h("Coordination credential refresh timed out.",true));},H);this.pendingAuthRefresh={socket:n,promise:s,resolve:o,reject:a,timer:c};try{n.send(JSON.stringify({v:1,type:"auth.refresh",token:r.token}));}catch(d){this.rejectPendingAuthRefresh(new h(d instanceof Error?d.message:"Coordination credential refresh send failed.",true),n);}await s,this.activeGrantToken=r.token,this.activeGrantJti=le(r.token),this.activeAvenue=r.avenue,this.activeGrantExpiresAtMs=r.expiresAtMs,this.activeGrantProtocolVersion=r.protocolVersion;}refreshLease(){let e=`lease\0${this.desiredPresence?.ticket??""}`,n=this.authenticationRefreshes.get(e);if(n)return n;let i=this.authenticationRefreshTail.catch(()=>{}).then(()=>this.performLeaseRefresh());this.authenticationRefreshTail=i,this.authenticationRefreshes.set(e,i);let r=()=>{this.authenticationRefreshes.get(e)===i&&this.authenticationRefreshes.delete(e);};return i.then(r,r),i}async performLeaseRefresh(){let e=this.socket;if(!e||e.readyState!==WebSocket.OPEN||!this.socketReady)throw new h("Coordination socket is unavailable for lease refresh.",true);if(this.pendingAuthRefresh)return this.pendingAuthRefresh.promise;let n=v("lease"),i,r,o=new Promise((s,c)=>{i=s,r=c;}),a=setTimeout(()=>{this.pendingAuthRefresh?.timer===a&&(this.pendingAuthRefresh=null,this.pendingLeaseRefreshKey=null),r(new h("Coordination lease refresh timed out.",true));},H);this.pendingLeaseRefreshKey=n,this.pendingAuthRefresh={socket:e,promise:o,resolve:i,reject:r,timer:a};try{e.send(JSON.stringify({v:1,type:"lease.refresh",idempotencyKey:n}));}catch(s){this.rejectPendingAuthRefresh(new h(s instanceof Error?s.message:"Coordination lease refresh send failed.",true),e);}try{await o;}catch(s){if(this.stopped||_(s))throw s;await this.performAuthenticationRefresh(true);}}stopForCredentialRevocation(e){return _(e)?(this.credentialRevoked=true,this.reconnectCircuitOpen=true,this.stopAuthActivity(),true):false}scheduleReconnect(e){if(this.stopForCredentialRevocation(e)||this.reconnectTimer||this.reconnectCircuitOpen||this.stopped)return;if(!(e instanceof h?e.retryable:!pe(e))){this.reconnectCircuitOpen=true,this.rejectConnectionReadyWaiters(e instanceof Error?e:new h("Coordination reconnect circuit is open.",false));return}if(this.reconnectOutageStartedAtMs??(this.reconnectOutageStartedAtMs=Date.now()),!this.hostAvailable)return;let i=Math.min(this.reconnectAttempt,ae),r=Date.now()-this.reconnectOutageStartedAtMs>=Be,o=$e(r?Fe:d(i,250,Le));this.reconnectAttempt=Math.min(i+1,ae),this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=null,this.ensureConnected().catch(a=>this.scheduleReconnect(a));},o);}stopSocket(e=true){this.peerAdmissionScope&&this.peerAdmissionRuntime&&this.peerAdmissionRuntime.__updateScopePeerAdmission(this.peerAdmissionScope,++this.peerAdmissionRevision,0,"[]"),e&&this.reconnectTimer&&clearTimeout(this.reconnectTimer),this.authRefreshTimer&&clearTimeout(this.authRefreshTimer),this.reconnectTimer=null,this.keepaliveTimer&&clearInterval(this.keepaliveTimer),this.keepaliveTimer=null,this.authRefreshTimer=null,this.leaseRefreshMode="off",this.pendingLeaseRefreshKey=null,this.rejectPendingAuthRefresh(new h("Coordination credential refresh was canceled.",true));let n=this.socket;this.socket=null,this.socketReady=false,this.activeGrantJti=null,this.activeAvenue=null,this.activeGrantExpiresAtMs=0,this.sparseRoutes.clear(),this.sparseTopologyRevision=0,this.pendingMembershipPageSnapshot=null,this.sparseMembers.size>0&&this.rebuildSparseDevices(),n?.close(1e3,"coordination session stopped");}waitForConnectionReady(){return this.socket?.readyState===WebSocket.OPEN&&this.socketReady?Promise.resolve():this.stopped||this.reconnectCircuitOpen?Promise.reject(new h("Coordination reconnect circuit is unavailable.",false)):new Promise((e,n)=>{this.connectionReadyWaiters.add({resolve:e,reject:n});})}resolveConnectionReadyWaiters(){for(let e of this.connectionReadyWaiters)e.resolve();this.connectionReadyWaiters.clear();}rejectConnectionReadyWaiters(e){for(let n of this.connectionReadyWaiters)n.reject(e);this.connectionReadyWaiters.clear();}rejectPendingAuthRefresh(e,n){let i=this.pendingAuthRefresh;!i||n&&i.socket!==n||(clearTimeout(i.timer),this.pendingAuthRefresh=null,this.pendingLeaseRefreshKey=null,i.reject(e));}rejectPendingAcks(e,n){for(let[i,r]of this.pendingAcks)n&&r.socket!==n||(clearTimeout(r.timer),r.reject(new Error(e)),this.pendingAcks.delete(i));}unscopedId(e){let n=e.split("::");return n.length===2?n[1]:e}requireRoomConnection(e){let n=e.trim().toUpperCase(),i=this.roomConnections.get(n);if(!i)throw new Error(`Room ${n} is not joined through the coordination gateway.`);return i}friendConnection(e){let n=this.friendConnections.get(e);n||(n=new t({...this.options,avenueOverride:{kind:"user",id:e}}),n.setHostAvailability({available:this.hostAvailable,reason:"parent-avenue-created"}),this.friendConnections.set(e,n));let i=this.desiredPresence??this.friendObservationPresence;return !n.desiredPresence&&i&&this.activateFriendConnection(n,i),n}activateFriendConnection(e,n){e.updatePresence(n.localNodeId,n.ticket,n.online,n.ttlMs,n.metadata,n.deviceName).catch(()=>{});}roomMember(e){return {nodeId:e.nodeId??e.deviceId,userId:e.userId??"",ticket:e.ticket,joinedAt:Number(e.createdAt??e.lastSeenAt??Date.now()),lastSeenAt:Number(e.lastSeenAt??Date.now()),expiresAt:typeof e.expiresAt=="number"?e.expiresAt:void 0}}};var F=class{constructor(e){this.provider=e;this.cached=null;this.inFlight=null;this.refreshTimer=null;this.refreshRetryUsed=false;this.listeners=new Set;}async get(e=false){if(!this.provider)throw new Error("[OpenRTC] Native coordination requires coordinationGateway.nativeTrustTokenProvider; obtain tokens through a trusted backend without shipping the developer secret.");let n=Date.now();if(!e&&this.cached&&this.cached.expiresAtMs>n+3e4)return this.cached;if(this.inFlight)return this.inFlight;let i=(async()=>{let r=await this.provider(e),o=r?.token?.trim()??"",a=Number(r?.expiresAtMs),s=Date.now();if(!o||!Number.isFinite(a)||a<=s+3e4)throw new Error("[OpenRTC] Native trust token provider returned no usable short-lived token.");let c={token:o,expiresAtMs:a};return this.cached=c,this.refreshRetryUsed=false,this.notify(c),this.scheduleRefresh(c),c})();this.inFlight=i;try{return await i}finally{this.inFlight===i&&(this.inFlight=null);}}invalidate(){this.cached=null,this.clearRefreshTimer(),this.notify(null);}clear(){this.invalidate(),this.listeners.clear();}subscribe(e,n){return this.listeners.add(e),this.cached&&this.cached.expiresAtMs>Date.now()&&(n?.emitCurrent!==false&&e(this.cached),this.scheduleRefresh(this.cached)),()=>{this.listeners.delete(e),this.listeners.size===0&&this.clearRefreshTimer();}}notify(e){for(let n of this.listeners)n(e);}scheduleRefresh(e){if(this.clearRefreshTimer(),this.listeners.size===0)return;let n=Math.max(0,e.expiresAtMs-Date.now()-3e4);this.refreshTimer=setTimeout(()=>{this.refreshTimer=null,this.get(true).catch(()=>{if(this.listeners.size===0||this.refreshRetryUsed){this.invalidate();return}this.refreshRetryUsed=true,this.refreshTimer=setTimeout(()=>{this.refreshTimer=null,this.get(true).catch(()=>this.invalidate());},15e3);});},n);}clearRefreshTimer(){this.refreshTimer&&(clearTimeout(this.refreshTimer),this.refreshTimer=null);}};var ge=class{constructor(e){this.options=e;this.signaling=null;this.wasmClient=null;this.managedStateProvider=null;this.hostAvailability={available:true,reason:"initial"};this.nativeTrustTokens=e.gateway?new F(e.gateway.nativeTrustTokenProvider):null;}usesGateway(){return !!this.options.gateway}getSignaling(){if(this.options.signalingMode==="ticket-only")throw new Error('[openrtc] Managed signaling is disabled when signalingMode="ticket-only".');if(!this.options.gateway)throw new Error("[OpenRTC] Managed coordination requires coordinationGateway; the legacy direct Firebase data plane has been removed.");if(!this.signaling){this.signaling=new B({projectId:this.options.projectId,gateway:this.options.gateway,appTag:this.options.appTag,discoveryMode:this.options.discoveryMode,resolveSpaceNamespaceId:this.options.resolveSpaceNamespaceId,getCurrentUserId:this.options.getCurrentUserId,getAuthToken:this.options.getAuthToken,getAppCheckToken:this.options.getAppCheckToken,getLocalDeviceId:this.options.getLocalDeviceId,getDefaultDeviceName:this.options.getDefaultDeviceName,getPlatformType:this.options.getPlatformType,normalizeDevice:this.options.normalizeDevice,avenueOverride:this.options.avenueOverride,roomArchitecture:this.options.roomArchitecture,initialExcludedPeers:this.options.initialExcludedPeers,nativeTrustTokens:this.nativeTrustTokens});let e=this.signaling;this.managedStateProvider?e.setManagedRoomRuntime(this.wasmClient,this.managedStateProvider):e.setWasmClient(this.wasmClient),this.signaling.setHostAvailability?.(this.hostAvailability);}return this.signaling}setWasmClient(e){this.wasmClient=e,this.managedStateProvider=null,this.signaling?.setWasmClient(e);}setManagedRoomRuntime(e,n){this.wasmClient=e,this.managedStateProvider=n,this.signaling?.setManagedRoomRuntime(e,n);}setHostAvailability(e){this.hostAvailability=e,this.signaling?.setHostAvailability?.(e);}async reconnectAfterHostResume(){await this.signaling?.reconnectAfterHostResume?.();}async handleScopeChange(){await this.signaling?.handleScopeChange();}stopAuthActivity(){this.signaling?.stopAuthActivity();}async getNativeTrustToken(e=false){if(!this.nativeTrustTokens)throw new Error("[OpenRTC] Native trust tokens require a coordination gateway.");return this.nativeTrustTokens.get(e)}invalidateNativeTrustToken(){this.nativeTrustTokens?.invalidate();}subscribeNativeTrustToken(e,n){return this.nativeTrustTokens?.subscribe(e,n)??(()=>{})}};function Ye(){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 $(t,e,n){if(Ye()){if(typeof n>"u"){console[t](e);return}console[t](e,n);}}function Bt(t,e){$("debug",t,e);}function Ft(t,e){$("info",t,e);}function jt(t,e){$("log",t,e);}function ye(){return typeof window>"u"?false:!!(window.__TAURI_IPC__||window.__TAURI_INTERNALS__||window.__TAURI__||window.location.protocol==="tauri:"||window.location.hostname==="tauri.localhost")}var Qe="[OpenRTC][teardown-trace]";function Xe(){try{let t=globalThis;if(t.OPENRTC_TEARDOWN_TRACE===!0||t.localStorage?.getItem("OPENRTC_TEARDOWN_TRACE")==="1")return !0}catch{}return false}function qt(t,e={}){console.info(Qe,{kind:t,ts:new Date().toISOString(),...e}),Xe()&&console.info("[OpenRTC][teardown-trace:stack]",{kind:t,stack:new Error(`teardown: ${t}`).stack});}var z="trustedDevice",Ze="plutonium:e2ee:identity:v1",et="plutonium:e2ee:identity:session:v1",tt="openrtc-trust",C="identity",ve="transport-trust:v1",nt=2,me="managed-room-keys",fe="managed-room-state",it=1,b=null,D=null;function S(t){let e=atob(t),n=new Uint8Array(e.length);for(let i=0;i<e.length;i+=1)n[i]=e.charCodeAt(i);return n}function N(t){let e="";for(let n=0;n<t.length;n+=1)e+=String.fromCharCode(t[n]);return btoa(e)}async function V(t){let e=await crypto.subtle.digest("SHA-256",t),n=new Uint8Array(e);return Array.from(n).map(i=>i.toString(16).padStart(2,"0")).join("")}function rt(){return typeof sessionStorage>"u"?null:sessionStorage}function ot(){if(!(typeof localStorage>"u"))try{localStorage.removeItem(Ze);}catch{}}var j=null;async function be(){return j||(j=(async()=>{let t=globalThis.crypto?.subtle;if(!t||typeof t.generateKey!="function")return false;try{let e=await t.generateKey({name:"Ed25519"},!1,["sign","verify"]);return !!(e&&e.privateKey&&e.publicKey)}catch{return false}})(),j)}async function st(t){let e=await crypto.subtle.exportKey("raw",t);return new Uint8Array(e)}function at(){try{return typeof indexedDB<"u"?indexedDB:null}catch{return null}}function we(){let t=at();return t?new Promise(e=>{let n;try{n=t.open(tt,nt);}catch{e(null);return}n.onupgradeneeded=()=>{let i=n.result;i.objectStoreNames.contains(C)||i.createObjectStore(C),i.objectStoreNames.contains(me)||i.createObjectStore(me),i.objectStoreNames.contains(fe)||i.createObjectStore(fe);},n.onsuccess=()=>e(n.result),n.onerror=()=>e(null),n.onblocked=()=>e(null);}):Promise.resolve(null)}async function ct(){let t=await we();if(!t)return null;try{return await new Promise(e=>{let r=t.transaction(C,"readonly").objectStore(C).get(ve);r.onsuccess=()=>{let o=r.result;e(o&&o.privateKey&&o.publicKey?o:null);},r.onerror=()=>e(null);})}catch{return null}finally{t.close();}}async function dt(t){let e=await we();if(!e)return false;try{return await new Promise(n=>{let i=e.transaction(C,"readwrite");i.objectStore(C).put(t,ve),i.oncomplete=()=>n(!0),i.onerror=()=>n(!1),i.onabort=()=>n(!1);})}catch{return false}finally{e.close();}}async function Se(t,e){let n=await st(t.publicKey),i=await V(n),r=t.privateKey;return {publicKey:n,fingerprint:i,backend:"webcrypto-nonextractable",durable:e,privateKey:r,async signChallenge(o){let a=await crypto.subtle.sign({name:"Ed25519"},r,S(o));return N(new Uint8Array(a))}}}function lt(t,e,n){let i=t.secretKey;return {publicKey:t.publicKey,secretKey:i,fingerprint:e,backend:"tweetnacl",durable:n,async signChallenge(r){return ut(r,i)}}}function Yt(t=32){let e=crypto.getRandomValues(new Uint8Array(t));return N(e)}function ut(t,e){let n=x.sign.detached(S(t),e);return N(n)}function pt(t,e,n){try{return x.sign.detached.verify(S(t),S(e),S(n))}catch{return false}}async function Qt(t,e,n){let i=globalThis.crypto?.subtle;if(i&&typeof i.importKey=="function"&&typeof i.verify=="function")try{let r=await i.importKey("raw",S(n),{name:"Ed25519"},!1,["verify"]);return await i.verify({name:"Ed25519"},r,S(e),S(t))}catch{}return pt(t,e,n)}function Xt(t){return N(t)}function Zt(t){if(!t||!t.trim())return null;try{let e=JSON.parse(t),n=e&&typeof e=="object"&&!Array.isArray(e)?e[z]:null;if(!n||typeof n!="object"||Array.isArray(n))return null;let i=n,r=typeof i.version=="number"?i.version:null,o=typeof i.identityPublicKey=="string"?i.identityPublicKey:null,a=typeof i.identityFingerprint=="string"?i.identityFingerprint:null;return !r||!o||!a?null:{version:r,identityPublicKey:o,identityFingerprint:a}}catch{return null}}async function ht(){let t=await vt().catch(()=>null);return t?{version:it,identityPublicKey:N(t.publicKey),identityFingerprint:t.fingerprint}:null}async function en(t){let e=await ht();if(!e)return t??void 0;let n=typeof t=="string"?t.trim():"";if(!n)return JSON.stringify({[z]:e});try{let i=JSON.parse(n);if(i&&typeof i=="object"&&!Array.isArray(i))return JSON.stringify({...i,[z]:e})}catch{}return JSON.stringify({metadata:t,[z]:e})}function gt(){if(typeof window>"u")return null;let t=window.__TAURI_INTERNALS__;return !t||typeof t.invoke!="function"?null:t.invoke.bind(t)}async function yt(){if(typeof window>"u")return null;let t=gt();if(!ye()&&!t)return null;if(!t)throw new Error("[OpenRTC] Tauri transport trust requires the native signing provider, but Tauri invoke is unavailable.");try{let e=await t("openrtc_get_transport_trust_identity"),n=S(e.publicKeyBase64);if(n.byteLength!==x.sign.publicKeyLength)throw new Error("native transport trust public key has an invalid length");let i=await V(n);if(e.fingerprint!==i)throw new Error("native transport trust fingerprint does not match its public key");return {publicKey:n,fingerprint:i,backend:"native-provider",durable:!0,async signChallenge(r){return t("openrtc_sign_transport_trust_challenge",{challenge:r})}}}catch(e){let n=new Error("[OpenRTC] native transport trust provider failed; refusing WebCrypto fallback in Tauri.");throw n.cause=e,n}}function mt(){let t=rt();t&&t.removeItem(et);}async function ft(){if(ot(),mt(),b)return b;let t=await yt();if(t)return b=t,b;if(await be()){let e=await ct();if(e)return b=await Se(e,true),b}return null}async function vt(t={}){let e=await ft();if(e)return e;if(D)return D;let n=bt(t);D=n;try{return await n}finally{D===n&&(D=null);}}async function bt(t){if(b)return b;let e=t.ephemeral===true;if(await be())try{let n=await crypto.subtle.generateKey({name:"Ed25519"},!1,["sign","verify"]),i=!1;return e||(i=await dt(n)),b=await Se(n,i),b}catch{}if(!e)return console.warn("[OpenRTC][TRUST] Managed transport trust requires WebCrypto Ed25519 or native keychain; refusing extractable fallback storage"),null;try{let n=x.sign.keyPair(),i=await V(b$1(n.publicKey));return b=lt(n,i,!1),b}catch{return null}}var wt={managedSession:{nativeStartRetryWindowMs:12e4,nativeStartRetryMinDelayMs:400,nativeStartRetryMaxDelayMs:5e3,deviceStatusRefreshDebounceMs:50},browserAutoConnect:{scanDebounceMs:150,retryCooldownMs:2e3,settleGuardMs:1e4,retryMaxMs:8e3,nonInitiatorBaseGraceMs:2e3,nonInitiatorMaxGraceMs:16e3},nativeIpc:{authRequiredWaitMs:15e3,defaultBoundedCommandTimeoutMs:15e3,connectionEventSubscribeWindowMs:15e3,connectionEventRetryMinDelayMs:250,connectionEventRetryMaxDelayMs:1e3,tauriIpcNegativeCacheMs:2e3},browserIdentity:{ephemeralDeviceIdTtlMs:6e4}};function nn(){return wt}var St={adapter:"browser-wasm",productMaturity:{boundedRooms:"stable",serviceNodes:"preview",offlineEdge:"support-only",broadcast:"preview"},signaling:{coordinationGateway:true,nativeIpc:false,managedPresence:true},transport:{irohQuic:false,irohLan:false,webRtc:true,moq:true,ble:false,wasm:true},nativeProtocols:{productAlpn:false,irohDocs:false,irohBlobs:false,irohGossip:false},lifecycle:{managedSession:true,autoConnect:true,manualDisconnect:true,connectionStateEvents:true,peerSessions:true},transfers:{explicitFilePath:false,explicitFileData:true,history:false},fallback:{wasm:false}},Rt={adapter:"native-ipc",productMaturity:{boundedRooms:"stable",serviceNodes:"unavailable",offlineEdge:"unavailable",broadcast:"unavailable"},signaling:{coordinationGateway:true,nativeIpc:true,managedPresence:true},transport:{irohQuic:true,irohLan:false,webRtc:false,moq:false,ble:false,wasm:false},nativeProtocols:{productAlpn:true,irohDocs:true,irohBlobs:true,irohGossip:true},lifecycle:{managedSession:true,autoConnect:true,manualDisconnect:true,connectionStateEvents:true,peerSessions:true},transfers:{explicitFilePath:true,explicitFileData:true,history:true},fallback:{wasm:false}};function Re(t){return {adapter:t.adapter,productMaturity:t.productMaturity?{...t.productMaturity}:void 0,signaling:{...t.signaling},transport:{...t.transport},nativeProtocols:{...t.nativeProtocols},lifecycle:{...t.lifecycle},transfers:{...t.transfers},fallback:{...t.fallback}}}function on(t=globalThis){let e=Re(St),n=typeof t?.RTCPeerConnection=="function";return e.transport.webRtc=n,e}function G(t){return t?.compiled===true&&t.enabled===true}function sn(t,e=false){let n=Re(Rt),i=t?.transport;return n.productMaturity={...n.productMaturity,...t?.productMaturity},i&&(n.transport.irohQuic=G(i.irohQuic),n.transport.irohLan=G(i.irohLan),n.transport.webRtc=G(i.webRtc),n.transport.moq=G(i.moq),n.transport.ble=G(i.ble)),n.transport.wasm=false,n.fallback.wasm=e,n}function an(t){return {environment:t.adapter==="native-ipc"||t.adapter==="tauri-ipc"?"native":t.adapter==="browser-wasm"?"web":"unknown",productMaturity:t.productMaturity?{...t.productMaturity}:void 0,transports:{quic:t.transport.irohQuic,irohRelay:t.transport.irohQuic||t.adapter==="browser-wasm",irohLan:t.transport.irohLan,webRtc:t.transport.webRtc,moq:t.transport.moq,ble:t.transport.ble},lifecycle:{...t.lifecycle},storage:{localFileSystem:t.transfers.explicitFilePath,transferHistory:t.transfers.history},nativeProtocols:{...t.nativeProtocols}}}function Ie(t){if(t.errorCode)return t;let e=t.error||t.readinessReason;if(!e)return t;let n=c(e);return {...t,errorCode:n.errorCode,retryable:n.retryable,errorPlane:n.errorPlane}}function M(t){return !t||typeof t!="object"?{}:t instanceof Map?Object.fromEntries(t):t}function J(t){let e=M(t),n=M(e.device);if(!Object.keys(n).length)return e;let i={...n,...e};return delete i.device,i}function p(t,...e){for(let n of e){let i=t[n];if(typeof i=="string"&&i.trim().length>0)return i}}function w(t,...e){for(let n of e){let i=t[n];if(typeof i=="boolean")return i}}function g(t,...e){for(let n of e){let i=t[n];if(typeof i=="number"&&Number.isFinite(i))return i}}function A(t){if(typeof t=="number"&&Number.isFinite(t))return t;if(t instanceof Date){let e=t.getTime();return Number.isFinite(e)?e:void 0}if(typeof t=="string"){let e=Date.parse(t);return Number.isFinite(e)?e:void 0}if(t&&typeof t=="object"){let e=t;if(typeof e.toMillis=="function"){let i=e.toMillis();return Number.isFinite(i)?i:void 0}let n=typeof e.seconds=="number"?e.seconds:typeof e._seconds=="number"?e._seconds:void 0;if(n!==void 0&&Number.isFinite(n)){let i=typeof e.nanoseconds=="number"?e.nanoseconds:typeof e._nanoseconds=="number"?e._nanoseconds:0;return n*1e3+Math.floor((Number.isFinite(i)?i:0)/1e6)}}}function Y(...t){let e=t.map(A).filter(n=>typeof n=="number"&&Number.isFinite(n));return e.length?Math.max(...e):void 0}function Q(t){if(typeof t!="string")return;let e=t.trim().toLowerCase();return e==="online"||e==="idle"||e==="offline"?e:void 0}function Ae(t){let e=Q("presenceStatus"in t?t.presenceStatus:void 0),n="presenceUpdatedAt"in t?A(t.presenceUpdatedAt):void 0,i="presenceExpiresAt"in t?A(t.presenceExpiresAt):void 0,r=n??Y(t.lastSeenAt,t.updatedAt,t.createdAt),o=i??A(t.expiresAt),a=e;a||(t.online?r!==void 0&&r+3e5<=Date.now()?a="idle":a="online":a="offline");let s=typeof t.ticket=="string"?t.ticket.trim():"",c="connectable"in t&&typeof t.connectable=="boolean"?t.connectable:a==="online"&&s.length>0;return {presenceStatus:a,presenceUpdatedAt:r,presenceExpiresAt:o,connectable:c}}function Te(t){return l(t)}function E(t,...e){return Te(p(t,...e))}function K(t){if(!Array.isArray(t))return;let e=Array.from(new Set(t.map(Te).filter(n=>!!n)));return e.length?e:void 0}function Pe(t){let e=M(t),n={webrtc:g(e,"webrtc"),iroh:g(e,"iroh"),irohLan:g(e,"irohLan","iroh_lan"),irohRelay:g(e,"irohRelay","iroh_relay"),ble:g(e,"ble"),moq:g(e,"moq")};return Object.values(n).some(i=>i!==void 0)?n:void 0}function pn(t){return (t.discoveryMode??"space")==="space"&&typeof t.apiKey=="string"&&t.apiKey.trim().length>0&&typeof t.spaceKey=="string"&&t.spaceKey.trim().length>0}function hn(t,e,n){return n?true:(typeof t.appTag=="string"?t.appTag:typeof t.tag=="string"?t.tag:void 0)===e}function It(t,e){let n=J(t),i=p(n,"deviceId","device_id")||e||"",r=p(n,"nodeId","node_id")||"",o=p(n,"ticket")||"";return {deviceId:i,deviceName:p(n,"deviceName","device_name")||"Unknown Device",online:!!n.online,ticket:o,friendTicket:p(n,"friendTicket","friend_ticket"),presenceStatus:Q(p(n,"presenceStatus","presence_status","livenessStatus","liveness_status")),presenceUpdatedAt:g(n,"presenceUpdatedAt","presence_updated_at")??Y(n.presenceUpdatedAt,n.presence_updated_at,n.lastSeenAt,n.last_seen_at,n.updatedAt,n.updated_at,n.createdAt,n.created_at),presenceExpiresAt:g(n,"presenceExpiresAt","presence_expires_at")??A(n.presenceExpiresAt??n.presence_expires_at)??A(n.expiresAt??n.expires_at),connectable:w(n,"connectable"),kind:p(n,"kind"),nodeId:r||void 0,devicePublicKeyJwk:n.devicePublicKeyJwk??n.device_public_key_jwk,platformType:p(n,"platformType","platform_type"),capabilities:n.capabilities||void 0,sessionId:p(n,"sessionId","session_id"),userId:p(n,"userId","user_id"),lastSeenAt:n.lastSeenAt??n.last_seen_at,expiresAt:n.expiresAt??n.expires_at,createdAt:n.createdAt??n.created_at,updatedAt:n.updatedAt??n.updated_at,metadata:p(n,"metadata"),excludedPeers:X(n.excludedPeers??n.excluded_peers),availableTransports:K(n.availableTransports??n.available_transports),transports:K(n.transports),topologyRole:n.topologyRole==="active"||n.topologyRole==="backup"?n.topologyRole:void 0,topologyRevision:Number.isSafeInteger(n.topologyRevision)&&Number(n.topologyRevision)>0?Number(n.topologyRevision):void 0}}function X(t){return Array.isArray(t)?t.filter(e=>typeof e=="string"):[]}function At(t){let e=Ae(t);return {...t,...e,connectionStatus:"connectionStatus"in t&&typeof t.connectionStatus=="string"?t.connectionStatus:t.online?"online":"disconnected",settledReady:"settledReady"in t&&typeof t.settledReady=="boolean"?t.settledReady:false,readinessState:"readinessState"in t&&typeof t.readinessState=="string"?t.readinessState:void 0,readinessReason:"readinessReason"in t&&typeof t.readinessReason=="string"?t.readinessReason:void 0,peerHealth:"peerHealth"in t&&typeof t.peerHealth=="string"?t.peerHealth:"unknown",peerId:"peerId"in t&&typeof t.peerId=="string"?t.peerId:void 0,promotionEligible:"promotionEligible"in t&&typeof t.promotionEligible=="boolean"?t.promotionEligible:true,scopes:"scopes"in t?X(t.scopes):[],connectionId:"connectionId"in t&&typeof t.connectionId=="string"?t.connectionId:void 0,deviceIdHint:"deviceIdHint"in t&&typeof t.deviceIdHint=="string"?t.deviceIdHint:void 0,transportStableId:"transportStableId"in t&&typeof t.transportStableId=="number"?t.transportStableId:"transportStableId"in t?t.transportStableId??null:void 0,transportGeneration:"transportGeneration"in t&&typeof t.transportGeneration=="number"?t.transportGeneration:void 0,routeGeneration:"routeGeneration"in t&&typeof t.routeGeneration=="number"?t.routeGeneration:void 0,activeTransport:"activeTransport"in t?t.activeTransport:void 0,parallelTransport:"parallelTransport"in t?t.parallelTransport:void 0,availableTransports:"availableTransports"in t?K(t.availableTransports):"transports"in t?K(t.transports):void 0,latencyMs:"latencyMs"in t&&typeof t.latencyMs=="number"?t.latencyMs:void 0,latencyByTransport:"latencyByTransport"in t?Pe(t.latencyByTransport):void 0}}function O(t,e){return e===void 0?true:e===null?t==null:t==null||t===e}function Ce(t,e){let n=O(t.connectionId,e.connectionId)&&O(t.nodeId,e.nodeId)&&O(t.transportStableId,e.transportStableId)&&O(t.transportGeneration,e.transportGeneration)&&O(t.routeGeneration,e.routeGeneration),i=(r,o)=>r!==void 0?r:n?o:void 0;return {inheritsSnapshot:n,fields:{connectionId:i(e.connectionId??void 0,t.connectionId),transportStableId:i(e.transportStableId,t.transportStableId),transportGeneration:i(e.transportGeneration,t.transportGeneration),routeGeneration:i(e.routeGeneration,t.routeGeneration),activeTransport:i(e.activeTransport,t.activeTransport),parallelTransport:i(e.parallelTransport,t.parallelTransport),latencyMs:n?t.latencyMs:void 0,latencyByTransport:n?t.latencyByTransport:void 0}}}var Tt={connectionId:void 0,transportStableId:null,transportGeneration:void 0,routeGeneration:void 0,activeTransport:void 0,parallelTransport:void 0,latencyMs:void 0,latencyByTransport:void 0};function Pt(t,e,n){let i=Ce(t,{connectionId:e.activeConnectionId,nodeId:e.nodeId,transportStableId:e.transportStableId,transportGeneration:e.transportGeneration,routeGeneration:e.routeGeneration,activeTransport:e.activeTransport,parallelTransport:e.parallelTransport}),r=n?n({connectionId:e.activeConnectionId??void 0,deviceId:e.deviceId??void 0,deviceIdHint:e.deviceIdHint??void 0,nodeId:e.nodeId??void 0}):t.promotionEligible??true;if(!r)return {...t,peerHealth:e.health??t.peerHealth,peerId:e.peerId??t.peerId,promotionEligible:r,scopes:e.scopes?.length?[...e.scopes]:t.scopes,nodeId:e.nodeId===void 0?t.nodeId:e.nodeId??void 0,deviceIdHint:e.deviceIdHint??t.deviceIdHint,...i.fields,readinessReason:e.readinessReason??t.readinessReason};let o=e.status??t.connectionStatus,a=typeof o=="string"?o.trim().toLowerCase():"",s=a==="failed"||a==="closed"||a==="disconnected",d=typeof e.readinessState=="string"&&e.readinessState.trim().length>0?e.readinessState==="routable":e.settledReady===true,l=t.settledReady===true||t.readinessState==="routable";if(i.inheritsSnapshot&&l&&!s&&!d)return {...t,peerHealth:e.health??t.peerHealth,peerId:e.peerId??t.peerId,promotionEligible:r,scopes:e.scopes?.length?[...e.scopes]:t.scopes,nodeId:e.nodeId===void 0?t.nodeId:e.nodeId??void 0,deviceIdHint:e.deviceIdHint??t.deviceIdHint,...i.fields,readinessReason:e.readinessReason??t.readinessReason};let u=s?false:d,f=d&&!s&&(a==="connecting"||a==="connected")?"connected":o,y=d?"routable":e.readinessState??(i.inheritsSnapshot?t.readinessState:void 0),m=u?e.readinessReason??"peer-session-settled":e.readinessReason??(i.inheritsSnapshot?t.readinessReason:void 0);return {...t,connectionStatus:f,settledReady:u,readinessState:y,readinessReason:m,peerHealth:e.health??t.peerHealth,peerId:e.peerId??t.peerId,promotionEligible:r,scopes:e.scopes?.length?[...e.scopes]:t.scopes,nodeId:e.nodeId===void 0?t.nodeId:e.nodeId??void 0,deviceIdHint:e.deviceIdHint??t.deviceIdHint,...i.fields}}function Ct(t,e){let n=Ce(t,{connectionId:e.connectionId,nodeId:e.nodeId,transportStableId:e.transportStableId,transportGeneration:e.transportGeneration,routeGeneration:e.routeGeneration,activeTransport:e.activeTransport,parallelTransport:e.parallelTransport});if(e.promotionEligible===false)return {...t,peerHealth:e.health??t.peerHealth,peerId:e.peerId??t.peerId,promotionEligible:false,nodeId:e.nodeId??t.nodeId,deviceIdHint:e.deviceIdHint??t.deviceIdHint,...n.fields,scopes:e.scopes?.length?[...e.scopes]:t.scopes};let i=e.status??t.connectionStatus,r=typeof i=="string"?i.trim().toLowerCase():"",o=r==="failed"||r==="closed"||r==="disconnected",a=t.settledReady===true||t.readinessState==="routable",s=e.routable===false;if(n.inheritsSnapshot&&a&&o&&!s)return {...t,peerHealth:t.peerHealth??e.health,peerId:t.peerId??e.peerId,promotionEligible:e.promotionEligible??t.promotionEligible??true,connectionId:t.connectionId??e.connectionId,deviceIdHint:t.deviceIdHint??e.deviceIdHint,scopes:t.scopes?.length?t.scopes:e.scopes??t.scopes};if(a&&o)return {...t,connectionStatus:i,settledReady:false,readinessState:void 0,readinessReason:e.error??t.readinessReason,peerHealth:e.health??t.peerHealth,peerId:e.peerId??t.peerId,promotionEligible:e.promotionEligible??t.promotionEligible??true,deviceIdHint:e.deviceIdHint??t.deviceIdHint,...Tt,scopes:e.scopes?.length?[...e.scopes]:t.scopes};let c=e.routable===true||e.protocolState==="routable";if(n.inheritsSnapshot&&a&&!o&&!c)return {...t,peerHealth:t.peerHealth??e.health,peerId:t.peerId??e.peerId,promotionEligible:e.promotionEligible??t.promotionEligible??true,connectionId:t.connectionId??e.connectionId,deviceIdHint:t.deviceIdHint??e.deviceIdHint,transportStableId:t.transportStableId??e.transportStableId,transportGeneration:t.transportGeneration??e.transportGeneration,routeGeneration:t.routeGeneration??e.routeGeneration,activeTransport:t.activeTransport??e.activeTransport,parallelTransport:t.parallelTransport===void 0?e.parallelTransport:t.parallelTransport,scopes:t.scopes?.length?t.scopes:e.scopes??t.scopes};let d=e.transportState==="connected"&&e.health==="healthy",l=o?false:c,u=!o&&(c||d)&&(r==="connecting"||r==="connected"||e.transportState==="connected")?"connected":i,f=l?"routable":(e.routable===false&&e.protocolState?e.protocolState:void 0)??(n.inheritsSnapshot?t.readinessState:void 0)??(e.status==="connecting"?e.transportState==="connected"?"transport-only":"connecting":void 0),y=l?(n.inheritsSnapshot?t.readinessReason:void 0)??(e.routable===true?"peer-projection-routable":void 0):(e.routable===false&&e.error?e.error:void 0)??(n.inheritsSnapshot?t.readinessReason:void 0)??(e.status==="connecting"?e.transportState==="connected"?"peer-projection-transport-ready":"peer-projection-connecting":void 0);return {...t,connectionStatus:u,settledReady:l,readinessState:f,readinessReason:y,peerHealth:e.health??t.peerHealth,peerId:e.peerId??t.peerId,promotionEligible:e.promotionEligible??t.promotionEligible??true,nodeId:e.nodeId??t.nodeId,deviceIdHint:e.deviceIdHint??t.deviceIdHint,...n.fields,scopes:e.scopes?.length?[...e.scopes]:t.scopes}}function Mt(t){let{device:e,session:n=null,peer:i=null,isPromotionEligible:r}=t,o=At(e);return n&&(o=Pt(o,n,r)),i&&(o=Ct(o,i)),Ie(o)}function gn(t){let e=J(t),n=It(e),i=Q(p(e,"presenceStatus","presence_status","livenessStatus","liveness_status")),r=Ae({...n,...i?{presenceStatus:i}:{},presenceUpdatedAt:g(e,"presenceUpdatedAt","presence_updated_at")??Y(e.presenceUpdatedAt,e.presence_updated_at,e.lastSeenAt,e.last_seen_at,e.updatedAt,e.updated_at,e.createdAt,e.created_at),presenceExpiresAt:g(e,"presenceExpiresAt","presence_expires_at")??A(e.presenceExpiresAt??e.presence_expires_at)??A(e.expiresAt??e.expires_at),connectable:w(e,"connectable")}),o={...n,...r,connectionStatus:p(e,"connectionStatus","connection_status")||"disconnected",settledReady:w(e,"settledReady","settled_ready")??false,readinessState:p(e,"readinessState","readiness_state")??void 0,readinessReason:p(e,"readinessReason","readiness_reason")??void 0,peerHealth:p(e,"peerHealth","peer_health")||"unknown",peerId:p(e,"peerId","peer_id"),scopes:X(e.scopes),connectionId:p(e,"connectionId","connection_id"),deviceIdHint:p(e,"deviceIdHint","device_id_hint"),transportStableId:g(e,"transportStableId","activeTransportStableId","active_transport_stable_id")??void 0,transportGeneration:g(e,"transportGeneration","transport_generation")??void 0,routeGeneration:g(e,"routeGeneration","route_generation")??void 0,activeTransport:E(e,"activeTransport","active_transport"),parallelTransport:E(e,"parallelTransport","parallel_transport")??null,availableTransports:K(e.availableTransports??e.available_transports),latencyMs:g(e,"latencyMs","latency_ms"),latencyByTransport:Pe(e.latencyByTransport??e.latency_by_transport)};return Mt({device:o})}function yn(t){let e=J(t);return Ie({peerId:p(e,"peerId","peer_id")||"",deviceId:p(e,"deviceId","device_id"),deviceIdHint:p(e,"deviceIdHint","device_id_hint"),nodeId:p(e,"nodeId","node_id"),activeConnectionId:p(e,"activeConnectionId","active_connection_id"),candidates:Array.isArray(e.candidates)?e.candidates.filter(n=>typeof n=="string"):Array.isArray(e.candidateConnectionIds)?e.candidateConnectionIds.filter(n=>typeof n=="string"):Array.isArray(e.candidate_connection_ids)?e.candidate_connection_ids.filter(n=>typeof n=="string"):[],status:p(e,"status")||"disconnected",health:p(e,"health")||"unknown",settledReady:w(e,"settledReady","settled_ready")??false,readinessState:p(e,"readinessState","readiness_state")??void 0,transportStableId:g(e,"transportStableId","activeTransportStableId","active_transport_stable_id")??void 0,transportGeneration:g(e,"transportGeneration","transport_generation")??void 0,routeGeneration:g(e,"routeGeneration","route_generation")??void 0,activeTransport:E(e,"activeTransport","active_transport"),parallelTransport:E(e,"parallelTransport","parallel_transport")??null,replacementPending:w(e,"replacementPending","replacement_pending")??void 0,logicalSessionTerminal:w(e,"logicalSessionTerminal","logical_session_terminal")??false,lastTransitionAtMs:g(e,"lastTransitionAtMs","lastLifecycleTransitionAtMs","last_lifecycle_transition_at_ms")??void 0,readinessReason:p(e,"readinessReason","readiness_reason")??void 0,transitionCount:g(e,"transitionCount","transition_count")??void 0,connectTransitions:g(e,"connectTransitions","connectingTransitionCount","connecting_transition_count")??void 0,replacementCount:g(e,"replacementCount","replacement_count")??void 0,retireCount:g(e,"retireCount","retire_count")??void 0,lastDisconnectReason:p(e,"lastDisconnectReason","last_disconnect_reason")??void 0,lastReconnectReason:p(e,"lastReconnectReason","last_reconnect_reason")??void 0,scopes:Array.isArray(e.scopes)?e.scopes.filter(n=>typeof n=="string"):[],lastSeenAtMs:typeof e.lastSeenAtMs=="number"?e.lastSeenAtMs:typeof e.last_seen_at_ms=="number"?e.last_seen_at_ms:0,error:p(e,"error"),errorCode:p(e,"errorCode","error_code")??void 0,retryable:w(e,"retryable")??void 0,errorPlane:p(e,"errorPlane","error_plane")??void 0})}function mn(t){let e=M(t);return {connectionId:typeof e.connectionId=="string"?e.connectionId:"",nodeId:typeof e.nodeId=="string"?e.nodeId:null,deviceId:typeof e.deviceId=="string"?e.deviceId:null,deviceIdHint:typeof e.deviceIdHint=="string"?e.deviceIdHint:null,endpointId:typeof e.endpointId=="string"?e.endpointId:null,transportGeneration:typeof e.transportGeneration=="number"?e.transportGeneration:0,routeGeneration:typeof e.routeGeneration=="number"?e.routeGeneration:void 0,transportStableId:typeof e.transportStableId=="number"?e.transportStableId:null,transportSource:typeof e.transportSource=="string"?e.transportSource:null,lastTransportChangeAtMs:typeof e.lastTransportChangeAtMs=="number"?e.lastTransportChangeAtMs:0,lastRouteChangeAtMs:typeof e.lastRouteChangeAtMs=="number"?e.lastRouteChangeAtMs:void 0,state:typeof e.state=="string"?e.state:"pending",statusReason:typeof e.statusReason=="string"?e.statusReason:null,transitionCount:typeof e.transitionCount=="number"?e.transitionCount:void 0,connectTransitions:typeof e.connectTransitions=="number"?e.connectTransitions:void 0,replacementCount:typeof e.replacementCount=="number"?e.replacementCount:void 0,retireCount:typeof e.retireCount=="number"?e.retireCount:void 0,lastDisconnectReason:typeof e.lastDisconnectReason=="string"?e.lastDisconnectReason:void 0,lastReconnectReason:typeof e.lastReconnectReason=="string"?e.lastReconnectReason:void 0,createdAtMs:typeof e.createdAtMs=="number"?e.createdAtMs:0,updatedAtMs:typeof e.updatedAtMs=="number"?e.updatedAtMs:0}}function fn(t){let e=M(t);return {peerId:typeof e.peerId=="string"?e.peerId:null,deviceId:typeof e.deviceId=="string"?e.deviceId:null,deviceIdHint:typeof e.deviceIdHint=="string"?e.deviceIdHint:null,nodeId:typeof e.nodeId=="string"?e.nodeId:null}}function Et(t){switch(t){case "connected":return "connected";case "connecting":return "connecting";case "failed":return "failed";default:return "closed"}}function vn(t){let e=t.activeConnectionId||t.candidates[0]||null;if(!e)return null;let n=Et(t.status),i=n==="connected"?"connected":n==="connecting"?"connecting":"closed",r=n==="connected"?t.settledReady?"routable":"transport-only":n==="connecting"?"connecting":"closed";return {connectionId:e,deviceId:t.deviceId??null,deviceIdHint:t.deviceIdHint??null,remoteNodeId:t.nodeId??null,state:n,transportState:i,protocolState:r,routable:!!t.settledReady,readinessState:t.readinessState,readinessReason:t.readinessReason,transportGeneration:t.transportGeneration,routeGeneration:t.routeGeneration,transportStableId:t.transportStableId,activeTransport:t.activeTransport,parallelTransport:t.parallelTransport??null,replacementInProgress:t.replacementPending,logicalSessionTerminal:t.logicalSessionTerminal===true,lastTransitionAtMs:t.lastTransitionAtMs,transitionCount:t.transitionCount,connectTransitions:t.connectTransitions,replacementCount:t.replacementCount,retireCount:t.retireCount,lastDisconnectReason:t.lastDisconnectReason??void 0,lastReconnectReason:t.lastReconnectReason??void 0,updatedAt:t.lastSeenAtMs,error:t.error??void 0}}function bn(t){let e=M(t),n=p(e,"connectionId","connection_id");if(!n)return null;let i=p(e,"state")||"connecting",r=g(e,"createdAt","created_at")??g(e,"updatedAt","updated_at")??Date.now(),o=g(e,"updatedAt","updated_at")??r;return {connectionId:n,deviceId:p(e,"deviceId","device_id"),deviceIdHint:p(e,"deviceIdHint","device_id_hint"),remoteNodeId:p(e,"remoteNodeId","remote_node_id"),state:i,transportState:p(e,"transportState","transport_state")??(i==="connected"?"connected":i==="connecting"?"connecting":"closed"),protocolState:p(e,"protocolState","protocol_state")??(i==="connected"?"routable":i==="connecting"?"connecting":"closed"),routable:w(e,"routable")??false,logicalSessionTerminal:w(e,"logicalSessionTerminal","logical_session_terminal")??false,readinessState:p(e,"readinessState","readiness_state")??void 0,readinessReason:p(e,"readinessReason","readiness_reason")??void 0,transportGeneration:g(e,"transportGeneration","transport_generation")??void 0,routeGeneration:g(e,"routeGeneration","route_generation")??void 0,transportStableId:g(e,"transportStableId","activeTransportStableId","active_transport_stable_id")??void 0,activeTransport:E(e,"activeTransport","active_transport"),parallelTransport:E(e,"parallelTransport","parallel_transport")??null,replacementInProgress:w(e,"replacementInProgress","replacement_in_progress")??void 0,lastTransitionAtMs:g(e,"lastTransitionAtMs","lastLifecycleTransitionAtMs","last_lifecycle_transition_at_ms")??void 0,transitionCount:g(e,"transitionCount","transition_count")??void 0,connectTransitions:g(e,"connectTransitions","connectingTransitionCount","connecting_transition_count")??void 0,replacementCount:g(e,"replacementCount","replacement_count")??void 0,retireCount:g(e,"retireCount","retire_count")??void 0,lastDisconnectReason:p(e,"lastDisconnectReason","last_disconnect_reason")??void 0,lastReconnectReason:p(e,"lastReconnectReason","last_reconnect_reason")??void 0,error:p(e,"error")??void 0,createdAt:r,updatedAt:o}}function wn(t,e){return t?t.connectionId===e.connectionId&&(t.deviceId??null)===(e.deviceId??null)&&(t.deviceIdHint??null)===(e.deviceIdHint??null)&&(t.remoteNodeId??null)===(e.remoteNodeId??null)&&t.state===e.state&&(t.transportState??null)===(e.transportState??null)&&(t.protocolState??null)===(e.protocolState??null)&&!!t.routable==!!e.routable&&(t.activeTransport??null)===(e.activeTransport??null)&&(t.parallelTransport??null)===(e.parallelTransport??null)&&(t.transportStableId??null)===(e.transportStableId??null)&&(t.transportGeneration??null)===(e.transportGeneration??null)&&(t.routeGeneration??null)===(e.routeGeneration??null)&&!!t.replacementInProgress==!!e.replacementInProgress&&!!t.logicalSessionTerminal==!!e.logicalSessionTerminal&&(t.transitionCount??null)===(e.transitionCount??null)&&(t.connectTransitions??null)===(e.connectTransitions??null)&&(t.replacementCount??null)===(e.replacementCount??null)&&(t.retireCount??null)===(e.retireCount??null)&&(t.lastDisconnectReason??null)===(e.lastDisconnectReason??null)&&(t.lastReconnectReason??null)===(e.lastReconnectReason??null)&&(t.error??null)===(e.error??null):false}
|
|
2
|
+
export{Mt as A,gn as B,yn as C,mn as D,fn as E,vn as F,bn as G,wn as H,kt as a,ge as b,Ye as c,Bt as d,Ft as e,jt as f,ye as g,qt as h,Yt as i,Qt as j,Xt as k,Zt as l,en as m,vt as n,wt as o,nn as p,St as q,Rt as r,Re as s,on as t,sn as u,an as v,J as w,pn as x,hn as y,It as z};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import {a as a$1}from'./chunk-AYHD4X2R.js';import {o,b,a,t,m,g,x,y,h,z,B,C,F,G,H,d as d$1,e as e$1}from'./chunk-25CN4MLA.js';import {c,e,d,f,b as b$1}from'./chunk-XMYBBLYK.js';import {a as a$2}from'./chunk-OT7IPLZE.js';import {a as a$3}from'./chunk-CNAW5BZ3.js';import {c as c$1}from'./chunk-CCCYE3XN.js';import {a as a$4}from'./chunk-JPBW67B3.js';function M(u){if(!u)return null;let e=2166136261;for(let t=0;t<u.length;t+=1)e^=u.charCodeAt(t),e=Math.imul(e,16777619);return `fp-${(e>>>0).toString(16).padStart(8,"0")}`}var _=class _{constructor(e){this.deps=e;this.startedAutoConnectKey=null;this.browserAutoConnectUnsubscribe=null;this.desiredPeerRevision=0;this.desiredPeerSignature=null;this.desiredPeerSubmission=null;this.desiredPeerSubmissionQueue=Promise.resolve();this.queuedDesiredPeers=null;this.desiredPeersByDeviceId=new Map;this.wakeSubmission=null;this.presenceState=null;this.presenceStartGeneration=0;this.localExcludedPeers=new Set;this.localDesiredPeerDeviceId=null;for(let t of e.initialExcludedPeers??[]){let i=t.trim().toLowerCase();i&&this.localExcludedPeers.add(i);}}stop(){this.stopAutoConnect(),this.stopPresenceLoop();}get autoConnectKey(){return this.startedAutoConnectKey}set autoConnectKey(e){this.startedAutoConnectKey=e;}get presenceLoopState(){return this.presenceState}set presenceLoopState(e){this.presenceState=e;}stopPresence(){this.stopPresenceLoop();}updatePresenceLoopState(e){this.presenceState=e;}startAutoConnect(e,t){if(this.deps.isTicketOnlyMode())return;let i=t.trim()||this.deps.resolveWebLogicalDeviceId(),n=`${e}::${i}`;this.startedAutoConnectKey===n&&this.browserAutoConnectUnsubscribe||(this.stopAutoConnect(),this.localDesiredPeerDeviceId=i,this.startedAutoConnectKey=n,this.browserAutoConnectUnsubscribe=this.deps.getCoordinationSignaling().onDevicesChange(o=>this.submitDesiredPeers(o),this.currentLocalNodeId()??void 0));}wakeRustAutoConnectOwner(){return this.deps.isTicketOnlyMode()||!this.startedAutoConnectKey||this.wakeSubmission?false:(this.wakeSubmission=this.deps.waitForWasmClient(500).then(async e=>{e&&typeof e.wake_browser_auto_connect=="function"&&await e.wake_browser_auto_connect();}).finally(()=>{this.wakeSubmission=null;}),true)}submitDesiredPeers(e){if(!this.startedAutoConnectKey)return;let i=this.normalizeDesiredPeers(e);this.rememberDesiredPeers(i)&&(this.queuedDesiredPeers=i,this.flushDesiredPeerSubmission());}observeDesiredPeerProjection(e){this.rememberDesiredPeers(this.normalizeDesiredPeers(e));}async submitDesiredPeerProjection(e,t){if(!Number.isSafeInteger(e)||e<=0)throw new Error("Desired-peer projection revision must be a positive safe integer.");let i=this.startedAutoConnectKey;if(!i)throw new Error("Cannot submit a desired-peer projection before managed auto-connect starts.");let n=this.normalizeDesiredPeers(t);this.rememberDesiredPeers(n),this.queuedDesiredPeers=null,this.desiredPeerRevision=Math.max(this.desiredPeerRevision,e),await this.enqueueDesiredPeerSubmission(i,e,n);}async handleRoomArchitectureChange(){let e=this.startedAutoConnectKey;if(this.deps.isTicketOnlyMode()||!e)return false;let t=Array.from(this.desiredPeersByDeviceId.values());this.queuedDesiredPeers=null;let i=++this.desiredPeerRevision;return await this.enqueueDesiredPeerSubmission(e,i,t),true}rememberDesiredPeers(e){this.desiredPeersByDeviceId=new Map(e.map(i=>[i.deviceId,i]));let t=JSON.stringify(e);return t===this.desiredPeerSignature?false:(this.desiredPeerSignature=t,this.deps.onDesiredPeersChanged?.(),true)}resolveDesiredPeer(e,t){let i=typeof e=="string"?e.trim():"",n=typeof t=="string"?t.trim():"";if(i){let o=this.desiredPeersByDeviceId.get(i);if(o&&(!n||!o.nodeId||o.nodeId===n))return o}return n?Array.from(this.desiredPeersByDeviceId.values()).find(o=>o.nodeId===n)??null:null}flushDesiredPeerSubmission(){if(this.desiredPeerSubmission||!this.queuedDesiredPeers||!this.startedAutoConnectKey)return;let e=this.startedAutoConnectKey,t=this.queuedDesiredPeers,i=++this.desiredPeerRevision;this.queuedDesiredPeers=null,this.desiredPeerSubmission=this.enqueueDesiredPeerSubmission(e,i,t).catch(()=>{}).finally(()=>{this.desiredPeerSubmission=null,this.flushDesiredPeerSubmission();});}normalizeDesiredPeers(e){return (Array.isArray(e)?e:[]).map(t=>({deviceId:String(t?.deviceId??"").trim(),nodeId:typeof t?.nodeId=="string"&&t.nodeId.trim()||null,ticket:typeof t?.ticket=="string"&&t.ticket.trim()||null,online:t?.online===true,sessionId:typeof t?.sessionId=="string"&&t.sessionId.trim()||null,excludedPeers:Array.isArray(t?.excludedPeers)?[...new Set(t.excludedPeers.map(i=>String(i??"").trim().toLowerCase()).filter(Boolean))].sort():[],devicePublicKeyJwk:t?.devicePublicKeyJwk,topologyRole:t?.topologyRole,topologyRevision:t?.topologyRevision})).filter(t=>t.deviceId.length>0).sort((t,i)=>t.deviceId.localeCompare(i.deviceId))}enqueueDesiredPeerSubmission(e,t,i,n=this.roomGossipFanoutEnabled()){let o=this.desiredPeerSubmissionQueue.then(async()=>{if(this.startedAutoConnectKey!==e)return;let r=await this.deps.waitForWasmClient();if(this.startedAutoConnectKey===e){if(!r||typeof r.submit_browser_desired_peers!="function"){this.deps.warnMissingWasmOnce("submitBrowserDesiredPeers");return}if(await Promise.all(i.map(async s=>{if(s.ticket)try{await this.deps.rememberRouteRepairTokenFromTicket(s.ticket);}catch(c){console.warn("[WasmSignaling] failed to retain desired-peer admission token",{deviceId:s.deviceId,nodeId:s.nodeId,error:c});}})),n){if(typeof r.submit_browser_desired_peers_with_sparse_fanout!="function"){await r.submit_browser_desired_peers(t,JSON.stringify([])),this.deps.warnMissingWasmOnce("submitBrowserDesiredPeersWithSparseFanout");return}if(!this.deps.capabilityKey)throw new Error("Sparse fanout requires an explicit capability avenue.");await r.submit_browser_desired_peers_with_sparse_fanout(t,JSON.stringify(i),this.deps.capabilityKey,this.localDesiredPeerDeviceId,this.deps.localDeviceKeyX,true);}else await r.submit_browser_desired_peers(t,JSON.stringify(i));}});return this.desiredPeerSubmissionQueue=o.catch(r=>{console.warn("[WasmSignaling] failed to submit browser desired peers to Rust",{revision:t,error:r});}),o}roomGossipFanoutEnabled(){return typeof this.deps.roomGossipFanout=="function"?this.deps.roomGossipFanout():this.deps.roomGossipFanout===true}async excludeAutoConnect(e,t){let i=await this.deps.waitForWasmClient();i&&typeof i.set_auto_connect_excluded=="function"&&await i.set_auto_connect_excluded(e,t),await this.recordAutoConnectExcludedForPresence(e,t);}async installInitialAutoConnectExclusions(e){if(typeof e?.set_auto_connect_excluded=="function")for(let t of this.currentExcludedPeersSnapshot())await e.set_auto_connect_excluded(t,true);}async recordAutoConnectExcludedForPresence(e,t){let i=e.trim().toLowerCase();if(!i)return;t?this.localExcludedPeers.add(i):this.localExcludedPeers.delete(i);let n=this.deps.resolveWebLogicalDeviceId();n&&await this.deps.updateExcludedPeers(n,this.currentExcludedPeersSnapshot());}async startPresenceLoop(e,t,i,n,o){if(this.deps.isTicketOnlyMode())return;this.stopPresenceLoop();let r=this.presenceStartGeneration;this.presenceState={userId:e,localNodeId:t,ticket:n,metadata:o,deviceName:i};let s=this.deps.resolveWebLogicalDeviceId(),c=await this.deps.withWebPresenceMetadata(o,s);r!==this.presenceStartGeneration||this.presenceState===null||await this.deps.updatePresence(t,n,true,_.PRESENCE_LEASE_MS,c,i);}stopAutoConnect(){this.browserAutoConnectUnsubscribe?.(),this.browserAutoConnectUnsubscribe=null,this.startedAutoConnectKey=null,this.localDesiredPeerDeviceId=null,this.desiredPeerSignature=null,this.queuedDesiredPeers=null,this.desiredPeersByDeviceId.clear(),this.wakeSubmission=null;}currentExcludedPeersSnapshot(){return Array.from(this.localExcludedPeers).sort()}currentLocalNodeId(){let e=this.presenceState?.localNodeId;return typeof e=="string"&&e.trim()||null}stopPresenceLoop(){this.presenceStartGeneration+=1,this.presenceState=null;}};_.PRESENCE_LEASE_MS=15*6e4;var R=_;function ne(){if(!(typeof window>"u"))try{if(new URL(import.meta.url).pathname.includes("/node_modules/.vite/deps/"))return new URL("/node_modules/openrtc/dist/openrtc_bg.wasm",window.location.origin)}catch{}}async function oe(){let u=await import('./openrtc-UBIKDAZ5.js');return {initWasm:e=>u.default(e??ne()),WasmClient:u.WasmClient,start:u.start}}function re(u){try{let e=u.replace(/-/g,"+").replace(/_/g,"/"),t=(4-e.length%4)%4,i=e+"=".repeat(t);if(typeof atob=="function")return JSON.parse(atob(i));let n=globalThis.Buffer;if(n)return JSON.parse(n.from(i,"base64").toString("utf8"))}catch{return null}return null}function se(u){let e=typeof u=="string"?u.trim():"";if(!e)return {present:false};let t=e.lastIndexOf("."),i=t>=0?e.slice(0,t):e,n=t>=0?e.slice(t+1):null,o=n?re(n):null,r=o&&typeof o.t=="string"&&o.t.trim().length>0?o.t.trim():null,s=o&&typeof o.s=="string"&&o.s.trim().length>0?o.s.trim():null,c=o&&typeof o.m=="number"&&Number.isFinite(o.m)?o.m:null;return {present:true,irohFingerprint:M(i),tokenFingerprint:M(r),tokenSuffixFingerprint:M(n),scope:s,maxConnections:c}}function E(u,e,t={}){let i=typeof u.finishSend=="function"?u.finishSend.bind(u):typeof u.finish_send=="function"?u.finish_send.bind(u):null,n=typeof u.cancelSend=="function"?u.cancelSend.bind(u):typeof u.cancel_send=="function"?u.cancel_send.bind(u):null;if(!i){if(t.requireFinish===true)throw new Error("WASM peer stream is missing finishSend(); rebuild the current OpenRTC WASM before sending application data");return e}let o=e.getWriter(),r=new WritableStream({write:s=>o.write(s),async close(){await o.close(),await i();},async abort(s){await n?.(),await o.abort(s);}});return a$4(r,n)}var p=class p{constructor(e$1){this.spaceNamespaceIdPromise=null;this.cachedSpaceNamespaceId=null;this.authListeners=[];this.wasmClient=null;this.createdAtMs=Date.now();this.missingWasmWarnings=new Set;this.wasmReadyWarningDelayMs=15e3;this.browserCoordinationSignaling=null;this.effectiveRoomArchitecture="mesh";this.lastObservedFirebaseUserId=null;this.sessionReaders=new Set;this.authContext=null;this.injectedBrowserAuthSessionActive=false;this.hasSyncedAuthToWasmClient=false;this.lastWasmAuthUserId=null;this.lastWasmAuthToken=null;this.lastDeliveredConnectionStates=new Map;this.authScopedRuntimeGeneration=0;this.coreClient=null;this.applicationRouteEscalations=new Map;this.applicationRouteEscalationAttemptKeys=new Map;this.applicationRouteEscalationUnsubscribe=null;this.routeSubscriptionGeneration=-1;this.applicationRouteEscalationSubscriptionEpoch=0;this.appTag=c(e$1),this.options={...e$1,appTag:this.appTag,authMode:d(e$1),projectId:e(e$1)},this.effectiveRoomArchitecture=e$1.coordinationRoomArchitecture==="sparse"||e$1.coordinationRoomGossipFanout===true?"sparse":"mesh",this.coordinationHost=new b({appTag:this.appTag,projectId:this.options.projectId,discoveryMode:this.options.discoveryMode,signalingMode:this.options.signalingMode,gateway:this.options.coordinationGateway,avenueOverride:this.options.coordinationAvenueOverride,roomArchitecture:this.options.coordinationRoomArchitecture,initialExcludedPeers:this.options.initialAutoConnectExcludedDeviceIds,resolveSpaceNamespaceId:()=>this.ensureSpaceNamespaceIdPromise(),getCurrentUserId:()=>this.getCurrentUserId(),getAuthToken:async(r=false)=>this.currentUser?.getToken?.(r)??null,getAppCheckToken:async(r=false)=>{let s=this.authContext?.appCheckTokenProvider??this.options.attestationTokenProvider;return s?s(r):a().getAppCheckToken(r)},getLocalDeviceId:()=>this.resolveWebLogicalDeviceId(),getDefaultDeviceName:()=>this.getDefaultBrowserDeviceName(),getPlatformType:()=>this.options.coordinationPlatformType??"web",normalizeDevice:(r,s)=>this.normalizeDevice(r,s)});let n=this.options.coordinationRoomGossipFanout===true||this.options.coordinationRoomArchitecture==="auto"||this.options.coordinationRoomArchitecture==="sparse"?c$1(this.options.coordinationAvenueOverride).key:void 0;if(this.presenceManager=new R({isTicketOnlyMode:()=>this.isTicketOnlyMode(),waitForWasmClient:(r,s)=>this.waitForWasmClient(r,s),warnMissingWasmOnce:r=>this.warnMissingWasmOnce(r),resolveWebLogicalDeviceId:()=>this.resolveWebLogicalDeviceId(),withWebPresenceMetadata:(r,s)=>this.withWebPresenceMetadata(r,s),updatePresence:(r,s,c,a,d,h)=>this.updatePresence(r,s,c,a,d,h),updateExcludedPeers:(r,s)=>this.getCoordinationSignaling().updateDevice(r,{excludedPeers:s}),getCoordinationSignaling:()=>this.getCoordinationSignaling(),rememberRouteRepairTokenFromTicket:r=>this.coreClient?.rememberRouteRepairTokenFromTicket?.(r)??Promise.resolve(false),onDesiredPeersChanged:()=>this.retryManagedApplicationRouteEscalations(),roomGossipFanout:()=>this.effectiveRoomArchitecture==="sparse",capabilityKey:n,localDeviceKeyX:this.options.coordinationDevicePublicKeyX,initialExcludedPeers:this.options.initialAutoConnectExcludedDeviceIds}),this.persistenceReady=Promise.resolve(),this.isTicketOnlyMode()||this.usesProviderNeutralGrant()){this.app=null,this.auth=null;return}let o=a();this.app=o.getApp(),this.auth=o.getAuth(),o.onAuthStateChanged(r=>{if(this.authContext)return;if(this.isSpaceMode()){this.authListeners.forEach(a=>a(this.toRuntimeIdentity(r)));return}let s=r?.uid??null,c=this.lastObservedFirebaseUserId;this.lastObservedFirebaseUserId=s,c&&c!==s&&this.stopAuthActivity({userId:c}),this.browserCoordinationSignaling?.handleScopeChange()??this.coordinationHost.handleScopeChange(),this.authListeners.forEach(a=>a(this.toRuntimeIdentity(r)));});}async loadBrowserWasmRuntime(){return oe()}get tag(){return this.appTag}capabilities(){return t()}getDeviceIdentityStorageKey(){let e=f(this.options);return `${p.WEB_DEVICE_ID_STORAGE_PREFIX}_${e}`}getDeviceIdPersistenceMode(){return this.options.deviceIdPersistence??this.options.nodeIdPersistence??"persistent"}isTicketOnlyMode(){return this.options.signalingMode==="ticket-only"}usesProviderNeutralGrant(){return typeof this.options.coordinationGateway?.grantProvider=="function"}createRandomDeviceId(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`web-${Date.now()}-${Math.random().toString(36).slice(2,10)}`}resolveWebLogicalDeviceId(){let e=this.options.localDeviceId?.trim();if(e)return e;let t=this.getDeviceIdPersistenceMode();if(typeof localStorage>"u")return this.createRandomDeviceId();let i=this.getDeviceIdentityStorageKey(),n=Date.now(),o=null;try{let d=localStorage.getItem(i);o=d?JSON.parse(d):null;}catch{o=null;}let r=typeof o?.deviceId=="string"?o.deviceId.trim():"",s=typeof o?.expiresAt=="number"?o.expiresAt:void 0;if(t==="persistent"){let d=r||this.createRandomDeviceId();return localStorage.setItem(i,JSON.stringify({deviceId:d})),d}if(r&&typeof s=="number"&&s>n){let d=n+p.EPHEMERAL_DEVICE_ID_TTL_MS;return localStorage.setItem(i,JSON.stringify({deviceId:r,expiresAt:d})),r}let c=this.createRandomDeviceId(),a=n+p.EPHEMERAL_DEVICE_ID_TTL_MS;return localStorage.setItem(i,JSON.stringify({deviceId:c,expiresAt:a})),c}getDefaultBrowserDeviceName(){return this.options.deviceName?.trim()||(this.options.storagePrefix?`Web (${this.options.storagePrefix.replace(/_$/,"")})`:"Web Browser")}async getLocalDeviceInfo(){return {deviceId:this.resolveWebLogicalDeviceId(),deviceName:this.getDefaultBrowserDeviceName(),platformType:this.options.coordinationPlatformType??"web"}}getCoordinationSignaling(){return this.browserCoordinationSignaling??this.coordinationHost.getSignaling()}usesCoordinationGateway(){return this.coordinationHost.usesGateway()}setCoordinationHostAvailability(e){this.coordinationHost.setHostAvailability(e),this.browserCoordinationSignaling?.setHostAvailability?.(e);}async reconnectCoordinationAfterHostResume(){let e=this.browserCoordinationSignaling;if(e?.reconnectAfterHostResume){await e.reconnectAfterHostResume();return}await this.coordinationHost?.reconnectAfterHostResume();}async getCoordinationNativeTrustToken(e=false){return this.coordinationHost.getNativeTrustToken(e)}invalidateCoordinationNativeTrustToken(){this.coordinationHost.invalidateNativeTrustToken();}subscribeCoordinationNativeTrustToken(e,t){return this.coordinationHost.subscribeNativeTrustToken(e,t)}setCoordinationLocalDeviceId(e){if(!this.options.coordinationGateway)return;let t=e.trim();t&&(this.options.localDeviceId=t);}setCoordinationPlatformType(e){this.options.coordinationGateway&&(this.options.coordinationPlatformType=e);}async setCoordinationExcludedPeers(e){let t=this.resolveWebLogicalDeviceId();if(!t)throw new Error("The local device must be known before publishing peer exclusions.");await this.getCoordinationSignaling().updateDevice(t,{excludedPeers:e});}async joinCoordinationRoom(e,t,i){let n=this.getCoordinationSignaling();if(!n.joinCoordinationRoom)throw new Error("The active coordination provider does not support rooms.");await n.joinCoordinationRoom(e,t,i);}async leaveCoordinationRoom(e){await this.getCoordinationSignaling().leaveCoordinationRoom?.(e);}async getCoordinationRoomMembers(e){let t=this.getCoordinationSignaling();if(!t.getCoordinationRoomMembers)throw new Error("The active coordination provider does not support rooms.");return t.getCoordinationRoomMembers(e)}watchCoordinationRoomMembers(e,t){let i=this.getCoordinationSignaling();if(!i.watchCoordinationRoomMembers)throw new Error("The active coordination provider does not support rooms.");return i.watchCoordinationRoomMembers(e,t)}async withWebPresenceMetadata(e,t){let i;if(!e||!e.trim())i=JSON.stringify({deviceId:t});else {try{let n=JSON.parse(e);if(n&&typeof n=="object"&&!Array.isArray(n))return i=JSON.stringify({...n,deviceId:t}),await m(i)??i}catch{}i=JSON.stringify({deviceId:t,metadata:e});}return await m(i)??i}async setAuthContext(e){let t=this.injectedBrowserAuthSessionActive,i=this.authContext?.userId??null,n=e?.userId??null;if(this.authContext=e,!this.isTicketOnlyMode()&&!this.usesProviderNeutralGrant()&&e?.customToken?.trim()&&!(g()&&this.options.authMode==="external"&&typeof e.tokenProvider=="function"))try{await this.ensureBrowserPlatformAuth(e.userId,e.customToken.trim());}catch(o){console.warn("[WasmBridge] ensureBrowserPlatformAuth failed (non-fatal):",o);}else if(!this.isTicketOnlyMode()&&!this.usesProviderNeutralGrant()&&!e&&t)try{await this.auth?.signOut();}catch(o){console.warn("[WasmBridge] Failed to clear injected browser auth session:",o);}finally{this.injectedBrowserAuthSessionActive=false;}this.syncWasmAuthToken(),!this.isTicketOnlyMode()&&i!==n&&await(this.browserCoordinationSignaling?.handleScopeChange()??this.coordinationHost.handleScopeChange()),this.authListeners.forEach(o=>o(this.currentUser));}async ensureBrowserPlatformAuth(e,t){if((this.auth?.currentUser?.uid??null)===e){this.injectedBrowserAuthSessionActive=true;return}await a().signInWithCustomTokenValue(t),this.injectedBrowserAuthSessionActive=true;}syncWasmAuthToken(){let e=this.wasmClient?.setIdentityCredential??this.wasmClient?.set_auth_token;if(!this.wasmClient||typeof e!="function"||!this.authContext&&this.isSpaceMode())return;let t=this.authContext?.userId??null,i=this.authContext?.token,n=typeof i=="string"&&i.trim().length>0?i:null;if(!(this.hasSyncedAuthToWasmClient&&this.lastWasmAuthUserId===t&&this.lastWasmAuthToken===n)){if(this.lastWasmAuthUserId=t,this.lastWasmAuthToken=n,this.hasSyncedAuthToWasmClient=true,n===null&&typeof this.wasmClient.clearIdentityCredential=="function"){this.wasmClient.clearIdentityCredential();return}e.call(this.wasmClient,n);}}toRuntimeIdentity(e){return e?{id:e.uid,email:e.email,displayName:e.displayName,isAnonymous:e.isAnonymous,getToken:async(t=false)=>{try{return await e.getIdToken(t)}catch{return null}}}:null}getCurrentUserId(){return this.authContext?.userId?this.authContext.userId:this.isTicketOnlyMode()?null:this.auth?.currentUser?.uid??null}getCurrentUserIdForScope(){return this.getCurrentUserId()}getAuthContext(){return this.authContext}isSpaceMode(){return x(this.options)}getResolvedOptions(){return this.options}getDiscoveryScopeId(){if(this.isTicketOnlyMode())return null;let e=this.getCurrentUserId();return e||(this.isSpaceMode()?this.resolveWebLogicalDeviceId():null)}matchesTag(e){return y(e,this.appTag,this.isSpaceMode())}matchesLegacyOrCurrentTag(e){return this.matchesTag(e)}async stopSessionSubscriptions(){let e=Array.from(this.sessionReaders);this.sessionReaders.clear(),await Promise.allSettled(e.map(async t=>{try{await t.cancel();}catch{}}));}async stopRuntimeAuthScopedLoops(){let e=await this.waitForWasmClient(250);if(e)try{typeof e.stop_auth_scoped_activity=="function"?await e.stop_auth_scoped_activity():(typeof e.stop_presence_loop=="function"&&await e.stop_presence_loop(),typeof e.stop_auto_connect=="function"&&await e.stop_auto_connect());}catch(t){console.warn("[WasmSignaling] Failed to stop auth-scoped runtime loops:",t);}}async stopAuthActivity(e){h("WasmBridge.stopAuthActivity",{userId:e?.userId??null}),this.authScopedRuntimeGeneration+=1,this.stopApplicationRouteEscalationSubscription();let t=await this.waitForWasmClient(500);if(t&&typeof t.revoke_tokens_by_scope=="function")try{await t.revoke_tokens_by_scope("user-device");}catch(i){console.warn("[WasmBridge] user-device revoke during auth-scoped shutdown failed:",i);}this.presenceManager.stop(),this.browserCoordinationSignaling?.stopAuthActivity(),this.coordinationHost?.stopAuthActivity(),await this.stopSessionSubscriptions(),this.lastDeliveredConnectionStates.clear(),this.applicationRouteEscalations?.clear(),this.applicationRouteEscalationAttemptKeys?.clear(),await this.stopRuntimeAuthScopedLoops();}setWasmClient(e){this.wasmClient=e,this.coordinationHost.setWasmClient(e),this.lastWasmAuthUserId=null,this.lastWasmAuthToken=null,this.hasSyncedAuthToWasmClient=this.authContext===null,this.lastDeliveredConnectionStates.clear(),this.applicationRouteEscalations?.clear(),this.applicationRouteEscalationAttemptKeys?.clear(),this.syncWasmAuthToken();}async createBroadcastPublisher(){let e=await this.waitForWasmClient();if(!e)throw new Error("WASM broadcast publisher runtime is unavailable");return a$1.create(e)}async initializePersistentIrohProtocols(e){let t=await this.waitForWasmClient(),i=t?.__initPersistentIrohProtocols;if(typeof i!="function")throw new Error("This OpenRTC WASM host was built without persistent Iroh protocols");await i.call(t,e);}async createPersistentIrohNamespace(e,t){return (await this.requirePersistentProtocolHost()).__createPersistentIrohNamespace(BigInt(e),BigInt(t))}async importPersistentIrohTicket(e,t,i){return (await this.requirePersistentProtocolHost()).__importPersistentIrohTicket(e,BigInt(t),BigInt(i))}async sharePersistentIrohNamespace(e,t){return (await this.requirePersistentProtocolHost()).__sharePersistentIrohNamespace(e,t)}async removePersistentIrohNamespace(e,t,i){await(await this.requirePersistentProtocolHost()).__removePersistentIrohNamespace(e,BigInt(t),BigInt(i));}async putPersistentIrohBytes(e,t,i){return (await this.requirePersistentProtocolHost()).__putPersistentIrohBytes(e,t,i)}async setPersistentIrohHash(e,t,i,n){return (await this.requirePersistentProtocolHost()).__setPersistentIrohHash(e,t,i,BigInt(n))}async deletePersistentIrohPrefix(e,t){return (await this.requirePersistentProtocolHost()).__deletePersistentIrohPrefix(e,t)}async queryPersistentIrohNamespace(e,t){return (await this.requirePersistentProtocolHost()).__queryPersistentIrohNamespace(e,t)}async hydratePersistentIrohBlob(e){await(await this.requirePersistentProtocolHost()).__hydratePersistentIrohBlob(e);}async acknowledgePersistentIrohOutbox(e){await(await this.requirePersistentProtocolHost()).__acknowledgePersistentIrohOutbox(e);}async flushPersistentIrohProtocols(){await(await this.waitForWasmClient(500))?.__flushPersistentIrohProtocols?.();}async shutdownPersistentIrohProtocols(){await(await this.waitForWasmClient(500))?.__shutdownPersistentIrohProtocols?.();}async requirePersistentProtocolHost(){let e=await this.waitForWasmClient();if(!e||typeof e.__queryPersistentIrohNamespace!="function")throw new Error("This OpenRTC WASM host was built without persistent Iroh protocols");return e}warnMissingWasmOnce(e){!this.wasmClient&&Date.now()-this.createdAtMs<this.wasmReadyWarningDelayMs||this.missingWasmWarnings.has(e)||(this.missingWasmWarnings.add(e),console.warn(`[WasmSignaling] ${e} skipped: wasm client is not ready.`));}async waitForWasmClient(e=4e3,t=50){if(this.wasmClient)return this.wasmClient;let i=Date.now();for(;!this.wasmClient&&Date.now()-i<e;)await a$2(t);return this.wasmClient??null}normalizeDevice(e,t){return z(e,t)}normalizeDeviceRecord(e,t){return this.normalizeDevice(e,t)}getResolvedWebLogicalDeviceId(){return this.resolveWebLogicalDeviceId()}async encodeSparseFanoutMessage(e,t){let i=await this.waitForWasmClient(),n=this.options.coordinationDeviceSign;if(!i?.prepareSparseFanoutMessage||!i?.finalizeSparseFanoutMessage||!n)throw new Error("[OpenRTC] Browser sparse fanout signer is unavailable.");let o=await i.prepareSparseFanoutMessage(e,t),r=new Uint8Array(o.signingInput??o.signing_input??[]),s=await n(r);return new Uint8Array(await i.finalizeSparseFanoutMessage(String(o.requestId??o.request_id??""),s))}async acceptSparseFanoutMessage(e,t,i){let n=await this.waitForWasmClient();if(!n?.acceptSparseFanoutMessage)throw new Error("[OpenRTC] Browser sparse fanout verifier is unavailable.");let o=await n.acceptSparseFanoutMessage(e,t,i);return {payload:new Uint8Array(o.payload??[]),authorDeviceId:String(o.authorDeviceId??o.author_device_id??""),authorPeerId:String(o.authorPeerId??o.author_peer_id??""),topologyRevision:Number(o.topologyRevision??o.topology_revision),hop:Number(o.hop),forwardPeerIds:Array.isArray(o.forwardPeerIds??o.forward_peer_ids)?(o.forwardPeerIds??o.forward_peer_ids).map(String):[],forwardPeerLimit:Number(o.forwardPeerLimit??o.forward_peer_limit),forwardQueueCapacity:Number(o.forwardQueueCapacity??o.forward_queue_capacity),...o.forward==null?{}:{forward:new Uint8Array(o.forward)}}}async recordSparseFanoutForwardQueueDrop(e,t){let i=await this.waitForWasmClient();i?.recordSparseFanoutForwardQueueDrop&&await i.recordSparseFanoutForwardQueueDrop(e,t);}normalizeDeviceStatusSnapshot(e){return B(e)}normalizePeerSessionSnapshot(e){return C(e)}toBackendConnectionStateFromPeerSession(e){return F(e)}normalizeStateSnapshot(e){return G(e)}stabilizeConnectionState(e){let t=this.lastDeliveredConnectionStates.get(e.connectionId);return {...e,deviceId:e.deviceId??t?.deviceId??null,deviceIdHint:e.deviceIdHint??t?.deviceIdHint??null,remoteNodeId:e.remoteNodeId??t?.remoteNodeId??null,createdAt:e.createdAt??t?.createdAt,updatedAt:e.updatedAt??t?.updatedAt}}sameConnectionState(e,t){return H(e,t)}deliverConnectionState(e,t,i,n){let o=this.stabilizeConnectionState(e);this.lastDeliveredConnectionStates.set(o.connectionId,o);let s=(n??this.lastDeliveredConnectionStates).get(o.connectionId);this.sameConnectionState(s,o)||(n&&n.set(o.connectionId,o),t(o));}get browserPresenceLoopState(){return this.presenceManager.presenceLoopState}set browserPresenceLoopState(e){this.presenceManager.presenceLoopState=e;}get currentUser(){if(this.authContext?.userId){let e=this.authContext.token??null,t=this.authContext.tokenProvider;return {id:this.authContext.userId,getToken:async(i=false)=>{if(e&&(!i||!t))return e;if(t)try{let o=await t(i);if(o)return o}catch{}let n=this.isTicketOnlyMode()?null:this.auth?.currentUser??null;if(n&&n.uid===this.authContext?.userId)try{return await n.getIdToken(i)}catch{return null}return null}}}return this.isTicketOnlyMode()?null:this.toRuntimeIdentity(this.auth?.currentUser??null)}onAuthChange(e){return this.authListeners.push(e),e(this.currentUser),()=>{this.authListeners=this.authListeners.filter(t=>t!==e);}}async checkForSSOToken(){this.isTicketOnlyMode()||this.usesProviderNeutralGrant()||await a().checkForSSOToken();}async waitForAuth(){this.isTicketOnlyMode()||this.usesProviderNeutralGrant()||this.isSpaceMode()||this.authContext?.userId||this.auth?.currentUser||await a().waitForAuth();}async signInAnonymously(){if(!this.isTicketOnlyMode()){if(this.options.authMode!=="anonymous")throw new Error(`[pluto-rtc] Anonymous sign-in is disabled when authMode=${this.options.authMode}.`);await a().signInAnonymously();}}async signInWithPluto(){if(this.isTicketOnlyMode())throw new Error('[openrtc] Pluto sign-in is unavailable when signalingMode="ticket-only".');await a().signInWithPluto();}async signOut(){let e=this.getCurrentUserId();await this.stopAuthActivity({userId:e}),this.authContext=null,this.syncWasmAuthToken(),this.isTicketOnlyMode()||await this.auth?.signOut(),this.authListeners.forEach(t=>t(this.currentUser));}async getTurnCredentials(){return this.isTicketOnlyMode()||!this.auth?.currentUser?null:typeof this.options.turnCredentialsProvider=="function"?await this.options.turnCredentialsProvider()??null:null}async updatePresence(e,t,i=true,n=3e5,o,r){if(this.isTicketOnlyMode())return;let s=this.resolveWebLogicalDeviceId(),c=this.getDeviceIdPersistenceMode()==="ephemeral"?p.EPHEMERAL_DEVICE_ID_TTL_MS:n,a=await this.withWebPresenceMetadata(o,s);this.presenceManager.updatePresenceLoopState({userId:this.getCurrentUserId()??"",localNodeId:e,ticket:t,metadata:a,deviceName:r?.trim()||this.getDefaultBrowserDeviceName()}),await this.getCoordinationSignaling().updatePresence(e,t,i,c,a,r);}async refreshLivePresence(e,t,i,n){if(this.isTicketOnlyMode())return;let o=this.resolveWebLogicalDeviceId(),r=await this.withWebPresenceMetadata(i,o);this.presenceManager.updatePresenceLoopState({userId:this.getCurrentUserId()??"",localNodeId:e,ticket:t,metadata:r,deviceName:n?.trim()||this.getDefaultBrowserDeviceName()}),await this.getCoordinationSignaling().updatePresence(e,t,true,15*6e4,r,n);}async setOffline(e){this.presenceManager.stopPresence(),!this.isTicketOnlyMode()&&await this.getCoordinationSignaling().setOffline(e);}async updateDevice(e,t){if(!e?.trim())throw new Error("updateDevice requires a deviceId");this.isTicketOnlyMode()||await this.getCoordinationSignaling().updateDevice(e,t);}async deleteDevice(e){if(!e?.trim())throw new Error("deleteDevice requires a deviceId");this.isTicketOnlyMode()||await this.getCoordinationSignaling().deleteDevice(e);}async cleanupStaleDevices(){this.isTicketOnlyMode()||await this.getCoordinationSignaling().cleanupStaleDevices();}async sendMessage(e,t,i,n){if(this.isTicketOnlyMode())throw new Error('[openrtc] sendMessage() is unavailable when signalingMode="ticket-only".');return this.getCoordinationSignaling().sendMessage(e,t,i,n)}async pollMessages(e){return this.isTicketOnlyMode()?[]:this.getCoordinationSignaling().pollMessages(e)}async searchDevices(e){return this.isTicketOnlyMode()?[]:this.getCoordinationSignaling().searchDevices(e)}async listDeviceStatus(){if(this.isTicketOnlyMode())return [];if(!this.getDiscoveryScopeId())return [];let t=await this.getCoordinationSignaling().listDevices(),i=this.wasmClient;return Promise.all(t.map(async n=>{let o=this.normalizeDeviceStatusSnapshot({...n,connectionStatus:n.online?"online":"disconnected"}),r=typeof n.nodeId=="string"?n.nodeId.trim():"";if(!r||typeof i?.iroh_path_kind!="function"||typeof i?.iroh_transport_rtt_ms!="function")return o;try{let[s,c]=await Promise.all([i.iroh_path_kind(r),i.iroh_transport_rtt_ms(r)]);if(typeof c!="number"||!Number.isFinite(c))return o;let a=Math.max(0,Math.round(c)),d={};if(s==="direct-lan")d.irohLan=a;else if(s==="direct-quic")d.iroh=a;else if(s==="ble")d.ble=a;else if(s==="relay")d.irohRelay=a;else if(s==="webrtc")d.webrtc=a;else if(s==="moq")d.moq=a;else return o;return {...o,latencyMs:a,latencyByTransport:d}}catch(s){return d$1("[WasmBridge] iroh transport latency unavailable",{deviceId:n.deviceId,error:s instanceof Error?s.message:String(s)}),o}}))}async getPeerSession(e){let t=await this.waitForWasmClient(500);if(t&&typeof t.peer_session=="function"){let i=await t.peer_session(e);return !i||typeof i!="object"?null:this.normalizePeerSessionSnapshot(i)}return this.warnMissingWasmOnce("getPeerSession"),null}async listPeerSessions(){let e=await this.waitForWasmClient(500);if(e&&typeof e.peer_sessions=="function"){let t=await e.peer_sessions();return (Array.isArray(t)?t:[]).map(n=>this.normalizePeerSessionSnapshot(n)).filter(n=>!!(n.peerId||n.deviceId||n.deviceIdHint||n.nodeId||n.activeConnectionId))}return this.warnMissingWasmOnce("listPeerSessions"),[]}async waitForSettledPeer(e,t){let i=await this.waitForWasmClient(500);if(i&&typeof i.wait_for_peer=="function"){let n=await i.wait_for_peer(e,t);return !n||typeof n!="object"?null:this.normalizePeerSessionSnapshot(n)}return this.warnMissingWasmOnce("waitForSettledPeer"),null}async waitForSettledScope(e,t){let i=await this.waitForWasmClient(500);if(i&&typeof i.wait_for_settled_scope=="function"){let n=await i.wait_for_settled_scope(e,t);return !n||typeof n!="object"?null:this.normalizePeerSessionSnapshot(n)}return this.warnMissingWasmOnce("waitForSettledScope"),null}async openPeerBi(e,t){let i=await this.waitForWasmClient(500);if(i&&typeof i.open_peer_bi=="function"){let n=await i.open_peer_bi(e,t);if(!n?.recv||!n?.send)throw new Error("WASM open_peer_bi returned an invalid bidirectional stream");return {readable:n.recv,writable:E(n,n.send)}}throw this.warnMissingWasmOnce("openPeerBi"),new Error("WASM runtime does not support open_peer_bi()")}async openPeerBiRaw(e,t){if(this.options.applicationCrypto?.requireEncrypted)throw new Error("[WasmBridge] openPeerBiRaw is debug-only and cannot be used when application crypto is required");let i=await this.waitForWasmClient(500),n=i&&typeof i.open_peer_bi_transport_only=="function";if(console.debug("[WasmBridge] openPeerBiRaw",{peerId:e,hasWasmClient:!!i,hasTransportOnly:n,timeoutMs:t}),n){let o=await i.open_peer_bi_transport_only(e,t);if(!o?.recv||!o?.send)throw new Error("WASM open_peer_bi_transport_only returned an invalid bidirectional stream");return {readable:o.recv,writable:E(o,o.send)}}throw new Error("WASM runtime does not support the restricted transport-only diagnostic stream")}async openPeerUni(e,t){let i=await this.waitForWasmClient(500);if(i&&typeof i.open_peer_uni=="function"){let n=await i.open_peer_uni(e,t),o=n?.writable??n;if(!o)throw new Error("WASM open_peer_uni returned an invalid writable stream");return {writable:E(n,o)}}throw this.warnMissingWasmOnce("openPeerUni"),new Error("WASM runtime does not support open_peer_uni()")}beginOpenRtcMediaPublication(e){let t=this.wasmClient?.__beginOpenRtcMediaPublication;if(typeof t!="function")throw new Error("[OpenRTC] This WASM build does not include Rust-owned media sessions.");let i=t.call(this.wasmClient,e.publicationId||void 0,e.kind,e.codec,e.clockRate,e.codedWidth,e.codedHeight,e.channels);return {...i,control:new Uint8Array(i.control)}}encodeOpenRtcMediaSample(e){let t=this.wasmClient?.__encodeOpenRtcMediaSample;if(typeof t!="function")throw new Error("[OpenRTC] This WASM build does not include Rust-owned media sessions.");return new Uint8Array(t.call(this.wasmClient,e.publicationId,e.timestampUs,e.durationUs,e.keyframe,e.discardable,e.payload))}pauseOpenRtcMediaPublication(e){let t=this.wasmClient?.__pauseOpenRtcMediaPublication;if(typeof t!="function")throw new Error("[OpenRTC] This WASM build does not include Rust-owned media sessions.");t.call(this.wasmClient,e);}retireOpenRtcMediaPublication(e){let t=this.wasmClient?.__retireOpenRtcMediaPublication;if(typeof t!="function")throw new Error("[OpenRTC] This WASM build does not include Rust-owned media sessions.");t.call(this.wasmClient,e);}retireOpenRtcMediaReceiver(e,t){let i=this.wasmClient?.__retireOpenRtcMediaReceiver;if(typeof i!="function")throw new Error("[OpenRTC] This WASM build does not include Rust-owned media sessions.");i.call(this.wasmClient,e,t);}decodeOpenRtcMediaChunk(e){let t=this.wasmClient?.__decodeOpenRtcMediaChunk;if(typeof t!="function")throw new Error("[OpenRTC] This WASM build does not include the shared media protocol.");let i=t.call(this.wasmClient,e);return {...i,payload:new Uint8Array(i.payload)}}decodeOpenRtcMediaControl(e){let t=this.wasmClient?.__decodeOpenRtcMediaControl;if(typeof t!="function")throw new Error("[OpenRTC] This WASM build does not include the shared media protocol.");return t.call(this.wasmClient,e)}async sendPeerDatagram(e,t,i){let n=await this.waitForWasmClient(500),o=n?.sendPeerDatagram;if(typeof o!="function")throw new Error("[OpenRTC] This WASM build does not include protected peer datagrams.");return await o.call(n,e,t,i)!==false}async receivePeerDatagram(e){let t=await this.waitForWasmClient(500),i=t?.receivePeerDatagram;if(typeof i!="function")throw new Error("[OpenRTC] This WASM build does not include protected peer datagrams.");return new Uint8Array(await i.call(t,e))}peerDatagramMaxSize(){let e=this.wasmClient?.peerDatagramMaxSize?.();return Number.isSafeInteger(e)&&e>0?e:1024}createPeerDatagramPolicy(){let e=this.wasmClient?.createPeerDatagramPolicy;if(typeof e!="function")throw new Error("[OpenRTC] This WASM build does not include shared datagram policy.");return e.call(this.wasmClient)}async resolvePeerRecords(e){let t=await this.waitForWasmClient(500);if(t&&typeof t.resolve_peer_connection_records=="function"){let i=await t.resolve_peer_connection_records(e);return (Array.isArray(i)?i:[]).map(n=>({connectionId:typeof n.connectionId=="string"?n.connectionId:"",nodeId:typeof n.nodeId=="string"?n.nodeId:null,deviceId:typeof n.deviceId=="string"?n.deviceId:null,deviceIdHint:typeof n.deviceIdHint=="string"?n.deviceIdHint:null,endpointId:typeof n.endpointId=="string"?n.endpointId:null,transportGeneration:typeof n.transportGeneration=="number"?n.transportGeneration:0,routeGeneration:typeof n.routeGeneration=="number"?n.routeGeneration:void 0,transportStableId:typeof n.transportStableId=="number"?n.transportStableId:null,transportSource:typeof n.transportSource=="string"?n.transportSource:null,lastTransportChangeAtMs:typeof n.lastTransportChangeAtMs=="number"?n.lastTransportChangeAtMs:0,lastRouteChangeAtMs:typeof n.lastRouteChangeAtMs=="number"?n.lastRouteChangeAtMs:void 0,state:typeof n.state=="string"?n.state:"pending",statusReason:typeof n.statusReason=="string"?n.statusReason:null,createdAtMs:typeof n.createdAtMs=="number"?n.createdAtMs:0,updatedAtMs:typeof n.updatedAtMs=="number"?n.updatedAtMs:0}))}return this.warnMissingWasmOnce("resolvePeerRecords"),[]}async resolvePeerIdentity(e){let t=await this.waitForWasmClient(500);if(t){let i=n=>{if(!n||typeof n!="object")return {peerId:null,deviceId:null,deviceIdHint:null,nodeId:null};let o=n;return {peerId:typeof o.peerId=="string"?o.peerId:null,deviceId:typeof o.deviceId=="string"?o.deviceId:null,deviceIdHint:typeof o.deviceIdHint=="string"?o.deviceIdHint:null,nodeId:typeof o.nodeId=="string"?o.nodeId:null}};if(typeof t.peer_session=="function")try{let n=await t.peer_session(e),o=i(n);if(o.peerId||o.deviceId||o.deviceIdHint||o.nodeId)return o}catch{}if(typeof t.peer_snapshot=="function")try{return i(await t.peer_snapshot(e))}catch{}}return this.warnMissingWasmOnce("resolvePeerIdentity"),{peerId:null,deviceId:null,deviceIdHint:null,nodeId:null}}onDevicesChange(e,t){return this.isTicketOnlyMode()?(e([]),()=>{}):this.getCoordinationSignaling().onDevicesChange(e,t)}onRoomArchitectureChange(e){return this.getCoordinationSignaling().onRoomArchitectureChange?.(t=>{let i=this.effectiveRoomArchitecture!==t.effective;this.effectiveRoomArchitecture=t.effective,i&&this.presenceManager.handleRoomArchitectureChange().catch(n=>{console.warn("[WasmSignaling] failed to replay desired peers after room architecture change",{effectiveArchitecture:t.effective,epoch:t.epoch,error:n});}),e(t);})??(()=>{})}onRoomAuthorityAssignmentChange(e){return this.getCoordinationSignaling().onRoomAuthorityAssignmentChange?.(e)??(()=>{})}async publishAuthorityAssignment(e){let t=this.getCoordinationSignaling();if(!t.publishAuthorityAssignment)throw new Error("[OpenRTC] Authority assignment publication is unavailable.");await t.publishAuthorityAssignment(e);}async publishManagedRoomMessage(e){let t=this.getCoordinationSignaling().publishManagedRoomMessage;if(!t)throw new Error("[OpenRTC] Managed room fanout is unavailable.");await t.call(this.getCoordinationSignaling(),e);}onManagedRoomMessage(e){return this.getCoordinationSignaling().onManagedRoomMessage?.(e)??(()=>{})}async subscribeDevices(e){return this.isTicketOnlyMode()?new ReadableStream({start(t){t.close();}}):this.getCoordinationSignaling().subscribeDevices()}async startAutoConnect(e,t){if(this.isTicketOnlyMode())return;this.startApplicationRouteEscalationSubscription();let i=this.authScopedRuntimeGeneration;try{let n=await this.waitForWasmClient();if(i!==this.authScopedRuntimeGeneration||!n||typeof n.start_auto_connect!="function")return;await this.presenceManager.installInitialAutoConnectExclusions(n),await n.start_auto_connect(e,t),i===this.authScopedRuntimeGeneration&&this.presenceManager.startAutoConnect(e,t);}catch(n){console.warn("[WasmBridge] failed to initialize WASM auto-connect context",{userId:e,localDeviceId:t,error:n});}}async startAutoConnectOnce(e,t){await this.startAutoConnect(e,t),this.forceReconnect();}notifyDisconnectRequested(e){this.presenceManager.wakeRustAutoConnectOwner();}async excludeAutoConnect(e,t){await this.presenceManager.excludeAutoConnect(e,t);}async disconnectDevice(e){let t=await this.waitForWasmClient();if(!t||typeof t.disconnect_device!="function"){this.warnMissingWasmOnce("disconnectDevice"),await this.presenceManager.excludeAutoConnect(e,true).catch(()=>{});return}try{await t.disconnect_device(e,null),await this.presenceManager.recordAutoConnectExcludedForPresence(e,!0).catch(()=>{});}catch(i){throw console.warn("[WasmBridge] disconnect_device failed",{deviceId:e,error:i?.message??String(i)}),i}}async submitDesiredPeerProjection(e,t){return this.presenceManager.submitDesiredPeerProjection(e,t)}observeManagedDesiredPeers(e){this.presenceManager.observeDesiredPeerProjection(e),e$1("[OpenRTC][route-escalation] observed managed desired peers",{peerCount:e.length,peersWithTickets:e.filter(t=>typeof t.ticket=="string"&&t.ticket.trim()).length,deviceIds:e.map(t=>t.deviceId)});}setCoreClient(e){e&&typeof e.ensureManagedApplicationRoute=="function"?(this.coreClient=e,e$1("[OpenRTC][route-escalation] attached shared core client"),this.startApplicationRouteEscalationSubscription(),this.retryManagedApplicationRouteEscalations()):(this.coreClient=null,e$1("[OpenRTC][route-escalation] detached shared core client"),this.stopApplicationRouteEscalationSubscription());}startApplicationRouteEscalationSubscription(){if(this.applicationRouteEscalationUnsubscribe&&this.routeSubscriptionGeneration===this.authScopedRuntimeGeneration)return;this.stopApplicationRouteEscalationSubscription();let e=this.authScopedRuntimeGeneration,t=this.applicationRouteEscalationSubscriptionEpoch,i=this.onStateChange(n=>{let o=this.stabilizeConnectionState(n);this.lastDeliveredConnectionStates.set(o.connectionId,o),e$1("[OpenRTC][route-escalation] observed Rust connection state",{connectionId:o.connectionId,deviceId:o.deviceId??o.deviceIdHint??null,remoteNodeId:o.remoteNodeId??null,state:o.state,transportGeneration:o.transportGeneration??null,routeGeneration:o.routeGeneration??null}),this.escalateManagedApplicationRoute(o);});this.applicationRouteEscalationUnsubscribe=()=>{},this.routeSubscriptionGeneration=e,Promise.resolve(i).then(n=>{if(!this.coreClient||e!==this.authScopedRuntimeGeneration||t!==this.applicationRouteEscalationSubscriptionEpoch){n();return}this.applicationRouteEscalationUnsubscribe=n,this.routeSubscriptionGeneration=e;});}stopApplicationRouteEscalationSubscription(){this.applicationRouteEscalationSubscriptionEpoch+=1,this.applicationRouteEscalationUnsubscribe?.(),this.applicationRouteEscalationUnsubscribe=null,this.routeSubscriptionGeneration=-1;}retryManagedApplicationRouteEscalations(){for(let e of this.lastDeliveredConnectionStates.values())this.escalateManagedApplicationRoute(e);}escalateManagedApplicationRoute(e){if(!this.coreClient||!["connected","connecting"].includes(e.state))return;let t=[e.transportGeneration??0,e.routeGeneration??0].join(":"),i=this.applicationRouteEscalationAttemptKeys??(this.applicationRouteEscalationAttemptKeys=new Map);if(i.get(e.connectionId)===t||this.applicationRouteEscalations.has(e.connectionId))return;let n=this.presenceManager.resolveDesiredPeer(e.deviceId??e.deviceIdHint,e.remoteNodeId);if(!n?.ticket){e$1("[OpenRTC][route-escalation] awaiting matching desired-peer ticket",{connectionId:e.connectionId,deviceId:e.deviceId??e.deviceIdHint??null,remoteNodeId:e.remoteNodeId??null});return}let o=this.authScopedRuntimeGeneration,r=this.coreClient;i.set(e.connectionId,t),e$1("[OpenRTC][route-escalation] adopting Rust-managed generation",{connectionId:e.connectionId,deviceId:n.deviceId,remoteNodeId:e.remoteNodeId??n.nodeId??null,transportGeneration:e.transportGeneration??null,routeGeneration:e.routeGeneration??null});let s;s=(async()=>{let c=await r.ensureManagedApplicationRoute({ticket:n.ticket,connectionId:e.connectionId,remoteNodeId:e.remoteNodeId??n.nodeId,expectedDeviceId:n.deviceId,timeoutMs:2e4});if(o!==this.authScopedRuntimeGeneration)return;let a=c,d=a.id?.trim()||e.connectionId,h=a.remoteNodeId?.trim()||e.remoteNodeId?.trim()||a.deviceId?.trim()||n.deviceId;if(r.hasApplicationRouteForPeer?.(d,h)!==true&&r.hasApplicationRouteForPeer?.(d,h)!==true)throw new Error(`application crypto was not ready for ${h}`)})().catch(c=>{o===this.authScopedRuntimeGeneration&&console.warn("[OpenRTC][route-escalation] Rust-managed route remains pending",{connectionId:e.connectionId,deviceId:n.deviceId,remoteNodeId:e.remoteNodeId??n.nodeId,error:c?.message??String(c)});}).finally(()=>{if(this.applicationRouteEscalations.get(e.connectionId)===s){this.applicationRouteEscalations.delete(e.connectionId);let c=this.lastDeliveredConnectionStates?.get(e.connectionId),a=c?[c.transportGeneration??0,c.routeGeneration??0].join(":"):null;c&&a!==t&&o===this.authScopedRuntimeGeneration&&queueMicrotask(()=>this.escalateManagedApplicationRoute(c));}}),this.applicationRouteEscalations.set(e.connectionId,s);}async connectToDevice(e){let t=await this.waitForWasmClient();if(!t||typeof t.connect_device!="function")throw this.warnMissingWasmOnce("connectToDevice"),new Error("WASM runtime does not support connect_device()");let i=e.endpointTicket?.trim()??"",n=e.admissionToken?.trim()??"",o=e.admissionScope?.trim()??"",r=!i,s=i;if(r&&(!e.deviceId||!n||!o||typeof t.connect_known_device_with_token!="function"))throw new Error("WASM connectToDevice requires an endpoint ticket or supported known-device admission intent.");let c=Date.now();e$1("[WasmBridge][ROUTE-ESCALATION] starting managed transport dial",{deviceId:e.deviceId??null,ticket:se(i),knownDeviceAdmission:r,hasCoreClient:!!this.coreClient});let a=r?await(async()=>{let h=Date.now(),l=Math.max(1,e.timeoutMs??3e4),m=()=>Math.max(1,l-(Date.now()-h)),y=e.admissionPeerUserId?.trim()??"";if(y){let v=(await this.getCoordinationSignaling().waitForFriendDevice(y,e.deviceId,Math.min(1e4,m()))).ticket?.trim()??"";if(!v)throw new Error(`[pluto-rtc] authorized device ${e.deviceId} did not publish an endpoint ticket.`);if(typeof t.observe_known_device_endpoint!="function")throw new Error("WASM runtime does not support provider-authorized endpoint observations.");await t.observe_known_device_endpoint(e.deviceId,v),s=a$3(v).irohTicket;}return t.connect_known_device_with_token(e.deviceId,n,o,e.admissionMaxConnections??0,e.admissionExpiresAtMs==null?null:BigInt(Math.floor(e.admissionExpiresAtMs)),Math.min(1e4,m()))})():await t.connect_device(e.deviceId??null,i);e$1("[WasmBridge][ROUTE-ESCALATION] managed transport dial completed",{deviceId:e.deviceId??null,remoteNodeId:a?.remoteNodeId??null,connectionId:a?.connectionId??null,elapsedMs:Date.now()-c});let d=s;if(d&&this.coreClient){let h=this.coreClient;try{e$1("[WasmBridge][ROUTE-ESCALATION] starting typed application connection",{deviceId:e.deviceId??null,remoteNodeId:a?.remoteNodeId??null,connectionId:a?.connectionId??null});let l=await h.ensureManagedApplicationRoute({ticket:d,connectionId:a?.connectionId??null,remoteNodeId:a?.remoteNodeId??null,expectedDeviceId:e.deviceId??null,approvedScope:a?.approvedScope??null,timeoutMs:2e4}),m=typeof l?.remoteNodeId=="string"?l.remoteNodeId.trim():"",y=typeof l?.deviceId=="string"?l.deviceId.trim():"",g=m||a?.remoteNodeId?.trim?.()||y||e.deviceId?.trim?.()||"",v=typeof h.hasApplicationRouteForPeer=="function"?h.hasApplicationRouteForPeer.bind(h):null;if(!(!!g&&v?.(l?.id??void 0,g)===!0)&&g&&typeof h.waitForApplicationCryptoForPeer=="function"&&!(!!await h.waitForApplicationCryptoForPeer(g,2e4)&&(!v||v(l?.id??void 0,g)===!0)))throw console.warn("[WasmBridge][ROUTE-ESCALATION] application route still pending after managed dial",{deviceId:e.deviceId??null,remoteNodeId:m||(a?.remoteNodeId??null),connectionId:a?.connectionId??null,peerForCrypto:g,elapsedMs:Date.now()-c}),Object.assign(new Error(`application crypto was not ready for ${g}`),{applicationCryptoNotReady:!0});e$1("[WasmBridge][ROUTE-ESCALATION] application route ready",{deviceId:e.deviceId??null,remoteNodeId:m||(a?.remoteNodeId??null),connectionId:a?.connectionId??null,elapsedMs:Date.now()-c});}catch(l){if(l?.applicationCryptoNotReady)throw l;return console.warn("[WasmBridge] Managed transport connected; TS application route escalation is still pending",{deviceId:e.deviceId??null,remoteNodeId:a?.remoteNodeId??null,connectionId:a?.connectionId??null,error:l?.message??String(l)}),a}}return a}forceReconnect(){this.isTicketOnlyMode()||!this.app||!this.auth||this.presenceManager.wakeRustAutoConnectOwner();}startPresenceLoop(e,t,i,n,o){return this.presenceManager.startPresenceLoop(e,t,i,n,o)}ensureSpaceNamespaceIdPromise(){if(this.cachedSpaceNamespaceId)return Promise.resolve(this.cachedSpaceNamespaceId);if(!this.spaceNamespaceIdPromise){let e=this.options.apiKey?.trim()??"",t=this.options.spaceKey?.trim()??"";if(!e||!t)return Promise.resolve(null);this.spaceNamespaceIdPromise=b$1(e,t).then(i=>(this.cachedSpaceNamespaceId=i,i)).catch(()=>null);}return this.spaceNamespaceIdPromise}async createSession(e){if(this.isTicketOnlyMode())throw new Error('[openrtc] createSession() is unavailable when signalingMode="ticket-only".');let t=this.getCurrentUserId();if(!t&&!e.initiator&&!e.target&&!this.isSpaceMode())throw new Error("createSession requires user scope");let i={...e,appTag:e.appTag??this.appTag,initiator:e.initiator??t??void 0,target:e.target??t??void 0};await this.getCoordinationSignaling().createSession(i);}async updateSession(e,t){if(this.isTicketOnlyMode())throw new Error('[openrtc] updateSession() is unavailable when signalingMode="ticket-only".');await this.getCoordinationSignaling().updateSession(e,t);}async subscribeSessions(e){return this.isTicketOnlyMode()?new ReadableStream({start(t){t.close();}}):this.getCoordinationSignaling().subscribeSessions(e)}async getLocalDeviceId(){return this.resolveWebLogicalDeviceId()}async isConnected(e){let t=await this.waitForWasmClient();return t&&typeof t.is_connected=="function"?t.is_connected(e):false}async getConnectionStates(){let e=await this.waitForWasmClient(500);if(e&&typeof e.connection_states=="function"){let n=await e.connection_states(),o=(Array.isArray(n)?n:[]).map(r=>this.normalizeStateSnapshot(r)).filter(r=>!!r);return o.length>0&&d$1("[WasmBridge] replaying current wasm connection states",o.map(r=>({connectionId:r.connectionId,deviceId:r.deviceId??null,deviceIdHint:r.deviceIdHint??null,remoteNodeId:r.remoteNodeId??null,state:r.state,transportState:r.transportState??null,protocolState:r.protocolState??null,routable:r.routable??null}))),o}let i=(await this.listPeerSessions().catch(()=>[])).map(n=>this.toBackendConnectionStateFromPeerSession(n)).filter(n=>!!n);return i.length>0&&d$1("[WasmBridge] replaying current wasm connection states",i.map(n=>({connectionId:n.connectionId,deviceId:n.deviceId??null,deviceIdHint:n.deviceIdHint??null,remoteNodeId:n.remoteNodeId??null,state:n.state,transportState:n.transportState??null,protocolState:n.protocolState??null,routable:n.routable??null}))),i}onStateChange(e){let t=new Map,i=new Map,n=this.authScopedRuntimeGeneration,o=false,r=a=>{let d=a.detail,h=this.normalizeStateSnapshot(d),l=typeof d?.connectionId=="string"?d.connectionId.trim():"";if(!l||o)return;if(h&&(h.state==="closed"||h.state==="failed"||h.state==="disconnected")){this.deliverConnectionState(h,e,"rust-event-detail",t);return}let m=(i.get(l)??0)+1;i.set(l,m);let y=this.authScopedRuntimeGeneration;(async()=>{let g=await this.waitForWasmClient(500);if(!(o||y!==this.authScopedRuntimeGeneration||i.get(l)!==m)){if(g&&typeof g.connection_state=="function"){let v=await g.connection_state(l),w=this.normalizeStateSnapshot(v);if(!o&&y===this.authScopedRuntimeGeneration&&i.get(l)===m&&w){this.deliverConnectionState(w,e,"rust-event",t);return}}!o&&y===this.authScopedRuntimeGeneration&&i.get(l)===m&&h&&this.deliverConnectionState(h,e,"rust-event-detail",t);}})().catch(g=>{o||console.warn("[WasmBridge] Failed to read Rust connection state after lifecycle event",{connectionId:l,error:g});});},s=typeof window<"u"?window:null,c=typeof s?.addEventListener=="function"&&typeof s?.removeEventListener=="function";return c&&s.addEventListener("connection-state-changed",r),this.getConnectionStates().then(a=>{!o&&n===this.authScopedRuntimeGeneration&&a.forEach(d=>{i.has(d.connectionId)||this.deliverConnectionState(d,e,"replay",t);});}).catch(a=>{console.warn("[WasmBridge] Failed to replay wasm connection states after subscription:",a);}),()=>{o=true,i.clear(),c&&s.removeEventListener("connection-state-changed",r);}}async sendExplicitFilePath(e,t,i=""){throw new Error("sendExplicitFilePath is native-only. Use sendExplicitFileData in web/wasm runtime.")}sanitizeExplicitFileName(e){let i=(typeof e=="string"?e.replace(/\\/g,"/"):"").split("/").reverse().find(r=>r.trim().length>0)?.trim()??"";if(!i||i==="."||i==="..")return p.FALLBACK_EXPLICIT_FILE_NAME;let n="";for(let r of i){if([...n].length>=p.MAX_EXPLICIT_FILE_NAME_CHARS)break;let s=r.charCodeAt(0);r==="/"||r==="\\"||r==="\0"||s<32||s===127?n+="_":n+=r;}let o=n.trim();return !o||o==="."||o===".."?p.FALLBACK_EXPLICIT_FILE_NAME:o}sanitizeExplicitMimeType(e){let t=typeof e=="string"?e.trim():"";if(!t)return p.FALLBACK_EXPLICIT_MIME_TYPE;let i="";for(let n of t){if(i.length>=p.MAX_EXPLICIT_MIME_TYPE_CHARS)break;let o=n.charCodeAt(0);o<33||o>126||n==='"'||n==="\\"?i+="_":i+=n;}return i.length>0?i:p.FALLBACK_EXPLICIT_MIME_TYPE}assertExplicitTransferHeaderSize(e){if(e.byteLength===0||e.byteLength>p.MAX_EXPLICIT_TRANSFER_HEADER_BYTES)throw new Error(`Explicit transfer header is too large: ${e.byteLength} bytes`)}createWebRTCExplicitTransferId(){let e=new Uint8Array(16),t=globalThis.crypto;if(t&&typeof t.getRandomValues=="function")return t.getRandomValues(e),e;for(let i=0;i<e.byteLength;i+=1)e[i]=Math.floor(Math.random()*256);return e}createWebRTCExplicitTransferFrame(e,t,i,n,o){let r=o?.headerFrame===true?4:0,s=new Uint8Array(25+r+n.byteLength);s[0]=p.EXPLICIT_FILE_PROTOCOL_TYPE,s.set(e,1);let c=new DataView(s.buffer);c.setUint32(17,t,false),c.setUint32(21,i,false);let a=o?.headerFrame===true?29:25;return o?.headerFrame===true&&c.setUint32(25,n.byteLength,false),s.set(n,a),s}async sendExplicitFileData(e){let t=e.connection,i=e.file,n=e.applicationCrypto??this.options.applicationCrypto;if((e.requireApplicationCrypto===true||t?.requireApplicationCrypto===true)&&!n)throw new Error("[WasmBridge] Explicit transfer requires application crypto but none is available for this connection");let r=e.transferId&&e.transferId.trim().length>0?e.transferId:`transfer-${Date.now()}`;typeof e.receiverPlatformType=="string"?e.receiverPlatformType.trim().toLowerCase():null;let c=e.remoteNodeId?.trim()||t?.remoteNodeId?.trim()||t?.deviceId?.trim();if(e$1("[WasmBridge] sendExplicitFileData start",{connectionId:e.connectionId??null,connectionRemoteNodeId:t?.remoteNodeId??null,remoteNodeId:c??null,fileName:i.name,fileSize:i.size,transferId:r}),!c)throw new Error("Web explicit transfer requires an active connection with a resolved remote node ID");let a=await this.waitForWasmClient();if(!a)throw new Error("WASM explicit transfer requires an initialized WASM client");let d=new TextEncoder,h={transfer_id:r,filename:this.sanitizeExplicitFileName(i.name),size:i.size,mime_type:this.sanitizeExplicitMimeType(i.type)},l=d.encode(JSON.stringify(h));this.assertExplicitTransferHeaderSize(l);let m=new Uint8Array(4);new DataView(m.buffer).setUint32(0,l.byteLength,false);let y=new Uint8Array(m.byteLength+l.byteLength);y.set(m,0),y.set(l,m.byteLength);let g=async()=>{let v=a.open_peer_bi_explicit_file_sender;if(typeof v!="function")return false;let w=await v.call(a,c,5e3),S=w?.writable??w?.send;if(!S||typeof S.getWriter!="function")throw new Error("WASM explicit peer stream returned an invalid writable stream");e$1("[WasmBridge] sendExplicitFileData open_peer_bi_explicit_file_sender resolved",{remoteNodeId:c,transferId:e.transferId??null,applicationCryptoWrapped:w.applicationCryptoWrapped===true});let C=E(w,S,{requireFinish:true}).getWriter(),T=false;try{await C.write(y);let P=new Uint8Array(await i.arrayBuffer());for(let b=0;b<P.byteLength;b+=p.EXPLICIT_FILE_CHUNK_SIZE_BYTES){let ie=P.slice(b,Math.min(b+p.EXPLICIT_FILE_CHUNK_SIZE_BYTES,P.byteLength));await C.write(ie);}}catch(P){throw T=true,P}finally{try{await C.close();}catch(P){if(!T)throw P}finally{C.releaseLock();}}return true};try{if(await g())return;throw new Error("[WasmBridge] Explicit transfer requires the generation-fenced open_peer_bi_explicit_file_sender path, but it is unavailable on this WASM build. Rebuild the current OpenRTC WASM; raw open_bi fallback is intentionally unsupported for application data.")}finally{e$1("[WasmBridge] sendExplicitFileData completed",{remoteNodeId:c,transferId:r,fileName:i.name,fileSize:i.size});}}async getTransferHistory(e=50){return []}async deleteTransferJob(e){}watchFriendDevices(e,t){return this.isTicketOnlyMode()?()=>{}:this.getCoordinationSignaling().watchFriendDevices(e,t)}async updateFriendTicket(e){this.isTicketOnlyMode()||await this.getCoordinationSignaling().updateFriendTicket(e);}};p.EXPLICIT_FILE_PROTOCOL_TYPE=2,p.EXPLICIT_FILE_CHUNK_SIZE_BYTES=64*1024,p.MAX_EXPLICIT_TRANSFER_HEADER_BYTES=64*1024,p.FALLBACK_EXPLICIT_FILE_NAME="openrtc-transfer.bin",p.MAX_EXPLICIT_FILE_NAME_CHARS=180,p.FALLBACK_EXPLICIT_MIME_TYPE="application/octet-stream",p.MAX_EXPLICIT_MIME_TYPE_CHARS=255,p.WEB_DEVICE_ID_STORAGE_PREFIX="pluto_rtc_web_device_identity",p.EPHEMERAL_DEVICE_ID_TTL_MS=o.browserIdentity.ephemeralDeviceIdTtlMs;var te=p;export{oe as a,te as b};
|