@verirun/cli 0.1.0 → 0.2.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +296 -34
- package/dist/cli.js +25 -16
- package/dist/gate.mjs +1 -1
- package/dist/graph.mjs +58 -0
- package/man/verirun.1 +194 -6
- package/package.json +9 -2
package/dist/cli.js
CHANGED
|
@@ -1,30 +1,39 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import{createRequire as __cr}from'node:module';const require=__cr(import.meta.url);
|
|
3
|
-
import{createPublicKey as
|
|
4
|
-
`,{mode:384}),await ar(e,384).catch(()=>{})}import{existsSync as we}from"node:fs";import v from"node:path";var U=".verirun";function ur(e=process.cwd()){let r=v.resolve(e),o;for(;;){if(we(v.join(r,".git")))return r;!o&&we(v.join(r,"package.json"))&&(o=r);let n=v.dirname(r);if(n===r)break;r=n}return o??v.resolve(e)}function b(e){let r=ur(e),o=v.join(r,U);return{repoRoot:r,dataDir:o,workflowsDir:v.join(o,"workflows"),runsDir:v.join(o,"runs"),configPath:v.join(o,"config.json")}}function V(e,r){return v.join(e.workflowsDir,`${r}.json`)}function he(e=new Date){return e.toISOString().replace(/[:.]/g,"-")}function ye(e,r,o){return v.join(e.runsDir,`${r}-${o}`)}var Z=1;function fr(e){return e.commands.filter(r=>r.name()!=="help").map(r=>{let o=r.registeredArguments.map(n=>n.required?`<${n.name()}>`:`[${n.name()}]`).join(" ");return{name:r.name(),usage:`verirun ${r.name()}${o?` ${o}`:""}${r.options.length?" [options]":""}`,description:r.description(),options:r.options.map(n=>({flags:n.flags,description:n.description}))}})}async function pr(e){try{return(await be(e)).filter(r=>r.endsWith(".json")).map(r=>r.slice(0,-5)).sort()}catch{return[]}}async function mr(e,r){try{return(await be(e,{withFileTypes:!0})).filter(n=>n.isDirectory()).map(n=>n.name).sort().slice(-r).reverse()}catch{return[]}}async function gr(){let e=b(),r={};try{r=await E(e.configPath)}catch{}let o=["supabase","vercel","railway"].filter(n=>r[n]);return{repoRoot:e.repoRoot,dataDir:e.dataDir,dataDirExists:ve(e.dataDir),configPath:e.configPath,configExists:ve(e.configPath),logSources:[...o],userFilter:typeof r.userFilter=="string"?r.userFilter:null,workflows:await pr(e.workflowsDir),recentRuns:await mr(e.runsDir,5)}}var Se="verirun records a browser workflow once, replays those exact steps headless on demand, and captures the backend logs produced during the replay. Deterministic: the same recording gives the same run and the same answer.",Re=["A human records the workflow once: `verirun record <name> --url <app-url>` (needs a display).","After a code change, run it: `verirun run <name>`. Add `--user <email>` to keep only that user's log lines.","Exit code 0 = every step replayed. Exit code 1 = a step failed, or a licensing / setup error.","Read `.verirun/runs/<name>-<newest>/logs.json`: check `status`; on `failed` read `error` and `steps.failedAt`; then scan `entries` for the backend's side \u2014 a 200 that hid an exception, a write that never landed, a job that threw after the screen said done.","`verirun run` writes logs.json even when replay fails, so partial logs survive.","Do not edit files under `.verirun/workflows/` by hand unless you understand the selector format; re-record instead."];function wr(e,r){let o=[],n=(i="")=>{o.push(i)};n("# verirun \u2014 agent reference"),n(),n(Se),n(),n(`Version ${k}. Full docs: https://get-verirun.duely.in and the bundled README.md / \`man verirun\`.`),n(),n("## This checkout"),n(),n(`- repo root: ${e.repoRoot}`),n(`- data dir: ${e.dataDir} ${e.dataDirExists?"(exists)":"(not created yet)"}`),n(`- config: ${e.configPath} ${e.configExists?"(present)":"(absent)"}`),n(`- log sources: ${e.logSources.length?e.logSources.join(", "):"none configured \u2014 `verirun run` still replays, just with no backend logs"}`),n(`- user filter: ${e.userFilter??"none"}`),n(`- workflows: ${e.workflows.length?e.workflows.join(", "):"none recorded yet"}`),n(`- recent runs: ${e.recentRuns.length?e.recentRuns.join(", "):"none yet"}`),n(),n("Account: `record` and `run` need a connected account (`verirun login`, or `$VERIRUN_LICENSE_KEY` in CI). `verirun whoami` shows status. `--help`, `--version`, `verirun log`, and `verirun agent` do not need one."),n(),n("## Commands");for(let i of r){n(),n(`### ${i.usage}`),i.description&&n(i.description);for(let s of i.options)n(`- \`${s.flags}\` \u2014 ${s.description}`)}return n(),n("## `.verirun/` layout (at the repo root shown above)"),n(),n("```"),n(".verirun/"),n(" config.json log sources, userFilter, testIdAttribute"),n(" workflows/<name>.json one recorded workflow each"),n(" runs/<name>-<timestamp>/logs.json captured logs, one directory per run"),n("```"),n(),n("Per-user, not per-project: `~/.verirun/config.json` (device token), `~/.verirun/state.json` (signed license lease)."),n(),n(`## logs.json (schemaVersion ${Z})`),n(),n("```jsonc"),n("{"),n(` "schemaVersion": ${Z},`),n(' "workflow": "<name>",'),n(' "status": "ok" | "failed", // "failed" => process exit code 1'),n(' "window": { "startedAt": "<ISO>", "endedAt": "<ISO>" },'),n(' "steps": { "total": N, "replayed": N, "failedAt"?: N },'),n(' "error"?: "<message>", // present only when status is "failed"'),n(' "filter"?: { "user": "<needle>" }, // present when --user / config.userFilter narrowed entries'),n(' "sources": [ { "id": "supabase"|"vercel"|"railway", "name": "...", "entries": N } ],'),n(' "entries": ['),n(" {"),n(' "source": "supabase"|"vercel"|"railway",'),n(' "stream": "<sub-stream, e.g. edge_logs / lambda>",'),n(' "timestamp": "<ISO>",'),n(' "level": "<info|warn|error|...>",'),n(' "message": "<rendered log line>",'),n(' "raw": { /* provider payload, untouched */ }'),n(" }"),n(" ]"),n("}"),n("```"),n(),n("`entries` is every source merged and sorted by `timestamp`. When a `--user` filter is active, `entries` and every `sources[].entries` count are post-filter."),n(),n("## Recommended agent loop"),n(),Re.forEach((i,s)=>n(`${s+1}. ${i}`)),n(),n("Save this into your agent context: `verirun agent > .verirun/AGENT.md`, or paste it into `CLAUDE.md` / `.cursorrules` / an AGENTS.md. `verirun agent --json` emits the same information as JSON."),n(),o.join(`
|
|
5
|
-
`)}
|
|
6
|
-
`);
|
|
7
|
-
`)
|
|
3
|
+
import{createPublicKey as On,verify as _n}from"node:crypto";import{readFileSync as Dn}from"node:fs";import br from"node:path";import{fileURLToPath as Vn}from"node:url";import{Command as Un}from"commander";import oe from"node:os";import{setTimeout as Re}from"node:timers/promises";import{spawn as Cr}from"node:child_process";function L(e){let r=process.platform==="darwin"?"open":process.platform==="win32"?"cmd":"xdg-open",o=process.platform==="win32"?["/c","start","",e]:[e];try{let t=Cr(r,o,{stdio:"ignore",detached:!0});t.on("error",()=>{}),t.unref()}catch{}}var Er=!!process.stdout.isTTY&&!process.env.NO_COLOR,T=(e,r)=>Er?`\x1B[${e}m${r}\x1B[0m`:r,n={info:e=>console.log(e),step:e=>console.log(`${T("90","\xB7")} ${e}`),success:e=>console.log(`${T("32","\u2713")} ${e}`),warn:e=>console.warn(`${T("33","!")} ${e}`),error:e=>console.error(`${T("31","\u2717")} ${e}`),dim:e=>T("90",e),bold:e=>T("1",e)};var N="0.2.1";var Ir=1440*60*1e3;function ie(){return import("./gate.mjs")}async function Ce(e){let{getMachineId:r,saveGlobalConfig:o,clearLicenseState:t,loadGlobalConfig:i,resolveServer:s,persistLease:a}=await ie(),c=await i(),l=e.server?e.server.replace(/\/+$/,""):s(c.licenseServer);if(c.token&&!e.force){n.info("This machine is already connected. Run `verirun whoami`, or"),n.info("`verirun login --force` to connect it to a different account.");return}let d=await r(),p=await fetch(`${l}/api/cli/link`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({fingerprint:d,hostname:oe.hostname(),os:`${oe.platform()} ${oe.release()}`,cliVersion:N})}).catch(()=>{});if(!p||!p.ok)throw new Error(`Could not start login against ${l}. Check your connection.`);let f=await p.json(),m=`${f.verifyUrl}?code=${encodeURIComponent(f.userCode)}`;n.info(""),n.info("To connect this machine to your Verirun account:"),n.info(""),n.info(` 1. Open ${n.bold(f.verifyUrl)}`),n.info(` 2. Enter ${n.bold(f.userCode)}`),n.info(""),n.info(n.dim(`(trying to open ${m} for you)`)),L(m),n.info(""),n.step("Waiting for approval in the browser..."),e.server&&await o({licenseServer:l});let h=Date.now()+f.expiresIn*1e3,y=Math.max(2,f.interval)*1e3;for(;Date.now()<h;){await Re(y);let g=await fetch(`${l}/api/cli/link/poll`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({deviceCode:f.deviceCode,fingerprint:d})}).catch(()=>{});if(!g)continue;if(g.status===429){await Re(y);continue}let u=await g.json().catch(()=>({status:"server_error"}));if(u.status==="ok"&&u.token){await o({token:u.token,licenseKey:void 0}),await t();let v={kind:"token",value:u.token,server:l},S=u.license?.lease;if(S){await a(v,S);let $=u.license,j=$?.planName??$?.plan??"trial",x=typeof $?.seats=="number"&&$.seats>1?`, ${$.seats} machine seats`:"";n.success(`Connected. Plan: ${j} (${$?.status??"ok"})${x}.`)}else u.license&&u.license.valid===!1?(n.success("Connected."),u.license.reason==="trial_device_limit"?n.warn("This machine has already been used for the free trial on two other accounts, so record and run are blocked. Email support to request another trial, or subscribe from your account."):n.warn(`The account is connected but not active (${u.license.reason??u.license.status??"unknown"}). Check your subscription at your account page.`)):n.success("Connected.");return}if(u.status!=="pending"){if(u.status==="expired")throw new Error("The code expired. Run `verirun login` again.");if(u.status==="denied")throw new Error("The request was denied in the browser.");if(u.status==="no_license")throw new Error("That account has no license. Contact support.");if(u.status==="fingerprint_mismatch")throw new Error("This machine does not match the one that started the login.")}}throw new Error("Timed out waiting for approval. Run `verirun login` again.")}async function Ee(){let{loadGlobalConfig:e,resolveServer:r,saveGlobalConfig:o,clearLicenseState:t}=await ie(),i=await e(),s=r(i.licenseServer);i.token&&await fetch(`${s}/api/cli/logout`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:i.token})}).catch(()=>{}),await o({token:void 0,licenseKey:void 0}),await t(),n.success("Disconnected this machine. Run `verirun login` to reconnect.")}async function Ie(e){let{resolveCredential:r,checkWithServer:o,persistLease:t,readStoredLease:i}=await ie(),s=await r();if(n.info(""),!s){n.info(n.bold("Verirun: not connected")),n.info(""),n.info(`Run ${n.bold("verirun login")} to connect this machine.`),n.info("");return}let a=e.server?e.server.replace(/\/+$/,""):s.server,c={...s,server:a};n.info(n.bold("Verirun")),n.info(` credential ${s.kind==="token"?"device token":"license key"}`+(process.env.VERIRUN_LICENSE_KEY?n.dim(" (from $VERIRUN_LICENSE_KEY)"):"")),n.info(` server ${a}`);let l=await o(c);if(l.reachable&&l.lease){await t(c,l.lease);let f=(await i(c))?.payload;if(n.info(` status ${n.bold(f?.status??"valid")}`),f?.planName||f?.plan){let m=f.planName&&f.plan&&f.planName!==f.plan?n.dim(` (${f.plan})`):"";n.info(` plan ${f.planName??f.plan}${m}`)}typeof f?.seats=="number"&&n.info(` seats ${f.seats} machine${f.seats===1?"":"s"}`),f?.exp&&n.info(` lease until ${new Date(f.exp*1e3).toISOString()}`),n.info(""),n.info(n.dim("Checked just now, lease signature verified.")),n.info("");return}if(l.reachable&&l.result&&!l.result.valid){n.info(` status ${l.result.status??"invalid"} (${l.result.reason??"\u2014"})`),n.info(""),n.info("record and run will not proceed."),n.info("");return}n.warn(" the license server is not reachable right now.");let d=await i(c);if(d){let p=Math.floor((Date.now()-d.payload.iat*1e3)/Ir);n.info(` lease valid, issued ${p} day${p===1?"":"s"} ago`),n.info(n.dim(" Nags after 15 days offline, stops after 30."))}else n.info(n.dim(" No valid lease stored. Connect to the internet and run this again."));n.info("")}import{existsSync as Pe}from"node:fs";import{mkdir as Vr,readdir as _e,writeFile as Ur}from"node:fs/promises";import{join as Oe}from"node:path";import{existsSync as ae}from"node:fs";import{mkdir as Pr,readFile as je,writeFile as Or}from"node:fs/promises";import _r from"node:path";import{execFile as jr}from"node:child_process";import{chmod as xr}from"node:fs/promises";import Ar from"node:os";import{promisify as Lr}from"node:util";var Nr=Lr(jr);async function se(e,r){if(process.platform!=="win32")try{return await xr(e,r==="dir"?448:384),!0}catch{return!1}let o=Tr();if(!o)return!1;let t=r==="dir"?`${o}:(OI)(CI)F`:`${o}:F`;try{return await Nr("icacls",[e,"/inheritance:r","/grant:r",t],{timeout:1e4,windowsHide:!0}),!0}catch{return!1}}function Tr(){let e=process.env.USERNAME;if(!e)try{e=Ar.userInfo().username}catch{return}if(!e)return;let r=process.env.USERDOMAIN;return r&&r!==e?`${r}\\${e}`:e}var xe="data-testid";async function A(e){let r={};if(ae(e)){let a=await je(e,"utf8");try{r=JSON.parse(a)}catch(c){throw new Error(`Config file is not valid JSON: ${e}`,{cause:c})}}let o=process.env.VERIRUN_SUPABASE_ACCESS_TOKEN;o&&(r.supabase={...r.supabase,accessToken:o});let t=process.env.VERIRUN_RAILWAY_TOKEN;t&&(r.railway={...r.railway,token:t});let i=process.env.VERIRUN_VERCEL_DRAIN_SECRET;i&&(r.vercel={...r.vercel,drainSecret:i});let s=process.env.VERIRUN_VERCEL_TOKEN?.trim();return s&&(r.vercel={...r.vercel,token:s}),r}async function Ae(e,r){let o={};if(ae(e))try{o=JSON.parse(await je(e,"utf8"))}catch(a){throw new Error(`Config file is not valid JSON: ${e}`,{cause:a})}let t={...o,...r,supabase:r.supabase?{...o.supabase,...r.supabase}:o.supabase,vercel:r.vercel?{...o.vercel,...r.vercel}:o.vercel,railway:r.railway?{...o.railway,...r.railway}:o.railway},i=_r.dirname(e),s=ae(i);return await Pr(i,{recursive:!0,mode:448}),s||await se(i,"dir"),await Or(e,`${JSON.stringify(t,null,2)}
|
|
4
|
+
`,{mode:384}),se(e,"file")}import{existsSync as Le}from"node:fs";import C from"node:path";var W=".verirun";function Dr(e=process.cwd()){let r=C.resolve(e),o;for(;;){if(Le(C.join(r,".git")))return r;!o&&Le(C.join(r,"package.json"))&&(o=r);let t=C.dirname(r);if(t===r)break;r=t}return o??C.resolve(e)}function w(e){let r=Dr(e),o=C.join(r,W);return{repoRoot:r,dataDir:o,workflowsDir:C.join(o,"workflows"),runsDir:C.join(o,"runs"),configPath:C.join(o,"config.json")}}function P(e,r){return C.join(e.workflowsDir,`${r}.json`)}function Ne(e=new Date){return e.toISOString().replace(/[:.]/g,"-")}function Te(e,r,o){return C.join(e.runsDir,`${r}-${o}`)}var B=1;function Fr(e){return e.commands.filter(r=>r.name()!=="help").map(r=>{let o=r.registeredArguments.map(t=>t.required?`<${t.name()}>`:`[${t.name()}]`).join(" ");return{name:r.name(),usage:`verirun ${r.name()}${o?` ${o}`:""}${r.options.length?" [options]":""}`,description:r.description(),options:r.options.map(t=>({flags:t.flags,description:t.description}))}})}async function Mr(e){try{return(await _e(e)).filter(r=>r.endsWith(".json")).map(r=>r.slice(0,-5)).sort()}catch{return[]}}async function Wr(e,r){try{return(await _e(e,{withFileTypes:!0})).filter(t=>t.isDirectory()).map(t=>t.name).sort().slice(-r).reverse()}catch{return[]}}async function Br(){let e=w(),r={};try{r=await A(e.configPath)}catch{}let o=["supabase","vercel","railway"].filter(t=>r[t]);return{repoRoot:e.repoRoot,dataDir:e.dataDir,dataDirExists:Pe(e.dataDir),configPath:e.configPath,configExists:Pe(e.configPath),logSources:[...o],userFilter:typeof r.userFilter=="string"?r.userFilter:null,workflows:await Mr(e.workflowsDir),recentRuns:await Wr(e.runsDir,5)}}var ce="verirun records a browser workflow once, replays those exact steps headless on demand, and captures the backend logs produced during the replay. Deterministic: the same recording gives the same run and the same answer. `verirun map` is the static half: it reads a React/TypeScript repo and emits the interaction graph \u2014 every page, the interactive elements on it, where they navigate, and the backend calls they make \u2014 without running anything.",le=["```jsonc","{",' "schemaVersion": 1,',' "name": "<same as the filename>",',' "createdAt": "<ISO>",',' "startUrl": "https://app.example.com/login", // optional',' "browser": "chromium", // chromium | firefox | webkit',' "channel": "chrome", // optional: installed browser',' "steps": [',' { "index": 0, "action": "navigate", "params": { "url": "https://app.example.com/login" }, "signals": [] },',' { "index": 1, "action": "fill", "selector": "role=textbox[name=\\"Email\\"i]", "params": { "text": "ada@example.com" }, "signals": [] },',' { "index": 2, "action": "click", "selector": "role=button[name=\\"Log in\\"i]", "params": {}, "signals": [] }'," ]","}","```","","**Click your way through the app; do not walk it by URL.** Use `navigate` for the","first step, and after that reach a page by clicking the thing that goes there \u2014 a","workflow that jumps between URLs proves nothing about the UI, and a dead link or a","button that stopped submitting still passes. `verirun map --bfs <route> --depth 2`","prints each reachable page with the element that gets you there, and every element","in `map --json` carries the `selector` to click. Navigate mid-workflow only for a","page with no path to it, or to deliberately deep-link into a state.","","Actions and their required `params`: `navigate` (`url`, absolute), `click` /","`dblclick`, `fill` (`text`), `press` (`key`), `check` / `uncheck`, `select`","(`values`), `setInputFiles` (`files`). Everything except `navigate` needs a","`selector`. An unknown action stops the run; `assert*` is skipped with a warning.","`selector` goes straight to `page.locator()`, so it must be Playwright selector",'syntax \u2014 `role=button[name="Log in"i]`, `[data-testid="x"]`, or CSS.'],de=["Anything behind a login needs a browser profile that is already signed in.","Pass the profile to `record` and `run`:","","```bash","# macOS / Linux \u2014 the shell expands ~ before verirun sees it","verirun run <name> --channel chrome --user-data-dir ~/.verirun-profile","verirun record <name> --channel chrome --user-data-dir ~/.verirun-profile","```","","```powershell","# Windows \u2014 cmd and PowerShell do NOT expand ~ inside this argument, so pass an",'# absolute path. A literal ~ creates a directory named "~" and the run silently',"# starts logged out.",'verirun run <name> --channel chrome --user-data-dir "$env:USERPROFILE\\.verirun-profile"',"```","","verirun never expands `~` itself \u2014 the path goes straight through to Playwright.","","The profile has to be created once **by a human**, because identity providers","refuse to authenticate an automation-launched browser:","","```bash","# macOS / Linux",'google-chrome --user-data-dir="$HOME/.verirun-profile" --password-store=basic',"```","","```powershell","# Windows (PowerShell)",'& "$env:ProgramFiles\\Google\\Chrome\\Application\\chrome.exe" `',' --user-data-dir="$env:USERPROFILE\\.verirun-profile"',"```","","Sign in to the app in that window, then close it.","","`--password-store=basic` (and `--use-mock-keychain` on macOS) matter on Unix:","Playwright passes both on every platform, and cookies written under the OS keyring","cannot be decrypted without them \u2014 the run would silently start logged out.","Both switches are Unix-only, so on Windows they are ignored and the profile just","has to be created by the same Windows user that runs verirun. The Windows path is","untested \u2014 if a run there starts logged out despite a signed-in profile, report","that rather than guessing.","","On every platform, do not point `--user-data-dir` at the human's everyday Chrome","profile.","","If you are asked to test a signed-in flow and no such profile exists, say so and","give the command above rather than trying to script the login."],ue=["A human records the workflow once: `verirun record <name> --url <app-url>` (needs a display).","After a code change, run it: `verirun run <name>`. Add `--user <email>` to keep only that user's log lines.","Exit code 0 = every step replayed. Exit code 1 = a step failed, or a licensing / setup error.","Read `.verirun/runs/<name>-<newest>/logs.json`: check `status`; on `failed` read `error` and `steps.failedAt`; then scan `entries` for the backend's side \u2014 a 200 that hid an exception, a write that never landed, a job that threw after the screen said done.","`verirun run` writes logs.json even when replay fails, so partial logs survive.","Do not edit files under `.verirun/workflows/` by hand unless you understand the selector format; re-record instead.","`verirun map` needs no recording and no run: use it to find what a page can do before writing a workflow, `--json` for the whole graph, `--bfs <route> --depth N` for what is reachable from one page."];function Gr(e,r){let o=[],t=(i="")=>{o.push(i)};t("# verirun \u2014 agent reference"),t(),t(ce),t(),t(`Version ${N}. Full docs: https://get-verirun.duely.in and the bundled README.md / \`man verirun\`.`),t(),t("## This checkout"),t(),t(`- repo root: ${e.repoRoot}`),t(`- data dir: ${e.dataDir} ${e.dataDirExists?"(exists)":"(not created yet)"}`),t(`- config: ${e.configPath} ${e.configExists?"(present)":"(absent)"}`),t(`- log sources: ${e.logSources.length?e.logSources.join(", "):"none configured \u2014 `verirun run` still replays, just with no backend logs"}`),t(`- user filter: ${e.userFilter??"none"}`),t(`- workflows: ${e.workflows.length?e.workflows.join(", "):"none recorded yet"}`),t(`- recent runs: ${e.recentRuns.length?e.recentRuns.join(", "):"none yet"}`),t(),t("Account: `record`, `run` and `map` need a connected account (`verirun login`, or `$VERIRUN_LICENSE_KEY` in CI). `verirun whoami` shows status. `--help`, `--version`, `verirun log`, and `verirun agent` do not need one."),t(),t("## Commands");for(let i of r){t(),t(`### ${i.usage}`),i.description&&t(i.description);for(let s of i.options)t(`- \`${s.flags}\` \u2014 ${s.description}`)}t(),t("## `.verirun/` layout (at the repo root shown above)"),t(),t("```"),t(".verirun/"),t(" config.json log sources, userFilter, testIdAttribute"),t(" workflows/<name>.json one recorded workflow each"),t(" runs/<name>-<timestamp>/logs.json captured logs, one directory per run"),t("```"),t(),t("Per-user, not per-project: `~/.verirun/config.json` (device token), `~/.verirun/state.json` (signed license lease)."),t(),t(`## logs.json (schemaVersion ${B})`),t(),t("```jsonc"),t("{"),t(` "schemaVersion": ${B},`),t(' "workflow": "<name>",'),t(' "status": "ok" | "failed", // "failed" => process exit code 1'),t(' "window": { "startedAt": "<ISO>", "endedAt": "<ISO>" },'),t(' "steps": { "total": N, "replayed": N, "failedAt"?: N },'),t(' "error"?: "<message>", // present only when status is "failed"'),t(' "filter"?: { "user": "<needle>" }, // present when --user / config.userFilter narrowed entries'),t(' "sources": [ { "id": "supabase"|"vercel"|"railway", "name": "...", "entries": N } ],'),t(' "entries": ['),t(" {"),t(' "source": "supabase"|"vercel"|"railway",'),t(' "stream": "<sub-stream, e.g. edge_logs / lambda>",'),t(' "timestamp": "<ISO>",'),t(' "level": "<info|warn|error|...>",'),t(' "message": "<rendered log line>",'),t(' "raw": { /* provider payload, untouched */ }'),t(" }"),t(" ]"),t("}"),t("```"),t(),t("`entries` is every source merged and sorted by `timestamp`. When a `--user` filter is active, `entries` and every `sources[].entries` count are post-filter."),t(),t("## Writing a workflow yourself"),t(),t("`verirun map --json` gives every page element a `selector`, a `selectorConfidence` (`high` / `medium` / `low`) and a suggested `action`. That is enough to author `.verirun/workflows/<name>.json` without recording:"),t();for(let i of le)t(i);t(),t("Then `verirun workflow check <name>` (add `--json` for machine-readable findings) validates shape, actions, selectors and params without opening a browser. It cannot tell you a selector matches the live page \u2014 only `verirun run <name>` can. Prefer `high`-confidence selectors; a `low` one is a guess. A recorded workflow is still more faithful, so do not overwrite one with a generated file: pick a different name."),t(),t("## Signed-in runs"),t();for(let i of de)t(i);return t(),t("## Recommended agent loop"),t(),ue.forEach((i,s)=>t(`${s+1}. ${i}`)),t(),t("Save this into your agent context: `verirun agent > .verirun/AGENT.md`, or paste it into `CLAUDE.md` / `.cursorrules` / an AGENTS.md. `verirun agent --json` emits the same information as JSON."),t(),o.join(`
|
|
5
|
+
`)}function Kr(e,r){let o=[],t=(i="")=>{o.push(i)};t("---"),t("name: verirun"),t("description: >-"),t(" Test this app end to end with verirun: map the interaction graph to find what a"),t(" page does, replay a recorded browser workflow, and read the backend logs that the"),t(" replay produced. Use when asked to test a user flow, verify a change end to end,"),t(" reproduce a bug, or find out what a page can do and which API calls it makes."),t("---"),t(),t("# verirun"),t(),t(ce),t(),t("## Decide which command you need"),t(),t("| You want to | Command | Needs a recording? |"),t("|---|---|---|"),t("| Know what a page does / which endpoints it calls | `verirun map` | no |"),t("| Know what is reachable from a page | `verirun map --bfs /route --depth 2` | no |"),t("| Re-run a user flow after a change | `verirun run <name>` | yes |"),t("| Write a test for a flow yourself | `verirun map --json` then author the workflow | no |"),t("| Validate what you wrote | `verirun workflow check <name>` | no |"),t("| Capture a flow faithfully (incl. auth) | ask the human to run `verirun record <name>` | \u2014 |"),t(),t("## Static analysis first \u2014 `verirun map`"),t(),t("`map` reads the source and needs no browser, so reach for it before anything else."),t("It reports every page, the interactive elements on it, where they navigate, and the"),t("backend calls each one makes. `--json` gives the whole graph for programmatic use."),t("Limits to keep in mind: a target computed at runtime shows as `unresolved`, an"),t("endpoint passed through a variable as `?`, and Supabase `.auth.*` calls are not"),t("classified yet. `verirun map --reach` shows how much of each page it actually"),t("attached, so check it before trusting a page that looks empty."),t(),t("## Replay \u2014 `verirun run <name>`"),t(),t("A workflow is either recorded by a human (ground truth) or written by you from the"),t("map (a guess until `run` confirms it). Do not edit a recorded one by hand. Recording"),t("needs a display and a human, so ask for it rather than attempting it. For anything"),t("behind a login, see **Signed-in runs** below."),t(),ue.slice(1).forEach((i,s)=>t(`${s+1}. ${i}`)),t(),t("## Writing a workflow from the map"),t(),t("`verirun map --json` gives each element a `selector`, a `selectorConfidence`"),t("(`high`/`medium`/`low`) and a suggested `action`, so you can author"),t("`.verirun/workflows/<name>.json` yourself instead of asking for a recording:"),t();for(let i of le)t(i);t(),t("Loop: write the file \u2192 `verirun workflow check <name>` (static: shape, actions,"),t("params, selectors \u2014 no browser) \u2192 fix \u2192 `verirun run <name>` to find out whether"),t("the selectors actually match. Prefer `high` confidence; `low` means the selector"),t("matches more than one element. Never overwrite a recorded workflow with a"),t("generated one \u2014 use a new name; a recording is ground truth and yours is a guess."),t(),t("## Signed-in runs"),t();for(let i of de)t(i);return t(),t("## Reading the result"),t(),t(`\`.verirun/runs/<name>-<newest>/logs.json\` (schemaVersion ${B}): check \`status\`;`),t("on `failed` read `error` and `steps.failedAt`; then scan `entries` (every source"),t("merged, sorted by `timestamp`, each with `source` / `level` / `message` / `raw`) for"),t("the backend side of the failure. Exit code 1 means a step failed or setup is wrong."),t(),t("## This checkout"),t(),t(`- repo root: ${e.repoRoot}`),t(`- log sources configured: ${e.logSources.length?e.logSources.join(", "):"none \u2014 `run` replays but captures nothing"}`),t(`- workflows: ${e.workflows.length?e.workflows.join(", "):"none recorded yet"}`),t(),t("## Full reference"),t(),t(`Run \`verirun agent\` for every command and flag (${r.length} commands), the`),t("`.verirun/` layout and the complete `logs.json` schema. `verirun <command> --help`"),t("works for any single one."),t(),o.join(`
|
|
6
|
+
`)}async function De(e,r){let o=await Br(),t=Fr(e);if(r.json){process.stdout.write(`${JSON.stringify({about:ce,version:N,docs:"https://get-verirun.duely.in",checkout:o,commands:t,layout:{config:"<repo>/.verirun/config.json",workflows:"<repo>/.verirun/workflows/<name>.json",runs:"<repo>/.verirun/runs/<name>-<timestamp>/logs.json",userConfig:"~/.verirun/config.json",userState:"~/.verirun/state.json"},logsJsonSchemaVersion:B,signedIn:de.join(`
|
|
7
|
+
`),workflowSchema:{version:1,authoring:le.join(`
|
|
8
|
+
`),validate:"verirun workflow check <name> --json"},agentLoop:ue},null,2)}
|
|
9
|
+
`);return}if(r.skill){let i=`${Kr(o,t)}
|
|
10
|
+
`;if(!r.install){process.stdout.write(i);return}let s=Oe(w().repoRoot,".claude","skills","verirun");await Vr(s,{recursive:!0});let a=Oe(s,"SKILL.md");await Ur(a,i),n.success(`Wrote ${a}`),n.info(n.dim("Claude Code loads it automatically when a task looks like app testing."));return}process.stdout.write(`${Gr(o,t)}
|
|
11
|
+
`)}import{spawnSync as at}from"node:child_process";import{existsSync as ct,readFileSync as lt}from"node:fs";import dt from"node:path";import{createInterface as ut}from"node:readline/promises";var Jr="https://backboard.railway.com/graphql/v2",pe="https://railway.com/account/tokens";async function Ve(e,r,o){let t;try{t=await fetch(Jr,{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({query:r,variables:o})})}catch(s){return{error:s instanceof Error?s.message:String(s)}}let i=await t.json().catch(()=>{});return t.ok?i?.errors?.length?{error:i.errors.map(s=>s.message).filter(Boolean).join("; ")||"GraphQL error"}:i?.data?{data:i.data}:{error:"Railway returned no data."}:{error:i?.errors?.[0]?.message??`HTTP ${t.status}`}}async function G(e){if(e.deploymentId)return{deploymentId:e.deploymentId};if(!e.token||!e.projectId||!e.environmentId||!e.serviceId)return{error:"set railway.deploymentId, or railway.projectId + railway.environmentId + railway.serviceId"};let o=await Ve(e.token,`
|
|
8
12
|
query($input: JSON!) {
|
|
9
13
|
deployments(input: $input, first: 1) {
|
|
10
14
|
edges { node { id status createdAt } }
|
|
11
15
|
}
|
|
12
|
-
}`,{input:{projectId:e.projectId,environmentId:e.environmentId,serviceId:e.serviceId}});if("error"in o)return o;let
|
|
16
|
+
}`,{input:{projectId:e.projectId,environmentId:e.environmentId,serviceId:e.serviceId}});if("error"in o)return o;let t=o.data.deployments.edges[0]?.node;return t?{deploymentId:t.id}:{error:"no deployments found for that project / environment / service"}}async function me(e,r,o,t={}){let i=t.userNeedle?.trim(),s=i?`"${i.replace(/"/g,"")}"`:void 0,c=await Ve(e,`
|
|
13
17
|
query($id: String!, $start: DateTime, $end: DateTime, $filter: String) {
|
|
14
18
|
deploymentLogs(deploymentId: $id, startDate: $start, endDate: $end, filter: $filter, limit: 1000) {
|
|
15
19
|
timestamp message severity tags attributes
|
|
16
20
|
}
|
|
17
|
-
}`,{id:r,start:o.startedAt,end:o.endedAt,filter:s});return"error"in c?c:{entries:Array.isArray(c.data.deploymentLogs)?c.data.deploymentLogs:[]}}function
|
|
18
|
-
`).map(o=>o.trim()).filter(Boolean).map(o=>JSON.parse(o))}function Ar(e){return{source:"vercel",stream:typeof e.source=="string"?e.source:void 0,timestamp:typeof e.timestamp=="number"?new Date(e.timestamp).toISOString():void 0,level:typeof e.level=="string"?e.level:void 0,message:typeof e.message=="string"?e.message:void 0,raw:e}}function Ae(e){return e.vercel?new T(e.vercel):void 0}var xe=["vercel","supabase","railway"];async function Le(e,r){if(e!==void 0&&!xe.includes(e))throw new Error(`Unknown log source "${e}". Use one of: ${xe.join(", ")}.`);let o=b(),n=await E(o.configPath);if(e===void 0){jr(n);return}if(e==="vercel"){await Tr(n,r);return}if(e==="railway"){await Wr(n,r);return}await Ur(n,r)}function jr(e){let r=e.vercel,o=e.supabase,n=e.railway;t.info(""),t.info(t.bold("Log sources")),t.info(""),t.info(` ${"vercel".padEnd(10)} ${r?`configured listener :${r.listenerPort??F}${r.listenerPath??M}`:t.dim("not configured")}`),t.info(` ${"supabase".padEnd(10)} ${o?`configured project ${o.projectRef??t.dim("(no projectRef)")}`:t.dim("not configured")}`),t.info(` ${"railway".padEnd(10)} ${n?`configured ${n.deploymentId?`deployment ${n.deploymentId}`:`service ${n.serviceId??t.dim("(none)")}`}`:t.dim("not configured")}`),t.info(""),t.info(`Run ${t.bold("verirun log vercel")}, ${t.bold("verirun log supabase")} or ${t.bold("verirun log railway")} to connect one.`)}var Nr="https://vercel.com/d?to=%2F%5Bteam%5D%2F~%2Fsettings%2Flog-drains&title=Log%20Drains";async function Tr(e,r){let{configPath:o}=b(),n=e.vercel??{},i=n.listenerPort??F,s=n.listenerPath??M,a=n.drainGraceMs??ie;if(r.listen){await Pr({...n,listenerPort:i,listenerPath:s});return}let c=process.env.VERIRUN_VERCEL_DRAIN_SECRET;if(!!e.vercel&&!r.reconnect){t.info(""),t.info(t.bold("Vercel logs \u2014 connected")),t.info(` endpoint http://localhost:${i}${s}`),t.info(` drain secret ${c?"from $VERIRUN_VERCEL_DRAIN_SECRET":n.drainSecret?"from config.json":t.dim("none \u2014 deliveries are not verified")}`),t.info(` grace ${a}ms`),t.info(` project ${n.project??t.dim("all projects on the drain")}`),t.info(""),t.info(t.dim("--reconnect to change it \xB7 --listen to run the verification listener"));return}if(t.info(""),t.info(t.bold("Connect Vercel logs \u2014 do these in order:")),t.info(""),t.info(" 1. New terminal. Start a tunnel to port "+i+" and copy the https URL it prints:"),t.info(` ${t.bold(`ngrok http ${i}`)}`),t.info(t.dim(` (or: cloudflared tunnel --url http://localhost:${i})`)),t.info(""),t.info(" 2. Another new terminal. Start the listener and leave it running:"),t.info(` ${t.bold("verirun log vercel --listen")}`),t.info(""),t.info(" 3. Vercel page opening now (your team \u2192 Settings \u2192 Log Drains) \u2192 Add a drain:"),t.info(" Sources ......... check "+t.bold("Edge")+" and "+t.bold("Serverless")+", uncheck the rest"),t.info(" Delivery format . "+t.bold("JSON")),t.info(` Endpoint ........ ${t.bold(`<https URL from step 1>${s}`)}`),t.info(" then Save."),t.info(""),t.info(" 4. Vercel shows a Signing Secret. Copy it, paste it below."),!process.stdin.isTTY){t.info(""),t.info(t.dim(" Then: VERIRUN_VERCEL_DRAIN_SECRET=<secret> (or vercel.drainSecret in .verirun/config.json)"));return}x(Nr),t.info("");let u=await S(" Signing secret: ");if(!u){t.warn(" No secret. Deliveries would NOT be verified \u2014 anyone who finds the tunnel URL"),t.warn(" could feed fake logs into your runs.");let m=(await S(" Save without a secret anyway? [y/N]: ")).toLowerCase();if(m!=="y"&&m!=="yes"){t.info(" Nothing saved. Re-run `verirun log vercel` once you have the secret.");return}u=""}let p=await S(" Only one project's logs? Paste its name or prj_\u2026 ID, or press Enter for all: "),f={};u&&(f.drainSecret=u),p&&(f.project=p),await O(o,{vercel:f}),t.info(""),t.info(` Saved to ${t.dim(o)}`),t.success(" Done. `verirun run` starts its own listener \u2014 you only need --listen for tailing.")}async function Pr(e){let r=new T(e,{onEntry:o=>{let n=o.timestamp??new Date().toISOString(),i=(o.level??"log").padEnd(5),s=o.stream?`${o.stream} `:"";t.info(`${t.dim(n)} ${i} ${t.dim(s)}${o.message??""}`)}});await r.start(),e.project&&t.info(t.dim(`Filtering to project "${e.project}".`)),t.info(t.dim("Waiting for deliveries. Press Ctrl+C to stop.")),t.info(""),await new Promise(o=>{let n=()=>{process.off("SIGINT",n),process.off("SIGTERM",n),t.info(""),r.dispose().then(o)};process.on("SIGINT",n),process.on("SIGTERM",n)}),t.step("Listener stopped.")}var se="https://supabase.com/dashboard/account/tokens";async function S(e){if(!process.stdin.isTTY)return"";let r=Lr({input:process.stdin,output:process.stdout});try{return(await r.question(e)).trim()}finally{r.close()}}function _r(){let e=xr("supabase",["projects","list","--output","json"],{encoding:"utf8"});if(!(e.error||e.status!==0))try{let o=JSON.parse(e.stdout).map(n=>({ref:String(n.id??n.ref??n.reference_id??""),name:String(n.name??"")})).filter(n=>n.ref!=="");return o.length>0?o:void 0}catch{return}}async function Dr(e){if(e)return e;let r=_r();if(r&&r.length===1){let n=r[0];return t.info(` project ${n.name} (${n.ref}) ${t.dim("\u2014 from the supabase CLI")}`),n.ref}if(r&&r.length>1){t.info(" Which project?"),r.forEach((i,s)=>t.info(` ${s+1}. ${i.name} (${i.ref})`));let n=Number.parseInt(await S(" Number: "),10)-1;if(r[n])return r[n].ref;t.warn(" Not one of the choices.")}return await S(" Project ref (the <ref> in dashboard/project/<ref>): ")||void 0}async function Or(e,r,o){if(!e.projectRef)throw new Error("--test needs a connected project. Run `verirun log supabase` first.");if(!o)throw new Error("--test needs an access token. Run `verirun log supabase`, or set $VERIRUN_SUPABASE_ACCESS_TOKEN.");let n=new Date,i={startedAt:new Date(n.getTime()-5*6e4).toISOString(),endedAt:n.toISOString()};t.info(""),t.info(`Querying ${r.length} source${r.length===1?"":"s"} for the last 5 minutes\u2026`),t.info("");let s=!1;for(let a of r){let c=await W(e.projectRef,o,a,i);"error"in c?(s=!0,t.error(`${a.padEnd(16)} ${c.error}`)):t.success(`${a.padEnd(16)} ${c.rows.length} row${c.rows.length===1?"":"s"}`)}s&&(process.exitCode=1)}async function Ur(e,r){let{configPath:o}=b(),n=e.supabase??{},i=n.sources&&n.sources.length>0?n.sources:oe,s=process.env.VERIRUN_SUPABASE_ACCESS_TOKEN,a=s??n.accessToken;if(r.test){await Or(n,i,a);return}if(n.projectRef&&a&&!r.reconnect){t.info(""),t.info(t.bold("Supabase logs \u2014 connected")),t.info(` project ${n.projectRef}`),t.info(` token ${s?"from $VERIRUN_SUPABASE_ACCESS_TOKEN":"from config.json"}`),t.info(` sources ${i.join(", ")}`),t.info(""),t.info(t.dim("--reconnect to replace the token \xB7 --test to query the last 5 minutes"));return}if(t.info(""),t.info(t.bold("Connect Supabase logs")),!a||r.reconnect){if(!process.stdin.isTTY){t.info(""),t.info("Not an interactive shell. Set these and re-run:"),t.info(` export VERIRUN_SUPABASE_ACCESS_TOKEN=sbp_... ${t.dim(`(create at ${se})`)}`),t.info(` ${t.dim("and supabase.projectRef in .verirun/config.json")}`);return}t.info(` Opening ${t.bold(se)}`),t.info(' Click "Generate new token", copy it, come back here.'),x(se),t.info("");let m=await S(" Paste the token: ");if(!m){t.warn(" Nothing pasted. No changes made.");return}m.startsWith("sbp_")||t.warn(" That does not look like a Supabase token (expected sbp_\u2026). Saving it anyway."),a=m}let c=await Dr(r.reconnect?void 0:n.projectRef);if(!c){t.warn(" No project ref given. No changes made.");return}let d={projectRef:c};s||(d.accessToken=a),await O(o,{supabase:d}),t.info(""),t.info(` Saved to ${t.dim(o)}`),t.info(" Checking it works\u2026");let u=new Date,p={startedAt:new Date(u.getTime()-5*6e4).toISOString(),endedAt:u.toISOString()},f=await W(c,a,i[0],p);if("error"in f){t.error(` ${i[0]} query failed: ${f.error}`),t.info(t.dim(" Token or project ref looks wrong. Re-run `verirun log supabase --reconnect`.")),process.exitCode=1;return}t.success(` Connected. \`verirun run\` now includes Supabase logs (${i.join(", ")}).`)}function je(e){return!!(e.deploymentId||e.projectId&&e.environmentId&&e.serviceId)}function Vr(e){try{let r=new URL(e.trim());if(!/(^|\.)railway\.(com|app)$/.test(r.hostname))return;let o=r.pathname.match(/\/project\/([^/]+)\/service\/([^/?#]+)/),n=r.searchParams.get("environmentId");return!o||!o[1]||!o[2]||!n?void 0:{projectId:o[1],environmentId:n,serviceId:o[2]}}catch{return}}async function Br(e,r){if(!r)throw new Error("--test needs a token. Run `verirun log railway`, or set $VERIRUN_RAILWAY_TOKEN.");if(!je(e))throw new Error("--test needs a connected deployment. Run `verirun log railway` first.");let o=await B({...e,token:r});if("error"in o)throw new Error(`Railway: ${o.error}`);let n=new Date,i={startedAt:new Date(n.getTime()-5*6e4).toISOString(),endedAt:n.toISOString()};t.info(""),t.info(`Querying deployment ${o.deploymentId} for the last 5 minutes\u2026`);let s=await te(r,o.deploymentId,i);if("error"in s){t.error(`railway ${s.error}`),process.exitCode=1;return}t.success(`railway ${s.entries.length} row${s.entries.length===1?"":"s"}`)}async function Wr(e,r){let{configPath:o}=b(),n=e.railway??{},i=process.env.VERIRUN_RAILWAY_TOKEN,s=i??n.token;if(r.test){await Br(n,s);return}if(s&&je(n)&&!r.reconnect){t.info(""),t.info(t.bold("Railway logs \u2014 connected")),t.info(` token ${i?"from $VERIRUN_RAILWAY_TOKEN":"from config.json"}`),n.deploymentId?t.info(` deployment ${n.deploymentId} ${t.dim("(pinned)")}`):(t.info(` project ${n.projectId}`),t.info(` environment ${n.environmentId}`),t.info(` service ${n.serviceId} ${t.dim("(latest deployment resolved per run)")}`)),t.info(""),t.info(t.dim("--reconnect to change it \xB7 --test to query the last 5 minutes"));return}if(t.info(""),t.info(t.bold("Connect Railway logs \u2014 2 things:")),t.info(""),t.info(` 1. On the page opening now (${re}):`),t.info(' "Create Token" \u2192 name it \u2192 pick your team \u2192 Create \u2192 copy the value.'),t.info(" 2. In Railway, open the service you want logs from. Copy its URL from the"),t.info(" address bar \u2014 looks like:"),t.info(" https://railway.com/project/PROJECT/service/SERVICE?environmentId=ENV"),!process.stdin.isTTY){t.info(""),t.info(t.dim("Then: VERIRUN_RAILWAY_TOKEN=<token>, and railway.projectId / environmentId / serviceId (from that URL) in .verirun/config.json."));return}if(!s||r.reconnect){x(re),t.info("");let u=await S(" Railway token: ");if(!u){t.warn(" Nothing pasted. No changes made.");return}s=u}let a={};i||(a.token=s);let c=Vr(await S(" Service URL (paste the whole thing): "));if(c)a.projectId=c.projectId,a.environmentId=c.environmentId,a.serviceId=c.serviceId;else{t.warn(" Couldn't read that URL. Enter the three IDs from it by hand:");let u=await S(" Project ID: "),p=await S(" Environment ID: "),f=await S(" Service ID: ");if(!u||!p||!f){t.warn(" Need all three. No changes made.");return}a.projectId=u,a.environmentId=p,a.serviceId=f}await O(o,{railway:a}),t.info(""),t.info(` Saved to ${t.dim(o)}`),t.info(" Checking it works\u2026");let d=await B({...n,...a,token:s});if("error"in d){t.error(` ${d.error}`),t.info(t.dim(" Re-run `verirun log railway --reconnect` with the right token / IDs.")),process.exitCode=1;return}t.success(` Connected. Deployment ${d.deploymentId}. \`verirun run\` now includes Railway logs.`)}import{existsSync as gt}from"node:fs";import{mkdir as wt}from"node:fs/promises";import Be from"node:path";import{spawnSync as Fr}from"node:child_process";var Mr={browser:"chromium",channel:"chrome",label:"Chrome",approximated:!1},Gr={browser:"chromium",channel:"msedge",label:"Edge",approximated:!1},Hr={browser:"firefox",label:"Firefox",approximated:!1},Jr={browser:"chromium",label:"Chromium",approximated:!1};function ae(e,r){let o=e.toLowerCase(),n=i=>r?{...i,label:r}:i;if(o.includes("firefox")||o.includes("mozilla"))return n(Hr);if(o.includes("msedge")||o.includes("microsoft-edge")||o.includes("edgemac")||o.includes("microsoftedge"))return n(Gr);if(o.includes("google-chrome")||o.includes("com.google.chrome")||o==="chromehtml"||o.includes("chrome"))return n(Mr);if(o.includes("chromium"))return n(Jr);if(o.includes("safari"))return{browser:"webkit",label:"Safari",approximated:!0};if(o.includes("brave"))return{browser:"chromium",label:"Brave",approximated:!0};if(o.includes("thebrowser")||o.includes("arc"))return{browser:"chromium",label:"Arc",approximated:!0};if(o.includes("vivaldi"))return{browser:"chromium",label:"Vivaldi",approximated:!0};if(o.includes("opera")||o.includes("opr"))return{browser:"chromium",label:"Opera",approximated:!0}}function G(e,r){let o=Fr(e,r,{encoding:"utf8",timeout:4e3});if(!(o.error||o.status!==0))return(o.stdout||"").trim()||void 0}function Kr(){let e=G("xdg-settings",["get","default-web-browser"])??G("xdg-mime",["query","default","x-scheme-handler/https"]);return e?ae(e):void 0}function qr(){let e=G("plutil",["-convert","json","-o","-",`${process.env.HOME}/Library/Preferences/com.apple.LaunchServices/com.apple.launchservices.secure.plist`]);if(e)try{let o=(JSON.parse(e).LSHandlers??[]).find(i=>i.LSHandlerURLScheme==="https"),n=typeof o?.LSHandlerRoleAll=="string"?o.LSHandlerRoleAll:void 0;return n?ae(n):void 0}catch{return}}function Yr(){let r=G("reg",["query","HKCU\\Software\\Microsoft\\Windows\\Shell\\Associations\\UrlAssociations\\https\\UserChoice","/v","ProgId"])?.match(/ProgId\s+REG_SZ\s+(\S+)/i)?.[1];return r?ae(r):void 0}function Ne(){try{if(process.platform==="darwin")return qr();if(process.platform==="linux")return Kr();if(process.platform==="win32")return Yr()}catch{}}import{spawn as zr}from"node:child_process";import{mkdtemp as Qr,readFile as Xr,rm as Zr}from"node:fs/promises";import{createRequire as et}from"node:module";import rt from"node:os";import H from"node:path";var tt=new Set(["name","selector","locator","signals","pageGuid","ariaSnapshot"]);function Te(e){let r={};for(let[o,n]of Object.entries(e))!tt.has(o)&&n!==void 0&&(r[o]=n);return r}function nt(){let e=et(import.meta.url),r=e.resolve("playwright/package.json"),o=e("playwright/package.json"),n=typeof o.bin=="string"?o.bin:o.bin?.playwright;if(!n)throw new Error("Could not locate the Playwright CLI entrypoint in playwright/package.json.");return H.join(H.dirname(r),n)}async function Pe(e){let r=nt(),o=await Qr(H.join(rt.tmpdir(),"verirun-record-")),n=H.join(o,"recording.jsonl"),i=[r,"codegen","--target=jsonl",`--output=${n}`];e.browser&&i.push(`--browser=${e.browser}`),e.channel&&i.push(`--channel=${e.channel}`),e.userDataDir&&i.push(`--user-data-dir=${e.userDataDir}`),e.testIdAttribute&&i.push(`--test-id-attribute=${e.testIdAttribute}`),e.url&&i.push(e.url);try{let s=await new Promise((c,d)=>{let u=zr(process.execPath,i,{stdio:["ignore","inherit","inherit"]});u.on("error",d),u.on("close",p=>c(p))}),a=await Xr(n,"utf8").catch(()=>"");return{...ot(a),exitCode:s}}finally{await Zr(o,{recursive:!0,force:!0})}}function ot(e){let r=e.split(`
|
|
19
|
-
`).filter(i=>i.trim().length>0),o={},n=[];for(let[i,s]of r.entries()){let a;try{a=JSON.parse(s)}catch{continue}if(i===0&&a&&typeof a=="object"&&!("name"in a)){o=a;continue}a&&typeof a=="object"&&"name"in a&&n.push(a)}return{header:o,actions:n}}import{existsSync as it}from"node:fs";import{appendFile as st,readFile as at}from"node:fs/promises";import ct from"node:path";function dt(e){return e.split(`
|
|
20
|
-
`)
|
|
21
|
+
}`,{id:r,start:o.startedAt,end:o.endedAt,filter:s});return"error"in c?c:{entries:Array.isArray(c.data.deploymentLogs)?c.data.deploymentLogs:[]}}function Hr(e){let r=typeof e.severity=="string"?e.severity:void 0;return{source:"railway",stream:r?r.toLowerCase():"deploy",timestamp:typeof e.timestamp=="string"?e.timestamp:void 0,level:r,message:typeof e.message=="string"?e.message:void 0,raw:e}}var fe=class{id="railway";name="Railway";cfg;constructor(r){this.cfg=r}async start(){if(!this.cfg.token)throw new Error("Railway log capture needs an API token. Set VERIRUN_RAILWAY_TOKEN or railway.token in .verirun/config.json.");if(!this.cfg.deploymentId&&!(this.cfg.projectId&&this.cfg.environmentId&&this.cfg.serviceId))throw new Error("Railway log capture needs railway.deploymentId, or railway.projectId + railway.environmentId + railway.serviceId, in .verirun/config.json.")}async collect(r,o){let t=await G(this.cfg);if("error"in t)return n.warn(`Railway: ${t.error}`),[];let i=await me(this.cfg.token,t.deploymentId,o,{userNeedle:r.userFilter});if("error"in i)return n.warn(`Railway: ${i.error}`),[];let s=i.entries.map(Hr);return s.sort((a,c)=>(a.timestamp??"").localeCompare(c.timestamp??"")),s}async dispose(){}};function Ue(e){return e.railway?new fe(e.railway):void 0}var qr="https://api.supabase.com",he=["postgres_logs","edge_logs","auth_logs"],ge=class{id="supabase";name="Supabase";projectRef;accessToken;sources;constructor(r){this.projectRef=r.projectRef,this.accessToken=r.accessToken,this.sources=r.sources&&r.sources.length>0?r.sources:he}async start(){if(!this.projectRef)throw new Error("Supabase log capture needs supabase.projectRef in .verirun/config.json.");if(!this.accessToken)throw new Error("Supabase log capture needs an access token. Set VERIRUN_SUPABASE_ACCESS_TOKEN or supabase.accessToken in .verirun/config.json.")}async collect(r,o){let t=r.userFilter,i=[],s=!1;for(let a of this.sources){let c=await K(this.projectRef,this.accessToken,a,o,{userNeedle:t});if("error"in c){n.warn(`Supabase ${a}: ${c.error}`);continue}t&&!c.serverFiltered&&(s=!0);for(let l of c.rows)i.push(zr(a,l))}return t&&s&&n.info(n.dim("Supabase: user filter applied client-side for a source (more rows pulled).")),i.sort((a,c)=>(a.timestamp??"").localeCompare(c.timestamp??"")),i}async dispose(){}},Yr=/^[A-Za-z0-9._@%+-]{1,256}$/;async function Fe(e,r,o,t){let i=new URL(`/v1/projects/${e}/analytics/endpoints/logs.all`,qr);i.searchParams.set("sql",o),i.searchParams.set("iso_timestamp_start",t.startedAt),i.searchParams.set("iso_timestamp_end",t.endedAt);let s;try{s=await fetch(i,{headers:{Authorization:`Bearer ${r}`,Accept:"application/json"}})}catch(c){return{error:c instanceof Error?c.message:String(c)}}let a=await s.json().catch(()=>{});if(!s.ok){let c=(typeof a?.error=="string"?a.error:a?.error?.message)??a?.message??`HTTP ${s.status}`;return{error:`${c}${c.startsWith("HTTP")?"":` (HTTP ${s.status})`}`}}return{rows:Array.isArray(a?.result)?a.result:[]}}async function K(e,r,o,t,i={}){let s=i.userNeedle?.trim().toLowerCase(),a=s&&Yr.test(s)?s:void 0,c=p=>{let f=p&&a?` where strpos(lower(event_message), '${a}') > 0 or strpos(lower(to_json_string(metadata)), '${a}') > 0`:"";return`select id, timestamp, event_message, metadata from ${o}${f} order by timestamp asc limit 1000`},l=await Fe(e,r,c(!0),t);if(!("error"in l))return{rows:l.rows,serverFiltered:!!a};if(!a)return l;let d=await Fe(e,r,c(!1),t);return"error"in d?d:{rows:d.rows,serverFiltered:!1}}function zr(e,r){return{source:"supabase",stream:e,timestamp:Qr(r.timestamp),message:typeof r.event_message=="string"?r.event_message:void 0,raw:r}}function Qr(e){if(typeof e=="string")return e;if(typeof e=="number"&&Number.isFinite(e)){let r=e>1e14?e/1e3:e;return new Date(r).toISOString()}}function Me(e){return e.supabase?new ge(e.supabase):void 0}import{createHmac as rt,timingSafeEqual as tt}from"node:crypto";import{createServer as nt}from"node:http";import{setTimeout as ot}from"node:timers/promises";var We="https://api.vercel.com",H="https://vercel.com/account/settings/tokens",Xr=8e3,Zr=1500,et=3e3;function we(e){return e?`&teamId=${encodeURIComponent(e)}`:""}async function ye(e,r){let o;try{o=await fetch(`${We}${e}`,{headers:{Authorization:`Bearer ${r}`,Accept:"application/json"}})}catch(i){return{error:i instanceof Error?i.message:String(i)}}let t=await o.json().catch(()=>{});return o.ok?{data:t}:{error:t?.error?.message??`HTTP ${o.status}`}}async function Be(e,r){let o=await ye(`/v9/projects?limit=100${we(r)}`,e);return"error"in o?o:{projects:o.data.projects??[]}}async function Ge(e){let r=await ye("/v2/teams?limit=100",e);return"error"in r?r:{teams:r.data.teams??[]}}async function q(e){if(e.deploymentId)return{deploymentId:e.deploymentId,label:e.deploymentId};if(!e.token)return{error:"no token"};if(!e.projectId)return{error:"no projectId"};let r=e.environment??"production",o=await ye(`/v6/deployments?projectId=${encodeURIComponent(e.projectId)}&limit=1&state=READY&target=${encodeURIComponent(r)}${we(e.teamId)}`,e.token);if("error"in o)return{error:o.error};let t=o.data.deployments?.[0];return t?{deploymentId:t.uid,label:t.url??t.uid}:{error:`no READY ${r} deployment found for this project`}}async function Y(e,r,o){let t=`/v1/projects/${encodeURIComponent(e.projectId)}/deployments/${encodeURIComponent(r)}/runtime-logs?limit=1000${we(e.teamId)}`,i=new AbortController,s=setTimeout(()=>i.abort(),o),a,c=()=>{a&&clearTimeout(a),a=setTimeout(()=>i.abort(),Zr)},l=[];try{let d=await fetch(`${We}${t}`,{headers:{Authorization:`Bearer ${e.token}`,Accept:"application/x-ndjson, application/json"},signal:i.signal});if(!d.ok)return{error:(await d.json().catch(()=>{}))?.error?.message??`HTTP ${d.status}`};if(!d.body)return{rows:l};c();let p=new TextDecoder,f="";for await(let m of d.body){f+=p.decode(m,{stream:!0});let h=f.split(`
|
|
22
|
+
`);f=h.pop()??"";for(let y of h){let g=y.trim();if(g)try{let u=JSON.parse(g);Array.isArray(u)?l.push(...u):l.push(u)}catch{}}c()}}catch(d){if(!(d instanceof Error&&d.name==="AbortError"))return{error:d instanceof Error?d.message:String(d)}}finally{clearTimeout(s),a&&clearTimeout(a)}return{rows:l}}function ve(e){let r=e.requestPath?` ${e.requestMethod??""} ${e.requestPath}`.trim():"",o=e.responseStatusCode?` (${e.responseStatusCode})`:"";return{source:"vercel",...e.source?{stream:e.source}:{},...e.timestampInMs?{timestamp:new Date(e.timestampInMs).toISOString()}:{},...e.level?{level:e.level}:{},message:e.message??`${r}${o}`.trim(),raw:e}}var J=class{id="vercel";name="Vercel";config;constructor(r){this.config=r}async start(){if(!this.config.token)throw new Error("Vercel log capture needs an API token. Run `verirun log vercel`, or set VERIRUN_VERCEL_TOKEN / vercel.token in .verirun/config.json.");if(!this.config.projectId)throw new Error("Vercel log capture needs vercel.projectId. Run `verirun log vercel`.")}async collect(r,o){let t=await q(this.config);if("error"in t)return n.warn(`Vercel: ${t.error}`),[];let i=await Y(this.config,t.deploymentId,this.config.readMs??Xr);if("error"in i)return n.warn(`Vercel: ${i.error}`),[];let s=Date.parse(o.startedAt),a=Date.parse(o.endedAt)+(this.config.tailGraceMs??et);return i.rows.filter(c=>typeof c.timestampInMs!="number"?!0:c.timestampInMs>=s&&c.timestampInMs<=a).map(ve)}async dispose(){}};var z=4319,Q="/drain",be=3e3,V=class{id="vercel";name="Vercel";port;path;secret;graceMs;project;onEntry;server;received=[];droppedByProject=0;constructor(r,o={}){this.port=r.listenerPort??z,this.path=r.listenerPath??Q,this.secret=r.drainSecret,this.graceMs=r.drainGraceMs??be,this.project=r.project?.trim()||void 0,this.onEntry=o.onEntry}projectMatches(r){return this.project?r.projectId===this.project||r.projectName===this.project:!0}async start(){let r=nt((o,t)=>this.handle(o,t));this.server=r,await new Promise((o,t)=>{let i=s=>{t(s.code==="EADDRINUSE"?new Error(`Vercel log listener: port ${this.port} is already in use.`):s)};r.once("error",i),r.listen(this.port,()=>{r.off("error",i),o()})}),n.step(`Vercel log listener on http://localhost:${this.port}${this.path}`)}async collect(){return this.graceMs>0&&await ot(this.graceMs),this.received.length===0&&this.droppedByProject>0&&n.warn(`Vercel: ${this.droppedByProject} log line(s) arrived but none matched project "${this.project}". Check the name/ID in .verirun/config.json (vercel.project).`),[...this.received]}async dispose(){let r=this.server;r&&(this.server=void 0,await new Promise(o=>r.close(()=>o())))}handle(r,o){let t=r.headers["x-vercel-verify"];if(typeof t=="string"&&o.setHeader("x-vercel-verify",t),r.method!=="POST"||!this.matchesPath(r.url)){o.statusCode=r.method==="POST"?404:200,o.end();return}let i=[];r.on("data",s=>i.push(s)),r.on("error",()=>{o.statusCode=400,o.end()}),r.on("end",()=>{let s=Buffer.concat(i);if(!this.verifySignature(r,s)){n.warn("Vercel log drain: rejected a delivery with a bad signature."),o.statusCode=401,o.end();return}try{for(let a of it(s.toString("utf8"))){if(!this.projectMatches(a)){this.droppedByProject+=1;continue}let c=st(a);this.received.push(c),this.onEntry?.(c)}}catch{n.warn("Vercel log drain: could not parse a delivery body.")}o.statusCode=200,o.end()})}matchesPath(r){return r?(r.split("?")[0]??"")===this.path:!1}verifySignature(r,o){if(!this.secret)return!0;let t=r.headers["x-vercel-signature"];if(typeof t!="string")return!1;let i=rt("sha1",this.secret).update(o).digest("hex"),s=Buffer.from(i),a=Buffer.from(t);return s.length===a.length&&tt(s,a)}};function it(e){let r=e.trim();if(!r)return[];if(r.startsWith("[")){let o=JSON.parse(r);return Array.isArray(o)?o:[]}return r.split(`
|
|
23
|
+
`).map(o=>o.trim()).filter(Boolean).map(o=>JSON.parse(o))}function st(e){return{source:"vercel",stream:typeof e.source=="string"?e.source:void 0,timestamp:typeof e.timestamp=="number"?new Date(e.timestamp).toISOString():void 0,level:typeof e.level=="string"?e.level:void 0,message:typeof e.message=="string"?e.message:void 0,raw:e}}function Ke(e){if(e.vercel)return e.vercel.token?new J(e.vercel):new V(e.vercel)}var Je=["vercel","supabase","railway"];async function He(e,r){if(e!==void 0&&!Je.includes(e))throw new Error(`Unknown log source "${e}". Use one of: ${Je.join(", ")}.`);let o=w(),t=await A(o.configPath);if(e===void 0){ft(t);return}if(e==="vercel"){await wt(t,r);return}if(e==="railway"){await Et(t,r);return}await kt(t,r)}function ft(e){let r=e.vercel,o=e.supabase,t=e.railway;n.info(""),n.info(n.bold("Log sources")),n.info(""),n.info(` ${"vercel".padEnd(10)} ${r?.token&&r.projectId?`configured project ${r.projectId}`:r?`drain mode listener :${r.listenerPort??z}${r.listenerPath??Q}`:n.dim("not configured")}`),n.info(` ${"supabase".padEnd(10)} ${o?`configured project ${o.projectRef??n.dim("(no projectRef)")}`:n.dim("not configured")}`),n.info(` ${"railway".padEnd(10)} ${t?`configured ${t.deploymentId?`deployment ${t.deploymentId}`:`service ${t.serviceId??n.dim("(none)")}`}`:n.dim("not configured")}`),n.info(""),n.info(`Run ${n.bold("verirun log vercel")}, ${n.bold("verirun log supabase")} or ${n.bold("verirun log railway")} to connect one.`)}var pt="https://vercel.com/d?to=%2F%5Bteam%5D%2F~%2Fsettings%2Flog-drains&title=Log%20Drains";function mt(e){let r=dt.join(e,".vercel","project.json");if(ct(r))try{let o=JSON.parse(lt(r,"utf8"));return o.projectId?{projectId:o.projectId,...o.orgId?.startsWith("team_")?{teamId:o.orgId}:{}}:void 0}catch{return}}async function gt(e){let r=await Ge(e),o;if("error"in r)n.warn(` Could not list teams: ${r.error}`);else if(r.teams.length===1)o=r.teams[0].id,n.info(` team ${r.teams[0].name??o}`);else if(r.teams.length>1){n.info(" Which team?"),n.info(` 1. ${n.dim("(personal account)")}`),r.teams.forEach((c,l)=>n.info(` ${l+2}. ${c.name??c.slug??c.id}`));let a=Number.parseInt(await b(" Number: "),10)-2;r.teams[a]&&(o=r.teams[a].id)}let t=await Be(e,o);if("error"in t){n.error(` Could not list projects: ${t.error}`);return}if(t.projects.length===0){n.warn(" That token can see no projects.");return}if(t.projects.length===1){let a=t.projects[0];return n.info(` project ${a.name} (${a.id})`),{projectId:a.id,...o?{teamId:o}:{}}}n.info(" Which project?"),t.projects.forEach((a,c)=>n.info(` ${c+1}. ${a.name}`));let i=Number.parseInt(await b(" Number: "),10)-1,s=t.projects[i];if(!s){n.warn(" Not one of the choices.");return}return{projectId:s.id,...o?{teamId:o}:{}}}async function ht(e){if(!e.token||!e.projectId)throw new Error("--test needs a connected project. Run `verirun log vercel` first.");let r=await q(e);if("error"in r){n.error(` ${r.error}`),process.exitCode=1;return}n.info(""),n.info(`Reading runtime logs for ${n.bold(r.label)}\u2026`);let o=await Y(e,r.deploymentId,e.readMs??8e3);if("error"in o){n.error(` ${o.error}`),process.exitCode=1;return}let t=Date.now()-5*6e4,i=o.rows.filter(s=>typeof s.timestampInMs!="number"||s.timestampInMs>=t);n.success(` ${o.rows.length} line(s) on the stream, ${i.length} from the last 5 minutes.`);for(let s of i.slice(-5)){let a=ve(s);n.info(` ${n.dim(a.timestamp??"")} ${a.message??""}`)}o.rows.length===0&&n.info(n.dim(" No lines yet \u2014 hit the deployed app once, then re-run with --test."))}async function wt(e,r){let{configPath:o,repoRoot:t}=w(),i=e.vercel??{},s=process.env.VERIRUN_VERCEL_TOKEN;if(r.drain||r.listen){await yt(e,r);return}if(r.test){await ht(i);return}if(i.token&&i.projectId&&!r.reconnect){n.info(""),n.info(n.bold("Vercel logs \u2014 connected")),n.info(` project ${i.projectId}`),i.teamId&&n.info(` team ${i.teamId}`),n.info(` token ${s?"from $VERIRUN_VERCEL_TOKEN":"from config.json"}`),n.info(` deployment ${i.deploymentId??n.dim(`newest ready ${i.environment??"production"}`)}`),n.info(""),n.info(n.dim("--reconnect to replace it \xB7 --test to read the last 5 minutes"));return}n.info(""),n.info(n.bold("Connect Vercel logs"));let a=s??i.token;if(!a||r.reconnect){if(!process.stdin.isTTY){n.info(""),n.info("Not an interactive shell. Set these and re-run:"),n.info(` export VERIRUN_VERCEL_TOKEN=... ${n.dim(`(create at ${H})`)}`),n.info(` ${n.dim("and vercel.projectId (+ vercel.teamId) in .verirun/config.json")}`);return}n.info(` Opening ${n.bold(H)}`),n.info(" Create a token, copy it, come back here."),L(H),n.info("");let h=await b(" Paste the token: ");if(!h){n.warn(" Nothing pasted. No changes made.");return}a=h}let c=r.reconnect?void 0:mt(t);c&&n.info(` project ${c.projectId} ${n.dim("\u2014 from .vercel/project.json")}`);let l=c??await gt(a);if(!l){n.warn(" No project chosen. No changes made.");return}let d={projectId:l.projectId,...l.teamId?{teamId:l.teamId}:{}};s||(d.token=a),await X(o,{vercel:d}),n.info(""),n.info(` Saved to ${n.dim(o)}`),n.info(" Checking it works\u2026");let p={...i,...d,token:a},f=await q(p);if("error"in f){n.error(` ${f.error}`),n.info(n.dim(" Token or project looks wrong. Re-run `verirun log vercel --reconnect`.")),process.exitCode=1;return}let m=await Y(p,f.deploymentId,4e3);if("error"in m){n.error(` Reading logs failed: ${m.error}`),n.info(n.dim(" The token may lack access to this project. Re-run with --reconnect.")),process.exitCode=1;return}n.success(` Connected to ${f.label}. \`verirun run\` now includes Vercel logs.`),m.rows.length===0&&n.info(n.dim(" (No log lines in the stream right now \u2014 that is normal for an idle app.)"))}async function yt(e,r){let{configPath:o}=w(),t=e.vercel??{},i=t.listenerPort??z,s=t.listenerPath??Q,a=t.drainGraceMs??be;if(r.listen){await vt({...t,listenerPort:i,listenerPath:s});return}let c=process.env.VERIRUN_VERCEL_DRAIN_SECRET;if((t.drainSecret||c)&&!r.reconnect){n.info(""),n.info(n.bold("Vercel logs \u2014 drain mode")),n.info(` endpoint http://localhost:${i}${s}`),n.info(` drain secret ${c?"from $VERIRUN_VERCEL_DRAIN_SECRET":"from config.json"}`),n.info(` grace ${a}ms`),n.info(` project ${t.project??n.dim("all projects on the drain")}`),n.info(""),n.info(n.dim("--reconnect to change it \xB7 --listen to run the verification listener")),n.info(n.dim("`verirun log vercel` (no --drain) switches to the simpler API mode"));return}if(n.info(""),n.info(n.bold("Connect Vercel logs the old way (drain) \u2014 do these in order:")),n.info(n.dim(" You probably want `verirun log vercel` instead: a token, no tunnel.")),n.info(""),n.info(" 1. New terminal. Start a tunnel to port "+i+" and copy the https URL it prints:"),n.info(` ${n.bold(`ngrok http ${i}`)}`),n.info(n.dim(` (or: cloudflared tunnel --url http://localhost:${i})`)),n.info(""),n.info(" 2. Another new terminal. Start the listener and leave it running:"),n.info(` ${n.bold("verirun log vercel --listen")}`),n.info(""),n.info(" 3. Vercel page opening now (your team \u2192 Settings \u2192 Log Drains) \u2192 Add a drain:"),n.info(" Sources ......... check "+n.bold("Edge")+" and "+n.bold("Serverless")+", uncheck the rest"),n.info(" Delivery format . "+n.bold("JSON")),n.info(` Endpoint ........ ${n.bold(`<https URL from step 1>${s}`)}`),n.info(" then Save."),n.info(""),n.info(" 4. Vercel shows a Signing Secret. Copy it, paste it below."),!process.stdin.isTTY){n.info(""),n.info(n.dim(" Then: VERIRUN_VERCEL_DRAIN_SECRET=<secret> (or vercel.drainSecret in .verirun/config.json)"));return}L(pt),n.info("");let l=await b(" Signing secret: ");if(!l){n.warn(" No secret. Deliveries would NOT be verified \u2014 anyone who finds the tunnel URL"),n.warn(" could feed fake logs into your runs.");let f=(await b(" Save without a secret anyway? [y/N]: ")).toLowerCase();if(f!=="y"&&f!=="yes"){n.info(" Nothing saved. Re-run `verirun log vercel --drain` once you have the secret.");return}l=""}let d=await b(" Only one project's logs? Paste its name or prj_\u2026 ID, or press Enter for all: "),p={};l&&(p.drainSecret=l),d&&(p.project=d),await X(o,{vercel:p}),n.info(""),n.info(` Saved to ${n.dim(o)}`),n.success(" Done. `verirun run` starts its own listener \u2014 you only need --listen for tailing.")}async function vt(e){let r=new V(e,{onEntry:o=>{let t=o.timestamp??new Date().toISOString(),i=(o.level??"log").padEnd(5),s=o.stream?`${o.stream} `:"";n.info(`${n.dim(t)} ${i} ${n.dim(s)}${o.message??""}`)}});await r.start(),e.project&&n.info(n.dim(`Filtering to project "${e.project}".`)),n.info(n.dim("Waiting for deliveries. Press Ctrl+C to stop.")),n.info(""),await new Promise(o=>{let t=()=>{process.off("SIGINT",t),process.off("SIGTERM",t),n.info(""),r.dispose().then(o)};process.on("SIGINT",t),process.on("SIGTERM",t)}),n.step("Listener stopped.")}var Se="https://supabase.com/dashboard/account/tokens";async function b(e){if(!process.stdin.isTTY)return"";let r=ut({input:process.stdin,output:process.stdout});try{return(await r.question(e)).trim()}finally{r.close()}}async function X(e,r){await Ae(e,r)||n.warn(`Could not restrict ${e} to your account. It holds an API token \u2014 check its permissions.`)}function bt(){let e=at("supabase",["projects","list","--output","json"],{encoding:"utf8",shell:process.platform==="win32"});if(!(e.error||e.status!==0))try{let o=JSON.parse(e.stdout).map(t=>({ref:String(t.id??t.ref??t.reference_id??""),name:String(t.name??"")})).filter(t=>t.ref!=="");return o.length>0?o:void 0}catch{return}}async function St(e){if(e)return e;let r=bt();if(r&&r.length===1){let t=r[0];return n.info(` project ${t.name} (${t.ref}) ${n.dim("\u2014 from the supabase CLI")}`),t.ref}if(r&&r.length>1){n.info(" Which project?"),r.forEach((i,s)=>n.info(` ${s+1}. ${i.name} (${i.ref})`));let t=Number.parseInt(await b(" Number: "),10)-1;if(r[t])return r[t].ref;n.warn(" Not one of the choices.")}return await b(" Project ref (the <ref> in dashboard/project/<ref>): ")||void 0}async function $t(e,r,o){if(!e.projectRef)throw new Error("--test needs a connected project. Run `verirun log supabase` first.");if(!o)throw new Error("--test needs an access token. Run `verirun log supabase`, or set $VERIRUN_SUPABASE_ACCESS_TOKEN.");let t=new Date,i={startedAt:new Date(t.getTime()-5*6e4).toISOString(),endedAt:t.toISOString()};n.info(""),n.info(`Querying ${r.length} source${r.length===1?"":"s"} for the last 5 minutes\u2026`),n.info("");let s=!1;for(let a of r){let c=await K(e.projectRef,o,a,i);"error"in c?(s=!0,n.error(`${a.padEnd(16)} ${c.error}`)):n.success(`${a.padEnd(16)} ${c.rows.length} row${c.rows.length===1?"":"s"}`)}s&&(process.exitCode=1)}async function kt(e,r){let{configPath:o}=w(),t=e.supabase??{},i=t.sources&&t.sources.length>0?t.sources:he,s=process.env.VERIRUN_SUPABASE_ACCESS_TOKEN,a=s??t.accessToken;if(r.test){await $t(t,i,a);return}if(t.projectRef&&a&&!r.reconnect){n.info(""),n.info(n.bold("Supabase logs \u2014 connected")),n.info(` project ${t.projectRef}`),n.info(` token ${s?"from $VERIRUN_SUPABASE_ACCESS_TOKEN":"from config.json"}`),n.info(` sources ${i.join(", ")}`),n.info(""),n.info(n.dim("--reconnect to replace the token \xB7 --test to query the last 5 minutes"));return}if(n.info(""),n.info(n.bold("Connect Supabase logs")),!a||r.reconnect){if(!process.stdin.isTTY){n.info(""),n.info("Not an interactive shell. Set these and re-run:"),n.info(` export VERIRUN_SUPABASE_ACCESS_TOKEN=sbp_... ${n.dim(`(create at ${Se})`)}`),n.info(` ${n.dim("and supabase.projectRef in .verirun/config.json")}`);return}n.info(` Opening ${n.bold(Se)}`),n.info(' Click "Generate new token", copy it, come back here.'),L(Se),n.info("");let m=await b(" Paste the token: ");if(!m){n.warn(" Nothing pasted. No changes made.");return}m.startsWith("sbp_")||n.warn(" That does not look like a Supabase token (expected sbp_\u2026). Saving it anyway."),a=m}let c=await St(r.reconnect?void 0:t.projectRef);if(!c){n.warn(" No project ref given. No changes made.");return}let l={projectRef:c};s||(l.accessToken=a),await X(o,{supabase:l}),n.info(""),n.info(` Saved to ${n.dim(o)}`),n.info(" Checking it works\u2026");let d=new Date,p={startedAt:new Date(d.getTime()-5*6e4).toISOString(),endedAt:d.toISOString()},f=await K(c,a,i[0],p);if("error"in f){n.error(` ${i[0]} query failed: ${f.error}`),n.info(n.dim(" Token or project ref looks wrong. Re-run `verirun log supabase --reconnect`.")),process.exitCode=1;return}n.success(` Connected. \`verirun run\` now includes Supabase logs (${i.join(", ")}).`)}function qe(e){return!!(e.deploymentId||e.projectId&&e.environmentId&&e.serviceId)}function Rt(e){try{let r=new URL(e.trim());if(!/(^|\.)railway\.(com|app)$/.test(r.hostname))return;let o=r.pathname.match(/\/project\/([^/]+)\/service\/([^/?#]+)/),t=r.searchParams.get("environmentId");return!o||!o[1]||!o[2]||!t?void 0:{projectId:o[1],environmentId:t,serviceId:o[2]}}catch{return}}async function Ct(e,r){if(!r)throw new Error("--test needs a token. Run `verirun log railway`, or set $VERIRUN_RAILWAY_TOKEN.");if(!qe(e))throw new Error("--test needs a connected deployment. Run `verirun log railway` first.");let o=await G({...e,token:r});if("error"in o)throw new Error(`Railway: ${o.error}`);let t=new Date,i={startedAt:new Date(t.getTime()-5*6e4).toISOString(),endedAt:t.toISOString()};n.info(""),n.info(`Querying deployment ${o.deploymentId} for the last 5 minutes\u2026`);let s=await me(r,o.deploymentId,i);if("error"in s){n.error(`railway ${s.error}`),process.exitCode=1;return}n.success(`railway ${s.entries.length} row${s.entries.length===1?"":"s"}`)}async function Et(e,r){let{configPath:o}=w(),t=e.railway??{},i=process.env.VERIRUN_RAILWAY_TOKEN,s=i??t.token;if(r.test){await Ct(t,s);return}if(s&&qe(t)&&!r.reconnect){n.info(""),n.info(n.bold("Railway logs \u2014 connected")),n.info(` token ${i?"from $VERIRUN_RAILWAY_TOKEN":"from config.json"}`),t.deploymentId?n.info(` deployment ${t.deploymentId} ${n.dim("(pinned)")}`):(n.info(` project ${t.projectId}`),n.info(` environment ${t.environmentId}`),n.info(` service ${t.serviceId} ${n.dim("(latest deployment resolved per run)")}`)),n.info(""),n.info(n.dim("--reconnect to change it \xB7 --test to query the last 5 minutes"));return}if(n.info(""),n.info(n.bold("Connect Railway logs \u2014 2 things:")),n.info(""),n.info(` 1. On the page opening now (${pe}):`),n.info(' "Create Token" \u2192 name it \u2192 pick your team \u2192 Create \u2192 copy the value.'),n.info(" 2. In Railway, open the service you want logs from. Copy its URL from the"),n.info(" address bar \u2014 looks like:"),n.info(" https://railway.com/project/PROJECT/service/SERVICE?environmentId=ENV"),!process.stdin.isTTY){n.info(""),n.info(n.dim("Then: VERIRUN_RAILWAY_TOKEN=<token>, and railway.projectId / environmentId / serviceId (from that URL) in .verirun/config.json."));return}if(!s||r.reconnect){L(pe),n.info("");let d=await b(" Railway token: ");if(!d){n.warn(" Nothing pasted. No changes made.");return}s=d}let a={};i||(a.token=s);let c=Rt(await b(" Service URL (paste the whole thing): "));if(c)a.projectId=c.projectId,a.environmentId=c.environmentId,a.serviceId=c.serviceId;else{n.warn(" Couldn't read that URL. Enter the three IDs from it by hand:");let d=await b(" Project ID: "),p=await b(" Environment ID: "),f=await b(" Service ID: ");if(!d||!p||!f){n.warn(" Need all three. No changes made.");return}a.projectId=d,a.environmentId=p,a.serviceId=f}await X(o,{railway:a}),n.info(""),n.info(` Saved to ${n.dim(o)}`),n.info(" Checking it works\u2026");let l=await G({...t,...a,token:s});if("error"in l){n.error(` ${l.error}`),n.info(n.dim(" Re-run `verirun log railway --reconnect` with the right token / IDs.")),process.exitCode=1;return}n.success(` Connected. Deployment ${l.deploymentId}. \`verirun run\` now includes Railway logs.`)}import{existsSync as ze,readFileSync as Qe}from"node:fs";import{mkdir as It,readdir as jt,writeFile as Ye}from"node:fs/promises";import E from"node:path";var xt=new Set(["node_modules",".git",".next",".verirun","dist","build","out","coverage",".turbo",".vercel"]);async function At(e){let r=[],o=async t=>{for(let i of await jt(t,{withFileTypes:!0})){if(i.name.startsWith(".")&&i.name!==".")continue;let s=E.join(t,i.name);if(i.isDirectory()){if(xt.has(i.name))continue;await o(s)}else/\.tsx?$/.test(i.name)&&!i.name.endsWith(".d.ts")&&r.push({file:E.relative(e,s).split(E.sep).join("/"),source:Qe(s,"utf8")})}};return await o(e),r}function Lt(e){let r=E.join(e,"tsconfig.json");if(!ze(r))return{};try{let o=Qe(r,"utf8").replace(/\/\*[\s\S]*?\*\//g,"").replace(/(^|[^:])\/\/.*$/gm,"$1").replace(/,(\s*[}\]])/g,"$1"),t=JSON.parse(o),i={};for(let[s,a]of Object.entries(t.compilerOptions?.paths??{})){let c=a[0];!s.endsWith("/*")||!c?.endsWith("/*")||(i[s.slice(0,-1)]=c.slice(0,-2).replace(/^\.\//,""))}return i}catch{return{}}}function Nt(e,r){let o={...r};for(let t of e??[]){let[i,s]=t.split("=");i&&(o[i]=s??"")}return o}function Tt(e,r){let o=e.nodes.pages.filter(i=>!i.inferred);n.info(`${n.bold(String(o.length))} pages \xB7 ${n.bold(String(e.nodes.leaves.length))} backend effects \xB7 ${n.bold(String(e.edges.length))} edges ${n.dim(`(${r.length} files)`)}`),n.info("");for(let i of e.nodes.pages){let s=e.edges.filter(d=>d.from===i.id),a=s.filter(d=>d.kind==="nav").length,c=s.filter(d=>d.kind==="effect").length,l=i.inferred?n.dim(" (inferred)"):"";n.info(` ${i.path}${l} ${n.dim(`\u2014 ${i.component}, ${i.elements.length} element(s), ${a} nav, ${c} effect`)}`)}let t=e.diagnostics;t.parseErrors.length>0&&n.warn(`${t.parseErrors.length} file(s) failed to parse`),t.unresolvedTargets.length>0&&(n.info(""),n.info(n.dim(`${t.unresolvedTargets.length} nav target(s) could not be resolved to a page`)))}async function Xe(e){let{assertLicensed:r}=await import("./gate.mjs"),{assembleTree:o,bfs:t,buildCoverage:i,measureReach:s,renderBfs:a,renderMarkdown:c,renderReachTable:l}=await import("./graph.mjs"),d=await r();d.note&&n.warn(d.note);let p=w(),f=e.dir?E.resolve(e.dir):p.repoRoot;if(!ze(f))throw new Error(`no such directory: ${f}`);let m=await At(f);if(m.length===0)throw new Error(`no .ts/.tsx files found under ${f}`);let y={aliases:Nt(e.alias,Lt(f)),...e.followChildren===!1?{followChildren:!1}:{},...e.appFile?{appFile:e.appFile}:{}};if(e.bfs){let u=o(m,y),v=e.kind==="nav"||e.kind==="effect"?[e.kind]:void 0,S=t(u,e.bfs,{depth:e.depth?Number(e.depth):2,...v?{kinds:v}:{}});n.info(n.dim(`${S.order.length-1} node(s) within ${S.maxDepth} step(s) of ${S.from}`)),n.info(a(S));return}if(e.reach){let u=s(m,y);n.info(l(u));for(let v of u.unreachedFiles)n.info(n.dim(`unreached: ${v.file} (${v.elements} elements)`));return}let g=o(m,y);if(e.json){process.stdout.write(`${JSON.stringify(g,null,2)}
|
|
24
|
+
`);return}if(e.report){let u=e.out?E.resolve(e.out):E.join(p.dataDir,"map");await It(u,{recursive:!0});let v=i(m,g);await Ye(E.join(u,"interaction-tree.json"),`${JSON.stringify(g,null,2)}
|
|
25
|
+
`),await Ye(E.join(u,"coverage.md"),`${c(v,g)}
|
|
26
|
+
`);let S=E.relative(process.cwd(),u),$=S.startsWith("..")?u:S;n.success(`wrote ${$}/interaction-tree.json + coverage.md`);let j=v.bar.filter(x=>x.pass===!1).length;n.info(n.dim(`${v.bar.length-j}/${v.bar.length} coverage checks pass`));return}Tt(g,m)}import{existsSync as ln}from"node:fs";import{mkdir as dn}from"node:fs/promises";import sr from"node:path";import{spawnSync as Pt}from"node:child_process";var Ot={browser:"chromium",channel:"chrome",label:"Chrome",approximated:!1},_t={browser:"chromium",channel:"msedge",label:"Edge",approximated:!1},Dt={browser:"firefox",label:"Firefox",approximated:!1},Vt={browser:"chromium",label:"Chromium",approximated:!1};function $e(e,r){let o=e.toLowerCase(),t=i=>r?{...i,label:r}:i;if(o.includes("firefox")||o.includes("mozilla"))return t(Dt);if(o.includes("msedge")||o.includes("microsoft-edge")||o.includes("edgemac")||o.includes("microsoftedge"))return t(_t);if(o.includes("google-chrome")||o.includes("com.google.chrome")||o==="chromehtml"||o.includes("chrome"))return t(Ot);if(o.includes("chromium"))return t(Vt);if(o.includes("safari"))return{browser:"webkit",label:"Safari",approximated:!0};if(o.includes("brave"))return{browser:"chromium",label:"Brave",approximated:!0};if(o.includes("thebrowser")||o.includes("arc"))return{browser:"chromium",label:"Arc",approximated:!0};if(o.includes("vivaldi"))return{browser:"chromium",label:"Vivaldi",approximated:!0};if(o.includes("opera")||o.includes("opr"))return{browser:"chromium",label:"Opera",approximated:!0}}function Z(e,r){let o=Pt(e,r,{encoding:"utf8",timeout:4e3});if(!(o.error||o.status!==0))return(o.stdout||"").trim()||void 0}function Ut(){let e=Z("xdg-settings",["get","default-web-browser"])??Z("xdg-mime",["query","default","x-scheme-handler/https"]);return e?$e(e):void 0}function Ft(){let e=Z("plutil",["-convert","json","-o","-",`${process.env.HOME}/Library/Preferences/com.apple.LaunchServices/com.apple.launchservices.secure.plist`]);if(e)try{let o=(JSON.parse(e).LSHandlers??[]).find(i=>i.LSHandlerURLScheme==="https"),t=typeof o?.LSHandlerRoleAll=="string"?o.LSHandlerRoleAll:void 0;return t?$e(t):void 0}catch{return}}function Mt(){let r=Z("reg",["query","HKCU\\Software\\Microsoft\\Windows\\Shell\\Associations\\UrlAssociations\\https\\UserChoice","/v","ProgId"])?.match(/ProgId\s+REG_SZ\s+(\S+)/i)?.[1];return r?$e(r):void 0}function Ze(){try{if(process.platform==="darwin")return Ft();if(process.platform==="linux")return Ut();if(process.platform==="win32")return Mt()}catch{}}import{spawn as Wt}from"node:child_process";import{mkdtemp as Bt,readFile as Gt,rm as Kt}from"node:fs/promises";import{createRequire as Jt}from"node:module";import Ht from"node:os";import ee from"node:path";var qt=new Set(["name","selector","locator","signals","pageGuid","ariaSnapshot"]);function er(e){let r={};for(let[o,t]of Object.entries(e))!qt.has(o)&&t!==void 0&&(r[o]=t);return r}function Yt(){let e=Jt(import.meta.url),r=e.resolve("playwright/package.json"),o=e("playwright/package.json"),t=typeof o.bin=="string"?o.bin:o.bin?.playwright;if(!t)throw new Error("Could not locate the Playwright CLI entrypoint in playwright/package.json.");return ee.join(ee.dirname(r),t)}async function rr(e){let r=Yt(),o=await Bt(ee.join(Ht.tmpdir(),"verirun-record-")),t=ee.join(o,"recording.jsonl"),i=[r,"codegen","--target=jsonl",`--output=${t}`];e.browser&&i.push(`--browser=${e.browser}`),e.channel&&i.push(`--channel=${e.channel}`),e.userDataDir&&i.push(`--user-data-dir=${e.userDataDir}`),e.testIdAttribute&&i.push(`--test-id-attribute=${e.testIdAttribute}`),e.url&&i.push(e.url);try{let s=await new Promise((c,l)=>{let d=Wt(process.execPath,i,{stdio:["ignore","inherit","inherit"]});d.on("error",l),d.on("close",p=>c(p))}),a=await Gt(t,"utf8").catch(()=>"");return{...zt(a),exitCode:s}}finally{await Kt(o,{recursive:!0,force:!0})}}function zt(e){let r=e.split(`
|
|
27
|
+
`).filter(i=>i.trim().length>0),o={},t=[];for(let[i,s]of r.entries()){let a;try{a=JSON.parse(s)}catch{continue}if(i===0&&a&&typeof a=="object"&&!("name"in a)){o=a;continue}a&&typeof a=="object"&&"name"in a&&t.push(a)}return{header:o,actions:t}}import{existsSync as Qt}from"node:fs";import{appendFile as Xt,readFile as Zt}from"node:fs/promises";import en from"node:path";function rn(e){return e.split(`
|
|
28
|
+
`).map(r=>r.trim()).filter(r=>r&&!r.startsWith("#")).some(r=>r.replace(/^\//,"").replace(/\/$/,"")===W)}async function tr(e){let r=en.join(e,".gitignore");if(!Qt(r))return"no-gitignore";let o=await Zt(r,"utf8");if(rn(o))return"already-present";let t=o.length===0||o.endsWith(`
|
|
21
29
|
`)?"":`
|
|
22
|
-
`;return await
|
|
30
|
+
`;return await Xt(r,`${t}
|
|
23
31
|
# verirun: recorded workflows and captured run logs (may contain secrets)
|
|
24
|
-
${
|
|
25
|
-
`,"utf8"),"added"}function
|
|
26
|
-
`,"utf8")}async function
|
|
27
|
-
`,"utf8"),
|
|
32
|
+
${W}/
|
|
33
|
+
`,"utf8"),"added"}function O(e){return`'${e.replace(/\\/g,"\\\\").replace(/'/g,"\\'").replace(/\n/g,"\\n")}'`}function U(e){if(e&&typeof e=="object"&&"source"in e){let r=e;return`/${r.source??""}/${r.flags??""}`}return O(String(e))}function tn(e){let r=e.options??{},o=e.body;switch(e.kind){case"role":{let t=[];r.name!==void 0&&t.push(`name: ${U(r.name)}`),r.exact===!0&&t.push("exact: true");for(let i of r.attrs??[])t.push(`${i.name}: ${JSON.stringify(i.value)}`);return t.length?`getByRole(${O(o)}, { ${t.join(", ")} })`:`getByRole(${O(o)})`}case"test-id":return`getByTestId(${O(o)})`;case"text":case"label":case"placeholder":case"alt":case"title":{let t={text:"getByText",label:"getByLabel",placeholder:"getByPlaceholder",alt:"getByAltText",title:"getByTitle"}[e.kind];return r.exact===!0?`${t}(${U(o)}, { exact: true })`:`${t}(${U(o)})`}case"nth":return`nth(${o})`;case"first":return"first()";case"last":return"last()";case"visible":return`filter({ visible: ${o==="true"} })`;case"frame":return"contentFrame()";case"frame-locator":return`frameLocator(${O(o)})`;case"has-text":return`filter({ hasText: ${U(o)} })`;case"has-not-text":return`filter({ hasNotText: ${U(o)} })`;default:return`locator(${O(o)})`}}function nr(e){if(!e)return;let r=[],o=e;for(;o;)r.push(tn(o)),o=o.next;return r.join(".")}var nn=/^[A-Za-z0-9][A-Za-z0-9._-]*$/;var on=/^(con|prn|aux|nul|com[1-9]|lpt[1-9])$/i;function _(e){if(!e)throw new Error("Workflow name is required.");if(e.length>64)throw new Error("Workflow name must be 64 characters or fewer.");if(!nn.test(e))throw new Error(`Invalid workflow name "${e}". Use letters, digits, dot, dash or underscore, starting with a letter or digit.`);if(e==="."||e==="..")throw new Error(`Invalid workflow name "${e}".`);if(e.endsWith("."))throw new Error(`Invalid workflow name "${e}". A trailing dot is dropped on Windows, so "${e}" and "${e.replace(/\.+$/,"")}" would be the same file.`);let r=e.split(".")[0]??"";if(on.test(r))throw new Error(`Invalid workflow name "${e}". "${r}" is a reserved device name on Windows and cannot be used as a filename.`)}import{mkdir as sn,readFile as an,writeFile as cn}from"node:fs/promises";import or from"node:path";var D=1;async function ir(e,r){await sn(or.dirname(e),{recursive:!0}),await cn(e,`${JSON.stringify(r,null,2)}
|
|
34
|
+
`,"utf8")}async function re(e){let r=await an(e,"utf8"),o;try{o=JSON.parse(r)}catch(i){throw new Error(`Workflow file is not valid JSON: ${e}`,{cause:i})}let t=o;if(!t||typeof t!="object"||!Array.isArray(t.steps))throw new Error(`Workflow file is malformed (no steps array): ${e}`);if(t.schemaVersion!==D)throw new Error(`Workflow "${t.name??or.basename(e)}" uses schema version ${t.schemaVersion}, but this build expects ${D}. Re-record it.`);return t}function un(e){return!(e.name==="openPage"&&e.url==="about:blank")}function fn(e){let r=e.length;for(;r>0&&e[r-1]?.name==="closePage";)r-=1;return e.slice(0,r)}function pn(e,r){let o={index:r,action:e.name,params:er(e),signals:Array.isArray(e.signals)?e.signals:[]};e.selector&&(o.selector=e.selector),e.locator&&(o.locator=e.locator);let t=nr(e.locator);return t&&(o.description=t),e.pageGuid&&(o.pageGuid=e.pageGuid),o}function mn(e){let r=e.description??e.selector??"";switch(e.action){case"navigate":return`navigate ${String(e.params.url??"")}`;case"fill":return`fill ${r} ${n.dim(`= ${JSON.stringify(e.params.text??"")}`)}`;case"press":return`press ${r} ${n.dim(String(e.params.key??""))}`;default:return`${e.action.padEnd(9)} ${r}`.trimEnd()}}async function ar(e,r){let{assertLicensed:o}=await import("./gate.mjs"),t=await o();t.note&&n.warn(t.note),_(e);let i=w(),s=await A(i.configPath),a=P(i,e);if(ln(a)&&!r.force)throw new Error(`Workflow "${e}" already exists at ${sr.relative(i.repoRoot,a)}. Re-run with --force to overwrite it.`);await dn(i.workflowsDir,{recursive:!0});let c=await tr(i.repoRoot);c==="added"?n.step("Added .verirun/ to .gitignore"):c==="no-gitignore"&&n.warn("No .gitignore at the repo root, so .verirun/ is not ignored. Recorded values and run logs may contain secrets.");let l=r.testIdAttribute??s.testIdAttribute??xe,d=r.browser,p=r.channel;if(r.defaultBrowser){(r.browser||r.channel)&&n.warn("--default-browser overrides -b / --channel.");let u=Ze();u?(d=u.browser,p=u.channel,u.approximated?n.warn(`Your default browser is ${u.label}, which Playwright can't drive directly \u2014 recording in ${p??d}.`):n.info(n.dim(`Recording in your default browser: ${u.label}`))):(n.warn("Couldn't detect your default browser; recording in bundled Chromium."),d="chromium",p=void 0)}n.info(""),n.info(`Recording ${n.bold(e)}. A browser window will open.`),n.info(n.dim("Perform the workflow, then close the browser to save.")),n.info("");let f=await rr({url:r.url,browser:d,channel:p,userDataDir:r.userDataDir,testIdAttribute:l}),m=fn(f.actions.filter(un));if(m.length===0){if(f.exitCode!==0)throw new Error(`Playwright codegen exited with code ${f.exitCode} and recorded nothing. If this persists, the installed Playwright may no longer support the \`jsonl\` codegen target that recording depends on.`);n.warn("No actions were recorded, so nothing was saved.");return}let h=m.map(pn),y=h.find(u=>u.action==="navigate"),g={schemaVersion:D,name:e,createdAt:new Date().toISOString(),startUrl:r.url??y?.params.url,browser:f.header.browserName??d??"chromium",channel:p,testIdAttribute:l,steps:h};await ir(a,g),n.info("");for(let u of h)n.info(` ${n.dim(String(u.index).padStart(2))} ${mn(u)}`);n.info(""),n.success(`Saved ${h.length} step${h.length===1?"":"s"} to ${sr.relative(i.repoRoot,a)}`),h.some(u=>u.action==="fill"&&u.params.text)&&n.warn("Recorded steps include text you typed. Check the workflow file before sharing it.")}import{existsSync as Sn}from"node:fs";import{mkdir as $n,writeFile as kn}from"node:fs/promises";import hr from"node:path";import{chromium as F,firefox as gn,selectors as hn,webkit as wn}from"playwright";var yn={chromium:F,firefox:gn,webkit:wn};async function vn(e,r){let o=!r.headed,t=r.slowMoMs&&r.slowMoMs>0?r.slowMoMs:void 0;if(r.cdpEndpoint){let c=await F.connectOverCDP(r.cdpEndpoint,{slowMo:t}),l=c.contexts()[0]??await c.newContext(),d=l.pages()[0]??await l.newPage();return{context:l,page:d,close:()=>c.close()}}if(r.userDataDir){let c=await F.launchPersistentContext(r.userDataDir,{headless:o,channel:r.channel,slowMo:t}),l=c.pages()[0]??await c.newPage();return{context:c,page:l,close:()=>c.close()}}if(r.channel){let c=await F.launch({headless:o,channel:r.channel,slowMo:t}),l=await c.newContext();return{context:l,page:await l.newPage(),close:()=>c.close()}}let s=await(yn[e.browser]??F).launch({headless:o,slowMo:t}),a=await s.newContext();return{context:a,page:await a.newPage(),close:()=>s.close()}}function cr(e){let r=typeof e=="number"?e:0,o=[];return r&1&&o.push("Alt"),r&2&&o.push("Control"),r&4&&o.push("Meta"),r&8&&o.push("Shift"),o}function te(e){return typeof e=="string"?e:void 0}function lr(e){return Array.isArray(e)?e.filter(r=>typeof r=="string"):[]}async function bn(e,r){let o=()=>{if(!r.selector)throw new Error(`Step ${r.index} (${r.action}) has no selector to act on.`);return e.locator(r.selector)};switch(r.action){case"navigate":{let t=te(r.params.url);if(!t)throw new Error(`Step ${r.index} (navigate) has no url.`);await e.goto(t);return}case"openPage":return;case"closePage":await e.close();return;case"click":case"dblclick":{await o().click({button:te(r.params.button)??"left",clickCount:typeof r.params.clickCount=="number"?r.params.clickCount:r.action==="dblclick"?2:1,modifiers:cr(r.params.modifiers)});return}case"fill":await o().fill(te(r.params.text)??"");return;case"press":{let t=te(r.params.key);if(!t)throw new Error(`Step ${r.index} (press) has no key.`);await o().press([...cr(r.params.modifiers),t].join("+"));return}case"check":await o().check();return;case"uncheck":await o().uncheck();return;case"select":await o().selectOption(lr(r.params.options));return;case"setInputFiles":await o().setInputFiles(lr(r.params.files));return;default:if(r.action.startsWith("assert")){n.warn(`Step ${r.index}: skipping ${r.action} (assertions are not replayed).`);return}throw new Error(`Step ${r.index}: don't know how to replay a "${r.action}" action.`)}}async function dr(e,r={}){e.testIdAttribute&&hn.setTestIdAttribute(e.testIdAttribute);let o={...r,channel:r.channel??e.channel},t=await vn(e,o),i=0;try{let{context:s}=t;r.timeoutMs!==void 0&&s.setDefaultTimeout(r.timeoutMs);let a=t.page;s.on("page",c=>{a=c});for(let c of e.steps){n.step(`${String(c.index).padStart(2)} ${c.action}`+(c.description?` ${n.dim(c.description)}`:""));try{await bn(a,c)}catch(l){return{stepsTotal:e.steps.length,stepsReplayed:i,error:l instanceof Error?l:new Error(String(l)),failedStepIndex:c.index}}if(i+=1,a.isClosed()){let l=s.pages().at(-1);l&&(a=l)}}return{stepsTotal:e.steps.length,stepsReplayed:i}}finally{await t.close()}}function ur(e,r){let o=r.toLowerCase();if(!o||typeof e.message=="string"&&e.message.toLowerCase().includes(o))return!0;if(e.raw!==void 0)try{return JSON.stringify(e.raw).toLowerCase().includes(o)}catch{return!1}return!1}var fr=[];function ne(e){fr.push(e)}function pr(e){return fr.map(r=>r(e)).filter(r=>!!r)}var mr=!1;function gr(){mr||(mr=!0,ne(Me),ne(Ke),ne(Ue))}var Rn=1,Cn=500;function En(e){if(e.slowMo!==void 0){let r=Number(e.slowMo);if(!Number.isFinite(r)||r<0)throw new Error(`--slow-mo needs a number of milliseconds, got "${e.slowMo}".`);return r}return e.headed?Cn:0}function M(e){return e instanceof Error?e.message:String(e)}function In(e){return e.replace(/\x1b\[[0-9;]*m/g,"")}async function wr(e){for(let r of[...e].reverse())try{await r.dispose()}catch(o){n.warn(`${r.name}: dispose failed: ${M(o)}`)}}async function yr(e,r){let{assertLicensed:o}=await import("./gate.mjs"),t=await o();t.note&&n.warn(t.note),_(e);let i=w(),s=await A(i.configPath),a=P(i,e);if(!Sn(a))throw new Error(`No workflow named "${e}". Record it first with: verirun record ${e}`);let c=await re(a),l;if(r.timeout!==void 0&&(l=Number(r.timeout),!Number.isFinite(l)||l<0))throw new Error(`--timeout must be a non-negative number of milliseconds, got "${r.timeout}".`);let d=(r.user??s.userFilter)?.trim()||void 0;gr();let p=pr(s),f=Ne(),m=Te(i,e,f);await $n(m,{recursive:!0});let h={config:s,runDir:m,workflowName:e,userFilter:d};n.info(""),n.info(`Running ${n.bold(e)} ${n.dim(`${c.steps.length} steps \xB7 ${c.browser}`)}`),p.length===0?n.warn("No log sources configured. Add a supabase or vercel block to .verirun/config.json."):n.info(n.dim(`Log sources: ${p.map(g=>g.name).join(", ")}`)),d&&n.info(n.dim(`User filter: entries mentioning "${d}"`)),n.info("");let y=[];try{for(let g of p)await g.start(h),y.push(g)}catch(g){let u=p[y.length];throw await wr(y),new Error(`Log source "${u?.name??"?"}" failed to start: ${M(g)}`)}try{let g=new Date().toISOString(),u=await dr(c,{headed:r.headed,slowMoMs:En(r),timeoutMs:l,channel:r.channel,userDataDir:r.userDataDir,cdpEndpoint:r.cdp}),v=new Date().toISOString(),S={startedAt:g,endedAt:v};u.error?n.error(`Replay failed at step ${u.failedStepIndex}: ${M(u.error)}`):n.success(`Replayed ${u.stepsReplayed} step${u.stepsReplayed===1?"":"s"}`);let $=[],j=[],x=0;for(let k of y)try{let I=await k.collect(h,S);x+=I.length,d&&(I=I.filter(Rr=>ur(Rr,d))),j.push(...I),$.push({id:k.id,name:k.name,entries:I.length})}catch(I){n.warn(`${k.name}: log collection failed: ${M(I)}`),$.push({id:k.id,name:k.name,entries:0})}d&&j.length===0&&x>0&&n.warn(`${x} log entr${x===1?"y":"ies"} collected, none mention "${d}".`),j.sort((k,I)=>(k.timestamp??"").localeCompare(I.timestamp??""));let kr={schemaVersion:Rn,workflow:e,status:u.error?"failed":"ok",window:S,steps:{total:u.stepsTotal,replayed:u.stepsReplayed,...u.failedStepIndex!==void 0?{failedAt:u.failedStepIndex}:{}},...u.error?{error:In(M(u.error))}:{},...d?{filter:{user:d}}:{},sources:$,entries:j},ke=hr.join(m,"logs.json");await kn(ke,`${JSON.stringify(kr,null,2)}
|
|
35
|
+
`,"utf8"),n.info("");for(let k of $)n.info(` ${k.name.padEnd(10)} ${k.entries} entr${k.entries===1?"y":"ies"}`);n.info(""),n.success(`Logs written to ${hr.relative(i.repoRoot,ke)}`),u.error&&(process.exitCode=1)}finally{await wr(y)}}import{existsSync as jn}from"node:fs";import xn from"node:path";var An=new Set(["navigate","click","dblclick","fill","press","check","uncheck","select","setInputFiles","openPage","closePage"]),Ln=/^assert/,Nn=new Set(["click","dblclick","fill","press","check","uncheck","select","setInputFiles"]),Tn={navigate:["url"],fill:["text"],press:["key"],select:["values"],setInputFiles:["files"]};function Pn(e){let r=[],o=(i,s,a)=>{r.push({step:i,level:s,message:a})};e.length===0&&r.push({step:0,level:"error",message:"no steps"}),e.forEach((i,s)=>{let a=s+1;if(typeof i.action!="string"||i.action===""){o(a,"error",'missing "action"');return}if(Ln.test(i.action)){o(a,"warning",`"${i.action}" is skipped at replay \u2014 it asserts nothing`);return}if(!An.has(i.action)){o(a,"error",`unknown action "${i.action}" \u2014 a run stops here`);return}Nn.has(i.action)&&!i.selector&&o(a,"error",`"${i.action}" needs a "selector"`);for(let c of Tn[i.action]??[])i.params?.[c]===void 0&&o(a,"error",`"${i.action}" needs params.${c}`);if(i.action==="navigate"){let c=i.params?.url;typeof c=="string"&&!/^https?:\/\//.test(c)&&o(a,"error",`params.url must be absolute, got "${c}"`)}i.selector?.startsWith("role=")&&!/\[name=/.test(i.selector)&&o(a,"warning",`"${i.selector}" matches every such element on the page`),typeof i.index!="number"&&o(a,"warning",`missing "index" \u2014 set it to the step's position`)}),e.length>0&&e[0]?.action!=="navigate"&&r.push({step:1,level:"warning",message:'first step is not "navigate" \u2014 replay opens a blank page, so start with one'});let t=e.map((i,s)=>({step:i,n:s+1})).filter(({step:i,n:s})=>s>1&&i.action==="navigate");for(let{n:i}of t)r.push({step:i,level:"warning",message:"navigating by URL skips the UI \u2014 click the link or button that goes there instead (`verirun map --bfs <route>` names it). Fine only for a deep link with no path to it."});return r}async function vr(e,r,o){if(e!=="check")throw new Error(`Unknown workflow action "${e}". Only "check" exists.`);if(!r)throw new Error("workflow check needs a workflow name or a path to a .json file.");let t=w(),i;if(r.endsWith(".json")?i=xn.resolve(r):(_(r),i=P(t,r)),!jn(i))throw new Error(`No such workflow file: ${i}`);let s=await re(i),a=Pn(s.steps),c=a.filter(l=>l.level==="error");if(o.json){process.stdout.write(`${JSON.stringify({file:i,name:s.name,steps:s.steps.length,ok:c.length===0,findings:a},null,2)}
|
|
36
|
+
`),c.length>0&&(process.exitCode=1);return}n.info(""),n.info(`${n.bold(s.name)} ${n.dim(`\u2014 ${s.steps.length} step(s), schemaVersion ${s.schemaVersion}`)}`),n.info(n.dim(` ${i}`)),n.info("");for(let l of a){let d=`step ${l.step}`.padEnd(8);l.level==="error"?n.error(`${d} ${l.message}`):n.warn(`${d} ${l.message}`)}a.length===0?n.success(` Looks runnable. Try it: verirun run ${s.name}`):c.length===0?(n.info(""),n.success(` No errors. Try it: verirun run ${s.name}`)):(n.info(""),n.error(` ${c.length} error(s) \u2014 a run would fail. Fix them and check again.`),process.exitCode=1),n.info(""),n.info(n.dim(` Static checks only: selectors are not resolved against a page. Schema version ${D}.`))}var Sr="maxex4IKUNrxtTOrel4kbxHVS6xCB67iCHdrJjYp1fz84mMMMqSj5OVHRCJ45wwL0N/zVy0my3fcNQtyPibhCA==",$r="MCowBQYDK2VwAyEATFTl78zmb+BITZuy9mdPMtujnz1tAeVidJT3dccuhLg=";function Fn(){if(Sr.startsWith("@@")||$r.startsWith("@@"))return!0;try{let e=br.dirname(Vn(import.meta.url)),r=Dn(br.join(e,"gate.mjs")),o=On({key:Buffer.from($r,"base64"),format:"der",type:"spki"});return _n(null,r,o,Buffer.from(Sr,"base64"))}catch{return!1}}var R=new Un;R.name("verirun").description("Record and replay app workflows, and capture backend logs for each run.").version(N);R.command("record").argument("<name>","name for the workflow").description("Record a workflow in a headed browser and save it to .verirun/workflows").option("-u, --url <url>","URL to open the browser at").option("-b, --browser <browser>","browser to record in: chromium, firefox or webkit").option("--channel <channel>","use an installed browser: chrome, msedge, chrome-beta, ...").option("--default-browser","record in your OS default browser (falls back to bundled Chromium)").option("--user-data-dir <dir>","record in a persistent profile directory (keeps you logged in)").option("--test-id-attribute <attribute>","attribute to prefer for getByTestId selectors").option("-f, --force","overwrite an existing workflow with this name").action(async(e,r)=>{await ar(e,r)});R.command("run").argument("<name>","name of the workflow to replay").description("Replay a recorded workflow and capture Supabase / Vercel / Railway logs for the run window").option("--headed","run with a visible browser window instead of headless (paced so you can watch)").option("--slow-mo <ms>","pause before each action; default 500 when --headed, 0 otherwise").option("--timeout <ms>","per-action timeout in milliseconds (default: Playwright 30000)").option("--channel <channel>","replay in an installed browser: chrome, msedge, ...").option("--user-data-dir <dir>","replay in a persistent profile directory (keeps you logged in)").option("--cdp <url>","attach to a browser already running with --remote-debugging-port, e.g. http://localhost:9222").option("--user <id>","keep only log entries mentioning this string, e.g. an email (overrides config.userFilter)").action(async(e,r)=>{await yr(e,r)});R.command("login").description("Connect this machine to your Verirun account").option("-f, --force","connect even if this machine is already linked").option("--server <url>","account server base URL (default: https://get-verirun.duely.in)").action(async e=>{await Ce(e)});R.command("logout").description("Disconnect this machine from your Verirun account").action(async()=>{await Ee()});R.command("whoami").description("Show the connected account and subscription status").option("--server <url>","account server base URL").action(async e=>{await Ie(e)});R.command("map").description("Build an interaction graph of this repo: pages, the elements on them, and the backend calls they make").option("-d, --dir <dir>","directory to analyze (default: the repo root)").option("--json","print the full interaction graph as JSON").option("--report","write interaction-tree.json + coverage.md (default: .verirun/map)").option("--out <dir>","output directory for --report").option("--reach","per-route table of reachable vs attached elements").option("--bfs <node>","walk the graph from a node: a route path, page id or component name").option("--depth <n>","steps to follow for --bfs (default: 2)").option("--kind <kind>","--bfs: follow only nav or only effect edges").option("--alias <prefix=dir...>","extra import alias, e.g. @/=src (tsconfig paths are read automatically)").option("--no-follow-children","do not follow child components out of a page file").option("--app-file <file>","file declaring <Routes> (react-router apps; auto-detected by default)").action(async e=>{await Xe(e)});R.command("workflow").argument("<action>","what to do: check").argument("[name]","workflow name, or a path to a .json file").description("Check a workflow file without running it (shape, actions, selectors, params)").option("--json","emit the findings as JSON").action(async(e,r,o)=>{await vr(e,r,o)});R.command("agent").description("Print a compact reference (commands, .verirun/ layout, logs.json schema) for an AI coding agent").option("--json","emit JSON instead of Markdown").option("--skill","emit a Claude Code skill file instead of the plain reference").option("--install","with --skill: write it to .claude/skills/verirun/SKILL.md").action(async e=>{await De(R,e)});R.command("log").argument("[source]","log source to connect: vercel, supabase or railway (omit for an overview)").description("Connect a log source and check its configuration").option("--test","query the last 5 minutes and report what comes back").option("--drain","vercel: set up the old push-based log drain instead of the API").option("--listen","vercel: run the drain listener until Ctrl+C (drain mode only)").option("--reconnect","re-run the connect step and replace what was saved").action(async(e,r)=>{await He(e,r)});async function Mn(){Fn()||(process.stderr.write(`verirun: this installation looks modified. Reinstall it:
|
|
28
37
|
|
|
29
38
|
npm install -g @verirun/cli
|
|
30
|
-
`),process.exit(1));try{await
|
|
39
|
+
`),process.exit(1));try{await R.parseAsync(process.argv)}catch(e){n.error(e instanceof Error?e.message:String(e)),process.exitCode=1}}Mn();
|