openrtc 0.2.0 → 0.2.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.
Files changed (36) hide show
  1. package/LICENSE +92 -0
  2. package/README.md +51 -10
  3. package/dist/{DelegatingRuntimeAdapter-CjHzBEBA.d.ts → DelegatingRuntimeAdapter-BxOcVIx_.d.ts} +23 -2
  4. package/dist/{IpcRuntimeAdapter-CtckyMol.d.ts → IpcRuntimeAdapter-U5AEH0jn.d.ts} +6 -3
  5. package/dist/auth/index.js +1 -1
  6. package/dist/auth/internal.js +1 -1
  7. package/dist/chunk-7DN33VUQ.js +1 -0
  8. package/dist/chunk-BLOEZIFJ.js +1 -0
  9. package/dist/chunk-FQETZQPW.js +2 -0
  10. package/dist/chunk-IUHUYHNZ.js +1 -0
  11. package/dist/chunk-UBEE42VU.js +2 -0
  12. package/dist/chunk-UPO23UMZ.js +3 -0
  13. package/dist/chunk-WNJE3MJF.js +1 -0
  14. package/dist/{factories-CwZiIRg1.d.ts → framing-lxzHEuSr.d.ts} +71 -4
  15. package/dist/index.d.ts +109 -9
  16. package/dist/index.js +2 -2
  17. package/dist/openrtc_bg.wasm +0 -0
  18. package/dist/runtime/WasmRuntimeAdapter.d.ts +2 -2
  19. package/dist/runtime/WasmRuntimeAdapter.js +1 -1
  20. package/dist/runtime/index.d.ts +14 -7
  21. package/dist/runtime/index.js +1 -1
  22. package/dist/runtime/tauri.d.ts +3 -3
  23. package/dist/runtime/tauri.js +1 -1
  24. package/dist/transport/index.d.ts +1 -1
  25. package/dist/transport/index.js +1 -1
  26. package/dist/{types-DyCGvj9l.d.ts → types-D0fRvUbN.d.ts} +31 -10
  27. package/env/index.d.ts +64 -0
  28. package/env/index.mjs +230 -0
  29. package/package.json +19 -10
  30. package/dist/chunk-3VTF5RKW.js +0 -1
  31. package/dist/chunk-JXGKO7SX.js +0 -1
  32. package/dist/chunk-MFT6SOZ6.js +0 -3
  33. package/dist/chunk-SGZWR63E.js +0 -1
  34. package/dist/chunk-VARALO7G.js +0 -1
  35. package/dist/chunk-WOHFM6DI.js +0 -2
  36. package/dist/chunk-YHJOXD46.js +0 -2
