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