sootsim 0.0.1
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/README.md +197 -0
- package/dist-cli/bin.js +29 -0
- package/dist-cli/chunks/bridge-host-2EY7Z4AO.js +2 -0
- package/dist-cli/chunks/chunk-3C3ZH7PP.js +4 -0
- package/dist-cli/chunks/chunk-3R4ZZESY.js +119 -0
- package/dist-cli/chunks/chunk-64TOMNZX.js +37 -0
- package/dist-cli/chunks/chunk-74XPLOV4.js +2 -0
- package/dist-cli/chunks/chunk-7LMDCMSI.js +8 -0
- package/dist-cli/chunks/chunk-7X6OPSRD.js +2 -0
- package/dist-cli/chunks/chunk-A2CZQIWO.js +1 -0
- package/dist-cli/chunks/chunk-CKZ376AY.js +322 -0
- package/dist-cli/chunks/chunk-E522F5JW.js +2 -0
- package/dist-cli/chunks/chunk-E5UBZEYR.js +2 -0
- package/dist-cli/chunks/chunk-G5MR66EB.js +180 -0
- package/dist-cli/chunks/chunk-GPVPHE2B.js +3 -0
- package/dist-cli/chunks/chunk-HOIHCO7S.js +3 -0
- package/dist-cli/chunks/chunk-J2S3OCWA.js +69 -0
- package/dist-cli/chunks/chunk-JSF5LPNT.js +176 -0
- package/dist-cli/chunks/chunk-KQWZZ56P.js +2 -0
- package/dist-cli/chunks/chunk-KSACMDXK.js +3 -0
- package/dist-cli/chunks/chunk-KSB6MSZ4.js +34 -0
- package/dist-cli/chunks/chunk-KXYKAYYB.js +51 -0
- package/dist-cli/chunks/chunk-MBFP2LVH.js +3 -0
- package/dist-cli/chunks/chunk-MPSZ5EWF.js +16 -0
- package/dist-cli/chunks/chunk-OROM7DZI.js +2 -0
- package/dist-cli/chunks/chunk-PWXPA745.js +3 -0
- package/dist-cli/chunks/chunk-QOBRRY5X.js +4 -0
- package/dist-cli/chunks/chunk-X2U72K7X.js +1 -0
- package/dist-cli/chunks/chunk-YCETS3B3.js +2 -0
- package/dist-cli/chunks/compat-MRN2ORY5.js +33 -0
- package/dist-cli/chunks/config-CO5IYWUY.js +45 -0
- package/dist-cli/chunks/control-Y7TKKB6D.js +2 -0
- package/dist-cli/chunks/daemon-G4XVRFHM.js +49 -0
- package/dist-cli/chunks/debug-ZNSZTWT6.js +182 -0
- package/dist-cli/chunks/detox-JEGYNTYV.js +49 -0
- package/dist-cli/chunks/dev-ZUKCZQEX.js +25 -0
- package/dist-cli/chunks/dev-checkout-IEZVVTCN.js +2 -0
- package/dist-cli/chunks/device-BS34FAFM.js +16 -0
- package/dist-cli/chunks/drivers-46PFFIDF.js +2 -0
- package/dist-cli/chunks/electron-P2KOPX2S.js +15 -0
- package/dist-cli/chunks/flow-VVOF6UNC.js +2 -0
- package/dist-cli/chunks/hints-7Z656W4H.js +2 -0
- package/dist-cli/chunks/inspect-NAHXP2M5.js +1042 -0
- package/dist-cli/chunks/install-EPUJX4AT.js +67 -0
- package/dist-cli/chunks/install-desktop-PYIZIH67.js +19 -0
- package/dist-cli/chunks/login-Z5Z54HUJ.js +26 -0
- package/dist-cli/chunks/logout-T2QDYGCB.js +2 -0
- package/dist-cli/chunks/maestro-4AXTS7OE.js +75 -0
- package/dist-cli/chunks/preview-NMGWHWMX.js +17 -0
- package/dist-cli/chunks/profile-6RGJA4FR.js +22 -0
- package/dist-cli/chunks/record-IE27Z2GA.js +37 -0
- package/dist-cli/chunks/screenshot-R3GCCSCI.js +26 -0
- package/dist-cli/chunks/screenshot-mode-SZQDNGYE.js +17 -0
- package/dist-cli/chunks/screenshots-4UQJE4NC.js +70 -0
- package/dist-cli/chunks/server-AN2G5KO4.js +21 -0
- package/dist-cli/chunks/skills-2PPKPL4B.js +10 -0
- package/dist-cli/chunks/store-PU5ES4YQ.js +2 -0
- package/dist-cli/chunks/test-5LFKOQ4M.js +31 -0
- package/dist-cli/chunks/upload-BYNPC54C.js +2 -0
- package/dist-cli/chunks/vite-plugin-5AEUUBKP.js +9 -0
- package/dist-cli/chunks/whoami-H6FW34JS.js +2 -0
- package/package.json +56 -0
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
/*! sootsim v0.0.1 | (c) 2026 Tamagui LLC | Proprietary — see LICENSE */
|
|
2
|
+
import{spawn as B}from"child_process";import{createServer as C}from"http";import{WebSocket as u,WebSocketServer as v}from"ws";var A=new Set(["tap","keyboard","close"]);function I(p){return!p||typeof p.type!="string"?!1:p.acquireLock===!0?!0:p.readOnly===!0?!1:A.has(p.type)}var m=class p{port;openUrlHandler;httpServer=null;wss=null;nextCommandId=1;nextBrowserId=1;browsers=new Map;primaryBrowserId=null;pendingCommands=new Map;cliBySentId=new Map;cliBrowserBySocket=new Map;cliLastCommandAt=new Map;cliSessionKeyBySocket=new Map;cliLabelBySocket=new Map;restorableBrowsers=new Map;nextCliFallbackId=1;cliIdleTimer=null;static CLI_IDLE_TIMEOUT_MS=6e4;static CLI_LEASE_TTL_MS=6e5;static USER_ACTIVE_LEASE_TTL_MS=8e3;static BROWSER_RECONNECT_TTL_MS=3e4;constructor(e={}){this.port=e.port||7668,this.openUrlHandler=e.openUrl}start(e){if(this.httpServer||this.wss)return;let t=!1,r=s=>{if(s.code!=="EADDRINUSE")throw s;this.resetServerState(),!t&&!e?.silent&&process.stderr.write(`ws bridge port ${this.port} already in use
|
|
3
|
+
`),t=!0};this.httpServer=C(),this.httpServer.on("error",r),this.wss=new v({server:this.httpServer}),this.wss.on("error",r),this.wss.on("connection",(s,o)=>{let a=o.headers.origin,c=a?"browser":"cli",n=null;if(c==="browser")n={id:`tab-${this.nextBrowserId++}`,ws:s,origin:a,connectedAt:Date.now(),lastSeenAt:Date.now(),lastActiveAt:0,recentActions:[]},this.browsers.set(n.id,n),this.shouldPromoteBrowser(n)&&(this.primaryBrowserId=n.id),process.stderr.write(`sootsim browser connected [${n.id}]${a?` (${a})`:""}${n.id===this.primaryBrowserId?" [primary]":""}
|
|
4
|
+
`),this.broadcastBrowserAssignments(),this.broadcastBrowserClientStates();else{let g=`ws-${this.nextCliFallbackId++}`;this.cliSessionKeyBySocket.set(s,g)}s.on("message",g=>{let i;try{i=JSON.parse(g.toString())}catch{return}if(!(!i||typeof i!="object")){if(c==="browser"){if(n&&(n.lastSeenAt=Date.now()),i.type==="bridge:register"&&n){let l=i,w=this.tryRestoreBrowserId(n,l.browserId);n.url=l.url,n.title=l.title,n.userAgent=l.userAgent,w&&(process.stderr.write(`sootsim browser restored [${n.id}]
|
|
5
|
+
`),this.broadcastBrowserAssignments(),this.broadcastBrowserClientStates());return}if(i.type==="bridge:user-focus-state"&&n){let l=i;this.updateUserFocusLease(n,l.focused===!0);return}if(i.type==="bridge:user-interact"&&n){this.updateUserActivity(n);return}if(i.type==="bridge:open-path"){let l=typeof i.path=="string"?i.path:"",w=typeof i.line=="number"&&Number.isFinite(i.line)?i.line:void 0,h=typeof i.column=="number"&&Number.isFinite(i.column)?i.column:void 0;l&&this.openPathInEditor(l,w,h);return}if(i.type==="bridge:boot-clients"&&n){let l=[];for(let[h,y]of this.cliBrowserBySocket)y===n.id&&l.push(h);for(let h of l){this.cliBrowserBySocket.delete(h);try{h.close(1e3,"booted by browser")}catch{}}let w=!!n.cliLease;n.cliLease=void 0,(l.length>0||w)&&(process.stderr.write(`sootsim booted ${l.length} cli client(s)${w?" + cleared lease":""} from [${n.id}]
|
|
6
|
+
`),this.recordBrowserAction(n.id,"browser booted cli clients"),this.broadcastBrowserClientStates());return}let d=this.pendingCommands.get(i.id);if(d){this.pendingCommands.delete(i.id),i.error?d.reject(new Error(i.error)):d.resolve(i.result);return}let f=this.cliBySentId.get(i.id);if(f&&(this.cliBySentId.delete(i.id),f.ws.readyState===u.OPEN)){let l=this.getOtherCliSessionCount(f.ws,f.browserId),w=l>0?{...i,id:f.originalId,i:l}:{...i,id:f.originalId};f.ws.send(JSON.stringify(w))}return}(async()=>{this.cliLastCommandAt.set(s,Date.now());try{if(i.type==="bridge:bye"){let h=this.cliBrowserBySocket.delete(s);this.cliLastCommandAt.delete(s),this.cliSessionKeyBySocket.delete(s),this.cliLabelBySocket.delete(s);for(let[y,S]of this.cliBySentId)S.ws===s&&this.cliBySentId.delete(y);h&&this.broadcastBrowserClientStates();return}if(i.type==="bridge:hello"){let h=typeof i.cliSessionKey=="string"&&i.cliSessionKey.trim()?i.cliSessionKey.trim():this.cliSessionKeyBySocket.get(s)||`ws-${this.nextCliFallbackId++}`;this.cliSessionKeyBySocket.set(s,h),typeof i.cliLabel=="string"&&i.cliLabel.trim()&&this.cliLabelBySocket.set(s,i.cliLabel.trim()),s.readyState===u.OPEN&&s.send(JSON.stringify({id:i.id,result:{cliSessionKey:h,leaseTtlMs:p.CLI_LEASE_TTL_MS,leasing:!0}}));return}if(i.type==="bridge:list-browsers"){s.readyState===u.OPEN&&s.send(JSON.stringify({id:i.id,result:this.listBrowsers()}));return}if(i.type==="bridge:open"){if(typeof i.url!="string"||!i.url)throw new Error("bridge:open requires a url");await this.openUrl(i.url),s.readyState===u.OPEN&&s.send(JSON.stringify({id:i.id,result:{ok:!0,url:i.url}}));return}if(i.type==="bridge:claim"){let h=await this.waitForBrowser(i.browserId),y=this.tryAcquireLease(s,h,{force:i.force===!0});if(!y.granted){s.readyState===u.OPEN&&s.send(JSON.stringify({id:i.id,error:`tab ${h.id} is locked by another cli`,s:y.lock}));return}this.setCliBrowserTarget(s,h.id),this.recordBrowserAction(h.id,y.bootedCount>0?`cli force-claimed tab (booted ${y.bootedCount})`:"cli claimed tab"),s.readyState===u.OPEN&&s.send(JSON.stringify({id:i.id,result:{browserId:h.id,lockedBy:y.lease.cliSessionKey,lockExpiresAt:y.lease.expiresAt,bootedCount:y.bootedCount}}));return}let d=await this.waitForBrowser(i.browserId);if(I(i)){let h=this.tryAcquireLease(s,d);if(!h.granted){s.readyState===u.OPEN&&s.send(JSON.stringify({id:i.id,error:`tab ${d.id} is locked by another cli \u2014 use \`sootsim claim ${d.id} --force\` or \`sootsim open --new\``,s:h.lock}));return}}else this.ensureCliSessionKey(s);this.setCliBrowserTarget(s,d.id),this.recordBrowserAction(d.id,this.describeForwardedCommand(i));let f=this.nextCommandId++;this.cliBySentId.set(f,{browserId:d.id,ws:s,originalId:i.id});let{browserId:l,...w}=i;d.ws.send(JSON.stringify({...w,id:f}))}catch(d){s.readyState===u.OPEN&&s.send(JSON.stringify({id:i.id,error:d instanceof Error?d.message:String(d)}))}})()}}),s.on("close",()=>{if(c==="browser"&&n){process.stderr.write(`sootsim browser disconnected [${n.id}]
|
|
7
|
+
`),this.rememberDisconnectedBrowser(n),this.primaryBrowserId===n.id&&(this.primaryBrowserId=this.getOpenBrowser()?.id??null);for(let[g,i]of this.pendingCommands)i.browserId===n.id&&(i.reject(new Error("browser disconnected")),this.pendingCommands.delete(g));for(let[g,i]of this.cliBySentId)i.browserId===n.id&&(i.ws.readyState===u.OPEN&&i.ws.send(JSON.stringify({id:i.originalId,error:"browser disconnected before responding"})),this.cliBySentId.delete(g));this.broadcastBrowserAssignments(),this.broadcastBrowserClientStates()}else if(c==="cli"){let g=this.cliBrowserBySocket.delete(s);this.cliLastCommandAt.delete(s),this.cliSessionKeyBySocket.delete(s),this.cliLabelBySocket.delete(s);for(let[i,d]of this.cliBySentId)d.ws===s&&this.cliBySentId.delete(i);g&&this.broadcastBrowserClientStates()}})}),this.httpServer.listen(this.port,()=>{process.stderr.write(`ws bridge listening on port ${this.port}
|
|
8
|
+
`)}),this.cliIdleTimer=setInterval(()=>this.sweepIdleCliClients(),3e4),this.cliIdleTimer.unref()}sweepIdleCliClients(){let e=Date.now(),t=!1;for(let[r,s]of this.cliBrowserBySocket){let o=this.cliLastCommandAt.get(r)??0;if(!(e-o<p.CLI_IDLE_TIMEOUT_MS)){this.cliBrowserBySocket.delete(r),this.cliLastCommandAt.delete(r);for(let[a,c]of this.cliBySentId)c.ws===r&&this.cliBySentId.delete(a);try{r.close(1e3,"idle timeout")}catch{}t=!0}}t&&this.broadcastBrowserClientStates(),this.sweepRestorableBrowsers(e)}listBrowsers(){return Array.from(this.browsers.values()).sort((e,t)=>e.id===this.primaryBrowserId?-1:t.id===this.primaryBrowserId?1:e.connectedAt-t.connectedAt).map(e=>this.describeBrowser(e))}async sendCommand(e){let t=await this.waitForBrowser(e.browserId),r=this.nextCommandId++;return new Promise((s,o)=>{let a=setTimeout(()=>{this.pendingCommands.delete(r),this.broadcastBrowserClientStates(),o(new Error("command timed out after 30s"))},3e4);this.pendingCommands.set(r,{browserId:t.id,resolve:g=>{clearTimeout(a),this.pendingCommands.delete(r),this.broadcastBrowserClientStates(),s(g)},reject:g=>{clearTimeout(a),this.pendingCommands.delete(r),this.broadcastBrowserClientStates(),o(g)}}),this.broadcastBrowserClientStates();let{browserId:c,...n}=e;t.ws.send(JSON.stringify({...n,id:r}))})}async evaluate(e,t){return this.sendCommand({type:"evaluate",code:e,browserId:t})}async focusBrowser(e){return this.sendCommand({type:"focus",browserId:e})}async closeBrowser(e){return this.sendCommand({type:"close",browserId:e})}async openPathInEditor(e,t,r){let s=t!=null?`:${t}${r!=null?`:${r}`:""}`:"",o=`${e}${s}`,a=(n,g)=>new Promise(i=>{try{let d=B(n,g,{detached:!0,stdio:"ignore"}),f=!1;d.on("error",()=>{f||(f=!0,i(!1))}),d.on("spawn",()=>{f||(f=!0,d.unref(),i(!0))})}catch{i(!1)}}),c=process.env.REACT_EDITOR||process.env.EDITOR;if(c){let n=c.split(" ").filter(Boolean);if(n.length&&await a(n[0],[...n.slice(1),"-g",o]))return}await a("cursor",["-g",o])||await a("code",["-g",o])||await this.openUrl(e)}async openUrl(e){if(this.openUrlHandler){await this.openUrlHandler(e);return}if(process.platform==="darwin"){B("open",["-g",e],{detached:!0,stdio:"ignore"}).unref();return}if(process.platform==="win32"){B("cmd",["/c","start","",e],{detached:!0,stdio:"ignore"}).unref();return}B("xdg-open",[e],{detached:!0,stdio:"ignore"}).unref()}async close(){this.cliIdleTimer&&(clearInterval(this.cliIdleTimer),this.cliIdleTimer=null);for(let[r,s]of this.pendingCommands)s.reject(new Error("server closing")),this.pendingCommands.delete(r);for(let r of this.browsers.values())r.ws.close();this.browsers.clear(),this.primaryBrowserId=null;let e=this.wss,t=this.httpServer;if(this.wss=null,this.httpServer=null,e)try{e.close()}catch{}if(t)try{t.close()}catch{}}describeBrowser(e){let t;try{t=e.ws.readyState}catch{t=u.CLOSED}let r=this.getActiveLease(e);return{id:e.id,origin:e.origin,url:e.url,title:e.title,userAgent:e.userAgent,connectedAt:e.connectedAt,lastSeenAt:e.lastSeenAt,lastActiveAt:e.lastActiveAt||void 0,isPrimary:e.id===this.primaryBrowserId,readyState:t===u.OPEN?"open":t===u.CLOSING?"closing":"closed",attachedCliCount:this.getAttachedCliCount(e.id),lockedBy:r?r.cliLabel||r.cliSessionKey:void 0,lockedByKind:r?r.kind:void 0,lockExpiresAt:r?r.expiresAt:void 0,userFocused:e.userFocused||void 0}}getActiveLease(e){let t=e.cliLease;return t?Date.now()>=t.expiresAt?(e.cliLease=void 0,null):t:null}tryAcquireLease(e,t,r={}){let s=this.cliSessionKeyBySocket.get(e)??(()=>{let d=`ws-${this.nextCliFallbackId++}`;return this.cliSessionKeyBySocket.set(e,d),d})(),o=this.cliLabelBySocket.get(e),a=Date.now(),c=this.getActiveLease(t),n=c&&c.cliSessionKey===s,g=0;if(c&&!n&&!r.force)return{granted:!1,lease:c,lock:{by:c.cliLabel||c.cliSessionKey,expiresInMs:Math.max(0,c.expiresAt-a)},bootedCount:0};if(c&&!n&&r.force)for(let[d,f]of this.cliBrowserBySocket){if(f!==t.id)continue;let l=this.cliSessionKeyBySocket.get(d);if(l&&l!==s){this.cliBrowserBySocket.delete(d);try{d.close(1e3,"lease claimed by another cli")}catch{}g++}}let i={kind:"cli",cliSessionKey:s,cliLabel:o,expiresAt:a+p.CLI_LEASE_TTL_MS};return t.cliLease=i,{granted:!0,lease:i,bootedCount:g}}updateUserFocusLease(e,t){let r=t;e.userFocused!==r&&(e.userFocused=r,this.broadcastBrowserClientStates())}updateUserActivity(e){let t=this.getActiveLease(e);t&&t.kind==="cli"||(e.cliLease={kind:"user-active",cliSessionKey:"__user-active__",cliLabel:"active user",expiresAt:Date.now()+p.USER_ACTIVE_LEASE_TTL_MS},this.broadcastBrowserClientStates())}ensureCliSessionKey(e){let t=this.cliSessionKeyBySocket.get(e);if(t)return t;let r=`ws-${this.nextCliFallbackId++}`;return this.cliSessionKeyBySocket.set(e,r),r}getOpenBrowser(e){if(e){let r=this.browsers.get(e);return r?.ws.readyState===u.OPEN?r:null}let t=this.primaryBrowserId!=null?this.browsers.get(this.primaryBrowserId):null;if(t?.ws.readyState===u.OPEN)return t;for(let r of this.browsers.values())if(r.ws.readyState===u.OPEN)return r;return null}async waitForBrowser(e,t={}){let r=t.attempts??10,s=t.intervalMs??200;for(let o=0;o<r;o++){let a=this.getOpenBrowser(e);if(a)return a;await new Promise(c=>setTimeout(c,s))}throw new Error(e?`no browser connected with id ${e}`:"no browser connected")}shouldPromoteBrowser(e){let t=this.primaryBrowserId?this.browsers.get(this.primaryBrowserId):null,r=e.origin?.includes(":5173"),s=t?.origin?.includes(":5173");return!t||t.ws.readyState!==u.OPEN||!!r||!s}broadcastBrowserAssignments(){for(let e of this.browsers.values())e.ws.readyState===u.OPEN&&e.ws.send(JSON.stringify({type:"bridge:welcome",browserId:e.id,isPrimary:e.id===this.primaryBrowserId}))}broadcastBrowserClientStates(){for(let e of this.browsers.values()){if(e.ws.readyState!==u.OPEN)continue;let t=this.getActiveLease(e),r={type:"bridge:client-state",attachedCliCount:this.getAttachedCliCount(e.id),activeAgentCommandCount:this.getActiveAgentCommandCount(e.id),recentActions:e.recentActions,lockedBy:t?t.cliLabel||t.cliSessionKey:void 0,lockedByKind:t?t.kind:void 0,lockExpiresAt:t?t.expiresAt:void 0,userFocused:e.userFocused||void 0};e.ws.send(JSON.stringify(r))}}setCliBrowserTarget(e,t){let r=this.cliBrowserBySocket.get(e);r!==t&&(this.cliBrowserBySocket.set(e,t),this.recordBrowserAction(t,r?"cli switched tabs":"cli connected",!1),this.broadcastBrowserClientStates())}recordBrowserAction(e,t,r=!0){let s=t?.trim();if(!s)return;let o=this.browsers.get(e);if(!o)return;let a=Date.now();o.lastActiveAt=a,o.recentActions=[{label:s,at:a},...o.recentActions.filter(c=>c.label!==s)].slice(0,4),r&&this.broadcastBrowserClientStates()}describeForwardedCommand(e){switch(e?.type){case"evaluate":return"evaluated page state";case"screenshot":return"captured screenshot";case"tap":return"sent tap event";case"keyboard":return e?.action==="type"?"typed text":"used keyboard";case"tree":return"dumped tree";case"focus":return"focused tab";case"close":return"requested close";default:return typeof e?.type=="string"?e.type:null}}getAttachedCliCount(e){let t=new Set;for(let[r,s]of this.cliBrowserBySocket){if(s!==e||r.readyState!==u.OPEN)continue;let o=this.cliSessionKeyBySocket.get(r);t.add(o??`ws-unknown-${t.size}`)}return t.size}getOtherCliSessionCount(e,t){let r=this.cliSessionKeyBySocket.get(e),s=new Set;for(let[o,a]of this.cliBrowserBySocket){if(a!==t||o.readyState!==u.OPEN)continue;let c=this.cliSessionKeyBySocket.get(o);c&&c===r||s.add(c??`ws-unknown-${s.size}`)}return s.size}getActiveAgentCommandCount(e){let t=0;for(let r of this.pendingCommands.values())r.browserId===e&&t++;return t}tryRestoreBrowserId(e,t){let r=t?.trim();if(!r||r===e.id)return!1;let s=this.browsers.get(r);if(s&&s!==e&&s.ws.readyState===u.OPEN)return!1;let o=this.getRestorableBrowserState(r),a=e.id;this.browsers.delete(a),e.id=r,o&&(e.recentActions=o.recentActions.map(c=>({...c})),e.lastActiveAt=o.lastActiveAt,e.cliLease=o.cliLease?{...o.cliLease}:void 0,this.restorableBrowsers.delete(r)),this.browsers.set(e.id,e),this.primaryBrowserId===a&&(this.primaryBrowserId=e.id);for(let[c,n]of this.cliBrowserBySocket)n===a&&this.cliBrowserBySocket.set(c,e.id);return!0}rememberDisconnectedBrowser(e){let t=this.getActiveLease(e);this.restorableBrowsers.set(e.id,{recentActions:e.recentActions.map(r=>({...r})),lastActiveAt:e.lastActiveAt,cliLease:t&&t.kind==="cli"?{...t}:void 0,expiresAt:Date.now()+p.BROWSER_RECONNECT_TTL_MS}),this.browsers.delete(e.id)}getRestorableBrowserState(e){let t=this.restorableBrowsers.get(e);return t?t.expiresAt<=Date.now()?(this.restorableBrowsers.delete(e),null):(t.cliLease&&t.cliLease.expiresAt<=Date.now()&&(t.cliLease=void 0),t):null}sweepRestorableBrowsers(e=Date.now()){for(let[t,r]of this.restorableBrowsers)if(!(r.expiresAt>e)){this.restorableBrowsers.delete(t);for(let[s,o]of this.cliBrowserBySocket)o===t&&this.cliBrowserBySocket.delete(s)}}resetServerState(){this.cliIdleTimer&&(clearInterval(this.cliIdleTimer),this.cliIdleTimer=null);let e=this.wss,t=this.httpServer;if(this.wss=null,this.httpServer=null,e)try{e.close()}catch{}if(t)try{t.close()}catch{}}};export{m as a};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
/*! sootsim v0.0.1 | (c) 2026 Tamagui LLC | Proprietary — see LICENSE */
|
|
2
|
+
import{a as n,b as d}from"./chunk-MBFP2LVH.js";import{execFileSync as v,spawn as f}from"child_process";import{existsSync as g}from"fs";var D=["/Applications/Google Chrome.app/Contents/MacOS/Google Chrome","/Applications/Chromium.app/Contents/MacOS/Chromium","/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge","/Applications/Brave Browser.app/Contents/MacOS/Brave Browser","/Applications/Arc.app/Contents/MacOS/Arc"],y=["/usr/bin/google-chrome","/usr/bin/chromium","/usr/bin/chromium-browser","/usr/bin/microsoft-edge","/snap/bin/chromium"],w=["C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe","C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe","C:\\Program Files (x86)\\Microsoft\\Edge\\Application\\msedge.exe"];function p(){let e=(process.platform==="darwin"?D:process.platform==="win32"?w:y).find(i=>g(i));if(e)return e;if(process.platform==="win32")return null;for(let i of["google-chrome","chromium","chromium-browser","microsoft-edge"])try{let t=v("which",[i],{encoding:"utf8",timeout:1500}).trim();if(t)return t}catch{}return null}function b(){let r=p();return r?{available:!0,reason:null,detail:r}:{available:!1,reason:"no chromium-family browser found (chrome, chromium, edge, brave, arc)"}}async function x(r){let e=p();if(!e)return{launched:!1,message:"chromium not found \u2014 install chrome or run `sootsim list --drivers`"};if(!r.url)return{launched:!1,message:"chromium driver requires a target url"};let i=[];r.headless?i.push("--headless=new"):i.push("--new-window"),i.push(r.url);try{let t=f(e,i,{detached:r.detached??!0,stdio:"ignore"});return t.unref(),{launched:!0,message:`chromium launched \u2192 ${r.url}`,pid:t.pid,target:e,attachUrl:r.url}}catch(t){return{launched:!1,message:`chromium spawn failed: ${t instanceof Error?t.message:String(t)}`}}}var o={id:"chromium",name:"chromium",description:"system chrome / chromium / edge \u2014 supports --headless",kind:"browser",availability:b,launch:x};function A(){let r=n();return r?{available:!0,reason:null,detail:`${r.kind} @ ${r.path}`}:{available:!1,reason:"sootsim desktop app not installed (run `sootsim install-desktop`)"}}async function L(r){let e=n();if(!e)return{launched:!1,message:"sootsim desktop app not installed"};try{let i=await d(r.url,e,{device:r.device});return i.launched?{launched:!0,message:r.url?`electron launched via ${i.via} \u2192 ${r.url}`:`electron launched via ${i.via}`,target:i.target,attachUrl:r.url}:{launched:!1,message:"desktop companion failed to start"}}catch(i){return{launched:!1,message:`electron launch failed: ${i instanceof Error?i.message:String(i)}`}}}var s={id:"electron",name:"electron",description:"sootsim desktop companion app (native window, menu bar)",kind:"native",availability:A,launch:L};import{createRequire as C}from"module";function h(){try{let r=C(process.cwd()+"/");for(let e of["playwright","playwright-chromium","playwright-core"])try{return r.resolve(e),e}catch{}}catch{}return null}function R(){let r=h();return r?{available:!0,reason:null,detail:`resolved via ${r}`}:{available:!1,reason:"playwright not installed in the current workspace"}}async function k(r){let e=h();if(!e)return{launched:!1,message:"playwright not installed \u2014 run `bun add -D playwright` first"};if(!r.url)return{launched:!1,message:"playwright driver requires a target url"};try{return await(await(await(await(await import(e)).chromium.launch({headless:r.headless??!0})).newContext()).newPage()).goto(r.url),{launched:!0,message:`playwright chromium launched \u2192 ${r.url}`,target:e,attachUrl:r.url}}catch(i){return{launched:!1,message:`playwright launch failed: ${i instanceof Error?i.message:String(i)}`}}}var l={id:"playwright",name:"playwright",description:"programmatic chromium via the playwright package \u2014 headless default",kind:"automation",availability:R,launch:k};import{spawn as c}from"child_process";function S(){return process.platform!=="darwin"&&process.platform!=="linux"&&process.platform!=="win32"?{available:!1,reason:`unsupported platform: ${process.platform}`}:{available:!0,reason:null,detail:process.platform==="darwin"?"open(1)":process.platform==="win32"?"cmd /c start":"xdg-open(1)"}}async function $(r){if(r.headless)return{launched:!1,message:"system driver does not support --headless; use chromium or playwright"};if(!r.url)return{launched:!1,message:"system driver requires a target url"};try{if(process.platform==="darwin"){let i=c("open",["-g",r.url],{detached:r.detached??!0,stdio:"ignore"});return i.unref(),{launched:!0,message:`system open \u2192 ${r.url}`,pid:i.pid,attachUrl:r.url}}if(process.platform==="win32"){let i=c("cmd",["/c","start","",r.url],{detached:r.detached??!0,stdio:"ignore"});return i.unref(),{launched:!0,message:`system start \u2192 ${r.url}`,pid:i.pid,attachUrl:r.url}}let e=c("xdg-open",[r.url],{detached:r.detached??!0,stdio:"ignore"});return e.unref(),{launched:!0,message:`xdg-open \u2192 ${r.url}`,pid:e.pid,attachUrl:r.url}}catch(e){return{launched:!1,message:`system launch failed: ${e instanceof Error?e.message:String(e)}`}}}var u={id:"system",name:"system",description:"OS default handler \u2014 open(mac), xdg-open(linux), cmd start(win)",kind:"delegate",availability:S,launch:$};var a=[o,s,l,u];function O(){return a}function E(r){return a.find(e=>e.id===r)??null}function I(r,e){if(r)return a.find(t=>t.id===r)??null;for(let i of e){let t=a.find(m=>m.id===i);if(t&&t.availability().available)return t}return null}function M(){return a.map(r=>{let e=r.availability();return{id:r.id,name:r.name,kind:r.kind,description:r.description,available:e.available,reason:e.reason,detail:e.detail??null}})}export{o as a,s as b,l as c,u as d,a as e,O as f,E as g,I as h,M as i};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
/*! sootsim v0.0.1 | (c) 2026 Tamagui LLC | Proprietary — see LICENSE */
|
|
@@ -0,0 +1,322 @@
|
|
|
1
|
+
/*! sootsim v0.0.1 | (c) 2026 Tamagui LLC | Proprietary — see LICENSE */
|
|
2
|
+
import{a as Oe}from"./chunk-G5MR66EB.js";import{a as Ce,b as ae,c as Ne}from"./chunk-KXYKAYYB.js";import{f as ve}from"./chunk-YCETS3B3.js";import{a as H,b as R,c as Ee,d as se,f as Ae,g as Pe}from"./chunk-JSF5LPNT.js";import{a as ke,c as Re,i as $e}from"./chunk-HOIHCO7S.js";import{b as Te}from"./chunk-KSB6MSZ4.js";import{b as ie,c as Ie,d as Fe}from"./chunk-MPSZ5EWF.js";import{d as xe}from"./chunk-3C3ZH7PP.js";import{a as _e}from"./chunk-MBFP2LVH.js";import{a as st}from"./chunk-E522F5JW.js";import*as I from"fs";import{tmpdir as ze}from"os";import*as S from"path";import{execSync as je}from"child_process";import St from"http";import vt from"net";import{existsSync as y,readFileSync as D,writeFileSync as M}from"node:fs";import{homedir as it}from"node:os";import{dirname as at,join as w,resolve as lt}from"node:path";import{fileURLToPath as ct}from"node:url";var N=it(),dt=()=>{let t=at(ct(import.meta.url));return lt(t,"../../sootsim-engine/scripts/expensify-web-proxy.ts")},le={USE_NGROK:"true",NGROK_URL:"http://localhost:9000/",SECURE_NGROK_URL:"http://localhost:9000/"},V=w(N,"github/uniswap-interface"),ut=w(V,"apps/mobile"),q=w(V,".env.defaults.local"),ft="stored-in-.env.local",Me="# sootsim demo env overrides",pt=w(V,"packages/uniswap/src/features/forceUpgrade/hooks/useForceUpgradeStatus.ts"),mt=w(V,"apps/mobile/src/notification-service/data-sources/createForceUpgradeNotificationDataSource.ts"),De="SOOTSIM_DEMO_DISABLE_FORCE_UPGRADE";function Ue(t){if(!y(t))return{};let e={},o=D(t,"utf8");for(let r of o.split(/\r?\n/)){let n=r.trim();if(!n||n.startsWith("#"))continue;let i=n.match(/^([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/);if(!i)continue;let s=i[2].trim();(s.startsWith('"')&&s.endsWith('"')||s.startsWith("'")&&s.endsWith("'"))&&(s=s.slice(1,-1)),e[i[1]]=s}return e}function ce(t){if(!t)return!1;let e=t.trim();return!(!e||e.includes(ft)||e==="TRADING_API_KEY"||e==="UNISWAP_API_KEY")}function Le(t,e){for(let o of t)for(let r of e){let n=o[r];if(ce(n))return n.trim()}}function Ve(){let t=Ue(q),e=Ue(w(V,"apps/web/.env")),o=[process.env,t,e],r={},n=[["AMPLITUDE_PROXY_URL_OVERRIDE",["REACT_APP_AMPLITUDE_PROXY_URL"]],["QUICKNODE_ENDPOINT_NAME",["REACT_APP_QUICKNODE_ENDPOINT_NAME"]],["QUICKNODE_ENDPOINT_TOKEN",["REACT_APP_QUICKNODE_ENDPOINT_TOKEN"]],["INFURA_KEY",["REACT_APP_INFURA_KEY"]],["STATSIG_API_KEY",["REACT_APP_STATSIG_API_KEY"]],["STATSIG_PROXY_URL_OVERRIDE",["REACT_APP_STATSIG_PROXY_URL"]],["WALLETCONNECT_PROJECT_ID",["REACT_APP_WALLET_CONNECT_PROJECT_ID"]],["WALLETCONNECT_PROJECT_ID_BETA",["REACT_APP_WALLET_CONNECT_PROJECT_ID"]],["WALLETCONNECT_PROJECT_ID_DEV",["REACT_APP_WALLET_CONNECT_PROJECT_ID"]],["TRADING_API_KEY",["REACT_APP_TRADING_API_KEY"]],["UNISWAP_API_KEY",[]]];for(let[s,a]of n){let l=Le(o,[s,...a]);if(l){r[s]=l;for(let c of a)r[c]=l}}if(!(ce(r.TRADING_API_KEY)&&ce(r.UNISWAP_API_KEY))){let s=Le(o,["GRAPHQL_URL_OVERRIDE","REACT_APP_AWS_API_ENDPOINT"])||"https://interface.gateway.uniswap.org/v1/graphql";r.API_BASE_URL_OVERRIDE="https://interface.gateway.uniswap.org",r.API_BASE_URL_V2_OVERRIDE="https://interface.gateway.uniswap.org/v2",r.GRAPHQL_URL_OVERRIDE=s,r.TRADING_API_URL_OVERRIDE="https://trading-api-labs.interface.gateway.uniswap.org",r.FOR_API_URL_OVERRIDE="https://for.interface.gateway.uniswap.org/v2/FOR.v1.FORService"}return r}function wt(){let t=y(q)?D(q,"utf8"):"";if(t&&!t.includes(Me))return;let e=Ve(),o=[Me];for(let[r,n]of Object.entries(e).sort(([i],[s])=>i.localeCompare(s)))o.push(`${r}=${JSON.stringify(n)}`);o.push(""),M(q,`${o.join(`
|
|
3
|
+
`)}
|
|
4
|
+
`)}function gt(){let t=`export function useForceUpgradeStatus(): ForceUpgradeStatus {
|
|
5
|
+
`,e=` // sootsim demo: bypass the force-upgrade gate during local engine demos.
|
|
6
|
+
return 'not-required'
|
|
7
|
+
|
|
8
|
+
`,o=` // sootsim demo: bypass the force-upgrade gate during local engine demos.
|
|
9
|
+
if (process.env.${De} === 'true') {
|
|
10
|
+
return 'not-required'
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
`,r=` const getForceUpgradeStatus = (): ForceUpgradeStatus => {
|
|
14
|
+
`,n=` // sootsim demo: bypass the force-upgrade gate during local engine demos.
|
|
15
|
+
return 'not-required'
|
|
16
|
+
|
|
17
|
+
`,i=` // sootsim demo: bypass the force-upgrade gate during local engine demos.
|
|
18
|
+
if (process.env.${De} === 'true') {
|
|
19
|
+
return 'not-required'
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
`,s=(a,l,c,m)=>{let h=D(a,"utf8");if(!h.includes(c)){if(h.includes(m)){M(a,h.replace(m,c));return}if(!h.includes(l))throw new Error(`uniswap demo patch failed: expected snippet not found in ${a}`);M(a,h.replace(l,`${l}${c}`))}};s(pt,t,e,o),s(mt,r,n,i)}var v=w(N,"github/eigen"),z=w(v,"keys.shared.json"),We=w(v,"metaflags.json"),Ke=w(v,"src/__generated__/.relay-complete");function ht(){if(y(z))try{let t=JSON.parse(D(z,"utf8"));if(!t||typeof t!="object")return;let e=t.secure&&typeof t.secure=="object"?t.secure:void 0,o=t.public&&typeof t.public=="object"?t.public:void 0;return!e&&!o?void 0:{secure:e,public:o}}catch{return}}function bt(){let t=process.env.SOOTSIM_ARTSY_EMAIL??process.env.MAESTRO_TEST_EMAIL,e=process.env.SOOTSIM_ARTSY_PASSWORD??process.env.MAESTRO_TEST_PASSWORD,o=ht(),r={};if(t&&e&&(r.SOOTSIM_LAUNCH_ARGUMENTS=JSON.stringify({email:t,password:e,useMaestroInit:!0})),o&&(r.SOOTSIM_REACT_NATIVE_KEYS_JSON=JSON.stringify(o)),Object.keys(r).length!==0)return{env:r}}function yt(){if(!y(v))return;let{execSync:t}=st("node:child_process"),e=w(v,".yarn/releases/yarn-4.10.3.cjs");if(y(e)){let r=D(e,"utf8"),n='["clone","-c core.autocrlf=false",';r.includes(n)&&M(e,r.replace(n,'["clone","-c","core.autocrlf=false",'))}if(y(w(v,"node_modules/.yarn-state.yml"))||t("yarn install",{cwd:v,stdio:"inherit",env:{...process.env,YARN_CHECKSUM_BEHAVIOR:"update"}}),!y(z)||!y(We))try{t("yarn setup:oss",{cwd:v,stdio:"inherit"})}catch{if(!y(z)||!y(We))throw new Error("artsy demo: setup:oss did not create keys/metaflags")}let o=w(v,"node_modules/react-native-launch-arguments/package.json");if(y(o)){let r=D(o,"utf8");r.includes('"dist/index.js"')&&M(o,r.replace('"dist/index.js"','"src/index.ts"'))}y(Ke)||(t("yarn relay",{cwd:v,stdio:"inherit"}),M(Ke,""))}var Be=[{name:"bluesky",label:"Bluesky",dir:w(N,"github/bluesky"),preferredPort:8082,framework:"expo",command:t=>({cmd:`npx expo start --port ${t}`}),credentials:{envVars:["SOOTSIM_BLUESKY_PASSWORD"],known:{HANDLE:"natew.bsky.social"}}},{name:"3pc",label:"3PunchConvo",dir:w(N,"lightstrike-labs/three-punch-convo-app/apps/one"),preferredPort:8081,framework:"one",command:t=>({cmd:"npx one dev",env:{ONE_PORT:String(t)}})},{name:"uniswap",label:"Uniswap",dir:ut,preferredPort:8085,framework:"expo",prepare:()=>{wt(),gt()},command:t=>({cmd:`npx expo start --clear --port ${t}`,env:Ve()})},{name:"takeout",label:"Takeout",dir:w(N,"takeout"),preferredPort:8086,framework:"one",command:t=>({cmd:"npx one dev",env:{ONE_PORT:String(t)}})},{name:"expensify",label:"Expensify",dir:w(N,"github/expensify"),preferredPort:8087,framework:"rock",runtimeConfig:{env:le},sidecars:[{name:"web-proxy",port:9e3,readyPath:"/api/Ping",command:()=>({cmd:`bun ${JSON.stringify(dt())}`,env:le})}],command:t=>({cmd:`fnm exec --using=20.20.0 npx rock start --port ${t} --no-interactive`,env:le})},{name:"artsy",label:"Artsy",dir:v,preferredPort:8088,framework:"expo",runtimeConfig:bt(),prepare:()=>{yt()},command:t=>({cmd:`npx react-native start --port ${t}`}),credentials:{envVars:["SOOTSIM_ARTSY_EMAIL","SOOTSIM_ARTSY_PASSWORD"],note:"auto-login reuses Artsy\u2019s built-in Maestro launch-arguments hook"}}];var Je=250,_t=120;function Tt(t,e=_t){return new Promise(o=>{let r=new vt.Socket,n=!1,i=s=>{n||(n=!0,r.destroy(),o(s))};r.setTimeout(e),r.once("connect",()=>i(!0)),r.once("timeout",()=>i(!1)),r.once("error",()=>i(!1)),r.connect(t,"localhost")})}function B(t,e,o="GET",r=Je,n={}){return new Promise(i=>{let s=St.request({hostname:"localhost",port:t,path:e,method:o,timeout:r,headers:n},a=>{let l="";a.on("data",c=>l+=c.toString()),a.on("end",()=>i({statusCode:a.statusCode||0,body:l}))});s.on("error",()=>i(null)),s.setTimeout(r,()=>{s.destroy(),i(null)}),s.end()})}var Et=[8081,8082,8083,8084,8085,8086,3e3,3001,19e3].map(t=>({port:t,pid:0}));function de(t,e){return!(t<=0||t>=2e4||e.has(t)||t>=5170&&t<=5200)}function At(t=[]){let e=new Set(t);try{let o=je("lsof -iTCP -sTCP:LISTEN -P -n 2>/dev/null | grep -E '^(node|bun)'",{encoding:"utf8",timeout:2e3});if(o.trim()){let r=new Map;for(let n of o.trim().split(`
|
|
23
|
+
`)){let i=n.trim().split(/\s+/);if(i.length<9)continue;let s=Number(i[1]),l=i[8].match(/:(\d+)$/);if(!l)continue;let c=Number(l[1]);de(c,e)&&(r.has(c)||r.set(c,s))}if(r.size>0)return[...r.entries()].map(([n,i])=>({port:n,pid:i}))}}catch{}try{let o=je(`ss -tlnp 2>/dev/null | grep -E '"(node|bun)"'`,{encoding:"utf8",timeout:2e3});if(o.trim()){let r=new Map;for(let n of o.trim().split(`
|
|
24
|
+
`)){let i=n.match(/:(\d+)\s/),s=n.match(/pid=(\d+)/);if(!i)continue;let a=Number(i[1]),l=s?Number(s[1]):0;de(a,e)&&(r.has(a)||r.set(a,l))}if(r.size>0)return[...r.entries()].map(([n,i])=>({port:n,pid:i}))}}catch{}return Et.filter(o=>de(o.port,e))}function Pt(t,e){return{port:t,framework:e,bundleUrl:U(t,`http://localhost:${t}/index.bundle?platform=ios&dev=true&hot=true&minify=false`),hmrUrl:`ws://localhost:${t}/hot`,lastSeen:Date.now()}}function U(t,e){let o=Be.find(r=>r.preferredPort===t);return o?.runtimeConfig?ke(e,o.runtimeConfig):e}function xt(t){return t.includes("/node_modules/one/metro-entry.bundle")}function X(t,e,o){if(!e)return t;try{let r=JSON.parse(e.body),n=r?.extra?.expoClient||r?.extra||{};n.name&&(t.projectName=n.name),n.ios?.bundleIdentifier&&(t.bundleId=n.ios.bundleIdentifier),t.framework==="metro"&&n.sdkVersion&&(t.framework="expo");let i=r?.launchAsset?.url;i&&!t.patched&&!xt(t.bundleUrl)&&(t.bundleUrl=U(t.port,i));let s=n.iconUrl||n.ios?.iconUrl||n.icon||n.ios?.icon;if(s)if(t.iconPath=s,o)if(s.startsWith("http"))t.iconUrl=o(s);else{let a=s.replace(/^\.\//,"");t.iconUrl=o(`http://localhost:${t.port}/assets/${a}`)}else t.iconUrl=s.startsWith("http")?s:`http://localhost:${t.port}/assets/${s.replace(/^\.\//,"")}`}catch{}return t}var A=new Set,$=new Set;async function It(t,e){if(!await Tt(t))return null;let o="/node_modules/one/metro-entry.bundle?platform=ios&dev=true",[r,n,i,s,a]=await Promise.all([A.has(t)?Promise.resolve(null):B(t,"/__soot/"),B(t,"/status"),B(t,o,"HEAD"),B(t,"/","GET",Je,{"expo-platform":"ios"}),$.has(t)?Promise.resolve(null):B(t,"/_expo/status")]);if(a&&a.statusCode===200?$.delete(t):$.has(t)||$.add(t),i&&i.statusCode>0&&i.statusCode<400)return A.add(t),X({port:t,framework:"one",bundleUrl:U(t,`http://localhost:${t}${o}&minify=false`),hmrUrl:`ws://localhost:${t}/hot`,lastSeen:Date.now()},s,e);if(n&&n.body.includes("packager-status:running"))return A.add(t),X(Pt(t,a&&a.statusCode===200?"expo":"metro"),s,e);if(s)try{let l=JSON.parse(s.body);if((l?.extra?.expoClient||{}).name){let m=l?.launchAsset?.url||`http://localhost:${t}/index.bundle?platform=ios&dev=true&hot=true&minify=false`;return A.add(t),X({port:t,framework:"one",bundleUrl:U(t,m),hmrUrl:`ws://localhost:${t}/hot`,lastSeen:Date.now()},s,e)}}catch{}return r&&r.statusCode===200&&r.body.includes("sootsim-patched")?(A.delete(t),X({port:t,framework:"one",bundleUrl:U(t,`http://localhost:${t}/__soot/bundle.js`),hmrUrl:`ws://localhost:${t}/hot`,lastSeen:Date.now(),patched:!0},s,e)):(A.add(t),null)}function Ft(t){let e=t.projectName?.trim().toLowerCase();return!!(e==="soot"||e==="sootsim"||t.bundleId?.trim().toLowerCase()?.startsWith("dev.soot"))}var Q=new Map,kt=3e4,Rt=1500;function $t(t){return!!(!t||t.framework==="metro"||t.framework==="unknown"||t.bundleUrl.includes("minify=false"))}function Ot(t){return t?U(t.port,t.bundleUrl)===t.bundleUrl:!0}function Ct(t,e,o=Date.now()){if(e===0||t.pid!==e||!Ot(t.result))return!1;let r=o-t.cachedAt;return!(t.result===null&&r>=kt||$t(t.result)&&r>=Rt)}async function Ye(t={}){let e=At(t.excludePorts),o=new Set(e.map(i=>i.port));for(let i of[...Q.keys()])o.has(i)||Q.delete(i);for(let i of[...A])o.has(i)||A.delete(i);for(let i of[...$])o.has(i)||$.delete(i);let r=[],n=[];for(let{port:i,pid:s}of e){let a=Q.get(i);if(a&&Ct(a,s)){a.result&&r.push(a.result);continue}a&&a.pid!==s&&(A.delete(i),$.delete(i)),n.push({port:i,pid:s})}return n.length>0&&(await Promise.all(n.map(s=>It(s.port,t.buildIconProxyUrl)))).forEach((s,a)=>{let{port:l,pid:c}=n[a];c!==0&&Q.set(l,{pid:c,result:s,cachedAt:Date.now()}),s&&r.push(s)}),r.filter(i=>!Ft(i))}import*as b from"fs";import*as g from"path";var Z=1e4,ee=393,L=852,Ge="__sootsimCliPerf",Nt="maestroCopiedText",fe=new Map;function p(t){return new Promise(e=>setTimeout(e,t))}function Mt(t){return t?g.basename(t)===".maestro"?g.dirname(t):t:process.cwd()}function Dt(t,e,o){let r=e.endsWith(".png")?e:`${e}.png`;if(g.isAbsolute(r))return r;if(o.mode==="flow"&&/[\\/]/.test(r)){let n=r.startsWith("./")||r.startsWith("../")?o.flowDir??process.cwd():Mt(o.flowDir);return g.resolve(n,r)}return g.join(t,r)}function Ut(t){if(typeof t=="string")return{path:t,withFrame:!1};let e=t.path?.trim()||t.name?.trim();if(!e)throw new Error("takeScreenshot object form requires path or name");return{path:e,withFrame:t.withFrame===!0}}function ue(t){let[e,o]=t.split(",").map(n=>n.trim()),r=(n,i)=>n.endsWith("%")?Number.parseFloat(n)/100*i:Number.parseFloat(n);return{x:r(e,ee),y:r(o,L)}}function pe(t){return typeof t=="string"?t.replace(/\$\{([A-Za-z_][A-Za-z0-9_]*)\}/g,(e,o)=>{if(fe.has(o))return fe.get(o);let r=process.env[o];if(r===void 0)throw new Error(`missing environment variable for flow placeholder: ${o}`);return r}):Array.isArray(t)?t.map(e=>pe(e)):t&&typeof t=="object"?Object.fromEntries(Object.entries(t).map(([e,o])=>[e,pe(o)])):t}function Lt(t){let e=t.split(/^---$/m),o=e.length>1?e[e.length-1]:t,r=pe(R.parse(o));return Array.isArray(r)?r:[]}var te=class{constructor(e,o){this.bridge=e;this.opts=o}stepDelay=0;firstLaunchDone=!1;profilingEnabled=!1;recordingEnabled=!1;browserRouteHint=null;lastFailedStep=null;get browserId(){return this.opts.browserId}setBrowserRouteHint(e){this.browserRouteHint=this.normalizeBrowserRoute(e)}normalizeBrowserRoute(e){if(!e)return null;try{let o=new URL(e);o.searchParams.delete("inspectOpen");let r=o.searchParams.toString();return`${o.origin}${o.pathname}${r?`?${r}`:""}`}catch{return e}}async refreshBrowserId(){if(this.opts.browserId)try{let e=await this.bridge.listBrowsers(),o=e.find(l=>l.id===this.opts.browserId);if(o&&(this.browserRouteHint=this.normalizeBrowserRoute(o.url||o.origin)),e.find(l=>l.id===this.opts.browserId&&l.readyState==="open")||!this.browserRouteHint)return;let n=this.browserRouteHint&&e.find(l=>l.readyState==="open"&&this.normalizeBrowserRoute(l.url||l.origin)===this.browserRouteHint);if(!n)return;let i=e.find(l=>l.isPrimary&&l.readyState==="open"),s=e.find(l=>l.readyState==="open"),a=n??i??s;a&&(this.opts.browserId=a.id,console.log(` [flow] session rotated to ${a.id}`))}catch{}}async evaluate(e){return this.bridge.send({type:"evaluate",browserId:this.opts.browserId,code:e})}async callTest(e,...o){return this.bridge.send({type:"call",browserId:this.opts.browserId,path:`__sootsimTest.${e}`,args:o})}async waitForTree(e=Z){let o=Date.now()+e,r=null;for(;Date.now()<o;){try{let n=await this.evaluate(`(async () => {
|
|
25
|
+
const test = window.__sootsimTest
|
|
26
|
+
if (!test) return { count: 0, loading: true }
|
|
27
|
+
const count = (await test.getNodeCount?.()) || 0
|
|
28
|
+
const external = globalThis.__sootsimExternalAppState
|
|
29
|
+
if (external?.error) {
|
|
30
|
+
return { count, loading: false, error: String(external.error) }
|
|
31
|
+
}
|
|
32
|
+
if (external) {
|
|
33
|
+
return {
|
|
34
|
+
count,
|
|
35
|
+
loading: !external.ready,
|
|
36
|
+
error: null,
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
const loadingNode = await test.findByText?.('loading')
|
|
40
|
+
const capturingNode = await test.findByText?.('capturing')
|
|
41
|
+
const openingAppNode = await test.findByText?.('opening app')
|
|
42
|
+
const isLoading = !!loadingNode || !!capturingNode || !!openingAppNode || count < 5
|
|
43
|
+
return { count, loading: isLoading, error: null }
|
|
44
|
+
})()`);if(n?.error)throw new Error(`app failed to load: ${n.error}`);if(n&&n.count>10&&!n.loading)return}catch(n){r=n instanceof Error?n:new Error(String(n)),await this.refreshBrowserId()}await p(500)}throw r?.message.startsWith("app failed to load:")?r:new Error(`app not ready after ${e}ms`)}async ensureRecordingStarted(){if(!this.opts.recordingOutputDir)throw new Error("recording output directory not configured");let e=await this.evaluate(`(() => {
|
|
45
|
+
const rec = window.__sootsimRecorder
|
|
46
|
+
if (!rec) return { ok: false, error: 'recorder unavailable on this page' }
|
|
47
|
+
if (rec.state() === 'recording') return { ok: true, format: 'webm' }
|
|
48
|
+
return rec.start({ format: 'webm', fps: 24 })
|
|
49
|
+
})()`);if(!e?.ok)throw new Error(e?.error||"recording unavailable on this page")}async startRecording(){this.recordingEnabled=!0,await this.ensureRecordingStarted()}prepareRecording(){this.recordingEnabled=!0}async stopRecording(){if(!this.recordingEnabled||!this.opts.recordingOutputDir)return null;this.recordingEnabled=!1,await this.evaluate("window.__sootsimRecorder.stop()");let e=[],o=0;for(;;){let n=await this.evaluate(`window.__sootsimRecorder.getBlobBase64({ offset: ${o}, chunk: 2097152 })`);if(!n||(e.push(Buffer.from(n.data,"base64")),o=n.offset,n.done))break}if(e.length===0)throw new Error("recording requested but no video buffer was produced");b.mkdirSync(this.opts.recordingOutputDir,{recursive:!0});let r=g.join(this.opts.recordingOutputDir,`sootsim-${Date.now()}.webm`);return b.writeFileSync(r,Buffer.concat(e)),r}async findElement(e){return this.evaluate(`(async () => {
|
|
50
|
+
const test = window.__sootsimTest
|
|
51
|
+
if (!test) return null
|
|
52
|
+
let node = null
|
|
53
|
+
if (${JSON.stringify(!!e.text)}) node = await test.findByText(${JSON.stringify(e.text||"")})
|
|
54
|
+
if (!node && ${JSON.stringify(!!e.id)}) {
|
|
55
|
+
node = (await test.findByTestId(${JSON.stringify(e.id||"")})) || (await test.findById(${JSON.stringify(e.id||"")}))
|
|
56
|
+
}
|
|
57
|
+
if (!node || !node.absolutePosition || !node.layout) return null
|
|
58
|
+
return {
|
|
59
|
+
nodeId: typeof node.nodeId === 'number' ? node.nodeId : null,
|
|
60
|
+
id: node.id || null,
|
|
61
|
+
testID: node.testID || null,
|
|
62
|
+
text: node.text || null,
|
|
63
|
+
absolutePosition: node.absolutePosition,
|
|
64
|
+
layout: node.layout,
|
|
65
|
+
isTextInput: !!node.isTextInput,
|
|
66
|
+
}
|
|
67
|
+
})()`)}async resolveTapTarget(e){return this.evaluate(`(async () => {
|
|
68
|
+
const test = window.__sootsimTest
|
|
69
|
+
if (!test?.resolveTapTarget) return null
|
|
70
|
+
return await test.resolveTapTarget(${e})
|
|
71
|
+
})()`)}async activatePressTarget(e){return this.evaluate(`(async () => {
|
|
72
|
+
const test = window.__sootsimTest
|
|
73
|
+
if (!test) return null
|
|
74
|
+
${e.id?`const direct = await test.activatePressById?.(${JSON.stringify(e.id)})`:`const direct = await test.activatePressByText?.(${JSON.stringify(e.text||"")})`}
|
|
75
|
+
return direct || null
|
|
76
|
+
})()`)}async activatePressAt(e,o){return this.evaluate(`(async () => {
|
|
77
|
+
const test = window.__sootsimTest
|
|
78
|
+
if (!test?.activatePressAt) return null
|
|
79
|
+
return await test.activatePressAt(${e}, ${o})
|
|
80
|
+
})()`)}async tap(e,o){return this.bridge.send({type:"tap",browserId:this.opts.browserId,x:e,y:o})}async tapOn(e){let o=typeof e=="string"?{text:e}:e;if(o.point){let l=ue(o.point);(await this.activatePressAt(l.x,l.y))?.ok||await this.tap(l.x,l.y),await p(300);return}let r=5e3,n=150,i=Date.now()+r,s=await this.findElement({text:o.text,id:o.id});for(;!s&&Date.now()<i;)await p(n),s=await this.findElement({text:o.text,id:o.id});if(s&&!s.isTextInput&&(await this.activatePressTarget(o))?.ok){await p(300);return}if(s){let l=typeof s.nodeId=="number"?await this.resolveTapTarget(s.nodeId):null,c=l?.cx??s.absolutePosition.x+s.layout.width/2,m=l?.cy??s.absolutePosition.y+s.layout.height/2;if((await this.tap(c,m))?.hit!==!1){await p(300);return}}if((await this.activatePressTarget(o))?.ok){await p(300);return}throw new Error(`tapOn: element not found: ${JSON.stringify(o)}`)}async tapAtCoords(e,o){await this.tap(e,o),await p(300)}async doubleTapAtCoords(e,o,r=80){let n=Math.max(0,Math.round(r));if(!await this.evaluate(`(async () => {
|
|
81
|
+
const interact = window.__sootsimInteract
|
|
82
|
+
if (interact?.doubleTap) {
|
|
83
|
+
return !!(await interact.doubleTap(${e}, ${o}, ${n}))
|
|
84
|
+
}
|
|
85
|
+
if (!interact?.tap) return false
|
|
86
|
+
const first = await interact.tap(${e}, ${o})
|
|
87
|
+
if (!first || first.hit === false) return false
|
|
88
|
+
await new Promise((resolve) => setTimeout(resolve, ${n}))
|
|
89
|
+
const second = await interact.tap(${e}, ${o})
|
|
90
|
+
return !!second && second.hit !== false
|
|
91
|
+
})()`))throw new Error(`doubleTapAtCoords failed at (${e}, ${o})`);await p(300)}async assertVisible(e){let o=typeof e=="string"?{text:e}:e;for(let r=0;r<15;r++){let n=await this.findElement(o);if(n&&n.absolutePosition.y+n.layout.height>0&&n.absolutePosition.y<L)return;await p(200)}throw new Error(`assertVisible: ${JSON.stringify(o)} not found or off-screen`)}async assertNotVisible(e){let o=typeof e=="string"?{text:e}:e,r=await this.findElement(o);if(r&&r.absolutePosition.y+r.layout.height>0&&r.absolutePosition.y<L)throw new Error(`assertNotVisible: ${JSON.stringify(o)} IS visible`)}async inputText(e){await this.bridge.send({type:"keyboard",browserId:this.opts.browserId,action:"type",text:e}),await p(200)}async pressKey(e){await this.bridge.send({type:"keyboard",browserId:this.opts.browserId,action:"press",text:e}),await p(120)}async dispatchKey(e){await this.bridge.send({type:"keyboard",browserId:this.opts.browserId,action:"dispatchKey",text:e}),await p(120)}async hideKeyboard(){try{await this.callTest("blurFocusedTextInput")}catch{}await this.bridge.send({type:"keyboard",browserId:this.opts.browserId,action:"dismiss"});let e=Date.now()+3e3;for(;Date.now()<e;){let o=await this.evaluate(`(() => {
|
|
92
|
+
const keyboard =
|
|
93
|
+
window.__sootsimKeyboard ??
|
|
94
|
+
window.SootSim?.bridges?.keyboard ??
|
|
95
|
+
null
|
|
96
|
+
const test = window.__sootsimTest
|
|
97
|
+
return {
|
|
98
|
+
visible: !!keyboard?.isVisible?.(),
|
|
99
|
+
focused: !!test?.isTextInputFocused?.(),
|
|
100
|
+
}
|
|
101
|
+
})()`);if(!o?.visible&&!o?.focused){await p(80);return}await p(80)}}async eraseText(e){for(let o=0;o<e;o++)await this.pressKey("Backspace");await p(100)}async waitFor(e){let o=Date.now()+(e.timeout||Z);for(;Date.now()<o;){if(await this.findElement(e))return;await p(200)}throw new Error(`waitFor: ${JSON.stringify(e)} not found after ${e.timeout||Z}ms`)}async takeScreenshot(e){await p(250);let o=Ut(e),r=Dt(this.opts.screenshotDir,o.path,{mode:this.opts.screenshotPathMode??"dir",flowDir:this.opts.flowDir});b.mkdirSync(g.dirname(r),{recursive:!0});let i=(await this.bridge.send({type:"screenshot",browserId:this.opts.browserId})).replace(/^data:image\/png;base64,/,""),s=Buffer.from(i,"base64");if(o.withFrame){let a=await this.readCurrentDeviceModel();if(!a)throw new Error("could not read current device model for framed screenshot");let l=await Oe(s,a);b.writeFileSync(r,l),console.log(`[flow] screenshot: ${r} (frame: ${a})`);return}b.writeFileSync(r,s),console.log(`[flow] screenshot: ${r}`)}async readCurrentDeviceModel(){let e=await this.bridge.send({type:"call",browserId:this.opts.browserId,path:"SootSim.bridges.settings.get",args:[]}),o=e&&typeof e.deviceModel=="string"?e.deviceModel:null;return!o||!(o in ve)?null:o}async captureFailureScreenshot(e){b.mkdirSync(g.dirname(e),{recursive:!0});let r=(await this.bridge.send({type:"screenshot",browserId:this.opts.browserId})).replace(/^data:image\/png;base64,/,"");b.writeFileSync(e,Buffer.from(r,"base64"))}async captureFailureBundle(e,o){b.mkdirSync(e,{recursive:!0});let r=(c,m)=>{try{b.writeFileSync(g.join(e,c),m)}catch{}},n=async c=>{try{return await this.bridge.send({type:"evaluate",browserId:this.opts.browserId,code:c})}catch{return null}};r("error.json",JSON.stringify({message:o.error.message,stack:o.error.stack,stepIndex:o.stepIndex,stepKind:o.stepKind,stepTarget:o.stepTarget,capturedAt:new Date().toISOString()},null,2));try{let m=(await this.bridge.send({type:"screenshot",browserId:this.opts.browserId})).replace(/^data:image\/png;base64,/,"");r("screenshot.png",Buffer.from(m,"base64"))}catch{}let i=await n(`(async () => {
|
|
102
|
+
const t = window.__sootsimTest
|
|
103
|
+
const mainShell = window.SootSim?.bridges?.mainShell
|
|
104
|
+
if (!t) return { error: 'no test bridge' }
|
|
105
|
+
let shell = null
|
|
106
|
+
try {
|
|
107
|
+
shell = typeof mainShell?.getState === 'function' ? await mainShell.getState() : null
|
|
108
|
+
} catch {}
|
|
109
|
+
const all = await t.queryAll({ pruneHidden: true })
|
|
110
|
+
return { shell, nodes: all, url: location.href, title: document.title }
|
|
111
|
+
})()`);i&&r("describe.json",JSON.stringify(i,null,2));let s=await n("(async () => await window.__sootsimTest?.dumpAccessibilityTree?.(20))()");typeof s=="string"&&r("a11y.txt",s);let a=await n("(async () => await window.__sootsimTest?.dumpTree?.(15))()");typeof a=="string"&&r("tree.txt",a);let l=await n(`(() => {
|
|
112
|
+
const c = window.__sootsimConsole
|
|
113
|
+
return {
|
|
114
|
+
errors: c?.getErrors?.() ?? [],
|
|
115
|
+
warnings: c?.getWarnings?.() ?? [],
|
|
116
|
+
requests: (window.__sootsimGetFailedRequests?.() ?? []),
|
|
117
|
+
}
|
|
118
|
+
})()`);return l&&r("console.json",JSON.stringify(l,null,2)),e}async swipe(e="UP",o=300){let r=ee/2,n=L/2,i=200,s=r,a=n,l=r,c=n;switch(e.toUpperCase()){case"UP":a+=i,c-=i;break;case"DOWN":a-=i,c+=i;break;case"LEFT":s+=i,l-=i;break;case"RIGHT":s-=i,l+=i;break}let m=Math.max(10,Math.round(o/16));await this.drag(s,a,l,c,m,16)}async drag(e,o,r,n,i=12,s=16){if(!(await this.evaluate(`(async () => {
|
|
119
|
+
const interact = window.__sootsimInteract
|
|
120
|
+
if (!interact?.drag) return { ok: false }
|
|
121
|
+
const value = await interact.drag(${e}, ${o}, ${r}, ${n}, ${Math.max(1,Math.round(i))}, ${Math.max(0,Math.round(s))})
|
|
122
|
+
return { ok: !!value, value }
|
|
123
|
+
})()`))?.ok)throw new Error("drag failed");await p(300)}async swipeCoords(e,o,r=300){let n=ue(e),i=ue(o),s=Math.max(10,Math.round(r/16));await this.drag(n.x,n.y,i.x,i.y,s,16)}async swipeFrom(e,o="UP",r=300){let n=await this.findElement(e);if(!n)throw new Error(`swipeFrom: element not found: ${JSON.stringify(e)}`);let i=n.absolutePosition.x+n.layout.width/2,s=n.absolutePosition.y+n.layout.height/2,a=180,l=i,c=s;switch(o.toUpperCase()){case"UP":c-=a;break;case"DOWN":c+=a;break;case"LEFT":l-=a;break;case"RIGHT":l+=a;break}let m=Math.max(10,Math.round(r/16));await this.drag(i,s,l,c,m,16)}async scrollTo(e,o,r){let n=await this.callTest("scrollTo",e,o,r,!1);if(!n?.ok)throw new Error(`scrollTo failed: ${n?.reason||"unknown error"}`);await p(250)}async pinch(e){let o=await this.evaluate(`(async () => {
|
|
124
|
+
const interact = window.__sootsimInteract
|
|
125
|
+
if (!interact?.pinch) return { ok: false, reason: 'no interact.pinch' }
|
|
126
|
+
const ok = await interact.pinch(
|
|
127
|
+
${e.from[0]}, ${e.from[1]}, ${e.from[2]}, ${e.from[3]},
|
|
128
|
+
${e.to[0]}, ${e.to[1]}, ${e.to[2]}, ${e.to[3]},
|
|
129
|
+
${e.steps||12}, ${e.stepMs||16}
|
|
130
|
+
)
|
|
131
|
+
return { ok: !!ok, reason: ok ? null : 'pinch returned false' }
|
|
132
|
+
})()`);if(!o?.ok)throw new Error(`pinch failed: ${o?.reason||"unknown error"}`);await p(250)}async dumpTree(e=6){let o=await this.bridge.send({type:"tree",browserId:this.opts.browserId,depth:e});return console.log("[flow] tree:"),console.log(typeof o=="string"?o:JSON.stringify(o,null,2)),typeof o=="string"?o:JSON.stringify(o)}async assertTreeContains(e){if(!(await this.dumpTree(8)).includes(e))throw new Error(`assertTreeContains: "${e}" not in tree`)}async waitForAnimationToEnd(e=2e3){await p(e)}async back(){try{await this.tapOn("\u2039")}catch{await this.tapOn("<")}}async scrollUntilVisible(e){let o=Date.now()+(e.timeout||15e3),r=e.direction?.toUpperCase()||"DOWN",n=r==="DOWN"?"UP":r==="UP"?"DOWN":r;for(;Date.now()<o;){let i=await this.findElement({text:e.element});if(i&&i.absolutePosition.y>=0&&i.absolutePosition.y+i.layout.height>0&&i.absolutePosition.y<L-50){if(e.centerElement){let s=L/2,a=i.absolutePosition.y-s;if(Math.abs(a)>100){let l=Math.min(150,Math.abs(a)*.5),c=a>0?s-l:s+l;await this.drag(ee/2,s,ee/2,c,10,16)}}return}await this.swipe(n,250),await p(500)}throw new Error(`scrollUntilVisible: "${e.element}" not found`)}async extendedWaitUntil(e){let o=Date.now()+(e.timeout||Z);for(;Date.now()<o;){let r=e.visible?!!await this.findElement(typeof e.visible=="string"?{text:e.visible}:e.visible):!0,n=e.notVisible?!await this.findElement(typeof e.notVisible=="string"?{text:e.notVisible}:e.notVisible):!0;if(r&&n)return;await p(200)}throw new Error("extendedWaitUntil timed out")}async launchApp(e){await this.refreshBrowserId();let o=!!(e&&typeof e=="object"&&e.clearState);if(o&&await this.evaluate(`(async () => {
|
|
133
|
+
await (${H})
|
|
134
|
+
try {
|
|
135
|
+
const regs = await navigator.serviceWorker?.getRegistrations?.()
|
|
136
|
+
await Promise.all((regs || []).map((reg) => reg.unregister()))
|
|
137
|
+
} catch {}
|
|
138
|
+
})()`),!this.firstLaunchDone&&!o)this.firstLaunchDone=!0,await this.waitForTree(3e4);else if(this.firstLaunchDone=!0,await this.evaluate("window.location.reload()").catch(()=>{}),await p(500),await this.refreshBrowserId(),await this.waitForTree(12e4),this.opts.onAfterLaunch)try{await this.opts.onAfterLaunch()}catch(r){console.warn(` warn: onAfterLaunch hook threw: ${r instanceof Error?r.message:r}`)}this.profilingEnabled&&await this.startProfile(),this.recordingEnabled&&(await this.waitForVisualSettle(),await this.ensureRecordingStarted())}async waitForVisualSettle(){try{await this.evaluate(`new Promise((resolve) => {
|
|
139
|
+
requestAnimationFrame(() => {
|
|
140
|
+
requestAnimationFrame(() => {
|
|
141
|
+
requestAnimationFrame(() => {
|
|
142
|
+
setTimeout(resolve, 180)
|
|
143
|
+
})
|
|
144
|
+
})
|
|
145
|
+
})
|
|
146
|
+
})`)}catch{await p(180)}}async startProfile(){await this.evaluate(`((sessionKey) => {
|
|
147
|
+
const host = window.__sootsimRenderHost
|
|
148
|
+
if (host?.startPerfSession) {
|
|
149
|
+
host.startPerfSession(sessionKey)
|
|
150
|
+
window[sessionKey] = {
|
|
151
|
+
active: true,
|
|
152
|
+
mode: 'render-worker',
|
|
153
|
+
startedAt: performance.now(),
|
|
154
|
+
}
|
|
155
|
+
return
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
const perf = window.__sootsimPerf
|
|
159
|
+
const a11y = window.__sootsimA11y
|
|
160
|
+
perf?.enableFrameStats?.()
|
|
161
|
+
perf?.resetFrameStats?.()
|
|
162
|
+
a11y?.resetProfile?.()
|
|
163
|
+
window[sessionKey] = {
|
|
164
|
+
active: true,
|
|
165
|
+
mode: 'main-thread',
|
|
166
|
+
startedAt: performance.now(),
|
|
167
|
+
}
|
|
168
|
+
})(${JSON.stringify(Ge)})`),this.profilingEnabled=!0}async stopProfile(){let e=await this.evaluate(`(async (sessionKey) => {
|
|
169
|
+
const host = window.__sootsimRenderHost
|
|
170
|
+
if (host?.stopPerfSession) {
|
|
171
|
+
const stopped = await host.stopPerfSession(sessionKey)
|
|
172
|
+
if (!stopped || !Array.isArray(stopped.samples)) {
|
|
173
|
+
return { error: 'no render-worker perf samples available' }
|
|
174
|
+
}
|
|
175
|
+
const samples = stopped.samples
|
|
176
|
+
const frameTimes = samples.map((sample) => Number(sample?.[1]) || 0).filter((value) => value > 0)
|
|
177
|
+
const sorted = [...frameTimes].sort((a, b) => a - b)
|
|
178
|
+
const worstFrames = samples
|
|
179
|
+
.slice()
|
|
180
|
+
.sort((a, b) => (Number(b?.[1]) || 0) - (Number(a?.[1]) || 0))
|
|
181
|
+
.slice(0, 10)
|
|
182
|
+
.map((sample) => [
|
|
183
|
+
Number(sample?.[0]) || 0,
|
|
184
|
+
Number(sample?.[1]) || 0,
|
|
185
|
+
Number(sample?.[2]) || 0,
|
|
186
|
+
Number(sample?.[3]) || 0,
|
|
187
|
+
Number(sample?.[4]) || 0,
|
|
188
|
+
])
|
|
189
|
+
|
|
190
|
+
return {
|
|
191
|
+
mode: 'render-worker',
|
|
192
|
+
frames: Number(stopped.frameCount) || frameTimes.length,
|
|
193
|
+
totalMs: Number(stopped.totalMs) || frameTimes.reduce((sum, value) => sum + value, 0),
|
|
194
|
+
avgMs: Number(stopped.avgMs) || (frameTimes.length ? frameTimes.reduce((sum, value) => sum + value, 0) / frameTimes.length : 0),
|
|
195
|
+
maxMs: Number(stopped.maxMs) || (sorted[sorted.length - 1] || 0),
|
|
196
|
+
layoutTotalMs: Number(stopped.layoutTotalMs) || samples.reduce((sum, sample) => sum + (Number(sample?.[2]) || 0), 0),
|
|
197
|
+
renderTotalMs: Number(stopped.renderTotalMs) || samples.reduce((sum, sample) => sum + (Number(sample?.[3]) || 0), 0),
|
|
198
|
+
copyTotalMs: Number(stopped.copyTotalMs) || samples.reduce((sum, sample) => sum + (Number(sample?.[4]) || 0), 0),
|
|
199
|
+
layoutAvgMs: Number(stopped.layoutAvgMs) || 0,
|
|
200
|
+
renderAvgMs: Number(stopped.renderAvgMs) || 0,
|
|
201
|
+
copyAvgMs: Number(stopped.copyAvgMs) || 0,
|
|
202
|
+
p50: sorted[Math.floor(sorted.length * 0.5)] || 0,
|
|
203
|
+
p95: sorted[Math.floor(sorted.length * 0.95)] || 0,
|
|
204
|
+
p99: sorted[Math.floor(sorted.length * 0.99)] || 0,
|
|
205
|
+
jankFrames: frameTimes.filter((value) => value > 16.67).length,
|
|
206
|
+
sampleCount: frameTimes.length,
|
|
207
|
+
worstFrames,
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
const perf = window.__sootsimPerf
|
|
212
|
+
const a11y = window.__sootsimA11y
|
|
213
|
+
if (!perf && !a11y) return { error: 'no perf globals available' }
|
|
214
|
+
|
|
215
|
+
const frameStats = perf?.getFrameStats?.() || {}
|
|
216
|
+
const profile = a11y?.profile?.() || {}
|
|
217
|
+
const recent = Array.isArray(frameStats.recentFrames) ? frameStats.recentFrames : []
|
|
218
|
+
const sorted = [...recent].sort((a, b) => a - b)
|
|
219
|
+
perf?.disableFrameStats?.()
|
|
220
|
+
|
|
221
|
+
return {
|
|
222
|
+
mode: 'main-thread',
|
|
223
|
+
frames: frameStats.frames || profile.syncCount || 0,
|
|
224
|
+
totalMs: frameStats.totalMs || 0,
|
|
225
|
+
avgMs: frameStats.totalMs && frameStats.frames ? frameStats.totalMs / frameStats.frames : profile.avgSyncMs || 0,
|
|
226
|
+
maxMs: frameStats.maxMs || profile.maxSyncMs || 0,
|
|
227
|
+
layoutTotalMs: frameStats.layoutTotalMs || 0,
|
|
228
|
+
p50: sorted[Math.floor(sorted.length * 0.5)] || 0,
|
|
229
|
+
p95: sorted[Math.floor(sorted.length * 0.95)] || 0,
|
|
230
|
+
p99: sorted[Math.floor(sorted.length * 0.99)] || 0,
|
|
231
|
+
jankFrames: recent.filter((value) => value > 16.67).length,
|
|
232
|
+
sampleCount: recent.length,
|
|
233
|
+
worstFrames: recent.slice().sort((a, b) => b - a).slice(0, 10),
|
|
234
|
+
}
|
|
235
|
+
})(${JSON.stringify(Ge)})`);if(this.profilingEnabled=!1,e?.error)throw new Error(e.error);return e}async stopApp(){await this.evaluate(`(async () => {
|
|
236
|
+
try { await (${H}) } catch {}
|
|
237
|
+
try {
|
|
238
|
+
const regs = await navigator.serviceWorker?.getRegistrations?.()
|
|
239
|
+
await Promise.all((regs || []).map((reg) => reg.unregister()))
|
|
240
|
+
} catch {}
|
|
241
|
+
})()`)}async clearState(){await this.evaluate(`(async () => {
|
|
242
|
+
await (${H})
|
|
243
|
+
})()`)}clearKeychain(){console.warn("[flow] clearKeychain: sootsim has no keychain surface \u2014 no-op (warning)")}async copyTextFrom(e){let o=typeof e=="string"?{id:e}:e,r=await this.findElement(o);if(!r)throw new Error(`copyTextFrom: element not found: ${JSON.stringify(o)}`);let n=r.text??r.testID??"";fe.set(Nt,n),console.log(`[flow] copied text: ${JSON.stringify(n)}`)}async evalScript(e){let r=await this.evaluate(`(async () => {
|
|
244
|
+
try {
|
|
245
|
+
return { ok: true, value: await (async () => { ${e} })() }
|
|
246
|
+
} catch (err) {
|
|
247
|
+
return { ok: false, error: err && err.message ? err.message : String(err) }
|
|
248
|
+
}
|
|
249
|
+
})()`);if(!r.ok)throw new Error(`evalScript failed: ${r.error}`);r.value!==void 0&&console.log("[flow] evalScript ->",r.value)}async openLink(e){let o=typeof e=="string"?e:e.link;if(!o)throw new Error("openLink: missing link");await this.evaluate(`window.location.href = ${JSON.stringify(o)}`),await p(300),await this.refreshBrowserId(),await this.waitForTree(3e4)}async evaluateWhen(e){if(e.visible!==void 0){let o=typeof e.visible=="string"?{text:e.visible}:e.visible;return!!await this.findElement(o)}if(e.notVisible!==void 0){let o=typeof e.notVisible=="string"?{text:e.notVisible}:e.notVisible;return!await this.findElement(o)}return e.platform!==void 0?e.platform.toLowerCase()==="ios":e.true!==void 0?e.true.toLowerCase()!=="false":!0}isOptional(e){if(e.optional===!0)return!0;let r=Object.entries(e).find(([i])=>i!=="when"&&i!=="optional"),n=r?r[1]:void 0;return!!(n&&typeof n=="object"&&"optional"in n&&n.optional)}async runStep(e,o){let r=Object.keys(e).find(n=>n!=="when")||Object.keys(e)[0];if(console.log(`[flow] step ${o+1}: ${r}`),e.when&&!await this.evaluateWhen(e.when)){console.log("[flow] (when: predicate false, skipped)");return}try{let n=!!(e.extendedWaitUntil||e.waitFor||e.launchApp||e.runFlow),i=1e4,s=this.runStepInner(e);if(n)await s;else{let l=null,c=new Promise((m,h)=>{l=setTimeout(()=>{h(new Error(`step watchdog: ${r} made no progress in ${i}ms \u2014 bridge or bundle probably hung`))},i)});try{await Promise.race([s,c])}finally{l&&clearTimeout(l)}}let a=!!(e.assertVisible||e.assertNotVisible||e.extendedWaitUntil||e.waitFor);this.stepDelay>0&&!a&&await p(this.stepDelay)}catch(n){if(this.isOptional(e)){console.log(`[flow] (optional, skipped: ${n.message.slice(0,80)})`);return}throw this.lastFailedStep={index:o,kind:r,target:e[r]},n}}async runStepInner(e){if(e.tapOn)await this.tapOn(e.tapOn);else if(e.scrollUntilVisible)await this.scrollUntilVisible(e.scrollUntilVisible);else if(e.extendedWaitUntil)await this.extendedWaitUntil(e.extendedWaitUntil);else if(e.assertVisible)await this.assertVisible(e.assertVisible);else if(e.assertNotVisible)await this.assertNotVisible(e.assertNotVisible);else if(e.inputText)await this.inputText(e.inputText);else if(e.pressKey)await this.pressKey(e.pressKey);else if(e.dispatchKey)await this.dispatchKey(e.dispatchKey);else if(e.waitFor)await this.waitFor(e.waitFor);else if(e.takeScreenshot)await this.takeScreenshot(e.takeScreenshot);else if(e.swipe)e.swipe.start&&e.swipe.end?await this.swipeCoords(e.swipe.start,e.swipe.end,e.swipe.duration):e.swipe.from?await this.swipeFrom(e.swipe.from,e.swipe.direction,e.swipe.duration):await this.swipe(e.swipe.direction,e.swipe.duration);else if(e.scroll)await this.swipe(e.scroll.direction==="DOWN"?"UP":"DOWN");else if(e.scrollTo)await this.scrollTo(e.scrollTo.id,e.scrollTo.x,e.scrollTo.y);else if(e.pinch)await this.pinch(e.pinch);else if(e.waitForAnimationToEnd)await this.waitForAnimationToEnd(typeof e.waitForAnimationToEnd=="number"?e.waitForAnimationToEnd:2e3);else if(e.back)await this.back();else if(e.hideKeyboard)await this.hideKeyboard();else if(e.launchApp)await this.launchApp(e.launchApp);else if(typeof e.wait=="number")await p(e.wait);else if(e.dumpTree)await this.dumpTree(e.dumpTree);else if(e.tapAtCoords)await this.tapAtCoords(e.tapAtCoords.x,e.tapAtCoords.y);else if(e.doubleTapAtCoords)await this.doubleTapAtCoords(e.doubleTapAtCoords.x,e.doubleTapAtCoords.y,e.doubleTapAtCoords.gapMs);else if(e.assertTreeContains)await this.assertTreeContains(e.assertTreeContains);else if(typeof e.eraseText=="number")await this.eraseText(e.eraseText);else if(e.repeat)for(let o=0;o<e.repeat.times;o++)for(let r=0;r<e.repeat.commands.length;r++)await this.runStep(e.repeat.commands[r],r);else if(e.stopApp!==void 0)await this.stopApp();else if(e.clearState!==void 0)await this.clearState();else if(e.clearKeychain!==void 0)this.clearKeychain();else if(e.copyTextFrom!==void 0)await this.copyTextFrom(e.copyTextFrom);else if(typeof e.evalScript=="string")await this.evalScript(e.evalScript);else if(e.openLink!==void 0)await this.openLink(e.openLink);else if(e.runFlow){let o=e.runFlow,r=typeof o=="string"?o:o.file,n=typeof o=="string"?void 0:o.when;if(n&&!await this.evaluateWhen(n)){console.log(`[flow] runFlow skipped (when predicate false): ${r}`);return}let i=g.resolve(this.opts.flowDir,r),s=b.readFileSync(i,"utf8"),a=this.opts.flowDir;this.opts.flowDir=g.dirname(i),await this.runFlow(Lt(s)),this.opts.flowDir=a}else throw new Error(`unsupported flow step: ${JSON.stringify(e)}`)}async runFlow(e){let o=[],r=[],n=[];for(let s of e){let a=Object.keys(s);if(a.length===1&&a[0]==="onFlowStart"&&Array.isArray(s.onFlowStart)){o.push(...s.onFlowStart);continue}if(a.length===1&&a[0]==="onFlowComplete"&&Array.isArray(s.onFlowComplete)){r.push(...s.onFlowComplete);continue}n.push(s)}if(o.length>0){console.log(`[flow] onFlowStart (${o.length} steps)`);for(let s=0;s<o.length;s++)await this.runStep(o[s],s)}let i=null;try{await this.runFlowBody(n)}catch(s){i=s instanceof Error?s:new Error(String(s))}if(r.length>0){console.log(`[flow] onFlowComplete (${r.length} steps)`);for(let s=0;s<r.length;s++)try{await this.runStep(r[s],s)}catch(a){console.warn(`[flow] onFlowComplete step ${s+1} failed: ${a instanceof Error?a.message:a}`)}}if(i)throw i}async runFlowBody(e){for(let o=0;o<e.length;o++){let r=e[o],n=typeof r.wait=="number"?r.wait:0,i=typeof r.waitFor?.timeout=="number"?r.waitFor.timeout:0,s=Math.max(6e4,n+15e3,i+15e3);if(r.runFlow){await this.runStep(r,o);continue}await Promise.race([this.runStep(r,o),new Promise((a,l)=>setTimeout(()=>l(new Error(`step ${o+1} (${Object.keys(r)[0]}) exceeded ${s}ms deadline`)),s))])}}};function Xe(t){let e={},o=t,r=t.match(/^---\n([\s\S]*?)\n---\n?/);if(r){try{e=R.parse(r[1])??{}}catch(s){console.warn(` warn: could not parse frontmatter: ${s.message}`)}o=t.slice(r[0].length);let i=R.parse(o);return{frontmatter:e,steps:Array.isArray(i)?i:[]}}if(/\n---\s*\n/.test(t))try{let i=R.parseAllDocuments(t);if(i.length>=2){let s=i[0].toJS(),a=i[i.length-1].toJS();return{frontmatter:s&&typeof s=="object"?s:{},steps:Array.isArray(a)?a:[]}}}catch(i){console.warn(` warn: could not parse multi-doc flow: ${i.message}`)}let n=R.parse(o);return{frontmatter:e,steps:Array.isArray(n)?n:[]}}async function Wt(){let t=await Ye(),e=t.find(r=>r.patched);if(e)return`http://localhost:${e.port}/__soot/`;let o=t[0];return o?`http://localhost:${o.port}/__soot/`:null}async function Qe(t){(t.length===0||t.includes("--help")||t.includes("-h"))&&(console.log(`
|
|
250
|
+
sootsim flow \u2014 run flows or manage a draft session
|
|
251
|
+
|
|
252
|
+
usage:
|
|
253
|
+
sootsim flow <flow.yaml> [options]
|
|
254
|
+
sootsim flow start
|
|
255
|
+
sootsim flow keep
|
|
256
|
+
sootsim flow end [--output <path>] [--validate] [--video]
|
|
257
|
+
sootsim flow validate <path>
|
|
258
|
+
|
|
259
|
+
options:
|
|
260
|
+
--record record a webm artifact while the flow runs
|
|
261
|
+
--profile capture perf stats while the flow runs
|
|
262
|
+
--out <dir> output directory (default: /tmp/sootsim-recordings)
|
|
263
|
+
--device <model> override the flow frontmatter device for this run
|
|
264
|
+
--slow <ms> delay between steps for natural pacing
|
|
265
|
+
--url <url> load this target before running the flow
|
|
266
|
+
--screenshot-paths <mode>
|
|
267
|
+
screenshot path mode: dir (default) or flow
|
|
268
|
+
--replace <m>=<f> replace a Metro module with a local file for this run
|
|
269
|
+
--new open a fresh session before running the flow
|
|
270
|
+
--electron prefer opening the target in the desktop companion
|
|
271
|
+
--session <id> target a specific current session
|
|
272
|
+
--validate replay the drafted flow before clearing it
|
|
273
|
+
--video replay and record the drafted flow before clearing it
|
|
274
|
+
|
|
275
|
+
frontmatter (top of flow.yaml between --- markers):
|
|
276
|
+
app: 8081 load this target before the flow starts
|
|
277
|
+
device: iphone-14 set the live device model for this flow run
|
|
278
|
+
electron: true prefer the desktop companion session for this flow
|
|
279
|
+
|
|
280
|
+
default runtime:
|
|
281
|
+
bridge-backed flow playback against the current sootsim session
|
|
282
|
+
if no current session exists, flow opens the discovered target first
|
|
283
|
+
recording and profiling both run on the same bridge-backed path
|
|
284
|
+
|
|
285
|
+
examples:
|
|
286
|
+
sootsim flow login.yaml
|
|
287
|
+
sootsim flow demo.yaml --url 8081 --record --slow 500 --out ./recordings
|
|
288
|
+
sootsim flow demo.yaml --session tab-2
|
|
289
|
+
sootsim flow start
|
|
290
|
+
sootsim flow keep
|
|
291
|
+
sootsim flow end --output ./flows/draft.yaml
|
|
292
|
+
sootsim flow end --output ./flows/draft.yaml --validate
|
|
293
|
+
sootsim flow end --output ./flows/draft.yaml --video
|
|
294
|
+
sootsim flow validate ./flows/draft.yaml
|
|
295
|
+
|
|
296
|
+
flow extension:
|
|
297
|
+
takeScreenshot: hero
|
|
298
|
+
takeScreenshot:
|
|
299
|
+
path: marketing/hero
|
|
300
|
+
withFrame: true
|
|
301
|
+
`),process.exit(0));let e=t[0];I.existsSync(e)||(console.error(` error: ${e} not found`),process.exit(1));let o=d=>t.find((f,_)=>t[_-1]===d),r=t.includes("--profile"),n=t.includes("--new"),i=o("--out")||"/tmp/sootsim-recordings",s=o("--screenshots")||"/tmp/sootsim-flow",a=o("--screenshot-paths")==="flow"?"flow":"dir",l=o("--device")?.trim()||"",c=t.includes("--slow")?+(o("--slow")||"500"):0,m=t.includes("--electron"),h=t.includes("--preview"),me=await Ne(o("--preview-origin")),Ze=t.includes("--preview-open"),et=t.flatMap((d,f)=>t[f-1]==="--replace"?["--replace",d]:[]),O=t.includes("--record")||h,tt=I.readFileSync(e,"utf8"),{frontmatter:F,steps:C}=Xe(tt);C.length===0&&(console.error(" error: flow file must contain a YAML array of steps"),process.exit(1));let W=l||F.device||"",j=m||F.electron===!0,re=F.app===void 0||F.app===null?"":typeof F.app=="number"?String(F.app):F.app,we={stripBooleanFlags:["--record","--profile","--electron","--new","--preview","--preview-open"],stripValueFlags:["--out","--device","--slow","--url","--replace","--headless","--screenshots","--screenshot-paths","--preview-origin"]},T=ie(t,we),rt=o("--url")||"";j&&!_e()&&(console.error(" error: desktop companion not found. install or build it first with `bun run build:electron`"),process.exit(1));let ge=j?"desktop companion":"bridge",ot=re?` | target: ${re}`:"";console.log(`
|
|
302
|
+
sootsim flow \u2014 ${S.basename(e)}
|
|
303
|
+
${C.length} steps | ${ge}${ot}${O?" | recording":""}${r?" | profiling":""}${c?` | ${c}ms delay`:""}
|
|
304
|
+
`),h&&Ce({event:"preview_flow_started",properties:{flowName:S.basename(e),stepCount:C.length,mode:ge,electron:j,record:O,profile:r,previewOrigin:me}});let P=rt||re||"",oe=n||j&&T.browserIdSource!=="flag",he=!1;if(!P&&!oe&&T.browserIdSource==="none"){let d=Fe(T);try{let f=await d.listBrowsers(),_=f.find(G=>G.isPrimary&&G.readyState==="open"),Y=f.find(G=>G.readyState==="open"),Se=_??Y;Se&&(he=!0,console.log(` reusing active session: ${Se.id}`))}catch{}finally{d.close()}}if(!P&&!he&&(oe||T.browserIdSource==="none")){let d=await Wt();d||(console.error(" error: no current session and no sootsim target found"),await ae(),process.exit(1)),P=d}if(P&&W){let d=new URL(await Re(P));d.searchParams.set("device",W),P=d.toString()}if(P){let d=[P];d.push(...et),oe&&d.push("--new"),T.browserIdSource==="flag"&&T.browserId&&d.push("--session",T.browserId),await $e(d,{port:T.wsPort,timeoutMs:T.commandTimeoutMs})}let K=ie(t,we),be=K.browserIdSource==="flag"?K.browserId:xe()||K.browserId,x=Ie(K.wsPort,{commandTimeoutMs:K.commandTimeoutMs,browserId:be,fallbackOnMissingBrowserId:!1}),u,ye=async()=>{if(!W)return!1;let d=await x.send({type:"evaluate",browserId:u.browserId,code:"window.location.href"});if(typeof d=="string"&&d.length>0){let f=new URL(d);f.searchParams.set("device",W),u.setBrowserRouteHint(f.toString())}return!!await x.send({type:"call",browserId:u.browserId,path:"SootSim.bridges.settings.set",args:["deviceModel",W]})};u=new te(x,{screenshotDir:s,flowDir:S.dirname(S.resolve(e)),screenshotPathMode:a,browserId:be,recordingOutputDir:O?i:void 0,onAfterLaunch:async()=>{await ye()&&await u.waitForTree(12e4),h&&await x.send({type:"evaluate",browserId:u.browserId,code:`(() => {
|
|
305
|
+
const r = window.SootSim?.bridges?.eventRecorder ?? window.__sootsimEventRecorder
|
|
306
|
+
return r?.start?.() ?? false
|
|
307
|
+
})()`})}}),c&&(u.stepDelay=c);let k=null,E=null,ne=null,J=0,nt=!!C[0]?.launchApp;try{await u.waitForTree(12e4),await ye()&&await u.waitForTree(12e4),O&&(nt?u.prepareRecording():await u.startRecording()),r&&await u.startProfile(),h&&(await x.send({type:"evaluate",browserId:u.browserId,code:`(() => {
|
|
308
|
+
const r = window.SootSim?.bridges?.eventRecorder ?? window.__sootsimEventRecorder
|
|
309
|
+
return r?.start?.() ?? false
|
|
310
|
+
})()`})||console.warn(" warn: eventRecorder.start() returned false \u2014 preview will upload bundle without replay events")),await u.runFlow(C),r&&(k=await u.stopProfile()),O&&(E=await u.stopRecording()),h&&(ne=await x.send({type:"evaluate",browserId:u.browserId,code:`(() => {
|
|
311
|
+
const r = window.SootSim?.bridges?.eventRecorder ?? window.__sootsimEventRecorder
|
|
312
|
+
return r?.stop?.() ?? []
|
|
313
|
+
})()`}),console.log(` captured ${ne.length} replay events`)),console.log(`
|
|
314
|
+
+ completed (${C.length} steps)`),k&&qe(k),E&&console.log(` video: ${E}`),console.log()}catch(d){if(r&&!k)try{k=await u.stopProfile()}catch{}if(O&&!E)try{E=await u.stopRecording()}catch(f){console.warn(` recording stop failed: ${f?.message||String(f)}`)}console.error(`
|
|
315
|
+
x failed: ${d.message}
|
|
316
|
+
`),k&&(console.log(" partial profile:"),qe(k)),E&&console.log(` partial video: ${E}`);try{let f=u.lastFailedStep,_=f?`step-${String(f.index+1).padStart(2,"0")}-${f.kind}`:"unstaged",Y=S.join(s,_);await u.captureFailureBundle(Y,{error:d,stepIndex:f?.index,stepKind:f?.kind,stepTarget:f?.target}),console.log(` failure bundle: ${Y}`),console.log(" (contents: screenshot.png, describe.json, a11y.txt, tree.txt, console.json, error.json)")}catch(f){try{let _=S.join(s,"error.png");await u.captureFailureScreenshot(_),console.log(` error screenshot: ${_}`)}catch{}console.log(` (failure bundle capture failed: ${f instanceof Error?f.message:String(f)})`)}await Te(x,{errorsCommand:`sootsim get errors 5${u.browserId?` --session ${u.browserId}`:""}`,warningsCommand:`sootsim get warnings 5${u.browserId?` --session ${u.browserId}`:""}`,requestsCommand:`sootsim get requests 5${u.browserId?` --session ${u.browserId}`:""}`}),J=1}finally{x.close()}if(J===0&&h)try{let d=await Kt(ne??[]),f=["--origin",me,"--events",d];E&&f.push("--video",E),u.browserId&&f.push("--session",u.browserId),Ze&&f.push("--open"),console.log(`
|
|
317
|
+
preparing preview upload\u2026`);let{runUpload:_}=await import("./upload-BYNPC54C.js");await _(f,{})}catch(d){console.error(` preview upload failed: ${d?.message||d}`),J=1}return await ae(),J}async function Kt(t){let{gzipSync:e}=await import("zlib"),o=t.map(i=>JSON.stringify(i)).join(`
|
|
318
|
+
`)+(t.length?`
|
|
319
|
+
`:""),r=e(Buffer.from(o,"utf8")),n=S.join(ze(),`sootsim-events-${Date.now()}.jsonl.gz`);return I.writeFileSync(n,r),console.log(` events: ${t.length} written to ${n} (${r.length} bytes gz)`),n}async function Vt(t){let e=t[0],o=r=>t.find((n,i)=>t[i-1]===r);switch(e){case"start":{let{path:r,state:n}=Ee();console.log(" flow draft started"),console.log(` session: ${r}`),console.log(` steps: ${n.steps.length}`);return}case"keep":case"good":{let r=Ae();if(r.active||(console.error(" no active flow draft \u2014 run `sootsim flow start` first"),process.exit(1)),!r.kept){console.log(" no pending action to keep");return}console.log(` kept: ${r.candidate.summary}`),console.log(` steps: ${r.stepCount}`);return}case"end":{let r=o("--output")||(t[1]&&!t[1].startsWith("-")?t[1]:void 0),n=t.includes("--validate")||t.includes("--video"),i=t.includes("--video"),s=Pe(r||(n?jt():void 0));if(s.active||(console.error(" no active flow draft \u2014 run `sootsim flow start` first"),process.exit(1)),n){let a=Jt(t,s.outputPath),l=await Qe(a);if(l!==0){console.error(`
|
|
320
|
+
validation failed \u2014 draft preserved so you can keep iterating`),process.exitCode=l;return}se(),console.log(` flow draft validated (${s.stepCount} step${s.stepCount===1?"":"s"})`),s.outputPath&&console.log(` saved: ${s.outputPath}`),i&&console.log(" video: recorded during validation run");return}if(se(),console.log(` flow draft ended (${s.stepCount} step${s.stepCount===1?"":"s"})`),s.outputPath){console.log(` saved: ${s.outputPath}`),console.log(` next: sootsim flow ${s.outputPath} --record`);return}console.log(""),process.stdout.write(s.yaml);return}case"validate":{let r=t[1];(!r||r.startsWith("-"))&&(console.error(" usage: sootsim flow validate <path>"),process.exit(1));let n=Bt(r);if(n.length>0){console.error(` x ${r} failed validation:`);for(let i of n)console.error(` - ${i}`);process.exit(1)}console.log(` + ${r} looks valid`);return}}}var He=new Set(["tapOn","inputText","pressKey","dispatchKey","hideKeyboard","swipe","pinch","scroll","scrollUntilVisible"]);function Bt(t){let e=[];if(!I.existsSync(t))return[`file not found: ${t}`];let o;try{o=I.readFileSync(t,"utf8")}catch(i){return[`cannot read file: ${i.message}`]}if(o.trim().length===0)return["file is empty"];let r;try{r=Xe(o)}catch(i){return[`yaml parse error: ${i.message}`]}if(!Array.isArray(r.steps)||r.steps.length===0)return e.push("flow body must be a non-empty YAML array of steps"),e;let n=0;for(let i=0;i<r.steps.length;i++){let s=r.steps[i];s&&typeof s=="object"?Object.keys(s).some(l=>He.has(l))&&(n+=1):typeof s=="string"&&He.has(s)&&(n+=1)}return n===0&&e.push("no interaction steps found (expected at least one tapOn / inputText / pressKey / swipe / scroll)"),e}async function Sr(t){let e=t[0];if(e==="start"||e==="keep"||e==="good"||e==="end"||e==="validate")return await Vt(t),0;let o=await Qe(t);return o!==0&&(process.exitCode=o),o}function qe(t){let e=t.avgMs>0?(1e3/t.avgMs).toFixed(1):"?",o=t.sampleCount>0?(t.jankFrames/t.sampleCount*100).toFixed(1):"0";console.log(`
|
|
321
|
+
profile:`),console.log(` frames: ${t.frames}`),console.log(` total: ${t.totalMs.toFixed(1)}ms`),console.log(` avg: ${t.avgMs.toFixed(2)}ms (${e} fps)`),console.log(` max: ${t.maxMs.toFixed(2)}ms`),t.layoutAvgMs!==void 0&&console.log(` breakdown: layout ${t.layoutAvgMs.toFixed(2)}ms | render ${t.renderAvgMs?.toFixed(2)||"0.00"}ms | copy ${t.copyAvgMs?.toFixed(2)||"0.00"}ms`),console.log(` p95: ${t.p95.toFixed(2)}ms`),console.log(` p99: ${t.p99.toFixed(2)}ms`),console.log(` jank: ${t.jankFrames}/${t.sampleCount} (${o}%) >16.67ms`);let r=Array.isArray(t.worstFrames)?t.worstFrames:[];if(r.length!==0){if(console.log(`
|
|
322
|
+
worst frames:`),t.mode==="render-worker"){console.log(" total layout render copy t+");for(let n of r){let[i,s,a,l,c]=n;console.log(` ${s.toFixed(2).padStart(7)} ${a.toFixed(2).padStart(7)} ${l.toFixed(2).padStart(7)} ${c.toFixed(2).padStart(7)} ${String(i).padStart(5)}`)}return}console.log(` ${r.map(n=>n.toFixed(2)).join(", ")}`)}}function jt(){return S.join(ze(),`sootsim-flow-draft-${Date.now()}.yaml`)}function Jt(t,e){if(!e)throw new Error("validated flow draft requires an output path");let o=[e];for(let r=1;r<t.length;r++){let n=t[r];if(!(n==="--validate"||n==="--video")){if(n==="--output"){r+=1;continue}r===1&&!n.startsWith("-")||o.push(n)}}return!o.includes("--record")&&t.includes("--video")&&o.push("--record"),o}export{Xe as a,Wt as b,Qe as c,Sr as d};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
/*! sootsim v0.0.1 | (c) 2026 Tamagui LLC | Proprietary — see LICENSE */
|
|
2
|
+
var d=Object.defineProperty;var e=(a=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(a,{get:(b,c)=>(typeof require<"u"?require:b)[c]}):a)(function(a){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+a+'" is not supported')});var f=(a,b)=>{for(var c in b)d(a,c,{get:b[c],enumerable:!0})};export{e as a,f as b};
|