package/LICENSE ADDED
@@ -0,0 +1,92 @@
1
+ Required Notice: Copyright (c) 2026 Bryant Hargreaves and OpenRTC contributors.
2
+ Licensor Line of Business: OpenRTC realtime collaboration runtime, SDKs, developer services, and related tools (https://openrtc.app)
3
+
4
+ # PolyForm Shield License 1.0.0
5
+
6
+ <https://polyformproject.org/licenses/shield/1.0.0>
7
+
8
+ ## Acceptance
9
+
10
+ In order to get any license under these terms, you must agree to them as both strict obligations and conditions to all your licenses.
11
+
12
+ ## Copyright License
13
+
14
+ The licensor grants you a copyright license for the software to do everything you might do with the software that would otherwise infringe the licensor's copyright in it for any permitted purpose. However, you may only distribute the software according to [Distribution License](#distribution-license) and make changes or new works based on the software according to [Changes and New Works License](#changes-and-new-works-license).
15
+
16
+ ## Distribution License
17
+
18
+ The licensor grants you an additional copyright license to distribute copies of the software. Your license to distribute covers distributing the software with changes and new works permitted by [Changes and New Works License](#changes-and-new-works-license).
19
+
20
+ ## Notices
21
+
22
+ You must ensure that anyone who gets a copy of any part of the software from you also gets a copy of these terms or the URL for them above, as well as copies of any plain-text lines beginning with `Required Notice:` that the licensor provided with the software. For example:
23
+
24
+ > Required Notice: Copyright Yoyodyne, Inc. (http://example.com)
25
+
26
+ ## Changes and New Works License
27
+
28
+ The licensor grants you an additional copyright license to make changes and new works based on the software for any permitted purpose.
29
+
30
+ ## Patent License
31
+
32
+ The licensor grants you a patent license for the software that covers patent claims the licensor can license, or becomes able to license, that you would infringe by using the software.
33
+
34
+ ## Noncompete
35
+
36
+ Any purpose is a permitted purpose, except for providing any product that competes with the software or any product the licensor or any of its affiliates provides using the software.
37
+
38
+ ## Competition
39
+
40
+ Goods and services compete even when they provide functionality through different kinds of interfaces or for different technical platforms. Applications can compete with services, libraries with plugins, frameworks with development tools, and so on, even if they're written in different programming languages or for different computer architectures. Goods and services compete even when provided free of charge. If you market a product as a practical substitute for the software or another product, it definitely competes.
41
+
42
+ ## New Products
43
+
44
+ If you are using the software to provide a product that does not compete, but the licensor or any of its affiliates brings your product into competition by providing a new version of the software or another product using the software, you may continue using versions of the software available under these terms beforehand to provide your competing product, but not any later versions.
45
+
46
+ ## Discontinued Products
47
+
48
+ You may begin using the software to compete with a product or service that the licensor or any of its affiliates has stopped providing, unless the licensor includes a plain-text line beginning with `Licensor Line of Business:` with the software that mentions that line of business. For example:
49
+
50
+ > Licensor Line of Business: YoyodyneCMS Content Management System (http://example.com/cms)
51
+
52
+ ## Sales of Business
53
+
54
+ If the licensor or any of its affiliates sells a line of business developing the software or using the software to provide a product, the buyer can also enforce [Noncompete](#noncompete) for that product.
55
+
56
+ ## Fair Use
57
+
58
+ You may have "fair use" rights for the software under the law. These terms do not limit them.
59
+
60
+ ## No Other Rights
61
+
62
+ These terms do not allow you to sublicense or transfer any of your licenses to anyone else, or prevent the licensor from granting licenses to anyone else. These terms do not imply any other licenses.
63
+
64
+ ## Patent Defense
65
+
66
+ If you make any written claim that the software infringes or contributes to infringement of any patent, your patent license for the software granted under these terms ends immediately. If your company makes such a claim, your patent license ends immediately for work on behalf of your company.
67
+
68
+ ## Violations
69
+
70
+ The first time you are notified in writing that you have violated any of these terms, or done anything with the software not covered by your licenses, your licenses can nonetheless continue if you come into full compliance with these terms, and take practical steps to correct past violations, within 32 days of receiving notice. Otherwise, all your licenses end immediately.
71
+
72
+ ## No Liability
73
+
74
+ ***As far as the law allows, the software comes as is, without any warranty or condition, and the licensor will not be liable to you for any damages arising out of these terms or the use or nature of the software, under any kind of legal claim.***
75
+
76
+ ## Definitions
77
+
78
+ The **licensor** is the individual or entity offering these terms, and the **software** is the software the licensor makes available under these terms.
79
+
80
+ A **product** can be a good or service, or a combination of them.
81
+
82
+ **You** refers to the individual or entity agreeing to these terms.
83
+
84
+ **Your company** is any legal entity, sole proprietorship, or other kind of organization that you work for, plus all its affiliates.
85
+
86
+ **Affiliates** means the other organizations than an organization has control over, is under the control of, or is under common control with.
87
+
88
+ **Control** means ownership of substantially all the assets of an entity, or the power to direct its management and policies by vote, contract, or otherwise. Control can be direct or indirect.
89
+
90
+ **Your licenses** are all the licenses granted to you for the software under these terms.
91
+
92
+ **Use** means anything you do with the software requiring one of your licenses.
package/README.md CHANGED
@@ -8,27 +8,40 @@ It does not implement a second realtime engine. It exposes the Rust runtime to:
8
8
 
9
9
  ## Recommended Usage
10
10
 
11
- Use the OpenRTC client entry points for new integrations:
11
+ Use the OpenRTC client entry points for new integrations, and choose the
12
+ avenue that matches your product:
13
+
14
+ - `user-scoped` for a signed-in user's durable device mesh
15
+ - `space` for a small live shared namespace
16
+ - rooms for intentional group membership
17
+ - tickets/share grants for explicit one-off pairing without a roster
12
18
 
13
19
  ```ts
14
20
  import { OpenRTC } from 'openrtc';
15
21
 
16
22
  const client = OpenRTC({
17
23
  apiKey: 'pk_live_...',
24
+ discoveryMode: 'user-scoped',
18
25
  authMode: 'external',
19
26
  });
20
27
 
21
28
  await client.connect();
29
+ await client.devices.startSession({
30
+ deviceName: 'Work Laptop',
31
+ });
22
32
  ```
23
33
 
24
34
  For normal app code, the default flow is:
25
35
 
26
- 1. discover or select a `deviceId`
27
- 2. call `client.peers.connect(...)` or `client.devices.connect(...)`
28
- 3. wait for `client.peers.waitConnected(deviceId)`
29
- 4. open app channel streams with `client.channels.openBi(...)` / `client.channels.openUni(...)`
36
+ 1. discover or select a device
37
+ 2. open a named logical app channel with `client.channels.connect({ device, channelId })`
38
+ 3. send and receive app payloads on that channel
30
39
 
31
- Low-level peer handles returned by runtime methods, along with `openPeerBi(deviceId)` and `openPeerUni(deviceId)`, remain available for advanced runtime flows, but they are not the default integration model.
40
+ `channels.connect(...)` owns the peer dial, readiness wait, channel selection,
41
+ roster-ticket reuse, and default `session` lifecycle scope. Use `client.peers.connect(...)`,
42
+ `client.channels.openBi(...)`, `connectScoped(...)`, `openPeerBi(...)`, or
43
+ `openPeerUni(...)` only when you need explicit lifecycle, stream, or transport
44
+ control.
32
45
 
33
46
  ## Naming Guide
34
47
 
@@ -51,7 +64,25 @@ const client = OpenRTC({
51
64
 
52
65
  - Use `space` instead of `spaceKey` in app code.
53
66
  - Use `spaceTokenProvider` and `spaceToken(...)` for scoped shared-space auth.
54
- - Use `client.devices.*`, `client.peers.*`, and `client.channels.*` before reaching for lower-level runtime names.
67
+ - Use `client.devices.*`, `client.rooms.*`, `client.tickets.*`,
68
+ `client.channels.*`, and `client.peers.*` before reaching for lower-level
69
+ runtime names.
70
+
71
+ ## Discovery Avenues
72
+
73
+ OpenRTC discovery is not one generic live device list:
74
+
75
+ - User-scope/user-device is the persistent owned-device avenue. Devices remain
76
+ visible while `presenceStatus` degrades `online` -> `idle` -> `offline`, and
77
+ are removed only by explicit deletion or offline retention expiry.
78
+ - Spaces and rooms are ephemeral collaboration avenues. Active rosters may
79
+ filter or clean up stale entries.
80
+ - Ticket-only/share flows do not use a hosted discovery roster; the ticket or
81
+ grant is the bootstrap avenue.
82
+
83
+ Status-aware device APIs should preserve presence-only changes and merge
84
+ authoritative roster refreshes with live watch state so no avenue-specific
85
+ device disappears just because one read model missed it.
55
86
 
56
87
  ## What This Package Owns
57
88
  - runtime factories and adapters
@@ -77,8 +108,8 @@ Those responsibilities belong to the Rust runtime and the host platform adapter.
77
108
 
78
109
  The recommended TypeScript extension path is:
79
110
 
80
- 1. wait for a Rust-backed connected peer session
81
- 2. open a bidirectional or unidirectional stream
111
+ 1. choose the public avenue (`user-scoped`, `space`, room, or ticket/share)
112
+ 2. open a named logical channel with `client.channels.connect(...)`
82
113
  3. implement your own framing and message semantics in app code
83
114
 
84
115
  This keeps the runtime responsible for peer/session establishment while leaving
@@ -106,15 +137,25 @@ full ALPN plugin layer.
106
137
  - `openrtc-tauri`
107
138
  - `createTauriIpcBridge()`
108
139
  - `TauriRuntimeAdapter`
140
+ - Rust plugin crate: `openrtc-tauri-plugin`
109
141
  - `openrtc/runtime/tauri` remains as a deprecated compatibility shim for one release cycle
110
142
 
143
+ For Tauri desktop/mobile apps, use `OpenRTC.native(options)` with the
144
+ `openrtc-tauri` bridge and register `openrtc-tauri-plugin` in the Rust Tauri
145
+ builder. Do not copy product-owned RTC command files into new apps. The plugin
146
+ owns the native IPC command set and delegates lifecycle, discovery, presence,
147
+ auto-connect, and connection state to one `openrtc::client::Client`. Do not use
148
+ `OpenRTC(options)` inside a Tauri shell unless you intentionally want the
149
+ browser/WASM runtime for a prototype; that path bypasses the native Rust runtime
150
+ and can hide native lifecycle/presence issues from tests.
151
+
111
152
  ## Auth Model
112
153
  - `anonymous`: no Pluto auth required
113
154
  - `required`: Pluto auth required; the SDK may initiate Pluto SSO
114
155
  - `external`: Pluto auth still required, but the host app acquires it and injects it into the runtime
115
156
 
116
157
  ## Design Rule
117
- If a feature requires discovery, signaling, presence, or lifecycle state, the TypeScript package should delegate to Rust rather than reimplement it locally, except for the scoped browser Firebase host layer where the official browser SDK is the source of truth.
158
+ If a feature requires discovery, signaling, presence, or lifecycle state, the TypeScript package should delegate to Rust rather than reimplement it locally, except for the scoped browser Firebase host layer where the official browser SDK is the source of truth. In both cases, keep the avenue semantics intact: persistent user-device rosters are not space/room live rosters.
118
159
 
119
160
  ## Allowed vs. Not Allowed
120
161
 
@@ -1,4 +1,4 @@
1
- import { D as DiscoveryMode, A as AuthMode, S as SignalingMode, E as ExplicitFileDataSendParams, I as ISignalingBackend, R as RuntimeIdentity, a as Device, b as DeviceStatusSnapshot, P as PeerSessionSnapshot, c as ResolvedPeerIdentity, M as ManagedConnectionRecord, d as SignalingEnvelope, e as DeviceEvent, f as SignalingSession, g as SessionEvent, L as LocalDeviceInfo, N as NativeManagedSessionStartResult, G as GrantScope, B as BackendPeerBiStream, h as BackendPeerUniStream, i as NativeConnectResult, j as BackendConnectionState } from './types-DyCGvj9l.js';
1
+ import { D as DiscoveryMode, A as AuthMode, S as SignalingMode, E as ExplicitFileDataSendParams, I as ISignalingBackend, R as RuntimeIdentity, a as Device, b as DeviceStatusSnapshot, P as PeerSessionSnapshot, c as ResolvedPeerIdentity, M as ManagedConnectionRecord, d as SignalingEnvelope, e as DeviceEvent, f as SignalingSession, g as SessionEvent, L as LocalDeviceInfo, N as NativeManagedSessionStartResult, G as GrantScope, B as BackendPeerBiStream, h as BackendPeerUniStream, i as NativeConnectResult, j as BackendConnectionState } from './types-D0fRvUbN.js';
2
2
 
3
3
  type RuntimeAdapterKind = 'browser-wasm' | 'native-ipc' | 'tauri-ipc' | 'unknown';
4
4
  interface RuntimeCapabilities {
@@ -58,9 +58,29 @@ interface RuntimeCapabilityProfile {
58
58
  };
59
59
  nativeProtocols: RuntimeCapabilities['nativeProtocols'];
60
60
  }
61
+ interface NativeRuntimeTransportFeatureStatus {
62
+ compiled?: boolean;
63
+ enabled?: boolean;
64
+ }
65
+ interface NativeRuntimeStatusSnapshot {
66
+ ready?: boolean;
67
+ nodeId?: string | null;
68
+ node_id?: string | null;
69
+ transport?: {
70
+ irohQuic?: NativeRuntimeTransportFeatureStatus;
71
+ irohLan?: NativeRuntimeTransportFeatureStatus;
72
+ webRtc?: NativeRuntimeTransportFeatureStatus;
73
+ webRtcLan?: NativeRuntimeTransportFeatureStatus;
74
+ moq?: NativeRuntimeTransportFeatureStatus;
75
+ ble?: NativeRuntimeTransportFeatureStatus;
76
+ irohRelayOnly?: boolean;
77
+ irohRelayTransportPolicy?: string | null;
78
+ };
79
+ }
61
80
  declare const BROWSER_WASM_RUNTIME_CAPABILITIES: RuntimeCapabilities;
62
81
  declare const NATIVE_IPC_RUNTIME_CAPABILITIES: RuntimeCapabilities;
63
82
  declare function cloneRuntimeCapabilities(capabilities: RuntimeCapabilities): RuntimeCapabilities;
83
+ declare function runtimeCapabilitiesFromNativeStatus(status: NativeRuntimeStatusSnapshot | null | undefined, allowWasmFallback?: boolean): RuntimeCapabilities;
64
84
  declare function runtimeCapabilityProfile(capabilities: RuntimeCapabilities): RuntimeCapabilityProfile;
65
85
 
66
86
  type AuthContext = {
@@ -150,6 +170,7 @@ declare abstract class DelegatingRuntimeAdapter implements ISignalingBackend {
150
170
  registerSessionToken(token: string, scope: GrantScope, maxConnections: number): Promise<void>;
151
171
  revokeSessionTokensByScope(scope: GrantScope): Promise<string[]>;
152
172
  openPeerBi(id: string, timeoutMs?: number): Promise<BackendPeerBiStream>;
173
+ incoming_streams(): Promise<ReadableStream<unknown>>;
153
174
  openPeerNativeBi(id: string, label: string, timeoutMs?: number): Promise<BackendPeerBiStream>;
154
175
  openPeerBiTransportOnly(id: string, timeoutMs?: number): Promise<BackendPeerBiStream>;
155
176
  openPeerUni(id: string, timeoutMs?: number): Promise<BackendPeerUniStream>;
@@ -177,4 +198,4 @@ declare abstract class DelegatingRuntimeAdapter implements ISignalingBackend {
177
198
  setCoreClient(client: unknown): void;
178
199
  }
179
200
 
180
- export { type AuthContext as A, BROWSER_WASM_RUNTIME_CAPABILITIES as B, DelegatingRuntimeAdapter as D, NATIVE_IPC_RUNTIME_CAPABILITIES as N, type RuntimeCapabilities as R, type WasmBridgeOptions as W, type RuntimeCapabilityProfile as a, type RuntimeAdapterKind as b, cloneRuntimeCapabilities as c, runtimeCapabilityProfile as r };
201
+ export { type AuthContext as A, BROWSER_WASM_RUNTIME_CAPABILITIES as B, DelegatingRuntimeAdapter as D, NATIVE_IPC_RUNTIME_CAPABILITIES as N, type RuntimeCapabilities as R, type WasmBridgeOptions as W, type RuntimeCapabilityProfile as a, type RuntimeAdapterKind as b, type NativeRuntimeStatusSnapshot as c, type NativeRuntimeTransportFeatureStatus as d, cloneRuntimeCapabilities as e, runtimeCapabilityProfile as f, runtimeCapabilitiesFromNativeStatus as r };
@@ -1,5 +1,5 @@
1
- import { C as ClientOptions } from './types-DyCGvj9l.js';
2
- import { W as WasmBridgeOptions, D as DelegatingRuntimeAdapter } from './DelegatingRuntimeAdapter-CjHzBEBA.js';
1
+ import { C as ClientOptions } from './types-D0fRvUbN.js';
2
+ import { W as WasmBridgeOptions, D as DelegatingRuntimeAdapter } from './DelegatingRuntimeAdapter-BxOcVIx_.js';
3
3
 
4
4
  type PlutoIpcUnlisten = () => void | Promise<void>;
5
5
  interface PlutoIpcBridge {
@@ -7,6 +7,9 @@ interface PlutoIpcBridge {
7
7
  listen<T = unknown>(event: string, handler: (payload: T) => void): Promise<PlutoIpcUnlisten>;
8
8
  isAvailable?(): boolean | Promise<boolean>;
9
9
  }
10
+ type NativeIpcFailureKind = 'command-unavailable' | 'runtime-unavailable' | 'timeout' | 'unknown';
11
+ declare function classifyNativeIpcFailure(error: unknown): NativeIpcFailureKind;
12
+ declare function isNativeIpcCommandUnavailable(error: unknown): boolean;
10
13
 
11
14
  interface NativeIpcBridgeOptions extends WasmBridgeOptions {
12
15
  allowWasmFallback?: boolean;
@@ -22,4 +25,4 @@ declare class IpcRuntimeAdapter extends DelegatingRuntimeAdapter {
22
25
  constructor(options: IpcRuntimeAdapterOptions);
23
26
  }
24
27
 
25
- export { IpcRuntimeAdapter as I, type NativeIpcBridgeOptions as N, type PlutoIpcBridge as P, type IpcRuntimeAdapterOptions as a, type PlutoIpcUnlisten as b };
28
+ export { IpcRuntimeAdapter as I, type NativeIpcBridgeOptions as N, type PlutoIpcBridge as P, type IpcRuntimeAdapterOptions as a, type NativeIpcFailureKind as b, type PlutoIpcUnlisten as c, classifyNativeIpcFailure as d, isNativeIpcCommandUnavailable as i };
@@ -1 +1 @@
1
- export{D as authHost,C as getAuthHost,B as registerDesktopAuthRelay}from'../chunk-YHJOXD46.js';
1
+ export{E as authHost,D as getAuthHost,C as registerDesktopAuthRelay}from'../chunk-FQETZQPW.js';
@@ -1 +1 @@
1
- export{B as registerDesktopAuthRelay}from'../chunk-YHJOXD46.js';
1
+ export{C as registerDesktopAuthRelay}from'../chunk-FQETZQPW.js';
@@ -0,0 +1 @@
1
+ import {g,h}from'./chunk-UBEE42VU.js';function c(){return g()}var i=class extends h{constructor(r){super({...r,bridge:g(),allowWasmFallback:r.allowWasmFallback??false});}};export{c as a,i as b};
@@ -0,0 +1 @@
1
+ var e=["iroh","iroh-quic","iroh-relay","iroh-lan","ble","webrtc","webrtc-lan","moq"],t=new Set(e);function r(o){if(typeof o!="string")return;let n=o.trim().toLowerCase();return t.has(n)?n:void 0}function i(o){let n=r(o);return n==="iroh"||n==="iroh-quic"||n==="iroh-relay"||n==="iroh-lan"||n==="ble"}function a(o){let n=r(o);return n==="iroh-quic"||n==="iroh-lan"||n==="ble"}function l(o){let n=r(o);return n==="webrtc"||n==="webrtc-lan"||n==="moq"}function s(o){let n=r(o);return n==="webrtc"||n==="webrtc-lan"}function c(o){let n=r(o);return n==="webrtc"||n==="moq"}export{e as a,r as b,i as c,a as d,l as e,s as f,c as g};
@@ -0,0 +1,2 @@
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};
@@ -0,0 +1 @@
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};
@@ -0,0 +1,2 @@
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};