prompttest 1.3.2 → 1.3.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,62 +1,62 @@
1
- import Ce from"fs";import me from"path";import R from"chalk";import{spawn as et}from"child_process";import Bt from"readline";var ae={DEVICES:["devices","-l"],SCREENCAP:["exec-out","screencap","-p"],FOREGROUND_APP:["shell","dumpsys","window"],CURRENT_FOCUS:["shell","dumpsys","activity","activities"],FORCE_STOP:u=>["shell","am","force-stop",u],CLEAR_APP:u=>["shell","pm","clear",u],LAUNCH_APP:u=>["shell","am","start","-a","android.intent.action.MAIN","-c","android.intent.category.LAUNCHER",u],UIAUTOMATOR_DUMP:["exec-out","uiautomator","dump","--compressed","/dev/tty"],INPUT_TAP:(u,e)=>["shell","input","tap",u.toString(),e.toString()],INPUT_TEXT:u=>["shell","input","text",u],INPUT_KEY:u=>["shell","input","keyevent",u.toString()],INPUT_SWIPE:(u,e,t,s,i=300)=>["shell","input","swipe",u.toString(),e.toString(),t.toString(),s.toString(),i.toString()],LOGCAT_CRASH:u=>["shell","logcat","-d","-b","crash","-s","AndroidRuntime:E"],CLEAR_CRASH_LOGS:()=>["shell","logcat","-b","crash","-c"],GRANT_PERMISSION:(u,e)=>["shell","pm","grant",u,e.startsWith("android.permission.")?e:`android.permission.${e}`],INSTALL_APK:u=>["install","-r",u],UNINSTALL_APP:u=>["uninstall",u],DEEP_LINK:u=>["shell","am","start","-a","android.intent.action.VIEW","-d",u],TCPIP:(u=5555)=>["tcpip",u.toString()],CONNECT:u=>["connect",u],DISCONNECT:u=>u?["disconnect",u]:["disconnect"],GET_WLAN_IP:["shell","ip","-f","inet","addr","show","wlan0"]};function fi(){let u=process.env.PROMPTTEST_SETTLE_FACTOR;if(!u)return 1;let e=parseFloat(u);return isNaN(e)||e<=0?1:e}function ye(u,e=50){return Math.max(e,Math.round(u*fi()))}var T={adb:{commandTimeoutMs:2e4,binaryTimeoutMs:45e3,retryCount:2,retryBaseDelayMs:200},polling:{intervalMs:200,jitterMs:80,defaultTimeoutMs:3e3,extendedTimeoutMs:3500,hierarchyCacheTtlMs:3500,verifyCacheTtlMs:2e3},settle:{get tapMs(){return ye(500)},get backMs(){return ye(700)},get launchMs(){return ye(2500)},get stopMs(){return ye(600)},get keyboardDismissMs(){return ye(500)},get scrollMs(){return ye(350)},get toggleMs(){return ye(350)},get selectMs(){return ye(600)},get inputFocusMs(){return ye(250)},get inputClearMs(){return ye(150)},get inputDoneMs(){return ye(350)},get submitWaitMs(){return ye(1800)}},gestures:{swipeDurationMs:300,longPressDurationMs:1e3,bottomNavThresholdRatio:.88,tapTargetYRatio:.96},recorder:{staleTapTimeoutMs:3e3,asyncRefreshDelayMs:80,heartbeatIntervalMs:1500},screen:{fallbackWidth:1080,fallbackHeight:2400},visual:{overlapRatio:.2},device:{maxDeviceRetries:2,autoReconnect:!0},flow:{maxLoopIterations:50,waitUntilTimeoutMs:1e4,defaultRetryCount:3},ai:{provider:"heuristic",model:"gpt-4o-mini",selfHealing:!0,confidenceThreshold:.75,maxHealingAttempts:2,endpoint:""},memory:{staleThresholdDays:parseInt(process.env.PROMPTTEST_STALE_DAYS||"14",10),staleDecayAmount:.2,minConfidenceFloor:.2,maxHealedConfidence:.65},parser:{mode:process.env.PROMPTTEST_XML_PARSER||"regex"},safety:{mode:process.env.PROMPTTEST_SAFETY_MODE||"strict",customBlacklist:process.env.PROMPTTEST_SAFETY_BLACKLIST?process.env.PROMPTTEST_SAFETY_BLACKLIST.split(",").map(u=>u.trim()).filter(Boolean):[]},explorer:{strategy:process.env.PROMPTTEST_STRATEGY||"heuristic",maxTabs:parseInt(process.env.PROMPTTEST_MAX_TABS||"15",10),maxScreens:parseInt(process.env.PROMPTTEST_MAX_SCREENS||"30",10),maxDepth:parseInt(process.env.PROMPTTEST_MAX_DEPTH||"5",10),stepBudget:parseInt(process.env.PROMPTTEST_STEP_BUDGET||"100",10),screenshots:process.env.PROMPTTEST_SCREENSHOTS||"state-change"},locale:"en"};function ks(u=T.polling.intervalMs,e=T.polling.jitterMs){return Math.round(u+(Math.random()*2-1)*(e/2))}var Cs=(n=>(n[n.SUCCESS=0]="SUCCESS",n[n.TEST_FAILED=1]="TEST_FAILED",n[n.DEVICE_UNAVAILABLE=2]="DEVICE_UNAVAILABLE",n[n.CONFIG_ERROR=3]="CONFIG_ERROR",n[n.LOCKED=4]="LOCKED",n))(Cs||{}),Fe=class extends Error{exitCode;phase;constructor(e,t=1,s){super(e),this.name="PromptTestError",this.exitCode=t,this.phase=s,Object.setPrototypeOf(this,new.target.prototype)}},gt=class extends Fe{constructor(e,t="Device"){super(e,2,t),this.name="DeviceError"}},Ft=class extends Fe{target;candidateMatches;constructor(e,t,s,i="Locator"){super(e,1,i),this.name="LocatorError",this.target=t,this.candidateMatches=s}},_t=class extends Fe{constructor(e,t="Config"){super(e,3,t),this.name="ConfigError"}},Ot=class extends Fe{serial;constructor(e,t,s="Lock"){super(e,4,s),this.name="LockError",this.serial=t}},mt=class extends Fe{cycle;constructor(e,t,s="SpecLoader"){super(e,3,s),this.name="SpecRecursionError",this.cycle=t}};var tt=class{defaultSerial=null;cachedDimensions=new Map;inFlightHierarchies=new Map;constructor(e){e&&(this.defaultSerial=e)}setDefaultDevice(e){this.defaultSerial=e}getDefaultDevice(){return this.defaultSerial}async getScreenDimensions(e){let t=e||this.defaultSerial||"default";if(this.cachedDimensions.has(t))return this.cachedDimensions.get(t);try{let{stdout:i}=await this.execAdb(["shell","wm","size"],e),n=i.match(/(?:Physical|Override)\s*size:\s*(\d+)x(\d+)/i);if(n){let r={width:parseInt(n[1],10),height:parseInt(n[2],10)};return this.cachedDimensions.set(t,r),r}}catch{}let s={width:T.screen.fallbackWidth,height:T.screen.fallbackHeight};return this.cachedDimensions.set(t,s),s}clearScreenDimensionsCache(e){e?this.cachedDimensions.delete(e):this.cachedDimensions.clear()}async getNavigationBarHeight(e){try{let{stdout:t}=await this.execAdb(["shell","dumpsys","window","displays"],e).catch(()=>({stdout:""})),s=t.match(/(?:navigationBarHeight|navBarHeight|navigationBarFrame)[=:\s]+(\d+)/i);if(s&&parseInt(s[1],10)>0)return parseInt(s[1],10)}catch{}return 0}isGlobalAdbCommand(e){return e?["devices","connect","disconnect","version","kill-server","start-server","help"].includes(e.toLowerCase()):!0}async execAdbInternal(e,t,s=2e4){let i=t||this.defaultSerial;!i&&!this.isGlobalAdbCommand(e[0])&&(await this.ensureDefaultDevice(),i=this.defaultSerial);let n=i&&!this.isGlobalAdbCommand(e[0])?["-s",i,...e]:[...e];return new Promise((r,o)=>{let a=et("adb",n),l="",c="",p=!1,h=setTimeout(()=>{p=!0;try{a.kill("SIGKILL")}catch{}o(new Error(`ADB command timed out after ${s}ms: adb ${n.join(" ")}`))},s);a.stdout.on("data",d=>{l+=d.toString("utf-8")}),a.stderr.on("data",d=>{c+=d.toString("utf-8")}),a.on("close",d=>{clearTimeout(h),!p&&(d===0?r({stdout:l,stderr:c}):o(new Error(`ADB command failed (code ${d}): adb ${n.join(" ")}
2
- Error: ${c}`)))}),a.on("error",d=>{clearTimeout(h),!p&&o(d)})})}async execAdb(e,t,s=T.adb.commandTimeoutMs,i=T.device.maxDeviceRetries){let n;for(let r=0;r<=i;r++)try{return await this.execAdbInternal(e,t,s)}catch(o){n=o;let a=o instanceof Error?o.message:String(o),l=a.toLowerCase(),c=l.includes("device offline")||l.includes("device not found"),p=c||l.includes("error: closed")||l.includes("timed out");if(r>=i||!p||this.isGlobalAdbCommand(e[0]))throw c?new gt(`Target Android device ${t||this.defaultSerial||""} is offline or disconnected: ${a}`):o;if(T.device.autoReconnect&&c)try{await this.execAdbInternal(["reconnect"],t,5e3).catch(()=>{})}catch{}await new Promise(h=>setTimeout(h,T.adb.retryBaseDelayMs*Math.pow(2,r+1)))}throw n||new Error(`ADB command failed after ${i} retries: ${e.join(" ")}`)}async execAdbBinary(e,t,s=45e3){let i=t||this.defaultSerial;!i&&!this.isGlobalAdbCommand(e[0])&&(await this.ensureDefaultDevice(),i=this.defaultSerial);let n=i&&!this.isGlobalAdbCommand(e[0])?["-s",i,...e]:[...e];return new Promise((r,o)=>{let a=et("adb",n),l=[],c="",p=!1,h=setTimeout(()=>{p=!0;try{a.kill("SIGKILL")}catch{}o(new Error(`ADB binary command timed out after ${s}ms: adb ${n.join(" ")}`))},s);a.stdout.on("data",d=>l.push(Buffer.from(d))),a.stderr.on("data",d=>{c+=d.toString("utf-8")}),a.on("close",d=>{clearTimeout(h),!p&&(d===0?r(Buffer.concat(l)):o(new Error(`ADB binary command failed (code ${d}): adb ${n.join(" ")}
3
- ${c}`)))}),a.on("error",d=>{clearTimeout(h),!p&&o(d)})})}async getConnectedDevices(){let{stdout:e}=await this.execAdb(ae.DEVICES),t=e.split(`
4
- `).map(o=>o.trim()).filter(Boolean),s=t.findIndex(o=>o.toLowerCase().includes("list of devices attached")),i=s!==-1?t.slice(s+1):t,n=[];return n=(o=>{let a=[];for(let l of o){if(!l||l.startsWith("*")||l.toLowerCase().includes("list of devices"))continue;let c=l.split(/\s+/);if(c.length>=2){let p=c[0],h=c[1],d,g;for(let f of c.slice(2))f.startsWith("model:")&&(d=f.replace("model:","")),f.startsWith("product:")&&(g=f.replace("product:",""));a.push({serial:p,state:h,model:d,product:g})}}return a})(i),n}async wakeDevice(e){try{await this.execAdb(["shell","input","keyevent","224"],e),await this.execAdb(["shell","wm","dismiss-keyguard"],e)}catch{}}async ensureDefaultDevice(e){if(e)return await this.wakeDevice(e),e;if(this.defaultSerial)return await this.wakeDevice(this.defaultSerial),this.defaultSerial;let s=(await this.getConnectedDevices()).find(i=>i.state==="device");return s&&(this.defaultSerial=s.serial,await this.wakeDevice(this.defaultSerial)),this.defaultSerial||void 0}async getDeviceModel(e){try{let{stdout:n}=await this.execAdb(["shell","getprop","ro.product.model"],e),r=n.trim();if(r)return r}catch{}let t=await this.getConnectedDevices(),s=e||this.defaultSerial;return t.find(n=>n.serial===s)?.model||s||"Android Device"}async captureScreenshot(e){return this.execAdbBinary(ae.SCREENCAP,e)}async getUiHierarchy(e){let t=e||this.defaultSerial||"default",s=this.inFlightHierarchies.get(t);if(s)return s;let i=(async()=>{try{let{stdout:n}=await this.execAdb(ae.UIAUTOMATOR_DUMP,e,1e4,0),r=n.indexOf("<hierarchy");return r>=0?n.slice(r):n}finally{this.inFlightHierarchies.delete(t)}})();return this.inFlightHierarchies.set(t,i),i}clearInFlightHierarchies(e){e?this.inFlightHierarchies.delete(e):this.inFlightHierarchies.clear()}async getForegroundPackage(e){let t=s=>{let i=s.toLowerCase();return i==="android"||i.includes("systemui")||i.includes("inputmethod")||i.includes("latin")||i.includes("gboard")||i.includes("swiftkey")||i.includes("ime")};try{let{stdout:s}=await this.execAdb(["shell","dumpsys","activity","activities"],e).catch(()=>({stdout:""})),i=s.match(/(?:topResumedActivity|mResumedActivity)=.+?\s+([a-zA-Z0-9._]+)\//);if(i&&i[1]&&!t(i[1]))return i[1];let{stdout:n}=await this.execAdb(ae.FOREGROUND_APP,e),r=n.matchAll(/(?:mCurrentFocus|mFocusedWindow|mFocusedApp|topResumedActivity|mResumedActivity|mFocusedActivity)=.+?\s+([a-zA-Z0-9._]+)\/([a-zA-Z0-9._]+)/g);for(let o of r)if(o&&o[1]&&!t(o[1]))return o[1]}catch{}return null}async tap(e,t,s){await this.execAdb(ae.INPUT_TAP(e,t),s)}async inputText(e,t){let s=e.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/'/g,"\\'").replace(/%/g,"\\%").replace(/ /g,"%s").replace(/&/g,"\\&").replace(/</g,"\\<").replace(/>/g,"\\>").replace(/\(/g,"\\(").replace(/\)/g,"\\)").replace(/;/g,"\\;").replace(/\|/g,"\\|").replace(/\$/g,"\\$").replace(/#/g,"\\#").replace(/\*/g,"\\*").replace(/\?/g,"\\?").replace(/~/g,"\\~").replace(/`/g,"\\`");try{await this.execAdb(ae.INPUT_TEXT(s),t)}catch{for(let i of e)if(i===" ")await this.pressKey(62,t);else if(i==="@")await this.pressKey(77,t);else{let n=i.replace(/([\\"'&<>()|$;#*?~`%])/g,"\\$1");await this.execAdb(["shell","input","text",n],t).catch(()=>{})}}}async pressKey(e,t){await this.execAdb(ae.INPUT_KEY(e),t)}async pressEnter(e){await this.pressKey(66,e)}async pressTab(e){await this.pressKey(61,e)}async pressHome(e){await this.pressKey(3,e)}async pressBack(e){await this.pressKey(4,e)}async setWifiEnabled(e,t){await this.execAdb(["shell","svc","wifi",e?"enable":"disable"],t)}async setAirplaneMode(e,t){await this.execAdb(["shell","cmd","connectivity","airplane-mode",e?"enable":"disable"],t)}async setOrientation(e,t){await this.execAdb(["shell","content","insert","--uri","content://settings/system","--bind","name:s:accelerometer_rotation","--bind","value:i:0"],t).catch(()=>{});let s=e==="landscape"?"1":"0";await this.execAdb(["shell","settings","put","system","user_rotation",s],t)}async openNotificationShade(e){await this.execAdb(["shell","cmd","statusbar","expand-notifications"],e)}async collapseNotificationShade(e){await this.execAdb(["shell","cmd","statusbar","collapse"],e)}async clearInput(e=45,t){let s=Array(e).fill("67");await this.execAdb(["shell","input","keyevent",...s],t)}async clearField(e,t=80){await this.pressKey(123,e);let s=Math.max(50,t+10),i=Array(s).fill("67");await this.execAdb(["shell","input","keyevent",...i],e).catch(()=>{}),await this.pressKey(122,e);let n=Array(Math.max(30,Math.floor(t/2))).fill("112");await this.execAdb(["shell","input","keyevent",...n],e).catch(()=>{})}async swipe(e,t,s,i,n=300,r){await this.execAdb(ae.INPUT_SWIPE(e,t,s,i,n),r)}async launchApp(e,t){try{let{stdout:s}=await this.execAdb(["shell","cmd","package","resolve-activity","--brief",e],t),n=(s||"").split(`
5
- `).map(r=>r.trim()).find(r=>r.includes("/")&&!r.includes(" "));if(n){await this.execAdb(["shell","am","start","-n",n],t);return}}catch{}await this.execAdb(ae.LAUNCH_APP(e),t)}async forceStop(e,t){await this.execAdb(ae.FORCE_STOP(e),t)}async clearAppData(e,t){await this.execAdb(ae.CLEAR_APP(e),t)}async restartApp(e,t){await this.forceStop(e,t),await new Promise(s=>setTimeout(s,600)),await this.launchApp(e,t)}async grantPermission(e,t,s){await this.execAdb(ae.GRANT_PERMISSION(e,t),s)}async isAppInstalled(e,t){try{let{stdout:s}=await this.execAdb(["shell","pm","list","packages",e],t);return s.toLowerCase().includes(`package:${e.toLowerCase()}`)||s.includes(e)}catch{return!1}}async installApk(e,t){await this.execAdb(ae.INSTALL_APK(e),t)}async uninstallApp(e,t){await this.execAdb(ae.UNINSTALL_APP(e),t)}async openDeepLink(e,t){await this.execAdb(ae.DEEP_LINK(e),t)}async checkCrashes(e,t){try{let{stdout:s}=await this.execAdb(ae.LOGCAT_CRASH(e),t);if(s&&s.includes("FATAL EXCEPTION")&&s.includes(e))return s}catch{}return null}async clearCrashLogs(e){try{await this.execAdb(ae.CLEAR_CRASH_LOGS(),e)}catch{}}async getDeviceIp(e){try{let{stdout:t}=await this.execAdb(ae.GET_WLAN_IP,e),s=t.match(/inet\s+(\d+\.\d+\.\d+\.\d+)/);if(s&&s[1])return s[1]}catch{}try{let{stdout:t}=await this.execAdb(["shell","ip","route"],e),s=t.match(/src\s+(\d+\.\d+\.\d+\.\d+)/);if(s&&s[1])return s[1]}catch{}return null}async connectWifi(e,t=5555,s){let i=e,n=t;if(e&&e.includes(":")){let p=e.split(":");i=p[0],n=parseInt(p[1],10)||t}if(!i){let p=await this.getDeviceIp(s);if(!p)throw new Error("Could not auto-detect phone Wi-Fi IP. Make sure the phone is on Wi-Fi, or pass IP manually: npx prompttest wifi <ip>");i=p}let r=`${i}:${n}`;if(e)try{let{stdout:p,stderr:h}=await this.execAdb(ae.CONNECT(r)),d=`${p} ${h}`.trim();if(d.toLowerCase().includes("connected")||d.toLowerCase().includes("already"))return this.defaultSerial=r,{success:!0,target:r,message:d}}catch{}try{await this.execAdb(ae.TCPIP(n),s),await new Promise(p=>setTimeout(p,1e3))}catch{}let{stdout:o,stderr:a}=await this.execAdb(ae.CONNECT(r)),l=`${o} ${a}`.trim(),c=l.toLowerCase().includes("connected")||l.toLowerCase().includes("already");return c&&(this.defaultSerial=r),{success:c,target:r,message:l}}async disconnectWifi(e){let{stdout:t,stderr:s}=await this.execAdb(ae.DISCONNECT(e));return`${t} ${s}`.trim()}streamLogcatEvents(e,t){let i=et("adb",["-s",e,"shell","logcat","-b","events","-v","time"]),n=Bt.createInterface({input:i.stdout});return n.on("line",t),i.on("close",()=>{try{n.close()}catch{}}),i.on("error",()=>{}),i}streamLogcatCrashes(e,t){let i=et("adb",["-s",e,"shell","logcat","-T","1","-s","AndroidRuntime:E","ANRManager:E","-v","time"]),n=Bt.createInterface({input:i.stdout});return n.on("line",t),i.on("close",()=>{try{n.close()}catch{}}),i.on("error",()=>{}),i}streamLogcatToasts(e,t){let i=et("adb",["-s",e,"shell","logcat","-s","Toast:D","Snackbar:D","-v","time"]),n=Bt.createInterface({input:i.stdout});return n.on("line",t),i.on("close",()=>{try{n.close()}catch{}}),i.on("error",()=>{}),i}async getLogcatTail(e=150,t){try{let{stdout:s}=await this.execAdb(["logcat","-d","-t",String(e),"-v","time"],t);return s}catch(s){return`Failed to capture logcat: ${s instanceof Error?s.message:String(s)}`}}async startScreenRecording(e="/sdcard/prompttest_temp.mp4",t){let s=t||this.defaultSerial,n=et("adb",s?["-s",s,"shell","screenrecord",e]:["shell","screenrecord",e]);return n.on("error",()=>{}),{remotePath:e,process:n}}async stopScreenRecording(e,t,s){try{try{e.process.kill("SIGINT")}catch{}return await this.execAdb(["shell","pkill","-2","screenrecord"],s).catch(()=>{}),await new Promise(i=>setTimeout(i,1500)),await this.execAdb(["pull",e.remotePath,t],s),await this.execAdb(["shell","rm","-f",e.remotePath],s).catch(()=>{}),t}catch{return""}}async isKeyboardVisible(e){try{let{stdout:t}=await this.execAdb(["shell","dumpsys","input_method"],e,4e3,0);return t.includes("mInputShown=true")||t.includes("isInputViewShown=true")||t.includes("mHasSurface=true")}catch{return!1}}async ensureAccessibilityServices(e){try{await this.execAdb(["shell","settings","put","secure","accessibility_enabled","1"],e,4e3,0)}catch{}}},he=new tt;var Ls=/^(\d+(?:\.\d+)*\.?|\-|\*)\s*/;function Rs(u){let e=u.trim(),t=e.match(/^"([^"]+)"$/);if(t)return t[1].trim();let s=e.match(/^'([^']+)'$/);return s?s[1].trim():e.replace(/^['"]+|['"]+$/g,"").trim()}var V=`(?:"([^"]+)"|'([^']+)'|([^'"\\s][^'"]*?[^'"\\s]|\\S))`;function W(u){for(let e of u)if(e!=null&&e.trim().length>0)return e.trim();return""}function Xe(u,e){let t=u;if(e)for(let[s,i]of Object.entries(e))t=t.replace(new RegExp(`\\$${s}\\b`,"g"),()=>i);return t=t.replace(/\$ENV\{([A-Z0-9_]+)\}/gi,(s,i)=>process.env[i]||""),t=t.replace(/\$RANDOM_EMAIL\b/g,()=>`test_${Date.now().toString().slice(-6)}@prompttest.io`),t=t.replace(/\$RANDOM_NAME\b/g,()=>`User_${Math.floor(1e3+Math.random()*9e3)}`),t=t.replace(/\$RANDOM_PHONE\b/g,()=>`98${Math.floor(1e7+Math.random()*9e7)}`),t=t.replace(/\$TIMESTAMP\b/g,()=>Date.now().toString()),t=t.replace(/\$UUID\b/g,()=>`${Date.now().toString(16)}-${Math.random().toString(16).substring(2,8)}`),t=t.replace(/\$RANDOM_UUID\b/g,()=>"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,s=>{let i=Math.random()*16|0;return(s==="x"?i:i&3|8).toString(16)})),t=t.replace(/\$RANDOM_CARD\b/g,()=>{let s="4532";for(let i=0;i<12;i++)s+=Math.floor(Math.random()*10);return s}),t=t.replace(/\$DATE_OFFSET\((-?\d+)\)/g,(s,i)=>{let n=parseInt(i,10)||0;return new Date(Date.now()+n*864e5).toISOString().slice(0,10)}),t=t.replace(/\$RANDOM_INT\((\d+),\s*(\d+)\)/g,(s,i,n)=>{let r=parseInt(i,10),o=parseInt(n,10);return String(Math.floor(r+Math.random()*(o-r+1)))}),t}var O={TAP:new RegExp(`^(?:tap|click|press)(?:\\s+on)?\\s+(?:button\\s+|item\\s+)?${V}$`,"i"),ORDINAL_TAP:new RegExp(`^(?:tap|click|press)(?:\\s+on)?\\s+(?:the\\s+)?(1st|2nd|3rd|4th|5th|last|first)\\s+(?:button\\s+|item\\s+)?${V}$`,"i"),PROXIMITY_TAP:new RegExp(`^(?:tap|click|press)(?:\\s+on)?\\s+${V}\\s+(?:next\\s+to|near|beside|inside|for)\\s+${V}$`,"i"),CLEAR:new RegExp(`^(?:clear|empty)(?:\\s+(?:text\\s+(?:in|of)|field|input))?\\s+${V}$`,"i"),LONG_PRESS:new RegExp(`^(?:long\\s+press|press\\s+and\\s+hold)\\s+(?:button\\s+|item\\s+)?${V}$`,"i"),TYPE:new RegExp(`^(?:type|enter|input)\\s+${V}\\s+(?:in|into)\\s+${V}$`,"i"),VERIFY:new RegExp(`^(?:verify|veryfy|check|assert|ensure)\\s+(?:that\\s+)?(?:error\\s+message\\s+|message\\s+|text\\s+|element\\s+|button\\s+|toast\\s+|my\\s+)?${V}\\s*(?:is\\s+(visible|exists|appears|enabled|disabled|not\\s+visible|hidden|absent|not\\s+present|gone))?$`,"i"),BACK:/^(?:press\s+back|go\s+back|navigate\s+back|back)$/i,SCROLL_TO:new RegExp(`^(?:scroll|swipe)(?:\\s+(down|up))?\\s+(?:to|until)\\s+${V}$`,"i"),SCROLL:/^(?:scroll|swipe)\s+(down|up)$/i,DIRECTIONAL_SWIPE:new RegExp(`^(?:swipe|scroll)\\s+(left|right|up|down)(?:\\s+on\\s+${V})?$`,"i"),TOGGLE:new RegExp(`^(?:toggle|turn\\s+(on|off)|check|uncheck)\\s+(?:checkbox\\s+|switch\\s+)?${V}$`,"i"),SELECT_DROPDOWN:new RegExp(`^(?:select|choose)\\s+${V}\\s+from\\s+${V}$`,"i"),LAUNCH_APP:new RegExp(`^(?:launch|open)\\s+(?:app\\s+)?${V}$`,"i"),RESTART_APP:new RegExp(`^(?:restart|relaunch)\\s+(?:app\\s+)?${V}$`,"i"),TERMINATE_APP:new RegExp(`^(?:terminate|close|force\\s*stop)\\s+(?:app\\s+)?(?:${V})?$`,"i"),CLEAR_DATA:new RegExp(`^(?:clear\\s+(?:app\\s+)?data\\s+(?:for\\s+)?|reset\\s+app\\s+)${V}$`,"i"),GRANT_PERMISSION:new RegExp(`^grant\\s+permissions?\\s+${V}(?:\\s+(?:to|for)\\s+${V})?$`,"i"),DEEP_LINK:new RegExp(`^(?:open\\s+deep\\s*link|navigate\\s+to\\s+url)\\s+${V}$`,"i"),WAIT:/^wait\s+(\d+)\s*(?:s|sec|seconds|ms)?$/i,WAIT_UNTIL:new RegExp(`^(?:wait\\s+until|wait\\s+for)\\s+${V}\\s+(?:(?:is\\s+)?(visible|appears?|enabled|exists))?(?:\\s+(?:up\\s+to|for)\\s+(\\d+)\\s*(s|sec|seconds|ms)?)?$`,"i"),IF_VISIBLE:new RegExp(`^if\\s+(?:(?:that\\s+)?${V}\\s+(?:is\\s+)?(visible|present|exists|appears?)|element\\s+${V}\\s+(?:is\\s+)?visible)$`,"i"),ELSE:/^else$/i,END:/^(?:end|end\s*if|end\s*loop|fi|done)$/i,LOOP:/^(?:loop|repeat)\s+(\d+)\s*(?:times)?$/i,FOR_EACH:new RegExp(`^for\\s+each\\s+(?:item\\s+)?(?:in\\s+)?${V}$`,"i"),SET_VARIABLE:/^set\s+\$([a-zA-Z0-9_]+)\s*=\s*(.+)$/i,DEVICE_WIFI:/^(?:turn\s+|set\s+)?wifi\s+(on|off|enable|disable)$/i,DEVICE_AIRPLANE:/^(?:turn\s+|set\\s+)?airplane\s*(?:mode)?\s+(on|off|enable|disable)$/i,DEVICE_ORIENTATION:/^(?:set\s+)?orientation\s+(?:to\s+)?(portrait|landscape)$/i,DEVICE_NOTIFICATIONS:/^(open|expand|pull\s+down|collapse|close)\s+notification(?:s|\s+shade)?$/i,INCLUDE_SPEC:new RegExp(`^(?:include|run_spec|subflow)\\s+${V}$`,"i"),RUN_JS:/^(?:run\s+js|eval\s+js|js)(?::|\s+)(.+)$/i,ENTER_OTP:new RegExp(`^(?:enter|input|type)\\s+(?:the\\s+)?(?:verification\\s+code|otp|2fa\\s+code|sms\\s+code)(?:\\s+just\\s+sent)?(?:\\s+(?:in|into)\\s+${V})?$`,"i"),API_REQUEST:new RegExp(`^(?:api|call\\s+api)\\s+(GET|POST|PUT|DELETE|PATCH)\\s+${V}(?:\\s+with\\s+body\\s+${V})?(?:\\s+store\\s+${V}\\s+as\\s+\\$([a-zA-Z0-9_]+))?(?:\\s+assert\\s+status\\s+(\\d+))?$`,"i"),EMAIL_ASSERT:new RegExp(`^(?:assert|verify)\\s+email\\s+to\\s+${V}\\s+with\\s+subject\\s+${V}(?:\\s+contains\\s+${V})?$`,"i"),OPTIONAL_SUFFIX:/\s*\((?:optional|if\s+present|maybe)\)\s*$/i,FALLBACK_QUOTED_TAP:/^(?:tap|click)\s+.*?['"]([^'"]+)['"]/i},ft={HIERARCHY_ROOT:/<hierarchy[^>]*>([\s\S]*?)<\/hierarchy>/i,NODE_TAG:/<node\b([^>]*?)(\/?)>|<\/node>/gi,ATTR_KEY_VALUE:/([a-zA-Z0-9_-]+)="([^"]*)"/g,BOUNDS_RECT:/\[(\d+),(\d+)\]\[(\d+),(\d+)\]/};function st(u){return(u||"").replace(/&#(\d+);/g,(e,t)=>{try{return String.fromCodePoint(parseInt(t,10))}catch{return""}}).replace(/&#x([0-9a-fA-F]+);/g,(e,t)=>{try{return String.fromCodePoint(parseInt(t,16))}catch{return""}}).replace(/&amp;/g,"&").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&quot;/g,'"').replace(/&apos;/g,"'")}function X(u){return st(u||"").trim().toLowerCase().replace(/[\u2018\u2019]/g,"'").replace(/[\u201C\u201D]/g,'"').replace(/\uFFFD/g,"").replace(new RegExp("\\p{Extended_Pictographic}","gu"),"").replace(/[\uE000-\uF8FF\uFFF0-\uFFFF]/g,"").replace(/\s+/g," ").trim()}var Is=new Map;function z(u,e){if(!u||!e)return!1;let t=X(u),s=X(e);if(t.length<=3){let i=Is.get(t);if(!i){let n=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");i=new RegExp(`(?:^|\\b)${n}(?:\\b|$)`,"i"),Is.set(t,i)}return i.test(s)}return s.includes(t)}var Ns=["sign in","signin","login","log in","submit","save","continue","next","done","send","confirm","proceed","post","rate","enter","join","apply","update"],Ms=["sign in","signin","login","log in","submit","save","next","continue","done","like","fav","favorite","star","bookmark","add","post","confirm","apply","explore","search","filter"];function bi(u,e){let t=X(u),s=X(e),i=t.length,n=s.length;if(i===0)return n;if(n===0)return i;let r=Array.from({length:n+1},(a,l)=>l),o=new Array(n+1);for(let a=1;a<=i;a++){o[0]=a;for(let c=1;c<=n;c++){let p=t[a-1]===s[c-1]?0:1;o[c]=Math.min(r[c]+1,o[c-1]+1,r[c-1]+p)}let l=r;r=o,o=l}return r[n]}function yi(u,e){let t=X(u),s=X(e);if(t===s)return 1;if(!t||!s)return 0;let i=Math.max(t.length,s.length);return 1-bi(t,s)/i}function We(u,e,t=3,s=.35){return Array.from(new Set(e.map(r=>r.trim()).filter(r=>r.length>0))).map(r=>({text:r,score:yi(u,r)})).filter(r=>r.score>=s).sort((r,o)=>o.score-r.score).slice(0,t)}function Fs(u){let e=u.match(ft.BOUNDS_RECT);if(!e)return{x1:0,y1:0,x2:0,y2:0,width:0,height:0,centerX:0,centerY:0};let t=parseInt(e[1],10),s=parseInt(e[2],10),i=parseInt(e[3],10),n=parseInt(e[4],10);return{x1:t,y1:s,x2:i,y2:n,width:i-t,height:n-s,centerX:Math.round((t+i)/2),centerY:Math.round((s+n)/2)}}function Si(u){let e=u.match(ft.HIERARCHY_ROOT);if(!e)return{root:[],flat:[]};let t=e[1],s=new RegExp(ft.NODE_TAG.source,"gi"),i=new RegExp(ft.ATTR_KEY_VALUE.source,"g"),n=[],r=[],o=[],a;for(;(a=s.exec(t))!==null;){let l=a[0],c=a[1],p=a[2]==="/";if(l.startsWith("</node>")){o.pop();continue}let h={};i.lastIndex=0;let d;for(;(d=i.exec(c))!==null;)h[d[1]]=d[2];let g={index:parseInt(h.index||"0",10),text:st(h.text||""),resourceId:h["resource-id"]||"",className:h.class||"",packageName:h.package||"",contentDesc:st(h["content-desc"]||""),bounds:Fs(h.bounds||""),clickable:h.clickable==="true",enabled:h.enabled==="true",focused:h.focused==="true",scrollable:h.scrollable==="true",password:h.password==="true",selected:h.selected==="true",checked:h.checked!==void 0?h.checked==="true":void 0,checkable:h.checkable!==void 0?h.checkable==="true":void 0,children:[]};r.push(g),o.length===0?n.push(g):o[o.length-1].children.push(g),p||o.push(g)}return{root:n,flat:r}}function wi(u){let e=[],t=[],s=[],i=u.length,n=0;for(;n<i;){let r=u.indexOf("<",n);if(r===-1)break;if(u.startsWith("<!--",r)){let S=u.indexOf("-->",r+4);n=S===-1?i:S+3;continue}if(u.startsWith("<?",r)){let S=u.indexOf("?>",r+2);n=S===-1?i:S+2;continue}if(u.startsWith("</",r)){let S=u.indexOf(">",r+2);if(S===-1)break;u.slice(r+2,S).trim()==="node"&&s.pop(),n=S+1;continue}let o=-1,a=null,l=!1;for(let S=r+1;S<i;S++){let b=u[S];if(a)b===a&&(a=null);else if(b==='"'||b==="'")a=b;else if(b===">"){o=S,u[S-1]==="/"&&(l=!0);break}}if(o===-1)break;let c=u.slice(r+1,l?o-1:o).trim();n=o+1;let p=0;for(;p<c.length&&!/\s/.test(c[p]);)p++;if(c.slice(0,p)!=="node")continue;let d={},g=p,f=c.length;for(;g<f;){for(;g<f&&/\s/.test(c[g]);)g++;if(g>=f)break;let S=g;for(;g<f&&c[g]!=="="&&!/\s/.test(c[g]);)g++;let b=c.slice(S,g);for(;g<f&&/\s/.test(c[g]);)g++;if(g>=f||c[g]!=="=")break;for(g++;g<f&&/\s/.test(c[g]);)g++;if(g>=f)break;let m=c[g];if(m==='"'||m==="'"){g++;let v=g;for(;g<f&&c[g]!==m;)g++;d[b]=c.slice(v,g),g<f&&g++}else{let v=g;for(;g<f&&!/\s/.test(c[g]);)g++;d[b]=c.slice(v,g)}}let y={index:parseInt(d.index||"0",10),text:st(d.text||""),resourceId:d["resource-id"]||"",className:d.class||"",packageName:d.package||"",contentDesc:st(d["content-desc"]||""),bounds:Fs(d.bounds||""),clickable:d.clickable==="true",enabled:d.enabled==="true",focused:d.focused==="true",scrollable:d.scrollable==="true",password:d.password==="true",selected:d.selected==="true",checked:d.checked!==void 0?d.checked==="true":void 0,checkable:d.checkable!==void 0?d.checkable==="true":void 0,children:[]};t.push(y),s.length===0?e.push(y):s[s.length-1].children.push(y),l||s.push(y)}return{root:e,flat:t}}function ue(u,e){if((e||T.parser?.mode||"regex")==="streaming")try{return wi(u)}catch{}return Si(u)}function ir(u,e){return u.filter(t=>{if(e.clickable!==void 0&&t.clickable!==e.clickable||e.className&&!t.className.includes(e.className))return!1;if(e.text){if(typeof e.text=="string"){if(!t.text.toLowerCase().includes(e.text.toLowerCase()))return!1}else if(!e.text.test(t.text))return!1}if(e.contentDesc){if(typeof e.contentDesc=="string"){if(!t.contentDesc.toLowerCase().includes(e.contentDesc.toLowerCase()))return!1}else if(!e.contentDesc.test(t.contentDesc))return!1}if(e.resourceId){if(typeof e.resourceId=="string"){if(!t.resourceId.toLowerCase().includes(e.resourceId.toLowerCase()))return!1}else if(!e.resourceId.test(t.resourceId))return!1}return!0})}var vi=[/logbox/i,/^Log \d+ of \d+/i,/Console (?:Error|Warning|Log|Info)/i,/^Call Stack$/i,/^Source Map$/i,/^(?:Dismiss|Minimize|Copy|View error log)$/i,/\b[\w-]+\.(?:tsx?|jsx?|js|ts):\d+:\d+\b/i,/Unhandled Promise Rejection/i,/SyntaxError/i,/TypeError:/i,/ReferenceError:/i,/Warning:/i,/LogBoxNotificationOverlay/i];function Se(u){if(u.resourceId&&/logbox/i.test(u.resourceId)||u.className&&/logbox/i.test(u.className))return!0;let e=`${u.text} ${u.contentDesc}`.trim();return!!vi.some(t=>t.test(e))}function _e(u){return u.filter(e=>Se(e)?!1:(e.className.includes("EditText")||e.className.includes("TextInputEditText")||e.focused&&e.clickable)&&e.bounds.width>0&&e.bounds.height>0)}function Ht(u){return u.className.includes("EditText")||u.className.includes("TextInputEditText")?!0:(u.children||[]).some(Ht)}function bt(u,e){let t=e?.width||T.screen.fallbackWidth,s=e?.height||T.screen.fallbackHeight,i=s*.08,n=s*.88,r=u.filter(a=>!Se(a)&&(a.className.includes("RecyclerView")||a.className.includes("ListView")||a.className.includes("ScrollView"))),o=[];for(let a of r)for(let l of a.children){if(Se(l)||l.bounds.centerY<i||l.bounds.centerY>n)continue;(l.clickable||l.children.some(p=>!Se(p)&&p.clickable&&p.bounds.width>t*.1))&&l.bounds.width>t*.08&&l.bounds.height>s*.02&&!Ht(l)&&o.push(l)}return o.length===0?u.filter(a=>{if(Se(a))return!1;let l=(a.text||a.contentDesc||"").trim();return l.length<=1||/^(remember me|forgot password|sign in|sign up|login|submit|cancel)$/i.test(l)?!1:a.clickable&&a.bounds.width>t*.14&&a.bounds.height>s*.033&&a.bounds.centerY>i&&a.bounds.centerY<n&&!a.className.includes("Button")&&!a.className.includes("EditText")&&!Ht(a)}):o}function Ge(u){return u.filter(e=>{if(Se(e)||!e.clickable||e.bounds.width===0||e.className.includes("EditText"))return!1;let t=e.className.includes("Button")||e.className.includes("ImageButton"),s=Ms.some(i=>z(i,e.text)||z(i,e.contentDesc)||z(i,e.resourceId));return t||s})}function Ut(u,e=T.screen.fallbackHeight,t){if(!u||u.length===0)return[];let s=u.find(d=>d.bounds.height>=e*.6&&d.bounds.y1<=e*.15),i=s?.bounds?.y1!==void 0&&s.bounds.y1>=0?s.bounds.y1:0,n=s?.bounds?.y2&&s.bounds.y2>i?s.bounds.y2:e,r=n-i,o=s?.bounds?.x2&&s.bounds.x2>0?s.bounds.x2-(s.bounds.x1||0):T.screen.fallbackWidth,a=i+r*.78,l=u.filter(d=>Se(d)||t&&d.packageName&&!d.packageName.includes(t)||!d.clickable||d.bounds.width<=0||d.bounds.height<=0||!(d.bounds.centerY>=a||d.bounds.y2>=n-20)?!1:d.bounds.width>=o*.12&&d.bounds.width<=o*.55);if(l.length<=1)return l;let c=[];for(let d of l){let g=c.find(f=>Math.abs(f[0].bounds.centerY-d.bounds.centerY)<=30||Math.abs(f[0].bounds.y2-d.bounds.y2)<=20);g||(g=[],c.push(g)),g.push(d)}let p=c.map(d=>{d.sort((f,y)=>f.bounds.centerX-y.bounds.centerX);let g=[];for(let f of d)g.some(y=>Math.abs(y.bounds.centerX-f.bounds.centerX)<o*.08)||g.push(f);return g}).filter(d=>d.length<2||d.length>6?!1:d[d.length-1].bounds.x2-d[0].bounds.x1>=o*.6);return p.length===0?l.slice(0,5):(p.sort((d,g)=>g[0].bounds.centerY-d[0].bounds.centerY),p[0].slice(0,5))}function _s(u){let e=[/fatal\s+exception/i,/unfortunately.*stopped/i,/(?:app|system|process).*(?:isn't|is not|not)\s+responding/i,/(?:isn't|is not|not)\s+responding/i,/force\s+close/i,/network\s+connection\s+(?:failed|lost|error)/i,/something went wrong/i,/(?:failed|unable)\s+to\s+(?:connect|load|fetch)/i];return u.filter(t=>{let s=`${t.text} ${t.contentDesc}`;return e.some(i=>i.test(s))})}var xi=[/(?:\b|[_\s-])(?:log[_\s-]*out|sign[_\s-]*out)(?:\b|[_\s-])/i,/(?:\b|[_\s-])(?:delete|remove)(?:[_\s-]+(?:account|profile|all|data|item|cart|user))?(?:\b|[_\s-])/i,/(?:\b|[_\s-])(?:clear[_\s-]+data|wipe|force[_\s-]+stop|factory[_\s-]+reset|uninstall)(?:\b|[_\s-])/i,/(?:\b|[_\s-])(?:pay|purchase|checkout|buy[_\s-]+now|order[_\s-]+now)(?:\b|[_\s-])/i],Ti=[/(?:\b|[_\s-])(?:log[_\s-]*out|sign[_\s-]*out)(?:\b|[_\s-])/i,/(?:\b|[_\s-])(?:delete|remove)[_\s-]+(?:account|profile|user)(?:\b|[_\s-])/i,/(?:\b|[_\s-])(?:clear[_\s-]+data|wipe|force[_\s-]+stop|factory[_\s-]+reset|uninstall)(?:\b|[_\s-])/i],Ei=[/(?:\b|[_\s-])(?:rate[_\s-]*us|review[_\s-]*(?:on|in)[_\s-]*(?:play|store)|play[_\s-]*store)(?:\b|[_\s-])/i,/(?:\b|[_\s-])(?:visit[_\s-]*(?:our)?[_\s-]*website|privacy[_\s-]*policy|terms[_\s-]*of[_\s-]*service|terms[_\s-]*&[_\s-]*conditions)(?:\b|[_\s-])/i,/(?:\b|[_\s-])(?:follow[_\s-]*us|share[_\s-]*via|share[_\s-]*app|open[_\s-]*in[_\s-]*browser)(?:\b|[_\s-])/i,/^https?:\/\//i,/(?:www\.[a-z0-9-]+\.[a-z]{2,})/i];function Ee(u,e,t=T.safety?.mode||"strict"){if(t==="disabled")return!1;let s=`${u.text} ${u.contentDesc} ${u.resourceId}`.trim();if((t==="moderate"?Ti:xi).some(r=>r.test(s)))return!0;let n=e||T.safety?.customBlacklist||[];for(let r of n)if(typeof r=="string"&&r.length>0){if(s.toLowerCase().includes(r.toLowerCase()))return!0}else if(r instanceof RegExp&&r.test(s))return!0;return!1}function Pe(u){let e=`${u.text} ${u.contentDesc} ${u.resourceId}`.trim();return Ei.some(t=>t.test(e))}function yt(u){for(let e of u){let t=`${e.text} ${e.contentDesc} ${e.resourceId}`;if(e.resourceId.toLowerCase().includes("logbox")||t.includes("Unhandled Promise Rejection")||t.includes("SyntaxError")||t.includes("Encountered two children with the same key")||t.includes("Warning:")||t.includes("Console Error")||t.includes("Console Warning")||t.includes("Console Info")||t.includes("TypeError:")||t.includes("ReferenceError:")||/Log \d+ of \d+/i.test(t)||t.includes("LogBox")&&(e.className.includes("Modal")||e.className.includes("ViewGroup"))){let i="error";/warning/i.test(t)?i="warning":/info/i.test(t)&&(i="info");let n=e.resourceId.includes("notification")||e.bounds.height>0&&e.bounds.height<250,r,o=[];for(let c of u){let p=`${c.text} ${c.contentDesc}`.trim();if(!r){let h=p.match(/\b([a-zA-Z0-9_.-]+\.(?:tsx?|jsx?|js|ts):\d+:\d+)\b/);h&&(r=h[1])}/\b(?:at\s+|\()?[a-zA-Z0-9_.-]+\.(?:tsx?|jsx?|js|ts):\d+/i.test(p)&&!o.includes(p)&&p.length<200&&o.push(p)}let a=u.find(c=>c.clickable&&c.bounds.width>0&&(/^(?:dismiss|close)$/i.test((c.text||"").trim())||/^(?:dismiss|close)$/i.test((c.contentDesc||"").trim())));if(!a&&!n){let p=u.filter(h=>h.clickable&&h.bounds.width>0&&h.bounds.height>0&&!/minimize|copy/i.test(`${h.text} ${h.contentDesc}`)).filter(h=>h.bounds.centerY>T.screen.fallbackHeight*.8);p.length>0&&(p.sort((h,d)=>h.bounds.x1-d.bounds.x1),a=p[0])}!a&&n&&(a=u.find(c=>c.clickable&&c.bounds.y1>=e.bounds.y1-20&&c.bounds.y2<=e.bounds.y2+20&&c.bounds.x1>=e.bounds.x2-120));let l=e.text||e.contentDesc||"React Native LogBox Console Overlay";return{type:"logbox",severity:i,node:e,errorText:l,sourceLocation:r,stackTrace:o.length>0?o:void 0,dismissButton:a,isToast:n}}if(e.resourceId.includes("alertTitle")&&(t.includes("isn't responding")||t.includes("has stopped"))){let i=u.find(n=>n.text.toLowerCase().includes("close app")||n.text.toLowerCase().includes("ok"));return{type:"anr",severity:"error",node:e,errorText:e.text||"Application Not Responding (ANR)",dismissButton:i}}}return null}function it(u){return u.filter(e=>Se(e)?!1:(e.checkable||e.className.includes("CheckBox")||e.className.includes("Switch")||e.className.includes("RadioButton")||e.className.includes("SwitchCompat"))&&e.bounds.width>0&&e.bounds.height>0)}function Oe(u,e=T.screen.fallbackHeight,t=T.screen.fallbackWidth){let s=e*.22,i=/(?:menu|hamburger|drawer|navigation|\u2630|open[_\s-]*drawer)/i,n=u.find(r=>{if(!r.clickable||r.bounds.width===0||r.bounds.centerY>s)return!1;let o=`${r.contentDesc} ${r.text} ${r.resourceId}`;return i.test(o)});return n||u.find(r=>{if(!r.clickable||r.bounds.width===0||r.bounds.height===0||r.bounds.centerY>s||(r.text||r.contentDesc||"").trim().length>0)return!1;let a=r.bounds.x1<=t*.25,l=r.bounds.width<=250&&r.bounds.height<=250;return a&&l})||null}function Os(u,e=T.screen.fallbackHeight,t=T.screen.fallbackWidth){let s=e*.22;return u.filter(i=>{if(!i.clickable||i.bounds.width===0||i.bounds.height===0||i.bounds.centerY>s)return!1;let n=i.bounds.x2>=t*.75,r=i.bounds.width<=250&&i.bounds.height<=250;return n&&r})}function Bs(u){return u.filter(e=>{if(e.bounds.width===0||e.bounds.height===0)return!1;let t=e.className.includes("ScrollView")||e.className.includes("RecyclerView")||e.className.includes("ListView")||e.className.includes("NestedScrollView");return e.scrollable||t})}function Hs(u,e=T.screen.fallbackWidth,t=T.screen.fallbackHeight,s=T.visual.overlapRatio){let i=[];for(let h of u)(h.text||h.clickable)&&h.bounds.width>0&&(h.bounds.x2>e+10&&h.bounds.x1<e&&i.push({type:"OVERFLOW",severity:"WARN",description:`Element "${h.text||h.contentDesc||h.className}" overflows right screen boundary by ${h.bounds.x2-e}px`,elements:[h.text||h.contentDesc||h.className]}),h.bounds.y2>t+20&&h.bounds.y1<t&&i.push({type:"OVERFLOW",severity:"WARN",description:`Element "${h.text||h.contentDesc||h.className}" overflows bottom screen boundary by ${h.bounds.y2-t}px`,elements:[h.text||h.contentDesc||h.className]}));let n=u.filter(h=>h.text&&h.text.trim().length>1&&h.bounds.width>0&&h.bounds.height>0),r=200,o=new Map;for(let h of n){let d=Math.floor(h.bounds.y1/r),g=Math.floor(h.bounds.y2/r);for(let f=d;f<=g;f++)o.has(f)||o.set(f,[]),o.get(f).push(h)}let a=new Set;for(let[,h]of o)for(let d=0;d<h.length;d++)for(let g=d+1;g<h.length;g++){let f=h[d],y=h[g];if(f===y||f.text===y.text)continue;let S=f.bounds.x1<y.bounds.x1?`${f.bounds.x1},${f.bounds.y1}:${y.bounds.x1},${y.bounds.y1}`:`${y.bounds.x1},${y.bounds.y1}:${f.bounds.x1},${f.bounds.y1}`;if(a.has(S))continue;a.add(S);let b=f.bounds,m=y.bounds;if(Math.abs(b.centerY-m.centerY)>(b.height+m.height)/2)continue;let v=Math.max(0,Math.min(b.x2,m.x2)-Math.max(b.x1,m.x1)),E=Math.max(0,Math.min(b.y2,m.y2)-Math.max(b.y1,m.y1)),k=v*E;if(k>0){let w=b.width*b.height,A=m.width*m.height,B=Math.min(w,A);B>0&&k/B>s&&i.push({type:"OVERLAP",severity:"WARN",description:`Visual text collision: "${f.text}" overlaps with "${y.text}" (${Math.round(k)}px\xB2 collision)`,elements:[f.text,y.text]})}}let l=u.filter(h=>(h.className.includes("ProgressBar")||h.className.includes("ActivityIndicator"))&&h.bounds.width>0);l.length>0&&i.push({type:"STALLED_LOADER",severity:"WARN",description:`Active loading indicator (${l[0].className}) detected on screen`,elements:l.map(h=>h.className)});let c=[],p=new Set;for(let h of i){let d=`${h.type}::${[...h.elements].sort().join("::")}`;p.has(d)||(p.add(d),c.push(h))}return c}function Yt(u,e,t){let s=e?.height||T.screen.fallbackHeight,i=e?.width||T.screen.fallbackWidth,n=Ut(u,s,t);if(n.length>1&&n[0].bounds.centerY>=s*.75)return{paradigm:"bottom_tabs",roots:n};let r=s*.05,o=s*.22,a=u.filter(c=>{if(Se(c)||t&&c.packageName&&!c.packageName.includes(t))return!1;let p=c.className.includes("Tab")||c.resourceId.toLowerCase().includes("tab")||c.resourceId.toLowerCase().includes("header_tab")||/(?:tab\s*\d|\bphotos\b|\bvideos\b|\baudios\b)/i.test(`${c.text} ${c.contentDesc}`),h=c.bounds.centerY>=r&&c.bounds.centerY<=o,d=c.bounds.height>25&&c.bounds.height<=220;return(p||h)&&c.clickable&&c.bounds.width>50&&d});if(a.length>=2){let c=[];for(let h of a){let d=c.find(g=>Math.abs(g[0].bounds.centerY-h.bounds.centerY)<=20);d||(d=[],c.push(d)),d.push(h)}let p=c.find(h=>h.length>=2);if(p){p.sort((g,f)=>g.bounds.centerX-f.bounds.centerX);let h=[];for(let g of p)h.some(f=>Math.abs(f.bounds.centerX-g.bounds.centerX)<40)||h.push(g);if(!(h.length===2&&h[0].bounds.x1<=i*.25&&h[1].bounds.x2>=i*.75&&!h.some(g=>g.className.includes("Tab")||g.resourceId.toLowerCase().includes("tab")))&&h.length>=2)return{paradigm:"top_tabs",roots:h.slice(0,5)}}}let l=Oe(u,s,i);return l?{paradigm:"drawer",roots:[l]}:{paradigm:"single_hub",roots:[]}}function Us(u,e=2){if(u.length<=e)return u;let t=[];for(let i of u){let n=t.find(r=>{let o=r[0],a=o.className===i.className,l=Math.abs(o.bounds.width-i.bounds.width)<=30,c=Math.abs(o.bounds.height-i.bounds.height)<=30,p=Math.abs(o.bounds.x1-i.bounds.x1)<=30;return a&&l&&c&&p});n||(n=[],t.push(n)),n.push(i)}let s=[];for(let i of t)s.push(...i.slice(0,e));return s}function we(u,e=T.screen.fallbackHeight,t=T.screen.fallbackWidth,s=!1){let i=e*.22,n=t*.28,r=/(?:navigate[_\s-]*up|go[_\s-]*back|^back$|\bback\b|arrow_back|ic_arrow_back|chevron[_\s-]*left|ic_back|btn_back|action_bar_up|header[_\s-]*left|prev(?:ious)?|^close$|\bclose\b|^cancel$|^dismiss$|^done$|^exit$|[<←«‹❮⟨◁◀✕✖×]|\u2190|\u2196|\u2039|\u27E8|\u276E|\u25C1|\u25C0|\u00AB|\u2715|\u2716|\u00D7|[\uF060\uF104\uF053\uF2EA\uF00D\uE5C4\uE5CD])/i,o=a=>a.bounds.width>0&&a.bounds.height>0&&a.bounds.centerY<=i;for(let a of u){if(Se(a)||!o(a))continue;let l=`${a.text||""} ${a.contentDesc||""} ${a.resourceId||""}`.trim();if(r.test(l)||l.length<=2&&/^[<‹«←x✕×\-]$/i.test(l))return a.clickable?a:u.find(p=>p.clickable&&p.bounds.x1<=a.bounds.x1&&p.bounds.x2>=a.bounds.x2&&p.bounds.y1<=a.bounds.y1&&p.bounds.y2>=a.bounds.y2&&p.bounds.width<=300&&p.bounds.height<=300)||a}for(let a of u){if(Se(a)||!o(a)||a.bounds.x1>n)continue;if(a.className.includes("ImageButton")||a.className.includes("ImageView")||a.className.includes("ViewGroup")&&a.bounds.width<=250&&a.bounds.height<=250){let c=`${a.text||""} ${a.contentDesc||""} ${a.resourceId||""}`.toLowerCase();if(c.includes("back")||c.includes("up")||c.includes("arrow")||c.includes("chevron")||c.includes("nav")||c.includes("close")||c.includes("cancel"))return a.clickable?a:u.find(h=>h.clickable&&h.bounds.x1<=a.bounds.x1&&h.bounds.x2>=a.bounds.x2&&h.bounds.y1<=a.bounds.y1&&h.bounds.y2>=a.bounds.y2)||a}}if(s){let a=u.find(l=>{if(Se(l)||!o(l)||!l.clickable)return!1;let c=l.bounds.x1<=n,p=l.bounds.width<=250&&l.bounds.height<=250;return c&&p&&l.bounds.width<t*.4});if(a)return a}return null}import Le from"fs";import Be from"path";var rt=class{outputDir;steps=[];errorsDetected=[];startTime=new Date;packageName="Unknown";deviceId="Unknown";pendingWrites=[];formats=["json","md","junit","html"];videoPath;embedScreenshots=!1;screenshotBuffers=new Map;stepListeners=[];completeListeners=[];errorListeners=[];constructor(e,t){typeof e=="object"&&e!==null?(this.outputDir=e.outputDir||Be.resolve(process.cwd(),"output"),e.formats&&e.formats.length>0&&(this.formats=e.formats),this.embedScreenshots=!!e.embedScreenshots):(this.outputDir=e||Be.resolve(process.cwd(),"output"),t&&t.length>0&&(this.formats=t)),Le.existsSync(this.outputDir)||Le.mkdirSync(this.outputDir,{recursive:!0})}setEmbedScreenshots(e){this.embedScreenshots=e}onStep(e){return this.stepListeners.push(e),()=>{let t=this.stepListeners.indexOf(e);t!==-1&&this.stepListeners.splice(t,1)}}onComplete(e){return this.completeListeners.push(e),()=>{let t=this.completeListeners.indexOf(e);t!==-1&&this.completeListeners.splice(t,1)}}onError(e){return this.errorListeners.push(e),()=>{let t=this.errorListeners.indexOf(e);t!==-1&&this.errorListeners.splice(t,1)}}setFormats(e){this.formats=e}setVideoPath(e){this.videoPath=e}init(e,t){this.packageName=e,this.deviceId=t,this.startTime=new Date,this.steps=[],this.errorsDetected=[],this.pendingWrites=[],this.videoPath=void 0,this.screenshotBuffers.clear()}clearScreenshotBuffers(){this.screenshotBuffers.clear()}logStep(e,t,s,i,n,r,o,a,l){let c=this.steps.length+1,p;if(r){this.embedScreenshots&&this.screenshotBuffers.set(c,r);let d=`step_${c}_${e.toLowerCase().replace(/[^a-z0-9]/g,"_")}.png`,g=Be.join(this.outputDir,d),f=Le.promises.writeFile(g,r).catch(y=>{console.error(`Warning: Failed to write screenshot ${d}:`,y)}).finally(()=>{let y=this.pendingWrites.indexOf(f);y!==-1&&this.pendingWrites.splice(y,1)});this.pendingWrites.push(f),p=d}let h={stepIndex:c,timestamp:new Date().toISOString(),phase:e,description:t,action:s,target:n,status:i,screenshotPath:p,durationMs:a,triageBundle:l,details:o};this.steps.push(h);for(let d of this.stepListeners)try{d(h)}catch{}return h}logError(e){this.errorsDetected.push(e);for(let t of this.errorListeners)try{t(e)}catch{}}async generateReport(e){this.pendingWrites.length>0&&await Promise.all(this.pendingWrites);let t=new Date,s=Math.round((t.getTime()-this.startTime.getTime())/1e3),i={packageName:this.packageName,deviceId:this.deviceId,startTime:this.startTime.toISOString(),endTime:t.toISOString(),durationSeconds:s,totalSteps:this.steps.length,passedSteps:this.steps.filter(r=>r.status==="PASS").length,failedSteps:this.steps.filter(r=>r.status==="FAIL").length,skippedSteps:this.steps.filter(r=>r.status==="SKIPPED").length,warnSteps:this.steps.filter(r=>r.status==="WARN").length,errorsDetected:this.errorsDetected,videoPath:this.videoPath,steps:this.steps},n=e||"prompttest";if(this.formats.includes("json")){let r=Be.join(this.outputDir,`${n}-results.json`);await Le.promises.writeFile(r,JSON.stringify(i,null,2),"utf-8")}if(this.formats.includes("md")){let r=Be.join(this.outputDir,`${n}-report.md`),o=this.formatMarkdownReport(i);await Le.promises.writeFile(r,o,"utf-8")}if(this.formats.includes("junit")){let r=Be.join(this.outputDir,`${n}-junit.xml`),o=this.formatJunitXml(i,n);await Le.promises.writeFile(r,o,"utf-8")}if(this.formats.includes("html")){let r=Be.join(this.outputDir,`${n}-report.html`),o=this.formatHtmlReport(i,n);await Le.promises.writeFile(r,o,"utf-8")}for(let r of this.completeListeners)try{r(i)}catch{}return this.clearScreenshotBuffers(),i}escapeXml(e){return(e||"").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&apos;")}escapeHtml(e){return(e||"").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#039;")}formatJunitXml(e,t){let s=e.durationSeconds,i=e.failedSteps+(e.errorsDetected.length>0&&e.failedSteps===0?1:0),n=['<?xml version="1.0" encoding="UTF-8"?>',`<testsuites name="PromptTest" tests="${e.totalSteps}" failures="${i}" skipped="${e.skippedSteps}" time="${s}">`,` <testsuite name="${this.escapeXml(t)}" tests="${e.totalSteps}" failures="${i}" skipped="${e.skippedSteps}" time="${s}">`];for(let r of e.steps){let o=`Step ${r.stepIndex}: ${this.escapeXml(r.action)} - ${this.escapeXml(r.description)}`,a=r.durationMs!==void 0?(r.durationMs/1e3).toFixed(3):"1.000";n.push(` <testcase classname="${this.escapeXml(t)}" name="${o}" time="${a}">`),r.status==="FAIL"?n.push(` <failure message="${this.escapeXml(r.description)}">${this.escapeXml(r.description)}</failure>`):r.status==="SKIPPED"&&n.push(` <skipped message="${this.escapeXml(r.description)}"/>`),n.push(" </testcase>")}return e.failedSteps===0&&e.errorsDetected.length>0&&n.push(` <testcase classname="${this.escapeXml(t)}" name="Error Sentinel Crash Detection" time="0.000">`,` <failure message="${this.escapeXml(e.errorsDetected[0])}">${this.escapeXml(e.errorsDetected.join(`
1
+ import Ce from"fs";import me from"path";import R from"chalk";import{spawn as et}from"child_process";import Bt from"readline";var ae={DEVICES:["devices","-l"],SCREENCAP:["exec-out","screencap","-p"],FOREGROUND_APP:["shell","dumpsys","window"],CURRENT_FOCUS:["shell","dumpsys","activity","activities"],FORCE_STOP:p=>["shell","am","force-stop",p],CLEAR_APP:p=>["shell","pm","clear",p],LAUNCH_APP:p=>["shell","am","start","-a","android.intent.action.MAIN","-c","android.intent.category.LAUNCHER",p],UIAUTOMATOR_DUMP:["exec-out","uiautomator","dump","--compressed","/dev/tty"],INPUT_TAP:(p,e)=>["shell","input","tap",p.toString(),e.toString()],INPUT_TEXT:p=>["shell","input","text",p],INPUT_KEY:p=>["shell","input","keyevent",p.toString()],INPUT_SWIPE:(p,e,t,s,i=300)=>["shell","input","swipe",p.toString(),e.toString(),t.toString(),s.toString(),i.toString()],LOGCAT_CRASH:p=>["shell","logcat","-d","-b","crash","-s","AndroidRuntime:E"],CLEAR_CRASH_LOGS:()=>["shell","logcat","-b","crash","-c"],GRANT_PERMISSION:(p,e)=>["shell","pm","grant",p,e.startsWith("android.permission.")?e:`android.permission.${e}`],INSTALL_APK:p=>["install","-r",p],UNINSTALL_APP:p=>["uninstall",p],DEEP_LINK:p=>["shell","am","start","-a","android.intent.action.VIEW","-d",p],TCPIP:(p=5555)=>["tcpip",p.toString()],CONNECT:p=>["connect",p],DISCONNECT:p=>p?["disconnect",p]:["disconnect"],GET_WLAN_IP:["shell","ip","-f","inet","addr","show","wlan0"]};function bi(){let p=process.env.PROMPTTEST_SETTLE_FACTOR;if(!p)return 1;let e=parseFloat(p);return isNaN(e)||e<=0?1:e}function ye(p,e=50){return Math.max(e,Math.round(p*bi()))}var E={adb:{commandTimeoutMs:2e4,binaryTimeoutMs:45e3,retryCount:2,retryBaseDelayMs:200},polling:{intervalMs:200,jitterMs:80,defaultTimeoutMs:3e3,extendedTimeoutMs:3500,hierarchyCacheTtlMs:3500,verifyCacheTtlMs:2e3},settle:{get tapMs(){return ye(500)},get backMs(){return ye(700)},get launchMs(){return ye(2500)},get stopMs(){return ye(600)},get keyboardDismissMs(){return ye(500)},get scrollMs(){return ye(350)},get toggleMs(){return ye(350)},get selectMs(){return ye(600)},get inputFocusMs(){return ye(250)},get inputClearMs(){return ye(150)},get inputDoneMs(){return ye(350)},get submitWaitMs(){return ye(1800)}},gestures:{swipeDurationMs:300,longPressDurationMs:1e3,bottomNavThresholdRatio:.88,tapTargetYRatio:.96},recorder:{staleTapTimeoutMs:3e3,asyncRefreshDelayMs:80,heartbeatIntervalMs:1500},screen:{fallbackWidth:1080,fallbackHeight:2400},visual:{overlapRatio:.2},device:{maxDeviceRetries:2,autoReconnect:!0},flow:{maxLoopIterations:50,waitUntilTimeoutMs:1e4,defaultRetryCount:3},ai:{provider:"heuristic",model:"gpt-4o-mini",selfHealing:!0,confidenceThreshold:.75,maxHealingAttempts:2,endpoint:""},memory:{staleThresholdDays:parseInt(process.env.PROMPTTEST_STALE_DAYS||"14",10),staleDecayAmount:.2,minConfidenceFloor:.2,maxHealedConfidence:.65},parser:{mode:process.env.PROMPTTEST_XML_PARSER||"regex"},safety:{mode:process.env.PROMPTTEST_SAFETY_MODE||"strict",customBlacklist:process.env.PROMPTTEST_SAFETY_BLACKLIST?process.env.PROMPTTEST_SAFETY_BLACKLIST.split(",").map(p=>p.trim()).filter(Boolean):[]},explorer:{strategy:process.env.PROMPTTEST_STRATEGY||"heuristic",maxTabs:parseInt(process.env.PROMPTTEST_MAX_TABS||"15",10),maxScreens:parseInt(process.env.PROMPTTEST_MAX_SCREENS||"30",10),maxDepth:parseInt(process.env.PROMPTTEST_MAX_DEPTH||"5",10),stepBudget:parseInt(process.env.PROMPTTEST_STEP_BUDGET||"100",10),screenshots:process.env.PROMPTTEST_SCREENSHOTS||"state-change"},locale:"en"};function ks(p=E.polling.intervalMs,e=E.polling.jitterMs){return Math.round(p+(Math.random()*2-1)*(e/2))}var Cs=(n=>(n[n.SUCCESS=0]="SUCCESS",n[n.TEST_FAILED=1]="TEST_FAILED",n[n.DEVICE_UNAVAILABLE=2]="DEVICE_UNAVAILABLE",n[n.CONFIG_ERROR=3]="CONFIG_ERROR",n[n.LOCKED=4]="LOCKED",n))(Cs||{}),Fe=class extends Error{exitCode;phase;constructor(e,t=1,s){super(e),this.name="PromptTestError",this.exitCode=t,this.phase=s,Object.setPrototypeOf(this,new.target.prototype)}},gt=class extends Fe{constructor(e,t="Device"){super(e,2,t),this.name="DeviceError"}},Ft=class extends Fe{target;candidateMatches;constructor(e,t,s,i="Locator"){super(e,1,i),this.name="LocatorError",this.target=t,this.candidateMatches=s}},_t=class extends Fe{constructor(e,t="Config"){super(e,3,t),this.name="ConfigError"}},Ot=class extends Fe{serial;constructor(e,t,s="Lock"){super(e,4,s),this.name="LockError",this.serial=t}},mt=class extends Fe{cycle;constructor(e,t,s="SpecLoader"){super(e,3,s),this.name="SpecRecursionError",this.cycle=t}};var tt=class{defaultSerial=null;cachedDimensions=new Map;inFlightHierarchies=new Map;constructor(e){e&&(this.defaultSerial=e)}setDefaultDevice(e){this.defaultSerial=e}getDefaultDevice(){return this.defaultSerial}async getScreenDimensions(e){let t=e||this.defaultSerial||"default";if(this.cachedDimensions.has(t))return this.cachedDimensions.get(t);try{let{stdout:i}=await this.execAdb(["shell","wm","size"],e),n=i.match(/(?:Physical|Override)\s*size:\s*(\d+)x(\d+)/i);if(n){let r={width:parseInt(n[1],10),height:parseInt(n[2],10)};return this.cachedDimensions.set(t,r),r}}catch{}let s={width:E.screen.fallbackWidth,height:E.screen.fallbackHeight};return this.cachedDimensions.set(t,s),s}clearScreenDimensionsCache(e){e?this.cachedDimensions.delete(e):this.cachedDimensions.clear()}async getNavigationBarHeight(e){try{let{stdout:t}=await this.execAdb(["shell","dumpsys","window","displays"],e).catch(()=>({stdout:""})),s=t.match(/(?:navigationBarHeight|navBarHeight|navigationBarFrame)[=:\s]+(\d+)/i);if(s&&parseInt(s[1],10)>0)return parseInt(s[1],10)}catch{}return 0}isGlobalAdbCommand(e){return e?["devices","connect","disconnect","version","kill-server","start-server","help"].includes(e.toLowerCase()):!0}async execAdbInternal(e,t,s=2e4){let i=t||this.defaultSerial;!i&&!this.isGlobalAdbCommand(e[0])&&(await this.ensureDefaultDevice(),i=this.defaultSerial);let n=i&&!this.isGlobalAdbCommand(e[0])?["-s",i,...e]:[...e];return new Promise((r,o)=>{let a=et("adb",n),d="",c="",l=!1,h=setTimeout(()=>{l=!0;try{a.kill("SIGKILL")}catch{}o(new Error(`ADB command timed out after ${s}ms: adb ${n.join(" ")}`))},s);a.stdout.on("data",u=>{d+=u.toString("utf-8")}),a.stderr.on("data",u=>{c+=u.toString("utf-8")}),a.on("close",u=>{clearTimeout(h),!l&&(u===0?r({stdout:d,stderr:c}):o(new Error(`ADB command failed (code ${u}): adb ${n.join(" ")}
2
+ Error: ${c}`)))}),a.on("error",u=>{clearTimeout(h),!l&&o(u)})})}async execAdb(e,t,s=E.adb.commandTimeoutMs,i=E.device.maxDeviceRetries){let n;for(let r=0;r<=i;r++)try{return await this.execAdbInternal(e,t,s)}catch(o){n=o;let a=o instanceof Error?o.message:String(o),d=a.toLowerCase(),c=d.includes("device offline")||d.includes("device not found"),l=c||d.includes("error: closed")||d.includes("timed out");if(r>=i||!l||this.isGlobalAdbCommand(e[0]))throw c?new gt(`Target Android device ${t||this.defaultSerial||""} is offline or disconnected: ${a}`):o;if(E.device.autoReconnect&&c)try{await this.execAdbInternal(["reconnect"],t,5e3).catch(()=>{})}catch{}await new Promise(h=>setTimeout(h,E.adb.retryBaseDelayMs*Math.pow(2,r+1)))}throw n||new Error(`ADB command failed after ${i} retries: ${e.join(" ")}`)}async execAdbBinary(e,t,s=45e3){let i=t||this.defaultSerial;!i&&!this.isGlobalAdbCommand(e[0])&&(await this.ensureDefaultDevice(),i=this.defaultSerial);let n=i&&!this.isGlobalAdbCommand(e[0])?["-s",i,...e]:[...e];return new Promise((r,o)=>{let a=et("adb",n),d=[],c="",l=!1,h=setTimeout(()=>{l=!0;try{a.kill("SIGKILL")}catch{}o(new Error(`ADB binary command timed out after ${s}ms: adb ${n.join(" ")}`))},s);a.stdout.on("data",u=>d.push(Buffer.from(u))),a.stderr.on("data",u=>{c+=u.toString("utf-8")}),a.on("close",u=>{clearTimeout(h),!l&&(u===0?r(Buffer.concat(d)):o(new Error(`ADB binary command failed (code ${u}): adb ${n.join(" ")}
3
+ ${c}`)))}),a.on("error",u=>{clearTimeout(h),!l&&o(u)})})}async getConnectedDevices(){let{stdout:e}=await this.execAdb(ae.DEVICES),t=e.split(`
4
+ `).map(o=>o.trim()).filter(Boolean),s=t.findIndex(o=>o.toLowerCase().includes("list of devices attached")),i=s!==-1?t.slice(s+1):t,n=[];return n=(o=>{let a=[];for(let d of o){if(!d||d.startsWith("*")||d.toLowerCase().includes("list of devices"))continue;let c=d.split(/\s+/);if(c.length>=2){let l=c[0],h=c[1],u,g;for(let f of c.slice(2))f.startsWith("model:")&&(u=f.replace("model:","")),f.startsWith("product:")&&(g=f.replace("product:",""));a.push({serial:l,state:h,model:u,product:g})}}return a})(i),n}async wakeDevice(e){try{await this.execAdb(["shell","input","keyevent","224"],e),await this.execAdb(["shell","wm","dismiss-keyguard"],e)}catch{}}async ensureDefaultDevice(e){if(e)return await this.wakeDevice(e),e;if(this.defaultSerial)return await this.wakeDevice(this.defaultSerial),this.defaultSerial;let s=(await this.getConnectedDevices()).find(i=>i.state==="device");return s&&(this.defaultSerial=s.serial,await this.wakeDevice(this.defaultSerial)),this.defaultSerial||void 0}async getDeviceModel(e){try{let{stdout:n}=await this.execAdb(["shell","getprop","ro.product.model"],e),r=n.trim();if(r)return r}catch{}let t=await this.getConnectedDevices(),s=e||this.defaultSerial;return t.find(n=>n.serial===s)?.model||s||"Android Device"}async captureScreenshot(e){return this.execAdbBinary(ae.SCREENCAP,e)}async getUiHierarchy(e){let t=e||this.defaultSerial||"default",s=this.inFlightHierarchies.get(t);if(s)return s;let i=(async()=>{try{let{stdout:n}=await this.execAdb(ae.UIAUTOMATOR_DUMP,e,1e4,0),r=n.indexOf("<hierarchy");return r>=0?n.slice(r):n}finally{this.inFlightHierarchies.delete(t)}})();return this.inFlightHierarchies.set(t,i),i}clearInFlightHierarchies(e){e?this.inFlightHierarchies.delete(e):this.inFlightHierarchies.clear()}async getForegroundPackage(e){let t=s=>{let i=s.toLowerCase();return i==="android"||i.includes("systemui")||i.includes("inputmethod")||i.includes("latin")||i.includes("gboard")||i.includes("swiftkey")||i.includes("ime")};try{let{stdout:s}=await this.execAdb(["shell","dumpsys","activity","activities"],e).catch(()=>({stdout:""})),i=s.match(/(?:topResumedActivity|mResumedActivity|ResumedActivity)[=:\s]+(?:ActivityRecord\{[^}]*?\s+)?([a-zA-Z0-9._]+)\//i);if(i&&i[1]&&!t(i[1]))return i[1];let{stdout:n}=await this.execAdb(ae.FOREGROUND_APP,e).catch(()=>({stdout:""})),r=n.matchAll(/(?:mCurrentFocus|mFocusedWindow|mFocusedApp|topResumedActivity|mResumedActivity|mFocusedActivity)[=:\s]+(?:Window\{[^}]*?\s+|ActivityRecord\{[^}]*?\s+|AppWindowToken\{[^}]*?\s+)?([a-zA-Z0-9._]+)\//gi);for(let o of r)if(o&&o[1]&&!t(o[1]))return o[1]}catch{}return null}async tap(e,t,s){await this.execAdb(ae.INPUT_TAP(e,t),s)}async inputText(e,t){let s=e.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/'/g,"\\'").replace(/%/g,"\\%").replace(/ /g,"%s").replace(/&/g,"\\&").replace(/</g,"\\<").replace(/>/g,"\\>").replace(/\(/g,"\\(").replace(/\)/g,"\\)").replace(/;/g,"\\;").replace(/\|/g,"\\|").replace(/\$/g,"\\$").replace(/#/g,"\\#").replace(/\*/g,"\\*").replace(/\?/g,"\\?").replace(/~/g,"\\~").replace(/`/g,"\\`");try{await this.execAdb(ae.INPUT_TEXT(s),t)}catch{for(let i of e)if(i===" ")await this.pressKey(62,t);else if(i==="@")await this.pressKey(77,t);else{let n=i.replace(/([\\"'&<>()|$;#*?~`%])/g,"\\$1");await this.execAdb(["shell","input","text",n],t).catch(()=>{})}}}async pressKey(e,t){await this.execAdb(ae.INPUT_KEY(e),t)}async pressEnter(e){await this.pressKey(66,e)}async pressTab(e){await this.pressKey(61,e)}async pressHome(e){await this.pressKey(3,e)}async pressBack(e){await this.pressKey(4,e)}async setWifiEnabled(e,t){await this.execAdb(["shell","svc","wifi",e?"enable":"disable"],t)}async setAirplaneMode(e,t){await this.execAdb(["shell","cmd","connectivity","airplane-mode",e?"enable":"disable"],t)}async setOrientation(e,t){await this.execAdb(["shell","content","insert","--uri","content://settings/system","--bind","name:s:accelerometer_rotation","--bind","value:i:0"],t).catch(()=>{});let s=e==="landscape"?"1":"0";await this.execAdb(["shell","settings","put","system","user_rotation",s],t)}async openNotificationShade(e){await this.execAdb(["shell","cmd","statusbar","expand-notifications"],e)}async collapseNotificationShade(e){await this.execAdb(["shell","cmd","statusbar","collapse"],e)}async clearInput(e=45,t){let s=Array(e).fill("67");await this.execAdb(["shell","input","keyevent",...s],t)}async clearField(e,t=80){await this.pressKey(123,e);let s=Math.max(50,t+10),i=Array(s).fill("67");await this.execAdb(["shell","input","keyevent",...i],e).catch(()=>{}),await this.pressKey(122,e);let n=Array(Math.max(30,Math.floor(t/2))).fill("112");await this.execAdb(["shell","input","keyevent",...n],e).catch(()=>{})}async swipe(e,t,s,i,n=300,r){await this.execAdb(ae.INPUT_SWIPE(e,t,s,i,n),r)}async launchApp(e,t){try{let{stdout:s}=await this.execAdb(["shell","cmd","package","resolve-activity","--brief",e],t),n=(s||"").split(`
5
+ `).map(r=>r.trim()).find(r=>r.includes("/")&&!r.includes(" "));if(n){await this.execAdb(["shell","am","start","-n",n],t);return}}catch{}await this.execAdb(ae.LAUNCH_APP(e),t)}async forceStop(e,t){await this.execAdb(ae.FORCE_STOP(e),t)}async clearAppData(e,t){await this.execAdb(ae.CLEAR_APP(e),t)}async restartApp(e,t){await this.forceStop(e,t),await new Promise(s=>setTimeout(s,600)),await this.launchApp(e,t)}async grantPermission(e,t,s){await this.execAdb(ae.GRANT_PERMISSION(e,t),s)}async isAppInstalled(e,t){try{let{stdout:s}=await this.execAdb(["shell","pm","list","packages",e],t);return s.toLowerCase().includes(`package:${e.toLowerCase()}`)||s.includes(e)}catch{return!1}}async installApk(e,t){await this.execAdb(ae.INSTALL_APK(e),t)}async uninstallApp(e,t){await this.execAdb(ae.UNINSTALL_APP(e),t)}async openDeepLink(e,t){await this.execAdb(ae.DEEP_LINK(e),t)}async checkCrashes(e,t){try{let{stdout:s}=await this.execAdb(ae.LOGCAT_CRASH(e),t);if(s&&s.includes("FATAL EXCEPTION")&&s.includes(e))return s}catch{}return null}async clearCrashLogs(e){try{await this.execAdb(ae.CLEAR_CRASH_LOGS(),e)}catch{}}async getDeviceIp(e){try{let{stdout:t}=await this.execAdb(ae.GET_WLAN_IP,e),s=t.match(/inet\s+(\d+\.\d+\.\d+\.\d+)/);if(s&&s[1])return s[1]}catch{}try{let{stdout:t}=await this.execAdb(["shell","ip","route"],e),s=t.match(/src\s+(\d+\.\d+\.\d+\.\d+)/);if(s&&s[1])return s[1]}catch{}return null}async connectWifi(e,t=5555,s){let i=e,n=t;if(e&&e.includes(":")){let l=e.split(":");i=l[0],n=parseInt(l[1],10)||t}if(!i){let l=await this.getDeviceIp(s);if(!l)throw new Error("Could not auto-detect phone Wi-Fi IP. Make sure the phone is on Wi-Fi, or pass IP manually: npx prompttest wifi <ip>");i=l}let r=`${i}:${n}`;if(e)try{let{stdout:l,stderr:h}=await this.execAdb(ae.CONNECT(r)),u=`${l} ${h}`.trim();if(u.toLowerCase().includes("connected")||u.toLowerCase().includes("already"))return this.defaultSerial=r,{success:!0,target:r,message:u}}catch{}try{await this.execAdb(ae.TCPIP(n),s),await new Promise(l=>setTimeout(l,1e3))}catch{}let{stdout:o,stderr:a}=await this.execAdb(ae.CONNECT(r)),d=`${o} ${a}`.trim(),c=d.toLowerCase().includes("connected")||d.toLowerCase().includes("already");return c&&(this.defaultSerial=r),{success:c,target:r,message:d}}async disconnectWifi(e){let{stdout:t,stderr:s}=await this.execAdb(ae.DISCONNECT(e));return`${t} ${s}`.trim()}streamLogcatEvents(e,t){let i=et("adb",["-s",e,"shell","logcat","-b","events","-v","time"]),n=Bt.createInterface({input:i.stdout});return n.on("line",t),i.on("close",()=>{try{n.close()}catch{}}),i.on("error",()=>{}),i}streamLogcatCrashes(e,t){let i=et("adb",["-s",e,"shell","logcat","-T","1","-s","AndroidRuntime:E","ANRManager:E","-v","time"]),n=Bt.createInterface({input:i.stdout});return n.on("line",t),i.on("close",()=>{try{n.close()}catch{}}),i.on("error",()=>{}),i}streamLogcatToasts(e,t){let i=et("adb",["-s",e,"shell","logcat","-s","Toast:D","Snackbar:D","-v","time"]),n=Bt.createInterface({input:i.stdout});return n.on("line",t),i.on("close",()=>{try{n.close()}catch{}}),i.on("error",()=>{}),i}async getLogcatTail(e=150,t){try{let{stdout:s}=await this.execAdb(["logcat","-d","-t",String(e),"-v","time"],t);return s}catch(s){return`Failed to capture logcat: ${s instanceof Error?s.message:String(s)}`}}async startScreenRecording(e="/sdcard/prompttest_temp.mp4",t){let s=t||this.defaultSerial,n=et("adb",s?["-s",s,"shell","screenrecord",e]:["shell","screenrecord",e]);return n.on("error",()=>{}),{remotePath:e,process:n}}async stopScreenRecording(e,t,s){try{try{e.process.kill("SIGINT")}catch{}return await this.execAdb(["shell","pkill","-2","screenrecord"],s).catch(()=>{}),await new Promise(i=>setTimeout(i,1500)),await this.execAdb(["pull",e.remotePath,t],s),await this.execAdb(["shell","rm","-f",e.remotePath],s).catch(()=>{}),t}catch{return""}}async isKeyboardVisible(e){try{let{stdout:t}=await this.execAdb(["shell","dumpsys","input_method"],e,4e3,0);return t.includes("mInputShown=true")||t.includes("isInputViewShown=true")||t.includes("mHasSurface=true")}catch{return!1}}async ensureAccessibilityServices(e){try{await this.execAdb(["shell","settings","put","secure","accessibility_enabled","1"],e,4e3,0)}catch{}}},he=new tt;var Ls=/^(\d+(?:\.\d+)*\.?|\-|\*)\s*/;function Rs(p){let e=p.trim(),t=e.match(/^"([^"]+)"$/);if(t)return t[1].trim();let s=e.match(/^'([^']+)'$/);return s?s[1].trim():e.replace(/^['"]+|['"]+$/g,"").trim()}var V=`(?:"([^"]+)"|'([^']+)'|([^'"\\s][^'"]*?[^'"\\s]|\\S))`;function W(p){for(let e of p)if(e!=null&&e.trim().length>0)return e.trim();return""}function Xe(p,e){let t=p;if(e)for(let[s,i]of Object.entries(e))t=t.replace(new RegExp(`\\$${s}\\b`,"g"),()=>i);return t=t.replace(/\$ENV\{([A-Z0-9_]+)\}/gi,(s,i)=>process.env[i]||""),t=t.replace(/\$RANDOM_EMAIL\b/g,()=>`test_${Date.now().toString().slice(-6)}@prompttest.io`),t=t.replace(/\$RANDOM_NAME\b/g,()=>`User_${Math.floor(1e3+Math.random()*9e3)}`),t=t.replace(/\$RANDOM_PHONE\b/g,()=>`98${Math.floor(1e7+Math.random()*9e7)}`),t=t.replace(/\$TIMESTAMP\b/g,()=>Date.now().toString()),t=t.replace(/\$UUID\b/g,()=>`${Date.now().toString(16)}-${Math.random().toString(16).substring(2,8)}`),t=t.replace(/\$RANDOM_UUID\b/g,()=>"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,s=>{let i=Math.random()*16|0;return(s==="x"?i:i&3|8).toString(16)})),t=t.replace(/\$RANDOM_CARD\b/g,()=>{let s="4532";for(let i=0;i<12;i++)s+=Math.floor(Math.random()*10);return s}),t=t.replace(/\$DATE_OFFSET\((-?\d+)\)/g,(s,i)=>{let n=parseInt(i,10)||0;return new Date(Date.now()+n*864e5).toISOString().slice(0,10)}),t=t.replace(/\$RANDOM_INT\((\d+),\s*(\d+)\)/g,(s,i,n)=>{let r=parseInt(i,10),o=parseInt(n,10);return String(Math.floor(r+Math.random()*(o-r+1)))}),t}var O={TAP:new RegExp(`^(?:tap|click|press)(?:\\s+on)?\\s+(?:button\\s+|item\\s+)?${V}$`,"i"),ORDINAL_TAP:new RegExp(`^(?:tap|click|press)(?:\\s+on)?\\s+(?:the\\s+)?(1st|2nd|3rd|4th|5th|last|first)\\s+(?:button\\s+|item\\s+)?${V}$`,"i"),PROXIMITY_TAP:new RegExp(`^(?:tap|click|press)(?:\\s+on)?\\s+${V}\\s+(?:next\\s+to|near|beside|inside|for)\\s+${V}$`,"i"),CLEAR:new RegExp(`^(?:clear|empty)(?:\\s+(?:text\\s+(?:in|of)|field|input))?\\s+${V}$`,"i"),LONG_PRESS:new RegExp(`^(?:long\\s+press|press\\s+and\\s+hold)\\s+(?:button\\s+|item\\s+)?${V}$`,"i"),TYPE:new RegExp(`^(?:type|enter|input)\\s+${V}\\s+(?:in|into)\\s+${V}$`,"i"),VERIFY:new RegExp(`^(?:verify|veryfy|check|assert|ensure)\\s+(?:that\\s+)?(?:error\\s+message\\s+|message\\s+|text\\s+|element\\s+|button\\s+|toast\\s+|my\\s+)?${V}\\s*(?:is\\s+(visible|exists|appears|enabled|disabled|not\\s+visible|hidden|absent|not\\s+present|gone))?$`,"i"),BACK:/^(?:press\s+back|go\s+back|navigate\s+back|back)$/i,SCROLL_TO:new RegExp(`^(?:scroll|swipe)(?:\\s+(down|up))?\\s+(?:to|until)\\s+${V}$`,"i"),SCROLL:/^(?:scroll|swipe)\s+(down|up)$/i,DIRECTIONAL_SWIPE:new RegExp(`^(?:swipe|scroll)\\s+(left|right|up|down)(?:\\s+on\\s+${V})?$`,"i"),TOGGLE:new RegExp(`^(?:toggle|turn\\s+(on|off)|check|uncheck)\\s+(?:checkbox\\s+|switch\\s+)?${V}$`,"i"),SELECT_DROPDOWN:new RegExp(`^(?:select|choose)\\s+${V}\\s+from\\s+${V}$`,"i"),LAUNCH_APP:new RegExp(`^(?:launch|open)\\s+(?:app\\s+)?${V}$`,"i"),RESTART_APP:new RegExp(`^(?:restart|relaunch)\\s+(?:app\\s+)?${V}$`,"i"),TERMINATE_APP:new RegExp(`^(?:terminate|close|force\\s*stop)\\s+(?:app\\s+)?(?:${V})?$`,"i"),CLEAR_DATA:new RegExp(`^(?:clear\\s+(?:app\\s+)?data\\s+(?:for\\s+)?|reset\\s+app\\s+)${V}$`,"i"),GRANT_PERMISSION:new RegExp(`^grant\\s+permissions?\\s+${V}(?:\\s+(?:to|for)\\s+${V})?$`,"i"),DEEP_LINK:new RegExp(`^(?:open\\s+deep\\s*link|navigate\\s+to\\s+url)\\s+${V}$`,"i"),WAIT:/^wait\s+(\d+)\s*(?:s|sec|seconds|ms)?$/i,WAIT_UNTIL:new RegExp(`^(?:wait\\s+until|wait\\s+for)\\s+${V}\\s+(?:(?:is\\s+)?(visible|appears?|enabled|exists))?(?:\\s+(?:up\\s+to|for)\\s+(\\d+)\\s*(s|sec|seconds|ms)?)?$`,"i"),IF_VISIBLE:new RegExp(`^if\\s+(?:(?:that\\s+)?${V}\\s+(?:is\\s+)?(visible|present|exists|appears?)|element\\s+${V}\\s+(?:is\\s+)?visible)$`,"i"),ELSE:/^else$/i,END:/^(?:end|end\s*if|end\s*loop|fi|done)$/i,LOOP:/^(?:loop|repeat)\s+(\d+)\s*(?:times)?$/i,FOR_EACH:new RegExp(`^for\\s+each\\s+(?:item\\s+)?(?:in\\s+)?${V}$`,"i"),SET_VARIABLE:/^set\s+\$([a-zA-Z0-9_]+)\s*=\s*(.+)$/i,DEVICE_WIFI:/^(?:turn\s+|set\s+)?wifi\s+(on|off|enable|disable)$/i,DEVICE_AIRPLANE:/^(?:turn\s+|set\\s+)?airplane\s*(?:mode)?\s+(on|off|enable|disable)$/i,DEVICE_ORIENTATION:/^(?:set\s+)?orientation\s+(?:to\s+)?(portrait|landscape)$/i,DEVICE_NOTIFICATIONS:/^(open|expand|pull\s+down|collapse|close)\s+notification(?:s|\s+shade)?$/i,INCLUDE_SPEC:new RegExp(`^(?:include|run_spec|subflow)\\s+${V}$`,"i"),RUN_JS:/^(?:run\s+js|eval\s+js|js)(?::|\s+)(.+)$/i,ENTER_OTP:new RegExp(`^(?:enter|input|type)\\s+(?:the\\s+)?(?:verification\\s+code|otp|2fa\\s+code|sms\\s+code)(?:\\s+just\\s+sent)?(?:\\s+(?:in|into)\\s+${V})?$`,"i"),API_REQUEST:new RegExp(`^(?:api|call\\s+api)\\s+(GET|POST|PUT|DELETE|PATCH)\\s+${V}(?:\\s+with\\s+body\\s+${V})?(?:\\s+store\\s+${V}\\s+as\\s+\\$([a-zA-Z0-9_]+))?(?:\\s+assert\\s+status\\s+(\\d+))?$`,"i"),EMAIL_ASSERT:new RegExp(`^(?:assert|verify)\\s+email\\s+to\\s+${V}\\s+with\\s+subject\\s+${V}(?:\\s+contains\\s+${V})?$`,"i"),OPTIONAL_SUFFIX:/\s*\((?:optional|if\s+present|maybe)\)\s*$/i,FALLBACK_QUOTED_TAP:/^(?:tap|click)\s+.*?['"]([^'"]+)['"]/i},ft={HIERARCHY_ROOT:/<hierarchy[^>]*>([\s\S]*?)<\/hierarchy>/i,NODE_TAG:/<node\b([^>]*?)(\/?)>|<\/node>/gi,ATTR_KEY_VALUE:/([a-zA-Z0-9_-]+)="([^"]*)"/g,BOUNDS_RECT:/\[(\d+),(\d+)\]\[(\d+),(\d+)\]/};function st(p){return(p||"").replace(/&#(\d+);/g,(e,t)=>{try{return String.fromCodePoint(parseInt(t,10))}catch{return""}}).replace(/&#x([0-9a-fA-F]+);/g,(e,t)=>{try{return String.fromCodePoint(parseInt(t,16))}catch{return""}}).replace(/&amp;/g,"&").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&quot;/g,'"').replace(/&apos;/g,"'")}function X(p){return st(p||"").trim().toLowerCase().replace(/[\u2018\u2019]/g,"'").replace(/[\u201C\u201D]/g,'"').replace(/\uFFFD/g,"").replace(new RegExp("\\p{Extended_Pictographic}","gu"),"").replace(/[\uE000-\uF8FF\uFFF0-\uFFFF]/g,"").replace(/\s+/g," ").trim()}var Is=new Map;function z(p,e){if(!p||!e)return!1;let t=X(p),s=X(e);if(t.length<=3){let i=Is.get(t);if(!i){let n=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");i=new RegExp(`(?:^|\\b)${n}(?:\\b|$)`,"i"),Is.set(t,i)}return i.test(s)}return s.includes(t)}var Ns=["sign in","signin","login","log in","submit","save","continue","next","done","send","confirm","proceed","post","rate","enter","join","apply","update"],Ms=["sign in","signin","login","log in","submit","save","next","continue","done","like","fav","favorite","star","bookmark","add","post","confirm","apply","explore","search","filter"];function yi(p,e){let t=X(p),s=X(e),i=t.length,n=s.length;if(i===0)return n;if(n===0)return i;let r=Array.from({length:n+1},(a,d)=>d),o=new Array(n+1);for(let a=1;a<=i;a++){o[0]=a;for(let c=1;c<=n;c++){let l=t[a-1]===s[c-1]?0:1;o[c]=Math.min(r[c]+1,o[c-1]+1,r[c-1]+l)}let d=r;r=o,o=d}return r[n]}function Si(p,e){let t=X(p),s=X(e);if(t===s)return 1;if(!t||!s)return 0;let i=Math.max(t.length,s.length);return 1-yi(t,s)/i}function We(p,e,t=3,s=.35){return Array.from(new Set(e.map(r=>r.trim()).filter(r=>r.length>0))).map(r=>({text:r,score:Si(p,r)})).filter(r=>r.score>=s).sort((r,o)=>o.score-r.score).slice(0,t)}function Fs(p){let e=p.match(ft.BOUNDS_RECT);if(!e)return{x1:0,y1:0,x2:0,y2:0,width:0,height:0,centerX:0,centerY:0};let t=parseInt(e[1],10),s=parseInt(e[2],10),i=parseInt(e[3],10),n=parseInt(e[4],10);return{x1:t,y1:s,x2:i,y2:n,width:i-t,height:n-s,centerX:Math.round((t+i)/2),centerY:Math.round((s+n)/2)}}function wi(p){let e=p.match(ft.HIERARCHY_ROOT);if(!e)return{root:[],flat:[]};let t=e[1],s=new RegExp(ft.NODE_TAG.source,"gi"),i=new RegExp(ft.ATTR_KEY_VALUE.source,"g"),n=[],r=[],o=[],a;for(;(a=s.exec(t))!==null;){let d=a[0],c=a[1],l=a[2]==="/";if(d.startsWith("</node>")){o.pop();continue}let h={};i.lastIndex=0;let u;for(;(u=i.exec(c))!==null;)h[u[1]]=u[2];let g={index:parseInt(h.index||"0",10),text:st(h.text||""),resourceId:h["resource-id"]||"",className:h.class||"",packageName:h.package||"",contentDesc:st(h["content-desc"]||""),bounds:Fs(h.bounds||""),clickable:h.clickable==="true",enabled:h.enabled==="true",focused:h.focused==="true",scrollable:h.scrollable==="true",password:h.password==="true",selected:h.selected==="true",checked:h.checked!==void 0?h.checked==="true":void 0,checkable:h.checkable!==void 0?h.checkable==="true":void 0,children:[]};r.push(g),o.length===0?n.push(g):o[o.length-1].children.push(g),l||o.push(g)}return{root:n,flat:r}}function vi(p){let e=[],t=[],s=[],i=p.length,n=0;for(;n<i;){let r=p.indexOf("<",n);if(r===-1)break;if(p.startsWith("<!--",r)){let S=p.indexOf("-->",r+4);n=S===-1?i:S+3;continue}if(p.startsWith("<?",r)){let S=p.indexOf("?>",r+2);n=S===-1?i:S+2;continue}if(p.startsWith("</",r)){let S=p.indexOf(">",r+2);if(S===-1)break;p.slice(r+2,S).trim()==="node"&&s.pop(),n=S+1;continue}let o=-1,a=null,d=!1;for(let S=r+1;S<i;S++){let b=p[S];if(a)b===a&&(a=null);else if(b==='"'||b==="'")a=b;else if(b===">"){o=S,p[S-1]==="/"&&(d=!0);break}}if(o===-1)break;let c=p.slice(r+1,d?o-1:o).trim();n=o+1;let l=0;for(;l<c.length&&!/\s/.test(c[l]);)l++;if(c.slice(0,l)!=="node")continue;let u={},g=l,f=c.length;for(;g<f;){for(;g<f&&/\s/.test(c[g]);)g++;if(g>=f)break;let S=g;for(;g<f&&c[g]!=="="&&!/\s/.test(c[g]);)g++;let b=c.slice(S,g);for(;g<f&&/\s/.test(c[g]);)g++;if(g>=f||c[g]!=="=")break;for(g++;g<f&&/\s/.test(c[g]);)g++;if(g>=f)break;let m=c[g];if(m==='"'||m==="'"){g++;let v=g;for(;g<f&&c[g]!==m;)g++;u[b]=c.slice(v,g),g<f&&g++}else{let v=g;for(;g<f&&!/\s/.test(c[g]);)g++;u[b]=c.slice(v,g)}}let y={index:parseInt(u.index||"0",10),text:st(u.text||""),resourceId:u["resource-id"]||"",className:u.class||"",packageName:u.package||"",contentDesc:st(u["content-desc"]||""),bounds:Fs(u.bounds||""),clickable:u.clickable==="true",enabled:u.enabled==="true",focused:u.focused==="true",scrollable:u.scrollable==="true",password:u.password==="true",selected:u.selected==="true",checked:u.checked!==void 0?u.checked==="true":void 0,checkable:u.checkable!==void 0?u.checkable==="true":void 0,children:[]};t.push(y),s.length===0?e.push(y):s[s.length-1].children.push(y),d||s.push(y)}return{root:e,flat:t}}function ue(p,e){if((e||E.parser?.mode||"regex")==="streaming")try{return vi(p)}catch{}return wi(p)}function ir(p,e){return p.filter(t=>{if(e.clickable!==void 0&&t.clickable!==e.clickable||e.className&&!t.className.includes(e.className))return!1;if(e.text){if(typeof e.text=="string"){if(!t.text.toLowerCase().includes(e.text.toLowerCase()))return!1}else if(!e.text.test(t.text))return!1}if(e.contentDesc){if(typeof e.contentDesc=="string"){if(!t.contentDesc.toLowerCase().includes(e.contentDesc.toLowerCase()))return!1}else if(!e.contentDesc.test(t.contentDesc))return!1}if(e.resourceId){if(typeof e.resourceId=="string"){if(!t.resourceId.toLowerCase().includes(e.resourceId.toLowerCase()))return!1}else if(!e.resourceId.test(t.resourceId))return!1}return!0})}var xi=[/logbox/i,/^Log \d+ of \d+/i,/Console (?:Error|Warning|Log|Info)/i,/^Call Stack$/i,/^Source Map$/i,/^(?:Dismiss|Minimize|Copy|View error log)$/i,/\b[\w-]+\.(?:tsx?|jsx?|js|ts):\d+:\d+\b/i,/Unhandled Promise Rejection/i,/SyntaxError/i,/TypeError:/i,/ReferenceError:/i,/Warning:/i,/LogBoxNotificationOverlay/i];function Se(p){if(p.resourceId&&/logbox/i.test(p.resourceId)||p.className&&/logbox/i.test(p.className))return!0;let e=`${p.text} ${p.contentDesc}`.trim();return!!xi.some(t=>t.test(e))}function _e(p){return p.filter(e=>Se(e)?!1:(e.className.includes("EditText")||e.className.includes("TextInputEditText")||e.focused&&e.clickable)&&e.bounds.width>0&&e.bounds.height>0)}function Ht(p){return p.className.includes("EditText")||p.className.includes("TextInputEditText")?!0:(p.children||[]).some(Ht)}function bt(p,e){let t=e?.width||E.screen.fallbackWidth,s=e?.height||E.screen.fallbackHeight,i=s*.08,n=s*.88,r=p.filter(a=>!Se(a)&&(a.className.includes("RecyclerView")||a.className.includes("ListView")||a.className.includes("ScrollView"))),o=[];for(let a of r)for(let d of a.children){if(Se(d)||d.bounds.centerY<i||d.bounds.centerY>n)continue;(d.clickable||d.children.some(l=>!Se(l)&&l.clickable&&l.bounds.width>t*.1))&&d.bounds.width>t*.08&&d.bounds.height>s*.02&&!Ht(d)&&o.push(d)}return o.length===0?p.filter(a=>{if(Se(a))return!1;let d=(a.text||a.contentDesc||"").trim();return d.length<=1||/^(remember me|forgot password|sign in|sign up|login|submit|cancel)$/i.test(d)?!1:a.clickable&&a.bounds.width>t*.14&&a.bounds.height>s*.033&&a.bounds.centerY>i&&a.bounds.centerY<n&&!a.className.includes("Button")&&!a.className.includes("EditText")&&!Ht(a)}):o}function Ge(p){return p.filter(e=>{if(Se(e)||!e.clickable||e.bounds.width===0||e.className.includes("EditText"))return!1;let t=e.className.includes("Button")||e.className.includes("ImageButton"),s=Ms.some(i=>z(i,e.text)||z(i,e.contentDesc)||z(i,e.resourceId));return t||s})}function Ut(p,e=E.screen.fallbackHeight,t){if(!p||p.length===0)return[];let s=p.find(u=>u.bounds.height>=e*.6&&u.bounds.y1<=e*.15),i=s?.bounds?.y1!==void 0&&s.bounds.y1>=0?s.bounds.y1:0,n=s?.bounds?.y2&&s.bounds.y2>i?s.bounds.y2:e,r=n-i,o=s?.bounds?.x2&&s.bounds.x2>0?s.bounds.x2-(s.bounds.x1||0):E.screen.fallbackWidth,a=i+r*.78,d=p.filter(u=>Se(u)||t&&u.packageName&&!u.packageName.includes(t)||!u.clickable||u.bounds.width<=0||u.bounds.height<=0||!(u.bounds.centerY>=a||u.bounds.y2>=n-20)?!1:u.bounds.width>=o*.12&&u.bounds.width<=o*.55);if(d.length<=1)return d;let c=[];for(let u of d){let g=c.find(f=>Math.abs(f[0].bounds.centerY-u.bounds.centerY)<=30||Math.abs(f[0].bounds.y2-u.bounds.y2)<=20);g||(g=[],c.push(g)),g.push(u)}let l=c.map(u=>{u.sort((f,y)=>f.bounds.centerX-y.bounds.centerX);let g=[];for(let f of u)g.some(y=>Math.abs(y.bounds.centerX-f.bounds.centerX)<o*.08)||g.push(f);return g}).filter(u=>u.length<2||u.length>6?!1:u[u.length-1].bounds.x2-u[0].bounds.x1>=o*.6);return l.length===0?d.slice(0,5):(l.sort((u,g)=>g[0].bounds.centerY-u[0].bounds.centerY),l[0].slice(0,5))}function _s(p){let e=[/fatal\s+exception/i,/unfortunately.*stopped/i,/(?:app|system|process).*(?:isn't|is not|not)\s+responding/i,/(?:isn't|is not|not)\s+responding/i,/force\s+close/i,/network\s+connection\s+(?:failed|lost|error)/i,/something went wrong/i,/(?:failed|unable)\s+to\s+(?:connect|load|fetch)/i];return p.filter(t=>{let s=`${t.text} ${t.contentDesc}`;return e.some(i=>i.test(s))})}var Ti=[/(?:\b|[_\s-])(?:log[_\s-]*out|sign[_\s-]*out)(?:\b|[_\s-])/i,/(?:\b|[_\s-])(?:delete|remove)(?:[_\s-]+(?:account|profile|all|data|item|cart|user))?(?:\b|[_\s-])/i,/(?:\b|[_\s-])(?:clear[_\s-]+data|wipe|force[_\s-]+stop|factory[_\s-]+reset|uninstall)(?:\b|[_\s-])/i,/(?:\b|[_\s-])(?:pay|purchase|checkout|buy[_\s-]+now|order[_\s-]+now)(?:\b|[_\s-])/i,/(?:\b|[_\s-])(?:exit[_\s-]*app|close[_\s-]*app|^exit$|^quit$)(?:\b|[_\s-])/i],Ei=[/(?:\b|[_\s-])(?:log[_\s-]*out|sign[_\s-]*out)(?:\b|[_\s-])/i,/(?:\b|[_\s-])(?:delete|remove)[_\s-]+(?:account|profile|user)(?:\b|[_\s-])/i,/(?:\b|[_\s-])(?:clear[_\s-]+data|wipe|force[_\s-]+stop|factory[_\s-]+reset|uninstall)(?:\b|[_\s-])/i],Pi=[/(?:\b|[_\s-])(?:rate[_\s-]*us|review[_\s-]*(?:on|in)[_\s-]*(?:play|store)|play[_\s-]*store)(?:\b|[_\s-])/i,/(?:\b|[_\s-])(?:visit[_\s-]*(?:our)?[_\s-]*website|privacy[_\s-]*policy|terms[_\s-]*of[_\s-]*service|terms[_\s-]*&[_\s-]*conditions)(?:\b|[_\s-])/i,/(?:\b|[_\s-])(?:follow[_\s-]*us|share[_\s-]*via|share[_\s-]*app|open[_\s-]*in[_\s-]*browser)(?:\b|[_\s-])/i,/^https?:\/\//i,/(?:www\.[a-z0-9-]+\.[a-z]{2,})/i];function Ee(p,e,t=E.safety?.mode||"strict"){if(t==="disabled")return!1;let s=`${p.text} ${p.contentDesc} ${p.resourceId}`.trim();if((t==="moderate"?Ei:Ti).some(r=>r.test(s)))return!0;let n=e||E.safety?.customBlacklist||[];for(let r of n)if(typeof r=="string"&&r.length>0){if(s.toLowerCase().includes(r.toLowerCase()))return!0}else if(r instanceof RegExp&&r.test(s))return!0;return!1}function Pe(p){let e=`${p.text} ${p.contentDesc} ${p.resourceId}`.trim();return Pi.some(t=>t.test(e))}function yt(p){for(let e of p){let t=`${e.text} ${e.contentDesc} ${e.resourceId}`;if(e.resourceId.toLowerCase().includes("logbox")||t.includes("Unhandled Promise Rejection")||t.includes("SyntaxError")||t.includes("Encountered two children with the same key")||t.includes("Warning:")||t.includes("Console Error")||t.includes("Console Warning")||t.includes("Console Info")||t.includes("TypeError:")||t.includes("ReferenceError:")||/Log \d+ of \d+/i.test(t)||t.includes("LogBox")&&(e.className.includes("Modal")||e.className.includes("ViewGroup"))){let i="error";/warning/i.test(t)?i="warning":/info/i.test(t)&&(i="info");let n=e.resourceId.includes("notification")||e.bounds.height>0&&e.bounds.height<250,r,o=[];for(let c of p){let l=`${c.text} ${c.contentDesc}`.trim();if(!r){let h=l.match(/\b([a-zA-Z0-9_.-]+\.(?:tsx?|jsx?|js|ts):\d+:\d+)\b/);h&&(r=h[1])}/\b(?:at\s+|\()?[a-zA-Z0-9_.-]+\.(?:tsx?|jsx?|js|ts):\d+/i.test(l)&&!o.includes(l)&&l.length<200&&o.push(l)}let a=p.find(c=>c.clickable&&c.bounds.width>0&&(/^(?:dismiss|close)$/i.test((c.text||"").trim())||/^(?:dismiss|close)$/i.test((c.contentDesc||"").trim())));if(!a&&!n){let l=p.filter(h=>h.clickable&&h.bounds.width>0&&h.bounds.height>0&&!/minimize|copy/i.test(`${h.text} ${h.contentDesc}`)).filter(h=>h.bounds.centerY>E.screen.fallbackHeight*.8);l.length>0&&(l.sort((h,u)=>h.bounds.x1-u.bounds.x1),a=l[0])}!a&&n&&(a=p.find(c=>c.clickable&&c.bounds.y1>=e.bounds.y1-20&&c.bounds.y2<=e.bounds.y2+20&&c.bounds.x1>=e.bounds.x2-120));let d=e.text||e.contentDesc||"React Native LogBox Console Overlay";return{type:"logbox",severity:i,node:e,errorText:d,sourceLocation:r,stackTrace:o.length>0?o:void 0,dismissButton:a,isToast:n}}if(e.resourceId.includes("alertTitle")&&(t.includes("isn't responding")||t.includes("has stopped"))){let i=p.find(n=>n.text.toLowerCase().includes("close app")||n.text.toLowerCase().includes("ok"));return{type:"anr",severity:"error",node:e,errorText:e.text||"Application Not Responding (ANR)",dismissButton:i}}}return null}function it(p){return p.filter(e=>Se(e)?!1:(e.checkable||e.className.includes("CheckBox")||e.className.includes("Switch")||e.className.includes("RadioButton")||e.className.includes("SwitchCompat"))&&e.bounds.width>0&&e.bounds.height>0)}function Oe(p,e=E.screen.fallbackHeight,t=E.screen.fallbackWidth){let s=e*.22,i=/(?:menu|hamburger|drawer|navigation|\u2630|open[_\s-]*drawer)/i,n=p.find(r=>{if(!r.clickable||r.bounds.width===0||r.bounds.centerY>s)return!1;let o=`${r.contentDesc} ${r.text} ${r.resourceId}`;return i.test(o)});return n||p.find(r=>{if(!r.clickable||r.bounds.width===0||r.bounds.height===0||r.bounds.centerY>s||(r.text||r.contentDesc||"").trim().length>0)return!1;let a=r.bounds.x1<=t*.25,d=r.bounds.width<=250&&r.bounds.height<=250;return a&&d})||null}function Os(p,e=E.screen.fallbackHeight,t=E.screen.fallbackWidth){let s=e*.22;return p.filter(i=>{if(!i.clickable||i.bounds.width===0||i.bounds.height===0||i.bounds.centerY>s)return!1;let n=i.bounds.x2>=t*.75,r=i.bounds.width<=250&&i.bounds.height<=250;return n&&r})}function Bs(p){return p.filter(e=>{if(e.bounds.width===0||e.bounds.height===0)return!1;let t=e.className.includes("ScrollView")||e.className.includes("RecyclerView")||e.className.includes("ListView")||e.className.includes("NestedScrollView");return e.scrollable||t})}function Hs(p,e=E.screen.fallbackWidth,t=E.screen.fallbackHeight,s=E.visual.overlapRatio){let i=[];for(let h of p)(h.text||h.clickable)&&h.bounds.width>0&&(h.bounds.x2>e+10&&h.bounds.x1<e&&i.push({type:"OVERFLOW",severity:"WARN",description:`Element "${h.text||h.contentDesc||h.className}" overflows right screen boundary by ${h.bounds.x2-e}px`,elements:[h.text||h.contentDesc||h.className]}),h.bounds.y2>t+20&&h.bounds.y1<t&&i.push({type:"OVERFLOW",severity:"WARN",description:`Element "${h.text||h.contentDesc||h.className}" overflows bottom screen boundary by ${h.bounds.y2-t}px`,elements:[h.text||h.contentDesc||h.className]}));let n=p.filter(h=>h.text&&h.text.trim().length>1&&h.bounds.width>0&&h.bounds.height>0),r=200,o=new Map;for(let h of n){let u=Math.floor(h.bounds.y1/r),g=Math.floor(h.bounds.y2/r);for(let f=u;f<=g;f++)o.has(f)||o.set(f,[]),o.get(f).push(h)}let a=new Set;for(let[,h]of o)for(let u=0;u<h.length;u++)for(let g=u+1;g<h.length;g++){let f=h[u],y=h[g];if(f===y||f.text===y.text)continue;let S=f.bounds.x1<y.bounds.x1?`${f.bounds.x1},${f.bounds.y1}:${y.bounds.x1},${y.bounds.y1}`:`${y.bounds.x1},${y.bounds.y1}:${f.bounds.x1},${f.bounds.y1}`;if(a.has(S))continue;a.add(S);let b=f.bounds,m=y.bounds;if(Math.abs(b.centerY-m.centerY)>(b.height+m.height)/2)continue;let v=Math.max(0,Math.min(b.x2,m.x2)-Math.max(b.x1,m.x1)),x=Math.max(0,Math.min(b.y2,m.y2)-Math.max(b.y1,m.y1)),D=v*x;if(D>0){let w=b.width*b.height,A=m.width*m.height,B=Math.min(w,A);B>0&&D/B>s&&i.push({type:"OVERLAP",severity:"WARN",description:`Visual text collision: "${f.text}" overlaps with "${y.text}" (${Math.round(D)}px\xB2 collision)`,elements:[f.text,y.text]})}}let d=p.filter(h=>(h.className.includes("ProgressBar")||h.className.includes("ActivityIndicator"))&&h.bounds.width>0);d.length>0&&i.push({type:"STALLED_LOADER",severity:"WARN",description:`Active loading indicator (${d[0].className}) detected on screen`,elements:d.map(h=>h.className)});let c=[],l=new Set;for(let h of i){let u=`${h.type}::${[...h.elements].sort().join("::")}`;l.has(u)||(l.add(u),c.push(h))}return c}function Yt(p,e,t){let s=e?.height||E.screen.fallbackHeight,i=e?.width||E.screen.fallbackWidth,n=Ut(p,s,t);if(n.length>1&&n[0].bounds.centerY>=s*.75)return{paradigm:"bottom_tabs",roots:n};let r=s*.05,o=s*.22,a=p.filter(c=>{if(Se(c)||t&&c.packageName&&!c.packageName.includes(t))return!1;let l=c.className.includes("Tab")||c.resourceId.toLowerCase().includes("tab")||c.resourceId.toLowerCase().includes("header_tab")||/(?:tab\s*\d|\bphotos\b|\bvideos\b|\baudios\b)/i.test(`${c.text} ${c.contentDesc}`),h=c.bounds.centerY>=r&&c.bounds.centerY<=o,u=c.bounds.height>25&&c.bounds.height<=220;return(l||h)&&c.clickable&&c.bounds.width>50&&u});if(a.length>=2){let c=[];for(let h of a){let u=c.find(g=>Math.abs(g[0].bounds.centerY-h.bounds.centerY)<=20);u||(u=[],c.push(u)),u.push(h)}let l=c.find(h=>h.length>=2);if(l){l.sort((g,f)=>g.bounds.centerX-f.bounds.centerX);let h=[];for(let g of l)h.some(f=>Math.abs(f.bounds.centerX-g.bounds.centerX)<40)||h.push(g);if(!(h.length===2&&h[0].bounds.x1<=i*.25&&h[1].bounds.x2>=i*.75&&!h.some(g=>g.className.includes("Tab")||g.resourceId.toLowerCase().includes("tab")))&&h.length>=2)return{paradigm:"top_tabs",roots:h.slice(0,5)}}}let d=Oe(p,s,i);return d?{paradigm:"drawer",roots:[d]}:{paradigm:"single_hub",roots:[]}}function Us(p,e=2){if(p.length<=e)return p;let t=[];for(let i of p){let n=t.find(r=>{let o=r[0],a=o.className===i.className,d=Math.abs(o.bounds.width-i.bounds.width)<=30,c=Math.abs(o.bounds.height-i.bounds.height)<=30,l=Math.abs(o.bounds.x1-i.bounds.x1)<=30;return a&&d&&c&&l});n||(n=[],t.push(n)),n.push(i)}let s=[];for(let i of t)s.push(...i.slice(0,e));return s}function we(p,e=E.screen.fallbackHeight,t=E.screen.fallbackWidth,s=!1){let i=e*.22,n=t*.28,r=/(?:navigate[_\s-]*up|go[_\s-]*back|^back$|\bback\b|arrow_back|ic_arrow_back|chevron[_\s-]*left|ic_back|btn_back|action_bar_up|header[_\s-]*left|prev(?:ious)?|^close$|\bclose\b|^cancel$|^dismiss$|^done$|^exit$|[<←«‹❮⟨◁◀✕✖×]|\u2190|\u2196|\u2039|\u27E8|\u276E|\u25C1|\u25C0|\u00AB|\u2715|\u2716|\u00D7|[\uF060\uF104\uF053\uF2EA\uF00D\uE5C4\uE5CD])/i,o=a=>a.bounds.width>0&&a.bounds.height>0&&a.bounds.centerY<=i;for(let a of p){if(Se(a)||!o(a))continue;let d=`${a.text||""} ${a.contentDesc||""} ${a.resourceId||""}`.trim();if(r.test(d)||d.length<=2&&/^[<‹«←x✕×\-]$/i.test(d))return a.clickable?a:p.find(l=>l.clickable&&l.bounds.x1<=a.bounds.x1&&l.bounds.x2>=a.bounds.x2&&l.bounds.y1<=a.bounds.y1&&l.bounds.y2>=a.bounds.y2&&l.bounds.width<=300&&l.bounds.height<=300)||a}for(let a of p){if(Se(a)||!o(a)||a.bounds.x1>n)continue;if(a.className.includes("ImageButton")||a.className.includes("ImageView")||a.className.includes("ViewGroup")&&a.bounds.width<=250&&a.bounds.height<=250){let c=`${a.text||""} ${a.contentDesc||""} ${a.resourceId||""}`.toLowerCase();if(c.includes("back")||c.includes("up")||c.includes("arrow")||c.includes("chevron")||c.includes("nav")||c.includes("close")||c.includes("cancel"))return a.clickable?a:p.find(h=>h.clickable&&h.bounds.x1<=a.bounds.x1&&h.bounds.x2>=a.bounds.x2&&h.bounds.y1<=a.bounds.y1&&h.bounds.y2>=a.bounds.y2)||a}}if(s){let a=p.find(d=>{if(Se(d)||!o(d)||!d.clickable)return!1;let c=d.bounds.x1<=n,l=d.bounds.width<=250&&d.bounds.height<=250;return c&&l&&d.bounds.width<t*.4});if(a)return a}return null}import Le from"fs";import Be from"path";var rt=class{outputDir;steps=[];errorsDetected=[];startTime=new Date;packageName="Unknown";deviceId="Unknown";pendingWrites=[];formats=["json","md","junit","html"];videoPath;embedScreenshots=!1;screenshotBuffers=new Map;stepListeners=[];completeListeners=[];errorListeners=[];constructor(e,t){typeof e=="object"&&e!==null?(this.outputDir=e.outputDir||Be.resolve(process.cwd(),"output"),e.formats&&e.formats.length>0&&(this.formats=e.formats),this.embedScreenshots=!!e.embedScreenshots):(this.outputDir=e||Be.resolve(process.cwd(),"output"),t&&t.length>0&&(this.formats=t)),Le.existsSync(this.outputDir)||Le.mkdirSync(this.outputDir,{recursive:!0})}setEmbedScreenshots(e){this.embedScreenshots=e}onStep(e){return this.stepListeners.push(e),()=>{let t=this.stepListeners.indexOf(e);t!==-1&&this.stepListeners.splice(t,1)}}onComplete(e){return this.completeListeners.push(e),()=>{let t=this.completeListeners.indexOf(e);t!==-1&&this.completeListeners.splice(t,1)}}onError(e){return this.errorListeners.push(e),()=>{let t=this.errorListeners.indexOf(e);t!==-1&&this.errorListeners.splice(t,1)}}setFormats(e){this.formats=e}setVideoPath(e){this.videoPath=e}init(e,t){this.packageName=e,this.deviceId=t,this.startTime=new Date,this.steps=[],this.errorsDetected=[],this.pendingWrites=[],this.videoPath=void 0,this.screenshotBuffers.clear()}clearScreenshotBuffers(){this.screenshotBuffers.clear()}logStep(e,t,s,i,n,r,o,a,d){let c=this.steps.length+1,l;if(r){this.embedScreenshots&&this.screenshotBuffers.set(c,r);let u=`step_${c}_${e.toLowerCase().replace(/[^a-z0-9]/g,"_")}.png`,g=Be.join(this.outputDir,u),f=Le.promises.writeFile(g,r).catch(y=>{console.error(`Warning: Failed to write screenshot ${u}:`,y)}).finally(()=>{let y=this.pendingWrites.indexOf(f);y!==-1&&this.pendingWrites.splice(y,1)});this.pendingWrites.push(f),l=u}let h={stepIndex:c,timestamp:new Date().toISOString(),phase:e,description:t,action:s,target:n,status:i,screenshotPath:l,durationMs:a,triageBundle:d,details:o};this.steps.push(h);for(let u of this.stepListeners)try{u(h)}catch{}return h}logError(e){this.errorsDetected.push(e);for(let t of this.errorListeners)try{t(e)}catch{}}async generateReport(e){this.pendingWrites.length>0&&await Promise.all(this.pendingWrites);let t=new Date,s=Math.round((t.getTime()-this.startTime.getTime())/1e3),i={packageName:this.packageName,deviceId:this.deviceId,startTime:this.startTime.toISOString(),endTime:t.toISOString(),durationSeconds:s,totalSteps:this.steps.length,passedSteps:this.steps.filter(r=>r.status==="PASS").length,failedSteps:this.steps.filter(r=>r.status==="FAIL").length,skippedSteps:this.steps.filter(r=>r.status==="SKIPPED").length,warnSteps:this.steps.filter(r=>r.status==="WARN").length,errorsDetected:this.errorsDetected,videoPath:this.videoPath,steps:this.steps},n=e||"prompttest";if(this.formats.includes("json")){let r=Be.join(this.outputDir,`${n}-results.json`);await Le.promises.writeFile(r,JSON.stringify(i,null,2),"utf-8")}if(this.formats.includes("md")){let r=Be.join(this.outputDir,`${n}-report.md`),o=this.formatMarkdownReport(i);await Le.promises.writeFile(r,o,"utf-8")}if(this.formats.includes("junit")){let r=Be.join(this.outputDir,`${n}-junit.xml`),o=this.formatJunitXml(i,n);await Le.promises.writeFile(r,o,"utf-8")}if(this.formats.includes("html")){let r=Be.join(this.outputDir,`${n}-report.html`),o=this.formatHtmlReport(i,n);await Le.promises.writeFile(r,o,"utf-8")}for(let r of this.completeListeners)try{r(i)}catch{}return this.clearScreenshotBuffers(),i}escapeXml(e){return(e||"").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&apos;")}escapeHtml(e){return(e||"").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#039;")}formatJunitXml(e,t){let s=e.durationSeconds,i=e.failedSteps+(e.errorsDetected.length>0&&e.failedSteps===0?1:0),n=['<?xml version="1.0" encoding="UTF-8"?>',`<testsuites name="PromptTest" tests="${e.totalSteps}" failures="${i}" skipped="${e.skippedSteps}" time="${s}">`,` <testsuite name="${this.escapeXml(t)}" tests="${e.totalSteps}" failures="${i}" skipped="${e.skippedSteps}" time="${s}">`];for(let r of e.steps){let o=`Step ${r.stepIndex}: ${this.escapeXml(r.action)} - ${this.escapeXml(r.description)}`,a=r.durationMs!==void 0?(r.durationMs/1e3).toFixed(3):"1.000";n.push(` <testcase classname="${this.escapeXml(t)}" name="${o}" time="${a}">`),r.status==="FAIL"?n.push(` <failure message="${this.escapeXml(r.description)}">${this.escapeXml(r.description)}</failure>`):r.status==="SKIPPED"&&n.push(` <skipped message="${this.escapeXml(r.description)}"/>`),n.push(" </testcase>")}return e.failedSteps===0&&e.errorsDetected.length>0&&n.push(` <testcase classname="${this.escapeXml(t)}" name="Error Sentinel Crash Detection" time="0.000">`,` <failure message="${this.escapeXml(e.errorsDetected[0])}">${this.escapeXml(e.errorsDetected.join(`
6
6
  `))}</failure>`," </testcase>"),n.push(" </testsuite>"),n.push("</testsuites>"),n.join(`
7
- `)}formatMarkdownReport(e){let i=["# \u{1F9EA} PromptTest Autonomous Mobile QA Audit Report","",`**Status:** ${e.failedSteps===0&&e.errorsDetected.length===0?"\u2705 ALL PASSED":"\u26A0\uFE0F ISSUES DETECTED"} `,`**Target Package:** \`${e.packageName}\` `,`**Device:** \`${e.deviceId}\` `,`**Execution Time:** ${e.durationSeconds}s (${e.startTime} to ${e.endTime}) `];if(e.videoPath&&i.push(`**Screen Recording:** [Download Video](./${e.videoPath}) `),i.push("","---","","## \u{1F4CA} Executive Summary","","| Metric | Count |","|---|---|",`| **Total Steps** | ${e.totalSteps} |`,`| **Passed** | \u{1F7E2} ${e.passedSteps} |`,`| **Warnings** | \u{1F7E1} ${e.warnSteps} |`,`| **Failures** | \u{1F534} ${e.failedSteps} |`,`| **Skipped** | \u26AA ${e.skippedSteps} |`,`| **Errors Detected** | ${e.errorsDetected.length} |`,""),e.errorsDetected.length>0){i.push("## \u26A0\uFE0F Errors & Sentinels Flagged");for(let r of e.errorsDetected)i.push(`- \u{1F534} \`${r}\``);i.push("")}i.push("## \u{1F50D} Detailed Execution Timeline"),i.push(""),i.push("| Step | Phase | Action | Target / Details | Status | Duration | Screenshot / Triage |"),i.push("|---|---|---|---|---|---|---|");let n=r=>(r||"").replace(/\|/g,"\\|").replace(/\r?\n/g," ");for(let r of e.steps){let o="\u2014";r.triageBundle?o=`[\u{1F50D} Triage Bundle](./${r.triageBundle})`:r.screenshotPath&&(o=`[\u{1F4F8} Screenshot](./${r.screenshotPath})`);let a=r.durationMs!==void 0?`${r.durationMs}ms`:"\u2014",l=r.status==="PASS"?"\u{1F7E2} PASS":r.status==="WARN"?"\u{1F7E1} WARN":r.status==="SKIPPED"?"\u26AA SKIPPED":"\u{1F534} FAIL";i.push(`| ${r.stepIndex} | ${n(r.phase)} | ${n(r.action)} | ${n(r.description)} | ${l} | ${a} | ${o} |`)}return i.push(""),i.push("---"),i.push("*Generated autonomously by PromptTest Mobile QA Brain.*"),i.join(`
8
- `)}resolveScreenshotData(e){if(e.screenshotPath){if(this.embedScreenshots){if(this.screenshotBuffers.has(e.stepIndex))return`data:image/png;base64,${this.screenshotBuffers.get(e.stepIndex).toString("base64")}`;let t=Be.join(this.outputDir,e.screenshotPath);if(Le.existsSync(t))try{return`data:image/png;base64,${Le.readFileSync(t).toString("base64")}`}catch{}}return`./${e.screenshotPath}`}}formatHtmlReport(e,t){return jt(e,{suiteName:t,embedScreenshots:this.embedScreenshots,screenshotResolver:s=>this.resolveScreenshotData(s)})}};function jt(u,e){let t=e?.suiteName||"PromptTest Suite",s=u.failedSteps===0&&u.errorsDetected.length===0,i=s?"ALL PASSED":"ISSUES DETECTED",n=s?"#10b981":"#ef4444",r=u.totalSteps,o=r>0?Math.round(u.passedSteps/r*100):100,a=d=>(d||"").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#039;"),l=[],c=u.steps.map(d=>{let g=d.status.toLowerCase(),f=d.durationMs!==void 0?`${d.durationMs}ms`:"\u2014",y=e?.screenshotResolver?e.screenshotResolver(d):d.screenshotPath?`./${d.screenshotPath}`:void 0;y&&l.push({stepIndex:d.stepIndex,action:d.action,description:d.description,status:d.status,src:y,durationMs:d.durationMs});let S="\u2014";if(d.triageBundle){let E=a(d.triageBundle);S=`
7
+ `)}formatMarkdownReport(e){let i=["# \u{1F9EA} PromptTest Autonomous Mobile QA Audit Report","",`**Status:** ${e.failedSteps===0&&e.errorsDetected.length===0?"\u2705 ALL PASSED":"\u26A0\uFE0F ISSUES DETECTED"} `,`**Target Package:** \`${e.packageName}\` `,`**Device:** \`${e.deviceId}\` `,`**Execution Time:** ${e.durationSeconds}s (${e.startTime} to ${e.endTime}) `];if(e.videoPath&&i.push(`**Screen Recording:** [Download Video](./${e.videoPath}) `),i.push("","---","","## \u{1F4CA} Executive Summary","","| Metric | Count |","|---|---|",`| **Total Steps** | ${e.totalSteps} |`,`| **Passed** | \u{1F7E2} ${e.passedSteps} |`,`| **Warnings** | \u{1F7E1} ${e.warnSteps} |`,`| **Failures** | \u{1F534} ${e.failedSteps} |`,`| **Skipped** | \u26AA ${e.skippedSteps} |`,`| **Errors Detected** | ${e.errorsDetected.length} |`,""),e.errorsDetected.length>0){i.push("## \u26A0\uFE0F Errors & Sentinels Flagged");for(let r of e.errorsDetected)i.push(`- \u{1F534} \`${r}\``);i.push("")}i.push("## \u{1F50D} Detailed Execution Timeline"),i.push(""),i.push("| Step | Phase | Action | Target / Details | Status | Duration | Screenshot / Triage |"),i.push("|---|---|---|---|---|---|---|");let n=r=>(r||"").replace(/\|/g,"\\|").replace(/\r?\n/g," ");for(let r of e.steps){let o="\u2014";r.triageBundle?o=`[\u{1F50D} Triage Bundle](./${r.triageBundle})`:r.screenshotPath&&(o=`[\u{1F4F8} Screenshot](./${r.screenshotPath})`);let a=r.durationMs!==void 0?`${r.durationMs}ms`:"\u2014",d=r.status==="PASS"?"\u{1F7E2} PASS":r.status==="WARN"?"\u{1F7E1} WARN":r.status==="SKIPPED"?"\u26AA SKIPPED":"\u{1F534} FAIL";i.push(`| ${r.stepIndex} | ${n(r.phase)} | ${n(r.action)} | ${n(r.description)} | ${d} | ${a} | ${o} |`)}return i.push(""),i.push("---"),i.push("*Generated autonomously by PromptTest Mobile QA Brain.*"),i.join(`
8
+ `)}resolveScreenshotData(e){if(e.screenshotPath){if(this.embedScreenshots){if(this.screenshotBuffers.has(e.stepIndex))return`data:image/png;base64,${this.screenshotBuffers.get(e.stepIndex).toString("base64")}`;let t=Be.join(this.outputDir,e.screenshotPath);if(Le.existsSync(t))try{return`data:image/png;base64,${Le.readFileSync(t).toString("base64")}`}catch{}}return`./${e.screenshotPath}`}}formatHtmlReport(e,t){return jt(e,{suiteName:t,embedScreenshots:this.embedScreenshots,screenshotResolver:s=>this.resolveScreenshotData(s)})}};function jt(p,e){let t=e?.suiteName||"PromptTest Suite",s=p.failedSteps===0&&p.errorsDetected.length===0,i=s?"ALL PASSED":"ISSUES DETECTED",n=s?"#10b981":"#ef4444",r=p.totalSteps,o=r>0?Math.round(p.passedSteps/r*100):100,a=u=>(u||"").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#039;"),d=[],c=p.steps.map(u=>{let g=u.status.toLowerCase(),f=u.durationMs!==void 0?`${u.durationMs}ms`:"\u2014",y=e?.screenshotResolver?e.screenshotResolver(u):u.screenshotPath?`./${u.screenshotPath}`:void 0;y&&d.push({stepIndex:u.stepIndex,action:u.action,description:u.description,status:u.status,src:y,durationMs:u.durationMs});let S="\u2014";if(u.triageBundle){let x=a(u.triageBundle);S=`
9
9
  <div class="triage-bundle-links">
10
- <a class="btn-triage" href="./${E}" target="_blank" title="Open Failure Triage Directory">\u{1F50D} Triage Bundle</a>
10
+ <a class="btn-triage" href="./${x}" target="_blank" title="Open Failure Triage Directory">\u{1F50D} Triage Bundle</a>
11
11
  <div class="triage-files">
12
- <a href="./${E}/screenshot.png" target="_blank" class="mini-link">\u{1F4F8} Shot</a>
13
- <a href="./${E}/hierarchy.xml" target="_blank" class="mini-link">\u{1F4C4} XML</a>
14
- <a href="./${E}/logcat_tail.log" target="_blank" class="mini-link">\u{1F4DC} Logcat</a>
15
- <a href="./${E}/match_scores.json" target="_blank" class="mini-link">\u{1F3AF} Scores</a>
12
+ <a href="./${x}/screenshot.png" target="_blank" class="mini-link">\u{1F4F8} Shot</a>
13
+ <a href="./${x}/hierarchy.xml" target="_blank" class="mini-link">\u{1F4C4} XML</a>
14
+ <a href="./${x}/logcat_tail.log" target="_blank" class="mini-link">\u{1F4DC} Logcat</a>
15
+ <a href="./${x}/match_scores.json" target="_blank" class="mini-link">\u{1F3AF} Scores</a>
16
16
  </div>
17
17
  </div>`}else y&&(S=`
18
18
  <div class="screenshot-cell">
19
- <img src="${y}" class="thumb" alt="Step ${d.stepIndex}" onclick="openLightboxByStep(${d.stepIndex})" title="Click to view in full-screen Lightbox"/>
20
- <button class="btn-zoom" onclick="openLightboxByStep(${d.stepIndex})" title="Enlarge Screenshot">\u{1F50D}</button>
21
- </div>`);let b="";if(d.details&&(typeof d.details.diffPercent=="number"||d.details.diffPath||d.details.baselinePath)){let E=typeof d.details.diffPercent=="number"?`${(d.details.diffPercent*100).toFixed(2)}%`:"N/A",k=typeof d.details.threshold=="number"?`${(d.details.threshold*100).toFixed(2)}%`:"2.00%";b=`
19
+ <img src="${y}" class="thumb" alt="Step ${u.stepIndex}" onclick="openLightboxByStep(${u.stepIndex})" title="Click to view in full-screen Lightbox"/>
20
+ <button class="btn-zoom" onclick="openLightboxByStep(${u.stepIndex})" title="Enlarge Screenshot">\u{1F50D}</button>
21
+ </div>`);let b="";if(u.details&&(typeof u.details.diffPercent=="number"||u.details.diffPath||u.details.baselinePath)){let x=typeof u.details.diffPercent=="number"?`${(u.details.diffPercent*100).toFixed(2)}%`:"N/A",D=typeof u.details.threshold=="number"?`${(u.details.threshold*100).toFixed(2)}%`:"2.00%";b=`
22
22
  <div class="diff-viewer-card">
23
23
  <div class="diff-header">
24
- <span class="badge diff-badge">Visual Diff: ${a(E)}</span>
25
- <span class="diff-meta">Threshold: ${a(k)}</span>
24
+ <span class="badge diff-badge">Visual Diff: ${a(x)}</span>
25
+ <span class="diff-meta">Threshold: ${a(D)}</span>
26
26
  </div>
27
27
  <div class="diff-grid">
28
- ${d.details.baselinePath?`<div class="diff-pane"><div class="pane-label">Baseline</div><img src="./${a(String(d.details.baselinePath))}" class="diff-thumb" onclick="openLightboxCustom('./${a(String(d.details.baselinePath))}', 'Baseline Screenshot')"/></div>`:""}
28
+ ${u.details.baselinePath?`<div class="diff-pane"><div class="pane-label">Baseline</div><img src="./${a(String(u.details.baselinePath))}" class="diff-thumb" onclick="openLightboxCustom('./${a(String(u.details.baselinePath))}', 'Baseline Screenshot')"/></div>`:""}
29
29
  ${y?`<div class="diff-pane"><div class="pane-label">Actual Screen</div><img src="${y}" class="diff-thumb" onclick="openLightboxCustom('${y}', 'Actual Screenshot')"/></div>`:""}
30
- ${d.details.diffPath?`<div class="diff-pane"><div class="pane-label">Pixel Diff Overlay</div><img src="./${a(String(d.details.diffPath))}" class="diff-thumb" onclick="openLightboxCustom('./${a(String(d.details.diffPath))}', 'Visual Difference Overlay')"/></div>`:""}
30
+ ${u.details.diffPath?`<div class="diff-pane"><div class="pane-label">Pixel Diff Overlay</div><img src="./${a(String(u.details.diffPath))}" class="diff-thumb" onclick="openLightboxCustom('./${a(String(u.details.diffPath))}', 'Visual Difference Overlay')"/></div>`:""}
31
31
  </div>
32
- </div>`}let m="";d.details&&Object.keys(d.details).length>0&&(m=`
32
+ </div>`}let m="";u.details&&Object.keys(u.details).length>0&&(m=`
33
33
  <details class="step-details">
34
34
  <summary>Diagnostics &amp; Context</summary>
35
- <pre>${a(JSON.stringify(d.details,null,2))}</pre>
36
- </details>`);let v=`${d.stepIndex} ${d.phase} ${d.action} ${d.description} ${d.target||""}`.toLowerCase();return`
35
+ <pre>${a(JSON.stringify(u.details,null,2))}</pre>
36
+ </details>`);let v=`${u.stepIndex} ${u.phase} ${u.action} ${u.description} ${u.target||""}`.toLowerCase();return`
37
37
  <tr class="step-row status-${g}" data-status="${g}" data-search="${a(v)}">
38
- <td class="col-num">${d.stepIndex}</td>
39
- <td><span class="badge phase-badge">${a(d.phase)}</span></td>
40
- <td><span class="badge action-badge">${a(d.action)}</span></td>
38
+ <td class="col-num">${u.stepIndex}</td>
39
+ <td><span class="badge phase-badge">${a(u.phase)}</span></td>
40
+ <td><span class="badge action-badge">${a(u.action)}</span></td>
41
41
  <td>
42
- <div class="desc-text">${a(d.description)}</div>
42
+ <div class="desc-text">${a(u.description)}</div>
43
43
  ${b}
44
44
  ${m}
45
45
  </td>
46
- <td><code>${a(d.target||"\u2014")}</code></td>
47
- <td><span class="badge status-badge status-${g}">${d.status}</span></td>
46
+ <td><code>${a(u.target||"\u2014")}</code></td>
47
+ <td><span class="badge status-badge status-${g}">${u.status}</span></td>
48
48
  <td class="col-duration">${f}</td>
49
49
  <td class="col-artifact">${S}</td>
50
50
  </tr>`}).join(`
51
- `),p=u.videoPath?`
51
+ `),l=p.videoPath?`
52
52
  <section class="card video-card">
53
53
  <h3>\u{1F3AC} Session Screen Recording</h3>
54
- <video controls preload="metadata" class="recording-player" src="./${a(u.videoPath)}"></video>
55
- </section>`:"",h=u.errorsDetected.length>0?`
54
+ <video controls preload="metadata" class="recording-player" src="./${a(p.videoPath)}"></video>
55
+ </section>`:"",h=p.errorsDetected.length>0?`
56
56
  <section class="card error-card">
57
- <h3>\u26A0\uFE0F Critical Flagged Errors (${u.errorsDetected.length})</h3>
57
+ <h3>\u26A0\uFE0F Critical Flagged Errors (${p.errorsDetected.length})</h3>
58
58
  <ul class="error-list">
59
- ${u.errorsDetected.map(d=>`<li>\u{1F534} <code>${a(d)}</code></li>`).join(`
59
+ ${p.errorsDetected.map(u=>`<li>\u{1F534} <code>${a(u)}</code></li>`).join(`
60
60
  `)}
61
61
  </ul>
62
62
  </section>`:"";return`<!DOCTYPE html>
@@ -460,9 +460,9 @@ ${c}`)))}),a.on("error",d=>{clearTimeout(h),!p&&o(d)})})}async getConnectedDevic
460
460
  <h1>PromptTest QA Audit Report</h1>
461
461
  <div class="header-meta">
462
462
  <strong>Suite:</strong> <code>${a(t)}</code> &bull;
463
- <strong>App:</strong> <code>${a(u.packageName)}</code> &bull;
464
- <strong>Device:</strong> <code>${a(u.deviceId)}</code> &bull;
465
- <strong>Duration:</strong> ${u.durationSeconds}s (${u.startTime.substring(11,19)} to ${u.endTime.substring(11,19)})
463
+ <strong>App:</strong> <code>${a(p.packageName)}</code> &bull;
464
+ <strong>Device:</strong> <code>${a(p.deviceId)}</code> &bull;
465
+ <strong>Duration:</strong> ${p.durationSeconds}s (${p.startTime.substring(11,19)} to ${p.endTime.substring(11,19)})
466
466
  </div>
467
467
  </div>
468
468
  <div class="status-pill">${i}</div>
@@ -479,37 +479,37 @@ ${c}`)))}),a.on("error",d=>{clearTimeout(h),!p&&o(d)})})}async getConnectedDevic
479
479
  </div>
480
480
  <div class="stat-card">
481
481
  <div class="stat-label">Total Steps</div>
482
- <div class="stat-value">${u.totalSteps}</div>
482
+ <div class="stat-value">${p.totalSteps}</div>
483
483
  </div>
484
484
  <div class="stat-card">
485
485
  <div class="stat-label">Passed</div>
486
- <div class="stat-value val-pass">${u.passedSteps}</div>
486
+ <div class="stat-value val-pass">${p.passedSteps}</div>
487
487
  </div>
488
488
  <div class="stat-card">
489
489
  <div class="stat-label">Failures</div>
490
- <div class="stat-value val-fail">${u.failedSteps}</div>
490
+ <div class="stat-value val-fail">${p.failedSteps}</div>
491
491
  </div>
492
492
  <div class="stat-card">
493
493
  <div class="stat-label">Warnings</div>
494
- <div class="stat-value val-warn">${u.warnSteps}</div>
494
+ <div class="stat-value val-warn">${p.warnSteps}</div>
495
495
  </div>
496
496
  <div class="stat-card">
497
497
  <div class="stat-label">Skipped</div>
498
- <div class="stat-value val-skip">${u.skippedSteps}</div>
498
+ <div class="stat-value val-skip">${p.skippedSteps}</div>
499
499
  </div>
500
500
  </div>
501
501
 
502
- ${p}
502
+ ${l}
503
503
  ${h}
504
504
 
505
505
  <section class="card">
506
506
  <div class="toolbar">
507
507
  <div class="filter-bar">
508
- <button class="filter-btn active" data-filter="all" onclick="setFilter('all', this)">All (${u.totalSteps})</button>
509
- <button class="filter-btn" data-filter="pass" onclick="setFilter('pass', this)">Passed (${u.passedSteps})</button>
510
- <button class="filter-btn" data-filter="fail" onclick="setFilter('fail', this)">Failed (${u.failedSteps})</button>
511
- <button class="filter-btn" data-filter="warn" onclick="setFilter('warn', this)">Warnings (${u.warnSteps})</button>
512
- <button class="filter-btn" data-filter="skipped" onclick="setFilter('skipped', this)">Skipped (${u.skippedSteps})</button>
508
+ <button class="filter-btn active" data-filter="all" onclick="setFilter('all', this)">All (${p.totalSteps})</button>
509
+ <button class="filter-btn" data-filter="pass" onclick="setFilter('pass', this)">Passed (${p.passedSteps})</button>
510
+ <button class="filter-btn" data-filter="fail" onclick="setFilter('fail', this)">Failed (${p.failedSteps})</button>
511
+ <button class="filter-btn" data-filter="warn" onclick="setFilter('warn', this)">Warnings (${p.warnSteps})</button>
512
+ <button class="filter-btn" data-filter="skipped" onclick="setFilter('skipped', this)">Skipped (${p.skippedSteps})</button>
513
513
  </div>
514
514
  <div class="search-box">
515
515
  <input type="text" id="filter-search" placeholder="\u{1F50D} Search steps, actions, targets..." oninput="applyFilters()"/>
@@ -564,7 +564,7 @@ ${c}`)))}),a.on("error",d=>{clearTimeout(h),!p&&o(d)})})}async getConnectedDevic
564
564
  </div>
565
565
 
566
566
  <script>
567
- const SCREENSHOTS = ${JSON.stringify(l)};
567
+ const SCREENSHOTS = ${JSON.stringify(d)};
568
568
  let currentLightboxIdx = -1;
569
569
  let currentFilter = 'all';
570
570
 
@@ -677,9 +677,9 @@ ${c}`)))}),a.on("error",d=>{clearTimeout(h),!p&&o(d)})})}async getConnectedDevic
677
677
  }
678
678
  </script>
679
679
  </body>
680
- </html>`}var nt=new rt;import ge from"fs";import Re from"path";import{fileURLToPath as Pi}from"url";var ot={en:{bell:["bell","notification","notifications","alert","alerts","reminders","notice","badge"],notification:["notification","notifications","bell","alert","alerts","reminders","badge"],close:["close","dismiss","cancel","clear","cross","exit","\u2715","\xD7","x"],like:["like","favorite","heart","thumbs up","thumbs-up","fav","upvote"],dislike:["dislike","thumbs down","thumbs-down","downvote"],search:["search","find","query","magnifier","explore","lookup"],settings:["settings","preferences","gear","options","setup","config"],profile:["profile","account","user","my profile","avatar","me","personal"],trash:["trash","delete","remove","bin","discard"],delete:["delete","trash","remove","bin","discard"],share:["share","export","send to","forward"],back:["back","navigate up","previous","arrow back","chevron left","return"],menu:["menu","hamburger","drawer","sidebar","options","navigation","\u2630"],add:["add","new","create","plus","+","insert"],edit:["edit","pencil","modify","update","rename","change"],calendar:["calendar","schedule","date","events","timetable"],refresh:["refresh","reload","sync","update"],info:["info","information","details","help","about"],filter:["filter","filters","sort","refine","funnel"],check:["check","done","tick","mark","select","\u2713","\u2714"],lock:["lock","security","privacy","padlock"],camera:["camera","photo","picture","capture","snapshot"],cart:["cart","shopping cart","bag","basket","checkout"],email:["email","username","user name","e-mail","mail","login ID","user id"],username:["username","user name","email","user id","handle"],password:["password","passcode","pin","pwd","secret"],phone:["phone","mobile","contact","telephone","cell","phone number"],name:["name","full name","first name","last name"],otp:["otp","verification code","code","pin"],submit:["submit","save","continue","confirm","proceed","done","apply","ok"],save:["save","submit","done","apply","store","update"],cancel:["cancel","abort","discard","close","dismiss"],confirm:["confirm","yes","proceed","ok","agree","accept"],login:["sign in","signin","log in","login","enter"],signin:["sign in","signin","log in","login","enter"],logout:["sign out","signout","log out","logout","exit"],signout:["sign out","signout","log out","logout","exit"]},es:{bell:["campana","notificaci\xF3n","notificaciones","alerta","alertas","aviso","avisos"],notification:["notificaci\xF3n","notificaciones","campana","alerta","alertas","aviso","avisos","notification","notifications"],close:["cerrar","cancelar","quitar","salir","descartar","\u2715","\xD7","x","close"],like:["me gusta","favorito","favoritos","coraz\xF3n","like"],dislike:["no me gusta","desaprobar"],search:["buscar","b\xFAsqueda","lupa","explorar","encontrar","search"],settings:["ajustes","configuraci\xF3n","preferencias","opciones","settings"],profile:["perfil","cuenta","usuario","mi perfil","avatar","profile"],trash:["papelera","eliminar","borrar","descartar","quitar"],delete:["eliminar","borrar","quitar","papelera","descartar","delete"],share:["compartir","enviar","difundir","share"],back:["atr\xE1s","volver","regresar","anterior","flecha atr\xE1s","back"],menu:["men\xFA","opciones","navegaci\xF3n","\u2630","menu"],add:["a\xF1adir","agregar","nuevo","crear","m\xE1s","+","add"],edit:["editar","modificar","cambiar","actualizar","edit"],calendar:["calendario","fecha","eventos","horario","calendar"],refresh:["actualizar","recargar","sincronizar","refresh"],info:["informaci\xF3n","detalles","ayuda","acerca de","info"],filter:["filtrar","filtros","ordenar","filter"],check:["listo","hecho","marcar","seleccionar","\u2713","\u2714","check"],lock:["bloqueo","seguridad","privacidad","candado","lock"],camera:["c\xE1mara","foto","captura","imagen","camera"],cart:["carrito","cesta","bolsa","comprar","cart","checkout"],email:["correo","correo electr\xF3nico","email","usuario","mail"],username:["usuario","nombre de usuario","correo","username"],password:["contrase\xF1a","clave","pin","c\xF3digo","password"],phone:["tel\xE9fono","m\xF3vil","celular","contacto","n\xFAmero","phone"],name:["nombre","nombre completo","apellidos","name"],otp:["c\xF3digo de verificaci\xF3n","c\xF3digo","otp","pin"],submit:["enviar","guardar","confirmar","continuar","proceder","listo","aceptar","submit"],save:["guardar","salvar","almacenar","actualizar","save"],cancel:["cancelar","descartar","anular","abortar","cancel"],confirm:["confirmar","aceptar","s\xED","continuar","de acuerdo","confirm"],login:["iniciar sesi\xF3n","entrar","acceder","identificarse","ingresar","login","sign in"],signin:["iniciar sesi\xF3n","entrar","acceder","identificarse","ingresar","login","sign in"],logout:["cerrar sesi\xF3n","salir","desconectar","logout","sign out"],signout:["cerrar sesi\xF3n","salir","desconectar","logout","sign out"]},hi:{bell:["\u0918\u0902\u091F\u0940","\u0928\u094B\u091F\u093F\u092B\u093F\u0915\u0947\u0936\u0928","\u0938\u0942\u091A\u0928\u093E\u090F\u0902","alert","reminders"],notification:["\u0928\u094B\u091F\u093F\u092B\u093F\u0915\u0947\u0936\u0928","\u0938\u0942\u091A\u0928\u093E\u090F\u0902","alert","reminders","notification"],close:["\u092C\u0902\u0926 \u0915\u0930\u0947\u0902","\u0939\u091F\u093E\u090F\u0902","\u0930\u0926\u094D\u0926 \u0915\u0930\u0947\u0902","\u2715","\xD7","x","close"],like:["\u092A\u0938\u0902\u0926","\u0932\u093E\u0907\u0915","\u092A\u0938\u0902\u0926\u0940\u0926\u093E"],dislike:["\u0928\u093E\u092A\u0938\u0902\u0926"],search:["\u0916\u094B\u091C\u0947\u0902","\u0922\u0942\u0902\u0922\u0947\u0902","\u0938\u0930\u094D\u091A","explore","search"],settings:["\u0938\u0947\u091F\u093F\u0902\u0917\u094D\u0938","\u0935\u093F\u0915\u0932\u094D\u092A","\u092A\u094D\u0930\u093E\u0925\u092E\u093F\u0915\u0924\u093E\u090F\u0902","settings"],profile:["\u092A\u094D\u0930\u094B\u092B\u093C\u093E\u0907\u0932","\u0916\u093E\u0924\u093E","\u0909\u092A\u092F\u094B\u0917\u0915\u0930\u094D\u0924\u093E","\u0905\u0915\u093E\u0909\u0902\u091F","profile"],trash:["\u0939\u091F\u093E\u090F\u0902","\u0921\u093F\u0932\u0940\u091F","\u0915\u091A\u0930\u093E"],delete:["\u0939\u091F\u093E\u090F\u0902","\u0921\u093F\u0932\u0940\u091F","\u092E\u093F\u091F\u093E\u090F\u0902","delete"],share:["\u0936\u0947\u092F\u0930 \u0915\u0930\u0947\u0902","\u092D\u0947\u091C\u0947\u0902","share"],back:["\u0935\u093E\u092A\u0938","\u092A\u0940\u091B\u0947","\u0935\u093E\u092A\u0938 \u091C\u093E\u090F\u0902","back"],menu:["\u092E\u0947\u0928\u0942","\u0935\u093F\u0915\u0932\u094D\u092A","\u2630","menu"],add:["\u091C\u094B\u0921\u093C\u0947\u0902","\u0928\u092F\u093E","\u092C\u0928\u093E\u090F\u0902","+","add"],edit:["\u0938\u0902\u092A\u093E\u0926\u093F\u0924 \u0915\u0930\u0947\u0902","\u092C\u0926\u0932\u0947\u0902","\u090F\u0921\u093F\u091F","edit"],calendar:["\u0915\u0948\u0932\u0947\u0902\u0921\u0930","\u0924\u093E\u0930\u0940\u0916","\u0938\u092E\u092F \u0938\u093E\u0930\u093F\u0923\u0940"],refresh:["\u0930\u093F\u092B\u094D\u0930\u0947\u0936","\u0924\u093E\u091C\u093C\u093E \u0915\u0930\u0947\u0902","\u0905\u092A\u0921\u0947\u091F \u0915\u0930\u0947\u0902"],info:["\u091C\u093E\u0928\u0915\u093E\u0930\u0940","\u0935\u093F\u0935\u0930\u0923","\u092E\u0926\u0926","info"],filter:["\u092B\u093C\u093F\u0932\u094D\u091F\u0930","\u091B\u093E\u0902\u091F\u0947\u0902","filter"],check:["\u0939\u094B \u0917\u092F\u093E","\u091A\u0941\u0928\u0947\u0902","\u0938\u0939\u0940","\u2713","\u2714"],cart:["\u0915\u093E\u0930\u094D\u091F","\u0925\u0948\u0932\u093E","\u091F\u094B\u0915\u0930\u0940","cart"],email:["\u0908\u092E\u0947\u0932","\u0908-\u092E\u0947\u0932","\u092F\u0942\u091C\u0930\u0928\u0947\u092E","email"],username:["\u0909\u092A\u092F\u094B\u0917\u0915\u0930\u094D\u0924\u093E \u0928\u093E\u092E","\u092F\u0942\u091C\u0930\u0928\u0947\u092E","\u0908\u092E\u0947\u0932","username"],password:["\u092A\u093E\u0938\u0935\u0930\u094D\u0921","\u092A\u093F\u0928","\u092A\u093E\u0938\u0915\u094B\u0921","password"],phone:["\u092B\u093C\u094B\u0928","\u092E\u094B\u092C\u093E\u0907\u0932","\u0928\u0902\u092C\u0930","\u0938\u0902\u092A\u0930\u094D\u0915","phone"],name:["\u0928\u093E\u092E","\u092A\u0942\u0930\u093E \u0928\u093E\u092E","name"],otp:["\u0913\u091F\u0940\u092A\u0940","\u0938\u0924\u094D\u092F\u093E\u092A\u0928 \u0915\u094B\u0921","\u092A\u093F\u0928","otp"],submit:["\u091C\u092E\u093E \u0915\u0930\u0947\u0902","\u0938\u092C\u092E\u093F\u091F","\u092A\u0941\u0937\u094D\u091F\u093F \u0915\u0930\u0947\u0902","\u0906\u0917\u0947 \u092C\u0922\u093C\u0947\u0902","submit"],save:["\u0938\u0939\u0947\u091C\u0947\u0902","\u0938\u0947\u0935 \u0915\u0930\u0947\u0902","\u0938\u0941\u0930\u0915\u094D\u0937\u093F\u0924 \u0915\u0930\u0947\u0902","save"],cancel:["\u0930\u0926\u094D\u0926 \u0915\u0930\u0947\u0902","\u0915\u0948\u0902\u0938\u093F\u0932","cancel"],confirm:["\u092A\u0941\u0937\u094D\u091F\u093F \u0915\u0930\u0947\u0902","\u0938\u094D\u0935\u0940\u0915\u093E\u0930 \u0915\u0930\u0947\u0902","\u0939\u093E\u0901","\u0920\u0940\u0915 \u0939\u0948","confirm"],login:["\u0932\u0949\u0917 \u0907\u0928","\u0932\u0949\u0917\u093F\u0928","\u092A\u094D\u0930\u0935\u0947\u0936 \u0915\u0930\u0947\u0902","\u0938\u093E\u0907\u0928 \u0907\u0928","login","sign in"],signin:["\u0932\u0949\u0917 \u0907\u0928","\u0932\u0949\u0917\u093F\u0928","\u0938\u093E\u0907\u0928 \u0907\u0928","\u092A\u094D\u0930\u0935\u0947\u0936 \u0915\u0930\u0947\u0902","login","sign in"],logout:["\u0932\u0949\u0917 \u0906\u0909\u091F","\u0938\u093E\u0907\u0928 \u0906\u0909\u091F","\u092C\u093E\u0939\u0930 \u0928\u093F\u0915\u0932\u0947\u0902","logout"],signout:["\u0932\u0949\u0917 \u0906\u0909\u091F","\u0938\u093E\u0907\u0928 \u0906\u0909\u091F","\u092C\u093E\u0939\u0930 \u0928\u093F\u0915\u0932\u0947\u0902","logout"]}},lr=ot.en,Et=new Map;function Ys(u){let e=new Map;for(let[t,s]of Object.entries(u)){let n=[X(t),...s.map(r=>X(r))];for(let r of n){e.has(r)||e.set(r,[]);let o=e.get(r);for(let a of n)o.includes(a)||o.push(a)}}return e}for(let[u,e]of Object.entries(ot))Et.set(u.toLowerCase(),Ys(e));function dr(u,e){let t=u.toLowerCase();ot[t]={...ot[t]||{},...e},Et.set(t,Ys(ot[t]))}function ur(){return Object.keys(ot)}function St(u,e="en"){let t=X(u),s=(e||"en").toLowerCase(),i=Et.get(s);if(i){let n=i.get(t);if(n&&n.length>0)return n}if(s!=="en"){let n=Et.get("en");if(n){let r=n.get(t);if(r&&r.length>0)return r}}return[t]}var js=St;var He=class u{memoryDir;currentPackage="global";mappings=new Map;screens=new Map;intents=new Map;dirty=!1;locale="en";setLocale(e){this.locale=(e||"en").toLowerCase()}getLocale(){return this.locale}constructor(e){if(e)this.memoryDir=e;else{let t=Re.dirname(Pi(import.meta.url));this.memoryDir=Re.resolve(t,"..","memory")}ge.existsSync(this.memoryDir)||ge.mkdirSync(this.memoryDir,{recursive:!0})}cleanPackageName(e){return(e||"global").replace(/[^a-zA-Z0-9._-]/g,"_")}static SCHEMA_VERSION=2;async init(e){this.currentPackage=this.cleanPackageName(e),this.mappings.clear(),this.screens.clear(),this.intents.clear(),this.dirty=!1;let t=Re.join(this.memoryDir,`${this.currentPackage}.json`);if(ge.existsSync(t))try{let s=await ge.promises.readFile(t,"utf-8"),i=JSON.parse(s);if(i&&i.mappings){let n=!i.version||i.version<2;for(let[r,o]of Object.entries(i.mappings))n&&(o.totalSuccesses=o.totalSuccesses??o.successCount??1,o.recentOutcomes=o.recentOutcomes??(o.failCount>0?["FAIL"]:["PASS"]),o.lastSeenTs=o.lastSeenTs??o.lastUpdated??new Date().toISOString(),this.dirty=!0),this.mappings.set(r,o);if(i.screens)for(let[r,o]of Object.entries(i.screens))this.screens.set(r,o);if(i.intents)for(let[r,o]of Object.entries(i.intents))this.intents.set(r,o);this.decayStaleMappings()}else this.mappings.clear(),this.screens.clear(),this.intents.clear()}catch{this.mappings.clear(),this.screens.clear(),this.intents.clear()}}getCanonicalQuery(e){let t=X(e),s=St(t,this.locale);return s&&s.length>0?s[0]:t}buildKey(e,t){return`${e.toUpperCase()}:${this.getCanonicalQuery(t)}`}resolve(e,t){let s=this.buildKey(e,t),i=this.mappings.get(s);if(i)return i;let n=`${e.toUpperCase()}:${X(t)}`,r=this.mappings.get(n);if(r)return r;let o=St(t,this.locale);for(let a of o){let l=`${e.toUpperCase()}:${a}`,c=this.mappings.get(l);if(c)return c}}getAllCandidates(e,t,s,i){let n=(s||this.locale||"en").toLowerCase(),r=new Set;if(i){let l=this.getScreenElements(i),c=this.getCanonicalQuery(t);for(let p of l)p.action===e.toUpperCase()&&(p.canonicalIntent===c||p.canonicalIntent===X(t))&&p.confidence>=.7&&r.add(p.matchedIdentifier)}let o=this.resolve(e,t);o&&o.confidence>=.8&&r.add(o.matchedIdentifier),r.add(t);let a=St(t,n);for(let l of a)r.add(l);return Array.from(r)}recordSuccess(e,t,s,i,n=1,r,o){if(s.length>35||s.includes("?")||s.includes(`
681
- `))return;let a=this.buildKey(e,t),l=this.mappings.get(a),c=new Date().toISOString(),p=r||l?.healedFrom?T.memory?.maxHealedConfidence??.65:1,h=r||l?.healedFrom?Math.min(n,p):n;l&&l.matchedIdentifier===s?(l.successCount+=1,l.totalSuccesses=(l.totalSuccesses||0)+1,l.failCount=0,l.recentOutcomes||(l.recentOutcomes=[]),l.recentOutcomes.push("PASS"),l.recentOutcomes.length>5&&l.recentOutcomes.shift(),l.confidence=Math.min(p,Number((l.confidence+.05).toFixed(2))),l.lastUpdated=c,l.lastSeenTs=c,r&&(l.healedFrom=r)):this.mappings.set(a,{canonicalIntent:this.getCanonicalQuery(t),action:e.toUpperCase(),matchedIdentifier:s,matchType:i,confidence:h,successCount:1,failCount:0,totalSuccesses:1,recentOutcomes:["PASS"],lastUpdated:c,lastSeenTs:c,healedFrom:r}),o&&this.associateScreenElement(o,a),this.dirty=!0}associateScreenElement(e,t){if(!e||!t)return;let s=new Date().toISOString(),i=this.screens.get(e);i?(i.elements.includes(t)||i.elements.push(t),i.lastSeenTs=s):this.screens.set(e,{lastSeenTs:s,elements:[t]}),this.dirty=!0}getScreenElements(e){let t=this.screens.get(e);return t?t.elements.map(s=>this.mappings.get(s)).filter(s=>s!==void 0):[]}getScreenIndex(){return Object.fromEntries(this.screens.entries())}markScreenCrawled(e,t){if(!e)return;let s=new Date().toISOString(),i=this.screens.get(e);if(i){if(i.crawled=!0,i.crawledAt=s,i.lastSeenTs=s,t&&t.length>0){i.safeActions||(i.safeActions=[]);for(let n of t)i.safeActions.includes(n)||i.safeActions.push(n)}}else this.screens.set(e,{lastSeenTs:s,elements:[],crawled:!0,crawledAt:s,safeActions:t?[...t]:[]});this.dirty=!0}isScreenCrawled(e){return e?!!this.screens.get(e)?.crawled:!1}getScreenMemory(e){return this.screens.get(e)}getCrawledScreensCount(){let e=0;for(let t of this.screens.values())t.crawled&&e++;return e}recordIntentExpansion(e,t){if(!e||!t||t.length===0)return;let s=X(e),i=new Date().toISOString(),n=this.intents.get(s);n?(n.steps=[...t],n.usageCount=(n.usageCount||1)+1,n.learnedAt=i):this.intents.set(s,{intent:e,steps:[...t],learnedAt:i,usageCount:1}),this.dirty=!0}getIntentExpansion(e){if(!e)return;let t=X(e),s=this.intents.get(t);if(s)return s.usageCount=(s.usageCount||0)+1,this.dirty=!0,[...s.steps]}hasIntentExpansion(e){return e?this.intents.has(X(e)):!1}getIntentExpansionsCount(){return this.intents.size}recordFailure(e,t){let s=this.buildKey(e,t),i=this.mappings.get(s);i&&(i.failCount+=1,i.recentOutcomes||(i.recentOutcomes=[]),i.recentOutcomes.push("FAIL"),i.recentOutcomes.length>5&&i.recentOutcomes.shift(),i.confidence=Math.max(.1,Number((i.confidence-.25).toFixed(2))),i.lastUpdated=new Date().toISOString(),(i.recentOutcomes.filter(r=>r==="FAIL").length>=3||i.confidence<.2)&&this.mappings.delete(s),this.dirty=!0)}decayStaleMappings(e){let s=(e??T.memory?.staleThresholdDays??14)*24*60*60*1e3,i=Date.now(),n=0;for(let r of this.mappings.values()){let o=r.lastSeenTs?new Date(r.lastSeenTs).getTime():0;if(o>0&&i-o>s){let a=T.memory?.staleDecayAmount??.2,l=T.memory?.minConfidenceFloor??.2,c=Math.max(l,Number((r.confidence-a).toFixed(2)));c<r.confidence&&(r.confidence=c,n++,this.dirty=!0)}}return n}async save(){if(!this.dirty)return;let e={packageName:this.currentPackage,version:u.SCHEMA_VERSION,lastUpdated:new Date().toISOString(),mappings:Object.fromEntries(this.mappings.entries()),screens:Object.fromEntries(this.screens.entries()),intents:Object.fromEntries(this.intents.entries())},t=Re.join(this.memoryDir,`${this.currentPackage}.json`),s=`${t}.tmp.${Date.now()}`;await ge.promises.writeFile(s,JSON.stringify(e,null,2),"utf-8");try{await ge.promises.rename(s,t)}catch{await ge.promises.copyFile(s,t),await ge.promises.unlink(s).catch(()=>{})}this.dirty=!1}async exportMemory(e){let t=e?Re.resolve(e):Re.join(this.memoryDir,`${this.currentPackage}-export.json`),s=Re.dirname(t);ge.existsSync(s)||ge.mkdirSync(s,{recursive:!0});let i={packageName:this.currentPackage,version:u.SCHEMA_VERSION,lastUpdated:new Date().toISOString(),mappings:Object.fromEntries(this.mappings.entries()),screens:Object.fromEntries(this.screens.entries()),intents:Object.fromEntries(this.intents.entries())};return await ge.promises.writeFile(t,JSON.stringify(i,null,2),"utf-8"),t}async importMemory(e){let t=Re.resolve(e);if(!ge.existsSync(t))throw new Error(`Memory import source file not found: ${t}`);let s=await ge.promises.readFile(t,"utf-8"),i=JSON.parse(s);if(!i||!i.mappings)throw new Error("Invalid memory file format: missing mappings object.");let n=0,r=new Date().toISOString();for(let[o,a]of Object.entries(i.mappings)){let l=this.mappings.get(o);(!l||a.confidence>=l.confidence)&&(this.mappings.set(o,{...a,totalSuccesses:a.totalSuccesses??a.successCount??1,recentOutcomes:a.recentOutcomes??["PASS"],lastSeenTs:a.lastSeenTs??a.lastUpdated??r,lastUpdated:r}),n++)}if(i.screens)for(let[o,a]of Object.entries(i.screens)){let l=this.screens.get(o);if(!l)this.screens.set(o,a);else{let c=new Set([...l.elements,...a.elements]),p=new Set([...l.safeActions||[],...a.safeActions||[]]);this.screens.set(o,{lastSeenTs:a.lastSeenTs||l.lastSeenTs,elements:Array.from(c),crawled:l.crawled||a.crawled,crawledAt:a.crawledAt||l.crawledAt,safeActions:Array.from(p)})}}if(i.intents)for(let[o,a]of Object.entries(i.intents)){let l=this.intents.get(o);(!l||(a.usageCount||0)>=(l.usageCount||0))&&this.intents.set(o,a)}return n>0&&(this.dirty=!0,await this.save()),n}getMappingsList(){return Array.from(this.mappings.values())}getStats(){let e=Array.from(this.mappings.values()),t=e.reduce((n,r)=>n+(r.totalSuccesses||r.successCount||0),0),s=e.length>0?Number((e.reduce((n,r)=>n+r.confidence,0)/e.length).toFixed(2)):0,i=0;for(let n of this.screens.values())n.crawled&&i++;return{totalMappings:this.mappings.size,totalScreens:this.screens.size,crawledScreens:i,totalIntents:this.intents.size,package:this.currentPackage,totalSuccesses:t,averageConfidence:s}}async clear(e){let t=this.cleanPackageName(e||this.currentPackage),s=Re.join(this.memoryDir,`${t}.json`);return ge.existsSync(s)?(await ge.promises.unlink(s),t===this.currentPackage&&(this.mappings.clear(),this.screens.clear(),this.intents.clear(),this.dirty=!1),!0):!1}},at=new He;import De from"fs";import Di from"path";import Ai from"os";var Vt=new Map;function Ke(u){let e=(u||"default").replace(/[^a-zA-Z0-9._-]/g,"_"),t=Di.join(Ai.tmpdir(),`prompttest-${e}.lock`);if(De.existsSync(t))try{let i=De.readFileSync(t,"utf-8").trim(),n=parseInt(i,10);if(!isNaN(n)){if(n===process.pid)return{serial:u,lockFilePath:t,acquired:!0,pid:process.pid};try{throw process.kill(n,0),new Error(`Device "${u}" is locked by another PromptTest process (PID ${n}).
682
- Wait for the other run to complete, or remove the lock file if it is stale: ${t}`)}catch(r){if(r.code==="ESRCH")try{De.unlinkSync(t)}catch{}else throw r}}}catch(i){let n=i;if(n.message&&n.message.includes("locked by another"))throw n;try{De.unlinkSync(t)}catch{}}try{De.writeFileSync(t,process.pid.toString(),{flag:"wx"})}catch(i){throw i.code==="EEXIST"?new Error(`Device "${u}" was just acquired by a concurrent PromptTest process.`):i}let s=()=>{try{De.existsSync(t)&&De.readFileSync(t,"utf-8").trim()===process.pid.toString()&&De.unlinkSync(t)}catch{}};return Vt.set(t,s),process.once("exit",s),{serial:u,lockFilePath:t,acquired:!0,pid:process.pid}}function ze(u){if(u)try{let e=Vt.get(u.lockFilePath);if(e)process.removeListener("exit",e),Vt.delete(u.lockFilePath),e();else if(De.existsSync(u.lockFilePath))try{De.readFileSync(u.lockFilePath,"utf-8").trim()===process.pid.toString()&&De.unlinkSync(u.lockFilePath)}catch{}}catch{}}import Xt from"chalk";var Wt={DEBUG:0,INFO:1,WARN:2,ERROR:3,SILENT:4},Pt=class{currentLevel="INFO";constructor(e){let t=(process.env.LOG_LEVEL||"").toUpperCase();e?this.currentLevel=e:Wt[t]!==void 0?this.currentLevel=t:this.currentLevel="INFO"}setLevel(e){this.currentLevel=e}getLevel(){return this.currentLevel}isLevelEnabled(e){return Wt[this.currentLevel]<=Wt[e]}isJsonMode(){return(process.env.LOG_FORMAT||"").toLowerCase()==="json"}emitJson(e,...t){let s=t.map(n=>typeof n=="object"?JSON.stringify(n):String(n)).join(" "),i={ts:new Date().toISOString(),level:e,msg:s};e==="ERROR"||e==="WARN"?console.error(JSON.stringify(i)):console.log(JSON.stringify(i))}debug(...e){this.isLevelEnabled("DEBUG")&&(this.isJsonMode()?this.emitJson("DEBUG",...e):console.log(Xt.gray("[DEBUG]"),...e))}info(...e){this.isLevelEnabled("INFO")&&(this.isJsonMode()?this.emitJson("INFO",...e):console.log(...e))}warn(...e){this.isLevelEnabled("WARN")&&(this.isJsonMode()?this.emitJson("WARN",...e):console.warn(Xt.yellow("[WARN]"),...e))}error(...e){this.isLevelEnabled("ERROR")&&(this.isJsonMode()?this.emitJson("ERROR",...e):console.error(Xt.red("[ERROR]"),...e))}},ke=new Pt;import Ue from"fs";import Vs from"path";var Gt=class{checkpointDir;constructor(e){this.checkpointDir=e||Vs.resolve(process.cwd(),"output","checkpoints"),Ue.existsSync(this.checkpointDir)||Ue.mkdirSync(this.checkpointDir,{recursive:!0})}filePath(e){let t=e.replace(/[^a-zA-Z0-9._-]/g,"_");return Vs.join(this.checkpointDir,`${t}.checkpoint.json`)}async save(e,t,s,i){let n={specFile:e,packageName:t,lastPassedStep:s,totalSteps:i,savedAt:new Date().toISOString()},r=this.filePath(e)+`.tmp.${Date.now()}`;await Ue.promises.writeFile(r,JSON.stringify(n,null,2),"utf-8"),await Ue.promises.rename(r,this.filePath(e))}async load(e){let t=this.filePath(e);if(!Ue.existsSync(t))return null;try{let s=await Ue.promises.readFile(t,"utf-8");return JSON.parse(s)}catch{return null}}async clear(e){let t=this.filePath(e);Ue.existsSync(t)&&await Ue.promises.unlink(t)}async getResumeIndex(e){let t=await this.load(e);return t?t.lastPassedStep+1:0}},Xs=new Gt;import ve from"fs";import wt from"path";import{PNG as Je}from"pngjs";import $i from"pixelmatch";var ct=class{baselineDir;defaultThreshold;constructor(e,t=.02){this.baselineDir=e||wt.resolve(process.cwd(),"output","baselines"),this.defaultThreshold=t,ve.existsSync(this.baselineDir)||ve.mkdirSync(this.baselineDir,{recursive:!0})}filePath(e,t){let s=e.replace(/[^a-zA-Z0-9._-]/g,"_");return wt.join(this.baselineDir,`${s}_step${String(t).padStart(3,"0")}.png`)}diffFilePath(e,t){let s=e.replace(/[^a-zA-Z0-9._-]/g,"_");return wt.join(this.baselineDir,`${s}_step${String(t).padStart(3,"0")}_diff.png`)}async saveBaseline(e,t,s){let i=this.filePath(e,t),n=i+`.tmp.${Date.now()}`;return await ve.promises.writeFile(n,s),await ve.promises.rename(n,i),i}hasBaseline(e,t){return ve.existsSync(this.filePath(e,t))}async compare(e,t,s,i){let n=typeof i=="number"?{threshold:i}:i||{},r=this.filePath(e,t),o=wt.join(this.baselineDir,`${e.replace(/[^a-zA-Z0-9._-]/g,"_")}_step${String(t).padStart(3,"0")}_current.png`);await ve.promises.writeFile(o,s);let a=n.threshold??this.defaultThreshold;if(!ve.existsSync(r)){await this.saveBaseline(e,t,s);let w=Je.sync.read(s),A=w.width*w.height;return{stepName:`Step ${t}`,baselineFile:r,currentFile:o,diffRatio:0,diffPixels:0,totalPixels:A,passed:!0,threshold:a}}let l=await ve.promises.readFile(r),c=Je.sync.read(l),p=Je.sync.read(s),h=Math.max(c.width,p.width),d=Math.max(c.height,p.height),g=h*d,f=this.fitToCanvas(c,h,d),y=this.fitToCanvas(p,h,d);n.maskRegions&&n.maskRegions.length>0&&(this.applyMasks(f,n.maskRegions),this.applyMasks(y,n.maskRegions));let S=new Je({width:h,height:d}),b=n.pixelmatchThreshold??.1,m=$i(f.data,y.data,S.data,h,d,{threshold:b,includeAA:!1}),v=g>0?m/g:0,E=v<=a,k;if(m>0){k=this.diffFilePath(e,t);let w=Je.sync.write(S);await ve.promises.writeFile(k,w)}return{stepName:`Step ${t}`,baselineFile:r,currentFile:o,diffRatio:v,diffPixels:m,totalPixels:g,passed:E,threshold:a,diffImagePath:k}}fitToCanvas(e,t,s){if(e.width===t&&e.height===s)return e;let i=new Je({width:t,height:s});return i.data.fill(0),Je.bitblt(e,i,0,0,e.width,e.height,0,0),i}applyMasks(e,t){for(let s of t){let i=Math.min(e.width,s.x+s.width),n=Math.min(e.height,s.y+s.height);for(let r=Math.max(0,s.y);r<n;r++)for(let o=Math.max(0,s.x);o<i;o++){let a=e.width*r+o<<2;e.data[a]=0,e.data[a+1]=0,e.data[a+2]=0,e.data[a+3]=0}}}async clearBaselines(e){let t=e.replace(/[^a-zA-Z0-9._-]/g,"_");if(!ve.existsSync(this.baselineDir))return;let s=await ve.promises.readdir(this.baselineDir);await Promise.all(s.filter(i=>i.startsWith(t+"_step")).map(i=>ve.promises.unlink(wt.join(this.baselineDir,i)).catch(()=>{})))}},Kt=new ct;import se from"chalk";import Ws from"vm";function Y(u){return new Promise(e=>setTimeout(e,u))}function ki(u){let e=u.screenDimensions.height,t=u.navBarHeight>0?e-u.navBarHeight:e,s=u.navBarHeight>0?t*.94:e*T.gestures.bottomNavThresholdRatio;return{effectiveHeight:t,bottomThreshold:s}}var zt=class{type="TAP";async execute(e,t){let s=e.target,{width:i,height:n}=t.screenDimensions,r=Math.round(i*.5),{flat:o,matched:a}=await t.waitForTarget(s,t.serial,T.polling.defaultTimeoutMs,e);if(a.length===0&&t.upcomingSteps&&t.upcomingSteps.length>0&&!o.some(S=>S.password===!0||S.className.includes("EditText")&&o.some(b=>b.text?.toLowerCase().includes("password")))){let S=t.upcomingSteps.findIndex(m=>m.type==="VERIFY"&&m.target&&t.matchNodes(o,m.target,m).length>0);if(S!==-1)return{fastForwarded:!0,reason:`Screen already displays "${t.upcomingSteps[S].target}"`,skipCount:S};let b=t.upcomingSteps.findIndex(m=>m.type==="TAP"&&m.target&&t.matchNodes(o,m.target,m).length>0);if(b!==-1)return{fastForwarded:!0,reason:`Upcoming action "${t.upcomingSteps[b].target}" is directly actionable`,skipCount:b}}if(a.length===0){await t.driver.swipe(r,Math.round(n*.75),r,Math.round(n*.35),300,t.serial),await Y(350),t.setLastHierarchy(null);let y=await t.waitForTarget(s,t.serial,2e3,e);o=y.flat,a=y.matched}if(a.length===0)throw t.buildDiagnosticError(s,o,`Element matching "${s}" not found on current screen.`);let l=a.find(y=>y.clickable)||a[0];if(await t.ensureInViewport(l,t.serial)){let y=await t.waitForTarget(s,t.serial,1500,e);y.matched.length>0&&(o=y.flat,a=y.matched,l=a.find(S=>S.clickable)||a[0])}let p=l.bounds.centerX,{effectiveHeight:h}=ki(t),d=l.bounds.centerY;if(l.bounds.y2>h&&(d=Math.min(Math.round((l.bounds.y1+h)/2),h-15)),d=Math.min(d,l.bounds.y2-2),d=Math.max(d,l.bounds.y1+2),d>n*.6&&typeof t.driver.isKeyboardVisible=="function")try{await t.driver.isKeyboardVisible(t.serial)&&(console.log(se.gray(` [Keyboard] Target occluded by soft keyboard (Y=${d} > ${Math.round(n*.6)}). Dismissing...`)),await t.driver.pressBack(t.serial),await Y(300),t.setLastHierarchy(null))}catch{}let g=l.contentDesc||l.text||l.resourceId;console.log(se.gray(` [Tap Target] (${p}, ${d}) for "${g||s}"`));let f=t.lastHierarchy?.hash;await t.driver.tap(p,d,t.serial),await Y(T.settle.tapMs),t.setLastHierarchy(null),g&&X(g)!==X(s)&&t.memory.recordSuccess("TAP",s,g,l.contentDesc?"contentDesc":l.text?"text":"resourceId",1,void 0,f)}},Jt=class{type="LONG_PRESS";async execute(e,t){let s=e.target,{flat:i,matched:n}=await t.waitForTarget(s,t.serial,T.polling.defaultTimeoutMs,e);if(n.length===0)throw t.buildDiagnosticError(s,i,`Element matching "${s}" not found for long-press.`);let r=n[0];if(await t.ensureInViewport(r,t.serial)){let a=await t.waitForTarget(s,t.serial,1500,e);a.matched.length>0&&(r=a.matched[0])}await t.driver.swipe(r.bounds.centerX,r.bounds.centerY,r.bounds.centerX,r.bounds.centerY,T.gestures.longPressDurationMs,t.serial),await Y(300),t.setLastHierarchy(null)}},Dt=class{type="TYPE";async execute(e,t){let s=e.target,i=e.value??"",n=[],r=null;if(t.lastHierarchy&&Date.now()-t.lastHierarchy.timestamp<T.polling.hierarchyCacheTtlMs){let p=t.findTargetInputField(t.lastHierarchy.flat,s,i);p&&(n=t.lastHierarchy.flat,r=p)}if(r||(n=(await t.getCleanHierarchy(t.serial)).flat,r=t.findTargetInputField(n,s,i)),!r){let p=Date.now();for(;Date.now()-p<2e3&&(await Y(200),n=(await t.getCleanHierarchy(t.serial)).flat,r=t.findTargetInputField(n,s,i),!r););}if(!r&&t.upcomingSteps&&t.upcomingSteps.length>0&&!n.some(h=>h.className.includes("EditText"))){let h=t.upcomingSteps.findIndex(d=>d.type==="VERIFY"&&d.target&&t.matchNodes(n,d.target,d).length>0);if(h!==-1)return{fastForwarded:!0,reason:`Screen already displays "${t.upcomingSteps[h].target}" and form is completed`,skipCount:h}}if(!r)throw t.buildDiagnosticError(s,n,`Input field matching "${s}" not found.`);if(r.text&&r.text===i){console.log(se.gray(` [Input Field] Already contains desired value "${i}". Skipping typing.`));return}if(await t.ensureInViewport(r,t.serial)){n=(await t.getCleanHierarchy(t.serial)).flat;let h=t.findTargetInputField(n,s,i);h&&(r=h)}let{height:a}=t.screenDimensions;if(r.bounds.centerY>a*.6&&typeof t.driver.isKeyboardVisible=="function")try{await t.driver.isKeyboardVisible(t.serial)&&(console.log(se.gray(" [Keyboard] Input field occluded by soft keyboard. Dismissing before focus...")),await t.driver.pressBack(t.serial),await Y(300),t.setLastHierarchy(null))}catch{}let l=t.lastHierarchy?.hash;await t.driver.tap(r.bounds.centerX,r.bounds.centerY,t.serial),await Y(T.settle.inputFocusMs),await t.driver.clearField(t.serial),await Y(T.settle.inputClearMs),await t.driver.inputText(i,t.serial),await Y(T.settle.inputDoneMs),t.setLastHierarchy(null);let c=r.contentDesc||r.resourceId;c&&X(c)!==X(s)&&t.memory.recordSuccess("TYPE",s,c,r.contentDesc?"contentDesc":"resourceId",1,void 0,l)}},Qt=class{type="CLEAR";async execute(e,t){let s=e.target,i=[],n=null;if(t.lastHierarchy&&Date.now()-t.lastHierarchy.timestamp<T.polling.hierarchyCacheTtlMs&&(n=t.findTargetInputField(t.lastHierarchy.flat,s),n&&(i=t.lastHierarchy.flat)),n||(i=(await t.getCleanHierarchy(t.serial)).flat,n=t.findTargetInputField(i,s)),!n){let o=t.matchNodes(i,s,e);o.length>0&&(n=o[0])}if(!n)throw t.buildDiagnosticError(s,i,`Input field matching "${s}" not found to clear.`);await t.driver.tap(n.bounds.centerX,n.bounds.centerY,t.serial),await Y(300);let r=t.driver;typeof r.clearField=="function"?await r.clearField(t.serial):typeof r.clearInput=="function"&&await r.clearInput(50,t.serial),await Y(200),t.setLastHierarchy(null)}},qt=class{type="VERIFY";async execute(e,t){let s=e.target,i=e.expectedState||"visible";if(e.negative===!0||i==="absent"||i==="hidden"){let h=await t.getCleanHierarchy(t.serial);if(t.matchNodes(h.flat,s,e).length>0)throw new Error(`Negative assertion failed: "${s}" was expected to be NOT visible, but is present on screen.`);return}let{width:r,height:o}=t.screenDimensions,a=Math.round(r*.5),l=!1,c=[],p;if(t.lastHierarchy&&Date.now()-t.lastHierarchy.timestamp<T.polling.verifyCacheTtlMs&&(p=t.matchNodes(t.lastHierarchy.flat,s,e)[0],p&&(c=t.lastHierarchy.flat,l=!0,t.lastHierarchy.timestamp=Date.now())),!l){let h=Date.now();for(;Date.now()-h<T.polling.extendedTimeoutMs;){if(c=(await t.getCleanHierarchy(t.serial)).flat,p=t.matchNodes(c,s,e)[0],p){l=!0,t.lastHierarchy&&(t.lastHierarchy.timestamp=Date.now()),await Y(400);break}await Y(200)}}if(l||(await t.driver.swipe(a,Math.round(o*.75),a,Math.round(o*.35),300,t.serial),await Y(400),c=(await t.getCleanHierarchy(t.serial)).flat,p=t.matchNodes(c,s,e)[0],p&&(l=!0)),!l){if(t.upcomingSteps&&t.upcomingSteps.length>0&&!c.some(d=>d.password===!0||d.className.includes("EditText")&&c.some(g=>g.text?.toLowerCase().includes("password")))){let d=t.upcomingSteps.findIndex(g=>g.type==="VERIFY"&&g.target&&t.matchNodes(c,g.target,g).length>0);if(d!==-1)return{fastForwarded:!0,reason:`Screen is already on "${t.upcomingSteps[d].target}"`,skipCount:d}}throw await t.driver.swipe(a,Math.round(o*.35),a,Math.round(o*.75),300,t.serial),await Y(300),t.buildDiagnosticError(s,c,`Verification assertion failed: "${s}" is not visible on screen.`)}if(p&&i==="disabled"&&p.enabled)throw new Error(`State assertion failed: "${s}" was expected to be DISABLED, but is enabled.`);if(p&&i==="enabled"&&!p.enabled)throw new Error(`State assertion failed: "${s}" was expected to be ENABLED, but is disabled.`)}},Zt=class{type="BACK";async execute(e,t){await t.driver.pressKey(4,t.serial),await Y(T.settle.backMs),t.setLastHierarchy(null)}},es=class{type="SCROLL";async execute(e,t){let{width:s,height:i}=t.screenDimensions,n=Math.round(s*.5);if(e.target&&e.target!=="up"&&e.target!=="down"){let o=e.target,a=e.direction||"down",l=!1;for(let c=0;c<5;c++){let{flat:p}=await t.getCleanHierarchy(t.serial),h=t.matchNodes(p,o,e);if(h.length>0){await t.ensureInViewport(h[0],t.serial),l=!0;break}a==="up"?await t.driver.swipe(n,Math.round(i*.35),n,Math.round(i*.75),300,t.serial):await t.driver.swipe(n,Math.round(i*.75),n,Math.round(i*.35),300,t.serial),await Y(T.settle.scrollMs),t.setLastHierarchy(null)}if(!l){let{flat:c}=await t.getCleanHierarchy(t.serial);throw t.buildDiagnosticError(o,c,`Element "${o}" not found after scrolling ${e.direction||"down"}.`)}}else e.target==="up"||e.direction==="up"?await t.driver.swipe(n,Math.round(i*.35),n,Math.round(i*.75),300,t.serial):await t.driver.swipe(n,Math.round(i*.75),n,Math.round(i*.35),300,t.serial),await Y(T.settle.scrollMs),t.setLastHierarchy(null)}},ts=class{type="SWIPE";async execute(e,t){let{width:s,height:i}=t.screenDimensions,n=Math.round(s*.5),r=e.direction||"left";if(e.target){let{matched:p}=await t.waitForTarget(e.target,t.serial,2500,e);if(p.length>0){let h=p[0],d=r==="left"?h.bounds.x2-40:r==="right"?h.bounds.x1+40:h.bounds.centerX,g=r==="left"?h.bounds.x1+40:r==="right"?h.bounds.x2-40:h.bounds.centerX,f=r==="up"?h.bounds.y2-40:r==="down"?h.bounds.y1+40:h.bounds.centerY,y=r==="up"?h.bounds.y1+40:r==="down"?h.bounds.y2-40:h.bounds.centerY;await t.driver.swipe(d,f,g,y,T.gestures.swipeDurationMs,t.serial),await Y(400),t.setLastHierarchy(null);return}}let o=r==="left"?Math.round(s*.8):r==="right"?Math.round(s*.2):n,a=r==="left"?Math.round(s*.2):r==="right"?Math.round(s*.8):n,l=Math.round(r==="up"?i*.75:r==="down"?i*.35:i*.5),c=Math.round(r==="up"?i*.35:r==="down"?i*.75:i*.5);await t.driver.swipe(o,l,a,c,T.gestures.swipeDurationMs,t.serial),await Y(400),t.setLastHierarchy(null)}},ss=class{type="TOGGLE";async execute(e,t){let s=e.target,{flat:i,matched:n}=await t.waitForTarget(s,t.serial,T.polling.defaultTimeoutMs,e);if(n.length===0)throw t.buildDiagnosticError(s,i,`Toggle element matching "${s}" not found.`);let r=n.find(a=>a.clickable)||n[0];if(await t.ensureInViewport(r,t.serial)){let a=await t.waitForTarget(s,t.serial,1500,e);a.matched.length>0&&(r=a.matched.find(l=>l.clickable)||a.matched[0])}if(e.desiredState!==void 0&&r.checked!==void 0&&r.checked===e.desiredState){console.log(se.gray(` [Toggle] "${s}" is already in desired state (${e.desiredState?"ON":"OFF"}).`));return}await t.driver.tap(r.bounds.centerX,r.bounds.centerY,t.serial),await Y(T.settle.toggleMs),t.setLastHierarchy(null)}},is=class{type="SELECT";async execute(e,t){let s=e.target,i=e.value,{flat:n,matched:r}=await t.waitForTarget(s,t.serial,T.polling.defaultTimeoutMs,e);if(r.length===0)throw t.buildDiagnosticError(s,n,`Dropdown / picker element matching "${s}" not found.`);let o=r.find(c=>c.clickable)||r[0];await t.driver.tap(o.bounds.centerX,o.bounds.centerY,t.serial),await Y(T.settle.selectMs),t.setLastHierarchy(null);let a=await t.waitForTarget(i,t.serial,T.polling.defaultTimeoutMs);if(a.matched.length===0)throw t.buildDiagnosticError(i,a.flat,`Dropdown option "${i}" not found.`);let l=a.matched[0];await t.driver.tap(l.bounds.centerX,l.bounds.centerY,t.serial),await Y(400),t.setLastHierarchy(null)}},rs=class{type="LAUNCH_APP";async execute(e,t){let s=e.target;if(!s)throw new Error("Target package name required to launch app.");await t.driver.launchApp(s,t.serial),await Y(T.settle.launchMs),t.setLastHierarchy(null)}},ns=class{type="RESTART_APP";async execute(e,t){let s=e.target;if(!s)throw new Error("Target package name required to restart app.");await t.driver.restartApp(s,t.serial),await Y(T.settle.launchMs),t.setLastHierarchy(null)}},os=class{type="TERMINATE_APP";async execute(e,t){let s=e.target||await t.driver.getForegroundPackage(t.serial);s&&await t.driver.forceStop(s,t.serial),await Y(T.settle.stopMs),t.setLastHierarchy(null)}},as=class{type="CLEAR_DATA";async execute(e,t){let s=e.target;if(!s)throw new Error("Target package name required to clear data.");await t.driver.clearAppData(s,t.serial),await Y(1e3),t.setLastHierarchy(null)}},cs=class{type="GRANT_PERMISSION";async execute(e,t){let s=e.value,i=e.target||await t.driver.getForegroundPackage(t.serial);if(!i)throw new Error("Foreground package not detected for grant permission.");await t.driver.grantPermission(i,s,t.serial),await Y(400)}},ls=class{type="DEEP_LINK";async execute(e,t){let s=e.target;await t.driver.openDeepLink(s,t.serial),await Y(T.settle.launchMs),t.setLastHierarchy(null)}},ds=class{type="WAIT";async execute(e,t){await Y(e.durationMs||1e3)}},us=class{type="IF_VISIBLE";async execute(e,t){let s=e.conditionTarget||e.target;if(!s)return;let i=!1;try{let{matched:n}=await t.waitForTarget(s,t.serial,1500,e);i=n.length>0}catch{i=!1}i?(console.log(se.cyan(` [Conditional] Condition met: "${s}" is visible.`)),e.thenSteps&&e.thenSteps.length>0&&t.executeChildSteps&&await t.executeChildSteps(e.thenSteps,t)):(console.log(se.gray(` [Conditional] Condition not met: "${s}" is not visible.`)),e.elseSteps&&e.elseSteps.length>0&&t.executeChildSteps&&await t.executeChildSteps(e.elseSteps,t))}},ps=class{type="LOOP";async execute(e,t){let s=T.flow?.maxLoopIterations||50,i=Math.min(e.loopCount||1,s),n=e.childSteps||[];if(!(n.length===0||!t.executeChildSteps)){console.log(se.cyan(` [Loop] Starting loop iteration (1 to ${i})...`));for(let r=1;r<=i;r++){e.loopVariable&&t.variables.set(e.loopVariable,String(r)),t.loopStack.push({current:r,total:i,variable:e.loopVariable});try{await t.executeChildSteps(n,t)}finally{t.loopStack.pop()}}}}},hs=class{type="WAIT_UNTIL";async execute(e,t){let s=e.target,i=e.durationMs||T.flow?.waitUntilTimeoutMs||1e4,n=e.expectedState||"visible";console.log(se.gray(` [Wait Until] Waiting for "${s}" to be ${n} (up to ${i}ms)...`));let r=Date.now(),o=!1;for(;Date.now()-r<i;){try{let{matched:a}=await t.waitForTarget(s,t.serial,1e3,e);if(a.length>0){let l=a[0];if(n==="enabled"&&!l.enabled){await Y(250);continue}o=!0;break}}catch{}await Y(250)}if(!o){let{flat:a}=await t.getCleanHierarchy(t.serial);throw t.buildDiagnosticError(s,a,`WaitUntil assertion failed: "${s}" did not become ${n} within ${i}ms.`)}}},gs=class{type="SET_VARIABLE";async execute(e,t){let s=e.variableName,i=e.variableExpression||"";i=Xe(i,Object.fromEntries(t.variables));let n=Rs(i);t.variables.set(s,n),console.log(se.cyan(` [Variable] $${s} = "${n}"`))}},ms=class{type="DEVICE_STATE";async execute(e,t){let s=e.deviceAction,i=e.deviceStateValue;switch(s){case"wifi":{let n=i===!0||i==="on"||i==="enable";console.log(se.cyan(` [Device] Setting Wi-Fi: ${n?"ENABLED":"DISABLED"}`)),await t.driver.setWifiEnabled(n,t.serial);break}case"airplane":{let n=i===!0||i==="on"||i==="enable";console.log(se.cyan(` [Device] Setting Airplane Mode: ${n?"ENABLED":"DISABLED"}`)),await t.driver.setAirplaneMode(n,t.serial);break}case"orientation":{let n=i==="landscape"?"landscape":"portrait";console.log(se.cyan(` [Device] Setting Orientation: ${n.toUpperCase()}`)),await t.driver.setOrientation(n,t.serial);break}case"notifications":{let n=i==="open"||i==="expand"||i===!0;console.log(se.cyan(` [Device] ${n?"Expanding":"Collapsing"} Notification Shade`)),n?await t.driver.openNotificationShade(t.serial):await t.driver.collapseNotificationShade(t.serial);break}default:throw new Error(`Unsupported device action: ${s}`)}await Y(400),t.setLastHierarchy(null)}},fs=class{type="RUN_JS";async execute(e,t){let s=e.jsCode||e.value||"";if(!s)return;console.log(se.cyan(" [JS Hook] Executing sandboxed JavaScript snippet..."));let i={vars:Object.fromEntries(t.variables),setVar:(r,o)=>{t.variables.set(r,String(o))},getVar:r=>t.variables.get(r),console:{log:(...r)=>console.log(se.gray(" [JS Output]",...r)),error:(...r)=>console.error(se.red(" [JS Error]",...r))}},n=Ws.createContext(i);Ws.runInContext(s,n,{timeout:3e3});for(let[r,o]of Object.entries(i.vars))t.variables.set(r,String(o))}},bs=class{type="ENTER_OTP";async execute(e,t){console.log(se.cyan(" [OTP Capture] Detecting verification code..."));let s=null;if(process.env.PROMPTTEST_MOCK_OTP)s=process.env.PROMPTTEST_MOCK_OTP.trim(),console.log(se.gray(` [OTP Capture] Captured code from environment: ${s}`));else try{let{stdout:i}=await t.driver.execAdb(["shell","logcat","-d","-t","200","-s","SMSDispatcher:V","SmsMessage:V","NotificationService:V","ActivityManager:I"],t.serial),n=i.match(/(?:code|otp|pin|verification)[^0-9\r\n]{0,35}(\d{4,8})\b/i)||i.match(/\b(\d{4,8})\s*(?:is your verification|is your otp)/i);n&&(s=n[1],console.log(se.gray(` [OTP Capture] Captured code from logcat: ${s}`)))}catch{}if(s||(s="123456",console.log(se.yellow(` [OTP Capture] No live code detected; using simulated OTP: ${s}`))),e.target){let i={originalText:`Type '${s}' into '${e.target}'`,type:"TYPE",target:e.target,value:s};return new Dt().execute(i,t)}else{let{flat:i}=await t.getCleanHierarchy(t.serial),n=t.findTargetInputField(i,"code",s)||i.find(r=>r.className.includes("EditText"));n?(await t.driver.tap(n.bounds.centerX,n.bounds.centerY,t.serial),await Y(250),await t.driver.inputText(s,t.serial)):await t.driver.inputText(s,t.serial)}}},ys=class{type="API_REQUEST";async execute(e,t){let s=e.apiMethod||"GET",i=e.apiUrl||"";if(!i)throw new Error("API_REQUEST requires a valid target URL.");console.log(se.cyan(` [API Request] ${s} ${i}...`));let n={method:s,headers:{"Content-Type":"application/json",Accept:"application/json"}};e.apiBody&&(s==="POST"||s==="PUT"||s==="PATCH")&&(n.body=e.apiBody);let r=await fetch(i,n);if(e.apiExpectedStatus!==void 0){if(r.status!==e.apiExpectedStatus)throw new Error(`API status assertion failed for ${i}: expected HTTP ${e.apiExpectedStatus}, but received HTTP ${r.status}`);console.log(se.green(` \u2714 API Status HTTP ${r.status} matched expectation.`))}if(e.apiStorePath&&e.apiStoreVariable)try{let o=await r.text(),a=JSON.parse(o),l=this.resolveJsonPath(a,e.apiStorePath);l!==void 0&&(t.variables.set(e.apiStoreVariable,String(l)),console.log(se.cyan(` [Variable] $${e.apiStoreVariable} = "${l}" (from ${e.apiStorePath})`)))}catch(o){ke.warn(`Failed to parse JSON response for path extraction: ${o.message}`)}}resolveJsonPath(e,t){let s=t.replace(/^\$\.?/,"").split("."),i=e;for(let n of s){if(i==null||typeof i!="object")return;i=i[n]}return i}},Ss=class{type="EMAIL_ASSERT";async execute(e,t){let s=e.emailRecipient||"",i=e.emailSubject||"";console.log(se.cyan(` [Email Assertion] Checking email to "${s}" with subject "${i}"...`));let n=[];if(process.env.PROMPTTEST_MOCK_EMAILS)try{n=JSON.parse(process.env.PROMPTTEST_MOCK_EMAILS)}catch{n=[]}let r=n.find(o=>o.to.toLowerCase()===s.toLowerCase()&&o.subject.toLowerCase().includes(i.toLowerCase()));if(!r){if(n.length===0){if(!s.includes("@"))throw new Error(`Invalid email recipient address: "${s}"`);console.log(se.yellow(" \u26A0 No mock inbox configured (PROMPTTEST_MOCK_EMAILS); simulated email check passed."));return}throw new Error(`Email assertion failed: No email to "${s}" with subject "${i}" found.`)}if(e.emailBodyContains&&r.body&&!r.body.includes(e.emailBodyContains))throw new Error(`Email body assertion failed: Expected email to contain "${e.emailBodyContains}", but content did not match.`);console.log(se.green(" \u2714 Email verified successfully."))}},Ci=[new zt,new Jt,new Dt,new Qt,new qt,new Zt,new es,new ts,new ss,new is,new rs,new ns,new os,new as,new cs,new ls,new ds,new us,new ps,new hs,new gs,new ms,new fs,new bs,new ys,new Ss],Gs=new Map(Ci.map(u=>[u.type,u]));var Qe=class{providerName="heuristic";async resolveIntent(e,t){let s=X(e);return(s.includes("login")||s.includes("log in")||s.includes("sign in")||s.includes("signin"))&&(s.includes("test user")||s.includes("default credentials")||s.includes("credentials"))?[{originalText:"Type 'user@example.com' into 'Email'",type:"TYPE",target:"Email",value:"user@example.com"},{originalText:"Type 'Password123!' into 'Password'",type:"TYPE",target:"Password",value:"Password123!"},{originalText:"Tap 'Sign In'",type:"TAP",target:"Sign In"}]:s.includes("sign up with random user")||s.includes("register new user")?[{originalText:"Type $RANDOM_NAME into 'Name'",type:"TYPE",target:"Name",value:"$RANDOM_NAME"},{originalText:"Type $RANDOM_EMAIL into 'Email'",type:"TYPE",target:"Email",value:"$RANDOM_EMAIL"},{originalText:"Type 'Password123!' into 'Password'",type:"TYPE",target:"Password",value:"Password123!"},{originalText:"Tap 'Create Account'",type:"TAP",target:"Create Account"}]:s.includes("dismiss dialog")||s.includes("close modal")||s.includes("dismiss popup")?[{originalText:"Tap 'Close'",type:"TAP",target:"Close",optional:!0},{originalText:"Tap 'Dismiss'",type:"TAP",target:"Dismiss",optional:!0},{originalText:"Press back",type:"BACK",optional:!0}]:null}async findSuggestions(e,t,s){let i=[],n=X(e),r=new Set,o=js(e,s?.locale);for(let p of o){let h=t.find(d=>d.bounds.width>0&&d.bounds.height>0&&(z(p,d.text)||z(p,d.contentDesc)));if(h){let d=(h.text||h.contentDesc||p).trim();r.has(d)||(r.add(d),i.push({text:d,score:.9,node:h,strategy:"synonym",reason:`Direct synonym match for "${e}" via semantic dictionary`}))}}for(let p of t)if(p.resourceId&&p.bounds.width>0&&p.bounds.height>0&&p.resourceId.toLowerCase().split(/[:/_]/).some(g=>g===n||n.includes(g))){let g=(p.text||p.contentDesc||p.resourceId).trim();r.has(g)||(r.add(g),i.push({text:g,score:.85,node:p,strategy:"exact",reason:`Resource-ID segment matches target "${e}"`}))}let a=[];for(let p of t)p.bounds.width>0&&p.bounds.height>0&&(p.text&&p.text.trim().length>1&&a.push({text:p.text.trim(),node:p}),p.contentDesc&&p.contentDesc.trim().length>1&&a.push({text:p.contentDesc.trim(),node:p}));let l=Array.from(new Set(a.map(p=>p.text))),c=We(e,l,5);for(let p of c)if(p.score>=.7&&!r.has(p.text)){r.add(p.text);let h=a.find(d=>d.text===p.text)?.node;i.push({text:p.text,score:p.score,node:h,strategy:"fuzzy",reason:`String similarity match (${Math.round(p.score*100)}%)`})}return i.sort((p,h)=>h.score-p.score)}};var lt=class{providerName="mock";mockIntents=new Map;mockSuggestions=new Map;constructor(){this.mockIntents.set("log in to account",[{originalText:"Type 'test@example.com' into 'Email'",type:"TYPE",target:"Email",value:"test@example.com"},{originalText:"Type 'Password123' into 'Password'",type:"TYPE",target:"Password",value:"Password123"},{originalText:"Tap 'Sign In'",type:"TAP",target:"Sign In"}])}setMockIntent(e,t){this.mockIntents.set(e.toLowerCase().trim(),t)}setMockSuggestion(e,t){this.mockSuggestions.set(e.toLowerCase().trim(),t)}async resolveIntent(e,t){let s=e.toLowerCase().trim();return this.mockIntents.has(s)?this.mockIntents.get(s):null}async findSuggestions(e,t,s){let i=e.toLowerCase().trim();return this.mockSuggestions.has(i)?this.mockSuggestions.get(i):new Qe().findSuggestions(e,t)}},At=class{providerName;config;heuristicFallback;constructor(e){this.config=e,this.providerName=e.provider,this.heuristicFallback=new Qe}async resolveIntent(e,t){if(this.config.provider==="mock")return new lt().resolveIntent(e,t);try{let s=`You are a test automation engineer generating steps for PromptTest.
680
+ </html>`}var nt=new rt;import ge from"fs";import Re from"path";import{fileURLToPath as Di}from"url";var ot={en:{bell:["bell","notification","notifications","alert","alerts","reminders","notice","badge"],notification:["notification","notifications","bell","alert","alerts","reminders","badge"],close:["close","dismiss","cancel","clear","cross","exit","\u2715","\xD7","x"],like:["like","favorite","heart","thumbs up","thumbs-up","fav","upvote"],dislike:["dislike","thumbs down","thumbs-down","downvote"],search:["search","find","query","magnifier","explore","lookup"],settings:["settings","preferences","gear","options","setup","config"],profile:["profile","account","user","my profile","avatar","me","personal"],trash:["trash","delete","remove","bin","discard"],delete:["delete","trash","remove","bin","discard"],share:["share","export","send to","forward"],back:["back","navigate up","previous","arrow back","chevron left","return"],menu:["menu","hamburger","drawer","sidebar","options","navigation","\u2630"],add:["add","new","create","plus","+","insert"],edit:["edit","pencil","modify","update","rename","change"],calendar:["calendar","schedule","date","events","timetable"],refresh:["refresh","reload","sync","update"],info:["info","information","details","help","about"],filter:["filter","filters","sort","refine","funnel"],check:["check","done","tick","mark","select","\u2713","\u2714"],lock:["lock","security","privacy","padlock"],camera:["camera","photo","picture","capture","snapshot"],cart:["cart","shopping cart","bag","basket","checkout"],email:["email","username","user name","e-mail","mail","login ID","user id"],username:["username","user name","email","user id","handle"],password:["password","passcode","pin","pwd","secret"],phone:["phone","mobile","contact","telephone","cell","phone number"],name:["name","full name","first name","last name"],otp:["otp","verification code","code","pin"],submit:["submit","save","continue","confirm","proceed","done","apply","ok"],save:["save","submit","done","apply","store","update"],cancel:["cancel","abort","discard","close","dismiss"],confirm:["confirm","yes","proceed","ok","agree","accept"],login:["sign in","signin","log in","login","enter"],signin:["sign in","signin","log in","login","enter"],logout:["sign out","signout","log out","logout","exit"],signout:["sign out","signout","log out","logout","exit"]},es:{bell:["campana","notificaci\xF3n","notificaciones","alerta","alertas","aviso","avisos"],notification:["notificaci\xF3n","notificaciones","campana","alerta","alertas","aviso","avisos","notification","notifications"],close:["cerrar","cancelar","quitar","salir","descartar","\u2715","\xD7","x","close"],like:["me gusta","favorito","favoritos","coraz\xF3n","like"],dislike:["no me gusta","desaprobar"],search:["buscar","b\xFAsqueda","lupa","explorar","encontrar","search"],settings:["ajustes","configuraci\xF3n","preferencias","opciones","settings"],profile:["perfil","cuenta","usuario","mi perfil","avatar","profile"],trash:["papelera","eliminar","borrar","descartar","quitar"],delete:["eliminar","borrar","quitar","papelera","descartar","delete"],share:["compartir","enviar","difundir","share"],back:["atr\xE1s","volver","regresar","anterior","flecha atr\xE1s","back"],menu:["men\xFA","opciones","navegaci\xF3n","\u2630","menu"],add:["a\xF1adir","agregar","nuevo","crear","m\xE1s","+","add"],edit:["editar","modificar","cambiar","actualizar","edit"],calendar:["calendario","fecha","eventos","horario","calendar"],refresh:["actualizar","recargar","sincronizar","refresh"],info:["informaci\xF3n","detalles","ayuda","acerca de","info"],filter:["filtrar","filtros","ordenar","filter"],check:["listo","hecho","marcar","seleccionar","\u2713","\u2714","check"],lock:["bloqueo","seguridad","privacidad","candado","lock"],camera:["c\xE1mara","foto","captura","imagen","camera"],cart:["carrito","cesta","bolsa","comprar","cart","checkout"],email:["correo","correo electr\xF3nico","email","usuario","mail"],username:["usuario","nombre de usuario","correo","username"],password:["contrase\xF1a","clave","pin","c\xF3digo","password"],phone:["tel\xE9fono","m\xF3vil","celular","contacto","n\xFAmero","phone"],name:["nombre","nombre completo","apellidos","name"],otp:["c\xF3digo de verificaci\xF3n","c\xF3digo","otp","pin"],submit:["enviar","guardar","confirmar","continuar","proceder","listo","aceptar","submit"],save:["guardar","salvar","almacenar","actualizar","save"],cancel:["cancelar","descartar","anular","abortar","cancel"],confirm:["confirmar","aceptar","s\xED","continuar","de acuerdo","confirm"],login:["iniciar sesi\xF3n","entrar","acceder","identificarse","ingresar","login","sign in"],signin:["iniciar sesi\xF3n","entrar","acceder","identificarse","ingresar","login","sign in"],logout:["cerrar sesi\xF3n","salir","desconectar","logout","sign out"],signout:["cerrar sesi\xF3n","salir","desconectar","logout","sign out"]},hi:{bell:["\u0918\u0902\u091F\u0940","\u0928\u094B\u091F\u093F\u092B\u093F\u0915\u0947\u0936\u0928","\u0938\u0942\u091A\u0928\u093E\u090F\u0902","alert","reminders"],notification:["\u0928\u094B\u091F\u093F\u092B\u093F\u0915\u0947\u0936\u0928","\u0938\u0942\u091A\u0928\u093E\u090F\u0902","alert","reminders","notification"],close:["\u092C\u0902\u0926 \u0915\u0930\u0947\u0902","\u0939\u091F\u093E\u090F\u0902","\u0930\u0926\u094D\u0926 \u0915\u0930\u0947\u0902","\u2715","\xD7","x","close"],like:["\u092A\u0938\u0902\u0926","\u0932\u093E\u0907\u0915","\u092A\u0938\u0902\u0926\u0940\u0926\u093E"],dislike:["\u0928\u093E\u092A\u0938\u0902\u0926"],search:["\u0916\u094B\u091C\u0947\u0902","\u0922\u0942\u0902\u0922\u0947\u0902","\u0938\u0930\u094D\u091A","explore","search"],settings:["\u0938\u0947\u091F\u093F\u0902\u0917\u094D\u0938","\u0935\u093F\u0915\u0932\u094D\u092A","\u092A\u094D\u0930\u093E\u0925\u092E\u093F\u0915\u0924\u093E\u090F\u0902","settings"],profile:["\u092A\u094D\u0930\u094B\u092B\u093C\u093E\u0907\u0932","\u0916\u093E\u0924\u093E","\u0909\u092A\u092F\u094B\u0917\u0915\u0930\u094D\u0924\u093E","\u0905\u0915\u093E\u0909\u0902\u091F","profile"],trash:["\u0939\u091F\u093E\u090F\u0902","\u0921\u093F\u0932\u0940\u091F","\u0915\u091A\u0930\u093E"],delete:["\u0939\u091F\u093E\u090F\u0902","\u0921\u093F\u0932\u0940\u091F","\u092E\u093F\u091F\u093E\u090F\u0902","delete"],share:["\u0936\u0947\u092F\u0930 \u0915\u0930\u0947\u0902","\u092D\u0947\u091C\u0947\u0902","share"],back:["\u0935\u093E\u092A\u0938","\u092A\u0940\u091B\u0947","\u0935\u093E\u092A\u0938 \u091C\u093E\u090F\u0902","back"],menu:["\u092E\u0947\u0928\u0942","\u0935\u093F\u0915\u0932\u094D\u092A","\u2630","menu"],add:["\u091C\u094B\u0921\u093C\u0947\u0902","\u0928\u092F\u093E","\u092C\u0928\u093E\u090F\u0902","+","add"],edit:["\u0938\u0902\u092A\u093E\u0926\u093F\u0924 \u0915\u0930\u0947\u0902","\u092C\u0926\u0932\u0947\u0902","\u090F\u0921\u093F\u091F","edit"],calendar:["\u0915\u0948\u0932\u0947\u0902\u0921\u0930","\u0924\u093E\u0930\u0940\u0916","\u0938\u092E\u092F \u0938\u093E\u0930\u093F\u0923\u0940"],refresh:["\u0930\u093F\u092B\u094D\u0930\u0947\u0936","\u0924\u093E\u091C\u093C\u093E \u0915\u0930\u0947\u0902","\u0905\u092A\u0921\u0947\u091F \u0915\u0930\u0947\u0902"],info:["\u091C\u093E\u0928\u0915\u093E\u0930\u0940","\u0935\u093F\u0935\u0930\u0923","\u092E\u0926\u0926","info"],filter:["\u092B\u093C\u093F\u0932\u094D\u091F\u0930","\u091B\u093E\u0902\u091F\u0947\u0902","filter"],check:["\u0939\u094B \u0917\u092F\u093E","\u091A\u0941\u0928\u0947\u0902","\u0938\u0939\u0940","\u2713","\u2714"],cart:["\u0915\u093E\u0930\u094D\u091F","\u0925\u0948\u0932\u093E","\u091F\u094B\u0915\u0930\u0940","cart"],email:["\u0908\u092E\u0947\u0932","\u0908-\u092E\u0947\u0932","\u092F\u0942\u091C\u0930\u0928\u0947\u092E","email"],username:["\u0909\u092A\u092F\u094B\u0917\u0915\u0930\u094D\u0924\u093E \u0928\u093E\u092E","\u092F\u0942\u091C\u0930\u0928\u0947\u092E","\u0908\u092E\u0947\u0932","username"],password:["\u092A\u093E\u0938\u0935\u0930\u094D\u0921","\u092A\u093F\u0928","\u092A\u093E\u0938\u0915\u094B\u0921","password"],phone:["\u092B\u093C\u094B\u0928","\u092E\u094B\u092C\u093E\u0907\u0932","\u0928\u0902\u092C\u0930","\u0938\u0902\u092A\u0930\u094D\u0915","phone"],name:["\u0928\u093E\u092E","\u092A\u0942\u0930\u093E \u0928\u093E\u092E","name"],otp:["\u0913\u091F\u0940\u092A\u0940","\u0938\u0924\u094D\u092F\u093E\u092A\u0928 \u0915\u094B\u0921","\u092A\u093F\u0928","otp"],submit:["\u091C\u092E\u093E \u0915\u0930\u0947\u0902","\u0938\u092C\u092E\u093F\u091F","\u092A\u0941\u0937\u094D\u091F\u093F \u0915\u0930\u0947\u0902","\u0906\u0917\u0947 \u092C\u0922\u093C\u0947\u0902","submit"],save:["\u0938\u0939\u0947\u091C\u0947\u0902","\u0938\u0947\u0935 \u0915\u0930\u0947\u0902","\u0938\u0941\u0930\u0915\u094D\u0937\u093F\u0924 \u0915\u0930\u0947\u0902","save"],cancel:["\u0930\u0926\u094D\u0926 \u0915\u0930\u0947\u0902","\u0915\u0948\u0902\u0938\u093F\u0932","cancel"],confirm:["\u092A\u0941\u0937\u094D\u091F\u093F \u0915\u0930\u0947\u0902","\u0938\u094D\u0935\u0940\u0915\u093E\u0930 \u0915\u0930\u0947\u0902","\u0939\u093E\u0901","\u0920\u0940\u0915 \u0939\u0948","confirm"],login:["\u0932\u0949\u0917 \u0907\u0928","\u0932\u0949\u0917\u093F\u0928","\u092A\u094D\u0930\u0935\u0947\u0936 \u0915\u0930\u0947\u0902","\u0938\u093E\u0907\u0928 \u0907\u0928","login","sign in"],signin:["\u0932\u0949\u0917 \u0907\u0928","\u0932\u0949\u0917\u093F\u0928","\u0938\u093E\u0907\u0928 \u0907\u0928","\u092A\u094D\u0930\u0935\u0947\u0936 \u0915\u0930\u0947\u0902","login","sign in"],logout:["\u0932\u0949\u0917 \u0906\u0909\u091F","\u0938\u093E\u0907\u0928 \u0906\u0909\u091F","\u092C\u093E\u0939\u0930 \u0928\u093F\u0915\u0932\u0947\u0902","logout"],signout:["\u0932\u0949\u0917 \u0906\u0909\u091F","\u0938\u093E\u0907\u0928 \u0906\u0909\u091F","\u092C\u093E\u0939\u0930 \u0928\u093F\u0915\u0932\u0947\u0902","logout"]}},lr=ot.en,Et=new Map;function Ys(p){let e=new Map;for(let[t,s]of Object.entries(p)){let n=[X(t),...s.map(r=>X(r))];for(let r of n){e.has(r)||e.set(r,[]);let o=e.get(r);for(let a of n)o.includes(a)||o.push(a)}}return e}for(let[p,e]of Object.entries(ot))Et.set(p.toLowerCase(),Ys(e));function dr(p,e){let t=p.toLowerCase();ot[t]={...ot[t]||{},...e},Et.set(t,Ys(ot[t]))}function ur(){return Object.keys(ot)}function St(p,e="en"){let t=X(p),s=(e||"en").toLowerCase(),i=Et.get(s);if(i){let n=i.get(t);if(n&&n.length>0)return n}if(s!=="en"){let n=Et.get("en");if(n){let r=n.get(t);if(r&&r.length>0)return r}}return[t]}var js=St;var He=class p{memoryDir;currentPackage="global";mappings=new Map;screens=new Map;intents=new Map;dirty=!1;locale="en";setLocale(e){this.locale=(e||"en").toLowerCase()}getLocale(){return this.locale}constructor(e){if(e)this.memoryDir=e;else{let t=Re.dirname(Di(import.meta.url));this.memoryDir=Re.resolve(t,"..","memory")}ge.existsSync(this.memoryDir)||ge.mkdirSync(this.memoryDir,{recursive:!0})}cleanPackageName(e){return(e||"global").replace(/[^a-zA-Z0-9._-]/g,"_")}static SCHEMA_VERSION=2;async init(e){this.currentPackage=this.cleanPackageName(e),this.mappings.clear(),this.screens.clear(),this.intents.clear(),this.dirty=!1;let t=Re.join(this.memoryDir,`${this.currentPackage}.json`);if(ge.existsSync(t))try{let s=await ge.promises.readFile(t,"utf-8"),i=JSON.parse(s);if(i&&i.mappings){let n=!i.version||i.version<2;for(let[r,o]of Object.entries(i.mappings))n&&(o.totalSuccesses=o.totalSuccesses??o.successCount??1,o.recentOutcomes=o.recentOutcomes??(o.failCount>0?["FAIL"]:["PASS"]),o.lastSeenTs=o.lastSeenTs??o.lastUpdated??new Date().toISOString(),this.dirty=!0),this.mappings.set(r,o);if(i.screens)for(let[r,o]of Object.entries(i.screens))this.screens.set(r,o);if(i.intents)for(let[r,o]of Object.entries(i.intents))this.intents.set(r,o);this.decayStaleMappings()}else this.mappings.clear(),this.screens.clear(),this.intents.clear()}catch{this.mappings.clear(),this.screens.clear(),this.intents.clear()}}getCanonicalQuery(e){let t=X(e),s=St(t,this.locale);return s&&s.length>0?s[0]:t}buildKey(e,t){return`${e.toUpperCase()}:${this.getCanonicalQuery(t)}`}resolve(e,t){let s=this.buildKey(e,t),i=this.mappings.get(s);if(i)return i;let n=`${e.toUpperCase()}:${X(t)}`,r=this.mappings.get(n);if(r)return r;let o=St(t,this.locale);for(let a of o){let d=`${e.toUpperCase()}:${a}`,c=this.mappings.get(d);if(c)return c}}getAllCandidates(e,t,s,i){let n=(s||this.locale||"en").toLowerCase(),r=new Set;if(i){let d=this.getScreenElements(i),c=this.getCanonicalQuery(t);for(let l of d)l.action===e.toUpperCase()&&(l.canonicalIntent===c||l.canonicalIntent===X(t))&&l.confidence>=.7&&r.add(l.matchedIdentifier)}let o=this.resolve(e,t);o&&o.confidence>=.8&&r.add(o.matchedIdentifier),r.add(t);let a=St(t,n);for(let d of a)r.add(d);return Array.from(r)}recordSuccess(e,t,s,i,n=1,r,o){if(s.length>35||s.includes("?")||s.includes(`
681
+ `))return;let a=this.buildKey(e,t),d=this.mappings.get(a),c=new Date().toISOString(),l=r||d?.healedFrom?E.memory?.maxHealedConfidence??.65:1,h=r||d?.healedFrom?Math.min(n,l):n;d&&d.matchedIdentifier===s?(d.successCount+=1,d.totalSuccesses=(d.totalSuccesses||0)+1,d.failCount=0,d.recentOutcomes||(d.recentOutcomes=[]),d.recentOutcomes.push("PASS"),d.recentOutcomes.length>5&&d.recentOutcomes.shift(),d.confidence=Math.min(l,Number((d.confidence+.05).toFixed(2))),d.lastUpdated=c,d.lastSeenTs=c,r&&(d.healedFrom=r)):this.mappings.set(a,{canonicalIntent:this.getCanonicalQuery(t),action:e.toUpperCase(),matchedIdentifier:s,matchType:i,confidence:h,successCount:1,failCount:0,totalSuccesses:1,recentOutcomes:["PASS"],lastUpdated:c,lastSeenTs:c,healedFrom:r}),o&&this.associateScreenElement(o,a),this.dirty=!0}associateScreenElement(e,t){if(!e||!t)return;let s=new Date().toISOString(),i=this.screens.get(e);i?(i.elements.includes(t)||i.elements.push(t),i.lastSeenTs=s):this.screens.set(e,{lastSeenTs:s,elements:[t]}),this.dirty=!0}getScreenElements(e){let t=this.screens.get(e);return t?t.elements.map(s=>this.mappings.get(s)).filter(s=>s!==void 0):[]}getScreenIndex(){return Object.fromEntries(this.screens.entries())}markScreenCrawled(e,t){if(!e)return;let s=new Date().toISOString(),i=this.screens.get(e);if(i){if(i.crawled=!0,i.crawledAt=s,i.lastSeenTs=s,t&&t.length>0){i.safeActions||(i.safeActions=[]);for(let n of t)i.safeActions.includes(n)||i.safeActions.push(n)}}else this.screens.set(e,{lastSeenTs:s,elements:[],crawled:!0,crawledAt:s,safeActions:t?[...t]:[]});this.dirty=!0}isScreenCrawled(e){return e?!!this.screens.get(e)?.crawled:!1}getScreenMemory(e){return this.screens.get(e)}getCrawledScreensCount(){let e=0;for(let t of this.screens.values())t.crawled&&e++;return e}recordIntentExpansion(e,t){if(!e||!t||t.length===0)return;let s=X(e),i=new Date().toISOString(),n=this.intents.get(s);n?(n.steps=[...t],n.usageCount=(n.usageCount||1)+1,n.learnedAt=i):this.intents.set(s,{intent:e,steps:[...t],learnedAt:i,usageCount:1}),this.dirty=!0}getIntentExpansion(e){if(!e)return;let t=X(e),s=this.intents.get(t);if(s)return s.usageCount=(s.usageCount||0)+1,this.dirty=!0,[...s.steps]}hasIntentExpansion(e){return e?this.intents.has(X(e)):!1}getIntentExpansionsCount(){return this.intents.size}recordFailure(e,t){let s=this.buildKey(e,t),i=this.mappings.get(s);i&&(i.failCount+=1,i.recentOutcomes||(i.recentOutcomes=[]),i.recentOutcomes.push("FAIL"),i.recentOutcomes.length>5&&i.recentOutcomes.shift(),i.confidence=Math.max(.1,Number((i.confidence-.25).toFixed(2))),i.lastUpdated=new Date().toISOString(),(i.recentOutcomes.filter(r=>r==="FAIL").length>=3||i.confidence<.2)&&this.mappings.delete(s),this.dirty=!0)}decayStaleMappings(e){let s=(e??E.memory?.staleThresholdDays??14)*24*60*60*1e3,i=Date.now(),n=0;for(let r of this.mappings.values()){let o=r.lastSeenTs?new Date(r.lastSeenTs).getTime():0;if(o>0&&i-o>s){let a=E.memory?.staleDecayAmount??.2,d=E.memory?.minConfidenceFloor??.2,c=Math.max(d,Number((r.confidence-a).toFixed(2)));c<r.confidence&&(r.confidence=c,n++,this.dirty=!0)}}return n}async save(){if(!this.dirty)return;let e={packageName:this.currentPackage,version:p.SCHEMA_VERSION,lastUpdated:new Date().toISOString(),mappings:Object.fromEntries(this.mappings.entries()),screens:Object.fromEntries(this.screens.entries()),intents:Object.fromEntries(this.intents.entries())},t=Re.join(this.memoryDir,`${this.currentPackage}.json`),s=`${t}.tmp.${Date.now()}`;await ge.promises.writeFile(s,JSON.stringify(e,null,2),"utf-8");try{await ge.promises.rename(s,t)}catch{await ge.promises.copyFile(s,t),await ge.promises.unlink(s).catch(()=>{})}this.dirty=!1}async exportMemory(e){let t=e?Re.resolve(e):Re.join(this.memoryDir,`${this.currentPackage}-export.json`),s=Re.dirname(t);ge.existsSync(s)||ge.mkdirSync(s,{recursive:!0});let i={packageName:this.currentPackage,version:p.SCHEMA_VERSION,lastUpdated:new Date().toISOString(),mappings:Object.fromEntries(this.mappings.entries()),screens:Object.fromEntries(this.screens.entries()),intents:Object.fromEntries(this.intents.entries())};return await ge.promises.writeFile(t,JSON.stringify(i,null,2),"utf-8"),t}async importMemory(e){let t=Re.resolve(e);if(!ge.existsSync(t))throw new Error(`Memory import source file not found: ${t}`);let s=await ge.promises.readFile(t,"utf-8"),i=JSON.parse(s);if(!i||!i.mappings)throw new Error("Invalid memory file format: missing mappings object.");let n=0,r=new Date().toISOString();for(let[o,a]of Object.entries(i.mappings)){let d=this.mappings.get(o);(!d||a.confidence>=d.confidence)&&(this.mappings.set(o,{...a,totalSuccesses:a.totalSuccesses??a.successCount??1,recentOutcomes:a.recentOutcomes??["PASS"],lastSeenTs:a.lastSeenTs??a.lastUpdated??r,lastUpdated:r}),n++)}if(i.screens)for(let[o,a]of Object.entries(i.screens)){let d=this.screens.get(o);if(!d)this.screens.set(o,a);else{let c=new Set([...d.elements,...a.elements]),l=new Set([...d.safeActions||[],...a.safeActions||[]]);this.screens.set(o,{lastSeenTs:a.lastSeenTs||d.lastSeenTs,elements:Array.from(c),crawled:d.crawled||a.crawled,crawledAt:a.crawledAt||d.crawledAt,safeActions:Array.from(l)})}}if(i.intents)for(let[o,a]of Object.entries(i.intents)){let d=this.intents.get(o);(!d||(a.usageCount||0)>=(d.usageCount||0))&&this.intents.set(o,a)}return n>0&&(this.dirty=!0,await this.save()),n}getMappingsList(){return Array.from(this.mappings.values())}getStats(){let e=Array.from(this.mappings.values()),t=e.reduce((n,r)=>n+(r.totalSuccesses||r.successCount||0),0),s=e.length>0?Number((e.reduce((n,r)=>n+r.confidence,0)/e.length).toFixed(2)):0,i=0;for(let n of this.screens.values())n.crawled&&i++;return{totalMappings:this.mappings.size,totalScreens:this.screens.size,crawledScreens:i,totalIntents:this.intents.size,package:this.currentPackage,totalSuccesses:t,averageConfidence:s}}async clear(e){let t=this.cleanPackageName(e||this.currentPackage),s=Re.join(this.memoryDir,`${t}.json`);return ge.existsSync(s)?(await ge.promises.unlink(s),t===this.currentPackage&&(this.mappings.clear(),this.screens.clear(),this.intents.clear(),this.dirty=!1),!0):!1}},at=new He;import De from"fs";import Ai from"path";import $i from"os";var Vt=new Map;function Ke(p){let e=(p||"default").replace(/[^a-zA-Z0-9._-]/g,"_"),t=Ai.join($i.tmpdir(),`prompttest-${e}.lock`);if(De.existsSync(t))try{let i=De.readFileSync(t,"utf-8").trim(),n=parseInt(i,10);if(!isNaN(n)){if(n===process.pid)return{serial:p,lockFilePath:t,acquired:!0,pid:process.pid};try{throw process.kill(n,0),new Error(`Device "${p}" is locked by another PromptTest process (PID ${n}).
682
+ Wait for the other run to complete, or remove the lock file if it is stale: ${t}`)}catch(r){if(r.code==="ESRCH")try{De.unlinkSync(t)}catch{}else throw r}}}catch(i){let n=i;if(n.message&&n.message.includes("locked by another"))throw n;try{De.unlinkSync(t)}catch{}}try{De.writeFileSync(t,process.pid.toString(),{flag:"wx"})}catch(i){throw i.code==="EEXIST"?new Error(`Device "${p}" was just acquired by a concurrent PromptTest process.`):i}let s=()=>{try{De.existsSync(t)&&De.readFileSync(t,"utf-8").trim()===process.pid.toString()&&De.unlinkSync(t)}catch{}};return Vt.set(t,s),process.once("exit",s),{serial:p,lockFilePath:t,acquired:!0,pid:process.pid}}function ze(p){if(p)try{let e=Vt.get(p.lockFilePath);if(e)process.removeListener("exit",e),Vt.delete(p.lockFilePath),e();else if(De.existsSync(p.lockFilePath))try{De.readFileSync(p.lockFilePath,"utf-8").trim()===process.pid.toString()&&De.unlinkSync(p.lockFilePath)}catch{}}catch{}}import Xt from"chalk";var Wt={DEBUG:0,INFO:1,WARN:2,ERROR:3,SILENT:4},Pt=class{currentLevel="INFO";constructor(e){let t=(process.env.LOG_LEVEL||"").toUpperCase();e?this.currentLevel=e:Wt[t]!==void 0?this.currentLevel=t:this.currentLevel="INFO"}setLevel(e){this.currentLevel=e}getLevel(){return this.currentLevel}isLevelEnabled(e){return Wt[this.currentLevel]<=Wt[e]}isJsonMode(){return(process.env.LOG_FORMAT||"").toLowerCase()==="json"}emitJson(e,...t){let s=t.map(n=>typeof n=="object"?JSON.stringify(n):String(n)).join(" "),i={ts:new Date().toISOString(),level:e,msg:s};e==="ERROR"||e==="WARN"?console.error(JSON.stringify(i)):console.log(JSON.stringify(i))}debug(...e){this.isLevelEnabled("DEBUG")&&(this.isJsonMode()?this.emitJson("DEBUG",...e):console.log(Xt.gray("[DEBUG]"),...e))}info(...e){this.isLevelEnabled("INFO")&&(this.isJsonMode()?this.emitJson("INFO",...e):console.log(...e))}warn(...e){this.isLevelEnabled("WARN")&&(this.isJsonMode()?this.emitJson("WARN",...e):console.warn(Xt.yellow("[WARN]"),...e))}error(...e){this.isLevelEnabled("ERROR")&&(this.isJsonMode()?this.emitJson("ERROR",...e):console.error(Xt.red("[ERROR]"),...e))}},ke=new Pt;import Ue from"fs";import Vs from"path";var Gt=class{checkpointDir;constructor(e){this.checkpointDir=e||Vs.resolve(process.cwd(),"output","checkpoints"),Ue.existsSync(this.checkpointDir)||Ue.mkdirSync(this.checkpointDir,{recursive:!0})}filePath(e){let t=e.replace(/[^a-zA-Z0-9._-]/g,"_");return Vs.join(this.checkpointDir,`${t}.checkpoint.json`)}async save(e,t,s,i){let n={specFile:e,packageName:t,lastPassedStep:s,totalSteps:i,savedAt:new Date().toISOString()},r=this.filePath(e)+`.tmp.${Date.now()}`;await Ue.promises.writeFile(r,JSON.stringify(n,null,2),"utf-8"),await Ue.promises.rename(r,this.filePath(e))}async load(e){let t=this.filePath(e);if(!Ue.existsSync(t))return null;try{let s=await Ue.promises.readFile(t,"utf-8");return JSON.parse(s)}catch{return null}}async clear(e){let t=this.filePath(e);Ue.existsSync(t)&&await Ue.promises.unlink(t)}async getResumeIndex(e){let t=await this.load(e);return t?t.lastPassedStep+1:0}},Xs=new Gt;import ve from"fs";import wt from"path";import{PNG as Je}from"pngjs";import ki from"pixelmatch";var ct=class{baselineDir;defaultThreshold;constructor(e,t=.02){this.baselineDir=e||wt.resolve(process.cwd(),"output","baselines"),this.defaultThreshold=t,ve.existsSync(this.baselineDir)||ve.mkdirSync(this.baselineDir,{recursive:!0})}filePath(e,t){let s=e.replace(/[^a-zA-Z0-9._-]/g,"_");return wt.join(this.baselineDir,`${s}_step${String(t).padStart(3,"0")}.png`)}diffFilePath(e,t){let s=e.replace(/[^a-zA-Z0-9._-]/g,"_");return wt.join(this.baselineDir,`${s}_step${String(t).padStart(3,"0")}_diff.png`)}async saveBaseline(e,t,s){let i=this.filePath(e,t),n=i+`.tmp.${Date.now()}`;return await ve.promises.writeFile(n,s),await ve.promises.rename(n,i),i}hasBaseline(e,t){return ve.existsSync(this.filePath(e,t))}async compare(e,t,s,i){let n=typeof i=="number"?{threshold:i}:i||{},r=this.filePath(e,t),o=wt.join(this.baselineDir,`${e.replace(/[^a-zA-Z0-9._-]/g,"_")}_step${String(t).padStart(3,"0")}_current.png`);await ve.promises.writeFile(o,s);let a=n.threshold??this.defaultThreshold;if(!ve.existsSync(r)){await this.saveBaseline(e,t,s);let w=Je.sync.read(s),A=w.width*w.height;return{stepName:`Step ${t}`,baselineFile:r,currentFile:o,diffRatio:0,diffPixels:0,totalPixels:A,passed:!0,threshold:a}}let d=await ve.promises.readFile(r),c=Je.sync.read(d),l=Je.sync.read(s),h=Math.max(c.width,l.width),u=Math.max(c.height,l.height),g=h*u,f=this.fitToCanvas(c,h,u),y=this.fitToCanvas(l,h,u);n.maskRegions&&n.maskRegions.length>0&&(this.applyMasks(f,n.maskRegions),this.applyMasks(y,n.maskRegions));let S=new Je({width:h,height:u}),b=n.pixelmatchThreshold??.1,m=ki(f.data,y.data,S.data,h,u,{threshold:b,includeAA:!1}),v=g>0?m/g:0,x=v<=a,D;if(m>0){D=this.diffFilePath(e,t);let w=Je.sync.write(S);await ve.promises.writeFile(D,w)}return{stepName:`Step ${t}`,baselineFile:r,currentFile:o,diffRatio:v,diffPixels:m,totalPixels:g,passed:x,threshold:a,diffImagePath:D}}fitToCanvas(e,t,s){if(e.width===t&&e.height===s)return e;let i=new Je({width:t,height:s});return i.data.fill(0),Je.bitblt(e,i,0,0,e.width,e.height,0,0),i}applyMasks(e,t){for(let s of t){let i=Math.min(e.width,s.x+s.width),n=Math.min(e.height,s.y+s.height);for(let r=Math.max(0,s.y);r<n;r++)for(let o=Math.max(0,s.x);o<i;o++){let a=e.width*r+o<<2;e.data[a]=0,e.data[a+1]=0,e.data[a+2]=0,e.data[a+3]=0}}}async clearBaselines(e){let t=e.replace(/[^a-zA-Z0-9._-]/g,"_");if(!ve.existsSync(this.baselineDir))return;let s=await ve.promises.readdir(this.baselineDir);await Promise.all(s.filter(i=>i.startsWith(t+"_step")).map(i=>ve.promises.unlink(wt.join(this.baselineDir,i)).catch(()=>{})))}},Kt=new ct;import se from"chalk";import Ws from"vm";function Y(p){return new Promise(e=>setTimeout(e,p))}function Ci(p){let e=p.screenDimensions.height,t=p.navBarHeight>0?e-p.navBarHeight:e,s=p.navBarHeight>0?t*.94:e*E.gestures.bottomNavThresholdRatio;return{effectiveHeight:t,bottomThreshold:s}}var zt=class{type="TAP";async execute(e,t){let s=e.target,{width:i,height:n}=t.screenDimensions,r=Math.round(i*.5),{flat:o,matched:a}=await t.waitForTarget(s,t.serial,E.polling.defaultTimeoutMs,e);if(a.length===0&&t.upcomingSteps&&t.upcomingSteps.length>0&&!o.some(S=>S.password===!0||S.className.includes("EditText")&&o.some(b=>b.text?.toLowerCase().includes("password")))){let S=t.upcomingSteps.findIndex(m=>m.type==="VERIFY"&&m.target&&t.matchNodes(o,m.target,m).length>0);if(S!==-1)return{fastForwarded:!0,reason:`Screen already displays "${t.upcomingSteps[S].target}"`,skipCount:S};let b=t.upcomingSteps.findIndex(m=>m.type==="TAP"&&m.target&&t.matchNodes(o,m.target,m).length>0);if(b!==-1)return{fastForwarded:!0,reason:`Upcoming action "${t.upcomingSteps[b].target}" is directly actionable`,skipCount:b}}if(a.length===0){await t.driver.swipe(r,Math.round(n*.75),r,Math.round(n*.35),300,t.serial),await Y(350),t.setLastHierarchy(null);let y=await t.waitForTarget(s,t.serial,2e3,e);o=y.flat,a=y.matched}if(a.length===0)throw t.buildDiagnosticError(s,o,`Element matching "${s}" not found on current screen.`);let d=a.find(y=>y.clickable)||a[0];if(await t.ensureInViewport(d,t.serial)){let y=await t.waitForTarget(s,t.serial,1500,e);y.matched.length>0&&(o=y.flat,a=y.matched,d=a.find(S=>S.clickable)||a[0])}let l=d.bounds.centerX,{effectiveHeight:h}=Ci(t),u=d.bounds.centerY;if(d.bounds.y2>h&&(u=Math.min(Math.round((d.bounds.y1+h)/2),h-15)),u=Math.min(u,d.bounds.y2-2),u=Math.max(u,d.bounds.y1+2),u>n*.6&&typeof t.driver.isKeyboardVisible=="function")try{await t.driver.isKeyboardVisible(t.serial)&&(console.log(se.gray(` [Keyboard] Target occluded by soft keyboard (Y=${u} > ${Math.round(n*.6)}). Dismissing...`)),await t.driver.pressBack(t.serial),await Y(300),t.setLastHierarchy(null))}catch{}let g=d.contentDesc||d.text||d.resourceId;console.log(se.gray(` [Tap Target] (${l}, ${u}) for "${g||s}"`));let f=t.lastHierarchy?.hash;await t.driver.tap(l,u,t.serial),await Y(E.settle.tapMs),t.setLastHierarchy(null),g&&X(g)!==X(s)&&t.memory.recordSuccess("TAP",s,g,d.contentDesc?"contentDesc":d.text?"text":"resourceId",1,void 0,f)}},Jt=class{type="LONG_PRESS";async execute(e,t){let s=e.target,{flat:i,matched:n}=await t.waitForTarget(s,t.serial,E.polling.defaultTimeoutMs,e);if(n.length===0)throw t.buildDiagnosticError(s,i,`Element matching "${s}" not found for long-press.`);let r=n[0];if(await t.ensureInViewport(r,t.serial)){let a=await t.waitForTarget(s,t.serial,1500,e);a.matched.length>0&&(r=a.matched[0])}await t.driver.swipe(r.bounds.centerX,r.bounds.centerY,r.bounds.centerX,r.bounds.centerY,E.gestures.longPressDurationMs,t.serial),await Y(300),t.setLastHierarchy(null)}},Dt=class{type="TYPE";async execute(e,t){let s=e.target,i=e.value??"",n=[],r=null;if(t.lastHierarchy&&Date.now()-t.lastHierarchy.timestamp<E.polling.hierarchyCacheTtlMs){let l=t.findTargetInputField(t.lastHierarchy.flat,s,i);l&&(n=t.lastHierarchy.flat,r=l)}if(r||(n=(await t.getCleanHierarchy(t.serial)).flat,r=t.findTargetInputField(n,s,i)),!r){let l=Date.now();for(;Date.now()-l<2e3&&(await Y(200),n=(await t.getCleanHierarchy(t.serial)).flat,r=t.findTargetInputField(n,s,i),!r););}if(!r&&t.upcomingSteps&&t.upcomingSteps.length>0&&!n.some(h=>h.className.includes("EditText"))){let h=t.upcomingSteps.findIndex(u=>u.type==="VERIFY"&&u.target&&t.matchNodes(n,u.target,u).length>0);if(h!==-1)return{fastForwarded:!0,reason:`Screen already displays "${t.upcomingSteps[h].target}" and form is completed`,skipCount:h}}if(!r)throw t.buildDiagnosticError(s,n,`Input field matching "${s}" not found.`);if(r.text&&r.text===i){console.log(se.gray(` [Input Field] Already contains desired value "${i}". Skipping typing.`));return}if(await t.ensureInViewport(r,t.serial)){n=(await t.getCleanHierarchy(t.serial)).flat;let h=t.findTargetInputField(n,s,i);h&&(r=h)}let{height:a}=t.screenDimensions;if(r.bounds.centerY>a*.6&&typeof t.driver.isKeyboardVisible=="function")try{await t.driver.isKeyboardVisible(t.serial)&&(console.log(se.gray(" [Keyboard] Input field occluded by soft keyboard. Dismissing before focus...")),await t.driver.pressBack(t.serial),await Y(300),t.setLastHierarchy(null))}catch{}let d=t.lastHierarchy?.hash;await t.driver.tap(r.bounds.centerX,r.bounds.centerY,t.serial),await Y(E.settle.inputFocusMs),await t.driver.clearField(t.serial),await Y(E.settle.inputClearMs),await t.driver.inputText(i,t.serial),await Y(E.settle.inputDoneMs),t.setLastHierarchy(null);let c=r.contentDesc||r.resourceId;c&&X(c)!==X(s)&&t.memory.recordSuccess("TYPE",s,c,r.contentDesc?"contentDesc":"resourceId",1,void 0,d)}},Qt=class{type="CLEAR";async execute(e,t){let s=e.target,i=[],n=null;if(t.lastHierarchy&&Date.now()-t.lastHierarchy.timestamp<E.polling.hierarchyCacheTtlMs&&(n=t.findTargetInputField(t.lastHierarchy.flat,s),n&&(i=t.lastHierarchy.flat)),n||(i=(await t.getCleanHierarchy(t.serial)).flat,n=t.findTargetInputField(i,s)),!n){let o=t.matchNodes(i,s,e);o.length>0&&(n=o[0])}if(!n)throw t.buildDiagnosticError(s,i,`Input field matching "${s}" not found to clear.`);await t.driver.tap(n.bounds.centerX,n.bounds.centerY,t.serial),await Y(300);let r=t.driver;typeof r.clearField=="function"?await r.clearField(t.serial):typeof r.clearInput=="function"&&await r.clearInput(50,t.serial),await Y(200),t.setLastHierarchy(null)}},qt=class{type="VERIFY";async execute(e,t){let s=e.target,i=e.expectedState||"visible";if(e.negative===!0||i==="absent"||i==="hidden"){let h=await t.getCleanHierarchy(t.serial);if(t.matchNodes(h.flat,s,e).length>0)throw new Error(`Negative assertion failed: "${s}" was expected to be NOT visible, but is present on screen.`);return}let{width:r,height:o}=t.screenDimensions,a=Math.round(r*.5),d=!1,c=[],l;if(t.lastHierarchy&&Date.now()-t.lastHierarchy.timestamp<E.polling.verifyCacheTtlMs&&(l=t.matchNodes(t.lastHierarchy.flat,s,e)[0],l&&(c=t.lastHierarchy.flat,d=!0,t.lastHierarchy.timestamp=Date.now())),!d){let h=Date.now();for(;Date.now()-h<E.polling.extendedTimeoutMs;){if(c=(await t.getCleanHierarchy(t.serial)).flat,l=t.matchNodes(c,s,e)[0],l){d=!0,t.lastHierarchy&&(t.lastHierarchy.timestamp=Date.now()),await Y(400);break}await Y(200)}}if(d||(await t.driver.swipe(a,Math.round(o*.75),a,Math.round(o*.35),300,t.serial),await Y(400),c=(await t.getCleanHierarchy(t.serial)).flat,l=t.matchNodes(c,s,e)[0],l&&(d=!0)),!d){if(t.upcomingSteps&&t.upcomingSteps.length>0&&!c.some(u=>u.password===!0||u.className.includes("EditText")&&c.some(g=>g.text?.toLowerCase().includes("password")))){let u=t.upcomingSteps.findIndex(g=>g.type==="VERIFY"&&g.target&&t.matchNodes(c,g.target,g).length>0);if(u!==-1)return{fastForwarded:!0,reason:`Screen is already on "${t.upcomingSteps[u].target}"`,skipCount:u}}throw await t.driver.swipe(a,Math.round(o*.35),a,Math.round(o*.75),300,t.serial),await Y(300),t.buildDiagnosticError(s,c,`Verification assertion failed: "${s}" is not visible on screen.`)}if(l&&i==="disabled"&&l.enabled)throw new Error(`State assertion failed: "${s}" was expected to be DISABLED, but is enabled.`);if(l&&i==="enabled"&&!l.enabled)throw new Error(`State assertion failed: "${s}" was expected to be ENABLED, but is disabled.`)}},Zt=class{type="BACK";async execute(e,t){await t.driver.pressKey(4,t.serial),await Y(E.settle.backMs),t.setLastHierarchy(null)}},es=class{type="SCROLL";async execute(e,t){let{width:s,height:i}=t.screenDimensions,n=Math.round(s*.5);if(e.target&&e.target!=="up"&&e.target!=="down"){let o=e.target,a=e.direction||"down",d=!1;for(let c=0;c<5;c++){let{flat:l}=await t.getCleanHierarchy(t.serial),h=t.matchNodes(l,o,e);if(h.length>0){await t.ensureInViewport(h[0],t.serial),d=!0;break}a==="up"?await t.driver.swipe(n,Math.round(i*.35),n,Math.round(i*.75),300,t.serial):await t.driver.swipe(n,Math.round(i*.75),n,Math.round(i*.35),300,t.serial),await Y(E.settle.scrollMs),t.setLastHierarchy(null)}if(!d){let{flat:c}=await t.getCleanHierarchy(t.serial);throw t.buildDiagnosticError(o,c,`Element "${o}" not found after scrolling ${e.direction||"down"}.`)}}else e.target==="up"||e.direction==="up"?await t.driver.swipe(n,Math.round(i*.35),n,Math.round(i*.75),300,t.serial):await t.driver.swipe(n,Math.round(i*.75),n,Math.round(i*.35),300,t.serial),await Y(E.settle.scrollMs),t.setLastHierarchy(null)}},ts=class{type="SWIPE";async execute(e,t){let{width:s,height:i}=t.screenDimensions,n=Math.round(s*.5),r=e.direction||"left";if(e.target){let{matched:l}=await t.waitForTarget(e.target,t.serial,2500,e);if(l.length>0){let h=l[0],u=r==="left"?h.bounds.x2-40:r==="right"?h.bounds.x1+40:h.bounds.centerX,g=r==="left"?h.bounds.x1+40:r==="right"?h.bounds.x2-40:h.bounds.centerX,f=r==="up"?h.bounds.y2-40:r==="down"?h.bounds.y1+40:h.bounds.centerY,y=r==="up"?h.bounds.y1+40:r==="down"?h.bounds.y2-40:h.bounds.centerY;await t.driver.swipe(u,f,g,y,E.gestures.swipeDurationMs,t.serial),await Y(400),t.setLastHierarchy(null);return}}let o=r==="left"?Math.round(s*.8):r==="right"?Math.round(s*.2):n,a=r==="left"?Math.round(s*.2):r==="right"?Math.round(s*.8):n,d=Math.round(r==="up"?i*.75:r==="down"?i*.35:i*.5),c=Math.round(r==="up"?i*.35:r==="down"?i*.75:i*.5);await t.driver.swipe(o,d,a,c,E.gestures.swipeDurationMs,t.serial),await Y(400),t.setLastHierarchy(null)}},ss=class{type="TOGGLE";async execute(e,t){let s=e.target,{flat:i,matched:n}=await t.waitForTarget(s,t.serial,E.polling.defaultTimeoutMs,e);if(n.length===0)throw t.buildDiagnosticError(s,i,`Toggle element matching "${s}" not found.`);let r=n.find(a=>a.clickable)||n[0];if(await t.ensureInViewport(r,t.serial)){let a=await t.waitForTarget(s,t.serial,1500,e);a.matched.length>0&&(r=a.matched.find(d=>d.clickable)||a.matched[0])}if(e.desiredState!==void 0&&r.checked!==void 0&&r.checked===e.desiredState){console.log(se.gray(` [Toggle] "${s}" is already in desired state (${e.desiredState?"ON":"OFF"}).`));return}await t.driver.tap(r.bounds.centerX,r.bounds.centerY,t.serial),await Y(E.settle.toggleMs),t.setLastHierarchy(null)}},is=class{type="SELECT";async execute(e,t){let s=e.target,i=e.value,{flat:n,matched:r}=await t.waitForTarget(s,t.serial,E.polling.defaultTimeoutMs,e);if(r.length===0)throw t.buildDiagnosticError(s,n,`Dropdown / picker element matching "${s}" not found.`);let o=r.find(c=>c.clickable)||r[0];await t.driver.tap(o.bounds.centerX,o.bounds.centerY,t.serial),await Y(E.settle.selectMs),t.setLastHierarchy(null);let a=await t.waitForTarget(i,t.serial,E.polling.defaultTimeoutMs);if(a.matched.length===0)throw t.buildDiagnosticError(i,a.flat,`Dropdown option "${i}" not found.`);let d=a.matched[0];await t.driver.tap(d.bounds.centerX,d.bounds.centerY,t.serial),await Y(400),t.setLastHierarchy(null)}},rs=class{type="LAUNCH_APP";async execute(e,t){let s=e.target;if(!s)throw new Error("Target package name required to launch app.");await t.driver.launchApp(s,t.serial),await Y(E.settle.launchMs),t.setLastHierarchy(null)}},ns=class{type="RESTART_APP";async execute(e,t){let s=e.target;if(!s)throw new Error("Target package name required to restart app.");await t.driver.restartApp(s,t.serial),await Y(E.settle.launchMs),t.setLastHierarchy(null)}},os=class{type="TERMINATE_APP";async execute(e,t){let s=e.target||await t.driver.getForegroundPackage(t.serial);s&&await t.driver.forceStop(s,t.serial),await Y(E.settle.stopMs),t.setLastHierarchy(null)}},as=class{type="CLEAR_DATA";async execute(e,t){let s=e.target;if(!s)throw new Error("Target package name required to clear data.");await t.driver.clearAppData(s,t.serial),await Y(1e3),t.setLastHierarchy(null)}},cs=class{type="GRANT_PERMISSION";async execute(e,t){let s=e.value,i=e.target||await t.driver.getForegroundPackage(t.serial);if(!i)throw new Error("Foreground package not detected for grant permission.");await t.driver.grantPermission(i,s,t.serial),await Y(400)}},ls=class{type="DEEP_LINK";async execute(e,t){let s=e.target;await t.driver.openDeepLink(s,t.serial),await Y(E.settle.launchMs),t.setLastHierarchy(null)}},ds=class{type="WAIT";async execute(e,t){await Y(e.durationMs||1e3)}},us=class{type="IF_VISIBLE";async execute(e,t){let s=e.conditionTarget||e.target;if(!s)return;let i=!1;try{let{matched:n}=await t.waitForTarget(s,t.serial,1500,e);i=n.length>0}catch{i=!1}i?(console.log(se.cyan(` [Conditional] Condition met: "${s}" is visible.`)),e.thenSteps&&e.thenSteps.length>0&&t.executeChildSteps&&await t.executeChildSteps(e.thenSteps,t)):(console.log(se.gray(` [Conditional] Condition not met: "${s}" is not visible.`)),e.elseSteps&&e.elseSteps.length>0&&t.executeChildSteps&&await t.executeChildSteps(e.elseSteps,t))}},ps=class{type="LOOP";async execute(e,t){let s=E.flow?.maxLoopIterations||50,i=Math.min(e.loopCount||1,s),n=e.childSteps||[];if(!(n.length===0||!t.executeChildSteps)){console.log(se.cyan(` [Loop] Starting loop iteration (1 to ${i})...`));for(let r=1;r<=i;r++){e.loopVariable&&t.variables.set(e.loopVariable,String(r)),t.loopStack.push({current:r,total:i,variable:e.loopVariable});try{await t.executeChildSteps(n,t)}finally{t.loopStack.pop()}}}}},hs=class{type="WAIT_UNTIL";async execute(e,t){let s=e.target,i=e.durationMs||E.flow?.waitUntilTimeoutMs||1e4,n=e.expectedState||"visible";console.log(se.gray(` [Wait Until] Waiting for "${s}" to be ${n} (up to ${i}ms)...`));let r=Date.now(),o=!1;for(;Date.now()-r<i;){try{let{matched:a}=await t.waitForTarget(s,t.serial,1e3,e);if(a.length>0){let d=a[0];if(n==="enabled"&&!d.enabled){await Y(250);continue}o=!0;break}}catch{}await Y(250)}if(!o){let{flat:a}=await t.getCleanHierarchy(t.serial);throw t.buildDiagnosticError(s,a,`WaitUntil assertion failed: "${s}" did not become ${n} within ${i}ms.`)}}},gs=class{type="SET_VARIABLE";async execute(e,t){let s=e.variableName,i=e.variableExpression||"";i=Xe(i,Object.fromEntries(t.variables));let n=Rs(i);t.variables.set(s,n),console.log(se.cyan(` [Variable] $${s} = "${n}"`))}},ms=class{type="DEVICE_STATE";async execute(e,t){let s=e.deviceAction,i=e.deviceStateValue;switch(s){case"wifi":{let n=i===!0||i==="on"||i==="enable";console.log(se.cyan(` [Device] Setting Wi-Fi: ${n?"ENABLED":"DISABLED"}`)),await t.driver.setWifiEnabled(n,t.serial);break}case"airplane":{let n=i===!0||i==="on"||i==="enable";console.log(se.cyan(` [Device] Setting Airplane Mode: ${n?"ENABLED":"DISABLED"}`)),await t.driver.setAirplaneMode(n,t.serial);break}case"orientation":{let n=i==="landscape"?"landscape":"portrait";console.log(se.cyan(` [Device] Setting Orientation: ${n.toUpperCase()}`)),await t.driver.setOrientation(n,t.serial);break}case"notifications":{let n=i==="open"||i==="expand"||i===!0;console.log(se.cyan(` [Device] ${n?"Expanding":"Collapsing"} Notification Shade`)),n?await t.driver.openNotificationShade(t.serial):await t.driver.collapseNotificationShade(t.serial);break}default:throw new Error(`Unsupported device action: ${s}`)}await Y(400),t.setLastHierarchy(null)}},fs=class{type="RUN_JS";async execute(e,t){let s=e.jsCode||e.value||"";if(!s)return;console.log(se.cyan(" [JS Hook] Executing sandboxed JavaScript snippet..."));let i={vars:Object.fromEntries(t.variables),setVar:(r,o)=>{t.variables.set(r,String(o))},getVar:r=>t.variables.get(r),console:{log:(...r)=>console.log(se.gray(" [JS Output]",...r)),error:(...r)=>console.error(se.red(" [JS Error]",...r))}},n=Ws.createContext(i);Ws.runInContext(s,n,{timeout:3e3});for(let[r,o]of Object.entries(i.vars))t.variables.set(r,String(o))}},bs=class{type="ENTER_OTP";async execute(e,t){console.log(se.cyan(" [OTP Capture] Detecting verification code..."));let s=null;if(process.env.PROMPTTEST_MOCK_OTP)s=process.env.PROMPTTEST_MOCK_OTP.trim(),console.log(se.gray(` [OTP Capture] Captured code from environment: ${s}`));else try{let{stdout:i}=await t.driver.execAdb(["shell","logcat","-d","-t","200","-s","SMSDispatcher:V","SmsMessage:V","NotificationService:V","ActivityManager:I"],t.serial),n=i.match(/(?:code|otp|pin|verification)[^0-9\r\n]{0,35}(\d{4,8})\b/i)||i.match(/\b(\d{4,8})\s*(?:is your verification|is your otp)/i);n&&(s=n[1],console.log(se.gray(` [OTP Capture] Captured code from logcat: ${s}`)))}catch{}if(s||(s="123456",console.log(se.yellow(` [OTP Capture] No live code detected; using simulated OTP: ${s}`))),e.target){let i={originalText:`Type '${s}' into '${e.target}'`,type:"TYPE",target:e.target,value:s};return new Dt().execute(i,t)}else{let{flat:i}=await t.getCleanHierarchy(t.serial),n=t.findTargetInputField(i,"code",s)||i.find(r=>r.className.includes("EditText"));n?(await t.driver.tap(n.bounds.centerX,n.bounds.centerY,t.serial),await Y(250),await t.driver.inputText(s,t.serial)):await t.driver.inputText(s,t.serial)}}},ys=class{type="API_REQUEST";async execute(e,t){let s=e.apiMethod||"GET",i=e.apiUrl||"";if(!i)throw new Error("API_REQUEST requires a valid target URL.");console.log(se.cyan(` [API Request] ${s} ${i}...`));let n={method:s,headers:{"Content-Type":"application/json",Accept:"application/json"}};e.apiBody&&(s==="POST"||s==="PUT"||s==="PATCH")&&(n.body=e.apiBody);let r=await fetch(i,n);if(e.apiExpectedStatus!==void 0){if(r.status!==e.apiExpectedStatus)throw new Error(`API status assertion failed for ${i}: expected HTTP ${e.apiExpectedStatus}, but received HTTP ${r.status}`);console.log(se.green(` \u2714 API Status HTTP ${r.status} matched expectation.`))}if(e.apiStorePath&&e.apiStoreVariable)try{let o=await r.text(),a=JSON.parse(o),d=this.resolveJsonPath(a,e.apiStorePath);d!==void 0&&(t.variables.set(e.apiStoreVariable,String(d)),console.log(se.cyan(` [Variable] $${e.apiStoreVariable} = "${d}" (from ${e.apiStorePath})`)))}catch(o){ke.warn(`Failed to parse JSON response for path extraction: ${o.message}`)}}resolveJsonPath(e,t){let s=t.replace(/^\$\.?/,"").split("."),i=e;for(let n of s){if(i==null||typeof i!="object")return;i=i[n]}return i}},Ss=class{type="EMAIL_ASSERT";async execute(e,t){let s=e.emailRecipient||"",i=e.emailSubject||"";console.log(se.cyan(` [Email Assertion] Checking email to "${s}" with subject "${i}"...`));let n=[];if(process.env.PROMPTTEST_MOCK_EMAILS)try{n=JSON.parse(process.env.PROMPTTEST_MOCK_EMAILS)}catch{n=[]}let r=n.find(o=>o.to.toLowerCase()===s.toLowerCase()&&o.subject.toLowerCase().includes(i.toLowerCase()));if(!r){if(n.length===0){if(!s.includes("@"))throw new Error(`Invalid email recipient address: "${s}"`);console.log(se.yellow(" \u26A0 No mock inbox configured (PROMPTTEST_MOCK_EMAILS); simulated email check passed."));return}throw new Error(`Email assertion failed: No email to "${s}" with subject "${i}" found.`)}if(e.emailBodyContains&&r.body&&!r.body.includes(e.emailBodyContains))throw new Error(`Email body assertion failed: Expected email to contain "${e.emailBodyContains}", but content did not match.`);console.log(se.green(" \u2714 Email verified successfully."))}},Ii=[new zt,new Jt,new Dt,new Qt,new qt,new Zt,new es,new ts,new ss,new is,new rs,new ns,new os,new as,new cs,new ls,new ds,new us,new ps,new hs,new gs,new ms,new fs,new bs,new ys,new Ss],Gs=new Map(Ii.map(p=>[p.type,p]));var Qe=class{providerName="heuristic";async resolveIntent(e,t){let s=X(e);return(s.includes("login")||s.includes("log in")||s.includes("sign in")||s.includes("signin"))&&(s.includes("test user")||s.includes("default credentials")||s.includes("credentials"))?[{originalText:"Type 'user@example.com' into 'Email'",type:"TYPE",target:"Email",value:"user@example.com"},{originalText:"Type 'Password123!' into 'Password'",type:"TYPE",target:"Password",value:"Password123!"},{originalText:"Tap 'Sign In'",type:"TAP",target:"Sign In"}]:s.includes("sign up with random user")||s.includes("register new user")?[{originalText:"Type $RANDOM_NAME into 'Name'",type:"TYPE",target:"Name",value:"$RANDOM_NAME"},{originalText:"Type $RANDOM_EMAIL into 'Email'",type:"TYPE",target:"Email",value:"$RANDOM_EMAIL"},{originalText:"Type 'Password123!' into 'Password'",type:"TYPE",target:"Password",value:"Password123!"},{originalText:"Tap 'Create Account'",type:"TAP",target:"Create Account"}]:s.includes("dismiss dialog")||s.includes("close modal")||s.includes("dismiss popup")?[{originalText:"Tap 'Close'",type:"TAP",target:"Close",optional:!0},{originalText:"Tap 'Dismiss'",type:"TAP",target:"Dismiss",optional:!0},{originalText:"Press back",type:"BACK",optional:!0}]:null}async findSuggestions(e,t,s){let i=[],n=X(e),r=new Set,o=js(e,s?.locale);for(let l of o){let h=t.find(u=>u.bounds.width>0&&u.bounds.height>0&&(z(l,u.text)||z(l,u.contentDesc)));if(h){let u=(h.text||h.contentDesc||l).trim();r.has(u)||(r.add(u),i.push({text:u,score:.9,node:h,strategy:"synonym",reason:`Direct synonym match for "${e}" via semantic dictionary`}))}}for(let l of t)if(l.resourceId&&l.bounds.width>0&&l.bounds.height>0&&l.resourceId.toLowerCase().split(/[:/_]/).some(g=>g===n||n.includes(g))){let g=(l.text||l.contentDesc||l.resourceId).trim();r.has(g)||(r.add(g),i.push({text:g,score:.85,node:l,strategy:"exact",reason:`Resource-ID segment matches target "${e}"`}))}let a=[];for(let l of t)l.bounds.width>0&&l.bounds.height>0&&(l.text&&l.text.trim().length>1&&a.push({text:l.text.trim(),node:l}),l.contentDesc&&l.contentDesc.trim().length>1&&a.push({text:l.contentDesc.trim(),node:l}));let d=Array.from(new Set(a.map(l=>l.text))),c=We(e,d,5);for(let l of c)if(l.score>=.7&&!r.has(l.text)){r.add(l.text);let h=a.find(u=>u.text===l.text)?.node;i.push({text:l.text,score:l.score,node:h,strategy:"fuzzy",reason:`String similarity match (${Math.round(l.score*100)}%)`})}return i.sort((l,h)=>h.score-l.score)}};var lt=class{providerName="mock";mockIntents=new Map;mockSuggestions=new Map;constructor(){this.mockIntents.set("log in to account",[{originalText:"Type 'test@example.com' into 'Email'",type:"TYPE",target:"Email",value:"test@example.com"},{originalText:"Type 'Password123' into 'Password'",type:"TYPE",target:"Password",value:"Password123"},{originalText:"Tap 'Sign In'",type:"TAP",target:"Sign In"}])}setMockIntent(e,t){this.mockIntents.set(e.toLowerCase().trim(),t)}setMockSuggestion(e,t){this.mockSuggestions.set(e.toLowerCase().trim(),t)}async resolveIntent(e,t){let s=e.toLowerCase().trim();return this.mockIntents.has(s)?this.mockIntents.get(s):null}async findSuggestions(e,t,s){let i=e.toLowerCase().trim();return this.mockSuggestions.has(i)?this.mockSuggestions.get(i):new Qe().findSuggestions(e,t)}},At=class{providerName;config;heuristicFallback;constructor(e){this.config=e,this.providerName=e.provider,this.heuristicFallback=new Qe}async resolveIntent(e,t){if(this.config.provider==="mock")return new lt().resolveIntent(e,t);try{let s=`You are a test automation engineer generating steps for PromptTest.
683
683
  Convert the following high-level user intent into a concrete sequence of plain-English test steps.
684
684
  Valid syntax examples:
685
685
  - Tap 'Button Label'
@@ -692,95 +692,95 @@ Valid syntax examples:
692
692
  User Intent: "${e}"
693
693
 
694
694
  Return ONLY a JSON array of plain strings representing each step, e.g.:
695
- ["Type 'user@test.com' into 'Email'", "Tap 'Next'"]`,i=await this.callLlm(s);if(!i)return this.heuristicFallback.resolveIntent(e,t);let n=i.match(/\[[\s\S]*\]/);return n?JSON.parse(n[0]).map(a=>({originalText:a,type:a.startsWith("Tap")?"TAP":a.startsWith("Type")?"TYPE":"VERIFY"})):this.heuristicFallback.resolveIntent(e,t)}catch(s){return ke.warn(`LLM intent resolution failed (${s.message}), falling back to heuristic engine.`),this.heuristicFallback.resolveIntent(e,t)}}async findSuggestions(e,t,s){if(this.config.provider==="mock")return new lt().findSuggestions(e,t,s);try{let i=t.filter(l=>l.bounds.width>0&&l.bounds.height>0&&(l.text||l.contentDesc)).map(l=>({text:l.text||l.contentDesc,id:l.resourceId||"",class:l.className.split(".").pop()})).slice(0,30),n=`A UI test failed because an element named "${e}" could not be found.
695
+ ["Type 'user@test.com' into 'Email'", "Tap 'Next'"]`,i=await this.callLlm(s);if(!i)return this.heuristicFallback.resolveIntent(e,t);let n=i.match(/\[[\s\S]*\]/);return n?JSON.parse(n[0]).map(a=>({originalText:a,type:a.startsWith("Tap")?"TAP":a.startsWith("Type")?"TYPE":"VERIFY"})):this.heuristicFallback.resolveIntent(e,t)}catch(s){return ke.warn(`LLM intent resolution failed (${s.message}), falling back to heuristic engine.`),this.heuristicFallback.resolveIntent(e,t)}}async findSuggestions(e,t,s){if(this.config.provider==="mock")return new lt().findSuggestions(e,t,s);try{let i=t.filter(d=>d.bounds.width>0&&d.bounds.height>0&&(d.text||d.contentDesc)).map(d=>({text:d.text||d.contentDesc,id:d.resourceId||"",class:d.className.split(".").pop()})).slice(0,30),n=`A UI test failed because an element named "${e}" could not be found.
696
696
  Here are the visible UI elements on the current Android screen:
697
697
  ${JSON.stringify(i,null,2)}
698
698
 
699
699
  Identify the best matching replacement element for "${e}".
700
700
  Respond ONLY with a JSON object in this format:
701
- {"bestMatch": "Exact Text of Best Element", "confidence": 0.85, "reason": "Reason for match"}`,r=await this.callLlm(n);if(!r)return this.heuristicFallback.findSuggestions(e,t,s);let o=r.match(/\{[\s\S]*\}/);if(!o)return this.heuristicFallback.findSuggestions(e,t,s);let a=JSON.parse(o[0]);if(a.bestMatch){let l=t.find(c=>c.text===a.bestMatch||c.contentDesc===a.bestMatch);return[{text:a.bestMatch,score:typeof a.confidence=="number"?a.confidence:.85,node:l,strategy:"llm",reason:a.reason||"LLM semantic match"},...await this.heuristicFallback.findSuggestions(e,t,s)]}}catch(i){ke.warn(`LLM self-healing failed (${i.message}), using heuristic suggestions.`)}return this.heuristicFallback.findSuggestions(e,t,s)}async callLlm(e){let t=this.config.timeoutMs||8e3,s=new AbortController,i=setTimeout(()=>s.abort(),t);try{if(this.config.provider==="openai"){let n=this.config.apiKey||process.env.OPENAI_API_KEY;if(!n)throw new Error("OPENAI_API_KEY is not set");let r=await fetch("https://api.openai.com/v1/chat/completions",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${n}`},body:JSON.stringify({model:this.config.model||"gpt-4o-mini",messages:[{role:"user",content:e}],temperature:.1}),signal:s.signal});if(!r.ok)throw new Error(`OpenAI HTTP ${r.status}: ${await r.text()}`);return(await r.json()).choices?.[0]?.message?.content||null}if(this.config.provider==="anthropic"){let n=this.config.apiKey||process.env.ANTHROPIC_API_KEY;if(!n)throw new Error("ANTHROPIC_API_KEY is not set");let r=await fetch("https://api.anthropic.com/v1/messages",{method:"POST",headers:{"Content-Type":"application/json","x-api-key":n,"anthropic-version":"2023-06-01"},body:JSON.stringify({model:this.config.model||"claude-3-haiku-20240307",max_tokens:1024,messages:[{role:"user",content:e}]}),signal:s.signal});if(!r.ok)throw new Error(`Anthropic HTTP ${r.status}: ${await r.text()}`);return(await r.json()).content?.[0]?.text||null}if(this.config.provider==="ollama"){let n=this.config.endpoint||process.env.OLLAMA_BASE_URL||"http://localhost:11434",r=await fetch(`${n.replace(/\/$/,"")}/api/chat`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({model:this.config.model||"llama3.2",messages:[{role:"user",content:e}],stream:!1}),signal:s.signal});if(!r.ok)throw new Error(`Ollama HTTP ${r.status}: ${await r.text()}`);return(await r.json()).message?.content||null}return null}finally{clearTimeout(i)}}};function ws(u){let e=u?.provider||T.ai.provider;if(e==="heuristic")return new Qe;if(e==="mock")return new lt;let t={provider:e,model:u?.model||T.ai.model,endpoint:u?.endpoint||T.ai.endpoint};return new At(t)}import Ks from"fs";import vs from"path";var dt=class{static extractDataDirective(e,t=process.cwd()){let s=e.split(`
702
- `),i="",n=-1;for(let c=0;c<s.length;c++){let p=s[c].trim();if(p.startsWith("#!data")||p.startsWith("#! data")){i=p,n=c;break}}if(n===-1)return null;let r=i.replace(/^#!\s*data\s*/,"").trim(),o=[],a="inline";if(r.startsWith("[")||r.startsWith("{"))try{let c=JSON.parse(r);o=Array.isArray(c)?c.map(p=>this.stringifyObject(p)):[this.stringifyObject(c)]}catch(c){throw new Error(`Failed to parse inline #!data JSON directive: ${c.message}`)}else{let c=r.replace(/^['"]+|['"]+$/g,"").trim(),p=vs.isAbsolute(c)?c:vs.resolve(t,c);a=p,o=this.loadFromFile(p)}let l=[...s];return l.splice(n,1),{directive:i,source:a,cleanedSpec:l.join(`
703
- `),rows:o}}static loadFromFile(e){if(!Ks.existsSync(e))throw new Error(`Data file not found: ${e}`);let t=Ks.readFileSync(e,"utf-8");return vs.extname(e).toLowerCase()===".json"?this.parseJson(t):this.parseCsv(t)}static parseJson(e){try{let t=JSON.parse(e);return Array.isArray(t)?t.map(s=>this.stringifyObject(s)):[this.stringifyObject(t)]}catch(t){throw new Error(`Invalid JSON data file format: ${t.message}`)}}static parseCsv(e){let t=this.splitCsvLines(e);if(t.length<2)return[];let s=this.parseCsvRow(t[0]).map(n=>n.trim().replace(/^['"]+|['"]+$/g,"")),i=[];for(let n=1;n<t.length;n++){if(!t[n].trim())continue;let o=this.parseCsvRow(t[n]),a={};for(let l=0;l<s.length;l++){let c=s[l];a[c]=o[l]!==void 0?o[l].trim():""}i.push(a)}return i}static filterRows(e,t){if(!t)return e;let s=[...e];if(t.onlyRow!==void 0&&t.onlyRow>0){let i=t.onlyRow-1;if(i<s.length)return[s[i]];throw new Error(`Requested --only-row=${t.onlyRow}, but dataset only contains ${s.length} row(s).`)}if(t.iterations!==void 0&&t.iterations>0){if(t.iterations<=s.length)return s.slice(0,t.iterations);let i=[];for(let n=0;n<t.iterations;n++)i.push(s[n%s.length]);return i}return s}static parseCsvRow(e){let t=[],s="",i=!1;for(let n=0;n<e.length;n++){let r=e[n];r==='"'?i&&e[n+1]==='"'?(s+='"',n++):i=!i:r===","&&!i?(t.push(s),s=""):s+=r}return t.push(s),t}static splitCsvLines(e){let t=[],s="",i=!1;for(let n=0;n<e.length;n++){let r=e[n];r==='"'?i&&e[n+1]==='"'?(s+='""',n++):(i=!i,s+=r):(r===`
701
+ {"bestMatch": "Exact Text of Best Element", "confidence": 0.85, "reason": "Reason for match"}`,r=await this.callLlm(n);if(!r)return this.heuristicFallback.findSuggestions(e,t,s);let o=r.match(/\{[\s\S]*\}/);if(!o)return this.heuristicFallback.findSuggestions(e,t,s);let a=JSON.parse(o[0]);if(a.bestMatch){let d=t.find(c=>c.text===a.bestMatch||c.contentDesc===a.bestMatch);return[{text:a.bestMatch,score:typeof a.confidence=="number"?a.confidence:.85,node:d,strategy:"llm",reason:a.reason||"LLM semantic match"},...await this.heuristicFallback.findSuggestions(e,t,s)]}}catch(i){ke.warn(`LLM self-healing failed (${i.message}), using heuristic suggestions.`)}return this.heuristicFallback.findSuggestions(e,t,s)}async callLlm(e){let t=this.config.timeoutMs||8e3,s=new AbortController,i=setTimeout(()=>s.abort(),t);try{if(this.config.provider==="openai"){let n=this.config.apiKey||process.env.OPENAI_API_KEY;if(!n)throw new Error("OPENAI_API_KEY is not set");let r=await fetch("https://api.openai.com/v1/chat/completions",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${n}`},body:JSON.stringify({model:this.config.model||"gpt-4o-mini",messages:[{role:"user",content:e}],temperature:.1}),signal:s.signal});if(!r.ok)throw new Error(`OpenAI HTTP ${r.status}: ${await r.text()}`);return(await r.json()).choices?.[0]?.message?.content||null}if(this.config.provider==="anthropic"){let n=this.config.apiKey||process.env.ANTHROPIC_API_KEY;if(!n)throw new Error("ANTHROPIC_API_KEY is not set");let r=await fetch("https://api.anthropic.com/v1/messages",{method:"POST",headers:{"Content-Type":"application/json","x-api-key":n,"anthropic-version":"2023-06-01"},body:JSON.stringify({model:this.config.model||"claude-3-haiku-20240307",max_tokens:1024,messages:[{role:"user",content:e}]}),signal:s.signal});if(!r.ok)throw new Error(`Anthropic HTTP ${r.status}: ${await r.text()}`);return(await r.json()).content?.[0]?.text||null}if(this.config.provider==="ollama"){let n=this.config.endpoint||process.env.OLLAMA_BASE_URL||"http://localhost:11434",r=await fetch(`${n.replace(/\/$/,"")}/api/chat`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({model:this.config.model||"llama3.2",messages:[{role:"user",content:e}],stream:!1}),signal:s.signal});if(!r.ok)throw new Error(`Ollama HTTP ${r.status}: ${await r.text()}`);return(await r.json()).message?.content||null}return null}finally{clearTimeout(i)}}};function ws(p){let e=p?.provider||E.ai.provider;if(e==="heuristic")return new Qe;if(e==="mock")return new lt;let t={provider:e,model:p?.model||E.ai.model,endpoint:p?.endpoint||E.ai.endpoint};return new At(t)}import Ks from"fs";import vs from"path";var dt=class{static extractDataDirective(e,t=process.cwd()){let s=e.split(`
702
+ `),i="",n=-1;for(let c=0;c<s.length;c++){let l=s[c].trim();if(l.startsWith("#!data")||l.startsWith("#! data")){i=l,n=c;break}}if(n===-1)return null;let r=i.replace(/^#!\s*data\s*/,"").trim(),o=[],a="inline";if(r.startsWith("[")||r.startsWith("{"))try{let c=JSON.parse(r);o=Array.isArray(c)?c.map(l=>this.stringifyObject(l)):[this.stringifyObject(c)]}catch(c){throw new Error(`Failed to parse inline #!data JSON directive: ${c.message}`)}else{let c=r.replace(/^['"]+|['"]+$/g,"").trim(),l=vs.isAbsolute(c)?c:vs.resolve(t,c);a=l,o=this.loadFromFile(l)}let d=[...s];return d.splice(n,1),{directive:i,source:a,cleanedSpec:d.join(`
703
+ `),rows:o}}static loadFromFile(e){if(!Ks.existsSync(e))throw new Error(`Data file not found: ${e}`);let t=Ks.readFileSync(e,"utf-8");return vs.extname(e).toLowerCase()===".json"?this.parseJson(t):this.parseCsv(t)}static parseJson(e){try{let t=JSON.parse(e);return Array.isArray(t)?t.map(s=>this.stringifyObject(s)):[this.stringifyObject(t)]}catch(t){throw new Error(`Invalid JSON data file format: ${t.message}`)}}static parseCsv(e){let t=this.splitCsvLines(e);if(t.length<2)return[];let s=this.parseCsvRow(t[0]).map(n=>n.trim().replace(/^['"]+|['"]+$/g,"")),i=[];for(let n=1;n<t.length;n++){if(!t[n].trim())continue;let o=this.parseCsvRow(t[n]),a={};for(let d=0;d<s.length;d++){let c=s[d];a[c]=o[d]!==void 0?o[d].trim():""}i.push(a)}return i}static filterRows(e,t){if(!t)return e;let s=[...e];if(t.onlyRow!==void 0&&t.onlyRow>0){let i=t.onlyRow-1;if(i<s.length)return[s[i]];throw new Error(`Requested --only-row=${t.onlyRow}, but dataset only contains ${s.length} row(s).`)}if(t.iterations!==void 0&&t.iterations>0){if(t.iterations<=s.length)return s.slice(0,t.iterations);let i=[];for(let n=0;n<t.iterations;n++)i.push(s[n%s.length]);return i}return s}static parseCsvRow(e){let t=[],s="",i=!1;for(let n=0;n<e.length;n++){let r=e[n];r==='"'?i&&e[n+1]==='"'?(s+='"',n++):i=!i:r===","&&!i?(t.push(s),s=""):s+=r}return t.push(s),t}static splitCsvLines(e){let t=[],s="",i=!1;for(let n=0;n<e.length;n++){let r=e[n];r==='"'?i&&e[n+1]==='"'?(s+='""',n++):(i=!i,s+=r):(r===`
704
704
  `||r==="\r")&&!i?(r==="\r"&&e[n+1]===`
705
- `&&n++,s.trim().length>0&&t.push(s),s=""):s+=r}return s.trim().length>0&&t.push(s),t}static stringifyObject(e){if(!e||typeof e!="object")return{};let t={};for(let[s,i]of Object.entries(e))t[s]=i!=null?String(i):"";return t}};import Ii from"http";import xs from"fs";import $t from"path";var Li={".html":"text/html; charset=utf-8",".json":"application/json; charset=utf-8",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".svg":"image/svg+xml",".mp4":"video/mp4",".log":"text/plain; charset=utf-8",".txt":"text/plain; charset=utf-8",".xml":"application/xml; charset=utf-8"};async function zs(u={}){let e=u.port??4040,t=u.host||"127.0.0.1",s=u.outputDir?$t.resolve(u.outputDir):$t.resolve(process.cwd(),"output"),i=u.suiteName||"PromptTest Live Monitor",n=u.initialReport||{packageName:"PromptTest Execution",deviceId:"Live Device",startTime:new Date().toISOString(),endTime:new Date().toISOString(),durationSeconds:0,totalSteps:0,passedSteps:0,failedSteps:0,skippedSteps:0,warnSteps:0,errorsDetected:[],steps:[]},r=new Set,o=setInterval(()=>{for(let d of r)try{d.write(`: heartbeat
705
+ `&&n++,s.trim().length>0&&t.push(s),s=""):s+=r}return s.trim().length>0&&t.push(s),t}static stringifyObject(e){if(!e||typeof e!="object")return{};let t={};for(let[s,i]of Object.entries(e))t[s]=i!=null?String(i):"";return t}};import Li from"http";import xs from"fs";import $t from"path";var Ri={".html":"text/html; charset=utf-8",".json":"application/json; charset=utf-8",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".svg":"image/svg+xml",".mp4":"video/mp4",".log":"text/plain; charset=utf-8",".txt":"text/plain; charset=utf-8",".xml":"application/xml; charset=utf-8"};async function zs(p={}){let e=p.port??4040,t=p.host||"127.0.0.1",s=p.outputDir?$t.resolve(p.outputDir):$t.resolve(process.cwd(),"output"),i=p.suiteName||"PromptTest Live Monitor",n=p.initialReport||{packageName:"PromptTest Execution",deviceId:"Live Device",startTime:new Date().toISOString(),endTime:new Date().toISOString(),durationSeconds:0,totalSteps:0,passedSteps:0,failedSteps:0,skippedSteps:0,warnSteps:0,errorsDetected:[],steps:[]},r=new Set,o=setInterval(()=>{for(let u of r)try{u.write(`: heartbeat
706
706
 
707
- `)}catch{r.delete(d)}},15e3),a=Ii.createServer((d,g)=>{let f=new URL(d.url||"/",`http://${t}:${e}`),y=decodeURIComponent(f.pathname);if(y==="/events"){g.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache, no-transform",Connection:"keep-alive","Access-Control-Allow-Origin":"*"}),g.write(`event: connected
707
+ `)}catch{r.delete(u)}},15e3),a=Li.createServer((u,g)=>{let f=new URL(u.url||"/",`http://${t}:${e}`),y=decodeURIComponent(f.pathname);if(y==="/events"){g.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache, no-transform",Connection:"keep-alive","Access-Control-Allow-Origin":"*"}),g.write(`event: connected
708
708
  data: ${JSON.stringify({status:"connected",time:Date.now()})}
709
709
 
710
- `),r.add(g),d.on("close",()=>{r.delete(g)});return}if(y==="/"||y==="/report"||y==="/index.html"){let m=jt(n,{suiteName:i});g.writeHead(200,{"Content-Type":"text/html; charset=utf-8","Cache-Control":"no-cache"}),g.end(m);return}if(y==="/api/report"||y==="/results.json"){g.writeHead(200,{"Content-Type":"application/json; charset=utf-8","Access-Control-Allow-Origin":"*"}),g.end(JSON.stringify(n,null,2));return}let S=y.replace(/^\/+/,""),b=$t.join(s,S);if(!b.startsWith(s)){g.writeHead(403,{"Content-Type":"text/plain"}),g.end("Access Denied");return}if(xs.existsSync(b)&&xs.statSync(b).isFile()){let m=$t.extname(b).toLowerCase(),v=Li[m]||"application/octet-stream";g.writeHead(200,{"Content-Type":v,"Cache-Control":"no-cache"}),xs.createReadStream(b).pipe(g);return}g.writeHead(404,{"Content-Type":"text/plain"}),g.end("Not Found")});await new Promise((d,g)=>{a.once("error",g),a.listen(e,t,()=>{d()})});let l=a.address(),c=typeof l=="object"&&l?l.port:e,p=`http://${t}:${c}`;function h(d,g){let f=`event: ${d}
710
+ `),r.add(g),u.on("close",()=>{r.delete(g)});return}if(y==="/"||y==="/report"||y==="/index.html"){let m=jt(n,{suiteName:i});g.writeHead(200,{"Content-Type":"text/html; charset=utf-8","Cache-Control":"no-cache"}),g.end(m);return}if(y==="/api/report"||y==="/results.json"){g.writeHead(200,{"Content-Type":"application/json; charset=utf-8","Access-Control-Allow-Origin":"*"}),g.end(JSON.stringify(n,null,2));return}let S=y.replace(/^\/+/,""),b=$t.join(s,S);if(!b.startsWith(s)){g.writeHead(403,{"Content-Type":"text/plain"}),g.end("Access Denied");return}if(xs.existsSync(b)&&xs.statSync(b).isFile()){let m=$t.extname(b).toLowerCase(),v=Ri[m]||"application/octet-stream";g.writeHead(200,{"Content-Type":v,"Cache-Control":"no-cache"}),xs.createReadStream(b).pipe(g);return}g.writeHead(404,{"Content-Type":"text/plain"}),g.end("Not Found")});await new Promise((u,g)=>{a.once("error",g),a.listen(e,t,()=>{u()})});let d=a.address(),c=typeof d=="object"&&d?d.port:e,l=`http://${t}:${c}`;function h(u,g){let f=`event: ${u}
711
711
  data: ${JSON.stringify(g)}
712
712
 
713
- `;for(let y of r)try{y.write(f)}catch{r.delete(y)}}return{server:a,port:c,url:p,broadcastStep(d){n.steps.push(d),n.totalSteps=n.steps.length,d.status==="PASS"?n.passedSteps++:d.status==="FAIL"?n.failedSteps++:d.status==="WARN"?n.warnSteps++:d.status==="SKIPPED"&&n.skippedSteps++,h("step",d)},broadcastComplete(d){n=d,h("complete",d)},broadcastError(d){n.errorsDetected.push(d),h("error",{error:d})},updateReport(d){n=d},async close(){clearInterval(o);for(let d of r)try{d.end()}catch{}r.clear(),await new Promise((d,g)=>{a.close(f=>{f?g(f):d()})})}}}import Js from"fs";import kt from"path";import ie from"chalk";function Ts(u,e=new Set){let t=kt.resolve(u);if(!Js.existsSync(t))throw new Error(`Included spec file not found: ${t}`);if(e.has(t)){let r=Array.from(e).concat(t);throw new mt(`Circular spec inclusion detected: ${r.join(" -> ")}`,r)}e.add(t);let i=Js.readFileSync(t,"utf-8").split(`
714
- `),n=[];for(let r of i){let o=r.trim(),a=o.match(O.INCLUDE_SPEC);if(a&&!o.startsWith("#")){let l=W([a[1],a[2],a[3]]),c=kt.isAbsolute(l)?l:kt.resolve(kt.dirname(t),l),p=Ts(c,new Set(e));n.push(p)}else n.push(r)}return n.join(`
715
- `)}function Ri(u){let e=[],t=[];for(let s of u){if(s._isControl==="END"){t.length>0&&t.pop();continue}if(s._isControl==="ELSE"){t.length>0&&t[t.length-1].step.type==="IF_VISIBLE"&&(t[t.length-1].inElse=!0);continue}let i=e;if(t.length>0){let n=t[t.length-1];n.step.type==="IF_VISIBLE"?n.inElse?(n.step.elseSteps=n.step.elseSteps||[],i=n.step.elseSteps):(n.step.thenSteps=n.step.thenSteps||[],i=n.step.thenSteps):n.step.type==="LOOP"&&(n.step.childSteps=n.step.childSteps||[],i=n.step.childSteps)}i.push(s),(s.type==="IF_VISIBLE"||s.type==="LOOP")&&t.push({step:s,inElse:!1})}return e}function Ct(u,e){let t=u.split(`
716
- `).map(i=>i.trim()).filter(i=>i.length>0&&!i.startsWith("#")),s=[];for(let i of t){let n=Xe(i,e),r=n.replace(Ls,"").trim(),o=O.OPTIONAL_SUFFIX.test(r)||/^[(\[]\s*optional\s*[)\]]/i.test(r)||/^optional\s*:/i.test(r),a=r.replace(O.OPTIONAL_SUFFIX,"").replace(/^[(\[]\s*optional\s*[)\]]\s*/i,"").replace(/^optional\s*:\s*/i,"").trim();if(O.BACK.test(a)){s.push({originalText:n,type:"BACK",optional:o});continue}let l=a.match(O.WAIT);if(l){let x=parseInt(l[1],10),$=a.toLowerCase().includes("ms")?x:x*1e3;s.push({originalText:n,type:"WAIT",durationMs:$,optional:o});continue}let c=a.match(O.WAIT_UNTIL);if(c){let x=W([c[1],c[2],c[3]]),_=(c[4]||"visible").toLowerCase().includes("enable")?"enabled":"visible",L=c[5]?parseInt(c[5],10):void 0,oe=(c[6]||"s").toLowerCase(),ee=L?oe.includes("ms")?L:L*1e3:void 0;s.push({originalText:n,type:"WAIT_UNTIL",target:x,expectedState:_,durationMs:ee,optional:o});continue}let p=a.match(O.IF_VISIBLE);if(p){let x=W([p[1],p[2],p[3],p[5],p[6],p[7]]);s.push({originalText:n,type:"IF_VISIBLE",conditionTarget:x,thenSteps:[],elseSteps:[],optional:o});continue}if(O.ELSE.test(a)){s.push({originalText:n,type:"IF_VISIBLE",_isControl:"ELSE"});continue}if(O.END.test(a)){s.push({originalText:n,type:"IF_VISIBLE",_isControl:"END"});continue}let h=a.match(O.LOOP);if(h){let x=parseInt(h[1],10);s.push({originalText:n,type:"LOOP",loopCount:x,childSteps:[],optional:o});continue}let d=a.match(O.FOR_EACH);if(d){let x=W([d[1],d[2],d[3]]);s.push({originalText:n,type:"LOOP",target:x,loopVariable:"item",childSteps:[],optional:o});continue}let g=a.match(O.SET_VARIABLE);if(g){let x=g[1].trim(),$=g[2].trim();s.push({originalText:n,type:"SET_VARIABLE",variableName:x,variableExpression:$,optional:o});continue}let f=a.match(O.DEVICE_WIFI);if(f){let x=f[1].toLowerCase();s.push({originalText:n,type:"DEVICE_STATE",deviceAction:"wifi",deviceStateValue:x==="on"||x==="enable",optional:o});continue}let y=a.match(O.DEVICE_AIRPLANE);if(y){let x=y[1].toLowerCase();s.push({originalText:n,type:"DEVICE_STATE",deviceAction:"airplane",deviceStateValue:x==="on"||x==="enable",optional:o});continue}let S=a.match(O.DEVICE_ORIENTATION);if(S){let x=S[1].toLowerCase();s.push({originalText:n,type:"DEVICE_STATE",deviceAction:"orientation",deviceStateValue:x,optional:o});continue}let b=a.match(O.DEVICE_NOTIFICATIONS);if(b){let x=b[1].toLowerCase(),$=x.startsWith("open")||x.startsWith("expand")||x.startsWith("pull");s.push({originalText:n,type:"DEVICE_STATE",deviceAction:"notifications",deviceStateValue:$?"open":"collapse",optional:o});continue}let m=a.match(O.RUN_JS);if(m){let x=m[1].trim();s.push({originalText:n,type:"RUN_JS",jsCode:x,optional:o});continue}let v=a.match(O.ENTER_OTP);if(v){let x=W([v[1],v[2],v[3]])||void 0;s.push({originalText:n,type:"ENTER_OTP",target:x,optional:o});continue}let E=a.match(O.API_REQUEST);if(E){let x=E[1].toUpperCase(),$=W([E[2],E[3],E[4]]),_=W([E[5],E[6],E[7]])||void 0,L=W([E[8],E[9],E[10]])||void 0,oe=E[11]||void 0,ee=E[12]?parseInt(E[12],10):void 0;s.push({originalText:n,type:"API_REQUEST",apiMethod:x,apiUrl:$,apiBody:_,apiStorePath:L,apiStoreVariable:oe,apiExpectedStatus:ee,optional:o});continue}let k=a.match(O.EMAIL_ASSERT);if(k){let x=W([k[1],k[2],k[3]]),$=W([k[4],k[5],k[6]]),_=W([k[7],k[8],k[9]])||void 0;s.push({originalText:n,type:"EMAIL_ASSERT",emailRecipient:x,emailSubject:$,emailBodyContains:_,optional:o});continue}let w=a.match(O.LAUNCH_APP);if(w){let x=W([w[1],w[2],w[3]]);s.push({originalText:n,type:"LAUNCH_APP",target:x,optional:o});continue}let A=a.match(O.RESTART_APP);if(A){let x=W([A[1],A[2],A[3]]);s.push({originalText:n,type:"RESTART_APP",target:x,optional:o});continue}let B=a.match(O.TERMINATE_APP);if(B){let x=W([B[1],B[2],B[3]])||void 0;s.push({originalText:n,type:"TERMINATE_APP",target:x,optional:o});continue}let Z=a.match(O.CLEAR_DATA);if(Z){let x=W([Z[1],Z[2],Z[3]]);s.push({originalText:n,type:"CLEAR_DATA",target:x,optional:o});continue}let j=a.match(O.GRANT_PERMISSION);if(j){let x=W([j[1],j[2],j[3]]),$=W([j[4],j[5],j[6]])||void 0;s.push({originalText:n,type:"GRANT_PERMISSION",value:x,target:$,optional:o});continue}let Te=a.match(O.DEEP_LINK);if(Te){let x=W([Te[1],Te[2],Te[3]]);s.push({originalText:n,type:"DEEP_LINK",target:x,optional:o});continue}let te=a.match(O.DIRECTIONAL_SWIPE);if(te){let x=te[1].toLowerCase(),$=W([te[2],te[3],te[4]])||void 0;s.push({originalText:n,type:"SWIPE",direction:x,target:$,optional:o});continue}let le=a.match(O.TOGGLE);if(le){let x=(le[1]||"").toLowerCase(),$=W([le[2],le[3],le[4]]),_=a.toLowerCase().startsWith("uncheck")||x==="off"?!1:x==="on"||a.toLowerCase().startsWith("check")?!0:void 0;s.push({originalText:n,type:"TOGGLE",target:$,desiredState:_,optional:o});continue}let U=a.match(O.SELECT_DROPDOWN);if(U){let x=W([U[1],U[2],U[3]]),$=W([U[4],U[5],U[6]]);s.push({originalText:n,type:"SELECT",value:x,target:$,optional:o});continue}let be=a.match(O.SCROLL_TO);if(be){let x=(be[1]||"down").toLowerCase(),$=W([be[2],be[3],be[4]]);s.push({originalText:n,type:"SCROLL",target:$,direction:x,optional:o});continue}let ne=a.match(O.SCROLL);if(ne){let x=ne[1].toLowerCase();s.push({originalText:n,type:"SCROLL",target:x,direction:x,optional:o});continue}let J=a.match(O.LONG_PRESS);if(J){let x=W([J[1],J[2],J[3]]);s.push({originalText:n,type:"LONG_PRESS",target:x,optional:o});continue}let N=a.match(O.ORDINAL_TAP);if(N){let x=N[1].toLowerCase(),$=W([N[2],N[3],N[4]]);s.push({originalText:n,type:"TAP",target:$,ordinal:x,optional:o});continue}let Q=a.match(O.PROXIMITY_TAP);if(Q){let x=W([Q[1],Q[2],Q[3]]),$=W([Q[4],Q[5],Q[6]]);s.push({originalText:n,type:"TAP",target:x,relativeTo:$,optional:o});continue}let C=a.match(O.TYPE);if(C){let x=W([C[1],C[2],C[3]]),$=W([C[4],C[5],C[6]]);s.push({originalText:n,type:"TYPE",value:x,target:$,optional:o});continue}let M=a.match(O.CLEAR);if(M){let x=W([M[1],M[2],M[3]]);s.push({originalText:n,type:"CLEAR",target:x,optional:o});continue}let I=a.match(O.VERIFY);if(I){let x=W([I[1],I[2],I[3]]),$=(I[4]||"visible").toLowerCase(),_=$.includes("not visible")||$.includes("not present")||$.includes("absent")||$.includes("hidden")||$.includes("gone"),L=_?"absent":$==="exists"||$==="enabled"||$==="disabled"?$:"visible";s.push({originalText:n,type:"VERIFY",target:x,expectedState:L,negative:_,optional:o});continue}let F=a.match(O.TAP);if(F&&!a.toLowerCase().includes("back")){let x=W([F[1],F[2],F[3]]);s.push({originalText:n,type:"TAP",target:x,optional:o});continue}let K=a.match(O.FALLBACK_QUOTED_TAP);if(K&&(a.toLowerCase().startsWith("tap")||a.toLowerCase().startsWith("click"))){s.push({originalText:n,type:"TAP",target:K[1],optional:o});continue}ke.warn(`Unrecognized prompt step: "${i}". Skipping.`)}return Ri(s)}function qs(u,e,t){let s=e.map(r=>(r.text||r.contentDesc||"").trim()).filter(r=>r.length>1),i=We(u,s,3),n=i.length>0?`
713
+ `;for(let y of r)try{y.write(f)}catch{r.delete(y)}}return{server:a,port:c,url:l,broadcastStep(u){n.steps.push(u),n.totalSteps=n.steps.length,u.status==="PASS"?n.passedSteps++:u.status==="FAIL"?n.failedSteps++:u.status==="WARN"?n.warnSteps++:u.status==="SKIPPED"&&n.skippedSteps++,h("step",u)},broadcastComplete(u){n=u,h("complete",u)},broadcastError(u){n.errorsDetected.push(u),h("error",{error:u})},updateReport(u){n=u},async close(){clearInterval(o);for(let u of r)try{u.end()}catch{}r.clear(),await new Promise((u,g)=>{a.close(f=>{f?g(f):u()})})}}}import Js from"fs";import kt from"path";import ie from"chalk";function Ts(p,e=new Set){let t=kt.resolve(p);if(!Js.existsSync(t))throw new Error(`Included spec file not found: ${t}`);if(e.has(t)){let r=Array.from(e).concat(t);throw new mt(`Circular spec inclusion detected: ${r.join(" -> ")}`,r)}e.add(t);let i=Js.readFileSync(t,"utf-8").split(`
714
+ `),n=[];for(let r of i){let o=r.trim(),a=o.match(O.INCLUDE_SPEC);if(a&&!o.startsWith("#")){let d=W([a[1],a[2],a[3]]),c=kt.isAbsolute(d)?d:kt.resolve(kt.dirname(t),d),l=Ts(c,new Set(e));n.push(l)}else n.push(r)}return n.join(`
715
+ `)}function Ni(p){let e=[],t=[];for(let s of p){if(s._isControl==="END"){t.length>0&&t.pop();continue}if(s._isControl==="ELSE"){t.length>0&&t[t.length-1].step.type==="IF_VISIBLE"&&(t[t.length-1].inElse=!0);continue}let i=e;if(t.length>0){let n=t[t.length-1];n.step.type==="IF_VISIBLE"?n.inElse?(n.step.elseSteps=n.step.elseSteps||[],i=n.step.elseSteps):(n.step.thenSteps=n.step.thenSteps||[],i=n.step.thenSteps):n.step.type==="LOOP"&&(n.step.childSteps=n.step.childSteps||[],i=n.step.childSteps)}i.push(s),(s.type==="IF_VISIBLE"||s.type==="LOOP")&&t.push({step:s,inElse:!1})}return e}function Ct(p,e){let t=p.split(`
716
+ `).map(i=>i.trim()).filter(i=>i.length>0&&!i.startsWith("#")),s=[];for(let i of t){let n=Xe(i,e),r=n.replace(Ls,"").trim(),o=O.OPTIONAL_SUFFIX.test(r)||/^[(\[]\s*optional\s*[)\]]/i.test(r)||/^optional\s*:/i.test(r),a=r.replace(O.OPTIONAL_SUFFIX,"").replace(/^[(\[]\s*optional\s*[)\]]\s*/i,"").replace(/^optional\s*:\s*/i,"").trim();if(O.BACK.test(a)){s.push({originalText:n,type:"BACK",optional:o});continue}let d=a.match(O.WAIT);if(d){let T=parseInt(d[1],10),k=a.toLowerCase().includes("ms")?T:T*1e3;s.push({originalText:n,type:"WAIT",durationMs:k,optional:o});continue}let c=a.match(O.WAIT_UNTIL);if(c){let T=W([c[1],c[2],c[3]]),_=(c[4]||"visible").toLowerCase().includes("enable")?"enabled":"visible",L=c[5]?parseInt(c[5],10):void 0,oe=(c[6]||"s").toLowerCase(),ee=L?oe.includes("ms")?L:L*1e3:void 0;s.push({originalText:n,type:"WAIT_UNTIL",target:T,expectedState:_,durationMs:ee,optional:o});continue}let l=a.match(O.IF_VISIBLE);if(l){let T=W([l[1],l[2],l[3],l[5],l[6],l[7]]);s.push({originalText:n,type:"IF_VISIBLE",conditionTarget:T,thenSteps:[],elseSteps:[],optional:o});continue}if(O.ELSE.test(a)){s.push({originalText:n,type:"IF_VISIBLE",_isControl:"ELSE"});continue}if(O.END.test(a)){s.push({originalText:n,type:"IF_VISIBLE",_isControl:"END"});continue}let h=a.match(O.LOOP);if(h){let T=parseInt(h[1],10);s.push({originalText:n,type:"LOOP",loopCount:T,childSteps:[],optional:o});continue}let u=a.match(O.FOR_EACH);if(u){let T=W([u[1],u[2],u[3]]);s.push({originalText:n,type:"LOOP",target:T,loopVariable:"item",childSteps:[],optional:o});continue}let g=a.match(O.SET_VARIABLE);if(g){let T=g[1].trim(),k=g[2].trim();s.push({originalText:n,type:"SET_VARIABLE",variableName:T,variableExpression:k,optional:o});continue}let f=a.match(O.DEVICE_WIFI);if(f){let T=f[1].toLowerCase();s.push({originalText:n,type:"DEVICE_STATE",deviceAction:"wifi",deviceStateValue:T==="on"||T==="enable",optional:o});continue}let y=a.match(O.DEVICE_AIRPLANE);if(y){let T=y[1].toLowerCase();s.push({originalText:n,type:"DEVICE_STATE",deviceAction:"airplane",deviceStateValue:T==="on"||T==="enable",optional:o});continue}let S=a.match(O.DEVICE_ORIENTATION);if(S){let T=S[1].toLowerCase();s.push({originalText:n,type:"DEVICE_STATE",deviceAction:"orientation",deviceStateValue:T,optional:o});continue}let b=a.match(O.DEVICE_NOTIFICATIONS);if(b){let T=b[1].toLowerCase(),k=T.startsWith("open")||T.startsWith("expand")||T.startsWith("pull");s.push({originalText:n,type:"DEVICE_STATE",deviceAction:"notifications",deviceStateValue:k?"open":"collapse",optional:o});continue}let m=a.match(O.RUN_JS);if(m){let T=m[1].trim();s.push({originalText:n,type:"RUN_JS",jsCode:T,optional:o});continue}let v=a.match(O.ENTER_OTP);if(v){let T=W([v[1],v[2],v[3]])||void 0;s.push({originalText:n,type:"ENTER_OTP",target:T,optional:o});continue}let x=a.match(O.API_REQUEST);if(x){let T=x[1].toUpperCase(),k=W([x[2],x[3],x[4]]),_=W([x[5],x[6],x[7]])||void 0,L=W([x[8],x[9],x[10]])||void 0,oe=x[11]||void 0,ee=x[12]?parseInt(x[12],10):void 0;s.push({originalText:n,type:"API_REQUEST",apiMethod:T,apiUrl:k,apiBody:_,apiStorePath:L,apiStoreVariable:oe,apiExpectedStatus:ee,optional:o});continue}let D=a.match(O.EMAIL_ASSERT);if(D){let T=W([D[1],D[2],D[3]]),k=W([D[4],D[5],D[6]]),_=W([D[7],D[8],D[9]])||void 0;s.push({originalText:n,type:"EMAIL_ASSERT",emailRecipient:T,emailSubject:k,emailBodyContains:_,optional:o});continue}let w=a.match(O.LAUNCH_APP);if(w){let T=W([w[1],w[2],w[3]]);s.push({originalText:n,type:"LAUNCH_APP",target:T,optional:o});continue}let A=a.match(O.RESTART_APP);if(A){let T=W([A[1],A[2],A[3]]);s.push({originalText:n,type:"RESTART_APP",target:T,optional:o});continue}let B=a.match(O.TERMINATE_APP);if(B){let T=W([B[1],B[2],B[3]])||void 0;s.push({originalText:n,type:"TERMINATE_APP",target:T,optional:o});continue}let Z=a.match(O.CLEAR_DATA);if(Z){let T=W([Z[1],Z[2],Z[3]]);s.push({originalText:n,type:"CLEAR_DATA",target:T,optional:o});continue}let j=a.match(O.GRANT_PERMISSION);if(j){let T=W([j[1],j[2],j[3]]),k=W([j[4],j[5],j[6]])||void 0;s.push({originalText:n,type:"GRANT_PERMISSION",value:T,target:k,optional:o});continue}let Te=a.match(O.DEEP_LINK);if(Te){let T=W([Te[1],Te[2],Te[3]]);s.push({originalText:n,type:"DEEP_LINK",target:T,optional:o});continue}let te=a.match(O.DIRECTIONAL_SWIPE);if(te){let T=te[1].toLowerCase(),k=W([te[2],te[3],te[4]])||void 0;s.push({originalText:n,type:"SWIPE",direction:T,target:k,optional:o});continue}let le=a.match(O.TOGGLE);if(le){let T=(le[1]||"").toLowerCase(),k=W([le[2],le[3],le[4]]),_=a.toLowerCase().startsWith("uncheck")||T==="off"?!1:T==="on"||a.toLowerCase().startsWith("check")?!0:void 0;s.push({originalText:n,type:"TOGGLE",target:k,desiredState:_,optional:o});continue}let U=a.match(O.SELECT_DROPDOWN);if(U){let T=W([U[1],U[2],U[3]]),k=W([U[4],U[5],U[6]]);s.push({originalText:n,type:"SELECT",value:T,target:k,optional:o});continue}let be=a.match(O.SCROLL_TO);if(be){let T=(be[1]||"down").toLowerCase(),k=W([be[2],be[3],be[4]]);s.push({originalText:n,type:"SCROLL",target:k,direction:T,optional:o});continue}let ne=a.match(O.SCROLL);if(ne){let T=ne[1].toLowerCase();s.push({originalText:n,type:"SCROLL",target:T,direction:T,optional:o});continue}let J=a.match(O.LONG_PRESS);if(J){let T=W([J[1],J[2],J[3]]);s.push({originalText:n,type:"LONG_PRESS",target:T,optional:o});continue}let N=a.match(O.ORDINAL_TAP);if(N){let T=N[1].toLowerCase(),k=W([N[2],N[3],N[4]]);s.push({originalText:n,type:"TAP",target:k,ordinal:T,optional:o});continue}let Q=a.match(O.PROXIMITY_TAP);if(Q){let T=W([Q[1],Q[2],Q[3]]),k=W([Q[4],Q[5],Q[6]]);s.push({originalText:n,type:"TAP",target:T,relativeTo:k,optional:o});continue}let C=a.match(O.TYPE);if(C){let T=W([C[1],C[2],C[3]]),k=W([C[4],C[5],C[6]]);s.push({originalText:n,type:"TYPE",value:T,target:k,optional:o});continue}let M=a.match(O.CLEAR);if(M){let T=W([M[1],M[2],M[3]]);s.push({originalText:n,type:"CLEAR",target:T,optional:o});continue}let I=a.match(O.VERIFY);if(I){let T=W([I[1],I[2],I[3]]),k=(I[4]||"visible").toLowerCase(),_=k.includes("not visible")||k.includes("not present")||k.includes("absent")||k.includes("hidden")||k.includes("gone"),L=_?"absent":k==="exists"||k==="enabled"||k==="disabled"?k:"visible";s.push({originalText:n,type:"VERIFY",target:T,expectedState:L,negative:_,optional:o});continue}let F=a.match(O.TAP);if(F&&!a.toLowerCase().includes("back")){let T=W([F[1],F[2],F[3]]);s.push({originalText:n,type:"TAP",target:T,optional:o});continue}let K=a.match(O.FALLBACK_QUOTED_TAP);if(K&&(a.toLowerCase().startsWith("tap")||a.toLowerCase().startsWith("click"))){s.push({originalText:n,type:"TAP",target:K[1],optional:o});continue}ke.warn(`Unrecognized prompt step: "${i}". Skipping.`)}return Ni(s)}function qs(p,e,t){let s=e.map(r=>(r.text||r.contentDesc||"").trim()).filter(r=>r.length>1),i=We(p,s,3),n=i.length>0?`
717
717
  \u{1F4A1} Did you mean one of these visible items?
718
718
  `+i.map(r=>` \u2022 "${r.text}" (${Math.round(r.score*100)}% match)`).join(`
719
719
  `):`
720
- \u{1F4A1} No similar text found on current screen.`;return new Error(`${t}${n}`)}function Zs(u,e,t,s){let i=X(e),n=i.includes("password")||i.includes("passcode")||i.includes("pin")||i.includes("pwd")||i.includes("secret"),r=i.includes("email")||i.includes("mail")||i.includes("user")||i.includes("login")||i.includes("username")||t&&t.includes("@"),o=u.filter(c=>c.className.includes("EditText")&&c.bounds.width>0);if(o.length===0)return null;let a=o.find(c=>z(e,c.contentDesc)||z(e,c.resourceId)||z(e,c.text));if(a)return a;let l=u.filter(c=>!c.className.includes("EditText")&&(z(e,c.text)||z(e,c.contentDesc)||z(e,c.resourceId))&&c.bounds.width>0);for(let c of l){let p=o.filter(h=>h.bounds.centerY>=c.bounds.centerY&&h.bounds.centerY-c.bounds.centerY<300&&Math.abs(h.bounds.centerX-c.bounds.centerX)<450);if(p.length>0)return p.sort((h,d)=>h.bounds.centerY-d.bounds.centerY),p[0]}if(s){let c=s.getAllCandidates("TYPE",e);for(let p of c){let h=o.find(d=>z(p,d.contentDesc)||z(p,d.resourceId)||z(p,d.text));if(h)return h}}if(n){let c=o.find(p=>p.password);if(c)return c;if(o.length>1){let p=o.find(h=>h.text?.toLowerCase().includes("email")||h.contentDesc?.toLowerCase().includes("email"));if(p){let h=o.filter(d=>d.bounds.centerY>p.bounds.centerY);if(h.length>0)return h.sort((d,g)=>d.bounds.centerY-g.bounds.centerY),h[0]}}if(o.length>=2)return o[1]}if(r){let c=o.find(p=>!p.password);if(c)return c;if(o.length>0)return o[0]}return o.length===1?o[0]:null}function It(u,e,t,s="en",i,n){let r=i?.type||"TAP",o=X(e),l=u.filter(d=>(X(d.text)===o||X(d.contentDesc)===o)&&d.bounds.width>0&&d.bounds.height>0).find(d=>d.clickable);if(l)return[l];let c=t.getAllCandidates(r,e,s,n),p=[];for(let d of c){let g=u.filter(f=>{let y=z(d,f.text),S=z(d,f.contentDesc),b=z(d,f.resourceId);return(y||S||b)&&f.bounds.width>0&&f.bounds.height>0});if(g.length>0){p=g;break}}if(p.length===0){let d=[];for(let f of u)f.text&&f.text.trim().length>1&&d.push(f.text.trim()),f.contentDesc&&f.contentDesc.trim().length>1&&d.push(f.contentDesc.trim());let g=We(e,d,1);if(g.length>0&&g[0].score>=.8){let f=g[0].text,y=u.filter(S=>(z(f,S.text)||z(f,S.contentDesc))&&S.bounds.width>0&&S.bounds.height>0);y.length>0&&(console.log(ie.yellow(` \u{1F4A1} [Self-Healing] Auto-resolved "${e}" \u2192 "${f}" (${Math.round(g[0].score*100)}% match)`)),p=y)}}if(p.length===0)return[];let h=p.filter(d=>{let g=X(d.text),f=X(d.contentDesc);return g===o||f===o});if(h.length>0)p=h;else{let d=p.filter(g=>{let f=X(g.contentDesc);return f.endsWith(o)||f.includes(`, ${o}`)});d.length>0&&(p=d)}if(i?.relativeTo){let d=u.find(g=>z(i.relativeTo,g.text)||z(i.relativeTo,g.contentDesc));if(d){let g=p.filter(f=>Math.abs(f.bounds.centerY-d.bounds.centerY)<140).sort((f,y)=>{let S=Math.hypot(f.bounds.centerX-d.bounds.centerX,f.bounds.centerY-d.bounds.centerY),b=Math.hypot(y.bounds.centerX-d.bounds.centerX,y.bounds.centerY-d.bounds.centerY);return S-b});if(g.length>0)return g}}if(i?.ordinal){let d=i.ordinal.toLowerCase();if(d==="1st"||d==="first")return[p[0]];if(d==="2nd"&&p.length>1)return[p[1]];if(d==="3rd"&&p.length>2)return[p[2]];if(d==="4th"&&p.length>3)return[p[3]];if(d==="5th"&&p.length>4)return[p[4]];if(d==="last"&&p.length>0)return[p[p.length-1]]}return p}function ce(u){if(!u||u.length===0)return"0";let e=2166136261;for(let t=0;t<u.length;t++){let s=u[t],i=`${s.text||""}|${s.contentDesc||""}|${s.resourceId||""}|${s.bounds?.x1||0},${s.bounds?.y1||0},${s.bounds?.width||0},${s.bounds?.height||0}`;for(let n=0;n<i.length;n++)e^=i.charCodeAt(n),e=Math.imul(e,16777619)}return(e>>>0).toString(16)}var Ni=[/\b\d{1,2}:\d{2}(?::\d{2})?\s*(?:AM|PM|am|pm)?\b/g,/\b\d+\s*(?:sec|min|hr|hour|day|week|month|year)s?\s*ago\b/gi,/\b(?:just now|yesterday|today)\b/gi,/[\$€£₹]\s*\d+(?:\.\d{1,2})?/g,/(?:#|(?:\b(?:ID|No)[\s:-]*))[A-Z0-9_-]{3,}\b/gi,/\b\d{1,3}%\b/g];function Qs(u){if(!u)return"";let e=u;for(let t of Ni)e=e.replace(t,"<VAL>");return e.trim()}function Ne(u,e){if(!u||u.length===0)return"0";let s=(e?.height||2400)*.04,i=2166136261;for(let n=0;n<u.length;n++){let r=u[n];if(r.bounds&&r.bounds.centerY<s)continue;let o=Qs(r.text||""),a=Qs(r.contentDesc||""),l=r.resourceId||"",c=r.className||"",p=r.clickable?"1":"0",h=r.checkable?"1":"0",d=Math.round((r.bounds?.x1||0)/50),g=Math.round((r.bounds?.y1||0)/50),f=Math.round((r.bounds?.width||0)/50),y=Math.round((r.bounds?.height||0)/50),S=`${c}|${l}|${o}|${a}|${p}|${h}|${d},${g},${f},${y}`;for(let b=0;b<S.length;b++)i^=S.charCodeAt(b),i=Math.imul(i,16777619)}return(i>>>0).toString(16)}function bn(u,e){let t=ce(u),s=ce(e);return{hasChanged:t!==s,previousHash:t,currentHash:s,nodeCountDelta:e.length-u.length}}function ei(u){let e=new Set;if(!u)return e;let t=u.split(",").map(s=>s.trim()).filter(Boolean);for(let s of t)if(s.includes("-")){let[i,n]=s.split("-").map(a=>a.trim()),r=parseInt(i,10),o=parseInt(n,10);if(!isNaN(r)&&!isNaN(o)){let[a,l]=r<=o?[r,o]:[o,r];for(let c=a;c<=l;c++)e.add(c)}}else{let i=parseInt(s,10);isNaN(i)||e.add(i)}return e}function ti(u){let e=new Set,t=u.split(`
721
- `);for(let s of t){let i=s.trim();if(!i.startsWith("#"))continue;let n=i.match(/#\s*@tags?:\s*(.+)/i);if(n){n[1].split(",").map(o=>o.trim().toLowerCase()).filter(Boolean).forEach(o=>e.add(o));continue}let r=i.match(/#\s*@([a-zA-Z0-9_-]+)/);r&&r[1].toLowerCase()!=="tags"&&r[1].toLowerCase()!=="tag"&&e.add(r[1].toLowerCase())}return Array.from(e)}function si(u){let e=["",ie.bold.cyan(`\u{1F4CB} Parsed Test Steps (${u.length} total):`),ie.gray("\u250C\u2500\u2500\u2500\u2500\u2500\u252C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u252C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u252C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u252C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510"),ie.gray("\u2502")+` ${ie.bold("#".padEnd(3))} `+ie.gray("\u2502")+` ${ie.bold("Type".padEnd(14))} `+ie.gray("\u2502")+` ${ie.bold("Target".padEnd(28))} `+ie.gray("\u2502")+` ${ie.bold("Value / Detail".padEnd(30))} `+ie.gray("\u2502")+` ${ie.bold("Optional".padEnd(8))} `+ie.gray("\u2502"),ie.gray("\u251C\u2500\u2500\u2500\u2500\u2500\u253C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524")];return u.forEach((t,s)=>{let i=`${s+1}`.padEnd(3),n=t.type.padEnd(14),r=(t.target||t.conditionTarget||"\u2014").slice(0,28).padEnd(28),o=(t.value||(t.durationMs?`${t.durationMs}ms`:t.expectedState)||"\u2014").slice(0,30).padEnd(30),a=(t.optional?"Yes":"No").padEnd(8);e.push(ie.gray("\u2502")+` ${ie.white(i)} `+ie.gray("\u2502")+` ${ie.cyan(n)} `+ie.gray("\u2502")+` ${ie.yellow(r)} `+ie.gray("\u2502")+` ${ie.white(o)} `+ie.gray("\u2502")+` ${ie.gray(a)} `+ie.gray("\u2502"))}),e.push(ie.gray(`\u2514\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518
720
+ \u{1F4A1} No similar text found on current screen.`;return new Error(`${t}${n}`)}function Zs(p,e,t,s){let i=X(e),n=i.includes("password")||i.includes("passcode")||i.includes("pin")||i.includes("pwd")||i.includes("secret"),r=i.includes("email")||i.includes("mail")||i.includes("user")||i.includes("login")||i.includes("username")||t&&t.includes("@"),o=p.filter(c=>c.className.includes("EditText")&&c.bounds.width>0);if(o.length===0)return null;let a=o.find(c=>z(e,c.contentDesc)||z(e,c.resourceId)||z(e,c.text));if(a)return a;let d=p.filter(c=>!c.className.includes("EditText")&&(z(e,c.text)||z(e,c.contentDesc)||z(e,c.resourceId))&&c.bounds.width>0);for(let c of d){let l=o.filter(h=>h.bounds.centerY>=c.bounds.centerY&&h.bounds.centerY-c.bounds.centerY<300&&Math.abs(h.bounds.centerX-c.bounds.centerX)<450);if(l.length>0)return l.sort((h,u)=>h.bounds.centerY-u.bounds.centerY),l[0]}if(s){let c=s.getAllCandidates("TYPE",e);for(let l of c){let h=o.find(u=>z(l,u.contentDesc)||z(l,u.resourceId)||z(l,u.text));if(h)return h}}if(n){let c=o.find(l=>l.password);if(c)return c;if(o.length>1){let l=o.find(h=>h.text?.toLowerCase().includes("email")||h.contentDesc?.toLowerCase().includes("email"));if(l){let h=o.filter(u=>u.bounds.centerY>l.bounds.centerY);if(h.length>0)return h.sort((u,g)=>u.bounds.centerY-g.bounds.centerY),h[0]}}if(o.length>=2)return o[1]}if(r){let c=o.find(l=>!l.password);if(c)return c;if(o.length>0)return o[0]}return o.length===1?o[0]:null}function It(p,e,t,s="en",i,n){let r=i?.type||"TAP",o=X(e),d=p.filter(u=>(X(u.text)===o||X(u.contentDesc)===o)&&u.bounds.width>0&&u.bounds.height>0).find(u=>u.clickable);if(d)return[d];let c=t.getAllCandidates(r,e,s,n),l=[];for(let u of c){let g=p.filter(f=>{let y=z(u,f.text),S=z(u,f.contentDesc),b=z(u,f.resourceId);return(y||S||b)&&f.bounds.width>0&&f.bounds.height>0});if(g.length>0){l=g;break}}if(l.length===0){let u=[];for(let f of p)f.text&&f.text.trim().length>1&&u.push(f.text.trim()),f.contentDesc&&f.contentDesc.trim().length>1&&u.push(f.contentDesc.trim());let g=We(e,u,1);if(g.length>0&&g[0].score>=.8){let f=g[0].text,y=p.filter(S=>(z(f,S.text)||z(f,S.contentDesc))&&S.bounds.width>0&&S.bounds.height>0);y.length>0&&(console.log(ie.yellow(` \u{1F4A1} [Self-Healing] Auto-resolved "${e}" \u2192 "${f}" (${Math.round(g[0].score*100)}% match)`)),l=y)}}if(l.length===0)return[];let h=l.filter(u=>{let g=X(u.text),f=X(u.contentDesc);return g===o||f===o});if(h.length>0)l=h;else{let u=l.filter(g=>{let f=X(g.contentDesc);return f.endsWith(o)||f.includes(`, ${o}`)});u.length>0&&(l=u)}if(i?.relativeTo){let u=p.find(g=>z(i.relativeTo,g.text)||z(i.relativeTo,g.contentDesc));if(u){let g=l.filter(f=>Math.abs(f.bounds.centerY-u.bounds.centerY)<140).sort((f,y)=>{let S=Math.hypot(f.bounds.centerX-u.bounds.centerX,f.bounds.centerY-u.bounds.centerY),b=Math.hypot(y.bounds.centerX-u.bounds.centerX,y.bounds.centerY-u.bounds.centerY);return S-b});if(g.length>0)return g}}if(i?.ordinal){let u=i.ordinal.toLowerCase();if(u==="1st"||u==="first")return[l[0]];if(u==="2nd"&&l.length>1)return[l[1]];if(u==="3rd"&&l.length>2)return[l[2]];if(u==="4th"&&l.length>3)return[l[3]];if(u==="5th"&&l.length>4)return[l[4]];if(u==="last"&&l.length>0)return[l[l.length-1]]}return l}function ce(p){if(!p||p.length===0)return"0";let e=2166136261;for(let t=0;t<p.length;t++){let s=p[t],i=`${s.text||""}|${s.contentDesc||""}|${s.resourceId||""}|${s.bounds?.x1||0},${s.bounds?.y1||0},${s.bounds?.width||0},${s.bounds?.height||0}`;for(let n=0;n<i.length;n++)e^=i.charCodeAt(n),e=Math.imul(e,16777619)}return(e>>>0).toString(16)}var Mi=[/\b\d{1,2}:\d{2}(?::\d{2})?\s*(?:AM|PM|am|pm)?\b/g,/\b\d+\s*(?:sec|min|hr|hour|day|week|month|year)s?\s*ago\b/gi,/\b(?:just now|yesterday|today)\b/gi,/[\$€£₹]\s*\d+(?:\.\d{1,2})?/g,/(?:#|(?:\b(?:ID|No)[\s:-]*))[A-Z0-9_-]{3,}\b/gi,/\b\d{1,3}%\b/g];function Qs(p){if(!p)return"";let e=p;for(let t of Mi)e=e.replace(t,"<VAL>");return e.trim()}function Ne(p,e){if(!p||p.length===0)return"0";let s=(e?.height||2400)*.04,i=2166136261;for(let n=0;n<p.length;n++){let r=p[n];if(r.bounds&&r.bounds.centerY<s)continue;let o=Qs(r.text||""),a=Qs(r.contentDesc||""),d=r.resourceId||"",c=r.className||"",l=r.clickable?"1":"0",h=r.checkable?"1":"0",u=Math.round((r.bounds?.x1||0)/50),g=Math.round((r.bounds?.y1||0)/50),f=Math.round((r.bounds?.width||0)/50),y=Math.round((r.bounds?.height||0)/50),S=`${c}|${d}|${o}|${a}|${l}|${h}|${u},${g},${f},${y}`;for(let b=0;b<S.length;b++)i^=S.charCodeAt(b),i=Math.imul(i,16777619)}return(i>>>0).toString(16)}function bn(p,e){let t=ce(p),s=ce(e);return{hasChanged:t!==s,previousHash:t,currentHash:s,nodeCountDelta:e.length-p.length}}function ei(p){let e=new Set;if(!p)return e;let t=p.split(",").map(s=>s.trim()).filter(Boolean);for(let s of t)if(s.includes("-")){let[i,n]=s.split("-").map(a=>a.trim()),r=parseInt(i,10),o=parseInt(n,10);if(!isNaN(r)&&!isNaN(o)){let[a,d]=r<=o?[r,o]:[o,r];for(let c=a;c<=d;c++)e.add(c)}}else{let i=parseInt(s,10);isNaN(i)||e.add(i)}return e}function ti(p){let e=new Set,t=p.split(`
721
+ `);for(let s of t){let i=s.trim();if(!i.startsWith("#"))continue;let n=i.match(/#\s*@tags?:\s*(.+)/i);if(n){n[1].split(",").map(o=>o.trim().toLowerCase()).filter(Boolean).forEach(o=>e.add(o));continue}let r=i.match(/#\s*@([a-zA-Z0-9_-]+)/);r&&r[1].toLowerCase()!=="tags"&&r[1].toLowerCase()!=="tag"&&e.add(r[1].toLowerCase())}return Array.from(e)}function si(p){let e=["",ie.bold.cyan(`\u{1F4CB} Parsed Test Steps (${p.length} total):`),ie.gray("\u250C\u2500\u2500\u2500\u2500\u2500\u252C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u252C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u252C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u252C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510"),ie.gray("\u2502")+` ${ie.bold("#".padEnd(3))} `+ie.gray("\u2502")+` ${ie.bold("Type".padEnd(14))} `+ie.gray("\u2502")+` ${ie.bold("Target".padEnd(28))} `+ie.gray("\u2502")+` ${ie.bold("Value / Detail".padEnd(30))} `+ie.gray("\u2502")+` ${ie.bold("Optional".padEnd(8))} `+ie.gray("\u2502"),ie.gray("\u251C\u2500\u2500\u2500\u2500\u2500\u253C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524")];return p.forEach((t,s)=>{let i=`${s+1}`.padEnd(3),n=t.type.padEnd(14),r=(t.target||t.conditionTarget||"\u2014").slice(0,28).padEnd(28),o=(t.value||(t.durationMs?`${t.durationMs}ms`:t.expectedState)||"\u2014").slice(0,30).padEnd(30),a=(t.optional?"Yes":"No").padEnd(8);e.push(ie.gray("\u2502")+` ${ie.white(i)} `+ie.gray("\u2502")+` ${ie.cyan(n)} `+ie.gray("\u2502")+` ${ie.yellow(r)} `+ie.gray("\u2502")+` ${ie.white(o)} `+ie.gray("\u2502")+` ${ie.gray(a)} `+ie.gray("\u2502"))}),e.push(ie.gray(`\u2514\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518
722
722
  `)),e.join(`
723
- `)}function Lt(u,e,t=[],s="SKIPPED",i="Validation"){let n=new Date().toISOString(),r=s==="PASS";return{packageName:u||"none",deviceId:e||"none",startTime:n,endTime:n,durationSeconds:0,totalSteps:t.length,passedSteps:r?t.length:0,failedSteps:0,skippedSteps:r?0:t.length,warnSteps:0,errorsDetected:[],steps:t.map((o,a)=>({stepIndex:a+1,timestamp:n,phase:i,description:o.originalText,action:o.type,target:o.target,status:s,durationMs:0}))}}function yn(u,e){return u&&(e&&/password|passwd|pin\b|secret|token|api[_-]?key|auth|credential/i.test(e)?"\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022":u)}var Ye=class{driver;memory;reporter;checkpoints;baselines;lastHierarchy=null;screenDimensions={width:T.screen.fallbackWidth,height:T.screen.fallbackHeight};navBarHeight=0;constructor(e,t,s,i,n,r){this.driver=e||he,this.memory=t||at,this.reporter=s||nt,this.checkpoints=i||Xs,this.baselines=n||Kt,this.semanticResolver=r||ws()}semanticResolver;healEnabled=!1;activeLocale="en";runtimeVariables=new Map;loopStack=[];expandSpecIncludes(e,t=new Set){return Ts(e,t)}async expandSpec(e,t){let s=t||this.semanticResolver,i=e.split(`
724
- `),n=[],r=0;for(let o of i){let a=o.trim();if(!a||a.startsWith("#")||a.startsWith("//")){n.push(o);continue}let l=this.parsePrompt(a);if(l.length>0&&l[0].type!==void 0&&!a.toLowerCase().startsWith("intent:")){n.push(o);continue}let p=a.replace(/^intent:\s*/i,""),h=this.memory?.getIntentExpansion(p);if(h?.length){n.push(`# [Cached Intent] ${a}`,...h),r+=h.length;continue}let d=await s.resolveIntent(p);if(d?.length){n.push(`# [AI Expanded] ${a}`);let g=d.map(f=>f.originalText);n.push(...g),this.memory&&(this.memory.recordIntentExpansion(p,g),await this.memory.save().catch(()=>{})),r+=d.length}else n.push(o)}return{expanded:n.join(`
725
- `),stepsAdded:r}}parsePrompt(e,t){return Ct(e,t)}async runSpec(e,t,s){if(!Ce.existsSync(e))throw new Error(`Spec file not found: ${e}`);let i=typeof t=="string"?{packageName:t,serial:s,screenshotMode:"on-failure",continueOnError:!1}:{screenshotMode:"on-failure",continueOnError:!1,...t};i.heal!==void 0&&(this.healEnabled=i.heal),i.noAi&&(this.semanticResolver=ws({provider:"heuristic"})),this.activeLocale=(i.locale||T.locale||"en").toLowerCase(),typeof this.memory.setLocale=="function"&&this.memory.setLocale(this.activeLocale);let n=this.expandSpecIncludes(e),r=n,o=[],a=dt.extractDataDirective(n,me.dirname(e));if(a)r=a.cleanedSpec,o=a.rows;else if(i.dataFile){let b=me.isAbsolute(i.dataFile)?i.dataFile:me.resolve(process.cwd(),i.dataFile);o=dt.loadFromFile(b)}(i.onlyRow!==void 0||i.iterations!==void 0)&&(o.length>0?o=dt.filterRows(o,{onlyRow:i.onlyRow,iterations:i.iterations}):i.iterations&&i.iterations>0&&(o=Array.from({length:i.iterations},()=>({}))));let l=o.length>0?o.map(b=>({...i.variables||{},...b})):[i.variables||{}],c=me.basename(e,me.extname(e)),p=r.match(/#\s*(?:Target\s*)?Package:\s*([a-zA-Z0-9._-]+)/i),h=p?p[1]:void 0;if(i.tags){let b=ti(n),m=i.tags.split(",").map(E=>E.trim().toLowerCase()).filter(Boolean);if(!m.some(E=>b.includes(E)))return console.log(R.yellow(`
726
- \u23E9 Skipping ${e}: tags [${b.join(", ")}] do not match filter [${m.join(", ")}]`)),Lt(h||i.packageName||"",i.serial||"",[],"SKIPPED")}if(i.listSteps){let b=this.parsePrompt(r,l[0]);return console.log(si(b)),Lt(h||i.packageName||"",i.serial||"",b,"SKIPPED","Listing")}if(i.dryRun){let b=this.parsePrompt(r,l[0]);return console.log(R.bold.cyan(`
727
- \u{1F50D} [Dry Run] Validated ${b.length} test step(s) in ${e} successfully (no device interaction).`)),Lt(h||i.packageName||"",i.serial||"",b,"PASS","Validation")}if(l.length>1)console.log(R.cyan(`
728
- \u{1F4CB} Loaded spec with ${l.length} data iteration(s) from ${e}`));else{let b=this.parsePrompt(r,l[0]);console.log(R.cyan(`
729
- \u{1F4CB} Loaded ${b.length} test step(s) from ${e}`))}console.log(R.gray("Execution Policy: ")+R.bold.white(i.continueOnError?"Continue on Error (Modular Run)":"Fail-Fast (Default)")+R.gray(" | Screenshots: ")+R.bold.white(i.screenshotMode==="all"?"All Steps":"Failure-Only")),i.serial=await this.driver.ensureDefaultDevice(i.serial);let d=i.serial||this.driver.getDefaultDevice()||"Default Device",g=null;i.serial&&(g=Ke(i.serial)),i.embedScreenshots&&typeof this.reporter.setEmbedScreenshots=="function"&&this.reporter.setEmbedScreenshots(!0);let f,y;if(i.serve){let b=typeof i.serve=="number"?i.serve:4040;try{f=await zs({port:b,suiteName:c}),console.log(R.bold.magenta(`
723
+ `)}function Lt(p,e,t=[],s="SKIPPED",i="Validation"){let n=new Date().toISOString(),r=s==="PASS";return{packageName:p||"none",deviceId:e||"none",startTime:n,endTime:n,durationSeconds:0,totalSteps:t.length,passedSteps:r?t.length:0,failedSteps:0,skippedSteps:r?0:t.length,warnSteps:0,errorsDetected:[],steps:t.map((o,a)=>({stepIndex:a+1,timestamp:n,phase:i,description:o.originalText,action:o.type,target:o.target,status:s,durationMs:0}))}}function yn(p,e){return p&&(e&&/password|passwd|pin\b|secret|token|api[_-]?key|auth|credential/i.test(e)?"\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022":p)}var Ye=class{driver;memory;reporter;checkpoints;baselines;lastHierarchy=null;screenDimensions={width:E.screen.fallbackWidth,height:E.screen.fallbackHeight};navBarHeight=0;constructor(e,t,s,i,n,r){this.driver=e||he,this.memory=t||at,this.reporter=s||nt,this.checkpoints=i||Xs,this.baselines=n||Kt,this.semanticResolver=r||ws()}semanticResolver;healEnabled=!1;activeLocale="en";runtimeVariables=new Map;loopStack=[];expandSpecIncludes(e,t=new Set){return Ts(e,t)}async expandSpec(e,t){let s=t||this.semanticResolver,i=e.split(`
724
+ `),n=[],r=0;for(let o of i){let a=o.trim();if(!a||a.startsWith("#")||a.startsWith("//")){n.push(o);continue}let d=this.parsePrompt(a);if(d.length>0&&d[0].type!==void 0&&!a.toLowerCase().startsWith("intent:")){n.push(o);continue}let l=a.replace(/^intent:\s*/i,""),h=this.memory?.getIntentExpansion(l);if(h?.length){n.push(`# [Cached Intent] ${a}`,...h),r+=h.length;continue}let u=await s.resolveIntent(l);if(u?.length){n.push(`# [AI Expanded] ${a}`);let g=u.map(f=>f.originalText);n.push(...g),this.memory&&(this.memory.recordIntentExpansion(l,g),await this.memory.save().catch(()=>{})),r+=u.length}else n.push(o)}return{expanded:n.join(`
725
+ `),stepsAdded:r}}parsePrompt(e,t){return Ct(e,t)}async runSpec(e,t,s){if(!Ce.existsSync(e))throw new Error(`Spec file not found: ${e}`);let i=typeof t=="string"?{packageName:t,serial:s,screenshotMode:"on-failure",continueOnError:!1}:{screenshotMode:"on-failure",continueOnError:!1,...t};i.heal!==void 0&&(this.healEnabled=i.heal),i.noAi&&(this.semanticResolver=ws({provider:"heuristic"})),this.activeLocale=(i.locale||E.locale||"en").toLowerCase(),typeof this.memory.setLocale=="function"&&this.memory.setLocale(this.activeLocale);let n=this.expandSpecIncludes(e),r=n,o=[],a=dt.extractDataDirective(n,me.dirname(e));if(a)r=a.cleanedSpec,o=a.rows;else if(i.dataFile){let b=me.isAbsolute(i.dataFile)?i.dataFile:me.resolve(process.cwd(),i.dataFile);o=dt.loadFromFile(b)}(i.onlyRow!==void 0||i.iterations!==void 0)&&(o.length>0?o=dt.filterRows(o,{onlyRow:i.onlyRow,iterations:i.iterations}):i.iterations&&i.iterations>0&&(o=Array.from({length:i.iterations},()=>({}))));let d=o.length>0?o.map(b=>({...i.variables||{},...b})):[i.variables||{}],c=me.basename(e,me.extname(e)),l=r.match(/#\s*(?:Target\s*)?Package:\s*([a-zA-Z0-9._-]+)/i),h=l?l[1]:void 0;if(i.tags){let b=ti(n),m=i.tags.split(",").map(x=>x.trim().toLowerCase()).filter(Boolean);if(!m.some(x=>b.includes(x)))return console.log(R.yellow(`
726
+ \u23E9 Skipping ${e}: tags [${b.join(", ")}] do not match filter [${m.join(", ")}]`)),Lt(h||i.packageName||"",i.serial||"",[],"SKIPPED")}if(i.listSteps){let b=this.parsePrompt(r,d[0]);return console.log(si(b)),Lt(h||i.packageName||"",i.serial||"",b,"SKIPPED","Listing")}if(i.dryRun){let b=this.parsePrompt(r,d[0]);return console.log(R.bold.cyan(`
727
+ \u{1F50D} [Dry Run] Validated ${b.length} test step(s) in ${e} successfully (no device interaction).`)),Lt(h||i.packageName||"",i.serial||"",b,"PASS","Validation")}if(d.length>1)console.log(R.cyan(`
728
+ \u{1F4CB} Loaded spec with ${d.length} data iteration(s) from ${e}`));else{let b=this.parsePrompt(r,d[0]);console.log(R.cyan(`
729
+ \u{1F4CB} Loaded ${b.length} test step(s) from ${e}`))}console.log(R.gray("Execution Policy: ")+R.bold.white(i.continueOnError?"Continue on Error (Modular Run)":"Fail-Fast (Default)")+R.gray(" | Screenshots: ")+R.bold.white(i.screenshotMode==="all"?"All Steps":"Failure-Only")),i.serial=await this.driver.ensureDefaultDevice(i.serial);let u=i.serial||this.driver.getDefaultDevice()||"Default Device",g=null;i.serial&&(g=Ke(i.serial)),i.embedScreenshots&&typeof this.reporter.setEmbedScreenshots=="function"&&this.reporter.setEmbedScreenshots(!0);let f,y;if(i.serve){let b=typeof i.serve=="number"?i.serve:4040;try{f=await zs({port:b,suiteName:c}),console.log(R.bold.magenta(`
730
730
  \u{1F4E1} Live Monitor streaming at: ${f.url}
731
- `)),typeof this.reporter.onStep=="function"&&(y=this.reporter.onStep(m=>{f?.broadcastStep(m)}))}catch(m){let v=m;console.warn(R.yellow(`Warning: Could not start live server: ${v.message}`))}}let S=null;i.video&&(console.log(R.cyan("\u{1F3AC} Starting ADB screen recording (--video enabled)...")),S=await this.driver.startScreenRecording("/sdcard/prompttest_temp.mp4",i.serial));try{this.screenDimensions=await this.driver.getScreenDimensions(i.serial),this.navBarHeight=typeof this.driver.getNavigationBarHeight=="function"?await this.driver.getNavigationBarHeight(i.serial):0,console.log(R.gray("Target Screen Geometry: ")+R.bold.cyan(`${this.screenDimensions.width}x${this.screenDimensions.height}`)+(this.navBarHeight>0?R.gray(` (Nav Bar: ${this.navBarHeight}px)`):"")),i.apkPath&&(Ce.existsSync(i.apkPath)?(console.log(R.cyan(`\u{1F4E6} Installing APK: ${i.apkPath}...`)),await this.driver.installApk(i.apkPath,i.serial),await new Promise(B=>setTimeout(B,2e3))):console.log(R.yellow(`Warning: Specified APK file not found at: ${i.apkPath}`)));let b=i.packageName||h||(typeof this.driver.getForegroundPackage=="function"?await this.driver.getForegroundPackage(i.serial):null)||"Foreground App";if(b&&!b.includes("Launcher")&&!b.includes("Foreground")){if(!(typeof this.driver.isAppInstalled=="function"?await this.driver.isAppInstalled(b,i.serial):!0))if(i.apkPath&&Ce.existsSync(i.apkPath))console.log(R.cyan(`\u{1F4E6} Target app not found. Auto-installing APK: ${i.apkPath}...`)),await this.driver.installApk(i.apkPath,i.serial),await new Promise(j=>setTimeout(j,2500));else throw new Error(`Target application "${b}" is not installed on device (${d}).
731
+ `)),typeof this.reporter.onStep=="function"&&(y=this.reporter.onStep(m=>{f?.broadcastStep(m)}))}catch(m){let v=m;console.warn(R.yellow(`Warning: Could not start live server: ${v.message}`))}}let S=null;i.video&&(console.log(R.cyan("\u{1F3AC} Starting ADB screen recording (--video enabled)...")),S=await this.driver.startScreenRecording("/sdcard/prompttest_temp.mp4",i.serial));try{this.screenDimensions=await this.driver.getScreenDimensions(i.serial),this.navBarHeight=typeof this.driver.getNavigationBarHeight=="function"?await this.driver.getNavigationBarHeight(i.serial):0,console.log(R.gray("Target Screen Geometry: ")+R.bold.cyan(`${this.screenDimensions.width}x${this.screenDimensions.height}`)+(this.navBarHeight>0?R.gray(` (Nav Bar: ${this.navBarHeight}px)`):"")),i.apkPath&&(Ce.existsSync(i.apkPath)?(console.log(R.cyan(`\u{1F4E6} Installing APK: ${i.apkPath}...`)),await this.driver.installApk(i.apkPath,i.serial),await new Promise(B=>setTimeout(B,2e3))):console.log(R.yellow(`Warning: Specified APK file not found at: ${i.apkPath}`)));let b=i.packageName||h||(typeof this.driver.getForegroundPackage=="function"?await this.driver.getForegroundPackage(i.serial):null)||"Foreground App";if(b&&!b.includes("Launcher")&&!b.includes("Foreground")){if(!(typeof this.driver.isAppInstalled=="function"?await this.driver.isAppInstalled(b,i.serial):!0))if(i.apkPath&&Ce.existsSync(i.apkPath))console.log(R.cyan(`\u{1F4E6} Target app not found. Auto-installing APK: ${i.apkPath}...`)),await this.driver.installApk(i.apkPath,i.serial),await new Promise(j=>setTimeout(j,2500));else throw new Error(`Target application "${b}" is not installed on device (${u}).
732
732
  \u{1F4A1} Suggestions:
733
733
  \u2022 Install the app manually or via: adb install <path-to-apk>
734
- \u2022 Or provide an APK path to auto-install before running: --apk=path/to/app.apk`);let Z=await this.driver.getForegroundPackage(i.serial);(i.fresh||Z&&Z!==b)&&(console.log(R.cyan(`\u{1F680} Launching target application: ${R.bold(b)}...`)),i.fresh&&(await this.driver.forceStop(b,i.serial),await new Promise(j=>setTimeout(j,600))),await this.driver.launchApp(b,i.serial),await new Promise(j=>setTimeout(j,2500)))}i.reporter&&(this.reporter=i.reporter),i.reporters&&typeof this.reporter.setFormats=="function"&&this.reporter.setFormats(i.reporters),this.reporter.init(b,d),await this.memory.init(b),this.lastHierarchy=null;let m=Date.now(),v=0;for(let B=0;B<l.length;B++){let Z=l[B],j=l.length>1,Te=i.onlyRow?`Row ${i.onlyRow}`:j?`Row ${B+1}`:void 0,te=Te?`${c} [${Te}]`:c;j&&(console.log(R.bold.magenta(`
734
+ \u2022 Or provide an APK path to auto-install before running: --apk=path/to/app.apk`);let Z=await this.driver.getForegroundPackage(i.serial);(i.fresh||Z&&Z!==b)&&(console.log(R.cyan(`\u{1F680} Launching target application: ${R.bold(b)}...`)),i.fresh&&(await this.driver.forceStop(b,i.serial),await new Promise(j=>setTimeout(j,600))),await this.driver.launchApp(b,i.serial),await new Promise(j=>setTimeout(j,2500)))}i.reporter&&(this.reporter=i.reporter),i.reporters&&typeof this.reporter.setFormats=="function"&&this.reporter.setFormats(i.reporters),this.reporter.init(b,u),await this.memory.init(b),this.lastHierarchy=null;let m=Date.now(),v=0;for(let B=0;B<d.length;B++){let Z=d[B],j=d.length>1,Te=i.onlyRow?`Row ${i.onlyRow}`:j?`Row ${B+1}`:void 0,te=Te?`${c} [${Te}]`:c;j&&(console.log(R.bold.magenta(`
735
735
  ======================================================
736
- \u{1F504} [Data-Driven Iteration ${B+1}/${l.length}] Row Data: ${JSON.stringify(Z)}
736
+ \u{1F504} [Data-Driven Iteration ${B+1}/${d.length}] Row Data: ${JSON.stringify(Z)}
737
737
  ======================================================`)),i.fresh&&B>0&&b&&(await this.driver.clearAppData(b,i.serial),await new Promise(J=>setTimeout(J,1e3)))),this.runtimeVariables.clear();for(let[J,N]of Object.entries(Z))this.runtimeVariables.set(J,N);this.loopStack=[];let le=this.parsePrompt(r,Z),U=1,be=i.resume&&B===0?await this.checkpoints.getResumeIndex(c):0;be>0&&console.log(R.cyan(`\u23ED Resuming from step ${be+1} (checkpoint found).`));let ne=i.only?ei(i.only):null;for(let J=0;J<le.length;J++){let N=le[J];if(U=J+1,ne&&!ne.has(U)){console.log(R.gray(`[Step ${U}/${le.length}] \u23E9 Skipped (not in --only range: ${i.only})`)),this.reporter.logStep(te,N.originalText,N.type,"SKIPPED",`Filtered out by --only="${i.only}"`,void 0,void 0,0);continue}if(J<be){this.reporter.logStep(te,N.originalText,N.type,"SKIPPED","Resumed \u2014 already passed",void 0,void 0,0);continue}let Q=le.slice(J+1);console.log(R.bold.blue(`
738
- [Step ${U}/${le.length}] ${N.originalText}`));let C=Date.now();try{let M=await this.executeStep(N,i.serial,Q),I=Date.now()-C;if(M&&M.fastForwarded){if(console.log(R.cyan(`\u23E9 Fast-Forward: ${M.reason}. Redundant step(s) bypassed.`)),this.reporter.logStep(te,N.originalText,N.type,"PASS",`Fast-Forward: ${M.reason}`,void 0,void 0,I),console.log(R.green(`\u2714 Step ${U} PASSED (Fast-Forward)`)),M?.skipCount&&M.skipCount>0){let F=M.skipCount;for(let K=0;K<F&&J+1<le.length;K++){J++;let x=le[J],$=J+1;this.reporter.logStep(te,x.originalText,x.type,"PASS",`Fast-Forward: ${M.reason}`,void 0,void 0,0),console.log(R.gray(` [Step ${$}/${le.length}] \u23E9 Fast-Forward: ${x.originalText}`))}}}else{let F;if((i.screenshotMode==="all"||i.saveBaseline||i.compareBaseline)&&(F=await this.driver.captureScreenshot(i.serial)),F&&i.compareBaseline){let K=await this.baselines.compare(te,U,F,i.baselineThreshold);K.passed||(console.log(R.yellow(` \u26A0\uFE0F [Baseline] Step ${U} visual diff ${(K.diffRatio*100).toFixed(1)}% exceeds threshold ${(K.threshold*100).toFixed(1)}%`)),this.reporter.logError(`Visual baseline diff at Step ${U}: ${(K.diffRatio*100).toFixed(1)}% changed`))}F&&i.saveBaseline&&await this.baselines.saveBaseline(te,U,F),this.reporter.logStep(te,N.originalText,N.type,"PASS",N.target||N.value,i.screenshotMode==="all"?F:void 0,void 0,I),console.log(R.green(`\u2714 Step ${U} PASSED`)),i.benchmark&&console.log(R.gray(` \u23F1 [Benchmark] Step ${U} latency: ${I}ms (${N.type}${N.target?` -> "${N.target}"`:""})`))}i.resume&&!j&&await this.checkpoints.save(c,b,J,le.length)}catch(M){let I=M,F=Date.now()-C;if(N.optional){console.log(R.yellow(`\u26AA Step ${U} OPTIONAL (Skipped: ${I.message})`)),this.reporter.logStep(te,N.originalText,N.type,"SKIPPED",`Optional step bypassed: ${I.message}`,void 0,void 0,F);continue}v++,console.log(R.red(`\u274C Step ${U} FAILED: ${I.message}`)),N.target&&this.memory.recordFailure(N.type,N.target);let K=await this.driver.captureScreenshot(i.serial).catch(()=>{}),x;try{let $=me.resolve(process.cwd(),"output"),_=`${c}_step_${U}`,L=me.join($,"failures",_);Ce.existsSync(L)||Ce.mkdirSync(L,{recursive:!0}),K&&await Ce.promises.writeFile(me.join(L,"screenshot.png"),K);let oe=this.lastHierarchy?.xml||await this.driver.getUiHierarchy(i.serial).catch(()=>"");oe&&await Ce.promises.writeFile(me.join(L,"hierarchy.xml"),oe,"utf-8");let ee=await this.driver.getLogcatTail(150,i.serial);await Ce.promises.writeFile(me.join(L,"logcat_tail.log"),ee,"utf-8");let fe=this.lastHierarchy?.flat||[],Ie=N.target&&fe.length>0?We(N.target,fe.map(q=>q.text||q.contentDesc||"").filter(Boolean)):[];await Ce.promises.writeFile(me.join(L,"match_scores.json"),JSON.stringify(Ie,null,2),"utf-8"),x=me.join("failures",_).replace(/\\/g,"/"),console.log(R.red(` \u{1F4C1} Failure Triage Bundle generated at: output/${x}`))}catch{}if(this.reporter.logStep(te,N.originalText,N.type,"FAIL",I.message,K,void 0,F,x),this.reporter.logError(`Step ${U} failed: ${I.message}`),i.continueOnError)console.log(R.yellow("Continuing with next test step (--continue enabled)..."));else{let $=le.slice(J+1);if($.length>0){console.log(R.yellow(`
739
- \u{1F6D1} Aborting dependent flow due to upstream failure at Step ${U}.`)),console.log(R.gray(`Cascading skip applied to ${$.length} downstream step(s):`));for(let _=0;_<$.length;_++){let L=$[_],oe=U+1+_;this.reporter.logStep(te,L.originalText,L.type,"SKIPPED",`Cascading skip: Precondition failed at Step ${U} (${N.originalText})`,void 0,void 0,0),console.log(R.gray(` [Step ${oe}/${le.length}] \u26AA SKIPPED: ${L.originalText}`))}}break}}}}try{let B=this.lastHierarchy;if(B?.flat){let Z=Hs(B.flat,this.screenDimensions.width,this.screenDimensions.height);if(Z.length>0){console.log(R.bold.yellow(`
740
- \u{1F50D} Visual QA Sentinel Warnings (${Z.length} detected):`));for(let j of Z)console.log(R.yellow(` \u2022 [${j.type}] ${j.description}`)),this.reporter.logError(`Visual Defect (${j.type}): ${j.description}`)}}}catch{}await this.memory.save(),i.resume&&v===0&&await this.checkpoints.clear(c);let E=this.memory.getStats();if(E.totalMappings>0&&console.log(R.cyan(`\u{1F9E0} Knowledge Engine: ${E.totalMappings} active learned mapping(s) for ${E.package}`)),S){console.log(R.cyan("\u{1F3AC} Finalizing video recording..."));let B=me.resolve(process.cwd(),"output"),Z=me.join(B,`${c}-recording.mp4`),j=await this.driver.stopScreenRecording(S,Z,i.serial);j&&Ce.existsSync(j)&&(this.reporter.setVideoPath?.(`${c}-recording.mp4`),console.log(R.green(`\u2714 Screen recording saved to: output/${c}-recording.mp4`))),S=null}let k=((Date.now()-m)/1e3).toFixed(1),w=await this.reporter.generateReport(c);f&&(f.broadcastComplete(w),y&&y()),console.log(R.bold.green(`
741
- \u2728 PromptTest Script Execution Finished in ${k}s!`));let A=w.failedSteps===0?R.bold.green:R.bold.yellow;return console.log(A(`Result: ${w.passedSteps}/${w.totalSteps} passed (${w.failedSteps} failed, ${w.skippedSteps} skipped).`)),console.log(R.cyan(`Report saved to output/${c}-report.html
742
- `)),i.json&&console.log(JSON.stringify(w,null,2)),w}finally{if(S)try{await this.driver.stopScreenRecording(S,me.join("output",`${c}-recording.mp4`),i.serial)}catch{}g&&ze(g)}}async getCleanHierarchy(e){let t=await this.driver.getUiHierarchy(e),{flat:s}=ue(t),i=s.find(o=>(o.text==="Dismiss"||o.contentDesc==="Dismiss")&&o.bounds.width>0);i&&(await this.driver.tap(i.bounds.centerX,i.bounds.centerY,e),await new Promise(o=>setTimeout(o,400)),t=await this.driver.getUiHierarchy(e),s=ue(t).flat);let n=s.find(o=>o.contentDesc&&(o.contentDesc.startsWith("!, ")||o.contentDesc.includes("react.dev/link")));if(n){let o=n.bounds.x2-45,a=n.bounds.centerY;await this.driver.tap(o,a,e),await new Promise(l=>setTimeout(l,350)),t=await this.driver.getUiHierarchy(e),s=ue(t).flat}let r=ce(s);return this.lastHierarchy={xml:t,flat:s,timestamp:Date.now(),hash:r},{xml:t,flat:s}}async ensureInViewport(e,t){let s=this.screenDimensions.width,i=this.screenDimensions.height,n=Math.round(s*.5),r=this.navBarHeight>0?i-this.navBarHeight:i,o=this.navBarHeight>0?r*.94:i*T.gestures.bottomNavThresholdRatio;if(e.bounds.centerY>o||e.bounds.y1>o)return!1;let l=e.bounds.y2>r,c=e.bounds.y1<Math.round(i*.04)&&e.bounds.centerY<Math.round(i*.06);return l?(await this.driver.swipe(n,Math.round(i*.75),n,Math.round(i*.45),250,t),await new Promise(p=>setTimeout(p,200)),this.lastHierarchy=null,!0):c?(await this.driver.swipe(n,Math.round(i*.35),n,Math.round(i*.65),250,t),await new Promise(p=>setTimeout(p,200)),this.lastHierarchy=null,!0):!1}async waitForTarget(e,t,s=3e3,i){if(this.lastHierarchy&&Date.now()-this.lastHierarchy.timestamp<T.polling.hierarchyCacheTtlMs){let a=this.matchNodes(this.lastHierarchy.flat,e,i);if(a.length>0)return{flat:this.lastHierarchy.flat,matched:a}}let n=Date.now();for(;Date.now()-n<s;){let{flat:a}=await this.getCleanHierarchy(t),l=this.matchNodes(a,e,i);if(l.length>0)return{flat:a,matched:l};await new Promise(c=>setTimeout(c,ks()))}let{flat:r}=await this.getCleanHierarchy(t),o=this.matchNodes(r,e,i);if(o.length===0&&(this.healEnabled||T.ai.selfHealing))try{let a=await this.semanticResolver.findSuggestions(e,r,{locale:this.activeLocale}),l=T.ai.confidenceThreshold||.75,c=a.find(p=>p.score>=l);if(c){let p=c.node||r.find(h=>(z(c.text,h.text)||z(c.text,h.contentDesc))&&h.bounds.width>0);if(p){console.log(R.yellow(` \u{1F4A1} [Self-Healing] Auto-healed "${e}" \u2192 "${c.text}" (${Math.round(c.score*100)}% confidence, ${c.strategy})`)),i&&(i.healedFrom=e);let h=p.text?"text":p.contentDesc?"contentDesc":"resourceId",d=this.lastHierarchy?.hash,g=Math.min(T.memory?.maxHealedConfidence??.65,c.score);this.memory.recordSuccess(i?.type||"TAP",e,c.text,h,g,e,d),o=[p]}}}catch(a){ke.warn(`Self-healing resolution failed: ${a.message}`)}return{flat:r,matched:o}}buildDiagnosticError(e,t,s){return qs(e,t,s)}async executeStep(e,t,s){let i=Gs.get(e.type);if(!i)throw new Error(`No handler registered for step type: ${e.type}`);e.target&&e.target.includes("$")&&(e.target=Xe(e.target,Object.fromEntries(this.runtimeVariables))),e.value&&e.value.includes("$")&&(e.value=Xe(e.value,Object.fromEntries(this.runtimeVariables)));let n={driver:this.driver,memory:this.memory,serial:t,screenDimensions:this.screenDimensions,navBarHeight:this.navBarHeight,lastHierarchy:this.lastHierarchy,setLastHierarchy:r=>{this.lastHierarchy=r},getCleanHierarchy:r=>this.getCleanHierarchy(r),waitForTarget:(r,o,a,l)=>this.waitForTarget(r,o,a,l),matchNodes:(r,o,a)=>this.matchNodes(r,o,a),ensureInViewport:(r,o)=>this.ensureInViewport(r,o),buildDiagnosticError:(r,o,a)=>this.buildDiagnosticError(r,o,a),findTargetInputField:(r,o,a)=>this.findTargetInputField(r,o,a),upcomingSteps:s,variables:this.runtimeVariables,loopStack:this.loopStack,executeChildSteps:async(r,o)=>{for(let a=0;a<r.length;a++){let l=r[a];await this.executeStep(l,o.serial,r.slice(a+1))}}};return i.execute(e,n)}findTargetInputField(e,t,s){return Zs(e,t,s,this.memory)}matchNodes(e,t,s){return It(e,t,this.memory,this.activeLocale,s,this.lastHierarchy?.hash)}},Jn=new Ye;import P from"chalk";import ii from"fs";import Mi from"path";var je=class{testData={};dataPath;isLoaded=!1;driver;constructor(e,t){this.dataPath=e||Mi.resolve(process.cwd(),"test-data.json"),this.driver=t||he}setTestData(e){this.testData=e,this.isLoaded=!0}async ensureDataLoaded(){if(!this.isLoaded){if(ii.existsSync(this.dataPath))try{let e=await ii.promises.readFile(this.dataPath,"utf-8");this.testData=JSON.parse(e)}catch{this.testData={}}this.isLoaded=!0}}async loadTestData(e){return e&&(this.dataPath=e),this.isLoaded=!1,await this.ensureDataLoaded(),this.testData}inferValueForNode(e,t){let s=[e.text,e.contentDesc,e.resourceId].join(" ").toLowerCase(),i="",n=t.filter(o=>o.text&&!o.clickable&&o.bounds.centerY<e.bounds.centerY&&e.bounds.centerY-o.bounds.centerY<250&&Math.abs(o.bounds.centerX-e.bounds.centerX)<400);n.length>0&&(i=n[n.length-1].text.toLowerCase());let r=`${s} ${i}`.toLowerCase();if(r.includes("review")||r.includes("feedback")||r.includes("comment")||r.includes("write a review")||r.includes("experience")){if(!this.testData.review?.text)throw new Error("Missing test-data.json field: review.text");return this.testData.review.text}if(r.includes("card")||r.includes("credit")||r.includes("debit")||r.includes("card number")){let o=this.testData.payment?.card;if(o)return String(o);let a="4532";for(let l=0;l<12;l++)a+=Math.floor(Math.random()*10);return a}if(r.includes("phone")||r.includes("mobile")||!r.includes("card")&&r.includes("number")||r.includes("contact")){let o=this.testData.auth?.phone||this.testData.profile?.phone;if(!o)throw new Error("Missing test-data.json field: auth.phone or profile.phone");return o}if(r.includes("email")||r.includes("e-mail")||r.includes("mail")){let o=this.testData.profile?.email||this.testData.auth?.email;if(!o)throw new Error("Missing test-data.json field: profile.email or auth.email");return o}if(r.includes("cvv")||r.includes("cvc")||r.includes("security code"))return"123";if(r.includes("expiry")||r.includes("exp date")||r.includes("expiration"))return"12/28";if(r.includes("pincode")||r.includes("zip")||r.includes("postal")){if(!this.testData.profile?.pincode)throw new Error("Missing test-data.json field: profile.pincode");return this.testData.profile.pincode}if(e.password||r.includes("password")||/\bpin\b/.test(r)&&!r.includes("pincode")||r.includes("passcode")){if(!this.testData.auth?.password)throw new Error("Missing test-data.json field: auth.password");return this.testData.auth.password}if(r.includes("otp")||r.includes("verification")||r.includes("code")&&!r.includes("postal")&&!r.includes("zip")){if(!this.testData.auth?.otp)throw new Error("Missing test-data.json field: auth.otp");return this.testData.auth.otp}if(r.includes("address")||r.includes("street")||r.includes("location")){if(!this.testData.profile?.address)throw new Error("Missing test-data.json field: profile.address");return this.testData.profile.address}if(r.includes("city")||r.includes("state")){if(!this.testData.profile?.city)throw new Error("Missing test-data.json field: profile.city");return this.testData.profile.city}if(r.includes("name")||r.includes("full name")||r.includes("first name")){if(!this.testData.profile?.name)throw new Error("Missing test-data.json field: profile.name");return this.testData.profile.name}if(r.includes("search")||r.includes("find")||r.includes("query")){if(!this.testData.search?.query)throw new Error("Missing test-data.json field: search.query");return this.testData.search.query}return this.testData.review?.text||"PromptTest Auto QA Test Data"}async fillAndSubmitForm(e,t,s=!0,i=!1){await this.ensureDataLoaded();let n=_e(e),r=[];if(n.length===0)return{filledFields:[],submitted:!1};let o=!1;for(let c of n){let p=c.resourceId||c.text||`input_${c.bounds.centerX}_${c.bounds.centerY}`,h=(c.text||"").trim(),d=!h||/^enter\s+/i.test(h)||/^type\s+/i.test(h)||/^e\.g\./i.test(h)||/^(email|email address|password|phone|name|search)$/i.test(h);if(!i&&!d){r.push({fieldId:p,fieldLabel:c.text||c.contentDesc||c.resourceId,valueEntered:h});continue}let g=this.inferValueForNode(c,e);await this.driver.tap(c.bounds.centerX,c.bounds.centerY,t),await new Promise(f=>setTimeout(f,400)),await this.driver.clearField(t,g.length+10),await new Promise(f=>setTimeout(f,200)),await this.driver.inputText(g,t),await new Promise(f=>setTimeout(f,300)),o=!0,r.push({fieldId:p,fieldLabel:c.text||c.contentDesc||c.resourceId,valueEntered:g})}o&&(await this.driver.pressKey(4,t),await new Promise(c=>setTimeout(c,500)));let a=!1,l;if(s){let c=e.filter(p=>!p.clickable||p.bounds.width===0?!1:Ns.some(h=>z(h,p.text)||z(h,p.contentDesc)||z(h,p.resourceId)));if(c.length>0){let p=["submit","sign in","signin","login","save","confirm","proceed","continue"];c.sort((d,g)=>{let f=(d.text||d.contentDesc||d.resourceId||"").toLowerCase(),y=(g.text||g.contentDesc||g.resourceId||"").toLowerCase(),S=p.findIndex(E=>f.includes(E)),b=p.findIndex(E=>y.includes(E)),m=S>=0?S:99,v=b>=0?b:99;return m!==v?m-v:g.bounds.centerY-d.bounds.centerY});let h=c[0];l=h.text||h.contentDesc||h.resourceId,await this.driver.tap(h.bounds.centerX,h.bounds.centerY,t),await new Promise(d=>setTimeout(d,T.settle.submitWaitMs));try{let d=await this.driver.getUiHierarchy(t),{flat:g}=ue(d),f=_e(g);a=!(f.length>0&&n.every(S=>f.some(b=>b.resourceId&&b.resourceId===S.resourceId)))}catch{a=!0}}}return{filledFields:r,submitted:a,submitButtonText:l}}},ri=new je;import H from"chalk";var Rt=class{driver;reporter;memory;formFiller;screenLedger=new Map;callStack=[];executedStepCount=0;visitedScreenHashes=new Set;devDefectsList=[];safetyHitList=[];externalSkippedList=[];constructor(e=he,t=nt,s=at){this.driver=e,this.reporter=t,this.memory=s,this.formFiller=new je(void 0,e)}async getCleanUiHierarchy(e,t,s=5){let i=await this.driver.getUiHierarchy(t),{flat:n}=ue(i),r=0;for(;r<s;){let o=yt(n);if(!o)break;r++;let a=`[${(o.severity||"error").toUpperCase()} - ${o.type.toUpperCase()}]`,l=o.sourceLocation?` [${o.sourceLocation}]`:"";console.log(H.red(` \u{1F6A8} Global Dev Console Intercepted: ${a} "${o.errorText.slice(0,80)}"${l}`)),this.devDefectsList.push(o.sourceLocation?`${o.errorText} (${o.sourceLocation})`:o.errorText);let c=await this.driver.captureScreenshot(t);this.reporter.logStep("Dev Overlay Triage",`Intercepted and triaged ${a}: "${o.errorText}"${l}`,"Verify","FAIL",o.errorText,c,{errors:[o.sourceLocation?`${o.errorText} at ${o.sourceLocation}`:o.errorText]}),o.dismissButton&&o.dismissButton.bounds.width>0?(console.log(H.gray(" Dismissing overlay via dismiss button...")),await this.driver.tap(o.dismissButton.bounds.centerX,o.dismissButton.bounds.centerY,t)):o.isToast&&o.node&&o.node.bounds.width>0?(console.log(H.gray(" Expanding toast notification to access Dismiss button...")),await this.driver.tap(o.node.bounds.centerX,o.node.bounds.centerY,t)):(console.log(H.gray(" Pressing Back to dismiss overlay...")),await this.driver.pressBack(t)),await new Promise(p=>setTimeout(p,800)),i=await this.driver.getUiHierarchy(t),n=ue(i).flat}return{xml:i,flat:n}}async dismissSoftKeyboard(e){try{await this.driver.pressKey(111,e),await new Promise(t=>setTimeout(t,150))}catch{}}async packageJailGuard(e,t){let s=await this.driver.getForegroundPackage(t);if(!s||!s.includes(e)){console.log(H.yellow(` \u{1F6A8} External App Jailbreak Detected [${s||"Unknown"}]. Recovering...`)),await this.driver.pressBack(t),await new Promise(n=>setTimeout(n,800));let i=await this.driver.getForegroundPackage(t);return(!i||!i.includes(e))&&(console.log(H.red(` Force restoring ${e} foreground...`)),await this.driver.launchApp(e,t),await new Promise(n=>setTimeout(n,1500)),this.callStack=this.callStack.slice(0,1)),!0}return!1}async handleExternalMediaChooser(e,t){let s=await this.driver.getForegroundPackage(t);if(s==="android"||s?.includes("resolver")||s?.includes("intentresolver")||s&&!s.includes(e)){console.log(H.yellow(` \u{1F6E1}\uFE0F External Media Chooser / Third-Party App Intercepted [${s||"Unknown"}]. Dismissing to stay in-app...`)),await this.driver.pressBack(t),await new Promise(r=>setTimeout(r,800));let n=await this.driver.getForegroundPackage(t);return(!n||!n.includes(e))&&(await this.driver.launchApp(e,t),await new Promise(r=>setTimeout(r,1200)),this.callStack=this.callStack.slice(0,1)),!0}return!1}catalogScreen(e,t,s=[]){let i=[],n=t.height,r=n*.06,o=n*.88,a=m=>s.some(v=>Math.abs(v.bounds.centerX-m.bounds.centerX)<30&&Math.abs(v.bounds.centerY-m.bounds.centerY)<30),l=_e(e);for(let m of l){if(a(m))continue;let v=m.text||m.contentDesc||m.resourceId||"Text Input";i.push({node:m,type:"input",label:v,tested:!1})}let c=it(e);for(let m of c){if(a(m))continue;let v=m.text||m.contentDesc||m.resourceId||"Toggle Control";i.push({node:m,type:"toggle",label:v,tested:!1})}let p=Ge(e);for(let m of p){if(a(m)||Oe([m],n,t.width)||we([m],n,t.width,!0))continue;let v=m.text||m.contentDesc||m.resourceId||"Action Button";if(Pe(m)){this.externalSkippedList.push(v);continue}let E=m.selected!==void 0||m.checkable||/(?:tab|chip|pill|filter|segment|toggle)/i.test(`${m.resourceId} ${m.className} ${m.contentDesc}`)||/(?:today|yesterday|all|active|archived|pending|completed|present|absent)/i.test(v);i.push({node:m,type:E?"toggle":"transition",label:v,tested:!1})}let h=Os(e,n,t.width);for(let m of h){if(a(m)||we([m],n,t.width,!0)||i.some(E=>Math.abs(E.node.bounds.centerX-m.bounds.centerX)<25&&Math.abs(E.node.bounds.centerY-m.bounds.centerY)<25))continue;let v=m.text||m.contentDesc||m.resourceId||"Notification / Header Action";if(Pe(m)){this.externalSkippedList.push(v);continue}i.push({node:m,type:"transition",label:v,tested:!1})}let d=e.filter(m=>{if(!m.clickable||m.bounds.width===0)return!1;let v=`${m.text} ${m.contentDesc} ${m.resourceId}`.toLowerCase();return v.includes("now playing")||v.includes("play")||v.includes("pause")});for(let m of d){if(a(m)||i.some(E=>Math.abs(E.node.bounds.centerX-m.bounds.centerX)<25&&Math.abs(E.node.bounds.centerY-m.bounds.centerY)<25))continue;let v=m.text||m.contentDesc||m.resourceId||"Media Control";i.push({node:m,type:"toggle",label:v,tested:!1})}let g=bt(e,t).filter(m=>!a(m)&&m.bounds.centerY>r&&m.bounds.centerY<o&&!we([m],n,t.width,!0)&&!Pe(m)),f=Us(g,2);for(let m of f){let v=m.text||m.contentDesc||m.resourceId||`Item (${m.bounds.centerX},${m.bounds.centerY})`;i.push({node:m,type:"transition",label:v,tested:!1})}let y=0,S=0,b=[];for(let m of i){let v=/\.(?:mp4|mkv|mov|webm|flv|avi)\b/i.test(m.label),E=/\.(?:mp3|wav|m4a|aac|ogg)\b/i.test(m.label);if(v){if(y++,y>1)continue}else if(E&&(S++,S>1))continue;b.push(m)}return b}async safeBacktrack(e,t,s,i,n=!0){let{flat:r}=await this.getCleanUiHierarchy(t,s),{height:o,width:a}=await this.driver.getScreenDimensions(s),l=Ne(r,{width:a,height:o});if(l===e)return!0;let c=we(r,o,a,!0);if(c&&c.bounds.width>0){console.log(H.gray(` [Backtrack] Tapping in-app back/close button "${c.text||c.contentDesc||c.className}"...`)),await this.driver.tap(c.bounds.centerX,c.bounds.centerY,s),await new Promise(d=>setTimeout(d,1e3)),await this.packageJailGuard(t,s);let p=await this.getCleanUiHierarchy(t,s),h=Ne(p.flat,{width:a,height:o});if(h===e||h!==l)return!0}if(i&&i.bounds.width>0){console.log(H.gray(` [Backtrack] Restoring root domain via tab "${i.text||i.contentDesc||"Root Tab"}"...`)),await this.driver.tap(i.bounds.centerX,i.bounds.centerY,s),await new Promise(d=>setTimeout(d,1e3)),await this.packageJailGuard(t,s);let p=await this.getCleanUiHierarchy(t,s),h=Ne(p.flat,{width:a,height:o});if(h===e||h!==l)return!0}if(n){if(console.log(H.gray(" [Backtrack] Sending fallback KEYCODE_BACK...")),await this.driver.pressKey(4,s),await new Promise(g=>setTimeout(g,1e3)),await this.packageJailGuard(t,s))return console.log(H.yellow(" \u26A0\uFE0F Backtrack via KEYCODE_BACK caused app jailbreak. Aborting branch restoration.")),!1;let h=await this.getCleanUiHierarchy(t,s),d=Ne(h.flat,{width:a,height:o});if(d===e||d!==l)return!0}return!1}async explore(e){let{packageName:t,serial:s,maxScreens:i=30,maxDepth:n=3,stepBudget:r=100,maxInteractionsPerScreen:o=6,safetyMode:a="strict",safetyBlacklist:l=[]}=e;console.log(H.bold.cyan(`
743
- \u{1F916} PromptTest Universal State-Graph DFS Engine`)),console.log(H.gray(`Target Package: ${t}`)),console.log(H.gray(`Safety Policy: ${a.toUpperCase()}`)),console.log(H.gray(`Limits: Max Screens = ${i}, Step Budget = ${r}, Max Depth = ${n}`)),await this.driver.clearCrashLogs(s);let c=await this.driver.getScreenDimensions(s),p=await this.driver.getForegroundPackage(s);(!p||!p.includes(t))&&(console.log(H.gray(`Launching ${t}...`)),await this.driver.launchApp(t,s),await new Promise(S=>setTimeout(S,2500)));let{flat:h}=await this.getCleanUiHierarchy(t,s);await this.dismissSoftKeyboard(s);let d=Yt(h,c,t);console.log(H.magenta(`\u26A1 Universal Paradigm Detected: [${d.paradigm.toUpperCase()}] with ${d.roots.length} root node(s).`));let g=[],f;if(d.paradigm==="drawer"&&d.roots.length>0){f=d.roots[0];let S={...h[0]||{},text:"Home Screen / Main Hub",contentDesc:"Home Screen / Main Hub",clickable:!0,bounds:{x1:0,y1:0,x2:c.width,y2:c.height,centerX:c.width/2,centerY:c.height/2,width:c.width,height:c.height}};g.push(S),console.log(H.gray(" Opening drawer to catalog root destinations...")),await this.driver.tap(f.bounds.centerX,f.bounds.centerY,s),await new Promise(w=>setTimeout(w,1200));let b=await this.getCleanUiHierarchy(t,s),m=b.flat.filter(w=>{if(!w.clickable||w.bounds.width===0||w.bounds.height===0||w.bounds.width>=c.width*.95&&w.bounds.height>=c.height*.95||we([w],c.height,c.width,!0))return!1;let A=`${w.contentDesc} ${w.text}`.trim(),B=w.bounds.width>c.width*.15&&w.bounds.height>c.height*.05;return A.toLowerCase().includes("developed by")||w.bounds.centerY>c.height*.85?!1:A.length>=2||B});for(let w of m)g.some(A=>Math.abs(A.bounds.centerX-w.bounds.centerX)<30&&Math.abs(A.bounds.centerY-w.bounds.centerY)<30)||g.push(w);let v=we(b.flat,c.height,c.width,!0);v?await this.driver.tap(v.bounds.centerX,v.bounds.centerY,s):await this.driver.tap(f.bounds.centerX,f.bounds.centerY,s),await new Promise(w=>setTimeout(w,1200));let E=await this.getCleanUiHierarchy(t,s);if(E.flat.some(w=>`${w.contentDesc} ${w.text}`.includes("Gallery")&&`${w.contentDesc} ${w.text}`.includes("Planner"))){let w=we(E.flat,c.height,c.width,!0);w?await this.driver.tap(w.bounds.centerX,w.bounds.centerY,s):await this.driver.tap(c.width-50,c.height/2,s),await new Promise(A=>setTimeout(A,1e3))}console.log(H.magenta(` Discovered ${g.length} destinations (1 Main Hub + ${g.length-1} Drawer destinations).`))}else d.roots.length>0?g=d.roots:g=[h[0]||{text:"Main Hub",clickable:!0}];let y=1;for(let S of g){if(this.executedStepCount>=r||this.visitedScreenHashes.size>=i)break;let b=S.text||S.contentDesc||`Root #${y}`;if(console.log(H.yellow(`
744
- [Domain ${y}/${g.length}] Entering Root Tree: "${b}"...`)),d.paradigm==="bottom_tabs"||d.paradigm==="top_tabs"){let E=S.bounds.height<25?Math.max(S.bounds.y1-10,S.bounds.centerY):Math.min(S.bounds.centerY,S.bounds.y2-4);await this.driver.tap(S.bounds.centerX,E,s),this.executedStepCount++,await new Promise(k=>setTimeout(k,1200))}else d.paradigm==="drawer"&&y>1&&f&&(await this.dismissSoftKeyboard(s),console.log(H.gray(` Opening drawer to select "${b}"...`)),await this.driver.tap(f.bounds.centerX,f.bounds.centerY,s),await new Promise(E=>setTimeout(E,1e3)),await this.driver.tap(S.bounds.centerX,S.bounds.centerY,s),this.executedStepCount++,await new Promise(E=>setTimeout(E,1500)));h=(await this.getCleanUiHierarchy(t,s)).flat,await this.dismissSoftKeyboard(s);let v=y===1?Math.max(25,Math.ceil(r*.45)):Math.max(8,Math.ceil(r*.55/Math.max(1,g.length-1)));if(await this.exploreDfsNode({packageName:t,serial:s,screenDims:c,rootNodes:d.roots,activeRootNode:S,currentDepth:0,maxDepth:n,maxScreens:i,stepBudget:r,domainStepLimit:this.executedStepCount+v,maxInteractionsPerScreen:o,safetyMode:a,safetyBlacklist:l,domainLabel:b}),d.paradigm==="drawer"&&y>1){let E=0;for(;E<4;){let k=await this.getCleanUiHierarchy(t,s),w=Oe(k.flat,c.height,c.width),A=k.flat.some(Z=>`${Z.contentDesc} ${Z.text}`.includes("Gallery")&&`${Z.contentDesc} ${Z.text}`.includes("Planner"));if(w&&!A)break;let B=we(k.flat,c.height,c.width,!0);if(B)console.log(H.gray(" [Domain Wrap-Up] Returning to Home Screen via in-app back...")),await this.driver.tap(B.bounds.centerX,B.bounds.centerY,s),await new Promise(Z=>setTimeout(Z,1e3)),E++;else break}}if(y===1&&g.length===1){let E=await this.getCleanUiHierarchy(t,s),k=Yt(E.flat,c,t);if((k.paradigm==="bottom_tabs"||k.paradigm==="top_tabs")&&k.roots.length>1){console.log(H.magenta(`
745
- \u26A1 Post-Auth Navigation Discovered: [${k.paradigm.toUpperCase()}] with ${k.roots.length} root domain(s)!`)),d.paradigm=k.paradigm,d.roots=k.roots;let w=k.roots.slice(1);g.push(...w.length>0?w:k.roots)}}y++}for(let S of this.visitedScreenHashes)this.memory.markScreenCrawled(S);await this.memory.save(),console.log(H.green(`
746
- \u2714 Universal DFS Traversal Complete!`)),console.log(H.cyan(` Visited Screens: ${this.visitedScreenHashes.size}`)),console.log(H.cyan(` Total Steps Executed: ${this.executedStepCount}/${r}`)),console.log(H.cyan(` Defects Triaged: ${this.devDefectsList.length}`))}async exploreDfsNode(e){let{packageName:t,serial:s,screenDims:i,rootNodes:n,activeRootNode:r,currentDepth:o,maxDepth:a,maxScreens:l,stepBudget:c,domainStepLimit:p,maxInteractionsPerScreen:h,safetyMode:d,safetyBlacklist:g,domainLabel:f}=e;if(this.executedStepCount>=c||this.visitedScreenHashes.size>=l||p&&this.executedStepCount>=p)return;let{flat:y}=await this.getCleanUiHierarchy(t,s),S=ce(y),b=Ne(y,i);this.visitedScreenHashes.add(S);let m=this.screenLedger.get(b);if(m){if(m.status==="FULLY_EXPLORED"){console.log(H.gray(` \u26A1 Cycle Detected: Screen [${b.slice(0,8)}] already fully explored. Pruning branch.`));return}}else{let w=this.catalogScreen(y,i,n);m={hash:S,semanticHash:b,title:`${f} (depth ${o})`,elements:w,status:"IN_PROGRESS",depth:o,interactionCount:0},this.screenLedger.set(b,m),console.log(H.cyan(` \u{1F50E} Discovered Screen [${b.slice(0,8)}] at depth ${o} with ${w.length} candidate element(s).`))}this.callStack.push({screenHash:S,semanticHash:b,title:m.title,timestamp:Date.now()});let v=m.elements.filter(w=>w.type==="input"&&!w.tested);if(v.length>0&&m.interactionCount<h){console.log(H.magenta(` Filling in-place form fields (${v.length} inputs)...`));let w=await this.formFiller.fillAndSubmitForm(y,s,!0,!1);this.executedStepCount++,m.interactionCount++;for(let A of v)A.tested=!0;await this.dismissSoftKeyboard(s),await this.packageJailGuard(t,s),this.reporter.logStep("In-Place Form Fill",`Populated ${w.filledFields.length} field(s) on [${b.slice(0,8)}]`,"FormSubmit","PASS",w.submitButtonText||"Auto")}let E=m.elements.filter(w=>w.type==="toggle"&&!w.tested);for(let w of E){if(this.executedStepCount>=c||m.interactionCount>=h)break;if(w.tested=!0,Ee(w.node,g,d)){this.safetyHitList.push(w.label);continue}console.log(H.gray(` Exercising toggle: "${w.label.slice(0,30)}"...`)),this.executedStepCount++,m.interactionCount++,await this.driver.tap(w.node.bounds.centerX,w.node.bounds.centerY,s),await new Promise(A=>setTimeout(A,600)),this.reporter.logStep("In-Place Toggle",`Toggled control "${w.label}"`,"Tap","PASS",w.label)}let k=m.elements.filter(w=>w.type==="transition"&&!w.tested);for(let w of k){if(this.executedStepCount>=c||this.visitedScreenHashes.size>=l||p&&this.executedStepCount>=p&&!(o===0&&f.includes("Home Screen"))||m.interactionCount>=h)break;if(w.tested=!0,Pe(w.node)){this.externalSkippedList.push(w.label);continue}if(Ee(w.node,g,d)){this.safetyHitList.push(w.label);continue}console.log(H.magenta(` \u26A1 [DFS Depth ${o}] Testing transition: "${w.label.slice(0,40)}"...`)),this.executedStepCount++,m.interactionCount++,await this.driver.tap(w.node.bounds.centerX,w.node.bounds.centerY,s),await new Promise(j=>setTimeout(j,1500)),await this.dismissSoftKeyboard(s),await this.handleExternalMediaChooser(t,s),await this.packageJailGuard(t,s);let A=await this.getCleanUiHierarchy(t,s),Z=Ne(A.flat,i)!==b;if(this.reporter.logStep("DFS Transition",`Tapped "${w.label}" [${Z?"Navigated":"In-Place"}]`,"Tap","PASS",w.label),Z){if(o<a){let te=o===0&&f.includes("Home Screen")?Math.min(this.executedStepCount+3,p||this.executedStepCount+3):p;await this.exploreDfsNode({packageName:t,serial:s,screenDims:i,rootNodes:n,activeRootNode:r,domainStepLimit:te,currentDepth:o+1,maxDepth:a,maxScreens:l,stepBudget:c,maxInteractionsPerScreen:h,safetyMode:d,safetyBlacklist:g,domainLabel:`${f} > ${w.label.slice(0,20)}`})}console.log(H.gray(` [DFS Backtrack] Returning to [${b.slice(0,8)}]...`)),await this.safeBacktrack(b,t,s,o===0?r:void 0,o>0),await this.dismissSoftKeyboard(s);let j=await this.getCleanUiHierarchy(t,s);if(Ne(j.flat,i)!==b){let te=we(j.flat,i.height,i.width,!0);te&&(console.log(H.gray(" [Backtrack Verification] Re-tapping in-app back/close button...")),await this.driver.tap(te.bounds.centerX,te.bounds.centerY,s),await new Promise(be=>setTimeout(be,1e3)),await this.packageJailGuard(t,s));let le=await this.getCleanUiHierarchy(t,s);if(Ne(le.flat,i)!==b){console.log(H.yellow(` \u26A0\uFE0F Unable to restore parent screen [${b.slice(0,8)}]. Unwinding branch to prevent jailbreak loop.`));break}}}}m.status="FULLY_EXPLORED",this.callStack.pop()}};var ut=class{driver;formFiller;reporter;memory;safetyHitList=[];externalSkippedList=[];devDefectsList=[];visitedScreenHashes=new Set;executedStepCount=0;constructor(e,t,s,i){this.driver=e||he,this.formFiller=t||ri,this.reporter=s||nt,this.memory=i||at}getMemory(){return this.memory}getSafetyHitList(){return this.safetyHitList}getExternalSkippedList(){return this.externalSkippedList}getDevDefectsList(){return this.devDefectsList}getVisitedScreensCount(){return this.visitedScreenHashes.size}async packageJailGuard(e,t){let s=await this.driver.getForegroundPackage(t);if(s&&!s.includes(e)){console.log(P.yellow(` \u{1F6E1}\uFE0F Jail Containment: App escaped to "${s}". Executing containment recovery...`)),await this.driver.pressBack(t),await new Promise(n=>setTimeout(n,600));let i=await this.driver.getForegroundPackage(t);return(!i||!i.includes(e))&&(console.log(P.gray(` Force re-launching ${e} to restore foreground...`)),await this.driver.launchApp(e,t),await new Promise(n=>setTimeout(n,1200))),this.reporter.logStep("Jail Containment",`App escaped to "${s}"; successfully contained and restored "${e}"`,"Back","PASS"),!0}return!1}async getCleanUiHierarchy(e,t,s=5){let i=await this.driver.getUiHierarchy(t),{flat:n}=ue(i),r=0;for(;r<s;){let o=yt(n);if(!o)break;r++;let a=`[${(o.severity||"error").toUpperCase()} - ${o.type.toUpperCase()}]`,l=o.sourceLocation?` [${o.sourceLocation}]`:"";console.log(P.red(` \u{1F6A8} Global Dev Console Intercepted: ${a} "${o.errorText.slice(0,80)}"${l}`)),this.devDefectsList.push(o.sourceLocation?`${o.errorText} (${o.sourceLocation})`:o.errorText);let c=await this.driver.captureScreenshot(t);this.reporter.logStep("Dev Overlay Triage",`Intercepted and triaged ${a}: "${o.errorText}"${l}`,"Verify","FAIL",o.errorText,c,{errors:[o.sourceLocation?`${o.errorText} at ${o.sourceLocation}`:o.errorText]}),o.dismissButton&&o.dismissButton.bounds.width>0?(console.log(P.gray(" Dismissing overlay via dismiss button...")),await this.driver.tap(o.dismissButton.bounds.centerX,o.dismissButton.bounds.centerY,t)):o.isToast&&o.node&&o.node.bounds.width>0?(console.log(P.gray(" Expanding toast notification to access Dismiss button...")),await this.driver.tap(o.node.bounds.centerX,o.node.bounds.centerY,t)):(console.log(P.gray(" Pressing Back to dismiss overlay...")),await this.driver.pressBack(t)),await new Promise(p=>setTimeout(p,800)),i=await this.driver.getUiHierarchy(t),n=ue(i).flat}return{xml:i,flat:n}}async handleDevOverlays(e,t,s){let i=yt(e);if(!i)return!1;let n=`[${(i.severity||"error").toUpperCase()} - ${i.type.toUpperCase()}]`,r=i.sourceLocation?` [${i.sourceLocation}]`:"";console.log(P.red(` \u{1F6A8} Dev Overlay Detected: ${n} "${i.errorText.slice(0,80)}"${r}`)),this.devDefectsList.push(i.sourceLocation?`${i.errorText} (${i.sourceLocation})`:i.errorText);let o=await this.driver.captureScreenshot(s);return this.reporter.logStep("Dev Overlay Triage",`Detected and triaged ${n} error: "${i.errorText}"${r}`,"Verify","FAIL",i.errorText,o,{errors:[i.sourceLocation?`${i.errorText} (${i.sourceLocation})`:i.errorText]}),i.dismissButton&&i.dismissButton.bounds.width>0?(console.log(P.gray(" Dismissing error overlay via dismiss button...")),await this.driver.tap(i.dismissButton.bounds.centerX,i.dismissButton.bounds.centerY,s)):i.isToast&&i.node&&i.node.bounds.width>0?(console.log(P.gray(" Expanding toast notification to access Dismiss button...")),await this.driver.tap(i.node.bounds.centerX,i.node.bounds.centerY,s)):(console.log(P.gray(" Pressing Back to dismiss error overlay...")),await this.driver.pressBack(s)),await new Promise(a=>setTimeout(a,800)),!0}async dismissSoftKeyboard(e){try{await this.driver.pressKey(111,e),await new Promise(t=>setTimeout(t,200))}catch{}}async explore(e){let{packageName:t,serial:s,maxTabs:i=T.explorer?.maxTabs||15,exploreLists:n=!0,skipAlreadyCrawled:r=!1,safetyMode:o=T.safety?.mode||"strict",safetyBlacklist:a=T.safety?.customBlacklist?[...T.safety.customBlacklist]:[],maxScreens:l=T.explorer?.maxScreens||30,stepBudget:c=T.explorer?.stepBudget||100,screenshots:p=T.explorer?.screenshots||"state-change"}=e;console.log(P.cyan(`
747
- \u{1F916} PromptTest Autonomous Exploration Brain v3`)),console.log(P.gray("Target Package: ")+P.bold.white(t)),console.log(P.gray("Safety Policy: ")+P.bold.yellow(o.toUpperCase())+(a.length>0?P.gray(` (+${a.length} custom blacklist)`):"")),console.log(P.gray("Screenshots Policy: ")+P.bold.white(p));let h=async(y,S=!0)=>{if(!(p==="failure-only"&&y!=="FAIL")&&!(p==="state-change"&&!S&&y!=="FAIL"))try{return await this.driver.captureScreenshot(s)}catch{return}};await this.memory.init(t);let d=s||this.driver.getDefaultDevice(),g=d||"Default Device";this.reporter.init(t,g);let f=null;d&&(f=Ke(d)),this.safetyHitList=[],this.externalSkippedList=[],this.devDefectsList=[],this.visitedScreenHashes.clear(),this.executedStepCount=0;try{if(await this.driver.clearCrashLogs(s),(e.strategy||T.explorer?.strategy||"heuristic")==="dfs"){let ne=new Rt(this.driver,this.reporter,this.memory);await ne.explore({packageName:t,serial:s,maxScreens:l,maxDepth:e.maxDepth||T.explorer?.maxDepth||5,stepBudget:c,safetyMode:o,safetyBlacklist:a,screenshotPolicy:p,skipAlreadyCrawled:r}),this.safetyHitList=ne.safetyHitList,this.externalSkippedList=ne.externalSkippedList,this.devDefectsList=ne.devDefectsList,this.visitedScreenHashes=ne.visitedScreenHashes,this.executedStepCount=ne.executedStepCount;let J=this.memory.getStats();this.reporter.logStep("Coverage Audit",`State Graph Coverage: Visited ${this.visitedScreenHashes.size} unique screen state(s). Memory Engine cached ${J.totalScreens} crawled screen(s).`,"Verify","PASS"),await this.reporter.generateReport(),console.log(P.bold.green(`
738
+ [Step ${U}/${le.length}] ${N.originalText}`));let C=Date.now();try{let M=await this.executeStep(N,i.serial,Q),I=Date.now()-C;if(M&&M.fastForwarded){if(console.log(R.cyan(`\u23E9 Fast-Forward: ${M.reason}. Redundant step(s) bypassed.`)),this.reporter.logStep(te,N.originalText,N.type,"PASS",`Fast-Forward: ${M.reason}`,void 0,void 0,I),console.log(R.green(`\u2714 Step ${U} PASSED (Fast-Forward)`)),M?.skipCount&&M.skipCount>0){let F=M.skipCount;for(let K=0;K<F&&J+1<le.length;K++){J++;let T=le[J],k=J+1;this.reporter.logStep(te,T.originalText,T.type,"PASS",`Fast-Forward: ${M.reason}`,void 0,void 0,0),console.log(R.gray(` [Step ${k}/${le.length}] \u23E9 Fast-Forward: ${T.originalText}`))}}}else{let F;if((i.screenshotMode==="all"||i.saveBaseline||i.compareBaseline)&&(F=await this.driver.captureScreenshot(i.serial)),F&&i.compareBaseline){let K=await this.baselines.compare(te,U,F,i.baselineThreshold);K.passed||(console.log(R.yellow(` \u26A0\uFE0F [Baseline] Step ${U} visual diff ${(K.diffRatio*100).toFixed(1)}% exceeds threshold ${(K.threshold*100).toFixed(1)}%`)),this.reporter.logError(`Visual baseline diff at Step ${U}: ${(K.diffRatio*100).toFixed(1)}% changed`))}F&&i.saveBaseline&&await this.baselines.saveBaseline(te,U,F),this.reporter.logStep(te,N.originalText,N.type,"PASS",N.target||N.value,i.screenshotMode==="all"?F:void 0,void 0,I),console.log(R.green(`\u2714 Step ${U} PASSED`)),i.benchmark&&console.log(R.gray(` \u23F1 [Benchmark] Step ${U} latency: ${I}ms (${N.type}${N.target?` -> "${N.target}"`:""})`))}i.resume&&!j&&await this.checkpoints.save(c,b,J,le.length)}catch(M){let I=M,F=Date.now()-C;if(N.optional){console.log(R.yellow(`\u26AA Step ${U} OPTIONAL (Skipped: ${I.message})`)),this.reporter.logStep(te,N.originalText,N.type,"SKIPPED",`Optional step bypassed: ${I.message}`,void 0,void 0,F);continue}v++,console.log(R.red(`\u274C Step ${U} FAILED: ${I.message}`)),N.target&&this.memory.recordFailure(N.type,N.target);let K=await this.driver.captureScreenshot(i.serial).catch(()=>{}),T;try{let k=me.resolve(process.cwd(),"output"),_=`${c}_step_${U}`,L=me.join(k,"failures",_);Ce.existsSync(L)||Ce.mkdirSync(L,{recursive:!0}),K&&await Ce.promises.writeFile(me.join(L,"screenshot.png"),K);let oe=this.lastHierarchy?.xml||await this.driver.getUiHierarchy(i.serial).catch(()=>"");oe&&await Ce.promises.writeFile(me.join(L,"hierarchy.xml"),oe,"utf-8");let ee=await this.driver.getLogcatTail(150,i.serial);await Ce.promises.writeFile(me.join(L,"logcat_tail.log"),ee,"utf-8");let fe=this.lastHierarchy?.flat||[],Ie=N.target&&fe.length>0?We(N.target,fe.map(q=>q.text||q.contentDesc||"").filter(Boolean)):[];await Ce.promises.writeFile(me.join(L,"match_scores.json"),JSON.stringify(Ie,null,2),"utf-8"),T=me.join("failures",_).replace(/\\/g,"/"),console.log(R.red(` \u{1F4C1} Failure Triage Bundle generated at: output/${T}`))}catch{}if(this.reporter.logStep(te,N.originalText,N.type,"FAIL",I.message,K,void 0,F,T),this.reporter.logError(`Step ${U} failed: ${I.message}`),i.continueOnError)console.log(R.yellow("Continuing with next test step (--continue enabled)..."));else{let k=le.slice(J+1);if(k.length>0){console.log(R.yellow(`
739
+ \u{1F6D1} Aborting dependent flow due to upstream failure at Step ${U}.`)),console.log(R.gray(`Cascading skip applied to ${k.length} downstream step(s):`));for(let _=0;_<k.length;_++){let L=k[_],oe=U+1+_;this.reporter.logStep(te,L.originalText,L.type,"SKIPPED",`Cascading skip: Precondition failed at Step ${U} (${N.originalText})`,void 0,void 0,0),console.log(R.gray(` [Step ${oe}/${le.length}] \u26AA SKIPPED: ${L.originalText}`))}}break}}}}try{let B=this.lastHierarchy;if(B?.flat){let Z=Hs(B.flat,this.screenDimensions.width,this.screenDimensions.height);if(Z.length>0){console.log(R.bold.yellow(`
740
+ \u{1F50D} Visual QA Sentinel Warnings (${Z.length} detected):`));for(let j of Z)console.log(R.yellow(` \u2022 [${j.type}] ${j.description}`)),this.reporter.logError(`Visual Defect (${j.type}): ${j.description}`)}}}catch{}await this.memory.save(),i.resume&&v===0&&await this.checkpoints.clear(c);let x=this.memory.getStats();if(x.totalMappings>0&&console.log(R.cyan(`\u{1F9E0} Knowledge Engine: ${x.totalMappings} active learned mapping(s) for ${x.package}`)),S){console.log(R.cyan("\u{1F3AC} Finalizing video recording..."));let B=me.resolve(process.cwd(),"output"),Z=me.join(B,`${c}-recording.mp4`),j=await this.driver.stopScreenRecording(S,Z,i.serial);j&&Ce.existsSync(j)&&(this.reporter.setVideoPath?.(`${c}-recording.mp4`),console.log(R.green(`\u2714 Screen recording saved to: output/${c}-recording.mp4`))),S=null}let D=((Date.now()-m)/1e3).toFixed(1),w=await this.reporter.generateReport(c);f&&(f.broadcastComplete(w),y&&y()),console.log(R.bold.green(`
741
+ \u2728 PromptTest Script Execution Finished in ${D}s!`));let A=w.failedSteps===0?R.bold.green:R.bold.yellow;return console.log(A(`Result: ${w.passedSteps}/${w.totalSteps} passed (${w.failedSteps} failed, ${w.skippedSteps} skipped).`)),console.log(R.cyan(`Report saved to output/${c}-report.html
742
+ `)),i.json&&console.log(JSON.stringify(w,null,2)),w}finally{if(S)try{await this.driver.stopScreenRecording(S,me.join("output",`${c}-recording.mp4`),i.serial)}catch{}g&&ze(g)}}async getCleanHierarchy(e){let t=await this.driver.getUiHierarchy(e),{flat:s}=ue(t),i=s.find(o=>(o.text==="Dismiss"||o.contentDesc==="Dismiss")&&o.bounds.width>0);i&&(await this.driver.tap(i.bounds.centerX,i.bounds.centerY,e),await new Promise(o=>setTimeout(o,400)),t=await this.driver.getUiHierarchy(e),s=ue(t).flat);let n=s.find(o=>o.contentDesc&&(o.contentDesc.startsWith("!, ")||o.contentDesc.includes("react.dev/link")));if(n){let o=n.bounds.x2-45,a=n.bounds.centerY;await this.driver.tap(o,a,e),await new Promise(d=>setTimeout(d,350)),t=await this.driver.getUiHierarchy(e),s=ue(t).flat}let r=ce(s);return this.lastHierarchy={xml:t,flat:s,timestamp:Date.now(),hash:r},{xml:t,flat:s}}async ensureInViewport(e,t){let s=this.screenDimensions.width,i=this.screenDimensions.height,n=Math.round(s*.5),r=this.navBarHeight>0?i-this.navBarHeight:i,o=this.navBarHeight>0?r*.94:i*E.gestures.bottomNavThresholdRatio;if(e.bounds.centerY>o||e.bounds.y1>o)return!1;let d=e.bounds.y2>r,c=e.bounds.y1<Math.round(i*.04)&&e.bounds.centerY<Math.round(i*.06);return d?(await this.driver.swipe(n,Math.round(i*.75),n,Math.round(i*.45),250,t),await new Promise(l=>setTimeout(l,200)),this.lastHierarchy=null,!0):c?(await this.driver.swipe(n,Math.round(i*.35),n,Math.round(i*.65),250,t),await new Promise(l=>setTimeout(l,200)),this.lastHierarchy=null,!0):!1}async waitForTarget(e,t,s=3e3,i){if(this.lastHierarchy&&Date.now()-this.lastHierarchy.timestamp<E.polling.hierarchyCacheTtlMs){let a=this.matchNodes(this.lastHierarchy.flat,e,i);if(a.length>0)return{flat:this.lastHierarchy.flat,matched:a}}let n=Date.now();for(;Date.now()-n<s;){let{flat:a}=await this.getCleanHierarchy(t),d=this.matchNodes(a,e,i);if(d.length>0)return{flat:a,matched:d};await new Promise(c=>setTimeout(c,ks()))}let{flat:r}=await this.getCleanHierarchy(t),o=this.matchNodes(r,e,i);if(o.length===0&&(this.healEnabled||E.ai.selfHealing))try{let a=await this.semanticResolver.findSuggestions(e,r,{locale:this.activeLocale}),d=E.ai.confidenceThreshold||.75,c=a.find(l=>l.score>=d);if(c){let l=c.node||r.find(h=>(z(c.text,h.text)||z(c.text,h.contentDesc))&&h.bounds.width>0);if(l){console.log(R.yellow(` \u{1F4A1} [Self-Healing] Auto-healed "${e}" \u2192 "${c.text}" (${Math.round(c.score*100)}% confidence, ${c.strategy})`)),i&&(i.healedFrom=e);let h=l.text?"text":l.contentDesc?"contentDesc":"resourceId",u=this.lastHierarchy?.hash,g=Math.min(E.memory?.maxHealedConfidence??.65,c.score);this.memory.recordSuccess(i?.type||"TAP",e,c.text,h,g,e,u),o=[l]}}}catch(a){ke.warn(`Self-healing resolution failed: ${a.message}`)}return{flat:r,matched:o}}buildDiagnosticError(e,t,s){return qs(e,t,s)}async executeStep(e,t,s){let i=Gs.get(e.type);if(!i)throw new Error(`No handler registered for step type: ${e.type}`);e.target&&e.target.includes("$")&&(e.target=Xe(e.target,Object.fromEntries(this.runtimeVariables))),e.value&&e.value.includes("$")&&(e.value=Xe(e.value,Object.fromEntries(this.runtimeVariables)));let n={driver:this.driver,memory:this.memory,serial:t,screenDimensions:this.screenDimensions,navBarHeight:this.navBarHeight,lastHierarchy:this.lastHierarchy,setLastHierarchy:r=>{this.lastHierarchy=r},getCleanHierarchy:r=>this.getCleanHierarchy(r),waitForTarget:(r,o,a,d)=>this.waitForTarget(r,o,a,d),matchNodes:(r,o,a)=>this.matchNodes(r,o,a),ensureInViewport:(r,o)=>this.ensureInViewport(r,o),buildDiagnosticError:(r,o,a)=>this.buildDiagnosticError(r,o,a),findTargetInputField:(r,o,a)=>this.findTargetInputField(r,o,a),upcomingSteps:s,variables:this.runtimeVariables,loopStack:this.loopStack,executeChildSteps:async(r,o)=>{for(let a=0;a<r.length;a++){let d=r[a];await this.executeStep(d,o.serial,r.slice(a+1))}}};return i.execute(e,n)}findTargetInputField(e,t,s){return Zs(e,t,s,this.memory)}matchNodes(e,t,s){return It(e,t,this.memory,this.activeLocale,s,this.lastHierarchy?.hash)}},Jn=new Ye;import P from"chalk";import ii from"fs";import Fi from"path";var je=class{testData={};dataPath;isLoaded=!1;driver;constructor(e,t){this.dataPath=e||Fi.resolve(process.cwd(),"test-data.json"),this.driver=t||he}setTestData(e){this.testData=e,this.isLoaded=!0}async ensureDataLoaded(){if(!this.isLoaded){if(ii.existsSync(this.dataPath))try{let e=await ii.promises.readFile(this.dataPath,"utf-8");this.testData=JSON.parse(e)}catch{this.testData={}}this.isLoaded=!0}}async loadTestData(e){return e&&(this.dataPath=e),this.isLoaded=!1,await this.ensureDataLoaded(),this.testData}inferValueForNode(e,t){let s=[e.text,e.contentDesc,e.resourceId].join(" ").toLowerCase(),i="",n=t.filter(o=>o.text&&!o.clickable&&o.bounds.centerY<e.bounds.centerY&&e.bounds.centerY-o.bounds.centerY<250&&Math.abs(o.bounds.centerX-e.bounds.centerX)<400);n.length>0&&(i=n[n.length-1].text.toLowerCase());let r=`${s} ${i}`.toLowerCase();if(r.includes("review")||r.includes("feedback")||r.includes("comment")||r.includes("write a review")||r.includes("experience")){if(!this.testData.review?.text)throw new Error("Missing test-data.json field: review.text");return this.testData.review.text}if(r.includes("card")||r.includes("credit")||r.includes("debit")||r.includes("card number")){let o=this.testData.payment?.card;if(o)return String(o);let a="4532";for(let d=0;d<12;d++)a+=Math.floor(Math.random()*10);return a}if(r.includes("phone")||r.includes("mobile")||!r.includes("card")&&r.includes("number")||r.includes("contact")){let o=this.testData.auth?.phone||this.testData.profile?.phone;if(!o)throw new Error("Missing test-data.json field: auth.phone or profile.phone");return o}if(r.includes("email")||r.includes("e-mail")||r.includes("mail")){let o=this.testData.profile?.email||this.testData.auth?.email;if(!o)throw new Error("Missing test-data.json field: profile.email or auth.email");return o}if(r.includes("cvv")||r.includes("cvc")||r.includes("security code"))return"123";if(r.includes("expiry")||r.includes("exp date")||r.includes("expiration"))return"12/28";if(r.includes("pincode")||r.includes("zip")||r.includes("postal")){if(!this.testData.profile?.pincode)throw new Error("Missing test-data.json field: profile.pincode");return this.testData.profile.pincode}if(e.password||r.includes("password")||/\bpin\b/.test(r)&&!r.includes("pincode")||r.includes("passcode")){if(!this.testData.auth?.password)throw new Error("Missing test-data.json field: auth.password");return this.testData.auth.password}if(r.includes("otp")||r.includes("verification")||r.includes("code")&&!r.includes("postal")&&!r.includes("zip")){if(!this.testData.auth?.otp)throw new Error("Missing test-data.json field: auth.otp");return this.testData.auth.otp}if(r.includes("address")||r.includes("street")||r.includes("location")){if(!this.testData.profile?.address)throw new Error("Missing test-data.json field: profile.address");return this.testData.profile.address}if(r.includes("city")||r.includes("state")){if(!this.testData.profile?.city)throw new Error("Missing test-data.json field: profile.city");return this.testData.profile.city}if(r.includes("name")||r.includes("full name")||r.includes("first name")){if(!this.testData.profile?.name)throw new Error("Missing test-data.json field: profile.name");return this.testData.profile.name}if(r.includes("search")||r.includes("find")||r.includes("query")){if(!this.testData.search?.query)throw new Error("Missing test-data.json field: search.query");return this.testData.search.query}return this.testData.review?.text||"PromptTest Auto QA Test Data"}async fillAndSubmitForm(e,t,s=!0,i=!1){await this.ensureDataLoaded();let n=_e(e),r=[];if(n.length===0)return{filledFields:[],submitted:!1};let o=!1;for(let c of n){let l=c.resourceId||c.text||`input_${c.bounds.centerX}_${c.bounds.centerY}`,h=(c.text||"").trim(),u=!h||/^enter\s+/i.test(h)||/^type\s+/i.test(h)||/^e\.g\./i.test(h)||/^(email|email address|password|phone|name|search)$/i.test(h);if(!i&&!u){r.push({fieldId:l,fieldLabel:c.text||c.contentDesc||c.resourceId,valueEntered:h});continue}let g=this.inferValueForNode(c,e);await this.driver.tap(c.bounds.centerX,c.bounds.centerY,t),await new Promise(f=>setTimeout(f,400)),await this.driver.clearField(t,g.length+10),await new Promise(f=>setTimeout(f,200)),await this.driver.inputText(g,t),await new Promise(f=>setTimeout(f,300)),o=!0,r.push({fieldId:l,fieldLabel:c.text||c.contentDesc||c.resourceId,valueEntered:g})}o&&(await this.driver.pressKey(4,t),await new Promise(c=>setTimeout(c,500)));let a=!1,d;if(s){let c=e.filter(l=>!l.clickable||l.bounds.width===0?!1:Ns.some(h=>z(h,l.text)||z(h,l.contentDesc)||z(h,l.resourceId)));if(c.length>0){let l=["submit","sign in","signin","login","save","confirm","proceed","continue"];c.sort((u,g)=>{let f=(u.text||u.contentDesc||u.resourceId||"").toLowerCase(),y=(g.text||g.contentDesc||g.resourceId||"").toLowerCase(),S=l.findIndex(x=>f.includes(x)),b=l.findIndex(x=>y.includes(x)),m=S>=0?S:99,v=b>=0?b:99;return m!==v?m-v:g.bounds.centerY-u.bounds.centerY});let h=c[0];d=h.text||h.contentDesc||h.resourceId,await this.driver.tap(h.bounds.centerX,h.bounds.centerY,t),await new Promise(u=>setTimeout(u,E.settle.submitWaitMs));try{let u=await this.driver.getUiHierarchy(t),{flat:g}=ue(u),f=_e(g);a=!(f.length>0&&n.every(S=>f.some(b=>b.resourceId&&b.resourceId===S.resourceId)))}catch{a=!0}}}return{filledFields:r,submitted:a,submitButtonText:d}}},ri=new je;import H from"chalk";var Rt=class{driver;reporter;memory;formFiller;screenLedger=new Map;callStack=[];executedStepCount=0;visitedScreenHashes=new Set;devDefectsList=[];safetyHitList=[];externalSkippedList=[];constructor(e=he,t=nt,s=at){this.driver=e,this.reporter=t,this.memory=s,this.formFiller=new je(void 0,e)}async getCleanUiHierarchy(e,t,s=5){let i=await this.driver.getUiHierarchy(t),{flat:n}=ue(i),r=0;for(;r<s;){let o=yt(n);if(!o)break;r++;let a=`[${(o.severity||"error").toUpperCase()} - ${o.type.toUpperCase()}]`,d=o.sourceLocation?` [${o.sourceLocation}]`:"";console.log(H.red(` \u{1F6A8} Global Dev Console Intercepted: ${a} "${o.errorText.slice(0,80)}"${d}`)),this.devDefectsList.push(o.sourceLocation?`${o.errorText} (${o.sourceLocation})`:o.errorText);let c=await this.driver.captureScreenshot(t);this.reporter.logStep("Dev Overlay Triage",`Intercepted and triaged ${a}: "${o.errorText}"${d}`,"Verify","FAIL",o.errorText,c,{errors:[o.sourceLocation?`${o.errorText} at ${o.sourceLocation}`:o.errorText]}),o.dismissButton&&o.dismissButton.bounds.width>0?(console.log(H.gray(" Dismissing overlay via dismiss button...")),await this.driver.tap(o.dismissButton.bounds.centerX,o.dismissButton.bounds.centerY,t)):o.isToast&&o.node&&o.node.bounds.width>0?(console.log(H.gray(" Expanding toast notification to access Dismiss button...")),await this.driver.tap(o.node.bounds.centerX,o.node.bounds.centerY,t)):(console.log(H.gray(" Pressing Back to dismiss overlay...")),await this.driver.pressBack(t)),await new Promise(l=>setTimeout(l,800)),i=await this.driver.getUiHierarchy(t),n=ue(i).flat}return{xml:i,flat:n}}async dismissSoftKeyboard(e){try{await this.driver.pressKey(111,e),await new Promise(t=>setTimeout(t,150))}catch{}}async packageJailGuard(e,t){let s=await this.driver.getForegroundPackage(t);if(!s)return!1;if(!s.includes(e)){let i=s.includes("launcher")||s.includes("home")||s.includes("trebuchet");console.log(H.yellow(` \u{1F6A8} External App Jailbreak Detected [${s}]. Recovering...`)),i||(await this.driver.pressBack(t),await new Promise(r=>setTimeout(r,800)));let n=await this.driver.getForegroundPackage(t);return(!n||!n.includes(e))&&(console.log(H.red(` Force restoring ${e} foreground...`)),await this.driver.launchApp(e,t),await new Promise(r=>setTimeout(r,1500)),this.callStack=this.callStack.slice(0,1)),!0}return!1}async handleExternalMediaChooser(e,t){let s=await this.driver.getForegroundPackage(t);if(!s)return!1;let i=s==="android"||s.includes("resolver")||s.includes("intentresolver");if(i){console.log(H.yellow(` \u{1F6E1}\uFE0F External Media Chooser Intercepted [${s}]. Dismissing to stay in-app...`)),await this.driver.pressBack(t),await new Promise(r=>setTimeout(r,800));let n=await this.driver.getForegroundPackage(t);return n&&!n.includes(e)&&i&&(await this.driver.launchApp(e,t),await new Promise(r=>setTimeout(r,1200)),this.callStack=this.callStack.slice(0,1)),!0}return!1}catalogScreen(e,t,s=[]){let i=[],n=t.height,r=n*.06,o=n*.88,a=m=>s.some(v=>Math.abs(v.bounds.centerX-m.bounds.centerX)<30&&Math.abs(v.bounds.centerY-m.bounds.centerY)<30),d=_e(e);for(let m of d){if(a(m))continue;let v=m.text||m.contentDesc||m.resourceId||"Text Input";i.push({node:m,type:"input",label:v,tested:!1})}let c=it(e);for(let m of c){if(a(m))continue;let v=m.text||m.contentDesc||m.resourceId||"Toggle Control";i.push({node:m,type:"toggle",label:v,tested:!1})}let l=Ge(e);for(let m of l){if(a(m)||Oe([m],n,t.width)||we([m],n,t.width,!0))continue;let v=m.text||m.contentDesc||m.resourceId||"Action Button";if(Pe(m)){this.externalSkippedList.push(v);continue}let x=m.selected!==void 0||m.checkable||/(?:tab|chip|pill|filter|segment|toggle)/i.test(`${m.resourceId} ${m.className} ${m.contentDesc}`)||/(?:today|yesterday|all|active|archived|pending|completed|present|absent)/i.test(v);i.push({node:m,type:x?"toggle":"transition",label:v,tested:!1})}let h=Os(e,n,t.width);for(let m of h){if(a(m)||we([m],n,t.width,!0)||i.some(x=>Math.abs(x.node.bounds.centerX-m.bounds.centerX)<25&&Math.abs(x.node.bounds.centerY-m.bounds.centerY)<25))continue;let v=m.text||m.contentDesc||m.resourceId||"Notification / Header Action";if(Pe(m)){this.externalSkippedList.push(v);continue}i.push({node:m,type:"transition",label:v,tested:!1})}let u=e.filter(m=>{if(!m.clickable||m.bounds.width===0)return!1;let v=`${m.text} ${m.contentDesc} ${m.resourceId}`.toLowerCase();return v.includes("now playing")||v.includes("play")||v.includes("pause")});for(let m of u){if(a(m)||i.some(x=>Math.abs(x.node.bounds.centerX-m.bounds.centerX)<25&&Math.abs(x.node.bounds.centerY-m.bounds.centerY)<25))continue;let v=m.text||m.contentDesc||m.resourceId||"Media Control";i.push({node:m,type:"toggle",label:v,tested:!1})}let g=bt(e,t).filter(m=>!a(m)&&m.bounds.centerY>r&&m.bounds.centerY<o&&!we([m],n,t.width,!0)&&!Pe(m)),f=Us(g,2);for(let m of f){let v=m.text||m.contentDesc||m.resourceId||`Item (${m.bounds.centerX},${m.bounds.centerY})`;i.push({node:m,type:"transition",label:v,tested:!1})}let y=0,S=0,b=[];for(let m of i){let v=/\.(?:mp4|mkv|mov|webm|flv|avi)\b/i.test(m.label),x=/\.(?:mp3|wav|m4a|aac|ogg)\b/i.test(m.label);if(v){if(y++,y>1)continue}else if(x&&(S++,S>1))continue;b.push(m)}return b}async safeBacktrack(e,t,s,i,n=!0){let{flat:r}=await this.getCleanUiHierarchy(t,s),{height:o,width:a}=await this.driver.getScreenDimensions(s),d=Ne(r,{width:a,height:o});if(d===e)return!0;let c=we(r,o,a,!0);if(c&&c.bounds.width>0){console.log(H.gray(` [Backtrack] Tapping in-app back/close button "${c.text||c.contentDesc||c.className}"...`)),await this.driver.tap(c.bounds.centerX,c.bounds.centerY,s),await new Promise(u=>setTimeout(u,1e3)),await this.packageJailGuard(t,s);let l=await this.getCleanUiHierarchy(t,s),h=Ne(l.flat,{width:a,height:o});if(h===e||h!==d)return!0}if(i&&i.bounds.width>0){console.log(H.gray(` [Backtrack] Restoring root domain via tab "${i.text||i.contentDesc||"Root Tab"}"...`)),await this.driver.tap(i.bounds.centerX,i.bounds.centerY,s),await new Promise(u=>setTimeout(u,1e3)),await this.packageJailGuard(t,s);let l=await this.getCleanUiHierarchy(t,s),h=Ne(l.flat,{width:a,height:o});if(h===e||h!==d)return!0}if(n){if(console.log(H.gray(" [Backtrack] Sending fallback KEYCODE_BACK...")),await this.driver.pressKey(4,s),await new Promise(g=>setTimeout(g,1e3)),await this.packageJailGuard(t,s))return console.log(H.yellow(" \u26A0\uFE0F Backtrack via KEYCODE_BACK caused app jailbreak. Aborting branch restoration.")),!1;let h=await this.getCleanUiHierarchy(t,s),u=Ne(h.flat,{width:a,height:o});if(u===e||u!==d)return!0}return!1}async explore(e){let{packageName:t,serial:s,maxScreens:i=30,maxDepth:n=3,stepBudget:r=100,maxInteractionsPerScreen:o=6,safetyMode:a="strict",safetyBlacklist:d=[]}=e;console.log(H.bold.cyan(`
743
+ \u{1F916} PromptTest Universal State-Graph DFS Engine`)),console.log(H.gray(`Target Package: ${t}`)),console.log(H.gray(`Safety Policy: ${a.toUpperCase()}`)),console.log(H.gray(`Limits: Max Screens = ${i}, Step Budget = ${r}, Max Depth = ${n}`)),await this.driver.clearCrashLogs(s);let c=await this.driver.getScreenDimensions(s),l=await this.driver.getForegroundPackage(s);(!l||!l.includes(t))&&(console.log(H.gray(`Launching ${t}...`)),await this.driver.launchApp(t,s),await new Promise(S=>setTimeout(S,2500)));let{flat:h}=await this.getCleanUiHierarchy(t,s);await this.dismissSoftKeyboard(s);let u=Yt(h,c,t);console.log(H.magenta(`\u26A1 Universal Paradigm Detected: [${u.paradigm.toUpperCase()}] with ${u.roots.length} root node(s).`));let g=[],f;if(u.paradigm==="drawer"&&u.roots.length>0){f=u.roots[0];let S={...h[0]||{},text:"Home Screen / Main Hub",contentDesc:"Home Screen / Main Hub",clickable:!0,bounds:{x1:0,y1:0,x2:c.width,y2:c.height,centerX:c.width/2,centerY:c.height/2,width:c.width,height:c.height}};g.push(S),console.log(H.gray(" Opening drawer to catalog root destinations...")),await this.driver.tap(f.bounds.centerX,f.bounds.centerY,s),await new Promise(w=>setTimeout(w,1200));let b=await this.getCleanUiHierarchy(t,s),m=b.flat.filter(w=>{if(!w.clickable||w.bounds.width===0||w.bounds.height===0||w.bounds.width>=c.width*.95&&w.bounds.height>=c.height*.95||we([w],c.height,c.width,!0))return!1;let A=`${w.contentDesc} ${w.text}`.trim(),B=w.bounds.width>c.width*.15&&w.bounds.height>c.height*.05;return A.toLowerCase().includes("developed by")||w.bounds.centerY>c.height*.85?!1:A.length>=2||B});for(let w of m)g.some(A=>Math.abs(A.bounds.centerX-w.bounds.centerX)<30&&Math.abs(A.bounds.centerY-w.bounds.centerY)<30)||g.push(w);let v=we(b.flat,c.height,c.width,!0);v?await this.driver.tap(v.bounds.centerX,v.bounds.centerY,s):await this.driver.tap(f.bounds.centerX,f.bounds.centerY,s),await new Promise(w=>setTimeout(w,1200));let x=await this.getCleanUiHierarchy(t,s);if(x.flat.some(w=>`${w.contentDesc} ${w.text}`.includes("Gallery")&&`${w.contentDesc} ${w.text}`.includes("Planner"))){let w=we(x.flat,c.height,c.width,!0);w?await this.driver.tap(w.bounds.centerX,w.bounds.centerY,s):await this.driver.tap(c.width-50,c.height/2,s),await new Promise(A=>setTimeout(A,1e3))}console.log(H.magenta(` Discovered ${g.length} destinations (1 Main Hub + ${g.length-1} Drawer destinations).`))}else u.roots.length>0?g=u.roots:g=[h[0]||{text:"Main Hub",clickable:!0}];let y=1;for(let S of g){if(this.executedStepCount>=r||this.visitedScreenHashes.size>=i)break;let b=S.text||S.contentDesc||`Root #${y}`;if(console.log(H.yellow(`
744
+ [Domain ${y}/${g.length}] Entering Root Tree: "${b}"...`)),u.paradigm==="bottom_tabs"||u.paradigm==="top_tabs"){let x=S.bounds.height<25?Math.max(S.bounds.y1-10,S.bounds.centerY):Math.min(S.bounds.centerY,S.bounds.y2-4);await this.driver.tap(S.bounds.centerX,x,s),this.executedStepCount++,await new Promise(D=>setTimeout(D,1200))}else u.paradigm==="drawer"&&y>1&&f&&(await this.dismissSoftKeyboard(s),console.log(H.gray(` Opening drawer to select "${b}"...`)),await this.driver.tap(f.bounds.centerX,f.bounds.centerY,s),await new Promise(x=>setTimeout(x,1e3)),await this.driver.tap(S.bounds.centerX,S.bounds.centerY,s),this.executedStepCount++,await new Promise(x=>setTimeout(x,1500)));h=(await this.getCleanUiHierarchy(t,s)).flat,await this.dismissSoftKeyboard(s);let v=y===1?Math.max(25,Math.ceil(r*.45)):Math.max(8,Math.ceil(r*.55/Math.max(1,g.length-1)));if(await this.exploreDfsNode({packageName:t,serial:s,screenDims:c,rootNodes:u.roots,activeRootNode:S,currentDepth:0,maxDepth:n,maxScreens:i,stepBudget:r,domainStepLimit:this.executedStepCount+v,maxInteractionsPerScreen:o,safetyMode:a,safetyBlacklist:d,domainLabel:b}),u.paradigm==="drawer"&&y>1){let x=0;for(;x<4;){let D=await this.getCleanUiHierarchy(t,s),w=Oe(D.flat,c.height,c.width),A=D.flat.some(Z=>`${Z.contentDesc} ${Z.text}`.includes("Gallery")&&`${Z.contentDesc} ${Z.text}`.includes("Planner"));if(w&&!A)break;let B=we(D.flat,c.height,c.width,!0);if(B)console.log(H.gray(" [Domain Wrap-Up] Returning to Home Screen via in-app back...")),await this.driver.tap(B.bounds.centerX,B.bounds.centerY,s),await new Promise(Z=>setTimeout(Z,1e3)),x++;else break}}if(y===1&&g.length===1){let x=await this.getCleanUiHierarchy(t,s),D=Yt(x.flat,c,t);if((D.paradigm==="bottom_tabs"||D.paradigm==="top_tabs")&&D.roots.length>1){console.log(H.magenta(`
745
+ \u26A1 Post-Auth Navigation Discovered: [${D.paradigm.toUpperCase()}] with ${D.roots.length} root domain(s)!`)),u.paradigm=D.paradigm,u.roots=D.roots;let w=D.roots.slice(1);g.push(...w.length>0?w:D.roots)}}y++}for(let S of this.visitedScreenHashes)this.memory.markScreenCrawled(S);await this.memory.save(),console.log(H.green(`
746
+ \u2714 Universal DFS Traversal Complete!`)),console.log(H.cyan(` Visited Screens: ${this.visitedScreenHashes.size}`)),console.log(H.cyan(` Total Steps Executed: ${this.executedStepCount}/${r}`)),console.log(H.cyan(` Defects Triaged: ${this.devDefectsList.length}`))}async exploreDfsNode(e){let{packageName:t,serial:s,screenDims:i,rootNodes:n,activeRootNode:r,currentDepth:o,maxDepth:a,maxScreens:d,stepBudget:c,domainStepLimit:l,maxInteractionsPerScreen:h,safetyMode:u,safetyBlacklist:g,domainLabel:f}=e;if(this.executedStepCount>=c||this.visitedScreenHashes.size>=d||l&&this.executedStepCount>=l)return;let{flat:y}=await this.getCleanUiHierarchy(t,s),S=ce(y),b=Ne(y,i);this.visitedScreenHashes.add(S);let m=this.screenLedger.get(b);if(m){if(m.status==="FULLY_EXPLORED"){console.log(H.gray(` \u26A1 Cycle Detected: Screen [${b.slice(0,8)}] already fully explored. Pruning branch.`));return}}else{let w=this.catalogScreen(y,i,n);m={hash:S,semanticHash:b,title:`${f} (depth ${o})`,elements:w,status:"IN_PROGRESS",depth:o,interactionCount:0},this.screenLedger.set(b,m),console.log(H.cyan(` \u{1F50E} Discovered Screen [${b.slice(0,8)}] at depth ${o} with ${w.length} candidate element(s).`))}this.callStack.push({screenHash:S,semanticHash:b,title:m.title,timestamp:Date.now()});let v=m.elements.filter(w=>w.type==="input"&&!w.tested);if(v.length>0&&m.interactionCount<h){console.log(H.magenta(` Filling in-place form fields (${v.length} inputs)...`));let w=await this.formFiller.fillAndSubmitForm(y,s,!0,!1);this.executedStepCount++,m.interactionCount++;for(let A of v)A.tested=!0;await this.dismissSoftKeyboard(s),await this.packageJailGuard(t,s),this.reporter.logStep("In-Place Form Fill",`Populated ${w.filledFields.length} field(s) on [${b.slice(0,8)}]`,"FormSubmit","PASS",w.submitButtonText||"Auto")}let x=m.elements.filter(w=>w.type==="toggle"&&!w.tested);for(let w of x){if(this.executedStepCount>=c||m.interactionCount>=h)break;if(w.tested=!0,Ee(w.node,g,u)){this.safetyHitList.push(w.label);continue}console.log(H.gray(` Exercising toggle: "${w.label.slice(0,30)}"...`)),this.executedStepCount++,m.interactionCount++,await this.driver.tap(w.node.bounds.centerX,w.node.bounds.centerY,s),await new Promise(A=>setTimeout(A,600)),this.reporter.logStep("In-Place Toggle",`Toggled control "${w.label}"`,"Tap","PASS",w.label)}let D=m.elements.filter(w=>w.type==="transition"&&!w.tested);for(let w of D){if(this.executedStepCount>=c||this.visitedScreenHashes.size>=d||l&&this.executedStepCount>=l&&!(o===0&&f.includes("Home Screen"))||m.interactionCount>=h)break;if(w.tested=!0,Pe(w.node)){this.externalSkippedList.push(w.label);continue}if(Ee(w.node,g,u)){this.safetyHitList.push(w.label);continue}console.log(H.magenta(` \u26A1 [DFS Depth ${o}] Testing transition: "${w.label.slice(0,40)}"...`)),this.executedStepCount++,m.interactionCount++,await this.driver.tap(w.node.bounds.centerX,w.node.bounds.centerY,s),await new Promise(j=>setTimeout(j,1500)),await this.dismissSoftKeyboard(s),await this.handleExternalMediaChooser(t,s),await this.packageJailGuard(t,s);let A=await this.getCleanUiHierarchy(t,s),Z=Ne(A.flat,i)!==b;if(this.reporter.logStep("DFS Transition",`Tapped "${w.label}" [${Z?"Navigated":"In-Place"}]`,"Tap","PASS",w.label),Z){if(o<a){let te=o===0&&f.includes("Home Screen")?Math.min(this.executedStepCount+3,l||this.executedStepCount+3):l;await this.exploreDfsNode({packageName:t,serial:s,screenDims:i,rootNodes:n,activeRootNode:r,domainStepLimit:te,currentDepth:o+1,maxDepth:a,maxScreens:d,stepBudget:c,maxInteractionsPerScreen:h,safetyMode:u,safetyBlacklist:g,domainLabel:`${f} > ${w.label.slice(0,20)}`})}console.log(H.gray(` [DFS Backtrack] Returning to [${b.slice(0,8)}]...`)),await this.safeBacktrack(b,t,s,o===0?r:void 0,o>0),await this.dismissSoftKeyboard(s);let j=await this.getCleanUiHierarchy(t,s);if(Ne(j.flat,i)!==b){let te=we(j.flat,i.height,i.width,!0);te&&(console.log(H.gray(" [Backtrack Verification] Re-tapping in-app back/close button...")),await this.driver.tap(te.bounds.centerX,te.bounds.centerY,s),await new Promise(be=>setTimeout(be,1e3)),await this.packageJailGuard(t,s));let le=await this.getCleanUiHierarchy(t,s);if(Ne(le.flat,i)!==b){console.log(H.yellow(` \u26A0\uFE0F Unable to restore parent screen [${b.slice(0,8)}]. Unwinding branch to prevent jailbreak loop.`));break}}}}m.status="FULLY_EXPLORED",this.callStack.pop()}};var ut=class{driver;formFiller;reporter;memory;safetyHitList=[];externalSkippedList=[];devDefectsList=[];visitedScreenHashes=new Set;executedStepCount=0;constructor(e,t,s,i){this.driver=e||he,this.formFiller=t||ri,this.reporter=s||nt,this.memory=i||at}getMemory(){return this.memory}getSafetyHitList(){return this.safetyHitList}getExternalSkippedList(){return this.externalSkippedList}getDevDefectsList(){return this.devDefectsList}getVisitedScreensCount(){return this.visitedScreenHashes.size}async packageJailGuard(e,t){let s=await this.driver.getForegroundPackage(t);if(s&&!s.includes(e)){let i=s.includes("launcher")||s.includes("home")||s.includes("trebuchet");console.log(P.yellow(` \u{1F6E1}\uFE0F Jail Containment: App escaped to "${s}". Executing containment recovery...`)),i||(await this.driver.pressBack(t),await new Promise(r=>setTimeout(r,600)));let n=await this.driver.getForegroundPackage(t);return(!n||!n.includes(e))&&(console.log(P.gray(` Force re-launching ${e} to restore foreground...`)),await this.driver.launchApp(e,t),await new Promise(r=>setTimeout(r,1200))),this.reporter.logStep("Jail Containment",`App escaped to "${s}"; successfully contained and restored "${e}"`,"Back","PASS"),!0}return!1}async getCleanUiHierarchy(e,t,s=5){let i=await this.driver.getUiHierarchy(t),{flat:n}=ue(i),r=0;for(;r<s;){let o=yt(n);if(!o)break;r++;let a=`[${(o.severity||"error").toUpperCase()} - ${o.type.toUpperCase()}]`,d=o.sourceLocation?` [${o.sourceLocation}]`:"";console.log(P.red(` \u{1F6A8} Global Dev Console Intercepted: ${a} "${o.errorText.slice(0,80)}"${d}`)),this.devDefectsList.push(o.sourceLocation?`${o.errorText} (${o.sourceLocation})`:o.errorText);let c=await this.driver.captureScreenshot(t);this.reporter.logStep("Dev Overlay Triage",`Intercepted and triaged ${a}: "${o.errorText}"${d}`,"Verify","FAIL",o.errorText,c,{errors:[o.sourceLocation?`${o.errorText} at ${o.sourceLocation}`:o.errorText]}),o.dismissButton&&o.dismissButton.bounds.width>0?(console.log(P.gray(" Dismissing overlay via dismiss button...")),await this.driver.tap(o.dismissButton.bounds.centerX,o.dismissButton.bounds.centerY,t)):o.isToast&&o.node&&o.node.bounds.width>0?(console.log(P.gray(" Expanding toast notification to access Dismiss button...")),await this.driver.tap(o.node.bounds.centerX,o.node.bounds.centerY,t)):(console.log(P.gray(" Pressing Back to dismiss overlay...")),await this.driver.pressBack(t)),await new Promise(l=>setTimeout(l,800)),i=await this.driver.getUiHierarchy(t),n=ue(i).flat}return{xml:i,flat:n}}async handleDevOverlays(e,t,s){let i=yt(e);if(!i)return!1;let n=`[${(i.severity||"error").toUpperCase()} - ${i.type.toUpperCase()}]`,r=i.sourceLocation?` [${i.sourceLocation}]`:"";console.log(P.red(` \u{1F6A8} Dev Overlay Detected: ${n} "${i.errorText.slice(0,80)}"${r}`)),this.devDefectsList.push(i.sourceLocation?`${i.errorText} (${i.sourceLocation})`:i.errorText);let o=await this.driver.captureScreenshot(s);return this.reporter.logStep("Dev Overlay Triage",`Detected and triaged ${n} error: "${i.errorText}"${r}`,"Verify","FAIL",i.errorText,o,{errors:[i.sourceLocation?`${i.errorText} (${i.sourceLocation})`:i.errorText]}),i.dismissButton&&i.dismissButton.bounds.width>0?(console.log(P.gray(" Dismissing error overlay via dismiss button...")),await this.driver.tap(i.dismissButton.bounds.centerX,i.dismissButton.bounds.centerY,s)):i.isToast&&i.node&&i.node.bounds.width>0?(console.log(P.gray(" Expanding toast notification to access Dismiss button...")),await this.driver.tap(i.node.bounds.centerX,i.node.bounds.centerY,s)):(console.log(P.gray(" Pressing Back to dismiss error overlay...")),await this.driver.pressBack(s)),await new Promise(a=>setTimeout(a,800)),!0}async dismissSoftKeyboard(e){try{await this.driver.pressKey(111,e),await new Promise(t=>setTimeout(t,200))}catch{}}async explore(e){let{packageName:t,serial:s,maxTabs:i=E.explorer?.maxTabs||15,exploreLists:n=!0,skipAlreadyCrawled:r=!1,safetyMode:o=E.safety?.mode||"strict",safetyBlacklist:a=E.safety?.customBlacklist?[...E.safety.customBlacklist]:[],maxScreens:d=E.explorer?.maxScreens||30,stepBudget:c=E.explorer?.stepBudget||100,screenshots:l=E.explorer?.screenshots||"state-change"}=e;console.log(P.cyan(`
747
+ \u{1F916} PromptTest Autonomous Exploration Brain v3`)),console.log(P.gray("Target Package: ")+P.bold.white(t)),console.log(P.gray("Safety Policy: ")+P.bold.yellow(o.toUpperCase())+(a.length>0?P.gray(` (+${a.length} custom blacklist)`):"")),console.log(P.gray("Screenshots Policy: ")+P.bold.white(l));let h=async(y,S=!0)=>{if(!(l==="failure-only"&&y!=="FAIL")&&!(l==="state-change"&&!S&&y!=="FAIL"))try{return await this.driver.captureScreenshot(s)}catch{return}};await this.memory.init(t);let u=s||this.driver.getDefaultDevice(),g=u||"Default Device";this.reporter.init(t,g);let f=null;u&&(f=Ke(u)),this.safetyHitList=[],this.externalSkippedList=[],this.devDefectsList=[],this.visitedScreenHashes.clear(),this.executedStepCount=0;try{if(await this.driver.clearCrashLogs(s),(e.strategy||E.explorer?.strategy||"heuristic")==="dfs"){let ne=new Rt(this.driver,this.reporter,this.memory);await ne.explore({packageName:t,serial:s,maxScreens:d,maxDepth:e.maxDepth||E.explorer?.maxDepth||5,stepBudget:c,safetyMode:o,safetyBlacklist:a,screenshotPolicy:l,skipAlreadyCrawled:r}),this.safetyHitList=ne.safetyHitList,this.externalSkippedList=ne.externalSkippedList,this.devDefectsList=ne.devDefectsList,this.visitedScreenHashes=ne.visitedScreenHashes,this.executedStepCount=ne.executedStepCount;let J=this.memory.getStats();this.reporter.logStep("Coverage Audit",`State Graph Coverage: Visited ${this.visitedScreenHashes.size} unique screen state(s). Memory Engine cached ${J.totalScreens} crawled screen(s).`,"Verify","PASS"),await this.reporter.generateReport(),console.log(P.bold.green(`
748
748
  \u2728 Full Audit Report generated at: output/prompttest-report.md`));return}let{width:S,height:b}=await this.driver.getScreenDimensions(s);console.log(P.yellow(`
749
- [1/5] Verifying Foreground State...`));let m=await this.driver.getForegroundPackage(s);(!m||!m.includes(t))&&(console.log(P.gray(`Launching ${t}...`)),await this.driver.launchApp(t,s),await new Promise(ne=>setTimeout(ne,2500)));let v=await this.runErrorSentinel(t,s,"Post-Launch"),E=v.hasError?"FAIL":"PASS",k=await h(E,!0);this.reporter.logStep("Init",`Launched and verified foreground for ${t}`,"Launch",E,t,k,v.hasError?{errors:v.errors}:void 0),console.log(E==="PASS"?P.green("\u2714 App is active in foreground."):P.red(`\u2716 Issues detected during launch for ${t}.`)),console.log(P.yellow(`
750
- [2/5] Inspecting UI Hierarchy for Forms...`));let{xml:w,flat:A}=await this.getCleanUiHierarchy(t,s),B=ce(A);if(this.visitedScreenHashes.add(B),this.memory.isScreenCrawled(B)&&r)console.log(P.cyan(` \u26A1 Fast-Forward: Screen [${B.slice(0,8)}] was previously crawled offline. Skipping redundant element interactions.`)),this.reporter.logStep("Fast Forward",`Fast-forwarded past previously crawled screen [${B.slice(0,8)}] (Memory Engine)`,"Skip","PASS");else{let ne=_e(A);if(ne.length>0){console.log(P.magenta(`\u26A1 Detected ${ne.length} form field(s)! Engaging Semantic Form Filler...`));for(let L of ne)console.log(P.gray(` - Field: "${L.text||L.contentDesc||L.resourceId}"`));let C=await this.formFiller.fillAndSubmitForm(A,s,!0,!1);this.executedStepCount++,await new Promise(L=>setTimeout(L,1500)),await this.dismissSoftKeyboard(s),await this.packageJailGuard(t,s);let M=await this.getCleanUiHierarchy(t,s);w=M.xml,A=M.flat,this.visitedScreenHashes.add(ce(A));let I=await this.runErrorSentinel(t,s,"Post-Form-Submit"),F=_e(A),x=I.hasError||F.length===ne.length&&I.errors.length>0?"FAIL":"PASS",$=await h(x,!0),_=C.filledFields.map(L=>`${L.fieldLabel} -> "${L.valueEntered}"`).join(", ");this.reporter.logStep("Form Fill",`Filled ${C.filledFields.length} field(s) [${_}] and submitted via "${C.submitButtonText||"Auto"}"`,"FormSubmit",x,C.submitButtonText,$,I.hasError?{errors:I.errors}:void 0),console.log(x==="PASS"?P.green("\u2714 Form populated and submitted successfully!"):P.red("\u2716 Form submission triggered an error or remained unauthenticated."))}else console.log(P.gray("No form input fields detected on initial screen."));console.log(P.yellow(`
751
- [3/5] Inspecting Interactive Action Controls...`));let J=Ge(A).filter(C=>{let M=(C.text+" "+C.contentDesc).toLowerCase();if(M.includes("submit")||M.includes("cancel")||Oe([C],b))return!1;if(Pe(C)){let I=C.text||C.contentDesc||C.resourceId||"External Link";return console.log(P.gray(` \u{1F517} External Link Bypassed: "${I}"`)),this.externalSkippedList.push(I),!1}if(Ee(C,a,o)){let I=C.text||C.contentDesc||C.resourceId||"Action";return console.log(P.yellow(` \u{1F6E1}\uFE0F Safety Guard: Blocked destructive action "${I}"`)),this.safetyHitList.push(I),!1}return!0});if(J.length>0){let C=J[0],M=C.text||C.contentDesc||C.resourceId;console.log(P.magenta(`\u26A1 Found action button: "${M}". Testing interaction...`));let I=ce(A);this.executedStepCount++,await this.driver.tap(C.bounds.centerX,C.bounds.centerY,s),await new Promise(ee=>setTimeout(ee,1200)),await this.packageJailGuard(t,s);let F=await this.getCleanUiHierarchy(t,s);w=F.xml,A=F.flat;let K=ce(A);this.visitedScreenHashes.add(K);let x=await this.runErrorSentinel(t,s,"Post-Action-Tap"),$=I!==K,_="PASS",L="";x.hasError?(_="FAIL",L="Action triggered error or crash"):$?(_="PASS",L="Screen transitioned successfully"):(_="WARN",L="No visible screen transition or state change observed (No-Op)",console.log(P.yellow(` \u26A0\uFE0F Outcome Warning: Action "${M}" produced no UI state change.`)));let oe=await h(_,$);this.reporter.logStep("Action Testing",`Tapped action button "${M}" [${L}]`,"Tap",_,M,oe,x.hasError?{errors:x.errors}:void 0),console.log(_==="PASS"?P.green(`\u2714 Action interaction complete (${L}).`):_==="WARN"?P.yellow(`\u2714 Action interaction recorded with warning (${L}).`):P.red("\u2716 Action interaction triggered an error.")),_!=="FAIL"&&(this.memory.recordSuccess("TAP",M,C.resourceId||C.text||C.contentDesc||M,"text",1,void 0,I),this.memory.markScreenCrawled(I,[M]))}else console.log(P.gray("No standalone action buttons to test."));let N=it(A).filter(C=>!Ee(C,a,o));if(N.length>0){console.log(P.yellow(`
752
- [3b/5] Inspecting Toggle & Checkable Controls...`));let C=N[0],M=C.text||C.contentDesc||C.resourceId||"Switch/Checkbox",I=C.checked;console.log(P.magenta(`\u26A1 Found toggle: "${M}" (checked: ${I}). Testing toggle interaction...`)),this.executedStepCount++,await this.driver.tap(C.bounds.centerX,C.bounds.centerY,s),await new Promise(ee=>setTimeout(ee,1e3)),w=await this.driver.getUiHierarchy(s),A=ue(w).flat;let F=ce(A);this.visitedScreenHashes.add(F);let x=it(A).find(ee=>Math.abs(ee.bounds.centerX-C.bounds.centerX)<25&&Math.abs(ee.bounds.centerY-C.bounds.centerY)<25),$=x?x.checked!==I:!0,_=await this.runErrorSentinel(t,s,"Post-Toggle"),L=_.hasError?"FAIL":$?"PASS":"WARN",oe=await h(L,$);this.reporter.logStep("Toggle Testing",`Toggled "${M}" (Checked: ${I} -> ${x?x.checked:"flipped"})`,"Toggle",L,M,oe,_.hasError?{errors:_.errors}:void 0),console.log(L==="PASS"?P.green("\u2714 Toggle control flipped successfully!"):L==="WARN"?P.yellow("\u26A0\uFE0F Toggle tapped but checked state did not flip."):P.red("\u2716 Toggle control triggered an error.")),L!=="FAIL"&&this.memory.markScreenCrawled(F,[M])}let Q=Oe(A,b);if(Q&&!Ee(Q,a,o)){let C=Q.contentDesc||Q.text||Q.resourceId||"Drawer Menu";console.log(P.yellow(`
753
- [3c/5] Inspecting Side Navigation Drawer...`)),console.log(P.magenta(`\u26A1 Found drawer trigger: "${C}". Opening side drawer...`));let M=ce(A);this.executedStepCount++,await this.driver.tap(Q.bounds.centerX,Q.bounds.centerY,s),await new Promise(L=>setTimeout(L,1200)),await this.packageJailGuard(t,s);let I=await this.getCleanUiHierarchy(t,s);w=I.xml,A=I.flat;let F=ce(A);this.visitedScreenHashes.add(F);let K=M!==F,x=await this.runErrorSentinel(t,s,"Drawer-Open"),$=x.hasError?"FAIL":K?"PASS":"WARN",_=await h($,K);if(this.reporter.logStep("Drawer Navigation",`Opened side drawer via "${C}"`,"Tap",$,C,_,x.hasError?{errors:x.errors}:void 0),$==="PASS"){console.log(P.green("\u2714 Side drawer opened successfully!"));let L=Ge(A).filter(ee=>!Ee(ee,a,o)&&!Pe(ee)&&ee.bounds.centerY>Q.bounds.y2);if(L.length>0){let ee=L[0],fe=ee.text||ee.contentDesc||ee.resourceId||"Drawer Item";console.log(P.gray(` - Testing drawer item: "${fe}"...`)),this.executedStepCount++,await this.driver.tap(ee.bounds.centerX,ee.bounds.centerY,s),await new Promise(q=>setTimeout(q,1200)),await this.packageJailGuard(t,s);let Ie=await this.getCleanUiHierarchy(t,s);w=Ie.xml,A=Ie.flat,this.visitedScreenHashes.add(ce(A))}console.log(P.gray(" Closing side drawer to restore main view...")),await this.driver.pressBack(s),await new Promise(ee=>setTimeout(ee,1e3));let oe=await this.getCleanUiHierarchy(t,s);w=oe.xml,A=oe.flat,this.visitedScreenHashes.add(ce(A)),console.log(P.green("\u2714 Main view restored from side drawer."))}else $==="WARN"&&console.log(P.yellow("\u26A0\uFE0F Drawer button tapped but no visible screen change occurred."));$!=="FAIL"&&this.memory.markScreenCrawled(M,[C])}if(n){console.log(P.yellow(`
754
- [4/5] Inspecting Lists & Master-Detail Flows...`));let C=Bs(A);if(C.length>0){console.log(P.magenta(`\u26A1 Found ${C.length} scrollable container(s). Performing vertical scroll exploration...`));let I=ce(A),F=Math.round(S*.5);await this.driver.swipe(F,Math.round(b*.7),F,Math.round(b*.3),300,s),await new Promise(L=>setTimeout(L,1200));let K=await this.getCleanUiHierarchy(t,s);w=K.xml,A=K.flat;let x=ce(A);this.visitedScreenHashes.add(x);let $=I!==x,_=await h("PASS",$);this.reporter.logStep("Scroll Exploration",$?"Scrolled vertically to discover off-screen elements":"Scrolled but content remained at edge","Swipe","PASS","SwipeUp",_),$&&console.log(P.green("\u2714 Vertical scroll succeeded; discovered off-screen content below fold."))}let M=bt(A).filter(I=>{if(Pe(I)){let F=I.text||I.contentDesc||"External Link";return this.externalSkippedList.push(F),!1}if(Ee(I,a,o)){let F=I.text||I.contentDesc||"List Item";return console.log(P.yellow(` \u{1F6E1}\uFE0F Safety Guard: Blocked destructive list item "${F}"`)),this.safetyHitList.push(F),!1}return!0});if(M.length>0){let I=M[0],F=I.text||I.contentDesc||`Item at (${I.bounds.centerX}, ${I.bounds.centerY})`;console.log(P.magenta(`\u26A1 Found list item: "${F}". Diving into detail view...`));let K=ce(A);await this.driver.tap(I.bounds.centerX,I.bounds.centerY,s),await new Promise(Ae=>setTimeout(Ae,1800));let x=await this.getCleanUiHierarchy(t,s);w=x.xml,A=x.flat;let $=ce(A);this.visitedScreenHashes.add($);let _=await this.runErrorSentinel(t,s,"Detail-View"),L=K!==$,oe=_.hasError?"FAIL":L?"PASS":"WARN",ee=await h(oe,L);this.reporter.logStep("List Dive",`Dived into detail view for "${F}" [${L?"Navigated":"Unchanged"}]`,"Tap",oe,F,ee,_.hasError?{errors:_.errors}:void 0),console.log(oe==="PASS"?P.green("\u2714 Detail screen loaded."):oe==="WARN"?P.yellow("\u26A0\uFE0F Detail view tapped but no navigation detected."):P.red("\u2716 Detail view triggered an error."));let fe=we(x.flat,T.screen.fallbackHeight,T.screen.fallbackWidth,!0);fe&&fe.bounds.width>0?(console.log(P.gray(`Navigating back via in-app back button "${fe.text||fe.contentDesc||fe.className}"...`)),await this.driver.tap(fe.bounds.centerX,fe.bounds.centerY,s)):(console.log(P.gray("Navigating back to main view...")),await this.driver.pressKey(4,s)),await new Promise(Ae=>setTimeout(Ae,1200));let Ie=await this.driver.getForegroundPackage(s);(!Ie||!Ie.includes(t))&&(console.log(P.yellow(`Restoring ${t} foreground after back navigation...`)),await this.driver.launchApp(t,s),await new Promise(Ae=>setTimeout(Ae,2e3)));let q=await this.getCleanUiHierarchy(t,s);w=q.xml,A=q.flat,this.visitedScreenHashes.add(ce(A));let pe=await this.runErrorSentinel(t,s,"Post-Back-Restore"),Me=pe.hasError?"FAIL":"PASS",Tt=await h(Me,!0);this.reporter.logStep("List Dive","Navigated back to master screen","Back",Me,"KEYCODE_BACK",Tt,pe.hasError?{errors:pe.errors}:void 0),Me==="PASS"&&console.log(P.green("\u2714 Master view restored."))}else console.log(P.gray("No list items found for master-detail exploration."))}}console.log(P.yellow(`
755
- [5/5] Inspecting Navigation Tabs...`));let j=await this.driver.getForegroundPackage(s);(!j||!j.includes(t))&&(console.log(P.gray(`Restoring ${t} foreground for tab traversal...`)),await this.driver.launchApp(t,s),await new Promise(ne=>setTimeout(ne,2e3))),await this.dismissSoftKeyboard(s);let Te=await this.getCleanUiHierarchy(t,s);w=Te.xml,A=Te.flat;let te=Ut(A,void 0,t);if(te.length>1){console.log(P.magenta(`\u26A1 Found ${te.length} navigation tab(s). Traversal sequence initiated...`));let ne=te.slice(0,i),J=1;for(let N of ne){let Q=N.text||N.contentDesc||`Tab #${J}`;console.log(P.gray(` - Visiting ${Q}...`)),await this.dismissSoftKeyboard(s);let C=Math.min(N.bounds.centerY,N.bounds.y2-4);this.executedStepCount++,await this.driver.tap(N.bounds.centerX,C,s),await new Promise($=>setTimeout($,1500)),await this.packageJailGuard(t,s);let M=await this.getCleanUiHierarchy(t,s);w=M.xml,A=M.flat;let I=ce(A);this.visitedScreenHashes.add(I),this.memory.markScreenCrawled(I,[Q]);let F=await this.runErrorSentinel(t,s,`Tab-${Q}`),K=F.hasError?"FAIL":"PASS",x=await h(K,!0);if(this.reporter.logStep("Tab Traversal",`Navigated to tab "${Q}"`,"Tap",K,Q,x,F.hasError?{errors:F.errors}:void 0),console.log(K==="PASS"?P.green(` \u2714 Tab "${Q}" loaded cleanly.`):P.red(` \u2716 Tab "${Q}" triggered errors.`)),this.executedStepCount<c&&this.visitedScreenHashes.size<l){let $=[],_=b*.08,L=b*.88,oe=q=>q.bounds.centerY>_&&q.bounds.centerY<L&&q.clickable&&q.bounds.width>30&&q.bounds.height>20&&te.every(pe=>Math.abs(pe.bounds.centerX-q.bounds.centerX)>40||Math.abs(pe.bounds.centerY-q.bounds.centerY)>40),ee=bt(A,{width:S,height:b}).filter(oe);for(let q of ee.slice(0,3))$.push({node:q,type:"list"});let fe=Ge(A).filter(q=>!(!oe(q)||Oe([q],b)));for(let q of fe.slice(0,4))$.push({node:q,type:"button"});let Ie=it(A).filter(oe);for(let q of Ie.slice(0,2))$.push({node:q,type:"toggle"});for(let q of $){if(this.executedStepCount>=c||this.visitedScreenHashes.size>=l)break;let pe=q.node;if(Pe(pe)){this.externalSkippedList.push(pe.text||pe.contentDesc||"External Link");continue}if(Ee(pe,a,o)){let Ze=pe.text||pe.contentDesc||"Destructive Action";this.safetyHitList.push(Ze);continue}let Me=pe.text||pe.contentDesc||pe.resourceId||`${q.type} element`;console.log(P.gray(` Sub-crawl [${Q}]: Exercising ${q.type} "${Me.slice(0,40)}"...`)),this.executedStepCount++,await this.driver.tap(pe.bounds.centerX,pe.bounds.centerY,s),await new Promise(Ze=>setTimeout(Ze,1200)),await this.dismissSoftKeyboard(s),await this.packageJailGuard(t,s);let Tt=await this.getCleanUiHierarchy(t,s);w=Tt.xml,A=Tt.flat;let Ae=ce(A),pi=!this.visitedScreenHashes.has(Ae);this.visitedScreenHashes.add(Ae);let Mt=await this.runErrorSentinel(t,s,`Sub-${Me.slice(0,30)}`),As=Mt.hasError?"FAIL":"PASS",hi=await h(As,pi);if(this.reporter.logStep("Tab Sub-Crawl",`Tested ${q.type} "${Me}" under tab "${Q}"`,"Tap",As,Me,hi,Mt.hasError?{errors:Mt.errors}:void 0),Ae!==I){console.log(P.cyan(` \u{1F50E} Screen transitioned. Discovered new screen state [${Ae.slice(0,8)}]`));let Ze=Ge(A).filter($e=>oe($e)&&!Ee($e,a,o)&&!Pe($e));if(Ze.length>0&&this.executedStepCount<c){let $e=Ze[0],gi=$e.text||$e.contentDesc||"Child Action";console.log(P.gray(` Exercising child action "${gi.slice(0,30)}"...`)),this.executedStepCount++,await this.driver.tap($e.bounds.centerX,$e.bounds.centerY,s),await new Promise(mi=>setTimeout(mi,1e3)),await this.dismissSoftKeyboard(s)}console.log(P.gray(` Restoring ${Q} master view via Back...`)),await this.driver.pressBack(s),await new Promise($e=>setTimeout($e,1e3)),await this.dismissSoftKeyboard(s);let $s=await this.getCleanUiHierarchy(t,s);w=$s.xml,A=$s.flat}}}J++}console.log(P.green("\u2714 Navigation tabs traversed successfully!"))}else console.log(P.gray("Single-screen or tabs not detected at screen footer."));for(let ne of this.visitedScreenHashes)this.memory.markScreenCrawled(ne);await this.memory.save();let le=this.memory.getStats();this.reporter.logStep("Coverage Audit",`State Graph Coverage: Visited ${this.visitedScreenHashes.size} unique screen state(s). Memory Engine cached ${le.crawledScreens} crawled screen(s).`,"Verify","PASS"),await this.runErrorSentinel(t,s,"Final-State");let U=await this.reporter.generateReport(),be=U.failedSteps===0&&U.errorsDetected.length===0;console.log(be?P.bold.green(`
749
+ [1/5] Verifying Foreground State...`));let m=await this.driver.getForegroundPackage(s);(!m||!m.includes(t))&&(console.log(P.gray(`Launching ${t}...`)),await this.driver.launchApp(t,s),await new Promise(ne=>setTimeout(ne,2500)));let v=await this.runErrorSentinel(t,s,"Post-Launch"),x=v.hasError?"FAIL":"PASS",D=await h(x,!0);this.reporter.logStep("Init",`Launched and verified foreground for ${t}`,"Launch",x,t,D,v.hasError?{errors:v.errors}:void 0),console.log(x==="PASS"?P.green("\u2714 App is active in foreground."):P.red(`\u2716 Issues detected during launch for ${t}.`)),console.log(P.yellow(`
750
+ [2/5] Inspecting UI Hierarchy for Forms...`));let{xml:w,flat:A}=await this.getCleanUiHierarchy(t,s),B=ce(A);if(this.visitedScreenHashes.add(B),this.memory.isScreenCrawled(B)&&r)console.log(P.cyan(` \u26A1 Fast-Forward: Screen [${B.slice(0,8)}] was previously crawled offline. Skipping redundant element interactions.`)),this.reporter.logStep("Fast Forward",`Fast-forwarded past previously crawled screen [${B.slice(0,8)}] (Memory Engine)`,"Skip","PASS");else{let ne=_e(A);if(ne.length>0){console.log(P.magenta(`\u26A1 Detected ${ne.length} form field(s)! Engaging Semantic Form Filler...`));for(let L of ne)console.log(P.gray(` - Field: "${L.text||L.contentDesc||L.resourceId}"`));let C=await this.formFiller.fillAndSubmitForm(A,s,!0,!1);this.executedStepCount++,await new Promise(L=>setTimeout(L,1500)),await this.dismissSoftKeyboard(s),await this.packageJailGuard(t,s);let M=await this.getCleanUiHierarchy(t,s);w=M.xml,A=M.flat,this.visitedScreenHashes.add(ce(A));let I=await this.runErrorSentinel(t,s,"Post-Form-Submit"),F=_e(A),T=I.hasError||F.length===ne.length&&I.errors.length>0?"FAIL":"PASS",k=await h(T,!0),_=C.filledFields.map(L=>`${L.fieldLabel} -> "${L.valueEntered}"`).join(", ");this.reporter.logStep("Form Fill",`Filled ${C.filledFields.length} field(s) [${_}] and submitted via "${C.submitButtonText||"Auto"}"`,"FormSubmit",T,C.submitButtonText,k,I.hasError?{errors:I.errors}:void 0),console.log(T==="PASS"?P.green("\u2714 Form populated and submitted successfully!"):P.red("\u2716 Form submission triggered an error or remained unauthenticated."))}else console.log(P.gray("No form input fields detected on initial screen."));console.log(P.yellow(`
751
+ [3/5] Inspecting Interactive Action Controls...`));let J=Ge(A).filter(C=>{let M=(C.text+" "+C.contentDesc).toLowerCase();if(M.includes("submit")||M.includes("cancel")||Oe([C],b))return!1;if(Pe(C)){let I=C.text||C.contentDesc||C.resourceId||"External Link";return console.log(P.gray(` \u{1F517} External Link Bypassed: "${I}"`)),this.externalSkippedList.push(I),!1}if(Ee(C,a,o)){let I=C.text||C.contentDesc||C.resourceId||"Action";return console.log(P.yellow(` \u{1F6E1}\uFE0F Safety Guard: Blocked destructive action "${I}"`)),this.safetyHitList.push(I),!1}return!0});if(J.length>0){let C=J[0],M=C.text||C.contentDesc||C.resourceId;console.log(P.magenta(`\u26A1 Found action button: "${M}". Testing interaction...`));let I=ce(A);this.executedStepCount++,await this.driver.tap(C.bounds.centerX,C.bounds.centerY,s),await new Promise(ee=>setTimeout(ee,1200)),await this.packageJailGuard(t,s);let F=await this.getCleanUiHierarchy(t,s);w=F.xml,A=F.flat;let K=ce(A);this.visitedScreenHashes.add(K);let T=await this.runErrorSentinel(t,s,"Post-Action-Tap"),k=I!==K,_="PASS",L="";T.hasError?(_="FAIL",L="Action triggered error or crash"):k?(_="PASS",L="Screen transitioned successfully"):(_="WARN",L="No visible screen transition or state change observed (No-Op)",console.log(P.yellow(` \u26A0\uFE0F Outcome Warning: Action "${M}" produced no UI state change.`)));let oe=await h(_,k);this.reporter.logStep("Action Testing",`Tapped action button "${M}" [${L}]`,"Tap",_,M,oe,T.hasError?{errors:T.errors}:void 0),console.log(_==="PASS"?P.green(`\u2714 Action interaction complete (${L}).`):_==="WARN"?P.yellow(`\u2714 Action interaction recorded with warning (${L}).`):P.red("\u2716 Action interaction triggered an error.")),_!=="FAIL"&&(this.memory.recordSuccess("TAP",M,C.resourceId||C.text||C.contentDesc||M,"text",1,void 0,I),this.memory.markScreenCrawled(I,[M]))}else console.log(P.gray("No standalone action buttons to test."));let N=it(A).filter(C=>!Ee(C,a,o));if(N.length>0){console.log(P.yellow(`
752
+ [3b/5] Inspecting Toggle & Checkable Controls...`));let C=N[0],M=C.text||C.contentDesc||C.resourceId||"Switch/Checkbox",I=C.checked;console.log(P.magenta(`\u26A1 Found toggle: "${M}" (checked: ${I}). Testing toggle interaction...`)),this.executedStepCount++,await this.driver.tap(C.bounds.centerX,C.bounds.centerY,s),await new Promise(ee=>setTimeout(ee,1e3)),w=await this.driver.getUiHierarchy(s),A=ue(w).flat;let F=ce(A);this.visitedScreenHashes.add(F);let T=it(A).find(ee=>Math.abs(ee.bounds.centerX-C.bounds.centerX)<25&&Math.abs(ee.bounds.centerY-C.bounds.centerY)<25),k=T?T.checked!==I:!0,_=await this.runErrorSentinel(t,s,"Post-Toggle"),L=_.hasError?"FAIL":k?"PASS":"WARN",oe=await h(L,k);this.reporter.logStep("Toggle Testing",`Toggled "${M}" (Checked: ${I} -> ${T?T.checked:"flipped"})`,"Toggle",L,M,oe,_.hasError?{errors:_.errors}:void 0),console.log(L==="PASS"?P.green("\u2714 Toggle control flipped successfully!"):L==="WARN"?P.yellow("\u26A0\uFE0F Toggle tapped but checked state did not flip."):P.red("\u2716 Toggle control triggered an error.")),L!=="FAIL"&&this.memory.markScreenCrawled(F,[M])}let Q=Oe(A,b);if(Q&&!Ee(Q,a,o)){let C=Q.contentDesc||Q.text||Q.resourceId||"Drawer Menu";console.log(P.yellow(`
753
+ [3c/5] Inspecting Side Navigation Drawer...`)),console.log(P.magenta(`\u26A1 Found drawer trigger: "${C}". Opening side drawer...`));let M=ce(A);this.executedStepCount++,await this.driver.tap(Q.bounds.centerX,Q.bounds.centerY,s),await new Promise(L=>setTimeout(L,1200)),await this.packageJailGuard(t,s);let I=await this.getCleanUiHierarchy(t,s);w=I.xml,A=I.flat;let F=ce(A);this.visitedScreenHashes.add(F);let K=M!==F,T=await this.runErrorSentinel(t,s,"Drawer-Open"),k=T.hasError?"FAIL":K?"PASS":"WARN",_=await h(k,K);if(this.reporter.logStep("Drawer Navigation",`Opened side drawer via "${C}"`,"Tap",k,C,_,T.hasError?{errors:T.errors}:void 0),k==="PASS"){console.log(P.green("\u2714 Side drawer opened successfully!"));let L=Ge(A).filter(ee=>!Ee(ee,a,o)&&!Pe(ee)&&ee.bounds.centerY>Q.bounds.y2);if(L.length>0){let ee=L[0],fe=ee.text||ee.contentDesc||ee.resourceId||"Drawer Item";console.log(P.gray(` - Testing drawer item: "${fe}"...`)),this.executedStepCount++,await this.driver.tap(ee.bounds.centerX,ee.bounds.centerY,s),await new Promise(q=>setTimeout(q,1200)),await this.packageJailGuard(t,s);let Ie=await this.getCleanUiHierarchy(t,s);w=Ie.xml,A=Ie.flat,this.visitedScreenHashes.add(ce(A))}console.log(P.gray(" Closing side drawer to restore main view...")),await this.driver.pressBack(s),await new Promise(ee=>setTimeout(ee,1e3));let oe=await this.getCleanUiHierarchy(t,s);w=oe.xml,A=oe.flat,this.visitedScreenHashes.add(ce(A)),console.log(P.green("\u2714 Main view restored from side drawer."))}else k==="WARN"&&console.log(P.yellow("\u26A0\uFE0F Drawer button tapped but no visible screen change occurred."));k!=="FAIL"&&this.memory.markScreenCrawled(M,[C])}if(n){console.log(P.yellow(`
754
+ [4/5] Inspecting Lists & Master-Detail Flows...`));let C=Bs(A);if(C.length>0){console.log(P.magenta(`\u26A1 Found ${C.length} scrollable container(s). Performing vertical scroll exploration...`));let I=ce(A),F=Math.round(S*.5);await this.driver.swipe(F,Math.round(b*.7),F,Math.round(b*.3),300,s),await new Promise(L=>setTimeout(L,1200));let K=await this.getCleanUiHierarchy(t,s);w=K.xml,A=K.flat;let T=ce(A);this.visitedScreenHashes.add(T);let k=I!==T,_=await h("PASS",k);this.reporter.logStep("Scroll Exploration",k?"Scrolled vertically to discover off-screen elements":"Scrolled but content remained at edge","Swipe","PASS","SwipeUp",_),k&&console.log(P.green("\u2714 Vertical scroll succeeded; discovered off-screen content below fold."))}let M=bt(A).filter(I=>{if(Pe(I)){let F=I.text||I.contentDesc||"External Link";return this.externalSkippedList.push(F),!1}if(Ee(I,a,o)){let F=I.text||I.contentDesc||"List Item";return console.log(P.yellow(` \u{1F6E1}\uFE0F Safety Guard: Blocked destructive list item "${F}"`)),this.safetyHitList.push(F),!1}return!0});if(M.length>0){let I=M[0],F=I.text||I.contentDesc||`Item at (${I.bounds.centerX}, ${I.bounds.centerY})`;console.log(P.magenta(`\u26A1 Found list item: "${F}". Diving into detail view...`));let K=ce(A);await this.driver.tap(I.bounds.centerX,I.bounds.centerY,s),await new Promise(Ae=>setTimeout(Ae,1800));let T=await this.getCleanUiHierarchy(t,s);w=T.xml,A=T.flat;let k=ce(A);this.visitedScreenHashes.add(k);let _=await this.runErrorSentinel(t,s,"Detail-View"),L=K!==k,oe=_.hasError?"FAIL":L?"PASS":"WARN",ee=await h(oe,L);this.reporter.logStep("List Dive",`Dived into detail view for "${F}" [${L?"Navigated":"Unchanged"}]`,"Tap",oe,F,ee,_.hasError?{errors:_.errors}:void 0),console.log(oe==="PASS"?P.green("\u2714 Detail screen loaded."):oe==="WARN"?P.yellow("\u26A0\uFE0F Detail view tapped but no navigation detected."):P.red("\u2716 Detail view triggered an error."));let fe=we(T.flat,E.screen.fallbackHeight,E.screen.fallbackWidth,!0);fe&&fe.bounds.width>0?(console.log(P.gray(`Navigating back via in-app back button "${fe.text||fe.contentDesc||fe.className}"...`)),await this.driver.tap(fe.bounds.centerX,fe.bounds.centerY,s)):(console.log(P.gray("Navigating back to main view...")),await this.driver.pressKey(4,s)),await new Promise(Ae=>setTimeout(Ae,1200));let Ie=await this.driver.getForegroundPackage(s);Ie&&!Ie.includes(t)&&(console.log(P.yellow(`Restoring ${t} foreground after back navigation...`)),await this.driver.launchApp(t,s),await new Promise(Ae=>setTimeout(Ae,2e3)));let q=await this.getCleanUiHierarchy(t,s);w=q.xml,A=q.flat,this.visitedScreenHashes.add(ce(A));let pe=await this.runErrorSentinel(t,s,"Post-Back-Restore"),Me=pe.hasError?"FAIL":"PASS",Tt=await h(Me,!0);this.reporter.logStep("List Dive","Navigated back to master screen","Back",Me,"KEYCODE_BACK",Tt,pe.hasError?{errors:pe.errors}:void 0),Me==="PASS"&&console.log(P.green("\u2714 Master view restored."))}else console.log(P.gray("No list items found for master-detail exploration."))}}console.log(P.yellow(`
755
+ [5/5] Inspecting Navigation Tabs...`));let j=await this.driver.getForegroundPackage(s);j&&!j.includes(t)&&(console.log(P.gray(`Restoring ${t} foreground for tab traversal...`)),await this.driver.launchApp(t,s),await new Promise(ne=>setTimeout(ne,2e3))),await this.dismissSoftKeyboard(s);let Te=await this.getCleanUiHierarchy(t,s);w=Te.xml,A=Te.flat;let te=Ut(A,void 0,t);if(te.length>1){console.log(P.magenta(`\u26A1 Found ${te.length} navigation tab(s). Traversal sequence initiated...`));let ne=te.slice(0,i),J=1;for(let N of ne){let Q=N.text||N.contentDesc||`Tab #${J}`;console.log(P.gray(` - Visiting ${Q}...`)),await this.dismissSoftKeyboard(s);let C=Math.min(N.bounds.centerY,N.bounds.y2-4);this.executedStepCount++,await this.driver.tap(N.bounds.centerX,C,s),await new Promise(k=>setTimeout(k,1500)),await this.packageJailGuard(t,s);let M=await this.getCleanUiHierarchy(t,s);w=M.xml,A=M.flat;let I=ce(A);this.visitedScreenHashes.add(I),this.memory.markScreenCrawled(I,[Q]);let F=await this.runErrorSentinel(t,s,`Tab-${Q}`),K=F.hasError?"FAIL":"PASS",T=await h(K,!0);if(this.reporter.logStep("Tab Traversal",`Navigated to tab "${Q}"`,"Tap",K,Q,T,F.hasError?{errors:F.errors}:void 0),console.log(K==="PASS"?P.green(` \u2714 Tab "${Q}" loaded cleanly.`):P.red(` \u2716 Tab "${Q}" triggered errors.`)),this.executedStepCount<c&&this.visitedScreenHashes.size<d){let k=[],_=b*.08,L=b*.88,oe=q=>q.bounds.centerY>_&&q.bounds.centerY<L&&q.clickable&&q.bounds.width>30&&q.bounds.height>20&&te.every(pe=>Math.abs(pe.bounds.centerX-q.bounds.centerX)>40||Math.abs(pe.bounds.centerY-q.bounds.centerY)>40),ee=bt(A,{width:S,height:b}).filter(oe);for(let q of ee.slice(0,3))k.push({node:q,type:"list"});let fe=Ge(A).filter(q=>!(!oe(q)||Oe([q],b)));for(let q of fe.slice(0,4))k.push({node:q,type:"button"});let Ie=it(A).filter(oe);for(let q of Ie.slice(0,2))k.push({node:q,type:"toggle"});for(let q of k){if(this.executedStepCount>=c||this.visitedScreenHashes.size>=d)break;let pe=q.node;if(Pe(pe)){this.externalSkippedList.push(pe.text||pe.contentDesc||"External Link");continue}if(Ee(pe,a,o)){let Ze=pe.text||pe.contentDesc||"Destructive Action";this.safetyHitList.push(Ze);continue}let Me=pe.text||pe.contentDesc||pe.resourceId||`${q.type} element`;console.log(P.gray(` Sub-crawl [${Q}]: Exercising ${q.type} "${Me.slice(0,40)}"...`)),this.executedStepCount++,await this.driver.tap(pe.bounds.centerX,pe.bounds.centerY,s),await new Promise(Ze=>setTimeout(Ze,1200)),await this.dismissSoftKeyboard(s),await this.packageJailGuard(t,s);let Tt=await this.getCleanUiHierarchy(t,s);w=Tt.xml,A=Tt.flat;let Ae=ce(A),hi=!this.visitedScreenHashes.has(Ae);this.visitedScreenHashes.add(Ae);let Mt=await this.runErrorSentinel(t,s,`Sub-${Me.slice(0,30)}`),As=Mt.hasError?"FAIL":"PASS",gi=await h(As,hi);if(this.reporter.logStep("Tab Sub-Crawl",`Tested ${q.type} "${Me}" under tab "${Q}"`,"Tap",As,Me,gi,Mt.hasError?{errors:Mt.errors}:void 0),Ae!==I){console.log(P.cyan(` \u{1F50E} Screen transitioned. Discovered new screen state [${Ae.slice(0,8)}]`));let Ze=Ge(A).filter($e=>oe($e)&&!Ee($e,a,o)&&!Pe($e));if(Ze.length>0&&this.executedStepCount<c){let $e=Ze[0],mi=$e.text||$e.contentDesc||"Child Action";console.log(P.gray(` Exercising child action "${mi.slice(0,30)}"...`)),this.executedStepCount++,await this.driver.tap($e.bounds.centerX,$e.bounds.centerY,s),await new Promise(fi=>setTimeout(fi,1e3)),await this.dismissSoftKeyboard(s)}console.log(P.gray(` Restoring ${Q} master view via Back...`)),await this.driver.pressBack(s),await new Promise($e=>setTimeout($e,1e3)),await this.dismissSoftKeyboard(s);let $s=await this.getCleanUiHierarchy(t,s);w=$s.xml,A=$s.flat}}}J++}console.log(P.green("\u2714 Navigation tabs traversed successfully!"))}else console.log(P.gray("Single-screen or tabs not detected at screen footer."));for(let ne of this.visitedScreenHashes)this.memory.markScreenCrawled(ne);await this.memory.save();let le=this.memory.getStats();this.reporter.logStep("Coverage Audit",`State Graph Coverage: Visited ${this.visitedScreenHashes.size} unique screen state(s). Memory Engine cached ${le.crawledScreens} crawled screen(s).`,"Verify","PASS"),await this.runErrorSentinel(t,s,"Final-State");let U=await this.reporter.generateReport(),be=U.failedSteps===0&&U.errorsDetected.length===0;console.log(be?P.bold.green(`
756
756
  \u2728 PromptTest Exploration Complete \u2014 All Steps Passed!`):P.bold.red(`
757
757
  \u26A0\uFE0F PromptTest Exploration Complete \u2014 Issues Detected!`)),console.log(P.white(`Summary: ${U.passedSteps} passed, ${U.warnSteps} warnings, ${U.failedSteps} failed, ${U.errorsDetected.length} errors detected.`)),this.safetyHitList.length>0&&console.log(P.cyan(`\u{1F6E1}\uFE0F Safety Shield: Blocked ${this.safetyHitList.length} destructive action(s) [${this.safetyHitList.join(", ")}].`)),console.log(P.cyan(`\u{1F5FA}\uFE0F State Graph Coverage: Visited ${this.visitedScreenHashes.size} unique screen state(s).`)),console.log(P.cyan(`\u{1F9E0} Memory Engine Coverage: ${le.crawledScreens} crawled screen(s) indexed offline.`)),console.log(P.cyan(`Full Audit Report generated at: output/prompttest-report.md
758
- `))}finally{f&&ze(f)}}async runErrorSentinel(e,t,s){let i=[];try{let[n,r]=await Promise.all([this.driver.checkCrashes(e,t),this.driver.getUiHierarchy(t)]);if(n){let l=`Crash in ${s}: ${n.slice(0,300)}`;console.log(P.bold.red(`\u{1F6A8} FATAL EXCEPTION DETECTED in ${e} [${s}]!`)),this.reporter.logError(l),i.push(l)}let{flat:o}=ue(r),a=_s(o);if(a.length>0)for(let l of a){let c=l.text||l.contentDesc,p=`UI Error dialog in ${s}: "${c}"`;console.log(P.bold.yellow(`\u26A0\uFE0F Error Dialog/Banner on screen [${s}]: "${c}"`)),this.reporter.logError(p),i.push(p)}}catch{}return{hasError:i.length>0,errors:i}}},No=new ut;import de from"fs";import re from"path";import D from"chalk";import{spawn as Fi}from"child_process";import _i from"readline";import{createRequire as Oi}from"module";var Bi=Oi(import.meta.url),Es="1.1.0";try{Es=Bi("../../package.json").version||"1.1.0"}catch{}var pt=class{driver;deviceLock=null;isRecording=!1;recordedSteps=[];existingSteps=[];existingFileHeader=[];lastHierarchyFlat=[];lastScreenTitle="";visitedScreens=[];targetPackage=null;isAppendMode=!1;resolvedOutputPath="";activeInput=null;geteventProcess=null;isRefreshingHierarchy=!1;targetSerial="";touchMaxX=T.screen.fallbackWidth;touchMaxY=T.screen.fallbackHeight;displayWidth=T.screen.fallbackWidth;displayHeight=T.screen.fallbackHeight;lastTapTimestamp=0;lastRecordedTapTarget="";inFlightTapQueue=[];lastScrollTimestamp=0;lastScrollDirection="";inputDebounceTimer=null;logcatEventProcess=null;logcatCrashProcess=null;hierarchyStale=!0;hierarchyCacheTime=0;currentScreenName="";sessionScreenSections=[];sessionStartTime=0;screenshotDir="";screenshotCounter=0;crashDetected=!1;lastScreenTransitionTime=0;constructor(e){this.driver=e||he}extractBrandSlug(e){if(!e)return"app";let t=new Set(["com","org","net","io","in","co","uk","de","fr","us","ai","dev","android","mobile","app","apps","client","release","debug","main","browser","ui","view","experience","portal","phone","tablet","service"]),s=e.split("."),i=s.filter(r=>!t.has(r.toLowerCase())&&!/^\d+$/.test(r));return((i.length>0?i[i.length-1]:s[s.length-1])||"app").toLowerCase().replace(/[^a-z0-9_]/g,"")}async startRecording(e,t,s){let i=await this.driver.ensureDefaultDevice(t);if(!i)throw new Error("No Android device connected for recording.");this.deviceLock=Ke(i),this.targetSerial=i,this.isRecording=!0,this.recordedSteps=[],this.existingSteps=[],this.existingFileHeader=[],this.visitedScreens=[],this.targetPackage=null,this.activeInput=null,this.isAppendMode=!!s?.append;try{let m=await this.driver.getForegroundPackage(i);m&&(this.targetPackage=m)}catch{}let n=this.extractBrandSlug(this.targetPackage),r;if(e&&e!=="specs/recorded_suite.txt")r=re.resolve(e);else{let m=`${n}_flow`,v=re.resolve(`specs/${m}.txt`);if(!this.isAppendMode&&de.existsSync(v)){let E=1;for(v=re.resolve(`specs/${m}_${E}.txt`);de.existsSync(v);)E++,v=re.resolve(`specs/${m}_${E}.txt`)}r=v}if(this.resolvedOutputPath=r,de.existsSync(r))if(this.isAppendMode){let m=de.readFileSync(r,"utf-8"),v=m.split(`
759
- `);for(let k of v){let w=k.trim();if(/^\d+\.\s+/.test(w))this.existingSteps.push(w.replace(/^\d+\.\s+/,""));else if(w.startsWith("# Package:")){let A=w.match(/# Package:\s*([a-zA-Z0-9._]+)/);A&&(this.targetPackage=A[1])}}let E=`${r}.bak`;de.writeFileSync(E,m,"utf-8"),console.log(D.cyan(`\u{1F4E5} Loaded ${this.existingSteps.length} existing step(s) from: ${re.basename(r)}`)),console.log(D.gray(`\u{1F4E6} Safety backup preserved at: ${re.basename(E)}`))}else{let m=de.readFileSync(r,"utf-8"),v=`${r}.bak`;de.writeFileSync(v,m,"utf-8"),console.log(D.yellow(`\u26A0\uFE0F File "${re.basename(r)}" already exists.`)),console.log(D.gray(`\u{1F4E6} Safety backup preserved at: ${re.basename(v)}`))}await this.driver.wakeDevice(i).catch(()=>{});let a=await this.driver.getScreenDimensions(i);this.displayWidth=a.width||T.screen.fallbackWidth,this.displayHeight=a.height||T.screen.fallbackHeight,this.touchMaxX=this.displayWidth,this.touchMaxY=this.displayHeight;try{let{stdout:m}=await this.driver.execAdb(["shell","getevent","-p"],i),v=m.match(/0035\s*:\s*value\s*\d+,\s*min\s*\d+,\s*max\s*(\d+)/),E=m.match(/0036\s*:\s*value\s*\d+,\s*min\s*\d+,\s*max\s*(\d+)/);v&&parseInt(v[1])>0&&(this.touchMaxX=parseInt(v[1])),E&&parseInt(E[1])>0&&(this.touchMaxY=parseInt(E[1]))}catch{}this.sessionStartTime=Date.now(),this.sessionScreenSections=[],this.screenshotCounter=0,this.crashDetected=!1,this.hierarchyStale=!0,this.currentScreenName="";let l=re.basename(r,".txt"),c=re.resolve("output");this.screenshotDir=re.join(c,"screenshots",l),de.existsSync(this.screenshotDir)||de.mkdirSync(this.screenshotDir,{recursive:!0});let p=D.gray("\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501"),h=await this.driver.getDeviceModel(i).catch(()=>i);console.log(`
760
- ${p}`),console.log(D.bold.cyan(`\u26A1 PromptTest v${Es}`)+D.gray(" | Recording Session")),console.log(p),console.log(` ${D.gray("\u{1F4F1} Device ")} ${D.white(h)} ${D.gray(`(${i})`)}`),console.log(` ${D.gray("\u{1F4E6} App ")} ${D.green(this.targetPackage||"Unknown")}`),console.log(` ${D.gray("\u{1F3AF} Spec ")} ${D.yellow(re.basename(r))}`);let d=re.join(c,`${l}_report.md`);console.log(` ${D.gray("\u{1F4CA} Report ")} ${D.yellow(re.basename(d))}`),console.log(` ${D.gray("\u{1F4F8} Photos ")} ${D.yellow(re.relative(process.cwd(),this.screenshotDir))}`),this.isAppendMode&&this.existingSteps.length>0&&console.log(` ${D.gray("\u{1F4CE} Mode ")} ${D.magenta(`Append \u2014 resuming from step #${this.existingSteps.length+1}`)}`),console.log(p),process.stdout.write(` ${D.gray("Checking device health...")} `),console.log(D.green("\u2714 Ready")),process.stdout.write(` ${D.gray("Loading initial screen...")} `);let g=Date.now();await this.refreshHierarchySync();let f=Date.now()-g,y=this.currentScreenName?D.bold.white(this.currentScreenName):D.gray("Unknown");console.log(`${D.green("\u2714")} ${y} ${D.gray(`[${f}ms]`)}`),process.stdout.write(` ${D.gray("Starting screen watcher...")} `),this.startLogcatScreenWatcher(i),this.startLogcatCrashWatcher(i),console.log(D.green("\u2714 Streaming")),console.log(p),console.log(` ${D.gray("Use the app naturally. Every action is captured.")}`),console.log(` ${D.gray("Press Ctrl+C to stop and save.")}`),console.log(`${p}
761
- `);let S=()=>{if(this.isRecording=!1,this.inputDebounceTimer&&(clearTimeout(this.inputDebounceTimer),this.inputDebounceTimer=null),this.deviceLock&&(ze(this.deviceLock),this.deviceLock=null),this.geteventProcess)try{this.geteventProcess.kill()}catch{}if(this.logcatEventProcess)try{this.logcatEventProcess.kill()}catch{}if(this.logcatCrashProcess)try{this.logcatCrashProcess.kill()}catch{}this.saveSpec(this.resolvedOutputPath),this.saveReport(d),this.printExitSummary(p),process.exit(0)};process.once("SIGINT",S),process.once("SIGTERM",S),this.startEventStream(i);let b=0;for(;this.isRecording;)if(await new Promise(m=>setTimeout(m,1500)),b++,b%20===0&&this.driver.wakeDevice(i).catch(()=>{}),!this.targetPackage){let m=await this.driver.getForegroundPackage(i).catch(()=>null);m&&(this.targetPackage=m)}}startEventStream(e){let s=Fi("adb",e?["-s",e,"shell","getevent","-l"]:["shell","getevent","-l"]);this.geteventProcess=s;let i=null,n=null,r=null,o=null,a=0;_i.createInterface({input:s.stdout}).on("line",c=>{if(this.isRecording)if(c.includes("ABS_MT_POSITION_X")){let p=c.match(/ABS_MT_POSITION_X\s+([0-9a-fA-F]+)/);p&&(i=parseInt(p[1],16))}else if(c.includes("ABS_MT_POSITION_Y")){let p=c.match(/ABS_MT_POSITION_Y\s+([0-9a-fA-F]+)/);p&&(n=parseInt(p[1],16))}else if(c.includes("BTN_TOUCH")&&c.includes("DOWN"))r=i,o=n,a=Date.now();else if(c.includes("BTN_TOUCH")&&c.includes("UP")){let p=i!==null?i:r,h=n!==null?n:o,d=Date.now()-a;if(p!==null&&h!==null&&r!==null&&o!==null){let g=Math.round(r/this.touchMaxX*this.displayWidth),f=Math.round(o/this.touchMaxY*this.displayHeight),y=Math.round(p/this.touchMaxX*this.displayWidth),S=Math.round(h/this.touchMaxY*this.displayHeight),b=y-g,m=S-f,v=Math.abs(b),E=Math.abs(m),k=Math.hypot(v,E);if(this.activeInput&&f>this.displayHeight*.58&&S>this.displayHeight*.58){d>=20&&d<400&&k<45&&y>=this.displayWidth*.78&&S>=this.displayHeight*.84?this.flushActiveInput().then(()=>{this.handleKeyPress("Enter")}).catch(()=>{}):this.scheduleInputDebounce(),i=null,n=null,r=null,o=null;return}if(d>=20&&d<400&&k<45)this.isRefreshingHierarchy?this.inFlightTapQueue.push({x:y,y:S,timestamp:Date.now()}):this.handleTapAt(y,S);else if(d>=450&&k<45)this.handleLongPressAt(y,S);else if(E>=100&&E>1.4*v){let w=m<0?"down":"up";this.handleScroll(w)}else if(v>=100&&v>1.4*E){let w=b<0?"left":"right";this.handleSwipe(w)}}i=null,n=null,r=null,o=null}else c.includes("KEY_ENTER")&&c.includes("DOWN")?this.handleKeyPress("Enter"):c.includes("KEY_BACK")&&c.includes("DOWN")&&this.handleKeyPress("Back")}),s.on("close",c=>{this.isRecording&&(console.warn(D.yellow(`
762
- \u26A0\uFE0F [EventStream] ADB event listener stream closed (code ${c}). Auto-reconnecting in 800ms...`)),setTimeout(()=>{this.isRecording&&this.startEventStream(e)},800))}),s.on("error",c=>{this.isRecording&&console.warn(D.yellow(`
763
- \u26A0\uFE0F [EventStream] ADB stream error: ${c.message}.`))})}cleanLabel(e){return e?e.replace(/[\uE000-\uF8FF\uFFF0-\uFFFF\uFFFD]/gu,"").replace(/,\s*tab,\s*\d+\s*of\s*\d+/gi,"").replace(/,\s*button$/gi,"").replace(/^[\s,•\-_:;|/\\]+|[\s,•\-_:;|/\\]+$/g,"").trim():""}handleScroll(e){let t=Date.now();if(this.lastScrollDirection===e&&t-this.lastScrollTimestamp<850)return;this.lastScrollTimestamp=t,this.lastScrollDirection=e,this.activeInput&&this.flushActiveInput().catch(()=>{});let s=`Scroll ${e}`;this.recordedSteps[this.recordedSteps.length-1]!==s&&(this.recordedSteps.push(s),console.log(D.blue(` \u{1F4DC} Recorded Scroll [Step #${this.getCurrentStepNumber()-1}]: ${D.bold(s)}`)),this.triggerAsyncHierarchyRefresh(400))}handleSwipe(e){let t=Date.now();if(t-this.lastScrollTimestamp<600)return;this.lastScrollTimestamp=t,this.activeInput&&this.flushActiveInput().catch(()=>{});let s=`Swipe ${e}`;this.recordedSteps.push(s),console.log(D.blue(` \u{1F449} Recorded Swipe [Step #${this.getCurrentStepNumber()-1}]: ${D.bold(s)}`)),this.triggerAsyncHierarchyRefresh(500)}handleLongPressAt(e,t){let s=this.lastHierarchyFlat.filter(r=>e>=r.bounds.x1&&e<=r.bounds.x2&&t>=r.bounds.y1&&t<=r.bounds.y2);if(s.length===0)return;s.sort((r,o)=>{let a=(r.bounds.x2-r.bounds.x1)*(r.bounds.y2-r.bounds.y1),l=(o.bounds.x2-o.bounds.x1)*(o.bounds.y2-o.bounds.y1);return a-l});let i=s[0],n=this.resolveActionLabel(i,s,this.lastHierarchyFlat);if(n){let r=`Long press '${n}'`;this.recordedSteps.push(r),console.log(D.cyan(` \u23F1\uFE0F Recorded Long Press [Step #${this.getCurrentStepNumber()-1}]: ${D.bold(r)}`)),this.triggerAsyncHierarchyRefresh()}}handleTapAt(e,t){let s=Date.now(),i=this.lastHierarchyFlat.filter(h=>e>=h.bounds.x1&&e<=h.bounds.x2&&t>=h.bounds.y1&&t<=h.bounds.y2),r=this.lastHierarchyFlat.filter(h=>{let d=h.bounds.height;return d>0&&d<320&&h.bounds.width>0&&(h.clickable||h.contentDesc||h.text)}).filter(h=>t>=h.bounds.y1-30&&t<=h.bounds.y2+40);if(r.length>=2){let h=r.find(d=>e>=d.bounds.x1-20&&e<=d.bounds.x2+20);h&&(i=[this.lastHierarchyFlat.find(g=>(this.cleanLabel(g.text).length>0||this.cleanLabel(g.contentDesc).length>0)&&Math.abs(g.bounds.centerX-h.bounds.centerX)<h.bounds.width*.48&&Math.abs(g.bounds.centerY-h.bounds.centerY)<h.bounds.height*.48&&!this.isIconGlyph(this.cleanLabel(g.text)))||h])}if(t>this.displayHeight*.82){let d=this.lastHierarchyFlat.filter(g=>{let f=g.bounds.y1>=this.displayHeight*.78||g.bounds.y2>=this.displayHeight*.82,y=g.bounds.width>0&&g.bounds.width<=this.displayWidth*.52;return f&&y}).find(g=>e>=g.bounds.x1-20&&e<=g.bounds.x2+20);if(d){let g=this.lastHierarchyFlat.find(f=>(this.cleanLabel(f.text).length>0||this.cleanLabel(f.contentDesc).length>0)&&e>=f.bounds.x1-25&&e<=f.bounds.x2+25&&f.bounds.y1>=this.displayHeight*.78&&!this.isIconGlyph(this.cleanLabel(f.text)));g?i=[g]:(this.cleanLabel(d.text)||this.cleanLabel(d.contentDesc))&&(i=[d])}}if(i.length===0){let h=this.lastHierarchyFlat.filter(f=>(this.cleanLabel(f.text).length>0||this.cleanLabel(f.contentDesc).length>0)&&(f.clickable||f.className.includes("Button")||f.className.includes("Text"))),d=null,g=70;for(let f of h){let y=Math.hypot(f.bounds.centerX-e,f.bounds.centerY-t);y<g&&(g=y,d=f)}if(d)i=[d];else{this.triggerAsyncHierarchyRefresh();return}}i.sort((h,d)=>{let g=(h.bounds.x2-h.bounds.x1)*(h.bounds.y2-h.bounds.y1),f=(d.bounds.x2-d.bounds.x1)*(d.bounds.y2-d.bounds.y1);return g-f});let o=i[0],a=i.find(h=>h.className.includes("EditText"))||(o.className.includes("EditText")?o:null);if(a){this.activeInput&&this.activeInput.node!==a&&this.flushActiveInput().catch(()=>{});let h=this.resolveFieldLabel(a,this.lastHierarchyFlat);this.activeInput={node:a,label:h,startText:a.text||""},this.triggerAsyncHierarchyRefresh();return}this.activeInput&&this.flushActiveInput().catch(()=>{});let l=this.resolveActionLabel(o,i,this.lastHierarchyFlat);if(!l||l.length===0){this.triggerAsyncHierarchyRefresh();return}if(!o.clickable&&!i.some(h=>h.clickable||h.className.includes("Button"))&&/^\d+%$|^\d+$/.test(l)){this.triggerAsyncHierarchyRefresh();return}if(l===this.lastRecordedTapTarget&&s-this.lastTapTimestamp<350)return;this.lastTapTimestamp=s,this.lastRecordedTapTarget=l;let c;if(o.checkable||o.className.includes("Switch")||o.className.includes("CheckBox")){let h=o.checked!==void 0?!o.checked:!0;c=`Toggle '${l}' to ${h?"on":"off"}`}else{c=`Tap '${l}'`;let h=this.lastHierarchyFlat.filter(g=>this.cleanLabel(g.text)===l||this.cleanLabel(g.contentDesc)===l),d=[];for(let g of h)d.some(y=>Math.hypot(y.bounds.centerX-g.bounds.centerX,y.bounds.centerY-g.bounds.centerY)<40)||d.push(g);if(d.length>1){let f=this.lastHierarchyFlat.filter(y=>y!==o&&Math.abs(y.bounds.centerY-o.bounds.centerY)<140&&Math.abs(y.bounds.centerX-o.bounds.centerX)<550).find(y=>{let S=this.cleanLabel(y.text)||this.cleanLabel(y.contentDesc);return S.length>2&&S!==l&&!/^\d+$/.test(S)&&!this.isIconGlyph(S)});if(f){let y=this.cleanLabel(f.text)||this.cleanLabel(f.contentDesc);y&&y!==l&&(c=`Tap '${l}' next to '${y}'`)}}}this.recordedSteps[this.recordedSteps.length-1]!==c&&(this.recordedSteps.push(c),console.log(D.cyan(` \u{1F446} Recorded Tap [Step #${this.getCurrentStepNumber()-1}]: ${D.bold(c)}`))),this.triggerAsyncHierarchyRefresh()}handleKeyPress(e){if(this.activeInput&&this.flushActiveInput().catch(()=>{}),e==="Enter"){let t="Press 'Enter'";this.recordedSteps[this.recordedSteps.length-1]!==t&&(this.recordedSteps.push(t),console.log(D.magenta(` \u21B5 Recorded Key [Step #${this.getCurrentStepNumber()-1}]: ${D.bold(t)}`)))}else if(e==="Back"){let t="Tap 'Back'";this.recordedSteps[this.recordedSteps.length-1]!==t&&(this.recordedSteps.push(t),console.log(D.magenta(` \u25C0 Recorded Key [Step #${this.getCurrentStepNumber()-1}]: ${D.bold(t)}`)))}this.triggerAsyncHierarchyRefresh()}scheduleInputDebounce(){this.inputDebounceTimer&&clearTimeout(this.inputDebounceTimer),this.inputDebounceTimer=setTimeout(()=>{this.activeInput&&this.syncActiveInputText().catch(()=>{})},450)}async flushActiveInput(){if(this.inputDebounceTimer&&(clearTimeout(this.inputDebounceTimer),this.inputDebounceTimer=null),!this.activeInput)return;let e=this.activeInput;this.activeInput=null,await this.recordInputText(e)}async syncActiveInputText(){this.activeInput&&await this.recordInputText(this.activeInput)}async recordInputText(e){try{let t=await this.driver.getUiHierarchy(this.targetSerial).catch(()=>null);if(!t)return;let{flat:s}=ue(t);this.lastHierarchyFlat=s;let i=s.find(n=>n.className.includes("EditText")&&(n.focused||n.selected))||s.find(n=>n.className.includes("EditText")&&this.resolveFieldLabel(n,s).toLowerCase()===e.label.toLowerCase())||s.find(n=>n.className.includes("EditText")&&Math.abs(n.bounds.centerX-e.node.bounds.centerX)<80)||s.find(n=>n.className.includes("EditText"));if(i&&i.text&&i.text.trim().length>0){let n=i.text.trim(),r=/^[•*•\u2022\u25cf]+$/.test(n);if(!(n===e.startText)&&!r){if(e.startText===""&&this.isPlaceholderText(n))return;let a=e.label||this.resolveFieldLabel(i,s),l=`Type '${n}' into '${a}'`,c=this.recordedSteps.length-1,p=c>=0?this.recordedSteps[c]:"";p.startsWith("Type ")&&p.endsWith(`into '${a}'`)?p!==l&&(this.recordedSteps[c]=l,console.log(D.gray(` \u270D\uFE0F Updated Input [Step #${c+1+this.existingSteps.length}]: ${D.bold(l)}`))):(this.recordedSteps.push(l),console.log(D.green(` \u270D\uFE0F Recorded Input [Step #${this.getCurrentStepNumber()-1}]: ${D.bold(l)}`)))}else if(r&&(i.password||e.label.toLowerCase().includes("password"))){let a=e.label||"Password",l=`Type '<password>' into '${a}'`,c=this.recordedSteps.length-1,p=c>=0?this.recordedSteps[c]:"";(!p.startsWith("Type ")||!p.endsWith(`into '${a}'`))&&(this.recordedSteps.push(l),console.log(D.green(` \u270D\uFE0F Recorded Password Input [Step #${this.getCurrentStepNumber()-1}]: ${D.bold(l)}`)))}}}catch{}}startLogcatScreenWatcher(e){try{this.logcatEventProcess=this.driver.streamLogcatEvents(e,t=>{if(this.isRecording&&(t.includes("wm_on_resume_called")||t.includes("am_on_resume_called"))){let s=Date.now();if(s-this.lastScreenTransitionTime<500)return;this.lastScreenTransitionTime=s,this.hierarchyStale=!0,this.triggerAsyncHierarchyRefresh(50)}})}catch{}}startLogcatCrashWatcher(e){try{this.logcatCrashProcess=this.driver.streamLogcatCrashes(e,t=>{if(this.isRecording&&(t.includes("FATAL EXCEPTION")||t.includes("ANR in"))){if(this.targetPackage&&!t.includes(this.targetPackage))return;this.crashDetected=!0,console.log(D.red.bold(`
764
- \u26A0\uFE0F [Crash Alert] Fatal exception / ANR detected in ${this.targetPackage||"app"}!`))}})}catch{}}captureSessionScreenshot(e){if(!this.screenshotDir)return;let t=++this.screenshotCounter,s=e.toLowerCase().replace(/[^a-z0-9_]/g,"_").slice(0,30)||"screen",i=`screen_${String(t).padStart(2,"0")}_${s}.png`,n=re.join(this.screenshotDir,i);(async()=>{try{let r=await this.driver.captureScreenshot(this.targetSerial);if(r&&r.length>0){await de.promises.writeFile(n,r);let o=this.sessionScreenSections[this.sessionScreenSections.length-1];o&&!o.screenshotFile&&(o.screenshotFile=i)}}catch{}})()}triggerAsyncHierarchyRefresh(e=T.recorder.asyncRefreshDelayMs){this.isRefreshingHierarchy||(this.isRefreshingHierarchy=!0,setTimeout(()=>{this.doHierarchyRefresh().catch(()=>{this.isRefreshingHierarchy=!1})},e))}async doHierarchyRefresh(){try{let e=await this.driver.getUiHierarchy(this.targetSerial),{flat:t}=ue(e);this.lastHierarchyFlat=t,this.hierarchyStale=!1,this.hierarchyCacheTime=Date.now(),this.detectAndLogScreenHeader(t),this.detectAndLogTransientAlerts(t)}catch{}finally{for(this.isRefreshingHierarchy=!1;this.inFlightTapQueue.length>0;){let e=this.inFlightTapQueue.shift();if(!e)break;Date.now()-e.timestamp<T.recorder.staleTapTimeoutMs?this.handleTapAt(e.x,e.y):console.warn(D.yellow(`[Recorder] Dropped stale tap at (${e.x}, ${e.y}) \u2014 screen refresh took longer than ${T.recorder.staleTapTimeoutMs}ms`))}}}detectAndLogTransientAlerts(e){let t=e.find(s=>(s.className.includes("Toast")||s.className.includes("Snackbar")||s.resourceId&&s.resourceId.includes("snackbar")||s.contentDesc&&(s.contentDesc.includes("Alert")||s.contentDesc.includes("Success")))&&(s.text||s.contentDesc));if(t){let s=this.cleanLabel(t.text)||this.cleanLabel(t.contentDesc);if(s&&s.length>3&&s.length<80){let i=`Verify '${s}' is visible`;this.recordedSteps.slice(-3).includes(i)||(this.recordedSteps.push(i),console.log(D.green(` \u2714 Recorded Alert [Step #${this.getCurrentStepNumber()-1}]: ${D.bold(i)}`)))}}}async refreshHierarchySync(){try{let e=await this.driver.getUiHierarchy(this.targetSerial),{flat:t}=ue(e);this.lastHierarchyFlat=t,this.hierarchyStale=!1,this.hierarchyCacheTime=Date.now(),this.detectAndLogScreenHeader(t)}catch{}}isIconGlyph(e){if(!e||e.trim().length===0)return!0;let t=e.trim();return!!(/[\uE000-\uF8FF\uFFF0-\uFFFF]/.test(t)||t.length===1&&t.charCodeAt(0)>255&&!new RegExp("\\p{Extended_Pictographic}","u").test(t))}cleanDialogOrCompoundLabel(e){if(!e)return"";let t=e.trim();if(t.includes(",")||t.includes(`
765
- `)){let s=t.split(/[\n,]+/).map(i=>this.cleanLabel(i)).filter(Boolean);if(s.length>1){let i=s.find(r=>r.includes("?")||/\b(are you sure|do you want|cannot be undone|would you like|please confirm)\b/i.test(r)||r.length>35);if(i){let r=s.find(o=>o!==i&&o.length<=30&&!o.includes("?"));if(r)return r}let n=s.filter(r=>/^[A-Z]{1,3}$/.test(r)||/^\d+%?$/.test(r)||this.isCardMetadataSubtitle(r)||/^(attend|present|absent|status|active|inactive)$/i.test(r)?!1:r.length>1);if(n.length>0)return n[0]}}return t}isCardMetadataSubtitle(e){if(!e||e.trim().length===0)return!1;let t=e.trim();return!!(/\+?\d{1,3}[\s-]?\d{4,}[\s-]?\d{4,}/.test(t)||/^(STD|ID|EMP|REF|ORD|USER|ACC|BATCH)[\-_:\s]?\d+/i.test(t)||/[•|·]/.test(t)&&/\d/.test(t)||/^\d+$/.test(t)||/^\d{1,2}:\d{2}/.test(t)||/^(teacher|roll\s*no|std\s*id|class|sec)[\s:]+/i.test(t))}findPrimaryCardTitle(e,t,s){if(e.bounds.y1>=this.displayHeight*.8||e.bounds.centerY>=this.displayHeight*.82||e.clickable&&(e.className.includes("Button")||e.className.includes("Check")))return null;let i=this.cleanLabel(e.text),n=this.isCardMetadataSubtitle(i),r=s.find(l=>l!==e&&l.clickable&&l.bounds.height>60&&l.bounds.height<600),o;r?o=t.filter(l=>l.className.includes("Text")&&l.bounds.x1>=r.bounds.x1-10&&l.bounds.x2<=r.bounds.x2+10&&l.bounds.y1>=r.bounds.y1-10&&l.bounds.y2<=r.bounds.y2+10):o=t.filter(l=>l!==e&&l.className.includes("Text")&&l.bounds.centerY<e.bounds.centerY&&e.bounds.centerY-l.bounds.centerY<160&&Math.abs(l.bounds.centerX-e.bounds.centerX)<500);let a=o.filter(l=>{let c=this.cleanLabel(l.text);return c.length>2&&!this.isCardMetadataSubtitle(c)&&!this.isIconGlyph(c)&&!/^\d+$/.test(c)&&!/^(active|inactive|present|absent|new|pending)$/i.test(c)}).sort((l,c)=>l.bounds.y1-c.bounds.y1);if(a.length>0){let l=this.cleanLabel(a[0].text);if(n||r&&l!==i&&!e.clickable)return l}return null}resolveActionLabel(e,t,s){if(e.bounds.y1>=this.displayHeight*.8||e.bounds.centerY>=this.displayHeight*.82){let l=this.cleanLabel(e.contentDesc)||this.cleanLabel(e.text);if(l&&l.length>0&&!this.isIconGlyph(l))return this.cleanDialogOrCompoundLabel(l);for(let c of t){let p=this.cleanLabel(c.contentDesc)||this.cleanLabel(c.text);if(p&&p.length>0&&!this.isIconGlyph(p))return this.cleanDialogOrCompoundLabel(p)}}let i=this.findPrimaryCardTitle(e,s,t);if(i)return this.cleanDialogOrCompoundLabel(i);let n=this.cleanLabel(e.text);if(n.length>0&&n.length<90){let l=n.split(/[\n\r]+/).map(p=>this.cleanLabel(p)).filter(Boolean),c=l.length>1?l.find(p=>p.length>2&&!/^\d+$/.test(p))||l[0]:n;return this.cleanDialogOrCompoundLabel(c)}let r=this.cleanLabel(e.contentDesc);if(r.length>0&&r.length<90)return this.cleanDialogOrCompoundLabel(r);let o=t.find(l=>(l.clickable||l.className.includes("Button"))&&(this.cleanLabel(l.text)||this.cleanLabel(l.contentDesc)));if(o){let l=this.cleanLabel(o.text)||this.cleanLabel(o.contentDesc);if(l.length>0&&l.length<90)return this.cleanDialogOrCompoundLabel(l)}for(let l of t){let c=this.cleanLabel(l.text);if(c.length>0&&c.length<90){let h=c.split(/[\n\r]+/).map(g=>this.cleanLabel(g)).filter(Boolean),d=h.length>1?h.find(g=>g.length>2&&!/^\d+$/.test(g))||h[0]:c;return this.cleanDialogOrCompoundLabel(d)}let p=this.cleanLabel(l.contentDesc);if(p.length>0&&p.length<90)return this.cleanDialogOrCompoundLabel(p)}let a=s.find(l=>l!==e&&(this.cleanLabel(l.text).length>0||this.cleanLabel(l.contentDesc).length>0)&&Math.abs(l.bounds.centerX-e.bounds.centerX)<80&&Math.abs(l.bounds.centerY-e.bounds.centerY)<100);if(a){let l=this.cleanLabel(a.text)||this.cleanLabel(a.contentDesc);if(l.length>0)return this.cleanDialogOrCompoundLabel(l)}if(e.resourceId){let l=e.resourceId.split("/"),c=l[l.length-1];if(c&&!/^\d+$/.test(c)){let p=c.replace(/_/g," ").replace(/btn|button|icon|view|action/gi,"").trim();if(p.length>1)return p.charAt(0).toUpperCase()+p.slice(1)}}return""}getCurrentStepNumber(){return this.existingSteps.length+this.recordedSteps.length+1}detectAndLogScreenHeader(e){let t=e.filter(s=>{if(!s.className.includes("TextView")||s.text.trim().length<2||s.packageName&&(s.packageName.includes("systemui")||s.packageName.includes("launcher"))||s.bounds.y1<60||s.bounds.y1>=450)return!1;let i=s.text.trim();return!(this.isCardMetadataSubtitle(i)||/\b(JIO|Airtel|Vodafone|No service|Emergency|VoLTE|4G|5G)\b/i.test(i)||/^\d+%?$|^\d+$/.test(i)||/^step\s*\d+\s*(of|\/)\s*\d+/i.test(i))}).sort((s,i)=>s.bounds.y1-i.bounds.y1);if(t.length>0){let s=t[0].text.trim();if(s&&s!==this.lastScreenTitle&&!s.includes(":")&&s.length<40){this.lastScreenTitle=s,this.currentScreenName=s,this.visitedScreens.includes(s)||this.visitedScreens.push(s),this.sessionScreenSections.push({name:s,stepStart:this.recordedSteps.length}),this.captureSessionScreenshot(s);let i=`Verify '${s}' is visible`;this.recordedSteps[this.recordedSteps.length-1]!==i&&!this.recordedSteps.slice(-3).includes(i)&&(this.recordedSteps.push(i),console.log(D.green(` \u2714 Recorded Header [Step #${this.getCurrentStepNumber()-1}]: ${D.bold(i)}`)))}}}resolveFieldLabel(e,t){if(e.contentDesc&&e.contentDesc.trim().length>0)return e.contentDesc.trim();if(e.password)return"Password";let s=t.filter(i=>i.className.includes("TextView")&&i.text&&i.text.trim().length>1&&i.bounds.centerY<e.bounds.centerY&&e.bounds.centerY-i.bounds.centerY<250&&Math.abs(i.bounds.centerX-e.bounds.centerX)<450);if(s.length>0){s.sort((n,r)=>r.bounds.centerY-n.bounds.centerY);let i=s[0].text.trim().replace(/[*:]/g,"").trim();if(i.length>0)return i}if(e.resourceId){let i=e.resourceId.split("/"),n=i[i.length-1];if(n&&!/^\d+$/.test(n)){let r=n.replace(/_/g," ").replace(/edit|text|input|field|et|txt/gi,"").trim();return r.length>1?r.charAt(0).toUpperCase()+r.slice(1):n}}if(e.text&&e.text.trim().length>0&&e.text.trim().length<40){let i=e.text.trim();if(i.toLowerCase().startsWith("search"))return i.length<=25?i:"Search";if(!this.isPlaceholderText(i))return i}return"Input Field"}isPlaceholderText(e){let t=e.trim().toLowerCase();return t.startsWith("search")||t.startsWith("e.g.")||t.startsWith("enter ")||t.startsWith("type ")||t.includes("optional")}saveSpec(e){let t=re.resolve(e);if(re.basename(t).startsWith("app_flow")&&this.targetPackage&&!this.isAppendMode){let a=this.extractBrandSlug(this.targetPackage);if(a!=="app"){let l=`${a}_flow`,c=re.resolve(`specs/${l}.txt`),p=1;for(;de.existsSync(c);)c=re.resolve(`specs/${l}_${p}.txt`),p++;t=c}}let i=re.dirname(t);de.existsSync(i)||de.mkdirSync(i,{recursive:!0});let n=[];if(this.isAppendMode&&this.existingSteps.length>0&&de.existsSync(t)){let a=de.readFileSync(t,"utf-8").trim();n.push(a),n.push(""),n.push(`# --- Appended Session (${new Date().toISOString().replace("T"," ").slice(0,19)}) ---`),this.recordedSteps.forEach((l,c)=>{n.push(`${this.existingSteps.length+c+1}. ${l}`)})}else{n.push("# ==========================================================",`# Autonomous Recorded Test Spec: ${re.basename(t)}`,...this.targetPackage?[`# Package: ${this.targetPackage}`]:[],`# Generated: ${new Date().toISOString()}`,`# PromptTest v${Es}`,"# ==========================================================","");let a=0;this.recordedSteps.forEach((l,c)=>{if(a<this.sessionScreenSections.length&&c===this.sessionScreenSections[a].stepStart){let p=this.sessionScreenSections[a];n.push(""),n.push(`# Screen: ${p.name}`),a++}n.push(`${this.existingSteps.length+c+1}. ${l}`)})}n.push("");let r=n.join(`
766
- `),o=`${t}.tmp.${Date.now()}`;try{de.writeFileSync(o,r,"utf-8"),de.renameSync(o,t)}catch{try{de.unlinkSync(o)}catch{}de.writeFileSync(t,r,"utf-8")}}saveReport(e){let t=Math.round((Date.now()-this.sessionStartTime)/1e3),s=Math.floor(t/60),i=t%60,n=`${String(s).padStart(2,"0")}:${String(i).padStart(2,"0")}`,r=this.existingSteps.length+this.recordedSteps.length,o=["# PromptTest Recording Report","","| Property | Value |","|---|---|",`| **Target Package** | \`${this.targetPackage||"Unknown"}\` |`,`| **Device Serial** | \`${this.targetSerial}\` |`,`| **Session Started** | ${new Date(this.sessionStartTime).toISOString()} |`,`| **Session Duration** | ${n} |`,`| **Steps in Session** | ${this.recordedSteps.length} |`,`| **Total Suite Steps** | ${r} |`,`| **Screens Visited** | ${this.visitedScreens.length} |`,`| **Screenshots Saved** | ${this.screenshotCounter} |`,`| **Crash Signals** | ${this.crashDetected?"\u26A0\uFE0F Detected":"\u2705 None"} |`,"","---","","## Screen Journey","",this.visitedScreens.length>0?this.visitedScreens.map((a,l)=>`${l+1}. **${a}**`).join(`
767
- `):"*Single screen flow*","","---","","## Recorded Interactions",""];if(this.sessionScreenSections.length>0)for(let a=0;a<this.sessionScreenSections.length;a++){let l=this.sessionScreenSections[a],c=this.sessionScreenSections[a+1],p=c?c.stepStart:this.recordedSteps.length,h=this.recordedSteps.slice(l.stepStart,p);o.push(`### Screen: ${l.name}`),o.push(""),l.screenshotFile&&(o.push(`![${l.name}](screenshots/${re.basename(this.screenshotDir)}/${l.screenshotFile})`),o.push("")),h.length>0?h.forEach((d,g)=>{o.push(`${l.stepStart+g+1}. \`${d}\``)}):o.push("*(No interactions on this screen)*"),o.push("")}else o.push("### Steps"),o.push(""),this.recordedSteps.forEach((a,l)=>{o.push(`${l+1}. \`${a}\``)}),o.push("");try{let a=re.dirname(e);de.existsSync(a)||de.mkdirSync(a,{recursive:!0}),de.writeFileSync(e,o.join(`
758
+ `))}finally{f&&ze(f)}}async runErrorSentinel(e,t,s){let i=[];try{let[n,r]=await Promise.all([this.driver.checkCrashes(e,t),this.driver.getUiHierarchy(t)]);if(n){let d=`Crash in ${s}: ${n.slice(0,300)}`;console.log(P.bold.red(`\u{1F6A8} FATAL EXCEPTION DETECTED in ${e} [${s}]!`)),this.reporter.logError(d),i.push(d)}let{flat:o}=ue(r),a=_s(o);if(a.length>0)for(let d of a){let c=d.text||d.contentDesc,l=`UI Error dialog in ${s}: "${c}"`;console.log(P.bold.yellow(`\u26A0\uFE0F Error Dialog/Banner on screen [${s}]: "${c}"`)),this.reporter.logError(l),i.push(l)}}catch{}return{hasError:i.length>0,errors:i}}},No=new ut;import de from"fs";import re from"path";import $ from"chalk";import{spawn as _i}from"child_process";import ni from"readline";import{createRequire as Oi}from"module";var Bi=Oi(import.meta.url),Es="1.1.0";try{Es=Bi("../../package.json").version||"1.1.0"}catch{}var pt=class{driver;deviceLock=null;isRecording=!1;recordedSteps=[];existingSteps=[];existingFileHeader=[];lastHierarchyFlat=[];lastScreenTitle="";visitedScreens=[];targetPackage=null;isAppendMode=!1;resolvedOutputPath="";resolvedReportPath="";activeInput=null;geteventProcess=null;isRefreshingHierarchy=!1;targetSerial="";touchMaxX=E.screen.fallbackWidth;touchMaxY=E.screen.fallbackHeight;displayWidth=E.screen.fallbackWidth;displayHeight=E.screen.fallbackHeight;activeTouchX=-1;activeTouchY=-1;touchDownTime=0;isTouchActive=!1;isSwipeGesture=!1;lastHierarchyTimestamp=0;lastTapTimestamp=0;lastRecordedTapTarget="";inFlightTapQueue=[];inputDebounceTimer=null;logcatEventProcess=null;logcatCrashProcess=null;hierarchyCacheTime=0;hierarchyStale=!0;lastScrollTimestamp=0;lastScrollDirection="";currentScreenName="";sessionScreenSections=[];sessionStartTime=0;screenshotDir="";screenshotCounter=0;crashDetected=!1;lastScreenTransitionTime=0;constructor(e){this.driver=e||he}flushToDisk(){if(this.resolvedOutputPath)try{this.saveSpec(this.resolvedOutputPath)}catch{}if(this.resolvedReportPath)try{this.saveReport(this.resolvedReportPath)}catch{}}appendStep(e,t){this.recordedSteps[this.recordedSteps.length-1]!==e&&(this.recordedSteps.push(e),this.flushToDisk(),t&&console.log(t))}extractBrandSlug(e){if(!e)return"app";let t=new Set(["com","org","net","io","in","co","uk","de","fr","us","ai","dev","android","mobile","app","apps","client","release","debug","main","browser","ui","view","experience","portal","phone","tablet","service"]),s=e.split("."),i=s.filter(r=>!t.has(r.toLowerCase())&&!/^\d+$/.test(r));return((i.length>0?i[i.length-1]:s[s.length-1])||"app").toLowerCase().replace(/[^a-z0-9_]/g,"")}async startRecording(e,t,s){let i=await this.driver.ensureDefaultDevice(t);if(!i)throw new Error("No Android device connected for recording.");this.deviceLock=Ke(i),this.targetSerial=i,this.isRecording=!0,this.recordedSteps=[],this.existingSteps=[],this.existingFileHeader=[],this.visitedScreens=[],this.targetPackage=null,this.activeInput=null,this.isAppendMode=!!s?.append;try{let v=await this.driver.getForegroundPackage(i);v&&(this.targetPackage=v)}catch{}let n=this.extractBrandSlug(this.targetPackage),r;if(e&&e!=="specs/recorded_suite.txt")r=re.resolve(e);else{let v=`${n}_flow`,x=re.resolve(`specs/${v}.txt`);if(!this.isAppendMode&&de.existsSync(x)){let D=1;for(x=re.resolve(`specs/${v}_${D}.txt`);de.existsSync(x);)D++,x=re.resolve(`specs/${v}_${D}.txt`)}r=x}if(this.resolvedOutputPath=r,de.existsSync(r))if(this.isAppendMode){let v=de.readFileSync(r,"utf-8"),x=v.split(`
759
+ `);for(let w of x){let A=w.trim();if(/^\d+\.\s+/.test(A))this.existingSteps.push(A.replace(/^\d+\.\s+/,""));else if(A.startsWith("# Package:")){let B=A.match(/# Package:\s*([a-zA-Z0-9._]+)/);B&&(this.targetPackage=B[1])}}let D=`${r}.bak`;de.writeFileSync(D,v,"utf-8"),console.log($.cyan(`\u{1F4E5} Loaded ${this.existingSteps.length} existing step(s) from: ${re.basename(r)}`)),console.log($.gray(`\u{1F4E6} Safety backup preserved at: ${re.basename(D)}`))}else{let v=de.readFileSync(r,"utf-8"),x=`${r}.bak`;de.writeFileSync(x,v,"utf-8"),console.log($.yellow(`\u26A0\uFE0F File "${re.basename(r)}" already exists.`)),console.log($.gray(`\u{1F4E6} Safety backup preserved at: ${re.basename(x)}`))}await this.driver.wakeDevice(i).catch(()=>{});let a=await this.driver.getScreenDimensions(i);this.displayWidth=a.width||E.screen.fallbackWidth,this.displayHeight=a.height||E.screen.fallbackHeight,this.touchMaxX=this.displayWidth,this.touchMaxY=this.displayHeight;try{let{stdout:v}=await this.driver.execAdb(["shell","getevent","-p"],i),x=v.match(/0035\s*:\s*value\s*\d+,\s*min\s*\d+,\s*max\s*(\d+)/),D=v.match(/0036\s*:\s*value\s*\d+,\s*min\s*\d+,\s*max\s*(\d+)/);x&&parseInt(x[1])>0&&(this.touchMaxX=parseInt(x[1])),D&&parseInt(D[1])>0&&(this.touchMaxY=parseInt(D[1]))}catch{}this.sessionStartTime=Date.now(),this.sessionScreenSections=[],this.screenshotCounter=0,this.crashDetected=!1,this.hierarchyStale=!0,this.currentScreenName="";let d=re.basename(r,".txt"),c=re.resolve("output");this.screenshotDir=re.join(c,"screenshots",d),de.existsSync(this.screenshotDir)||de.mkdirSync(this.screenshotDir,{recursive:!0});let l=$.gray("\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501"),h=await this.driver.getDeviceModel(i).catch(()=>i);console.log(`
760
+ ${l}`),console.log($.bold.cyan(`\u26A1 PromptTest v${Es}`)+$.gray(" | Recording Session")),console.log(l),console.log(` ${$.gray("\u{1F4F1} Device ")} ${$.white(h)} ${$.gray(`(${i})`)}`),console.log(` ${$.gray("\u{1F4E6} App ")} ${$.green(this.targetPackage||"Unknown")}`),console.log(` ${$.gray("\u{1F3AF} Spec ")} ${$.yellow(re.basename(r))}`);let u=re.join(c,`${d}_report.md`);this.resolvedReportPath=u,console.log(` ${$.gray("\u{1F4CA} Report ")} ${$.yellow(re.basename(u))}`),console.log(` ${$.gray("\u{1F4F8} Photos ")} ${$.yellow(re.relative(process.cwd(),this.screenshotDir))}`),this.isAppendMode&&this.existingSteps.length>0&&console.log(` ${$.gray("\u{1F4CE} Mode ")} ${$.magenta(`Append \u2014 resuming from step #${this.existingSteps.length+1}`)}`),console.log(l),process.stdout.write(` ${$.gray("Checking device health...")} `),console.log($.green("\u2714 Ready")),process.stdout.write(` ${$.gray("Loading initial screen...")} `);let g=Date.now();await this.refreshHierarchySync();let f=Date.now()-g,y=this.currentScreenName?$.bold.white(this.currentScreenName):$.gray("Unknown");console.log(`${$.green("\u2714")} ${y} ${$.gray(`[${f}ms]`)}`),process.stdout.write(` ${$.gray("Starting screen watcher...")} `),this.startLogcatScreenWatcher(i),this.startLogcatCrashWatcher(i),console.log($.green("\u2714 Streaming")),console.log(l),console.log(` ${$.gray("Use the app naturally. Every action is captured.")}`),console.log(` ${$.gray('Press Ctrl+C or type "exit" / "q" + Enter to stop and save.')}`),console.log(`${l}
761
+ `),this.flushToDisk();let S=null,b=()=>{if(this.isRecording=!1,S)try{S.close()}catch{}if(this.inputDebounceTimer&&(clearTimeout(this.inputDebounceTimer),this.inputDebounceTimer=null),this.deviceLock&&(ze(this.deviceLock),this.deviceLock=null),this.geteventProcess)try{this.geteventProcess.kill()}catch{}if(this.logcatEventProcess)try{this.logcatEventProcess.kill()}catch{}if(this.logcatCrashProcess)try{this.logcatCrashProcess.kill()}catch{}this.flushToDisk(),this.printExitSummary(l),process.exit(0)};if(process.once("SIGINT",b),process.once("SIGTERM",b),process.stdin.isTTY)try{S=ni.createInterface({input:process.stdin,output:process.stdout}),S.on("line",v=>{let x=v.trim().toLowerCase();(x==="exit"||x==="quit"||x==="q"||x==="stop")&&b()}),S.on("SIGINT",()=>{b()})}catch{}this.startEventStream(i);let m=0;for(;this.isRecording;)if(await new Promise(v=>setTimeout(v,1500)),m++,m%20===0&&this.driver.wakeDevice(i).catch(()=>{}),!this.targetPackage){let v=await this.driver.getForegroundPackage(i).catch(()=>null);v&&(this.targetPackage=v)}}startEventStream(e){let s=_i("adb",e?["-s",e,"shell","getevent","-l"]:["shell","getevent","-l"]);this.geteventProcess=s;let i=null,n=null,r=null,o=null,a=0;ni.createInterface({input:s.stdout}).on("line",c=>{if(this.isRecording)if(c.includes("ABS_MT_POSITION_X")){let l=c.match(/ABS_MT_POSITION_X\s+([0-9a-fA-F]+)/);l&&(i=parseInt(l[1],16))}else if(c.includes("ABS_MT_POSITION_Y")){let l=c.match(/ABS_MT_POSITION_Y\s+([0-9a-fA-F]+)/);l&&(n=parseInt(l[1],16))}else if(c.includes("BTN_TOUCH")&&c.includes("DOWN"))r=i,o=n,a=Date.now();else if(c.includes("BTN_TOUCH")&&c.includes("UP")){let l=i!==null?i:r,h=n!==null?n:o,u=Date.now()-a;if(l!==null&&h!==null&&r!==null&&o!==null){let g=Math.round(r/this.touchMaxX*this.displayWidth),f=Math.round(o/this.touchMaxY*this.displayHeight),y=Math.round(l/this.touchMaxX*this.displayWidth),S=Math.round(h/this.touchMaxY*this.displayHeight),b=y-g,m=S-f,v=Math.abs(b),x=Math.abs(m),D=Math.hypot(v,x);if(this.activeInput&&f>this.displayHeight*.58&&S>this.displayHeight*.58){u>=20&&u<400&&D<45&&y>=this.displayWidth*.78&&S>=this.displayHeight*.84?this.flushActiveInput().then(()=>{this.handleKeyPress("Enter")}).catch(()=>{}):this.scheduleInputDebounce(),i=null,n=null,r=null,o=null;return}if(u>=20&&u<400&&D<45)this.isRefreshingHierarchy?this.inFlightTapQueue.push({x:y,y:S,timestamp:Date.now()}):this.handleTapAt(y,S);else if(u>=450&&D<45)this.handleLongPressAt(y,S);else if(x>=100&&x>1.4*v){let w=m<0?"down":"up";this.handleScroll(w)}else if(v>=100&&v>1.4*x){let w=b<0?"left":"right";this.handleSwipe(w)}}i=null,n=null,r=null,o=null}else c.includes("KEY_ENTER")&&c.includes("DOWN")?this.handleKeyPress("Enter"):c.includes("KEY_BACK")&&c.includes("DOWN")&&this.handleKeyPress("Back")}),s.on("close",c=>{this.isRecording&&(console.warn($.yellow(`
762
+ \u26A0\uFE0F [EventStream] ADB event listener stream closed (code ${c}). Auto-reconnecting in 800ms...`)),setTimeout(()=>{this.isRecording&&this.startEventStream(e)},800))}),s.on("error",c=>{this.isRecording&&console.warn($.yellow(`
763
+ \u26A0\uFE0F [EventStream] ADB stream error: ${c.message}.`))})}cleanLabel(e){return e?e.replace(/[\uE000-\uF8FF\uFFF0-\uFFFF\uFFFD]/gu,"").replace(/,\s*tab,\s*\d+\s*of\s*\d+/gi,"").replace(/,\s*button$/gi,"").replace(/^[\s,•\-_:;|/\\]+|[\s,•\-_:;|/\\]+$/g,"").trim():""}handleScroll(e){let t=Date.now();if(this.lastScrollDirection===e&&t-this.lastScrollTimestamp<850)return;this.lastScrollTimestamp=t,this.lastScrollDirection=e,this.activeInput&&this.flushActiveInput().catch(()=>{});let s=`Scroll ${e}`;this.recordedSteps[this.recordedSteps.length-1]!==s&&(this.appendStep(s,$.blue(` \u{1F4DC} Recorded Scroll [Step #${this.getCurrentStepNumber()}]: ${$.bold(s)}`)),this.triggerAsyncHierarchyRefresh(400))}handleSwipe(e){let t=Date.now();if(t-this.lastScrollTimestamp<600)return;this.lastScrollTimestamp=t,this.activeInput&&this.flushActiveInput().catch(()=>{});let s=`Swipe ${e}`;this.appendStep(s,$.blue(` \u{1F449} Recorded Swipe [Step #${this.getCurrentStepNumber()}]: ${$.bold(s)}`)),this.triggerAsyncHierarchyRefresh(500)}handleLongPressAt(e,t){let s=this.lastHierarchyFlat.filter(r=>e>=r.bounds.x1&&e<=r.bounds.x2&&t>=r.bounds.y1&&t<=r.bounds.y2);if(s.length===0)return;s.sort((r,o)=>{let a=(r.bounds.x2-r.bounds.x1)*(r.bounds.y2-r.bounds.y1),d=(o.bounds.x2-o.bounds.x1)*(o.bounds.y2-o.bounds.y1);return a-d});let i=s[0],n=this.resolveActionLabel(i,s,this.lastHierarchyFlat);if(n){let r=`Long press '${n}'`;this.appendStep(r,$.cyan(` \u23F1\uFE0F Recorded Long Press [Step #${this.getCurrentStepNumber()}]: ${$.bold(r)}`)),this.triggerAsyncHierarchyRefresh()}}handleTapAt(e,t){let s=Date.now(),i=this.lastHierarchyFlat.filter(l=>e>=l.bounds.x1&&e<=l.bounds.x2&&t>=l.bounds.y1&&t<=l.bounds.y2),r=this.lastHierarchyFlat.filter(l=>{let h=l.bounds.height;return h>0&&h<320&&l.bounds.width>0&&(l.clickable||l.contentDesc||l.text)}).filter(l=>t>=l.bounds.y1-30&&t<=l.bounds.y2+40);if(r.length>=2){let l=r.find(h=>e>=h.bounds.x1-20&&e<=h.bounds.x2+20);l&&(i=[this.lastHierarchyFlat.find(u=>(this.cleanLabel(u.text).length>0||this.cleanLabel(u.contentDesc).length>0)&&Math.abs(u.bounds.centerX-l.bounds.centerX)<l.bounds.width*.48&&Math.abs(u.bounds.centerY-l.bounds.centerY)<l.bounds.height*.48&&!this.isIconGlyph(this.cleanLabel(u.text)))||l])}if(t>this.displayHeight*.82){let h=this.lastHierarchyFlat.filter(u=>{let g=u.bounds.y1>=this.displayHeight*.78||u.bounds.y2>=this.displayHeight*.82,f=u.bounds.width>0&&u.bounds.width<=this.displayWidth*.52;return g&&f}).find(u=>e>=u.bounds.x1-20&&e<=u.bounds.x2+20);if(h){let u=this.lastHierarchyFlat.find(g=>(this.cleanLabel(g.text).length>0||this.cleanLabel(g.contentDesc).length>0)&&e>=g.bounds.x1-25&&e<=g.bounds.x2+25&&g.bounds.y1>=this.displayHeight*.78&&!this.isIconGlyph(this.cleanLabel(g.text)));u?i=[u]:(this.cleanLabel(h.text)||this.cleanLabel(h.contentDesc))&&(i=[h])}}if(i.length===0){let l=this.lastHierarchyFlat.filter(g=>(this.cleanLabel(g.text).length>0||this.cleanLabel(g.contentDesc).length>0)&&(g.clickable||g.className.includes("Button")||g.className.includes("Text"))),h=null,u=70;for(let g of l){let f=Math.hypot(g.bounds.centerX-e,g.bounds.centerY-t);f<u&&(u=f,h=g)}if(h)i=[h];else{this.triggerAsyncHierarchyRefresh();return}}i.sort((l,h)=>{let u=(l.bounds.x2-l.bounds.x1)*(l.bounds.y2-l.bounds.y1),g=(h.bounds.x2-h.bounds.x1)*(h.bounds.y2-h.bounds.y1);return u-g});let o=i[0],a=i.find(l=>l.className.includes("EditText"))||(o.className.includes("EditText")?o:null);if(a){this.activeInput&&this.activeInput.node!==a&&this.flushActiveInput().catch(()=>{});let l=this.resolveFieldLabel(a,this.lastHierarchyFlat);this.activeInput={node:a,label:l,startText:a.text||""},this.triggerAsyncHierarchyRefresh();return}this.activeInput&&this.flushActiveInput().catch(()=>{});let d=this.resolveActionLabel(o,i,this.lastHierarchyFlat);if(!d||d.length===0){this.triggerAsyncHierarchyRefresh();return}if(!o.clickable&&!i.some(l=>l.clickable||l.className.includes("Button"))&&/^\d+%$|^\d+$/.test(d)){this.triggerAsyncHierarchyRefresh();return}if(d===this.lastRecordedTapTarget&&s-this.lastTapTimestamp<350)return;this.lastTapTimestamp=s,this.lastRecordedTapTarget=d;let c;if(o.checkable||o.className.includes("Switch")||o.className.includes("CheckBox")){let l=o.checked!==void 0?!o.checked:!0;c=`Toggle '${d}' to ${l?"on":"off"}`}else{c=`Tap '${d}'`;let l=this.lastHierarchyFlat.filter(u=>this.cleanLabel(u.text)===d||this.cleanLabel(u.contentDesc)===d),h=[];for(let u of l)h.some(f=>Math.hypot(f.bounds.centerX-u.bounds.centerX,f.bounds.centerY-u.bounds.centerY)<40)||h.push(u);if(h.length>1){let g=this.lastHierarchyFlat.filter(f=>f!==o&&Math.abs(f.bounds.centerY-o.bounds.centerY)<140&&Math.abs(f.bounds.centerX-o.bounds.centerX)<550).find(f=>{let y=this.cleanLabel(f.text)||this.cleanLabel(f.contentDesc);return y.length>2&&y!==d&&!/^\d+$/.test(y)&&!this.isIconGlyph(y)});if(g){let f=this.cleanLabel(g.text)||this.cleanLabel(g.contentDesc);f&&f!==d&&(c=`Tap '${d}' next to '${f}'`)}}}this.appendStep(c,$.cyan(` \u{1F446} Recorded Tap [Step #${this.getCurrentStepNumber()}]: ${$.bold(c)}`)),this.triggerAsyncHierarchyRefresh()}handleKeyPress(e){if(this.activeInput&&this.flushActiveInput().catch(()=>{}),e==="Enter"){let t="Press 'Enter'";this.appendStep(t,$.magenta(` \u21B5 Recorded Key [Step #${this.getCurrentStepNumber()}]: ${$.bold(t)}`))}else if(e==="Back"){let t="Tap 'Back'";this.appendStep(t,$.magenta(` \u25C0 Recorded Key [Step #${this.getCurrentStepNumber()}]: ${$.bold(t)}`))}this.triggerAsyncHierarchyRefresh()}scheduleInputDebounce(){this.inputDebounceTimer&&clearTimeout(this.inputDebounceTimer),this.inputDebounceTimer=setTimeout(()=>{this.activeInput&&this.syncActiveInputText().catch(()=>{})},450)}async flushActiveInput(){if(this.inputDebounceTimer&&(clearTimeout(this.inputDebounceTimer),this.inputDebounceTimer=null),!this.activeInput)return;let e=this.activeInput;this.activeInput=null,await this.recordInputText(e)}async syncActiveInputText(){this.activeInput&&await this.recordInputText(this.activeInput)}async recordInputText(e){try{let t=await this.driver.getUiHierarchy(this.targetSerial).catch(()=>null);if(!t)return;let{flat:s}=ue(t);this.lastHierarchyFlat=s;let i=s.find(n=>n.className.includes("EditText")&&(n.focused||n.selected))||s.find(n=>n.className.includes("EditText")&&this.resolveFieldLabel(n,s).toLowerCase()===e.label.toLowerCase())||s.find(n=>n.className.includes("EditText")&&Math.abs(n.bounds.centerX-e.node.bounds.centerX)<80)||s.find(n=>n.className.includes("EditText"));if(i&&i.text&&i.text.trim().length>0){let n=i.text.trim(),r=/^[•*•\u2022\u25cf]+$/.test(n);if(!(n===e.startText)&&!r){if(e.startText===""&&this.isPlaceholderText(n))return;let a=e.label||this.resolveFieldLabel(i,s),d=`Type '${n}' into '${a}'`,c=this.recordedSteps.length-1,l=c>=0?this.recordedSteps[c]:"";l.startsWith("Type ")&&l.endsWith(`into '${a}'`)?l!==d&&(this.recordedSteps[c]=d,this.flushToDisk(),console.log($.gray(` \u270D\uFE0F Updated Input [Step #${c+1+this.existingSteps.length}]: ${$.bold(d)}`))):this.appendStep(d,$.green(` \u270D\uFE0F Recorded Input [Step #${this.getCurrentStepNumber()}]: ${$.bold(d)}`))}else if(r&&(i.password||e.label.toLowerCase().includes("password"))){let a=e.label||"Password",d=`Type '<password>' into '${a}'`,c=this.recordedSteps.length-1,l=c>=0?this.recordedSteps[c]:"";(!l.startsWith("Type ")||!l.endsWith(`into '${a}'`))&&this.appendStep(d,$.green(` \u270D\uFE0F Recorded Password Input [Step #${this.getCurrentStepNumber()}]: ${$.bold(d)}`))}}}catch{}}startLogcatScreenWatcher(e){try{this.logcatEventProcess=this.driver.streamLogcatEvents(e,t=>{if(this.isRecording&&(t.includes("wm_on_resume_called")||t.includes("am_on_resume_called"))){let s=Date.now();if(s-this.lastScreenTransitionTime<500)return;this.lastScreenTransitionTime=s,this.hierarchyStale=!0,this.triggerAsyncHierarchyRefresh(50)}})}catch{}}startLogcatCrashWatcher(e){try{this.logcatCrashProcess=this.driver.streamLogcatCrashes(e,t=>{if(this.isRecording&&(t.includes("FATAL EXCEPTION")||t.includes("ANR in"))){if(this.targetPackage&&!t.includes(this.targetPackage))return;this.crashDetected=!0,console.log($.red.bold(`
764
+ \u26A0\uFE0F [Crash Alert] Fatal exception / ANR detected in ${this.targetPackage||"app"}!`))}})}catch{}}captureSessionScreenshot(e){if(!this.screenshotDir)return;let t=++this.screenshotCounter,s=e.toLowerCase().replace(/[^a-z0-9_]/g,"_").slice(0,30)||"screen",i=`screen_${String(t).padStart(2,"0")}_${s}.png`,n=re.join(this.screenshotDir,i);(async()=>{try{let r=await this.driver.captureScreenshot(this.targetSerial);if(r&&r.length>0){await de.promises.writeFile(n,r);let o=this.sessionScreenSections[this.sessionScreenSections.length-1];o&&!o.screenshotFile&&(o.screenshotFile=i)}}catch{}})()}triggerAsyncHierarchyRefresh(e=E.recorder.asyncRefreshDelayMs){this.isRefreshingHierarchy||(this.isRefreshingHierarchy=!0,setTimeout(()=>{this.doHierarchyRefresh().catch(()=>{this.isRefreshingHierarchy=!1})},e))}async doHierarchyRefresh(){try{let e=await this.driver.getUiHierarchy(this.targetSerial),{flat:t}=ue(e);this.lastHierarchyFlat=t,this.hierarchyStale=!1,this.hierarchyCacheTime=Date.now(),this.detectAndLogScreenHeader(t),this.detectAndLogTransientAlerts(t)}catch{}finally{for(this.isRefreshingHierarchy=!1;this.inFlightTapQueue.length>0;){let e=this.inFlightTapQueue.shift();if(!e)break;Date.now()-e.timestamp<E.recorder.staleTapTimeoutMs?this.handleTapAt(e.x,e.y):console.warn($.yellow(`[Recorder] Dropped stale tap at (${e.x}, ${e.y}) \u2014 screen refresh took longer than ${E.recorder.staleTapTimeoutMs}ms`))}}}detectAndLogTransientAlerts(e){let t=e.find(s=>(s.className.includes("Toast")||s.className.includes("Snackbar")||s.resourceId&&s.resourceId.includes("snackbar")||s.contentDesc&&(s.contentDesc.includes("Alert")||s.contentDesc.includes("Success")))&&(s.text||s.contentDesc));if(t){let s=this.cleanLabel(t.text)||this.cleanLabel(t.contentDesc);if(s&&s.length>3&&s.length<80){let i=`Verify '${s}' is visible`;this.recordedSteps.slice(-3).includes(i)||this.appendStep(i,$.green(` \u2714 Recorded Alert [Step #${this.getCurrentStepNumber()}]: ${$.bold(i)}`))}}}async refreshHierarchySync(){try{let e=await this.driver.getUiHierarchy(this.targetSerial),{flat:t}=ue(e);this.lastHierarchyFlat=t,this.hierarchyStale=!1,this.hierarchyCacheTime=Date.now(),this.detectAndLogScreenHeader(t)}catch{}}isIconGlyph(e){if(!e||e.trim().length===0)return!0;let t=e.trim();return!!(/[\uE000-\uF8FF\uFFF0-\uFFFF]/.test(t)||t.length===1&&t.charCodeAt(0)>255&&!new RegExp("\\p{Extended_Pictographic}","u").test(t))}cleanDialogOrCompoundLabel(e){if(!e)return"";let t=e.trim();if(t.includes(",")||t.includes(`
765
+ `)){let s=t.split(/[\n,]+/).map(i=>this.cleanLabel(i)).filter(Boolean);if(s.length>1){let i=s.find(r=>r.includes("?")||/\b(are you sure|do you want|cannot be undone|would you like|please confirm)\b/i.test(r)||r.length>35);if(i){let r=s.find(o=>o!==i&&o.length<=30&&!o.includes("?"));if(r)return r}let n=s.filter(r=>/^[A-Z]{1,3}$/.test(r)||/^\d+%?$/.test(r)||this.isCardMetadataSubtitle(r)||/^(attend|present|absent|status|active|inactive)$/i.test(r)?!1:r.length>1);if(n.length>0)return n[0]}}return t}isCardMetadataSubtitle(e){if(!e||e.trim().length===0)return!1;let t=e.trim();return!!(/\+?\d{1,3}[\s-]?\d{4,}[\s-]?\d{4,}/.test(t)||/^(STD|ID|EMP|REF|ORD|USER|ACC|BATCH)[\-_:\s]?\d+/i.test(t)||/[•|·]/.test(t)&&/\d/.test(t)||/^\d+$/.test(t)||/^\d{1,2}:\d{2}/.test(t)||/^(teacher|roll\s*no|std\s*id|class|sec)[\s:]+/i.test(t))}findPrimaryCardTitle(e,t,s){if(e.bounds.y1>=this.displayHeight*.8||e.bounds.centerY>=this.displayHeight*.82||e.clickable&&(e.className.includes("Button")||e.className.includes("Check")))return null;let i=this.cleanLabel(e.text),n=this.isCardMetadataSubtitle(i),r=s.find(d=>d!==e&&d.clickable&&d.bounds.height>60&&d.bounds.height<600),o;r?o=t.filter(d=>d.className.includes("Text")&&d.bounds.x1>=r.bounds.x1-10&&d.bounds.x2<=r.bounds.x2+10&&d.bounds.y1>=r.bounds.y1-10&&d.bounds.y2<=r.bounds.y2+10):o=t.filter(d=>d!==e&&d.className.includes("Text")&&d.bounds.centerY<e.bounds.centerY&&e.bounds.centerY-d.bounds.centerY<160&&Math.abs(d.bounds.centerX-e.bounds.centerX)<500);let a=o.filter(d=>{let c=this.cleanLabel(d.text);return c.length>2&&!this.isCardMetadataSubtitle(c)&&!this.isIconGlyph(c)&&!/^\d+$/.test(c)&&!/^(active|inactive|present|absent|new|pending)$/i.test(c)}).sort((d,c)=>d.bounds.y1-c.bounds.y1);if(a.length>0){let d=this.cleanLabel(a[0].text);if(n||r&&d!==i&&!e.clickable)return d}return null}resolveActionLabel(e,t,s){if(e.bounds.y1>=this.displayHeight*.8||e.bounds.centerY>=this.displayHeight*.82){let d=this.cleanLabel(e.contentDesc)||this.cleanLabel(e.text);if(d&&d.length>0&&!this.isIconGlyph(d))return this.cleanDialogOrCompoundLabel(d);for(let c of t){let l=this.cleanLabel(c.contentDesc)||this.cleanLabel(c.text);if(l&&l.length>0&&!this.isIconGlyph(l))return this.cleanDialogOrCompoundLabel(l)}}let i=this.findPrimaryCardTitle(e,s,t);if(i)return this.cleanDialogOrCompoundLabel(i);let n=this.cleanLabel(e.text);if(n.length>0&&n.length<90){let d=n.split(/[\n\r]+/).map(l=>this.cleanLabel(l)).filter(Boolean),c=d.length>1?d.find(l=>l.length>2&&!/^\d+$/.test(l))||d[0]:n;return this.cleanDialogOrCompoundLabel(c)}let r=this.cleanLabel(e.contentDesc);if(r.length>0&&r.length<90)return this.cleanDialogOrCompoundLabel(r);let o=t.find(d=>(d.clickable||d.className.includes("Button"))&&(this.cleanLabel(d.text)||this.cleanLabel(d.contentDesc)));if(o){let d=this.cleanLabel(o.text)||this.cleanLabel(o.contentDesc);if(d.length>0&&d.length<90)return this.cleanDialogOrCompoundLabel(d)}for(let d of t){let c=this.cleanLabel(d.text);if(c.length>0&&c.length<90){let h=c.split(/[\n\r]+/).map(g=>this.cleanLabel(g)).filter(Boolean),u=h.length>1?h.find(g=>g.length>2&&!/^\d+$/.test(g))||h[0]:c;return this.cleanDialogOrCompoundLabel(u)}let l=this.cleanLabel(d.contentDesc);if(l.length>0&&l.length<90)return this.cleanDialogOrCompoundLabel(l)}let a=s.find(d=>d!==e&&(this.cleanLabel(d.text).length>0||this.cleanLabel(d.contentDesc).length>0)&&Math.abs(d.bounds.centerX-e.bounds.centerX)<80&&Math.abs(d.bounds.centerY-e.bounds.centerY)<100);if(a){let d=this.cleanLabel(a.text)||this.cleanLabel(a.contentDesc);if(d.length>0)return this.cleanDialogOrCompoundLabel(d)}if(e.resourceId){let d=e.resourceId.split("/"),c=d[d.length-1];if(c&&!/^\d+$/.test(c)){let l=c.replace(/_/g," ").replace(/btn|button|icon|view|action/gi,"").trim();if(l.length>1)return l.charAt(0).toUpperCase()+l.slice(1)}}return""}getCurrentStepNumber(){return this.existingSteps.length+this.recordedSteps.length+1}detectAndLogScreenHeader(e){let t=e.filter(s=>{if(!s.className.includes("TextView")||s.text.trim().length<2||s.packageName&&(s.packageName.includes("systemui")||s.packageName.includes("launcher"))||s.bounds.y1<60||s.bounds.y1>=450)return!1;let i=s.text.trim();return!(this.isCardMetadataSubtitle(i)||/\b(JIO|Airtel|Vodafone|No service|Emergency|VoLTE|4G|5G)\b/i.test(i)||/^\d+%?$|^\d+$/.test(i)||/^step\s*\d+\s*(of|\/)\s*\d+/i.test(i))}).sort((s,i)=>s.bounds.y1-i.bounds.y1);if(t.length>0){let s=t[0].text.trim();if(s&&s!==this.lastScreenTitle&&!s.includes(":")&&s.length<40){this.lastScreenTitle=s,this.currentScreenName=s,this.visitedScreens.includes(s)||this.visitedScreens.push(s),this.sessionScreenSections.push({name:s,stepStart:this.recordedSteps.length}),this.captureSessionScreenshot(s);let i=`Verify '${s}' is visible`;this.recordedSteps[this.recordedSteps.length-1]!==i&&!this.recordedSteps.slice(-3).includes(i)&&this.appendStep(i,$.green(` \u2714 Recorded Header [Step #${this.getCurrentStepNumber()}]: ${$.bold(i)}`))}}}resolveFieldLabel(e,t){if(e.contentDesc&&e.contentDesc.trim().length>0)return e.contentDesc.trim();if(e.password)return"Password";let s=t.filter(i=>i.className.includes("TextView")&&i.text&&i.text.trim().length>1&&i.bounds.centerY<e.bounds.centerY&&e.bounds.centerY-i.bounds.centerY<250&&Math.abs(i.bounds.centerX-e.bounds.centerX)<450);if(s.length>0){s.sort((n,r)=>r.bounds.centerY-n.bounds.centerY);let i=s[0].text.trim().replace(/[*:]/g,"").trim();if(i.length>0)return i}if(e.resourceId){let i=e.resourceId.split("/"),n=i[i.length-1];if(n&&!/^\d+$/.test(n)){let r=n.replace(/_/g," ").replace(/edit|text|input|field|et|txt/gi,"").trim();return r.length>1?r.charAt(0).toUpperCase()+r.slice(1):n}}if(e.text&&e.text.trim().length>0&&e.text.trim().length<40){let i=e.text.trim();if(i.toLowerCase().startsWith("search"))return i.length<=25?i:"Search";if(!this.isPlaceholderText(i))return i}return"Input Field"}isPlaceholderText(e){let t=e.trim().toLowerCase();return t.startsWith("search")||t.startsWith("e.g.")||t.startsWith("enter ")||t.startsWith("type ")||t.includes("optional")}saveSpec(e){let t=re.resolve(e);if(re.basename(t).startsWith("app_flow")&&this.targetPackage&&!this.isAppendMode){let a=this.extractBrandSlug(this.targetPackage);if(a!=="app"){let d=`${a}_flow`,c=re.resolve(`specs/${d}.txt`),l=1;for(;de.existsSync(c);)c=re.resolve(`specs/${d}_${l}.txt`),l++;t=c}}let i=re.dirname(t);de.existsSync(i)||de.mkdirSync(i,{recursive:!0});let n=[];if(this.isAppendMode&&this.existingSteps.length>0&&de.existsSync(t)){let a=de.readFileSync(t,"utf-8").trim();n.push(a),n.push(""),n.push(`# --- Appended Session (${new Date().toISOString().replace("T"," ").slice(0,19)}) ---`),this.recordedSteps.forEach((d,c)=>{n.push(`${this.existingSteps.length+c+1}. ${d}`)})}else{n.push("# ==========================================================",`# Autonomous Recorded Test Spec: ${re.basename(t)}`,...this.targetPackage?[`# Package: ${this.targetPackage}`]:[],`# Generated: ${new Date().toISOString()}`,`# PromptTest v${Es}`,"# ==========================================================","");let a=0;this.recordedSteps.forEach((d,c)=>{if(a<this.sessionScreenSections.length&&c===this.sessionScreenSections[a].stepStart){let l=this.sessionScreenSections[a];n.push(""),n.push(`# Screen: ${l.name}`),a++}n.push(`${this.existingSteps.length+c+1}. ${d}`)})}n.push("");let r=n.join(`
766
+ `),o=`${t}.tmp.${Date.now()}`;try{de.writeFileSync(o,r,"utf-8"),de.renameSync(o,t)}catch{try{de.unlinkSync(o)}catch{}de.writeFileSync(t,r,"utf-8")}}saveReport(e){let t=Math.round((Date.now()-this.sessionStartTime)/1e3),s=Math.floor(t/60),i=t%60,n=`${String(s).padStart(2,"0")}:${String(i).padStart(2,"0")}`,r=this.existingSteps.length+this.recordedSteps.length,o=["# PromptTest Recording Report","","| Property | Value |","|---|---|",`| **Target Package** | \`${this.targetPackage||"Unknown"}\` |`,`| **Device Serial** | \`${this.targetSerial}\` |`,`| **Session Started** | ${new Date(this.sessionStartTime).toISOString()} |`,`| **Session Duration** | ${n} |`,`| **Steps in Session** | ${this.recordedSteps.length} |`,`| **Total Suite Steps** | ${r} |`,`| **Screens Visited** | ${this.visitedScreens.length} |`,`| **Screenshots Saved** | ${this.screenshotCounter} |`,`| **Crash Signals** | ${this.crashDetected?"\u26A0\uFE0F Detected":"\u2705 None"} |`,"","---","","## Screen Journey","",this.visitedScreens.length>0?this.visitedScreens.map((a,d)=>`${d+1}. **${a}**`).join(`
767
+ `):"*Single screen flow*","","---","","## Recorded Interactions",""];if(this.sessionScreenSections.length>0)for(let a=0;a<this.sessionScreenSections.length;a++){let d=this.sessionScreenSections[a],c=this.sessionScreenSections[a+1],l=c?c.stepStart:this.recordedSteps.length,h=this.recordedSteps.slice(d.stepStart,l);o.push(`### Screen: ${d.name}`),o.push(""),d.screenshotFile&&(o.push(`![${d.name}](screenshots/${re.basename(this.screenshotDir)}/${d.screenshotFile})`),o.push("")),h.length>0?h.forEach((u,g)=>{o.push(`${d.stepStart+g+1}. \`${u}\``)}):o.push("*(No interactions on this screen)*"),o.push("")}else o.push("### Steps"),o.push(""),this.recordedSteps.forEach((a,d)=>{o.push(`${d+1}. \`${a}\``)}),o.push("");try{let a=re.dirname(e);de.existsSync(a)||de.mkdirSync(a,{recursive:!0}),de.writeFileSync(e,o.join(`
768
768
  `),"utf-8")}catch{}}printExitSummary(e){let t=Math.round((Date.now()-this.sessionStartTime)/1e3),s=Math.floor(t/60),i=t%60,n=`${String(s).padStart(2,"0")}:${String(i).padStart(2,"0")}`,r=this.existingSteps.length+this.recordedSteps.length;console.log(`
769
- ${e}`),console.log(D.bold.green(" \u{1F4BE} Recording Session Saved Successfully!")),console.log(e),console.log(` ${D.gray("Steps Captured ")} ${D.bold.yellow(this.recordedSteps.length.toString())} ${this.isAppendMode?D.gray(`(Total Suite: ${r})`):""}`),console.log(` ${D.gray("Screens Visited")} ${D.bold.white(this.visitedScreens.length.toString())} ${this.visitedScreens.length>0?D.gray(`(${this.visitedScreens.join(" \u2192 ")})`):""}`),console.log(` ${D.gray("Screenshots ")} ${D.bold.white(this.screenshotCounter.toString())} saved`),console.log(` ${D.gray("Session Time ")} ${D.bold.white(n)}`),console.log(` ${D.gray("Crash Signals ")} ${this.crashDetected?D.red.bold("\u26A0\uFE0F Detected"):D.green("\u2714 0 detected")}`),console.log(e),console.log(` ${D.gray("\u{1F4C4} Spec ")} ${D.cyan(this.resolvedOutputPath)}`);let o=re.basename(this.resolvedOutputPath,".txt");console.log(` ${D.gray("\u{1F4CA} Report ")} ${D.cyan(re.resolve("output",`${o}_report.md`))}`),console.log(`${e}
770
- `)}},Jo=new pt;import ni from"fs";import Hi from"path";var vt=null;function Ui(u){return JSON.parse(JSON.stringify(u))}function oi(u,e){for(let t of Object.keys(e)){let s=e[t],i=u[t];s&&typeof s=="object"&&!Array.isArray(s)&&i&&typeof i=="object"?oi(i,s):s!==void 0&&(u[t]=s)}return u}function Yi(u){let e=Ui(T),t=u||Hi.resolve(process.cwd(),"prompttest.config.json");if(ni.existsSync(t))try{let m=ni.readFileSync(t,"utf-8"),v=JSON.parse(m);typeof v=="object"&&v!==null&&oi(e,v)}catch{}let s=process.env.PROMPTTEST_ADB_COMMAND_TIMEOUT_MS||process.env.PROMPTTEST_COMMAND_TIMEOUT_MS;if(s){let m=parseInt(s,10);isNaN(m)||(e.adb.commandTimeoutMs=m)}let i=process.env.PROMPTTEST_POLLING_INTERVAL_MS||process.env.PROMPTTEST_POLL_INTERVAL_MS;if(i){let m=parseInt(i,10);isNaN(m)||(e.polling.intervalMs=m)}let n=process.env.PROMPTTEST_POLLING_DEFAULT_TIMEOUT_MS||process.env.PROMPTTEST_DEFAULT_TIMEOUT_MS;if(n){let m=parseInt(n,10);isNaN(m)||(e.polling.defaultTimeoutMs=m)}let r=process.env.PROMPTTEST_SCREEN_FALLBACK_WIDTH||process.env.PROMPTTEST_FALLBACK_WIDTH;if(r){let m=parseInt(r,10);isNaN(m)||(e.screen.fallbackWidth=m)}let o=process.env.PROMPTTEST_SCREEN_FALLBACK_HEIGHT||process.env.PROMPTTEST_FALLBACK_HEIGHT;if(o){let m=parseInt(o,10);isNaN(m)||(e.screen.fallbackHeight=m)}let a=process.env.PROMPTTEST_VISUAL_OVERLAP_RATIO||process.env.PROMPTTEST_OVERLAP_RATIO;if(a){let m=parseFloat(a);isNaN(m)||(e.visual.overlapRatio=m)}let l=process.env.PROMPTTEST_DEVICE_MAX_DEVICE_RETRIES||process.env.PROMPTTEST_MAX_DEVICE_RETRIES;if(l){let m=parseInt(l,10);isNaN(m)||(e.device.maxDeviceRetries=m)}let c=process.env.PROMPTTEST_DEVICE_AUTO_RECONNECT??process.env.PROMPTTEST_AUTO_RECONNECT;c!==void 0&&(e.device.autoReconnect=c.toLowerCase()!=="false");let p=process.env.PROMPTTEST_GESTURES_SWIPE_DURATION_MS||process.env.PROMPTTEST_SWIPE_DURATION_MS;if(p){let m=parseInt(p,10);isNaN(m)||(e.gestures.swipeDurationMs=m)}let h=process.env.PROMPTTEST_FLOW_MAX_LOOP_ITERATIONS||process.env.PROMPTTEST_MAX_LOOP_ITERATIONS;if(h){let m=parseInt(h,10);isNaN(m)||(e.flow.maxLoopIterations=m)}let d=process.env.PROMPTTEST_AI_PROVIDER;d&&["heuristic","openai","anthropic","ollama","mock"].includes(d)&&(e.ai.provider=d);let g=process.env.PROMPTTEST_AI_MODEL;g&&(e.ai.model=g);let f=process.env.PROMPTTEST_SELF_HEALING;f!==void 0&&(e.ai.selfHealing=f.toLowerCase()!=="false");let y=process.env.PROMPTTEST_CONFIDENCE_THRESHOLD;if(y){let m=parseFloat(y);isNaN(m)||(e.ai.confidenceThreshold=m)}let S=process.env.PROMPTTEST_AI_ENDPOINT;S&&(e.ai.endpoint=S);let b=process.env.PROMPTTEST_LOCALE;return b&&(e.locale=b.toLowerCase()),vt=e,e}function ta(){return vt||(vt=Yi()),vt}function sa(){vt=null}import xe from"chalk";function ai(u,e){if(u.length===0)return 0;let t=[...u].sort((i,n)=>i-n),s=Math.min(t.length-1,Math.max(0,Math.floor(e/100*(t.length-1))));return Math.round(t[s]*100)/100}function Ps(u){if(u.length===0)return{minMs:0,maxMs:0,avgMs:0,p50Ms:0,p95Ms:0,iterations:0,durations:[]};let e=Math.round(Math.min(...u)*100)/100,t=Math.round(Math.max(...u)*100)/100,s=u.reduce((o,a)=>o+a,0),i=Math.round(s/u.length*100)/100,n=ai(u,50),r=ai(u,95);return{minMs:e,maxMs:t,avgMs:i,p50Ms:n,p95Ms:r,iterations:u.length,durations:u}}function ji(u=1e3){let e=[];e.push({index:0,className:"android.widget.FrameLayout",packageName:"com.app",text:"",resourceId:"android:id/content",contentDesc:"Main Screen Root",clickable:!1,enabled:!0,focused:!1,scrollable:!1,password:!1,selected:!1,children:[],bounds:{x1:0,y1:0,x2:1080,y2:2400,width:1080,height:2400,centerX:540,centerY:1200}}),e.push({index:1,className:"android.widget.TextView",packageName:"com.app",text:"Apex Coaching Academy - Dashboard",resourceId:"com.app:id/title_header",contentDesc:"Header Title",clickable:!1,enabled:!0,focused:!1,scrollable:!1,password:!1,selected:!1,children:[],bounds:{x1:40,y1:100,x2:1040,y2:220,width:1e3,height:120,centerX:540,centerY:160}});let t=["android.widget.TextView","android.widget.Button","android.widget.EditText","android.widget.ImageView","android.view.ViewGroup","android.widget.LinearLayout","android.widget.CheckBox","android.widget.Switch"],s=["Sign In","Email Address","Password","Submit","Save Changes","Settings","Profile","Notifications","Batch 10A","Mathematics","Physics","Attendance","Export PDF","Delete Record","Cancel","Next","Back","Search","Filter","Refresh"];for(let i=2;i<u;i++){let n=t[i%t.length],r=n.includes("Button")||n.includes("CheckBox")||n.includes("Switch"),o=s[i%s.length],a=`${o} #${i}`,l=Math.min(2400,250+i*20%2e3),c=50+i*30%900;e.push({index:i,className:n,packageName:"com.app",text:n.includes("ImageView")?"":a,resourceId:`com.app:id/element_${i}`,contentDesc:n.includes("ImageView")?`Icon of ${o}`:"",clickable:r,enabled:i%25!==0,focused:!1,scrollable:!1,password:o.toLowerCase().includes("password"),selected:!1,children:[],bounds:{x1:c,y1:l,x2:c+200,y2:l+80,width:200,height:80,centerX:c+100,centerY:l+40}})}return e}async function la(u=he,e={}){let t=e.iterations||5,s=Date.now(),i=e.serial,n="Synthetic Mock Android Environment",r=!1;if(!e.forceMock)try{i=await u.ensureDefaultDevice(e.serial),i&&(n=await u.getDeviceModel(i),r=!0)}catch{r=!1}let o=[];for(let g=0;g<t;g++){let f=performance.now();r?await u.captureScreenshot(i):(await new Promise(y=>setTimeout(y,15)),Buffer.alloc(1024*1024)),o.push(performance.now()-f)}let a=[];for(let g=0;g<t;g++){let f=performance.now();r?await u.getUiHierarchy(i):await new Promise(y=>setTimeout(y,25)),a.push(performance.now()-f)}let l=ji(1e3),c=new He,p=["Submit","Email Address","Mathematics","Save Changes","NonExistent Query Fallback"],h=[];for(let g=0;g<t;g++){let f=p[g%p.length],y=performance.now();It(l,f,c),h.push(performance.now()-y)}let d=Date.now()-s;return{timestamp:new Date().toISOString(),device:n,package:e.packageName,screencap:Ps(o),uiHierarchy:Ps(a),nodeMatching:Ps(h),totalDurationMs:d}}function da(u){let e=(n,r)=>{let o=`${r.minMs.toFixed(1)}ms`.padStart(9),a=`${r.avgMs.toFixed(1)}ms`.padStart(9),l=`${r.p50Ms.toFixed(1)}ms`.padStart(9),c=`${r.p95Ms.toFixed(1)}ms`.padStart(9),p=`${r.maxMs.toFixed(1)}ms`.padStart(9);return`\u2502 ${n.padEnd(28)} \u2502 ${o} \u2502 ${a} \u2502 ${l} \u2502 ${c} \u2502 ${p} \u2502`};return["",xe.bold.cyan("\u26A1 PromptTest Performance Diagnostic Benchmark"),xe.gray("Device: ")+xe.bold.white(u.device)+xe.gray(` | Samples: ${u.screencap.iterations} runs`),"\u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u252C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u252C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u252C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u252C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u252C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510",`\u2502 ${xe.bold("Operation".padEnd(28))} \u2502 ${xe.bold("Min".padStart(9))} \u2502 ${xe.bold("Avg".padStart(9))} \u2502 ${xe.bold("p50".padStart(9))} \u2502 ${xe.bold("p95".padStart(9))} \u2502 ${xe.bold("Max".padStart(9))} \u2502`,"\u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524",e("Device Screencap",u.screencap),e("UI Hierarchy Dump (XML)",u.uiHierarchy),e("Node Matching (1k nodes)",u.nodeMatching),"\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518",xe.gray("Total Benchmark Wall-Time: ")+xe.bold.green(`${u.totalDurationMs}ms
769
+ ${e}`),console.log($.bold.green(" \u{1F4BE} Recording Session Saved Successfully!")),console.log(e),console.log(` ${$.gray("Steps Captured ")} ${$.bold.yellow(this.recordedSteps.length.toString())} ${this.isAppendMode?$.gray(`(Total Suite: ${r})`):""}`),console.log(` ${$.gray("Screens Visited")} ${$.bold.white(this.visitedScreens.length.toString())} ${this.visitedScreens.length>0?$.gray(`(${this.visitedScreens.join(" \u2192 ")})`):""}`),console.log(` ${$.gray("Screenshots ")} ${$.bold.white(this.screenshotCounter.toString())} saved`),console.log(` ${$.gray("Session Time ")} ${$.bold.white(n)}`),console.log(` ${$.gray("Crash Signals ")} ${this.crashDetected?$.red.bold("\u26A0\uFE0F Detected"):$.green("\u2714 0 detected")}`),console.log(e),console.log(` ${$.gray("\u{1F4C4} Spec ")} ${$.cyan(this.resolvedOutputPath)}`);let o=re.basename(this.resolvedOutputPath,".txt");console.log(` ${$.gray("\u{1F4CA} Report ")} ${$.cyan(re.resolve("output",`${o}_report.md`))}`),console.log(`${e}
770
+ `)}},Jo=new pt;import oi from"fs";import Hi from"path";var vt=null;function Ui(p){return JSON.parse(JSON.stringify(p))}function ai(p,e){for(let t of Object.keys(e)){let s=e[t],i=p[t];s&&typeof s=="object"&&!Array.isArray(s)&&i&&typeof i=="object"?ai(i,s):s!==void 0&&(p[t]=s)}return p}function Yi(p){let e=Ui(E),t=p||Hi.resolve(process.cwd(),"prompttest.config.json");if(oi.existsSync(t))try{let m=oi.readFileSync(t,"utf-8"),v=JSON.parse(m);typeof v=="object"&&v!==null&&ai(e,v)}catch{}let s=process.env.PROMPTTEST_ADB_COMMAND_TIMEOUT_MS||process.env.PROMPTTEST_COMMAND_TIMEOUT_MS;if(s){let m=parseInt(s,10);isNaN(m)||(e.adb.commandTimeoutMs=m)}let i=process.env.PROMPTTEST_POLLING_INTERVAL_MS||process.env.PROMPTTEST_POLL_INTERVAL_MS;if(i){let m=parseInt(i,10);isNaN(m)||(e.polling.intervalMs=m)}let n=process.env.PROMPTTEST_POLLING_DEFAULT_TIMEOUT_MS||process.env.PROMPTTEST_DEFAULT_TIMEOUT_MS;if(n){let m=parseInt(n,10);isNaN(m)||(e.polling.defaultTimeoutMs=m)}let r=process.env.PROMPTTEST_SCREEN_FALLBACK_WIDTH||process.env.PROMPTTEST_FALLBACK_WIDTH;if(r){let m=parseInt(r,10);isNaN(m)||(e.screen.fallbackWidth=m)}let o=process.env.PROMPTTEST_SCREEN_FALLBACK_HEIGHT||process.env.PROMPTTEST_FALLBACK_HEIGHT;if(o){let m=parseInt(o,10);isNaN(m)||(e.screen.fallbackHeight=m)}let a=process.env.PROMPTTEST_VISUAL_OVERLAP_RATIO||process.env.PROMPTTEST_OVERLAP_RATIO;if(a){let m=parseFloat(a);isNaN(m)||(e.visual.overlapRatio=m)}let d=process.env.PROMPTTEST_DEVICE_MAX_DEVICE_RETRIES||process.env.PROMPTTEST_MAX_DEVICE_RETRIES;if(d){let m=parseInt(d,10);isNaN(m)||(e.device.maxDeviceRetries=m)}let c=process.env.PROMPTTEST_DEVICE_AUTO_RECONNECT??process.env.PROMPTTEST_AUTO_RECONNECT;c!==void 0&&(e.device.autoReconnect=c.toLowerCase()!=="false");let l=process.env.PROMPTTEST_GESTURES_SWIPE_DURATION_MS||process.env.PROMPTTEST_SWIPE_DURATION_MS;if(l){let m=parseInt(l,10);isNaN(m)||(e.gestures.swipeDurationMs=m)}let h=process.env.PROMPTTEST_FLOW_MAX_LOOP_ITERATIONS||process.env.PROMPTTEST_MAX_LOOP_ITERATIONS;if(h){let m=parseInt(h,10);isNaN(m)||(e.flow.maxLoopIterations=m)}let u=process.env.PROMPTTEST_AI_PROVIDER;u&&["heuristic","openai","anthropic","ollama","mock"].includes(u)&&(e.ai.provider=u);let g=process.env.PROMPTTEST_AI_MODEL;g&&(e.ai.model=g);let f=process.env.PROMPTTEST_SELF_HEALING;f!==void 0&&(e.ai.selfHealing=f.toLowerCase()!=="false");let y=process.env.PROMPTTEST_CONFIDENCE_THRESHOLD;if(y){let m=parseFloat(y);isNaN(m)||(e.ai.confidenceThreshold=m)}let S=process.env.PROMPTTEST_AI_ENDPOINT;S&&(e.ai.endpoint=S);let b=process.env.PROMPTTEST_LOCALE;return b&&(e.locale=b.toLowerCase()),vt=e,e}function ta(){return vt||(vt=Yi()),vt}function sa(){vt=null}import xe from"chalk";function ci(p,e){if(p.length===0)return 0;let t=[...p].sort((i,n)=>i-n),s=Math.min(t.length-1,Math.max(0,Math.floor(e/100*(t.length-1))));return Math.round(t[s]*100)/100}function Ps(p){if(p.length===0)return{minMs:0,maxMs:0,avgMs:0,p50Ms:0,p95Ms:0,iterations:0,durations:[]};let e=Math.round(Math.min(...p)*100)/100,t=Math.round(Math.max(...p)*100)/100,s=p.reduce((o,a)=>o+a,0),i=Math.round(s/p.length*100)/100,n=ci(p,50),r=ci(p,95);return{minMs:e,maxMs:t,avgMs:i,p50Ms:n,p95Ms:r,iterations:p.length,durations:p}}function ji(p=1e3){let e=[];e.push({index:0,className:"android.widget.FrameLayout",packageName:"com.app",text:"",resourceId:"android:id/content",contentDesc:"Main Screen Root",clickable:!1,enabled:!0,focused:!1,scrollable:!1,password:!1,selected:!1,children:[],bounds:{x1:0,y1:0,x2:1080,y2:2400,width:1080,height:2400,centerX:540,centerY:1200}}),e.push({index:1,className:"android.widget.TextView",packageName:"com.app",text:"Apex Coaching Academy - Dashboard",resourceId:"com.app:id/title_header",contentDesc:"Header Title",clickable:!1,enabled:!0,focused:!1,scrollable:!1,password:!1,selected:!1,children:[],bounds:{x1:40,y1:100,x2:1040,y2:220,width:1e3,height:120,centerX:540,centerY:160}});let t=["android.widget.TextView","android.widget.Button","android.widget.EditText","android.widget.ImageView","android.view.ViewGroup","android.widget.LinearLayout","android.widget.CheckBox","android.widget.Switch"],s=["Sign In","Email Address","Password","Submit","Save Changes","Settings","Profile","Notifications","Batch 10A","Mathematics","Physics","Attendance","Export PDF","Delete Record","Cancel","Next","Back","Search","Filter","Refresh"];for(let i=2;i<p;i++){let n=t[i%t.length],r=n.includes("Button")||n.includes("CheckBox")||n.includes("Switch"),o=s[i%s.length],a=`${o} #${i}`,d=Math.min(2400,250+i*20%2e3),c=50+i*30%900;e.push({index:i,className:n,packageName:"com.app",text:n.includes("ImageView")?"":a,resourceId:`com.app:id/element_${i}`,contentDesc:n.includes("ImageView")?`Icon of ${o}`:"",clickable:r,enabled:i%25!==0,focused:!1,scrollable:!1,password:o.toLowerCase().includes("password"),selected:!1,children:[],bounds:{x1:c,y1:d,x2:c+200,y2:d+80,width:200,height:80,centerX:c+100,centerY:d+40}})}return e}async function la(p=he,e={}){let t=e.iterations||5,s=Date.now(),i=e.serial,n="Synthetic Mock Android Environment",r=!1;if(!e.forceMock)try{i=await p.ensureDefaultDevice(e.serial),i&&(n=await p.getDeviceModel(i),r=!0)}catch{r=!1}let o=[];for(let g=0;g<t;g++){let f=performance.now();r?await p.captureScreenshot(i):(await new Promise(y=>setTimeout(y,15)),Buffer.alloc(1024*1024)),o.push(performance.now()-f)}let a=[];for(let g=0;g<t;g++){let f=performance.now();r?await p.getUiHierarchy(i):await new Promise(y=>setTimeout(y,25)),a.push(performance.now()-f)}let d=ji(1e3),c=new He,l=["Submit","Email Address","Mathematics","Save Changes","NonExistent Query Fallback"],h=[];for(let g=0;g<t;g++){let f=l[g%l.length],y=performance.now();It(d,f,c),h.push(performance.now()-y)}let u=Date.now()-s;return{timestamp:new Date().toISOString(),device:n,package:e.packageName,screencap:Ps(o),uiHierarchy:Ps(a),nodeMatching:Ps(h),totalDurationMs:u}}function da(p){let e=(n,r)=>{let o=`${r.minMs.toFixed(1)}ms`.padStart(9),a=`${r.avgMs.toFixed(1)}ms`.padStart(9),d=`${r.p50Ms.toFixed(1)}ms`.padStart(9),c=`${r.p95Ms.toFixed(1)}ms`.padStart(9),l=`${r.maxMs.toFixed(1)}ms`.padStart(9);return`\u2502 ${n.padEnd(28)} \u2502 ${o} \u2502 ${a} \u2502 ${d} \u2502 ${c} \u2502 ${l} \u2502`};return["",xe.bold.cyan("\u26A1 PromptTest Performance Diagnostic Benchmark"),xe.gray("Device: ")+xe.bold.white(p.device)+xe.gray(` | Samples: ${p.screencap.iterations} runs`),"\u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u252C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u252C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u252C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u252C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u252C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510",`\u2502 ${xe.bold("Operation".padEnd(28))} \u2502 ${xe.bold("Min".padStart(9))} \u2502 ${xe.bold("Avg".padStart(9))} \u2502 ${xe.bold("p50".padStart(9))} \u2502 ${xe.bold("p95".padStart(9))} \u2502 ${xe.bold("Max".padStart(9))} \u2502`,"\u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524",e("Device Screencap",p.screencap),e("UI Hierarchy Dump (XML)",p.uiHierarchy),e("Node Matching (1k nodes)",p.nodeMatching),"\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518",xe.gray("Total Benchmark Wall-Time: ")+xe.bold.green(`${p.totalDurationMs}ms
771
771
  `)].join(`
772
- `)}import Nt from"fs";import ci from"path";import Ve from"chalk";async function ba(u=he,e={}){let t=[],s=process.versions.node,n=parseInt(s.split(".")[0],10)>=18;t.push({name:"Node.js Runtime",passed:n,message:`Node.js v${s} (Required >= 18.0.0)`,hint:n?void 0:"Please upgrade Node.js to v18.0.0 or higher: https://nodejs.org"});let r=!1,o="ADB binary not found in PATH",a='Install Android SDK platform-tools and ensure "adb" is in your system PATH.';try{let{stdout:b}=await u.execAdb(["version"],void 0,5e3),m=b.match(/Android Debug Bridge version ([\d.]+)/i);m?(r=!0,o=`Android Debug Bridge version ${m[1]}`,a=void 0):(r=!0,o=b.split(`
773
- `)[0].trim(),a=void 0)}catch(b){o=`Failed to execute adb: ${b.message}`}t.push({name:"Android Debug Bridge (ADB)",passed:r,message:o,hint:a});let l=!1,c="No connected Android devices or emulators found",p="Connect an Android device via USB/Wi-Fi or launch an emulator with USB Debugging enabled.";try{let b=await u.getConnectedDevices(),m=b.filter(k=>k.state==="device"),v=b.filter(k=>k.state==="unauthorized"),E=b.filter(k=>k.state==="offline");if(m.length>0){l=!0;let k=m.map(w=>`${w.serial} (${w.model||"Unknown"})`).join(", ");c=`Found ${m.length} authorized device(s): ${k}`,p=void 0}else v.length>0?(c=`Device(s) found but unauthorized: ${v.map(k=>k.serial).join(", ")}`,p='Check the device screen and accept the "Allow USB debugging" RSA prompt.'):E.length>0&&(c=`Device(s) found in offline state: ${E.map(k=>k.serial).join(", ")}`,p='Try running "adb reconnect" or reconnect the USB cable.')}catch(b){c=`Failed to list devices: ${b.message}`}if(t.push({name:"Connected Android Device",passed:l,message:c,hint:p}),e.packageName){let b=e.packageName,m=!1,v=`Package "${b}" not found on target device`,E='Install the APK using "adb install <path.apk>" or check the package identifier.';if(l)try{let{stdout:k}=await u.execAdb(["shell","pm","list","packages",b],e.serial,5e3);k.includes(`package:${b}`)&&(m=!0,v=`Package "${b}" is installed on target device`,E=void 0)}catch(k){v=`Failed to query package status: ${k.message}`}else v="Skipped package verification (no authorized device available)",E=`Connect a device to verify package "${b}".`;t.push({name:`Target Package [${b}]`,passed:m,message:v,hint:E})}let h=!0,d="All required workspace directories are accessible",g,f=["output","memory",".prompttest"];for(let b of f)try{let m=ci.resolve(process.cwd(),b);Nt.existsSync(m)||Nt.mkdirSync(m,{recursive:!0});let v=ci.join(m,".doctor_perm_test");Nt.writeFileSync(v,"ok","utf-8"),Nt.unlinkSync(v)}catch(m){h=!1,d=`Filesystem permission error for "./${b}": ${m.message}`,g="Ensure the current user has write permissions to the workspace directory.";break}t.push({name:"Workspace Storage & Permissions",passed:h,message:d,hint:g});let y=t.filter(b=>b.passed).length,S=t.filter(b=>!b.passed).length;return{timestamp:new Date().toISOString(),allPassed:S===0,checks:t,summary:{passed:y,failed:S,warnings:0}}}function ya(u){let e=["",Ve.bold.cyan("\u{1FA7A} PromptTest Doctor \u2014 Environment Health Diagnostic"),Ve.gray(`Scanned at ${u.timestamp}
774
- `)];for(let t of u.checks){let s=t.passed?Ve.green("\u2714"):Ve.red("\u2716"),i=Ve.bold(t.name);e.push(` ${s} ${i}: ${t.message}`),t.hint&&!t.passed&&e.push(Ve.yellow(` \u{1F4A1} Fix: ${t.hint}`))}return e.push(""),u.allPassed?e.push(Ve.bold.green("\u2728 All diagnostic checks passed! Your environment is ready to test.")):e.push(Ve.bold.red(`\u26A0\uFE0F ${u.summary.failed} diagnostic check(s) failed. Please review the remediation hints above.`)),e.push(""),e.join(`
775
- `)}import Vi from"readline";import ht from"fs";import li from"path";import G from"chalk";async function ka(u=he,e,t={}){let s=await u.ensureDefaultDevice(t.serial),i=e||new Ye(u),n={history:[],successfulSteps:[]},r=t.input||process.stdin,o=t.output||process.stdout,a=Vi.createInterface({input:r,output:o,prompt:G.bold.cyan("prompttest> ")}),l=!1,c=()=>{if(!l)try{a.prompt()}catch{}},p=h=>{o.write(h+`
776
- `)};return p(G.bold.cyan(`
777
- \u26A1 PromptTest Interactive Live REPL / Playground (v1.1.0)`)),p(G.gray("Device: ")+G.bold.white(s||"No device connected (offline mock)")+(t.packageName?G.gray(" | Package: ")+G.bold.white(t.packageName):"")),p(G.gray(`Type natural language instructions (e.g. Tap 'Sign In'), or REPL commands: "inspect", "screenshot", "history", "save <file.txt>", "exit".
778
- `)),new Promise(h=>{c(),a.on("line",async d=>{let g=d.trim();if(!g){c();return}n.history.push(g);let f=g.toLowerCase();if(f==="exit"||f==="quit"||f===":q"){l=!0,p(G.yellow("Exiting PromptTest REPL.")),a.close();return}if(f==="help"||f==="?"){p(G.bold.white(`
779
- \u{1F4D6} PromptTest REPL Commands:`)),p(` \u2022 ${G.cyan("Tap '...'")} / ${G.cyan("Type '...' into '...'")} : Execute action live on device`),p(` \u2022 ${G.cyan("Verify '...' is visible")} : Assert element visibility`),p(` \u2022 ${G.cyan("inspect")} / ${G.cyan("tree")} : List interactive elements and input fields on screen`),p(` \u2022 ${G.cyan("screenshot [path]")} : Capture current screen to image file`),p(` \u2022 ${G.cyan("history")} : Show executed commands in current session`),p(` \u2022 ${G.cyan("save <file.txt>")} : Save successful steps into a reusable spec file`),p(` \u2022 ${G.cyan("clear")} : Clear session history`),p(` \u2022 ${G.cyan("exit")} : Quit the REPL
780
- `),c();return}if(f==="history"){p(G.bold.white(`
781
- \u{1F4DC} Session History (${n.history.length} commands):`)),n.history.forEach((y,S)=>{p(` ${S+1}. ${y}`)}),p(""),c();return}if(f==="clear"){n.successfulSteps=[],n.history=[],p(G.green("Session history cleared.")),c();return}if(f.startsWith("save")){let S=g.split(/\s+/)[1]||"output/repl_spec.txt";try{let b=li.dirname(S);b&&!ht.existsSync(b)&&ht.mkdirSync(b,{recursive:!0});let m=n.successfulSteps.map((v,E)=>`${E+1}. ${v}`).join(`
782
- `);ht.writeFileSync(S,m,"utf-8"),p(G.bold.green(`\u2714 Saved ${n.successfulSteps.length} step(s) to ${S}`))}catch(b){let m=b;p(G.red(`Failed to save spec: ${m.message}`))}c();return}if(f.startsWith("screenshot")){let S=g.split(/\s+/)[1]||`output/repl_screenshot_${Date.now()}.png`;try{let b=li.dirname(S);b&&!ht.existsSync(b)&&ht.mkdirSync(b,{recursive:!0});let m=await u.captureScreenshot(s);ht.writeFileSync(S,m),p(G.bold.green(`\u2714 Screenshot saved to ${S}`))}catch(b){let m=b;p(G.red(`Failed to capture screenshot: ${m.message}`))}c();return}if(f==="inspect"||f==="tree"){try{p(G.gray("Dumping UI hierarchy..."));let y=await u.getUiHierarchy(s),{flat:S}=ue(y),b=S.filter(m=>m.clickable||m.className.includes("Button")||m.className.includes("EditText"));p(G.bold.white(`
783
- \u{1F50D} Visible Interactive Elements (${b.length} found):`)),b.slice(0,25).forEach((m,v)=>{let E=m.text||m.contentDesc||m.resourceId||`<Unnamed ${m.className}>`,k=m.className.split(".").pop()||m.className;p(` [${v+1}] (${k}) "${E}" at (${m.bounds.centerX}, ${m.bounds.centerY})`)}),b.length>25&&p(G.gray(` ... and ${b.length-25} more elements.`)),p("")}catch(y){let S=y;p(G.red(`Failed to inspect hierarchy: ${S.message}`))}c();return}try{let y=Ct(g);if(y.length===0){p(G.yellow(`Could not parse natural language step: "${g}"`)),c();return}let S=y[0],b=performance.now();await i.executeStep(S,s);let m=Math.round(performance.now()-b);n.successfulSteps.push(g),p(G.green(`\u2714 [${S.type}] Completed in ${m}ms: `)+G.white(S.originalText))}catch(y){let S=y;p(G.red(`\u2716 Step failed: ${S.message}`))}c()}),a.on("close",()=>{l=!0,h(n)})})}import{execFile as qe}from"child_process";var di=class{defaultUdid;wdaBaseUrl;isMock;defaultDimensions={width:1170,height:2532};constructor(e={}){typeof e=="string"?(this.defaultUdid=e,this.isMock=!1):(this.defaultUdid=e.udid,this.wdaBaseUrl=e.wdaBaseUrl,this.isMock=e.useMock??!1),process.platform!=="darwin"&&!this.wdaBaseUrl&&this.isMock===void 0&&(this.isMock=!0)}getDefaultDevice(){return this.defaultUdid}async ensureDefaultDevice(e){if(e)return e;if(this.defaultUdid)return this.defaultUdid;let s=(await this.getConnectedDevices()).find(n=>n.state==="simulator"||n.state==="device");if(s)return this.defaultUdid=s.serial,s.serial;let i="booted-simulator";return this.defaultUdid=i,i}async getConnectedDevices(){return this.isMock||process.platform!=="darwin"?[{serial:this.defaultUdid||"00008101-001234567890001E",state:"simulator",model:"iPhone 15 Pro (Simulator)",platform:"ios"}]:new Promise(e=>{qe("xcrun",["simctl","list","devices","available","--json"],(t,s)=>{if(t||!s){e([{serial:"booted-ios-simulator",state:"simulator",model:"iPhone Simulator",platform:"ios"}]);return}try{let i=JSON.parse(s),n=[],r=i.devices||{};for(let o of Object.keys(r)){let a=r[o];if(Array.isArray(a))for(let l of a)l.isAvailable&&l.state==="Booted"&&n.push({serial:l.udid,state:"simulator",model:`${l.name} (${o.split(".").pop()||"iOS"})`,platform:"ios"})}e(n.length>0?n:[{serial:"booted-ios-simulator",state:"simulator",model:"iPhone Simulator",platform:"ios"}])}catch{e([])}})})}async getScreenDimensions(e){return this.isMock||process.platform!=="darwin"?this.defaultDimensions:this.defaultDimensions}async captureScreenshot(e){let t=await this.ensureDefaultDevice(e);return this.isMock||process.platform!=="darwin"?Buffer.from("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==","base64"):new Promise((s,i)=>{qe("xcrun",["simctl","io",t,"screenshot","--type=png","-"],{encoding:"buffer",maxBuffer:10*1024*1024},(n,r)=>{if(n)return i(n);s(r)})})}async getUiHierarchy(e){let t=`<?xml version="1.0" encoding="UTF-8"?>
772
+ `)}import Nt from"fs";import li from"path";import Ve from"chalk";async function ba(p=he,e={}){let t=[],s=process.versions.node,n=parseInt(s.split(".")[0],10)>=18;t.push({name:"Node.js Runtime",passed:n,message:`Node.js v${s} (Required >= 18.0.0)`,hint:n?void 0:"Please upgrade Node.js to v18.0.0 or higher: https://nodejs.org"});let r=!1,o="ADB binary not found in PATH",a='Install Android SDK platform-tools and ensure "adb" is in your system PATH.';try{let{stdout:b}=await p.execAdb(["version"],void 0,5e3),m=b.match(/Android Debug Bridge version ([\d.]+)/i);m?(r=!0,o=`Android Debug Bridge version ${m[1]}`,a=void 0):(r=!0,o=b.split(`
773
+ `)[0].trim(),a=void 0)}catch(b){o=`Failed to execute adb: ${b.message}`}t.push({name:"Android Debug Bridge (ADB)",passed:r,message:o,hint:a});let d=!1,c="No connected Android devices or emulators found",l="Connect an Android device via USB/Wi-Fi or launch an emulator with USB Debugging enabled.";try{let b=await p.getConnectedDevices(),m=b.filter(D=>D.state==="device"),v=b.filter(D=>D.state==="unauthorized"),x=b.filter(D=>D.state==="offline");if(m.length>0){d=!0;let D=m.map(w=>`${w.serial} (${w.model||"Unknown"})`).join(", ");c=`Found ${m.length} authorized device(s): ${D}`,l=void 0}else v.length>0?(c=`Device(s) found but unauthorized: ${v.map(D=>D.serial).join(", ")}`,l='Check the device screen and accept the "Allow USB debugging" RSA prompt.'):x.length>0&&(c=`Device(s) found in offline state: ${x.map(D=>D.serial).join(", ")}`,l='Try running "adb reconnect" or reconnect the USB cable.')}catch(b){c=`Failed to list devices: ${b.message}`}if(t.push({name:"Connected Android Device",passed:d,message:c,hint:l}),e.packageName){let b=e.packageName,m=!1,v=`Package "${b}" not found on target device`,x='Install the APK using "adb install <path.apk>" or check the package identifier.';if(d)try{let{stdout:D}=await p.execAdb(["shell","pm","list","packages",b],e.serial,5e3);D.includes(`package:${b}`)&&(m=!0,v=`Package "${b}" is installed on target device`,x=void 0)}catch(D){v=`Failed to query package status: ${D.message}`}else v="Skipped package verification (no authorized device available)",x=`Connect a device to verify package "${b}".`;t.push({name:`Target Package [${b}]`,passed:m,message:v,hint:x})}let h=!0,u="All required workspace directories are accessible",g,f=["output","memory",".prompttest"];for(let b of f)try{let m=li.resolve(process.cwd(),b);Nt.existsSync(m)||Nt.mkdirSync(m,{recursive:!0});let v=li.join(m,".doctor_perm_test");Nt.writeFileSync(v,"ok","utf-8"),Nt.unlinkSync(v)}catch(m){h=!1,u=`Filesystem permission error for "./${b}": ${m.message}`,g="Ensure the current user has write permissions to the workspace directory.";break}t.push({name:"Workspace Storage & Permissions",passed:h,message:u,hint:g});let y=t.filter(b=>b.passed).length,S=t.filter(b=>!b.passed).length;return{timestamp:new Date().toISOString(),allPassed:S===0,checks:t,summary:{passed:y,failed:S,warnings:0}}}function ya(p){let e=["",Ve.bold.cyan("\u{1FA7A} PromptTest Doctor \u2014 Environment Health Diagnostic"),Ve.gray(`Scanned at ${p.timestamp}
774
+ `)];for(let t of p.checks){let s=t.passed?Ve.green("\u2714"):Ve.red("\u2716"),i=Ve.bold(t.name);e.push(` ${s} ${i}: ${t.message}`),t.hint&&!t.passed&&e.push(Ve.yellow(` \u{1F4A1} Fix: ${t.hint}`))}return e.push(""),p.allPassed?e.push(Ve.bold.green("\u2728 All diagnostic checks passed! Your environment is ready to test.")):e.push(Ve.bold.red(`\u26A0\uFE0F ${p.summary.failed} diagnostic check(s) failed. Please review the remediation hints above.`)),e.push(""),e.join(`
775
+ `)}import Vi from"readline";import ht from"fs";import di from"path";import G from"chalk";async function ka(p=he,e,t={}){let s=await p.ensureDefaultDevice(t.serial),i=e||new Ye(p),n={history:[],successfulSteps:[]},r=t.input||process.stdin,o=t.output||process.stdout,a=Vi.createInterface({input:r,output:o,prompt:G.bold.cyan("prompttest> ")}),d=!1,c=()=>{if(!d)try{a.prompt()}catch{}},l=h=>{o.write(h+`
776
+ `)};return l(G.bold.cyan(`
777
+ \u26A1 PromptTest Interactive Live REPL / Playground (v1.1.0)`)),l(G.gray("Device: ")+G.bold.white(s||"No device connected (offline mock)")+(t.packageName?G.gray(" | Package: ")+G.bold.white(t.packageName):"")),l(G.gray(`Type natural language instructions (e.g. Tap 'Sign In'), or REPL commands: "inspect", "screenshot", "history", "save <file.txt>", "exit".
778
+ `)),new Promise(h=>{c(),a.on("line",async u=>{let g=u.trim();if(!g){c();return}n.history.push(g);let f=g.toLowerCase();if(f==="exit"||f==="quit"||f===":q"){d=!0,l(G.yellow("Exiting PromptTest REPL.")),a.close();return}if(f==="help"||f==="?"){l(G.bold.white(`
779
+ \u{1F4D6} PromptTest REPL Commands:`)),l(` \u2022 ${G.cyan("Tap '...'")} / ${G.cyan("Type '...' into '...'")} : Execute action live on device`),l(` \u2022 ${G.cyan("Verify '...' is visible")} : Assert element visibility`),l(` \u2022 ${G.cyan("inspect")} / ${G.cyan("tree")} : List interactive elements and input fields on screen`),l(` \u2022 ${G.cyan("screenshot [path]")} : Capture current screen to image file`),l(` \u2022 ${G.cyan("history")} : Show executed commands in current session`),l(` \u2022 ${G.cyan("save <file.txt>")} : Save successful steps into a reusable spec file`),l(` \u2022 ${G.cyan("clear")} : Clear session history`),l(` \u2022 ${G.cyan("exit")} : Quit the REPL
780
+ `),c();return}if(f==="history"){l(G.bold.white(`
781
+ \u{1F4DC} Session History (${n.history.length} commands):`)),n.history.forEach((y,S)=>{l(` ${S+1}. ${y}`)}),l(""),c();return}if(f==="clear"){n.successfulSteps=[],n.history=[],l(G.green("Session history cleared.")),c();return}if(f.startsWith("save")){let S=g.split(/\s+/)[1]||"output/repl_spec.txt";try{let b=di.dirname(S);b&&!ht.existsSync(b)&&ht.mkdirSync(b,{recursive:!0});let m=n.successfulSteps.map((v,x)=>`${x+1}. ${v}`).join(`
782
+ `);ht.writeFileSync(S,m,"utf-8"),l(G.bold.green(`\u2714 Saved ${n.successfulSteps.length} step(s) to ${S}`))}catch(b){let m=b;l(G.red(`Failed to save spec: ${m.message}`))}c();return}if(f.startsWith("screenshot")){let S=g.split(/\s+/)[1]||`output/repl_screenshot_${Date.now()}.png`;try{let b=di.dirname(S);b&&!ht.existsSync(b)&&ht.mkdirSync(b,{recursive:!0});let m=await p.captureScreenshot(s);ht.writeFileSync(S,m),l(G.bold.green(`\u2714 Screenshot saved to ${S}`))}catch(b){let m=b;l(G.red(`Failed to capture screenshot: ${m.message}`))}c();return}if(f==="inspect"||f==="tree"){try{l(G.gray("Dumping UI hierarchy..."));let y=await p.getUiHierarchy(s),{flat:S}=ue(y),b=S.filter(m=>m.clickable||m.className.includes("Button")||m.className.includes("EditText"));l(G.bold.white(`
783
+ \u{1F50D} Visible Interactive Elements (${b.length} found):`)),b.slice(0,25).forEach((m,v)=>{let x=m.text||m.contentDesc||m.resourceId||`<Unnamed ${m.className}>`,D=m.className.split(".").pop()||m.className;l(` [${v+1}] (${D}) "${x}" at (${m.bounds.centerX}, ${m.bounds.centerY})`)}),b.length>25&&l(G.gray(` ... and ${b.length-25} more elements.`)),l("")}catch(y){let S=y;l(G.red(`Failed to inspect hierarchy: ${S.message}`))}c();return}try{let y=Ct(g);if(y.length===0){l(G.yellow(`Could not parse natural language step: "${g}"`)),c();return}let S=y[0],b=performance.now();await i.executeStep(S,s);let m=Math.round(performance.now()-b);n.successfulSteps.push(g),l(G.green(`\u2714 [${S.type}] Completed in ${m}ms: `)+G.white(S.originalText))}catch(y){let S=y;l(G.red(`\u2716 Step failed: ${S.message}`))}c()}),a.on("close",()=>{d=!0,h(n)})})}import{execFile as qe}from"child_process";var ui=class{defaultUdid;wdaBaseUrl;isMock;defaultDimensions={width:1170,height:2532};constructor(e={}){typeof e=="string"?(this.defaultUdid=e,this.isMock=!1):(this.defaultUdid=e.udid,this.wdaBaseUrl=e.wdaBaseUrl,this.isMock=e.useMock??!1),process.platform!=="darwin"&&!this.wdaBaseUrl&&this.isMock===void 0&&(this.isMock=!0)}getDefaultDevice(){return this.defaultUdid}async ensureDefaultDevice(e){if(e)return e;if(this.defaultUdid)return this.defaultUdid;let s=(await this.getConnectedDevices()).find(n=>n.state==="simulator"||n.state==="device");if(s)return this.defaultUdid=s.serial,s.serial;let i="booted-simulator";return this.defaultUdid=i,i}async getConnectedDevices(){return this.isMock||process.platform!=="darwin"?[{serial:this.defaultUdid||"00008101-001234567890001E",state:"simulator",model:"iPhone 15 Pro (Simulator)",platform:"ios"}]:new Promise(e=>{qe("xcrun",["simctl","list","devices","available","--json"],(t,s)=>{if(t||!s){e([{serial:"booted-ios-simulator",state:"simulator",model:"iPhone Simulator",platform:"ios"}]);return}try{let i=JSON.parse(s),n=[],r=i.devices||{};for(let o of Object.keys(r)){let a=r[o];if(Array.isArray(a))for(let d of a)d.isAvailable&&d.state==="Booted"&&n.push({serial:d.udid,state:"simulator",model:`${d.name} (${o.split(".").pop()||"iOS"})`,platform:"ios"})}e(n.length>0?n:[{serial:"booted-ios-simulator",state:"simulator",model:"iPhone Simulator",platform:"ios"}])}catch{e([])}})})}async getScreenDimensions(e){return this.isMock||process.platform!=="darwin"?this.defaultDimensions:this.defaultDimensions}async captureScreenshot(e){let t=await this.ensureDefaultDevice(e);return this.isMock||process.platform!=="darwin"?Buffer.from("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==","base64"):new Promise((s,i)=>{qe("xcrun",["simctl","io",t,"screenshot","--type=png","-"],{encoding:"buffer",maxBuffer:10*1024*1024},(n,r)=>{if(n)return i(n);s(r)})})}async getUiHierarchy(e){let t=`<?xml version="1.0" encoding="UTF-8"?>
784
784
  <hierarchy rotation="0">
785
785
  <XCUIElementTypeApplication type="XCUIElementTypeApplication" name="TargetApp" label="TargetApp" enabled="true" visible="true" x="0" y="0" width="390" height="844">
786
786
  <XCUIElementTypeWindow type="XCUIElementTypeWindow" enabled="true" visible="true" x="0" y="0" width="390" height="844">
@@ -789,7 +789,7 @@ ${e}`),console.log(D.bold.green(" \u{1F4BE} Recording Session Saved Successful
789
789
  <XCUIElementTypeTextField type="XCUIElementTypeTextField" identifier="user_field" name="Username" label="Username" enabled="true" visible="true" x="40" y="120" width="310" height="44" />
790
790
  </XCUIElementTypeWindow>
791
791
  </XCUIElementTypeApplication>
792
- </hierarchy>`;if(this.isMock||process.platform!=="darwin")return t;if(this.wdaBaseUrl)try{let s=await fetch(`${this.wdaBaseUrl}/source?format=xml`);if(s.ok)return await s.text()}catch{}return t}async tap(e,t,s){let i=await this.ensureDefaultDevice(s);if(!(this.isMock||process.platform!=="darwin")){if(this.wdaBaseUrl){await fetch(`${this.wdaBaseUrl}/wda/tap/nil`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({x:e,y:t})}).catch(()=>{});return}await new Promise(n=>{qe("idb",["ui","tap",`${e}`,`${t}`,"--udid",i],()=>n())})}}async inputText(e,t){let s=await this.ensureDefaultDevice(t);if(!(this.isMock||process.platform!=="darwin")){if(this.wdaBaseUrl){await fetch(`${this.wdaBaseUrl}/wda/keys`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({value:e.split("")})}).catch(()=>{});return}await new Promise(i=>{qe("idb",["ui","type",e,"--udid",s],()=>i())})}}async pressKey(e,t){this.isMock||process.platform!=="darwin"||(await this.ensureDefaultDevice(t),this.wdaBaseUrl&&await fetch(`${this.wdaBaseUrl}/wda/keys`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({value:[e]})}).catch(()=>{}))}async swipe(e,t,s,i,n=300,r){this.isMock||process.platform!=="darwin"||(await this.ensureDefaultDevice(r),this.wdaBaseUrl&&await fetch(`${this.wdaBaseUrl}/wda/dragfromtoforduration`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({fromX:e,fromY:t,toX:s,toY:i,duration:n/1e3})}).catch(()=>{}))}async launchApp(e,t){let s=await this.ensureDefaultDevice(t);if(!(this.isMock||process.platform!=="darwin"))return new Promise(i=>{qe("xcrun",["simctl","launch",s,e],()=>i())})}async forceStop(e,t){let s=await this.ensureDefaultDevice(t);if(!(this.isMock||process.platform!=="darwin"))return new Promise(i=>{qe("xcrun",["simctl","terminate",s,e],()=>i())})}async isAppInstalled(e,t){let s=await this.ensureDefaultDevice(t);return this.isMock||process.platform!=="darwin"?!0:new Promise(i=>{qe("xcrun",["simctl","get_app_container",s,e],n=>{i(!n)})})}async getForegroundPackage(e){return"com.apple.mobilesafari"}};import xt from"fs";import Ds from"path";function ui(u){let e=u.totalSteps||0,t=u.passedSteps||0,s=u.failedSteps||0,i=u.skippedSteps||0,n=u.errorsDetected?u.errorsDetected.length:0;if(e===0)return{score:0,grade:"F",verdict:"RELEASE_BLOCKER",rationale:"No test steps were executed.",metrics:{passRate:0,criticalFailures:0,visualDefects:0,totalSteps:0,skippedSteps:0}};let r=t/e,o=Math.min(30,n*10),a=s>0?35+Math.min(25,s*5):0,l=Math.round(r*80+20-o-a);l=Math.max(0,Math.min(100,l));let c="F",p="RELEASE_BLOCKER",h="";return l>=90?(c="A",p="READY_FOR_RELEASE",h="High quality gate confidence. All critical assertion paths verified."):l>=80?(c="B",p="READY_FOR_RELEASE",h="Acceptable release confidence. Minor non-critical or optional warnings observed."):l>=70?(c="C",p="PROCEED_WITH_CAUTION",h="Elevated risk. Visual QA warnings or multiple non-critical step failures detected."):(c="F",p="RELEASE_BLOCKER",h=`Critical test failures (${s}) or visual defects (${n}) block safe release.`),{score:l,grade:c,verdict:p,rationale:h,metrics:{passRate:Math.round(r*100)/100,criticalFailures:s,visualDefects:n,totalSteps:e,skippedSteps:i}}}function Ma(u="output"){let e=[],t=d=>{if(!xt.existsSync(d))return;let g=xt.readdirSync(d,{withFileTypes:!0});for(let f of g){let y=Ds.join(d,f.name);f.isDirectory()?t(y):f.isFile()&&(f.name.endsWith("-results.json")||f.name.endsWith("-report.json"))&&e.push(y)}};if(Array.isArray(u))for(let d of u)xt.existsSync(d)&&(xt.statSync(d).isDirectory()?t(d):e.push(d));else t(u);let s=[],i=new Set,n=0,r=0,o=0,a=0,l=[];for(let d of e)try{let g=xt.readFileSync(d,"utf-8"),f=JSON.parse(g),y=ui(f),S=f.deviceId||"unknown-device";i.add(S),n+=f.totalSteps||0,r+=f.passedSteps||0,o+=f.failedSteps||0,a+=f.skippedSteps||0,f.errorsDetected&&l.push(...f.errorsDetected),s.push({deviceId:S,suiteName:Ds.basename(d,Ds.extname(d)).replace(/-results|-report/,""),packageName:f.packageName||"unknown",totalSteps:f.totalSteps||0,passedSteps:f.passedSteps||0,failedSteps:f.failedSteps||0,skippedSteps:f.skippedSteps||0,durationSeconds:f.durationSeconds||0,confidenceScore:y.score,confidenceGrade:y.grade,sourceFile:d})}catch{}let c=n>0?Math.round(r/n*100)/100:0,p={packageName:s[0]?.packageName||"Enterprise Matrix",deviceId:`${i.size} devices`,startTime:new Date().toISOString(),endTime:new Date().toISOString(),durationSeconds:s.reduce((d,g)=>d+g.durationSeconds,0),totalSteps:n,passedSteps:r,failedSteps:o,skippedSteps:a,warnSteps:0,errorsDetected:l,steps:[]},h=ui(p);return{timestamp:new Date().toISOString(),totalRuns:s.length,uniqueDevices:Array.from(i),totalSteps:n,passedSteps:r,failedSteps:o,skippedSteps:a,overallPassRate:c,overallConfidence:h,deviceSummaries:s}}function Fa(u){let e=u.overallConfidence,t=e.grade==="A"?"#10B981":e.grade==="B"?"#3B82F6":e.grade==="C"?"#F59E0B":"#EF4444",s=u.deviceSummaries.map(i=>{let n=i.confidenceGrade==="A"?"#10B981":i.confidenceGrade==="B"?"#3B82F6":i.confidenceGrade==="C"?"#F59E0B":"#EF4444";return`
792
+ </hierarchy>`;if(this.isMock||process.platform!=="darwin")return t;if(this.wdaBaseUrl)try{let s=await fetch(`${this.wdaBaseUrl}/source?format=xml`);if(s.ok)return await s.text()}catch{}return t}async tap(e,t,s){let i=await this.ensureDefaultDevice(s);if(!(this.isMock||process.platform!=="darwin")){if(this.wdaBaseUrl){await fetch(`${this.wdaBaseUrl}/wda/tap/nil`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({x:e,y:t})}).catch(()=>{});return}await new Promise(n=>{qe("idb",["ui","tap",`${e}`,`${t}`,"--udid",i],()=>n())})}}async inputText(e,t){let s=await this.ensureDefaultDevice(t);if(!(this.isMock||process.platform!=="darwin")){if(this.wdaBaseUrl){await fetch(`${this.wdaBaseUrl}/wda/keys`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({value:e.split("")})}).catch(()=>{});return}await new Promise(i=>{qe("idb",["ui","type",e,"--udid",s],()=>i())})}}async pressKey(e,t){this.isMock||process.platform!=="darwin"||(await this.ensureDefaultDevice(t),this.wdaBaseUrl&&await fetch(`${this.wdaBaseUrl}/wda/keys`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({value:[e]})}).catch(()=>{}))}async swipe(e,t,s,i,n=300,r){this.isMock||process.platform!=="darwin"||(await this.ensureDefaultDevice(r),this.wdaBaseUrl&&await fetch(`${this.wdaBaseUrl}/wda/dragfromtoforduration`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({fromX:e,fromY:t,toX:s,toY:i,duration:n/1e3})}).catch(()=>{}))}async launchApp(e,t){let s=await this.ensureDefaultDevice(t);if(!(this.isMock||process.platform!=="darwin"))return new Promise(i=>{qe("xcrun",["simctl","launch",s,e],()=>i())})}async forceStop(e,t){let s=await this.ensureDefaultDevice(t);if(!(this.isMock||process.platform!=="darwin"))return new Promise(i=>{qe("xcrun",["simctl","terminate",s,e],()=>i())})}async isAppInstalled(e,t){let s=await this.ensureDefaultDevice(t);return this.isMock||process.platform!=="darwin"?!0:new Promise(i=>{qe("xcrun",["simctl","get_app_container",s,e],n=>{i(!n)})})}async getForegroundPackage(e){return"com.apple.mobilesafari"}};import xt from"fs";import Ds from"path";function pi(p){let e=p.totalSteps||0,t=p.passedSteps||0,s=p.failedSteps||0,i=p.skippedSteps||0,n=p.errorsDetected?p.errorsDetected.length:0;if(e===0)return{score:0,grade:"F",verdict:"RELEASE_BLOCKER",rationale:"No test steps were executed.",metrics:{passRate:0,criticalFailures:0,visualDefects:0,totalSteps:0,skippedSteps:0}};let r=t/e,o=Math.min(30,n*10),a=s>0?35+Math.min(25,s*5):0,d=Math.round(r*80+20-o-a);d=Math.max(0,Math.min(100,d));let c="F",l="RELEASE_BLOCKER",h="";return d>=90?(c="A",l="READY_FOR_RELEASE",h="High quality gate confidence. All critical assertion paths verified."):d>=80?(c="B",l="READY_FOR_RELEASE",h="Acceptable release confidence. Minor non-critical or optional warnings observed."):d>=70?(c="C",l="PROCEED_WITH_CAUTION",h="Elevated risk. Visual QA warnings or multiple non-critical step failures detected."):(c="F",l="RELEASE_BLOCKER",h=`Critical test failures (${s}) or visual defects (${n}) block safe release.`),{score:d,grade:c,verdict:l,rationale:h,metrics:{passRate:Math.round(r*100)/100,criticalFailures:s,visualDefects:n,totalSteps:e,skippedSteps:i}}}function Ma(p="output"){let e=[],t=u=>{if(!xt.existsSync(u))return;let g=xt.readdirSync(u,{withFileTypes:!0});for(let f of g){let y=Ds.join(u,f.name);f.isDirectory()?t(y):f.isFile()&&(f.name.endsWith("-results.json")||f.name.endsWith("-report.json"))&&e.push(y)}};if(Array.isArray(p))for(let u of p)xt.existsSync(u)&&(xt.statSync(u).isDirectory()?t(u):e.push(u));else t(p);let s=[],i=new Set,n=0,r=0,o=0,a=0,d=[];for(let u of e)try{let g=xt.readFileSync(u,"utf-8"),f=JSON.parse(g),y=pi(f),S=f.deviceId||"unknown-device";i.add(S),n+=f.totalSteps||0,r+=f.passedSteps||0,o+=f.failedSteps||0,a+=f.skippedSteps||0,f.errorsDetected&&d.push(...f.errorsDetected),s.push({deviceId:S,suiteName:Ds.basename(u,Ds.extname(u)).replace(/-results|-report/,""),packageName:f.packageName||"unknown",totalSteps:f.totalSteps||0,passedSteps:f.passedSteps||0,failedSteps:f.failedSteps||0,skippedSteps:f.skippedSteps||0,durationSeconds:f.durationSeconds||0,confidenceScore:y.score,confidenceGrade:y.grade,sourceFile:u})}catch{}let c=n>0?Math.round(r/n*100)/100:0,l={packageName:s[0]?.packageName||"Enterprise Matrix",deviceId:`${i.size} devices`,startTime:new Date().toISOString(),endTime:new Date().toISOString(),durationSeconds:s.reduce((u,g)=>u+g.durationSeconds,0),totalSteps:n,passedSteps:r,failedSteps:o,skippedSteps:a,warnSteps:0,errorsDetected:d,steps:[]},h=pi(l);return{timestamp:new Date().toISOString(),totalRuns:s.length,uniqueDevices:Array.from(i),totalSteps:n,passedSteps:r,failedSteps:o,skippedSteps:a,overallPassRate:c,overallConfidence:h,deviceSummaries:s}}function Fa(p){let e=p.overallConfidence,t=e.grade==="A"?"#10B981":e.grade==="B"?"#3B82F6":e.grade==="C"?"#F59E0B":"#EF4444",s=p.deviceSummaries.map(i=>{let n=i.confidenceGrade==="A"?"#10B981":i.confidenceGrade==="B"?"#3B82F6":i.confidenceGrade==="C"?"#F59E0B":"#EF4444";return`
793
793
  <tr style="border-bottom: 1px solid #334155;">
794
794
  <td style="padding: 12px; font-weight: bold; color: #F8FAFC;">${i.deviceId}</td>
795
795
  <td style="padding: 12px; color: #94A3B8;">${i.suiteName}</td>
@@ -822,12 +822,12 @@ ${e}`),console.log(D.bold.green(" \u{1F4BE} Recording Session Saved Successful
822
822
  <div class="card header-grid">
823
823
  <div>
824
824
  <h1 style="margin-top: 0; color: #38BDF8;">PromptTest Executive Quality Matrix</h1>
825
- <p style="color: #94A3B8; margin-bottom: 20px;">Generated at ${u.timestamp} across ${u.uniqueDevices.length} target device(s).</p>
825
+ <p style="color: #94A3B8; margin-bottom: 20px;">Generated at ${p.timestamp} across ${p.uniqueDevices.length} target device(s).</p>
826
826
  <div style="display: flex; gap: 24px;">
827
- <div><span style="font-size: 24px; font-weight: bold; color: #F8FAFC;">${u.totalRuns}</span><br><span style="color: #94A3B8; font-size: 12px;">Test Suites</span></div>
828
- <div><span style="font-size: 24px; font-weight: bold; color: #10B981;">${u.passedSteps}</span><br><span style="color: #94A3B8; font-size: 12px;">Passed Steps</span></div>
829
- <div><span style="font-size: 24px; font-weight: bold; color: #EF4444;">${u.failedSteps}</span><br><span style="color: #94A3B8; font-size: 12px;">Failed Steps</span></div>
830
- <div><span style="font-size: 24px; font-weight: bold; color: #38BDF8;">${Math.round(u.overallPassRate*100)}%</span><br><span style="color: #94A3B8; font-size: 12px;">Overall Pass Rate</span></div>
827
+ <div><span style="font-size: 24px; font-weight: bold; color: #F8FAFC;">${p.totalRuns}</span><br><span style="color: #94A3B8; font-size: 12px;">Test Suites</span></div>
828
+ <div><span style="font-size: 24px; font-weight: bold; color: #10B981;">${p.passedSteps}</span><br><span style="color: #94A3B8; font-size: 12px;">Passed Steps</span></div>
829
+ <div><span style="font-size: 24px; font-weight: bold; color: #EF4444;">${p.failedSteps}</span><br><span style="color: #94A3B8; font-size: 12px;">Failed Steps</span></div>
830
+ <div><span style="font-size: 24px; font-weight: bold; color: #38BDF8;">${Math.round(p.overallPassRate*100)}%</span><br><span style="color: #94A3B8; font-size: 12px;">Overall Pass Rate</span></div>
831
831
  </div>
832
832
  </div>
833
833
  <div class="score-badge">
@@ -859,4 +859,4 @@ ${e}`),console.log(D.bold.green(" \u{1F4BE} Recording Session Saved Successful
859
859
  </table>
860
860
  </div>
861
861
  </body>
862
- </html>`}function Wa(u,e,t){return new Ye(u,e,t)}function Ga(u,e,t){return new ut(u,e,t)}function Ka(u){return new tt(u)}function za(){return new He}function Ja(u){return new rt(u)}function Qa(u){return new pt(u)}function qa(u,e){return new je(u,e)}function Za(u,e){return new ct(u,e)}export{Ms as ACTION_KEYWORDS,tt as AndroidDriver,ys as ApiHandler,ut as AutonomousExplorer,pt as AutonomousRecorder,Zt as BackHandler,ct as BaselineManager,T as CONFIG,as as ClearDataHandler,Qt as ClearHandler,us as ConditionalHandler,_t as ConfigError,xi as DESTRUCTIVE_ACTION_PATTERNS,dt as DataSpecLoader,ls as DeepLinkHandler,gt as DeviceError,ms as DeviceStateHandler,Ei as EXTERNAL_INTENT_PATTERNS,Ss as EmailHandler,Cs as ExitCode,lr as GLOBAL_SEED_DICTIONARY,cs as GrantPermissionHandler,Qe as HeuristicResolver,di as IosDriver,At as LLMResolver,ot as LOCALE_PACKS,vi as LOGBOX_PATTERNS,rs as LaunchAppHandler,Ft as LocatorError,Ot as LockError,Pt as Logger,Jt as LongPressHandler,ps as LoopHandler,Ti as MODERATE_DESTRUCTIVE_PATTERNS,He as MemoryEngine,lt as MockAIProvider,bs as OtpHandler,O as PROMPT_ACTION_PATTERNS,Ye as PromptRunner,Fe as PromptTestError,rt as QaReporter,ns as RestartAppHandler,fs as RunJsHandler,Gs as STEP_HANDLER_REGISTRY,Ls as STEP_PREFIX_REGEX,Ns as SUBMIT_KEYWORDS,es as ScrollHandler,is as SelectHandler,je as SemanticFormFiller,gs as SetVariableHandler,mt as SpecRecursionError,ts as SwipeHandler,zt as TapHandler,os as TerminateAppHandler,ss as ToggleHandler,Dt as TypeHandler,Ni as VOLATILE_DATA_PATTERNS,qt as VerifyHandler,ds as WaitHandler,hs as WaitUntilHandler,ft as XML_HIERARCHY_PATTERNS,Ke as acquireDeviceLock,Ri as assembleAstBlocks,Kt as baselineManager,qs as buildDiagnosticError,ai as calculatePercentile,ui as calculateReleaseConfidence,Us as clusterSiblingElements,bn as compareHierarchyNodes,Ne as computeCanonicalSemanticHash,ce as computeHierarchyHash,Ka as createAndroidDriver,Ga as createAutonomousExplorer,Qa as createAutonomousRecorder,Za as createBaselineManager,qa as createFormFiller,za as createMemoryEngine,Wa as createPromptRunner,Ja as createQaReporter,ws as createSemanticResolver,Lt as createSyntheticReport,Yt as detectNavigationParadigm,Hs as detectVisualDefects,Ts as expandSpecIncludes,Rs as extractQuotedText,ti as extractSpecTags,Ge as findActionButtons,it as findCheckableControls,We as findClosestMatches,yt as findDevOverlay,Oe as findDrawerButton,_s as findErrorDialogs,Os as findHeaderActionButtons,we as findInAppBackButton,_e as findInputFields,bt as findListItems,Ut as findNavigationTabs,ir as findNodes,Bs as findScrollableContainers,Zs as findTargetInputField,da as formatBenchmarkTable,ya as formatDoctorReport,si as formatStepTable,Fa as generateAggregatedHtml,ji as generateSyntheticHierarchy,ta as getActiveConfig,ks as getJitteredPollDelay,St as getSeedSynonyms,fi as getSettleFactor,ur as getSupportedLocales,js as getSynonyms,Xe as interpolateVariables,Ee as isDestructiveAction,Pe as isExternalIntentAction,Se as isLogBoxNode,bi as levenshteinDistance,Yi as loadConfig,ke as logger,yn as maskSensitiveValue,It as matchNodes,z as matchesText,Ma as mergeReports,Qs as normalizeSemanticText,X as normalizeText,Fs as parseBounds,ue as parseHierarchyXml,Si as parseHierarchyXmlRegex,wi as parseHierarchyXmlStreaming,Ct as parsePrompt,ei as parseStepRange,dr as registerLocalePack,ze as releaseDeviceLock,sa as resetActiveConfig,W as resolveTokenMatch,la as runBenchmark,ba as runDoctor,ye as scaleSettle,zs as startLiveServer,ka as startRepl,yi as stringSimilarity,Ps as summarizeMetrics,st as unescapeXml};
862
+ </html>`}function Wa(p,e,t){return new Ye(p,e,t)}function Ga(p,e,t){return new ut(p,e,t)}function Ka(p){return new tt(p)}function za(){return new He}function Ja(p){return new rt(p)}function Qa(p){return new pt(p)}function qa(p,e){return new je(p,e)}function Za(p,e){return new ct(p,e)}export{Ms as ACTION_KEYWORDS,tt as AndroidDriver,ys as ApiHandler,ut as AutonomousExplorer,pt as AutonomousRecorder,Zt as BackHandler,ct as BaselineManager,E as CONFIG,as as ClearDataHandler,Qt as ClearHandler,us as ConditionalHandler,_t as ConfigError,Ti as DESTRUCTIVE_ACTION_PATTERNS,dt as DataSpecLoader,ls as DeepLinkHandler,gt as DeviceError,ms as DeviceStateHandler,Pi as EXTERNAL_INTENT_PATTERNS,Ss as EmailHandler,Cs as ExitCode,lr as GLOBAL_SEED_DICTIONARY,cs as GrantPermissionHandler,Qe as HeuristicResolver,ui as IosDriver,At as LLMResolver,ot as LOCALE_PACKS,xi as LOGBOX_PATTERNS,rs as LaunchAppHandler,Ft as LocatorError,Ot as LockError,Pt as Logger,Jt as LongPressHandler,ps as LoopHandler,Ei as MODERATE_DESTRUCTIVE_PATTERNS,He as MemoryEngine,lt as MockAIProvider,bs as OtpHandler,O as PROMPT_ACTION_PATTERNS,Ye as PromptRunner,Fe as PromptTestError,rt as QaReporter,ns as RestartAppHandler,fs as RunJsHandler,Gs as STEP_HANDLER_REGISTRY,Ls as STEP_PREFIX_REGEX,Ns as SUBMIT_KEYWORDS,es as ScrollHandler,is as SelectHandler,je as SemanticFormFiller,gs as SetVariableHandler,mt as SpecRecursionError,ts as SwipeHandler,zt as TapHandler,os as TerminateAppHandler,ss as ToggleHandler,Dt as TypeHandler,Mi as VOLATILE_DATA_PATTERNS,qt as VerifyHandler,ds as WaitHandler,hs as WaitUntilHandler,ft as XML_HIERARCHY_PATTERNS,Ke as acquireDeviceLock,Ni as assembleAstBlocks,Kt as baselineManager,qs as buildDiagnosticError,ci as calculatePercentile,pi as calculateReleaseConfidence,Us as clusterSiblingElements,bn as compareHierarchyNodes,Ne as computeCanonicalSemanticHash,ce as computeHierarchyHash,Ka as createAndroidDriver,Ga as createAutonomousExplorer,Qa as createAutonomousRecorder,Za as createBaselineManager,qa as createFormFiller,za as createMemoryEngine,Wa as createPromptRunner,Ja as createQaReporter,ws as createSemanticResolver,Lt as createSyntheticReport,Yt as detectNavigationParadigm,Hs as detectVisualDefects,Ts as expandSpecIncludes,Rs as extractQuotedText,ti as extractSpecTags,Ge as findActionButtons,it as findCheckableControls,We as findClosestMatches,yt as findDevOverlay,Oe as findDrawerButton,_s as findErrorDialogs,Os as findHeaderActionButtons,we as findInAppBackButton,_e as findInputFields,bt as findListItems,Ut as findNavigationTabs,ir as findNodes,Bs as findScrollableContainers,Zs as findTargetInputField,da as formatBenchmarkTable,ya as formatDoctorReport,si as formatStepTable,Fa as generateAggregatedHtml,ji as generateSyntheticHierarchy,ta as getActiveConfig,ks as getJitteredPollDelay,St as getSeedSynonyms,bi as getSettleFactor,ur as getSupportedLocales,js as getSynonyms,Xe as interpolateVariables,Ee as isDestructiveAction,Pe as isExternalIntentAction,Se as isLogBoxNode,yi as levenshteinDistance,Yi as loadConfig,ke as logger,yn as maskSensitiveValue,It as matchNodes,z as matchesText,Ma as mergeReports,Qs as normalizeSemanticText,X as normalizeText,Fs as parseBounds,ue as parseHierarchyXml,wi as parseHierarchyXmlRegex,vi as parseHierarchyXmlStreaming,Ct as parsePrompt,ei as parseStepRange,dr as registerLocalePack,ze as releaseDeviceLock,sa as resetActiveConfig,W as resolveTokenMatch,la as runBenchmark,ba as runDoctor,ye as scaleSettle,zs as startLiveServer,ka as startRepl,Si as stringSimilarity,Ps as summarizeMetrics,st as unescapeXml};