@verirun/cli 0.2.4 → 0.2.5
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 +78 -2
- package/dist/cli.js +28 -28
- package/dist/gate.mjs +1 -1
- package/dist/graph.mjs +39 -39
- package/man/verirun.1 +47 -3
- package/package.json +1 -1
package/dist/cli.js
CHANGED
|
@@ -1,42 +1,42 @@
|
|
|
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
|
-
${
|
|
5
|
-
`,{mode:384}),ce(e,"file")}import{existsSync as Oe}from"node:fs";import I from"node:path";var G=".verirun";function qr(e=process.cwd()){let r=I.resolve(e),o;for(;;){if(Oe(I.join(r,".git")))return r;!o&&Oe(I.join(r,"package.json"))&&(o=r);let t=I.dirname(r);if(t===r)break;r=t}return o??I.resolve(e)}function y(e){let r=qr(e),o=I.join(r,G);return{repoRoot:r,dataDir:o,workflowsDir:I.join(o,"workflows"),runsDir:I.join(o,"runs"),configPath:I.join(o,"config.json")}}function _(e,r){return I.join(e.workflowsDir,`${r}.json`)}function De(e=new Date){return e.toISOString().replace(/[:.]/g,"-")}function Ue(e,r,o){return I.join(e.runsDir,`${r}-${o}`)}var H=1;function Qr(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 Zr(e){try{return(await Me(e)).filter(r=>r.endsWith(".json")).map(r=>r.slice(0,-5)).sort()}catch{return[]}}async function et(e,r){try{return(await Me(e,{withFileTypes:!0})).filter(t=>t.isDirectory()).map(t=>t.name).sort().slice(-r).reverse()}catch{return[]}}async function rt(){let e=y(),r={};try{r=await T(e.configPath)}catch{}let o=["supabase","vercel","railway"].filter(t=>r[t]);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 Zr(e.workflowsDir),recentRuns:await et(e.runsDir,5)}}var de="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.",ue=["```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.'],fe=["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."],pe=["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.","If `map` reports every page with 0 elements and 0 effects, its import aliases did not resolve \u2014 it prints the `--alias` flag to re-run with. That is a config gap, not an empty app."];function tt(e,r){let o=[],t=(i="")=>{o.push(i)};t("# verirun \u2014 agent reference"),t(),t(de),t(),t(`Version ${L}. 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 ${H})`),t(),t("```jsonc"),t("{"),t(` "schemaVersion": ${H},`),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 ue)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 fe)t(i);return t(),t("## Recommended agent loop"),t(),pe.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` / an AGENTS.md. `verirun agent --skill --install [claude|cursor|all]` installs it as a skill the agent loads on its own. `verirun agent --json` emits the same information as JSON."),t(),o.join(`
|
|
6
|
-
`)}function
|
|
7
|
-
`)}function
|
|
8
|
-
`).map(c=>c.trim()).join(" ").trim():s?.[1]?.trim()??"",body:t}}function
|
|
9
|
-
`)}var
|
|
10
|
-
`),workflowSchema:{version:1,authoring:
|
|
11
|
-
`),validate:"verirun workflow check <name> --json"},agentLoop:
|
|
12
|
-
`);return}if(r.skill){let i=`${
|
|
13
|
-
`;if(!r.install){process.stdout.write(i);return}let{repoRoot:s}=y();for(let a of
|
|
14
|
-
`)}import{spawnSync as
|
|
3
|
+
import{createPublicKey as uo,verify as fo}from"node:crypto";import{readFileSync as po}from"node:fs";import Nr from"node:path";import{fileURLToPath as mo}from"node:url";import{Command as go}from"commander";import ae from"node:os";import{setTimeout as Te}from"node:timers/promises";var xe=!1,Dr=["https_proxy","HTTPS_PROXY","http_proxy","HTTP_PROXY"];function G(){for(let e of Dr){let r=process.env[e]?.trim();if(r)return r}}function Ur(e,r=process.env.NO_PROXY??process.env.no_proxy){let o=r?.trim();if(!o)return!1;if(o==="*")return!0;let t=e.toLowerCase();return o.split(",").map(i=>i.trim().toLowerCase().replace(/^\./,"").split(":")[0]??"").filter(Boolean).some(i=>t===i||t.endsWith(`.${i}`))}async function Vr(e){if(xe)return;xe=!0;let r=G();if(!r)return;let o;try{o=(typeof e=="string"?new URL(e):e).hostname}catch{return}if(!Ur(o))try{let{ProxyAgent:t,setGlobalDispatcher:i}=await import("undici");i(new t(r))}catch{}}async function C(e,r){return await Vr(e),fetch(e,r)}function Ae(e){let r=Fr(e);if(r)switch(r){case"ENOTFOUND":case"EAI_AGAIN":return`${r} \u2014 the address could not be resolved. A DNS filter or a captive portal will do this.`;case"ECONNREFUSED":case"ECONNRESET":case"EHOSTUNREACH":case"ENETUNREACH":return`${r} \u2014 the connection was blocked. ${je()}`;case"UND_ERR_CONNECT_TIMEOUT":case"ETIMEDOUT":return`${r} \u2014 the connection timed out. ${je()}`;case"UNABLE_TO_GET_ISSUER_CERT_LOCALLY":case"SELF_SIGNED_CERT_IN_CHAIN":case"DEPTH_ZERO_SELF_SIGNED_CERT":case"CERT_HAS_EXPIRED":return`${r} \u2014 the TLS certificate was not trusted. A proxy that inspects traffic causes this; point NODE_EXTRA_CA_CERTS at your organisation's CA file.`;default:return r}}function je(){let e=G();return e?`Reached through the proxy ${e}, so check that the proxy is correct and running.`:"If this network needs a proxy, set HTTPS_PROXY."}function Fr(e){for(let r=e,o=0;r&&o<4;o++){if(typeof r=="object"&&"code"in r&&typeof r.code=="string")return r.code;r=typeof r=="object"&&"cause"in r?r.cause:void 0}}import{spawn as Mr}from"node:child_process";function N(e){let r=process.platform==="darwin"?"open":process.platform==="win32"?"cmd":"xdg-open",o=process.platform==="win32"?["/c","start","",e]:[e];try{let t=Mr(r,o,{stdio:"ignore",detached:!0});t.on("error",()=>{}),t.unref()}catch{}}var Wr=!!process.stdout.isTTY&&!process.env.NO_COLOR,P=(e,r)=>Wr?`\x1B[${e}m${r}\x1B[0m`:r,n={info:e=>console.log(e),step:e=>console.log(`${P("90","\xB7")} ${e}`),success:e=>console.log(`${P("32","\u2713")} ${e}`),warn:e=>console.warn(`${P("33","!")} ${e}`),error:e=>console.error(`${P("31","\u2717")} ${e}`),dim:e=>P("90",e),bold:e=>P("1",e)};var L="0.2.5";var Br=1440*60*1e3;function ce(){return import("./gate.mjs")}async function Ne(e){let{getMachineId:r,saveGlobalConfig:o,clearLicenseState:t,loadGlobalConfig:i,resolveServer:s,persistLease:a}=await ce(),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(),u;try{u=await C(`${l}/api/cli/link`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({fingerprint:d,hostname:ae.hostname(),os:`${ae.platform()} ${ae.release()}`,cliVersion:L})})}catch(w){let f=Ae(w);throw new Error(`Could not reach ${l}.${f?`
|
|
4
|
+
${f}`:" Check your connection."}`)}if(!u.ok)throw new Error(u.status===429?`${l} is rate limiting this machine (429). Wait a few minutes and try again.`:`${l} could not start the login (HTTP ${u.status}). This is a server-side problem, not your connection.`);let p=await u.json(),m=`${p.verifyUrl}?code=${encodeURIComponent(p.userCode)}`;n.info(""),n.info("To connect this machine to your Verirun account:"),n.info(""),n.info(` 1. Open ${n.bold(p.verifyUrl)}`),n.info(` 2. Enter ${n.bold(p.userCode)}`),n.info(""),n.info(n.dim(`(trying to open ${m} for you)`)),N(m),n.info(""),n.step("Waiting for approval in the browser..."),e.server&&await o({licenseServer:l});let g=Date.now()+p.expiresIn*1e3,v=Math.max(2,p.interval)*1e3;for(;Date.now()<g;){await Te(v);let w=await C(`${l}/api/cli/link/poll`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({deviceCode:p.deviceCode,fingerprint:d})}).catch(()=>{});if(!w)continue;if(w.status===429){await Te(v);continue}let f=await w.json().catch(()=>({status:"server_error"}));if(f.status==="ok"&&f.token){await o({token:f.token,licenseKey:void 0}),await t();let h={kind:"token",value:f.token,server:l},$=f.license?.lease;if($){await a(h,$);let E=f.license,j=E?.planName??E?.plan??"trial",A=typeof E?.seats=="number"&&E.seats>1?`, ${E.seats} machine seats`:"";n.success(`Connected. Plan: ${j} (${E?.status??"ok"})${A}.`)}else f.license&&f.license.valid===!1?(n.success("Connected."),f.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 (${f.license.reason??f.license.status??"unknown"}). Check your subscription at your account page.`)):n.success("Connected.");return}if(f.status!=="pending"){if(f.status==="expired")throw new Error("The code expired. Run `verirun login` again.");if(f.status==="denied")throw new Error("The request was denied in the browser.");if(f.status==="no_license")throw new Error("That account has no license. Contact support.");if(f.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 Le(){let{loadGlobalConfig:e,resolveServer:r,saveGlobalConfig:o,clearLicenseState:t}=await ce(),i=await e(),s=r(i.licenseServer);i.token&&await C(`${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 Pe(e){let{resolveCredential:r,checkWithServer:o,persistLease:t,readStoredLease:i,getMachineId:s}=await ce(),a=await r();if(n.info(""),!a){n.info(n.bold("Verirun: not connected")),n.info(""),n.info(`Run ${n.bold("verirun login")} to connect this machine.`),n.info("");return}let c=e.server?e.server.replace(/\/+$/,""):a.server,l={...a,server:c};n.info(n.bold("Verirun")),n.info(` credential ${a.kind==="token"?"device token":"license key"}`+(process.env.VERIRUN_LICENSE_KEY?n.dim(" (from $VERIRUN_LICENSE_KEY)"):"")),n.info(` server ${c}`),n.info(` machine ${(await s()).slice(0,24)}\u2026`);let d=await o(l);if(d.reachable&&d.lease){await t(l,d.lease);let g=(await i(l))?.payload;if(n.info(` status ${n.bold(g?.status??"valid")}`),g?.planName||g?.plan){let v=g.planName&&g.plan&&g.planName!==g.plan?n.dim(` (${g.plan})`):"";n.info(` plan ${g.planName??g.plan}${v}`)}typeof g?.seats=="number"&&n.info(` seats ${g.seats>1e3?"unlimited":`${g.seats} machine${g.seats===1?"":"s"}`}`),g?.exp&&n.info(` lease until ${new Date(g.exp*1e3).toISOString()}`),n.info(""),n.info(n.dim("Checked just now, lease signature verified.")),n.info("");return}if(d.reachable&&d.result&&!d.result.valid){n.info(` status ${d.result.status??"invalid"} (${d.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."),d.detail&&n.info(` reason ${d.detail}`);let u=G();u&&!d.detail?.includes(u)&&n.info(` network using proxy ${u}`);let p=await i(l);if(p){let m=Math.floor((Date.now()-p.payload.iat*1e3)/Br);n.info(` lease valid, issued ${m} day${m===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 Me}from"node:fs";import{mkdir as et,readdir as Be,writeFile as rt}from"node:fs/promises";import{join as We}from"node:path";import{existsSync as de}from"node:fs";import{mkdir as zr,readFile as Oe,writeFile as Xr}from"node:fs/promises";import Qr from"node:path";import{execFile as Gr}from"node:child_process";import{chmod as Hr}from"node:fs/promises";import Jr from"node:os";import{promisify as Kr}from"node:util";var Yr=Kr(Gr);async function le(e,r){if(process.platform!=="win32")try{return await Hr(e,r==="dir"?448:384),!0}catch{return!1}let o=qr();if(!o)return!1;let t=r==="dir"?`${o}:(OI)(CI)F`:`${o}:F`;try{return await Yr("icacls",[e,"/inheritance:r","/grant:r",t],{timeout:1e4,windowsHide:!0}),!0}catch{return!1}}function qr(){let e=process.env.USERNAME;if(!e)try{e=Jr.userInfo().username}catch{return}if(!e)return;let r=process.env.USERDOMAIN;return r&&r!==e?`${r}\\${e}`:e}var _e="data-testid";async function T(e){let r={};if(de(e)){let a=await Oe(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 De(e,r){let o={};if(de(e))try{o=JSON.parse(await Oe(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=Qr.dirname(e),s=de(i);return await zr(i,{recursive:!0,mode:448}),s||await le(i,"dir"),await Xr(e,`${JSON.stringify(t,null,2)}
|
|
5
|
+
`,{mode:384}),le(e,"file")}import{existsSync as Ue}from"node:fs";import I from"node:path";var H=".verirun";function Zr(e=process.cwd()){let r=I.resolve(e),o;for(;;){if(Ue(I.join(r,".git")))return r;!o&&Ue(I.join(r,"package.json"))&&(o=r);let t=I.dirname(r);if(t===r)break;r=t}return o??I.resolve(e)}function y(e){let r=Zr(e),o=I.join(r,H);return{repoRoot:r,dataDir:o,workflowsDir:I.join(o,"workflows"),runsDir:I.join(o,"runs"),configPath:I.join(o,"config.json")}}function O(e,r){return I.join(e.workflowsDir,`${r}.json`)}function Ve(e=new Date){return e.toISOString().replace(/[:.]/g,"-")}function Fe(e,r,o){return I.join(e.runsDir,`${r}-${o}`)}var J=1;function tt(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 nt(e){try{return(await Be(e)).filter(r=>r.endsWith(".json")).map(r=>r.slice(0,-5)).sort()}catch{return[]}}async function ot(e,r){try{return(await Be(e,{withFileTypes:!0})).filter(t=>t.isDirectory()).map(t=>t.name).sort().slice(-r).reverse()}catch{return[]}}async function it(){let e=y(),r={};try{r=await T(e.configPath)}catch{}let o=["supabase","vercel","railway"].filter(t=>r[t]);return{repoRoot:e.repoRoot,dataDir:e.dataDir,dataDirExists:Me(e.dataDir),configPath:e.configPath,configExists:Me(e.configPath),logSources:[...o],userFilter:typeof r.userFilter=="string"?r.userFilter:null,workflows:await nt(e.workflowsDir),recentRuns:await ot(e.runsDir,5)}}var ue="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.",fe=["```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.","A step that opens a browser dialog (alert / confirm / prompt) may carry",'`"dialog": { "action": "accept" | "dismiss", "promptText"?: "..." }` \u2014 `accept` is',"OK, `dismiss` is Cancel. Without it the run answers with `--dialog` (default accept).","In `map --json` such an element carries `dialogs`. `gates: true` means the handler","reads the answer, so pick the path on purpose: with `dismiss` the guarded backend","call does not happen (its `guardSource` names the dialog). After `verirun map","--report`, `workflow check` warns about a dialog-opening step with no `dialog`.","`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.'],pe=["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."],me=["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.","If `map` reports every page with 0 elements and 0 effects, its import aliases did not resolve \u2014 it prints the `--alias` flag to re-run with. That is a config gap, not an empty app."];function st(e,r){let o=[],t=(i="")=>{o.push(i)};t("# verirun \u2014 agent reference"),t(),t(ue),t(),t(`Version ${L}. 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 ${J})`),t(),t("```jsonc"),t("{"),t(` "schemaVersion": ${J},`),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(' "dialogs": [ // browser dialogs the replay answered, in order'),t(' { "step"?: N, "type": "alert"|"confirm"|"prompt"|"beforeunload", "message": "...",'),t(' "defaultValue"?: "...", "action": "accept"|"dismiss", "promptText"?: "...", "at": "<ISO>" }'),t(" ],"),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 fe)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 pe)t(i);return t(),t("## Recommended agent loop"),t(),me.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` / an AGENTS.md. `verirun agent --skill --install [claude|cursor|all]` installs it as a skill the agent loads on its own. `verirun agent --json` emits the same information as JSON."),t(),o.join(`
|
|
6
|
+
`)}function at(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(ue),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(),t("If every page comes back with 0 elements and 0 effects, the import aliases did not"),t("resolve \u2014 `map` prints the `--alias` flag to re-run with. Do that before concluding"),t("the app has nothing in it."),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(),me.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 fe)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 pe)t(i);return t(),t("## Reading the result"),t(),t(`\`.verirun/runs/<name>-<newest>/logs.json\` (schemaVersion ${J}): 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(`
|
|
7
|
+
`)}function ct(e){let r=/^---\n([\s\S]*?)\n---\n([\s\S]*)$/.exec(e);if(!r)return{description:"",body:e};let[,o="",t=""]=r,i=/description:\s*>-?\n([\s\S]*?)(?:\n\S|$)/.exec(o),s=/description:\s*(.+)/.exec(o);return{description:i?.[1]?i[1].split(`
|
|
8
|
+
`).map(c=>c.trim()).join(" ").trim():s?.[1]?.trim()??"",body:t}}function lt(e){let{description:r,body:o}=ct(e);return["---",`description: ${r}`,"globs:","alwaysApply: false","---","",o.replace(/^\n+/,"")].join(`
|
|
9
|
+
`)}var Ge={claude:{label:"Claude Code",path:[".claude","skills","verirun","SKILL.md"],note:"Claude Code loads it automatically when a task looks like app testing.",render:e=>e},cursor:{label:"Cursor",path:[".cursor","rules","verirun.mdc"],note:"Cursor loads it when a task matches its description. Restart Cursor, or reopen the project, to pick it up.",render:lt}};function dt(e){if(e===!0)return["claude"];let r=String(e).toLowerCase();if(r==="all"||r==="both")return["claude","cursor"];if(r in Ge)return[r];throw new Error(`Unknown --install target "${e}". Use claude, cursor, all, or --install on its own for Claude Code.`)}async function He(e,r){let o=await it(),t=tt(e);if(r.json){process.stdout.write(`${JSON.stringify({about:ue,version:L,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:J,signedIn:pe.join(`
|
|
10
|
+
`),workflowSchema:{version:1,authoring:fe.join(`
|
|
11
|
+
`),validate:"verirun workflow check <name> --json"},agentLoop:me},null,2)}
|
|
12
|
+
`);return}if(r.skill){let i=`${at(o,t)}
|
|
13
|
+
`;if(!r.install){process.stdout.write(i);return}let{repoRoot:s}=y();for(let a of dt(r.install)){let c=Ge[a],l=We(s,...c.path);await et(We(s,...c.path.slice(0,-1)),{recursive:!0}),await rt(l,c.render(i)),n.success(`Wrote ${l} ${n.dim(`(${c.label})`)}`),n.info(n.dim(` ${c.note}`))}return}process.stdout.write(`${st(o,t)}
|
|
14
|
+
`)}import{spawnSync as Ct}from"node:child_process";import{existsSync as It,readFileSync as xt}from"node:fs";import jt from"node:path";import{createInterface as At}from"node:readline/promises";var ut="https://backboard.railway.com/graphql/v2",he="https://railway.com/account/tokens";async function Je(e,r,o){let t;try{t=await C(ut,{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 K(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 Je(e.token,`
|
|
15
15
|
query($input: JSON!) {
|
|
16
16
|
deployments(input: $input, first: 1) {
|
|
17
17
|
edges { node { id status createdAt } }
|
|
18
18
|
}
|
|
19
|
-
}`,{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
|
|
19
|
+
}`,{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 we(e,r,o,t={}){let i=t.userNeedle?.trim(),s=i?`"${i.replace(/"/g,"")}"`:void 0,c=await Je(e,`
|
|
20
20
|
query($id: String!, $start: DateTime, $end: DateTime, $filter: String) {
|
|
21
21
|
deploymentLogs(deploymentId: $id, startDate: $start, endDate: $end, filter: $filter, limit: 1000) {
|
|
22
22
|
timestamp message severity tags attributes
|
|
23
23
|
}
|
|
24
|
-
}`,{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
|
|
25
|
-
`);p=
|
|
26
|
-
`).map(o=>o.trim()).filter(Boolean).map(o=>JSON.parse(o))}function $t(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 ze(e){if(e.vercel)return e.vercel.token?new Y(e.vercel):new V(e.vercel)}var Qe=["vercel","supabase","railway"];async function Ze(e,r){if(e!==void 0&&!Qe.includes(e))throw new Error(`Unknown log source "${e}". Use one of: ${Qe.join(", ")}.`);let o=y(),t=await T(o.configPath);if(e===void 0){It(t);return}if(e==="vercel"){await Nt(t,r);return}if(e==="railway"){await Mt(t,r);return}await Ut(t,r)}function It(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??Q}${r.listenerPath??Z}`: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 jt="https://vercel.com/d?to=%2F%5Bteam%5D%2F~%2Fsettings%2Flog-drains&title=Log%20Drains";function xt(e){let r=Et.join(e,".vercel","project.json");if(kt(r))try{let o=JSON.parse(Rt(r,"utf8"));return o.projectId?{projectId:o.projectId,...o.orgId?.startsWith("team_")?{teamId:o.orgId}:{}}:void 0}catch{return}}async function At(e){let r=await Xe(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 qe(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 Tt(e){if(!e.token||!e.projectId)throw new Error("--test needs a connected project. Run `verirun log vercel` first.");let r=await X(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 z(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=$e(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 Nt(e,r){let{configPath:o,repoRoot:t}=y(),i=e.vercel??{},s=process.env.VERIRUN_VERCEL_TOKEN;if(r.drain||r.listen){await Lt(e,r);return}if(r.test){await Tt(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 ${q})`)}`),n.info(` ${n.dim("and vercel.projectId (+ vercel.teamId) in .verirun/config.json")}`);return}n.info(` Opening ${n.bold(q)}`),n.info(" Create a token, copy it, come back here."),N(q),n.info("");let m=await b(" Paste the token: ");if(!m){n.warn(" Nothing pasted. No changes made.");return}a=m}let c=r.reconnect?void 0:xt(t);c&&n.info(` project ${c.projectId} ${n.dim("\u2014 from .vercel/project.json")}`);let l=c??await At(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 ee(o,{vercel:d}),n.info(""),n.info(` Saved to ${n.dim(o)}`),n.info(" Checking it works\u2026");let f={...i,...d,token:a},p=await X(f);if("error"in p){n.error(` ${p.error}`),n.info(n.dim(" Token or project looks wrong. Re-run `verirun log vercel --reconnect`.")),process.exitCode=1;return}let g=await z(f,p.deploymentId,4e3);if("error"in g){n.error(` Reading logs failed: ${g.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 ${p.label}. \`verirun run\` now includes Vercel logs.`),g.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 Lt(e,r){let{configPath:o}=y(),t=e.vercel??{},i=t.listenerPort??Q,s=t.listenerPath??Z,a=t.drainGraceMs??Se;if(r.listen){await Pt({...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}N(jt),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 p=(await b(" Save without a secret anyway? [y/N]: ")).toLowerCase();if(p!=="y"&&p!=="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: "),f={};l&&(f.drainSecret=l),d&&(f.project=d),await ee(o,{vercel:f}),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 Pt(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 ke="https://supabase.com/dashboard/account/tokens";async function b(e){if(!process.stdin.isTTY)return"";let r=Ct({input:process.stdin,output:process.stdout});try{return(await r.question(e)).trim()}finally{r.close()}}async function ee(e,r){await _e(e,r)||n.warn(`Could not restrict ${e} to your account. It holds an API token \u2014 check its permissions.`)}function _t(){let e=St("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 Ot(e){if(e)return e;let r=_t();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 Dt(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 Ut(e,r){let{configPath:o}=y(),t=e.supabase??{},i=t.sources&&t.sources.length>0?t.sources:ye,s=process.env.VERIRUN_SUPABASE_ACCESS_TOKEN,a=s??t.accessToken;if(r.test){await Dt(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 ${ke})`)}`),n.info(` ${n.dim("and supabase.projectRef in .verirun/config.json")}`);return}n.info(` Opening ${n.bold(ke)}`),n.info(' Click "Generate new token", copy it, come back here.'),N(ke),n.info("");let g=await b(" Paste the token: ");if(!g){n.warn(" Nothing pasted. No changes made.");return}g.startsWith("sbp_")||n.warn(" That does not look like a Supabase token (expected sbp_\u2026). Saving it anyway."),a=g}let c=await Ot(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 ee(o,{supabase:l}),n.info(""),n.info(` Saved to ${n.dim(o)}`),n.info(" Checking it works\u2026");let d=new Date,f={startedAt:new Date(d.getTime()-5*6e4).toISOString(),endedAt:d.toISOString()},p=await K(c,a,i[0],f);if("error"in p){n.error(` ${i[0]} query failed: ${p.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 er(e){return!!(e.deploymentId||e.projectId&&e.environmentId&&e.serviceId)}function Vt(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 Ft(e,r){if(!r)throw new Error("--test needs a token. Run `verirun log railway`, or set $VERIRUN_RAILWAY_TOKEN.");if(!er(e))throw new Error("--test needs a connected deployment. Run `verirun log railway` first.");let o=await J({...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 he(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 Mt(e,r){let{configPath:o}=y(),t=e.railway??{},i=process.env.VERIRUN_RAILWAY_TOKEN,s=i??t.token;if(r.test){await Ft(t,s);return}if(s&&er(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 (${ge}):`),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){N(ge),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=Vt(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: "),f=await b(" Environment ID: "),p=await b(" Service ID: ");if(!d||!f||!p){n.warn(" Need all three. No changes made.");return}a.projectId=d,a.environmentId=f,a.serviceId=p}await ee(o,{railway:a}),n.info(""),n.info(` Saved to ${n.dim(o)}`),n.info(" Checking it works\u2026");let l=await J({...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 tr,readFileSync as nr}from"node:fs";import{mkdir as Wt,readdir as Bt,writeFile as rr}from"node:fs/promises";import R from"node:path";var Gt=new Set(["node_modules",".git",".next",".verirun","dist","build","out","coverage",".turbo",".vercel"]);async function Ht(e){let r=[],o=async t=>{for(let i of await Bt(t,{withFileTypes:!0})){if(i.name.startsWith(".")&&i.name!==".")continue;let s=R.join(t,i.name);if(i.isDirectory()){if(Gt.has(i.name))continue;await o(s)}else/\.tsx?$/.test(i.name)&&!i.name.endsWith(".d.ts")&&r.push({file:R.relative(e,s).split(R.sep).join("/"),source:nr(s,"utf8")})}};return await o(e),r}function Jt(e){if(tr(e))try{let r=nr(e,"utf8").replace(/\/\*[\s\S]*?\*\//g,"").replace(/(^|[^:])\/\/.*$/gm,"$1").replace(/,(\s*[}\]])/g,"$1");return JSON.parse(r)}catch{return}}function or(e,r=0){if(r>5)return{};let o=Jt(e);if(!o)return{};let t=o.compilerOptions??{},i=o.extends;if(typeof i!="string"||!i.startsWith("."))return t;let s=R.resolve(R.dirname(e),i),a=or(/\.json$/.test(s)?s:`${s}.json`,r+1);return{...a,...t,paths:t.paths??a.paths}}function Kt(e){let{baseUrl:r,paths:o}=or(R.join(e,"tsconfig.json")),t=(r??"").replace(/^\.\/?/,"").replace(/\/$/,""),i={};for(let[s,a]of Object.entries(o??{})){let c=a[0];if(!s.endsWith("/*")||!c?.endsWith("*"))continue;let l=c.slice(0,-1).replace(/\/$/,"").replace(/^\.\//,"");i[s.slice(0,-1)]=[t,l].filter(Boolean).join("/")}return i}function Yt(e,r){let o={...r};for(let t of e??[]){let[i,s]=t.split("=");i&&(o[i]=s??"")}return o}var qt=/(?:from|import)\s*\(?\s*['"]([^'"]+)['"]/g;function Xt(e,r){let o=new Set(e.map(i=>i.file)),t=new Map;for(let i of e)for(let[,s]of i.source.matchAll(qt)){if(!s||s.startsWith(".")||Object.keys(r).some(d=>s.startsWith(d)))continue;let a=s.indexOf("/");if(a<=0)continue;let c=`${s.slice(0,a)}/`;if(t.has(c))continue;let l=s.slice(a+1);for(let d of o){let f=d.replace(/\.tsx?$/,"").replace(/\/index$/,"");if(f===l||!f.endsWith(`/${l}`)){if(f===l)t.set(c,"");else continue;break}t.set(c,f.slice(0,f.length-l.length-1));break}}return[...t].map(([i,s])=>`--alias ${i}=${s}`)}function zt(e,r,o){let t=e.nodes.pages.filter(s=>!s.inferred);n.info(`${n.bold(String(t.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 s of e.nodes.pages){let a=e.edges.filter(f=>f.from===s.id),c=a.filter(f=>f.kind==="nav").length,l=a.filter(f=>f.kind==="effect").length,d=s.inferred?n.dim(" (inferred)"):"";n.info(` ${s.path}${d} ${n.dim(`\u2014 ${s.component}, ${s.elements.length} element(s), ${c} nav, ${l} effect`)}`)}let i=e.diagnostics;i.parseErrors.length>0&&n.warn(`${i.parseErrors.length} file(s) failed to parse`);for(let s of o)n.info(""),n.warn(`Imports like ${n.bold(s.split(" ")[1]?.split("=")[0]??"")} could not be resolved, so components they point at were not analysed. Re-run with:`),n.info(` verirun map ${s}`);i.unresolvedTargets.length>0&&(n.info(""),n.info(n.dim(`${i.unresolvedTargets.length} nav target(s) could not be resolved to a page`)))}async function ir(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 f=y(),p=e.dir?R.resolve(e.dir):f.repoRoot;if(!tr(p))throw new Error(`no such directory: ${p}`);let g=await Ht(p);if(g.length===0)throw new Error(`no .ts/.tsx files found under ${p}`);let m=Yt(e.alias,Kt(p)),w={aliases:m,...e.followChildren===!1?{followChildren:!1}:{},...e.appFile?{appFile:e.appFile}:{}};if(e.bfs){let u=o(g,w),v=e.kind==="nav"||e.kind==="effect"?[e.kind]:void 0,$=t(u,e.bfs,{depth:e.depth?Number(e.depth):2,...v?{kinds:v}:{}});n.info(n.dim(`${$.order.length-1} node(s) within ${$.maxDepth} step(s) of ${$.from}`)),n.info(a($));return}if(e.reach){let u=s(g,w);n.info(l(u));for(let v of u.unreachedFiles)n.info(n.dim(`unreached: ${v.file} (${v.elements} elements)`));return}let h=o(g,w);if(e.json){process.stdout.write(`${JSON.stringify(h,null,2)}
|
|
27
|
-
`);return}if(e.report){let
|
|
28
|
-
`),await
|
|
29
|
-
`);let $=
|
|
30
|
-
`).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
|
|
31
|
-
`).map(r=>r.trim()).filter(r=>r&&!r.startsWith("#")).some(r=>r.replace(/^\//,"").replace(/\/$/,"")===
|
|
24
|
+
}`,{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 ft(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 ge=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 K(this.cfg);if("error"in t)return n.warn(`Railway: ${t.error}`),[];let i=await we(this.cfg.token,t.deploymentId,o,{userNeedle:r.userFilter});if("error"in i)return n.warn(`Railway: ${i.error}`),[];let s=i.entries.map(ft);return s.sort((a,c)=>(a.timestamp??"").localeCompare(c.timestamp??"")),s}async dispose(){}};function Ke(e){return e.railway?new ge(e.railway):void 0}var pt="https://api.supabase.com",ve=["postgres_logs","edge_logs","auth_logs"],ye=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:ve}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 Y(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(gt(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(){}},mt=/^[A-Za-z0-9._@%+-]{1,256}$/;async function Ye(e,r,o,t){let i=new URL(`/v1/projects/${e}/analytics/endpoints/logs.all`,pt);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 C(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 Y(e,r,o,t,i={}){let s=i.userNeedle?.trim().toLowerCase(),a=s&&mt.test(s)?s:void 0,c=u=>{let p=u&&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}${p} order by timestamp asc limit 1000`},l=await Ye(e,r,c(!0),t);if(!("error"in l))return{rows:l.rows,serverFiltered:!!a};if(!a)return l;let d=await Ye(e,r,c(!1),t);return"error"in d?d:{rows:d.rows,serverFiltered:!1}}function gt(e,r){return{source:"supabase",stream:e,timestamp:ht(r.timestamp),message:typeof r.event_message=="string"?r.event_message:void 0,raw:r}}function ht(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 qe(e){return e.supabase?new ye(e.supabase):void 0}import{createHmac as bt,timingSafeEqual as $t}from"node:crypto";import{createServer as St}from"node:http";import{setTimeout as kt}from"node:timers/promises";var ze="https://api.vercel.com",z="https://vercel.com/account/settings/tokens",wt=8e3,yt=1500,vt=3e3;function be(e){return e?`&teamId=${encodeURIComponent(e)}`:""}async function $e(e,r){let o;try{o=await C(`${ze}${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 Xe(e,r){let o=await $e(`/v9/projects?limit=100${be(r)}`,e);return"error"in o?o:{projects:o.data.projects??[]}}async function Qe(e){let r=await $e("/v2/teams?limit=100",e);return"error"in r?r:{teams:r.data.teams??[]}}async function X(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 $e(`/v6/deployments?projectId=${encodeURIComponent(e.projectId)}&limit=1&state=READY&target=${encodeURIComponent(r)}${be(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 Q(e,r,o){let t=`/v1/projects/${encodeURIComponent(e.projectId)}/deployments/${encodeURIComponent(r)}/runtime-logs?limit=1000${be(e.teamId)}`,i=new AbortController,s=setTimeout(()=>i.abort(),o),a,c=()=>{a&&clearTimeout(a),a=setTimeout(()=>i.abort(),yt)},l=[];try{let d=await C(`${ze}${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 u=new TextDecoder,p="";for await(let m of d.body){p+=u.decode(m,{stream:!0});let g=p.split(`
|
|
25
|
+
`);p=g.pop()??"";for(let v of g){let w=v.trim();if(w)try{let f=JSON.parse(w);Array.isArray(f)?l.push(...f):l.push(f)}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 Se(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 q=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 X(this.config);if("error"in t)return n.warn(`Vercel: ${t.error}`),[];let i=await Q(this.config,t.deploymentId,this.config.readMs??wt);if("error"in i)return n.warn(`Vercel: ${i.error}`),[];let s=Date.parse(o.startedAt),a=Date.parse(o.endedAt)+(this.config.tailGraceMs??vt);return i.rows.filter(c=>typeof c.timestampInMs!="number"?!0:c.timestampInMs>=s&&c.timestampInMs<=a).map(Se)}async dispose(){}};var Z=4319,ee="/drain",ke=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??ee,this.secret=r.drainSecret,this.graceMs=r.drainGraceMs??ke,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=St((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 kt(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 Rt(s.toString("utf8"))){if(!this.projectMatches(a)){this.droppedByProject+=1;continue}let c=Et(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=bt("sha1",this.secret).update(o).digest("hex"),s=Buffer.from(i),a=Buffer.from(t);return s.length===a.length&&$t(s,a)}};function Rt(e){let r=e.trim();if(!r)return[];if(r.startsWith("[")){let o=JSON.parse(r);return Array.isArray(o)?o:[]}return r.split(`
|
|
26
|
+
`).map(o=>o.trim()).filter(Boolean).map(o=>JSON.parse(o))}function Et(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 Ze(e){if(e.vercel)return e.vercel.token?new q(e.vercel):new V(e.vercel)}var er=["vercel","supabase","railway"];async function rr(e,r){if(e!==void 0&&!er.includes(e))throw new Error(`Unknown log source "${e}". Use one of: ${er.join(", ")}.`);let o=y(),t=await T(o.configPath);if(e===void 0){Tt(t);return}if(e==="vercel"){await _t(t,r);return}if(e==="railway"){await Ht(t,r);return}await Wt(t,r)}function Tt(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??ee}`: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 Nt="https://vercel.com/d?to=%2F%5Bteam%5D%2F~%2Fsettings%2Flog-drains&title=Log%20Drains";function Lt(e){let r=jt.join(e,".vercel","project.json");if(It(r))try{let o=JSON.parse(xt(r,"utf8"));return o.projectId?{projectId:o.projectId,...o.orgId?.startsWith("team_")?{teamId:o.orgId}:{}}:void 0}catch{return}}async function Pt(e){let r=await Qe(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 Xe(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 Ot(e){if(!e.token||!e.projectId)throw new Error("--test needs a connected project. Run `verirun log vercel` first.");let r=await X(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 Q(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=Se(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 _t(e,r){let{configPath:o,repoRoot:t}=y(),i=e.vercel??{},s=process.env.VERIRUN_VERCEL_TOKEN;if(r.drain||r.listen){await Dt(e,r);return}if(r.test){await Ot(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 ${z})`)}`),n.info(` ${n.dim("and vercel.projectId (+ vercel.teamId) in .verirun/config.json")}`);return}n.info(` Opening ${n.bold(z)}`),n.info(" Create a token, copy it, come back here."),N(z),n.info("");let g=await b(" Paste the token: ");if(!g){n.warn(" Nothing pasted. No changes made.");return}a=g}let c=r.reconnect?void 0:Lt(t);c&&n.info(` project ${c.projectId} ${n.dim("\u2014 from .vercel/project.json")}`);let l=c??await Pt(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 re(o,{vercel:d}),n.info(""),n.info(` Saved to ${n.dim(o)}`),n.info(" Checking it works\u2026");let u={...i,...d,token:a},p=await X(u);if("error"in p){n.error(` ${p.error}`),n.info(n.dim(" Token or project looks wrong. Re-run `verirun log vercel --reconnect`.")),process.exitCode=1;return}let m=await Q(u,p.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 ${p.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 Dt(e,r){let{configPath:o}=y(),t=e.vercel??{},i=t.listenerPort??Z,s=t.listenerPath??ee,a=t.drainGraceMs??ke;if(r.listen){await Ut({...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}N(Nt),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 p=(await b(" Save without a secret anyway? [y/N]: ")).toLowerCase();if(p!=="y"&&p!=="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: "),u={};l&&(u.drainSecret=l),d&&(u.project=d),await re(o,{vercel:u}),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 Ut(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 Re="https://supabase.com/dashboard/account/tokens";async function b(e){if(!process.stdin.isTTY)return"";let r=At({input:process.stdin,output:process.stdout});try{return(await r.question(e)).trim()}finally{r.close()}}async function re(e,r){await De(e,r)||n.warn(`Could not restrict ${e} to your account. It holds an API token \u2014 check its permissions.`)}function Vt(){let e=Ct("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 Ft(e){if(e)return e;let r=Vt();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 Mt(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 Y(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 Wt(e,r){let{configPath:o}=y(),t=e.supabase??{},i=t.sources&&t.sources.length>0?t.sources:ve,s=process.env.VERIRUN_SUPABASE_ACCESS_TOKEN,a=s??t.accessToken;if(r.test){await Mt(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 ${Re})`)}`),n.info(` ${n.dim("and supabase.projectRef in .verirun/config.json")}`);return}n.info(` Opening ${n.bold(Re)}`),n.info(' Click "Generate new token", copy it, come back here.'),N(Re),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 Ft(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 re(o,{supabase:l}),n.info(""),n.info(` Saved to ${n.dim(o)}`),n.info(" Checking it works\u2026");let d=new Date,u={startedAt:new Date(d.getTime()-5*6e4).toISOString(),endedAt:d.toISOString()},p=await Y(c,a,i[0],u);if("error"in p){n.error(` ${i[0]} query failed: ${p.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 tr(e){return!!(e.deploymentId||e.projectId&&e.environmentId&&e.serviceId)}function Bt(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 Gt(e,r){if(!r)throw new Error("--test needs a token. Run `verirun log railway`, or set $VERIRUN_RAILWAY_TOKEN.");if(!tr(e))throw new Error("--test needs a connected deployment. Run `verirun log railway` first.");let o=await K({...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 we(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 Ht(e,r){let{configPath:o}=y(),t=e.railway??{},i=process.env.VERIRUN_RAILWAY_TOKEN,s=i??t.token;if(r.test){await Gt(t,s);return}if(s&&tr(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 (${he}):`),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){N(he),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=Bt(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: "),u=await b(" Environment ID: "),p=await b(" Service ID: ");if(!d||!u||!p){n.warn(" Need all three. No changes made.");return}a.projectId=d,a.environmentId=u,a.serviceId=p}await re(o,{railway:a}),n.info(""),n.info(` Saved to ${n.dim(o)}`),n.info(" Checking it works\u2026");let l=await K({...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 or,readFileSync as ir}from"node:fs";import{mkdir as Jt,readdir as Kt,writeFile as nr}from"node:fs/promises";import k from"node:path";var Yt=new Set(["node_modules",".git",".next",".verirun","dist","build","out","coverage",".turbo",".vercel"]);async function qt(e){let r=[],o=async t=>{for(let i of await Kt(t,{withFileTypes:!0})){if(i.name.startsWith(".")&&i.name!==".")continue;let s=k.join(t,i.name);if(i.isDirectory()){if(Yt.has(i.name))continue;await o(s)}else/\.tsx?$/.test(i.name)&&!i.name.endsWith(".d.ts")&&r.push({file:k.relative(e,s).split(k.sep).join("/"),source:ir(s,"utf8")})}};return await o(e),r}function zt(e){if(or(e))try{let r=ir(e,"utf8").replace(/\/\*[\s\S]*?\*\//g,"").replace(/(^|[^:])\/\/.*$/gm,"$1").replace(/,(\s*[}\]])/g,"$1");return JSON.parse(r)}catch{return}}function sr(e,r=0){if(r>5)return{};let o=zt(e);if(!o)return{};let t=o.compilerOptions??{},i=o.extends;if(typeof i!="string"||!i.startsWith("."))return t;let s=k.resolve(k.dirname(e),i),a=sr(/\.json$/.test(s)?s:`${s}.json`,r+1);return{...a,...t,paths:t.paths??a.paths}}function Xt(e){let{baseUrl:r,paths:o}=sr(k.join(e,"tsconfig.json")),t=(r??"").replace(/^\.\/?/,"").replace(/\/$/,""),i={};for(let[s,a]of Object.entries(o??{})){let c=a[0];if(!s.endsWith("/*")||!c?.endsWith("*"))continue;let l=c.slice(0,-1).replace(/\/$/,"").replace(/^\.\//,"");i[s.slice(0,-1)]=[t,l].filter(Boolean).join("/")}return i}function Qt(e,r){let o={...r};for(let t of e??[]){let[i,s]=t.split("=");i&&(o[i]=s??"")}return o}var Zt=/(?:from|import)\s*\(?\s*['"]([^'"]+)['"]/g;function en(e,r){let o=new Set(e.map(i=>i.file)),t=new Map;for(let i of e)for(let[,s]of i.source.matchAll(Zt)){if(!s||s.startsWith(".")||Object.keys(r).some(d=>s.startsWith(d)))continue;let a=s.indexOf("/");if(a<=0)continue;let c=`${s.slice(0,a)}/`;if(t.has(c))continue;let l=s.slice(a+1);for(let d of o){let u=d.replace(/\.tsx?$/,"").replace(/\/index$/,"");if(u===l||!u.endsWith(`/${l}`)){if(u===l)t.set(c,"");else continue;break}t.set(c,u.slice(0,u.length-l.length-1));break}}return[...t].map(([i,s])=>`--alias ${i}=${s}`)}function rn(e,r,o){let t=e.nodes.pages.filter(s=>!s.inferred);n.info(`${n.bold(String(t.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 s of e.nodes.pages){let a=e.edges.filter(m=>m.from===s.id),c=a.filter(m=>m.kind==="nav").length,l=a.filter(m=>m.kind==="effect").length,d=new Set([...s.elements,...a.map(m=>m.trigger)].filter(m=>m.dialogs&&m.dialogs.length>0).map(m=>m.id)).size,u=d>0?`, ${d} opening a dialog`:"",p=s.inferred?n.dim(" (inferred)"):"";n.info(` ${s.path}${p} ${n.dim(`\u2014 ${s.component}, ${s.elements.length} element(s), ${c} nav, ${l} effect${u}`)}`)}let i=e.diagnostics;i.parseErrors.length>0&&n.warn(`${i.parseErrors.length} file(s) failed to parse`);for(let s of o)n.info(""),n.warn(`Imports like ${n.bold(s.split(" ")[1]?.split("=")[0]??"")} could not be resolved, so components they point at were not analysed. Re-run with:`),n.info(` verirun map ${s}`);i.unresolvedTargets.length>0&&(n.info(""),n.info(n.dim(`${i.unresolvedTargets.length} nav target(s) could not be resolved to a page`)))}async function ar(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 u=y(),p=e.dir?k.resolve(e.dir):u.repoRoot;if(!or(p))throw new Error(`no such directory: ${p}`);let m=await qt(p);if(m.length===0)throw new Error(`no .ts/.tsx files found under ${p}`);let g=Qt(e.alias,Xt(p)),v={aliases:g,...e.followChildren===!1?{followChildren:!1}:{},...e.appFile?{appFile:e.appFile}:{}};if(e.bfs){let f=o(m,v),h=e.kind==="nav"||e.kind==="effect"?[e.kind]:void 0,$=t(f,e.bfs,{depth:e.depth?Number(e.depth):2,...h?{kinds:h}:{}});n.info(n.dim(`${$.order.length-1} node(s) within ${$.maxDepth} step(s) of ${$.from}`)),n.info(a($));return}if(e.reach){let f=s(m,v);n.info(l(f));for(let h of f.unreachedFiles)n.info(n.dim(`unreached: ${h.file} (${h.elements} elements)`));return}let w=o(m,v);if(e.json){process.stdout.write(`${JSON.stringify(w,null,2)}
|
|
27
|
+
`);return}if(e.report){let f=e.out?k.resolve(e.out):k.join(u.dataDir,"map");await Jt(f,{recursive:!0});let h=i(m,w);await nr(k.join(f,"interaction-tree.json"),`${JSON.stringify(w,null,2)}
|
|
28
|
+
`),await nr(k.join(f,"coverage.md"),`${c(h,w)}
|
|
29
|
+
`);let $=k.relative(process.cwd(),f),E=$.startsWith("..")?f:$;n.success(`wrote ${E}/interaction-tree.json + coverage.md`);let j=h.bar.filter(A=>A.pass===!1).length;n.info(n.dim(`${h.bar.length-j}/${h.bar.length} coverage checks pass`));return}rn(w,m,en(m,g))}import{existsSync as Pn}from"node:fs";import{mkdir as On}from"node:fs/promises";import hr from"node:path";import{createInterface as _n}from"node:readline/promises";import{spawnSync as tn}from"node:child_process";var nn={browser:"chromium",channel:"chrome",label:"Chrome",approximated:!1},on={browser:"chromium",channel:"msedge",label:"Edge",approximated:!1},sn={browser:"firefox",label:"Firefox",approximated:!1},an={browser:"chromium",label:"Chromium",approximated:!1};function Ee(e,r){let o=e.toLowerCase(),t=i=>r?{...i,label:r}:i;if(o.includes("firefox")||o.includes("mozilla"))return t(sn);if(o.includes("msedge")||o.includes("microsoft-edge")||o.includes("edgemac")||o.includes("microsoftedge"))return t(on);if(o.includes("google-chrome")||o.includes("com.google.chrome")||o==="chromehtml"||o.includes("chrome"))return t(nn);if(o.includes("chromium"))return t(an);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 te(e,r){let o=tn(e,r,{encoding:"utf8",timeout:4e3});if(!(o.error||o.status!==0))return(o.stdout||"").trim()||void 0}function cn(){let e=te("xdg-settings",["get","default-web-browser"])??te("xdg-mime",["query","default","x-scheme-handler/https"]);return e?Ee(e):void 0}function ln(){let e=te("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?Ee(t):void 0}catch{return}}function dn(){let r=te("reg",["query","HKCU\\Software\\Microsoft\\Windows\\Shell\\Associations\\UrlAssociations\\https\\UserChoice","/v","ProgId"])?.match(/ProgId\s+REG_SZ\s+(\S+)/i)?.[1];return r?Ee(r):void 0}function cr(){try{if(process.platform==="darwin")return ln();if(process.platform==="linux")return cn();if(process.platform==="win32")return dn()}catch{}}import{spawn as un}from"node:child_process";import{mkdtemp as fn,readFile as pn,rm as mn}from"node:fs/promises";import{createRequire as gn}from"node:module";import hn from"node:os";import ne from"node:path";var wn=new Set(["name","selector","locator","signals","pageGuid","ariaSnapshot"]);function lr(e){let r={};for(let[o,t]of Object.entries(e))!wn.has(o)&&t!==void 0&&(r[o]=t);return r}function yn(){let e=gn(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 ne.join(ne.dirname(r),t)}async function dr(e){let r=yn(),o=await fn(ne.join(hn.tmpdir(),"verirun-record-")),t=ne.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=un(process.execPath,i,{stdio:["ignore","inherit","inherit"]});d.on("error",l),d.on("close",u=>c(u))}),a=await pn(t,"utf8").catch(()=>"");return{...vn(a),exitCode:s}}finally{await mn(o,{recursive:!0,force:!0})}}function vn(e){let r=e.split(`
|
|
30
|
+
`).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 bn}from"node:fs";import{appendFile as $n,readFile as Sn}from"node:fs/promises";import kn from"node:path";function Rn(e){return e.split(`
|
|
31
|
+
`).map(r=>r.trim()).filter(r=>r&&!r.startsWith("#")).some(r=>r.replace(/^\//,"").replace(/\/$/,"")===H)}async function ur(e){let r=kn.join(e,".gitignore");if(!bn(r))return"no-gitignore";let o=await Sn(r,"utf8");if(Rn(o))return"already-present";let t=o.length===0||o.endsWith(`
|
|
32
32
|
`)?"":`
|
|
33
|
-
`;return await
|
|
33
|
+
`;return await $n(r,`${t}
|
|
34
34
|
# verirun: recorded workflows and captured run logs (may contain secrets)
|
|
35
|
-
${
|
|
36
|
-
`,"utf8"),"added"}function
|
|
37
|
-
`,"utf8")}async function ne(e){let r=await jn(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!==U)throw new Error(`Workflow "${t.name??fr.basename(e)}" uses schema version ${t.schemaVersion}, but this build expects ${U}. Re-record it.`);return t}function Nn(e){return!(e.name==="openPage"&&e.url==="about:blank")}function Ln(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:ar(e),signals:Array.isArray(e.signals)?e.signals:[]};e.selector&&(o.selector=e.selector),e.locator&&(o.locator=e.locator);let t=dr(e.locator);return t&&(o.description=t),e.pageGuid&&(o.pageGuid=e.pageGuid),o}function _n(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 gr(e,r){let{assertLicensed:o}=await import("./gate.mjs"),t=await o();t.note&&n.warn(t.note),D(e);let i=y(),s=await T(i.configPath),a=_(i,e);if(An(a)&&!r.force)throw new Error(`Workflow "${e}" already exists at ${mr.relative(i.repoRoot,a)}. Re-run with --force to overwrite it.`);await Tn(i.workflowsDir,{recursive:!0});let c=await lr(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??Pe,d=r.browser,f=r.channel;if(r.defaultBrowser){(r.browser||r.channel)&&n.warn("--default-browser overrides -b / --channel.");let u=sr();u?(d=u.browser,f=u.channel,u.approximated?n.warn(`Your default browser is ${u.label}, which Playwright can't drive directly \u2014 recording in ${f??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",f=void 0)}if(r.url){let u=await ur(r.url);if(u.reachable===!1)throw new Error(`Nothing is listening at ${r.url} (connection refused on ${u.host}:${u.port}). Start the app you want to record, then run this again.`)}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 p=await cr({url:r.url,browser:d,channel:f,userDataDir:r.userDataDir,testIdAttribute:l}),g=Ln(p.actions.filter(Nn));if(g.length===0){if(p.exitCode!==0)throw new Error(`Playwright codegen exited with code ${p.exitCode} before anything was recorded. Its output is above \u2014 commonly the browser failed to open, or a page the recording needed was unreachable. If it persists against a page that loads fine, 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 m=g.map(Pn),w=m.find(u=>u.action==="navigate"),h={schemaVersion:U,name:e,createdAt:new Date().toISOString(),startUrl:r.url??w?.params.url,browser:p.header.browserName??d??"chromium",channel:f,testIdAttribute:l,steps:m};await pr(a,h),n.info("");for(let u of m)n.info(` ${n.dim(String(u.index).padStart(2))} ${_n(u)}`);n.info(""),n.success(`Saved ${m.length} step${m.length===1?"":"s"} to ${mr.relative(i.repoRoot,a)}`),m.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 Wn}from"node:fs";import{mkdir as Bn,writeFile as Gn}from"node:fs/promises";import Rr from"node:path";import{chromium as M,firefox as On,selectors as Dn,webkit as Un}from"playwright";var Vn={chromium:M,firefox:On,webkit:Un};async function Fn(e,r){let o=!r.headed,t=r.slowMoMs&&r.slowMoMs>0?r.slowMoMs:void 0;if(r.cdpEndpoint){let c=await M.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 M.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 M.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(Vn[e.browser]??M).launch({headless:o,slowMo:t}),a=await s.newContext();return{context:a,page:await a.newPage(),close:()=>s.close()}}function hr(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 oe(e){return typeof e=="string"?e:void 0}function wr(e){return Array.isArray(e)?e.filter(r=>typeof r=="string"):[]}async function Mn(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=oe(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:oe(r.params.button)??"left",clickCount:typeof r.params.clickCount=="number"?r.params.clickCount:r.action==="dblclick"?2:1,modifiers:hr(r.params.modifiers)});return}case"fill":await o().fill(oe(r.params.text)??"");return;case"press":{let t=oe(r.params.key);if(!t)throw new Error(`Step ${r.index} (press) has no key.`);await o().press([...hr(r.params.modifiers),t].join("+"));return}case"check":await o().check();return;case"uncheck":await o().uncheck();return;case"select":await o().selectOption(wr(r.params.options));return;case"setInputFiles":await o().setInputFiles(wr(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 yr(e,r={}){e.testIdAttribute&&Dn.setTestIdAttribute(e.testIdAttribute);let o={...r,channel:r.channel??e.channel},t=await Fn(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 Mn(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 vr(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 br=[];function ie(e){br.push(e)}function $r(e){return br.map(r=>r(e)).filter(r=>!!r)}var Sr=!1;function kr(){Sr||(Sr=!0,ie(Ke),ie(ze),ie(He))}var Hn=1,Jn=500;function Kn(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?Jn:0}function W(e){return e instanceof Error?e.message:String(e)}function Yn(e){return e.replace(/\x1b\[[0-9;]*m/g,"")}async function Er(e){for(let r of[...e].reverse())try{await r.dispose()}catch(o){n.warn(`${r.name}: dispose failed: ${W(o)}`)}}async function Cr(e,r){let{assertLicensed:o}=await import("./gate.mjs"),t=await o();t.note&&n.warn(t.note),D(e);let i=y(),s=await T(i.configPath),a=_(i,e);if(!Wn(a))throw new Error(`No workflow named "${e}". Record it first with: verirun record ${e}`);let c=await ne(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;kr();let f=$r(s),p=De(),g=Ue(i,e,p);await Bn(g,{recursive:!0});let m={config:s,runDir:g,workflowName:e,userFilter:d};n.info(""),n.info(`Running ${n.bold(e)} ${n.dim(`${c.steps.length} steps \xB7 ${c.browser}`)}`),f.length===0?n.warn("No log sources configured. Add a supabase or vercel block to .verirun/config.json."):n.info(n.dim(`Log sources: ${f.map(h=>h.name).join(", ")}`)),d&&n.info(n.dim(`User filter: entries mentioning "${d}"`)),n.info("");let w=[];try{for(let h of f)await h.start(m),w.push(h)}catch(h){let u=f[w.length];throw await Er(w),new Error(`Log source "${u?.name??"?"}" failed to start: ${W(h)}`)}try{let h=new Date().toISOString(),u=await yr(c,{headed:r.headed,slowMoMs:Kn(r),timeoutMs:l,channel:r.channel,userDataDir:r.userDataDir,cdpEndpoint:r.cdp}),v=new Date().toISOString(),$={startedAt:h,endedAt:v};u.error?n.error(`Replay failed at step ${u.failedStepIndex}: ${W(u.error)}`):n.success(`Replayed ${u.stepsReplayed} step${u.stepsReplayed===1?"":"s"}`);let S=[],x=[],A=0;for(let k of w)try{let j=await k.collect(m,$);A+=j.length,d&&(j=j.filter(Nr=>vr(Nr,d))),x.push(...j),S.push({id:k.id,name:k.name,entries:j.length})}catch(j){n.warn(`${k.name}: log collection failed: ${W(j)}`),S.push({id:k.id,name:k.name,entries:0})}d&&x.length===0&&A>0&&n.warn(`${A} log entr${A===1?"y":"ies"} collected, none mention "${d}".`),x.sort((k,j)=>(k.timestamp??"").localeCompare(j.timestamp??""));let Tr={schemaVersion:Hn,workflow:e,status:u.error?"failed":"ok",window:$,steps:{total:u.stepsTotal,replayed:u.stepsReplayed,...u.failedStepIndex!==void 0?{failedAt:u.failedStepIndex}:{}},...u.error?{error:Yn(W(u.error))}:{},...d?{filter:{user:d}}:{},sources:S,entries:x},Ee=Rr.join(g,"logs.json");await Gn(Ee,`${JSON.stringify(Tr,null,2)}
|
|
38
|
-
`,"utf8"),n.info("");for(let
|
|
39
|
-
`),
|
|
35
|
+
${H}/
|
|
36
|
+
`,"utf8"),"added"}function _(e){return`'${e.replace(/\\/g,"\\\\").replace(/'/g,"\\'").replace(/\n/g,"\\n")}'`}function F(e){if(e&&typeof e=="object"&&"source"in e){let r=e;return`/${r.source??""}/${r.flags??""}`}return _(String(e))}function En(e){let r=e.options??{},o=e.body;switch(e.kind){case"role":{let t=[];r.name!==void 0&&t.push(`name: ${F(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)}, { ${t.join(", ")} })`:`getByRole(${_(o)})`}case"test-id":return`getByTestId(${_(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}(${F(o)}, { exact: true })`:`${t}(${F(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)})`;case"has-text":return`filter({ hasText: ${F(o)} })`;case"has-not-text":return`filter({ hasNotText: ${F(o)} })`;default:return`locator(${_(o)})`}}function fr(e){if(!e)return;let r=[],o=e;for(;o;)r.push(En(o)),o=o.next;return r.join(".")}var Cn=/^[A-Za-z0-9][A-Za-z0-9._-]*$/;var In=/^(con|prn|aux|nul|com[1-9]|lpt[1-9])$/i;function D(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(!Cn.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(In.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 xn from"node:net";var jn=2e3,An={"http:":80,"https:":443};async function pr(e){let r;try{r=new URL(e)}catch{return{reachable:"unknown"}}let o=An[r.protocol];if(o===void 0)return{reachable:"unknown"};let t=r.hostname.replace(/^\[|\]$/g,""),i=r.port?Number(r.port):o;return new Promise(s=>{let a=!1,c=d=>{a||(a=!0,l.destroy(),s(d))},l=xn.connect({host:t,port:i,autoSelectFamily:!0});l.setTimeout(jn),l.on("connect",()=>c({reachable:!0})),l.on("timeout",()=>c({reachable:"unknown"})),l.on("error",d=>{c(d.code==="ECONNREFUSED"?{reachable:!1,host:t,port:i}:{reachable:"unknown"})})})}import{mkdir as Tn,readFile as Nn,writeFile as Ln}from"node:fs/promises";import mr from"node:path";var U=1;async function gr(e,r){await Tn(mr.dirname(e),{recursive:!0}),await Ln(e,`${JSON.stringify(r,null,2)}
|
|
37
|
+
`,"utf8")}async function oe(e){let r=await Nn(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!==U)throw new Error(`Workflow "${t.name??mr.basename(e)}" uses schema version ${t.schemaVersion}, but this build expects ${U}. Re-record it.`);return t}function Dn(e){return!(e.name==="openPage"&&e.url==="about:blank")}function Un(e){let r=e.length;for(;r>0&&e[r-1]?.name==="closePage";)r-=1;return e.slice(0,r)}function Vn(e){return Array.isArray(e.signals)&&e.signals.some(r=>!!r&&typeof r=="object"&&r.name==="dialog")}function Fn(e,r){let o={index:r,action:e.name,params:lr(e),signals:Array.isArray(e.signals)?e.signals:[]};e.selector&&(o.selector=e.selector),e.locator&&(o.locator=e.locator);let t=fr(e.locator);return t&&(o.description=t),e.pageGuid&&(o.pageGuid=e.pageGuid),Vn(e)&&(o.dialog={action:"accept"}),o}function wr(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()}}function Mn(e){let r=wr(e);return e.dialog?`${r} ${n.dim(`\u2192 dialog: ${e.dialog.action==="accept"?"OK":"Cancel"}`)}`:r}async function Wn(e){let r=e.filter(t=>t.dialog);if(r.length===0||!process.stdin.isTTY)return;n.info(""),n.info(`${r.length===1?"A step":`${r.length} steps`} opened a browser dialog. Which button did you press?`);let o=_n({input:process.stdin,output:process.stdout});try{for(let t of r)(await o.question(` ${n.dim(String(t.index).padStart(2))} ${wr(t)} [O]K / [c]ancel: `)).trim().toLowerCase().startsWith("c")&&(t.dialog={action:"dismiss"})}finally{o.close()}}async function yr(e,r){let{assertLicensed:o}=await import("./gate.mjs"),t=await o();t.note&&n.warn(t.note),D(e);let i=y(),s=await T(i.configPath),a=O(i,e);if(Pn(a)&&!r.force)throw new Error(`Workflow "${e}" already exists at ${hr.relative(i.repoRoot,a)}. Re-run with --force to overwrite it.`);await On(i.workflowsDir,{recursive:!0});let c=await ur(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??_e,d=r.browser,u=r.channel;if(r.defaultBrowser){(r.browser||r.channel)&&n.warn("--default-browser overrides -b / --channel.");let f=cr();f?(d=f.browser,u=f.channel,f.approximated?n.warn(`Your default browser is ${f.label}, which Playwright can't drive directly \u2014 recording in ${u??d}.`):n.info(n.dim(`Recording in your default browser: ${f.label}`))):(n.warn("Couldn't detect your default browser; recording in bundled Chromium."),d="chromium",u=void 0)}if(r.url){let f=await pr(r.url);if(f.reachable===!1)throw new Error(`Nothing is listening at ${r.url} (connection refused on ${f.host}:${f.port}). Start the app you want to record, then run this again.`)}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 p=await dr({url:r.url,browser:d,channel:u,userDataDir:r.userDataDir,testIdAttribute:l}),m=Un(p.actions.filter(Dn));if(m.length===0){if(p.exitCode!==0)throw new Error(`Playwright codegen exited with code ${p.exitCode} before anything was recorded. Its output is above \u2014 commonly the browser failed to open, or a page the recording needed was unreachable. If it persists against a page that loads fine, 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 g=m.map(Fn);await Wn(g);let v=g.find(f=>f.action==="navigate"),w={schemaVersion:U,name:e,createdAt:new Date().toISOString(),startUrl:r.url??v?.params.url,browser:p.header.browserName??d??"chromium",channel:u,testIdAttribute:l,steps:g};await gr(a,w),n.info("");for(let f of g)n.info(` ${n.dim(String(f.index).padStart(2))} ${Mn(f)}`);n.info(""),n.success(`Saved ${g.length} step${g.length===1?"":"s"} to ${hr.relative(i.repoRoot,a)}`),g.some(f=>f.dialog)&&n.info(n.dim('Steps marked "\u2192 dialog" answer it on replay. To answer a prompt(), set "dialog": { "action": "accept", "promptText": "..." } on that step.')),g.some(f=>f.action==="fill"&&f.params.text)&&n.warn("Recorded steps include text you typed. Check the workflow file before sharing it.")}import{existsSync as qn}from"node:fs";import{mkdir as zn,writeFile as Xn}from"node:fs/promises";import Ir from"node:path";import{chromium as M,firefox as Bn,selectors as Gn,webkit as Hn}from"playwright";var Jn={chromium:M,firefox:Bn,webkit:Hn};async function Kn(e,r){let o=!r.headed,t=r.slowMoMs&&r.slowMoMs>0?r.slowMoMs:void 0;if(r.cdpEndpoint){let c=await M.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 M.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 M.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(Jn[e.browser]??M).launch({headless:o,slowMo:t}),a=await s.newContext();return{context:a,page:await a.newPage(),close:()=>s.close()}}function vr(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 ie(e){return typeof e=="string"?e:void 0}function br(e){return Array.isArray(e)?e.filter(r=>typeof r=="string"):[]}async function Yn(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=ie(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:ie(r.params.button)??"left",clickCount:typeof r.params.clickCount=="number"?r.params.clickCount:r.action==="dblclick"?2:1,modifiers:vr(r.params.modifiers)});return}case"fill":await o().fill(ie(r.params.text)??"");return;case"press":{let t=ie(r.params.key);if(!t)throw new Error(`Step ${r.index} (press) has no key.`);await o().press([...vr(r.params.modifiers),t].join("+"));return}case"check":await o().check();return;case"uncheck":await o().uncheck();return;case"select":await o().selectOption(br(r.params.options));return;case"setInputFiles":await o().setInputFiles(br(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 $r(e,r={}){e.testIdAttribute&&Gn.setTestIdAttribute(e.testIdAttribute);let o={...r,channel:r.channel??e.channel},t=await Kn(e,o),i=0,s=[],a,c=l=>{let d=a?.dialog??{action:r.dialogDefault??"accept"},u=l.type()==="prompt",p=u&&d.action==="accept"?d.promptText??l.defaultValue():void 0;s.push({...a?{step:a.index}:{},type:l.type(),message:l.message(),...u?{defaultValue:l.defaultValue()}:{},action:d.action,...p!==void 0?{promptText:p}:{},at:new Date().toISOString()}),n.step(` ${n.dim(`${l.type()} ${JSON.stringify(l.message())} \u2192 ${d.action}`)}`+(p!==void 0?n.dim(` ${JSON.stringify(p)}`):"")),(d.action==="accept"?l.accept(p):l.dismiss()).catch(()=>{})};try{let{context:l}=t;r.timeoutMs!==void 0&&l.setDefaultTimeout(r.timeoutMs);let d=t.page;d.on("dialog",c),l.on("page",u=>{u.on("dialog",c),d=u});for(let u of e.steps){n.step(`${String(u.index).padStart(2)} ${u.action}`+(u.description?` ${n.dim(u.description)}`:"")),a=u;try{await Yn(d,u)}catch(p){return{stepsTotal:e.steps.length,stepsReplayed:i,dialogs:s,error:p instanceof Error?p:new Error(String(p)),failedStepIndex:u.index}}if(i+=1,d.isClosed()){let p=l.pages().at(-1);p&&(d=p)}}return{stepsTotal:e.steps.length,stepsReplayed:i,dialogs:s}}finally{await t.close()}}function Sr(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 kr=[];function se(e){kr.push(e)}function Rr(e){return kr.map(r=>r(e)).filter(r=>!!r)}var Er=!1;function Cr(){Er||(Er=!0,se(qe),se(Ze),se(Ke))}var Qn=1,Zn=500;function eo(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?Zn:0}function W(e){return e instanceof Error?e.message:String(e)}function ro(e){return e.replace(/\x1b\[[0-9;]*m/g,"")}async function xr(e){for(let r of[...e].reverse())try{await r.dispose()}catch(o){n.warn(`${r.name}: dispose failed: ${W(o)}`)}}async function jr(e,r){let{assertLicensed:o}=await import("./gate.mjs"),t=await o();t.note&&n.warn(t.note),D(e);let i=y(),s=await T(i.configPath),a=O(i,e);if(!qn(a))throw new Error(`No workflow named "${e}". Record it first with: verirun record ${e}`);let c=await oe(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}".`);if(r.dialog!==void 0&&r.dialog!=="accept"&&r.dialog!=="dismiss")throw new Error(`--dialog must be "accept" or "dismiss", got "${r.dialog}".`);let d=r.dialog,u=(r.user??s.userFilter)?.trim()||void 0;Cr();let p=Rr(s),m=Ve(),g=Fe(i,e,m);await zn(g,{recursive:!0});let v={config:s,runDir:g,workflowName:e,userFilter:u};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(f=>f.name).join(", ")}`)),u&&n.info(n.dim(`User filter: entries mentioning "${u}"`)),n.info("");let w=[];try{for(let f of p)await f.start(v),w.push(f)}catch(f){let h=p[w.length];throw await xr(w),new Error(`Log source "${h?.name??"?"}" failed to start: ${W(f)}`)}try{let f=new Date().toISOString(),h=await $r(c,{headed:r.headed,slowMoMs:eo(r),timeoutMs:l,channel:r.channel,userDataDir:r.userDataDir,cdpEndpoint:r.cdp,dialogDefault:d}),$=new Date().toISOString(),E={startedAt:f,endedAt:$};h.error?n.error(`Replay failed at step ${h.failedStepIndex}: ${W(h.error)}`):n.success(`Replayed ${h.stepsReplayed} step${h.stepsReplayed===1?"":"s"}`);let j=[],A=[],B=0;for(let S of w)try{let x=await S.collect(v,E);B+=x.length,u&&(x=x.filter(_r=>Sr(_r,u))),A.push(...x),j.push({id:S.id,name:S.name,entries:x.length})}catch(x){n.warn(`${S.name}: log collection failed: ${W(x)}`),j.push({id:S.id,name:S.name,entries:0})}u&&A.length===0&&B>0&&n.warn(`${B} log entr${B===1?"y":"ies"} collected, none mention "${u}".`),A.sort((S,x)=>(S.timestamp??"").localeCompare(x.timestamp??""));let Or={schemaVersion:Qn,workflow:e,status:h.error?"failed":"ok",window:E,steps:{total:h.stepsTotal,replayed:h.stepsReplayed,...h.failedStepIndex!==void 0?{failedAt:h.failedStepIndex}:{}},...h.error?{error:ro(W(h.error))}:{},...u?{filter:{user:u}}:{},dialogs:h.dialogs,sources:j,entries:A},Ie=Ir.join(g,"logs.json");await Xn(Ie,`${JSON.stringify(Or,null,2)}
|
|
38
|
+
`,"utf8"),n.info("");for(let S of j)n.info(` ${S.name.padEnd(10)} ${S.entries} entr${S.entries===1?"y":"ies"}`);n.info(""),n.success(`Logs written to ${Ir.relative(i.repoRoot,Ie)}`),h.error&&(process.exitCode=1)}finally{await xr(w)}}import{existsSync as Ar}from"node:fs";import{readFile as to}from"node:fs/promises";import Ce from"node:path";var no=new Set(["navigate","click","dblclick","fill","press","check","uncheck","select","setInputFiles","openPage","closePage"]),oo=/^assert/,io=new Set(["click","dblclick","fill","press","check","uncheck","select","setInputFiles"]),so={navigate:["url"],fill:["text"],press:["key"],select:["values"],setInputFiles:["files"]};function ao(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(oo.test(i.action)){o(a,"warning",`"${i.action}" is skipped at replay \u2014 it asserts nothing`);return}if(!no.has(i.action)){o(a,"error",`unknown action "${i.action}" \u2014 a run stops here`);return}io.has(i.action)&&!i.selector&&o(a,"error",`"${i.action}" needs a "selector"`);for(let c of so[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}"`)}if(i.dialog!==void 0){let c=i.dialog;!c||typeof c!="object"||c.action!=="accept"&&c.action!=="dismiss"?o(a,"error",'dialog.action must be "accept" or "dismiss"'):c.promptText!==void 0&&typeof c.promptText!="string"?o(a,"error","dialog.promptText must be a string"):c.promptText!==void 0&&c.action==="dismiss"&&o(a,"warning","dialog.promptText is ignored when the dialog is dismissed")}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}function co(e,r){let o=new Map,t=s=>{if(!s.selector)return;let a=o.get(s.selector);a||o.set(s.selector,a={dialogs:new Map,allOpenOne:!0}),(!s.dialogs||s.dialogs.length===0)&&(a.allOpenOne=!1);for(let c of s.dialogs??[])a.dialogs.set(`${c.type}|${c.message??c.messageRaw??""}`,c)};for(let s of r.nodes?.pages??[])for(let a of s.elements??[])t(a);for(let s of r.edges??[])t(s.trigger);let i=[];return e.forEach((s,a)=>{if(s.dialog||!s.selector)return;let c=o.get(s.selector);if(c?.allOpenOne)for(let l of c.dialogs.values()){let d=l.message!==void 0?` ${JSON.stringify(l.message)}`:"";i.push({step:a+1,level:"warning",message:`opens ${l.type}${d} and has no "dialog" \u2014 replay answers OK. `+(l.gates?'The handler reads the answer, so set "dialog": {"action": "accept"|"dismiss"} to pick the path.':'Set "dialog" to make that explicit.')})}}),i}async function lo(e){let r=Ce.join(e,"map","interaction-tree.json");if(Ar(r))try{return{file:r,tree:JSON.parse(await to(r,"utf8"))}}catch{return}}async function Tr(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=y(),i;if(r.endsWith(".json")?i=Ce.resolve(r):(D(r),i=O(t,r)),!Ar(i))throw new Error(`No such workflow file: ${i}`);let s=await oe(i),a=ao(s.steps),c=await lo(t.dataDir);c&&(a.push(...co(s.steps,c.tree)),a.sort((d,u)=>d.step-u.step));let l=a.filter(d=>d.level==="error");if(o.json){process.stdout.write(`${JSON.stringify({file:i,name:s.name,steps:s.steps.length,ok:l.length===0,findings:a},null,2)}
|
|
39
|
+
`),l.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 d of a){let u=`step ${d.step}`.padEnd(8);d.level==="error"?n.error(`${u} ${d.message}`):n.warn(`${u} ${d.message}`)}a.length===0?n.success(` Looks runnable. Try it: verirun run ${s.name}`):l.length===0?(n.info(""),n.success(` No errors. Try it: verirun run ${s.name}`)):(n.info(""),n.error(` ${l.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 ${U}.`)),n.info(n.dim(c?` Dialog hints from ${Ce.relative(t.repoRoot,c.file)} \u2014 re-run \`verirun map --report\` if the app changed.`:" Run `verirun map --report` once and this also flags steps that open a browser dialog."))}var Lr="6W4p+s1zHXEl0CuZCI+lDJBzWVhsqsye52iKjcyRDCOJwd2SVCA+hPFvZZRBo/z7lD0jUh+od3Pd3Mk+l5aKCg==",Pr="MCowBQYDK2VwAyEATFTl78zmb+BITZuy9mdPMtujnz1tAeVidJT3dccuhLg=";function ho(){if(Lr.startsWith("@@")||Pr.startsWith("@@"))return!0;try{let e=Nr.dirname(mo(import.meta.url)),r=po(Nr.join(e,"gate.mjs")),o=uo({key:Buffer.from(Pr,"base64"),format:"der",type:"spki"});return fo(null,r,o,Buffer.from(Lr,"base64"))}catch{return!1}}var R=new go;R.name("verirun").description("Record and replay app workflows, and capture backend logs for each run.").version(L);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 yr(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)").option("--dialog <answer>","answer browser dialogs a step has no saved answer for: accept (OK, default) or dismiss (Cancel)").action(async(e,r)=>{await jr(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 Ne(e)});R.command("logout").description("Disconnect this machine from your Verirun account").action(async()=>{await Le()});R.command("whoami").description("Show the connected account and subscription status").option("--server <url>","account server base URL").action(async e=>{await Pe(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 ar(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 Tr(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 an agent skill file (Claude Code, Cursor) instead of the plain reference").option("--install [agent]","with --skill: write it where the agent looks \u2014 claude (default), cursor, or all").action(async e=>{await He(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 rr(e,r)});async function wo(){ho()||(process.stderr.write(`verirun: this installation looks modified. Reinstall it:
|
|
40
40
|
|
|
41
41
|
npm install -g @verirun/cli
|
|
42
|
-
`),process.exit(1));try{await
|
|
42
|
+
`),process.exit(1));try{await R.parseAsync(process.argv)}catch(e){n.error(e instanceof Error?e.message:String(e)),process.exitCode=1}}wo();
|