@limrun/ui 0.22.5 → 0.22.7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/components/remote-control.d.ts +15 -0
- package/dist/core/device-stream.d.ts +1 -0
- package/dist/core/stream-options.d.ts +10 -0
- package/dist/core/stream-utils.d.ts +10 -0
- package/dist/core-B3nWmNki.js +2 -0
- package/dist/{core-nbvkIrvp.mjs → core-B7MkSLE_.mjs} +950 -899
- package/dist/core.cjs +1 -1
- package/dist/core.js +4 -4
- package/dist/{duo-frame-Bm0hprn9.js → duo-frame-Bpou_8n1.js} +1 -1
- package/dist/{duo-frame-BCmB9_5p.mjs → duo-frame-BvOU1zvh.mjs} +2 -2
- package/dist/{duo-view-tUJbbWoS.js → duo-view-DbnkRRU-.js} +1 -1
- package/dist/{duo-view-C07GD_5E.mjs → duo-view-DuGDgUyB.mjs} +3 -3
- package/dist/index.cjs +1 -1
- package/dist/index.js +2 -2
- package/dist/lite.cjs +1 -1
- package/dist/lite.js +2 -2
- package/dist/{macbook-frame-Dm6ko0j9.mjs → macbook-frame-Bhu3fUB7.mjs} +1 -1
- package/dist/{macbook-frame-BxJfxUcU.js → macbook-frame-DASJ960L.js} +1 -1
- package/dist/remote-control-D_851mel.js +1 -0
- package/dist/remote-control-cQIifCub.mjs +1723 -0
- package/package.json +1 -1
- package/dist/core-BCBQrYsk.js +0 -2
- package/dist/remote-control-BX6dzHtt.mjs +0 -1712
- package/dist/remote-control-CEVcOPQZ.js +0 -1
|
@@ -226,6 +226,21 @@ export interface RemoteControlProps {
|
|
|
226
226
|
* track mid-stream, and when capture stops.
|
|
227
227
|
*/
|
|
228
228
|
onMicrophoneStateChange?: (state: MicrophoneState) => void;
|
|
229
|
+
/**
|
|
230
|
+
* Plays the device's speaker output in sync with the screen
|
|
231
|
+
* when false. Defaults to true, and the device sends no sound while every
|
|
232
|
+
* viewer is muted. Unmute from a click handler or after other user
|
|
233
|
+
* interaction, because browsers refuse sound before it. Changing it never
|
|
234
|
+
* reconnects the stream.
|
|
235
|
+
*/
|
|
236
|
+
speakerMuted?: boolean;
|
|
237
|
+
/**
|
|
238
|
+
* Fires when the browser refuses to play the sound, for example when the
|
|
239
|
+
* audio arrives or reconnects long after the click that unmuted it. The
|
|
240
|
+
* sound stays off until the next click or key press on the page, unless the
|
|
241
|
+
* caller sets `speakerMuted` first.
|
|
242
|
+
*/
|
|
243
|
+
onSpeakerBlocked?: () => void;
|
|
229
244
|
}
|
|
230
245
|
export interface RemoteControlHandle {
|
|
231
246
|
openUrl: (url: string) => void;
|
|
@@ -6,6 +6,7 @@ export declare function createDeviceStream(initialOptions: DeviceStreamOptions):
|
|
|
6
6
|
start: () => void;
|
|
7
7
|
stop: () => void;
|
|
8
8
|
attachVideo: (video: HTMLVideoElement, display?: StreamDisplay) => () => void;
|
|
9
|
+
attachAudio: (audio: HTMLAudioElement) => () => void;
|
|
9
10
|
attachFrameSink: (sink: DeviceFrameSink, display?: StreamDisplay) => () => void;
|
|
10
11
|
dispose: () => void;
|
|
11
12
|
getState: () => DeviceStreamState;
|
|
@@ -45,6 +45,16 @@ export interface DeviceStreamLiveOptions {
|
|
|
45
45
|
onCameraDemandChange?: (active: boolean, granted?: boolean, camera?: CameraCaptureInfo) => void;
|
|
46
46
|
onCameraStats?: (stats: CameraStreamStats | null) => void;
|
|
47
47
|
onMicrophoneStateChange?: (state: MicrophoneState) => void;
|
|
48
|
+
/**
|
|
49
|
+
* False asks the device to send its speaker output, which
|
|
50
|
+
* elements passed to `attachAudio` play in sync with the screen. Defaults to
|
|
51
|
+
* true, so a stream nobody listens to carries no sound. Muting those
|
|
52
|
+
* elements stays with the caller, because only a user gesture lets a
|
|
53
|
+
* browser play sound.
|
|
54
|
+
*/
|
|
55
|
+
speakerMuted?: boolean;
|
|
56
|
+
/** The browser refused unmuted speaker audio, so an attached audio element went muted. */
|
|
57
|
+
onSpeakerBlocked?: () => void;
|
|
48
58
|
}
|
|
49
59
|
export type DeviceStreamOptions = DeviceStreamLiveOptions & {
|
|
50
60
|
/** Disable device input and outbound media. Enforce access with a server-issued watch token. */
|
|
@@ -1,5 +1,15 @@
|
|
|
1
1
|
export declare const debugLog: (...args: any[]) => void;
|
|
2
2
|
export declare const debugWarn: (...args: any[]) => void;
|
|
3
|
+
/** Drops a pending retry, because the caller chose mute or unmute itself. */
|
|
4
|
+
export declare const cancelSpeakerRetry: (audio: HTMLMediaElement) => void;
|
|
5
|
+
/**
|
|
6
|
+
* Plays an element that carries the device's speaker audio. Browsers
|
|
7
|
+
* refuse sound outside a recent user gesture; the element then keeps playing
|
|
8
|
+
* muted, `onBlocked` lets the caller show that the sound is off, and the next
|
|
9
|
+
* click or key press anywhere on the page turns the sound back on. A caller
|
|
10
|
+
* that mutes in between cancels that with `cancelSpeakerRetry`.
|
|
11
|
+
*/
|
|
12
|
+
export declare const playSpeaker: (audio: HTMLMediaElement, onBlocked: () => void) => void;
|
|
3
13
|
export declare const safeInvoke: <Args extends unknown[]>(label: string, fn: ((...args: Args) => unknown) | undefined, ...args: Args) => void;
|
|
4
14
|
export type DevicePlatform = 'ios' | 'android' | 'macos';
|
|
5
15
|
export declare const detectPlatform: (url: string) => DevicePlatform;
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
"use strict";const Z={INJECT_KEYCODE:0,INJECT_TEXT:1,INJECT_TOUCH_EVENT:2,INJECT_TWO_FINGER_TOUCH_EVENT:18,INJECT_SCROLL_EVENT:3,BACK_OR_SCREEN_ON:4,EXPAND_NOTIFICATION_PANEL:5,EXPAND_SETTINGS_PANEL:6,COLLAPSE_PANELS:7,GET_CLIPBOARD:8,SET_CLIPBOARD:9,SET_DISPLAY_POWER:10,ROTATE_DEVICE:11,INJECT_MOUSE_EVENT:40,INJECT_MAC_KEY:41,INJECT_MAC_SCROLL:42},Pe={DOWN:0,UP:1,MOVE:2},Le={ACTION_DOWN:0,ACTION_UP:1,ACTION_MOVE:2,ACTION_CANCEL:3,ACTION_POINTER_DOWN:5,ACTION_POINTER_UP:6,BUTTON_PRIMARY:1,BUTTON_SECONDARY:2,BUTTON_TERTIARY:4},a={ACTION_DOWN:0,ACTION_UP:1,META_NONE:0,META_SHIFT_ON:1,META_ALT_ON:2,META_CTRL_ON:4096,META_META_ON:65536,KEYCODE_UNKNOWN:0,KEYCODE_SOFT_LEFT:1,KEYCODE_SOFT_RIGHT:2,KEYCODE_HOME:3,KEYCODE_BACK:4,KEYCODE_CALL:5,KEYCODE_ENDCALL:6,KEYCODE_0:7,KEYCODE_1:8,KEYCODE_2:9,KEYCODE_3:10,KEYCODE_4:11,KEYCODE_5:12,KEYCODE_6:13,KEYCODE_7:14,KEYCODE_8:15,KEYCODE_9:16,KEYCODE_STAR:17,KEYCODE_POUND:18,DPAD_UP:19,DPAD_DOWN:20,DPAD_LEFT:21,DPAD_RIGHT:22,KEYCODE_DPAD_CENTER:23,KEYCODE_VOLUME_UP:24,KEYCODE_VOLUME_DOWN:25,KEYCODE_POWER:26,KEYCODE_CAMERA:27,KEYCODE_CLEAR:28,KEYCODE_A:29,KEYCODE_B:30,KEYCODE_C:31,KEYCODE_D:32,KEYCODE_E:33,KEYCODE_F:34,KEYCODE_G:35,KEYCODE_H:36,KEYCODE_I:37,KEYCODE_J:38,KEYCODE_K:39,KEYCODE_L:40,KEYCODE_M:41,KEYCODE_N:42,KEYCODE_O:43,KEYCODE_P:44,KEYCODE_Q:45,KEYCODE_R:46,KEYCODE_S:47,KEYCODE_T:48,KEYCODE_U:49,KEYCODE_V:50,KEYCODE_W:51,KEYCODE_X:52,KEYCODE_Y:53,KEYCODE_Z:54,KEYCODE_COMMA:55,KEYCODE_PERIOD:56,KEYCODE_ALT_LEFT:57,KEYCODE_ALT_RIGHT:58,KEYCODE_SHIFT_LEFT:59,KEYCODE_SHIFT_RIGHT:60,KEYCODE_TAB:61,KEYCODE_SPACE:62,KEYCODE_SYM:63,KEYCODE_EXPLORER:64,KEYCODE_ENVELOPE:65,ENTER:66,DEL:67,KEYCODE_GRAVE:68,KEYCODE_MINUS:69,KEYCODE_EQUALS:70,KEYCODE_LEFT_BRACKET:71,KEYCODE_RIGHT_BRACKET:72,KEYCODE_BACKSLASH:73,KEYCODE_SEMICOLON:74,KEYCODE_APOSTROPHE:75,KEYCODE_SLASH:76,KEYCODE_AT:77,KEYCODE_NUM:78,KEYCODE_HEADSETHOOK:79,KEYCODE_FOCUS:80,KEYCODE_PLUS:81,MENU:82,KEYCODE_NOTIFICATION:83,KEYCODE_SEARCH:84,KEYCODE_MEDIA_PLAY_PAUSE:85,KEYCODE_MEDIA_STOP:86,KEYCODE_MEDIA_NEXT:87,KEYCODE_MEDIA_PREVIOUS:88,KEYCODE_MEDIA_REWIND:89,KEYCODE_MEDIA_FAST_FORWARD:90,KEYCODE_MUTE:91,KEYCODE_PAGE_UP:92,KEYCODE_PAGE_DOWN:93,KEYCODE_PICTSYMBOLS:94,KEYCODE_SWITCH_CHARSET:95,KEYCODE_BUTTON_A:96,KEYCODE_BUTTON_B:97,KEYCODE_BUTTON_C:98,KEYCODE_BUTTON_X:99,KEYCODE_BUTTON_Y:100,KEYCODE_BUTTON_Z:101,KEYCODE_BUTTON_L1:102,KEYCODE_BUTTON_R1:103,KEYCODE_BUTTON_L2:104,KEYCODE_BUTTON_R2:105,KEYCODE_BUTTON_THUMBL:106,KEYCODE_BUTTON_THUMBR:107,KEYCODE_BUTTON_START:108,KEYCODE_BUTTON_SELECT:109,KEYCODE_BUTTON_MODE:110,KEYCODE_ESCAPE:111,FORWARD_DEL:112,KEYCODE_CTRL_LEFT:113,KEYCODE_CTRL_RIGHT:114,KEYCODE_CAPS_LOCK:115,KEYCODE_SCROLL_LOCK:116,KEYCODE_META_LEFT:117,KEYCODE_META_RIGHT:118,KEYCODE_FUNCTION:119,KEYCODE_SYSRQ:120,KEYCODE_BREAK:121,KEYCODE_MOVE_HOME:122,KEYCODE_MOVE_END:123,KEYCODE_INSERT:124,KEYCODE_FORWARD:125,KEYCODE_MEDIA_PLAY:126,KEYCODE_MEDIA_PAUSE:127,KEYCODE_MEDIA_CLOSE:128,KEYCODE_MEDIA_EJECT:129,KEYCODE_MEDIA_RECORD:130,KEYCODE_F1:131,KEYCODE_F2:132,KEYCODE_F3:133,KEYCODE_F4:134,KEYCODE_F5:135,KEYCODE_F6:136,KEYCODE_F7:137,KEYCODE_F8:138,KEYCODE_F9:139,KEYCODE_F10:140,KEYCODE_F11:141,KEYCODE_F12:142,KEYCODE_NUM_LOCK:143,KEYCODE_NUMPAD_0:144,KEYCODE_NUMPAD_1:145,KEYCODE_NUMPAD_2:146,KEYCODE_NUMPAD_3:147,KEYCODE_NUMPAD_4:148,KEYCODE_NUMPAD_5:149,KEYCODE_NUMPAD_6:150,KEYCODE_NUMPAD_7:151,KEYCODE_NUMPAD_8:152,KEYCODE_NUMPAD_9:153,KEYCODE_NUMPAD_DIVIDE:154,KEYCODE_NUMPAD_MULTIPLY:155,KEYCODE_NUMPAD_SUBTRACT:156,KEYCODE_NUMPAD_ADD:157,KEYCODE_NUMPAD_DOT:158,KEYCODE_NUMPAD_COMMA:159,KEYCODE_NUMPAD_ENTER:160,KEYCODE_NUMPAD_EQUALS:161,KEYCODE_NUMPAD_LEFT_PAREN:162,KEYCODE_NUMPAD_RIGHT_PAREN:163,KEYCODE_VOLUME_MUTE:164,KEYCODE_INFO:165,KEYCODE_CHANNEL_UP:166,KEYCODE_CHANNEL_DOWN:167,KEYCODE_ZOOM_IN:168,KEYCODE_ZOOM_OUT:169,KEYCODE_TV:170,KEYCODE_WINDOW:171,KEYCODE_GUIDE:172,KEYCODE_DVR:173,KEYCODE_BOOKMARK:174,KEYCODE_CAPTIONS:175,KEYCODE_SETTINGS:176,KEYCODE_TV_POWER:177,KEYCODE_TV_INPUT:178,KEYCODE_STB_POWER:179,KEYCODE_STB_INPUT:180,KEYCODE_AVR_POWER:181,KEYCODE_AVR_INPUT:182,KEYCODE_PROG_RED:183,KEYCODE_PROG_GREEN:184,KEYCODE_PROG_YELLOW:185,KEYCODE_PROG_BLUE:186,KEYCODE_APP_SWITCH:187,KEYCODE_LANGUAGE_SWITCH:204,KEYCODE_ASSIST:219,KEYCODE_BRIGHTNESS_DOWN:220,KEYCODE_BRIGHTNESS_UP:221,KEYCODE_SLEEP:223,KEYCODE_WAKEUP:224,KEYCODE_SOFT_SLEEP:276},Pt={KeyA:a.KEYCODE_A,KeyB:a.KEYCODE_B,KeyC:a.KEYCODE_C,KeyD:a.KEYCODE_D,KeyE:a.KEYCODE_E,KeyF:a.KEYCODE_F,KeyG:a.KEYCODE_G,KeyH:a.KEYCODE_H,KeyI:a.KEYCODE_I,KeyJ:a.KEYCODE_J,KeyK:a.KEYCODE_K,KeyL:a.KEYCODE_L,KeyM:a.KEYCODE_M,KeyN:a.KEYCODE_N,KeyO:a.KEYCODE_O,KeyP:a.KEYCODE_P,KeyQ:a.KEYCODE_Q,KeyR:a.KEYCODE_R,KeyS:a.KEYCODE_S,KeyT:a.KEYCODE_T,KeyU:a.KEYCODE_U,KeyV:a.KEYCODE_V,KeyW:a.KEYCODE_W,KeyX:a.KEYCODE_X,KeyY:a.KEYCODE_Y,KeyZ:a.KEYCODE_Z,Digit0:a.KEYCODE_0,Digit1:a.KEYCODE_1,Digit2:a.KEYCODE_2,Digit3:a.KEYCODE_3,Digit4:a.KEYCODE_4,Digit5:a.KEYCODE_5,Digit6:a.KEYCODE_6,Digit7:a.KEYCODE_7,Digit8:a.KEYCODE_8,Digit9:a.KEYCODE_9,Backquote:a.KEYCODE_GRAVE,Minus:a.KEYCODE_MINUS,Equal:a.KEYCODE_EQUALS,BracketLeft:a.KEYCODE_LEFT_BRACKET,BracketRight:a.KEYCODE_RIGHT_BRACKET,Backslash:a.KEYCODE_BACKSLASH,Semicolon:a.KEYCODE_SEMICOLON,Quote:a.KEYCODE_APOSTROPHE,Comma:a.KEYCODE_COMMA,Period:a.KEYCODE_PERIOD,Slash:a.KEYCODE_SLASH,Space:a.KEYCODE_SPACE,Tab:a.KEYCODE_TAB,Escape:a.KEYCODE_ESCAPE,ArrowUp:a.DPAD_UP,ArrowDown:a.DPAD_DOWN,ArrowLeft:a.DPAD_LEFT,ArrowRight:a.DPAD_RIGHT,Enter:a.ENTER,Backspace:a.DEL,Delete:a.FORWARD_DEL,Home:a.KEYCODE_MOVE_HOME,End:a.KEYCODE_MOVE_END,PageUp:a.KEYCODE_PAGE_UP,PageDown:a.KEYCODE_PAGE_DOWN,Insert:a.KEYCODE_INSERT,F1:a.KEYCODE_F1,F2:a.KEYCODE_F2,F3:a.KEYCODE_F3,F4:a.KEYCODE_F4,F5:a.KEYCODE_F5,F6:a.KEYCODE_F6,F7:a.KEYCODE_F7,F8:a.KEYCODE_F8,F9:a.KEYCODE_F9,F10:a.KEYCODE_F10,F11:a.KEYCODE_F11,F12:a.KEYCODE_F12,ShiftLeft:a.KEYCODE_SHIFT_LEFT,ShiftRight:a.KEYCODE_SHIFT_RIGHT,ControlLeft:a.KEYCODE_CTRL_LEFT,ControlRight:a.KEYCODE_CTRL_RIGHT,AltLeft:a.KEYCODE_ALT_LEFT,AltRight:a.KEYCODE_ALT_RIGHT,MetaLeft:a.KEYCODE_META_LEFT,MetaRight:a.KEYCODE_META_RIGHT,ContextMenu:a.MENU,Numpad0:a.KEYCODE_NUMPAD_0,Numpad1:a.KEYCODE_NUMPAD_1,Numpad2:a.KEYCODE_NUMPAD_2,Numpad3:a.KEYCODE_NUMPAD_3,Numpad4:a.KEYCODE_NUMPAD_4,Numpad5:a.KEYCODE_NUMPAD_5,Numpad6:a.KEYCODE_NUMPAD_6,Numpad7:a.KEYCODE_NUMPAD_7,Numpad8:a.KEYCODE_NUMPAD_8,Numpad9:a.KEYCODE_NUMPAD_9,NumpadDivide:a.KEYCODE_NUMPAD_DIVIDE,NumpadMultiply:a.KEYCODE_NUMPAD_MULTIPLY,NumpadSubtract:a.KEYCODE_NUMPAD_SUBTRACT,NumpadAdd:a.KEYCODE_NUMPAD_ADD,NumpadDecimal:a.KEYCODE_NUMPAD_DOT,NumpadComma:a.KEYCODE_NUMPAD_COMMA,NumpadEnter:a.KEYCODE_NUMPAD_ENTER,NumpadEqual:a.KEYCODE_NUMPAD_EQUALS},pr={KeyA:0,KeyS:1,KeyD:2,KeyF:3,KeyH:4,KeyG:5,KeyZ:6,KeyX:7,KeyC:8,KeyV:9,IntlBackslash:10,KeyB:11,KeyQ:12,KeyW:13,KeyE:14,KeyR:15,KeyY:16,KeyT:17,Digit1:18,Digit2:19,Digit3:20,Digit4:21,Digit6:22,Digit5:23,Equal:24,Digit9:25,Digit7:26,Minus:27,Digit8:28,Digit0:29,BracketRight:30,KeyO:31,KeyU:32,BracketLeft:33,KeyI:34,KeyP:35,Enter:36,KeyL:37,KeyJ:38,Quote:39,KeyK:40,Semicolon:41,Backslash:42,Comma:43,Slash:44,KeyN:45,KeyM:46,Period:47,Tab:48,Space:49,Backquote:50,Backspace:51,Escape:53,MetaRight:54,MetaLeft:55,ShiftLeft:56,CapsLock:57,AltLeft:58,ControlLeft:59,ShiftRight:60,AltRight:61,ControlRight:62,Fn:63,F17:64,NumpadDecimal:65,NumpadMultiply:67,NumpadAdd:69,NumLock:71,NumpadDivide:75,NumpadEnter:76,NumpadSubtract:78,F18:79,F19:80,NumpadEqual:81,Numpad0:82,Numpad1:83,Numpad2:84,Numpad3:85,Numpad4:86,Numpad5:87,Numpad6:88,Numpad7:89,F20:90,Numpad8:91,Numpad9:92,F5:96,F6:97,F7:98,F3:99,F8:100,F9:101,F11:103,F13:105,F16:106,F14:107,F10:109,ContextMenu:110,F12:111,F15:113,Help:114,Insert:114,Home:115,PageUp:116,Delete:117,F4:118,End:119,F2:120,PageDown:121,F1:122,ArrowLeft:123,ArrowRight:124,ArrowDown:125,ArrowUp:126};function ft(t){return pr[t]}function Lt(t,e,r,o,u,l,i=1,h=0,D=0){const p=new ArrayBuffer(32),S=new DataView(p);let w=0;S.setUint8(w,Z.INJECT_TOUCH_EVENT),w+=1;const N=t===Le.ACTION_POINTER_DOWN?Le.ACTION_DOWN:t===Le.ACTION_POINTER_UP?Le.ACTION_UP:t;return S.setUint8(w,N),w+=1,S.setBigInt64(w,BigInt(e),!0),w+=8,S.setInt32(w,Math.round(u),!0),w+=4,S.setInt32(w,Math.round(l),!0),w+=4,S.setUint16(w,r,!0),w+=2,S.setUint16(w,o,!0),w+=2,S.setInt16(w,Math.round(i*65535),!0),w+=2,S.setInt32(w,h,!0),w+=4,S.setInt32(w,D,!0),p}function mr(t,e,r,o,u,l,i){const h=new ArrayBuffer(24),D=new DataView(h);let p=0;return D.setUint8(p,Z.INJECT_TWO_FINGER_TOUCH_EVENT),p+=1,D.setUint8(p,t),p+=1,D.setInt32(p,Math.round(o),!0),p+=4,D.setInt32(p,Math.round(u),!0),p+=4,D.setInt32(p,Math.round(l),!0),p+=4,D.setInt32(p,Math.round(i),!0),p+=4,D.setUint16(p,e,!0),p+=2,D.setUint16(p,r,!0),p+=2,D.setUint16(p,0,!0),h}function Ft(t,e=!0){const o=new TextEncoder().encode(t),u=new ArrayBuffer(14+o.length),l=new DataView(u);let i=0;return l.setUint8(i,Z.SET_CLIPBOARD),i+=1,l.setBigInt64(i,BigInt(0),!1),i+=8,l.setUint8(i,e?1:0),i+=1,l.setUint32(i,o.length,!1),i+=4,new Uint8Array(u,i).set(o),u}function Ze(t,e,r=0,o=0){const u=new ArrayBuffer(14),l=new DataView(u);let i=0;return l.setUint8(i,Z.INJECT_KEYCODE),i+=1,l.setUint8(i,t),i+=1,l.setInt32(i,e,!0),i+=4,l.setInt32(i,r,!0),i+=4,l.setInt32(i,o,!0),u}function Cr(t,e,r,o,u,l){const i=new ArrayBuffer(18),h=new DataView(i);return h.setUint8(0,Z.INJECT_MOUSE_EVENT),h.setUint8(1,t),h.setInt32(2,Math.round(o),!0),h.setInt32(6,Math.round(u),!0),h.setUint16(10,e,!0),h.setUint16(12,r,!0),h.setInt32(14,l,!0),i}function Bt(t,e){const r=new ArrayBuffer(4),o=new DataView(r);return o.setUint8(0,Z.INJECT_MAC_KEY),o.setUint8(1,t),o.setUint16(2,e,!0),r}function Or(t,e,r,o,u,l){const i=new ArrayBuffer(21),h=new DataView(i);return h.setUint8(0,Z.INJECT_MAC_SCROLL),h.setInt32(1,Math.round(r),!0),h.setInt32(5,Math.round(o),!0),h.setUint16(9,t,!0),h.setUint16(11,e,!0),h.setFloat32(13,u,!0),h.setFloat32(17,l,!0),i}function Dr(t){return t?.displays.find(e=>e.id===(t.angleDegrees<90?"outer":"inner"))}function xt(t){return t===2?2:t===3?1:t===4?3:0}class _r{constructor(e){this.send=e}send;screenId;turns=0;held;get active(){return this.held!==void 0}setDisplay(e,r=xt(e?.orientation)){(this.screenId!==e?.screenId||this.turns!==r)&&this.release(),this.screenId=e?.screenId,this.turns=r}touch(e,r,o,u=!1){if(this.screenId===void 0)return;const l=Wt(r,o,u?0:this.turns);e==="begin"&&(this.release(),this.held={screenId:this.screenId,...l}),this.held&&(Object.assign(this.held,l),e==="end"?this.release():this.send(e==="begin"?0:2,this.held.screenId,l.x,l.y))}release(){if(!this.held)return;const{screenId:e,x:r,y:o}=this.held;this.held=void 0,this.send(1,e,r,o)}}const gr={width:164.6,height:117.8,depth:5.2};function Wt(t,e,r){return t=Math.max(0,Math.min(1,t)),e=Math.max(0,Math.min(1,e)),r===1?{x:e,y:1-t}:r===2?{x:1-t,y:1-e}:r===3?{x:1-e,y:t}:{x:t,y:e}}function Tr(t){return Number.isFinite(t)&&t>=0&&t<=180}function yr(t,e){return{x:Math.max(0,Math.min(1,t)),y:Math.max(0,Math.min(1,1-e))}}function Sr(t,e,r){return e&&(t||!r)?"touch":t?"ignore":"orbit"}function qt(t,e,r,o){if(!Number.isInteger(t)||t<0||t>3||!Number.isInteger(e)||e<1||e>255||!Number.isFinite(r)||!Number.isFinite(o)||r<0||r>1||o<0||o>1)throw new RangeError("Invalid display touch coordinates");const u=new ArrayBuffer(12),l=new DataView(u);return l.setUint8(0,19),l.setUint8(1,t),l.setUint8(2,e),l.setFloat32(4,r,!0),l.setFloat32(8,o,!0),u}class Kr{constructor(e,r){this.send=e,this.failed=r}send;failed;latest;running=!1;stopped=!1;set(e){this.stopped||!Tr(e)||(this.latest=e,this.flush())}stop(){this.stopped=!0,this.latest=void 0}async flush(){if(!(this.running||this.stopped)){this.running=!0;try{for(;this.latest!==void 0&&!this.stopped;){const e=this.latest;this.latest=void 0,await this.send(e)}}catch(e){this.latest=void 0,this.stopped||this.failed(e)}finally{this.running=!1}}}}const Ar={side:"Sleep/Wake",volumeUp:"Volume Up",volumeDown:"Volume Down"};class Mr{constructor(e,r){this.send=e,this.failed=r}send;failed;held;tail=Promise.resolve();timeout;press(e){this.held||(this.held=e,this.enqueue(e,!0),this.timeout=setTimeout(()=>this.release(),1e4))}release(){if(!this.held)return;clearTimeout(this.timeout);const e=this.held;this.held=void 0,this.enqueue(e,!1)}enqueue(e,r){this.tail=this.tail.then(()=>this.send(e,r)).catch(this.failed)}}const et="Accessibility unavailable on this device.",tt=500,Vt=(t,e)=>Math.abs(t.x-e.x)<.5&&Math.abs(t.y-e.y)<.5&&Math.abs(t.width-e.width)<.5&&Math.abs(t.height-e.height)<.5,vr=t=>Math.max(0,t.width)*Math.max(0,t.height),wr=t=>{const e=t.find(r=>r.frame&&r.frame.width>0&&r.frame.height>0);return e?.frame?((Math.abs(e.frame.x)>.5||Math.abs(e.frame.y)>.5)&&console.warn(`[ax-tree] iOS root frame is not anchored at (0,0): (${e.frame.x},${e.frame.y}). Element positions may be slightly off from the rendered video.`),{x:0,y:0,width:e.frame.width,height:e.frame.height}):{x:0,y:0,width:1,height:1}},Nr=t=>{const e={};return typeof t.AXUniqueId=="string"&&t.AXUniqueId.length>0&&(e.AXUniqueId=t.AXUniqueId),typeof t.AXLabel=="string"&&t.AXLabel.length>0&&(e.AXLabel=t.AXLabel),typeof t.type=="string"&&t.type.length>0&&(e.className=t.type),e},br=t=>{const e={};for(const[r,o]of Object.entries(t))r!=="children"&&(e[r]=o);return e};function $t(t){const e=Array.isArray(t)?t:[t],r=wr(e),o=[],u=(l,i)=>{if(o.length>=tt)return;const h=l.frame;if(h&&h.width>0&&h.height>0&&!Vt(h,r)){const p=l.role_description||l.role||"",S=(typeof l.AXLabel=="string"?l.AXLabel:"")||(typeof l.title=="string"?l.title:"")||"";o.push({id:typeof l.AXUniqueId=="string"&&l.AXUniqueId.length>0?l.AXUniqueId:i,path:i,label:S,value:typeof l.AXValue=="string"?l.AXValue:"",role:p,type:typeof l.type=="string"?l.type:"",enabled:l.enabled!==!1,focused:l.focused===!0,frame:{x:h.x,y:h.y,width:h.width,height:h.height},selectors:Nr(l),raw:br(l)})}const D=Array.isArray(l.children)?l.children:[];for(let p=0;p<D.length&&o.length<tt;p++)u(D[p],`${i}.${p}`)};for(let l=0;l<e.length&&o.length<tt;l++)u(e[l],String(l));return{platform:"ios",screen:{width:r.width,height:r.height},elements:o,capturedAt:Date.now()}}const Yr=t=>{let e={x:0,y:0,width:1,height:1},r=0;for(const o of t){const u=o.parsedBounds;if(!u)continue;const l=u.right-u.left,i=u.bottom-u.top,h=Math.max(0,l)*Math.max(0,i);h>r&&(r=h,e={x:0,y:0,width:l,height:i})}return e},Ir=t=>{const e={};return typeof t.resourceId=="string"&&t.resourceId.length>0&&(e.resourceId=t.resourceId),typeof t.contentDesc=="string"&&t.contentDesc.length>0&&(e.contentDesc=t.contentDesc),typeof t.text=="string"&&t.text.length>0&&(e.text=t.text),typeof t.className=="string"&&t.className.length>0&&(e.className=t.className),e};function Ht(t){const e=Yr(t),r=[];for(let o=0;o<t.length&&r.length<tt;o++){const u=t[o],l=u.parsedBounds;if(!l)continue;const i=Math.max(0,l.right-l.left),h=Math.max(0,l.bottom-l.top);if(i<=0||h<=0)continue;const D={x:l.left,y:l.top,width:i,height:h};if(Vt(D,{x:0,y:0,width:e.width,height:e.height}))continue;const p=u.contentDesc||u.text||"",S=u.className||"";r.push({id:u.resourceId&&u.resourceId.length>0?u.resourceId:u.contentDesc&&u.contentDesc.length>0?`cd:${u.contentDesc}`:String(o),path:String(o),label:p,value:typeof u.text=="string"?u.text:"",role:S,type:S,enabled:u.enabled!==!1,focused:u.focused===!0,frame:D,selectors:Ir(u),raw:{...u}})}return{platform:"android",screen:{width:e.width,height:e.height},elements:r,capturedAt:Date.now()}}function Rr(t,e){const r=Math.max(0,t.x),o=Math.max(0,t.y),u=Math.min(e.width,t.x+t.width),l=Math.min(e.height,t.y+t.height),i=Math.max(0,u-r),h=Math.max(0,l-o);return i>0&&h>0?{x:r,y:o,width:i,height:h}:null}function Jt(t,e){if(t===e)return!0;if(t.id!==e.id||t.path!==e.path||t.label!==e.label||t.value!==e.value||t.role!==e.role||t.type!==e.type||t.enabled!==e.enabled||t.focused!==e.focused)return!1;const r=t.frame,o=e.frame;return r.x===o.x&&r.y===o.y&&r.width===o.width&&r.height===o.height}function Gt(t,e){if(t===e)return!0;if(!t||!e||t.platform!==e.platform||t.screen.width!==e.screen.width||t.screen.height!==e.screen.height||t.elements.length!==e.elements.length)return!1;for(let r=0;r<t.elements.length;r++)if(!Jt(t.elements[r],e.elements[r]))return!1;return!0}function kr(t,e,r){let o=null,u=1/0;for(const l of t.elements){const i=l.frame;if(e<i.x||r<i.y||e>i.x+i.width||r>i.y+i.height)continue;const h=vr(i);h<u&&(u=h,o=l)}return o}function Ur(t,e){if(e==="ios"){if(t.selectors.AXUniqueId)return`client.tapElement({ AXUniqueId: ${JSON.stringify(t.selectors.AXUniqueId)} })`;if(t.selectors.AXLabel){const r=t.selectors.className?`, type: ${JSON.stringify(t.selectors.className)}`:"";return`client.tapElement({ AXLabel: ${JSON.stringify(t.selectors.AXLabel)}${r} })`}return null}return t.selectors.resourceId?`client.tap({ selector: { resourceId: ${JSON.stringify(t.selectors.resourceId)} } })`:t.selectors.contentDesc?`client.tap({ selector: { contentDesc: ${JSON.stringify(t.selectors.contentDesc)} } })`:t.selectors.text?`client.tap({ selector: { text: ${JSON.stringify(t.selectors.text)} } })`:null}function jt(t){const e=t.role||t.type||"";if(!e)return"element";let r=e.replace(/^AX/,"");return r.includes(".")&&(r=r.split(".").pop()),r==="GenericElement"?"Element":(r=r.replace(/([a-z])([A-Z])/g,"$1 $2"),r)}const Nt=80;function Pr(t){const e=jt(t),r=t.label||t.value||"";if(!r)return e;const o=r.length>Nt?r.slice(0,Nt).trimEnd()+"…":r;return`${e} · ${o}`}const Lr=500,Fr=2e3,bt=5e3,Br=8e3,xr=1200,Wr=250,qr=()=>`ax-rc-${Date.now()}-${Math.random().toString(36).slice(2,8)}`;class Vr{platform;send;onSnapshot;onStatusChange;baseIntervalMs;maxBackoffMs;androidElementTreeOptions;pending=new Map;running=!1;timer;currentInterval;lastSnapshot=null;inflight=!1;lastBumpAtMs=0;boostUntilMs=0;status="idle";constructor(e){this.platform=e.platform,this.send=e.send,this.onSnapshot=e.onSnapshot,this.onStatusChange=e.onStatusChange,this.baseIntervalMs=e.baseIntervalMs??Lr,this.maxBackoffMs=e.maxBackoffMs??Fr,this.androidElementTreeOptions=e.androidElementTreeOptions,this.currentInterval=this.baseIntervalMs}start(){this.running||(this.running=!0,this.currentInterval=this.baseIntervalMs,this.boostUntilMs=0,this.setStatus("starting"),this.runOnce())}stop(){this.running&&(this.running=!1,this.timer!==void 0&&(window.clearTimeout(this.timer),this.timer=void 0),this.failAllPending("Inspector stopped"),this.lastSnapshot=null,this.setStatus("idle"),this.onSnapshot(null))}getStatus(){return this.status}setStatus(e,r){if(this.status!==e&&(this.status=e,!!this.onStatusChange))try{this.onStatusChange(e,r)}catch(o){console.error("[AxFetcher] onStatusChange threw:",o)}}bumpActivity(){if(!this.running)return;const e=Date.now();this.boostUntilMs=e+xr;const r=Math.max(150,Math.floor(this.baseIntervalMs/2));if(e-this.lastBumpAtMs<r){this.currentInterval=this.baseIntervalMs;return}this.lastBumpAtMs=e,this.currentInterval=this.baseIntervalMs,this.timer!==void 0&&(window.clearTimeout(this.timer),this.timer=void 0),this.inflight||this.runOnce()}async refresh(){const e=await this.requestOnce();return this.running&&this.deliver(e),e}getLatest(){return this.lastSnapshot}handleMessage(e){if(!e||typeof e.id!="string")return!1;const r=e.id;if(!this.pending.get(r))return!1;if(this.platform==="ios"){if(e.type!=="elementTreeResult")return!1;const h=typeof e.error=="string"?e.error:null;if(h)return this.settleReject(r,new Error(h)),!0;const D=typeof e.json=="string"?e.json:"";try{const p=JSON.parse(D),S=$t(p);this.settleResolve(r,S)}catch(p){this.settleReject(r,p instanceof Error?p:new Error(String(p)))}return!0}if(e.type!=="getElementTreeResult")return!1;const u=e.error;if(u&&typeof u=="object"){const h=typeof u.message=="string"?u.message:"getElementTree failed";return this.settleReject(r,new Error(h)),!0}const l=e.payload,i=Array.isArray(l?.nodes)?l.nodes:[];try{const h=Ht(i);this.settleResolve(r,h)}catch(h){this.settleReject(r,h instanceof Error?h:new Error(String(h)))}return!0}buildRequest(e){return this.platform==="ios"?{type:"elementTree",id:e}:{type:"getElementTree",id:e,...this.androidElementTreeOptions}}async requestOnce(){const e=qr();return new Promise((r,o)=>{const u=window.setTimeout(()=>{this.pending.delete(e),o(new Error("elementTree request timed out"))},Br+(this.androidElementTreeOptions?.waitForIdleTimeoutMs??0));this.pending.set(e,{resolve:r,reject:o,timer:u}),this.send(this.buildRequest(e))||(window.clearTimeout(u),this.pending.delete(e),o(new Error("elementTree send failed (WebSocket not open)")))})}async runOnce(){if(this.running&&!this.inflight){this.inflight=!0;try{const e=await this.requestOnce();if(!this.running)return;this.deliver(e)}catch(e){if(!this.running)return;const r=e instanceof Error?e.message:String(e),o=/unavailable|not (yet )?running|failed|timeout/i.test(r);this.currentInterval=o?bt:Math.min(this.currentInterval*2,this.maxBackoffMs),this.setStatus(o?"unavailable":"error",r)}finally{this.inflight=!1,this.scheduleNext()}}}deliver(e){const r=this.lastSnapshot;if(Gt(r,e)){this.currentInterval=Math.min(this.currentInterval*2,this.maxBackoffMs),this.lastSnapshot=e,e.errors?.includes(et)||this.setStatus("ready");return}this.lastSnapshot=e,this.currentInterval=this.baseIntervalMs,e.errors?.includes(et)?(this.currentInterval=bt,this.setStatus("unavailable",et)):this.setStatus("ready"),this.onSnapshot(e)}scheduleNext(){if(!this.running)return;this.timer!==void 0&&window.clearTimeout(this.timer);const e=Date.now()<this.boostUntilMs?Math.min(Wr,this.currentInterval):this.currentInterval;this.timer=window.setTimeout(()=>{this.timer=void 0,this.runOnce()},e)}settleResolve(e,r){const o=this.pending.get(e);o&&(window.clearTimeout(o.timer),this.pending.delete(e),o.resolve(r))}settleReject(e,r){const o=this.pending.get(e);o&&(window.clearTimeout(o.timer),this.pending.delete(e),o.reject(r))}failAllPending(e){for(const[r,o]of this.pending.entries())window.clearTimeout(o.timer),o.reject(new Error(e)),this.pending.delete(r)}}function Yt(t,e){if(e!=null&&(!Number.isFinite(e)||e<0||e>4e3)){console.warn("RemoteControl: jitterBufferTargetMs must be a finite number between 0 and 4000.");return}if(!("jitterBufferTarget"in t))return;const r=e??null;try{t.jitterBufferTarget!==r&&(t.jitterBufferTarget=r)}catch(o){console.warn("RemoteControl: could not set the jitter buffer target.",o)}}const Xt=`(function(){"use strict";let e,t;self.onmessage=async({data:s})=>{s.type==="start"?(e=new AbortController,t=s.readable.pipeTo(s.writable,{signal:e.signal}).catch(o=>{e?.signal.aborted||self.postMessage({type:"error",message:String(o)})})):s.type==="stop"&&(e?.abort(),await t,self.postMessage({type:"stopped"}),self.close())}})();
|
|
2
|
+
`,It=typeof self<"u"&&self.Blob&&new Blob(["(self.URL || self.webkitURL).revokeObjectURL(self.location.href);",Xt],{type:"text/javascript;charset=utf-8"});function $r(t){let e;try{if(e=It&&(self.URL||self.webkitURL).createObjectURL(It),!e)throw"";const r=new Worker(e,{name:t?.name});return r.addEventListener("error",()=>{(self.URL||self.webkitURL).revokeObjectURL(e)}),r}catch{return new Worker("data:text/javascript;charset=utf-8,"+encodeURIComponent(Xt),{name:t?.name})}}function Hr(t,e,r){const{MediaStreamTrackProcessor:o,MediaStreamTrackGenerator:u}=globalThis,l=e.getVideoTracks()[0];let i,h,D,p,S=!1;const w=()=>{S||(S=!0,i?.stop(),h?.stop(),D&&(D.postMessage({type:"stop"}),p=setTimeout(()=>D?.terminate(),1e3)))},N=_=>{t.srcObject=_,t.play().catch(()=>{})},V=_=>{S||(w(),r(_),N(e))};try{if(l&&o&&u){i=l.clone();const _=new o({track:i,maxBufferSize:1}),H=new u({kind:"video"});h=H,D=new $r,D.onmessage=({data:F})=>{F.type==="error"?V(new Error(F.message)):F.type==="stopped"&&(clearTimeout(p),D?.terminate())},D.onerror=F=>V(new Error(F.message)),D.postMessage({type:"start",readable:_.readable,writable:H.writable},[_.readable,H.writable]),N(new MediaStream(e.getTracks().map(F=>F===l?H:F)))}else N(e)}catch(_){V(_)}return w}function Fe(t){return typeof t=="number"&&Number.isFinite(t)}function Se(t,e){if(!(!Fe(t)||!Fe(e)||t<e||e<0))return t-e}class Jr{previous=new Map;reset(){this.previous.clear()}read(e,r,o){const u={timestamp:0,video:[],audio:[]};o==null?u.requestedTargetMs=null:Fe(o)&&o>=0&&o<=4e3&&(u.requestedTargetMs=o);const l=new Map;return e.forEach(i=>{if(i.type!=="inbound-rtp"||!Fe(i.timestamp))return;const h=i.kind??i.mediaType;if(h!=="video"&&h!=="audio")return;const D=r.filter(P=>P.kind===h),p=i.trackIdentifier?D.find(P=>P.trackId===i.trackIdentifier):i.mid!=null?D.find(P=>P.mid===i.mid):D.length===1?D[0]:void 0;if(!p)return;const S=this.previous.get(i.id),N=S?.trackId===p.trackId&&S.stats.ssrc===i.ssrc?S.stats:void 0,V=N?i.timestamp-N.timestamp:void 0,_={id:i.id,trackId:p.trackId,timestamp:i.timestamp};if(V!==void 0&&V>0){_.intervalMs=V;const P=Se(i.jitterBufferEmittedCount,N?.jitterBufferEmittedCount),B=Se(i.jitterBufferDelay,N?.jitterBufferDelay);P!==void 0&&P>0&&B!==void 0&&(_.bufferDelayMs=B/P*1e3);const x=Se(i.bytesReceived,N?.bytesReceived);x!==void 0&&(_.bitrateBps=x*8e3/V)}if(h==="video"){const P={..._,display:p.display??"primary"};if(_.intervalMs!==void 0){const B=Se(i.framesDecoded,N?.framesDecoded);B!==void 0&&(P.fps=B*1e3/_.intervalMs),P.droppedFrames=Se(i.framesDropped,N?.framesDropped),P.freezes=Se(i.freezeCount,N?.freezeCount)}u.video.push(P)}else u.audio.push(_);u.timestamp=Math.max(u.timestamp,i.timestamp),l.set(i.id,N&&i.timestamp<=N.timestamp?S:{stats:i,trackId:p.trackId});const H=i.transportId?e.get(i.transportId):void 0,F=H?.selectedCandidatePairId?e.get(H.selectedCandidatePairId):void 0;F?.state==="succeeded"&&Fe(F.currentRoundTripTime)&&F.currentRoundTripTime>=0&&(u.rttMs=F.currentRoundTripTime*1e3)}),this.previous=l,u.video.length||u.audio.length?u:null}}const dt=new WeakSet;function Gr(t,e,r){const{peer:o,displays:u}=t,l=new Jr;let i,h=!1,D=!1,p=!1,S=0,w=!1,N=!1;const V=()=>!h&&!document.hidden&&o.connectionState==="connected",_=B=>{if(!(!B&&!w)){w=B!==null;try{e()?.(B)}catch(x){console.error('[RemoteControl] customer callback "onPlaybackStats" threw:',x)}}},H=()=>{D=!1,S++,clearTimeout(i),l.reset(),_(null)},F=async()=>{if(p||!V())return;if(dt.has(o)){i=setTimeout(()=>{F()},2e3);return}p=!0,dt.add(o);const B=S;try{const x=await o.getStats();if(B!==S||!V())return;const ce=o.getTransceivers().filter(I=>(I.currentDirection==="recvonly"||I.currentDirection==="sendrecv")&&I.receiver.track.readyState!=="ended").map(I=>({trackId:I.receiver.track.id,kind:I.receiver.track.kind,mid:I.mid,display:u.get(I.receiver)}));_(l.read(x,ce,r())),N=!1}catch(x){if(B!==S||!V())return;N||console.warn("[RemoteControl] could not read playback stats:",x),N=!0,l.reset(),_(null)}finally{p=!1,dt.delete(o),D&&V()&&(i=setTimeout(()=>{F()},B===S?2e3:0))}},P=()=>{if(!V()){H();return}D||(D=!0,F())};return document.addEventListener("visibilitychange",P),o.addEventListener("connectionstatechange",P),P(),()=>{h=!0,document.removeEventListener("visibilitychange",P),o.removeEventListener("connectionstatechange",P),H()}}function jr(t,e){const r=t.createDataChannel("latency-trace-v1",{ordered:!0,negotiated:!0,id:2});let o=!1,u=!1,l=0;return r.onmessage=i=>{if(u)return;let h;try{h=JSON.parse(i.data)}catch(D){console.warn("Invalid latency trace message",D);return}h&&typeof h=="object"&&!Array.isArray(h)&&e(h)},r.onclose=()=>{u=!0,o=!1},{accept(i){o=!u&&i===1},wrap(i){if(!o||i.byteLength===0)return i;const h=new DataView(i),D=h.getUint8(0),p=D===Z.INJECT_MOUSE_EVENT||D===Z.INJECT_MAC_KEY||D===Z.INJECT_MAC_SCROLL,S=i.byteLength===32&&D===Z.INJECT_TOUCH_EVENT&&h.getUint8(1)<=2;if(!p&&!S)return i;const w=new ArrayBuffer(6+i.byteLength),N=new DataView(w);return N.setUint8(0,240),N.setUint8(1,1),N.setUint32(2,++l,!0),new Uint8Array(w,6).set(new Uint8Array(i)),w},close(){u=!0,o=!1,r.onmessage=null,r.onclose=null,r.close()}}}class Xr{generation=0;tail=Promise.resolve();get currentGeneration(){return this.generation}enqueue(e){const r=++this.generation;return this.append(r,e)}enqueueCurrent(e){return this.append(this.generation,e)}append(e,r){const o={generation:e,isCurrent:()=>e===this.generation},u=this.tail.then(()=>r(o));return this.tail=u.catch(()=>{}),u}invalidate(){++this.generation}}function Qr(t){if(!t||typeof t!="object")return null;const e=t;if(e.type!=="cameraRequest"||typeof e.active!="boolean")return null;const r={active:e.active};return(e.facingMode==="user"||e.facingMode==="environment")&&(r.facingMode=e.facingMode),r}function zr(t){const e={frameRate:{ideal:30,max:30}};return t?.facingMode&&(e.facingMode={ideal:t.facingMode}),e}function Zr(t,e){return!t||t.facingMode!==e.facingMode}function en(t){const e=t.getSettings();return{width:e.width,height:e.height,frameRate:e.frameRate,deviceId:e.deviceId,label:t.label||void 0,facingMode:e.facingMode}}function tn(t){return{type:"cameraResult",granted:!0,camera:en(t)}}const se=(...t)=>{window.debugRemoteControl&&console.log(...t)},y=(...t)=>{window.debugRemoteControl&&console.warn(...t)},Rt=["click","keydown"],rt=new WeakMap,Qt=t=>{rt.get(t)?.()},Et=(t,e)=>{if(rt.has(t)){Promise.resolve(t.play()).catch(()=>{});return}Promise.resolve(t.play()).catch(r=>{if(r?.name!=="NotAllowedError"||t.muted)return;t.muted=!0,Promise.resolve(t.play()).catch(()=>{});const o=t.ownerDocument,u=()=>{l(),t.muted=!1,Et(t,e)},l=()=>{for(const i of Rt)o.removeEventListener(i,u,!0);rt.delete(t)};for(const i of Rt)o.addEventListener(i,u,!0);rt.set(t,l),e()})},L=(t,e,...r)=>{if(e)try{e(...r)}catch(o){console.error(`[RemoteControl] customer callback "${t}" threw:`,o)}},zt=t=>t.includes("/android_")?"android":t.includes("/macos_")?"macos":"ios",kt=(t,e)=>{const r=new URL(t);return r.searchParams.set("token",e),r.toString()},ut=3,rn=1e3,nn=15e3,on=3e3,an=4e3;function Ut(){const t=crypto.getRandomValues(new Uint8Array(16));t[6]=t[6]&15|64,t[8]=t[8]&63|128;const e=Array.from(t,r=>r.toString(16).padStart(2,"0")).join("");return`${e.slice(0,8)}-${e.slice(8,12)}-${e.slice(12,16)}-${e.slice(16,20)}-${e.slice(20)}`}function sn(t){let e={...t};const{url:r,deviceModel:o}=e;let u=e.token;const l=e.watchOnly??!1,i=e.sessionId??Ut(),h=e.platform??zt(r??"");let D={connection:"idle",videoReady:!1,controlReady:!1,duo:!1,duoState:null};const p=n=>{D={...D,...n},L("onStateChange",e.onStateChange,D)},S=n=>p({videoReady:n}),w=n=>p({duoState:n}),N=n=>p({duoError:n}),V=n=>p({duo:n}),_=n=>se(n);let H=null,F;const P=()=>{F?.(),F=H&&e.onPlaybackStats?Gr(H,()=>e.onPlaybackStats,()=>e.jitterBufferTargetMs):void 0},B=new Map,x=new Set,ce=new Set,I=new Map;let Ee=!1;const Be=new Map,ht=(n,f,c)=>{f.stop?.(),f.stop=Hr(n,c,d=>y("Video playback fallback:",d))},Ke=new Set;let Ae=null;const pt=n=>{n.srcObject=Ae,Ae&&Et(n,()=>L("onSpeakerBlocked",e.onSpeakerBlocked))},Zt=()=>{Be.clear(),Ae=null;for(const n of Ke)n.srcObject=null;for(const[n,f]of B)f.clear?.(),f.stop?.(),f.stop=void 0,n.srcObject=null};let he=!1,Me=!1,xe=0,g=null,pe=null;const mt=()=>{!pe||pe!==g||pe.readyState===WebSocket.OPEN&&pe.send(JSON.stringify({type:"speakerAudio",sessionId:i,enabled:!(e.speakerMuted??!0)}))};let R=null,W=null,We=null,me,ve,we,qe,Ce,de=0,Ve=0,re=!1,ue=null,Q=null,fe;const nt=new Xr;let Ne=null,$e=null,it=!l&&(e.microphoneEnabled??!1),ot=!1,be=null,te=null,He=0,Ct=Promise.resolve(),Oe=null,Ye=!1,ne=new Map,ee=new Map,le=new Map,ie=new Map,$=null,Ie=null,Ot=0;const Je=n=>{if(n===null&&Ie===null)return;Ie=n;const f=++Ot;queueMicrotask(()=>{f===Ot&&L("onAxSnapshotChange",e.onAxSnapshotChange,n)})};let De=null,_e=new Map;const er=(n,f)=>new Promise((c,d)=>{if(l){d(new Error("Device is watch-only"));return}const K=g;if(!K||K.readyState!==WebSocket.OPEN){d(new Error("Simulator disconnected"));return}const m=Ut(),C=setTimeout(()=>{_e.delete(m),d(new Error("Device control timed out"))},5e3);_e.set(m,{resolve:c,reject:d,timer:C}),K.send(JSON.stringify({type:n,id:m,...f}))}),ge=n=>{De!==n&&(De=n,p({connection:n}),L("onConnectionStateChange",e.onConnectionStateChange,n))},oe=n=>{l||!W||W.readyState!=="open"||(W.send(We?.wrap(n)??n),$?.bumpActivity())},tr=()=>{g&&g.readyState===WebSocket.OPEN&&g.send(JSON.stringify({type:"keepAlive",sessionId:i}))},Dt=()=>{me&&window.clearInterval(me),me=window.setInterval(tr,1e4)},Re=()=>{me&&(window.clearInterval(me),me=void 0)},Ge=()=>{ve&&(window.clearTimeout(ve),ve=void 0)},je=()=>{we&&(window.clearTimeout(we),we=void 0)},ke=()=>{qe&&(window.clearInterval(qe),qe=void 0)},Ue=()=>{Ce!==void 0&&(window.clearTimeout(Ce),Ce=void 0)},rr=()=>{Ye||(Ye=!0,ke(),S(!0),ge("connected"))},J=n=>{for(const f of n.getTracks())try{f.stop()}catch(c){y("track.stop() failed:",c)}},nr=()=>{const n=Q;n&&(Q=null,J(n))},_t=n=>{const f=Ct.then(n).catch(c=>{y("microphone operation failed:",c)});return Ct=f,f},at=()=>it||ot,gt=n=>{const f=`ui-mic-${Date.now()}-${Math.random().toString(36).substring(2,9)}`;Oe=f,n.send(JSON.stringify({type:"microphoneStart",id:f}))},st=()=>_t(()=>ir()),ir=async()=>{const n=He,f=()=>n===He&&at(),c=E=>{L("onMicrophoneStateChange",e.onMicrophoneStateChange,{active:!1,error:E})};if(!f())return;const d=g,K=be;if(!d||d.readyState!==WebSocket.OPEN||!K||te)return;if(!navigator.mediaDevices||typeof navigator.mediaDevices.getUserMedia!="function"){console.warn("[RemoteControl] navigator.mediaDevices.getUserMedia unavailable. getUserMedia requires a secure context (https or http://localhost)."),c("Microphone capture requires a secure context (https)");return}let m=null;try{m=await navigator.mediaDevices.getUserMedia({audio:!0,video:!1})}catch(E){console.warn("[RemoteControl] microphone getUserMedia denied/failed:",E)}if(!f()){m&&J(m);return}if(!m){c("Microphone permission denied or no device available");return}const C=m.getAudioTracks()[0]??null;if(!C){J(m),c("Captured stream has no audio track");return}try{await K.replaceTrack(C)}catch(E){y("replaceTrack(audioTrack) failed:",E),J(m),c("Failed to attach the microphone track to the connection");return}if(!f()){try{await K.replaceTrack(null)}catch(E){y("replaceTrack(null) on stale mic attach failed:",E)}J(m);return}te=m,C.onended=()=>{te===m&&Xe("microphone capture ended by the browser")},gt(d),L("onMicrophoneStateChange",e.onMicrophoneStateChange,{active:!0,label:C.label||void 0})},Xe=n=>(++He,Oe=null,_t(async()=>{const f=be,c=te;if(te=null,f&&c)try{await f.replaceTrack(null)}catch(K){y("replaceTrack(null) on mic detach failed:",K)}c&&J(c);const d=g;if(c&&d&&d.readyState===WebSocket.OPEN){const K=`ui-mic-${Date.now()}-${Math.random().toString(36).substring(2,9)}`;d.send(JSON.stringify({type:"microphoneStop",id:K}))}(c||n)&&L("onMicrophoneStateChange",e.onMicrophoneStateChange,{active:!1,...n!==void 0&&{error:n}})})),Tt=(n,f)=>{let c;try{c=tn(f),console.info(`[RemoteControl] camera capture: ${c.camera?.width}x${c.camera?.height} @ ${c.camera?.frameRate??"?"}fps`+(c.camera?.label?` — ${c.camera.label}`:""))}catch(d){y("getSettings() on outbound camera track failed:",d),c={type:"cameraResult",granted:!0,camera:{label:f.label||void 0}}}n.send(JSON.stringify(c)),L("onCameraDemandChange",e.onCameraDemandChange,!0,!0,c.camera)},or=n=>{if(!n)return;const f=n.indexOf("/"),d=(f>=0?n.slice(f+1):n).toUpperCase();return d==="HEVC"?"H265":d},ar=async()=>{const n=ue,f=e.onCameraStats;if(!n||!f)return;let c;try{c=await n.getStats()}catch{return}let d,K,m;if(c.forEach(U=>{U.type==="outbound-rtp"&&U.kind==="video"?d=U:U.type==="remote-inbound-rtp"&&U.kind==="video"&&(m=U)}),d?.codecId){const U=c.get(d.codecId);U&&(K=U.mimeType)}if(!d)return;const C=d.timestamp??Date.now(),E=$e;let k,b,G;if(E&&C>E.timestamp){const U=(C-E.timestamp)/1e3;if(typeof d.framesEncoded=="number"&&typeof E.framesEncoded=="number"&&(k=Math.max(0,(d.framesEncoded-E.framesEncoded)/U)),typeof d.bytesSent=="number"&&typeof E.bytesSent=="number"&&(b=Math.max(0,(d.bytesSent-E.bytesSent)*8/U)),typeof d.packetsSent=="number"&&typeof E.packetsSent=="number"&&m&&typeof m.packetsLost=="number"&&typeof E.packetsLost=="number"){const A=d.packetsSent-E.packetsSent,ze=m.packetsLost-E.packetsLost;A>0&&(G=Math.max(0,Math.min(100,ze/A*100)))}}$e={timestamp:C,framesEncoded:d.framesEncoded,bytesSent:d.bytesSent,packetsSent:d.packetsSent,packetsLost:m?.packetsLost};const v={codec:or(K),encoderImplementation:d.encoderImplementation,hardwareAccelerated:typeof d.powerEfficientEncoder=="boolean"?d.powerEfficientEncoder:void 0,framesPerSecond:k,framesEncoded:d.framesEncoded,bitrateBps:b,width:d.frameWidth,height:d.frameHeight,qualityLimitationReason:d.qualityLimitationReason,rttMs:typeof m?.roundTripTime=="number"?m.roundTripTime*1e3:void 0,packetsLostPct:G};L("onCameraStats",e.onCameraStats,v)},yt=()=>{Ne===null&&($e=null,Ne=setInterval(()=>{ar()},1e3))},Qe=()=>{Ne!==null&&(clearInterval(Ne),Ne=null),$e=null,L("onCameraStats",e.onCameraStats,null)},sr=(n,f,c,d)=>nt.enqueue(async({isCurrent:K})=>{const m=()=>K()&&d()&&g===f&&ue===c;if(!m())return;if(!n.active){const v=Q;try{await c.replaceTrack(null)}catch(U){y("replaceTrack(null) on camera detach failed:",U)}if(Q===v&&(Q=null,fe=void 0,v&&J(v)),Qe(),!m())return;L("onCameraDemandChange",e.onCameraDemandChange,!1);return}L("onCameraDemandChange",e.onCameraDemandChange,!0);const C=Q,E=C?.getVideoTracks()[0],k=fe;if(E?.readyState==="live"&&k&&!Zr(k,n)){fe=n,Tt(f,E),yt();return}if(C){try{await c.replaceTrack(null)}catch(v){y("replaceTrack(null) before camera switch failed:",v)}if(Q===C&&(Q=null,fe=void 0,J(C)),Qe(),!m())return}if(!navigator.mediaDevices||typeof navigator.mediaDevices.getUserMedia!="function"){if(console.warn("[RemoteControl] navigator.mediaDevices.getUserMedia unavailable. getUserMedia requires a secure context (https or http://localhost). Replying cameraResult granted=false so limulator falls back to black frames."),!m())return;f.send(JSON.stringify({type:"cameraResult",granted:!1})),L("onCameraDemandChange",e.onCameraDemandChange,!0,!1);return}let b=null;try{b=await navigator.mediaDevices.getUserMedia({video:zr(n),audio:!1})}catch(v){console.warn("[RemoteControl] getUserMedia denied/failed:",v)}if(!m()){b&&J(b);return}if(!b){f.send(JSON.stringify({type:"cameraResult",granted:!1})),L("onCameraDemandChange",e.onCameraDemandChange,!0,!1);return}const G=b.getVideoTracks()[0]??null;if(!G){if(J(b),!m())return;f.send(JSON.stringify({type:"cameraResult",granted:!1})),L("onCameraDemandChange",e.onCameraDemandChange,!0,!1);return}try{G.contentHint="motion"}catch{}try{await c.replaceTrack(G)}catch(v){if(y("replaceTrack(videoTrack) failed:",v),J(b),!m())return;f.send(JSON.stringify({type:"cameraResult",granted:!1})),L("onCameraDemandChange",e.onCameraDemandChange,!0,!1);return}if(!m()){try{await c.replaceTrack(null)}catch(v){y("replaceTrack(null) for stale camera attach failed:",v)}J(b);return}try{const v=c.getParameters();(!v.encodings||v.encodings.length===0)&&(v.encodings=[{}]),v.encodings[0].maxBitrate=8e6,v.encodings[0].maxFramerate=30,v.degradationPreference="maintain-framerate",await c.setParameters(v)}catch(v){y("setParameters on outbound camera failed:",v)}if(!m()){try{await c.replaceTrack(null)}catch(v){y("replaceTrack(null) for stale camera finalize failed:",v)}J(b);return}Q=b,fe=n,G.onended=()=>{Q===b&&nt.enqueueCurrent(async({isCurrent:v})=>{if(!(!v()||Q!==b||!d()||g!==f||ue!==c)){try{await c.replaceTrack(null)}catch(U){y("replaceTrack(null) after camera ended failed:",U)}!v()||Q!==b||!d()||g!==f||ue!==c||(Q=null,fe=void 0,J(b),Qe(),f.send(JSON.stringify({type:"cameraResult",granted:!1})),L("onCameraDemandChange",e.onCameraDemandChange,!0,!1))}}).catch(v=>y("camera ended cleanup failed:",v))},m()&&(Tt(f,G),yt())}),Te=()=>{for(const n of ce)n();ce.clear();for(const n of I.values())clearTimeout(n);I.clear();for(const n of ee.values())n(new Error("Simulator disconnected"));for(const n of ie.values())n(new Error("Simulator disconnected"));ee.clear(),ne.clear(),ie.clear(),le.clear(),F?.(),F=void 0,Zt(),H=null;for(const n of _e.values())clearTimeout(n.timer),n.reject(new Error("Simulator disconnected"));_e.clear(),w(null),p({controlReady:!1,videoReady:!1}),je(),Ue(),ke(),$&&($.stop(),$=null),Ie!==null&&Je(null),nt.invalidate(),Qe(),nr(),fe=void 0,ue=null,++He,ot=!1,Oe=null,te&&(J(te),te=null,L("onMicrophoneStateChange",e.onMicrophoneStateChange,{active:!1})),be=null,pe=null,g&&(g.onopen=null,g.onmessage=null,g.onerror=null,g.onclose=null,g.close(),g=null),We?.close(),We=null,R&&(R.onconnectionstatechange=null,R.oniceconnectionstatechange=null,R.ontrack=null,R.onicecandidate=null,R.close(),R=null),W&&(W.onopen=null,W.onclose=null,W.onerror=null,W.close(),W=null)},St=()=>{document.hidden?Re():Dt()},cr=async()=>{if(e.transport)return e.transport.isTerminated?.()??!1;if(typeof navigator<"u"&&navigator.onLine===!1)return!1;let n;try{const d=new URL(r);d.protocol=d.protocol==="wss:"?"https:":d.protocol==="ws:"?"http:":d.protocol,n=kt(d.toString(),u)}catch{return!1}const f=new AbortController,c=window.setTimeout(()=>f.abort(),an);try{return(await fetch(n,{method:"GET",cache:"no-store",signal:f.signal})).status===404}catch{return!1}finally{window.clearTimeout(c)}},lr=()=>{he||(he=!0,de+=1,Ge(),je(),Ue(),Te(),_("Instance terminated"),Re(),ge("terminated"),L("onTerminated",e.onTerminated))},dr=()=>{if(he||Me)return;Me=!0;const n=xe;cr().catch(()=>!1).then(f=>{n===xe&&(Me=!1,f&&lr())})},ye=(n,f)=>{if(he||f!==de)return;if(dr(),re){if(e.autoReconnect===!1){_(`Connection failed after it was established: ${n}`),Re(),ge("failed"),Te();return}_(`Reconnecting after established session dropped: ${n}`),re=!1,Ve=-1}Ge();const c=Ve+1;if(c>=ut){_(`Connection failed after ${ut} attempts: ${n}`),Re(),ge("failed"),Te();return}_(`Retrying connection (${c+1}/${ut})`),ge("reconnecting"),Te(),ve=window.setTimeout(()=>{ve=void 0,f===de&&Kt(c)},rn)},Kt=async(n=0)=>{const{openUrl:f,axPollIntervalMs:c,axMaxBackoffMs:d,androidElementTreeOptions:K}=e;if(he)return;const m=de+1;de=m,Ve=n,re=!1,n===0&&De!=="reconnecting"&&ge("connecting"),Ge(),je(),ke(),Ye=!1,S(!1),Te();const C=()=>m===de;we=window.setTimeout(()=>{we=void 0,!(!C()||re)&&ye("Connection did not succeed within 15 seconds",m)},nn);try{const E=e.transport?await e.transport.connect():new WebSocket(kt(r,u));if(!C()){E.close();return}if(g=E,await new Promise((O,s)=>{let Y=!1;const q=()=>M(()=>s(new Error("Connection stopped")));ce.add(q);const T=window.setTimeout(()=>M(()=>s(new Error("WebSocket connection timeout"))),3e4),M=z=>{Y||(Y=!0,ce.delete(q),window.clearTimeout(T),z())};E.onopen=()=>{!C()||g!==E||M(O)},E.onerror=z=>{!C()||g!==E||(_("WebSocket error: "+z),M(()=>s(new Error("WebSocket connection failed"))))},E.onclose=()=>{!C()||g!==E||(_("WebSocket closed"),M(()=>s(new Error("WebSocket closed before connection was established"))))},E.readyState===WebSocket.OPEN?M(O):E.readyState!==WebSocket.CONNECTING&&M(()=>s(new Error("WebSocket is closed")))}),!C()||g!==E)return;E.onerror=O=>{!C()||g!==E||_("WebSocket error: "+O)},E.onclose=()=>{!C()||g!==E||_("WebSocket closed")};const k=new Promise((O,s)=>{let Y=!1;const q=()=>T(()=>s(new Error("Connection stopped")));ce.add(q);const T=j=>{Y||(Y=!0,ce.delete(q),window.clearTimeout(M),E.removeEventListener("message",z),j())},M=window.setTimeout(()=>T(()=>s(new Error("RTCConfiguration timeout"))),3e4),z=j=>{if(!(!C()||g!==E))try{const X=JSON.parse(j.data);if(X.type==="signalingError"&&X.requestType==="requestRtcConfiguration"&&X.sessionId===i){const hr=typeof X.error=="string"?X.error:"Unable to load streaming configuration";T(()=>s(new Error(hr)))}else X.type==="rtcConfiguration"&&T(()=>O({rtcConfiguration:X.rtcConfiguration,cameraSupported:X.cameraSupported===!0,foldSupported:X.foldSupported===!0}))}catch(X){console.error("Error handling RTC configuration:",X),T(()=>s(X))}};E.addEventListener("message",z),E.send(JSON.stringify({type:"requestRtcConfiguration",sessionId:i}))}),{rtcConfiguration:b,cameraSupported:G,foldSupported:v}=await k;if(!C()||g!==E)return;const U=o==="iphone-duo"||v;V(U);const A=new RTCPeerConnection({...b,iceTransportPolicy:"relay"});R=A;const ze={peer:A,displays:new Map};H=ze,P(),A.addTransceiver("audio",{direction:"recvonly"});const fr=A.addTransceiver("video",{direction:"recvonly"}),Er=U?A.addTransceiver("video",{direction:"recvonly"}):null,wt=!l&&(h==="ios"||G),ct=wt?A.addTransceiver("video",{direction:"sendonly"}):null;if(ue=ct?.sender??null,be=(wt?A.addTransceiver("audio",{direction:"sendonly"}):null)?.sender??null,RTCRtpReceiver.getCapabilities){const O=RTCRtpReceiver.getCapabilities("video");if(O&&O.codecs){const Y=O.codecs.sort((q,T)=>{const M=z=>{const j=z.mimeType.toLowerCase();return j.includes("h265")||j.includes("hevc")?1:j.includes("h264")||j.includes("avc")?2:3};return M(q)-M(T)});fr.setCodecPreferences(Y),Er?.setCodecPreferences(Y),se("Set codec preferences:",Y.map(q=>q.mimeType).join(", "))}}if(ct&&RTCRtpSender.getCapabilities){const O=RTCRtpSender.getCapabilities("video");if(O&&O.codecs){const s=new Set(["42e01f","42e028","640c1f"]),Y=T=>{const M=T.mimeType.toLowerCase(),j=(T.sdpFmtpLine||"").toLowerCase().match(/profile-level-id=([0-9a-f]{6})/),X=j?j[1]:"";return M==="video/h265"||M==="video/hevc"?1:M==="video/h264"&&s.has(X)?2:M==="video/h264"?3:M==="video/vp9"?4:M==="video/vp8"?5:M==="video/rtx"||M==="video/red"||M==="video/ulpfec"?0:6},q=[...O.codecs].sort((T,M)=>Y(T)-Y(M));try{ct.setCodecPreferences(q),se("Outbound camera codec preferences:",q.map(T=>`${T.mimeType}${T.sdpFmtpLine?`[${T.sdpFmtpLine}]`:""}`).join(", "))}catch(T){y("Failed to set outbound camera codec preferences:",T)}}}const ae=A.createDataChannel("control",{ordered:!0,negotiated:!0,id:1});W=ae;const lt=!l&&!U&&e.onTrace?jr(A,O=>{C()&&R===A&&L("onTrace",e.onTrace,O)}):null;if(We=lt,ae.onopen=()=>{if(!C()||W!==ae||g!==E)return;re=!0,p({controlReady:!l}),je(),_("Control channel opened"),U&&E.send(JSON.stringify({type:"getFoldState",id:"duo-capabilities"})),!$&&h!=="macos"&&($=new Vr({platform:h,baseIntervalMs:c,maxBackoffMs:d,androidElementTreeOptions:K,send:s=>{if(!g||g.readyState!==WebSocket.OPEN)return!1;try{return g.send(JSON.stringify(s)),!0}catch{return!1}},onSnapshot:Je,onStatusChange:(s,Y)=>{L("onAxStatusChange",e.onAxStatusChange,s,Y)}}),(e.inspectMode===!0||e.inspectMode==="hover-only")&&$.start());const O=()=>{!C()||Ye||W!==ae||g!==E||E.readyState!==WebSocket.OPEN||E.send(JSON.stringify({type:"requestFrame",sessionId:i}))};if(O(),ke(),qe=window.setInterval(()=>{if(!C()||Ye||W!==ae||g!==E||E.readyState!==WebSocket.OPEN){ke();return}O()},250),!l&&f){try{const s=decodeURIComponent(f);_("Opening URL"),E.send(JSON.stringify({type:"openUrl",url:s,sessionId:i}))}catch(s){console.error({error:s},"Error decoding URL, falling back to the original URL"),E.send(JSON.stringify({type:"openUrl",url:f,sessionId:i}))}$?.bumpActivity()}},ae.onclose=()=>{!C()||W!==ae||(p({controlReady:!1}),_("Control channel closed"))},ae.onerror=O=>{!C()||W!==ae||(console.error("Control channel error:",O),_("Control channel error: "+O))},A.onconnectionstatechange=()=>{!C()||R!==A||(_("Connection state: "+A.connectionState),A.connectionState==="failed"&&re&&ye("WebRTC connection entered failed state",m))},A.oniceconnectionstatechange=()=>{if(!C()||R!==A)return;const O=A.iceConnectionState;if(_("ICE state: "+O),O==="connected"||O==="completed"){Ue(),at()&&!te&&st();return}if(O==="failed"){Ue(),re&&ye("ICE connection entered failed state",m);return}O==="disconnected"&&re&&e.autoReconnect!==!1&&Ce===void 0&&(Ce=window.setTimeout(()=>{Ce=void 0,!(!C()||R!==A)&&A.iceConnectionState==="disconnected"&&ye("ICE stayed disconnected past grace period",m)},on))},A.ontrack=O=>{if(!C()||R!==A)return;Yt(O.receiver,e.jitterBufferTargetMs);const s=O.track.id==="duo-inner"||O.streams.some(Y=>Y.id==="duo-inner");if(O.track.kind==="video"&&ze.displays.set(O.receiver,s?"inner":"primary"),_("Received remote track: "+O.track.kind),O.track.kind==="video"){const Y=s?"inner":"primary",q=U?new MediaStream([O.track]):O.streams[0]??new MediaStream([O.track]);Be.set(Y,q);for(const[T,M]of B)M.display===Y&&ht(T,M,q)}if(O.track.kind==="audio"){Ae=new MediaStream([O.track]);for(const Y of Ke)pt(Y)}},A.onicecandidate=O=>{if(!(!C()||R!==A||g!==E))if(O.candidate&&E.readyState===WebSocket.OPEN){const s={type:"candidate",candidate:O.candidate.candidate,sdpMid:O.candidate.sdpMid,sdpMLineIndex:O.candidate.sdpMLineIndex,sessionId:i};E.send(JSON.stringify(s)),_("Sent ICE candidate")}else _("ICE candidate gathering completed")},E.onmessage=async O=>{if(!C()||g!==E)return;let s;try{s=JSON.parse(O.data)}catch(Y){y("Error parsing message:",Y);return}if(!$?.handleMessage(s))switch(_("Received: "+s.type),s.type){case"performActionsResult":case"foldStateResult":case"foldStateChanged":{if(!U)break;s.state?(w(s.state),N(void 0)):s.id==="duo-capabilities"&&N(s.error||"This instance does not support native iPhone Duo displays.");const T=_e.get(s.id);T&&(clearTimeout(T.timer),_e.delete(s.id),s.error?T.reject(new Error(s.error)):T.resolve());break}case"signalingError":{if(s.requestType!=="offer"||s.sessionId!==i)break;const T=typeof s.error=="string"?s.error:"Unable to establish the streaming connection";_("Error: "+T),ye(T,m);break}case"answer":if(!R||R!==A){_("No peer connection, skipping answer");break}if(lt?.accept(s.latencyTraceVersion),await A.setRemoteDescription(new RTCSessionDescription({type:"answer",sdp:s.sdp})),!C()||R!==A)return;_("Set remote description"),pe=E,(e.speakerMuted??!0)||mt();break;case"candidate":if(!R||R!==A){_("No peer connection, skipping candidate");break}if(await A.addIceCandidate(new RTCIceCandidate({candidate:s.candidate,sdpMid:s.sdpMid,sdpMLineIndex:s.sdpMLineIndex})),!C()||R!==A)return;_("Added ICE candidate");break;case"screenshot":case"screenshotResult":{if(typeof s.id!="string"){y("Received invalid screenshot success message:",s);break}const T=cn(s);if(T){const j=ee.get(s.id);if(typeof j!="function"){y(`Received screenshot error for unknown or handled id: ${s.id}`);break}y(`Received screenshot error for id ${s.id}: ${T}`),j(new Error(T)),ne.delete(s.id),ee.delete(s.id),clearTimeout(I.get(s.id)),I.delete(s.id);break}const M=ln(s);if(!M){y("Received screenshot message without image data:",s);break}const z=ne.get(s.id);if(typeof z!="function"){y(`Received screenshot data for unknown or handled id: ${s.id}`);break}se(`Received screenshot data for id ${s.id}`),z(M),ne.delete(s.id),ee.delete(s.id),clearTimeout(I.get(s.id)),I.delete(s.id);break}case"screenshotError":if(typeof s.id!="string"||typeof s.message!="string"){y("Received invalid screenshot error message:",s);break}const Y=ee.get(s.id);if(typeof Y!="function"){y(`Received screenshot error for unknown or handled id: ${s.id}`);break}y(`Received screenshot error for id ${s.id}: ${s.message}`),Y(new Error(s.message)),ne.delete(s.id),ee.delete(s.id),clearTimeout(I.get(s.id)),I.delete(s.id);break;case"cameraRequest":{const T=ue;if(!T)break;const M=Qr(s);if(!M){y("Received invalid cameraRequest:",s);break}console.info("[RemoteControl] cameraRequest received:",M.active,M.facingMode),await sr(M,E,T,C);break}case"microphoneRequest":{if(!be)break;const T=s.active===!0;if(ot=T,console.info("[RemoteControl] microphoneRequest received, active=",T),!T){it||await Xe();break}if(te){gt(E);break}await st();break}case"microphoneStartResult":{if(Oe===null||s.id!==Oe)break;Oe=null,typeof s.error=="string"&&(console.warn("[RemoteControl] microphoneStart rejected by host:",s.error),Xe(s.error));break}case"terminateAppResult":if(typeof s.id!="string"){y("Received invalid terminateApp result message:",s);break}if(typeof s.error=="string"){const T=ie.get(s.id);if(typeof T!="function"){y(`Received terminateApp error for unknown or handled id: ${s.id}`);break}y(`Received terminateApp error for id ${s.id}: ${s.error}`),T(new Error(s.error)),le.delete(s.id),ie.delete(s.id),clearTimeout(I.get(s.id)),I.delete(s.id);break}const q=le.get(s.id);if(typeof q!="function"){y(`Received terminateApp result for unknown or handled id: ${s.id}`);break}se(`Received terminateApp success for id ${s.id}`),q(),le.delete(s.id),ie.delete(s.id),clearTimeout(I.get(s.id)),I.delete(s.id);break;default:y(`Received unhandled message type: ${s.type}`,s);break}},R===A){const O=await A.createOffer({offerToReceiveVideo:!0,offerToReceiveAudio:!0});if(!C()||R!==A||(await A.setLocalDescription(O),!C()||R!==A))return;C()&&g===E&&E.readyState===WebSocket.OPEN&&E.send(JSON.stringify({type:"offer",...U?{displayStreams:!0}:{},speakerAudio:!0,...lt?{latencyTraceVersion:1}:{},sdp:O.sdp,sessionId:i})),_("Sent offer")}}catch(E){if(!C()||E instanceof Error&&E.message==="Connection stopped")return;const k=E instanceof Error?E.message:String(E);_("Error: "+k),ye(k,m)}},At=()=>{if(Ee)throw new Error("Device stream is disposed");xe++,Me=!1,Je(null),De!=="reconnecting"&&(De=null),document.addEventListener("visibilitychange",St),document.hidden||Dt(),he=!1,Kt(0)},Mt=()=>{xe++,Me=!1,Re(),document.removeEventListener("visibilitychange",St),de+=1,Ve=0,re=!1,Ge(),Ue(),Te(),De=null,p({connection:"idle",videoReady:!1,controlReady:!1}),_("Stopped")},ur=n=>{if(Ee)throw new Error("Device stream is disposed");if(Ke.has(n))throw new Error("Audio element is already attached");Ke.add(n),Ae&&pt(n);let f=!1;const c=()=>{f||(f=!0,x.delete(c),Ke.delete(n),Qt(n),n.srcObject=null)};return x.add(c),c},vt=(n,f="primary")=>{if(Ee)throw new Error("Device stream is disposed");if(B.has(n))throw new Error("Video element is already attached");const c={display:f};B.set(n,c);const d=()=>{f==="primary"&&Be.has(f)&&rr()};n.addEventListener("loadeddata",d);const K=Be.get(f);K&&ht(n,c,K);let m=!1;const C=()=>{m||(m=!0,x.delete(C),n.removeEventListener("loadeddata",d),c.stop?.(),B.delete(n),n.srcObject=null)};return x.add(C),C};return{start:At,stop:Mt,attachVideo:vt,attachAudio:ur,attachFrameSink:(n,f="primary")=>{const c=document.createElement("video");c.muted=!0,c.playsInline=!0,c.autoplay=!0;const d=vt(c,f);let K=!1,m=0,C=0;const E=()=>{c.cancelVideoFrameCallback?.(m),cancelAnimationFrame(C)},k=()=>{K||!c.srcObject||(c.readyState>=2&&c.videoWidth>0&&L("present",(...v)=>n.present(...v),c,c.videoWidth,c.videoHeight,f),!(K||!c.srcObject)&&(c.requestVideoFrameCallback?m=c.requestVideoFrameCallback(k):C=requestAnimationFrame(k)))},b=()=>{E(),k()};B.get(c).clear=E,c.addEventListener("loadeddata",b);const G=()=>{K||(K=!0,x.delete(G),E(),c.removeEventListener("loadeddata",b),d(),c.remove())};return x.delete(d),x.add(G),c.readyState>=2&&b(),G},dispose:()=>{if(!Ee){Ee=!0,Mt();for(const n of x)n();x.clear()}},getState:()=>D,updateOptions:({token:n,...f})=>{if(Ee)throw new Error("Device stream is disposed");n!==void 0&&!e.transport&&(u=n);const c=e;if(e={...e,...f},c.jitterBufferTargetMs!==e.jitterBufferTargetMs)for(const d of R?.getTransceivers()??[])(d.currentDirection==="recvonly"||d.currentDirection==="sendrecv")&&Yt(d.receiver,e.jitterBufferTargetMs);!!c.onPlaybackStats!=!!e.onPlaybackStats&&P(),!!c.microphoneEnabled!=!!e.microphoneEnabled&&(it=!l&&(e.microphoneEnabled??!1),at()?st():Xe()),(c.speakerMuted??!0)!==(e.speakerMuted??!0)&&mt(),!!c.inspectMode!=!!e.inspectMode&&(e.inspectMode?$?.start():($?.stop(),Ie!==null&&Je(null)))},sendControl:oe,sendTouch:(n,f,c,d,K,m=0)=>oe(Lt(n==="begin"?0:n==="end"?1:2,m,d,K,f,c,n==="end"?0:1)),sendText:n=>oe(Ft(n)),sendDisplayTouch:(n,f,c,d)=>oe(qt(n,f,c,d)),sendDuoControl:er,pressButton:n=>{const f={home:3,back:4,recents:187,power:26}[n];oe(Ze(0,f,0,0)),oe(Ze(1,f,0,0))},rotate:()=>oe(new Uint8Array([11]).buffer),bumpActivity:()=>$?.bumpActivity(),getAxStatus:()=>$?.getStatus()??"idle",openUrl:n=>{if(!l){if(!g||g.readyState!==WebSocket.OPEN){y("WebSocket not open, cannot send open_url command.");return}try{const f=decodeURIComponent(n);_("Opening URL"),g.send(JSON.stringify({type:"openUrl",url:f,sessionId:i}))}catch(f){y("Error decoding or sending URL :",{error:f,url:n}),g.send(JSON.stringify({type:"openUrl",url:n,sessionId:i}))}$?.bumpActivity()}},sendKeyEvent:n=>{if(!W||W.readyState!=="open"){y("Data channel not ready for imperative key command:",W?.readyState);return}if(h==="macos"){const m=ft(n.code);if(m===void 0){y(`Unknown event.code for imperative command: ${n.code}`);return}const C=[[n.metaKey,"Meta"],[n.ctrlKey,"Control"],[n.altKey,"Alt"],[n.shiftKey,"Shift"]].filter(([k,b])=>k&&!n.code.startsWith(b)).map(([,k])=>ft(`${k}Left`)),E=(k,b)=>oe(Bt(k,b));if(n.type==="keydown"){for(const k of C)E(Pe.DOWN,k);E(Pe.DOWN,m)}else{E(Pe.UP,m);for(const k of[...C].reverse())E(Pe.UP,k)}return}const f=Pt[n.code];if(!f){y(`Unknown event.code for imperative command: ${n.code}`);return}let c=a.META_NONE;n.shiftKey&&(c|=a.META_SHIFT_ON),n.altKey&&(c|=a.META_ALT_ON),n.ctrlKey&&(c|=a.META_CTRL_ON),n.metaKey&&(c|=a.META_META_ON);const d=n.type==="keydown"?a.ACTION_DOWN:a.ACTION_UP;se(`Sending Imperative Key Command: code=${n.code}, keycode=${f}, action=${d}, meta=${c}`);const K=Ze(d,f,0,c);K&&oe(K)},screenshot:n=>new Promise((f,c)=>{if(!g||g.readyState!==WebSocket.OPEN)return y("WebSocket not open, cannot send screenshot command."),c(new Error("WebSocket is not connected or connection is not open."));const d=`ui-ss-${Date.now()}-${Math.random().toString(36).substring(2,9)}`,K={type:n?"screenshotDisplay":"screenshot",...n?{display:n}:{},id:d};ne.set(d,f),ee.set(d,c),se("Sending screenshot request:",K);try{g.send(JSON.stringify(K))}catch(m){y("Failed to send screenshot request immediately:",m),ne.delete(d),ee.delete(d),c(m);return}I.set(d,setTimeout(()=>{I.delete(d),ne.has(d)&&(y(`Screenshot request timed out for id ${d}`),ee.get(d)?.(new Error("Screenshot request timed out")),ne.delete(d),ee.delete(d))},3e4))}),terminateApp:n=>l?Promise.reject(new Error("Device is watch-only")):new Promise((f,c)=>{if(!g||g.readyState!==WebSocket.OPEN)return y("WebSocket not open, cannot send terminateApp command."),c(new Error("WebSocket is not connected or connection is not open."));const d=`ui-term-${Date.now()}-${Math.random().toString(36).substring(2,9)}`,K={type:"terminateApp",id:d,bundleId:n};le.set(d,f),ie.set(d,c),se("Sending terminateApp request:",K);try{g.send(JSON.stringify(K))}catch(m){y("Failed to send terminateApp request immediately:",m),le.delete(d),ie.delete(d),c(m);return}$?.bumpActivity(),I.set(d,setTimeout(()=>{I.delete(d),le.has(d)&&(y(`terminateApp request timed out for id ${d}`),ie.get(d)?.(new Error("terminateApp request timed out")),le.delete(d),ie.delete(d))},3e4))}),reconnect:()=>At(),refreshAxTree:async()=>{const n=$;if(!n)throw new Error("Inspect mode is not active");return n.refresh()},getAxSnapshot:()=>Ie}}const cn=t=>typeof t.message=="string"?t.message:typeof t.error=="string"?t.error:null,ln=t=>typeof t.dataUri=="string"?{dataUri:t.dataUri}:typeof t.base64=="string"?t.base64.startsWith("data:")?{dataUri:t.base64}:{dataUri:`data:${t.base64.startsWith("/9j/")?"image/jpeg":"image/png"};base64,${t.base64}`}:null;exports.AMOTION_EVENT=Le;exports.ANDROID_KEYS=a;exports.AX_UNAVAILABLE_ERROR=et;exports.CONTROL_MSG_TYPE=Z;exports.DUO_BUTTONS=Ar;exports.DUO_DIMENSIONS=gr;exports.DuoButtonSender=Mr;exports.DuoTouchController=_r;exports.HingeSender=Kr;exports.MAC_INPUT_ACTION=Pe;exports.axElementAtPoint=kr;exports.axElementRoleLabel=jt;exports.axElementSelectorExpression=Ur;exports.axElementSummary=Pr;exports.axElementsEqual=Jt;exports.axSnapshotsEqual=Gt;exports.cancelSpeakerRetry=Qt;exports.clampAxFrameForScreen=Rr;exports.codeMap=Pt;exports.createDeviceStream=sn;exports.createDisplayTouchMessage=qt;exports.createInjectKeycodeMessage=Ze;exports.createMacKeyMessage=Bt;exports.createMacScrollMessage=Or;exports.createMouseControlMessage=Cr;exports.createSetClipboardMessage=Ft;exports.createTouchControlMessage=Lt;exports.createTwoFingerTouchControlMessage=mr;exports.debugLog=se;exports.debugWarn=y;exports.detectPlatform=zt;exports.duoDisplayTurns=xt;exports.duoPointerMode=Sr;exports.flatDisplayTouch=Wt;exports.getDuoDisplay=Dr;exports.macKeyCodeFor=ft;exports.normalizeAndroidTree=Ht;exports.normalizeIosTree=$t;exports.panelTouch=yr;exports.playSpeaker=Et;exports.safeInvoke=L;
|