openrtc 2.0.0-rc.0 → 2.0.0-rc.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. package/dist/DelegatingRuntimeAdapter-BLNigcS4.d.ts +134 -0
  2. package/dist/{types-BDc7AZYI.d.ts → OpenRTCShared-BswnbjpG.d.ts} +4 -196
  3. package/dist/{WasmBridge-2A22U7RU.js → WasmBridge-B7NTRYN5.js} +1 -1
  4. package/dist/chunk-23XC6TGK.js +2 -0
  5. package/dist/{chunk-4K2QPYGT.js → chunk-A7AMB23L.js} +1 -1
  6. package/dist/{chunk-A3IAG6EL.js → chunk-C6PAXO3N.js} +1 -1
  7. package/dist/chunk-D45U2NXV.js +1 -0
  8. package/dist/chunk-DZCZLRM5.js +1 -0
  9. package/dist/chunk-EUNCYGJD.js +1 -0
  10. package/dist/chunk-IAIGT5G3.js +1 -0
  11. package/dist/chunk-JIVVHBCB.js +2 -0
  12. package/dist/chunk-KWXAZUAZ.js +2 -0
  13. package/dist/{chunk-CEMN2JKR.js → chunk-NCL672QJ.js} +3 -3
  14. package/dist/{chunk-DTWEQS3J.js → chunk-O3D7S5MD.js} +1 -1
  15. package/dist/factories-TLUZAXUG.js +1 -0
  16. package/dist/index.d.ts +5 -4
  17. package/dist/index.js +1 -1
  18. package/dist/ipcFactory-QOAZVE56.js +1 -0
  19. package/dist/native.d.ts +5 -4
  20. package/dist/native.js +1 -1
  21. package/dist/openrtc-C53CKZUM.js +2 -0
  22. package/dist/openrtc_bg.wasm +0 -0
  23. package/dist/runtime/WasmRuntimeAdapter.d.ts +3 -3
  24. package/dist/runtime/WasmRuntimeAdapter.js +1 -1
  25. package/dist/runtime/device-status.d.ts +2 -2
  26. package/dist/runtime/index.d.ts +10 -33
  27. package/dist/runtime/index.js +2 -2
  28. package/dist/runtime/legacy.d.ts +18 -0
  29. package/dist/runtime/legacy.js +1 -0
  30. package/dist/runtime/tauri.d.ts +4 -4
  31. package/dist/runtime/tauri.js +1 -1
  32. package/dist/{tauri-Cz9n17g8.d.ts → tauri-BgLgJoQA.d.ts} +2 -2
  33. package/dist/testing.d.ts +4 -3
  34. package/dist/testing.js +1 -1
  35. package/dist/transport/index.d.ts +2 -2
  36. package/dist/{types-BVJr065k.d.ts → types-BHePJWbM.d.ts} +1 -1
  37. package/dist/{types-BUXwspL0.d.ts → types-D0pqNSOf.d.ts} +2 -2
  38. package/dist/types-byWIP-WI.d.ts +234 -0
  39. package/package.json +5 -1
  40. package/dist/DelegatingRuntimeAdapter-DqfHkjLy.d.ts +0 -373
  41. package/dist/chunk-GW7P3D54.js +0 -1
  42. package/dist/chunk-PODAMIL6.js +0 -2
  43. package/dist/chunk-UEYM6WTT.js +0 -2
  44. package/dist/chunk-WMRCP3YX.js +0 -1
  45. package/dist/chunk-XE43HAXV.js +0 -2
  46. package/dist/chunk-YBXGNKM7.js +0 -2
  47. package/dist/chunk-YGJ6OAPR.js +0 -1
  48. package/dist/factories-O5575ECL.js +0 -1
  49. package/dist/ipcFactory-FBNUVH7V.js +0 -1
