ripplo 0.7.33 → 0.7.35
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/chunk-GLXPGXO6.js +164 -0
- package/dist/chunk-KAILSYCU.js +238 -0
- package/dist/daemon-4RH7ZUNM.js +2 -0
- package/dist/daemon-LUNDHEVG.js +102 -0
- package/dist/index.js +159 -154
- package/package.json +5 -5
- package/dist/chunk-APYROHWG.js +0 -163
- package/dist/chunk-DP5GPMT3.js +0 -238
- package/dist/daemon-WKOUQS3E.js +0 -90
- package/dist/daemon-XBKRUQRS.js +0 -2
|
@@ -0,0 +1,238 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import{B as ze,V as Je,W as Ke,Z as Qe,_ as Ge,a as N,b as De,g as _e,i as qe,j as He,k as We,l as g,m as Be,p as ie,q as h,r as F,s as Ve,w as I}from"./chunk-GLXPGXO6.js";import{b as Ue,d as f,e as y,g as Oe,h as w,i as Ne}from"./chunk-5VRJXHWH.js";import Ze from"fs";import W from"path";import{config as Rt}from"dotenv";import{z as q}from"zod";import{err as kt,ok as en}from"neverthrow";import _ from"fs";import le from"path";import{err as ae,ok as Xe}from"neverthrow";import{z as D}from"zod";var yt=le.join(".ripplo","project.json"),se=[".env",".env.local"],mt=D.object({envFiles:D.array(D.string().min(1)).optional(),projectId:D.string().min(1)});function Ye(e){return le.join(e,yt)}function de(e){let n=Ye(e);return _.existsSync(n)?gt(n).andThen(t=>{let r=mt.safeParse(t);return r.success?Xe({envFiles:r.data.envFiles??se,projectId:r.data.projectId}):ae({issues:r.error.issues.map(o=>`${o.path.join(".")}: ${o.message}`),kind:"project-file-invalid",path:n})}):ae({kind:"project-file-missing",path:n})}function ce(e){return de(e).match(n=>n,()=>{})}function gt(e){try{return Xe(JSON.parse(_.readFileSync(e,"utf8")))}catch(n){return ae({issues:[n instanceof Error?n.message:String(n)],kind:"project-file-invalid",path:e})}}function Vi({cwd:e,envFiles:n,projectId:t}){let r=Ye(e);_.mkdirSync(le.dirname(r),{recursive:!0});let o={projectId:t};n!=null&&!ht(n)&&(o.envFiles=[...n]),_.writeFileSync(r,JSON.stringify(o,null,2)+`
|
|
3
|
+
`)}function ht(e){return e.length!==se.length?!1:e.every((n,t)=>n===se[t])}function Zi(e){let t=ce(e)?.envFiles??[".env",".env.local"],r=W.join(e,".ripplo");t.forEach(o=>{let i=W.resolve(r,o);Ze.existsSync(i)&&Rt({override:!0,path:i,quiet:!0})}),H=void 0}var St=q.object({RIPPLO_APP_URL:q.url(),RIPPLO_ENGINE_URL:q.url(),RIPPLO_WEBHOOK_SECRET:q.string().min(1)}),H;function B(){return H!=null?en(H):wt().map(e=>(H=e,e))}function xt(e){let t=ce(e)?.envFiles??[],r=W.join(e,".ripplo");return t.map(o=>W.resolve(r,o)).filter(o=>!Ze.existsSync(o))}function wt(){let e=St.safeParse(process.env);if(!e.success)return kt({issues:e.error.issues.map(t=>`${t.path.join(".")}: ${t.message}`),kind:"env-invalid",missingEnvFiles:xt(process.cwd())});let n=e.data;return en({appUrl:n.RIPPLO_APP_URL,engineUrl:n.RIPPLO_ENGINE_URL,webhookSecret:n.RIPPLO_WEBHOOK_SECRET})}import{readFileSync as bt}from"fs";import{z as nn}from"zod";var Et=nn.object({version:nn.string()});function V(){let e=bt(new URL("../package.json",import.meta.url),"utf8");return Et.parse(JSON.parse(e)).version}import me from"fs";import z from"path";import{createJiti as $t}from"jiti";import{err as U,ok as an}from"neverthrow";import vt from"fs";import M from"path";import P from"typescript";function tn(e){let n=M.join(e,"index.ts"),t=Ct(e);vt.mkdirSync(M.dirname(t.tsBuildInfoFile??""),{recursive:!0});let r=P.createIncrementalCompilerHost(t),o=P.createIncrementalProgram({host:r,options:t,rootNames:[n]}),i=[...o.getSyntacticDiagnostics(),...o.getSemanticDiagnostics()];o.emit();let s=i.filter(d=>It(d,e));if(s.length===0)return{diagnostics:[],ok:!0};let l={getCanonicalFileName:d=>d,getCurrentDirectory:()=>M.dirname(e),getNewLine:()=>`
|
|
4
|
+
`};return{diagnostics:P.formatDiagnosticsWithColorAndContext(s,l).split(`
|
|
5
|
+
`).filter(d=>d.length>0),ok:!1}}function It(e,n){let t=e.file?.fileName;return t==null?!0:t.startsWith(n)}var Pt=M.join(".local","tsbuildinfo");function Ct(e){return{allowImportingTsExtensions:!0,allowJs:!1,esModuleInterop:!0,incremental:!0,module:P.ModuleKind.Preserve,moduleResolution:P.ModuleResolutionKind.Bundler,noEmit:!0,resolveJsonModule:!0,skipLibCheck:!0,strict:!1,target:P.ScriptTarget.ES2022,tsBuildInfoFile:M.join(e,Pt)}}import{createHash as Tt}from"crypto";import rn from"fs/promises";import ue from"path";import{err as C,ok as pe,Result as jt}from"neverthrow";var $=".ripplo/fixtures",fe=10*1024*1024,ye=50*1024*1024;async function on(e,n){let t=At(n);if(t.length===0)return pe({});let r=ue.join(e,$),o=await Promise.all(t.map(i=>Ft({fixturesRoot:r,name:i})));return jt.combine(o).andThen(Mt)}function At(e){let t=e.workflows.flatMap(r=>[...r.steps,...r.tests.flatMap(o=>o.steps)]).flatMap(r=>r.action.kind==="upload"?r.action.files:[]);return[...new Set(t)].toSorted((r,o)=>r.localeCompare(o))}async function Ft({fixturesRoot:e,name:n}){if(n.includes("..")||ue.isAbsolute(n))return C({kind:"fixture-invalid-name",name:n});let t=ue.join(e,n),r=await rn.lstat(t).catch(()=>null);if(r==null)return C({kind:"fixture-missing",name:n,path:t});if(r.isSymbolicLink())return C({kind:"fixture-symlink",name:n});if(!r.isFile())return C({kind:"fixture-not-file",name:n});let o=await rn.readFile(t);if(o.byteLength>fe)return C({kind:"fixture-too-large",name:n,size:o.byteLength});let i=Tt("sha256").update(o).digest("hex");return pe([n,{sha256:i,size:o.byteLength}])}function Mt(e){let n=e.reduce((t,[,r])=>t+r.size,0);return n>ye?C({kind:"fixtures-total-too-large",total:n}):pe(Object.fromEntries(e))}var T=".ripplo/ripplo.lock",L;async function sn(e){let{result:n}=await ge(e);return n}async function ge(e){let n=Ut(z.join(e,".ripplo"));if(L!=null&&L.fingerprint===n&&L.result.isOk())return{fingerprint:n,result:L.result};let t=await O(e);return L={fingerprint:n,result:t},{fingerprint:n,result:t}}async function O(e){let n=z.join(e,".ripplo"),t=z.join(n,"index.ts"),r=tn(n);return r.ok?(await Ot(t)).andThen(s=>Dt({entryPath:t,exported:s})).match(async s=>(await on(e,s)).map(u=>({...s,fixtures:u})).mapErr(u=>({error:u,kind:"fixture-failed"})),s=>Promise.resolve(U(s))):U({diagnostics:r.diagnostics,kind:"typecheck-failed"})}var Lt=new Set([".local","debug","node_modules"]);function Ut(e){return ln(e).toSorted((n,t)=>n.localeCompare(t)).join("|")}function ln(e){return(me.existsSync(e)?me.readdirSync(e,{withFileTypes:!0}):[]).flatMap(t=>{if(Lt.has(t.name))return[];let r=z.join(e,t.name);if(t.isDirectory())return ln(r);let o=me.statSync(r);return[`${r}:${String(o.mtimeMs)}:${String(o.size)}`]})}async function Ot(e){try{let t=await $t(import.meta.url,{fsCache:!1,moduleCache:!1,sourceMaps:!0}).import(e),r=t!=null&&typeof t=="object"&&"default"in t?Reflect.get(t,"default"):t;return an(r)}catch(n){return U({kind:"load-threw",message:Nt(n)})}}function Nt(e){return e instanceof Error?e.message:String(e)}function Dt({entryPath:e,exported:n}){if(n==null||typeof n!="object"||!("lockfile"in n))return U({entryPath:e,kind:"not-ripplo"});let t=_e.safeParse(Reflect.get(n,"lockfile"));return t.success?an(t.data):U({issues:t.error.issues.map(r=>`${r.path.join(".")}: ${r.message}`),kind:"invalid-lockfile"})}function j(e,n){return n==null?`Load \`/ripplo:${e}\` skill for instructions.`:`Load \`/ripplo:${e}\` skill for instructions on ${n}.`}function xa(e){return e.length===1?j(e[0]):`Before proceeding, load the ${e.map(t=>`\`/ripplo:${t}\``).join(" and ")} skills \u2014 every one, each carries rules the others don't.`}function K(e){return[`Compilation failed: ${_t(e)}`,j("create","DSL authoring + lint rules")].join(`
|
|
6
|
+
`)}function Ia(){return`${T} is up to date`}function Pa(e){return[`${T} is ${e==="missing"?"missing":"out of date"} \u2014 run \`npx ripplo compile\` and commit the result`,j("setup")].join(`
|
|
7
|
+
`)}function Ca(){return`Wrote ${T}`}function _t(e){switch(e.kind){case"typecheck-failed":return["TypeScript errors in .ripplo/:",...dn(e.diagnostics)].join(`
|
|
8
|
+
`);case"not-ripplo":return`${e.entryPath} must default-export a Ripplo (createRipplo({ entities, singletons, workflows })). Check that the default export is the value returned by createRipplo, not a function or a re-export.`;case"invalid-lockfile":return["Lockfile failed schema validation (stale or hand-edited .ripplo/ripplo.lock?):",...dn(e.issues),"Regenerate with `npx ripplo compile` \u2014 never hand-edit the lockfile."].join(`
|
|
9
|
+
`);case"load-threw":return[`.ripplo/index.ts threw while loading: ${e.message}`,"Usually a bad import or a top-level throw in .ripplo/ \u2014 run `npx ripplo compile` for the stack."].join(`
|
|
10
|
+
`);case"fixture-failed":return qt(e.error)}}function dn(e,n=8){return e.length<=n?e:[...e.slice(0,n),`\u2026 and ${String(e.length-n)} more`]}function qt(e){switch(e.kind){case"fixture-missing":return`Fixture "${e.name}" not found at ${e.path} \u2014 add the file under .ripplo/fixtures/ or fix the upload() name.`;case"fixture-invalid-name":return`Invalid fixture name "${e.name}" \u2014 upload() takes a bare name under .ripplo/fixtures/, no .. or absolute paths.`;case"fixture-symlink":return`Fixture "${e.name}" is a symlink \u2014 only regular files are allowed.`;case"fixture-not-file":return`Fixture "${e.name}" is not a regular file.`;case"fixture-too-large":return`Fixture "${e.name}" is ${J(e.size)} \u2014 over the ${J(fe)} per-file limit.`;case"fixtures-total-too-large":return`Fixtures total ${J(e.total)} \u2014 over the ${J(ye)} limit.`}}function J(e){return`${String(Math.round(e/(1024*1024)*10)/10)} MB`}var Q=class extends Error{failure;constructor(n){super(n.kind),this.name="CliError",this.failure=n}};function $a(e){return e instanceof Q?he(e.failure):e instanceof Error?e.message:String(e)}function he(e){switch(e.kind){case"project-file-missing":return[`Missing ${e.path} \u2014 this directory is not a Ripplo project.`,"Run `npx ripplo init` to create it (or cd into the project root).",j("setup")].join(`
|
|
11
|
+
`);case"project-file-invalid":return[`${e.path} is invalid:`,...e.issues.map(n=>` ${n}`),"Fix the file by hand or re-run `npx ripplo init`."].join(`
|
|
12
|
+
`);case"not-authenticated":return["Not signed in. Run `npx ripplo auth login`.","(Claude Code: run it yourself in the background \u2014 the user just approves in the browser.)"].join(`
|
|
13
|
+
`);case"env-invalid":return Ht(e);case"playwright-install-failed":return["Playwright browser install failed \u2014 Chromium is still missing.","Run `npx playwright install chromium` and check its output for network, proxy, or disk-space errors."].join(`
|
|
14
|
+
`);case"gitdir-unrecognized":return`Unrecognized .git file at ${e.marker} \u2014 expected a directory or a "gitdir:" pointer (worktree). Is the repo corrupted?`;case"gitdir-empty":return`Empty gitdir pointer at ${e.marker} \u2014 the worktree's .git file points nowhere. Re-create the worktree.`;case"oauth-device-code-failed":return[`Could not start sign-in (device-code request failed): ${e.description}`,"Is the Ripplo server reachable? Check RIPPLO_SERVER_URL and retry."].join(`
|
|
15
|
+
`);case"oauth-authorization-failed":return[`Sign-in failed (${e.code}): ${e.description}`,e.code==="expired_token"?"The approval window expired \u2014 run `npx ripplo auth login` again.":"Run `npx ripplo auth login` to retry."].join(`
|
|
16
|
+
`);case"compilation-failed":return K(e.error)}}function Ht(e){let n=e.missingEnvFiles.length===0?[]:["Declared env files not found:",...e.missingEnvFiles.map(t=>` ${t}`),"In a git worktree? Env files aren't copied from the main checkout \u2014 recreate them, or symlink to a shared file outside the working tree."];return["Env config invalid:",...e.issues.map(t=>` ${t}`),"Add the missing values to the env files declared in .ripplo/project.json.",...n].join(`
|
|
17
|
+
`)}import{err as Vt,ok as zt}from"neverthrow";import{z as Re}from"zod";var Wt="https://ripplo.ai";function un(){return fn().RIPPLO_SERVER_URL}function pn(){return fn().RIPPLO_PROJECT_ID}var Bt=Re.object({RIPPLO_PROJECT_ID:Re.string().min(1).optional(),RIPPLO_SERVER_URL:Re.string().min(1).default(Wt)}),cn;function fn(){return cn??=Bt.parse(process.env),cn}import yn from"fs";import ke from"path";function mn(e){let n=yn.realpathSync(e),t=n,r=ke.dirname(t);for(;r!==t;){if(yn.existsSync(ke.join(t,".git")))return t;t=r,r=ke.dirname(t)}return n}function gn(e){return de(e).andThen(n=>B().andThen(t=>{let r=un(),o=Ne(r);return o==null?Vt({kind:"not-authenticated"}):zt({appUrl:t.appUrl,cwd:mn(e),engineUrl:t.engineUrl,projectId:pn()??n.projectId,ripploServerUrl:r,token:o,tunnelAuth:void 0,webhookSecret:t.webhookSecret})}))}import hn from"fs";import{checkSync as Jt,lockSync as Kt}from"proper-lockfile";var Qt="dev.pid",Rn=15e3;function kn(e){return w(e,Qt)}function Sn(e){try{return Jt(kn(e),{realpath:!1,stale:Rn})}catch{return!1}}var Se=class extends Error{pid;cwd;constructor({cwd:n,pid:t}){super("dev-lock-held"),this.name="DevLockHeldError",this.pid=t,this.cwd=n}};function Xa({cwd:e,onCompromised:n}){Oe(e);let t=kn(e),r=Gt({cwd:e,onCompromised:n,path:t});return hn.writeFileSync(t,String(process.pid)),()=>{try{r()}catch{}}}function Gt({cwd:e,onCompromised:n,path:t}){try{return Kt(t,{realpath:!1,stale:Rn,onCompromised:()=>{n()}})}catch(r){throw Xt(r)?new Se({cwd:e,pid:Yt(t)}):r}}function Xt(e){if(!(e instanceof Error)||!("code"in e))return!1;let{code:n}=e;return n==="ELOCKED"}function Yt(e){try{let n=hn.readFileSync(e,"utf8").trim(),t=Number.parseInt(n,10);return Number.isFinite(t)&&t>0?t:null}catch{return null}}import Zt from"p-queue";var er=4,nr={"p0-ui":3,"p1-cli":2,"p2-cover":1,"p3-explore":0},G=new Zt({concurrency:er}),k={headedActive:0,interactiveActive:0,interactiveQueued:0},xn={current:null};function es({headed:e,task:n,workClass:t}){let r=nr[t];return t==="p3-explore"?G.add(n,{priority:r}):(k.interactiveQueued+=1,X(),G.add(()=>tr({headed:e,task:n}),{priority:r}))}function ns(e){!Number.isFinite(e)||e<1||(G.concurrency=Math.floor(e),X())}function xe(){return{active:k.interactiveActive,headedActive:k.headedActive,poolSize:G.concurrency,queued:k.interactiveQueued}}function ts(e){xn.current=e}async function tr({headed:e,task:n}){k.interactiveQueued-=1,k.interactiveActive+=1,k.headedActive+=e?1:0,X();try{return await n()}finally{k.interactiveActive-=1,k.headedActive-=e?1:0,X()}}function X(){xn.current?.()}import we from"fs";import be from"path";function wn(e){try{let n=rr(e);if(n==null)return;let t=be.join(n,"HEAD"),r=we.readFileSync(t,"utf8").trim(),o="ref: refs/heads/";return r.startsWith(o)?r.slice(o.length):r.length===0?void 0:r.slice(0,7)}catch{return}}function rr(e){let n=be.join(e,".git");if(we.statSync(n).isDirectory())return n;let r=we.readFileSync(n,"utf8").trim(),o="gitdir:";if(!r.startsWith(o))return;let i=r.slice(o.length).trim();if(i.length!==0)return be.resolve(e,i)}import or from"crypto";import{readFile as bn}from"fs/promises";import En from"path";import{graphql as ir}from"gql.tada";import{err as ar,ok as sr}from"neverthrow";var lr=ir(`
|
|
18
|
+
mutation SyncDevSession(
|
|
19
|
+
$projectId: String!
|
|
20
|
+
$cwd: String!
|
|
21
|
+
$branch: String
|
|
22
|
+
$lockfileContent: String
|
|
23
|
+
$fixtures: [SyncDevFixtureInput!]
|
|
24
|
+
$preconditions: [SyncDevPreconditionInput!]!
|
|
25
|
+
$singletons: [SyncDevSingletonInput!]
|
|
26
|
+
$workflows: [SyncDevWorkflowInput!]!
|
|
27
|
+
) {
|
|
28
|
+
syncDevSession(
|
|
29
|
+
projectId: $projectId
|
|
30
|
+
cwd: $cwd
|
|
31
|
+
branch: $branch
|
|
32
|
+
lockfileContent: $lockfileContent
|
|
33
|
+
fixtures: $fixtures
|
|
34
|
+
preconditions: $preconditions
|
|
35
|
+
singletons: $singletons
|
|
36
|
+
workflows: $workflows
|
|
37
|
+
) {
|
|
38
|
+
id
|
|
39
|
+
hooksPaused
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
`);async function hs(e,n){let t=await O(e);if(t.isErr())return ar({error:t.error,kind:"compilation-failed"});let r=await Ee({config:n,cwd:e,lockfile:t.value});return sr({devSessionId:r.devSessionId,lockfile:t.value})}async function Ee(e){let n=He(e.lockfile);return cr({config:e.config,cwd:e.cwd,fixtures:e.lockfile.fixtures,payload:n})}function dr(e){return or.createHash("sha256").update(JSON.stringify(e)).digest("hex")}async function cr({config:e,cwd:n,fixtures:t,payload:r}){let o=dr(r),i=wn(n),s=await pr(n),l=await ur(n,t),u=await f({config:e,document:lr,variables:{branch:i??null,cwd:n,fixtures:l,lockfileContent:s,preconditions:r.preconditions.map(d=>({depends:[...d.depends],description:d.description,name:d.name,returns:[...d.returns]})),projectId:e.projectId,singletons:r.singletons.map(d=>({defaultValue:d.defaultValue,description:d.description,name:d.name,type:d.type})),workflows:r.workflows.map(d=>({expectedOutcome:d.expectedOutcome,name:d.name,preconditions:[...d.preconditions],requiresKeys:d.requiresKeys.map(p=>({namespace:p.namespace,preconditionName:p.preconditionName})),slug:d.slug,sourcePath:d.sourcePath,spec:JSON.stringify(d.spec)}))}});if(u.syncDevSession==null)throw new Error("syncDevSession returned null");return{devSessionId:u.syncDevSession.id,hash:o,hooksPaused:u.syncDevSession.hooksPaused}}async function ur(e,n){let t=Object.entries(n);return Promise.all(t.map(async([r,o])=>({contentBase64:(await bn(En.join(e,$,r))).toString("base64"),sha256:o.sha256})))}async function pr(e){try{return await bn(En.join(e,T),"utf8")}catch{return null}}import{randomUUID as Vr}from"crypto";import{createId as zr}from"@paralleldrive/cuid2";import{CancellationTokenSource as Jr,ResponseError as Kr}from"vscode-jsonrpc/node";import{graphql as fr}from"gql.tada";var yr=fr(`
|
|
43
|
+
mutation DaemonCreateRun(
|
|
44
|
+
$id: String
|
|
45
|
+
$workflowId: String!
|
|
46
|
+
$testId: String
|
|
47
|
+
$clientVersion: String
|
|
48
|
+
$executor: RunExecutor
|
|
49
|
+
$target: RunTarget
|
|
50
|
+
$lockfileHash: String
|
|
51
|
+
) {
|
|
52
|
+
createRun(
|
|
53
|
+
id: $id
|
|
54
|
+
workflowId: $workflowId
|
|
55
|
+
testId: $testId
|
|
56
|
+
executor: $executor
|
|
57
|
+
target: $target
|
|
58
|
+
clientVersion: $clientVersion
|
|
59
|
+
lockfileHash: $lockfileHash
|
|
60
|
+
) {
|
|
61
|
+
__typename
|
|
62
|
+
... on MutationCreateRunSuccess {
|
|
63
|
+
data {
|
|
64
|
+
id
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
... on LimitExceededError {
|
|
68
|
+
code
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
`);async function vn(e){try{let t=(await f({config:e.config,document:yr,variables:mr(e)})).createRun;return t==null?Y({detail:"create-run-null",type:"generic"}):t.__typename==="MutationCreateRunSuccess"?null:t.__typename==="LimitExceededError"?Y({code:t.code,type:"limit"}):Y({detail:t.__typename,type:"generic"})}catch(n){return gr(n)}}function mr({executor:e,lockfileHash:n,runId:t,target:r}){return{clientVersion:V(),executor:e,id:t,lockfileHash:n,target:e==="cloud"?"tunnel":void 0,testId:r.testId,workflowId:r.workflowId}}function Y(e){return{kind:"dispatch-error",reason:e}}function gr(e){return e instanceof Ue?{detail:e.message,kind:"infra-error"}:Y({detail:e instanceof Error?e.message:String(e),type:"generic"})}import{createMessageConnection as hr,NotificationType as In,RequestType as Rr,RequestType0 as Pn,SocketMessageReader as kr,SocketMessageWriter as Sr}from"vscode-jsonrpc/node";import{z as a}from"zod";var xr="daemon.sock",wr="daemon.log";function Is(e){return w(e,xr)}function Ps(e){return w(e,wr)}function Cn(e){return hr(new kr(e),new Sr(e))}var Tn=a.object({all:a.boolean(),headed:a.boolean(),tests:a.array(a.string())}),Cs=a.object({jobId:a.string(),total:a.number()}),br=a.enum(["on","off"]),Er=a.object({attempts:a.number(),findings:a.number()}),Ts=a.object({active:a.number(),explorer:br,exploring:a.number(),progress:Er,queued:a.number(),sseHealth:a.object({detail:a.string().optional(),ok:a.boolean()}).optional(),version:a.string().optional()}),vr=a.enum(["MAX_RUNS","OVERAGE_CAP","MAX_AGENTS","MAX_CONCURRENT_RUNS","MAX_PROJECTS"]),Ir=a.discriminatedUnion("type",[a.object({code:vr,type:a.literal("limit")}),a.object({detail:a.string(),type:a.literal("generic")})]),ve=a.discriminatedUnion("kind",[a.object({kind:a.literal("pass")}),a.object({findingLines:a.array(a.string()),kind:a.literal("findings")}),a.object({detail:a.string(),kind:a.literal("error")}),a.object({kind:a.literal("dispatch-error"),reason:Ir}),a.object({detail:a.string(),kind:a.literal("dispatch-timeout")}),a.object({detail:a.string(),kind:a.literal("infra-error")})]),Pr=a.discriminatedUnion("kind",[a.object({kind:a.literal("test-started"),runId:a.string(),testName:a.string(),workflowName:a.string()}),a.object({kind:a.literal("test-outcome"),outcome:ve,runId:a.string(),testName:a.string(),workflowName:a.string()})]),js=a.object({event:Pr,jobId:a.string()}),As=a.object({failed:a.number(),jobId:a.string(),notRun:a.number(),passed:a.number()}),Fs=a.discriminatedUnion("code",[a.object({code:a.literal("compile-failed"),detail:a.string(),diagnostics:a.array(a.string()).default([])}),a.object({code:a.literal("selection-conflicting-flags")}),a.object({code:a.literal("selection-nothing-selected")}),a.object({code:a.literal("selection-unknown-ids"),known:a.array(a.string()),unknown:a.array(a.string())}),a.object({code:a.literal("scope-failed"),detail:a.string()}),a.object({code:a.literal("app-unreachable"),detail:a.string(),url:a.string()}),a.object({code:a.literal("sync-failed"),detail:a.string()}),a.object({code:a.literal("bad-message")})]),jn=new Rr("ripplo/enqueue"),An=new Pn("ripplo/status"),Fn=new Pn("ripplo/shutdownIfIdle"),Mn=new In("ripplo/jobEvent"),$n=new In("ripplo/jobDone");import{graphql as Cr}from"gql.tada";async function Ln(e,n){let r=(await f({config:e,document:Tr,variables:{cwd:n,projectId:e.projectId}})).project?.devSession?.workflows??[];return new Map(r.flatMap(o=>o.tests.map(i=>[`${o.slug}/${i.slug}`,{testId:i.id,workflowId:o.id}])))}var Tr=Cr(`
|
|
73
|
+
query DaemonWorkflows($projectId: String!, $cwd: String!) {
|
|
74
|
+
project(id: $projectId) {
|
|
75
|
+
id
|
|
76
|
+
devSession(cwd: $cwd) {
|
|
77
|
+
id
|
|
78
|
+
workflows {
|
|
79
|
+
id
|
|
80
|
+
slug
|
|
81
|
+
tests {
|
|
82
|
+
id
|
|
83
|
+
slug
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
`);import{CancellationTokenSource as jr}from"vscode-jsonrpc/node";function Ie(e){return`${e.workflowSlug}/${e.testSlug}`}function Un(e){let{headed:n,inflight:t,jobId:r,lockfileHashValue:o,onExpire:i,runId:s,selection:l,timeoutMs:u}=e,d=Ie(l),p=`${d}@${o}@${String(n)}`,c=t.get(p);if(c!=null)return c.jobIds.add(r),null;let m={cancellation:new jr,claimed:!1,claimKey:d,headed:n,inflightKey:p,jobIds:new Set([r]),runId:s,testName:l.testName,timer:null,workflowName:l.workflowName};return m.timer=setTimeout(()=>{Z(t,m),i(m)},u),t.set(p,m),m}function Z(e,n){n.timer!=null&&(clearTimeout(n.timer),n.timer=null),e.delete(n.inflightKey)}function Pe(e,n){let t=[...e.values()].find(r=>r.runId===n&&!r.claimed);return t==null?null:(t.claimed=!0,t.timer!=null&&(clearTimeout(t.timer),t.timer=null),t)}function On(e,n){[...e.values()].filter(t=>t.jobIds.has(n)).forEach(t=>{t.jobIds.delete(n),t.jobIds.size===0&&(Z(e,t),t.cancellation.cancel())})}import{err as Ce,ok as Nn}from"neverthrow";function _n({all:e,ids:n,lockfile:t}){if(e&&n.length>0)return Ce({kind:"conflicting-flags"});if(e)return Nn(t.workflows.filter(i=>!i.stub).flatMap(i=>i.tests.map(s=>h(s))));if(n.length===0)return Ce({kind:"nothing-selected"});let r=n.map(i=>({id:i,refs:Fr(t,i)})),o=r.filter(i=>i.refs.length===0).map(i=>i.id);return o.length>0?Ce({kind:"unknown-ids",known:Ar(t),unknown:o}):Nn([...new Set(r.flatMap(i=>i.refs))])}function qn(e,n){let t=new Map(F(e).map(r=>[r.ref,{testName:r.test.name,testSlug:r.test.slug,workflowName:r.workflow.name,workflowSlug:g(r.workflow.name)}]));return n.map(r=>{let o=t.get(r);if(o==null)throw new Error(`selectionsFor: ref not in lockfile: ${r}`);return o})}function Ar(e){return e.workflows.map(n=>g(n.name))}function Fr(e,n){let t=e.workflows.find(r=>r.name===n||g(r.name)===g(n));return t!=null?t.tests.map(r=>h(r)):F(e).filter(r=>r.ref===n||Dn(r.ref)===Dn(n)).map(r=>r.ref)}function Dn(e){let n=e.lastIndexOf("/");return n===-1?g(e):`${g(e.slice(0,n))}/${g(e.slice(n+1))}`}import{err as Te,ok as Wn}from"neverthrow";import{graphql as Bn}from"gql.tada";import{execFileSync as Mr}from"child_process";var $r=256*1024*1024;function ee(e,n){return Mr("git",[...e],{cwd:n,encoding:"utf8",maxBuffer:$r,stdio:["ignore","pipe","pipe"]})}async function Vn({config:e,cwd:n,lockfile:t}){await Ur({config:e,cwd:n,lockfile:t});let r=await Nr(e);if(r.isErr())return Te(r.error);let o=new Map(t.workflows.filter(s=>!s.stub).map(s=>[g(s.name),s])),i=[...new Set(r.value)].flatMap(s=>{let l=o.get(s);return l==null?[]:l.tests.map(u=>h(u))});return i.length===0?Te({kind:"scope-empty"}):Wn(i)}var Lr=Bn(`
|
|
90
|
+
mutation AddDirtyTestsToScope($projectId: String!, $cwd: String!, $workflowSlugs: [String!]!) {
|
|
91
|
+
addDirtyTestsToScope(projectId: $projectId, cwd: $cwd, workflowSlugs: $workflowSlugs) {
|
|
92
|
+
__typename
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
`);async function Ur({config:e,cwd:n,lockfile:t}){let r=new Set(Dr(n)),o=t.workflows.filter(i=>i.sourcePath!=null&&r.has(i.sourcePath)).map(i=>g(i.name));o.length!==0&&await f({config:e,document:Lr,variables:{cwd:e.cwd,projectId:e.projectId,workflowSlugs:o}}).catch(i=>{y.warn({err:i},"auto-scope of dirty tests failed")})}var Or=Bn(`
|
|
96
|
+
query ScopeSelection($projectId: String!, $cwd: String!) {
|
|
97
|
+
project(id: $projectId) {
|
|
98
|
+
id
|
|
99
|
+
devSession(cwd: $cwd) {
|
|
100
|
+
id
|
|
101
|
+
scopeItems {
|
|
102
|
+
id
|
|
103
|
+
workflow {
|
|
104
|
+
id
|
|
105
|
+
slug
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
`);async function Nr(e){try{let t=(await f({config:e,document:Or,variables:{cwd:e.cwd,projectId:e.projectId}})).project?.devSession?.scopeItems??[];return Wn(t.flatMap(r=>r.workflow==null?[]:[r.workflow.slug]))}catch(n){return Te({detail:n instanceof Error?n.message:String(n),kind:"scope-fetch-failed"})}}var Hn=".ripplo/workflows/";function Dr(e){try{return ee(["status","--porcelain","--",".ripplo/workflows"],e).split(`
|
|
112
|
+
`).map(n=>n.slice(3).trim()).filter(n=>n.startsWith(Hn)&&n.endsWith(".ts")).map(n=>n.slice(Hn.length)).filter(n=>n!=="index.ts"&&!n.endsWith("/index.ts"))}catch{return[]}}import{graphql as _r}from"gql.tada";var qr=2e3,Hr=_r(`
|
|
113
|
+
query DaemonCloudRunStatus($runId: String!) {
|
|
114
|
+
run(id: $runId) {
|
|
115
|
+
status
|
|
116
|
+
failureReason
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
`);function Jn({config:e,onComplete:n,onStarted:t,runId:r,signal:o}){let i=!1,s,l=!1,u=async()=>{if(i||o.aborted)return;let d=await Wr(e,r).catch(()=>"unknown");if(!(i||o.aborted)){if(!l&&(d==="running"||zn(d))&&(l=!0,t()),zn(d)){i=!0,n(Br(d));return}s=setTimeout(()=>{u()},qr)}};return u(),{stop:()=>{i=!0,s!=null&&clearTimeout(s)}}}async function Wr(e,n){let r=(await f({config:e,document:Hr,variables:{runId:n}})).run?.status;return r??"unknown"}function zn(e){return e==="passed"||e==="failed"||e==="warning"||e==="cancelled"||e==="unready"}function Br(e){return e==="passed"?{kind:"pass"}:e==="failed"?{detail:"failed",kind:"error"}:e==="warning"?{findingLines:[],kind:"findings"}:e==="cancelled"?{detail:"cancelled",kind:"error"}:e==="unready"?{detail:"unready",kind:"error"}:{detail:"unknown",kind:"error"}}var Qr=12e4,Gr=-32099;function Xr(e){let n=new AbortController;return e.isCancellationRequested?(n.abort(),n.signal):(e.onCancellationRequested(()=>{n.abort()}),n.signal)}function hl(e){let n={...e,inflight:new Map,jobs:new Map};return{claim:t=>to(n,t),handleConnection:t=>{Yr(n,t)},idle:()=>Gn(n)}}function Yr(e,n){let t=Cn(n);t.onRequest(jn,(r,o)=>Zr({connection:t,ctx:e,params:r,token:o})),t.onRequest(An,()=>{let r=xe();return{active:r.active,queued:r.queued,sseHealth:e.sseHealth(),version:V(),...e.explorationStatus()}}),t.onRequest(Fn,()=>{let r=Gn(e);return r&&e.onShutdownRequest(),r}),t.onClose(()=>{eo(e,t)}),t.onError(r=>{y.warn({err:r},"ipc connection error")}),n.on("error",r=>{y.warn({err:r},"ipc socket error")}),t.listen()}function Gn(e){let n=xe();return e.jobs.size===0&&n.active===0&&n.queued===0}async function Zr({connection:e,ctx:n,params:t,token:r}){let o=Tn.safeParse(t);if(!o.success)throw Kn({code:"bad-message"});await n.ready;let i=await oo({config:n.config,cwd:n.cwd,message:o.data});if(i.kind==="error")throw Kn(i.error);let s=Vr(),l=new Jr;return r.onCancellationRequested(()=>{Xn(n,s)}),n.jobs.set(s,{cancellation:l,connection:e,failed:0,notRun:0,passed:0,total:i.selections.length}),fo({ctx:n,headed:o.data.headed,jobId:s,lockfileHashValue:i.lockfileHashValue,selections:i.selections,targetsByClaimKey:i.targetsByClaimKey,token:l.token}).catch(u=>{y.error({err:u},"ipc dispatch failed")}),{jobId:s,total:i.selections.length}}function Kn(e){return new Kr(Gr,e.code,e)}function Xn(e,n){let t=e.jobs.get(n);t!=null&&(t.cancellation.cancel(),e.jobs.delete(n),On(e.inflight,n))}function eo(e,n){[...e.jobs.entries()].filter(([,t])=>t.connection===n).forEach(([t])=>{Xn(e,t)})}function Yn(e,n,t){let r=e.jobs.get(n);r!=null&&(Qn(()=>r.connection.sendNotification(Mn,{event:t,jobId:n})),t.kind==="test-outcome"&&(no(r,t.outcome.kind),r.passed+r.failed+r.notRun>=r.total&&(Qn(()=>r.connection.sendNotification($n,{failed:r.failed,jobId:n,notRun:r.notRun,passed:r.passed})),e.jobs.delete(n))))}function Qn(e){Promise.resolve().then(e).catch(n=>{y.warn({err:n},"ipc notification failed")})}function no(e,n){if(n==="pass"){e.passed+=1;return}if(n==="dispatch-error"||n==="dispatch-timeout"||n==="infra-error"){e.notRun+=1;return}e.failed+=1}function A(e,n,t){n.jobIds.forEach(r=>{Yn(e,r,t)})}function to(e,n){let t=Pe(e.inflight,n);return t==null?null:{headed:t.headed,token:t.cancellation.token,finished:(r,o)=>{e.inflight.delete(t.inflightKey),A(e,t,{kind:"test-outcome",outcome:o,runId:t.runId,testName:t.testName,workflowName:t.workflowName})},started:()=>{A(e,t,{kind:"test-started",runId:t.runId,testName:t.testName,workflowName:t.workflowName})}}}function ro(e){return e.kind==="typecheck-failed"?e.diagnostics.slice(0,5):e.kind==="invalid-lockfile"?e.issues.slice(0,5):e.kind==="load-threw"?[e.message]:[]}async function oo({config:e,cwd:n,message:t}){return(await sn(n)).match(o=>io({config:e,cwd:n,lockfile:o,message:t}),o=>Promise.resolve({error:{code:"compile-failed",detail:o.kind,diagnostics:[...ro(o)]},kind:"error"}))}async function io({config:e,cwd:n,lockfile:t,message:r}){let o=await so(e.appUrl);if(o!=null)return{error:{code:"app-unreachable",detail:o,url:e.appUrl},kind:"error"};let i=await lo({config:e,cwd:n,lockfile:t});return i!=null?{error:{code:"sync-failed",detail:i},kind:"error"}:(await co({config:e,cwd:n,lockfile:t,message:r})).match(async l=>({kind:"ready",lockfileHashValue:qe(t),selections:qn(t,l),targetsByClaimKey:await Ln(e,n)}),l=>Promise.resolve({error:l,kind:"error"}))}var ao=2e3;async function so(e){try{return await fetch(e,{method:"HEAD",signal:AbortSignal.timeout(ao)}),null}catch(n){return n instanceof Error?n.message:String(n)}}async function lo(e){try{return await Ee(e),null}catch(n){return n instanceof Error?n.message:String(n)}}async function co({config:e,cwd:n,lockfile:t,message:r}){return!r.all&&r.tests.length===0?(await Vn({config:e,cwd:n,lockfile:t})).mapErr(uo):_n({all:r.all,ids:r.tests,lockfile:t}).mapErr(po)}function uo(e){return e.kind==="scope-empty"?{code:"selection-nothing-selected"}:{code:"scope-failed",detail:e.detail}}function po(e){switch(e.kind){case"conflicting-flags":return{code:"selection-conflicting-flags"};case"nothing-selected":return{code:"selection-nothing-selected"};case"unknown-ids":return{code:"selection-unknown-ids",known:[...e.known],unknown:[...e.unknown]}}}async function fo(e){await e.selections.reduce((n,t)=>n.then(()=>yo(e,t)),Promise.resolve())}async function yo(e,n){let{ctx:t,headed:r,jobId:o,lockfileHashValue:i,targetsByClaimKey:s,token:l}=e;if(l.isCancellationRequested)return;let u=Ie(n),d=s.get(u);if(d==null){Yn(t,o,{kind:"test-outcome",outcome:{kind:"dispatch-error",reason:{detail:"test-not-found",type:"generic"}},runId:"",testName:n.testName,workflowName:n.workflowName});return}let p=Un({headed:r,inflight:t.inflight,jobId:o,lockfileHashValue:i,runId:zr(),selection:n,timeoutMs:Qr,onExpire:m=>{A(t,m,{kind:"test-outcome",outcome:{detail:"dispatch-timeout",kind:"dispatch-timeout"},runId:"",testName:m.testName,workflowName:m.workflowName})}});if(p==null)return;let c=await mo(t,d,p.runId,i);if(c!=null){Z(t.inflight,p),A(t,p,{kind:"test-outcome",outcome:c,runId:"",testName:n.testName,workflowName:n.workflowName});return}t.executor==="cloud"&&go(t,p)}function mo(e,n,t,r){return vn({config:e.config,executor:e.executor,lockfileHash:r,runId:t,target:n})}function go(e,n){let t=Pe(e.inflight,n.runId);t!=null&&Jn({config:e.config,runId:t.runId,signal:Xr(t.cancellation.token),onComplete:r=>{e.inflight.delete(t.inflightKey),A(e,t,{kind:"test-outcome",outcome:r,runId:t.runId,testName:t.testName,workflowName:t.workflowName})},onStarted:()=>{A(e,t,{kind:"test-started",runId:t.runId,testName:t.testName,workflowName:t.workflowName})}})}import ho from"fs";import Ro from"path";async function vl(e){let n=Ro.join(e,".ripplo","index.ts");if(!ho.existsSync(n))return{appUrl:void 0,engineUrl:void 0,errors:[{message:".ripplo/index.ts not found",path:""}],valid:!1,warnings:[]};let t=await O(e);return t.isErr()?{appUrl:void 0,engineUrl:void 0,errors:[{message:K(t.error),path:".ripplo/"}],valid:!1,warnings:[]}:B().match(r=>({appUrl:r.appUrl,engineUrl:r.engineUrl,errors:[],valid:!0,warnings:[]}),r=>({appUrl:void 0,engineUrl:void 0,errors:[{message:he(r),path:""}],valid:!1,warnings:[]}))}async function Il(e){try{await fetch(e,{method:"HEAD",signal:AbortSignal.timeout(5e3)});return}catch{return`appUrl (${e}) is not responding. Make sure your dev server is running on that port.`}}async function Pl({appUrl:e,engineUrl:n}){let t=n.startsWith("http://")||n.startsWith("https://")?n:`${e}${n}`;try{return(await fetch(`${t}/setup`,{body:JSON.stringify({}),headers:{"Content-Type":"application/json"},method:"PUT",signal:AbortSignal.timeout(5e3)})).ok?"Engine endpoint accepted an unsigned request \u2014 webhook signature verification may be missing.":void 0}catch{return}}import wo from"fs";import ko from"fs";import je from"path";var So=["MERGE_HEAD","rebase-merge","rebase-apply","CHERRY_PICK_HEAD","REVERT_HEAD"];function Zn(e){let n=xo(e);return n==null?!1:So.some(t=>ko.existsSync(je.join(n,t)))}function xo(e){try{let n=ee(["rev-parse","--git-dir"],e).trim();return n.length===0?null:je.isAbsolute(n)?n:je.resolve(e,n)}catch{return null}}function bo(e){return w(e,"hooks-paused")}function Ol(e){return wo.existsSync(bo(e))||Zn(e)?!1:Sn(e)}import{createMessageConnection as et,IPCMessageReader as nt,IPCMessageWriter as tt,NotificationType as Eo,NotificationType0 as rt,RequestType as ot,RequestType0 as vo}from"vscode-jsonrpc/node";import{z as R}from"zod";var Wl=R.object({headed:R.boolean(),runId:R.string().min(1),testRef:R.string().min(1)}),Bl=R.object({lockfileJson:R.string().optional(),unavailable:R.string().optional()}),Vl=R.object({runId:R.string().min(1),span:De}),zl=R.object({outcome:ve,serverNotified:R.boolean()}),Jl=new rt("worker/ready"),Kl=new ot("worker/run"),Ql=new vo("worker/lockfile"),Gl=new ot("worker/exploreTrail"),Xl=new Eo("worker/span"),Yl=new rt("worker/shutdown");function Zl(e){let n=et(new nt(e),new tt(e));return n.listen(),n}function ed(){let e=et(new nt(process),new tt(process));return e.listen(),e}import{graphql as v}from"gql.tada";import{gzip as Mo}from"zlib";import{promisify as $o}from"util";import{existsSync as Fe,readFileSync as Me}from"fs";import ne from"path";import{graphql as E}from"gql.tada";function it(e){return[e.kind,e.target,e.value].filter(n=>n.length>0).join(" ")}var Io={"no-effect":"noEffect","required-state-unsatisfied":"requiredStateUnsatisfied",unresolvable:"unresolvable"},Po={"data-rule":"dataRule","page-rule":"pageRule",step:"step"},Co={aborted:"aborted","action-failed":"actionFailed","check-failed":"checkFailed","client-mount-missing":"clientMountMissing","conflicting-sessions":"conflictingSessions","driver-launch":"driverLaunch","engine-decode":"engineDecode","engine-http":"engineHttp","engine-network":"engineNetwork","engine-unreachable":"engineUnreachable","setup-missing-row":"setupMissingRow","state-identity":"stateIdentity"};function at(e){return e.kind==="consistency"?{consistency:{mismatch:Ao(e.mismatch),pending:e.pending}}:e.kind==="pending-check"?{pendingCheck:{budget:e.budget,source:Po[e.source.kind],...To(e.source)}}:e.kind==="unrunnable"?{unrunnable:{reason:Io[e.reason]}}:e.kind==="driver-error"?{driverError:{errorKind:Co[e.error.kind],message:Fo(e.error)}}:{impossibleAction:{subject:jo(e.step.action)}}}function To(e){return"check"in e?st(e.check,!1):{checkKind:void 0,expected:void 0,negated:void 0,subject:void 0}}function st(e,n){return e.kind==="not"?st(e.inner,!n):e.kind==="browser"?{checkKind:"browser",expected:e.value??void 0,negated:n,subject:ie(e.key)}:e.kind==="value"||e.kind==="text"?{checkKind:e.kind,expected:e.value,negated:n,subject:N(e.locator)}:{checkKind:e.kind,expected:void 0,negated:n,subject:N(e.locator)}}function jo(e){let n=e.locator==null?e.url??"":N(e.locator);return`${e.kind} ${n}`.trim()}function Ao(e){return e.kind==="wrong-value"?{wrongValue:{entity:e.entity,field:e.field,key:e.key,snapshot:b(e.snapshot),sut:b(e.sut)}}:e.kind==="expected-change"?{expectedChange:{entity:e.entity,field:e.field,key:e.key,value:b(e.value)}}:e.kind==="singleton-mismatch"?{singletonMismatch:{singleton:e.singleton,snapshot:b(e.snapshot),sut:b(e.sut)}}:e.kind==="unexpected-row"?{unexpectedRow:{entity:e.entity,key:e.key}}:e.kind==="browser-mismatch"?{singletonMismatch:{singleton:ie(e.key),snapshot:b(e.snapshot),sut:b(e.sut)}}:{missingRow:{entity:e.entity,key:e.key}}}function b(e){return e==null?null:String(e)}function Fo(e){return"message"in e?e.message:"detail"in e?e.detail:null}async function Lo({config:e,cwd:n,fixturesDir:t,headed:r,lockfile:o,runId:i,session:s,signal:l,test:u}){if(!await ai(e,i))return{kind:"dispatch-failed",reason:"already-claimed",runId:i};let p=ne.join(n,".ripplo","debug"),c=[];return(await s.runOnce({capture:!0,lockfile:o,onPhase:void 0,options:{baseUrl:e.appUrl,engineUrl:e.engineUrl,fixturesDir:t,generate:I,headed:r,secret:e.webhookSecret,tunnelAuth:e.tunnelAuth},params:void 0,runId:i,sequence:void 0,test:u,onEvent:S=>{c.push(S)}},l)).match(async S=>{let x=dt(c).flatMap(ft=>ft.findings),Le=Uo(x);return Le!=null?(await lt({config:e,debugDir:p,events:c,recordingOptional:!0,runId:i,stepSources:void 0}),{error:Le,kind:"error",runId:i}):(await te({config:e,debugDir:p,events:c,recordingOptional:!1,runId:i,stepSources:void 0}),x.length>0?{findings:x,kind:"findings",runId:i}:{kind:"pass",runId:i})},S=>Promise.resolve({error:S,kind:"error",runId:i}))}function Uo(e){let n=e.find(t=>t.kind==="driver-error"&&Be(t.error));return n!=null&&n.kind==="driver-error"?n.error:void 0}async function te(e){let n=await lt(e);await ii(e.config,e.runId,n),await No(e.config,e.debugDir,e.runId)}async function lt({config:e,debugDir:n,events:t,recordingOptional:r,runId:o,stepSources:i}){let s=dt(t),l=_o(n,o);if(l==null&&!r)throw new Error("recording-missing");return await Ko({aliases:[...Wo(t),...Bo(s)],config:e,generated:Vo(t),generatedSingletons:zo(t),origin:l==null?Do(s):l.origin,records:s,rrwebEvents:l==null?[]:l.events,runId:o,stepSources:i}),l!=null&&await oi(e,o,l),s}var Oo=E(`
|
|
120
|
+
mutation ClipUploadUrl($runId: ID!) {
|
|
121
|
+
clipUploadUrl(runId: $runId)
|
|
122
|
+
}
|
|
123
|
+
`);async function No(e,n,t){let r=ne.join(n,t,"clip.gif");if(Fe(r))try{let o=await f({config:e,document:Oo,variables:{runId:t}});if(o.clipUploadUrl==null)return;let i=await fetch(o.clipUploadUrl,{body:new Uint8Array(Me(r)),headers:{"Content-Type":"image/gif"},method:"PUT"});i.ok||y.warn({runId:t,status:i.status},"Clip upload failed")}catch(o){y.warn({err:o,runId:t},"Clip upload skipped")}}function Do(e){return e.reduce((n,t)=>Math.min(n,t.startMs),e[0]?.startMs??0)}function dt(e){return e.flatMap(n=>n.kind==="step"?[{annotations:n.annotations,endMs:n.endMs,findings:n.findings,index:n.index,source:n.source,startMs:n.startMs,state:n.state,url:n.url}]:[])}function _o(e,n){let t=ne.join(e,n,"behavior.jsonl");if(!Fe(t))return null;let r=Me(t,"utf8").split(`
|
|
124
|
+
`).filter(i=>i.length>0).map(i=>qo(i)).flatMap(i=>Ho(i)?[i.event]:[]),o=r[0];return o==null?null:{events:r,origin:o.timestamp}}function qo(e){return JSON.parse(e)}function Ho(e){return typeof e=="object"&&e!=null&&Reflect.get(e,"kind")==="rrweb"}function Wo(e){return e.flatMap(n=>n.kind==="world"?n.aliases:[])}function Bo(e){return e.flatMap(n=>{let t=Jo(n.source);return t.flatMap(r=>{let i=t.filter(l=>l.entity===r.entity).indexOf(r),s=n.state.rows.filter(l=>l.status==="created"&&l.entity===r.entity).at(i);return s==null?[]:[{alias:r.as,entity:r.entity,key:s.key}]})})}function Vo(e){return new Set(e.flatMap(n=>n.kind==="world"?n.generated.map(t=>ct(t)):[]))}function ct({entity:e,field:n,key:t}){return`${e}\0${t}\0${n}`}function zo(e){return new Set(e.flatMap(n=>n.kind==="world"?n.generatedSingletons:[]))}function Jo(e){return e==null?[]:e.expect.flatMap(n=>Ae(n))}function Ae(e){return e.kind==="state"&&e.assertion.kind==="created"?[{as:e.assertion.as,entity:e.entity}]:e.kind==="and"?e.predicates.flatMap(n=>Ae(n)):e.kind==="when"?e.branches.flatMap(n=>n.consequence.flatMap(t=>Ae(t))):[]}async function Ko({aliases:e,config:n,generated:t,generatedSingletons:r,origin:o,records:i,rrwebEvents:s,runId:l,stepSources:u}){let d=i.map((p,c)=>Yo({aliases:e,generated:t,generatedSingletons:r,origin:o,record:p,rrwebEvents:s,sourceTest:u?.[c]??null}));await f({config:n,document:li,variables:{items:[{runId:l,steps:d}]}})}var Qo=3,Go=0;function Xo({endMs:e,rrwebEvents:n,startMs:t}){let r=n.find(o=>o.type===Qo&&o.data?.source===Go&&o.timestamp>=t&&o.timestamp<=e);return r==null?t:r.timestamp}function Yo({aliases:e,generated:n,generatedSingletons:t,origin:r,record:o,rrwebEvents:i,sourceTest:s}){let l=We(o.source,o.index),u=Xo({endMs:o.endMs,rrwebEvents:i,startMs:o.startMs}),d=o.annotations.map(c=>({kind:c.kind,label:c.label,outcome:c.outcome,recordingStartMs:Math.max(0,(c.kind==="action"?u:c.atMs)-r),rrwebIds:[...c.rrwebIds],url:c.url})),p=o.annotations.find(c=>c.kind==="action")?.rrwebIds??[];return{annotations:d,detail:null,duration:Math.max(0,o.endMs-o.startMs),findings:o.findings.map(c=>at(c)),nodeType:l.kind,recordingEndMs:Math.max(0,o.endMs-r),recordingStartMs:Math.max(0,u-r),rrwebIds:[...p],snapshotTimestamp:Math.max(0,o.endMs-r),sourceTest:s,stateRows:o.state.rows.map(c=>Zo({aliases:e,generated:n,row:c})),stateSingletons:o.state.singletons.map(c=>({changed:c.changed,generated:t.has(c.name),name:c.name,value:c.value==null?null:String(c.value)})),status:o.findings.length>0?"failed":"passed",stepIndex:o.index,title:it(l),url:o.url}}function Zo({aliases:e,generated:n,row:t}){let r=e.find(o=>o.entity===t.entity&&o.key===t.key);return{entity:t.entity,fields:t.fields.map(o=>({changed:o.changed,field:o.field,generated:n.has(ct({entity:t.entity,field:o.field,key:t.key})),value:o.value==null?null:String(o.value)})),key:t.key,label:r?.alias??t.key,status:t.status}}var ei=$o(Mo);async function ut(e,n){await f({config:e,document:ui,variables:{runIds:[n]}})}var ni="application/x-ndjson";async function ti({config:e,debugDir:n,runId:t}){let r=ne.join(n,t,"behavior.jsonl");if(Fe(r))try{let o=await f({config:e,document:ri,variables:{runId:t}}),i=await fetch(o.debugArtifactUploadUrl,{body:Me(r),headers:{"content-type":ni},method:"PUT"});if(!i.ok){y.warn({runId:t,status:i.status},"behavior upload PUT failed");return}await ut(e,t)}catch(o){y.warn({error:o,runId:t},"behavior upload failed")}}var ri=E(`
|
|
125
|
+
mutation DebugArtifactUploadUrl($runId: String!) {
|
|
126
|
+
debugArtifactUploadUrl(runId: $runId)
|
|
127
|
+
}
|
|
128
|
+
`);async function oi(e,n,t){let r=t.events.map(s=>JSON.stringify(s)).join(`
|
|
129
|
+
`),o=await ei(Buffer.from(r,"utf8")),i=t.events.at(-1);await f({config:e,document:di,variables:{input:{bodyBase64:o.toString("base64"),chunkIndex:0,endTimestamp:Math.max(0,(i?.timestamp??t.origin)-t.origin),eventCount:t.events.length,runId:n,startTimestamp:0}}})}async function ii(e,n,t){let r=t.filter(s=>s.findings.length>0).length,o=t.length-r,i=t.reduce((s,l)=>s+Math.max(0,l.endMs-l.startMs),0);await f({config:e,document:ci,variables:{items:[{duration:i,failCount:r,passCount:o,runId:n,status:r>0?"failed":"passed",summary:null,warnCount:0}]}})}async function ai(e,n){return((await f({config:e,document:si,variables:{runIds:[n]}})).startRunsBatch??[]).some(r=>r.id===n)}var si=E(`
|
|
130
|
+
mutation StartRunsBatch($runIds: [String!]!) {
|
|
131
|
+
startRunsBatch(runIds: $runIds) {
|
|
132
|
+
id
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
`),li=E(`
|
|
136
|
+
mutation SubmitRunStepsBatch($items: [SubmitRunStepsItem!]!) {
|
|
137
|
+
submitRunStepsBatch(items: $items)
|
|
138
|
+
}
|
|
139
|
+
`),di=E(`
|
|
140
|
+
mutation SubmitRunRecordingChunk($input: SubmitRunRecordingChunkInput!) {
|
|
141
|
+
submitRunRecordingChunk(input: $input)
|
|
142
|
+
}
|
|
143
|
+
`),ci=E(`
|
|
144
|
+
mutation CompleteRunsBatch($items: [CompleteRunItem!]!) {
|
|
145
|
+
completeRunsBatch(items: $items) {
|
|
146
|
+
id
|
|
147
|
+
status
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
`),ui=E(`
|
|
151
|
+
mutation MarkRunArtifactsUploadedBatch($runIds: [String!]!) {
|
|
152
|
+
markRunArtifactsUploadedBatch(runIds: $runIds)
|
|
153
|
+
}
|
|
154
|
+
`);function pi(e){let n=e.trail;if(!(n==null||!fi(e.kind)))return{baseLabel:n.baseLabel,baseState:n.baseState,durationMs:n.durationMs,outcome:e.kind,runId:e.runId,signature:n.signature,steps:n.steps}}function fi(e){return e==="clean"||e==="flaky"||e==="finding"}async function $e({baseState:e,branchName:n,category:t,commitSha:r,config:o,debugDir:i,devSessionId:s,events:l,lockfileHash:u,reproJson:d,runId:p,signature:c,spec:m,stepSources:S}){await f({config:o,document:Si,variables:{branchName:n??null,commitSha:r??null,devSessionId:s??null,lockfileHash:u??null,projectId:o.projectId,reproJson:d,runId:p,spec:m??null}}),await te({config:o,debugDir:i,events:l,recordingOptional:!0,runId:p,stepSources:S}),await f({config:o,document:xi,variables:{baseState:e,category:t,projectId:o.projectId,reproRunId:p,signature:c}})}async function re(e,n,t){return(await f({config:e,document:wi,variables:{lockfileHash:t,projectId:e.projectId,signature:n}})).exploreFindingExists}async function yi({attempts:e,config:n,devSessionId:t,findings:r,trail:o}){await f({config:n,document:Ri,variables:{attempts:e,devSessionId:t,findings:r,trail:o==null?null:{baseLabel:o.baseLabel,baseState:o.baseState,durationMs:o.durationMs,findingRunId:o.runId??null,findingSignature:o.signature??null,outcome:o.outcome,steps:o.steps.map(i=>({test:i.test,text:i.text}))}}})}async function mi(e,n,t){let r=await f({config:e,document:gi,variables:{devSessionId:n}}).catch(i=>(y.warn({error:i},"fetchScopedTestRefs failed"),null)),o=new Set(r?.exploreScope??[]);return o.size===0?new Set:new Set(t.workflows.filter(i=>o.has(g(i.name))).flatMap(i=>i.tests.map(s=>h(s))))}var gi=v(`
|
|
155
|
+
query ExploreScope($devSessionId: String!) {
|
|
156
|
+
exploreScope(devSessionId: $devSessionId)
|
|
157
|
+
}
|
|
158
|
+
`);async function hi(e,n){return(await f({config:e,document:ki,variables:{devSessionId:n}}).catch(r=>(y.warn({error:r},"reportExploreUnhealthy failed"),null)))?.reportExploreUnhealthy??!1}var Ri=v(`
|
|
159
|
+
mutation RecordExplorationProgress(
|
|
160
|
+
$devSessionId: String!
|
|
161
|
+
$attempts: Int!
|
|
162
|
+
$findings: Int!
|
|
163
|
+
$trail: ExploreTrailInput
|
|
164
|
+
) {
|
|
165
|
+
recordExplorationProgress(
|
|
166
|
+
devSessionId: $devSessionId
|
|
167
|
+
attempts: $attempts
|
|
168
|
+
findings: $findings
|
|
169
|
+
trail: $trail
|
|
170
|
+
)
|
|
171
|
+
}
|
|
172
|
+
`),ki=v(`
|
|
173
|
+
mutation ReportExploreUnhealthy($devSessionId: String!) {
|
|
174
|
+
reportExploreUnhealthy(devSessionId: $devSessionId)
|
|
175
|
+
}
|
|
176
|
+
`),Si=v(`
|
|
177
|
+
mutation CreateExploreRun(
|
|
178
|
+
$projectId: String!
|
|
179
|
+
$runId: String!
|
|
180
|
+
$devSessionId: String
|
|
181
|
+
$branchName: String
|
|
182
|
+
$commitSha: String
|
|
183
|
+
$lockfileHash: String
|
|
184
|
+
$spec: String
|
|
185
|
+
$reproJson: String
|
|
186
|
+
) {
|
|
187
|
+
createExploreRun(
|
|
188
|
+
projectId: $projectId
|
|
189
|
+
runId: $runId
|
|
190
|
+
devSessionId: $devSessionId
|
|
191
|
+
branchName: $branchName
|
|
192
|
+
commitSha: $commitSha
|
|
193
|
+
lockfileHash: $lockfileHash
|
|
194
|
+
spec: $spec
|
|
195
|
+
reproJson: $reproJson
|
|
196
|
+
) {
|
|
197
|
+
id
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
`),xi=v(`
|
|
201
|
+
mutation SubmitExploreFinding(
|
|
202
|
+
$projectId: String!
|
|
203
|
+
$signature: String!
|
|
204
|
+
$baseState: String!
|
|
205
|
+
$category: ExploreFindingCategory!
|
|
206
|
+
$reproRunId: String!
|
|
207
|
+
) {
|
|
208
|
+
submitExploreFinding(
|
|
209
|
+
projectId: $projectId
|
|
210
|
+
signature: $signature
|
|
211
|
+
baseState: $baseState
|
|
212
|
+
category: $category
|
|
213
|
+
reproRunId: $reproRunId
|
|
214
|
+
) {
|
|
215
|
+
id
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
`),wd=v(`
|
|
219
|
+
mutation SetExploreFindingStatus(
|
|
220
|
+
$projectId: String!
|
|
221
|
+
$signature: String!
|
|
222
|
+
$status: ExploreFindingStatus!
|
|
223
|
+
) {
|
|
224
|
+
setExploreFindingStatus(projectId: $projectId, signature: $signature, status: $status)
|
|
225
|
+
}
|
|
226
|
+
`),wi=v(`
|
|
227
|
+
query ExploreFindingExists($projectId: String!, $signature: String!, $lockfileHash: String!) {
|
|
228
|
+
exploreFindingExists(projectId: $projectId, signature: $signature, lockfileHash: $lockfileHash)
|
|
229
|
+
}
|
|
230
|
+
`);import{graphql as pt}from"gql.tada";async function bi(e,n,t){await f({config:e,document:Ei,variables:{reason:t,runId:n}}).catch(r=>{y.error(r,"failRun submission failed")})}var Ei=pt(`
|
|
231
|
+
mutation FailRun($runId: String!, $reason: String!) {
|
|
232
|
+
failRun(runId: $runId, reason: $reason)
|
|
233
|
+
}
|
|
234
|
+
`),Id=pt(`
|
|
235
|
+
mutation MarkRunUnready($runId: String!, $cause: RunUnreadyCause!) {
|
|
236
|
+
markRunUnready(runId: $runId, cause: $cause)
|
|
237
|
+
}
|
|
238
|
+
`);import{randomUUID as vi}from"crypto";async function Ii({assign:e,config:n,debugDir:t,devSessionId:r,fixturesDir:o,headed:i,lockfile:s,report:l,session:u,signal:d}){let p=Ve(s);if(e.stepRuns.length===0)return{kind:"error",reason:"empty-trail"};let c=Li(p,e.stepRuns),m=await Qe({baseState:{name:h(e.baseStateTest),test:e.baseStateTest},corpus:p,lockfile:s,options:{baseUrl:n.appUrl,engineUrl:n.engineUrl,fixturesDir:o,generate:I,headed:i,secret:n.webhookSecret,tunnelAuth:n.tunnelAuth},seenSignature:l?x=>re(n,x,e.lockfileHash):void 0,session:u,stepRuns:e.stepRuns,runIdFor:x=>`explore-${vi()}-${String(x)}`},d),S=l?await Fi({baseStateTest:e.baseStateTest,config:n,debugDir:t,devSessionId:r,lockfileHash:e.lockfileHash,outcome:m,reproJson:ji(p,e),stepSources:Ai(c)}):!1;return Ti(m,c.length),Ui(m,S,Pi(c,e,m))}function Pi(e,n,t){if(t.kind==="error"||t.kind==="aborted")return;let r=t.timing.confirm;return{baseLabel:n.baseStateTest.intent,baseState:h(n.baseStateTest),durationMs:Math.round(oe(t.timing.detect)+(r==null?0:oe(r))),signature:t.kind==="finding"?t.signature:void 0,steps:Ci(e)}}function Ci(e){return e.flatMap(n=>{let t=n.label.split("#")[0]??n.label;return n.actions.map(r=>({test:t,text:r}))})}function oe(e){return e.engineMs+e.worldMs+e.browserMs+e.driveMs+e.teardownMs}function Ti(e,n){if(e.kind==="error"){y.info({kind:e.kind,reason:e.error.kind,steps:n},"explore trail");return}if(e.kind==="aborted"){y.info({kind:e.kind,steps:n},"explore trail");return}let t=e.timing.detect,r=e.timing.confirm;y.info({browserMs:t.browserMs,confirmMs:r==null?void 0:oe(r),detectMs:oe(t),driveMs:t.driveMs,engineMs:t.engineMs,kind:e.kind,steps:n,teardownMs:t.teardownMs,worldMs:t.worldMs},"explore trail")}function ji(e,n){let t=n.stepRuns.flatMap(o=>{let i=e[o.idx];return i==null?[]:[{index:i.index,params:o.params,test:i.test}]}),r={baseStateRef:h(n.baseStateTest),steps:t};return JSON.stringify(r)}function Ai(e){return e.flatMap(n=>{let t=n.label.split("#")[0]??n.label;return n.actions.map(()=>t)})}async function Fi({baseStateTest:e,config:n,debugDir:t,devSessionId:r,lockfileHash:o,outcome:i,reproJson:s,stepSources:l}){return i.kind!=="finding"||i.captureEvents.length===0?!1:await re(n,i.signature,o)?(y.info({devSessionId:r,signature:i.signature},"explore finding already reported, skipping duplicate"),!1):(await $e({baseState:i.baseState,branchName:void 0,category:Mi(i.verifierLayer),commitSha:void 0,config:n,debugDir:t,devSessionId:r,events:i.captureEvents,lockfileHash:o,reproJson:s,runId:i.runId,signature:i.signature,spec:$i(e,i.captureEvents),stepSources:l}).catch(u=>{y.warn({error:u},"explore finding report failed")}),!0)}function Mi(e){return e==="data-rule"?"dataRule":e==="page-rule"?"pageRule":e}function $i(e,n){let t=n.flatMap(o=>o.kind==="step"?[o.source]:[]),r={absent:e.absent,exclusive:e.exclusive,intent:e.intent,maybe:[],name:e.name,params:e.params,singletons:e.singletons,steps:t,stub:!1,tests:[],world:e.world};return JSON.stringify(r)}function Li(e,n){return n.flatMap(t=>{let r=e[t.idx];return r==null?[]:[{actions:[...r.nav,...r.steps].map(o=>ze(o.action)),label:`${r.test}#${String(r.index)}`}]})}function Ui(e,n,t){return e.kind==="error"?{kind:e.kind,reason:`runtime:${e.error.kind}`}:e.kind==="finding"?{kind:e.kind,runId:n?e.runId:void 0,trail:t}:{kind:e.kind,trail:t}}import Oi from"path";import{randomUUID as Ni}from"crypto";async function Jd({cwd:e,onReady:n,signal:t,step:r,target:o}){let i=gn(e).match(c=>({config:c}),c=>({failure:c}));if("failure"in i)return{failure:i.failure,kind:"config-failed"};let s=i.config,l=await ge(e);if(l.result.isErr())return{error:l.result.error,kind:"compile-failed"};let u=l.result.value,d=await Di(u,o);return d.kind!=="ok"?d:(await Je({lockfile:u,onReady:n,options:_i(s),runId:`teleport-${Ni()}`,sequence:d.sequence,stopAfterStep:r,test:d.test},t)).match(c=>({kind:"done",result:c}),c=>({error:c,kind:"run-failed"}))}async function Di(e,n){if(n.kind==="explore"){let r=await Ge(e,n.repro);return r.kind==="unplannable"?{kind:"unplannable"}:{kind:"ok",sequence:r.sequence,test:r.baseTest}}let t=F(e).find(r=>r.ref===n.ref);return t==null?{kind:"no-test",ref:n.ref}:{kind:"ok",sequence:Ke(e,t.test,void 0),test:t.test}}function _i(e){return{baseUrl:e.appUrl,engineUrl:e.engineUrl,fixturesDir:Oi.join(e.cwd,$),generate:I,headed:!0,secret:e.webhookSecret,tunnelAuth:e.tunnelAuth}}export{Vi as a,Zi as b,B as c,xt as d,V as e,$ as f,T as g,sn as h,ge as i,O as j,j as k,xa as l,K as m,Ia as n,Pa as o,Ca as p,$a as q,he as r,un as s,fn as t,gn as u,Sn as v,Se as w,Xa as x,ee as y,Zn as z,vl as A,Il as B,Pl as C,bo as D,Ol as E,Is as F,Ps as G,Cn as H,Cs as I,Ts as J,js as K,As as L,Fs as M,jn as N,An as O,Fn as P,Mn as Q,$n as R,Wl as S,Vl as T,zl as U,Jl as V,Kl as W,Ql as X,Gl as Y,Xl as Z,Yl as _,Zl as $,ed as aa,es as ba,ns as ca,xe as da,ts as ea,wn as fa,hs as ga,Ee as ha,Xr as ia,hl as ja,Lo as ka,ti as la,bi as ma,pi as na,yi as oa,mi as pa,hi as qa,Ii as ra,Jd as sa};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import{aa as a,ba as b,ca as c,da as d,ea as e,fa as f,ga as g,ha as h,ia as i,ja as j,ka as k}from"./chunk-GLXPGXO6.js";import"./chunk-IHSHBPJY.js";import"./chunk-7UWDMECF.js";export{b as renderDaemonBindError,g as renderDaemonLockCompromised,f as renderDaemonLockHeld,e as renderDaemonReady,h as renderDaemonStatus,j as renderDaemonVersionNote,i as renderExplorationProgress,d as renderNotSignedIn,c as renderProjectAccessDenied,a as renderTunnelProvisionFailed,k as wireOutcome};
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import{$ as Ie,B as ie,D as me,F as ye,U as be,V as xe,W as Pe,X as Re,Y as Ee,Z as Te,_ as Ce,b as K,ba as P,ca as R,da as We,e as Y,ea as M,fa as Ae,h as x,ha as U,i as re,ia as Le,j as H,ja as De,m as _,ma as E,na as He,oa as _e,pa as Me,qa as Ue,r as oe,sa as qe,u as w,w as ne,x as te}from"./chunk-KAILSYCU.js";import{G as se,I as ce,J as de,K as ue,L as pe,T as fe,ba as ge,ca as Se,da as ke,e as X,ea as ve,fa as we,ga as he,h as Z,i as D,l as ee,n as ae,q as le}from"./chunk-GLXPGXO6.js";import{b as Oe}from"./chunk-RLXQYG7H.js";import{c as G,d as g,e as s,f as L,g as V}from"./chunk-5VRJXHWH.js";import"./chunk-IHSHBPJY.js";import"./chunk-7UWDMECF.js";import Bo from"path";import{createClient as jo}from"graphql-sse";import zo,{AbortError as Jo}from"p-retry";import{graphql as z}from"gql.tada";import{graphql as Ar}from"gql.tada";import{print as Lr}from"graphql";async function Fe({config:e,cwd:r,headed:o,pool:n,runId:t,signal:i,testSlug:a,workClass:l,workflowSlug:c}){let u=await x(r);if(u.isErr())return await E(e,t,`lockfile:${u.error.kind}`),{kind:"dispatch-error",reason:{detail:`lockfile:${u.error.kind}`,type:"generic"}};let p=Wr(u.value,{testSlug:a,workflowSlug:c});if(p==null)return await E(e,t,`no-test:${c}/${a}`),{kind:"dispatch-error",reason:{detail:`no-test:${c}/${a}`,type:"generic"}};let d=await P({headed:o,workClass:l,task:()=>n.execute({headed:o,runId:t,testRef:p},i)});return!d.serverNotified&&d.outcome.kind==="error"&&await E(e,t,d.outcome.detail),d.outcome}function Wr(e,{testSlug:r,workflowSlug:o}){let t=e.workflows.find(i=>ee(i.name)===o)?.tests.find(i=>i.slug===r);return t==null?void 0:le(t)}var Dr=6e4,Hr=Ar(`
|
|
3
|
+
subscription RunRequestedWatch($devSessionId: String!) {
|
|
4
|
+
runRequested(devSessionId: $devSessionId) {
|
|
5
|
+
runId
|
|
6
|
+
testSlug
|
|
7
|
+
workflowId
|
|
8
|
+
workflowSlug
|
|
9
|
+
}
|
|
10
|
+
}
|
|
11
|
+
`);async function Ne(e){let r=Math.min(1e3*2**e,Dr)+Ur();await new Promise(o=>setTimeout(o,r))}function $e({claim:e,cwd:r,devSessionId:o,onSubscriptionDead:n,pool:t,sseClient:i,sseHealth:a}){let l=new Set;return i.subscribe({query:Lr(Hr),variables:{devSessionId:o}},{complete:()=>{},error:c=>{let u=c instanceof Error?c.message:String(c);s.warn("runRequested SSE failed: %s; re-registering session",u),n(u)},next:c=>{_r({claim:e,cwd:r,event:c.data?.runRequested,inFlightRunIds:l,pool:t})}},{connected:()=>{a.onConnected()},connecting:c=>{a.onConnecting(c),c&&s.debug("runRequested SSE reconnecting")}})}function _r({claim:e,cwd:r,event:o,inFlightRunIds:n,pool:t}){if(o==null)return;if(n.has(o.runId)){s.warn({runId:o.runId,workflowSlug:o.workflowSlug},"duplicate runRequested event; skipping dispatch");return}n.add(o.runId),process.stdout.write(`ripplo: run ${o.workflowSlug}
|
|
12
|
+
`),K(r);let i=w(r).match(l=>l,l=>{s.error({failure:l,runId:o.runId},"failed to load env for run dispatch; skipping")});if(i==null){n.delete(o.runId);return}let a=Mr(e(o.runId),o);a.started(),Fe({config:i,cwd:r,headed:a.headed,pool:t,runId:o.runId,signal:a.signal,testSlug:o.testSlug,workClass:a.workClass,workflowSlug:o.workflowSlug}).then(l=>{a.finished(l)}).catch(l=>{s.error({err:l,runId:o.runId,workflowSlug:o.workflowSlug},"run execution failed; daemon continuing"),a.finished({detail:l instanceof Error?l.message:String(l),kind:"error"})}).finally(()=>{n.delete(o.runId)})}function Mr(e,r){return e==null?(s.debug({runId:r.runId,workflowSlug:r.workflowSlug},"dispatching unclaimed run (externally triggered or replayed)"),{headed:!1,signal:new AbortController().signal,workClass:"p0-ui",finished:()=>{},started:()=>{}}):{headed:e.headed,signal:Le(e.token),workClass:"p1-cli",finished:o=>{e.finished(r.runId,o)},started:()=>{e.started(r.runId)}}}function Ur(){return Math.floor(Math.random()*2700)+300}import{graphql as q}from"gql.tada";import{print as qr}from"graphql";var Or=q(`
|
|
13
|
+
subscription TeleportRequestedWatch($devSessionId: String!) {
|
|
14
|
+
teleportRequested(devSessionId: $devSessionId) {
|
|
15
|
+
runId
|
|
16
|
+
stepIndex
|
|
17
|
+
kind
|
|
18
|
+
testSlug
|
|
19
|
+
workflowSlug
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
`),Fr=q(`
|
|
23
|
+
query TeleportRunRepro($id: String!) {
|
|
24
|
+
run(id: $id) {
|
|
25
|
+
id
|
|
26
|
+
reproJson
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
`),Nr=q(`
|
|
30
|
+
mutation ReportTeleportResult($devSessionId: String!, $runId: String!, $status: String!) {
|
|
31
|
+
reportTeleportResult(devSessionId: $devSessionId, runId: $runId, status: $status)
|
|
32
|
+
}
|
|
33
|
+
`);function Be({cwd:e,devSessionId:r,onSubscriptionDead:o,sseClient:n}){let t=new Set,i=n.subscribe({query:qr(Or),variables:{devSessionId:r}},{complete:()=>{},error:a=>{let l=a instanceof Error?a.message:String(a);s.warn("teleportRequested SSE failed: %s; re-registering session",l),o(l)},next:a=>{$r({cwd:e,devSessionId:r,event:a.data?.teleportRequested,running:t})}});return()=>{t.forEach(a=>{a.abort()}),t.clear(),i()}}function $r({cwd:e,devSessionId:r,event:o,running:n}){if(o==null)return;let t=new AbortController;n.add(t),Br({cwd:e,devSessionId:r,event:o,signal:t.signal}).catch(i=>{s.error({err:i},"teleport failed; daemon continuing")}).finally(()=>{n.delete(t)})}async function Br({cwd:e,devSessionId:r,event:o,signal:n}){let t=c=>jr({cwd:e,devSessionId:r,runId:o.runId,status:c}),i=await zr(e,o);if(i==null){s.warn({runId:o.runId},"teleport could not resolve target"),await t("unplannable");return}process.stdout.write(`ripplo: teleport ${Qr(o)} step ${String(o.stepIndex+1)}
|
|
34
|
+
`);let l=await qe({cwd:e,onReady:()=>{t("opened")},signal:n,step:o.stepIndex+1,target:i});l.kind==="done"&&l.result.kind==="handed-over"||(s.warn({kind:l.kind,runId:o.runId},"teleport could not open"),await t(l.kind==="unplannable"?"unplannable":"error"))}async function jr({cwd:e,devSessionId:r,runId:o,status:n}){let t=w(e).match(i=>i,()=>null);t!=null&&await g({config:t,document:Nr,variables:{devSessionId:r,runId:o,status:n}}).catch(()=>null)}async function zr(e,r){if(r.kind==="explore"){let o=await Jr(e,r.runId);return o==null?null:{kind:"explore",repro:o}}return r.testSlug==null||r.workflowSlug==null?null:{kind:"test",ref:`${r.workflowSlug}/${r.testSlug}`}}async function Jr(e,r){let o=w(e).match(t=>t,()=>null);if(o==null)return null;let n=await g({config:o,document:Fr,variables:{id:r}}).catch(()=>null);return n?.run?.reproJson==null?null:ce.parse(JSON.parse(n.run.reproJson))}function Qr(e){return e.kind==="explore"?"explore finding":`${String(e.workflowSlug)}/${String(e.testSlug)}`}function je(){let e=!0,r,o=null,n=()=>{o!=null&&(clearTimeout(o),o=null)};return{markUnhealthy:t=>{e=!1,r=t,n()},onConnected:()=>{n(),o=setTimeout(()=>{e=!0,r=void 0,o=null},1e4)},onConnecting:()=>{n()},snapshot:()=>({detail:r,ok:e})}}import Gr from"fs";import Ge from"net";import{err as Ve,ok as Vr}from"neverthrow";async function Ke({cwd:e,onConnection:r}){V(e);let o=ye(e),n=await ze({onConnection:r,socketPath:o});return n.isOk()||n.error.kind!=="stale-candidate"?n.map(Je(o)).mapErr(Qe(o)):await Kr(o)?Ve({kind:"already-running",socketPath:o}):(Ye(o),(await ze({onConnection:r,socketPath:o})).map(Je(o)).mapErr(Qe(o)))}function Kr(e){return new Promise(r=>{let o=Ge.connect(e);o.once("connect",()=>{o.destroy(),r(!0)}),o.once("error",()=>{r(!1)})})}async function ze(e){let r=await Yr(e);return r.kind==="listening"?Vr(r.server):Ve(r.error)}function Yr({onConnection:e,socketPath:r}){return new Promise(o=>{let n=Ge.createServer(e);n.once("error",t=>{o({error:t.code==="EADDRINUSE"?{kind:"stale-candidate"}:{kind:"listen-failed",message:t.message},kind:"failed"})}),n.listen(r,()=>{o({kind:"listening",server:n})})})}function Je(e){return r=>({socketPath:e,close:()=>{r.close(),Ye(e)}})}function Ye(e){Gr.rmSync(e,{force:!0})}function Qe(e){return r=>r.kind==="stale-candidate"?{kind:"already-running",socketPath:e}:{kind:"bind-failed",message:r.message}}import{randomInt as Xr,randomUUID as Zr}from"crypto";function Ze(e){let r={attempts:0,consecutiveErrors:0,driverBackoffUntil:0,findings:0,lastUnhealthyReportMs:0,lockfile:null,prepared:null,preparing:!1,refreshing:!1,scopedAt:0,scopedTests:new Set,scoping:!1,windowAttempts:0,windowFindings:0,windowStartMs:Date.now()},o=O(e,r);return{priority:"p3",next:()=>so(e,r),onResult:()=>{},ready:()=>o,status:()=>({attempts:r.attempts,findings:r.findings}),stop:()=>Promise.resolve()}}var eo=10;async function O(e,r){if(!r.preparing){r.preparing=!0;try{let o=await e.loadLockfile(),n=o==null?null:await ro(o);if(n==null||o==null)return;r.lockfile=o.lockfile,r.scopedAt=0,r.prepared=n,F(r),e.notifyWork()}finally{r.preparing=!1}}}async function ro({lockfile:e}){let r=await ue(e);return r==null?null:{exploration:r,lockfileHashValue:D(e),strategy:se("even")}}var oo=6,no=3e4,to=2e4;function F(e){e.consecutiveErrors=0,e.driverBackoffUntil=0,e.lastUnhealthyReportMs=0}async function io(e,r){if(!(r.refreshing||r.preparing||r.prepared==null)){r.refreshing=!0;try{let o=await e.loadLockfile();if(o==null||D(o.lockfile)===r.prepared.lockfileHashValue)return;s.info("workflow definitions changed, re-preparing exploration"),r.prepared=null,await O(e,r)}finally{r.refreshing=!1}}}var ao=15e3;async function lo(e,r){if(!(r.scoping||r.lockfile==null||Date.now()-r.scopedAt<ao)){r.scoping=!0;try{r.scopedTests=await e.scopedTestRefs(r.lockfile),r.scopedAt=Date.now()}finally{r.scoping=!1}}}function so(e,r){io(e,r),lo(e,r);let o=r.prepared;if(o==null||Date.now()<r.driverBackoffUntil)return null;let n=pe({lockfileHash:o.lockfileHashValue,prepared:o.exploration,random:co,scopedTests:r.scopedTests,strategy:{...o.strategy,maxAttemptLength:e.maxTrailLength()}});if(n==null)return null;let t=n.baseStateTest.name;return{id:`explore:${Zr()}`,label:t,run:i=>uo({assign:n,params:e,signal:i,state:r})}}var Xe=2**31;function co(){return Xr(Xe)/Xe}async function uo({assign:e,params:r,signal:o,state:n}){if(!await r.probeApp()){er({params:r,reason:"app-unreachable",state:n});return}let t=await r.executeTrail(e,o);if(t.kind==="aborted")return;if(t.kind==="error"){fo({params:r,reason:t.reason,state:n});return}F(n),n.attempts+=1,n.windowAttempts+=1;let i=t.kind==="finding";i&&(n.findings+=1,n.windowFindings+=1,s.info("exploration finding recorded")),r.reportProgress({attempts:1,findings:i?1:0,result:t}),n.windowAttempts>=eo&&po(n)}function po(e){let r=Date.now()-e.windowStartMs;s.info({attempts:e.windowAttempts,avgTrailMs:Math.round(r/e.windowAttempts),findings:e.windowFindings,windowMs:r,yield:Number((e.windowFindings/e.windowAttempts).toFixed(3))},"explore window"),e.windowAttempts=0,e.windowFindings=0,e.windowStartMs=Date.now()}function fo({params:e,reason:r,state:o}){if(r?.startsWith("lockfile:daemon-load-failed")===!0){mo(e,o);return}er({params:e,reason:r,state:o})}function mo(e,r){r.preparing||(r.prepared=null,O(e,r))}function er({params:e,reason:r,state:o}){let n=go(r);if(n==="trail"){F(o);return}o.consecutiveErrors+=1,s.debug("exploration infra error: %s",r),!(o.consecutiveErrors<oo)&&(n==="driver"&&(o.driverBackoffUntil=Date.now()+no),yo({params:e,reason:r,state:o}))}function yo({params:e,reason:r,state:o}){let n=Date.now();n-o.lastUnhealthyReportMs<to||(o.lastUnhealthyReportMs=n,s.warn("exploration unhealthy after %d consecutive infra errors (last: %s)",o.consecutiveErrors,r),e.reportUnhealthy())}function go(e){if(e==null||e==="error"||e==="app-unreachable"||e.startsWith("transport:"))return"infra";if(e.startsWith("runtime:")){let r=e.slice(8);return r==="driver-launch"?"driver":ae(r)?"infra":"trail"}return"trail"}function So(e){let{backoffActive:r,exploreEnabled:o,headedActive:n,interactiveActive:t,interactiveQueued:i}=e,{explorationActive:a,exploreConcurrency:l,poolSize:c}=e;if(!o||n||i>0)return{abortCount:a,refillCount:0};if(r)return{abortCount:0,refillCount:0};let u=Math.min(l,c-1,c-t);return{abortCount:0,refillCount:Math.max(0,u-a)}}function nr(e){let r={active:new Map,backoffUntil:0,cancelBackoffTimer:null,cancelHeartbeat:null,prevInteractiveActive:e.probe().interactiveActive,stopped:!1};return tr(r,e),{explorationActive:()=>r.active.size,notifyQueueChange:()=>{ko(r,e)},stop:()=>{r.stopped=!0,r.cancelBackoffTimer?.(),r.cancelBackoffTimer=null,r.cancelHeartbeat?.(),r.cancelHeartbeat=null,ir(r,r.active.size)}}}function tr(e,r){e.stopped||(e.cancelHeartbeat=r.setTimer(()=>{T(e,r),tr(e,r)},15e3))}function T(e,r){if(e.stopped)return;let o=r.probe(),n=So({backoffActive:r.now()<e.backoffUntil,explorationActive:e.active.size,exploreConcurrency:r.exploreConcurrency(),exploreEnabled:r.exploreEnabled(),headedActive:o.headedActive>0,interactiveActive:o.interactiveActive,interactiveQueued:o.interactiveQueued,poolSize:o.poolSize});ir(e,n.abortCount),ar({count:n.refillCount,params:r,state:e})}function ir(e,r){[...e.active.values()].slice(0,r).forEach(({controller:o})=>{o.abort()})}function ko(e,r){let o=r.probe();o.interactiveActive<e.prevInteractiveActive&&vo(e,r),e.prevInteractiveActive=o.interactiveActive,T(e,r)}function vo(e,r){e.backoffUntil=r.now()+3e4,e.cancelBackoffTimer?.(),e.cancelBackoffTimer=r.setTimer(()=>{e.cancelBackoffTimer=null,T(e,r)},3e4)}function ar({count:e,params:r,state:o}){if(e<=0)return;let n=wo(r.sources);n!=null&&(ho({params:r,pulled:n,state:o}),ar({count:e-1,params:r,state:o}))}function wo(e){return e.reduce((r,o)=>{if(r!=null)return r;let n=o.next();return n==null?null:{job:n,source:o}},null)}function ho({params:e,pulled:r,state:o}){let{job:n,source:t}=r,i=new AbortController;o.active.set(n.id,{controller:i,job:n,source:t}),e.execute({job:n,priority:t.priority,signal:i.signal}).then(()=>{or({job:n,outcome:rr(i.signal,null),params:e,source:t,state:o})}).catch(a=>{or({job:n,outcome:rr(i.signal,{error:a}),params:e,source:t,state:o})})}function rr(e,r){return e.aborted?{kind:"aborted"}:r==null?{kind:"completed"}:{error:r.error,kind:"error"}}function or({job:e,outcome:r,params:o,source:n,state:t}){t.active.delete(e.id),n.onResult(e,r),T(t,o)}function N(e){return{priority:e,next:()=>null,onResult:()=>{}}}var xo=12;function lr({config:e,executor:r,pool:o}){return Po({appUrl:e.appUrl,cwd:e.cwd,localExecutor:r==="local",executeTrail:async(n,t)=>(await o).exploreTrail(n,t)})}function Po({appUrl:e,cwd:r,executeTrail:o,localExecutor:n}){let t={concurrency:2,enabled:!1,maxTrailLength:xo},i={notify:()=>{}},a={report:d=>{}},l={report:()=>{}},c={fetch:d=>Promise.resolve(new Set)},u=Ro({appUrl:e,cwd:r,executeTrail:o,maxTrailLength:()=>t.maxTrailLength,notifyWork:()=>{i.notify()},reportProgress:d=>{a.report(d)},reportUnhealthy:()=>{l.report()},scopedTestRefs:d=>c.fetch(d)}),p=nr({now:Date.now,probe:Eo,setTimer:To,sources:[N("p0"),N("p1"),u],execute:({job:d,priority:S,signal:v})=>P({headed:!1,workClass:Co(S),task:()=>d.run(v)}),exploreConcurrency:()=>t.concurrency,exploreEnabled:()=>t.enabled});return M(()=>{p.notifyQueueChange()}),i.notify=()=>{p.notifyQueueChange()},{progress:()=>u.status(),setConcurrency:d=>{n&&d!==t.concurrency&&s.info({workers:d},"explore local worker count changed"),t.concurrency=d,p.notifyQueueChange()},setEnabled:d=>{t.enabled=d&&n,p.notifyQueueChange()},setMaxTrailLength:d=>{t.maxTrailLength=d},setReportProgress:d=>{a.report=d},setReportUnhealthy:d=>{l.report=d},setScopedTestRefs:d=>{c.fetch=d},status:()=>({explorer:t.enabled?"on":"off",exploring:p.explorationActive(),progress:u.status()}),stop:()=>{p.stop(),M(null),u.stop()}}}function Ro({appUrl:e,cwd:r,executeTrail:o,maxTrailLength:n,notifyWork:t,reportProgress:i,reportUnhealthy:a,scopedTestRefs:l}){return Ze({cwd:r,executeTrail:o,maxTrailLength:n,notifyWork:t,reportProgress:i,reportUnhealthy:a,scopedTestRefs:l,loadLockfile:async()=>{let{fingerprint:c,result:u}=await re(r);return u.match(p=>({fingerprint:c,lockfile:p}),()=>null)},probeApp:async()=>await ie(e)==null})}function Eo(){let e=We();return{headedActive:e.headedActive,interactiveActive:e.active,interactiveQueued:e.queued,poolSize:e.poolSize}}function To(e,r){let o=setTimeout(e,r);return()=>{clearTimeout(o)}}function Co(e){switch(e){case"p0":return"p0-ui";case"p1":return"p1-cli";case"p2":return"p2-cover";case"p3":return"p3-explore"}}import{fork as Io}from"child_process";import sr from"os";import{CancellationTokenSource as cr,ResponseError as dr}from"vscode-jsonrpc/node";function ur(e,r){return()=>{let o=Io(e,["run-worker"],{cwd:r,detached:!0,stdio:["ignore","inherit","inherit","ipc"]});return{connection:Ie(o),kill:()=>{Wo(o)},onExit:n=>{o.once("exit",n)}}}}function pr(e){let r={closed:!1,lockfileProvider:e.lockfileProvider,nextId:0,size:e.initialSize,spawn:e.spawn,waiters:[],workers:[]};return{close:async()=>{r.closed=!0,await Promise.all([...r.workers].map(o=>$(o,r)))},execute:(o,n)=>Lo(o,n,r),exploreTrail:(o,n)=>_o(o,n,r),routeSpan:(o,n)=>{let t=r.workers.find(i=>i.runId===o);t?.worker.connection.sendNotification(Te,{runId:o,span:n})},setSize:o=>{Uo(o,r)}}}function Wo(e){let r=e.pid;if(r!=null)try{process.kill(-r,"SIGKILL")}catch{e.kill("SIGKILL")}}var Ao=1e4,fr=-32800;async function Lo(e,r,o){let n=await mr(o);if(n.runId=e.runId,!n.alive)return C(n,o),{outcome:{detail:"worker-exit",kind:"error"},serverNotified:!1};let t=new cr,i=()=>{t.cancel()};r.aborted&&t.cancel(),r.addEventListener("abort",i,{once:!0});try{let a=await n.worker.connection.sendRequest(Pe,e,t.token),l=be.safeParse(a);return l.success?l.data:{outcome:{detail:"bad-outcome-frame",kind:"error"},serverNotified:!1}}catch(a){return Ho(a,n)}finally{r.removeEventListener("abort",i),t.dispose(),C(n,o)}}async function mr(e){let r=e.workers.find(o=>o.alive&&o.runId===void 0);if(r!=null)return r.runId="pending",r;if(e.workers.length<e.size){let o=Do(e);return o.runId="pending",await o.ready,o}return new Promise(o=>{e.waiters.push(n=>{n.runId="pending",o(n)})})}function Do(e){let r=e.spawn(),o={resolve:()=>{}},n={alive:!0,id:e.nextId,ready:new Promise(t=>{o.resolve=t,r.connection.onNotification(xe,t)}),runId:void 0,worker:r};return e.nextId+=1,r.connection.onRequest(Re,()=>e.lockfileProvider()),r.onExit(()=>{n.alive=!1,e.workers=e.workers.filter(t=>t!==n),r.connection.dispose(),o.resolve()}),e.workers.push(n),n}function C(e,r){if(e.runId=void 0,!e.alive||r.closed)return;if(r.workers.length>r.size){$(e,r);return}let o=r.waiters.shift();o?.(e)}async function $(e,r){if(r.workers=r.workers.filter(t=>t!==e),!e.alive)return;let o=new Promise(t=>{e.worker.onExit(t)});await e.worker.connection.sendNotification(Ce).catch(()=>{});let n=setTimeout(()=>{e.worker.kill()},Ao);await o,clearTimeout(n)}function Ho(e,r){return e instanceof dr&&e.code===fr?{outcome:{detail:"aborted",kind:"error"},serverNotified:!1}:r.alive?{outcome:{detail:e instanceof Error?e.message:String(e),kind:"error"},serverNotified:!1}:{outcome:{detail:"worker-exit",kind:"error"},serverNotified:!1}}async function _o(e,r,o){let n=await mr(o);if(n.runId="explore",!n.alive)return C(n,o),{kind:"error"};let t=new cr,i=()=>{t.cancel()};r.aborted&&t.cancel(),r.addEventListener("abort",i,{once:!0});try{let a=await n.worker.connection.sendRequest(Ee,e,t.token),l=de.safeParse(a);return l.success?l.data:{kind:"error"}}catch(a){return Mo(a)}finally{r.removeEventListener("abort",i),t.dispose(),C(n,o)}}function Mo(e){return e instanceof dr&&e.code===fr?{kind:"aborted"}:{kind:"error",reason:`transport:${e instanceof Error?e.message.slice(0,120):"unknown"}`}}function Uo(e,r){r.size=e,e>sr.availableParallelism()&&s.warn({cores:sr.availableParallelism(),size:e},"worker pool size exceeds available cores");let o=r.workers.filter(t=>t.alive&&t.runId===void 0),n=r.workers.length-e;o.slice(0,Math.max(0,n)).forEach(t=>{$(t,r)})}import I from"fs";import{graphql as W}from"gql.tada";import{print as B}from"graphql";var qo=W(`
|
|
35
|
+
query DaemonExploration($devSessionId: String!) {
|
|
36
|
+
exploration(devSessionId: $devSessionId) {
|
|
37
|
+
active
|
|
38
|
+
localWorkers
|
|
39
|
+
maxTrailLength
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
`),Oo=W(`
|
|
43
|
+
subscription WatchExplorationChanged($devSessionId: String!) {
|
|
44
|
+
explorationChanged(devSessionId: $devSessionId) {
|
|
45
|
+
exploration {
|
|
46
|
+
active
|
|
47
|
+
localWorkers
|
|
48
|
+
maxTrailLength
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
`);function yr({config:e,devSessionId:r,machinery:o,sseClient:n}){return Fo({config:e,devSessionId:r,machinery:o}),n.subscribe({query:B(Oo),variables:{devSessionId:r}},{complete:()=>{},error:t=>{s.error(t,"exploration subscription error")},next:t=>{gr(o,t.data?.explorationChanged.exploration)}})}async function Fo({config:e,devSessionId:r,machinery:o}){let n=await g({config:e,document:qo,variables:{devSessionId:r}});gr(o,n.exploration)}function gr(e,r){r!=null&&(e.setMaxTrailLength(r.maxTrailLength),e.setConcurrency(r.localWorkers),e.setEnabled(r.active))}function Sr({config:e,devSessionId:r,machinery:o}){o.setScopedTestRefs(n=>Me(e,r,n)),o.setReportProgress(n=>{_e({attempts:n.attempts,config:e,devSessionId:r,findings:n.findings,trail:He(n.result)}).catch(t=>{s.warn({error:t},"exploration progress report failed")})}),o.setReportUnhealthy(()=>{Ue(e,r).catch(n=>{s.warn({error:n},"exploration unhealthy report failed")})})}var No=W(`
|
|
53
|
+
subscription HooksPausedWatch($projectId: String!) {
|
|
54
|
+
hooksPausedRequested(projectId: $projectId) {
|
|
55
|
+
paused
|
|
56
|
+
projectId
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
`),$o=W(`
|
|
60
|
+
subscription WatchLocalConcurrencyChanged {
|
|
61
|
+
myMaxLocalConcurrentRunsChanged
|
|
62
|
+
}
|
|
63
|
+
`);function kr({pool:e,sseClient:r}){return r.subscribe({query:B($o)},{complete:()=>{},error:o=>{s.error(o,"localConcurrency subscription error")},next:o=>{let n=o.data?.myMaxLocalConcurrentRunsChanged;n!=null&&(R(n),e.setSize(n))}})}function vr({cwd:e,projectId:r,sseClient:o}){return o.subscribe({query:B(No),variables:{projectId:r}},{complete:()=>{},error:n=>{s.error(n,"hooksPaused subscription error")},next:n=>{let t=n.data?.hooksPausedRequested?.paused;t!=null&&j({cwd:e,paused:t})}})}function j({cwd:e,paused:r}){let o=me(e);if(r&&!I.existsSync(o)){I.writeFileSync(o,"");return}!r&&I.existsSync(o)&&I.unlinkSync(o)}var Qo=6e4,wr=500,Go=15e3,hr=6e4,Vo=3,Ko=z(`
|
|
64
|
+
mutation HeartbeatDevSessionWatch($id: String!) {
|
|
65
|
+
heartbeatDevSession(id: $id) {
|
|
66
|
+
__typename
|
|
67
|
+
... on DevSession {
|
|
68
|
+
id
|
|
69
|
+
}
|
|
70
|
+
... on DevSessionEndedError {
|
|
71
|
+
message
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
`),Yo=z(`
|
|
76
|
+
query WatchLocalConcurrency {
|
|
77
|
+
currentUser {
|
|
78
|
+
id
|
|
79
|
+
maxLocalConcurrentRuns
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
`),Xo=z(`
|
|
83
|
+
mutation EndDevSessionWatch($projectId: String!, $cwd: String!) {
|
|
84
|
+
endDevSession(projectId: $projectId, cwd: $cwd) {
|
|
85
|
+
__typename
|
|
86
|
+
... on DevSession {
|
|
87
|
+
id
|
|
88
|
+
}
|
|
89
|
+
... on NoActiveDevSessionError {
|
|
90
|
+
message
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
`);async function Kt(e){let{executor:r}=e;Sn();let o=fn(process.cwd()),n=o.cwd,t=sn(n),i=pn(),a=lr({config:o,executor:r,pool:i.pool}),l={handler:()=>{}},c=dn(),u=je(),p=De({config:o,cwd:n,executor:r,explorationStatus:a.status,ready:c.promise,onShutdownRequest:()=>{l.handler()},sseHealth:()=>u.snapshot()}),d=await un({cwd:n,ipc:p,releasePid:t}),S=await H(n);S.isErr()&&(process.stderr.write(`ripplo: ${_(S.error)}
|
|
95
|
+
`),process.exit(1));let v=S.value,k=await br(()=>U({config:o,cwd:n,lockfile:v}),{config:o,label:"initial sync"}),b=await vn(o);j({cwd:n,paused:k.hooksPaused});let f=Ae(n);f!=null&&s.info("watching branch %s in %s",f,n);let m=jo({headers:{Authorization:`Bearer ${o.token}`},retry:Ne,retryAttempts:1/0,url:`${o.ripploServerUrl}/graphql`}),y=ln({cwd:n,initialConcurrency:b});i.provide(y);let A=await rn({cwd:n,pool:y}),J=tn({claim:p.claim,config:o,cwd:n,initialId:k.devSessionId,pool:y,sseClient:m,sseHealth:u}),xr=vr({cwd:n,projectId:o.projectId,sseClient:m}),Pr=kr({pool:y,sseClient:m}),Rr=yr({config:o,devSessionId:k.devSessionId,machinery:a,sseClient:m});Sr({config:o,devSessionId:k.devSessionId,machinery:a});let Er=nn({config:o,session:J}),Tr=gn(),Q=await Zo({config:o,devSessionId:k.devSessionId,executor:r});c.resolve(),on({devSessionId:k.devSessionId,executor:r,tunnel:Q});let Cr=async()=>{Er(),Tr(),a.stop(),d.close(),J.stop(),xr(),Pr(),Rr(),await y.close(),await en(Q),await A.stop().catch(()=>{}),await Promise.race([g({config:o,document:Xo,variables:{cwd:o.cwd,projectId:o.projectId}}).catch(()=>{}),new Promise(Ir=>setTimeout(Ir,3e3))]),t()},h=()=>{Cr().finally(()=>process.exit(0))};l.handler=h,process.on("SIGINT",h),process.on("SIGTERM",h),process.on("SIGHUP",h),process.on("SIGBREAK",h),await new Promise(()=>{})}async function Zo({config:e,devSessionId:r,executor:o}){if(o==="cloud")return Oe({config:e,devSessionId:r})}async function en(e){e!=null&&await e.stop()}function rn({cwd:e,pool:r}){return fe({localDir:Bo.join(e,".ripplo",".local"),writePortFile:!0,onRrwebBatch:()=>{},onSpan:o=>{let n=o.attributes["ripplo.run"];n!=null&&r.routeSpan(n,o)}})}function on({devSessionId:e,executor:r,tunnel:o}){process.stdout.write(`${ve({devSessionId:e,executor:r,tunnelHostname:o?.hostname,version:Y()})}
|
|
96
|
+
`)}function nn({config:e,session:r}){let o=async()=>{try{let t=await g({config:e,document:Ko,variables:{id:r.getId()}});t.heartbeatDevSession?.__typename==="DevSessionEndedError"&&(s.warn("dev session ended server-side (%s); re-registering",t.heartbeatDevSession.message),await r.reregister())}catch(t){s.warn("heartbeat failed: %s",t instanceof Error?t.message:String(t))}},n=setInterval(()=>{o()},Go);return()=>{clearInterval(n)}}function tn({claim:e,config:r,cwd:o,initialId:n,pool:t,sseClient:i,sseHealth:a}){let l=n,c=null,u=0,p=0,d=f=>{b(f)},S=()=>{let f=$e({claim:e,cwd:o,devSessionId:l,onSubscriptionDead:d,pool:t,sseClient:i,sseHealth:a}),m=Be({cwd:o,devSessionId:l,onSubscriptionDead:d,sseClient:i});return()=>{f(),m()}},v=S(),k=async f=>{let m=Date.now();u=m-p>hr*2?1:u+1,p=m,u>=Vo&&a.markUnhealthy(f),await an(Math.min(1e3*2**(u-1),hr));let y=await H(o);if(y.isErr()){s.error("re-register: compile failed: %s",_(y.error));return}let A=await br(()=>U({config:r,cwd:o,lockfile:y.value}),{config:r,label:"re-register sync"});v(),l=A.devSessionId,v=S(),s.info("re-registered dev session as %s",l)},b=f=>(c!=null||(c=k(f).finally(()=>{c=null})),c);return{getId:()=>l,reregister:()=>b("dev session ended server-side"),stop:()=>{v()}}}function an(e){return new Promise(r=>setTimeout(r,e))}function ln({cwd:e,initialConcurrency:r}){return pr({initialSize:r,spawn:ur(wn(),e),lockfileProvider:async()=>{let o=await x(e);return o.isErr()?{unavailable:`daemon-load-failed:${o.error.kind}`}:{lockfileJson:X(Z,o.value)}}})}function sn(e){try{return te({cwd:e,onCompromised:cn})}catch(r){throw r instanceof ne&&(process.stderr.write(`${we({cwd:r.cwd,pid:r.pid})}
|
|
97
|
+
`),process.exit(1)),r}}function cn(){s.error("daemon lock compromised; shutting down"),process.stderr.write(`${he()}
|
|
98
|
+
`),process.exit(1)}function dn(){let e={handler:()=>{}};return{promise:new Promise(o=>{e.handler=o}),resolve:()=>{e.handler()}}}async function un({cwd:e,ipc:r,releasePid:o}){return(await Ke({cwd:e,onConnection:r.handleConnection})).match(t=>t,t=>{process.stderr.write(`${ge(t)}
|
|
99
|
+
`),o(),process.exit(1)})}function pn(){let e={provide:()=>{}};return{pool:new Promise(o=>{e.provide=o}),provide:o=>{e.provide(o)}}}function fn(e){return w(e).match(r=>r,r=>{process.stderr.write(`${oe(r)}
|
|
100
|
+
`),process.exit(1)})}function br(e,{config:r,label:o}){let n=r.ripploServerUrl.includes("localhost")||r.ripploServerUrl.includes("127.0.0.1");return zo(async()=>{try{return await e()}catch(t){mn({config:r,error:t});let i=t instanceof Error?t.message:String(t);throw yn(i)?t:(s.error("%s failed: %s",o,i),new Jo(i))}},{factor:2,maxTimeout:n?2e3:1e4,minTimeout:n?100:1e3,retries:1/0,onFailedAttempt:({attemptNumber:t,error:i})=>{s.warn("%s attempt %d failed \u2014 retrying: %s",o,t,i.message)}})}function mn({config:e,error:r}){let o=G(r);o==="UNAUTHENTICATED"&&(process.stderr.write(`ripplo: ${ke()}
|
|
101
|
+
`),process.exit(1)),o==="FORBIDDEN"&&(process.stderr.write(`ripplo: ${Se({projectId:e.projectId,serverUrl:e.ripploServerUrl})}
|
|
102
|
+
`),process.exit(1))}function yn(e){return e.includes("status 502")||e.includes("ECONNREFUSED")||e.includes("Failed to connect")||e.includes("fetch failed")}function gn(){L({maxRuns:wr});let e=setInterval(()=>{L({maxRuns:wr})},Qo);return()=>{clearInterval(e)}}function Sn(){process.on("unhandledRejection",e=>{s.error({err:e},"unhandledRejection in watch; continuing")}),process.on("uncaughtException",e=>{s.error({err:e},"uncaughtException in watch; continuing")})}var kn=4;async function vn(e){try{let o=(await g({config:e,document:Yo,variables:void 0})).currentUser?.maxLocalConcurrentRuns;if(o!=null)return R(o),o}catch(r){s.warn({err:r},"failed to fetch local concurrency setting; using default")}return kn}function wn(){let e=process.argv[1];if(e==null)throw new Error("cli entry unavailable");return e}export{Kt as runDaemon};
|