ripplo 0.7.37 → 0.7.39

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.
@@ -1,238 +0,0 @@
1
- #!/usr/bin/env node
2
- import{B as Je,V as Ke,W as Qe,Z as Ge,_ as Xe,a as N,b as De,g as _e,i as qe,j as He,k as We,l as g,m as Be,o as Ve,p as ie,q as h,r as F,s as ze,w as I}from"./chunk-ITI53W73.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 en from"fs";import W from"path";import{config as kt}from"dotenv";import{z as q}from"zod";import{err as St,ok as nn}from"neverthrow";import _ from"fs";import le from"path";import{err as ae,ok as Ye}from"neverthrow";import{z as D}from"zod";var mt=le.join(".ripplo","project.json"),se=[".env",".env.local"],gt=D.object({envFiles:D.array(D.string().min(1)).optional(),projectId:D.string().min(1)});function Ze(e){return le.join(e,mt)}function de(e){let n=Ze(e);return _.existsSync(n)?ht(n).andThen(t=>{let r=gt.safeParse(t);return r.success?Ye({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 ht(e){try{return Ye(JSON.parse(_.readFileSync(e,"utf8")))}catch(n){return ae({issues:[n instanceof Error?n.message:String(n)],kind:"project-file-invalid",path:e})}}function zi({cwd:e,envFiles:n,projectId:t}){let r=Ze(e);_.mkdirSync(le.dirname(r),{recursive:!0});let o={projectId:t};n!=null&&!Rt(n)&&(o.envFiles=[...n]),_.writeFileSync(r,JSON.stringify(o,null,2)+`
3
- `)}function Rt(e){return e.length!==se.length?!1:e.every((n,t)=>n===se[t])}function ea(e){let t=ce(e)?.envFiles??[".env",".env.local"],r=W.join(e,".ripplo");t.forEach(o=>{let i=W.resolve(r,o);en.existsSync(i)&&kt({override:!0,path:i,quiet:!0})}),H=void 0}var xt=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?nn(H):bt().map(e=>(H=e,e))}function wt(e){let t=ce(e)?.envFiles??[],r=W.join(e,".ripplo");return t.map(o=>W.resolve(r,o)).filter(o=>!en.existsSync(o))}function bt(){let e=xt.safeParse(process.env);if(!e.success)return St({issues:e.error.issues.map(t=>`${t.path.join(".")}: ${t.message}`),kind:"env-invalid",missingEnvFiles:wt(process.cwd())});let n=e.data;return nn({appUrl:n.RIPPLO_APP_URL,engineUrl:n.RIPPLO_ENGINE_URL,webhookSecret:n.RIPPLO_WEBHOOK_SECRET})}import{readFileSync as Et}from"fs";import{z as tn}from"zod";var vt=tn.object({version:tn.string()});function V(){let e=Et(new URL("../package.json",import.meta.url),"utf8");return vt.parse(JSON.parse(e)).version}import me from"fs";import z from"path";import{createJiti as Lt}from"jiti";import{err as U,ok as sn}from"neverthrow";import It from"fs";import M from"path";import P from"typescript";function rn(e){let n=M.join(e,"index.ts"),t=Tt(e);It.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=>Pt(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 Pt(e,n){let t=e.file?.fileName;return t==null?!0:t.startsWith(n)}var Ct=M.join(".local","tsbuildinfo");function Tt(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,Ct)}}import{createHash as jt}from"crypto";import on from"fs/promises";import ue from"path";import{err as C,ok as pe,Result as At}from"neverthrow";var $=".ripplo/fixtures",fe=10*1024*1024,ye=50*1024*1024;async function an(e,n){let t=Ft(n);if(t.length===0)return pe({});let r=ue.join(e,$),o=await Promise.all(t.map(i=>Mt({fixturesRoot:r,name:i})));return At.combine(o).andThen($t)}function Ft(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 Mt({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 on.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 on.readFile(t);if(o.byteLength>fe)return C({kind:"fixture-too-large",name:n,size:o.byteLength});let i=jt("sha256").update(o).digest("hex");return pe([n,{sha256:i,size:o.byteLength}])}function $t(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 ln(e){let{result:n}=await ge(e);return n}async function ge(e){let n=Ot(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=rn(n);return r.ok?(await Nt(t)).andThen(s=>_t({entryPath:t,exported:s})).match(async s=>(await an(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 Ut=new Set([".local","debug","node_modules"]);function Ot(e){return dn(e).toSorted((n,t)=>n.localeCompare(t)).join("|")}function dn(e){return(me.existsSync(e)?me.readdirSync(e,{withFileTypes:!0}):[]).flatMap(t=>{if(Ut.has(t.name))return[];let r=z.join(e,t.name);if(t.isDirectory())return dn(r);let o=me.statSync(r);return[`${r}:${String(o.mtimeMs)}:${String(o.size)}`]})}async function Nt(e){try{let t=await Lt(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 sn(r)}catch(n){return U({kind:"load-threw",message:Dt(n)})}}function Dt(e){return e instanceof Error?e.message:String(e)}function _t({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?sn(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 wa(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: ${qt(e)}`,j("create","DSL authoring + lint rules")].join(`
6
- `)}function Pa(){return`${T} is up to date`}function Ca(e){return[`${T} is ${e==="missing"?"missing":"out of date"} \u2014 run \`npx ripplo compile\` and commit the result`,j("setup")].join(`
7
- `)}function Ta(){return`Wrote ${T}`}function qt(e){switch(e.kind){case"typecheck-failed":return["TypeScript errors in .ripplo/:",...cn(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?):",...cn(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 Ht(e.error)}}function cn(e,n=8){return e.length<=n?e:[...e.slice(0,n),`\u2026 and ${String(e.length-n)} more`]}function Ht(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 La(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 Wt(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 Wt(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 zt,ok as Jt}from"neverthrow";import{z as Re}from"zod";var Bt="https://ripplo.ai";function pn(){return yn().RIPPLO_SERVER_URL}function fn(){return yn().RIPPLO_PROJECT_ID}var Vt=Re.object({RIPPLO_PROJECT_ID:Re.string().min(1).optional(),RIPPLO_SERVER_URL:Re.string().min(1).default(Bt)}),un;function yn(){return un??=Vt.parse(process.env),un}import mn from"fs";import ke from"path";function gn(e){let n=mn.realpathSync(e),t=n,r=ke.dirname(t);for(;r!==t;){if(mn.existsSync(ke.join(t,".git")))return t;t=r,r=ke.dirname(t)}return n}function hn(e){return de(e).andThen(n=>B().andThen(t=>{let r=pn(),o=Ne(r);return o==null?zt({kind:"not-authenticated"}):Jt({appUrl:t.appUrl,cwd:gn(e),engineUrl:t.engineUrl,projectId:fn()??n.projectId,ripploServerUrl:r,token:o,tunnelAuth:void 0,webhookSecret:t.webhookSecret})}))}import Rn from"fs";import{checkSync as Kt,lockSync as Qt}from"proper-lockfile";var Gt="dev.pid",kn=15e3;function Sn(e){return w(e,Gt)}function xn(e){try{return Kt(Sn(e),{realpath:!1,stale:kn})}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 Ya({cwd:e,onCompromised:n}){Oe(e);let t=Sn(e),r=Xt({cwd:e,onCompromised:n,path:t});return Rn.writeFileSync(t,String(process.pid)),()=>{try{r()}catch{}}}function Xt({cwd:e,onCompromised:n,path:t}){try{return Qt(t,{realpath:!1,stale:kn,onCompromised:()=>{n()}})}catch(r){throw Yt(r)?new Se({cwd:e,pid:Zt(t)}):r}}function Yt(e){if(!(e instanceof Error)||!("code"in e))return!1;let{code:n}=e;return n==="ELOCKED"}function Zt(e){try{let n=Rn.readFileSync(e,"utf8").trim(),t=Number.parseInt(n,10);return Number.isFinite(t)&&t>0?t:null}catch{return null}}import er from"p-queue";var nr=4,tr={"p0-ui":3,"p1-cli":2,"p2-cover":1,"p3-explore":0},G=new er({concurrency:nr}),k={headedActive:0,interactiveActive:0,interactiveQueued:0},wn={current:null};function ns({headed:e,task:n,workClass:t}){let r=tr[t];return t==="p3-explore"?G.add(n,{priority:r}):(k.interactiveQueued+=1,X(),G.add(()=>rr({headed:e,task:n}),{priority:r}))}function ts(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 rs(e){wn.current=e}async function rr({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(){wn.current?.()}import we from"fs";import be from"path";function bn(e){try{let n=or(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 or(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 ir from"crypto";import{readFile as En}from"fs/promises";import vn from"path";import{graphql as ar}from"gql.tada";import{err as sr,ok as lr}from"neverthrow";var dr=ar(`
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 Rs(e,n){let t=await O(e);if(t.isErr())return sr({error:t.error,kind:"compilation-failed"});let r=await Ee({config:n,cwd:e,lockfile:t.value});return lr({devSessionId:r.devSessionId,lockfile:t.value})}async function Ee(e){let n=He(e.lockfile);return ur({config:e.config,cwd:e.cwd,fixtures:e.lockfile.fixtures,payload:n})}function cr(e){return ir.createHash("sha256").update(JSON.stringify(e)).digest("hex")}async function ur({config:e,cwd:n,fixtures:t,payload:r}){let o=cr(r),i=bn(n),s=await fr(n),l=await pr(n,t),u=await f({config:e,document:dr,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 pr(e,n){let t=Object.entries(n);return Promise.all(t.map(async([r,o])=>({contentBase64:(await En(vn.join(e,$,r))).toString("base64"),sha256:o.sha256})))}async function fr(e){try{return await En(vn.join(e,T),"utf8")}catch{return null}}import{randomUUID as zr}from"crypto";import{createId as Jr}from"@paralleldrive/cuid2";import{CancellationTokenSource as Kr,ResponseError as Qr}from"vscode-jsonrpc/node";import{graphql as yr}from"gql.tada";var mr=yr(`
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 In(e){try{let t=(await f({config:e.config,document:mr,variables:gr(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 hr(n)}}function gr({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 hr(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 Rr,NotificationType as Pn,RequestType as kr,RequestType0 as Cn,SocketMessageReader as Sr,SocketMessageWriter as xr}from"vscode-jsonrpc/node";import{z as a}from"zod";var wr="daemon.sock",br="daemon.log";function Ps(e){return w(e,wr)}function Cs(e){return w(e,br)}function Tn(e){return Rr(new Sr(e),new xr(e))}var jn=a.object({all:a.boolean(),headed:a.boolean(),tests:a.array(a.string())}),Ts=a.object({jobId:a.string(),total:a.number()}),Er=a.enum(["on","off"]),vr=a.object({attempts:a.number(),findings:a.number()}),js=a.object({active:a.number(),explorer:Er,exploring:a.number(),progress:vr,queued:a.number(),sseHealth:a.object({detail:a.string().optional(),ok:a.boolean()}).optional(),version:a.string().optional()}),Ir=a.enum(["MAX_RUNS","OVERAGE_CAP","MAX_AGENTS","MAX_CONCURRENT_RUNS","MAX_PROJECTS"]),Pr=a.discriminatedUnion("type",[a.object({code:Ir,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:Pr}),a.object({detail:a.string(),kind:a.literal("dispatch-timeout")}),a.object({detail:a.string(),kind:a.literal("infra-error")})]),Cr=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()})]),As=a.object({event:Cr,jobId:a.string()}),Fs=a.object({failed:a.number(),jobId:a.string(),notRun:a.number(),passed:a.number()}),Ms=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")})]),An=new kr("ripplo/enqueue"),Fn=new Cn("ripplo/status"),Mn=new Cn("ripplo/shutdownIfIdle"),$n=new Pn("ripplo/jobEvent"),Ln=new Pn("ripplo/jobDone");import{graphql as Tr}from"gql.tada";async function Un(e,n){let r=(await f({config:e,document:jr,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 jr=Tr(`
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 Ar}from"vscode-jsonrpc/node";function Ie(e){return`${e.workflowSlug}/${e.testSlug}`}function On(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 Ar,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 Nn(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 Dn}from"neverthrow";function qn({all:e,ids:n,lockfile:t}){if(e&&n.length>0)return Ce({kind:"conflicting-flags"});if(e)return Dn(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:Mr(t,i)})),o=r.filter(i=>i.refs.length===0).map(i=>i.id);return o.length>0?Ce({kind:"unknown-ids",known:Fr(t),unknown:o}):Dn([...new Set(r.flatMap(i=>i.refs))])}function Hn(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 Fr(e){return e.workflows.map(n=>g(n.name))}function Mr(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||_n(r.ref)===_n(n)).map(r=>r.ref)}function _n(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 Bn}from"neverthrow";import{graphql as Vn}from"gql.tada";import{execFileSync as $r}from"child_process";var Lr=256*1024*1024;function ee(e,n){return $r("git",[...e],{cwd:n,encoding:"utf8",maxBuffer:Lr,stdio:["ignore","pipe","pipe"]})}async function zn({config:e,cwd:n,lockfile:t}){await Or({config:e,cwd:n,lockfile:t});let r=await Dr(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"}):Bn(i)}var Ur=Vn(`
90
- mutation AddDirtyTestsToScope($projectId: String!, $cwd: String!, $workflowSlugs: [String!]!) {
91
- addDirtyTestsToScope(projectId: $projectId, cwd: $cwd, workflowSlugs: $workflowSlugs) {
92
- __typename
93
- }
94
- }
95
- `);async function Or({config:e,cwd:n,lockfile:t}){let r=new Set(_r(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:Ur,variables:{cwd:e.cwd,projectId:e.projectId,workflowSlugs:o}}).catch(i=>{y.warn({err:i},"auto-scope of dirty tests failed")})}var Nr=Vn(`
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 Dr(e){try{let t=(await f({config:e,document:Nr,variables:{cwd:e.cwd,projectId:e.projectId}})).project?.devSession?.scopeItems??[];return Bn(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 Wn=".ripplo/workflows/";function _r(e){try{return ee(["status","--porcelain","--",".ripplo/workflows"],e).split(`
112
- `).map(n=>n.slice(3).trim()).filter(n=>n.startsWith(Wn)&&n.endsWith(".ts")).map(n=>n.slice(Wn.length)).filter(n=>n!=="index.ts"&&!n.endsWith("/index.ts"))}catch{return[]}}import{graphql as qr}from"gql.tada";var Hr=2e3,Wr=qr(`
113
- query DaemonCloudRunStatus($runId: String!) {
114
- run(id: $runId) {
115
- status
116
- failureReason
117
- }
118
- }
119
- `);function Kn({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 Br(e,r).catch(()=>"unknown");if(!(i||o.aborted)){if(!l&&(d==="running"||Jn(d))&&(l=!0,t()),Jn(d)){i=!0,n(Vr(d));return}s=setTimeout(()=>{u()},Hr)}};return u(),{stop:()=>{i=!0,s!=null&&clearTimeout(s)}}}async function Br(e,n){let r=(await f({config:e,document:Wr,variables:{runId:n}})).run?.status;return r??"unknown"}function Jn(e){return e==="passed"||e==="failed"||e==="warning"||e==="cancelled"||e==="unready"}function Vr(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 Gr=12e4,Xr=-32099;function Yr(e){let n=new AbortController;return e.isCancellationRequested?(n.abort(),n.signal):(e.onCancellationRequested(()=>{n.abort()}),n.signal)}function Rl(e){let n={...e,inflight:new Map,jobs:new Map};return{claim:t=>ro(n,t),handleConnection:t=>{Zr(n,t)},idle:()=>Xn(n)}}function Zr(e,n){let t=Tn(n);t.onRequest(An,(r,o)=>eo({connection:t,ctx:e,params:r,token:o})),t.onRequest(Fn,()=>{let r=xe();return{active:r.active,queued:r.queued,sseHealth:e.sseHealth(),version:V(),...e.explorationStatus()}}),t.onRequest(Mn,()=>{let r=Xn(e);return r&&e.onShutdownRequest(),r}),t.onClose(()=>{no(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 Xn(e){let n=xe();return e.jobs.size===0&&n.active===0&&n.queued===0}async function eo({connection:e,ctx:n,params:t,token:r}){let o=jn.safeParse(t);if(!o.success)throw Qn({code:"bad-message"});await n.ready;let i=await io({config:n.config,cwd:n.cwd,message:o.data});if(i.kind==="error")throw Qn(i.error);let s=zr(),l=new Kr;return r.onCancellationRequested(()=>{Yn(n,s)}),n.jobs.set(s,{cancellation:l,connection:e,failed:0,notRun:0,passed:0,total:i.selections.length}),yo({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 Qn(e){return new Qr(Xr,e.code,e)}function Yn(e,n){let t=e.jobs.get(n);t!=null&&(t.cancellation.cancel(),e.jobs.delete(n),Nn(e.inflight,n))}function no(e,n){[...e.jobs.entries()].filter(([,t])=>t.connection===n).forEach(([t])=>{Yn(e,t)})}function Zn(e,n,t){let r=e.jobs.get(n);r!=null&&(Gn(()=>r.connection.sendNotification($n,{event:t,jobId:n})),t.kind==="test-outcome"&&(to(r,t.outcome.kind),r.passed+r.failed+r.notRun>=r.total&&(Gn(()=>r.connection.sendNotification(Ln,{failed:r.failed,jobId:n,notRun:r.notRun,passed:r.passed})),e.jobs.delete(n))))}function Gn(e){Promise.resolve().then(e).catch(n=>{y.warn({err:n},"ipc notification failed")})}function to(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=>{Zn(e,r,t)})}function ro(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 oo(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 io({config:e,cwd:n,message:t}){return(await ln(n)).match(o=>ao({config:e,cwd:n,lockfile:o,message:t}),o=>Promise.resolve({error:{code:"compile-failed",detail:o.kind,diagnostics:[...oo(o)]},kind:"error"}))}async function ao({config:e,cwd:n,lockfile:t,message:r}){let o=await lo(e.appUrl);if(o!=null)return{error:{code:"app-unreachable",detail:o,url:e.appUrl},kind:"error"};let i=await co({config:e,cwd:n,lockfile:t});return i!=null?{error:{code:"sync-failed",detail:i},kind:"error"}:(await uo({config:e,cwd:n,lockfile:t,message:r})).match(async l=>({kind:"ready",lockfileHashValue:qe(t),selections:Hn(t,l),targetsByClaimKey:await Un(e,n)}),l=>Promise.resolve({error:l,kind:"error"}))}var so=2e3;async function lo(e){try{return await fetch(e,{method:"HEAD",signal:AbortSignal.timeout(so)}),null}catch(n){return n instanceof Error?n.message:String(n)}}async function co(e){try{return await Ee(e),null}catch(n){return n instanceof Error?n.message:String(n)}}async function uo({config:e,cwd:n,lockfile:t,message:r}){return!r.all&&r.tests.length===0?(await zn({config:e,cwd:n,lockfile:t})).mapErr(po):qn({all:r.all,ids:r.tests,lockfile:t}).mapErr(fo)}function po(e){return e.kind==="scope-empty"?{code:"selection-nothing-selected"}:{code:"scope-failed",detail:e.detail}}function fo(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 yo(e){await e.selections.reduce((n,t)=>n.then(()=>mo(e,t)),Promise.resolve())}async function mo(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){Zn(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=On({headed:r,inflight:t.inflight,jobId:o,lockfileHashValue:i,runId:Jr(),selection:n,timeoutMs:Gr,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 go(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"&&ho(t,p)}function go(e,n,t,r){return In({config:e.config,executor:e.executor,lockfileHash:r,runId:t,target:n})}function ho(e,n){let t=Pe(e.inflight,n.runId);t!=null&&Kn({config:e.config,runId:t.runId,signal:Yr(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 Ro from"fs";import ko from"path";async function Il(e){let n=ko.join(e,".ripplo","index.ts");if(!Ro.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 Pl(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 Cl({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 bo from"fs";import So from"fs";import je from"path";var xo=["MERGE_HEAD","rebase-merge","rebase-apply","CHERRY_PICK_HEAD","REVERT_HEAD"];function et(e){let n=wo(e);return n==null?!1:xo.some(t=>So.existsSync(je.join(n,t)))}function wo(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 Eo(e){return w(e,"hooks-paused")}function Nl(e){return bo.existsSync(Eo(e))||et(e)?!1:xn(e)}import{createMessageConnection as nt,IPCMessageReader as tt,IPCMessageWriter as rt,NotificationType as vo,NotificationType0 as ot,RequestType as it,RequestType0 as Io}from"vscode-jsonrpc/node";import{z as R}from"zod";var Bl=R.object({headed:R.boolean(),runId:R.string().min(1),testRef:R.string().min(1)}),Vl=R.object({lockfileJson:R.string().optional(),unavailable:R.string().optional()}),zl=R.object({runId:R.string().min(1),span:De}),Jl=R.object({outcome:ve,serverNotified:R.boolean()}),Kl=new ot("worker/ready"),Ql=new it("worker/run"),Gl=new Io("worker/lockfile"),Xl=new it("worker/exploreTrail"),Yl=new vo("worker/span"),Zl=new ot("worker/shutdown");function ed(e){let n=nt(new tt(e),new rt(e));return n.listen(),n}function nd(){let e=nt(new tt(process),new rt(process));return e.listen(),e}import{graphql as v}from"gql.tada";import{gzip as $o}from"zlib";import{promisify as Lo}from"util";import{existsSync as Fe,readFileSync as Me}from"fs";import ne from"path";import{graphql as E}from"gql.tada";function at(e){return[e.kind,e.target,e.value].filter(n=>n.length>0).join(" ")}var Po={"no-effect":"noEffect","required-state-unsatisfied":"requiredStateUnsatisfied",unresolvable:"unresolvable"},Co={"data-rule":"dataRule","page-rule":"pageRule",step:"step"},To={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 st(e){return e.kind==="consistency"?{consistency:{mismatch:Fo(e.mismatch),pending:e.pending}}:e.kind==="pending-check"?{pendingCheck:{budget:e.budget,source:Co[e.source.kind],...jo(e.source)}}:e.kind==="unrunnable"?{unrunnable:{reason:Po[e.reason]}}:e.kind==="driver-error"?{driverError:{errorKind:To[e.error.kind],message:Mo(e.error)}}:{impossibleAction:{subject:Ao(e.step.action)}}}function jo(e){return"check"in e?lt(e.check,!1):{checkKind:void 0,expected:void 0,negated:void 0,subject:void 0}}function lt(e,n){return e.kind==="not"?lt(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 Ao(e){let n=e.locator==null?e.url??"":N(e.locator);return`${e.kind} ${n}`.trim()}function Fo(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 Mo(e){return"message"in e?e.message:"detail"in e?e.detail:null}async function Uo({config:e,cwd:n,fixturesDir:t,headed:r,lockfile:o,runId:i,session:s,signal:l,test:u}){if(!await si(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=ct(c).flatMap(yt=>yt.findings),Le=Oo(x);return Le!=null?(await dt({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 Oo(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 dt(e);await ai(e.config,e.runId,n),await Do(e.config,e.debugDir,e.runId)}async function dt({config:e,debugDir:n,events:t,recordingOptional:r,runId:o,stepSources:i}){let s=ct(t),l=qo(n,o);if(l==null&&!r)throw new Error("recording-missing");return await Qo({aliases:[...Bo(t),...Vo(s)],config:e,generated:zo(t),generatedSingletons:Jo(t),origin:l==null?_o(s):l.origin,records:s,rrwebEvents:l==null?[]:l.events,runId:o,stepSources:i}),l!=null&&await ii(e,o,l),s}var No=E(`
120
- mutation ClipUploadUrl($runId: ID!) {
121
- clipUploadUrl(runId: $runId)
122
- }
123
- `);async function Do(e,n,t){let r=ne.join(n,t,"clip.gif");if(Fe(r))try{let o=await f({config:e,document:No,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 _o(e){return e.reduce((n,t)=>Math.min(n,t.startMs),e[0]?.startMs??0)}function ct(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 qo(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=>Ho(i)).flatMap(i=>Wo(i)?[i.event]:[]),o=r[0];return o==null?null:{events:r,origin:o.timestamp}}function Ho(e){return JSON.parse(e)}function Wo(e){return typeof e=="object"&&e!=null&&Reflect.get(e,"kind")==="rrweb"}function Bo(e){return e.flatMap(n=>n.kind==="world"?n.aliases:[])}function Vo(e){return e.flatMap(n=>{let t=Ko(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 zo(e){return new Set(e.flatMap(n=>n.kind==="world"?n.generated.map(t=>ut(t)):[]))}function ut({entity:e,field:n,key:t}){return`${e}\0${t}\0${n}`}function Jo(e){return new Set(e.flatMap(n=>n.kind==="world"?n.generatedSingletons:[]))}function Ko(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 Qo({aliases:e,config:n,generated:t,generatedSingletons:r,origin:o,records:i,rrwebEvents:s,runId:l,stepSources:u}){let d=i.map((p,c)=>Zo({aliases:e,generated:t,generatedSingletons:r,origin:o,record:p,rrwebEvents:s,sourceTest:u?.[c]??null}));await f({config:n,document:di,variables:{items:[{runId:l,steps:d}]}})}var Go=3,Xo=0;function Yo({endMs:e,rrwebEvents:n,startMs:t}){let r=n.find(o=>o.type===Go&&o.data?.source===Xo&&o.timestamp>=t&&o.timestamp<=e);return r==null?t:r.timestamp}function Zo({aliases:e,generated:n,generatedSingletons:t,origin:r,record:o,rrwebEvents:i,sourceTest:s}){let l=We(o.source,o.index),u=Yo({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,value:c.value??null})),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=>st(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=>ei({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:at(l),url:o.url}}function ei({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(ut({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 ni=Lo($o);async function pt(e,n){await f({config:e,document:pi,variables:{runIds:[n]}})}var ti="application/x-ndjson";async function ri({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:oi,variables:{runId:t}}),i=await fetch(o.debugArtifactUploadUrl,{body:Me(r),headers:{"content-type":ti},method:"PUT"});if(!i.ok){y.warn({runId:t,status:i.status},"behavior upload PUT failed");return}await pt(e,t)}catch(o){y.warn({error:o,runId:t},"behavior upload failed")}}var oi=E(`
125
- mutation DebugArtifactUploadUrl($runId: String!) {
126
- debugArtifactUploadUrl(runId: $runId)
127
- }
128
- `);async function ii(e,n,t){let r=t.events.map(s=>JSON.stringify(s)).join(`
129
- `),o=await ni(Buffer.from(r,"utf8")),i=t.events.at(-1);await f({config:e,document:ci,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 ai(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:ui,variables:{items:[{duration:i,failCount:r,passCount:o,runId:n,status:r>0?"failed":"passed",summary:null,warnCount:0}]}})}async function si(e,n){return((await f({config:e,document:li,variables:{runIds:[n]}})).startRunsBatch??[]).some(r=>r.id===n)}var li=E(`
130
- mutation StartRunsBatch($runIds: [String!]!) {
131
- startRunsBatch(runIds: $runIds) {
132
- id
133
- }
134
- }
135
- `),di=E(`
136
- mutation SubmitRunStepsBatch($items: [SubmitRunStepsItem!]!) {
137
- submitRunStepsBatch(items: $items)
138
- }
139
- `),ci=E(`
140
- mutation SubmitRunRecordingChunk($input: SubmitRunRecordingChunkInput!) {
141
- submitRunRecordingChunk(input: $input)
142
- }
143
- `),ui=E(`
144
- mutation CompleteRunsBatch($items: [CompleteRunItem!]!) {
145
- completeRunsBatch(items: $items) {
146
- id
147
- status
148
- }
149
- }
150
- `),pi=E(`
151
- mutation MarkRunArtifactsUploadedBatch($runIds: [String!]!) {
152
- markRunArtifactsUploadedBatch(runIds: $runIds)
153
- }
154
- `);function fi(e){let n=e.trail;if(!(n==null||!yi(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 yi(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:xi,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:wi,variables:{baseState:e,category:t,projectId:o.projectId,reproRunId:p,signature:c}})}async function re(e,n,t){return(await f({config:e,document:bi,variables:{lockfileHash:t,projectId:e.projectId,signature:n}})).exploreFindingExists}async function mi({attempts:e,config:n,devSessionId:t,findings:r,trail:o}){await f({config:n,document:ki,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 gi(e,n,t){let r=await f({config:e,document:hi,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 hi=v(`
155
- query ExploreScope($devSessionId: String!) {
156
- exploreScope(devSessionId: $devSessionId)
157
- }
158
- `);async function Ri(e,n){return(await f({config:e,document:Si,variables:{devSessionId:n}}).catch(r=>(y.warn({error:r},"reportExploreUnhealthy failed"),null)))?.reportExploreUnhealthy??!1}var ki=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
- `),Si=v(`
173
- mutation ReportExploreUnhealthy($devSessionId: String!) {
174
- reportExploreUnhealthy(devSessionId: $devSessionId)
175
- }
176
- `),xi=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
- `),wi=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
- `),bd=v(`
219
- mutation SetExploreFindingStatus(
220
- $projectId: String!
221
- $signature: String!
222
- $status: ExploreFindingStatus!
223
- ) {
224
- setExploreFindingStatus(projectId: $projectId, signature: $signature, status: $status)
225
- }
226
- `),bi=v(`
227
- query ExploreFindingExists($projectId: String!, $signature: String!, $lockfileHash: String!) {
228
- exploreFindingExists(projectId: $projectId, signature: $signature, lockfileHash: $lockfileHash)
229
- }
230
- `);import{graphql as ft}from"gql.tada";async function Ei(e,n,t){await f({config:e,document:vi,variables:{reason:t,runId:n}}).catch(r=>{y.error(r,"failRun submission failed")})}var vi=ft(`
231
- mutation FailRun($runId: String!, $reason: String!) {
232
- failRun(runId: $runId, reason: $reason)
233
- }
234
- `),Pd=ft(`
235
- mutation MarkRunUnready($runId: String!, $cause: RunUnreadyCause!) {
236
- markRunUnready(runId: $runId, cause: $cause)
237
- }
238
- `);import{randomUUID as Ii}from"crypto";async function Pi({assign:e,config:n,debugDir:t,devSessionId:r,fixturesDir:o,headed:i,lockfile:s,report:l,session:u,signal:d}){let p=ze(s);if(e.stepRuns.length===0)return{kind:"error",reason:"empty-trail"};let c=Ui(p,e.stepRuns),m=await Ge({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-${Ii()}-${String(x)}`},d),S=l?await Mi({baseStateTest:e.baseStateTest,config:n,debugDir:t,devSessionId:r,lockfileHash:e.lockfileHash,outcome:m,reproJson:Ai(p,e),stepSources:Fi(c)}):!1;return ji(m,c.length),Oi(m,S,Ci(c,e,m))}function Ci(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:Ti(e)}}function Ti(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 ji(e,n){if(e.kind==="error"){y.info({detail:Ve(e.error),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 Ai(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 Fi(e){return e.flatMap(n=>{let t=n.label.split("#")[0]??n.label;return n.actions.map(()=>t)})}async function Mi({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:$i(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:Li(e,i.captureEvents),stepSources:l}).catch(u=>{y.warn({error:u},"explore finding report failed")}),!0)}function $i(e){return e==="data-rule"?"dataRule":e==="page-rule"?"pageRule":e}function Li(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 Ui(e,n){return n.flatMap(t=>{let r=e[t.idx];return r==null?[]:[{actions:[...r.nav,...r.steps].map(o=>Je(o.action)),label:`${r.test}#${String(r.index)}`}]})}function Oi(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 Ni from"path";import{randomUUID as Di}from"crypto";async function Kd({cwd:e,onReady:n,signal:t,step:r,target:o}){let i=hn(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 _i(u,o);return d.kind!=="ok"?d:(await Ke({lockfile:u,onReady:n,options:qi(s),runId:`teleport-${Di()}`,sequence:d.sequence,stopAfterStep:r,test:d.test},t)).match(c=>({kind:"done",result:c}),c=>({error:c,kind:"run-failed"}))}async function _i(e,n){if(n.kind==="explore"){let r=await Xe(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:Qe(e,t.test,void 0),test:t.test}}function qi(e){return{baseUrl:e.appUrl,engineUrl:e.engineUrl,fixturesDir:Ni.join(e.cwd,$),generate:I,headed:!0,secret:e.webhookSecret,tunnelAuth:e.tunnelAuth}}export{zi as a,ea as b,B as c,wt as d,V as e,$ as f,T as g,ln as h,ge as i,O as j,j as k,wa as l,K as m,Pa as n,Ca as o,Ta as p,La as q,he as r,pn as s,yn as t,hn as u,xn as v,Se as w,Ya as x,ee as y,et as z,Il as A,Pl as B,Cl as C,Eo as D,Nl as E,Ps as F,Cs as G,Tn as H,Ts as I,js as J,As as K,Fs as L,Ms as M,An as N,Fn as O,Mn as P,$n as Q,Ln as R,Bl as S,zl as T,Jl as U,Kl as V,Ql as W,Gl as X,Xl as Y,Yl as Z,Zl as _,ed as $,nd as aa,ns as ba,ts as ca,xe as da,rs as ea,bn as fa,Rs as ga,Ee as ha,Yr as ia,Rl as ja,Uo as ka,ri as la,Ei as ma,fi as na,mi as oa,gi as pa,Ri as qa,Pi as ra,Kd as sa};
@@ -1,2 +0,0 @@
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-ITI53W73.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};
@@ -1,102 +0,0 @@
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-SM6N6ZSY.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-ITI53W73.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};
@@ -1,2 +0,0 @@
1
- #!/usr/bin/env node
2
- import{a,b}from"./chunk-RLXQYG7H.js";import"./chunk-5VRJXHWH.js";import"./chunk-IHSHBPJY.js";import"./chunk-7UWDMECF.js";export{a as TunnelProvisionFailedError,b as startDaemonTunnel};
@@ -1,2 +0,0 @@
1
- #!/usr/bin/env node
2
- import"./chunk-7UWDMECF.js";var Z={signature:"GIF",version:"89a",trailer:59,extensionIntroducer:33,applicationExtensionLabel:255,graphicControlExtensionLabel:249,imageSeparator:44,signatureSize:3,versionSize:3,globalColorTableFlagMask:128,colorResolutionMask:112,sortFlagMask:8,globalColorTableSizeMask:7,applicationIdentifierSize:8,applicationAuthCodeSize:3,disposalMethodMask:28,userInputFlagMask:2,transparentColorFlagMask:1,localColorTableFlagMask:128,interlaceFlagMask:64,idSortFlagMask:32,localColorTableSizeMask:7};function K(t=256){let e=0,o=new Uint8Array(t);return{get buffer(){return o.buffer},reset(){e=0},bytesView(){return o.subarray(0,e)},bytes(){return o.slice(0,e)},writeByte(n){r(e+1),o[e]=n,e++},writeBytes(n,a=0,i=n.length){r(e+i);for(let c=0;c<i;c++)o[e++]=n[c+a]},writeBytesView(n,a=0,i=n.byteLength){r(e+i),o.set(n.subarray(a,a+i),e),e+=i}};function r(n){var a=o.length;if(a>=n)return;var i=1024*1024;n=Math.max(n,a*(a<i?2:1.125)>>>0),a!=0&&(n=Math.max(n,256));let c=o;o=new Uint8Array(n),e>0&&o.set(c.subarray(0,e),0)}}var D=12,_=5003,$=[0,1,3,7,15,31,63,127,255,511,1023,2047,4095,8191,16383,32767,65535];function tt(t,e,o,r,n=K(512),a=new Uint8Array(256),i=new Int32Array(_),c=new Int32Array(_)){let w=i.length,u=Math.max(2,r);a.fill(0),c.fill(0),i.fill(-1);let f=0,l=0,h=u+1,B=h,y=!1,b=B,s=(1<<b)-1,A=1<<h-1,C=A+1,x=A+2,g=0,m=o[0],F=0;for(let M=w;M<65536;M*=2)++F;F=8-F,n.writeByte(u),v(A);let p=o.length;for(let M=1;M<p;M++)t:{let U=o[M],z=(U<<D)+m,k=U<<F^m;if(i[k]===z){m=c[k];break t}let R=k===0?1:w-k;for(;i[k]>=0;)if(k-=R,k<0&&(k+=w),i[k]===z){m=c[k];break t}v(m),m=U,x<1<<D?(c[k]=x++,i[k]=z):(i.fill(-1),x=A+2,y=!0,v(A))}return v(m),v(C),n.writeByte(0),n.bytesView();function v(M){for(f&=$[l],l>0?f|=M<<l:f=M,l+=b;l>=8;)a[g++]=f&255,g>=254&&(n.writeByte(g),n.writeBytesView(a,0,g),g=0),f>>=8,l-=8;if((x>s||y)&&(y?(b=B,s=(1<<b)-1,y=!1):(++b,s=b===D?1<<b:(1<<b)-1)),M==C){for(;l>0;)a[g++]=f&255,g>=254&&(n.writeByte(g),n.writeBytesView(a,0,g),g=0),f>>=8,l-=8;g>0&&(n.writeByte(g),n.writeBytesView(a,0,g),g=0)}}}var et=tt;function O(t,e,o){return t<<8&63488|e<<2&992|o>>3}function Q(t,e,o,r){return t>>4|e&240|(o&240)<<4|(r&240)<<8}function X(t,e,o){return t>>4<<8|e&240|o>>4}function V(t,e,o){return t<e?e:t>o?o:t}function q(t){return t*t}function j(t,e,o){var r=0,n=1e100;let a=t[e],i=a.cnt,c=a.ac,w=a.rc,u=a.gc,f=a.bc;for(var l=a.fw;l!=0;l=t[l].fw){let B=t[l],y=B.cnt,b=i*y/(i+y);if(!(b>=n)){var h=0;o&&(h+=b*q(B.ac-c),h>=n)||(h+=b*q(B.rc-w),!(h>=n)&&(h+=b*q(B.gc-u),!(h>=n)&&(h+=b*q(B.bc-f),!(h>=n)&&(n=h,r=l))))}}a.err=n,a.nn=r}function H(){return{ac:0,rc:0,gc:0,bc:0,cnt:0,nn:0,fw:0,bk:0,tm:0,mtm:0,err:0}}function rt(t,e){let o=e==="rgb444"?4096:65536,r=new Array(o),n=t.length;if(e==="rgba4444")for(let a=0;a<n;++a){let i=t[a],c=i>>24&255,w=i>>16&255,u=i>>8&255,f=i&255,l=Q(f,u,w,c),h=l in r?r[l]:r[l]=H();h.rc+=f,h.gc+=u,h.bc+=w,h.ac+=c,h.cnt++}else if(e==="rgb444")for(let a=0;a<n;++a){let i=t[a],c=i>>16&255,w=i>>8&255,u=i&255,f=X(u,w,c),l=f in r?r[f]:r[f]=H();l.rc+=u,l.gc+=w,l.bc+=c,l.cnt++}else for(let a=0;a<n;++a){let i=t[a],c=i>>16&255,w=i>>8&255,u=i&255,f=O(u,w,c),l=f in r?r[f]:r[f]=H();l.rc+=u,l.gc+=w,l.bc+=c,l.cnt++}return r}function bt(t,e,o={}){let{format:r="rgb565",clearAlpha:n=!0,clearAlphaColor:a=0,clearAlphaThreshold:i=0,oneBitAlpha:c=!1}=o;if(!t||!t.buffer)throw new Error("quantize() expected RGBA Uint8Array data");if(!(t instanceof Uint8Array)&&!(t instanceof Uint8ClampedArray))throw new Error("quantize() expected RGBA Uint8Array data");let w=new Uint32Array(t.buffer),u=o.useSqrt!==!1,f=r==="rgba4444",l=rt(w,r),h=l.length,B=h-1,y=new Uint32Array(h+1);for(var b=0,s=0;s<h;++s){let d=l[s];if(d!=null){var A=1/d.cnt;f&&(d.ac*=A),d.rc*=A,d.gc*=A,d.bc*=A,l[b++]=d}}q(e)/b<.022&&(u=!1);for(var s=0;s<b-1;++s)l[s].fw=s+1,l[s+1].bk=s,u&&(l[s].cnt=Math.sqrt(l[s].cnt));u&&(l[s].cnt=Math.sqrt(l[s].cnt));var C,x,g;for(s=0;s<b;++s){j(l,s,!1);var m=l[s].err;for(x=++y[0];x>1&&(g=x>>1,!(l[C=y[g]].err<=m));x=g)y[x]=C;y[x]=s}var F=b-e;for(s=0;s<F;){for(var p;;){var v=y[1];if(p=l[v],p.tm>=p.mtm&&l[p.nn].mtm<=p.tm)break;p.mtm==B?v=y[1]=y[y[0]--]:(j(l,v,!1),p.tm=s);var m=l[v].err;for(x=1;(g=x+x)<=y[0]&&(g<y[0]&&l[y[g]].err>l[y[g+1]].err&&g++,!(m<=l[C=y[g]].err));x=g)y[x]=C;y[x]=v}var M=l[p.nn],U=p.cnt,z=M.cnt,A=1/(U+z);f&&(p.ac=A*(U*p.ac+z*M.ac)),p.rc=A*(U*p.rc+z*M.rc),p.gc=A*(U*p.gc+z*M.gc),p.bc=A*(U*p.bc+z*M.bc),p.cnt+=M.cnt,p.mtm=++s,l[M.bk].fw=M.fw,l[M.fw].bk=M.bk,M.mtm=B}let k=[];var R=0;for(s=0;;++R){let d=V(Math.round(l[s].rc),0,255),P=V(Math.round(l[s].gc),0,255),L=V(Math.round(l[s].bc),0,255),S=255;f&&(S=V(Math.round(l[s].ac),0,255),c&&(S=S<=(typeof c=="number"?c:127)?0:255),n&&S<=i&&(d=P=L=a,S=0));let W=f?[d,P,L,S]:[d,P,L];if(nt(k,W)||k.push(W),(s=l[s].fw)==0)break}return k}function nt(t,e){for(let o=0;o<t.length;o++){let r=t[o],n=r[0]===e[0]&&r[1]===e[1]&&r[2]===e[2],a=r.length>=4&&e.length>=4?r[3]===e[3]:!0;if(n&&a)return!0}return!1}function T(t,e){var o=0,r;for(r=0;r<t.length;r++){let n=t[r]-e[r];o+=n*n}return o}function G(t,e){return e>1?Math.round(t/e)*e:t}function gt(t,{roundRGB:e=5,roundAlpha:o=10,oneBitAlpha:r=null}={}){let n=new Uint32Array(t.buffer);for(let a=0;a<n.length;a++){let i=n[a],c=i>>24&255,w=i>>16&255,u=i>>8&255,f=i&255;c=G(c,o),r&&(c=c<=(typeof r=="number"?r:127)?0:255),f=G(f,e),u=G(u,e),w=G(w,e),n[a]=c<<24|w<<16|u<<8|f<<0}}function pt(t,e,o="rgb565"){if(!t||!t.buffer)throw new Error("quantize() expected RGBA Uint8Array data");if(!(t instanceof Uint8Array)&&!(t instanceof Uint8ClampedArray))throw new Error("quantize() expected RGBA Uint8Array data");if(e.length>256)throw new Error("applyPalette() only works with 256 colors or less");let r=new Uint32Array(t.buffer),n=r.length,a=o==="rgb444"?4096:65536,i=new Uint8Array(n),c=new Array(a),w=o==="rgba4444";if(o==="rgba4444")for(let u=0;u<n;u++){let f=r[u],l=f>>24&255,h=f>>16&255,B=f>>8&255,y=f&255,b=Q(y,B,h,l),s=b in c?c[b]:c[b]=at(y,B,h,l,e);i[u]=s}else{let u=o==="rgb444"?X:O;for(let f=0;f<n;f++){let l=r[f],h=l>>16&255,B=l>>8&255,y=l&255,b=u(y,B,h),s=b in c?c[b]:c[b]=it(y,B,h,e);i[f]=s}}return i}function at(t,e,o,r,n){let a=0,i=1e100;for(let c=0;c<n.length;c++){let w=n[c],u=w[3],f=I(u-r);if(f>i)continue;let l=w[0];if(f+=I(l-t),f>i)continue;let h=w[1];if(f+=I(h-e),f>i)continue;let B=w[2];f+=I(B-o),!(f>i)&&(i=f,a=c)}return a}function it(t,e,o,r){let n=0,a=1e100;for(let i=0;i<r.length;i++){let c=r[i],w=c[0],u=I(w-t);if(u>a)continue;let f=c[1];if(u+=I(f-e),u>a)continue;let l=c[2];u+=I(l-o),!(u>a)&&(a=u,n=i)}return n}function Bt(t,e,o=5){if(!t.length||!e.length)return;let r=t.map(i=>i.slice(0,3)),n=o*o,a=t[0].length;for(let i=0;i<e.length;i++){let c=e[i];c.length<a?c=[c[0],c[1],c[2],255]:c.length>a?c=c.slice(0,3):c=c.slice();let w=ot(r,c.slice(0,3),T),u=w[0],f=w[1];f>0&&f<=n&&(t[u]=c)}}function I(t){return t*t}function lt(t,e,o=T){let r=1/0,n=-1;for(let a=0;a<t.length;a++){let i=t[a],c=o(e,i);c<r&&(r=c,n=a)}return n}function ot(t,e,o=T){let r=1/0,n=-1;for(let a=0;a<t.length;a++){let i=t[a],c=o(e,i);c<r&&(r=c,n=a)}return[n,r]}function At(t,e,o=T){return t[lt(t,e,o)]}function ct(t={}){let{initialCapacity:e=4096,auto:o=!0}=t,r=K(e),n=5003,a=new Uint8Array(256),i=new Int32Array(n),c=new Int32Array(n),w=!1;return{reset(){r.reset(),w=!1},finish(){r.writeByte(Z.trailer)},bytes(){return r.bytes()},bytesView(){return r.bytesView()},get buffer(){return r.buffer},get stream(){return r},writeHeader:u,writeFrame(f,l,h,B={}){let{transparent:y=!1,transparentIndex:b=0,delay:s=0,palette:A=null,repeat:C=0,colorDepth:x=8,dispose:g=-1}=B,m=!1;if(o?w||(m=!0,u(),w=!0):m=!!B.first,l=Math.max(0,Math.floor(l)),h=Math.max(0,Math.floor(h)),m){if(!A)throw new Error("First frame must include a { palette } option");ut(r,l,h,A,x),J(r,A),C>=0&&st(r,C)}let F=Math.round(s/10);ft(r,g,F,y,b);let p=!!A&&!m;wt(r,l,h,p?A:null),p&&J(r,A),ht(r,f,l,h,x,a,i,c)}};function u(){Y(r,"GIF89a")}}function ft(t,e,o,r,n){t.writeByte(33),t.writeByte(249),t.writeByte(4),n<0&&(n=0,r=!1);var a,i;r?(a=1,i=2):(a=0,i=0),e>=0&&(i=e&7),i<<=2,t.writeByte(0|i|0|a),E(t,o),t.writeByte(n||0),t.writeByte(0)}function ut(t,e,o,r,n=8){let a=1,i=0,c=N(r.length)-1,w=a<<7|n-1<<4|i<<3|c;E(t,e),E(t,o),t.writeBytes([w,0,0])}function st(t,e){t.writeByte(33),t.writeByte(255),t.writeByte(11),Y(t,"NETSCAPE2.0"),t.writeByte(3),t.writeByte(1),E(t,e),t.writeByte(0)}function J(t,e){let o=1<<N(e.length);for(let r=0;r<o;r++){let n=[0,0,0];r<e.length&&(n=e[r]),t.writeByte(n[0]),t.writeByte(n[1]),t.writeByte(n[2])}}function wt(t,e,o,r){if(t.writeByte(44),E(t,0),E(t,0),E(t,e),E(t,o),r){let n=0,a=0,i=N(r.length)-1;t.writeByte(128|n|a|0|i)}else t.writeByte(0)}function ht(t,e,o,r,n=8,a,i,c){et(o,r,e,n,t,a,i,c)}function E(t,e){t.writeByte(e&255),t.writeByte(e>>8&255)}function Y(t,e){for(var o=0;o<e.length;o++)t.writeByte(e.charCodeAt(o))}function N(t){return Math.max(Math.ceil(Math.log2(t)),1)}var Mt=ct;export{ct as GIFEncoder,pt as applyPalette,Mt as default,At as nearestColor,lt as nearestColorIndex,ot as nearestColorIndexWithDistance,gt as prequantize,bt as quantize,Bt as snapColorsToPalette};