@limrun/ui 0.20.4 → 0.20.6
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/{GLTFLoader-HYStnvvW.js → GLTFLoader-CDlCzcwQ.js} +1 -1
- package/dist/{GLTFLoader-BoPozIl8.mjs → GLTFLoader-k2LXj_Q8.mjs} +1 -1
- package/dist/core/device-stream.d.ts +4 -1
- package/dist/core-Bdivxz74.js +2 -0
- package/dist/{core-DuukW7sF.mjs → core-BpV73M0K.mjs} +328 -321
- package/dist/core.cjs +1 -1
- package/dist/core.js +1 -1
- package/dist/{duo-frame-xMRcGXf4.mjs → duo-frame-Sz0TWot-.mjs} +3 -3
- package/dist/{duo-frame-n5_DJUKk.js → duo-frame-gXvPDImv.js} +2 -2
- package/dist/{duo-view-Cy8dvjCI.js → duo-view-BMPB0h3C.js} +1 -1
- package/dist/{duo-view-CvOd3jDJ.mjs → duo-view-DWqQXwdZ.mjs} +2 -2
- 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/remote-control-CTn0dIkj.js +1 -0
- package/dist/remote-control-VZ7b8hFe.mjs +1175 -0
- package/package.json +1 -1
- package/dist/core-OsPKiOsB.js +0 -2
- package/dist/remote-control-CRqEQ8NT.mjs +0 -1159
- package/dist/remote-control-CiWHN9Do.js +0 -1
package/package.json
CHANGED
package/dist/core-OsPKiOsB.js
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
"use strict";const Ue={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},Re={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},i={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},Kt={KeyA:i.KEYCODE_A,KeyB:i.KEYCODE_B,KeyC:i.KEYCODE_C,KeyD:i.KEYCODE_D,KeyE:i.KEYCODE_E,KeyF:i.KEYCODE_F,KeyG:i.KEYCODE_G,KeyH:i.KEYCODE_H,KeyI:i.KEYCODE_I,KeyJ:i.KEYCODE_J,KeyK:i.KEYCODE_K,KeyL:i.KEYCODE_L,KeyM:i.KEYCODE_M,KeyN:i.KEYCODE_N,KeyO:i.KEYCODE_O,KeyP:i.KEYCODE_P,KeyQ:i.KEYCODE_Q,KeyR:i.KEYCODE_R,KeyS:i.KEYCODE_S,KeyT:i.KEYCODE_T,KeyU:i.KEYCODE_U,KeyV:i.KEYCODE_V,KeyW:i.KEYCODE_W,KeyX:i.KEYCODE_X,KeyY:i.KEYCODE_Y,KeyZ:i.KEYCODE_Z,Digit0:i.KEYCODE_0,Digit1:i.KEYCODE_1,Digit2:i.KEYCODE_2,Digit3:i.KEYCODE_3,Digit4:i.KEYCODE_4,Digit5:i.KEYCODE_5,Digit6:i.KEYCODE_6,Digit7:i.KEYCODE_7,Digit8:i.KEYCODE_8,Digit9:i.KEYCODE_9,Backquote:i.KEYCODE_GRAVE,Minus:i.KEYCODE_MINUS,Equal:i.KEYCODE_EQUALS,BracketLeft:i.KEYCODE_LEFT_BRACKET,BracketRight:i.KEYCODE_RIGHT_BRACKET,Backslash:i.KEYCODE_BACKSLASH,Semicolon:i.KEYCODE_SEMICOLON,Quote:i.KEYCODE_APOSTROPHE,Comma:i.KEYCODE_COMMA,Period:i.KEYCODE_PERIOD,Slash:i.KEYCODE_SLASH,Space:i.KEYCODE_SPACE,Tab:i.KEYCODE_TAB,Escape:i.KEYCODE_ESCAPE,ArrowUp:i.DPAD_UP,ArrowDown:i.DPAD_DOWN,ArrowLeft:i.DPAD_LEFT,ArrowRight:i.DPAD_RIGHT,Enter:i.ENTER,Backspace:i.DEL,Delete:i.FORWARD_DEL,Home:i.KEYCODE_MOVE_HOME,End:i.KEYCODE_MOVE_END,PageUp:i.KEYCODE_PAGE_UP,PageDown:i.KEYCODE_PAGE_DOWN,Insert:i.KEYCODE_INSERT,F1:i.KEYCODE_F1,F2:i.KEYCODE_F2,F3:i.KEYCODE_F3,F4:i.KEYCODE_F4,F5:i.KEYCODE_F5,F6:i.KEYCODE_F6,F7:i.KEYCODE_F7,F8:i.KEYCODE_F8,F9:i.KEYCODE_F9,F10:i.KEYCODE_F10,F11:i.KEYCODE_F11,F12:i.KEYCODE_F12,ShiftLeft:i.KEYCODE_SHIFT_LEFT,ShiftRight:i.KEYCODE_SHIFT_RIGHT,ControlLeft:i.KEYCODE_CTRL_LEFT,ControlRight:i.KEYCODE_CTRL_RIGHT,AltLeft:i.KEYCODE_ALT_LEFT,AltRight:i.KEYCODE_ALT_RIGHT,MetaLeft:i.KEYCODE_META_LEFT,MetaRight:i.KEYCODE_META_RIGHT,ContextMenu:i.MENU,Numpad0:i.KEYCODE_NUMPAD_0,Numpad1:i.KEYCODE_NUMPAD_1,Numpad2:i.KEYCODE_NUMPAD_2,Numpad3:i.KEYCODE_NUMPAD_3,Numpad4:i.KEYCODE_NUMPAD_4,Numpad5:i.KEYCODE_NUMPAD_5,Numpad6:i.KEYCODE_NUMPAD_6,Numpad7:i.KEYCODE_NUMPAD_7,Numpad8:i.KEYCODE_NUMPAD_8,Numpad9:i.KEYCODE_NUMPAD_9,NumpadDivide:i.KEYCODE_NUMPAD_DIVIDE,NumpadMultiply:i.KEYCODE_NUMPAD_MULTIPLY,NumpadSubtract:i.KEYCODE_NUMPAD_SUBTRACT,NumpadAdd:i.KEYCODE_NUMPAD_ADD,NumpadDecimal:i.KEYCODE_NUMPAD_DOT,NumpadComma:i.KEYCODE_NUMPAD_COMMA,NumpadEnter:i.KEYCODE_NUMPAD_ENTER,NumpadEqual:i.KEYCODE_NUMPAD_EQUALS};function Mt(t,e,n,s,E,l,a=1,m=0,O=0){const h=new ArrayBuffer(32),A=new DataView(h);let w=0;A.setUint8(w,Ue.INJECT_TOUCH_EVENT),w+=1;const I=t===Re.ACTION_POINTER_DOWN?Re.ACTION_DOWN:t===Re.ACTION_POINTER_UP?Re.ACTION_UP:t;return A.setUint8(w,I),w+=1,A.setBigInt64(w,BigInt(e),!0),w+=8,A.setInt32(w,Math.round(E),!0),w+=4,A.setInt32(w,Math.round(l),!0),w+=4,A.setUint16(w,n,!0),w+=2,A.setUint16(w,s,!0),w+=2,A.setInt16(w,Math.round(a*65535),!0),w+=2,A.setInt32(w,m,!0),w+=4,A.setInt32(w,O,!0),h}function nn(t,e,n,s,E,l,a){const m=new ArrayBuffer(24),O=new DataView(m);let h=0;return O.setUint8(h,Ue.INJECT_TWO_FINGER_TOUCH_EVENT),h+=1,O.setUint8(h,t),h+=1,O.setInt32(h,Math.round(s),!0),h+=4,O.setInt32(h,Math.round(E),!0),h+=4,O.setInt32(h,Math.round(l),!0),h+=4,O.setInt32(h,Math.round(a),!0),h+=4,O.setUint16(h,e,!0),h+=2,O.setUint16(h,n,!0),h+=2,O.setUint16(h,0,!0),m}function wt(t,e=!0){const s=new TextEncoder().encode(t),E=new ArrayBuffer(14+s.length),l=new DataView(E);let a=0;return l.setUint8(a,Ue.SET_CLIPBOARD),a+=1,l.setBigInt64(a,BigInt(0),!1),a+=8,l.setUint8(a,e?1:0),a+=1,l.setUint32(a,s.length,!1),a+=4,new Uint8Array(E,a).set(s),E}function je(t,e,n=0,s=0){const E=new ArrayBuffer(14),l=new DataView(E);let a=0;return l.setUint8(a,Ue.INJECT_KEYCODE),a+=1,l.setUint8(a,t),a+=1,l.setInt32(a,e,!0),a+=4,l.setInt32(a,n,!0),a+=4,l.setInt32(a,s,!0),E}function rn(t){return t?.displays.find(e=>e.id===(t.angleDegrees<90?"outer":"inner"))}function Yt(t){return t===2?2:t===3?1:t===4?3:0}class on{constructor(e){this.send=e}send;screenId;turns=0;held;get active(){return this.held!==void 0}setDisplay(e,n=Yt(e?.orientation)){(this.screenId!==e?.screenId||this.turns!==n)&&this.release(),this.screenId=e?.screenId,this.turns=n}touch(e,n,s,E=!1){if(this.screenId===void 0)return;const l=bt(n,s,E?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:n,y:s}=this.held;this.held=void 0,this.send(1,e,n,s)}}const an={width:164.6,height:117.8,depth:5.2};function bt(t,e,n){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}}function sn(t){return Number.isFinite(t)&&t>=0&&t<=180}function cn(t,e){return{x:Math.max(0,Math.min(1,t)),y:Math.max(0,Math.min(1,1-e))}}function ln(t,e,n){return e&&(t||!n)?"touch":t?"ignore":"orbit"}function Nt(t,e,n,s){if(!Number.isInteger(t)||t<0||t>3||!Number.isInteger(e)||e<1||e>255||!Number.isFinite(n)||!Number.isFinite(s)||n<0||n>1||s<0||s>1)throw new RangeError("Invalid display touch coordinates");const E=new ArrayBuffer(12),l=new DataView(E);return l.setUint8(0,19),l.setUint8(1,t),l.setUint8(2,e),l.setFloat32(4,n,!0),l.setFloat32(8,s,!0),E}class dn{constructor(e,n){this.send=e,this.failed=n}send;failed;latest;running=!1;stopped=!1;set(e){this.stopped||!sn(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 un={side:"Sleep/Wake",volumeUp:"Volume Up",volumeDown:"Volume Down"};class En{constructor(e,n){this.send=e,this.failed=n}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,n){this.tail=this.tail.then(()=>this.send(e,n)).catch(this.failed)}}const Xe="Accessibility unavailable on this device.",Qe=500,Rt=(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,fn=t=>Math.max(0,t.width)*Math.max(0,t.height),hn=t=>{const e=t.find(n=>n.frame&&n.frame.width>0&&n.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}},mn=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},pn=t=>{const e={};for(const[n,s]of Object.entries(t))n!=="children"&&(e[n]=s);return e};function It(t){const e=Array.isArray(t)?t:[t],n=hn(e),s=[],E=(l,a)=>{if(s.length>=Qe)return;const m=l.frame;if(m&&m.width>0&&m.height>0&&!Rt(m,n)){const h=l.role_description||l.role||"",A=(typeof l.AXLabel=="string"?l.AXLabel:"")||(typeof l.title=="string"?l.title:"")||"";s.push({id:typeof l.AXUniqueId=="string"&&l.AXUniqueId.length>0?l.AXUniqueId:a,path:a,label:A,value:typeof l.AXValue=="string"?l.AXValue:"",role:h,type:typeof l.type=="string"?l.type:"",enabled:l.enabled!==!1,focused:l.focused===!0,frame:{x:m.x,y:m.y,width:m.width,height:m.height},selectors:mn(l),raw:pn(l)})}const O=Array.isArray(l.children)?l.children:[];for(let h=0;h<O.length&&s.length<Qe;h++)E(O[h],`${a}.${h}`)};for(let l=0;l<e.length&&s.length<Qe;l++)E(e[l],String(l));return{platform:"ios",screen:{width:n.width,height:n.height},elements:s,capturedAt:Date.now()}}const Cn=t=>{let e={x:0,y:0,width:1,height:1},n=0;for(const s of t){const E=s.parsedBounds;if(!E)continue;const l=E.right-E.left,a=E.bottom-E.top,m=Math.max(0,l)*Math.max(0,a);m>n&&(n=m,e={x:0,y:0,width:l,height:a})}return e},On=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 Ut(t){const e=Cn(t),n=[];for(let s=0;s<t.length&&n.length<Qe;s++){const E=t[s],l=E.parsedBounds;if(!l)continue;const a=Math.max(0,l.right-l.left),m=Math.max(0,l.bottom-l.top);if(a<=0||m<=0)continue;const O={x:l.left,y:l.top,width:a,height:m};if(Rt(O,{x:0,y:0,width:e.width,height:e.height}))continue;const h=E.contentDesc||E.text||"",A=E.className||"";n.push({id:E.resourceId&&E.resourceId.length>0?E.resourceId:E.contentDesc&&E.contentDesc.length>0?`cd:${E.contentDesc}`:String(s),path:String(s),label:h,value:typeof E.text=="string"?E.text:"",role:A,type:A,enabled:E.enabled!==!1,focused:E.focused===!0,frame:O,selectors:On(E),raw:{...E}})}return{platform:"android",screen:{width:e.width,height:e.height},elements:n,capturedAt:Date.now()}}function Dn(t,e){const n=Math.max(0,t.x),s=Math.max(0,t.y),E=Math.min(e.width,t.x+t.width),l=Math.min(e.height,t.y+t.height),a=Math.max(0,E-n),m=Math.max(0,l-s);return a>0&&m>0?{x:n,y:s,width:a,height:m}:null}function kt(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 n=t.frame,s=e.frame;return n.x===s.x&&n.y===s.y&&n.width===s.width&&n.height===s.height}function Pt(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 n=0;n<t.elements.length;n++)if(!kt(t.elements[n],e.elements[n]))return!1;return!0}function _n(t,e,n){let s=null,E=1/0;for(const l of t.elements){const a=l.frame;if(e<a.x||n<a.y||e>a.x+a.width||n>a.y+a.height)continue;const m=fn(a);m<E&&(E=m,s=l)}return s}function gn(t,e){if(e==="ios"){if(t.selectors.AXUniqueId)return`client.tapElement({ AXUniqueId: ${JSON.stringify(t.selectors.AXUniqueId)} })`;if(t.selectors.AXLabel){const n=t.selectors.className?`, type: ${JSON.stringify(t.selectors.className)}`:"";return`client.tapElement({ AXLabel: ${JSON.stringify(t.selectors.AXLabel)}${n} })`}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 Lt(t){const e=t.role||t.type||"";if(!e)return"element";let n=e.replace(/^AX/,"");return n.includes(".")&&(n=n.split(".").pop()),n==="GenericElement"?"Element":(n=n.replace(/([a-z])([A-Z])/g,"$1 $2"),n)}const gt=80;function Tn(t){const e=Lt(t),n=t.label||t.value||"";if(!n)return e;const s=n.length>gt?n.slice(0,gt).trimEnd()+"…":n;return`${e} · ${s}`}const Sn=500,yn=2e3,Tt=5e3,vn=8e3,An=1200,Kn=250,Mn=()=>`ax-rc-${Date.now()}-${Math.random().toString(36).slice(2,8)}`;class wn{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??Sn,this.maxBackoffMs=e.maxBackoffMs??yn,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,n){if(this.status!==e&&(this.status=e,!!this.onStatusChange))try{this.onStatusChange(e,n)}catch(s){console.error("[AxFetcher] onStatusChange threw:",s)}}bumpActivity(){if(!this.running)return;const e=Date.now();this.boostUntilMs=e+An;const n=Math.max(150,Math.floor(this.baseIntervalMs/2));if(e-this.lastBumpAtMs<n){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 n=e.id;if(!this.pending.get(n))return!1;if(this.platform==="ios"){if(e.type!=="elementTreeResult")return!1;const m=typeof e.error=="string"?e.error:null;if(m)return this.settleReject(n,new Error(m)),!0;const O=typeof e.json=="string"?e.json:"";try{const h=JSON.parse(O),A=It(h);this.settleResolve(n,A)}catch(h){this.settleReject(n,h instanceof Error?h:new Error(String(h)))}return!0}if(e.type!=="getElementTreeResult")return!1;const E=e.error;if(E&&typeof E=="object"){const m=typeof E.message=="string"?E.message:"getElementTree failed";return this.settleReject(n,new Error(m)),!0}const l=e.payload,a=Array.isArray(l?.nodes)?l.nodes:[];try{const m=Ut(a);this.settleResolve(n,m)}catch(m){this.settleReject(n,m instanceof Error?m:new Error(String(m)))}return!0}buildRequest(e){return this.platform==="ios"?{type:"elementTree",id:e}:{type:"getElementTree",id:e,...this.androidElementTreeOptions}}async requestOnce(){const e=Mn();return new Promise((n,s)=>{const E=window.setTimeout(()=>{this.pending.delete(e),s(new Error("elementTree request timed out"))},vn+(this.androidElementTreeOptions?.waitForIdleTimeoutMs??0));this.pending.set(e,{resolve:n,reject:s,timer:E}),this.send(this.buildRequest(e))||(window.clearTimeout(E),this.pending.delete(e),s(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 n=e instanceof Error?e.message:String(e),s=/unavailable|not (yet )?running|failed|timeout/i.test(n);this.currentInterval=s?Tt:Math.min(this.currentInterval*2,this.maxBackoffMs),this.setStatus(s?"unavailable":"error",n)}finally{this.inflight=!1,this.scheduleNext()}}}deliver(e){const n=this.lastSnapshot;if(Pt(n,e)){this.currentInterval=Math.min(this.currentInterval*2,this.maxBackoffMs),this.lastSnapshot=e,e.errors?.includes(Xe)||this.setStatus("ready");return}this.lastSnapshot=e,this.currentInterval=this.baseIntervalMs,e.errors?.includes(Xe)?(this.currentInterval=Tt,this.setStatus("unavailable",Xe)):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(Kn,this.currentInterval):this.currentInterval;this.timer=window.setTimeout(()=>{this.timer=void 0,this.runOnce()},e)}settleResolve(e,n){const s=this.pending.get(e);s&&(window.clearTimeout(s.timer),this.pending.delete(e),s.resolve(n))}settleReject(e,n){const s=this.pending.get(e);s&&(window.clearTimeout(s.timer),this.pending.delete(e),s.reject(n))}failAllPending(e){for(const[n,s]of this.pending.entries())window.clearTimeout(s.timer),s.reject(new Error(e)),this.pending.delete(n)}}function St(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 n=e??null;try{t.jitterBufferTarget!==n&&(t.jitterBufferTarget=n)}catch(s){console.warn("RemoteControl: could not set the jitter buffer target.",s)}}const Ft=`(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
|
-
`,yt=typeof self<"u"&&self.Blob&&new Blob(["(self.URL || self.webkitURL).revokeObjectURL(self.location.href);",Ft],{type:"text/javascript;charset=utf-8"});function Yn(t){let e;try{if(e=yt&&(self.URL||self.webkitURL).createObjectURL(yt),!e)throw"";const n=new Worker(e,{name:t?.name});return n.addEventListener("error",()=>{(self.URL||self.webkitURL).revokeObjectURL(e)}),n}catch{return new Worker("data:text/javascript;charset=utf-8,"+encodeURIComponent(Ft),{name:t?.name})}}function bn(t,e,n){const{MediaStreamTrackProcessor:s,MediaStreamTrackGenerator:E}=globalThis,l=e.getVideoTracks()[0];let a,m,O,h,A=!1;const w=()=>{A||(A=!0,a?.stop(),m?.stop(),O&&(O.postMessage({type:"stop"}),h=setTimeout(()=>O?.terminate(),1e3)))},I=D=>{t.srcObject=D,t.play().catch(()=>{})},W=D=>{A||(w(),n(D),I(e))};try{if(l&&s&&E){a=l.clone();const D=new s({track:a,maxBufferSize:1}),$=new E({kind:"video"});m=$,O=new Yn,O.onmessage=({data:P})=>{P.type==="error"?W(new Error(P.message)):P.type==="stopped"&&(clearTimeout(h),O?.terminate())},O.onerror=P=>W(new Error(P.message)),O.postMessage({type:"start",readable:D.readable,writable:$.writable},[D.readable,$.writable]),I(new MediaStream(e.getTracks().map(P=>P===l?$:P)))}else I(e)}catch(D){W(D)}return w}function Ie(t){return typeof t=="number"&&Number.isFinite(t)}function ge(t,e){if(!(!Ie(t)||!Ie(e)||t<e||e<0))return t-e}class Nn{previous=new Map;reset(){this.previous.clear()}read(e,n,s){const E={timestamp:0,video:[],audio:[]};s==null?E.requestedTargetMs=null:Ie(s)&&s>=0&&s<=4e3&&(E.requestedTargetMs=s);const l=new Map;return e.forEach(a=>{if(a.type!=="inbound-rtp"||!Ie(a.timestamp))return;const m=a.kind??a.mediaType;if(m!=="video"&&m!=="audio")return;const O=n.filter(U=>U.kind===m),h=a.trackIdentifier?O.find(U=>U.trackId===a.trackIdentifier):a.mid!=null?O.find(U=>U.mid===a.mid):O.length===1?O[0]:void 0;if(!h)return;const A=this.previous.get(a.id),I=A?.trackId===h.trackId&&A.stats.ssrc===a.ssrc?A.stats:void 0,W=I?a.timestamp-I.timestamp:void 0,D={id:a.id,trackId:h.trackId,timestamp:a.timestamp};if(W!==void 0&&W>0){D.intervalMs=W;const U=ge(a.jitterBufferEmittedCount,I?.jitterBufferEmittedCount),F=ge(a.jitterBufferDelay,I?.jitterBufferDelay);U!==void 0&&U>0&&F!==void 0&&(D.bufferDelayMs=F/U*1e3);const q=ge(a.bytesReceived,I?.bytesReceived);q!==void 0&&(D.bitrateBps=q*8e3/W)}if(m==="video"){const U={...D,display:h.display??"primary"};if(D.intervalMs!==void 0){const F=ge(a.framesDecoded,I?.framesDecoded);F!==void 0&&(U.fps=F*1e3/D.intervalMs),U.droppedFrames=ge(a.framesDropped,I?.framesDropped),U.freezes=ge(a.freezeCount,I?.freezeCount)}E.video.push(U)}else E.audio.push(D);E.timestamp=Math.max(E.timestamp,a.timestamp),l.set(a.id,I&&a.timestamp<=I.timestamp?A:{stats:a,trackId:h.trackId});const $=a.transportId?e.get(a.transportId):void 0,P=$?.selectedCandidatePairId?e.get($.selectedCandidatePairId):void 0;P?.state==="succeeded"&&Ie(P.currentRoundTripTime)&&P.currentRoundTripTime>=0&&(E.rttMs=P.currentRoundTripTime*1e3)}),this.previous=l,E.video.length||E.audio.length?E:null}}const ot=new WeakSet;function Rn(t,e,n){const{peer:s,displays:E}=t,l=new Nn;let a,m=!1,O=!1,h=!1,A=0,w=!1,I=!1;const W=()=>!m&&!document.hidden&&s.connectionState==="connected",D=F=>{if(!(!F&&!w)){w=F!==null;try{e()?.(F)}catch(q){console.error('[RemoteControl] customer callback "onPlaybackStats" threw:',q)}}},$=()=>{O=!1,A++,clearTimeout(a),l.reset(),D(null)},P=async()=>{if(h||!W())return;if(ot.has(s)){a=setTimeout(()=>{P()},2e3);return}h=!0,ot.add(s);const F=A;try{const q=await s.getStats();if(F!==A||!W())return;const ae=s.getTransceivers().filter(Y=>(Y.currentDirection==="recvonly"||Y.currentDirection==="sendrecv")&&Y.receiver.track.readyState!=="ended").map(Y=>({trackId:Y.receiver.track.id,kind:Y.receiver.track.kind,mid:Y.mid,display:E.get(Y.receiver)}));D(l.read(q,ae,n())),I=!1}catch(q){if(F!==A||!W())return;I||console.warn("[RemoteControl] could not read playback stats:",q),I=!0,l.reset(),D(null)}finally{h=!1,ot.delete(s),O&&W()&&(a=setTimeout(()=>{P()},F===A?2e3:0))}},U=()=>{if(!W()){$();return}O||(O=!0,P())};return document.addEventListener("visibilitychange",U),s.addEventListener("connectionstatechange",U),U(),()=>{m=!0,document.removeEventListener("visibilitychange",U),s.removeEventListener("connectionstatechange",U),$()}}function In(t,e){const n=t.createDataChannel("latency-trace-v1",{ordered:!0,negotiated:!0,id:2});let s=!1,E=!1,l=0;return n.onmessage=a=>{if(E)return;let m;try{m=JSON.parse(a.data)}catch(O){console.warn("Invalid latency trace message",O);return}m&&typeof m=="object"&&!Array.isArray(m)&&e(m)},n.onclose=()=>{E=!0,s=!1},{accept(a){s=!E&&a===1},wrap(a){if(!s||a.byteLength!==32)return a;const m=new DataView(a);if(m.getUint8(0)!==2||m.getUint8(1)>2)return a;const O=new ArrayBuffer(38),h=new DataView(O);return h.setUint8(0,240),h.setUint8(1,1),h.setUint32(2,++l,!0),new Uint8Array(O,6).set(new Uint8Array(a)),O},close(){E=!0,s=!1,n.onmessage=null,n.onclose=null,n.close()}}}class Un{generation=0;tail=Promise.resolve();get currentGeneration(){return this.generation}enqueue(e){const n=++this.generation;return this.append(n,e)}enqueueCurrent(e){return this.append(this.generation,e)}append(e,n){const s={generation:e,isCurrent:()=>e===this.generation},E=this.tail.then(()=>n(s));return this.tail=E.catch(()=>{}),E}invalidate(){++this.generation}}function kn(t){if(!t||typeof t!="object")return null;const e=t;if(e.type!=="cameraRequest"||typeof e.active!="boolean")return null;const n={active:e.active};return(e.facingMode==="user"||e.facingMode==="environment")&&(n.facingMode=e.facingMode),n}function Pn(t){const e={frameRate:{ideal:30,max:30}};return t?.facingMode&&(e.facingMode={ideal:t.facingMode}),e}function Ln(t,e){return!t||t.facingMode!==e.facingMode}function Fn(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 Bn(t){return{type:"cameraResult",granted:!0,camera:Fn(t)}}const oe=(...t)=>{window.debugRemoteControl&&console.log(...t)},S=(...t)=>{window.debugRemoteControl&&console.warn(...t)},L=(t,e,...n)=>{if(e)try{e(...n)}catch(s){console.error(`[RemoteControl] customer callback "${t}" threw:`,s)}},Bt=t=>t.includes("/android_")?"android":"ios",vt=(t,e)=>{const n=new URL(t);return n.searchParams.set("token",e),n.toString()},at=3,xn=1e3,Wn=15e3,qn=3e3,Vn=4e3;function At(){const t=crypto.getRandomValues(new Uint8Array(16));t[6]=t[6]&15|64,t[8]=t[8]&63|128;const e=Array.from(t,n=>n.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 $n(t){let e={...t};const{url:n,token:s,deviceModel:E}=e,l=e.watchOnly??!1,a=e.sessionId??At(),m=e.platform??Bt(n??"");let O={connection:"idle",videoReady:!1,controlReady:!1,duo:!1,duoState:null};const h=r=>{O={...O,...r},L("onStateChange",e.onStateChange,O)},A=r=>h({videoReady:r}),w=r=>h({duoState:r}),I=r=>h({duoError:r}),W=r=>h({duo:r}),D=r=>oe(r);let $=null,P;const U=()=>{P?.(),P=$&&e.onPlaybackStats?Rn($,()=>e.onPlaybackStats,()=>e.jitterBufferTargetMs):void 0},F=new Map,q=new Set,ae=new Set,Y=new Map;let Te=!1;const ke=new Map,st=(r,u,c)=>{u.stop?.(),u.stop=bn(r,c,d=>S("Video playback fallback:",d))},xt=()=>{ke.clear();for(const[r,u]of F)u.clear?.(),u.stop?.(),u.stop=void 0,r.srcObject=null};let Ee=!1,Se=!1,Pe=0,g=null,b=null,B=null,Le=null,fe,ye,ve,Fe,he,le=0,Be=0,te=!1,de=null,Q=null,ue;const ze=new Un;let Ae=null,xe=null,Ze=!l&&(e.microphoneEnabled??!1),et=!1,Ke=null,ee=null,We=0,ct=Promise.resolve(),me=null,Me=!1,ne=new Map,Z=new Map,se=new Map,re=new Map,V=null,we=null,lt=0;const qe=r=>{if(r===null&&we===null)return;we=r;const u=++lt;queueMicrotask(()=>{u===lt&&L("onAxSnapshotChange",e.onAxSnapshotChange,r)})};let pe=null,Ce=new Map;const Wt=(r,u)=>new Promise((c,d)=>{if(l){d(new Error("Device is watch-only"));return}const y=g;if(!y||y.readyState!==WebSocket.OPEN){d(new Error("Simulator disconnected"));return}const p=At(),C=setTimeout(()=>{Ce.delete(p),d(new Error("Device control timed out"))},5e3);Ce.set(p,{resolve:c,reject:d,timer:C}),y.send(JSON.stringify({type:r,id:p,...u}))}),Oe=r=>{pe!==r&&(pe=r,h({connection:r}),L("onConnectionStateChange",e.onConnectionStateChange,r))},ce=r=>{l||!B||B.readyState!=="open"||(B.send(Le?.wrap(r)??r),V?.bumpActivity())},qt=()=>{g&&g.readyState===WebSocket.OPEN&&g.send(JSON.stringify({type:"keepAlive",sessionId:a}))},dt=()=>{fe&&window.clearInterval(fe),fe=window.setInterval(qt,1e4)},Ye=()=>{fe&&(window.clearInterval(fe),fe=void 0)},Ve=()=>{ye&&(window.clearTimeout(ye),ye=void 0)},$e=()=>{ve&&(window.clearTimeout(ve),ve=void 0)},be=()=>{Fe&&(window.clearInterval(Fe),Fe=void 0)},Ne=()=>{he!==void 0&&(window.clearTimeout(he),he=void 0)},Vt=()=>{Me||(Me=!0,be(),A(!0),Oe("connected"))},H=r=>{for(const u of r.getTracks())try{u.stop()}catch(c){S("track.stop() failed:",c)}},$t=()=>{const r=Q;r&&(Q=null,H(r))},ut=r=>{const u=ct.then(r).catch(c=>{S("microphone operation failed:",c)});return ct=u,u},tt=()=>Ze||et,Et=r=>{const u=`ui-mic-${Date.now()}-${Math.random().toString(36).substring(2,9)}`;me=u,r.send(JSON.stringify({type:"microphoneStart",id:u}))},nt=()=>ut(()=>Ht()),Ht=async()=>{const r=We,u=()=>r===We&&tt(),c=f=>{L("onMicrophoneStateChange",e.onMicrophoneStateChange,{active:!1,error:f})};if(!u())return;const d=g,y=Ke;if(!d||d.readyState!==WebSocket.OPEN||!y||ee)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 p=null;try{p=await navigator.mediaDevices.getUserMedia({audio:!0,video:!1})}catch(f){console.warn("[RemoteControl] microphone getUserMedia denied/failed:",f)}if(!u()){p&&H(p);return}if(!p){c("Microphone permission denied or no device available");return}const C=p.getAudioTracks()[0]??null;if(!C){H(p),c("Captured stream has no audio track");return}try{await y.replaceTrack(C)}catch(f){S("replaceTrack(audioTrack) failed:",f),H(p),c("Failed to attach the microphone track to the connection");return}if(!u()){try{await y.replaceTrack(null)}catch(f){S("replaceTrack(null) on stale mic attach failed:",f)}H(p);return}ee=p,C.onended=()=>{ee===p&&He("microphone capture ended by the browser")},Et(d),L("onMicrophoneStateChange",e.onMicrophoneStateChange,{active:!0,label:C.label||void 0})},He=r=>(++We,me=null,ut(async()=>{const u=Ke,c=ee;if(ee=null,u&&c)try{await u.replaceTrack(null)}catch(y){S("replaceTrack(null) on mic detach failed:",y)}c&&H(c);const d=g;if(c&&d&&d.readyState===WebSocket.OPEN){const y=`ui-mic-${Date.now()}-${Math.random().toString(36).substring(2,9)}`;d.send(JSON.stringify({type:"microphoneStop",id:y}))}(c||r)&&L("onMicrophoneStateChange",e.onMicrophoneStateChange,{active:!1,...r!==void 0&&{error:r}})})),ft=(r,u)=>{let c;try{c=Bn(u),console.info(`[RemoteControl] camera capture: ${c.camera?.width}x${c.camera?.height} @ ${c.camera?.frameRate??"?"}fps`+(c.camera?.label?` — ${c.camera.label}`:""))}catch(d){S("getSettings() on outbound camera track failed:",d),c={type:"cameraResult",granted:!0,camera:{label:u.label||void 0}}}r.send(JSON.stringify(c)),L("onCameraDemandChange",e.onCameraDemandChange,!0,!0,c.camera)},Gt=r=>{if(!r)return;const u=r.indexOf("/"),d=(u>=0?r.slice(u+1):r).toUpperCase();return d==="HEVC"?"H265":d},Jt=async()=>{const r=de,u=e.onCameraStats;if(!r||!u)return;let c;try{c=await r.getStats()}catch{return}let d,y,p;if(c.forEach(N=>{N.type==="outbound-rtp"&&N.kind==="video"?d=N:N.type==="remote-inbound-rtp"&&N.kind==="video"&&(p=N)}),d?.codecId){const N=c.get(d.codecId);N&&(y=N.mimeType)}if(!d)return;const C=d.timestamp??Date.now(),f=xe;let J,k,j;if(f&&C>f.timestamp){const N=(C-f.timestamp)/1e3;if(typeof d.framesEncoded=="number"&&typeof f.framesEncoded=="number"&&(J=Math.max(0,(d.framesEncoded-f.framesEncoded)/N)),typeof d.bytesSent=="number"&&typeof f.bytesSent=="number"&&(k=Math.max(0,(d.bytesSent-f.bytesSent)*8/N)),typeof d.packetsSent=="number"&&typeof f.packetsSent=="number"&&p&&typeof p.packetsLost=="number"&&typeof f.packetsLost=="number"){const v=d.packetsSent-f.packetsSent,Je=p.packetsLost-f.packetsLost;v>0&&(j=Math.max(0,Math.min(100,Je/v*100)))}}xe={timestamp:C,framesEncoded:d.framesEncoded,bytesSent:d.bytesSent,packetsSent:d.packetsSent,packetsLost:p?.packetsLost};const M={codec:Gt(y),encoderImplementation:d.encoderImplementation,hardwareAccelerated:typeof d.powerEfficientEncoder=="boolean"?d.powerEfficientEncoder:void 0,framesPerSecond:J,framesEncoded:d.framesEncoded,bitrateBps:k,width:d.frameWidth,height:d.frameHeight,qualityLimitationReason:d.qualityLimitationReason,rttMs:typeof p?.roundTripTime=="number"?p.roundTripTime*1e3:void 0,packetsLostPct:j};L("onCameraStats",e.onCameraStats,M)},ht=()=>{Ae===null&&(xe=null,Ae=setInterval(()=>{Jt()},1e3))},Ge=()=>{Ae!==null&&(clearInterval(Ae),Ae=null),xe=null,L("onCameraStats",e.onCameraStats,null)},jt=(r,u,c,d)=>ze.enqueue(async({isCurrent:y})=>{const p=()=>y()&&d()&&g===u&&de===c;if(!p())return;if(!r.active){const M=Q;try{await c.replaceTrack(null)}catch(N){S("replaceTrack(null) on camera detach failed:",N)}if(Q===M&&(Q=null,ue=void 0,M&&H(M)),Ge(),!p())return;L("onCameraDemandChange",e.onCameraDemandChange,!1);return}L("onCameraDemandChange",e.onCameraDemandChange,!0);const C=Q,f=C?.getVideoTracks()[0],J=ue;if(f?.readyState==="live"&&J&&!Ln(J,r)){ue=r,ft(u,f),ht();return}if(C){try{await c.replaceTrack(null)}catch(M){S("replaceTrack(null) before camera switch failed:",M)}if(Q===C&&(Q=null,ue=void 0,H(C)),Ge(),!p())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."),!p())return;u.send(JSON.stringify({type:"cameraResult",granted:!1})),L("onCameraDemandChange",e.onCameraDemandChange,!0,!1);return}let k=null;try{k=await navigator.mediaDevices.getUserMedia({video:Pn(r),audio:!1})}catch(M){console.warn("[RemoteControl] getUserMedia denied/failed:",M)}if(!p()){k&&H(k);return}if(!k){u.send(JSON.stringify({type:"cameraResult",granted:!1})),L("onCameraDemandChange",e.onCameraDemandChange,!0,!1);return}const j=k.getVideoTracks()[0]??null;if(!j){if(H(k),!p())return;u.send(JSON.stringify({type:"cameraResult",granted:!1})),L("onCameraDemandChange",e.onCameraDemandChange,!0,!1);return}try{j.contentHint="motion"}catch{}try{await c.replaceTrack(j)}catch(M){if(S("replaceTrack(videoTrack) failed:",M),H(k),!p())return;u.send(JSON.stringify({type:"cameraResult",granted:!1})),L("onCameraDemandChange",e.onCameraDemandChange,!0,!1);return}if(!p()){try{await c.replaceTrack(null)}catch(M){S("replaceTrack(null) for stale camera attach failed:",M)}H(k);return}try{const M=c.getParameters();(!M.encodings||M.encodings.length===0)&&(M.encodings=[{}]),M.encodings[0].maxBitrate=8e6,M.encodings[0].maxFramerate=30,M.degradationPreference="maintain-framerate",await c.setParameters(M)}catch(M){S("setParameters on outbound camera failed:",M)}if(!p()){try{await c.replaceTrack(null)}catch(M){S("replaceTrack(null) for stale camera finalize failed:",M)}H(k);return}Q=k,ue=r,j.onended=()=>{Q===k&&ze.enqueueCurrent(async({isCurrent:M})=>{if(!(!M()||Q!==k||!d()||g!==u||de!==c)){try{await c.replaceTrack(null)}catch(N){S("replaceTrack(null) after camera ended failed:",N)}!M()||Q!==k||!d()||g!==u||de!==c||(Q=null,ue=void 0,H(k),Ge(),u.send(JSON.stringify({type:"cameraResult",granted:!1})),L("onCameraDemandChange",e.onCameraDemandChange,!0,!1))}}).catch(M=>S("camera ended cleanup failed:",M))},p()&&(ft(u,j),ht())}),De=()=>{for(const r of ae)r();ae.clear();for(const r of Y.values())clearTimeout(r);Y.clear();for(const r of Z.values())r(new Error("Simulator disconnected"));for(const r of re.values())r(new Error("Simulator disconnected"));Z.clear(),ne.clear(),re.clear(),se.clear(),P?.(),P=void 0,xt(),$=null;for(const r of Ce.values())clearTimeout(r.timer),r.reject(new Error("Simulator disconnected"));Ce.clear(),w(null),h({controlReady:!1,videoReady:!1}),$e(),Ne(),be(),V&&(V.stop(),V=null),we!==null&&qe(null),ze.invalidate(),Ge(),$t(),ue=void 0,de=null,++We,et=!1,me=null,ee&&(H(ee),ee=null,L("onMicrophoneStateChange",e.onMicrophoneStateChange,{active:!1})),Ke=null,g&&(g.onopen=null,g.onmessage=null,g.onerror=null,g.onclose=null,g.close(),g=null),Le?.close(),Le=null,b&&(b.onconnectionstatechange=null,b.oniceconnectionstatechange=null,b.ontrack=null,b.onicecandidate=null,b.close(),b=null),B&&(B.onopen=null,B.onclose=null,B.onerror=null,B.close(),B=null)},mt=()=>{document.hidden?Ye():dt()},Xt=async()=>{if(e.transport)return e.transport.isTerminated?.()??!1;if(typeof navigator<"u"&&navigator.onLine===!1)return!1;let r;try{const d=new URL(n);d.protocol=d.protocol==="wss:"?"https:":d.protocol==="ws:"?"http:":d.protocol,r=vt(d.toString(),s)}catch{return!1}const u=new AbortController,c=window.setTimeout(()=>u.abort(),Vn);try{return(await fetch(r,{method:"GET",cache:"no-store",signal:u.signal})).status===404}catch{return!1}finally{window.clearTimeout(c)}},Qt=()=>{Ee||(Ee=!0,le+=1,Ve(),$e(),Ne(),De(),D("Instance terminated"),Ye(),Oe("terminated"),L("onTerminated",e.onTerminated))},zt=()=>{if(Ee||Se)return;Se=!0;const r=Pe;Xt().catch(()=>!1).then(u=>{r===Pe&&(Se=!1,u&&Qt())})},_e=(r,u)=>{if(Ee||u!==le)return;if(zt(),te){if(e.autoReconnect===!1){D(`Connection failed after it was established: ${r}`),Ye(),Oe("failed"),De();return}D(`Reconnecting after established session dropped: ${r}`),te=!1,Be=-1}Ve();const c=Be+1;if(c>=at){D(`Connection failed after ${at} attempts: ${r}`),Ye(),Oe("failed"),De();return}D(`Retrying connection (${c+1}/${at})`),Oe("reconnecting"),De(),ye=window.setTimeout(()=>{ye=void 0,u===le&&pt(c)},xn)},pt=async(r=0)=>{const{openUrl:u,axPollIntervalMs:c,axMaxBackoffMs:d,androidElementTreeOptions:y}=e;if(Ee)return;const p=le+1;le=p,Be=r,te=!1,r===0&&pe!=="reconnecting"&&Oe("connecting"),Ve(),$e(),be(),Me=!1,A(!1),De();const C=()=>p===le;ve=window.setTimeout(()=>{ve=void 0,!(!C()||te)&&_e("Connection did not succeed within 15 seconds",p)},Wn);try{const f=e.transport?await e.transport.connect():new WebSocket(vt(n,s));if(!C()){f.close();return}if(g=f,await new Promise((_,o)=>{let R=!1;const x=()=>K(()=>o(new Error("Connection stopped")));ae.add(x);const T=window.setTimeout(()=>K(()=>o(new Error("WebSocket connection timeout"))),3e4),K=z=>{R||(R=!0,ae.delete(x),window.clearTimeout(T),z())};f.onopen=()=>{!C()||g!==f||K(_)},f.onerror=z=>{!C()||g!==f||(D("WebSocket error: "+z),K(()=>o(new Error("WebSocket connection failed"))))},f.onclose=()=>{!C()||g!==f||(D("WebSocket closed"),K(()=>o(new Error("WebSocket closed before connection was established"))))},f.readyState===WebSocket.OPEN?K(_):f.readyState!==WebSocket.CONNECTING&&K(()=>o(new Error("WebSocket is closed")))}),!C()||g!==f)return;f.onerror=_=>{!C()||g!==f||D("WebSocket error: "+_)},f.onclose=()=>{!C()||g!==f||D("WebSocket closed")};const J=new Promise((_,o)=>{let R=!1;const x=()=>T(()=>o(new Error("Connection stopped")));ae.add(x);const T=G=>{R||(R=!0,ae.delete(x),window.clearTimeout(K),f.removeEventListener("message",z),G())},K=window.setTimeout(()=>T(()=>o(new Error("RTCConfiguration timeout"))),3e4),z=G=>{if(!(!C()||g!==f))try{const X=JSON.parse(G.data);if(X.type==="signalingError"&&X.requestType==="requestRtcConfiguration"&&X.sessionId===a){const tn=typeof X.error=="string"?X.error:"Unable to load streaming configuration";T(()=>o(new Error(tn)))}else X.type==="rtcConfiguration"&&T(()=>_({rtcConfiguration:X.rtcConfiguration,cameraSupported:X.cameraSupported===!0,foldSupported:X.foldSupported===!0}))}catch(X){console.error("Error handling RTC configuration:",X),T(()=>o(X))}};f.addEventListener("message",z),f.send(JSON.stringify({type:"requestRtcConfiguration",sessionId:a}))}),{rtcConfiguration:k,cameraSupported:j,foldSupported:M}=await J;if(!C()||g!==f)return;const N=E==="iphone-duo"||M;W(N);const v=new RTCPeerConnection({...k,iceTransportPolicy:"relay"});b=v;const Je={peer:v,displays:new Map};$=Je,U(),v.addTransceiver("audio",{direction:"recvonly"});const Zt=v.addTransceiver("video",{direction:"recvonly"}),en=N?v.addTransceiver("video",{direction:"recvonly"}):null,_t=!l&&(m==="ios"||j),rt=_t?v.addTransceiver("video",{direction:"sendonly"}):null;if(de=rt?.sender??null,Ke=(_t?v.addTransceiver("audio",{direction:"sendonly"}):null)?.sender??null,RTCRtpReceiver.getCapabilities){const _=RTCRtpReceiver.getCapabilities("video");if(_&&_.codecs){const R=_.codecs.sort((x,T)=>{const K=z=>{const G=z.mimeType.toLowerCase();return G.includes("vp9")?1:G.includes("h265")||G.includes("hevc")?2:G.includes("h264")||G.includes("avc")?3:4};return K(x)-K(T)});Zt.setCodecPreferences(R),en?.setCodecPreferences(R),oe("Set codec preferences:",R.map(x=>x.mimeType).join(", "))}}if(rt&&RTCRtpSender.getCapabilities){const _=RTCRtpSender.getCapabilities("video");if(_&&_.codecs){const o=new Set(["42e01f","42e028","640c1f"]),R=T=>{const K=T.mimeType.toLowerCase(),G=(T.sdpFmtpLine||"").toLowerCase().match(/profile-level-id=([0-9a-f]{6})/),X=G?G[1]:"";return K==="video/h265"||K==="video/hevc"?1:K==="video/h264"&&o.has(X)?2:K==="video/h264"?3:K==="video/vp9"?4:K==="video/vp8"?5:K==="video/rtx"||K==="video/red"||K==="video/ulpfec"?0:6},x=[..._.codecs].sort((T,K)=>R(T)-R(K));try{rt.setCodecPreferences(x),oe("Outbound camera codec preferences:",x.map(T=>`${T.mimeType}${T.sdpFmtpLine?`[${T.sdpFmtpLine}]`:""}`).join(", "))}catch(T){S("Failed to set outbound camera codec preferences:",T)}}}const ie=v.createDataChannel("control",{ordered:!0,negotiated:!0,id:1});B=ie;const it=!l&&!N&&e.onTrace?In(v,_=>{C()&&b===v&&L("onTrace",e.onTrace,_)}):null;if(Le=it,ie.onopen=()=>{if(!C()||B!==ie||g!==f)return;te=!0,h({controlReady:!l}),$e(),D("Control channel opened"),N&&f.send(JSON.stringify({type:"getFoldState",id:"duo-capabilities"})),V||(V=new wn({platform:m,baseIntervalMs:c,maxBackoffMs:d,androidElementTreeOptions:y,send:o=>{if(!g||g.readyState!==WebSocket.OPEN)return!1;try{return g.send(JSON.stringify(o)),!0}catch{return!1}},onSnapshot:qe,onStatusChange:(o,R)=>{L("onAxStatusChange",e.onAxStatusChange,o,R)}}),(e.inspectMode===!0||e.inspectMode==="hover-only")&&V.start());const _=()=>{!C()||Me||B!==ie||g!==f||f.readyState!==WebSocket.OPEN||f.send(JSON.stringify({type:"requestFrame",sessionId:a}))};if(_(),be(),Fe=window.setInterval(()=>{if(!C()||Me||B!==ie||g!==f||f.readyState!==WebSocket.OPEN){be();return}_()},250),!l&&u){try{const o=decodeURIComponent(u);D("Opening URL"),f.send(JSON.stringify({type:"openUrl",url:o,sessionId:a}))}catch(o){console.error({error:o},"Error decoding URL, falling back to the original URL"),f.send(JSON.stringify({type:"openUrl",url:u,sessionId:a}))}V?.bumpActivity()}},ie.onclose=()=>{!C()||B!==ie||(h({controlReady:!1}),D("Control channel closed"))},ie.onerror=_=>{!C()||B!==ie||(console.error("Control channel error:",_),D("Control channel error: "+_))},v.onconnectionstatechange=()=>{!C()||b!==v||(D("Connection state: "+v.connectionState),v.connectionState==="failed"&&te&&_e("WebRTC connection entered failed state",p))},v.oniceconnectionstatechange=()=>{if(!C()||b!==v)return;const _=v.iceConnectionState;if(D("ICE state: "+_),_==="connected"||_==="completed"){Ne(),tt()&&!ee&&nt();return}if(_==="failed"){Ne(),te&&_e("ICE connection entered failed state",p);return}_==="disconnected"&&te&&e.autoReconnect!==!1&&he===void 0&&(he=window.setTimeout(()=>{he=void 0,!(!C()||b!==v)&&v.iceConnectionState==="disconnected"&&_e("ICE stayed disconnected past grace period",p)},qn))},v.ontrack=_=>{if(!C()||b!==v)return;St(_.receiver,e.jitterBufferTargetMs);const o=_.track.id==="duo-inner"||_.streams.some(R=>R.id==="duo-inner");if(_.track.kind==="video"&&Je.displays.set(_.receiver,o?"inner":"primary"),D("Received remote track: "+_.track.kind),_.track.kind==="video"){const R=o?"inner":"primary",x=N?new MediaStream([_.track]):_.streams[0]??new MediaStream([_.track]);ke.set(R,x);for(const[T,K]of F)K.display===R&&st(T,K,x)}},v.onicecandidate=_=>{if(!(!C()||b!==v||g!==f))if(_.candidate&&f.readyState===WebSocket.OPEN){const o={type:"candidate",candidate:_.candidate.candidate,sdpMid:_.candidate.sdpMid,sdpMLineIndex:_.candidate.sdpMLineIndex,sessionId:a};f.send(JSON.stringify(o)),D("Sent ICE candidate")}else D("ICE candidate gathering completed")},f.onmessage=async _=>{if(!C()||g!==f)return;let o;try{o=JSON.parse(_.data)}catch(R){S("Error parsing message:",R);return}if(!V?.handleMessage(o))switch(D("Received: "+o.type),o.type){case"performActionsResult":case"foldStateResult":case"foldStateChanged":{if(!N)break;o.state?(w(o.state),I(void 0)):o.id==="duo-capabilities"&&I(o.error||"This instance does not support native iPhone Duo displays.");const T=Ce.get(o.id);T&&(clearTimeout(T.timer),Ce.delete(o.id),o.error?T.reject(new Error(o.error)):T.resolve());break}case"signalingError":{if(o.requestType!=="offer"||o.sessionId!==a)break;const T=typeof o.error=="string"?o.error:"Unable to establish the streaming connection";D("Error: "+T),_e(T,p);break}case"answer":if(!b||b!==v){D("No peer connection, skipping answer");break}if(it?.accept(o.latencyTraceVersion),await v.setRemoteDescription(new RTCSessionDescription({type:"answer",sdp:o.sdp})),!C()||b!==v)return;D("Set remote description");break;case"candidate":if(!b||b!==v){D("No peer connection, skipping candidate");break}if(await v.addIceCandidate(new RTCIceCandidate({candidate:o.candidate,sdpMid:o.sdpMid,sdpMLineIndex:o.sdpMLineIndex})),!C()||b!==v)return;D("Added ICE candidate");break;case"screenshot":case"screenshotResult":{if(typeof o.id!="string"){S("Received invalid screenshot success message:",o);break}const T=Hn(o);if(T){const G=Z.get(o.id);if(typeof G!="function"){S(`Received screenshot error for unknown or handled id: ${o.id}`);break}S(`Received screenshot error for id ${o.id}: ${T}`),G(new Error(T)),ne.delete(o.id),Z.delete(o.id),clearTimeout(Y.get(o.id)),Y.delete(o.id);break}const K=Gn(o);if(!K){S("Received screenshot message without image data:",o);break}const z=ne.get(o.id);if(typeof z!="function"){S(`Received screenshot data for unknown or handled id: ${o.id}`);break}oe(`Received screenshot data for id ${o.id}`),z(K),ne.delete(o.id),Z.delete(o.id),clearTimeout(Y.get(o.id)),Y.delete(o.id);break}case"screenshotError":if(typeof o.id!="string"||typeof o.message!="string"){S("Received invalid screenshot error message:",o);break}const R=Z.get(o.id);if(typeof R!="function"){S(`Received screenshot error for unknown or handled id: ${o.id}`);break}S(`Received screenshot error for id ${o.id}: ${o.message}`),R(new Error(o.message)),ne.delete(o.id),Z.delete(o.id),clearTimeout(Y.get(o.id)),Y.delete(o.id);break;case"cameraRequest":{const T=de;if(!T)break;const K=kn(o);if(!K){S("Received invalid cameraRequest:",o);break}console.info("[RemoteControl] cameraRequest received:",K.active,K.facingMode),await jt(K,f,T,C);break}case"microphoneRequest":{if(!Ke)break;const T=o.active===!0;if(et=T,console.info("[RemoteControl] microphoneRequest received, active=",T),!T){Ze||await He();break}if(ee){Et(f);break}await nt();break}case"microphoneStartResult":{if(me===null||o.id!==me)break;me=null,typeof o.error=="string"&&(console.warn("[RemoteControl] microphoneStart rejected by host:",o.error),He(o.error));break}case"terminateAppResult":if(typeof o.id!="string"){S("Received invalid terminateApp result message:",o);break}if(typeof o.error=="string"){const T=re.get(o.id);if(typeof T!="function"){S(`Received terminateApp error for unknown or handled id: ${o.id}`);break}S(`Received terminateApp error for id ${o.id}: ${o.error}`),T(new Error(o.error)),se.delete(o.id),re.delete(o.id),clearTimeout(Y.get(o.id)),Y.delete(o.id);break}const x=se.get(o.id);if(typeof x!="function"){S(`Received terminateApp result for unknown or handled id: ${o.id}`);break}oe(`Received terminateApp success for id ${o.id}`),x(),se.delete(o.id),re.delete(o.id),clearTimeout(Y.get(o.id)),Y.delete(o.id);break;default:S(`Received unhandled message type: ${o.type}`,o);break}},b===v){const _=await v.createOffer({offerToReceiveVideo:!0,offerToReceiveAudio:!1});if(!C()||b!==v||(await v.setLocalDescription(_),!C()||b!==v))return;C()&&g===f&&f.readyState===WebSocket.OPEN&&f.send(JSON.stringify({type:"offer",...N?{displayStreams:!0}:{},...it?{latencyTraceVersion:1}:{},sdp:_.sdp,sessionId:a})),D("Sent offer")}}catch(f){if(!C()||f instanceof Error&&f.message==="Connection stopped")return;const J=f instanceof Error?f.message:String(f);D("Error: "+J),_e(J,p)}},Ct=()=>{if(Te)throw new Error("Device stream is disposed");Pe++,Se=!1,qe(null),pe!=="reconnecting"&&(pe=null),document.addEventListener("visibilitychange",mt),document.hidden||dt(),Ee=!1,pt(0)},Ot=()=>{Pe++,Se=!1,Ye(),document.removeEventListener("visibilitychange",mt),le+=1,Be=0,te=!1,Ve(),Ne(),De(),pe=null,h({connection:"idle",videoReady:!1,controlReady:!1}),D("Stopped")},Dt=(r,u="primary")=>{if(Te)throw new Error("Device stream is disposed");if(F.has(r))throw new Error("Video element is already attached");const c={display:u};F.set(r,c);const d=()=>{u==="primary"&&ke.has(u)&&Vt()};r.addEventListener("loadeddata",d);const y=ke.get(u);y&&st(r,c,y);let p=!1;const C=()=>{p||(p=!0,q.delete(C),r.removeEventListener("loadeddata",d),c.stop?.(),F.delete(r),r.srcObject=null)};return q.add(C),C};return{start:Ct,stop:Ot,attachVideo:Dt,attachFrameSink:(r,u="primary")=>{const c=document.createElement("video");c.muted=!0,c.playsInline=!0,c.autoplay=!0;const d=Dt(c,u);let y=!1,p=0,C=0;const f=()=>{c.cancelVideoFrameCallback?.(p),cancelAnimationFrame(C)},J=()=>{y||!c.srcObject||(c.readyState>=2&&c.videoWidth>0&&L("present",(...M)=>r.present(...M),c,c.videoWidth,c.videoHeight,u),!(y||!c.srcObject)&&(c.requestVideoFrameCallback?p=c.requestVideoFrameCallback(J):C=requestAnimationFrame(J)))},k=()=>{f(),J()};F.get(c).clear=f,c.addEventListener("loadeddata",k);const j=()=>{y||(y=!0,q.delete(j),f(),c.removeEventListener("loadeddata",k),d(),c.remove())};return q.delete(d),q.add(j),c.readyState>=2&&k(),j},dispose:()=>{if(!Te){Te=!0,Ot();for(const r of q)r();q.clear()}},getState:()=>O,updateOptions:r=>{if(Te)throw new Error("Device stream is disposed");const u=e;if(e={...e,...r},u.jitterBufferTargetMs!==e.jitterBufferTargetMs)for(const c of b?.getTransceivers()??[])(c.currentDirection==="recvonly"||c.currentDirection==="sendrecv")&&St(c.receiver,e.jitterBufferTargetMs);!!u.onPlaybackStats!=!!e.onPlaybackStats&&U(),!!u.microphoneEnabled!=!!e.microphoneEnabled&&(Ze=!l&&(e.microphoneEnabled??!1),tt()?nt():He()),!!u.inspectMode!=!!e.inspectMode&&(e.inspectMode?V?.start():(V?.stop(),we!==null&&qe(null)))},sendControl:ce,sendTouch:(r,u,c,d,y,p=0)=>ce(Mt(r==="begin"?0:r==="end"?1:2,p,d,y,u,c,r==="end"?0:1)),sendText:r=>ce(wt(r)),sendDisplayTouch:(r,u,c,d)=>ce(Nt(r,u,c,d)),sendDuoControl:Wt,pressButton:r=>{const u={home:3,back:4,recents:187,power:26}[r];ce(je(0,u,0,0)),ce(je(1,u,0,0))},rotate:()=>ce(new Uint8Array([11]).buffer),bumpActivity:()=>V?.bumpActivity(),getAxStatus:()=>V?.getStatus()??"idle",openUrl:r=>{if(!l){if(!g||g.readyState!==WebSocket.OPEN){S("WebSocket not open, cannot send open_url command.");return}try{const u=decodeURIComponent(r);D("Opening URL"),g.send(JSON.stringify({type:"openUrl",url:u,sessionId:a}))}catch(u){S("Error decoding or sending URL :",{error:u,url:r}),g.send(JSON.stringify({type:"openUrl",url:r,sessionId:a}))}V?.bumpActivity()}},sendKeyEvent:r=>{if(!B||B.readyState!=="open"){S("Data channel not ready for imperative key command:",B?.readyState);return}const u=Kt[r.code];if(!u){S(`Unknown event.code for imperative command: ${r.code}`);return}let c=i.META_NONE;r.shiftKey&&(c|=i.META_SHIFT_ON),r.altKey&&(c|=i.META_ALT_ON),r.ctrlKey&&(c|=i.META_CTRL_ON),r.metaKey&&(c|=i.META_META_ON);const d=r.type==="keydown"?i.ACTION_DOWN:i.ACTION_UP;oe(`Sending Imperative Key Command: code=${r.code}, keycode=${u}, action=${d}, meta=${c}`);const y=je(d,u,0,c);y&&ce(y)},screenshot:r=>new Promise((u,c)=>{if(!g||g.readyState!==WebSocket.OPEN)return S("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)}`,y={type:r?"screenshotDisplay":"screenshot",...r?{display:r}:{},id:d};ne.set(d,u),Z.set(d,c),oe("Sending screenshot request:",y);try{g.send(JSON.stringify(y))}catch(p){S("Failed to send screenshot request immediately:",p),ne.delete(d),Z.delete(d),c(p);return}Y.set(d,setTimeout(()=>{Y.delete(d),ne.has(d)&&(S(`Screenshot request timed out for id ${d}`),Z.get(d)?.(new Error("Screenshot request timed out")),ne.delete(d),Z.delete(d))},3e4))}),terminateApp:r=>l?Promise.reject(new Error("Device is watch-only")):new Promise((u,c)=>{if(!g||g.readyState!==WebSocket.OPEN)return S("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)}`,y={type:"terminateApp",id:d,bundleId:r};se.set(d,u),re.set(d,c),oe("Sending terminateApp request:",y);try{g.send(JSON.stringify(y))}catch(p){S("Failed to send terminateApp request immediately:",p),se.delete(d),re.delete(d),c(p);return}V?.bumpActivity(),Y.set(d,setTimeout(()=>{Y.delete(d),se.has(d)&&(S(`terminateApp request timed out for id ${d}`),re.get(d)?.(new Error("terminateApp request timed out")),se.delete(d),re.delete(d))},3e4))}),reconnect:()=>Ct(),refreshAxTree:async()=>{const r=V;if(!r)throw new Error("Inspect mode is not active");return r.refresh()},getAxSnapshot:()=>we}}const Hn=t=>typeof t.message=="string"?t.message:typeof t.error=="string"?t.error:null,Gn=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=Re;exports.ANDROID_KEYS=i;exports.AX_UNAVAILABLE_ERROR=Xe;exports.CONTROL_MSG_TYPE=Ue;exports.DUO_BUTTONS=un;exports.DUO_DIMENSIONS=an;exports.DuoButtonSender=En;exports.DuoTouchController=on;exports.HingeSender=dn;exports.axElementAtPoint=_n;exports.axElementRoleLabel=Lt;exports.axElementSelectorExpression=gn;exports.axElementSummary=Tn;exports.axElementsEqual=kt;exports.axSnapshotsEqual=Pt;exports.clampAxFrameForScreen=Dn;exports.codeMap=Kt;exports.createDeviceStream=$n;exports.createDisplayTouchMessage=Nt;exports.createInjectKeycodeMessage=je;exports.createSetClipboardMessage=wt;exports.createTouchControlMessage=Mt;exports.createTwoFingerTouchControlMessage=nn;exports.debugLog=oe;exports.debugWarn=S;exports.detectPlatform=Bt;exports.duoDisplayTurns=Yt;exports.duoPointerMode=ln;exports.flatDisplayTouch=bt;exports.getDuoDisplay=rn;exports.normalizeAndroidTree=Ut;exports.normalizeIosTree=It;exports.panelTouch=cn;exports.safeInvoke=L;
|