@limrun/ui 0.20.8 → 0.21.0

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.
@@ -0,0 +1,2327 @@
1
+ const ee = {
2
+ INJECT_KEYCODE: 0,
3
+ INJECT_TEXT: 1,
4
+ INJECT_TOUCH_EVENT: 2,
5
+ // iOS-specific: send two touch points in one message (Option/Alt+drag pinch)
6
+ INJECT_TWO_FINGER_TOUCH_EVENT: 18,
7
+ INJECT_SCROLL_EVENT: 3,
8
+ BACK_OR_SCREEN_ON: 4,
9
+ EXPAND_NOTIFICATION_PANEL: 5,
10
+ EXPAND_SETTINGS_PANEL: 6,
11
+ COLLAPSE_PANELS: 7,
12
+ GET_CLIPBOARD: 8,
13
+ SET_CLIPBOARD: 9,
14
+ SET_DISPLAY_POWER: 10,
15
+ ROTATE_DEVICE: 11,
16
+ // macOS: a desktop pointer, with hover moves and a button mask.
17
+ INJECT_MOUSE_EVENT: 40,
18
+ // macOS: a key by its macOS virtual key code, so modifiers travel on their own.
19
+ INJECT_MAC_KEY: 41,
20
+ // macOS: wheel and trackpad scrolling, as pixel deltas.
21
+ INJECT_MAC_SCROLL: 42
22
+ }, Ge = {
23
+ DOWN: 0,
24
+ UP: 1,
25
+ MOVE: 2
26
+ }, je = {
27
+ ACTION_DOWN: 0,
28
+ ACTION_UP: 1,
29
+ ACTION_MOVE: 2,
30
+ ACTION_CANCEL: 3,
31
+ ACTION_POINTER_DOWN: 5,
32
+ ACTION_POINTER_UP: 6,
33
+ BUTTON_PRIMARY: 1,
34
+ BUTTON_SECONDARY: 2,
35
+ BUTTON_TERTIARY: 4
36
+ }, o = {
37
+ // Actions
38
+ ACTION_DOWN: 0,
39
+ ACTION_UP: 1,
40
+ // Meta state flags (from android.view.KeyEvent)
41
+ META_NONE: 0,
42
+ META_SHIFT_ON: 1,
43
+ META_ALT_ON: 2,
44
+ META_CTRL_ON: 4096,
45
+ // META_CTRL_LEFT_ON | META_CTRL_RIGHT_ON
46
+ META_META_ON: 65536,
47
+ // META_META_LEFT_ON | META_META_RIGHT_ON
48
+ // Keycodes (from android.view.KeyEvent)
49
+ KEYCODE_UNKNOWN: 0,
50
+ KEYCODE_SOFT_LEFT: 1,
51
+ KEYCODE_SOFT_RIGHT: 2,
52
+ KEYCODE_HOME: 3,
53
+ KEYCODE_BACK: 4,
54
+ KEYCODE_CALL: 5,
55
+ KEYCODE_ENDCALL: 6,
56
+ KEYCODE_0: 7,
57
+ KEYCODE_1: 8,
58
+ KEYCODE_2: 9,
59
+ KEYCODE_3: 10,
60
+ KEYCODE_4: 11,
61
+ KEYCODE_5: 12,
62
+ KEYCODE_6: 13,
63
+ KEYCODE_7: 14,
64
+ KEYCODE_8: 15,
65
+ KEYCODE_9: 16,
66
+ KEYCODE_STAR: 17,
67
+ KEYCODE_POUND: 18,
68
+ DPAD_UP: 19,
69
+ // KEYCODE_DPAD_UP
70
+ DPAD_DOWN: 20,
71
+ // KEYCODE_DPAD_DOWN
72
+ DPAD_LEFT: 21,
73
+ // KEYCODE_DPAD_LEFT
74
+ DPAD_RIGHT: 22,
75
+ // KEYCODE_DPAD_RIGHT
76
+ KEYCODE_DPAD_CENTER: 23,
77
+ KEYCODE_VOLUME_UP: 24,
78
+ KEYCODE_VOLUME_DOWN: 25,
79
+ KEYCODE_POWER: 26,
80
+ KEYCODE_CAMERA: 27,
81
+ KEYCODE_CLEAR: 28,
82
+ KEYCODE_A: 29,
83
+ KEYCODE_B: 30,
84
+ KEYCODE_C: 31,
85
+ KEYCODE_D: 32,
86
+ KEYCODE_E: 33,
87
+ KEYCODE_F: 34,
88
+ KEYCODE_G: 35,
89
+ KEYCODE_H: 36,
90
+ KEYCODE_I: 37,
91
+ KEYCODE_J: 38,
92
+ KEYCODE_K: 39,
93
+ KEYCODE_L: 40,
94
+ KEYCODE_M: 41,
95
+ KEYCODE_N: 42,
96
+ KEYCODE_O: 43,
97
+ KEYCODE_P: 44,
98
+ KEYCODE_Q: 45,
99
+ KEYCODE_R: 46,
100
+ KEYCODE_S: 47,
101
+ KEYCODE_T: 48,
102
+ KEYCODE_U: 49,
103
+ KEYCODE_V: 50,
104
+ KEYCODE_W: 51,
105
+ KEYCODE_X: 52,
106
+ KEYCODE_Y: 53,
107
+ KEYCODE_Z: 54,
108
+ KEYCODE_COMMA: 55,
109
+ KEYCODE_PERIOD: 56,
110
+ KEYCODE_ALT_LEFT: 57,
111
+ KEYCODE_ALT_RIGHT: 58,
112
+ KEYCODE_SHIFT_LEFT: 59,
113
+ KEYCODE_SHIFT_RIGHT: 60,
114
+ KEYCODE_TAB: 61,
115
+ KEYCODE_SPACE: 62,
116
+ KEYCODE_SYM: 63,
117
+ KEYCODE_EXPLORER: 64,
118
+ KEYCODE_ENVELOPE: 65,
119
+ ENTER: 66,
120
+ // KEYCODE_ENTER
121
+ DEL: 67,
122
+ // KEYCODE_DEL (Backspace)
123
+ KEYCODE_GRAVE: 68,
124
+ // `
125
+ KEYCODE_MINUS: 69,
126
+ // -
127
+ KEYCODE_EQUALS: 70,
128
+ // =
129
+ KEYCODE_LEFT_BRACKET: 71,
130
+ // [
131
+ KEYCODE_RIGHT_BRACKET: 72,
132
+ // ]
133
+ KEYCODE_BACKSLASH: 73,
134
+ // \
135
+ KEYCODE_SEMICOLON: 74,
136
+ // ;
137
+ KEYCODE_APOSTROPHE: 75,
138
+ // '
139
+ KEYCODE_SLASH: 76,
140
+ // /
141
+ KEYCODE_AT: 77,
142
+ // @
143
+ KEYCODE_NUM: 78,
144
+ KEYCODE_HEADSETHOOK: 79,
145
+ KEYCODE_FOCUS: 80,
146
+ KEYCODE_PLUS: 81,
147
+ MENU: 82,
148
+ // KEYCODE_MENU
149
+ KEYCODE_NOTIFICATION: 83,
150
+ KEYCODE_SEARCH: 84,
151
+ KEYCODE_MEDIA_PLAY_PAUSE: 85,
152
+ KEYCODE_MEDIA_STOP: 86,
153
+ KEYCODE_MEDIA_NEXT: 87,
154
+ KEYCODE_MEDIA_PREVIOUS: 88,
155
+ KEYCODE_MEDIA_REWIND: 89,
156
+ KEYCODE_MEDIA_FAST_FORWARD: 90,
157
+ KEYCODE_MUTE: 91,
158
+ KEYCODE_PAGE_UP: 92,
159
+ KEYCODE_PAGE_DOWN: 93,
160
+ KEYCODE_PICTSYMBOLS: 94,
161
+ KEYCODE_SWITCH_CHARSET: 95,
162
+ KEYCODE_BUTTON_A: 96,
163
+ KEYCODE_BUTTON_B: 97,
164
+ KEYCODE_BUTTON_C: 98,
165
+ KEYCODE_BUTTON_X: 99,
166
+ KEYCODE_BUTTON_Y: 100,
167
+ KEYCODE_BUTTON_Z: 101,
168
+ KEYCODE_BUTTON_L1: 102,
169
+ KEYCODE_BUTTON_R1: 103,
170
+ KEYCODE_BUTTON_L2: 104,
171
+ KEYCODE_BUTTON_R2: 105,
172
+ KEYCODE_BUTTON_THUMBL: 106,
173
+ KEYCODE_BUTTON_THUMBR: 107,
174
+ KEYCODE_BUTTON_START: 108,
175
+ KEYCODE_BUTTON_SELECT: 109,
176
+ KEYCODE_BUTTON_MODE: 110,
177
+ KEYCODE_ESCAPE: 111,
178
+ FORWARD_DEL: 112,
179
+ // KEYCODE_FORWARD_DEL (Delete key)
180
+ KEYCODE_CTRL_LEFT: 113,
181
+ KEYCODE_CTRL_RIGHT: 114,
182
+ KEYCODE_CAPS_LOCK: 115,
183
+ KEYCODE_SCROLL_LOCK: 116,
184
+ KEYCODE_META_LEFT: 117,
185
+ KEYCODE_META_RIGHT: 118,
186
+ KEYCODE_FUNCTION: 119,
187
+ KEYCODE_SYSRQ: 120,
188
+ KEYCODE_BREAK: 121,
189
+ KEYCODE_MOVE_HOME: 122,
190
+ KEYCODE_MOVE_END: 123,
191
+ KEYCODE_INSERT: 124,
192
+ KEYCODE_FORWARD: 125,
193
+ KEYCODE_MEDIA_PLAY: 126,
194
+ KEYCODE_MEDIA_PAUSE: 127,
195
+ KEYCODE_MEDIA_CLOSE: 128,
196
+ KEYCODE_MEDIA_EJECT: 129,
197
+ KEYCODE_MEDIA_RECORD: 130,
198
+ KEYCODE_F1: 131,
199
+ KEYCODE_F2: 132,
200
+ KEYCODE_F3: 133,
201
+ KEYCODE_F4: 134,
202
+ KEYCODE_F5: 135,
203
+ KEYCODE_F6: 136,
204
+ KEYCODE_F7: 137,
205
+ KEYCODE_F8: 138,
206
+ KEYCODE_F9: 139,
207
+ KEYCODE_F10: 140,
208
+ KEYCODE_F11: 141,
209
+ KEYCODE_F12: 142,
210
+ KEYCODE_NUM_LOCK: 143,
211
+ KEYCODE_NUMPAD_0: 144,
212
+ KEYCODE_NUMPAD_1: 145,
213
+ KEYCODE_NUMPAD_2: 146,
214
+ KEYCODE_NUMPAD_3: 147,
215
+ KEYCODE_NUMPAD_4: 148,
216
+ KEYCODE_NUMPAD_5: 149,
217
+ KEYCODE_NUMPAD_6: 150,
218
+ KEYCODE_NUMPAD_7: 151,
219
+ KEYCODE_NUMPAD_8: 152,
220
+ KEYCODE_NUMPAD_9: 153,
221
+ KEYCODE_NUMPAD_DIVIDE: 154,
222
+ KEYCODE_NUMPAD_MULTIPLY: 155,
223
+ KEYCODE_NUMPAD_SUBTRACT: 156,
224
+ KEYCODE_NUMPAD_ADD: 157,
225
+ KEYCODE_NUMPAD_DOT: 158,
226
+ KEYCODE_NUMPAD_COMMA: 159,
227
+ KEYCODE_NUMPAD_ENTER: 160,
228
+ KEYCODE_NUMPAD_EQUALS: 161,
229
+ KEYCODE_NUMPAD_LEFT_PAREN: 162,
230
+ KEYCODE_NUMPAD_RIGHT_PAREN: 163,
231
+ KEYCODE_VOLUME_MUTE: 164,
232
+ KEYCODE_INFO: 165,
233
+ KEYCODE_CHANNEL_UP: 166,
234
+ KEYCODE_CHANNEL_DOWN: 167,
235
+ KEYCODE_ZOOM_IN: 168,
236
+ KEYCODE_ZOOM_OUT: 169,
237
+ KEYCODE_TV: 170,
238
+ KEYCODE_WINDOW: 171,
239
+ KEYCODE_GUIDE: 172,
240
+ KEYCODE_DVR: 173,
241
+ KEYCODE_BOOKMARK: 174,
242
+ KEYCODE_CAPTIONS: 175,
243
+ KEYCODE_SETTINGS: 176,
244
+ KEYCODE_TV_POWER: 177,
245
+ KEYCODE_TV_INPUT: 178,
246
+ KEYCODE_STB_POWER: 179,
247
+ KEYCODE_STB_INPUT: 180,
248
+ KEYCODE_AVR_POWER: 181,
249
+ KEYCODE_AVR_INPUT: 182,
250
+ KEYCODE_PROG_RED: 183,
251
+ KEYCODE_PROG_GREEN: 184,
252
+ KEYCODE_PROG_YELLOW: 185,
253
+ KEYCODE_PROG_BLUE: 186,
254
+ KEYCODE_APP_SWITCH: 187,
255
+ KEYCODE_LANGUAGE_SWITCH: 204,
256
+ KEYCODE_ASSIST: 219,
257
+ KEYCODE_BRIGHTNESS_DOWN: 220,
258
+ KEYCODE_BRIGHTNESS_UP: 221,
259
+ KEYCODE_SLEEP: 223,
260
+ KEYCODE_WAKEUP: 224,
261
+ KEYCODE_SOFT_SLEEP: 276
262
+ }, Ht = {
263
+ KeyA: o.KEYCODE_A,
264
+ KeyB: o.KEYCODE_B,
265
+ KeyC: o.KEYCODE_C,
266
+ KeyD: o.KEYCODE_D,
267
+ KeyE: o.KEYCODE_E,
268
+ KeyF: o.KEYCODE_F,
269
+ KeyG: o.KEYCODE_G,
270
+ KeyH: o.KEYCODE_H,
271
+ KeyI: o.KEYCODE_I,
272
+ KeyJ: o.KEYCODE_J,
273
+ KeyK: o.KEYCODE_K,
274
+ KeyL: o.KEYCODE_L,
275
+ KeyM: o.KEYCODE_M,
276
+ KeyN: o.KEYCODE_N,
277
+ KeyO: o.KEYCODE_O,
278
+ KeyP: o.KEYCODE_P,
279
+ KeyQ: o.KEYCODE_Q,
280
+ KeyR: o.KEYCODE_R,
281
+ KeyS: o.KEYCODE_S,
282
+ KeyT: o.KEYCODE_T,
283
+ KeyU: o.KEYCODE_U,
284
+ KeyV: o.KEYCODE_V,
285
+ KeyW: o.KEYCODE_W,
286
+ KeyX: o.KEYCODE_X,
287
+ KeyY: o.KEYCODE_Y,
288
+ KeyZ: o.KEYCODE_Z,
289
+ Digit0: o.KEYCODE_0,
290
+ Digit1: o.KEYCODE_1,
291
+ Digit2: o.KEYCODE_2,
292
+ Digit3: o.KEYCODE_3,
293
+ Digit4: o.KEYCODE_4,
294
+ Digit5: o.KEYCODE_5,
295
+ Digit6: o.KEYCODE_6,
296
+ Digit7: o.KEYCODE_7,
297
+ Digit8: o.KEYCODE_8,
298
+ Digit9: o.KEYCODE_9,
299
+ Backquote: o.KEYCODE_GRAVE,
300
+ Minus: o.KEYCODE_MINUS,
301
+ Equal: o.KEYCODE_EQUALS,
302
+ BracketLeft: o.KEYCODE_LEFT_BRACKET,
303
+ BracketRight: o.KEYCODE_RIGHT_BRACKET,
304
+ Backslash: o.KEYCODE_BACKSLASH,
305
+ Semicolon: o.KEYCODE_SEMICOLON,
306
+ Quote: o.KEYCODE_APOSTROPHE,
307
+ Comma: o.KEYCODE_COMMA,
308
+ Period: o.KEYCODE_PERIOD,
309
+ Slash: o.KEYCODE_SLASH,
310
+ Space: o.KEYCODE_SPACE,
311
+ Tab: o.KEYCODE_TAB,
312
+ Escape: o.KEYCODE_ESCAPE,
313
+ ArrowUp: o.DPAD_UP,
314
+ ArrowDown: o.DPAD_DOWN,
315
+ ArrowLeft: o.DPAD_LEFT,
316
+ ArrowRight: o.DPAD_RIGHT,
317
+ Enter: o.ENTER,
318
+ Backspace: o.DEL,
319
+ Delete: o.FORWARD_DEL,
320
+ Home: o.KEYCODE_MOVE_HOME,
321
+ End: o.KEYCODE_MOVE_END,
322
+ PageUp: o.KEYCODE_PAGE_UP,
323
+ PageDown: o.KEYCODE_PAGE_DOWN,
324
+ Insert: o.KEYCODE_INSERT,
325
+ F1: o.KEYCODE_F1,
326
+ F2: o.KEYCODE_F2,
327
+ F3: o.KEYCODE_F3,
328
+ F4: o.KEYCODE_F4,
329
+ F5: o.KEYCODE_F5,
330
+ F6: o.KEYCODE_F6,
331
+ F7: o.KEYCODE_F7,
332
+ F8: o.KEYCODE_F8,
333
+ F9: o.KEYCODE_F9,
334
+ F10: o.KEYCODE_F10,
335
+ F11: o.KEYCODE_F11,
336
+ F12: o.KEYCODE_F12,
337
+ ShiftLeft: o.KEYCODE_SHIFT_LEFT,
338
+ ShiftRight: o.KEYCODE_SHIFT_RIGHT,
339
+ ControlLeft: o.KEYCODE_CTRL_LEFT,
340
+ ControlRight: o.KEYCODE_CTRL_RIGHT,
341
+ AltLeft: o.KEYCODE_ALT_LEFT,
342
+ AltRight: o.KEYCODE_ALT_RIGHT,
343
+ MetaLeft: o.KEYCODE_META_LEFT,
344
+ MetaRight: o.KEYCODE_META_RIGHT,
345
+ // Windows/Command key
346
+ ContextMenu: o.MENU,
347
+ // Often the Menu key
348
+ // Numpad mappings
349
+ Numpad0: o.KEYCODE_NUMPAD_0,
350
+ Numpad1: o.KEYCODE_NUMPAD_1,
351
+ Numpad2: o.KEYCODE_NUMPAD_2,
352
+ Numpad3: o.KEYCODE_NUMPAD_3,
353
+ Numpad4: o.KEYCODE_NUMPAD_4,
354
+ Numpad5: o.KEYCODE_NUMPAD_5,
355
+ Numpad6: o.KEYCODE_NUMPAD_6,
356
+ Numpad7: o.KEYCODE_NUMPAD_7,
357
+ Numpad8: o.KEYCODE_NUMPAD_8,
358
+ Numpad9: o.KEYCODE_NUMPAD_9,
359
+ NumpadDivide: o.KEYCODE_NUMPAD_DIVIDE,
360
+ NumpadMultiply: o.KEYCODE_NUMPAD_MULTIPLY,
361
+ NumpadSubtract: o.KEYCODE_NUMPAD_SUBTRACT,
362
+ NumpadAdd: o.KEYCODE_NUMPAD_ADD,
363
+ NumpadDecimal: o.KEYCODE_NUMPAD_DOT,
364
+ NumpadComma: o.KEYCODE_NUMPAD_COMMA,
365
+ // Some numpads have comma
366
+ NumpadEnter: o.KEYCODE_NUMPAD_ENTER,
367
+ NumpadEqual: o.KEYCODE_NUMPAD_EQUALS
368
+ }, Jt = {
369
+ KeyA: 0,
370
+ KeyS: 1,
371
+ KeyD: 2,
372
+ KeyF: 3,
373
+ KeyH: 4,
374
+ KeyG: 5,
375
+ KeyZ: 6,
376
+ KeyX: 7,
377
+ KeyC: 8,
378
+ KeyV: 9,
379
+ IntlBackslash: 10,
380
+ KeyB: 11,
381
+ KeyQ: 12,
382
+ KeyW: 13,
383
+ KeyE: 14,
384
+ KeyR: 15,
385
+ KeyY: 16,
386
+ KeyT: 17,
387
+ Digit1: 18,
388
+ Digit2: 19,
389
+ Digit3: 20,
390
+ Digit4: 21,
391
+ Digit6: 22,
392
+ Digit5: 23,
393
+ Equal: 24,
394
+ Digit9: 25,
395
+ Digit7: 26,
396
+ Minus: 27,
397
+ Digit8: 28,
398
+ Digit0: 29,
399
+ BracketRight: 30,
400
+ KeyO: 31,
401
+ KeyU: 32,
402
+ BracketLeft: 33,
403
+ KeyI: 34,
404
+ KeyP: 35,
405
+ Enter: 36,
406
+ KeyL: 37,
407
+ KeyJ: 38,
408
+ Quote: 39,
409
+ KeyK: 40,
410
+ Semicolon: 41,
411
+ Backslash: 42,
412
+ Comma: 43,
413
+ Slash: 44,
414
+ KeyN: 45,
415
+ KeyM: 46,
416
+ Period: 47,
417
+ Tab: 48,
418
+ Space: 49,
419
+ Backquote: 50,
420
+ Backspace: 51,
421
+ Escape: 53,
422
+ MetaRight: 54,
423
+ MetaLeft: 55,
424
+ ShiftLeft: 56,
425
+ CapsLock: 57,
426
+ AltLeft: 58,
427
+ ControlLeft: 59,
428
+ ShiftRight: 60,
429
+ AltRight: 61,
430
+ ControlRight: 62,
431
+ Fn: 63,
432
+ F17: 64,
433
+ NumpadDecimal: 65,
434
+ NumpadMultiply: 67,
435
+ NumpadAdd: 69,
436
+ NumLock: 71,
437
+ NumpadDivide: 75,
438
+ NumpadEnter: 76,
439
+ NumpadSubtract: 78,
440
+ F18: 79,
441
+ F19: 80,
442
+ NumpadEqual: 81,
443
+ Numpad0: 82,
444
+ Numpad1: 83,
445
+ Numpad2: 84,
446
+ Numpad3: 85,
447
+ Numpad4: 86,
448
+ Numpad5: 87,
449
+ Numpad6: 88,
450
+ Numpad7: 89,
451
+ F20: 90,
452
+ Numpad8: 91,
453
+ Numpad9: 92,
454
+ F5: 96,
455
+ F6: 97,
456
+ F7: 98,
457
+ F3: 99,
458
+ F8: 100,
459
+ F9: 101,
460
+ F11: 103,
461
+ F13: 105,
462
+ F16: 106,
463
+ F14: 107,
464
+ F10: 109,
465
+ ContextMenu: 110,
466
+ F12: 111,
467
+ F15: 113,
468
+ Help: 114,
469
+ Insert: 114,
470
+ Home: 115,
471
+ PageUp: 116,
472
+ Delete: 117,
473
+ F4: 118,
474
+ End: 119,
475
+ F2: 120,
476
+ PageDown: 121,
477
+ F1: 122,
478
+ ArrowLeft: 123,
479
+ ArrowRight: 124,
480
+ ArrowDown: 125,
481
+ ArrowUp: 126
482
+ };
483
+ function Tt(t) {
484
+ return Jt[t];
485
+ }
486
+ function Gt(t, e, n, a, u, l, i = 1, E = 0, O = 0) {
487
+ const m = new ArrayBuffer(32), S = new DataView(m);
488
+ let w = 0;
489
+ S.setUint8(w, ee.INJECT_TOUCH_EVENT), w += 1;
490
+ const N = t === je.ACTION_POINTER_DOWN ? je.ACTION_DOWN : t === je.ACTION_POINTER_UP ? je.ACTION_UP : t;
491
+ 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, n, !0), w += 2, S.setUint16(w, a, !0), w += 2, S.setInt16(w, Math.round(i * 65535), !0), w += 2, S.setInt32(w, E, !0), w += 4, S.setInt32(w, O, !0), m;
492
+ }
493
+ function Bn(t, e, n, a, u, l, i) {
494
+ const E = new ArrayBuffer(24), O = new DataView(E);
495
+ let m = 0;
496
+ return O.setUint8(m, ee.INJECT_TWO_FINGER_TOUCH_EVENT), m += 1, O.setUint8(m, t), m += 1, O.setInt32(m, Math.round(a), !0), m += 4, O.setInt32(m, Math.round(u), !0), m += 4, O.setInt32(m, Math.round(l), !0), m += 4, O.setInt32(m, Math.round(i), !0), m += 4, O.setUint16(m, e, !0), m += 2, O.setUint16(m, n, !0), m += 2, O.setUint16(m, 0, !0), E;
497
+ }
498
+ function jt(t, e = !0) {
499
+ const a = new TextEncoder().encode(t), u = new ArrayBuffer(14 + a.length), l = new DataView(u);
500
+ let i = 0;
501
+ return l.setUint8(i, ee.SET_CLIPBOARD), i += 1, l.setBigInt64(i, BigInt(0), !1), i += 8, l.setUint8(i, e ? 1 : 0), i += 1, l.setUint32(i, a.length, !1), i += 4, new Uint8Array(u, i).set(a), u;
502
+ }
503
+ function it(t, e, n = 0, a = 0) {
504
+ const u = new ArrayBuffer(14), l = new DataView(u);
505
+ let i = 0;
506
+ return l.setUint8(i, ee.INJECT_KEYCODE), i += 1, l.setUint8(i, t), i += 1, l.setInt32(i, e, !0), i += 4, l.setInt32(i, n, !0), i += 4, l.setInt32(i, a, !0), u;
507
+ }
508
+ function xn(t, e, n, a, u, l) {
509
+ const i = new ArrayBuffer(18), E = new DataView(i);
510
+ return E.setUint8(0, ee.INJECT_MOUSE_EVENT), E.setUint8(1, t), E.setInt32(2, Math.round(a), !0), E.setInt32(6, Math.round(u), !0), E.setUint16(10, e, !0), E.setUint16(12, n, !0), E.setInt32(14, l, !0), i;
511
+ }
512
+ function Xt(t, e) {
513
+ const n = new ArrayBuffer(4), a = new DataView(n);
514
+ return a.setUint8(0, ee.INJECT_MAC_KEY), a.setUint8(1, t), a.setUint16(2, e, !0), n;
515
+ }
516
+ function Wn(t, e, n, a, u, l) {
517
+ const i = new ArrayBuffer(21), E = new DataView(i);
518
+ return E.setUint8(0, ee.INJECT_MAC_SCROLL), E.setInt32(1, Math.round(n), !0), E.setInt32(5, Math.round(a), !0), E.setUint16(9, t, !0), E.setUint16(11, e, !0), E.setFloat32(13, u, !0), E.setFloat32(17, l, !0), i;
519
+ }
520
+ function qn(t) {
521
+ return t?.displays.find((e) => e.id === (t.angleDegrees < 90 ? "outer" : "inner"));
522
+ }
523
+ function Qt(t) {
524
+ return t === 2 ? 2 : t === 3 ? 1 : t === 4 ? 3 : 0;
525
+ }
526
+ class Vn {
527
+ constructor(e) {
528
+ this.send = e;
529
+ }
530
+ send;
531
+ screenId;
532
+ turns = 0;
533
+ held;
534
+ get active() {
535
+ return this.held !== void 0;
536
+ }
537
+ setDisplay(e, n = Qt(e?.orientation)) {
538
+ (this.screenId !== e?.screenId || this.turns !== n) && this.release(), this.screenId = e?.screenId, this.turns = n;
539
+ }
540
+ /** Coordinates are normalized; native input already accounts for the viewer's rotation. */
541
+ touch(e, n, a, u = !1) {
542
+ if (this.screenId === void 0) return;
543
+ const l = zt(n, a, u ? 0 : this.turns);
544
+ 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));
545
+ }
546
+ /** Call on pointer cancellation, lost capture, disconnect, and viewer disposal. */
547
+ release() {
548
+ if (!this.held) return;
549
+ const { screenId: e, x: n, y: a } = this.held;
550
+ this.held = void 0, this.send(1, e, n, a);
551
+ }
552
+ }
553
+ const $n = { width: 164.6, height: 117.8, depth: 5.2 };
554
+ function zt(t, e, n) {
555
+ return t = Math.max(0, Math.min(1, t)), e = Math.max(0, Math.min(1, e)), n === 1 ? { x: e, y: 1 - t } : n === 2 ? { x: 1 - t, y: 1 - e } : n === 3 ? { x: 1 - e, y: t } : { x: t, y: e };
556
+ }
557
+ function Zt(t) {
558
+ return Number.isFinite(t) && t >= 0 && t <= 180;
559
+ }
560
+ function Hn(t, e) {
561
+ return { x: Math.max(0, Math.min(1, t)), y: Math.max(0, Math.min(1, 1 - e)) };
562
+ }
563
+ function Jn(t, e, n) {
564
+ return e && (t || !n) ? "touch" : t ? "ignore" : "orbit";
565
+ }
566
+ function en(t, e, n, a) {
567
+ if (!Number.isInteger(t) || t < 0 || t > 3 || !Number.isInteger(e) || e < 1 || e > 255 || !Number.isFinite(n) || !Number.isFinite(a) || n < 0 || n > 1 || a < 0 || a > 1)
568
+ throw new RangeError("Invalid display touch coordinates");
569
+ const u = new ArrayBuffer(12), l = new DataView(u);
570
+ return l.setUint8(0, 19), l.setUint8(1, t), l.setUint8(2, e), l.setFloat32(4, n, !0), l.setFloat32(8, a, !0), u;
571
+ }
572
+ class Gn {
573
+ constructor(e, n) {
574
+ this.send = e, this.failed = n;
575
+ }
576
+ send;
577
+ failed;
578
+ latest;
579
+ running = !1;
580
+ stopped = !1;
581
+ set(e) {
582
+ this.stopped || !Zt(e) || (this.latest = e, this.flush());
583
+ }
584
+ stop() {
585
+ this.stopped = !0, this.latest = void 0;
586
+ }
587
+ async flush() {
588
+ if (!(this.running || this.stopped)) {
589
+ this.running = !0;
590
+ try {
591
+ for (; this.latest !== void 0 && !this.stopped; ) {
592
+ const e = this.latest;
593
+ this.latest = void 0, await this.send(e);
594
+ }
595
+ } catch (e) {
596
+ this.latest = void 0, this.stopped || this.failed(e);
597
+ } finally {
598
+ this.running = !1;
599
+ }
600
+ }
601
+ }
602
+ }
603
+ const jn = {
604
+ side: "Sleep/Wake",
605
+ volumeUp: "Volume Up",
606
+ volumeDown: "Volume Down"
607
+ };
608
+ class Xn {
609
+ constructor(e, n) {
610
+ this.send = e, this.failed = n;
611
+ }
612
+ send;
613
+ failed;
614
+ held;
615
+ tail = Promise.resolve();
616
+ timeout;
617
+ press(e) {
618
+ this.held || (this.held = e, this.enqueue(e, !0), this.timeout = setTimeout(() => this.release(), 1e4));
619
+ }
620
+ release() {
621
+ if (!this.held) return;
622
+ clearTimeout(this.timeout);
623
+ const e = this.held;
624
+ this.held = void 0, this.enqueue(e, !1);
625
+ }
626
+ enqueue(e, n) {
627
+ this.tail = this.tail.then(() => this.send(e, n)).catch(this.failed);
628
+ }
629
+ }
630
+ const ot = "Accessibility unavailable on this device.", Xe = 500, wt = (t, e) => Math.abs(t.x - e.x) < 0.5 && Math.abs(t.y - e.y) < 0.5 && Math.abs(t.width - e.width) < 0.5 && Math.abs(t.height - e.height) < 0.5, tn = (t) => Math.max(0, t.width) * Math.max(0, t.height), nn = (t) => {
631
+ const e = t.find((n) => n.frame && n.frame.width > 0 && n.frame.height > 0);
632
+ return e?.frame ? ((Math.abs(e.frame.x) > 0.5 || Math.abs(e.frame.y) > 0.5) && console.warn(
633
+ `[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.`
634
+ ), { x: 0, y: 0, width: e.frame.width, height: e.frame.height }) : { x: 0, y: 0, width: 1, height: 1 };
635
+ }, rn = (t) => {
636
+ const e = {};
637
+ 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;
638
+ }, on = (t) => {
639
+ const e = {};
640
+ for (const [n, a] of Object.entries(t))
641
+ n !== "children" && (e[n] = a);
642
+ return e;
643
+ };
644
+ function an(t) {
645
+ const e = Array.isArray(t) ? t : [t], n = nn(e), a = [], u = (l, i) => {
646
+ if (a.length >= Xe) return;
647
+ const E = l.frame;
648
+ if (E && E.width > 0 && E.height > 0 && !wt(E, n)) {
649
+ const m = l.role_description || l.role || "", S = (typeof l.AXLabel == "string" ? l.AXLabel : "") || (typeof l.title == "string" ? l.title : "") || "";
650
+ a.push({
651
+ id: typeof l.AXUniqueId == "string" && l.AXUniqueId.length > 0 ? l.AXUniqueId : i,
652
+ path: i,
653
+ label: S,
654
+ value: typeof l.AXValue == "string" ? l.AXValue : "",
655
+ role: m,
656
+ type: typeof l.type == "string" ? l.type : "",
657
+ enabled: l.enabled !== !1,
658
+ focused: l.focused === !0,
659
+ frame: { x: E.x, y: E.y, width: E.width, height: E.height },
660
+ selectors: rn(l),
661
+ raw: on(l)
662
+ });
663
+ }
664
+ const O = Array.isArray(l.children) ? l.children : [];
665
+ for (let m = 0; m < O.length && a.length < Xe; m++)
666
+ u(O[m], `${i}.${m}`);
667
+ };
668
+ for (let l = 0; l < e.length && a.length < Xe; l++)
669
+ u(e[l], String(l));
670
+ return {
671
+ platform: "ios",
672
+ screen: { width: n.width, height: n.height },
673
+ elements: a,
674
+ capturedAt: Date.now()
675
+ };
676
+ }
677
+ const sn = (t) => {
678
+ let e = { x: 0, y: 0, width: 1, height: 1 }, n = 0;
679
+ for (const a of t) {
680
+ const u = a.parsedBounds;
681
+ if (!u) continue;
682
+ const l = u.right - u.left, i = u.bottom - u.top, E = Math.max(0, l) * Math.max(0, i);
683
+ E > n && (n = E, e = { x: 0, y: 0, width: l, height: i });
684
+ }
685
+ return e;
686
+ }, cn = (t) => {
687
+ const e = {};
688
+ 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;
689
+ };
690
+ function ln(t) {
691
+ const e = sn(t), n = [];
692
+ for (let a = 0; a < t.length && n.length < Xe; a++) {
693
+ const u = t[a], l = u.parsedBounds;
694
+ if (!l) continue;
695
+ const i = Math.max(0, l.right - l.left), E = Math.max(0, l.bottom - l.top);
696
+ if (i <= 0 || E <= 0) continue;
697
+ const O = { x: l.left, y: l.top, width: i, height: E };
698
+ if (wt(O, { x: 0, y: 0, width: e.width, height: e.height })) continue;
699
+ const m = u.contentDesc || u.text || "", S = u.className || "";
700
+ n.push({
701
+ id: u.resourceId && u.resourceId.length > 0 ? u.resourceId : u.contentDesc && u.contentDesc.length > 0 ? `cd:${u.contentDesc}` : String(a),
702
+ path: String(a),
703
+ label: m,
704
+ value: typeof u.text == "string" ? u.text : "",
705
+ role: S,
706
+ type: S,
707
+ enabled: u.enabled !== !1,
708
+ focused: u.focused === !0,
709
+ frame: O,
710
+ selectors: cn(u),
711
+ raw: { ...u }
712
+ });
713
+ }
714
+ return {
715
+ platform: "android",
716
+ screen: { width: e.width, height: e.height },
717
+ elements: n,
718
+ capturedAt: Date.now()
719
+ };
720
+ }
721
+ function Qn(t, e) {
722
+ const n = Math.max(0, t.x), a = 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 - n), E = Math.max(0, l - a);
723
+ return i > 0 && E > 0 ? { x: n, y: a, width: i, height: E } : null;
724
+ }
725
+ function dn(t, e) {
726
+ if (t === e) return !0;
727
+ 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;
728
+ const n = t.frame, a = e.frame;
729
+ return n.x === a.x && n.y === a.y && n.width === a.width && n.height === a.height;
730
+ }
731
+ function un(t, e) {
732
+ if (t === e) return !0;
733
+ 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;
734
+ for (let n = 0; n < t.elements.length; n++)
735
+ if (!dn(t.elements[n], e.elements[n])) return !1;
736
+ return !0;
737
+ }
738
+ function zn(t, e, n) {
739
+ let a = null, u = 1 / 0;
740
+ for (const l of t.elements) {
741
+ const i = l.frame;
742
+ if (e < i.x || n < i.y || e > i.x + i.width || n > i.y + i.height) continue;
743
+ const E = tn(i);
744
+ E < u && (u = E, a = l);
745
+ }
746
+ return a;
747
+ }
748
+ function Zn(t, e) {
749
+ if (e === "ios") {
750
+ if (t.selectors.AXUniqueId)
751
+ return `client.tapElement({ AXUniqueId: ${JSON.stringify(t.selectors.AXUniqueId)} })`;
752
+ if (t.selectors.AXLabel) {
753
+ const n = t.selectors.className ? `, type: ${JSON.stringify(t.selectors.className)}` : "";
754
+ return `client.tapElement({ AXLabel: ${JSON.stringify(t.selectors.AXLabel)}${n} })`;
755
+ }
756
+ return null;
757
+ }
758
+ 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;
759
+ }
760
+ function fn(t) {
761
+ const e = t.role || t.type || "";
762
+ if (!e) return "element";
763
+ let n = e.replace(/^AX/, "");
764
+ return n.includes(".") && (n = n.split(".").pop()), n === "GenericElement" ? "Element" : (n = n.replace(/([a-z])([A-Z])/g, "$1 $2"), n);
765
+ }
766
+ const yt = 80;
767
+ function er(t) {
768
+ const e = fn(t), n = t.label || t.value || "";
769
+ if (!n) return e;
770
+ const a = n.length > yt ? n.slice(0, yt).trimEnd() + "…" : n;
771
+ return `${e} · ${a}`;
772
+ }
773
+ const En = 500, hn = 2e3, St = 5e3, mn = 8e3, pn = 1200, Cn = 250, On = () => `ax-rc-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
774
+ class Dn {
775
+ platform;
776
+ send;
777
+ onSnapshot;
778
+ onStatusChange;
779
+ baseIntervalMs;
780
+ maxBackoffMs;
781
+ androidElementTreeOptions;
782
+ pending = /* @__PURE__ */ new Map();
783
+ running = !1;
784
+ timer;
785
+ currentInterval;
786
+ lastSnapshot = null;
787
+ // Single-flight: only one outstanding request at a time. Avoids piling
788
+ // identical requests on a slow server.
789
+ inflight = !1;
790
+ // Rate-limit floor for bumpActivity so high-frequency input (drags,
791
+ // typing) doesn't trigger a request storm.
792
+ lastBumpAtMs = 0;
793
+ // Wall-clock timestamp until which we're in "activity boost" mode and
794
+ // schedule fetches at ACTIVITY_BOOST_INTERVAL_MS instead of the normal
795
+ // backed-off interval. Set by bumpActivity().
796
+ boostUntilMs = 0;
797
+ // Coarse-grained current status; deduplicated before emission so
798
+ // identical-to-current transitions are no-ops.
799
+ status = "idle";
800
+ constructor(e) {
801
+ this.platform = e.platform, this.send = e.send, this.onSnapshot = e.onSnapshot, this.onStatusChange = e.onStatusChange, this.baseIntervalMs = e.baseIntervalMs ?? En, this.maxBackoffMs = e.maxBackoffMs ?? hn, this.androidElementTreeOptions = e.androidElementTreeOptions, this.currentInterval = this.baseIntervalMs;
802
+ }
803
+ start() {
804
+ this.running || (this.running = !0, this.currentInterval = this.baseIntervalMs, this.boostUntilMs = 0, this.setStatus("starting"), this.runOnce());
805
+ }
806
+ stop() {
807
+ 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));
808
+ }
809
+ getStatus() {
810
+ return this.status;
811
+ }
812
+ setStatus(e, n) {
813
+ if (this.status !== e && (this.status = e, !!this.onStatusChange))
814
+ try {
815
+ this.onStatusChange(e, n);
816
+ } catch (a) {
817
+ console.error("[AxFetcher] onStatusChange threw:", a);
818
+ }
819
+ }
820
+ // Called after any user-driven action that's likely to change the UI
821
+ // (taps, scrolls, key events, openUrl, app termination, orientation
822
+ // change, etc.). Has two effects:
823
+ //
824
+ // 1. Resets the polling interval to base and triggers an immediate
825
+ // fetch (rate-limited so drags / rapid typing don't request-storm).
826
+ // 2. Enters a brief "boost" window during which scheduleNext() uses a
827
+ // shorter interval (ACTIVITY_BOOST_INTERVAL_MS), so we capture the
828
+ // mid- and post-animation tree without waiting for the next
829
+ // back-off cycle.
830
+ bumpActivity() {
831
+ if (!this.running) return;
832
+ const e = Date.now();
833
+ this.boostUntilMs = e + pn;
834
+ const n = Math.max(150, Math.floor(this.baseIntervalMs / 2));
835
+ if (e - this.lastBumpAtMs < n) {
836
+ this.currentInterval = this.baseIntervalMs;
837
+ return;
838
+ }
839
+ this.lastBumpAtMs = e, this.currentInterval = this.baseIntervalMs, this.timer !== void 0 && (window.clearTimeout(this.timer), this.timer = void 0), this.inflight || this.runOnce();
840
+ }
841
+ // Fire a one-shot fetch independent of the poll loop. Useful for the
842
+ // imperative refresh() ref method customers may call.
843
+ //
844
+ // Goes through the same change-detect path as the regular poll loop —
845
+ // identical-to-last-snapshot responses do NOT re-emit via onSnapshot, so
846
+ // a customer calling refresh() in a tight loop doesn't see a stream of
847
+ // duplicate snapshots. The returned promise still resolves with the
848
+ // (possibly identical) snapshot for the caller's own use.
849
+ async refresh() {
850
+ const e = await this.requestOnce();
851
+ return this.running && this.deliver(e), e;
852
+ }
853
+ // Returns the latest snapshot delivered to onSnapshot. May be stale.
854
+ getLatest() {
855
+ return this.lastSnapshot;
856
+ }
857
+ // Called by RemoteControl's ws.onmessage when it sees a message type we own.
858
+ // Returns true when the message was a response we were waiting for.
859
+ handleMessage(e) {
860
+ if (!e || typeof e.id != "string") return !1;
861
+ const n = e.id;
862
+ if (!this.pending.get(n)) return !1;
863
+ if (this.platform === "ios") {
864
+ if (e.type !== "elementTreeResult") return !1;
865
+ const E = typeof e.error == "string" ? e.error : null;
866
+ if (E)
867
+ return this.settleReject(n, new Error(E)), !0;
868
+ const O = typeof e.json == "string" ? e.json : "";
869
+ try {
870
+ const m = JSON.parse(O), S = an(m);
871
+ this.settleResolve(n, S);
872
+ } catch (m) {
873
+ this.settleReject(n, m instanceof Error ? m : new Error(String(m)));
874
+ }
875
+ return !0;
876
+ }
877
+ if (e.type !== "getElementTreeResult") return !1;
878
+ const u = e.error;
879
+ if (u && typeof u == "object") {
880
+ const E = typeof u.message == "string" ? u.message : "getElementTree failed";
881
+ return this.settleReject(n, new Error(E)), !0;
882
+ }
883
+ const l = e.payload, i = Array.isArray(l?.nodes) ? l.nodes : [];
884
+ try {
885
+ const E = ln(i);
886
+ this.settleResolve(n, E);
887
+ } catch (E) {
888
+ this.settleReject(n, E instanceof Error ? E : new Error(String(E)));
889
+ }
890
+ return !0;
891
+ }
892
+ buildRequest(e) {
893
+ return this.platform === "ios" ? { type: "elementTree", id: e } : { type: "getElementTree", id: e, ...this.androidElementTreeOptions };
894
+ }
895
+ async requestOnce() {
896
+ const e = On();
897
+ return new Promise((n, a) => {
898
+ const u = window.setTimeout(
899
+ () => {
900
+ this.pending.delete(e), a(new Error("elementTree request timed out"));
901
+ },
902
+ mn + (this.androidElementTreeOptions?.waitForIdleTimeoutMs ?? 0)
903
+ );
904
+ this.pending.set(e, { resolve: n, reject: a, timer: u }), this.send(this.buildRequest(e)) || (window.clearTimeout(u), this.pending.delete(e), a(new Error("elementTree send failed (WebSocket not open)")));
905
+ });
906
+ }
907
+ async runOnce() {
908
+ if (this.running && !this.inflight) {
909
+ this.inflight = !0;
910
+ try {
911
+ const e = await this.requestOnce();
912
+ if (!this.running) return;
913
+ this.deliver(e);
914
+ } catch (e) {
915
+ if (!this.running) return;
916
+ const n = e instanceof Error ? e.message : String(e), a = /unavailable|not (yet )?running|failed|timeout/i.test(n);
917
+ this.currentInterval = a ? St : Math.min(this.currentInterval * 2, this.maxBackoffMs), this.setStatus(a ? "unavailable" : "error", n);
918
+ } finally {
919
+ this.inflight = !1, this.scheduleNext();
920
+ }
921
+ }
922
+ }
923
+ deliver(e) {
924
+ const n = this.lastSnapshot;
925
+ if (un(n, e)) {
926
+ this.currentInterval = Math.min(this.currentInterval * 2, this.maxBackoffMs), this.lastSnapshot = e, e.errors?.includes(ot) || this.setStatus("ready");
927
+ return;
928
+ }
929
+ this.lastSnapshot = e, this.currentInterval = this.baseIntervalMs, e.errors?.includes(ot) ? (this.currentInterval = St, this.setStatus("unavailable", ot)) : this.setStatus("ready"), this.onSnapshot(e);
930
+ }
931
+ scheduleNext() {
932
+ if (!this.running) return;
933
+ this.timer !== void 0 && window.clearTimeout(this.timer);
934
+ const e = Date.now() < this.boostUntilMs ? Math.min(Cn, this.currentInterval) : this.currentInterval;
935
+ this.timer = window.setTimeout(() => {
936
+ this.timer = void 0, this.runOnce();
937
+ }, e);
938
+ }
939
+ settleResolve(e, n) {
940
+ const a = this.pending.get(e);
941
+ a && (window.clearTimeout(a.timer), this.pending.delete(e), a.resolve(n));
942
+ }
943
+ settleReject(e, n) {
944
+ const a = this.pending.get(e);
945
+ a && (window.clearTimeout(a.timer), this.pending.delete(e), a.reject(n));
946
+ }
947
+ failAllPending(e) {
948
+ for (const [n, a] of this.pending.entries())
949
+ window.clearTimeout(a.timer), a.reject(new Error(e)), this.pending.delete(n);
950
+ }
951
+ }
952
+ function Kt(t, e) {
953
+ if (e != null && (!Number.isFinite(e) || e < 0 || e > 4e3)) {
954
+ console.warn("RemoteControl: jitterBufferTargetMs must be a finite number between 0 and 4000.");
955
+ return;
956
+ }
957
+ if (!("jitterBufferTarget" in t)) return;
958
+ const n = e ?? null;
959
+ try {
960
+ t.jitterBufferTarget !== n && (t.jitterBufferTarget = n);
961
+ } catch (a) {
962
+ console.warn("RemoteControl: could not set the jitter buffer target.", a);
963
+ }
964
+ }
965
+ const Nt = `(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())}})();
966
+ `, At = typeof self < "u" && self.Blob && new Blob(["(self.URL || self.webkitURL).revokeObjectURL(self.location.href);", Nt], { type: "text/javascript;charset=utf-8" });
967
+ function _n(t) {
968
+ let e;
969
+ try {
970
+ if (e = At && (self.URL || self.webkitURL).createObjectURL(At), !e) throw "";
971
+ const n = new Worker(e, {
972
+ name: t?.name
973
+ });
974
+ return n.addEventListener("error", () => {
975
+ (self.URL || self.webkitURL).revokeObjectURL(e);
976
+ }), n;
977
+ } catch {
978
+ return new Worker(
979
+ "data:text/javascript;charset=utf-8," + encodeURIComponent(Nt),
980
+ {
981
+ name: t?.name
982
+ }
983
+ );
984
+ }
985
+ }
986
+ function gn(t, e, n) {
987
+ const { MediaStreamTrackProcessor: a, MediaStreamTrackGenerator: u } = globalThis, l = e.getVideoTracks()[0];
988
+ let i, E, O, m, S = !1;
989
+ const w = () => {
990
+ S || (S = !0, i?.stop(), E?.stop(), O && (O.postMessage({ type: "stop" }), m = setTimeout(() => O?.terminate(), 1e3)));
991
+ }, N = (D) => {
992
+ t.srcObject = D, t.play().catch(() => {
993
+ });
994
+ }, q = (D) => {
995
+ S || (w(), n(D), N(e));
996
+ };
997
+ try {
998
+ if (l && a && u) {
999
+ i = l.clone();
1000
+ const D = new a({ track: i, maxBufferSize: 1 }), H = new u({ kind: "video" });
1001
+ E = H, O = new _n(), O.onmessage = ({ data: L }) => {
1002
+ L.type === "error" ? q(new Error(L.message)) : L.type === "stopped" && (clearTimeout(m), O?.terminate());
1003
+ }, O.onerror = (L) => q(new Error(L.message)), O.postMessage({ type: "start", readable: D.readable, writable: H.writable }, [
1004
+ D.readable,
1005
+ H.writable
1006
+ ]), N(new MediaStream(e.getTracks().map((L) => L === l ? H : L)));
1007
+ } else
1008
+ N(e);
1009
+ } catch (D) {
1010
+ q(D);
1011
+ }
1012
+ return w;
1013
+ }
1014
+ function Re(t) {
1015
+ return typeof t == "number" && Number.isFinite(t);
1016
+ }
1017
+ function Te(t, e) {
1018
+ if (!(!Re(t) || !Re(e) || t < e || e < 0))
1019
+ return t - e;
1020
+ }
1021
+ class Tn {
1022
+ previous = /* @__PURE__ */ new Map();
1023
+ reset() {
1024
+ this.previous.clear();
1025
+ }
1026
+ read(e, n, a) {
1027
+ const u = { timestamp: 0, video: [], audio: [] };
1028
+ a == null ? u.requestedTargetMs = null : Re(a) && a >= 0 && a <= 4e3 && (u.requestedTargetMs = a);
1029
+ const l = /* @__PURE__ */ new Map();
1030
+ return e.forEach((i) => {
1031
+ if (i.type !== "inbound-rtp" || !Re(i.timestamp)) return;
1032
+ const E = i.kind ?? i.mediaType;
1033
+ if (E !== "video" && E !== "audio") return;
1034
+ const O = n.filter((P) => P.kind === E), m = i.trackIdentifier ? O.find((P) => P.trackId === i.trackIdentifier) : i.mid != null ? O.find((P) => P.mid === i.mid) : O.length === 1 ? O[0] : void 0;
1035
+ if (!m) return;
1036
+ const S = this.previous.get(i.id), N = S?.trackId === m.trackId && S.stats.ssrc === i.ssrc ? S.stats : void 0, q = N ? i.timestamp - N.timestamp : void 0, D = {
1037
+ id: i.id,
1038
+ trackId: m.trackId,
1039
+ timestamp: i.timestamp
1040
+ };
1041
+ if (q !== void 0 && q > 0) {
1042
+ D.intervalMs = q;
1043
+ const P = Te(i.jitterBufferEmittedCount, N?.jitterBufferEmittedCount), B = Te(i.jitterBufferDelay, N?.jitterBufferDelay);
1044
+ P !== void 0 && P > 0 && B !== void 0 && (D.bufferDelayMs = B / P * 1e3);
1045
+ const V = Te(i.bytesReceived, N?.bytesReceived);
1046
+ V !== void 0 && (D.bitrateBps = V * 8e3 / q);
1047
+ }
1048
+ if (E === "video") {
1049
+ const P = { ...D, display: m.display ?? "primary" };
1050
+ if (D.intervalMs !== void 0) {
1051
+ const B = Te(i.framesDecoded, N?.framesDecoded);
1052
+ B !== void 0 && (P.fps = B * 1e3 / D.intervalMs), P.droppedFrames = Te(i.framesDropped, N?.framesDropped), P.freezes = Te(i.freezeCount, N?.freezeCount);
1053
+ }
1054
+ u.video.push(P);
1055
+ } else u.audio.push(D);
1056
+ u.timestamp = Math.max(u.timestamp, i.timestamp), l.set(
1057
+ i.id,
1058
+ N && i.timestamp <= N.timestamp ? S : { stats: i, trackId: m.trackId }
1059
+ );
1060
+ const H = i.transportId ? e.get(i.transportId) : void 0, L = H?.selectedCandidatePairId ? e.get(H.selectedCandidatePairId) : void 0;
1061
+ L?.state === "succeeded" && Re(L.currentRoundTripTime) && L.currentRoundTripTime >= 0 && (u.rttMs = L.currentRoundTripTime * 1e3);
1062
+ }), this.previous = l, u.video.length || u.audio.length ? u : null;
1063
+ }
1064
+ }
1065
+ const at = /* @__PURE__ */ new WeakSet();
1066
+ function yn(t, e, n) {
1067
+ const { peer: a, displays: u } = t, l = new Tn();
1068
+ let i, E = !1, O = !1, m = !1, S = 0, w = !1, N = !1;
1069
+ const q = () => !E && !document.hidden && a.connectionState === "connected", D = (B) => {
1070
+ if (!(!B && !w)) {
1071
+ w = B !== null;
1072
+ try {
1073
+ e()?.(B);
1074
+ } catch (V) {
1075
+ console.error('[RemoteControl] customer callback "onPlaybackStats" threw:', V);
1076
+ }
1077
+ }
1078
+ }, H = () => {
1079
+ O = !1, S++, clearTimeout(i), l.reset(), D(null);
1080
+ }, L = async () => {
1081
+ if (m || !q()) return;
1082
+ if (at.has(a)) {
1083
+ i = setTimeout(() => {
1084
+ L();
1085
+ }, 2e3);
1086
+ return;
1087
+ }
1088
+ m = !0, at.add(a);
1089
+ const B = S;
1090
+ try {
1091
+ const V = await a.getStats();
1092
+ if (B !== S || !q()) return;
1093
+ const se = a.getTransceivers().filter(
1094
+ (Y) => (Y.currentDirection === "recvonly" || Y.currentDirection === "sendrecv") && Y.receiver.track.readyState !== "ended"
1095
+ ).map((Y) => ({
1096
+ trackId: Y.receiver.track.id,
1097
+ kind: Y.receiver.track.kind,
1098
+ mid: Y.mid,
1099
+ display: u.get(Y.receiver)
1100
+ }));
1101
+ D(l.read(V, se, n())), N = !1;
1102
+ } catch (V) {
1103
+ if (B !== S || !q()) return;
1104
+ N || console.warn("[RemoteControl] could not read playback stats:", V), N = !0, l.reset(), D(null);
1105
+ } finally {
1106
+ m = !1, at.delete(a), O && q() && (i = setTimeout(
1107
+ () => {
1108
+ L();
1109
+ },
1110
+ B === S ? 2e3 : 0
1111
+ ));
1112
+ }
1113
+ }, P = () => {
1114
+ if (!q()) {
1115
+ H();
1116
+ return;
1117
+ }
1118
+ O || (O = !0, L());
1119
+ };
1120
+ return document.addEventListener("visibilitychange", P), a.addEventListener("connectionstatechange", P), P(), () => {
1121
+ E = !0, document.removeEventListener("visibilitychange", P), a.removeEventListener("connectionstatechange", P), H();
1122
+ };
1123
+ }
1124
+ function Sn(t, e) {
1125
+ const n = t.createDataChannel("latency-trace-v1", {
1126
+ ordered: !0,
1127
+ negotiated: !0,
1128
+ id: 2
1129
+ });
1130
+ let a = !1, u = !1, l = 0;
1131
+ return n.onmessage = (i) => {
1132
+ if (u) return;
1133
+ let E;
1134
+ try {
1135
+ E = JSON.parse(i.data);
1136
+ } catch (O) {
1137
+ console.warn("Invalid latency trace message", O);
1138
+ return;
1139
+ }
1140
+ E && typeof E == "object" && !Array.isArray(E) && e(E);
1141
+ }, n.onclose = () => {
1142
+ u = !0, a = !1;
1143
+ }, {
1144
+ accept(i) {
1145
+ a = !u && i === 1;
1146
+ },
1147
+ wrap(i) {
1148
+ if (!a || i.byteLength === 0) return i;
1149
+ const E = new DataView(i), O = E.getUint8(0), m = O === ee.INJECT_MOUSE_EVENT || O === ee.INJECT_MAC_KEY || O === ee.INJECT_MAC_SCROLL, S = i.byteLength === 32 && O === ee.INJECT_TOUCH_EVENT && E.getUint8(1) <= 2;
1150
+ if (!m && !S) return i;
1151
+ const w = new ArrayBuffer(6 + i.byteLength), N = new DataView(w);
1152
+ return N.setUint8(0, 240), N.setUint8(1, 1), N.setUint32(2, ++l, !0), new Uint8Array(w, 6).set(new Uint8Array(i)), w;
1153
+ },
1154
+ close() {
1155
+ u = !0, a = !1, n.onmessage = null, n.onclose = null, n.close();
1156
+ }
1157
+ };
1158
+ }
1159
+ class Kn {
1160
+ generation = 0;
1161
+ tail = Promise.resolve();
1162
+ get currentGeneration() {
1163
+ return this.generation;
1164
+ }
1165
+ enqueue(e) {
1166
+ const n = ++this.generation;
1167
+ return this.append(n, e);
1168
+ }
1169
+ /**
1170
+ * Queues related work without superseding an already queued request.
1171
+ *
1172
+ * The operation retains the generation current at enqueue time and becomes
1173
+ * stale if a later camera request increments it before this work starts.
1174
+ */
1175
+ enqueueCurrent(e) {
1176
+ return this.append(this.generation, e);
1177
+ }
1178
+ append(e, n) {
1179
+ const a = {
1180
+ generation: e,
1181
+ isCurrent: () => e === this.generation
1182
+ }, u = this.tail.then(() => n(a));
1183
+ return this.tail = u.catch(() => {
1184
+ }), u;
1185
+ }
1186
+ invalidate() {
1187
+ ++this.generation;
1188
+ }
1189
+ }
1190
+ function An(t) {
1191
+ if (!t || typeof t != "object") return null;
1192
+ const e = t;
1193
+ if (e.type !== "cameraRequest" || typeof e.active != "boolean") return null;
1194
+ const n = { active: e.active };
1195
+ return (e.facingMode === "user" || e.facingMode === "environment") && (n.facingMode = e.facingMode), n;
1196
+ }
1197
+ function Mn(t) {
1198
+ const e = {
1199
+ frameRate: { ideal: 30, max: 30 }
1200
+ };
1201
+ return t?.facingMode && (e.facingMode = { ideal: t.facingMode }), e;
1202
+ }
1203
+ function vn(t, e) {
1204
+ return !t || t.facingMode !== e.facingMode;
1205
+ }
1206
+ function wn(t) {
1207
+ const e = t.getSettings();
1208
+ return {
1209
+ width: e.width,
1210
+ height: e.height,
1211
+ frameRate: e.frameRate,
1212
+ deviceId: e.deviceId,
1213
+ label: t.label || void 0,
1214
+ facingMode: e.facingMode
1215
+ };
1216
+ }
1217
+ function Nn(t) {
1218
+ return {
1219
+ type: "cameraResult",
1220
+ granted: !0,
1221
+ camera: wn(t)
1222
+ };
1223
+ }
1224
+ const le = (...t) => {
1225
+ window.debugRemoteControl && console.log(...t);
1226
+ }, y = (...t) => {
1227
+ window.debugRemoteControl && console.warn(...t);
1228
+ }, F = (t, e, ...n) => {
1229
+ if (e)
1230
+ try {
1231
+ e(...n);
1232
+ } catch (a) {
1233
+ console.error(`[RemoteControl] customer callback "${t}" threw:`, a);
1234
+ }
1235
+ }, bn = (t) => t.includes("/android_") ? "android" : t.includes("/macos_") ? "macos" : "ios", Mt = (t, e) => {
1236
+ const n = new URL(t);
1237
+ return n.searchParams.set("token", e), n.toString();
1238
+ }, st = 3, Yn = 1e3, In = 15e3, Rn = 3e3, Un = 4e3;
1239
+ function vt() {
1240
+ const t = crypto.getRandomValues(new Uint8Array(16));
1241
+ t[6] = t[6] & 15 | 64, t[8] = t[8] & 63 | 128;
1242
+ const e = Array.from(t, (n) => n.toString(16).padStart(2, "0")).join("");
1243
+ return `${e.slice(0, 8)}-${e.slice(8, 12)}-${e.slice(12, 16)}-${e.slice(16, 20)}-${e.slice(20)}`;
1244
+ }
1245
+ function tr(t) {
1246
+ let e = { ...t };
1247
+ const { url: n, deviceModel: a } = e;
1248
+ let u = e.token;
1249
+ const l = e.watchOnly ?? !1, i = e.sessionId ?? vt(), E = e.platform ?? bn(n ?? "");
1250
+ let O = {
1251
+ connection: "idle",
1252
+ videoReady: !1,
1253
+ controlReady: !1,
1254
+ duo: !1,
1255
+ duoState: null
1256
+ };
1257
+ const m = (r) => {
1258
+ O = { ...O, ...r }, F("onStateChange", e.onStateChange, O);
1259
+ }, S = (r) => m({ videoReady: r }), w = (r) => m({ duoState: r }), N = (r) => m({ duoError: r }), q = (r) => m({ duo: r }), D = (r) => le(r);
1260
+ let H = null, L;
1261
+ const P = () => {
1262
+ L?.(), L = H && e.onPlaybackStats ? yn(
1263
+ H,
1264
+ () => e.onPlaybackStats,
1265
+ () => e.jitterBufferTargetMs
1266
+ ) : void 0;
1267
+ }, B = /* @__PURE__ */ new Map(), V = /* @__PURE__ */ new Set(), se = /* @__PURE__ */ new Set(), Y = /* @__PURE__ */ new Map();
1268
+ let ye = !1;
1269
+ const Ue = /* @__PURE__ */ new Map(), ct = (r, f, c) => {
1270
+ f.stop?.(), f.stop = gn(r, c, (d) => y("Video playback fallback:", d));
1271
+ }, bt = () => {
1272
+ Ue.clear();
1273
+ for (const [r, f] of B)
1274
+ f.clear?.(), f.stop?.(), f.stop = void 0, r.srcObject = null;
1275
+ };
1276
+ let Ee = !1, Se = !1, ke = 0, g = null, I = null, x = null, Pe = null, he, Ke, Ae, Le, me, de = 0, Fe = 0, ne = !1, ue = null, Q = null, fe;
1277
+ const Qe = new Kn();
1278
+ let Me = null, Be = null, ze = !l && (e.microphoneEnabled ?? !1), Ze = !1, ve = null, te = null, xe = 0, lt = Promise.resolve(), pe = null, we = !1, re = /* @__PURE__ */ new Map(), Z = /* @__PURE__ */ new Map(), ce = /* @__PURE__ */ new Map(), ie = /* @__PURE__ */ new Map(), $ = null, Ne = null, dt = 0;
1279
+ const We = (r) => {
1280
+ if (r === null && Ne === null) return;
1281
+ Ne = r;
1282
+ const f = ++dt;
1283
+ queueMicrotask(() => {
1284
+ f === dt && F("onAxSnapshotChange", e.onAxSnapshotChange, r);
1285
+ });
1286
+ };
1287
+ let Ce = null, Oe = /* @__PURE__ */ new Map();
1288
+ const Yt = (r, f) => new Promise((c, d) => {
1289
+ if (l) {
1290
+ d(new Error("Device is watch-only"));
1291
+ return;
1292
+ }
1293
+ const K = g;
1294
+ if (!K || K.readyState !== WebSocket.OPEN) {
1295
+ d(new Error("Simulator disconnected"));
1296
+ return;
1297
+ }
1298
+ const p = vt(), C = setTimeout(() => {
1299
+ Oe.delete(p), d(new Error("Device control timed out"));
1300
+ }, 5e3);
1301
+ Oe.set(p, { resolve: c, reject: d, timer: C }), K.send(JSON.stringify({ type: r, id: p, ...f }));
1302
+ }), De = (r) => {
1303
+ Ce !== r && (Ce = r, m({ connection: r }), F("onConnectionStateChange", e.onConnectionStateChange, r));
1304
+ }, oe = (r) => {
1305
+ l || !x || x.readyState !== "open" || (x.send(Pe?.wrap(r) ?? r), $?.bumpActivity());
1306
+ }, It = () => {
1307
+ g && g.readyState === WebSocket.OPEN && g.send(
1308
+ JSON.stringify({
1309
+ type: "keepAlive",
1310
+ sessionId: i
1311
+ })
1312
+ );
1313
+ }, ut = () => {
1314
+ he && window.clearInterval(he), he = window.setInterval(It, 1e4);
1315
+ }, be = () => {
1316
+ he && (window.clearInterval(he), he = void 0);
1317
+ }, qe = () => {
1318
+ Ke && (window.clearTimeout(Ke), Ke = void 0);
1319
+ }, Ve = () => {
1320
+ Ae && (window.clearTimeout(Ae), Ae = void 0);
1321
+ }, Ye = () => {
1322
+ Le && (window.clearInterval(Le), Le = void 0);
1323
+ }, Ie = () => {
1324
+ me !== void 0 && (window.clearTimeout(me), me = void 0);
1325
+ }, Rt = () => {
1326
+ we || (we = !0, Ye(), S(!0), De("connected"));
1327
+ }, J = (r) => {
1328
+ for (const f of r.getTracks())
1329
+ try {
1330
+ f.stop();
1331
+ } catch (c) {
1332
+ y("track.stop() failed:", c);
1333
+ }
1334
+ }, Ut = () => {
1335
+ const r = Q;
1336
+ r && (Q = null, J(r));
1337
+ }, ft = (r) => {
1338
+ const f = lt.then(r).catch((c) => {
1339
+ y("microphone operation failed:", c);
1340
+ });
1341
+ return lt = f, f;
1342
+ }, et = () => ze || Ze, Et = (r) => {
1343
+ const f = `ui-mic-${Date.now()}-${Math.random().toString(36).substring(2, 9)}`;
1344
+ pe = f, r.send(JSON.stringify({ type: "microphoneStart", id: f }));
1345
+ }, tt = () => ft(() => kt()), kt = async () => {
1346
+ const r = xe, f = () => r === xe && et(), c = (h) => {
1347
+ F("onMicrophoneStateChange", e.onMicrophoneStateChange, {
1348
+ active: !1,
1349
+ error: h
1350
+ });
1351
+ };
1352
+ if (!f()) return;
1353
+ const d = g, K = ve;
1354
+ if (!d || d.readyState !== WebSocket.OPEN || !K || te) return;
1355
+ if (!navigator.mediaDevices || typeof navigator.mediaDevices.getUserMedia != "function") {
1356
+ console.warn(
1357
+ "[RemoteControl] navigator.mediaDevices.getUserMedia unavailable. getUserMedia requires a secure context (https or http://localhost)."
1358
+ ), c("Microphone capture requires a secure context (https)");
1359
+ return;
1360
+ }
1361
+ let p = null;
1362
+ try {
1363
+ p = await navigator.mediaDevices.getUserMedia({ audio: !0, video: !1 });
1364
+ } catch (h) {
1365
+ console.warn("[RemoteControl] microphone getUserMedia denied/failed:", h);
1366
+ }
1367
+ if (!f()) {
1368
+ p && J(p);
1369
+ return;
1370
+ }
1371
+ if (!p) {
1372
+ c("Microphone permission denied or no device available");
1373
+ return;
1374
+ }
1375
+ const C = p.getAudioTracks()[0] ?? null;
1376
+ if (!C) {
1377
+ J(p), c("Captured stream has no audio track");
1378
+ return;
1379
+ }
1380
+ try {
1381
+ await K.replaceTrack(C);
1382
+ } catch (h) {
1383
+ y("replaceTrack(audioTrack) failed:", h), J(p), c("Failed to attach the microphone track to the connection");
1384
+ return;
1385
+ }
1386
+ if (!f()) {
1387
+ try {
1388
+ await K.replaceTrack(null);
1389
+ } catch (h) {
1390
+ y("replaceTrack(null) on stale mic attach failed:", h);
1391
+ }
1392
+ J(p);
1393
+ return;
1394
+ }
1395
+ te = p, C.onended = () => {
1396
+ te === p && $e("microphone capture ended by the browser");
1397
+ }, Et(d), F("onMicrophoneStateChange", e.onMicrophoneStateChange, {
1398
+ active: !0,
1399
+ label: C.label || void 0
1400
+ });
1401
+ }, $e = (r) => (++xe, pe = null, ft(async () => {
1402
+ const f = ve, c = te;
1403
+ if (te = null, f && c)
1404
+ try {
1405
+ await f.replaceTrack(null);
1406
+ } catch (K) {
1407
+ y("replaceTrack(null) on mic detach failed:", K);
1408
+ }
1409
+ c && J(c);
1410
+ const d = g;
1411
+ if (c && d && d.readyState === WebSocket.OPEN) {
1412
+ const K = `ui-mic-${Date.now()}-${Math.random().toString(36).substring(2, 9)}`;
1413
+ d.send(JSON.stringify({ type: "microphoneStop", id: K }));
1414
+ }
1415
+ (c || r) && F("onMicrophoneStateChange", e.onMicrophoneStateChange, {
1416
+ active: !1,
1417
+ ...r !== void 0 && { error: r }
1418
+ });
1419
+ })), ht = (r, f) => {
1420
+ let c;
1421
+ try {
1422
+ c = Nn(f), console.info(
1423
+ `[RemoteControl] camera capture: ${c.camera?.width}x${c.camera?.height} @ ${c.camera?.frameRate ?? "?"}fps` + (c.camera?.label ? ` — ${c.camera.label}` : "")
1424
+ );
1425
+ } catch (d) {
1426
+ y("getSettings() on outbound camera track failed:", d), c = {
1427
+ type: "cameraResult",
1428
+ granted: !0,
1429
+ camera: {
1430
+ label: f.label || void 0
1431
+ }
1432
+ };
1433
+ }
1434
+ r.send(JSON.stringify(c)), F("onCameraDemandChange", e.onCameraDemandChange, !0, !0, c.camera);
1435
+ }, Pt = (r) => {
1436
+ if (!r) return;
1437
+ const f = r.indexOf("/"), d = (f >= 0 ? r.slice(f + 1) : r).toUpperCase();
1438
+ return d === "HEVC" ? "H265" : d;
1439
+ }, Lt = async () => {
1440
+ const r = ue, f = e.onCameraStats;
1441
+ if (!r || !f) return;
1442
+ let c;
1443
+ try {
1444
+ c = await r.getStats();
1445
+ } catch {
1446
+ return;
1447
+ }
1448
+ let d, K, p;
1449
+ if (c.forEach((U) => {
1450
+ U.type === "outbound-rtp" && U.kind === "video" ? d = U : U.type === "remote-inbound-rtp" && U.kind === "video" && (p = U);
1451
+ }), d?.codecId) {
1452
+ const U = c.get(d.codecId);
1453
+ U && (K = U.mimeType);
1454
+ }
1455
+ if (!d) return;
1456
+ const C = d.timestamp ?? Date.now(), h = Be;
1457
+ let R, b, G;
1458
+ if (h && C > h.timestamp) {
1459
+ const U = (C - h.timestamp) / 1e3;
1460
+ if (typeof d.framesEncoded == "number" && typeof h.framesEncoded == "number" && (R = Math.max(0, (d.framesEncoded - h.framesEncoded) / U)), typeof d.bytesSent == "number" && typeof h.bytesSent == "number" && (b = Math.max(0, (d.bytesSent - h.bytesSent) * 8 / U)), typeof d.packetsSent == "number" && typeof h.packetsSent == "number" && p && typeof p.packetsLost == "number" && typeof h.packetsLost == "number") {
1461
+ const A = d.packetsSent - h.packetsSent, Je = p.packetsLost - h.packetsLost;
1462
+ A > 0 && (G = Math.max(0, Math.min(100, Je / A * 100)));
1463
+ }
1464
+ }
1465
+ Be = {
1466
+ timestamp: C,
1467
+ framesEncoded: d.framesEncoded,
1468
+ bytesSent: d.bytesSent,
1469
+ packetsSent: d.packetsSent,
1470
+ packetsLost: p?.packetsLost
1471
+ };
1472
+ const v = {
1473
+ codec: Pt(K),
1474
+ encoderImplementation: d.encoderImplementation,
1475
+ hardwareAccelerated: typeof d.powerEfficientEncoder == "boolean" ? d.powerEfficientEncoder : void 0,
1476
+ framesPerSecond: R,
1477
+ framesEncoded: d.framesEncoded,
1478
+ bitrateBps: b,
1479
+ width: d.frameWidth,
1480
+ height: d.frameHeight,
1481
+ qualityLimitationReason: d.qualityLimitationReason,
1482
+ rttMs: typeof p?.roundTripTime == "number" ? p.roundTripTime * 1e3 : void 0,
1483
+ packetsLostPct: G
1484
+ };
1485
+ F("onCameraStats", e.onCameraStats, v);
1486
+ }, mt = () => {
1487
+ Me === null && (Be = null, Me = setInterval(() => {
1488
+ Lt();
1489
+ }, 1e3));
1490
+ }, He = () => {
1491
+ Me !== null && (clearInterval(Me), Me = null), Be = null, F("onCameraStats", e.onCameraStats, null);
1492
+ }, Ft = (r, f, c, d) => Qe.enqueue(async ({ isCurrent: K }) => {
1493
+ const p = () => K() && d() && g === f && ue === c;
1494
+ if (!p()) return;
1495
+ if (!r.active) {
1496
+ const v = Q;
1497
+ try {
1498
+ await c.replaceTrack(null);
1499
+ } catch (U) {
1500
+ y("replaceTrack(null) on camera detach failed:", U);
1501
+ }
1502
+ if (Q === v && (Q = null, fe = void 0, v && J(v)), He(), !p()) return;
1503
+ F("onCameraDemandChange", e.onCameraDemandChange, !1);
1504
+ return;
1505
+ }
1506
+ F("onCameraDemandChange", e.onCameraDemandChange, !0);
1507
+ const C = Q, h = C?.getVideoTracks()[0], R = fe;
1508
+ if (h?.readyState === "live" && R && !vn(R, r)) {
1509
+ fe = r, ht(f, h), mt();
1510
+ return;
1511
+ }
1512
+ if (C) {
1513
+ try {
1514
+ await c.replaceTrack(null);
1515
+ } catch (v) {
1516
+ y("replaceTrack(null) before camera switch failed:", v);
1517
+ }
1518
+ if (Q === C && (Q = null, fe = void 0, J(C)), He(), !p()) return;
1519
+ }
1520
+ if (!navigator.mediaDevices || typeof navigator.mediaDevices.getUserMedia != "function") {
1521
+ if (console.warn(
1522
+ "[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."
1523
+ ), !p()) return;
1524
+ f.send(JSON.stringify({ type: "cameraResult", granted: !1 })), F("onCameraDemandChange", e.onCameraDemandChange, !0, !1);
1525
+ return;
1526
+ }
1527
+ let b = null;
1528
+ try {
1529
+ b = await navigator.mediaDevices.getUserMedia({
1530
+ video: Mn(r),
1531
+ audio: !1
1532
+ });
1533
+ } catch (v) {
1534
+ console.warn("[RemoteControl] getUserMedia denied/failed:", v);
1535
+ }
1536
+ if (!p()) {
1537
+ b && J(b);
1538
+ return;
1539
+ }
1540
+ if (!b) {
1541
+ f.send(JSON.stringify({ type: "cameraResult", granted: !1 })), F("onCameraDemandChange", e.onCameraDemandChange, !0, !1);
1542
+ return;
1543
+ }
1544
+ const G = b.getVideoTracks()[0] ?? null;
1545
+ if (!G) {
1546
+ if (J(b), !p()) return;
1547
+ f.send(JSON.stringify({ type: "cameraResult", granted: !1 })), F("onCameraDemandChange", e.onCameraDemandChange, !0, !1);
1548
+ return;
1549
+ }
1550
+ try {
1551
+ G.contentHint = "motion";
1552
+ } catch {
1553
+ }
1554
+ try {
1555
+ await c.replaceTrack(G);
1556
+ } catch (v) {
1557
+ if (y("replaceTrack(videoTrack) failed:", v), J(b), !p()) return;
1558
+ f.send(JSON.stringify({ type: "cameraResult", granted: !1 })), F("onCameraDemandChange", e.onCameraDemandChange, !0, !1);
1559
+ return;
1560
+ }
1561
+ if (!p()) {
1562
+ try {
1563
+ await c.replaceTrack(null);
1564
+ } catch (v) {
1565
+ y("replaceTrack(null) for stale camera attach failed:", v);
1566
+ }
1567
+ J(b);
1568
+ return;
1569
+ }
1570
+ try {
1571
+ const v = c.getParameters();
1572
+ (!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);
1573
+ } catch (v) {
1574
+ y("setParameters on outbound camera failed:", v);
1575
+ }
1576
+ if (!p()) {
1577
+ try {
1578
+ await c.replaceTrack(null);
1579
+ } catch (v) {
1580
+ y("replaceTrack(null) for stale camera finalize failed:", v);
1581
+ }
1582
+ J(b);
1583
+ return;
1584
+ }
1585
+ Q = b, fe = r, G.onended = () => {
1586
+ Q === b && Qe.enqueueCurrent(async ({ isCurrent: v }) => {
1587
+ if (!(!v() || Q !== b || !d() || g !== f || ue !== c)) {
1588
+ try {
1589
+ await c.replaceTrack(null);
1590
+ } catch (U) {
1591
+ y("replaceTrack(null) after camera ended failed:", U);
1592
+ }
1593
+ !v() || Q !== b || !d() || g !== f || ue !== c || (Q = null, fe = void 0, J(b), He(), f.send(JSON.stringify({ type: "cameraResult", granted: !1 })), F("onCameraDemandChange", e.onCameraDemandChange, !0, !1));
1594
+ }
1595
+ }).catch((v) => y("camera ended cleanup failed:", v));
1596
+ }, p() && (ht(f, G), mt());
1597
+ }), _e = () => {
1598
+ for (const r of se) r();
1599
+ se.clear();
1600
+ for (const r of Y.values()) clearTimeout(r);
1601
+ Y.clear();
1602
+ for (const r of Z.values())
1603
+ r(new Error("Simulator disconnected"));
1604
+ for (const r of ie.values())
1605
+ r(new Error("Simulator disconnected"));
1606
+ Z.clear(), re.clear(), ie.clear(), ce.clear(), L?.(), L = void 0, bt(), H = null;
1607
+ for (const r of Oe.values())
1608
+ clearTimeout(r.timer), r.reject(new Error("Simulator disconnected"));
1609
+ Oe.clear(), w(null), m({ controlReady: !1, videoReady: !1 }), Ve(), Ie(), Ye(), $ && ($.stop(), $ = null), Ne !== null && We(null), Qe.invalidate(), He(), Ut(), fe = void 0, ue = null, ++xe, Ze = !1, pe = null, te && (J(te), te = null, F("onMicrophoneStateChange", e.onMicrophoneStateChange, {
1610
+ active: !1
1611
+ })), ve = null, g && (g.onopen = null, g.onmessage = null, g.onerror = null, g.onclose = null, g.close(), g = null), Pe?.close(), Pe = null, I && (I.onconnectionstatechange = null, I.oniceconnectionstatechange = null, I.ontrack = null, I.onicecandidate = null, I.close(), I = null), x && (x.onopen = null, x.onclose = null, x.onerror = null, x.close(), x = null);
1612
+ }, pt = () => {
1613
+ document.hidden ? be() : ut();
1614
+ }, Bt = async () => {
1615
+ if (e.transport) return e.transport.isTerminated?.() ?? !1;
1616
+ if (typeof navigator < "u" && navigator.onLine === !1)
1617
+ return !1;
1618
+ let r;
1619
+ try {
1620
+ const d = new URL(n);
1621
+ d.protocol = d.protocol === "wss:" ? "https:" : d.protocol === "ws:" ? "http:" : d.protocol, r = Mt(d.toString(), u);
1622
+ } catch {
1623
+ return !1;
1624
+ }
1625
+ const f = new AbortController(), c = window.setTimeout(() => f.abort(), Un);
1626
+ try {
1627
+ return (await fetch(r, { method: "GET", cache: "no-store", signal: f.signal })).status === 404;
1628
+ } catch {
1629
+ return !1;
1630
+ } finally {
1631
+ window.clearTimeout(c);
1632
+ }
1633
+ }, xt = () => {
1634
+ Ee || (Ee = !0, de += 1, qe(), Ve(), Ie(), _e(), D("Instance terminated"), be(), De("terminated"), F("onTerminated", e.onTerminated));
1635
+ }, Wt = () => {
1636
+ if (Ee || Se) return;
1637
+ Se = !0;
1638
+ const r = ke;
1639
+ Bt().catch(() => !1).then((f) => {
1640
+ r === ke && (Se = !1, f && xt());
1641
+ });
1642
+ }, ge = (r, f) => {
1643
+ if (Ee || f !== de)
1644
+ return;
1645
+ if (Wt(), ne) {
1646
+ if (e.autoReconnect === !1) {
1647
+ D(`Connection failed after it was established: ${r}`), be(), De("failed"), _e();
1648
+ return;
1649
+ }
1650
+ D(`Reconnecting after established session dropped: ${r}`), ne = !1, Fe = -1;
1651
+ }
1652
+ qe();
1653
+ const c = Fe + 1;
1654
+ if (c >= st) {
1655
+ D(`Connection failed after ${st} attempts: ${r}`), be(), De("failed"), _e();
1656
+ return;
1657
+ }
1658
+ D(`Retrying connection (${c + 1}/${st})`), De("reconnecting"), _e(), Ke = window.setTimeout(() => {
1659
+ Ke = void 0, f === de && Ct(c);
1660
+ }, Yn);
1661
+ }, Ct = async (r = 0) => {
1662
+ const { openUrl: f, axPollIntervalMs: c, axMaxBackoffMs: d, androidElementTreeOptions: K } = e;
1663
+ if (Ee) return;
1664
+ const p = de + 1;
1665
+ de = p, Fe = r, ne = !1, r === 0 && Ce !== "reconnecting" && De("connecting"), qe(), Ve(), Ye(), we = !1, S(!1), _e();
1666
+ const C = () => p === de;
1667
+ Ae = window.setTimeout(() => {
1668
+ Ae = void 0, !(!C() || ne) && ge("Connection did not succeed within 15 seconds", p);
1669
+ }, In);
1670
+ try {
1671
+ const h = e.transport ? await e.transport.connect() : new WebSocket(Mt(n, u));
1672
+ if (!C()) {
1673
+ h.close();
1674
+ return;
1675
+ }
1676
+ if (g = h, await new Promise((_, s) => {
1677
+ let k = !1;
1678
+ const W = () => M(() => s(new Error("Connection stopped")));
1679
+ se.add(W);
1680
+ const T = window.setTimeout(
1681
+ () => M(() => s(new Error("WebSocket connection timeout"))),
1682
+ 3e4
1683
+ ), M = (z) => {
1684
+ k || (k = !0, se.delete(W), window.clearTimeout(T), z());
1685
+ };
1686
+ h.onopen = () => {
1687
+ !C() || g !== h || M(_);
1688
+ }, h.onerror = (z) => {
1689
+ !C() || g !== h || (D("WebSocket error: " + z), M(() => s(new Error("WebSocket connection failed"))));
1690
+ }, h.onclose = () => {
1691
+ !C() || g !== h || (D("WebSocket closed"), M(() => s(new Error("WebSocket closed before connection was established"))));
1692
+ }, h.readyState === WebSocket.OPEN ? M(_) : h.readyState !== WebSocket.CONNECTING && M(() => s(new Error("WebSocket is closed")));
1693
+ }), !C() || g !== h)
1694
+ return;
1695
+ h.onerror = (_) => {
1696
+ !C() || g !== h || D("WebSocket error: " + _);
1697
+ }, h.onclose = () => {
1698
+ !C() || g !== h || D("WebSocket closed");
1699
+ };
1700
+ const R = new Promise((_, s) => {
1701
+ let k = !1;
1702
+ const W = () => T(() => s(new Error("Connection stopped")));
1703
+ se.add(W);
1704
+ const T = (j) => {
1705
+ k || (k = !0, se.delete(W), window.clearTimeout(M), h.removeEventListener("message", z), j());
1706
+ }, M = window.setTimeout(
1707
+ () => T(() => s(new Error("RTCConfiguration timeout"))),
1708
+ 3e4
1709
+ ), z = (j) => {
1710
+ if (!(!C() || g !== h))
1711
+ try {
1712
+ const X = JSON.parse(j.data);
1713
+ if (X.type === "signalingError" && X.requestType === "requestRtcConfiguration" && X.sessionId === i) {
1714
+ const $t = typeof X.error == "string" ? X.error : "Unable to load streaming configuration";
1715
+ T(() => s(new Error($t)));
1716
+ } else X.type === "rtcConfiguration" && T(
1717
+ () => _({
1718
+ rtcConfiguration: X.rtcConfiguration,
1719
+ cameraSupported: X.cameraSupported === !0,
1720
+ foldSupported: X.foldSupported === !0
1721
+ })
1722
+ );
1723
+ } catch (X) {
1724
+ console.error("Error handling RTC configuration:", X), T(() => s(X));
1725
+ }
1726
+ };
1727
+ h.addEventListener("message", z), h.send(
1728
+ JSON.stringify({
1729
+ type: "requestRtcConfiguration",
1730
+ sessionId: i
1731
+ })
1732
+ );
1733
+ }), {
1734
+ rtcConfiguration: b,
1735
+ cameraSupported: G,
1736
+ foldSupported: v
1737
+ } = await R;
1738
+ if (!C() || g !== h)
1739
+ return;
1740
+ const U = a === "iphone-duo" || v;
1741
+ q(U);
1742
+ const A = new RTCPeerConnection({ ...b, iceTransportPolicy: "relay" });
1743
+ I = A;
1744
+ const Je = { peer: A, displays: /* @__PURE__ */ new Map() };
1745
+ H = Je, P(), A.addTransceiver("audio", { direction: "recvonly" });
1746
+ const qt = A.addTransceiver("video", { direction: "recvonly" }), Vt = U ? A.addTransceiver("video", { direction: "recvonly" }) : null, gt = !l && (E === "ios" || G), nt = gt ? A.addTransceiver("video", {
1747
+ direction: "sendonly"
1748
+ }) : null;
1749
+ if (ue = nt?.sender ?? null, ve = (gt ? A.addTransceiver("audio", {
1750
+ direction: "sendonly"
1751
+ }) : null)?.sender ?? null, RTCRtpReceiver.getCapabilities) {
1752
+ const _ = RTCRtpReceiver.getCapabilities("video");
1753
+ if (_ && _.codecs) {
1754
+ const k = _.codecs.sort((W, T) => {
1755
+ const M = (z) => {
1756
+ const j = z.mimeType.toLowerCase();
1757
+ return j.includes("h265") || j.includes("hevc") ? 1 : j.includes("h264") || j.includes("avc") ? 2 : 3;
1758
+ };
1759
+ return M(W) - M(T);
1760
+ });
1761
+ qt.setCodecPreferences(k), Vt?.setCodecPreferences(k), le("Set codec preferences:", k.map((W) => W.mimeType).join(", "));
1762
+ }
1763
+ }
1764
+ if (nt && RTCRtpSender.getCapabilities) {
1765
+ const _ = RTCRtpSender.getCapabilities("video");
1766
+ if (_ && _.codecs) {
1767
+ const s = /* @__PURE__ */ new Set(["42e01f", "42e028", "640c1f"]), k = (T) => {
1768
+ const M = T.mimeType.toLowerCase(), j = (T.sdpFmtpLine || "").toLowerCase().match(/profile-level-id=([0-9a-f]{6})/), X = j ? j[1] : "";
1769
+ 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;
1770
+ }, W = [..._.codecs].sort((T, M) => k(T) - k(M));
1771
+ try {
1772
+ nt.setCodecPreferences(W), le(
1773
+ "Outbound camera codec preferences:",
1774
+ W.map((T) => `${T.mimeType}${T.sdpFmtpLine ? `[${T.sdpFmtpLine}]` : ""}`).join(", ")
1775
+ );
1776
+ } catch (T) {
1777
+ y("Failed to set outbound camera codec preferences:", T);
1778
+ }
1779
+ }
1780
+ }
1781
+ const ae = A.createDataChannel("control", {
1782
+ ordered: !0,
1783
+ negotiated: !0,
1784
+ id: 1
1785
+ });
1786
+ x = ae;
1787
+ const rt = !l && !U && e.onTrace ? Sn(A, (_) => {
1788
+ C() && I === A && F("onTrace", e.onTrace, _);
1789
+ }) : null;
1790
+ if (Pe = rt, ae.onopen = () => {
1791
+ if (!C() || x !== ae || g !== h)
1792
+ return;
1793
+ ne = !0, m({ controlReady: !l }), Ve(), D("Control channel opened"), U && h.send(JSON.stringify({ type: "getFoldState", id: "duo-capabilities" })), !$ && E !== "macos" && ($ = new Dn({
1794
+ platform: E,
1795
+ baseIntervalMs: c,
1796
+ maxBackoffMs: d,
1797
+ androidElementTreeOptions: K,
1798
+ send: (s) => {
1799
+ if (!g || g.readyState !== WebSocket.OPEN) return !1;
1800
+ try {
1801
+ return g.send(JSON.stringify(s)), !0;
1802
+ } catch {
1803
+ return !1;
1804
+ }
1805
+ },
1806
+ onSnapshot: We,
1807
+ onStatusChange: (s, k) => {
1808
+ F("onAxStatusChange", e.onAxStatusChange, s, k);
1809
+ }
1810
+ }), (e.inspectMode === !0 || e.inspectMode === "hover-only") && $.start());
1811
+ const _ = () => {
1812
+ !C() || we || x !== ae || g !== h || h.readyState !== WebSocket.OPEN || h.send(JSON.stringify({ type: "requestFrame", sessionId: i }));
1813
+ };
1814
+ if (_(), Ye(), Le = window.setInterval(() => {
1815
+ if (!C() || we || x !== ae || g !== h || h.readyState !== WebSocket.OPEN) {
1816
+ Ye();
1817
+ return;
1818
+ }
1819
+ _();
1820
+ }, 250), !l && f) {
1821
+ try {
1822
+ const s = decodeURIComponent(f);
1823
+ D("Opening URL"), h.send(
1824
+ JSON.stringify({
1825
+ type: "openUrl",
1826
+ url: s,
1827
+ sessionId: i
1828
+ })
1829
+ );
1830
+ } catch (s) {
1831
+ console.error({ error: s }, "Error decoding URL, falling back to the original URL"), h.send(
1832
+ JSON.stringify({
1833
+ type: "openUrl",
1834
+ url: f,
1835
+ sessionId: i
1836
+ })
1837
+ );
1838
+ }
1839
+ $?.bumpActivity();
1840
+ }
1841
+ }, ae.onclose = () => {
1842
+ !C() || x !== ae || (m({ controlReady: !1 }), D("Control channel closed"));
1843
+ }, ae.onerror = (_) => {
1844
+ !C() || x !== ae || (console.error("Control channel error:", _), D("Control channel error: " + _));
1845
+ }, A.onconnectionstatechange = () => {
1846
+ !C() || I !== A || (D("Connection state: " + A.connectionState), A.connectionState === "failed" && ne && ge("WebRTC connection entered failed state", p));
1847
+ }, A.oniceconnectionstatechange = () => {
1848
+ if (!C() || I !== A)
1849
+ return;
1850
+ const _ = A.iceConnectionState;
1851
+ if (D("ICE state: " + _), _ === "connected" || _ === "completed") {
1852
+ Ie(), et() && !te && tt();
1853
+ return;
1854
+ }
1855
+ if (_ === "failed") {
1856
+ Ie(), ne && ge("ICE connection entered failed state", p);
1857
+ return;
1858
+ }
1859
+ _ === "disconnected" && ne && e.autoReconnect !== !1 && me === void 0 && (me = window.setTimeout(() => {
1860
+ me = void 0, !(!C() || I !== A) && A.iceConnectionState === "disconnected" && ge("ICE stayed disconnected past grace period", p);
1861
+ }, Rn));
1862
+ }, A.ontrack = (_) => {
1863
+ if (!C() || I !== A)
1864
+ return;
1865
+ Kt(_.receiver, e.jitterBufferTargetMs);
1866
+ const s = _.track.id === "duo-inner" || _.streams.some((k) => k.id === "duo-inner");
1867
+ if (_.track.kind === "video" && Je.displays.set(_.receiver, s ? "inner" : "primary"), D("Received remote track: " + _.track.kind), _.track.kind === "video") {
1868
+ const k = s ? "inner" : "primary", W = U ? new MediaStream([_.track]) : _.streams[0] ?? new MediaStream([_.track]);
1869
+ Ue.set(k, W);
1870
+ for (const [T, M] of B)
1871
+ M.display === k && ct(T, M, W);
1872
+ }
1873
+ }, A.onicecandidate = (_) => {
1874
+ if (!(!C() || I !== A || g !== h))
1875
+ if (_.candidate && h.readyState === WebSocket.OPEN) {
1876
+ const s = {
1877
+ type: "candidate",
1878
+ candidate: _.candidate.candidate,
1879
+ sdpMid: _.candidate.sdpMid,
1880
+ sdpMLineIndex: _.candidate.sdpMLineIndex,
1881
+ sessionId: i
1882
+ };
1883
+ h.send(JSON.stringify(s)), D("Sent ICE candidate");
1884
+ } else
1885
+ D("ICE candidate gathering completed");
1886
+ }, h.onmessage = async (_) => {
1887
+ if (!C() || g !== h)
1888
+ return;
1889
+ let s;
1890
+ try {
1891
+ s = JSON.parse(_.data);
1892
+ } catch (k) {
1893
+ y("Error parsing message:", k);
1894
+ return;
1895
+ }
1896
+ if (!$?.handleMessage(s))
1897
+ switch (D("Received: " + s.type), s.type) {
1898
+ case "performActionsResult":
1899
+ case "foldStateResult":
1900
+ case "foldStateChanged": {
1901
+ if (!U) break;
1902
+ s.state ? (w(s.state), N(void 0)) : s.id === "duo-capabilities" && N(s.error || "This instance does not support native iPhone Duo displays.");
1903
+ const T = Oe.get(s.id);
1904
+ T && (clearTimeout(T.timer), Oe.delete(s.id), s.error ? T.reject(new Error(s.error)) : T.resolve());
1905
+ break;
1906
+ }
1907
+ case "signalingError": {
1908
+ if (s.requestType !== "offer" || s.sessionId !== i)
1909
+ break;
1910
+ const T = typeof s.error == "string" ? s.error : "Unable to establish the streaming connection";
1911
+ D("Error: " + T), ge(T, p);
1912
+ break;
1913
+ }
1914
+ case "answer":
1915
+ if (!I || I !== A) {
1916
+ D("No peer connection, skipping answer");
1917
+ break;
1918
+ }
1919
+ if (rt?.accept(s.latencyTraceVersion), await A.setRemoteDescription(
1920
+ new RTCSessionDescription({
1921
+ type: "answer",
1922
+ sdp: s.sdp
1923
+ })
1924
+ ), !C() || I !== A)
1925
+ return;
1926
+ D("Set remote description");
1927
+ break;
1928
+ case "candidate":
1929
+ if (!I || I !== A) {
1930
+ D("No peer connection, skipping candidate");
1931
+ break;
1932
+ }
1933
+ if (await A.addIceCandidate(
1934
+ new RTCIceCandidate({
1935
+ candidate: s.candidate,
1936
+ sdpMid: s.sdpMid,
1937
+ sdpMLineIndex: s.sdpMLineIndex
1938
+ })
1939
+ ), !C() || I !== A)
1940
+ return;
1941
+ D("Added ICE candidate");
1942
+ break;
1943
+ case "screenshot":
1944
+ case "screenshotResult": {
1945
+ if (typeof s.id != "string") {
1946
+ y("Received invalid screenshot success message:", s);
1947
+ break;
1948
+ }
1949
+ const T = kn(s);
1950
+ if (T) {
1951
+ const j = Z.get(s.id);
1952
+ if (typeof j != "function") {
1953
+ y(`Received screenshot error for unknown or handled id: ${s.id}`);
1954
+ break;
1955
+ }
1956
+ y(`Received screenshot error for id ${s.id}: ${T}`), j(new Error(T)), re.delete(s.id), Z.delete(s.id), clearTimeout(Y.get(s.id)), Y.delete(s.id);
1957
+ break;
1958
+ }
1959
+ const M = Pn(s);
1960
+ if (!M) {
1961
+ y("Received screenshot message without image data:", s);
1962
+ break;
1963
+ }
1964
+ const z = re.get(s.id);
1965
+ if (typeof z != "function") {
1966
+ y(`Received screenshot data for unknown or handled id: ${s.id}`);
1967
+ break;
1968
+ }
1969
+ le(`Received screenshot data for id ${s.id}`), z(M), re.delete(s.id), Z.delete(s.id), clearTimeout(Y.get(s.id)), Y.delete(s.id);
1970
+ break;
1971
+ }
1972
+ case "screenshotError":
1973
+ if (typeof s.id != "string" || typeof s.message != "string") {
1974
+ y("Received invalid screenshot error message:", s);
1975
+ break;
1976
+ }
1977
+ const k = Z.get(s.id);
1978
+ if (typeof k != "function") {
1979
+ y(`Received screenshot error for unknown or handled id: ${s.id}`);
1980
+ break;
1981
+ }
1982
+ y(`Received screenshot error for id ${s.id}: ${s.message}`), k(new Error(s.message)), re.delete(s.id), Z.delete(s.id), clearTimeout(Y.get(s.id)), Y.delete(s.id);
1983
+ break;
1984
+ case "cameraRequest": {
1985
+ const T = ue;
1986
+ if (!T)
1987
+ break;
1988
+ const M = An(s);
1989
+ if (!M) {
1990
+ y("Received invalid cameraRequest:", s);
1991
+ break;
1992
+ }
1993
+ console.info("[RemoteControl] cameraRequest received:", M.active, M.facingMode), await Ft(M, h, T, C);
1994
+ break;
1995
+ }
1996
+ case "microphoneRequest": {
1997
+ if (!ve)
1998
+ break;
1999
+ const T = s.active === !0;
2000
+ if (Ze = T, console.info("[RemoteControl] microphoneRequest received, active=", T), !T) {
2001
+ ze || await $e();
2002
+ break;
2003
+ }
2004
+ if (te) {
2005
+ Et(h);
2006
+ break;
2007
+ }
2008
+ await tt();
2009
+ break;
2010
+ }
2011
+ case "microphoneStartResult": {
2012
+ if (pe === null || s.id !== pe)
2013
+ break;
2014
+ pe = null, typeof s.error == "string" && (console.warn("[RemoteControl] microphoneStart rejected by host:", s.error), $e(s.error));
2015
+ break;
2016
+ }
2017
+ case "terminateAppResult":
2018
+ if (typeof s.id != "string") {
2019
+ y("Received invalid terminateApp result message:", s);
2020
+ break;
2021
+ }
2022
+ if (typeof s.error == "string") {
2023
+ const T = ie.get(s.id);
2024
+ if (typeof T != "function") {
2025
+ y(`Received terminateApp error for unknown or handled id: ${s.id}`);
2026
+ break;
2027
+ }
2028
+ y(`Received terminateApp error for id ${s.id}: ${s.error}`), T(new Error(s.error)), ce.delete(s.id), ie.delete(s.id), clearTimeout(Y.get(s.id)), Y.delete(s.id);
2029
+ break;
2030
+ }
2031
+ const W = ce.get(s.id);
2032
+ if (typeof W != "function") {
2033
+ y(`Received terminateApp result for unknown or handled id: ${s.id}`);
2034
+ break;
2035
+ }
2036
+ le(`Received terminateApp success for id ${s.id}`), W(), ce.delete(s.id), ie.delete(s.id), clearTimeout(Y.get(s.id)), Y.delete(s.id);
2037
+ break;
2038
+ default:
2039
+ y(`Received unhandled message type: ${s.type}`, s);
2040
+ break;
2041
+ }
2042
+ }, I === A) {
2043
+ const _ = await A.createOffer({
2044
+ offerToReceiveVideo: !0,
2045
+ offerToReceiveAudio: !1
2046
+ });
2047
+ if (!C() || I !== A || (await A.setLocalDescription(_), !C() || I !== A))
2048
+ return;
2049
+ C() && g === h && h.readyState === WebSocket.OPEN && h.send(
2050
+ JSON.stringify({
2051
+ type: "offer",
2052
+ ...U ? { displayStreams: !0 } : {},
2053
+ ...rt ? { latencyTraceVersion: 1 } : {},
2054
+ sdp: _.sdp,
2055
+ sessionId: i
2056
+ })
2057
+ ), D("Sent offer");
2058
+ }
2059
+ } catch (h) {
2060
+ if (!C() || h instanceof Error && h.message === "Connection stopped")
2061
+ return;
2062
+ const R = h instanceof Error ? h.message : String(h);
2063
+ D("Error: " + R), ge(R, p);
2064
+ }
2065
+ }, Ot = () => {
2066
+ if (ye) throw new Error("Device stream is disposed");
2067
+ ke++, Se = !1, We(null), Ce !== "reconnecting" && (Ce = null), document.addEventListener("visibilitychange", pt), document.hidden || ut(), Ee = !1, Ct(0);
2068
+ }, Dt = () => {
2069
+ ke++, Se = !1, be(), document.removeEventListener("visibilitychange", pt), de += 1, Fe = 0, ne = !1, qe(), Ie(), _e(), Ce = null, m({ connection: "idle", videoReady: !1, controlReady: !1 }), D("Stopped");
2070
+ }, _t = (r, f = "primary") => {
2071
+ if (ye) throw new Error("Device stream is disposed");
2072
+ if (B.has(r)) throw new Error("Video element is already attached");
2073
+ const c = { display: f };
2074
+ B.set(r, c);
2075
+ const d = () => {
2076
+ f === "primary" && Ue.has(f) && Rt();
2077
+ };
2078
+ r.addEventListener("loadeddata", d);
2079
+ const K = Ue.get(f);
2080
+ K && ct(r, c, K);
2081
+ let p = !1;
2082
+ const C = () => {
2083
+ p || (p = !0, V.delete(C), r.removeEventListener("loadeddata", d), c.stop?.(), B.delete(r), r.srcObject = null);
2084
+ };
2085
+ return V.add(C), C;
2086
+ };
2087
+ return {
2088
+ start: Ot,
2089
+ stop: Dt,
2090
+ attachVideo: _t,
2091
+ attachFrameSink: (r, f = "primary") => {
2092
+ const c = document.createElement("video");
2093
+ c.muted = !0, c.playsInline = !0, c.autoplay = !0;
2094
+ const d = _t(c, f);
2095
+ let K = !1, p = 0, C = 0;
2096
+ const h = () => {
2097
+ c.cancelVideoFrameCallback?.(p), cancelAnimationFrame(C);
2098
+ }, R = () => {
2099
+ K || !c.srcObject || (c.readyState >= 2 && c.videoWidth > 0 && F(
2100
+ "present",
2101
+ (...v) => r.present(...v),
2102
+ c,
2103
+ c.videoWidth,
2104
+ c.videoHeight,
2105
+ f
2106
+ ), !(K || !c.srcObject) && (c.requestVideoFrameCallback ? p = c.requestVideoFrameCallback(R) : C = requestAnimationFrame(R)));
2107
+ }, b = () => {
2108
+ h(), R();
2109
+ };
2110
+ B.get(c).clear = h, c.addEventListener("loadeddata", b);
2111
+ const G = () => {
2112
+ K || (K = !0, V.delete(G), h(), c.removeEventListener("loadeddata", b), d(), c.remove());
2113
+ };
2114
+ return V.delete(d), V.add(G), c.readyState >= 2 && b(), G;
2115
+ },
2116
+ dispose: () => {
2117
+ if (!ye) {
2118
+ ye = !0, Dt();
2119
+ for (const r of V) r();
2120
+ V.clear();
2121
+ }
2122
+ },
2123
+ getState: () => O,
2124
+ /** A new token applies to the next connection attempt and termination probe. */
2125
+ updateOptions: ({
2126
+ token: r,
2127
+ ...f
2128
+ }) => {
2129
+ if (ye) throw new Error("Device stream is disposed");
2130
+ r !== void 0 && !e.transport && (u = r);
2131
+ const c = e;
2132
+ if (e = { ...e, ...f }, c.jitterBufferTargetMs !== e.jitterBufferTargetMs)
2133
+ for (const d of I?.getTransceivers() ?? [])
2134
+ (d.currentDirection === "recvonly" || d.currentDirection === "sendrecv") && Kt(d.receiver, e.jitterBufferTargetMs);
2135
+ !!c.onPlaybackStats != !!e.onPlaybackStats && P(), !!c.microphoneEnabled != !!e.microphoneEnabled && (ze = !l && (e.microphoneEnabled ?? !1), et() ? tt() : $e()), !!c.inspectMode != !!e.inspectMode && (e.inspectMode ? $?.start() : ($?.stop(), Ne !== null && We(null)));
2136
+ },
2137
+ sendControl: oe,
2138
+ sendTouch: (r, f, c, d, K, p = 0) => oe(
2139
+ Gt(
2140
+ r === "begin" ? 0 : r === "end" ? 1 : 2,
2141
+ p,
2142
+ d,
2143
+ K,
2144
+ f,
2145
+ c,
2146
+ r === "end" ? 0 : 1
2147
+ )
2148
+ ),
2149
+ sendText: (r) => oe(jt(r)),
2150
+ sendDisplayTouch: (r, f, c, d) => oe(en(r, f, c, d)),
2151
+ sendDuoControl: Yt,
2152
+ pressButton: (r) => {
2153
+ const f = { home: 3, back: 4, recents: 187, power: 26 }[r];
2154
+ oe(it(0, f, 0, 0)), oe(it(1, f, 0, 0));
2155
+ },
2156
+ rotate: () => oe(new Uint8Array([11]).buffer),
2157
+ bumpActivity: () => $?.bumpActivity(),
2158
+ getAxStatus: () => $?.getStatus() ?? "idle",
2159
+ openUrl: (r) => {
2160
+ if (!l) {
2161
+ if (!g || g.readyState !== WebSocket.OPEN) {
2162
+ y("WebSocket not open, cannot send open_url command.");
2163
+ return;
2164
+ }
2165
+ try {
2166
+ const f = decodeURIComponent(r);
2167
+ D("Opening URL"), g.send(
2168
+ JSON.stringify({
2169
+ type: "openUrl",
2170
+ url: f,
2171
+ sessionId: i
2172
+ })
2173
+ );
2174
+ } catch (f) {
2175
+ y("Error decoding or sending URL :", { error: f, url: r }), g.send(
2176
+ JSON.stringify({
2177
+ type: "openUrl",
2178
+ url: r,
2179
+ sessionId: i
2180
+ })
2181
+ );
2182
+ }
2183
+ $?.bumpActivity();
2184
+ }
2185
+ },
2186
+ sendKeyEvent: (r) => {
2187
+ if (!x || x.readyState !== "open") {
2188
+ y("Data channel not ready for imperative key command:", x?.readyState);
2189
+ return;
2190
+ }
2191
+ if (E === "macos") {
2192
+ const p = Tt(r.code);
2193
+ if (p === void 0) {
2194
+ y(`Unknown event.code for imperative command: ${r.code}`);
2195
+ return;
2196
+ }
2197
+ const C = [
2198
+ [r.metaKey, "Meta"],
2199
+ [r.ctrlKey, "Control"],
2200
+ [r.altKey, "Alt"],
2201
+ [r.shiftKey, "Shift"]
2202
+ ].filter(([R, b]) => R && !r.code.startsWith(b)).map(([, R]) => Tt(`${R}Left`)), h = (R, b) => oe(Xt(R, b));
2203
+ if (r.type === "keydown") {
2204
+ for (const R of C) h(Ge.DOWN, R);
2205
+ h(Ge.DOWN, p);
2206
+ } else {
2207
+ h(Ge.UP, p);
2208
+ for (const R of [...C].reverse()) h(Ge.UP, R);
2209
+ }
2210
+ return;
2211
+ }
2212
+ const f = Ht[r.code];
2213
+ if (!f) {
2214
+ y(`Unknown event.code for imperative command: ${r.code}`);
2215
+ return;
2216
+ }
2217
+ let c = o.META_NONE;
2218
+ r.shiftKey && (c |= o.META_SHIFT_ON), r.altKey && (c |= o.META_ALT_ON), r.ctrlKey && (c |= o.META_CTRL_ON), r.metaKey && (c |= o.META_META_ON);
2219
+ const d = r.type === "keydown" ? o.ACTION_DOWN : o.ACTION_UP;
2220
+ le(
2221
+ `Sending Imperative Key Command: code=${r.code}, keycode=${f}, action=${d}, meta=${c}`
2222
+ );
2223
+ const K = it(
2224
+ d,
2225
+ f,
2226
+ 0,
2227
+ // repeat count, typically 0 for single presses
2228
+ c
2229
+ );
2230
+ K && oe(K);
2231
+ },
2232
+ screenshot: (r) => new Promise((f, c) => {
2233
+ if (!g || g.readyState !== WebSocket.OPEN)
2234
+ return y("WebSocket not open, cannot send screenshot command."), c(new Error("WebSocket is not connected or connection is not open."));
2235
+ const d = `ui-ss-${Date.now()}-${Math.random().toString(36).substring(2, 9)}`, K = {
2236
+ type: r ? "screenshotDisplay" : "screenshot",
2237
+ ...r ? { display: r } : {},
2238
+ id: d
2239
+ };
2240
+ re.set(d, f), Z.set(d, c), le("Sending screenshot request:", K);
2241
+ try {
2242
+ g.send(JSON.stringify(K));
2243
+ } catch (p) {
2244
+ y("Failed to send screenshot request immediately:", p), re.delete(d), Z.delete(d), c(p);
2245
+ return;
2246
+ }
2247
+ Y.set(
2248
+ d,
2249
+ setTimeout(() => {
2250
+ Y.delete(d), re.has(d) && (y(`Screenshot request timed out for id ${d}`), Z.get(d)?.(new Error("Screenshot request timed out")), re.delete(d), Z.delete(d));
2251
+ }, 3e4)
2252
+ );
2253
+ }),
2254
+ terminateApp: (r) => l ? Promise.reject(new Error("Device is watch-only")) : new Promise((f, c) => {
2255
+ if (!g || g.readyState !== WebSocket.OPEN)
2256
+ return y("WebSocket not open, cannot send terminateApp command."), c(new Error("WebSocket is not connected or connection is not open."));
2257
+ const d = `ui-term-${Date.now()}-${Math.random().toString(36).substring(2, 9)}`, K = {
2258
+ type: "terminateApp",
2259
+ id: d,
2260
+ bundleId: r
2261
+ };
2262
+ ce.set(d, f), ie.set(d, c), le("Sending terminateApp request:", K);
2263
+ try {
2264
+ g.send(JSON.stringify(K));
2265
+ } catch (p) {
2266
+ y("Failed to send terminateApp request immediately:", p), ce.delete(d), ie.delete(d), c(p);
2267
+ return;
2268
+ }
2269
+ $?.bumpActivity(), Y.set(
2270
+ d,
2271
+ setTimeout(() => {
2272
+ Y.delete(d), ce.has(d) && (y(`terminateApp request timed out for id ${d}`), ie.get(d)?.(new Error("terminateApp request timed out")), ce.delete(d), ie.delete(d));
2273
+ }, 3e4)
2274
+ );
2275
+ }),
2276
+ reconnect: () => Ot(),
2277
+ refreshAxTree: async () => {
2278
+ const r = $;
2279
+ if (!r)
2280
+ throw new Error("Inspect mode is not active");
2281
+ return r.refresh();
2282
+ },
2283
+ getAxSnapshot: () => Ne
2284
+ };
2285
+ }
2286
+ const kn = (t) => typeof t.message == "string" ? t.message : typeof t.error == "string" ? t.error : null, Pn = (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;
2287
+ export {
2288
+ ot as A,
2289
+ qn as B,
2290
+ Qt as C,
2291
+ $n as D,
2292
+ Xn as E,
2293
+ jn as F,
2294
+ Jn as G,
2295
+ Gn as H,
2296
+ Hn as I,
2297
+ ee as J,
2298
+ en as K,
2299
+ zt as L,
2300
+ Ge as M,
2301
+ zn as a,
2302
+ Zn as b,
2303
+ er as c,
2304
+ dn as d,
2305
+ un as e,
2306
+ Qn as f,
2307
+ an as g,
2308
+ fn as h,
2309
+ bn as i,
2310
+ Xt as j,
2311
+ tr as k,
2312
+ Wn as l,
2313
+ xn as m,
2314
+ ln as n,
2315
+ le as o,
2316
+ y as p,
2317
+ Tt as q,
2318
+ jt as r,
2319
+ F as s,
2320
+ it as t,
2321
+ o as u,
2322
+ Gt as v,
2323
+ Ht as w,
2324
+ je as x,
2325
+ Bn as y,
2326
+ Vn as z
2327
+ };