@@ -0,0 +1,134 @@
1
+ import { D as DiscoveryMode, A as AuthMode, S as SignalingMode, C as ClientOptions, E as ExplicitFileDataSendParams, I as ISignalingBackend, R as RuntimeIdentity, a as RoomMember, b as Device, c as DeviceStatusSnapshot, P as PeerSessionSnapshot, d as ResolvedPeerIdentity, M as ManagedConnectionRecord, e as SignalingEnvelope, f as DeviceEvent, g as DesiredPeerProjection, h as SignalingSession, i as SessionEvent, L as LocalDeviceInfo, N as NativeManagedSessionStartResult, G as GrantScope, B as BackendPeerBiStream, j as BackendPeerUniStream, k as NativeConnectParams, l as NativeConnectResult, m as BackendConnectionState } from './types-BHePJWbM.js';
2
+ import { A as AuthContext } from './IEngineBridge-BbsT8hof.js';
3
+ import { R as RuntimeCapabilities } from './capabilities-YSskrE8H.js';
4
+
5
+ interface WasmBridgeOptions {
6
+ apiKey?: string;
7
+ discoveryMode?: DiscoveryMode;
8
+ space?: string;
9
+ spaceKey?: string;
10
+ authMode?: AuthMode;
11
+ signalingMode?: SignalingMode;
12
+ projectId?: string;
13
+ coordinationGateway?: ClientOptions['coordinationGateway'];
14
+ coordinationAvenueOverride?: ClientOptions['coordinationAvenueOverride'];
15
+ platformAttestationTokenProvider?: ClientOptions['platformAttestationTokenProvider'];
16
+ /** Internal host hint used by the provider-neutral gateway projection. */
17
+ coordinationPlatformType?: 'web' | 'desktop' | 'mobile';
18
+ storagePrefix?: string;
19
+ deviceIdPersistence?: 'persistent' | 'ephemeral';
20
+ endpointIdPersistence?: 'persistent' | 'ephemeral';
21
+ nodeIdPersistence?: 'persistent' | 'ephemeral';
22
+ localDeviceId?: string;
23
+ deviceName?: string;
24
+ turnCredentialsProvider?: () => Promise<{
25
+ iceServers?: RTCIceServer[];
26
+ } | null | undefined>;
27
+ applicationCrypto?: ExplicitFileDataSendParams['applicationCrypto'];
28
+ spaceAuth?: 'scoped-token';
29
+ }
30
+
31
+ declare abstract class DelegatingRuntimeAdapter implements ISignalingBackend {
32
+ protected readonly backend: ISignalingBackend;
33
+ protected constructor(backend: ISignalingBackend);
34
+ get currentUser(): RuntimeIdentity | null;
35
+ setAuthContext(context: AuthContext | null): Promise<void> | void;
36
+ signInAnonymously(): Promise<void>;
37
+ signInWithPluto(): Promise<void>;
38
+ signOut(): Promise<void>;
39
+ stopAuthScopedActivity(): Promise<void>;
40
+ usesCoordinationGateway(): boolean;
41
+ joinCoordinationRoom(roomId: string, nodeId: string, ticket: string): Promise<void>;
42
+ leaveCoordinationRoom(roomId: string): Promise<void>;
43
+ getCoordinationRoomMembers(roomId: string): Promise<RoomMember[]>;
44
+ watchCoordinationRoomMembers(roomId: string, callback: (members: RoomMember[]) => void): () => void;
45
+ getTurnCredentials(): Promise<any>;
46
+ updatePresence(localNodeId: string, ticketStr: string, isOnline: boolean, ttlMs: number, metadata?: string): Promise<void>;
47
+ refreshLivePresence(localNodeId: string, ticketStr: string, metadata?: string): Promise<void>;
48
+ setOffline(localNodeId: string): Promise<void>;
49
+ cleanupStaleDevices(): Promise<void>;
50
+ searchDevices(excludeNodeId?: string): Promise<Device[]>;
51
+ listDevicesWithStatus(): Promise<DeviceStatusSnapshot[]>;
52
+ getPeerSession(id: string): Promise<PeerSessionSnapshot | null>;
53
+ listPeerSessions(): Promise<PeerSessionSnapshot[]>;
54
+ waitForSettledPeer(id: string, timeoutMs?: number): Promise<PeerSessionSnapshot | null>;
55
+ resolvePeerIdentity(id: string): Promise<ResolvedPeerIdentity>;
56
+ resolvePeerConnectionRecords(id: string): Promise<ManagedConnectionRecord[]>;
57
+ updateDevice(deviceId: string, updates: {
58
+ deviceName?: string;
59
+ capabilities?: Device['capabilities'];
60
+ metadata?: string;
61
+ }): Promise<void>;
62
+ deleteDevice(deviceId: string): Promise<void>;
63
+ onDevicesChange(callback: (devices: Device[]) => void, excludeNodeId?: string): () => void;
64
+ onAuthChange(callback: (user: RuntimeIdentity | null) => void): () => void;
65
+ checkForSSOToken(): Promise<void>;
66
+ waitForAuth(): Promise<void>;
67
+ sendMessage(targetId: string, payload: string, state?: string, replyPayload?: string): Promise<string>;
68
+ pollMessages(targetId: string): Promise<SignalingEnvelope[]>;
69
+ watchFriendDevices(friendUserIds: string[], callback: (friendDevices: Map<string, Device[]>) => void): () => void;
70
+ updateFriendTicket(friendTicket: string | null): Promise<void>;
71
+ subscribeDevices(userId: string): Promise<ReadableStream<DeviceEvent[]>>;
72
+ startAutoConnect(userId: string, localDeviceId: string): void;
73
+ submitDesiredPeerProjection(revision: number, peers: DesiredPeerProjection[]): Promise<void>;
74
+ startPresenceLoop(userId: string, localNodeId: string, deviceName: string, ticket: string, metadata?: string): void;
75
+ createSession(session: SignalingSession): Promise<void>;
76
+ updateSession(sessionId: string, updateData: any): Promise<void>;
77
+ subscribeSessions(localDeviceId: string): Promise<ReadableStream<SessionEvent[]>>;
78
+ forceReconnectSnapshot(): void;
79
+ getLocalDeviceId(): Promise<string | null>;
80
+ getLocalDeviceInfo(): Promise<LocalDeviceInfo | null>;
81
+ updateLocalDeviceName(deviceName: string): Promise<LocalDeviceInfo | null>;
82
+ startManagedSessionNative(options: {
83
+ userId: string;
84
+ deviceName?: string;
85
+ localDeviceId?: string | null;
86
+ metadata?: string;
87
+ autoConnect?: boolean;
88
+ presence?: boolean;
89
+ }): Promise<NativeManagedSessionStartResult>;
90
+ notifyNetworkChange(options?: {
91
+ reason?: string;
92
+ }): Promise<unknown>;
93
+ getManagedNodeId(options?: {
94
+ initializeIfMissing?: boolean;
95
+ }): Promise<string | null>;
96
+ startPresenceLoopOnce(userId: string, localNodeId: string, deviceName: string, ticket: string, metadata?: string): Promise<void>;
97
+ startAutoConnectOnce(userId: string, localDeviceId: string): Promise<void>;
98
+ getEndpointTicket(): Promise<string>;
99
+ getEndpointTicketWithToken(scope: GrantScope, maxConnections: number): Promise<string | null>;
100
+ registerSessionToken(token: string, scope: GrantScope, maxConnections: number): Promise<void>;
101
+ revokeSessionTokensByScope(scope: GrantScope): Promise<string[]>;
102
+ openPeerBi(id: string, timeoutMs?: number): Promise<BackendPeerBiStream>;
103
+ incoming_streams(): Promise<ReadableStream<unknown>>;
104
+ is_current_transport_stable_id(endpointId: string, transportStableId: bigint): Promise<boolean>;
105
+ openPeerNativeBi(id: string, label: string, timeoutMs?: number): Promise<BackendPeerBiStream>;
106
+ openPeerBiTransportOnly(id: string, timeoutMs?: number): Promise<BackendPeerBiStream>;
107
+ openPeerUni(id: string, timeoutMs?: number): Promise<BackendPeerUniStream>;
108
+ connectToDevice(params: NativeConnectParams): Promise<NativeConnectResult>;
109
+ disconnectDevice(deviceId: string): Promise<void>;
110
+ setAutoConnectExcluded(deviceId: string, excluded: boolean): Promise<void>;
111
+ isConnected(nodeId: string): Promise<boolean>;
112
+ getConnectionStates(): Promise<BackendConnectionState[]>;
113
+ onConnectionStateChange(callback: (state: BackendConnectionState) => void): Promise<() => void> | (() => void);
114
+ /** @deprecated Use named channels or `openrtc-file-transfer`. */
115
+ sendExplicitFilePath(connectionId: string, filePath: string, transferId?: string): Promise<string>;
116
+ /** @deprecated Use named channels or `openrtc-file-transfer`. */
117
+ sendExplicitFileData(params: ExplicitFileDataSendParams): Promise<void>;
118
+ /** @deprecated Transfer history belongs to the consumer application. */
119
+ getTransferHistory(limit?: number): Promise<Array<[string, unknown]>>;
120
+ /** @deprecated Transfer history belongs to the consumer application. */
121
+ deleteTransferJob(jobId: string): Promise<void>;
122
+ getRuntimeCapabilities(): RuntimeCapabilities;
123
+ onIncomingNativeMessage(callback: (connectionId: string, remoteNodeId: string | null, message: any) => void): Promise<() => void>;
124
+ unwrap(): ISignalingBackend;
125
+ /**
126
+ * Forward setCoreClient() to the inner backend if it implements it. This
127
+ * lets the core Client inject a reference into backends (e.g. WasmBridge)
128
+ * that need to escalate transport-level dials into full Client.connect()
129
+ * handshakes.
130
+ */
131
+ setCoreClient(client: unknown): void;
132
+ }
133
+
134
+ export { DelegatingRuntimeAdapter as D, type WasmBridgeOptions as W };
@@ -1,6 +1,6 @@
1
- import { H as GrantScope, q as ISignalingBackend, Y as ConnectDeviceHooks, Z as ConnectDeviceOptions, _ as ConnectDeviceResult, u as ManagedConnectionRecord, m as PeerSessionSnapshot, v as ResolvedPeerIdentity, $ as AppLimits, N as NativeConnectParams, z as NativeConnectResult, E as ExplicitFileDataSendParams } from './types-BVJr065k.js';
1
+ import { G as GrantScope, I as ISignalingBackend, X as ConnectDeviceHooks, Y as ConnectDeviceOptions, Z as ConnectDeviceResult, M as ManagedConnectionRecord, P as PeerSessionSnapshot, d as ResolvedPeerIdentity, _ as AppLimits, k as NativeConnectParams, l as NativeConnectResult, E as ExplicitFileDataSendParams } from './types-BHePJWbM.js';
2
2
  import { A as AuthContext } from './IEngineBridge-BbsT8hof.js';
3
- import { a as RuntimePeerState, b as RuntimeConnectionStateSnapshot, c as RuntimePeerReadinessSnapshot, d as RuntimePeerConnectOptions, C as Connection, e as RuntimeIncomingStream, R as RuntimeClientOptions, f as RuntimeAuthIdentity, g as RuntimeLocalDeviceInfo, h as RuntimeLocalDeviceProfile, i as RuntimeDevice, j as RuntimeManagedSessionOptions, k as RuntimeManagedSession, l as RuntimeDeviceStatusSnapshot, m as RuntimeDeviceConnectOptions, n as RuntimeSession, o as RuntimeJoinRoomOptions, p as RuntimeRoomMember, q as RuntimeConnectionTarget, r as RuntimeScopedChannelOptions, s as RuntimeScopedLogicalChannel, t as RuntimePeerStreamOptions, u as RuntimeRawConnection, v as RuntimeChannelDescriptor, w as RuntimePresenceLoopOptions, x as RuntimePeerHealth, y as RuntimeApplicationPayloadReadinessOptions, z as RuntimeConnectionEvent } from './types-BUXwspL0.js';
3
+ import { b as RuntimePeerState, c as RuntimeConnectionStateSnapshot, d as RuntimePeerReadinessSnapshot, e as RuntimePeerConnectOptions, C as Connection, f as RuntimeIncomingStream, a as RuntimeClientOptions, g as RuntimeAuthIdentity, h as RuntimeLocalDeviceInfo, i as RuntimeLocalDeviceProfile, j as RuntimeDevice, k as RuntimeManagedSessionOptions, l as RuntimeManagedSession, m as RuntimeDeviceStatusSnapshot, n as RuntimeDeviceConnectOptions, o as RuntimeSession, p as RuntimeJoinRoomOptions, q as RuntimeRoomMember, r as RuntimeConnectionTarget, s as RuntimeScopedChannelOptions, t as RuntimeScopedLogicalChannel, u as RuntimePeerStreamOptions, v as RuntimeRawConnection, R as RuntimeChannelDescriptor, w as RuntimePresenceLoopOptions, x as RuntimePeerHealth, y as RuntimeApplicationPayloadReadinessOptions, z as RuntimeConnectionEvent } from './types-D0pqNSOf.js';
4
4
  import { R as RuntimeCapabilities, a as RuntimeCapabilityProfile } from './capabilities-YSskrE8H.js';
