@limrun/ui 0.22.6 → 0.22.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/lite.cjs CHANGED
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const r=require("./remote-control-y8mgo_2E.js"),e=require("./core-_qwksEry.js");exports.RemoteControl=r.RemoteControl;exports.AX_UNAVAILABLE_ERROR=e.AX_UNAVAILABLE_ERROR;exports.axElementAtPoint=e.axElementAtPoint;exports.axElementSelectorExpression=e.axElementSelectorExpression;exports.axElementSummary=e.axElementSummary;exports.axElementsEqual=e.axElementsEqual;exports.axSnapshotsEqual=e.axSnapshotsEqual;exports.clampAxFrameForScreen=e.clampAxFrameForScreen;exports.normalizeAndroidTree=e.normalizeAndroidTree;exports.normalizeIosTree=e.normalizeIosTree;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const r=require("./remote-control-D_851mel.js"),e=require("./core-B3nWmNki.js");exports.RemoteControl=r.RemoteControl;exports.AX_UNAVAILABLE_ERROR=e.AX_UNAVAILABLE_ERROR;exports.axElementAtPoint=e.axElementAtPoint;exports.axElementSelectorExpression=e.axElementSelectorExpression;exports.axElementSummary=e.axElementSummary;exports.axElementsEqual=e.axElementsEqual;exports.axSnapshotsEqual=e.axSnapshotsEqual;exports.clampAxFrameForScreen=e.clampAxFrameForScreen;exports.normalizeAndroidTree=e.normalizeAndroidTree;exports.normalizeIosTree=e.normalizeIosTree;
package/dist/lite.js CHANGED
@@ -1,5 +1,5 @@
1
- import { R as o } from "./remote-control-DmPKov-i.mjs";
2
- import { A as s, a as m, b as n, c as t, d as l, e as x, f as E, n as A, g as i } from "./core-BPDihn1M.mjs";
1
+ import { R as o } from "./remote-control-cQIifCub.mjs";
2
+ import { A as s, a as m, b as n, c as t, d as l, e as x, f as E, n as A, g as i } from "./core-B7MkSLE_.mjs";
3
3
  export {
4
4
  s as AX_UNAVAILABLE_ERROR,
5
5
  o as RemoteControl,
@@ -1,6 +1,6 @@
1
1
  import { jsxs as _, jsx as M } from "react/jsx-runtime";
2
2
  import { useRef as E, useState as ne, useId as ze, useEffect as Pe } from "react";
3
- import { M as L, l as q, m as $e, a as Ze, b as qe, c as Je, s as Qe, d as et, e as Ce } from "./remote-control-DmPKov-i.mjs";
3
+ import { M as L, l as q, m as $e, a as Ze, b as qe, c as Je, s as Qe, d as et, e as Ce } from "./remote-control-cQIifCub.mjs";
4
4
  import { u as tt, P as ot, c as rt, V as nt, S as st, L as Ie, M as it, D as Re, G as se, B as ct, I as at, a as ie, b as ce, d as Ne, l as lt, T as dt, R as ut, e as F, f as _e, g as ft, h as pt, i as R } from "./model-source-CN_i4mVy.mjs";
5
5
  const T = {
6
6
  front: { yaw: 0, pitch: 0.1, label: "Front" },
@@ -1,2 +1,2 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const p=require("react/jsx-runtime"),f=require("react"),c=require("./remote-control-y8mgo_2E.js"),r=require("./model-source-D3_k9qRK.js"),N={front:{yaw:0,pitch:.1,label:"Front"},desk:{yaw:-.5,pitch:.42,label:"Desk"},side:{yaw:-1.15,pitch:.16,label:"Side"}},Oe=28,Ie={environment:.45,hemisphere:1,key:{intensity:2.2,position:[-120,220,260]},rim:{intensity:.7,position:[220,40,-220]}};function Ne(v,j){const n=r.DoubleSide;switch(v){case"screen":return j;case"shell":return new r.MeshStandardMaterial({color:3421498,metalness:.9,roughness:.34,side:n});case"glass":return new r.MeshPhysicalMaterial({color:328966,roughness:.06,clearcoat:1,side:n});case"camera":return new r.MeshStandardMaterial({color:790549,roughness:.2,side:n});case"well":return new r.MeshStandardMaterial({color:1052690,roughness:.9,side:n});case"keys":return new r.MeshStandardMaterial({color:723725,roughness:.7,side:n});case"trackpad":return new r.MeshPhysicalMaterial({color:2895153,metalness:.4,roughness:.3,clearcoat:.6,side:n});case"scoop":return new r.MeshStandardMaterial({color:1579035,metalness:.6,roughness:.5,side:n})}}const je={glass:1,camera:2,screen:2,well:1,keys:2,trackpad:1,scoop:1};function Ge(v){const j=f.useRef(null),n=f.useRef(v);n.current=v;const[te,z]=f.useState(),[xe,ke]=f.useState(!1),re=f.useRef(!1),{view:oe,viewRef:$,chooseView:Se,locked:x,lockedRef:De,setLocked:_e,orbit:ne,drag:Be}=r.useStageView("front"),P=f.useRef(()=>{}),k=f.useRef(c.MACBOOK_LID_OPEN_DEGREES),m=f.useRef(c.MACBOOK_LID_OPEN_DEGREES),[G,Z]=f.useState(c.MACBOOK_LID_OPEN_DEGREES),F=f.useRef(void 0),se=f.useId(),ie=o=>{const u=m.current;k.current=o,F.current={from:u,to:o,start:performance.now(),duration:c.MACBOOK_LID_OPENING_MS*Math.abs(o-u)/c.MACBOOK_LID_OPEN_DEGREES},P.current()};return f.useEffect(()=>P.current(),[oe,x]),f.useEffect(()=>{const o=j.current,u=v.video;if(!o||!u)return;const ce=()=>{ke(!0),n.current.onReady?.()};z(void 0);const S=new r.PerspectiveCamera(Oe,1,10,4e3);let J=1;const K=r.createDeviceStage({container:o,videos:[u],maxPixelRatio:2,lighting:Ie,resize:(e,t)=>{J=e/t,S.aspect=J,S.updateProjectionMatrix()},frame:(e,t)=>Ce(e,t)});if(!K){z("3D rendering is unavailable in this browser. Enable WebGL to use the 3D MacBook."),ce();return}const{renderer:T,scene:ae,invalidate:C}=K;let U=!1;const b=new r.VideoTexture(u);b.colorSpace=r.SRGBColorSpace,b.minFilter=r.LinearFilter,b.magFilter=r.LinearFilter,b.anisotropy=T.capabilities.getMaxAnisotropy();const D=new r.MeshBasicMaterial({map:b,toneMapped:!1,side:r.DoubleSide});D.onBeforeCompile=e=>{e.fragmentShader=e.fragmentShader.replace("#include <map_fragment>",`#include <map_fragment>
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const p=require("react/jsx-runtime"),f=require("react"),c=require("./remote-control-D_851mel.js"),r=require("./model-source-D3_k9qRK.js"),N={front:{yaw:0,pitch:.1,label:"Front"},desk:{yaw:-.5,pitch:.42,label:"Desk"},side:{yaw:-1.15,pitch:.16,label:"Side"}},Oe=28,Ie={environment:.45,hemisphere:1,key:{intensity:2.2,position:[-120,220,260]},rim:{intensity:.7,position:[220,40,-220]}};function Ne(v,j){const n=r.DoubleSide;switch(v){case"screen":return j;case"shell":return new r.MeshStandardMaterial({color:3421498,metalness:.9,roughness:.34,side:n});case"glass":return new r.MeshPhysicalMaterial({color:328966,roughness:.06,clearcoat:1,side:n});case"camera":return new r.MeshStandardMaterial({color:790549,roughness:.2,side:n});case"well":return new r.MeshStandardMaterial({color:1052690,roughness:.9,side:n});case"keys":return new r.MeshStandardMaterial({color:723725,roughness:.7,side:n});case"trackpad":return new r.MeshPhysicalMaterial({color:2895153,metalness:.4,roughness:.3,clearcoat:.6,side:n});case"scoop":return new r.MeshStandardMaterial({color:1579035,metalness:.6,roughness:.5,side:n})}}const je={glass:1,camera:2,screen:2,well:1,keys:2,trackpad:1,scoop:1};function Ge(v){const j=f.useRef(null),n=f.useRef(v);n.current=v;const[te,z]=f.useState(),[xe,ke]=f.useState(!1),re=f.useRef(!1),{view:oe,viewRef:$,chooseView:Se,locked:x,lockedRef:De,setLocked:_e,orbit:ne,drag:Be}=r.useStageView("front"),P=f.useRef(()=>{}),k=f.useRef(c.MACBOOK_LID_OPEN_DEGREES),m=f.useRef(c.MACBOOK_LID_OPEN_DEGREES),[G,Z]=f.useState(c.MACBOOK_LID_OPEN_DEGREES),F=f.useRef(void 0),se=f.useId(),ie=o=>{const u=m.current;k.current=o,F.current={from:u,to:o,start:performance.now(),duration:c.MACBOOK_LID_OPENING_MS*Math.abs(o-u)/c.MACBOOK_LID_OPEN_DEGREES},P.current()};return f.useEffect(()=>P.current(),[oe,x]),f.useEffect(()=>{const o=j.current,u=v.video;if(!o||!u)return;const ce=()=>{ke(!0),n.current.onReady?.()};z(void 0);const S=new r.PerspectiveCamera(Oe,1,10,4e3);let J=1;const K=r.createDeviceStage({container:o,videos:[u],maxPixelRatio:2,lighting:Ie,resize:(e,t)=>{J=e/t,S.aspect=J,S.updateProjectionMatrix()},frame:(e,t)=>Ce(e,t)});if(!K){z("3D rendering is unavailable in this browser. Enable WebGL to use the 3D MacBook."),ce();return}const{renderer:T,scene:ae,invalidate:C}=K;let U=!1;const b=new r.VideoTexture(u);b.colorSpace=r.SRGBColorSpace,b.minFilter=r.LinearFilter,b.magFilter=r.LinearFilter,b.anisotropy=T.capabilities.getMaxAnisotropy();const D=new r.MeshBasicMaterial({map:b,toneMapped:!1,side:r.DoubleSide});D.onBeforeCompile=e=>{e.fragmentShader=e.fragmentShader.replace("#include <map_fragment>",`#include <map_fragment>
2
2
  if (vMapUv.x < 0.0 || vMapUv.x > 1.0 || vMapUv.y < 0.0 || vMapUv.y > 1.0) diffuseColor.rgb = vec3(0.0);`)},D.customProgramCacheKey=()=>"macbook-fitted-screen";let I=n.current.aspect,le=0,_=c.streamFit(I,I);const Re=()=>{const e=u.videoWidth&&u.videoHeight?u.videoWidth/u.videoHeight:I;_=c.streamFit(e,I,le),b.repeat.set(_.repeat[0],_.repeat[1]),b.offset.set(_.offset[0],_.offset[1])},g=new r.Group,y=new r.Group,h=new r.Group;h.rotation.x=c.lidRotation(m.current),y.add(h),g.add(y),ae.add(g);const de=[D],Y=[];let X;for(const e of c.macbookMeshes(n.current.aspect)){const t=new r.BufferGeometry,a=new r.InterleavedBuffer(e.vertices,c.MACBOOK_VERTEX_FLOATS);t.setAttribute("position",new r.InterleavedBufferAttribute(a,3,0)),t.setAttribute("normal",new r.InterleavedBufferAttribute(a,3,3)),t.setAttribute("uv",new r.InterleavedBufferAttribute(a,2,6));const s=Ne(e.kind,D),d=je[e.kind];d&&(s.polygonOffset=!0,s.polygonOffsetFactor=-d,s.polygonOffsetUnits=-d);const w=new r.Mesh(t,s);e.kind==="screen"&&(X=w),(e.part==="lid"?h:y).add(w),Y.push(t),s!==D&&Y.push(s)}const ue=new r.Box3,fe=e=>{const t=h.rotation.x;return h.rotation.x=c.lidRotation(c.MACBOOK_LID_OPEN_DEGREES),e.updateMatrixWorld(!0),ue.setFromObject(e),h.rotation.x=t,ue},pe=()=>{g.rotation.set(0,0,0),y.position.set(0,0,0),y.position.copy(fe(g).getCenter(new r.Vector3)).negate()};pe();const Ae=!!window.matchMedia?.("(prefers-reduced-motion: reduce)").matches;let Q=!1;const me=()=>{g.visible=!0,!re.current&&n.current.animateLid!==!1&&!Ae&&(m.current=0,h.rotation.x=c.lidRotation(0),Z(0),ie(c.MACBOOK_LID_OPEN_DEGREES)),re.current=!0,Q=!0,C()},Pe=async e=>{const{GLTFLoader:t}=await Promise.resolve().then(()=>require("./GLTFLoader-CfPNHfJQ.js")),{scene:a}=await r.loadModel(new t,e),s=[];if(a.traverse(l=>{if(l instanceof r.Mesh){s.push(l.geometry);for(const ge of Array.isArray(l.material)?l.material:[l.material]){s.push(ge);for(const Le of Object.values(ge))Le instanceof r.Texture&&s.push(Le)}}}),U){for(const l of s)l.dispose();return}de.push(...s);const d=a.getObjectByName("macbook-base"),w=a.getObjectByName("macbook-lid"),M=a.getObjectByName("macbook-screen");if(!d||!w||!(M instanceof r.Mesh))throw new Error("it has no macbook-base, macbook-lid or macbook-screen");for(const l of[...y.children])l!==h&&y.remove(l);h.clear(),y.add(d);for(const l of[...w.children])h.add(l);M.material=D,X=M;const A=M.userData.aspect;typeof A=="number"&&A>0&&(I=A);const E=M.userData.notch;typeof E=="number"&&E>=0&&E<.5&&(le=E);for(const l of Y.splice(0))l.dispose();pe()},ee=n.current.model;ee&&(g.visible=!1,Pe(ee).catch(e=>{U||z(`The MacBook model could not load: ${e instanceof Error?e.message:e}`)}).finally(()=>{U||me()}));const V=new r.Vector3;let O=0;const he=new r.Raycaster,ve=new r.Vector2;let i,B=N[$.current].yaw,R=N[$.current].pitch;P.current=C;const W=e=>{if(!X)return;const t=T.domElement.getBoundingClientRect();ve.set((e.clientX-t.left)/t.width*2-1,1-(e.clientY-t.top)/t.height*2),he.setFromCamera(ve,S);const a=he.intersectObject(y,!0)[0],s=a?.object===X?a.uv:void 0;return s&&c.streamPoint(s.x,s.y,_)},we=e=>{if(C(),i)return;const t=n.current.watchOnly||e.altKey?void 0:W(e);!t&&(De.current||e.button!==0)||(o.focus({preventScroll:!0}),o.setPointerCapture(e.pointerId),i={pointer:e.pointerId,kind:t?"screen":"orbit",clientX:e.clientX,clientY:e.clientY,x:t?.x??0,y:t?.y??0},t&&n.current.pointer("down",t.x,t.y,e.buttons))},Me=e=>{if(C(),!i){const t=n.current.watchOnly?void 0:W(e);T.domElement.style.cursor=t?"none":"",t&&n.current.pointer("move",t.x,t.y,0);return}if(i.pointer===e.pointerId){if(i.kind==="screen"){const t=W(e);t&&(i.x=t.x,i.y=t.y),n.current.pointer("move",i.x,i.y,e.buttons)}else Be(e.clientX-i.clientX,e.clientY-i.clientY,1.2);i.clientX=e.clientX,i.clientY=e.clientY}},L=e=>{C(),!(!i||e&&i.pointer!==e.pointerId)&&(i.kind==="screen"&&n.current.pointer("up",i.x,i.y,e?.buttons??0),i=void 0)},Ee=e=>{if(n.current.watchOnly||e.ctrlKey)return;const t=W(e);if(!t)return;e.preventDefault();const a=e.deltaMode===WheelEvent.DOM_DELTA_LINE?16:e.deltaMode===WheelEvent.DOM_DELTA_PAGE?o.clientHeight:1;n.current.scroll(t.x,t.y,e.deltaX*a,e.deltaY*a)},q=e=>e.stopPropagation(),ye=["mousedown","mousemove","mouseup","touchstart","touchmove","touchend","touchcancel"];for(const e of ye)o.addEventListener(e,q);const be=e=>e.preventDefault(),H=()=>{L(),n.current.onBlur()};o.addEventListener("pointerdown",we),o.addEventListener("pointermove",Me),o.addEventListener("pointerup",L),o.addEventListener("pointercancel",L),o.addEventListener("lostpointercapture",L),o.addEventListener("wheel",Ee,{passive:!1}),o.addEventListener("wheel",q),o.addEventListener("contextmenu",be),o.addEventListener("focusout",H),window.addEventListener("blur",H);const Ce=(e,t)=>{const a=N[$.current];let s=!1;const d=F.current;if(d){const l=d.duration>0?(e-d.start)/d.duration:1;m.current=d.from+(d.to-d.from)*c.lidEase(l),l>=1?F.current=void 0:s=!0,Z(m.current)}else m.current!==k.current&&(m.current=r.MathUtils.damp(m.current,k.current,14,t),Math.abs(m.current-k.current)<.05?m.current=k.current:s=!0);h.rotation.x=c.lidRotation(m.current);const w=a.yaw+ne.yaw,M=a.pitch+ne.pitch;B=r.MathUtils.damp(B,w,10,t),R=r.MathUtils.damp(R,M,10,t),Math.abs(B-w)<5e-4&&(B=w),Math.abs(R-M)<5e-4&&(R=M),Re(),g.rotation.set(R,B,0,"XYZ"),fe(g).getSize(V);const A=Math.tan(r.MathUtils.degToRad(Oe/2)),E=Math.max(V.y/2/A,V.x/2/(A*J))*1.12+V.z/2;return O=O?r.MathUtils.damp(O,E,10,t):E,Math.abs(O-E)<.01&&(O=E),S.position.set(0,0,O),S.lookAt(0,0,0),T.render(ae,S),Q&&(Q=!1,ce()),s||B!==w||R!==M||O!==E};return K.start(),ee||me(),()=>{U=!0,P.current=()=>{},L();for(const e of ye)o.removeEventListener(e,q);o.removeEventListener("pointerdown",we),o.removeEventListener("pointermove",Me),o.removeEventListener("pointerup",L),o.removeEventListener("pointercancel",L),o.removeEventListener("lostpointercapture",L),o.removeEventListener("wheel",Ee),o.removeEventListener("wheel",q),o.removeEventListener("contextmenu",be),o.removeEventListener("focusout",H),window.removeEventListener("blur",H);for(const e of[...de,...Y])e.dispose();b.dispose(),K.dispose()}},[v.video,v.aspect,v.model]),p.jsxs("div",{className:"rc-duo rc-macbook-3d",style:xe?void 0:{visibility:"hidden"},children:[p.jsx("div",{ref:j,className:"rc-duo-stage","data-position-locked":x,tabIndex:0,role:"application","aria-label":"MacBook running macOS. Use the screen to control the guest. Drag around the MacBook to turn it when position is unlocked.",onKeyDown:v.onKeyDown,onKeyUp:v.onKeyUp}),p.jsxs("div",{className:"rc-duo-controls",onPointerDown:o=>o.stopPropagation(),children:[p.jsxs("div",{className:"rc-duo-hinge",children:[p.jsx("button",{type:"button",className:"rc-duo-fold",onClick:()=>ie(G<45?c.MACBOOK_LID_OPEN_DEGREES:0),children:G<45?"Open":"Close"}),p.jsx("label",{htmlFor:se,children:"Lid"}),p.jsx("input",{id:se,type:"range",min:0,max:c.MACBOOK_LID_MAX_DEGREES,step:1,value:Math.round(G),onChange:o=>{const u=Number(o.target.value);F.current=void 0,k.current=u,Z(u),P.current()}}),p.jsxs("output",{children:[Math.round(G),"°"]})]}),p.jsxs("div",{className:"rc-duo-views",children:[Object.keys(N).map(o=>p.jsx("button",{type:"button","aria-pressed":oe===o,onClick:()=>{Se(o)},children:N[o].label},o)),p.jsx("button",{type:"button",className:"rc-duo-lock","aria-pressed":x,title:x?"Position is locked. The screen still controls macOS.":"Drag around the MacBook to turn it. Alt-drag turns it from the screen.",onClick:()=>_e(!x),children:x?"Position locked":"Lock position"})]})]}),te&&p.jsx("div",{role:"alert",className:"rc-duo-error",children:te})]})}exports.default=Ge;
@@ -1 +1 @@
1
- "use strict";require('./index.css');const p=require("react/jsx-runtime"),i=require("./core-_qwksEry.js"),a=require("react"),Go=require("react-dom"),Q={sideBezel:1.7,topBezel:2.4,chin:2.4,baseHeight:2.2,baseOverhang:4,screenRadius:.9,lidThickness:.7},Dt=100+2*Q.sideBezel,et=Dt+2*Q.baseOverhang,Pt=Q.topBezel+Q.chin+Q.baseHeight,qo=(Pt-2*Q.topBezel)/2,Zo=8;function Jo(d){const t=100/d,c=t+Q.topBezel+Q.chin;return{screenHeight:t,lidHeight:c,depth:c}}const Qo=Math.PI/2,en=135,tn=100,on=2400;function nn(d){return Qo-d*Math.PI/180}function rn(d){const t=Math.max(0,Math.min(1,d));return 1-Math.pow(1-t,3)}function De(d,t,c,u=6){const v=[],E=[[d/2-c.top,t/2-c.top,c.top,0],[-d/2+c.top,t/2-c.top,c.top,Math.PI/2],[-d/2+c.bottom,-t/2+c.bottom,c.bottom,Math.PI],[d/2-c.bottom,-t/2+c.bottom,c.bottom,Math.PI*1.5]];for(const[y,A,N,C]of E)for(let x=0;x<=u;x++){const R=C+x*Math.PI/2/u;v.push({x:y+N*Math.cos(R),y:A+N*Math.sin(R),nx:Math.cos(R),ny:Math.sin(R)})}return v}function sn(d){const{screenHeight:t,lidHeight:c,depth:u}=Jo(d),v=[],E=(f,O,b)=>v.push({part:f,kind:O,vertices:new Float32Array(b)}),y=(f,O,b,L,D)=>{const H=b.map(G=>G.x),z=b.map(G=>G.y),[oe,K,ae,ye]=[Math.min(...H),Math.max(...H),Math.min(...z),Math.max(...z)],le=(oe+K)/2,B=(ae+ye)/2,de=(G,Oe)=>[...L(G,Oe),...D,(G-oe)/(K-oe||1),(Oe-ae)/(ye-ae||1)],P=[];for(let G=0;G<b.length;G++){const Oe=b[G],tt=b[(G+1)%b.length];for(const Z of[de(le,B),de(Oe.x,Oe.y),de(tt.x,tt.y)])P.push(...Z)}E(f,O,P)},A=(f,O,b,L,D,H,z)=>{const oe=[];for(let K=0;K<b.length;K++){const ae=b[K],ye=b[(K+1)%b.length],le=(B,de)=>[...L(B.x,B.y,de),...D(B.nx,B.ny),0,0];for(const B of[le(ae,H),le(ye,H),le(ye,z),le(ae,H),le(ye,z),le(ae,z)])oe.push(...B)}E(f,O,oe)},N=De(Dt,c,{top:2.2,bottom:.4}),C=f=>f+c/2,x=Q.lidThickness;A("lid","shell",N,(f,O,b)=>[f,C(O),b],(f,O)=>[f,O,0],-x,0),y("lid","shell",N,(f,O)=>[f,C(O),-x],[0,0,-1]),y("lid","glass",De(Dt-.5,c-.5,{top:1.95,bottom:.2}),(f,O)=>[f,C(O),.01],[0,0,1]);const R=Q.chin;y("lid","screen",De(100,t,{top:Q.screenRadius,bottom:0}),(f,O)=>[f,R+t/2+O,.02],[0,0,1]),y("lid","camera",De(.5,.5,{top:.25,bottom:.25},4),(f,O)=>[f,c-Q.topBezel/2+O,.02],[0,0,1]);const Y=De(et,u+x,{top:3,bottom:3}),j=f=>(u-x)/2-f;A("base","shell",Y,(f,O,b)=>[f,b,j(O)],(f,O)=>[f,0,-O],-2.2,0),y("base","shell",Y,(f,O)=>[f,0,j(O)],[0,1,0]),y("base","shell",Y,(f,O)=>[f,-2.2,j(O)],[0,-1,0]);const ee=(f,O,b,L,D,H,z)=>y("base",f,De(L,D,{top:z,bottom:z},3),(oe,K)=>[O+oe,H,b-K],[0,1,0]),ge=et*.72,ce=u*.08,_=[.55,1,1,1,1,1],te=u*.4/_.reduce((f,O)=>f+O,0);ee("well",0,ce+u*.4/2,ge+1.4,u*.4+1.4,.01,.8);let U=ce;for(const[f,O]of _.entries()){const b=O*te,L=ge/14;for(let D=0;D<14;D++){if(f===5&&D>4&&D<9)continue;const H=f===5&&D===4?5:1;ee("keys",-ge/2+L*(D+H/2),U+b/2,L*H-.5,b-.5,.03,.3)}U+=b}ee("trackpad",0,u*.72,et*.4,u*.36,.01,1.2),y("base","scoop",De(14,.9,{top:0,bottom:.45},3),(f,O)=>[f,-.45+O,u+.01],[0,0,1]);const k=new Map;for(const f of v){const O=`${f.part}:${f.kind}`;k.set(O,[...k.get(O)??[],f])}return[...k.values()].map(f=>{const O=new Float32Array(f.reduce((L,D)=>L+D.vertices.length,0));let b=0;for(const L of f)O.set(L.vertices,b),b+=L.vertices.length;return{part:f[0].part,kind:f[0].kind,vertices:O}})}function cn(d,t,c=0){const u=d>=t?1:d/t,v=d>=t?t/d:1,E=(1-u)/2,y=c>0?1-v:(1-v)/2;return{repeat:[1/u,1/v],offset:[(0-E)/u,(0-y)/v]}}function an(d,t,c){const u=d*c.repeat[0]+c.offset[0],v=t*c.repeat[1]+c.offset[1],E=1e-9;if(u<-E||u>1+E||v<-E||v>1+E)return;const y=A=>Math.max(0,Math.min(1,A));return{x:y(u),y:y(1-v)}}const ln=150,dn=8;class un{constructor(t,c=()=>!1){this.send=t,this.blocked=c}send;blocked;last;gesture;screen;pointer(t,c,u){const v=t===i.MAC_INPUT_ACTION.UP&&!!this.last?.buttons;this.blocked()&&!v||(this.last={...c,buttons:u},this.send(i.createMouseControlMessage(t,c.width,c.height,c.x,c.y,u)))}scroll(t,c,u){this.blocked()||this.send(i.createMacScrollMessage(t.width,t.height,t.x,t.y,c,u))}touch(t,c,u){const v=this.gesture;if(c.length>=2){const y={x:c.reduce((A,N)=>A+N.x,0)/c.length,y:c.reduce((A,N)=>A+N.y,0)/c.length};if(v?.mode==="scroll"){const A=u.map(y.x,y.y);A&&t==="touchmove"&&this.scroll(A,(v.x-y.x)*u.scale,(v.y-y.y)*u.scale)}else v?.mode==="press"?this.lift(v,u):v?.mode==="pending"&&clearTimeout(v.timer);return this.gesture={mode:"scroll",...y},!1}const E=c[0];if(E&&t==="touchstart"&&!v)return this.blocked()||!u.contains(E.x,E.y)?!1:(this.screen=u,this.gesture={mode:"pending",x:E.x,y:E.y,timer:setTimeout(()=>this.press(),ln)},!0);if(E&&v?.mode==="pending"){if(Math.hypot(E.x-v.x,E.y-v.y)<dn)return!1;this.press()}if(E&&this.gesture?.mode==="press"){this.gesture={mode:"press",x:E.x,y:E.y};const y=u.map(E.x,E.y);return y&&this.pointer(i.MAC_INPUT_ACTION.MOVE,y,1),!1}if(c.length===0){v?.mode==="pending"&&(t==="touchcancel"?clearTimeout(v.timer):this.press());const y=this.gesture;y?.mode==="press"&&this.lift(y,u),this.gesture=void 0}return!1}release(){clearTimeout(this.gesture?.timer),this.gesture=void 0;const t=this.last;t?.buttons&&this.pointer(i.MAC_INPUT_ACTION.UP,t,0)}press(){const t=this.gesture;if(t?.mode!=="pending")return;clearTimeout(t.timer),this.gesture={mode:"press",x:t.x,y:t.y};const c=this.screen?.map(t.x,t.y);c&&this.pointer(i.MAC_INPUT_ACTION.DOWN,c,1)}lift(t,c){const u=c.map(t.x,t.y);u&&this.pointer(i.MAC_INPUT_ACTION.UP,u,0)}}function hn(d,t){return t.type==="choose"?t.mode===d.mode?d:t.mode==="3d"?{...d,mode:"3d",selection:d.selection+1}:{...d,mode:"2d"}:d.mode!=="3d"||t.selection!==d.selection||d.ready===t.selection?d:{...d,ready:t.selection}}function ho(d){const[t,c]=a.useReducer(hn,{mode:"2d",selection:0,ready:0}),u=a.useRef(t);u.current=t;const v=a.useRef(d);v.current=d;const{mode:E,selection:y,ready:A}=t,N=a.useCallback(R=>c({type:"choose",mode:R}),[]),C=a.useCallback(()=>{const R=u.current;R.mode!=="3d"||R.selection!==y||R.ready===y||(v.current?.(),c({type:"ready",selection:y}))},[y]),x=E==="3d"&&A!==y;return{mode:E,shown:E==="3d"&&!x?"3d":"2d",loading:x,choose:N,onReady:C}}function fo({view:d,label:t}){return p.jsxs("div",{className:"rc-duo-mode",role:"group","aria-label":t,children:[p.jsx("button",{type:"button","aria-pressed":d.mode==="2d",onClick:()=>d.choose("2d"),children:"2D"}),p.jsx("button",{type:"button","aria-pressed":d.mode==="3d","aria-busy":d.loading,title:d.loading?"Loading 3D":void 0,onClick:()=>d.choose("3d"),children:"3D"})]})}const fn=async d=>{if(!d)return!1;try{if(typeof navigator<"u"&&navigator.clipboard?.writeText)return await navigator.clipboard.writeText(d),!0}catch{}try{const t=document.createElement("textarea");t.value=d,t.style.position="fixed",t.style.opacity="0",document.body.appendChild(t),t.select();const c=document.execCommand("copy");return document.body.removeChild(t),c}catch{return!1}},mn=a.memo(function({element:t,screen:c,highlighted:u,selected:v,selectable:E,onClick:y}){const A=i.clampAxFrameForScreen(t.frame,c);if(!A)return null;const N=i.axElementSummary(t);return p.jsx("button",{type:"button",className:t.enabled?"rc-inspect-box":"rc-inspect-box rc-inspect-box-disabled","data-ax-id":t.id,"data-ax-path":t.path,"data-ax-label":t.label||void 0,"data-ax-role":t.role||void 0,"data-highlighted":u?"true":"false","data-selected":v?"true":"false","aria-label":N,onClick:C=>{E&&(C.preventDefault(),C.stopPropagation(),y(t,{x:C.clientX,y:C.clientY}))},style:{left:`${A.x/c.width*100}%`,top:`${A.y/c.height*100}%`,width:`${A.width/c.width*100}%`,height:`${A.height/c.height*100}%`}})},(d,t)=>d.highlighted===t.highlighted&&d.selected===t.selected&&d.selectable===t.selectable&&d.screen.width===t.screen.width&&d.screen.height===t.screen.height&&d.onClick===t.onClick&&i.axElementsEqual(d.element,t.element)),pn=260,gn=220,yn=6,vn=8,Tn=a.memo(function({element:t,platform:c,anchor:u,cursorAnchored:v,showActions:E,onTap:y}){const[A,N]=a.useState(null);a.useEffect(()=>{if(!A)return;const _=window.setTimeout(()=>N(null),1100);return()=>window.clearTimeout(_)},[A]);const C=a.useMemo(()=>{const _=pn,te=gn,U=yn,k=vn,f=typeof window<"u"?window.innerWidth:1024,O=typeof window<"u"?window.innerHeight:768,b=u.x+U+_<=f-k,L=u.y-U-te>=k;let D=b?u.x+U:u.x-U,H=L?u.y-U:u.y+U;const K=`translate(${b?"0":"-100%"}, ${L?"-100%":"0"})`;return D=Math.max(k+(b?0:_),Math.min(f-k-(b?_:0),D)),H=Math.max(k+(L?te:0),Math.min(O-k-(L?0:te),H)),{left:`${D}px`,top:`${H}px`,transform:K}},[u.x,u.y]),x=a.useMemo(()=>i.axElementSelectorExpression(t,c),[t,c]),R=c==="ios"?t.selectors.AXUniqueId:t.selectors.resourceId,Y=c==="ios"?"AXUniqueId":"resourceId",j=a.useCallback(async(_,te)=>{if(!_)return;await fn(_)&&N(te)},[]),ee=i.axElementRoleLabel(t),ge=t.label||t.value||ee,ce=i.axElementSummary(t);return Go.createPortal(p.jsxs("div",{className:"rc-inspect-card","data-cursor-anchored":v?"true":"false",style:C,onClick:_=>_.stopPropagation(),onMouseDown:_=>_.stopPropagation(),onMouseMove:_=>_.stopPropagation(),children:[p.jsxs("div",{className:"rc-inspect-card-header",children:[p.jsx("span",{className:"rc-inspect-card-role",children:ee}),!t.enabled&&p.jsx("span",{className:"rc-inspect-card-tag",children:"disabled"}),t.focused&&p.jsx("span",{className:"rc-inspect-card-tag rc-inspect-card-tag-blue",children:"focused"})]}),p.jsx("p",{className:"rc-inspect-card-title",title:ce,children:ge}),R&&p.jsxs("div",{className:"rc-inspect-card-row",children:[p.jsxs("span",{className:"rc-inspect-card-row-label",children:[Y,":"]}),p.jsx("span",{className:"rc-inspect-card-row-value",children:R})]}),t.value&&t.value!==t.label&&p.jsxs("div",{className:"rc-inspect-card-row",children:[p.jsx("span",{className:"rc-inspect-card-row-label",children:"value:"}),p.jsx("span",{className:"rc-inspect-card-row-value",children:t.value})]}),p.jsxs("div",{className:"rc-inspect-card-row",children:[p.jsx("span",{className:"rc-inspect-card-row-label",children:"frame:"}),p.jsxs("span",{className:"rc-inspect-card-row-value",children:[Math.round(t.frame.width),"×",Math.round(t.frame.height)," @ ",Math.round(t.frame.x),",",Math.round(t.frame.y)]})]}),E&&p.jsxs("div",{className:"rc-inspect-card-actions",children:[p.jsx("button",{type:"button",className:"rc-inspect-card-btn rc-inspect-card-btn-primary",disabled:!y,onClick:()=>y?.(t,u),children:"Tap"}),p.jsx("button",{type:"button",className:A==="selector"?"rc-inspect-card-btn rc-inspect-card-btn-copied":"rc-inspect-card-btn",disabled:!x,title:x??"No usable selector for this element",onClick:()=>j(x??void 0,"selector"),children:A==="selector"?"Copied!":"Copy selector"}),p.jsx("button",{type:"button",className:A==="id"?"rc-inspect-card-btn rc-inspect-card-btn-copied":"rc-inspect-card-btn",disabled:!R,title:R??`No ${Y}`,onClick:()=>j(R,"id"),children:A==="id"?"Copied!":`Copy ${Y}`})]})]}),document.body)}),On=a.memo(function({snapshot:t,geometry:c,highlightedId:u,selectedId:v,mode:E,cursorPosition:y,frozenCursorPosition:A,onSelectChange:N,onTapElement:C}){const x=E==="select",R=x?u!==null&&u!==v:u!==null,Y=x?u??v:u,j=a.useMemo(()=>{const k=new Map;if(!t)return k;for(const f of t.elements)k.set(f.id,f);return k},[t]),ee=a.useMemo(()=>Y?j.get(Y)??null:null,[Y,j]);if(!(!!t&&!!c&&t.screen.width>0&&t.screen.height>0&&t.elements.length>0))return null;const ce=R?y:A??y,_=R,te=x&&!R&&v!==null,U=k=>{x&&k.target===k.currentTarget&&N(null,null)};return p.jsxs(p.Fragment,{children:[p.jsx("div",{className:x?"rc-inspect-overlay rc-inspect-overlay-select":"rc-inspect-overlay",style:{left:`${c.left}px`,top:`${c.top}px`,width:`${c.width}px`,height:`${c.height}px`},onClick:U,children:t.elements.map(k=>p.jsx(mn,{element:k,screen:t.screen,highlighted:k.id===u,selected:k.id===v,selectable:x,onClick:N},k.id))}),ee&&ce&&p.jsx(Tn,{element:ee,platform:t.platform,anchor:ce,cursorAnchored:_,showActions:te,onTap:C})]})});function En(d,t){if(!t.startsWith("lim_st_"))return!1;try{const c=new URL(d).pathname.split("/").map(decodeURIComponent).find(C=>/^(ios|android)_[a-z0-9_]+$/.test(C));if(!c)return!1;const u=c.split("_")[0],v=t.slice(7).split(".");if(v.length!==3||v.some(C=>!C))return!1;const E=atob(v[1].replace(/-/g,"+").replace(/_/g,"/")),y=JSON.parse(new TextDecoder().decode(Uint8Array.from(E,C=>C.charCodeAt(0))));if(!y||typeof y!="object"||!("scopes"in y))return!1;const A=y.scopes;if(!Array.isArray(A)||!A.every(C=>typeof C=="string"))return!1;let N=!1;for(const C of A){const[x,R,Y,j]=C.split(":");if(!(j!==void 0||x!==u&&x!=="*")&&!(R!==c&&R!=="*")){if(Y==="stream"||Y==="all")return!1;Y==="watch"&&(N=!0)}}return N}catch{return!1}}const An=a.lazy(()=>Promise.resolve().then(()=>require("./duo-view-CKlDgO_u.js")).then(d=>d.duoView)),bn=a.lazy(()=>Promise.resolve().then(()=>require("./macbook-frame-g3h4xP5G.js"))),Tt=d=>Object.entries(i.AMOTION_EVENT).find(([c,u])=>c.startsWith("ACTION_")&&u===d)?.[0]??String(d),lo=1920,uo=1200,Mn=(d,t)=>d===lo&&t===uo||d===uo&&t===lo,Nn={ios:{videoBorderRadiusMultiplier:.15,loadingLogoSize:"20%",videoPosition:{portrait:{heightMultiplier:.9678},landscape:{widthMultiplier:.9678}}},android:{videoBorderRadiusMultiplier:.13,loadingLogoSize:"40%",videoPosition:{portrait:{heightMultiplier:.967},landscape:{widthMultiplier:.962}}},macos:{videoBorderRadiusMultiplier:0,loadingLogoSize:"10%",videoPosition:{portrait:{heightMultiplier:1},landscape:{widthMultiplier:1}}}},_n={"iphone-se":{videoBorderRadiusMultiplier:0,loadingLogoSize:"20%",videoPosition:{portrait:{heightMultiplier:667/889},landscape:{widthMultiplier:667/889}},homeButton:{offset:389/889,diameter:64/889}},"iphone-17e":{videoBorderRadiusMultiplier:47.33/452,loadingLogoSize:"20%",videoPosition:{portrait:{heightMultiplier:844/888},landscape:{widthMultiplier:844/888}}}},kt=16/10,Ot=44,wn={videoBorderRadiusMultiplier:32/1837,loadingLogoSize:"40%",videoPosition:{portrait:{heightMultiplier:2560/2798},landscape:{widthMultiplier:2560/2798}}};function In(d){const t=d.code,c=i.codeMap[t];if(!c)return i.debugWarn(`Unknown event.code: ${t}, key: ${d.key}`),null;let u=i.ANDROID_KEYS.META_NONE;const v=t>="KeyA"&&t<="KeyZ",E=d.getModifierState("CapsLock"),y=d.shiftKey;let A=y;return v&&(A=y!==E),A&&(u|=i.ANDROID_KEYS.META_SHIFT_ON),d.ctrlKey&&(u|=i.ANDROID_KEYS.META_CTRL_ON),d.altKey&&(u|=i.ANDROID_KEYS.META_ALT_ON),d.metaKey&&(u|=i.ANDROID_KEYS.META_META_ON),{keycode:c,metaState:u}}function Et(d,t){const c=Object.keys(d);return c.length===Object.keys(t).length&&c.every(u=>d[u]===t[u])}const Rn=a.forwardRef(({className:d,url:t,token:c,sessionId:u,openUrl:v,watchOnly:E=!1,showFrame:y=!0,animateLid:A=!0,deviceModel:N,duoModelUrl:C,macbookModelUrl:x,autoReconnect:R,jitterBufferTargetMs:Y,onPlaybackStats:j,onTerminated:ee,assets:ge,onConnectionStateChange:ce,inspectMode:_,onAxSnapshotChange:te,onInspectSelectionChange:U,onAxStatusChange:k,axPollIntervalMs:f,axMaxBackoffMs:O,androidElementTreeOptions:b,onCameraDemandChange:L,onCameraStats:D,onTrace:H,microphoneEnabled:z=!1,onMicrophoneStateChange:oe,speakerMuted:K=!0,onSpeakerBlocked:ae},ye)=>{const le=a.useMemo(()=>En(t,c),[t,c]),B=E||le,de=a.useRef(null),P=a.useRef(null),G=a.useRef(null),[Oe,tt]=a.useState(!1),Z=N==="iphone-duo"||Oe,ot=N==="iphone-duo"?N:void 0,nt=a.useRef(null),rt=a.useRef(null),[Lt,mo]=a.useState(null),[Yt,po]=a.useState(),[go,yo]=a.useState(!1),[vo,To]=a.useState(!1),[Oo,Eo]=a.useState(!1),[At,Ht]=a.useState(!1),[Wt,Xt]=a.useState(!1),[Ao,jt]=a.useState({}),[Kt,Vt]=a.useState(null),[bt,bo]=a.useState(null),[Bt,Mo]=a.useState(null),[$t,Ut]=a.useState(null),Ue=ho(()=>dt.current?.release()),it=a.useRef(!1),Mt=a.useRef(null),$=a.useRef(new Map),Ee=a.useRef(!1),[No,_o]=a.useState(!1),W=a.useRef(null),Pe=a.useRef(null),Fe=a.useRef({handle:()=>{},end:()=>{}}),[Ae,st]=a.useState(null),[Ft,Nt]=a.useState(null),[_t,ze]=a.useState(null),[wt,ct]=a.useState(null),[wo,zt]=a.useState(null),[Io,Gt]=a.useState(null),at=a.useRef(null),fe=a.useRef(void 0),qt=e=>{at.current=e,fe.current===void 0&&(fe.current=window.requestAnimationFrame(()=>{fe.current=void 0,Gt(at.current)}))},[Ro,Le]=a.useState(null),be=a.useRef(null);be.current=Ft;const Ye=a.useRef(U);Ye.current=U;const Me=_===!0||_==="hover-only",Zt=a.useRef(Me);Zt.current=Me;const Co=_==="hover-only"?"hover-only":"select",V=a.useMemo(()=>i.detectPlatform(t),[t]),So=a.useMemo(()=>u||Array.from(crypto.getRandomValues(new Uint32Array(4)),e=>e.toString(36)).join(""),[u]),Ge=V==="ios"&&N&&N!=="iphone-duo"?N:void 0,Ne=V==="android"&&Wt?wn:Ge?_n[Ge]:Nn[V],ne=ge?.[V],Jt=Ge&&ne?.modelFrames?.[Ge],Qt=V==="android"&&Wt?At?ne?.tabletFrameLandscape:ne?.tabletFrame:Ge?At?Jt?.frameLandscape:Jt?.frame:At?ne?.frameLandscape:ne?.frame,eo=ne?.loadingLogo,qe=!Z&&V!=="macos"&&y&&!!Qt,ue=V==="macos"&&y,_e=ue&&ne?.frame&&ne.screen?{src:ne.frame,screen:ne.screen}:void 0,It=a.useRef(null),xo=ue&&Ue.mode==="3d",we=ue&&Ue.shown==="3d";it.current=we;const to=Ue.choose;a.useEffect(()=>{ue||to("2d")},[ue,to]);const w=a.useRef(null),ie=e=>w.current?.sendControl(e),lt=a.useRef(new Set),oo=a.useRef(!1);oo.current=_===!0;const dt=a.useRef(null);dt.current||(dt.current=new un(e=>w.current?.sendControl(e),()=>oo.current));const Ie=dt.current;a.useEffect(()=>()=>Ie.release(),[Ie]);const Ze=a.useCallback(()=>{for(const e of lt.current)w.current?.sendControl(i.createMacKeyMessage(i.MAC_INPUT_ACTION.UP,e));lt.current.clear()},[]),Rt=(e,o)=>w.current?.sendDuoControl(e,o)??Promise.reject(new Error("Simulator disconnected")),no=-10,ro=(e,o)=>{const n=We();if(!n)return;const s=me(n,e,o);if(!s)return;const{videoX:r,videoY:h,videoWidth:l,videoHeight:m}=s,g=i.createTouchControlMessage(i.AMOTION_EVENT.ACTION_DOWN,no,l,m,r,h,1,i.AMOTION_EVENT.BUTTON_PRIMARY,i.AMOTION_EVENT.BUTTON_PRIMARY);g&&ie(g),window.setTimeout(()=>{const M=i.createTouchControlMessage(i.AMOTION_EVENT.ACTION_UP,no,l,m,r,h,0,i.AMOTION_EVENT.BUTTON_PRIMARY,i.AMOTION_EVENT.BUTTON_PRIMARY);M&&ie(M)},60)},ko=(e,o)=>{const n=We();if(!n||o.screen.width<=0||o.screen.height<=0)return;const s=e.frame.x+e.frame.width/2,r=e.frame.y+e.frame.height/2,h=s/o.screen.width*n.actualWidth,l=r/o.screen.height*n.actualHeight,m=n.videoRect.left+n.offsetX+h,g=n.videoRect.top+n.offsetY+l;ro(m,g)},ut=-1,ht=-2,Re=-3,He=(e,o,n,s,r,h)=>{const l=i.createTouchControlMessage(e,o,n,s,r,h,1,i.AMOTION_EVENT.BUTTON_PRIMARY,i.AMOTION_EVENT.BUTTON_PRIMARY);l&&(i.debugLog("[rc-touch] sendSingleTouch",{action:e,actionName:Tt(e),pointerId:o,x:r,y:h,video:{width:n,height:s}}),ie(l))},Ce=(e,o,n)=>{if(!n)return;const{videoX:s,videoY:r,videoWidth:h,videoHeight:l}=n;let m=null,g=null,M=1;const S=i.AMOTION_EVENT.BUTTON_PRIMARY;switch(o){case"down":e!==Re&&Fe.current.end(),m=$.current.size===0?i.AMOTION_EVENT.ACTION_DOWN:i.AMOTION_EVENT.ACTION_POINTER_DOWN,g={x:s,y:r},$.current.set(e,g),e===-1&&P.current?.focus();break;case"move":$.current.has(e)&&(m=i.AMOTION_EVENT.ACTION_MOVE,g={x:s,y:r},$.current.set(e,g));break;case"up":case"cancel":$.current.has(e)&&(g=$.current.get(e),$.current.delete(e),o==="cancel"?m=i.AMOTION_EVENT.ACTION_CANCEL:m=$.current.size===0?i.AMOTION_EVENT.ACTION_UP:i.AMOTION_EVENT.ACTION_POINTER_UP);break}if(m!==null&&g!==null){i.debugLog("[rc-touch][mouse->touch] sending",{pointerId:e,eventType:o,action:m,actionName:Tt(m),positionToSend:g,video:{width:h,height:l},altHeld:Ee.current,activePointersAfter:Array.from($.current.entries()).map(([J,X])=>({id:J,x:X.x,y:X.y}))});const T=i.createTouchControlMessage(m,e,h,l,g.x,g.y,M,S,S);T&&(i.debugLog("[rc-touch][mouse->touch] buffer",{pointerId:e,actionName:Tt(m),byteLength:T.byteLength}),ie(T))}else(o==="up"||o==="cancel")&&$.current.delete(e)},Ct=e=>{if(Ee.current!==e&&(Ee.current=e,_o(e),e||st(null),i.debugLog("[rc-touch][alt] updateAltHeld",{nextHeld:e,activePointerIds:Array.from($.current.keys())}),V==="ios"&&w.current?.getState().controlReady)){const o=e?i.ANDROID_KEYS.ACTION_DOWN:i.ANDROID_KEYS.ACTION_UP,n=i.createInjectKeycodeMessage(o,i.ANDROID_KEYS.KEYCODE_ALT_LEFT,0,i.ANDROID_KEYS.META_NONE);i.debugLog("[rc-touch][alt] sending Indigo modifier keycode",{action:o,keycode:i.ANDROID_KEYS.KEYCODE_ALT_LEFT}),n&&ie(n)}},We=()=>{const e=P.current,o=de.current;if(!e||!o)return null;const n=e.videoWidth,s=e.videoHeight;if(!n||!s)return null;const r=e.getBoundingClientRect(),h=o.getBoundingClientRect(),l=r.width,m=r.height,g=n/s,M=l/m;let S=l,T=m;g>M?T=l/g:S=m*g;const J=(l-S)/2,X=(m-T)/2;return{videoWidth:n,videoHeight:s,videoRect:r,containerRect:h,actualWidth:S,actualHeight:T,offsetX:J,offsetY:X}},me=(e,o,n)=>{const s=o-e.videoRect.left-e.offsetX,r=n-e.videoRect.top-e.offsetY,h=Math.max(0,Math.min(e.actualWidth,s)),l=Math.max(0,Math.min(e.actualHeight,r)),m=Math.max(0,Math.min(e.videoWidth,h/e.actualWidth*e.videoWidth)),g=Math.max(0,Math.min(e.videoHeight,l/e.actualHeight*e.videoHeight));return{videoX:m,videoY:g,videoWidth:e.videoWidth,videoHeight:e.videoHeight}},Do=(e,o,n)=>{const s=o-e.videoRect.left-e.offsetX,r=n-e.videoRect.top-e.offsetY,h=Math.max(0,Math.min(e.actualWidth,s)),l=Math.max(0,Math.min(e.actualHeight,r)),m=Math.max(0,Math.min(e.videoWidth,h/e.actualWidth*e.videoWidth)),g=Math.max(0,Math.min(e.videoHeight,l/e.actualHeight*e.videoHeight)),M=e.videoWidth-m,S=e.videoHeight-g,T=e.videoRect.left+e.offsetX,J=e.videoRect.top+e.offsetY,X=T-e.containerRect.left+h,q=J-e.containerRect.top+l,re=T-e.containerRect.left+(e.actualWidth-h),I=J-e.containerRect.top+(e.actualHeight-l);return{containerX:X,containerY:q,mirrorContainerX:re,mirrorContainerY:I,videoX:m,videoY:g,mirrorVideoX:M,mirrorVideoY:S,videoWidth:e.videoWidth,videoHeight:e.videoHeight}},Po=(e,o,n,s,r,h,l)=>{const m=i.createTwoFingerTouchControlMessage(e,o,n,s,r,h,l);i.debugLog("[rc-touch2] sendTwoFingerMessage (iOS)",{actionName:Tt(e),video:{width:o,height:n},p0:{x:s,y:r},p1:{x:h,y:l},byteLength:m.byteLength}),ie(m)},Xe=(e,o,n,s,r,h,l,m,g)=>{if(i.debugLog("[rc-touch2] applyTwoFingerEvent",{platform:V,eventType:e,video:{width:o,height:n},p0:{x:s,y:r,id:m},p1:{x:h,y:l,id:g}}),e==="down"&&Fe.current.end(),V==="ios"){const M=e==="down"?i.AMOTION_EVENT.ACTION_DOWN:e==="move"?i.AMOTION_EVENT.ACTION_MOVE:i.AMOTION_EVENT.ACTION_UP;Po(M,o,n,s,r,h,l)}else e==="down"?(He(i.AMOTION_EVENT.ACTION_DOWN,m,o,n,s,r),He(i.AMOTION_EVENT.ACTION_POINTER_DOWN,g,o,n,h,l)):e==="move"?(He(i.AMOTION_EVENT.ACTION_MOVE,m,o,n,s,r),He(i.AMOTION_EVENT.ACTION_MOVE,g,o,n,h,l)):(He(i.AMOTION_EVENT.ACTION_POINTER_UP,g,o,n,h,l),He(i.AMOTION_EVENT.ACTION_UP,m,o,n,s,r))},Lo=(e,o,n)=>{if(!Ee.current){Ae!==null&&st(null);return}const s=Do(e,o,n);st(s)},Yo=(e,o,n)=>{const s=be.current;if(!s||s.screen.width<=0||s.screen.height<=0)return null;const r=o-e.videoRect.left-e.offsetX,h=n-e.videoRect.top-e.offsetY;if(r<0||h<0||r>e.actualWidth||h>e.actualHeight)return null;const l=r/e.actualWidth*s.screen.width,m=h/e.actualHeight*s.screen.height;return i.axElementAtPoint(s,l,m)},Ho=e=>({map:(o,n)=>{const s=me(e,o,n);if(s)return{x:s.videoX,y:s.videoY,width:s.videoWidth,height:s.videoHeight}},contains:(o,n)=>{const s=o-e.videoRect.left-e.offsetX,r=n-e.videoRect.top-e.offsetY;return s>=0&&s<=e.actualWidth&&r>=0&&r<=e.actualHeight},scale:e.actualWidth>0?e.videoWidth/e.actualWidth:1}),ve=e=>{if(Z||it.current)return;e.preventDefault(),e.stopPropagation();const o=We();if((_===!0||_==="hover-only")&&!("touches"in e))if(e.type==="mousemove"){if(qt({x:e.clientX,y:e.clientY}),o){const s=Yo(o,e.clientX,e.clientY);ze(s?.id??null)}}else e.type==="mouseleave"&&(qt(null),ze(null));if(_!==!0){if(V==="macos"){if(!o||!w.current?.getState().controlReady)return;if("touches"in e){const l=Array.from(e.touches,m=>({x:m.clientX,y:m.clientY}));Ie.touch(e.type,l,Ho(o))&&P.current?.focus();return}const s=me(o,e.clientX,e.clientY);if(!s)return;const r=e.type==="mousedown"?i.MAC_INPUT_ACTION.DOWN:e.type==="mouseup"?i.MAC_INPUT_ACTION.UP:i.MAC_INPUT_ACTION.MOVE,h=e.type==="mouseleave"?0:e.buttons;e.type==="mousedown"&&P.current?.focus(),Ie.pointer(r,{x:s.videoX,y:s.videoY,width:s.videoWidth,height:s.videoHeight},h);return}if(!("touches"in e)&&o&&(e.type==="mousemove"?Lo(o,e.clientX,e.clientY):e.type==="mouseleave"&&st(null)),!(!w.current?.getState().controlReady||!P.current||!o))if("touches"in e){const s=e.touches,r=e.changedTouches;let h;switch(e.type){case"touchstart":h="down";break;case"touchmove":h="move";break;case"touchend":h="up";break;case"touchcancel":h="cancel";break;default:return}if(s.length===2){const l=s[0],m=s[1],g=me(o,l.clientX,l.clientY),M=me(o,m.clientX,m.clientY);if(!g||!M)return;W.current?W.current.source==="real-touch"&&(W.current.finger0={x:g.videoX,y:g.videoY},W.current.finger1={x:M.videoX,y:M.videoY},Xe("move",g.videoWidth,g.videoHeight,g.videoX,g.videoY,M.videoX,M.videoY,W.current.pointerId0,W.current.pointerId1)):(W.current={finger0:{x:g.videoX,y:g.videoY},finger1:{x:M.videoX,y:M.videoY},videoSize:{width:g.videoWidth,height:g.videoHeight},source:"real-touch",pointerId0:l.identifier,pointerId1:m.identifier},Xe("down",g.videoWidth,g.videoHeight,g.videoX,g.videoY,M.videoX,M.videoY,l.identifier,m.identifier))}else if(s.length<2&&W.current?.source==="real-touch"){const l=W.current;Xe("up",l.videoSize.width,l.videoSize.height,l.finger0.x,l.finger0.y,l.finger1.x,l.finger1.y,l.pointerId0,l.pointerId1),W.current=null;return}else{if(s.length>2)return;{const l=r[0];if(l){const m=me(o,l.clientX,l.clientY);Ce(l.identifier,h,m)}}}}else{let r=null;const h=W.current?.source==="alt-mouse";switch(e.type){case"mousedown":e.button===0&&(r="down");break;case"mousemove":(h||$.current.has(-1))&&(r="move");break;case"mouseup":e.button===0&&(r="up");break;case"mouseleave":(h||$.current.has(-1))&&(r="up");break}if(r){const l=me(o,e.clientX,e.clientY);if(!l)return;i.debugLog("[rc-touch][mouse] event",{domType:e.type,eventType:r,button:e.button,buttons:e.buttons,client:{x:e.clientX,y:e.clientY},altHeldRef:Ee.current,inTwoFingerMode:h,geometry:{videoX:l.videoX,videoY:l.videoY,videoWidth:l.videoWidth,videoHeight:l.videoHeight},activePointerIds:Array.from($.current.keys())}),Ee.current||h?Wo(r,l):Ce(-1,r,l)}}}},Wo=(e,o)=>{const{videoX:n,videoY:s,videoWidth:r,videoHeight:h}=o,l=r-n,m=h-s;if(e==="down"){W.current={finger0:{x:n,y:s},finger1:{x:l,y:m},videoSize:{width:r,height:h},source:"alt-mouse",pointerId0:ut,pointerId1:ht},P.current?.focus(),Xe("down",r,h,n,s,l,m,ut,ht);return}if(e==="move"){W.current?.source==="alt-mouse"&&(W.current.finger0={x:n,y:s},W.current.finger1={x:l,y:m},Xe("move",r,h,n,s,l,m,ut,ht));return}if(e==="up"||e==="cancel"){const g=W.current;if(g?.source==="alt-mouse"){const{finger0:M,finger1:S,videoSize:T}=g;Xe("up",T.width,T.height,M.x,M.y,S.x,S.y,ut,ht),W.current=null}return}},Xo=150,io=()=>{const e=Pe.current;e&&(window.clearTimeout(e.endTimer),Ce(Re,"up",e.pos),Pe.current=null)},jo=e=>{if(!w.current?.getState().controlReady||e.ctrlKey)return;if(V==="macos"){if(it.current)return;const I=We();if(!I)return;const Se=e.clientX-I.videoRect.left-I.offsetX,pe=e.clientY-I.videoRect.top-I.offsetY;if(Se<0||Se>I.actualWidth||pe<0||pe>I.actualHeight)return;const he=me(I,e.clientX,e.clientY);if(!he)return;e.preventDefault();const Ke=e.deltaMode===WheelEvent.DOM_DELTA_LINE?16:e.deltaMode===WheelEvent.DOM_DELTA_PAGE?I.actualHeight:1;Ie.scroll({x:he.videoX,y:he.videoY,width:he.videoWidth,height:he.videoHeight},e.deltaX*Ke,e.deltaY*Ke);return}if(Ee.current||W.current)return;const o=$.current.size;if(o>1||o===1&&!$.current.has(Re))return;const n=We();if(!n)return;const s=e.clientX-n.videoRect.left-n.offsetX,r=e.clientY-n.videoRect.top-n.offsetY;if(s<0||s>n.actualWidth||r<0||r>n.actualHeight)return;const h=me(n,e.clientX,e.clientY);if(!h)return;e.preventDefault();const l=(e.deltaMode===1?16:e.deltaMode===2?n.actualWidth:1)*(n.videoWidth/n.actualWidth),m=(e.deltaMode===1?16:e.deltaMode===2?n.actualHeight:1)*(n.videoHeight/n.actualHeight),g=-e.deltaX*l,M=-e.deltaY*m,S=I=>{window.clearTimeout(I.endTimer),I.endTimer=window.setTimeout(io,Xo)};if(g===0&&M===0){Pe.current&&S(Pe.current);return}const T=()=>({videoWidth:h.videoWidth,videoHeight:h.videoHeight,videoX:Math.abs(g)>Math.abs(M)?Math.min(Math.max(h.videoX,h.videoWidth*.2),h.videoWidth*.8):h.videoX,videoY:Math.abs(M)>=Math.abs(g)?Math.min(Math.max(h.videoY,h.videoHeight*.2),h.videoHeight*.8):h.videoY}),J=I=>({...I,videoX:Math.min(Math.max(I.videoX+g,0),I.videoWidth),videoY:Math.min(Math.max(I.videoY+M,0),I.videoHeight)});let X=Pe.current;if(X)window.clearTimeout(X.endTimer);else{const I=T();Ce(Re,"down",I),X={pos:I,endTimer:0},Pe.current=X}let q=X.pos,re=J(q);re.videoX===q.videoX&&re.videoY===q.videoY&&(Ce(Re,"up",q),q=T(),Ce(Re,"down",q),re=J(q)),Ce(Re,"move",re),X.pos=re,S(X)};a.useEffect(()=>{Fe.current={handle:jo,end:io}}),a.useEffect(()=>{const e=de.current;if(!e)return;const o=n=>Fe.current.handle(n);return e.addEventListener("wheel",o,{passive:!1}),()=>{Fe.current.end(),e.removeEventListener("wheel",o)}},[]),a.useEffect(()=>{const e=r=>{r.key==="Alt"&&Ct(!0)},o=r=>{r.key==="Alt"&&Ct(!1)},n=()=>{Ct(!1),Ze()},s=()=>{document.hidden&&Ze()};return window.addEventListener("keydown",e,!0),window.addEventListener("keyup",o,!0),window.addEventListener("blur",n),document.addEventListener("visibilitychange",s),()=>{window.removeEventListener("keydown",e,!0),window.removeEventListener("keyup",o,!0),window.removeEventListener("blur",n),document.removeEventListener("visibilitychange",s)}},[Ze]);const je=e=>{e.preventDefault(),e.stopPropagation();const o=document.activeElement===P.current||(Z||it.current)&&document.activeElement===e.currentTarget;if(i.debugLog("Keyboard event:",{type:e.type,key:e.key,keyCode:e.keyCode,code:e.code,target:e.target.tagName,focused:o}),!o){i.debugWarn("Simulator input not focused, skipping keyboard event");return}if(!w.current?.getState().controlReady){i.debugWarn("Data channel not ready for keyboard event:",w.current?.getState().connection);return}if(V==="macos"){if(e.type==="keydown"&&e.repeat)return;const s=i.macKeyCodeFor(e.code);if(s===void 0){i.debugLog(`Ignoring unmapped key for macOS: code=${e.code}`);return}e.type==="keydown"?lt.current.add(s):lt.current.delete(s),ie(i.createMacKeyMessage(e.type==="keydown"?i.MAC_INPUT_ACTION.DOWN:i.MAC_INPUT_ACTION.UP,s));return}if(e.type==="keydown"){if(e.key.toLowerCase()==="v"&&(e.metaKey||e.ctrlKey)){i.debugLog("Paste shortcut detected"),navigator.clipboard.readText().then(s=>{if(s){i.debugLog("Pasting text via SET_CLIPBOARD:",s.substring(0,20)+(s.length>20?"...":""));const r=i.createSetClipboardMessage(s,!0);ie(r)}}).catch(s=>{console.error("Failed to read clipboard contents: ",s)});return}if(e.key.toLowerCase()==="m"&&(e.metaKey||e.ctrlKey)){i.debugLog("Menu shortcut detected");const s=i.createInjectKeycodeMessage(i.ANDROID_KEYS.ACTION_DOWN,i.ANDROID_KEYS.MENU,0,i.ANDROID_KEYS.META_NONE);ie(s);const r=i.createInjectKeycodeMessage(i.ANDROID_KEYS.ACTION_UP,i.ANDROID_KEYS.MENU,0,i.ANDROID_KEYS.META_NONE);ie(r);return}}const n=In(e);if(n){const{keycode:s,metaState:r}=n,h=e.type==="keydown"?i.ANDROID_KEYS.ACTION_DOWN:i.ANDROID_KEYS.ACTION_UP;i.debugLog(`Sending Keycode: key=${e.key}, code=${s}, action=${h}, meta=${r}`);const l=i.createInjectKeycodeMessage(h,s,0,r);ie(l)}else i.debugLog(`Ignoring unhandled key event: type=${e.type}, key=${e.key}`)},Ko=e=>{e.stopPropagation(),w.current?.reconnect()},F=a.useRef({onSpeakerBlocked:ae,onAxSnapshotChange:te,onAxStatusChange:k,onCameraDemandChange:L,onCameraStats:D,onMicrophoneStateChange:oe,onTrace:H,onTerminated:ee,onConnectionStateChange:ce,onPlaybackStats:j});F.current={onSpeakerBlocked:ae,onAxSnapshotChange:te,onAxStatusChange:k,onCameraDemandChange:L,onCameraStats:D,onMicrophoneStateChange:oe,onTrace:H,onTerminated:ee,onConnectionStateChange:ce,onPlaybackStats:j};const St=!!H;a.useEffect(()=>{Mt.current=null,Ht(!1),Xt(!1),jt({}),Vt(null)},[t,ot]),a.useEffect(()=>{let e=!0;be.current!==null&&(be.current=null,Nt(null),i.safeInvoke("onAxSnapshotChange",F.current.onAxSnapshotChange,null));const o=i.createDeviceStream({url:t,token:c,sessionId:So,watchOnly:B,deviceModel:ot,autoReconnect:R,jitterBufferTargetMs:Y,openUrl:v,inspectMode:_,axPollIntervalMs:f,axMaxBackoffMs:O,androidElementTreeOptions:b,microphoneEnabled:z,speakerMuted:K,onStateChange:r=>{(r.videoReady||r.connection==="idle"||r.connection==="connecting"||r.connection==="reconnecting")&&yo(r.videoReady),To(r.connection==="failed"),Eo(r.connection==="terminated"),tt(r.duo),mo(r.duoState),po(r.duoError)},onAxSnapshotChange:r=>{e&&(Nt(h=>i.axSnapshotsEqual(h,r)?h:r),F.current.onAxSnapshotChange?.(r))},onAxStatusChange:(...r)=>F.current.onAxStatusChange?.(...r),onCameraDemandChange:(...r)=>F.current.onCameraDemandChange?.(...r),onCameraStats:D?(...r)=>F.current.onCameraStats?.(...r):void 0,onMicrophoneStateChange:(...r)=>F.current.onMicrophoneStateChange?.(...r),onSpeakerBlocked:()=>F.current.onSpeakerBlocked?.(),onTrace:St?(...r)=>F.current.onTrace?.(...r):void 0,onTerminated:()=>F.current.onTerminated?.(),onConnectionStateChange:(...r)=>F.current.onConnectionStateChange?.(...r),onPlaybackStats:j?(...r)=>F.current.onPlaybackStats?.(...r):void 0});w.current=o;const n=P.current?o.attachVideo(P.current):void 0,s=rt.current?o.attachAudio(rt.current):void 0;return o.start(),()=>{e=!1,o.dispose(),n?.(),s?.(),w.current=null}},[t,u,ot,St,B]),a.useLayoutEffect(()=>{w.current?.updateOptions({speakerMuted:K});const e=rt.current;e&&(i.cancelSpeakerRetry(e),e.muted=K,!K&&e.srcObject&&i.playSpeaker(e,()=>i.safeInvoke("onSpeakerBlocked",F.current.onSpeakerBlocked)))},[K]),a.useEffect(()=>{if(Z&&nt.current)return w.current?.attachVideo(nt.current,"inner")},[Z,t,u,ot,St,B]),a.useEffect(()=>{w.current?.updateOptions({token:c,openUrl:v,axPollIntervalMs:f,axMaxBackoffMs:O,androidElementTreeOptions:b,autoReconnect:R,jitterBufferTargetMs:Y,microphoneEnabled:z,inspectMode:_,onPlaybackStats:j?(...e)=>F.current.onPlaybackStats?.(...e):void 0,onCameraStats:D?(...e)=>F.current.onCameraStats?.(...e):void 0})},[c,R,Y,z,_,!!j,!!D,v,f,O,b]);const Je=()=>{if(!Zt.current)return;const e=We();if(!e){zt(null);return}const o={left:e.videoRect.left-e.containerRect.left+e.offsetX,top:e.videoRect.top-e.containerRect.top+e.offsetY,width:e.actualWidth,height:e.actualHeight};zt(n=>n&&n.left===o.left&&n.top===o.top&&n.width===o.width&&n.height===o.height?n:o)};a.useEffect(()=>{const e=P.current,o=G.current,n=de.current;if(!e)return;const s=S=>jt(T=>Et(T,S)?T:S),r=S=>Vt(T=>T&&S&&Et(T,S)?T:S),h=S=>bo(T=>T&&S&&Et(T,S)?T:S),l=()=>{const S=e.videoWidth>0&&e.videoHeight>0;S&&(Mt.current={width:e.videoWidth,height:e.videoHeight});const T=Mt.current,J=T?`${T.width} / ${T.height}`:void 0,X=It.current;if(_e&&n){if(Ut(T?T.width/T.height:kt),!X?.naturalWidth)return;const xe=X.naturalWidth/X.naturalHeight,ft=n.clientHeight-Ot,ke=n.clientHeight>0?Math.min(n.clientWidth,ft*xe):n.clientWidth;if(ke<=0)return;const Ve=ke/xe,Te=n.clientHeight>0?Ot/2:0,{screen:se}=_e,mt=se.notch??0,Be=se.left*ke,$e=se.top*Ve,pt=se.width*ke,gt=se.height*Ve,co=T?T.width/T.height:kt,yt=Math.min(pt,gt*co),xt=yt/co,$o=Be+(pt-yt)/2,Uo=mt>0?$e:$e+(gt-xt)/2,ao=(Qe,vt,Fo,zo)=>`translate(calc(-50% + ${Qe+Fo/2-ke/2}px), calc(-50% + ${vt+zo/2-Ve/2+Te}px))`;s({width:`${yt}px`,height:`${xt}px`,transform:ao($o,Uo,yt,xt)}),Mo(Qe=>{const vt={width:`${pt}px`,height:`${gt}px`,transform:ao(Be,$e,pt,gt)};return Qe&&Et(Qe,vt)?Qe:vt}),h({width:`${ke}px`,height:`${Ve}px`,transform:Te?`translateY(${Te}px)`:void 0}),r(null),Je();return}if(ue&&n){const xe=T?T.width/T.height:kt,ft=n.clientWidth*100/et,Ve=(n.clientHeight-Ot)/(1/xe+Pt/100),Te=n.clientHeight>0?Math.min(ft,Ve):ft;if(Te<=0)return;const se=Te/100,mt=Te/xe,Be=n.clientHeight>0?Ot/2:0,$e=`${se*Q.screenRadius}px`;s({aspectRatio:`${xe}`,width:`${Te}px`,height:`${mt}px`,borderRadius:`${$e} ${$e} 0 0`,transform:`translate(-50%, calc(-50% - ${se*qo-Be}px))`}),h({width:`${se*et}px`,height:`${mt+se*Pt}px`,transform:Be?`translateY(${Be}px)`:void 0,"--rc-macbook-unit":`${se}px`}),Ut(xe),r(null),Je();return}if(h(null),!qe||!o){s(!S&&T?{aspectRatio:J,contain:"size",containIntrinsicSize:`${T.width}px ${T.height}px`}:{}),r(null),Je();return}const q=o.clientWidth,re=o.clientHeight;if(q===0||re===0)return;const I=T?T.width>T.height:!1;Ht(I),Xt(V==="android"&&!!T&&Mn(T.width,T.height));const Se=I?Ne.videoPosition.landscape:Ne.videoPosition.portrait;let pe={aspectRatio:J};Se.heightMultiplier?(pe.height=`${re*Se.heightMultiplier}px`,pe.width="auto"):Se.widthMultiplier&&(pe.width=`${q*Se.widthMultiplier}px`,pe.height="auto"),pe.borderRadius=`${I?re*Ne.videoBorderRadiusMultiplier:q*Ne.videoBorderRadiusMultiplier}px`,s(pe);const he=Ne.homeButton,Ke=I?q:re,so=`calc(50% + ${Ke*(he?.offset??0)}px)`;r(he?{width:`${Ke*he.diameter}px`,height:`${Ke*he.diameter}px`,left:I?so:"50%",top:I?"50%":so}:null),Je()},m=new ResizeObserver(()=>{l()});o&&m.observe(o),m.observe(e),n&&m.observe(n),o&&o.addEventListener("load",l);const g=It.current;g?.addEventListener("load",l),e.addEventListener("loadedmetadata",l),e.addEventListener("resize",l);const M=()=>w.current?.bumpActivity();return e.addEventListener("resize",M),l(),()=>{m.disconnect(),e.removeEventListener("loadedmetadata",l),e.removeEventListener("resize",l),e.removeEventListener("resize",M),o&&o.removeEventListener("load",l),g?.removeEventListener("load",l)}},[Ne,qe,ue,_e?.src,we,t,N]),a.useEffect(()=>{Me?Je():(Nt(null),ze(null),ct(null),Gt(null),Le(null),at.current=null,fe.current!==void 0&&(window.cancelAnimationFrame(fe.current),fe.current=void 0))},[Me]),a.useEffect(()=>()=>{fe.current!==void 0&&(window.cancelAnimationFrame(fe.current),fe.current=void 0)},[]),a.useEffect(()=>{if(!Me)return;const e=o=>{o.key==="Escape"&&(wt||_t)&&(ct(null),ze(null),Le(null),i.safeInvoke("onInspectSelectionChange",Ye.current,null))};return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)},[Me,wt,_t]);const Vo=()=>{P.current&&P.current.focus()};a.useImperativeHandle(ye,()=>({openUrl:e=>w.current?.openUrl(e),sendKeyEvent:e=>w.current?.sendKeyEvent(e),screenshot:e=>w.current?.screenshot(e)??Promise.reject(new Error("Simulator disconnected")),terminateApp:e=>w.current?.terminateApp(e)??Promise.reject(new Error("Simulator disconnected")),reconnect:()=>w.current?.reconnect(),refreshAxTree:()=>w.current?.refreshAxTree()??Promise.reject(new Error("Simulator disconnected")),getAxSnapshot:()=>w.current?.getAxSnapshot()??null,setInspectHighlight:e=>{ze(e?.id??null)},setInspectSelection:e=>{ct(e?.id??null),Le(e?at.current:null);const o=be.current;e&&o?i.safeInvoke("onInspectSelectionChange",Ye.current,{element:e,snapshot:o}):i.safeInvoke("onInspectSelectionChange",Ye.current,null)},getAxStatus:()=>w.current?.getAxStatus()??"idle"}));const Bo=No&&Ae!==null;return p.jsxs("div",{ref:de,className:["rc-container",d].filter(Boolean).join(" "),style:{touchAction:"none"},onMouseDown:ve,onMouseMove:ve,onMouseUp:ve,onMouseLeave:ve,onTouchStart:ve,onTouchMove:ve,onTouchEnd:ve,onTouchCancel:ve,onContextMenu:V==="macos"?e=>e.preventDefault():void 0,children:[Bo&&Ae&&p.jsxs(p.Fragment,{children:[p.jsx("div",{className:"rc-touch-indicator",style:{left:`${Ae.containerX}px`,top:`${Ae.containerY}px`}}),p.jsx("div",{className:"rc-touch-indicator",style:{left:`${Ae.mirrorContainerX}px`,top:`${Ae.mirrorContainerY}px`}})]}),qe&&p.jsx("img",{ref:G,src:Qt,alt:"",className:V==="ios"?"rc-phone-frame rc-phone-frame-ios":"rc-phone-frame",draggable:!1}),_e&&!we&&Bt&&p.jsx("div",{className:"rc-macbook-screen",style:Bt,"aria-hidden":"true"}),_e&&!we&&p.jsx("img",{ref:It,src:_e.src,alt:"",className:"rc-macbook-image",style:bt??{visibility:"hidden"},draggable:!1}),ue&&!_e&&bt&&!we&&p.jsxs("div",{className:"rc-macbook",style:bt,"aria-hidden":"true",children:[p.jsx("div",{className:"rc-macbook-lid",children:p.jsx("div",{className:"rc-macbook-camera"})}),p.jsx("div",{className:"rc-macbook-base"})]}),qe&&Kt&&!B&&p.jsx("button",{type:"button",className:"rc-home-button","aria-label":"Home",title:"Home",style:Kt,onMouseDown:e=>e.stopPropagation(),onTouchStart:e=>e.stopPropagation(),onTouchEnd:e=>{e.stopPropagation(),e.preventDefault(),w.current?.pressButton("home")},onClick:e=>{e.stopPropagation(),w.current?.pressButton("home")}}),p.jsx("video",{ref:P,className:["rc-video",!qe&&!ue&&"rc-video-frameless",!go&&(V==="macos"?"rc-video-loading-desktop":"rc-video-loading")].filter(Boolean).join(" "),style:{...Ao,...Z||we?{opacity:0,width:1,height:1,pointerEvents:"none"}:{},...eo?{backgroundImage:`url("${eo}")`,backgroundRepeat:"no-repeat",backgroundPosition:"center",backgroundSize:Ne.loadingLogoSize}:{}},autoPlay:!0,playsInline:!0,muted:!0,tabIndex:Z||we?-1:0,onKeyDown:je,onKeyUp:je,onClick:Vo,onFocus:()=>{P.current&&(P.current.style.outline="none")},onBlur:()=>{P.current&&(P.current.style.outline="none"),Ze()}}),xo&&$t&&p.jsx(a.Suspense,{fallback:null,children:p.jsx(bn,{video:P.current,aspect:$t,model:x??ne?.model,animateLid:A,watchOnly:B,onReady:Ue.onReady,pointer:(e,o,n,s)=>{const r=P.current;!r?.videoWidth||!w.current?.getState().controlReady||Ie.pointer(e==="down"?i.MAC_INPUT_ACTION.DOWN:e==="up"?i.MAC_INPUT_ACTION.UP:i.MAC_INPUT_ACTION.MOVE,{x:o*r.videoWidth,y:n*r.videoHeight,width:r.videoWidth,height:r.videoHeight},s)},scroll:(e,o,n,s)=>{const r=P.current;!r?.videoWidth||!w.current?.getState().controlReady||Ie.scroll({x:e*r.videoWidth,y:o*r.videoHeight,width:r.videoWidth,height:r.videoHeight},n,s)},onKeyDown:je,onKeyUp:je,onBlur:Ze})}),ue&&p.jsx(fo,{view:Ue,label:"MacBook rendering"}),p.jsx("audio",{ref:rt,muted:!0,hidden:!0}),Z&&p.jsx("video",{ref:nt,autoPlay:!0,playsInline:!0,muted:!0,style:{position:"absolute",width:1,height:1,opacity:0,pointerEvents:"none"}}),Z&&Lt&&p.jsx(a.Suspense,{fallback:p.jsx("div",{children:"Loading iPhone Duo…"}),children:p.jsx(An,{watchOnly:B,showFrame:y,model:C??ne?.model,outer:P.current,inner:nt.current,state:Lt,setAngle:e=>Rt("setHingeAngle",{angleDegrees:e}),setOrientation:e=>Rt("setDuoOrientation",{orientation:e}),button:(e,o)=>Rt("performActions",{actions:[{type:o?"buttonDown":"buttonUp",button:e}]}),touch:(e,o,n,s)=>{w.current?.sendDisplayTouch(e,o,n,s)},onKeyDown:je,onKeyUp:je})}),Z&&Yt&&p.jsx("div",{role:"alert",className:"rc-duo-error",children:Yt}),!Z&&Me&&p.jsx(On,{snapshot:Ft,geometry:wo,highlightedId:_t,selectedId:wt,mode:Co,cursorPosition:Io,frozenCursorPosition:Ro,onSelectChange:(e,o)=>{ct(e?.id??null),e&&o?Le(o):e||Le(null);const n=be.current;e&&n?i.safeInvoke("onInspectSelectionChange",Ye.current,{element:e,snapshot:n}):i.safeInvoke("onInspectSelectionChange",Ye.current,null)},onTapElement:B?void 0:((e,o)=>{if(o){ro(o.x,o.y);return}const n=be.current;n&&ko(e,n)})}),Oo?p.jsxs("div",{className:"rc-terminated",role:"status",children:[p.jsx("div",{className:"rc-terminated-title",children:"Instance terminated"}),p.jsx("div",{className:"rc-terminated-message",children:"This instance no longer exists and can't be reconnected."})]}):vo&&p.jsx("button",{type:"button",className:"rc-retry-button",onClick:Ko,children:"Retry"})]})});exports.DeviceModeToggle=fo;exports.MACBOOK_LID_MAX_DEGREES=en;exports.MACBOOK_LID_OPENING_MS=on;exports.MACBOOK_LID_OPEN_DEGREES=tn;exports.MACBOOK_VERTEX_FLOATS=Zo;exports.RemoteControl=Rn;exports.lidEase=rn;exports.lidRotation=nn;exports.macbookMeshes=sn;exports.streamFit=cn;exports.streamPoint=an;exports.useDeviceView=ho;
1
+ "use strict";require('./index.css');const p=require("react/jsx-runtime"),i=require("./core-B3nWmNki.js"),a=require("react"),Go=require("react-dom"),Q={sideBezel:1.7,topBezel:2.4,chin:2.4,baseHeight:2.2,baseOverhang:4,screenRadius:.9,lidThickness:.7},Dt=100+2*Q.sideBezel,et=Dt+2*Q.baseOverhang,Pt=Q.topBezel+Q.chin+Q.baseHeight,qo=(Pt-2*Q.topBezel)/2,Zo=8;function Jo(d){const t=100/d,c=t+Q.topBezel+Q.chin;return{screenHeight:t,lidHeight:c,depth:c}}const Qo=Math.PI/2,en=135,tn=100,on=2400;function nn(d){return Qo-d*Math.PI/180}function rn(d){const t=Math.max(0,Math.min(1,d));return 1-Math.pow(1-t,3)}function De(d,t,c,u=6){const v=[],E=[[d/2-c.top,t/2-c.top,c.top,0],[-d/2+c.top,t/2-c.top,c.top,Math.PI/2],[-d/2+c.bottom,-t/2+c.bottom,c.bottom,Math.PI],[d/2-c.bottom,-t/2+c.bottom,c.bottom,Math.PI*1.5]];for(const[y,A,N,C]of E)for(let x=0;x<=u;x++){const R=C+x*Math.PI/2/u;v.push({x:y+N*Math.cos(R),y:A+N*Math.sin(R),nx:Math.cos(R),ny:Math.sin(R)})}return v}function sn(d){const{screenHeight:t,lidHeight:c,depth:u}=Jo(d),v=[],E=(f,O,b)=>v.push({part:f,kind:O,vertices:new Float32Array(b)}),y=(f,O,b,L,D)=>{const H=b.map(G=>G.x),z=b.map(G=>G.y),[oe,K,ae,ye]=[Math.min(...H),Math.max(...H),Math.min(...z),Math.max(...z)],le=(oe+K)/2,B=(ae+ye)/2,de=(G,Oe)=>[...L(G,Oe),...D,(G-oe)/(K-oe||1),(Oe-ae)/(ye-ae||1)],P=[];for(let G=0;G<b.length;G++){const Oe=b[G],tt=b[(G+1)%b.length];for(const Z of[de(le,B),de(Oe.x,Oe.y),de(tt.x,tt.y)])P.push(...Z)}E(f,O,P)},A=(f,O,b,L,D,H,z)=>{const oe=[];for(let K=0;K<b.length;K++){const ae=b[K],ye=b[(K+1)%b.length],le=(B,de)=>[...L(B.x,B.y,de),...D(B.nx,B.ny),0,0];for(const B of[le(ae,H),le(ye,H),le(ye,z),le(ae,H),le(ye,z),le(ae,z)])oe.push(...B)}E(f,O,oe)},N=De(Dt,c,{top:2.2,bottom:.4}),C=f=>f+c/2,x=Q.lidThickness;A("lid","shell",N,(f,O,b)=>[f,C(O),b],(f,O)=>[f,O,0],-x,0),y("lid","shell",N,(f,O)=>[f,C(O),-x],[0,0,-1]),y("lid","glass",De(Dt-.5,c-.5,{top:1.95,bottom:.2}),(f,O)=>[f,C(O),.01],[0,0,1]);const R=Q.chin;y("lid","screen",De(100,t,{top:Q.screenRadius,bottom:0}),(f,O)=>[f,R+t/2+O,.02],[0,0,1]),y("lid","camera",De(.5,.5,{top:.25,bottom:.25},4),(f,O)=>[f,c-Q.topBezel/2+O,.02],[0,0,1]);const Y=De(et,u+x,{top:3,bottom:3}),j=f=>(u-x)/2-f;A("base","shell",Y,(f,O,b)=>[f,b,j(O)],(f,O)=>[f,0,-O],-2.2,0),y("base","shell",Y,(f,O)=>[f,0,j(O)],[0,1,0]),y("base","shell",Y,(f,O)=>[f,-2.2,j(O)],[0,-1,0]);const ee=(f,O,b,L,D,H,z)=>y("base",f,De(L,D,{top:z,bottom:z},3),(oe,K)=>[O+oe,H,b-K],[0,1,0]),ge=et*.72,ce=u*.08,_=[.55,1,1,1,1,1],te=u*.4/_.reduce((f,O)=>f+O,0);ee("well",0,ce+u*.4/2,ge+1.4,u*.4+1.4,.01,.8);let U=ce;for(const[f,O]of _.entries()){const b=O*te,L=ge/14;for(let D=0;D<14;D++){if(f===5&&D>4&&D<9)continue;const H=f===5&&D===4?5:1;ee("keys",-ge/2+L*(D+H/2),U+b/2,L*H-.5,b-.5,.03,.3)}U+=b}ee("trackpad",0,u*.72,et*.4,u*.36,.01,1.2),y("base","scoop",De(14,.9,{top:0,bottom:.45},3),(f,O)=>[f,-.45+O,u+.01],[0,0,1]);const k=new Map;for(const f of v){const O=`${f.part}:${f.kind}`;k.set(O,[...k.get(O)??[],f])}return[...k.values()].map(f=>{const O=new Float32Array(f.reduce((L,D)=>L+D.vertices.length,0));let b=0;for(const L of f)O.set(L.vertices,b),b+=L.vertices.length;return{part:f[0].part,kind:f[0].kind,vertices:O}})}function cn(d,t,c=0){const u=d>=t?1:d/t,v=d>=t?t/d:1,E=(1-u)/2,y=c>0?1-v:(1-v)/2;return{repeat:[1/u,1/v],offset:[(0-E)/u,(0-y)/v]}}function an(d,t,c){const u=d*c.repeat[0]+c.offset[0],v=t*c.repeat[1]+c.offset[1],E=1e-9;if(u<-E||u>1+E||v<-E||v>1+E)return;const y=A=>Math.max(0,Math.min(1,A));return{x:y(u),y:y(1-v)}}const ln=150,dn=8;class un{constructor(t,c=()=>!1){this.send=t,this.blocked=c}send;blocked;last;gesture;screen;pointer(t,c,u){const v=t===i.MAC_INPUT_ACTION.UP&&!!this.last?.buttons;this.blocked()&&!v||(this.last={...c,buttons:u},this.send(i.createMouseControlMessage(t,c.width,c.height,c.x,c.y,u)))}scroll(t,c,u){this.blocked()||this.send(i.createMacScrollMessage(t.width,t.height,t.x,t.y,c,u))}touch(t,c,u){const v=this.gesture;if(c.length>=2){const y={x:c.reduce((A,N)=>A+N.x,0)/c.length,y:c.reduce((A,N)=>A+N.y,0)/c.length};if(v?.mode==="scroll"){const A=u.map(y.x,y.y);A&&t==="touchmove"&&this.scroll(A,(v.x-y.x)*u.scale,(v.y-y.y)*u.scale)}else v?.mode==="press"?this.lift(v,u):v?.mode==="pending"&&clearTimeout(v.timer);return this.gesture={mode:"scroll",...y},!1}const E=c[0];if(E&&t==="touchstart"&&!v)return this.blocked()||!u.contains(E.x,E.y)?!1:(this.screen=u,this.gesture={mode:"pending",x:E.x,y:E.y,timer:setTimeout(()=>this.press(),ln)},!0);if(E&&v?.mode==="pending"){if(Math.hypot(E.x-v.x,E.y-v.y)<dn)return!1;this.press()}if(E&&this.gesture?.mode==="press"){this.gesture={mode:"press",x:E.x,y:E.y};const y=u.map(E.x,E.y);return y&&this.pointer(i.MAC_INPUT_ACTION.MOVE,y,1),!1}if(c.length===0){v?.mode==="pending"&&(t==="touchcancel"?clearTimeout(v.timer):this.press());const y=this.gesture;y?.mode==="press"&&this.lift(y,u),this.gesture=void 0}return!1}release(){clearTimeout(this.gesture?.timer),this.gesture=void 0;const t=this.last;t?.buttons&&this.pointer(i.MAC_INPUT_ACTION.UP,t,0)}press(){const t=this.gesture;if(t?.mode!=="pending")return;clearTimeout(t.timer),this.gesture={mode:"press",x:t.x,y:t.y};const c=this.screen?.map(t.x,t.y);c&&this.pointer(i.MAC_INPUT_ACTION.DOWN,c,1)}lift(t,c){const u=c.map(t.x,t.y);u&&this.pointer(i.MAC_INPUT_ACTION.UP,u,0)}}function hn(d,t){return t.type==="choose"?t.mode===d.mode?d:t.mode==="3d"?{...d,mode:"3d",selection:d.selection+1}:{...d,mode:"2d"}:d.mode!=="3d"||t.selection!==d.selection||d.ready===t.selection?d:{...d,ready:t.selection}}function ho(d){const[t,c]=a.useReducer(hn,{mode:"2d",selection:0,ready:0}),u=a.useRef(t);u.current=t;const v=a.useRef(d);v.current=d;const{mode:E,selection:y,ready:A}=t,N=a.useCallback(R=>c({type:"choose",mode:R}),[]),C=a.useCallback(()=>{const R=u.current;R.mode!=="3d"||R.selection!==y||R.ready===y||(v.current?.(),c({type:"ready",selection:y}))},[y]),x=E==="3d"&&A!==y;return{mode:E,shown:E==="3d"&&!x?"3d":"2d",loading:x,choose:N,onReady:C}}function fo({view:d,label:t}){return p.jsxs("div",{className:"rc-duo-mode",role:"group","aria-label":t,children:[p.jsx("button",{type:"button","aria-pressed":d.mode==="2d",onClick:()=>d.choose("2d"),children:"2D"}),p.jsx("button",{type:"button","aria-pressed":d.mode==="3d","aria-busy":d.loading,title:d.loading?"Loading 3D":void 0,onClick:()=>d.choose("3d"),children:"3D"})]})}const fn=async d=>{if(!d)return!1;try{if(typeof navigator<"u"&&navigator.clipboard?.writeText)return await navigator.clipboard.writeText(d),!0}catch{}try{const t=document.createElement("textarea");t.value=d,t.style.position="fixed",t.style.opacity="0",document.body.appendChild(t),t.select();const c=document.execCommand("copy");return document.body.removeChild(t),c}catch{return!1}},mn=a.memo(function({element:t,screen:c,highlighted:u,selected:v,selectable:E,onClick:y}){const A=i.clampAxFrameForScreen(t.frame,c);if(!A)return null;const N=i.axElementSummary(t);return p.jsx("button",{type:"button",className:t.enabled?"rc-inspect-box":"rc-inspect-box rc-inspect-box-disabled","data-ax-id":t.id,"data-ax-path":t.path,"data-ax-label":t.label||void 0,"data-ax-role":t.role||void 0,"data-highlighted":u?"true":"false","data-selected":v?"true":"false","aria-label":N,onClick:C=>{E&&(C.preventDefault(),C.stopPropagation(),y(t,{x:C.clientX,y:C.clientY}))},style:{left:`${A.x/c.width*100}%`,top:`${A.y/c.height*100}%`,width:`${A.width/c.width*100}%`,height:`${A.height/c.height*100}%`}})},(d,t)=>d.highlighted===t.highlighted&&d.selected===t.selected&&d.selectable===t.selectable&&d.screen.width===t.screen.width&&d.screen.height===t.screen.height&&d.onClick===t.onClick&&i.axElementsEqual(d.element,t.element)),pn=260,gn=220,yn=6,vn=8,Tn=a.memo(function({element:t,platform:c,anchor:u,cursorAnchored:v,showActions:E,onTap:y}){const[A,N]=a.useState(null);a.useEffect(()=>{if(!A)return;const _=window.setTimeout(()=>N(null),1100);return()=>window.clearTimeout(_)},[A]);const C=a.useMemo(()=>{const _=pn,te=gn,U=yn,k=vn,f=typeof window<"u"?window.innerWidth:1024,O=typeof window<"u"?window.innerHeight:768,b=u.x+U+_<=f-k,L=u.y-U-te>=k;let D=b?u.x+U:u.x-U,H=L?u.y-U:u.y+U;const K=`translate(${b?"0":"-100%"}, ${L?"-100%":"0"})`;return D=Math.max(k+(b?0:_),Math.min(f-k-(b?_:0),D)),H=Math.max(k+(L?te:0),Math.min(O-k-(L?0:te),H)),{left:`${D}px`,top:`${H}px`,transform:K}},[u.x,u.y]),x=a.useMemo(()=>i.axElementSelectorExpression(t,c),[t,c]),R=c==="ios"?t.selectors.AXUniqueId:t.selectors.resourceId,Y=c==="ios"?"AXUniqueId":"resourceId",j=a.useCallback(async(_,te)=>{if(!_)return;await fn(_)&&N(te)},[]),ee=i.axElementRoleLabel(t),ge=t.label||t.value||ee,ce=i.axElementSummary(t);return Go.createPortal(p.jsxs("div",{className:"rc-inspect-card","data-cursor-anchored":v?"true":"false",style:C,onClick:_=>_.stopPropagation(),onMouseDown:_=>_.stopPropagation(),onMouseMove:_=>_.stopPropagation(),children:[p.jsxs("div",{className:"rc-inspect-card-header",children:[p.jsx("span",{className:"rc-inspect-card-role",children:ee}),!t.enabled&&p.jsx("span",{className:"rc-inspect-card-tag",children:"disabled"}),t.focused&&p.jsx("span",{className:"rc-inspect-card-tag rc-inspect-card-tag-blue",children:"focused"})]}),p.jsx("p",{className:"rc-inspect-card-title",title:ce,children:ge}),R&&p.jsxs("div",{className:"rc-inspect-card-row",children:[p.jsxs("span",{className:"rc-inspect-card-row-label",children:[Y,":"]}),p.jsx("span",{className:"rc-inspect-card-row-value",children:R})]}),t.value&&t.value!==t.label&&p.jsxs("div",{className:"rc-inspect-card-row",children:[p.jsx("span",{className:"rc-inspect-card-row-label",children:"value:"}),p.jsx("span",{className:"rc-inspect-card-row-value",children:t.value})]}),p.jsxs("div",{className:"rc-inspect-card-row",children:[p.jsx("span",{className:"rc-inspect-card-row-label",children:"frame:"}),p.jsxs("span",{className:"rc-inspect-card-row-value",children:[Math.round(t.frame.width),"×",Math.round(t.frame.height)," @ ",Math.round(t.frame.x),",",Math.round(t.frame.y)]})]}),E&&p.jsxs("div",{className:"rc-inspect-card-actions",children:[p.jsx("button",{type:"button",className:"rc-inspect-card-btn rc-inspect-card-btn-primary",disabled:!y,onClick:()=>y?.(t,u),children:"Tap"}),p.jsx("button",{type:"button",className:A==="selector"?"rc-inspect-card-btn rc-inspect-card-btn-copied":"rc-inspect-card-btn",disabled:!x,title:x??"No usable selector for this element",onClick:()=>j(x??void 0,"selector"),children:A==="selector"?"Copied!":"Copy selector"}),p.jsx("button",{type:"button",className:A==="id"?"rc-inspect-card-btn rc-inspect-card-btn-copied":"rc-inspect-card-btn",disabled:!R,title:R??`No ${Y}`,onClick:()=>j(R,"id"),children:A==="id"?"Copied!":`Copy ${Y}`})]})]}),document.body)}),On=a.memo(function({snapshot:t,geometry:c,highlightedId:u,selectedId:v,mode:E,cursorPosition:y,frozenCursorPosition:A,onSelectChange:N,onTapElement:C}){const x=E==="select",R=x?u!==null&&u!==v:u!==null,Y=x?u??v:u,j=a.useMemo(()=>{const k=new Map;if(!t)return k;for(const f of t.elements)k.set(f.id,f);return k},[t]),ee=a.useMemo(()=>Y?j.get(Y)??null:null,[Y,j]);if(!(!!t&&!!c&&t.screen.width>0&&t.screen.height>0&&t.elements.length>0))return null;const ce=R?y:A??y,_=R,te=x&&!R&&v!==null,U=k=>{x&&k.target===k.currentTarget&&N(null,null)};return p.jsxs(p.Fragment,{children:[p.jsx("div",{className:x?"rc-inspect-overlay rc-inspect-overlay-select":"rc-inspect-overlay",style:{left:`${c.left}px`,top:`${c.top}px`,width:`${c.width}px`,height:`${c.height}px`},onClick:U,children:t.elements.map(k=>p.jsx(mn,{element:k,screen:t.screen,highlighted:k.id===u,selected:k.id===v,selectable:x,onClick:N},k.id))}),ee&&ce&&p.jsx(Tn,{element:ee,platform:t.platform,anchor:ce,cursorAnchored:_,showActions:te,onTap:C})]})});function En(d,t){if(!t.startsWith("lim_st_"))return!1;try{const c=new URL(d).pathname.split("/").map(decodeURIComponent).find(C=>/^(ios|android)_[a-z0-9_]+$/.test(C));if(!c)return!1;const u=c.split("_")[0],v=t.slice(7).split(".");if(v.length!==3||v.some(C=>!C))return!1;const E=atob(v[1].replace(/-/g,"+").replace(/_/g,"/")),y=JSON.parse(new TextDecoder().decode(Uint8Array.from(E,C=>C.charCodeAt(0))));if(!y||typeof y!="object"||!("scopes"in y))return!1;const A=y.scopes;if(!Array.isArray(A)||!A.every(C=>typeof C=="string"))return!1;let N=!1;for(const C of A){const[x,R,Y,j]=C.split(":");if(!(j!==void 0||x!==u&&x!=="*")&&!(R!==c&&R!=="*")){if(Y==="stream"||Y==="all")return!1;Y==="watch"&&(N=!0)}}return N}catch{return!1}}const An=a.lazy(()=>Promise.resolve().then(()=>require("./duo-view-DbnkRRU-.js")).then(d=>d.duoView)),bn=a.lazy(()=>Promise.resolve().then(()=>require("./macbook-frame-DASJ960L.js"))),Tt=d=>Object.entries(i.AMOTION_EVENT).find(([c,u])=>c.startsWith("ACTION_")&&u===d)?.[0]??String(d),lo=1920,uo=1200,Mn=(d,t)=>d===lo&&t===uo||d===uo&&t===lo,Nn={ios:{videoBorderRadiusMultiplier:.15,loadingLogoSize:"20%",videoPosition:{portrait:{heightMultiplier:.9678},landscape:{widthMultiplier:.9678}}},android:{videoBorderRadiusMultiplier:.13,loadingLogoSize:"40%",videoPosition:{portrait:{heightMultiplier:.967},landscape:{widthMultiplier:.962}}},macos:{videoBorderRadiusMultiplier:0,loadingLogoSize:"10%",videoPosition:{portrait:{heightMultiplier:1},landscape:{widthMultiplier:1}}}},_n={"iphone-se":{videoBorderRadiusMultiplier:0,loadingLogoSize:"20%",videoPosition:{portrait:{heightMultiplier:667/889},landscape:{widthMultiplier:667/889}},homeButton:{offset:389/889,diameter:64/889}},"iphone-17e":{videoBorderRadiusMultiplier:47.33/452,loadingLogoSize:"20%",videoPosition:{portrait:{heightMultiplier:844/888},landscape:{widthMultiplier:844/888}}}},kt=16/10,Ot=44,wn={videoBorderRadiusMultiplier:32/1837,loadingLogoSize:"40%",videoPosition:{portrait:{heightMultiplier:2560/2798},landscape:{widthMultiplier:2560/2798}}};function In(d){const t=d.code,c=i.codeMap[t];if(!c)return i.debugWarn(`Unknown event.code: ${t}, key: ${d.key}`),null;let u=i.ANDROID_KEYS.META_NONE;const v=t>="KeyA"&&t<="KeyZ",E=d.getModifierState("CapsLock"),y=d.shiftKey;let A=y;return v&&(A=y!==E),A&&(u|=i.ANDROID_KEYS.META_SHIFT_ON),d.ctrlKey&&(u|=i.ANDROID_KEYS.META_CTRL_ON),d.altKey&&(u|=i.ANDROID_KEYS.META_ALT_ON),d.metaKey&&(u|=i.ANDROID_KEYS.META_META_ON),{keycode:c,metaState:u}}function Et(d,t){const c=Object.keys(d);return c.length===Object.keys(t).length&&c.every(u=>d[u]===t[u])}const Rn=a.forwardRef(({className:d,url:t,token:c,sessionId:u,openUrl:v,watchOnly:E=!1,showFrame:y=!0,animateLid:A=!0,deviceModel:N,duoModelUrl:C,macbookModelUrl:x,autoReconnect:R,jitterBufferTargetMs:Y,onPlaybackStats:j,onTerminated:ee,assets:ge,onConnectionStateChange:ce,inspectMode:_,onAxSnapshotChange:te,onInspectSelectionChange:U,onAxStatusChange:k,axPollIntervalMs:f,axMaxBackoffMs:O,androidElementTreeOptions:b,onCameraDemandChange:L,onCameraStats:D,onTrace:H,microphoneEnabled:z=!1,onMicrophoneStateChange:oe,speakerMuted:K=!0,onSpeakerBlocked:ae},ye)=>{const le=a.useMemo(()=>En(t,c),[t,c]),B=E||le,de=a.useRef(null),P=a.useRef(null),G=a.useRef(null),[Oe,tt]=a.useState(!1),Z=N==="iphone-duo"||Oe,ot=N==="iphone-duo"?N:void 0,nt=a.useRef(null),rt=a.useRef(null),[Lt,mo]=a.useState(null),[Yt,po]=a.useState(),[go,yo]=a.useState(!1),[vo,To]=a.useState(!1),[Oo,Eo]=a.useState(!1),[At,Ht]=a.useState(!1),[Wt,Xt]=a.useState(!1),[Ao,jt]=a.useState({}),[Kt,Vt]=a.useState(null),[bt,bo]=a.useState(null),[Bt,Mo]=a.useState(null),[$t,Ut]=a.useState(null),Ue=ho(()=>dt.current?.release()),it=a.useRef(!1),Mt=a.useRef(null),$=a.useRef(new Map),Ee=a.useRef(!1),[No,_o]=a.useState(!1),W=a.useRef(null),Pe=a.useRef(null),Fe=a.useRef({handle:()=>{},end:()=>{}}),[Ae,st]=a.useState(null),[Ft,Nt]=a.useState(null),[_t,ze]=a.useState(null),[wt,ct]=a.useState(null),[wo,zt]=a.useState(null),[Io,Gt]=a.useState(null),at=a.useRef(null),fe=a.useRef(void 0),qt=e=>{at.current=e,fe.current===void 0&&(fe.current=window.requestAnimationFrame(()=>{fe.current=void 0,Gt(at.current)}))},[Ro,Le]=a.useState(null),be=a.useRef(null);be.current=Ft;const Ye=a.useRef(U);Ye.current=U;const Me=_===!0||_==="hover-only",Zt=a.useRef(Me);Zt.current=Me;const Co=_==="hover-only"?"hover-only":"select",V=a.useMemo(()=>i.detectPlatform(t),[t]),So=a.useMemo(()=>u||Array.from(crypto.getRandomValues(new Uint32Array(4)),e=>e.toString(36)).join(""),[u]),Ge=V==="ios"&&N&&N!=="iphone-duo"?N:void 0,Ne=V==="android"&&Wt?wn:Ge?_n[Ge]:Nn[V],ne=ge?.[V],Jt=Ge&&ne?.modelFrames?.[Ge],Qt=V==="android"&&Wt?At?ne?.tabletFrameLandscape:ne?.tabletFrame:Ge?At?Jt?.frameLandscape:Jt?.frame:At?ne?.frameLandscape:ne?.frame,eo=ne?.loadingLogo,qe=!Z&&V!=="macos"&&y&&!!Qt,ue=V==="macos"&&y,_e=ue&&ne?.frame&&ne.screen?{src:ne.frame,screen:ne.screen}:void 0,It=a.useRef(null),xo=ue&&Ue.mode==="3d",we=ue&&Ue.shown==="3d";it.current=we;const to=Ue.choose;a.useEffect(()=>{ue||to("2d")},[ue,to]);const w=a.useRef(null),ie=e=>w.current?.sendControl(e),lt=a.useRef(new Set),oo=a.useRef(!1);oo.current=_===!0;const dt=a.useRef(null);dt.current||(dt.current=new un(e=>w.current?.sendControl(e),()=>oo.current));const Ie=dt.current;a.useEffect(()=>()=>Ie.release(),[Ie]);const Ze=a.useCallback(()=>{for(const e of lt.current)w.current?.sendControl(i.createMacKeyMessage(i.MAC_INPUT_ACTION.UP,e));lt.current.clear()},[]),Rt=(e,o)=>w.current?.sendDuoControl(e,o)??Promise.reject(new Error("Simulator disconnected")),no=-10,ro=(e,o)=>{const n=We();if(!n)return;const s=me(n,e,o);if(!s)return;const{videoX:r,videoY:h,videoWidth:l,videoHeight:m}=s,g=i.createTouchControlMessage(i.AMOTION_EVENT.ACTION_DOWN,no,l,m,r,h,1,i.AMOTION_EVENT.BUTTON_PRIMARY,i.AMOTION_EVENT.BUTTON_PRIMARY);g&&ie(g),window.setTimeout(()=>{const M=i.createTouchControlMessage(i.AMOTION_EVENT.ACTION_UP,no,l,m,r,h,0,i.AMOTION_EVENT.BUTTON_PRIMARY,i.AMOTION_EVENT.BUTTON_PRIMARY);M&&ie(M)},60)},ko=(e,o)=>{const n=We();if(!n||o.screen.width<=0||o.screen.height<=0)return;const s=e.frame.x+e.frame.width/2,r=e.frame.y+e.frame.height/2,h=s/o.screen.width*n.actualWidth,l=r/o.screen.height*n.actualHeight,m=n.videoRect.left+n.offsetX+h,g=n.videoRect.top+n.offsetY+l;ro(m,g)},ut=-1,ht=-2,Re=-3,He=(e,o,n,s,r,h)=>{const l=i.createTouchControlMessage(e,o,n,s,r,h,1,i.AMOTION_EVENT.BUTTON_PRIMARY,i.AMOTION_EVENT.BUTTON_PRIMARY);l&&(i.debugLog("[rc-touch] sendSingleTouch",{action:e,actionName:Tt(e),pointerId:o,x:r,y:h,video:{width:n,height:s}}),ie(l))},Ce=(e,o,n)=>{if(!n)return;const{videoX:s,videoY:r,videoWidth:h,videoHeight:l}=n;let m=null,g=null,M=1;const S=i.AMOTION_EVENT.BUTTON_PRIMARY;switch(o){case"down":e!==Re&&Fe.current.end(),m=$.current.size===0?i.AMOTION_EVENT.ACTION_DOWN:i.AMOTION_EVENT.ACTION_POINTER_DOWN,g={x:s,y:r},$.current.set(e,g),e===-1&&P.current?.focus();break;case"move":$.current.has(e)&&(m=i.AMOTION_EVENT.ACTION_MOVE,g={x:s,y:r},$.current.set(e,g));break;case"up":case"cancel":$.current.has(e)&&(g=$.current.get(e),$.current.delete(e),o==="cancel"?m=i.AMOTION_EVENT.ACTION_CANCEL:m=$.current.size===0?i.AMOTION_EVENT.ACTION_UP:i.AMOTION_EVENT.ACTION_POINTER_UP);break}if(m!==null&&g!==null){i.debugLog("[rc-touch][mouse->touch] sending",{pointerId:e,eventType:o,action:m,actionName:Tt(m),positionToSend:g,video:{width:h,height:l},altHeld:Ee.current,activePointersAfter:Array.from($.current.entries()).map(([J,X])=>({id:J,x:X.x,y:X.y}))});const T=i.createTouchControlMessage(m,e,h,l,g.x,g.y,M,S,S);T&&(i.debugLog("[rc-touch][mouse->touch] buffer",{pointerId:e,actionName:Tt(m),byteLength:T.byteLength}),ie(T))}else(o==="up"||o==="cancel")&&$.current.delete(e)},Ct=e=>{if(Ee.current!==e&&(Ee.current=e,_o(e),e||st(null),i.debugLog("[rc-touch][alt] updateAltHeld",{nextHeld:e,activePointerIds:Array.from($.current.keys())}),V==="ios"&&w.current?.getState().controlReady)){const o=e?i.ANDROID_KEYS.ACTION_DOWN:i.ANDROID_KEYS.ACTION_UP,n=i.createInjectKeycodeMessage(o,i.ANDROID_KEYS.KEYCODE_ALT_LEFT,0,i.ANDROID_KEYS.META_NONE);i.debugLog("[rc-touch][alt] sending Indigo modifier keycode",{action:o,keycode:i.ANDROID_KEYS.KEYCODE_ALT_LEFT}),n&&ie(n)}},We=()=>{const e=P.current,o=de.current;if(!e||!o)return null;const n=e.videoWidth,s=e.videoHeight;if(!n||!s)return null;const r=e.getBoundingClientRect(),h=o.getBoundingClientRect(),l=r.width,m=r.height,g=n/s,M=l/m;let S=l,T=m;g>M?T=l/g:S=m*g;const J=(l-S)/2,X=(m-T)/2;return{videoWidth:n,videoHeight:s,videoRect:r,containerRect:h,actualWidth:S,actualHeight:T,offsetX:J,offsetY:X}},me=(e,o,n)=>{const s=o-e.videoRect.left-e.offsetX,r=n-e.videoRect.top-e.offsetY,h=Math.max(0,Math.min(e.actualWidth,s)),l=Math.max(0,Math.min(e.actualHeight,r)),m=Math.max(0,Math.min(e.videoWidth,h/e.actualWidth*e.videoWidth)),g=Math.max(0,Math.min(e.videoHeight,l/e.actualHeight*e.videoHeight));return{videoX:m,videoY:g,videoWidth:e.videoWidth,videoHeight:e.videoHeight}},Do=(e,o,n)=>{const s=o-e.videoRect.left-e.offsetX,r=n-e.videoRect.top-e.offsetY,h=Math.max(0,Math.min(e.actualWidth,s)),l=Math.max(0,Math.min(e.actualHeight,r)),m=Math.max(0,Math.min(e.videoWidth,h/e.actualWidth*e.videoWidth)),g=Math.max(0,Math.min(e.videoHeight,l/e.actualHeight*e.videoHeight)),M=e.videoWidth-m,S=e.videoHeight-g,T=e.videoRect.left+e.offsetX,J=e.videoRect.top+e.offsetY,X=T-e.containerRect.left+h,q=J-e.containerRect.top+l,re=T-e.containerRect.left+(e.actualWidth-h),I=J-e.containerRect.top+(e.actualHeight-l);return{containerX:X,containerY:q,mirrorContainerX:re,mirrorContainerY:I,videoX:m,videoY:g,mirrorVideoX:M,mirrorVideoY:S,videoWidth:e.videoWidth,videoHeight:e.videoHeight}},Po=(e,o,n,s,r,h,l)=>{const m=i.createTwoFingerTouchControlMessage(e,o,n,s,r,h,l);i.debugLog("[rc-touch2] sendTwoFingerMessage (iOS)",{actionName:Tt(e),video:{width:o,height:n},p0:{x:s,y:r},p1:{x:h,y:l},byteLength:m.byteLength}),ie(m)},Xe=(e,o,n,s,r,h,l,m,g)=>{if(i.debugLog("[rc-touch2] applyTwoFingerEvent",{platform:V,eventType:e,video:{width:o,height:n},p0:{x:s,y:r,id:m},p1:{x:h,y:l,id:g}}),e==="down"&&Fe.current.end(),V==="ios"){const M=e==="down"?i.AMOTION_EVENT.ACTION_DOWN:e==="move"?i.AMOTION_EVENT.ACTION_MOVE:i.AMOTION_EVENT.ACTION_UP;Po(M,o,n,s,r,h,l)}else e==="down"?(He(i.AMOTION_EVENT.ACTION_DOWN,m,o,n,s,r),He(i.AMOTION_EVENT.ACTION_POINTER_DOWN,g,o,n,h,l)):e==="move"?(He(i.AMOTION_EVENT.ACTION_MOVE,m,o,n,s,r),He(i.AMOTION_EVENT.ACTION_MOVE,g,o,n,h,l)):(He(i.AMOTION_EVENT.ACTION_POINTER_UP,g,o,n,h,l),He(i.AMOTION_EVENT.ACTION_UP,m,o,n,s,r))},Lo=(e,o,n)=>{if(!Ee.current){Ae!==null&&st(null);return}const s=Do(e,o,n);st(s)},Yo=(e,o,n)=>{const s=be.current;if(!s||s.screen.width<=0||s.screen.height<=0)return null;const r=o-e.videoRect.left-e.offsetX,h=n-e.videoRect.top-e.offsetY;if(r<0||h<0||r>e.actualWidth||h>e.actualHeight)return null;const l=r/e.actualWidth*s.screen.width,m=h/e.actualHeight*s.screen.height;return i.axElementAtPoint(s,l,m)},Ho=e=>({map:(o,n)=>{const s=me(e,o,n);if(s)return{x:s.videoX,y:s.videoY,width:s.videoWidth,height:s.videoHeight}},contains:(o,n)=>{const s=o-e.videoRect.left-e.offsetX,r=n-e.videoRect.top-e.offsetY;return s>=0&&s<=e.actualWidth&&r>=0&&r<=e.actualHeight},scale:e.actualWidth>0?e.videoWidth/e.actualWidth:1}),ve=e=>{if(Z||it.current)return;e.preventDefault(),e.stopPropagation();const o=We();if((_===!0||_==="hover-only")&&!("touches"in e))if(e.type==="mousemove"){if(qt({x:e.clientX,y:e.clientY}),o){const s=Yo(o,e.clientX,e.clientY);ze(s?.id??null)}}else e.type==="mouseleave"&&(qt(null),ze(null));if(_!==!0){if(V==="macos"){if(!o||!w.current?.getState().controlReady)return;if("touches"in e){const l=Array.from(e.touches,m=>({x:m.clientX,y:m.clientY}));Ie.touch(e.type,l,Ho(o))&&P.current?.focus();return}const s=me(o,e.clientX,e.clientY);if(!s)return;const r=e.type==="mousedown"?i.MAC_INPUT_ACTION.DOWN:e.type==="mouseup"?i.MAC_INPUT_ACTION.UP:i.MAC_INPUT_ACTION.MOVE,h=e.type==="mouseleave"?0:e.buttons;e.type==="mousedown"&&P.current?.focus(),Ie.pointer(r,{x:s.videoX,y:s.videoY,width:s.videoWidth,height:s.videoHeight},h);return}if(!("touches"in e)&&o&&(e.type==="mousemove"?Lo(o,e.clientX,e.clientY):e.type==="mouseleave"&&st(null)),!(!w.current?.getState().controlReady||!P.current||!o))if("touches"in e){const s=e.touches,r=e.changedTouches;let h;switch(e.type){case"touchstart":h="down";break;case"touchmove":h="move";break;case"touchend":h="up";break;case"touchcancel":h="cancel";break;default:return}if(s.length===2){const l=s[0],m=s[1],g=me(o,l.clientX,l.clientY),M=me(o,m.clientX,m.clientY);if(!g||!M)return;W.current?W.current.source==="real-touch"&&(W.current.finger0={x:g.videoX,y:g.videoY},W.current.finger1={x:M.videoX,y:M.videoY},Xe("move",g.videoWidth,g.videoHeight,g.videoX,g.videoY,M.videoX,M.videoY,W.current.pointerId0,W.current.pointerId1)):(W.current={finger0:{x:g.videoX,y:g.videoY},finger1:{x:M.videoX,y:M.videoY},videoSize:{width:g.videoWidth,height:g.videoHeight},source:"real-touch",pointerId0:l.identifier,pointerId1:m.identifier},Xe("down",g.videoWidth,g.videoHeight,g.videoX,g.videoY,M.videoX,M.videoY,l.identifier,m.identifier))}else if(s.length<2&&W.current?.source==="real-touch"){const l=W.current;Xe("up",l.videoSize.width,l.videoSize.height,l.finger0.x,l.finger0.y,l.finger1.x,l.finger1.y,l.pointerId0,l.pointerId1),W.current=null;return}else{if(s.length>2)return;{const l=r[0];if(l){const m=me(o,l.clientX,l.clientY);Ce(l.identifier,h,m)}}}}else{let r=null;const h=W.current?.source==="alt-mouse";switch(e.type){case"mousedown":e.button===0&&(r="down");break;case"mousemove":(h||$.current.has(-1))&&(r="move");break;case"mouseup":e.button===0&&(r="up");break;case"mouseleave":(h||$.current.has(-1))&&(r="up");break}if(r){const l=me(o,e.clientX,e.clientY);if(!l)return;i.debugLog("[rc-touch][mouse] event",{domType:e.type,eventType:r,button:e.button,buttons:e.buttons,client:{x:e.clientX,y:e.clientY},altHeldRef:Ee.current,inTwoFingerMode:h,geometry:{videoX:l.videoX,videoY:l.videoY,videoWidth:l.videoWidth,videoHeight:l.videoHeight},activePointerIds:Array.from($.current.keys())}),Ee.current||h?Wo(r,l):Ce(-1,r,l)}}}},Wo=(e,o)=>{const{videoX:n,videoY:s,videoWidth:r,videoHeight:h}=o,l=r-n,m=h-s;if(e==="down"){W.current={finger0:{x:n,y:s},finger1:{x:l,y:m},videoSize:{width:r,height:h},source:"alt-mouse",pointerId0:ut,pointerId1:ht},P.current?.focus(),Xe("down",r,h,n,s,l,m,ut,ht);return}if(e==="move"){W.current?.source==="alt-mouse"&&(W.current.finger0={x:n,y:s},W.current.finger1={x:l,y:m},Xe("move",r,h,n,s,l,m,ut,ht));return}if(e==="up"||e==="cancel"){const g=W.current;if(g?.source==="alt-mouse"){const{finger0:M,finger1:S,videoSize:T}=g;Xe("up",T.width,T.height,M.x,M.y,S.x,S.y,ut,ht),W.current=null}return}},Xo=150,io=()=>{const e=Pe.current;e&&(window.clearTimeout(e.endTimer),Ce(Re,"up",e.pos),Pe.current=null)},jo=e=>{if(!w.current?.getState().controlReady||e.ctrlKey)return;if(V==="macos"){if(it.current)return;const I=We();if(!I)return;const Se=e.clientX-I.videoRect.left-I.offsetX,pe=e.clientY-I.videoRect.top-I.offsetY;if(Se<0||Se>I.actualWidth||pe<0||pe>I.actualHeight)return;const he=me(I,e.clientX,e.clientY);if(!he)return;e.preventDefault();const Ke=e.deltaMode===WheelEvent.DOM_DELTA_LINE?16:e.deltaMode===WheelEvent.DOM_DELTA_PAGE?I.actualHeight:1;Ie.scroll({x:he.videoX,y:he.videoY,width:he.videoWidth,height:he.videoHeight},e.deltaX*Ke,e.deltaY*Ke);return}if(Ee.current||W.current)return;const o=$.current.size;if(o>1||o===1&&!$.current.has(Re))return;const n=We();if(!n)return;const s=e.clientX-n.videoRect.left-n.offsetX,r=e.clientY-n.videoRect.top-n.offsetY;if(s<0||s>n.actualWidth||r<0||r>n.actualHeight)return;const h=me(n,e.clientX,e.clientY);if(!h)return;e.preventDefault();const l=(e.deltaMode===1?16:e.deltaMode===2?n.actualWidth:1)*(n.videoWidth/n.actualWidth),m=(e.deltaMode===1?16:e.deltaMode===2?n.actualHeight:1)*(n.videoHeight/n.actualHeight),g=-e.deltaX*l,M=-e.deltaY*m,S=I=>{window.clearTimeout(I.endTimer),I.endTimer=window.setTimeout(io,Xo)};if(g===0&&M===0){Pe.current&&S(Pe.current);return}const T=()=>({videoWidth:h.videoWidth,videoHeight:h.videoHeight,videoX:Math.abs(g)>Math.abs(M)?Math.min(Math.max(h.videoX,h.videoWidth*.2),h.videoWidth*.8):h.videoX,videoY:Math.abs(M)>=Math.abs(g)?Math.min(Math.max(h.videoY,h.videoHeight*.2),h.videoHeight*.8):h.videoY}),J=I=>({...I,videoX:Math.min(Math.max(I.videoX+g,0),I.videoWidth),videoY:Math.min(Math.max(I.videoY+M,0),I.videoHeight)});let X=Pe.current;if(X)window.clearTimeout(X.endTimer);else{const I=T();Ce(Re,"down",I),X={pos:I,endTimer:0},Pe.current=X}let q=X.pos,re=J(q);re.videoX===q.videoX&&re.videoY===q.videoY&&(Ce(Re,"up",q),q=T(),Ce(Re,"down",q),re=J(q)),Ce(Re,"move",re),X.pos=re,S(X)};a.useEffect(()=>{Fe.current={handle:jo,end:io}}),a.useEffect(()=>{const e=de.current;if(!e)return;const o=n=>Fe.current.handle(n);return e.addEventListener("wheel",o,{passive:!1}),()=>{Fe.current.end(),e.removeEventListener("wheel",o)}},[]),a.useEffect(()=>{const e=r=>{r.key==="Alt"&&Ct(!0)},o=r=>{r.key==="Alt"&&Ct(!1)},n=()=>{Ct(!1),Ze()},s=()=>{document.hidden&&Ze()};return window.addEventListener("keydown",e,!0),window.addEventListener("keyup",o,!0),window.addEventListener("blur",n),document.addEventListener("visibilitychange",s),()=>{window.removeEventListener("keydown",e,!0),window.removeEventListener("keyup",o,!0),window.removeEventListener("blur",n),document.removeEventListener("visibilitychange",s)}},[Ze]);const je=e=>{e.preventDefault(),e.stopPropagation();const o=document.activeElement===P.current||(Z||it.current)&&document.activeElement===e.currentTarget;if(i.debugLog("Keyboard event:",{type:e.type,key:e.key,keyCode:e.keyCode,code:e.code,target:e.target.tagName,focused:o}),!o){i.debugWarn("Simulator input not focused, skipping keyboard event");return}if(!w.current?.getState().controlReady){i.debugWarn("Data channel not ready for keyboard event:",w.current?.getState().connection);return}if(V==="macos"){if(e.type==="keydown"&&e.repeat)return;const s=i.macKeyCodeFor(e.code);if(s===void 0){i.debugLog(`Ignoring unmapped key for macOS: code=${e.code}`);return}e.type==="keydown"?lt.current.add(s):lt.current.delete(s),ie(i.createMacKeyMessage(e.type==="keydown"?i.MAC_INPUT_ACTION.DOWN:i.MAC_INPUT_ACTION.UP,s));return}if(e.type==="keydown"){if(e.key.toLowerCase()==="v"&&(e.metaKey||e.ctrlKey)){i.debugLog("Paste shortcut detected"),navigator.clipboard.readText().then(s=>{if(s){i.debugLog("Pasting text via SET_CLIPBOARD:",s.substring(0,20)+(s.length>20?"...":""));const r=i.createSetClipboardMessage(s,!0);ie(r)}}).catch(s=>{console.error("Failed to read clipboard contents: ",s)});return}if(e.key.toLowerCase()==="m"&&(e.metaKey||e.ctrlKey)){i.debugLog("Menu shortcut detected");const s=i.createInjectKeycodeMessage(i.ANDROID_KEYS.ACTION_DOWN,i.ANDROID_KEYS.MENU,0,i.ANDROID_KEYS.META_NONE);ie(s);const r=i.createInjectKeycodeMessage(i.ANDROID_KEYS.ACTION_UP,i.ANDROID_KEYS.MENU,0,i.ANDROID_KEYS.META_NONE);ie(r);return}}const n=In(e);if(n){const{keycode:s,metaState:r}=n,h=e.type==="keydown"?i.ANDROID_KEYS.ACTION_DOWN:i.ANDROID_KEYS.ACTION_UP;i.debugLog(`Sending Keycode: key=${e.key}, code=${s}, action=${h}, meta=${r}`);const l=i.createInjectKeycodeMessage(h,s,0,r);ie(l)}else i.debugLog(`Ignoring unhandled key event: type=${e.type}, key=${e.key}`)},Ko=e=>{e.stopPropagation(),w.current?.reconnect()},F=a.useRef({onSpeakerBlocked:ae,onAxSnapshotChange:te,onAxStatusChange:k,onCameraDemandChange:L,onCameraStats:D,onMicrophoneStateChange:oe,onTrace:H,onTerminated:ee,onConnectionStateChange:ce,onPlaybackStats:j});F.current={onSpeakerBlocked:ae,onAxSnapshotChange:te,onAxStatusChange:k,onCameraDemandChange:L,onCameraStats:D,onMicrophoneStateChange:oe,onTrace:H,onTerminated:ee,onConnectionStateChange:ce,onPlaybackStats:j};const St=!!H;a.useEffect(()=>{Mt.current=null,Ht(!1),Xt(!1),jt({}),Vt(null)},[t,ot]),a.useEffect(()=>{let e=!0;be.current!==null&&(be.current=null,Nt(null),i.safeInvoke("onAxSnapshotChange",F.current.onAxSnapshotChange,null));const o=i.createDeviceStream({url:t,token:c,sessionId:So,watchOnly:B,deviceModel:ot,autoReconnect:R,jitterBufferTargetMs:Y,openUrl:v,inspectMode:_,axPollIntervalMs:f,axMaxBackoffMs:O,androidElementTreeOptions:b,microphoneEnabled:z,speakerMuted:K,onStateChange:r=>{(r.videoReady||r.connection==="idle"||r.connection==="connecting"||r.connection==="reconnecting")&&yo(r.videoReady),To(r.connection==="failed"),Eo(r.connection==="terminated"),tt(r.duo),mo(r.duoState),po(r.duoError)},onAxSnapshotChange:r=>{e&&(Nt(h=>i.axSnapshotsEqual(h,r)?h:r),F.current.onAxSnapshotChange?.(r))},onAxStatusChange:(...r)=>F.current.onAxStatusChange?.(...r),onCameraDemandChange:(...r)=>F.current.onCameraDemandChange?.(...r),onCameraStats:D?(...r)=>F.current.onCameraStats?.(...r):void 0,onMicrophoneStateChange:(...r)=>F.current.onMicrophoneStateChange?.(...r),onSpeakerBlocked:()=>F.current.onSpeakerBlocked?.(),onTrace:St?(...r)=>F.current.onTrace?.(...r):void 0,onTerminated:()=>F.current.onTerminated?.(),onConnectionStateChange:(...r)=>F.current.onConnectionStateChange?.(...r),onPlaybackStats:j?(...r)=>F.current.onPlaybackStats?.(...r):void 0});w.current=o;const n=P.current?o.attachVideo(P.current):void 0,s=rt.current?o.attachAudio(rt.current):void 0;return o.start(),()=>{e=!1,o.dispose(),n?.(),s?.(),w.current=null}},[t,u,ot,St,B]),a.useLayoutEffect(()=>{w.current?.updateOptions({speakerMuted:K});const e=rt.current;e&&(i.cancelSpeakerRetry(e),e.muted=K,!K&&e.srcObject&&i.playSpeaker(e,()=>i.safeInvoke("onSpeakerBlocked",F.current.onSpeakerBlocked)))},[K]),a.useEffect(()=>{if(Z&&nt.current)return w.current?.attachVideo(nt.current,"inner")},[Z,t,u,ot,St,B]),a.useEffect(()=>{w.current?.updateOptions({token:c,openUrl:v,axPollIntervalMs:f,axMaxBackoffMs:O,androidElementTreeOptions:b,autoReconnect:R,jitterBufferTargetMs:Y,microphoneEnabled:z,inspectMode:_,onPlaybackStats:j?(...e)=>F.current.onPlaybackStats?.(...e):void 0,onCameraStats:D?(...e)=>F.current.onCameraStats?.(...e):void 0})},[c,R,Y,z,_,!!j,!!D,v,f,O,b]);const Je=()=>{if(!Zt.current)return;const e=We();if(!e){zt(null);return}const o={left:e.videoRect.left-e.containerRect.left+e.offsetX,top:e.videoRect.top-e.containerRect.top+e.offsetY,width:e.actualWidth,height:e.actualHeight};zt(n=>n&&n.left===o.left&&n.top===o.top&&n.width===o.width&&n.height===o.height?n:o)};a.useEffect(()=>{const e=P.current,o=G.current,n=de.current;if(!e)return;const s=S=>jt(T=>Et(T,S)?T:S),r=S=>Vt(T=>T&&S&&Et(T,S)?T:S),h=S=>bo(T=>T&&S&&Et(T,S)?T:S),l=()=>{const S=e.videoWidth>0&&e.videoHeight>0;S&&(Mt.current={width:e.videoWidth,height:e.videoHeight});const T=Mt.current,J=T?`${T.width} / ${T.height}`:void 0,X=It.current;if(_e&&n){if(Ut(T?T.width/T.height:kt),!X?.naturalWidth)return;const xe=X.naturalWidth/X.naturalHeight,ft=n.clientHeight-Ot,ke=n.clientHeight>0?Math.min(n.clientWidth,ft*xe):n.clientWidth;if(ke<=0)return;const Ve=ke/xe,Te=n.clientHeight>0?Ot/2:0,{screen:se}=_e,mt=se.notch??0,Be=se.left*ke,$e=se.top*Ve,pt=se.width*ke,gt=se.height*Ve,co=T?T.width/T.height:kt,yt=Math.min(pt,gt*co),xt=yt/co,$o=Be+(pt-yt)/2,Uo=mt>0?$e:$e+(gt-xt)/2,ao=(Qe,vt,Fo,zo)=>`translate(calc(-50% + ${Qe+Fo/2-ke/2}px), calc(-50% + ${vt+zo/2-Ve/2+Te}px))`;s({width:`${yt}px`,height:`${xt}px`,transform:ao($o,Uo,yt,xt)}),Mo(Qe=>{const vt={width:`${pt}px`,height:`${gt}px`,transform:ao(Be,$e,pt,gt)};return Qe&&Et(Qe,vt)?Qe:vt}),h({width:`${ke}px`,height:`${Ve}px`,transform:Te?`translateY(${Te}px)`:void 0}),r(null),Je();return}if(ue&&n){const xe=T?T.width/T.height:kt,ft=n.clientWidth*100/et,Ve=(n.clientHeight-Ot)/(1/xe+Pt/100),Te=n.clientHeight>0?Math.min(ft,Ve):ft;if(Te<=0)return;const se=Te/100,mt=Te/xe,Be=n.clientHeight>0?Ot/2:0,$e=`${se*Q.screenRadius}px`;s({aspectRatio:`${xe}`,width:`${Te}px`,height:`${mt}px`,borderRadius:`${$e} ${$e} 0 0`,transform:`translate(-50%, calc(-50% - ${se*qo-Be}px))`}),h({width:`${se*et}px`,height:`${mt+se*Pt}px`,transform:Be?`translateY(${Be}px)`:void 0,"--rc-macbook-unit":`${se}px`}),Ut(xe),r(null),Je();return}if(h(null),!qe||!o){s(!S&&T?{aspectRatio:J,contain:"size",containIntrinsicSize:`${T.width}px ${T.height}px`}:{}),r(null),Je();return}const q=o.clientWidth,re=o.clientHeight;if(q===0||re===0)return;const I=T?T.width>T.height:!1;Ht(I),Xt(V==="android"&&!!T&&Mn(T.width,T.height));const Se=I?Ne.videoPosition.landscape:Ne.videoPosition.portrait;let pe={aspectRatio:J};Se.heightMultiplier?(pe.height=`${re*Se.heightMultiplier}px`,pe.width="auto"):Se.widthMultiplier&&(pe.width=`${q*Se.widthMultiplier}px`,pe.height="auto"),pe.borderRadius=`${I?re*Ne.videoBorderRadiusMultiplier:q*Ne.videoBorderRadiusMultiplier}px`,s(pe);const he=Ne.homeButton,Ke=I?q:re,so=`calc(50% + ${Ke*(he?.offset??0)}px)`;r(he?{width:`${Ke*he.diameter}px`,height:`${Ke*he.diameter}px`,left:I?so:"50%",top:I?"50%":so}:null),Je()},m=new ResizeObserver(()=>{l()});o&&m.observe(o),m.observe(e),n&&m.observe(n),o&&o.addEventListener("load",l);const g=It.current;g?.addEventListener("load",l),e.addEventListener("loadedmetadata",l),e.addEventListener("resize",l);const M=()=>w.current?.bumpActivity();return e.addEventListener("resize",M),l(),()=>{m.disconnect(),e.removeEventListener("loadedmetadata",l),e.removeEventListener("resize",l),e.removeEventListener("resize",M),o&&o.removeEventListener("load",l),g?.removeEventListener("load",l)}},[Ne,qe,ue,_e?.src,we,t,N]),a.useEffect(()=>{Me?Je():(Nt(null),ze(null),ct(null),Gt(null),Le(null),at.current=null,fe.current!==void 0&&(window.cancelAnimationFrame(fe.current),fe.current=void 0))},[Me]),a.useEffect(()=>()=>{fe.current!==void 0&&(window.cancelAnimationFrame(fe.current),fe.current=void 0)},[]),a.useEffect(()=>{if(!Me)return;const e=o=>{o.key==="Escape"&&(wt||_t)&&(ct(null),ze(null),Le(null),i.safeInvoke("onInspectSelectionChange",Ye.current,null))};return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)},[Me,wt,_t]);const Vo=()=>{P.current&&P.current.focus()};a.useImperativeHandle(ye,()=>({openUrl:e=>w.current?.openUrl(e),sendKeyEvent:e=>w.current?.sendKeyEvent(e),screenshot:e=>w.current?.screenshot(e)??Promise.reject(new Error("Simulator disconnected")),terminateApp:e=>w.current?.terminateApp(e)??Promise.reject(new Error("Simulator disconnected")),reconnect:()=>w.current?.reconnect(),refreshAxTree:()=>w.current?.refreshAxTree()??Promise.reject(new Error("Simulator disconnected")),getAxSnapshot:()=>w.current?.getAxSnapshot()??null,setInspectHighlight:e=>{ze(e?.id??null)},setInspectSelection:e=>{ct(e?.id??null),Le(e?at.current:null);const o=be.current;e&&o?i.safeInvoke("onInspectSelectionChange",Ye.current,{element:e,snapshot:o}):i.safeInvoke("onInspectSelectionChange",Ye.current,null)},getAxStatus:()=>w.current?.getAxStatus()??"idle"}));const Bo=No&&Ae!==null;return p.jsxs("div",{ref:de,className:["rc-container",d].filter(Boolean).join(" "),style:{touchAction:"none"},onMouseDown:ve,onMouseMove:ve,onMouseUp:ve,onMouseLeave:ve,onTouchStart:ve,onTouchMove:ve,onTouchEnd:ve,onTouchCancel:ve,onContextMenu:V==="macos"?e=>e.preventDefault():void 0,children:[Bo&&Ae&&p.jsxs(p.Fragment,{children:[p.jsx("div",{className:"rc-touch-indicator",style:{left:`${Ae.containerX}px`,top:`${Ae.containerY}px`}}),p.jsx("div",{className:"rc-touch-indicator",style:{left:`${Ae.mirrorContainerX}px`,top:`${Ae.mirrorContainerY}px`}})]}),qe&&p.jsx("img",{ref:G,src:Qt,alt:"",className:V==="ios"?"rc-phone-frame rc-phone-frame-ios":"rc-phone-frame",draggable:!1}),_e&&!we&&Bt&&p.jsx("div",{className:"rc-macbook-screen",style:Bt,"aria-hidden":"true"}),_e&&!we&&p.jsx("img",{ref:It,src:_e.src,alt:"",className:"rc-macbook-image",style:bt??{visibility:"hidden"},draggable:!1}),ue&&!_e&&bt&&!we&&p.jsxs("div",{className:"rc-macbook",style:bt,"aria-hidden":"true",children:[p.jsx("div",{className:"rc-macbook-lid",children:p.jsx("div",{className:"rc-macbook-camera"})}),p.jsx("div",{className:"rc-macbook-base"})]}),qe&&Kt&&!B&&p.jsx("button",{type:"button",className:"rc-home-button","aria-label":"Home",title:"Home",style:Kt,onMouseDown:e=>e.stopPropagation(),onTouchStart:e=>e.stopPropagation(),onTouchEnd:e=>{e.stopPropagation(),e.preventDefault(),w.current?.pressButton("home")},onClick:e=>{e.stopPropagation(),w.current?.pressButton("home")}}),p.jsx("video",{ref:P,className:["rc-video",!qe&&!ue&&"rc-video-frameless",!go&&(V==="macos"?"rc-video-loading-desktop":"rc-video-loading")].filter(Boolean).join(" "),style:{...Ao,...Z||we?{opacity:0,width:1,height:1,pointerEvents:"none"}:{},...eo?{backgroundImage:`url("${eo}")`,backgroundRepeat:"no-repeat",backgroundPosition:"center",backgroundSize:Ne.loadingLogoSize}:{}},autoPlay:!0,playsInline:!0,muted:!0,tabIndex:Z||we?-1:0,onKeyDown:je,onKeyUp:je,onClick:Vo,onFocus:()=>{P.current&&(P.current.style.outline="none")},onBlur:()=>{P.current&&(P.current.style.outline="none"),Ze()}}),xo&&$t&&p.jsx(a.Suspense,{fallback:null,children:p.jsx(bn,{video:P.current,aspect:$t,model:x??ne?.model,animateLid:A,watchOnly:B,onReady:Ue.onReady,pointer:(e,o,n,s)=>{const r=P.current;!r?.videoWidth||!w.current?.getState().controlReady||Ie.pointer(e==="down"?i.MAC_INPUT_ACTION.DOWN:e==="up"?i.MAC_INPUT_ACTION.UP:i.MAC_INPUT_ACTION.MOVE,{x:o*r.videoWidth,y:n*r.videoHeight,width:r.videoWidth,height:r.videoHeight},s)},scroll:(e,o,n,s)=>{const r=P.current;!r?.videoWidth||!w.current?.getState().controlReady||Ie.scroll({x:e*r.videoWidth,y:o*r.videoHeight,width:r.videoWidth,height:r.videoHeight},n,s)},onKeyDown:je,onKeyUp:je,onBlur:Ze})}),ue&&p.jsx(fo,{view:Ue,label:"MacBook rendering"}),p.jsx("audio",{ref:rt,muted:!0,hidden:!0}),Z&&p.jsx("video",{ref:nt,autoPlay:!0,playsInline:!0,muted:!0,style:{position:"absolute",width:1,height:1,opacity:0,pointerEvents:"none"}}),Z&&Lt&&p.jsx(a.Suspense,{fallback:p.jsx("div",{children:"Loading iPhone Duo…"}),children:p.jsx(An,{watchOnly:B,showFrame:y,model:C??ne?.model,outer:P.current,inner:nt.current,state:Lt,setAngle:e=>Rt("setHingeAngle",{angleDegrees:e}),setOrientation:e=>Rt("setDuoOrientation",{orientation:e}),button:(e,o)=>Rt("performActions",{actions:[{type:o?"buttonDown":"buttonUp",button:e}]}),touch:(e,o,n,s)=>{w.current?.sendDisplayTouch(e,o,n,s)},onKeyDown:je,onKeyUp:je})}),Z&&Yt&&p.jsx("div",{role:"alert",className:"rc-duo-error",children:Yt}),!Z&&Me&&p.jsx(On,{snapshot:Ft,geometry:wo,highlightedId:_t,selectedId:wt,mode:Co,cursorPosition:Io,frozenCursorPosition:Ro,onSelectChange:(e,o)=>{ct(e?.id??null),e&&o?Le(o):e||Le(null);const n=be.current;e&&n?i.safeInvoke("onInspectSelectionChange",Ye.current,{element:e,snapshot:n}):i.safeInvoke("onInspectSelectionChange",Ye.current,null)},onTapElement:B?void 0:((e,o)=>{if(o){ro(o.x,o.y);return}const n=be.current;n&&ko(e,n)})}),Oo?p.jsxs("div",{className:"rc-terminated",role:"status",children:[p.jsx("div",{className:"rc-terminated-title",children:"Instance terminated"}),p.jsx("div",{className:"rc-terminated-message",children:"This instance no longer exists and can't be reconnected."})]}):vo&&p.jsx("button",{type:"button",className:"rc-retry-button",onClick:Ko,children:"Retry"})]})});exports.DeviceModeToggle=fo;exports.MACBOOK_LID_MAX_DEGREES=en;exports.MACBOOK_LID_OPENING_MS=on;exports.MACBOOK_LID_OPEN_DEGREES=tn;exports.MACBOOK_VERTEX_FLOATS=Zo;exports.RemoteControl=Rn;exports.lidEase=rn;exports.lidRotation=nn;exports.macbookMeshes=sn;exports.streamFit=cn;exports.streamPoint=an;exports.useDeviceView=ho;
@@ -1,5 +1,5 @@
1
1
  import { jsxs as oe, jsx as b, Fragment as Eo } from "react/jsx-runtime";
2
- import { M as te, o as hn, q as fn, f as mn, c as No, d as pn, b as gn, r as yn, s as vn, t as To, u as Xe, v as bn, w as wn, x as Mn, e as An, y as q, z as zt, B as Tn, C as Cn, E as Et, F as B, G as Nt, a as Rn, I as On, J as I, K as En } from "./core-BPDihn1M.mjs";
2
+ import { M as te, o as hn, q as fn, f as mn, c as No, d as pn, b as gn, r as yn, s as vn, t as To, u as Xe, v as bn, w as wn, x as Mn, e as An, y as q, z as zt, B as Tn, C as Cn, E as Et, F as B, G as Nt, a as Rn, I as On, J as I, K as En } from "./core-B7MkSLE_.mjs";
3
3
  import { useReducer as Nn, useRef as x, useCallback as It, memo as jt, useState as D, useEffect as ee, useMemo as Be, lazy as ko, forwardRef as kn, useLayoutEffect as _n, useImperativeHandle as Sn, Suspense as Co } from "react";
4
4
  import { createPortal as In } from "react-dom";
5
5
  import './index.css';const re = {
@@ -501,7 +501,7 @@ function qn(a, t) {
501
501
  return !1;
502
502
  }
503
503
  }
504
- const Zn = ko(() => import("./duo-view-B2i1POpD.mjs").then((a) => a.d)), Jn = ko(() => import("./macbook-frame-BZhBYM9R.mjs")), kt = (a) => Object.entries(I).find(
504
+ const Zn = ko(() => import("./duo-view-DuGDgUyB.mjs").then((a) => a.d)), Jn = ko(() => import("./macbook-frame-Bhu3fUB7.mjs")), kt = (a) => Object.entries(I).find(
505
505
  ([c, l]) => c.startsWith("ACTION_") && l === a
506
506
  )?.[0] ?? String(a), Ro = 1920, Oo = 1200, Qn = (a, t) => a === Ro && t === Oo || a === Oo && t === Ro, ei = {
507
507
  ios: {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@limrun/ui",
3
- "version": "0.22.6",
3
+ "version": "0.22.7",
4
4
  "publishConfig": {
5
5
  "access": "public"
6
6
  },
@@ -1,2 +0,0 @@
1
- "use strict";const Z={INJECT_KEYCODE:0,INJECT_TEXT:1,INJECT_TOUCH_EVENT:2,INJECT_TWO_FINGER_TOUCH_EVENT:18,INJECT_SCROLL_EVENT:3,BACK_OR_SCREEN_ON:4,EXPAND_NOTIFICATION_PANEL:5,EXPAND_SETTINGS_PANEL:6,COLLAPSE_PANELS:7,GET_CLIPBOARD:8,SET_CLIPBOARD:9,SET_DISPLAY_POWER:10,ROTATE_DEVICE:11,INJECT_MOUSE_EVENT:40,INJECT_MAC_KEY:41,INJECT_MAC_SCROLL:42},Pe={DOWN:0,UP:1,MOVE:2},Le={ACTION_DOWN:0,ACTION_UP:1,ACTION_MOVE:2,ACTION_CANCEL:3,ACTION_POINTER_DOWN:5,ACTION_POINTER_UP:6,BUTTON_PRIMARY:1,BUTTON_SECONDARY:2,BUTTON_TERTIARY:4},a={ACTION_DOWN:0,ACTION_UP:1,META_NONE:0,META_SHIFT_ON:1,META_ALT_ON:2,META_CTRL_ON:4096,META_META_ON:65536,KEYCODE_UNKNOWN:0,KEYCODE_SOFT_LEFT:1,KEYCODE_SOFT_RIGHT:2,KEYCODE_HOME:3,KEYCODE_BACK:4,KEYCODE_CALL:5,KEYCODE_ENDCALL:6,KEYCODE_0:7,KEYCODE_1:8,KEYCODE_2:9,KEYCODE_3:10,KEYCODE_4:11,KEYCODE_5:12,KEYCODE_6:13,KEYCODE_7:14,KEYCODE_8:15,KEYCODE_9:16,KEYCODE_STAR:17,KEYCODE_POUND:18,DPAD_UP:19,DPAD_DOWN:20,DPAD_LEFT:21,DPAD_RIGHT:22,KEYCODE_DPAD_CENTER:23,KEYCODE_VOLUME_UP:24,KEYCODE_VOLUME_DOWN:25,KEYCODE_POWER:26,KEYCODE_CAMERA:27,KEYCODE_CLEAR:28,KEYCODE_A:29,KEYCODE_B:30,KEYCODE_C:31,KEYCODE_D:32,KEYCODE_E:33,KEYCODE_F:34,KEYCODE_G:35,KEYCODE_H:36,KEYCODE_I:37,KEYCODE_J:38,KEYCODE_K:39,KEYCODE_L:40,KEYCODE_M:41,KEYCODE_N:42,KEYCODE_O:43,KEYCODE_P:44,KEYCODE_Q:45,KEYCODE_R:46,KEYCODE_S:47,KEYCODE_T:48,KEYCODE_U:49,KEYCODE_V:50,KEYCODE_W:51,KEYCODE_X:52,KEYCODE_Y:53,KEYCODE_Z:54,KEYCODE_COMMA:55,KEYCODE_PERIOD:56,KEYCODE_ALT_LEFT:57,KEYCODE_ALT_RIGHT:58,KEYCODE_SHIFT_LEFT:59,KEYCODE_SHIFT_RIGHT:60,KEYCODE_TAB:61,KEYCODE_SPACE:62,KEYCODE_SYM:63,KEYCODE_EXPLORER:64,KEYCODE_ENVELOPE:65,ENTER:66,DEL:67,KEYCODE_GRAVE:68,KEYCODE_MINUS:69,KEYCODE_EQUALS:70,KEYCODE_LEFT_BRACKET:71,KEYCODE_RIGHT_BRACKET:72,KEYCODE_BACKSLASH:73,KEYCODE_SEMICOLON:74,KEYCODE_APOSTROPHE:75,KEYCODE_SLASH:76,KEYCODE_AT:77,KEYCODE_NUM:78,KEYCODE_HEADSETHOOK:79,KEYCODE_FOCUS:80,KEYCODE_PLUS:81,MENU:82,KEYCODE_NOTIFICATION:83,KEYCODE_SEARCH:84,KEYCODE_MEDIA_PLAY_PAUSE:85,KEYCODE_MEDIA_STOP:86,KEYCODE_MEDIA_NEXT:87,KEYCODE_MEDIA_PREVIOUS:88,KEYCODE_MEDIA_REWIND:89,KEYCODE_MEDIA_FAST_FORWARD:90,KEYCODE_MUTE:91,KEYCODE_PAGE_UP:92,KEYCODE_PAGE_DOWN:93,KEYCODE_PICTSYMBOLS:94,KEYCODE_SWITCH_CHARSET:95,KEYCODE_BUTTON_A:96,KEYCODE_BUTTON_B:97,KEYCODE_BUTTON_C:98,KEYCODE_BUTTON_X:99,KEYCODE_BUTTON_Y:100,KEYCODE_BUTTON_Z:101,KEYCODE_BUTTON_L1:102,KEYCODE_BUTTON_R1:103,KEYCODE_BUTTON_L2:104,KEYCODE_BUTTON_R2:105,KEYCODE_BUTTON_THUMBL:106,KEYCODE_BUTTON_THUMBR:107,KEYCODE_BUTTON_START:108,KEYCODE_BUTTON_SELECT:109,KEYCODE_BUTTON_MODE:110,KEYCODE_ESCAPE:111,FORWARD_DEL:112,KEYCODE_CTRL_LEFT:113,KEYCODE_CTRL_RIGHT:114,KEYCODE_CAPS_LOCK:115,KEYCODE_SCROLL_LOCK:116,KEYCODE_META_LEFT:117,KEYCODE_META_RIGHT:118,KEYCODE_FUNCTION:119,KEYCODE_SYSRQ:120,KEYCODE_BREAK:121,KEYCODE_MOVE_HOME:122,KEYCODE_MOVE_END:123,KEYCODE_INSERT:124,KEYCODE_FORWARD:125,KEYCODE_MEDIA_PLAY:126,KEYCODE_MEDIA_PAUSE:127,KEYCODE_MEDIA_CLOSE:128,KEYCODE_MEDIA_EJECT:129,KEYCODE_MEDIA_RECORD:130,KEYCODE_F1:131,KEYCODE_F2:132,KEYCODE_F3:133,KEYCODE_F4:134,KEYCODE_F5:135,KEYCODE_F6:136,KEYCODE_F7:137,KEYCODE_F8:138,KEYCODE_F9:139,KEYCODE_F10:140,KEYCODE_F11:141,KEYCODE_F12:142,KEYCODE_NUM_LOCK:143,KEYCODE_NUMPAD_0:144,KEYCODE_NUMPAD_1:145,KEYCODE_NUMPAD_2:146,KEYCODE_NUMPAD_3:147,KEYCODE_NUMPAD_4:148,KEYCODE_NUMPAD_5:149,KEYCODE_NUMPAD_6:150,KEYCODE_NUMPAD_7:151,KEYCODE_NUMPAD_8:152,KEYCODE_NUMPAD_9:153,KEYCODE_NUMPAD_DIVIDE:154,KEYCODE_NUMPAD_MULTIPLY:155,KEYCODE_NUMPAD_SUBTRACT:156,KEYCODE_NUMPAD_ADD:157,KEYCODE_NUMPAD_DOT:158,KEYCODE_NUMPAD_COMMA:159,KEYCODE_NUMPAD_ENTER:160,KEYCODE_NUMPAD_EQUALS:161,KEYCODE_NUMPAD_LEFT_PAREN:162,KEYCODE_NUMPAD_RIGHT_PAREN:163,KEYCODE_VOLUME_MUTE:164,KEYCODE_INFO:165,KEYCODE_CHANNEL_UP:166,KEYCODE_CHANNEL_DOWN:167,KEYCODE_ZOOM_IN:168,KEYCODE_ZOOM_OUT:169,KEYCODE_TV:170,KEYCODE_WINDOW:171,KEYCODE_GUIDE:172,KEYCODE_DVR:173,KEYCODE_BOOKMARK:174,KEYCODE_CAPTIONS:175,KEYCODE_SETTINGS:176,KEYCODE_TV_POWER:177,KEYCODE_TV_INPUT:178,KEYCODE_STB_POWER:179,KEYCODE_STB_INPUT:180,KEYCODE_AVR_POWER:181,KEYCODE_AVR_INPUT:182,KEYCODE_PROG_RED:183,KEYCODE_PROG_GREEN:184,KEYCODE_PROG_YELLOW:185,KEYCODE_PROG_BLUE:186,KEYCODE_APP_SWITCH:187,KEYCODE_LANGUAGE_SWITCH:204,KEYCODE_ASSIST:219,KEYCODE_BRIGHTNESS_DOWN:220,KEYCODE_BRIGHTNESS_UP:221,KEYCODE_SLEEP:223,KEYCODE_WAKEUP:224,KEYCODE_SOFT_SLEEP:276},Lt={KeyA:a.KEYCODE_A,KeyB:a.KEYCODE_B,KeyC:a.KEYCODE_C,KeyD:a.KEYCODE_D,KeyE:a.KEYCODE_E,KeyF:a.KEYCODE_F,KeyG:a.KEYCODE_G,KeyH:a.KEYCODE_H,KeyI:a.KEYCODE_I,KeyJ:a.KEYCODE_J,KeyK:a.KEYCODE_K,KeyL:a.KEYCODE_L,KeyM:a.KEYCODE_M,KeyN:a.KEYCODE_N,KeyO:a.KEYCODE_O,KeyP:a.KEYCODE_P,KeyQ:a.KEYCODE_Q,KeyR:a.KEYCODE_R,KeyS:a.KEYCODE_S,KeyT:a.KEYCODE_T,KeyU:a.KEYCODE_U,KeyV:a.KEYCODE_V,KeyW:a.KEYCODE_W,KeyX:a.KEYCODE_X,KeyY:a.KEYCODE_Y,KeyZ:a.KEYCODE_Z,Digit0:a.KEYCODE_0,Digit1:a.KEYCODE_1,Digit2:a.KEYCODE_2,Digit3:a.KEYCODE_3,Digit4:a.KEYCODE_4,Digit5:a.KEYCODE_5,Digit6:a.KEYCODE_6,Digit7:a.KEYCODE_7,Digit8:a.KEYCODE_8,Digit9:a.KEYCODE_9,Backquote:a.KEYCODE_GRAVE,Minus:a.KEYCODE_MINUS,Equal:a.KEYCODE_EQUALS,BracketLeft:a.KEYCODE_LEFT_BRACKET,BracketRight:a.KEYCODE_RIGHT_BRACKET,Backslash:a.KEYCODE_BACKSLASH,Semicolon:a.KEYCODE_SEMICOLON,Quote:a.KEYCODE_APOSTROPHE,Comma:a.KEYCODE_COMMA,Period:a.KEYCODE_PERIOD,Slash:a.KEYCODE_SLASH,Space:a.KEYCODE_SPACE,Tab:a.KEYCODE_TAB,Escape:a.KEYCODE_ESCAPE,ArrowUp:a.DPAD_UP,ArrowDown:a.DPAD_DOWN,ArrowLeft:a.DPAD_LEFT,ArrowRight:a.DPAD_RIGHT,Enter:a.ENTER,Backspace:a.DEL,Delete:a.FORWARD_DEL,Home:a.KEYCODE_MOVE_HOME,End:a.KEYCODE_MOVE_END,PageUp:a.KEYCODE_PAGE_UP,PageDown:a.KEYCODE_PAGE_DOWN,Insert:a.KEYCODE_INSERT,F1:a.KEYCODE_F1,F2:a.KEYCODE_F2,F3:a.KEYCODE_F3,F4:a.KEYCODE_F4,F5:a.KEYCODE_F5,F6:a.KEYCODE_F6,F7:a.KEYCODE_F7,F8:a.KEYCODE_F8,F9:a.KEYCODE_F9,F10:a.KEYCODE_F10,F11:a.KEYCODE_F11,F12:a.KEYCODE_F12,ShiftLeft:a.KEYCODE_SHIFT_LEFT,ShiftRight:a.KEYCODE_SHIFT_RIGHT,ControlLeft:a.KEYCODE_CTRL_LEFT,ControlRight:a.KEYCODE_CTRL_RIGHT,AltLeft:a.KEYCODE_ALT_LEFT,AltRight:a.KEYCODE_ALT_RIGHT,MetaLeft:a.KEYCODE_META_LEFT,MetaRight:a.KEYCODE_META_RIGHT,ContextMenu:a.MENU,Numpad0:a.KEYCODE_NUMPAD_0,Numpad1:a.KEYCODE_NUMPAD_1,Numpad2:a.KEYCODE_NUMPAD_2,Numpad3:a.KEYCODE_NUMPAD_3,Numpad4:a.KEYCODE_NUMPAD_4,Numpad5:a.KEYCODE_NUMPAD_5,Numpad6:a.KEYCODE_NUMPAD_6,Numpad7:a.KEYCODE_NUMPAD_7,Numpad8:a.KEYCODE_NUMPAD_8,Numpad9:a.KEYCODE_NUMPAD_9,NumpadDivide:a.KEYCODE_NUMPAD_DIVIDE,NumpadMultiply:a.KEYCODE_NUMPAD_MULTIPLY,NumpadSubtract:a.KEYCODE_NUMPAD_SUBTRACT,NumpadAdd:a.KEYCODE_NUMPAD_ADD,NumpadDecimal:a.KEYCODE_NUMPAD_DOT,NumpadComma:a.KEYCODE_NUMPAD_COMMA,NumpadEnter:a.KEYCODE_NUMPAD_ENTER,NumpadEqual:a.KEYCODE_NUMPAD_EQUALS},mr={KeyA:0,KeyS:1,KeyD:2,KeyF:3,KeyH:4,KeyG:5,KeyZ:6,KeyX:7,KeyC:8,KeyV:9,IntlBackslash:10,KeyB:11,KeyQ:12,KeyW:13,KeyE:14,KeyR:15,KeyY:16,KeyT:17,Digit1:18,Digit2:19,Digit3:20,Digit4:21,Digit6:22,Digit5:23,Equal:24,Digit9:25,Digit7:26,Minus:27,Digit8:28,Digit0:29,BracketRight:30,KeyO:31,KeyU:32,BracketLeft:33,KeyI:34,KeyP:35,Enter:36,KeyL:37,KeyJ:38,Quote:39,KeyK:40,Semicolon:41,Backslash:42,Comma:43,Slash:44,KeyN:45,KeyM:46,Period:47,Tab:48,Space:49,Backquote:50,Backspace:51,Escape:53,MetaRight:54,MetaLeft:55,ShiftLeft:56,CapsLock:57,AltLeft:58,ControlLeft:59,ShiftRight:60,AltRight:61,ControlRight:62,Fn:63,F17:64,NumpadDecimal:65,NumpadMultiply:67,NumpadAdd:69,NumLock:71,NumpadDivide:75,NumpadEnter:76,NumpadSubtract:78,F18:79,F19:80,NumpadEqual:81,Numpad0:82,Numpad1:83,Numpad2:84,Numpad3:85,Numpad4:86,Numpad5:87,Numpad6:88,Numpad7:89,F20:90,Numpad8:91,Numpad9:92,F5:96,F6:97,F7:98,F3:99,F8:100,F9:101,F11:103,F13:105,F16:106,F14:107,F10:109,ContextMenu:110,F12:111,F15:113,Help:114,Insert:114,Home:115,PageUp:116,Delete:117,F4:118,End:119,F2:120,PageDown:121,F1:122,ArrowLeft:123,ArrowRight:124,ArrowDown:125,ArrowUp:126};function Et(t){return mr[t]}function Ft(t,e,r,o,u,l,i=1,E=0,D=0){const p=new ArrayBuffer(32),S=new DataView(p);let w=0;S.setUint8(w,Z.INJECT_TOUCH_EVENT),w+=1;const N=t===Le.ACTION_POINTER_DOWN?Le.ACTION_DOWN:t===Le.ACTION_POINTER_UP?Le.ACTION_UP:t;return S.setUint8(w,N),w+=1,S.setBigInt64(w,BigInt(e),!0),w+=8,S.setInt32(w,Math.round(u),!0),w+=4,S.setInt32(w,Math.round(l),!0),w+=4,S.setUint16(w,r,!0),w+=2,S.setUint16(w,o,!0),w+=2,S.setInt16(w,Math.round(i*65535),!0),w+=2,S.setInt32(w,E,!0),w+=4,S.setInt32(w,D,!0),p}function Cr(t,e,r,o,u,l,i){const E=new ArrayBuffer(24),D=new DataView(E);let p=0;return D.setUint8(p,Z.INJECT_TWO_FINGER_TOUCH_EVENT),p+=1,D.setUint8(p,t),p+=1,D.setInt32(p,Math.round(o),!0),p+=4,D.setInt32(p,Math.round(u),!0),p+=4,D.setInt32(p,Math.round(l),!0),p+=4,D.setInt32(p,Math.round(i),!0),p+=4,D.setUint16(p,e,!0),p+=2,D.setUint16(p,r,!0),p+=2,D.setUint16(p,0,!0),E}function Bt(t,e=!0){const o=new TextEncoder().encode(t),u=new ArrayBuffer(14+o.length),l=new DataView(u);let i=0;return l.setUint8(i,Z.SET_CLIPBOARD),i+=1,l.setBigInt64(i,BigInt(0),!1),i+=8,l.setUint8(i,e?1:0),i+=1,l.setUint32(i,o.length,!1),i+=4,new Uint8Array(u,i).set(o),u}function Ze(t,e,r=0,o=0){const u=new ArrayBuffer(14),l=new DataView(u);let i=0;return l.setUint8(i,Z.INJECT_KEYCODE),i+=1,l.setUint8(i,t),i+=1,l.setInt32(i,e,!0),i+=4,l.setInt32(i,r,!0),i+=4,l.setInt32(i,o,!0),u}function Or(t,e,r,o,u,l){const i=new ArrayBuffer(18),E=new DataView(i);return E.setUint8(0,Z.INJECT_MOUSE_EVENT),E.setUint8(1,t),E.setInt32(2,Math.round(o),!0),E.setInt32(6,Math.round(u),!0),E.setUint16(10,e,!0),E.setUint16(12,r,!0),E.setInt32(14,l,!0),i}function xt(t,e){const r=new ArrayBuffer(4),o=new DataView(r);return o.setUint8(0,Z.INJECT_MAC_KEY),o.setUint8(1,t),o.setUint16(2,e,!0),r}function Dr(t,e,r,o,u,l){const i=new ArrayBuffer(21),E=new DataView(i);return E.setUint8(0,Z.INJECT_MAC_SCROLL),E.setInt32(1,Math.round(r),!0),E.setInt32(5,Math.round(o),!0),E.setUint16(9,t,!0),E.setUint16(11,e,!0),E.setFloat32(13,u,!0),E.setFloat32(17,l,!0),i}function _r(t){return t?.displays.find(e=>e.id===(t.angleDegrees<90?"outer":"inner"))}function Wt(t){return t===2?2:t===3?1:t===4?3:0}class gr{constructor(e){this.send=e}send;screenId;turns=0;held;get active(){return this.held!==void 0}setDisplay(e,r=Wt(e?.orientation)){(this.screenId!==e?.screenId||this.turns!==r)&&this.release(),this.screenId=e?.screenId,this.turns=r}touch(e,r,o,u=!1){if(this.screenId===void 0)return;const l=qt(r,o,u?0:this.turns);e==="begin"&&(this.release(),this.held={screenId:this.screenId,...l}),this.held&&(Object.assign(this.held,l),e==="end"?this.release():this.send(e==="begin"?0:2,this.held.screenId,l.x,l.y))}release(){if(!this.held)return;const{screenId:e,x:r,y:o}=this.held;this.held=void 0,this.send(1,e,r,o)}}const Tr={width:164.6,height:117.8,depth:5.2};function qt(t,e,r){return t=Math.max(0,Math.min(1,t)),e=Math.max(0,Math.min(1,e)),r===1?{x:e,y:1-t}:r===2?{x:1-t,y:1-e}:r===3?{x:1-e,y:t}:{x:t,y:e}}function yr(t){return Number.isFinite(t)&&t>=0&&t<=180}function Sr(t,e){return{x:Math.max(0,Math.min(1,t)),y:Math.max(0,Math.min(1,1-e))}}function Kr(t,e,r){return e&&(t||!r)?"touch":t?"ignore":"orbit"}function Vt(t,e,r,o){if(!Number.isInteger(t)||t<0||t>3||!Number.isInteger(e)||e<1||e>255||!Number.isFinite(r)||!Number.isFinite(o)||r<0||r>1||o<0||o>1)throw new RangeError("Invalid display touch coordinates");const u=new ArrayBuffer(12),l=new DataView(u);return l.setUint8(0,19),l.setUint8(1,t),l.setUint8(2,e),l.setFloat32(4,r,!0),l.setFloat32(8,o,!0),u}class Ar{constructor(e,r){this.send=e,this.failed=r}send;failed;latest;running=!1;stopped=!1;set(e){this.stopped||!yr(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 Mr={side:"Sleep/Wake",volumeUp:"Volume Up",volumeDown:"Volume Down"};class vr{constructor(e,r){this.send=e,this.failed=r}send;failed;held;tail=Promise.resolve();timeout;press(e){this.held||(this.held=e,this.enqueue(e,!0),this.timeout=setTimeout(()=>this.release(),1e4))}release(){if(!this.held)return;clearTimeout(this.timeout);const e=this.held;this.held=void 0,this.enqueue(e,!1)}enqueue(e,r){this.tail=this.tail.then(()=>this.send(e,r)).catch(this.failed)}}const et="Accessibility unavailable on this device.",tt=500,$t=(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,wr=t=>Math.max(0,t.width)*Math.max(0,t.height),Nr=t=>{const e=t.find(r=>r.frame&&r.frame.width>0&&r.frame.height>0);return e?.frame?((Math.abs(e.frame.x)>.5||Math.abs(e.frame.y)>.5)&&console.warn(`[ax-tree] iOS root frame is not anchored at (0,0): (${e.frame.x},${e.frame.y}). Element positions may be slightly off from the rendered video.`),{x:0,y:0,width:e.frame.width,height:e.frame.height}):{x:0,y:0,width:1,height:1}},br=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},Yr=t=>{const e={};for(const[r,o]of Object.entries(t))r!=="children"&&(e[r]=o);return e};function Ht(t){const e=Array.isArray(t)?t:[t],r=Nr(e),o=[],u=(l,i)=>{if(o.length>=tt)return;const E=l.frame;if(E&&E.width>0&&E.height>0&&!$t(E,r)){const p=l.role_description||l.role||"",S=(typeof l.AXLabel=="string"?l.AXLabel:"")||(typeof l.title=="string"?l.title:"")||"";o.push({id:typeof l.AXUniqueId=="string"&&l.AXUniqueId.length>0?l.AXUniqueId:i,path:i,label:S,value:typeof l.AXValue=="string"?l.AXValue:"",role:p,type:typeof l.type=="string"?l.type:"",enabled:l.enabled!==!1,focused:l.focused===!0,frame:{x:E.x,y:E.y,width:E.width,height:E.height},selectors:br(l),raw:Yr(l)})}const D=Array.isArray(l.children)?l.children:[];for(let p=0;p<D.length&&o.length<tt;p++)u(D[p],`${i}.${p}`)};for(let l=0;l<e.length&&o.length<tt;l++)u(e[l],String(l));return{platform:"ios",screen:{width:r.width,height:r.height},elements:o,capturedAt:Date.now()}}const Ir=t=>{let e={x:0,y:0,width:1,height:1},r=0;for(const o of t){const u=o.parsedBounds;if(!u)continue;const l=u.right-u.left,i=u.bottom-u.top,E=Math.max(0,l)*Math.max(0,i);E>r&&(r=E,e={x:0,y:0,width:l,height:i})}return e},Rr=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 Jt(t){const e=Ir(t),r=[];for(let o=0;o<t.length&&r.length<tt;o++){const u=t[o],l=u.parsedBounds;if(!l)continue;const i=Math.max(0,l.right-l.left),E=Math.max(0,l.bottom-l.top);if(i<=0||E<=0)continue;const D={x:l.left,y:l.top,width:i,height:E};if($t(D,{x:0,y:0,width:e.width,height:e.height}))continue;const p=u.contentDesc||u.text||"",S=u.className||"";r.push({id:u.resourceId&&u.resourceId.length>0?u.resourceId:u.contentDesc&&u.contentDesc.length>0?`cd:${u.contentDesc}`:String(o),path:String(o),label:p,value:typeof u.text=="string"?u.text:"",role:S,type:S,enabled:u.enabled!==!1,focused:u.focused===!0,frame:D,selectors:Rr(u),raw:{...u}})}return{platform:"android",screen:{width:e.width,height:e.height},elements:r,capturedAt:Date.now()}}function kr(t,e){const r=Math.max(0,t.x),o=Math.max(0,t.y),u=Math.min(e.width,t.x+t.width),l=Math.min(e.height,t.y+t.height),i=Math.max(0,u-r),E=Math.max(0,l-o);return i>0&&E>0?{x:r,y:o,width:i,height:E}:null}function Gt(t,e){if(t===e)return!0;if(t.id!==e.id||t.path!==e.path||t.label!==e.label||t.value!==e.value||t.role!==e.role||t.type!==e.type||t.enabled!==e.enabled||t.focused!==e.focused)return!1;const r=t.frame,o=e.frame;return r.x===o.x&&r.y===o.y&&r.width===o.width&&r.height===o.height}function jt(t,e){if(t===e)return!0;if(!t||!e||t.platform!==e.platform||t.screen.width!==e.screen.width||t.screen.height!==e.screen.height||t.elements.length!==e.elements.length)return!1;for(let r=0;r<t.elements.length;r++)if(!Gt(t.elements[r],e.elements[r]))return!1;return!0}function Ur(t,e,r){let o=null,u=1/0;for(const l of t.elements){const i=l.frame;if(e<i.x||r<i.y||e>i.x+i.width||r>i.y+i.height)continue;const E=wr(i);E<u&&(u=E,o=l)}return o}function Pr(t,e){if(e==="ios"){if(t.selectors.AXUniqueId)return`client.tapElement({ AXUniqueId: ${JSON.stringify(t.selectors.AXUniqueId)} })`;if(t.selectors.AXLabel){const r=t.selectors.className?`, type: ${JSON.stringify(t.selectors.className)}`:"";return`client.tapElement({ AXLabel: ${JSON.stringify(t.selectors.AXLabel)}${r} })`}return null}return t.selectors.resourceId?`client.tap({ selector: { resourceId: ${JSON.stringify(t.selectors.resourceId)} } })`:t.selectors.contentDesc?`client.tap({ selector: { contentDesc: ${JSON.stringify(t.selectors.contentDesc)} } })`:t.selectors.text?`client.tap({ selector: { text: ${JSON.stringify(t.selectors.text)} } })`:null}function Xt(t){const e=t.role||t.type||"";if(!e)return"element";let r=e.replace(/^AX/,"");return r.includes(".")&&(r=r.split(".").pop()),r==="GenericElement"?"Element":(r=r.replace(/([a-z])([A-Z])/g,"$1 $2"),r)}const bt=80;function Lr(t){const e=Xt(t),r=t.label||t.value||"";if(!r)return e;const o=r.length>bt?r.slice(0,bt).trimEnd()+"…":r;return`${e} · ${o}`}const Fr=500,Br=2e3,Yt=5e3,xr=8e3,Wr=1200,qr=250,Vr=()=>`ax-rc-${Date.now()}-${Math.random().toString(36).slice(2,8)}`;class $r{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??Fr,this.maxBackoffMs=e.maxBackoffMs??Br,this.androidElementTreeOptions=e.androidElementTreeOptions,this.currentInterval=this.baseIntervalMs}start(){this.running||(this.running=!0,this.currentInterval=this.baseIntervalMs,this.boostUntilMs=0,this.setStatus("starting"),this.runOnce())}stop(){this.running&&(this.running=!1,this.timer!==void 0&&(window.clearTimeout(this.timer),this.timer=void 0),this.failAllPending("Inspector stopped"),this.lastSnapshot=null,this.setStatus("idle"),this.onSnapshot(null))}getStatus(){return this.status}setStatus(e,r){if(this.status!==e&&(this.status=e,!!this.onStatusChange))try{this.onStatusChange(e,r)}catch(o){console.error("[AxFetcher] onStatusChange threw:",o)}}bumpActivity(){if(!this.running)return;const e=Date.now();this.boostUntilMs=e+Wr;const r=Math.max(150,Math.floor(this.baseIntervalMs/2));if(e-this.lastBumpAtMs<r){this.currentInterval=this.baseIntervalMs;return}this.lastBumpAtMs=e,this.currentInterval=this.baseIntervalMs,this.timer!==void 0&&(window.clearTimeout(this.timer),this.timer=void 0),this.inflight||this.runOnce()}async refresh(){const e=await this.requestOnce();return this.running&&this.deliver(e),e}getLatest(){return this.lastSnapshot}handleMessage(e){if(!e||typeof e.id!="string")return!1;const r=e.id;if(!this.pending.get(r))return!1;if(this.platform==="ios"){if(e.type!=="elementTreeResult")return!1;const E=typeof e.error=="string"?e.error:null;if(E)return this.settleReject(r,new Error(E)),!0;const D=typeof e.json=="string"?e.json:"";try{const p=JSON.parse(D),S=Ht(p);this.settleResolve(r,S)}catch(p){this.settleReject(r,p instanceof Error?p:new Error(String(p)))}return!0}if(e.type!=="getElementTreeResult")return!1;const u=e.error;if(u&&typeof u=="object"){const E=typeof u.message=="string"?u.message:"getElementTree failed";return this.settleReject(r,new Error(E)),!0}const l=e.payload,i=Array.isArray(l?.nodes)?l.nodes:[];try{const E=Jt(i);this.settleResolve(r,E)}catch(E){this.settleReject(r,E instanceof Error?E:new Error(String(E)))}return!0}buildRequest(e){return this.platform==="ios"?{type:"elementTree",id:e}:{type:"getElementTree",id:e,...this.androidElementTreeOptions}}async requestOnce(){const e=Vr();return new Promise((r,o)=>{const u=window.setTimeout(()=>{this.pending.delete(e),o(new Error("elementTree request timed out"))},xr+(this.androidElementTreeOptions?.waitForIdleTimeoutMs??0));this.pending.set(e,{resolve:r,reject:o,timer:u}),this.send(this.buildRequest(e))||(window.clearTimeout(u),this.pending.delete(e),o(new Error("elementTree send failed (WebSocket not open)")))})}async runOnce(){if(this.running&&!this.inflight){this.inflight=!0;try{const e=await this.requestOnce();if(!this.running)return;this.deliver(e)}catch(e){if(!this.running)return;const r=e instanceof Error?e.message:String(e),o=/unavailable|not (yet )?running|failed|timeout/i.test(r);this.currentInterval=o?Yt:Math.min(this.currentInterval*2,this.maxBackoffMs),this.setStatus(o?"unavailable":"error",r)}finally{this.inflight=!1,this.scheduleNext()}}}deliver(e){const r=this.lastSnapshot;if(jt(r,e)){this.currentInterval=Math.min(this.currentInterval*2,this.maxBackoffMs),this.lastSnapshot=e,e.errors?.includes(et)||this.setStatus("ready");return}this.lastSnapshot=e,this.currentInterval=this.baseIntervalMs,e.errors?.includes(et)?(this.currentInterval=Yt,this.setStatus("unavailable",et)):this.setStatus("ready"),this.onSnapshot(e)}scheduleNext(){if(!this.running)return;this.timer!==void 0&&window.clearTimeout(this.timer);const e=Date.now()<this.boostUntilMs?Math.min(qr,this.currentInterval):this.currentInterval;this.timer=window.setTimeout(()=>{this.timer=void 0,this.runOnce()},e)}settleResolve(e,r){const o=this.pending.get(e);o&&(window.clearTimeout(o.timer),this.pending.delete(e),o.resolve(r))}settleReject(e,r){const o=this.pending.get(e);o&&(window.clearTimeout(o.timer),this.pending.delete(e),o.reject(r))}failAllPending(e){for(const[r,o]of this.pending.entries())window.clearTimeout(o.timer),o.reject(new Error(e)),this.pending.delete(r)}}function It(t,e){if(e!=null&&(!Number.isFinite(e)||e<0||e>4e3)){console.warn("RemoteControl: jitterBufferTargetMs must be a finite number between 0 and 4000.");return}if(!("jitterBufferTarget"in t))return;const r=e??null;try{t.jitterBufferTarget!==r&&(t.jitterBufferTarget=r)}catch(o){console.warn("RemoteControl: could not set the jitter buffer target.",o)}}const Qt=`(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
- `,Rt=typeof self<"u"&&self.Blob&&new Blob(["(self.URL || self.webkitURL).revokeObjectURL(self.location.href);",Qt],{type:"text/javascript;charset=utf-8"});function Hr(t){let e;try{if(e=Rt&&(self.URL||self.webkitURL).createObjectURL(Rt),!e)throw"";const r=new Worker(e,{name:t?.name});return r.addEventListener("error",()=>{(self.URL||self.webkitURL).revokeObjectURL(e)}),r}catch{return new Worker("data:text/javascript;charset=utf-8,"+encodeURIComponent(Qt),{name:t?.name})}}function Jr(t,e,r){const{MediaStreamTrackProcessor:o,MediaStreamTrackGenerator:u}=globalThis,l=e.getVideoTracks()[0];let i,E,D,p,S=!1;const w=()=>{S||(S=!0,i?.stop(),E?.stop(),D&&(D.postMessage({type:"stop"}),p=setTimeout(()=>D?.terminate(),1e3)))},N=_=>{t.srcObject=_,t.play().catch(()=>{})},V=_=>{S||(w(),r(_),N(e))};try{if(l&&o&&u){i=l.clone();const _=new o({track:i,maxBufferSize:1}),H=new u({kind:"video"});E=H,D=new Hr,D.onmessage=({data:F})=>{F.type==="error"?V(new Error(F.message)):F.type==="stopped"&&(clearTimeout(p),D?.terminate())},D.onerror=F=>V(new Error(F.message)),D.postMessage({type:"start",readable:_.readable,writable:H.writable},[_.readable,H.writable]),N(new MediaStream(e.getTracks().map(F=>F===l?H:F)))}else N(e)}catch(_){V(_)}return w}function Fe(t){return typeof t=="number"&&Number.isFinite(t)}function Se(t,e){if(!(!Fe(t)||!Fe(e)||t<e||e<0))return t-e}class Gr{previous=new Map;reset(){this.previous.clear()}read(e,r,o){const u={timestamp:0,video:[],audio:[]};o==null?u.requestedTargetMs=null:Fe(o)&&o>=0&&o<=4e3&&(u.requestedTargetMs=o);const l=new Map;return e.forEach(i=>{if(i.type!=="inbound-rtp"||!Fe(i.timestamp))return;const E=i.kind??i.mediaType;if(E!=="video"&&E!=="audio")return;const D=r.filter(P=>P.kind===E),p=i.trackIdentifier?D.find(P=>P.trackId===i.trackIdentifier):i.mid!=null?D.find(P=>P.mid===i.mid):D.length===1?D[0]:void 0;if(!p)return;const S=this.previous.get(i.id),N=S?.trackId===p.trackId&&S.stats.ssrc===i.ssrc?S.stats:void 0,V=N?i.timestamp-N.timestamp:void 0,_={id:i.id,trackId:p.trackId,timestamp:i.timestamp};if(V!==void 0&&V>0){_.intervalMs=V;const P=Se(i.jitterBufferEmittedCount,N?.jitterBufferEmittedCount),B=Se(i.jitterBufferDelay,N?.jitterBufferDelay);P!==void 0&&P>0&&B!==void 0&&(_.bufferDelayMs=B/P*1e3);const x=Se(i.bytesReceived,N?.bytesReceived);x!==void 0&&(_.bitrateBps=x*8e3/V)}if(E==="video"){const P={..._,display:p.display??"primary"};if(_.intervalMs!==void 0){const B=Se(i.framesDecoded,N?.framesDecoded);B!==void 0&&(P.fps=B*1e3/_.intervalMs),P.droppedFrames=Se(i.framesDropped,N?.framesDropped),P.freezes=Se(i.freezeCount,N?.freezeCount)}u.video.push(P)}else u.audio.push(_);u.timestamp=Math.max(u.timestamp,i.timestamp),l.set(i.id,N&&i.timestamp<=N.timestamp?S:{stats:i,trackId:p.trackId});const H=i.transportId?e.get(i.transportId):void 0,F=H?.selectedCandidatePairId?e.get(H.selectedCandidatePairId):void 0;F?.state==="succeeded"&&Fe(F.currentRoundTripTime)&&F.currentRoundTripTime>=0&&(u.rttMs=F.currentRoundTripTime*1e3)}),this.previous=l,u.video.length||u.audio.length?u:null}}const ut=new WeakSet;function jr(t,e,r){const{peer:o,displays:u}=t,l=new Gr;let i,E=!1,D=!1,p=!1,S=0,w=!1,N=!1;const V=()=>!E&&!document.hidden&&o.connectionState==="connected",_=B=>{if(!(!B&&!w)){w=B!==null;try{e()?.(B)}catch(x){console.error('[RemoteControl] customer callback "onPlaybackStats" threw:',x)}}},H=()=>{D=!1,S++,clearTimeout(i),l.reset(),_(null)},F=async()=>{if(p||!V())return;if(ut.has(o)){i=setTimeout(()=>{F()},2e3);return}p=!0,ut.add(o);const B=S;try{const x=await o.getStats();if(B!==S||!V())return;const ce=o.getTransceivers().filter(I=>(I.currentDirection==="recvonly"||I.currentDirection==="sendrecv")&&I.receiver.track.readyState!=="ended").map(I=>({trackId:I.receiver.track.id,kind:I.receiver.track.kind,mid:I.mid,display:u.get(I.receiver)}));_(l.read(x,ce,r())),N=!1}catch(x){if(B!==S||!V())return;N||console.warn("[RemoteControl] could not read playback stats:",x),N=!0,l.reset(),_(null)}finally{p=!1,ut.delete(o),D&&V()&&(i=setTimeout(()=>{F()},B===S?2e3:0))}},P=()=>{if(!V()){H();return}D||(D=!0,F())};return document.addEventListener("visibilitychange",P),o.addEventListener("connectionstatechange",P),P(),()=>{E=!0,document.removeEventListener("visibilitychange",P),o.removeEventListener("connectionstatechange",P),H()}}function Xr(t,e){const r=t.createDataChannel("latency-trace-v1",{ordered:!0,negotiated:!0,id:2});let o=!1,u=!1,l=0;return r.onmessage=i=>{if(u)return;let E;try{E=JSON.parse(i.data)}catch(D){console.warn("Invalid latency trace message",D);return}E&&typeof E=="object"&&!Array.isArray(E)&&e(E)},r.onclose=()=>{u=!0,o=!1},{accept(i){o=!u&&i===1},wrap(i){if(!o||i.byteLength===0)return i;const E=new DataView(i),D=E.getUint8(0),p=D===Z.INJECT_MOUSE_EVENT||D===Z.INJECT_MAC_KEY||D===Z.INJECT_MAC_SCROLL,S=i.byteLength===32&&D===Z.INJECT_TOUCH_EVENT&&E.getUint8(1)<=2;if(!p&&!S)return i;const w=new ArrayBuffer(6+i.byteLength),N=new DataView(w);return N.setUint8(0,240),N.setUint8(1,1),N.setUint32(2,++l,!0),new Uint8Array(w,6).set(new Uint8Array(i)),w},close(){u=!0,o=!1,r.onmessage=null,r.onclose=null,r.close()}}}class Qr{generation=0;tail=Promise.resolve();get currentGeneration(){return this.generation}enqueue(e){const r=++this.generation;return this.append(r,e)}enqueueCurrent(e){return this.append(this.generation,e)}append(e,r){const o={generation:e,isCurrent:()=>e===this.generation},u=this.tail.then(()=>r(o));return this.tail=u.catch(()=>{}),u}invalidate(){++this.generation}}function zr(t){if(!t||typeof t!="object")return null;const e=t;if(e.type!=="cameraRequest"||typeof e.active!="boolean")return null;const r={active:e.active};return(e.facingMode==="user"||e.facingMode==="environment")&&(r.facingMode=e.facingMode),r}function Zr(t){const e={frameRate:{ideal:30,max:30}};return t?.facingMode&&(e.facingMode={ideal:t.facingMode}),e}function en(t,e){return!t||t.facingMode!==e.facingMode}function tn(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 rn(t){return{type:"cameraResult",granted:!0,camera:tn(t)}}const se=(...t)=>{window.debugRemoteControl&&console.log(...t)},y=(...t)=>{window.debugRemoteControl&&console.warn(...t)},kt=["click","keydown"],rt=new WeakMap,zt=t=>{rt.get(t)?.()},ht=(t,e)=>{if(rt.has(t)){Promise.resolve(t.play()).catch(()=>{});return}Promise.resolve(t.play()).catch(r=>{if(r?.name!=="NotAllowedError"||t.muted)return;t.muted=!0,Promise.resolve(t.play()).catch(()=>{});const o=t.ownerDocument,u=()=>{l(),t.muted=!1,ht(t,e)},l=()=>{for(const i of kt)o.removeEventListener(i,u,!0);rt.delete(t)};for(const i of kt)o.addEventListener(i,u,!0);rt.set(t,l),e()})},L=(t,e,...r)=>{if(e)try{e(...r)}catch(o){console.error(`[RemoteControl] customer callback "${t}" threw:`,o)}},Zt=t=>t.includes("/android_")?"android":t.includes("/macos_")?"macos":"ios",Ut=(t,e)=>{const r=new URL(t);return r.searchParams.set("token",e),r.toString()},ft=3,nn=1e3,on=15e3,an=3e3,sn=4e3;function Pt(){const t=crypto.getRandomValues(new Uint8Array(16));t[6]=t[6]&15|64,t[8]=t[8]&63|128;const e=Array.from(t,r=>r.toString(16).padStart(2,"0")).join("");return`${e.slice(0,8)}-${e.slice(8,12)}-${e.slice(12,16)}-${e.slice(16,20)}-${e.slice(20)}`}function cn(t){let e={...t};const{url:r,deviceModel:o}=e;let u=e.token;const l=e.watchOnly??!1,i=e.sessionId??Pt(),E=e.platform??Zt(r??"");let D={connection:"idle",videoReady:!1,controlReady:!1,duo:!1,duoState:null};const p=n=>{D={...D,...n},L("onStateChange",e.onStateChange,D)},S=n=>p({videoReady:n}),w=n=>p({duoState:n}),N=n=>p({duoError:n}),V=n=>p({duo:n}),_=n=>se(n);let H=null,F;const P=()=>{F?.(),F=H&&e.onPlaybackStats?jr(H,()=>e.onPlaybackStats,()=>e.jitterBufferTargetMs):void 0},B=new Map,x=new Set,ce=new Set,I=new Map;let Ee=!1;const Be=new Map,pt=(n,f,c)=>{f.stop?.(),f.stop=Jr(n,c,d=>y("Video playback fallback:",d))},Ke=new Set;let Ae=null;const mt=n=>{n.srcObject=Ae,Ae&&ht(n,()=>L("onSpeakerBlocked",e.onSpeakerBlocked))},er=()=>{Be.clear(),Ae=null;for(const n of Ke)n.srcObject=null;for(const[n,f]of B)f.clear?.(),f.stop?.(),f.stop=void 0,n.srcObject=null};let he=!1,Me=!1,xe=0,g=null,pe=null;const Ct=()=>{E!=="ios"||!pe||pe!==g||pe.readyState===WebSocket.OPEN&&pe.send(JSON.stringify({type:"speakerAudio",sessionId:i,enabled:!(e.speakerMuted??!0)}))};let R=null,W=null,We=null,me,ve,we,qe,Ce,de=0,Ve=0,re=!1,ue=null,Q=null,fe;const nt=new Qr;let Ne=null,$e=null,it=!l&&(e.microphoneEnabled??!1),ot=!1,be=null,te=null,He=0,Ot=Promise.resolve(),Oe=null,Ye=!1,ne=new Map,ee=new Map,le=new Map,ie=new Map,$=null,Ie=null,Dt=0;const Je=n=>{if(n===null&&Ie===null)return;Ie=n;const f=++Dt;queueMicrotask(()=>{f===Dt&&L("onAxSnapshotChange",e.onAxSnapshotChange,n)})};let De=null,_e=new Map;const tr=(n,f)=>new Promise((c,d)=>{if(l){d(new Error("Device is watch-only"));return}const K=g;if(!K||K.readyState!==WebSocket.OPEN){d(new Error("Simulator disconnected"));return}const m=Pt(),C=setTimeout(()=>{_e.delete(m),d(new Error("Device control timed out"))},5e3);_e.set(m,{resolve:c,reject:d,timer:C}),K.send(JSON.stringify({type:n,id:m,...f}))}),ge=n=>{De!==n&&(De=n,p({connection:n}),L("onConnectionStateChange",e.onConnectionStateChange,n))},oe=n=>{l||!W||W.readyState!=="open"||(W.send(We?.wrap(n)??n),$?.bumpActivity())},rr=()=>{g&&g.readyState===WebSocket.OPEN&&g.send(JSON.stringify({type:"keepAlive",sessionId:i}))},_t=()=>{me&&window.clearInterval(me),me=window.setInterval(rr,1e4)},Re=()=>{me&&(window.clearInterval(me),me=void 0)},Ge=()=>{ve&&(window.clearTimeout(ve),ve=void 0)},je=()=>{we&&(window.clearTimeout(we),we=void 0)},ke=()=>{qe&&(window.clearInterval(qe),qe=void 0)},Ue=()=>{Ce!==void 0&&(window.clearTimeout(Ce),Ce=void 0)},nr=()=>{Ye||(Ye=!0,ke(),S(!0),ge("connected"))},J=n=>{for(const f of n.getTracks())try{f.stop()}catch(c){y("track.stop() failed:",c)}},ir=()=>{const n=Q;n&&(Q=null,J(n))},gt=n=>{const f=Ot.then(n).catch(c=>{y("microphone operation failed:",c)});return Ot=f,f},at=()=>it||ot,Tt=n=>{const f=`ui-mic-${Date.now()}-${Math.random().toString(36).substring(2,9)}`;Oe=f,n.send(JSON.stringify({type:"microphoneStart",id:f}))},st=()=>gt(()=>or()),or=async()=>{const n=He,f=()=>n===He&&at(),c=h=>{L("onMicrophoneStateChange",e.onMicrophoneStateChange,{active:!1,error:h})};if(!f())return;const d=g,K=be;if(!d||d.readyState!==WebSocket.OPEN||!K||te)return;if(!navigator.mediaDevices||typeof navigator.mediaDevices.getUserMedia!="function"){console.warn("[RemoteControl] navigator.mediaDevices.getUserMedia unavailable. getUserMedia requires a secure context (https or http://localhost)."),c("Microphone capture requires a secure context (https)");return}let m=null;try{m=await navigator.mediaDevices.getUserMedia({audio:!0,video:!1})}catch(h){console.warn("[RemoteControl] microphone getUserMedia denied/failed:",h)}if(!f()){m&&J(m);return}if(!m){c("Microphone permission denied or no device available");return}const C=m.getAudioTracks()[0]??null;if(!C){J(m),c("Captured stream has no audio track");return}try{await K.replaceTrack(C)}catch(h){y("replaceTrack(audioTrack) failed:",h),J(m),c("Failed to attach the microphone track to the connection");return}if(!f()){try{await K.replaceTrack(null)}catch(h){y("replaceTrack(null) on stale mic attach failed:",h)}J(m);return}te=m,C.onended=()=>{te===m&&Xe("microphone capture ended by the browser")},Tt(d),L("onMicrophoneStateChange",e.onMicrophoneStateChange,{active:!0,label:C.label||void 0})},Xe=n=>(++He,Oe=null,gt(async()=>{const f=be,c=te;if(te=null,f&&c)try{await f.replaceTrack(null)}catch(K){y("replaceTrack(null) on mic detach failed:",K)}c&&J(c);const d=g;if(c&&d&&d.readyState===WebSocket.OPEN){const K=`ui-mic-${Date.now()}-${Math.random().toString(36).substring(2,9)}`;d.send(JSON.stringify({type:"microphoneStop",id:K}))}(c||n)&&L("onMicrophoneStateChange",e.onMicrophoneStateChange,{active:!1,...n!==void 0&&{error:n}})})),yt=(n,f)=>{let c;try{c=rn(f),console.info(`[RemoteControl] camera capture: ${c.camera?.width}x${c.camera?.height} @ ${c.camera?.frameRate??"?"}fps`+(c.camera?.label?` — ${c.camera.label}`:""))}catch(d){y("getSettings() on outbound camera track failed:",d),c={type:"cameraResult",granted:!0,camera:{label:f.label||void 0}}}n.send(JSON.stringify(c)),L("onCameraDemandChange",e.onCameraDemandChange,!0,!0,c.camera)},ar=n=>{if(!n)return;const f=n.indexOf("/"),d=(f>=0?n.slice(f+1):n).toUpperCase();return d==="HEVC"?"H265":d},sr=async()=>{const n=ue,f=e.onCameraStats;if(!n||!f)return;let c;try{c=await n.getStats()}catch{return}let d,K,m;if(c.forEach(U=>{U.type==="outbound-rtp"&&U.kind==="video"?d=U:U.type==="remote-inbound-rtp"&&U.kind==="video"&&(m=U)}),d?.codecId){const U=c.get(d.codecId);U&&(K=U.mimeType)}if(!d)return;const C=d.timestamp??Date.now(),h=$e;let k,b,G;if(h&&C>h.timestamp){const U=(C-h.timestamp)/1e3;if(typeof d.framesEncoded=="number"&&typeof h.framesEncoded=="number"&&(k=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"&&m&&typeof m.packetsLost=="number"&&typeof h.packetsLost=="number"){const A=d.packetsSent-h.packetsSent,ze=m.packetsLost-h.packetsLost;A>0&&(G=Math.max(0,Math.min(100,ze/A*100)))}}$e={timestamp:C,framesEncoded:d.framesEncoded,bytesSent:d.bytesSent,packetsSent:d.packetsSent,packetsLost:m?.packetsLost};const v={codec:ar(K),encoderImplementation:d.encoderImplementation,hardwareAccelerated:typeof d.powerEfficientEncoder=="boolean"?d.powerEfficientEncoder:void 0,framesPerSecond:k,framesEncoded:d.framesEncoded,bitrateBps:b,width:d.frameWidth,height:d.frameHeight,qualityLimitationReason:d.qualityLimitationReason,rttMs:typeof m?.roundTripTime=="number"?m.roundTripTime*1e3:void 0,packetsLostPct:G};L("onCameraStats",e.onCameraStats,v)},St=()=>{Ne===null&&($e=null,Ne=setInterval(()=>{sr()},1e3))},Qe=()=>{Ne!==null&&(clearInterval(Ne),Ne=null),$e=null,L("onCameraStats",e.onCameraStats,null)},cr=(n,f,c,d)=>nt.enqueue(async({isCurrent:K})=>{const m=()=>K()&&d()&&g===f&&ue===c;if(!m())return;if(!n.active){const v=Q;try{await c.replaceTrack(null)}catch(U){y("replaceTrack(null) on camera detach failed:",U)}if(Q===v&&(Q=null,fe=void 0,v&&J(v)),Qe(),!m())return;L("onCameraDemandChange",e.onCameraDemandChange,!1);return}L("onCameraDemandChange",e.onCameraDemandChange,!0);const C=Q,h=C?.getVideoTracks()[0],k=fe;if(h?.readyState==="live"&&k&&!en(k,n)){fe=n,yt(f,h),St();return}if(C){try{await c.replaceTrack(null)}catch(v){y("replaceTrack(null) before camera switch failed:",v)}if(Q===C&&(Q=null,fe=void 0,J(C)),Qe(),!m())return}if(!navigator.mediaDevices||typeof navigator.mediaDevices.getUserMedia!="function"){if(console.warn("[RemoteControl] navigator.mediaDevices.getUserMedia unavailable. getUserMedia requires a secure context (https or http://localhost). Replying cameraResult granted=false so limulator falls back to black frames."),!m())return;f.send(JSON.stringify({type:"cameraResult",granted:!1})),L("onCameraDemandChange",e.onCameraDemandChange,!0,!1);return}let b=null;try{b=await navigator.mediaDevices.getUserMedia({video:Zr(n),audio:!1})}catch(v){console.warn("[RemoteControl] getUserMedia denied/failed:",v)}if(!m()){b&&J(b);return}if(!b){f.send(JSON.stringify({type:"cameraResult",granted:!1})),L("onCameraDemandChange",e.onCameraDemandChange,!0,!1);return}const G=b.getVideoTracks()[0]??null;if(!G){if(J(b),!m())return;f.send(JSON.stringify({type:"cameraResult",granted:!1})),L("onCameraDemandChange",e.onCameraDemandChange,!0,!1);return}try{G.contentHint="motion"}catch{}try{await c.replaceTrack(G)}catch(v){if(y("replaceTrack(videoTrack) failed:",v),J(b),!m())return;f.send(JSON.stringify({type:"cameraResult",granted:!1})),L("onCameraDemandChange",e.onCameraDemandChange,!0,!1);return}if(!m()){try{await c.replaceTrack(null)}catch(v){y("replaceTrack(null) for stale camera attach failed:",v)}J(b);return}try{const v=c.getParameters();(!v.encodings||v.encodings.length===0)&&(v.encodings=[{}]),v.encodings[0].maxBitrate=8e6,v.encodings[0].maxFramerate=30,v.degradationPreference="maintain-framerate",await c.setParameters(v)}catch(v){y("setParameters on outbound camera failed:",v)}if(!m()){try{await c.replaceTrack(null)}catch(v){y("replaceTrack(null) for stale camera finalize failed:",v)}J(b);return}Q=b,fe=n,G.onended=()=>{Q===b&&nt.enqueueCurrent(async({isCurrent:v})=>{if(!(!v()||Q!==b||!d()||g!==f||ue!==c)){try{await c.replaceTrack(null)}catch(U){y("replaceTrack(null) after camera ended failed:",U)}!v()||Q!==b||!d()||g!==f||ue!==c||(Q=null,fe=void 0,J(b),Qe(),f.send(JSON.stringify({type:"cameraResult",granted:!1})),L("onCameraDemandChange",e.onCameraDemandChange,!0,!1))}}).catch(v=>y("camera ended cleanup failed:",v))},m()&&(yt(f,G),St())}),Te=()=>{for(const n of ce)n();ce.clear();for(const n of I.values())clearTimeout(n);I.clear();for(const n of ee.values())n(new Error("Simulator disconnected"));for(const n of ie.values())n(new Error("Simulator disconnected"));ee.clear(),ne.clear(),ie.clear(),le.clear(),F?.(),F=void 0,er(),H=null;for(const n of _e.values())clearTimeout(n.timer),n.reject(new Error("Simulator disconnected"));_e.clear(),w(null),p({controlReady:!1,videoReady:!1}),je(),Ue(),ke(),$&&($.stop(),$=null),Ie!==null&&Je(null),nt.invalidate(),Qe(),ir(),fe=void 0,ue=null,++He,ot=!1,Oe=null,te&&(J(te),te=null,L("onMicrophoneStateChange",e.onMicrophoneStateChange,{active:!1})),be=null,pe=null,g&&(g.onopen=null,g.onmessage=null,g.onerror=null,g.onclose=null,g.close(),g=null),We?.close(),We=null,R&&(R.onconnectionstatechange=null,R.oniceconnectionstatechange=null,R.ontrack=null,R.onicecandidate=null,R.close(),R=null),W&&(W.onopen=null,W.onclose=null,W.onerror=null,W.close(),W=null)},Kt=()=>{document.hidden?Re():_t()},lr=async()=>{if(e.transport)return e.transport.isTerminated?.()??!1;if(typeof navigator<"u"&&navigator.onLine===!1)return!1;let n;try{const d=new URL(r);d.protocol=d.protocol==="wss:"?"https:":d.protocol==="ws:"?"http:":d.protocol,n=Ut(d.toString(),u)}catch{return!1}const f=new AbortController,c=window.setTimeout(()=>f.abort(),sn);try{return(await fetch(n,{method:"GET",cache:"no-store",signal:f.signal})).status===404}catch{return!1}finally{window.clearTimeout(c)}},dr=()=>{he||(he=!0,de+=1,Ge(),je(),Ue(),Te(),_("Instance terminated"),Re(),ge("terminated"),L("onTerminated",e.onTerminated))},ur=()=>{if(he||Me)return;Me=!0;const n=xe;lr().catch(()=>!1).then(f=>{n===xe&&(Me=!1,f&&dr())})},ye=(n,f)=>{if(he||f!==de)return;if(ur(),re){if(e.autoReconnect===!1){_(`Connection failed after it was established: ${n}`),Re(),ge("failed"),Te();return}_(`Reconnecting after established session dropped: ${n}`),re=!1,Ve=-1}Ge();const c=Ve+1;if(c>=ft){_(`Connection failed after ${ft} attempts: ${n}`),Re(),ge("failed"),Te();return}_(`Retrying connection (${c+1}/${ft})`),ge("reconnecting"),Te(),ve=window.setTimeout(()=>{ve=void 0,f===de&&At(c)},nn)},At=async(n=0)=>{const{openUrl:f,axPollIntervalMs:c,axMaxBackoffMs:d,androidElementTreeOptions:K}=e;if(he)return;const m=de+1;de=m,Ve=n,re=!1,n===0&&De!=="reconnecting"&&ge("connecting"),Ge(),je(),ke(),Ye=!1,S(!1),Te();const C=()=>m===de;we=window.setTimeout(()=>{we=void 0,!(!C()||re)&&ye("Connection did not succeed within 15 seconds",m)},on);try{const h=e.transport?await e.transport.connect():new WebSocket(Ut(r,u));if(!C()){h.close();return}if(g=h,await new Promise((O,s)=>{let Y=!1;const q=()=>M(()=>s(new Error("Connection stopped")));ce.add(q);const T=window.setTimeout(()=>M(()=>s(new Error("WebSocket connection timeout"))),3e4),M=z=>{Y||(Y=!0,ce.delete(q),window.clearTimeout(T),z())};h.onopen=()=>{!C()||g!==h||M(O)},h.onerror=z=>{!C()||g!==h||(_("WebSocket error: "+z),M(()=>s(new Error("WebSocket connection failed"))))},h.onclose=()=>{!C()||g!==h||(_("WebSocket closed"),M(()=>s(new Error("WebSocket closed before connection was established"))))},h.readyState===WebSocket.OPEN?M(O):h.readyState!==WebSocket.CONNECTING&&M(()=>s(new Error("WebSocket is closed")))}),!C()||g!==h)return;h.onerror=O=>{!C()||g!==h||_("WebSocket error: "+O)},h.onclose=()=>{!C()||g!==h||_("WebSocket closed")};const k=new Promise((O,s)=>{let Y=!1;const q=()=>T(()=>s(new Error("Connection stopped")));ce.add(q);const T=j=>{Y||(Y=!0,ce.delete(q),window.clearTimeout(M),h.removeEventListener("message",z),j())},M=window.setTimeout(()=>T(()=>s(new Error("RTCConfiguration timeout"))),3e4),z=j=>{if(!(!C()||g!==h))try{const X=JSON.parse(j.data);if(X.type==="signalingError"&&X.requestType==="requestRtcConfiguration"&&X.sessionId===i){const pr=typeof X.error=="string"?X.error:"Unable to load streaming configuration";T(()=>s(new Error(pr)))}else X.type==="rtcConfiguration"&&T(()=>O({rtcConfiguration:X.rtcConfiguration,cameraSupported:X.cameraSupported===!0,foldSupported:X.foldSupported===!0}))}catch(X){console.error("Error handling RTC configuration:",X),T(()=>s(X))}};h.addEventListener("message",z),h.send(JSON.stringify({type:"requestRtcConfiguration",sessionId:i}))}),{rtcConfiguration:b,cameraSupported:G,foldSupported:v}=await k;if(!C()||g!==h)return;const U=o==="iphone-duo"||v;V(U);const A=new RTCPeerConnection({...b,iceTransportPolicy:"relay"});R=A;const ze={peer:A,displays:new Map};H=ze,P(),A.addTransceiver("audio",{direction:"recvonly"});const ct=E==="ios",Er=A.addTransceiver("video",{direction:"recvonly"}),hr=U?A.addTransceiver("video",{direction:"recvonly"}):null,Nt=!l&&(E==="ios"||G),lt=Nt?A.addTransceiver("video",{direction:"sendonly"}):null;if(ue=lt?.sender??null,be=(Nt?A.addTransceiver("audio",{direction:"sendonly"}):null)?.sender??null,RTCRtpReceiver.getCapabilities){const O=RTCRtpReceiver.getCapabilities("video");if(O&&O.codecs){const Y=O.codecs.sort((q,T)=>{const M=z=>{const j=z.mimeType.toLowerCase();return j.includes("h265")||j.includes("hevc")?1:j.includes("h264")||j.includes("avc")?2:3};return M(q)-M(T)});Er.setCodecPreferences(Y),hr?.setCodecPreferences(Y),se("Set codec preferences:",Y.map(q=>q.mimeType).join(", "))}}if(lt&&RTCRtpSender.getCapabilities){const O=RTCRtpSender.getCapabilities("video");if(O&&O.codecs){const s=new Set(["42e01f","42e028","640c1f"]),Y=T=>{const M=T.mimeType.toLowerCase(),j=(T.sdpFmtpLine||"").toLowerCase().match(/profile-level-id=([0-9a-f]{6})/),X=j?j[1]:"";return M==="video/h265"||M==="video/hevc"?1:M==="video/h264"&&s.has(X)?2:M==="video/h264"?3:M==="video/vp9"?4:M==="video/vp8"?5:M==="video/rtx"||M==="video/red"||M==="video/ulpfec"?0:6},q=[...O.codecs].sort((T,M)=>Y(T)-Y(M));try{lt.setCodecPreferences(q),se("Outbound camera codec preferences:",q.map(T=>`${T.mimeType}${T.sdpFmtpLine?`[${T.sdpFmtpLine}]`:""}`).join(", "))}catch(T){y("Failed to set outbound camera codec preferences:",T)}}}const ae=A.createDataChannel("control",{ordered:!0,negotiated:!0,id:1});W=ae;const dt=!l&&!U&&e.onTrace?Xr(A,O=>{C()&&R===A&&L("onTrace",e.onTrace,O)}):null;if(We=dt,ae.onopen=()=>{if(!C()||W!==ae||g!==h)return;re=!0,p({controlReady:!l}),je(),_("Control channel opened"),U&&h.send(JSON.stringify({type:"getFoldState",id:"duo-capabilities"})),!$&&E!=="macos"&&($=new $r({platform:E,baseIntervalMs:c,maxBackoffMs:d,androidElementTreeOptions:K,send:s=>{if(!g||g.readyState!==WebSocket.OPEN)return!1;try{return g.send(JSON.stringify(s)),!0}catch{return!1}},onSnapshot:Je,onStatusChange:(s,Y)=>{L("onAxStatusChange",e.onAxStatusChange,s,Y)}}),(e.inspectMode===!0||e.inspectMode==="hover-only")&&$.start());const O=()=>{!C()||Ye||W!==ae||g!==h||h.readyState!==WebSocket.OPEN||h.send(JSON.stringify({type:"requestFrame",sessionId:i}))};if(O(),ke(),qe=window.setInterval(()=>{if(!C()||Ye||W!==ae||g!==h||h.readyState!==WebSocket.OPEN){ke();return}O()},250),!l&&f){try{const s=decodeURIComponent(f);_("Opening URL"),h.send(JSON.stringify({type:"openUrl",url:s,sessionId:i}))}catch(s){console.error({error:s},"Error decoding URL, falling back to the original URL"),h.send(JSON.stringify({type:"openUrl",url:f,sessionId:i}))}$?.bumpActivity()}},ae.onclose=()=>{!C()||W!==ae||(p({controlReady:!1}),_("Control channel closed"))},ae.onerror=O=>{!C()||W!==ae||(console.error("Control channel error:",O),_("Control channel error: "+O))},A.onconnectionstatechange=()=>{!C()||R!==A||(_("Connection state: "+A.connectionState),A.connectionState==="failed"&&re&&ye("WebRTC connection entered failed state",m))},A.oniceconnectionstatechange=()=>{if(!C()||R!==A)return;const O=A.iceConnectionState;if(_("ICE state: "+O),O==="connected"||O==="completed"){Ue(),at()&&!te&&st();return}if(O==="failed"){Ue(),re&&ye("ICE connection entered failed state",m);return}O==="disconnected"&&re&&e.autoReconnect!==!1&&Ce===void 0&&(Ce=window.setTimeout(()=>{Ce=void 0,!(!C()||R!==A)&&A.iceConnectionState==="disconnected"&&ye("ICE stayed disconnected past grace period",m)},an))},A.ontrack=O=>{if(!C()||R!==A)return;It(O.receiver,e.jitterBufferTargetMs);const s=O.track.id==="duo-inner"||O.streams.some(Y=>Y.id==="duo-inner");if(O.track.kind==="video"&&ze.displays.set(O.receiver,s?"inner":"primary"),_("Received remote track: "+O.track.kind),O.track.kind==="video"){const Y=s?"inner":"primary",q=U?new MediaStream([O.track]):O.streams[0]??new MediaStream([O.track]);Be.set(Y,q);for(const[T,M]of B)M.display===Y&&pt(T,M,q)}if(O.track.kind==="audio"&&ct){Ae=new MediaStream([O.track]);for(const Y of Ke)mt(Y)}},A.onicecandidate=O=>{if(!(!C()||R!==A||g!==h))if(O.candidate&&h.readyState===WebSocket.OPEN){const s={type:"candidate",candidate:O.candidate.candidate,sdpMid:O.candidate.sdpMid,sdpMLineIndex:O.candidate.sdpMLineIndex,sessionId:i};h.send(JSON.stringify(s)),_("Sent ICE candidate")}else _("ICE candidate gathering completed")},h.onmessage=async O=>{if(!C()||g!==h)return;let s;try{s=JSON.parse(O.data)}catch(Y){y("Error parsing message:",Y);return}if(!$?.handleMessage(s))switch(_("Received: "+s.type),s.type){case"performActionsResult":case"foldStateResult":case"foldStateChanged":{if(!U)break;s.state?(w(s.state),N(void 0)):s.id==="duo-capabilities"&&N(s.error||"This instance does not support native iPhone Duo displays.");const T=_e.get(s.id);T&&(clearTimeout(T.timer),_e.delete(s.id),s.error?T.reject(new Error(s.error)):T.resolve());break}case"signalingError":{if(s.requestType!=="offer"||s.sessionId!==i)break;const T=typeof s.error=="string"?s.error:"Unable to establish the streaming connection";_("Error: "+T),ye(T,m);break}case"answer":if(!R||R!==A){_("No peer connection, skipping answer");break}if(dt?.accept(s.latencyTraceVersion),await A.setRemoteDescription(new RTCSessionDescription({type:"answer",sdp:s.sdp})),!C()||R!==A)return;_("Set remote description"),pe=h,(e.speakerMuted??!0)||Ct();break;case"candidate":if(!R||R!==A){_("No peer connection, skipping candidate");break}if(await A.addIceCandidate(new RTCIceCandidate({candidate:s.candidate,sdpMid:s.sdpMid,sdpMLineIndex:s.sdpMLineIndex})),!C()||R!==A)return;_("Added ICE candidate");break;case"screenshot":case"screenshotResult":{if(typeof s.id!="string"){y("Received invalid screenshot success message:",s);break}const T=ln(s);if(T){const j=ee.get(s.id);if(typeof j!="function"){y(`Received screenshot error for unknown or handled id: ${s.id}`);break}y(`Received screenshot error for id ${s.id}: ${T}`),j(new Error(T)),ne.delete(s.id),ee.delete(s.id),clearTimeout(I.get(s.id)),I.delete(s.id);break}const M=dn(s);if(!M){y("Received screenshot message without image data:",s);break}const z=ne.get(s.id);if(typeof z!="function"){y(`Received screenshot data for unknown or handled id: ${s.id}`);break}se(`Received screenshot data for id ${s.id}`),z(M),ne.delete(s.id),ee.delete(s.id),clearTimeout(I.get(s.id)),I.delete(s.id);break}case"screenshotError":if(typeof s.id!="string"||typeof s.message!="string"){y("Received invalid screenshot error message:",s);break}const Y=ee.get(s.id);if(typeof Y!="function"){y(`Received screenshot error for unknown or handled id: ${s.id}`);break}y(`Received screenshot error for id ${s.id}: ${s.message}`),Y(new Error(s.message)),ne.delete(s.id),ee.delete(s.id),clearTimeout(I.get(s.id)),I.delete(s.id);break;case"cameraRequest":{const T=ue;if(!T)break;const M=zr(s);if(!M){y("Received invalid cameraRequest:",s);break}console.info("[RemoteControl] cameraRequest received:",M.active,M.facingMode),await cr(M,h,T,C);break}case"microphoneRequest":{if(!be)break;const T=s.active===!0;if(ot=T,console.info("[RemoteControl] microphoneRequest received, active=",T),!T){it||await Xe();break}if(te){Tt(h);break}await st();break}case"microphoneStartResult":{if(Oe===null||s.id!==Oe)break;Oe=null,typeof s.error=="string"&&(console.warn("[RemoteControl] microphoneStart rejected by host:",s.error),Xe(s.error));break}case"terminateAppResult":if(typeof s.id!="string"){y("Received invalid terminateApp result message:",s);break}if(typeof s.error=="string"){const T=ie.get(s.id);if(typeof T!="function"){y(`Received terminateApp error for unknown or handled id: ${s.id}`);break}y(`Received terminateApp error for id ${s.id}: ${s.error}`),T(new Error(s.error)),le.delete(s.id),ie.delete(s.id),clearTimeout(I.get(s.id)),I.delete(s.id);break}const q=le.get(s.id);if(typeof q!="function"){y(`Received terminateApp result for unknown or handled id: ${s.id}`);break}se(`Received terminateApp success for id ${s.id}`),q(),le.delete(s.id),ie.delete(s.id),clearTimeout(I.get(s.id)),I.delete(s.id);break;default:y(`Received unhandled message type: ${s.type}`,s);break}},R===A){const O=await A.createOffer({offerToReceiveVideo:!0,offerToReceiveAudio:ct});if(!C()||R!==A||(await A.setLocalDescription(O),!C()||R!==A))return;C()&&g===h&&h.readyState===WebSocket.OPEN&&h.send(JSON.stringify({type:"offer",...U?{displayStreams:!0}:{},...ct?{speakerAudio:!0}:{},...dt?{latencyTraceVersion:1}:{},sdp:O.sdp,sessionId:i})),_("Sent offer")}}catch(h){if(!C()||h instanceof Error&&h.message==="Connection stopped")return;const k=h instanceof Error?h.message:String(h);_("Error: "+k),ye(k,m)}},Mt=()=>{if(Ee)throw new Error("Device stream is disposed");xe++,Me=!1,Je(null),De!=="reconnecting"&&(De=null),document.addEventListener("visibilitychange",Kt),document.hidden||_t(),he=!1,At(0)},vt=()=>{xe++,Me=!1,Re(),document.removeEventListener("visibilitychange",Kt),de+=1,Ve=0,re=!1,Ge(),Ue(),Te(),De=null,p({connection:"idle",videoReady:!1,controlReady:!1}),_("Stopped")},fr=n=>{if(Ee)throw new Error("Device stream is disposed");if(Ke.has(n))throw new Error("Audio element is already attached");Ke.add(n),Ae&&mt(n);let f=!1;const c=()=>{f||(f=!0,x.delete(c),Ke.delete(n),zt(n),n.srcObject=null)};return x.add(c),c},wt=(n,f="primary")=>{if(Ee)throw new Error("Device stream is disposed");if(B.has(n))throw new Error("Video element is already attached");const c={display:f};B.set(n,c);const d=()=>{f==="primary"&&Be.has(f)&&nr()};n.addEventListener("loadeddata",d);const K=Be.get(f);K&&pt(n,c,K);let m=!1;const C=()=>{m||(m=!0,x.delete(C),n.removeEventListener("loadeddata",d),c.stop?.(),B.delete(n),n.srcObject=null)};return x.add(C),C};return{start:Mt,stop:vt,attachVideo:wt,attachAudio:fr,attachFrameSink:(n,f="primary")=>{const c=document.createElement("video");c.muted=!0,c.playsInline=!0,c.autoplay=!0;const d=wt(c,f);let K=!1,m=0,C=0;const h=()=>{c.cancelVideoFrameCallback?.(m),cancelAnimationFrame(C)},k=()=>{K||!c.srcObject||(c.readyState>=2&&c.videoWidth>0&&L("present",(...v)=>n.present(...v),c,c.videoWidth,c.videoHeight,f),!(K||!c.srcObject)&&(c.requestVideoFrameCallback?m=c.requestVideoFrameCallback(k):C=requestAnimationFrame(k)))},b=()=>{h(),k()};B.get(c).clear=h,c.addEventListener("loadeddata",b);const G=()=>{K||(K=!0,x.delete(G),h(),c.removeEventListener("loadeddata",b),d(),c.remove())};return x.delete(d),x.add(G),c.readyState>=2&&b(),G},dispose:()=>{if(!Ee){Ee=!0,vt();for(const n of x)n();x.clear()}},getState:()=>D,updateOptions:({token:n,...f})=>{if(Ee)throw new Error("Device stream is disposed");n!==void 0&&!e.transport&&(u=n);const c=e;if(e={...e,...f},c.jitterBufferTargetMs!==e.jitterBufferTargetMs)for(const d of R?.getTransceivers()??[])(d.currentDirection==="recvonly"||d.currentDirection==="sendrecv")&&It(d.receiver,e.jitterBufferTargetMs);!!c.onPlaybackStats!=!!e.onPlaybackStats&&P(),!!c.microphoneEnabled!=!!e.microphoneEnabled&&(it=!l&&(e.microphoneEnabled??!1),at()?st():Xe()),(c.speakerMuted??!0)!==(e.speakerMuted??!0)&&Ct(),!!c.inspectMode!=!!e.inspectMode&&(e.inspectMode?$?.start():($?.stop(),Ie!==null&&Je(null)))},sendControl:oe,sendTouch:(n,f,c,d,K,m=0)=>oe(Ft(n==="begin"?0:n==="end"?1:2,m,d,K,f,c,n==="end"?0:1)),sendText:n=>oe(Bt(n)),sendDisplayTouch:(n,f,c,d)=>oe(Vt(n,f,c,d)),sendDuoControl:tr,pressButton:n=>{const f={home:3,back:4,recents:187,power:26}[n];oe(Ze(0,f,0,0)),oe(Ze(1,f,0,0))},rotate:()=>oe(new Uint8Array([11]).buffer),bumpActivity:()=>$?.bumpActivity(),getAxStatus:()=>$?.getStatus()??"idle",openUrl:n=>{if(!l){if(!g||g.readyState!==WebSocket.OPEN){y("WebSocket not open, cannot send open_url command.");return}try{const f=decodeURIComponent(n);_("Opening URL"),g.send(JSON.stringify({type:"openUrl",url:f,sessionId:i}))}catch(f){y("Error decoding or sending URL :",{error:f,url:n}),g.send(JSON.stringify({type:"openUrl",url:n,sessionId:i}))}$?.bumpActivity()}},sendKeyEvent:n=>{if(!W||W.readyState!=="open"){y("Data channel not ready for imperative key command:",W?.readyState);return}if(E==="macos"){const m=Et(n.code);if(m===void 0){y(`Unknown event.code for imperative command: ${n.code}`);return}const C=[[n.metaKey,"Meta"],[n.ctrlKey,"Control"],[n.altKey,"Alt"],[n.shiftKey,"Shift"]].filter(([k,b])=>k&&!n.code.startsWith(b)).map(([,k])=>Et(`${k}Left`)),h=(k,b)=>oe(xt(k,b));if(n.type==="keydown"){for(const k of C)h(Pe.DOWN,k);h(Pe.DOWN,m)}else{h(Pe.UP,m);for(const k of[...C].reverse())h(Pe.UP,k)}return}const f=Lt[n.code];if(!f){y(`Unknown event.code for imperative command: ${n.code}`);return}let c=a.META_NONE;n.shiftKey&&(c|=a.META_SHIFT_ON),n.altKey&&(c|=a.META_ALT_ON),n.ctrlKey&&(c|=a.META_CTRL_ON),n.metaKey&&(c|=a.META_META_ON);const d=n.type==="keydown"?a.ACTION_DOWN:a.ACTION_UP;se(`Sending Imperative Key Command: code=${n.code}, keycode=${f}, action=${d}, meta=${c}`);const K=Ze(d,f,0,c);K&&oe(K)},screenshot:n=>new Promise((f,c)=>{if(!g||g.readyState!==WebSocket.OPEN)return y("WebSocket not open, cannot send screenshot command."),c(new Error("WebSocket is not connected or connection is not open."));const d=`ui-ss-${Date.now()}-${Math.random().toString(36).substring(2,9)}`,K={type:n?"screenshotDisplay":"screenshot",...n?{display:n}:{},id:d};ne.set(d,f),ee.set(d,c),se("Sending screenshot request:",K);try{g.send(JSON.stringify(K))}catch(m){y("Failed to send screenshot request immediately:",m),ne.delete(d),ee.delete(d),c(m);return}I.set(d,setTimeout(()=>{I.delete(d),ne.has(d)&&(y(`Screenshot request timed out for id ${d}`),ee.get(d)?.(new Error("Screenshot request timed out")),ne.delete(d),ee.delete(d))},3e4))}),terminateApp:n=>l?Promise.reject(new Error("Device is watch-only")):new Promise((f,c)=>{if(!g||g.readyState!==WebSocket.OPEN)return y("WebSocket not open, cannot send terminateApp command."),c(new Error("WebSocket is not connected or connection is not open."));const d=`ui-term-${Date.now()}-${Math.random().toString(36).substring(2,9)}`,K={type:"terminateApp",id:d,bundleId:n};le.set(d,f),ie.set(d,c),se("Sending terminateApp request:",K);try{g.send(JSON.stringify(K))}catch(m){y("Failed to send terminateApp request immediately:",m),le.delete(d),ie.delete(d),c(m);return}$?.bumpActivity(),I.set(d,setTimeout(()=>{I.delete(d),le.has(d)&&(y(`terminateApp request timed out for id ${d}`),ie.get(d)?.(new Error("terminateApp request timed out")),le.delete(d),ie.delete(d))},3e4))}),reconnect:()=>Mt(),refreshAxTree:async()=>{const n=$;if(!n)throw new Error("Inspect mode is not active");return n.refresh()},getAxSnapshot:()=>Ie}}const ln=t=>typeof t.message=="string"?t.message:typeof t.error=="string"?t.error:null,dn=t=>typeof t.dataUri=="string"?{dataUri:t.dataUri}:typeof t.base64=="string"?t.base64.startsWith("data:")?{dataUri:t.base64}:{dataUri:`data:${t.base64.startsWith("/9j/")?"image/jpeg":"image/png"};base64,${t.base64}`}:null;exports.AMOTION_EVENT=Le;exports.ANDROID_KEYS=a;exports.AX_UNAVAILABLE_ERROR=et;exports.CONTROL_MSG_TYPE=Z;exports.DUO_BUTTONS=Mr;exports.DUO_DIMENSIONS=Tr;exports.DuoButtonSender=vr;exports.DuoTouchController=gr;exports.HingeSender=Ar;exports.MAC_INPUT_ACTION=Pe;exports.axElementAtPoint=Ur;exports.axElementRoleLabel=Xt;exports.axElementSelectorExpression=Pr;exports.axElementSummary=Lr;exports.axElementsEqual=Gt;exports.axSnapshotsEqual=jt;exports.cancelSpeakerRetry=zt;exports.clampAxFrameForScreen=kr;exports.codeMap=Lt;exports.createDeviceStream=cn;exports.createDisplayTouchMessage=Vt;exports.createInjectKeycodeMessage=Ze;exports.createMacKeyMessage=xt;exports.createMacScrollMessage=Dr;exports.createMouseControlMessage=Or;exports.createSetClipboardMessage=Bt;exports.createTouchControlMessage=Ft;exports.createTwoFingerTouchControlMessage=Cr;exports.debugLog=se;exports.debugWarn=y;exports.detectPlatform=Zt;exports.duoDisplayTurns=Wt;exports.duoPointerMode=Kr;exports.flatDisplayTouch=qt;exports.getDuoDisplay=_r;exports.macKeyCodeFor=Et;exports.normalizeAndroidTree=Jt;exports.normalizeIosTree=Ht;exports.panelTouch=Sr;exports.playSpeaker=ht;exports.safeInvoke=L;