@appetize/cli 0.23.0 → 0.24.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 +11 -0
- package/cli.js +10 -9
- package/daemon.js +2 -3
- package/package.json +1 -1
- package/skills/appetize/SKILL.md +2 -1
- package/skills/appetize/references/commands.md +7 -0
- package/stream-BowDfEJS.js +4 -0
- package/viewer.html +1 -1
- package/stream-DqsoC5l1.js +0 -3
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,16 @@
|
|
|
1
1
|
# @appetize/cli
|
|
2
2
|
|
|
3
|
+
## 0.24.0
|
|
4
|
+
|
|
5
|
+
### Minor Changes
|
|
6
|
+
|
|
7
|
+
- feat(session): `session start` sets the device's orientation, locale, timezone, location, appearance, font size, keyboards, autocorrect, soft keyboard and adb shell command
|
|
8
|
+
|
|
9
|
+
### Patch Changes
|
|
10
|
+
|
|
11
|
+
- fix(session): `session start` errors include the webserver's reason
|
|
12
|
+
- fix(session): `session start` rejects invalid options before spawning its daemon
|
|
13
|
+
|
|
3
14
|
## 0.23.0
|
|
4
15
|
|
|
5
16
|
### Minor Changes
|
package/cli.js
CHANGED
|
@@ -1,11 +1,12 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import
|
|
3
|
-
`}const
|
|
4
|
-
`)},
|
|
5
|
-
`)}return
|
|
2
|
+
import He from"sade";import{p as u,a as h,f as _,U as a,d as R,b as Ye,i as Je,c as Qe,e as et,r as te,g as E,h as T,j as tt,D as ot,s as nt,k as it,l as oe,m as ne,S as U,n as ie,o as re,q as se,v as rt,t as st,u as ae,w as at,x as ce,y as ct,z as pt,A as dt,B as lt,C as pe,E as de,F as ut,G as ft,H as mt,I as ht,J as gt,K as wt}from"./stream-BowDfEJS.js";import{existsSync as le,openAsBlob as yt,openSync as vt,closeSync as xt}from"node:fs";import{basename as z,extname as St,resolve as ue,dirname as bt,join as x,relative as Et}from"node:path";import{writeFile as fe,stat as At,rm as Ot,cp as It}from"node:fs/promises";import{spawn as Pt}from"node:child_process";import{fileURLToPath as me}from"node:url";import{humanId as Tt}from"human-id";import{homedir as $t}from"node:os";import kt from"debug";import Lt from"yocto-spinner";import Dt from"cli-table3";import"json-rpc-2.0";import"zod/mini";import"stream";import"module";import"node:net";const j=["closed","fullyOpen","partiallyOpen"],he=["back","menu","unlock","volumeDown","volumeUp"],ge=["home","lock"],we=[...ge,...he],F=["down","left","right","up"],ye=[{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 C({appId:e,buildNumber:t,created:o,id:n,platform:i,versionName:r}){return{appId:e,buildNumber:t,created:o,id:n,platform:i,versionName:r}}const Nt=["app"],_t=10,Rt=[{fields:ye,key:"builds"},{header:"Total",key:"total"},{header:"Next page",key:"nextPage"}];async function Ut({options:e,signal:t}){const o=u(e.app,"--app"),n=h(e.limit,"--limit")??_t,i=h(e.page,"--page"),r={limit:String(n)};o!==void 0&&(r.appId=o),i!==void 0&&(r.page=String(i));const s=await _("/api/v2/builds",{commandOptions:e,query:r,signal:t});return{builds:s.builds.map(C),nextPage:s.nextPage,total:s.total}}const zt=["note","tags"],ve=12e4,jt=2e3,M=[".apk",".apks",".zip",".tar.gz",".tgz"],Ft={".apk":"android",".apks":"android",".tar.gz":"ios",".tgz":"ios",".zip":"ios"},Ct=ye;async function Mt({options:e,positionals:[t],progress:o,signal:n}){const i=Gt(t),r=z(t);o.status(`Uploading ${r}`);const s=await Kt(t,i,e,n);if(e.wait!==!0)return o.status(`Uploaded ${r}`),C(s);o.step(`Uploaded ${r}`),o.status("Waiting for build metadata");const p=await Bt(s.id,e,n);return o.status(`Processed ${r}`),C(p)}async function Bt(e,t,o){const n=h(t.timeout,"--timeout")??ve,i=Date.now()+n;for(;;){const r=await _(`/api/v2/builds/${e}`,{commandOptions:t,signal:o});if(r.appId!==void 0)return r;if(Date.now()>=i)throw new Error(`Build ${e} is still being processed after ${String(n)}ms; find it with 'appetize build list'`);await R(jt,o)}}async function qt(e){if(!le(e))throw new Error(`No build file at ${e}`);return await yt(e)}function Gt(e){const t=e.toLowerCase(),o=M.find(n=>t.endsWith(n));if(o===void 0)throw new a(`Cannot tell the platform of ${z(e)}; upload a ${M.join(", ")} file`);return Ft[o]}async function Kt(e,t,o,n){const i=new FormData;i.set("platform",t);const r=u(o.note,"--note");r!==void 0&&i.set("note",r);const s=u(o.tags,"--tags");return s!==void 0&&i.set("tags",s),i.set("file",await qt(e),z(e)),await _("/api/v2/builds",{body:i,commandOptions:o,method:"POST",signal:n})}const Zt=["platform"],Vt=[{fields:[{header:"ID",key:"id"},{header:"Name",key:"name"},{header:"Platform",key:"platform"},{header:"OS versions",key:"osVersions"}],key:"devices"}];async function Wt({options:e,signal:t}){const o=Xt(e.platform);return{devices:(await Ye(e,t)).filter(i=>o===void 0||i.platform===o).map(Ht)}}function Xt(e){const t=u(e,"--platform");if(t!==void 0){if(!Je(t))throw new a(`--platform expects one of: ${Qe.join(", ")}`);return t}}function Ht({id:e,name:t,osVersions:o,platform:n}){return{id:e,name:t,osVersions:o,platform:n}}const Yt="cli-fold",Jt=async({device:e,positionals:[t]})=>{if(!Qt(t))throw new a(`Hinge must be one of: ${j.join(", ")}`);await e.fold(t)};function Qt(e){return j.some(t=>t===e)}const eo=async({device:e,options:t,positionals:[o]})=>{await e.gesture(oo(o),to(t))};function to(e){const t=h(e.timeout,"--timeout");return t===void 0?void 0:{timeout:t}}function oo(e){let t;try{t=et(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 no="APPETIZE_OUTPUT";function io(e,t,o){return{format:ro(e,t),progress:so(e,o)}}function B(e,{extension:t,strict:o=!1}){const n=St(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 ro(e,t){if(e.json===!0)return"json";if(e.json===!1)return"text";const o=process.env[no]?.trim();return o==="json"||o==="text"?o:t.isTTY===!0?"text":"json"}function so(e,t){return e.quiet===!0?"silent":t.isTTY===!0&&process.env.TERM!=="dumb"&&!("CI"in process.env)?"interactive":"silent"}const S=["text","testId"],g="select",A={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"}},q="index",$="position",G="x",K="y";function xe(e,{prefix:t=g}={}){return S.reduce((o,n)=>{const{help:i,suffix:r}=A[n];return o.option(`--${d(t,r)}`,i)},e).option(`--${d(t,q)}`,"Which match when multiple (0-based)")}function Z(e,t={}){const{prefix:o=g}=t;return xe(e,t).option(`--${d(o,$)}`,"Screen position to use as x,y (0-1), e.g., 0.5,0.75").option(`--${d(o,G)}`,"Horizontal position within the element (0-1, outside allowed)").option(`--${d(o,K)}`,"Vertical position within the element (0-1, outside allowed)")}function Se(e,{prefix:t=g}={}){const o=W(e,t);if(o.length===0)throw new a(`A selector is required: pass one of ${L(S,t)}`);if(o.length>1)throw new a(`Only one selector may be given, got ${L(o,t)}`);const[n]=o,i=Pe(e,d(t,A[n].suffix)),r=h(e[d(t,q)],`--${d(t,q)}`);switch(n){case"testId":return{by:"testId",index:r,testId:i};case"text":return{by:"text",index:r,text:po(i)}}}function be(e){const t=h(e.timeout,"--timeout");return t===void 0?void 0:{timeout:t}}function ao(e,{prefix:t=g}={}){return Oe(e,t)?Se(e,{prefix:t}):void 0}function k(e,{prefix:t=g}={}){return Oe(e,t)?Ee(e,{prefix:t}):void 0}function Ee(e,{prefix:t=g}={}){const o=d(t,$),n=e[o],i=Ie(e,d(t,G)),r=Ie(e,d(t,K));if(n===void 0){if(W(e,t).length===0)throw new a(`A selector is required: pass one of ${O({prefix:t})}`);return{...Se(e,{prefix:t}),x:i,y:r}}if(W(e,t).length>0)throw new a(`--${o} may not be combined with ${L(S,t)}`);if(i!==void 0||r!==void 0)throw new a(`--${o} may not be combined with --${d(t,G)} or --${d(t,K)}`);return co(Pe(e,o),o)}function O(e={}){const{prefix:t=g}=e;return`${L(S,t)}, --${d(t,$)}`}function V(e={}){const{prefix:t=g}=e;return[...Ae(e),d(t,$)]}function Ae({prefix:e=g}={}){return S.map(t=>d(e,A[t].suffix))}function W(e,t){return S.filter(o=>e[d(t,A[o].suffix)]!==void 0)}function d(...e){return e.filter(Boolean).join("-")}function L(e,t){return e.map(o=>`--${d(t,A[o].suffix)}`).join(", ")}function Oe(e,t){return Object.entries(e).some(([o,n])=>n!==void 0&&o.startsWith(`${t}-`))}function Ie(e,t){return h(e[t],`--${t}`)}function co(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(r=>Number(r.trim()));return{by:"position",x:te(n,`--${t}`),y:te(i,`--${t}`)}}function po(e){const t=/^\/(.*)\/([a-z]*)$/s.exec(e);return t?new RegExp(t[1],t[2]):e}function Pe(e,t){return E(e[t],`--${t}`)}const lo=Ae(),uo=async({device:e,options:t,positionals:[o]})=>{const n=fo(o),i=ao(t),r=await e.inspect(i,be(t)),s=mo(r,t.pretty===!0);await fe(n,s);const p=Buffer.byteLength(s),c=Te(r.roots);return i?{bytes:p,matches:r.roots.length,nodes:c,output:n}:{bytes:p,nodes:c,output:n}};function Te(e){return e.reduce((t,o)=>t+1+Te(o.children),0)}function fo(e="inspect"){return B(e,{extension:".json"})}function mo(e,t){return`${JSON.stringify(e,null,t?2:void 0)}
|
|
3
|
+
`}const ho=async({device:e})=>{await e.clearKeychain()},go=async({device:e,positionals:[t]})=>{await e.open(wo(t))};function wo(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 yo=new Set(we),vo=async({device:e,positionals:[t]})=>{if(!xo(t))throw new a(`Button must be one of: ${we.join(", ")}`);await e.press(t)};function xo(e){return typeof e=="string"&&yo.has(e)}const So=async({control:e,options:t,positionals:[o]})=>{const{path:n}=await e.recordStart({force:t.force===!0,path:Eo(o)});return{path:n}},bo=async({control:e})=>{const{path:t}=await e.recordStop();return{path:t}};function Eo(e){const t=ue(B(e,{extension:".mp4",strict:!0})),o=bt(t);if(!le(o))throw new a(`No such directory: ${o}`);return t}const Ao=async({device:e,positionals:[t]})=>{if(!Oo(t))throw new a(`Orientation must be one of: ${T.join(", ")}`);await e.rotate(t)};function Oo(e){return T.some(t=>t===e)}const Io=async({device:e,positionals:[t]})=>{const o=await e.screenshot(),n=To(o.mimeType,t);return await fe(n,o.data),{bytes:o.data.byteLength,output:n}};function Po(e){const t=e.split("/").at(1);return`.${t==="jpeg"?"jpg":t??"png"}`}function To(e,t="screenshot"){return B(t,{extension:Po(e)})}function $o(e){const t=me(new URL("./daemon.js",import.meta.url)),o=vt(tt(e.sessionId),"a"),n=Pt(process.execPath,[t],{detached:!0,env:{...process.env,[ot]:nt(e),DEBUG:ko(process.env.DEBUG)},stdio:["ignore",o,o]});if(xt(o),n.unref(),n.pid===void 0)throw new Error("Failed to spawn the session daemon");return n.pid}function ko(e){return e?`${e},appetize:daemon`:"appetize:daemon"}const Lo=/^[a-z0-9](?:[a-z0-9._-]{0,62}[a-z0-9])?$/i;function Do(){return Tt({capitalize:!1,separator:"-"})}function No(e){if(!Lo.test(e))throw new a('--session-id must use letters, digits, ".", "-" or "_"');return e}const $e=1e4;function ke(e){if(!it(e))return!1;try{process.kill(e.pid,"SIGTERM")}catch{}return!0}async function Le(e,t){(ke(e)||Ro(e))&&await _o(e,t)}async function _o({pid:e,sessionId:t},o){const n=ne(e);try{await R($e,AbortSignal.any([o,n]))}catch(i){if(n.aborted||!oe(e))return;throw i}throw new U(`Session ${t} did not stop in time`,{sessionId:t})}function Ro({endedAt:e,pid:t}){return e!==void 0&&Date.now()-Date.parse(e)<$e&&oe(t)}const Uo=["device-android-shell","device-appearance","device-font-size","device-ios-keyboards","device-locale","device-location","device-orientation","device-os-version","device-timezone"];function zo(e,t){const o=De({shell:u(e["device-android-shell"],"--device-android-shell"),softKeyboard:ie(e["device-android-soft-keyboard"],{defaultValue:!0})}),n=De({autocorrect:ie(e["device-ios-autocorrect"],{defaultValue:!0}),keyboards:Co(e["device-ios-keyboards"],"--device-ios-keyboards")});return{android:o,appearance:X(e["device-appearance"],se,"--device-appearance"),fontSize:X(e["device-font-size"],re,"--device-font-size"),id:t,ios:n,locale:u(e["device-locale"],"--device-locale"),location:Fo(e["device-location"]),orientation:X(e["device-orientation"],T,"--device-orientation"),osVersion:u(e["device-os-version"],"--device-os-version"),timezone:u(e["device-timezone"],"--device-timezone")}}function jo(e){return e!==""&&Number.isFinite(Number(e))}function De(e){return Object.values(e).some(t=>t!==void 0)?e:void 0}function X(e,t,o){const n=u(e,o);if(n===void 0)return;const i=t.find(r=>r===n);if(i===void 0)throw new a(`${o} expects one of ${t.join(", ")}`);return i}function Fo(e){const t=u(e,"--device-location");if(t===void 0)return;const o=t.split(",").map(r=>r.trim());if(o.length!==2||!o.every(jo))throw new a("--device-location expects <lat>,<lng>, e.g., 43.65,-79.38");const[n,i]=o.map(Number);return{latitude:n,longitude:i}}function Co(e,t){return e===void 0?void 0:(Array.isArray(e)?e:[e]).map(n=>E(n,t))}const Ne={"device.id":"<device>","device.location.latitude":"--device-location latitude","device.location.longitude":"--device-location longitude","launch.url":"--open"};function Mo(e,{endpointFromEnv:t=!1}={}){const o=t?{...Ne,endpoint:"APPETIZE_ENDPOINT"}:Ne;try{rt(e)}catch(n){throw n instanceof st?new a(n.issues.map(i=>Bo(i,o)).join(`
|
|
4
|
+
`)):n}}function Bo({code:e,message:t,path:o},n){const i=qo(o,n);switch(e){case"invalidValue":return`${i} ${t.replace(/^expected /,"expects ")}`;case"needsLaunchApp":return`${i} has no effect without --target, or with --no-launch-app`;case"needsTarget":return`${i} has no effect without --target`}}function qo(e,t){return t[e]??`--${e.split(".").filter(o=>!/^\d+$/.test(o)).map(o=>o.replaceAll(/([A-Z])/g,"-$1").toLowerCase()).join("-")}`}const Go=[...Uo,"open","proxy","target"],Ko=150,Zo={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"},Vo=[{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 Wo(e,{onPhase:t,signal:o}){let n;for(;;){const i=ce(e),r=i?.state?.phase;if(r&&r!==n&&(n=r,t?.(r)),i&&r==="ready"&&i.controlSocket!==void 0)return{...i,controlSocket:i.controlSocket};if(r==="error")throw new Error(i?.endedReason??"The session failed to start");if(r==="ended")throw new Error(i?.endedReason??"The session ended");await R(Ko,o)}}function Xo(e){const t=u(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 Ho(e){if(!(e===void 0||e===!1)){if(e===""||e==="intercept")return"intercept";if(typeof e!="string"||!Jo(e))throw new a("--proxy expects 'intercept' or an http:// url, e.g., http://proxy:8080");return e}}async function Yo({options:e,positionals:t,progress:o,signal:n}){const[i]=t,r=u(e.target,"--target")??en(e);if(r===void 0&&!process.env.APPETIZE_API_TOKEN)throw new a("APPETIZE_API_TOKEN must be set without a target",["Set APPETIZE_API_TOKEN, or pass --target"]);const s=u(e["session-id"],"--session-id"),p=e.force===!0;if(p&&s===void 0)throw new a("--force needs --session-id");const c=s===void 0?Do():No(s),l={device:zo(e,i),endpoint:at(e),featureFlags:ae(),launch:tn(Xo(e.open)),proxy:Ho(e.proxy),sessionId:c,target:r};Mo(l,{endpointFromEnv:e.endpoint===void 0});const f=ce(c);if(f!==void 0){if(!p)throw new ct(c);o.status(`Replacing session ${c}`),await Le(f,n),pt(c)}$o(l),o.step(`Session ${c}`);const v=dt(c,l.proxy);if(e.wait===!1)return{logs:v,sessionId:c};const I=await Wo(c,{onPhase:P=>{Qo(P)&&o.status(Zo[P]??"Starting the session")},signal:n}).catch(P=>{throw U.wrap(P,c)});return{adbSerial:I.adbSerial,baseUrl:I.baseUrl,controlSocket:I.controlSocket,logs:v,sessionId:c,viewerUrl:I.viewerUrl}}function Jo(e){return e.startsWith("http://")}function Qo(e){return e!=="ended"&&e!=="error"}function en(e){const t=e._;return Array.isArray(t)&&typeof t[0]=="string"?t[0]:void 0}function tn(e){return e===void 0?void 0:{url:e}}const on=async({options:e,progress:t,record:o,signal:n})=>(e.wait===!1?ke(o):(t.status(`Stopping session ${o.sessionId}`),await Le(o,n)),{sessionId:o.sessionId}),_e="appetize",nn=me(new URL(`./skills/${_e}/`,import.meta.url)),H=["agents","claude","codex","copilot","cursor"],Re=["project","user"],rn={agents:".agents",claude:".claude",codex:".codex",copilot:".copilot",cursor:".cursor"},sn=x(".agents","skills"),an=["claude","agents"];function cn(e){return H.some(t=>t===e)}function pn(e){return Re.some(t=>t===e)}async function dn(e){const t=e.agents??await ln(e),o=await Promise.all(t.map(n=>Ue(n,e)));return[...new Set(o.flat())]}async function Ue(e,t){const o=ze(e,t);if(e==="claude")return[x(o,"skills")];const n=x(t.root,sn);return t.scope==="project"?[n]:await je(o)?[n,x(o,"skills")]:[n]}function ze(e,t){if(e==="claude"&&t.scope==="user"){const o=process.env.CLAUDE_CONFIG_DIR?.trim();if(o)return ue(o)}return x(t.root,rn[e])}async function ln(e){const o=(await Promise.all(H.map(async n=>await un(n,e)?n:void 0))).filter(n=>n!==void 0);return o.length>0?o:an}async function un(e,t){const o=[ze(e,t),...await Ue(e,t)];return(await Promise.all(o.map(i=>je(i)))).includes(!0)}async function je(e){try{return(await At(e)).isDirectory()}catch{return!1}}const fn=["agent","scope"];async function mn({options:e,signal:t}){const o=wn(e.scope),n=gn(e.agent),i=o==="user"?$t():process.cwd(),r=await dn({agents:n,root:i,scope:o}),s=[];for(const p of r){t.throwIfAborted();const c=x(p,_e);await Ot(c,{force:!0,recursive:!0}),await It(nn,c,{recursive:!0}),s.push(o==="user"?c:Et(i,c))}return{installed:s}}function hn(e){const t=E(e,"--agent");if(!cn(t))throw new a(`--agent expects one of ${H.join(", ")}`);return t}function gn(e){return e===void 0?void 0:(Array.isArray(e)?e:[e]).map(o=>hn(o))}function wn(e){if(e===void 0)return"project";const t=E(e,"--scope");if(!pn(t))throw new a(`--scope expects one of ${Re.join(", ")}`);return t}const w="from",y="to",yn=[...V({prefix:w}),...V({prefix:y})],vn=async({device:e,options:t})=>{await e.swipe(En(t),On(t))};function xn(e){return F.some(t=>t===e)}function Sn(e){if(e===void 0)return;const t=E(e,"--direction");if(!xn(t))throw new a(`--direction expects one of ${F.join(", ")}`);return t}function bn(e,t){const o=lt(e.distance,"--distance");if(k(e,{prefix:y})!==void 0)throw new a(`--direction may not be combined with --${y}-*`);return{direction:t,distance:o,from:k(e,{prefix:w})}}function En(e){const t=Sn(e.direction);return t===void 0?An(e):bn(e,t)}function An(e){if(e.distance!==void 0)throw new a("--distance is only valid with --direction");return{from:Fe(k(e,{prefix:w}),w),to:Fe(k(e,{prefix:y}),y)}}function On(e){const t=h(e.duration,"--duration"),o=h(e.timeout,"--timeout");return t===void 0&&o===void 0?void 0:{duration:t,timeout:o}}function Fe(e,t){if(e===void 0)throw new a(`A swipe needs --direction, or both endpoints: pass one of ${O({prefix:t})}`);return e}const In=V(),Pn=async({device:e,options:t})=>{const o=Ee(t);await e.tap(o,be(t))},Tn=async({device:e,options:t,positionals:[o]})=>{await e.type(o,$n(t))};function $n(e){const t=h(e.delay,"--delay");return t===void 0?void 0:{delay:t}}const Y=kt("appetize:cli"),kn={fail:()=>{},status:()=>{},step:()=>{},succeed:()=>{}};function Ln(e,t,o){return e==="interactive"?Dn(t,o):kn}function Dn(e,t){const o=Lt({handleSignals:!1,stream:e});let n=0;const i=()=>{o.stop()};t.addEventListener("abort",i,{once:!0});const r=()=>(process.off("exit",i),o.isSpinning);return{fail:()=>{r()&&o.stop()},status:s=>{if(!t.aborted){if(o.isSpinning){o.text=s;return}n=Date.now(),process.once("exit",i),o.start(s)}},step:s=>{e.write(`\u25B8 ${s}
|
|
5
|
+
`)},succeed:()=>{if(!r())return;const s=Math.round((Date.now()-n)/1e3);o.success(`${o.text} (${String(s)}s)`)}}}const Nn=new Set(["adb","api","apk","id","os","url"]),_n={bottom:"","bottom-left":"","bottom-mid":"","bottom-right":"",left:"","left-mid":"",mid:"","mid-mid":"",middle:" ",right:"","right-mid":"",top:"","top-left":"","top-mid":"","top-right":""},Ce=2,Rn=10;function Un(e){return e.split(/(?=[A-Z])/).map((t,o)=>{const n=t.toLowerCase();return Nn.has(n)?n.toUpperCase():o===0?n.charAt(0).toUpperCase()+n.slice(1):n}).join(" ")}function zn(e,t,o){return Q(e)?Ze(e,t,o):D(e,{fields:t,key:""},o)}function jn(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 Me(e){return new Dt({chars:_n,head:e,style:{border:[],head:[],"padding-left":0,"padding-right":Ce}})}function Be(e,t){return e.find(o=>o.key===t)}function qe(e,t){return t?.header??Un(e)}function J(e){return e!=null}function Q(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Ge(e){return["boolean","number","string"].includes(typeof e)}function Ke(e,t){const o=new Set(t),n=e.map(r=>r.key).filter(r=>o.has(r)),i=new Set(e.filter(r=>r.hidden).map(r=>r.key));return[...new Set([...n,...t])].filter(r=>!i.has(r))}function Ze(e,t,o){const n=new Map(Object.entries(e)),i=Ke(t,[...n.keys()]).filter(f=>J(n.get(f))),r=i.map(f=>Be(t,f)),s=i.map((f,v)=>qe(f,r[v])),p=Math.max(0,...s.map(f=>f.length))+Ce,c=o===void 0?void 0:o-p-1,l=Me();return l.push(...i.map((f,v)=>[s[v],D(n.get(f),r[v],c)])),Ve(l.toString())}function Fn(e,t){const o=e.map(s=>new Map(Object.entries(s))),n=Ke(t,o.flatMap(s=>[...s.keys()])),i=n.map(s=>Be(t,s)),r=Me(n.map((s,p)=>qe(s,i[p])));for(const s of o)r.push(n.map((p,c)=>{const l=s.get(p);return J(l)?D(l,i[c]):""}));return Ve(r.toString())}function D(e,t,o){if(t?.format)return N(t.format(e),o);if(Ge(e))return N(pe(e),o);if(Array.isArray(e)){const n=e.filter(J);return n.every(Ge)?N(pe(n),o):n.every(Q)?Fn(n,t?.fields??[]):n.map(i=>D(i,t,o)).join(`
|
|
6
|
+
`)}return Q(e)?Ze(e,t?.fields??[],o):N(String(e),o)}function Ve(e){return e.split(`
|
|
6
7
|
`).map(t=>t.trimEnd()).join(`
|
|
7
|
-
`)}function
|
|
8
|
-
`).flatMap(o=>
|
|
9
|
-
`)}function Sn(e,t){const o=[];let n="";for(const i of e.split(" ").flatMap(s=>vn(s,t)))n===""?n=i:n.length+1+i.length<=t?n=`${n} ${i}`:(o.push(n),n=i);return o.push(n),o}async function bn(e,t={}){const o=await se(e,{signal:t.signal});return new it(o,{...t,onClose:()=>{o.close(),t.onClose?.()}})}function En(e,t){if(e.controlSocket===void 0)throw new Error("Session is not ready");return bn(e.controlSocket,{baseUrl:e.baseUrl,signal:t})}async function In(e,t){if(e.controlSocket===void 0)throw new Error("Session is not ready");const o=await se(e.controlSocket,{signal:t}),{client:n}=st(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 Pn(e){return async({options:t,positionals:o,progress:n,signal:i})=>{const s=t["session-id"],r=rt(typeof s=="string"?s:void 0);try{return await e({options:t,positionals:o,progress:n,record:r,signal:AbortSignal.any([i,oe(r.pid)])})}catch(p){throw R.wrap(p,r.sessionId)}}}function An(e){return async({options:t,positionals:o,progress:n,record:i,signal:s})=>{const r=await En(i,s);try{return await e({device:r,options:t,positionals:o,progress:n,signal:s})}finally{r.close()}}}function Tn(e){return async({options:t,positionals:o,progress:n,record:i,signal:s})=>{const r=await In(i,s);try{return await e({control:r,options:t,positionals:o,progress:n,signal:s})}finally{r.close()}}}const On=["session-id",...Pt,...kt,...zt,...Qt,...Wo,...Po,...Yo,...an],kn=["json","quiet"];function $n(e){const t=qe("appetize").version(e).option("--json","Print the result as JSON").option("--quiet","Hide progress");return b(t,"session start <device>",o=>o.describe(["Start a device session and wait until it is ready","","Environment variables:","APPETIZE_API_TOKEN: Authorizes private APIs and targets; required with no target","APPETIZE_ENDPOINT: Appetize URL used when --endpoint is omitted"]).option("--device-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").option("--target","App, build or app group id to run").example("session start iphone15pro --target app_a1b2c3").example("session start iphone15pro").example("session start pixel7 --target app_a1b2c3 --device-os-version 14").example("session start iphone15pro --target app_a1b2c3 --open myapp://orders/42").example("session start iphone15pro --target app_a1b2c3 --session-id demo --force"),Do,{fields:Oo}),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"),jo),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"),Ot,{fields:Tt}),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(me)})`).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:Dt}),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: ${le.join(", ")}; Android only: ${de.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=>K(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"),cn),m(t,"swipe",o=>K(K(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"),Qo),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=>he(o.describe("Capture the view hierarchy of the screen, or of every element a selector matches")).option("--timeout","Milliseconds to wait for a match").option("--pretty","Pretty-print the JSON",!1).example("inspect").example("inspect --select-text 'Log in'").example("inspect hierarchy.json --pretty"),eo),m(t,"type <text>",o=>o.describe(`Type text; {...} presses a named key: ${pt.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"),pn),Me(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),Me(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"),Xo),t}function b(e,t,o,n,{fields:i}={}){const s=t.split(" ").filter(r=>!/^[<[]/.test(r)).join(" ");return o(e.command(t)).action(Nn({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"),Pn(n))}function m(e,t,o,n){return J(e,t,o,An(n))}function Me(e,t,o,n){return J(e,t,o,Tn(n))}function Be(e){return`${String(Date.now()-e)}ms`}function Ln(e,t,o){if(e==="json")return JSON.stringify(t===void 0?{}:t,null,2);const n=t===void 0?"":yn(t,o,process.stdout.columns);return n===""?void 0:n}async function Dn({action:e,fields:t=[],name:o},n){const i=Date.now();X(`invoked: ${process.argv.slice(2).join(" ")}`);const s=at(n),{format:r,progress:p}=Wt(s.options,process.stdout,process.stderr),d=un(p,process.stderr,s.signal);try{const c=Ln(r,await e({...s,progress:d}),t);d.succeed(),c!==void 0&&process.stdout.write(`${c}
|
|
10
|
-
`),
|
|
11
|
-
`),
|
|
8
|
+
`)}function N(e,t){return t===void 0||t<Rn?e:e.split(`
|
|
9
|
+
`).flatMap(o=>Cn(o,t)).join(`
|
|
10
|
+
`)}function Cn(e,t){const o=[];let n="";for(const i of e.split(" ").flatMap(r=>jn(r,t)))n===""?n=i:n.length+1+i.length<=t?n=`${n} ${i}`:(o.push(n),n=i);return o.push(n),o}async function Mn(e,t={}){const o=await de(e,{signal:t.signal});return new ut(o,{...t,onClose:()=>{o.close(),t.onClose?.()}})}function Bn(e,t){if(e.controlSocket===void 0)throw new Error("Session is not ready");return Mn(e.controlSocket,{baseUrl:e.baseUrl,signal:t})}async function qn(e,t){if(e.controlSocket===void 0)throw new Error("Session is not ready");const o=await de(e.controlSocket,{signal:t}),{client:n}=ft(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 Gn(e){return async({options:t,positionals:o,progress:n,signal:i})=>{const r=t["session-id"],s=mt(typeof r=="string"?r:void 0);try{return await e({options:t,positionals:o,progress:n,record:s,signal:AbortSignal.any([i,ne(s.pid)])})}catch(p){throw U.wrap(p,s.sessionId)}}}function Kn(e){return async({options:t,positionals:o,progress:n,record:i,signal:r})=>{const s=await Bn(i,r);try{return await e({device:s,options:t,positionals:o,progress:n,signal:r})}finally{s.close()}}}function Zn(e){return async({options:t,positionals:o,progress:n,record:i,signal:r})=>{const s=await qn(i,r);try{return await e({control:s,options:t,positionals:o,progress:n,signal:r})}finally{s.close()}}}const Vn=["session-id",...Nt,...zt,...Zt,...lo,...fn,...Go,...yn,...In],Wn=["json","quiet"];function Xn(e){const t=He("appetize").version(e).option("--json","Print the result as JSON").option("--quiet","Hide progress");return b(t,"session start <device>",o=>o.describe(["Start a device session and wait until it is ready","","Environment variables:","APPETIZE_API_TOKEN: Authorizes private APIs and targets; required with no target","APPETIZE_ENDPOINT: Appetize URL used when --endpoint is omitted"]).option("--device-android-shell","Android only: adb shell command run at start; needs --target").option("--device-appearance",`Device appearance: ${se.join(" or ")}`).option("--device-font-size",`Device font size: ${re.join(", ")}`).option("--device-ios-keyboards","iOS only: keyboard layout (e.g., en_US@sw=QWERTY); repeatable").option("--device-locale","Device locale as a BCP 47 tag (e.g., fr-CA)").option("--device-location","Device location as <lat>,<lng>; use = if latitude is negative").option("--device-orientation",`Initial orientation: ${T.join(", ")}`).option("--device-os-version","Device OS version (e.g., 17 for iOS, 14 for Android)").option("--device-timezone","Device IANA timezone (e.g., America/Toronto)").option("--endpoint","Appetize URL (e.g., https://appetize.io); overrides APPETIZE_ENDPOINT").option("--force","Replace a session with the same id",!1).option("--no-device-android-soft-keyboard","Android only: hide the on-screen keyboard").option("--no-device-ios-autocorrect","iOS only: keep autocorrect off, its default").option("--no-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").option("--target","App, build or app group id to run").example("session start iphone15pro --target app_a1b2c3").example("session start iphone15pro").example("session start pixel7 --target app_a1b2c3 --device-os-version 14").example("session start iphone15pro --target app_a1b2c3 --open myapp://orders/42").example("session start iphone15pro --device-orientation landscapeLeft --device-appearance dark").example("session start pixel7 --device-locale fr-CA --device-timezone America/Toronto").example("session start iphone15pro --target app_a1b2c3 --session-id demo --force"),Yo,{fields:Vo}),ee(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"),on),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"),Ut,{fields:Rt}),b(t,"build upload <file>",o=>o.describe([`Upload a build (${M.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(ve)})`).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"'),Mt,{fields:Ct}),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"),Wt,{fields:Vt}),m(t,"press <button>",o=>o.describe(`Press a device button: ${ge.join(", ")}; Android only: ${he.join(", ")}`).example("press home").example("press volumeUp"),vo),m(t,"rotate <orientation>",o=>o.describe("Rotate the device to an orientation: portrait, landscapeLeft, landscapeRight or upsideDown").example("rotate portrait").example("rotate landscapeLeft"),Ao),Yt in ae()&&m(t,"fold <hinge>",o=>o.describe(`Fold a foldable device: ${j.join(", ")}`).example("fold closed").example("fold fullyOpen"),Jt),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"),go),m(t,"keychain clear",o=>o.describe("Clear the entire device keychain (iOS only)").example("keychain clear"),ho),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"),Io),m(t,"tap",o=>Z(o.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"),Pn),m(t,"swipe",o=>Z(Z(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 --${y}-* point to form a path`,"",`Pick one per point: ${O({prefix:w})}`,` ${O({prefix:y})}`]).option("--direction",`Direction to travel: ${F.join(", ")}`).option("--distance","Travel as a fraction of the screen (0-1)"),{prefix:w}),{prefix:y}).option("--duration","Milliseconds the gesture travels for").option("--timeout",`Milliseconds to wait for any --${w}/--${y} elements`).example("swipe --direction up").example("swipe --direction up --distance 0.25").example("swipe --direction left --from-test-id card --from-index 1").example("swipe --from-position 0.5,0.75 --to-position 0.5,0.3").example("swipe --from-text 'Drag me' --from-y 0.9 --to-test-id drop-zone"),vn),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"),eo),m(t,"inspect [output]",o=>xe(o.describe("Capture the view hierarchy of the screen, or of every element a selector matches")).option("--timeout","Milliseconds to wait for a match").option("--pretty","Pretty-print the JSON",!1).example("inspect").example("inspect --select-text 'Log in'").example("inspect hierarchy.json --pretty"),uo),m(t,"type <text>",o=>o.describe(`Type text; {...} presses a named key: ${wt.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"),Tn),We(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"),So),We(t,"recording stop",o=>o.describe("Stop recording the device video and close the file").example("recording stop"),bo),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"),mn),t}function b(e,t,o,n,{fields:i}={}){const r=t.split(" ").filter(s=>!/^[<[]/.test(s)).join(" ");return o(e.command(t)).action(Jn({action:n,fields:i,name:r}))}function ee(e,t,o,n){return b(e,t,i=>o(i).option("--session-id","Target session id; defaults to the sole active session"),Gn(n))}function m(e,t,o,n){return ee(e,t,o,Kn(n))}function We(e,t,o,n){return ee(e,t,o,Zn(n))}function Xe(e){return`${String(Date.now()-e)}ms`}function Hn(e,t,o){if(e==="json")return JSON.stringify(t===void 0?{}:t,null,2);const n=t===void 0?"":zn(t,o,process.stdout.columns);return n===""?void 0:n}async function Yn({action:e,fields:t=[],name:o},n){const i=Date.now();Y(`invoked: ${process.argv.slice(2).join(" ")}`);const r=ht(n),{format:s,progress:p}=io(r.options,process.stdout,process.stderr),c=Ln(p,process.stderr,r.signal);try{const l=Hn(s,await e({...r,progress:c}),t);c.succeed(),l!==void 0&&process.stdout.write(`${l}
|
|
11
|
+
`),Y(`ok in ${Xe(i)}`)}catch(l){c.fail(),process.stderr.write(`${gt(s,l,{command:o})}
|
|
12
|
+
`),Y(`failed after ${Xe(i)}:`,l),process.exitCode=1}}function Jn(e){return(...t)=>{Yn(e,t)}}Xn("0.24.0").parse(process.argv,{boolean:Wn,string:Vn});
|
package/daemon.js
CHANGED
|
@@ -1,3 +1,2 @@
|
|
|
1
|
-
import{T as G,G as I,H as K,I as L,J,z as Z,K as B,h as Y,L as X,M as U,N as ee,O as te,v as ne,P as oe,Q as re,R as se,V as ae}from"./stream-DqsoC5l1.js";import k from"debug";import*as a from"zod/mini";import{createServer as x}from"node:net";import{pipeline as C}from"node:stream";import{rm as ie}from"node:fs/promises";import{readFileSync as ce,createWriteStream as de,existsSync as le,rmSync as ue}from"node:fs";import{createServer as pe}from"node:http";import{WebSocketServer as fe}from"ws";import{pipeline as he}from"node:stream/promises";import{EncodedVideoPacketSource as ge,Output as we,FilePathTarget as me,Mp4OutputFormat as ye,EncodedPacket as ve}from"mediabunny";import"json-rpc-2.0";import"node:path";import"node:os";import"stream";import"module";const be=["h264","jpeg"],Se=k("appetize.io:transport:ws-ping"),Ee=3e4;function Ae(e){let t=!0;const n=()=>{t=!0};e.on("pong",n);const o=setInterval(()=>{if(!t){clearInterval(o),Se("liveness ping went unanswered, terminating"),e.terminate();return}e.readyState===e.OPEN&&(t=!1,e.ping())},Ee);return{destroy(){clearInterval(o),e.off("pong",n)},pong:n}}const y=k("appetize.io:trace:transport:websocket");class R extends G{constructor(t,{signal:n}={}){super(async r=>{this.#e.send(I(r))},{signal:n}),this.wsOrUrl=t,typeof t=="string"?(this.#e=new WebSocket(t),this.#e.binaryType="arraybuffer"):this.#e=t;const o=this.#e;if(o instanceof WebSocket?(o.addEventListener("open",this.#s),o.addEventListener("message",this.#r),o.addEventListener("error",this.#o),o.addEventListener("close",this.#n),this.#t.push(()=>{o.removeEventListener("open",this.#s),o.removeEventListener("message",this.#r),o.removeEventListener("error",this.#o),o.removeEventListener("close",this.#n)})):(o.addEventListener("open",this.#s),o.addEventListener("message",this.#r),o.addEventListener("error",this.#o),o.addEventListener("close",this.#n),this.#t.push(()=>{o.removeEventListener("open",this.#s),o.removeEventListener("message",this.#r),o.removeEventListener("error",this.#o),o.removeEventListener("close",this.#n)})),this.send=o.send.bind(o),"ping"in o){const{destroy:r,pong:s}=Ae(o);this.#c=s,this.#t.push(r)}}wsOrUrl;onclose;onerror;onmessage;onopen;send;get bufferedAmount(){return this.#e.bufferedAmount}get readyState(){return this.#e.readyState}#t=[];#a=!1;#i=!1;#c;#e;close({destroyWs:t=!1,...n}={}){this.closed||(this.#a=t,super.close(n))}handleClose(t){y("close()");for(const n of this.#t.splice(0))n();if((typeof this.wsOrUrl=="string"||this.#a)&&(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.#i||(this.#i=!0,this.onclose?.(t))}#n=t=>{y("handleWebSocketClose()",t);try{this.#d(t)}finally{this.close()}};#o=t=>{y("handleWebSocketError()",t),this.onerror?.(t)};#r=async t=>{y("handleWebSocketMessage()",t),this.#c?.();const n=this.#l(t);if(!n){y("handleWebSocketMessage() -> legacy"),this.onmessage?.(t);return}y("handleWebSocketMessage() -> jsonrpc",n),this[K].dispatchMessage(n)};#s=t=>{y("handleWebSocketOpen()",t),this.onopen?.(t)};#l(t){try{const n=L(new Uint8Array(t.data));return J(n)?n:null}catch{return null}}}function A(e){return typeof e=="object"&&e!==null}function z(e){try{const t=L(new Uint8Array(e.data));if(A(t)&&typeof t.name=="string")return{name:t.name,payload:"payload"in t?t.payload:void 0}}catch{}}async function Te(e,t={}){const n=t.baseUrl??(typeof e=="string"?new URL(e).origin:void 0),o=typeof e=="string"?new R(e,{signal:t.signal}):e,r=new Z(o,{...t,baseUrl:n});return typeof e=="string"&&await Le(o,r,t),r}function Le(e,t,n){const o=B(n)?.onLegacyMessage;return new Promise((r,s)=>{e.onopen=()=>{r()},e.onclose=()=>{t.close(),n.signal?.aborted?s(n.signal.reason):s(new Error("The websocket was closed before the device connection was established"))},e.onerror=s,e.onmessage=i=>{const d=z(i);d&&o?.(d)}})}async function ke(e,{onStateChange:t,signal:n}){n?.throwIfAborted(),t?.({phase:"starting"}),await new Promise((o,r)=>{const s=()=>{i(),r(n?.reason)},i=()=>{e.onmessage=void 0,e.onclose=void 0,n?.removeEventListener("abort",s)};e.onmessage=d=>{const c=Re(z(d));c&&(t?.(c),c.phase==="ready"&&(i(),o()))},e.onclose=()=>{i(),r(new Error("The device closed before it was ready"))},n?.addEventListener("abort",s,{once:!0})})}function Re(e){if(!e)return;if(e.name==="ready")return{phase:"ready"};if(e.name!=="launchStatus")return;switch(A(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 $e(){return typeof process>"u"?void 0:process}const Pe=["light","dark"],Ie=["xs","s","m","l","xl","xxl","xxxl"];function Ue(e){return{adbShellCommand:e.android?.shell,appearance:e.appearance,deviceType:e.id,disableVirtualKeyboard:e.android?.softKeyboard===!1?!0:void 0,fontSize:e.fontSize,iosAutocorrect:e.ios?.autocorrect,iosKeyboard:e.ios?.keyboards,language:e.locale,locale:e.locale,location:e.location&&[e.location.latitude,e.location.longitude],orientation:e.orientation,osVersion:e.osVersion,timezone:e.timezone}}const xe=["grant"];function Ce(e){return{grantPermissions:e?.permissions==="grant"?!0:void 0,launchApp:e?.app,launchArgs:e?.ios?.args,launchUrl:e?.url,params:e?.params}}function ze(e){return e==="intercept"?"interceptOnDemand":e}class v extends Error{code;issues;constructor(t,n,o=[]){super(n),this.name="SessionRequestError",this.code=t,this.issues=o}}const l=e=>`expected ${e}`,b=e=>a.string(l(e)).check(a.minLength(1,l(e))),E=e=>a.literal(e,l(`one of ${e.join(", ")}`)),S=e=>a.object(e,l("an object")),_=()=>a.boolean(l("true or false")),D=e=>a.number(l("a number")).check(a.gte(-e,l(`at least -${String(e)}`)),a.lte(e,l(`at most ${String(e)}`))),_e=/^\w{2}(?:_\w{2})?@sw(=[\w-]+)?$/,De=/^[a-z0-9_.=:/ ()"-]+$/i,Oe='letters, digits or _ . = : / ( ) " - and spaces',We=/^[A-Za-z]{2,3}([-_][A-Za-z0-9]{2,8})*$/;function Me(e){if(!We.test(e))return!1;try{return new Intl.Locale(e.replaceAll("_","-")),!0}catch{return!1}}function qe(e){try{return new Intl.DateTimeFormat(void 0,{timeZone:e}),!0}catch{return!1}}const $="has no effect without a target",O="has no effect without a target, or with launch.app: false";function W({launch:e}){return e?.app!==!1}const je=a.object({apiToken:a.optional(b("an API token")),codec:a.optional(E(be)),device:S({android:a.optional(S({shell:a.optional(b("a shell command")),softKeyboard:a.optional(_())})),appearance:a.optional(E(Pe)),fontSize:a.optional(E(Ie)),id:b("a device id"),ios:a.optional(S({autocorrect:a.optional(_()),keyboards:a.optional(a.array(a.string(l("a keyboard layout")).check(a.regex(_e,l("a layout like en_US@sw=QWERTY"))),l("a list of keyboard layouts")))})),locale:a.optional(a.string(l("a BCP 47 tag, e.g. fr-CA")).check(a.refine(Me,{error:l("a BCP 47 tag, e.g. fr-CA")}))),location:a.optional(S({latitude:D(90),longitude:D(180)})),orientation:a.optional(E(Y)),osVersion:a.optional(b("an OS version")),timezone:a.optional(a.string(l("an IANA timezone")).check(a.refine(qe,{error:l("an IANA timezone, e.g. America/Toronto")})))}),endpoint:a.optional(a.url(l("a URL"))),launch:a.optional(S({app:a.optional(a.union([b("an app id"),a.literal(!1)],l("an app id or false"))),ios:a.optional(S({args:a.optional(a.array(a.string(l("an argument")).check(a.regex(De,l(Oe))),l("a list of arguments")).check(a.maxLength(20,l("at most 20 arguments"))))})),params:a.optional(a.custom(e=>typeof e=="object"&&e!==null&&!Array.isArray(e),l("an object"))),permissions:a.optional(E(xe)),url:a.optional(a.url(l("a URL")))})),proxy:a.optional(a.union([a.literal("intercept"),a.templateLiteral(["http://",a.string()])],l("intercept or an http:// URL"))),target:a.optional(b("an app, build or group id"))}).check(a.refine(e=>e.device.android?.shell===void 0||e.target!==void 0,{error:$,path:["device","android","shell"]}),a.refine(e=>e.launch?.app===void 0||e.target!==void 0,{error:$,path:["launch","app"]}),a.refine(e=>e.launch?.permissions===void 0||e.target!==void 0,{error:$,path:["launch","permissions"]}),a.refine(e=>e.launch?.params===void 0||e.target!==void 0&&W(e),{error:O,path:["launch","params"]}),a.refine(e=>e.launch?.ios?.args===void 0||e.target!==void 0&&W(e),{error:O,path:["launch","ios","args"]}));function Ne(e){const t=je.safeParse(e);if(t.success)return;const n=t.error.issues.map(o=>({message:o.message,path:o.path.join(".")}));throw new v("invalid",n.map(({message:o,path:r})=>`${r}: ${o}`).join(`
|
|
2
|
-
`)
|
|
3
|
-
`)}})}async function It(e,t,{signal:n}={}){await Q(async()=>await e.debug.createLogStream({signal:n}),t,{label:"log capture",signal:n})}async function Ut(e,t,{signal:n}={}){await Q(async()=>await e.debug.createProxyInterceptStream({signal:n}),t,{label:"network capture",signal:n})}const P=30;async function xt(e,t){await e.pipeTo(zt(t))}function Ct(e){return{decoderConfig:{codec:"avc1.640028",codedHeight:e.height,codedWidth:e.width}}}function zt(e){let t;const n=async()=>{await t?.output.finalize()};return new WritableStream({abort:n,close:n,write:async o=>{o.data.byteLength!==0&&(t??=await _t(Ot(o),e),Dt(t,o),await Wt(t,o))}})}async function _t(e,t){const n=new ge("avc"),o=new we({format:new ye({fastStart:"fragmented"}),target:new me(t,{chunked:!1})});return o.addVideoTrack(n,{frameRate:P}),await o.start(),{frame:0,output:o,seen:{height:e.height,width:e.width},size:{height:e.height,width:e.width},source:n}}function Dt(e,t){if(t.type!=="key")return;const{seen:n,size:o}=e;t.width===n.width&&t.height===n.height||(e.seen={height:t.height,width:t.width},g(`video resized to ${String(t.width)}x${String(t.height)}; keeping ${String(o.width)}x${String(o.height)}`))}function Ot(e){if(e.type!=="key")throw new Error("Video stream started without a key chunk");return e}async function Wt(e,t){const n=new ve(t.data,t.type,e.frame/P,1/P);e.frame+=1,await e.source.add(n,Ct(e.size))}function Mt(e,t,{signal:n}={}){let o,r;const s=async(c,{force:u=!1}={})=>{if(le(c)){if(!u)throw new Error(`A recording already exists at ${c}; pass --force to overwrite`);ue(c)}const h=await e.video.createStream({signal:n});return o={done:qt(h,c),path:c,stream:h},t.save({video:{path:c,recording:!0}}),g(`recording video to ${c}`),{path:c}},i=async c=>{c.stream.close();try{await c.done,t.save({video:{path:c.path,recording:!1}})}finally{o=void 0,r=void 0}},d=async()=>{if(!o)return;const{path:c}=o;await i(o),g(`closed the video recording: ${c}`)};return n?.addEventListener("abort",()=>{d()},{once:!0}),{start:async({force:c=!1,path:u})=>{const h=o?.path??r;if(h!==void 0)throw new Error(`Already recording to ${h}`);r=u;try{return await s(u,{force:c})}finally{r=void 0}},stop:async()=>{if(!o)throw new Error("No video recording in progress");const{path:c}=o;return await i(o),{path:c}}}}async function qt(e,t){try{await xt(e.readable,t)}catch(n){g(`video capture ended with an error: ${String(n)}`)}}async function jt(){const{config:e,logs:t,store:n}=wt();g(`recording to ${n.path}`);const{shutdown:o,signal:r}=Rt(n);try{const{device:s,transport:i}=await gt(e,n,{onClose:o,signal:r}),d=Mt(s,n,{signal:r});await mt(s,e,n,{signal:r}),await bt(i,n,{signal:r});const c=await vt(i,n,e.sessionId,{recorder:d,signal:r});g(`control socket listening at ${c}`),It(s,t.device,{signal:r}),g(`recording device logs to ${t.device}`),t.network&&(Ut(s,t.network,{signal:r}),g(`recording network events to ${t.network}`))}catch(s){if(r.aborted)return;const i=s instanceof Error?s.message:String(s);n.save({endedAt:new Date().toISOString(),endedReason:i,state:{message:i,phase:"error"}}),g(`error: ${i}`),process.exitCode=1}}jt();
|
|
1
|
+
import{T as _,L as A,M as F,N as E,O as z,F as V,P as N,t as v,Q as j,v as H,R as Q,V as J,W as $,X as G,Y as K,A as Z,Z as X,_ as Y,$ as B,a0 as ee}from"./stream-BowDfEJS.js";import T from"debug";import{createServer as R}from"node:net";import{pipeline as P}from"node:stream";import{rm as te}from"node:fs/promises";import{readFileSync as ne,createWriteStream as oe,existsSync as re,rmSync as se}from"node:fs";import{createServer as ie}from"node:http";import{WebSocketServer as ae}from"ws";import{pipeline as ce}from"node:stream/promises";import{EncodedVideoPacketSource as de,Output as ue,FilePathTarget as le,Mp4OutputFormat as fe,EncodedPacket as pe}from"mediabunny";import"json-rpc-2.0";import"zod/mini";import"node:path";import"node:os";import"stream";import"module";const he=T("appetize.io:transport:ws-ping"),we=3e4;function ge(e){let t=!0;const n=()=>{t=!0};e.on("pong",n);const o=setInterval(()=>{if(!t){clearInterval(o),he("liveness ping went unanswered, terminating"),e.terminate();return}e.readyState===e.OPEN&&(t=!1,e.ping())},we);return{destroy(){clearInterval(o),e.off("pong",n)},pong:n}}const w=T("appetize.io:trace:transport:websocket");class L extends _{constructor(t,{signal:n}={}){super(async r=>{this.#e.send(A(r))},{signal:n}),this.wsOrUrl=t,typeof t=="string"?(this.#e=new WebSocket(t),this.#e.binaryType="arraybuffer"):this.#e=t;const o=this.#e;if(o instanceof WebSocket?(o.addEventListener("open",this.#s),o.addEventListener("message",this.#r),o.addEventListener("error",this.#o),o.addEventListener("close",this.#n),this.#t.push(()=>{o.removeEventListener("open",this.#s),o.removeEventListener("message",this.#r),o.removeEventListener("error",this.#o),o.removeEventListener("close",this.#n)})):(o.addEventListener("open",this.#s),o.addEventListener("message",this.#r),o.addEventListener("error",this.#o),o.addEventListener("close",this.#n),this.#t.push(()=>{o.removeEventListener("open",this.#s),o.removeEventListener("message",this.#r),o.removeEventListener("error",this.#o),o.removeEventListener("close",this.#n)})),this.send=o.send.bind(o),"ping"in o){const{destroy:r,pong:s}=ge(o);this.#c=s,this.#t.push(r)}}wsOrUrl;onclose;onerror;onmessage;onopen;send;get bufferedAmount(){return this.#e.bufferedAmount}get readyState(){return this.#e.readyState}#t=[];#i=!1;#a=!1;#c;#e;close({destroyWs:t=!1,...n}={}){this.closed||(this.#i=t,super.close(n))}handleClose(t){w("close()");for(const n of this.#t.splice(0))n();if((typeof this.wsOrUrl=="string"||this.#i)&&(this.#e.close(t.code,t.reason),"terminate"in this.#e)){const n=this.#e;setTimeout(()=>{n.terminate()},100)}this.#d(),super.handleClose(t)}#d(t){this.#a||(this.#a=!0,this.onclose?.(t))}#n=t=>{w("handleWebSocketClose()",t);try{this.#d(t)}finally{this.close()}};#o=t=>{w("handleWebSocketError()",t),this.onerror?.(t)};#r=async t=>{w("handleWebSocketMessage()",t),this.#c?.();const n=this.#u(t);if(!n){w("handleWebSocketMessage() -> legacy"),this.onmessage?.(t);return}w("handleWebSocketMessage() -> jsonrpc",n),this[F].dispatchMessage(n)};#s=t=>{w("handleWebSocketOpen()",t),this.onopen?.(t)};#u(t){try{const n=E(new Uint8Array(t.data));return z(n)?n:null}catch{return null}}}function b(e){return typeof e=="object"&&e!==null}function I(e){try{const t=E(new Uint8Array(e.data));if(b(t)&&typeof t.name=="string")return{name:t.name,payload:"payload"in t?t.payload:void 0}}catch{}}async function ve(e,t={}){const n=t.baseUrl??(typeof e=="string"?new URL(e).origin:void 0),o=typeof e=="string"?new L(e,{signal:t.signal}):e,r=new V(o,{...t,baseUrl:n});return typeof e=="string"&&await me(o,r,t),r}function me(e,t,n){const o=N(n)?.onLegacyMessage;return new Promise((r,s)=>{e.onopen=()=>{r()},e.onclose=()=>{t.close(),n.signal?.aborted?s(n.signal.reason):s(new Error("The websocket was closed before the device connection was established"))},e.onerror=s,e.onmessage=i=>{const c=I(i);c&&o?.(c)}})}async function ye(e,{onStateChange:t,signal:n}){n?.throwIfAborted(),t?.({phase:"starting"}),await new Promise((o,r)=>{const s=()=>{i(),r(n?.reason)},i=()=>{e.onmessage=void 0,e.onclose=void 0,n?.removeEventListener("abort",s)};e.onmessage=c=>{const a=be(I(c));a&&(t?.(a),a.phase==="ready"&&(i(),o()))},e.onclose=()=>{i(),r(new Error("The device closed before it was ready"))},n?.addEventListener("abort",s,{once:!0})})}function be(e){if(!e)return;if(e.name==="ready")return{phase:"ready"};if(e.name!=="launchStatus")return;switch(b(e.payload)&&typeof e.payload.status=="string"?e.payload.status:void 0){case"downloadingApp":return{phase:"downloadingApp"};case"installingApp":return{phase:"installingApp"};case"launchingApp":return{phase:"launchingApp"};default:return}}function Se(){return typeof process>"u"?void 0:process}function Ee(e){return e==="intercept"?"interceptOnDemand":e}function Te(e,{onClose:t,onEvent:n,signal:o}={}){return new Promise((r,s)=>{const i=new WebSocket(e);i.binaryType="arraybuffer",i.onopen=()=>{W(i,{capabilities:{},t:"handshake"})},i.onmessage=c=>{Le(i,c,{onEvent:n,onHandshake:a=>{r({close:()=>{i.close()},id:a})}})},i.onclose=()=>{s(new v("disconnected",`The connection to ${e} closed`)),t?.()},o?.addEventListener("abort",()=>{s(o.reason),i.close()},{once:!0})})}function Le(e,t,n){const o=E(new Uint8Array(t.data));b(o)&&(o.t==="handshake"&&typeof o.id=="string"?n.onHandshake(o.id):o.name==="ping"?W(e,{name:"pong"}):typeof o.name=="string"&&n.onEvent?.(o.name,o.payload))}function W(e,t){e.send(A(t))}async function ke(e,t,{apiToken:n,onQueue:o,signal:r}={}){const s=j();Pe(s.reject,r);const i=await Te(Ie(e),{onClose:()=>{s.reject(Ae())},onEvent:(c,a)=>{$e(c,a,s,o)},signal:r});return Re(e,{apiToken:n,data:t,socketid:i.id},r).catch(s.reject),await s.promise.finally(()=>{i.close()})}function Ae(){return new v("disconnected","The webserver connection closed before a session was granted")}function U(e,t){return b(e)?e[t]:void 0}function $e(e,t,n,o){if(e==="queue"||e==="concurrentQueue"){const r=e==="queue"?Ue(t):Ce(t);r&&o?.(r)}else e==="newSession"?We(n,t):e==="userError"&&n.reject(new v("denied",De(t)))}function C(e,t){const n=U(e,t);return typeof n=="number"?n:void 0}function m(e,t){const n=U(e,t);return typeof n=="string"?n:void 0}async function Re(e,t,n){const o=await fetch(new URL("/api/session/request",e),{body:JSON.stringify(t),headers:{"content-type":"application/json"},method:"POST",signal:n});if(!o.ok)throw new v("denied",await Me(o))}function Pe(e,t){t?.addEventListener("abort",()=>{e(t.reason)},{once:!0})}function Ie(e){const t=new URL("/client",e);return t.protocol=t.protocol==="http:"?"ws:":"wss:",t.href}function We(e,t){const n=m(t,"path"),o=m(t,"sessionToken");n!==void 0&&o!==void 0?e.resolve({path:n,sessionToken:o}):e.reject(new v("denied","The granted session is missing its address"))}function Ue(e){const t=C(e,"position");return t===void 0?void 0:{position:t,reason:"capacity"}}function Ce(e){const t=C(e,"position");if(t!==void 0)return{limit:m(e,"name")??"Queue",position:t,reason:"concurrency"}}function De(e){return m(e,"message")??"The session request was denied"}async function Me(e){const t=`The webserver rejected the session request (${String(e.status)})`,n=await e.json().catch(()=>{}),o=m(n,"message");return o?`${t}: ${o}`:t}async function qe({apiToken:e=Oe(),codec:t="h264",device:n,endpoint:o="https://appetize.io",launch:r,onStateChange:s,proxy:i,signal:c,target:a}){c?.throwIfAborted(),H({apiToken:e,codec:t,device:n,endpoint:o,launch:r,proxy:i,target:a}),s?.({phase:"requesting"});const d=await ke(o,{codec:t,noVideo:!0,proxy:Ee(i),publicKey:a,...J(n),...Q(r)},{apiToken:e,onQueue:h=>{s?.({phase:"queued",queue:h})},signal:c});return{baseUrl:new URL(d.path).origin,url:xe(d)}}function Oe(){return Se()?.env.APPETIZE_API_TOKEN}function xe(e){const t=new URL("/client",e.path);return t.protocol=t.protocol==="http:"?"ws:":"wss:",t.searchParams.set("sessionToken",e.sessionToken),t.href}async function _e(e,{host:t="127.0.0.1",onError:n,port:o=0,signal:r}={}){r?.throwIfAborted();let s;const i=()=>{const u=s;s=void 0,u&&(u.tunnel?.close(),u.socket.destroy())},c=async u=>{const{socket:l}=u;try{const p=await e.debug.createAdbTunnel();if(l.destroyed){p.close();return}u.tunnel=p,p.closed.catch(S=>{n?.(S)}),Fe(l,p)}catch(p){l.destroyed||n?.(p),l.destroy()}},a=R(u=>{i();const l={socket:u};s=l,u.once("close",()=>{s===l&&(s=void 0)}),c(l)}),d=()=>{r?.removeEventListener("abort",d),i(),a.close()};r?.addEventListener("abort",d,{once:!0});const h=await ze(a,t,o);return{close:d,url:new URL(`adb://${h.address}:${String(h.port)}`)}}function Fe(e,t){P(t.readable,e,D),P(e,async n=>{const o=t.writable.getWriter();try{for await(const r of n)await o.write(r);await o.close()}catch(r){throw await o.abort(r),r}},D)}function D(){}function ze(e,t,n){return new Promise((o,r)=>{e.once("error",r),e.listen({host:t,port:n},()=>{e.off("error",r);const s=e.address();if(s===null||typeof s=="string"){r(new Error("The listener has no tcp address"));return}o(s)})})}async function Ve(e,{methods:t={},path:n,signal:o}){o?.throwIfAborted(),await te(n,{force:!0});const r=new Set,s=R(c=>{r.add(c),c.once("close",()=>{r.delete(c)}),$(new G(c),e,{leftEffects:()=>t})}),i=()=>{o?.removeEventListener("abort",i);for(const c of r)c.destroy();s.close()};return await Ne(s,n),o?.aborted&&(i(),o.throwIfAborted()),o?.addEventListener("abort",i,{once:!0}),{close:i,path:n}}function Ne(e,t){return new Promise((n,o)=>{e.once("error",o),e.listen(t,()=>{e.off("error",o),n()})})}const je=T("appetize:daemon");function f(e){je(e)}function He(e,{message:t="The operation timed out"}={}){const n=new AbortController,o=setTimeout(()=>{n.abort(new Error(t))},e),r=()=>{clearTimeout(o)};return{cancel:r,signal:n.signal,[Symbol.dispose]:r}}var Qe=(e,t)=>(t=Symbol[e])?t:Symbol.for("Symbol."+e),M=e=>{throw TypeError(e)},Je=(e,t,n)=>{if(t!=null){typeof t!="object"&&typeof t!="function"&&M("Object expected");var o,r;o===void 0&&(o=t[Qe("dispose")]),typeof o!="function"&&M("Object not disposable"),r&&(o=function(){try{r.call(this)}catch(s){return Promise.reject(s)}}),e.push([n,o,t])}return t},Ge=(e,t,n)=>{var o=typeof SuppressedError=="function"?SuppressedError:function(i,c,a,d){return d=Error(a),d.name="SuppressedError",d.error=i,d.suppressed=c,d},r=i=>t=n?new o(i,t,"An error was suppressed during disposal"):(n=!0,i),s=i=>{for(;i=e.pop();)try{var c=i[1]&&i[1].call(i[2]);if(i[0])return Promise.resolve(c).then(s,a=>(r(a),s()))}catch(a){r(a)}if(n)throw t};return s()};const Ke=1e4;async function Ze(e,t,{onClose:n,signal:o}={}){var r=[];try{const c=Je(r,He(Ke,{message:"Timed out waiting for session request state"})),a=AbortSignal.any([o,c.signal].filter(g=>!!g)),d=g=>{t.save({state:g}),f(g.phase),g.phase!=="requesting"&&c.cancel()},{featureFlags:h,sessionId:u,...l}=e,{baseUrl:p,url:S}=await qe({...l,onStateChange:d,signal:a});t.save({baseUrl:p});const y=new L(S,{signal:a});return await ye(y,{onStateChange:d,signal:a}),y.onclose=()=>{n?.("The device connection closed")},{device:await ve(y,{baseUrl:p,signal:a}),transport:y}}catch(c){var s=c,i=!0}finally{Ge(r,s,i)}}function Xe(){const e=K(),t=Z(e.sessionId,e.proxy),n=X({device:e.device,endpoint:e.endpoint,open:e.launch?.url,pid:process.pid,proxy:e.proxy,sessionId:e.sessionId,startedAt:new Date().toISOString(),target:e.target});return n.save({logs:t}),{config:e,logs:t,store:n}}async function Ye(e,t,n,{signal:o}={}){try{if(!await Be(t))return;const r=await _e(e,{onError:s=>{f(`adb endpoint error: ${q(s)}`)},signal:o});n.save({adbSerial:r.url.host}),f(`adb endpoint listening at ${r.url.host}`)}catch(r){f(`adb endpoint unavailable: ${q(r)}`)}}async function Be(e){return await Y(e.device.id,{endpoint:e.endpoint})==="android"}function q(e){return e instanceof Error?e.message:String(e)}async function et(e,t,n,{recorder:o,signal:r}){const{path:s}=await Ve(e,{methods:{"appetizeio.cli.record.start":async i=>await o.start(i),"appetizeio.cli.record.stop":async()=>await o.stop()},path:B(n),signal:r});return t.save({controlSocket:s}),s}const O="127.0.0.1";async function tt(e,t,n={}){try{const o=await nt(e,n);return t.save({viewerUrl:o.url.href}),f(`web endpoint listening at ${o.url.href}`),o}catch(o){f(`web endpoint unavailable: ${at(o)}`);return}}async function nt(e,{port:t=0,signal:n,viewerHtml:o=ne(new URL("./viewer.html",import.meta.url),"utf8")}){n?.throwIfAborted();const r=ie((u,l)=>{rt(u,l,o)}),s=new Set,i=new ae({noServer:!0,perMessageDeflate:!1});let c;i.on("connection",u=>{if(s.size>0){u.close(1013,"Viewer already connected");return}s.add(u);const l=new L(u);$(l,e),u.once("close",()=>{s.delete(u)})}),r.on("upgrade",(u,l,p)=>{st(i,u,l,p)});const a=()=>(c??=new Promise((u,l)=>{n?.removeEventListener("abort",d);for(const p of s)ot(p);i.close(),r.close(p=>{p?l(p):u()})}),c),d=()=>{a()};await it(r,t),n?.addEventListener("abort",d,{once:!0});const h=r.address();if(!h||typeof h=="string")throw await a(),new Error("Web address unavailable");return{close:a,url:new URL(`http://${O}:${String(h.port)}/`)}}function ot(e){e.close(1001)}function rt(e,t,n){if(e.method==="GET"&&e.url==="/"){t.writeHead(200,{"Cache-Control":"no-store","Content-Type":"text/html; charset=utf-8"}),t.end(n);return}t.writeHead(404).end()}function st(e,t,n,o){if(t.url!=="/ws"){n.destroy();return}e.handleUpgrade(t,n,o,r=>{e.emit("connection",r,t)})}function it(e,t){return new Promise((n,o)=>{const r=s=>{o(s)};e.once("error",r),e.listen(t,O,()=>{e.removeListener("error",r),n()})})}function at(e){return e instanceof Error?e.message:String(e)}function ct(e){const t=new AbortController,n=dt(e,t),o=ee();return o.addEventListener("abort",()=>{const{reason:r}=o;n(r instanceof Error?r.message:String(r))},{once:!0}),{shutdown:n,signal:t.signal}}function dt(e,t){let n=!1;return o=>{n||(n=!0,e.save({endedAt:new Date().toISOString(),endedReason:o,state:{phase:"ended"}}),f(o),t.abort())}}async function x(e,t,{label:n,signal:o}){try{const r=await e();await ce(r.readable.pipeThrough(ut()),oe(t,{flags:"a"}))}catch(r){if(o?.aborted)return;const s=r instanceof Error?r.message:String(r);f(`${n} ended with an error: ${s}`)}}function ut(){return new TransformStream({transform:(e,t)=>{t.enqueue(`${JSON.stringify(e)}
|
|
2
|
+
`)}})}async function lt(e,t,{signal:n}={}){await x(async()=>await e.debug.createLogStream({signal:n}),t,{label:"log capture",signal:n})}async function ft(e,t,{signal:n}={}){await x(async()=>await e.debug.createProxyInterceptStream({signal:n}),t,{label:"network capture",signal:n})}const k=30;async function pt(e,t){await e.pipeTo(wt(t))}function ht(e){return{decoderConfig:{codec:"avc1.640028",codedHeight:e.height,codedWidth:e.width}}}function wt(e){let t;const n=async()=>{await t?.output.finalize()};return new WritableStream({abort:n,close:n,write:async o=>{o.data.byteLength!==0&&(t??=await gt(mt(o),e),vt(t,o),await yt(t,o))}})}async function gt(e,t){const n=new de("avc"),o=new ue({format:new fe({fastStart:"fragmented"}),target:new le(t,{chunked:!1})});return o.addVideoTrack(n,{frameRate:k}),await o.start(),{frame:0,output:o,seen:{height:e.height,width:e.width},size:{height:e.height,width:e.width},source:n}}function vt(e,t){if(t.type!=="key")return;const{seen:n,size:o}=e;t.width===n.width&&t.height===n.height||(e.seen={height:t.height,width:t.width},f(`video resized to ${String(t.width)}x${String(t.height)}; keeping ${String(o.width)}x${String(o.height)}`))}function mt(e){if(e.type!=="key")throw new Error("Video stream started without a key chunk");return e}async function yt(e,t){const n=new pe(t.data,t.type,e.frame/k,1/k);e.frame+=1,await e.source.add(n,ht(e.size))}function bt(e,t,{signal:n}={}){let o,r;const s=async(a,{force:d=!1}={})=>{if(re(a)){if(!d)throw new Error(`A recording already exists at ${a}; pass --force to overwrite`);se(a)}const h=await e.video.createStream({signal:n});return o={done:St(h,a),path:a,stream:h},t.save({video:{path:a,recording:!0}}),f(`recording video to ${a}`),{path:a}},i=async a=>{a.stream.close();try{await a.done,t.save({video:{path:a.path,recording:!1}})}finally{o=void 0,r=void 0}},c=async()=>{if(!o)return;const{path:a}=o;await i(o),f(`closed the video recording: ${a}`)};return n?.addEventListener("abort",()=>{c()},{once:!0}),{start:async({force:a=!1,path:d})=>{const h=o?.path??r;if(h!==void 0)throw new Error(`Already recording to ${h}`);r=d;try{return await s(d,{force:a})}finally{r=void 0}},stop:async()=>{if(!o)throw new Error("No video recording in progress");const{path:a}=o;return await i(o),{path:a}}}}async function St(e,t){try{await pt(e.readable,t)}catch(n){f(`video capture ended with an error: ${String(n)}`)}}async function Et(){const{config:e,logs:t,store:n}=Xe();f(`recording to ${n.path}`);const{shutdown:o,signal:r}=ct(n);try{const{device:s,transport:i}=await Ze(e,n,{onClose:o,signal:r}),c=bt(s,n,{signal:r});await Ye(s,e,n,{signal:r}),await tt(i,n,{signal:r});const a=await et(i,n,e.sessionId,{recorder:c,signal:r});f(`control socket listening at ${a}`),lt(s,t.device,{signal:r}),f(`recording device logs to ${t.device}`),t.network&&(ft(s,t.network,{signal:r}),f(`recording network events to ${t.network}`))}catch(s){if(r.aborted)return;const i=s instanceof Error?s.message:String(s);n.save({endedAt:new Date().toISOString(),endedReason:i,state:{message:i,phase:"error"}}),f(`error: ${i}`),process.exitCode=1}}Et();
|
package/package.json
CHANGED
package/skills/appetize/SKILL.md
CHANGED
|
@@ -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.
|
|
13
|
+
cli-version: '0.24.0'
|
|
14
14
|
---
|
|
15
15
|
|
|
16
16
|
# Appetize
|
|
@@ -43,6 +43,7 @@ environment.
|
|
|
43
43
|
appetize session start iphone15pro --target app_a1b2c3 --json
|
|
44
44
|
appetize session start iphone15pro --json
|
|
45
45
|
appetize session start pixel7 --target app_a1b2c3 --device-os-version 14 --proxy --json
|
|
46
|
+
appetize session start iphone15pro --device-orientation landscapeLeft --device-appearance dark --json
|
|
46
47
|
```
|
|
47
48
|
|
|
48
49
|
This blocks until the device is ready; a background daemon then holds the
|
|
@@ -29,6 +29,13 @@ Session directories live under `~/.appetize/cli/sessions/`, or
|
|
|
29
29
|
- `--proxy http://host:port` routes through your own proxy; other schemes are
|
|
30
30
|
rejected. Interception rewrites TLS, so an app that pins certificates may
|
|
31
31
|
fail under it.
|
|
32
|
+
- `--device-orientation`, `--device-locale`, `--device-timezone`,
|
|
33
|
+
`--device-location <lat>,<lng>` (`--device-location=-43.5,172.6` when the
|
|
34
|
+
latitude is negative),
|
|
35
|
+
`--device-appearance` and `--device-font-size` set the device up. iOS takes
|
|
36
|
+
`--device-ios-keyboards` (repeatable) and `--no-device-ios-autocorrect`;
|
|
37
|
+
Android takes `--no-device-android-soft-keyboard` and
|
|
38
|
+
`--device-android-shell`, which needs a target.
|
|
32
39
|
|
|
33
40
|
## session stop
|
|
34
41
|
|