5
5
 
6
6
  /**
@@ -675,7 +675,6 @@ declare class RuntimeClient {
675
675
  type RuntimeAdapterWithAuth = ISignalingBackend & {
676
676
  setAuthContext?: (context: AuthContext | null) => Promise<void> | void;
677
677
  };
678
- type RuntimeFactoryOptions = RuntimeClientOptions;
679
678
  interface PlutoRuntimeAssembly<TBackend extends RuntimeAdapterWithAuth = RuntimeAdapterWithAuth> {
680
679
  runtime: RuntimeClient;
681
680
  identity: any;
@@ -857,7 +856,7 @@ interface OpenRTCAdvancedNamespace {
857
856
  *
858
857
  * This is the unified type returned by OpenRTC() and OpenRTC.native().
859
858
  */
860
- interface OpenRTCClient$1 extends RuntimeClient {
859
+ interface OpenRTCClient extends RuntimeClient {
861
860
  readonly devices: OpenRTCDeviceNamespace;
862
861
  readonly peers: OpenRTCPeerNamespace;
863
862
  readonly channels: OpenRTCChannelNamespace;
@@ -942,195 +941,4 @@ interface OpenRTCClient$1 extends RuntimeClient {
942
941
  readonly _assembly: PlutoRuntimeAssembly;
943
942
  }
944
943
 
945
- interface OpenRTCAuthProvider {
946
- /** Registered provider ID from the developer app capability manifest. */
947
- readonly providerId?: string;
948
- getAssertion(input: {
949
- audience: 'https://api.openrtc.app/v2/assertions/exchange';
950
- forceRefresh: boolean;
951
- }): Promise<string | null>;
952
- /**
953
- * Optional identity-epoch observer. Notify only when the signed-in
954
- * principal/session changes (login, logout, account switch, or explicit
955
- * revocation). Do not notify for ordinary OAuth/Firebase access-token
956
- * refreshes: OpenRTC refreshes its own avenue grant in place.
957
- */
958
- subscribe?(listener: () => void): () => void;
959
- }
960
- interface OpenRTCAttestationProvider {
961
- readonly kind: 'firebase-app-check' | 'apple-app-attest' | 'play-integrity' | `custom:${string}`;
962
- /**
963
- * Describes what the provider actually signs. Reusable app-integrity
964
- * tokens (for example Firebase App Check) do not become request-bound just
965
- * because OpenRTC supplies an enrollment challenge. The server derives and
966
- * enforces the authoritative binding from the registered provider kind;
967
- * this field keeps host integrations and diagnostics honest.
968
- */
969
- readonly evidenceBinding: 'app-session' | 'request-challenge';
970
- getEvidence(input: {
971
- challenge: string;
972
- apiKey: string;
973
- }): Promise<{
974
- token: string;
975
- }>;
976
- }
977
- /**
978
- * Optional consumer-owned bot challenge. Core OpenRTC does not render a UI or
979
- * load a CAPTCHA dependency; the host supplies a fresh token only when its
980
- * developer manifest requires anonymous capability verification.
981
- */
982
- interface OpenRTCBotVerificationProvider {
983
- getToken(input: {
984
- action: 'openrtc_capability';
985
- apiKey: string;
986
- }): Promise<string>;
987
- }
988
- interface OpenRTCUsageUpdate {
989
- sessionCreditsUsd: number;
990
- operation: string;
991
- estimated: boolean;
992
- }
993
- interface OpenRTCUsageWarning extends OpenRTCUsageUpdate {
994
- thresholdCreditsUsd: number;
995
- kind: 'warning' | 'session-limit';
996
- }
997
- interface OpenRTCTransportPreferences {
998
- iroh?: boolean;
999
- webrtc?: boolean;
1000
- relay?: boolean;
1001
- moq?: boolean;
1002
- ble?: boolean;
1003
- /**
1004
- * Advanced privacy mode. `relay-only` suppresses direct Iroh addresses,
1005
- * local discovery, and host/srflx WebRTC candidates. It also requires the
1006
- * developer manifest's relay opt-in.
1007
- */
1008
- privacy?: 'direct' | 'relay-only';
1009
- /**
1010
- * Advanced native integration for hosts whose Rust process owns the
1011
- * application protocol registry (for example, a Tauri file-transfer host).
1012
- * Normal SDK consumers should leave this disabled.
1013
- */
1014
- nativeHostProtocols?: boolean;
1015
- priority?: readonly ('iroh' | 'webrtc' | 'moq' | 'ble')[];
1016
- }
1017
- interface OpenRTCOptions {
1018
- apiKey: string;
1019
- auth?: OpenRTCAuthProvider;
1020
- trust?: {
1021
- attestation?: OpenRTCAttestationProvider;
1022
- botVerification?: OpenRTCBotVerificationProvider;
1023
- };
1024
- usage?: {
1025
- warnAtSessionCreditsUsd?: number;
1026
- maxSessionCreditsUsd?: number;
1027
- onUsage?: (event: OpenRTCUsageUpdate) => void;
1028
- onWarning?: (warning: OpenRTCUsageWarning) => void;
1029
- };
1030
- transports?: OpenRTCTransportPreferences;
1031
- }
1032
- type OpenRTCAccessMode = 'capability' | 'authenticated';
1033
- type OpenRTCLatestStateMode = 'reliable' | 'latest-state';
1034
- interface OpenRTCCapabilityHandle {
1035
- readonly kind: 'devices' | 'space' | 'room' | 'ticket';
1036
- readonly id: string;
1037
- readonly peers: OpenRTCPeerNamespace;
1038
- readonly channels: OpenRTCChannelNamespace;
1039
- readonly diagnostics: OpenRTCDiagnosticsNamespace;
1040
- readonly closed: boolean;
1041
- close(): Promise<void>;
1042
- }
1043
- interface OpenRTCDevicesHandle extends OpenRTCCapabilityHandle {
1044
- readonly kind: 'devices';
1045
- localId(): ReturnType<OpenRTCDeviceNamespace['localId']>;
1046
- localInfo(): ReturnType<OpenRTCDeviceNamespace['localInfo']>;
1047
- list(): ReturnType<OpenRTCDeviceNamespace['list']>;
1048
- listWithStatus(): ReturnType<OpenRTCDeviceNamespace['listWithStatus']>;
1049
- watch: OpenRTCDeviceNamespace['watch'];
1050
- connect: OpenRTCDeviceNamespace['connect'];
1051
- disconnect: OpenRTCDeviceNamespace['disconnect'];
1052
- }
1053
- interface OpenRTCSpaceHandle extends OpenRTCCapabilityHandle {
1054
- readonly kind: 'space';
1055
- readonly delivery: OpenRTCLatestStateMode;
1056
- leave(): Promise<void>;
1057
- }
1058
- interface OpenRTCRoomHandle extends OpenRTCCapabilityHandle {
1059
- readonly kind: 'room';
1060
- readonly membership: 'ephemeral' | 'durable';
1061
- leave(): Promise<void>;
1062
- }
1063
- interface OpenRTCTicketHandle extends OpenRTCCapabilityHandle {
1064
- readonly kind: 'ticket';
1065
- readonly token: string;
1066
- }
1067
- interface OpenRTCDevicesStartOptions {
1068
- auth?: OpenRTCAuthProvider;
1069
- autoConnect?: 'none' | 'online';
1070
- /** Optional local profile; it does not alter the durable device identity. */
1071
- profile?: {
1072
- name?: string;
1073
- /**
1074
- * Optional application-owned public presence metadata. It is bounded
1075
- * to 4 KiB and folded into the initial connection/presence operation.
1076
- */
1077
- metadata?: string;
1078
- };
1079
- maxPeers?: number;
1080
- /** Requires the app manifest's advanced-fanout opt-in. */
1081
- advancedFanout?: boolean;
1082
- }
1083
- interface OpenRTCSpaceJoinOptions {
1084
- access?: 'capability';
1085
- identity?: 'ephemeral';
1086
- payload?: OpenRTCLatestStateMode;
1087
- maxPeers?: number;
1088
- /** Requires the app manifest's advanced-fanout opt-in. */
1089
- advancedFanout?: boolean;
1090
- }
1091
- interface OpenRTCRoomJoinOptions {
1092
- access?: OpenRTCAccessMode;
1093
- membership?: 'ephemeral' | 'durable';
1094
- auth?: OpenRTCAuthProvider;
1095
- maxPeers?: number;
1096
- /** Requires the app manifest's advanced-fanout opt-in. */
1097
- advancedFanout?: boolean;
1098
- }
1099
- interface OpenRTCTicketIssueOptions {
1100
- maxPeers?: number;
1101
- /** Requires the app manifest's advanced-fanout opt-in. */
1102
- advancedFanout?: boolean;
1103
- }
1104
- interface OpenRTCChannelCatalog {
1105
- register(descriptor: RuntimeChannelDescriptor): () => void;
1106
- list(): readonly RuntimeChannelDescriptor[];
1107
- }
1108
- interface OpenRTCUsageNamespace {
1109
- estimate(input: {
1110
- operation: string;
1111
- units?: number;
1112
- }): {
1113
- creditsUsd: number;
1114
- estimated: true;
1115
- };
1116
- readonly sessionCreditsUsd: number;
1117
- }
1118
- interface OpenRTCClient {
1119
- readonly devices: {
1120
- start(options?: OpenRTCDevicesStartOptions): Promise<OpenRTCDevicesHandle>;
1121
- };
1122
- readonly spaces: {
1123
- join(id: string, options?: OpenRTCSpaceJoinOptions): Promise<OpenRTCSpaceHandle>;
1124
- };
1125
- readonly rooms: {
1126
- join(id: string, options?: OpenRTCRoomJoinOptions): Promise<OpenRTCRoomHandle>;
1127
- };
1128
- readonly tickets: {
1129
- issue(id: string, options?: OpenRTCTicketIssueOptions): Promise<OpenRTCTicketHandle>;
1130
- };
1131
- readonly channels: OpenRTCChannelCatalog;
1132
- readonly usage: OpenRTCUsageNamespace;
1133
- close(): Promise<void>;
1134
- }
1135
-
1136
- export { DriveGrantActorHandle as A, type DriveGrantActorHandleOptions as B, DriveGrantActorRegistry as C, DriveGrantActorError as D, type DriveGrantActorState as E, type DriveGrantClose as F, type DriveGrantDial as G, type DriveGrantConnectionKey as H, type DriveGrantLogicalChannelHandle as I, type DriveGrantPreferredTransport as J, getRuntimePolicy as K, driveGrantConnectionKey as L, driveGrantConnectionKeyToString as M, type OpenRTCOptions as O, type PlutoRuntimeAssembly as P, type RuntimeFactoryOptions as R, type OpenRTCClient as a, type OpenRTCAccessMode as b, type OpenRTCAttestationProvider as c, type OpenRTCAuthProvider as d, type OpenRTCBotVerificationProvider as e, type OpenRTCCapabilityHandle as f, type OpenRTCChannelCatalog as g, type OpenRTCDevicesHandle as h, type OpenRTCDevicesStartOptions as i, type OpenRTCLatestStateMode as j, type OpenRTCRoomHandle as k, type OpenRTCRoomJoinOptions as l, type OpenRTCSpaceHandle as m, type OpenRTCSpaceJoinOptions as n, type OpenRTCTicketHandle as o, type OpenRTCTicketIssueOptions as p, type OpenRTCTransportPreferences as q, type OpenRTCUsageNamespace as r, type OpenRTCUsageUpdate as s, type OpenRTCUsageWarning as t, type OpenRTCClient$1 as u, type PeerReconciliationStats as v, OPENRTC_RUNTIME_POLICY as w, RuntimeClient as x, type RuntimePolicySnapshot as y, type DriveGrantActorErrorKind as z };
944
+ export { DriveGrantActorError as D, type OpenRTCPeerNamespace as O, type PeerReconciliationStats as P, RuntimeClient as R, type OpenRTCChannelNamespace as a, type OpenRTCDiagnosticsNamespace as b, type OpenRTCDeviceNamespace as c, type OpenRTCClient as d, OPENRTC_RUNTIME_POLICY as e, type RuntimePolicySnapshot as f, type DriveGrantActorErrorKind as g, DriveGrantActorHandle as h, type DriveGrantActorHandleOptions as i, DriveGrantActorRegistry as j, type DriveGrantActorState as k, type DriveGrantClose as l, type DriveGrantDial as m, type DriveGrantConnectionKey as n, type DriveGrantLogicalChannelHandle as o, type DriveGrantPreferredTransport as p, getRuntimePolicy as q, driveGrantConnectionKey as r, driveGrantConnectionKeyToString as s };
@@ -1 +1 @@
1
- export{w as WasmBridge}from'./chunk-YBXGNKM7.js';import'./chunk-VK6KX433.js';import'./chunk-NT5YHZQH.js';import'./chunk-N26S7V4N.js';import'./chunk-NB4H5TP3.js';import'./chunk-RD3JEGGF.js';import'./chunk-C7YN5MSV.js';
1
+ export{w as WasmBridge}from'./chunk-JIVVHBCB.js';import'./chunk-VK6KX433.js';import'./chunk-NT5YHZQH.js';import'./chunk-N26S7V4N.js';import'./chunk-NB4H5TP3.js';import'./chunk-RD3JEGGF.js';import'./chunk-C7YN5MSV.js';
@@ -0,0 +1,2 @@
1
+ var T=new Map;function P(a){let e=new Uint8Array(a),t="";for(let i of e)t+=String.fromCharCode(i);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function V(a){let e=JSON.stringify({crv:a.crv,kty:a.kty,x:a.x});return P(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(e)))}function q(){return P(crypto.getRandomValues(new Uint8Array(24)).buffer)}async function O(){return typeof indexedDB>"u"?null:new Promise((a,e)=>{let t=indexedDB.open("openrtc-v2-device-keys",1);t.onupgradeneeded=()=>{t.result.objectStoreNames.contains("keys")||t.result.createObjectStore("keys");},t.onsuccess=()=>a(t.result),t.onerror=()=>e(t.error);})}async function W(a){let e=await O().catch(()=>null);if(!e)return T.get(a)??null;try{return await new Promise((t,i)=>{let n=e.transaction("keys","readonly").objectStore("keys").get(a);n.onsuccess=()=>t(n.result??null),n.onerror=()=>i(n.error);})}finally{e.close();}}async function B(a,e){let t=await O().catch(()=>null);if(!t){T.set(a,e);return}try{await new Promise((i,n)=>{let r=t.transaction("keys","readwrite").objectStore("keys").put(e,a);r.onsuccess=()=>i(),r.onerror=()=>n(r.error);});}finally{t.close();}}async function z(a){T.delete(a);let e=await O().catch(()=>null);if(e)try{await new Promise((t,i)=>{let n=e.transaction("keys","readwrite").objectStore("keys").delete(a);n.onsuccess=()=>t(),n.onerror=()=>i(n.error);});}finally{e.close();}}async function Z(a){let e=await W(a);if(e)return e;let t=await crypto.subtle.generateKey({name:"Ed25519"},false,["sign","verify"]);return await B(a,t),t}var J={async getOrCreate(a){let e=await Z(a),t=await crypto.subtle.exportKey("jwk",e.publicKey),i=await V(t);return {publicKeyJwk:t,thumbprint:i,async proof(n){let r=q(),o=Math.floor(Date.now()/1e3),s=await crypto.subtle.sign({name:"Ed25519"},e.privateKey,new TextEncoder().encode(n(r,o)));return {publicKeyJwk:t,signature:P(s),nonce:r,issuedAt:o}}}},delete:z};var N={"identity.assertion.exchange":25692e-8,"identity.monthly-active-principal":110352e-9,"capability.issue":212346e-9,"device.enroll":218946e-9,"gateway.grant.issue":202146e-9,"gateway.grant.refresh":200346e-9,"security.attestation.verify":29694e-8,"room.create":388056e-9,"room.join":209946e-9,"room.leave":200346e-9,"coordination.connection.open":287514e-9,"coordination.credential.refresh":259662e-9,"coordination.presence.offline":253638e-9,"coordination.signal.send":259638e-9,"coordination.session.put":259638e-9,"coordination.session.delete":253638e-9,"coordination.usage.ingest":197088e-9};var R={controlPlane:"https://api.openrtc.app",gateway:"https://gateway.openrtc.app"},j=1440*6e4,f=class extends Error{constructor(t,i){super(t);this.status=i;this.name="OpenRTCV2HttpError";}};function k(a,e,t){return `openrtc:v2:device-certificate:${a}:${e}:${t}`}function A(a,e){return `openrtc:v2:device-session:${a}:${e}`}async function X(a,e,t){let i=new TextEncoder().encode(`openrtc:v2:session\0${a}\0${e}\0${t}`),n=new Uint8Array(await crypto.subtle.digest("SHA-256",i)),r="";for(let o of n)r+=String.fromCharCode(o);return btoa(r).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,"")}function U(a){let e=a.replace(/-/g,"+").replace(/_/g,"/"),t=e.padEnd(Math.ceil(e.length/4)*4,"="),i=atob(t);return Uint8Array.from(i,n=>n.charCodeAt(0))}async function F(a,e,t,i,n){if(typeof a.token!="string"||typeof a.expiresAtMs!="number"||a.expiresAtMs<=Date.now()+j||!a.signingPublicJwk||a.signingPublicJwk.kty!=="OKP"||a.signingPublicJwk.crv!=="Ed25519"||typeof a.signingPublicJwk.x!="string")return null;let r=a.token.split(".");if(r.length!==3)return null;let o,s;try{o=JSON.parse(new TextDecoder().decode(U(r[0]))),s=v(a.token);}catch{return null}if(o.alg!=="EdDSA"||a.signingPublicJwk.kid&&o.kid!==a.signingPublicJwk.kid)return null;try{let u=await crypto.subtle.importKey("jwk",a.signingPublicJwk,{name:"Ed25519"},!1,["verify"]);if(!await crypto.subtle.verify({name:"Ed25519"},u,U(r[2]),new TextEncoder().encode(`${r[0]}.${r[1]}`)))return null}catch{return null}let c=typeof s.principalId=="string"?s.principalId:"",l=Number(s.iat),d=Number(s.exp);return s.iss!=="openrtc"||s.aud!=="openrtc:v2:gateway-grant"||s.typ!=="device-certificate"||s.appTag!==e||!c||n!==void 0&&c!==n||typeof s.principalKey!="string"||s.principalKey.length===0||s.deviceId!==t||s.deviceKeyThumbprint!==i||typeof s.jti!="string"||s.jti.length===0||!Number.isSafeInteger(l)||!Number.isSafeInteger(d)||l>=d||d*1e3!==a.expiresAtMs?null:{token:a.token,expiresAtMs:a.expiresAtMs,principalId:c,signingPublicJwk:a.signingPublicJwk,enrolled:false}}async function Q(a,e,t,i){try{let n=globalThis.localStorage?.getItem(k(a,e,t));if(!n)return null;let r=JSON.parse(n),o=await F(r,a,t,i,e);return o?{token:o.token,expiresAtMs:o.expiresAtMs,principalId:e,signingPublicJwk:o.signingPublicJwk}:null}catch{return null}}async function Y(a,e,t,i){try{let n=globalThis.localStorage?.getItem(A(a,t));return n?await F(JSON.parse(n),e,t,i):null}catch{return null}}function ee(a,e,t,i){try{globalThis.localStorage?.setItem(k(a,e,t),JSON.stringify(i));}catch{}}function te(a,e,t){try{globalThis.localStorage?.setItem(A(a,e),JSON.stringify({token:t.token,expiresAtMs:t.expiresAtMs,principalId:t.principalId,signingPublicJwk:t.signingPublicJwk}));}catch{}}function $(a,e,t,i){try{globalThis.localStorage?.removeItem(k(a,e,t)),i&&globalThis.localStorage?.removeItem(A(i,t));}catch{}}function ie(a){return `${a}_${crypto.randomUUID()}`}async function ne(a,e){let t=new TextEncoder().encode(`${a}:${e}`);return [...new Uint8Array(await crypto.subtle.digest("SHA-256",t))].map(n=>n.toString(16).padStart(2,"0")).join("")}function v(a){let e=a.split(".")[1];if(!e)throw new Error("OpenRTC returned a malformed credential.");let t=e.replace(/-/g,"+").replace(/_/g,"/"),i=t.padEnd(Math.ceil(t.length/4)*4,"=");return JSON.parse(atob(i))}var C=class{constructor(e,t,i,n,r={},o){this.apiKey=e;this.endpoints=t;this.keyProvider=i;this.attestation=n;this.events=r;this.botVerification=o;this.keyPromise=null;this.authEpochs=new Map;this.appTag=`app_${e.slice(-16)}`;}record(e){this.events.onLogicalOperation?.(e);}before(e){this.events.beforeLogicalOperation?.(e);}authEpoch(e){let t=this.authEpochs.get(e);if(t)return t;let i={generation:0,devices:new Map};return this.authEpochs.set(e,i),e.subscribe&&(i.unsubscribe=e.subscribe(n=>{n?.type==="principal-changed"&&(i.generation+=1,i.devices.clear(),i.sessionKeyHash=void 0,this.events.onAuthEpochChanged?.(e));})),i}dispose(){for(let e of this.authEpochs.values())e.unsubscribe?.();this.authEpochs.clear();}key(){return this.keyPromise??(this.keyPromise=this.keyProvider.getOrCreate(this.appTag))}async post(e,t){let i=ie("request"),n=JSON.stringify({apiKey:this.apiKey,...t}),r=null;for(let o=0;o<2;o+=1)try{let s=await fetch(`${this.endpoints.controlPlane}${e}`,{method:"POST",headers:{"Content-Type":"application/json","X-OpenRTC-Idempotency-Key":i},body:n,signal:AbortSignal.timeout(15e3)});if(s.ok)return s.json();let c=`OpenRTC request failed (${s.status}).`;try{let d=await s.json();typeof d.error=="string"&&(c=d.error.slice(0,256));}catch{}let l=new f(c,s.status);if(r=l,o===0&&[502,503,504].includes(s.status))continue;throw l}catch(s){if(r=s,o===0&&s instanceof TypeError)continue;throw s}throw r instanceof Error?r:new Error("OpenRTC request failed.")}async capability(e,t,i,n=false){this.before("capability.issue");let r=e==="space"?await ne(this.apiKey,t):t,s=await(await this.key()).proof((u,p)=>["openrtc:v2:capability",this.apiKey,e,r,u,p].join(":")),c=this.botVerification?await this.botVerification.getToken({action:"openrtc_capability",apiKey:this.apiKey}):void 0,l=await this.post("/v2/capabilities",{avenue:{kind:e,id:r},deviceProof:s,...i?{maxPeers:i}:{},...n?{advancedFanout:true}:{},...c?{turnstileToken:c}:{}});this.record("capability.issue");let d={type:"capability",token:l.capability,avenue:e==="ticket"?{kind:"session",id:r}:l.avenue,expiresAtMs:l.expiresAt*1e3};return d.renew=()=>this.capability(e,t,i,n),d}async deviceCertificate(e,t,i){let n=this.authEpoch(e),r=n.devices.get(t)??{};if(n.devices.set(t,r),r.current&&r.current.expiresAtMs>Date.now()+j)return this.deviceCertificateResult(e,t,i,{...r.current,enrolled:false});if(!r.inFlight){let s=n.generation;r.inFlight=this.resolveAuthenticatedDevice(e,t,n).then(c=>{if(n.generation!==s)throw new Error("The OpenRTC authentication identity changed during enrollment.");return r.current=c,c}).finally(()=>{r.inFlight=void 0;});}let o=await r.inFlight;return this.deviceCertificateResult(e,t,i,o)}async resolveAuthenticatedDevice(e,t,i){let n=await this.key();if(e.getSessionKey){let r=await e.getSessionKey();if(!r)throw new Error("The OpenRTC auth provider has no active principal.");let o=await X(this.appTag,n.thumbprint,r);i.sessionKeyHash=o;let s=await Y(o,this.appTag,t,n.thumbprint);if(s)return s}return this.enrollAuthenticatedDevice(e,t,i.sessionKeyHash)}deviceCertificateResult(e,t,i,n){let r={type:"device-certificate",token:n.token,avenue:i??{kind:"user",id:n.principalId},expiresAtMs:n.expiresAtMs};return r.renew=async()=>(await this.deviceCertificate(e,t,i)).source,{principalId:n.principalId,source:r,enrolled:n.enrolled}}async enrollAuthenticatedDevice(e,t,i){this.before("identity.assertion.exchange"),this.before("identity.monthly-active-principal");let n=async p=>{let h=await e.getAssertion({audience:"https://api.openrtc.app/v2/assertions/exchange",forceRefresh:p,deviceId:t});if(!h)throw new Error("The OpenRTC auth provider returned no assertion.");return this.post("/v2/assertions/exchange",{assertion:h,...e.providerId?{providerId:e.providerId}:{}})},r;try{r=await n(!1);}catch(p){if(!(p instanceof f)||p.status!==401)throw p;r=await n(true);}this.record("identity.assertion.exchange"),this.record("identity.monthly-active-principal");let o=await this.key(),s=await Q(this.appTag,r.principalId,t,o.thumbprint);if(s)return {...s,principalId:r.principalId,enrolled:false};this.before("device.enroll"),this.attestation&&this.before("security.attestation.verify");let c=await o.proof((p,h)=>["openrtc:v2:device-enroll",this.appTag,r.principalId,t,p,h].join(":")),l=this.attestation?{kind:this.attestation.kind,...await this.attestation.getEvidence({challenge:`openrtc:v2:attestation:${this.appTag}:${r.principalId}:${t}:${c.nonce}`,apiKey:this.apiKey})}:void 0,d=await this.post("/v2/devices/enroll",{identitySession:r.identitySession,deviceId:t,deviceProof:c,...l?{attestation:l}:{}});this.record("device.enroll"),l&&this.record("security.attestation.verify");let u={principalId:r.principalId,token:d.deviceCertificate,expiresAtMs:d.expiresAt*1e3,signingPublicJwk:d.signingPublicJwk,enrolled:true};return ee(this.appTag,r.principalId,t,{token:u.token,expiresAtMs:u.expiresAtMs,signingPublicJwk:u.signingPublicJwk}),i&&te(i,t,u),u}async listEnrolledDevices(e,t){let i=await this.deviceCertificate(e,t);return (await this.deviceManagement(i.source,t,"list")).devices??[]}async revokeDevice(e,t,i){let n=await this.deviceCertificate(e,t);if(await this.deviceManagement(n.source,t,"revoke",i),i===t){let r=this.authEpoch(e);$(this.appTag,n.principalId,t,r.sessionKeyHash),r.devices.delete(t),await this.deleteDeviceKey();}}async revokeAllDevices(e,t,i){let n=await this.deviceCertificate(e,t);await this.deviceManagement(n.source,t,"revoke-all",void 0,i);let r=this.authEpoch(e);$(this.appTag,n.principalId,t,r.sessionKeyHash),r.devices.delete(t),i?await this.deviceCertificate(e,t):(r.devices.clear(),await this.deleteDeviceKey());}async deleteDeviceKey(){this.keyPromise=null,await this.keyProvider.delete?.(this.appTag);}async deviceManagement(e,t,i,n,r=false){if(e.type!=="device-certificate")throw new Error("Device management requires an authenticated device certificate.");let o=v(e.token),s=String(o.jti??""),l=await(await this.key()).proof((p,h)=>["openrtc:v2:device-management",s,i,n??"",r?"except-current":"include-current",p,h].join(":")),d=i==="revoke"?"device.revoke":i==="revoke-all"?"identity.revoke-all":null;d&&this.before(d);let u=await this.post("/v2/devices/manage",{action:i,deviceCertificate:e.token,currentDeviceId:t,...n?{targetDeviceId:n}:{},...r?{exceptCurrent:true}:{},deviceProof:l});return d&&this.record(d),u}async durableRoomMembership(e,t,i){if(e.type!=="device-certificate")throw new Error("Durable rooms require a device certificate.");this.before(i==="join"?"room.join":"room.leave");let n=v(e.token),r=String(n.jti??""),s=await(await this.key()).proof((c,l)=>["openrtc:v2:room-membership",r,i,t,c,l].join(":"));await this.post("/v2/rooms/memberships",{action:i,roomId:t,deviceCertificate:e.token,deviceProof:s}),this.record(i==="join"?"room.join":"room.leave");}grantProvider(e,t={}){let i=null,n=e;return async r=>{if(i)return i;let o=(async()=>{let s=false;n.expiresAtMs<=Date.now()+5*6e4&&n.renew&&(n=await n.renew(),s=true);let c=r.refreshGrant?"gateway.grant.refresh":"gateway.grant.issue";this.before(c),r.refreshGrant&&this.before("coordination.credential.refresh");let l=v(n.token),d=String(l.jti??""),p=await(await this.key()).proof((y,b)=>["openrtc:v2:gateway-grant",d,r.avenue.kind,r.avenue.id,r.runtimeInstanceId,y,b].join(":")),h=await this.post("/v2/gateway/grants",{credentialType:n.type,credential:n.token,avenue:r.avenue,runtimeInstanceId:r.runtimeInstanceId,ticketFingerprint:r.ticketFingerprint,deviceProof:p,...r.refreshGrant?{refreshGrant:r.refreshGrant}:{},...t.maxPeers?{maxPeers:t.maxPeers}:{},...t.features?{features:t.features}:{}});return this.record(c),r.refreshGrant&&this.record("coordination.credential.refresh"),s&&await t.onSourceRenewed?.({token:n.token,expiresAtMs:n.expiresAtMs}),h})();i=o;try{return await o}finally{i===o&&(i=null);}}}};var I=new WeakMap;function ye(a){let e=I.get(a);if(!e)throw new Error("[OpenRTC] Capability runtime is unavailable or already closed.");return e}function re(a){let e=a?.trim()??"";if(!/^pk_(?:live|test)_[0-9a-f]{40}$/.test(e))throw new Error("[OpenRTC] apiKey must be a public pk_live_ or pk_test_ key.");return e}function g(a){let e=a?.trim()??"";if(!e||e.length>160||!/^[A-Za-z0-9_.:@-]+$/.test(e))throw new Error("[OpenRTC] Capability id is invalid.");return e}function ae(a){let e=a?.trim();if(e){if(new TextEncoder().encode(e).byteLength>4*1024)throw new Error("[OpenRTC] Device profile metadata must not exceed 4 KiB.");return e}}var G=/^[A-Za-z0-9_.:@-]{1,160}$/,se=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;function L(a){let e=typeof a=="string"?a.trim():"";if(!G.test(e))return null;let t=e.startsWith("device_")?e.slice(7):"";return se.test(t)?t:e}function oe(a,e){try{let t=a.getItem(`pluto_rtc_web_device_identity_${e}`);if(!t)return null;let i=JSON.parse(t);return L(i?.deviceId)}catch{return null}}function ce(a){let e=`openrtc:v2:device-id:${a}`,t=`pluto_rtc_web_device_identity_${a}`,i,n=(()=>{try{return i=globalThis.localStorage,i&&oe(i,a)||L(i?.getItem(e))||crypto.randomUUID()}catch{return crypto.randomUUID()}})();try{i?.setItem(e,n),i?.setItem(t,JSON.stringify({deviceId:n}));}catch{}return n}function H(a){let e=typeof a=="string"?a.trim():"";if(!G.test(e))throw new Error("[OpenRTC] The native host returned an invalid durable device ID.");return e}function S(a){let e=v(a.token),t=typeof e.deviceKeyThumbprint=="string"?e.deviceKeyThumbprint.trim():"";if(!/^[A-Za-z0-9_-]{43}$/.test(t))throw new Error("[OpenRTC] Anonymous capability is missing its device-key binding.");return `anon_${t.slice(0,32)}`}var x=class{constructor(){this.descriptors=new Map;this.targets=new Map;}register(e){if(!e?.id?.trim())throw new Error("[OpenRTC] Channel id is required.");this.descriptors.set(e.id,{...e});for(let[t,i]of this.targets)t.channels.register({...e,delivery:e.delivery??i});return ()=>{this.descriptors.delete(e.id);for(let t of this.targets.keys())t.channels.unregister(e.id);}}list(){return [...this.descriptors.values()].map(e=>({...e}))}attach(e,t){this.targets.set(e,t);for(let i of this.descriptors.values())e.channels.register({...i,delivery:i.delivery??t});}detach(e){this.targets.delete(e);}},D=class{constructor(e){this.options=e;this.total=0;this.warned=false;}get sessionCreditsUsd(){return this.total}estimate(e){let t=Math.max(0,Math.floor(e.units??1));return {creditsUsd:(N[e.operation]??0)*t,estimated:true}}assertCanSpend(e,t=1){let i=this.options?.maxSessionCreditsUsd;if(i===void 0||this.total+this.estimate({operation:e,units:t}).creditsUsd<=i)return;let r={sessionCreditsUsd:this.total,operation:e,estimated:true,thresholdCreditsUsd:i,kind:"session-limit"};throw this.options?.onWarning?.(r),new Error("[OpenRTC] The client-side session credit limit was reached.")}record(e,t=1){let i=this.estimate({operation:e,units:t}).creditsUsd;this.total+=i;let n={sessionCreditsUsd:this.total,operation:e,estimated:true};this.options?.onUsage?.(n);let r=this.options?.warnAtSessionCreditsUsd;!this.warned&&r!==void 0&&this.total>=r&&(this.warned=true,this.options?.onWarning?.({...n,thresholdCreditsUsd:r,kind:"warning"}));}},m=class{constructor(e,t,i,n){this.kind=e;this.id=t;this.client=i;this.onClosed=n;this.closed=false;I.set(this,i);}get peers(){return this.client.peers}get channels(){return this.client.channels}get diagnostics(){return this.client.diagnostics}async retireDeviceIfPresent(e){(await this.client.devices.list()).some(i=>i.deviceId===e)&&await this.client.devices.delete(e);}async retireAllOtherDevices(e){let t=await this.client.devices.list();for(let i of t)i.deviceId!==e&&await this.client.devices.delete(i.deviceId);}async close(){if(!this.closed){this.closed=true;try{await this.client.advanced.runtime.shutdown();}finally{I.delete(this),this.onClosed();}}}},E=class extends m{constructor(t,i,n){super("devices",t,i,n);this.kind="devices";this.localId=()=>this.client.devices.localId();this.localInfo=()=>this.client.devices.localInfo();this.list=()=>this.client.devices.list();this.listWithStatus=()=>this.client.devices.listWithStatus();this.watch=this.client.devices.watch;this.connect=this.client.devices.connect;this.disconnect=this.client.devices.disconnect;}},K=class extends m{constructor(t,i,n,r){super("space",t,i,n);this.delivery=r;this.kind="space";this.leave=()=>this.close();}},w=class extends m{constructor(t,i,n,r,o){super("room",t,i,n);this.membership=r;this.onLeave=o;this.kind="room";this.left=false;}async leave(){this.left||(this.left=true,await this.onLeave?.()),await this.close();}},M=class extends m{constructor(t,i,n,r){super("ticket",t,i,n);this.token=r;this.kind="ticket";}},_=class{constructor(e,t){this.options=e;this.internals=t;this.channels=new x;this.handles=new Set;this.activations=new Map;this.closed=false;this.devices={start:(e={})=>{let t=e.auth??this.options.auth;return this.activateOnce("devices",JSON.stringify({autoConnect:e.autoConnect??"online",maxPeers:e.maxPeers??null,advancedFanout:e.advancedFanout===true,profile:e.profile??null}),t,()=>this.startDevices(e))},listEnrolled:async(e={})=>{this.assertOpen();let t=e.auth??this.options.auth;if(!t)throw new Error("[OpenRTC] devices.listEnrolled() requires an auth provider.");return this.controlPlane.listEnrolledDevices(t,await this.deviceId())},revoke:async(e,t={})=>{this.assertOpen();let i=t.auth??this.options.auth;if(!i)throw new Error("[OpenRTC] devices.revoke() requires an auth provider.");let n=H(e),r=await this.deviceId();await this.controlPlane.revokeDevice(i,r,n),await Promise.allSettled([...this.handles].map(o=>o.retireDeviceIfPresent(n))),n===r&&this.retireAuthCapabilities(i);},revokeAll:async(e={})=>{this.assertOpen();let t=e.auth??this.options.auth;if(!t)throw new Error("[OpenRTC] devices.revokeAll() requires an auth provider.");if(await this.controlPlane.revokeAllDevices(t,await this.deviceId(),e.exceptCurrent===true),e.exceptCurrent===true){let i=await this.deviceId();await Promise.allSettled([...this.handles].map(n=>n.retireAllOtherDevices(i)));}e.exceptCurrent!==true&&this.retireAuthCapabilities(t);}};this.spaces={join:(e,t={})=>this.activateOnce(`space:${g(e)}`,JSON.stringify({payload:t.payload??"reliable",maxPeers:t.maxPeers??null,advancedFanout:t.advancedFanout===true}),void 0,()=>this.joinSpace(e,t))};this.rooms={join:(e,t={})=>{let i=t.access??"capability";return this.activateOnce(`room:${g(e)}`,JSON.stringify({access:i,membership:t.membership??"ephemeral",maxPeers:t.maxPeers??null,advancedFanout:t.advancedFanout===true}),i==="authenticated"?t.auth??this.options.auth:void 0,()=>this.joinRoom(e,t))}};this.tickets={issue:(e,t={})=>this.activateOnce(`ticket:${g(e)}`,JSON.stringify({maxPeers:t.maxPeers??null,advancedFanout:t.advancedFanout===true}),void 0,()=>this.issueTicket(e,t))};this.onClosed=e=>{this.handles.delete(e);for(let[t,i]of this.activations)i.handle===e&&this.activations.delete(t);};this.apiKey=re(e.apiKey),this.usage=new D(e.usage),this.controlPlane=new C(this.apiKey,t.endpoints??R,t.deviceKeyProvider??J,e.trust?.attestation,{beforeLogicalOperation:i=>this.usage.assertCanSpend(i),onLogicalOperation:i=>this.usage.record(i),onAuthEpochChanged:i=>this.retireAuthCapabilities(i)},e.trust?.botVerification);}assertOpen(){if(this.closed)throw new Error("[OpenRTC] Client is closed.")}activateOnce(e,t,i,n){this.assertOpen();let r=this.activations.get(e);if(r){if(r.fingerprint!==t||r.auth!==i)throw new Error(`[OpenRTC] ${e} is already active with different options.`);return r.promise}let o={fingerprint:t,auth:i},s=n().then(c=>(o.handle=c,c)).catch(c=>{throw this.activations.get(e)===o&&this.activations.delete(e),c});return o.promise=s,this.activations.set(e,o),s}retireAuthCapabilities(e){for(let t of this.activations.values())t.auth===e&&t.promise.then(i=>i.close()).catch(()=>{});}async deviceId(){let e=this.internals.deviceIdProvider?await this.internals.deviceIdProvider(this.controlPlane.appTag):ce(this.controlPlane.appTag);return H(e)}runtimeOptions(e){let t=this.options.transports,i=t?.privacy==="relay-only";if(i&&t?.relay!==true)throw new Error("[OpenRTC] transports.privacy: relay-only requires transports.relay: true.");return {apiKey:this.apiKey,authMode:"external",discoveryMode:e.avenue?.kind==="user"?"user-scoped":"space",space:e.avenue?.id,localDeviceId:e.deviceId,deviceIdPersistence:"persistent",endpointIdPersistence:this.internals.platform==="native"?"persistent":"ephemeral",deviceName:e.deviceName?.trim()||void 0,nativeApplicationStreamConsumer:this.internals.platform==="native"&&t?.nativeHostProtocols===true?"host":"runtime",coordinationAvenueOverride:e.avenue,coordinationGateway:{endpoint:(this.internals.endpoints??R).gateway,environment:"production",grantProvider:e.grantProvider,testingAllowInsecureLoopback:this.internals.testingAllowInsecureLoopback},transports:{iroh:i?{relayOnly:true,relayTransportPolicy:"websocketRequired",localDiscovery:false,persistenceMode:this.internals.platform==="native"?"persistent":"ephemeral",...this.internals.irohTestRelayUrl?{testRelayUrl:this.internals.irohTestRelayUrl}:{}}:this.internals.irohTestRelayUrl?{testRelayUrl:this.internals.irohTestRelayUrl,persistenceMode:this.internals.platform==="native"?"persistent":"ephemeral"}:t?.iroh??true,webrtc:t?.webrtc===true?i?{privacyMode:true,useTurn:true,useDefaultIceServers:false}:true:false,ble:t?.ble??false,moq:t?.moq??false},transportPriority:t?.priority}}async activate(e){let t={relay:this.options.transports?.relay===true,moq:this.options.transports?.moq===true,ble:this.options.transports?.ble===true,advancedFanout:e.advancedFanout===true,durableMembership:e.durableMembership===true},i=e.source,n=null,r=()=>({userId:e.principalId,token:i.token,tokenProvider:async()=>i.token,expiresAtMs:i.expiresAtMs}),o=this.runtimeOptions({avenue:e.source.avenue,grantProvider:this.controlPlane.grantProvider(e.source,{maxPeers:e.maxPeers,features:t,onSourceRenewed:async l=>{i={...i,...l},await n?.setAuth(r());}}),deviceId:e.deviceId,userId:e.principalId,deviceName:e.deviceName}),[s,{wrapAssembly:c}]=await Promise.all([this.internals.runtimeFactory(o),import('./OpenRTCShared-TKAQLONA.js')]);n=c(s,this.internals.platform==="native"?"native":"web"),await n.setAuth(r()),this.channels.attach(n,e.defaultDelivery??"reliable");try{this.usage.assertCanSpend("coordination.connection.open"),await n.devices.startSession({sessionKind:e.kind==="devices"?"app-user-device":"scoped-guest",scope:`v2:${e.kind}:${e.id}`,userId:e.principalId,localDeviceId:e.deviceId,metadata:e.deviceMetadata,autoConnectPolicy:e.autoConnect?"enabled":"disabled",presencePolicy:"online"});}catch(l){throw this.channels.detach(n),await n.advanced.runtime.shutdown().catch(()=>{}),l}return this.usage.record("coordination.connection.open"),n}async startDevices(e={}){this.assertOpen();let t=e.auth??this.options.auth;if(!t)throw new Error("[OpenRTC] devices.start() requires an auth provider.");let i=await this.deviceId(),n=await this.controlPlane.deviceCertificate(t,i),r=await this.activate({kind:"devices",id:n.principalId,source:n.source,principalId:n.principalId,deviceId:i,maxPeers:e.maxPeers,autoConnect:e.autoConnect!=="none",advancedFanout:e.advancedFanout,deviceName:e.profile?.name,deviceMetadata:ae(e.profile?.metadata)}),o;return o=new E(n.principalId,r,()=>{this.channels.detach(r),this.onClosed(o);}),this.handles.add(o),o}async joinSpace(e,t={}){this.assertOpen();let i=g(e),n=await this.controlPlane.capability("space",i,t.maxPeers,t.advancedFanout),r=String(v(n.token).principalId),o=await this.activate({kind:"space",id:i,source:n,principalId:r,deviceId:S(n),maxPeers:t.maxPeers,autoConnect:true,defaultDelivery:t.payload??"reliable",advancedFanout:t.advancedFanout}),s;return s=new K(i,o,()=>{this.channels.detach(o),this.onClosed(s);},t.payload??"reliable"),this.handles.add(s),s}async joinRoom(e,t={}){this.assertOpen();let i=g(e),n=t.membership??"ephemeral",r=t.access??"capability";if(n==="durable"&&r!=="authenticated")throw new Error("[OpenRTC] Durable room membership requires access: authenticated.");if(r==="authenticated"){let d=t.auth??this.options.auth;if(!d)throw new Error("[OpenRTC] Authenticated rooms require an auth provider.");let u=await this.deviceId(),p=await this.controlPlane.deviceCertificate(d,u,{kind:"room",id:i});n==="durable"&&await this.controlPlane.durableRoomMembership(p.source,i,"join");let h;try{h=await this.activate({kind:"room",id:i,source:p.source,principalId:p.principalId,deviceId:u,maxPeers:t.maxPeers,autoConnect:!0,durableMembership:n==="durable",advancedFanout:t.advancedFanout});}catch(b){throw n==="durable"&&await this.controlPlane.durableRoomMembership(p.source,i,"leave").catch(()=>{}),b}let y;return y=new w(i,h,()=>{this.channels.detach(h),this.onClosed(y);},n,n==="durable"?async()=>{await this.controlPlane.durableRoomMembership(p.source,i,"leave");}:void 0),this.handles.add(y),y}let o=await this.controlPlane.capability("room",i,t.maxPeers,t.advancedFanout),s=String(v(o.token).principalId),c=await this.activate({kind:"room",id:i,source:o,principalId:s,deviceId:S(o),maxPeers:t.maxPeers,autoConnect:true,advancedFanout:t.advancedFanout}),l;return l=new w(i,c,()=>{this.channels.detach(c),this.onClosed(l);},"ephemeral"),this.handles.add(l),l}async issueTicket(e,t={}){this.assertOpen();let i=g(e),n=await this.controlPlane.capability("ticket",i,t.maxPeers,t.advancedFanout),r=String(v(n.token).principalId),o=await this.activate({kind:"ticket",id:i,source:n,principalId:r,deviceId:S(n),maxPeers:t.maxPeers,autoConnect:false,advancedFanout:t.advancedFanout}),s;return s=new M(i,o,()=>{this.channels.detach(o),this.onClosed(s);},n.token),this.handles.add(s),s}async close(){if(!this.closed){this.closed=true;try{await Promise.all([...this.handles].map(e=>e.close()));}finally{this.controlPlane.dispose(),this.activations.clear();}}}};function ge(a,e){return new _(a,e)}
2
+ export{V as a,ye as b,ge as c};