@appetize/cli 0.20.0 → 0.21.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,11 @@
1
1
  # @appetize/cli
2
2
 
3
+ ## 0.21.0
4
+
5
+ ### Minor Changes
6
+
7
+ - feat: `appetize gesture` plays single-pointer gesture syntax
8
+
3
9
  ## 0.20.0
4
10
 
5
11
  ### Minor Changes
package/cli.js CHANGED
@@ -1,11 +1,11 @@
1
1
  #!/usr/bin/env node
2
- import Be from"sade";import{d as Y,D as qe,p as v,a as f,f as N,U as c,b as _,c as Ge,i as Ke,e as Ze,r as Q,g as $,h as We,j as Xe,s as Ve,k as He,l as ee,m as te,S as R,n as Je,o as Ye,q as ne,t as Qe,u as et,v as tt,w as nt,x as oe,y as ot,z as it,A as st,B as rt,C as at}from"./config-DfwUvfKT.js";import{existsSync as ie,openAsBlob as ct,openSync as pt,closeSync as dt}from"node:fs";import{basename as U,extname as lt,resolve as se,dirname as ut,join as S,relative as ft}from"node:path";import{writeFile as re,stat as mt,rm as ht,cp as wt}from"node:fs/promises";import{spawn as gt}from"node:child_process";import{fileURLToPath as ae}from"node:url";import{humanId as yt}from"human-id";import{homedir as vt}from"node:os";import St from"debug";import xt from"yocto-spinner";import bt from"cli-table3";import"stream";import"module";import"node:net";import"json-rpc-2.0";const ce=["back","menu","unlock","volumeDown","volumeUp"],pe=["home","lock"],de=[...pe,...ce],j=["down","left","right","up"];async function Et(e,t={}){const n=await Y(e,{signal:t.signal});return new qe(n,{...t,onClose:()=>{n.close(),t.onClose?.()}})}const le=[{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 z({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 Ot=["app"],It=10,kt=[{fields:le,key:"builds"},{header:"Total",key:"total"},{header:"Next page",key:"nextPage"}];async function $t({options:e,signal:t}){const n=v(e.app,"--app"),o=f(e.limit,"--limit")??It,i=f(e.page,"--page"),s={limit:String(o)};n!==void 0&&(s.appId=n),i!==void 0&&(s.page=String(i));const r=await N("/api/v2/builds",{commandOptions:e,query:s,signal:t});return{builds:r.builds.map(z),nextPage:r.nextPage,total:r.total}}const At=["note","tags"],ue=12e4,Pt=2e3,F=[".apk",".apks",".zip",".tar.gz",".tgz"],Tt={".apk":"android",".apks":"android",".tar.gz":"ios",".tgz":"ios",".zip":"ios"},Dt=le;async function Lt({options:e,positionals:[t],progress:n,signal:o}){const i=Rt(t),s=U(t);n.status(`Uploading ${s}`);const r=await Ut(t,i,e,o);if(e.wait!==!0)return n.status(`Uploaded ${s}`),z(r);n.step(`Uploaded ${s}`),n.status("Waiting for build metadata");const d=await Nt(r.id,e,o);return n.status(`Processed ${s}`),z(d)}async function Nt(e,t,n){const o=f(t.timeout,"--timeout")??ue,i=Date.now()+o;for(;;){const s=await N(`/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 _(Pt,n)}}async function _t(e){if(!ie(e))throw new Error(`No build file at ${e}`);return await ct(e)}function Rt(e){const t=e.toLowerCase(),n=F.find(o=>t.endsWith(o));if(n===void 0)throw new c(`Cannot tell the platform of ${U(e)}; upload a ${F.join(", ")} file`);return Tt[n]}async function Ut(e,t,n,o){const i=new FormData;i.set("platform",t);const s=v(n.note,"--note");s!==void 0&&i.set("note",s);const r=v(n.tags,"--tags");return r!==void 0&&i.set("tags",r),i.set("file",await _t(e),U(e)),await N("/api/v2/builds",{body:i,commandOptions:n,method:"POST",signal:o})}const jt=["platform"],zt=[{fields:[{header:"ID",key:"id"},{header:"Name",key:"name"},{header:"Platform",key:"platform"},{header:"OS versions",key:"osVersions"}],key:"devices"}];async function Ft({options:e,signal:t}){const n=Ct(e.platform);return{devices:(await Ge(e,t)).filter(i=>n===void 0||i.platform===n).map(Mt)}}function Ct(e){const t=v(e,"--platform");if(t!==void 0){if(!Ke(t))throw new c(`--platform expects one of: ${Ze.join(", ")}`);return t}}function Mt({id:e,name:t,osVersions:n,platform:o}){return{id:e,name:t,osVersions:n,platform:o}}const Bt="APPETIZE_OUTPUT";function qt(e,t,n){return{format:Gt(e,t),progress:Kt(e,n)}}function C(e,{extension:t,strict:n=!1}){const o=lt(e);if(o==="")return`${e}${t}`;if(n&&o!==t)throw new c(`The output must be a path ending in ${t}`);return e}function Gt(e,t){if(e.json===!0)return"json";if(e.json===!1)return"text";const n=process.env[Bt]?.trim();return n==="json"||n==="text"?n:t.isTTY===!0?"text":"json"}function Kt(e,t){return e.quiet===!0?"silent":t.isTTY===!0&&process.env.TERM!=="dumb"&&!("CI"in process.env)?"interactive":"silent"}const x=["text","testId"],m="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"}},M="index",A="position",B="x",q="y";function fe(e,{prefix:t=m}={}){return x.reduce((n,o)=>{const{help:i,suffix:s}=E[o];return n.option(`--${p(t,s)}`,i)},e).option(`--${p(t,M)}`,"Which match when multiple (0-based)")}function G(e,t={}){const{prefix:n=m}=t;return fe(e,t).option(`--${p(n,A)}`,"Screen position to use as x,y (0-1), e.g., 0.5,0.75").option(`--${p(n,B)}`,"Horizontal position within the element (0-1, outside allowed)").option(`--${p(n,q)}`,"Vertical position within the element (0-1, outside allowed)")}function me(e,{prefix:t=m}={}){const n=Z(e,t);if(n.length===0)throw new c(`A selector is required: pass one of ${T(x,t)}`);if(n.length>1)throw new c(`Only one selector may be given, got ${T(n,t)}`);const[o]=n,i=Se(e,p(t,E[o].suffix)),s=f(e[p(t,M)],`--${p(t,M)}`);switch(o){case"testId":return{by:"testId",index:s,testId:i};case"text":return{by:"text",index:s,text:Xt(i)}}}function he(e){const t=f(e.timeout,"--timeout");return t===void 0?void 0:{timeout:t}}function Zt(e,{prefix:t=m}={}){return ye(e,t)?me(e,{prefix:t}):void 0}function P(e,{prefix:t=m}={}){return ye(e,t)?we(e,{prefix:t}):void 0}function we(e,{prefix:t=m}={}){const n=p(t,A),o=e[n],i=ve(e,p(t,B)),s=ve(e,p(t,q));if(o===void 0){if(Z(e,t).length===0)throw new c(`A selector is required: pass one of ${O({prefix:t})}`);return{...me(e,{prefix:t}),x:i,y:s}}if(Z(e,t).length>0)throw new c(`--${n} may not be combined with ${T(x,t)}`);if(i!==void 0||s!==void 0)throw new c(`--${n} may not be combined with --${p(t,B)} or --${p(t,q)}`);return Wt(Se(e,n),n)}function O(e={}){const{prefix:t=m}=e;return`${T(x,t)}, --${p(t,A)}`}function K(e={}){const{prefix:t=m}=e;return[...ge(e),p(t,A)]}function ge({prefix:e=m}={}){return x.map(t=>p(e,E[t].suffix))}function Z(e,t){return x.filter(n=>e[p(t,E[n].suffix)]!==void 0)}function p(...e){return e.filter(Boolean).join("-")}function T(e,t){return e.map(n=>`--${p(t,E[n].suffix)}`).join(", ")}function ye(e,t){return Object.entries(e).some(([n,o])=>o!==void 0&&n.startsWith(`${t}-`))}function ve(e,t){return f(e[t],`--${t}`)}function Wt(e,t){const n=e.split(",");if(n.length!==2)throw new c(`--${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:Q(o,`--${t}`),y:Q(i,`--${t}`)}}function Xt(e){const t=/^\/(.*)\/([a-z]*)$/s.exec(e);return t?new RegExp(t[1],t[2]):e}function Se(e,t){return $(e[t],`--${t}`)}const Vt=ge(),Ht=async({device:e,options:t,positionals:[n]})=>{const o=Jt(n),i=Zt(t),s=await e.inspect(i,he(t)),r=Yt(s,t.pretty===!0);return await re(o,r),{bytes:Buffer.byteLength(r),nodes:xe(s.root),output:o}};function xe(e){return e.children.reduce((t,n)=>t+xe(n),1)}function Jt(e="inspect"){return C(e,{extension:".json"})}function Yt(e,t){return`${JSON.stringify(e,null,t?2:void 0)}
3
- `}const Qt=async({device:e})=>{await e.clearKeychain()},en=async({device:e,positionals:[t]})=>{await e.open(tn(t))};function tn(e){if(typeof e=="string")try{return new URL(e),e}catch{throw new c("<url> expects a URL, e.g., myapp://orders/42")}throw new c("<url> expects a URL, e.g., myapp://orders/42")}const nn=new Set(de),on=async({device:e,positionals:[t]})=>{if(!sn(t))throw new c(`Button must be one of: ${de.join(", ")}`);await e.press(t)};function sn(e){return typeof e=="string"&&nn.has(e)}const rn=async({control:e,options:t,positionals:[n]})=>{const{path:o}=await e.recordStart({force:t.force===!0,path:cn(n)});return{path:o}},an=async({control:e})=>{const{path:t}=await e.recordStop();return{path:t}};function cn(e){const t=se(C(e,{extension:".mp4",strict:!0})),n=ut(t);if(!ie(n))throw new c(`No such directory: ${n}`);return t}const be={landscapeLeft:!0,landscapeRight:!0,portrait:!0,upsideDown:!0},pn=async({device:e,positionals:[t]})=>{if(!dn(t))throw new c(`Orientation must be one of: ${Object.keys(be).join(", ")}`);await e.rotate(t)};function dn(e){return typeof e=="string"&&Object.hasOwn(be,e)}const ln=async({device:e,positionals:[t]})=>{const n=await e.screenshot(),o=fn(n.mimeType,t);return await re(o,n.data),{bytes:n.data.byteLength,output:o}};function un(e){const t=e.split("/").at(1);return`.${t==="jpeg"?"jpg":t??"png"}`}function fn(e,t="screenshot"){return C(t,{extension:un(e)})}function mn(e){const t=ae(new URL("./daemon.js",import.meta.url)),n=pt(We(e.sessionId),"a"),o=gt(process.execPath,[t],{detached:!0,env:{...process.env,[Xe]:Ve(e),DEBUG:hn(process.env.DEBUG)},stdio:["ignore",n,n]});if(dt(n),o.unref(),o.pid===void 0)throw new Error("Failed to spawn the session daemon");return o.pid}function hn(e){return e?`${e},appetize:daemon`:"appetize:daemon"}const wn=/^[a-z0-9](?:[a-z0-9._-]{0,62}[a-z0-9])?$/i;function gn(){return yt({capitalize:!1,separator:"-"})}function yn(e){if(!wn.test(e))throw new c('--session-id must use letters, digits, ".", "-" or "_"');return e}const Ee=1e4;function Oe(e){if(!He(e))return!1;try{process.kill(e.pid,"SIGTERM")}catch{}return!0}async function Ie(e,t){(Oe(e)||Sn(e))&&await vn(e,t)}async function vn({pid:e,sessionId:t},n){const o=te(e);try{await _(Ee,AbortSignal.any([n,o]))}catch(i){if(o.aborted||!ee(e))return;throw i}throw new R(`Session ${t} did not stop in time`,{sessionId:t})}function Sn({endedAt:e,pid:t}){return e!==void 0&&Date.now()-Date.parse(e)<Ee&&ee(t)}const xn=["device-os-version","open","proxy"],bn=150,En={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"},On=[{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 In(e,{onPhase:t,signal:n}){let o;for(;;){const i=ne(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 _(bn,n)}}function kn(e){const t=v(e,"--open");if(t!==void 0){try{new URL(t)}catch{throw new c("--open expects a URL, e.g., myapp://orders/42")}return t}}function $n(e){if(!(e===void 0||e===!1)){if(e===""||e==="intercept")return"intercept";if(typeof e!="string"||!Pn(e))throw new c("--proxy expects 'intercept' or an http:// url, e.g., http://proxy:8080");return e}}async function An({options:e,positionals:[t,n],progress:o,signal:i}){const s=v(e["device-os-version"],"--device-os-version"),r=v(e["session-id"],"--session-id"),d=e.force===!0;if(d&&r===void 0)throw new c("--force needs --session-id");const a=r===void 0?gn():yn(r),l={device:s===void 0?{id:t}:{id:t,osVersion:s},endpoint:Ye(e),featureFlags:Je(),open:kn(e.open),proxy:$n(e.proxy),sessionId:a,target:n},u=ne(a);if(u!==void 0){if(!d)throw new Qe(a);o.status(`Replacing session ${a}`),await Ie(u,i),et(a)}mn(l),o.step(`Session ${a}`);const y=tt(a,l.proxy);if(e.wait===!1)return{logs:y,sessionId:a};const I=await In(a,{onPhase:k=>{Tn(k)&&o.status(En[k]??"Starting the session")},signal:i}).catch(k=>{throw R.wrap(k,a)});return{adbSerial:I.adbSerial,baseUrl:I.baseUrl,controlSocket:I.controlSocket,logs:y,sessionId:a,viewerUrl:I.viewerUrl}}function Pn(e){return e.startsWith("http://")}function Tn(e){return e!=="ended"&&e!=="error"}const Dn=async({options:e,progress:t,record:n,signal:o})=>(e.wait===!1?Oe(n):(t.status(`Stopping session ${n.sessionId}`),await Ie(n,o)),{sessionId:n.sessionId}),ke="appetize",Ln=ae(new URL(`./skills/${ke}/`,import.meta.url)),W=["agents","claude","codex","copilot","cursor"],$e=["project","user"],Nn={agents:".agents",claude:".claude",codex:".codex",copilot:".copilot",cursor:".cursor"},_n=S(".agents","skills"),Rn=["claude","agents"];function Un(e){return W.some(t=>t===e)}function jn(e){return $e.some(t=>t===e)}async function zn(e){const t=e.agents??await Fn(e),n=await Promise.all(t.map(o=>Ae(o,e)));return[...new Set(n.flat())]}async function Ae(e,t){const n=Pe(e,t);if(e==="claude")return[S(n,"skills")];const o=S(t.root,_n);return t.scope==="project"?[o]:await Te(n)?[o,S(n,"skills")]:[o]}function Pe(e,t){if(e==="claude"&&t.scope==="user"){const n=process.env.CLAUDE_CONFIG_DIR?.trim();if(n)return se(n)}return S(t.root,Nn[e])}async function Fn(e){const n=(await Promise.all(W.map(async o=>await Cn(o,e)?o:void 0))).filter(o=>o!==void 0);return n.length>0?n:Rn}async function Cn(e,t){const n=[Pe(e,t),...await Ae(e,t)];return(await Promise.all(n.map(i=>Te(i)))).includes(!0)}async function Te(e){try{return(await mt(e)).isDirectory()}catch{return!1}}const Mn=["agent","scope"];async function Bn({options:e,signal:t}){const n=Kn(e.scope),o=Gn(e.agent),i=n==="user"?vt():process.cwd(),s=await zn({agents:o,root:i,scope:n}),r=[];for(const d of s){t.throwIfAborted();const a=S(d,ke);await ht(a,{force:!0,recursive:!0}),await wt(Ln,a,{recursive:!0}),r.push(n==="user"?a:ft(i,a))}return{installed:r}}function qn(e){const t=$(e,"--agent");if(!Un(t))throw new c(`--agent expects one of ${W.join(", ")}`);return t}function Gn(e){return e===void 0?void 0:(Array.isArray(e)?e:[e]).map(n=>qn(n))}function Kn(e){if(e===void 0)return"project";const t=$(e,"--scope");if(!jn(t))throw new c(`--scope expects one of ${$e.join(", ")}`);return t}const h="from",w="to",Zn=[...K({prefix:h}),...K({prefix:w})],Wn=async({device:e,options:t})=>{await e.swipe(Jn(t),Qn(t))};function Xn(e){return j.some(t=>t===e)}function Vn(e){if(e===void 0)return;const t=$(e,"--direction");if(!Xn(t))throw new c(`--direction expects one of ${j.join(", ")}`);return t}function Hn(e,t){const n=nt(e.distance,"--distance");if(P(e,{prefix:w})!==void 0)throw new c(`--direction may not be combined with --${w}-*`);return{direction:t,distance:n,from:P(e,{prefix:h})}}function Jn(e){const t=Vn(e.direction);return t===void 0?Yn(e):Hn(e,t)}function Yn(e){if(e.distance!==void 0)throw new c("--distance is only valid with --direction");return{from:De(P(e,{prefix:h}),h),to:De(P(e,{prefix:w}),w)}}function Qn(e){const t=f(e.duration,"--duration"),n=f(e.timeout,"--timeout");return t===void 0&&n===void 0?void 0:{duration:t,timeout:n}}function De(e,t){if(e===void 0)throw new c(`A swipe needs --direction, or both endpoints: pass one of ${O({prefix:t})}`);return e}const eo=K(),to=async({device:e,options:t})=>{const n=we(t);await e.tap(n,he(t))},no=async({device:e,options:t,positionals:[n]})=>{await e.type(n,oo(t))};function oo(e){const t=f(e.delay,"--delay");return t===void 0?void 0:{delay:t}}const X=St("appetize:cli"),io={fail:()=>{},status:()=>{},step:()=>{},succeed:()=>{}};function so(e,t,n){return e==="interactive"?ro(t,n):io}function ro(e,t){const n=xt({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}
4
- `)},succeed:()=>{if(!s())return;const r=Math.round((Date.now()-o)/1e3);n.success(`${n.text} (${String(r)}s)`)}}}const ao=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":""},Le=2,po=10;function lo(e){return e.split(/(?=[A-Z])/).map((t,n)=>{const o=t.toLowerCase();return ao.has(o)?o.toUpperCase():n===0?o.charAt(0).toUpperCase()+o.slice(1):o}).join(" ")}function uo(e,t,n){return H(e)?ze(e,t,n):D(e,{fields:t,key:""},n)}function fo(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 Ne(e){return new bt({chars:co,head:e,style:{border:[],head:[],"padding-left":0,"padding-right":Le}})}function _e(e,t){return e.find(n=>n.key===t)}function Re(e,t){return t?.header??lo(e)}function V(e){return e!=null}function H(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Ue(e){return["boolean","number","string"].includes(typeof e)}function je(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 ze(e,t,n){const o=new Map(Object.entries(e)),i=je(t,[...o.keys()]).filter(u=>V(o.get(u))),s=i.map(u=>_e(t,u)),r=i.map((u,y)=>Re(u,s[y])),d=Math.max(0,...r.map(u=>u.length))+Le,a=n===void 0?void 0:n-d-1,l=Ne();return l.push(...i.map((u,y)=>[r[y],D(o.get(u),s[y],a)])),Fe(l.toString())}function mo(e,t){const n=e.map(r=>new Map(Object.entries(r))),o=je(t,n.flatMap(r=>[...r.keys()])),i=o.map(r=>_e(t,r)),s=Ne(o.map((r,d)=>Re(r,i[d])));for(const r of n)s.push(o.map((d,a)=>{const l=r.get(d);return V(l)?D(l,i[a]):""}));return Fe(s.toString())}function D(e,t,n){if(t?.format)return L(t.format(e),n);if(Ue(e))return L(oe(e),n);if(Array.isArray(e)){const o=e.filter(V);return o.every(Ue)?L(oe(o),n):o.every(H)?mo(o,t?.fields??[]):o.map(i=>D(i,t,n)).join(`
5
- `)}return H(e)?ze(e,t?.fields??[],n):L(String(e),n)}function Fe(e){return e.split(`
2
+ import Be from"sade";import{d as Y,D as qe,p as x,a as f,f as N,U as a,b as _,c as Ge,i as Ke,e as Ze,g as We,r as Q,h as k,j as Xe,k as Ve,s as He,l as Je,m as ee,n as te,S as R,o as Ye,q as Qe,t as oe,u as et,v as tt,w as ot,x as nt,y as ne,z as it,A as st,B as rt,C as at,E as ct}from"./config-B56X5rgA.js";import{existsSync as ie,openAsBlob as pt,openSync as dt,closeSync as lt}from"node:fs";import{basename as U,extname as ut,resolve as se,dirname as ft,join as v,relative as mt}from"node:path";import{writeFile as re,stat as ht,rm as wt,cp as gt}from"node:fs/promises";import{spawn as yt}from"node:child_process";import{fileURLToPath as ae}from"node:url";import{humanId as xt}from"human-id";import{homedir as vt}from"node:os";import St from"debug";import bt from"yocto-spinner";import Et from"cli-table3";import"stream";import"module";import"node:net";import"json-rpc-2.0";const ce=["back","menu","unlock","volumeDown","volumeUp"],pe=["home","lock"],de=[...pe,...ce],j=["down","left","right","up"];async function It(e,t={}){const o=await Y(e,{signal:t.signal});return new qe(o,{...t,onClose:()=>{o.close(),t.onClose?.()}})}const le=[{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 z({appId:e,buildNumber:t,created:o,id:n,platform:i,versionName:s}){return{appId:e,buildNumber:t,created:o,id:n,platform:i,versionName:s}}const Ot=["app"],Tt=10,kt=[{fields:le,key:"builds"},{header:"Total",key:"total"},{header:"Next page",key:"nextPage"}];async function Pt({options:e,signal:t}){const o=x(e.app,"--app"),n=f(e.limit,"--limit")??Tt,i=f(e.page,"--page"),s={limit:String(n)};o!==void 0&&(s.appId=o),i!==void 0&&(s.page=String(i));const r=await N("/api/v2/builds",{commandOptions:e,query:s,signal:t});return{builds:r.builds.map(z),nextPage:r.nextPage,total:r.total}}const At=["note","tags"],ue=12e4,$t=2e3,F=[".apk",".apks",".zip",".tar.gz",".tgz"],Dt={".apk":"android",".apks":"android",".tar.gz":"ios",".tgz":"ios",".zip":"ios"},Lt=le;async function Nt({options:e,positionals:[t],progress:o,signal:n}){const i=Ut(t),s=U(t);o.status(`Uploading ${s}`);const r=await jt(t,i,e,n);if(e.wait!==!0)return o.status(`Uploaded ${s}`),z(r);o.step(`Uploaded ${s}`),o.status("Waiting for build metadata");const d=await _t(r.id,e,n);return o.status(`Processed ${s}`),z(d)}async function _t(e,t,o){const n=f(t.timeout,"--timeout")??ue,i=Date.now()+n;for(;;){const s=await N(`/api/v2/builds/${e}`,{commandOptions:t,signal:o});if(s.appId!==void 0)return s;if(Date.now()>=i)throw new Error(`Build ${e} is still being processed after ${String(n)}ms; find it with 'appetize build list'`);await _($t,o)}}async function Rt(e){if(!ie(e))throw new Error(`No build file at ${e}`);return await pt(e)}function Ut(e){const t=e.toLowerCase(),o=F.find(n=>t.endsWith(n));if(o===void 0)throw new a(`Cannot tell the platform of ${U(e)}; upload a ${F.join(", ")} file`);return Dt[o]}async function jt(e,t,o,n){const i=new FormData;i.set("platform",t);const s=x(o.note,"--note");s!==void 0&&i.set("note",s);const r=x(o.tags,"--tags");return r!==void 0&&i.set("tags",r),i.set("file",await Rt(e),U(e)),await N("/api/v2/builds",{body:i,commandOptions:o,method:"POST",signal:n})}const zt=["platform"],Ft=[{fields:[{header:"ID",key:"id"},{header:"Name",key:"name"},{header:"Platform",key:"platform"},{header:"OS versions",key:"osVersions"}],key:"devices"}];async function Ct({options:e,signal:t}){const o=Mt(e.platform);return{devices:(await Ge(e,t)).filter(i=>o===void 0||i.platform===o).map(Bt)}}function Mt(e){const t=x(e,"--platform");if(t!==void 0){if(!Ke(t))throw new a(`--platform expects one of: ${Ze.join(", ")}`);return t}}function Bt({id:e,name:t,osVersions:o,platform:n}){return{id:e,name:t,osVersions:o,platform:n}}const qt=async({device:e,options:t,positionals:[o]})=>{await e.gesture(Kt(o),Gt(t))};function Gt(e){const t=f(e.timeout,"--timeout");return t===void 0?void 0:{timeout:t}}function Kt(e){let t;try{t=We(e)}catch(o){throw o instanceof SyntaxError?new a(o.message):o}if(t.length===0)throw new a("Expected at least one gesture step");return t}const Zt="APPETIZE_OUTPUT";function Wt(e,t,o){return{format:Xt(e,t),progress:Vt(e,o)}}function C(e,{extension:t,strict:o=!1}){const n=ut(e);if(n==="")return`${e}${t}`;if(o&&n!==t)throw new a(`The output must be a path ending in ${t}`);return e}function Xt(e,t){if(e.json===!0)return"json";if(e.json===!1)return"text";const o=process.env[Zt]?.trim();return o==="json"||o==="text"?o:t.isTTY===!0?"text":"json"}function Vt(e,t){return e.quiet===!0?"silent":t.isTTY===!0&&process.env.TERM!=="dumb"&&!("CI"in process.env)?"interactive":"silent"}const S=["text","testId"],h="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"}},M="index",P="position",B="x",q="y";function fe(e,{prefix:t=h}={}){return S.reduce((o,n)=>{const{help:i,suffix:s}=E[n];return o.option(`--${p(t,s)}`,i)},e).option(`--${p(t,M)}`,"Which match when multiple (0-based)")}function G(e,t={}){const{prefix:o=h}=t;return fe(e,t).option(`--${p(o,P)}`,"Screen position to use as x,y (0-1), e.g., 0.5,0.75").option(`--${p(o,B)}`,"Horizontal position within the element (0-1, outside allowed)").option(`--${p(o,q)}`,"Vertical position within the element (0-1, outside allowed)")}function me(e,{prefix:t=h}={}){const o=Z(e,t);if(o.length===0)throw new a(`A selector is required: pass one of ${$(S,t)}`);if(o.length>1)throw new a(`Only one selector may be given, got ${$(o,t)}`);const[n]=o,i=ve(e,p(t,E[n].suffix)),s=f(e[p(t,M)],`--${p(t,M)}`);switch(n){case"testId":return{by:"testId",index:s,testId:i};case"text":return{by:"text",index:s,text:Yt(i)}}}function he(e){const t=f(e.timeout,"--timeout");return t===void 0?void 0:{timeout:t}}function Ht(e,{prefix:t=h}={}){return ye(e,t)?me(e,{prefix:t}):void 0}function A(e,{prefix:t=h}={}){return ye(e,t)?we(e,{prefix:t}):void 0}function we(e,{prefix:t=h}={}){const o=p(t,P),n=e[o],i=xe(e,p(t,B)),s=xe(e,p(t,q));if(n===void 0){if(Z(e,t).length===0)throw new a(`A selector is required: pass one of ${I({prefix:t})}`);return{...me(e,{prefix:t}),x:i,y:s}}if(Z(e,t).length>0)throw new a(`--${o} may not be combined with ${$(S,t)}`);if(i!==void 0||s!==void 0)throw new a(`--${o} may not be combined with --${p(t,B)} or --${p(t,q)}`);return Jt(ve(e,o),o)}function I(e={}){const{prefix:t=h}=e;return`${$(S,t)}, --${p(t,P)}`}function K(e={}){const{prefix:t=h}=e;return[...ge(e),p(t,P)]}function ge({prefix:e=h}={}){return S.map(t=>p(e,E[t].suffix))}function Z(e,t){return S.filter(o=>e[p(t,E[o].suffix)]!==void 0)}function p(...e){return e.filter(Boolean).join("-")}function $(e,t){return e.map(o=>`--${p(t,E[o].suffix)}`).join(", ")}function ye(e,t){return Object.entries(e).some(([o,n])=>n!==void 0&&o.startsWith(`${t}-`))}function xe(e,t){return f(e[t],`--${t}`)}function Jt(e,t){const o=e.split(",");if(o.length!==2)throw new a(`--${t} expects x,y (0-1), e.g., 0.5,0.75`);const[n,i]=o.map(s=>Number(s.trim()));return{by:"position",x:Q(n,`--${t}`),y:Q(i,`--${t}`)}}function Yt(e){const t=/^\/(.*)\/([a-z]*)$/s.exec(e);return t?new RegExp(t[1],t[2]):e}function ve(e,t){return k(e[t],`--${t}`)}const Qt=ge(),eo=async({device:e,options:t,positionals:[o]})=>{const n=to(o),i=Ht(t),s=await e.inspect(i,he(t)),r=oo(s,t.pretty===!0);return await re(n,r),{bytes:Buffer.byteLength(r),nodes:Se(s.root),output:n}};function Se(e){return e.children.reduce((t,o)=>t+Se(o),1)}function to(e="inspect"){return C(e,{extension:".json"})}function oo(e,t){return`${JSON.stringify(e,null,t?2:void 0)}
3
+ `}const no=async({device:e})=>{await e.clearKeychain()},io=async({device:e,positionals:[t]})=>{await e.open(so(t))};function so(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 ro=new Set(de),ao=async({device:e,positionals:[t]})=>{if(!co(t))throw new a(`Button must be one of: ${de.join(", ")}`);await e.press(t)};function co(e){return typeof e=="string"&&ro.has(e)}const po=async({control:e,options:t,positionals:[o]})=>{const{path:n}=await e.recordStart({force:t.force===!0,path:uo(o)});return{path:n}},lo=async({control:e})=>{const{path:t}=await e.recordStop();return{path:t}};function uo(e){const t=se(C(e,{extension:".mp4",strict:!0})),o=ft(t);if(!ie(o))throw new a(`No such directory: ${o}`);return t}const be={landscapeLeft:!0,landscapeRight:!0,portrait:!0,upsideDown:!0},fo=async({device:e,positionals:[t]})=>{if(!mo(t))throw new a(`Orientation must be one of: ${Object.keys(be).join(", ")}`);await e.rotate(t)};function mo(e){return typeof e=="string"&&Object.hasOwn(be,e)}const ho=async({device:e,positionals:[t]})=>{const o=await e.screenshot(),n=go(o.mimeType,t);return await re(n,o.data),{bytes:o.data.byteLength,output:n}};function wo(e){const t=e.split("/").at(1);return`.${t==="jpeg"?"jpg":t??"png"}`}function go(e,t="screenshot"){return C(t,{extension:wo(e)})}function yo(e){const t=ae(new URL("./daemon.js",import.meta.url)),o=dt(Xe(e.sessionId),"a"),n=yt(process.execPath,[t],{detached:!0,env:{...process.env,[Ve]:He(e),DEBUG:xo(process.env.DEBUG)},stdio:["ignore",o,o]});if(lt(o),n.unref(),n.pid===void 0)throw new Error("Failed to spawn the session daemon");return n.pid}function xo(e){return e?`${e},appetize:daemon`:"appetize:daemon"}const vo=/^[a-z0-9](?:[a-z0-9._-]{0,62}[a-z0-9])?$/i;function So(){return xt({capitalize:!1,separator:"-"})}function bo(e){if(!vo.test(e))throw new a('--session-id must use letters, digits, ".", "-" or "_"');return e}const Ee=1e4;function Ie(e){if(!Je(e))return!1;try{process.kill(e.pid,"SIGTERM")}catch{}return!0}async function Oe(e,t){(Ie(e)||Io(e))&&await Eo(e,t)}async function Eo({pid:e,sessionId:t},o){const n=te(e);try{await _(Ee,AbortSignal.any([o,n]))}catch(i){if(n.aborted||!ee(e))return;throw i}throw new R(`Session ${t} did not stop in time`,{sessionId:t})}function Io({endedAt:e,pid:t}){return e!==void 0&&Date.now()-Date.parse(e)<Ee&&ee(t)}const Oo=["device-os-version","open","proxy"],To=150,ko={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"},Po=[{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 Ao(e,{onPhase:t,signal:o}){let n;for(;;){const i=oe(e),s=i?.state?.phase;if(s&&s!==n&&(n=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 _(To,o)}}function $o(e){const t=x(e,"--open");if(t!==void 0){try{new URL(t)}catch{throw new a("--open expects a URL, e.g., myapp://orders/42")}return t}}function Do(e){if(!(e===void 0||e===!1)){if(e===""||e==="intercept")return"intercept";if(typeof e!="string"||!No(e))throw new a("--proxy expects 'intercept' or an http:// url, e.g., http://proxy:8080");return e}}async function Lo({options:e,positionals:[t,o],progress:n,signal:i}){const s=x(e["device-os-version"],"--device-os-version"),r=x(e["session-id"],"--session-id"),d=e.force===!0;if(d&&r===void 0)throw new a("--force needs --session-id");const c=r===void 0?So():bo(r),l={device:s===void 0?{id:t}:{id:t,osVersion:s},endpoint:Qe(e),featureFlags:Ye(),open:$o(e.open),proxy:Do(e.proxy),sessionId:c,target:o},u=oe(c);if(u!==void 0){if(!d)throw new et(c);n.status(`Replacing session ${c}`),await Oe(u,i),tt(c)}yo(l),n.step(`Session ${c}`);const y=ot(c,l.proxy);if(e.wait===!1)return{logs:y,sessionId:c};const O=await Ao(c,{onPhase:T=>{_o(T)&&n.status(ko[T]??"Starting the session")},signal:i}).catch(T=>{throw R.wrap(T,c)});return{adbSerial:O.adbSerial,baseUrl:O.baseUrl,controlSocket:O.controlSocket,logs:y,sessionId:c,viewerUrl:O.viewerUrl}}function No(e){return e.startsWith("http://")}function _o(e){return e!=="ended"&&e!=="error"}const Ro=async({options:e,progress:t,record:o,signal:n})=>(e.wait===!1?Ie(o):(t.status(`Stopping session ${o.sessionId}`),await Oe(o,n)),{sessionId:o.sessionId}),Te="appetize",Uo=ae(new URL(`./skills/${Te}/`,import.meta.url)),W=["agents","claude","codex","copilot","cursor"],ke=["project","user"],jo={agents:".agents",claude:".claude",codex:".codex",copilot:".copilot",cursor:".cursor"},zo=v(".agents","skills"),Fo=["claude","agents"];function Co(e){return W.some(t=>t===e)}function Mo(e){return ke.some(t=>t===e)}async function Bo(e){const t=e.agents??await qo(e),o=await Promise.all(t.map(n=>Pe(n,e)));return[...new Set(o.flat())]}async function Pe(e,t){const o=Ae(e,t);if(e==="claude")return[v(o,"skills")];const n=v(t.root,zo);return t.scope==="project"?[n]:await $e(o)?[n,v(o,"skills")]:[n]}function Ae(e,t){if(e==="claude"&&t.scope==="user"){const o=process.env.CLAUDE_CONFIG_DIR?.trim();if(o)return se(o)}return v(t.root,jo[e])}async function qo(e){const o=(await Promise.all(W.map(async n=>await Go(n,e)?n:void 0))).filter(n=>n!==void 0);return o.length>0?o:Fo}async function Go(e,t){const o=[Ae(e,t),...await Pe(e,t)];return(await Promise.all(o.map(i=>$e(i)))).includes(!0)}async function $e(e){try{return(await ht(e)).isDirectory()}catch{return!1}}const Ko=["agent","scope"];async function Zo({options:e,signal:t}){const o=Vo(e.scope),n=Xo(e.agent),i=o==="user"?vt():process.cwd(),s=await Bo({agents:n,root:i,scope:o}),r=[];for(const d of s){t.throwIfAborted();const c=v(d,Te);await wt(c,{force:!0,recursive:!0}),await gt(Uo,c,{recursive:!0}),r.push(o==="user"?c:mt(i,c))}return{installed:r}}function Wo(e){const t=k(e,"--agent");if(!Co(t))throw new a(`--agent expects one of ${W.join(", ")}`);return t}function Xo(e){return e===void 0?void 0:(Array.isArray(e)?e:[e]).map(o=>Wo(o))}function Vo(e){if(e===void 0)return"project";const t=k(e,"--scope");if(!Mo(t))throw new a(`--scope expects one of ${ke.join(", ")}`);return t}const w="from",g="to",Ho=[...K({prefix:w}),...K({prefix:g})],Jo=async({device:e,options:t})=>{await e.swipe(tn(t),nn(t))};function Yo(e){return j.some(t=>t===e)}function Qo(e){if(e===void 0)return;const t=k(e,"--direction");if(!Yo(t))throw new a(`--direction expects one of ${j.join(", ")}`);return t}function en(e,t){const o=nt(e.distance,"--distance");if(A(e,{prefix:g})!==void 0)throw new a(`--direction may not be combined with --${g}-*`);return{direction:t,distance:o,from:A(e,{prefix:w})}}function tn(e){const t=Qo(e.direction);return t===void 0?on(e):en(e,t)}function on(e){if(e.distance!==void 0)throw new a("--distance is only valid with --direction");return{from:De(A(e,{prefix:w}),w),to:De(A(e,{prefix:g}),g)}}function nn(e){const t=f(e.duration,"--duration"),o=f(e.timeout,"--timeout");return t===void 0&&o===void 0?void 0:{duration:t,timeout:o}}function De(e,t){if(e===void 0)throw new a(`A swipe needs --direction, or both endpoints: pass one of ${I({prefix:t})}`);return e}const sn=K(),rn=async({device:e,options:t})=>{const o=we(t);await e.tap(o,he(t))},an=async({device:e,options:t,positionals:[o]})=>{await e.type(o,cn(t))};function cn(e){const t=f(e.delay,"--delay");return t===void 0?void 0:{delay:t}}const X=St("appetize:cli"),pn={fail:()=>{},status:()=>{},step:()=>{},succeed:()=>{}};function dn(e,t,o){return e==="interactive"?ln(t,o):pn}function ln(e,t){const o=bt({handleSignals:!1,stream:e});let n=0;const i=()=>{o.stop()};t.addEventListener("abort",i,{once:!0});const s=()=>(process.off("exit",i),o.isSpinning);return{fail:()=>{s()&&o.stop()},status:r=>{if(!t.aborted){if(o.isSpinning){o.text=r;return}n=Date.now(),process.once("exit",i),o.start(r)}},step:r=>{e.write(`\u25B8 ${r}
4
+ `)},succeed:()=>{if(!s())return;const r=Math.round((Date.now()-n)/1e3);o.success(`${o.text} (${String(r)}s)`)}}}const un=new Set(["adb","api","apk","id","os","url"]),fn={bottom:"","bottom-left":"","bottom-mid":"","bottom-right":"",left:"","left-mid":"",mid:"","mid-mid":"",middle:" ",right:"","right-mid":"",top:"","top-left":"","top-mid":"","top-right":""},Le=2,mn=10;function hn(e){return e.split(/(?=[A-Z])/).map((t,o)=>{const n=t.toLowerCase();return un.has(n)?n.toUpperCase():o===0?n.charAt(0).toUpperCase()+n.slice(1):n}).join(" ")}function wn(e,t,o){return H(e)?ze(e,t,o):D(e,{fields:t,key:""},o)}function gn(e,t){const o=[];for(let n=0;n<e.length;n+=t)o.push(e.slice(n,n+t));return o.length===0?[e]:o}function Ne(e){return new Et({chars:fn,head:e,style:{border:[],head:[],"padding-left":0,"padding-right":Le}})}function _e(e,t){return e.find(o=>o.key===t)}function Re(e,t){return t?.header??hn(e)}function V(e){return e!=null}function H(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Ue(e){return["boolean","number","string"].includes(typeof e)}function je(e,t){const o=new Set(t),n=e.map(s=>s.key).filter(s=>o.has(s)),i=new Set(e.filter(s=>s.hidden).map(s=>s.key));return[...new Set([...n,...t])].filter(s=>!i.has(s))}function ze(e,t,o){const n=new Map(Object.entries(e)),i=je(t,[...n.keys()]).filter(u=>V(n.get(u))),s=i.map(u=>_e(t,u)),r=i.map((u,y)=>Re(u,s[y])),d=Math.max(0,...r.map(u=>u.length))+Le,c=o===void 0?void 0:o-d-1,l=Ne();return l.push(...i.map((u,y)=>[r[y],D(n.get(u),s[y],c)])),Fe(l.toString())}function yn(e,t){const o=e.map(r=>new Map(Object.entries(r))),n=je(t,o.flatMap(r=>[...r.keys()])),i=n.map(r=>_e(t,r)),s=Ne(n.map((r,d)=>Re(r,i[d])));for(const r of o)s.push(n.map((d,c)=>{const l=r.get(d);return V(l)?D(l,i[c]):""}));return Fe(s.toString())}function D(e,t,o){if(t?.format)return L(t.format(e),o);if(Ue(e))return L(ne(e),o);if(Array.isArray(e)){const n=e.filter(V);return n.every(Ue)?L(ne(n),o):n.every(H)?yn(n,t?.fields??[]):n.map(i=>D(i,t,o)).join(`
5
+ `)}return H(e)?ze(e,t?.fields??[],o):L(String(e),o)}function Fe(e){return e.split(`
6
6
  `).map(t=>t.trimEnd()).join(`
7
- `)}function L(e,t){return t===void 0||t<po?e:e.split(`
8
- `).flatMap(n=>ho(n,t)).join(`
9
- `)}function ho(e,t){const n=[];let o="";for(const i of e.split(" ").flatMap(s=>fo(s,t)))o===""?o=i:o.length+1+i.length<=t?o=`${o} ${i}`:(n.push(o),o=i);return n.push(o),n}function wo(e,t){if(e.controlSocket===void 0)throw new Error("Session is not ready");return Et(e.controlSocket,{baseUrl:e.baseUrl,signal:t})}async function go(e,t){if(e.controlSocket===void 0)throw new Error("Session is not ready");const n=await Y(e.controlSocket,{signal:t}),{client:o}=ot(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 yo(e){return async({options:t,positionals:n,progress:o,signal:i})=>{const s=t["session-id"],r=it(typeof s=="string"?s:void 0);try{return await e({options:t,positionals:n,progress:o,record:r,signal:AbortSignal.any([i,te(r.pid)])})}catch(d){throw R.wrap(d,r.sessionId)}}}function vo(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 So(e){return async({options:t,positionals:n,progress:o,record:i,signal:s})=>{const r=await go(i,s);try{return await e({control:r,options:t,positionals:n,progress:o,signal:s})}finally{r.close()}}}const xo=["session-id",...Ot,...At,...jt,...Vt,...Mn,...xn,...Zn,...eo],bo=["json","quiet"];function Eo(e){const t=Be("appetize").version(e).option("--json","Print the result as JSON").option("--quiet","Hide progress");return b(t,"session start <device-id> <target>",n=>n.describe(["Start a device session and wait until it is ready","","Environment variables:","APPETIZE_API_TOKEN: Authorizes private APIs and session targets","APPETIZE_ENDPOINT: Appetize URL used when --endpoint is omitted"]).option("--device-os-version","Device OS version (e.g., 17 for iOS, 14 for Android)").option("--endpoint","Appetize URL (e.g., https://appetize.io); overrides APPETIZE_ENDPOINT").option("--force","Replace a session with the same id",!1).option("--no-wait","Return without waiting for the device session to be ready").option("--open","URL opened once the session is 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").example("session start iphone15pro app_a1b2c3").example("session start pixel7 app_a1b2c3 --device-os-version 14").example("session start iphone15pro app_a1b2c3 --open myapp://orders/42").example("session start iphone15pro app_a1b2c3 --session-id demo --force"),An,{fields:On}),J(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"),Dn),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"),$t,{fields:kt}),b(t,"build upload <file>",n=>n.describe([`Upload a build (${F.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(ue)})`).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"'),Lt,{fields:Dt}),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"),Ft,{fields:zt}),g(t,"press <button>",n=>n.describe(`Press a device button: ${pe.join(", ")}; Android only: ${ce.join(", ")}`).example("press home").example("press volumeUp"),on),g(t,"rotate <orientation>",n=>n.describe("Rotate the device to an orientation: portrait, landscapeLeft, landscapeRight or upsideDown").example("rotate portrait").example("rotate landscapeLeft"),pn),g(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"),en),g(t,"keychain clear",n=>n.describe("Clear the entire device keychain (iOS only)").example("keychain clear"),Qt),g(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"),ln),g(t,"tap",n=>G(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"),to),g(t,"swipe",n=>G(G(n.describe(["Swipe in a direction, or along a path between two points","",`Pick a --direction with an optional --${h} starting point,`,`or both a --${h}-* and a --${w}-* point to form a path`,"",`Pick one per point: ${O({prefix:h})}`,` ${O({prefix:w})}`]).option("--direction",`Direction to travel: ${j.join(", ")}`).option("--distance","Travel as a fraction of the screen (0-1)"),{prefix:h}),{prefix:w}).option("--duration","Milliseconds the gesture travels for").option("--timeout",`Milliseconds to wait for any --${h}/--${w} 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"),Wn),g(t,"inspect [output]",n=>fe(n.describe("Capture the view hierarchy of the screen, or of an element matched by a selector")).option("--timeout","Milliseconds to wait for the element").option("--pretty","Pretty-print the JSON",!1).example("inspect").example("inspect --select-text 'Log in'").example("inspect hierarchy.json --pretty"),Ht),g(t,"type <text>",n=>n.describe(`Type text; {...} presses a named key: ${at.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),Ce(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"),rn),Ce(t,"recording stop",n=>n.describe("Stop recording the device video and close the file").example("recording stop"),an),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"),Bn),t}function b(e,t,n,o,{fields:i}={}){const s=t.split(" ").filter(r=>!/^[<[]/.test(r)).join(" ");return n(e.command(t)).action(ko({action:o,fields:i,name:s}))}function J(e,t,n,o){return b(e,t,i=>n(i).option("--session-id","Target session id; defaults to the sole active session"),yo(o))}function g(e,t,n,o){return J(e,t,n,vo(o))}function Ce(e,t,n,o){return J(e,t,n,So(o))}function Me(e){return`${String(Date.now()-e)}ms`}function Oo(e,t,n){if(e==="json")return JSON.stringify(t===void 0?{}:t,null,2);const o=t===void 0?"":uo(t,n,process.stdout.columns);return o===""?void 0:o}async function Io({action:e,fields:t=[],name:n},o){const i=Date.now();X(`invoked: ${process.argv.slice(2).join(" ")}`);const s=st(o),{format:r,progress:d}=qt(s.options,process.stdout,process.stderr),a=so(d,process.stderr,s.signal);try{const l=Oo(r,await e({...s,progress:a}),t);a.succeed(),l!==void 0&&process.stdout.write(`${l}
10
- `),X(`ok in ${Me(i)}`)}catch(l){a.fail(),process.stderr.write(`${rt(r,l,{command:n})}
11
- `),X(`failed after ${Me(i)}:`,l),process.exitCode=1}}function ko(e){return(...t)=>{Io(e,t)}}Eo("0.20.0").parse(process.argv,{boolean:bo,string:xo});
7
+ `)}function L(e,t){return t===void 0||t<mn?e:e.split(`
8
+ `).flatMap(o=>xn(o,t)).join(`
9
+ `)}function xn(e,t){const o=[];let n="";for(const i of e.split(" ").flatMap(s=>gn(s,t)))n===""?n=i:n.length+1+i.length<=t?n=`${n} ${i}`:(o.push(n),n=i);return o.push(n),o}function vn(e,t){if(e.controlSocket===void 0)throw new Error("Session is not ready");return It(e.controlSocket,{baseUrl:e.baseUrl,signal:t})}async function Sn(e,t){if(e.controlSocket===void 0)throw new Error("Session is not ready");const o=await Y(e.controlSocket,{signal:t}),{client:n}=it(o,{});return{close:()=>{o.close()},recordStart:async i=>await n.request("appetizeio.cli.record.start",i),recordStop:async()=>await n.request("appetizeio.cli.record.stop")}}function bn(e){return async({options:t,positionals:o,progress:n,signal:i})=>{const s=t["session-id"],r=st(typeof s=="string"?s:void 0);try{return await e({options:t,positionals:o,progress:n,record:r,signal:AbortSignal.any([i,te(r.pid)])})}catch(d){throw R.wrap(d,r.sessionId)}}}function En(e){return async({options:t,positionals:o,progress:n,record:i,signal:s})=>{const r=await vn(i,s);try{return await e({device:r,options:t,positionals:o,progress:n,signal:s})}finally{r.close()}}}function In(e){return async({options:t,positionals:o,progress:n,record:i,signal:s})=>{const r=await Sn(i,s);try{return await e({control:r,options:t,positionals:o,progress:n,signal:s})}finally{r.close()}}}const On=["session-id",...Ot,...At,...zt,...Qt,...Ko,...Oo,...Ho,...sn],Tn=["json","quiet"];function kn(e){const t=Be("appetize").version(e).option("--json","Print the result as JSON").option("--quiet","Hide progress");return b(t,"session start <device-id> <target>",o=>o.describe(["Start a device session and wait until it is ready","","Environment variables:","APPETIZE_API_TOKEN: Authorizes private APIs and session targets","APPETIZE_ENDPOINT: Appetize URL used when --endpoint is omitted"]).option("--device-os-version","Device OS version (e.g., 17 for iOS, 14 for Android)").option("--endpoint","Appetize URL (e.g., https://appetize.io); overrides APPETIZE_ENDPOINT").option("--force","Replace a session with the same id",!1).option("--no-wait","Return without waiting for the device session to be ready").option("--open","URL opened once the session is 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").example("session start iphone15pro app_a1b2c3").example("session start pixel7 app_a1b2c3 --device-os-version 14").example("session start iphone15pro app_a1b2c3 --open myapp://orders/42").example("session start iphone15pro app_a1b2c3 --session-id demo --force"),Lo,{fields:Po}),J(t,"session stop",o=>o.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"),Ro),b(t,"build list",o=>o.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"),Pt,{fields:kt}),b(t,"build upload <file>",o=>o.describe([`Upload a build (${F.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(ue)})`).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"'),Nt,{fields:Lt}),b(t,"device list",o=>o.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"),Ct,{fields:Ft}),m(t,"press <button>",o=>o.describe(`Press a device button: ${pe.join(", ")}; Android only: ${ce.join(", ")}`).example("press home").example("press volumeUp"),ao),m(t,"rotate <orientation>",o=>o.describe("Rotate the device to an orientation: portrait, landscapeLeft, landscapeRight or upsideDown").example("rotate portrait").example("rotate landscapeLeft"),fo),m(t,"open <url>",o=>o.describe("Open a URL or deep link on the device").example("open myapp://orders/42").example("open https://example.com"),io),m(t,"keychain clear",o=>o.describe("Clear the entire device keychain (iOS only)").example("keychain clear"),no),m(t,"screenshot [output]",o=>o.describe("Take a screenshot of the current device screen").example("screenshot").example("screenshot home-screen").example("screenshot ./shots/checkout.png"),ho),m(t,"tap",o=>G(o.describe(["Tap an element matched by a selector, or a screen position","",`Pick one of: ${I()}`])).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"),rn),m(t,"swipe",o=>G(G(o.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 --${g}-* point to form a path`,"",`Pick one per point: ${I({prefix:w})}`,` ${I({prefix:g})}`]).option("--direction",`Direction to travel: ${j.join(", ")}`).option("--distance","Travel as a fraction of the screen (0-1)"),{prefix:w}),{prefix:g}).option("--duration","Milliseconds the gesture travels for").option("--timeout",`Milliseconds to wait for any --${w}/--${g} 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"),Jo),m(t,"gesture <syntax>",o=>o.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"),qt),m(t,"inspect [output]",o=>fe(o.describe("Capture the view hierarchy of the screen, or of an element matched by a selector")).option("--timeout","Milliseconds to wait for the element").option("--pretty","Pretty-print the JSON",!1).example("inspect").example("inspect --select-text 'Log in'").example("inspect hierarchy.json --pretty"),eo),m(t,"type <text>",o=>o.describe(`Type text; {...} presses a named key: ${ct.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"),an),Ce(t,"recording start <output>",o=>o.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"),po),Ce(t,"recording stop",o=>o.describe("Stop recording the device video and close the file").example("recording stop"),lo),b(t,"skill install",o=>o.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"),Zo),t}function b(e,t,o,n,{fields:i}={}){const s=t.split(" ").filter(r=>!/^[<[]/.test(r)).join(" ");return o(e.command(t)).action($n({action:n,fields:i,name:s}))}function J(e,t,o,n){return b(e,t,i=>o(i).option("--session-id","Target session id; defaults to the sole active session"),bn(n))}function m(e,t,o,n){return J(e,t,o,En(n))}function Ce(e,t,o,n){return J(e,t,o,In(n))}function Me(e){return`${String(Date.now()-e)}ms`}function Pn(e,t,o){if(e==="json")return JSON.stringify(t===void 0?{}:t,null,2);const n=t===void 0?"":wn(t,o,process.stdout.columns);return n===""?void 0:n}async function An({action:e,fields:t=[],name:o},n){const i=Date.now();X(`invoked: ${process.argv.slice(2).join(" ")}`);const s=rt(n),{format:r,progress:d}=Wt(s.options,process.stdout,process.stderr),c=dn(d,process.stderr,s.signal);try{const l=Pn(r,await e({...s,progress:c}),t);c.succeed(),l!==void 0&&process.stdout.write(`${l}
10
+ `),X(`ok in ${Me(i)}`)}catch(l){c.fail(),process.stderr.write(`${at(r,l,{command:o})}
11
+ `),X(`failed after ${Me(i)}:`,l),process.exitCode=1}}function $n(e){return(...t)=>{An(e,t)}}kn("0.21.0").parse(process.argv,{boolean:Tn,string:On});
@@ -0,0 +1,3 @@
1
+ import{Transform as yr}from"stream";import{createRequire as wr}from"module";import{connect as br}from"node:net";import je from"debug";import{JSONRPCServerAndClient as gr,JSONRPCServer as mr,JSONRPCClient as Er,JSONRPC as Sr}from"json-rpc-2.0";import{writeFileSync as vr,renameSync as Ar,mkdirSync as At,readFileSync as xr,rmSync as kr,readdirSync as Ir}from"node:fs";import{sep as Or,join as re}from"node:path";import{homedir as xt}from"node:os";let $e;try{$e=new TextDecoder}catch{}let w,V,f=0;const Ve=[],Tr=105,Mr=57342,Rr=57343,kt=57337,It=6,de={};let ge=11281e4,Y=1681e4,se=Ve,me=0,k={},N,Ee,Se=0,ne=0,D,J,B=[],Ke=[],K,$,ve,Ot={useRecords:!1,mapsAsObjects:!0},Ae=!1,Tt=2;try{new Function("")}catch{Tt=1/0}class ye{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[W(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 Nt(()=>(Ge(),this?this.decode(e,r):ye.prototype.decode.call(Ot,e,r)));V=r>-1?r:e.length,f=0,me=0,ne=0,Ee=null,se=Ve,D=null,w=e;try{$=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 ye){if(k=this,K=this.sharedValues&&(this.pack?new Array(this.maxPrivatePackedValues||16).concat(this.sharedValues):this.sharedValues),this.structures)return N=this.structures,Me();(!N||N.length>0)&&(N=[])}else k=Ot,(!N||N.length>0)&&(N=[]),K=null;return Me()}decodeMultiple(e,r){let s,n=0;try{let i=e.length;Ae=!0;let l=this?this.decode(e,i):Ze.decode(e,i);if(r){if(r(l)===!1)return;for(;f<i;)if(n=f,r(Me())===!1)return}else{for(s=[l];f<i;)n=f,s.push(Me());return s}}catch(i){throw i.lastPosition=n,i.values=s,i}finally{Ae=!1,Ge()}}}function Me(){try{let t=I();if(D){if(f>=D.postBundlePosition){let e=new Error("Unexpected bundle position");throw e.incomplete=!0,e}f=D.postBundlePosition,D=null}if(f==V)N=null,w=null,J&&(J=null);else if(f>V){let e=new Error("Unexpected end of CBOR data");throw e.incomplete=!0,e}else if(!Ae)throw new Error("Data read, but end of buffer not reached");return t}catch(t){throw Ge(),(t instanceof RangeError||t.message.startsWith("Unexpected end of buffer"))&&(t.incomplete=!0),t}}function ie(){let t=new Error("Unexpected end of CBOR data");return t.incomplete=!0,t}function I(){if(!(f<V))throw ie();let t=w[f++],e=t>>5;if(t=t&31,t>23)switch(t){case 24:if(f>=V)throw ie();t=w[f++];break;case 25:if(e==7)return Lr();t=$.getUint16(f),f+=2;break;case 26:if(e==7){let r=$.getFloat32(f);if(k.useFloat32>2){let s=He[(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=$.getUint32(f),f+=4,e===1)return-1-t;break;case 27:if(e==7){let r=$.getFloat64(f);return f+=8,r}if(e>1){if($.getUint32(f)>0)throw new Error("JavaScript does not support arrays, maps, or strings with length over 4294967295");t=$.getUint32(f+4)}else k.int64AsNumber?(t=$.getUint32(f)*4294967296,t+=$.getUint32(f+4)):t=$.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())!=de;){if(n>=ge)throw new Error(`Array length exceeds ${ge}`);r[n++]=s}return e==4?r:e==3?r.join(""):Buffer.concat(r);case 5:let i;if(k.mapsAsObjects){let l={},y=0;if(k.keyMap)for(;(i=I())!=de;){if(y++>=Y)throw new Error(`Property count exceeds ${Y}`);l[W(k.decodeKey(i))]=I()}else for(;(i=I())!=de;){if(y++>=Y)throw new Error(`Property count exceeds ${Y}`);l[W(i)]=I()}return l}else{ve&&(k.mapsAsObjects=!0,ve=!1);let l=new Map;if(k.keyMap){let y=0;for(;(i=I())!=de;){if(y++>=Y)throw new Error(`Map size exceeds ${Y}`);l.set(k.decodeKey(i),I())}}else{let y=0;for(;(i=I())!=de;){if(y++>=Y)throw new Error(`Map size exceeds ${Y}`);l.set(i,I())}}return l}case 7:return de;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 Cr(t);case 3:if(ne>=f)return Ee.slice(f-Se,(f+=t)-Se);if(ne==0&&V<140&&t<32){let n=t<16?Ut(t):Pr(t);if(n!=null)return n}return Rt(t);case 4:if(t>=ge)throw new Error(`Array length exceeds ${ge}`);if(t>V-f)throw ie();let r=new Array(t);for(let n=0;n<t;n++)r[n]=I();return r;case 5:if(t>=Y)throw new Error(`Map size exceeds ${ge}`);if(t>(V-f)/2)throw ie();if(k.mapsAsObjects){let n={};if(k.keyMap)for(let i=0;i<t;i++)n[W(k.decodeKey(I()))]=I();else for(let i=0;i<t;i++)n[W(I())]=I();return n}else{ve&&(k.mapsAsObjects=!0,ve=!1);let n=new Map;if(k.keyMap)for(let i=0;i<t;i++)n.set(k.decodeKey(I()),I());else for(let i=0;i<t;i++)n.set(I(),I());return n}case 6:if(t>=kt){let n=N[t&8191];if(n)return n.read||(n.read=qe(n)),n.read();if(t<65536){if(t==Rr){let i=pe(),l=I(),y=I();Je(l,y);let p={};if(k.keyMap)for(let v=2;v<i;v++){let m=k.decodeKey(y[v-2]);p[W(m)]=I()}else for(let v=2;v<i;v++){let m=y[v-2];p[W(m)]=I()}return p}else if(t==Mr){let i=pe(),l=I();for(let y=2;y<i;y++)Je(l++,I());return I()}else if(t==kt)return zr();if(k.getShared&&(We(),n=N[t&8191],n))return n.read||(n.read=qe(n)),n.read()}}let s=B[t];if(s)return s.handlesRead?s(I):s(I());{let n=I();for(let i=0;i<Ke.length;i++){let l=Ke[i](t,n);if(l!==void 0)return l}return new oe(n,t)}case 7:switch(t){case 20:return!1;case 21:return!0;case 22:return null;case 23:return;default:let n=(K||ae())[t];if(n!==void 0)return n;throw new Error("Unknown token "+t)}default:throw isNaN(t)?ie():new Error("Unknown CBOR token "+t)}}const Mt=/^[a-zA-Z_$][a-zA-Z\d_$]*$/;function qe(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=$.getUint16(f),f+=2;break;case 26:r=$.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++>=Tt){let i=this.length==r?this:this.slice(0,r);return s=k.keyMap?new Function("r","return {"+i.map(l=>k.decodeKey(l)).map(l=>Mt.test(l)?W(l)+":r()":"["+JSON.stringify(l)+"]:r()").join(",")+"}"):new Function("r","return {"+i.map(l=>Mt.test(l)?W(l)+":r()":"["+JSON.stringify(l)+"]:r()").join(",")+"}"),this.compiledReader&&(s.next=this.compiledReader),s.propertyCount=r,this.compiledReader=s,s(I)}let n={};if(k.keyMap)for(let i=0;i<r;i++)n[W(k.decodeKey(this[i]))]=I();else for(let i=0;i<r;i++)n[W(this[i])]=I();return n}return t.slowReads=0,e}function W(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 Rt=Re;function Ur(t){Rt=e();function e(r){return function(n){let i=se[me++];if(i==null){if(D)return Re(n);let y=t(f,V,n,w);if(typeof y=="string")i=y,se=Ve;else if(se=y,me=1,ne=1,i=se[0],i===void 0)throw new Error("Unexpected end of buffer")}let l=i.length;return l<=n?(f+=n,i):(Ee=i,Se=f,ne=f+l,f+=n,i.slice(0,n))}}}function Re(t){let e;if(t<16&&(e=Ut(t)))return e;if(t>64&&$e)return $e.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+=z.apply(String,s),s.length=0)}return s.length>0&&(e+=z.apply(String,s)),e}let z=String.fromCharCode;function Pr(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 z.apply(String,r)}function Ut(t){if(t<4)if(t<2){if(t===0)return"";{let e=w[f++];if((e&128)>1){f-=1;return}return z(e)}}else{let e=w[f++],r=w[f++];if((e&128)>0||(r&128)>0){f-=2;return}if(t<3)return z(e,r);let s=w[f++];if((s&128)>0){f-=3;return}return z(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 z(e,r,s,n);{let i=w[f++];if((i&128)>0){f-=5;return}return z(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 z(e,r,s,n,i,l);let y=w[f++];if((y&128)>0){f-=7;return}return z(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 z(e,r,s,n,i,l,y,p);{let v=w[f++];if((v&128)>0){f-=9;return}return z(e,r,s,n,i,l,y,p,v)}}else if(t<12){let v=w[f++],m=w[f++];if((v&128)>0||(m&128)>0){f-=10;return}if(t<11)return z(e,r,s,n,i,l,y,p,v,m);let T=w[f++];if((T&128)>0){f-=11;return}return z(e,r,s,n,i,l,y,p,v,m,T)}else{let v=w[f++],m=w[f++],T=w[f++],M=w[f++];if((v&128)>0||(m&128)>0||(T&128)>0||(M&128)>0){f-=12;return}if(t<14){if(t===12)return z(e,r,s,n,i,l,y,p,v,m,T,M);{let L=w[f++];if((L&128)>0){f-=13;return}return z(e,r,s,n,i,l,y,p,v,m,T,M,L)}}else{let L=w[f++],C=w[f++];if((L&128)>0||(C&128)>0){f-=14;return}if(t<15)return z(e,r,s,n,i,l,y,p,v,m,T,M,L,C);let P=w[f++];if((P&128)>0){f-=15;return}return z(e,r,s,n,i,l,y,p,v,m,T,M,L,C,P)}}}}}function Cr(t){return k.copyBuffers?Uint8Array.prototype.slice.call(w,f,f+=t):w.subarray(f,f+=t)}let Pt=new Float32Array(1),Ue=new Uint8Array(Pt.buffer,0,4);function Lr(){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 Ue[3]=t&128|(r>>1)+56,Ue[2]=(t&7)<<5|e>>3,Ue[1]=e<<5,Ue[0]=0,Pt[0]}new Array(4096);class oe{constructor(e,r){this.value=e,this.tag=r}}B[0]=t=>new Date(t),B[1]=t=>new Date(Math.round(t*1e3)),B[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},B[3]=t=>BigInt(-1)-B[2](t),B[4]=t=>+(t[1]+"e"+t[0]),B[5]=t=>t[1]*Math.exp(t[0]*Math.log(2));const Je=(t,e)=>{t=t-57344;let r=N[t];r&&r.isShared&&((N.restoreStructures||(N.restoreStructures=[]))[t]=r),N[t]=e,e.read=qe(e)};B[Tr]=t=>{let e=t.length,r=t[1];Je(t[0],r);let s={};for(let n=2;n<e;n++){let i=r[n-2];s[W(i)]=t[n]}return s},B[14]=t=>D?D[0].slice(D.position0,D.position0+=t):new oe(t,14),B[15]=t=>D?D[1].slice(D.position1,D.position1+=t):new oe(t,15);let Nr={Error,RegExp};B[27]=t=>(Nr[t[0]]||Error)(t[1],t[2]);const Ct=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 K=K?e.concat(K.slice(e.length)):e,K.prefixes=t(),K.suffixes=t(),t()};Ct.handlesRead=!0,B[51]=Ct,B[It]=t=>{if(!K)if(k.getShared)We();else return new oe(t,It);if(typeof t=="number")return K[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},B[28]=t=>{J||(J=new Map,J.id=0);let e=J.id++,r=f,s=w[f],n;s>>5==4?n=[]:n={};let i={target:n};J.set(e,i);let l=t();return i.used?(Object.getPrototypeOf(n)!==Object.getPrototypeOf(l)&&(f=r,n=l,J.set(e,{target:n}),l=t()),Object.assign(n,l)):(i.target=l,l)},B[28].handlesRead=!0,B[29]=t=>{let e=J.get(t);return e.used=!0,e.target},B[258]=t=>new Set(t),(B[259]=t=>(k.mapsAsObjects&&(k.mapsAsObjects=!1,ve=!0),t())).handlesRead=!0;function he(t,e){return typeof t=="string"?t+e:t instanceof Array?t.concat(e):Object.assign({},t,e)}function ae(){if(!K)if(k.getShared)We();else throw new Error("No packed values available");return K}const _r=1399353956;Ke.push((t,e)=>{if(t>=225&&t<=255)return he(ae().prefixes[t-224],e);if(t>=28704&&t<=32767)return he(ae().prefixes[t-28672],e);if(t>=1879052288&&t<=2147483647)return he(ae().prefixes[t-1879048192],e);if(t>=216&&t<=223)return he(e,ae().suffixes[t-216]);if(t>=27647&&t<=28671)return he(e,ae().suffixes[t-27639]);if(t>=1811940352&&t<=1879048191)return he(e,ae().suffixes[t-1811939328]);if(t==_r)return{packedValues:K,structures:N.slice(0),version:e};if(t==55799)return e});const Dr=new Uint8Array(new Uint16Array([1]).buffer)[0]==1,Lt=[Uint8Array,Uint8ClampedArray,Uint16Array,Uint32Array,typeof BigUint64Array>"u"?{name:"BigUint64Array"}:BigUint64Array,Int8Array,Int16Array,Int32Array,typeof BigInt64Array>"u"?{name:"BigInt64Array"}:BigInt64Array,Float32Array,Float64Array],Br=[64,68,69,70,71,72,77,78,79,85,86];for(let t=0;t<Lt.length;t++)Fr(Lt[t],Br[t]);function Fr(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;B[n?e:e-4]=s==1||n==Dr?l=>{if(!t)throw new Error("Could not find typed array for code "+e);return!k.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,v=new t(p),m=y[r];for(let T=0;T<p;T++)v[T]=m.call(y,T<<i,n);return v}}}function zr(){let t=pe(),e=f+I();for(let s=2;s<t;s++){let n=pe();f+=n}let r=f;return f=e,D=[Re(pe()),Re(pe())],D.position0=0,D.position1=0,D.postBundlePosition=f,f=r,I()}function pe(){if(!(f<V))throw ie();let t=w[f++]&31;if(t>23)switch(t){case 24:if(f>=V)throw ie();t=w[f++];break;case 25:t=$.getUint16(f),f+=2;break;case 26:t=$.getUint32(f),f+=4;break}return t}function We(){if(k.getShared){let t=Nt(()=>(w=null,k.getShared()))||{},e=t.structures||[];k.sharedVersion=t.version,K=k.sharedValues=t.packedValues,N===!0?k.structures=N=e:N.splice.apply(N,[0,e.length].concat(e))}}function Nt(t){let e=V,r=f,s=me,n=Se,i=ne,l=Ee,y=se,p=J,v=D,m=new Uint8Array(w.slice(0,V)),T=N,M=k,L=Ae,C=t();return V=e,f=r,me=s,Se=n,ne=i,Ee=l,se=y,J=p,D=v,w=m,Ae=L,N=T,k=M,$=new DataView(w.buffer,w.byteOffset,w.byteLength),C}function Ge(){w=null,J=null,N=null}const He=new Array(147);for(let t=0;t<256;t++)He[t]=+("1e"+Math.floor(45.15-t*.30103));let Ze=new ye({useRecords:!1});const jr=Ze.decode;Ze.decodeMultiple;let Pe;try{Pe=new TextEncoder}catch{}let Xe,_t;const Ce=typeof globalThis=="object"&&globalThis.Buffer,xe=typeof Ce<"u",Ye=xe?Ce.allocUnsafeSlow:Uint8Array,Dt=xe?Ce:Uint8Array,Bt=256,Ft=xe?4294967296:2144337920;let Qe,c,U,o=0,ee,F=null;const $r=61440,Vr=/[\u0080-\uFFFF]/,q=Symbol("record-id");class zt extends ye{constructor(e){super(e),this.offset=0;let r,s,n,i,l;e=e||{};let y=Dt.prototype.utf8Write?function(a,b){return c.utf8Write(a,b,c.byteLength-b)}:Pe&&Pe.encodeInto?function(a,b){return Pe.encodeInto(a,c.subarray(b)).written}:!1,p=this,v=e.structures||e.saveStructures,m=e.maxSharedStructures;if(m==null&&(m=v?128:0),m>8190)throw new Error("Maximum maxSharedStructure is 8190");let T=e.sequential;T&&(m=0),this.structures||(this.structures=[]),this.saveStructures&&(this.saveShared=this.saveStructures);let M,L,C=e.sharedValues,P;if(C){P=Object.create(null);for(let a=0,b=C.length;a<b;a++)P[C[a]]=a}let G=[],we=0,H=0;this.mapEncode=function(a,b){return this._keyMap&&!this._mapped&&a.constructor.name==="Array"&&(a=a.map(d=>this.encodeKeys(d))),this.encode(a,b)},this.encode=function(a,b){if(c||(c=new Ye(8192),U=new DataView(c.buffer,0,8192),o=0),ee=c.length-10,ee-o<2048?(c=new Ye(c.length),U=new DataView(c.buffer,0,c.length),ee=c.length-10,o=0):b===Kt&&(o=o+7&2147483640),r=o,p.useSelfDescribedHeader&&(U.setUint32(o,3654940416),o+=3),l=p.structuredClone?new Map:null,p.bundleStrings&&typeof a!="string"?(F=[],F.size=1/0):F=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){P={};for(let g=0,E=u.length;g<E;g++)P[u[g]]=g}}let d=s.length;if(d>m&&!T&&(d=m),!s.transitions){s.transitions=Object.create(null);for(let h=0;h<d;h++){let u=s[h];if(!u)continue;let g,E=s.transitions;for(let S=0,A=u.length;S<A;S++){E[q]===void 0&&(E[q]=h);let O=u[S];g=E[O],g||(g=E[O]=Object.create(null)),E=g}E[q]=h|1048576}}T||(s.nextId=d)}if(n&&(n=!1),i=s||[],L=P,e.pack){let d=new Map;if(d.values=[],d.encoder=p,d.maxValues=e.maxPrivatePackedValues||(P?16:1/0),d.objectMap=P||!1,d.samplingPackedValues=M,Le(a,d),d.values.length>0){c[o++]=216,c[o++]=51,Z(4);let h=d.values;x(h),Z(0),Z(0),L=Object.create(P||null);for(let u=0,g=h.length;u<g;u++)L[h[u]]=u}}Qe=b&st;try{if(Qe)return;if(x(a),F&&Vt(r,x),p.offset=o,l&&l.idsToInsert){o+=l.idsToInsert.length*2,o>ee&&fe(o),p.offset=o;let d=Jr(c.subarray(r,o),l.idsToInsert);return l=null,d}return b&Kt?(c.start=r,c.end=o,c):c.subarray(r,o)}finally{if(s){if(H<10&&H++,s.length>m&&(s.length=m),we>1e4)s.transitions=null,H=0,we=0,G.length>0&&(G=[]);else if(G.length>0&&!T){for(let d=0,h=G.length;d<h;d++)G[d][q]=void 0;G=[]}}if(n&&p.saveShared){p.structures.length>m&&(p.structures=p.structures.slice(0,m));let d=c.subarray(r,o);return p.updateSharedData()===!1?p.encode(a):d}b&Gr&&(o=r)}},this.findCommonStringsToPack=()=>(M=new Map,P||(P=Object.create(null)),a=>{let b=a&&a.threshold||4,d=this.pack?a.maxPrivatePackedValues||16:0;C||(C=this.sharedValues=[]);for(let[h,u]of M)u.count>b&&(P[h]=d++,C.push(h),n=!0);for(;this.saveShared&&this.updateSharedData()===!1;);M=null});const x=a=>{o>ee&&(c=fe(o));var b=typeof a,d;if(b==="string"){if(L){let E=L[a];if(E>=0){E<16?c[o++]=E+224:(c[o++]=198,E&1?x(15-E>>1):x(E-16>>1));return}else if(M&&!e.pack){let S=M.get(a);S?S.count++:M.set(a,{count:1})}}let h=a.length;if(F&&h>=4&&h<1024){if((F.size+=h)>$r){let S,A=(F[0]?F[0].length*3+F[1].length:0)+10;o+A>ee&&(c=fe(o+A)),c[o++]=217,c[o++]=223,c[o++]=249,c[o++]=F.position?132:130,c[o++]=26,S=o-r,o+=4,F.position&&Vt(r,x),F=["",""],F.size=0,F.position=S}let E=Vr.test(a);F[E?0:1]+=a,c[o++]=E?206:207,x(h);return}let u;h<32?u=1:h<256?u=2:h<65536?u=3:u=5;let g=h*3;if(o+g>ee&&(c=fe(o+g)),h<64||!y){let E,S,A,O=o+u;for(E=0;E<h;E++)S=a.charCodeAt(E),S<128?c[O++]=S:S<2048?(c[O++]=S>>6|192,c[O++]=S&63|128):(S&64512)===55296&&((A=a.charCodeAt(E+1))&64512)===56320?(S=65536+((S&1023)<<10)+(A&1023),E++,c[O++]=S>>18|240,c[O++]=S>>12&63|128,c[O++]=S>>6&63|128,c[O++]=S&63|128):(c[O++]=S>>12|224,c[O++]=S>>6&63|128,c[O++]=S&63|128);d=O-o-u}else d=y(a,o+u,g);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,U.setUint32(o,d),o+=4),o+=d}else if(b==="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,U.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,U.setUint16(o,~a),o+=2):(c[o++]=58,U.setUint32(o,~a),o+=4);else if(!this.alwaysUseFloat&&a<0&&a>=-4294967296&&Math.floor(a)===a)c[o++]=58,U.setUint32(o,-1-a),o+=4;else{let h;if((h=this.useFloat32)>0&&a<4294967296&&a>=-2147483648){c[o++]=250,U.setFloat32(o,a);let u;if(h<4||(u=a*He[(c[o]&127)<<1|c[o+1]>>7])>>0===u){o+=4;return}else o--}c[o++]=251,U.setFloat64(o,a),o+=8}else if(b==="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 g=l.idsToInsert||(l.idsToInsert=[]);u.references=[],g.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]])])),j(a);else if(h===Array){d=a.length,d<24?c[o++]=128|d:Z(d);for(let u=0;u<d;u++)x(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,U.setUint32(o,d),o+=4),p.keyMap)for(let[u,g]of a)x(p.encodeKey(u)),x(g);else for(let[u,g]of a)x(u),x(g);else{for(let u=0,g=Xe.length;u<g;u++){let E=_t[u];if(a instanceof E){let S=Xe[u],A=S.tag;A==null&&(A=S.getTag&&S.getTag.call(this,a)),A<24?c[o++]=192|A:A<256?(c[o++]=216,c[o++]=A):A<65536?(c[o++]=217,c[o++]=A>>8,c[o++]=A&255):A>-1&&(c[o++]=218,U.setUint32(o,A),o+=4),S.encode.call(this,a,x,fe);return}}if(a[Symbol.iterator]){if(Qe){let u=new Error("Iterable should be serialized as iterator");throw u.iteratorNotHandled=!0,u}c[o++]=159;for(let u of a)x(u);c[o++]=255;return}if(a[Symbol.asyncIterator]||et(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 x(u)}j(a)}}else if(b==="boolean")c[o++]=a?245:244;else if(b==="bigint"){if(a<BigInt(1)<<BigInt(64)&&a>=0)c[o++]=27,U.setBigUint64(o,a);else if(a>-(BigInt(1)<<BigInt(64))&&a<0)c[o++]=59,U.setBigUint64(o,-a-BigInt(1));else if(this.largeBigIntToFloat)c[o++]=251,U.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);tt(new Uint8Array(h.reverse()),fe);return}o+=8}else if(b==="undefined")c[o++]=247;else throw new Error("Unknown type: "+b)},j=this.useRecords===!1?this.variableMapSize?a=>{let b=Object.keys(a),d=Object.values(a),h=b.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,U.setUint32(o,h),o+=4),p.keyMap)for(let u=0;u<h;u++)x(p.encodeKey(b[u])),x(d[u]);else for(let u=0;u<h;u++)x(b[u]),x(d[u])}:a=>{c[o++]=185;let b=o-r;o+=2;let d=0;if(p.keyMap)for(let h in a)(typeof a.hasOwnProperty!="function"||a.hasOwnProperty(h))&&(x(p.encodeKey(h)),x(a[h]),d++);else for(let h in a)(typeof a.hasOwnProperty!="function"||a.hasOwnProperty(h))&&(x(h),x(a[h]),d++);c[b+++r]=d>>8,c[b+r]=d&255}:(a,b)=>{let d,h=i.transitions||(i.transitions=Object.create(null)),u=0,g=0,E,S;if(this.keyMap){S=Object.keys(a).map(O=>this.encodeKey(O)),g=S.length;for(let O=0;O<g;O++){let vt=S[O];d=h[vt],d||(d=h[vt]=Object.create(null),u++),h=d}}else for(let O in a)(typeof a.hasOwnProperty!="function"||a.hasOwnProperty(O))&&(d=h[O],d||(h[q]&1048576&&(E=h[q]&65535),d=h[O]=Object.create(null),u++),h=d,g++);let A=h[q];if(A!==void 0)A&=65535,c[o++]=217,c[o++]=A>>8|224,c[o++]=A&255;else if(S||(S=h.__keys__||(h.__keys__=Object.keys(a))),E===void 0?(A=i.nextId++,A||(A=0,i.nextId=1),A>=Bt&&(i.nextId=(A=m)+1)):A=E,i[A]=S,A<m){c[o++]=217,c[o++]=A>>8|224,c[o++]=A&255,h=i.transitions;for(let O=0;O<g;O++)(h[q]===void 0||h[q]&1048576)&&(h[q]=A),h=h[S[O]];h[q]=A|1048576,n=!0}else{if(h[q]=A,U.setUint32(o,3655335680),o+=3,u&&(we+=H*u),G.length>=Bt-m&&(G.shift()[q]=void 0),G.push(h),Z(g+2),x(57344+A),x(S),b)return;for(let O in a)(typeof a.hasOwnProperty!="function"||a.hasOwnProperty(O))&&x(a[O]);return}if(g<24?c[o++]=128|g:Z(g),!b)for(let O in a)(typeof a.hasOwnProperty!="function"||a.hasOwnProperty(O))&&x(a[O])},fe=a=>{let b;if(a>16777216){if(a-r>Ft)throw new Error("Encoded buffer would be larger than maximum buffer size");b=Math.min(Ft,Math.round(Math.max((a-r)*(a>67108864?1.25:2),4194304)/4096)*4096)}else b=(Math.max(a-r<<2,c.length-1)>>12)+1<<12;let d=new Ye(b);return U=new DataView(d.buffer,0,b),c.copy?c.copy(d,0,r,a):d.set(c.slice(r,a)),o-=r,r=0,ee=d.length-10,c=d};let te=100,mt=1e3;this.encodeAsIterable=function(a,b){return Et(a,b,ue)},this.encodeAsAsyncIterable=function(a,b){return Et(a,b,St)};function*ue(a,b,d){let h=a.constructor;if(h===Object){let u=p.useRecords!==!1;u?j(a,!0):jt(Object.keys(a).length,160);for(let g in a){let E=a[g];u||x(g),E&&typeof E=="object"?b[g]?yield*ue(E,b[g]):yield*ze(E,b,g):x(E)}}else if(h===Array){let u=a.length;Z(u);for(let g=0;g<u;g++){let E=a[g];E&&(typeof E=="object"||o-r>te)?b.element?yield*ue(E,b.element):yield*ze(E,b,"element"):x(E)}}else if(a[Symbol.iterator]&&!a.buffer){c[o++]=159;for(let u of a)u&&(typeof u=="object"||o-r>te)?b.element?yield*ue(u,b.element):yield*ze(u,b,"element"):x(u);c[o++]=255}else et(a)?(jt(a.size,64),yield c.subarray(r,o),yield a,be()):a[Symbol.asyncIterator]?(c[o++]=159,yield c.subarray(r,o),yield a,be(),c[o++]=255):x(a);d&&o>r?yield c.subarray(r,o):o-r>te&&(yield c.subarray(r,o),be())}function*ze(a,b,d){let h=o-r;try{x(a),o-r>te&&(yield c.subarray(r,o),be())}catch(u){if(u.iteratorNotHandled)b[d]={},o=r+h,yield*ue.call(this,a,b[d]);else throw u}}function be(){te=mt,p.encode(null,st)}function Et(a,b,d){return b&&b.chunkThreshold?te=mt=b.chunkThreshold:te=100,a&&typeof a=="object"?(p.encode(null,st),d(a,p.iterateProperties||(p.iterateProperties={}),!0)):[p.encode(a)]}async function*St(a,b){for(let d of ue(a,b,!0)){let h=d.constructor;if(h===Dt||h===Uint8Array)yield d;else if(et(d)){let u=d.stream().getReader(),g;for(;!(g=await u.read()).done;)yield g.value}else if(d[Symbol.asyncIterator])for await(let u of d)be(),u?yield*St(u,b.async||(b.async={})):yield p.encode(u);else yield d}}}useBuffer(e){c=e,U=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 $t(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 jt(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,U.setUint32(o,t),o+=4)}class $t{constructor(e,r,s){this.structures=e,this.packedValues=r,this.version=s}}function Z(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,U.setUint32(o,t),o+=4)}const Kr=typeof Blob>"u"?function(){}:Blob;function et(t){if(t instanceof Kr)return!0;let e=t[Symbol.toStringTag];return e==="Blob"||e==="File"}function Le(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++)Le(t[s],e);else{let s=!e.encoder.useRecords;for(var r in t)t.hasOwnProperty(r)&&(s&&Le(r,e),Le(t[r],e))}break;case"function":console.log(t)}}const qr=new Uint8Array(new Uint16Array([1]).buffer)[0]==1;_t=[Date,Set,Error,RegExp,oe,ArrayBuffer,Uint8Array,Uint8ClampedArray,Uint16Array,Uint32Array,typeof BigUint64Array>"u"?function(){}:BigUint64Array,Int8Array,Int16Array,Int32Array,typeof BigInt64Array>"u"?function(){}:BigInt64Array,Float32Array,Float64Array,$t],Xe=[{tag:1,encode(t,e){let r=t.getTime()/1e3;(this.useTimestamp32||t.getMilliseconds()===0)&&r>=0&&r<4294967296?(c[o++]=26,U.setUint32(o,r),o+=4):(c[o++]=251,U.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){tt(t,r)}},{getTag(t){if(t.constructor===Uint8Array&&(this.tagUint8Array||xe&&this.tagUint8Array!==!1))return 64},encode(t,e,r){tt(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,Z(4);let n=r.values;e(n),Z(0),Z(0),packedObjectMap=Object.create(sharedPackedObjectMap||null);for(let i=0,l=n.length;i<l;i++)packedObjectMap[n[i]]=i}if(s){U.setUint32(o,3655335424),o+=3;let n=s.slice(0);n.unshift(57344),n.push(new oe(t.version,1399353956)),e(n)}else e(new oe(t.version,1399353956))}}];function X(t,e){return!qr&&e>1&&(t-=4),{tag:t,encode:function(s,n){let i=s.byteLength,l=s.byteOffset||0,y=s.buffer||s;n(xe?Ce.from(y,l,i):new Uint8Array(y,l,i))}}}function tt(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,U.setUint32(o,r),o+=4),o+r>=c.length&&e(o+r),c.set(t.buffer?t:new Uint8Array(t),o),o+=r}function Jr(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 Vt(t,e){U.setUint32(F.position+t,o-F.position-t+1);let r=F;F=null,e(r[0]),e(r[1])}let rt=new zt({useRecords:!1});const Wr=rt.encode;rt.encodeAsIterable,rt.encodeAsAsyncIterable;const Kt=512,Gr=1024,st=2048;class Hr extends yr{constructor(e){e||(e={}),e.objectMode=!0,super(e),e.structures=[],this.decoder=e.decoder||new ye(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 Zr=process.env.CBOR_NATIVE_ACCELERATION_DISABLED!==void 0&&process.env.CBOR_NATIVE_ACCELERATION_DISABLED.toLowerCase()==="true";if(!Zr){let t;try{typeof require=="function"?t=require("cbor-extract"):t=wr(import.meta.url)("cbor-extract"),t&&Ur(t.extractStrings)}catch{}}class Xr 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 Yr(t,e){const r="CloseEvent"in globalThis?globalThis.CloseEvent:Xr;return new r(t,e)}class Qr{#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 R=Symbol.for("@appetizeio/rpc:rpcMethods");class es extends Qr{send;constructor(e){super(),this.send=e}dispatchClose(e){return this.dispatchEvent(Yr("close",e))}dispatchMessage(e){return this.dispatchEvent(new CustomEvent("message",{detail:e}))}}function nt(t){return!!t&&typeof t=="object"&&"jsonrpc"in t}function ts(){let t,e;return{promise:new Promise((s,n)=>{e=s,t=n}),reject:t,resolve:e}}class ke{closed=!1;[R];#e;constructor(e,{signal:r}={}){this[R]=new es(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[R].dispatchClose(e)}#t=()=>{this.close({code:1e3,reason:String(this.#e?.reason)})}}const qt={useRecords:!1},rs=new zt(qt);class Jt extends ke{#e=[];#t;constructor(e,{signal:r}={}){super(async l=>{this.#t.write(rs.encode(l))},{signal:r}),this.#t=e;const s=new Hr(qt);s.on("data",l=>{nt(l)&&this[R].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 ss(t,e){const{promise:r,reject:s,resolve:n}=ts(),i=br(t),l=e?.signal,y=()=>{i.off("connect",m),i.off("error",T),l?.removeEventListener("abort",v)},p=M=>{y(),i.destroy(),s(M)},v=()=>{p(new Error("The connection was aborted"))},m=()=>{y();const M=new Jt(i,e);M[R].addEventListener("close",()=>{i.destroy()},{once:!0}),n(M)},T=M=>{p(M)};return l?.aborted?(p(new Error("The connection was aborted")),r):(i.once("connect",m),i.once("error",T),l?.addEventListener("abort",v,{once:!0}),r)}const Wt=je("appetize.io:error:rpc");function it(t,e){const r=new gr(new mr({errorListener:Wt}),ns(t),{errorListener:Wt}),s=t[R].addEventListener("message",({detail:i})=>{r.receiveAndSend(i)}),n=t[R].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 Gt(t,e){const{rpc:r,unsub:s}=it(t,e);return{client:r.client,unsub:s}}function Ne(t,e){const r=t[R].addEventListener("message",({detail:n})=>{if("method"in n)try{e({method:n.method,param:n.params})}catch{}}),s=t[R].addEventListener("close",r,{once:!0});return()=>{r(),s()}}function ns(t){return new Er(t[R].send.bind(t[R]),()=>Math.floor(Math.random()*Number.MAX_SAFE_INTEGER)+1)}function ot(t,e,{leftEffects:r=()=>({}),notifiesLeft:s,notifiesRight:n,rightEffects:i=()=>({})}={}){const l=it(t,{}),y=it(e,{}),p=[()=>{l.unsub(),y.unsub()}],v=()=>{for(const C of p)try{C()}catch{}},m=y.rpc.client,T=l.rpc.client;p.push(t[R].addEventListener("close",()=>{v()},{once:!0}),e[R].addEventListener("close",()=>{v()},{once:!0}));const M=r(m,T);for(const C in M){const P=M[C];P&&l.rpc.addMethod(C,P)}const L=i(T,m);for(const C in L){const P=L[C];P&&y.rpc.addMethod(C,P)}return Ht(l.rpc,y.rpc,{notifies:s}),Ht(y.rpc,l.rpc,{notifies:n}),v}function Ht(t,e,{notifies:r}={}){t.applyServerMiddleware(async(s,n)=>{const i=r?.();if(i){const{id:y,...p}=n;i[R].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:Sr,result:l}})}function Q(t,...e){t.notify(e[0],e[1],e[2])}const is=(...t)=>Gt(...t),at=["ArrowDown","ArrowLeft","ArrowRight","ArrowUp","Backspace","Enter","Tab"];function ct(){const t=new ke(async r=>{e[R].dispatchMessage(r)}),e=new ke(async r=>{t[R].dispatchMessage(r)});return t[R].addEventListener("close",()=>{e.close()},{once:!0}),e[R].addEventListener("close",()=>{t.close()},{once:!0}),[t,e]}function Zt(t,e){const r=[],s=()=>{for(const n of r)n()};r.push(t[R].addEventListener("message",n=>e[R].send(n.detail))),r.push(t[R].addEventListener("close",s,{once:!0})),r.push(e[R].addEventListener("message",n=>t[R].send(n.detail))),r.push(e[R].addEventListener("close",s,{once:!0}))}const ce=je("appetize.io:trace:transport:iframe");class Xt extends ke{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){ce("postMessage(legacy)",{message:e,targetOrigin:r,transfer:s}),this.#t.postMessage(e,r??this.#e,s)}handleClose(e){ce("close()"),window.removeEventListener("message",this.#r),super.handleClose(e)}#r=async e=>{if(ce("handleMessage()",e),e.source!==this.#t||(ce("handleMessage() -> source ok"),this.#e!=="*"&&e.origin!==this.#e))return;ce("handleMessage() -> origin ok");const r=e.data;if(!nt(r)){ce("handleMessage() -> legacy"),this.onmessage?.(e);return}ce("handleMessage() -> jsonrpc"),this[R].dispatchMessage(r)}}function _e(){let t,e;return{promise:new Promise((s,n)=>{e=s,t=n}),reject:t,resolve:e}}const os=2*1024*1024,Yt=je("appetize:client:acked-writable-stream");class as{unacked=0;#e;#t;#r;#s;#n=[];#o;constructor(e){this.#r=e,this.#o=e.window??os}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()},Yt("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;Yt("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={..._e(),until:e};return this.#n.push(r),r.promise}}class cs extends WritableStream{get unacked(){return this.#e.unacked}#e;constructor(e){const r=new as(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 ls=1024*1024;class fs{#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??=_e();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 us extends ReadableStream{#e;constructor({highWaterMark:e=ls,onCancel:r}={}){const s=new fs(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 ds{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=_e(),this.closed=this.#t.promise,this.closed.catch(hs),this.#s=new us({highWaterMark:s,onCancel:()=>{this.#i(void 0)}}),this.readable=this.#s,this.#n=new cs({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&&Q(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 hs(){}class ps{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 ys{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 Qt extends ys{#e;constructor(e){super({start:e.start,stop:e.stop}),this.#e=e.label}async createStream({signal:e}={}){e?.throwIfAborted();const r=new ps({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 ws{#e;#t;#r;#s;constructor(e){this.#s=e,this.#t=new Qt({label:"Log stream",start:()=>e.request("appetizeio.device.server.debug.log.start"),stop:()=>{Q(e,"appetizeio.device.server.debug.log.stop",void 0)}}),this.#r=new Qt({label:"Proxy intercept stream",start:()=>e.request("appetizeio.device.server.debug.proxyIntercept.start"),stop:()=>{Q(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 ds(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 lt(t){return{...bs(t),index:t.index,within:t.within?lt(t.within):void 0}}function bs(t){switch(t.by){case"testId":return{by:"testId",testId:t.testId};case"text":return{by:"text",text:gs(t.text)}}}function gs(t){return typeof t=="string"?{kind:"exact",value:t}:{flags:t.flags,kind:"regex",source:t.source}}const ms=400,er=["byTestId","byText","duration","index","x","y"],Es=new Set(er),Ss=/^-?(?:\d+(?:\.\d*)?|\.\d+)$/u,vs=/^[a-z]$/u,ft=/^\s$/u;class _ extends SyntaxError{constructor(e,r,s){super(`${e} at position ${String(r)}`,{cause:s})}}class As{#e=0;#t;constructor(e){this.#t=e}parse(){const e=[];for(;this.#e<this.#t.length;){const r=this.#i();if(ft.test(r))this.#e++;else if(r===">"){if(this.#t.charAt(this.#e+1)===">")throw new _('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 _(`Unexpected ${JSON.stringify(s)}; write selectors as {...}`,this.#e)}}return e}#r(){const e=this.#e,r=this.#c(s=>s!=="="&&!ut(s));if(this.#i()!=="=")return{kind:"bare",name:r,offset:e};if(r.length===0)throw new _('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 _('Only \\" and \\\\ escapes are supported',this.#e-1);this.#e++,r+=n}else{if(s==="")throw new _("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 _("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=>vs.test(i));try{return new RegExp(r,n)}catch(i){throw new _(`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 _('Unclosed "{"',e);if(i==="}"){if(this.#e++,n===0)throw new _('Expected a selector or wait in "{}"',e);return r===void 0?Is(s,e):{duration:r,kind:"wait"}}const l=this.#r();if(n===0&&l.name==="wait")r=l.kind==="attribute"?rr(l.value,"wait"):ms;else{if(r!==void 0)throw new _('"wait" takes no other attributes',l.offset);xs(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=>!ut(i));if(n.length===0)throw new _('Expected a value after "="',e);return{kind:"raw",offset:e,text:n}}if(!ut(this.#i()))throw new _('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=>ft.test(e))}}function tr(t){return new As(t).parse()}function xs(t,e,r){const{name:s,offset:n}=e;if(e.kind==="attribute"){dt(t,s,n,e.value);return}if(!s.includes(","))throw new _(`Expected key=value, got ${JSON.stringify(s)}`,n);if(r>0)throw new _("Write the x,y position first",n);const[i,l,...y]=s.split(",");if(y.length>0)throw new _("Expected a screen position as x,y",n);const p=n+i.length+1;dt(t,"x",n,{kind:"raw",offset:n,text:i}),dt(t,"y",p,{kind:"raw",offset:p,text:l})}function ks(t){return Es.has(t)}function ut(t){return t===""||t==="}"||ft.test(t)}function dt(t,e,r,s){if(!ks(e))throw new _(`Unknown attribute ${JSON.stringify(e)}; expected one of ${er.join(", ")}`,r);if(t.offsets[e]!==void 0)throw new _(`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 _("Only one of byText and byTestId may be given",r);e==="byText"?t.byText=Ms(s):t.byTestId=Ts(s);return;default:t[e]=rr(s,e)}}function Is(t,e){return{duration:t.duration,kind:"move",to:Os(t,e)}}function rr(t,e){if(t.kind!=="raw"||!Ss.test(t.text))throw new _(`"${e}" takes a number`,t.offset);return Number(t.text)}function Os(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 _('"index" needs byText or byTestId',i.index);if(l===void 0||y===void 0)throw new _("A screen position needs x and y",e);return{by:"position",x:l,y}}function Ts(t){if(t.kind==="regex")throw new _('"byTestId" takes a string',t.offset);return t.text}function Ms(t){return t.kind==="regex"?t.regex:t.text}function Ie(t){return t.by==="position"?{by:"position",x:t.x,y:t.y}:{...lt(t),x:t.x,y:t.y}}function Rs(t){return t.map(e=>e.kind==="move"?{duration:e.duration,kind:"move",to:Ie(e.to)}:e)}function Us(t){return{press:e=>{Q(t,"appetizeio.device.server.keyboard.press",{key:e})}}}function Ps({onRequest:t,parent:e,proxyInlet:r,signal:s}){const n=new Xt(e,{signal:s}),i=[()=>{n.close()}];return Zt(n,r),t&&i.push(Ne(n,l=>{t(l,{source:"parent"})})),{cleanup:()=>{for(const l of i)l()},notifies:()=>e===globalThis.window?void 0:n}}const Cs="@appetizeio/rpc:playwrightAdapter",De=Symbol.for(Cs);function Ls(t){window[De]&&console.warn("playwright exposed more than once, overwriting previous adapter");const e={send(r){t[R].send(r)},subscribe(r){return t[R].addEventListener("message",s=>{r(s.detail)})}};return window[De]=e,()=>{window[De]===e&&delete window[De]}}function Ns({onRequest:t,proxyInlet:e}){const[r,s]=ct(),i=[Ls(s),()=>{r.close()}];return Zt(r,e),t&&i.push(Ne(r,l=>{t(l,{source:"parent"})})),{cleanup:()=>{for(const l of i)l()},notifies:()=>r}}function _s(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 Ds(t){return{down:(e,r)=>{Q(t,"appetizeio.device.server.touch.down",{x:e,y:r})},move:(e,r)=>{Q(t,"appetizeio.device.server.touch.move",{x:e,y:r})},up:(e,r)=>{Q(t,"appetizeio.device.server.touch.up",{x:e,y:r})}}}const Bs=new Set(at),Fs=/^(?<key>[A-Za-z]+)>(?<repeat>\d+)\/$/u,zs=/(\{\{|\{[^{}]*\})/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(zs).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(!Bs.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: ${at.join(", ")}. Type characters as text, and escape a literal "{" as "{{".`)}function Vs(t){const e=Fs.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 sr(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,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 Js{#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,Q(this.#t,"appetizeio.device.server.video.stop",void 0))}#a(){this.#e||(this.#e=!0,Q(this.#t,"appetizeio.device.server.video.requestKeyFrame",void 0))}}class Ws{debug;keyboard;touch;video;#e;#t=[];#r;constructor(e,r={}){const s=sr(r)??{},{baseUrl:n,onClose:i,signal:l}=r;this.#e=n?Gs(n):void 0;const{onRequest:y,parent:p,proxyRequest:v}=s,m=Hs(y);l?.addEventListener("abort",this.close);const[T,M]=ct(),[L,C]=ct();this.#t.push(()=>{T.close(),M.close(),L.close(),C.close()}),this.#t.push(ot(C,e,{leftEffects:v}));const P=p==="playwright"?Ns({onRequest:m,proxyInlet:L}):p?Ps({onRequest:m,parent:p,proxyInlet:L,signal:l}):void 0;P&&this.#t.push(P.cleanup),this.#t.push(ot(M,L,{notifiesLeft:P?.notifies}));const{client:G,unsub:we}=is(T,{"appetizeio.device.client.debug.adbTunnel.data":j=>H.handleAdbTunnelData(j),"appetizeio.device.client.debug.adbTunnel.stopped":async j=>{H.handleAdbTunnelStopped(j)},"appetizeio.device.client.debug.log.entry":async j=>{H.handleLogEntry(j)},"appetizeio.device.client.debug.proxyIntercept.event":async j=>{H.handleProxyInterceptEvent(j)},"appetizeio.device.client.video.chunk":async j=>{x.handleChunk(j)}});this.#r=G,this.#t.push(we);const H=new ws(this.#r);this.#t.push(()=>{H.close()});const x=new Js(this.#r);this.#t.push(()=>{x.close()}),this.debug=H,this.keyboard=Us(this.#r),this.touch=Ds(this.#r),this.video=x,m&&(this.#t.push(Ne(M,j=>{m(j,{source:"self"})})),e instanceof Xt&&this.#t.push(Ne(e,j=>{m(j,{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 gesture(e,r){await this.#r.request("appetizeio.device.server.gesture",{options:r,steps:Rs(typeof e=="string"?tr(e):e)})}async inspect(e,r){return await this.#r.request("appetizeio.device.server.inspect",{options:r,selector:e?lt(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){return 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:_s(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: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)}},Zs={dateStyle:"medium",timeStyle:"short"},Xs=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(?::\d{2}(?:\.\d+)?)?(?:Z|[+-]\d{2}:\d{2})$/;function Be(t){return Array.isArray(t)?t.map(Be).join(", "):typeof t=="boolean"?t?"yes":"no":typeof t=="number"?t.toLocaleString():Ys(t)}function Ys(t){if(Xs.test(t)){const r=new Date(t);if(!Number.isNaN(r.getTime()))return r.toLocaleString(void 0,Zs)}const e=xt();return t===e?"~":t.startsWith(`${e}${Or}`)?`~${t.slice(e.length)}`:t}function nr(){return process.env.APPETIZE_CLI_HOME??re(xt(),".appetize","cli","sessions")}function ht(t){return re(nr(),t)}class Fe 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 Te extends Fe{sessionDir;constructor(e,{cause:r,details:s={},sessionId:n}){const i=ht(n);super(e,Object.assign({sessionDir:i},s),r),this.name="SessionError",this.sessionDir=i}static wrap(e,r){if(e instanceof Te||e instanceof le)return e;const s=e instanceof Error?e.message:String(e),n=e instanceof Fe?e.details:{};return new Te(s,{cause:e,details:n,sessionId:r})}hints(){return[`Check the session logs for details: ${Be(this.sessionDir)}`]}}class Qs extends Te{constructor(e){super(`Session ${e} already exists`,{sessionId:e}),this.name="SessionAlreadyExistsError"}hints(){return[`Pass --force to replace it, deleting ${Be(this.sessionDir)}`]}}class le extends Fe{#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 en(t,e,r){const s=e instanceof Error?e.message:String(e);if(!(e instanceof Fe))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(`
2
+ `)}function pt(t){try{return process.kill(t,0),!0}catch{return!1}}const tn=["SIGINT","SIGTERM"],rn=150;function sn(t){const e=new AbortController,r=setInterval(()=>{pt(t)||(clearInterval(r),e.abort(new Error("The device session exited")))},rn);return r.unref(),e.signal}function ir(){const t=new AbortController;for(const e of tn)process.once(e,()=>{t.abort(new Error(`Received ${e}`))});return t.signal}function nn(t,e){return new Promise((r,s)=>{if(e.aborted){s(or(e.reason));return}const n=()=>{clearTimeout(i),s(or(e.reason))},i=setTimeout(()=>{e.removeEventListener("abort",n),r()},t);e.addEventListener("abort",n,{once:!0})})}function or(t){return t instanceof Error?t:new Error(String(t))}function on(t){const e=t.at(-1);return{options:ln(e)?e:{},positionals:t.slice(0,-1).filter(r=>typeof r=="string"),signal:ir()}}function an(t,e){const r=ar(t,e);return r===void 0?void 0:cr(r,e)}function ar(t,e){if(t===void 0)return;const r=typeof t=="boolean"?Number.NaN:Number(t);if(!Number.isFinite(r))throw new le(`${e} expects a number, e.g., ${e}=-0.1`);return r}function yt(t,e){if(t!==void 0){if(typeof t!="string"||t==="")throw new le(`${e} needs a value`);return t}}function cr(t,e){if(!(t>=0&&t<=1))throw new le(`${e} expects a number between 0 and 1`);return t}function cn(t,e){const r=yt(t,e);if(r===void 0)throw new le(`${e} needs a value`);return r}function ln(t){return typeof t=="object"&&t!==null}const fn="APPETIZEIO_FEATURE_FLAGS";function un(){const t={};for(const e of(process.env[fn]??"").split(",")){const r=e.trim();r!==""&&(t[r]=!0)}return t}function dn(){const t=process.env.APPETIZE_API_TOKEN;if(!t)throw new Error("APPETIZE_API_TOKEN must be set");return t}function lr(t){return yt(t.endpoint,"--endpoint")??hn()}function hn(){const t=process.env.APPETIZE_ENDPOINT?.trim();return t===""?void 0:t}const pn="https://appetize.io";async function fr(t,{authorize:e=!0,commandOptions:r={},query:s={},...n}={}){const i=new URL(t,lr(r)??pn);for(const[p,v]of Object.entries(s))i.searchParams.set(p,v);const l=new Headers(n.headers);e&&l.set("x-api-key",dn());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 ur=["android","ios"];function dr(t={},e){return fr("/api/v2/service/devices",{authorize:!1,commandOptions:t,signal:e})}function yn(t){return ur.includes(t)}async function wn(t,e={}){return(await dr(e)).find(s=>s.id===t)?.platform}function bn(t){let e={...t,updatedAt:new Date().toISOString()};return{path:bt(e.sessionId),save:r=>(e={...e,...r,updatedAt:new Date().toISOString()},kn(e),e)}}function hr(t){const e=t.state?.phase;return e==="ended"||e==="error"?!1:pt(t.pid)}function gn(){const t=nr();return At(t,{recursive:!0}),Ir(t).map(e=>wt(e)).filter(e=>e!==void 0)}function mn(t){if(t!==void 0){const r=wt(t);if(!r)throw new Error(`No session found for id ${t}`);return r}const e=gn().filter(hr);if(e.length===0)throw new Error("No active sessions");if(e.length>1)throw new le("There are multiple active sessions",["Specify --session-id to pick one"]);return e[0]}function wt(t){try{return JSON.parse(xr(bt(t),"utf8"))}catch{return}}function En(t){kr(ht(t),{force:!0,recursive:!0})}function Sn(t){return re(Oe(t),"control.sock")}function pr(t){return re(Oe(t),"daemon.log")}function vn(t){return re(Oe(t),"device.log.jsonl")}function An(t,e){return{daemon:pr(t),device:vn(t),...e==="intercept"?{network:xn(t)}:void 0}}function xn(t){return re(Oe(t),"network.jsonl")}function Oe(t){const e=ht(t);return At(e,{recursive:!0}),e}function bt(t){return re(Oe(t),"state.json")}function kn(t){const e=bt(t.sessionId),r=`${e}.tmp`;vr(r,`${JSON.stringify(t,null,2)}
3
+ `),Ar(r,e)}const gt="APPETIZE_DAEMON_CONFIG";function In(){const t=process.env[gt];if(!t)throw new Error(`${gt} is not set`);return JSON.parse(t)}function On(t){return JSON.stringify(t)}export{mn as A,on as B,en as C,Ws as D,at as E,Wr as F,R as G,jr as H,nt as I,sr as J,_e as K,In as L,bn as M,wn as N,Jt as O,ot as P,Sn as Q,ir as R,Te as S,ke as T,le as U,ar as a,nn as b,dr as c,ss as d,ur as e,fr as f,tr as g,cn as h,yn as i,pr as j,gt as k,hr as l,pt as m,sn as n,un as o,yt as p,lr as q,cr as r,On as s,wt as t,Qs as u,En as v,An as w,an as x,Be as y,Gt as z};
package/daemon.js CHANGED
@@ -1,2 +1,2 @@
1
- import{T as M,E as L,F as O,G as b,H as _,D as z,I as F,J as V,K as N,v as j,L as H,M as Q,N as J,O as k,P as G,Q as K}from"./config-DfwUvfKT.js";import S from"debug";import{createServer as A}from"node:net";import{pipeline as $}from"node:stream";import{rm as Z}from"node:fs/promises";import{readFileSync as B,createWriteStream as X,existsSync as Y,rmSync as ee}from"node:fs";import{createServer as te}from"node:http";import{WebSocketServer as ne}from"ws";import{pipeline as re}from"node:stream/promises";import{EncodedVideoPacketSource as oe,Output as se,FilePathTarget as ie,Mp4OutputFormat as ae,EncodedPacket as ce}from"mediabunny";import"stream";import"module";import"json-rpc-2.0";import"node:path";import"node:os";const de=S("appetize.io:transport:ws-ping"),ue=3e4;function le(e){let t=!0;const n=()=>{t=!0};e.on("pong",n);const r=setInterval(()=>{if(!t){clearInterval(r),de("liveness ping went unanswered, terminating"),e.terminate();return}e.readyState===e.OPEN&&(t=!1,e.ping())},ue);return{destroy(){clearInterval(r),e.off("pong",n)},pong:n}}const v=S("appetize.io:trace:transport:websocket");class E extends M{constructor(t,{signal:n}={}){super(async o=>{this.#e.send(L(o))},{signal:n}),this.wsOrUrl=t,typeof t=="string"?(this.#e=new WebSocket(t),this.#e.binaryType="arraybuffer"):this.#e=t;const r=this.#e;if(r instanceof WebSocket?(r.addEventListener("open",this.#s),r.addEventListener("message",this.#o),r.addEventListener("error",this.#r),r.addEventListener("close",this.#n),this.#t.push(()=>{r.removeEventListener("open",this.#s),r.removeEventListener("message",this.#o),r.removeEventListener("error",this.#r),r.removeEventListener("close",this.#n)})):(r.addEventListener("open",this.#s),r.addEventListener("message",this.#o),r.addEventListener("error",this.#r),r.addEventListener("close",this.#n),this.#t.push(()=>{r.removeEventListener("open",this.#s),r.removeEventListener("message",this.#o),r.removeEventListener("error",this.#r),r.removeEventListener("close",this.#n)})),this.send=r.send.bind(r),"ping"in r){const{destroy:o,pong:s}=le(r);this.#c=s,this.#t.push(o)}}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){v("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=>{v("handleWebSocketClose()",t);try{this.#d(t)}finally{this.close()}};#r=t=>{v("handleWebSocketError()",t),this.onerror?.(t)};#o=async t=>{v("handleWebSocketMessage()",t),this.#c?.();const n=this.#u(t);if(!n){v("handleWebSocketMessage() -> legacy"),this.onmessage?.(t);return}v("handleWebSocketMessage() -> jsonrpc",n),this[O].dispatchMessage(n)};#s=t=>{v("handleWebSocketOpen()",t),this.onopen?.(t)};#u(t){try{const n=b(new Uint8Array(t.data));return _(n)?n:null}catch{return null}}}function y(e){return typeof e=="object"&&e!==null}function R(e){try{const t=b(new Uint8Array(e.data));if(y(t)&&typeof t.name=="string")return{name:t.name,payload:"payload"in t?t.payload:void 0}}catch{}}async function fe(e,t={}){const n=t.baseUrl??(typeof e=="string"?new URL(e).origin:void 0),r=typeof e=="string"?new E(e,{signal:t.signal}):e,o=new z(r,{...t,baseUrl:n});return typeof e=="string"&&await pe(r,o,t),o}function pe(e,t,n){const r=F(n)?.onLegacyMessage;return new Promise((o,s)=>{e.onopen=()=>{o()},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=R(i);c&&r?.(c)}})}async function he(e,{device:t,onStateChange:n,signal:r}){r?.throwIfAborted(),n?.({device:t,phase:"starting"}),await new Promise((o,s)=>{const i=()=>{c(),s(r?.reason)},c=()=>{e.onmessage=void 0,e.onclose=void 0,r?.removeEventListener("abort",i)};e.onmessage=a=>{const d=we(R(a),t);d&&(n?.(d),d.phase==="ready"&&(c(),o()))},e.onclose=()=>{c(),s(new Error("The device closed before it was ready"))},r?.addEventListener("abort",i,{once:!0})})}function we(e,t){if(!e)return;if(e.name==="ready")return{device:t,phase:"ready"};if(e.name!=="launchStatus")return;switch(y(e.payload)&&typeof e.payload.status=="string"?e.payload.status:void 0){case"downloadingApp":return{device:t,phase:"downloadingApp"};case"installingApp":return{device:t,phase:"installingApp"};case"launchingApp":return{device:t,phase:"launchingApp"};default:return}}function ve(){return typeof process>"u"?void 0:process}function ge(e){return{deviceType:e.id,osVersion:e.osVersion}}function ye(e){return e==="intercept"?"interceptOnDemand":e}class g extends Error{code;constructor(t,n){super(n),this.name="SessionRequestError",this.code=t}}function me(e,{onClose:t,onEvent:n,signal:r}={}){return new Promise((o,s)=>{const i=new WebSocket(e);i.binaryType="arraybuffer",i.onopen=()=>{P(i,{capabilities:{},t:"handshake"})},i.onmessage=c=>{be(i,c,{onEvent:n,onHandshake:a=>{o({close:()=>{i.close()},id:a})}})},i.onclose=()=>{s(new g("disconnected",`The connection to ${e} closed`)),t?.()},r?.addEventListener("abort",()=>{s(r.reason),i.close()},{once:!0})})}function be(e,t,n){const r=b(new Uint8Array(t.data));y(r)&&(r.t==="handshake"&&typeof r.id=="string"?n.onHandshake(r.id):r.name==="ping"?P(e,{name:"pong"}):typeof r.name=="string"&&n.onEvent?.(r.name,r.payload))}function P(e,t){e.send(L(t))}async function Se(e,t,{apiToken:n,onQueue:r,signal:o}={}){const s=V();ke(s.reject,o);const i=await me(Ae(e),{onClose:()=>{s.reject(Ee())},onEvent:(c,a)=>{Te(c,a,s,r)},signal:o});return Le(e,{apiToken:n,data:t,socketid:i.id},o).catch(s.reject),await s.promise.finally(()=>{i.close()})}function Ee(){return new g("disconnected","The webserver connection closed before a session was granted")}function I(e,t){return y(e)?e[t]:void 0}function Te(e,t,n,r){if(e==="queue"||e==="concurrentQueue"){const o=e==="queue"?Re(t):Pe(t);o&&r?.(o)}else e==="newSession"?$e(n,t):e==="userError"&&n.reject(new g("denied",Ie(t)))}function U(e,t){const n=I(e,t);return typeof n=="number"?n:void 0}function m(e,t){const n=I(e,t);return typeof n=="string"?n:void 0}async function Le(e,t,n){const r=await fetch(new URL("/api/session/request",e),{body:JSON.stringify(t),headers:{"content-type":"application/json"},method:"POST",signal:n});if(!r.ok)throw new g("denied",`The webserver rejected the session request (${String(r.status)})`)}function ke(e,t){t?.addEventListener("abort",()=>{e(t.reason)},{once:!0})}function Ae(e){const t=new URL("/client",e);return t.protocol=t.protocol==="http:"?"ws:":"wss:",t.href}function $e(e,t){const n=m(t,"path"),r=m(t,"sessionToken");n!==void 0&&r!==void 0?e.resolve({path:n,sessionToken:r}):e.reject(new g("denied","The granted session is missing its address"))}function Re(e){const t=U(e,"position");return t===void 0?void 0:{position:t,reason:"capacity"}}function Pe(e){const t=U(e,"position");if(t!==void 0)return{limit:m(e,"name")??"Queue",position:t,reason:"concurrency"}}function Ie(e){return m(e,"message")??"The session request was denied"}async function Ue({apiToken:e=Ce(),codec:t="h264",device:n,endpoint:r="https://appetize.io",onStateChange:o,open:s,proxy:i,signal:c,target:a}){if(c?.throwIfAborted(),!a)throw new TypeError("target is required");if(!n.id)throw new TypeError("device.id is required");o?.({phase:"requesting"});const d=await Se(r,{codec:t,launchUrl:s,noVideo:!0,proxy:ye(i),publicKey:a,...ge(n)},{apiToken:e,onQueue:p=>{o?.({phase:"queued",queue:p})},signal:c});return{baseUrl:new URL(d.path).origin,url:We(d)}}function Ce(){return ve()?.env.APPETIZE_API_TOKEN}function We(e){const t=new URL("/client",e.path);return t.protocol=t.protocol==="http:"?"ws:":"wss:",t.searchParams.set("sessionToken",e.sessionToken),t.href}const De=S("appetize:daemon");function f(e){De(e)}function qe(e,{message:t="The operation timed out"}={}){const n=new AbortController,r=setTimeout(()=>{n.abort(new Error(t))},e),o=()=>{clearTimeout(r)};return{cancel:o,signal:n.signal,[Symbol.dispose]:o}}var xe=(e,t)=>(t=Symbol[e])?t:Symbol.for("Symbol."+e),C=e=>{throw TypeError(e)},Me=(e,t,n)=>{if(t!=null){typeof t!="object"&&typeof t!="function"&&C("Object expected");var r,o;r===void 0&&(r=t[xe("dispose")]),typeof r!="function"&&C("Object not disposable"),o&&(r=function(){try{o.call(this)}catch(s){return Promise.reject(s)}}),e.push([n,r,t])}return t},Oe=(e,t,n)=>{var r=typeof SuppressedError=="function"?SuppressedError:function(i,c,a,d){return d=Error(a),d.name="SuppressedError",d.error=i,d.suppressed=c,d},o=i=>t=n?new r(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=>(o(a),s()))}catch(a){o(a)}if(n)throw t};return s()};const _e=1e4;async function ze(e,t,{onClose:n,signal:r}={}){var o=[];try{const c=Me(o,qe(_e,{message:"Timed out waiting for session request state"})),a=AbortSignal.any([r,c.signal].filter(w=>!!w)),d=w=>{t.save({state:w}),f(w.phase),w.phase!=="requesting"&&c.cancel()},{baseUrl:p,url:u}=await Ue({device:e.device,endpoint:e.endpoint,onStateChange:d,open:e.open,proxy:e.proxy,signal:a,target:e.target});t.save({baseUrl:p});const l=new E(u,{signal:a});return await he(l,{device:e.device,onStateChange:d,signal:a}),l.onclose=()=>{n?.("The device connection closed")},{device:await fe(l,{baseUrl:p,signal:a}),transport:l}}catch(c){var s=c,i=!0}finally{Oe(o,s,i)}}function Fe(){const e=N(),t=j(e.sessionId,e.proxy),n=H({device:e.device,endpoint:e.endpoint,open:e.open,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 Ve(e,{host:t="127.0.0.1",onError:n,port:r=0,signal:o}={}){o?.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 h=await e.debug.createAdbTunnel();if(l.destroyed){h.close();return}u.tunnel=h,h.closed.catch(w=>{n?.(w)}),Ne(l,h)}catch(h){l.destroyed||n?.(h),l.destroy()}},a=A(u=>{i();const l={socket:u};s=l,u.once("close",()=>{s===l&&(s=void 0)}),c(l)}),d=()=>{o?.removeEventListener("abort",d),i(),a.close()};o?.addEventListener("abort",d,{once:!0});const p=await je(a,t,r);return{close:d,url:new URL(`adb://${p.address}:${String(p.port)}`)}}function Ne(e,t){$(t.readable,e,W),$(e,async n=>{const r=t.writable.getWriter();try{for await(const o of n)await r.write(o);await r.close()}catch(o){throw await r.abort(o),o}},W)}function W(){}function je(e,t,n){return new Promise((r,o)=>{e.once("error",o),e.listen({host:t,port:n},()=>{e.off("error",o);const s=e.address();if(s===null||typeof s=="string"){o(new Error("The listener has no tcp address"));return}r(s)})})}async function He(e,t,n,{signal:r}={}){try{if(!await Qe(t))return;const o=await Ve(e,{onError:s=>{f(`adb endpoint error: ${D(s)}`)},signal:r});n.save({adbSerial:o.url.host}),f(`adb endpoint listening at ${o.url.host}`)}catch(o){f(`adb endpoint unavailable: ${D(o)}`)}}async function Qe(e){return await Q(e.device.id,{endpoint:e.endpoint})==="android"}function D(e){return e instanceof Error?e.message:String(e)}async function Je(e,t,{methods:n={},signal:r}={}){await Z(t,{force:!0});const o=new Set,s=A(i=>{f("control client connected"),o.add(i),i.once("close",()=>{o.delete(i)});const c=new J(i,{signal:r});k(c,e,{leftEffects:()=>n})});r?.addEventListener("abort",()=>{for(const i of o)i.destroy()},{once:!0}),await new Promise((i,c)=>{s.once("error",c),s.listen({path:t,signal:r},()=>{s.off("error",c),i()})})}async function Ge(e,t,n,{recorder:r,signal:o}){const s=G(n);return await Je(e,s,{methods:{"appetizeio.cli.record.start":async i=>await r.start(i),"appetizeio.cli.record.stop":async()=>await r.stop()},signal:o}),t.save({controlSocket:s}),s}const q="127.0.0.1";async function Ke(e,t,n={}){try{const r=await Ze(e,n);return t.save({viewerUrl:r.url.href}),f(`web endpoint listening at ${r.url.href}`),r}catch(r){f(`web endpoint unavailable: ${tt(r)}`);return}}async function Ze(e,{port:t=0,signal:n,viewerHtml:r=B(new URL("./viewer.html",import.meta.url),"utf8")}){n?.throwIfAborted();const o=te((u,l)=>{Xe(u,l,r)}),s=new Set,i=new ne({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 E(u);k(l,e),u.once("close",()=>{s.delete(u)})}),o.on("upgrade",(u,l,h)=>{Ye(i,u,l,h)});const a=()=>(c??=new Promise((u,l)=>{n?.removeEventListener("abort",d);for(const h of s)Be(h);i.close(),o.close(h=>{h?l(h):u()})}),c),d=()=>{a()};await et(o,t),n?.addEventListener("abort",d,{once:!0});const p=o.address();if(!p||typeof p=="string")throw await a(),new Error("Web address unavailable");return{close:a,url:new URL(`http://${q}:${String(p.port)}/`)}}function Be(e){e.close(1001)}function Xe(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 Ye(e,t,n,r){if(t.url!=="/ws"){n.destroy();return}e.handleUpgrade(t,n,r,o=>{e.emit("connection",o,t)})}function et(e,t){return new Promise((n,r)=>{const o=s=>{r(s)};e.once("error",o),e.listen(t,q,()=>{e.removeListener("error",o),n()})})}function tt(e){return e instanceof Error?e.message:String(e)}function nt(e){const t=new AbortController,n=rt(e,t),r=K();return r.addEventListener("abort",()=>{const{reason:o}=r;n(o instanceof Error?o.message:String(o))},{once:!0}),{shutdown:n,signal:t.signal}}function rt(e,t){let n=!1;return r=>{n||(n=!0,e.save({endedAt:new Date().toISOString(),endedReason:r,state:{phase:"ended"}}),f(r),t.abort())}}async function x(e,t,{label:n,signal:r}){try{const o=await e();await re(o.readable.pipeThrough(ot()),X(t,{flags:"a"}))}catch(o){if(r?.aborted)return;const s=o instanceof Error?o.message:String(o);f(`${n} ended with an error: ${s}`)}}function ot(){return new TransformStream({transform:(e,t)=>{t.enqueue(`${JSON.stringify(e)}
1
+ import{T as M,F as L,G as O,H as b,I as _,D as z,J as F,K as V,L as N,w as j,M as H,N as Q,O as J,P as k,Q as G,R as K}from"./config-B56X5rgA.js";import S from"debug";import{createServer as A}from"node:net";import{pipeline as $}from"node:stream";import{rm as Z}from"node:fs/promises";import{readFileSync as B,createWriteStream as X,existsSync as Y,rmSync as ee}from"node:fs";import{createServer as te}from"node:http";import{WebSocketServer as ne}from"ws";import{pipeline as re}from"node:stream/promises";import{EncodedVideoPacketSource as oe,Output as se,FilePathTarget as ie,Mp4OutputFormat as ae,EncodedPacket as ce}from"mediabunny";import"stream";import"module";import"json-rpc-2.0";import"node:path";import"node:os";const de=S("appetize.io:transport:ws-ping"),ue=3e4;function le(e){let t=!0;const n=()=>{t=!0};e.on("pong",n);const r=setInterval(()=>{if(!t){clearInterval(r),de("liveness ping went unanswered, terminating"),e.terminate();return}e.readyState===e.OPEN&&(t=!1,e.ping())},ue);return{destroy(){clearInterval(r),e.off("pong",n)},pong:n}}const v=S("appetize.io:trace:transport:websocket");class E extends M{constructor(t,{signal:n}={}){super(async o=>{this.#e.send(L(o))},{signal:n}),this.wsOrUrl=t,typeof t=="string"?(this.#e=new WebSocket(t),this.#e.binaryType="arraybuffer"):this.#e=t;const r=this.#e;if(r instanceof WebSocket?(r.addEventListener("open",this.#s),r.addEventListener("message",this.#o),r.addEventListener("error",this.#r),r.addEventListener("close",this.#n),this.#t.push(()=>{r.removeEventListener("open",this.#s),r.removeEventListener("message",this.#o),r.removeEventListener("error",this.#r),r.removeEventListener("close",this.#n)})):(r.addEventListener("open",this.#s),r.addEventListener("message",this.#o),r.addEventListener("error",this.#r),r.addEventListener("close",this.#n),this.#t.push(()=>{r.removeEventListener("open",this.#s),r.removeEventListener("message",this.#o),r.removeEventListener("error",this.#r),r.removeEventListener("close",this.#n)})),this.send=r.send.bind(r),"ping"in r){const{destroy:o,pong:s}=le(r);this.#c=s,this.#t.push(o)}}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){v("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=>{v("handleWebSocketClose()",t);try{this.#d(t)}finally{this.close()}};#r=t=>{v("handleWebSocketError()",t),this.onerror?.(t)};#o=async t=>{v("handleWebSocketMessage()",t),this.#c?.();const n=this.#u(t);if(!n){v("handleWebSocketMessage() -> legacy"),this.onmessage?.(t);return}v("handleWebSocketMessage() -> jsonrpc",n),this[O].dispatchMessage(n)};#s=t=>{v("handleWebSocketOpen()",t),this.onopen?.(t)};#u(t){try{const n=b(new Uint8Array(t.data));return _(n)?n:null}catch{return null}}}function y(e){return typeof e=="object"&&e!==null}function R(e){try{const t=b(new Uint8Array(e.data));if(y(t)&&typeof t.name=="string")return{name:t.name,payload:"payload"in t?t.payload:void 0}}catch{}}async function fe(e,t={}){const n=t.baseUrl??(typeof e=="string"?new URL(e).origin:void 0),r=typeof e=="string"?new E(e,{signal:t.signal}):e,o=new z(r,{...t,baseUrl:n});return typeof e=="string"&&await pe(r,o,t),o}function pe(e,t,n){const r=F(n)?.onLegacyMessage;return new Promise((o,s)=>{e.onopen=()=>{o()},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=R(i);c&&r?.(c)}})}async function he(e,{onStateChange:t,signal:n}){n?.throwIfAborted(),t?.({phase:"starting"}),await new Promise((r,o)=>{const s=()=>{i(),o(n?.reason)},i=()=>{e.onmessage=void 0,e.onclose=void 0,n?.removeEventListener("abort",s)};e.onmessage=c=>{const a=we(R(c));a&&(t?.(a),a.phase==="ready"&&(i(),r()))},e.onclose=()=>{i(),o(new Error("The device closed before it was ready"))},n?.addEventListener("abort",s,{once:!0})})}function we(e){if(!e)return;if(e.name==="ready")return{phase:"ready"};if(e.name!=="launchStatus")return;switch(y(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 ve(){return typeof process>"u"?void 0:process}function ge(e){return{deviceType:e.id,osVersion:e.osVersion}}function ye(e){return e==="intercept"?"interceptOnDemand":e}class g extends Error{code;constructor(t,n){super(n),this.name="SessionRequestError",this.code=t}}function me(e,{onClose:t,onEvent:n,signal:r}={}){return new Promise((o,s)=>{const i=new WebSocket(e);i.binaryType="arraybuffer",i.onopen=()=>{P(i,{capabilities:{},t:"handshake"})},i.onmessage=c=>{be(i,c,{onEvent:n,onHandshake:a=>{o({close:()=>{i.close()},id:a})}})},i.onclose=()=>{s(new g("disconnected",`The connection to ${e} closed`)),t?.()},r?.addEventListener("abort",()=>{s(r.reason),i.close()},{once:!0})})}function be(e,t,n){const r=b(new Uint8Array(t.data));y(r)&&(r.t==="handshake"&&typeof r.id=="string"?n.onHandshake(r.id):r.name==="ping"?P(e,{name:"pong"}):typeof r.name=="string"&&n.onEvent?.(r.name,r.payload))}function P(e,t){e.send(L(t))}async function Se(e,t,{apiToken:n,onQueue:r,signal:o}={}){const s=V();ke(s.reject,o);const i=await me(Ae(e),{onClose:()=>{s.reject(Ee())},onEvent:(c,a)=>{Te(c,a,s,r)},signal:o});return Le(e,{apiToken:n,data:t,socketid:i.id},o).catch(s.reject),await s.promise.finally(()=>{i.close()})}function Ee(){return new g("disconnected","The webserver connection closed before a session was granted")}function I(e,t){return y(e)?e[t]:void 0}function Te(e,t,n,r){if(e==="queue"||e==="concurrentQueue"){const o=e==="queue"?Re(t):Pe(t);o&&r?.(o)}else e==="newSession"?$e(n,t):e==="userError"&&n.reject(new g("denied",Ie(t)))}function U(e,t){const n=I(e,t);return typeof n=="number"?n:void 0}function m(e,t){const n=I(e,t);return typeof n=="string"?n:void 0}async function Le(e,t,n){const r=await fetch(new URL("/api/session/request",e),{body:JSON.stringify(t),headers:{"content-type":"application/json"},method:"POST",signal:n});if(!r.ok)throw new g("denied",`The webserver rejected the session request (${String(r.status)})`)}function ke(e,t){t?.addEventListener("abort",()=>{e(t.reason)},{once:!0})}function Ae(e){const t=new URL("/client",e);return t.protocol=t.protocol==="http:"?"ws:":"wss:",t.href}function $e(e,t){const n=m(t,"path"),r=m(t,"sessionToken");n!==void 0&&r!==void 0?e.resolve({path:n,sessionToken:r}):e.reject(new g("denied","The granted session is missing its address"))}function Re(e){const t=U(e,"position");return t===void 0?void 0:{position:t,reason:"capacity"}}function Pe(e){const t=U(e,"position");if(t!==void 0)return{limit:m(e,"name")??"Queue",position:t,reason:"concurrency"}}function Ie(e){return m(e,"message")??"The session request was denied"}async function Ue({apiToken:e=Ce(),codec:t="h264",device:n,endpoint:r="https://appetize.io",onStateChange:o,open:s,proxy:i,signal:c,target:a}){if(c?.throwIfAborted(),!a)throw new TypeError("target is required");if(!n.id)throw new TypeError("device.id is required");o?.({phase:"requesting"});const d=await Se(r,{codec:t,launchUrl:s,noVideo:!0,proxy:ye(i),publicKey:a,...ge(n)},{apiToken:e,onQueue:p=>{o?.({phase:"queued",queue:p})},signal:c});return{baseUrl:new URL(d.path).origin,url:We(d)}}function Ce(){return ve()?.env.APPETIZE_API_TOKEN}function We(e){const t=new URL("/client",e.path);return t.protocol=t.protocol==="http:"?"ws:":"wss:",t.searchParams.set("sessionToken",e.sessionToken),t.href}const De=S("appetize:daemon");function f(e){De(e)}function qe(e,{message:t="The operation timed out"}={}){const n=new AbortController,r=setTimeout(()=>{n.abort(new Error(t))},e),o=()=>{clearTimeout(r)};return{cancel:o,signal:n.signal,[Symbol.dispose]:o}}var xe=(e,t)=>(t=Symbol[e])?t:Symbol.for("Symbol."+e),C=e=>{throw TypeError(e)},Me=(e,t,n)=>{if(t!=null){typeof t!="object"&&typeof t!="function"&&C("Object expected");var r,o;r===void 0&&(r=t[xe("dispose")]),typeof r!="function"&&C("Object not disposable"),o&&(r=function(){try{o.call(this)}catch(s){return Promise.reject(s)}}),e.push([n,r,t])}return t},Oe=(e,t,n)=>{var r=typeof SuppressedError=="function"?SuppressedError:function(i,c,a,d){return d=Error(a),d.name="SuppressedError",d.error=i,d.suppressed=c,d},o=i=>t=n?new r(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=>(o(a),s()))}catch(a){o(a)}if(n)throw t};return s()};const _e=1e4;async function ze(e,t,{onClose:n,signal:r}={}){var o=[];try{const c=Me(o,qe(_e,{message:"Timed out waiting for session request state"})),a=AbortSignal.any([r,c.signal].filter(w=>!!w)),d=w=>{t.save({state:w}),f(w.phase),w.phase!=="requesting"&&c.cancel()},{baseUrl:p,url:u}=await Ue({device:e.device,endpoint:e.endpoint,onStateChange:d,open:e.open,proxy:e.proxy,signal:a,target:e.target});t.save({baseUrl:p});const l=new E(u,{signal:a});return await he(l,{onStateChange:d,signal:a}),l.onclose=()=>{n?.("The device connection closed")},{device:await fe(l,{baseUrl:p,signal:a}),transport:l}}catch(c){var s=c,i=!0}finally{Oe(o,s,i)}}function Fe(){const e=N(),t=j(e.sessionId,e.proxy),n=H({device:e.device,endpoint:e.endpoint,open:e.open,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 Ve(e,{host:t="127.0.0.1",onError:n,port:r=0,signal:o}={}){o?.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 h=await e.debug.createAdbTunnel();if(l.destroyed){h.close();return}u.tunnel=h,h.closed.catch(w=>{n?.(w)}),Ne(l,h)}catch(h){l.destroyed||n?.(h),l.destroy()}},a=A(u=>{i();const l={socket:u};s=l,u.once("close",()=>{s===l&&(s=void 0)}),c(l)}),d=()=>{o?.removeEventListener("abort",d),i(),a.close()};o?.addEventListener("abort",d,{once:!0});const p=await je(a,t,r);return{close:d,url:new URL(`adb://${p.address}:${String(p.port)}`)}}function Ne(e,t){$(t.readable,e,W),$(e,async n=>{const r=t.writable.getWriter();try{for await(const o of n)await r.write(o);await r.close()}catch(o){throw await r.abort(o),o}},W)}function W(){}function je(e,t,n){return new Promise((r,o)=>{e.once("error",o),e.listen({host:t,port:n},()=>{e.off("error",o);const s=e.address();if(s===null||typeof s=="string"){o(new Error("The listener has no tcp address"));return}r(s)})})}async function He(e,t,n,{signal:r}={}){try{if(!await Qe(t))return;const o=await Ve(e,{onError:s=>{f(`adb endpoint error: ${D(s)}`)},signal:r});n.save({adbSerial:o.url.host}),f(`adb endpoint listening at ${o.url.host}`)}catch(o){f(`adb endpoint unavailable: ${D(o)}`)}}async function Qe(e){return await Q(e.device.id,{endpoint:e.endpoint})==="android"}function D(e){return e instanceof Error?e.message:String(e)}async function Je(e,t,{methods:n={},signal:r}={}){await Z(t,{force:!0});const o=new Set,s=A(i=>{f("control client connected"),o.add(i),i.once("close",()=>{o.delete(i)});const c=new J(i,{signal:r});k(c,e,{leftEffects:()=>n})});r?.addEventListener("abort",()=>{for(const i of o)i.destroy()},{once:!0}),await new Promise((i,c)=>{s.once("error",c),s.listen({path:t,signal:r},()=>{s.off("error",c),i()})})}async function Ge(e,t,n,{recorder:r,signal:o}){const s=G(n);return await Je(e,s,{methods:{"appetizeio.cli.record.start":async i=>await r.start(i),"appetizeio.cli.record.stop":async()=>await r.stop()},signal:o}),t.save({controlSocket:s}),s}const q="127.0.0.1";async function Ke(e,t,n={}){try{const r=await Ze(e,n);return t.save({viewerUrl:r.url.href}),f(`web endpoint listening at ${r.url.href}`),r}catch(r){f(`web endpoint unavailable: ${tt(r)}`);return}}async function Ze(e,{port:t=0,signal:n,viewerHtml:r=B(new URL("./viewer.html",import.meta.url),"utf8")}){n?.throwIfAborted();const o=te((u,l)=>{Xe(u,l,r)}),s=new Set,i=new ne({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 E(u);k(l,e),u.once("close",()=>{s.delete(u)})}),o.on("upgrade",(u,l,h)=>{Ye(i,u,l,h)});const a=()=>(c??=new Promise((u,l)=>{n?.removeEventListener("abort",d);for(const h of s)Be(h);i.close(),o.close(h=>{h?l(h):u()})}),c),d=()=>{a()};await et(o,t),n?.addEventListener("abort",d,{once:!0});const p=o.address();if(!p||typeof p=="string")throw await a(),new Error("Web address unavailable");return{close:a,url:new URL(`http://${q}:${String(p.port)}/`)}}function Be(e){e.close(1001)}function Xe(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 Ye(e,t,n,r){if(t.url!=="/ws"){n.destroy();return}e.handleUpgrade(t,n,r,o=>{e.emit("connection",o,t)})}function et(e,t){return new Promise((n,r)=>{const o=s=>{r(s)};e.once("error",o),e.listen(t,q,()=>{e.removeListener("error",o),n()})})}function tt(e){return e instanceof Error?e.message:String(e)}function nt(e){const t=new AbortController,n=rt(e,t),r=K();return r.addEventListener("abort",()=>{const{reason:o}=r;n(o instanceof Error?o.message:String(o))},{once:!0}),{shutdown:n,signal:t.signal}}function rt(e,t){let n=!1;return r=>{n||(n=!0,e.save({endedAt:new Date().toISOString(),endedReason:r,state:{phase:"ended"}}),f(r),t.abort())}}async function x(e,t,{label:n,signal:r}){try{const o=await e();await re(o.readable.pipeThrough(ot()),X(t,{flags:"a"}))}catch(o){if(r?.aborted)return;const s=o instanceof Error?o.message:String(o);f(`${n} ended with an error: ${s}`)}}function ot(){return new TransformStream({transform:(e,t)=>{t.enqueue(`${JSON.stringify(e)}
2
2
  `)}})}async function st(e,t,{signal:n}={}){await x(async()=>await e.debug.createLogStream({signal:n}),t,{label:"log capture",signal:n})}async function it(e,t,{signal:n}={}){await x(async()=>await e.debug.createProxyInterceptStream({signal:n}),t,{label:"network capture",signal:n})}const T=30;async function at(e,t){await e.pipeTo(dt(t))}function ct(e){return{decoderConfig:{codec:"avc1.640028",codedHeight:e.height,codedWidth:e.width}}}function dt(e){let t;const n=async()=>{await t?.output.finalize()};return new WritableStream({abort:n,close:n,write:async r=>{r.data.byteLength!==0&&(t??=await ut(ft(r),e),lt(t,r),await pt(t,r))}})}async function ut(e,t){const n=new oe("avc"),r=new se({format:new ae({fastStart:"fragmented"}),target:new ie(t,{chunked:!1})});return r.addVideoTrack(n,{frameRate:T}),await r.start(),{frame:0,output:r,seen:{height:e.height,width:e.width},size:{height:e.height,width:e.width},source:n}}function lt(e,t){if(t.type!=="key")return;const{seen:n,size:r}=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(r.width)}x${String(r.height)}`))}function ft(e){if(e.type!=="key")throw new Error("Video stream started without a key chunk");return e}async function pt(e,t){const n=new ce(t.data,t.type,e.frame/T,1/T);e.frame+=1,await e.source.add(n,ct(e.size))}function ht(e,t,{signal:n}={}){let r,o;const s=async(a,{force:d=!1}={})=>{if(Y(a)){if(!d)throw new Error(`A recording already exists at ${a}; pass --force to overwrite`);ee(a)}const p=await e.video.createStream({signal:n});return r={done:wt(p,a),path:a,stream:p},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{r=void 0,o=void 0}},c=async()=>{if(!r)return;const{path:a}=r;await i(r),f(`closed the video recording: ${a}`)};return n?.addEventListener("abort",()=>{c()},{once:!0}),{start:async({force:a=!1,path:d})=>{const p=r?.path??o;if(p!==void 0)throw new Error(`Already recording to ${p}`);o=d;try{return await s(d,{force:a})}finally{o=void 0}},stop:async()=>{if(!r)throw new Error("No video recording in progress");const{path:a}=r;return await i(r),{path:a}}}}async function wt(e,t){try{await at(e.readable,t)}catch(n){f(`video capture ended with an error: ${String(n)}`)}}async function vt(){const{config:e,logs:t,store:n}=Fe();f(`recording to ${n.path}`);const{shutdown:r,signal:o}=nt(n);try{const{device:s,transport:i}=await ze(e,n,{onClose:r,signal:o}),c=ht(s,n,{signal:o});await He(s,e,n,{signal:o}),await Ke(i,n,{signal:o});const a=await Ge(i,n,e.sessionId,{recorder:c,signal:o});f(`control socket listening at ${a}`),st(s,t.device,{signal:o}),f(`recording device logs to ${t.device}`),t.network&&(it(s,t.network,{signal:o}),f(`recording network events to ${t.network}`))}catch(s){if(o.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}}vt();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@appetize/cli",
3
- "version": "0.20.0",
3
+ "version": "0.21.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,9 +32,9 @@
32
32
  "debug": "^4.4.3",
33
33
  "human-id": "^4.2.1",
34
34
  "json-rpc-2.0": "^1.8.1",
35
- "mediabunny": "^1.59.0",
35
+ "mediabunny": "^1.60.0",
36
36
  "sade": "^1.8.1",
37
- "ws": "^8.21.3",
37
+ "ws": "^8.22.0",
38
38
  "yocto-spinner": "^1.2.2"
39
39
  }
40
40
  }
@@ -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.20.0'
13
+ cli-version: '0.21.0'
14
14
  ---
15
15
 
16
16
  # Appetize
@@ -95,6 +95,13 @@ appetize swipe --from-text 'Drag me' --to-test-id drop-zone --json
95
95
  A `--direction` swipe scrolls; a `--from-*`/`--to-*` pair drags along a path,
96
96
  naming its ends with the same selectors as `tap`.
97
97
 
98
+ ```bash
99
+ appetize gesture '{byText=Photo}>{wait=800}/' --json
100
+ ```
101
+
102
+ `gesture` covers long-presses, double taps and multi-point drags; run
103
+ `appetize gesture --help` for its syntax.
104
+
98
105
  Prefer `--select-test-id`, then `--select-text` (exact, or `/regex/flags`). A
99
106
  selector survives layout changes; a coordinate (`--select-position 0.5,0.75`)
100
107
  does not, so save those for canvases, maps and sliders.
@@ -49,6 +49,15 @@ for them.
49
49
  Needs no `APPETIZE_API_TOKEN`. `osVersions` are the values
50
50
  `--device-os-version` accepts.
51
51
 
52
+ ## gesture
53
+
54
+ `--help` holds the syntax and examples. Every element is resolved before the
55
+ gesture starts, so a missing one fails without touching the screen; so does a
56
+ syntax error, reporting its position.
57
+
58
+ Android ignores a second tap within 40 ms, and `{wait}` overruns its 300 ms
59
+ double-tap window.
60
+
52
61
  ## inspect
53
62
 
54
63
  Writes `{ platform, root }`, where each node carries `attributes`, `bounds` and
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 nr(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var Ie={exports:{}},ze,wt;function ir(){if(wt)return ze;wt=1;var t=1e3,e=t*60,r=e*60,n=r*24,i=n*7,s=n*365.25;ze=function(w,p){p=p||{};var v=typeof w;if(v==="string"&&w.length>0)return o(w);if(v==="number"&&isFinite(w))return p.long?c(w):y(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 p=/^(-?(?:\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(p){var v=parseFloat(p[1]),f=(p[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 y(w){var p=Math.abs(w);return p>=n?Math.round(w/n)+"d":p>=r?Math.round(w/r)+"h":p>=e?Math.round(w/e)+"m":p>=t?Math.round(w/t)+"s":w+"ms"}function c(w){var p=Math.abs(w);return p>=n?h(w,p,n,"day"):p>=r?h(w,p,r,"hour"):p>=e?h(w,p,e,"minute"):p>=t?h(w,p,t,"second"):w+" ms"}function h(w,p,v,f){var S=p>=v*1.5;return Math.round(w/v)+" "+f+(S?"s":"")}return ze}var Ke,vt;function sr(){if(vt)return Ke;vt=1;function t(e){n.debug=n,n.default=n,n.coerce=h,n.disable=y,n.enable=s,n.enabled=c,n.humanize=ir(),n.destroy=w,Object.keys(e).forEach(p=>{n[p]=e[p]}),n.names=[],n.skips=[],n.formatters={};function r(p){let v=0;for(let f=0;f<p.length;f++)v=(v<<5)-v+p.charCodeAt(f),v|=0;return n.colors[Math.abs(v)%n.colors.length]}n.selectColor=r;function n(p){let v,f=null,S,g;function C(...b){if(!C.enabled)return;const E=C,M=Number(new Date),N=M-(v||M);E.diff=N,E.prev=v,E.curr=M,v=M,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,G)=>{if(q==="%%")return"%";P++;const F=n.formatters[G];if(typeof F=="function"){const V=b[P];q=F.call(E,V),b.splice(P,1),P--}return q}),n.formatArgs.call(E,b),(E.log||n.log).apply(E,b)}return C.namespace=p,C.useColors=n.useColors(),C.color=n.selectColor(p),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(p)),g),set:b=>{f=b}}),typeof n.init=="function"&&n.init(C),C}function i(p,v){const f=n(this.namespace+(typeof v>"u"?":":v)+p);return f.log=this.log,f}function s(p){n.save(p),n.namespaces=p,n.names=[],n.skips=[];const v=(typeof p=="string"?p:"").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(p,v){let f=0,S=0,g=-1,C=0;for(;f<p.length;)if(S<v.length&&(v[S]===p[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 y(){const p=[...n.names,...n.skips.map(v=>"-"+v)].join(",");return n.enable(""),p}function c(p){for(const v of n.skips)if(o(p,v))return!1;for(const v of n.names)if(o(p,v))return!0;return!1}function h(p){return p instanceof Error?p.stack||p.message:p}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 Ke=t,Ke}var gt;function or(){return gt||(gt=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 h="color: "+this.color;c.splice(1,0,h,"color: inherit");let w=0,p=0;c[0].replace(/%[a-zA-Z%]/g,v=>{v!=="%%"&&(w++,v==="%c"&&(p=w))}),c.splice(p,0,h)}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=sr()(e);const{formatters:y}=t.exports;y.j=function(c){try{return JSON.stringify(c)}catch(h){return"[UnexpectedJSONParseError]: "+h.message}}})(Ie,Ie.exports)),Ie.exports}var ar=or(),me=nr(ar),ue={},ie={},Se={},bt;function Ne(){return bt||(bt=1,(function(t){var e=Se&&Se.__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 y=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 y(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 h=function(f,S,g,C){return{jsonrpc:t.JSONRPC,id:f,error:y(S,g,C)}};t.createJSONRPCErrorResponse=h;var w=function(f,S){return{jsonrpc:t.JSONRPC,id:f,result:S??null}};t.createJSONRPCSuccessResponse=w;var p=function(f,S,g){return{jsonrpc:t.JSONRPC,id:f,method:S,params:g}};t.createJSONRPCRequest=p;var v=function(f,S){return{jsonrpc:t.JSONRPC,method:f,params:S}};t.createJSONRPCNotification=v})(Se)),Se}var Ce={},mt;function St(){return mt||(mt=1,Object.defineProperty(Ce,"__esModule",{value:!0}),Ce.DefaultErrorCode=void 0,Ce.DefaultErrorCode=0),Ce}var Ct;function cr(){if(Ct)return ie;Ct=1;var t=ie&&ie.__awaiter||function(o,y,c,h){function w(p){return p instanceof c?p:new c(function(v){v(p)})}return new(c||(c=Promise))(function(p,v){function f(C){try{g(h.next(C))}catch(b){v(b)}}function S(C){try{g(h.throw(C))}catch(b){v(b)}}function g(C){C.done?p(C.value):w(C.value).then(f,S)}g((h=h.apply(o,y||[])).next())})},e=ie&&ie.__generator||function(o,y){var c={label:0,sent:function(){if(p[0]&1)throw p[1];return p[1]},trys:[],ops:[]},h,w,p,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(h)throw new TypeError("Generator is already executing.");for(;v&&(v=0,g[0]&&(c=0)),c;)try{if(h=1,w&&(p=g[0]&2?w.return:g[0]?w.throw||((p=w.return)&&p.call(w),0):w.next)&&!(p=p.call(w,g[1])).done)return p;switch(w=0,p&&(g=[g[0]&2,p.value]),g[0]){case 0:case 1:p=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(p=c.trys,!(p=p.length>0&&p[p.length-1])&&(g[0]===6||g[0]===2)){c=0;continue}if(g[0]===3&&(!p||g[1]>p[0]&&g[1]<p[3])){c.label=g[1];break}if(g[0]===6&&c.label<p[1]){c.label=p[1],p=g;break}if(p&&c.label<p[2]){c.label=p[2],c.ops.push(g);break}p[2]&&c.ops.pop(),c.trys.pop();continue}g=y.call(o,c)}catch(C){g=[6,C],w=0}finally{h=p=0}if(g[0]&5)throw g[1];return{value:g[0]?g[1]:void 0,done:!0}}};Object.defineProperty(ie,"__esModule",{value:!0}),ie.JSONRPCClient=void 0;var r=Ne(),n=St(),i=(function(){function o(y,c){this._send=y,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(y,c){var h=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=h.idToResolveMap.get(g);C&&(h.idToResolveMap.delete(g),C(c(g)))})},y);return f().then(function(g){return clearTimeout(S),g},function(g){return clearTimeout(S),Promise.reject(g)})},p=function(v,f){var S=(Array.isArray(v)?v:[v]).map(function(g){return g.id}).filter(s);return w(S,function(){return h.requestAdvanced(v,f)})};return{request:function(v,f,S){var g=h._createID();return w([g],function(){return h.requestWithID(v,f,S,g)})},requestAdvanced:function(v,f){return p(v,f)}}},o.prototype.request=function(y,c,h){return this.requestWithID(y,c,h,this._createID())},o.prototype.requestWithID=function(y,c,h,w){return t(this,void 0,void 0,function(){var p,v;return e(this,function(f){switch(f.label){case 0:return p=(0,r.createJSONRPCRequest)(w,y,c),[4,this.requestAdvanced(p,h)];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(y,c){var h=this,w=Array.isArray(y);Array.isArray(y)||(y=[y]);var p=y.filter(function(S){return s(S.id)}),v=p.map(function(S){return new Promise(function(g){return h.idToResolveMap.set(S.id,g)})}),f=Promise.all(v).then(function(S){return w||!S.length?S:S[0]});return this.send(w?y:y[0],c).then(function(){return f},function(S){return p.forEach(function(g){h.receive((0,r.createJSONRPCErrorResponse)(g.id,n.DefaultErrorCode,S&&S.message||"Failed to send a request"))}),f})},o.prototype.notify=function(y,c,h){var w=(0,r.createJSONRPCNotification)(y,c);this.send(w,h).then(void 0,function(){})},o.prototype.send=function(y,c){return t(this,void 0,void 0,function(){return e(this,function(h){return[2,this._send(y,c)]})})},o.prototype.rejectAllPendingRequests=function(y){this.idToResolveMap.forEach(function(c,h){return c((0,r.createJSONRPCErrorResponse)(h,n.DefaultErrorCode,y))}),this.idToResolveMap.clear()},o.prototype.receive=function(y){var c=this;Array.isArray(y)||(y=[y]),y.forEach(function(h){var w=c.idToResolveMap.get(h.id);w&&(c.idToResolveMap.delete(h.id),w(h))})},o})();ie.JSONRPCClient=i;var s=function(o){return o!=null};return ie}var Ve={},Et;function lr(){return Et||(Et=1,Object.defineProperty(Ve,"__esModule",{value:!0})),Ve}var se={},Rt;function ur(){return Rt||(Rt=1,(function(t){var e=se&&se.__awaiter||function(C,b,E,M){function N(P){return P instanceof E?P:new E(function(D){D(P)})}return new(E||(E=Promise))(function(P,D){function q(V){try{F(M.next(V))}catch(we){D(we)}}function G(V){try{F(M.throw(V))}catch(we){D(we)}}function F(V){V.done?P(V.value):N(V.value).then(q,G)}F((M=M.apply(C,b||[])).next())})},r=se&&se.__generator||function(C,b){var E={label:0,sent:function(){if(P[0]&1)throw P[1];return P[1]},trys:[],ops:[]},M,N,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(F){return function(V){return G([F,V])}}function G(F){if(M)throw new TypeError("Generator is already executing.");for(;D&&(D=0,F[0]&&(E=0)),E;)try{if(M=1,N&&(P=F[0]&2?N.return:F[0]?N.throw||((P=N.return)&&P.call(N),0):N.next)&&!(P=P.call(N,F[1])).done)return P;switch(N=0,P&&(F=[F[0]&2,P.value]),F[0]){case 0:case 1:P=F;break;case 4:return E.label++,{value:F[1],done:!1};case 5:E.label++,N=F[1],F=[0];continue;case 7:F=E.ops.pop(),E.trys.pop();continue;default:if(P=E.trys,!(P=P.length>0&&P[P.length-1])&&(F[0]===6||F[0]===2)){E=0;continue}if(F[0]===3&&(!P||F[1]>P[0]&&F[1]<P[3])){E.label=F[1];break}if(F[0]===6&&E.label<P[1]){E.label=P[1],P=F;break}if(P&&E.label<P[2]){E.label=P[2],E.ops.push(F);break}P[2]&&E.ops.pop(),E.trys.pop();continue}F=b.call(C,E)}catch(V){F=[6,V],N=0}finally{M=P=0}if(F[0]&5)throw F[1];return{value:F[0]?F[1]:void 0,done:!0}}},n=se&&se.__spreadArray||function(C,b,E){if(E||arguments.length===2)for(var M=0,N=b.length,P;M<N;M++)(P||!(M in b))&&(P||(P=Array.prototype.slice.call(b,0,M)),P[M]=b[M]);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=Ne(),s=St(),o=function(){return(0,i.createJSONRPCErrorResponse)(null,i.JSONRPCErrorCode.ParseError,"Parse error")},y=function(C){return(0,i.createJSONRPCErrorResponse)((0,i.isJSONRPCID)(C.id)?C.id:null,i.JSONRPCErrorCode.InvalidRequest,"Invalid Request")};t.createInvalidRequestResponse=y;var c=function(C){return(0,i.createJSONRPCErrorResponse)(C,i.JSONRPCErrorCode.MethodNotFound,"Method not found")};t.createMethodNotFoundResponse=c;var h=(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,M){var N=b(E.params,M);return Promise.resolve(N).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 M=this.tryParseRequestJSON(b);return M?this.receive(M,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 M,N=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 N.receiveSingle(D,E)}))];case 1:return M=P.sent().filter(w),M.length===1?[2,M[0]]:M.length?[2,M]:[2,null]}})})},C.prototype.receiveSingle=function(b,E){return e(this,void 0,void 0,function(){var M,N;return r(this,function(P){switch(P.label){case 0:return M=this.nameToMethodMap.get(b.method),(0,i.isJSONRPCRequest)(b)?[3,1]:[2,(0,t.createInvalidRequestResponse)(b)];case 1:return[4,this.callMethod(M,b,E)];case 2:return N=P.sent(),[2,g(b,N)]}})})},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(M,N,P){return b(function(D,q){return E(M,D,q)},N,P)}},C.prototype.callMethod=function(b,E,M){var N=this,P=function(q,G){return b?b(q,G):N.handleMethodNotFound(q,G)},D=function(q){return N.errorListener('An unexpected error occurred while executing "'.concat(E.method,'" JSON-RPC method:'),q),Promise.resolve(N.mapErrorToJSONRPCErrorResponseIfNecessary(E.id,q))};try{return(this.middleware||p)(P,E,M).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=h;var w=function(C){return C!==null},p=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,M=(E=b?.message)!==null&&E!==void 0?E:"An unexpected error occurred",N=s.DefaultErrorCode,P;return b instanceof i.JSONRPCErrorException&&(N=b.code,P=b.data),(0,i.createJSONRPCErrorResponse)(C,N,M,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)}})(se)),se}var oe={},Ot;function fr(){if(Ot)return oe;Ot=1;var t=oe&&oe.__awaiter||function(i,s,o,y){function c(h){return h instanceof o?h:new o(function(w){w(h)})}return new(o||(o=Promise))(function(h,w){function p(S){try{f(y.next(S))}catch(g){w(g)}}function v(S){try{f(y.throw(S))}catch(g){w(g)}}function f(S){S.done?h(S.value):c(S.value).then(p,v)}f((y=y.apply(i,s||[])).next())})},e=oe&&oe.__generator||function(i,s){var o={label:0,sent:function(){if(h[0]&1)throw h[1];return h[1]},trys:[],ops:[]},y,c,h,w;return w={next:p(0),throw:p(1),return:p(2)},typeof Symbol=="function"&&(w[Symbol.iterator]=function(){return this}),w;function p(f){return function(S){return v([f,S])}}function v(f){if(y)throw new TypeError("Generator is already executing.");for(;w&&(w=0,f[0]&&(o=0)),o;)try{if(y=1,c&&(h=f[0]&2?c.return:f[0]?c.throw||((h=c.return)&&h.call(c),0):c.next)&&!(h=h.call(c,f[1])).done)return h;switch(c=0,h&&(f=[f[0]&2,h.value]),f[0]){case 0:case 1:h=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(h=o.trys,!(h=h.length>0&&h[h.length-1])&&(f[0]===6||f[0]===2)){o=0;continue}if(f[0]===3&&(!h||f[1]>h[0]&&f[1]<h[3])){o.label=f[1];break}if(f[0]===6&&o.label<h[1]){o.label=h[1],h=f;break}if(h&&o.label<h[2]){o.label=h[2],o.ops.push(f);break}h[2]&&o.ops.pop(),o.trys.pop();continue}f=s.call(i,o)}catch(S){f=[6,S],c=0}finally{y=h=0}if(f[0]&5)throw f[1];return{value:f[0]?f[1]:void 0,done:!0}}};Object.defineProperty(oe,"__esModule",{value:!0}),oe.JSONRPCServerAndClient=void 0;var r=Ne(),n=(function(){function i(s,o,y){y===void 0&&(y={});var c;this.server=s,this.client=o,this.errorListener=(c=y.errorListener)!==null&&c!==void 0?c:console.warn}return i.prototype.applyServerMiddleware=function(){for(var s,o=[],y=0;y<arguments.length;y++)o[y]=arguments[y];(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,y){return this.client.request(s,o,y)},i.prototype.requestAdvanced=function(s,o){return this.client.requestAdvanced(s,o)},i.prototype.notify=function(s,o,y){this.client.notify(s,o,y)},i.prototype.rejectAllPendingRequests=function(s){this.client.rejectAllPendingRequests(s)},i.prototype.receiveAndSend=function(s,o,y){return t(this,void 0,void 0,function(){var c,h;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,y)]:[3,4];case 3:return h="Received an invalid JSON-RPC message",this.errorListener(h,s),[2,Promise.reject(new Error(h))];case 4:return[2]}})})},i})();return oe.JSONRPCServerAndClient=n,oe}var Mt;function dr(){return Mt||(Mt=1,(function(t){var e=ue&&ue.__createBinding||(Object.create?(function(n,i,s,o){o===void 0&&(o=s);var y=Object.getOwnPropertyDescriptor(i,s);(!y||("get"in y?!i.__esModule:y.writable||y.configurable))&&(y={enumerable:!0,get:function(){return i[s]}}),Object.defineProperty(n,o,y)}):(function(n,i,s,o){o===void 0&&(o=s),n[o]=i[s]})),r=ue&&ue.__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(cr(),t),r(lr(),t),r(Ne(),t),r(ur(),t),r(fr(),t)})(ue)),ue}var ke=dr();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 pr(t,e){const r="CloseEvent"in globalThis?globalThis.CloseEvent:hr;return new r(t,e)}class yr{#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 wr extends yr{send;constructor(e){super(),this.send=e}dispatchClose(e){return this.dispatchEvent(pr("close",e))}dispatchMessage(e){return this.dispatchEvent(new CustomEvent("message",{detail:e}))}}const At=me("appetize.io:error:rpc");function We(t,e){const r=new ke.JSONRPCServerAndClient(new ke.JSONRPCServer({errorListener:At}),gr(t),{errorListener:At}),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 vr(t,e){const{rpc:r,unsub:n}=We(t,e);return{client:r.client,unsub:n}}function _e(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 gr(t){return new ke.JSONRPCClient(t[j].send.bind(t[j]),()=>Math.floor(Math.random()*Number.MAX_SAFE_INTEGER)+1)}const br=(...t)=>vr(...t),$e=["ArrowDown","ArrowLeft","ArrowRight","ArrowUp","Backspace","Enter","Tab"],mr=33333,Sr=[[99,10],[396,11],[792,21],[1620,22],[3600,31],[5120,32],[8192,40],[8704,42],[22080,50],[36864,51],[139264,60]],Cr=new Intl.Segmenter(void 0,{granularity:"grapheme"}),Er=new Set($e);class Rr{#e;#r=!1;#t;#n;#i;#s;#o;#a;#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.#s=n,this.#o=i,this.#a=s,this.#c=o,this.#a?.addEventListener("abort",this.close,{once:!0}),this.#p()}close=()=>{this.#r||(this.#r=!0,this.#f(),this.#n=void 0,this.#c.close(),this.#a?.removeEventListener("abort",this.close),this.#s?.())};#f(){this.#n&&this.#n.state!=="closed"&&this.#n.close()}#h(e){const r=Pr(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+=mr}}}}catch(e){this.#r||this.#o?.(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 Or(t,e,{signal:r}={}){if(r?.aborted)return()=>{};const n=s=>{s.altKey||s.ctrlKey||s.metaKey||!Ir(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 Mr(t,e,{signal:r}={}){let n,i;const s=h=>{n===void 0&&(h.preventDefault(),n=h.pointerId,i=He(e,h),e.focus(),e.setPointerCapture(h.pointerId),t.touch.down(i.x,i.y))},o=h=>{h.pointerId===n&&(h.preventDefault(),i=He(e,h),t.touch.move(i.x,i.y))},y=h=>{if(h.pointerId!==n)return;h.preventDefault();const w=He(e,h);t.touch.up(w.x,w.y),It(e,h.pointerId),n=void 0,i=void 0},c=()=>{n!==void 0&&It(e,n),i&&t.touch.up(i.x,i.y),n=void 0,i=void 0,e.removeEventListener("pointercancel",y),e.removeEventListener("pointerdown",s),e.removeEventListener("pointermove",o),e.removeEventListener("pointerup",y),r?.removeEventListener("abort",c)};return r?.aborted||(e.addEventListener("pointercancel",y),e.addEventListener("pointerdown",s),e.addEventListener("pointermove",o),e.addEventListener("pointerup",y),r?.addEventListener("abort",c,{once:!0})),c}async function Ar(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 Rr({canvas:e,context:s,onClose:r,onError:n,signal:i,stream:o}).close}}function Pt(t){return Math.max(0,Math.min(1,t))}function Pr(t,e,r){const n=Math.ceil(e/16)*Math.ceil(r/16),i=Sr.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,y=t[s]===0&&t[s+1]===0&&t[s+2]===0&&t[s+3]===1,c=o?s+3:y?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(h=>h.toString(16).padStart(2,"0")).join("")}`}return"avc1.42e01e"}function Ir(t){return Array.from(Cr.segment(t)).length===1||Er.has(t)}function He(t,e){const r=t.getBoundingClientRect();return{x:Pt((e.clientX-r.left)/r.width),y:Pt((e.clientY-r.top)/r.height)}}function It(t,e){t.hasPointerCapture(e)&&t.releasePointerCapture(e)}let Ge;try{Ge=new TextDecoder}catch{}let A,X,d=0;const Nr=105,kr=57342,_r=57343,Nt=57337,kt=6,ve={};let Ee=11281e4,ae=1681e4,T={},z,Fe,Le=0,Re=0,W,ee,K=[],Ze=[],Y,Z,Oe,_t={useRecords:!1,mapsAsObjects:!0},Me=!1,Ft=2;try{new Function("")}catch{Ft=1/0}class Pe{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[te(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(A)return Dt(()=>(tt(),this?this.decode(e,r):Pe.prototype.decode.call(_t,e,r)));X=r>-1?r:e.length,d=0,Re=0,Fe=null,W=null,A=e;try{Z=e.dataView||(e.dataView=new DataView(e.buffer,e.byteOffset,e.byteLength))}catch(n){throw A=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 Pe){if(T=this,Y=this.sharedValues&&(this.pack?new Array(this.maxPrivatePackedValues||16).concat(this.sharedValues):this.sharedValues),this.structures)return z=this.structures,xe();(!z||z.length>0)&&(z=[])}else T=_t,(!z||z.length>0)&&(z=[]),Y=null;return xe()}decodeMultiple(e,r){let n,i=0;try{let s=e.length;Me=!0;let o=this?this.decode(e,s):nt.decode(e,s);if(r){if(r(o)===!1)return;for(;d<s;)if(i=d,r(xe())===!1)return}else{for(n=[o];d<s;)i=d,n.push(xe());return n}}catch(s){throw s.lastPosition=i,s.values=n,s}finally{Me=!1,tt()}}}function xe(){try{let t=U();if(W){if(d>=W.postBundlePosition){let e=new Error("Unexpected bundle position");throw e.incomplete=!0,e}d=W.postBundlePosition,W=null}if(d==X)z=null,A=null,ee&&(ee=null);else if(d>X){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 tt(),(t instanceof RangeError||t.message.startsWith("Unexpected end of buffer"))&&(t.incomplete=!0),t}}function fe(){let t=new Error("Unexpected end of CBOR data");return t.incomplete=!0,t}function U(){if(!(d<X))throw fe();let t=A[d++],e=t>>5;if(t=t&31,t>23)switch(t){case 24:if(d>=X)throw fe();t=A[d++];break;case 25:if(e==7)return Tr();t=Z.getUint16(d),d+=2;break;case 26:if(e==7){let r=Z.getFloat32(d);if(T.useFloat32>2){let n=rt[(A[d]&127)<<1|A[d+1]>>7];return d+=4,(n*r+(r>0?.5:-.5)>>0)/n}return d+=4,r}if(t=Z.getUint32(d),d+=4,e===1)return-1-t;break;case 27:if(e==7){let r=Z.getFloat64(d);return d+=8,r}if(e>1){if(Z.getUint32(d)>0)throw new Error("JavaScript does not support arrays, maps, or strings with length over 4294967295");t=Z.getUint32(d+4)}else T.int64AsNumber?(t=Z.getUint32(d)*4294967296,t+=Z.getUint32(d+4)):t=Z.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())!=ve;){if(i>=Ee)throw new Error(`Array length exceeds ${Ee}`);r[i++]=n}return e==4?r:e==3?r.join(""):Buffer.concat(r);case 5:let s;if(T.mapsAsObjects){let o={},y=0;if(T.keyMap)for(;(s=U())!=ve;){if(y++>=ae)throw new Error(`Property count exceeds ${ae}`);o[te(T.decodeKey(s))]=U()}else for(;(s=U())!=ve;){if(y++>=ae)throw new Error(`Property count exceeds ${ae}`);o[te(s)]=U()}return o}else{Oe&&(T.mapsAsObjects=!0,Oe=!1);let o=new Map;if(T.keyMap){let y=0;for(;(s=U())!=ve;){if(y++>=ae)throw new Error(`Map size exceeds ${ae}`);o.set(T.decodeKey(s),U())}}else{let y=0;for(;(s=U())!=ve;){if(y++>=ae)throw new Error(`Map size exceeds ${ae}`);o.set(s,U())}}return o}case 7:return ve;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 xr(t);case 3:if(Re>=d)return Fe.slice(d-Le,(d+=t)-Le);if(Re==0&&X<140&&t<32){let i=t<16?xt(t):Lr(t);if(i!=null)return i}return Fr(t);case 4:if(t>=Ee)throw new Error(`Array length exceeds ${Ee}`);if(t>X-d)throw fe();let r=new Array(t);for(let i=0;i<t;i++)r[i]=U();return r;case 5:if(t>=ae)throw new Error(`Map size exceeds ${Ee}`);if(t>(X-d)/2)throw fe();if(T.mapsAsObjects){let i={};if(T.keyMap)for(let s=0;s<t;s++)i[te(T.decodeKey(U()))]=U();else for(let s=0;s<t;s++)i[te(U())]=U();return i}else{Oe&&(T.mapsAsObjects=!0,Oe=!1);let i=new Map;if(T.keyMap)for(let s=0;s<t;s++)i.set(T.decodeKey(U()),U());else for(let s=0;s<t;s++)i.set(U(),U());return i}case 6:if(t>=Nt){let i=z[t&8191];if(i)return i.read||(i.read=Ye(i)),i.read();if(t<65536){if(t==_r){let s=be(),o=U(),y=U();Qe(o,y);let c={};if(T.keyMap)for(let h=2;h<s;h++){let w=T.decodeKey(y[h-2]);c[te(w)]=U()}else for(let h=2;h<s;h++){let w=y[h-2];c[te(w)]=U()}return c}else if(t==kr){let s=be(),o=U();for(let y=2;y<s;y++)Qe(o++,U());return U()}else if(t==Nt)return qr();if(T.getShared&&(et(),i=z[t&8191],i))return i.read||(i.read=Ye(i)),i.read()}}let n=K[t];if(n)return n.handlesRead?n(U):n(U());{let i=U();for(let s=0;s<Ze.length;s++){let o=Ze[s](t,i);if(o!==void 0)return o}return new de(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||he())[t];if(i!==void 0)return i;throw new Error("Unknown token "+t)}default:throw isNaN(t)?fe():new Error("Unknown CBOR token "+t)}}const Lt=/^[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=A[d++];if(r=r&31,r>23)switch(r){case 24:r=A[d++];break;case 25:r=Z.getUint16(d),d+=2;break;case 26:r=Z.getUint32(d),d+=4;break;default:throw new Error("Expected array header, but got "+A[d-1])}let n=this.compiledReader;for(;n;){if(n.propertyCount===r)return n(U);n=n.next}if(this.slowReads++>=Ft){let s=this.length==r?this:this.slice(0,r);return n=T.keyMap?new Function("r","return {"+s.map(o=>T.decodeKey(o)).map(o=>Lt.test(o)?te(o)+":r()":"["+JSON.stringify(o)+"]:r()").join(",")+"}"):new Function("r","return {"+s.map(o=>Lt.test(o)?te(o)+":r()":"["+JSON.stringify(o)+"]:r()").join(",")+"}"),this.compiledReader&&(n.next=this.compiledReader),n.propertyCount=r,this.compiledReader=n,n(U)}let i={};if(T.keyMap)for(let s=0;s<r;s++)i[te(T.decodeKey(this[s]))]=U();else for(let s=0;s<r;s++)i[te(this[s])]=U();return i}return t.slowReads=0,e}function te(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 Fr=Xe;function Xe(t){let e;if(t<16&&(e=xt(t)))return e;if(t>64&&Ge)return Ge.decode(A.subarray(d,d+=t));const r=d+t,n=[];for(e="";d<r;){const i=A[d++];if((i&128)===0)n.push(i);else if((i&224)===192)if(i<194||d>=r||(A[d]&192)!==128)n.push(65533);else{const s=A[d++]&63;n.push((i&31)<<6|s)}else if((i&240)===224){const s=d<r?A[d]:0;if(d>=r||(s&192)!==128||i===224&&s<160||i===237&&s>=160)n.push(65533);else if(d++,d>=r||(A[d]&192)!==128)n.push(65533);else{const o=A[d++]&63;n.push((i&31)<<12|(s&63)<<6|o)}}else if((i&248)===240){const s=d<r?A[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||(A[d]&192)!==128)n.push(65533);else{const o=A[d++]&63;if(d>=r||(A[d]&192)!==128)n.push(65533);else{const y=A[d++]&63;let c=(i&7)<<18|(s&63)<<12|o<<6|y;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 Lr(t){let e=d,r=new Array(t);for(let n=0;n<t;n++){const i=A[d++];if((i&128)>0){d=e;return}r[n]=i}return H.apply(String,r)}function xt(t){if(t<4)if(t<2){if(t===0)return"";{let e=A[d++];if((e&128)>1){d-=1;return}return H(e)}}else{let e=A[d++],r=A[d++];if((e&128)>0||(r&128)>0){d-=2;return}if(t<3)return H(e,r);let n=A[d++];if((n&128)>0){d-=3;return}return H(e,r,n)}else{let e=A[d++],r=A[d++],n=A[d++],i=A[d++];if((e&128)>0||(r&128)>0||(n&128)>0||(i&128)>0){d-=4;return}if(t<6){if(t===4)return H(e,r,n,i);{let s=A[d++];if((s&128)>0){d-=5;return}return H(e,r,n,i,s)}}else if(t<8){let s=A[d++],o=A[d++];if((s&128)>0||(o&128)>0){d-=6;return}if(t<7)return H(e,r,n,i,s,o);let y=A[d++];if((y&128)>0){d-=7;return}return H(e,r,n,i,s,o,y)}else{let s=A[d++],o=A[d++],y=A[d++],c=A[d++];if((s&128)>0||(o&128)>0||(y&128)>0||(c&128)>0){d-=8;return}if(t<10){if(t===8)return H(e,r,n,i,s,o,y,c);{let h=A[d++];if((h&128)>0){d-=9;return}return H(e,r,n,i,s,o,y,c,h)}}else if(t<12){let h=A[d++],w=A[d++];if((h&128)>0||(w&128)>0){d-=10;return}if(t<11)return H(e,r,n,i,s,o,y,c,h,w);let p=A[d++];if((p&128)>0){d-=11;return}return H(e,r,n,i,s,o,y,c,h,w,p)}else{let h=A[d++],w=A[d++],p=A[d++],v=A[d++];if((h&128)>0||(w&128)>0||(p&128)>0||(v&128)>0){d-=12;return}if(t<14){if(t===12)return H(e,r,n,i,s,o,y,c,h,w,p,v);{let f=A[d++];if((f&128)>0){d-=13;return}return H(e,r,n,i,s,o,y,c,h,w,p,v,f)}}else{let f=A[d++],S=A[d++];if((f&128)>0||(S&128)>0){d-=14;return}if(t<15)return H(e,r,n,i,s,o,y,c,h,w,p,v,f,S);let g=A[d++];if((g&128)>0){d-=15;return}return H(e,r,n,i,s,o,y,c,h,w,p,v,f,S,g)}}}}}function xr(t){return T.copyBuffers?Uint8Array.prototype.slice.call(A,d,d+=t):A.subarray(d,d+=t)}let Tt=new Float32Array(1),Te=new Uint8Array(Tt.buffer,0,4);function Tr(){let t=A[d++],e=A[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 Te[3]=t&128|(r>>1)+56,Te[2]=(t&7)<<5|e>>3,Te[1]=e<<5,Te[0]=0,Tt[0]}new Array(4096);class de{constructor(e,r){this.value=e,this.tag=r}}K[0]=t=>new Date(t),K[1]=t=>new Date(Math.round(t*1e3)),K[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},K[3]=t=>BigInt(-1)-K[2](t),K[4]=t=>+(t[1]+"e"+t[0]),K[5]=t=>t[1]*Math.exp(t[0]*Math.log(2));const Qe=(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)};K[Nr]=t=>{let e=t.length,r=t[1];Qe(t[0],r);let n={};for(let i=2;i<e;i++){let s=r[i-2];n[te(s)]=t[i]}return n},K[14]=t=>W?W[0].slice(W.position0,W.position0+=t):new de(t,14),K[15]=t=>W?W[1].slice(W.position1,W.position1+=t):new de(t,15);let Ur={Error,RegExp};K[27]=t=>(Ur[t[0]]||Error)(t[1],t[2]);const Ut=t=>{if(A[d++]!=132){let r=new Error("Packed values structure must be followed by a 4 element array");throw A.length<d&&(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()};Ut.handlesRead=!0,K[51]=Ut,K[kt]=t=>{if(!Y)if(T.getShared)et();else return new de(t,kt);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},K[28]=t=>{ee||(ee=new Map,ee.id=0);let e=ee.id++,r=d,n=A[d],i;n>>5==4?i=[]:i={};let s={target:i};ee.set(e,s);let o=t();return s.used?(Object.getPrototypeOf(i)!==Object.getPrototypeOf(o)&&(d=r,i=o,ee.set(e,{target:i}),o=t()),Object.assign(i,o)):(s.target=o,o)},K[28].handlesRead=!0,K[29]=t=>{let e=ee.get(t);return e.used=!0,e.target},K[258]=t=>new Set(t),(K[259]=t=>(T.mapsAsObjects&&(T.mapsAsObjects=!1,Oe=!0),t())).handlesRead=!0;function ge(t,e){return typeof t=="string"?t+e:t instanceof Array?t.concat(e):Object.assign({},t,e)}function he(){if(!Y)if(T.getShared)et();else throw new Error("No packed values available");return Y}const Jr=1399353956;Ze.push((t,e)=>{if(t>=225&&t<=255)return ge(he().prefixes[t-224],e);if(t>=28704&&t<=32767)return ge(he().prefixes[t-28672],e);if(t>=1879052288&&t<=2147483647)return ge(he().prefixes[t-1879048192],e);if(t>=216&&t<=223)return ge(e,he().suffixes[t-216]);if(t>=27647&&t<=28671)return ge(e,he().suffixes[t-27639]);if(t>=1811940352&&t<=1879048191)return ge(e,he().suffixes[t-1811939328]);if(t==Jr)return{packedValues:Y,structures:z.slice(0),version:e};if(t==55799)return e});const Dr=new Uint8Array(new Uint16Array([1]).buffer)[0]==1,Jt=[Uint8Array,Uint8ClampedArray,Uint16Array,Uint32Array,typeof BigUint64Array>"u"?{name:"BigUint64Array"}:BigUint64Array,Int8Array,Int16Array,Int32Array,typeof BigInt64Array>"u"?{name:"BigInt64Array"}:BigInt64Array,Float32Array,Float64Array],jr=[64,68,69,70,71,72,77,78,79,85,86];for(let t=0;t<Jt.length;t++)Br(Jt[t],jr[t]);function Br(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;K[i?e:e-4]=n==1||i==Dr?o=>{if(!t)throw new Error("Could not find typed array for code "+e);return!T.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 y=new DataView(o.buffer,o.byteOffset,o.byteLength),c=o.length>>s,h=new t(c),w=y[r];for(let p=0;p<c;p++)h[p]=w.call(y,p<<s,i);return h}}}function qr(){let t=be(),e=d+U();for(let n=2;n<t;n++){let i=be();d+=i}let r=d;return d=e,W=[Xe(be()),Xe(be())],W.position0=0,W.position1=0,W.postBundlePosition=d,d=r,U()}function be(){if(!(d<X))throw fe();let t=A[d++]&31;if(t>23)switch(t){case 24:if(d>=X)throw fe();t=A[d++];break;case 25:t=Z.getUint16(d),d+=2;break;case 26:t=Z.getUint32(d),d+=4;break}return t}function et(){if(T.getShared){let t=Dt(()=>(A=null,T.getShared()))||{},e=t.structures||[];T.sharedVersion=t.version,Y=T.sharedValues=t.packedValues,z===!0?T.structures=z=e:z.splice.apply(z,[0,e.length].concat(e))}}function Dt(t){let e=X,r=d,n=Le,i=Re,s=Fe,o=ee,y=W,c=new Uint8Array(A.slice(0,X)),h=z,w=T,p=Me,v=t();return X=e,d=r,Le=n,Re=i,Fe=s,ee=o,W=y,A=c,Me=p,z=h,T=w,Z=new DataView(A.buffer,A.byteOffset,A.byteLength),v}function tt(){A=null,ee=null,z=null}const rt=new Array(147);for(let t=0;t<256;t++)rt[t]=+("1e"+Math.floor(45.15-t*.30103));let nt=new Pe({useRecords:!1});const jt=nt.decode;nt.decodeMultiple;let Ue;try{Ue=new TextEncoder}catch{}let it,Bt;const Je=typeof globalThis=="object"&&globalThis.Buffer,Ae=typeof Je<"u",st=Ae?Je.allocUnsafeSlow:Uint8Array,qt=Ae?Je:Uint8Array,zt=256,Kt=Ae?4294967296:2144337920;let ot,u,B,a=0,le,$=null;const zr=61440,Kr=/[\u0080-\uFFFF]/,Q=Symbol("record-id");class Vr extends Pe{constructor(e){super(e),this.offset=0;let r,n,i,s,o;e=e||{};let y=qt.prototype.utf8Write?function(l,I){return u.utf8Write(l,I,u.byteLength-I)}:Ue&&Ue.encodeInto?function(l,I){return Ue.encodeInto(l,u.subarray(I)).written}:!1,c=this,h=e.structures||e.saveStructures,w=e.maxSharedStructures;if(w==null&&(w=h?128:0),w>8190)throw new Error("Maximum maxSharedStructure is 8190");let p=e.sequential;p&&(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 st(8192),B=new DataView(u.buffer,0,8192),a=0),le=u.length-10,le-a<2048?(u=new st(u.length),B=new DataView(u.buffer,0,u.length),le=u.length-10,a=0):I===Ht&&(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"?($=[],$.size=1/0):$=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 k=0,_=m.length;k<_;k++)g[m[k]]=k}}let R=n.length;if(R>w&&!p&&(R=w),!n.transitions){n.transitions=Object.create(null);for(let O=0;O<R;O++){let m=n[O];if(!m)continue;let k,_=n.transitions;for(let L=0,x=m.length;L<x;L++){_[Q]===void 0&&(_[Q]=O);let J=m[L];k=_[J],k||(k=_[J]=Object.create(null)),_=k}_[Q]=O|1048576}}p||(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,De(l,R),R.values.length>0){u[a++]=216,u[a++]=51,re(4);let O=R.values;M(O),re(0),re(0),f=Object.create(g||null);for(let m=0,k=O.length;m<k;m++)f[O[m]]=m}}ot=I&ut;try{if(ot)return;if(M(l),$&&$t(r,M),c.offset=a,o&&o.idsToInsert){a+=o.idsToInsert.length*2,a>le&&P(a),c.offset=a;let R=Hr(u.subarray(r,a),o.idsToInsert);return o=null,R}return I&Ht?(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&&!p){for(let R=0,O=C.length;R<O;R++)C[R][Q]=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&Zr&&(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 M=l=>{a>le&&(u=P(a));var I=typeof l,R;if(I==="string"){if(f){let _=f[l];if(_>=0){_<16?u[a++]=_+224:(u[a++]=198,_&1?M(15-_>>1):M(_-16>>1));return}else if(v&&!e.pack){let L=v.get(l);L?L.count++:v.set(l,{count:1})}}let O=l.length;if($&&O>=4&&O<1024){if(($.size+=O)>zr){let L,x=($[0]?$[0].length*3+$[1].length:0)+10;a+x>le&&(u=P(a+x)),u[a++]=217,u[a++]=223,u[a++]=249,u[a++]=$.position?132:130,u[a++]=26,L=a-r,a+=4,$.position&&$t(r,M),$=["",""],$.size=0,$.position=L}let _=Kr.test(l);$[_?0:1]+=l,u[a++]=_?206:207,M(O);return}let m;O<32?m=1:O<256?m=2:O<65536?m=3:m=5;let k=O*3;if(a+k>le&&(u=P(a+k)),O<64||!y){let _,L,x,J=a+m;for(_=0;_<O;_++)L=l.charCodeAt(_),L<128?u[J++]=L:L<2048?(u[J++]=L>>6|192,u[J++]=L&63|128):(L&64512)===55296&&((x=l.charCodeAt(_+1))&64512)===56320?(L=65536+((L&1023)<<10)+(x&1023),_++,u[J++]=L>>18|240,u[J++]=L>>12&63|128,u[J++]=L>>6&63|128,u[J++]=L&63|128):(u[J++]=L>>12|224,u[J++]=L>>6&63|128,u[J++]=L&63|128);R=J-a-m}else R=y(l,a+m,k);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*rt[(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 k=o.idsToInsert||(o.idsToInsert=[]);m.references=[],k.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]])])),N(l);else if(O===Array){R=l.length,R<24?u[a++]=128|R:re(R);for(let m=0;m<R;m++)M(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,k]of l)M(c.encodeKey(m)),M(k);else for(let[m,k]of l)M(m),M(k);else{for(let m=0,k=it.length;m<k;m++){let _=Bt[m];if(l instanceof _){let L=it[m],x=L.tag;x==null&&(x=L.getTag&&L.getTag.call(this,l)),x<24?u[a++]=192|x:x<256?(u[a++]=216,u[a++]=x):x<65536?(u[a++]=217,u[a++]=x>>8,u[a++]=x&255):x>-1&&(u[a++]=218,B.setUint32(a,x),a+=4),L.encode.call(this,l,M,P);return}}if(l[Symbol.iterator]){if(ot){let m=new Error("Iterable should be serialized as iterator");throw m.iteratorNotHandled=!0,m}u[a++]=159;for(let m of l)M(m);u[a++]=255;return}if(l[Symbol.asyncIterator]||at(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 M(m)}N(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);ct(new Uint8Array(O.reverse()),P);return}a+=8}else if(I==="undefined")u[a++]=247;else throw new Error("Unknown type: "+I)},N=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++)M(c.encodeKey(I[m])),M(R[m]);else for(let m=0;m<O;m++)M(I[m]),M(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))&&(M(c.encodeKey(O)),M(l[O]),R++);else for(let O in l)(typeof l.hasOwnProperty!="function"||l.hasOwnProperty(O))&&(M(O),M(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,k=0,_,L;if(this.keyMap){L=Object.keys(l).map(J=>this.encodeKey(J)),k=L.length;for(let J=0;J<k;J++){let yt=L[J];R=O[yt],R||(R=O[yt]=Object.create(null),m++),O=R}}else for(let J in l)(typeof l.hasOwnProperty!="function"||l.hasOwnProperty(J))&&(R=O[J],R||(O[Q]&1048576&&(_=O[Q]&65535),R=O[J]=Object.create(null),m++),O=R,k++);let x=O[Q];if(x!==void 0)x&=65535,u[a++]=217,u[a++]=x>>8|224,u[a++]=x&255;else if(L||(L=O.__keys__||(O.__keys__=Object.keys(l))),_===void 0?(x=s.nextId++,x||(x=0,s.nextId=1),x>=zt&&(s.nextId=(x=w)+1)):x=_,s[x]=L,x<w){u[a++]=217,u[a++]=x>>8|224,u[a++]=x&255,O=s.transitions;for(let J=0;J<k;J++)(O[Q]===void 0||O[Q]&1048576)&&(O[Q]=x),O=O[L[J]];O[Q]=x|1048576,i=!0}else{if(O[Q]=x,B.setUint32(a,3655335680),a+=3,m&&(b+=E*m),C.length>=zt-w&&(C.shift()[Q]=void 0),C.push(O),re(k+2),M(57344+x),M(L),I)return;for(let J in l)(typeof l.hasOwnProperty!="function"||l.hasOwnProperty(J))&&M(l[J]);return}if(k<24?u[a++]=128|k:re(k),!I)for(let J in l)(typeof l.hasOwnProperty!="function"||l.hasOwnProperty(J))&&M(l[J])},P=l=>{let I;if(l>16777216){if(l-r>Kt)throw new Error("Encoded buffer would be larger than maximum buffer size");I=Math.min(Kt,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 st(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,le=R.length-10,u=R};let D=100,q=1e3;this.encodeAsIterable=function(l,I){return we(l,I,G)},this.encodeAsAsyncIterable=function(l,I){return we(l,I,pt)};function*G(l,I,R){let O=l.constructor;if(O===Object){let m=c.useRecords!==!1;m?N(l,!0):Vt(Object.keys(l).length,160);for(let k in l){let _=l[k];m||M(k),_&&typeof _=="object"?I[k]?yield*G(_,I[k]):yield*F(_,I,k):M(_)}}else if(O===Array){let m=l.length;re(m);for(let k=0;k<m;k++){let _=l[k];_&&(typeof _=="object"||a-r>D)?I.element?yield*G(_,I.element):yield*F(_,I,"element"):M(_)}}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*G(m,I.element):yield*F(m,I,"element"):M(m);u[a++]=255}else at(l)?(Vt(l.size,64),yield u.subarray(r,a),yield l,V()):l[Symbol.asyncIterator]?(u[a++]=159,yield u.subarray(r,a),yield l,V(),u[a++]=255):M(l);R&&a>r?yield u.subarray(r,a):a-r>D&&(yield u.subarray(r,a),V())}function*F(l,I,R){let O=a-r;try{M(l),a-r>D&&(yield u.subarray(r,a),V())}catch(m){if(m.iteratorNotHandled)I[R]={},a=r+O,yield*G.call(this,l,I[R]);else throw m}}function V(){D=q,c.encode(null,ut)}function we(l,I,R){return I&&I.chunkThreshold?D=q=I.chunkThreshold:D=100,l&&typeof l=="object"?(c.encode(null,ut),R(l,c.iterateProperties||(c.iterateProperties={}),!0)):[c.encode(l)]}async function*pt(l,I){for(let R of G(l,I,!0)){let O=R.constructor;if(O===qt||O===Uint8Array)yield R;else if(at(R)){let m=R.stream().getReader(),k;for(;!(k=await m.read()).done;)yield k.value}else if(R[Symbol.asyncIterator])for await(let m of R)V(),m?yield*pt(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 Wt(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 Vt(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 Wt{constructor(e,r,n){this.structures=e,this.packedValues=r,this.version=n}}function re(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 Wr=typeof Blob>"u"?function(){}:Blob;function at(t){if(t instanceof Wr)return!0;let e=t[Symbol.toStringTag];return e==="Blob"||e==="File"}function De(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++)De(t[n],e);else{let n=!e.encoder.useRecords;for(var r in t)t.hasOwnProperty(r)&&(n&&De(r,e),De(t[r],e))}break;case"function":console.log(t)}}const $r=new Uint8Array(new Uint16Array([1]).buffer)[0]==1;Bt=[Date,Set,Error,RegExp,de,ArrayBuffer,Uint8Array,Uint8ClampedArray,Uint16Array,Uint32Array,typeof BigUint64Array>"u"?function(){}:BigUint64Array,Int8Array,Int16Array,Int32Array,typeof BigInt64Array>"u"?function(){}:BigInt64Array,Float32Array,Float64Array,Wt],it=[{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){ct(t,r)}},{getTag(t){if(t.constructor===Uint8Array&&(this.tagUint8Array||Ae&&this.tagUint8Array!==!1))return 64},encode(t,e,r){ct(t,r)}},ne(68,1),ne(69,2),ne(70,4),ne(71,8),ne(72,1),ne(77,2),ne(78,4),ne(79,8),ne(85,4),ne(86,8),{encode(t,e){let r=t.packedValues||[],n=t.structures||[];if(r.values.length>0){u[a++]=216,u[a++]=51,re(4);let i=r.values;e(i),re(0),re(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 de(t.version,1399353956)),e(i)}else e(new de(t.version,1399353956))}}];function ne(t,e){return!$r&&e>1&&(t-=4),{tag:t,encode:function(n,i){let s=n.byteLength,o=n.byteOffset||0,y=n.buffer||n;i(Ae?Je.from(y,o,s):new Uint8Array(y,o,s))}}}function ct(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 Hr(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 y of o.references)t[y++]=s>>8,t[y]=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 $t(t,e){B.setUint32($.position+t,a-$.position-t+1);let r=$;$=null,e(r[0]),e(r[1])}let lt=new Vr({useRecords:!1});const Gr=lt.encode;lt.encodeAsIterable,lt.encodeAsAsyncIterable;const Ht=512,Zr=1024,ut=2048;function Gt(t){return!!t&&typeof t=="object"&&"jsonrpc"in t}class je{closed=!1;[j];#e;constructor(e,{signal:r}={}){this[j]=new wr(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 Yr=me("appetize.io:transport:ws-ping"),Xr=3e4;function Qr(t){let e=!0;const r=()=>{e=!0};t.on("pong",r);const n=setInterval(()=>{if(!e){clearInterval(n),Yr("liveness ping went unanswered, terminating"),t.terminate();return}t.readyState===t.OPEN&&(e=!1,t.ping())},Xr);return{destroy(){clearInterval(n),t.off("pong",r)},pong:r}}const pe=me("appetize.io:trace:transport:websocket");class en extends je{constructor(e,{signal:r}={}){super(async i=>{this.#i.send(Gr(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.#a),n.addEventListener("close",this.#o),this.#e.push(()=>{n.removeEventListener("open",this.#l),n.removeEventListener("message",this.#c),n.removeEventListener("error",this.#a),n.removeEventListener("close",this.#o)})):(n.addEventListener("open",this.#l),n.addEventListener("message",this.#c),n.addEventListener("error",this.#a),n.addEventListener("close",this.#o),this.#e.push(()=>{n.removeEventListener("open",this.#l),n.removeEventListener("message",this.#c),n.removeEventListener("error",this.#a),n.removeEventListener("close",this.#o)})),this.send=n.send.bind(n),"ping"in n){const{destroy:i,pong:s}=Qr(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){pe("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.#s(),super.handleClose(e)}#s(e){this.#t||(this.#t=!0,this.onclose?.(e))}#o=e=>{pe("handleWebSocketClose()",e);try{this.#s(e)}finally{this.close()}};#a=e=>{pe("handleWebSocketError()",e),this.onerror?.(e)};#c=async e=>{pe("handleWebSocketMessage()",e),this.#n?.();const r=this.#u(e);if(!r){pe("handleWebSocketMessage() -> legacy"),this.onmessage?.(e);return}pe("handleWebSocketMessage() -> jsonrpc",r),this[j].dispatchMessage(r)};#l=e=>{pe("handleWebSocketOpen()",e),this.onopen?.(e)};#u(e){try{const r=jt(new Uint8Array(e.data));return Gt(r)?r:null}catch{return null}}}function Zt(t,e,{leftEffects:r=()=>({}),notifiesLeft:n,notifiesRight:i,rightEffects:s=()=>({})}={}){const o=We(t,{}),y=We(e,{}),c=[()=>{o.unsub(),y.unsub()}],h=()=>{for(const S of c)try{S()}catch{}},w=y.rpc.client,p=o.rpc.client;c.push(t[j].addEventListener("close",()=>{h()},{once:!0}),e[j].addEventListener("close",()=>{h()},{once:!0}));const v=r(w,p);for(const S in v){const g=v[S];g&&o.rpc.addMethod(S,g)}const f=s(p,w);for(const S in f){const g=f[S];g&&y.rpc.addMethod(S,g)}return Yt(o.rpc,y.rpc,{notifies:n}),Yt(y.rpc,o.rpc,{notifies:i}),h}function Yt(t,e,{notifies:r}={}){t.applyServerMiddleware(async(n,i)=>{const s=r?.();if(s){const{id:y,...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:ke.JSONRPC,result:o}})}function ce(t,...e){t.notify(e[0],e[1],e[2])}function ft(){const t=new je(async r=>{e[j].dispatchMessage(r)}),e=new je(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 Xt(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 ye=me("appetize.io:trace:transport:iframe");class Qt extends je{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){ye("postMessage(legacy)",{message:e,targetOrigin:r,transfer:n}),this.#r.postMessage(e,r??this.#e,n)}handleClose(e){ye("close()"),window.removeEventListener("message",this.#t),super.handleClose(e)}#t=async e=>{if(ye("handleMessage()",e),e.source!==this.#r||(ye("handleMessage() -> source ok"),this.#e!=="*"&&e.origin!==this.#e))return;ye("handleMessage() -> origin ok");const r=e.data;if(!Gt(r)){ye("handleMessage() -> legacy"),this.onmessage?.(e);return}ye("handleMessage() -> jsonrpc"),this[j].dispatchMessage(r)}}function dt(){let t,e;return{promise:new Promise((n,i)=>{e=n,t=i}),reject:t,resolve:e}}const tn=2*1024*1024,er=me("appetize:client:acked-writable-stream");class rn{unacked=0;#e;#r;#t;#n;#i=[];#s;constructor(e){this.#t=e,this.#s=e.window??tn}abort(e){this.#a(e),this.#t.onAbort?.(e)}async close(){await this.#c(()=>this.unacked===0),this.#t.onClose?.()}fail(e){this.#a(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.#o()},n=>{this.fail(n)}),this.unacked>=this.#s&&!this.#n&&(this.#n={acked:0,at:performance.now()},er("window full: %d bytes unacked, writes stalled",this.unacked)),this.#c(()=>this.unacked<this.#s)}#o(){if(this.#n&&this.unacked<=this.#s/2){const e=performance.now()-this.#n.at;er("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)}#a(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={...dt(),until:e};return this.#i.push(r),r.promise}}class nn extends WritableStream{get unacked(){return this.#e.unacked}#e;constructor(e){const r=new rn(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 sn=1024*1024;class on{#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??=dt();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 an extends ReadableStream{#e;constructor({highWaterMark:e=sn,onCancel:r}={}){const n=new on(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 cn{closed;readable;writable;#e=[];#r;#t;#n;#i;#s;#o="starting";constructor(e,{onClose:r,receiveBuffer:n,sendWindow:i,signal:s}){if(this.#s=e,this.#r=dt(),this.closed=this.#r.promise,this.closed.catch(ln),this.#n=new an({highWaterMark:n,onCancel:()=>{this.#a(void 0)}}),this.readable=this.#n,this.#i=new nn({onAbort:()=>{this.#a(void 0)},onClose:()=>{this.#a(void 0)},onError:o=>{this.#a(o)},send:o=>e.request("appetizeio.device.server.debug.adbTunnel.data",{data:o}),window:i}),this.writable=this.#i,s){const o=()=>{this.#a(s.reason)};s.addEventListener("abort",o,{once:!0}),this.#e.push(()=>{s.removeEventListener("abort",o)})}this.#e.push(()=>{r(this)})}close=()=>{this.#a(void 0)};detach(){this.#a(void 0,{notifyServer:!1})}async handleData(e){this.#o==="open"&&await this.#n.push(e)}handleStopped({error:e}){this.#o==="open"&&this.#a(e?new Error(e):void 0)}async start(){try{await this.#s.request("appetizeio.device.server.debug.adbTunnel.start",void 0)}catch(e){throw this.#a(e),e}if(this.#o==="closed")throw this.#t?this.#t:new Error("The adb tunnel closed before it started");this.#o="open"}async[Symbol.asyncDispose](){this.close();try{await this.closed}catch{}}#a(e,{notifyServer:r=!0}={}){if(this.#o!=="closed"){this.#o="closed",this.#t=e,r&&ce(this.#s,"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 ln(){}class un{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.#o()},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.#s()};fail(e){this.#s(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()}}#s(e){this.#r||(this.#t.close(),this.#o(e))}#o(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 fn{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 tr extends fn{#e;constructor(e){super({start:e.start,stop:e.stop}),this.#e=e.label}async createStream({signal:e}={}){e?.throwIfAborted();const r=new un({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 dn{#e;#r;#t;#n;constructor(e){this.#n=e,this.#r=new tr({label:"Log stream",start:()=>e.request("appetizeio.device.server.debug.log.start"),stop:()=>{ce(e,"appetizeio.device.server.debug.log.stop",void 0)}}),this.#t=new tr({label:"Proxy intercept stream",start:()=>e.request("appetizeio.device.server.debug.proxyIntercept.start"),stop:()=>{ce(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 cn(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 ht(t){return{...hn(t),index:t.index,within:t.within?ht(t.within):void 0}}function hn(t){switch(t.by){case"testId":return{by:"testId",testId:t.testId};case"text":return{by:"text",text:pn(t.text)}}}function pn(t){return typeof t=="string"?{kind:"exact",value:t}:{flags:t.flags,kind:"regex",source:t.source}}function yn(t){return{press:e=>{ce(t,"appetizeio.device.server.keyboard.press",{key:e})}}}function wn({onRequest:t,parent:e,proxyInlet:r,signal:n}){const i=new Qt(e,{signal:n}),s=[()=>{i.close()}];return Xt(i,r),t&&s.push(_e(i,o=>{t(o,{source:"parent"})})),{cleanup:()=>{for(const o of s)o()},notifies:()=>e===globalThis.window?void 0:i}}const vn="@appetizeio/rpc:playwrightAdapter",Be=Symbol.for(vn);function gn(t){window[Be]&&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[Be]=e,()=>{window[Be]===e&&delete window[Be]}}function bn({onRequest:t,proxyInlet:e}){const[r,n]=ft(),s=[gn(n),()=>{r.close()}];return Xt(r,e),t&&s.push(_e(r,o=>{t(o,{source:"parent"})})),{cleanup:()=>{for(const o of s)o()},notifies:()=>r}}function qe(t){return t.by==="position"?{by:"position",x:t.x,y:t.y}:{...ht(t),x:t.x,y:t.y}}function mn(t){return"to"in t?{from:qe(t.from),kind:"path",to:qe(t.to)}:{direction:t.direction,distance:t.distance,from:t.from?qe(t.from):void 0,kind:"direction"}}function Sn(t){return{down:(e,r)=>{ce(t,"appetizeio.device.server.touch.down",{x:e,y:r})},move:(e,r)=>{ce(t,"appetizeio.device.server.touch.move",{x:e,y:r})},up:(e,r)=>{ce(t,"appetizeio.device.server.touch.up",{x:e,y:r})}}}const Cn=new Set($e),En=/^(?<key>[A-Za-z]+)>(?<repeat>\d+)\/$/u,Rn=/(\{\{|\{[^{}]*\})/u;function On(t){const e=[];let r="";function n(){r.length>0&&(e.push({kind:"text",text:r}),r="")}for(const[i,s]of t.split(Rn).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 Mn(t,e){if(!Cn.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: ${$e.join(", ")}. Type characters as text, and escape a literal "{" as "{{".`)}function An(t){const e=En.exec(t)?.groups,r=e?.key??t;if(Mn(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 Pn=Symbol("@appetizeio/client:v1Compat");function rr(t){return t?.[Pn]}class In{readable;ready;get dimensions(){return this.#n}#e=[];#r=!1;#t;#n;#i;#s;constructor({onClose:e,requestKeyFrame:r,signal:n}){this.#i=r,this.ready=new Promise((s,o)=>{this.#s={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(()=>{e(this)})}close=()=>{this.#o()};fail(e){this.#o(e)}handleChunk(e){if(this.#s){if(e.type!=="key")return;const{resolve:r}=this.#s;this.#s=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()}}#o(e){this.#r||(this.#t.close(),this.#a(e))}#a(e){this.#r=!0;for(const r of this.#e)r();this.#s?.reject(e??new Error("Video stream closed before the first key chunk")),this.#s=void 0}}class Nn{#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 In({onClose:n=>{this.#s(n)},requestKeyFrame:()=>{this.#o()},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.#o(),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)}#s(e){this.#n.delete(e),!(this.#n.size>0||!this.#t)&&(this.#t=void 0,ce(this.#r,"appetizeio.device.server.video.stop",void 0))}#o(){this.#e||(this.#e=!0,ce(this.#r,"appetizeio.device.server.video.requestKeyFrame",void 0))}}class kn{debug;keyboard;touch;video;#e;#r=[];#t;constructor(e,r={}){const n=rr(r)??{},{baseUrl:i,onClose:s,signal:o}=r;this.#e=i?_n(i):void 0;const{onRequest:y,parent:c,proxyRequest:h}=n,w=Fn(y);o?.addEventListener("abort",this.close);const[p,v]=ft(),[f,S]=ft();this.#r.push(()=>{p.close(),v.close(),f.close(),S.close()}),this.#r.push(Zt(S,e,{leftEffects:h}));const g=c==="playwright"?bn({onRequest:w,proxyInlet:f}):c?wn({onRequest:w,parent:c,proxyInlet:f,signal:o}):void 0;g&&this.#r.push(g.cleanup),this.#r.push(Zt(v,f,{notifiesLeft:g?.notifies}));const{client:C,unsub:b}=br(p,{"appetizeio.device.client.debug.adbTunnel.data":N=>E.handleAdbTunnelData(N),"appetizeio.device.client.debug.adbTunnel.stopped":async N=>{E.handleAdbTunnelStopped(N)},"appetizeio.device.client.debug.log.entry":async N=>{E.handleLogEntry(N)},"appetizeio.device.client.debug.proxyIntercept.event":async N=>{E.handleProxyInterceptEvent(N)},"appetizeio.device.client.video.chunk":async N=>{M.handleChunk(N)}});this.#t=C,this.#r.push(b);const E=new dn(this.#t);this.#r.push(()=>{E.close()});const M=new Nn(this.#t);this.#r.push(()=>{M.close()}),this.debug=E,this.keyboard=yn(this.#t),this.touch=Sn(this.#t),this.video=M,w&&(this.#r.push(_e(v,N=>{w(N,{source:"self"})})),e instanceof Qt&&this.#r.push(_e(e,N=>{w(N,{source:"iframe"})}))),this.#r.push(()=>s?.())}async clearKeychain(){await this.#t.request("appetizeio.device.server.clearKeychain")}close=()=>{for(const e of this.#r)try{e()}catch(r){console.error("Device cleanup error:",r)}};async inspect(e,r){return await this.#t.request("appetizeio.device.server.inspect",{options:r,selector:e?ht(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){return await this.#t.request("appetizeio.device.server.rotate",{orientation:e})}async screenshot(){const e=await this.#t.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.#t.request("appetizeio.device.server.swipe",{gesture:mn(e),options:r})}async tap(e,r){await this.#t.request("appetizeio.device.server.tap",{options:r,selector:qe(e)})}async type(e,r){await this.#t.request("appetizeio.device.server.type",{options:r,steps:On(e)})}}function _n(t){const e=new URL(t);return e.protocol==="ws:"?e.protocol="http:":e.protocol==="wss:"&&(e.protocol="https:"),e.href}const Fn=t=>{if(t)return(e,r)=>{e.method.startsWith("appetizeio.device.server.")&&t(e,r)}};function Ln(t){return typeof t=="object"&&t!==null}function xn(t){try{const e=jt(new Uint8Array(t.data));if(Ln(e)&&typeof e.name=="string")return{name:e.name,payload:"payload"in e?e.payload:void 0}}catch{}}async function Tn(t,e={}){const r=e.baseUrl??(typeof t=="string"?new URL(t).origin:void 0),n=typeof t=="string"?new en(t,{signal:e.signal}):t,i=new kn(n,{...e,baseUrl:r});return typeof t=="string"&&await Un(n,i,e),i}function Un(t,e,r){const n=rr(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 y=xn(o);y&&n?.(y)}})}async function Jn(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 Tn(`${n}//${e.host}/ws`);Or(i,r),Mr(i,r),await Ar(i,r)}await Jn(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 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 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){return 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);
2
2
  </script></body></html>
@@ -1,3 +0,0 @@
1
- import{Transform as cr}from"stream";import{createRequire as lr}from"module";import{connect as fr}from"node:net";import ze from"debug";import{JSONRPCServerAndClient as ur,JSONRPCServer as dr,JSONRPCClient as hr,JSONRPC as pr}from"json-rpc-2.0";import{writeFileSync as yr,renameSync as wr,mkdirSync as gt,readFileSync as mr,rmSync as br,readdirSync as gr}from"node:fs";import{sep as Er,join as te}from"node:path";import{homedir as Et}from"node:os";let je;try{je=new TextDecoder}catch{}let p,V,l=0;const Ve=[],Sr=105,vr=57342,Ar=57343,St=57337,vt=6,ue={};let me=11281e4,Y=1681e4,re=Ve,be=0,k={},_,ge,Ee=0,se=0,D,q,N=[],Ke=[],K,j,Se,At={useRecords:!1,mapsAsObjects:!0},ve=!1,Ot=2;try{new Function("")}catch{Ot=1/0}class pe{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[J(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(p)return Pt(()=>(We(),this?this.decode(e,r):pe.prototype.decode.call(At,e,r)));V=r>-1?r:e.length,l=0,be=0,se=0,ge=null,re=Ve,D=null,p=e;try{j=e.dataView||(e.dataView=new DataView(e.buffer,e.byteOffset,e.byteLength))}catch(s){throw p=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 pe){if(k=this,K=this.sharedValues&&(this.pack?new Array(this.maxPrivatePackedValues||16).concat(this.sharedValues):this.sharedValues),this.structures)return _=this.structures,xe();(!_||_.length>0)&&(_=[])}else k=At,(!_||_.length>0)&&(_=[]),K=null;return xe()}decodeMultiple(e,r){let s,n=0;try{let i=e.length;ve=!0;let f=this?this.decode(e,i):He.decode(e,i);if(r){if(r(f)===!1)return;for(;l<i;)if(n=l,r(xe())===!1)return}else{for(s=[f];l<i;)n=l,s.push(xe());return s}}catch(i){throw i.lastPosition=n,i.values=s,i}finally{ve=!1,We()}}}function xe(){try{let t=I();if(D){if(l>=D.postBundlePosition){let e=new Error("Unexpected bundle position");throw e.incomplete=!0,e}l=D.postBundlePosition,D=null}if(l==V)_=null,p=null,q&&(q=null);else if(l>V){let e=new Error("Unexpected end of CBOR data");throw e.incomplete=!0,e}else if(!ve)throw new Error("Data read, but end of buffer not reached");return t}catch(t){throw We(),(t instanceof RangeError||t.message.startsWith("Unexpected end of buffer"))&&(t.incomplete=!0),t}}function ne(){let t=new Error("Unexpected end of CBOR data");return t.incomplete=!0,t}function I(){if(!(l<V))throw ne();let t=p[l++],e=t>>5;if(t=t&31,t>23)switch(t){case 24:if(l>=V)throw ne();t=p[l++];break;case 25:if(e==7)return xr();t=j.getUint16(l),l+=2;break;case 26:if(e==7){let r=j.getFloat32(l);if(k.useFloat32>2){let s=Ge[(p[l]&127)<<1|p[l+1]>>7];return l+=4,(s*r+(r>0?.5:-.5)>>0)/s}return l+=4,r}if(t=j.getUint32(l),l+=4,e===1)return-1-t;break;case 27:if(e==7){let r=j.getFloat64(l);return l+=8,r}if(e>1){if(j.getUint32(l)>0)throw new Error("JavaScript does not support arrays, maps, or strings with length over 4294967295");t=j.getUint32(l+4)}else k.int64AsNumber?(t=j.getUint32(l)*4294967296,t+=j.getUint32(l+4)):t=j.getBigUint64(l);l+=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())!=ue;){if(n>=me)throw new Error(`Array length exceeds ${me}`);r[n++]=s}return e==4?r:e==3?r.join(""):Buffer.concat(r);case 5:let i;if(k.mapsAsObjects){let f={},m=0;if(k.keyMap)for(;(i=I())!=ue;){if(m++>=Y)throw new Error(`Property count exceeds ${Y}`);f[J(k.decodeKey(i))]=I()}else for(;(i=I())!=ue;){if(m++>=Y)throw new Error(`Property count exceeds ${Y}`);f[J(i)]=I()}return f}else{Se&&(k.mapsAsObjects=!0,Se=!1);let f=new Map;if(k.keyMap){let m=0;for(;(i=I())!=ue;){if(m++>=Y)throw new Error(`Map size exceeds ${Y}`);f.set(k.decodeKey(i),I())}}else{let m=0;for(;(i=I())!=ue;){if(m++>=Y)throw new Error(`Map size exceeds ${Y}`);f.set(i,I())}}return f}case 7:return ue;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 Ir(t);case 3:if(se>=l)return ge.slice(l-Ee,(l+=t)-Ee);if(se==0&&V<140&&t<32){let n=t<16?xt(t):kr(t);if(n!=null)return n}return It(t);case 4:if(t>=me)throw new Error(`Array length exceeds ${me}`);if(t>V-l)throw ne();let r=new Array(t);for(let n=0;n<t;n++)r[n]=I();return r;case 5:if(t>=Y)throw new Error(`Map size exceeds ${me}`);if(t>(V-l)/2)throw ne();if(k.mapsAsObjects){let n={};if(k.keyMap)for(let i=0;i<t;i++)n[J(k.decodeKey(I()))]=I();else for(let i=0;i<t;i++)n[J(I())]=I();return n}else{Se&&(k.mapsAsObjects=!0,Se=!1);let n=new Map;if(k.keyMap)for(let i=0;i<t;i++)n.set(k.decodeKey(I()),I());else for(let i=0;i<t;i++)n.set(I(),I());return n}case 6:if(t>=St){let n=_[t&8191];if(n)return n.read||(n.read=$e(n)),n.read();if(t<65536){if(t==Ar){let i=he(),f=I(),m=I();qe(f,m);let y={};if(k.keyMap)for(let v=2;v<i;v++){let g=k.decodeKey(m[v-2]);y[J(g)]=I()}else for(let v=2;v<i;v++){let g=m[v-2];y[J(g)]=I()}return y}else if(t==vr){let i=he(),f=I();for(let m=2;m<i;m++)qe(f++,I());return I()}else if(t==St)return Ur();if(k.getShared&&(Je(),n=_[t&8191],n))return n.read||(n.read=$e(n)),n.read()}}let s=N[t];if(s)return s.handlesRead?s(I):s(I());{let n=I();for(let i=0;i<Ke.length;i++){let f=Ke[i](t,n);if(f!==void 0)return f}return new ie(n,t)}case 7:switch(t){case 20:return!1;case 21:return!0;case 22:return null;case 23:return;default:let n=(K||oe())[t];if(n!==void 0)return n;throw new Error("Unknown token "+t)}default:throw isNaN(t)?ne():new Error("Unknown CBOR token "+t)}}const kt=/^[a-zA-Z_$][a-zA-Z\d_$]*$/;function $e(t){if(!t)throw new Error("Structure is required in record definition");function e(){let r=p[l++];if(r=r&31,r>23)switch(r){case 24:r=p[l++];break;case 25:r=j.getUint16(l),l+=2;break;case 26:r=j.getUint32(l),l+=4;break;default:throw new Error("Expected array header, but got "+p[l-1])}let s=this.compiledReader;for(;s;){if(s.propertyCount===r)return s(I);s=s.next}if(this.slowReads++>=Ot){let i=this.length==r?this:this.slice(0,r);return s=k.keyMap?new Function("r","return {"+i.map(f=>k.decodeKey(f)).map(f=>kt.test(f)?J(f)+":r()":"["+JSON.stringify(f)+"]:r()").join(",")+"}"):new Function("r","return {"+i.map(f=>kt.test(f)?J(f)+":r()":"["+JSON.stringify(f)+"]:r()").join(",")+"}"),this.compiledReader&&(s.next=this.compiledReader),s.propertyCount=r,this.compiledReader=s,s(I)}let n={};if(k.keyMap)for(let i=0;i<r;i++)n[J(k.decodeKey(this[i]))]=I();else for(let i=0;i<r;i++)n[J(this[i])]=I();return n}return t.slowReads=0,e}function J(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 It=Me;function Or(t){It=e();function e(r){return function(n){let i=re[be++];if(i==null){if(D)return Me(n);let m=t(l,V,n,p);if(typeof m=="string")i=m,re=Ve;else if(re=m,be=1,se=1,i=re[0],i===void 0)throw new Error("Unexpected end of buffer")}let f=i.length;return f<=n?(l+=n,i):(ge=i,Ee=l,se=l+f,l+=n,i.slice(0,n))}}}function Me(t){let e;if(t<16&&(e=xt(t)))return e;if(t>64&&je)return je.decode(p.subarray(l,l+=t));const r=l+t,s=[];for(e="";l<r;){const n=p[l++];if((n&128)===0)s.push(n);else if((n&224)===192)if(n<194||l>=r||(p[l]&192)!==128)s.push(65533);else{const i=p[l++]&63;s.push((n&31)<<6|i)}else if((n&240)===224){const i=l<r?p[l]:0;if(l>=r||(i&192)!==128||n===224&&i<160||n===237&&i>=160)s.push(65533);else if(l++,l>=r||(p[l]&192)!==128)s.push(65533);else{const f=p[l++]&63;s.push((n&31)<<12|(i&63)<<6|f)}}else if((n&248)===240){const i=l<r?p[l]:0;if(n>244||l>=r||(i&192)!==128||n===240&&i<144||n===244&&i>=144)s.push(65533);else if(l++,l>=r||(p[l]&192)!==128)s.push(65533);else{const f=p[l++]&63;if(l>=r||(p[l]&192)!==128)s.push(65533);else{const m=p[l++]&63;let y=(n&7)<<18|(i&63)<<12|f<<6|m;y-=65536,s.push(y>>>10&1023|55296),s.push(56320|y&1023)}}}else s.push(65533);s.length>=4096&&(e+=F.apply(String,s),s.length=0)}return s.length>0&&(e+=F.apply(String,s)),e}let F=String.fromCharCode;function kr(t){let e=l,r=new Array(t);for(let s=0;s<t;s++){const n=p[l++];if((n&128)>0){l=e;return}r[s]=n}return F.apply(String,r)}function xt(t){if(t<4)if(t<2){if(t===0)return"";{let e=p[l++];if((e&128)>1){l-=1;return}return F(e)}}else{let e=p[l++],r=p[l++];if((e&128)>0||(r&128)>0){l-=2;return}if(t<3)return F(e,r);let s=p[l++];if((s&128)>0){l-=3;return}return F(e,r,s)}else{let e=p[l++],r=p[l++],s=p[l++],n=p[l++];if((e&128)>0||(r&128)>0||(s&128)>0||(n&128)>0){l-=4;return}if(t<6){if(t===4)return F(e,r,s,n);{let i=p[l++];if((i&128)>0){l-=5;return}return F(e,r,s,n,i)}}else if(t<8){let i=p[l++],f=p[l++];if((i&128)>0||(f&128)>0){l-=6;return}if(t<7)return F(e,r,s,n,i,f);let m=p[l++];if((m&128)>0){l-=7;return}return F(e,r,s,n,i,f,m)}else{let i=p[l++],f=p[l++],m=p[l++],y=p[l++];if((i&128)>0||(f&128)>0||(m&128)>0||(y&128)>0){l-=8;return}if(t<10){if(t===8)return F(e,r,s,n,i,f,m,y);{let v=p[l++];if((v&128)>0){l-=9;return}return F(e,r,s,n,i,f,m,y,v)}}else if(t<12){let v=p[l++],g=p[l++];if((v&128)>0||(g&128)>0){l-=10;return}if(t<11)return F(e,r,s,n,i,f,m,y,v,g);let M=p[l++];if((M&128)>0){l-=11;return}return F(e,r,s,n,i,f,m,y,v,g,M)}else{let v=p[l++],g=p[l++],M=p[l++],R=p[l++];if((v&128)>0||(g&128)>0||(M&128)>0||(R&128)>0){l-=12;return}if(t<14){if(t===12)return F(e,r,s,n,i,f,m,y,v,g,M,R);{let L=p[l++];if((L&128)>0){l-=13;return}return F(e,r,s,n,i,f,m,y,v,g,M,R,L)}}else{let L=p[l++],U=p[l++];if((L&128)>0||(U&128)>0){l-=14;return}if(t<15)return F(e,r,s,n,i,f,m,y,v,g,M,R,L,U);let C=p[l++];if((C&128)>0){l-=15;return}return F(e,r,s,n,i,f,m,y,v,g,M,R,L,U,C)}}}}}function Ir(t){return k.copyBuffers?Uint8Array.prototype.slice.call(p,l,l+=t):p.subarray(l,l+=t)}let Mt=new Float32Array(1),Re=new Uint8Array(Mt.buffer,0,4);function xr(){let t=p[l++],e=p[l++],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 Re[3]=t&128|(r>>1)+56,Re[2]=(t&7)<<5|e>>3,Re[1]=e<<5,Re[0]=0,Mt[0]}new Array(4096);class ie{constructor(e,r){this.value=e,this.tag=r}}N[0]=t=>new Date(t),N[1]=t=>new Date(Math.round(t*1e3)),N[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},N[3]=t=>BigInt(-1)-N[2](t),N[4]=t=>+(t[1]+"e"+t[0]),N[5]=t=>t[1]*Math.exp(t[0]*Math.log(2));const qe=(t,e)=>{t=t-57344;let r=_[t];r&&r.isShared&&((_.restoreStructures||(_.restoreStructures=[]))[t]=r),_[t]=e,e.read=$e(e)};N[Sr]=t=>{let e=t.length,r=t[1];qe(t[0],r);let s={};for(let n=2;n<e;n++){let i=r[n-2];s[J(i)]=t[n]}return s},N[14]=t=>D?D[0].slice(D.position0,D.position0+=t):new ie(t,14),N[15]=t=>D?D[1].slice(D.position1,D.position1+=t):new ie(t,15);let Mr={Error,RegExp};N[27]=t=>(Mr[t[0]]||Error)(t[1],t[2]);const Rt=t=>{if(p[l++]!=132){let r=new Error("Packed values structure must be followed by a 4 element array");throw p.length<l&&(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 K=K?e.concat(K.slice(e.length)):e,K.prefixes=t(),K.suffixes=t(),t()};Rt.handlesRead=!0,N[51]=Rt,N[vt]=t=>{if(!K)if(k.getShared)Je();else return new ie(t,vt);if(typeof t=="number")return K[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},N[28]=t=>{q||(q=new Map,q.id=0);let e=q.id++,r=l,s=p[l],n;s>>5==4?n=[]:n={};let i={target:n};q.set(e,i);let f=t();return i.used?(Object.getPrototypeOf(n)!==Object.getPrototypeOf(f)&&(l=r,n=f,q.set(e,{target:n}),f=t()),Object.assign(n,f)):(i.target=f,f)},N[28].handlesRead=!0,N[29]=t=>{let e=q.get(t);return e.used=!0,e.target},N[258]=t=>new Set(t),(N[259]=t=>(k.mapsAsObjects&&(k.mapsAsObjects=!1,Se=!0),t())).handlesRead=!0;function de(t,e){return typeof t=="string"?t+e:t instanceof Array?t.concat(e):Object.assign({},t,e)}function oe(){if(!K)if(k.getShared)Je();else throw new Error("No packed values available");return K}const Rr=1399353956;Ke.push((t,e)=>{if(t>=225&&t<=255)return de(oe().prefixes[t-224],e);if(t>=28704&&t<=32767)return de(oe().prefixes[t-28672],e);if(t>=1879052288&&t<=2147483647)return de(oe().prefixes[t-1879048192],e);if(t>=216&&t<=223)return de(e,oe().suffixes[t-216]);if(t>=27647&&t<=28671)return de(e,oe().suffixes[t-27639]);if(t>=1811940352&&t<=1879048191)return de(e,oe().suffixes[t-1811939328]);if(t==Rr)return{packedValues:K,structures:_.slice(0),version:e};if(t==55799)return e});const Tr=new Uint8Array(new Uint16Array([1]).buffer)[0]==1,Tt=[Uint8Array,Uint8ClampedArray,Uint16Array,Uint32Array,typeof BigUint64Array>"u"?{name:"BigUint64Array"}:BigUint64Array,Int8Array,Int16Array,Int32Array,typeof BigInt64Array>"u"?{name:"BigInt64Array"}:BigInt64Array,Float32Array,Float64Array],Pr=[64,68,69,70,71,72,77,78,79,85,86];for(let t=0;t<Tt.length;t++)Cr(Tt[t],Pr[t]);function Cr(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;N[n?e:e-4]=s==1||n==Tr?f=>{if(!t)throw new Error("Could not find typed array for code "+e);return!k.copyBuffers&&(s===1||s===2&&!(f.byteOffset&1)||s===4&&!(f.byteOffset&3)||s===8&&!(f.byteOffset&7))?new t(f.buffer,f.byteOffset,f.byteLength>>i):new t(Uint8Array.prototype.slice.call(f,0).buffer)}:f=>{if(!t)throw new Error("Could not find typed array for code "+e);let m=new DataView(f.buffer,f.byteOffset,f.byteLength),y=f.length>>i,v=new t(y),g=m[r];for(let M=0;M<y;M++)v[M]=g.call(m,M<<i,n);return v}}}function Ur(){let t=he(),e=l+I();for(let s=2;s<t;s++){let n=he();l+=n}let r=l;return l=e,D=[Me(he()),Me(he())],D.position0=0,D.position1=0,D.postBundlePosition=l,l=r,I()}function he(){if(!(l<V))throw ne();let t=p[l++]&31;if(t>23)switch(t){case 24:if(l>=V)throw ne();t=p[l++];break;case 25:t=j.getUint16(l),l+=2;break;case 26:t=j.getUint32(l),l+=4;break}return t}function Je(){if(k.getShared){let t=Pt(()=>(p=null,k.getShared()))||{},e=t.structures||[];k.sharedVersion=t.version,K=k.sharedValues=t.packedValues,_===!0?k.structures=_=e:_.splice.apply(_,[0,e.length].concat(e))}}function Pt(t){let e=V,r=l,s=be,n=Ee,i=se,f=ge,m=re,y=q,v=D,g=new Uint8Array(p.slice(0,V)),M=_,R=k,L=ve,U=t();return V=e,l=r,be=s,Ee=n,se=i,ge=f,re=m,q=y,D=v,p=g,ve=L,_=M,k=R,j=new DataView(p.buffer,p.byteOffset,p.byteLength),U}function We(){p=null,q=null,_=null}const Ge=new Array(147);for(let t=0;t<256;t++)Ge[t]=+("1e"+Math.floor(45.15-t*.30103));let He=new pe({useRecords:!1});const Lr=He.decode;He.decodeMultiple;let Te;try{Te=new TextEncoder}catch{}let Ze,Ct;const Pe=typeof globalThis=="object"&&globalThis.Buffer,Ae=typeof Pe<"u",Ye=Ae?Pe.allocUnsafeSlow:Uint8Array,Ut=Ae?Pe:Uint8Array,Lt=256,_t=Ae?4294967296:2144337920;let Xe,c,P,o=0,Q,B=null;const _r=61440,Dr=/[\u0080-\uFFFF]/,$=Symbol("record-id");class Dt extends pe{constructor(e){super(e),this.offset=0;let r,s,n,i,f;e=e||{};let m=Ut.prototype.utf8Write?function(a,w){return c.utf8Write(a,w,c.byteLength-w)}:Te&&Te.encodeInto?function(a,w){return Te.encodeInto(a,c.subarray(w)).written}:!1,y=this,v=e.structures||e.saveStructures,g=e.maxSharedStructures;if(g==null&&(g=v?128:0),g>8190)throw new Error("Maximum maxSharedStructure is 8190");let M=e.sequential;M&&(g=0),this.structures||(this.structures=[]),this.saveStructures&&(this.saveShared=this.saveStructures);let R,L,U=e.sharedValues,C;if(U){C=Object.create(null);for(let a=0,w=U.length;a<w;a++)C[U[a]]=a}let W=[],ye=0,G=0;this.mapEncode=function(a,w){return this._keyMap&&!this._mapped&&a.constructor.name==="Array"&&(a=a.map(d=>this.encodeKeys(d))),this.encode(a,w)},this.encode=function(a,w){if(c||(c=new Ye(8192),P=new DataView(c.buffer,0,8192),o=0),Q=c.length-10,Q-o<2048?(c=new Ye(c.length),P=new DataView(c.buffer,0,c.length),Q=c.length-10,o=0):w===zt&&(o=o+7&2147483640),r=o,y.useSelfDescribedHeader&&(P.setUint32(o,3654940416),o+=3),f=y.structuredClone?new Map:null,y.bundleStrings&&typeof a!="string"?(B=[],B.size=1/0):B=null,s=y.structures,s){if(s.uninitialized){let h=y.getShared()||{};y.structures=s=h.structures||[],y.sharedVersion=h.version;let u=y.sharedValues=h.packedValues;if(u){C={};for(let b=0,E=u.length;b<E;b++)C[u[b]]=b}}let d=s.length;if(d>g&&!M&&(d=g),!s.transitions){s.transitions=Object.create(null);for(let h=0;h<d;h++){let u=s[h];if(!u)continue;let b,E=s.transitions;for(let S=0,A=u.length;S<A;S++){E[$]===void 0&&(E[$]=h);let x=u[S];b=E[x],b||(b=E[x]=Object.create(null)),E=b}E[$]=h|1048576}}M||(s.nextId=d)}if(n&&(n=!1),i=s||[],L=C,e.pack){let d=new Map;if(d.values=[],d.encoder=y,d.maxValues=e.maxPrivatePackedValues||(C?16:1/0),d.objectMap=C||!1,d.samplingPackedValues=R,Ce(a,d),d.values.length>0){c[o++]=216,c[o++]=51,H(4);let h=d.values;O(h),H(0),H(0),L=Object.create(C||null);for(let u=0,b=h.length;u<b;u++)L[h[u]]=u}}Xe=w&rt;try{if(Xe)return;if(O(a),B&&Ft(r,O),y.offset=o,f&&f.idsToInsert){o+=f.idsToInsert.length*2,o>Q&&le(o),y.offset=o;let d=Fr(c.subarray(r,o),f.idsToInsert);return f=null,d}return w&zt?(c.start=r,c.end=o,c):c.subarray(r,o)}finally{if(s){if(G<10&&G++,s.length>g&&(s.length=g),ye>1e4)s.transitions=null,G=0,ye=0,W.length>0&&(W=[]);else if(W.length>0&&!M){for(let d=0,h=W.length;d<h;d++)W[d][$]=void 0;W=[]}}if(n&&y.saveShared){y.structures.length>g&&(y.structures=y.structures.slice(0,g));let d=c.subarray(r,o);return y.updateSharedData()===!1?y.encode(a):d}w&jr&&(o=r)}},this.findCommonStringsToPack=()=>(R=new Map,C||(C=Object.create(null)),a=>{let w=a&&a.threshold||4,d=this.pack?a.maxPrivatePackedValues||16:0;U||(U=this.sharedValues=[]);for(let[h,u]of R)u.count>w&&(C[h]=d++,U.push(h),n=!0);for(;this.saveShared&&this.updateSharedData()===!1;);R=null});const O=a=>{o>Q&&(c=le(o));var w=typeof a,d;if(w==="string"){if(L){let E=L[a];if(E>=0){E<16?c[o++]=E+224:(c[o++]=198,E&1?O(15-E>>1):O(E-16>>1));return}else if(R&&!e.pack){let S=R.get(a);S?S.count++:R.set(a,{count:1})}}let h=a.length;if(B&&h>=4&&h<1024){if((B.size+=h)>_r){let S,A=(B[0]?B[0].length*3+B[1].length:0)+10;o+A>Q&&(c=le(o+A)),c[o++]=217,c[o++]=223,c[o++]=249,c[o++]=B.position?132:130,c[o++]=26,S=o-r,o+=4,B.position&&Ft(r,O),B=["",""],B.size=0,B.position=S}let E=Dr.test(a);B[E?0:1]+=a,c[o++]=E?206:207,O(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>Q&&(c=le(o+b)),h<64||!m){let E,S,A,x=o+u;for(E=0;E<h;E++)S=a.charCodeAt(E),S<128?c[x++]=S:S<2048?(c[x++]=S>>6|192,c[x++]=S&63|128):(S&64512)===55296&&((A=a.charCodeAt(E+1))&64512)===56320?(S=65536+((S&1023)<<10)+(A&1023),E++,c[x++]=S>>18|240,c[x++]=S>>12&63|128,c[x++]=S>>6&63|128,c[x++]=S&63|128):(c[x++]=S>>12|224,c[x++]=S>>6&63|128,c[x++]=S&63|128);d=x-o-u}else d=m(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,P.setUint32(o,d),o+=4),o+=d}else if(w==="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,P.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,P.setUint16(o,~a),o+=2):(c[o++]=58,P.setUint32(o,~a),o+=4);else if(!this.alwaysUseFloat&&a<0&&a>=-4294967296&&Math.floor(a)===a)c[o++]=58,P.setUint32(o,-1-a),o+=4;else{let h;if((h=this.useFloat32)>0&&a<4294967296&&a>=-2147483648){c[o++]=250,P.setFloat32(o,a);let u;if(h<4||(u=a*Ge[(c[o]&127)<<1|c[o+1]>>7])>>0===u){o+=4;return}else o--}c[o++]=251,P.setFloat64(o,a),o+=8}else if(w==="object")if(!a)c[o++]=246;else{if(f){let u=f.get(a);if(u){if(c[o++]=216,c[o++]=29,c[o++]=25,!u.references){let b=f.idsToInsert||(f.idsToInsert=[]);u.references=[],b.push(u)}u.references.push(o-r),o+=2;return}else f.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]])])),z(a);else if(h===Array){d=a.length,d<24?c[o++]=128|d:H(d);for(let u=0;u<d;u++)O(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,P.setUint32(o,d),o+=4),y.keyMap)for(let[u,b]of a)O(y.encodeKey(u)),O(b);else for(let[u,b]of a)O(u),O(b);else{for(let u=0,b=Ze.length;u<b;u++){let E=Ct[u];if(a instanceof E){let S=Ze[u],A=S.tag;A==null&&(A=S.getTag&&S.getTag.call(this,a)),A<24?c[o++]=192|A:A<256?(c[o++]=216,c[o++]=A):A<65536?(c[o++]=217,c[o++]=A>>8,c[o++]=A&255):A>-1&&(c[o++]=218,P.setUint32(o,A),o+=4),S.encode.call(this,a,O,le);return}}if(a[Symbol.iterator]){if(Xe){let u=new Error("Iterable should be serialized as iterator");throw u.iteratorNotHandled=!0,u}c[o++]=159;for(let u of a)O(u);c[o++]=255;return}if(a[Symbol.asyncIterator]||Qe(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 O(u)}z(a)}}else if(w==="boolean")c[o++]=a?245:244;else if(w==="bigint"){if(a<BigInt(1)<<BigInt(64)&&a>=0)c[o++]=27,P.setBigUint64(o,a);else if(a>-(BigInt(1)<<BigInt(64))&&a<0)c[o++]=59,P.setBigUint64(o,-a-BigInt(1));else if(this.largeBigIntToFloat)c[o++]=251,P.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);et(new Uint8Array(h.reverse()),le);return}o+=8}else if(w==="undefined")c[o++]=247;else throw new Error("Unknown type: "+w)},z=this.useRecords===!1?this.variableMapSize?a=>{let w=Object.keys(a),d=Object.values(a),h=w.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,P.setUint32(o,h),o+=4),y.keyMap)for(let u=0;u<h;u++)O(y.encodeKey(w[u])),O(d[u]);else for(let u=0;u<h;u++)O(w[u]),O(d[u])}:a=>{c[o++]=185;let w=o-r;o+=2;let d=0;if(y.keyMap)for(let h in a)(typeof a.hasOwnProperty!="function"||a.hasOwnProperty(h))&&(O(y.encodeKey(h)),O(a[h]),d++);else for(let h in a)(typeof a.hasOwnProperty!="function"||a.hasOwnProperty(h))&&(O(h),O(a[h]),d++);c[w+++r]=d>>8,c[w+r]=d&255}:(a,w)=>{let d,h=i.transitions||(i.transitions=Object.create(null)),u=0,b=0,E,S;if(this.keyMap){S=Object.keys(a).map(x=>this.encodeKey(x)),b=S.length;for(let x=0;x<b;x++){let bt=S[x];d=h[bt],d||(d=h[bt]=Object.create(null),u++),h=d}}else for(let x in a)(typeof a.hasOwnProperty!="function"||a.hasOwnProperty(x))&&(d=h[x],d||(h[$]&1048576&&(E=h[$]&65535),d=h[x]=Object.create(null),u++),h=d,b++);let A=h[$];if(A!==void 0)A&=65535,c[o++]=217,c[o++]=A>>8|224,c[o++]=A&255;else if(S||(S=h.__keys__||(h.__keys__=Object.keys(a))),E===void 0?(A=i.nextId++,A||(A=0,i.nextId=1),A>=Lt&&(i.nextId=(A=g)+1)):A=E,i[A]=S,A<g){c[o++]=217,c[o++]=A>>8|224,c[o++]=A&255,h=i.transitions;for(let x=0;x<b;x++)(h[$]===void 0||h[$]&1048576)&&(h[$]=A),h=h[S[x]];h[$]=A|1048576,n=!0}else{if(h[$]=A,P.setUint32(o,3655335680),o+=3,u&&(ye+=G*u),W.length>=Lt-g&&(W.shift()[$]=void 0),W.push(h),H(b+2),O(57344+A),O(S),w)return;for(let x in a)(typeof a.hasOwnProperty!="function"||a.hasOwnProperty(x))&&O(a[x]);return}if(b<24?c[o++]=128|b:H(b),!w)for(let x in a)(typeof a.hasOwnProperty!="function"||a.hasOwnProperty(x))&&O(a[x])},le=a=>{let w;if(a>16777216){if(a-r>_t)throw new Error("Encoded buffer would be larger than maximum buffer size");w=Math.min(_t,Math.round(Math.max((a-r)*(a>67108864?1.25:2),4194304)/4096)*4096)}else w=(Math.max(a-r<<2,c.length-1)>>12)+1<<12;let d=new Ye(w);return P=new DataView(d.buffer,0,w),c.copy?c.copy(d,0,r,a):d.set(c.slice(r,a)),o-=r,r=0,Q=d.length-10,c=d};let ee=100,yt=1e3;this.encodeAsIterable=function(a,w){return wt(a,w,fe)},this.encodeAsAsyncIterable=function(a,w){return wt(a,w,mt)};function*fe(a,w,d){let h=a.constructor;if(h===Object){let u=y.useRecords!==!1;u?z(a,!0):Nt(Object.keys(a).length,160);for(let b in a){let E=a[b];u||O(b),E&&typeof E=="object"?w[b]?yield*fe(E,w[b]):yield*Fe(E,w,b):O(E)}}else if(h===Array){let u=a.length;H(u);for(let b=0;b<u;b++){let E=a[b];E&&(typeof E=="object"||o-r>ee)?w.element?yield*fe(E,w.element):yield*Fe(E,w,"element"):O(E)}}else if(a[Symbol.iterator]&&!a.buffer){c[o++]=159;for(let u of a)u&&(typeof u=="object"||o-r>ee)?w.element?yield*fe(u,w.element):yield*Fe(u,w,"element"):O(u);c[o++]=255}else Qe(a)?(Nt(a.size,64),yield c.subarray(r,o),yield a,we()):a[Symbol.asyncIterator]?(c[o++]=159,yield c.subarray(r,o),yield a,we(),c[o++]=255):O(a);d&&o>r?yield c.subarray(r,o):o-r>ee&&(yield c.subarray(r,o),we())}function*Fe(a,w,d){let h=o-r;try{O(a),o-r>ee&&(yield c.subarray(r,o),we())}catch(u){if(u.iteratorNotHandled)w[d]={},o=r+h,yield*fe.call(this,a,w[d]);else throw u}}function we(){ee=yt,y.encode(null,rt)}function wt(a,w,d){return w&&w.chunkThreshold?ee=yt=w.chunkThreshold:ee=100,a&&typeof a=="object"?(y.encode(null,rt),d(a,y.iterateProperties||(y.iterateProperties={}),!0)):[y.encode(a)]}async function*mt(a,w){for(let d of fe(a,w,!0)){let h=d.constructor;if(h===Ut||h===Uint8Array)yield d;else if(Qe(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)we(),u?yield*mt(u,w.async||(w.async={})):yield y.encode(u);else yield d}}}useBuffer(e){c=e,P=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 Bt(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,f)=>this.structures[f]=i),n}}function Nt(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,P.setUint32(o,t),o+=4)}class Bt{constructor(e,r,s){this.structures=e,this.packedValues=r,this.version=s}}function H(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,P.setUint32(o,t),o+=4)}const Nr=typeof Blob>"u"?function(){}:Blob;function Qe(t){if(t instanceof Nr)return!0;let e=t[Symbol.toStringTag];return e==="Blob"||e==="File"}function Ce(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++)Ce(t[s],e);else{let s=!e.encoder.useRecords;for(var r in t)t.hasOwnProperty(r)&&(s&&Ce(r,e),Ce(t[r],e))}break;case"function":console.log(t)}}const Br=new Uint8Array(new Uint16Array([1]).buffer)[0]==1;Ct=[Date,Set,Error,RegExp,ie,ArrayBuffer,Uint8Array,Uint8ClampedArray,Uint16Array,Uint32Array,typeof BigUint64Array>"u"?function(){}:BigUint64Array,Int8Array,Int16Array,Int32Array,typeof BigInt64Array>"u"?function(){}:BigInt64Array,Float32Array,Float64Array,Bt],Ze=[{tag:1,encode(t,e){let r=t.getTime()/1e3;(this.useTimestamp32||t.getMilliseconds()===0)&&r>=0&&r<4294967296?(c[o++]=26,P.setUint32(o,r),o+=4):(c[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){et(t,r)}},{getTag(t){if(t.constructor===Uint8Array&&(this.tagUint8Array||Ae&&this.tagUint8Array!==!1))return 64},encode(t,e,r){et(t,r)}},Z(68,1),Z(69,2),Z(70,4),Z(71,8),Z(72,1),Z(77,2),Z(78,4),Z(79,8),Z(85,4),Z(86,8),{encode(t,e){let r=t.packedValues||[],s=t.structures||[];if(r.values.length>0){c[o++]=216,c[o++]=51,H(4);let n=r.values;e(n),H(0),H(0),packedObjectMap=Object.create(sharedPackedObjectMap||null);for(let i=0,f=n.length;i<f;i++)packedObjectMap[n[i]]=i}if(s){P.setUint32(o,3655335424),o+=3;let n=s.slice(0);n.unshift(57344),n.push(new ie(t.version,1399353956)),e(n)}else e(new ie(t.version,1399353956))}}];function Z(t,e){return!Br&&e>1&&(t-=4),{tag:t,encode:function(s,n){let i=s.byteLength,f=s.byteOffset||0,m=s.buffer||s;n(Ae?Pe.from(m,f,i):new Uint8Array(m,f,i))}}}function et(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,P.setUint32(o,r),o+=4),o+r>=c.length&&e(o+r),c.set(t.buffer?t:new Uint8Array(t),o),o+=r}function Fr(t,e){let r,s=e.length*2,n=t.length-s;e.sort((i,f)=>i.offset>f.offset?1:-1);for(let i=0;i<e.length;i++){let f=e[i];f.id=i;for(let m of f.references)t[m++]=i>>8,t[m]=i&255}for(;r=e.pop();){let i=r.offset;t.copyWithin(i+s,i,n),s-=2;let f=i+s;t[f++]=216,t[f++]=28,n=i}return t}function Ft(t,e){P.setUint32(B.position+t,o-B.position-t+1);let r=B;B=null,e(r[0]),e(r[1])}let tt=new Dt({useRecords:!1});const zr=tt.encode;tt.encodeAsIterable,tt.encodeAsAsyncIterable;const zt=512,jr=1024,rt=2048;class Vr extends cr{constructor(e){e||(e={}),e.objectMode=!0,super(e),e.structures=[],this.decoder=e.decoder||new pe(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 Kr=process.env.CBOR_NATIVE_ACCELERATION_DISABLED!==void 0&&process.env.CBOR_NATIVE_ACCELERATION_DISABLED.toLowerCase()==="true";if(!Kr){let t;try{typeof require=="function"?t=require("cbor-extract"):t=lr(import.meta.url)("cbor-extract"),t&&Or(t.extractStrings)}catch{}}class $r 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 qr(t,e){const r="CloseEvent"in globalThis?globalThis.CloseEvent:$r;return new r(t,e)}class Jr{#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 T=Symbol.for("@appetizeio/rpc:rpcMethods");class Wr extends Jr{send;constructor(e){super(),this.send=e}dispatchClose(e){return this.dispatchEvent(qr("close",e))}dispatchMessage(e){return this.dispatchEvent(new CustomEvent("message",{detail:e}))}}function st(t){return!!t&&typeof t=="object"&&"jsonrpc"in t}function Gr(){let t,e;return{promise:new Promise((s,n)=>{e=s,t=n}),reject:t,resolve:e}}class Oe{closed=!1;[T];#e;constructor(e,{signal:r}={}){this[T]=new Wr(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[T].dispatchClose(e)}#r=()=>{this.close({code:1e3,reason:String(this.#e?.reason)})}}const jt={useRecords:!1},Hr=new Dt(jt);class Vt extends Oe{#e=[];#r;constructor(e,{signal:r}={}){super(async f=>{this.#r.write(Hr.encode(f))},{signal:r}),this.#r=e;const s=new Vr(jt);s.on("data",f=>{st(f)&&this[T].dispatchMessage(f)}),s.on("error",()=>{this.close()});const n=f=>{s.write(f)},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 Zr(t,e){const{promise:r,reject:s,resolve:n}=Gr(),i=fr(t),f=e?.signal,m=()=>{i.off("connect",g),i.off("error",M),f?.removeEventListener("abort",v)},y=R=>{m(),i.destroy(),s(R)},v=()=>{y(new Error("The connection was aborted"))},g=()=>{m();const R=new Vt(i,e);R[T].addEventListener("close",()=>{i.destroy()},{once:!0}),n(R)},M=R=>{y(R)};return f?.aborted?(y(new Error("The connection was aborted")),r):(i.once("connect",g),i.once("error",M),f?.addEventListener("abort",v,{once:!0}),r)}const Kt=ze("appetize.io:error:rpc");function nt(t,e){const r=new ur(new dr({errorListener:Kt}),Yr(t),{errorListener:Kt}),s=t[T].addEventListener("message",({detail:i})=>{r.receiveAndSend(i)}),n=t[T].addEventListener("close",()=>{s(),r.rejectAllPendingRequests("Transport closed")},{once:!0});for(const i in e){const f=e[i];f&&r.addMethod(i,f.bind(e))}return{rpc:r,unsub:()=>{s(),n()}}}function $t(t,e){const{rpc:r,unsub:s}=nt(t,e);return{client:r.client,unsub:s}}function Ue(t,e){const r=t[T].addEventListener("message",({detail:n})=>{if("method"in n)try{e({method:n.method,param:n.params})}catch{}}),s=t[T].addEventListener("close",r,{once:!0});return()=>{r(),s()}}function Yr(t){return new hr(t[T].send.bind(t[T]),()=>Math.floor(Math.random()*Number.MAX_SAFE_INTEGER)+1)}function it(t,e,{leftEffects:r=()=>({}),notifiesLeft:s,notifiesRight:n,rightEffects:i=()=>({})}={}){const f=nt(t,{}),m=nt(e,{}),y=[()=>{f.unsub(),m.unsub()}],v=()=>{for(const U of y)try{U()}catch{}},g=m.rpc.client,M=f.rpc.client;y.push(t[T].addEventListener("close",()=>{v()},{once:!0}),e[T].addEventListener("close",()=>{v()},{once:!0}));const R=r(g,M);for(const U in R){const C=R[U];C&&f.rpc.addMethod(U,C)}const L=i(M,g);for(const U in L){const C=L[U];C&&m.rpc.addMethod(U,C)}return qt(f.rpc,m.rpc,{notifies:s}),qt(m.rpc,f.rpc,{notifies:n}),v}function qt(t,e,{notifies:r}={}){t.applyServerMiddleware(async(s,n)=>{const i=r?.();if(i){const{id:m,...y}=n;i[T].send(y)}if(t.hasMethod(n.method))return await s(n);if(!n.id)return e.notify(n.method,n.params),null;const f=await e.request(n.method,n.params);return{id:n.id,jsonrpc:pr,result:f}})}function X(t,...e){t.notify(e[0],e[1],e[2])}const Xr=(...t)=>$t(...t),ot=["ArrowDown","ArrowLeft","ArrowRight","ArrowUp","Backspace","Enter","Tab"];function at(){const t=new Oe(async r=>{e[T].dispatchMessage(r)}),e=new Oe(async r=>{t[T].dispatchMessage(r)});return t[T].addEventListener("close",()=>{e.close()},{once:!0}),e[T].addEventListener("close",()=>{t.close()},{once:!0}),[t,e]}function Jt(t,e){const r=[],s=()=>{for(const n of r)n()};r.push(t[T].addEventListener("message",n=>e[T].send(n.detail))),r.push(t[T].addEventListener("close",s,{once:!0})),r.push(e[T].addEventListener("message",n=>t[T].send(n.detail))),r.push(e[T].addEventListener("close",s,{once:!0}))}const ae=ze("appetize.io:trace:transport:iframe");class Wt extends Oe{onmessage;#e;#r;constructor(e,{origin:r="*",signal:s}={}){super(async n=>{e.postMessage(n,this.#e)},{signal:s}),this.#r=e,this.#e=r,window.addEventListener("message",this.#t)}postMessage(e,r,s){ae("postMessage(legacy)",{message:e,targetOrigin:r,transfer:s}),this.#r.postMessage(e,r??this.#e,s)}handleClose(e){ae("close()"),window.removeEventListener("message",this.#t),super.handleClose(e)}#t=async e=>{if(ae("handleMessage()",e),e.source!==this.#r||(ae("handleMessage() -> source ok"),this.#e!=="*"&&e.origin!==this.#e))return;ae("handleMessage() -> origin ok");const r=e.data;if(!st(r)){ae("handleMessage() -> legacy"),this.onmessage?.(e);return}ae("handleMessage() -> jsonrpc"),this[T].dispatchMessage(r)}}function Le(){let t,e;return{promise:new Promise((s,n)=>{e=s,t=n}),reject:t,resolve:e}}const Qr=2*1024*1024,Gt=ze("appetize:client:acked-writable-stream");class es{unacked=0;#e;#r;#t;#s;#n=[];#i;constructor(e){this.#t=e,this.#i=e.window??Qr}abort(e){this.#a(e),this.#t.onAbort?.(e)}async close(){await this.#c(()=>this.unacked===0),this.#t.onClose?.()}fail(e){this.#a(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.#s&&(this.#s.acked+=r),this.#o()},s=>{this.fail(s)}),this.unacked>=this.#i&&!this.#s&&(this.#s={acked:0,at:performance.now()},Gt("window full: %d bytes unacked, writes stalled",this.unacked)),this.#c(()=>this.unacked<this.#i)}#o(){if(this.#s&&this.unacked<=this.#i/2){const e=performance.now()-this.#s.at;Gt("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)}#a(e){if(this.#r)return!1;this.#r={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={...Le(),until:e};return this.#n.push(r),r.promise}}class ts extends WritableStream{get unacked(){return this.#e.unacked}#e;constructor(e){const r=new es(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 rs=1024*1024;class ss{#e;#r=!1;#t;#s;constructor(e){this.#t=e}cancel(e){this.#n(),this.#t?.(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.#r)return;this.#s??=Le();const{promise:r}=this.#s;this.#e.enqueue(e),await r}start(e){this.#e=e}#n(){return this.#r?!1:(this.#r=!0,this.pull(),!0)}}class ns extends ReadableStream{#e;constructor({highWaterMark:e=rs,onCancel:r}={}){const s=new ss(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 is{closed;readable;writable;#e=[];#r;#t;#s;#n;#i;#o="starting";constructor(e,{onClose:r,receiveBuffer:s,sendWindow:n,signal:i}){if(this.#i=e,this.#r=Le(),this.closed=this.#r.promise,this.closed.catch(os),this.#s=new ns({highWaterMark:s,onCancel:()=>{this.#a(void 0)}}),this.readable=this.#s,this.#n=new ts({onAbort:()=>{this.#a(void 0)},onClose:()=>{this.#a(void 0)},onError:f=>{this.#a(f)},send:f=>e.request("appetizeio.device.server.debug.adbTunnel.data",{data:f}),window:n}),this.writable=this.#n,i){const f=()=>{this.#a(i.reason)};i.addEventListener("abort",f,{once:!0}),this.#e.push(()=>{i.removeEventListener("abort",f)})}this.#e.push(()=>{r(this)})}close=()=>{this.#a(void 0)};detach(){this.#a(void 0,{notifyServer:!1})}async handleData(e){this.#o==="open"&&await this.#s.push(e)}handleStopped({error:e}){this.#o==="open"&&this.#a(e?new Error(e):void 0)}async start(){try{await this.#i.request("appetizeio.device.server.debug.adbTunnel.start",void 0)}catch(e){throw this.#a(e),e}if(this.#o==="closed")throw this.#t?this.#t:new Error("The adb tunnel closed before it started");this.#o="open"}async[Symbol.asyncDispose](){this.close();try{await this.closed}catch{}}#a(e,{notifyServer:r=!0}={}){if(this.#o!=="closed"){this.#o="closed",this.#t=e,r&&X(this.#i,"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.#r.reject(e):this.#r.resolve(void 0)}}}function os(){}class as{readable;ready;#e=[];#r=!1;#t;#s;#n;constructor({label:e,onClose:r,signal:s}){this.#s=e,this.ready=new Promise((i,f)=>{this.#n={reject:f,resolve:i}});let n;if(this.readable=new ReadableStream({cancel:()=>{this.#o()},start:i=>{n=i}}),!n)throw new Error("ReadableStream controller was not initialized");if(this.#t=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.#i()};fail(e){this.#i(e)}handleItem(e){this.#t.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()}}#i(e){this.#r||(this.#t.close(),this.#o(e))}#o(e){this.#r=!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 cs{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 Ht extends cs{#e;constructor(e){super({start:e.start,stop:e.stop}),this.#e=e.label}async createStream({signal:e}={}){e?.throwIfAborted();const r=new as({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 ls{#e;#r;#t;#s;constructor(e){this.#s=e,this.#r=new Ht({label:"Log stream",start:()=>e.request("appetizeio.device.server.debug.log.start"),stop:()=>{X(e,"appetizeio.device.server.debug.log.stop",void 0)}}),this.#t=new Ht({label:"Proxy intercept stream",start:()=>e.request("appetizeio.device.server.debug.proxyIntercept.start"),stop:()=>{X(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 is(this.#s,{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 ct(t){return{...fs(t),index:t.index,within:t.within?ct(t.within):void 0}}function fs(t){switch(t.by){case"testId":return{by:"testId",testId:t.testId};case"text":return{by:"text",text:us(t.text)}}}function us(t){return typeof t=="string"?{kind:"exact",value:t}:{flags:t.flags,kind:"regex",source:t.source}}function ds(t){return{press:e=>{X(t,"appetizeio.device.server.keyboard.press",{key:e})}}}function hs({onRequest:t,parent:e,proxyInlet:r,signal:s}){const n=new Wt(e,{signal:s}),i=[()=>{n.close()}];return Jt(n,r),t&&i.push(Ue(n,f=>{t(f,{source:"parent"})})),{cleanup:()=>{for(const f of i)f()},notifies:()=>e===globalThis.window?void 0:n}}const ps="@appetizeio/rpc:playwrightAdapter",_e=Symbol.for(ps);function ys(t){window[_e]&&console.warn("playwright exposed more than once, overwriting previous adapter");const e={send(r){t[T].send(r)},subscribe(r){return t[T].addEventListener("message",s=>{r(s.detail)})}};return window[_e]=e,()=>{window[_e]===e&&delete window[_e]}}function ws({onRequest:t,proxyInlet:e}){const[r,s]=at(),i=[ys(s),()=>{r.close()}];return Jt(r,e),t&&i.push(Ue(r,f=>{t(f,{source:"parent"})})),{cleanup:()=>{for(const f of i)f()},notifies:()=>r}}function De(t){return t.by==="position"?{by:"position",x:t.x,y:t.y}:{...ct(t),x:t.x,y:t.y}}function ms(t){return"to"in t?{from:De(t.from),kind:"path",to:De(t.to)}:{direction:t.direction,distance:t.distance,from:t.from?De(t.from):void 0,kind:"direction"}}function bs(t){return{down:(e,r)=>{X(t,"appetizeio.device.server.touch.down",{x:e,y:r})},move:(e,r)=>{X(t,"appetizeio.device.server.touch.move",{x:e,y:r})},up:(e,r)=>{X(t,"appetizeio.device.server.touch.up",{x:e,y:r})}}}const gs=new Set(ot),Es=/^(?<key>[A-Za-z]+)>(?<repeat>\d+)\/$/u,Ss=/(\{\{|\{[^{}]*\})/u;function vs(t){const e=[];let r="";function s(){r.length>0&&(e.push({kind:"text",text:r}),r="")}for(const[n,i]of t.split(Ss).entries())if(n%2===0){if(i.includes("{"))throw new Error(`Unclosed "{" in ${JSON.stringify(t)}`);r+=i}else i==="{{"?r+="{":(s(),e.push(Os(i.slice(1,-1))));return s(),e}function As(t,e){if(!gs.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: ${ot.join(", ")}. Type characters as text, and escape a literal "{" as "{{".`)}function Os(t){const e=Es.exec(t)?.groups,r=e?.key??t;if(As(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 Zt(t){return t?.[ks]}class Is{readable;ready;get dimensions(){return this.#s}#e=[];#r=!1;#t;#s;#n;#i;constructor({onClose:e,requestKeyFrame:r,signal:s}){this.#n=r,this.ready=new Promise((i,f)=>{this.#i={reject:f,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.#t=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.#o()};fail(e){this.#o(e)}handleChunk(e){if(this.#i){if(e.type!=="key")return;const{resolve:r}=this.#i;this.#i=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.#t.enqueue(e)}requestKeyFrame=()=>{this.#r||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()}}#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("Video stream closed before the first key chunk")),this.#i=void 0}}class xs{#e=!1;#r;#t;#s=new Set;constructor(e){this.#r=e}close(){this.#t=void 0;for(const e of[...this.#s])e.close()}async createStream({signal:e}={}){e?.throwIfAborted();const r=new Is({onClose:s=>{this.#i(s)},requestKeyFrame:()=>{this.#o()},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.#t?(this.#o(),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)}#i(e){this.#s.delete(e),!(this.#s.size>0||!this.#t)&&(this.#t=void 0,X(this.#r,"appetizeio.device.server.video.stop",void 0))}#o(){this.#e||(this.#e=!0,X(this.#r,"appetizeio.device.server.video.requestKeyFrame",void 0))}}class Ms{debug;keyboard;touch;video;#e;#r=[];#t;constructor(e,r={}){const s=Zt(r)??{},{baseUrl:n,onClose:i,signal:f}=r;this.#e=n?Rs(n):void 0;const{onRequest:m,parent:y,proxyRequest:v}=s,g=Ts(m);f?.addEventListener("abort",this.close);const[M,R]=at(),[L,U]=at();this.#r.push(()=>{M.close(),R.close(),L.close(),U.close()}),this.#r.push(it(U,e,{leftEffects:v}));const C=y==="playwright"?ws({onRequest:g,proxyInlet:L}):y?hs({onRequest:g,parent:y,proxyInlet:L,signal:f}):void 0;C&&this.#r.push(C.cleanup),this.#r.push(it(R,L,{notifiesLeft:C?.notifies}));const{client:W,unsub:ye}=Xr(M,{"appetizeio.device.client.debug.adbTunnel.data":z=>G.handleAdbTunnelData(z),"appetizeio.device.client.debug.adbTunnel.stopped":async z=>{G.handleAdbTunnelStopped(z)},"appetizeio.device.client.debug.log.entry":async z=>{G.handleLogEntry(z)},"appetizeio.device.client.debug.proxyIntercept.event":async z=>{G.handleProxyInterceptEvent(z)},"appetizeio.device.client.video.chunk":async z=>{O.handleChunk(z)}});this.#t=W,this.#r.push(ye);const G=new ls(this.#t);this.#r.push(()=>{G.close()});const O=new xs(this.#t);this.#r.push(()=>{O.close()}),this.debug=G,this.keyboard=ds(this.#t),this.touch=bs(this.#t),this.video=O,g&&(this.#r.push(Ue(R,z=>{g(z,{source:"self"})})),e instanceof Wt&&this.#r.push(Ue(e,z=>{g(z,{source:"iframe"})}))),this.#r.push(()=>i?.())}async clearKeychain(){await this.#t.request("appetizeio.device.server.clearKeychain")}close=()=>{for(const e of this.#r)try{e()}catch(r){console.error("Device cleanup error:",r)}};async inspect(e,r){return await this.#t.request("appetizeio.device.server.inspect",{options:r,selector:e?ct(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){return await this.#t.request("appetizeio.device.server.rotate",{orientation:e})}async screenshot(){const e=await this.#t.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.#t.request("appetizeio.device.server.swipe",{gesture:ms(e),options:r})}async tap(e,r){await this.#t.request("appetizeio.device.server.tap",{options:r,selector:De(e)})}async type(e,r){await this.#t.request("appetizeio.device.server.type",{options:r,steps:vs(e)})}}function Rs(t){const e=new URL(t);return e.protocol==="ws:"?e.protocol="http:":e.protocol==="wss:"&&(e.protocol="https:"),e.href}const Ts=t=>{if(t)return(e,r)=>{e.method.startsWith("appetizeio.device.server.")&&t(e,r)}},Ps={dateStyle:"medium",timeStyle:"short"},Cs=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(?::\d{2}(?:\.\d+)?)?(?:Z|[+-]\d{2}:\d{2})$/;function Ne(t){return Array.isArray(t)?t.map(Ne).join(", "):typeof t=="boolean"?t?"yes":"no":typeof t=="number"?t.toLocaleString():Us(t)}function Us(t){if(Cs.test(t)){const r=new Date(t);if(!Number.isNaN(r.getTime()))return r.toLocaleString(void 0,Ps)}const e=Et();return t===e?"~":t.startsWith(`${e}${Er}`)?`~${t.slice(e.length)}`:t}function Yt(){return process.env.APPETIZE_CLI_HOME??te(Et(),".appetize","cli","sessions")}function lt(t){return te(Yt(),t)}class Be 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 Ie extends Be{sessionDir;constructor(e,{cause:r,details:s={},sessionId:n}){const i=lt(n);super(e,Object.assign({sessionDir:i},s),r),this.name="SessionError",this.sessionDir=i}static wrap(e,r){if(e instanceof Ie||e instanceof ce)return e;const s=e instanceof Error?e.message:String(e),n=e instanceof Be?e.details:{};return new Ie(s,{cause:e,details:n,sessionId:r})}hints(){return[`Check the session logs for details: ${Ne(this.sessionDir)}`]}}class Ls extends Ie{constructor(e){super(`Session ${e} already exists`,{sessionId:e}),this.name="SessionAlreadyExistsError"}hints(){return[`Pass --force to replace it, deleting ${Ne(this.sessionDir)}`]}}class ce extends Be{#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 _s(t,e,r){const s=e instanceof Error?e.message:String(e);if(!(e instanceof Be))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(`
2
- `)}function ft(t){try{return process.kill(t,0),!0}catch{return!1}}const Ds=["SIGINT","SIGTERM"],Ns=150;function Bs(t){const e=new AbortController,r=setInterval(()=>{ft(t)||(clearInterval(r),e.abort(new Error("The device session exited")))},Ns);return r.unref(),e.signal}function Xt(){const t=new AbortController;for(const e of Ds)process.once(e,()=>{t.abort(new Error(`Received ${e}`))});return t.signal}function Fs(t,e){return new Promise((r,s)=>{if(e.aborted){s(Qt(e.reason));return}const n=()=>{clearTimeout(i),s(Qt(e.reason))},i=setTimeout(()=>{e.removeEventListener("abort",n),r()},t);e.addEventListener("abort",n,{once:!0})})}function Qt(t){return t instanceof Error?t:new Error(String(t))}function zs(t){const e=t.at(-1);return{options:Ks(e)?e:{},positionals:t.slice(0,-1).filter(r=>typeof r=="string"),signal:Xt()}}function js(t,e){const r=er(t,e);return r===void 0?void 0:tr(r,e)}function er(t,e){if(t===void 0)return;const r=typeof t=="boolean"?Number.NaN:Number(t);if(!Number.isFinite(r))throw new ce(`${e} expects a number, e.g., ${e}=-0.1`);return r}function ut(t,e){if(t!==void 0){if(typeof t!="string"||t==="")throw new ce(`${e} needs a value`);return t}}function tr(t,e){if(!(t>=0&&t<=1))throw new ce(`${e} expects a number between 0 and 1`);return t}function Vs(t,e){const r=ut(t,e);if(r===void 0)throw new ce(`${e} needs a value`);return r}function Ks(t){return typeof t=="object"&&t!==null}const $s="APPETIZEIO_FEATURE_FLAGS";function qs(){const t={};for(const e of(process.env[$s]??"").split(",")){const r=e.trim();r!==""&&(t[r]=!0)}return t}function Js(){const t=process.env.APPETIZE_API_TOKEN;if(!t)throw new Error("APPETIZE_API_TOKEN must be set");return t}function rr(t){return ut(t.endpoint,"--endpoint")??Ws()}function Ws(){const t=process.env.APPETIZE_ENDPOINT?.trim();return t===""?void 0:t}const Gs="https://appetize.io";async function sr(t,{authorize:e=!0,commandOptions:r={},query:s={},...n}={}){const i=new URL(t,rr(r)??Gs);for(const[y,v]of Object.entries(s))i.searchParams.set(y,v);const f=new Headers(n.headers);e&&f.set("x-api-key",Js());const m=await fetch(i,{...n,headers:f});if(!m.ok)throw new Error(`The webserver rejected the request (${String(m.status)})`);return await m.json()}const nr=["android","ios"];function ir(t={},e){return sr("/api/v2/service/devices",{authorize:!1,commandOptions:t,signal:e})}function Hs(t){return nr.includes(t)}async function Zs(t,e={}){return(await ir(e)).find(s=>s.id===t)?.platform}function Ys(t){let e={...t,updatedAt:new Date().toISOString()};return{path:ht(e.sessionId),save:r=>(e={...e,...r,updatedAt:new Date().toISOString()},on(e),e)}}function or(t){const e=t.state?.phase;return e==="ended"||e==="error"?!1:ft(t.pid)}function Xs(){const t=Yt();return gt(t,{recursive:!0}),gr(t).map(e=>dt(e)).filter(e=>e!==void 0)}function Qs(t){if(t!==void 0){const r=dt(t);if(!r)throw new Error(`No session found for id ${t}`);return r}const e=Xs().filter(or);if(e.length===0)throw new Error("No active sessions");if(e.length>1)throw new ce("There are multiple active sessions",["Specify --session-id to pick one"]);return e[0]}function dt(t){try{return JSON.parse(mr(ht(t),"utf8"))}catch{return}}function en(t){br(lt(t),{force:!0,recursive:!0})}function tn(t){return te(ke(t),"control.sock")}function ar(t){return te(ke(t),"daemon.log")}function rn(t){return te(ke(t),"device.log.jsonl")}function sn(t,e){return{daemon:ar(t),device:rn(t),...e==="intercept"?{network:nn(t)}:void 0}}function nn(t){return te(ke(t),"network.jsonl")}function ke(t){const e=lt(t);return gt(e,{recursive:!0}),e}function ht(t){return te(ke(t),"state.json")}function on(t){const e=ht(t.sessionId),r=`${e}.tmp`;yr(r,`${JSON.stringify(t,null,2)}
3
- `),wr(r,e)}const pt="APPETIZE_DAEMON_CONFIG";function an(){const t=process.env[pt];if(!t)throw new Error(`${pt} is not set`);return JSON.parse(t)}function cn(t){return JSON.stringify(t)}export{zs as A,_s as B,ot as C,Ms as D,zr as E,T as F,Lr as G,st as H,Zt as I,Le as J,an as K,Ys as L,Zs as M,Vt as N,it as O,tn as P,Xt as Q,Ie as S,Oe as T,ce as U,er as a,Fs as b,ir as c,Zr as d,nr as e,sr as f,Vs as g,ar as h,Hs as i,pt as j,or as k,ft as l,Bs as m,qs as n,rr as o,ut as p,dt as q,tr as r,cn as s,Ls as t,en as u,sn as v,js as w,Ne as x,$t as y,Qs as z};