openrtc 0.2.1 → 1.0.1
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/README.md +49 -0
- package/dist/{DelegatingRuntimeAdapter-BxOcVIx_.d.ts → DelegatingRuntimeAdapter-By7pziBs.d.ts} +15 -15
- package/dist/IEngineBridge-C7OT2CRv.d.ts +10 -0
- package/dist/{IpcRuntimeAdapter-U5AEH0jn.d.ts → IpcRuntimeAdapter-DymXAsNU.d.ts} +2 -2
- package/dist/auth/index.js +1 -1
- package/dist/auth/internal.js +1 -1
- package/dist/chunk-A2ENDDFR.js +2 -0
- package/dist/chunk-CK6WQV7J.js +1 -0
- package/dist/{chunk-7DN33VUQ.js → chunk-EGEA3GU2.js} +1 -1
- package/dist/chunk-KZ3KWQTO.js +1 -0
- package/dist/chunk-MA2JFAV7.js +2 -0
- package/dist/chunk-OCNLQID3.js +1 -0
- package/dist/chunk-VIPNH2BE.js +3 -0
- package/dist/device-status-nkXepu97.d.ts +560 -0
- package/dist/{framing-lxzHEuSr.d.ts → framing-BUtu0oZK.d.ts} +19 -559
- package/dist/index.d.ts +11 -7
- package/dist/index.js +2 -2
- package/dist/openrtc_bg.wasm +0 -0
- package/dist/runtime/WasmRuntimeAdapter.d.ts +3 -2
- package/dist/runtime/WasmRuntimeAdapter.js +1 -1
- package/dist/runtime/device-status.d.ts +3 -0
- package/dist/runtime/device-status.js +1 -0
- package/dist/runtime/index.d.ts +86 -83
- package/dist/runtime/index.js +1 -1
- package/dist/runtime/tauri.d.ts +4 -3
- package/dist/runtime/tauri.js +1 -1
- package/dist/transport/index.d.ts +1 -1
- package/dist/{types-D0fRvUbN.d.ts → types-CzIpGV9x.d.ts} +87 -5
- package/package.json +11 -8
- package/dist/chunk-FQETZQPW.js +0 -2
- package/dist/chunk-IUHUYHNZ.js +0 -1
- package/dist/chunk-UBEE42VU.js +0 -2
- package/dist/chunk-UPO23UMZ.js +0 -3
- package/dist/chunk-WNJE3MJF.js +0 -1
- package/env/index.d.ts +0 -64
- package/env/index.mjs +0 -230
|
@@ -20,8 +20,16 @@ interface LocalPeerSnapshot {
|
|
|
20
20
|
discoveredAtMs: number;
|
|
21
21
|
localReachable: boolean;
|
|
22
22
|
}
|
|
23
|
+
interface PlutoMoQServerCertificateHash {
|
|
24
|
+
algorithm: 'sha-256';
|
|
25
|
+
value: ArrayBuffer;
|
|
26
|
+
}
|
|
23
27
|
interface PlutoMoQConfiguration {
|
|
24
28
|
relayUrl?: string;
|
|
29
|
+
/** Relay JWT appended only at WebTransport connection time. Never include it in relayUrl. */
|
|
30
|
+
accessToken?: string;
|
|
31
|
+
/** Explicit certificate pins for self-signed development relays. */
|
|
32
|
+
serverCertificateHashes?: PlutoMoQServerCertificateHash[];
|
|
25
33
|
}
|
|
26
34
|
interface PlutoIrohConfiguration {
|
|
27
35
|
relayOnly?: boolean;
|
|
@@ -37,10 +45,6 @@ interface PlutoBleConfiguration {
|
|
|
37
45
|
enabled?: boolean;
|
|
38
46
|
/** Timeout for a single BLE connection attempt. */
|
|
39
47
|
connectTimeoutMs?: number;
|
|
40
|
-
/** Preferred retry budget for native BLE connection establishment. */
|
|
41
|
-
retryAttempts?: number;
|
|
42
|
-
/** Backoff between BLE retry attempts. */
|
|
43
|
-
retryBackoffMs?: number;
|
|
44
48
|
}
|
|
45
49
|
interface TurnCredentials {
|
|
46
50
|
iceServers?: RTCIceServer[];
|
|
@@ -162,6 +166,21 @@ interface ClientOptions {
|
|
|
162
166
|
storagePrefix?: string;
|
|
163
167
|
deviceTTL?: number;
|
|
164
168
|
deviceName?: string;
|
|
169
|
+
/**
|
|
170
|
+
* Persistence of the app-facing logical device identity. Defaults to
|
|
171
|
+
* `persistent` in browsers so a reload updates one durable device record.
|
|
172
|
+
*/
|
|
173
|
+
deviceIdPersistence?: 'persistent' | 'ephemeral';
|
|
174
|
+
/**
|
|
175
|
+
* Persistence of the Iroh endpoint secret/EndpointId. Browser runtimes
|
|
176
|
+
* default to `ephemeral` so each tab/process incarnation has an unambiguous
|
|
177
|
+
* transport identity. Native hosts may persist their endpoint explicitly.
|
|
178
|
+
*/
|
|
179
|
+
endpointIdPersistence?: 'persistent' | 'ephemeral';
|
|
180
|
+
/**
|
|
181
|
+
* @deprecated Use `deviceIdPersistence` and `endpointIdPersistence`.
|
|
182
|
+
* When supplied, this legacy option remains an explicit override for both.
|
|
183
|
+
*/
|
|
165
184
|
nodeIdPersistence?: 'persistent' | 'ephemeral';
|
|
166
185
|
secretKey?: string;
|
|
167
186
|
strictMode?: boolean;
|
|
@@ -268,6 +287,7 @@ interface PeerState {
|
|
|
268
287
|
routable?: boolean;
|
|
269
288
|
activeTransportStableId?: number | null;
|
|
270
289
|
transportGeneration?: number;
|
|
290
|
+
routeGeneration?: number;
|
|
271
291
|
activeTransport?: ProtocolName;
|
|
272
292
|
fallbackTransport?: ProtocolName | null;
|
|
273
293
|
parallelTransport?: ProtocolName | null;
|
|
@@ -293,6 +313,7 @@ interface BackendConnectionState {
|
|
|
293
313
|
readinessState?: string;
|
|
294
314
|
readinessReason?: string;
|
|
295
315
|
transportGeneration?: number;
|
|
316
|
+
routeGeneration?: number;
|
|
296
317
|
activeTransportStableId?: number | null;
|
|
297
318
|
replacementInProgress?: boolean;
|
|
298
319
|
lastLifecycleTransitionAtMs?: number;
|
|
@@ -314,6 +335,12 @@ interface NativeConnectResult {
|
|
|
314
335
|
state: string;
|
|
315
336
|
approvedScope?: string | null;
|
|
316
337
|
}
|
|
338
|
+
interface NativeConnectParams {
|
|
339
|
+
deviceId?: string | null;
|
|
340
|
+
endpointTicket: string;
|
|
341
|
+
/** Total native dial/admission budget. The host command must enforce it. */
|
|
342
|
+
timeoutMs?: number;
|
|
343
|
+
}
|
|
317
344
|
interface BackendPeerBiStream {
|
|
318
345
|
readable: ReadableStream<Uint8Array>;
|
|
319
346
|
writable: WritableStream<Uint8Array>;
|
|
@@ -353,6 +380,7 @@ interface JoinRoomOptions {
|
|
|
353
380
|
}
|
|
354
381
|
interface SignalingEnvelope {
|
|
355
382
|
name?: string;
|
|
383
|
+
appTag?: string;
|
|
356
384
|
senderId: string;
|
|
357
385
|
targetId: string;
|
|
358
386
|
senderUserId?: string;
|
|
@@ -361,6 +389,7 @@ interface SignalingEnvelope {
|
|
|
361
389
|
payload: string;
|
|
362
390
|
replyPayload?: string;
|
|
363
391
|
timestamp?: number;
|
|
392
|
+
expiresAt?: number;
|
|
364
393
|
}
|
|
365
394
|
interface SignalingSession {
|
|
366
395
|
connectionId: string;
|
|
@@ -470,6 +499,7 @@ interface DeviceStatusSnapshot extends Device {
|
|
|
470
499
|
deviceIdHint?: string;
|
|
471
500
|
activeTransportStableId?: number | null;
|
|
472
501
|
transportGeneration?: number;
|
|
502
|
+
routeGeneration?: number;
|
|
473
503
|
activeTransport?: ProtocolName;
|
|
474
504
|
parallelTransport?: ProtocolName | null;
|
|
475
505
|
availableTransports?: ProtocolName[];
|
|
@@ -481,9 +511,11 @@ interface ManagedConnectionRecord {
|
|
|
481
511
|
deviceIdHint?: string | null;
|
|
482
512
|
endpointId?: string | null;
|
|
483
513
|
transportGeneration: number;
|
|
514
|
+
routeGeneration?: number;
|
|
484
515
|
transportStableId?: number | null;
|
|
485
516
|
transportSource?: string | null;
|
|
486
517
|
lastTransportChangeAtMs: number;
|
|
518
|
+
lastRouteChangeAtMs?: number;
|
|
487
519
|
state: string;
|
|
488
520
|
statusReason?: string | null;
|
|
489
521
|
transitionCount?: number;
|
|
@@ -514,6 +546,7 @@ interface PeerSessionSnapshot {
|
|
|
514
546
|
readinessState?: string;
|
|
515
547
|
activeTransportStableId?: number | null;
|
|
516
548
|
transportGeneration?: number;
|
|
549
|
+
routeGeneration?: number;
|
|
517
550
|
activeTransport?: ProtocolName;
|
|
518
551
|
parallelTransport?: ProtocolName | null;
|
|
519
552
|
replacementPending?: boolean;
|
|
@@ -592,6 +625,7 @@ interface ExplicitFileDataSendParams {
|
|
|
592
625
|
file: File;
|
|
593
626
|
transferId: string;
|
|
594
627
|
channelId?: string;
|
|
628
|
+
receiverPlatformType?: string | null;
|
|
595
629
|
applicationCrypto?: ApplicationPayloadCrypto;
|
|
596
630
|
requireApplicationCrypto?: boolean;
|
|
597
631
|
}
|
|
@@ -603,6 +637,7 @@ interface ISignalingBackend {
|
|
|
603
637
|
stopAuthScopedActivity?(): Promise<void>;
|
|
604
638
|
getTurnCredentials(): Promise<any>;
|
|
605
639
|
updatePresence(localNodeId: string, ticketStr: string, isOnline: boolean, ttlMs: number, metadata?: string): Promise<void>;
|
|
640
|
+
refreshLivePresence?(localNodeId: string, ticketStr: string, metadata?: string): Promise<void>;
|
|
606
641
|
setOffline(localNodeId: string): Promise<void>;
|
|
607
642
|
cleanupStaleDevices(): Promise<void>;
|
|
608
643
|
searchDevices(excludeNodeId?: string): Promise<Device[]>;
|
|
@@ -648,6 +683,9 @@ interface ISignalingBackend {
|
|
|
648
683
|
reconcileNativeManagedSession?(options?: {
|
|
649
684
|
reason?: string;
|
|
650
685
|
}): Promise<unknown>;
|
|
686
|
+
notifyNetworkChange?(options?: {
|
|
687
|
+
reason?: string;
|
|
688
|
+
}): Promise<unknown>;
|
|
651
689
|
getManagedNodeId?(options?: {
|
|
652
690
|
initializeIfMissing?: boolean;
|
|
653
691
|
}): Promise<string | null>;
|
|
@@ -670,9 +708,13 @@ interface ISignalingBackend {
|
|
|
670
708
|
isConnected(nodeId: string): Promise<boolean>;
|
|
671
709
|
getConnectionStates?(): Promise<BackendConnectionState[]>;
|
|
672
710
|
onConnectionStateChange?(callback: (state: BackendConnectionState) => void): Promise<() => void> | (() => void);
|
|
711
|
+
/** @deprecated Implement file protocols over named channels, or use `openrtc-file-transfer`. */
|
|
673
712
|
sendExplicitFilePath?(connectionId: string, filePath: string, transferId?: string): Promise<string>;
|
|
713
|
+
/** @deprecated Implement file protocols over named channels, or use `openrtc-file-transfer`. */
|
|
674
714
|
sendExplicitFileData?(params: ExplicitFileDataSendParams): Promise<void>;
|
|
715
|
+
/** @deprecated Transfer history is consumer-owned application state. */
|
|
675
716
|
getTransferHistory?(limit?: number): Promise<Array<[string, unknown]>>;
|
|
717
|
+
/** @deprecated Transfer history is consumer-owned application state. */
|
|
676
718
|
deleteTransferJob?(jobId: string): Promise<void>;
|
|
677
719
|
}
|
|
678
720
|
interface CoreClientBridgeHost {
|
|
@@ -680,11 +722,25 @@ interface CoreClientBridgeHost {
|
|
|
680
722
|
admissionAlreadyPresented?: boolean;
|
|
681
723
|
approvedScope?: string | null;
|
|
682
724
|
}): Promise<{
|
|
725
|
+
id?: string | null;
|
|
726
|
+
remoteNodeId?: string | null;
|
|
727
|
+
deviceId?: string | null;
|
|
728
|
+
} | unknown>;
|
|
729
|
+
ensureManagedApplicationRoute?(options: ManagedApplicationRouteOptions): Promise<{
|
|
730
|
+
id?: string | null;
|
|
683
731
|
remoteNodeId?: string | null;
|
|
684
732
|
deviceId?: string | null;
|
|
685
733
|
} | unknown>;
|
|
686
734
|
waitForApplicationCryptoForPeer?(peerId?: string, timeoutMs?: number): Promise<unknown>;
|
|
687
735
|
hasApplicationRouteForPeer?(connectionId?: string, remoteNodeId?: string): boolean;
|
|
736
|
+
rememberRouteRepairTokenFromTicket?(ticket: string): Promise<boolean>;
|
|
737
|
+
}
|
|
738
|
+
interface ManagedApplicationRouteOptions {
|
|
739
|
+
ticket: string;
|
|
740
|
+
connectionId?: string | null;
|
|
741
|
+
remoteNodeId?: string | null;
|
|
742
|
+
expectedDeviceId?: string | null;
|
|
743
|
+
timeoutMs?: number;
|
|
688
744
|
}
|
|
689
745
|
interface SignalingOptions {
|
|
690
746
|
apiKey?: string;
|
|
@@ -750,11 +806,28 @@ interface ApplicationPayloadRouteOptions extends ApplicationPayloadReadinessOpti
|
|
|
750
806
|
}
|
|
751
807
|
interface ApplicationPayloadSendOptions extends ApplicationPayloadRouteOptions {
|
|
752
808
|
}
|
|
809
|
+
interface ApplicationRouteReadyObservation {
|
|
810
|
+
connectionId: string;
|
|
811
|
+
remoteNodeId: string;
|
|
812
|
+
activeTransport: ProtocolName;
|
|
813
|
+
parallelTransport?: ProtocolName | null;
|
|
814
|
+
reason: 'webrtc-route-ready' | 'webrtc-heartbeat-healthy' | 'webrtc-application-send' | 'base-transport-loss-preserved';
|
|
815
|
+
transportStableId?: number;
|
|
816
|
+
transportGeneration?: number;
|
|
817
|
+
routeGeneration?: number;
|
|
818
|
+
}
|
|
753
819
|
interface ConnectionOptions {
|
|
754
820
|
reliable?: boolean;
|
|
755
821
|
rtcConfig?: PlutoRTCConfiguration;
|
|
756
822
|
transportContext?: TransportContext;
|
|
757
823
|
applicationCrypto?: ApplicationPayloadCrypto;
|
|
824
|
+
/**
|
|
825
|
+
* Whether the constructor's reader/writer represent a routable base
|
|
826
|
+
* application stream. Transport-only ticket channels set this to false:
|
|
827
|
+
* their placeholder streams exist only to satisfy the compatibility object,
|
|
828
|
+
* while application bytes use named runtime channels.
|
|
829
|
+
*/
|
|
830
|
+
hasBaseApplicationStream?: boolean;
|
|
758
831
|
/** Framing used by the underlying iroh control stream. */
|
|
759
832
|
controlFrameMode?: 'typed' | 'native-main';
|
|
760
833
|
/**
|
|
@@ -767,7 +840,16 @@ interface ConnectionOptions {
|
|
|
767
840
|
onTransportStatusChange?: (status: {
|
|
768
841
|
activeTransport: ProtocolName;
|
|
769
842
|
parallelTransport?: ProtocolName | null;
|
|
843
|
+
transportStableId?: number;
|
|
844
|
+
transportGeneration?: number;
|
|
845
|
+
routeGeneration?: number;
|
|
770
846
|
}) => void;
|
|
847
|
+
/**
|
|
848
|
+
* Fired when a connection-owned application route has proven it can carry
|
|
849
|
+
* app traffic. Consumers should use this as a lifecycle signal for the same
|
|
850
|
+
* connection record, not as an independent projection source.
|
|
851
|
+
*/
|
|
852
|
+
onApplicationRouteReady?: (event: ApplicationRouteReadyObservation) => void;
|
|
771
853
|
/**
|
|
772
854
|
* Fired when the WebRTC data plane has proven a ping/pong round trip but the
|
|
773
855
|
* mandatory application crypto route is not installed yet. Connection owns
|
|
@@ -787,4 +869,4 @@ interface JoinRequest {
|
|
|
787
869
|
state: 'pending' | 'accepted' | 'rejected';
|
|
788
870
|
}
|
|
789
871
|
|
|
790
|
-
export type {
|
|
872
|
+
export type { PeerState as $, AuthMode as A, BackendPeerBiStream as B, ClientOptions as C, DiscoveryMode as D, ExplicitFileDataSendParams as E, ProtocolBaseName as F, GrantScope as G, ProtocolImplementationKind as H, ISignalingBackend as I, ProtocolLocality as J, SpaceAuthMode as K, LocalDeviceInfo as L, ManagedConnectionRecord as M, NativeManagedSessionStartResult as N, SignalingOptions as O, PeerSessionSnapshot as P, JoinRoomOptions as Q, RuntimeIdentity as R, SignalingMode as S, RoomMember as T, IncomingStreamChannelMetadata as U, RoomCreationMode as V, ScanningLoopOptions as W, ScanningLoopHandle as X, RuntimeBootstrapOptions as Y, RuntimeBootstrapResult as Z, ManagedApplicationRouteOptions as _, Device as a, PeerScope as a0, PeerHealth as a1, ChannelDescriptor as a2, JoinRequest as a3, ConnectionOptions as a4, ManagedDeviceConnectOptions as a5, PeerLifecycleStatus as a6, DeviceStatusSnapshot as b, ResolvedPeerIdentity as c, SignalingEnvelope as d, DeviceEvent as e, SignalingSession as f, SessionEvent as g, BackendPeerUniStream as h, NativeConnectParams as i, NativeConnectResult as j, BackendConnectionState as k, ConnectDeviceResult as l, ConnectDeviceHooks as m, ConnectDeviceOptions as n, ProtocolName as o, ProtocolCapability as p, ProtocolCapabilityMap as q, ApplicationPayloadCrypto as r, ApplicationCryptoStreamTools as s, SpaceTokenProvider as t, AppLimits as u, ApplicationCryptoBiStream as v, ApplicationPayloadReadinessOptions as w, ApplicationPayloadRouteOptions as x, ApplicationPayloadSendOptions as y, DevicePresenceStatus as z };
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "openrtc",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "1.0.1",
|
|
4
4
|
"private": false,
|
|
5
5
|
"type": "module",
|
|
6
6
|
"sideEffects": false,
|
|
@@ -27,8 +27,6 @@
|
|
|
27
27
|
"dist/**/*.js",
|
|
28
28
|
"dist/**/*.d.ts",
|
|
29
29
|
"dist/**/*.wasm",
|
|
30
|
-
"env/index.mjs",
|
|
31
|
-
"env/index.d.ts",
|
|
32
30
|
"LICENSE",
|
|
33
31
|
"README.md"
|
|
34
32
|
],
|
|
@@ -45,6 +43,10 @@
|
|
|
45
43
|
"types": "./dist/runtime/index.d.ts",
|
|
46
44
|
"import": "./dist/runtime/index.js"
|
|
47
45
|
},
|
|
46
|
+
"./runtime/device-status": {
|
|
47
|
+
"types": "./dist/runtime/device-status.d.ts",
|
|
48
|
+
"import": "./dist/runtime/device-status.js"
|
|
49
|
+
},
|
|
48
50
|
"./runtime/wasm": {
|
|
49
51
|
"types": "./dist/runtime/WasmRuntimeAdapter.d.ts",
|
|
50
52
|
"import": "./dist/runtime/WasmRuntimeAdapter.js"
|
|
@@ -61,29 +63,30 @@
|
|
|
61
63
|
"types": "./dist/auth/internal.d.ts",
|
|
62
64
|
"import": "./dist/auth/internal.js"
|
|
63
65
|
},
|
|
64
|
-
"./env": {
|
|
65
|
-
"types": "./env/index.d.ts",
|
|
66
|
-
"import": "./env/index.mjs"
|
|
67
|
-
},
|
|
68
66
|
"./package.json": "./package.json"
|
|
69
67
|
},
|
|
70
68
|
"scripts": {
|
|
71
69
|
"build": "tsup",
|
|
72
70
|
"build:clean": "rm -rf dist && pnpm run build",
|
|
71
|
+
"release:prepare": "pnpm run build:wasm && pnpm run build:clean",
|
|
73
72
|
"build:types": "tsc --noEmit",
|
|
74
73
|
"build:wasm": "cd ../../crates/openrtc && OPENRTC_REPO_ROOT=$(cd ../.. && pwd) && CARGO_REGISTRY_ROOT=${CARGO_HOME:-$HOME/.cargo} && RUSTUP_TOOLCHAIN=nightly RUSTFLAGS=\"-Zlocation-detail=none --remap-path-prefix=$HOME=/home --remap-path-prefix=$CARGO_REGISTRY_ROOT=/cargo --remap-path-prefix=$OPENRTC_REPO_ROOT=/openrtc\" wasm-pack build --target web --out-dir ../../packages/openrtc/wasm && rm -rf ../../packages/openrtc/wasm/.gitignore",
|
|
75
74
|
"test": "pnpm run test:deterministic && pnpm run test:emulator",
|
|
76
75
|
"test:deterministic": "OPENRTC_DETERMINISTIC_TESTS=1 vitest run tests/unit tests/contract",
|
|
77
76
|
"test:emulator": "node ../../tests/emulator/run-emulator-suite.mjs",
|
|
77
|
+
"test:avenues:openrtc": "OPENRTC_EMULATOR_TEST_FILTER='tests/emulator/AvenueRetention.emulator.test.ts tests/emulator/MagicLink.ephemeral-session.wasm-wasm.emulator.test.ts tests/emulator/MultiDeviceStress.transport-matrix.emulator.test.ts tests/emulator/NativeStandaloneAuth.parity.emulator.test.ts tests/emulator/RealOpenRtcAcceptance.native-wasm.emulator.test.ts tests/emulator/UserDevice.persistent-autoconnect.wasm-wasm.emulator.test.ts tests/emulator/WebRtcUpgrade.offer-answer.native-wasm.emulator.test.ts tests/emulator/WebRtcUpgrade.reliability.native-wasm.emulator.test.ts' pnpm run test:emulator",
|
|
78
|
+
"test:avenues:tauri": "OPENRTC_EMULATOR_TEST_FILTER='tests/emulator/DriveGrant.revoke-enforcement.desktop-wasm.emulator.test.ts tests/emulator/DriveGrant.zombie-replacement.native-wasm.emulator.test.ts tests/emulator/MagicLink.ephemeral-session.desktop-wasm.emulator.test.ts tests/emulator/ThreeStoreReconciliation.disconnect.desktop-wasm.emulator.test.ts tests/emulator/UserDevice.persistent-autoconnect.desktop-desktop.emulator.test.ts tests/emulator/UserDevice.persistent-autoconnect.desktop-wasm.emulator.test.ts tests/emulator/WebRtcUpgrade.preexisting-acl-share.desktop-desktop.emulator.test.ts tests/emulator/WebRtcUpgrade.preexisting-acl-share.desktop-wasm.emulator.test.ts' pnpm run test:emulator",
|
|
79
|
+
"test:avenues:full": "OPENRTC_EMULATOR_TRANSPORT_MATRIX_FULL=1 OPENRTC_EMULATOR_TRANSPORT_MATRIX_FIVE=1 OPENRTC_EMULATOR_TRANSPORT_MATRIX_REFRESH_FOCUS=1 OPENRTC_EMULATOR_TRANSPORT_MATRIX_FLICKER=1 OPENRTC_EMULATOR_TRANSPORT_MATRIX_RELAY_ONLY=1 OPENRTC_EMULATOR_TEST_FILTER='tests/emulator/AvenueRetention.emulator.test.ts tests/emulator/DriveGrant.revoke-enforcement.desktop-wasm.emulator.test.ts tests/emulator/DriveGrant.zombie-replacement.native-wasm.emulator.test.ts tests/emulator/MagicLink.ephemeral-session.desktop-wasm.emulator.test.ts tests/emulator/MagicLink.ephemeral-session.wasm-wasm.emulator.test.ts tests/emulator/MultiDeviceStress.transport-matrix.emulator.test.ts tests/emulator/NativeStandaloneAuth.parity.emulator.test.ts tests/emulator/RealOpenRtcAcceptance.native-wasm.emulator.test.ts tests/emulator/ThreeStoreReconciliation.disconnect.desktop-wasm.emulator.test.ts tests/emulator/UserDevice.persistent-autoconnect.desktop-desktop.emulator.test.ts tests/emulator/UserDevice.persistent-autoconnect.desktop-wasm.emulator.test.ts tests/emulator/UserDevice.persistent-autoconnect.wasm-wasm.emulator.test.ts tests/emulator/WebRtcUpgrade.offer-answer.native-wasm.emulator.test.ts tests/emulator/WebRtcUpgrade.preexisting-acl-share.desktop-desktop.emulator.test.ts tests/emulator/WebRtcUpgrade.preexisting-acl-share.desktop-wasm.emulator.test.ts tests/emulator/WebRtcUpgrade.reliability.native-wasm.emulator.test.ts' pnpm run test:emulator",
|
|
78
80
|
"test:emulator:running": "FIREBASE_AUTH_EMULATOR_HOST=127.0.0.1:9100 FIRESTORE_EMULATOR_HOST=127.0.0.1:8082 OPENRTC_FIRESTORE_HOST=127.0.0.1:8082 VITE_USE_EMULATORS=true VITE_OPENRTC_FIRESTORE_EMULATOR_HOST=127.0.0.1:8082 VITE_OPENRTC_RTDB_EMULATOR_HOST=127.0.0.1:9001 vitest run tests/emulator --no-file-parallelism --maxWorkers=1 --maxConcurrency=1",
|
|
79
81
|
"test:acceptance:native:running": "FIREBASE_AUTH_EMULATOR_HOST=127.0.0.1:9100 FIRESTORE_EMULATOR_HOST=127.0.0.1:8082 OPENRTC_FIRESTORE_HOST=127.0.0.1:8082 VITE_USE_EMULATORS=true VITE_OPENRTC_FIRESTORE_EMULATOR_HOST=127.0.0.1:8082 VITE_OPENRTC_RTDB_EMULATOR_HOST=127.0.0.1:9001 vitest run tests/emulator/RealOpenRtcAcceptance.native-wasm.emulator.test.ts --no-file-parallelism --maxWorkers=1 --maxConcurrency=1",
|
|
80
82
|
"test:live": "pnpm run build:wasm && pnpm run build && vitest run tests/live",
|
|
81
83
|
"test:live:emulator": "FIREBASE_AUTH_EMULATOR_HOST=127.0.0.1:9099 vitest run tests/live",
|
|
82
84
|
"test:watch": "vitest",
|
|
83
85
|
"coverage": "vitest run --coverage",
|
|
84
|
-
"prepublishOnly": "
|
|
86
|
+
"prepublishOnly": "pnpm run release:prepare"
|
|
85
87
|
},
|
|
86
88
|
"dependencies": {
|
|
89
|
+
"@moq/net": "0.1.9",
|
|
87
90
|
"@noble/ciphers": "^2.2.0",
|
|
88
91
|
"@noble/curves": "^1.9.0",
|
|
89
92
|
"@noble/hashes": "^1.8.0",
|
package/dist/chunk-FQETZQPW.js
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import {getApps,initializeApp}from'firebase/app';import {getFunctions,connectFunctionsEmulator,httpsCallable}from'firebase/functions';import {browserLocalPersistence,inMemoryPersistence,browserPopupRedirectResolver,initializeAuth,getAuth,connectAuthEmulator,setPersistence,onIdTokenChanged,getIdToken,signInWithCustomToken,onAuthStateChanged,signInAnonymously,signInWithEmailAndPassword,createUserWithEmailAndPassword,signOut,deleteUser,updateProfile,GoogleAuthProvider,OAuthProvider,signInWithCredential,signInWithPopup,signInWithRedirect,getRedirectResult}from'firebase/auth';function _(){return typeof window>"u"?false:!!(window.__TAURI_IPC__||window.__TAURI_INTERNALS__||window.__TAURI__||window.location.protocol==="tauri:"||window.location.hostname==="tauri.localhost")}var E=new Set;function S(e,t){E.has(e)||(E.add(e),console.warn(t));}function ie(e){return /^pk_(live|test)_[0-9a-f]{40}$/.test(e)}async function Ee(e,t){let n=`${e}:${t}`,r=new TextEncoder().encode(n),i=await crypto.subtle.digest("SHA-256",r);return Array.from(new Uint8Array(i)).map(d=>d.toString(16).padStart(2,"0")).join("")}function I(e){let t=typeof e.apiKey=="string"?e.apiKey.trim():"";if(t)return ie(t)||S(`invalid-api-key:${t.slice(0,10)}`,"[pluto-rtc] The provided `apiKey` does not match the expected format (pk_live_... or pk_test_...). Create an app at https://api.openrtc.app/developer."),`app_${t.slice(-16)}`;throw new Error("[openrtc] `apiKey` is required. Create an app at https://api.openrtc.app/developer.")}function P(e){return e.authMode?e.authMode:("apiKey"in e&&typeof e.apiKey=="string"&&e.apiKey.trim().length>0&&typeof(e.spaceKey??e.space)=="string"&&(e.spaceKey??e.space).trim().length>0||S("default-auth-mode","[pluto-rtc] `authMode` is not set; defaulting to `anonymous` for compatibility."),"anonymous")}function He(e){let t=typeof e.projectId=="string"?e.projectId.trim():"";return t||(S("default-project-id","[pluto-rtc] `projectId` is not set; defaulting to the built-in PlutoRTC Firebase project."),b)}function H(e){return e.trim().replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"")}function Le(e){let t="storagePrefix"in e&&typeof e.storagePrefix=="string"?H(e.storagePrefix):"";return t||H(I(e))||"default"}var Fe={devicesPerUser:2,maxRooms:10,maxMembersPerRoom:5,maxPersonalDevices:25},R="https://relay.cloudflare.mediaoverquic.com:443/moq",se=[{urls:"stun:stun.l.google.com:19302"},{urls:"stun:stun.cloudflare.com:3478"}],L={iceServers:se},B={relayUrl:R};var F=["iroh-relay","iroh","moq"];function ae(e){return (Array.isArray(e.urls)?e.urls:[e.urls]).some(n=>typeof n=="string"&&(n.startsWith("turn:")||n.startsWith("turns:")))}function ce(e){let n=(Array.isArray(e.urls)?e.urls:[e.urls]).filter(o=>typeof o=="string"&&!o.startsWith("stun:"));return n.length===0?null:{...e,urls:Array.isArray(e.urls)?n:n[0]}}function C(e){if(e)return e.map(t=>ce(t)).filter(t=>t!==null)}function A(e){return (e??"").trim().replace(/\/+$/,"").toLowerCase()}function W(e,t){let n=new Set(["iroh-relay","iroh","moq"]);t&&n.add("webrtc");let o=(e??F).filter(r=>n.has(r));return o.length>0?o:[...F]}function qe(e){return !!e?.transports?.webrtc}function Ke(e,t){let n=e?.transports?.webrtc||void 0;if(n)return e?.strictMode||n.privacyMode?{...n,iceServers:C(n.iceServers),iceTransportPolicy:"relay"}:n.iceTransportPolicy==="relay"&&!(Array.isArray(n.iceServers)&&n.iceServers.some(r=>ae(r)))?(t?.("[Client] Overriding relay-only ICE policy to all because no TURN servers are configured"),{...n,iceTransportPolicy:"all"}):n}var le=["iroh-lan","webrtc-lan","ble","webrtc","moq","iroh"];function k(e){let t=e.spaceKey??e.space;return {...e,...t!==void 0?{spaceKey:t}:{}}}function q(e){return {...e,iceServers:e.iceServers?e.iceServers.map(t=>({...t})):e.iceServers}}function K(e){return {...e}}function de(e){return {...e}}function ue(e){if(e)return {iroh:typeof e.iroh=="object"?de(e.iroh):e.iroh,webrtc:typeof e.webrtc=="object"?q(e.webrtc):e.webrtc,ble:typeof e.ble=="object"?{...e.ble}:e.ble,moq:typeof e.moq=="object"?K(e.moq):e.moq}}function pe(e){e.strictMode&&!e.transports&&(e.transports={iroh:{relayOnly:true}}),e.transports&&(e.transports.webrtc===true?e.transports.webrtc=q(L):e.transports.webrtc===false&&(e.transports.webrtc=void 0),e.transports.moq===true?e.transports.moq=K(B):e.transports.moq===false&&(e.transports.moq=void 0),e.transports.iroh===true?e.transports.iroh={}:e.transports.iroh===false&&(e.transports.iroh=void 0));}function ge(e){if(!e.strictMode||!e.transports)return;let t=e.transports.iroh&&typeof e.transports.iroh=="object"?e.transports.iroh:{};e.transports.iroh={...t,relayOnly:true,relayTransportPolicy:t.relayTransportPolicy??"auto",localDiscovery:false,localDiscoveryMode:void 0},e.transports.ble=void 0;let n=e.transports.webrtc;n&&typeof n=="object"&&(e.transports.webrtc={...n,privacyMode:true,lanMode:false,iceServers:C(n.iceServers)??[],iceTransportPolicy:"relay"});let o=e.transports.moq;if(o&&typeof o=="object"){let r=o.relayUrl?.trim();if(!r||A(r)===A(R))throw new Error("[OpenRTC] strictMode requires transports.moq.relayUrl to point at a self-hosted MoQ relay; the default public relay is not allowed.");e.transports.moq={...o,relayUrl:r};}}function Qe(e){let t=k(e),n=I(t),o=P(t),r={strictMode:false,disableIrohFallback:false,transportPriority:[...le],...t,authMode:o,transports:ue(t.transports)};pe(r),ge(r),r.strictMode&&(r.transportPriority=W(t.transportPriority,!!r.transports?.webrtc));let i=j(r),s=(r.discoveryMode??"space")==="space"?"client-open":"client-auth";return {appTag:n,authMode:o,configuredPersistenceMode:i,options:r,roomCreationMode:s}}function j(e){let t=e.transports?.iroh;return e.nodeIdPersistence??(typeof t=="object"?t.persistenceMode:void 0)??"persistent"}function Ve(e){return "options"in e&&"configuredPersistenceMode"in e?{apiKey:e.options.apiKey,authMode:P(e.options),projectId:e.options.projectId,storagePrefix:e.options.storagePrefix,nodeIdPersistence:e.configuredPersistenceMode}:{apiKey:e.apiKey,authMode:P(e),projectId:e.projectId,storagePrefix:e.storagePrefix,nodeIdPersistence:j(e)}}function Je(e,t){t&&(e.transports={...e.transports||{},...t});}var b="pluto-rtc-prod",z={apiKey:"AIzaSyA62Krj-7ZYFT5xjrTUq7mXana41Ahj_mM",authDomain:"api.openrtc.app",projectId:b,storageBucket:"pluto-rtc-prod.firebasestorage.app",messagingSenderId:"607066575224",appId:"1:607066575224:web:ed3f51825ba228db92b88d"};function Xe(e){let t=k(e),n=typeof t.projectId=="string"&&t.projectId.trim()?t.projectId.trim():b;return {...t,projectId:n}}function $(e){return new Promise(t=>setTimeout(t,e))}function tt(e){let t=new Uint8Array(e.byteLength);return t.set(e),t}function nt(e){let t=e.reduce((r,i)=>r+i.byteLength,0),n=new Uint8Array(t),o=0;for(let r of e)n.set(r,o),o+=r.byteLength;return n}function rt(e,t,n){let o=t*Math.pow(2,Math.max(0,e-1));return Math.min(n,o)}function ot(e){try{let t=e;return !!t&&!!t.send&&typeof t.send.getWriter=="function"&&!!t.recv&&typeof t.recv.getReader=="function"}catch{return false}}function it(e,t){let n=e;if(!n)return null;try{let o=n.send,r=n.recv;if(!o||typeof o.getWriter!="function"||!r||typeof r.getReader!="function")return null;let i=typeof n.endpoint_id=="string"&&n.endpoint_id.trim().length>0?n.endpoint_id:t;return {send:o,recv:r,endpoint_id:i}}catch{return null}}function st(e,t){let n={send:e.send,recv:t,endpoint_id:typeof e.endpoint_id=="string"?e.endpoint_id:""};return e?.applicationCryptoWrapped===true&&(n.applicationCryptoWrapped=true),n}async function at(e,t){if(!e)return false;try{let n=e.send?.getWriter?.();if(n)try{await n.close();}catch{}finally{try{n.releaseLock();}catch{}}}catch{}try{let n=e.recv?.getReader?.();if(n)try{await n.cancel(t);}catch{}finally{try{n.releaseLock();}catch{}}}catch{}return true}function ct(e,t,n={}){let o=n.context??"prependBytesToReader",r=n.traceId,i=t.byteLength===0,s=n.pendingRead??null,l=a=>n.release?.(a),d=(a,p)=>n.log?.(a,p);return new ReadableStream({async pull(a){if(!i){i=true,a.enqueue(t);return}if(s){let u=s;s=null;let g;try{g=await u;}catch(y){a.error(y),l("pending-read-error"),d("prepend-bytes:pending-read-error",{context:o,traceId:r||null,error:y?.message||String(y)});return}if(g.done){a.close(),l("pending-done");return}g.value&&a.enqueue(g.value);return}let p;try{p=await e.read();}catch(u){a.error(u),l("read-error"),d("prepend-bytes:read-error",{context:o,traceId:r||null,error:u?.message||String(u)});return}let{done:T,value:v}=p;if(T){a.close(),l("done");return}v&&a.enqueue(v);},async cancel(a){l("cancel");}})}async function lt(e,t){let n=e.read(),o=t-Date.now();if(o<=0)return {status:"timeout",pendingRead:n};let r=Symbol("probe-timeout"),i,s=new Promise(l=>{i=setTimeout(()=>l(r),o);});try{let l=await Promise.race([n,s]);if(l===r)return {status:"timeout",pendingRead:n};let{done:d,value:a}=l;return d?{status:"done"}:{status:"data",value:a&&a.byteLength>0?new Uint8Array(a):new Uint8Array(0)}}finally{i&&clearTimeout(i);}}function G(e,t,n){let o;return new Promise((r,i)=>{o=setTimeout(()=>{if(o=void 0,typeof n=="function"){i(n());return}let s=n?`${n} timed out`:"timeout";i(new Error(`${s} after ${t}ms`));},t),e.then(s=>{o!==void 0&&clearTimeout(o),r(s);},s=>{o!==void 0&&clearTimeout(o),i(s);});})}var X="pluto-rtc-auth",D=null;function Oe(){if(typeof globalThis<"u"&&globalThis.__OPENRTC_DEBUG__===true)return true;if(typeof localStorage<"u")try{return localStorage.getItem("openrtc:debug")==="1"}catch{return false}return false}function c(e,t){if(Oe()){if(typeof t>"u"){console.log(e);return}console.log(e,t);}}function Ct(e){D=e;}function Me(){return _()}function re(){return typeof navigator>"u"?false:/iPhone|iPad|iPod|Android/i.test(navigator.userAgent||"")}function ee(){return Me()&&re()}function m(e,t,n){return G(e,t,()=>new Error(`${n} timeout after ${t}ms`))}function te(e){let t="0123456789ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvwxyz-._",n=new Uint8Array(e);window.crypto.getRandomValues(n);let o="";for(let r=0;r<e;r+=1)o+=t[n[r]%t.length];return o}async function ne(e){let n=new TextEncoder().encode(e),o=await crypto.subtle.digest("SHA-256",n);return Array.from(new Uint8Array(o)).map(i=>i.toString(16).padStart(2,"0")).join("")}var N=class{constructor(){this.redirectResultPromise=null;this.redirectResultConsumed=false;this.lastRelayedToken=null;this.lastRelayedRefreshToken=null;this.desktopTokenRefreshIntervalId=null;let t=getApps().find(r=>r.name===X);this.app=t||initializeApp(z,X);let n=re(),o=ee();if(n)try{let r=o?{persistence:[browserLocalPersistence,inMemoryPersistence]}:{persistence:[browserLocalPersistence,inMemoryPersistence],popupRedirectResolver:browserPopupRedirectResolver};this.auth=initializeAuth(this.app,r),c("[PLUTO-RTC][AUTH-HOST] Using mobile-safe Firebase auth initialization",{appName:this.app.name,persistence:"browserLocalPersistence->inMemoryPersistence",redirectResolver:o?"disabled-for-tauri-mobile":"browserPopupRedirectResolver",tauriMobile:o});}catch{this.auth=getAuth(this.app),console.warn("[PLUTO-RTC][AUTH-HOST] Mobile-safe auth initialization unavailable; falling back to default getAuth");}else this.auth=getAuth(this.app);this.functions=getFunctions(this.app);try{let r=typeof globalThis<"u"?String(globalThis.__OPENRTC_AUTH_EMULATOR_HOST__??"").trim():"",i=typeof globalThis<"u"?String(globalThis.__OPENRTC_FUNCTIONS_EMULATOR_HOST__??"").trim():"",s=typeof import.meta<"u"?import.meta.env:null;if(!!r||!!i||!!s&&String(s.VITE_USE_EMULATORS)==="true"&&(s.DEV||String(s.VITE_E2E)==="true")){let d=String(s?.VITE_OPENRTC_EMULATOR_HOST??"127.0.0.1").trim()||"127.0.0.1",[a,p]=r.split(":"),[T,v]=i.split(":"),u=(a??"").trim()||d,g=(T??"").trim()||d,y=Number(p??s?.VITE_OPENRTC_AUTH_EMULATOR_PORT??9100),oe=Number(v??s?.VITE_OPENRTC_FUNCTIONS_EMULATOR_PORT??5002);try{connectAuthEmulator(this.auth,`http://${u}:${y}`,{disableWarnings:!0});}catch{}try{connectFunctionsEmulator(this.functions,g,oe);}catch{}}}catch{}n?this.persistenceReady=Promise.resolve():this.persistenceReady=setPersistence(this.auth,browserLocalPersistence).catch(r=>{console.warn("[PLUTO-RTC][AUTH-HOST] Failed to set auth persistence",{message:r?.message});}),c("[PLUTO-RTC][AUTH-HOST] Initialized auth host",{appName:this.app.name,mobileSafeAuth:n}),onIdTokenChanged(this.auth,r=>{c("[PLUTO-RTC][AUTH-HOST] Firebase ID token changed",{hasUser:!!r,uid:r?.uid,providerDataCount:r?.providerData?.length||0}),this.syncDesktopAuthToken(r);}),this.desktopTokenRefreshIntervalId||(this.desktopTokenRefreshIntervalId=setInterval(()=>{this.syncDesktopAuthToken(this.auth.currentUser,true);},600*1e3));}async syncDesktopAuthToken(t,n=false){if(!D)return;let o=t?await getIdToken(t,n).catch(()=>null):null,r=t?t.refreshToken??null:null;if(o===this.lastRelayedToken&&r===this.lastRelayedRefreshToken)return;this.lastRelayedToken=o,this.lastRelayedRefreshToken=r;let i=await Promise.allSettled([Promise.resolve(D({authToken:o,refreshToken:r}))]);i[0]?.status==="rejected"&&console.warn("[PLUTO-RTC][AUTH-HOST] Failed to relay auth token to desktop backend",{message:i[0].reason?.message});}getApp(){return this.app}getCurrentUser(){return this.auth.currentUser}getAuth(){return this.auth}onAuthStateChanged(t){return c("[PLUTO-RTC][AUTH-HOST] onAuthStateChanged listener registered (via onIdTokenChanged)"),onIdTokenChanged(this.auth,t)}onIdTokenChanged(t){return c("[PLUTO-RTC][AUTH-HOST] onIdTokenChanged listener registered"),onIdTokenChanged(this.auth,t)}async getIdToken(t){return this.auth.currentUser?getIdToken(this.auth.currentUser,t?.forceRefresh??true):null}async checkForSSOToken(){if(typeof window>"u")return;let t=new URLSearchParams(window.location.search),n=new URLSearchParams(window.location.hash.startsWith("#")?window.location.hash.slice(1):window.location.hash),o=t.get("token")||n.get("token")||(t.get("custom_token")==="true"||n.get("custom_token")==="true"?t.get("id_token")||n.get("id_token"):null);if(o)try{await this.persistenceReady,await signInWithCustomToken(this.auth,o),window.history.replaceState({},document.title,window.location.pathname);}catch(r){console.error("[PLUTO-RTC][AUTH-HOST] SSO sign-in failed:",r);}}async signInWithCustomTokenValue(t){return await this.persistenceReady,(await signInWithCustomToken(this.auth,t)).user}async signInWithPluto(t){if(typeof window>"u")throw new Error("Pluto SSO requires a browser environment.");let n=t?.redirectUri||window.location.href,o=t?.authorizeBaseUrl||"https://pluto.openrtc.app/sso/authorize",r=new URL(o);r.searchParams.set("redirect_uri",n),window.location.assign(r.toString());}async waitForAuth(){if(await this.persistenceReady,!this.auth.currentUser)return new Promise(t=>{let n=onAuthStateChanged(this.auth,o=>{o&&(n(),t());});})}async signInAnonymously(){await signInAnonymously(this.auth);}async signIn(t,n){return (await signInWithEmailAndPassword(this.auth,t,n)).user}async signUp(t,n){return (await createUserWithEmailAndPassword(this.auth,t,n)).user}async signOut(){await signOut(this.auth);}async deleteAccount(){if(!this.auth.currentUser)throw new Error("No user signed in");await deleteUser(this.auth.currentUser);}async signInWithCredential(t){let n=Date.now();if(c("[PLUTO-RTC][AUTH-HOST] signInWithCredential start",{callbackId:t.callbackId,provider:t.provider,hasIdToken:!!t.idToken,hasAccessToken:!!t.accessToken,hasNonce:!!t.nonce}),t.isCustomToken){c("[PLUTO-RTC][AUTH-HOST] signInWithCredential: custom token detected, using signInWithCustomToken");try{if(ee())c("[PLUTO-RTC][AUTH-HOST] Skipping authStateReady before custom token sign-in on Tauri mobile",{callbackId:t.callbackId});else {c("[PLUTO-RTC][AUTH-HOST] Awaiting authStateReady...");try{await m(this.auth.authStateReady(),5e3,"authStateReady"),c("[PLUTO-RTC][AUTH-HOST] Auth state ready, signing in with custom token...");}catch(s){console.warn("[PLUTO-RTC][AUTH-HOST] authStateReady did not resolve in time; continuing custom token sign-in",{callbackId:t.callbackId,message:s?.message});}}let i;try{i=await m(signInWithCustomToken(this.auth,t.idToken),25e3,"signInWithCustomToken (custom token path)");}catch(s){console.warn("[PLUTO-RTC][AUTH-HOST] First custom token sign-in attempt failed; retrying once",{callbackId:t.callbackId,message:s?.message,code:s?.code}),await $(250),i=await m(signInWithCustomToken(this.auth,t.idToken),25e3,"signInWithCustomToken (custom token path retry)");}if(c("[PLUTO-RTC][AUTH-HOST] signInWithCustomToken success",{callbackId:t.callbackId,provider:t.provider,uid:i.user?.uid,elapsedMs:Date.now()-n}),i.user&&(t.displayName||t.photoURL))try{await updateProfile(i.user,{displayName:t.displayName||i.user.displayName||void 0,photoURL:t.photoURL||i.user.photoURL||void 0});}catch(s){console.warn("[PLUTO-RTC][AUTH-HOST] Failed to update custom-token user profile",{callbackId:t.callbackId,message:s?.message});}return i.user}catch(r){throw console.error("[PLUTO-RTC][AUTH-HOST] signInWithCustomToken failed",{callbackId:t.callbackId,error:r?.message,code:r?.code,stack:r?.stack,elapsedMs:Date.now()-n}),r}}let o;t.provider==="google"?o=GoogleAuthProvider.credential(t.idToken,t.accessToken):o=new OAuthProvider("apple.com").credential({idToken:t.idToken,rawNonce:t.nonce,accessToken:t.accessToken});try{let r=await m(signInWithCredential(this.auth,o),1e4,"firebase signInWithCredential");return c("[PLUTO-RTC][AUTH-HOST] signInWithCredential success",{callbackId:t.callbackId,provider:t.provider,uid:r.user?.uid,elapsedMs:Date.now()-n}),r.user}catch(r){console.warn("[PLUTO-RTC][AUTH-HOST] signInWithCredential primary path failed; trying custom token fallback",{callbackId:t.callbackId,provider:t.provider,elapsedMs:Date.now()-n,code:r?.code,message:r?.message});let i=await m(this.mintSessionTokenFromProviderToken(t),15e3,"mintSessionTokenFromProviderToken"),s=await m(signInWithCustomToken(this.auth,i),15e3,"signInWithCustomToken");return c("[PLUTO-RTC][AUTH-HOST] signInWithCustomToken fallback success",{callbackId:t.callbackId,provider:t.provider,uid:s.user?.uid,elapsedMs:Date.now()-n}),s.user}}async mintSessionTokenFromProviderToken(t){let n=httpsCallable(this.functions,"mintSessionToken");c("[PLUTO-RTC][AUTH-HOST] mintSessionToken fallback request start",{provider:t.provider,hasIdToken:!!t.idToken,hasNonce:!!t.nonce});let r=(await n({provider:t.provider,idToken:t.idToken,nonce:t.nonce})).data?.token;if(!r)throw new Error("mintSessionToken did not return a token for provider exchange");return c("[PLUTO-RTC][AUTH-HOST] mintSessionToken fallback request success",{provider:t.provider}),r}async signInWithPopup(t){if(t==="google"){let i=new GoogleAuthProvider;i.addScope("email"),i.addScope("profile"),i.setCustomParameters({prompt:"select_account"});let s=await signInWithPopup(this.auth,i);return {idToken:await getIdToken(s.user,true),refreshToken:s.user.refreshToken}}let n=new OAuthProvider("apple.com");n.addScope("email"),n.addScope("name");let o=te(32);typeof sessionStorage<"u"&&sessionStorage.setItem("apple_auth_nonce",o),n.setCustomParameters({nonce:await ne(o)});let r=await signInWithPopup(this.auth,n);return {idToken:await getIdToken(r.user,true),refreshToken:r.user.refreshToken}}async signInWithRedirect(t,n){if(t==="google"){let i=new GoogleAuthProvider;i.addScope("email"),i.addScope("profile"),i.setCustomParameters({prompt:"select_account"}),await signInWithRedirect(this.auth,i);return}let o=new OAuthProvider("apple.com");o.addScope("email"),o.addScope("name");let r=n?.nonce||te(32);typeof sessionStorage<"u"&&sessionStorage.setItem("apple_auth_nonce",r),o.setCustomParameters({nonce:await ne(r)}),await signInWithRedirect(this.auth,o);}async consumeRedirectResult(){return this.redirectResultConsumed?(c("[PLUTO-RTC][AUTH-HOST] consumeRedirectResult skipped (already consumed)"),null):this.redirectResultPromise?this.redirectResultPromise:(this.redirectResultPromise=(async()=>{try{c("[PLUTO-RTC][AUTH-HOST] consumeRedirectResult start");let t=await getRedirectResult(this.auth);if(!t)return c("[PLUTO-RTC][AUTH-HOST] consumeRedirectResult: no redirect result"),{fromRedirect:!1,user:null};this.redirectResultConsumed=!0;let n=await getIdToken(t.user,!0).catch(()=>null),o=t.providerId||t.user.providerData?.[0]?.providerId||null;return c("[PLUTO-RTC][AUTH-HOST] consumeRedirectResult success",{uid:t.user.uid,providerId:o,hasIdToken:!!n}),{fromRedirect:!0,user:t.user,providerId:o,idToken:n}}finally{this.redirectResultPromise=null;}})(),this.redirectResultPromise)}async startGoogleSignIn(){await this.signInWithRedirect("google");}async startAppleSignIn(){await this.signInWithRedirect("apple");}async mintSessionToken(){let o=(await httpsCallable(this.functions,"mintSessionToken")()).data;if(!o?.token)throw new Error("mintSessionToken did not return a token");return o.token}},M=null;function De(){return M||(M=new N),M}var At=new Proxy({},{get(e,t,n){let o=De(),r=o[t];return typeof r=="function"?r.bind(o):r}});
|
|
2
|
-
export{lt as A,G as B,Ct as C,De as D,At as E,_ as a,Ee as b,I as c,P as d,He as e,Le as f,Fe as g,se as h,L as i,B as j,qe as k,Ke as l,k as m,Qe as n,Ve as o,Je as p,Xe as q,$ as r,tt as s,nt as t,rt as u,ot as v,it as w,st as x,at as y,ct as z};
|
package/dist/chunk-IUHUYHNZ.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import {z,y}from'./chunk-WNJE3MJF.js';var n=class extends z{constructor(e){super(new y(e));}setWasmClient(e){this.unwrap().setWasmClient(e);}};export{n as a};
|
package/dist/chunk-UBEE42VU.js
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import {q as q$1,z,v as v$1,y,u as u$1,j,d,x,c,i,l,m,n,o,p}from'./chunk-WNJE3MJF.js';import {u,r,b,a,B as B$1,D}from'./chunk-FQETZQPW.js';function te(d){let e=String(d?.message??d??"").toLowerCase();return e?e.includes("__tauri_internals__")||e.includes("window is not defined")||e.includes("cannot read properties of undefined")?"runtime-unavailable":e.includes("timeout after")?"timeout":e.includes("not found")||e.includes("not allowed")||e.includes("unknown command")||e.includes("plugin not found")||e.includes("plugin:openrtc-tauri-plugin")||e.includes("plugin:openrtc")?"command-unavailable":"unknown":"unknown"}function B(d){return te(d)==="command-unavailable"}function S(d,e="native runtime"){if(!d||typeof d!="object")throw new Error(`[openrtc] ${e} requires a valid IPC bridge object.`);if(typeof d.invoke!="function")throw new Error(`[openrtc] ${e} IPC bridge is missing invoke(command, args).`);if(typeof d.listen!="function")throw new Error(`[openrtc] ${e} IPC bridge is missing listen(event, handler).`);return d}var U=null;async function ie(){return U||(U=(async()=>{let d="openrtc-tauri",e="../../../tauri/src/runtime/ipc";try{return await import(d)}catch(t){try{return await import(e)}catch(i){let n=new Error("[openrtc] Native support now lives in the first-party `openrtc-tauri` package. Install `openrtc-tauri` (and `@tauri-apps/api`) or pass an explicit IPC bridge to OpenRTC.native(...).");throw n.cause={packageError:t,workspaceError:i},n}}})()),U}function J(){let d=null,e=async()=>(d||(d=ie().then(t=>S(t.createTauriIpcBridge(),"openrtc-tauri"))),d);return {async invoke(t,i){return (await e()).invoke(t,i)},async listen(t,i){return (await e()).listen(t,i)},async isAvailable(){try{let t=await e();return typeof t.isAvailable=="function"?!!await t.isAvailable():!0}catch{return false}}}}var ne="relay-only endpoint ticket unavailable",ae=12e3,re=250,se=1500;function oe(d){return String(d?.message??d??"").toLowerCase().includes(ne)}async function q(d,e={}){let t=e.windowMs??ae,i=e.minDelayMs??re,n=e.maxDelayMs??se,a=Date.now(),s=0,r$1=null;for(;e.isActive?.()??true;){s+=1;try{return await d()}catch(l){if(r$1=l,!oe(l))throw l;let o=Date.now()-a;if(o>=t)throw l;let c=Math.min(u(s,i,n),Math.max(0,t-o));c>0&&await r(c);}}throw r$1||new Error("endpoint ticket minting stopped before a ticket was available")}function X(d){let e=d?.split(".")[1];if(!e)return null;try{let t=e.replace(/-/g,"+").replace(/_/g,"/"),i=(4-t.length%4)%4,n=atob(t+"=".repeat(i)),a=JSON.parse(n);return a&&typeof a=="object"&&!Array.isArray(a)?a:null}catch{return null}}function Q(d,e){let t=d?.[e];return typeof t=="string"&&t.trim()?t.trim():null}function Z(d,e){return Q(d,"namespaceId")===e||Q(d,"appTag")===`space::${e}`}var v=class v{constructor(e){this.subscriptionNonce=0;this.lastSyncedAuthToken=null;this.cachedLocalDeviceId=null;this.cachedLocalDeviceName=null;this.tauriCoreAvailability=null;this.tauriCoreAvailabilityValue=null;this.tauriCoreAvailabilityCheckedAtMs=0;this.authSyncInFlight=null;this.nativeRuntimeCapabilitiesSyncInFlight=null;this.lastNativeAuthSyncAtMs=0;this.hasLoggedMissingAuthForDevices=false;this.runtimeCapabilities=v$1(null,false);this.nativeRtdbPresenceScope=null;this.nativeRtdbTicketVersion=0;this.lastNativePresenceTicket=null;this.nativeRtdbPresenceDisabledForSession=false;this.fallback=new y(e),this.app=this.fallback.app,this.auth=this.fallback.auth,this.appTag=this.fallback.tag,this.options=this.fallback.getResolvedOptions(),this.transportOptions=e.transports,this.strictMode=e.strictMode===true,this.turnCredentialsProvider=e.turnCredentialsProvider,this.allowWasmFallback=e.allowWasmFallback??false,this.ipcBridge=S(e.ipcBridge??J(),"NativeIpcBridge"),this.runtimeCapabilities=v$1(null,this.allowWasmFallback),this.syncNativeRuntimeCapabilities("constructor");}get currentUser(){return this.fallback.currentUser}get tag(){return this.fallback.tag}getRuntimeCapabilities(){let e=u$1(this.runtimeCapabilities);return e.fallback.wasm=this.allowWasmFallback,e}setWasmClient(e){if(!this.allowWasmFallback){let t="[NativeIpcBridge][NATIVE-GUARD] Refusing WasmClient attachment because native IPC is authoritative and WASM fallback is disabled.";throw console.error(t,{capabilities:this.getRuntimeCapabilities()}),new Error(t)}this.fallback.setWasmClient(e);}onAuthChange(e){return this.fallback.onAuthChange(e)}checkForSSOToken(){return this.fallback.checkForSSOToken()}waitForAuth(){return this.fallback.waitForAuth()}signInAnonymously(){return this.fallback.signInAnonymously()}getTurnCredentials(){return this.fallback.getTurnCredentials()}cleanupStaleDevices(){return this.fallback.cleanupStaleDevices()}sendMessage(e,t,i,n){return this.fallback.sendMessage(e,t,i,n)}pollMessages(e){return this.fallback.pollMessages(e)}createSession(e){return this.fallback.createSession(e)}updateSession(e,t){return this.fallback.updateSession(e,t)}async openPeerBi(e,t){return await this.canUseTauriIpc()?this.openPeerBiViaIpc("open_peer_bi_stream",{peerId:e,timeoutMs:t??null}):this.fallback.openPeerBi(e,t)}async openPeerBiTransportOnly(e,t){return await this.canUseTauriIpc()?this.openPeerBiViaIpc("open_peer_bi_transport_only_stream",{peerId:e,timeoutMs:t??null},{fallbackCommand:"open_peer_bi_stream"}):this.fallback.openPeerBiTransportOnly(e,t)}async openPeerNativeBi(e,t,i){return await this.canUseTauriIpc()?this.openPeerBiViaIpc("open_peer_native_bi_stream",{peerId:e,label:t,timeoutMs:i??null},{fallbackCommand:"open_peer_bi_stream",fallbackArgs:{peerId:e,timeoutMs:i??null}}):this.fallback.openPeerNativeBi(e,t,i)}async incoming_streams(){if(!await this.canUseTauriIpc()){let a=this.fallback;if(typeof a.incoming_streams=="function")return a.incoming_streams();throw new Error("Native incoming stream bridge is unavailable")}let e=`native-incoming-${Date.now()}-${++this.subscriptionNonce}`,t=null,i=false,n=async()=>{i=true;let a=t;t=null,await Promise.allSettled([a?Promise.resolve(a()):Promise.resolve(),this.invokeIpc("stop_rtc_subscription",{requestId:e},{timeoutMs:null}).catch(()=>{})]);};return new ReadableStream({start:async a=>{try{t=await this.listenIpc("openrtc://peer-bi-stream/incoming",s=>{if(i)return;let r=s.payload;if((typeof r?.requestId=="string"?r.requestId:typeof r?.request_id=="string"?r.request_id:"")!==e)return;let o=typeof r?.streamId=="string"?r.streamId.trim():typeof r?.stream_id=="string"?r.stream_id.trim():"";if(!o)return;let c=typeof r?.remoteNodeId=="string"?r.remoteNodeId.trim():typeof r?.remote_node_id=="string"?r.remote_node_id.trim():"",u=this.peerBiStreamFromId(o,{startReadAfterListeners:!0});a.enqueue({type:"bi",stream:{send:u.writable,recv:u.readable,endpoint_id:c},endpointId:c,protocolHint:"unknown",channel:null});}),await this.invokeIpc("start_incoming_peer_bi_streams",{requestId:e},{timeoutMs:null});}catch(s){i=true,a.error(s),await n();}},cancel:async()=>{await n();}})}openPeerUni(e,t){return this.fallback.openPeerUni(e,t)}isConnected(e){return this.fallback.isConnected(e)}getAuthContext(){return this.fallback.getAuthContext()}resolveNativeAuthScopedUserId(e){return this.currentUser?.id??this.getAuthContext()?.userId??e??null}usesAnonymousSpaceMode(){return this.options.authMode==="anonymous"&&typeof this.options.spaceKey=="string"&&this.options.spaceKey.trim().length>0}requiresNativeAuthToken(){return !this.usesAnonymousSpaceMode()||typeof this.options.spaceTokenProvider=="function"}async nativeAuthTokenMatchesExpectedScope(e){if(!this.usesAnonymousSpaceMode())return true;let t=typeof this.options.apiKey=="string"?this.options.apiKey.trim():"",i=typeof this.options.spaceKey=="string"?this.options.spaceKey.trim():"";if(!t||!i)return true;let n=await b(t,i).catch(()=>null);return n?Z(X(e),n):true}resolveNativeSignalingUserId(e){return this.usesAnonymousSpaceMode()?(typeof e=="string"?e.trim():"")||this.options.spaceKey?.trim()||null:this.resolveNativeAuthScopedUserId(e)}getCurrentUserId(){return this.resolveNativeSignalingUserId(this.fallback.getCurrentUserIdForScope())}nativeAuthWaitMs(){return this.requiresNativeAuthToken()?v.AUTH_REQUIRED_WAIT_MS:0}resolveWebLogicalDeviceId(){return this.fallback.getResolvedWebLogicalDeviceId()}normalizeDevice(e,t){return this.fallback.normalizeDeviceRecord(e,t)}matchesTag(e){return this.fallback.matchesLegacyOrCurrentTag(e)}matchesNativeStatusTag(e){let t=j(e);return this.matchesTag(t)}async buildNativeRtdbScope(e){return this.fallback.resolveRtdbScope(e??void 0)}async syncNativeRtdbPresenceTicket(e){if(this.nativeRtdbPresenceDisabledForSession)return;let t=await this.buildNativeRtdbScope(),i=await this.resolveLocalDeviceId();if(!(!t||!i))try{if(!this.fallback.rtdbPresence||!this.nativeRtdbPresenceScope){await this.fallback.registerRtdbPresence(t,i,this.nativeRtdbTicketVersion),this.nativeRtdbPresenceScope=t,this.lastNativePresenceTicket=e,d("[NativeIpcBridge][RTDB] registered native presence ticket state",{deviceId:i,ticketVersion:this.nativeRtdbTicketVersion,ticketFingerprint:x(e)});return}let a=this.lastNativePresenceTicket!==e;(this.nativeRtdbPresenceScope.kind!==t.kind||t.kind==="user-scoped"&&this.nativeRtdbPresenceScope.kind==="user-scoped"&&(this.nativeRtdbPresenceScope.appTag!==t.appTag||this.nativeRtdbPresenceScope.userId!==t.userId)||t.kind==="space"&&this.nativeRtdbPresenceScope.kind==="space"&&this.nativeRtdbPresenceScope.namespaceId!==t.namespaceId)&&(await this.fallback.registerRtdbPresence(t,i,this.nativeRtdbTicketVersion),this.nativeRtdbPresenceScope=t),a&&(this.nativeRtdbTicketVersion+=1,await this.fallback.rtdbPresence?.bumpTicketVersion(t,i,this.nativeRtdbTicketVersion),d("[NativeIpcBridge][RTDB] bumped native ticketVersion after managed ticket change",{deviceId:i,ticketVersion:this.nativeRtdbTicketVersion,ticketFingerprint:x(e)})),this.nativeRtdbPresenceScope=t,this.lastNativePresenceTicket=e;}catch(n){this.nativeRtdbPresenceDisabledForSession=true,this.nativeRtdbPresenceScope=null,this.lastNativePresenceTicket=null,console.warn("[NativeIpcBridge][RTDB] native RTDB presence mirror unavailable; continuing with Firestore/native presence.",n);}}async markNativeRtdbOffline(){if(!this.nativeRtdbPresenceScope)return;let e=await this.resolveLocalDeviceId();if(e)try{await this.fallback.rtdbPresence?.markOffline(this.nativeRtdbPresenceScope,e,this.nativeRtdbTicketVersion),d("[NativeIpcBridge][RTDB] marked native presence offline",{deviceId:e,ticketVersion:this.nativeRtdbTicketVersion});}catch(t){console.warn("[NativeIpcBridge][RTDB] failed to mark native presence offline:",t);}finally{this.nativeRtdbPresenceScope=null,this.nativeRtdbTicketVersion=0,this.lastNativePresenceTicket=null,this.nativeRtdbPresenceDisabledForSession=false;}}normalizeNativeIceServer(e){let t=e.urls,i=Array.isArray(t)?t.filter(n=>typeof n=="string"&&n.trim().length>0):typeof t=="string"&&t.trim().length>0?[t]:[];return i.length===0?null:{urls:i,username:typeof e.username=="string"&&e.username.trim().length>0?e.username:void 0,credential:typeof e.credential=="string"&&e.credential.trim().length>0?e.credential:void 0}}filterNativeStunServers(e){return e.map(t=>({...t,urls:t.urls.filter(i=>!i.startsWith("stun:"))})).filter(t=>t.urls.length>0)}nativeIceServerHasTurnUrl(e){return e.urls.some(t=>t.startsWith("turn:")||t.startsWith("turns:"))}async loadNativeTurnIceServers(){if(typeof this.turnCredentialsProvider!="function")return [];let e=await this.turnCredentialsProvider().catch(t=>(console.warn("[NativeIpcBridge] TURN credential provider failed:",t),null));return !e||!Array.isArray(e.iceServers)?[]:e.iceServers.map(t=>this.normalizeNativeIceServer(t)).filter(t=>!!t)}async buildNativeTransportConfigPayload(){let e=this.transportOptions;if(!e&&!this.strictMode)return null;let t=null;if(!this.strictMode&&e?.iroh&&typeof e.iroh=="object"){let o=e.iroh;o.localDiscovery===true&&(t={enabled:true,advertise:o.localDiscoveryMode!=="passive"});}let i=null;if(e?.webrtc===true||e?.webrtc&&typeof e.webrtc=="object"){let o=e.webrtc===true?null:e.webrtc,c=Array.isArray(o?.iceServers)?o.iceServers.map(y=>this.normalizeNativeIceServer(y)).filter(y=>!!y):[],u=this.strictMode||o?.privacyMode===true;(this.strictMode||o?.privacyMode===true||o?.useTurn===true)&&(c=[...c,...await this.loadNativeTurnIceServers()]),u&&(c=this.filterNativeStunServers(c));let m=c.some(y=>this.nativeIceServerHasTurnUrl(y)),p=u&&m;u&&!m&&console.warn("[NativeIpcBridge] Relay-only WebRTC requested, but no TURN servers are configured; native WebRTC override disabled");let f=o?.lanMode===true;(c.length>0||p||f)&&(i={iceServers:c.length>0?c:void 0,privacyMode:p,lanMode:f||void 0});}let n=null;if(e?.moq&&typeof e.moq=="object"){let o=typeof e.moq.relayUrl=="string"&&e.moq.relayUrl.trim().length>0?e.moq.relayUrl:void 0;o&&(n={relayUrl:o});}let a=null;if(!this.strictMode&&(e?.ble===true||e?.ble&&typeof e.ble=="object")){let o=e.ble===true?null:e.ble,c=Number(o?.connectTimeoutMs),u=Number(o?.retryAttempts),g=Number(o?.retryBackoffMs);a={enabled:o?.enabled!==false,connectTimeoutMs:Number.isFinite(c)&&c>0?Math.round(c):void 0,retryAttempts:Number.isFinite(u)&&u>=0?Math.round(u):void 0,retryBackoffMs:Number.isFinite(g)&&g>=0?Math.round(g):void 0};}let s=this.strictMode||e?.iroh&&typeof e.iroh=="object"&&e.iroh.relayOnly===true,r=e?.iroh&&typeof e.iroh=="object"?e.iroh.relayTransportPolicy:void 0,l=this.strictMode?r??"auto":r;return !s&&!l&&!i&&!n&&!t&&!a?null:{irohRelayOnly:s||void 0,irohRelayTransportPolicy:l,irohLan:t,webrtc:i,moq:n,ble:a}}isTauriEnv(){return a()}nextConnectionEventRetryDelayMs(e){return u(e,v.CONNECTION_EVENT_RETRY_MIN_DELAY_MS,v.CONNECTION_EVENT_RETRY_MAX_DELAY_MS)}async clearNativeAuthRelay(e){if(await this.canUseTauriIpc())try{await this.invokeIpc("desktop_set_pluto_auth_token",{authToken:null,refreshToken:null}),this.lastSyncedAuthToken=null,this.lastNativeAuthSyncAtMs=0,d(`[NativeIpcBridge] cleared native auth relay (${e})`);}catch(t){console.warn(`[NativeIpcBridge] failed clearing native auth relay (${e}):`,t);}}applyNativeRuntimeStatus(e){this.runtimeCapabilities=v$1(e,this.allowWasmFallback);}syncNativeRuntimeCapabilities(e){return this.ipcBridge?this.nativeRuntimeCapabilitiesSyncInFlight?this.nativeRuntimeCapabilitiesSyncInFlight:(this.nativeRuntimeCapabilitiesSyncInFlight=(async()=>{try{let t=await this.invokeIpc("rtc_native_status",void 0,{timeoutMs:v.NATIVE_STATUS_IPC_TIMEOUT_MS});this.applyNativeRuntimeStatus(t),d(`[NativeIpcBridge] refreshed native runtime capabilities (${e})`);}catch(t){c("[NativeIpcBridge] native runtime capability refresh skipped",t);}})().finally(()=>{this.nativeRuntimeCapabilitiesSyncInFlight=null;}),this.nativeRuntimeCapabilitiesSyncInFlight):Promise.resolve()}async canUseTauriIpc(){if(this.ipcBridge){let e=typeof this.ipcBridge.isAvailable=="function"?!!await this.ipcBridge.isAvailable():true;return e&&this.syncNativeRuntimeCapabilities("ipc-available"),e}return typeof window>"u"?false:this.tauriCoreAvailabilityValue===true?true:this.tauriCoreAvailabilityValue===false&&Date.now()-this.tauriCoreAvailabilityCheckedAtMs<v.TAURI_IPC_NEGATIVE_CACHE_MS?false:(this.tauriCoreAvailability||(this.tauriCoreAvailability=(async()=>{try{if(this.isTauriEnv())return this.tauriCoreAvailabilityValue=!0,this.tauriCoreAvailabilityCheckedAtMs=Date.now(),this.syncNativeRuntimeCapabilities("tauri-env"),!0;try{let e=await this.invokeIpc("rtc_native_status");return this.applyNativeRuntimeStatus(e),d("[NativeIpcBridge] Resolved Tauri IPC via rtc_native_status probe"),this.tauriCoreAvailabilityValue=!0,this.tauriCoreAvailabilityCheckedAtMs=Date.now(),!0}catch(e){let t=String(e?.message??e??"");return t.includes("__TAURI_INTERNALS__")||t.includes("Cannot read properties of undefined")||t.includes("window is not defined")?(this.tauriCoreAvailabilityValue=!1,this.tauriCoreAvailabilityCheckedAtMs=Date.now(),!1):(d("[NativeIpcBridge] Tauri IPC probe reached native layer (command-level error acceptable)"),this.tauriCoreAvailabilityValue=!0,this.tauriCoreAvailabilityCheckedAtMs=Date.now(),!0)}}catch{return this.tauriCoreAvailabilityValue=false,this.tauriCoreAvailabilityCheckedAtMs=Date.now(),false}})().finally(()=>{this.tauriCoreAvailability=null;})),this.tauriCoreAvailability)}async invokeIpc(e,t,i){let n=this.ipcBridge.invoke(e,t),a=i?.timeoutMs??v.MANAGED_SESSION_IPC_TIMEOUT_MS;return a===null||a<=0?n:B$1(n,a,()=>new Error(`${e} timeout after ${a}ms`))}isRetryableManagedSessionStartError(e){let t=(e instanceof Error?e.message:String(e??"")).toLowerCase();return !t||t.includes("start_rtc_managed_session")&&t.includes("timeout after")?false:!!(t.includes("callback")&&t.includes("id")||t.includes("channel closed")||t.includes("ipc channel closed"))}async listenIpc(e,t){return this.ipcBridge.listen(e,i=>{t({payload:i});})}async openPeerBiViaIpc(e,t,i){let n=await this.invokePeerBiOpen(e,t,i),a=typeof n?.streamId=="string"?n.streamId.trim():typeof n?.stream_id=="string"?n.stream_id.trim():"";if(!a)throw new Error(`${e} returned no streamId`);return this.peerBiStreamFromId(a)}peerBiStreamFromId(e,t={}){let i=this,n=null,a=null,s=false,r=null,l=null,o=async()=>{let p=[n,a];n=null,a=null,await Promise.allSettled(p.filter(f=>typeof f=="function").map(f=>Promise.resolve(f())));},c=(async()=>{n=await this.listenIpc("openrtc://peer-bi-stream/chunk",p=>{let f=p.payload;if((typeof f?.streamId=="string"?f.streamId:typeof f?.stream_id=="string"?f.stream_id:"")!==e||s||!r)return;let y=f?.bytes;y instanceof Uint8Array?r.enqueue(y):Array.isArray(y)&&r.enqueue(new Uint8Array(y));}),a=await this.listenIpc("openrtc://peer-bi-stream/closed",p=>{let f=p.payload;if((typeof f?.streamId=="string"?f.streamId:typeof f?.stream_id=="string"?f.stream_id:"")!==e||s||!r)return;s=true;let y=typeof f?.error=="string"?f.error.trim():"";y?r.error(new Error(y)):r.close(),o();}),t.startReadAfterListeners&&await this.invokeIpc("start_peer_bi_stream_read",{streamId:e},{timeoutMs:null});})().catch(p=>{l=p,r&&!s&&(s=true,r.error(p));}),u=async()=>{await this.invokeIpc("close_peer_bi_stream",{streamId:e},{timeoutMs:null}).catch(()=>{}),await o();},g=new ReadableStream({async start(p){r=p,await c,l&&!s&&(s=true,p.error(l));},async cancel(){s=true,await u();}}),m=new WritableStream({write:async p=>{await i.invokeIpc("write_peer_bi_stream",{streamId:e,bytes:Array.from(p)},{timeoutMs:null});},close:u,abort:u});return {readable:g,writable:m}}async invokePeerBiOpen(e,t,i){try{return await this.invokeIpc(e,t)}catch(n){if(!i?.fallbackCommand||!this.isMissingNativeCommandError(n))throw n;return this.invokeIpc(i.fallbackCommand,i.fallbackArgs??t)}}isMissingNativeCommandError(e){let t=e instanceof Error?e.message:String(e??"");return t.includes("Command")&&t.includes("not found")}async shouldUseTauriSignaling(){if(await this.canUseTauriIpc())return true;if(this.allowWasmFallback)return false;throw new Error("[pluto-rtc] Tauri runtime adapter requires native IPC, but it is unavailable.")}async signInWithPluto(){if(!await this.canUseTauriIpc()){await this.fallback.signInWithPluto();return}let e=await this.invokeIpc("rtc_sign_in_with_pluto"),t=typeof e?.customToken=="string"?e.customToken.trim():"";if(!t)throw new Error("[pluto-rtc] Native Pluto SSO did not return a custom token.");await D().signInWithCustomTokenValue(t),await this.ensureNativeAuth("pluto-sso",{requireToken:true,maxWaitMs:1e4});}async setAuthContext(e){if(await this.fallback.setAuthContext(e),!e?.token)await this.markNativeRtdbOffline(),await this.clearNativeAuthRelay("setAuthContext");else if(!await this.ensureNativeAuth("setAuthContext",{requireToken:true,maxWaitMs:v.AUTH_REQUIRED_WAIT_MS}))throw new Error("Native auth token unavailable for setAuthContext")}async signOut(){await this.fallback.signOut(),await this.markNativeRtdbOffline(),await this.clearNativeAuthRelay("signOut");}async stopAuthScopedActivity(e){let t=this.resolveNativeSignalingUserId(e?.userId??null),i$1=await this.shouldUseTauriSignaling();if(i("NativeIpcBridge.stopAuthScopedActivity",{userId:t,useTauri:i$1}),i$1)try{await Promise.allSettled([this.revokeSessionTokensByScope("user-device"),this.invokeIpc("stop_rtc_presence_loop"),this.invokeIpc("stop_rtc_auto_connect"),t?this.invokeIpc("set_rtc_offline",{userId:t}):Promise.resolve()]);}catch(n){console.warn("[NativeIpcBridge] Failed to stop native auth-scoped RTC activity:",n);}await this.markNativeRtdbOffline(),await this.fallback.stopAuthScopedActivity({userId:t});}async ensureNativeAuthOnce(e,t){if(!await this.canUseTauriIpc())return true;if(this.authSyncInFlight)return this.authSyncInFlight;let i=(async()=>{try{if(!this.currentUser)return d(`[NativeIpcBridge] auth sync deferred (${e}): no current user`),!t;let n=Date.now()-this.lastNativeAuthSyncAtMs>=480*1e3,a=this.currentUser?.getToken?await this.currentUser.getToken(n):null,r=this.getAuthContext()?.refreshToken??this.auth?.currentUser?.refreshToken??null;if(!a)return d(`[NativeIpcBridge] auth sync deferred (${e}): missing token for user ${this.currentUser?.id}`),!t;if(!await this.nativeAuthTokenMatchesExpectedScope(a))return d(`[NativeIpcBridge] auth sync deferred (${e}): token claims do not match configured space`),!1;if(a===this.lastSyncedAuthToken)return !0;let l=await Promise.allSettled([this.invokeIpc("desktop_set_pluto_auth_token",{authToken:a,refreshToken:r})]);return l[0]?.status==="rejected"?(B(l[0].reason)?console.warn(`[NativeIpcBridge] desktop auth relay unavailable (${e}); install/register openrtc-tauri-plugin and include its default permission set.`,l[0].reason):console.warn(`[NativeIpcBridge] desktop auth relay failed (${e}):`,l[0].reason),!1):(this.lastSyncedAuthToken=a,this.lastNativeAuthSyncAtMs=Date.now(),d(`[NativeIpcBridge] auth token relayed to native runtime (${e}) user_id=${this.currentUser?.id}`),!0)}catch(n){return console.error("[NativeIpcBridge] auth sync failed:",n),false}})();this.authSyncInFlight=i;try{return await i}finally{this.authSyncInFlight===i&&(this.authSyncInFlight=null);}}async ensureNativeAuth(e="runtime",t){if(!await this.canUseTauriIpc())return true;let i=t?.requireToken??false,n=t?.maxWaitMs??(i?v.AUTH_REQUIRED_WAIT_MS:0),a=t?.pollMs??250,s=Date.now()+Math.max(0,n);for(;;){if(await this.ensureNativeAuthOnce(e,i))return true;if(!i||Date.now()>=s)return false;await r(a);}}async resolveLocalDeviceId(){if(this.cachedLocalDeviceId)return this.cachedLocalDeviceId;if(await this.canUseTauriIpc())try{let t=await this.invokeIpc("get_rtc_local_device_info"),i=typeof t?.device_id=="string"?t.device_id:"",n=typeof t?.device_name=="string"?t.device_name.trim():"";if(i)return this.cachedLocalDeviceId=i,n&&(this.cachedLocalDeviceName=n),i}catch(t){console.warn("[NativeIpcBridge] get_rtc_local_device_info failed:",t);}let e=this.resolveWebLogicalDeviceId();return this.cachedLocalDeviceId=e,e}async resolveLocalDeviceName(){if(this.cachedLocalDeviceName)return this.cachedLocalDeviceName;if(await this.canUseTauriIpc())try{let e=await this.invokeIpc("get_rtc_local_device_info"),t=typeof e?.device_name=="string"?e.device_name.trim():"";if(t){let i=this.normalizeNativeDeviceName(t);return this.cachedLocalDeviceName=i,i}}catch(e){console.warn("[NativeIpcBridge] get_rtc_local_device_info failed:",e);}return this.defaultDeviceNameFallback()}normalizeNativeDeviceName(e){let t=e.trim();if(!t)return this.defaultDeviceNameFallback();if(t==="Desktop Device"){let i=this.defaultDeviceNameFallback();if(i!=="Desktop Device")return i}return t}defaultDeviceNameFallback(){if(typeof window>"u"||typeof navigator>"u")return "Desktop Device";let e=navigator.userAgent||"";return /iPhone|iPad|iPod/i.test(e)?"iPhone":/Android/i.test(e)?"Android":"Desktop Device"}inferNativePlatformTypeFallback(){if(typeof window>"u"||typeof navigator>"u")return "desktop";if(!this.isTauriEnv())return "web";let e=navigator.userAgent||"";return /iPhone|iPad|iPod|Android|Mobile/i.test(e)?"mobile":"desktop"}withPresenceMetadata(e,t){try{let i=e?JSON.parse(e):{};return JSON.stringify({...i,deviceId:t,plutoVersion:"0.1.0-desktop"})}catch{return JSON.stringify({deviceId:t,plutoVersion:"0.1.0-desktop",rawMetadata:e})}}async searchDevices(e){if(await this.shouldUseTauriSignaling()){if(!await this.ensureNativeAuth("searchDevices",{requireToken:this.requiresNativeAuthToken(),maxWaitMs:this.nativeAuthWaitMs()}))throw new Error("Native auth token unavailable for searchDevices");let i=await this.invokeIpc("search_rtc_devices",{userId:this.getCurrentUserId()});if(Array.isArray(i?.devices)){let n=i.devices.map(a=>this.normalizeDevice(a));return e&&(n=n.filter(a=>a.ticket!==e&&a.deviceId!==e&&a.nodeId!==e)),n}throw typeof i?.message=="string"?new Error(String(i.message)):new Error("Unexpected response for search_rtc_devices")}return this.fallback.searchDevices(e)}async listDevicesWithStatus(){if(await this.shouldUseTauriSignaling()){if(!await this.ensureNativeAuth("listDevicesWithStatus",{requireToken:this.requiresNativeAuthToken(),maxWaitMs:this.nativeAuthWaitMs()}))throw new Error("Native auth token unavailable for listDevicesWithStatus");let t=await this.invokeIpc("search_rtc_devices_with_status",{userId:this.getCurrentUserId()});if(Array.isArray(t?.devices)){let i=t.devices,n=i.filter(r=>this.matchesNativeStatusTag(r)).map(r=>l(r)),a=await this.resolveLocalDeviceId().catch(()=>null),s=!!a&&n.some(r=>r.deviceId===a);return c("[NativeIpcBridge] listDevicesWithStatus result",{rawCount:i.length,count:n.length,localDeviceId:a,selfIncluded:s,devices:n.map(r=>({deviceId:r.deviceId,deviceName:r.deviceName,online:!!r.online,presenceStatus:r.presenceStatus,connectable:r.connectable,connectionStatus:r.connectionStatus,settledReady:!!r.settledReady,peerHealth:r.peerHealth,scopes:r.scopes,connectionId:r.connectionId??null,deviceIdHint:r.deviceIdHint??null,nodeId:r.nodeId??null,activeTransport:r.activeTransport??null,parallelTransport:r.parallelTransport??null}))}),a&&!s&&c("[NativeIpcBridge] native status snapshot excludes local device by design",{localDeviceId:a,count:n.length}),n}throw typeof t?.message=="string"?new Error(String(t.message)):new Error("Unexpected response for search_rtc_devices_with_status")}return this.fallback.listDevicesWithStatus()}async getPeerSession(e){if(await this.shouldUseTauriSignaling()){let t=await this.invokeIpc("get_rtc_peer_session",{id:e});return !t||typeof t!="object"?null:m(t)}return this.fallback.getPeerSession(e)}async listPeerSessions(){if(await this.shouldUseTauriSignaling()){let e=await this.invokeIpc("list_rtc_peer_sessions");return (Array.isArray(e)?e:[]).map(t=>m(t))}return this.fallback.listPeerSessions()}async waitForSettledPeer(e,t){if(await this.shouldUseTauriSignaling()){let i=typeof t=="number"?Math.max(v.MANAGED_SESSION_IPC_TIMEOUT_MS,t+1e3):v.MANAGED_SESSION_IPC_TIMEOUT_MS,n=await this.invokeIpc("wait_for_rtc_settled_peer",{id:e,timeoutMs:t},{timeoutMs:i});return !n||typeof n!="object"?null:m(n)}return this.fallback.waitForSettledPeer(e,t)}async resolvePeerConnectionRecords(e){if(await this.shouldUseTauriSignaling()){let t=await this.invokeIpc("resolve_rtc_peer_connection_records",{id:e});return (Array.isArray(t)?t:[]).map(i=>n(i))}return this.fallback.resolvePeerConnectionRecords(e)}async resolvePeerIdentity(e){if(await this.shouldUseTauriSignaling()){let t=await this.invokeIpc("resolve_rtc_peer_identity",{id:e});return o(t)}return this.fallback.resolvePeerIdentity(e)}async setOffline(e){if(await this.shouldUseTauriSignaling())try{if(!await this.ensureNativeAuth("setOffline",{requireToken:this.requiresNativeAuthToken(),maxWaitMs:this.nativeAuthWaitMs()}))throw new Error("Native auth token unavailable for setOffline");let i=this.getCurrentUserId();await this.invokeIpc("set_rtc_offline",{userId:i}),await this.markNativeRtdbOffline();return}catch(t){console.warn("[NativeIpcBridge] set_rtc_offline failed:",t);}return this.fallback.setOffline(e)}async updateDevice(e,t){if(await this.shouldUseTauriSignaling()){if(!await this.ensureNativeAuth("updateDevice",{requireToken:this.requiresNativeAuthToken(),maxWaitMs:this.nativeAuthWaitMs()}))throw new Error("Native auth token unavailable for updateDevice");let a=this.getCurrentUserId();if(!a)throw new Error("updateDevice requires authenticated user scope");try{await this.invokeIpc("update_rtc_device",{userId:a,deviceId:e,deviceName:t.deviceName??null,capabilities:t.capabilities??null,metadata:t.metadata??null});return}catch(s){throw console.warn("[NativeIpcBridge] update_rtc_device failed:",s),s instanceof Error?s:new Error(String(s))}}return this.fallback.updateDevice(e,t)}async deleteDevice(e){if(await this.shouldUseTauriSignaling()){if(!await this.ensureNativeAuth("deleteDevice",{requireToken:this.requiresNativeAuthToken(),maxWaitMs:this.nativeAuthWaitMs()}))throw new Error("Native auth token unavailable for deleteDevice");let n=this.getCurrentUserId();if(!n)throw new Error("deleteDevice requires authenticated user scope");try{await this.invokeIpc("delete_rtc_device",{userId:n,deviceId:e});return}catch(a){throw console.warn("[NativeIpcBridge] delete_rtc_device failed:",a),a instanceof Error?a:new Error(String(a))}}return this.fallback.deleteDevice(e)}async getLocalDeviceInfo(){if(!await this.canUseTauriIpc()){let e=await this.getLocalDeviceId?.();return e?{deviceId:e,deviceName:this.defaultDeviceNameFallback(),platformType:this.inferNativePlatformTypeFallback()}:null}try{let e=await this.invokeIpc("get_rtc_local_device_info"),t=typeof e?.device_id=="string"?e.device_id.trim():"";return t?{deviceId:t,deviceName:this.normalizeNativeDeviceName(typeof e?.device_name=="string"?e.device_name:""),platformType:typeof e?.platform_type=="string"?e.platform_type:this.inferNativePlatformTypeFallback(),capabilities:e?.capabilities??void 0,lastSeenAt:typeof e?.last_seen_at=="string"?e.last_seen_at:void 0}:null}catch(e){return console.warn("[NativeIpcBridge] getLocalDeviceInfo failed:",e),null}}async updateLocalDeviceName(e){if(!await this.canUseTauriIpc())return null;try{let t=await this.invokeIpc("update_rtc_local_device_name",{deviceName:e}),i=typeof t?.device_id=="string"?t.device_id.trim():"";return i?(this.cachedLocalDeviceName=this.normalizeNativeDeviceName(e),{deviceId:i,deviceName:this.cachedLocalDeviceName,platformType:typeof t?.platform_type=="string"?t.platform_type:this.inferNativePlatformTypeFallback(),capabilities:t?.capabilities??void 0,lastSeenAt:typeof t?.last_seen_at=="string"?t.last_seen_at:void 0}):null}catch(t){return console.warn("[NativeIpcBridge] updateLocalDeviceName failed:",t),null}}async startManagedSessionNative(e){if(!await this.shouldUseTauriSignaling())throw new Error("[pluto-rtc] Native IPC unavailable for startManagedSessionNative().");if(!await this.ensureNativeAuth("startManagedSessionNative",{requireToken:this.requiresNativeAuthToken(),maxWaitMs:this.nativeAuthWaitMs()}))throw new Error("Native auth token unavailable for startManagedSessionNative");let i=this.resolveNativeSignalingUserId(e.userId);if(!i)throw new Error("Native managed session startup requires a runtime auth-scoped user id.");i!==e.userId&&console.info("[NativeIpcBridge][managed-session][user-id-remap]",{requestedUserId:e.userId,runtimeUserId:this.currentUser?.id??this.getAuthContext()?.userId??null,effectiveUserId:i}),console.info("[NativeIpcBridge][managed-session][start-request]",{requestedUserId:e.userId,runtimeUserId:this.currentUser?.id??this.getAuthContext()?.userId??null,effectiveUserId:i,spaceKey:this.options.spaceKey?"[configured]":null,deviceName:e.deviceName??null,localDeviceId:e.localDeviceId??null,presence:e.presence!==false,autoConnect:e.autoConnect!==false,hasMetadata:typeof e.metadata=="string"&&e.metadata.trim().length>0});let n=await this.buildNativeTransportConfigPayload(),a={userId:i,deviceName:e.deviceName??null,localDeviceId:e.localDeviceId??null,metadata:e.metadata??null,...n?{transports:n}:{},autoConnect:e.autoConnect!==false,presence:e.presence!==false,apiKey:this.options.apiKey??null,spaceKey:this.options.spaceKey??null},s=null,r$1=null;for(let g=1;g<=v.MANAGED_SESSION_IPC_MAX_ATTEMPTS;g+=1)try{s=await this.invokeIpc("start_rtc_managed_session",a,{timeoutMs:v.MANAGED_SESSION_IPC_TIMEOUT_MS}),r$1=null;break}catch(m){r$1=m;let p=this.isRetryableManagedSessionStartError(m),f=v.MANAGED_SESSION_IPC_MAX_ATTEMPTS-g;if(console.warn("[NativeIpcBridge][managed-session][ipc-attempt-failed]",{attempt:g,retryable:p,remaining:f,message:m instanceof Error?m.message:String(m)}),!p||f<=0)throw m;await this.ensureNativeAuth("startManagedSessionNative-retry",{requireToken:this.requiresNativeAuthToken(),maxWaitMs:this.requiresNativeAuthToken()?5e3:0}),await r(250*g);}if(!s&&r$1)throw r$1 instanceof Error?r$1:new Error(String(r$1));this.syncNativeRuntimeCapabilities("managed-session-started");let l=typeof s?.ticket=="string"&&s.ticket.trim().length>0?s.ticket.trim():null;l&&e.presence!==false&&await this.syncNativeRtdbPresenceTicket(l);let o=s?.localDevice&&typeof s.localDevice=="object"?s.localDevice:s?.local_device&&typeof s.local_device=="object"?s.local_device:null,c=o?{deviceId:typeof o.deviceId=="string"?o.deviceId:typeof o.device_id=="string"?o.device_id:"",deviceName:this.normalizeNativeDeviceName(typeof o.deviceName=="string"?o.deviceName:typeof o.device_name=="string"?o.device_name:""),platformType:typeof o.platformType=="string"?o.platformType:typeof o.platform_type=="string"?o.platform_type:"desktop",capabilities:o.capabilities??void 0,lastSeenAt:typeof o.lastSeenAt=="string"?o.lastSeenAt:typeof o.last_seen_at=="string"?o.last_seen_at:void 0}:null,u={localNodeId:typeof s?.localNodeId=="string"?s.localNodeId:typeof s?.local_node_id=="string"?s.local_node_id:null,ticket:l,ticketScope:typeof s?.ticketScope=="string"?s.ticketScope:typeof s?.ticket_scope=="string"?s.ticket_scope:null,presenceStarted:typeof s?.presenceStarted=="boolean"?s.presenceStarted:!!s?.presence_started,autoConnectStarted:typeof s?.autoConnectStarted=="boolean"?s.autoConnectStarted:!!s?.auto_connect_started,localDevice:c?.deviceId?c:null};return console.info("[NativeIpcBridge][managed-session][ipc-started]",{requestedUserId:e.userId,runtimeUserId:this.currentUser?.id??this.getAuthContext()?.userId??null,effectiveUserId:i,localNodeId:u.localNodeId,ticketScope:u.ticketScope,presenceStarted:u.presenceStarted,autoConnectStarted:u.autoConnectStarted,localDeviceId:u.localDevice?.deviceId??null}),u}async reconcileNativeManagedSession(e){if(!await this.shouldUseTauriSignaling())return null;if(!await this.ensureNativeAuth("reconcileNativeManagedSession",{requireToken:this.requiresNativeAuthToken(),maxWaitMs:this.nativeAuthWaitMs()}))throw new Error("Native auth token unavailable for reconcileNativeManagedSession");return this.invokeIpc("reconcile_mobile_rtc_after_resume",{reason:e?.reason??"frontend"})}async getManagedNodeId(e){let t=e?.initializeIfMissing??true;console.info("[NativeIpcBridge][getManagedNodeId] enter",{initializeIfMissing:t});let i=await this.canUseTauriIpc();if(console.info("[NativeIpcBridge][getManagedNodeId] canUseTauriIpc",{canUse:i}),!i)return null;try{console.info("[NativeIpcBridge][getManagedNodeId] invoking get_iroh_node_id");let n=await this.invokeIpc("get_iroh_node_id");if(console.info("[NativeIpcBridge][getManagedNodeId] get_iroh_node_id returned",{existing:n}),n||!t)return n;console.info("[NativeIpcBridge][getManagedNodeId] invoking start_iroh_node");let a=await this.invokeIpc("start_iroh_node");return console.info("[NativeIpcBridge][getManagedNodeId] start_iroh_node returned",{started:a}),a}catch(n){if(console.warn("[NativeIpcBridge] getManagedNodeId failed:",n),!t)return null;throw n}}async getEndpointTicket(){if(!await this.canUseTauriIpc())throw new Error("[pluto-rtc] getEndpointTicket requires native IPC in Tauri runtime.");return q(()=>this.invokeIpc("get_iroh_endpoint_ticket"))}async connectToDevice(e){if(!await this.canUseTauriIpc())throw new Error("[pluto-rtc] connectToDevice requires native IPC in Tauri runtime.");return this.options.authMode!=="anonymous"?await this.ensureNativeAuth("connectToDevice",{requireToken:true,maxWaitMs:v.AUTH_REQUIRED_WAIT_MS}):d("[NativeIpcBridge] connectToDevice using anonymous native ticket path"),this.invokeIpc("connect_to_device",{deviceId:e.deviceId??null,endpointTicket:e.endpointTicket})}async registerSessionToken(e,t,i){await this.canUseTauriIpc()&&await this.invokeIpc("register_session_token",{token:e,scope:t,maxConnections:i});}async getEndpointTicketWithToken(e,t){if(!await this.canUseTauriIpc())return null;try{return await q(()=>this.invokeIpc("get_endpoint_ticket_with_token",{scope:e,maxConnections:t}))}catch{return null}}async validateSessionToken(e,t){if(!await this.canUseTauriIpc())return null;try{return await this.invokeIpc("validate_session_token",{token:e,connectionId:t??null})}catch{return null}}async revokeSessionTokensByScope(e){if(i("NativeIpcBridge.revokeSessionTokensByScope",{grantScope:e}),!await this.canUseTauriIpc())return [];try{return await this.invokeIpc("revoke_session_tokens_by_scope",{scope:e})}catch{return []}}async disconnectDevice(e){if(!await this.canUseTauriIpc())throw new Error("[pluto-rtc] disconnectDevice requires native IPC in Tauri runtime.");await this.invokeIpc("disconnect_device",{deviceId:e});}async setAutoConnectExcluded(e,t){await this.canUseTauriIpc()&&await this.invokeIpc("set_auto_connect_excluded",{deviceId:e,excluded:t});}onDevicesChange(e,t){let i=false,n=new Map,a=null,s=false,r$1=false,l=()=>{if(r$1=false,i)return;let g=Array.from(n.values());t&&(g=g.filter(m=>m.ticket!==t&&m.deviceId!==t&&m.nodeId!==t)),e(g);},o=()=>{if(!r$1){if(r$1=true,typeof queueMicrotask=="function"){queueMicrotask(l);return}Promise.resolve().then(l);}},c=async()=>{if(!await this.shouldUseTauriSignaling()){console.warn("[NativeIpcBridge] onDevicesChange falling back to wasm signaling (Tauri IPC unavailable)"),u=this.fallback.onDevicesChange(e,t);return}for(;!i;)try{let g=this.requiresNativeAuthToken()?15e3:0,m=Date.now()+g,p=this.getCurrentUserId();for(;!i&&!p&&Date.now()<m&&(this.hasLoggedMissingAuthForDevices||(this.hasLoggedMissingAuthForDevices=!0,d("[NativeIpcBridge] onDevicesChange waiting for authenticated user before subscription")),p=this.getCurrentUserId(),!p);)await r(250);if(!p){!i&&!s&&(console.warn("[NativeIpcBridge] onDevicesChange could not resolve authenticated user; keeping subscription in retry mode"),e([]),s=!0),await r(1e3);continue}if(!await this.ensureNativeAuth("onDevicesChange",{requireToken:this.requiresNativeAuthToken(),maxWaitMs:Math.max(0,m-Date.now())})){!i&&!s&&(console.warn("[NativeIpcBridge] onDevicesChange timed out waiting for auth token; keeping subscription in retry mode"),e([]),s=!0),await r(1e3);continue}this.hasLoggedMissingAuthForDevices=!1,s=!1,d(`[NativeIpcBridge] onDevicesChange starting subscription user_id=${p}`);let N=await this.listDevicesWithStatus().catch(async w=>(d(`[NativeIpcBridge] onDevicesChange full-roster seed failed; falling back to online-only search: ${w}`),this.searchDevices(t)));n.clear();for(let w of N)w?.deviceId&&n.set(w.deviceId,w);for(o(),a=(await this.subscribeDevices(p)).getReader();!i;){let{done:w,value:O}=await a.read();if(w||!O)break;for(let _ of O){if(_.type==="removed"){n.delete(_.deviceId);continue}let W=_.device?.deviceId;if(!this.matchesTag(_.device??{})){W&&n.delete(W);continue}let R=this.normalizeDevice(_.device);R.deviceId&&n.set(R.deviceId,R);}o();}}catch(g){i||(console.error("[NativeIpcBridge] onDevicesChange stream failed; retrying subscription:",g),await r(1e3));}finally{if(a){try{await a.cancel();}catch{}a=null;}}},u=()=>{i=true,a&&(a.cancel(),a=null);};return c(),()=>u()}async subscribeDevices(e){if(await this.shouldUseTauriSignaling()){if(!await this.ensureNativeAuth("subscribeDevices",{requireToken:this.requiresNativeAuthToken(),maxWaitMs:this.nativeAuthWaitMs()}))throw new Error("Native auth token unavailable for subscribeDevices");let i=`sub-${Math.random().toString(36).substring(2,11)}`,n=null,a=null,s=false,r=async()=>{if(!s&&(s=true,n&&(await Promise.resolve(n()),n=null),a)){try{await a();}catch{}a=null;}};return new ReadableStream({start:async l=>{d(`[NativeIpcBridge] subscribeDevices request start user_id=${e} request_id=${i}`),n=await this.listenIpc("rtc-device-events",o=>{if(s)return;let c$1=o.payload;if(c$1.requestId===i){if(c$1.type==="deviceEvents"){let u=Array.isArray(c$1.events)?c$1.events.length:0;c(`[NativeIpcBridge] subscribeDevices event batch request_id=${i} count=${u}`);try{l.enqueue(c$1.events);}catch{r();}}else if(c$1.type==="error"&&(console.warn(`[NativeIpcBridge] subscribeDevices stream error request_id=${i}: ${c$1.message}`),!s)){try{l.error(c$1.message);}catch{}r();}}}),a=async()=>{await this.invokeIpc("stop_rtc_subscription",{requestId:i});};try{await this.invokeIpc("start_rtc_device_subscription",{requestId:i,userId:e});}catch(o){try{l.error(o);}catch{}await r();}},cancel:async()=>{d(`[NativeIpcBridge] subscribeDevices request stop request_id=${i}`),await r();}})}return this.fallback.subscribeDevices(e)}async subscribeSessions(e){if(await this.shouldUseTauriSignaling()){if(!await this.ensureNativeAuth("subscribeSessions",{requireToken:this.requiresNativeAuthToken(),maxWaitMs:this.nativeAuthWaitMs()}))throw new Error("Native auth token unavailable for subscribeSessions");let i=`sub-${Math.random().toString(36).substring(2,11)}`,n=await this.resolveLocalDeviceId()||e,a=null,s=null,r=false,l=async()=>{if(!r&&(r=true,a&&(await Promise.resolve(a()),a=null),s)){try{await s();}catch{}s=null;}};return new ReadableStream({start:async o=>{a=await this.listenIpc("rtc-session-events",c=>{if(r)return;let u=c.payload;if(u.requestId===i){if(u.type==="sessionEvents")try{o.enqueue(u.events);}catch{l();}else if(u.type==="error"&&!r){try{o.error(u.message);}catch{}l();}}}),s=async()=>{await this.invokeIpc("stop_rtc_subscription",{requestId:i});};try{await this.invokeIpc("start_rtc_session_subscription",{requestId:i,localDeviceId:n});}catch(c){try{o.error(c);}catch{}await l();}},cancel:async()=>{await l();}})}return this.fallback.subscribeSessions(e)}async getLocalDeviceId(){return this.resolveLocalDeviceId()}async updatePresence(e,t,i=true,n=3e5,a){if(await this.shouldUseTauriSignaling())try{if(!await this.ensureNativeAuth("updatePresence",{requireToken:this.requiresNativeAuthToken(),maxWaitMs:this.nativeAuthWaitMs()}))throw new Error("Native auth token unavailable for updatePresence");let r=this.resolveNativeSignalingUserId(),l=await this.resolveLocalDeviceId(),o=await this.resolveLocalDeviceName();await this.invokeIpc("update_rtc_presence",{userId:r,deviceName:o,ticket:t,metadata:this.withPresenceMetadata(a,l)}),await this.syncNativeRtdbPresenceTicket(t);return}catch(s){console.warn("[NativeIpcBridge] update_rtc_presence failed:",s);}return this.fallback.updatePresence(e,t,i,n,a)}startAutoConnect(e,t){(async()=>{try{if(!await this.shouldUseTauriSignaling()){console.error("[NativeIpcBridge] startAutoConnect requires native Rust signaling; IPC unavailable");return}let i=await this.resolveLocalDeviceId()||t;await this.startAutoConnectOnce(e,i);}catch(i){console.warn("[NativeIpcBridge] startAutoConnect failed:",i);}})();}forceReconnectSnapshot(){(async()=>{if(!await this.shouldUseTauriSignaling()){console.error("[NativeIpcBridge] forceReconnectSnapshot requires native Rust signaling; IPC unavailable");return}try{await this.invokeIpc("force_rtc_reconnect_snapshot");}catch(e){console.warn("[NativeIpcBridge] force_rtc_reconnect_snapshot failed:",e);}})();}startPresenceLoop(e,t,i,n,a){(async()=>{try{if(!await this.shouldUseTauriSignaling()){console.warn("[NativeIpcBridge] startPresenceLoop falling back to wasm signaling (Tauri IPC unavailable)"),this.fallback.startPresenceLoop(e,t,i,n,a);return}let s=await this.resolveLocalDeviceId(),r=this.shouldUseResolvedDeviceName(i)?await this.resolveLocalDeviceName():i.trim(),l=this.withPresenceMetadata(a,s);await this.startPresenceLoopOnce(e,t,r,n,l),await this.syncNativeRtdbPresenceTicket(n);}catch(s){console.warn("[NativeIpcBridge] startPresenceLoop failed:",s);}})();}async startAutoConnectOnce(e,t){if(!await this.shouldUseTauriSignaling())throw new Error("[pluto-rtc] Native IPC unavailable for startAutoConnectOnce().");if(!await this.ensureNativeAuth("startAutoConnect",{requireToken:this.requiresNativeAuthToken(),maxWaitMs:this.nativeAuthWaitMs()}))throw new Error("Native auth token unavailable for startAutoConnect");let n=this.resolveNativeSignalingUserId(e);if(!n)throw new Error("Native auto-connect requires a runtime auth-scoped user id.");await this.invokeIpc("start_rtc_auto_connect",{userId:n,localDeviceId:t});}async startPresenceLoopOnce(e,t,i,n,a){if(!await this.shouldUseTauriSignaling())throw new Error("[pluto-rtc] Native IPC unavailable for startPresenceLoopOnce().");if(console.info("[NativeIpcBridge][presence][start-request]",{userId:e,localNodeId:t,deviceName:i,hasMetadata:typeof a=="string"&&a.trim().length>0,hasCompoundTicket:typeof n=="string"&&n.includes(".")}),!await this.ensureNativeAuth("startPresenceLoop",{requireToken:this.requiresNativeAuthToken(),maxWaitMs:this.nativeAuthWaitMs()}))throw new Error("Native auth token unavailable for startPresenceLoop");let r=this.resolveNativeSignalingUserId(e);if(!r)throw new Error("Native presence loop requires a runtime auth-scoped user id.");console.info("[NativeIpcBridge][presence][auth-ready]",{requestedUserId:e,runtimeUserId:this.currentUser?.id??this.getAuthContext()?.userId??null,effectiveUserId:r,localNodeId:t}),await this.invokeIpc("start_rtc_presence_loop",{userId:r,localNodeId:t,deviceName:i,ticket:n,metadata:a,apiKey:this.options.apiKey??null,spaceKey:this.options.spaceKey??null}),console.info("[NativeIpcBridge][presence][ipc-started]",{requestedUserId:e,effectiveUserId:r,localNodeId:t,deviceName:i});}shouldUseResolvedDeviceName(e){let t=e.trim();return t.length===0||t==="Unknown Device"||t==="Desktop Device"}async sendExplicitFilePath(e,t,i=""){if(d("[NativeIpcBridge] sendExplicitFilePath start",{connectionId:e,filePath:t,transferId:i||null,authMode:this.options.authMode}),await this.canUseTauriIpc()){this.options.authMode!=="anonymous"?await this.ensureNativeAuth("sendExplicitFilePath"):d("[NativeIpcBridge] sendExplicitFilePath using anonymous native path");let n=await this.invokeIpc("send_file",{connectionId:e,filePath:t,transferId:i});return d("[NativeIpcBridge] sendExplicitFilePath completed",{connectionId:e,transferId:i||null,result:n}),n}return this.fallback.sendExplicitFilePath(e,t,i)}async sendExplicitFileData(e){d("[NativeIpcBridge] sendExplicitFileData start",{connectionId:e.connectionId??null,connectionRemoteNodeId:e.connection?.remoteNodeId??null,remoteNodeId:e.remoteNodeId??null,transferId:e.transferId??null,fileName:e.file.name,fileSize:e.file.size,authMode:this.options.authMode});let t=e.applicationCrypto??this.options.applicationCrypto;if(await this.canUseTauriIpc()){this.options.authMode!=="anonymous"?await this.ensureNativeAuth("sendExplicitFileData"):d("[NativeIpcBridge] sendExplicitFileData using anonymous native path");let i=e.connectionId||e.connection?.deviceId||e.connection?.remoteNodeId||e.remoteNodeId||"";if(!i)throw new Error("sendExplicitFileData requires a settled peer identifier in native runtime");let n=new Uint8Array(await e.file.arrayBuffer());await this.invokeIpc("send_file_data",{connectionId:i,filename:e.file.name,data:Array.from(n),transferId:e.transferId}),d("[NativeIpcBridge] sendExplicitFileData completed",{connectionId:i,transferId:e.transferId??null,fileName:e.file.name,fileSize:e.file.size});return}return this.fallback.sendExplicitFileData({...e,applicationCrypto:t})}async getConnectionStates(){if(await this.canUseTauriIpc())try{this.options.authMode!=="anonymous"&&await this.ensureNativeAuth("getConnectionStates");let e=await this.invokeIpc("list_rtc_connection_states");return (Array.isArray(e)?e:[]).map(t=>p(t)).filter(t=>!!t)}catch(e){return B(e)?d("[NativeIpcBridge] native connection-state replay unavailable; continuing without replay. Install/register openrtc-tauri-plugin default permissions to enable it."):console.warn("[NativeIpcBridge] Failed to fetch native connection states:",e),[]}return []}async getConnectionState(e){let t=e.trim();if(!t||!await this.canUseTauriIpc())return null;try{return this.options.authMode!=="anonymous"&&await this.ensureNativeAuth("getConnectionState"),p(await this.invokeIpc("get_rtc_connection_state",{connectionId:t}))}catch(i){return console.warn("[NativeIpcBridge] Failed to fetch native connection state:",{connectionId:t,error:i}),null}}async onConnectionStateChange(e){let t=false,i=null,n=Date.now(),a=0,s=()=>{let o=i;o&&Promise.resolve(o());},r$1=async()=>{try{let o=await this.getConnectionStates();o.length>0&&(c("[NativeIpcBridge] replaying current native connection states",o.map(c=>({connectionId:c.connectionId,deviceId:c.deviceId??null,deviceIdHint:c.deviceIdHint??null,remoteNodeId:c.remoteNodeId??null,state:c.state,transportState:c.transportState??null,protocolState:c.protocolState??null,routable:c.routable??null}))),o.forEach(c=>e(c)));}catch(o){console.warn("[NativeIpcBridge] Failed to replay native connection states after event subscription:",o);}},l=async o=>{let c=await this.getConnectionState(o);c&&e(c);};for(;!t&&Date.now()-n<=v.CONNECTION_EVENT_SUBSCRIBE_WINDOW_MS;){if(a+=1,!await this.canUseTauriIpc()){await r(this.nextConnectionEventRetryDelayMs(a));continue}return i=await this.listenIpc("connection-state-changed",o=>{let c$1=p(o?.payload);c$1&&(c("[NativeIpcBridge] connection-state-changed trigger",{connectionId:c$1.connectionId}),l(c$1.connectionId));}),await r$1(),()=>{t=true,s();}}return ()=>{t=true,s();}}async onIncomingNativeMessage(e){if(!await this.canUseTauriIpc())return ()=>{};let t=await this.listenIpc("iroh://message",i=>{if(i?.payload?.data&&i.payload.streamId==="main")try{let n=new Uint8Array(i.payload.data);if(n.length<2||n[0]!==0)return;let s=n.slice(1),r=new TextDecoder().decode(s),l=JSON.parse(r);e(i.payload.connectionId,i.payload.remoteNodeId??null,l);}catch{}});return typeof t=="function"?t:()=>{}}async getTransferHistory(e=50){return await this.canUseTauriIpc()?this.invokeIpc("get_transfer_history",{limit:e}):[]}async deleteTransferJob(e){await this.canUseTauriIpc()&&await this.invokeIpc("delete_transfer_job",{jobId:e});}};v.AUTH_REQUIRED_WAIT_MS=q$1.nativeIpc.authRequiredWaitMs,v.MANAGED_SESSION_IPC_TIMEOUT_MS=q$1.nativeIpc.managedSessionIpcTimeoutMs,v.MANAGED_SESSION_IPC_MAX_ATTEMPTS=q$1.nativeIpc.managedSessionIpcMaxAttempts,v.CONNECTION_EVENT_SUBSCRIBE_WINDOW_MS=q$1.nativeIpc.connectionEventSubscribeWindowMs,v.CONNECTION_EVENT_RETRY_MIN_DELAY_MS=q$1.nativeIpc.connectionEventRetryMinDelayMs,v.CONNECTION_EVENT_RETRY_MAX_DELAY_MS=q$1.nativeIpc.connectionEventRetryMaxDelayMs,v.TAURI_IPC_NEGATIVE_CACHE_MS=q$1.nativeIpc.tauriIpcNegativeCacheMs,v.NATIVE_STATUS_IPC_TIMEOUT_MS=2500;var C=v;var ee=class extends z{constructor(e){let t=S(e.bridge,"IpcRuntimeAdapter");super(new C({...e,ipcBridge:t,allowWasmFallback:e.allowWasmFallback??false}));}};
|
|
2
|
-
export{X as a,Q as b,Z as c,q as d,te as e,B as f,J as g,ee as h};
|