@appetize/cli 0.25.0 → 0.26.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,17 @@
1
1
  # @appetize/cli
2
2
 
3
+ ## 0.26.0
4
+
5
+ ### Minor Changes
6
+
7
+ - feat: `shake` shakes the device
8
+
9
+ ## 0.25.1
10
+
11
+ ### Patch Changes
12
+
13
+ - fix: webserver API errors include the webserver's reason
14
+
3
15
  ## 0.25.0
4
16
 
5
17
  ### Minor Changes
@@ -1,4 +1,4 @@
1
- cbor-x 1.6.6
1
+ cbor-x 1.6.8
2
2
  MIT
3
3
 
4
4
  MIT License
package/cli.js CHANGED
@@ -1,12 +1,12 @@
1
1
  #!/usr/bin/env node
2
- import Ye from"sade";import{p as u,a as h,f as R,U as a,d as z,b as Qe,i as et,c as tt,e as nt,r as oe,g as I,h as k,j as ot,D as it,s as st,k as rt,l as ie,m as se,S as U,n as j,o as re,q as F,t as T,u as ae,v as ce,w as pe,x as at,y as ct,z as de,A as pt,B as le,C as dt,E as lt,F as ut,G as ft,H as ue,I as fe,J as mt,K as ht,L as gt,M as wt,N as yt,O as vt}from"./stream-C9RfmvVk.js";import{existsSync as me,openAsBlob as xt,openSync as St,closeSync as bt}from"node:fs";import{basename as C,extname as Et,resolve as he,dirname as Ot,join as x,relative as At}from"node:path";import{writeFile as ge,stat as Pt,rm as It,cp as kt}from"node:fs/promises";import{spawn as Tt}from"node:child_process";import{fileURLToPath as we}from"node:url";import{humanId as $t}from"human-id";import{homedir as Lt}from"node:os";import Dt from"debug";import Nt from"yocto-spinner";import _t from"cli-table3";import"json-rpc-2.0";import"zod/mini";import"stream";import"module";import"node:net";const M=["closed","fullyOpen","partiallyOpen"],ye=["back","menu","unlock","volumeDown","volumeUp"],ve=["home","lock"],xe=[...ve,...ye],B=["down","left","right","up"],Se=[{header:"Target",key:"id"},{header:"App",key:"appId"},{header:"Platform",key:"platform"},{header:"Version",key:"versionName"},{header:"Build",key:"buildNumber"},{header:"Uploaded",key:"created"}];function q({appId:e,buildNumber:t,created:n,id:o,platform:i,versionName:s}){return{appId:e,buildNumber:t,created:n,id:o,platform:i,versionName:s}}const Rt=["app"],zt=10,Ut=[{fields:Se,key:"builds"},{header:"Total",key:"total"},{header:"Next page",key:"nextPage"}];async function jt({options:e,signal:t}){const n=u(e.app,"--app"),o=h(e.limit,"--limit")??zt,i=h(e.page,"--page"),s={limit:String(o)};n!==void 0&&(s.appId=n),i!==void 0&&(s.page=String(i));const r=await R("/api/v2/builds",{commandOptions:e,query:s,signal:t});return{builds:r.builds.map(q),nextPage:r.nextPage,total:r.total}}const Ft=["note","tags"],be=12e4,Ct=2e3,G=[".apk",".apks",".zip",".tar.gz",".tgz"],Mt={".apk":"android",".apks":"android",".tar.gz":"ios",".tgz":"ios",".zip":"ios"},Bt=Se;async function qt({options:e,positionals:[t],progress:n,signal:o}){const i=Zt(t),s=C(t);n.status(`Uploading ${s}`);const r=await Vt(t,i,e,o);if(e.wait!==!0)return n.status(`Uploaded ${s}`),q(r);n.step(`Uploaded ${s}`),n.status("Waiting for build metadata");const p=await Gt(r.id,e,o);return n.status(`Processed ${s}`),q(p)}async function Gt(e,t,n){const o=h(t.timeout,"--timeout")??be,i=Date.now()+o;for(;;){const s=await R(`/api/v2/builds/${e}`,{commandOptions:t,signal:n});if(s.appId!==void 0)return s;if(Date.now()>=i)throw new Error(`Build ${e} is still being processed after ${String(o)}ms; find it with 'appetize build list'`);await z(Ct,n)}}async function Kt(e){if(!me(e))throw new Error(`No build file at ${e}`);return await xt(e)}function Zt(e){const t=e.toLowerCase(),n=G.find(o=>t.endsWith(o));if(n===void 0)throw new a(`Cannot tell the platform of ${C(e)}; upload a ${G.join(", ")} file`);return Mt[n]}async function Vt(e,t,n,o){const i=new FormData;i.set("platform",t);const s=u(n.note,"--note");s!==void 0&&i.set("note",s);const r=u(n.tags,"--tags");return r!==void 0&&i.set("tags",r),i.set("file",await Kt(e),C(e)),await R("/api/v2/builds",{body:i,commandOptions:n,method:"POST",signal:o})}const Wt=["platform"],Xt=[{fields:[{header:"ID",key:"id"},{header:"Name",key:"name"},{header:"Platform",key:"platform"},{header:"OS versions",key:"osVersions"}],key:"devices"}];async function Ht({options:e,signal:t}){const n=Jt(e.platform);return{devices:(await Qe(e,t)).filter(i=>n===void 0||i.platform===n).map(Yt)}}function Jt(e){const t=u(e,"--platform");if(t!==void 0){if(!et(t))throw new a(`--platform expects one of: ${tt.join(", ")}`);return t}}function Yt({id:e,name:t,osVersions:n,platform:o}){return{id:e,name:t,osVersions:n,platform:o}}const Qt="cli-fold",en=async({device:e,positionals:[t]})=>{if(!tn(t))throw new a(`Hinge must be one of: ${M.join(", ")}`);await e.fold(t)};function tn(e){return M.some(t=>t===e)}const nn=async({device:e,options:t,positionals:[n]})=>{await e.gesture(sn(n),on(t))};function on(e){const t=h(e.timeout,"--timeout");return t===void 0?void 0:{timeout:t}}function sn(e){let t;try{t=nt(e)}catch(n){throw n instanceof SyntaxError?new a(n.message):n}if(t.length===0)throw new a("Expected at least one gesture step");return t}const rn="APPETIZE_OUTPUT";function an(e,t,n){return{format:cn(e,t),progress:pn(e,n)}}function K(e,{extension:t,strict:n=!1}){const o=Et(e);if(o==="")return`${e}${t}`;if(n&&o!==t)throw new a(`The output must be a path ending in ${t}`);return e}function cn(e,t){if(e.json===!0)return"json";if(e.json===!1)return"text";const n=process.env[rn]?.trim();return n==="json"||n==="text"?n:t.isTTY===!0?"text":"json"}function pn(e,t){return e.quiet===!0?"silent":t.isTTY===!0&&process.env.TERM!=="dumb"&&!("CI"in process.env)?"interactive":"silent"}const S=["text","testId"],g="select",E={testId:{help:"Test id to match by exact string",suffix:"test-id"},text:{help:'Text to match by exact string or regex (e.g., "Sign in" or "/sign in/i")',suffix:"text"}},Z="index",$="position",V="x",W="y";function Ee(e,{prefix:t=g}={}){return S.reduce((n,o)=>{const{help:i,suffix:s}=E[o];return n.option(`--${d(t,s)}`,i)},e).option(`--${d(t,Z)}`,"Which match when multiple (0-based)")}function X(e,t={}){const{prefix:n=g}=t;return Ee(e,t).option(`--${d(n,$)}`,"Screen position to use as x,y (0-1), e.g., 0.5,0.75").option(`--${d(n,V)}`,"Horizontal position within the element (0-1, outside allowed)").option(`--${d(n,W)}`,"Vertical position within the element (0-1, outside allowed)")}function Oe(e,{prefix:t=g}={}){const n=J(e,t);if(n.length===0)throw new a(`A selector is required: pass one of ${D(S,t)}`);if(n.length>1)throw new a(`Only one selector may be given, got ${D(n,t)}`);const[o]=n,i=$e(e,d(t,E[o].suffix)),s=h(e[d(t,Z)],`--${d(t,Z)}`);switch(o){case"testId":return{by:"testId",index:s,testId:i};case"text":return{by:"text",index:s,text:un(i)}}}function Ae(e){const t=h(e.timeout,"--timeout");return t===void 0?void 0:{timeout:t}}function dn(e,{prefix:t=g}={}){return ke(e,t)?Oe(e,{prefix:t}):void 0}function L(e,{prefix:t=g}={}){return ke(e,t)?Pe(e,{prefix:t}):void 0}function Pe(e,{prefix:t=g}={}){const n=d(t,$),o=e[n],i=Te(e,d(t,V)),s=Te(e,d(t,W));if(o===void 0){if(J(e,t).length===0)throw new a(`A selector is required: pass one of ${O({prefix:t})}`);return{...Oe(e,{prefix:t}),x:i,y:s}}if(J(e,t).length>0)throw new a(`--${n} may not be combined with ${D(S,t)}`);if(i!==void 0||s!==void 0)throw new a(`--${n} may not be combined with --${d(t,V)} or --${d(t,W)}`);return ln($e(e,n),n)}function O(e={}){const{prefix:t=g}=e;return`${D(S,t)}, --${d(t,$)}`}function H(e={}){const{prefix:t=g}=e;return[...Ie(e),d(t,$)]}function Ie({prefix:e=g}={}){return S.map(t=>d(e,E[t].suffix))}function J(e,t){return S.filter(n=>e[d(t,E[n].suffix)]!==void 0)}function d(...e){return e.filter(Boolean).join("-")}function D(e,t){return e.map(n=>`--${d(t,E[n].suffix)}`).join(", ")}function ke(e,t){return Object.entries(e).some(([n,o])=>o!==void 0&&n.startsWith(`${t}-`))}function Te(e,t){return h(e[t],`--${t}`)}function ln(e,t){const n=e.split(",");if(n.length!==2)throw new a(`--${t} expects x,y (0-1), e.g., 0.5,0.75`);const[o,i]=n.map(s=>Number(s.trim()));return{by:"position",x:oe(o,`--${t}`),y:oe(i,`--${t}`)}}function un(e){const t=/^\/(.*)\/([a-z]*)$/s.exec(e);return t?new RegExp(t[1],t[2]):e}function $e(e,t){return I(e[t],`--${t}`)}const fn=Ie(),mn=async({device:e,options:t,positionals:[n]})=>{const o=hn(n),i=dn(t),s=await e.inspect(i,Ae(t)),r=gn(s,t.pretty===!0);await ge(o,r);const p=Buffer.byteLength(r),c=Le(s.roots);return i?{bytes:p,matches:s.roots.length,nodes:c,output:o}:{bytes:p,nodes:c,output:o}};function Le(e){return e.reduce((t,n)=>t+1+Le(n.children),0)}function hn(e="inspect"){return K(e,{extension:".json"})}function gn(e,t){return`${JSON.stringify(e,null,t?2:void 0)}
3
- `}const wn=async({device:e})=>{await e.clearKeychain()},yn=async({device:e,positionals:[t]})=>{await e.open(vn(t))};function vn(e){if(typeof e=="string")try{return new URL(e),e}catch{throw new a("<url> expects a URL, e.g., myapp://orders/42")}throw new a("<url> expects a URL, e.g., myapp://orders/42")}const xn=new Set(xe),Sn=async({device:e,positionals:[t]})=>{if(!bn(t))throw new a(`Button must be one of: ${xe.join(", ")}`);await e.press(t)};function bn(e){return typeof e=="string"&&xn.has(e)}const En=async({control:e,options:t,positionals:[n]})=>{const{path:o}=await e.recordStart({force:t.force===!0,path:An(n)});return{path:o}},On=async({control:e})=>{const{path:t}=await e.recordStop();return{path:t}};function An(e){const t=he(K(e,{extension:".mp4",strict:!0})),n=Ot(t);if(!me(n))throw new a(`No such directory: ${n}`);return t}const Pn=async({device:e,positionals:[t]})=>{if(!In(t))throw new a(`Orientation must be one of: ${k.join(", ")}`);await e.rotate(t)};function In(e){return k.some(t=>t===e)}const kn=async({device:e,positionals:[t]})=>{const n=await e.screenshot(),o=$n(n.mimeType,t);return await ge(o,n.data),{bytes:n.data.byteLength,output:o}};function Tn(e){const t=e.split("/").at(1);return`.${t==="jpeg"?"jpg":t??"png"}`}function $n(e,t="screenshot"){return K(t,{extension:Tn(e)})}function Ln(e){const t=we(new URL("./daemon.js",import.meta.url)),n=St(ot(e.sessionId),"a"),o=Tt(process.execPath,[t],{detached:!0,env:{...process.env,[it]:st(e),DEBUG:Dn(process.env.DEBUG)},stdio:["ignore",n,n]});if(bt(n),o.unref(),o.pid===void 0)throw new Error("Failed to spawn the session daemon");return o.pid}function Dn(e){return e?`${e},appetize:daemon`:"appetize:daemon"}const Nn=/^[a-z0-9](?:[a-z0-9._-]{0,62}[a-z0-9])?$/i;function _n(){return $t({capitalize:!1,separator:"-"})}function Rn(e){if(!Nn.test(e))throw new a('--session-id must use letters, digits, ".", "-" or "_"');return e}const De=1e4;function Ne(e){if(!rt(e))return!1;try{process.kill(e.pid,"SIGTERM")}catch{}return!0}async function _e(e,t){(Ne(e)||Un(e))&&await zn(e,t)}async function zn({pid:e,sessionId:t},n){const o=se(e);try{await z(De,AbortSignal.any([n,o]))}catch(i){if(o.aborted||!ie(e))return;throw i}throw new U(`Session ${t} did not stop in time`,{sessionId:t})}function Un({endedAt:e,pid:t}){return e!==void 0&&Date.now()-Date.parse(e)<De&&ie(t)}const jn=["device-android-shell","device-appearance","device-font-size","device-ios-keyboards","device-locale","device-location","device-orientation","device-os-version","device-timezone"];function Fn(e,t){const n=j({shell:u(e["device-android-shell"],"--device-android-shell"),softKeyboard:re(e["device-android-soft-keyboard"],{defaultValue:!0})}),o=j({autocorrect:re(e["device-ios-autocorrect"],{defaultValue:!0}),keyboards:F(e["device-ios-keyboards"],"--device-ios-keyboards")});return{android:n,appearance:T(e["device-appearance"],ce,"--device-appearance"),fontSize:T(e["device-font-size"],ae,"--device-font-size"),id:t,ios:o,locale:u(e["device-locale"],"--device-locale"),location:Mn(e["device-location"]),orientation:T(e["device-orientation"],k,"--device-orientation"),osVersion:u(e["device-os-version"],"--device-os-version"),timezone:u(e["device-timezone"],"--device-timezone")}}function Cn(e){return e!==""&&Number.isFinite(Number(e))}function Mn(e){const t=u(e,"--device-location");if(t===void 0)return;const n=t.split(",").map(s=>s.trim());if(n.length!==2||!n.every(Cn))throw new a("--device-location expects <lat>,<lng>, e.g., 43.65,-79.38");const[o,i]=n.map(Number);return{latitude:o,longitude:i}}const Bn=["launch-app","launch-ios-args","launch-params","launch-permissions","launch-url","open"];function qn(e){const t=F(e["launch-ios-args"],"--launch-ios-args");return j({app:Gn(e["launch-app"]),ios:t===void 0?void 0:{args:t},params:Kn(e["launch-params"]),permissions:T(e["launch-permissions"],pe,"--launch-permissions"),url:u(e["launch-url"],"--launch-url")??u(e.open,"--open")})}function Gn(e){return e===!1?!1:u(e,"--launch-app")}function Kn(e){const t=F(e,"--launch-params");if(t!==void 0)return Object.fromEntries(t.map(Zn))}function Zn(e){const t=e.indexOf("=");if(t<1)throw new a("--launch-params expects key=value, e.g., --launch-params debug=true");return[e.slice(0,t),Vn(e.slice(t+1))]}function Vn(e){try{return JSON.parse(e)}catch{return e}}const Re={"device.id":"<device>","device.location.latitude":"--device-location latitude","device.location.longitude":"--device-location longitude"};function Wn(e,{endpointFromEnv:t=!1}={}){const n=t?{...Re,endpoint:"APPETIZE_ENDPOINT"}:Re;try{at(e)}catch(o){throw o instanceof ct?new a(o.issues.map(i=>Xn(i,n)).join(`
4
- `)):o}}function Xn({code:e,message:t,path:n},o){const i=Hn(n,o);switch(e){case"invalidValue":return`${i} ${t.replace(/^expected /,"expects ")}`;case"needsLaunchApp":return`${i} has no effect without --target, or with --no-launch-app`;case"needsTarget":return`${i} has no effect without --target`}}function Hn(e,t){return t[e]??`--${e.split(".").filter(n=>!/^\d+$/.test(n)).map(n=>n.replaceAll(/([A-Z])/g,"-$1").toLowerCase()).join("-")}`}const Jn=[...jn,...Bn,"proxy","target"],Yn=150,Qn={downloadingApp:"Downloading the app",installingApp:"Installing the app",launchingApp:"Launching the app",queued:"Queued",ready:"Device ready",requesting:"Requesting a device",starting:"Starting the device"},eo=[{header:"Session ID",key:"sessionId"},{header:"Web view",key:"viewerUrl"},{format:e=>`adb connect ${e}`,header:"adb",key:"adbSerial"},{header:"Host",key:"baseUrl"},{fields:[{header:"Device",key:"device"},{header:"Daemon",key:"daemon"},{header:"Network",key:"network"}],header:"Logs",key:"logs"},{hidden:!0,key:"controlSocket"}];async function to(e,{onPhase:t,signal:n}){let o;for(;;){const i=le(e),s=i?.state?.phase;if(s&&s!==o&&(o=s,t?.(s)),i&&s==="ready"&&i.controlSocket!==void 0)return{...i,controlSocket:i.controlSocket};if(s==="error")throw new Error(i?.endedReason??"The session failed to start");if(s==="ended")throw new Error(i?.endedReason??"The session ended");await z(Yn,n)}}function no(e){if(!(e===void 0||e===!1)){if(e===""||e==="intercept")return"intercept";if(typeof e!="string"||!io(e))throw new a("--proxy expects 'intercept' or an http:// url, e.g., http://proxy:8080");return e}}async function oo({options:e,positionals:t,progress:n,signal:o}){const[i]=t,s=u(e.target,"--target")??ro(e);if(s===void 0&&!process.env.APPETIZE_API_TOKEN)throw new a("APPETIZE_API_TOKEN must be set without a target",["Set APPETIZE_API_TOKEN, or pass --target"]);const r=u(e["session-id"],"--session-id"),p=e.force===!0;if(p&&r===void 0)throw new a("--force needs --session-id");const c=r===void 0?_n():Rn(r),l={device:Fn(e,i),endpoint:pt(e),featureFlags:de(),launch:qn(e),proxy:no(e.proxy),sessionId:c,target:s};Wn(l,{endpointFromEnv:e.endpoint===void 0});const f=le(c);if(f!==void 0){if(!p)throw new dt(c);n.status(`Replacing session ${c}`),await _e(f,o),lt(c)}Ln(l),n.step(`Session ${c}`);const v=ut(c,l.proxy);if(e.wait===!1)return{logs:v,sessionId:c};const A=await to(c,{onPhase:P=>{so(P)&&n.status(Qn[P]??"Starting the session")},signal:o}).catch(P=>{throw U.wrap(P,c)});return{adbSerial:A.adbSerial,baseUrl:A.baseUrl,controlSocket:A.controlSocket,logs:v,sessionId:c,viewerUrl:A.viewerUrl}}function io(e){return e.startsWith("http://")}function so(e){return e!=="ended"&&e!=="error"}function ro(e){const t=e._;return Array.isArray(t)&&typeof t[0]=="string"?t[0]:void 0}const ao=async({options:e,progress:t,record:n,signal:o})=>(e.wait===!1?Ne(n):(t.status(`Stopping session ${n.sessionId}`),await _e(n,o)),{sessionId:n.sessionId}),ze="appetize",co=we(new URL(`./skills/${ze}/`,import.meta.url)),Y=["agents","claude","codex","copilot","cursor"],Ue=["project","user"],po={agents:".agents",claude:".claude",codex:".codex",copilot:".copilot",cursor:".cursor"},lo=x(".agents","skills"),uo=["claude","agents"];function fo(e){return Y.some(t=>t===e)}function mo(e){return Ue.some(t=>t===e)}async function ho(e){const t=e.agents??await go(e),n=await Promise.all(t.map(o=>je(o,e)));return[...new Set(n.flat())]}async function je(e,t){const n=Fe(e,t);if(e==="claude")return[x(n,"skills")];const o=x(t.root,lo);return t.scope==="project"?[o]:await Ce(n)?[o,x(n,"skills")]:[o]}function Fe(e,t){if(e==="claude"&&t.scope==="user"){const n=process.env.CLAUDE_CONFIG_DIR?.trim();if(n)return he(n)}return x(t.root,po[e])}async function go(e){const n=(await Promise.all(Y.map(async o=>await wo(o,e)?o:void 0))).filter(o=>o!==void 0);return n.length>0?n:uo}async function wo(e,t){const n=[Fe(e,t),...await je(e,t)];return(await Promise.all(n.map(i=>Ce(i)))).includes(!0)}async function Ce(e){try{return(await Pt(e)).isDirectory()}catch{return!1}}const yo=["agent","scope"];async function vo({options:e,signal:t}){const n=bo(e.scope),o=So(e.agent),i=n==="user"?Lt():process.cwd(),s=await ho({agents:o,root:i,scope:n}),r=[];for(const p of s){t.throwIfAborted();const c=x(p,ze);await It(c,{force:!0,recursive:!0}),await kt(co,c,{recursive:!0}),r.push(n==="user"?c:At(i,c))}return{installed:r}}function xo(e){const t=I(e,"--agent");if(!fo(t))throw new a(`--agent expects one of ${Y.join(", ")}`);return t}function So(e){return e===void 0?void 0:(Array.isArray(e)?e:[e]).map(n=>xo(n))}function bo(e){if(e===void 0)return"project";const t=I(e,"--scope");if(!mo(t))throw new a(`--scope expects one of ${Ue.join(", ")}`);return t}const w="from",y="to",Eo=[...H({prefix:w}),...H({prefix:y})],Oo=async({device:e,options:t})=>{await e.swipe(ko(t),$o(t))};function Ao(e){return B.some(t=>t===e)}function Po(e){if(e===void 0)return;const t=I(e,"--direction");if(!Ao(t))throw new a(`--direction expects one of ${B.join(", ")}`);return t}function Io(e,t){const n=ft(e.distance,"--distance");if(L(e,{prefix:y})!==void 0)throw new a(`--direction may not be combined with --${y}-*`);return{direction:t,distance:n,from:L(e,{prefix:w})}}function ko(e){const t=Po(e.direction);return t===void 0?To(e):Io(e,t)}function To(e){if(e.distance!==void 0)throw new a("--distance is only valid with --direction");return{from:Me(L(e,{prefix:w}),w),to:Me(L(e,{prefix:y}),y)}}function $o(e){const t=h(e.duration,"--duration"),n=h(e.timeout,"--timeout");return t===void 0&&n===void 0?void 0:{duration:t,timeout:n}}function Me(e,t){if(e===void 0)throw new a(`A swipe needs --direction, or both endpoints: pass one of ${O({prefix:t})}`);return e}const Lo=H(),Do=async({device:e,options:t})=>{const n=Pe(t);await e.tap(n,Ae(t))},No=async({device:e,options:t,positionals:[n]})=>{await e.type(n,_o(t))};function _o(e){const t=h(e.delay,"--delay");return t===void 0?void 0:{delay:t}}const Q=Dt("appetize:cli"),Ro={fail:()=>{},status:()=>{},step:()=>{},succeed:()=>{}};function zo(e,t,n){return e==="interactive"?Uo(t,n):Ro}function Uo(e,t){const n=Nt({handleSignals:!1,stream:e});let o=0;const i=()=>{n.stop()};t.addEventListener("abort",i,{once:!0});const s=()=>(process.off("exit",i),n.isSpinning);return{fail:()=>{s()&&n.stop()},status:r=>{if(!t.aborted){if(n.isSpinning){n.text=r;return}o=Date.now(),process.once("exit",i),n.start(r)}},step:r=>{e.write(`\u25B8 ${r}
5
- `)},succeed:()=>{if(!s())return;const r=Math.round((Date.now()-o)/1e3);n.success(`${n.text} (${String(r)}s)`)}}}const jo=new Set(["adb","api","apk","id","os","url"]),Fo={bottom:"","bottom-left":"","bottom-mid":"","bottom-right":"",left:"","left-mid":"",mid:"","mid-mid":"",middle:" ",right:"","right-mid":"",top:"","top-left":"","top-mid":"","top-right":""},Be=2,Co=10;function Mo(e){return e.split(/(?=[A-Z])/).map((t,n)=>{const o=t.toLowerCase();return jo.has(o)?o.toUpperCase():n===0?o.charAt(0).toUpperCase()+o.slice(1):o}).join(" ")}function Bo(e,t,n){return te(e)?We(e,t,n):N(e,{fields:t,key:""},n)}function qo(e,t){const n=[];for(let o=0;o<e.length;o+=t)n.push(e.slice(o,o+t));return n.length===0?[e]:n}function qe(e){return new _t({chars:Fo,head:e,style:{border:[],head:[],"padding-left":0,"padding-right":Be}})}function Ge(e,t){return e.find(n=>n.key===t)}function Ke(e,t){return t?.header??Mo(e)}function ee(e){return e!=null}function te(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Ze(e){return["boolean","number","string"].includes(typeof e)}function Ve(e,t){const n=new Set(t),o=e.map(s=>s.key).filter(s=>n.has(s)),i=new Set(e.filter(s=>s.hidden).map(s=>s.key));return[...new Set([...o,...t])].filter(s=>!i.has(s))}function We(e,t,n){const o=new Map(Object.entries(e)),i=Ve(t,[...o.keys()]).filter(f=>ee(o.get(f))),s=i.map(f=>Ge(t,f)),r=i.map((f,v)=>Ke(f,s[v])),p=Math.max(0,...r.map(f=>f.length))+Be,c=n===void 0?void 0:n-p-1,l=qe();return l.push(...i.map((f,v)=>[r[v],N(o.get(f),s[v],c)])),Xe(l.toString())}function Go(e,t){const n=e.map(r=>new Map(Object.entries(r))),o=Ve(t,n.flatMap(r=>[...r.keys()])),i=o.map(r=>Ge(t,r)),s=qe(o.map((r,p)=>Ke(r,i[p])));for(const r of n)s.push(o.map((p,c)=>{const l=r.get(p);return ee(l)?N(l,i[c]):""}));return Xe(s.toString())}function N(e,t,n){if(t?.format)return _(t.format(e),n);if(Ze(e))return _(ue(e),n);if(Array.isArray(e)){const o=e.filter(ee);return o.every(Ze)?_(ue(o),n):o.every(te)?Go(o,t?.fields??[]):o.map(i=>N(i,t,n)).join(`
2
+ import Ye from"sade";import{p as u,a as h,f as R,U as a,d as z,b as Qe,i as et,c as tt,e as nt,r as oe,g as k,h as I,j as ot,D as it,s as st,k as rt,l as ie,m as se,S as U,n as j,o as re,q as F,t as T,u as ae,v as ce,w as pe,x as at,y as ct,z as de,A as pt,B as le,C as dt,E as lt,F as ut,G as ft,H as ue,I as fe,J as mt,K as ht,L as gt,M as wt,N as yt,O as vt}from"./stream-C_BND5fe.js";import{existsSync as me,openAsBlob as xt,openSync as St,closeSync as bt}from"node:fs";import{basename as C,extname as Et,resolve as he,dirname as Ot,join as x,relative as At}from"node:path";import{writeFile as ge,stat as Pt,rm as kt,cp as It}from"node:fs/promises";import{spawn as Tt}from"node:child_process";import{fileURLToPath as we}from"node:url";import{humanId as $t}from"human-id";import{homedir as Lt}from"node:os";import Dt from"debug";import Nt from"yocto-spinner";import _t from"cli-table3";import"json-rpc-2.0";import"zod/mini";import"stream";import"module";import"node:net";const M=["closed","fullyOpen","partiallyOpen"],ye=["back","menu","unlock","volumeDown","volumeUp"],ve=["home","lock"],xe=[...ve,...ye],B=["down","left","right","up"],Se=[{header:"Target",key:"id"},{header:"App",key:"appId"},{header:"Platform",key:"platform"},{header:"Version",key:"versionName"},{header:"Build",key:"buildNumber"},{header:"Uploaded",key:"created"}];function q({appId:e,buildNumber:t,created:n,id:o,platform:i,versionName:s}){return{appId:e,buildNumber:t,created:n,id:o,platform:i,versionName:s}}const Rt=["app"],zt=10,Ut=[{fields:Se,key:"builds"},{header:"Total",key:"total"},{header:"Next page",key:"nextPage"}];async function jt({options:e,signal:t}){const n=u(e.app,"--app"),o=h(e.limit,"--limit")??zt,i=h(e.page,"--page"),s={limit:String(o)};n!==void 0&&(s.appId=n),i!==void 0&&(s.page=String(i));const r=await R("/api/v2/builds",{commandOptions:e,query:s,signal:t});return{builds:r.builds.map(q),nextPage:r.nextPage,total:r.total}}const Ft=["note","tags"],be=12e4,Ct=2e3,G=[".apk",".apks",".zip",".tar.gz",".tgz"],Mt={".apk":"android",".apks":"android",".tar.gz":"ios",".tgz":"ios",".zip":"ios"},Bt=Se;async function qt({options:e,positionals:[t],progress:n,signal:o}){const i=Zt(t),s=C(t);n.status(`Uploading ${s}`);const r=await Vt(t,i,e,o);if(e.wait!==!0)return n.status(`Uploaded ${s}`),q(r);n.step(`Uploaded ${s}`),n.status("Waiting for build metadata");const p=await Gt(r.id,e,o);return n.status(`Processed ${s}`),q(p)}async function Gt(e,t,n){const o=h(t.timeout,"--timeout")??be,i=Date.now()+o;for(;;){const s=await R(`/api/v2/builds/${e}`,{commandOptions:t,signal:n});if(s.appId!==void 0)return s;if(Date.now()>=i)throw new Error(`Build ${e} is still being processed after ${String(o)}ms; find it with 'appetize build list'`);await z(Ct,n)}}async function Kt(e){if(!me(e))throw new Error(`No build file at ${e}`);return await xt(e)}function Zt(e){const t=e.toLowerCase(),n=G.find(o=>t.endsWith(o));if(n===void 0)throw new a(`Cannot tell the platform of ${C(e)}; upload a ${G.join(", ")} file`);return Mt[n]}async function Vt(e,t,n,o){const i=new FormData;i.set("platform",t);const s=u(n.note,"--note");s!==void 0&&i.set("note",s);const r=u(n.tags,"--tags");return r!==void 0&&i.set("tags",r),i.set("file",await Kt(e),C(e)),await R("/api/v2/builds",{body:i,commandOptions:n,method:"POST",signal:o})}const Wt=["platform"],Xt=[{fields:[{header:"ID",key:"id"},{header:"Name",key:"name"},{header:"Platform",key:"platform"},{header:"OS versions",key:"osVersions"}],key:"devices"}];async function Ht({options:e,signal:t}){const n=Jt(e.platform);return{devices:(await Qe(e,t)).filter(i=>n===void 0||i.platform===n).map(Yt)}}function Jt(e){const t=u(e,"--platform");if(t!==void 0){if(!et(t))throw new a(`--platform expects one of: ${tt.join(", ")}`);return t}}function Yt({id:e,name:t,osVersions:n,platform:o}){return{id:e,name:t,osVersions:n,platform:o}}const Qt="cli-fold",en=async({device:e,positionals:[t]})=>{if(!tn(t))throw new a(`Hinge must be one of: ${M.join(", ")}`);await e.fold(t)};function tn(e){return M.some(t=>t===e)}const nn=async({device:e,options:t,positionals:[n]})=>{await e.gesture(sn(n),on(t))};function on(e){const t=h(e.timeout,"--timeout");return t===void 0?void 0:{timeout:t}}function sn(e){let t;try{t=nt(e)}catch(n){throw n instanceof SyntaxError?new a(n.message):n}if(t.length===0)throw new a("Expected at least one gesture step");return t}const rn="APPETIZE_OUTPUT";function an(e,t,n){return{format:cn(e,t),progress:pn(e,n)}}function K(e,{extension:t,strict:n=!1}){const o=Et(e);if(o==="")return`${e}${t}`;if(n&&o!==t)throw new a(`The output must be a path ending in ${t}`);return e}function cn(e,t){if(e.json===!0)return"json";if(e.json===!1)return"text";const n=process.env[rn]?.trim();return n==="json"||n==="text"?n:t.isTTY===!0?"text":"json"}function pn(e,t){return e.quiet===!0?"silent":t.isTTY===!0&&process.env.TERM!=="dumb"&&!("CI"in process.env)?"interactive":"silent"}const S=["text","testId"],g="select",E={testId:{help:"Test id to match by exact string",suffix:"test-id"},text:{help:'Text to match by exact string or regex (e.g., "Sign in" or "/sign in/i")',suffix:"text"}},Z="index",$="position",V="x",W="y";function Ee(e,{prefix:t=g}={}){return S.reduce((n,o)=>{const{help:i,suffix:s}=E[o];return n.option(`--${d(t,s)}`,i)},e).option(`--${d(t,Z)}`,"Which match when multiple (0-based)")}function X(e,t={}){const{prefix:n=g}=t;return Ee(e,t).option(`--${d(n,$)}`,"Screen position to use as x,y (0-1), e.g., 0.5,0.75").option(`--${d(n,V)}`,"Horizontal position within the element (0-1, outside allowed)").option(`--${d(n,W)}`,"Vertical position within the element (0-1, outside allowed)")}function Oe(e,{prefix:t=g}={}){const n=J(e,t);if(n.length===0)throw new a(`A selector is required: pass one of ${D(S,t)}`);if(n.length>1)throw new a(`Only one selector may be given, got ${D(n,t)}`);const[o]=n,i=$e(e,d(t,E[o].suffix)),s=h(e[d(t,Z)],`--${d(t,Z)}`);switch(o){case"testId":return{by:"testId",index:s,testId:i};case"text":return{by:"text",index:s,text:un(i)}}}function Ae(e){const t=h(e.timeout,"--timeout");return t===void 0?void 0:{timeout:t}}function dn(e,{prefix:t=g}={}){return Ie(e,t)?Oe(e,{prefix:t}):void 0}function L(e,{prefix:t=g}={}){return Ie(e,t)?Pe(e,{prefix:t}):void 0}function Pe(e,{prefix:t=g}={}){const n=d(t,$),o=e[n],i=Te(e,d(t,V)),s=Te(e,d(t,W));if(o===void 0){if(J(e,t).length===0)throw new a(`A selector is required: pass one of ${O({prefix:t})}`);return{...Oe(e,{prefix:t}),x:i,y:s}}if(J(e,t).length>0)throw new a(`--${n} may not be combined with ${D(S,t)}`);if(i!==void 0||s!==void 0)throw new a(`--${n} may not be combined with --${d(t,V)} or --${d(t,W)}`);return ln($e(e,n),n)}function O(e={}){const{prefix:t=g}=e;return`${D(S,t)}, --${d(t,$)}`}function H(e={}){const{prefix:t=g}=e;return[...ke(e),d(t,$)]}function ke({prefix:e=g}={}){return S.map(t=>d(e,E[t].suffix))}function J(e,t){return S.filter(n=>e[d(t,E[n].suffix)]!==void 0)}function d(...e){return e.filter(Boolean).join("-")}function D(e,t){return e.map(n=>`--${d(t,E[n].suffix)}`).join(", ")}function Ie(e,t){return Object.entries(e).some(([n,o])=>o!==void 0&&n.startsWith(`${t}-`))}function Te(e,t){return h(e[t],`--${t}`)}function ln(e,t){const n=e.split(",");if(n.length!==2)throw new a(`--${t} expects x,y (0-1), e.g., 0.5,0.75`);const[o,i]=n.map(s=>Number(s.trim()));return{by:"position",x:oe(o,`--${t}`),y:oe(i,`--${t}`)}}function un(e){const t=/^\/(.*)\/([a-z]*)$/s.exec(e);return t?new RegExp(t[1],t[2]):e}function $e(e,t){return k(e[t],`--${t}`)}const fn=ke(),mn=async({device:e,options:t,positionals:[n]})=>{const o=hn(n),i=dn(t),s=await e.inspect(i,Ae(t)),r=gn(s,t.pretty===!0);await ge(o,r);const p=Buffer.byteLength(r),c=Le(s.roots);return i?{bytes:p,matches:s.roots.length,nodes:c,output:o}:{bytes:p,nodes:c,output:o}};function Le(e){return e.reduce((t,n)=>t+1+Le(n.children),0)}function hn(e="inspect"){return K(e,{extension:".json"})}function gn(e,t){return`${JSON.stringify(e,null,t?2:void 0)}
3
+ `}const wn=async({device:e})=>{await e.settings.clearKeychain()},yn=async({device:e,positionals:[t]})=>{await e.open(vn(t))};function vn(e){if(typeof e=="string")try{return new URL(e),e}catch{throw new a("<url> expects a URL, e.g., myapp://orders/42")}throw new a("<url> expects a URL, e.g., myapp://orders/42")}const xn=new Set(xe),Sn=async({device:e,positionals:[t]})=>{if(!bn(t))throw new a(`Button must be one of: ${xe.join(", ")}`);await e.press(t)};function bn(e){return typeof e=="string"&&xn.has(e)}const En=async({control:e,options:t,positionals:[n]})=>{const{path:o}=await e.recordStart({force:t.force===!0,path:An(n)});return{path:o}},On=async({control:e})=>{const{path:t}=await e.recordStop();return{path:t}};function An(e){const t=he(K(e,{extension:".mp4",strict:!0})),n=Ot(t);if(!me(n))throw new a(`No such directory: ${n}`);return t}const Pn=async({device:e,positionals:[t]})=>{if(!kn(t))throw new a(`Orientation must be one of: ${I.join(", ")}`);await e.rotate(t)};function kn(e){return I.some(t=>t===e)}const In=async({device:e,positionals:[t]})=>{const n=await e.screenshot(),o=$n(n.mimeType,t);return await ge(o,n.data),{bytes:n.data.byteLength,output:o}};function Tn(e){const t=e.split("/").at(1);return`.${t==="jpeg"?"jpg":t??"png"}`}function $n(e,t="screenshot"){return K(t,{extension:Tn(e)})}function Ln(e){const t=we(new URL("./daemon.js",import.meta.url)),n=St(ot(e.sessionId),"a"),o=Tt(process.execPath,[t],{detached:!0,env:{...process.env,[it]:st(e),DEBUG:Dn(process.env.DEBUG)},stdio:["ignore",n,n]});if(bt(n),o.unref(),o.pid===void 0)throw new Error("Failed to spawn the session daemon");return o.pid}function Dn(e){return e?`${e},appetize:daemon`:"appetize:daemon"}const Nn=/^[a-z0-9](?:[a-z0-9._-]{0,62}[a-z0-9])?$/i;function _n(){return $t({capitalize:!1,separator:"-"})}function Rn(e){if(!Nn.test(e))throw new a('--session-id must use letters, digits, ".", "-" or "_"');return e}const De=1e4;function Ne(e){if(!rt(e))return!1;try{process.kill(e.pid,"SIGTERM")}catch{}return!0}async function _e(e,t){(Ne(e)||Un(e))&&await zn(e,t)}async function zn({pid:e,sessionId:t},n){const o=se(e);try{await z(De,AbortSignal.any([n,o]))}catch(i){if(o.aborted||!ie(e))return;throw i}throw new U(`Session ${t} did not stop in time`,{sessionId:t})}function Un({endedAt:e,pid:t}){return e!==void 0&&Date.now()-Date.parse(e)<De&&ie(t)}const jn=["device-android-shell","device-appearance","device-font-size","device-ios-keyboards","device-locale","device-location","device-orientation","device-os-version","device-timezone"];function Fn(e,t){const n=j({shell:u(e["device-android-shell"],"--device-android-shell"),softKeyboard:re(e["device-android-soft-keyboard"],{defaultValue:!0})}),o=j({autocorrect:re(e["device-ios-autocorrect"],{defaultValue:!0}),keyboards:F(e["device-ios-keyboards"],"--device-ios-keyboards")});return{android:n,appearance:T(e["device-appearance"],ce,"--device-appearance"),fontSize:T(e["device-font-size"],ae,"--device-font-size"),id:t,ios:o,locale:u(e["device-locale"],"--device-locale"),location:Mn(e["device-location"]),orientation:T(e["device-orientation"],I,"--device-orientation"),osVersion:u(e["device-os-version"],"--device-os-version"),timezone:u(e["device-timezone"],"--device-timezone")}}function Cn(e){return e!==""&&Number.isFinite(Number(e))}function Mn(e){const t=u(e,"--device-location");if(t===void 0)return;const n=t.split(",").map(s=>s.trim());if(n.length!==2||!n.every(Cn))throw new a("--device-location expects <lat>,<lng>, e.g., 43.65,-79.38");const[o,i]=n.map(Number);return{latitude:o,longitude:i}}const Bn=["launch-app","launch-ios-args","launch-params","launch-permissions","launch-url","open"];function qn(e){const t=F(e["launch-ios-args"],"--launch-ios-args");return j({app:Gn(e["launch-app"]),ios:t===void 0?void 0:{args:t},params:Kn(e["launch-params"]),permissions:T(e["launch-permissions"],pe,"--launch-permissions"),url:u(e["launch-url"],"--launch-url")??u(e.open,"--open")})}function Gn(e){return e===!1?!1:u(e,"--launch-app")}function Kn(e){const t=F(e,"--launch-params");if(t!==void 0)return Object.fromEntries(t.map(Zn))}function Zn(e){const t=e.indexOf("=");if(t<1)throw new a("--launch-params expects key=value, e.g., --launch-params debug=true");return[e.slice(0,t),Vn(e.slice(t+1))]}function Vn(e){try{return JSON.parse(e)}catch{return e}}const Re={"device.id":"<device>","device.location.latitude":"--device-location latitude","device.location.longitude":"--device-location longitude"};function Wn(e,{endpointFromEnv:t=!1}={}){const n=t?{...Re,endpoint:"APPETIZE_ENDPOINT"}:Re;try{at(e)}catch(o){throw o instanceof ct?new a(o.issues.map(i=>Xn(i,n)).join(`
4
+ `)):o}}function Xn({code:e,message:t,path:n},o){const i=Hn(n,o);switch(e){case"invalidValue":return`${i} ${t.replace(/^expected /,"expects ")}`;case"needsLaunchApp":return`${i} has no effect without --target, or with --no-launch-app`;case"needsTarget":return`${i} has no effect without --target`}}function Hn(e,t){return t[e]??`--${e.split(".").filter(n=>!/^\d+$/.test(n)).map(n=>n.replaceAll(/([A-Z])/g,"-$1").toLowerCase()).join("-")}`}const Jn=[...jn,...Bn,"proxy","target"],Yn=150,Qn={downloadingApp:"Downloading the app",installingApp:"Installing the app",launchingApp:"Launching the app",queued:"Queued",ready:"Device ready",requesting:"Requesting a device",starting:"Starting the device"},eo=[{header:"Session ID",key:"sessionId"},{header:"Web view",key:"viewerUrl"},{format:e=>`adb connect ${e}`,header:"adb",key:"adbSerial"},{header:"Host",key:"baseUrl"},{fields:[{header:"Device",key:"device"},{header:"Daemon",key:"daemon"},{header:"Network",key:"network"}],header:"Logs",key:"logs"},{hidden:!0,key:"controlSocket"}];async function to(e,{onPhase:t,signal:n}){let o;for(;;){const i=le(e),s=i?.state?.phase;if(s&&s!==o&&(o=s,t?.(s)),i&&s==="ready"&&i.controlSocket!==void 0)return{...i,controlSocket:i.controlSocket};if(s==="error")throw new Error(i?.endedReason??"The session failed to start");if(s==="ended")throw new Error(i?.endedReason??"The session ended");await z(Yn,n)}}function no(e){if(!(e===void 0||e===!1)){if(e===""||e==="intercept")return"intercept";if(typeof e!="string"||!io(e))throw new a("--proxy expects 'intercept' or an http:// url, e.g., http://proxy:8080");return e}}async function oo({options:e,positionals:t,progress:n,signal:o}){const[i]=t,s=u(e.target,"--target")??ro(e);if(s===void 0&&!process.env.APPETIZE_API_TOKEN)throw new a("APPETIZE_API_TOKEN must be set without a target",["Set APPETIZE_API_TOKEN, or pass --target"]);const r=u(e["session-id"],"--session-id"),p=e.force===!0;if(p&&r===void 0)throw new a("--force needs --session-id");const c=r===void 0?_n():Rn(r),l={device:Fn(e,i),endpoint:pt(e),featureFlags:de(),launch:qn(e),proxy:no(e.proxy),sessionId:c,target:s};Wn(l,{endpointFromEnv:e.endpoint===void 0});const f=le(c);if(f!==void 0){if(!p)throw new dt(c);n.status(`Replacing session ${c}`),await _e(f,o),lt(c)}Ln(l),n.step(`Session ${c}`);const v=ut(c,l.proxy);if(e.wait===!1)return{logs:v,sessionId:c};const A=await to(c,{onPhase:P=>{so(P)&&n.status(Qn[P]??"Starting the session")},signal:o}).catch(P=>{throw U.wrap(P,c)});return{adbSerial:A.adbSerial,baseUrl:A.baseUrl,controlSocket:A.controlSocket,logs:v,sessionId:c,viewerUrl:A.viewerUrl}}function io(e){return e.startsWith("http://")}function so(e){return e!=="ended"&&e!=="error"}function ro(e){const t=e._;return Array.isArray(t)&&typeof t[0]=="string"?t[0]:void 0}const ao=async({options:e,progress:t,record:n,signal:o})=>(e.wait===!1?Ne(n):(t.status(`Stopping session ${n.sessionId}`),await _e(n,o)),{sessionId:n.sessionId}),co=async({device:e})=>{await e.shake()},ze="appetize",po=we(new URL(`./skills/${ze}/`,import.meta.url)),Y=["agents","claude","codex","copilot","cursor"],Ue=["project","user"],lo={agents:".agents",claude:".claude",codex:".codex",copilot:".copilot",cursor:".cursor"},uo=x(".agents","skills"),fo=["claude","agents"];function mo(e){return Y.some(t=>t===e)}function ho(e){return Ue.some(t=>t===e)}async function go(e){const t=e.agents??await wo(e),n=await Promise.all(t.map(o=>je(o,e)));return[...new Set(n.flat())]}async function je(e,t){const n=Fe(e,t);if(e==="claude")return[x(n,"skills")];const o=x(t.root,uo);return t.scope==="project"?[o]:await Ce(n)?[o,x(n,"skills")]:[o]}function Fe(e,t){if(e==="claude"&&t.scope==="user"){const n=process.env.CLAUDE_CONFIG_DIR?.trim();if(n)return he(n)}return x(t.root,lo[e])}async function wo(e){const n=(await Promise.all(Y.map(async o=>await yo(o,e)?o:void 0))).filter(o=>o!==void 0);return n.length>0?n:fo}async function yo(e,t){const n=[Fe(e,t),...await je(e,t)];return(await Promise.all(n.map(i=>Ce(i)))).includes(!0)}async function Ce(e){try{return(await Pt(e)).isDirectory()}catch{return!1}}const vo=["agent","scope"];async function xo({options:e,signal:t}){const n=Eo(e.scope),o=bo(e.agent),i=n==="user"?Lt():process.cwd(),s=await go({agents:o,root:i,scope:n}),r=[];for(const p of s){t.throwIfAborted();const c=x(p,ze);await kt(c,{force:!0,recursive:!0}),await It(po,c,{recursive:!0}),r.push(n==="user"?c:At(i,c))}return{installed:r}}function So(e){const t=k(e,"--agent");if(!mo(t))throw new a(`--agent expects one of ${Y.join(", ")}`);return t}function bo(e){return e===void 0?void 0:(Array.isArray(e)?e:[e]).map(n=>So(n))}function Eo(e){if(e===void 0)return"project";const t=k(e,"--scope");if(!ho(t))throw new a(`--scope expects one of ${Ue.join(", ")}`);return t}const w="from",y="to",Oo=[...H({prefix:w}),...H({prefix:y})],Ao=async({device:e,options:t})=>{await e.swipe(To(t),Lo(t))};function Po(e){return B.some(t=>t===e)}function ko(e){if(e===void 0)return;const t=k(e,"--direction");if(!Po(t))throw new a(`--direction expects one of ${B.join(", ")}`);return t}function Io(e,t){const n=ft(e.distance,"--distance");if(L(e,{prefix:y})!==void 0)throw new a(`--direction may not be combined with --${y}-*`);return{direction:t,distance:n,from:L(e,{prefix:w})}}function To(e){const t=ko(e.direction);return t===void 0?$o(e):Io(e,t)}function $o(e){if(e.distance!==void 0)throw new a("--distance is only valid with --direction");return{from:Me(L(e,{prefix:w}),w),to:Me(L(e,{prefix:y}),y)}}function Lo(e){const t=h(e.duration,"--duration"),n=h(e.timeout,"--timeout");return t===void 0&&n===void 0?void 0:{duration:t,timeout:n}}function Me(e,t){if(e===void 0)throw new a(`A swipe needs --direction, or both endpoints: pass one of ${O({prefix:t})}`);return e}const Do=H(),No=async({device:e,options:t})=>{const n=Pe(t);await e.tap(n,Ae(t))},_o=async({device:e,options:t,positionals:[n]})=>{await e.type(n,Ro(t))};function Ro(e){const t=h(e.delay,"--delay");return t===void 0?void 0:{delay:t}}const Q=Dt("appetize:cli"),zo={fail:()=>{},status:()=>{},step:()=>{},succeed:()=>{}};function Uo(e,t,n){return e==="interactive"?jo(t,n):zo}function jo(e,t){const n=Nt({handleSignals:!1,stream:e});let o=0;const i=()=>{n.stop()};t.addEventListener("abort",i,{once:!0});const s=()=>(process.off("exit",i),n.isSpinning);return{fail:()=>{s()&&n.stop()},status:r=>{if(!t.aborted){if(n.isSpinning){n.text=r;return}o=Date.now(),process.once("exit",i),n.start(r)}},step:r=>{e.write(`\u25B8 ${r}
5
+ `)},succeed:()=>{if(!s())return;const r=Math.round((Date.now()-o)/1e3);n.success(`${n.text} (${String(r)}s)`)}}}const Fo=new Set(["adb","api","apk","id","os","url"]),Co={bottom:"","bottom-left":"","bottom-mid":"","bottom-right":"",left:"","left-mid":"",mid:"","mid-mid":"",middle:" ",right:"","right-mid":"",top:"","top-left":"","top-mid":"","top-right":""},Be=2,Mo=10;function Bo(e){return e.split(/(?=[A-Z])/).map((t,n)=>{const o=t.toLowerCase();return Fo.has(o)?o.toUpperCase():n===0?o.charAt(0).toUpperCase()+o.slice(1):o}).join(" ")}function qo(e,t,n){return te(e)?We(e,t,n):N(e,{fields:t,key:""},n)}function Go(e,t){const n=[];for(let o=0;o<e.length;o+=t)n.push(e.slice(o,o+t));return n.length===0?[e]:n}function qe(e){return new _t({chars:Co,head:e,style:{border:[],head:[],"padding-left":0,"padding-right":Be}})}function Ge(e,t){return e.find(n=>n.key===t)}function Ke(e,t){return t?.header??Bo(e)}function ee(e){return e!=null}function te(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Ze(e){return["boolean","number","string"].includes(typeof e)}function Ve(e,t){const n=new Set(t),o=e.map(s=>s.key).filter(s=>n.has(s)),i=new Set(e.filter(s=>s.hidden).map(s=>s.key));return[...new Set([...o,...t])].filter(s=>!i.has(s))}function We(e,t,n){const o=new Map(Object.entries(e)),i=Ve(t,[...o.keys()]).filter(f=>ee(o.get(f))),s=i.map(f=>Ge(t,f)),r=i.map((f,v)=>Ke(f,s[v])),p=Math.max(0,...r.map(f=>f.length))+Be,c=n===void 0?void 0:n-p-1,l=qe();return l.push(...i.map((f,v)=>[r[v],N(o.get(f),s[v],c)])),Xe(l.toString())}function Ko(e,t){const n=e.map(r=>new Map(Object.entries(r))),o=Ve(t,n.flatMap(r=>[...r.keys()])),i=o.map(r=>Ge(t,r)),s=qe(o.map((r,p)=>Ke(r,i[p])));for(const r of n)s.push(o.map((p,c)=>{const l=r.get(p);return ee(l)?N(l,i[c]):""}));return Xe(s.toString())}function N(e,t,n){if(t?.format)return _(t.format(e),n);if(Ze(e))return _(ue(e),n);if(Array.isArray(e)){const o=e.filter(ee);return o.every(Ze)?_(ue(o),n):o.every(te)?Ko(o,t?.fields??[]):o.map(i=>N(i,t,n)).join(`
6
6
  `)}return te(e)?We(e,t?.fields??[],n):_(String(e),n)}function Xe(e){return e.split(`
7
7
  `).map(t=>t.trimEnd()).join(`
8
- `)}function _(e,t){return t===void 0||t<Co?e:e.split(`
9
- `).flatMap(n=>Ko(n,t)).join(`
10
- `)}function Ko(e,t){const n=[];let o="";for(const i of e.split(" ").flatMap(s=>qo(s,t)))o===""?o=i:o.length+1+i.length<=t?o=`${o} ${i}`:(n.push(o),o=i);return n.push(o),n}async function Zo(e,t={}){const n=await fe(e,{signal:t.signal});return new mt(n,{...t,onClose:()=>{n.close(),t.onClose?.()}})}function Vo(e,t){if(e.controlSocket===void 0)throw new Error("Session is not ready");return Zo(e.controlSocket,{baseUrl:e.baseUrl,signal:t})}async function Wo(e,t){if(e.controlSocket===void 0)throw new Error("Session is not ready");const n=await fe(e.controlSocket,{signal:t}),{client:o}=ht(n,{});return{close:()=>{n.close()},recordStart:async i=>await o.request("appetizeio.cli.record.start",i),recordStop:async()=>await o.request("appetizeio.cli.record.stop")}}function Xo(e){return async({options:t,positionals:n,progress:o,signal:i})=>{const s=t["session-id"],r=gt(typeof s=="string"?s:void 0);try{return await e({options:t,positionals:n,progress:o,record:r,signal:AbortSignal.any([i,se(r.pid)])})}catch(p){throw U.wrap(p,r.sessionId)}}}function Ho(e){return async({options:t,positionals:n,progress:o,record:i,signal:s})=>{const r=await Vo(i,s);try{return await e({device:r,options:t,positionals:n,progress:o,signal:s})}finally{r.close()}}}function Jo(e){return async({options:t,positionals:n,progress:o,record:i,signal:s})=>{const r=await Wo(i,s);try{return await e({control:r,options:t,positionals:n,progress:o,signal:s})}finally{r.close()}}}const Yo=["session-id",...Rt,...Ft,...Wt,...fn,...yo,...Jn,...Eo,...Lo],Qo=["json","quiet"];function ei(e){const t=Ye("appetize").version(e).option("--json","Print the result as JSON").option("--quiet","Hide progress");return b(t,"session start <device>",n=>n.describe(["Start a device session and wait until it is ready","","Environment variables:","APPETIZE_API_TOKEN: Authorizes private APIs and targets; required with no target","APPETIZE_ENDPOINT: Appetize URL used when --endpoint is omitted"]).option("--device-android-shell","Android only: adb shell command run at start; needs --target").option("--device-appearance",`Device appearance: ${ce.join(" or ")}`).option("--device-font-size",`Device font size: ${ae.join(", ")}`).option("--device-ios-keyboards","iOS only: keyboard layout (e.g., en_US@sw=QWERTY); repeatable").option("--device-locale","Device locale as a BCP 47 tag (e.g., fr-CA)").option("--device-location","Device location as <lat>,<lng>; use = if latitude is negative").option("--device-orientation",`Initial orientation: ${k.join(", ")}`).option("--device-os-version","Device OS version (e.g., 17 for iOS, 14 for Android)").option("--device-timezone","Device IANA timezone (e.g., America/Toronto)").option("--endpoint","Appetize URL (e.g., https://appetize.io); overrides APPETIZE_ENDPOINT").option("--force","Replace a session with the same id",!1).option("--launch-app","App id to launch instead of the target app; needs --target").option("--launch-ios-args","iOS only: app launch argument, joined with = if it starts with -; repeatable; needs --target").option("--launch-params","App launch parameter as key=value, JSON when valid; repeatable; needs --target").option("--launch-permissions",`Grant app permissions: ${pe.join(", ")}; needs --target`).option("--launch-url","URL opened once the session is ready").option("--no-device-android-soft-keyboard","Android only: hide the on-screen keyboard").option("--no-device-ios-autocorrect","iOS only: keep autocorrect off, its default").option("--no-launch-app","Skip launching the app; needs --target").option("--no-wait","Return without waiting for the device session to be ready").option("--proxy","Route traffic through a proxy: 'intercept' to capture it, or an http url").option("--session-id","Session id; defaults to a generated 3-word id").option("--target","App, build or app group id to run").example("session start iphone15pro --target app_a1b2c3").example("session start iphone15pro").example("session start pixel7 --target app_a1b2c3 --device-os-version 14").example("session start iphone15pro --target app_a1b2c3 --launch-url myapp://orders/42").example("session start iphone15pro --target app_a1b2c3 --launch-params debug=true --launch-params retries=3").example(`session start iphone15pro --target app_a1b2c3 --launch-params 'zip="90210"'`).example(`session start iphone15pro --target app_a1b2c3 --launch-params 'tags=["beta","qa"]'`).example("session start iphone15pro --device-orientation landscapeLeft --device-appearance dark").example("session start pixel7 --device-locale fr-CA --device-timezone America/Toronto").example("session start iphone15pro --target app_a1b2c3 --session-id demo --force"),oo,{fields:eo}),ne(t,"session stop",n=>n.describe("Stop a device session and await its exit").option("--no-wait","Return without waiting for the session to exit").example("session stop --no-wait"),ao),b(t,"build list",n=>n.describe(["List uploaded builds, printing session start targets","","Environment variables:","APPETIZE_API_TOKEN: Authorizes the listing request","APPETIZE_ENDPOINT: Appetize URL used when --endpoint is omitted"]).option("--app","App id to filter by (bundle or package id)").option("--endpoint","Appetize URL (e.g., https://appetize.io); overrides APPETIZE_ENDPOINT").option("--limit","Builds per page (default 10, max 200)").option("--page","Page of results to fetch (default 1)").example("build list").example("build list --app com.example.app").example("build list --app com.example.app --page 2"),jt,{fields:Ut}),b(t,"build upload <file>",n=>n.describe([`Upload a build (${G.join(", ")}) as a session start target`,"","Environment variables:","APPETIZE_API_TOKEN: Authorizes the upload","APPETIZE_ENDPOINT: Appetize URL used when --endpoint is omitted"]).option("--endpoint","Appetize URL (e.g., https://appetize.io); overrides APPETIZE_ENDPOINT").option("--note","Note to store with the build").option("--tags","Comma separated tags to store with the build").option("--timeout",`Milliseconds to wait with --wait (default ${String(be)})`).option("--wait","Wait for the app id and version metadata to resolve").example("build upload ./app.apk").example("build upload ./app.zip").example("build upload ./app.apk --wait").example('build upload ./app.apk --tags beta,latest --note "PR 42"'),qt,{fields:Bt}),b(t,"device list",n=>n.describe(["List device models and their supported OS versions","","Environment variables:","APPETIZE_ENDPOINT: Appetize URL used when --endpoint is omitted"]).option("--endpoint","Appetize URL (e.g., https://appetize.io); overrides APPETIZE_ENDPOINT").option("--platform","Platform to filter by: ios or android").example("device list").example("device list --platform ios"),Ht,{fields:Xt}),m(t,"press <button>",n=>n.describe(`Press a device button: ${ve.join(", ")}; Android only: ${ye.join(", ")}`).example("press home").example("press volumeUp"),Sn),m(t,"rotate <orientation>",n=>n.describe("Rotate the device to an orientation: portrait, landscapeLeft, landscapeRight or upsideDown").example("rotate portrait").example("rotate landscapeLeft"),Pn),Qt in de()&&m(t,"fold <hinge>",n=>n.describe(`Fold a foldable device: ${M.join(", ")}`).example("fold closed").example("fold fullyOpen"),en),m(t,"open <url>",n=>n.describe("Open a URL or deep link on the device").example("open myapp://orders/42").example("open https://example.com"),yn),m(t,"keychain clear",n=>n.describe("Clear the entire device keychain (iOS only)").example("keychain clear"),wn),m(t,"screenshot [output]",n=>n.describe("Take a screenshot of the current device screen").example("screenshot").example("screenshot home-screen").example("screenshot ./shots/checkout.png"),kn),m(t,"tap",n=>X(n.describe(["Tap an element matched by a selector, or a screen position","",`Pick one of: ${O()}`])).option("--timeout","Milliseconds to wait for the element").example("tap --select-text 'Log in'").example("tap --select-test-id save").example("tap --select-text '/^Item \\d+/i' --select-index 2").example("tap --select-position 0.5,0.75").example("tap --select-test-id slider --select-x 0.9").example("tap --select-test-id dialog --select-x=-0.1").example("tap --select-test-id row --select-y=1.2"),Do),m(t,"swipe",n=>X(X(n.describe(["Swipe in a direction, or along a path between two points","",`Pick a --direction with an optional --${w} starting point,`,`or both a --${w}-* and a --${y}-* point to form a path`,"",`Pick one per point: ${O({prefix:w})}`,` ${O({prefix:y})}`]).option("--direction",`Direction to travel: ${B.join(", ")}`).option("--distance","Travel as a fraction of the screen (0-1)"),{prefix:w}),{prefix:y}).option("--duration","Milliseconds the gesture travels for").option("--timeout",`Milliseconds to wait for any --${w}/--${y} elements`).example("swipe --direction up").example("swipe --direction up --distance 0.25").example("swipe --direction left --from-test-id card --from-index 1").example("swipe --from-position 0.5,0.75 --to-position 0.5,0.3").example("swipe --from-text 'Drag me' --from-y 0.9 --to-test-id drop-zone"),Oo),m(t,"gesture <syntax>",n=>n.describe(["Play a single-pointer gesture",""," > press the pointer down"," / lift it"," {wait} pause 400 ms"," {wait=ms} pause ms"," {...} move the pointer:"," byText=Photo to the element with exactly that text"," byText=/photo/i to the element matching the regex",' byText="My photos" quote values with spaces'," byTestId=card to the element with that test id"," index=1 to the second match, from 0"," x=0 y=0 to a point in it; 0-1 spans it"," 0.5,0.6 to a screen position, each 0-1"," x=0.5 y=0.6 the same screen position"," duration=ms glide time while down; default 400","","Single-quote the gesture. A pointer still down at the end lifts.","Double taps need {wait=100} between taps; Android drops faster ones."]).option("--timeout","Milliseconds to wait for any elements").example("gesture '{byText=Photo}>/' # tap").example("gesture '{byText=Photo}>{wait=800}/' # long-press").example("gesture '{0.5,0.5}>/{wait=100}>/' # double tap").example("gesture '{byTestId=card}>{byTestId=drop-zone duration=600}/' # drag").example(`gesture '{byText="My photos" x=0 y=0}>{wait}/' # top-left corner`).example("gesture '{byText=/photo/i index=1}>{wait=800}/' # 2nd match").example("gesture '{byTestId=slider x=0}>{byTestId=slider x=1 duration=1000}/' # slide").example("gesture '{0.5,0.8}>{0.5,0.6}{0.8,0.6}{0.8,0.2}/' # path").example("gesture '{0.2,0.4}>{0.5,0.6 duration=300}/{0.2,0.7}>{0.8,0.7}/' # 2 strokes").example("gesture '{byTestId=card}>{wait=800}/' --timeout 5000 # wait for card"),nn),m(t,"inspect [output]",n=>Ee(n.describe("Capture the view hierarchy of the screen, or of every element a selector matches")).option("--timeout","Milliseconds to wait for a match").option("--pretty","Pretty-print the JSON",!1).example("inspect").example("inspect --select-text 'Log in'").example("inspect hierarchy.json --pretty"),mn),m(t,"type <text>",n=>n.describe(`Type text; {...} presses a named key: ${vt.join(", ")}`).option("--delay","Milliseconds to wait between steps").example("type 'hello{Enter}'").example("type '{Backspace>16/}'").example("type 'user@example.com{Tab}hunter2{Enter}' --delay 50"),No),He(t,"recording start <output>",n=>n.describe("Start recording the device video to an mp4 file").option("--force","Overwrite the file if it already exists",!1).example("recording start login-flow").example("recording start ./captures/checkout.mp4").example("recording start login-flow --force"),En),He(t,"recording stop",n=>n.describe("Stop recording the device video and close the file").example("recording stop"),On),b(t,"skill install",n=>n.describe("Install the Appetize agent skill for coding agents").option("--agent","Agent to install for, repeatable; defaults to the agents detected").option("--scope","Install for the project (default) or the user").example("skill install").example("skill install --scope user").example("skill install --agent claude --agent cursor"),vo),t}function b(e,t,n,o,{fields:i}={}){const s=t.split(" ").filter(r=>!/^[<[]/.test(r)).join(" ");return n(e.command(t)).action(oi({action:o,fields:i,name:s}))}function ne(e,t,n,o){return b(e,t,i=>n(i).option("--session-id","Target session id; defaults to the sole active session"),Xo(o))}function m(e,t,n,o){return ne(e,t,n,Ho(o))}function He(e,t,n,o){return ne(e,t,n,Jo(o))}function Je(e){return`${String(Date.now()-e)}ms`}function ti(e,t,n){if(e==="json")return JSON.stringify(t===void 0?{}:t,null,2);const o=t===void 0?"":Bo(t,n,process.stdout.columns);return o===""?void 0:o}async function ni({action:e,fields:t=[],name:n},o){const i=Date.now();Q(`invoked: ${process.argv.slice(2).join(" ")}`);const s=wt(o),{format:r,progress:p}=an(s.options,process.stdout,process.stderr),c=zo(p,process.stderr,s.signal);try{const l=ti(r,await e({...s,progress:c}),t);c.succeed(),l!==void 0&&process.stdout.write(`${l}
8
+ `)}function _(e,t){return t===void 0||t<Mo?e:e.split(`
9
+ `).flatMap(n=>Zo(n,t)).join(`
10
+ `)}function Zo(e,t){const n=[];let o="";for(const i of e.split(" ").flatMap(s=>Go(s,t)))o===""?o=i:o.length+1+i.length<=t?o=`${o} ${i}`:(n.push(o),o=i);return n.push(o),n}async function Vo(e,t={}){const n=await fe(e,{signal:t.signal});return new mt(n,{...t,onClose:()=>{n.close(),t.onClose?.()}})}function Wo(e,t){if(e.controlSocket===void 0)throw new Error("Session is not ready");return Vo(e.controlSocket,{baseUrl:e.baseUrl,signal:t})}async function Xo(e,t){if(e.controlSocket===void 0)throw new Error("Session is not ready");const n=await fe(e.controlSocket,{signal:t}),{client:o}=ht(n,{});return{close:()=>{n.close()},recordStart:async i=>await o.request("appetizeio.cli.record.start",i),recordStop:async()=>await o.request("appetizeio.cli.record.stop")}}function Ho(e){return async({options:t,positionals:n,progress:o,signal:i})=>{const s=t["session-id"],r=gt(typeof s=="string"?s:void 0);try{return await e({options:t,positionals:n,progress:o,record:r,signal:AbortSignal.any([i,se(r.pid)])})}catch(p){throw U.wrap(p,r.sessionId)}}}function Jo(e){return async({options:t,positionals:n,progress:o,record:i,signal:s})=>{const r=await Wo(i,s);try{return await e({device:r,options:t,positionals:n,progress:o,signal:s})}finally{r.close()}}}function Yo(e){return async({options:t,positionals:n,progress:o,record:i,signal:s})=>{const r=await Xo(i,s);try{return await e({control:r,options:t,positionals:n,progress:o,signal:s})}finally{r.close()}}}const Qo=["session-id",...Rt,...Ft,...Wt,...fn,...vo,...Jn,...Oo,...Do],ei=["json","quiet"];function ti(e){const t=Ye("appetize").version(e).option("--json","Print the result as JSON").option("--quiet","Hide progress");return b(t,"session start <device>",n=>n.describe(["Start a device session and wait until it is ready","","Environment variables:","APPETIZE_API_TOKEN: Authorizes private APIs and targets; required with no target","APPETIZE_ENDPOINT: Appetize URL used when --endpoint is omitted"]).option("--device-android-shell","Android only: adb shell command run at start; needs --target").option("--device-appearance",`Device appearance: ${ce.join(" or ")}`).option("--device-font-size",`Device font size: ${ae.join(", ")}`).option("--device-ios-keyboards","iOS only: keyboard layout (e.g., en_US@sw=QWERTY); repeatable").option("--device-locale","Device locale as a BCP 47 tag (e.g., fr-CA)").option("--device-location","Device location as <lat>,<lng>; use = if latitude is negative").option("--device-orientation",`Initial orientation: ${I.join(", ")}`).option("--device-os-version","Device OS version (e.g., 17 for iOS, 14 for Android)").option("--device-timezone","Device IANA timezone (e.g., America/Toronto)").option("--endpoint","Appetize URL (e.g., https://appetize.io); overrides APPETIZE_ENDPOINT").option("--force","Replace a session with the same id",!1).option("--launch-app","App id to launch instead of the target app; needs --target").option("--launch-ios-args","iOS only: app launch argument, joined with = if it starts with -; repeatable; needs --target").option("--launch-params","App launch parameter as key=value, JSON when valid; repeatable; needs --target").option("--launch-permissions",`Grant app permissions: ${pe.join(", ")}; needs --target`).option("--launch-url","URL opened once the session is ready").option("--no-device-android-soft-keyboard","Android only: hide the on-screen keyboard").option("--no-device-ios-autocorrect","iOS only: keep autocorrect off, its default").option("--no-launch-app","Skip launching the app; needs --target").option("--no-wait","Return without waiting for the device session to be ready").option("--proxy","Route traffic through a proxy: 'intercept' to capture it, or an http url").option("--session-id","Session id; defaults to a generated 3-word id").option("--target","App, build or app group id to run").example("session start iphone15pro --target app_a1b2c3").example("session start iphone15pro").example("session start pixel7 --target app_a1b2c3 --device-os-version 14").example("session start iphone15pro --target app_a1b2c3 --launch-url myapp://orders/42").example("session start iphone15pro --target app_a1b2c3 --launch-params debug=true --launch-params retries=3").example(`session start iphone15pro --target app_a1b2c3 --launch-params 'zip="90210"'`).example(`session start iphone15pro --target app_a1b2c3 --launch-params 'tags=["beta","qa"]'`).example("session start iphone15pro --device-orientation landscapeLeft --device-appearance dark").example("session start pixel7 --device-locale fr-CA --device-timezone America/Toronto").example("session start iphone15pro --target app_a1b2c3 --session-id demo --force"),oo,{fields:eo}),ne(t,"session stop",n=>n.describe("Stop a device session and await its exit").option("--no-wait","Return without waiting for the session to exit").example("session stop --no-wait"),ao),b(t,"build list",n=>n.describe(["List uploaded builds, printing session start targets","","Environment variables:","APPETIZE_API_TOKEN: Authorizes the listing request","APPETIZE_ENDPOINT: Appetize URL used when --endpoint is omitted"]).option("--app","App id to filter by (bundle or package id)").option("--endpoint","Appetize URL (e.g., https://appetize.io); overrides APPETIZE_ENDPOINT").option("--limit","Builds per page (default 10, max 200)").option("--page","Page of results to fetch (default 1)").example("build list").example("build list --app com.example.app").example("build list --app com.example.app --page 2"),jt,{fields:Ut}),b(t,"build upload <file>",n=>n.describe([`Upload a build (${G.join(", ")}) as a session start target`,"","Environment variables:","APPETIZE_API_TOKEN: Authorizes the upload","APPETIZE_ENDPOINT: Appetize URL used when --endpoint is omitted"]).option("--endpoint","Appetize URL (e.g., https://appetize.io); overrides APPETIZE_ENDPOINT").option("--note","Note to store with the build").option("--tags","Comma separated tags to store with the build").option("--timeout",`Milliseconds to wait with --wait (default ${String(be)})`).option("--wait","Wait for the app id and version metadata to resolve").example("build upload ./app.apk").example("build upload ./app.zip").example("build upload ./app.apk --wait").example('build upload ./app.apk --tags beta,latest --note "PR 42"'),qt,{fields:Bt}),b(t,"device list",n=>n.describe(["List device models and their supported OS versions","","Environment variables:","APPETIZE_ENDPOINT: Appetize URL used when --endpoint is omitted"]).option("--endpoint","Appetize URL (e.g., https://appetize.io); overrides APPETIZE_ENDPOINT").option("--platform","Platform to filter by: ios or android").example("device list").example("device list --platform ios"),Ht,{fields:Xt}),m(t,"press <button>",n=>n.describe(`Press a device button: ${ve.join(", ")}; Android only: ${ye.join(", ")}`).example("press home").example("press volumeUp"),Sn),m(t,"rotate <orientation>",n=>n.describe("Rotate the device to an orientation: portrait, landscapeLeft, landscapeRight or upsideDown").example("rotate portrait").example("rotate landscapeLeft"),Pn),Qt in de()&&m(t,"fold <hinge>",n=>n.describe(`Fold a foldable device: ${M.join(", ")}`).example("fold closed").example("fold fullyOpen"),en),m(t,"open <url>",n=>n.describe("Open a URL or deep link on the device").example("open myapp://orders/42").example("open https://example.com"),yn),m(t,"keychain clear",n=>n.describe("Clear the entire device keychain (iOS only)").example("keychain clear"),wn),m(t,"shake",n=>n.describe("Shake the device").example("shake"),co),m(t,"screenshot [output]",n=>n.describe("Take a screenshot of the current device screen").example("screenshot").example("screenshot home-screen").example("screenshot ./shots/checkout.png"),In),m(t,"tap",n=>X(n.describe(["Tap an element matched by a selector, or a screen position","",`Pick one of: ${O()}`])).option("--timeout","Milliseconds to wait for the element").example("tap --select-text 'Log in'").example("tap --select-test-id save").example("tap --select-text '/^Item \\d+/i' --select-index 2").example("tap --select-position 0.5,0.75").example("tap --select-test-id slider --select-x 0.9").example("tap --select-test-id dialog --select-x=-0.1").example("tap --select-test-id row --select-y=1.2"),No),m(t,"swipe",n=>X(X(n.describe(["Swipe in a direction, or along a path between two points","",`Pick a --direction with an optional --${w} starting point,`,`or both a --${w}-* and a --${y}-* point to form a path`,"",`Pick one per point: ${O({prefix:w})}`,` ${O({prefix:y})}`]).option("--direction",`Direction to travel: ${B.join(", ")}`).option("--distance","Travel as a fraction of the screen (0-1)"),{prefix:w}),{prefix:y}).option("--duration","Milliseconds the gesture travels for").option("--timeout",`Milliseconds to wait for any --${w}/--${y} elements`).example("swipe --direction up").example("swipe --direction up --distance 0.25").example("swipe --direction left --from-test-id card --from-index 1").example("swipe --from-position 0.5,0.75 --to-position 0.5,0.3").example("swipe --from-text 'Drag me' --from-y 0.9 --to-test-id drop-zone"),Ao),m(t,"gesture <syntax>",n=>n.describe(["Play a single-pointer gesture",""," > press the pointer down"," / lift it"," {wait} pause 400 ms"," {wait=ms} pause ms"," {...} move the pointer:"," byText=Photo to the element with exactly that text"," byText=/photo/i to the element matching the regex",' byText="My photos" quote values with spaces'," byTestId=card to the element with that test id"," index=1 to the second match, from 0"," x=0 y=0 to a point in it; 0-1 spans it"," 0.5,0.6 to a screen position, each 0-1"," x=0.5 y=0.6 the same screen position"," duration=ms glide time while down; default 400","","Single-quote the gesture. A pointer still down at the end lifts.","Double taps need {wait=100} between taps; Android drops faster ones."]).option("--timeout","Milliseconds to wait for any elements").example("gesture '{byText=Photo}>/' # tap").example("gesture '{byText=Photo}>{wait=800}/' # long-press").example("gesture '{0.5,0.5}>/{wait=100}>/' # double tap").example("gesture '{byTestId=card}>{byTestId=drop-zone duration=600}/' # drag").example(`gesture '{byText="My photos" x=0 y=0}>{wait}/' # top-left corner`).example("gesture '{byText=/photo/i index=1}>{wait=800}/' # 2nd match").example("gesture '{byTestId=slider x=0}>{byTestId=slider x=1 duration=1000}/' # slide").example("gesture '{0.5,0.8}>{0.5,0.6}{0.8,0.6}{0.8,0.2}/' # path").example("gesture '{0.2,0.4}>{0.5,0.6 duration=300}/{0.2,0.7}>{0.8,0.7}/' # 2 strokes").example("gesture '{byTestId=card}>{wait=800}/' --timeout 5000 # wait for card"),nn),m(t,"inspect [output]",n=>Ee(n.describe("Capture the view hierarchy of the screen, or of every element a selector matches")).option("--timeout","Milliseconds to wait for a match").option("--pretty","Pretty-print the JSON",!1).example("inspect").example("inspect --select-text 'Log in'").example("inspect hierarchy.json --pretty"),mn),m(t,"type <text>",n=>n.describe(`Type text; {...} presses a named key: ${vt.join(", ")}`).option("--delay","Milliseconds to wait between steps").example("type 'hello{Enter}'").example("type '{Backspace>16/}'").example("type 'user@example.com{Tab}hunter2{Enter}' --delay 50"),_o),He(t,"recording start <output>",n=>n.describe("Start recording the device video to an mp4 file").option("--force","Overwrite the file if it already exists",!1).example("recording start login-flow").example("recording start ./captures/checkout.mp4").example("recording start login-flow --force"),En),He(t,"recording stop",n=>n.describe("Stop recording the device video and close the file").example("recording stop"),On),b(t,"skill install",n=>n.describe("Install the Appetize agent skill for coding agents").option("--agent","Agent to install for, repeatable; defaults to the agents detected").option("--scope","Install for the project (default) or the user").example("skill install").example("skill install --scope user").example("skill install --agent claude --agent cursor"),xo),t}function b(e,t,n,o,{fields:i}={}){const s=t.split(" ").filter(r=>!/^[<[]/.test(r)).join(" ");return n(e.command(t)).action(ii({action:o,fields:i,name:s}))}function ne(e,t,n,o){return b(e,t,i=>n(i).option("--session-id","Target session id; defaults to the sole active session"),Ho(o))}function m(e,t,n,o){return ne(e,t,n,Jo(o))}function He(e,t,n,o){return ne(e,t,n,Yo(o))}function Je(e){return`${String(Date.now()-e)}ms`}function ni(e,t,n){if(e==="json")return JSON.stringify(t===void 0?{}:t,null,2);const o=t===void 0?"":qo(t,n,process.stdout.columns);return o===""?void 0:o}async function oi({action:e,fields:t=[],name:n},o){const i=Date.now();Q(`invoked: ${process.argv.slice(2).join(" ")}`);const s=wt(o),{format:r,progress:p}=an(s.options,process.stdout,process.stderr),c=Uo(p,process.stderr,s.signal);try{const l=ni(r,await e({...s,progress:c}),t);c.succeed(),l!==void 0&&process.stdout.write(`${l}
11
11
  `),Q(`ok in ${Je(i)}`)}catch(l){c.fail(),process.stderr.write(`${yt(r,l,{command:n})}
12
- `),Q(`failed after ${Je(i)}:`,l),process.exitCode=1}}function oi(e){return(...t)=>{ni(e,t)}}ei("0.25.0").parse(process.argv,{boolean:Qo,string:Yo});
12
+ `),Q(`failed after ${Je(i)}:`,l),process.exitCode=1}}function ii(e){return(...t)=>{oi(e,t)}}ti("0.26.0").parse(process.argv,{boolean:ei,string:Qo});
package/daemon.js CHANGED
@@ -1,2 +1,2 @@
1
- import{T as _,P as A,Q as F,R as E,V as z,J as V,W as j,y as v,X as N,x as H,Y as Q,Z as J,_ as $,$ as G,a0 as K,F as Z,a1 as X,a2 as Y,a3 as B,a4 as ee}from"./stream-C9RfmvVk.js";import T from"debug";import{createServer as R}from"node:net";import{pipeline as P}from"node:stream";import{rm as te}from"node:fs/promises";import{readFileSync as ne,createWriteStream as oe,existsSync as re,rmSync as se}from"node:fs";import{createServer as ie}from"node:http";import{WebSocketServer as ae}from"ws";import{pipeline as ce}from"node:stream/promises";import{EncodedVideoPacketSource as de,Output as ue,FilePathTarget as le,Mp4OutputFormat as fe,EncodedPacket as pe}from"mediabunny";import"json-rpc-2.0";import"zod/mini";import"node:path";import"node:os";import"stream";import"module";const he=T("appetize.io:transport:ws-ping"),we=3e4;function ge(e){let t=!0;const n=()=>{t=!0};e.on("pong",n);const o=setInterval(()=>{if(!t){clearInterval(o),he("liveness ping went unanswered, terminating"),e.terminate();return}e.readyState===e.OPEN&&(t=!1,e.ping())},we);return{destroy(){clearInterval(o),e.off("pong",n)},pong:n}}const w=T("appetize.io:trace:transport:websocket");class L extends _{constructor(t,{signal:n}={}){super(async r=>{this.#e.send(A(r))},{signal:n}),this.wsOrUrl=t,typeof t=="string"?(this.#e=new WebSocket(t),this.#e.binaryType="arraybuffer"):this.#e=t;const o=this.#e;if(o instanceof WebSocket?(o.addEventListener("open",this.#s),o.addEventListener("message",this.#r),o.addEventListener("error",this.#o),o.addEventListener("close",this.#n),this.#t.push(()=>{o.removeEventListener("open",this.#s),o.removeEventListener("message",this.#r),o.removeEventListener("error",this.#o),o.removeEventListener("close",this.#n)})):(o.addEventListener("open",this.#s),o.addEventListener("message",this.#r),o.addEventListener("error",this.#o),o.addEventListener("close",this.#n),this.#t.push(()=>{o.removeEventListener("open",this.#s),o.removeEventListener("message",this.#r),o.removeEventListener("error",this.#o),o.removeEventListener("close",this.#n)})),this.send=o.send.bind(o),"ping"in o){const{destroy:r,pong:s}=ge(o);this.#c=s,this.#t.push(r)}}wsOrUrl;onclose;onerror;onmessage;onopen;send;get bufferedAmount(){return this.#e.bufferedAmount}get readyState(){return this.#e.readyState}#t=[];#i=!1;#a=!1;#c;#e;close({destroyWs:t=!1,...n}={}){this.closed||(this.#i=t,super.close(n))}handleClose(t){w("close()");for(const n of this.#t.splice(0))n();if((typeof this.wsOrUrl=="string"||this.#i)&&(this.#e.close(t.code,t.reason),"terminate"in this.#e)){const n=this.#e;setTimeout(()=>{n.terminate()},100)}this.#d(),super.handleClose(t)}#d(t){this.#a||(this.#a=!0,this.onclose?.(t))}#n=t=>{w("handleWebSocketClose()",t);try{this.#d(t)}finally{this.close()}};#o=t=>{w("handleWebSocketError()",t),this.onerror?.(t)};#r=async t=>{w("handleWebSocketMessage()",t),this.#c?.();const n=this.#u(t);if(!n){w("handleWebSocketMessage() -> legacy"),this.onmessage?.(t);return}w("handleWebSocketMessage() -> jsonrpc",n),this[F].dispatchMessage(n)};#s=t=>{w("handleWebSocketOpen()",t),this.onopen?.(t)};#u(t){try{const n=E(new Uint8Array(t.data));return z(n)?n:null}catch{return null}}}function b(e){return typeof e=="object"&&e!==null}function I(e){try{const t=E(new Uint8Array(e.data));if(b(t)&&typeof t.name=="string")return{name:t.name,payload:"payload"in t?t.payload:void 0}}catch{}}async function ve(e,t={}){const n=t.baseUrl??(typeof e=="string"?new URL(e).origin:void 0),o=typeof e=="string"?new L(e,{signal:t.signal}):e,r=new V(o,{...t,baseUrl:n});return typeof e=="string"&&await me(o,r,t),r}function me(e,t,n){const o=j(n)?.onLegacyMessage;return new Promise((r,s)=>{e.onopen=()=>{r()},e.onclose=()=>{t.close(),n.signal?.aborted?s(n.signal.reason):s(new Error("The websocket was closed before the device connection was established"))},e.onerror=s,e.onmessage=i=>{const c=I(i);c&&o?.(c)}})}async function ye(e,{onStateChange:t,signal:n}){n?.throwIfAborted(),t?.({phase:"starting"}),await new Promise((o,r)=>{const s=()=>{i(),r(n?.reason)},i=()=>{e.onmessage=void 0,e.onclose=void 0,n?.removeEventListener("abort",s)};e.onmessage=c=>{const a=be(I(c));a&&(t?.(a),a.phase==="ready"&&(i(),o()))},e.onclose=()=>{i(),r(new Error("The device closed before it was ready"))},n?.addEventListener("abort",s,{once:!0})})}function be(e){if(!e)return;if(e.name==="ready")return{phase:"ready"};if(e.name!=="launchStatus")return;switch(b(e.payload)&&typeof e.payload.status=="string"?e.payload.status:void 0){case"downloadingApp":return{phase:"downloadingApp"};case"installingApp":return{phase:"installingApp"};case"launchingApp":return{phase:"launchingApp"};default:return}}function Se(){return typeof process>"u"?void 0:process}function Ee(e){return e==="intercept"?"interceptOnDemand":e}function Te(e,{onClose:t,onEvent:n,signal:o}={}){return new Promise((r,s)=>{const i=new WebSocket(e);i.binaryType="arraybuffer",i.onopen=()=>{W(i,{capabilities:{},t:"handshake"})},i.onmessage=c=>{Le(i,c,{onEvent:n,onHandshake:a=>{r({close:()=>{i.close()},id:a})}})},i.onclose=()=>{s(new v("disconnected",`The connection to ${e} closed`)),t?.()},o?.addEventListener("abort",()=>{s(o.reason),i.close()},{once:!0})})}function Le(e,t,n){const o=E(new Uint8Array(t.data));b(o)&&(o.t==="handshake"&&typeof o.id=="string"?n.onHandshake(o.id):o.name==="ping"?W(e,{name:"pong"}):typeof o.name=="string"&&n.onEvent?.(o.name,o.payload))}function W(e,t){e.send(A(t))}async function ke(e,t,{apiToken:n,onQueue:o,signal:r}={}){const s=N();s.promise.catch(()=>{}),Pe(s.reject,r);const i=await Te(Ie(e),{onClose:()=>{s.reject(Ae())},onEvent:(c,a)=>{$e(c,a,s,o)},signal:r});return Re(e,{apiToken:n,data:t,socketid:i.id},r).catch(s.reject),await s.promise.finally(()=>{i.close()})}function Ae(){return new v("disconnected","The webserver connection closed before a session was granted")}function U(e,t){return b(e)?e[t]:void 0}function $e(e,t,n,o){if(e==="queue"||e==="concurrentQueue"){const r=e==="queue"?Ue(t):Ce(t);r&&o?.(r)}else e==="newSession"?We(n,t):e==="userError"&&n.reject(new v("denied",De(t)))}function C(e,t){const n=U(e,t);return typeof n=="number"?n:void 0}function m(e,t){const n=U(e,t);return typeof n=="string"?n:void 0}async function Re(e,t,n){const o=await fetch(new URL("/api/session/request",e),{body:JSON.stringify(t),headers:{"content-type":"application/json"},method:"POST",signal:n});if(!o.ok)throw new v("denied",await qe(o))}function Pe(e,t){t?.addEventListener("abort",()=>{e(t.reason)},{once:!0})}function Ie(e){const t=new URL("/client",e);return t.protocol=t.protocol==="http:"?"ws:":"wss:",t.href}function We(e,t){const n=m(t,"path"),o=m(t,"sessionToken");n!==void 0&&o!==void 0?e.resolve({path:n,sessionToken:o}):e.reject(new v("denied","The granted session is missing its address"))}function Ue(e){const t=C(e,"position");return t===void 0?void 0:{position:t,reason:"capacity"}}function Ce(e){const t=C(e,"position");if(t!==void 0)return{limit:m(e,"name")??"Queue",position:t,reason:"concurrency"}}function De(e){return m(e,"message")??"The session request was denied"}async function qe(e){const t=`The webserver rejected the session request (${String(e.status)})`,n=await e.json().catch(()=>{}),o=m(n,"message");return o?`${t}: ${o}`:t}async function Me({apiToken:e=Oe(),codec:t="h264",device:n,endpoint:o="https://appetize.io",launch:r,onStateChange:s,proxy:i,signal:c,target:a}){c?.throwIfAborted(),H({apiToken:e,codec:t,device:n,endpoint:o,launch:r,proxy:i,target:a}),s?.({phase:"requesting"});const d=await ke(o,{codec:t,noVideo:!0,proxy:Ee(i),publicKey:a,...J(n),...Q(r)},{apiToken:e,onQueue:h=>{s?.({phase:"queued",queue:h})},signal:c});return{baseUrl:new URL(d.path).origin,sessionToken:d.sessionToken,url:xe(d)}}function Oe(){return Se()?.env.APPETIZE_API_TOKEN}function xe(e){const t=new URL("/client",e.path);return t.protocol=t.protocol==="http:"?"ws:":"wss:",t.searchParams.set("sessionToken",e.sessionToken),t.href}async function _e(e,{host:t="127.0.0.1",onError:n,port:o=0,signal:r}={}){r?.throwIfAborted();let s;const i=()=>{const u=s;s=void 0,u&&(u.tunnel?.close(),u.socket.destroy())},c=async u=>{const{socket:l}=u;try{const p=await e.debug.createAdbTunnel();if(l.destroyed){p.close();return}u.tunnel=p,p.closed.catch(S=>{n?.(S)}),Fe(l,p)}catch(p){l.destroyed||n?.(p),l.destroy()}},a=R(u=>{i();const l={socket:u};s=l,u.once("close",()=>{s===l&&(s=void 0)}),c(l)}),d=()=>{r?.removeEventListener("abort",d),i(),a.close()};r?.addEventListener("abort",d,{once:!0});const h=await ze(a,t,o);return{close:d,url:new URL(`adb://${h.address}:${String(h.port)}`)}}function Fe(e,t){P(t.readable,e,D),P(e,async n=>{const o=t.writable.getWriter();try{for await(const r of n)await o.write(r);await o.close()}catch(r){throw await o.abort(r),r}},D)}function D(){}function ze(e,t,n){return new Promise((o,r)=>{e.once("error",r),e.listen({host:t,port:n},()=>{e.off("error",r);const s=e.address();if(s===null||typeof s=="string"){r(new Error("The listener has no tcp address"));return}o(s)})})}async function Ve(e,{methods:t={},path:n,signal:o}){o?.throwIfAborted(),await te(n,{force:!0});const r=new Set,s=R(c=>{r.add(c),c.once("close",()=>{r.delete(c)}),$(new G(c),e,{leftEffects:()=>t})}),i=()=>{o?.removeEventListener("abort",i);for(const c of r)c.destroy();s.close()};return await je(s,n),o?.aborted&&(i(),o.throwIfAborted()),o?.addEventListener("abort",i,{once:!0}),{close:i,path:n}}function je(e,t){return new Promise((n,o)=>{e.once("error",o),e.listen(t,()=>{e.off("error",o),n()})})}const Ne=T("appetize:daemon");function f(e){Ne(e)}function He(e,{message:t="The operation timed out"}={}){const n=new AbortController,o=setTimeout(()=>{n.abort(new Error(t))},e),r=()=>{clearTimeout(o)};return{cancel:r,signal:n.signal,[Symbol.dispose]:r}}var Qe=(e,t)=>(t=Symbol[e])?t:Symbol.for("Symbol."+e),q=e=>{throw TypeError(e)},Je=(e,t,n)=>{if(t!=null){typeof t!="object"&&typeof t!="function"&&q("Object expected");var o,r;o===void 0&&(o=t[Qe("dispose")]),typeof o!="function"&&q("Object not disposable"),r&&(o=function(){try{r.call(this)}catch(s){return Promise.reject(s)}}),e.push([n,o,t])}return t},Ge=(e,t,n)=>{var o=typeof SuppressedError=="function"?SuppressedError:function(i,c,a,d){return d=Error(a),d.name="SuppressedError",d.error=i,d.suppressed=c,d},r=i=>t=n?new o(i,t,"An error was suppressed during disposal"):(n=!0,i),s=i=>{for(;i=e.pop();)try{var c=i[1]&&i[1].call(i[2]);if(i[0])return Promise.resolve(c).then(s,a=>(r(a),s()))}catch(a){r(a)}if(n)throw t};return s()};const Ke=1e4;async function Ze(e,t,{onClose:n,signal:o}={}){var r=[];try{const c=Je(r,He(Ke,{message:"Timed out waiting for session request state"})),a=AbortSignal.any([o,c.signal].filter(g=>!!g)),d=g=>{t.save({state:g}),f(g.phase),g.phase!=="requesting"&&c.cancel()},{featureFlags:h,sessionId:u,...l}=e,{baseUrl:p,url:S}=await Me({...l,onStateChange:d,signal:a});t.save({baseUrl:p});const y=new L(S,{signal:a});return await ye(y,{onStateChange:d,signal:a}),y.onclose=()=>{n?.("The device connection closed")},{device:await ve(y,{baseUrl:p,signal:a}),transport:y}}catch(c){var s=c,i=!0}finally{Ge(r,s,i)}}function Xe(){const e=K(),t=Z(e.sessionId,e.proxy),n=X({device:e.device,endpoint:e.endpoint,open:e.launch?.url,pid:process.pid,proxy:e.proxy,sessionId:e.sessionId,startedAt:new Date().toISOString(),target:e.target});return n.save({logs:t}),{config:e,logs:t,store:n}}async function Ye(e,t,n,{signal:o}={}){try{if(!await Be(t))return;const r=await _e(e,{onError:s=>{f(`adb endpoint error: ${M(s)}`)},signal:o});n.save({adbSerial:r.url.host}),f(`adb endpoint listening at ${r.url.host}`)}catch(r){f(`adb endpoint unavailable: ${M(r)}`)}}async function Be(e){return await Y(e.device.id,{endpoint:e.endpoint})==="android"}function M(e){return e instanceof Error?e.message:String(e)}async function et(e,t,n,{recorder:o,signal:r}){const{path:s}=await Ve(e,{methods:{"appetizeio.cli.record.start":async i=>await o.start(i),"appetizeio.cli.record.stop":async()=>await o.stop()},path:B(n),signal:r});return t.save({controlSocket:s}),s}const O="127.0.0.1";async function tt(e,t,n={}){try{const o=await nt(e,n);return t.save({viewerUrl:o.url.href}),f(`web endpoint listening at ${o.url.href}`),o}catch(o){f(`web endpoint unavailable: ${at(o)}`);return}}async function nt(e,{port:t=0,signal:n,viewerHtml:o=ne(new URL("./viewer.html",import.meta.url),"utf8")}){n?.throwIfAborted();const r=ie((u,l)=>{rt(u,l,o)}),s=new Set,i=new ae({noServer:!0,perMessageDeflate:!1});let c;i.on("connection",u=>{if(s.size>0){u.close(1013,"Viewer already connected");return}s.add(u);const l=new L(u);$(l,e),u.once("close",()=>{s.delete(u)})}),r.on("upgrade",(u,l,p)=>{st(i,u,l,p)});const a=()=>(c??=new Promise((u,l)=>{n?.removeEventListener("abort",d);for(const p of s)ot(p);i.close(),r.close(p=>{p?l(p):u()})}),c),d=()=>{a()};await it(r,t),n?.addEventListener("abort",d,{once:!0});const h=r.address();if(!h||typeof h=="string")throw await a(),new Error("Web address unavailable");return{close:a,url:new URL(`http://${O}:${String(h.port)}/`)}}function ot(e){e.close(1001)}function rt(e,t,n){if(e.method==="GET"&&e.url==="/"){t.writeHead(200,{"Cache-Control":"no-store","Content-Type":"text/html; charset=utf-8"}),t.end(n);return}t.writeHead(404).end()}function st(e,t,n,o){if(t.url!=="/ws"){n.destroy();return}e.handleUpgrade(t,n,o,r=>{e.emit("connection",r,t)})}function it(e,t){return new Promise((n,o)=>{const r=s=>{o(s)};e.once("error",r),e.listen(t,O,()=>{e.removeListener("error",r),n()})})}function at(e){return e instanceof Error?e.message:String(e)}function ct(e){const t=new AbortController,n=dt(e,t),o=ee();return o.addEventListener("abort",()=>{const{reason:r}=o;n(r instanceof Error?r.message:String(r))},{once:!0}),{shutdown:n,signal:t.signal}}function dt(e,t){let n=!1;return o=>{n||(n=!0,e.save({endedAt:new Date().toISOString(),endedReason:o,state:{phase:"ended"}}),f(o),t.abort())}}async function x(e,t,{label:n,signal:o}){try{const r=await e();await ce(r.readable.pipeThrough(ut()),oe(t,{flags:"a"}))}catch(r){if(o?.aborted)return;const s=r instanceof Error?r.message:String(r);f(`${n} ended with an error: ${s}`)}}function ut(){return new TransformStream({transform:(e,t)=>{t.enqueue(`${JSON.stringify(e)}
2
- `)}})}async function lt(e,t,{signal:n}={}){await x(async()=>await e.debug.createLogStream({signal:n}),t,{label:"log capture",signal:n})}async function ft(e,t,{signal:n}={}){await x(async()=>await e.debug.createProxyInterceptStream({signal:n}),t,{label:"network capture",signal:n})}const k=30;async function pt(e,t){await e.pipeTo(wt(t))}function ht(e){return{decoderConfig:{codec:"avc1.640028",codedHeight:e.height,codedWidth:e.width}}}function wt(e){let t;const n=async()=>{await t?.output.finalize()};return new WritableStream({abort:n,close:n,write:async o=>{o.data.byteLength!==0&&(t??=await gt(mt(o),e),vt(t,o),await yt(t,o))}})}async function gt(e,t){const n=new de("avc"),o=new ue({format:new fe({fastStart:"fragmented"}),target:new le(t,{chunked:!1})});return o.addVideoTrack(n,{frameRate:k}),await o.start(),{frame:0,output:o,seen:{height:e.height,width:e.width},size:{height:e.height,width:e.width},source:n}}function vt(e,t){if(t.type!=="key")return;const{seen:n,size:o}=e;t.width===n.width&&t.height===n.height||(e.seen={height:t.height,width:t.width},f(`video resized to ${String(t.width)}x${String(t.height)}; keeping ${String(o.width)}x${String(o.height)}`))}function mt(e){if(e.type!=="key")throw new Error("Video stream started without a key chunk");return e}async function yt(e,t){const n=new pe(t.data,t.type,e.frame/k,1/k);e.frame+=1,await e.source.add(n,ht(e.size))}function bt(e,t,{signal:n}={}){let o,r;const s=async(a,{force:d=!1}={})=>{if(re(a)){if(!d)throw new Error(`A recording already exists at ${a}; pass --force to overwrite`);se(a)}const h=await e.video.createStream({signal:n});return o={done:St(h,a),path:a,stream:h},t.save({video:{path:a,recording:!0}}),f(`recording video to ${a}`),{path:a}},i=async a=>{a.stream.close();try{await a.done,t.save({video:{path:a.path,recording:!1}})}finally{o=void 0,r=void 0}},c=async()=>{if(!o)return;const{path:a}=o;await i(o),f(`closed the video recording: ${a}`)};return n?.addEventListener("abort",()=>{c()},{once:!0}),{start:async({force:a=!1,path:d})=>{const h=o?.path??r;if(h!==void 0)throw new Error(`Already recording to ${h}`);r=d;try{return await s(d,{force:a})}finally{r=void 0}},stop:async()=>{if(!o)throw new Error("No video recording in progress");const{path:a}=o;return await i(o),{path:a}}}}async function St(e,t){try{await pt(e.readable,t)}catch(n){f(`video capture ended with an error: ${String(n)}`)}}async function Et(){const{config:e,logs:t,store:n}=Xe();f(`recording to ${n.path}`);const{shutdown:o,signal:r}=ct(n);try{const{device:s,transport:i}=await Ze(e,n,{onClose:o,signal:r}),c=bt(s,n,{signal:r});await Ye(s,e,n,{signal:r}),await tt(i,n,{signal:r});const a=await et(i,n,e.sessionId,{recorder:c,signal:r});f(`control socket listening at ${a}`),lt(s,t.device,{signal:r}),f(`recording device logs to ${t.device}`),t.network&&(ft(s,t.network,{signal:r}),f(`recording network events to ${t.network}`))}catch(s){if(r.aborted)return;const i=s instanceof Error?s.message:String(s);n.save({endedAt:new Date().toISOString(),endedReason:i,state:{message:i,phase:"error"}}),f(`error: ${i}`),process.exitCode=1}}Et();
1
+ import{T as _,P as A,Q as F,R as T,V as z,J as V,W as j,y as v,X as N,x as H,Y as Q,Z as J,_ as $,$ as G,a0 as K,F as Z,a1 as X,a2 as Y,a3 as B,a4 as ee}from"./stream-C_BND5fe.js";import b from"debug";import{createServer as R}from"node:net";import{pipeline as P}from"node:stream";import{rm as te}from"node:fs/promises";import{readFileSync as ne,createWriteStream as oe,existsSync as re,rmSync as se}from"node:fs";import{createServer as ie}from"node:http";import{WebSocketServer as ae}from"ws";import{pipeline as ce}from"node:stream/promises";import{EncodedVideoPacketSource as de,Output as ue,Mp4OutputFormat as le,EncodedPacket as fe,FilePathTarget as pe}from"mediabunny";import"json-rpc-2.0";import"zod/mini";import"node:path";import"node:os";import"stream";import"module";const he=b("appetize.io:transport:ws-ping"),we=3e4;function ge(e){let t=!0;const n=()=>{t=!0};e.on("pong",n);const o=setInterval(()=>{if(!t){clearInterval(o),he("liveness ping went unanswered, terminating"),e.terminate();return}e.readyState===e.OPEN&&(t=!1,e.ping())},we);return{destroy(){clearInterval(o),e.off("pong",n)},pong:n}}const w=b("appetize.io:trace:transport:websocket");class L extends _{constructor(t,{signal:n}={}){super(async r=>{this.#e.send(A(r))},{signal:n}),this.wsOrUrl=t,typeof t=="string"?(this.#e=new WebSocket(t),this.#e.binaryType="arraybuffer"):this.#e=t;const o=this.#e;if(o instanceof WebSocket?(o.addEventListener("open",this.#s),o.addEventListener("message",this.#r),o.addEventListener("error",this.#o),o.addEventListener("close",this.#n),this.#t.push(()=>{o.removeEventListener("open",this.#s),o.removeEventListener("message",this.#r),o.removeEventListener("error",this.#o),o.removeEventListener("close",this.#n)})):(o.addEventListener("open",this.#s),o.addEventListener("message",this.#r),o.addEventListener("error",this.#o),o.addEventListener("close",this.#n),this.#t.push(()=>{o.removeEventListener("open",this.#s),o.removeEventListener("message",this.#r),o.removeEventListener("error",this.#o),o.removeEventListener("close",this.#n)})),this.send=o.send.bind(o),"ping"in o){const{destroy:r,pong:s}=ge(o);this.#c=s,this.#t.push(r)}}wsOrUrl;onclose;onerror;onmessage;onopen;send;get bufferedAmount(){return this.#e.bufferedAmount}get readyState(){return this.#e.readyState}#t=[];#i=!1;#a=!1;#c;#e;close({destroyWs:t=!1,...n}={}){this.closed||(this.#i=t,super.close(n))}handleClose(t){w("close()");for(const n of this.#t.splice(0))n();if((typeof this.wsOrUrl=="string"||this.#i)&&(this.#e.close(t.code,t.reason),"terminate"in this.#e)){const n=this.#e;setTimeout(()=>{n.terminate()},100)}this.#d(),super.handleClose(t)}#d(t){this.#a||(this.#a=!0,this.onclose?.(t))}#n=t=>{w("handleWebSocketClose()",t);try{this.#d(t)}finally{this.close()}};#o=t=>{w("handleWebSocketError()",t),this.onerror?.(t)};#r=async t=>{w("handleWebSocketMessage()",t),this.#c?.();const n=this.#u(t);if(!n){w("handleWebSocketMessage() -> legacy"),this.onmessage?.(t);return}w("handleWebSocketMessage() -> jsonrpc",n),this[F].dispatchMessage(n)};#s=t=>{w("handleWebSocketOpen()",t),this.onopen?.(t)};#u(t){try{const n=T(new Uint8Array(t.data));return z(n)?n:null}catch{return null}}}function S(e){return typeof e=="object"&&e!==null}function I(e){try{const t=T(new Uint8Array(e.data));if(S(t)&&typeof t.name=="string")return{name:t.name,payload:"payload"in t?t.payload:void 0}}catch{}}async function ve(e,t={}){const n=t.baseUrl??(typeof e=="string"?new URL(e).origin:void 0),o=typeof e=="string"?new L(e,{signal:t.signal}):e,r=new V(o,{...t,baseUrl:n});return typeof e=="string"&&await ye(o,r,t),r}function ye(e,t,n){const o=j(n)?.onLegacyMessage;return new Promise((r,s)=>{e.onopen=()=>{r()},e.onclose=()=>{t.close(),n.signal?.aborted?s(n.signal.reason):s(new Error("The websocket was closed before the device connection was established"))},e.onerror=s,e.onmessage=i=>{const c=I(i);c&&o?.(c)}})}const me=b("appetize:client:render-video-to-mp4"),k=30;async function be(e,t){await e.pipeTo(Ee(t))}function Se(e){return{decoderConfig:{codec:"avc1.640028",codedHeight:e.height,codedWidth:e.width}}}function Ee(e){let t;const n=async()=>{await t?.output.finalize()};return new WritableStream({abort:n,close:n,write:async o=>{if(o.data.byteLength!==0)try{t??=await Te(ke(o),e()),Le(t,o),await Ae(t,o)}catch(r){throw await t?.output.cancel(),r}}})}async function Te(e,t){const n=new de("avc"),o=new ue({format:new le({fastStart:"fragmented"}),target:t});return o.addVideoTrack(n,{frameRate:k}),await o.start(),{frame:0,output:o,seen:{height:e.height,width:e.width},size:{height:e.height,width:e.width},source:n}}function Le(e,t){if(t.type!=="key")return;const{seen:n,size:o}=e;t.width===n.width&&t.height===n.height||(e.seen={height:t.height,width:t.width},me(`video resized to ${String(t.width)}x${String(t.height)}; keeping ${String(o.width)}x${String(o.height)}`))}function ke(e){if(e.type!=="key")throw new Error("Video stream started without a key chunk");return e}async function Ae(e,t){const n=new fe(t.data,t.type,e.frame/k,1/k);e.frame+=1,await e.source.add(n,Se(e.size))}async function $e(e,{onStateChange:t,signal:n}){n?.throwIfAborted(),t?.({phase:"starting"}),await new Promise((o,r)=>{const s=()=>{i(),r(n?.reason)},i=()=>{e.onmessage=void 0,e.onclose=void 0,n?.removeEventListener("abort",s)};e.onmessage=c=>{const a=Re(I(c));a&&(t?.(a),a.phase==="ready"&&(i(),o()))},e.onclose=()=>{i(),r(new Error("The device closed before it was ready"))},n?.addEventListener("abort",s,{once:!0})})}function Re(e){if(!e)return;if(e.name==="ready")return{phase:"ready"};if(e.name!=="launchStatus")return;switch(S(e.payload)&&typeof e.payload.status=="string"?e.payload.status:void 0){case"downloadingApp":return{phase:"downloadingApp"};case"installingApp":return{phase:"installingApp"};case"launchingApp":return{phase:"launchingApp"};default:return}}function Pe(){return typeof process>"u"?void 0:process}function Ie(e){return e==="intercept"?"interceptOnDemand":e}function We(e,{onClose:t,onEvent:n,signal:o}={}){return new Promise((r,s)=>{const i=new WebSocket(e);i.binaryType="arraybuffer",i.onopen=()=>{W(i,{capabilities:{},t:"handshake"})},i.onmessage=c=>{Ue(i,c,{onEvent:n,onHandshake:a=>{r({close:()=>{i.close()},id:a})}})},i.onclose=()=>{s(new v("disconnected",`The connection to ${e} closed`)),t?.()},o?.addEventListener("abort",()=>{s(o.reason),i.close()},{once:!0})})}function Ue(e,t,n){const o=T(new Uint8Array(t.data));S(o)&&(o.t==="handshake"&&typeof o.id=="string"?n.onHandshake(o.id):o.name==="ping"?W(e,{name:"pong"}):typeof o.name=="string"&&n.onEvent?.(o.name,o.payload))}function W(e,t){e.send(A(t))}async function Ce(e,t,{apiToken:n,onQueue:o,signal:r}={}){const s=N();s.promise.catch(()=>{}),Oe(s.reject,r);const i=await We(xe(e),{onClose:()=>{s.reject(De())},onEvent:(c,a)=>{Me(c,a,s,o)},signal:r});return qe(e,{apiToken:n,data:t,socketid:i.id},r).catch(s.reject),await s.promise.finally(()=>{i.close()})}function De(){return new v("disconnected","The webserver connection closed before a session was granted")}function U(e,t){return S(e)?e[t]:void 0}function Me(e,t,n,o){if(e==="queue"||e==="concurrentQueue"){const r=e==="queue"?Fe(t):ze(t);r&&o?.(r)}else e==="newSession"?_e(n,t):e==="userError"&&n.reject(new v("denied",Ve(t)))}function C(e,t){const n=U(e,t);return typeof n=="number"?n:void 0}function y(e,t){const n=U(e,t);return typeof n=="string"?n:void 0}async function qe(e,t,n){const o=await fetch(new URL("/api/session/request",e),{body:JSON.stringify(t),headers:{"content-type":"application/json"},method:"POST",signal:n});if(!o.ok)throw new v("denied",await je(o))}function Oe(e,t){t?.addEventListener("abort",()=>{e(t.reason)},{once:!0})}function xe(e){const t=new URL("/client",e);return t.protocol=t.protocol==="http:"?"ws:":"wss:",t.href}function _e(e,t){const n=y(t,"path"),o=y(t,"sessionToken");n!==void 0&&o!==void 0?e.resolve({path:n,sessionToken:o}):e.reject(new v("denied","The granted session is missing its address"))}function Fe(e){const t=C(e,"position");return t===void 0?void 0:{position:t,reason:"capacity"}}function ze(e){const t=C(e,"position");if(t!==void 0)return{limit:y(e,"name")??"Queue",position:t,reason:"concurrency"}}function Ve(e){return y(e,"message")??"The session request was denied"}async function je(e){const t=`The webserver rejected the session request (${String(e.status)})`,n=await e.json().catch(()=>{}),o=y(n,"message");return o?`${t}: ${o}`:t}async function Ne({apiToken:e=He(),codec:t="h264",device:n,endpoint:o="https://appetize.io",launch:r,onStateChange:s,proxy:i,signal:c,target:a}){c?.throwIfAborted(),H({apiToken:e,codec:t,device:n,endpoint:o,launch:r,proxy:i,target:a}),s?.({phase:"requesting"});const d=await Ce(o,{codec:t,noVideo:!0,proxy:Ie(i),publicKey:a,...J(n),...Q(r)},{apiToken:e,onQueue:h=>{s?.({phase:"queued",queue:h})},signal:c});return{baseUrl:new URL(d.path).origin,sessionToken:d.sessionToken,url:Qe(d)}}function He(){return Pe()?.env.APPETIZE_API_TOKEN}function Qe(e){const t=new URL("/client",e.path);return t.protocol=t.protocol==="http:"?"ws:":"wss:",t.searchParams.set("sessionToken",e.sessionToken),t.href}async function Je(e,t){await be(e,()=>new pe(t,{chunked:!1}))}async function Ge(e,{host:t="127.0.0.1",onError:n,port:o=0,signal:r}={}){r?.throwIfAborted();let s;const i=()=>{const u=s;s=void 0,u&&(u.tunnel?.close(),u.socket.destroy())},c=async u=>{const{socket:l}=u;try{const f=await e.debug.createAdbTunnel();if(l.destroyed){f.close();return}u.tunnel=f,f.closed.catch(E=>{n?.(E)}),Ke(l,f)}catch(f){l.destroyed||n?.(f),l.destroy()}},a=R(u=>{i();const l={socket:u};s=l,u.once("close",()=>{s===l&&(s=void 0)}),c(l)}),d=()=>{r?.removeEventListener("abort",d),i(),a.close()};r?.addEventListener("abort",d,{once:!0});const h=await Ze(a,t,o);return{close:d,url:new URL(`adb://${h.address}:${String(h.port)}`)}}function Ke(e,t){P(t.readable,e,D),P(e,async n=>{const o=t.writable.getWriter();try{for await(const r of n)await o.write(r);await o.close()}catch(r){throw await o.abort(r),r}},D)}function D(){}function Ze(e,t,n){return new Promise((o,r)=>{e.once("error",r),e.listen({host:t,port:n},()=>{e.off("error",r);const s=e.address();if(s===null||typeof s=="string"){r(new Error("The listener has no tcp address"));return}o(s)})})}async function Xe(e,{methods:t={},path:n,signal:o}){o?.throwIfAborted(),await te(n,{force:!0});const r=new Set,s=R(c=>{r.add(c),c.once("close",()=>{r.delete(c)}),$(new G(c),e,{leftEffects:()=>t})}),i=()=>{o?.removeEventListener("abort",i);for(const c of r)c.destroy();s.close()};return await Ye(s,n),o?.aborted&&(i(),o.throwIfAborted()),o?.addEventListener("abort",i,{once:!0}),{close:i,path:n}}function Ye(e,t){return new Promise((n,o)=>{e.once("error",o),e.listen(t,()=>{e.off("error",o),n()})})}const Be=b("appetize:daemon");function p(e){Be(e)}function et(e,{message:t="The operation timed out"}={}){const n=new AbortController,o=setTimeout(()=>{n.abort(new Error(t))},e),r=()=>{clearTimeout(o)};return{cancel:r,signal:n.signal,[Symbol.dispose]:r}}var tt=(e,t)=>(t=Symbol[e])?t:Symbol.for("Symbol."+e),M=e=>{throw TypeError(e)},nt=(e,t,n)=>{if(t!=null){typeof t!="object"&&typeof t!="function"&&M("Object expected");var o,r;o===void 0&&(o=t[tt("dispose")]),typeof o!="function"&&M("Object not disposable"),r&&(o=function(){try{r.call(this)}catch(s){return Promise.reject(s)}}),e.push([n,o,t])}return t},ot=(e,t,n)=>{var o=typeof SuppressedError=="function"?SuppressedError:function(i,c,a,d){return d=Error(a),d.name="SuppressedError",d.error=i,d.suppressed=c,d},r=i=>t=n?new o(i,t,"An error was suppressed during disposal"):(n=!0,i),s=i=>{for(;i=e.pop();)try{var c=i[1]&&i[1].call(i[2]);if(i[0])return Promise.resolve(c).then(s,a=>(r(a),s()))}catch(a){r(a)}if(n)throw t};return s()};const rt=1e4;async function st(e,t,{onClose:n,signal:o}={}){var r=[];try{const c=nt(r,et(rt,{message:"Timed out waiting for session request state"})),a=AbortSignal.any([o,c.signal].filter(g=>!!g)),d=g=>{t.save({state:g}),p(g.phase),g.phase!=="requesting"&&c.cancel()},{featureFlags:h,sessionId:u,...l}=e,{baseUrl:f,url:E}=await Ne({...l,onStateChange:d,signal:a});t.save({baseUrl:f});const m=new L(E,{signal:a});return await $e(m,{onStateChange:d,signal:a}),m.onclose=()=>{n?.("The device connection closed")},{device:await ve(m,{baseUrl:f,signal:a}),transport:m}}catch(c){var s=c,i=!0}finally{ot(r,s,i)}}function it(){const e=K(),t=Z(e.sessionId,e.proxy),n=X({device:e.device,endpoint:e.endpoint,open:e.launch?.url,pid:process.pid,proxy:e.proxy,sessionId:e.sessionId,startedAt:new Date().toISOString(),target:e.target});return n.save({logs:t}),{config:e,logs:t,store:n}}async function at(e,t,n,{signal:o}={}){try{if(!await ct(t))return;const r=await Ge(e,{onError:s=>{p(`adb endpoint error: ${q(s)}`)},signal:o});n.save({adbSerial:r.url.host}),p(`adb endpoint listening at ${r.url.host}`)}catch(r){p(`adb endpoint unavailable: ${q(r)}`)}}async function ct(e){return await Y(e.device.id,{endpoint:e.endpoint})==="android"}function q(e){return e instanceof Error?e.message:String(e)}async function dt(e,t,n,{recorder:o,signal:r}){const{path:s}=await Xe(e,{methods:{"appetizeio.cli.record.start":async i=>await o.start(i),"appetizeio.cli.record.stop":async()=>await o.stop()},path:B(n),signal:r});return t.save({controlSocket:s}),s}const O="127.0.0.1";async function ut(e,t,n={}){try{const o=await lt(e,n);return t.save({viewerUrl:o.url.href}),p(`web endpoint listening at ${o.url.href}`),o}catch(o){p(`web endpoint unavailable: ${gt(o)}`);return}}async function lt(e,{port:t=0,signal:n,viewerHtml:o=ne(new URL("./viewer.html",import.meta.url),"utf8")}){n?.throwIfAborted();const r=ie((u,l)=>{pt(u,l,o)}),s=new Set,i=new ae({noServer:!0,perMessageDeflate:!1});let c;i.on("connection",u=>{if(s.size>0){u.close(1013,"Viewer already connected");return}s.add(u);const l=new L(u);$(l,e),u.once("close",()=>{s.delete(u)})}),r.on("upgrade",(u,l,f)=>{ht(i,u,l,f)});const a=()=>(c??=new Promise((u,l)=>{n?.removeEventListener("abort",d);for(const f of s)ft(f);i.close(),r.close(f=>{f?l(f):u()})}),c),d=()=>{a()};await wt(r,t),n?.addEventListener("abort",d,{once:!0});const h=r.address();if(!h||typeof h=="string")throw await a(),new Error("Web address unavailable");return{close:a,url:new URL(`http://${O}:${String(h.port)}/`)}}function ft(e){e.close(1001)}function pt(e,t,n){if(e.method==="GET"&&e.url==="/"){t.writeHead(200,{"Cache-Control":"no-store","Content-Type":"text/html; charset=utf-8"}),t.end(n);return}t.writeHead(404).end()}function ht(e,t,n,o){if(t.url!=="/ws"){n.destroy();return}e.handleUpgrade(t,n,o,r=>{e.emit("connection",r,t)})}function wt(e,t){return new Promise((n,o)=>{const r=s=>{o(s)};e.once("error",r),e.listen(t,O,()=>{e.removeListener("error",r),n()})})}function gt(e){return e instanceof Error?e.message:String(e)}function vt(e){const t=new AbortController,n=yt(e,t),o=ee();return o.addEventListener("abort",()=>{const{reason:r}=o;n(r instanceof Error?r.message:String(r))},{once:!0}),{shutdown:n,signal:t.signal}}function yt(e,t){let n=!1;return o=>{n||(n=!0,e.save({endedAt:new Date().toISOString(),endedReason:o,state:{phase:"ended"}}),p(o),t.abort())}}async function x(e,t,{label:n,signal:o}){try{const r=await e();await ce(r.readable.pipeThrough(mt()),oe(t,{flags:"a"}))}catch(r){if(o?.aborted)return;const s=r instanceof Error?r.message:String(r);p(`${n} ended with an error: ${s}`)}}function mt(){return new TransformStream({transform:(e,t)=>{t.enqueue(`${JSON.stringify(e)}
2
+ `)}})}async function bt(e,t,{signal:n}={}){await x(async()=>await e.debug.createLogStream({signal:n}),t,{label:"log capture",signal:n})}async function St(e,t,{signal:n}={}){await x(async()=>await e.debug.createProxyInterceptStream({signal:n}),t,{label:"network capture",signal:n})}function Et(e,t,{signal:n}={}){let o,r;const s=async(a,{force:d=!1}={})=>{if(re(a)){if(!d)throw new Error(`A recording already exists at ${a}; pass --force to overwrite`);se(a)}const h=await e.video.createStream({signal:n});return o={done:Tt(h,a),path:a,stream:h},t.save({video:{path:a,recording:!0}}),p(`recording video to ${a}`),{path:a}},i=async a=>{a.stream.close();try{await a.done,t.save({video:{path:a.path,recording:!1}})}finally{o=void 0,r=void 0}},c=async()=>{if(!o)return;const{path:a}=o;await i(o),p(`closed the video recording: ${a}`)};return n?.addEventListener("abort",()=>{c()},{once:!0}),{start:async({force:a=!1,path:d})=>{const h=o?.path??r;if(h!==void 0)throw new Error(`Already recording to ${h}`);r=d;try{return await s(d,{force:a})}finally{r=void 0}},stop:async()=>{if(!o)throw new Error("No video recording in progress");const{path:a}=o;return await i(o),{path:a}}}}async function Tt(e,t){try{await Je(e.readable,t)}catch(n){p(`video capture ended with an error: ${String(n)}`)}}async function Lt(){const{config:e,logs:t,store:n}=it();p(`recording to ${n.path}`);const{shutdown:o,signal:r}=vt(n);try{const{device:s,transport:i}=await st(e,n,{onClose:o,signal:r}),c=Et(s,n,{signal:r});await at(s,e,n,{signal:r}),await ut(i,n,{signal:r});const a=await dt(i,n,e.sessionId,{recorder:c,signal:r});p(`control socket listening at ${a}`),bt(s,t.device,{signal:r}),p(`recording device logs to ${t.device}`),t.network&&(St(s,t.network,{signal:r}),p(`recording network events to ${t.network}`))}catch(s){if(r.aborted)return;const i=s instanceof Error?s.message:String(s);n.save({endedAt:new Date().toISOString(),endedReason:i,state:{message:i,phase:"error"}}),p(`error: ${i}`),process.exitCode=1}}Lt();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@appetize/cli",
3
- "version": "0.25.0",
3
+ "version": "0.26.0",
4
4
  "description": "Run, inspect and control iOS and Android apps on Appetize cloud devices",
5
5
  "license": "SEE LICENSE IN LICENSE",
6
6
  "homepage": "https://appetize.io",
@@ -32,10 +32,10 @@
32
32
  "debug": "^4.4.3",
33
33
  "human-id": "^4.2.2",
34
34
  "json-rpc-2.0": "^1.8.1",
35
- "mediabunny": "^1.61.3",
35
+ "mediabunny": "^1.62.0",
36
36
  "sade": "^1.8.1",
37
37
  "ws": "^8.22.0",
38
38
  "yocto-spinner": "^1.2.2",
39
- "zod": "^4.6.5"
39
+ "zod": "^4.6.7"
40
40
  }
41
41
  }
@@ -10,7 +10,7 @@ description: >-
10
10
  or answering what is currently on screen — even if Appetize is not mentioned
11
11
  by name.
12
12
  metadata:
13
- cli-version: '0.25.0'
13
+ cli-version: '0.26.0'
14
14
  ---
15
15
 
16
16
  # Appetize
@@ -208,6 +208,10 @@ destination with `inspect --timeout`. A custom scheme needs its app installed.
208
208
  On iOS, `appetize keychain clear` clears the keychain without restarting the
209
209
  session.
210
210
 
211
+ ## Shake
212
+
213
+ `appetize shake` shakes the device.
214
+
211
215
  ## Full command reference
212
216
 
213
217
  Run `appetize <command> --help` for flags. `references/commands.md` covers
@@ -103,6 +103,10 @@ last second. A write failure is reported here, not when it happens.
103
103
  Playback is a constant 30fps, so it does not track real time. A rotation keeps
104
104
  the original dimensions.
105
105
 
106
+ ## shake
107
+
108
+ Returns once the shake finishes, about a second on Android.
109
+
106
110
  ## skill install
107
111
 
108
112
  Installs into each agent directory already present — `.claude/skills` for
@@ -0,0 +1,4 @@
1
+ import Ze from"debug";import{JSONRPCServerAndClient as Nr,JSONRPCServer as Dr,JSONRPCClient as zr,JSONRPC as Br}from"json-rpc-2.0";import*as m from"zod/mini";import{writeFileSync as Fr,renameSync as jr,mkdirSync as Ut,readFileSync as $r,rmSync as Vr,readdirSync as Kr}from"node:fs";import{sep as qr,join as oe}from"node:path";import{homedir as Pt}from"node:os";import{Transform as Wr}from"stream";import{createRequire as Jr}from"module";import{connect as Gr}from"node:net";class Hr extends Event{code;reason;wasClean;constructor(e,r={}){super(e,r),this.code=r.code??0,this.reason=r.reason??"",this.wasClean=r.wasClean??!1}}function Zr(t,e){const r="CloseEvent"in globalThis?globalThis.CloseEvent:Hr;return new r(t,e)}class Yr{#e=new EventTarget;addEventListener(e,r,s){return this.#e.addEventListener(e,r,s),()=>{this.#e.removeEventListener(e,r,s)}}removeEventListener(e,r,s){this.#e.removeEventListener(e,r,s)}dispatchEvent(e){return this.#e.dispatchEvent(e)}}const L=Symbol.for("@appetizeio/rpc:rpcMethods");class Qr extends Yr{send;constructor(e){super(),this.send=e}dispatchClose(e){return this.dispatchEvent(Zr("close",e))}dispatchMessage(e){return this.dispatchEvent(new CustomEvent("message",{detail:e}))}}const Xr="@appetizeio/rpc:playwrightAdapter";class xe{closed=!1;[L];#e;constructor(e,{signal:r}={}){this[L]=new Qr(e),this.#e=r,this.#e?.addEventListener("abort",this.#t)}close(e={}){this.closed||(this.closed=!0,this.handleClose(e))}handleClose(e){this.#e?.removeEventListener("abort",this.#t),this[L].dispatchClose(e)}#t=()=>{this.close({code:1e3,reason:String(this.#e?.reason)})}}const Ce=Symbol.for(Xr);function es(t){window[Ce]&&console.warn("playwright exposed more than once, overwriting previous adapter");const e={send(r){t[L].send(r)},subscribe(r){return t[L].addEventListener("message",s=>{r(s.detail)})}};return window[Ce]=e,()=>{window[Ce]===e&&delete window[Ce]}}const Ct=Ze("appetize.io:error:rpc");function Ye(t,e){const r=new Nr(new Dr({errorListener:Ct}),ts(t),{errorListener:Ct}),s=t[L].addEventListener("message",({detail:i})=>{r.receiveAndSend(i)}),n=t[L].addEventListener("close",()=>{s(),r.rejectAllPendingRequests("Transport closed")},{once:!0});for(const i in e){const a=e[i];a&&r.addMethod(i,a.bind(e))}return{rpc:r,unsub:()=>{s(),n()}}}function _t(t,e){const{rpc:r,unsub:s}=Ye(t,e);return{client:r.client,unsub:s}}function _e(t,e){const r=t[L].addEventListener("message",({detail:n})=>{if("method"in n)try{e({method:n.method,param:n.params})}catch{}}),s=t[L].addEventListener("close",r,{once:!0});return()=>{r(),s()}}function ts(t){return new zr(t[L].send.bind(t[L]),()=>Math.floor(Math.random()*Number.MAX_SAFE_INTEGER)+1)}function Qe(t,e,{leftEffects:r=()=>({}),notifiesLeft:s,notifiesRight:n,rightEffects:i=()=>({})}={}){const a=Ye(t,{}),y=Ye(e,{}),p=[()=>{a.unsub(),y.unsub()}],A=()=>{for(const _ of p)try{_()}catch{}},E=y.rpc.client,R=a.rpc.client;p.push(t[L].addEventListener("close",()=>{A()},{once:!0}),e[L].addEventListener("close",()=>{A()},{once:!0}));const M=r(E,R);for(const _ in M){const U=M[_];U&&a.rpc.addMethod(_,U)}const N=i(R,E);for(const _ in N){const U=N[_];U&&y.rpc.addMethod(_,U)}return Nt(a.rpc,y.rpc,{notifies:s}),Nt(y.rpc,a.rpc,{notifies:n}),A}function Nt(t,e,{notifies:r}={}){t.applyServerMiddleware(async(s,n)=>{const i=r?.();if(i){const{id:y,...p}=n;i[L].send(p)}if(t.hasMethod(n.method))return await s(n);if(!n.id)return e.notify(n.method,n.params),null;const a=await e.request(n.method,n.params);return{id:n.id,jsonrpc:Br,result:a}})}function re(t,...e){t.notify(e[0],e[1],e[2])}const rs=(...t)=>_t(...t),ss=["h264","jpeg"],Xe=["ArrowDown","ArrowLeft","ArrowRight","ArrowUp","Backspace","Enter","Tab"],Dt=["landscapeLeft","landscapeRight","portrait","upsideDown"],ns=["dark","light"],is=["xs","s","m","l","xl","xxl","xxxl"];function et(){const t=new xe(async r=>{e[L].dispatchMessage(r)}),e=new xe(async r=>{t[L].dispatchMessage(r)});return t[L].addEventListener("close",()=>{e.close()},{once:!0}),e[L].addEventListener("close",()=>{t.close()},{once:!0}),[t,e]}function zt(t,e){const r=[],s=()=>{for(const n of r)n()};r.push(t[L].addEventListener("message",n=>e[L].send(n.detail))),r.push(t[L].addEventListener("close",s,{once:!0})),r.push(e[L].addEventListener("message",n=>t[L].send(n.detail))),r.push(e[L].addEventListener("close",s,{once:!0}))}function tt(t){return!!t&&typeof t=="object"&&"jsonrpc"in t}const ae=Ze("appetize.io:trace:transport:iframe");class Bt extends xe{onmessage;#e;#t;constructor(e,{origin:r="*",signal:s}={}){super(async n=>{e.postMessage(n,this.#e)},{signal:s}),this.#t=e,this.#e=r,window.addEventListener("message",this.#r)}postMessage(e,r,s){ae("postMessage(legacy)",{message:e,targetOrigin:r,transfer:s}),this.#t.postMessage(e,r??this.#e,s)}handleClose(e){ae("close()"),window.removeEventListener("message",this.#r),super.handleClose(e)}#r=async e=>{if(ae("handleMessage()",e),e.source!==this.#t||(ae("handleMessage() -> source ok"),this.#e!=="*"&&e.origin!==this.#e))return;ae("handleMessage() -> origin ok");const r=e.data;if(!tt(r)){ae("handleMessage() -> legacy"),this.onmessage?.(e);return}ae("handleMessage() -> jsonrpc"),this[L].dispatchMessage(r)}}function os(t){return{clearState:async e=>{await t.request("appetizeio.device.server.app.clearState",{appId:e})},launch:async e=>{await t.request("appetizeio.device.server.app.launch",{appId:e})},reinstall:async e=>{await t.request("appetizeio.device.server.app.reinstall",{appId:e})},restart:async e=>{await t.request("appetizeio.device.server.app.restart",{appId:e})}}}function Ne(){let t,e;return{promise:new Promise((s,n)=>{e=s,t=n}),reject:t,resolve:e}}const as=2*1024*1024,Ft=Ze("appetize:client:acked-writable-stream");class cs{unacked=0;#e;#t;#r;#s;#n=[];#o;constructor(e){this.#r=e,this.#o=e.window??as}abort(e){this.#i(e),this.#r.onAbort?.(e)}async close(){await this.#c(()=>this.unacked===0),this.#r.onClose?.()}fail(e){this.#i(e)&&this.#r.onError?.(e)}start(e){this.#e=e}write(e){const r=e.byteLength;return this.unacked+=r,this.#r.send(e).then(()=>{this.unacked-=r,this.#s&&(this.#s.acked+=r),this.#a()},s=>{this.fail(s)}),this.unacked>=this.#o&&!this.#s&&(this.#s={acked:0,at:performance.now()},Ft("window full: %d bytes unacked, writes stalled",this.unacked)),this.#c(()=>this.unacked<this.#o)}#a(){if(this.#s&&this.unacked<=this.#o/2){const e=performance.now()-this.#s.at;Ft("pressure relieved after %dms: %d bytes acked, %s MB/s",Math.round(e),this.#s.acked,(this.#s.acked/Math.max(e,1)/1e3).toFixed(2)),this.#s=void 0}this.#n=this.#n.filter(e=>e.until()?(e.resolve(void 0),!1):!0)}#i(e){if(this.#t)return!1;this.#t={reason:e},this.#e.error(e);const r=this.#n;this.#n=[];for(const s of r)s.reject(e);return!0}#c(e){if(e())return Promise.resolve();const r={...Ne(),until:e};return this.#n.push(r),r.promise}}class ls extends WritableStream{get unacked(){return this.#e.unacked}#e;constructor(e){const r=new cs(e);super({abort:s=>{r.abort(s)},close:()=>r.close(),start:s=>{r.start(s)},write:s=>r.write(s)}),this.#e=r}fail(e){this.#e.fail(e)}}const fs=1024*1024;class us{#e;#t=!1;#r;#s;constructor(e){this.#r=e}cancel(e){this.#n(),this.#r?.(e)}close(){this.#n()&&this.#e.close()}error(e){this.#n()&&this.#e.error(e)}pull(){const e=this.#s;this.#s=void 0,e?.resolve(void 0)}async push(e){if(this.#t)return;this.#s??=Ne();const{promise:r}=this.#s;this.#e.enqueue(e),await r}start(e){this.#e=e}#n(){return this.#t?!1:(this.#t=!0,this.pull(),!0)}}class ds extends ReadableStream{#e;constructor({highWaterMark:e=fs,onCancel:r}={}){const s=new us(r);super({cancel:n=>{s.cancel(n)},pull:()=>{s.pull()},start:n=>{s.start(n)}},new ByteLengthQueuingStrategy({highWaterMark:e})),this.#e=s}close(){this.#e.close()}error(e){this.#e.error(e)}push(e){return this.#e.push(e)}}class hs{closed;readable;writable;#e=[];#t;#r;#s;#n;#o;#a="starting";constructor(e,{onClose:r,receiveBuffer:s,sendWindow:n,signal:i}){if(this.#o=e,this.#t=Ne(),this.closed=this.#t.promise,this.closed.catch(ps),this.#s=new ds({highWaterMark:s,onCancel:()=>{this.#i(void 0)}}),this.readable=this.#s,this.#n=new ls({onAbort:()=>{this.#i(void 0)},onClose:()=>{this.#i(void 0)},onError:a=>{this.#i(a)},send:a=>e.request("appetizeio.device.server.debug.adbTunnel.data",{data:a}),window:n}),this.writable=this.#n,i){const a=()=>{this.#i(i.reason)};i.addEventListener("abort",a,{once:!0}),this.#e.push(()=>{i.removeEventListener("abort",a)})}this.#e.push(()=>{r(this)})}close=()=>{this.#i(void 0)};detach(){this.#i(void 0,{notifyServer:!1})}async handleData(e){this.#a==="open"&&await this.#s.push(e)}handleStopped({error:e}){this.#a==="open"&&this.#i(e?new Error(e):void 0)}async start(){try{await this.#o.request("appetizeio.device.server.debug.adbTunnel.start",void 0)}catch(e){throw this.#i(e),e}if(this.#a==="closed")throw this.#r?this.#r:new Error("The adb tunnel closed before it started");this.#a="open"}async[Symbol.asyncDispose](){this.close();try{await this.closed}catch{}}#i(e,{notifyServer:r=!0}={}){if(this.#a!=="closed"){this.#a="closed",this.#r=e,r&&re(this.#o,"appetizeio.device.server.debug.adbTunnel.stop",void 0),e?(this.#s.error(e),this.#n.fail(e)):(this.#s.close(),this.#n.fail(new Error("The adb tunnel has stopped")));for(const s of this.#e)s();e?this.#t.reject(e):this.#t.resolve(void 0)}}}function ps(){}class ys{readable;ready;#e=[];#t=!1;#r;#s;#n;constructor({label:e,onClose:r,signal:s}){this.#s=e,this.ready=new Promise((i,a)=>{this.#n={reject:a,resolve:i}});let n;if(this.readable=new ReadableStream({cancel:()=>{this.#a()},start:i=>{n=i}}),!n)throw new Error("ReadableStream controller was not initialized");if(this.#r=n,s){const i=()=>{this.fail(s.reason)};s.addEventListener("abort",i,{once:!0}),this.#e.push(()=>{s.removeEventListener("abort",i)})}this.#e.push(()=>{r(this)})}close=()=>{this.#o()};fail(e){this.#o(e)}handleItem(e){this.#r.enqueue(e)}markReady(){if(!this.#n)return;const{resolve:e}=this.#n;this.#n=void 0,e(this)}async*[Symbol.asyncIterator](){const e=this.readable.getReader();try{for(let r=await e.read();!r.done;r=await e.read())yield r.value}finally{await e.cancel()}}#o(e){this.#t||(this.#r.close(),this.#a(e))}#a(e){this.#t=!0;for(const r of this.#e)r();this.#n?.reject(e??new Error(`${this.#s} closed before it started`)),this.#n=void 0}}class ws{get subscribers(){return this.#r}#e;#t;#r=new Set;constructor(e){this.#e=e}close(){this.#t=void 0;for(const e of[...this.#r])e.close();this.#r.clear()}add(e){this.#r.add(e)}ensureStarted(){return this.#t||(this.#t=(async()=>{try{return await this.#e.start()}catch(e){throw this.#t=void 0,e}})()),this.#t}release(e){this.#r.delete(e),!(this.#r.size>0||!this.#t)&&(this.#t=void 0,this.#e.stop())}}class jt extends ws{#e;constructor(e){super({start:e.start,stop:e.stop}),this.#e=e.label}async createStream({signal:e}={}){e?.throwIfAborted();const r=new ys({label:this.#e,onClose:s=>{this.release(s)},signal:e});this.add(r);try{await this.ensureStarted(),r.markReady()}catch(s){r.fail(s)}return await r.ready}handleNotification(e){for(const r of this.subscribers)r.handleItem(e)}}class gs{#e;#t;#r;#s;constructor(e){this.#s=e,this.#t=new jt({label:"Log stream",start:()=>e.request("appetizeio.device.server.debug.log.start"),stop:()=>{re(e,"appetizeio.device.server.debug.log.stop",void 0)}}),this.#r=new jt({label:"Proxy intercept stream",start:()=>e.request("appetizeio.device.server.debug.proxyIntercept.start"),stop:()=>{re(e,"appetizeio.device.server.debug.proxyIntercept.stop",void 0)}})}close(){this.#e?.detach(),this.#t.close(),this.#r.close()}async createAdbTunnel({signal:e}={}){e?.throwIfAborted(),this.#e?.close();const r=new hs(this.#s,{onClose:()=>{this.#e=void 0},signal:e});return this.#e=r,await r.start(),r}async createLogStream(e){return await this.#t.createStream(e)}async createProxyInterceptStream(e){return await this.#r.createStream(e)}async handleAdbTunnelData({data:e}){await this.#e?.handleData(e)}handleAdbTunnelStopped(e){this.#e?.handleStopped(e)}handleLogEntry(e){this.#t.handleNotification(e)}handleProxyInterceptEvent(e){this.#r.handleNotification(e)}}function De(t){return{...ms(t),index:t.index,within:t.within?De(t.within):void 0}}function ms(t){switch(t.by){case"testId":return{by:"testId",testId:t.testId};case"text":return{by:"text",text:bs(t.text)}}}function bs(t){return typeof t=="string"?{kind:"exact",value:t}:{flags:t.flags,kind:"regex",source:t.source}}const Es=400,$t=["byTestId","byText","duration","index","x","y"],Ss=new Set($t),vs=/^-?(?:\d+(?:\.\d*)?|\.\d+)$/u,As=/^[a-z]$/u,rt=/^\s$/u;class D extends SyntaxError{constructor(e,r,s){super(`${e} at position ${String(r)}`,{cause:s})}}class xs{#e=0;#t;constructor(e){this.#t=e}parse(){const e=[];for(;this.#e<this.#t.length;){const r=this.#i();if(rt.test(r))this.#e++;else if(r===">"){if(this.#t.charAt(this.#e+1)===">")throw new D('Force press ">>" is not supported',this.#e);this.#e++,e.push({kind:"down"})}else if(r==="/")this.#e++,e.push({kind:"up"});else if(r==="{")e.push(this.#o());else{const[s]=this.#t.slice(this.#e,this.#e+2);throw new D(`Unexpected ${JSON.stringify(s)}; write selectors as {...}`,this.#e)}}return e}#r(){const e=this.#e,r=this.#c(s=>s!=="="&&!st(s));if(this.#i()!=="=")return{kind:"bare",name:r,offset:e};if(r.length===0)throw new D('Expected an attribute name before "="',e);return this.#e++,{kind:"attribute",name:r,offset:e,value:this.#a()}}#s(){const e=this.#e;this.#e++;let r="";for(;;){const s=this.#i();if(this.#e++,s==='"')return r;if(s==="\\"){const n=this.#i();if(n!=='"'&&n!=="\\"&&n!=="")throw new D('Only \\" and \\\\ escapes are supported',this.#e-1);this.#e++,r+=n}else{if(s==="")throw new D("Unclosed string",e);r+=s}}}#n(){const e=this.#e;this.#e++;let r="",s=!1;for(;;){const i=this.#i();if(i==="")throw new D("Unclosed regex",e);if(this.#e++,i==="/"&&!s)break;r+=i,i==="\\"?(r+=this.#i(),this.#e++):i==="["?s=!0:i==="]"&&(s=!1)}const n=this.#c(i=>As.test(i));try{return new RegExp(r,n)}catch(i){throw new D(`Invalid regex /${r}/${n}`,e,i)}}#o(){const e=this.#e;this.#e++;let r;const s={offsets:{}};for(let n=0;;n++){this.#l();const i=this.#i();if(i==="")throw new D('Unclosed "{"',e);if(i==="}"){if(this.#e++,n===0)throw new D('Expected a selector or wait in "{}"',e);return r===void 0?Is(s,e):{duration:r,kind:"wait"}}const a=this.#r();if(n===0&&a.name==="wait")r=a.kind==="attribute"?Kt(a.value,"wait"):Es;else{if(r!==void 0)throw new D('"wait" takes no other attributes',a.offset);ks(s,a,n)}}}#a(){const e=this.#e,r=this.#i();let s;if(r==='"')s={kind:"quoted",offset:e,text:this.#s()};else if(r==="/")s={kind:"regex",offset:e,regex:this.#n()};else{const n=this.#c(i=>!st(i));if(n.length===0)throw new D('Expected a value after "="',e);return{kind:"raw",offset:e,text:n}}if(!st(this.#i()))throw new D('Expected a space or "}" after the value',this.#e);return s}#i(){return this.#t.charAt(this.#e)}#c(e){const r=this.#e;for(;this.#e<this.#t.length&&e(this.#i());)this.#e++;return this.#t.slice(r,this.#e)}#l(){this.#c(e=>rt.test(e))}}function Vt(t){return new xs(t).parse()}function ks(t,e,r){const{name:s,offset:n}=e;if(e.kind==="attribute"){nt(t,s,n,e.value);return}if(!s.includes(","))throw new D(`Expected key=value, got ${JSON.stringify(s)}`,n);if(r>0)throw new D("Write the x,y position first",n);const[i,a,...y]=s.split(",");if(y.length>0)throw new D("Expected a screen position as x,y",n);const p=n+i.length+1;nt(t,"x",n,{kind:"raw",offset:n,text:i}),nt(t,"y",p,{kind:"raw",offset:p,text:a})}function Os(t){return Ss.has(t)}function st(t){return t===""||t==="}"||rt.test(t)}function nt(t,e,r,s){if(!Os(e))throw new D(`Unknown attribute ${JSON.stringify(e)}; expected one of ${$t.join(", ")}`,r);if(t.offsets[e]!==void 0)throw new D(`Duplicate attribute ${JSON.stringify(e)}`,r);switch(t.offsets[e]=r,e){case"byTestId":case"byText":if(t.byText!==void 0||t.byTestId!==void 0)throw new D("Only one of byText and byTestId may be given",r);e==="byText"?t.byText=Ms(s):t.byTestId=Rs(s);return;default:t[e]=Kt(s,e)}}function Is(t,e){return{duration:t.duration,kind:"move",to:Ts(t,e)}}function Kt(t,e){if(t.kind!=="raw"||!vs.test(t.text))throw new D(`"${e}" takes a number`,t.offset);return Number(t.text)}function Ts(t,e){const{byTestId:r,byText:s,index:n,offsets:i,x:a,y}=t;if(s!==void 0)return{by:"text",index:n,text:s,x:a,y};if(r!==void 0)return{by:"testId",index:n,testId:r,x:a,y};if(i.index!==void 0)throw new D('"index" needs byText or byTestId',i.index);if(a===void 0||y===void 0)throw new D("A screen position needs x and y",e);return{by:"position",x:a,y}}function Rs(t){if(t.kind==="regex")throw new D('"byTestId" takes a string',t.offset);return t.text}function Ms(t){return t.kind==="regex"?t.regex:t.text}function ke(t){return t.by==="position"?{by:"position",x:t.x,y:t.y}:{...De(t),x:t.x,y:t.y}}function Ls(t){return t.map(e=>e.kind==="move"?{duration:e.duration,kind:"move",to:ke(e.to)}:e)}function Us(t){return{press:e=>{re(t,"appetizeio.device.server.keyboard.press",{key:e})}}}function Ps({onRequest:t,parent:e,proxyInlet:r,signal:s}){const n=new Bt(e,{signal:s}),i=[()=>{n.close()}];return zt(n,r),t&&i.push(_e(n,a=>{t(a,{source:"parent"})})),{cleanup:()=>{for(const a of i)a()},notifies:()=>e===globalThis.window?void 0:n}}function Cs({onRequest:t,proxyInlet:e}){const[r,s]=et(),i=[es(s),()=>{r.close()}];return zt(r,e),t&&i.push(_e(r,a=>{t(a,{source:"parent"})})),{cleanup:()=>{for(const a of i)a()},notifies:()=>r}}function _s(t){return{clearKeychain:async()=>{await t.request("appetizeio.device.server.settings.clearKeychain")},setAppearance:async e=>{await t.request("appetizeio.device.server.settings.setAppearance",{appearance:e})},setBiometryEnrolled:async e=>{await t.request("appetizeio.device.server.settings.setBiometryEnrolled",{enrolled:e})},setFontSize:async e=>{await t.request("appetizeio.device.server.settings.setFontSize",{fontSize:e})},setLocation:async({latitude:e,longitude:r})=>{await t.request("appetizeio.device.server.settings.setLocation",{latitude:e,longitude:r})}}}function Ns(t){return"to"in t?{from:ke(t.from),kind:"path",to:ke(t.to)}:{direction:t.direction,distance:t.distance,from:t.from?ke(t.from):void 0,kind:"direction"}}function Ds(t){return{down:(e,r)=>{re(t,"appetizeio.device.server.touch.down",{x:e,y:r})},move:(e,r)=>{re(t,"appetizeio.device.server.touch.move",{x:e,y:r})},up:(e,r)=>{re(t,"appetizeio.device.server.touch.up",{x:e,y:r})}}}const zs=new Set(Xe),Bs=/^(?<key>[A-Za-z]+)>(?<repeat>\d+)\/$/u,Fs=/(\{\{|\{[^{}]*\})/u;function js(t){const e=[];let r="";function s(){r.length>0&&(e.push({kind:"text",text:r}),r="")}for(const[n,i]of t.split(Fs).entries())if(n%2===0){if(i.includes("{"))throw new Error(`Unclosed "{" in ${JSON.stringify(t)}`);r+=i}else i==="{{"?r+="{":(s(),e.push(Vs(i.slice(1,-1))));return s(),e}function $s(t,e){if(!zs.has(t))throw e.endsWith(">")?new Error(`Holding a key is not supported: {${e}}`):e.startsWith("/")?new Error(`Releasing a key is not supported: {${e}}`):new Error(`{${e}} does not name a supported key. Supported: ${Xe.join(", ")}. Type characters as text, and escape a literal "{" as "{{".`)}function Vs(t){const e=Bs.exec(t)?.groups,r=e?.key??t;if($s(r,t),!e)return{key:r,kind:"press"};const s=Number(e.repeat);if(s<1)throw new Error(`Repeat for {${t}} must be at least 1`);return{key:r,kind:"press",repeat:s}}const Ks=Symbol("@appetizeio/client:v1Compat");function qt(t){return t?.[Ks]}class qs{readable;ready;get dimensions(){return this.#s}#e=[];#t=!1;#r;#s;#n;#o;constructor({onClose:e,requestKeyFrame:r,signal:s}){this.#n=r,this.ready=new Promise((i,a)=>{this.#o={reject:a,resolve:i}});let n;if(this.readable=new ReadableStream({cancel:()=>{this.#i()},start:i=>{n=i}}),!n)throw new Error("ReadableStream controller was not initialized");if(this.#r=n,s){const i=()=>{this.fail(s.reason)};s.addEventListener("abort",i,{once:!0}),this.#e.push(()=>{s.removeEventListener("abort",i)})}this.#e.push(()=>{e(this)})}close=()=>{this.#a()};fail(e){this.#a(e)}handleChunk(e){if(this.#o){if(e.type!=="key")return;const{resolve:r}=this.#o;this.#o=void 0,this.#s={height:e.height,width:e.width},r(this)}else e.type==="key"&&(this.#s={height:e.height,width:e.width});this.#r.enqueue(e)}requestKeyFrame=()=>{this.#t||this.#n()};async*[Symbol.asyncIterator](){const e=this.readable.getReader();try{for(let r=await e.read();!r.done;r=await e.read())yield r.value}finally{await e.cancel()}}#a(e){this.#t||(this.#r.close(),this.#i(e))}#i(e){this.#t=!0;for(const r of this.#e)r();this.#o?.reject(e??new Error("Video stream closed before the first key chunk")),this.#o=void 0}}class Ws{#e=!1;#t;#r;#s=new Set;constructor(e){this.#t=e}close(){this.#r=void 0;for(const e of[...this.#s])e.close()}async createStream({signal:e}={}){e?.throwIfAborted();const r=new qs({onClose:s=>{this.#o(s)},requestKeyFrame:()=>{this.#a()},signal:e});this.#s.add(r);try{await this.#n()}catch(s){r.fail(s)}return await r.ready}handleChunk(e){e.type==="key"&&(this.#e=!1);for(const r of this.#s)r.handleChunk(e)}#n(){return this.#r?(this.#a(),this.#r):(this.#e=!0,this.#r=(async()=>{try{await this.#t.request("appetizeio.device.server.video.start")}catch(e){throw this.#r=void 0,e}})(),this.#r)}#o(e){this.#s.delete(e),!(this.#s.size>0||!this.#r)&&(this.#r=void 0,re(this.#t,"appetizeio.device.server.video.stop",void 0))}#a(){this.#e||(this.#e=!0,re(this.#t,"appetizeio.device.server.video.requestKeyFrame",void 0))}}class Js{app;debug;keyboard;settings;touch;video;#e;#t=[];#r;constructor(e,r={}){const s=qt(r)??{},{baseUrl:n,onClose:i,signal:a}=r;this.#e=n?Gs(n):void 0;const{onRequest:y,parent:p,proxyRequest:A}=s,E=Hs(y);a?.addEventListener("abort",this.close);const[R,M]=et(),[N,_]=et();this.#t.push(()=>{R.close(),M.close(),N.close(),_.close()}),this.#t.push(Qe(_,e,{leftEffects:A}));const U=p==="playwright"?Cs({onRequest:E,proxyInlet:N}):p?Ps({onRequest:E,parent:p,proxyInlet:N,signal:a}):void 0;U&&this.#t.push(U.cleanup),this.#t.push(Qe(M,N,{notifiesLeft:U?.notifies}));const{client:Y,unsub:ve}=rs(R,{"appetizeio.device.client.debug.adbTunnel.data":K=>Q.handleAdbTunnelData(K),"appetizeio.device.client.debug.adbTunnel.stopped":async K=>{Q.handleAdbTunnelStopped(K)},"appetizeio.device.client.debug.log.entry":async K=>{Q.handleLogEntry(K)},"appetizeio.device.client.debug.proxyIntercept.event":async K=>{Q.handleProxyInterceptEvent(K)},"appetizeio.device.client.video.chunk":async K=>{k.handleChunk(K)}});this.#r=Y,this.#t.push(ve);const Q=new gs(this.#r);this.#t.push(()=>{Q.close()});const k=new Ws(this.#r);this.#t.push(()=>{k.close()}),this.app=os(this.#r),this.debug=Q,this.keyboard=Us(this.#r),this.settings=_s(this.#r),this.touch=Ds(this.#r),this.video=k,E&&(this.#t.push(_e(M,K=>{E(K,{source:"self"})})),e instanceof Bt&&this.#t.push(_e(e,K=>{E(K,{source:"iframe"})}))),this.#t.push(()=>i?.())}close=()=>{for(const e of this.#t)try{e()}catch(r){console.error("Device cleanup error:",r)}};async fold(e){await this.#r.request("appetizeio.device.server.fold",{hinge:e})}async gesture(e,r){await this.#r.request("appetizeio.device.server.gesture",{options:r,steps:Ls(typeof e=="string"?Vt(e):e)})}async inspect(e,r){return await this.#r.request("appetizeio.device.server.inspect",{options:r,selector:e?De(e):void 0})}async open(e){new URL(e),await this.#r.request("appetizeio.device.server.open",{url:e})}async press(e){await this.#r.request("appetizeio.device.server.press",{action:e})}async rotate(e){await this.#r.request("appetizeio.device.server.rotate",{orientation:e})}async screenshot(e,r){const s=await this.#r.request("appetizeio.device.server.screenshot",{options:r,selector:e?De(e):void 0}),n=this.#e?new URL(s.url,this.#e).href:s.url,i=await fetch(n);if(!i.ok)throw new Error(`Screenshot download failed: ${String(i.status)} ${i.statusText}`);const a=i.headers.get("content-type")??"application/octet-stream";return{data:new Uint8Array(await i.arrayBuffer()),mimeType:a}}async shake(){await this.#r.request("appetizeio.device.server.shake")}async swipe(e,r){await this.#r.request("appetizeio.device.server.swipe",{gesture:Ns(e),options:r})}async tap(e,r){await this.#r.request("appetizeio.device.server.tap",{options:r,selector:ke(e)})}async type(e,r){await this.#r.request("appetizeio.device.server.type",{options:r,steps:js(e)})}}function Gs(t){const e=new URL(t);return e.protocol==="ws:"?e.protocol="http:":e.protocol==="wss:"&&(e.protocol="https:"),e.href}const Hs=t=>{if(t)return(e,r)=>{e.method.startsWith("appetizeio.device.server.")&&t(e,r)}};let it;try{it=new TextDecoder}catch{}let w,z,f=0;const ot=[],Zs=105,Ys=57342,Qs=57343,Wt=57337,Jt=6,pe={};let ze=11281e4,ye=1681e4,Xs=1671e4,we=Xs,ce=ot,Oe=0,O={},B,Ie,Te=0,le=0,F,H,j=[],at=[],W,q,X,Gt={useRecords:!1,mapsAsObjects:!0},Re=!1,Ht=2;try{new Function("")}catch{Ht=1/0}class Se{constructor(e){if(e&&((e.keyMap||e._keyMap)&&!e.useRecords&&(e.useRecords=!1,e.mapsAsObjects=!0),e.useRecords===!1&&e.mapsAsObjects===void 0&&(e.mapsAsObjects=!0),e.getStructures&&(e.getShared=e.getStructures),e.getShared&&!e.structures&&((e.structures=[]).uninitialized=!0),e.keyMap)){this.mapKey=new Map;for(let[r,s]of Object.entries(e.keyMap))this.mapKey.set(s,r)}Object.assign(this,e)}decodeKey(e){return this.keyMap&&this.mapKey.get(e)||e}encodeKey(e){return this.keyMap&&this.keyMap.hasOwnProperty(e)?this.keyMap[e]:e}encodeKeys(e){if(!this._keyMap)return e;let r=new Map;for(let[s,n]of Object.entries(e))r.set(this._keyMap.hasOwnProperty(s)?this._keyMap[s]:s,n);return r}decodeKeys(e){if(!this._keyMap||e.constructor.name!="Map")return e;if(!this._mapKey){this._mapKey=new Map;for(let[s,n]of Object.entries(this._keyMap))this._mapKey.set(n,s)}let r={};return e.forEach((s,n)=>r[Z(this._mapKey.has(n)?this._mapKey.get(n):n)]=s),r}mapDecode(e,r){let s=this.decode(e);return this._keyMap&&s.constructor.name==="Array"?s.map(n=>this.decodeKeys(n)):s}decode(e,r){if(w)return sr(()=>{ut();try{return this?this.decode(e,r):Se.prototype.decode.call(Gt,e,r)}catch(s){throw s&&typeof s=="object"&&Zt.add(s),s}});z=r>-1?r:e.length,f=0,Oe=0,le=0,Ie=null,ce=ot,F=null,w=e;try{q=e.dataView||(e.dataView=new DataView(e.buffer,e.byteOffset,e.byteLength))}catch(s){throw w=null,e instanceof Uint8Array?s:new Error("Source must be a Uint8Array or Buffer but was a "+(e&&typeof e=="object"?e.constructor.name:typeof e))}if(this instanceof Se){if(O=this,W=this.sharedValues&&(this.pack?new Array(this.maxPrivatePackedValues||16).concat(this.sharedValues):this.sharedValues),this.structures)return B=this.structures,Fe();(!B||B.length>0)&&(B=[])}else O=Gt,(!B||B.length>0)&&(B=[]),W=null;return Fe()}decodeMultiple(e,r){let s,n=0;try{let i=e.length;Re=!0;let a=this?this.decode(e,i):ht.decode(e,i);if(r){if(r(a)===!1)return;for(;f<i;)if(n=f,r(Fe())===!1)return}else{for(s=[a];f<i;)n=f,s.push(Fe());return s}}catch(i){throw i.lastPosition=n,i.values=s,i}finally{Re=!1,ut()}}}const Zt=new WeakSet;let Be;function Fe(){try{Be=z-f;let t=I();if(F){if(f>=F.postBundlePosition)throw new Error("Unexpected bundle position");f=F.postBundlePosition,F=null}if(f==z)B=null,w=null,H&&(H=null);else if(f>z){let e=new Error("Unexpected end of CBOR data");throw e.incomplete=!0,e}else if(!Re)throw new Error("Data read, but end of buffer not reached");return t}catch(t){throw ut(),Zt.has(t)?t.incomplete&&(t.incomplete=!1):(t instanceof RangeError&&f+8>z||t&&typeof t.message=="string"&&t.message.startsWith("Unexpected end of buffer"))&&(t.incomplete=!0),t}}function J(){let t=new Error("Unexpected end of CBOR data");return t.incomplete=!0,t}function I(){if(!(f<z))throw J();let t=w[f++],e=t>>5;if(t=t&31,t>23)switch(t){case 24:if(f>=z)throw J();t=w[f++];break;case 25:if(e==7)return sn();t=q.getUint16(f),f+=2;break;case 26:if(e==7){let r=q.getFloat32(f);if(O.useFloat32>2){let s=dt[(w[f]&127)<<1|w[f+1]>>7];return f+=4,(s*r+(r>0?.5:-.5)>>0)/s}return f+=4,r}if(t=q.getUint32(f),f+=4,e===1)return-1-t;break;case 27:if(e==7){let r=q.getFloat64(f);return f+=8,r}if(e>1){if(q.getUint32(f)>0)throw new Error("JavaScript does not support arrays, maps, or strings with length over 4294967295");t=q.getUint32(f+4)}else O.int64AsNumber?(t=q.getUint32(f)*4294967296,t+=q.getUint32(f+4)):t=q.getBigUint64(f);f+=8;break;case 31:switch(e){case 2:case 3:throw new Error("Indefinite length not supported for byte or text strings");case 4:let r=[],s,n=0;for(;(s=I())!=pe;){if(n>=ze)throw new Error(`Array length exceeds ${ze}`);r[n++]=s}return e==4?r:e==3?r.join(""):Buffer.concat(r);case 5:let i;if(O.mapsAsObjects){let a={},y=0;if(O.keyMap)for(;(i=I())!=pe;){if(y++>=we)throw new Error(`Property count exceeds ${we}`);a[Z(O.decodeKey(i))]=I()}else for(;(i=I())!=pe;){if(y++>=we)throw new Error(`Property count exceeds ${we}`);a[Z(i)]=I()}return a}else{X&&(O.mapsAsObjects=!0,X=!1);let a=new Map;if(O.keyMap){let y=0;for(;(i=I())!=pe;){if(y++>=ye)throw new Error(`Map size exceeds ${ye}`);a.set(O.decodeKey(i),I())}}else{let y=0;for(;(i=I())!=pe;){if(y++>=ye)throw new Error(`Map size exceeds ${ye}`);a.set(i,I())}}return a}case 7:return pe;default:throw new Error("Invalid major type for indefinite length "+e)}default:throw new Error("Unknown token "+t)}switch(e){case 0:return t;case 1:return~t;case 2:if(t>z-f)throw J();return rn(t);case 3:if(le>=f)return Ie.slice(f-Te,(f+=t)-Te);if(t>z-f)throw J();if(le==0&&z<140&&t<32){let n=t<16?Xt(t):tn(t);if(n!=null)return n}return Qt(t);case 4:if(t>ze)throw new Error(`Array length exceeds ${ze}`);if(t>z-f||(Be-=t)<0)throw J();let r=new Array(t);for(let n=0;n<t;n++)r[n]=I();return r;case 5:if(O.mapsAsObjects){if(t>we)throw new Error(`Property count exceeds ${we}`);if(t>(z-f)/2)throw J();let n={};if(O.keyMap)for(let i=0;i<t;i++)n[Z(O.decodeKey(I()))]=I();else for(let i=0;i<t;i++)n[Z(I())]=I();return n}else{if(X&&(O.mapsAsObjects=!0,X=!1),t>ye)throw new Error(`Map size exceeds ${ye}`);if(t>(z-f)/2)throw J();let n=new Map;if(O.keyMap)for(let i=0;i<t;i++)n.set(O.decodeKey(I()),I());else for(let i=0;i<t;i++)n.set(I(),I());return n}case 6:if(t>=Wt){let n=B[t&8191];if(n)return n.read||(n.read=ct(n)),n.read();if(t<65536){if(t==Qs){let i=me(),a=I(),y=I();lt(a,y);let p={};if(O.keyMap)for(let A=2;A<i;A++){let E=O.decodeKey(y[A-2]);p[Z(E)]=I()}else for(let A=2;A<i;A++){let E=y[A-2];p[Z(E)]=I()}return p}else if(t==Ys){let i=me(),a=I();for(let y=2;y<i;y++)lt(a++,I());return I()}else if(t==Wt)return fn();if(O.getShared&&(ft(),n=B[t&8191],n))return n.read||(n.read=ct(n)),n.read()}}let s=j[t];if(s)return s.handlesRead?s(I):s(I());{let n=I();for(let i=0;i<at.length;i++){let a=at[i](t,n);if(a!==void 0)return a}return new fe(n,t)}case 7:switch(t){case 20:return!1;case 21:return!0;case 22:return null;case 23:return;default:let n=(W||ue())[t];if(n!==void 0)return n;throw new Error("Unknown token "+t)}default:throw isNaN(t)?J():new Error("Unknown CBOR token "+t)}}const Yt=/^[a-zA-Z_$][a-zA-Z\d_$]*$/;function ct(t){if(!t)throw new Error("Structure is required in record definition");function e(){let r=w[f++];if(r=r&31,r>23)switch(r){case 24:r=w[f++];break;case 25:r=q.getUint16(f),f+=2;break;case 26:r=q.getUint32(f),f+=4;break;default:throw new Error("Expected array header, but got "+w[f-1])}let s=this.compiledReader;for(;s;){if(s.propertyCount===r)return s(I);s=s.next}if(this.slowReads++>=Ht){let i=this.length==r?this:this.slice(0,r);return s=O.keyMap?new Function("r","return {"+i.map(a=>O.decodeKey(a)).map(a=>Yt.test(a)?Z(a)+":r()":"["+JSON.stringify(a)+"]:r()").join(",")+"}"):new Function("r","return {"+i.map(a=>Yt.test(a)?Z(a)+":r()":"["+JSON.stringify(a)+"]:r()").join(",")+"}"),this.compiledReader&&(s.next=this.compiledReader),s.propertyCount=r,this.compiledReader=s,s(I)}let n={};if(O.keyMap)for(let i=0;i<r;i++)n[Z(O.decodeKey(this[i]))]=I();else for(let i=0;i<r;i++)n[Z(this[i])]=I();return n}return t.slowReads=0,e}function Z(t){if(typeof t=="string")return t==="__proto__"?"__proto_":t;if(typeof t=="number"||typeof t=="boolean"||typeof t=="bigint")return t.toString();if(t==null)return t+"";throw new Error("Invalid property name type "+typeof t)}let Qt=je;function en(t){Qt=e();function e(r){return function(n){let i=ce[Oe++];if(i==null){if(F)return je(n);let y=t(f,z,n,w);if(typeof y=="string")i=y,ce=ot;else if(ce=y,Oe=1,le=1,i=ce[0],i===void 0)throw new Error("Unexpected end of buffer")}let a=i.length;return a<=n?(f+=n,i):(Ie=i,Te=f,le=f+a,f+=n,i.slice(0,n))}}}function je(t){let e;if(t<16&&(e=Xt(t)))return e;if(t>64&&it)return it.decode(w.subarray(f,f+=t));const r=f+t,s=[];for(e="";f<r;){const n=w[f++];if((n&128)===0)s.push(n);else if((n&224)===192)if(n<194||f>=r||(w[f]&192)!==128)s.push(65533);else{const i=w[f++]&63;s.push((n&31)<<6|i)}else if((n&240)===224){const i=f<r?w[f]:0;if(f>=r||(i&192)!==128||n===224&&i<160||n===237&&i>=160)s.push(65533);else if(f++,f>=r||(w[f]&192)!==128)s.push(65533);else{const a=w[f++]&63;s.push((n&31)<<12|(i&63)<<6|a)}}else if((n&248)===240){const i=f<r?w[f]:0;if(n>244||f>=r||(i&192)!==128||n===240&&i<144||n===244&&i>=144)s.push(65533);else if(f++,f>=r||(w[f]&192)!==128)s.push(65533);else{const a=w[f++]&63;if(f>=r||(w[f]&192)!==128)s.push(65533);else{const y=w[f++]&63;let p=(n&7)<<18|(i&63)<<12|a<<6|y;p-=65536,s.push(p>>>10&1023|55296),s.push(56320|p&1023)}}}else s.push(65533);s.length>=4096&&(e+=V.apply(String,s),s.length=0)}return s.length>0&&(e+=V.apply(String,s)),e}let V=String.fromCharCode;function tn(t){let e=f,r=new Array(t);for(let s=0;s<t;s++){const n=w[f++];if((n&128)>0){f=e;return}r[s]=n}return V.apply(String,r)}function Xt(t){if(t<4)if(t<2){if(t===0)return"";{let e=w[f++];if((e&128)>1){f-=1;return}return V(e)}}else{let e=w[f++],r=w[f++];if((e&128)>0||(r&128)>0){f-=2;return}if(t<3)return V(e,r);let s=w[f++];if((s&128)>0){f-=3;return}return V(e,r,s)}else{let e=w[f++],r=w[f++],s=w[f++],n=w[f++];if((e&128)>0||(r&128)>0||(s&128)>0||(n&128)>0){f-=4;return}if(t<6){if(t===4)return V(e,r,s,n);{let i=w[f++];if((i&128)>0){f-=5;return}return V(e,r,s,n,i)}}else if(t<8){let i=w[f++],a=w[f++];if((i&128)>0||(a&128)>0){f-=6;return}if(t<7)return V(e,r,s,n,i,a);let y=w[f++];if((y&128)>0){f-=7;return}return V(e,r,s,n,i,a,y)}else{let i=w[f++],a=w[f++],y=w[f++],p=w[f++];if((i&128)>0||(a&128)>0||(y&128)>0||(p&128)>0){f-=8;return}if(t<10){if(t===8)return V(e,r,s,n,i,a,y,p);{let A=w[f++];if((A&128)>0){f-=9;return}return V(e,r,s,n,i,a,y,p,A)}}else if(t<12){let A=w[f++],E=w[f++];if((A&128)>0||(E&128)>0){f-=10;return}if(t<11)return V(e,r,s,n,i,a,y,p,A,E);let R=w[f++];if((R&128)>0){f-=11;return}return V(e,r,s,n,i,a,y,p,A,E,R)}else{let A=w[f++],E=w[f++],R=w[f++],M=w[f++];if((A&128)>0||(E&128)>0||(R&128)>0||(M&128)>0){f-=12;return}if(t<14){if(t===12)return V(e,r,s,n,i,a,y,p,A,E,R,M);{let N=w[f++];if((N&128)>0){f-=13;return}return V(e,r,s,n,i,a,y,p,A,E,R,M,N)}}else{let N=w[f++],_=w[f++];if((N&128)>0||(_&128)>0){f-=14;return}if(t<15)return V(e,r,s,n,i,a,y,p,A,E,R,M,N,_);let U=w[f++];if((U&128)>0){f-=15;return}return V(e,r,s,n,i,a,y,p,A,E,R,M,N,_,U)}}}}}function rn(t){return O.copyBuffers?Uint8Array.prototype.slice.call(w,f,f+=t):w.subarray(f,f+=t)}let er=new Float32Array(1),$e=new Uint8Array(er.buffer,0,4);function sn(){let t=w[f++],e=w[f++],r=(t&127)>>2;if(r===31)return e||t&3?NaN:t&128?-1/0:1/0;if(r===0){let s=((t&3)<<8|e)/16777216;return t&128?-s:s}return $e[3]=t&128|(r>>1)+56,$e[2]=(t&7)<<5|e>>3,$e[1]=e<<5,$e[0]=0,er[0]}new Array(4096);class fe{constructor(e,r){this.value=e,this.tag=r}}j[0]=t=>new Date(t),j[1]=t=>new Date(Math.round(t*1e3)),j[2]=t=>{let e=BigInt(0);for(let r=0,s=t.byteLength;r<s;r++)e=BigInt(t[r])+(e<<BigInt(8));return e},j[3]=t=>BigInt(-1)-j[2](t),j[4]=t=>+(t[1]+"e"+t[0]),j[5]=t=>t[1]*Math.exp(t[0]*Math.log(2));const lt=(t,e)=>{t=t-57344;let r=B[t];r&&r.isShared&&((B.restoreStructures||(B.restoreStructures=[]))[t]=r),B[t]=e,e.read=ct(e)};j[Zs]=t=>{let e=t.length,r=t[1];lt(t[0],r);let s={};for(let n=2;n<e;n++){let i=r[n-2];s[Z(i)]=t[n]}return s},j[14]=t=>F?F[0].slice(F.position0,F.position0+=t):new fe(t,14),j[15]=t=>F?F[1].slice(F.position1,F.position1+=t):new fe(t,15);let nn={Error,RegExp};j[27]=t=>(nn[t[0]]||Error)(t[1],t[2]);const tr=t=>{if(!(f<z))throw J();if(w[f++]!=132)throw new Error("Packed values structure must be followed by a 4 element array");let e=t();if(!Array.isArray(e)||!e.length)throw new Error("Packed values structure must be followed by a 4 element array");return W=W?e.concat(W.slice(e.length)):e,W.prefixes=t(),W.suffixes=t(),t()};tr.handlesRead=!0,j[51]=tr,j[Jt]=t=>{if(!W)if(O.getShared)ft();else return new fe(t,Jt);if(typeof t=="number")return W[16+(t>=0?2*t:-2*t-1)];throw new Error("No support for non-integer packed references yet")},j[28]=t=>{H||(H=new Map,H.id=0);let e=H.id++,r=f,s=w[f],n;s>>5==4?n=[]:n={};let i={target:n};H.set(e,i);let a=t();return i.used?(Object.getPrototypeOf(n)!==Object.getPrototypeOf(a)&&(f=r,n=a,H.set(e,{target:n}),a=t()),Object.assign(n,a)):(i.target=a,a)},j[28].handlesRead=!0,j[29]=t=>{let e=H.get(t);return e.used=!0,e.target},j[258]=t=>new Set(t),(j[259]=t=>{let e=O;if(e.mapsAsObjects){e.mapsAsObjects=!1,X=!0;try{return t()}finally{X&&(e.mapsAsObjects=!0,X=!1)}}return t()}).handlesRead=!0;function ge(t,e){return typeof t=="string"?t+e:t instanceof Array?t.concat(e):Object.assign({},t,e)}function ue(){if(!W)if(O.getShared)ft();else throw new Error("No packed values available");return W}const on=1399353956;at.push((t,e)=>{if(t>=225&&t<=255)return ge(ue().prefixes[t-224],e);if(t>=28704&&t<=32767)return ge(ue().prefixes[t-28672],e);if(t>=1879052288&&t<=2147483647)return ge(ue().prefixes[t-1879048192],e);if(t>=216&&t<=223)return ge(e,ue().suffixes[t-216]);if(t>=27647&&t<=28671)return ge(e,ue().suffixes[t-27639]);if(t>=1811940352&&t<=1879048191)return ge(e,ue().suffixes[t-1811939328]);if(t==on)return{packedValues:W,structures:B.slice(0),version:e};if(t==55799)return e});const an=new Uint8Array(new Uint16Array([1]).buffer)[0]==1,rr=[Uint8Array,Uint8ClampedArray,Uint16Array,Uint32Array,typeof BigUint64Array>"u"?{name:"BigUint64Array"}:BigUint64Array,Int8Array,Int16Array,Int32Array,typeof BigInt64Array>"u"?{name:"BigInt64Array"}:BigInt64Array,Float32Array,Float64Array],cn=[64,68,69,70,71,72,77,78,79,85,86];for(let t=0;t<rr.length;t++)ln(rr[t],cn[t]);function ln(t,e){let r="get"+t.name.slice(0,-5),s;typeof t=="function"?s=t.BYTES_PER_ELEMENT:t=null;for(let n=0;n<2;n++){if(!n&&s==1)continue;let i=s==2?1:s==4?2:s==8?3:0;j[n?e:e-4]=s==1||n==an?a=>{if(!t)throw new Error("Could not find typed array for code "+e);return!O.copyBuffers&&(s===1||s===2&&!(a.byteOffset&1)||s===4&&!(a.byteOffset&3)||s===8&&!(a.byteOffset&7))?new t(a.buffer,a.byteOffset,a.byteLength>>i):new t(Uint8Array.prototype.slice.call(a,0).buffer)}:a=>{if(!t)throw new Error("Could not find typed array for code "+e);let y=new DataView(a.buffer,a.byteOffset,a.byteLength),p=a.length>>i,A=new t(p),E=y[r];for(let R=0;R<p;R++)A[R]=E.call(y,R<<i,n);return A}}}function fn(){let t=me(),e=f+I();for(let s=2;s<t;s++){let n=me();f+=n}let r=f;return f=e,F=[je(me()),je(me())],F.position0=0,F.position1=0,F.postBundlePosition=f,f=r,I()}function me(){if(!(f<z))throw J();let t=w[f++]&31;if(t>23)switch(t){case 24:if(f>=z)throw J();t=w[f++];break;case 25:if(f+2>z)throw J();t=q.getUint16(f),f+=2;break;case 26:if(f+4>z)throw J();t=q.getUint32(f),f+=4;break}return t}function ft(){if(O.getShared){let t=sr(()=>(w=null,O.getShared()))||{},e=t.structures||[];O.sharedVersion=t.version,W=O.sharedValues=t.packedValues,B===!0?O.structures=B=e:B.splice.apply(B,[0,e.length].concat(e))}}function sr(t){let e=z,r=f,s=Oe,n=Te,i=le,a=Ie,y=ce,p=H,A=F,E=new Uint8Array(w.slice(0,z)),R=B,M=O,N=Re,_=X,U=Be;X=!1;try{return t()}finally{z=e,f=r,Oe=s,Te=n,le=i,Ie=a,ce=y,H=p,F=A,w=E,Re=N,B=R,O=M,X=_,Be=U,q=new DataView(w.buffer,w.byteOffset,w.byteLength)}}function ut(){w=null,H=null,B=null}const dt=new Array(147);for(let t=0;t<256;t++)dt[t]=+("1e"+Math.floor(45.15-t*.30103));let ht=new Se({useRecords:!1});const un=ht.decode;ht.decodeMultiple;let Ve;try{Ve=new TextEncoder}catch{}let pt,nr;const Ke=typeof globalThis=="object"&&globalThis.Buffer,Me=typeof Ke<"u",yt=Me?Ke.allocUnsafeSlow:Uint8Array,ir=Me?Ke:Uint8Array,or=256,ar=Me?4294967296:2144337920;let wt,l,P,o=0,se,$=null;const dn=61440,hn=/[\u0080-\uFFFF]/,G=Symbol("record-id");class cr extends Se{constructor(e){super(e),this.offset=0;let r,s,n,i,a;e=e||{};let y=ir.prototype.utf8Write?function(c,g){return l.utf8Write(c,g,l.byteLength-g)}:Ve&&Ve.encodeInto?function(c,g){return Ve.encodeInto(c,l.subarray(g)).written}:!1,p=this,A=e.structures||e.saveStructures,E=e.maxSharedStructures;if(E==null&&(E=A?128:0),E>8190)throw new Error("Maximum maxSharedStructure is 8190");let R=e.sequential;R&&(E=0),this.structures||(this.structures=[]),this.saveStructures&&(this.saveShared=this.saveStructures);let M,N,_=e.sharedValues,U;if(_){U=Object.create(null);for(let c=0,g=_.length;c<g;c++)U[_[c]]=c}let Y=[],ve=0,Q=0;this.mapEncode=function(c,g){return this._keyMap&&!this._mapped&&c.constructor.name==="Array"&&(c=c.map(d=>this.encodeKeys(d))),this.encode(c,g)},this.encode=function(c,g){if(l||(l=new yt(8192),P=new DataView(l.buffer,0,8192),o=0),se=l.length-10,se-o<2048?(l=new yt(l.length),P=new DataView(l.buffer,0,l.length),se=l.length-10,o=0):g===dr&&(o=o+7&2147483640),r=o,p.useSelfDescribedHeader&&(P.setUint32(o,3654940416),o+=3),a=p.structuredClone?new Map:null,p.bundleStrings&&typeof c!="string"?($=[],$.size=1/0):$=null,s=p.structures,s){if(s.uninitialized){let h=p.getShared()||{};p.structures=s=h.structures||[],p.sharedVersion=h.version;let u=p.sharedValues=h.packedValues;if(u){U={};for(let b=0,S=u.length;b<S;b++)U[u[b]]=b}}let d=s.length;if(d>E&&!R&&(d=E),!s.transitions){s.transitions=Object.create(null);for(let h=0;h<d;h++){let u=s[h];if(!u)continue;let b,S=s.transitions;for(let v=0,x=u.length;v<x;v++){S[G]===void 0&&(S[G]=h);let T=u[v];b=S[T],b||(b=S[T]=Object.create(null)),S=b}S[G]=h|1048576}}R||(s.nextId=d)}if(n&&(n=!1),i=s||[],N=U,e.pack){let d=new Map;if(d.values=[],d.encoder=p,d.maxValues=e.maxPrivatePackedValues||(U?16:1/0),d.objectMap=U||!1,d.samplingPackedValues=M,qe(c,d),d.values.length>0){l[o++]=216,l[o++]=51,ee(4);let h=d.values;k(h),ee(0),ee(0),N=Object.create(U||null);for(let u=0,b=h.length;u<b;u++)N[h[u]]=u}}wt=g&Et;try{if(wt)return;if(k(c),$&&$.position&&ur(r,k),p.offset=o,a&&a.idsToInsert){o+=a.idsToInsert.length*2,o>se&&de(o),p.offset=o;let d=wn(l.subarray(r,o),a.idsToInsert);return a=null,d}return g&dr?(l.start=r,l.end=o,l):l.subarray(r,o)}finally{if(s){if(Q<10&&Q++,s.length>E&&(s.length=E),ve>1e4)s.transitions=null,Q=0,ve=0,Y.length>0&&(Y=[]);else if(Y.length>0&&!R){for(let d=0,h=Y.length;d<h;d++)Y[d][G]=void 0;Y=[]}}if(n&&p.saveShared){p.structures.length>E&&(p.structures=p.structures.slice(0,E));let d=l.subarray(r,o);return p.updateSharedData()===!1?p.encode(c):d}g&mn&&(o=r)}},this.findCommonStringsToPack=()=>(M=new Map,U||(U=Object.create(null)),c=>{let g=c&&c.threshold||4,d=this.pack?c.maxPrivatePackedValues||16:0;_||(_=this.sharedValues=[]);for(let[h,u]of M)u.count>g&&(U[h]=d++,_.push(h),n=!0);for(;this.saveShared&&this.updateSharedData()===!1;);M=null});const k=c=>{o>se&&(l=de(o));var g=typeof c,d;if(g==="string"){if(N){let S=N[c];if(S>=0){S<16?l[o++]=S+224:(l[o++]=198,S&1?k(15-S>>1):k(S-16>>1));return}else if(M&&!e.pack){let v=M.get(c);v?v.count++:M.set(c,{count:1})}}let h=c.length;if($&&h>=4&&h<1024){if(($.size+=h)>dn){let v,x=($[0]?$[0].length*3+$[1].length:0)+10;o+x>se&&(l=de(o+x)),l[o++]=217,l[o++]=223,l[o++]=249,l[o++]=$.position?132:130,l[o++]=26,v=o-r,o+=4,$.position&&ur(r,k),$=["",""],$.size=0,$.position=v}let S=hn.test(c);$[S?0:1]+=c,l[o++]=S?206:207,k(h);return}let u;h<32?u=1:h<256?u=2:h<65536?u=3:u=5;let b=h*3;if(o+b>se&&(l=de(o+b)),h<64||!y){let S,v,x,T=o+u;for(S=0;S<h;S++)v=c.charCodeAt(S),v<128?l[T++]=v:v<2048?(l[T++]=v>>6|192,l[T++]=v&63|128):(v&64512)===55296&&((x=c.charCodeAt(S+1))&64512)===56320?(v=65536+((v&1023)<<10)+(x&1023),S++,l[T++]=v>>18|240,l[T++]=v>>12&63|128,l[T++]=v>>6&63|128,l[T++]=v&63|128):(l[T++]=v>>12|224,l[T++]=v>>6&63|128,l[T++]=v&63|128);d=T-o-u}else d=y(c,o+u,b);d<24?l[o++]=96|d:d<256?(u<2&&l.copyWithin(o+2,o+1,o+1+d),l[o++]=120,l[o++]=d):d<65536?(u<3&&l.copyWithin(o+3,o+2,o+2+d),l[o++]=121,l[o++]=d>>8,l[o++]=d&255):(u<5&&l.copyWithin(o+5,o+3,o+3+d),l[o++]=122,P.setUint32(o,d),o+=4),o+=d}else if(g==="number")if(!this.alwaysUseFloat&&c>>>0===c)c<24?l[o++]=c:c<256?(l[o++]=24,l[o++]=c):c<65536?(l[o++]=25,l[o++]=c>>8,l[o++]=c&255):(l[o++]=26,P.setUint32(o,c),o+=4);else if(!this.alwaysUseFloat&&c>>0===c)c>=-24?l[o++]=31-c:c>=-256?(l[o++]=56,l[o++]=~c):c>=-65536?(l[o++]=57,P.setUint16(o,~c),o+=2):(l[o++]=58,P.setUint32(o,~c),o+=4);else if(!this.alwaysUseFloat&&c<0&&c>=-4294967296&&Math.floor(c)===c)l[o++]=58,P.setUint32(o,-1-c),o+=4;else{let h;if((h=this.useFloat32)>0&&c<4294967296&&c>=-2147483648){l[o++]=250,P.setFloat32(o,c);let u;if(h<4||(u=c*dt[(l[o]&127)<<1|l[o+1]>>7])>>0===u){o+=4;return}else o--}l[o++]=251,P.setFloat64(o,c),o+=8}else if(g==="object")if(!c)l[o++]=246;else{if(a){let u=a.get(c);if(u){if(l[o++]=216,l[o++]=29,l[o++]=25,!u.references){let b=a.idsToInsert||(a.idsToInsert=[]);u.references=[],b.push(u)}u.references.push(o-r),o+=2;return}else a.set(c,{offset:o-r})}let h=c.constructor;if(h===Object)this.skipFunction===!0&&(c=Object.fromEntries([...Object.keys(c).filter(u=>typeof c[u]!="function").map(u=>[u,c[u]])])),K(c);else if(h===Array){d=c.length,d<24?l[o++]=128|d:ee(d);for(let u=0;u<d;u++)k(c[u])}else if(h===Map)if((this.mapsAsObjects?this.useTag259ForMaps!==!1:this.useTag259ForMaps)&&(l[o++]=217,l[o++]=1,l[o++]=3),d=c.size,d<24?l[o++]=160|d:d<256?(l[o++]=184,l[o++]=d):d<65536?(l[o++]=185,l[o++]=d>>8,l[o++]=d&255):(l[o++]=186,P.setUint32(o,d),o+=4),p.keyMap)for(let[u,b]of c)k(p.encodeKey(u)),k(b);else for(let[u,b]of c)k(u),k(b);else{for(let u=0,b=pt.length;u<b;u++){let S=nr[u];if(c instanceof S){let v=pt[u],x=v.tag;x==null&&(x=v.getTag&&v.getTag.call(this,c)),x<24?l[o++]=192|x:x<256?(l[o++]=216,l[o++]=x):x<65536?(l[o++]=217,l[o++]=x>>8,l[o++]=x&255):x>-1&&(l[o++]=218,P.setUint32(o,x),o+=4),v.encode.call(this,c,k,de);return}}if(c[Symbol.iterator]){if(wt){let u=new Error("Iterable should be serialized as iterator");throw u.iteratorNotHandled=!0,u}l[o++]=159;for(let u of c)k(u);l[o++]=255;return}if(c[Symbol.asyncIterator]||gt(c)){let u=new Error("Iterable/blob should be serialized as iterator");throw u.iteratorNotHandled=!0,u}if(this.useToJSON&&c.toJSON){const u=c.toJSON();if(u!==c)return k(u)}K(c)}}else if(g==="boolean")l[o++]=c?245:244;else if(g==="bigint"){if(c<BigInt(1)<<BigInt(64)&&c>=0)l[o++]=27,P.setBigUint64(o,c);else if(c>-(BigInt(1)<<BigInt(64))&&c<0)l[o++]=59,P.setBigUint64(o,-c-BigInt(1));else if(this.largeBigIntToFloat)l[o++]=251,P.setFloat64(o,Number(c));else{c>=BigInt(0)?l[o++]=194:(l[o++]=195,c=BigInt(-1)-c);let h=[];for(;c;)h.push(Number(c&BigInt(255))),c>>=BigInt(8);mt(new Uint8Array(h.reverse()),de);return}o+=8}else if(g==="undefined")l[o++]=247;else throw new Error("Unknown type: "+g)},K=this.useRecords===!1?this.variableMapSize?c=>{let g=Object.keys(c),d=Object.values(c),h=g.length;if(h<24?l[o++]=160|h:h<256?(l[o++]=184,l[o++]=h):h<65536?(l[o++]=185,l[o++]=h>>8,l[o++]=h&255):(l[o++]=186,P.setUint32(o,h),o+=4),p.keyMap)for(let u=0;u<h;u++)k(p.encodeKey(g[u])),k(d[u]);else for(let u=0;u<h;u++)k(g[u]),k(d[u])}:c=>{l[o++]=185;let g=o-r;o+=2;let d=0;if(p.keyMap)for(let h in c)(typeof c.hasOwnProperty!="function"||c.hasOwnProperty(h))&&(k(p.encodeKey(h)),k(c[h]),d++);else for(let h in c)(typeof c.hasOwnProperty!="function"||c.hasOwnProperty(h))&&(k(h),k(c[h]),d++);l[g+++r]=d>>8,l[g+r]=d&255}:(c,g)=>{let d,h=i.transitions||(i.transitions=Object.create(null)),u=0,b=0,S,v;if(this.keyMap){v=Object.keys(c).map(T=>this.encodeKey(T)),b=v.length;for(let T=0;T<b;T++){let Lt=v[T];d=h[Lt],d||(d=h[Lt]=Object.create(null),u++),h=d}}else for(let T in c)(typeof c.hasOwnProperty!="function"||c.hasOwnProperty(T))&&(d=h[T],d||(h[G]&1048576&&(S=h[G]&65535),d=h[T]=Object.create(null),u++),h=d,b++);let x=h[G];if(x!==void 0)x&=65535,l[o++]=217,l[o++]=x>>8|224,l[o++]=x&255;else if(v||(v=h.__keys__||(h.__keys__=Object.keys(c))),S===void 0?(x=i.nextId++,x||(x=0,i.nextId=1),x>=or&&(i.nextId=(x=E)+1)):x=S,i[x]=v,x<E){l[o++]=217,l[o++]=x>>8|224,l[o++]=x&255,h=i.transitions;for(let T=0;T<b;T++)(h[G]===void 0||h[G]&1048576)&&(h[G]=x),h=h[v[T]];h[G]=x|1048576,n=!0}else{if(h[G]=x,P.setUint32(o,3655335680),o+=3,u&&(ve+=Q*u),Y.length>=or-E&&(Y.shift()[G]=void 0),Y.push(h),ee(b+2),k(57344+x),k(v),g)return;for(let T in c)(typeof c.hasOwnProperty!="function"||c.hasOwnProperty(T))&&k(c[T]);return}if(b<24?l[o++]=128|b:ee(b),!g)for(let T in c)(typeof c.hasOwnProperty!="function"||c.hasOwnProperty(T))&&k(c[T])},de=c=>{let g;if(c>16777216){if(c-r>ar)throw new Error("Encoded buffer would be larger than maximum buffer size");g=Math.min(ar,Math.round(Math.max((c-r)*(c>67108864?1.25:2),4194304)/4096)*4096)}else g=(Math.max(c-r<<2,l.length-1)>>12)+1<<12;let d=new yt(g);return P=new DataView(d.buffer,0,g),l.copy?l.copy(d,0,r,c):d.set(l.slice(r,c)),o-=r,r=0,se=d.length-10,l=d};let ie=100,Tt=1e3;this.encodeAsIterable=function(c,g){return Rt(c,g,he)},this.encodeAsAsyncIterable=function(c,g){return Rt(c,g,Mt)};function*he(c,g,d){let h=c.constructor;if(h===Object){let u=p.useRecords!==!1;u?K(c,!0):lr(Object.keys(c).length,160);for(let b in c){let S=c[b];u||k(b),S&&typeof S=="object"?g[b]?yield*he(S,g[b]):yield*He(S,g,b):k(S)}}else if(h===Array){let u=c.length;ee(u);for(let b=0;b<u;b++){let S=c[b];S&&(typeof S=="object"||o-r>ie)?g.element?yield*he(S,g.element):yield*He(S,g,"element"):k(S)}}else if(c[Symbol.iterator]&&!c.buffer){l[o++]=159;for(let u of c)u&&(typeof u=="object"||o-r>ie)?g.element?yield*he(u,g.element):yield*He(u,g,"element"):k(u);l[o++]=255}else gt(c)?(lr(c.size,64),yield l.subarray(r,o),yield c,Ae()):c[Symbol.asyncIterator]?(l[o++]=159,yield l.subarray(r,o),yield c,Ae(),l[o++]=255):k(c);d&&o>r?yield l.subarray(r,o):o-r>ie&&(yield l.subarray(r,o),Ae())}function*He(c,g,d){let h=o-r;try{k(c),o-r>ie&&(yield l.subarray(r,o),Ae())}catch(u){if(u.iteratorNotHandled)g[d]={},o=r+h,yield*he.call(this,c,g[d]);else throw u}}function Ae(){ie=Tt,p.encode(null,Et)}function Rt(c,g,d){return g&&g.chunkThreshold?ie=Tt=g.chunkThreshold:ie=100,c&&typeof c=="object"?(p.encode(null,Et),d(c,p.iterateProperties||(p.iterateProperties={}),!0)):[p.encode(c)]}async function*Mt(c,g){for(let d of he(c,g,!0)){let h=d.constructor;if(h===ir||h===Uint8Array)yield d;else if(gt(d)){let u=d.stream().getReader(),b;for(;!(b=await u.read()).done;)yield b.value}else if(d[Symbol.asyncIterator])for await(let u of d)Ae(),u?yield*Mt(u,g.async||(g.async={})):yield p.encode(u);else yield d}}}useBuffer(e){l=e,P=new DataView(l.buffer,l.byteOffset,l.byteLength),o=0}clearSharedData(){this.structures&&(this.structures=[]),this.sharedValues&&(this.sharedValues=void 0)}updateSharedData(){let e=this.sharedVersion||0;this.sharedVersion=e+1;let r=this.structures.slice(0),s=new fr(r,this.sharedValues,this.sharedVersion),n=this.saveShared(s,i=>(i&&i.version||0)==e);return n===!1?(s=this.getShared()||{},this.structures=s.structures||[],this.sharedValues=s.packedValues,this.sharedVersion=s.version,this.structures.nextId=this.structures.length):r.forEach((i,a)=>this.structures[a]=i),n}}function lr(t,e){t<24?l[o++]=e|t:t<256?(l[o++]=e|24,l[o++]=t):t<65536?(l[o++]=e|25,l[o++]=t>>8,l[o++]=t&255):(l[o++]=e|26,P.setUint32(o,t),o+=4)}class fr{constructor(e,r,s){this.structures=e,this.packedValues=r,this.version=s}}function ee(t){t<24?l[o++]=128|t:t<256?(l[o++]=152,l[o++]=t):t<65536?(l[o++]=153,l[o++]=t>>8,l[o++]=t&255):(l[o++]=154,P.setUint32(o,t),o+=4)}const pn=typeof Blob>"u"?function(){}:Blob;function gt(t){if(t instanceof pn)return!0;let e=t[Symbol.toStringTag];return e==="Blob"||e==="File"}function qe(t,e){switch(typeof t){case"string":if(t.length>3){if(e.objectMap[t]>-1||e.values.length>=e.maxValues)return;let s=e.get(t);if(s)++s.count==2&&e.values.push(t);else if(e.set(t,{count:1}),e.samplingPackedValues){let n=e.samplingPackedValues.get(t);n?n.count++:e.samplingPackedValues.set(t,{count:1})}}break;case"object":if(t)if(t instanceof Array)for(let s=0,n=t.length;s<n;s++)qe(t[s],e);else{let s=!e.encoder.useRecords;for(var r in t)t.hasOwnProperty(r)&&(s&&qe(r,e),qe(t[r],e))}break;case"function":console.log(t)}}const yn=new Uint8Array(new Uint16Array([1]).buffer)[0]==1;nr=[Date,Set,Error,RegExp,fe,ArrayBuffer,Uint8Array,Uint8ClampedArray,Uint16Array,Uint32Array,typeof BigUint64Array>"u"?function(){}:BigUint64Array,Int8Array,Int16Array,Int32Array,typeof BigInt64Array>"u"?function(){}:BigInt64Array,Float32Array,Float64Array,fr],pt=[{tag:1,encode(t,e){let r=t.getTime()/1e3;(this.useTimestamp32||t.getMilliseconds()===0)&&r>=0&&r<4294967296?(l[o++]=26,P.setUint32(o,r),o+=4):(l[o++]=251,P.setFloat64(o,r),o+=8)}},{tag:258,encode(t,e){let r=Array.from(t);e(r)}},{tag:27,encode(t,e){e([t.name,t.message])}},{tag:27,encode(t,e){e(["RegExp",t.source,t.flags])}},{getTag(t){return t.tag},encode(t,e){e(t.value)}},{encode(t,e,r){mt(t,r)}},{getTag(t){if(t.constructor===Uint8Array&&(this.tagUint8Array||Me&&this.tagUint8Array!==!1))return 64},encode(t,e,r){mt(t,r)}},te(68,1),te(69,2),te(70,4),te(71,8),te(72,1),te(77,2),te(78,4),te(79,8),te(85,4),te(86,8),{encode(t,e){let r=t.packedValues||[],s=t.structures||[];if(r.values.length>0){l[o++]=216,l[o++]=51,ee(4);let n=r.values;e(n),ee(0),ee(0),packedObjectMap=Object.create(sharedPackedObjectMap||null);for(let i=0,a=n.length;i<a;i++)packedObjectMap[n[i]]=i}if(s){P.setUint32(o,3655335424),o+=3;let n=s.slice(0);n.unshift(57344),n.push(new fe(t.version,1399353956)),e(n)}else e(new fe(t.version,1399353956))}}];function te(t,e){return!yn&&e>1&&(t-=4),{tag:t,encode:function(s,n){let i=s.byteLength,a=s.byteOffset||0,y=s.buffer||s;n(Me?Ke.from(y,a,i):new Uint8Array(y,a,i))}}}function mt(t,e){let r=t.byteLength;r<24?l[o++]=64+r:r<256?(l[o++]=88,l[o++]=r):r<65536?(l[o++]=89,l[o++]=r>>8,l[o++]=r&255):(l[o++]=90,P.setUint32(o,r),o+=4),o+r>=l.length&&e(o+r),l.set(t.buffer?t:new Uint8Array(t),o),o+=r}function wn(t,e){let r,s=e.length*2,n=t.length-s;e.sort((i,a)=>i.offset>a.offset?1:-1);for(let i=0;i<e.length;i++){let a=e[i];a.id=i;for(let y of a.references)t[y++]=i>>8,t[y]=i&255}for(;r=e.pop();){let i=r.offset;t.copyWithin(i+s,i,n),s-=2;let a=i+s;t[a++]=216,t[a++]=28,n=i}return t}function ur(t,e){P.setUint32($.position+t,o-$.position-t+1);let r=$;$=null,e(r[0]),e(r[1])}let bt=new cr({useRecords:!1});const gn=bt.encode;bt.encodeAsIterable,bt.encodeAsAsyncIterable;const dr=512,mn=1024,Et=2048;class bn extends Wr{constructor(e){e||(e={}),e.objectMode=!0,super(e),e.structures=[],this.decoder=e.decoder||new Se(e)}_transform(e,r,s){this.incompleteBuffer&&(e=Buffer.concat([this.incompleteBuffer,e]),this.incompleteBuffer=null);let n,i;try{n=this.decoder.decodeMultiple(e)}catch(a){n=a.values,a.incomplete?this.incompleteBuffer=e.slice(a.lastPosition):i=a}for(let a of n||[])a===null&&(a=this.getNullValue()),this.push(a);s(i)}getNullValue(){return Symbol.for(null)}}const En=process.env.CBOR_NATIVE_ACCELERATION_DISABLED!==void 0&&process.env.CBOR_NATIVE_ACCELERATION_DISABLED.toLowerCase()==="true";if(!En){let t;try{typeof require=="function"?t=require("cbor-extract"):t=Jr(import.meta.url)("cbor-extract"),t&&en(t.extractStrings)}catch{}}const hr=ns,pr=is;function Sn(t){return{adbShellCommand:t.android?.shell,appearance:t.appearance,deviceType:t.id,disableVirtualKeyboard:t.android?.softKeyboard===!1?!0:void 0,fontSize:t.fontSize,iosAutocorrect:t.ios?.autocorrect,iosKeyboard:t.ios?.keyboards,language:t.locale,locale:t.locale,location:t.location&&[t.location.latitude,t.location.longitude],orientation:t.orientation,osVersion:t.osVersion,timezone:t.timezone}}const yr=["grant"];function vn(t){return{grantPermissions:t?.permissions==="grant"?!0:void 0,launchApp:t?.app,launchArgs:t?.ios?.args,launchUrl:t?.url,params:t?.params}}class wr extends Error{code;issues;constructor(e,r,s=[]){super(r),this.name="SessionRequestError",this.code=e,this.issues=s}}const C=t=>`expected ${t}`,be=t=>m.string(C(t)).check(m.minLength(1,C(t))),Le=t=>m.literal(t,C(`one of ${t.join(", ")}`)),Ee=t=>m.object(t,C("an object")),gr=()=>m.boolean(C("true or false")),mr=t=>m.number(C("a number")).check(m.gte(-t,C(`at least -${String(t)}`)),m.lte(t,C(`at most ${String(t)}`))),An=/^\w{2}(?:_\w{2})?@sw(=[\w-]+)?$/,xn=/^[a-z0-9_.=:/ ()"-]+$/i,kn='letters, digits or _ . = : / ( ) " - and spaces',On=/^[A-Za-z]{2,3}([-_][A-Za-z0-9]{2,8})*$/;function In(t){if(!On.test(t))return!1;try{return new Intl.Locale(t.replaceAll("_","-")),!0}catch{return!1}}function Tn(t){try{return new Intl.DateTimeFormat(void 0,{timeZone:t}),!0}catch{return!1}}const St={code:"needsTarget"},br={code:"needsLaunchApp"},vt="has no effect without a target",Er="has no effect without a target, or with launch.app: false";function Sr({launch:t}){return t?.app!==!1}const Rn=m.object({apiToken:m.optional(be("an API token")),codec:m.optional(Le(ss)),device:Ee({android:m.optional(Ee({shell:m.optional(be("a shell command")),softKeyboard:m.optional(gr())})),appearance:m.optional(Le(hr)),fontSize:m.optional(Le(pr)),id:be("a device id"),ios:m.optional(Ee({autocorrect:m.optional(gr()),keyboards:m.optional(m.array(m.string(C("a keyboard layout")).check(m.regex(An,C("a layout like en_US@sw=QWERTY"))),C("a list of keyboard layouts")))})),locale:m.optional(m.string(C("a BCP 47 tag, e.g. fr-CA")).check(m.refine(In,{error:C("a BCP 47 tag, e.g. fr-CA")}))),location:m.optional(Ee({latitude:mr(90),longitude:mr(180)})),orientation:m.optional(Le(Dt)),osVersion:m.optional(be("an OS version")),timezone:m.optional(m.string(C("an IANA timezone")).check(m.refine(Tn,{error:C("an IANA timezone, e.g. America/Toronto")})))}),endpoint:m.optional(m.url(C("a URL"))),launch:m.optional(Ee({app:m.optional(m.union([be("an app id"),m.literal(!1)],C("an app id or false"))),ios:m.optional(Ee({args:m.optional(m.array(m.string(C("an argument")).check(m.regex(xn,C(kn))),C("a list of arguments")).check(m.maxLength(20,C("at most 20 arguments"))))})),params:m.optional(m.custom(t=>typeof t=="object"&&t!==null&&!Array.isArray(t),C("an object"))),permissions:m.optional(Le(yr)),url:m.optional(m.url(C("a URL")))})),proxy:m.optional(m.union([m.literal("intercept"),m.templateLiteral(["http://",m.string()])],C("intercept or an http:// URL"))),target:m.optional(be("an app, build or group id"))}).check(m.refine(t=>t.device.android?.shell===void 0||t.target!==void 0,{error:vt,params:St,path:["device","android","shell"]}),m.refine(t=>t.launch?.app===void 0||t.target!==void 0,{error:vt,params:St,path:["launch","app"]}),m.refine(t=>t.launch?.permissions===void 0||t.target!==void 0,{error:vt,params:St,path:["launch","permissions"]}),m.refine(t=>t.launch?.params===void 0||t.target!==void 0&&Sr(t),{error:Er,params:br,path:["launch","params"]}),m.refine(t=>t.launch?.ios?.args===void 0||t.target!==void 0&&Sr(t),{error:Er,params:br,path:["launch","ios","args"]}));function Mn(t){if(t.code==="custom"){const e=t.params?.code;if(e==="needsTarget"||e==="needsLaunchApp")return e}return"invalidValue"}function Ln(t){const e=Rn.safeParse(t);if(e.success)return;const r=e.error.issues.map(s=>({code:Mn(s),message:s.message,path:s.path.join(".")}));throw new wr("invalid",r.map(({message:s,path:n})=>`${n}: ${s}`).join(`
2
+ `),r)}const Un={dateStyle:"medium",timeStyle:"short"},Pn=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(?::\d{2}(?:\.\d+)?)?(?:Z|[+-]\d{2}:\d{2})$/;function We(t){return Array.isArray(t)?t.map(We).join(", "):typeof t=="boolean"?t?"yes":"no":typeof t=="number"?t.toLocaleString():Cn(t)}function Cn(t){if(Pn.test(t)){const r=new Date(t);if(!Number.isNaN(r.getTime()))return r.toLocaleString(void 0,Un)}const e=Pt();return t===e?"~":t.startsWith(`${e}${qr}`)?`~${t.slice(e.length)}`:t}function vr(){return process.env.APPETIZE_CLI_HOME??oe(Pt(),".appetize","cli","sessions")}function At(t){return oe(vr(),t)}class Je extends Error{details;constructor(e,r={},s){super(e,s===void 0?void 0:{cause:s}),this.name="CommandError",this.details=r}hints(e){return[]}}class Pe extends Je{sessionDir;constructor(e,{cause:r,details:s={},sessionId:n}){const i=At(n);super(e,Object.assign({sessionDir:i},s),r),this.name="SessionError",this.sessionDir=i}static wrap(e,r){if(e instanceof Pe||e instanceof ne)return e;const s=e instanceof Error?e.message:String(e),n=e instanceof Je?e.details:{};return new Pe(s,{cause:e,details:n,sessionId:r})}hints(){return[`Check the session logs for details: ${We(this.sessionDir)}`]}}class _n extends Pe{constructor(e){super(`Session ${e} already exists`,{sessionId:e}),this.name="SessionAlreadyExistsError"}hints(){return[`Pass --force to replace it, deleting ${We(this.sessionDir)}`]}}class ne extends Je{#e;constructor(e,r=[]){super(e),this.name="UsageError",this.#e=r}hints({command:e}){return[...this.#e,`Run 'appetize ${e} --help' for usage`]}}function Nn(t,e,r){const s=e instanceof Error?e.message:String(e);if(!(e instanceof Je))return t==="json"?JSON.stringify({error:{message:s}},null,2):`\u2716 ${s}`;const n=e.hints(r);if(t==="json"){const i=n.length>0?{hints:n}:{};return JSON.stringify({error:{message:s,...e.details,...i}},null,2)}return[`\u2716 ${s}`,...n.map(i=>` ${i}`)].join(`
3
+ `)}function xt(t){try{return process.kill(t,0),!0}catch{return!1}}const Dn=["SIGINT","SIGTERM"],zn=150;function Bn(t){const e=new AbortController,r=setInterval(()=>{xt(t)||(clearInterval(r),e.abort(new Error("The device session exited")))},zn);return r.unref(),e.signal}function Ar(){const t=new AbortController;for(const e of Dn)process.once(e,()=>{t.abort(new Error(`Received ${e}`))});return t.signal}function Fn(t,e){return new Promise((r,s)=>{if(e.aborted){s(xr(e.reason));return}const n=()=>{clearTimeout(i),s(xr(e.reason))},i=setTimeout(()=>{e.removeEventListener("abort",n),r()},t);e.addEventListener("abort",n,{once:!0})})}function xr(t){return t instanceof Error?t:new Error(String(t))}function jn(t){return Object.values(t).some(e=>e!==void 0)?t:void 0}function $n(t,{defaultValue:e=!1}={}){return t===!e?!e:void 0}function Vn(t,e,r){const s=Ge(t,r);if(s===void 0)return;const n=e.find(i=>i===s);if(n===void 0)throw new ne(`${r} expects one of ${e.join(", ")}`);return n}function Kn(t){const e=t.at(-1);return{options:Jn(e)?e:{},positionals:t.slice(0,-1).filter(r=>typeof r=="string"),signal:Ar()}}function qn(t,e){const r=kr(t,e);return r===void 0?void 0:Or(r,e)}function kr(t,e){if(t===void 0)return;const r=typeof t=="boolean"?Number.NaN:Number(t);if(!Number.isFinite(r))throw new ne(`${e} expects a number, e.g., ${e}=-0.1`);return r}function Wn(t,e){return t===void 0?void 0:(Array.isArray(t)?t:[t]).map(s=>Ir(s,e))}function Ge(t,e){if(t!==void 0){if(typeof t!="string"||t==="")throw new ne(`${e} needs a value`);return t}}function Or(t,e){if(!(t>=0&&t<=1))throw new ne(`${e} expects a number between 0 and 1`);return t}function Ir(t,e){const r=Ge(t,e);if(r===void 0)throw new ne(`${e} needs a value`);return r}function Jn(t){return typeof t=="object"&&t!==null}const Gn="APPETIZEIO_FEATURE_FLAGS";function Hn(){const t={};for(const e of(process.env[Gn]??"").split(",")){const r=e.trim();r!==""&&(t[r]=!0)}return t}function Zn(){const t=process.env.APPETIZE_API_TOKEN;if(!t)throw new Error("APPETIZE_API_TOKEN must be set");return t}function Tr(t){return Ge(t.endpoint,"--endpoint")??Yn()}function Yn(){const t=process.env.APPETIZE_ENDPOINT?.trim();return t===""?void 0:t}const Qn="https://appetize.io";async function Rr(t,{authorize:e=!0,commandOptions:r={},query:s={},...n}={}){const i=new URL(t,Tr(r)??Qn);for(const[p,A]of Object.entries(s))i.searchParams.set(p,A);const a=new Headers(n.headers);e&&a.set("x-api-key",Zn());const y=await fetch(i,{...n,headers:a});if(!y.ok)throw new Error(await ei(y));return await y.json()}function Xn(t){if(!(typeof t!="object"||t===null||!("message"in t)))return typeof t.message=="string"?t.message:void 0}async function ei(t){const e=`The webserver rejected the request (${String(t.status)})`,r=await t.json().catch(()=>{}),s=Xn(r);return s?`${e}: ${s}`:e}const Mr=["android","ios"];function Lr(t={},e){return Rr("/api/v2/service/devices",{authorize:!1,commandOptions:t,signal:e})}function ti(t){return Mr.includes(t)}async function ri(t,e={}){return(await Lr(e)).find(s=>s.id===t)?.platform}function si(t){let e={...t,updatedAt:new Date().toISOString()};return{path:Ot(e.sessionId),save:r=>(e={...e,...r,updatedAt:new Date().toISOString()},ui(e),e)}}function Ur(t){const e=t.state?.phase;return e==="ended"||e==="error"?!1:xt(t.pid)}function ni(){const t=vr();return Ut(t,{recursive:!0}),Kr(t).map(e=>kt(e)).filter(e=>e!==void 0)}function ii(t){if(t!==void 0){const r=kt(t);if(!r)throw new Error(`No session found for id ${t}`);return r}const e=ni().filter(Ur);if(e.length===0)throw new Error("No active sessions");if(e.length>1)throw new ne("There are multiple active sessions",["Specify --session-id to pick one"]);return e[0]}function kt(t){try{return JSON.parse($r(Ot(t),"utf8"))}catch{return}}function oi(t){Vr(At(t),{force:!0,recursive:!0})}function ai(t){return oe(Ue(t),"control.sock")}function Pr(t){return oe(Ue(t),"daemon.log")}function ci(t){return oe(Ue(t),"device.log.jsonl")}function li(t,e){return{daemon:Pr(t),device:ci(t),...e==="intercept"?{network:fi(t)}:void 0}}function fi(t){return oe(Ue(t),"network.jsonl")}function Ue(t){const e=At(t);return Ut(e,{recursive:!0}),e}function Ot(t){return oe(Ue(t),"state.json")}function ui(t){const e=Ot(t.sessionId),r=`${e}.tmp`;Fr(r,`${JSON.stringify(t,null,2)}
4
+ `),jr(r,e)}const It="APPETIZE_DAEMON_CONFIG";function di(){const t=process.env[It];if(!t)throw new Error(`${It} is not set`);return JSON.parse(t)}function hi(t){return JSON.stringify(t)}function pi(){let t,e;return{promise:new Promise((s,n)=>{e=s,t=n}),reject:t,resolve:e}}const Cr={useRecords:!1},yi=new cr(Cr);class _r extends xe{#e=[];#t;constructor(e,{signal:r}={}){super(async a=>{this.#t.write(yi.encode(a))},{signal:r}),this.#t=e;const s=new bn(Cr);s.on("data",a=>{tt(a)&&this[L].dispatchMessage(a)}),s.on("error",()=>{this.close()});const n=a=>{s.write(a)},i=()=>{this.close()};e.on("data",n),e.once("close",i),e.once("error",i),this.#e.push(()=>{e.off("data",n),e.off("close",i),e.off("error",i),s.destroy()})}handleClose(e){for(const r of this.#e.splice(0))r();super.handleClose(e)}}function wi(t,e){const{promise:r,reject:s,resolve:n}=pi(),i=Gr(t),a=e?.signal,y=()=>{i.off("connect",E),i.off("error",R),a?.removeEventListener("abort",A)},p=M=>{y(),i.destroy(),s(M)},A=()=>{p(new Error("The connection was aborted"))},E=()=>{y();const M=new _r(i,e);M[L].addEventListener("close",()=>{i.destroy()},{once:!0}),n(M)},R=M=>{p(M)};return a?.aborted?(p(new Error("The connection was aborted")),r):(i.once("connect",E),i.once("error",R),a?.addEventListener("abort",A,{once:!0}),r)}export{_r as $,Tr as A,kt as B,_n as C,It as D,oi as E,li as F,qn as G,We as H,wi as I,Js as J,_t as K,ii as L,Kn as M,Nn as N,Xe as O,gn as P,L as Q,un as R,Pe as S,xe as T,ne as U,tt as V,qt as W,Ne as X,vn as Y,Sn as Z,Qe as _,kr as a,di as a0,si as a1,ri as a2,ai as a3,Ar as a4,Lr as b,Mr as c,Fn as d,Vt as e,Rr as f,Ir as g,Dt as h,ti as i,Pr as j,Ur as k,xt as l,Bn as m,jn as n,$n as o,Ge as p,Wn as q,Or as r,hi as s,Vn as t,pr as u,hr as v,yr as w,Ln as x,wr as y,Hn as z};
package/viewer.html CHANGED
@@ -1,2 +1,2 @@
1
- <!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><link rel="icon" href="data:,"><title>Appetize device</title><style>body,html{height:100%;margin:0;background:#111318}body{display:grid;place-items:center}canvas{max-width:100vw;max-height:100vh;background:#000;touch-action:none}</style></head><body><canvas aria-label="Device screen" tabindex="0"></canvas><script type="module">function lr(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var Ne={exports:{}},Ke,mt;function ur(){if(mt)return Ke;mt=1;var t=1e3,e=t*60,r=e*60,n=r*24,i=n*7,s=n*365.25;Ke=function(w,y){y=y||{};var v=typeof w;if(v==="string"&&w.length>0)return o(w);if(v==="number"&&isFinite(w))return y.long?c(w):d(w);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(w))};function o(w){if(w=String(w),!(w.length>100)){var y=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(w);if(y){var v=parseFloat(y[1]),f=(y[2]||"ms").toLowerCase();switch(f){case"years":case"year":case"yrs":case"yr":case"y":return v*s;case"weeks":case"week":case"w":return v*i;case"days":case"day":case"d":return v*n;case"hours":case"hour":case"hrs":case"hr":case"h":return v*r;case"minutes":case"minute":case"mins":case"min":case"m":return v*e;case"seconds":case"second":case"secs":case"sec":case"s":return v*t;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return v;default:return}}}}function d(w){var y=Math.abs(w);return y>=n?Math.round(w/n)+"d":y>=r?Math.round(w/r)+"h":y>=e?Math.round(w/e)+"m":y>=t?Math.round(w/t)+"s":w+"ms"}function c(w){var y=Math.abs(w);return y>=n?p(w,y,n,"day"):y>=r?p(w,y,r,"hour"):y>=e?p(w,y,e,"minute"):y>=t?p(w,y,t,"second"):w+" ms"}function p(w,y,v,f){var S=y>=v*1.5;return Math.round(w/v)+" "+f+(S?"s":"")}return Ke}var Ve,St;function fr(){if(St)return Ve;St=1;function t(e){n.debug=n,n.default=n,n.coerce=p,n.disable=d,n.enable=s,n.enabled=c,n.humanize=ur(),n.destroy=w,Object.keys(e).forEach(y=>{n[y]=e[y]}),n.names=[],n.skips=[],n.formatters={};function r(y){let v=0;for(let f=0;f<y.length;f++)v=(v<<5)-v+y.charCodeAt(f),v|=0;return n.colors[Math.abs(v)%n.colors.length]}n.selectColor=r;function n(y){let v,f=null,S,g;function C(...b){if(!C.enabled)return;const E=C,A=Number(new Date),k=A-(v||A);E.diff=k,E.prev=v,E.curr=A,v=A,b[0]=n.coerce(b[0]),typeof b[0]!="string"&&b.unshift("%O");let P=0;b[0]=b[0].replace(/%([a-zA-Z%])/g,(q,Z)=>{if(q==="%%")return"%";P++;const _=n.formatters[Z];if(typeof _=="function"){const $=b[P];q=_.call(E,$),b.splice(P,1),P--}return q}),n.formatArgs.call(E,b),(E.log||n.log).apply(E,b)}return C.namespace=y,C.useColors=n.useColors(),C.color=n.selectColor(y),C.extend=i,C.destroy=n.destroy,Object.defineProperty(C,"enabled",{enumerable:!0,configurable:!1,get:()=>f!==null?f:(S!==n.namespaces&&(S=n.namespaces,g=n.enabled(y)),g),set:b=>{f=b}}),typeof n.init=="function"&&n.init(C),C}function i(y,v){const f=n(this.namespace+(typeof v>"u"?":":v)+y);return f.log=this.log,f}function s(y){n.save(y),n.namespaces=y,n.names=[],n.skips=[];const v=(typeof y=="string"?y:"").trim().replace(/\s+/g,",").split(",").filter(Boolean);for(const f of v)f[0]==="-"?n.skips.push(f.slice(1)):n.names.push(f)}function o(y,v){let f=0,S=0,g=-1,C=0;for(;f<y.length;)if(S<v.length&&(v[S]===y[f]||v[S]==="*"))v[S]==="*"?(g=S,C=f,S++):(f++,S++);else if(g!==-1)S=g+1,C++,f=C;else return!1;for(;S<v.length&&v[S]==="*";)S++;return S===v.length}function d(){const y=[...n.names,...n.skips.map(v=>"-"+v)].join(",");return n.enable(""),y}function c(y){for(const v of n.skips)if(o(y,v))return!1;for(const v of n.names)if(o(y,v))return!0;return!1}function p(y){return y instanceof Error?y.stack||y.message:y}function w(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return n.enable(n.load()),n}return Ve=t,Ve}var Ct;function dr(){return Ct||(Ct=1,(function(t,e){e.formatArgs=n,e.save=i,e.load=s,e.useColors=r,e.storage=o(),e.destroy=(()=>{let c=!1;return()=>{c||(c=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})(),e.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"];function r(){if(typeof window<"u"&&window.process&&(window.process.type==="renderer"||window.process.__nwjs))return!0;if(typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;let c;return typeof document<"u"&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||typeof window<"u"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<"u"&&navigator.userAgent&&(c=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(c[1],10)>=31||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}function n(c){if(c[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+c[0]+(this.useColors?"%c ":" ")+"+"+t.exports.humanize(this.diff),!this.useColors)return;const p="color: "+this.color;c.splice(1,0,p,"color: inherit");let w=0,y=0;c[0].replace(/%[a-zA-Z%]/g,v=>{v!=="%%"&&(w++,v==="%c"&&(y=w))}),c.splice(y,0,p)}e.log=console.debug||console.log||(()=>{});function i(c){try{c?e.storage.setItem("debug",c):e.storage.removeItem("debug")}catch{}}function s(){let c;try{c=e.storage.getItem("debug")||e.storage.getItem("DEBUG")}catch{}return!c&&typeof process<"u"&&"env"in process&&(c=process.env.DEBUG),c}function o(){try{return localStorage}catch{}}t.exports=fr()(e);const{formatters:d}=t.exports;d.j=function(c){try{return JSON.stringify(c)}catch(p){return"[UnexpectedJSONParseError]: "+p.message}}})(Ne,Ne.exports)),Ne.exports}var hr=dr(),Se=lr(hr),fe={},se={},Ce={},Et;function xe(){return Et||(Et=1,(function(t){var e=Ce&&Ce.__extends||(function(){var f=function(S,g){return f=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(C,b){C.__proto__=b}||function(C,b){for(var E in b)Object.prototype.hasOwnProperty.call(b,E)&&(C[E]=b[E])},f(S,g)};return function(S,g){if(typeof g!="function"&&g!==null)throw new TypeError("Class extends value "+String(g)+" is not a constructor or null");f(S,g);function C(){this.constructor=S}S.prototype=g===null?Object.create(g):(C.prototype=g.prototype,new C)}})();Object.defineProperty(t,"__esModule",{value:!0}),t.createJSONRPCNotification=t.createJSONRPCRequest=t.createJSONRPCSuccessResponse=t.createJSONRPCErrorResponse=t.JSONRPCErrorCode=t.JSONRPCErrorException=t.isJSONRPCResponses=t.isJSONRPCResponse=t.isJSONRPCRequests=t.isJSONRPCRequest=t.isJSONRPCID=t.JSONRPC=void 0,t.JSONRPC="2.0";var r=function(f){return typeof f=="string"||typeof f=="number"||f===null};t.isJSONRPCID=r;var n=function(f){return f.jsonrpc===t.JSONRPC&&f.method!==void 0&&f.result===void 0&&f.error===void 0};t.isJSONRPCRequest=n;var i=function(f){return Array.isArray(f)&&f.every(t.isJSONRPCRequest)};t.isJSONRPCRequests=i;var s=function(f){return f.jsonrpc===t.JSONRPC&&f.id!==void 0&&(f.result!==void 0||f.error!==void 0)};t.isJSONRPCResponse=s;var o=function(f){return Array.isArray(f)&&f.every(t.isJSONRPCResponse)};t.isJSONRPCResponses=o;var d=function(f,S,g){var C={code:f,message:S};return g!=null&&(C.data=g),C},c=(function(f){e(S,f);function S(g,C,b){var E=f.call(this,g)||this;return Object.setPrototypeOf(E,S.prototype),E.code=C,E.data=b,E}return S.prototype.toObject=function(){return d(this.code,this.message,this.data)},S})(Error);t.JSONRPCErrorException=c,(function(f){f[f.ParseError=-32700]="ParseError",f[f.InvalidRequest=-32600]="InvalidRequest",f[f.MethodNotFound=-32601]="MethodNotFound",f[f.InvalidParams=-32602]="InvalidParams",f[f.InternalError=-32603]="InternalError"})(t.JSONRPCErrorCode||(t.JSONRPCErrorCode={}));var p=function(f,S,g,C){return{jsonrpc:t.JSONRPC,id:f,error:d(S,g,C)}};t.createJSONRPCErrorResponse=p;var w=function(f,S){return{jsonrpc:t.JSONRPC,id:f,result:S??null}};t.createJSONRPCSuccessResponse=w;var y=function(f,S,g){return{jsonrpc:t.JSONRPC,id:f,method:S,params:g}};t.createJSONRPCRequest=y;var v=function(f,S){return{jsonrpc:t.JSONRPC,method:f,params:S}};t.createJSONRPCNotification=v})(Ce)),Ce}var Ee={},Rt;function Ot(){return Rt||(Rt=1,Object.defineProperty(Ee,"__esModule",{value:!0}),Ee.DefaultErrorCode=void 0,Ee.DefaultErrorCode=0),Ee}var At;function pr(){if(At)return se;At=1;var t=se&&se.__awaiter||function(o,d,c,p){function w(y){return y instanceof c?y:new c(function(v){v(y)})}return new(c||(c=Promise))(function(y,v){function f(C){try{g(p.next(C))}catch(b){v(b)}}function S(C){try{g(p.throw(C))}catch(b){v(b)}}function g(C){C.done?y(C.value):w(C.value).then(f,S)}g((p=p.apply(o,d||[])).next())})},e=se&&se.__generator||function(o,d){var c={label:0,sent:function(){if(y[0]&1)throw y[1];return y[1]},trys:[],ops:[]},p,w,y,v;return v={next:f(0),throw:f(1),return:f(2)},typeof Symbol=="function"&&(v[Symbol.iterator]=function(){return this}),v;function f(g){return function(C){return S([g,C])}}function S(g){if(p)throw new TypeError("Generator is already executing.");for(;v&&(v=0,g[0]&&(c=0)),c;)try{if(p=1,w&&(y=g[0]&2?w.return:g[0]?w.throw||((y=w.return)&&y.call(w),0):w.next)&&!(y=y.call(w,g[1])).done)return y;switch(w=0,y&&(g=[g[0]&2,y.value]),g[0]){case 0:case 1:y=g;break;case 4:return c.label++,{value:g[1],done:!1};case 5:c.label++,w=g[1],g=[0];continue;case 7:g=c.ops.pop(),c.trys.pop();continue;default:if(y=c.trys,!(y=y.length>0&&y[y.length-1])&&(g[0]===6||g[0]===2)){c=0;continue}if(g[0]===3&&(!y||g[1]>y[0]&&g[1]<y[3])){c.label=g[1];break}if(g[0]===6&&c.label<y[1]){c.label=y[1],y=g;break}if(y&&c.label<y[2]){c.label=y[2],c.ops.push(g);break}y[2]&&c.ops.pop(),c.trys.pop();continue}g=d.call(o,c)}catch(C){g=[6,C],w=0}finally{p=y=0}if(g[0]&5)throw g[1];return{value:g[0]?g[1]:void 0,done:!0}}};Object.defineProperty(se,"__esModule",{value:!0}),se.JSONRPCClient=void 0;var r=xe(),n=Ot(),i=(function(){function o(d,c){this._send=d,this.createID=c,this.idToResolveMap=new Map,this.id=0}return o.prototype._createID=function(){return this.createID?this.createID():++this.id},o.prototype.timeout=function(d,c){var p=this;c===void 0&&(c=function(v){return(0,r.createJSONRPCErrorResponse)(v,n.DefaultErrorCode,"Request timeout")});var w=function(v,f){var S=setTimeout(function(){v.forEach(function(g){var C=p.idToResolveMap.get(g);C&&(p.idToResolveMap.delete(g),C(c(g)))})},d);return f().then(function(g){return clearTimeout(S),g},function(g){return clearTimeout(S),Promise.reject(g)})},y=function(v,f){var S=(Array.isArray(v)?v:[v]).map(function(g){return g.id}).filter(s);return w(S,function(){return p.requestAdvanced(v,f)})};return{request:function(v,f,S){var g=p._createID();return w([g],function(){return p.requestWithID(v,f,S,g)})},requestAdvanced:function(v,f){return y(v,f)}}},o.prototype.request=function(d,c,p){return this.requestWithID(d,c,p,this._createID())},o.prototype.requestWithID=function(d,c,p,w){return t(this,void 0,void 0,function(){var y,v;return e(this,function(f){switch(f.label){case 0:return y=(0,r.createJSONRPCRequest)(w,d,c),[4,this.requestAdvanced(y,p)];case 1:return v=f.sent(),v.result!==void 0&&!v.error?[2,v.result]:v.result===void 0&&v.error?[2,Promise.reject(new r.JSONRPCErrorException(v.error.message,v.error.code,v.error.data))]:[2,Promise.reject(new Error("An unexpected error occurred"))]}})})},o.prototype.requestAdvanced=function(d,c){var p=this,w=Array.isArray(d);Array.isArray(d)||(d=[d]);var y=d.filter(function(S){return s(S.id)}),v=y.map(function(S){return new Promise(function(g){return p.idToResolveMap.set(S.id,g)})}),f=Promise.all(v).then(function(S){return w||!S.length?S:S[0]});return this.send(w?d:d[0],c).then(function(){return f},function(S){return y.forEach(function(g){p.receive((0,r.createJSONRPCErrorResponse)(g.id,n.DefaultErrorCode,S&&S.message||"Failed to send a request"))}),f})},o.prototype.notify=function(d,c,p){var w=(0,r.createJSONRPCNotification)(d,c);this.send(w,p).then(void 0,function(){})},o.prototype.send=function(d,c){return t(this,void 0,void 0,function(){return e(this,function(p){return[2,this._send(d,c)]})})},o.prototype.rejectAllPendingRequests=function(d){this.idToResolveMap.forEach(function(c,p){return c((0,r.createJSONRPCErrorResponse)(p,n.DefaultErrorCode,d))}),this.idToResolveMap.clear()},o.prototype.receive=function(d){var c=this;Array.isArray(d)||(d=[d]),d.forEach(function(p){var w=c.idToResolveMap.get(p.id);w&&(c.idToResolveMap.delete(p.id),w(p))})},o})();se.JSONRPCClient=i;var s=function(o){return o!=null};return se}var $e={},Mt;function yr(){return Mt||(Mt=1,Object.defineProperty($e,"__esModule",{value:!0})),$e}var oe={},Pt;function wr(){return Pt||(Pt=1,(function(t){var e=oe&&oe.__awaiter||function(C,b,E,A){function k(P){return P instanceof E?P:new E(function(D){D(P)})}return new(E||(E=Promise))(function(P,D){function q($){try{_(A.next($))}catch(ve){D(ve)}}function Z($){try{_(A.throw($))}catch(ve){D(ve)}}function _($){$.done?P($.value):k($.value).then(q,Z)}_((A=A.apply(C,b||[])).next())})},r=oe&&oe.__generator||function(C,b){var E={label:0,sent:function(){if(P[0]&1)throw P[1];return P[1]},trys:[],ops:[]},A,k,P,D;return D={next:q(0),throw:q(1),return:q(2)},typeof Symbol=="function"&&(D[Symbol.iterator]=function(){return this}),D;function q(_){return function($){return Z([_,$])}}function Z(_){if(A)throw new TypeError("Generator is already executing.");for(;D&&(D=0,_[0]&&(E=0)),E;)try{if(A=1,k&&(P=_[0]&2?k.return:_[0]?k.throw||((P=k.return)&&P.call(k),0):k.next)&&!(P=P.call(k,_[1])).done)return P;switch(k=0,P&&(_=[_[0]&2,P.value]),_[0]){case 0:case 1:P=_;break;case 4:return E.label++,{value:_[1],done:!1};case 5:E.label++,k=_[1],_=[0];continue;case 7:_=E.ops.pop(),E.trys.pop();continue;default:if(P=E.trys,!(P=P.length>0&&P[P.length-1])&&(_[0]===6||_[0]===2)){E=0;continue}if(_[0]===3&&(!P||_[1]>P[0]&&_[1]<P[3])){E.label=_[1];break}if(_[0]===6&&E.label<P[1]){E.label=P[1],P=_;break}if(P&&E.label<P[2]){E.label=P[2],E.ops.push(_);break}P[2]&&E.ops.pop(),E.trys.pop();continue}_=b.call(C,E)}catch($){_=[6,$],k=0}finally{A=P=0}if(_[0]&5)throw _[1];return{value:_[0]?_[1]:void 0,done:!0}}},n=oe&&oe.__spreadArray||function(C,b,E){if(E||arguments.length===2)for(var A=0,k=b.length,P;A<k;A++)(P||!(A in b))&&(P||(P=Array.prototype.slice.call(b,0,A)),P[A]=b[A]);return C.concat(P||Array.prototype.slice.call(b))};Object.defineProperty(t,"__esModule",{value:!0}),t.JSONRPCServer=t.createMethodNotFoundResponse=t.createInvalidRequestResponse=void 0;var i=xe(),s=Ot(),o=function(){return(0,i.createJSONRPCErrorResponse)(null,i.JSONRPCErrorCode.ParseError,"Parse error")},d=function(C){return(0,i.createJSONRPCErrorResponse)((0,i.isJSONRPCID)(C.id)?C.id:null,i.JSONRPCErrorCode.InvalidRequest,"Invalid Request")};t.createInvalidRequestResponse=d;var c=function(C){return(0,i.createJSONRPCErrorResponse)(C,i.JSONRPCErrorCode.MethodNotFound,"Method not found")};t.createMethodNotFoundResponse=c;var p=(function(){function C(b){b===void 0&&(b={});var E;this.mapErrorToJSONRPCErrorResponse=f,this.handleMethodNotFound=S,this.nameToMethodMap=new Map,this.middleware=null,this.errorListener=(E=b.errorListener)!==null&&E!==void 0?E:console.warn}return C.prototype.hasMethod=function(b){return this.nameToMethodMap.has(b)},C.prototype.addMethod=function(b,E){this.addMethodAdvanced(b,this.toJSONRPCMethod(E))},C.prototype.removeMethod=function(b){this.nameToMethodMap.delete(b)},C.prototype.toJSONRPCMethod=function(b){return function(E,A){var k=b(E.params,A);return Promise.resolve(k).then(function(P){return v(E.id,P)})}},C.prototype.addMethodAdvanced=function(b,E){this.nameToMethodMap.set(b,E)},C.prototype.receiveJSON=function(b,E){var A=this.tryParseRequestJSON(b);return A?this.receive(A,E):Promise.resolve(o())},C.prototype.tryParseRequestJSON=function(b){try{return JSON.parse(b)}catch{return null}},C.prototype.receive=function(b,E){return Array.isArray(b)?this.receiveMultiple(b,E):this.receiveSingle(b,E)},C.prototype.receiveMultiple=function(b,E){return e(this,void 0,void 0,function(){var A,k=this;return r(this,function(P){switch(P.label){case 0:return b.length===0?[2,(0,i.createJSONRPCErrorResponse)(null,i.JSONRPCErrorCode.InvalidRequest,"Invalid Request")]:[4,Promise.all(b.map(function(D){return k.receiveSingle(D,E)}))];case 1:return A=P.sent().filter(w),A.length===1?[2,A[0]]:A.length?[2,A]:[2,null]}})})},C.prototype.receiveSingle=function(b,E){return e(this,void 0,void 0,function(){var A,k;return r(this,function(P){switch(P.label){case 0:return A=this.nameToMethodMap.get(b.method),(0,i.isJSONRPCRequest)(b)?[3,1]:[2,(0,t.createInvalidRequestResponse)(b)];case 1:return[4,this.callMethod(A,b,E)];case 2:return k=P.sent(),[2,g(b,k)]}})})},C.prototype.applyMiddleware=function(){for(var b=[],E=0;E<arguments.length;E++)b[E]=arguments[E];this.middleware?this.middleware=this.combineMiddlewares(n([this.middleware],b,!0)):this.middleware=this.combineMiddlewares(b)},C.prototype.combineMiddlewares=function(b){return b.length?b.reduce(this.middlewareReducer):null},C.prototype.middlewareReducer=function(b,E){return function(A,k,P){return b(function(D,q){return E(A,D,q)},k,P)}},C.prototype.callMethod=function(b,E,A){var k=this,P=function(q,Z){return b?b(q,Z):k.handleMethodNotFound(q,Z)},D=function(q){return k.errorListener('An unexpected error occurred while executing "'.concat(E.method,'" JSON-RPC method:'),q),Promise.resolve(k.mapErrorToJSONRPCErrorResponseIfNecessary(E.id,q))};try{return(this.middleware||y)(P,E,A).then(void 0,D)}catch(q){return D(q)}},C.prototype.mapErrorToJSONRPCErrorResponseIfNecessary=function(b,E){return b!==void 0?this.mapErrorToJSONRPCErrorResponse(b,E):null},C})();t.JSONRPCServer=p;var w=function(C){return C!==null},y=function(C,b,E){return C(b,E)},v=function(C,b){return C!==void 0?(0,i.createJSONRPCSuccessResponse)(C,b):null},f=function(C,b){var E,A=(E=b?.message)!==null&&E!==void 0?E:"An unexpected error occurred",k=s.DefaultErrorCode,P;return b instanceof i.JSONRPCErrorException&&(k=b.code,P=b.data),(0,i.createJSONRPCErrorResponse)(C,k,A,P)},S=function(C){return e(void 0,void 0,void 0,function(){return r(this,function(b){return C.id!==void 0?[2,(0,t.createMethodNotFoundResponse)(C.id)]:[2,null]})})},g=function(C,b){return b||(C.id!==void 0?(0,i.createJSONRPCErrorResponse)(C.id,i.JSONRPCErrorCode.InternalError,"Internal error"):null)}})(oe)),oe}var ae={},It;function vr(){if(It)return ae;It=1;var t=ae&&ae.__awaiter||function(i,s,o,d){function c(p){return p instanceof o?p:new o(function(w){w(p)})}return new(o||(o=Promise))(function(p,w){function y(S){try{f(d.next(S))}catch(g){w(g)}}function v(S){try{f(d.throw(S))}catch(g){w(g)}}function f(S){S.done?p(S.value):c(S.value).then(y,v)}f((d=d.apply(i,s||[])).next())})},e=ae&&ae.__generator||function(i,s){var o={label:0,sent:function(){if(p[0]&1)throw p[1];return p[1]},trys:[],ops:[]},d,c,p,w;return w={next:y(0),throw:y(1),return:y(2)},typeof Symbol=="function"&&(w[Symbol.iterator]=function(){return this}),w;function y(f){return function(S){return v([f,S])}}function v(f){if(d)throw new TypeError("Generator is already executing.");for(;w&&(w=0,f[0]&&(o=0)),o;)try{if(d=1,c&&(p=f[0]&2?c.return:f[0]?c.throw||((p=c.return)&&p.call(c),0):c.next)&&!(p=p.call(c,f[1])).done)return p;switch(c=0,p&&(f=[f[0]&2,p.value]),f[0]){case 0:case 1:p=f;break;case 4:return o.label++,{value:f[1],done:!1};case 5:o.label++,c=f[1],f=[0];continue;case 7:f=o.ops.pop(),o.trys.pop();continue;default:if(p=o.trys,!(p=p.length>0&&p[p.length-1])&&(f[0]===6||f[0]===2)){o=0;continue}if(f[0]===3&&(!p||f[1]>p[0]&&f[1]<p[3])){o.label=f[1];break}if(f[0]===6&&o.label<p[1]){o.label=p[1],p=f;break}if(p&&o.label<p[2]){o.label=p[2],o.ops.push(f);break}p[2]&&o.ops.pop(),o.trys.pop();continue}f=s.call(i,o)}catch(S){f=[6,S],c=0}finally{d=p=0}if(f[0]&5)throw f[1];return{value:f[0]?f[1]:void 0,done:!0}}};Object.defineProperty(ae,"__esModule",{value:!0}),ae.JSONRPCServerAndClient=void 0;var r=xe(),n=(function(){function i(s,o,d){d===void 0&&(d={});var c;this.server=s,this.client=o,this.errorListener=(c=d.errorListener)!==null&&c!==void 0?c:console.warn}return i.prototype.applyServerMiddleware=function(){for(var s,o=[],d=0;d<arguments.length;d++)o[d]=arguments[d];(s=this.server).applyMiddleware.apply(s,o)},i.prototype.hasMethod=function(s){return this.server.hasMethod(s)},i.prototype.addMethod=function(s,o){this.server.addMethod(s,o)},i.prototype.addMethodAdvanced=function(s,o){this.server.addMethodAdvanced(s,o)},i.prototype.removeMethod=function(s){this.server.removeMethod(s)},i.prototype.timeout=function(s){return this.client.timeout(s)},i.prototype.request=function(s,o,d){return this.client.request(s,o,d)},i.prototype.requestAdvanced=function(s,o){return this.client.requestAdvanced(s,o)},i.prototype.notify=function(s,o,d){this.client.notify(s,o,d)},i.prototype.rejectAllPendingRequests=function(s){this.client.rejectAllPendingRequests(s)},i.prototype.receiveAndSend=function(s,o,d){return t(this,void 0,void 0,function(){var c,p;return e(this,function(w){switch(w.label){case 0:return(0,r.isJSONRPCResponse)(s)||(0,r.isJSONRPCResponses)(s)?(this.client.receive(s),[3,4]):[3,1];case 1:return(0,r.isJSONRPCRequest)(s)||(0,r.isJSONRPCRequests)(s)?[4,this.server.receive(s,o)]:[3,3];case 2:return c=w.sent(),c?[2,this.client.send(c,d)]:[3,4];case 3:return p="Received an invalid JSON-RPC message",this.errorListener(p,s),[2,Promise.reject(new Error(p))];case 4:return[2]}})})},i})();return ae.JSONRPCServerAndClient=n,ae}var kt;function gr(){return kt||(kt=1,(function(t){var e=fe&&fe.__createBinding||(Object.create?(function(n,i,s,o){o===void 0&&(o=s);var d=Object.getOwnPropertyDescriptor(i,s);(!d||("get"in d?!i.__esModule:d.writable||d.configurable))&&(d={enumerable:!0,get:function(){return i[s]}}),Object.defineProperty(n,o,d)}):(function(n,i,s,o){o===void 0&&(o=s),n[o]=i[s]})),r=fe&&fe.__exportStar||function(n,i){for(var s in n)s!=="default"&&!Object.prototype.hasOwnProperty.call(i,s)&&e(i,n,s)};Object.defineProperty(t,"__esModule",{value:!0}),r(pr(),t),r(yr(),t),r(xe(),t),r(wr(),t),r(vr(),t)})(fe)),fe}var _e=gr();class br extends Event{code;reason;wasClean;constructor(e,r={}){super(e,r),this.code=r.code??0,this.reason=r.reason??"",this.wasClean=r.wasClean??!1}}function mr(t,e){const r="CloseEvent"in globalThis?globalThis.CloseEvent:br;return new r(t,e)}class Sr{#e=new EventTarget;addEventListener(e,r,n){return this.#e.addEventListener(e,r,n),()=>{this.#e.removeEventListener(e,r,n)}}removeEventListener(e,r,n){this.#e.removeEventListener(e,r,n)}dispatchEvent(e){return this.#e.dispatchEvent(e)}}const j=Symbol.for("@appetizeio/rpc:rpcMethods");class Cr extends Sr{send;constructor(e){super(),this.send=e}dispatchClose(e){return this.dispatchEvent(mr("close",e))}dispatchMessage(e){return this.dispatchEvent(new CustomEvent("message",{detail:e}))}}const Nt=Se("appetize.io:error:rpc");function We(t,e){const r=new _e.JSONRPCServerAndClient(new _e.JSONRPCServer({errorListener:Nt}),Rr(t),{errorListener:Nt}),n=t[j].addEventListener("message",({detail:s})=>{r.receiveAndSend(s)}),i=t[j].addEventListener("close",()=>{n(),r.rejectAllPendingRequests("Transport closed")},{once:!0});for(const s in e){const o=e[s];o&&r.addMethod(s,o.bind(e))}return{rpc:r,unsub:()=>{n(),i()}}}function Er(t,e){const{rpc:r,unsub:n}=We(t,e);return{client:r.client,unsub:n}}function Fe(t,e){const r=t[j].addEventListener("message",({detail:i})=>{if("method"in i)try{e({method:i.method,param:i.params})}catch{}}),n=t[j].addEventListener("close",r,{once:!0});return()=>{r(),n()}}function Rr(t){return new _e.JSONRPCClient(t[j].send.bind(t[j]),()=>Math.floor(Math.random()*Number.MAX_SAFE_INTEGER)+1)}const Or=(...t)=>Er(...t),Ge=["ArrowDown","ArrowLeft","ArrowRight","ArrowUp","Backspace","Enter","Tab"],Ar=33333,Mr=[[99,10],[396,11],[792,21],[1620,22],[3600,31],[5120,32],[8192,40],[8704,42],[22080,50],[36864,51],[139264,60]],Pr=new Intl.Segmenter(void 0,{granularity:"grapheme"}),Ir=new Set(Ge);class kr{#e;#t=!1;#r;#n;#i;#o;#a;#s;#c;#l=0;#u=!1;constructor({canvas:e,context:r,onClose:n,onError:i,signal:s,stream:o}){this.#e=e,this.#r=r,this.#o=n,this.#a=i,this.#s=s,this.#c=o,this.#s?.addEventListener("abort",this.close,{once:!0}),this.#p()}close=()=>{this.#t||(this.#t=!0,this.#f(),this.#n=void 0,this.#c.close(),this.#s?.removeEventListener("abort",this.close),this.#o?.())};#f(){this.#n&&this.#n.state!=="closed"&&this.#n.close()}#h(e){const r=Fr(e.data,e.width,e.height),n=`${r}:${String(e.width)}x${String(e.height)}`;this.#n&&this.#i===n||(this.#f(),this.#i=n,this.#e.height=e.height,this.#e.width=e.width,this.#n=new VideoDecoder({error:this.#d,output:i=>{this.#r.drawImage(i,0,0,this.#e.width,this.#e.height),i.close()}}),this.#n.configure({codec:r,codedHeight:e.height,codedWidth:e.width,hardwareAcceleration:"no-preference",optimizeForLatency:!0}))}async#p(){try{for await(const e of this.#c){if(this.#t)return;if(e.data.byteLength!==0){if(e.type==="key"&&e.codec==="jpeg"){this.#u=!1,this.#i=void 0,this.#f(),this.#n=void 0,await this.#y(e);continue}if(!(e.type==="delta"&&this.#u)&&(e.type==="key"&&(this.#u=!1,this.#h(e)),this.#n?.state==="configured")){if(this.#n.decodeQueueSize>2&&e.type==="delta"){this.#d();continue}this.#n.decode(new EncodedVideoChunk({data:new Uint8Array(e.data),timestamp:this.#l,type:e.type})),this.#l+=Ar}}}}catch(e){this.#t||this.#a?.(e)}finally{this.close()}}#d=()=>{this.#u=!0,this.#i=void 0,this.#f(),this.#n=void 0,this.#c.requestKeyFrame()};async#y(e){const r=await createImageBitmap(new Blob([new Uint8Array(e.data)],{type:"image/jpeg"}));this.#e.height=e.height,this.#e.width=e.width,this.#r.drawImage(r,0,0,e.width,e.height),r.close()}}function Nr(t,e,{signal:r}={}){if(r?.aborted)return()=>{};const n=s=>{s.altKey||s.ctrlKey||s.metaKey||!Tr(s.key)||(s.preventDefault(),t.keyboard.press(s.key))},i=()=>{e.removeEventListener("keydown",n),r?.removeEventListener("abort",i)};return e.addEventListener("keydown",n),r?.addEventListener("abort",i,{once:!0}),i}function xr(t,e,{signal:r}={}){let n,i;const s=p=>{n===void 0&&(p.preventDefault(),n=p.pointerId,i=He(e,p),e.focus(),e.setPointerCapture(p.pointerId),t.touch.down(i.x,i.y))},o=p=>{p.pointerId===n&&(p.preventDefault(),i=He(e,p),t.touch.move(i.x,i.y))},d=p=>{if(p.pointerId!==n)return;p.preventDefault();const w=He(e,p);t.touch.up(w.x,w.y),_t(e,p.pointerId),n=void 0,i=void 0},c=()=>{n!==void 0&&_t(e,n),i&&t.touch.up(i.x,i.y),n=void 0,i=void 0,e.removeEventListener("pointercancel",d),e.removeEventListener("pointerdown",s),e.removeEventListener("pointermove",o),e.removeEventListener("pointerup",d),r?.removeEventListener("abort",c)};return r?.aborted||(e.addEventListener("pointercancel",d),e.addEventListener("pointerdown",s),e.addEventListener("pointermove",o),e.addEventListener("pointerup",d),r?.addEventListener("abort",c,{once:!0})),c}async function _r(t,e,{onClose:r,onError:n,signal:i}={}){const s=e.getContext("2d");if(!s)throw new Error("Canvas context unavailable");i?.throwIfAborted();const o=await t.video.createStream({signal:i});return{close:new kr({canvas:e,context:s,onClose:r,onError:n,signal:i,stream:o}).close}}function xt(t){return Math.max(0,Math.min(1,t))}function Fr(t,e,r){const n=Math.ceil(e/16)*Math.ceil(r/16),i=Mr.find(([s])=>n<=s)?.[1]??62;for(let s=0;s<t.length-7;s+=1){const o=t[s]===0&&t[s+1]===0&&t[s+2]===1,d=t[s]===0&&t[s+1]===0&&t[s+2]===0&&t[s+3]===1,c=o?s+3:d?s+4:-1;if(c>=0&&(t[c]&31)===7)return`avc1.${[t[c+1],t[c+2],Math.max(t[c+3],i)].map(p=>p.toString(16).padStart(2,"0")).join("")}`}return"avc1.42e01e"}function Tr(t){return Array.from(Pr.segment(t)).length===1||Ir.has(t)}function He(t,e){const r=t.getBoundingClientRect();return{x:xt((e.clientX-r.left)/r.width),y:xt((e.clientY-r.top)/r.height)}}function _t(t,e){t.hasPointerCapture(e)&&t.releasePointerCapture(e)}let Ze;try{Ze=new TextDecoder}catch{}let M,Q,h=0;const Lr=105,Ur=57342,Jr=57343,Ft=57337,Tt=6,ge={};let Re=11281e4,ce=1681e4,L={},z,Te,Le=0,Oe=0,W,te,V=[],Xe=[],Y,X,Ae,Lt={useRecords:!1,mapsAsObjects:!0},Me=!1,Ut=2;try{new Function("")}catch{Ut=1/0}class ke{constructor(e){if(e&&((e.keyMap||e._keyMap)&&!e.useRecords&&(e.useRecords=!1,e.mapsAsObjects=!0),e.useRecords===!1&&e.mapsAsObjects===void 0&&(e.mapsAsObjects=!0),e.getStructures&&(e.getShared=e.getStructures),e.getShared&&!e.structures&&((e.structures=[]).uninitialized=!0),e.keyMap)){this.mapKey=new Map;for(let[r,n]of Object.entries(e.keyMap))this.mapKey.set(n,r)}Object.assign(this,e)}decodeKey(e){return this.keyMap&&this.mapKey.get(e)||e}encodeKey(e){return this.keyMap&&this.keyMap.hasOwnProperty(e)?this.keyMap[e]:e}encodeKeys(e){if(!this._keyMap)return e;let r=new Map;for(let[n,i]of Object.entries(e))r.set(this._keyMap.hasOwnProperty(n)?this._keyMap[n]:n,i);return r}decodeKeys(e){if(!this._keyMap||e.constructor.name!="Map")return e;if(!this._mapKey){this._mapKey=new Map;for(let[n,i]of Object.entries(this._keyMap))this._mapKey.set(i,n)}let r={};return e.forEach((n,i)=>r[re(this._mapKey.has(i)?this._mapKey.get(i):i)]=n),r}mapDecode(e,r){let n=this.decode(e);return this._keyMap&&n.constructor.name==="Array"?n.map(i=>this.decodeKeys(i)):n}decode(e,r){if(M)return zt(()=>(rt(),this?this.decode(e,r):ke.prototype.decode.call(Lt,e,r)));Q=r>-1?r:e.length,h=0,Oe=0,Te=null,W=null,M=e;try{X=e.dataView||(e.dataView=new DataView(e.buffer,e.byteOffset,e.byteLength))}catch(n){throw M=null,e instanceof Uint8Array?n:new Error("Source must be a Uint8Array or Buffer but was a "+(e&&typeof e=="object"?e.constructor.name:typeof e))}if(this instanceof ke){if(L=this,Y=this.sharedValues&&(this.pack?new Array(this.maxPrivatePackedValues||16).concat(this.sharedValues):this.sharedValues),this.structures)return z=this.structures,Ue();(!z||z.length>0)&&(z=[])}else L=Lt,(!z||z.length>0)&&(z=[]),Y=null;return Ue()}decodeMultiple(e,r){let n,i=0;try{let s=e.length;Me=!0;let o=this?this.decode(e,s):it.decode(e,s);if(r){if(r(o)===!1)return;for(;h<s;)if(i=h,r(Ue())===!1)return}else{for(n=[o];h<s;)i=h,n.push(Ue());return n}}catch(s){throw s.lastPosition=i,s.values=n,s}finally{Me=!1,rt()}}}function Ue(){try{let t=U();if(W){if(h>=W.postBundlePosition){let e=new Error("Unexpected bundle position");throw e.incomplete=!0,e}h=W.postBundlePosition,W=null}if(h==Q)z=null,M=null,te&&(te=null);else if(h>Q){let e=new Error("Unexpected end of CBOR data");throw e.incomplete=!0,e}else if(!Me)throw new Error("Data read, but end of buffer not reached");return t}catch(t){throw rt(),(t instanceof RangeError||t.message.startsWith("Unexpected end of buffer"))&&(t.incomplete=!0),t}}function de(){let t=new Error("Unexpected end of CBOR data");return t.incomplete=!0,t}function U(){if(!(h<Q))throw de();let t=M[h++],e=t>>5;if(t=t&31,t>23)switch(t){case 24:if(h>=Q)throw de();t=M[h++];break;case 25:if(e==7)return qr();t=X.getUint16(h),h+=2;break;case 26:if(e==7){let r=X.getFloat32(h);if(L.useFloat32>2){let n=nt[(M[h]&127)<<1|M[h+1]>>7];return h+=4,(n*r+(r>0?.5:-.5)>>0)/n}return h+=4,r}if(t=X.getUint32(h),h+=4,e===1)return-1-t;break;case 27:if(e==7){let r=X.getFloat64(h);return h+=8,r}if(e>1){if(X.getUint32(h)>0)throw new Error("JavaScript does not support arrays, maps, or strings with length over 4294967295");t=X.getUint32(h+4)}else L.int64AsNumber?(t=X.getUint32(h)*4294967296,t+=X.getUint32(h+4)):t=X.getBigUint64(h);h+=8;break;case 31:switch(e){case 2:case 3:throw new Error("Indefinite length not supported for byte or text strings");case 4:let r=[],n,i=0;for(;(n=U())!=ge;){if(i>=Re)throw new Error(`Array length exceeds ${Re}`);r[i++]=n}return e==4?r:e==3?r.join(""):Buffer.concat(r);case 5:let s;if(L.mapsAsObjects){let o={},d=0;if(L.keyMap)for(;(s=U())!=ge;){if(d++>=ce)throw new Error(`Property count exceeds ${ce}`);o[re(L.decodeKey(s))]=U()}else for(;(s=U())!=ge;){if(d++>=ce)throw new Error(`Property count exceeds ${ce}`);o[re(s)]=U()}return o}else{Ae&&(L.mapsAsObjects=!0,Ae=!1);let o=new Map;if(L.keyMap){let d=0;for(;(s=U())!=ge;){if(d++>=ce)throw new Error(`Map size exceeds ${ce}`);o.set(L.decodeKey(s),U())}}else{let d=0;for(;(s=U())!=ge;){if(d++>=ce)throw new Error(`Map size exceeds ${ce}`);o.set(s,U())}}return o}case 7:return ge;default:throw new Error("Invalid major type for indefinite length "+e)}default:throw new Error("Unknown token "+t)}switch(e){case 0:return t;case 1:return~t;case 2:return Br(t);case 3:if(Oe>=h)return Te.slice(h-Le,(h+=t)-Le);if(Oe==0&&Q<140&&t<32){let i=t<16?Dt(t):jr(t);if(i!=null)return i}return Dr(t);case 4:if(t>=Re)throw new Error(`Array length exceeds ${Re}`);if(t>Q-h)throw de();let r=new Array(t);for(let i=0;i<t;i++)r[i]=U();return r;case 5:if(t>=ce)throw new Error(`Map size exceeds ${Re}`);if(t>(Q-h)/2)throw de();if(L.mapsAsObjects){let i={};if(L.keyMap)for(let s=0;s<t;s++)i[re(L.decodeKey(U()))]=U();else for(let s=0;s<t;s++)i[re(U())]=U();return i}else{Ae&&(L.mapsAsObjects=!0,Ae=!1);let i=new Map;if(L.keyMap)for(let s=0;s<t;s++)i.set(L.decodeKey(U()),U());else for(let s=0;s<t;s++)i.set(U(),U());return i}case 6:if(t>=Ft){let i=z[t&8191];if(i)return i.read||(i.read=Ye(i)),i.read();if(t<65536){if(t==Jr){let s=me(),o=U(),d=U();et(o,d);let c={};if(L.keyMap)for(let p=2;p<s;p++){let w=L.decodeKey(d[p-2]);c[re(w)]=U()}else for(let p=2;p<s;p++){let w=d[p-2];c[re(w)]=U()}return c}else if(t==Ur){let s=me(),o=U();for(let d=2;d<s;d++)et(o++,U());return U()}else if(t==Ft)return Gr();if(L.getShared&&(tt(),i=z[t&8191],i))return i.read||(i.read=Ye(i)),i.read()}}let n=V[t];if(n)return n.handlesRead?n(U):n(U());{let i=U();for(let s=0;s<Xe.length;s++){let o=Xe[s](t,i);if(o!==void 0)return o}return new he(i,t)}case 7:switch(t){case 20:return!1;case 21:return!0;case 22:return null;case 23:return;default:let i=(Y||pe())[t];if(i!==void 0)return i;throw new Error("Unknown token "+t)}default:throw isNaN(t)?de():new Error("Unknown CBOR token "+t)}}const Jt=/^[a-zA-Z_$][a-zA-Z\d_$]*$/;function Ye(t){if(!t)throw new Error("Structure is required in record definition");function e(){let r=M[h++];if(r=r&31,r>23)switch(r){case 24:r=M[h++];break;case 25:r=X.getUint16(h),h+=2;break;case 26:r=X.getUint32(h),h+=4;break;default:throw new Error("Expected array header, but got "+M[h-1])}let n=this.compiledReader;for(;n;){if(n.propertyCount===r)return n(U);n=n.next}if(this.slowReads++>=Ut){let s=this.length==r?this:this.slice(0,r);return n=L.keyMap?new Function("r","return {"+s.map(o=>L.decodeKey(o)).map(o=>Jt.test(o)?re(o)+":r()":"["+JSON.stringify(o)+"]:r()").join(",")+"}"):new Function("r","return {"+s.map(o=>Jt.test(o)?re(o)+":r()":"["+JSON.stringify(o)+"]:r()").join(",")+"}"),this.compiledReader&&(n.next=this.compiledReader),n.propertyCount=r,this.compiledReader=n,n(U)}let i={};if(L.keyMap)for(let s=0;s<r;s++)i[re(L.decodeKey(this[s]))]=U();else for(let s=0;s<r;s++)i[re(this[s])]=U();return i}return t.slowReads=0,e}function re(t){if(typeof t=="string")return t==="__proto__"?"__proto_":t;if(typeof t=="number"||typeof t=="boolean"||typeof t=="bigint")return t.toString();if(t==null)return t+"";throw new Error("Invalid property name type "+typeof t)}let Dr=Qe;function Qe(t){let e;if(t<16&&(e=Dt(t)))return e;if(t>64&&Ze)return Ze.decode(M.subarray(h,h+=t));const r=h+t,n=[];for(e="";h<r;){const i=M[h++];if((i&128)===0)n.push(i);else if((i&224)===192)if(i<194||h>=r||(M[h]&192)!==128)n.push(65533);else{const s=M[h++]&63;n.push((i&31)<<6|s)}else if((i&240)===224){const s=h<r?M[h]:0;if(h>=r||(s&192)!==128||i===224&&s<160||i===237&&s>=160)n.push(65533);else if(h++,h>=r||(M[h]&192)!==128)n.push(65533);else{const o=M[h++]&63;n.push((i&31)<<12|(s&63)<<6|o)}}else if((i&248)===240){const s=h<r?M[h]:0;if(i>244||h>=r||(s&192)!==128||i===240&&s<144||i===244&&s>=144)n.push(65533);else if(h++,h>=r||(M[h]&192)!==128)n.push(65533);else{const o=M[h++]&63;if(h>=r||(M[h]&192)!==128)n.push(65533);else{const d=M[h++]&63;let c=(i&7)<<18|(s&63)<<12|o<<6|d;c-=65536,n.push(c>>>10&1023|55296),n.push(56320|c&1023)}}}else n.push(65533);n.length>=4096&&(e+=H.apply(String,n),n.length=0)}return n.length>0&&(e+=H.apply(String,n)),e}let H=String.fromCharCode;function jr(t){let e=h,r=new Array(t);for(let n=0;n<t;n++){const i=M[h++];if((i&128)>0){h=e;return}r[n]=i}return H.apply(String,r)}function Dt(t){if(t<4)if(t<2){if(t===0)return"";{let e=M[h++];if((e&128)>1){h-=1;return}return H(e)}}else{let e=M[h++],r=M[h++];if((e&128)>0||(r&128)>0){h-=2;return}if(t<3)return H(e,r);let n=M[h++];if((n&128)>0){h-=3;return}return H(e,r,n)}else{let e=M[h++],r=M[h++],n=M[h++],i=M[h++];if((e&128)>0||(r&128)>0||(n&128)>0||(i&128)>0){h-=4;return}if(t<6){if(t===4)return H(e,r,n,i);{let s=M[h++];if((s&128)>0){h-=5;return}return H(e,r,n,i,s)}}else if(t<8){let s=M[h++],o=M[h++];if((s&128)>0||(o&128)>0){h-=6;return}if(t<7)return H(e,r,n,i,s,o);let d=M[h++];if((d&128)>0){h-=7;return}return H(e,r,n,i,s,o,d)}else{let s=M[h++],o=M[h++],d=M[h++],c=M[h++];if((s&128)>0||(o&128)>0||(d&128)>0||(c&128)>0){h-=8;return}if(t<10){if(t===8)return H(e,r,n,i,s,o,d,c);{let p=M[h++];if((p&128)>0){h-=9;return}return H(e,r,n,i,s,o,d,c,p)}}else if(t<12){let p=M[h++],w=M[h++];if((p&128)>0||(w&128)>0){h-=10;return}if(t<11)return H(e,r,n,i,s,o,d,c,p,w);let y=M[h++];if((y&128)>0){h-=11;return}return H(e,r,n,i,s,o,d,c,p,w,y)}else{let p=M[h++],w=M[h++],y=M[h++],v=M[h++];if((p&128)>0||(w&128)>0||(y&128)>0||(v&128)>0){h-=12;return}if(t<14){if(t===12)return H(e,r,n,i,s,o,d,c,p,w,y,v);{let f=M[h++];if((f&128)>0){h-=13;return}return H(e,r,n,i,s,o,d,c,p,w,y,v,f)}}else{let f=M[h++],S=M[h++];if((f&128)>0||(S&128)>0){h-=14;return}if(t<15)return H(e,r,n,i,s,o,d,c,p,w,y,v,f,S);let g=M[h++];if((g&128)>0){h-=15;return}return H(e,r,n,i,s,o,d,c,p,w,y,v,f,S,g)}}}}}function Br(t){return L.copyBuffers?Uint8Array.prototype.slice.call(M,h,h+=t):M.subarray(h,h+=t)}let jt=new Float32Array(1),Je=new Uint8Array(jt.buffer,0,4);function qr(){let t=M[h++],e=M[h++],r=(t&127)>>2;if(r===31)return e||t&3?NaN:t&128?-1/0:1/0;if(r===0){let n=((t&3)<<8|e)/16777216;return t&128?-n:n}return Je[3]=t&128|(r>>1)+56,Je[2]=(t&7)<<5|e>>3,Je[1]=e<<5,Je[0]=0,jt[0]}new Array(4096);class he{constructor(e,r){this.value=e,this.tag=r}}V[0]=t=>new Date(t),V[1]=t=>new Date(Math.round(t*1e3)),V[2]=t=>{let e=BigInt(0);for(let r=0,n=t.byteLength;r<n;r++)e=BigInt(t[r])+(e<<BigInt(8));return e},V[3]=t=>BigInt(-1)-V[2](t),V[4]=t=>+(t[1]+"e"+t[0]),V[5]=t=>t[1]*Math.exp(t[0]*Math.log(2));const et=(t,e)=>{t=t-57344;let r=z[t];r&&r.isShared&&((z.restoreStructures||(z.restoreStructures=[]))[t]=r),z[t]=e,e.read=Ye(e)};V[Lr]=t=>{let e=t.length,r=t[1];et(t[0],r);let n={};for(let i=2;i<e;i++){let s=r[i-2];n[re(s)]=t[i]}return n},V[14]=t=>W?W[0].slice(W.position0,W.position0+=t):new he(t,14),V[15]=t=>W?W[1].slice(W.position1,W.position1+=t):new he(t,15);let zr={Error,RegExp};V[27]=t=>(zr[t[0]]||Error)(t[1],t[2]);const Bt=t=>{if(M[h++]!=132){let r=new Error("Packed values structure must be followed by a 4 element array");throw M.length<h&&(r.incomplete=!0),r}let e=t();if(!e||!e.length){let r=new Error("Packed values structure must be followed by a 4 element array");throw r.incomplete=!0,r}return Y=Y?e.concat(Y.slice(e.length)):e,Y.prefixes=t(),Y.suffixes=t(),t()};Bt.handlesRead=!0,V[51]=Bt,V[Tt]=t=>{if(!Y)if(L.getShared)tt();else return new he(t,Tt);if(typeof t=="number")return Y[16+(t>=0?2*t:-2*t-1)];let e=new Error("No support for non-integer packed references yet");throw t===void 0&&(e.incomplete=!0),e},V[28]=t=>{te||(te=new Map,te.id=0);let e=te.id++,r=h,n=M[h],i;n>>5==4?i=[]:i={};let s={target:i};te.set(e,s);let o=t();return s.used?(Object.getPrototypeOf(i)!==Object.getPrototypeOf(o)&&(h=r,i=o,te.set(e,{target:i}),o=t()),Object.assign(i,o)):(s.target=o,o)},V[28].handlesRead=!0,V[29]=t=>{let e=te.get(t);return e.used=!0,e.target},V[258]=t=>new Set(t),(V[259]=t=>(L.mapsAsObjects&&(L.mapsAsObjects=!1,Ae=!0),t())).handlesRead=!0;function be(t,e){return typeof t=="string"?t+e:t instanceof Array?t.concat(e):Object.assign({},t,e)}function pe(){if(!Y)if(L.getShared)tt();else throw new Error("No packed values available");return Y}const Kr=1399353956;Xe.push((t,e)=>{if(t>=225&&t<=255)return be(pe().prefixes[t-224],e);if(t>=28704&&t<=32767)return be(pe().prefixes[t-28672],e);if(t>=1879052288&&t<=2147483647)return be(pe().prefixes[t-1879048192],e);if(t>=216&&t<=223)return be(e,pe().suffixes[t-216]);if(t>=27647&&t<=28671)return be(e,pe().suffixes[t-27639]);if(t>=1811940352&&t<=1879048191)return be(e,pe().suffixes[t-1811939328]);if(t==Kr)return{packedValues:Y,structures:z.slice(0),version:e};if(t==55799)return e});const Vr=new Uint8Array(new Uint16Array([1]).buffer)[0]==1,qt=[Uint8Array,Uint8ClampedArray,Uint16Array,Uint32Array,typeof BigUint64Array>"u"?{name:"BigUint64Array"}:BigUint64Array,Int8Array,Int16Array,Int32Array,typeof BigInt64Array>"u"?{name:"BigInt64Array"}:BigInt64Array,Float32Array,Float64Array],$r=[64,68,69,70,71,72,77,78,79,85,86];for(let t=0;t<qt.length;t++)Wr(qt[t],$r[t]);function Wr(t,e){let r="get"+t.name.slice(0,-5),n;typeof t=="function"?n=t.BYTES_PER_ELEMENT:t=null;for(let i=0;i<2;i++){if(!i&&n==1)continue;let s=n==2?1:n==4?2:n==8?3:0;V[i?e:e-4]=n==1||i==Vr?o=>{if(!t)throw new Error("Could not find typed array for code "+e);return!L.copyBuffers&&(n===1||n===2&&!(o.byteOffset&1)||n===4&&!(o.byteOffset&3)||n===8&&!(o.byteOffset&7))?new t(o.buffer,o.byteOffset,o.byteLength>>s):new t(Uint8Array.prototype.slice.call(o,0).buffer)}:o=>{if(!t)throw new Error("Could not find typed array for code "+e);let d=new DataView(o.buffer,o.byteOffset,o.byteLength),c=o.length>>s,p=new t(c),w=d[r];for(let y=0;y<c;y++)p[y]=w.call(d,y<<s,i);return p}}}function Gr(){let t=me(),e=h+U();for(let n=2;n<t;n++){let i=me();h+=i}let r=h;return h=e,W=[Qe(me()),Qe(me())],W.position0=0,W.position1=0,W.postBundlePosition=h,h=r,U()}function me(){if(!(h<Q))throw de();let t=M[h++]&31;if(t>23)switch(t){case 24:if(h>=Q)throw de();t=M[h++];break;case 25:t=X.getUint16(h),h+=2;break;case 26:t=X.getUint32(h),h+=4;break}return t}function tt(){if(L.getShared){let t=zt(()=>(M=null,L.getShared()))||{},e=t.structures||[];L.sharedVersion=t.version,Y=L.sharedValues=t.packedValues,z===!0?L.structures=z=e:z.splice.apply(z,[0,e.length].concat(e))}}function zt(t){let e=Q,r=h,n=Le,i=Oe,s=Te,o=te,d=W,c=new Uint8Array(M.slice(0,Q)),p=z,w=L,y=Me,v=t();return Q=e,h=r,Le=n,Oe=i,Te=s,te=o,W=d,M=c,Me=y,z=p,L=w,X=new DataView(M.buffer,M.byteOffset,M.byteLength),v}function rt(){M=null,te=null,z=null}const nt=new Array(147);for(let t=0;t<256;t++)nt[t]=+("1e"+Math.floor(45.15-t*.30103));let it=new ke({useRecords:!1});const Kt=it.decode;it.decodeMultiple;let De;try{De=new TextEncoder}catch{}let st,Vt;const je=typeof globalThis=="object"&&globalThis.Buffer,Pe=typeof je<"u",ot=Pe?je.allocUnsafeSlow:Uint8Array,$t=Pe?je:Uint8Array,Wt=256,Gt=Pe?4294967296:2144337920;let at,u,B,a=0,ue,G=null;const Hr=61440,Zr=/[\u0080-\uFFFF]/,ee=Symbol("record-id");class Xr extends ke{constructor(e){super(e),this.offset=0;let r,n,i,s,o;e=e||{};let d=$t.prototype.utf8Write?function(l,I){return u.utf8Write(l,I,u.byteLength-I)}:De&&De.encodeInto?function(l,I){return De.encodeInto(l,u.subarray(I)).written}:!1,c=this,p=e.structures||e.saveStructures,w=e.maxSharedStructures;if(w==null&&(w=p?128:0),w>8190)throw new Error("Maximum maxSharedStructure is 8190");let y=e.sequential;y&&(w=0),this.structures||(this.structures=[]),this.saveStructures&&(this.saveShared=this.saveStructures);let v,f,S=e.sharedValues,g;if(S){g=Object.create(null);for(let l=0,I=S.length;l<I;l++)g[S[l]]=l}let C=[],b=0,E=0;this.mapEncode=function(l,I){return this._keyMap&&!this._mapped&&l.constructor.name==="Array"&&(l=l.map(R=>this.encodeKeys(R))),this.encode(l,I)},this.encode=function(l,I){if(u||(u=new ot(8192),B=new DataView(u.buffer,0,8192),a=0),ue=u.length-10,ue-a<2048?(u=new ot(u.length),B=new DataView(u.buffer,0,u.length),ue=u.length-10,a=0):I===Yt&&(a=a+7&2147483640),r=a,c.useSelfDescribedHeader&&(B.setUint32(a,3654940416),a+=3),o=c.structuredClone?new Map:null,c.bundleStrings&&typeof l!="string"?(G=[],G.size=1/0):G=null,n=c.structures,n){if(n.uninitialized){let O=c.getShared()||{};c.structures=n=O.structures||[],c.sharedVersion=O.version;let m=c.sharedValues=O.packedValues;if(m){g={};for(let N=0,x=m.length;N<x;N++)g[m[N]]=N}}let R=n.length;if(R>w&&!y&&(R=w),!n.transitions){n.transitions=Object.create(null);for(let O=0;O<R;O++){let m=n[O];if(!m)continue;let N,x=n.transitions;for(let F=0,T=m.length;F<T;F++){x[ee]===void 0&&(x[ee]=O);let J=m[F];N=x[J],N||(N=x[J]=Object.create(null)),x=N}x[ee]=O|1048576}}y||(n.nextId=R)}if(i&&(i=!1),s=n||[],f=g,e.pack){let R=new Map;if(R.values=[],R.encoder=c,R.maxValues=e.maxPrivatePackedValues||(g?16:1/0),R.objectMap=g||!1,R.samplingPackedValues=v,Be(l,R),R.values.length>0){u[a++]=216,u[a++]=51,ne(4);let O=R.values;A(O),ne(0),ne(0),f=Object.create(g||null);for(let m=0,N=O.length;m<N;m++)f[O[m]]=m}}at=I&ft;try{if(at)return;if(A(l),G&&Xt(r,A),c.offset=a,o&&o.idsToInsert){a+=o.idsToInsert.length*2,a>ue&&P(a),c.offset=a;let R=en(u.subarray(r,a),o.idsToInsert);return o=null,R}return I&Yt?(u.start=r,u.end=a,u):u.subarray(r,a)}finally{if(n){if(E<10&&E++,n.length>w&&(n.length=w),b>1e4)n.transitions=null,E=0,b=0,C.length>0&&(C=[]);else if(C.length>0&&!y){for(let R=0,O=C.length;R<O;R++)C[R][ee]=void 0;C=[]}}if(i&&c.saveShared){c.structures.length>w&&(c.structures=c.structures.slice(0,w));let R=u.subarray(r,a);return c.updateSharedData()===!1?c.encode(l):R}I&rn&&(a=r)}},this.findCommonStringsToPack=()=>(v=new Map,g||(g=Object.create(null)),l=>{let I=l&&l.threshold||4,R=this.pack?l.maxPrivatePackedValues||16:0;S||(S=this.sharedValues=[]);for(let[O,m]of v)m.count>I&&(g[O]=R++,S.push(O),i=!0);for(;this.saveShared&&this.updateSharedData()===!1;);v=null});const A=l=>{a>ue&&(u=P(a));var I=typeof l,R;if(I==="string"){if(f){let x=f[l];if(x>=0){x<16?u[a++]=x+224:(u[a++]=198,x&1?A(15-x>>1):A(x-16>>1));return}else if(v&&!e.pack){let F=v.get(l);F?F.count++:v.set(l,{count:1})}}let O=l.length;if(G&&O>=4&&O<1024){if((G.size+=O)>Hr){let F,T=(G[0]?G[0].length*3+G[1].length:0)+10;a+T>ue&&(u=P(a+T)),u[a++]=217,u[a++]=223,u[a++]=249,u[a++]=G.position?132:130,u[a++]=26,F=a-r,a+=4,G.position&&Xt(r,A),G=["",""],G.size=0,G.position=F}let x=Zr.test(l);G[x?0:1]+=l,u[a++]=x?206:207,A(O);return}let m;O<32?m=1:O<256?m=2:O<65536?m=3:m=5;let N=O*3;if(a+N>ue&&(u=P(a+N)),O<64||!d){let x,F,T,J=a+m;for(x=0;x<O;x++)F=l.charCodeAt(x),F<128?u[J++]=F:F<2048?(u[J++]=F>>6|192,u[J++]=F&63|128):(F&64512)===55296&&((T=l.charCodeAt(x+1))&64512)===56320?(F=65536+((F&1023)<<10)+(T&1023),x++,u[J++]=F>>18|240,u[J++]=F>>12&63|128,u[J++]=F>>6&63|128,u[J++]=F&63|128):(u[J++]=F>>12|224,u[J++]=F>>6&63|128,u[J++]=F&63|128);R=J-a-m}else R=d(l,a+m,N);R<24?u[a++]=96|R:R<256?(m<2&&u.copyWithin(a+2,a+1,a+1+R),u[a++]=120,u[a++]=R):R<65536?(m<3&&u.copyWithin(a+3,a+2,a+2+R),u[a++]=121,u[a++]=R>>8,u[a++]=R&255):(m<5&&u.copyWithin(a+5,a+3,a+3+R),u[a++]=122,B.setUint32(a,R),a+=4),a+=R}else if(I==="number")if(!this.alwaysUseFloat&&l>>>0===l)l<24?u[a++]=l:l<256?(u[a++]=24,u[a++]=l):l<65536?(u[a++]=25,u[a++]=l>>8,u[a++]=l&255):(u[a++]=26,B.setUint32(a,l),a+=4);else if(!this.alwaysUseFloat&&l>>0===l)l>=-24?u[a++]=31-l:l>=-256?(u[a++]=56,u[a++]=~l):l>=-65536?(u[a++]=57,B.setUint16(a,~l),a+=2):(u[a++]=58,B.setUint32(a,~l),a+=4);else if(!this.alwaysUseFloat&&l<0&&l>=-4294967296&&Math.floor(l)===l)u[a++]=58,B.setUint32(a,-1-l),a+=4;else{let O;if((O=this.useFloat32)>0&&l<4294967296&&l>=-2147483648){u[a++]=250,B.setFloat32(a,l);let m;if(O<4||(m=l*nt[(u[a]&127)<<1|u[a+1]>>7])>>0===m){a+=4;return}else a--}u[a++]=251,B.setFloat64(a,l),a+=8}else if(I==="object")if(!l)u[a++]=246;else{if(o){let m=o.get(l);if(m){if(u[a++]=216,u[a++]=29,u[a++]=25,!m.references){let N=o.idsToInsert||(o.idsToInsert=[]);m.references=[],N.push(m)}m.references.push(a-r),a+=2;return}else o.set(l,{offset:a-r})}let O=l.constructor;if(O===Object)this.skipFunction===!0&&(l=Object.fromEntries([...Object.keys(l).filter(m=>typeof l[m]!="function").map(m=>[m,l[m]])])),k(l);else if(O===Array){R=l.length,R<24?u[a++]=128|R:ne(R);for(let m=0;m<R;m++)A(l[m])}else if(O===Map)if((this.mapsAsObjects?this.useTag259ForMaps!==!1:this.useTag259ForMaps)&&(u[a++]=217,u[a++]=1,u[a++]=3),R=l.size,R<24?u[a++]=160|R:R<256?(u[a++]=184,u[a++]=R):R<65536?(u[a++]=185,u[a++]=R>>8,u[a++]=R&255):(u[a++]=186,B.setUint32(a,R),a+=4),c.keyMap)for(let[m,N]of l)A(c.encodeKey(m)),A(N);else for(let[m,N]of l)A(m),A(N);else{for(let m=0,N=st.length;m<N;m++){let x=Vt[m];if(l instanceof x){let F=st[m],T=F.tag;T==null&&(T=F.getTag&&F.getTag.call(this,l)),T<24?u[a++]=192|T:T<256?(u[a++]=216,u[a++]=T):T<65536?(u[a++]=217,u[a++]=T>>8,u[a++]=T&255):T>-1&&(u[a++]=218,B.setUint32(a,T),a+=4),F.encode.call(this,l,A,P);return}}if(l[Symbol.iterator]){if(at){let m=new Error("Iterable should be serialized as iterator");throw m.iteratorNotHandled=!0,m}u[a++]=159;for(let m of l)A(m);u[a++]=255;return}if(l[Symbol.asyncIterator]||ct(l)){let m=new Error("Iterable/blob should be serialized as iterator");throw m.iteratorNotHandled=!0,m}if(this.useToJSON&&l.toJSON){const m=l.toJSON();if(m!==l)return A(m)}k(l)}}else if(I==="boolean")u[a++]=l?245:244;else if(I==="bigint"){if(l<BigInt(1)<<BigInt(64)&&l>=0)u[a++]=27,B.setBigUint64(a,l);else if(l>-(BigInt(1)<<BigInt(64))&&l<0)u[a++]=59,B.setBigUint64(a,-l-BigInt(1));else if(this.largeBigIntToFloat)u[a++]=251,B.setFloat64(a,Number(l));else{l>=BigInt(0)?u[a++]=194:(u[a++]=195,l=BigInt(-1)-l);let O=[];for(;l;)O.push(Number(l&BigInt(255))),l>>=BigInt(8);lt(new Uint8Array(O.reverse()),P);return}a+=8}else if(I==="undefined")u[a++]=247;else throw new Error("Unknown type: "+I)},k=this.useRecords===!1?this.variableMapSize?l=>{let I=Object.keys(l),R=Object.values(l),O=I.length;if(O<24?u[a++]=160|O:O<256?(u[a++]=184,u[a++]=O):O<65536?(u[a++]=185,u[a++]=O>>8,u[a++]=O&255):(u[a++]=186,B.setUint32(a,O),a+=4),c.keyMap)for(let m=0;m<O;m++)A(c.encodeKey(I[m])),A(R[m]);else for(let m=0;m<O;m++)A(I[m]),A(R[m])}:l=>{u[a++]=185;let I=a-r;a+=2;let R=0;if(c.keyMap)for(let O in l)(typeof l.hasOwnProperty!="function"||l.hasOwnProperty(O))&&(A(c.encodeKey(O)),A(l[O]),R++);else for(let O in l)(typeof l.hasOwnProperty!="function"||l.hasOwnProperty(O))&&(A(O),A(l[O]),R++);u[I+++r]=R>>8,u[I+r]=R&255}:(l,I)=>{let R,O=s.transitions||(s.transitions=Object.create(null)),m=0,N=0,x,F;if(this.keyMap){F=Object.keys(l).map(J=>this.encodeKey(J)),N=F.length;for(let J=0;J<N;J++){let bt=F[J];R=O[bt],R||(R=O[bt]=Object.create(null),m++),O=R}}else for(let J in l)(typeof l.hasOwnProperty!="function"||l.hasOwnProperty(J))&&(R=O[J],R||(O[ee]&1048576&&(x=O[ee]&65535),R=O[J]=Object.create(null),m++),O=R,N++);let T=O[ee];if(T!==void 0)T&=65535,u[a++]=217,u[a++]=T>>8|224,u[a++]=T&255;else if(F||(F=O.__keys__||(O.__keys__=Object.keys(l))),x===void 0?(T=s.nextId++,T||(T=0,s.nextId=1),T>=Wt&&(s.nextId=(T=w)+1)):T=x,s[T]=F,T<w){u[a++]=217,u[a++]=T>>8|224,u[a++]=T&255,O=s.transitions;for(let J=0;J<N;J++)(O[ee]===void 0||O[ee]&1048576)&&(O[ee]=T),O=O[F[J]];O[ee]=T|1048576,i=!0}else{if(O[ee]=T,B.setUint32(a,3655335680),a+=3,m&&(b+=E*m),C.length>=Wt-w&&(C.shift()[ee]=void 0),C.push(O),ne(N+2),A(57344+T),A(F),I)return;for(let J in l)(typeof l.hasOwnProperty!="function"||l.hasOwnProperty(J))&&A(l[J]);return}if(N<24?u[a++]=128|N:ne(N),!I)for(let J in l)(typeof l.hasOwnProperty!="function"||l.hasOwnProperty(J))&&A(l[J])},P=l=>{let I;if(l>16777216){if(l-r>Gt)throw new Error("Encoded buffer would be larger than maximum buffer size");I=Math.min(Gt,Math.round(Math.max((l-r)*(l>67108864?1.25:2),4194304)/4096)*4096)}else I=(Math.max(l-r<<2,u.length-1)>>12)+1<<12;let R=new ot(I);return B=new DataView(R.buffer,0,I),u.copy?u.copy(R,0,r,l):R.set(u.slice(r,l)),a-=r,r=0,ue=R.length-10,u=R};let D=100,q=1e3;this.encodeAsIterable=function(l,I){return ve(l,I,Z)},this.encodeAsAsyncIterable=function(l,I){return ve(l,I,gt)};function*Z(l,I,R){let O=l.constructor;if(O===Object){let m=c.useRecords!==!1;m?k(l,!0):Ht(Object.keys(l).length,160);for(let N in l){let x=l[N];m||A(N),x&&typeof x=="object"?I[N]?yield*Z(x,I[N]):yield*_(x,I,N):A(x)}}else if(O===Array){let m=l.length;ne(m);for(let N=0;N<m;N++){let x=l[N];x&&(typeof x=="object"||a-r>D)?I.element?yield*Z(x,I.element):yield*_(x,I,"element"):A(x)}}else if(l[Symbol.iterator]&&!l.buffer){u[a++]=159;for(let m of l)m&&(typeof m=="object"||a-r>D)?I.element?yield*Z(m,I.element):yield*_(m,I,"element"):A(m);u[a++]=255}else ct(l)?(Ht(l.size,64),yield u.subarray(r,a),yield l,$()):l[Symbol.asyncIterator]?(u[a++]=159,yield u.subarray(r,a),yield l,$(),u[a++]=255):A(l);R&&a>r?yield u.subarray(r,a):a-r>D&&(yield u.subarray(r,a),$())}function*_(l,I,R){let O=a-r;try{A(l),a-r>D&&(yield u.subarray(r,a),$())}catch(m){if(m.iteratorNotHandled)I[R]={},a=r+O,yield*Z.call(this,l,I[R]);else throw m}}function $(){D=q,c.encode(null,ft)}function ve(l,I,R){return I&&I.chunkThreshold?D=q=I.chunkThreshold:D=100,l&&typeof l=="object"?(c.encode(null,ft),R(l,c.iterateProperties||(c.iterateProperties={}),!0)):[c.encode(l)]}async function*gt(l,I){for(let R of Z(l,I,!0)){let O=R.constructor;if(O===$t||O===Uint8Array)yield R;else if(ct(R)){let m=R.stream().getReader(),N;for(;!(N=await m.read()).done;)yield N.value}else if(R[Symbol.asyncIterator])for await(let m of R)$(),m?yield*gt(m,I.async||(I.async={})):yield c.encode(m);else yield R}}}useBuffer(e){u=e,B=new DataView(u.buffer,u.byteOffset,u.byteLength),a=0}clearSharedData(){this.structures&&(this.structures=[]),this.sharedValues&&(this.sharedValues=void 0)}updateSharedData(){let e=this.sharedVersion||0;this.sharedVersion=e+1;let r=this.structures.slice(0),n=new Zt(r,this.sharedValues,this.sharedVersion),i=this.saveShared(n,s=>(s&&s.version||0)==e);return i===!1?(n=this.getShared()||{},this.structures=n.structures||[],this.sharedValues=n.packedValues,this.sharedVersion=n.version,this.structures.nextId=this.structures.length):r.forEach((s,o)=>this.structures[o]=s),i}}function Ht(t,e){t<24?u[a++]=e|t:t<256?(u[a++]=e|24,u[a++]=t):t<65536?(u[a++]=e|25,u[a++]=t>>8,u[a++]=t&255):(u[a++]=e|26,B.setUint32(a,t),a+=4)}class Zt{constructor(e,r,n){this.structures=e,this.packedValues=r,this.version=n}}function ne(t){t<24?u[a++]=128|t:t<256?(u[a++]=152,u[a++]=t):t<65536?(u[a++]=153,u[a++]=t>>8,u[a++]=t&255):(u[a++]=154,B.setUint32(a,t),a+=4)}const Yr=typeof Blob>"u"?function(){}:Blob;function ct(t){if(t instanceof Yr)return!0;let e=t[Symbol.toStringTag];return e==="Blob"||e==="File"}function Be(t,e){switch(typeof t){case"string":if(t.length>3){if(e.objectMap[t]>-1||e.values.length>=e.maxValues)return;let n=e.get(t);if(n)++n.count==2&&e.values.push(t);else if(e.set(t,{count:1}),e.samplingPackedValues){let i=e.samplingPackedValues.get(t);i?i.count++:e.samplingPackedValues.set(t,{count:1})}}break;case"object":if(t)if(t instanceof Array)for(let n=0,i=t.length;n<i;n++)Be(t[n],e);else{let n=!e.encoder.useRecords;for(var r in t)t.hasOwnProperty(r)&&(n&&Be(r,e),Be(t[r],e))}break;case"function":console.log(t)}}const Qr=new Uint8Array(new Uint16Array([1]).buffer)[0]==1;Vt=[Date,Set,Error,RegExp,he,ArrayBuffer,Uint8Array,Uint8ClampedArray,Uint16Array,Uint32Array,typeof BigUint64Array>"u"?function(){}:BigUint64Array,Int8Array,Int16Array,Int32Array,typeof BigInt64Array>"u"?function(){}:BigInt64Array,Float32Array,Float64Array,Zt],st=[{tag:1,encode(t,e){let r=t.getTime()/1e3;(this.useTimestamp32||t.getMilliseconds()===0)&&r>=0&&r<4294967296?(u[a++]=26,B.setUint32(a,r),a+=4):(u[a++]=251,B.setFloat64(a,r),a+=8)}},{tag:258,encode(t,e){let r=Array.from(t);e(r)}},{tag:27,encode(t,e){e([t.name,t.message])}},{tag:27,encode(t,e){e(["RegExp",t.source,t.flags])}},{getTag(t){return t.tag},encode(t,e){e(t.value)}},{encode(t,e,r){lt(t,r)}},{getTag(t){if(t.constructor===Uint8Array&&(this.tagUint8Array||Pe&&this.tagUint8Array!==!1))return 64},encode(t,e,r){lt(t,r)}},ie(68,1),ie(69,2),ie(70,4),ie(71,8),ie(72,1),ie(77,2),ie(78,4),ie(79,8),ie(85,4),ie(86,8),{encode(t,e){let r=t.packedValues||[],n=t.structures||[];if(r.values.length>0){u[a++]=216,u[a++]=51,ne(4);let i=r.values;e(i),ne(0),ne(0),packedObjectMap=Object.create(sharedPackedObjectMap||null);for(let s=0,o=i.length;s<o;s++)packedObjectMap[i[s]]=s}if(n){B.setUint32(a,3655335424),a+=3;let i=n.slice(0);i.unshift(57344),i.push(new he(t.version,1399353956)),e(i)}else e(new he(t.version,1399353956))}}];function ie(t,e){return!Qr&&e>1&&(t-=4),{tag:t,encode:function(n,i){let s=n.byteLength,o=n.byteOffset||0,d=n.buffer||n;i(Pe?je.from(d,o,s):new Uint8Array(d,o,s))}}}function lt(t,e){let r=t.byteLength;r<24?u[a++]=64+r:r<256?(u[a++]=88,u[a++]=r):r<65536?(u[a++]=89,u[a++]=r>>8,u[a++]=r&255):(u[a++]=90,B.setUint32(a,r),a+=4),a+r>=u.length&&e(a+r),u.set(t.buffer?t:new Uint8Array(t),a),a+=r}function en(t,e){let r,n=e.length*2,i=t.length-n;e.sort((s,o)=>s.offset>o.offset?1:-1);for(let s=0;s<e.length;s++){let o=e[s];o.id=s;for(let d of o.references)t[d++]=s>>8,t[d]=s&255}for(;r=e.pop();){let s=r.offset;t.copyWithin(s+n,s,i),n-=2;let o=s+n;t[o++]=216,t[o++]=28,i=s}return t}function Xt(t,e){B.setUint32(G.position+t,a-G.position-t+1);let r=G;G=null,e(r[0]),e(r[1])}let ut=new Xr({useRecords:!1});const tn=ut.encode;ut.encodeAsIterable,ut.encodeAsAsyncIterable;const Yt=512,rn=1024,ft=2048;function Qt(t){return!!t&&typeof t=="object"&&"jsonrpc"in t}class qe{closed=!1;[j];#e;constructor(e,{signal:r}={}){this[j]=new Cr(e),this.#e=r,this.#e?.addEventListener("abort",this.#t)}close(e={}){this.closed||(this.closed=!0,this.handleClose(e))}handleClose(e){this.#e?.removeEventListener("abort",this.#t),this[j].dispatchClose(e)}#t=()=>{this.close({code:1e3,reason:String(this.#e?.reason)})}}const nn=Se("appetize.io:transport:ws-ping"),sn=3e4;function on(t){let e=!0;const r=()=>{e=!0};t.on("pong",r);const n=setInterval(()=>{if(!e){clearInterval(n),nn("liveness ping went unanswered, terminating"),t.terminate();return}t.readyState===t.OPEN&&(e=!1,t.ping())},sn);return{destroy(){clearInterval(n),t.off("pong",r)},pong:r}}const ye=Se("appetize.io:trace:transport:websocket");class an extends qe{constructor(e,{signal:r}={}){super(async i=>{this.#i.send(tn(i))},{signal:r}),this.wsOrUrl=e,typeof e=="string"?(this.#i=new WebSocket(e),this.#i.binaryType="arraybuffer"):this.#i=e;const n=this.#i;if(n instanceof WebSocket?(n.addEventListener("open",this.#l),n.addEventListener("message",this.#c),n.addEventListener("error",this.#s),n.addEventListener("close",this.#a),this.#e.push(()=>{n.removeEventListener("open",this.#l),n.removeEventListener("message",this.#c),n.removeEventListener("error",this.#s),n.removeEventListener("close",this.#a)})):(n.addEventListener("open",this.#l),n.addEventListener("message",this.#c),n.addEventListener("error",this.#s),n.addEventListener("close",this.#a),this.#e.push(()=>{n.removeEventListener("open",this.#l),n.removeEventListener("message",this.#c),n.removeEventListener("error",this.#s),n.removeEventListener("close",this.#a)})),this.send=n.send.bind(n),"ping"in n){const{destroy:i,pong:s}=on(n);this.#n=s,this.#e.push(i)}}wsOrUrl;onclose;onerror;onmessage;onopen;send;get bufferedAmount(){return this.#i.bufferedAmount}get readyState(){return this.#i.readyState}#e=[];#t=!1;#r=!1;#n;#i;close({destroyWs:e=!1,...r}={}){this.closed||(this.#t=e,super.close(r))}handleClose(e){ye("close()");for(const r of this.#e.splice(0))r();if((typeof this.wsOrUrl=="string"||this.#t)&&(this.#i.close(e.code,e.reason),"terminate"in this.#i)){const r=this.#i;setTimeout(()=>{r.terminate()},100)}this.#o(),super.handleClose(e)}#o(e){this.#r||(this.#r=!0,this.onclose?.(e))}#a=e=>{ye("handleWebSocketClose()",e);try{this.#o(e)}finally{this.close()}};#s=e=>{ye("handleWebSocketError()",e),this.onerror?.(e)};#c=async e=>{ye("handleWebSocketMessage()",e),this.#n?.();const r=this.#u(e);if(!r){ye("handleWebSocketMessage() -> legacy"),this.onmessage?.(e);return}ye("handleWebSocketMessage() -> jsonrpc",r),this[j].dispatchMessage(r)};#l=e=>{ye("handleWebSocketOpen()",e),this.onopen?.(e)};#u(e){try{const r=Kt(new Uint8Array(e.data));return Qt(r)?r:null}catch{return null}}}function er(t,e,{leftEffects:r=()=>({}),notifiesLeft:n,notifiesRight:i,rightEffects:s=()=>({})}={}){const o=We(t,{}),d=We(e,{}),c=[()=>{o.unsub(),d.unsub()}],p=()=>{for(const S of c)try{S()}catch{}},w=d.rpc.client,y=o.rpc.client;c.push(t[j].addEventListener("close",()=>{p()},{once:!0}),e[j].addEventListener("close",()=>{p()},{once:!0}));const v=r(w,y);for(const S in v){const g=v[S];g&&o.rpc.addMethod(S,g)}const f=s(y,w);for(const S in f){const g=f[S];g&&d.rpc.addMethod(S,g)}return tr(o.rpc,d.rpc,{notifies:n}),tr(d.rpc,o.rpc,{notifies:i}),p}function tr(t,e,{notifies:r}={}){t.applyServerMiddleware(async(n,i)=>{const s=r?.();if(s){const{id:d,...c}=i;s[j].send(c)}if(t.hasMethod(i.method))return await n(i);if(!i.id)return e.notify(i.method,i.params),null;const o=await e.request(i.method,i.params);return{id:i.id,jsonrpc:_e.JSONRPC,result:o}})}function le(t,...e){t.notify(e[0],e[1],e[2])}function dt(){const t=new qe(async r=>{e[j].dispatchMessage(r)}),e=new qe(async r=>{t[j].dispatchMessage(r)});return t[j].addEventListener("close",()=>{e.close()},{once:!0}),e[j].addEventListener("close",()=>{t.close()},{once:!0}),[t,e]}function rr(t,e){const r=[],n=()=>{for(const i of r)i()};r.push(t[j].addEventListener("message",i=>e[j].send(i.detail))),r.push(t[j].addEventListener("close",n,{once:!0})),r.push(e[j].addEventListener("message",i=>t[j].send(i.detail))),r.push(e[j].addEventListener("close",n,{once:!0}))}const we=Se("appetize.io:trace:transport:iframe");class nr extends qe{onmessage;#e;#t;constructor(e,{origin:r="*",signal:n}={}){super(async i=>{e.postMessage(i,this.#e)},{signal:n}),this.#t=e,this.#e=r,window.addEventListener("message",this.#r)}postMessage(e,r,n){we("postMessage(legacy)",{message:e,targetOrigin:r,transfer:n}),this.#t.postMessage(e,r??this.#e,n)}handleClose(e){we("close()"),window.removeEventListener("message",this.#r),super.handleClose(e)}#r=async e=>{if(we("handleMessage()",e),e.source!==this.#t||(we("handleMessage() -> source ok"),this.#e!=="*"&&e.origin!==this.#e))return;we("handleMessage() -> origin ok");const r=e.data;if(!Qt(r)){we("handleMessage() -> legacy"),this.onmessage?.(e);return}we("handleMessage() -> jsonrpc"),this[j].dispatchMessage(r)}}function ht(){let t,e;return{promise:new Promise((n,i)=>{e=n,t=i}),reject:t,resolve:e}}const cn=2*1024*1024,ir=Se("appetize:client:acked-writable-stream");class ln{unacked=0;#e;#t;#r;#n;#i=[];#o;constructor(e){this.#r=e,this.#o=e.window??cn}abort(e){this.#s(e),this.#r.onAbort?.(e)}async close(){await this.#c(()=>this.unacked===0),this.#r.onClose?.()}fail(e){this.#s(e)&&this.#r.onError?.(e)}start(e){this.#e=e}write(e){const r=e.byteLength;return this.unacked+=r,this.#r.send(e).then(()=>{this.unacked-=r,this.#n&&(this.#n.acked+=r),this.#a()},n=>{this.fail(n)}),this.unacked>=this.#o&&!this.#n&&(this.#n={acked:0,at:performance.now()},ir("window full: %d bytes unacked, writes stalled",this.unacked)),this.#c(()=>this.unacked<this.#o)}#a(){if(this.#n&&this.unacked<=this.#o/2){const e=performance.now()-this.#n.at;ir("pressure relieved after %dms: %d bytes acked, %s MB/s",Math.round(e),this.#n.acked,(this.#n.acked/Math.max(e,1)/1e3).toFixed(2)),this.#n=void 0}this.#i=this.#i.filter(e=>e.until()?(e.resolve(void 0),!1):!0)}#s(e){if(this.#t)return!1;this.#t={reason:e},this.#e.error(e);const r=this.#i;this.#i=[];for(const n of r)n.reject(e);return!0}#c(e){if(e())return Promise.resolve();const r={...ht(),until:e};return this.#i.push(r),r.promise}}class un extends WritableStream{get unacked(){return this.#e.unacked}#e;constructor(e){const r=new ln(e);super({abort:n=>{r.abort(n)},close:()=>r.close(),start:n=>{r.start(n)},write:n=>r.write(n)}),this.#e=r}fail(e){this.#e.fail(e)}}const fn=1024*1024;class dn{#e;#t=!1;#r;#n;constructor(e){this.#r=e}cancel(e){this.#i(),this.#r?.(e)}close(){this.#i()&&this.#e.close()}error(e){this.#i()&&this.#e.error(e)}pull(){const e=this.#n;this.#n=void 0,e?.resolve(void 0)}async push(e){if(this.#t)return;this.#n??=ht();const{promise:r}=this.#n;this.#e.enqueue(e),await r}start(e){this.#e=e}#i(){return this.#t?!1:(this.#t=!0,this.pull(),!0)}}class hn extends ReadableStream{#e;constructor({highWaterMark:e=fn,onCancel:r}={}){const n=new dn(r);super({cancel:i=>{n.cancel(i)},pull:()=>{n.pull()},start:i=>{n.start(i)}},new ByteLengthQueuingStrategy({highWaterMark:e})),this.#e=n}close(){this.#e.close()}error(e){this.#e.error(e)}push(e){return this.#e.push(e)}}class pn{closed;readable;writable;#e=[];#t;#r;#n;#i;#o;#a="starting";constructor(e,{onClose:r,receiveBuffer:n,sendWindow:i,signal:s}){if(this.#o=e,this.#t=ht(),this.closed=this.#t.promise,this.closed.catch(yn),this.#n=new hn({highWaterMark:n,onCancel:()=>{this.#s(void 0)}}),this.readable=this.#n,this.#i=new un({onAbort:()=>{this.#s(void 0)},onClose:()=>{this.#s(void 0)},onError:o=>{this.#s(o)},send:o=>e.request("appetizeio.device.server.debug.adbTunnel.data",{data:o}),window:i}),this.writable=this.#i,s){const o=()=>{this.#s(s.reason)};s.addEventListener("abort",o,{once:!0}),this.#e.push(()=>{s.removeEventListener("abort",o)})}this.#e.push(()=>{r(this)})}close=()=>{this.#s(void 0)};detach(){this.#s(void 0,{notifyServer:!1})}async handleData(e){this.#a==="open"&&await this.#n.push(e)}handleStopped({error:e}){this.#a==="open"&&this.#s(e?new Error(e):void 0)}async start(){try{await this.#o.request("appetizeio.device.server.debug.adbTunnel.start",void 0)}catch(e){throw this.#s(e),e}if(this.#a==="closed")throw this.#r?this.#r:new Error("The adb tunnel closed before it started");this.#a="open"}async[Symbol.asyncDispose](){this.close();try{await this.closed}catch{}}#s(e,{notifyServer:r=!0}={}){if(this.#a!=="closed"){this.#a="closed",this.#r=e,r&&le(this.#o,"appetizeio.device.server.debug.adbTunnel.stop",void 0),e?(this.#n.error(e),this.#i.fail(e)):(this.#n.close(),this.#i.fail(new Error("The adb tunnel has stopped")));for(const n of this.#e)n();e?this.#t.reject(e):this.#t.resolve(void 0)}}}function yn(){}class wn{readable;ready;#e=[];#t=!1;#r;#n;#i;constructor({label:e,onClose:r,signal:n}){this.#n=e,this.ready=new Promise((s,o)=>{this.#i={reject:o,resolve:s}});let i;if(this.readable=new ReadableStream({cancel:()=>{this.#a()},start:s=>{i=s}}),!i)throw new Error("ReadableStream controller was not initialized");if(this.#r=i,n){const s=()=>{this.fail(n.reason)};n.addEventListener("abort",s,{once:!0}),this.#e.push(()=>{n.removeEventListener("abort",s)})}this.#e.push(()=>{r(this)})}close=()=>{this.#o()};fail(e){this.#o(e)}handleItem(e){this.#r.enqueue(e)}markReady(){if(!this.#i)return;const{resolve:e}=this.#i;this.#i=void 0,e(this)}async*[Symbol.asyncIterator](){const e=this.readable.getReader();try{for(let r=await e.read();!r.done;r=await e.read())yield r.value}finally{await e.cancel()}}#o(e){this.#t||(this.#r.close(),this.#a(e))}#a(e){this.#t=!0;for(const r of this.#e)r();this.#i?.reject(e??new Error(`${this.#n} closed before it started`)),this.#i=void 0}}class vn{get subscribers(){return this.#r}#e;#t;#r=new Set;constructor(e){this.#e=e}close(){this.#t=void 0;for(const e of[...this.#r])e.close();this.#r.clear()}add(e){this.#r.add(e)}ensureStarted(){return this.#t||(this.#t=(async()=>{try{return await this.#e.start()}catch(e){throw this.#t=void 0,e}})()),this.#t}release(e){this.#r.delete(e),!(this.#r.size>0||!this.#t)&&(this.#t=void 0,this.#e.stop())}}class sr extends vn{#e;constructor(e){super({start:e.start,stop:e.stop}),this.#e=e.label}async createStream({signal:e}={}){e?.throwIfAborted();const r=new wn({label:this.#e,onClose:n=>{this.release(n)},signal:e});this.add(r);try{await this.ensureStarted(),r.markReady()}catch(n){r.fail(n)}return await r.ready}handleNotification(e){for(const r of this.subscribers)r.handleItem(e)}}class gn{#e;#t;#r;#n;constructor(e){this.#n=e,this.#t=new sr({label:"Log stream",start:()=>e.request("appetizeio.device.server.debug.log.start"),stop:()=>{le(e,"appetizeio.device.server.debug.log.stop",void 0)}}),this.#r=new sr({label:"Proxy intercept stream",start:()=>e.request("appetizeio.device.server.debug.proxyIntercept.start"),stop:()=>{le(e,"appetizeio.device.server.debug.proxyIntercept.stop",void 0)}})}close(){this.#e?.detach(),this.#t.close(),this.#r.close()}async createAdbTunnel({signal:e}={}){e?.throwIfAborted(),this.#e?.close();const r=new pn(this.#n,{onClose:()=>{this.#e=void 0},signal:e});return this.#e=r,await r.start(),r}async createLogStream(e){return await this.#t.createStream(e)}async createProxyInterceptStream(e){return await this.#r.createStream(e)}async handleAdbTunnelData({data:e}){await this.#e?.handleData(e)}handleAdbTunnelStopped(e){this.#e?.handleStopped(e)}handleLogEntry(e){this.#t.handleNotification(e)}handleProxyInterceptEvent(e){this.#r.handleNotification(e)}}function pt(t){return{...bn(t),index:t.index,within:t.within?pt(t.within):void 0}}function bn(t){switch(t.by){case"testId":return{by:"testId",testId:t.testId};case"text":return{by:"text",text:mn(t.text)}}}function mn(t){return typeof t=="string"?{kind:"exact",value:t}:{flags:t.flags,kind:"regex",source:t.source}}const Sn=400,or=["byTestId","byText","duration","index","x","y"],Cn=new Set(or),En=/^-?(?:\d+(?:\.\d*)?|\.\d+)$/u,Rn=/^[a-z]$/u,yt=/^\s$/u;class K extends SyntaxError{constructor(e,r,n){super(`${e} at position ${String(r)}`,{cause:n})}}class On{#e=0;#t;constructor(e){this.#t=e}parse(){const e=[];for(;this.#e<this.#t.length;){const r=this.#s();if(yt.test(r))this.#e++;else if(r===">"){if(this.#t.charAt(this.#e+1)===">")throw new K('Force press ">>" is not supported',this.#e);this.#e++,e.push({kind:"down"})}else if(r==="/")this.#e++,e.push({kind:"up"});else if(r==="{")e.push(this.#o());else{const[n]=this.#t.slice(this.#e,this.#e+2);throw new K(`Unexpected ${JSON.stringify(n)}; write selectors as {...}`,this.#e)}}return e}#r(){const e=this.#e,r=this.#c(n=>n!=="="&&!wt(n));if(this.#s()!=="=")return{kind:"bare",name:r,offset:e};if(r.length===0)throw new K('Expected an attribute name before "="',e);return this.#e++,{kind:"attribute",name:r,offset:e,value:this.#a()}}#n(){const e=this.#e;this.#e++;let r="";for(;;){const n=this.#s();if(this.#e++,n==='"')return r;if(n==="\\"){const i=this.#s();if(i!=='"'&&i!=="\\"&&i!=="")throw new K('Only \\" and \\\\ escapes are supported',this.#e-1);this.#e++,r+=i}else{if(n==="")throw new K("Unclosed string",e);r+=n}}}#i(){const e=this.#e;this.#e++;let r="",n=!1;for(;;){const s=this.#s();if(s==="")throw new K("Unclosed regex",e);if(this.#e++,s==="/"&&!n)break;r+=s,s==="\\"?(r+=this.#s(),this.#e++):s==="["?n=!0:s==="]"&&(n=!1)}const i=this.#c(s=>Rn.test(s));try{return new RegExp(r,i)}catch(s){throw new K(`Invalid regex /${r}/${i}`,e,s)}}#o(){const e=this.#e;this.#e++;let r;const n={offsets:{}};for(let i=0;;i++){this.#l();const s=this.#s();if(s==="")throw new K('Unclosed "{"',e);if(s==="}"){if(this.#e++,i===0)throw new K('Expected a selector or wait in "{}"',e);return r===void 0?In(n,e):{duration:r,kind:"wait"}}const o=this.#r();if(i===0&&o.name==="wait")r=o.kind==="attribute"?ar(o.value,"wait"):Sn;else{if(r!==void 0)throw new K('"wait" takes no other attributes',o.offset);Mn(n,o,i)}}}#a(){const e=this.#e,r=this.#s();let n;if(r==='"')n={kind:"quoted",offset:e,text:this.#n()};else if(r==="/")n={kind:"regex",offset:e,regex:this.#i()};else{const i=this.#c(s=>!wt(s));if(i.length===0)throw new K('Expected a value after "="',e);return{kind:"raw",offset:e,text:i}}if(!wt(this.#s()))throw new K('Expected a space or "}" after the value',this.#e);return n}#s(){return this.#t.charAt(this.#e)}#c(e){const r=this.#e;for(;this.#e<this.#t.length&&e(this.#s());)this.#e++;return this.#t.slice(r,this.#e)}#l(){this.#c(e=>yt.test(e))}}function An(t){return new On(t).parse()}function Mn(t,e,r){const{name:n,offset:i}=e;if(e.kind==="attribute"){vt(t,n,i,e.value);return}if(!n.includes(","))throw new K(`Expected key=value, got ${JSON.stringify(n)}`,i);if(r>0)throw new K("Write the x,y position first",i);const[s,o,...d]=n.split(",");if(d.length>0)throw new K("Expected a screen position as x,y",i);const c=i+s.length+1;vt(t,"x",i,{kind:"raw",offset:i,text:s}),vt(t,"y",c,{kind:"raw",offset:c,text:o})}function Pn(t){return Cn.has(t)}function wt(t){return t===""||t==="}"||yt.test(t)}function vt(t,e,r,n){if(!Pn(e))throw new K(`Unknown attribute ${JSON.stringify(e)}; expected one of ${or.join(", ")}`,r);if(t.offsets[e]!==void 0)throw new K(`Duplicate attribute ${JSON.stringify(e)}`,r);switch(t.offsets[e]=r,e){case"byTestId":case"byText":if(t.byText!==void 0||t.byTestId!==void 0)throw new K("Only one of byText and byTestId may be given",r);e==="byText"?t.byText=xn(n):t.byTestId=Nn(n);return;default:t[e]=ar(n,e)}}function In(t,e){return{duration:t.duration,kind:"move",to:kn(t,e)}}function ar(t,e){if(t.kind!=="raw"||!En.test(t.text))throw new K(`"${e}" takes a number`,t.offset);return Number(t.text)}function kn(t,e){const{byTestId:r,byText:n,index:i,offsets:s,x:o,y:d}=t;if(n!==void 0)return{by:"text",index:i,text:n,x:o,y:d};if(r!==void 0)return{by:"testId",index:i,testId:r,x:o,y:d};if(s.index!==void 0)throw new K('"index" needs byText or byTestId',s.index);if(o===void 0||d===void 0)throw new K("A screen position needs x and y",e);return{by:"position",x:o,y:d}}function Nn(t){if(t.kind==="regex")throw new K('"byTestId" takes a string',t.offset);return t.text}function xn(t){return t.kind==="regex"?t.regex:t.text}function Ie(t){return t.by==="position"?{by:"position",x:t.x,y:t.y}:{...pt(t),x:t.x,y:t.y}}function _n(t){return t.map(e=>e.kind==="move"?{duration:e.duration,kind:"move",to:Ie(e.to)}:e)}function Fn(t){return{press:e=>{le(t,"appetizeio.device.server.keyboard.press",{key:e})}}}function Tn({onRequest:t,parent:e,proxyInlet:r,signal:n}){const i=new nr(e,{signal:n}),s=[()=>{i.close()}];return rr(i,r),t&&s.push(Fe(i,o=>{t(o,{source:"parent"})})),{cleanup:()=>{for(const o of s)o()},notifies:()=>e===globalThis.window?void 0:i}}const Ln="@appetizeio/rpc:playwrightAdapter",ze=Symbol.for(Ln);function Un(t){window[ze]&&console.warn("playwright exposed more than once, overwriting previous adapter");const e={send(r){t[j].send(r)},subscribe(r){return t[j].addEventListener("message",n=>{r(n.detail)})}};return window[ze]=e,()=>{window[ze]===e&&delete window[ze]}}function Jn({onRequest:t,proxyInlet:e}){const[r,n]=dt(),s=[Un(n),()=>{r.close()}];return rr(r,e),t&&s.push(Fe(r,o=>{t(o,{source:"parent"})})),{cleanup:()=>{for(const o of s)o()},notifies:()=>r}}function Dn(t){return"to"in t?{from:Ie(t.from),kind:"path",to:Ie(t.to)}:{direction:t.direction,distance:t.distance,from:t.from?Ie(t.from):void 0,kind:"direction"}}function jn(t){return{down:(e,r)=>{le(t,"appetizeio.device.server.touch.down",{x:e,y:r})},move:(e,r)=>{le(t,"appetizeio.device.server.touch.move",{x:e,y:r})},up:(e,r)=>{le(t,"appetizeio.device.server.touch.up",{x:e,y:r})}}}const Bn=new Set(Ge),qn=/^(?<key>[A-Za-z]+)>(?<repeat>\d+)\/$/u,zn=/(\{\{|\{[^{}]*\})/u;function Kn(t){const e=[];let r="";function n(){r.length>0&&(e.push({kind:"text",text:r}),r="")}for(const[i,s]of t.split(zn).entries())if(i%2===0){if(s.includes("{"))throw new Error(`Unclosed "{" in ${JSON.stringify(t)}`);r+=s}else s==="{{"?r+="{":(n(),e.push($n(s.slice(1,-1))));return n(),e}function Vn(t,e){if(!Bn.has(t))throw e.endsWith(">")?new Error(`Holding a key is not supported: {${e}}`):e.startsWith("/")?new Error(`Releasing a key is not supported: {${e}}`):new Error(`{${e}} does not name a supported key. Supported: ${Ge.join(", ")}. Type characters as text, and escape a literal "{" as "{{".`)}function $n(t){const e=qn.exec(t)?.groups,r=e?.key??t;if(Vn(r,t),!e)return{key:r,kind:"press"};const n=Number(e.repeat);if(n<1)throw new Error(`Repeat for {${t}} must be at least 1`);return{key:r,kind:"press",repeat:n}}const Wn=Symbol("@appetizeio/client:v1Compat");function cr(t){return t?.[Wn]}class Gn{readable;ready;get dimensions(){return this.#n}#e=[];#t=!1;#r;#n;#i;#o;constructor({onClose:e,requestKeyFrame:r,signal:n}){this.#i=r,this.ready=new Promise((s,o)=>{this.#o={reject:o,resolve:s}});let i;if(this.readable=new ReadableStream({cancel:()=>{this.#s()},start:s=>{i=s}}),!i)throw new Error("ReadableStream controller was not initialized");if(this.#r=i,n){const s=()=>{this.fail(n.reason)};n.addEventListener("abort",s,{once:!0}),this.#e.push(()=>{n.removeEventListener("abort",s)})}this.#e.push(()=>{e(this)})}close=()=>{this.#a()};fail(e){this.#a(e)}handleChunk(e){if(this.#o){if(e.type!=="key")return;const{resolve:r}=this.#o;this.#o=void 0,this.#n={height:e.height,width:e.width},r(this)}else e.type==="key"&&(this.#n={height:e.height,width:e.width});this.#r.enqueue(e)}requestKeyFrame=()=>{this.#t||this.#i()};async*[Symbol.asyncIterator](){const e=this.readable.getReader();try{for(let r=await e.read();!r.done;r=await e.read())yield r.value}finally{await e.cancel()}}#a(e){this.#t||(this.#r.close(),this.#s(e))}#s(e){this.#t=!0;for(const r of this.#e)r();this.#o?.reject(e??new Error("Video stream closed before the first key chunk")),this.#o=void 0}}class Hn{#e=!1;#t;#r;#n=new Set;constructor(e){this.#t=e}close(){this.#r=void 0;for(const e of[...this.#n])e.close()}async createStream({signal:e}={}){e?.throwIfAborted();const r=new Gn({onClose:n=>{this.#o(n)},requestKeyFrame:()=>{this.#a()},signal:e});this.#n.add(r);try{await this.#i()}catch(n){r.fail(n)}return await r.ready}handleChunk(e){e.type==="key"&&(this.#e=!1);for(const r of this.#n)r.handleChunk(e)}#i(){return this.#r?(this.#a(),this.#r):(this.#e=!0,this.#r=(async()=>{try{await this.#t.request("appetizeio.device.server.video.start")}catch(e){throw this.#r=void 0,e}})(),this.#r)}#o(e){this.#n.delete(e),!(this.#n.size>0||!this.#r)&&(this.#r=void 0,le(this.#t,"appetizeio.device.server.video.stop",void 0))}#a(){this.#e||(this.#e=!0,le(this.#t,"appetizeio.device.server.video.requestKeyFrame",void 0))}}class Zn{debug;keyboard;touch;video;#e;#t=[];#r;constructor(e,r={}){const n=cr(r)??{},{baseUrl:i,onClose:s,signal:o}=r;this.#e=i?Xn(i):void 0;const{onRequest:d,parent:c,proxyRequest:p}=n,w=Yn(d);o?.addEventListener("abort",this.close);const[y,v]=dt(),[f,S]=dt();this.#t.push(()=>{y.close(),v.close(),f.close(),S.close()}),this.#t.push(er(S,e,{leftEffects:p}));const g=c==="playwright"?Jn({onRequest:w,proxyInlet:f}):c?Tn({onRequest:w,parent:c,proxyInlet:f,signal:o}):void 0;g&&this.#t.push(g.cleanup),this.#t.push(er(v,f,{notifiesLeft:g?.notifies}));const{client:C,unsub:b}=Or(y,{"appetizeio.device.client.debug.adbTunnel.data":k=>E.handleAdbTunnelData(k),"appetizeio.device.client.debug.adbTunnel.stopped":async k=>{E.handleAdbTunnelStopped(k)},"appetizeio.device.client.debug.log.entry":async k=>{E.handleLogEntry(k)},"appetizeio.device.client.debug.proxyIntercept.event":async k=>{E.handleProxyInterceptEvent(k)},"appetizeio.device.client.video.chunk":async k=>{A.handleChunk(k)}});this.#r=C,this.#t.push(b);const E=new gn(this.#r);this.#t.push(()=>{E.close()});const A=new Hn(this.#r);this.#t.push(()=>{A.close()}),this.debug=E,this.keyboard=Fn(this.#r),this.touch=jn(this.#r),this.video=A,w&&(this.#t.push(Fe(v,k=>{w(k,{source:"self"})})),e instanceof nr&&this.#t.push(Fe(e,k=>{w(k,{source:"iframe"})}))),this.#t.push(()=>s?.())}async clearKeychain(){await this.#r.request("appetizeio.device.server.clearKeychain")}close=()=>{for(const e of this.#t)try{e()}catch(r){console.error("Device cleanup error:",r)}};async fold(e){await this.#r.request("appetizeio.device.server.fold",{hinge:e})}async gesture(e,r){await this.#r.request("appetizeio.device.server.gesture",{options:r,steps:_n(typeof e=="string"?An(e):e)})}async inspect(e,r){return await this.#r.request("appetizeio.device.server.inspect",{options:r,selector:e?pt(e):void 0})}async open(e){new URL(e),await this.#r.request("appetizeio.device.server.open",{url:e})}async press(e){await this.#r.request("appetizeio.device.server.press",{action:e})}async rotate(e){await this.#r.request("appetizeio.device.server.rotate",{orientation:e})}async screenshot(){const e=await this.#r.request("appetizeio.device.server.screenshot"),r=this.#e?new URL(e.url,this.#e).href:e.url,n=await fetch(r);if(!n.ok)throw new Error(`Screenshot download failed: ${String(n.status)} ${n.statusText}`);const i=n.headers.get("content-type")??"application/octet-stream";return{data:new Uint8Array(await n.arrayBuffer()),mimeType:i}}async swipe(e,r){await this.#r.request("appetizeio.device.server.swipe",{gesture:Dn(e),options:r})}async tap(e,r){await this.#r.request("appetizeio.device.server.tap",{options:r,selector:Ie(e)})}async type(e,r){await this.#r.request("appetizeio.device.server.type",{options:r,steps:Kn(e)})}}function Xn(t){const e=new URL(t);return e.protocol==="ws:"?e.protocol="http:":e.protocol==="wss:"&&(e.protocol="https:"),e.href}const Yn=t=>{if(t)return(e,r)=>{e.method.startsWith("appetizeio.device.server.")&&t(e,r)}};function Qn(t){return typeof t=="object"&&t!==null}function ei(t){try{const e=Kt(new Uint8Array(t.data));if(Qn(e)&&typeof e.name=="string")return{name:e.name,payload:"payload"in e?e.payload:void 0}}catch{}}async function ti(t,e={}){const r=e.baseUrl??(typeof t=="string"?new URL(t).origin:void 0),n=typeof t=="string"?new an(t,{signal:e.signal}):t,i=new Zn(n,{...e,baseUrl:r});return typeof t=="string"&&await ri(n,i,e),i}function ri(t,e,r){const n=cr(r)?.onLegacyMessage;return new Promise((i,s)=>{t.onopen=()=>{i()},t.onclose=()=>{e.close(),r.signal?.aborted?s(r.signal.reason):s(new Error("The websocket was closed before the device connection was established"))},t.onerror=s,t.onmessage=o=>{const d=ei(o);d&&n?.(d)}})}async function ni(t,e){const r=t.querySelector("canvas");if(!(r instanceof HTMLCanvasElement))throw new Error("Canvas unavailable");const n=e.protocol==="https:"?"wss:":"ws:",i=await ti(`${n}//${e.host}/ws`);Nr(i,r),xr(i,r),await _r(i,r)}await ni(document,location);
1
+ <!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><link rel="icon" href="data:,"><title>Appetize device</title><style>body,html{height:100%;margin:0;background:#111318}body{display:grid;place-items:center}canvas{max-width:100vw;max-height:100vh;background:#000;touch-action:none}</style></head><body><canvas aria-label="Device screen" tabindex="0"></canvas><script type="module">function dr(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var xe={exports:{}},We,Ct;function hr(){if(Ct)return We;Ct=1;var t=1e3,e=t*60,r=e*60,n=r*24,i=n*7,s=n*365.25;We=function(w,y){y=y||{};var v=typeof w;if(v==="string"&&w.length>0)return o(w);if(v==="number"&&isFinite(w))return y.long?c(w):h(w);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(w))};function o(w){if(w=String(w),!(w.length>100)){var y=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(w);if(y){var v=parseFloat(y[1]),f=(y[2]||"ms").toLowerCase();switch(f){case"years":case"year":case"yrs":case"yr":case"y":return v*s;case"weeks":case"week":case"w":return v*i;case"days":case"day":case"d":return v*n;case"hours":case"hour":case"hrs":case"hr":case"h":return v*r;case"minutes":case"minute":case"mins":case"min":case"m":return v*e;case"seconds":case"second":case"secs":case"sec":case"s":return v*t;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return v;default:return}}}}function h(w){var y=Math.abs(w);return y>=n?Math.round(w/n)+"d":y>=r?Math.round(w/r)+"h":y>=e?Math.round(w/e)+"m":y>=t?Math.round(w/t)+"s":w+"ms"}function c(w){var y=Math.abs(w);return y>=n?p(w,y,n,"day"):y>=r?p(w,y,r,"hour"):y>=e?p(w,y,e,"minute"):y>=t?p(w,y,t,"second"):w+" ms"}function p(w,y,v,f){var S=y>=v*1.5;return Math.round(w/v)+" "+f+(S?"s":"")}return We}var Ge,Et;function pr(){if(Et)return Ge;Et=1;function t(e){n.debug=n,n.default=n,n.coerce=p,n.disable=h,n.enable=s,n.enabled=c,n.humanize=hr(),n.destroy=w,Object.keys(e).forEach(y=>{n[y]=e[y]}),n.names=[],n.skips=[],n.formatters={};function r(y){let v=0;for(let f=0;f<y.length;f++)v=(v<<5)-v+y.charCodeAt(f),v|=0;return n.colors[Math.abs(v)%n.colors.length]}n.selectColor=r;function n(y){let v,f=null,S,g;function C(...b){if(!C.enabled)return;const E=C,A=Number(new Date),k=A-(v||A);E.diff=k,E.prev=v,E.curr=A,v=A,b[0]=n.coerce(b[0]),typeof b[0]!="string"&&b.unshift("%O");let M=0;b[0]=b[0].replace(/%([a-zA-Z%])/g,(z,X)=>{if(z==="%%")return"%";M++;const _=n.formatters[X];if(typeof _=="function"){const G=b[M];z=_.call(E,G),b.splice(M,1),M--}return z}),n.formatArgs.call(E,b),(E.log||n.log).apply(E,b)}return C.namespace=y,C.useColors=n.useColors(),C.color=n.selectColor(y),C.extend=i,C.destroy=n.destroy,Object.defineProperty(C,"enabled",{enumerable:!0,configurable:!1,get:()=>f!==null?f:(S!==n.namespaces&&(S=n.namespaces,g=n.enabled(y)),g),set:b=>{f=b}}),typeof n.init=="function"&&n.init(C),C}function i(y,v){const f=n(this.namespace+(typeof v>"u"?":":v)+y);return f.log=this.log,f}function s(y){n.save(y),n.namespaces=y,n.names=[],n.skips=[];const v=(typeof y=="string"?y:"").trim().replace(/\s+/g,",").split(",").filter(Boolean);for(const f of v)f[0]==="-"?n.skips.push(f.slice(1)):n.names.push(f)}function o(y,v){let f=0,S=0,g=-1,C=0;for(;f<y.length;)if(S<v.length&&(v[S]===y[f]||v[S]==="*"))v[S]==="*"?(g=S,C=f,S++):(f++,S++);else if(g!==-1)S=g+1,C++,f=C;else return!1;for(;S<v.length&&v[S]==="*";)S++;return S===v.length}function h(){const y=[...n.names,...n.skips.map(v=>"-"+v)].join(",");return n.enable(""),y}function c(y){for(const v of n.skips)if(o(y,v))return!1;for(const v of n.names)if(o(y,v))return!0;return!1}function p(y){return y instanceof Error?y.stack||y.message:y}function w(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return n.enable(n.load()),n}return Ge=t,Ge}var Rt;function yr(){return Rt||(Rt=1,(function(t,e){e.formatArgs=n,e.save=i,e.load=s,e.useColors=r,e.storage=o(),e.destroy=(()=>{let c=!1;return()=>{c||(c=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})(),e.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"];function r(){if(typeof window<"u"&&window.process&&(window.process.type==="renderer"||window.process.__nwjs))return!0;if(typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;let c;return typeof document<"u"&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||typeof window<"u"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<"u"&&navigator.userAgent&&(c=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(c[1],10)>=31||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}function n(c){if(c[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+c[0]+(this.useColors?"%c ":" ")+"+"+t.exports.humanize(this.diff),!this.useColors)return;const p="color: "+this.color;c.splice(1,0,p,"color: inherit");let w=0,y=0;c[0].replace(/%[a-zA-Z%]/g,v=>{v!=="%%"&&(w++,v==="%c"&&(y=w))}),c.splice(y,0,p)}e.log=console.debug||console.log||(()=>{});function i(c){try{c?e.storage.setItem("debug",c):e.storage.removeItem("debug")}catch{}}function s(){let c;try{c=e.storage.getItem("debug")||e.storage.getItem("DEBUG")}catch{}return!c&&typeof process<"u"&&"env"in process&&(c=process.env.DEBUG),c}function o(){try{return localStorage}catch{}}t.exports=pr()(e);const{formatters:h}=t.exports;h.j=function(c){try{return JSON.stringify(c)}catch(p){return"[UnexpectedJSONParseError]: "+p.message}}})(xe,xe.exports)),xe.exports}var wr=yr(),Ee=dr(wr),de={},ae={},Re={},Ot;function Ne(){return Ot||(Ot=1,(function(t){var e=Re&&Re.__extends||(function(){var f=function(S,g){return f=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(C,b){C.__proto__=b}||function(C,b){for(var E in b)Object.prototype.hasOwnProperty.call(b,E)&&(C[E]=b[E])},f(S,g)};return function(S,g){if(typeof g!="function"&&g!==null)throw new TypeError("Class extends value "+String(g)+" is not a constructor or null");f(S,g);function C(){this.constructor=S}S.prototype=g===null?Object.create(g):(C.prototype=g.prototype,new C)}})();Object.defineProperty(t,"__esModule",{value:!0}),t.createJSONRPCNotification=t.createJSONRPCRequest=t.createJSONRPCSuccessResponse=t.createJSONRPCErrorResponse=t.JSONRPCErrorCode=t.JSONRPCErrorException=t.isJSONRPCResponses=t.isJSONRPCResponse=t.isJSONRPCRequests=t.isJSONRPCRequest=t.isJSONRPCID=t.JSONRPC=void 0,t.JSONRPC="2.0";var r=function(f){return typeof f=="string"||typeof f=="number"||f===null};t.isJSONRPCID=r;var n=function(f){return f.jsonrpc===t.JSONRPC&&f.method!==void 0&&f.result===void 0&&f.error===void 0};t.isJSONRPCRequest=n;var i=function(f){return Array.isArray(f)&&f.every(t.isJSONRPCRequest)};t.isJSONRPCRequests=i;var s=function(f){return f.jsonrpc===t.JSONRPC&&f.id!==void 0&&(f.result!==void 0||f.error!==void 0)};t.isJSONRPCResponse=s;var o=function(f){return Array.isArray(f)&&f.every(t.isJSONRPCResponse)};t.isJSONRPCResponses=o;var h=function(f,S,g){var C={code:f,message:S};return g!=null&&(C.data=g),C},c=(function(f){e(S,f);function S(g,C,b){var E=f.call(this,g)||this;return Object.setPrototypeOf(E,S.prototype),E.code=C,E.data=b,E}return S.prototype.toObject=function(){return h(this.code,this.message,this.data)},S})(Error);t.JSONRPCErrorException=c,(function(f){f[f.ParseError=-32700]="ParseError",f[f.InvalidRequest=-32600]="InvalidRequest",f[f.MethodNotFound=-32601]="MethodNotFound",f[f.InvalidParams=-32602]="InvalidParams",f[f.InternalError=-32603]="InternalError"})(t.JSONRPCErrorCode||(t.JSONRPCErrorCode={}));var p=function(f,S,g,C){return{jsonrpc:t.JSONRPC,id:f,error:h(S,g,C)}};t.createJSONRPCErrorResponse=p;var w=function(f,S){return{jsonrpc:t.JSONRPC,id:f,result:S??null}};t.createJSONRPCSuccessResponse=w;var y=function(f,S,g){return{jsonrpc:t.JSONRPC,id:f,method:S,params:g}};t.createJSONRPCRequest=y;var v=function(f,S){return{jsonrpc:t.JSONRPC,method:f,params:S}};t.createJSONRPCNotification=v})(Re)),Re}var Oe={},At;function Mt(){return At||(At=1,Object.defineProperty(Oe,"__esModule",{value:!0}),Oe.DefaultErrorCode=void 0,Oe.DefaultErrorCode=0),Oe}var Pt;function vr(){if(Pt)return ae;Pt=1;var t=ae&&ae.__awaiter||function(o,h,c,p){function w(y){return y instanceof c?y:new c(function(v){v(y)})}return new(c||(c=Promise))(function(y,v){function f(C){try{g(p.next(C))}catch(b){v(b)}}function S(C){try{g(p.throw(C))}catch(b){v(b)}}function g(C){C.done?y(C.value):w(C.value).then(f,S)}g((p=p.apply(o,h||[])).next())})},e=ae&&ae.__generator||function(o,h){var c={label:0,sent:function(){if(y[0]&1)throw y[1];return y[1]},trys:[],ops:[]},p,w,y,v;return v={next:f(0),throw:f(1),return:f(2)},typeof Symbol=="function"&&(v[Symbol.iterator]=function(){return this}),v;function f(g){return function(C){return S([g,C])}}function S(g){if(p)throw new TypeError("Generator is already executing.");for(;v&&(v=0,g[0]&&(c=0)),c;)try{if(p=1,w&&(y=g[0]&2?w.return:g[0]?w.throw||((y=w.return)&&y.call(w),0):w.next)&&!(y=y.call(w,g[1])).done)return y;switch(w=0,y&&(g=[g[0]&2,y.value]),g[0]){case 0:case 1:y=g;break;case 4:return c.label++,{value:g[1],done:!1};case 5:c.label++,w=g[1],g=[0];continue;case 7:g=c.ops.pop(),c.trys.pop();continue;default:if(y=c.trys,!(y=y.length>0&&y[y.length-1])&&(g[0]===6||g[0]===2)){c=0;continue}if(g[0]===3&&(!y||g[1]>y[0]&&g[1]<y[3])){c.label=g[1];break}if(g[0]===6&&c.label<y[1]){c.label=y[1],y=g;break}if(y&&c.label<y[2]){c.label=y[2],c.ops.push(g);break}y[2]&&c.ops.pop(),c.trys.pop();continue}g=h.call(o,c)}catch(C){g=[6,C],w=0}finally{p=y=0}if(g[0]&5)throw g[1];return{value:g[0]?g[1]:void 0,done:!0}}};Object.defineProperty(ae,"__esModule",{value:!0}),ae.JSONRPCClient=void 0;var r=Ne(),n=Mt(),i=(function(){function o(h,c){this._send=h,this.createID=c,this.idToResolveMap=new Map,this.id=0}return o.prototype._createID=function(){return this.createID?this.createID():++this.id},o.prototype.timeout=function(h,c){var p=this;c===void 0&&(c=function(v){return(0,r.createJSONRPCErrorResponse)(v,n.DefaultErrorCode,"Request timeout")});var w=function(v,f){var S=setTimeout(function(){v.forEach(function(g){var C=p.idToResolveMap.get(g);C&&(p.idToResolveMap.delete(g),C(c(g)))})},h);return f().then(function(g){return clearTimeout(S),g},function(g){return clearTimeout(S),Promise.reject(g)})},y=function(v,f){var S=(Array.isArray(v)?v:[v]).map(function(g){return g.id}).filter(s);return w(S,function(){return p.requestAdvanced(v,f)})};return{request:function(v,f,S){var g=p._createID();return w([g],function(){return p.requestWithID(v,f,S,g)})},requestAdvanced:function(v,f){return y(v,f)}}},o.prototype.request=function(h,c,p){return this.requestWithID(h,c,p,this._createID())},o.prototype.requestWithID=function(h,c,p,w){return t(this,void 0,void 0,function(){var y,v;return e(this,function(f){switch(f.label){case 0:return y=(0,r.createJSONRPCRequest)(w,h,c),[4,this.requestAdvanced(y,p)];case 1:return v=f.sent(),v.result!==void 0&&!v.error?[2,v.result]:v.result===void 0&&v.error?[2,Promise.reject(new r.JSONRPCErrorException(v.error.message,v.error.code,v.error.data))]:[2,Promise.reject(new Error("An unexpected error occurred"))]}})})},o.prototype.requestAdvanced=function(h,c){var p=this,w=Array.isArray(h);Array.isArray(h)||(h=[h]);var y=h.filter(function(S){return s(S.id)}),v=y.map(function(S){return new Promise(function(g){return p.idToResolveMap.set(S.id,g)})}),f=Promise.all(v).then(function(S){return w||!S.length?S:S[0]});return this.send(w?h:h[0],c).then(function(){return f},function(S){return y.forEach(function(g){p.receive((0,r.createJSONRPCErrorResponse)(g.id,n.DefaultErrorCode,S&&S.message||"Failed to send a request"))}),f})},o.prototype.notify=function(h,c,p){var w=(0,r.createJSONRPCNotification)(h,c);this.send(w,p).then(void 0,function(){})},o.prototype.send=function(h,c){return t(this,void 0,void 0,function(){return e(this,function(p){return[2,this._send(h,c)]})})},o.prototype.rejectAllPendingRequests=function(h){this.idToResolveMap.forEach(function(c,p){return c((0,r.createJSONRPCErrorResponse)(p,n.DefaultErrorCode,h))}),this.idToResolveMap.clear()},o.prototype.receive=function(h){var c=this;Array.isArray(h)||(h=[h]),h.forEach(function(p){var w=c.idToResolveMap.get(p.id);w&&(c.idToResolveMap.delete(p.id),w(p))})},o})();ae.JSONRPCClient=i;var s=function(o){return o!=null};return ae}var He={},It;function gr(){return It||(It=1,Object.defineProperty(He,"__esModule",{value:!0})),He}var ce={},kt;function br(){return kt||(kt=1,(function(t){var e=ce&&ce.__awaiter||function(C,b,E,A){function k(M){return M instanceof E?M:new E(function(D){D(M)})}return new(E||(E=Promise))(function(M,D){function z(G){try{_(A.next(G))}catch(ve){D(ve)}}function X(G){try{_(A.throw(G))}catch(ve){D(ve)}}function _(G){G.done?M(G.value):k(G.value).then(z,X)}_((A=A.apply(C,b||[])).next())})},r=ce&&ce.__generator||function(C,b){var E={label:0,sent:function(){if(M[0]&1)throw M[1];return M[1]},trys:[],ops:[]},A,k,M,D;return D={next:z(0),throw:z(1),return:z(2)},typeof Symbol=="function"&&(D[Symbol.iterator]=function(){return this}),D;function z(_){return function(G){return X([_,G])}}function X(_){if(A)throw new TypeError("Generator is already executing.");for(;D&&(D=0,_[0]&&(E=0)),E;)try{if(A=1,k&&(M=_[0]&2?k.return:_[0]?k.throw||((M=k.return)&&M.call(k),0):k.next)&&!(M=M.call(k,_[1])).done)return M;switch(k=0,M&&(_=[_[0]&2,M.value]),_[0]){case 0:case 1:M=_;break;case 4:return E.label++,{value:_[1],done:!1};case 5:E.label++,k=_[1],_=[0];continue;case 7:_=E.ops.pop(),E.trys.pop();continue;default:if(M=E.trys,!(M=M.length>0&&M[M.length-1])&&(_[0]===6||_[0]===2)){E=0;continue}if(_[0]===3&&(!M||_[1]>M[0]&&_[1]<M[3])){E.label=_[1];break}if(_[0]===6&&E.label<M[1]){E.label=M[1],M=_;break}if(M&&E.label<M[2]){E.label=M[2],E.ops.push(_);break}M[2]&&E.ops.pop(),E.trys.pop();continue}_=b.call(C,E)}catch(G){_=[6,G],k=0}finally{A=M=0}if(_[0]&5)throw _[1];return{value:_[0]?_[1]:void 0,done:!0}}},n=ce&&ce.__spreadArray||function(C,b,E){if(E||arguments.length===2)for(var A=0,k=b.length,M;A<k;A++)(M||!(A in b))&&(M||(M=Array.prototype.slice.call(b,0,A)),M[A]=b[A]);return C.concat(M||Array.prototype.slice.call(b))};Object.defineProperty(t,"__esModule",{value:!0}),t.JSONRPCServer=t.createMethodNotFoundResponse=t.createInvalidRequestResponse=void 0;var i=Ne(),s=Mt(),o=function(){return(0,i.createJSONRPCErrorResponse)(null,i.JSONRPCErrorCode.ParseError,"Parse error")},h=function(C){return(0,i.createJSONRPCErrorResponse)((0,i.isJSONRPCID)(C.id)?C.id:null,i.JSONRPCErrorCode.InvalidRequest,"Invalid Request")};t.createInvalidRequestResponse=h;var c=function(C){return(0,i.createJSONRPCErrorResponse)(C,i.JSONRPCErrorCode.MethodNotFound,"Method not found")};t.createMethodNotFoundResponse=c;var p=(function(){function C(b){b===void 0&&(b={});var E;this.mapErrorToJSONRPCErrorResponse=f,this.handleMethodNotFound=S,this.nameToMethodMap=new Map,this.middleware=null,this.errorListener=(E=b.errorListener)!==null&&E!==void 0?E:console.warn}return C.prototype.hasMethod=function(b){return this.nameToMethodMap.has(b)},C.prototype.addMethod=function(b,E){this.addMethodAdvanced(b,this.toJSONRPCMethod(E))},C.prototype.removeMethod=function(b){this.nameToMethodMap.delete(b)},C.prototype.toJSONRPCMethod=function(b){return function(E,A){var k=b(E.params,A);return Promise.resolve(k).then(function(M){return v(E.id,M)})}},C.prototype.addMethodAdvanced=function(b,E){this.nameToMethodMap.set(b,E)},C.prototype.receiveJSON=function(b,E){var A=this.tryParseRequestJSON(b);return A?this.receive(A,E):Promise.resolve(o())},C.prototype.tryParseRequestJSON=function(b){try{return JSON.parse(b)}catch{return null}},C.prototype.receive=function(b,E){return Array.isArray(b)?this.receiveMultiple(b,E):this.receiveSingle(b,E)},C.prototype.receiveMultiple=function(b,E){return e(this,void 0,void 0,function(){var A,k=this;return r(this,function(M){switch(M.label){case 0:return b.length===0?[2,(0,i.createJSONRPCErrorResponse)(null,i.JSONRPCErrorCode.InvalidRequest,"Invalid Request")]:[4,Promise.all(b.map(function(D){return k.receiveSingle(D,E)}))];case 1:return A=M.sent().filter(w),A.length===1?[2,A[0]]:A.length?[2,A]:[2,null]}})})},C.prototype.receiveSingle=function(b,E){return e(this,void 0,void 0,function(){var A,k;return r(this,function(M){switch(M.label){case 0:return A=this.nameToMethodMap.get(b.method),(0,i.isJSONRPCRequest)(b)?[3,1]:[2,(0,t.createInvalidRequestResponse)(b)];case 1:return[4,this.callMethod(A,b,E)];case 2:return k=M.sent(),[2,g(b,k)]}})})},C.prototype.applyMiddleware=function(){for(var b=[],E=0;E<arguments.length;E++)b[E]=arguments[E];this.middleware?this.middleware=this.combineMiddlewares(n([this.middleware],b,!0)):this.middleware=this.combineMiddlewares(b)},C.prototype.combineMiddlewares=function(b){return b.length?b.reduce(this.middlewareReducer):null},C.prototype.middlewareReducer=function(b,E){return function(A,k,M){return b(function(D,z){return E(A,D,z)},k,M)}},C.prototype.callMethod=function(b,E,A){var k=this,M=function(z,X){return b?b(z,X):k.handleMethodNotFound(z,X)},D=function(z){return k.errorListener('An unexpected error occurred while executing "'.concat(E.method,'" JSON-RPC method:'),z),Promise.resolve(k.mapErrorToJSONRPCErrorResponseIfNecessary(E.id,z))};try{return(this.middleware||y)(M,E,A).then(void 0,D)}catch(z){return D(z)}},C.prototype.mapErrorToJSONRPCErrorResponseIfNecessary=function(b,E){return b!==void 0?this.mapErrorToJSONRPCErrorResponse(b,E):null},C})();t.JSONRPCServer=p;var w=function(C){return C!==null},y=function(C,b,E){return C(b,E)},v=function(C,b){return C!==void 0?(0,i.createJSONRPCSuccessResponse)(C,b):null},f=function(C,b){var E,A=(E=b?.message)!==null&&E!==void 0?E:"An unexpected error occurred",k=s.DefaultErrorCode,M;return b instanceof i.JSONRPCErrorException&&(k=b.code,M=b.data),(0,i.createJSONRPCErrorResponse)(C,k,A,M)},S=function(C){return e(void 0,void 0,void 0,function(){return r(this,function(b){return C.id!==void 0?[2,(0,t.createMethodNotFoundResponse)(C.id)]:[2,null]})})},g=function(C,b){return b||(C.id!==void 0?(0,i.createJSONRPCErrorResponse)(C.id,i.JSONRPCErrorCode.InternalError,"Internal error"):null)}})(ce)),ce}var le={},xt;function mr(){if(xt)return le;xt=1;var t=le&&le.__awaiter||function(i,s,o,h){function c(p){return p instanceof o?p:new o(function(w){w(p)})}return new(o||(o=Promise))(function(p,w){function y(S){try{f(h.next(S))}catch(g){w(g)}}function v(S){try{f(h.throw(S))}catch(g){w(g)}}function f(S){S.done?p(S.value):c(S.value).then(y,v)}f((h=h.apply(i,s||[])).next())})},e=le&&le.__generator||function(i,s){var o={label:0,sent:function(){if(p[0]&1)throw p[1];return p[1]},trys:[],ops:[]},h,c,p,w;return w={next:y(0),throw:y(1),return:y(2)},typeof Symbol=="function"&&(w[Symbol.iterator]=function(){return this}),w;function y(f){return function(S){return v([f,S])}}function v(f){if(h)throw new TypeError("Generator is already executing.");for(;w&&(w=0,f[0]&&(o=0)),o;)try{if(h=1,c&&(p=f[0]&2?c.return:f[0]?c.throw||((p=c.return)&&p.call(c),0):c.next)&&!(p=p.call(c,f[1])).done)return p;switch(c=0,p&&(f=[f[0]&2,p.value]),f[0]){case 0:case 1:p=f;break;case 4:return o.label++,{value:f[1],done:!1};case 5:o.label++,c=f[1],f=[0];continue;case 7:f=o.ops.pop(),o.trys.pop();continue;default:if(p=o.trys,!(p=p.length>0&&p[p.length-1])&&(f[0]===6||f[0]===2)){o=0;continue}if(f[0]===3&&(!p||f[1]>p[0]&&f[1]<p[3])){o.label=f[1];break}if(f[0]===6&&o.label<p[1]){o.label=p[1],p=f;break}if(p&&o.label<p[2]){o.label=p[2],o.ops.push(f);break}p[2]&&o.ops.pop(),o.trys.pop();continue}f=s.call(i,o)}catch(S){f=[6,S],c=0}finally{h=p=0}if(f[0]&5)throw f[1];return{value:f[0]?f[1]:void 0,done:!0}}};Object.defineProperty(le,"__esModule",{value:!0}),le.JSONRPCServerAndClient=void 0;var r=Ne(),n=(function(){function i(s,o,h){h===void 0&&(h={});var c;this.server=s,this.client=o,this.errorListener=(c=h.errorListener)!==null&&c!==void 0?c:console.warn}return i.prototype.applyServerMiddleware=function(){for(var s,o=[],h=0;h<arguments.length;h++)o[h]=arguments[h];(s=this.server).applyMiddleware.apply(s,o)},i.prototype.hasMethod=function(s){return this.server.hasMethod(s)},i.prototype.addMethod=function(s,o){this.server.addMethod(s,o)},i.prototype.addMethodAdvanced=function(s,o){this.server.addMethodAdvanced(s,o)},i.prototype.removeMethod=function(s){this.server.removeMethod(s)},i.prototype.timeout=function(s){return this.client.timeout(s)},i.prototype.request=function(s,o,h){return this.client.request(s,o,h)},i.prototype.requestAdvanced=function(s,o){return this.client.requestAdvanced(s,o)},i.prototype.notify=function(s,o,h){this.client.notify(s,o,h)},i.prototype.rejectAllPendingRequests=function(s){this.client.rejectAllPendingRequests(s)},i.prototype.receiveAndSend=function(s,o,h){return t(this,void 0,void 0,function(){var c,p;return e(this,function(w){switch(w.label){case 0:return(0,r.isJSONRPCResponse)(s)||(0,r.isJSONRPCResponses)(s)?(this.client.receive(s),[3,4]):[3,1];case 1:return(0,r.isJSONRPCRequest)(s)||(0,r.isJSONRPCRequests)(s)?[4,this.server.receive(s,o)]:[3,3];case 2:return c=w.sent(),c?[2,this.client.send(c,h)]:[3,4];case 3:return p="Received an invalid JSON-RPC message",this.errorListener(p,s),[2,Promise.reject(new Error(p))];case 4:return[2]}})})},i})();return le.JSONRPCServerAndClient=n,le}var Nt;function Sr(){return Nt||(Nt=1,(function(t){var e=de&&de.__createBinding||(Object.create?(function(n,i,s,o){o===void 0&&(o=s);var h=Object.getOwnPropertyDescriptor(i,s);(!h||("get"in h?!i.__esModule:h.writable||h.configurable))&&(h={enumerable:!0,get:function(){return i[s]}}),Object.defineProperty(n,o,h)}):(function(n,i,s,o){o===void 0&&(o=s),n[o]=i[s]})),r=de&&de.__exportStar||function(n,i){for(var s in n)s!=="default"&&!Object.prototype.hasOwnProperty.call(i,s)&&e(i,n,s)};Object.defineProperty(t,"__esModule",{value:!0}),r(vr(),t),r(gr(),t),r(Ne(),t),r(br(),t),r(mr(),t)})(de)),de}var _e=Sr();class Cr extends Event{code;reason;wasClean;constructor(e,r={}){super(e,r),this.code=r.code??0,this.reason=r.reason??"",this.wasClean=r.wasClean??!1}}function Er(t,e){const r="CloseEvent"in globalThis?globalThis.CloseEvent:Cr;return new r(t,e)}class Rr{#e=new EventTarget;addEventListener(e,r,n){return this.#e.addEventListener(e,r,n),()=>{this.#e.removeEventListener(e,r,n)}}removeEventListener(e,r,n){this.#e.removeEventListener(e,r,n)}dispatchEvent(e){return this.#e.dispatchEvent(e)}}const j=Symbol.for("@appetizeio/rpc:rpcMethods");class Or extends Rr{send;constructor(e){super(),this.send=e}dispatchClose(e){return this.dispatchEvent(Er("close",e))}dispatchMessage(e){return this.dispatchEvent(new CustomEvent("message",{detail:e}))}}const _t=Ee("appetize.io:error:rpc");function Ze(t,e){const r=new _e.JSONRPCServerAndClient(new _e.JSONRPCServer({errorListener:_t}),Mr(t),{errorListener:_t}),n=t[j].addEventListener("message",({detail:s})=>{r.receiveAndSend(s)}),i=t[j].addEventListener("close",()=>{n(),r.rejectAllPendingRequests("Transport closed")},{once:!0});for(const s in e){const o=e[s];o&&r.addMethod(s,o.bind(e))}return{rpc:r,unsub:()=>{n(),i()}}}function Ar(t,e){const{rpc:r,unsub:n}=Ze(t,e);return{client:r.client,unsub:n}}function Fe(t,e){const r=t[j].addEventListener("message",({detail:i})=>{if("method"in i)try{e({method:i.method,param:i.params})}catch{}}),n=t[j].addEventListener("close",r,{once:!0});return()=>{r(),n()}}function Mr(t){return new _e.JSONRPCClient(t[j].send.bind(t[j]),()=>Math.floor(Math.random()*Number.MAX_SAFE_INTEGER)+1)}const Pr=(...t)=>Ar(...t),Xe=["ArrowDown","ArrowLeft","ArrowRight","ArrowUp","Backspace","Enter","Tab"],Ir=33333,kr=[[99,10],[396,11],[792,21],[1620,22],[3600,31],[5120,32],[8192,40],[8704,42],[22080,50],[36864,51],[139264,60]],xr=new Intl.Segmenter(void 0,{granularity:"grapheme"}),Nr=new Set(Xe);class _r{#e;#r=!1;#t;#n;#i;#o;#a;#s;#c;#l=0;#u=!1;constructor({canvas:e,context:r,onClose:n,onError:i,signal:s,stream:o}){this.#e=e,this.#t=r,this.#o=n,this.#a=i,this.#s=s,this.#c=o,this.#s?.addEventListener("abort",this.close,{once:!0}),this.#p()}close=()=>{this.#r||(this.#r=!0,this.#f(),this.#n=void 0,this.#c.close(),this.#s?.removeEventListener("abort",this.close),this.#o?.())};#f(){this.#n&&this.#n.state!=="closed"&&this.#n.close()}#h(e){const r=Ur(e.data,e.width,e.height),n=`${r}:${String(e.width)}x${String(e.height)}`;this.#n&&this.#i===n||(this.#f(),this.#i=n,this.#e.height=e.height,this.#e.width=e.width,this.#n=new VideoDecoder({error:this.#d,output:i=>{this.#t.drawImage(i,0,0,this.#e.width,this.#e.height),i.close()}}),this.#n.configure({codec:r,codedHeight:e.height,codedWidth:e.width,hardwareAcceleration:"no-preference",optimizeForLatency:!0}))}async#p(){try{for await(const e of this.#c){if(this.#r)return;if(e.data.byteLength!==0){if(e.type==="key"&&e.codec==="jpeg"){this.#u=!1,this.#i=void 0,this.#f(),this.#n=void 0,await this.#y(e);continue}if(!(e.type==="delta"&&this.#u)&&(e.type==="key"&&(this.#u=!1,this.#h(e)),this.#n?.state==="configured")){if(this.#n.decodeQueueSize>2&&e.type==="delta"){this.#d();continue}this.#n.decode(new EncodedVideoChunk({data:new Uint8Array(e.data),timestamp:this.#l,type:e.type})),this.#l+=Ir}}}}catch(e){this.#r||this.#a?.(e)}finally{this.close()}}#d=()=>{this.#u=!0,this.#i=void 0,this.#f(),this.#n=void 0,this.#c.requestKeyFrame()};async#y(e){const r=await createImageBitmap(new Blob([new Uint8Array(e.data)],{type:"image/jpeg"}));this.#e.height=e.height,this.#e.width=e.width,this.#t.drawImage(r,0,0,e.width,e.height),r.close()}}function Fr(t,e,{signal:r}={}){if(r?.aborted)return()=>{};const n=s=>{s.altKey||s.ctrlKey||s.metaKey||!Jr(s.key)||(s.preventDefault(),t.keyboard.press(s.key))},i=()=>{e.removeEventListener("keydown",n),r?.removeEventListener("abort",i)};return e.addEventListener("keydown",n),r?.addEventListener("abort",i,{once:!0}),i}function Tr(t,e,{signal:r}={}){let n,i;const s=p=>{n===void 0&&(p.preventDefault(),n=p.pointerId,i=Ye(e,p),e.focus(),e.setPointerCapture(p.pointerId),t.touch.down(i.x,i.y))},o=p=>{p.pointerId===n&&(p.preventDefault(),i=Ye(e,p),t.touch.move(i.x,i.y))},h=p=>{if(p.pointerId!==n)return;p.preventDefault();const w=Ye(e,p);t.touch.up(w.x,w.y),Tt(e,p.pointerId),n=void 0,i=void 0},c=()=>{n!==void 0&&Tt(e,n),i&&t.touch.up(i.x,i.y),n=void 0,i=void 0,e.removeEventListener("pointercancel",h),e.removeEventListener("pointerdown",s),e.removeEventListener("pointermove",o),e.removeEventListener("pointerup",h),r?.removeEventListener("abort",c)};return r?.aborted||(e.addEventListener("pointercancel",h),e.addEventListener("pointerdown",s),e.addEventListener("pointermove",o),e.addEventListener("pointerup",h),r?.addEventListener("abort",c,{once:!0})),c}async function Lr(t,e,{onClose:r,onError:n,signal:i}={}){const s=e.getContext("2d");if(!s)throw new Error("Canvas context unavailable");i?.throwIfAborted();const o=await t.video.createStream({signal:i});return{close:new _r({canvas:e,context:s,onClose:r,onError:n,signal:i,stream:o}).close}}function Ft(t){return Math.max(0,Math.min(1,t))}function Ur(t,e,r){const n=Math.ceil(e/16)*Math.ceil(r/16),i=kr.find(([s])=>n<=s)?.[1]??62;for(let s=0;s<t.length-7;s+=1){const o=t[s]===0&&t[s+1]===0&&t[s+2]===1,h=t[s]===0&&t[s+1]===0&&t[s+2]===0&&t[s+3]===1,c=o?s+3:h?s+4:-1;if(c>=0&&(t[c]&31)===7)return`avc1.${[t[c+1],t[c+2],Math.max(t[c+3],i)].map(p=>p.toString(16).padStart(2,"0")).join("")}`}return"avc1.42e01e"}function Jr(t){return Array.from(xr.segment(t)).length===1||Nr.has(t)}function Ye(t,e){const r=t.getBoundingClientRect();return{x:Ft((e.clientX-r.left)/r.width),y:Ft((e.clientY-r.top)/r.height)}}function Tt(t,e){t.hasPointerCapture(e)&&t.releasePointerCapture(e)}function Lt(t){return!!t&&typeof t=="object"&&"jsonrpc"in t}class Te{closed=!1;[j];#e;constructor(e,{signal:r}={}){this[j]=new Or(e),this.#e=r,this.#e?.addEventListener("abort",this.#r)}close(e={}){this.closed||(this.closed=!0,this.handleClose(e))}handleClose(e){this.#e?.removeEventListener("abort",this.#r),this[j].dispatchClose(e)}#r=()=>{this.close({code:1e3,reason:String(this.#e?.reason)})}}const he=Ee("appetize.io:trace:transport:iframe");class Ut extends Te{onmessage;#e;#r;constructor(e,{origin:r="*",signal:n}={}){super(async i=>{e.postMessage(i,this.#e)},{signal:n}),this.#r=e,this.#e=r,window.addEventListener("message",this.#t)}postMessage(e,r,n){he("postMessage(legacy)",{message:e,targetOrigin:r,transfer:n}),this.#r.postMessage(e,r??this.#e,n)}handleClose(e){he("close()"),window.removeEventListener("message",this.#t),super.handleClose(e)}#t=async e=>{if(he("handleMessage()",e),e.source!==this.#r||(he("handleMessage() -> source ok"),this.#e!=="*"&&e.origin!==this.#e))return;he("handleMessage() -> origin ok");const r=e.data;if(!Lt(r)){he("handleMessage() -> legacy"),this.onmessage?.(e);return}he("handleMessage() -> jsonrpc"),this[j].dispatchMessage(r)}}function Jt(t,e,{leftEffects:r=()=>({}),notifiesLeft:n,notifiesRight:i,rightEffects:s=()=>({})}={}){const o=Ze(t,{}),h=Ze(e,{}),c=[()=>{o.unsub(),h.unsub()}],p=()=>{for(const S of c)try{S()}catch{}},w=h.rpc.client,y=o.rpc.client;c.push(t[j].addEventListener("close",()=>{p()},{once:!0}),e[j].addEventListener("close",()=>{p()},{once:!0}));const v=r(w,y);for(const S in v){const g=v[S];g&&o.rpc.addMethod(S,g)}const f=s(y,w);for(const S in f){const g=f[S];g&&h.rpc.addMethod(S,g)}return Dt(o.rpc,h.rpc,{notifies:n}),Dt(h.rpc,o.rpc,{notifies:i}),p}function Dt(t,e,{notifies:r}={}){t.applyServerMiddleware(async(n,i)=>{const s=r?.();if(s){const{id:h,...c}=i;s[j].send(c)}if(t.hasMethod(i.method))return await n(i);if(!i.id)return e.notify(i.method,i.params),null;const o=await e.request(i.method,i.params);return{id:i.id,jsonrpc:_e.JSONRPC,result:o}})}function ue(t,...e){t.notify(e[0],e[1],e[2])}function Qe(){const t=new Te(async r=>{e[j].dispatchMessage(r)}),e=new Te(async r=>{t[j].dispatchMessage(r)});return t[j].addEventListener("close",()=>{e.close()},{once:!0}),e[j].addEventListener("close",()=>{t.close()},{once:!0}),[t,e]}function jt(t,e){const r=[],n=()=>{for(const i of r)i()};r.push(t[j].addEventListener("message",i=>e[j].send(i.detail))),r.push(t[j].addEventListener("close",n,{once:!0})),r.push(e[j].addEventListener("message",i=>t[j].send(i.detail))),r.push(e[j].addEventListener("close",n,{once:!0}))}function Dr(t){return{clearState:async e=>{await t.request("appetizeio.device.server.app.clearState",{appId:e})},launch:async e=>{await t.request("appetizeio.device.server.app.launch",{appId:e})},reinstall:async e=>{await t.request("appetizeio.device.server.app.reinstall",{appId:e})},restart:async e=>{await t.request("appetizeio.device.server.app.restart",{appId:e})}}}function et(){let t,e;return{promise:new Promise((n,i)=>{e=n,t=i}),reject:t,resolve:e}}const jr=2*1024*1024,Bt=Ee("appetize:client:acked-writable-stream");class Br{unacked=0;#e;#r;#t;#n;#i=[];#o;constructor(e){this.#t=e,this.#o=e.window??jr}abort(e){this.#s(e),this.#t.onAbort?.(e)}async close(){await this.#c(()=>this.unacked===0),this.#t.onClose?.()}fail(e){this.#s(e)&&this.#t.onError?.(e)}start(e){this.#e=e}write(e){const r=e.byteLength;return this.unacked+=r,this.#t.send(e).then(()=>{this.unacked-=r,this.#n&&(this.#n.acked+=r),this.#a()},n=>{this.fail(n)}),this.unacked>=this.#o&&!this.#n&&(this.#n={acked:0,at:performance.now()},Bt("window full: %d bytes unacked, writes stalled",this.unacked)),this.#c(()=>this.unacked<this.#o)}#a(){if(this.#n&&this.unacked<=this.#o/2){const e=performance.now()-this.#n.at;Bt("pressure relieved after %dms: %d bytes acked, %s MB/s",Math.round(e),this.#n.acked,(this.#n.acked/Math.max(e,1)/1e3).toFixed(2)),this.#n=void 0}this.#i=this.#i.filter(e=>e.until()?(e.resolve(void 0),!1):!0)}#s(e){if(this.#r)return!1;this.#r={reason:e},this.#e.error(e);const r=this.#i;this.#i=[];for(const n of r)n.reject(e);return!0}#c(e){if(e())return Promise.resolve();const r={...et(),until:e};return this.#i.push(r),r.promise}}class zr extends WritableStream{get unacked(){return this.#e.unacked}#e;constructor(e){const r=new Br(e);super({abort:n=>{r.abort(n)},close:()=>r.close(),start:n=>{r.start(n)},write:n=>r.write(n)}),this.#e=r}fail(e){this.#e.fail(e)}}const qr=1024*1024;class Kr{#e;#r=!1;#t;#n;constructor(e){this.#t=e}cancel(e){this.#i(),this.#t?.(e)}close(){this.#i()&&this.#e.close()}error(e){this.#i()&&this.#e.error(e)}pull(){const e=this.#n;this.#n=void 0,e?.resolve(void 0)}async push(e){if(this.#r)return;this.#n??=et();const{promise:r}=this.#n;this.#e.enqueue(e),await r}start(e){this.#e=e}#i(){return this.#r?!1:(this.#r=!0,this.pull(),!0)}}class Vr extends ReadableStream{#e;constructor({highWaterMark:e=qr,onCancel:r}={}){const n=new Kr(r);super({cancel:i=>{n.cancel(i)},pull:()=>{n.pull()},start:i=>{n.start(i)}},new ByteLengthQueuingStrategy({highWaterMark:e})),this.#e=n}close(){this.#e.close()}error(e){this.#e.error(e)}push(e){return this.#e.push(e)}}class $r{closed;readable;writable;#e=[];#r;#t;#n;#i;#o;#a="starting";constructor(e,{onClose:r,receiveBuffer:n,sendWindow:i,signal:s}){if(this.#o=e,this.#r=et(),this.closed=this.#r.promise,this.closed.catch(Wr),this.#n=new Vr({highWaterMark:n,onCancel:()=>{this.#s(void 0)}}),this.readable=this.#n,this.#i=new zr({onAbort:()=>{this.#s(void 0)},onClose:()=>{this.#s(void 0)},onError:o=>{this.#s(o)},send:o=>e.request("appetizeio.device.server.debug.adbTunnel.data",{data:o}),window:i}),this.writable=this.#i,s){const o=()=>{this.#s(s.reason)};s.addEventListener("abort",o,{once:!0}),this.#e.push(()=>{s.removeEventListener("abort",o)})}this.#e.push(()=>{r(this)})}close=()=>{this.#s(void 0)};detach(){this.#s(void 0,{notifyServer:!1})}async handleData(e){this.#a==="open"&&await this.#n.push(e)}handleStopped({error:e}){this.#a==="open"&&this.#s(e?new Error(e):void 0)}async start(){try{await this.#o.request("appetizeio.device.server.debug.adbTunnel.start",void 0)}catch(e){throw this.#s(e),e}if(this.#a==="closed")throw this.#t?this.#t:new Error("The adb tunnel closed before it started");this.#a="open"}async[Symbol.asyncDispose](){this.close();try{await this.closed}catch{}}#s(e,{notifyServer:r=!0}={}){if(this.#a!=="closed"){this.#a="closed",this.#t=e,r&&ue(this.#o,"appetizeio.device.server.debug.adbTunnel.stop",void 0),e?(this.#n.error(e),this.#i.fail(e)):(this.#n.close(),this.#i.fail(new Error("The adb tunnel has stopped")));for(const n of this.#e)n();e?this.#r.reject(e):this.#r.resolve(void 0)}}}function Wr(){}class Gr{readable;ready;#e=[];#r=!1;#t;#n;#i;constructor({label:e,onClose:r,signal:n}){this.#n=e,this.ready=new Promise((s,o)=>{this.#i={reject:o,resolve:s}});let i;if(this.readable=new ReadableStream({cancel:()=>{this.#a()},start:s=>{i=s}}),!i)throw new Error("ReadableStream controller was not initialized");if(this.#t=i,n){const s=()=>{this.fail(n.reason)};n.addEventListener("abort",s,{once:!0}),this.#e.push(()=>{n.removeEventListener("abort",s)})}this.#e.push(()=>{r(this)})}close=()=>{this.#o()};fail(e){this.#o(e)}handleItem(e){this.#t.enqueue(e)}markReady(){if(!this.#i)return;const{resolve:e}=this.#i;this.#i=void 0,e(this)}async*[Symbol.asyncIterator](){const e=this.readable.getReader();try{for(let r=await e.read();!r.done;r=await e.read())yield r.value}finally{await e.cancel()}}#o(e){this.#r||(this.#t.close(),this.#a(e))}#a(e){this.#r=!0;for(const r of this.#e)r();this.#i?.reject(e??new Error(`${this.#n} closed before it started`)),this.#i=void 0}}class Hr{get subscribers(){return this.#t}#e;#r;#t=new Set;constructor(e){this.#e=e}close(){this.#r=void 0;for(const e of[...this.#t])e.close();this.#t.clear()}add(e){this.#t.add(e)}ensureStarted(){return this.#r||(this.#r=(async()=>{try{return await this.#e.start()}catch(e){throw this.#r=void 0,e}})()),this.#r}release(e){this.#t.delete(e),!(this.#t.size>0||!this.#r)&&(this.#r=void 0,this.#e.stop())}}class zt extends Hr{#e;constructor(e){super({start:e.start,stop:e.stop}),this.#e=e.label}async createStream({signal:e}={}){e?.throwIfAborted();const r=new Gr({label:this.#e,onClose:n=>{this.release(n)},signal:e});this.add(r);try{await this.ensureStarted(),r.markReady()}catch(n){r.fail(n)}return await r.ready}handleNotification(e){for(const r of this.subscribers)r.handleItem(e)}}class Zr{#e;#r;#t;#n;constructor(e){this.#n=e,this.#r=new zt({label:"Log stream",start:()=>e.request("appetizeio.device.server.debug.log.start"),stop:()=>{ue(e,"appetizeio.device.server.debug.log.stop",void 0)}}),this.#t=new zt({label:"Proxy intercept stream",start:()=>e.request("appetizeio.device.server.debug.proxyIntercept.start"),stop:()=>{ue(e,"appetizeio.device.server.debug.proxyIntercept.stop",void 0)}})}close(){this.#e?.detach(),this.#r.close(),this.#t.close()}async createAdbTunnel({signal:e}={}){e?.throwIfAborted(),this.#e?.close();const r=new $r(this.#n,{onClose:()=>{this.#e=void 0},signal:e});return this.#e=r,await r.start(),r}async createLogStream(e){return await this.#r.createStream(e)}async createProxyInterceptStream(e){return await this.#t.createStream(e)}async handleAdbTunnelData({data:e}){await this.#e?.handleData(e)}handleAdbTunnelStopped(e){this.#e?.handleStopped(e)}handleLogEntry(e){this.#r.handleNotification(e)}handleProxyInterceptEvent(e){this.#t.handleNotification(e)}}function Le(t){return{...Xr(t),index:t.index,within:t.within?Le(t.within):void 0}}function Xr(t){switch(t.by){case"testId":return{by:"testId",testId:t.testId};case"text":return{by:"text",text:Yr(t.text)}}}function Yr(t){return typeof t=="string"?{kind:"exact",value:t}:{flags:t.flags,kind:"regex",source:t.source}}const Qr=400,qt=["byTestId","byText","duration","index","x","y"],en=new Set(qt),tn=/^-?(?:\d+(?:\.\d*)?|\.\d+)$/u,rn=/^[a-z]$/u,tt=/^\s$/u;class q extends SyntaxError{constructor(e,r,n){super(`${e} at position ${String(r)}`,{cause:n})}}class nn{#e=0;#r;constructor(e){this.#r=e}parse(){const e=[];for(;this.#e<this.#r.length;){const r=this.#s();if(tt.test(r))this.#e++;else if(r===">"){if(this.#r.charAt(this.#e+1)===">")throw new q('Force press ">>" is not supported',this.#e);this.#e++,e.push({kind:"down"})}else if(r==="/")this.#e++,e.push({kind:"up"});else if(r==="{")e.push(this.#o());else{const[n]=this.#r.slice(this.#e,this.#e+2);throw new q(`Unexpected ${JSON.stringify(n)}; write selectors as {...}`,this.#e)}}return e}#t(){const e=this.#e,r=this.#c(n=>n!=="="&&!rt(n));if(this.#s()!=="=")return{kind:"bare",name:r,offset:e};if(r.length===0)throw new q('Expected an attribute name before "="',e);return this.#e++,{kind:"attribute",name:r,offset:e,value:this.#a()}}#n(){const e=this.#e;this.#e++;let r="";for(;;){const n=this.#s();if(this.#e++,n==='"')return r;if(n==="\\"){const i=this.#s();if(i!=='"'&&i!=="\\"&&i!=="")throw new q('Only \\" and \\\\ escapes are supported',this.#e-1);this.#e++,r+=i}else{if(n==="")throw new q("Unclosed string",e);r+=n}}}#i(){const e=this.#e;this.#e++;let r="",n=!1;for(;;){const s=this.#s();if(s==="")throw new q("Unclosed regex",e);if(this.#e++,s==="/"&&!n)break;r+=s,s==="\\"?(r+=this.#s(),this.#e++):s==="["?n=!0:s==="]"&&(n=!1)}const i=this.#c(s=>rn.test(s));try{return new RegExp(r,i)}catch(s){throw new q(`Invalid regex /${r}/${i}`,e,s)}}#o(){const e=this.#e;this.#e++;let r;const n={offsets:{}};for(let i=0;;i++){this.#l();const s=this.#s();if(s==="")throw new q('Unclosed "{"',e);if(s==="}"){if(this.#e++,i===0)throw new q('Expected a selector or wait in "{}"',e);return r===void 0?cn(n,e):{duration:r,kind:"wait"}}const o=this.#t();if(i===0&&o.name==="wait")r=o.kind==="attribute"?Kt(o.value,"wait"):Qr;else{if(r!==void 0)throw new q('"wait" takes no other attributes',o.offset);on(n,o,i)}}}#a(){const e=this.#e,r=this.#s();let n;if(r==='"')n={kind:"quoted",offset:e,text:this.#n()};else if(r==="/")n={kind:"regex",offset:e,regex:this.#i()};else{const i=this.#c(s=>!rt(s));if(i.length===0)throw new q('Expected a value after "="',e);return{kind:"raw",offset:e,text:i}}if(!rt(this.#s()))throw new q('Expected a space or "}" after the value',this.#e);return n}#s(){return this.#r.charAt(this.#e)}#c(e){const r=this.#e;for(;this.#e<this.#r.length&&e(this.#s());)this.#e++;return this.#r.slice(r,this.#e)}#l(){this.#c(e=>tt.test(e))}}function sn(t){return new nn(t).parse()}function on(t,e,r){const{name:n,offset:i}=e;if(e.kind==="attribute"){nt(t,n,i,e.value);return}if(!n.includes(","))throw new q(`Expected key=value, got ${JSON.stringify(n)}`,i);if(r>0)throw new q("Write the x,y position first",i);const[s,o,...h]=n.split(",");if(h.length>0)throw new q("Expected a screen position as x,y",i);const c=i+s.length+1;nt(t,"x",i,{kind:"raw",offset:i,text:s}),nt(t,"y",c,{kind:"raw",offset:c,text:o})}function an(t){return en.has(t)}function rt(t){return t===""||t==="}"||tt.test(t)}function nt(t,e,r,n){if(!an(e))throw new q(`Unknown attribute ${JSON.stringify(e)}; expected one of ${qt.join(", ")}`,r);if(t.offsets[e]!==void 0)throw new q(`Duplicate attribute ${JSON.stringify(e)}`,r);switch(t.offsets[e]=r,e){case"byTestId":case"byText":if(t.byText!==void 0||t.byTestId!==void 0)throw new q("Only one of byText and byTestId may be given",r);e==="byText"?t.byText=fn(n):t.byTestId=un(n);return;default:t[e]=Kt(n,e)}}function cn(t,e){return{duration:t.duration,kind:"move",to:ln(t,e)}}function Kt(t,e){if(t.kind!=="raw"||!tn.test(t.text))throw new q(`"${e}" takes a number`,t.offset);return Number(t.text)}function ln(t,e){const{byTestId:r,byText:n,index:i,offsets:s,x:o,y:h}=t;if(n!==void 0)return{by:"text",index:i,text:n,x:o,y:h};if(r!==void 0)return{by:"testId",index:i,testId:r,x:o,y:h};if(s.index!==void 0)throw new q('"index" needs byText or byTestId',s.index);if(o===void 0||h===void 0)throw new q("A screen position needs x and y",e);return{by:"position",x:o,y:h}}function un(t){if(t.kind==="regex")throw new q('"byTestId" takes a string',t.offset);return t.text}function fn(t){return t.kind==="regex"?t.regex:t.text}function Ae(t){return t.by==="position"?{by:"position",x:t.x,y:t.y}:{...Le(t),x:t.x,y:t.y}}function dn(t){return t.map(e=>e.kind==="move"?{duration:e.duration,kind:"move",to:Ae(e.to)}:e)}function hn(t){return{press:e=>{ue(t,"appetizeio.device.server.keyboard.press",{key:e})}}}function pn({onRequest:t,parent:e,proxyInlet:r,signal:n}){const i=new Ut(e,{signal:n}),s=[()=>{i.close()}];return jt(i,r),t&&s.push(Fe(i,o=>{t(o,{source:"parent"})})),{cleanup:()=>{for(const o of s)o()},notifies:()=>e===globalThis.window?void 0:i}}const yn="@appetizeio/rpc:playwrightAdapter",Ue=Symbol.for(yn);function wn(t){window[Ue]&&console.warn("playwright exposed more than once, overwriting previous adapter");const e={send(r){t[j].send(r)},subscribe(r){return t[j].addEventListener("message",n=>{r(n.detail)})}};return window[Ue]=e,()=>{window[Ue]===e&&delete window[Ue]}}function vn({onRequest:t,proxyInlet:e}){const[r,n]=Qe(),s=[wn(n),()=>{r.close()}];return jt(r,e),t&&s.push(Fe(r,o=>{t(o,{source:"parent"})})),{cleanup:()=>{for(const o of s)o()},notifies:()=>r}}function gn(t){return{clearKeychain:async()=>{await t.request("appetizeio.device.server.settings.clearKeychain")},setAppearance:async e=>{await t.request("appetizeio.device.server.settings.setAppearance",{appearance:e})},setBiometryEnrolled:async e=>{await t.request("appetizeio.device.server.settings.setBiometryEnrolled",{enrolled:e})},setFontSize:async e=>{await t.request("appetizeio.device.server.settings.setFontSize",{fontSize:e})},setLocation:async({latitude:e,longitude:r})=>{await t.request("appetizeio.device.server.settings.setLocation",{latitude:e,longitude:r})}}}function bn(t){return"to"in t?{from:Ae(t.from),kind:"path",to:Ae(t.to)}:{direction:t.direction,distance:t.distance,from:t.from?Ae(t.from):void 0,kind:"direction"}}function mn(t){return{down:(e,r)=>{ue(t,"appetizeio.device.server.touch.down",{x:e,y:r})},move:(e,r)=>{ue(t,"appetizeio.device.server.touch.move",{x:e,y:r})},up:(e,r)=>{ue(t,"appetizeio.device.server.touch.up",{x:e,y:r})}}}const Sn=new Set(Xe),Cn=/^(?<key>[A-Za-z]+)>(?<repeat>\d+)\/$/u,En=/(\{\{|\{[^{}]*\})/u;function Rn(t){const e=[];let r="";function n(){r.length>0&&(e.push({kind:"text",text:r}),r="")}for(const[i,s]of t.split(En).entries())if(i%2===0){if(s.includes("{"))throw new Error(`Unclosed "{" in ${JSON.stringify(t)}`);r+=s}else s==="{{"?r+="{":(n(),e.push(An(s.slice(1,-1))));return n(),e}function On(t,e){if(!Sn.has(t))throw e.endsWith(">")?new Error(`Holding a key is not supported: {${e}}`):e.startsWith("/")?new Error(`Releasing a key is not supported: {${e}}`):new Error(`{${e}} does not name a supported key. Supported: ${Xe.join(", ")}. Type characters as text, and escape a literal "{" as "{{".`)}function An(t){const e=Cn.exec(t)?.groups,r=e?.key??t;if(On(r,t),!e)return{key:r,kind:"press"};const n=Number(e.repeat);if(n<1)throw new Error(`Repeat for {${t}} must be at least 1`);return{key:r,kind:"press",repeat:n}}const Mn=Symbol("@appetizeio/client:v1Compat");function Vt(t){return t?.[Mn]}class Pn{readable;ready;get dimensions(){return this.#n}#e=[];#r=!1;#t;#n;#i;#o;constructor({onClose:e,requestKeyFrame:r,signal:n}){this.#i=r,this.ready=new Promise((s,o)=>{this.#o={reject:o,resolve:s}});let i;if(this.readable=new ReadableStream({cancel:()=>{this.#s()},start:s=>{i=s}}),!i)throw new Error("ReadableStream controller was not initialized");if(this.#t=i,n){const s=()=>{this.fail(n.reason)};n.addEventListener("abort",s,{once:!0}),this.#e.push(()=>{n.removeEventListener("abort",s)})}this.#e.push(()=>{e(this)})}close=()=>{this.#a()};fail(e){this.#a(e)}handleChunk(e){if(this.#o){if(e.type!=="key")return;const{resolve:r}=this.#o;this.#o=void 0,this.#n={height:e.height,width:e.width},r(this)}else e.type==="key"&&(this.#n={height:e.height,width:e.width});this.#t.enqueue(e)}requestKeyFrame=()=>{this.#r||this.#i()};async*[Symbol.asyncIterator](){const e=this.readable.getReader();try{for(let r=await e.read();!r.done;r=await e.read())yield r.value}finally{await e.cancel()}}#a(e){this.#r||(this.#t.close(),this.#s(e))}#s(e){this.#r=!0;for(const r of this.#e)r();this.#o?.reject(e??new Error("Video stream closed before the first key chunk")),this.#o=void 0}}class In{#e=!1;#r;#t;#n=new Set;constructor(e){this.#r=e}close(){this.#t=void 0;for(const e of[...this.#n])e.close()}async createStream({signal:e}={}){e?.throwIfAborted();const r=new Pn({onClose:n=>{this.#o(n)},requestKeyFrame:()=>{this.#a()},signal:e});this.#n.add(r);try{await this.#i()}catch(n){r.fail(n)}return await r.ready}handleChunk(e){e.type==="key"&&(this.#e=!1);for(const r of this.#n)r.handleChunk(e)}#i(){return this.#t?(this.#a(),this.#t):(this.#e=!0,this.#t=(async()=>{try{await this.#r.request("appetizeio.device.server.video.start")}catch(e){throw this.#t=void 0,e}})(),this.#t)}#o(e){this.#n.delete(e),!(this.#n.size>0||!this.#t)&&(this.#t=void 0,ue(this.#r,"appetizeio.device.server.video.stop",void 0))}#a(){this.#e||(this.#e=!0,ue(this.#r,"appetizeio.device.server.video.requestKeyFrame",void 0))}}class kn{app;debug;keyboard;settings;touch;video;#e;#r=[];#t;constructor(e,r={}){const n=Vt(r)??{},{baseUrl:i,onClose:s,signal:o}=r;this.#e=i?xn(i):void 0;const{onRequest:h,parent:c,proxyRequest:p}=n,w=Nn(h);o?.addEventListener("abort",this.close);const[y,v]=Qe(),[f,S]=Qe();this.#r.push(()=>{y.close(),v.close(),f.close(),S.close()}),this.#r.push(Jt(S,e,{leftEffects:p}));const g=c==="playwright"?vn({onRequest:w,proxyInlet:f}):c?pn({onRequest:w,parent:c,proxyInlet:f,signal:o}):void 0;g&&this.#r.push(g.cleanup),this.#r.push(Jt(v,f,{notifiesLeft:g?.notifies}));const{client:C,unsub:b}=Pr(y,{"appetizeio.device.client.debug.adbTunnel.data":k=>E.handleAdbTunnelData(k),"appetizeio.device.client.debug.adbTunnel.stopped":async k=>{E.handleAdbTunnelStopped(k)},"appetizeio.device.client.debug.log.entry":async k=>{E.handleLogEntry(k)},"appetizeio.device.client.debug.proxyIntercept.event":async k=>{E.handleProxyInterceptEvent(k)},"appetizeio.device.client.video.chunk":async k=>{A.handleChunk(k)}});this.#t=C,this.#r.push(b);const E=new Zr(this.#t);this.#r.push(()=>{E.close()});const A=new In(this.#t);this.#r.push(()=>{A.close()}),this.app=Dr(this.#t),this.debug=E,this.keyboard=hn(this.#t),this.settings=gn(this.#t),this.touch=mn(this.#t),this.video=A,w&&(this.#r.push(Fe(v,k=>{w(k,{source:"self"})})),e instanceof Ut&&this.#r.push(Fe(e,k=>{w(k,{source:"iframe"})}))),this.#r.push(()=>s?.())}close=()=>{for(const e of this.#r)try{e()}catch(r){console.error("Device cleanup error:",r)}};async fold(e){await this.#t.request("appetizeio.device.server.fold",{hinge:e})}async gesture(e,r){await this.#t.request("appetizeio.device.server.gesture",{options:r,steps:dn(typeof e=="string"?sn(e):e)})}async inspect(e,r){return await this.#t.request("appetizeio.device.server.inspect",{options:r,selector:e?Le(e):void 0})}async open(e){new URL(e),await this.#t.request("appetizeio.device.server.open",{url:e})}async press(e){await this.#t.request("appetizeio.device.server.press",{action:e})}async rotate(e){await this.#t.request("appetizeio.device.server.rotate",{orientation:e})}async screenshot(e,r){const n=await this.#t.request("appetizeio.device.server.screenshot",{options:r,selector:e?Le(e):void 0}),i=this.#e?new URL(n.url,this.#e).href:n.url,s=await fetch(i);if(!s.ok)throw new Error(`Screenshot download failed: ${String(s.status)} ${s.statusText}`);const o=s.headers.get("content-type")??"application/octet-stream";return{data:new Uint8Array(await s.arrayBuffer()),mimeType:o}}async shake(){await this.#t.request("appetizeio.device.server.shake")}async swipe(e,r){await this.#t.request("appetizeio.device.server.swipe",{gesture:bn(e),options:r})}async tap(e,r){await this.#t.request("appetizeio.device.server.tap",{options:r,selector:Ae(e)})}async type(e,r){await this.#t.request("appetizeio.device.server.type",{options:r,steps:Rn(e)})}}function xn(t){const e=new URL(t);return e.protocol==="ws:"?e.protocol="http:":e.protocol==="wss:"&&(e.protocol="https:"),e.href}const Nn=t=>{if(t)return(e,r)=>{e.method.startsWith("appetizeio.device.server.")&&t(e,r)}};let it;try{it=new TextDecoder}catch{}let P,V,d=0;const _n=105,Fn=57342,Tn=57343,$t=57337,Wt=6,ge={};let Je=11281e4,be=1681e4,Ln=1671e4,me=Ln,L={},K,De,je=0,Me=0,H,re,$=[],st=[],Q,Y,ie,Gt={useRecords:!1,mapsAsObjects:!0},Pe=!1,Ht=2;try{new Function("")}catch{Ht=1/0}class ke{constructor(e){if(e&&((e.keyMap||e._keyMap)&&!e.useRecords&&(e.useRecords=!1,e.mapsAsObjects=!0),e.useRecords===!1&&e.mapsAsObjects===void 0&&(e.mapsAsObjects=!0),e.getStructures&&(e.getShared=e.getStructures),e.getShared&&!e.structures&&((e.structures=[]).uninitialized=!0),e.keyMap)){this.mapKey=new Map;for(let[r,n]of Object.entries(e.keyMap))this.mapKey.set(n,r)}Object.assign(this,e)}decodeKey(e){return this.keyMap&&this.mapKey.get(e)||e}encodeKey(e){return this.keyMap&&this.keyMap.hasOwnProperty(e)?this.keyMap[e]:e}encodeKeys(e){if(!this._keyMap)return e;let r=new Map;for(let[n,i]of Object.entries(e))r.set(this._keyMap.hasOwnProperty(n)?this._keyMap[n]:n,i);return r}decodeKeys(e){if(!this._keyMap||e.constructor.name!="Map")return e;if(!this._mapKey){this._mapKey=new Map;for(let[n,i]of Object.entries(this._keyMap))this._mapKey.set(i,n)}let r={};return e.forEach((n,i)=>r[ne(this._mapKey.has(i)?this._mapKey.get(i):i)]=n),r}mapDecode(e,r){let n=this.decode(e);return this._keyMap&&n.constructor.name==="Array"?n.map(i=>this.decodeKeys(i)):n}decode(e,r){if(P)return rr(()=>{ut();try{return this?this.decode(e,r):ke.prototype.decode.call(Gt,e,r)}catch(n){throw n&&typeof n=="object"&&Zt.add(n),n}});V=r>-1?r:e.length,d=0,Me=0,De=null,H=null,P=e;try{Y=e.dataView||(e.dataView=new DataView(e.buffer,e.byteOffset,e.byteLength))}catch(n){throw P=null,e instanceof Uint8Array?n:new Error("Source must be a Uint8Array or Buffer but was a "+(e&&typeof e=="object"?e.constructor.name:typeof e))}if(this instanceof ke){if(L=this,Q=this.sharedValues&&(this.pack?new Array(this.maxPrivatePackedValues||16).concat(this.sharedValues):this.sharedValues),this.structures)return K=this.structures,ze();(!K||K.length>0)&&(K=[])}else L=Gt,(!K||K.length>0)&&(K=[]),Q=null;return ze()}decodeMultiple(e,r){let n,i=0;try{let s=e.length;Pe=!0;let o=this?this.decode(e,s):dt.decode(e,s);if(r){if(r(o)===!1)return;for(;d<s;)if(i=d,r(ze())===!1)return}else{for(n=[o];d<s;)i=d,n.push(ze());return n}}catch(s){throw s.lastPosition=i,s.values=n,s}finally{Pe=!1,ut()}}}const Zt=new WeakSet;let Be;function ze(){try{Be=V-d;let t=U();if(H){if(d>=H.postBundlePosition)throw new Error("Unexpected bundle position");d=H.postBundlePosition,H=null}if(d==V)K=null,P=null,re&&(re=null);else if(d>V){let e=new Error("Unexpected end of CBOR data");throw e.incomplete=!0,e}else if(!Pe)throw new Error("Data read, but end of buffer not reached");return t}catch(t){throw ut(),Zt.has(t)?t.incomplete&&(t.incomplete=!1):(t instanceof RangeError&&d+8>V||t&&typeof t.message=="string"&&t.message.startsWith("Unexpected end of buffer"))&&(t.incomplete=!0),t}}function ee(){let t=new Error("Unexpected end of CBOR data");return t.incomplete=!0,t}function U(){if(!(d<V))throw ee();let t=P[d++],e=t>>5;if(t=t&31,t>23)switch(t){case 24:if(d>=V)throw ee();t=P[d++];break;case 25:if(e==7)return jn();t=Y.getUint16(d),d+=2;break;case 26:if(e==7){let r=Y.getFloat32(d);if(L.useFloat32>2){let n=ft[(P[d]&127)<<1|P[d+1]>>7];return d+=4,(n*r+(r>0?.5:-.5)>>0)/n}return d+=4,r}if(t=Y.getUint32(d),d+=4,e===1)return-1-t;break;case 27:if(e==7){let r=Y.getFloat64(d);return d+=8,r}if(e>1){if(Y.getUint32(d)>0)throw new Error("JavaScript does not support arrays, maps, or strings with length over 4294967295");t=Y.getUint32(d+4)}else L.int64AsNumber?(t=Y.getUint32(d)*4294967296,t+=Y.getUint32(d+4)):t=Y.getBigUint64(d);d+=8;break;case 31:switch(e){case 2:case 3:throw new Error("Indefinite length not supported for byte or text strings");case 4:let r=[],n,i=0;for(;(n=U())!=ge;){if(i>=Je)throw new Error(`Array length exceeds ${Je}`);r[i++]=n}return e==4?r:e==3?r.join(""):Buffer.concat(r);case 5:let s;if(L.mapsAsObjects){let o={},h=0;if(L.keyMap)for(;(s=U())!=ge;){if(h++>=me)throw new Error(`Property count exceeds ${me}`);o[ne(L.decodeKey(s))]=U()}else for(;(s=U())!=ge;){if(h++>=me)throw new Error(`Property count exceeds ${me}`);o[ne(s)]=U()}return o}else{ie&&(L.mapsAsObjects=!0,ie=!1);let o=new Map;if(L.keyMap){let h=0;for(;(s=U())!=ge;){if(h++>=be)throw new Error(`Map size exceeds ${be}`);o.set(L.decodeKey(s),U())}}else{let h=0;for(;(s=U())!=ge;){if(h++>=be)throw new Error(`Map size exceeds ${be}`);o.set(s,U())}}return o}case 7:return ge;default:throw new Error("Invalid major type for indefinite length "+e)}default:throw new Error("Unknown token "+t)}switch(e){case 0:return t;case 1:return~t;case 2:if(t>V-d)throw ee();return Dn(t);case 3:if(Me>=d)return De.slice(d-je,(d+=t)-je);if(t>V-d)throw ee();if(Me==0&&V<140&&t<32){let i=t<16?Yt(t):Jn(t);if(i!=null)return i}return Un(t);case 4:if(t>Je)throw new Error(`Array length exceeds ${Je}`);if(t>V-d||(Be-=t)<0)throw ee();let r=new Array(t);for(let i=0;i<t;i++)r[i]=U();return r;case 5:if(L.mapsAsObjects){if(t>me)throw new Error(`Property count exceeds ${me}`);if(t>(V-d)/2)throw ee();let i={};if(L.keyMap)for(let s=0;s<t;s++)i[ne(L.decodeKey(U()))]=U();else for(let s=0;s<t;s++)i[ne(U())]=U();return i}else{if(ie&&(L.mapsAsObjects=!0,ie=!1),t>be)throw new Error(`Map size exceeds ${be}`);if(t>(V-d)/2)throw ee();let i=new Map;if(L.keyMap)for(let s=0;s<t;s++)i.set(L.decodeKey(U()),U());else for(let s=0;s<t;s++)i.set(U(),U());return i}case 6:if(t>=$t){let i=K[t&8191];if(i)return i.read||(i.read=ot(i)),i.read();if(t<65536){if(t==Tn){let s=Ce(),o=U(),h=U();ct(o,h);let c={};if(L.keyMap)for(let p=2;p<s;p++){let w=L.decodeKey(h[p-2]);c[ne(w)]=U()}else for(let p=2;p<s;p++){let w=h[p-2];c[ne(w)]=U()}return c}else if(t==Fn){let s=Ce(),o=U();for(let h=2;h<s;h++)ct(o++,U());return U()}else if(t==$t)return $n();if(L.getShared&&(lt(),i=K[t&8191],i))return i.read||(i.read=ot(i)),i.read()}}let n=$[t];if(n)return n.handlesRead?n(U):n(U());{let i=U();for(let s=0;s<st.length;s++){let o=st[s](t,i);if(o!==void 0)return o}return new pe(i,t)}case 7:switch(t){case 20:return!1;case 21:return!0;case 22:return null;case 23:return;default:let i=(Q||ye())[t];if(i!==void 0)return i;throw new Error("Unknown token "+t)}default:throw isNaN(t)?ee():new Error("Unknown CBOR token "+t)}}const Xt=/^[a-zA-Z_$][a-zA-Z\d_$]*$/;function ot(t){if(!t)throw new Error("Structure is required in record definition");function e(){let r=P[d++];if(r=r&31,r>23)switch(r){case 24:r=P[d++];break;case 25:r=Y.getUint16(d),d+=2;break;case 26:r=Y.getUint32(d),d+=4;break;default:throw new Error("Expected array header, but got "+P[d-1])}let n=this.compiledReader;for(;n;){if(n.propertyCount===r)return n(U);n=n.next}if(this.slowReads++>=Ht){let s=this.length==r?this:this.slice(0,r);return n=L.keyMap?new Function("r","return {"+s.map(o=>L.decodeKey(o)).map(o=>Xt.test(o)?ne(o)+":r()":"["+JSON.stringify(o)+"]:r()").join(",")+"}"):new Function("r","return {"+s.map(o=>Xt.test(o)?ne(o)+":r()":"["+JSON.stringify(o)+"]:r()").join(",")+"}"),this.compiledReader&&(n.next=this.compiledReader),n.propertyCount=r,this.compiledReader=n,n(U)}let i={};if(L.keyMap)for(let s=0;s<r;s++)i[ne(L.decodeKey(this[s]))]=U();else for(let s=0;s<r;s++)i[ne(this[s])]=U();return i}return t.slowReads=0,e}function ne(t){if(typeof t=="string")return t==="__proto__"?"__proto_":t;if(typeof t=="number"||typeof t=="boolean"||typeof t=="bigint")return t.toString();if(t==null)return t+"";throw new Error("Invalid property name type "+typeof t)}let Un=at;function at(t){let e;if(t<16&&(e=Yt(t)))return e;if(t>64&&it)return it.decode(P.subarray(d,d+=t));const r=d+t,n=[];for(e="";d<r;){const i=P[d++];if((i&128)===0)n.push(i);else if((i&224)===192)if(i<194||d>=r||(P[d]&192)!==128)n.push(65533);else{const s=P[d++]&63;n.push((i&31)<<6|s)}else if((i&240)===224){const s=d<r?P[d]:0;if(d>=r||(s&192)!==128||i===224&&s<160||i===237&&s>=160)n.push(65533);else if(d++,d>=r||(P[d]&192)!==128)n.push(65533);else{const o=P[d++]&63;n.push((i&31)<<12|(s&63)<<6|o)}}else if((i&248)===240){const s=d<r?P[d]:0;if(i>244||d>=r||(s&192)!==128||i===240&&s<144||i===244&&s>=144)n.push(65533);else if(d++,d>=r||(P[d]&192)!==128)n.push(65533);else{const o=P[d++]&63;if(d>=r||(P[d]&192)!==128)n.push(65533);else{const h=P[d++]&63;let c=(i&7)<<18|(s&63)<<12|o<<6|h;c-=65536,n.push(c>>>10&1023|55296),n.push(56320|c&1023)}}}else n.push(65533);n.length>=4096&&(e+=Z.apply(String,n),n.length=0)}return n.length>0&&(e+=Z.apply(String,n)),e}let Z=String.fromCharCode;function Jn(t){let e=d,r=new Array(t);for(let n=0;n<t;n++){const i=P[d++];if((i&128)>0){d=e;return}r[n]=i}return Z.apply(String,r)}function Yt(t){if(t<4)if(t<2){if(t===0)return"";{let e=P[d++];if((e&128)>1){d-=1;return}return Z(e)}}else{let e=P[d++],r=P[d++];if((e&128)>0||(r&128)>0){d-=2;return}if(t<3)return Z(e,r);let n=P[d++];if((n&128)>0){d-=3;return}return Z(e,r,n)}else{let e=P[d++],r=P[d++],n=P[d++],i=P[d++];if((e&128)>0||(r&128)>0||(n&128)>0||(i&128)>0){d-=4;return}if(t<6){if(t===4)return Z(e,r,n,i);{let s=P[d++];if((s&128)>0){d-=5;return}return Z(e,r,n,i,s)}}else if(t<8){let s=P[d++],o=P[d++];if((s&128)>0||(o&128)>0){d-=6;return}if(t<7)return Z(e,r,n,i,s,o);let h=P[d++];if((h&128)>0){d-=7;return}return Z(e,r,n,i,s,o,h)}else{let s=P[d++],o=P[d++],h=P[d++],c=P[d++];if((s&128)>0||(o&128)>0||(h&128)>0||(c&128)>0){d-=8;return}if(t<10){if(t===8)return Z(e,r,n,i,s,o,h,c);{let p=P[d++];if((p&128)>0){d-=9;return}return Z(e,r,n,i,s,o,h,c,p)}}else if(t<12){let p=P[d++],w=P[d++];if((p&128)>0||(w&128)>0){d-=10;return}if(t<11)return Z(e,r,n,i,s,o,h,c,p,w);let y=P[d++];if((y&128)>0){d-=11;return}return Z(e,r,n,i,s,o,h,c,p,w,y)}else{let p=P[d++],w=P[d++],y=P[d++],v=P[d++];if((p&128)>0||(w&128)>0||(y&128)>0||(v&128)>0){d-=12;return}if(t<14){if(t===12)return Z(e,r,n,i,s,o,h,c,p,w,y,v);{let f=P[d++];if((f&128)>0){d-=13;return}return Z(e,r,n,i,s,o,h,c,p,w,y,v,f)}}else{let f=P[d++],S=P[d++];if((f&128)>0||(S&128)>0){d-=14;return}if(t<15)return Z(e,r,n,i,s,o,h,c,p,w,y,v,f,S);let g=P[d++];if((g&128)>0){d-=15;return}return Z(e,r,n,i,s,o,h,c,p,w,y,v,f,S,g)}}}}}function Dn(t){return L.copyBuffers?Uint8Array.prototype.slice.call(P,d,d+=t):P.subarray(d,d+=t)}let Qt=new Float32Array(1),qe=new Uint8Array(Qt.buffer,0,4);function jn(){let t=P[d++],e=P[d++],r=(t&127)>>2;if(r===31)return e||t&3?NaN:t&128?-1/0:1/0;if(r===0){let n=((t&3)<<8|e)/16777216;return t&128?-n:n}return qe[3]=t&128|(r>>1)+56,qe[2]=(t&7)<<5|e>>3,qe[1]=e<<5,qe[0]=0,Qt[0]}new Array(4096);class pe{constructor(e,r){this.value=e,this.tag=r}}$[0]=t=>new Date(t),$[1]=t=>new Date(Math.round(t*1e3)),$[2]=t=>{let e=BigInt(0);for(let r=0,n=t.byteLength;r<n;r++)e=BigInt(t[r])+(e<<BigInt(8));return e},$[3]=t=>BigInt(-1)-$[2](t),$[4]=t=>+(t[1]+"e"+t[0]),$[5]=t=>t[1]*Math.exp(t[0]*Math.log(2));const ct=(t,e)=>{t=t-57344;let r=K[t];r&&r.isShared&&((K.restoreStructures||(K.restoreStructures=[]))[t]=r),K[t]=e,e.read=ot(e)};$[_n]=t=>{let e=t.length,r=t[1];ct(t[0],r);let n={};for(let i=2;i<e;i++){let s=r[i-2];n[ne(s)]=t[i]}return n},$[14]=t=>H?H[0].slice(H.position0,H.position0+=t):new pe(t,14),$[15]=t=>H?H[1].slice(H.position1,H.position1+=t):new pe(t,15);let Bn={Error,RegExp};$[27]=t=>(Bn[t[0]]||Error)(t[1],t[2]);const er=t=>{if(!(d<V))throw ee();if(P[d++]!=132)throw new Error("Packed values structure must be followed by a 4 element array");let e=t();if(!Array.isArray(e)||!e.length)throw new Error("Packed values structure must be followed by a 4 element array");return Q=Q?e.concat(Q.slice(e.length)):e,Q.prefixes=t(),Q.suffixes=t(),t()};er.handlesRead=!0,$[51]=er,$[Wt]=t=>{if(!Q)if(L.getShared)lt();else return new pe(t,Wt);if(typeof t=="number")return Q[16+(t>=0?2*t:-2*t-1)];throw new Error("No support for non-integer packed references yet")},$[28]=t=>{re||(re=new Map,re.id=0);let e=re.id++,r=d,n=P[d],i;n>>5==4?i=[]:i={};let s={target:i};re.set(e,s);let o=t();return s.used?(Object.getPrototypeOf(i)!==Object.getPrototypeOf(o)&&(d=r,i=o,re.set(e,{target:i}),o=t()),Object.assign(i,o)):(s.target=o,o)},$[28].handlesRead=!0,$[29]=t=>{let e=re.get(t);return e.used=!0,e.target},$[258]=t=>new Set(t),($[259]=t=>{let e=L;if(e.mapsAsObjects){e.mapsAsObjects=!1,ie=!0;try{return t()}finally{ie&&(e.mapsAsObjects=!0,ie=!1)}}return t()}).handlesRead=!0;function Se(t,e){return typeof t=="string"?t+e:t instanceof Array?t.concat(e):Object.assign({},t,e)}function ye(){if(!Q)if(L.getShared)lt();else throw new Error("No packed values available");return Q}const zn=1399353956;st.push((t,e)=>{if(t>=225&&t<=255)return Se(ye().prefixes[t-224],e);if(t>=28704&&t<=32767)return Se(ye().prefixes[t-28672],e);if(t>=1879052288&&t<=2147483647)return Se(ye().prefixes[t-1879048192],e);if(t>=216&&t<=223)return Se(e,ye().suffixes[t-216]);if(t>=27647&&t<=28671)return Se(e,ye().suffixes[t-27639]);if(t>=1811940352&&t<=1879048191)return Se(e,ye().suffixes[t-1811939328]);if(t==zn)return{packedValues:Q,structures:K.slice(0),version:e};if(t==55799)return e});const qn=new Uint8Array(new Uint16Array([1]).buffer)[0]==1,tr=[Uint8Array,Uint8ClampedArray,Uint16Array,Uint32Array,typeof BigUint64Array>"u"?{name:"BigUint64Array"}:BigUint64Array,Int8Array,Int16Array,Int32Array,typeof BigInt64Array>"u"?{name:"BigInt64Array"}:BigInt64Array,Float32Array,Float64Array],Kn=[64,68,69,70,71,72,77,78,79,85,86];for(let t=0;t<tr.length;t++)Vn(tr[t],Kn[t]);function Vn(t,e){let r="get"+t.name.slice(0,-5),n;typeof t=="function"?n=t.BYTES_PER_ELEMENT:t=null;for(let i=0;i<2;i++){if(!i&&n==1)continue;let s=n==2?1:n==4?2:n==8?3:0;$[i?e:e-4]=n==1||i==qn?o=>{if(!t)throw new Error("Could not find typed array for code "+e);return!L.copyBuffers&&(n===1||n===2&&!(o.byteOffset&1)||n===4&&!(o.byteOffset&3)||n===8&&!(o.byteOffset&7))?new t(o.buffer,o.byteOffset,o.byteLength>>s):new t(Uint8Array.prototype.slice.call(o,0).buffer)}:o=>{if(!t)throw new Error("Could not find typed array for code "+e);let h=new DataView(o.buffer,o.byteOffset,o.byteLength),c=o.length>>s,p=new t(c),w=h[r];for(let y=0;y<c;y++)p[y]=w.call(h,y<<s,i);return p}}}function $n(){let t=Ce(),e=d+U();for(let n=2;n<t;n++){let i=Ce();d+=i}let r=d;return d=e,H=[at(Ce()),at(Ce())],H.position0=0,H.position1=0,H.postBundlePosition=d,d=r,U()}function Ce(){if(!(d<V))throw ee();let t=P[d++]&31;if(t>23)switch(t){case 24:if(d>=V)throw ee();t=P[d++];break;case 25:if(d+2>V)throw ee();t=Y.getUint16(d),d+=2;break;case 26:if(d+4>V)throw ee();t=Y.getUint32(d),d+=4;break}return t}function lt(){if(L.getShared){let t=rr(()=>(P=null,L.getShared()))||{},e=t.structures||[];L.sharedVersion=t.version,Q=L.sharedValues=t.packedValues,K===!0?L.structures=K=e:K.splice.apply(K,[0,e.length].concat(e))}}function rr(t){let e=V,r=d,n=je,i=Me,s=De,o=re,h=H,c=new Uint8Array(P.slice(0,V)),p=K,w=L,y=Pe,v=ie,f=Be;ie=!1;try{return t()}finally{V=e,d=r,je=n,Me=i,De=s,re=o,H=h,P=c,Pe=y,K=p,L=w,ie=v,Be=f,Y=new DataView(P.buffer,P.byteOffset,P.byteLength)}}function ut(){P=null,re=null,K=null}const ft=new Array(147);for(let t=0;t<256;t++)ft[t]=+("1e"+Math.floor(45.15-t*.30103));let dt=new ke({useRecords:!1});const nr=dt.decode;dt.decodeMultiple;let Ke;try{Ke=new TextEncoder}catch{}let ht,ir;const Ve=typeof globalThis=="object"&&globalThis.Buffer,Ie=typeof Ve<"u",pt=Ie?Ve.allocUnsafeSlow:Uint8Array,sr=Ie?Ve:Uint8Array,or=256,ar=Ie?4294967296:2144337920;let yt,u,B,a=0,fe,W=null;const Wn=61440,Gn=/[\u0080-\uFFFF]/,te=Symbol("record-id");class Hn extends ke{constructor(e){super(e),this.offset=0;let r,n,i,s,o;e=e||{};let h=sr.prototype.utf8Write?function(l,I){return u.utf8Write(l,I,u.byteLength-I)}:Ke&&Ke.encodeInto?function(l,I){return Ke.encodeInto(l,u.subarray(I)).written}:!1,c=this,p=e.structures||e.saveStructures,w=e.maxSharedStructures;if(w==null&&(w=p?128:0),w>8190)throw new Error("Maximum maxSharedStructure is 8190");let y=e.sequential;y&&(w=0),this.structures||(this.structures=[]),this.saveStructures&&(this.saveShared=this.saveStructures);let v,f,S=e.sharedValues,g;if(S){g=Object.create(null);for(let l=0,I=S.length;l<I;l++)g[S[l]]=l}let C=[],b=0,E=0;this.mapEncode=function(l,I){return this._keyMap&&!this._mapped&&l.constructor.name==="Array"&&(l=l.map(R=>this.encodeKeys(R))),this.encode(l,I)},this.encode=function(l,I){if(u||(u=new pt(8192),B=new DataView(u.buffer,0,8192),a=0),fe=u.length-10,fe-a<2048?(u=new pt(u.length),B=new DataView(u.buffer,0,u.length),fe=u.length-10,a=0):I===fr&&(a=a+7&2147483640),r=a,c.useSelfDescribedHeader&&(B.setUint32(a,3654940416),a+=3),o=c.structuredClone?new Map:null,c.bundleStrings&&typeof l!="string"?(W=[],W.size=1/0):W=null,n=c.structures,n){if(n.uninitialized){let O=c.getShared()||{};c.structures=n=O.structures||[],c.sharedVersion=O.version;let m=c.sharedValues=O.packedValues;if(m){g={};for(let x=0,N=m.length;x<N;x++)g[m[x]]=x}}let R=n.length;if(R>w&&!y&&(R=w),!n.transitions){n.transitions=Object.create(null);for(let O=0;O<R;O++){let m=n[O];if(!m)continue;let x,N=n.transitions;for(let F=0,T=m.length;F<T;F++){N[te]===void 0&&(N[te]=O);let J=m[F];x=N[J],x||(x=N[J]=Object.create(null)),N=x}N[te]=O|1048576}}y||(n.nextId=R)}if(i&&(i=!1),s=n||[],f=g,e.pack){let R=new Map;if(R.values=[],R.encoder=c,R.maxValues=e.maxPrivatePackedValues||(g?16:1/0),R.objectMap=g||!1,R.samplingPackedValues=v,$e(l,R),R.values.length>0){u[a++]=216,u[a++]=51,se(4);let O=R.values;A(O),se(0),se(0),f=Object.create(g||null);for(let m=0,x=O.length;m<x;m++)f[O[m]]=m}}yt=I&bt;try{if(yt)return;if(A(l),W&&W.position&&ur(r,A),c.offset=a,o&&o.idsToInsert){a+=o.idsToInsert.length*2,a>fe&&M(a),c.offset=a;let R=Yn(u.subarray(r,a),o.idsToInsert);return o=null,R}return I&fr?(u.start=r,u.end=a,u):u.subarray(r,a)}finally{if(n){if(E<10&&E++,n.length>w&&(n.length=w),b>1e4)n.transitions=null,E=0,b=0,C.length>0&&(C=[]);else if(C.length>0&&!y){for(let R=0,O=C.length;R<O;R++)C[R][te]=void 0;C=[]}}if(i&&c.saveShared){c.structures.length>w&&(c.structures=c.structures.slice(0,w));let R=u.subarray(r,a);return c.updateSharedData()===!1?c.encode(l):R}I&ei&&(a=r)}},this.findCommonStringsToPack=()=>(v=new Map,g||(g=Object.create(null)),l=>{let I=l&&l.threshold||4,R=this.pack?l.maxPrivatePackedValues||16:0;S||(S=this.sharedValues=[]);for(let[O,m]of v)m.count>I&&(g[O]=R++,S.push(O),i=!0);for(;this.saveShared&&this.updateSharedData()===!1;);v=null});const A=l=>{a>fe&&(u=M(a));var I=typeof l,R;if(I==="string"){if(f){let N=f[l];if(N>=0){N<16?u[a++]=N+224:(u[a++]=198,N&1?A(15-N>>1):A(N-16>>1));return}else if(v&&!e.pack){let F=v.get(l);F?F.count++:v.set(l,{count:1})}}let O=l.length;if(W&&O>=4&&O<1024){if((W.size+=O)>Wn){let F,T=(W[0]?W[0].length*3+W[1].length:0)+10;a+T>fe&&(u=M(a+T)),u[a++]=217,u[a++]=223,u[a++]=249,u[a++]=W.position?132:130,u[a++]=26,F=a-r,a+=4,W.position&&ur(r,A),W=["",""],W.size=0,W.position=F}let N=Gn.test(l);W[N?0:1]+=l,u[a++]=N?206:207,A(O);return}let m;O<32?m=1:O<256?m=2:O<65536?m=3:m=5;let x=O*3;if(a+x>fe&&(u=M(a+x)),O<64||!h){let N,F,T,J=a+m;for(N=0;N<O;N++)F=l.charCodeAt(N),F<128?u[J++]=F:F<2048?(u[J++]=F>>6|192,u[J++]=F&63|128):(F&64512)===55296&&((T=l.charCodeAt(N+1))&64512)===56320?(F=65536+((F&1023)<<10)+(T&1023),N++,u[J++]=F>>18|240,u[J++]=F>>12&63|128,u[J++]=F>>6&63|128,u[J++]=F&63|128):(u[J++]=F>>12|224,u[J++]=F>>6&63|128,u[J++]=F&63|128);R=J-a-m}else R=h(l,a+m,x);R<24?u[a++]=96|R:R<256?(m<2&&u.copyWithin(a+2,a+1,a+1+R),u[a++]=120,u[a++]=R):R<65536?(m<3&&u.copyWithin(a+3,a+2,a+2+R),u[a++]=121,u[a++]=R>>8,u[a++]=R&255):(m<5&&u.copyWithin(a+5,a+3,a+3+R),u[a++]=122,B.setUint32(a,R),a+=4),a+=R}else if(I==="number")if(!this.alwaysUseFloat&&l>>>0===l)l<24?u[a++]=l:l<256?(u[a++]=24,u[a++]=l):l<65536?(u[a++]=25,u[a++]=l>>8,u[a++]=l&255):(u[a++]=26,B.setUint32(a,l),a+=4);else if(!this.alwaysUseFloat&&l>>0===l)l>=-24?u[a++]=31-l:l>=-256?(u[a++]=56,u[a++]=~l):l>=-65536?(u[a++]=57,B.setUint16(a,~l),a+=2):(u[a++]=58,B.setUint32(a,~l),a+=4);else if(!this.alwaysUseFloat&&l<0&&l>=-4294967296&&Math.floor(l)===l)u[a++]=58,B.setUint32(a,-1-l),a+=4;else{let O;if((O=this.useFloat32)>0&&l<4294967296&&l>=-2147483648){u[a++]=250,B.setFloat32(a,l);let m;if(O<4||(m=l*ft[(u[a]&127)<<1|u[a+1]>>7])>>0===m){a+=4;return}else a--}u[a++]=251,B.setFloat64(a,l),a+=8}else if(I==="object")if(!l)u[a++]=246;else{if(o){let m=o.get(l);if(m){if(u[a++]=216,u[a++]=29,u[a++]=25,!m.references){let x=o.idsToInsert||(o.idsToInsert=[]);m.references=[],x.push(m)}m.references.push(a-r),a+=2;return}else o.set(l,{offset:a-r})}let O=l.constructor;if(O===Object)this.skipFunction===!0&&(l=Object.fromEntries([...Object.keys(l).filter(m=>typeof l[m]!="function").map(m=>[m,l[m]])])),k(l);else if(O===Array){R=l.length,R<24?u[a++]=128|R:se(R);for(let m=0;m<R;m++)A(l[m])}else if(O===Map)if((this.mapsAsObjects?this.useTag259ForMaps!==!1:this.useTag259ForMaps)&&(u[a++]=217,u[a++]=1,u[a++]=3),R=l.size,R<24?u[a++]=160|R:R<256?(u[a++]=184,u[a++]=R):R<65536?(u[a++]=185,u[a++]=R>>8,u[a++]=R&255):(u[a++]=186,B.setUint32(a,R),a+=4),c.keyMap)for(let[m,x]of l)A(c.encodeKey(m)),A(x);else for(let[m,x]of l)A(m),A(x);else{for(let m=0,x=ht.length;m<x;m++){let N=ir[m];if(l instanceof N){let F=ht[m],T=F.tag;T==null&&(T=F.getTag&&F.getTag.call(this,l)),T<24?u[a++]=192|T:T<256?(u[a++]=216,u[a++]=T):T<65536?(u[a++]=217,u[a++]=T>>8,u[a++]=T&255):T>-1&&(u[a++]=218,B.setUint32(a,T),a+=4),F.encode.call(this,l,A,M);return}}if(l[Symbol.iterator]){if(yt){let m=new Error("Iterable should be serialized as iterator");throw m.iteratorNotHandled=!0,m}u[a++]=159;for(let m of l)A(m);u[a++]=255;return}if(l[Symbol.asyncIterator]||wt(l)){let m=new Error("Iterable/blob should be serialized as iterator");throw m.iteratorNotHandled=!0,m}if(this.useToJSON&&l.toJSON){const m=l.toJSON();if(m!==l)return A(m)}k(l)}}else if(I==="boolean")u[a++]=l?245:244;else if(I==="bigint"){if(l<BigInt(1)<<BigInt(64)&&l>=0)u[a++]=27,B.setBigUint64(a,l);else if(l>-(BigInt(1)<<BigInt(64))&&l<0)u[a++]=59,B.setBigUint64(a,-l-BigInt(1));else if(this.largeBigIntToFloat)u[a++]=251,B.setFloat64(a,Number(l));else{l>=BigInt(0)?u[a++]=194:(u[a++]=195,l=BigInt(-1)-l);let O=[];for(;l;)O.push(Number(l&BigInt(255))),l>>=BigInt(8);vt(new Uint8Array(O.reverse()),M);return}a+=8}else if(I==="undefined")u[a++]=247;else throw new Error("Unknown type: "+I)},k=this.useRecords===!1?this.variableMapSize?l=>{let I=Object.keys(l),R=Object.values(l),O=I.length;if(O<24?u[a++]=160|O:O<256?(u[a++]=184,u[a++]=O):O<65536?(u[a++]=185,u[a++]=O>>8,u[a++]=O&255):(u[a++]=186,B.setUint32(a,O),a+=4),c.keyMap)for(let m=0;m<O;m++)A(c.encodeKey(I[m])),A(R[m]);else for(let m=0;m<O;m++)A(I[m]),A(R[m])}:l=>{u[a++]=185;let I=a-r;a+=2;let R=0;if(c.keyMap)for(let O in l)(typeof l.hasOwnProperty!="function"||l.hasOwnProperty(O))&&(A(c.encodeKey(O)),A(l[O]),R++);else for(let O in l)(typeof l.hasOwnProperty!="function"||l.hasOwnProperty(O))&&(A(O),A(l[O]),R++);u[I+++r]=R>>8,u[I+r]=R&255}:(l,I)=>{let R,O=s.transitions||(s.transitions=Object.create(null)),m=0,x=0,N,F;if(this.keyMap){F=Object.keys(l).map(J=>this.encodeKey(J)),x=F.length;for(let J=0;J<x;J++){let St=F[J];R=O[St],R||(R=O[St]=Object.create(null),m++),O=R}}else for(let J in l)(typeof l.hasOwnProperty!="function"||l.hasOwnProperty(J))&&(R=O[J],R||(O[te]&1048576&&(N=O[te]&65535),R=O[J]=Object.create(null),m++),O=R,x++);let T=O[te];if(T!==void 0)T&=65535,u[a++]=217,u[a++]=T>>8|224,u[a++]=T&255;else if(F||(F=O.__keys__||(O.__keys__=Object.keys(l))),N===void 0?(T=s.nextId++,T||(T=0,s.nextId=1),T>=or&&(s.nextId=(T=w)+1)):T=N,s[T]=F,T<w){u[a++]=217,u[a++]=T>>8|224,u[a++]=T&255,O=s.transitions;for(let J=0;J<x;J++)(O[te]===void 0||O[te]&1048576)&&(O[te]=T),O=O[F[J]];O[te]=T|1048576,i=!0}else{if(O[te]=T,B.setUint32(a,3655335680),a+=3,m&&(b+=E*m),C.length>=or-w&&(C.shift()[te]=void 0),C.push(O),se(x+2),A(57344+T),A(F),I)return;for(let J in l)(typeof l.hasOwnProperty!="function"||l.hasOwnProperty(J))&&A(l[J]);return}if(x<24?u[a++]=128|x:se(x),!I)for(let J in l)(typeof l.hasOwnProperty!="function"||l.hasOwnProperty(J))&&A(l[J])},M=l=>{let I;if(l>16777216){if(l-r>ar)throw new Error("Encoded buffer would be larger than maximum buffer size");I=Math.min(ar,Math.round(Math.max((l-r)*(l>67108864?1.25:2),4194304)/4096)*4096)}else I=(Math.max(l-r<<2,u.length-1)>>12)+1<<12;let R=new pt(I);return B=new DataView(R.buffer,0,I),u.copy?u.copy(R,0,r,l):R.set(u.slice(r,l)),a-=r,r=0,fe=R.length-10,u=R};let D=100,z=1e3;this.encodeAsIterable=function(l,I){return ve(l,I,X)},this.encodeAsAsyncIterable=function(l,I){return ve(l,I,mt)};function*X(l,I,R){let O=l.constructor;if(O===Object){let m=c.useRecords!==!1;m?k(l,!0):cr(Object.keys(l).length,160);for(let x in l){let N=l[x];m||A(x),N&&typeof N=="object"?I[x]?yield*X(N,I[x]):yield*_(N,I,x):A(N)}}else if(O===Array){let m=l.length;se(m);for(let x=0;x<m;x++){let N=l[x];N&&(typeof N=="object"||a-r>D)?I.element?yield*X(N,I.element):yield*_(N,I,"element"):A(N)}}else if(l[Symbol.iterator]&&!l.buffer){u[a++]=159;for(let m of l)m&&(typeof m=="object"||a-r>D)?I.element?yield*X(m,I.element):yield*_(m,I,"element"):A(m);u[a++]=255}else wt(l)?(cr(l.size,64),yield u.subarray(r,a),yield l,G()):l[Symbol.asyncIterator]?(u[a++]=159,yield u.subarray(r,a),yield l,G(),u[a++]=255):A(l);R&&a>r?yield u.subarray(r,a):a-r>D&&(yield u.subarray(r,a),G())}function*_(l,I,R){let O=a-r;try{A(l),a-r>D&&(yield u.subarray(r,a),G())}catch(m){if(m.iteratorNotHandled)I[R]={},a=r+O,yield*X.call(this,l,I[R]);else throw m}}function G(){D=z,c.encode(null,bt)}function ve(l,I,R){return I&&I.chunkThreshold?D=z=I.chunkThreshold:D=100,l&&typeof l=="object"?(c.encode(null,bt),R(l,c.iterateProperties||(c.iterateProperties={}),!0)):[c.encode(l)]}async function*mt(l,I){for(let R of X(l,I,!0)){let O=R.constructor;if(O===sr||O===Uint8Array)yield R;else if(wt(R)){let m=R.stream().getReader(),x;for(;!(x=await m.read()).done;)yield x.value}else if(R[Symbol.asyncIterator])for await(let m of R)G(),m?yield*mt(m,I.async||(I.async={})):yield c.encode(m);else yield R}}}useBuffer(e){u=e,B=new DataView(u.buffer,u.byteOffset,u.byteLength),a=0}clearSharedData(){this.structures&&(this.structures=[]),this.sharedValues&&(this.sharedValues=void 0)}updateSharedData(){let e=this.sharedVersion||0;this.sharedVersion=e+1;let r=this.structures.slice(0),n=new lr(r,this.sharedValues,this.sharedVersion),i=this.saveShared(n,s=>(s&&s.version||0)==e);return i===!1?(n=this.getShared()||{},this.structures=n.structures||[],this.sharedValues=n.packedValues,this.sharedVersion=n.version,this.structures.nextId=this.structures.length):r.forEach((s,o)=>this.structures[o]=s),i}}function cr(t,e){t<24?u[a++]=e|t:t<256?(u[a++]=e|24,u[a++]=t):t<65536?(u[a++]=e|25,u[a++]=t>>8,u[a++]=t&255):(u[a++]=e|26,B.setUint32(a,t),a+=4)}class lr{constructor(e,r,n){this.structures=e,this.packedValues=r,this.version=n}}function se(t){t<24?u[a++]=128|t:t<256?(u[a++]=152,u[a++]=t):t<65536?(u[a++]=153,u[a++]=t>>8,u[a++]=t&255):(u[a++]=154,B.setUint32(a,t),a+=4)}const Zn=typeof Blob>"u"?function(){}:Blob;function wt(t){if(t instanceof Zn)return!0;let e=t[Symbol.toStringTag];return e==="Blob"||e==="File"}function $e(t,e){switch(typeof t){case"string":if(t.length>3){if(e.objectMap[t]>-1||e.values.length>=e.maxValues)return;let n=e.get(t);if(n)++n.count==2&&e.values.push(t);else if(e.set(t,{count:1}),e.samplingPackedValues){let i=e.samplingPackedValues.get(t);i?i.count++:e.samplingPackedValues.set(t,{count:1})}}break;case"object":if(t)if(t instanceof Array)for(let n=0,i=t.length;n<i;n++)$e(t[n],e);else{let n=!e.encoder.useRecords;for(var r in t)t.hasOwnProperty(r)&&(n&&$e(r,e),$e(t[r],e))}break;case"function":console.log(t)}}const Xn=new Uint8Array(new Uint16Array([1]).buffer)[0]==1;ir=[Date,Set,Error,RegExp,pe,ArrayBuffer,Uint8Array,Uint8ClampedArray,Uint16Array,Uint32Array,typeof BigUint64Array>"u"?function(){}:BigUint64Array,Int8Array,Int16Array,Int32Array,typeof BigInt64Array>"u"?function(){}:BigInt64Array,Float32Array,Float64Array,lr],ht=[{tag:1,encode(t,e){let r=t.getTime()/1e3;(this.useTimestamp32||t.getMilliseconds()===0)&&r>=0&&r<4294967296?(u[a++]=26,B.setUint32(a,r),a+=4):(u[a++]=251,B.setFloat64(a,r),a+=8)}},{tag:258,encode(t,e){let r=Array.from(t);e(r)}},{tag:27,encode(t,e){e([t.name,t.message])}},{tag:27,encode(t,e){e(["RegExp",t.source,t.flags])}},{getTag(t){return t.tag},encode(t,e){e(t.value)}},{encode(t,e,r){vt(t,r)}},{getTag(t){if(t.constructor===Uint8Array&&(this.tagUint8Array||Ie&&this.tagUint8Array!==!1))return 64},encode(t,e,r){vt(t,r)}},oe(68,1),oe(69,2),oe(70,4),oe(71,8),oe(72,1),oe(77,2),oe(78,4),oe(79,8),oe(85,4),oe(86,8),{encode(t,e){let r=t.packedValues||[],n=t.structures||[];if(r.values.length>0){u[a++]=216,u[a++]=51,se(4);let i=r.values;e(i),se(0),se(0),packedObjectMap=Object.create(sharedPackedObjectMap||null);for(let s=0,o=i.length;s<o;s++)packedObjectMap[i[s]]=s}if(n){B.setUint32(a,3655335424),a+=3;let i=n.slice(0);i.unshift(57344),i.push(new pe(t.version,1399353956)),e(i)}else e(new pe(t.version,1399353956))}}];function oe(t,e){return!Xn&&e>1&&(t-=4),{tag:t,encode:function(n,i){let s=n.byteLength,o=n.byteOffset||0,h=n.buffer||n;i(Ie?Ve.from(h,o,s):new Uint8Array(h,o,s))}}}function vt(t,e){let r=t.byteLength;r<24?u[a++]=64+r:r<256?(u[a++]=88,u[a++]=r):r<65536?(u[a++]=89,u[a++]=r>>8,u[a++]=r&255):(u[a++]=90,B.setUint32(a,r),a+=4),a+r>=u.length&&e(a+r),u.set(t.buffer?t:new Uint8Array(t),a),a+=r}function Yn(t,e){let r,n=e.length*2,i=t.length-n;e.sort((s,o)=>s.offset>o.offset?1:-1);for(let s=0;s<e.length;s++){let o=e[s];o.id=s;for(let h of o.references)t[h++]=s>>8,t[h]=s&255}for(;r=e.pop();){let s=r.offset;t.copyWithin(s+n,s,i),n-=2;let o=s+n;t[o++]=216,t[o++]=28,i=s}return t}function ur(t,e){B.setUint32(W.position+t,a-W.position-t+1);let r=W;W=null,e(r[0]),e(r[1])}let gt=new Hn({useRecords:!1});const Qn=gt.encode;gt.encodeAsIterable,gt.encodeAsAsyncIterable;const fr=512,ei=1024,bt=2048,ti=Ee("appetize.io:transport:ws-ping"),ri=3e4;function ni(t){let e=!0;const r=()=>{e=!0};t.on("pong",r);const n=setInterval(()=>{if(!e){clearInterval(n),ti("liveness ping went unanswered, terminating"),t.terminate();return}t.readyState===t.OPEN&&(e=!1,t.ping())},ri);return{destroy(){clearInterval(n),t.off("pong",r)},pong:r}}const we=Ee("appetize.io:trace:transport:websocket");class ii extends Te{constructor(e,{signal:r}={}){super(async i=>{this.#i.send(Qn(i))},{signal:r}),this.wsOrUrl=e,typeof e=="string"?(this.#i=new WebSocket(e),this.#i.binaryType="arraybuffer"):this.#i=e;const n=this.#i;if(n instanceof WebSocket?(n.addEventListener("open",this.#l),n.addEventListener("message",this.#c),n.addEventListener("error",this.#s),n.addEventListener("close",this.#a),this.#e.push(()=>{n.removeEventListener("open",this.#l),n.removeEventListener("message",this.#c),n.removeEventListener("error",this.#s),n.removeEventListener("close",this.#a)})):(n.addEventListener("open",this.#l),n.addEventListener("message",this.#c),n.addEventListener("error",this.#s),n.addEventListener("close",this.#a),this.#e.push(()=>{n.removeEventListener("open",this.#l),n.removeEventListener("message",this.#c),n.removeEventListener("error",this.#s),n.removeEventListener("close",this.#a)})),this.send=n.send.bind(n),"ping"in n){const{destroy:i,pong:s}=ni(n);this.#n=s,this.#e.push(i)}}wsOrUrl;onclose;onerror;onmessage;onopen;send;get bufferedAmount(){return this.#i.bufferedAmount}get readyState(){return this.#i.readyState}#e=[];#r=!1;#t=!1;#n;#i;close({destroyWs:e=!1,...r}={}){this.closed||(this.#r=e,super.close(r))}handleClose(e){we("close()");for(const r of this.#e.splice(0))r();if((typeof this.wsOrUrl=="string"||this.#r)&&(this.#i.close(e.code,e.reason),"terminate"in this.#i)){const r=this.#i;setTimeout(()=>{r.terminate()},100)}this.#o(),super.handleClose(e)}#o(e){this.#t||(this.#t=!0,this.onclose?.(e))}#a=e=>{we("handleWebSocketClose()",e);try{this.#o(e)}finally{this.close()}};#s=e=>{we("handleWebSocketError()",e),this.onerror?.(e)};#c=async e=>{we("handleWebSocketMessage()",e),this.#n?.();const r=this.#u(e);if(!r){we("handleWebSocketMessage() -> legacy"),this.onmessage?.(e);return}we("handleWebSocketMessage() -> jsonrpc",r),this[j].dispatchMessage(r)};#l=e=>{we("handleWebSocketOpen()",e),this.onopen?.(e)};#u(e){try{const r=nr(new Uint8Array(e.data));return Lt(r)?r:null}catch{return null}}}function si(t){return typeof t=="object"&&t!==null}function oi(t){try{const e=nr(new Uint8Array(t.data));if(si(e)&&typeof e.name=="string")return{name:e.name,payload:"payload"in e?e.payload:void 0}}catch{}}async function ai(t,e={}){const r=e.baseUrl??(typeof t=="string"?new URL(t).origin:void 0),n=typeof t=="string"?new ii(t,{signal:e.signal}):t,i=new kn(n,{...e,baseUrl:r});return typeof t=="string"&&await ci(n,i,e),i}function ci(t,e,r){const n=Vt(r)?.onLegacyMessage;return new Promise((i,s)=>{t.onopen=()=>{i()},t.onclose=()=>{e.close(),r.signal?.aborted?s(r.signal.reason):s(new Error("The websocket was closed before the device connection was established"))},t.onerror=s,t.onmessage=o=>{const h=oi(o);h&&n?.(h)}})}async function li(t,e){const r=t.querySelector("canvas");if(!(r instanceof HTMLCanvasElement))throw new Error("Canvas unavailable");const n=e.protocol==="https:"?"wss:":"ws:",i=await ai(`${n}//${e.host}/ws`);Fr(i,r),Tr(i,r),await Lr(i,r)}await li(document,location);
2
2
  </script></body></html>
@@ -1,4 +0,0 @@
1
- import Je from"debug";import{JSONRPCServerAndClient as Cr,JSONRPCServer as Pr,JSONRPCClient as _r,JSONRPC as Nr}from"json-rpc-2.0";import*as m from"zod/mini";import{writeFileSync as Dr,renameSync as Br,mkdirSync as Mt,readFileSync as zr,rmSync as Fr,readdirSync as jr}from"node:fs";import{sep as $r,join as ie}from"node:path";import{homedir as Ut}from"node:os";import{Transform as Vr}from"stream";import{createRequire as Kr}from"module";import{connect as qr}from"node:net";class Wr extends Event{code;reason;wasClean;constructor(e,r={}){super(e,r),this.code=r.code??0,this.reason=r.reason??"",this.wasClean=r.wasClean??!1}}function Jr(t,e){const r="CloseEvent"in globalThis?globalThis.CloseEvent:Wr;return new r(t,e)}class Gr{#e=new EventTarget;addEventListener(e,r,s){return this.#e.addEventListener(e,r,s),()=>{this.#e.removeEventListener(e,r,s)}}removeEventListener(e,r,s){this.#e.removeEventListener(e,r,s)}dispatchEvent(e){return this.#e.dispatchEvent(e)}}const U=Symbol.for("@appetizeio/rpc:rpcMethods");class Hr extends Gr{send;constructor(e){super(),this.send=e}dispatchClose(e){return this.dispatchEvent(Jr("close",e))}dispatchMessage(e){return this.dispatchEvent(new CustomEvent("message",{detail:e}))}}const Zr="@appetizeio/rpc:playwrightAdapter";class ve{closed=!1;[U];#e;constructor(e,{signal:r}={}){this[U]=new Hr(e),this.#e=r,this.#e?.addEventListener("abort",this.#t)}close(e={}){this.closed||(this.closed=!0,this.handleClose(e))}handleClose(e){this.#e?.removeEventListener("abort",this.#t),this[U].dispatchClose(e)}#t=()=>{this.close({code:1e3,reason:String(this.#e?.reason)})}}const Pe=Symbol.for(Zr);function Yr(t){window[Pe]&&console.warn("playwright exposed more than once, overwriting previous adapter");const e={send(r){t[U].send(r)},subscribe(r){return t[U].addEventListener("message",s=>{r(s.detail)})}};return window[Pe]=e,()=>{window[Pe]===e&&delete window[Pe]}}const Lt=Je("appetize.io:error:rpc");function Ge(t,e){const r=new Cr(new Pr({errorListener:Lt}),Qr(t),{errorListener:Lt}),s=t[U].addEventListener("message",({detail:i})=>{r.receiveAndSend(i)}),n=t[U].addEventListener("close",()=>{s(),r.rejectAllPendingRequests("Transport closed")},{once:!0});for(const i in e){const l=e[i];l&&r.addMethod(i,l.bind(e))}return{rpc:r,unsub:()=>{s(),n()}}}function Ct(t,e){const{rpc:r,unsub:s}=Ge(t,e);return{client:r.client,unsub:s}}function _e(t,e){const r=t[U].addEventListener("message",({detail:n})=>{if("method"in n)try{e({method:n.method,param:n.params})}catch{}}),s=t[U].addEventListener("close",r,{once:!0});return()=>{r(),s()}}function Qr(t){return new _r(t[U].send.bind(t[U]),()=>Math.floor(Math.random()*Number.MAX_SAFE_INTEGER)+1)}function He(t,e,{leftEffects:r=()=>({}),notifiesLeft:s,notifiesRight:n,rightEffects:i=()=>({})}={}){const l=Ge(t,{}),y=Ge(e,{}),p=[()=>{l.unsub(),y.unsub()}],A=()=>{for(const _ of p)try{_()}catch{}},E=y.rpc.client,R=l.rpc.client;p.push(t[U].addEventListener("close",()=>{A()},{once:!0}),e[U].addEventListener("close",()=>{A()},{once:!0}));const M=r(E,R);for(const _ in M){const C=M[_];C&&l.rpc.addMethod(_,C)}const N=i(R,E);for(const _ in N){const C=N[_];C&&y.rpc.addMethod(_,C)}return Pt(l.rpc,y.rpc,{notifies:s}),Pt(y.rpc,l.rpc,{notifies:n}),A}function Pt(t,e,{notifies:r}={}){t.applyServerMiddleware(async(s,n)=>{const i=r?.();if(i){const{id:y,...p}=n;i[U].send(p)}if(t.hasMethod(n.method))return await s(n);if(!n.id)return e.notify(n.method,n.params),null;const l=await e.request(n.method,n.params);return{id:n.id,jsonrpc:Nr,result:l}})}function ee(t,...e){t.notify(e[0],e[1],e[2])}const Xr=(...t)=>Ct(...t),es=["h264","jpeg"],Ze=["ArrowDown","ArrowLeft","ArrowRight","ArrowUp","Backspace","Enter","Tab"],_t=["landscapeLeft","landscapeRight","portrait","upsideDown"];function Ye(){const t=new ve(async r=>{e[U].dispatchMessage(r)}),e=new ve(async r=>{t[U].dispatchMessage(r)});return t[U].addEventListener("close",()=>{e.close()},{once:!0}),e[U].addEventListener("close",()=>{t.close()},{once:!0}),[t,e]}function Nt(t,e){const r=[],s=()=>{for(const n of r)n()};r.push(t[U].addEventListener("message",n=>e[U].send(n.detail))),r.push(t[U].addEventListener("close",s,{once:!0})),r.push(e[U].addEventListener("message",n=>t[U].send(n.detail))),r.push(e[U].addEventListener("close",s,{once:!0}))}function Qe(t){return!!t&&typeof t=="object"&&"jsonrpc"in t}const oe=Je("appetize.io:trace:transport:iframe");class Dt extends ve{onmessage;#e;#t;constructor(e,{origin:r="*",signal:s}={}){super(async n=>{e.postMessage(n,this.#e)},{signal:s}),this.#t=e,this.#e=r,window.addEventListener("message",this.#r)}postMessage(e,r,s){oe("postMessage(legacy)",{message:e,targetOrigin:r,transfer:s}),this.#t.postMessage(e,r??this.#e,s)}handleClose(e){oe("close()"),window.removeEventListener("message",this.#r),super.handleClose(e)}#r=async e=>{if(oe("handleMessage()",e),e.source!==this.#t||(oe("handleMessage() -> source ok"),this.#e!=="*"&&e.origin!==this.#e))return;oe("handleMessage() -> origin ok");const r=e.data;if(!Qe(r)){oe("handleMessage() -> legacy"),this.onmessage?.(e);return}oe("handleMessage() -> jsonrpc"),this[U].dispatchMessage(r)}}function Ne(){let t,e;return{promise:new Promise((s,n)=>{e=s,t=n}),reject:t,resolve:e}}const ts=2*1024*1024,Bt=Je("appetize:client:acked-writable-stream");class rs{unacked=0;#e;#t;#r;#s;#n=[];#o;constructor(e){this.#r=e,this.#o=e.window??ts}abort(e){this.#i(e),this.#r.onAbort?.(e)}async close(){await this.#c(()=>this.unacked===0),this.#r.onClose?.()}fail(e){this.#i(e)&&this.#r.onError?.(e)}start(e){this.#e=e}write(e){const r=e.byteLength;return this.unacked+=r,this.#r.send(e).then(()=>{this.unacked-=r,this.#s&&(this.#s.acked+=r),this.#a()},s=>{this.fail(s)}),this.unacked>=this.#o&&!this.#s&&(this.#s={acked:0,at:performance.now()},Bt("window full: %d bytes unacked, writes stalled",this.unacked)),this.#c(()=>this.unacked<this.#o)}#a(){if(this.#s&&this.unacked<=this.#o/2){const e=performance.now()-this.#s.at;Bt("pressure relieved after %dms: %d bytes acked, %s MB/s",Math.round(e),this.#s.acked,(this.#s.acked/Math.max(e,1)/1e3).toFixed(2)),this.#s=void 0}this.#n=this.#n.filter(e=>e.until()?(e.resolve(void 0),!1):!0)}#i(e){if(this.#t)return!1;this.#t={reason:e},this.#e.error(e);const r=this.#n;this.#n=[];for(const s of r)s.reject(e);return!0}#c(e){if(e())return Promise.resolve();const r={...Ne(),until:e};return this.#n.push(r),r.promise}}class ss extends WritableStream{get unacked(){return this.#e.unacked}#e;constructor(e){const r=new rs(e);super({abort:s=>{r.abort(s)},close:()=>r.close(),start:s=>{r.start(s)},write:s=>r.write(s)}),this.#e=r}fail(e){this.#e.fail(e)}}const ns=1024*1024;class is{#e;#t=!1;#r;#s;constructor(e){this.#r=e}cancel(e){this.#n(),this.#r?.(e)}close(){this.#n()&&this.#e.close()}error(e){this.#n()&&this.#e.error(e)}pull(){const e=this.#s;this.#s=void 0,e?.resolve(void 0)}async push(e){if(this.#t)return;this.#s??=Ne();const{promise:r}=this.#s;this.#e.enqueue(e),await r}start(e){this.#e=e}#n(){return this.#t?!1:(this.#t=!0,this.pull(),!0)}}class os extends ReadableStream{#e;constructor({highWaterMark:e=ns,onCancel:r}={}){const s=new is(r);super({cancel:n=>{s.cancel(n)},pull:()=>{s.pull()},start:n=>{s.start(n)}},new ByteLengthQueuingStrategy({highWaterMark:e})),this.#e=s}close(){this.#e.close()}error(e){this.#e.error(e)}push(e){return this.#e.push(e)}}class as{closed;readable;writable;#e=[];#t;#r;#s;#n;#o;#a="starting";constructor(e,{onClose:r,receiveBuffer:s,sendWindow:n,signal:i}){if(this.#o=e,this.#t=Ne(),this.closed=this.#t.promise,this.closed.catch(cs),this.#s=new os({highWaterMark:s,onCancel:()=>{this.#i(void 0)}}),this.readable=this.#s,this.#n=new ss({onAbort:()=>{this.#i(void 0)},onClose:()=>{this.#i(void 0)},onError:l=>{this.#i(l)},send:l=>e.request("appetizeio.device.server.debug.adbTunnel.data",{data:l}),window:n}),this.writable=this.#n,i){const l=()=>{this.#i(i.reason)};i.addEventListener("abort",l,{once:!0}),this.#e.push(()=>{i.removeEventListener("abort",l)})}this.#e.push(()=>{r(this)})}close=()=>{this.#i(void 0)};detach(){this.#i(void 0,{notifyServer:!1})}async handleData(e){this.#a==="open"&&await this.#s.push(e)}handleStopped({error:e}){this.#a==="open"&&this.#i(e?new Error(e):void 0)}async start(){try{await this.#o.request("appetizeio.device.server.debug.adbTunnel.start",void 0)}catch(e){throw this.#i(e),e}if(this.#a==="closed")throw this.#r?this.#r:new Error("The adb tunnel closed before it started");this.#a="open"}async[Symbol.asyncDispose](){this.close();try{await this.closed}catch{}}#i(e,{notifyServer:r=!0}={}){if(this.#a!=="closed"){this.#a="closed",this.#r=e,r&&ee(this.#o,"appetizeio.device.server.debug.adbTunnel.stop",void 0),e?(this.#s.error(e),this.#n.fail(e)):(this.#s.close(),this.#n.fail(new Error("The adb tunnel has stopped")));for(const s of this.#e)s();e?this.#t.reject(e):this.#t.resolve(void 0)}}}function cs(){}class ls{readable;ready;#e=[];#t=!1;#r;#s;#n;constructor({label:e,onClose:r,signal:s}){this.#s=e,this.ready=new Promise((i,l)=>{this.#n={reject:l,resolve:i}});let n;if(this.readable=new ReadableStream({cancel:()=>{this.#a()},start:i=>{n=i}}),!n)throw new Error("ReadableStream controller was not initialized");if(this.#r=n,s){const i=()=>{this.fail(s.reason)};s.addEventListener("abort",i,{once:!0}),this.#e.push(()=>{s.removeEventListener("abort",i)})}this.#e.push(()=>{r(this)})}close=()=>{this.#o()};fail(e){this.#o(e)}handleItem(e){this.#r.enqueue(e)}markReady(){if(!this.#n)return;const{resolve:e}=this.#n;this.#n=void 0,e(this)}async*[Symbol.asyncIterator](){const e=this.readable.getReader();try{for(let r=await e.read();!r.done;r=await e.read())yield r.value}finally{await e.cancel()}}#o(e){this.#t||(this.#r.close(),this.#a(e))}#a(e){this.#t=!0;for(const r of this.#e)r();this.#n?.reject(e??new Error(`${this.#s} closed before it started`)),this.#n=void 0}}class fs{get subscribers(){return this.#r}#e;#t;#r=new Set;constructor(e){this.#e=e}close(){this.#t=void 0;for(const e of[...this.#r])e.close();this.#r.clear()}add(e){this.#r.add(e)}ensureStarted(){return this.#t||(this.#t=(async()=>{try{return await this.#e.start()}catch(e){throw this.#t=void 0,e}})()),this.#t}release(e){this.#r.delete(e),!(this.#r.size>0||!this.#t)&&(this.#t=void 0,this.#e.stop())}}class zt extends fs{#e;constructor(e){super({start:e.start,stop:e.stop}),this.#e=e.label}async createStream({signal:e}={}){e?.throwIfAborted();const r=new ls({label:this.#e,onClose:s=>{this.release(s)},signal:e});this.add(r);try{await this.ensureStarted(),r.markReady()}catch(s){r.fail(s)}return await r.ready}handleNotification(e){for(const r of this.subscribers)r.handleItem(e)}}class us{#e;#t;#r;#s;constructor(e){this.#s=e,this.#t=new zt({label:"Log stream",start:()=>e.request("appetizeio.device.server.debug.log.start"),stop:()=>{ee(e,"appetizeio.device.server.debug.log.stop",void 0)}}),this.#r=new zt({label:"Proxy intercept stream",start:()=>e.request("appetizeio.device.server.debug.proxyIntercept.start"),stop:()=>{ee(e,"appetizeio.device.server.debug.proxyIntercept.stop",void 0)}})}close(){this.#e?.detach(),this.#t.close(),this.#r.close()}async createAdbTunnel({signal:e}={}){e?.throwIfAborted(),this.#e?.close();const r=new as(this.#s,{onClose:()=>{this.#e=void 0},signal:e});return this.#e=r,await r.start(),r}async createLogStream(e){return await this.#t.createStream(e)}async createProxyInterceptStream(e){return await this.#r.createStream(e)}async handleAdbTunnelData({data:e}){await this.#e?.handleData(e)}handleAdbTunnelStopped(e){this.#e?.handleStopped(e)}handleLogEntry(e){this.#t.handleNotification(e)}handleProxyInterceptEvent(e){this.#r.handleNotification(e)}}function Xe(t){return{...ds(t),index:t.index,within:t.within?Xe(t.within):void 0}}function ds(t){switch(t.by){case"testId":return{by:"testId",testId:t.testId};case"text":return{by:"text",text:hs(t.text)}}}function hs(t){return typeof t=="string"?{kind:"exact",value:t}:{flags:t.flags,kind:"regex",source:t.source}}const ps=400,Ft=["byTestId","byText","duration","index","x","y"],ys=new Set(Ft),ws=/^-?(?:\d+(?:\.\d*)?|\.\d+)$/u,gs=/^[a-z]$/u,et=/^\s$/u;class D extends SyntaxError{constructor(e,r,s){super(`${e} at position ${String(r)}`,{cause:s})}}class ms{#e=0;#t;constructor(e){this.#t=e}parse(){const e=[];for(;this.#e<this.#t.length;){const r=this.#i();if(et.test(r))this.#e++;else if(r===">"){if(this.#t.charAt(this.#e+1)===">")throw new D('Force press ">>" is not supported',this.#e);this.#e++,e.push({kind:"down"})}else if(r==="/")this.#e++,e.push({kind:"up"});else if(r==="{")e.push(this.#o());else{const[s]=this.#t.slice(this.#e,this.#e+2);throw new D(`Unexpected ${JSON.stringify(s)}; write selectors as {...}`,this.#e)}}return e}#r(){const e=this.#e,r=this.#c(s=>s!=="="&&!tt(s));if(this.#i()!=="=")return{kind:"bare",name:r,offset:e};if(r.length===0)throw new D('Expected an attribute name before "="',e);return this.#e++,{kind:"attribute",name:r,offset:e,value:this.#a()}}#s(){const e=this.#e;this.#e++;let r="";for(;;){const s=this.#i();if(this.#e++,s==='"')return r;if(s==="\\"){const n=this.#i();if(n!=='"'&&n!=="\\"&&n!=="")throw new D('Only \\" and \\\\ escapes are supported',this.#e-1);this.#e++,r+=n}else{if(s==="")throw new D("Unclosed string",e);r+=s}}}#n(){const e=this.#e;this.#e++;let r="",s=!1;for(;;){const i=this.#i();if(i==="")throw new D("Unclosed regex",e);if(this.#e++,i==="/"&&!s)break;r+=i,i==="\\"?(r+=this.#i(),this.#e++):i==="["?s=!0:i==="]"&&(s=!1)}const n=this.#c(i=>gs.test(i));try{return new RegExp(r,n)}catch(i){throw new D(`Invalid regex /${r}/${n}`,e,i)}}#o(){const e=this.#e;this.#e++;let r;const s={offsets:{}};for(let n=0;;n++){this.#l();const i=this.#i();if(i==="")throw new D('Unclosed "{"',e);if(i==="}"){if(this.#e++,n===0)throw new D('Expected a selector or wait in "{}"',e);return r===void 0?Ss(s,e):{duration:r,kind:"wait"}}const l=this.#r();if(n===0&&l.name==="wait")r=l.kind==="attribute"?$t(l.value,"wait"):ps;else{if(r!==void 0)throw new D('"wait" takes no other attributes',l.offset);bs(s,l,n)}}}#a(){const e=this.#e,r=this.#i();let s;if(r==='"')s={kind:"quoted",offset:e,text:this.#s()};else if(r==="/")s={kind:"regex",offset:e,regex:this.#n()};else{const n=this.#c(i=>!tt(i));if(n.length===0)throw new D('Expected a value after "="',e);return{kind:"raw",offset:e,text:n}}if(!tt(this.#i()))throw new D('Expected a space or "}" after the value',this.#e);return s}#i(){return this.#t.charAt(this.#e)}#c(e){const r=this.#e;for(;this.#e<this.#t.length&&e(this.#i());)this.#e++;return this.#t.slice(r,this.#e)}#l(){this.#c(e=>et.test(e))}}function jt(t){return new ms(t).parse()}function bs(t,e,r){const{name:s,offset:n}=e;if(e.kind==="attribute"){rt(t,s,n,e.value);return}if(!s.includes(","))throw new D(`Expected key=value, got ${JSON.stringify(s)}`,n);if(r>0)throw new D("Write the x,y position first",n);const[i,l,...y]=s.split(",");if(y.length>0)throw new D("Expected a screen position as x,y",n);const p=n+i.length+1;rt(t,"x",n,{kind:"raw",offset:n,text:i}),rt(t,"y",p,{kind:"raw",offset:p,text:l})}function Es(t){return ys.has(t)}function tt(t){return t===""||t==="}"||et.test(t)}function rt(t,e,r,s){if(!Es(e))throw new D(`Unknown attribute ${JSON.stringify(e)}; expected one of ${Ft.join(", ")}`,r);if(t.offsets[e]!==void 0)throw new D(`Duplicate attribute ${JSON.stringify(e)}`,r);switch(t.offsets[e]=r,e){case"byTestId":case"byText":if(t.byText!==void 0||t.byTestId!==void 0)throw new D("Only one of byText and byTestId may be given",r);e==="byText"?t.byText=xs(s):t.byTestId=As(s);return;default:t[e]=$t(s,e)}}function Ss(t,e){return{duration:t.duration,kind:"move",to:vs(t,e)}}function $t(t,e){if(t.kind!=="raw"||!ws.test(t.text))throw new D(`"${e}" takes a number`,t.offset);return Number(t.text)}function vs(t,e){const{byTestId:r,byText:s,index:n,offsets:i,x:l,y}=t;if(s!==void 0)return{by:"text",index:n,text:s,x:l,y};if(r!==void 0)return{by:"testId",index:n,testId:r,x:l,y};if(i.index!==void 0)throw new D('"index" needs byText or byTestId',i.index);if(l===void 0||y===void 0)throw new D("A screen position needs x and y",e);return{by:"position",x:l,y}}function As(t){if(t.kind==="regex")throw new D('"byTestId" takes a string',t.offset);return t.text}function xs(t){return t.kind==="regex"?t.regex:t.text}function Ae(t){return t.by==="position"?{by:"position",x:t.x,y:t.y}:{...Xe(t),x:t.x,y:t.y}}function ks(t){return t.map(e=>e.kind==="move"?{duration:e.duration,kind:"move",to:Ae(e.to)}:e)}function Is(t){return{press:e=>{ee(t,"appetizeio.device.server.keyboard.press",{key:e})}}}function Os({onRequest:t,parent:e,proxyInlet:r,signal:s}){const n=new Dt(e,{signal:s}),i=[()=>{n.close()}];return Nt(n,r),t&&i.push(_e(n,l=>{t(l,{source:"parent"})})),{cleanup:()=>{for(const l of i)l()},notifies:()=>e===globalThis.window?void 0:n}}function Ts({onRequest:t,proxyInlet:e}){const[r,s]=Ye(),i=[Yr(s),()=>{r.close()}];return Nt(r,e),t&&i.push(_e(r,l=>{t(l,{source:"parent"})})),{cleanup:()=>{for(const l of i)l()},notifies:()=>r}}function Rs(t){return"to"in t?{from:Ae(t.from),kind:"path",to:Ae(t.to)}:{direction:t.direction,distance:t.distance,from:t.from?Ae(t.from):void 0,kind:"direction"}}function Ms(t){return{down:(e,r)=>{ee(t,"appetizeio.device.server.touch.down",{x:e,y:r})},move:(e,r)=>{ee(t,"appetizeio.device.server.touch.move",{x:e,y:r})},up:(e,r)=>{ee(t,"appetizeio.device.server.touch.up",{x:e,y:r})}}}const Us=new Set(Ze),Ls=/^(?<key>[A-Za-z]+)>(?<repeat>\d+)\/$/u,Cs=/(\{\{|\{[^{}]*\})/u;function Ps(t){const e=[];let r="";function s(){r.length>0&&(e.push({kind:"text",text:r}),r="")}for(const[n,i]of t.split(Cs).entries())if(n%2===0){if(i.includes("{"))throw new Error(`Unclosed "{" in ${JSON.stringify(t)}`);r+=i}else i==="{{"?r+="{":(s(),e.push(Ns(i.slice(1,-1))));return s(),e}function _s(t,e){if(!Us.has(t))throw e.endsWith(">")?new Error(`Holding a key is not supported: {${e}}`):e.startsWith("/")?new Error(`Releasing a key is not supported: {${e}}`):new Error(`{${e}} does not name a supported key. Supported: ${Ze.join(", ")}. Type characters as text, and escape a literal "{" as "{{".`)}function Ns(t){const e=Ls.exec(t)?.groups,r=e?.key??t;if(_s(r,t),!e)return{key:r,kind:"press"};const s=Number(e.repeat);if(s<1)throw new Error(`Repeat for {${t}} must be at least 1`);return{key:r,kind:"press",repeat:s}}const Ds=Symbol("@appetizeio/client:v1Compat");function Vt(t){return t?.[Ds]}class Bs{readable;ready;get dimensions(){return this.#s}#e=[];#t=!1;#r;#s;#n;#o;constructor({onClose:e,requestKeyFrame:r,signal:s}){this.#n=r,this.ready=new Promise((i,l)=>{this.#o={reject:l,resolve:i}});let n;if(this.readable=new ReadableStream({cancel:()=>{this.#i()},start:i=>{n=i}}),!n)throw new Error("ReadableStream controller was not initialized");if(this.#r=n,s){const i=()=>{this.fail(s.reason)};s.addEventListener("abort",i,{once:!0}),this.#e.push(()=>{s.removeEventListener("abort",i)})}this.#e.push(()=>{e(this)})}close=()=>{this.#a()};fail(e){this.#a(e)}handleChunk(e){if(this.#o){if(e.type!=="key")return;const{resolve:r}=this.#o;this.#o=void 0,this.#s={height:e.height,width:e.width},r(this)}else e.type==="key"&&(this.#s={height:e.height,width:e.width});this.#r.enqueue(e)}requestKeyFrame=()=>{this.#t||this.#n()};async*[Symbol.asyncIterator](){const e=this.readable.getReader();try{for(let r=await e.read();!r.done;r=await e.read())yield r.value}finally{await e.cancel()}}#a(e){this.#t||(this.#r.close(),this.#i(e))}#i(e){this.#t=!0;for(const r of this.#e)r();this.#o?.reject(e??new Error("Video stream closed before the first key chunk")),this.#o=void 0}}class zs{#e=!1;#t;#r;#s=new Set;constructor(e){this.#t=e}close(){this.#r=void 0;for(const e of[...this.#s])e.close()}async createStream({signal:e}={}){e?.throwIfAborted();const r=new Bs({onClose:s=>{this.#o(s)},requestKeyFrame:()=>{this.#a()},signal:e});this.#s.add(r);try{await this.#n()}catch(s){r.fail(s)}return await r.ready}handleChunk(e){e.type==="key"&&(this.#e=!1);for(const r of this.#s)r.handleChunk(e)}#n(){return this.#r?(this.#a(),this.#r):(this.#e=!0,this.#r=(async()=>{try{await this.#t.request("appetizeio.device.server.video.start")}catch(e){throw this.#r=void 0,e}})(),this.#r)}#o(e){this.#s.delete(e),!(this.#s.size>0||!this.#r)&&(this.#r=void 0,ee(this.#t,"appetizeio.device.server.video.stop",void 0))}#a(){this.#e||(this.#e=!0,ee(this.#t,"appetizeio.device.server.video.requestKeyFrame",void 0))}}class Fs{debug;keyboard;touch;video;#e;#t=[];#r;constructor(e,r={}){const s=Vt(r)??{},{baseUrl:n,onClose:i,signal:l}=r;this.#e=n?js(n):void 0;const{onRequest:y,parent:p,proxyRequest:A}=s,E=$s(y);l?.addEventListener("abort",this.close);const[R,M]=Ye(),[N,_]=Ye();this.#t.push(()=>{R.close(),M.close(),N.close(),_.close()}),this.#t.push(He(_,e,{leftEffects:A}));const C=p==="playwright"?Ts({onRequest:E,proxyInlet:N}):p?Os({onRequest:E,parent:p,proxyInlet:N,signal:l}):void 0;C&&this.#t.push(C.cleanup),this.#t.push(He(M,N,{notifiesLeft:C?.notifies}));const{client:Z,unsub:Ee}=Xr(R,{"appetizeio.device.client.debug.adbTunnel.data":V=>Y.handleAdbTunnelData(V),"appetizeio.device.client.debug.adbTunnel.stopped":async V=>{Y.handleAdbTunnelStopped(V)},"appetizeio.device.client.debug.log.entry":async V=>{Y.handleLogEntry(V)},"appetizeio.device.client.debug.proxyIntercept.event":async V=>{Y.handleProxyInterceptEvent(V)},"appetizeio.device.client.video.chunk":async V=>{k.handleChunk(V)}});this.#r=Z,this.#t.push(Ee);const Y=new us(this.#r);this.#t.push(()=>{Y.close()});const k=new zs(this.#r);this.#t.push(()=>{k.close()}),this.debug=Y,this.keyboard=Is(this.#r),this.touch=Ms(this.#r),this.video=k,E&&(this.#t.push(_e(M,V=>{E(V,{source:"self"})})),e instanceof Dt&&this.#t.push(_e(e,V=>{E(V,{source:"iframe"})}))),this.#t.push(()=>i?.())}async clearKeychain(){await this.#r.request("appetizeio.device.server.clearKeychain")}close=()=>{for(const e of this.#t)try{e()}catch(r){console.error("Device cleanup error:",r)}};async fold(e){await this.#r.request("appetizeio.device.server.fold",{hinge:e})}async gesture(e,r){await this.#r.request("appetizeio.device.server.gesture",{options:r,steps:ks(typeof e=="string"?jt(e):e)})}async inspect(e,r){return await this.#r.request("appetizeio.device.server.inspect",{options:r,selector:e?Xe(e):void 0})}async open(e){new URL(e),await this.#r.request("appetizeio.device.server.open",{url:e})}async press(e){await this.#r.request("appetizeio.device.server.press",{action:e})}async rotate(e){await this.#r.request("appetizeio.device.server.rotate",{orientation:e})}async screenshot(){const e=await this.#r.request("appetizeio.device.server.screenshot"),r=this.#e?new URL(e.url,this.#e).href:e.url,s=await fetch(r);if(!s.ok)throw new Error(`Screenshot download failed: ${String(s.status)} ${s.statusText}`);const n=s.headers.get("content-type")??"application/octet-stream";return{data:new Uint8Array(await s.arrayBuffer()),mimeType:n}}async swipe(e,r){await this.#r.request("appetizeio.device.server.swipe",{gesture:Rs(e),options:r})}async tap(e,r){await this.#r.request("appetizeio.device.server.tap",{options:r,selector:Ae(e)})}async type(e,r){await this.#r.request("appetizeio.device.server.type",{options:r,steps:Ps(e)})}}function js(t){const e=new URL(t);return e.protocol==="ws:"?e.protocol="http:":e.protocol==="wss:"&&(e.protocol="https:"),e.href}const $s=t=>{if(t)return(e,r)=>{e.method.startsWith("appetizeio.device.server.")&&t(e,r)}};let st;try{st=new TextDecoder}catch{}let w,q,f=0;const nt=[],Vs=105,Ks=57342,qs=57343,Kt=57337,qt=6,pe={};let xe=11281e4,te=1681e4,ae=nt,ke=0,I={},B,Ie,Oe=0,ce=0,z,G,F=[],it=[],W,K,Te,Wt={useRecords:!1,mapsAsObjects:!0},Re=!1,Jt=2;try{new Function("")}catch{Jt=1/0}class be{constructor(e){if(e&&((e.keyMap||e._keyMap)&&!e.useRecords&&(e.useRecords=!1,e.mapsAsObjects=!0),e.useRecords===!1&&e.mapsAsObjects===void 0&&(e.mapsAsObjects=!0),e.getStructures&&(e.getShared=e.getStructures),e.getShared&&!e.structures&&((e.structures=[]).uninitialized=!0),e.keyMap)){this.mapKey=new Map;for(let[r,s]of Object.entries(e.keyMap))this.mapKey.set(s,r)}Object.assign(this,e)}decodeKey(e){return this.keyMap&&this.mapKey.get(e)||e}encodeKey(e){return this.keyMap&&this.keyMap.hasOwnProperty(e)?this.keyMap[e]:e}encodeKeys(e){if(!this._keyMap)return e;let r=new Map;for(let[s,n]of Object.entries(e))r.set(this._keyMap.hasOwnProperty(s)?this._keyMap[s]:s,n);return r}decodeKeys(e){if(!this._keyMap||e.constructor.name!="Map")return e;if(!this._mapKey){this._mapKey=new Map;for(let[s,n]of Object.entries(this._keyMap))this._mapKey.set(n,s)}let r={};return e.forEach((s,n)=>r[H(this._mapKey.has(n)?this._mapKey.get(n):n)]=s),r}mapDecode(e,r){let s=this.decode(e);return this._keyMap&&s.constructor.name==="Array"?s.map(n=>this.decodeKeys(n)):s}decode(e,r){if(w)return er(()=>(lt(),this?this.decode(e,r):be.prototype.decode.call(Wt,e,r)));q=r>-1?r:e.length,f=0,ke=0,ce=0,Ie=null,ae=nt,z=null,w=e;try{K=e.dataView||(e.dataView=new DataView(e.buffer,e.byteOffset,e.byteLength))}catch(s){throw w=null,e instanceof Uint8Array?s:new Error("Source must be a Uint8Array or Buffer but was a "+(e&&typeof e=="object"?e.constructor.name:typeof e))}if(this instanceof be){if(I=this,W=this.sharedValues&&(this.pack?new Array(this.maxPrivatePackedValues||16).concat(this.sharedValues):this.sharedValues),this.structures)return B=this.structures,De();(!B||B.length>0)&&(B=[])}else I=Wt,(!B||B.length>0)&&(B=[]),W=null;return De()}decodeMultiple(e,r){let s,n=0;try{let i=e.length;Re=!0;let l=this?this.decode(e,i):ut.decode(e,i);if(r){if(r(l)===!1)return;for(;f<i;)if(n=f,r(De())===!1)return}else{for(s=[l];f<i;)n=f,s.push(De());return s}}catch(i){throw i.lastPosition=n,i.values=s,i}finally{Re=!1,lt()}}}function De(){try{let t=O();if(z){if(f>=z.postBundlePosition){let e=new Error("Unexpected bundle position");throw e.incomplete=!0,e}f=z.postBundlePosition,z=null}if(f==q)B=null,w=null,G&&(G=null);else if(f>q){let e=new Error("Unexpected end of CBOR data");throw e.incomplete=!0,e}else if(!Re)throw new Error("Data read, but end of buffer not reached");return t}catch(t){throw lt(),(t instanceof RangeError||t.message.startsWith("Unexpected end of buffer"))&&(t.incomplete=!0),t}}function le(){let t=new Error("Unexpected end of CBOR data");return t.incomplete=!0,t}function O(){if(!(f<q))throw le();let t=w[f++],e=t>>5;if(t=t&31,t>23)switch(t){case 24:if(f>=q)throw le();t=w[f++];break;case 25:if(e==7)return Hs();t=K.getUint16(f),f+=2;break;case 26:if(e==7){let r=K.getFloat32(f);if(I.useFloat32>2){let s=ft[(w[f]&127)<<1|w[f+1]>>7];return f+=4,(s*r+(r>0?.5:-.5)>>0)/s}return f+=4,r}if(t=K.getUint32(f),f+=4,e===1)return-1-t;break;case 27:if(e==7){let r=K.getFloat64(f);return f+=8,r}if(e>1){if(K.getUint32(f)>0)throw new Error("JavaScript does not support arrays, maps, or strings with length over 4294967295");t=K.getUint32(f+4)}else I.int64AsNumber?(t=K.getUint32(f)*4294967296,t+=K.getUint32(f+4)):t=K.getBigUint64(f);f+=8;break;case 31:switch(e){case 2:case 3:throw new Error("Indefinite length not supported for byte or text strings");case 4:let r=[],s,n=0;for(;(s=O())!=pe;){if(n>=xe)throw new Error(`Array length exceeds ${xe}`);r[n++]=s}return e==4?r:e==3?r.join(""):Buffer.concat(r);case 5:let i;if(I.mapsAsObjects){let l={},y=0;if(I.keyMap)for(;(i=O())!=pe;){if(y++>=te)throw new Error(`Property count exceeds ${te}`);l[H(I.decodeKey(i))]=O()}else for(;(i=O())!=pe;){if(y++>=te)throw new Error(`Property count exceeds ${te}`);l[H(i)]=O()}return l}else{Te&&(I.mapsAsObjects=!0,Te=!1);let l=new Map;if(I.keyMap){let y=0;for(;(i=O())!=pe;){if(y++>=te)throw new Error(`Map size exceeds ${te}`);l.set(I.decodeKey(i),O())}}else{let y=0;for(;(i=O())!=pe;){if(y++>=te)throw new Error(`Map size exceeds ${te}`);l.set(i,O())}}return l}case 7:return pe;default:throw new Error("Invalid major type for indefinite length "+e)}default:throw new Error("Unknown token "+t)}switch(e){case 0:return t;case 1:return~t;case 2:return Gs(t);case 3:if(ce>=f)return Ie.slice(f-Oe,(f+=t)-Oe);if(ce==0&&q<140&&t<32){let n=t<16?Zt(t):Js(t);if(n!=null)return n}return Ht(t);case 4:if(t>=xe)throw new Error(`Array length exceeds ${xe}`);if(t>q-f)throw le();let r=new Array(t);for(let n=0;n<t;n++)r[n]=O();return r;case 5:if(t>=te)throw new Error(`Map size exceeds ${xe}`);if(t>(q-f)/2)throw le();if(I.mapsAsObjects){let n={};if(I.keyMap)for(let i=0;i<t;i++)n[H(I.decodeKey(O()))]=O();else for(let i=0;i<t;i++)n[H(O())]=O();return n}else{Te&&(I.mapsAsObjects=!0,Te=!1);let n=new Map;if(I.keyMap)for(let i=0;i<t;i++)n.set(I.decodeKey(O()),O());else for(let i=0;i<t;i++)n.set(O(),O());return n}case 6:if(t>=Kt){let n=B[t&8191];if(n)return n.read||(n.read=ot(n)),n.read();if(t<65536){if(t==qs){let i=we(),l=O(),y=O();at(l,y);let p={};if(I.keyMap)for(let A=2;A<i;A++){let E=I.decodeKey(y[A-2]);p[H(E)]=O()}else for(let A=2;A<i;A++){let E=y[A-2];p[H(E)]=O()}return p}else if(t==Ks){let i=we(),l=O();for(let y=2;y<i;y++)at(l++,O());return O()}else if(t==Kt)return tn();if(I.getShared&&(ct(),n=B[t&8191],n))return n.read||(n.read=ot(n)),n.read()}}let s=F[t];if(s)return s.handlesRead?s(O):s(O());{let n=O();for(let i=0;i<it.length;i++){let l=it[i](t,n);if(l!==void 0)return l}return new fe(n,t)}case 7:switch(t){case 20:return!1;case 21:return!0;case 22:return null;case 23:return;default:let n=(W||ue())[t];if(n!==void 0)return n;throw new Error("Unknown token "+t)}default:throw isNaN(t)?le():new Error("Unknown CBOR token "+t)}}const Gt=/^[a-zA-Z_$][a-zA-Z\d_$]*$/;function ot(t){if(!t)throw new Error("Structure is required in record definition");function e(){let r=w[f++];if(r=r&31,r>23)switch(r){case 24:r=w[f++];break;case 25:r=K.getUint16(f),f+=2;break;case 26:r=K.getUint32(f),f+=4;break;default:throw new Error("Expected array header, but got "+w[f-1])}let s=this.compiledReader;for(;s;){if(s.propertyCount===r)return s(O);s=s.next}if(this.slowReads++>=Jt){let i=this.length==r?this:this.slice(0,r);return s=I.keyMap?new Function("r","return {"+i.map(l=>I.decodeKey(l)).map(l=>Gt.test(l)?H(l)+":r()":"["+JSON.stringify(l)+"]:r()").join(",")+"}"):new Function("r","return {"+i.map(l=>Gt.test(l)?H(l)+":r()":"["+JSON.stringify(l)+"]:r()").join(",")+"}"),this.compiledReader&&(s.next=this.compiledReader),s.propertyCount=r,this.compiledReader=s,s(O)}let n={};if(I.keyMap)for(let i=0;i<r;i++)n[H(I.decodeKey(this[i]))]=O();else for(let i=0;i<r;i++)n[H(this[i])]=O();return n}return t.slowReads=0,e}function H(t){if(typeof t=="string")return t==="__proto__"?"__proto_":t;if(typeof t=="number"||typeof t=="boolean"||typeof t=="bigint")return t.toString();if(t==null)return t+"";throw new Error("Invalid property name type "+typeof t)}let Ht=Be;function Ws(t){Ht=e();function e(r){return function(n){let i=ae[ke++];if(i==null){if(z)return Be(n);let y=t(f,q,n,w);if(typeof y=="string")i=y,ae=nt;else if(ae=y,ke=1,ce=1,i=ae[0],i===void 0)throw new Error("Unexpected end of buffer")}let l=i.length;return l<=n?(f+=n,i):(Ie=i,Oe=f,ce=f+l,f+=n,i.slice(0,n))}}}function Be(t){let e;if(t<16&&(e=Zt(t)))return e;if(t>64&&st)return st.decode(w.subarray(f,f+=t));const r=f+t,s=[];for(e="";f<r;){const n=w[f++];if((n&128)===0)s.push(n);else if((n&224)===192)if(n<194||f>=r||(w[f]&192)!==128)s.push(65533);else{const i=w[f++]&63;s.push((n&31)<<6|i)}else if((n&240)===224){const i=f<r?w[f]:0;if(f>=r||(i&192)!==128||n===224&&i<160||n===237&&i>=160)s.push(65533);else if(f++,f>=r||(w[f]&192)!==128)s.push(65533);else{const l=w[f++]&63;s.push((n&31)<<12|(i&63)<<6|l)}}else if((n&248)===240){const i=f<r?w[f]:0;if(n>244||f>=r||(i&192)!==128||n===240&&i<144||n===244&&i>=144)s.push(65533);else if(f++,f>=r||(w[f]&192)!==128)s.push(65533);else{const l=w[f++]&63;if(f>=r||(w[f]&192)!==128)s.push(65533);else{const y=w[f++]&63;let p=(n&7)<<18|(i&63)<<12|l<<6|y;p-=65536,s.push(p>>>10&1023|55296),s.push(56320|p&1023)}}}else s.push(65533);s.length>=4096&&(e+=$.apply(String,s),s.length=0)}return s.length>0&&(e+=$.apply(String,s)),e}let $=String.fromCharCode;function Js(t){let e=f,r=new Array(t);for(let s=0;s<t;s++){const n=w[f++];if((n&128)>0){f=e;return}r[s]=n}return $.apply(String,r)}function Zt(t){if(t<4)if(t<2){if(t===0)return"";{let e=w[f++];if((e&128)>1){f-=1;return}return $(e)}}else{let e=w[f++],r=w[f++];if((e&128)>0||(r&128)>0){f-=2;return}if(t<3)return $(e,r);let s=w[f++];if((s&128)>0){f-=3;return}return $(e,r,s)}else{let e=w[f++],r=w[f++],s=w[f++],n=w[f++];if((e&128)>0||(r&128)>0||(s&128)>0||(n&128)>0){f-=4;return}if(t<6){if(t===4)return $(e,r,s,n);{let i=w[f++];if((i&128)>0){f-=5;return}return $(e,r,s,n,i)}}else if(t<8){let i=w[f++],l=w[f++];if((i&128)>0||(l&128)>0){f-=6;return}if(t<7)return $(e,r,s,n,i,l);let y=w[f++];if((y&128)>0){f-=7;return}return $(e,r,s,n,i,l,y)}else{let i=w[f++],l=w[f++],y=w[f++],p=w[f++];if((i&128)>0||(l&128)>0||(y&128)>0||(p&128)>0){f-=8;return}if(t<10){if(t===8)return $(e,r,s,n,i,l,y,p);{let A=w[f++];if((A&128)>0){f-=9;return}return $(e,r,s,n,i,l,y,p,A)}}else if(t<12){let A=w[f++],E=w[f++];if((A&128)>0||(E&128)>0){f-=10;return}if(t<11)return $(e,r,s,n,i,l,y,p,A,E);let R=w[f++];if((R&128)>0){f-=11;return}return $(e,r,s,n,i,l,y,p,A,E,R)}else{let A=w[f++],E=w[f++],R=w[f++],M=w[f++];if((A&128)>0||(E&128)>0||(R&128)>0||(M&128)>0){f-=12;return}if(t<14){if(t===12)return $(e,r,s,n,i,l,y,p,A,E,R,M);{let N=w[f++];if((N&128)>0){f-=13;return}return $(e,r,s,n,i,l,y,p,A,E,R,M,N)}}else{let N=w[f++],_=w[f++];if((N&128)>0||(_&128)>0){f-=14;return}if(t<15)return $(e,r,s,n,i,l,y,p,A,E,R,M,N,_);let C=w[f++];if((C&128)>0){f-=15;return}return $(e,r,s,n,i,l,y,p,A,E,R,M,N,_,C)}}}}}function Gs(t){return I.copyBuffers?Uint8Array.prototype.slice.call(w,f,f+=t):w.subarray(f,f+=t)}let Yt=new Float32Array(1),ze=new Uint8Array(Yt.buffer,0,4);function Hs(){let t=w[f++],e=w[f++],r=(t&127)>>2;if(r===31)return e||t&3?NaN:t&128?-1/0:1/0;if(r===0){let s=((t&3)<<8|e)/16777216;return t&128?-s:s}return ze[3]=t&128|(r>>1)+56,ze[2]=(t&7)<<5|e>>3,ze[1]=e<<5,ze[0]=0,Yt[0]}new Array(4096);class fe{constructor(e,r){this.value=e,this.tag=r}}F[0]=t=>new Date(t),F[1]=t=>new Date(Math.round(t*1e3)),F[2]=t=>{let e=BigInt(0);for(let r=0,s=t.byteLength;r<s;r++)e=BigInt(t[r])+(e<<BigInt(8));return e},F[3]=t=>BigInt(-1)-F[2](t),F[4]=t=>+(t[1]+"e"+t[0]),F[5]=t=>t[1]*Math.exp(t[0]*Math.log(2));const at=(t,e)=>{t=t-57344;let r=B[t];r&&r.isShared&&((B.restoreStructures||(B.restoreStructures=[]))[t]=r),B[t]=e,e.read=ot(e)};F[Vs]=t=>{let e=t.length,r=t[1];at(t[0],r);let s={};for(let n=2;n<e;n++){let i=r[n-2];s[H(i)]=t[n]}return s},F[14]=t=>z?z[0].slice(z.position0,z.position0+=t):new fe(t,14),F[15]=t=>z?z[1].slice(z.position1,z.position1+=t):new fe(t,15);let Zs={Error,RegExp};F[27]=t=>(Zs[t[0]]||Error)(t[1],t[2]);const Qt=t=>{if(w[f++]!=132){let r=new Error("Packed values structure must be followed by a 4 element array");throw w.length<f&&(r.incomplete=!0),r}let e=t();if(!e||!e.length){let r=new Error("Packed values structure must be followed by a 4 element array");throw r.incomplete=!0,r}return W=W?e.concat(W.slice(e.length)):e,W.prefixes=t(),W.suffixes=t(),t()};Qt.handlesRead=!0,F[51]=Qt,F[qt]=t=>{if(!W)if(I.getShared)ct();else return new fe(t,qt);if(typeof t=="number")return W[16+(t>=0?2*t:-2*t-1)];let e=new Error("No support for non-integer packed references yet");throw t===void 0&&(e.incomplete=!0),e},F[28]=t=>{G||(G=new Map,G.id=0);let e=G.id++,r=f,s=w[f],n;s>>5==4?n=[]:n={};let i={target:n};G.set(e,i);let l=t();return i.used?(Object.getPrototypeOf(n)!==Object.getPrototypeOf(l)&&(f=r,n=l,G.set(e,{target:n}),l=t()),Object.assign(n,l)):(i.target=l,l)},F[28].handlesRead=!0,F[29]=t=>{let e=G.get(t);return e.used=!0,e.target},F[258]=t=>new Set(t),(F[259]=t=>(I.mapsAsObjects&&(I.mapsAsObjects=!1,Te=!0),t())).handlesRead=!0;function ye(t,e){return typeof t=="string"?t+e:t instanceof Array?t.concat(e):Object.assign({},t,e)}function ue(){if(!W)if(I.getShared)ct();else throw new Error("No packed values available");return W}const Ys=1399353956;it.push((t,e)=>{if(t>=225&&t<=255)return ye(ue().prefixes[t-224],e);if(t>=28704&&t<=32767)return ye(ue().prefixes[t-28672],e);if(t>=1879052288&&t<=2147483647)return ye(ue().prefixes[t-1879048192],e);if(t>=216&&t<=223)return ye(e,ue().suffixes[t-216]);if(t>=27647&&t<=28671)return ye(e,ue().suffixes[t-27639]);if(t>=1811940352&&t<=1879048191)return ye(e,ue().suffixes[t-1811939328]);if(t==Ys)return{packedValues:W,structures:B.slice(0),version:e};if(t==55799)return e});const Qs=new Uint8Array(new Uint16Array([1]).buffer)[0]==1,Xt=[Uint8Array,Uint8ClampedArray,Uint16Array,Uint32Array,typeof BigUint64Array>"u"?{name:"BigUint64Array"}:BigUint64Array,Int8Array,Int16Array,Int32Array,typeof BigInt64Array>"u"?{name:"BigInt64Array"}:BigInt64Array,Float32Array,Float64Array],Xs=[64,68,69,70,71,72,77,78,79,85,86];for(let t=0;t<Xt.length;t++)en(Xt[t],Xs[t]);function en(t,e){let r="get"+t.name.slice(0,-5),s;typeof t=="function"?s=t.BYTES_PER_ELEMENT:t=null;for(let n=0;n<2;n++){if(!n&&s==1)continue;let i=s==2?1:s==4?2:s==8?3:0;F[n?e:e-4]=s==1||n==Qs?l=>{if(!t)throw new Error("Could not find typed array for code "+e);return!I.copyBuffers&&(s===1||s===2&&!(l.byteOffset&1)||s===4&&!(l.byteOffset&3)||s===8&&!(l.byteOffset&7))?new t(l.buffer,l.byteOffset,l.byteLength>>i):new t(Uint8Array.prototype.slice.call(l,0).buffer)}:l=>{if(!t)throw new Error("Could not find typed array for code "+e);let y=new DataView(l.buffer,l.byteOffset,l.byteLength),p=l.length>>i,A=new t(p),E=y[r];for(let R=0;R<p;R++)A[R]=E.call(y,R<<i,n);return A}}}function tn(){let t=we(),e=f+O();for(let s=2;s<t;s++){let n=we();f+=n}let r=f;return f=e,z=[Be(we()),Be(we())],z.position0=0,z.position1=0,z.postBundlePosition=f,f=r,O()}function we(){if(!(f<q))throw le();let t=w[f++]&31;if(t>23)switch(t){case 24:if(f>=q)throw le();t=w[f++];break;case 25:t=K.getUint16(f),f+=2;break;case 26:t=K.getUint32(f),f+=4;break}return t}function ct(){if(I.getShared){let t=er(()=>(w=null,I.getShared()))||{},e=t.structures||[];I.sharedVersion=t.version,W=I.sharedValues=t.packedValues,B===!0?I.structures=B=e:B.splice.apply(B,[0,e.length].concat(e))}}function er(t){let e=q,r=f,s=ke,n=Oe,i=ce,l=Ie,y=ae,p=G,A=z,E=new Uint8Array(w.slice(0,q)),R=B,M=I,N=Re,_=t();return q=e,f=r,ke=s,Oe=n,ce=i,Ie=l,ae=y,G=p,z=A,w=E,Re=N,B=R,I=M,K=new DataView(w.buffer,w.byteOffset,w.byteLength),_}function lt(){w=null,G=null,B=null}const ft=new Array(147);for(let t=0;t<256;t++)ft[t]=+("1e"+Math.floor(45.15-t*.30103));let ut=new be({useRecords:!1});const rn=ut.decode;ut.decodeMultiple;let Fe;try{Fe=new TextEncoder}catch{}let dt,tr;const je=typeof globalThis=="object"&&globalThis.Buffer,Me=typeof je<"u",ht=Me?je.allocUnsafeSlow:Uint8Array,rr=Me?je:Uint8Array,sr=256,nr=Me?4294967296:2144337920;let pt,c,L,o=0,re,j=null;const sn=61440,nn=/[\u0080-\uFFFF]/,J=Symbol("record-id");class ir extends be{constructor(e){super(e),this.offset=0;let r,s,n,i,l;e=e||{};let y=rr.prototype.utf8Write?function(a,g){return c.utf8Write(a,g,c.byteLength-g)}:Fe&&Fe.encodeInto?function(a,g){return Fe.encodeInto(a,c.subarray(g)).written}:!1,p=this,A=e.structures||e.saveStructures,E=e.maxSharedStructures;if(E==null&&(E=A?128:0),E>8190)throw new Error("Maximum maxSharedStructure is 8190");let R=e.sequential;R&&(E=0),this.structures||(this.structures=[]),this.saveStructures&&(this.saveShared=this.saveStructures);let M,N,_=e.sharedValues,C;if(_){C=Object.create(null);for(let a=0,g=_.length;a<g;a++)C[_[a]]=a}let Z=[],Ee=0,Y=0;this.mapEncode=function(a,g){return this._keyMap&&!this._mapped&&a.constructor.name==="Array"&&(a=a.map(d=>this.encodeKeys(d))),this.encode(a,g)},this.encode=function(a,g){if(c||(c=new ht(8192),L=new DataView(c.buffer,0,8192),o=0),re=c.length-10,re-o<2048?(c=new ht(c.length),L=new DataView(c.buffer,0,c.length),re=c.length-10,o=0):g===lr&&(o=o+7&2147483640),r=o,p.useSelfDescribedHeader&&(L.setUint32(o,3654940416),o+=3),l=p.structuredClone?new Map:null,p.bundleStrings&&typeof a!="string"?(j=[],j.size=1/0):j=null,s=p.structures,s){if(s.uninitialized){let h=p.getShared()||{};p.structures=s=h.structures||[],p.sharedVersion=h.version;let u=p.sharedValues=h.packedValues;if(u){C={};for(let b=0,S=u.length;b<S;b++)C[u[b]]=b}}let d=s.length;if(d>E&&!R&&(d=E),!s.transitions){s.transitions=Object.create(null);for(let h=0;h<d;h++){let u=s[h];if(!u)continue;let b,S=s.transitions;for(let v=0,x=u.length;v<x;v++){S[J]===void 0&&(S[J]=h);let T=u[v];b=S[T],b||(b=S[T]=Object.create(null)),S=b}S[J]=h|1048576}}R||(s.nextId=d)}if(n&&(n=!1),i=s||[],N=C,e.pack){let d=new Map;if(d.values=[],d.encoder=p,d.maxValues=e.maxPrivatePackedValues||(C?16:1/0),d.objectMap=C||!1,d.samplingPackedValues=M,$e(a,d),d.values.length>0){c[o++]=216,c[o++]=51,Q(4);let h=d.values;k(h),Q(0),Q(0),N=Object.create(C||null);for(let u=0,b=h.length;u<b;u++)N[h[u]]=u}}pt=g&mt;try{if(pt)return;if(k(a),j&&cr(r,k),p.offset=o,l&&l.idsToInsert){o+=l.idsToInsert.length*2,o>re&&de(o),p.offset=o;let d=cn(c.subarray(r,o),l.idsToInsert);return l=null,d}return g&lr?(c.start=r,c.end=o,c):c.subarray(r,o)}finally{if(s){if(Y<10&&Y++,s.length>E&&(s.length=E),Ee>1e4)s.transitions=null,Y=0,Ee=0,Z.length>0&&(Z=[]);else if(Z.length>0&&!R){for(let d=0,h=Z.length;d<h;d++)Z[d][J]=void 0;Z=[]}}if(n&&p.saveShared){p.structures.length>E&&(p.structures=p.structures.slice(0,E));let d=c.subarray(r,o);return p.updateSharedData()===!1?p.encode(a):d}g&fn&&(o=r)}},this.findCommonStringsToPack=()=>(M=new Map,C||(C=Object.create(null)),a=>{let g=a&&a.threshold||4,d=this.pack?a.maxPrivatePackedValues||16:0;_||(_=this.sharedValues=[]);for(let[h,u]of M)u.count>g&&(C[h]=d++,_.push(h),n=!0);for(;this.saveShared&&this.updateSharedData()===!1;);M=null});const k=a=>{o>re&&(c=de(o));var g=typeof a,d;if(g==="string"){if(N){let S=N[a];if(S>=0){S<16?c[o++]=S+224:(c[o++]=198,S&1?k(15-S>>1):k(S-16>>1));return}else if(M&&!e.pack){let v=M.get(a);v?v.count++:M.set(a,{count:1})}}let h=a.length;if(j&&h>=4&&h<1024){if((j.size+=h)>sn){let v,x=(j[0]?j[0].length*3+j[1].length:0)+10;o+x>re&&(c=de(o+x)),c[o++]=217,c[o++]=223,c[o++]=249,c[o++]=j.position?132:130,c[o++]=26,v=o-r,o+=4,j.position&&cr(r,k),j=["",""],j.size=0,j.position=v}let S=nn.test(a);j[S?0:1]+=a,c[o++]=S?206:207,k(h);return}let u;h<32?u=1:h<256?u=2:h<65536?u=3:u=5;let b=h*3;if(o+b>re&&(c=de(o+b)),h<64||!y){let S,v,x,T=o+u;for(S=0;S<h;S++)v=a.charCodeAt(S),v<128?c[T++]=v:v<2048?(c[T++]=v>>6|192,c[T++]=v&63|128):(v&64512)===55296&&((x=a.charCodeAt(S+1))&64512)===56320?(v=65536+((v&1023)<<10)+(x&1023),S++,c[T++]=v>>18|240,c[T++]=v>>12&63|128,c[T++]=v>>6&63|128,c[T++]=v&63|128):(c[T++]=v>>12|224,c[T++]=v>>6&63|128,c[T++]=v&63|128);d=T-o-u}else d=y(a,o+u,b);d<24?c[o++]=96|d:d<256?(u<2&&c.copyWithin(o+2,o+1,o+1+d),c[o++]=120,c[o++]=d):d<65536?(u<3&&c.copyWithin(o+3,o+2,o+2+d),c[o++]=121,c[o++]=d>>8,c[o++]=d&255):(u<5&&c.copyWithin(o+5,o+3,o+3+d),c[o++]=122,L.setUint32(o,d),o+=4),o+=d}else if(g==="number")if(!this.alwaysUseFloat&&a>>>0===a)a<24?c[o++]=a:a<256?(c[o++]=24,c[o++]=a):a<65536?(c[o++]=25,c[o++]=a>>8,c[o++]=a&255):(c[o++]=26,L.setUint32(o,a),o+=4);else if(!this.alwaysUseFloat&&a>>0===a)a>=-24?c[o++]=31-a:a>=-256?(c[o++]=56,c[o++]=~a):a>=-65536?(c[o++]=57,L.setUint16(o,~a),o+=2):(c[o++]=58,L.setUint32(o,~a),o+=4);else if(!this.alwaysUseFloat&&a<0&&a>=-4294967296&&Math.floor(a)===a)c[o++]=58,L.setUint32(o,-1-a),o+=4;else{let h;if((h=this.useFloat32)>0&&a<4294967296&&a>=-2147483648){c[o++]=250,L.setFloat32(o,a);let u;if(h<4||(u=a*ft[(c[o]&127)<<1|c[o+1]>>7])>>0===u){o+=4;return}else o--}c[o++]=251,L.setFloat64(o,a),o+=8}else if(g==="object")if(!a)c[o++]=246;else{if(l){let u=l.get(a);if(u){if(c[o++]=216,c[o++]=29,c[o++]=25,!u.references){let b=l.idsToInsert||(l.idsToInsert=[]);u.references=[],b.push(u)}u.references.push(o-r),o+=2;return}else l.set(a,{offset:o-r})}let h=a.constructor;if(h===Object)this.skipFunction===!0&&(a=Object.fromEntries([...Object.keys(a).filter(u=>typeof a[u]!="function").map(u=>[u,a[u]])])),V(a);else if(h===Array){d=a.length,d<24?c[o++]=128|d:Q(d);for(let u=0;u<d;u++)k(a[u])}else if(h===Map)if((this.mapsAsObjects?this.useTag259ForMaps!==!1:this.useTag259ForMaps)&&(c[o++]=217,c[o++]=1,c[o++]=3),d=a.size,d<24?c[o++]=160|d:d<256?(c[o++]=184,c[o++]=d):d<65536?(c[o++]=185,c[o++]=d>>8,c[o++]=d&255):(c[o++]=186,L.setUint32(o,d),o+=4),p.keyMap)for(let[u,b]of a)k(p.encodeKey(u)),k(b);else for(let[u,b]of a)k(u),k(b);else{for(let u=0,b=dt.length;u<b;u++){let S=tr[u];if(a instanceof S){let v=dt[u],x=v.tag;x==null&&(x=v.getTag&&v.getTag.call(this,a)),x<24?c[o++]=192|x:x<256?(c[o++]=216,c[o++]=x):x<65536?(c[o++]=217,c[o++]=x>>8,c[o++]=x&255):x>-1&&(c[o++]=218,L.setUint32(o,x),o+=4),v.encode.call(this,a,k,de);return}}if(a[Symbol.iterator]){if(pt){let u=new Error("Iterable should be serialized as iterator");throw u.iteratorNotHandled=!0,u}c[o++]=159;for(let u of a)k(u);c[o++]=255;return}if(a[Symbol.asyncIterator]||yt(a)){let u=new Error("Iterable/blob should be serialized as iterator");throw u.iteratorNotHandled=!0,u}if(this.useToJSON&&a.toJSON){const u=a.toJSON();if(u!==a)return k(u)}V(a)}}else if(g==="boolean")c[o++]=a?245:244;else if(g==="bigint"){if(a<BigInt(1)<<BigInt(64)&&a>=0)c[o++]=27,L.setBigUint64(o,a);else if(a>-(BigInt(1)<<BigInt(64))&&a<0)c[o++]=59,L.setBigUint64(o,-a-BigInt(1));else if(this.largeBigIntToFloat)c[o++]=251,L.setFloat64(o,Number(a));else{a>=BigInt(0)?c[o++]=194:(c[o++]=195,a=BigInt(-1)-a);let h=[];for(;a;)h.push(Number(a&BigInt(255))),a>>=BigInt(8);wt(new Uint8Array(h.reverse()),de);return}o+=8}else if(g==="undefined")c[o++]=247;else throw new Error("Unknown type: "+g)},V=this.useRecords===!1?this.variableMapSize?a=>{let g=Object.keys(a),d=Object.values(a),h=g.length;if(h<24?c[o++]=160|h:h<256?(c[o++]=184,c[o++]=h):h<65536?(c[o++]=185,c[o++]=h>>8,c[o++]=h&255):(c[o++]=186,L.setUint32(o,h),o+=4),p.keyMap)for(let u=0;u<h;u++)k(p.encodeKey(g[u])),k(d[u]);else for(let u=0;u<h;u++)k(g[u]),k(d[u])}:a=>{c[o++]=185;let g=o-r;o+=2;let d=0;if(p.keyMap)for(let h in a)(typeof a.hasOwnProperty!="function"||a.hasOwnProperty(h))&&(k(p.encodeKey(h)),k(a[h]),d++);else for(let h in a)(typeof a.hasOwnProperty!="function"||a.hasOwnProperty(h))&&(k(h),k(a[h]),d++);c[g+++r]=d>>8,c[g+r]=d&255}:(a,g)=>{let d,h=i.transitions||(i.transitions=Object.create(null)),u=0,b=0,S,v;if(this.keyMap){v=Object.keys(a).map(T=>this.encodeKey(T)),b=v.length;for(let T=0;T<b;T++){let Rt=v[T];d=h[Rt],d||(d=h[Rt]=Object.create(null),u++),h=d}}else for(let T in a)(typeof a.hasOwnProperty!="function"||a.hasOwnProperty(T))&&(d=h[T],d||(h[J]&1048576&&(S=h[J]&65535),d=h[T]=Object.create(null),u++),h=d,b++);let x=h[J];if(x!==void 0)x&=65535,c[o++]=217,c[o++]=x>>8|224,c[o++]=x&255;else if(v||(v=h.__keys__||(h.__keys__=Object.keys(a))),S===void 0?(x=i.nextId++,x||(x=0,i.nextId=1),x>=sr&&(i.nextId=(x=E)+1)):x=S,i[x]=v,x<E){c[o++]=217,c[o++]=x>>8|224,c[o++]=x&255,h=i.transitions;for(let T=0;T<b;T++)(h[J]===void 0||h[J]&1048576)&&(h[J]=x),h=h[v[T]];h[J]=x|1048576,n=!0}else{if(h[J]=x,L.setUint32(o,3655335680),o+=3,u&&(Ee+=Y*u),Z.length>=sr-E&&(Z.shift()[J]=void 0),Z.push(h),Q(b+2),k(57344+x),k(v),g)return;for(let T in a)(typeof a.hasOwnProperty!="function"||a.hasOwnProperty(T))&&k(a[T]);return}if(b<24?c[o++]=128|b:Q(b),!g)for(let T in a)(typeof a.hasOwnProperty!="function"||a.hasOwnProperty(T))&&k(a[T])},de=a=>{let g;if(a>16777216){if(a-r>nr)throw new Error("Encoded buffer would be larger than maximum buffer size");g=Math.min(nr,Math.round(Math.max((a-r)*(a>67108864?1.25:2),4194304)/4096)*4096)}else g=(Math.max(a-r<<2,c.length-1)>>12)+1<<12;let d=new ht(g);return L=new DataView(d.buffer,0,g),c.copy?c.copy(d,0,r,a):d.set(c.slice(r,a)),o-=r,r=0,re=d.length-10,c=d};let ne=100,It=1e3;this.encodeAsIterable=function(a,g){return Ot(a,g,he)},this.encodeAsAsyncIterable=function(a,g){return Ot(a,g,Tt)};function*he(a,g,d){let h=a.constructor;if(h===Object){let u=p.useRecords!==!1;u?V(a,!0):or(Object.keys(a).length,160);for(let b in a){let S=a[b];u||k(b),S&&typeof S=="object"?g[b]?yield*he(S,g[b]):yield*We(S,g,b):k(S)}}else if(h===Array){let u=a.length;Q(u);for(let b=0;b<u;b++){let S=a[b];S&&(typeof S=="object"||o-r>ne)?g.element?yield*he(S,g.element):yield*We(S,g,"element"):k(S)}}else if(a[Symbol.iterator]&&!a.buffer){c[o++]=159;for(let u of a)u&&(typeof u=="object"||o-r>ne)?g.element?yield*he(u,g.element):yield*We(u,g,"element"):k(u);c[o++]=255}else yt(a)?(or(a.size,64),yield c.subarray(r,o),yield a,Se()):a[Symbol.asyncIterator]?(c[o++]=159,yield c.subarray(r,o),yield a,Se(),c[o++]=255):k(a);d&&o>r?yield c.subarray(r,o):o-r>ne&&(yield c.subarray(r,o),Se())}function*We(a,g,d){let h=o-r;try{k(a),o-r>ne&&(yield c.subarray(r,o),Se())}catch(u){if(u.iteratorNotHandled)g[d]={},o=r+h,yield*he.call(this,a,g[d]);else throw u}}function Se(){ne=It,p.encode(null,mt)}function Ot(a,g,d){return g&&g.chunkThreshold?ne=It=g.chunkThreshold:ne=100,a&&typeof a=="object"?(p.encode(null,mt),d(a,p.iterateProperties||(p.iterateProperties={}),!0)):[p.encode(a)]}async function*Tt(a,g){for(let d of he(a,g,!0)){let h=d.constructor;if(h===rr||h===Uint8Array)yield d;else if(yt(d)){let u=d.stream().getReader(),b;for(;!(b=await u.read()).done;)yield b.value}else if(d[Symbol.asyncIterator])for await(let u of d)Se(),u?yield*Tt(u,g.async||(g.async={})):yield p.encode(u);else yield d}}}useBuffer(e){c=e,L=new DataView(c.buffer,c.byteOffset,c.byteLength),o=0}clearSharedData(){this.structures&&(this.structures=[]),this.sharedValues&&(this.sharedValues=void 0)}updateSharedData(){let e=this.sharedVersion||0;this.sharedVersion=e+1;let r=this.structures.slice(0),s=new ar(r,this.sharedValues,this.sharedVersion),n=this.saveShared(s,i=>(i&&i.version||0)==e);return n===!1?(s=this.getShared()||{},this.structures=s.structures||[],this.sharedValues=s.packedValues,this.sharedVersion=s.version,this.structures.nextId=this.structures.length):r.forEach((i,l)=>this.structures[l]=i),n}}function or(t,e){t<24?c[o++]=e|t:t<256?(c[o++]=e|24,c[o++]=t):t<65536?(c[o++]=e|25,c[o++]=t>>8,c[o++]=t&255):(c[o++]=e|26,L.setUint32(o,t),o+=4)}class ar{constructor(e,r,s){this.structures=e,this.packedValues=r,this.version=s}}function Q(t){t<24?c[o++]=128|t:t<256?(c[o++]=152,c[o++]=t):t<65536?(c[o++]=153,c[o++]=t>>8,c[o++]=t&255):(c[o++]=154,L.setUint32(o,t),o+=4)}const on=typeof Blob>"u"?function(){}:Blob;function yt(t){if(t instanceof on)return!0;let e=t[Symbol.toStringTag];return e==="Blob"||e==="File"}function $e(t,e){switch(typeof t){case"string":if(t.length>3){if(e.objectMap[t]>-1||e.values.length>=e.maxValues)return;let s=e.get(t);if(s)++s.count==2&&e.values.push(t);else if(e.set(t,{count:1}),e.samplingPackedValues){let n=e.samplingPackedValues.get(t);n?n.count++:e.samplingPackedValues.set(t,{count:1})}}break;case"object":if(t)if(t instanceof Array)for(let s=0,n=t.length;s<n;s++)$e(t[s],e);else{let s=!e.encoder.useRecords;for(var r in t)t.hasOwnProperty(r)&&(s&&$e(r,e),$e(t[r],e))}break;case"function":console.log(t)}}const an=new Uint8Array(new Uint16Array([1]).buffer)[0]==1;tr=[Date,Set,Error,RegExp,fe,ArrayBuffer,Uint8Array,Uint8ClampedArray,Uint16Array,Uint32Array,typeof BigUint64Array>"u"?function(){}:BigUint64Array,Int8Array,Int16Array,Int32Array,typeof BigInt64Array>"u"?function(){}:BigInt64Array,Float32Array,Float64Array,ar],dt=[{tag:1,encode(t,e){let r=t.getTime()/1e3;(this.useTimestamp32||t.getMilliseconds()===0)&&r>=0&&r<4294967296?(c[o++]=26,L.setUint32(o,r),o+=4):(c[o++]=251,L.setFloat64(o,r),o+=8)}},{tag:258,encode(t,e){let r=Array.from(t);e(r)}},{tag:27,encode(t,e){e([t.name,t.message])}},{tag:27,encode(t,e){e(["RegExp",t.source,t.flags])}},{getTag(t){return t.tag},encode(t,e){e(t.value)}},{encode(t,e,r){wt(t,r)}},{getTag(t){if(t.constructor===Uint8Array&&(this.tagUint8Array||Me&&this.tagUint8Array!==!1))return 64},encode(t,e,r){wt(t,r)}},X(68,1),X(69,2),X(70,4),X(71,8),X(72,1),X(77,2),X(78,4),X(79,8),X(85,4),X(86,8),{encode(t,e){let r=t.packedValues||[],s=t.structures||[];if(r.values.length>0){c[o++]=216,c[o++]=51,Q(4);let n=r.values;e(n),Q(0),Q(0),packedObjectMap=Object.create(sharedPackedObjectMap||null);for(let i=0,l=n.length;i<l;i++)packedObjectMap[n[i]]=i}if(s){L.setUint32(o,3655335424),o+=3;let n=s.slice(0);n.unshift(57344),n.push(new fe(t.version,1399353956)),e(n)}else e(new fe(t.version,1399353956))}}];function X(t,e){return!an&&e>1&&(t-=4),{tag:t,encode:function(s,n){let i=s.byteLength,l=s.byteOffset||0,y=s.buffer||s;n(Me?je.from(y,l,i):new Uint8Array(y,l,i))}}}function wt(t,e){let r=t.byteLength;r<24?c[o++]=64+r:r<256?(c[o++]=88,c[o++]=r):r<65536?(c[o++]=89,c[o++]=r>>8,c[o++]=r&255):(c[o++]=90,L.setUint32(o,r),o+=4),o+r>=c.length&&e(o+r),c.set(t.buffer?t:new Uint8Array(t),o),o+=r}function cn(t,e){let r,s=e.length*2,n=t.length-s;e.sort((i,l)=>i.offset>l.offset?1:-1);for(let i=0;i<e.length;i++){let l=e[i];l.id=i;for(let y of l.references)t[y++]=i>>8,t[y]=i&255}for(;r=e.pop();){let i=r.offset;t.copyWithin(i+s,i,n),s-=2;let l=i+s;t[l++]=216,t[l++]=28,n=i}return t}function cr(t,e){L.setUint32(j.position+t,o-j.position-t+1);let r=j;j=null,e(r[0]),e(r[1])}let gt=new ir({useRecords:!1});const ln=gt.encode;gt.encodeAsIterable,gt.encodeAsAsyncIterable;const lr=512,fn=1024,mt=2048;class un extends Vr{constructor(e){e||(e={}),e.objectMode=!0,super(e),e.structures=[],this.decoder=e.decoder||new be(e)}_transform(e,r,s){this.incompleteBuffer&&(e=Buffer.concat([this.incompleteBuffer,e]),this.incompleteBuffer=null);let n;try{n=this.decoder.decodeMultiple(e)}catch(i){if(i.incomplete)this.incompleteBuffer=e.slice(i.lastPosition),n=i.values;else return s(i)}finally{for(let i of n||[])i===null&&(i=this.getNullValue()),this.push(i)}s()}getNullValue(){return Symbol.for(null)}}const dn=process.env.CBOR_NATIVE_ACCELERATION_DISABLED!==void 0&&process.env.CBOR_NATIVE_ACCELERATION_DISABLED.toLowerCase()==="true";if(!dn){let t;try{typeof require=="function"?t=require("cbor-extract"):t=Kr(import.meta.url)("cbor-extract"),t&&Ws(t.extractStrings)}catch{}}const fr=["light","dark"],ur=["xs","s","m","l","xl","xxl","xxxl"];function hn(t){return{adbShellCommand:t.android?.shell,appearance:t.appearance,deviceType:t.id,disableVirtualKeyboard:t.android?.softKeyboard===!1?!0:void 0,fontSize:t.fontSize,iosAutocorrect:t.ios?.autocorrect,iosKeyboard:t.ios?.keyboards,language:t.locale,locale:t.locale,location:t.location&&[t.location.latitude,t.location.longitude],orientation:t.orientation,osVersion:t.osVersion,timezone:t.timezone}}const dr=["grant"];function pn(t){return{grantPermissions:t?.permissions==="grant"?!0:void 0,launchApp:t?.app,launchArgs:t?.ios?.args,launchUrl:t?.url,params:t?.params}}class hr extends Error{code;issues;constructor(e,r,s=[]){super(r),this.name="SessionRequestError",this.code=e,this.issues=s}}const P=t=>`expected ${t}`,ge=t=>m.string(P(t)).check(m.minLength(1,P(t))),Ue=t=>m.literal(t,P(`one of ${t.join(", ")}`)),me=t=>m.object(t,P("an object")),pr=()=>m.boolean(P("true or false")),yr=t=>m.number(P("a number")).check(m.gte(-t,P(`at least -${String(t)}`)),m.lte(t,P(`at most ${String(t)}`))),yn=/^\w{2}(?:_\w{2})?@sw(=[\w-]+)?$/,wn=/^[a-z0-9_.=:/ ()"-]+$/i,gn='letters, digits or _ . = : / ( ) " - and spaces',mn=/^[A-Za-z]{2,3}([-_][A-Za-z0-9]{2,8})*$/;function bn(t){if(!mn.test(t))return!1;try{return new Intl.Locale(t.replaceAll("_","-")),!0}catch{return!1}}function En(t){try{return new Intl.DateTimeFormat(void 0,{timeZone:t}),!0}catch{return!1}}const bt={code:"needsTarget"},wr={code:"needsLaunchApp"},Et="has no effect without a target",gr="has no effect without a target, or with launch.app: false";function mr({launch:t}){return t?.app!==!1}const Sn=m.object({apiToken:m.optional(ge("an API token")),codec:m.optional(Ue(es)),device:me({android:m.optional(me({shell:m.optional(ge("a shell command")),softKeyboard:m.optional(pr())})),appearance:m.optional(Ue(fr)),fontSize:m.optional(Ue(ur)),id:ge("a device id"),ios:m.optional(me({autocorrect:m.optional(pr()),keyboards:m.optional(m.array(m.string(P("a keyboard layout")).check(m.regex(yn,P("a layout like en_US@sw=QWERTY"))),P("a list of keyboard layouts")))})),locale:m.optional(m.string(P("a BCP 47 tag, e.g. fr-CA")).check(m.refine(bn,{error:P("a BCP 47 tag, e.g. fr-CA")}))),location:m.optional(me({latitude:yr(90),longitude:yr(180)})),orientation:m.optional(Ue(_t)),osVersion:m.optional(ge("an OS version")),timezone:m.optional(m.string(P("an IANA timezone")).check(m.refine(En,{error:P("an IANA timezone, e.g. America/Toronto")})))}),endpoint:m.optional(m.url(P("a URL"))),launch:m.optional(me({app:m.optional(m.union([ge("an app id"),m.literal(!1)],P("an app id or false"))),ios:m.optional(me({args:m.optional(m.array(m.string(P("an argument")).check(m.regex(wn,P(gn))),P("a list of arguments")).check(m.maxLength(20,P("at most 20 arguments"))))})),params:m.optional(m.custom(t=>typeof t=="object"&&t!==null&&!Array.isArray(t),P("an object"))),permissions:m.optional(Ue(dr)),url:m.optional(m.url(P("a URL")))})),proxy:m.optional(m.union([m.literal("intercept"),m.templateLiteral(["http://",m.string()])],P("intercept or an http:// URL"))),target:m.optional(ge("an app, build or group id"))}).check(m.refine(t=>t.device.android?.shell===void 0||t.target!==void 0,{error:Et,params:bt,path:["device","android","shell"]}),m.refine(t=>t.launch?.app===void 0||t.target!==void 0,{error:Et,params:bt,path:["launch","app"]}),m.refine(t=>t.launch?.permissions===void 0||t.target!==void 0,{error:Et,params:bt,path:["launch","permissions"]}),m.refine(t=>t.launch?.params===void 0||t.target!==void 0&&mr(t),{error:gr,params:wr,path:["launch","params"]}),m.refine(t=>t.launch?.ios?.args===void 0||t.target!==void 0&&mr(t),{error:gr,params:wr,path:["launch","ios","args"]}));function vn(t){if(t.code==="custom"){const e=t.params?.code;if(e==="needsTarget"||e==="needsLaunchApp")return e}return"invalidValue"}function An(t){const e=Sn.safeParse(t);if(e.success)return;const r=e.error.issues.map(s=>({code:vn(s),message:s.message,path:s.path.join(".")}));throw new hr("invalid",r.map(({message:s,path:n})=>`${n}: ${s}`).join(`
2
- `),r)}const xn={dateStyle:"medium",timeStyle:"short"},kn=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(?::\d{2}(?:\.\d+)?)?(?:Z|[+-]\d{2}:\d{2})$/;function Ve(t){return Array.isArray(t)?t.map(Ve).join(", "):typeof t=="boolean"?t?"yes":"no":typeof t=="number"?t.toLocaleString():In(t)}function In(t){if(kn.test(t)){const r=new Date(t);if(!Number.isNaN(r.getTime()))return r.toLocaleString(void 0,xn)}const e=Ut();return t===e?"~":t.startsWith(`${e}${$r}`)?`~${t.slice(e.length)}`:t}function br(){return process.env.APPETIZE_CLI_HOME??ie(Ut(),".appetize","cli","sessions")}function St(t){return ie(br(),t)}class Ke extends Error{details;constructor(e,r={},s){super(e,s===void 0?void 0:{cause:s}),this.name="CommandError",this.details=r}hints(e){return[]}}class Ce extends Ke{sessionDir;constructor(e,{cause:r,details:s={},sessionId:n}){const i=St(n);super(e,Object.assign({sessionDir:i},s),r),this.name="SessionError",this.sessionDir=i}static wrap(e,r){if(e instanceof Ce||e instanceof se)return e;const s=e instanceof Error?e.message:String(e),n=e instanceof Ke?e.details:{};return new Ce(s,{cause:e,details:n,sessionId:r})}hints(){return[`Check the session logs for details: ${Ve(this.sessionDir)}`]}}class On extends Ce{constructor(e){super(`Session ${e} already exists`,{sessionId:e}),this.name="SessionAlreadyExistsError"}hints(){return[`Pass --force to replace it, deleting ${Ve(this.sessionDir)}`]}}class se extends Ke{#e;constructor(e,r=[]){super(e),this.name="UsageError",this.#e=r}hints({command:e}){return[...this.#e,`Run 'appetize ${e} --help' for usage`]}}function Tn(t,e,r){const s=e instanceof Error?e.message:String(e);if(!(e instanceof Ke))return t==="json"?JSON.stringify({error:{message:s}},null,2):`\u2716 ${s}`;const n=e.hints(r);if(t==="json"){const i=n.length>0?{hints:n}:{};return JSON.stringify({error:{message:s,...e.details,...i}},null,2)}return[`\u2716 ${s}`,...n.map(i=>` ${i}`)].join(`
3
- `)}function vt(t){try{return process.kill(t,0),!0}catch{return!1}}const Rn=["SIGINT","SIGTERM"],Mn=150;function Un(t){const e=new AbortController,r=setInterval(()=>{vt(t)||(clearInterval(r),e.abort(new Error("The device session exited")))},Mn);return r.unref(),e.signal}function Er(){const t=new AbortController;for(const e of Rn)process.once(e,()=>{t.abort(new Error(`Received ${e}`))});return t.signal}function Ln(t,e){return new Promise((r,s)=>{if(e.aborted){s(Sr(e.reason));return}const n=()=>{clearTimeout(i),s(Sr(e.reason))},i=setTimeout(()=>{e.removeEventListener("abort",n),r()},t);e.addEventListener("abort",n,{once:!0})})}function Sr(t){return t instanceof Error?t:new Error(String(t))}function Cn(t){return Object.values(t).some(e=>e!==void 0)?t:void 0}function Pn(t,{defaultValue:e=!1}={}){return t===!e?!e:void 0}function _n(t,e,r){const s=qe(t,r);if(s===void 0)return;const n=e.find(i=>i===s);if(n===void 0)throw new se(`${r} expects one of ${e.join(", ")}`);return n}function Nn(t){const e=t.at(-1);return{options:zn(e)?e:{},positionals:t.slice(0,-1).filter(r=>typeof r=="string"),signal:Er()}}function Dn(t,e){const r=vr(t,e);return r===void 0?void 0:Ar(r,e)}function vr(t,e){if(t===void 0)return;const r=typeof t=="boolean"?Number.NaN:Number(t);if(!Number.isFinite(r))throw new se(`${e} expects a number, e.g., ${e}=-0.1`);return r}function Bn(t,e){return t===void 0?void 0:(Array.isArray(t)?t:[t]).map(s=>xr(s,e))}function qe(t,e){if(t!==void 0){if(typeof t!="string"||t==="")throw new se(`${e} needs a value`);return t}}function Ar(t,e){if(!(t>=0&&t<=1))throw new se(`${e} expects a number between 0 and 1`);return t}function xr(t,e){const r=qe(t,e);if(r===void 0)throw new se(`${e} needs a value`);return r}function zn(t){return typeof t=="object"&&t!==null}const Fn="APPETIZEIO_FEATURE_FLAGS";function jn(){const t={};for(const e of(process.env[Fn]??"").split(",")){const r=e.trim();r!==""&&(t[r]=!0)}return t}function $n(){const t=process.env.APPETIZE_API_TOKEN;if(!t)throw new Error("APPETIZE_API_TOKEN must be set");return t}function kr(t){return qe(t.endpoint,"--endpoint")??Vn()}function Vn(){const t=process.env.APPETIZE_ENDPOINT?.trim();return t===""?void 0:t}const Kn="https://appetize.io";async function Ir(t,{authorize:e=!0,commandOptions:r={},query:s={},...n}={}){const i=new URL(t,kr(r)??Kn);for(const[p,A]of Object.entries(s))i.searchParams.set(p,A);const l=new Headers(n.headers);e&&l.set("x-api-key",$n());const y=await fetch(i,{...n,headers:l});if(!y.ok)throw new Error(`The webserver rejected the request (${String(y.status)})`);return await y.json()}const Or=["android","ios"];function Tr(t={},e){return Ir("/api/v2/service/devices",{authorize:!1,commandOptions:t,signal:e})}function qn(t){return Or.includes(t)}async function Wn(t,e={}){return(await Tr(e)).find(s=>s.id===t)?.platform}function Jn(t){let e={...t,updatedAt:new Date().toISOString()};return{path:xt(e.sessionId),save:r=>(e={...e,...r,updatedAt:new Date().toISOString()},ti(e),e)}}function Rr(t){const e=t.state?.phase;return e==="ended"||e==="error"?!1:vt(t.pid)}function Gn(){const t=br();return Mt(t,{recursive:!0}),jr(t).map(e=>At(e)).filter(e=>e!==void 0)}function Hn(t){if(t!==void 0){const r=At(t);if(!r)throw new Error(`No session found for id ${t}`);return r}const e=Gn().filter(Rr);if(e.length===0)throw new Error("No active sessions");if(e.length>1)throw new se("There are multiple active sessions",["Specify --session-id to pick one"]);return e[0]}function At(t){try{return JSON.parse(zr(xt(t),"utf8"))}catch{return}}function Zn(t){Fr(St(t),{force:!0,recursive:!0})}function Yn(t){return ie(Le(t),"control.sock")}function Mr(t){return ie(Le(t),"daemon.log")}function Qn(t){return ie(Le(t),"device.log.jsonl")}function Xn(t,e){return{daemon:Mr(t),device:Qn(t),...e==="intercept"?{network:ei(t)}:void 0}}function ei(t){return ie(Le(t),"network.jsonl")}function Le(t){const e=St(t);return Mt(e,{recursive:!0}),e}function xt(t){return ie(Le(t),"state.json")}function ti(t){const e=xt(t.sessionId),r=`${e}.tmp`;Dr(r,`${JSON.stringify(t,null,2)}
4
- `),Br(r,e)}const kt="APPETIZE_DAEMON_CONFIG";function ri(){const t=process.env[kt];if(!t)throw new Error(`${kt} is not set`);return JSON.parse(t)}function si(t){return JSON.stringify(t)}function ni(){let t,e;return{promise:new Promise((s,n)=>{e=s,t=n}),reject:t,resolve:e}}const Ur={useRecords:!1},ii=new ir(Ur);class Lr extends ve{#e=[];#t;constructor(e,{signal:r}={}){super(async l=>{this.#t.write(ii.encode(l))},{signal:r}),this.#t=e;const s=new un(Ur);s.on("data",l=>{Qe(l)&&this[U].dispatchMessage(l)}),s.on("error",()=>{this.close()});const n=l=>{s.write(l)},i=()=>{this.close()};e.on("data",n),e.once("close",i),e.once("error",i),this.#e.push(()=>{e.off("data",n),e.off("close",i),e.off("error",i),s.destroy()})}handleClose(e){for(const r of this.#e.splice(0))r();super.handleClose(e)}}function oi(t,e){const{promise:r,reject:s,resolve:n}=ni(),i=qr(t),l=e?.signal,y=()=>{i.off("connect",E),i.off("error",R),l?.removeEventListener("abort",A)},p=M=>{y(),i.destroy(),s(M)},A=()=>{p(new Error("The connection was aborted"))},E=()=>{y();const M=new Lr(i,e);M[U].addEventListener("close",()=>{i.destroy()},{once:!0}),n(M)},R=M=>{p(M)};return l?.aborted?(p(new Error("The connection was aborted")),r):(i.once("connect",E),i.once("error",R),l?.addEventListener("abort",A,{once:!0}),r)}export{Lr as $,kr as A,At as B,On as C,kt as D,Zn as E,Xn as F,Dn as G,Ve as H,oi as I,Fs as J,Ct as K,Hn as L,Nn as M,Tn as N,Ze as O,ln as P,U as Q,rn as R,Ce as S,ve as T,se as U,Qe as V,Vt as W,Ne as X,pn as Y,hn as Z,He as _,vr as a,ri as a0,Jn as a1,Wn as a2,Yn as a3,Er as a4,Tr as b,Or as c,Ln as d,jt as e,Ir as f,xr as g,_t as h,qn as i,Mr as j,Rr as k,vt as l,Un as m,Cn as n,Pn as o,qe as p,Bn as q,Ar as r,si as s,_n as t,ur as u,fr as v,dr as w,An as x,hr as y,jn as z};