ripplo 0.15.1 → 0.16.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +18 -142
- package/dist/index.js +56 -643
- package/package.json +7 -43
- package/dist/assets/browser-trace.js +0 -1
- package/dist/assets/rrweb.js +0 -54
- package/dist/capture-worker.js +0 -13892
- package/dist/chunk-47LLHHJH.js +0 -9
- package/dist/chunk-5HFJIZLI.js +0 -4
- package/dist/chunk-5JXP37ET.js +0 -4
- package/dist/chunk-5PICILBD.js +0 -9
- package/dist/chunk-7WZ3VIUU.js +0 -4
- package/dist/chunk-ANAQCK5G.js +0 -4
- package/dist/chunk-AUXGLJ3J.js +0 -8
- package/dist/chunk-AXROBTLA.js +0 -4
- package/dist/chunk-BGY5F3IU.js +0 -5
- package/dist/chunk-BTIQ5H3K.js +0 -4
- package/dist/chunk-C7SV6AR2.js +0 -48
- package/dist/chunk-CI6273ZU.js +0 -107
- package/dist/chunk-EVEITUJH.js +0 -4
- package/dist/chunk-EYILCSW6.js +0 -11
- package/dist/chunk-F4UCCW7Q.js +0 -83
- package/dist/chunk-FEHVIHVA.js +0 -5
- package/dist/chunk-G6J2WIHJ.js +0 -4
- package/dist/chunk-HEOMRXZE.js +0 -4
- package/dist/chunk-IRT6UHD3.js +0 -61
- package/dist/chunk-IVW5DUE4.js +0 -360
- package/dist/chunk-JJ4QQPAV.js +0 -4
- package/dist/chunk-JPXTGKSB.js +0 -7
- package/dist/chunk-JS3DLVVI.js +0 -4
- package/dist/chunk-KH4QH23U.js +0 -4
- package/dist/chunk-KL6TIUNF.js +0 -4
- package/dist/chunk-KMZ3L5YA.js +0 -4
- package/dist/chunk-KOKEEAEF.js +0 -6
- package/dist/chunk-KOZTQJBB.js +0 -56
- package/dist/chunk-MHNGR6M7.js +0 -4
- package/dist/chunk-NNH3YVVO.js +0 -4
- package/dist/chunk-NUBMOTH6.js +0 -6
- package/dist/chunk-O4A5UISQ.js +0 -6
- package/dist/chunk-OQ6KNYPG.js +0 -4
- package/dist/chunk-PYDYI3AA.js +0 -23
- package/dist/chunk-QQ6VKZ6A.js +0 -5
- package/dist/chunk-QSKOYBDO.js +0 -8
- package/dist/chunk-R4ZTRVDQ.js +0 -4
- package/dist/chunk-RIASQHPG.js +0 -4
- package/dist/chunk-RXLDAR2J.js +0 -13
- package/dist/chunk-SXVWB7TZ.js +0 -6
- package/dist/chunk-T6WA2F3S.js +0 -16
- package/dist/chunk-XAMVRZJH.js +0 -23
- package/dist/chunk-XPOOWIRL.js +0 -4
- package/dist/cli-error-7LCAN3Z5.js +0 -4
- package/dist/compile-write-Y5III4OM.js +0 -4
- package/dist/daemon-6UYMYGPI.js +0 -175
- package/dist/daemon-EITBDEP7.js +0 -4
- package/dist/daemon-lock-RPKO5SNE.js +0 -4
- package/dist/dsl-loader-ASNZDV7E.js +0 -4
- package/dist/dsl-typecheck-worker.js +0 -6
- package/dist/exit-plan-gate-44YWEKYS.js +0 -4
- package/dist/hook.js +0 -5
- package/dist/plan-reminder-6VWOS6HD.js +0 -4
- package/dist/post-edit-A5Y26UH5.js +0 -4
- package/dist/post-edit-analyze-2SBNWX6Y.js +0 -4
- package/dist/post-edit-flag-stubs-I43B5QPO.js +0 -4
- package/dist/pre-bash-run-gate-CDFNAIK3.js +0 -4
- package/dist/pre-edit-HJVNM7U5.js +0 -4
- package/dist/pre-edit-ripplo-skill-gate-A6ETC3QN.js +0 -4
- package/dist/pre-edit-scope-gate-HNIQ7KOQ.js +0 -4
- package/dist/pre-edit-watch-gate-G6BVWIDL.js +0 -4
- package/dist/prompt-submit-OXYVNXHK.js +0 -4
- package/dist/scope-reminder-A6GVTTVE.js +0 -4
- package/dist/session-preamble-IZQPIWST.js +0 -4
- package/dist/status-XUIBJXNP.js +0 -4
- package/dist/stop-enforce-BP6IIW3D.js +0 -64
- package/dist/tasks-reminder-TDWPD3KV.js +0 -4
- package/dist/track-skill-load-SXSDMHFO.js +0 -4
- package/dist/track-skill-prompt-7N4TQAD2.js +0 -4
package/dist/index.js
CHANGED
|
@@ -1,669 +1,82 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import {
|
|
3
|
-
const require = globalThis.require ?? __ripploCreateRequire(import.meta.url);
|
|
4
|
-
|
|
5
|
-
query AuthViewer {
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
`);
|
|
12
|
-
`)
|
|
13
|
-
`)
|
|
2
|
+
import {createRequire}from'node:module';import*as mt from'zod';import {z}from'zod';import {exec}from'child_process';import {err,ok}from'neverthrow';import xe,{readFileSync,existsSync}from'fs';import ir from'path';import Cs,{homedir}from'os';import {Agent,RetryAgent,setGlobalDispatcher}from'undici';import nc from'yargs';import {hideBin}from'yargs/helpers';import {graphql}from'gql.tada';import {gunzipSync}from'zlib';import {readFile,mkdir,writeFile}from'fs/promises';import {createRequire as createRequire$1}from'module';import {fileURLToPath}from'url';globalThis.require ?? createRequire(import.meta.url);
|
|
3
|
+
var He=z.enum(["gt","gte","lt","lte"]),mr=z.union([z.string(),z.number(),z.boolean(),z.null()]),N=z.json();z.record(z.string().min(1),N);var O=z.object({path:z.array(z.string().min(1)),source:z.string().min(1)}),xo=z.enum(["observed","setup"]),fr=z.intersection(O,z.object({ownership:xo}));var j=z.lazy(()=>z.discriminatedUnion("kind",[z.object({kind:z.literal("value"),value:mr}),z.object({kind:z.literal("reference"),path:z.array(z.string().min(1)).min(1),record:z.string().min(1)}),z.object({kind:z.literal("path"),selector:O}),z.object({kind:z.literal("count"),selection:ve}),z.object({kind:z.literal("add"),left:j,right:j}),z.object({dividend:j,divisor:j,kind:z.literal("divide")}),z.object({kind:z.literal("concat"),values:z.array(j).min(1)}),z.object({kind:z.literal("invert"),value:j}),z.object({kind:z.literal("before")}),z.object({kind:z.literal("after")})])),ne=z.lazy(()=>z.discriminatedUnion("kind",[z.object({kind:z.literal("equals"),left:j,right:j}),z.object({kind:z.literal("compare"),left:j,op:He,right:j}),z.object({kind:z.literal("text"),left:j,op:z.enum(["contains","startsWith"]),right:j}),z.object({kind:z.literal("exists"),selection:ve}),z.object({kind:z.literal("not"),relation:ne}),z.object({kind:z.literal("and"),relations:z.array(ne).min(1)}),z.object({kind:z.literal("or"),relations:z.array(ne).min(1)})])),ve=z.lazy(()=>z.object({alias:z.string().min(1),relation:ne.nullable(),selector:O}));z.enum(["fast","slow","async"]);var Ot=z.object({ref:z.string().min(1)}),Tt=z.union([z.string(),z.number(),z.boolean()]);var yr=z.object({template:z.array(z.union([z.string(),Ot,j])).min(1)}),we=z.lazy(()=>z.union([Ot,Tt,yr,z.null()])),vo=z.lazy(()=>z.discriminatedUnion("kind",[z.object({kind:z.literal("not"),value:we}),z.object({kind:z.literal("compare"),op:He,value:we}),z.object({kind:z.literal("anyOf"),values:z.array(we).min(1)}),z.object({kind:z.literal("contains"),value:ce}),z.object({kind:z.literal("startsWith"),value:ce})])),wo=z.lazy(()=>z.object({entity:z.string().min(1),where:z.record(z.string().min(1),ko).default({})})),Ao=z.lazy(()=>z.object({field:z.string().min(1),kind:z.literal("within"),selection:wo})),ko=z.lazy(()=>z.union([we,Ao,vo]));z.lazy(()=>z.union([ce,z.object({kind:z.literal("contains"),value:ce}),z.object({kind:z.literal("startsWith"),value:ce})]));var Io=z.union([z.literal("increased"),z.literal("decreased")]),Co=z.object({direction:z.union([Io,z.undefined()]).optional().transform(e=>e),kind:z.literal("changed")});z.union([we,Co]);var ce=z.union([z.string(),Ot,yr]);var Po=z.object({by:z.literal("role"),name:z.union([ce,z.undefined()]).optional().transform(e=>e),role:z.string().min(1)}),Lo=z.object({by:z.literal("testId"),value:ce}),No=z.object({by:z.literal("describe"),description:ce}),Do=z.object({by:z.literal("inside"),scope:z.lazy(()=>Ge),target:z.lazy(()=>Ge)}),Uo=z.object({by:z.literal("surface"),container:z.lazy(()=>Ge),overlay:z.boolean()}),Mo=z.object({by:z.literal("frame"),element:z.lazy(()=>Ge)}),Ge=z.discriminatedUnion("by",[Po,Lo,No,Do,Uo,Mo]),Ae=z.enum(["string","number","boolean"]),hr=z.enum(["strict","eventual"]),jo=z.enum(["companyName","email","fullName","id","slug","url","word"]),$o=z.object({kind:z.literal("pattern"),maxLength:z.number().int().positive().optional(),minLength:z.number().int().nonnegative().optional(),name:z.string().min(1),pattern:z.string().min(1),refine:z.string().min(1).optional(),sampler:jo.optional()}),Vo=z.object({kind:z.literal("enum"),name:z.string().min(1),values:z.array(Tt).min(1)}),Fo=z.object({kind:z.literal("number"),max:z.number().int(),min:z.number().int(),name:z.string().min(1)}),Bo=z.object({kind:z.literal("boolean"),name:z.string().min(1)}),zo=z.object({kind:z.literal("datetime"),maxOffsetDays:z.number().int(),minOffsetDays:z.number().int(),name:z.string().min(1)}),gr=z.discriminatedUnion("kind",[$o,Vo,Fo,Bo,zo]);var qo=z.object({consistency:hr.default("strict"),optional:z.boolean(),type:Ae,valueSpace:z.string().min(1).optional()}),Sr=z.enum(["backend","client"]);z.object({description:z.string().optional(),identity:z.array(z.string().min(1)).min(1),identityKind:z.enum(["surrogate","natural"]),name:z.string().min(1),principal:z.boolean().default(false),props:z.record(z.string().min(1),qo),source:Sr.default("backend")});z.object({consistency:hr.default("strict"),default:Tt,description:z.string().optional(),name:z.string().min(1),source:Sr.default("backend"),type:Ae,valueSpace:z.string().min(1).optional()});z.enum(["url","title","viewport"]);z.enum(["mobile","desktop"]);var Ke=z.object({path:z.array(z.string().min(1)),recordKeyIndex:z.number().int().nonnegative().nullable(),source:z.string().min(1)});var Wo=z.record(z.string(),N),Yo=z.object({module:z.string().min(1)}),Ho=z.object({implementation:Yo.optional(),jsonSchema:Wo,name:z.string().min(1),schemaHash:z.string().regex(/^[0-9a-f]{64}$/u)});z.object({binding:Ho,datetimePaths:z.array(Ke).default([]),eventualPaths:z.array(Ke).default([]),recordPaths:z.array(fr).default([]),setupPaths:z.array(Ke).default([])});var Er=z.discriminatedUnion("kind",[z.object({kind:z.literal("equals"),selector:O,value:N}),z.object({kind:z.literal("absent-path"),selector:O}),z.object({alias:z.string().min(1),fields:z.record(z.string().min(1),N),kind:z.literal("required-record"),selector:O}),z.object({fields:z.record(z.string().min(1),N),kind:z.literal("absent-record"),selector:O}),z.object({kind:z.literal("closed-record"),rows:z.array(N),selector:O}),z.object({kind:z.literal("relation"),label:z.string().min(1),relation:ne})]);var Go=z.discriminatedUnion("kind",[z.object({kind:z.literal("transform"),relation:ne}),z.object({kind:z.literal("value"),value:N}),z.object({kind:z.literal("reference"),path:z.array(z.string().min(1)).min(1),record:z.string().min(1)})]),Ko=z.discriminatedUnion("kind",[z.object({kind:z.literal("null")}),z.object({kind:z.literal("scalar"),nullable:z.boolean(),type:Ae})]),br=z.object({domain:Ko,kind:z.literal("state-ref"),path:z.array(z.string().min(1)).min(1)}),Jo=z.discriminatedUnion("kind",[z.object({kind:z.literal("absent")}),z.object({kind:z.literal("generated")}),br,z.object({kind:z.literal("value"),value:N}),z.object({kind:z.literal("reference"),path:z.array(z.string().min(1)).min(1),record:z.string().min(1)})]),Rr=z.discriminatedUnion("kind",[z.object({kind:z.literal("set"),selector:O,value:N}),z.object({kind:z.literal("transform"),relation:ne,selector:O}),z.object({kind:z.literal("create-path"),selector:O,value:N}),z.object({kind:z.literal("delete-path"),selector:O}),z.object({as:z.string().min(1),fields:z.record(z.string().min(1),Jo),kind:z.literal("create-record"),selector:O}),z.object({kind:z.literal("delete-selected-records"),selection:ve,selector:O}),z.object({changes:z.record(z.string().min(1),Go),kind:z.literal("update-selected-records"),selection:ve,selector:O})]);z.object({constraints:z.array(Er),effects:z.array(Rr)});var oe=z.discriminatedUnion("present",[z.object({present:z.literal(false)}),z.object({present:z.literal(true),value:N})]),xt=z.discriminatedUnion("kind",[z.object({actual:oe,constraint:Er,kind:z.literal("constraint"),selector:O}),z.object({actual:oe,before:oe,effect:Rr,kind:z.literal("effect"),selector:O,targetKeys:z.array(z.string())}),z.object({actual:oe,before:oe,kind:z.literal("unexpected-change"),selector:O})]);z.object({mismatches:z.array(xt),requiredStateHolds:z.boolean()});var Zo=z.discriminatedUnion("kind",[z.object({kind:z.literal("state")}),z.object({kind:z.literal("record"),path:z.array(z.string().min(1)).min(1)})]),ue=z.lazy(()=>z.discriminatedUnion("kind",[z.object({fields:z.record(z.string().min(1),ue),kind:z.literal("object")}),z.object({items:z.array(ue),kind:z.literal("array")}),z.object({kind:z.literal("generate"),name:z.string().min(1),nullable:z.boolean(),space:gr,type:Ae}),z.object({kind:z.literal("reference"),operation:z.string().min(1),path:z.array(z.string().min(1))}),br,z.object({kind:z.literal("value"),value:N})]));var Xo=z.object({id:z.string().min(1),input:ue,optional:z.boolean(),source:z.string().min(1),target:Zo});var Qo=z.discriminatedUnion("kind",[z.object({kind:z.literal("equals"),selector:O,value:ue}),z.object({kind:z.literal("absent-path"),selector:O}),z.object({alias:z.string().min(1),kind:z.literal("optional-path"),operation:z.string().min(1),selector:O,value:ue}),z.object({alias:z.string().min(1),fields:z.record(z.string().min(1),ue),kind:z.literal("required-record"),selector:O}),z.object({alias:z.string().min(1),fields:z.record(z.string().min(1),ue),kind:z.literal("optional-record"),selector:O}),z.object({fields:z.record(z.string().min(1),ue),kind:z.literal("absent-record"),selector:O}),z.object({kind:z.literal("closed-record"),operations:z.array(z.string().min(1)),selector:O}),z.object({kind:z.literal("relation"),label:z.string().min(1),relation:ne})]);z.object({constraints:z.array(Qo),operations:z.array(Xo)});var ea=z.object({actual:z.string(),expected:z.string(),log:z.array(z.string()),name:z.string(),timeoutMs:z.number().int().nullable()}),Je=z.object({container:z.string().nullable(),name:z.string().nullable(),role:z.string().nullable(),tag:z.string(),visible:z.boolean()}),Ie={expectedRole:z.string().nullable()},ta=z.discriminatedUnion("kind",[z.object({...Ie,kind:z.literal("absent")}),z.object({...Ie,kind:z.literal("hidden"),matches:z.array(Je).min(1)}),z.object({...Ie,kind:z.literal("ambiguous"),matches:z.array(Je).min(2)}),z.object({...Ie,kind:z.literal("text-elsewhere"),match:Je,partial:z.boolean()}),z.object({...Ie,actualName:z.string(),kind:z.literal("name-differs"),match:Je})]),J=z.object({ariaSnapshot:z.string().nullable(),matcher:ea.nullable(),message:z.string(),miss:ta.nullable()});var vt=z.enum(["create-session","teardown"]),ra=z.enum(["create","read","setup"]),_r=[z.object({detail:z.string(),kind:z.literal("authentication-http"),operation:vt,status:z.number().int()}),z.object({code:z.string().nullable(),kind:z.literal("authentication-network"),message:z.string(),operation:vt}),z.object({kind:z.literal("app-not-ready"),timeoutMs:z.number().int()}),z.object({kind:z.literal("authentication-response"),message:z.string(),operation:vt}),z.object({kind:z.literal("binding-failed"),message:z.string(),operation:ra}),z.object({kind:z.literal("state-setup"),message:z.string()}),z.object({fields:z.record(z.string().min(1),N),kind:z.literal("read-only-record-unmatched"),selector:O}),z.object({kind:z.literal("driver-launch"),message:z.string()}),z.object({kind:z.literal("state-effect-reference"),path:z.array(z.string()),record:z.string()}),z.object({kind:z.literal("run-failed"),message:z.string()}),z.object({kind:z.literal("model-preparation"),message:z.string()}),z.object({kind:z.literal("workflow-plan"),reason:z.enum(["required-state-unsatisfied","no-effect","unresolvable","contradictory-expectations","action-relationship-unmet","invalid-state-effect"]),stepIndex:z.number().int().nonnegative(),test:z.string().min(1)}),z.object({kind:z.literal("page-read"),message:z.string()}),z.object({kind:z.literal("state-mismatch"),mismatches:z.array(xt).min(1)}),z.object({kind:z.literal("aborted")})],Or=z.discriminatedUnion("kind",[..._r]);z.discriminatedUnion("kind",[..._r,z.object({action:z.string(),failure:J,kind:z.literal("action-failed")}),z.object({failure:J,kind:z.literal("check-failed")})]);var w=z.lazy(()=>z.discriminatedUnion("by",[z.object({by:z.literal("role"),name:z.union([z.string(),z.undefined()]).optional().transform(e=>e),role:z.string()}),z.object({by:z.literal("testId"),value:z.string()}),z.object({by:z.literal("describe"),description:z.string().min(1)}),z.object({by:z.literal("inside"),scope:w,target:w}),z.object({by:z.literal("surface"),container:w,overlay:z.boolean()}),z.object({by:z.literal("frame"),element:w})])),Tr=z.union([z.string(),z.number(),z.boolean(),z.null()]),Ze=z.discriminatedUnion("kind",[z.object({kind:z.literal("goto"),url:z.string()}),z.object({kind:z.literal("fill"),locator:w,value:Tr}),z.object({kind:z.literal("clear"),locator:w}),z.object({kind:z.literal("click"),locator:w}),z.object({kind:z.literal("dblclick"),locator:w}),z.object({kind:z.literal("select"),locator:w,value:Tr}),z.object({kind:z.literal("check"),locator:w}),z.object({kind:z.literal("uncheck"),locator:w}),z.object({kind:z.literal("hover"),locator:w}),z.object({files:z.array(z.string().min(1)).min(1),kind:z.literal("upload"),locator:w}),z.object({key:z.string().min(1),kind:z.literal("press"),locator:w.optional()}),z.object({kind:z.literal("drag"),source:w,target:w})]);var na=z.object({__codec:z.string().min(1),data:z.unknown(),version:z.number().int().positive()}),Qe=class extends Error{codec;currentVersion;gotVersion;constructor(t){super(`Unsupported ${t.codec} version ${String(t.gotVersion)} (current ${String(t.currentVersion)}). Upgrade Ripplo or rebuild with a compatible CLI.`),this.name="CodecVersionError",this.codec=t.codec,this.currentVersion=t.currentVersion,this.gotVersion=t.gotVersion;}},wt=class extends Error{constructor(t){super(`Codec mismatch: expected "${t.expected}", got "${t.got}"`),this.name="CodecMismatchError";}};function xr({name:e,schema:t,steps:r=[]}){let n=r.length+1;return {currentVersion:n,name:e,decode:o=>oa({name:e,raw:o,schema:t,steps:r}),encode:o=>({__codec:e,data:o,version:n})}}function oa({name:e,raw:t,schema:r,steps:n}){let o=n.length+1,s=na.parse(t);if(s.__codec!==e)throw new wt({expected:e,got:s.__codec});if(s.version>o)throw new Qe({codec:e,currentVersion:o,gotVersion:s.version});let c=n.slice(s.version-1);if(c.some(d=>d.kind==="semantic"))throw new Qe({codec:e,currentVersion:o,gotVersion:s.version});let p=c.reduce((d,f)=>f.kind==="reshape"?f.migrate(d):d,s.data);return r.parse(p)}var At={boundAlias:void 0,braced:false};function et(e,t=At){return e.kind==="not"?`not ${et(e.relation,t)}`:e.kind==="and"||e.kind==="or"?e.relations.map(r=>et(r,t)).join(` ${e.kind} `):e.kind==="exists"?`${vr(e.selection,t)} exists`:e.kind==="text"?`${U(e.left,t)} ${e.op} ${U(e.right,t)}`:e.kind==="compare"?`${U(e.left,t)} is ${e.op} ${U(e.right,t)}`:`${U(e.left,t)} is ${U(e.right,t)}`}function vr(e,t=At){let r=e.selector.path.join("."),n=r.length===0?e.selector.source:r;return e.relation==null?`records in ${n}`:`records in ${n} where ${et(e.relation,{...t,boundAlias:e.alias})}`}function U(e,t=At){switch(e.kind){case "value":return JSON.stringify(e.value);case "reference":{if(e.record===t.boundAlias)return e.path.join(".");let r=`${e.record}.${e.path.join(".")}`;return t.braced?`{{${r}}}`:r}case "path":return aa(e);case "count":return `count of ${vr(e.selection,t)}`;case "add":return `${U(e.left,t)} + ${U(e.right,t)}`;case "divide":return `${U(e.dividend,t)} / ${U(e.divisor,t)}`;case "concat":return e.values.map(r=>U(r,t)).join(" + ");case "invert":return `opposite of ${U(e.value,t)}`;case "after":case "before":return e.kind}}function aa(e){let t=e.selector.path.join(".");return t.length===0?e.selector.source:t}function ae(e){return typeof e=="string"?e:"ref"in e?`{{${e.ref}}}`:e.template.map(t=>ia(t)).join("")}function ia(e){return typeof e=="string"?e:"ref"in e?`{{${e.ref}}}`:`{{${U(e)}}}`}function W(e){if(e.by==="testId")return `testId=${ae(e.value)}`;if(e.by==="describe")return `"${ae(e.description)}"`;if(e.by==="inside")return `${W(e.scope)} \u25B8 ${W(e.target)}`;if(e.by==="surface")return W(e.container);if(e.by==="frame")return `frame ${W(e.element)}`;let t=e.name==null?"":ae(e.name);return `${e.role} ${t}`.trim()}var sa=["visible","unobstructed","disabled","enabled","focused","checked","expanded","pressed"],la=["value","text"],It=z.enum(sa),Ct=z.enum(la),ca=z.discriminatedUnion("kind",[z.object({checkId:z.string(),kind:z.literal("step")}),z.object({factId:z.string(),kind:z.literal("fact")}),z.object({kind:z.literal("dataRule"),ruleId:z.string()})]),wr=z.discriminatedUnion("kind",[z.object({kind:z.literal("wrongScalar"),observed:z.string().nullable()})]),ua=z.enum(["increased","decreased"]),Ce={entity:z.string(),key:z.string()},Ir=z.discriminatedUnion("kind",[z.object({...Ce,expected:z.string(),field:z.string(),kind:z.literal("wrongValue"),observed:z.string()}),z.object({...Ce,kind:z.literal("missingRow")}),z.object({...Ce,kind:z.literal("unexpectedRow")}),z.object({...Ce,kind:z.literal("unexpectedlyDeleted")}),z.object({...Ce,direction:ua.nullable(),field:z.string(),from:z.string(),kind:z.literal("neverChanged"),observed:z.string()}),z.object({entity:z.string(),expected:z.number().int(),kind:z.literal("wrongCount"),observed:z.number().int()})]),kt=z.object({stepIndex:z.number().int(),testRef:z.string()}).nullable(),da=z.discriminatedUnion("kind",[...Ir.options,z.object({declaredAt:kt,expected:z.string().nullable(),kind:z.literal("wrongScalar"),observed:z.string().nullable(),subject:z.string(),subjectKey:z.string()}),z.object({checkKind:It,declaredAt:kt,kind:z.literal("wrongElementState"),observed:z.boolean(),subject:z.string(),subjectKey:z.string()}),z.object({checkKind:Ct,declaredAt:kt,expected:z.string().nullable(),kind:z.literal("wrongElementContent"),observed:z.string().nullable(),subject:z.string(),subjectKey:z.string()})]);function de(e){return z.discriminatedUnion("kind",[z.object({kind:z.literal("passed")}),z.object({kind:z.literal("failed"),reason:e})])}function Pt(e,t){return z.discriminatedUnion("kind",[z.object({kind:z.literal("passed"),observed:t.optional()}),z.object({kind:z.literal("failed"),observed:t.optional(),reason:e})])}var pa=z.array(z.record(z.string().min(1),oe)),Y={ephemeral:z.boolean(),kind:z.literal("check"),ordinal:z.number().int().optional(),origin:ca,rrwebIds:z.array(z.number()),source:z.literal("verifier"),stepIndex:z.number().int(),timeNanos:z.string(),waitedMs:z.number()},Ar=z.enum(["variable","path","query","hash","title","viewport","element"]),kr=z.enum(["exact","contains","startsWith"]),ma=z.discriminatedUnion("shape",[z.object({...Y,checkKind:It,family:z.literal("element"),negated:z.boolean(),outcome:de(J),shape:z.literal("legacy"),subject:z.string()}),z.object({...Y,checkKind:It,family:z.literal("element"),locator:w,negated:z.boolean(),outcome:de(J),shape:z.literal("concrete")})]),fa=z.discriminatedUnion("shape",[z.object({...Y,checkKind:Ct,expected:z.string(),family:z.literal("content"),match:kr,negated:z.boolean(),outcome:de(J),shape:z.literal("legacy"),subject:z.string()}),z.object({...Y,checkKind:Ct,expected:z.string(),family:z.literal("content"),locator:w,match:kr,negated:z.boolean(),outcome:de(J),shape:z.literal("concrete")})]),ya=z.discriminatedUnion("shape",[z.object({...Y,expected:z.string().nullable(),family:z.literal("scalar"),negated:z.boolean(),outcome:Pt(wr,oe),shape:z.literal("legacy"),subject:z.string(),subjectKey:z.string(),subjectKind:Ar}),z.object({...Y,expected:z.string().nullable(),family:z.literal("scalar"),locator:w.nullable(),negated:z.boolean(),outcome:Pt(wr,oe),shape:z.literal("concrete"),subject:z.string().nullable(),subjectKey:z.string(),subjectKind:Ar})]),ha=z.discriminatedUnion("shape",[z.object({...Y,actionKind:z.string(),family:z.literal("action"),outcome:de(J),shape:z.literal("legacy"),subject:z.string(),value:z.string().nullable()}),z.object({...Y,action:Ze,family:z.literal("action"),outcome:de(J),shape:z.literal("concrete")})]),Cr=z.discriminatedUnion("family",[ma,fa,ya,z.object({...Y,assertion:z.enum(["created","updated","deleted","exists","absent","count"]),entity:z.string(),family:z.literal("state"),outcome:Pt(Ir,pa),subject:z.string()}),z.object({...Y,family:z.literal("frame"),outcome:de(da)}),ha,z.object({...Y,family:z.literal("dataRule"),outcome:de(z.discriminatedUnion("kind",[z.object({kind:z.literal("violated")})])),rule:z.string()})]),Pr=z.object({error:Or,kind:z.literal("stepError"),source:z.literal("verifier"),stepIndex:z.number().int(),timeNanos:z.string()});var ga=["unspecified","internal","server","client","producer","consumer"],Sa=["unset","ok","error"],Ea=z.looseObject({node:z.looseObject({id:z.number()}).optional(),parentId:z.number().nullable().optional()}),ba=z.looseObject({data:z.looseObject({adds:z.array(Ea).optional(),attributes:z.array(z.looseObject({id:z.number()})).optional(),removes:z.array(z.looseObject({id:z.number()})).optional(),source:z.number().optional(),texts:z.array(z.looseObject({id:z.number()})).optional()}).optional(),timestamp:z.number(),type:z.number()}),Z=z.string(),Ra=z.object({action:z.string(),kind:z.literal("action"),source:z.literal("test"),target:z.string().optional(),timeNanos:Z,value:z.string().optional()}),_a=z.object({event:ba,kind:z.literal("rrweb"),rrwebType:z.string(),source:z.literal("browser"),timeNanos:Z}),Oa=z.object({durationMs:z.number().optional(),kind:z.literal("network"),method:z.string(),requestBody:z.string().optional(),resourceType:z.string(),responseBody:z.string().optional(),source:z.literal("browser"),spanId:z.string().optional(),status:z.number(),timeNanos:Z,traceId:z.string().optional(),url:z.string()}),Ta=z.object({kind:z.literal("console"),level:z.string(),source:z.literal("browser"),text:z.string(),timeNanos:Z}),xa=z.discriminatedUnion("problem",[z.object({message:z.string(),problem:z.literal("page-error"),stack:z.string().optional()}),z.object({method:z.string(),path:z.string(),problem:z.literal("server-error"),status:z.number()}),z.object({method:z.string(),path:z.string(),problem:z.literal("request-failed"),reason:z.string()})]),va=z.object({count:z.number().int().min(1),detail:xa,kind:z.literal("health"),source:z.literal("browser"),stepIndex:z.number().int().min(0).optional(),timeNanos:Z}),wa=z.object({clientVersion:z.string(),kind:z.literal("meta"),source:z.literal("capture"),timeNanos:Z}),Aa=z.object({kind:z.literal("notice"),message:z.string(),source:z.literal("capture"),timeNanos:Z}),ka=z.discriminatedUnion("kind",[z.object({kind:z.literal("unrunnable"),reason:z.enum(["requiredStateUnsatisfied","noEffect","unresolvable","contradictoryExpectations","actionRelationshipUnmet","invalidStateEffect"]),unmet:z.string().nullable()}),z.object({action:z.string(),kind:z.literal("impossibleAction"),subject:z.string()}),z.object({declaredIndex:z.number(),kind:z.literal("liftVisibility"),subject:z.string(),visibleIndex:z.number()})]),Ia=z.object({kind:z.literal("finding"),payload:ka,source:z.literal("verifier"),step:z.string(),stepIndex:z.number(),timeNanos:Z}),Ca=z.object({changed:z.boolean(),field:z.string(),generated:z.boolean(),value:z.string().nullable()}),Pa=z.object({entity:z.string(),fields:z.array(Ca),key:z.string(),label:z.string(),status:z.enum(["present","created","deleted"])}),La=z.object({changed:z.boolean(),generated:z.boolean(),name:z.string(),value:z.string().nullable()}),Lr={duration:z.number(),executedBranches:z.array(z.string()).default([]),kind:z.literal("step"),nodeType:z.string(),pageUrl:z.string().nullable(),recordingEndMs:z.number(),recordingStartMs:z.number(),source:z.literal("verifier"),sourceTest:z.string().nullable(),stateBindings:z.record(z.string(),z.json()).default({}),stateRows:z.array(Pa),stateSingletons:z.array(La),status:z.enum(["failed","passed","pending"]).optional(),stepIndex:z.number(),timeNanos:Z},Na=z.discriminatedUnion("shape",[z.object({...Lr,shape:z.literal("legacy"),title:z.string()}),z.object({...Lr,action:Ze.nullable(),shape:z.literal("concrete")})]),Dr=z.object({attributes:z.record(z.string(),z.string()),durationMs:z.number(),kind:z.literal("span"),name:z.string(),parentSpanId:z.string().optional(),source:z.literal("server"),spanId:z.string(),spanKind:z.enum(ga),status:z.object({code:z.enum(Sa),message:z.string().optional()}),timeNanos:Z,traceId:z.string()}),Da=z.discriminatedUnion("kind",[Ra,_a,Oa,Ta,va,wa,Aa,Ia,Cr,Pr,Dr,Na]),Ur=xr({name:"ripplo-behavior",schema:z.array(z.unknown()),steps:[{kind:"semantic"},{kind:"semantic"},{kind:"reshape",migrate:e=>e},{kind:"reshape",migrate:Ma},{kind:"semantic"},{kind:"reshape",migrate:Fa},{kind:"reshape",migrate:qa},{kind:"reshape",migrate:e=>e}]}),Ua=z.object({by:z.string().optional(),count:z.number().optional(),kind:z.string(),message:z.string().optional(),observed:z.unknown().optional()});function Ma(e){return Array.isArray(e)?e.map(t=>ja(t)):e}var he=z.record(z.string(),N);function ja(e){let t=he.safeParse(e);if(!t.success)return e;let r=he.safeParse(t.data.outcome);if(!r.success)return e;let n=Ua.safeParse(r.data.reason);return n.success?{...t.data,outcome:{...r.data,reason:$a(n.data)}}:e}function $a(e){return {ariaSnapshot:null,matcher:null,message:Ya(e),miss:null}}var Va=z.object({ariaSnapshot:z.unknown(),matcher:z.unknown(),message:z.string()});function Fa(e){return Array.isArray(e)?e.map(t=>Ba(t)):e}function Ba(e){let t=he.safeParse(e);if(!t.success)return e;let r=he.safeParse(t.data.outcome);if(!r.success)return e;let n=r.data.reason,o=Va.safeParse(n);return !o.success||typeof n=="object"&&n!=null&&"miss"in n?e:{...t.data,outcome:{...r.data,reason:{...o.data,miss:null}}}}var za=z.object({kind:z.enum(["wrongScalar","wrongElementState","wrongElementContent"]),subjectKey:z.string()});function qa(e){return Array.isArray(e)?e.map(t=>Wa(t)):e}function Wa(e){let t=he.safeParse(e);if(!t.success||t.data.family!=="frame")return e;let r=he.safeParse(t.data.outcome);if(!r.success)return e;let n=he.safeParse(r.data.reason);return !n.success||!za.safeParse(n.data).success||"declaredAt"in n.data?e:{...t.data,outcome:{...r.data,reason:{...n.data,declaredAt:null}}}}function Ya(e){return e.kind==="notFound"?"expected visible, matched 0 elements":e.kind==="multipleMatches"?`matched ${String(e.count??0)} elements`:e.kind==="covered"?`covered by ${e.by??"another element"}`:e.kind==="notPossible"?"the action is not possible on this element":e.kind==="unclassified"?e.message??"":JSON.stringify(e)}var Ha=z.object({__codec:z.string().min(1),version:z.number().int().positive()});function Pe(e){let t=e.split(`
|
|
4
|
+
`).filter(p=>p.length>0),r=t[0],n=r==null?null:Nr(r),o=Ha.parse(n),s=t.slice(1).flatMap(p=>{let d=Nr(p);return d==null?[]:[d]});return Ur.decode({...o,data:s}).flatMap(p=>{let d=Da.safeParse(p);return d.success?[d.data]:[]})}function ge(e){return Number(BigInt(e)/1000000n)}function Nr(e){try{return JSON.parse(e)}catch{return null}}function Se(e){return e.shape==="legacy"?e.subject:e.family==="action"?Mr(e.action):e.family==="scalar"?Ga(e):W(e.locator)}function Ga(e){if(e.locator!=null)return W(e.locator);if(e.subject==null)throw new Error(`Concrete scalar check "${e.subjectKey}" has neither locator nor subject`);return e.subject}function Mr(e){return e.kind==="goto"?e.url:e.kind==="drag"?`${W(e.source)} to ${W(e.target)}`:e.kind==="press"?e.locator==null?e.key:W(e.locator):W(e.locator)}function jr(e){return e.shape==="legacy"?e.actionKind:e.action.kind}function Lt(e){if(e.outcome.kind!=="passed")switch(e.family){case "element":return Ka(e,e.outcome.reason);case "content":return Ja(e,e.outcome.reason);case "scalar":return Za(e,e.outcome.reason.observed);case "state":return Nt(e.outcome.reason);case "frame":return $r(e.outcome.reason);case "action":return `Could not ${jr(e)} ${Se(e)} \u2014 ${Dt(e.outcome.reason)}`;case "dataRule":return `Data rule ${e.rule} broke \u2014 a referenced row went missing`}}function Ka(e,t){let r=Se(e),n=li(e.negated,e.checkKind),o=zr(t);return o==null?`${r} was expected ${n} \u2014 ${Dt(t)}`:`${r} was expected ${n} but was ${o}`}function Ja(e,t){let r=Se(e),n=e.negated?"not ":"",o=`${r} was expected ${n}to show ${ie(e.expected)}`,s=zr(t);return s==null?`${o} \u2014 ${Dt(t)}`:`${o} but showed ${ie(s)}`}function Za(e,t){let r=Se(e),n=pe(e.expected);return e.negated?`${r} was expected not to be ${n} but still was`:`${r} was expected to be ${n} but was ${pe(t)}`}function $r(e){return `undeclared change: ${Vr(e)}. ${ei(e)}`}function Nt(e){switch(e.kind){case "wrongValue":return `${e.entity}.${e.field} for row ${e.key} was declared ${e.expected} but is ${e.observed}. If the app is right, fix the declared value on this step. If ${e.expected} is right, this is an app bug`;case "missingRow":return `no ${e.entity} row matching ${e.key} exists, but this step declares creates(...) for it. If the app is right, remove the creates(...) effect. If the row should exist, this is an app bug`;case "unexpectedRow":return `a ${e.entity} row ${e.key} appeared that no effect on this step declares. If the app is right, add creates(...) for it to this step. If nothing should have been created, this is a cascade bug`;case "unexpectedlyDeleted":return `the ${e.entity} row ${e.key} was deleted, but no effect on this step deletes it. If the app is right, add deletes(...) for it to this step. If the row should have stayed, this is a cascade bug`;case "neverChanged":return `${e.entity}.${e.field} for row ${e.key} was declared to ${Xa(e.direction)} from ${e.from} but stayed at ${e.observed}. If the app is right, remove that effect from this step. If it should have changed, this is an app bug`;case "wrongCount":return `${e.entity} was declared to have ${String(e.expected)} rows but has ${String(e.observed)}. If the app is right, fix the declared effects on this step. If the count is wrong, this is an app bug`}}function Xa(e){return e==="increased"?"increase":e==="decreased"?"decrease":"change"}function Vr(e){switch(e.kind){case "wrongElementState":return `${e.subject} is ${Qa(e)}`;case "wrongElementContent":return `${e.subject} ${e.checkKind==="text"?"shows":"holds"} ${pe(e.observed)}, not ${pe(e.expected)}`;case "wrongScalar":return `${e.subject} became ${pe(e.observed)}, not ${pe(e.expected)}`;case "wrongValue":case "missingRow":case "unexpectedRow":case "unexpectedlyDeleted":case "neverChanged":case "wrongCount":return Nt(e)}}function Qa(e){return e.checkKind==="visible"&&!e.observed?"no longer visible":`now ${ci(e.observed,e.checkKind)}`}function ei(e){switch(e.kind){case "wrongElementState":case "wrongElementContent":case "wrongScalar":return `${ti(e)}If the app is right, add .expect(${ni(e)}) to this step. If it should have stayed, this is an app bug.`;case "wrongValue":case "missingRow":case "unexpectedRow":case "unexpectedlyDeleted":case "neverChanged":case "wrongCount":return ""}}function ti(e){let{declaredAt:t}=e;return t==null?"":`Step ${String(t.stepIndex+1)} of ${t.testRef} declared ${ri(e)} and no later step declared it changed. `}function ri(e){switch(e.kind){case "wrongElementState":return Fr({checkKind:e.checkKind,on:!e.observed,subject:e.subject});case "wrongElementContent":return `${e.checkKind}(${e.subject}, ${qr(e.expected)})`;case "wrongScalar":return `${e.subject} = ${pe(e.expected)}`}}function ni(e){switch(e.kind){case "wrongElementState":return Fr({checkKind:e.checkKind,on:e.observed,subject:e.subject});case "wrongElementContent":return `${e.checkKind}(${e.subject}, ${qr(e.observed)})`;case "wrongScalar":return `${e.subject} = ${pe(e.observed)}`}}function Fr({checkKind:e,on:t,subject:r}){let n=`${e}(${r})`;return t?n:`not(${n})`}function oi(e){let t=e.expectedRole??"element";switch(e.kind){case "absent":return "nothing on the page has that role and name. The element is missing or was renamed \u2014 check the frame at this step.";case "hidden":return ai(e.matches);case "ambiguous":return `it matched ${String(e.matches.length)} visible elements: ${Br(e.matches)}. Scope it with inside(<container>) or use a name only one of them has.`;case "text-elsewhere":return ii(e,t);case "name-differs":return `the ${t} is on the page but its accessible name is ${ie(e.actualName)}. Use ${t}(${ie(e.actualName)}).`}}function ai(e){let t=e[0];return e.length===1&&t!=null?`it exists (${t.tag}, ${t.role??"no role"}) but is hidden. If an earlier step should reveal it, declare that reveal there \u2014 otherwise this is an app bug.`:`${String(e.length)} matches exist but all are hidden: ${Br(e)}. If an earlier step should reveal it, declare that reveal there \u2014 otherwise this is an app bug.`}function ii(e,t){let{match:r}=e;return e.partial?`no ${t} has that name \u2014 the closest text is ${ie(r.name??"")} in a <${r.tag}>. Match it with contains(...) or use the full name.`:r.role==null?`no ${t} has that name \u2014 the text is on the page in a <${r.tag}> with no role. Use text(${ie(r.name??"")}) or give the element a ${t} role in the app.`:`no ${t} has that name \u2014 the text is a ${r.role} (<${r.tag}>). Change the locator to ${r.role}(${ie(r.name??"")}).`}function Br(e){return e.map(t=>si(t)).join(", ")}function si(e){let t=`<${e.tag}> ${e.role??"no role"} ${ie(e.name??"")}`;return e.container==null?t:`${t} in ${e.container}`}function zr(e){return e.miss!=null||e.matcher==null||e.matcher.actual.length===0?null:e.matcher.actual}function Dt(e){if(e.miss!=null)return oi(e.miss);let t=e.message.split(`
|
|
5
|
+
`).find(r=>r.trim().length>0);if(t==null)throw new Error("Failure carries no message");return t.trim()}function li(e,t){return `${e?"not ":""}${t}`}function ci(e,t){return `${e?"":"not "}${t}`}function qr(e){return e==null?"absent":ie(e)}function pe(e){return e??"absent"}function ie(e){return JSON.stringify(e)}function Wr(e){return e===null?"null":typeof e=="string"||typeof e=="number"||typeof e=="boolean"?String(e):"ref"in e?`{{${e.ref}}}`:e.template.map(t=>typeof t=="string"?t:"ref"in t?`{{${t.ref}}}`:`{{${U(t)}}}`).join("")}function Ut(e){let t=_e(e.kind);if(e.kind==="goto")return [t,fi(ae(e.url))];if(e.kind==="fill"||e.kind==="select")return [t,...se(e.locator),_e("with"),Le(`"${Wr(e.value)}"`)];if(e.kind==="press"){let r=e.locator==null?[]:se(e.locator);return [t,...r,Le(`"${e.key}"`)]}return e.kind==="drag"?[t,...se(e.source),_e("to"),...se(e.target)]:[t,...se(e.locator)]}var _e=e=>({kind:"g",text:e}),Yr=e=>({kind:"label",text:e}),Le=e=>({kind:"screen",text:e}),V={display:void 0,name:"label"},T={display:void 0,name:"screen"},ui={alert:T,alertdialog:T,banner:T,button:V,cell:T,checkbox:V,columnheader:T,combobox:V,complementary:T,contentinfo:T,dialog:T,form:T,grid:T,group:T,heading:T,img:T,link:V,list:T,listbox:T,listitem:T,main:T,menu:T,menuitem:{display:"menu item",name:"label"},menuitemcheckbox:{display:"menu item checkbox",name:"label"},menuitemradio:{display:"menu item radio",name:"label"},navigation:T,option:V,progressbar:T,radio:V,radiogroup:T,region:T,row:T,searchbox:V,slider:V,spinbutton:V,status:T,switch:V,tab:V,table:T,tablist:T,tabpanel:T,textbox:V,toolbar:T,treeitem:V};var di=new Map(Object.entries(ui));function pi(e){return di.get(e)??T}function mi(e){let t=pi(e.role),r=_e(t.display??e.role);if(e.name==null)return [r];let n=ae(e.name),o=t.name==="label"?Yr(n):Le(`"${n}"`);return [r,o]}function se(e){return e.by==="role"?mi(e):e.by==="testId"?[Yr(ae(e.value))]:e.by==="describe"?[Le(`"${ae(e.description)}"`)]:e.by==="surface"?se(e.container):e.by==="frame"?[_e("frame"),...se(e.element)]:[...se(e.target),_e("in"),...se(e.scope)]}function fi(e){return e.startsWith("/")?{kind:"path",text:e}:Le(`"${e}"`)}var Mt=["*, *::before, *::after { animation-duration: 0s !important; animation-delay: 0s !important; transition-duration: 0s !important; transition-delay: 0s !important; }","noscript { display: none !important; }"];var jt=null;function $t(e){jt=e;}function Hr(){return jt==null?{}:{"x-ripplo-client-version":jt}}var yi=15e3,hi=3,gi=300,tt=class extends Error{detail;serverUrl;constructor({detail:t,serverUrl:r}){super(`Failed to connect to Ripplo server at ${r}. Check the server is running and reachable. Details: ${t}`),this.name="GqlConnectionError",this.detail=t,this.serverUrl=r;}},Ne=class extends Error{errors;constructor(t){super(t.map(r=>r.message).join(", ")),this.name="GqlRequestError",this.errors=t;}};function Vt(e){if(e instanceof Ne)return e.errors[0]?.extensions?.code}var Si={attempts:hi,timeoutMs:yi};async function Ee(e){return Ei({headers:{},params:e,policy:Si})}async function Ei(e){let{headers:t,params:r,policy:n}=e,{print:o}=await import('graphql'),s=o(r.document),c=JSON.stringify({query:s,variables:r.variables}),p=`${r.config.ripploServerUrl}/graphql`,d=await bi({init:{body:c,headers:{...t,Authorization:`Bearer ${r.config.token}`,"Content-Type":"application/json",...Hr()},method:"POST"},policy:n,serverUrl:r.config.ripploServerUrl,url:p}),f=await Oi({res:d,url:p});if(!Ti(f))throw new Error("Invalid GraphQL response");if(xi(f))throw new Ne(f.errors);if(f.data==null)throw new Error("No data returned from server");return f.data}async function bi({init:e,policy:t,serverUrl:r,url:n}){let o=1,s=await Gr({init:e,timeoutMs:t.timeoutMs,url:n});for(;s.retryable&&o<t.attempts;)await _i(Ri(o)),o+=1,s=await Gr({init:e,timeoutMs:t.timeoutMs,url:n});let{response:c}=s;if(c!=null&&c.status<500)return c;throw new tt({detail:c==null?s.detail:`server returned status ${String(c.status)}`,serverUrl:r})}async function Gr({init:e,timeoutMs:t,url:r}){try{let n=await fetch(r,{...e,signal:AbortSignal.timeout(t)});return {detail:"",response:n,retryable:n.status>=500}}catch(n){return {detail:n instanceof Error?n.message:String(n),response:void 0,retryable:true}}}function Ri(e){return gi*3**(e-1)*(.5+Math.random())}function _i(e){return new Promise(t=>{setTimeout(t,e);})}async function Oi({res:e,url:t}){let r=await e.text();if(r.length===0)throw new Error(`Empty response from Ripplo server at ${t} (status ${String(e.status)}). The server may have restarted or the request was rejected before a body was sent.`);try{return JSON.parse(r)}catch{throw new Error(`Non-JSON response from Ripplo server at ${t} (status ${String(e.status)}): ${r.slice(0,200)}`)}}function Ti(e){return typeof e=="object"&&e!=null&&("data"in e||"errors"in e)}function xi(e){return Array.isArray(e.errors)&&e.errors.length>0}var rt=Symbol.for("better-auth:broadcast-channel"),vi=()=>Math.floor(Date.now()/1e3),wi=class{listeners=new Set;name;constructor(e="better-auth.message"){this.name=e;}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e);}}post(e){if(!(typeof window>"u"))try{localStorage.setItem(this.name,JSON.stringify({...e,timestamp:vi()}));}catch{}}setup(){if(typeof window>"u"||typeof window.addEventListener>"u")return ()=>{};let e=t=>{if(t.key!==this.name)return;let r=JSON.parse(t.newValue??"{}");r?.event!=="session"||!r?.data||this.listeners.forEach(n=>n(r));};return window.addEventListener("storage",e),()=>{window.removeEventListener("storage",e);}}};function De(e="better-auth.message"){return globalThis[rt]||(globalThis[rt]=new wi(e)),globalThis[rt]}var nt=Symbol.for("better-auth:focus-manager"),Ai=class{listeners=new Set;subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e);}}setFocused(e){this.listeners.forEach(t=>t(e));}setup(){if(typeof window>"u"||typeof document>"u"||typeof window.addEventListener>"u")return ()=>{};let e=()=>{document.visibilityState==="visible"&&this.setFocused(true);};return document.addEventListener("visibilitychange",e,false),()=>{document.removeEventListener("visibilitychange",e,false);}}};function Ft(){return globalThis[nt]||(globalThis[nt]=new Ai),globalThis[nt]}var ot=Symbol.for("better-auth:online-manager"),ki=class{listeners=new Set;isOnline=typeof navigator<"u"?navigator.onLine:true;subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e);}}setOnline(e){this.isOnline=e,this.listeners.forEach(t=>t(e));}setup(){if(typeof window>"u"||typeof window.addEventListener>"u")return ()=>{};let e=()=>this.setOnline(true),t=()=>this.setOnline(false);return window.addEventListener("online",e,false),window.addEventListener("offline",t,false),()=>{window.removeEventListener("online",e,false),window.removeEventListener("offline",t,false);}}};function at(){return globalThis[ot]||(globalThis[ot]=new ki),globalThis[ot]}var Ii={proto:/"(?:_|\\u0{2}5[Ff]){2}(?:p|\\u0{2}70)(?:r|\\u0{2}72)(?:o|\\u0{2}6[Ff])(?:t|\\u0{2}74)(?:o|\\u0{2}6[Ff])(?:_|\\u0{2}5[Ff]){2}"\s*:/,constructor:/"(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)"\s*:/,protoShort:/"__proto__"\s*:/,constructorShort:/"constructor"\s*:/},Ci=/^\s*["[{]|^\s*-?\d{1,16}(\.\d{1,17})?([Ee][+-]?\d+)?\s*$/,Kr={true:true,false:false,null:null,undefined:void 0,nan:NaN,infinity:Number.POSITIVE_INFINITY,"-infinity":Number.NEGATIVE_INFINITY},Pi=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.(\d{1,7}))?(?:Z|([+-])(\d{2}):(\d{2}))$/;function Li(e){return e instanceof Date&&!isNaN(e.getTime())}function Ni(e){let t=Pi.exec(e);if(!t)return null;let[,r,n,o,s,c,p,d,f,m,E]=t,b=new Date(Date.UTC(parseInt(r,10),parseInt(n,10)-1,parseInt(o,10),parseInt(s,10),parseInt(c,10),parseInt(p,10),d?parseInt(d.padEnd(3,"0"),10):0));if(f){let k=(parseInt(m,10)*60+parseInt(E,10))*(f==="+"?-1:1);b.setUTCMinutes(b.getUTCMinutes()+k);}return Li(b)?b:null}function Di(e,t={}){let{strict:r=false,warnings:n=false,reviver:o,parseDates:s=true}=t;if(typeof e!="string")return e;let c=e.trim();if(c.length>0&&c[0]==='"'&&c.endsWith('"')&&!c.slice(1,-1).includes('"'))return c.slice(1,-1);let p=c.toLowerCase();if(p.length<=9&&p in Kr)return Kr[p];if(!Ci.test(c)){if(r)throw new SyntaxError("[better-json] Invalid JSON");return e}if(Object.entries(Ii).some(([d,f])=>{let m=f.test(c);return m&&n&&console.warn(`[better-json] Detected potential prototype pollution attempt using ${d} pattern`),m})&&r)throw new Error("[better-json] Potential prototype pollution attempt detected");try{return JSON.parse(c,(f,m)=>{if(f==="__proto__"||f==="constructor"&&m&&typeof m=="object"&&"prototype"in m){n&&console.warn(`[better-json] Dropping "${f}" key to prevent prototype pollution`);return}if(s&&typeof m=="string"){let E=Ni(m);if(E)return E}return o?o(f,m):m})}catch(d){if(r)throw d;return e}}function Bt(e,t={strict:true}){return Di(e,t)}var Ue=Symbol("clean");var H=[],me=0,it=4,Me=e=>{let t=[],r={get(){return r.lc||r.listen(()=>{})(),r.value},lc:0,listen(n){return r.lc=t.push(n),()=>{for(let s=me+it;s<H.length;)H[s]===n?H.splice(s,it):s+=it;let o=t.indexOf(n);~o&&(t.splice(o,1),--r.lc||r.off());}},notify(n,o){let s=!H.length;for(let c of t)H.push(c,r.value,n,o);if(s){for(me=0;me<H.length;me+=it)H[me](H[me+1],H[me+2],H[me+3]);H.length=0;}},off(){},set(n){let o=r.value;o!==n&&(r.value=n,r.notify(o));},subscribe(n){let o=r.listen(n);return n(r.value),o},value:e};return process.env.NODE_ENV!=="production"&&(r[Ue]=()=>{t=[],r.lc=0,r.off();}),r};var Mi=5,Oe=6,st=10,ji=(e,t,r,n)=>(e.events=e.events||{},e.events[r+st]||(e.events[r+st]=n(o=>{e.events[r].reduceRight((s,c)=>(c(s),s),{shared:{},...o});})),e.events[r]=e.events[r]||[],e.events[r].push(t),()=>{let o=e.events[r],s=o.indexOf(t);o.splice(s,1),o.length||(delete e.events[r],e.events[r+st](),delete e.events[r+st]);});var Jr=1e3,je=(e,t)=>ji(e,n=>{let o=t(n);o&&e.events[Oe].push(o);},Mi,n=>{let o=e.listen;e.listen=(...c)=>(!e.lc&&!e.active&&(e.active=true,n()),o(...c));let s=e.off;if(e.events[Oe]=[],e.off=()=>{s(),setTimeout(()=>{if(e.active&&!e.lc){e.active=false;for(let c of e.events[Oe])c();e.events[Oe]=[];}},Jr);},process.env.NODE_ENV!=="production"){let c=e[Ue];e[Ue]=()=>{for(let p of e.events[Oe])p();e.events[Oe]=[],e.active=false,c();};}return ()=>{e.listen=o,e.off=s;}});var $i=()=>typeof window>"u",lt=(e,t,r,n)=>{let o=Me({data:null,error:null,isPending:true,isRefetching:false,refetch:p=>s(p)}),s=async p=>new Promise(d=>{let f=typeof n=="function"?n({data:o.get().data,error:o.get().error,isPending:o.get().isPending}):n;r(t,{...f,query:{...f?.query,...p?.query},async onSuccess(m){o.set({data:m.data,error:null,isPending:false,isRefetching:false,refetch:o.value.refetch}),await f?.onSuccess?.(m);},async onError(m){let{request:E}=m,b=typeof E.retry=="number"?E.retry:E.retry?.attempts,k=E.retryAttempt||0;if(b&&k<b)return;let C=m.error.status===401;o.set({error:m.error,data:C?null:o.get().data,isPending:false,isRefetching:false,refetch:o.value.refetch}),await f?.onError?.(m);},async onRequest(m){let E=o.get();o.set({isPending:E.data===null,data:E.data,error:null,isRefetching:true,refetch:o.value.refetch}),await f?.onRequest?.(m);}}).catch(m=>{o.set({error:m,data:o.get().data,isPending:false,isRefetching:false,refetch:o.value.refetch});}).finally(()=>{d(void 0);});});e=Array.isArray(e)?e:[e];let c=false;for(let p of e)p.subscribe(async()=>{$i()||(c?await s():je(o,()=>{let d=setTimeout(async()=>{c||(await s(),c=true);},0);return ()=>{o.off(),p.off(),clearTimeout(d);}}));});return o};var Te=()=>Math.floor(Date.now()/1e3);function Zr(e){return typeof e=="object"&&e!==null&&"data"in e&&"error"in e?e:{data:e,error:null}}var Vi=5;function zt(e){let{sessionAtom:t,sessionSignal:r,$fetch:n,options:o={}}=e,s=o.sessionOptions?.refetchInterval??0,c=o.sessionOptions?.refetchOnWindowFocus??true,p=o.sessionOptions?.refetchWhenOffline??false,d={lastSync:0,lastSessionRequest:0,cachedSession:void 0},f=()=>p||at().isOnline,m=P=>{if(!f())return;if(P?.event==="storage"){d.lastSync=Te(),r.set(!r.get());return}let $=t.get(),v=()=>{d.lastSessionRequest=Te(),n("/get-session").then(async S=>{let{data:R,error:ye}=Zr(S);if(R?.needsRefresh)try{let Re=await n("/get-session",{method:"POST"});({data:R,error:ye}=Zr(Re));}catch{}let Rt=R?.session&&R?.user?R:null;t.set({...$,data:Rt,error:ye}),d.lastSync=Te(),r.set(!r.get());}).catch(()=>{});};if(P?.event==="poll"){v();return}if(P?.event==="visibilitychange"){if(Te()-d.lastSessionRequest<Vi)return;d.lastSessionRequest=Te();}if(P?.event==="visibilitychange"){v();return}($?.data===null||$?.data===void 0)&&(d.lastSync=Te(),r.set(!r.get()));},E=P=>{De().post({event:"session",data:{trigger:P},clientId:Math.random().toString(36).substring(7)});},b=()=>{s&&s>0&&(d.pollInterval=setInterval(()=>{t.get()?.data&&m({event:"poll"});},s*1e3));},k=()=>{d.unsubscribeBroadcast=De().subscribe(()=>{m({event:"storage"});});},C=()=>{c&&(d.unsubscribeFocus=Ft().subscribe(()=>{m({event:"visibilitychange"});}));},le=()=>{d.unsubscribeOnline=at().subscribe(P=>{P&&m({event:"visibilitychange"});});};return {init:()=>{b(),k(),C(),le(),De().setup(),Ft().setup(),at().setup();},cleanup:()=>{d.pollInterval&&(clearInterval(d.pollInterval),d.pollInterval=void 0),d.unsubscribeBroadcast&&(d.unsubscribeBroadcast(),d.unsubscribeBroadcast=void 0),d.unsubscribeFocus&&(d.unsubscribeFocus(),d.unsubscribeFocus=void 0),d.unsubscribeOnline&&(d.unsubscribeOnline(),d.unsubscribeOnline=void 0),d.lastSync=0,d.lastSessionRequest=0,d.cachedSession=void 0;},triggerRefetch:m,broadcastSessionUpdate:E}}var ct=Object.create(null),$e=e=>globalThis.process?.env||globalThis.Deno?.env.toObject()||globalThis.__env__||(e?ct:globalThis),M=new Proxy(ct,{get(e,t){return $e()[t]??ct[t]},has(e,t){return t in $e()||t in ct},set(e,t,r){let n=$e(true);return n[t]=r,true},deleteProperty(e,t){if(!t)return false;let r=$e(true);return delete r[t],true},ownKeys(){let e=$e(true);return Object.keys(e)}});typeof process<"u"&&process.env&&process.env.NODE_ENV||"";function x(e,t){return typeof process<"u"&&process.env?process.env[e]??t:typeof Deno<"u"?Deno.env.get(e)??t:typeof Bun<"u"?Bun.env[e]??t:t}var Ve=1,I=4,X=8,F=24,Xr={eterm:I,cons25:I,console:I,cygwin:I,dtterm:I,gnome:I,hurd:I,jfbterm:I,konsole:I,kterm:I,mlterm:I,mosh:F,putty:I,st:I,"rxvt-unicode-24bit":F,terminator:F,"xterm-kitty":F},zi=new Map(Object.entries({APPVEYOR:X,BUILDKITE:X,CIRCLECI:F,DRONE:X,GITEA_ACTIONS:F,GITHUB_ACTIONS:F,GITLAB_CI:X,TRAVIS:X})),qi=[/ansi/,/color/,/linux/,/direct/,/^con[0-9]*x[0-9]/,/^rxvt/,/^screen/,/^xterm/,/^vt100/,/^vt220/];function qt(){if(x("FORCE_COLOR")!==void 0)switch(x("FORCE_COLOR")){case "":case "1":case "true":return I;case "2":return X;case "3":return F;default:return Ve}if(x("NODE_DISABLE_COLORS")!==void 0&&x("NODE_DISABLE_COLORS")!==""||x("NO_COLOR")!==void 0&&x("NO_COLOR")!==""||x("TERM")==="dumb")return Ve;if(x("TMUX"))return F;if("TF_BUILD"in M&&"AGENT_NAME"in M)return I;if("CI"in M){for(let{0:e,1:t}of zi)if(e in M)return t;return x("CI_NAME")==="codeship"?X:Ve}if("TEAMCITY_VERSION"in M)return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.exec(x("TEAMCITY_VERSION"))!==null?I:Ve;switch(x("TERM_PROGRAM")){case "iTerm.app":return !x("TERM_PROGRAM_VERSION")||/^[0-2]\./.exec(x("TERM_PROGRAM_VERSION"))!==null?X:F;case "HyperTerm":case "MacTerm":return F;case "Apple_Terminal":return X}if(x("COLORTERM")==="truecolor"||x("COLORTERM")==="24bit")return F;if(x("TERM")){if(/truecolor/.exec(x("TERM"))!==null)return F;if(/^xterm-256/.exec(x("TERM"))!==null)return X;let e=x("TERM").toLowerCase();if(Xr[e])return Xr[e];if(qi.some(t=>t.exec(e)!==null))return I}return x("COLORTERM")?I:Ve}var G={reset:"\x1B[0m",bright:"\x1B[1m",dim:"\x1B[2m",fg:{red:"\x1B[31m",green:"\x1B[32m",yellow:"\x1B[33m",blue:"\x1B[34m",magenta:"\x1B[35m"}},ut=["debug","info","success","warn","error"];function Qr(e,t){return ut.indexOf(t)>=ut.indexOf(e)}var Wi={info:G.fg.blue,success:G.fg.green,warn:G.fg.yellow,error:G.fg.red,debug:G.fg.magenta},Yi=(e,t,r)=>{let n=new Date().toISOString();return r?`${G.dim}${n}${G.reset} ${Wi[e]}${e.toUpperCase()}${G.reset} ${G.bright}[Better Auth]:${G.reset} ${t}`:`${n} ${e.toUpperCase()} [Better Auth]: ${t}`},en=e=>{let r="warn",n=qt()!==1,o=(s,c,p=[])=>{if(!Qr(r,s))return;let d=Yi(s,c,n);{s==="error"?console.error(d,...p):s==="warn"?console.warn(d,...p):console.log(d,...p);return}};return {...Object.fromEntries(ut.map(s=>[s,(...[c,...p])=>o(s,c,p)])),get level(){return r}}};en();function A(e){return Object.fromEntries(Object.entries(e).map(([t,r])=>[t,{code:t,message:r,toString:()=>t}]))}A({USER_NOT_FOUND:"User not found",FAILED_TO_CREATE_USER:"Failed to create user",FAILED_TO_CREATE_SESSION:"Failed to create session",FAILED_TO_UPDATE_USER:"Failed to update user",FAILED_TO_GET_SESSION:"Failed to get session",INVALID_PASSWORD:"Invalid password",INVALID_EMAIL:"Invalid email",INVALID_EMAIL_OR_PASSWORD:"Invalid email or password",INVALID_USER:"Invalid user",SOCIAL_ACCOUNT_ALREADY_LINKED:"Social account already linked",PROVIDER_NOT_FOUND:"Provider not found",INVALID_TOKEN:"Invalid token",TOKEN_EXPIRED:"Token expired",ID_TOKEN_NOT_SUPPORTED:"id_token not supported",FAILED_TO_GET_USER_INFO:"Failed to get user info",USER_EMAIL_NOT_FOUND:"User email not found",EMAIL_NOT_VERIFIED:"Email not verified",PASSWORD_TOO_SHORT:"Password too short",PASSWORD_TOO_LONG:"Password too long",USER_ALREADY_EXISTS:"User already exists.",USER_ALREADY_EXISTS_USE_ANOTHER_EMAIL:"User already exists. Use another email.",EMAIL_CAN_NOT_BE_UPDATED:"Email can not be updated",CREDENTIAL_ACCOUNT_NOT_FOUND:"Credential account not found",SESSION_EXPIRED:"Session expired. Re-authenticate to perform this action.",FAILED_TO_UNLINK_LAST_ACCOUNT:"You can't unlink your last account",ACCOUNT_NOT_FOUND:"Account not found",USER_ALREADY_HAS_PASSWORD:"User already has a password. Provide that to delete the account.",CROSS_SITE_NAVIGATION_LOGIN_BLOCKED:"Cross-site navigation login blocked. This request appears to be a CSRF attack.",VERIFICATION_EMAIL_NOT_ENABLED:"Verification email isn't enabled",EMAIL_ALREADY_VERIFIED:"Email is already verified",EMAIL_MISMATCH:"Email mismatch",SESSION_NOT_FRESH:"Session is not fresh",LINKED_ACCOUNT_ALREADY_EXISTS:"Linked account already exists",INVALID_ORIGIN:"Invalid origin",INVALID_CALLBACK_URL:"Invalid callbackURL",INVALID_REDIRECT_URL:"Invalid redirectURL",INVALID_ERROR_CALLBACK_URL:"Invalid errorCallbackURL",INVALID_NEW_USER_CALLBACK_URL:"Invalid newUserCallbackURL",MISSING_OR_NULL_ORIGIN:"Missing or null Origin",CALLBACK_URL_REQUIRED:"callbackURL is required",FAILED_TO_CREATE_VERIFICATION:"Unable to create verification",FIELD_NOT_ALLOWED:"Field not allowed to be set",ASYNC_VALIDATION_NOT_SUPPORTED:"Async validation is not supported",VALIDATION_ERROR:"Validation Error",MISSING_FIELD:"Field is required",METHOD_NOT_ALLOWED_DEFER_SESSION_REQUIRED:"POST method requires deferSessionRefresh to be enabled in session config",BODY_MUST_BE_AN_OBJECT:"Body must be an object",PASSWORD_ALREADY_SET:"User already has a password set"});var fe=class extends Error{constructor(e,t){super(e,t),this.name="BetterAuthError",this.message=e,this.stack="";}};function ts(e){try{return (new URL(e).pathname.replace(/\/+$/,"")||"/")!=="/"}catch{throw new fe(`Invalid base URL: ${e}. Please provide a valid base URL.`)}}function rs(e){try{let t=new URL(e);if(t.protocol!=="http:"&&t.protocol!=="https:")throw new fe(`Invalid base URL: ${e}. URL must include 'http://' or 'https://'`)}catch(t){throw t instanceof fe?t:new fe(`Invalid base URL: ${e}. Please provide a valid base URL.`,{cause:t})}}function Fe(e,t="/api/auth"){if(rs(e),ts(e))return e;let r=e.replace(/\/+$/,"");return !t||t==="/"?r:(t=t.startsWith("/")?t:`/${t}`,`${r}${t}`)}function rn(e,t,r,n,o){if(e)return Fe(e,t);{let p=M.BETTER_AUTH_URL||M.NEXT_PUBLIC_BETTER_AUTH_URL||M.PUBLIC_BETTER_AUTH_URL||M.NUXT_PUBLIC_BETTER_AUTH_URL||M.NUXT_PUBLIC_AUTH_URL||(M.BASE_URL!=="/"?M.BASE_URL:void 0);if(p)return Fe(p,t)}if(typeof window<"u"&&window.location)return Fe(window.location.origin,t)}var nn={id:"redirect",name:"Redirect",hooks:{onSuccess(e){if(e.data?.url&&e.data?.redirect&&typeof window<"u"&&window.location&&window.location)try{window.location.href=e.data.url;}catch{}}}};function on(e,t){let r=Me(false),n=lt(r,"/get-session",e,{method:"GET"}),o=()=>{};return je(n,()=>{let s=zt({sessionAtom:n,sessionSignal:r,$fetch:e,options:t});return s.init(),o=s.broadcastSessionUpdate,()=>{s.cleanup();}}),{session:n,$sessionSignal:r,broadcastSessionUpdate:s=>o(s)}}function Wt(e){if(e===null||typeof e!="object")return false;let t=Object.getPrototypeOf(e);return t!==null&&t!==Object.prototype&&Object.getPrototypeOf(t)!==null||Symbol.iterator in e?false:Symbol.toStringTag in e?Object.prototype.toString.call(e)==="[object Module]":true}function Yt(e,t,r=".",n){if(!Wt(t))return Yt(e,{},r,n);let o=Object.assign({},t);for(let s in e){if(s==="__proto__"||s==="constructor")continue;let c=e[s];c!=null&&(n&&n(o,s,c,r)||(Array.isArray(c)&&Array.isArray(o[s])?o[s]=[...c,...o[s]]:Wt(c)&&Wt(o[s])?o[s]=Yt(c,o[s],(r?`${r}.`:"")+s.toString(),n):o[s]=c));}return o}function Ht(e){return (...t)=>t.reduce((r,n)=>Yt(r,n,"",e),{})}var an=Ht();var os=Object.defineProperty,as=Object.defineProperties,is=Object.getOwnPropertyDescriptors,sn=Object.getOwnPropertySymbols,ss=Object.prototype.hasOwnProperty,ls=Object.prototype.propertyIsEnumerable,ln=(e,t,r)=>t in e?os(e,t,{enumerable:true,configurable:true,writable:true,value:r}):e[t]=r,K=(e,t)=>{for(var r in t||(t={}))ss.call(t,r)&&ln(e,r,t[r]);if(sn)for(var r of sn(t))ls.call(t,r)&&ln(e,r,t[r]);return e},Q=(e,t)=>as(e,is(t)),cs=class extends Error{constructor(e,t,r){super(t||e.toString(),{cause:r}),this.status=e,this.statusText=t,this.error=r,Error.captureStackTrace(this,this.constructor);}},us=async(e,t)=>{var r,n,o,s,c,p;let d=t||{},f={onRequest:[t?.onRequest],onResponse:[t?.onResponse],onSuccess:[t?.onSuccess],onError:[t?.onError],onRetry:[t?.onRetry]};if(!t||!t?.plugins)return {url:e,options:d,hooks:f};for(let m of t?.plugins||[]){if(m.init){let E=await((r=m.init)==null?void 0:r.call(m,e.toString(),t));d=E.options||d,e=E.url;}f.onRequest.push((n=m.hooks)==null?void 0:n.onRequest),f.onResponse.push((o=m.hooks)==null?void 0:o.onResponse),f.onSuccess.push((s=m.hooks)==null?void 0:s.onSuccess),f.onError.push((c=m.hooks)==null?void 0:c.onError),f.onRetry.push((p=m.hooks)==null?void 0:p.onRetry);}return {url:e,options:d,hooks:f}},cn=class{constructor(e){this.options=e;}shouldAttemptRetry(e,t){return this.options.shouldRetry?Promise.resolve(e<this.options.attempts&&this.options.shouldRetry(t)):Promise.resolve(e<this.options.attempts)}getDelay(){return this.options.delay}},ds=class{constructor(e){this.options=e;}shouldAttemptRetry(e,t){return this.options.shouldRetry?Promise.resolve(e<this.options.attempts&&this.options.shouldRetry(t)):Promise.resolve(e<this.options.attempts)}getDelay(e){return Math.min(this.options.maxDelay,this.options.baseDelay*2**e)}};function ps(e){if(typeof e=="number")return new cn({type:"linear",attempts:e,delay:1e3});switch(e.type){case "linear":return new cn(e);case "exponential":return new ds(e);default:throw new Error("Invalid retry strategy")}}var ms=async e=>{let t={},r=async n=>typeof n=="function"?await n():n;if(e?.auth){if(e.auth.type==="Bearer"){let n=await r(e.auth.token);if(!n)return t;t.authorization=`Bearer ${n}`;}else if(e.auth.type==="Basic"){let[n,o]=await Promise.all([r(e.auth.username),r(e.auth.password)]);if(!n||!o)return t;t.authorization=`Basic ${btoa(`${n}:${o}`)}`;}else if(e.auth.type==="Custom"){let[n,o]=await Promise.all([r(e.auth.prefix),r(e.auth.value)]);if(!o)return t;t.authorization=`${n??""} ${o}`;}}return t},fs=/^application\/(?:[\w!#$%&*.^`~-]*\+)?json(;.+)?$/i;function ys(e){let t=e.headers.get("content-type"),r=new Set(["image/svg","application/xml","application/xhtml","application/html"]);if(!t)return "json";let n=t.split(";").shift()||"";return fs.test(n)?"json":r.has(n)||n.startsWith("text/")?"text":"blob"}function hs(e){try{return JSON.parse(e),!0}catch{return false}}function Gt(e){if(e===void 0)return false;let t=typeof e;return t==="string"||t==="number"||t==="boolean"||t===null?true:t!=="object"?false:Array.isArray(e)?true:e.buffer?false:e.constructor&&e.constructor.name==="Object"||typeof e.toJSON=="function"}function un(e){try{return JSON.parse(e)}catch{return e}}function dn(e){return typeof e=="function"}function gs(e){if(e?.customFetchImpl)return e.customFetchImpl;if(typeof globalThis<"u"&&dn(globalThis.fetch))return globalThis.fetch;if(typeof window<"u"&&dn(window.fetch))return window.fetch;throw new Error("No fetch implementation found")}async function Ss(e){let t=new Headers(e?.headers),r=await ms(e);for(let[n,o]of Object.entries(r||{}))t.set(n,o);if(!t.has("content-type")){let n=Es(e?.body);n&&t.set("content-type",n);}return t}function Es(e){return Gt(e)?"application/json":null}function bs(e){if(!e?.body)return null;let t=new Headers(e?.headers);if(Gt(e.body)&&!t.has("content-type")){for(let[r,n]of Object.entries(e?.body))n instanceof Date&&(e.body[r]=n.toISOString());return JSON.stringify(e.body)}return t.has("content-type")&&t.get("content-type")==="application/x-www-form-urlencoded"&&Gt(e.body)?new URLSearchParams(e.body).toString():e.body}function Rs(e,t){var r;if(t?.method)return t.method.toUpperCase();if(e.startsWith("@")){let n=(r=e.split("@")[1])==null?void 0:r.split("/")[0];return mn.includes(n)?n.toUpperCase():t?.body?"POST":"GET"}return t?.body?"POST":"GET"}function _s(e,t){let r;return !e?.signal&&e?.timeout&&(r=setTimeout(()=>t?.abort(),e?.timeout)),{abortTimeout:r,clearTimeout:()=>{r&&clearTimeout(r);}}}var Os=class pn extends Error{constructor(t,r){super(r||JSON.stringify(t,null,2)),this.issues=t,Object.setPrototypeOf(this,pn.prototype);}};async function dt(e,t){let r=await e["~standard"].validate(t);if(r.issues)throw new Os(r.issues);return r.value}var mn=["get","post","put","patch","delete"];var Ts=e=>({id:"apply-schema",name:"Apply Schema",version:"1.0.0",async init(t,r){var n,o,s,c;let p=((o=(n=e.plugins)==null?void 0:n.find(d=>{var f;return (f=d.schema)!=null&&f.config?t.startsWith(d.schema.config.baseURL||"")||t.startsWith(d.schema.config.prefix||""):false}))==null?void 0:o.schema)||e.schema;if(p){let d=t;(s=p.config)!=null&&s.prefix&&d.startsWith(p.config.prefix)&&(d=d.replace(p.config.prefix,""),p.config.baseURL&&(t=t.replace(p.config.prefix,p.config.baseURL))),(c=p.config)!=null&&c.baseURL&&d.startsWith(p.config.baseURL)&&(d=d.replace(p.config.baseURL,""));let f=p.schema[d];if(f){let m=Q(K({},r),{method:f.method,output:f.output});return r?.disableValidation||(m=Q(K({},m),{body:f.input?await dt(f.input,r?.body):r?.body,params:f.params?await dt(f.params,r?.params):r?.params,query:f.query?await dt(f.query,r?.query):r?.query})),{url:t,options:m}}}return {url:t,options:r}}}),fn=e=>{async function t(r,n){let o=Q(K(K({},e),n),{plugins:[...e?.plugins||[],Ts(e||{}),...n?.plugins||[]]});if(e?.catchAllError)try{return await Kt(r,o)}catch(s){return {data:null,error:{status:500,statusText:"Fetch Error",message:"Fetch related error. Captured by catchAllError option. See error property for more details.",error:s}}}return await Kt(r,o)}return t};function xs(e,t){let{baseURL:r,params:n,query:o}=t||{query:{},params:{},baseURL:""},s=e.startsWith("http")?e.split("/").slice(0,3).join("/"):r||"";if(e.startsWith("@")){let E=e.toString().split("@")[1].split("/")[0];mn.includes(E)&&(e=e.replace(`@${E}/`,"/"));}s.endsWith("/")||(s+="/");let[c,p]=e.replace(s,"").split("?"),d=new URLSearchParams(p);for(let[E,b]of Object.entries(o||{})){if(b==null)continue;let k;if(typeof b=="string")k=b;else if(Array.isArray(b)){for(let C of b)d.append(E,C);continue}else k=JSON.stringify(b);d.set(E,k);}if(n)if(Array.isArray(n)){let E=c.split("/").filter(b=>b.startsWith(":"));for(let[b,k]of E.entries()){let C=n[b];c=c.replace(k,C);}}else for(let[E,b]of Object.entries(n))c=c.replace(`:${E}`,String(b));c=c.split("/").map(encodeURIComponent).join("/"),c.startsWith("/")&&(c=c.slice(1));let f=d.toString();return f=f.length>0?`?${f}`.replace(/\+/g,"%20"):"",s.startsWith("http")?new URL(`${c}${f}`,s):`${s}${c}${f}`}var Kt=async(e,t)=>{var r,n,o,s,c,p,d,f;let{hooks:m,url:E,options:b}=await us(e,t),k=gs(b),C=new AbortController,le=(r=b.signal)!=null?r:C.signal,B=xs(E,b),z=bs(b),P=await Ss(b),$=Rs(E,b),v=Q(K({},b),{url:B,headers:P,body:z,method:$,signal:le});for(let q of m.onRequest)if(q){let L=await q(v);typeof L=="object"&&L!==null&&(v=L);}("pipeTo"in v&&typeof v.pipeTo=="function"||typeof((n=t?.body)==null?void 0:n.pipe)=="function")&&("duplex"in v||(v.duplex="half"));let{clearTimeout:S}=_s(b,C),R=await k(v.url,v);S();let ye={response:R,request:v};for(let q of m.onResponse)if(q){let L=await q(Q(K({},ye),{response:(o=t?.hookOptions)!=null&&o.cloneResponse?R.clone():R}));L instanceof Response?R=L:typeof L=="object"&&L!==null&&(R=L.response);}if(R.ok){if(!(v.method!=="HEAD"))return {data:"",error:null};let L=ys(R),te={data:null,response:R,request:v};if(L==="json"||L==="text"){let re=await R.text(),To=(s=v.jsonParser)!=null?s:un;te.data=await To(re);}else te.data=await R[L]();v?.output&&v.output&&!v.disableValidation&&(te.data=await dt(v.output,te.data));for(let re of m.onSuccess)re&&await re(Q(K({},te),{response:(c=t?.hookOptions)!=null&&c.cloneResponse?R.clone():R}));return t?.throw?te.data:{data:te.data,error:null}}let Rt=(p=t?.jsonParser)!=null?p:un,Re=await R.text(),pr=hs(Re),_t=pr?await Rt(Re):null,Oo={response:R,responseText:Re,request:v,error:Q(K({},_t),{status:R.status,statusText:R.statusText})};for(let q of m.onError)q&&await q(Q(K({},Oo),{response:(d=t?.hookOptions)!=null&&d.cloneResponse?R.clone():R}));if(t?.retry){let q=ps(t.retry),L=(f=t.retryAttempt)!=null?f:0;if(await q.shouldAttemptRetry(L,R)){for(let re of m.onRetry)re&&await re(ye);let te=q.getDelay(L);return await new Promise(re=>setTimeout(re,te)),await Kt(e,Q(K({},t),{retryAttempt:L+1}))}}if(t?.throw)throw new cs(R.status,R.statusText,pr?_t:Re);return {data:null,error:Q(K({},_t),{status:R.status,statusText:R.statusText})}};var vs=e=>{if(typeof process>"u")return;let t=e??"/api/auth";if(process.env.NEXT_PUBLIC_AUTH_URL)return process.env.NEXT_PUBLIC_AUTH_URL;if(typeof window>"u"){if(process.env.NEXTAUTH_URL)try{return process.env.NEXTAUTH_URL}catch{}if(process.env.VERCEL_URL)try{let r=process.env.VERCEL_URL.startsWith("http")?"":"https://";return `${new URL(`${r}${process.env.VERCEL_URL}`).origin}${t}`}catch{}}},yn=(e,t)=>{let r="credentials"in Request.prototype,n=rn(e?.baseURL,e?.basePath)??vs(e?.basePath)??"/api/auth",o=e?.plugins?.flatMap(S=>S.fetchPlugins).filter(S=>S!==void 0)||[],s={id:"lifecycle-hooks",name:"lifecycle-hooks",hooks:{onSuccess:e?.fetchOptions?.onSuccess,onError:e?.fetchOptions?.onError,onRequest:e?.fetchOptions?.onRequest,onResponse:e?.fetchOptions?.onResponse}},{onSuccess:c,onError:p,onRequest:d,onResponse:f,...m}=e?.fetchOptions||{},E=fn({baseURL:n,...r?{credentials:"include"}:{},method:"GET",jsonParser(S){return S?Bt(S,{strict:false}):null},customFetchImpl:fetch,...m,plugins:[s,...m.plugins||[],...e?.disableDefaultFetchPlugins?[]:[nn],...o]}),{$sessionSignal:b,session:k,broadcastSessionUpdate:C}=on(E,e),le=e?.plugins||[],B={},z={$sessionSignal:b,session:k},P={"/sign-out":"POST","/revoke-sessions":"POST","/revoke-other-sessions":"POST","/delete-user":"POST"},$=[{signal:"$sessionSignal",matcher(S){return S==="/sign-out"||S==="/update-user"||S==="/update-session"||S==="/sign-up/email"||S==="/sign-in/email"||S==="/delete-user"||S==="/verify-email"||S==="/revoke-sessions"||S==="/revoke-session"||S==="/change-email"},callback(S){S==="/sign-out"?C("signout"):(S==="/update-user"||S==="/update-session")&&C("updateUser");}}];for(let S of le)S.getAtoms&&Object.assign(z,S.getAtoms?.(E)),S.pathMethods&&Object.assign(P,S.pathMethods),S.atomListeners&&$.push(...S.atomListeners);let v={notify:S=>{z[S].set(!z[S].get());},listen:(S,R)=>{z[S].subscribe(R);},atoms:z};for(let S of le)S.getActions&&(B=an(S.getActions?.(E,v,e)??{},B));return {get baseURL(){return n},pluginsActions:B,pluginsAtoms:z,pluginPathMethods:P,atomListeners:$,$fetch:E,$store:v}};function hn(e){return typeof e=="object"&&e!==null&&"get"in e&&typeof e.get=="function"&&"lc"in e&&typeof e.lc=="number"}function ws(e,t,r){let n=t[e],{fetchOptions:o,query:s,...c}=r||{};return n||(o?.method?o.method:c&&Object.keys(c).length>0?"POST":"GET")}function gn(e,t,r,n,o){function s(c=[]){return new Proxy(function(){},{get(p,d){if(typeof d!="string"||d==="then"||d==="catch"||d==="finally")return;let f=[...c,d],m=e;for(let E of f)if(m&&typeof m=="object"&&E in m)m=m[E];else {m=void 0;break}return typeof m=="function"||hn(m)?m:s(f)},apply:async(p,d,f)=>{let m="/"+c.map(P=>P.replace(/[A-Z]/g,$=>`-${$.toLowerCase()}`)).join("/"),E=f[0]||{},b=f[1]||{},{query:k,fetchOptions:C,...le}=E,B={...b,...C},z=ws(m,r,E);return await t(m,{...B,body:z==="GET"?void 0:{...le,...B?.body||{}},query:k||B?.query,method:z,async onSuccess(P){if(await B?.onSuccess?.(P),!o||B.disableSignal)return;let $=o.filter(S=>S.matcher(m));if(!$.length)return;let v=new Set;for(let S of $){let R=n[S.signal];if(!R)return;if(v.has(S.signal))continue;v.add(S.signal);let ye=R.get();setTimeout(()=>{R.set(!ye);},10),S.callback?.(m);}}})}})}return s()}function Sn(e){return e.charAt(0).toUpperCase()+e.slice(1)}function Jt(e){let{pluginPathMethods:t,pluginsActions:r,pluginsAtoms:n,$fetch:o,atomListeners:s,$store:c}=yn(e),p={};for(let[d,f]of Object.entries(n))p[`use${Sn(d)}`]=f;return gn({...r,...p,$fetch:o,$store:c},o,t,n,s)}A({FAILED_TO_CREATE_USER:"Failed to create user",USER_ALREADY_EXISTS:"User already exists.",USER_ALREADY_EXISTS_USE_ANOTHER_EMAIL:"User already exists. Use another email.",YOU_CANNOT_BAN_YOURSELF:"You cannot ban yourself",YOU_ARE_NOT_ALLOWED_TO_CHANGE_USERS_ROLE:"You are not allowed to change users role",YOU_ARE_NOT_ALLOWED_TO_CREATE_USERS:"You are not allowed to create users",YOU_ARE_NOT_ALLOWED_TO_LIST_USERS:"You are not allowed to list users",YOU_ARE_NOT_ALLOWED_TO_LIST_USERS_SESSIONS:"You are not allowed to list users sessions",YOU_ARE_NOT_ALLOWED_TO_BAN_USERS:"You are not allowed to ban users",YOU_ARE_NOT_ALLOWED_TO_IMPERSONATE_USERS:"You are not allowed to impersonate users",YOU_ARE_NOT_ALLOWED_TO_REVOKE_USERS_SESSIONS:"You are not allowed to revoke users sessions",YOU_ARE_NOT_ALLOWED_TO_DELETE_USERS:"You are not allowed to delete users",YOU_ARE_NOT_ALLOWED_TO_SET_USERS_PASSWORD:"You are not allowed to set users password",BANNED_USER:"You have been banned from this application",YOU_ARE_NOT_ALLOWED_TO_GET_USER:"You are not allowed to get user",NO_DATA_TO_UPDATE:"No data to update",YOU_ARE_NOT_ALLOWED_TO_UPDATE_USERS:"You are not allowed to update users",YOU_CANNOT_REMOVE_YOURSELF:"You cannot remove yourself",YOU_ARE_NOT_ALLOWED_TO_SET_NON_EXISTENT_VALUE:"You are not allowed to set a non-existent role value",YOU_CANNOT_IMPERSONATE_ADMINS:"You cannot impersonate admins",INVALID_ROLE_TYPE:"Invalid role type"});A({INVALID_EMAIL_FORMAT:"Email was not generated in a valid format",FAILED_TO_CREATE_USER:"Failed to create user",COULD_NOT_CREATE_SESSION:"Could not create session",ANONYMOUS_USERS_CANNOT_SIGN_IN_AGAIN_ANONYMOUSLY:"Anonymous users cannot sign in again anonymously",FAILED_TO_DELETE_ANONYMOUS_USER:"Failed to delete anonymous user",USER_IS_NOT_ANONYMOUS:"User is not anonymous",DELETE_ANONYMOUS_USER_DISABLED:"Deleting anonymous users is disabled"});var Xt=()=>({id:"device-authorization",$InferServerPlugin:{},pathMethods:{"/device/code":"POST","/device/token":"POST","/device":"GET","/device/approve":"POST","/device/deny":"POST"}});A({OTP_EXPIRED:"OTP expired",INVALID_OTP:"Invalid OTP",TOO_MANY_ATTEMPTS:"Too many attempts"});A({INVALID_OAUTH_CONFIGURATION:"Invalid OAuth configuration",TOKEN_URL_NOT_FOUND:"Invalid OAuth configuration. Token URL not found.",PROVIDER_CONFIG_NOT_FOUND:"No config found for provider",PROVIDER_ID_REQUIRED:"Provider ID is required",INVALID_OAUTH_CONFIG:"Invalid OAuth configuration.",SESSION_REQUIRED:"Session is required",ISSUER_MISMATCH:"OAuth issuer mismatch. The authorization server issuer does not match the expected value (RFC 9207).",ISSUER_MISSING:"OAuth issuer parameter missing. The authorization server did not include the required iss parameter (RFC 9207)."});A({INVALID_SESSION_TOKEN:"Invalid session token"});A({YOU_ARE_NOT_ALLOWED_TO_CREATE_A_NEW_ORGANIZATION:"You are not allowed to create a new organization",YOU_HAVE_REACHED_THE_MAXIMUM_NUMBER_OF_ORGANIZATIONS:"You have reached the maximum number of organizations",ORGANIZATION_ALREADY_EXISTS:"Organization already exists",ORGANIZATION_SLUG_ALREADY_TAKEN:"Organization slug already taken",ORGANIZATION_NOT_FOUND:"Organization not found",USER_IS_NOT_A_MEMBER_OF_THE_ORGANIZATION:"User is not a member of the organization",YOU_ARE_NOT_ALLOWED_TO_UPDATE_THIS_ORGANIZATION:"You are not allowed to update this organization",YOU_ARE_NOT_ALLOWED_TO_DELETE_THIS_ORGANIZATION:"You are not allowed to delete this organization",NO_ACTIVE_ORGANIZATION:"No active organization",USER_IS_ALREADY_A_MEMBER_OF_THIS_ORGANIZATION:"User is already a member of this organization",MEMBER_NOT_FOUND:"Member not found",ROLE_NOT_FOUND:"Role not found",YOU_ARE_NOT_ALLOWED_TO_CREATE_A_NEW_TEAM:"You are not allowed to create a new team",TEAM_ALREADY_EXISTS:"Team already exists",TEAM_NOT_FOUND:"Team not found",YOU_CANNOT_LEAVE_THE_ORGANIZATION_AS_THE_ONLY_OWNER:"You cannot leave the organization as the only owner",YOU_CANNOT_LEAVE_THE_ORGANIZATION_WITHOUT_AN_OWNER:"You cannot leave the organization without an owner",YOU_ARE_NOT_ALLOWED_TO_DELETE_THIS_MEMBER:"You are not allowed to delete this member",YOU_ARE_NOT_ALLOWED_TO_INVITE_USERS_TO_THIS_ORGANIZATION:"You are not allowed to invite users to this organization",USER_IS_ALREADY_INVITED_TO_THIS_ORGANIZATION:"User is already invited to this organization",INVITATION_NOT_FOUND:"Invitation not found",YOU_ARE_NOT_THE_RECIPIENT_OF_THE_INVITATION:"You are not the recipient of the invitation",EMAIL_VERIFICATION_REQUIRED_BEFORE_ACCEPTING_OR_REJECTING_INVITATION:"Email verification required before accepting or rejecting invitation",YOU_ARE_NOT_ALLOWED_TO_CANCEL_THIS_INVITATION:"You are not allowed to cancel this invitation",INVITER_IS_NO_LONGER_A_MEMBER_OF_THE_ORGANIZATION:"Inviter is no longer a member of the organization",YOU_ARE_NOT_ALLOWED_TO_INVITE_USER_WITH_THIS_ROLE:"You are not allowed to invite a user with this role",FAILED_TO_RETRIEVE_INVITATION:"Failed to retrieve invitation",YOU_HAVE_REACHED_THE_MAXIMUM_NUMBER_OF_TEAMS:"You have reached the maximum number of teams",UNABLE_TO_REMOVE_LAST_TEAM:"Unable to remove last team",YOU_ARE_NOT_ALLOWED_TO_UPDATE_THIS_MEMBER:"You are not allowed to update this member",ORGANIZATION_MEMBERSHIP_LIMIT_REACHED:"Organization membership limit reached",YOU_ARE_NOT_ALLOWED_TO_CREATE_TEAMS_IN_THIS_ORGANIZATION:"You are not allowed to create teams in this organization",YOU_ARE_NOT_ALLOWED_TO_DELETE_TEAMS_IN_THIS_ORGANIZATION:"You are not allowed to delete teams in this organization",YOU_ARE_NOT_ALLOWED_TO_UPDATE_THIS_TEAM:"You are not allowed to update this team",YOU_ARE_NOT_ALLOWED_TO_DELETE_THIS_TEAM:"You are not allowed to delete this team",INVITATION_LIMIT_REACHED:"Invitation limit reached",TEAM_MEMBER_LIMIT_REACHED:"Team member limit reached",USER_IS_NOT_A_MEMBER_OF_THE_TEAM:"User is not a member of the team",YOU_CAN_NOT_ACCESS_THE_MEMBERS_OF_THIS_TEAM:"You are not allowed to list the members of this team",YOU_DO_NOT_HAVE_AN_ACTIVE_TEAM:"You do not have an active team",YOU_ARE_NOT_ALLOWED_TO_CREATE_A_NEW_TEAM_MEMBER:"You are not allowed to create a new member",YOU_ARE_NOT_ALLOWED_TO_REMOVE_A_TEAM_MEMBER:"You are not allowed to remove a team member",YOU_ARE_NOT_ALLOWED_TO_ACCESS_THIS_ORGANIZATION:"You are not allowed to access this organization as an owner",YOU_ARE_NOT_A_MEMBER_OF_THIS_ORGANIZATION:"You are not a member of this organization",MISSING_AC_INSTANCE:"Dynamic Access Control requires a pre-defined ac instance on the server auth plugin. Read server logs for more information",YOU_MUST_BE_IN_AN_ORGANIZATION_TO_CREATE_A_ROLE:"You must be in an organization to create a role",YOU_ARE_NOT_ALLOWED_TO_CREATE_A_ROLE:"You are not allowed to create a role",YOU_ARE_NOT_ALLOWED_TO_UPDATE_A_ROLE:"You are not allowed to update a role",YOU_ARE_NOT_ALLOWED_TO_DELETE_A_ROLE:"You are not allowed to delete a role",YOU_ARE_NOT_ALLOWED_TO_READ_A_ROLE:"You are not allowed to read a role",YOU_ARE_NOT_ALLOWED_TO_LIST_A_ROLE:"You are not allowed to list a role",YOU_ARE_NOT_ALLOWED_TO_GET_A_ROLE:"You are not allowed to get a role",TOO_MANY_ROLES:"This organization has too many roles",INVALID_RESOURCE:"The provided permission includes an invalid resource",ROLE_NAME_IS_ALREADY_TAKEN:"That role name is already taken",CANNOT_DELETE_A_PRE_DEFINED_ROLE:"Cannot delete a pre-defined role",ROLE_IS_ASSIGNED_TO_MEMBERS:"Cannot delete a role that is assigned to members. Please reassign the members to a different role first"});A({INVALID_PHONE_NUMBER:"Invalid phone number",PHONE_NUMBER_EXIST:"Phone number already exists",PHONE_NUMBER_NOT_EXIST:"phone number isn't registered",INVALID_PHONE_NUMBER_OR_PASSWORD:"Invalid phone number or password",UNEXPECTED_ERROR:"Unexpected error",OTP_NOT_FOUND:"OTP not found",OTP_EXPIRED:"OTP expired",INVALID_OTP:"Invalid OTP",PHONE_NUMBER_NOT_VERIFIED:"Phone number not verified",PHONE_NUMBER_CANNOT_BE_UPDATED:"Phone number cannot be updated",SEND_OTP_NOT_IMPLEMENTED:"sendOTP not implemented",TOO_MANY_ATTEMPTS:"Too many attempts"});A({OTP_NOT_ENABLED:"OTP not enabled",OTP_HAS_EXPIRED:"OTP has expired",TOTP_NOT_ENABLED:"TOTP not enabled",TWO_FACTOR_NOT_ENABLED:"Two factor isn't enabled",BACKUP_CODES_NOT_ENABLED:"Backup codes aren't enabled",INVALID_BACKUP_CODE:"Invalid backup code",INVALID_CODE:"Invalid code",TOO_MANY_ATTEMPTS_REQUEST_NEW_CODE:"Too many attempts. Please request a new code.",INVALID_TWO_FACTOR_COOKIE:"Invalid two factor cookie"});A({INVALID_USERNAME_OR_PASSWORD:"Invalid username or password",EMAIL_NOT_VERIFIED:"Email not verified",UNEXPECTED_ERROR:"Unexpected error",USERNAME_IS_ALREADY_TAKEN:"Username is already taken. Please try another.",USERNAME_TOO_SHORT:"Username is too short",USERNAME_TOO_LONG:"Username is too long",INVALID_USERNAME:"Username is invalid",INVALID_DISPLAY_USERNAME:"Display username is invalid"});var Ps=".ripplo";function Mn(){return ir.join(Cs.homedir(),Ps)}function jn(){let e=Mn();return xe.existsSync(e)?xe.chmodSync(e,448):xe.mkdirSync(e,{mode:448,recursive:true}),e}function $n(e){return ir.join(Mn(),e)}function ze(e){let t=process.env.RIPPLO_TOKEN;if(t!=null&&t.trim().length>0)return t.trim();let r=be(e);if(!xe.existsSync(r))return null;let n=xe.readFileSync(r,"utf8").trim();return n.length===0?null:n}function er({serverUrl:e,token:t}){jn();let r=be(e);xe.mkdirSync(ir.dirname(r),{mode:448,recursive:true}),xe.writeFileSync(r,t+`
|
|
6
|
+
`,{mode:384});}function tr(e){let t=be(e);return xe.existsSync(t)?(xe.unlinkSync(t),true):false}function be(e){return $n(ir.join("tokens",Ls(e)))}function Ls(e){return new URL(e).host.replaceAll(/[^a-zA-Z0-9.]/g,"_")}var Us=5e3,Bn="ripplo-cli",Ms=new Set(["authorization_pending","slow_down"]);async function zn({onDeviceCode:e,serverUrl:t}){let r=js(t),n=await r.device.code({client_id:Bn});if(n.error!=null)return err({description:n.error.error_description,kind:"device-code-failed"});let{device_code:o,user_code:s,verification_uri_complete:c}=n.data;return e({userCode:s,verificationUrl:c}),Fs(c),(await $s({authClient:r,deviceCode:o})).map(d=>(er({serverUrl:t,token:d}),d))}function js(e){return Jt({baseURL:e,fetchOptions:{headers:{"User-Agent":"Ripplo CLI"}},plugins:[Xt()]})}async function $s({authClient:e,deviceCode:t}){for(;;){await Vs(Us);let r=await e.device.token({client_id:Bn,device_code:t,grant_type:"urn:ietf:params:oauth:grant-type:device_code"});if(r.data?.access_token!=null)return ok(r.data.access_token);if(r.error!=null&&!Ms.has(r.error.error))return err({code:r.error.error,description:r.error.error_description,kind:"authorization-failed"})}}function Vs(e){return new Promise(t=>{setTimeout(t,e);})}function Fs(e){let t=Bs();exec(`${t} "${e}"`,()=>{});}function Bs(){return process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open"}async function rr({lookupViewer:e,serverUrl:t}){let r=ze(t);if(r!=null&&await qs({lookupViewer:e,serverUrl:t,token:r}))return;let o=(await zn({onDeviceCode:zs,serverUrl:t})).match(p=>p,p=>{process.stderr.write(`${Ws(p)}
|
|
7
|
+
`),process.exit(1);}),s=await e({serverUrl:t,token:o}),c="Welcome to Ripplo";process.stdout.write(`
|
|
8
|
+
`),process.stdout.write(s.kind==="ok"?`${c}, ${Ys(s.viewer)}.
|
|
9
|
+
`:`${c}.
|
|
10
|
+
`),process.stdout.write(`Session saved to ${be(t)}.
|
|
11
|
+
`);}function nr(e){if(!tr(e)){process.stdout.write(`Already signed out.
|
|
12
|
+
`);return}process.stdout.write(`Signed out. Removed ${be(e)}.
|
|
13
|
+
`);}function zs(e){process.stdout.write(`Opening your browser to finish sign-in.
|
|
14
|
+
`),process.stdout.write(`If it didn't open, visit: ${e.verificationUrl}
|
|
15
|
+
`),process.stdout.write(`Verification code: ${e.userCode}
|
|
14
16
|
|
|
15
17
|
`),process.stdout.write(`Waiting for approval...
|
|
16
|
-
`)}})).
|
|
17
|
-
`),process.
|
|
18
|
-
`),process.stdout.write(o.kind==="ok"?`${s}, ${Ks(o.viewer)}.
|
|
19
|
-
`:`${s}.
|
|
20
|
-
`),process.stdout.write(`Session saved to ${He(e)}.
|
|
21
|
-
`),i||(process.stdout.write("\nNext: run `npx ripplo setup` to wire Ripplo into this project,\n"),process.stdout.write("or `npx ripplo init` to set it up by hand.\n"))}async function zs(e,r){let n=await er({serverUrl:e,token:r});return n.kind==="ok"?(process.stdout.write(`Already signed in as ${n.viewer.email}. Run \`npx ripplo auth logout\` to switch accounts.
|
|
22
|
-
`),!0):(n.kind==="unreachable"&&(process.stdout.write(`Could not reach the Ripplo server at ${e} (${n.message}). Your saved session may still be valid \u2014 fix connectivity and retry.
|
|
18
|
+
`);}async function qs({lookupViewer:e,serverUrl:t,token:r}){let n=await e({serverUrl:t,token:r});return n.kind==="ok"?(process.stdout.write(`Already signed in as ${n.viewer.email}. Run \`npx ripplo logout\` to switch accounts.
|
|
19
|
+
`),true):(n.kind==="unreachable"&&(process.stdout.write(`Could not reach the Ripplo server at ${t} (${n.message}). Your saved session may still be valid \u2014 fix connectivity and retry.
|
|
23
20
|
`),process.exit(1)),process.stdout.write(`Your session expired \u2014 signing you back in.
|
|
24
21
|
|
|
25
|
-
`)
|
|
26
|
-
`)
|
|
27
|
-
`)
|
|
28
|
-
|
|
29
|
-
`);return}process.stdout.write(`Signed out. Removed ${He(e)}.
|
|
30
|
-
`)}async function er({serverUrl:e,token:r}){try{let t=(await d({config:M({serverUrl:e,token:r}),document:Vs,variables:void 0})).currentUser;return t==null?{kind:"rejected"}:{kind:"ok",viewer:{email:t.email,name:t.name}}}catch(n){return Or(n)==="UNAUTHENTICATED"?{kind:"rejected"}:{kind:"unreachable",message:n instanceof Error?n.message:String(n)}}}function Ks(e){let r=e.name.trim().split(/\s+/)[0];return r!=null&&r.length>0?r:e.email}import{readFile as Gs,writeFile as Js}from"fs/promises";import Qs from"path";async function jt(e){let r=process.cwd(),n=await me(r);n.isErr()&&Se(J(n.error));let t=n.value,o=ye({cwd:r,lockfile:t});o.length>0&&Se(ke(o));let i=await G(r,t),s=Kr(T,i),a=Qs.join(r,V);if(e.check){await Zs(a,i);return}await Js(a,s),en(r,s),Ys(i)}function Se(e){process.stderr.write(`${e}
|
|
31
|
-
`),process.exit(1)}async function Zs(e,r){let n=await Gs(e,"utf8").catch(()=>null);n==null&&Se(Ge("missing")),Xs(n,r)||Se(Ge("stale")),process.stdout.write(`${xn()}
|
|
32
|
-
`)}function Xs(e,r){try{let n=N(T,e);return n.checks==null?!1:hn(n,r)}catch{return!1}}function Ys(e){let r=e.workflows.reduce((t,o)=>t+o.tests.length,0),n=[Rn(),Cn(r)];process.stdout.write(`${n.join(`
|
|
33
|
-
`)}
|
|
34
|
-
`)}import{graphql as Mt}from"gql.tada";function rr(e){return e==null?"Max local concurrent runs: unknown (not signed in?)":`Max local concurrent runs: ${String(e)} (the daemon applies changes live)`}import{graphql as ea}from"gql.tada";var ra=ea(`
|
|
35
|
-
query DevSessionCheckPreflight($projectId: String!, $cwd: String!) {
|
|
36
|
-
project(id: $projectId) {
|
|
37
|
-
id
|
|
38
|
-
devSession(cwd: $cwd) {
|
|
39
|
-
id
|
|
40
|
-
}
|
|
41
|
-
}
|
|
42
|
-
}
|
|
43
|
-
`);function b(){return y(process.cwd()).match(e=>e,e=>{process.stderr.write(`${S(e)}
|
|
44
|
-
`),process.stderr.write(`${R("setup")}
|
|
45
|
-
`),process.exit(1)})}async function x(e){(await d({config:e,document:ra,variables:{cwd:e.cwd,projectId:e.projectId}})).project?.devSession==null&&(process.stderr.write("No active dev session. Start `npx ripplo daemon` as a background process (your app's dev server must also be running), then retry. Or run `/ripplo:start` in Claude Code.\n"),process.stderr.write(`${R("setup")}
|
|
46
|
-
`),process.exit(1))}var na=Mt(`
|
|
47
|
-
mutation CliUpdateMaxLocalConcurrentRuns($value: Int!) {
|
|
48
|
-
updateMaxLocalConcurrentRuns(value: $value) {
|
|
49
|
-
id
|
|
50
|
-
maxLocalConcurrentRuns
|
|
51
|
-
}
|
|
52
|
-
}
|
|
53
|
-
`),ta=Mt(`
|
|
54
|
-
query CliMaxLocalConcurrentRuns {
|
|
55
|
-
currentUser {
|
|
56
|
-
id
|
|
57
|
-
maxLocalConcurrentRuns
|
|
58
|
-
}
|
|
59
|
-
}
|
|
60
|
-
`);async function Lt({value:e}){let r=b();if(e==null){let t=await d({config:r,document:ta,variables:{}});process.stdout.write(`${rr(t.currentUser?.maxLocalConcurrentRuns)}
|
|
61
|
-
`);return}let n=await d({config:r,document:na,variables:{value:e}});process.stdout.write(`${rr(n.updateMaxLocalConcurrentRuns?.maxLocalConcurrentRuns)}
|
|
62
|
-
`)}function Nt(e){return e.status==="match"?"\u2713 Webhook secret: your app and Ripplo agree":e.status==="missing-local"?"! Webhook secret: RIPPLO_WEBHOOK_SECRET is not set \u2014 the engine adapter needs it to verify Ripplo's calls":e.status==="unknown"?"! Webhook secret: could not read this project's secret from Ripplo, so a mismatch would not be caught here":`\u2717 Webhook secret: RIPPLO_WEBHOOK_SECRET does not match the secret Ripplo holds for this project (${oa(e)}). Local runs still pass because your app verifies against the same local value, but cloud runs will be rejected. Copy the secret from the project settings into your env file.`}function oa(e){let r=e.localFingerprint??"unset",n=e.serverFingerprint??"unknown";return`yours ${r}, Ripplo's ${n}`}function Ot(e){switch(e.type){case"settings":return ia(e);case"env-files":return sa(e);case"token":return aa(e);case"dev-server":return la(e);case"dev-session":return Xn(e);case"state-sources":return da(e);case"webhook-verification":return ca(e);case"model-validation":return ua(e);case"workflows":return pa(e);case"browser":return fa(e);case"engine-endpoint":return e.reachable?`\u2713 Engine endpoint: ${e.url} is reachable`:`\u2717 Engine endpoint: ${e.url} is not reachable`;case"adapter-enabled":return ga(e);case"lockfile":return ya(e);case"pre-commit-hook":return ha(e);case"plugin-version":return ka(e);case"stale-build":return wa(e);case"webhook-secret":return Nt(e)}}function ia(e){return e.valid?"\u2713 Settings: project configured":`\u2717 Settings: missing fields: ${e.missingFields.join(", ")}`}function sa(e){return e.missing.length===0?"\u2713 Env files: declared files present":`\u2717 Env files: declared in .ripplo/project.json but missing:
|
|
63
|
-
${e.missing.map(n=>` ${n}`).join(`
|
|
64
|
-
`)}
|
|
65
|
-
In a git worktree? Copy the env file from the main checkout, or symlink to a shared file outside the working tree.`}function aa(e){switch(e.status){case"valid":return`\u2713 Auth: signed in as ${e.email??"unknown"}`;case"missing":return"\u2717 Auth: not signed in. Run `npx ripplo auth login`.\n (Claude Code: run it yourself in the background \u2014 the user just approves in the browser.)";case"invalid":return"\u2717 Auth: saved token rejected by the server. Run `npx ripplo auth login` to sign in again.\n (Claude Code: run it yourself in the background \u2014 the user just approves in the browser.)";case"unreachable":return`! Auth: could not reach ${C()} to validate the token.`}}function la(e){return e.reachable?`\u2713 Dev server: ${e.appUrl} is reachable`:`\u2717 Dev server: ${e.appUrl} is not responding. Start your dev server.`}function da(e){return e.count===0?"! State sources: none use HTTP":e.configured?e.endpointReachable===void 0?`! State sources: ${String(e.count)} use HTTP, but the engine endpoint was not verified`:`\u2713 State sources: ${String(e.count)} HTTP sources configured`:`\u2717 State sources: ${String(e.count)} use HTTP but RIPPLO_ENGINE_URL is not set`}function ca(e){return e.rejectsUnsigned?"\u2713 Webhook verification: unsigned requests rejected":"\u2717 Webhook verification: endpoint accepted an unsigned request \u2014 signature verification may be missing or misconfigured."}function ua(e){if(!e.found)return"\u2717 Model: DSL failed to compile";if(e.valid)return"\u2713 Model: valid";let r=e.errors.map(n=>` - ${n.path===""?"":n.path+": "}${n.message}`);return`\u2717 Model: ${String(e.errorCount)} validation error${e.errorCount===1?"":"s"}
|
|
66
|
-
${r.join(`
|
|
67
|
-
`)}`}function pa(e){if(e.total===0)return"! Tests: none defined";if(e.invalidNames.length===0)return`\u2713 Tests: ${String(e.total)} valid`;let r=e.invalidWorkflows.map(n=>ma(n));return`\u2717 Tests: ${String(e.invalidNames.length)} invalid
|
|
68
|
-
${r.join(`
|
|
69
|
-
`)}`}function ma(e){let r=e.errors.map(n=>" - "+(n.path===""?"":n.path+": ")+n.message);return" "+e.name+`:
|
|
70
|
-
`+r.join(`
|
|
71
|
-
`)}function fa(e){return e.installed?"\u2713 Browser: Chromium installed":"\u2717 Browser: Chromium not installed. Run `npx playwright install chromium`."}function ga(e){switch(e.status){case"enabled":return`\u2713 Adapter: enabled at ${e.url}`;case"disabled":return"\u2717 Adapter: disabled (handler returned 404). Set ENABLE_RIPPLO_TESTING=true in your app's env (e.g. apps/<app>/.env.local for Next.js) and restart the dev server.";case"bad-secret":return"\u2717 Adapter: webhook signature rejected. RIPPLO_WEBHOOK_SECRET seen by your dev server does not match the one in your env file.";case"unreachable":return`\u2717 Adapter: ${e.url} could not be reached for signed probe.`;case"no-secret":return"\u2717 Adapter: RIPPLO_WEBHOOK_SECRET is not set in your env file (declared in .ripplo/project.json)."}}function ya(e){switch(e.status){case"match":return`\u2713 Lockfile: ${V} is up to date`;case"missing":return`\u2717 Lockfile: ${V} is missing \u2014 run \`npx ripplo compile\` and commit it`;case"stale":return`\u2717 Lockfile: ${V} is out of date \u2014 run \`npx ripplo compile\` and commit it`}}function ha(e){return e.installed?"\u2713 Pre-commit hook: .git/hooks/pre-commit runs `ripplo compile --check`":"! Pre-commit hook: .git/hooks/pre-commit does not run `ripplo compile --check` \u2014 see the setup skill for the snippet"}function ka(e){return e.installed===e.cliVersion?`\u2713 Claude plugin: v${e.installed} matches CLI`:`! Claude plugin: installed v${e.installed}, CLI v${e.cliVersion} \u2014 run \`npx ripplo update\` (or /plugin in Claude Code)`}function wa(e){return e.freshness.kind==="foreign-binary"?"! Build: running a ripplo binary from outside this workspace \u2014 its bundle may not match your source. Run `npx ripplo` from this workspace after `pnpm build`.":e.freshness.kind==="stale"?`! Build: source is newer than the built bundles (${e.freshness.packages.join(", ")}) \u2014 the daemon and engine may be serving stale code. Run \`pnpm build\`, then \`npx ripplo daemon stop\` and start it again.`:"\u2713 Build: bundles up to date"}import Re from"fs";import Ia from"os";import nr from"path";import{z as F}from"zod";import ba from"latest-version";import Ft from"semver";async function xe(e){try{return await Promise.race([ba("ripplo"),new Promise(r=>setTimeout(()=>{r(void 0)},e))])}catch{return}}function Wt(e){return e.filter(r=>Ft.valid(r)!=null).toSorted(Ft.rcompare)[0]}import{createHash as va}from"crypto";import{graphql as Sa}from"gql.tada";var xa=Sa(`
|
|
72
|
-
query ProjectWebhookSecret($projectId: String!) {
|
|
73
|
-
project(id: $projectId) {
|
|
74
|
-
id
|
|
75
|
-
webhookSecret
|
|
76
|
-
}
|
|
77
|
-
}
|
|
78
|
-
`);async function _t(e){let r=y(e).unwrapOr(void 0),n=r==null?null:Dt(r.webhookSecret);if(r==null||n==null)return{localFingerprint:null,serverFingerprint:null,status:"missing-local",type:"webhook-secret"};let t=await Ca(r),o=t==null?null:Dt(t);return o==null?{localFingerprint:n,serverFingerprint:null,status:"unknown",type:"webhook-secret"}:{localFingerprint:n,serverFingerprint:o,status:n===o?"match":"drifted",type:"webhook-secret"}}function Dt(e){return e.length===0?null:va("sha256").update(e).digest("hex").slice(0,Ra)}var Ra=8;async function Ca(e){return(await d({config:e,document:xa,variables:{projectId:e.projectId}}).catch(()=>null))?.project?.webhookSecret??null}import{graphql as $a}from"gql.tada";var Ea=$a(`
|
|
79
|
-
query DoctorAuthViewer {
|
|
22
|
+
`),false)}function Ws(e){return e.kind==="device-code-failed"?[`Could not start sign-in (device-code request failed): ${e.description}`,"Is the Ripplo server reachable? Check RIPPLO_SERVER_URL and retry."].join(`
|
|
23
|
+
`):[`Sign-in failed (${e.code}): ${e.description}`,e.code==="expired_token"?"The approval window expired \u2014 run `npx ripplo login` again.":"Run `npx ripplo login` to retry."].join(`
|
|
24
|
+
`)}function Ys(e){let t=e.name.trim().split(/\s+/)[0];return t!=null&&t.length>0?t:e.email}var Js=1500,Zs=4e3,Xs=3,Qs=50,el=100,qn=false;function or(){if(qn)return;qn=true;let e=new Agent({connections:el,keepAliveMaxTimeout:Zs,keepAliveTimeout:Js}),t=new RetryAgent(e,{errorCodes:["ECONNRESET","ECONNREFUSED","EPIPE","ETIMEDOUT","UND_ERR_SOCKET"],maxRetries:Xs,methods:["GET","POST","HEAD","OPTIONS","PUT","DELETE"],minTimeout:Qs,statusCodes:[]});setGlobalDispatcher(t);}var rl=mt.object({version:mt.string()});function ar(){let e=readFileSync(new URL("../package.json",import.meta.url),"utf8");return rl.parse(JSON.parse(e)).version}var ol=graphql(`
|
|
25
|
+
query AuthViewer {
|
|
80
26
|
currentUser {
|
|
81
27
|
name
|
|
82
28
|
email
|
|
83
29
|
}
|
|
84
30
|
}
|
|
85
|
-
`)
|
|
86
|
-
`);let t=n.map(i=>Ot(i));process.stdout.write(t.join(`
|
|
87
|
-
`)+`
|
|
88
|
-
`);let o=n.some(i=>qt(i));process.exit(o?1:0)}import Ce from"fs";import{graphql as Ga}from"gql.tada";var Ja=Ga(`
|
|
89
|
-
mutation CliSetHooksPaused($projectId: String!, $paused: Boolean!) {
|
|
90
|
-
setHooksPaused(projectId: $projectId, paused: $paused) {
|
|
91
|
-
id
|
|
92
|
-
}
|
|
93
|
-
}
|
|
94
|
-
`);async function zt(){let e=process.cwd();Wr(e);let r=Ve(e);if(Ce.existsSync(r)){process.stdout.write("Hooks already paused. Run `npx ripplo hooks resume` to re-enable.\n");return}Ce.writeFileSync(r,""),await Gt(e,!0),process.stdout.write("Hooks paused. Pre-edit gates and stop enforcement are off until you run `npx ripplo hooks resume`.\n")}async function Kt(){let e=process.cwd(),r=Ve(e);if(!Ce.existsSync(r)){process.stdout.write(`Hooks already active.
|
|
95
|
-
`);return}Ce.unlinkSync(r),await Gt(e,!1),process.stdout.write(`Hooks resumed.
|
|
96
|
-
`)}async function Gt(e,r){let n=y(e).unwrapOr(void 0);n!=null&&await d({config:n,document:Ja,variables:{paused:r,projectId:n.projectId}}).catch(t=>{process.stderr.write(`Warning: could not push hook-pause state to the server (${t instanceof Error?t.message:String(t)}) \u2014 the dashboard may show stale hook status.
|
|
97
|
-
`)})}import Z from"fs";import X from"path";import{input as io,select as so}from"@inquirer/prompts";import{graphql as Tl}from"gql.tada";import{exec as Qa,execFile as Za}from"child_process";import{err as Xa,ok as Jt}from"neverthrow";import m from"fs";import{createRequire as Ya}from"module";import k from"path";import{promisify as Xt}from"util";import{minVersion as el}from"semver";import{z as h}from"zod";var rl=["ripplo","@ripplo/testing","@ripplo/instrument"],Qt=[h.core.version.major,h.core.version.minor,h.core.version.patch].map(String).join("."),nl=4,Zt=".ripplo/ripplo.lock linguist-generated=true",tl=[".ripplo/debug/",".ripplo/.local/"],ol=h.object({dependencies:h.record(h.string(),h.string()).optional(),devDependencies:h.record(h.string(),h.string()).optional(),optionalDependencies:h.record(h.string(),h.string()).optional(),peerDependencies:h.record(h.string(),h.string()).optional()}),il=Xt(Qa),sl=Xt(Za);async function Yt({cwd:e,onStep:r}){let n=no(e);r("Scaffolding project files..."),kl({cwd:e,zodImportPath:n.importPath}),r("Updating .gitignore..."),bl(e),r("Marking ripplo.lock as generated..."),ml(e),r("Installing dependencies...");let t=w(),o=await ll({cwd:e,version:t}),i=[];o.ok||i.push({manualCommand:o.cmd,message:`Couldn't auto-install dev dependencies (${o.reason}). Run the command below, then run \`npx ripplo compile\` to build the lockfile.`});let s=o.ok?eo(e):void 0;if(s!=null&&s!==t&&i.push({manualCommand:void 0,message:`Installed ripplo ${s}, but ${t} was requested. A registry policy such as pnpm's minimumReleaseAge can silently resolve an older version \u2014 allow the newer version and reinstall so the installed package matches the scaffolded files.`}),o.ok){r("Compiling initial lockfile...");let l=await pl(e);l!=null&&i.push({manualCommand:void 0,message:l})}return r("Setting up browser..."),(await al()).map(()=>i)}async function al(){let{chromium:e}=await import("playwright"),r=e.executablePath();if(m.existsSync(r))return Jt(void 0);B.info("Chromium not found. Installing via Playwright...");let n=Ya(import.meta.url),t=k.dirname(n.resolve("playwright/package.json")),o=k.join(t,"cli.js");return await sl(process.execPath,[o,"install","chromium"]),m.existsSync(r)?Jt(void 0):Xa({kind:"playwright-install-failed"})}async function ll({cwd:e,version:r}){let n=tr({cwd:e,pm:or(e),version:r});B.info("Installing dependencies: %s",n);try{return await il(n,{cwd:e}),{ok:!0}}catch(t){let o=ul(t);return B.warn("Install failed (%s): %s",n,o),{cmd:n,ok:!1,reason:o}}}var dl=h.object({version:h.string()});function eo(e){let r=k.join(e,"node_modules","ripplo","package.json");if(!m.existsSync(r)){let n=k.dirname(e);return n===e?void 0:eo(n)}try{let n=dl.safeParse(JSON.parse(m.readFileSync(r,"utf8")));return n.success?n.data.version:void 0}catch{return}}var cl=h.object({stderr:h.string().optional(),stdout:h.string().optional()});function ul(e){let r=cl.safeParse(e),t=(r.success?[r.data.stderr,r.data.stdout]:[]).flatMap(o=>o==null?[]:o.split(`
|
|
98
|
-
`)).map(o=>o.trim()).filter(o=>o.length>0).slice(-nl);return t.length>0?t.join(" "):e instanceof Error?e.message:String(e)}async function pl(e){try{await kn(e);return}catch(r){return`Couldn't compile initial lockfile: ${r instanceof Error?r.message:String(r)}.`}}function ml(e){let r=k.join(e,".gitattributes"),n=m.existsSync(r)?m.readFileSync(r,"utf8"):"";if(n.includes(Zt))return;let t=n.length===0||n.endsWith(`
|
|
99
|
-
`)?"":`
|
|
100
|
-
`;m.writeFileSync(r,`${n}${t}${Zt}
|
|
101
|
-
`)}function tr({cwd:e,pm:r,version:n}){let t=rl.map(s=>`${s}@${n}`),o=no(e),i=[...t,o.installSpec].join(" ");return r==="pnpm"?fl(e)?`pnpm add -wD --save-exact ${i}`:`pnpm add -D --save-exact ${i}`:r==="yarn"?gl({cwd:e,deps:i}):r==="bun"?`bun add -d --exact ${i}`:`npm install -D --save-exact ${i}`}function or(e){return m.existsSync(k.join(e,"pnpm-lock.yaml"))?"pnpm":m.existsSync(k.join(e,"yarn.lock"))?"yarn":m.existsSync(k.join(e,"bun.lockb"))||m.existsSync(k.join(e,"bun.lock"))?"bun":"npm"}function fl(e){return m.existsSync(k.join(e,"pnpm-workspace.yaml"))||m.existsSync(k.join(e,"pnpm-workspace.yml"))}function gl({cwd:e,deps:r}){return yl(e)?`yarn add -D --exact ${r}`:hl(e)?`yarn add -WD --exact ${r}`:`yarn add -D --exact ${r}`}function yl(e){if(m.existsSync(k.join(e,".yarnrc.yml"))||m.existsSync(k.join(e,".pnp.cjs"))||m.existsSync(k.join(e,".pnp.js")))return!0;let r=k.join(e,"package.json");if(!m.existsSync(r))return!1;try{let n=JSON.parse(m.readFileSync(r,"utf8"));if(n==null||typeof n!="object"||!("packageManager"in n))return!1;let t=n.packageManager;if(typeof t!="string")return!1;let o=/^yarn@(\d+)/.exec(t);return o!=null&&Number(o[1])>=2}catch{return!1}}function hl(e){let r=k.join(e,"package.json");if(!m.existsSync(r))return!1;try{let n=JSON.parse(m.readFileSync(r,"utf8"));if(n==null||typeof n!="object"||!("workspaces"in n))return!1;let t=n.workspaces;return Array.isArray(t)||t!=null&&typeof t=="object"}catch{return!1}}function kl({cwd:e,zodImportPath:r}){let n=k.join(e,".ripplo");ro({zodImportPath:r}).forEach(({content:t,relPath:o})=>{let i=k.join(n,o);m.mkdirSync(k.dirname(i),{recursive:!0}),wl(i,t)})}function wl(e,r){m.existsSync(e)||m.writeFileSync(e,r)}function bl(e){let r=k.join(e,".gitignore");if(!m.existsSync(r))return;let n=m.readFileSync(r,"utf8"),t=tl.filter(i=>!n.includes(i));if(t.length===0)return;let o=n.endsWith(`
|
|
102
|
-
`)?"":`
|
|
103
|
-
`;m.writeFileSync(r,n+o+t.join(`
|
|
104
|
-
`)+`
|
|
105
|
-
`)}var vl=`import { createRipplo } from "@ripplo/testing";
|
|
106
|
-
import { facts } from "./facts";
|
|
107
|
-
import { state } from "./state";
|
|
108
|
-
import { workflows } from "./workflows/index";
|
|
109
|
-
|
|
110
|
-
export default createRipplo({
|
|
111
|
-
facts,
|
|
112
|
-
state,
|
|
113
|
-
viewports: ["desktop", "mobile"],
|
|
114
|
-
workflows,
|
|
115
|
-
});
|
|
116
|
-
`;function Sl(e){return`import { defineState, source } from "@ripplo/testing";
|
|
117
|
-
import { z } from "${e}";
|
|
118
|
-
|
|
119
|
-
export const state = defineState(
|
|
120
|
-
z.object({
|
|
121
|
-
app: source.http(z.object({})),
|
|
122
|
-
}),
|
|
123
|
-
);
|
|
124
|
-
`}var xl=`export const facts = [] as const;
|
|
125
|
-
`,Rl=`export const workflows = [] as const;
|
|
126
|
-
`,Cl=`{
|
|
127
|
-
"compilerOptions": {
|
|
128
|
-
"strict": true,
|
|
129
|
-
"noUncheckedIndexedAccess": true,
|
|
130
|
-
"esModuleInterop": true,
|
|
131
|
-
"target": "ES2022",
|
|
132
|
-
"module": "ESNext",
|
|
133
|
-
"moduleResolution": "Bundler",
|
|
134
|
-
"skipLibCheck": true,
|
|
135
|
-
"isolatedModules": true,
|
|
136
|
-
"lib": ["ES2023"]
|
|
137
|
-
},
|
|
138
|
-
"include": ["*.ts", "workflows/**/*.ts"],
|
|
139
|
-
"exclude": ["node_modules"]
|
|
140
|
-
}
|
|
141
|
-
`,$l=`// Guards spec files against shadowing DSL imports \u2014 \`const url = ...\` next to the
|
|
142
|
-
// imported \`url\` locator silently breaks specs. Requires typescript-eslint (and
|
|
143
|
-
// ESLint's per-directory config lookup). Delete this file if your lint setup differs.
|
|
144
|
-
import tseslint from "typescript-eslint";
|
|
145
|
-
|
|
146
|
-
export default tseslint.config({
|
|
147
|
-
files: ["**/*.ts"],
|
|
148
|
-
languageOptions: { parser: tseslint.parser },
|
|
149
|
-
rules: {
|
|
150
|
-
"no-shadow": "off",
|
|
151
|
-
"@typescript-eslint/no-shadow": ["error", { hoist: "all" }],
|
|
152
|
-
},
|
|
153
|
-
plugins: { "@typescript-eslint": tseslint.plugin },
|
|
154
|
-
});
|
|
155
|
-
`;function ro({zodImportPath:e}){return[{content:vl,relPath:"index.ts"},{content:Sl(e),relPath:"state.ts"},{content:xl,relPath:"facts.ts"},{content:Rl,relPath:"workflows/index.ts"},{content:Cl,relPath:"tsconfig.json"},{content:$l,relPath:"eslint.config.js"}]}var _f=ro({zodImportPath:"zod/v4"});function no(e){return El(e)?{importPath:"zod4",installSpec:`zod4@npm:zod@${Qt}`}:{importPath:"zod/v4",installSpec:`zod@${Qt}`}}function El(e){let r=k.join(e,"package.json");if(!m.existsSync(r))return!1;let n=JSON.parse(m.readFileSync(r,"utf8")),t=ol.parse(n);return[t.dependencies?.zod,t.devDependencies?.zod,t.optionalDependencies?.zod,t.peerDependencies?.zod].filter(i=>i!=null).some(i=>!Pl(i))}function Pl(e){let r=e.replace(/^workspace:/,"").replace(/^npm:zod@/,"");return el(r)?.major===4}import $e from"fs";import to from"path";import{z as ir}from"zod";var Il={autoUpdate:!0,source:{repo:"ripplo/claude-plugin",source:"github"}},oo=ir.record(ir.string(),ir.unknown());function Ee(e){let r=to.join(e,".claude","settings.json"),n=Al(r);if(n==null)return"unparseable";let t=oo.safeParse(n.extraKnownMarketplaces??{});if(!t.success)return"unparseable";if(t.data.ripplo!=null)return"already-present";let o={...n,extraKnownMarketplaces:{...t.data,ripplo:Il}};return $e.mkdirSync(to.dirname(r),{recursive:!0}),$e.writeFileSync(r,`${JSON.stringify(o,null,2)}
|
|
156
|
-
`),"written"}function Al(e){if(!$e.existsSync(e))return{};try{let r=oo.safeParse(JSON.parse($e.readFileSync(e,"utf8")));return r.success?r.data:void 0}catch{return}}function Pe(e){switch(e){case"written":return" registered ripplo plugin marketplace in .claude/settings.json (autoUpdate: true \u2014 Claude Code keeps the plugin current)";case"already-present":return" ripplo plugin marketplace already registered in .claude/settings.json";case"unparseable":return" ! .claude/settings.json could not be parsed \u2014 add the ripplo marketplace to extraKnownMarketplaces manually"}}var jl=Tl(`
|
|
157
|
-
query InitProjects {
|
|
158
|
-
projects {
|
|
159
|
-
id
|
|
160
|
-
name
|
|
161
|
-
}
|
|
162
|
-
}
|
|
163
|
-
`),sr=["../.env.local","../.env"];async function ao(e=Nl()){let r=process.cwd(),n=C(),t=P(n);t==null&&(process.stdout.write("Not signed in. Run `npx ripplo auth login` first.\n"),process.exit(1)),Ml(r)&&(process.stdout.write(`\`.ripplo/index.ts\` already exists at ${r}. To re-init, delete it first.
|
|
164
|
-
`),process.exit(1));let o=await Ll({serverUrl:n,token:t});o.length===0&&(process.stdout.write("No projects found. Run `npx ripplo projects create <name>` first, then re-run `npx ripplo init`.\n"),process.exit(1));let i=await Fl(o,e.projectId),s=await Wl(r,e.envFile),a=await _l(e.appUrl),l=Ol(a,e.engineUrl),c=X.resolve(X.join(r,".ripplo"),s);Tr({cwd:r,envFiles:[s],projectId:i}),ql({appUrl:a,engineUrl:l,filePath:c}),process.stdout.write(`${Pe(Ee(r))}
|
|
165
|
-
`);let f=(await Yt({cwd:r,onStep:p=>{process.stdout.write(` ${p}
|
|
166
|
-
`)}})).match(p=>p,p=>{process.stderr.write(`${S(p)}
|
|
167
|
-
`),process.exit(1)});if(f.length>0){process.stdout.write(`Done with warnings:
|
|
168
|
-
`),f.forEach(p=>{process.stdout.write(` - ${p.message}
|
|
169
|
-
`),p.manualCommand!=null&&process.stdout.write(` run: ${p.manualCommand}
|
|
170
|
-
`)});return}process.stdout.write("Ready. Start `npx ripplo daemon` as a background process (or run `/ripplo:start` in Claude Code), then write workflows in `.ripplo/workflows/`.\n")}function Ml(e){return Z.existsSync(X.join(e,".ripplo","index.ts"))}async function Ll({serverUrl:e,token:r}){return((await d({config:M({serverUrl:e,token:r}),document:jl,variables:void 0})).projects??[]).map(t=>({id:t.id,name:t.name}))}function Nl(){return{appUrl:void 0,engineUrl:void 0,envFile:void 0,projectId:void 0}}function Ol(e,r){if(r!=null){try{new URL(r)}catch{process.stdout.write(`--engine-url is not a valid URL: ${r}
|
|
171
|
-
`),process.exit(1)}return r}return`${e.replace(/\/$/,"")}/ripplo`}async function Fl(e,r){if(r!=null){let n=e.find(t=>t.id===r);return n==null&&(process.stdout.write(`Unknown project id: ${r}
|
|
172
|
-
`),process.exit(1)),process.stdout.write(`Using project: ${n.name} (${n.id})
|
|
173
|
-
`),n.id}if(e.length===1){let n=e[0];if(n==null)throw new Error("unreachable");return process.stdout.write(`Using project: ${n.name} (${n.id})
|
|
174
|
-
`),n.id}return so({choices:e.map(n=>({name:n.name,value:n.id})),message:"Select a project"})}async function Wl(e,r){return r!=null?(r.trim().length===0&&(process.stdout.write(`--env must not be empty
|
|
175
|
-
`),process.exit(1)),r):Dl(e)}async function Dl(e){let r=X.join(e,".ripplo"),n=sr.find(o=>Z.existsSync(X.resolve(r,o))),t=await so({choices:[...sr.map(o=>({name:n===o?`${o} (detected)`:o,value:o})),{name:"custom path",value:"__custom__"}],default:n??sr[0],message:"Which env file should ripplo write RIPPLO_APP_URL, RIPPLO_ENGINE_URL, RIPPLO_WEBHOOK_SECRET, and ENABLE_RIPPLO_TESTING to?"});return t!=="__custom__"?t:io({message:"Path to env file (relative to .ripplo/, e.g. ../apps/server/.env)",validate:o=>o.trim().length>0?!0:"required"})}async function _l(e){if(e!=null){try{new URL(e)}catch{process.stdout.write(`--app-url is not a valid URL: ${e}
|
|
176
|
-
`),process.exit(1)}return e}return Ul()}async function Ul(){return io({default:"http://localhost:3000",message:"Where does your dev server run? (RIPPLO_APP_URL)",validate:e=>{try{return new URL(e),!0}catch{return"must be a valid URL"}}})}function ql({appUrl:e,engineUrl:r,filePath:n}){Z.mkdirSync(X.dirname(n),{recursive:!0});let t=Z.existsSync(n)?Z.readFileSync(n,"utf8"):"",o=[];if(/^RIPPLO_APP_URL=/m.test(t)||o.push(`RIPPLO_APP_URL=${e}`),/^RIPPLO_ENGINE_URL=/m.test(t)||o.push(`RIPPLO_ENGINE_URL=${r}`),/^RIPPLO_WEBHOOK_SECRET=/m.test(t)||o.push(`RIPPLO_WEBHOOK_SECRET=${Br()}`),/^ENABLE_RIPPLO_TESTING=/m.test(t)||o.push("ENABLE_RIPPLO_TESTING=true"),o.length===0)return;let i=t.length===0||t.endsWith(`
|
|
177
|
-
`)?"":`
|
|
178
|
-
`;Z.writeFileSync(n,`${t}${i}${o.join(`
|
|
179
|
-
`)}
|
|
180
|
-
`)}import{graphql as dr}from"gql.tada";function ar(){return"Not signed in. Run `npx ripplo auth login` first."}function lo(){return"No organization found for your account. Sign in to the dashboard once, then retry."}function co(e){return["You belong to multiple organizations \u2014 pass `--org <id>`:",...e.map(n=>` ${n.id} ${n.name}`)].join(`
|
|
181
|
-
`)}function lr(e){return`Could not create the project \u2014 ${e}`}var Bl=dr(`
|
|
182
|
-
query ProjectsList {
|
|
183
|
-
projects {
|
|
184
|
-
id
|
|
185
|
-
name
|
|
186
|
-
}
|
|
187
|
-
}
|
|
188
|
-
`),Hl=dr(`
|
|
189
|
-
query OrganizationsList {
|
|
190
|
-
organizations {
|
|
191
|
-
id
|
|
192
|
-
name
|
|
193
|
-
}
|
|
194
|
-
}
|
|
195
|
-
`),Vl=dr(`
|
|
196
|
-
mutation CliCreateProject($name: String!, $organizationId: String!) {
|
|
197
|
-
createProject(cloudBaseUrl: "", name: $name, organizationId: $organizationId) {
|
|
198
|
-
__typename
|
|
199
|
-
... on Project {
|
|
200
|
-
id
|
|
201
|
-
name
|
|
202
|
-
}
|
|
203
|
-
... on LimitExceededError {
|
|
204
|
-
message
|
|
205
|
-
}
|
|
206
|
-
... on InvalidRepoLinkError {
|
|
207
|
-
message
|
|
208
|
-
}
|
|
209
|
-
}
|
|
210
|
-
}
|
|
211
|
-
`);async function uo(){let e=C(),r=P(e);r==null&&(process.stderr.write(`${ar()}
|
|
212
|
-
`),process.exit(1));let t=((await d({config:M({serverUrl:e,token:r}),document:Bl,variables:void 0})).projects??[]).map(o=>({id:o.id,name:o.name}));process.stdout.write(`${JSON.stringify({projects:t},null,2)}
|
|
213
|
-
`)}async function po({name:e,orgId:r}){let n=C(),t=P(n);t==null&&(process.stderr.write(`${ar()}
|
|
214
|
-
`),process.exit(1));let o=M({serverUrl:n,token:t}),i=r??await zl(o),a=(await d({config:o,document:Vl,variables:{name:e,organizationId:i}}).catch(l=>{throw l instanceof Nr&&(process.stderr.write(`${lr(l.message)}
|
|
215
|
-
`),process.exit(1)),l})).createProject;if(a?.__typename!=="Project"){let l=a?.message??"unknown error";process.stderr.write(`${lr(l)}
|
|
216
|
-
`),process.exit(1)}process.stdout.write(`${JSON.stringify({project:{id:a.id,name:a.name}},null,2)}
|
|
217
|
-
`)}async function zl(e){let n=((await d({config:e,document:Hl,variables:void 0})).organizations??[]).map(o=>({id:o.id,name:o.name})),t=n.length===1?n[0]:void 0;if(t!=null)return t.id;process.stderr.write(`${n.length===0?lo():co(n)}
|
|
218
|
-
`),process.exit(1)}import{spawnSync as Ie}from"child_process";function mo(){if(Ie("claude",["--version"],{stdio:"ignore"}).error!=null)return{kind:"claude-missing"};Ie("claude",["plugin","marketplace","add","ripplo/claude-plugin"],{stdio:"ignore"});let r=Ie("claude",["plugin","install","ripplo@ripplo"],{encoding:"utf8",stdio:["ignore","pipe","pipe"]}),n=/already installed/i.test(`${r.stdout}${r.stderr}`);return r.status!==0&&!n?{detail:r.stderr.trim(),kind:"plugin-install-failed"}:{exitCode:Ie("claude",["/ripplo:setup"],{stdio:"inherit"}).status??0,kind:"launched"}}function fo(){return"Installing the Ripplo plugin for Claude Code, then handing off to a guided setup session."}function go(e){return e.kind==="claude-missing"?"Claude Code not found on your PATH. Install it, then re-run `npx ripplo setup`.":`Could not install the Ripplo plugin for Claude Code.${e.detail.length>0?`
|
|
219
|
-
${e.detail}`:""}`}function yo(){process.stdout.write(`${fo()}
|
|
220
|
-
`);let e=mo();e.kind!=="launched"&&(process.stderr.write(`${go(e)}
|
|
221
|
-
`),process.exit(1)),process.exit(e.exitCode)}import Kl from"path";import{CancellationTokenSource as Gl}from"vscode-jsonrpc/node";function Ae(e){return`ripplo: workspace build is stale (${e.join(", ")}) \u2014 rebuilding`}function Te(){return"ripplo: workspace build failed \u2014 fix the build, then rerun"}function Y(e){return e.kind==="stale"?`! workspace build is stale (${e.packages.join(", ")}) \u2014 run pnpm build, then npx ripplo daemon restart`:e.kind==="foreign-binary"?"! this is the ripplo workspace but you're running the published CLI \u2014 use node_modules/.bin/ripplo so local changes apply":null}async function ho({all:e,headed:r,ids:n}){let t=process.cwd(),o=process.argv[1];o==null&&W(be({kind:"spawn-failed",message:"process.argv[1] missing"})),Zl();let i=await Bn(t);i!=null&&W(zn(i));let a=(await Dn({cliEntry:o,cwd:t})).match(p=>p,p=>W(be(p)));a.versionNote?.kind==="stale-busy"&&W(Ze(a.versionNote)),a.versionNote!=null&&process.stderr.write(`${Ze(a.versionNote)}
|
|
222
|
-
`);let l=new Gl;process.once("SIGINT",()=>{l.cancel(),a.socket.destroy(),process.exit(130)});let c=Kl.join(t,".ripplo","debug"),f=(await _n({connection:a,onEvent:Jl(c),request:{all:e,headed:r,tests:[...n]},token:l.token})).match(p=>p,p=>W(be(p)));await Ql({connection:a,result:f})}function Jl(e){let r=!1;return n=>{let t=Vn({debugDir:e,event:n});if(t!=null){if(process.stdout.isTTY&&n.kind==="run-progress"){process.stdout.write(`\r\x1B[2K${t}`),r=!0;return}r&&(process.stdout.write("\r\x1B[2K"),r=!1),process.stdout.write(`${t}
|
|
223
|
-
`)}}}async function Ql({connection:e,result:r}){await new Promise(n=>{e.socket.end(n)}),r.kind==="daemon-error"&&W(Kn(r.error)),process.stdout.write(`${Hn(r)}
|
|
224
|
-
`),r.failed>0&&process.exit(1),process.exit(r.notRun>0?2:0)}function W(e){process.stderr.write(`${e}
|
|
225
|
-
`),process.exit(1)}function Zl(){let e=O();if(e.kind==="fresh")return;if(e.kind==="foreign-binary"){let n=Y(e);W(n??"foreign binary in the ripplo workspace")}process.stderr.write(`${Ae(e.packages)}
|
|
226
|
-
`),we(e.workspaceRoot)||W(Te())}import U from"path";import nd from"os";import{mkdtempSync as td,rmSync as od}from"fs";import{err as Le,ok as pr}from"neverthrow";import{readdir as Xl,rm as Yl,stat as ed}from"fs/promises";import{existsSync as rd}from"fs";import cr from"path";async function ur(e,r){let t=(await Xl(e,{withFileTypes:!0}).catch(()=>[])).filter(s=>s.isDirectory()).map(s=>s.name).filter(s=>s.startsWith("replay-")||s.startsWith("explore-")||rd(cr.join(e,s,Fr)));if(t.length<=r)return;let i=(await Promise.all(t.map(async s=>({mtime:(await ed(cr.join(e,s)).catch(()=>null))?.mtimeMs??0,name:s})))).toSorted((s,a)=>a.mtime-s.mtime).slice(r);await Promise.all(i.map(s=>Yl(cr.join(e,s.name),{force:!0,recursive:!0}).catch(()=>{})))}var ko=50,id=15e3,sd=15e3;async function wo(){ue(w());let e=process.cwd(),r=B.child({worker:process.pid}),n=mt(),t=td(U.join(nd.tmpdir(),"ripplo-browser-cache-")),o=ge({cacheDir:t,clientVersion:w(),debugDir:U.join(e,".ripplo","debug"),headed:!1,writeOtlpPortFile:!1}),i=new Set,s=l=>{i.add(l),l.finally(()=>i.delete(l))},a=l=>{setTimeout(()=>{process.exit(l)},id).unref(),ud(i).then(()=>o.close().catch(()=>{})).then(()=>{od(t,{force:!0,recursive:!0}),process.exit(l)})};ad({exit:a,workerLogger:r}),n.onRequest(st,async(l,c)=>{let g=tt.safeParse(l);if(!g.success)return je("bad-run-assign");let f=g.data;ne(e);let p=y(e).match(v=>v,v=>v.kind);if(typeof p=="string")return je(`config:${p}`);let E=await bo(n);if(E.isErr())return je(`lockfile-unavailable:${E.error}`);let A=E.value,$=K(A).find(v=>v.ref===f.testRef);if($==null)return je(`no-test:${f.testRef}`);let ce=gt({config:p,intervalMs:sd,runId:f.runId});try{let{outcome:v,persisted:Be,progress:js}=await yt({config:p,cwd:e,errorSettle:"settle",fixturesDir:U.join(e,te),headed:f.headed,lockfile:A,onProgress:ld({connection:n,runId:f.runId}),runId:f.runId,session:o,signal:Xe(c),test:$.test}),Ir=U.join(e,".ripplo","debug");return s(Promise.allSettled([Be]).then(()=>dd({config:p,debugDir:Ir,progress:js,runId:f.runId})).then(()=>ur(Ir,ko)).catch(()=>{})),{outcome:nt(v),serverNotified:!0}}catch(v){let Be=U.join(e,".ripplo","debug");if(s(Q({config:p,debugDir:Be,runId:f.runId}).catch(()=>{})),v instanceof Lr)return{outcome:{detail:v.message,kind:"infra-error"},serverNotified:!1};throw v}finally{ce()}}),n.onRequest(dt,(l,c)=>pd({connection:n,cwd:e,raw:l,session:o,token:c,track:s})),n.onNotification(ct,l=>{let c=ot.safeParse(l);c.success&&o.injectSpan(c.data.runId,c.data.span)}),n.onNotification(pt,()=>{a(0)}),n.sendNotification(it),await new Promise(()=>{})}function ad({exit:e,workerLogger:r}){process.on("disconnect",()=>{e(1)}),process.on("unhandledRejection",n=>{r.error({err:n},"worker unhandled rejection")}),process.on("uncaughtException",n=>{r.error({err:n},"worker uncaught exception"),e(1)})}function ld({connection:e,runId:r}){return n=>{e.sendNotification(ut,{runId:r,signal:n})}}async function dd({config:e,debugDir:r,progress:n,runId:t}){n?.report({activity:{kind:"uploadingReplay"},deadlineAt:null,retry:null}),await n?.flush(),n!=null&&ht({debugDir:r,history:n.history(),runId:t}),await Q({config:e,debugDir:r,runId:t})}function je(e){return{outcome:{detail:e,kind:"error"},serverNotified:!1}}var cd=5e3;async function ud(e){e.size!==0&&await Promise.race([Promise.allSettled(e),new Promise(r=>{setTimeout(r,cd)})])}async function pd({connection:e,cwd:r,raw:n,session:t,token:o,track:i}){let s=lt.safeParse(n);if(!s.success)return{error:{reason:"format-unsupported",source:"assignment-rejected"},kind:"error"};let{assign:a,currentTargetGeneration:l,devSessionId:c}=s.data;ne(r);let g=y(r).match(v=>v,v=>v.kind);if(typeof g=="string")return{error:{detail:g,source:"config"},kind:"error"};let f=await bo(e);if(f.isErr())return{error:{source:"lockfile-stale"},kind:"error"};let p=f.value,E=await he(r);if(E==null)return{error:{source:"lockfile-stale"},kind:"error"};let A=U.join(g.cwd,".ripplo","debug"),$=await kt({assign:a,config:g,currentModelHash:E,currentTargetGeneration:l,debugDir:A,devSessionId:c??void 0,fixturesDir:U.join(g.cwd,te),headed:!1,lockfile:p,report:!0,session:t,signal:Xe(o)}),ce=($.kind==="finding"||$.kind==="coverage-gap")&&$.runId!=null?Q({config:g,debugDir:A,runId:$.runId}):Promise.resolve();return i(ce.then(()=>ur(A,ko)).catch(()=>{})),$}async function bo(e){return(await md(e)).andThen(n=>n.unavailable!=null?Le(n.unavailable):n.lockfileJson==null?Le("empty-reply"):fd(n.lockfileJson))}async function md(e){try{return pr(await e.sendRequest(at))}catch(r){return Le(`transport:${r instanceof Error?r.message:"unknown"}`)}}var Me;function fd(e){if(Me!==void 0&&Me.json===e)return pr(Me.lockfile);try{let r=Zr(N(T,e));return Me={json:e,lockfile:r},pr(r)}catch(r){return Le(`worker-decode-failed:${r instanceof Error?r.message.slice(0,200):"unknown"}`)}}async function vo(){await wo()}import{existsSync as Rd}from"fs";import Cd from"path";import{ok as $d}from"neverthrow";import{gunzipSync as gd}from"zlib";import{mkdir as yd,writeFile as hd}from"fs/promises";import So from"path";import{graphql as kd}from"gql.tada";import{err as ie,ok as wd}from"neverthrow";var bd=31,vd=139;async function Ne(e,r){let n=y(e).match(s=>s,s=>s.kind);if(typeof n=="string")return ie({detail:n,kind:"config"});let t=await d({config:n,document:Sd,variables:{id:r}}).catch(()=>null);if(t==null)return ie({kind:"request-failed"});if(t.run==null)return ie({kind:"not-found"});if(t.run.behaviorUrl==null)return ie({kind:"not-uploaded"});let o=await fetch(t.run.behaviorUrl);if(!o.ok)return ie({kind:"download-failed",status:o.status});let i=So.join(e,".ripplo","debug",r,"behavior.jsonl");return await yd(So.dirname(i),{recursive:!0}),await hd(i,xd(Buffer.from(await o.arrayBuffer()))),wd({path:i,runId:r})}var Sd=kd(`
|
|
31
|
+
`);async function Wn({serverUrl:e,token:t}){try{let n=(await Ee({config:{ripploServerUrl:e,token:t},document:ol,variables:void 0})).currentUser;return n==null?{kind:"rejected"}:{kind:"ok",viewer:{email:n.email,name:n.name}}}catch(r){return Vt(r)==="UNAUTHENTICATED"?{kind:"rejected"}:{kind:"unreachable",message:r instanceof Error?r.message:String(r)}}}var al="https://ripplo.ai";function ft(){let e=yt(),t=ze(e);return t==null?null:{serverUrl:e,token:t}}function yt(){return il.parse(process.env).RIPPLO_SERVER_URL}function ht({serverUrl:e,token:t}){return {ripploServerUrl:e,token:t}}var il=z.object({RIPPLO_SERVER_URL:z.string().min(1).default(al)});var ll="behavior.jsonl";function sr(e){return ir.join(cl(),"ripplo","runs",e)}function gt(e){return ir.join(sr(e),ll)}function cl(){let e=process.env.XDG_CACHE_HOME;return e!=null&&e.length>0?e:ir.join(homedir(),".cache")}var hl=31,gl=139;async function Hn(e){let t=ft();if(t==null)return err({kind:"not-signed-in"});let r=await Ee({config:ht(t),document:Sl,variables:{id:e}});if(r.run==null)return err({kind:"not-found"});if(r.run.behaviorUrl==null)return err({kind:"not-uploaded"});let n=await fetch(r.run.behaviorUrl);if(!n.ok)return err({kind:"download-failed",status:n.status});let o=gt(e);return await mkdir(ir.dirname(o),{recursive:true}),await writeFile(o,El(Buffer.from(await n.arrayBuffer()))),ok({path:o,runId:e})}var Sl=graphql(`
|
|
227
32
|
query RunBehaviorUrl($id: String!) {
|
|
228
33
|
run(id: $id) {
|
|
229
34
|
id
|
|
230
35
|
behaviorUrl
|
|
231
36
|
}
|
|
232
37
|
}
|
|
233
|
-
`);function
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
test {
|
|
239
|
-
id
|
|
240
|
-
slug
|
|
241
|
-
}
|
|
242
|
-
workflow {
|
|
243
|
-
id
|
|
244
|
-
slug
|
|
245
|
-
}
|
|
246
|
-
}
|
|
247
|
-
}
|
|
248
|
-
`);var Mo=" \u203A ",dc=["fact ","data rule ","step "];function Oo(e){if(e.failures.length===0)return cc(e);let r=e.viewport==null?"":` (viewport ${String(e.viewport.width)}\xD7${String(e.viewport.height)})`,n=`${e.runId} \u2014 ${j(e.failures.length,"failing check")}${r}`,t=e.lockfileLoaded?[]:[u.dim("(no lockfile \u2014 workflow source unavailable)")],o=e.progress.at(-1),i=o==null?[]:[u.dim(`last progress \u2014 ${Je(o.signal)}`)],s=uc(e.failures).map(a=>pc(a,e.runId));return[n,...t,...i,"",...s,R("tasks")].join(`
|
|
249
|
-
`)}function Fo(e){return`${u.bad("fail")} \u2014 no artifacts for ${e.runId}. Run \`npx ripplo pull ${e.runId}\` first.`}function cc(e){if(e.stepsRan>0)return`${u.good("ok")} \u2014 ${e.runId}: no failing checks.`;let r=e.progress.at(-1),n=r==null?"":` It stopped at: ${Je(r.signal)}.`;return`${e.runId}: no steps ran, so there are no checks to explain.${n} A run that ends this early failed before its first step \u2014 setup, sign-in, or reaching your app. The reason is on the run itself, not in this artifact.`}function uc(e){return[...new Set(e.map(n=>n.step))].map(n=>({failures:e.filter(t=>t.step===n),step:n}))}function pc(e,r){let n=e.failures[0];if(n==null)return"";let t=mc(e,r);if(t!=null)return t;let o=[...new Set(e.failures.map(s=>s.error==null?Do(s.label):z(s.error)))].join(", "),i=u.dim(`(${n.runWorkflow})`);return[`${u.bad("\u2717")} ${gc(e.step)} ${i}`,` ${u.dim("failed")} ${o}`,...yc(e),...bc(n),...vc(n.causes),` ${u.dim("frame")} npx ripplo snapshot ${r} --at ${String(n.snapshotAt)}`,""].join(`
|
|
250
|
-
`)}function mc(e,r){let n=e.failures[0],t=e.failures.flatMap(c=>c.browserMismatch==null?[]:[c.browserMismatch])[0],o=Wo(e.failures.flatMap(c=>c.rules));if(n==null||t==null||o.length===0)return null;let i=Do(e.failures.find(c=>c.rules.length>0)?.label??n.label),s=[...new Set(o.map(c=>c.url))].join(", "),a=u.dim(`(${n.runWorkflow})`);return[`${u.bad("\u2717")} ${i} ${u.warn("(wrong page)")} ${a}`,` ${u.dim("rule declared for url")} ${s}`,` ${u.dim("browser was actually at")} ${t.actual}`,` ${u.warn("\u21B3 declare the navigation: add url.path`...` to the step that caused it")}`,` ${u.dim("frame")} npx ripplo snapshot ${r} --at ${String(n.snapshotAt)}`,""].join(`
|
|
251
|
-
`)}function Wo(e){let r=e.map(n=>[fc(n),n]);return[...new Map(r).values()]}function fc(e){return`${e.url}|${e.when}|${e.origins.map(r=>r.intent).join(",")}`}function Do(e){let r=dc.find(n=>e.startsWith(n));return r==null?e:e.slice(r.length)}function gc(e){let r=e.split(Mo);return r.length<2?e:r.slice(1).join(Mo)}function yc(e){let r=Wo(e.failures.flatMap(n=>n.rules));return r.length===0?[]:[...r.flatMap(n=>hc(n)),...wc(e,r)]}function hc(e){let r=e.origins.length===0?u.dim("origin not in lockfile"):e.origins.map(n=>kc(n)).join(", ");return[` ${u.dim("workflow declaration")}`,` ${u.dim("from")} ${r}`,` ${u.dim("at")} ${e.url} ${u.dim("\u2014 holds only when")} ${e.when}`]}function kc(e){if(e.sourcePath==null)return e.intent;let r=u.dim(`(${e.sourcePath})`);return`${e.intent} ${r}`}function wc(e,r){let n=new Set(r.flatMap(o=>o.origins.map(i=>i.intent)));return e.failures.some(o=>n.has(o.runWorkflow))||n.size===0?[]:[` ${u.warn("\u21B3 declared by another workflow \u2014 this declaration may be missing distinguishing state")}`]}function bc(e){if(e.waitMs==null||e.wait==null)return[];let r=`${String(Math.round(e.waitMs/1e3))}s`,n=e.pending===!0?" \u2014 value never changed (write may be slow or dropped)":"";return[` ${u.dim("waited")} up to ${r} (wait: ${e.wait})${n}`]}function vc(e){if(e.length===0)return[];let r=Sc(e),n=e.flatMap(t=>xc(t,r));return n.length===0?[]:[` ${u.dim("nearby")} ${n.join(" \xB7 ")}`]}function Sc(e){let r=e.flatMap(n=>n.detail.kind==="span"&&n.detail.traceId!=null?[[n.detail.traceId,n.detail]]:[]);return new Map(r)}function xc(e,r){let n=e.detail;if(n.kind==="span"&&n.traceId!=null&&r.has(n.traceId))return[];if(n.kind==="network"&&n.traceId!=null){let t=r.get(n.traceId),o=t==null?"":` \u21B9 ${yr(t)}`;return[No(n,`${yr(n)}${o}`)]}return[No(n,yr(n))]}function yr(e){return e.kind==="network"?`${e.method} ${String(e.status)} ${Rc(e.url)}`:e.kind==="console"?`console.${e.level} ${Lo(e.text)}`:e.kind==="error"?`error ${Lo(e.message)}`:`span ${e.name} ${e.statusCode} ${String(Math.round(e.durationMs))}ms`}function Rc(e){let r=e.split("?")[0]??e;return r.length>60?`\u2026${r.slice(-57)}`:r}function Lo(e){let r=e.replaceAll(/\s+/g," ").trim();return r.length>100?`${r.slice(0,97)}\u2026`:r}function No(e,r){return Cc(e)?u.bad(r):r}function Cc(e){return e.kind==="network"?e.status>=400:e.kind==="console"?e.level==="error":e.kind==="error"||e.statusCode==="error"}function _o(e){return[$c(e.test),"",Pc(e.factOrigins),Ic(e.timeline,e.factOrigins)].filter(r=>r.length>0).join(`
|
|
252
|
-
`)}function $c(e){return e==null?u.dim("starting state (couldn't resolve the run's test \u2014 offline, or it left the model)"):["starting state",...[` - ${String(e.startingState.operations.length)} setup operations`,` - ${String(e.startingState.constraints.length)} state constraints`,` - actor: ${Ec(e)}`]].join(`
|
|
253
|
-
`)}function Ec(e){return e.actor.kind==="user"?`signed in as ${e.actor.alias}`:"signed out"}function Pc(e){return e.length===0?"":["facts checked here were declared in",...e.map(n=>` - ${n}`),""].join(`
|
|
254
|
-
`)}function Ic(e,r){return e.length===0?u.dim("timeline (no steps captured)"):["what happened, step by step",...e.map(t=>Ac(t,r))].join(`
|
|
255
|
-
`)}function Ac(e,r){let n=` ${String(e.index+1)}. ${e.title}${Tc(e.workflow)}${jc(e.url)}`,t=e.changes.length===0?[]:[` \u0394 ${e.changes.join(", ")}`],o=e.failures.map(s=>` ${u.bad("\u2717")} ${Mc(s,r)}`),i=e.checksHeld===0?[]:[u.dim(` ${String(e.checksHeld)} checks held`)];return[n,...t,...o,...i].join(`
|
|
256
|
-
`)}function Tc(e){if(e==null)return"";let r=`(${e})`;return` ${u.dim(r)}`}function jc(e){if(e==null)return"";let r=`@ ${e}`;return` ${u.dim(r)}`}function Mc(e,r){switch(e.kind){case"check":{let n=e.event.origin.kind==="fact"?Lc(r):"";return`${ln(e.event)}${n}`}case"stepError":return`run error \u2014 ${z(e.event.error)}`;case"finding":return Nc(e.payload)}}function Lc(e){if(e.length===0)return"";let r=`(fact from ${e.join(", ")})`;return` ${u.dim(r)}`}function Nc(e){switch(e.kind){case"unrunnable":{let r=e.unmet==null?"":`: needs ${e.unmet}`;return`couldn't run \u2014 ${e.reason}${r}`}case"impossibleAction":return`impossible action: ${e.action} on ${e.subject}`;case"liftVisibility":{let r=String(e.visibleIndex+1),n=String(e.declaredIndex+1);return`${e.subject} visible by step ${r} but declared at step ${n}`}}}function Uo(e){return`Saved behavior.jsonl to ${e.path}`}function re(e){switch(e.kind){case"config":return`Can't read project config (${e.detail}). Run this from your project root.`;case"request-failed":return"Couldn't reach the server. Check you're signed in with `npx ripplo auth`.";case"not-found":return"No run with that id.";case"not-uploaded":return"This run has no uploaded artifacts yet \u2014 it may still be running, or predates artifact upload.";case"download-failed":return`Download failed (HTTP ${String(e.status)}). The link may have expired \u2014 try again.`}}async function qo({full:e,json:r,runId:n}){let t=process.cwd(),o=await ee(t,n);o.isErr()&&(process.stderr.write(`${re(o.error)}
|
|
257
|
-
`),process.exit(1));let i=Eo(t,n).match(s=>s,s=>(process.stderr.write(`${Fo(s)}
|
|
258
|
-
`),process.exit(1)));process.stdout.write(`${r?JSON.stringify(i,null,2):Oo(i)}
|
|
259
|
-
`),e&&!r&&await Oc(t,n,Fc(i))}async function Oc(e,r,n){let t=y(e).unwrapOr(void 0);if(t==null)return;let o=await jo(e,r,t);process.stdout.write(`
|
|
260
|
-
${_o({...o,factOrigins:n})}
|
|
261
|
-
`)}function Fc(e){let r=e.failures.filter(n=>n.ruleKind==="fact").flatMap(n=>n.rules).flatMap(n=>n.origins).map(n=>n.sourcePath==null?n.intent:`${n.intent} (${n.sourcePath})`);return[...new Set(r)]}async function Bo({runId:e}){(await Ne(process.cwd(),e)).match(n=>{process.stdout.write(`${Uo(n)}
|
|
262
|
-
`)},n=>{process.stderr.write(`${re(n)}
|
|
263
|
-
`),process.exit(1)})}import{randomUUID as Wc}from"crypto";import{existsSync as Dc,readFileSync as _c}from"fs";import hr from"path";import{graphql as Vo}from"gql.tada";import{err as Fe,ok as Ho}from"neverthrow";async function zo(e,r,n){let t=Uc(e);if(t.kind==="error")return Fe(t.error);let o=t.config,i=await pe(e);if(i.result.isErr())return Fe({kind:"compile-failed"});let s=await qc({config:o,runId:r});if(s.kind==="error")return Fe(s.error);let{repro:a,reproJson:l}=s,c=await G(e,i.result.value),g=Sn(c);await vn({config:o,cwd:e,lockfile:c});let f=`replay-${Wc()}`,p=hr.join(e,".ripplo","debug"),E=[],A=ge({cacheDir:void 0,clientVersion:w(),debugDir:p,headed:!1,writeOtlpPortFile:!1});try{let $=await yn({capture:!0,lockfile:c,options:{baseUrl:o.appUrl,engineUrl:o.engineUrl,fixturesDir:hr.join(e,te),generate:zr,headed:!1,secret:o.webhookSecret},repro:a,runId:f,session:A,signal:n,onEvent:v=>{E.push(v)}});return(await Hc({config:o,debugDir:p,events:E,lockfileHash:g,outcome:$,replayRunId:f,reproJson:l,stepSources:Bc({lockfile:c,repro:a})})).map(()=>({outcome:$,recordingCaptured:Vc(p,f),replayRunId:f}))}finally{await A.close()}}function Uc(e){return y(e).match(r=>({config:r,kind:"found"}),r=>({error:{detail:r.kind,kind:"config"},kind:"error"}))}async function qc({config:e,runId:r}){let n=await d({config:e,document:zc,variables:{id:r}}).catch(()=>null);if(n==null)return{error:{kind:"request-failed"},kind:"error"};if(n.run==null)return{error:{kind:"not-found"},kind:"error"};let t=n.run.reproJson;if(t==null)return{error:{kind:"no-repro"},kind:"error"};let o=fe(t);return o.kind==="rejected"?{error:{kind:"stale-repro",reason:"format-unsupported"},kind:"error"}:{kind:"found",repro:o.repro,reproJson:t}}function Bc({lockfile:e,repro:r}){let n=tn(e);return r.steps.map(t=>n.find(o=>o.id===t.transitionId)?.test??null)}async function Hc({config:e,debugDir:r,events:n,lockfileHash:t,outcome:o,replayRunId:i,reproJson:s,stepSources:a}){if(o.kind!=="resolved"&&o.kind!=="still-fails")return Ho(void 0);try{return await d({config:e,document:Kc,variables:{lockfileHash:t,projectId:e.projectId,reproJson:s,runId:i}}),await ft({config:e,debugDir:r,events:n,recordingOptional:!0,runId:i,stepSources:a}),await Q({config:e,debugDir:r,runId:i}),Ho(void 0)}catch{return Fe({kind:"report-failed"})}}function Vc(e,r){let n=hr.join(e,r,"behavior.jsonl");return Dc(n)?_c(n,"utf8").split(`
|
|
264
|
-
`).some(t=>t.includes('"kind":"rrweb"')):!1}var zc=Vo(`
|
|
265
|
-
query RunRepro($id: String!) {
|
|
266
|
-
run(id: $id) {
|
|
38
|
+
`);function El(e){return e[0]===hl&&e[1]===gl?gunzipSync(e):e}async function Et(e){let t=gt(e);return existsSync(t)?ok(t):(await Hn(e)).map(n=>n.path)}function Gn(e){return e.shape==="legacy"?e.title:e.action==null?e.nodeType:Ut(e.action).map(t=>t.text).join(" ")}var Ol=4e3,Tl=5;function Jn({behaviorFile:e,runId:t}){let r=xl(readFileSync(e,"utf8")),n=[...r.failedChecks.map(o=>Al(o,r)),...r.stepErrors.map(o=>Nl(o,r)),...r.findings.map(o=>Dl(o,r))].toSorted((o,s)=>o.snapshotOffsetMs-s.snapshotOffsetMs);return {durationMs:Math.max(0,r.lastTs-r.firstTs),failures:n,runId:t,steps:[...r.stepTitles].map(([o,s])=>({index:o,title:s}))}}function xl(e){let t=Pe(e),r=t.map(n=>ge(n.timeNanos)).filter(n=>n>0);return {causes:t.flatMap(n=>vl(n)),failedChecks:t.filter(n=>n.kind==="check"&&n.outcome.kind==="failed"),findings:t.filter(n=>n.kind==="finding"),firstTs:r.length===0?0:Math.min(...r),lastTs:r.length===0?0:Math.max(...r),stepErrors:t.filter(n=>n.kind==="stepError"),stepTitles:new Map(t.flatMap(n=>n.kind==="step"?[[n.stepIndex,Gn(n)]]:[]))}}function vl(e){let t=wl(e);return t==null?[]:[{detail:t,timestamp:ge(e.timeNanos)}]}function wl(e){return e.kind==="network"?{kind:"network",method:e.method,status:e.status,traceId:e.traceId,url:e.url}:e.kind==="console"?e.level==="error"||e.level==="warning"?{kind:"console",level:e.level,text:e.text}:null:e.kind==="span"?{durationMs:e.durationMs,kind:"span",name:e.name,statusCode:e.status.code,traceId:e.traceId}:null}function Al(e,t){let r=ge(e.timeNanos);return {causes:lr(t.causes,r),error:void 0,label:Cl(e),outcome:"failed",snapshotOffsetMs:cr(t,r),step:Zn(t,e.stepIndex),stepIndex:e.stepIndex,waitMs:e.waitedMs}}function lr(e,t){let r=e.filter(n=>n.timestamp<=t&&n.timestamp>=t-Ol).toSorted((n,o)=>o.timestamp-n.timestamp);return kl(r).toSorted((n,o)=>Number(Kn(o.detail))-Number(Kn(n.detail))).slice(0,Tl).map(n=>({deltaMs:t-n.timestamp,detail:n.detail}))}function kl(e){let t=e.toReversed().map(r=>[Il(r.detail),r]);return [...new Map(t).values()].toReversed()}function Il(e){switch(e.kind){case "network":return `net ${e.method} ${String(e.status)} ${e.url.split("?")[0]??""}`;case "console":return `console ${e.text}`;case "span":return `span ${e.name} ${e.statusCode}`}}function Kn(e){switch(e.kind){case "network":return e.status>=400;case "span":return e.statusCode==="error";case "console":return true}}function Cl(e){let t=Lt(e);return t??`${e.family} ${Pl(e)}: ${e.outcome.kind}`}function Pl(e){switch(e.family){case "element":case "content":case "scalar":case "action":return Se(e);case "state":return e.subject;case "frame":return Ll(e);case "dataRule":return e.rule}}function Ll(e){if(e.outcome.kind==="passed")return e.family;let t=e.outcome.reason;return t.kind==="wrongScalar"||t.kind==="wrongElementState"||t.kind==="wrongElementContent"?t.subject:t.kind==="wrongCount"?t.entity:`${t.entity} [${t.key}]`}function cr(e,t){return Math.max(0,t-e.firstTs)}function Zn(e,t){return e.stepTitles.get(t)??String(t)}function Nl(e,t){let r=ge(e.timeNanos);return {causes:lr(t.causes,r),error:e.error,label:`driver ${e.error.kind}`,outcome:"error",snapshotOffsetMs:cr(t,r),step:Zn(t,e.stepIndex),stepIndex:e.stepIndex,waitMs:void 0}}function Dl(e,t){let r=ge(e.timeNanos);return {causes:lr(t.causes,r),error:void 0,label:Ul(e.payload),outcome:"failed",snapshotOffsetMs:cr(t,r),step:e.step,stepIndex:e.stepIndex,waitMs:void 0}}function Ul(e){switch(e.kind){case "unrunnable":return e.unmet==null?`${e.kind} ${e.reason}`:`${e.kind} ${e.reason}: ${e.unmet}`;case "impossibleAction":return `${e.kind} ${e.action}`;case "liftVisibility":return `${e.kind} ${e.subject}`}}function bt(e){switch(e.kind){case "not-signed-in":return ur();case "not-found":return "No run with that id.";case "not-uploaded":return "This run has no uploaded artifacts yet. It may still be running.";case "download-failed":return `Download failed (HTTP ${String(e.status)}). The link may have expired, try again.`}}function ur(){return "Not signed in. Run `npx ripplo login` first."}async function Xn({runId:e}){let t=await Et(e);t.isErr()&&(process.stderr.write(`${bt(t.error)}
|
|
39
|
+
`),process.exit(1));let r=Jn({behaviorFile:t.value,runId:e});process.stdout.write(`${JSON.stringify(r,null,2)}
|
|
40
|
+
`);}function Qn(e){return `No code review with id ${e}, or you do not have access to it.`}function eo(e){return `Code review ${e} has no published attempt yet. Wait for the review to finish.`}var jl=graphql(`
|
|
41
|
+
query CliCodeReviewIssues($id: String!) {
|
|
42
|
+
codeReview(id: $id) {
|
|
267
43
|
id
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
mutation CreateReplayRun(
|
|
273
|
-
$projectId: String!
|
|
274
|
-
$runId: String!
|
|
275
|
-
$reproJson: String
|
|
276
|
-
$lockfileHash: String!
|
|
277
|
-
) {
|
|
278
|
-
createExploreRun(
|
|
279
|
-
projectId: $projectId
|
|
280
|
-
runId: $runId
|
|
281
|
-
reproJson: $reproJson
|
|
282
|
-
lockfileHash: $lockfileHash
|
|
283
|
-
) {
|
|
284
|
-
id
|
|
285
|
-
}
|
|
286
|
-
}
|
|
287
|
-
`);function Ko({outcome:e,recordingCaptured:r,replayRunId:n}){let t=Gc(e);if(e.kind!=="resolved"&&e.kind!=="still-fails")return t;let o=r?"":"\n! No page recording was captured \u2014 the page may never have loaded. Treat this verdict with suspicion and confirm with `npx ripplo run`.",i=e.kind==="resolved"?`
|
|
288
|
-
! A clean replay confirms the fix but doesn't explain the original failure. Classify the root cause \u2014 app bug or model gap \u2014 before you resolve. Don't file it as flake unless you know why it flaked.`:"";return`${t}${o}${i}
|
|
289
|
-
Replay run ${n} \u2014 snapshot it, or cite it as resolve proof: \`npx ripplo tasks resolve <id> --run ${n}\`.`}function Gc(e){switch(e.kind){case"resolved":return"\u2713 Resolved \u2014 the finding's trail ran clean.";case"still-fails":return`\u2717 Still failing \u2014 ${j(e.contradictions.length,"check")} still mismatch.`;case"unplannable":return"! Model changed \u2014 this trail's base state or actions no longer exist. Use `npx ripplo compile` and `npx ripplo run`.";case"state-unavailable":return`! Couldn't run the trail (${e.reason}).`;case"aborted":return"Replay aborted."}}function Go(e){switch(e.kind){case"config":return`Can't read project config (${e.detail}). Run from your project root.`;case"compile-failed":return"Couldn't compile the local `.ripplo/` model. Run `npx ripplo compile` first.";case"request-failed":return"Couldn't reach the server. Check you're signed in with `npx ripplo auth`.";case"not-found":return"No run with that id.";case"no-repro":return"This run has no replayable trail \u2014 predates repro capture, or isn't an explore finding.";case"report-failed":return"The replay finished but couldn't be registered with the server, so its id won't work as resolve proof. Check you're signed in, then rerun `npx ripplo replay`.";case"stale-repro":return"This finding uses an older explorer trail format and cannot be replayed. Let the explorer reconcile stale findings."}}function Jo(e){return e.kind==="resolved"}async function Qo({runId:e}){(await zo(process.cwd(),e,new AbortController().signal)).match(n=>{process.stdout.write(`${Ko(n)}
|
|
290
|
-
`),process.exit(Jo(n.outcome)?0:1)},n=>{process.stderr.write(`${Go(n)}
|
|
291
|
-
`),process.exit(1)})}import si from"path";import{existsSync as ru}from"fs";import{writeFile as ti}from"fs/promises";import oi from"path";import{err as ae,ok as nu}from"neverthrow";import{readFile as Jc}from"fs/promises";import{z as se}from"zod";var Qc={height:800,width:1280};async function Zo(e){let r=await Jc(e,"utf8");return H(r).flatMap(n=>n.kind==="rrweb"?[n.event]:[])}var Zc=se.object({data:se.looseObject({height:se.number(),width:se.number()}),type:se.literal(4)});function kr(e){let r=e.flatMap(n=>{let t=Zc.safeParse(n);return t.success?[t.data]:[]})[0];return r==null?Qc:{height:r.data.height,width:r.data.width}}var Xc='<svg xmlns="http://www.w3.org/2000/svg" width="17" height="22" viewBox="0 0 17 22"><path d="M1 1 L1 17 L5.4 12.8 L8.5 20 L11 19 L8 11.8 L14 11.8 Z" fill="black" stroke="white" stroke-width="1.3"/></svg>',Yc=`.replayer-mouse-tail { display: none; }
|
|
292
|
-
.replayer-mouse {
|
|
293
|
-
position: absolute;
|
|
294
|
-
width: 17px;
|
|
295
|
-
height: 22px;
|
|
296
|
-
z-index: 9999;
|
|
297
|
-
background-repeat: no-repeat;
|
|
298
|
-
background-size: contain;
|
|
299
|
-
background-image: url('data:image/svg+xml;utf8,${Xc}');
|
|
300
|
-
}`,eu=".replayer-mouse, .replayer-mouse-tail { display: none; }";function Xo(e){return`<!doctype html><html><head><style>
|
|
301
|
-
html, body { margin: 0; padding: 0; }
|
|
302
|
-
.replayer-wrapper { position: relative; }
|
|
303
|
-
${e?Yc:eu}
|
|
304
|
-
iframe { border: none; }
|
|
305
|
-
</style></head><body></body></html>`}var Yo="*, *::before, *::after { animation-duration: 0s !important; animation-delay: 0s !important; transition-duration: 0s !important; transition-delay: 0s !important; }";function ei(){return`(async () => {
|
|
306
|
-
const doc = document.querySelector(".replayer-wrapper iframe")?.contentDocument;
|
|
307
|
-
if (doc?.fonts != null) {
|
|
308
|
-
await doc.fonts.ready;
|
|
309
|
-
}
|
|
310
|
-
await new Promise((resolve) => requestAnimationFrame(() => requestAnimationFrame(resolve)));
|
|
311
|
-
})()`}function ri(){return import("playwright").then(({chromium:e})=>e.launch({args:["--no-sandbox"],headless:!0})).catch(()=>null)}var ni=mn(pn("@ripplo/rrweb-bundle/replay","rrweb-replay.js"));async function ii({jsonlPath:e,moment:r,outDir:n,runId:t}){if(!ru(e))return ae({kind:"run-not-found",runId:t});let o=await Zo(e),i=o[0],s=o.at(-1);if(i==null||s==null)return ae({kind:"no-rrweb-events",runId:t});let a=s.timestamp-i.timestamp,l=r.kind==="offset"?r.offsetMs:r.at-i.timestamp;if(l<0)return ae({durationMs:a,firstTimestamp:i.timestamp,kind:"moment-out-of-range",lastTimestamp:s.timestamp,moment:r});let c=Math.min(l,a),g=String(Math.round(c)),f=oi.join(n,`snapshot-${g}ms.png`),p=oi.join(n,`snapshot-${g}ms.html`);return(await tu({events:o,htmlPath:p,offsetMs:c,pngPath:f})).map(()=>({durationMs:a,htmlPath:p,offsetMs:c,pngPath:f,viewport:kr(o)}))}async function tu({events:e,htmlPath:r,offsetMs:n,pngPath:t}){let o=await ri();if(o==null)return ae({detail:"chromium launch",kind:"browser-failed"});try{let{html:i,png:s}=await ou({browser:o,events:e,offsetMs:n});return await ti(t,s),await ti(r,i,"utf8"),nu(void 0)}catch(i){return ae({detail:i instanceof Error?i.message:String(i),kind:"browser-failed"})}finally{await o.close()}}async function ou({browser:e,events:r,offsetMs:n}){let t=kr(r),o=await e.newPage({viewport:t});await o.setContent(Xo(!1)),await o.addScriptTag({content:await ni()}),await o.evaluate(iu({events:r,offsetMs:n})),await o.evaluate(ei());let i=o.locator(".replayer-wrapper iframe").first(),a=await(await i.count()>0?i:o).screenshot({type:"png"});return{html:await o.evaluate(su()),png:a}}function iu({events:e,offsetMs:r}){return`(() => {
|
|
312
|
-
const replayer = new globalThis.__RipploReplayer(${JSON.stringify(e)}, {
|
|
313
|
-
insertStyleRules: [${JSON.stringify(Yo)}],
|
|
314
|
-
mouseTail: false,
|
|
315
|
-
root: document.body,
|
|
316
|
-
showWarning: false,
|
|
317
|
-
});
|
|
318
|
-
replayer.pause(${String(r+.5)});
|
|
319
|
-
globalThis.__ripploSnapshotReplayer = replayer;
|
|
320
|
-
})()`}function su(){return`(() => {
|
|
321
|
-
const replayer = globalThis.__ripploSnapshotReplayer;
|
|
322
|
-
if (replayer == null) {
|
|
323
|
-
return "";
|
|
324
|
-
}
|
|
325
|
-
const mirror = replayer.getMirror();
|
|
326
|
-
const iframe = document.querySelector(".replayer-wrapper iframe");
|
|
327
|
-
const doc = iframe == null ? null : iframe.contentDocument;
|
|
328
|
-
if (doc == null) {
|
|
329
|
-
return "";
|
|
330
|
-
}
|
|
331
|
-
Array.from(doc.querySelectorAll("*")).forEach((el) => {
|
|
332
|
-
const id = mirror.getId(el);
|
|
333
|
-
if (id != null && id > 0) {
|
|
334
|
-
el.setAttribute("data-rrweb-id", String(id));
|
|
335
|
-
}
|
|
336
|
-
});
|
|
337
|
-
return "<!doctype html>\\n" + doc.documentElement.outerHTML;
|
|
338
|
-
})()`}function ai({cwd:e,moment:r,runId:n}){let t=si.join(e,".ripplo","debug",n);return ii({jsonlPath:si.join(t,"behavior.jsonl"),moment:r,outDir:t,runId:n})}function li(e){return[`${u.good("ok")} \u2014 rendered the page at ${String(Math.round(e.offsetMs))}ms into the recording (duration ${String(Math.round(e.durationMs))}ms, viewport ${String(e.viewport.width)}\xD7${String(e.viewport.height)})`,e.pngPath,"Read the PNG above to see the page state. Layout and text are faithful \u2014 URL-referenced images may be blank if the dev server is down.",e.htmlPath,"The HTML is the same frame with every element tagged `data-rrweb-id`. Grep it for your element's class or text to get the id for `tasks comment --element`."].join(`
|
|
339
|
-
`)}function di(e){return`${u.bad("fail")} \u2014 ${au(e)}`}function ci(){return`${u.bad("fail")} \u2014 pass exactly one of --at <epoch-ms from behavior.jsonl> or --offset <ms from the start of the recording>.`}function au(e){switch(e.kind){case"run-not-found":return`no debug artifacts for run ${e.runId} (.ripplo/debug/${e.runId}/behavior.jsonl missing). ${R("run")}`;case"no-rrweb-events":return`run ${e.runId} has a behavior.jsonl but no rrweb events \u2014 nothing to replay.`;case"moment-out-of-range":return`${e.moment.kind==="offset"?"--offset":"--at"} is outside the recording, which spans ${String(e.firstTimestamp)}\u2013${String(e.lastTimestamp)} (duration ${String(e.durationMs)}ms). Pass --at <epoch-ms from behavior.jsonl> or --offset <0\u2013${String(e.durationMs)}>.`;case"browser-failed":return`replay browser failed (${e.detail}). Is chromium installed? Try \`npx playwright install chromium\`.`}}async function ui({at:e,offset:r,runId:n}){let t=lu({at:e,offset:r});t==null&&(process.stderr.write(`${ci()}
|
|
340
|
-
`),process.exit(1));let o=await ee(process.cwd(),n);o.isErr()&&(process.stderr.write(`${re(o.error)}
|
|
341
|
-
`),process.exit(1)),(await ai({cwd:process.cwd(),moment:t,runId:n})).match(s=>{process.stdout.write(`${li(s)}
|
|
342
|
-
`)},s=>{process.stderr.write(`${di(s)}
|
|
343
|
-
`),process.exit(1)})}function lu({at:e,offset:r}){if(e!=null&&r==null)return{at:e,kind:"absolute"};if(r!=null&&e==null)return{kind:"offset",offsetMs:r}}function pi(e,r){switch(e.kind){case"config-failed":return S(e.failure);case"compile-failed":return J(e.error);case"no-test":return`test "${e.ref}" not found \u2014 run npx ripplo compile to see available tests`;case"unplannable":return"the recorded walk no longer matches the model \u2014 run npx ripplo compile, then re-run";case"run-failed":return`teleport failed before reaching the step: ${z(e.error)}`;case"done":return du(e.result,r)}}function mi(e){return e.kind==="done"&&e.result.kind==="handed-over"}function fi(e,r){return`landed at step ${String(e)} of ${r} \u2014 close the window to tear down`}function du(e,r){return e.kind==="failed"?`couldn't reach the step \u2014 the run failed first.
|
|
344
|
-
|
|
345
|
-
${e.contradictions.map(t=>an({contradiction:t,evidencePath:void 0})).join(`
|
|
346
|
-
|
|
347
|
-
`)}`:`torn down \u2014 teleport session for ${r} ended`}async function gi({ref:e,step:r}){let n=new AbortController;process.once("SIGINT",()=>{n.abort()});let t=()=>{process.stdout.write(`${fi(r,e)}
|
|
348
|
-
`)},o=await wt({cwd:process.cwd(),onReady:t,signal:n.signal,step:r,target:{kind:"test",ref:e}});process.stdout.write(`${pi(o,e)}
|
|
349
|
-
`),process.exit(mi(o)?0:1)}import yi from"path";import{randomUUID as cu}from"crypto";async function hi({cwd:e,onReady:r,signal:n}){let t=y(e).match(s=>s,s=>s.kind);if(typeof t=="string")return{detail:t,kind:"config-failed"};let o=`capture-${cu()}`;return(await fn({clientVersion:w(),debugDir:yi.join(t.cwd,".ripplo","debug"),onReady:r,profileDir:yi.join(t.cwd,".ripplo",".local","capture-profile"),runId:o,startUrl:t.appUrl},n)).match(s=>({behaviorPath:s.behaviorPath,kind:"done",runId:o}),s=>({error:s,kind:"run-failed"}))}function ki(){return"Capturing. Sign in if needed, click through your flow, then press Ctrl-C here to finish. Your login is remembered for next time."}function wi(e){return e.kind==="config-failed"?`Could not read project config: ${e.detail}`:e.kind==="run-failed"?"Capture failed to start. Could not launch the browser.":uu(e.behaviorPath,e.runId)}function bi(e){return e.kind==="done"}function uu(e,r){return[`Capture saved to ${e}`,"","Paste this to Claude Code to model the journey:",""," Load /ripplo:create. Turn this session into one critical Ripplo user journey under .ripplo/workflows/.","",` 1. Run \`npx ripplo clickpath ${r}\`. Name the user's intent, natural entry point, and actions that belong to that intent. Omit capture detours that are not part of the journey.`,` 2. Read ${e} for state-source requests and spans. Add only relevant paths to .ripplo/state.ts. Write the widest starting-state constraints valid for the whole journey.`," 3. Keep state-rendered values connected through handles and arbitrary(field). Use exact(value) only when the literal drives behavior."," 4. Declare every visible outcome and complete state effect, including cascades. Make every effect provably change state."," 5. Run `npx ripplo compile`, complete the /ripplo:create generality audit, then run the workflow."].join(`
|
|
350
|
-
`)}async function vi(){let e=new AbortController;process.once("SIGINT",()=>{e.abort()});let r=await hi({cwd:process.cwd(),onReady:pu,signal:e.signal});process.stdout.write(`${wi(r)}
|
|
351
|
-
`),process.exit(bi(r)?0:1)}function pu(){process.stdout.write(`${ki()}
|
|
352
|
-
`)}import{existsSync as mu,readFileSync as fu}from"fs";import gu from"path";function Si(e,r){let n=gu.join(e,".ripplo","debug",r,"behavior.jsonl");return mu(n)?{actions:gn(fu(n,{encoding:"utf8"})),kind:"ok"}:{kind:"not-found",runId:r}}function xi(e){return e.kind==="not-found"?`No capture found for run ${e.runId}. Run npx ripplo capture first.`:e.actions.length===0?"No user actions found in this capture.":e.actions.map((r,n)=>yu(r,n)).join(`
|
|
353
|
-
`)}function Ri(e){return e.kind==="ok"}function yu(e,r){let n=e.element,t=n?.role??n?.tag??"?",o=n?.ariaLabel??n?.text;return[`${String(r+1)}.`,e.kind.padEnd(6),t.padEnd(10),o==null?"":`name=${JSON.stringify(o)}`,n?.testId==null?"":`testId=${n.testId}`,e.value==null?"":`value=${JSON.stringify(e.value)}`].filter(s=>s.length>0).join(" ")}function Ci({runId:e}){let r=Si(process.cwd(),e);process.stdout.write(`${xi(r)}
|
|
354
|
-
`),process.exit(Ri(r)?0:1)}async function $i(){let e=b();try{let n=(await oe(e.cwd,e)).match(t=>t,t=>{process.stderr.write(`${S(t)}
|
|
355
|
-
`),process.exit(1)});process.stdout.write(`Synced ${String(n.lockfile.workflows.length)} workflows to dev session ${n.devSessionId}
|
|
356
|
-
`)}catch(r){let n=r instanceof Error?r.message:String(r);process.stderr.write(`ripplo sync failed: ${n}
|
|
357
|
-
`),process.stderr.write(`${R("setup","verify auth + server reachability")}
|
|
358
|
-
`),process.exit(1)}}import{spawnSync as bu}from"child_process";import vu from"fs";import Su from"path";import xu from"semver";import le from"fs";import hu from"os";import q from"path";function Ei(e){let r=e.split(q.sep);return r.includes("_npx")?"npx":e.includes(q.join("packages","cli"))?"workspace":ku(r)?"local":"global"}function Pi(){let e=q.join(hu.homedir(),".npm","_npx");return le.existsSync(e)?le.readdirSync(e).map(r=>q.join(e,r)).filter(r=>le.existsSync(q.join(r,"node_modules","ripplo"))).map(r=>(le.rmSync(r,{force:!0,recursive:!0}),r)):[]}function ku(e){let r=e.lastIndexOf("node_modules");if(r<1)return!1;let n=e.slice(0,r).join(q.sep);return le.existsSync(q.join(n,"package.json"))}import{spawnSync as Ii}from"child_process";var wu=["user","project","local"];function wr(){return Ii("claude",["--version"],{stdio:"ignore"}).error!=null?"claude-missing":wu.find(n=>Ii("claude",["plugin","update","ripplo","--scope",n],{stdio:"ignore"}).status===0)==null?"not-installed":"updated"}function Ai(e){return`ripplo v${e} is already the latest version.`}function Ti(e){return`ripplo v${e}: could not reach the npm registry to check for updates.`}function br({evicted:e,latest:r,mode:n}){return n==="npx"?`ripplo: ${e===0?"npx cache had no stale copy":`cleared ${j(e,"stale npx cache entry","stale npx cache entries")}`} \u2014 the next \`npx ripplo\` command runs v${r}.`:`ripplo: updated global install to v${r}.`}function ji(){return"ripplo: this is a workspace build (packages/cli/dist) \u2014 update via git pull + `pnpm --filter ripplo build`."}function Mi(e){return`ripplo: installed as a project dependency \u2014 update it with your package manager: \`${e}\``}function Li(e){return`ripplo: \`npm install -g ripplo@latest\` failed: ${e}`}function vr(e){switch(e){case"updated":return"ripplo: Claude plugin updated \u2014 restart Claude Code (or /reload-plugins) to apply.";case"not-installed":return"ripplo: Claude plugin not installed in this project \u2014 skipped.";case"claude-missing":return"ripplo: claude binary not found \u2014 skipped plugin update."}}function Ni(e){return e?"ripplo: idle daemon stopped \u2014 the next `npx ripplo run` restarts it on the new version.":"ripplo: daemon is busy \u2014 it picks up the new version once idle (the next `npx ripplo run` handles it)."}var Ru=1e4;async function Oi(){let e=w(),r=process.argv[1];Cu(process.cwd());let n=await xe(Ru);process.stdout.write(`${ve({current:e,latest:n})}
|
|
359
|
-
`),n==null&&(process.stderr.write(`${Ti(e)}
|
|
360
|
-
`),process.exit(1)),xu.gt(n,e)||(process.stdout.write(`${Ai(e)}
|
|
361
|
-
`),process.stdout.write(`${vr(wr())}
|
|
362
|
-
`),process.exit(0));let t=r==null?"global":Ei(r);$u({latest:n,mode:t}),process.stdout.write(`${vr(wr())}
|
|
363
|
-
`),await Pu(process.cwd()),process.exit(0)}function Cu(e){if(!vu.existsSync(Su.join(e,".ripplo")))return;let r=Ee(e);r==="written"&&process.stdout.write(`${Pe(r).trim()}
|
|
364
|
-
`)}function $u({latest:e,mode:r}){if(r==="workspace"&&(process.stdout.write(`${ji()}
|
|
365
|
-
`),process.exit(0)),r==="local"){let n=process.cwd(),t=tr({cwd:n,pm:or(n),version:e});process.stdout.write(`${Mi(t)}
|
|
366
|
-
`),process.exit(0)}if(r==="npx"){let n=Pi();process.stdout.write(`${br({evicted:n.length,latest:e,mode:r})}
|
|
367
|
-
`);return}Eu(e)}function Eu(e){let r=`ripplo@${e}`,n=bu("npm",["install","-g",r],{stdio:"inherit"});if(n.status!==0){let t=`exit ${String(n.status)}`;process.stderr.write(`${Li(t)}
|
|
368
|
-
`),process.exit(1)}process.stdout.write(`${br({evicted:0,latest:e,mode:"global"})}
|
|
369
|
-
`)}async function Pu(e){if((await qn(e)).kind==="not-running")return;let n=await Un(e);process.stdout.write(`${Ni(n)}
|
|
370
|
-
`)}async function Fi({action:e,exploreDebug:r}){if(e==="status"){let{statusCommand:t}=await import("./status-XUIBJXNP.js");await t({format:"summary"});return}if(e==="stop"||e==="restart"){let t=await Iu();(e==="stop"||!t)&&process.exit(t?0:1)}Au();let{runDaemon:n}=await import("./daemon-6UYMYGPI.js");await n({exploreDebug:r})}async function Iu(){let{stopDevDaemon:e}=await import("./daemon-lock-RPKO5SNE.js"),{renderDaemonStopResult:r}=await import("./daemon-EITBDEP7.js"),n=await e(process.cwd());return process.stdout.write(`${r(n)}
|
|
371
|
-
`),n.kind!=="timeout"}function Au(){let e=Y(O());e!=null&&process.stderr.write(`${e}
|
|
372
|
-
`)}function Wi(e){return`executor: ${e}`}function Di(e){return e==="cloud"?"executor set to cloud \u2014 the daemon is bringing the tunnel up, the next run dispatches to the cloud fleet":"executor set to local \u2014 the next run executes on this machine"}function _i(e){switch(e.kind){case"no-session":return"No active dev session for this directory. Start `npx ripplo daemon` first.";case"starting":return"Dev session is still syncing \u2014 the daemon just started. Retry in a moment.";case"session-ended":return"The dev session ended before the switch landed. Check `npx ripplo daemon status` and try again.";case"empty-response":return"The server returned no result for the switch. Try again."}}async function Ui({mode:e}){let r=y(process.cwd()).match(t=>t,t=>{process.stderr.write(`${S(t)}
|
|
373
|
-
`),process.exit(1)});(e==null?await vt(r):await St(r,e)).match(t=>{process.stdout.write(`${e==null?Wi(t):Di(t)}
|
|
374
|
-
`)},t=>{process.stderr.write(`${_i(t)}
|
|
375
|
-
`),process.exit(1)})}import{spawnSync as Uu}from"child_process";import{graphql as qi}from"gql.tada";import{err as Sr,ok as xr}from"neverthrow";var Tu=qi(`
|
|
376
|
-
query ExploreState($devSessionId: String!) {
|
|
377
|
-
exploration(devSessionId: $devSessionId) {
|
|
378
|
-
active
|
|
379
|
-
autoCreateTasks
|
|
380
|
-
cloudWorkers
|
|
381
|
-
localWorkers
|
|
382
|
-
maxTrailLength
|
|
383
|
-
unhealthySince
|
|
384
|
-
}
|
|
385
|
-
}
|
|
386
|
-
`),ju=qi(`
|
|
387
|
-
mutation SetExploration(
|
|
388
|
-
$devSessionId: String!
|
|
389
|
-
$active: Boolean!
|
|
390
|
-
$autoCreateTasks: Boolean!
|
|
391
|
-
$cloudWorkers: Int!
|
|
392
|
-
$localWorkers: Int!
|
|
393
|
-
$maxTrailLength: Int!
|
|
394
|
-
) {
|
|
395
|
-
setExploration(
|
|
396
|
-
devSessionId: $devSessionId
|
|
397
|
-
active: $active
|
|
398
|
-
autoCreateTasks: $autoCreateTasks
|
|
399
|
-
cloudWorkers: $cloudWorkers
|
|
400
|
-
localWorkers: $localWorkers
|
|
401
|
-
maxTrailLength: $maxTrailLength
|
|
402
|
-
) {
|
|
403
|
-
active
|
|
404
|
-
autoCreateTasks
|
|
405
|
-
cloudWorkers
|
|
406
|
-
localWorkers
|
|
407
|
-
maxTrailLength
|
|
408
|
-
unhealthySince
|
|
409
|
-
}
|
|
410
|
-
}
|
|
411
|
-
`);async function Bi(e){let r=await Vi(e);if(r.isErr())return Sr(r.error);let n=await zi(e,r.value.id);return xr(Ki(r.value.executor,n))}async function Hi(e,r){let n=await Vi(e);if(n.isErr())return Sr(n.error);let t=await zi(e,n.value.id),o=Mu(n.value.executor,t,r),i=await d({config:e,document:ju,variables:{devSessionId:n.value.id,...o}});return xr(Ki(n.value.executor,i.setExploration))}async function Vi(e){let r=await Zn(e);return r.kind==="active"?xr({executor:r.executor,id:r.id}):Sr({kind:r.kind==="starting"?"starting":"no-session"})}async function zi(e,r){return(await d({config:e,document:Tu,variables:{devSessionId:r}})).exploration??null}function Ki(e,r){let n=e==="local";return{active:r?.active??!1,executor:e,maxTrailLength:r?.maxTrailLength??Ye,unhealthy:r?.unhealthySince!=null,workers:(n?r?.localWorkers:r?.cloudWorkers)??0}}function Mu(e,r,n){let t=e==="local",o=(t?r?.localWorkers:r?.cloudWorkers)??0,i=(t?r?.cloudWorkers:r?.localWorkers)??0,s=Lu(n,o);return{active:n.active,autoCreateTasks:r?.autoCreateTasks??!1,cloudWorkers:t?i:s,localWorkers:t?s:i,maxTrailLength:n.trail??r?.maxTrailLength??Ye}}function Lu(e,r){return e.active?e.workers!=null?e.workers:r>0?r:xt:r}function Gi(e){if(!e.active)return e.unhealthy?"explorer: off \u2014 paused after repeated infra errors, turn it back on with npx ripplo explore on":"explorer: off";let r=`explorer: on | ${String(e.workers)} workers | trail ${String(e.maxTrailLength)} | ${e.executor}`;return e.unhealthy?`${r}
|
|
412
|
-
explorer is hitting infra errors \u2014 it pauses if this persists`:r}function Ji(e){return e.active?`explorer on \u2014 walking ${String(e.workers)} background paths, trail ${String(e.maxTrailLength)}, on the ${e.executor} executor. Findings land as tasks \u2014 triage with /ripplo:tasks`:"explorer off \u2014 background exploration stopped"}function Qi(e){return e.kind==="starting"?"Dev session is still syncing \u2014 the daemon just started. Retry in a moment.":"No active dev session for this directory. Start `npx ripplo daemon` first."}var Nu=32;async function Zi({cwd:e,maxTrailLength:r}){let n=await pe(e);if(n.result.isErr())return{kind:"error",reason:"compile-failed"};let t=await he(e);if(t==null)return{kind:"error",reason:"no-lockfile"};let o=await G(e,n.result.value),i=cn(o);return i.kind==="model-empty"?{kind:"error",reason:"model-empty"}:{analysis:await un({attempts:Nu,modelHash:t,prepared:i.value,strategy:r==null?Ke("even"):{...Ke("even"),maxAttemptLength:r}}),kind:"ok"}}function Yi(e){return["Explorer model analysis",`${String(e.plannedPaths)} of ${String(e.attempts)} agendas produced complete paths.`,`${String(e.transitionsReached)} of ${String(e.transitionCount)} transitions were reached across ${String(e.composablePairs)} adjacent transition pairs.`,`${String(e.envelopesReached)} starting-state families and ${String(e.crossWorkflowPaths)} cross-workflow paths were used.`,Ou(e),Fu(e),Wu(e),Du(e),`Reached patterns: ${e.patternsReached.length===0?"none":e.patternsReached.join(", ")}.`,`${String(e.isolatedTransitions.length)} of ${String(e.targetsAnalyzed)} targeted transitions were unreachable. ${String(e.weaklyConnectedTransitions.length)} appeared in only one planned path.`,...Xi({heading:"Targets without a proved path:",transitions:e.isolatedTransitions}),...Xi({heading:"Targets reached in one planned path:",transitions:e.weaklyConnectedTransitions}),..._u(e.recommendations)].join(`
|
|
413
|
-
`)}function es(e){switch(e){case"compile-failed":return"Explorer analysis could not load the workflow model. Run npx ripplo compile and fix the reported errors.";case"model-empty":return"Explorer analysis found no runnable workflows. Add a workflow with a modeled navigation step.";case"no-lockfile":return"Explorer analysis could not find .ripplo/ripplo.lock. Run npx ripplo compile."}}function Ou(e){let r=e.planningDepth;return`Path length target: ${String(r.targetSteps)} steps. Planned ${de(r.averagePlannedSteps)} on average and ${String(r.maxPlannedSteps)} at most after searching ${de(r.averageSearchedSteps)} on average and ${String(r.maxSearchedSteps)} at most. Search stopped at the target ${String(r.searchStops.targetReached)} times, exhausted legal continuations ${String(r.searchStops.frontierExhausted)} times, and exhausted its budget ${String(r.searchStops.budgetExhausted)} times.`}function de(e){return String(Math.round(e))}function Fu(e){let r=e.planningPerformance;return`Planner average: ${D(r.total.averageMs)} total, ${D(r.envelopes.averageMs)} starting states, ${D(r.search.averageMs)} search, and ${D(r.selection.averageMs)} selection. Total p95: ${D(r.total.p95Ms)}.`}function D(e){return`${String(Math.round(e))} ms`}function Wu(e){let r=e.planningPerformance;return`Search average: ${D(r.expansion.averageMs)} proving runnable steps, ${D(r.candidates.averageMs)} scoring candidates, and ${D(r.beam.averageMs)} retaining the beam.`}function Du(e){let r=e.planningWork;return`Search average: ${de(r.averageExpandedNodes)} expanded nodes after considering ${de(r.averageRulesConsidered)} transitions and ${de(r.averageParameterAttempts)} parameter attempts.`}function Xi({heading:e,transitions:r}){return r.length===0?[]:[e,...r.map(n=>`- ${n.test}: ${n.action}`)]}function _u(e){return e.length===0?["No workflow coverage improvements are required by this analysis."]:["Recommendations:",...e.map(r=>`- ${r}`)]}async function rs({json:e,state:r,trail:n,workers:t}){if(r==="analyze"){qu();let s=await Zi({cwd:process.cwd(),maxTrailLength:n});s.kind==="error"&&(process.stderr.write(`${es(s.reason)}
|
|
414
|
-
`),process.exit(1)),process.stdout.write(`${e?JSON.stringify(s.analysis,null,2):Yi(s.analysis)}
|
|
415
|
-
`);return}let o=y(process.cwd()).match(s=>s,s=>{process.stderr.write(`${S(s)}
|
|
416
|
-
`),process.exit(1)});(r==null?await Bi(o):await Hi(o,{active:r==="on",trail:n,workers:t})).match(s=>{process.stdout.write(`${r==null?Gi(s):Ji(s)}
|
|
417
|
-
`)},s=>{process.stderr.write(`${Qi(s)}
|
|
418
|
-
`),process.exit(1)})}function qu(){let e=O();e.kind!=="fresh"&&(e.kind==="foreign-binary"&&We(Y(e)??"This command is not using the workspace CLI."),process.stderr.write(`${Ae(e.packages)}
|
|
419
|
-
`),we(e.workspaceRoot)||We(Te()),Bu())}function We(e){process.stderr.write(`${e}
|
|
420
|
-
`),process.exit(1)}function Bu(){let e=process.argv[1];e==null&&We("Ripplo rebuilt the workspace but could not find the CLI entry point.");let r=Uu(process.execPath,[e,...process.argv.slice(2)],{cwd:process.cwd(),stdio:"inherit"});r.error!=null&&We(`Ripplo rebuilt the workspace but could not restart analysis: ${r.error.message}`),process.exit(r.status??1)}import{graphql as De}from"gql.tada";function ns(){return"No scope items added \u2014 matched tests already in scope (`npx ripplo scope status`)."}function ts(e){return[`No test found for: ${e.join(", ")}`,"Pass a test id (kebab-case slug) or the exact intent string. List tests with `npx ripplo status`.",R("create")].join(`
|
|
421
|
-
`)}import{graphql as Hu}from"gql.tada";var os=Hu(`
|
|
422
|
-
query ScopeStatus($projectId: String!, $cwd: String!) {
|
|
423
|
-
project(id: $projectId) {
|
|
424
|
-
id
|
|
425
|
-
devSession(cwd: $cwd) {
|
|
426
|
-
id
|
|
427
|
-
scopeItems {
|
|
428
|
-
id
|
|
429
|
-
label
|
|
430
|
-
source
|
|
431
|
-
workflow {
|
|
432
|
-
id
|
|
433
|
-
slug
|
|
434
|
-
name
|
|
435
|
-
spec
|
|
436
|
-
}
|
|
437
|
-
}
|
|
438
|
-
}
|
|
439
|
-
}
|
|
440
|
-
}
|
|
441
|
-
`);var Vu=De(`
|
|
442
|
-
query ScopeWorkflowBySlug($projectId: String!, $cwd: String!, $slug: String!) {
|
|
443
|
-
project(id: $projectId) {
|
|
444
|
-
id
|
|
445
|
-
devSession(cwd: $cwd) {
|
|
446
|
-
id
|
|
447
|
-
workflows(where: { slug: $slug }) {
|
|
448
|
-
id
|
|
449
|
-
slug
|
|
450
|
-
}
|
|
451
|
-
}
|
|
452
|
-
}
|
|
453
|
-
}
|
|
454
|
-
`),zu=De(`
|
|
455
|
-
mutation ScopeAddDirtyTests($projectId: String!, $cwd: String!, $workflowSlugs: [String!]!) {
|
|
456
|
-
addDirtyTestsToScope(projectId: $projectId, cwd: $cwd, workflowSlugs: $workflowSlugs) {
|
|
457
|
-
__typename
|
|
458
|
-
... on MutationAddDirtyTestsToScopeSuccess {
|
|
459
|
-
data {
|
|
460
|
-
id
|
|
461
|
-
workflow {
|
|
462
|
-
id
|
|
463
|
-
slug
|
|
464
|
-
}
|
|
465
|
-
}
|
|
466
|
-
}
|
|
467
|
-
... on NoActiveDevSessionError {
|
|
468
|
-
message
|
|
469
|
-
}
|
|
470
|
-
... on UnknownWorkflowSlugsError {
|
|
471
|
-
message
|
|
472
|
-
slugs
|
|
473
|
-
}
|
|
474
|
-
}
|
|
475
|
-
}
|
|
476
|
-
`),Ku=De(`
|
|
477
|
-
mutation ScopeLink($id: ID!, $workflowId: String!) {
|
|
478
|
-
linkScopeItem(id: $id, workflowId: $workflowId) {
|
|
479
|
-
id
|
|
480
|
-
}
|
|
481
|
-
}
|
|
482
|
-
`),Gu=De(`
|
|
483
|
-
mutation ScopeRemoveMany($ids: [ID!]!) {
|
|
484
|
-
removeScopeItems(ids: $ids)
|
|
485
|
-
}
|
|
486
|
-
`);async function is(e){let r=b();await x(r);let t=(await d({config:r,document:os,variables:{cwd:r.cwd,projectId:r.projectId}})).project?.devSession?.scopeItems??[];if(e.format==="json"){process.stdout.write(`${JSON.stringify(t,null,2)}
|
|
487
|
-
`);return}if(t.length===0){process.stdout.write("No scope items. Add some with `npx ripplo scope add <test-ids..>` or from the dashboard.\n");return}t.forEach(o=>{let i=o.workflow;if(i==null){process.stdout.write(` [intent] (${o.id}) ${o.label??""}
|
|
488
|
-
`);return}let s=i.spec==null?"stub":"implemented";process.stdout.write(` [${s}] (${o.id}) ${i.slug} \u2014 ${i.name}
|
|
489
|
-
`)})}async function ss({testIds:e}){let r=b();await x(r),(await oe(r.cwd,r)).match(()=>{},a=>{process.stderr.write(`${S(a)}
|
|
490
|
-
`),process.exit(1)});let o=(await d({config:r,document:zu,variables:{cwd:r.cwd,projectId:r.projectId,workflowSlugs:e.map(a=>Yr(a))}})).addDirtyTestsToScope;o?.__typename==="NoActiveDevSessionError"&&(process.stderr.write(`${o.message}
|
|
491
|
-
`),process.exit(1)),o?.__typename==="UnknownWorkflowSlugsError"&&(process.stderr.write(`${ts(o.slugs)}
|
|
492
|
-
`),process.exit(1));let i=o?.__typename==="MutationAddDirtyTestsToScopeSuccess"?o.data:[];if(i.length===0){process.stdout.write(`${ns()}
|
|
493
|
-
`);return}let s=i.map(a=>a.workflow?.slug??"?").join(", ");process.stdout.write(`Added ${j(i.length,"scope item")}: ${s}
|
|
494
|
-
`)}async function as({id:e,testId:r}){let n=b();await x(n),(await oe(n.cwd,n)).match(()=>{},i=>{process.stderr.write(`${S(i)}
|
|
495
|
-
`),process.exit(1)});let o=await Ju({cfg:n,slug:r});await d({config:n,document:Ku,variables:{id:e,workflowId:o}}),process.stdout.write(`Linked scope item ${e} to ${r}
|
|
496
|
-
`)}async function ls({ids:e}){let r=b();await x(r);let t=(await d({config:r,document:Gu,variables:{ids:[...e]}})).removeScopeItems??0;process.stdout.write(`Removed ${j(t,"scope item")}
|
|
497
|
-
`)}async function Ju({cfg:e,slug:r}){let t=(await d({config:e,document:Vu,variables:{cwd:e.cwd,projectId:e.projectId,slug:r}})).project?.devSession?.workflows?.[0];return t==null&&(process.stderr.write(`No workflow found with id "${r}". Create a stub first via the testing DSL.
|
|
498
|
-
`),process.stderr.write(`${R("create")}
|
|
499
|
-
`),process.exit(1)),t.id}import{graphql as L}from"gql.tada";import{print as ws}from"graphql";import{createClient as bs}from"graphql-sse";import Rr from"fs";import Qu from"path";import{err as _e,ok as Zu}from"neverthrow";function cs({cwd:e,rrwebId:r,runId:n}){let t=ps(e,n);if(!Rr.existsSync(t))return _e({kind:"no-behavior"});let o=ys(gs(t,r));if(o==null)return _e({kind:"not-found"});let i=$r(o.node.type);return i===3?_e({kind:"text-node",parentId:$r(o.parent?.id)}):i!==2?_e({kind:"non-element",nodeType:i??-1}):Zu({tagName:I(o.node.tagName)})}function us({cwd:e,rrwebId:r,runId:n}){let t=gs(ps(e,n),r);if(t==null)return null;let o=ys(t);return o==null||$r(o.node.type)!==2?null:Xu(t)}function ps(e,r){return Qu.join(e,".ripplo","debug",r,"behavior.jsonl")}function Xu(e){let r=e.at(-1)??{},n=Er(r.attributes)??{},t=I(r.tagName);return{ariaName:I(n["aria-label"]),role:I(n.role),selector:ep(e),tagName:t==null?null:t.toLowerCase(),testId:I(n["data-testid"]),text:ip(op(r))}}var Yu=6;function ep(e){let r=ms(e,e.length-1,Yu);return r.length===0?null:r.join(" > ")}function ms(e,r,n){let t=e[r];if(t==null||n<=0)return[];let o=rp(t);if(o!=null)return[o];let i=np(t,e[r-1]);return r===0||n===1?[i]:[...ms(e,r-1,n-1),i]}function rp(e){let r=Er(e.attributes)??{},n=I(r["data-testid"]);if(n!=null)return`[data-testid="${n}"]`;let t=I(r.id);return t!=null&&t.length>0?`#${t}`:null}function np(e,r){let n=(I(e.tagName)??"*").toLowerCase(),t=fs(r).filter(i=>(I(i.tagName)??"*").toLowerCase()===n);if(t.length<=1)return n;let o=t.findIndex(i=>i.id===e.id);return o===-1?n:`${n}:nth-of-type(${String(o+1)})`}function fs(e){let r=e?.childNodes;return Array.isArray(r)?r.filter(n=>Ue(n)):[]}function gs(e,r){return Rr.existsSync(e)?Rr.readFileSync(e,"utf8").split(`
|
|
500
|
-
`).reduce((t,o)=>t!=null||o.length===0?t:tp(o,r),null):null}function tp(e,r){let n=Gr(e);if(n?.kind!=="rrweb")return null;let t=Er(n.event.data),o=Cr(t?.node,r);if(o!=null)return o;let i=t?.adds;return Array.isArray(i)?i.reduce((s,a)=>s??(Ue(a)?Cr(a.node,r):null),null):null}function Cr(e,r){if(!Ue(e))return null;if(e.id===r)return[e];let n=e.childNodes;if(!Array.isArray(n))return null;let t=n.reduce((o,i)=>o??Cr(i,r),null);return t==null?null:[e,...t]}function ys(e){let r=e?.at(-1);return r==null?null:{node:r,parent:e?.at(-2)}}var ds=80;function op(e){let r=fs(e).filter(n=>n.type===3).map(n=>I(n.textContent)).filter(n=>n!=null);return r.length===0?null:r.join(" ")}function I(e){return typeof e=="string"?e:null}function ip(e){let r=e==null?"":e.replaceAll(/\s+/g," ").trim();return r.length===0?null:r.length>ds?`${r.slice(0,ds)}\u2026`:r}function Er(e){return Ue(e)?e:void 0}function Ue(e){return typeof e=="object"&&e!=null}function $r(e){return typeof e=="number"?e:null}function Pr(e,r){let n=r.flatMap(o=>sp(e,o)),t=new Map(r.map(o=>[o.id,o.fingerprint]));return{changes:n,seen:t}}function sp(e,r){let n=e.get(r.id);return n==null?r.kind==="finding"||r.lastMessageAuthor==="agent"?[]:[{task:r,type:r.latestMessageKind==="reopen"?"reopened":"new"}]:n!==r.fingerprint&&r.lastMessageAuthor==="user"?[{task:r,type:"reply"}]:[]}var ap=L(`
|
|
501
|
-
query WorkList($projectId: String!, $cwd: String!) {
|
|
502
|
-
project(id: $projectId) {
|
|
503
|
-
id
|
|
504
|
-
devSession(cwd: $cwd) {
|
|
505
|
-
id
|
|
506
|
-
tasks(status: open) {
|
|
507
|
-
id
|
|
508
|
-
kind
|
|
509
|
-
status
|
|
510
|
-
title
|
|
511
|
-
messages {
|
|
512
|
-
body
|
|
513
|
-
}
|
|
514
|
-
}
|
|
515
|
-
}
|
|
516
|
-
}
|
|
517
|
-
}
|
|
518
|
-
`),lp=L(`
|
|
519
|
-
query WatchSeed($projectId: String!, $cwd: String!) {
|
|
520
|
-
project(id: $projectId) {
|
|
521
|
-
id
|
|
522
|
-
devSession(cwd: $cwd) {
|
|
523
|
-
id
|
|
524
|
-
tasks(status: open) {
|
|
525
|
-
id
|
|
526
|
-
kind
|
|
527
|
-
title
|
|
528
|
-
updatedAt
|
|
529
|
-
lastMessageAuthor
|
|
530
|
-
messages {
|
|
531
|
-
body
|
|
532
|
-
kind
|
|
533
|
-
}
|
|
534
|
-
}
|
|
535
|
-
}
|
|
536
|
-
}
|
|
537
|
-
}
|
|
538
|
-
`),vs=L(`
|
|
539
|
-
subscription WatchTasks($devSessionId: String!) {
|
|
540
|
-
tasksChanged(devSessionId: $devSessionId) {
|
|
541
|
-
devSession {
|
|
44
|
+
title
|
|
45
|
+
verdict
|
|
46
|
+
prUrl
|
|
47
|
+
publishedAttempt {
|
|
542
48
|
id
|
|
543
|
-
|
|
49
|
+
status
|
|
50
|
+
summaryText
|
|
51
|
+
issues {
|
|
544
52
|
id
|
|
545
53
|
kind
|
|
546
54
|
title
|
|
547
|
-
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
|
|
551
|
-
|
|
55
|
+
body
|
|
56
|
+
workflowSlugs
|
|
57
|
+
evidence {
|
|
58
|
+
runId
|
|
59
|
+
testRef
|
|
60
|
+
frameMs
|
|
61
|
+
rrwebId
|
|
552
62
|
}
|
|
553
63
|
}
|
|
554
64
|
}
|
|
555
65
|
}
|
|
556
66
|
}
|
|
557
|
-
`)
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
|
|
571
|
-
|
|
572
|
-
|
|
573
|
-
}
|
|
574
|
-
`),cp=L(`
|
|
575
|
-
mutation WorkComment(
|
|
576
|
-
$taskId: String!
|
|
577
|
-
$body: String!
|
|
578
|
-
$runId: String
|
|
579
|
-
$frameMs: Int
|
|
580
|
-
$rrwebId: Int
|
|
581
|
-
$authorName: String
|
|
582
|
-
) {
|
|
583
|
-
agentCommentOnTask(
|
|
584
|
-
taskId: $taskId
|
|
585
|
-
body: $body
|
|
586
|
-
runId: $runId
|
|
587
|
-
frameMs: $frameMs
|
|
588
|
-
rrwebId: $rrwebId
|
|
589
|
-
authorName: $authorName
|
|
590
|
-
) {
|
|
591
|
-
__typename
|
|
592
|
-
... on Task {
|
|
593
|
-
id
|
|
594
|
-
}
|
|
595
|
-
... on NoActiveDevSessionError {
|
|
596
|
-
message
|
|
597
|
-
}
|
|
598
|
-
}
|
|
599
|
-
}
|
|
600
|
-
`),up=L(`
|
|
601
|
-
mutation WorkResolve($taskId: String!, $runId: String!, $note: String, $authorName: String) {
|
|
602
|
-
agentResolveTask(taskId: $taskId, runId: $runId, note: $note, authorName: $authorName) {
|
|
603
|
-
__typename
|
|
604
|
-
... on Task {
|
|
605
|
-
id
|
|
606
|
-
}
|
|
607
|
-
... on NoActiveDevSessionError {
|
|
608
|
-
message
|
|
609
|
-
}
|
|
610
|
-
}
|
|
611
|
-
}
|
|
612
|
-
`),pp=L(`
|
|
613
|
-
mutation WorkStart($taskId: String!) {
|
|
614
|
-
agentStartTask(taskId: $taskId) {
|
|
615
|
-
__typename
|
|
616
|
-
... on Task {
|
|
617
|
-
id
|
|
618
|
-
agentStartedAt
|
|
619
|
-
}
|
|
620
|
-
... on NoActiveDevSessionError {
|
|
621
|
-
message
|
|
622
|
-
}
|
|
623
|
-
}
|
|
624
|
-
}
|
|
625
|
-
`),mp=L(`
|
|
626
|
-
mutation WorkClarify($taskId: String!, $body: String!, $authorName: String) {
|
|
627
|
-
agentSetNeedsClarification(taskId: $taskId, body: $body, authorName: $authorName) {
|
|
628
|
-
__typename
|
|
629
|
-
... on Task {
|
|
630
|
-
id
|
|
631
|
-
}
|
|
632
|
-
... on NoActiveDevSessionError {
|
|
633
|
-
message
|
|
634
|
-
}
|
|
635
|
-
}
|
|
636
|
-
}
|
|
637
|
-
`),fp=L(`
|
|
638
|
-
mutation WorkDismiss($taskId: String!, $note: String, $authorName: String) {
|
|
639
|
-
agentDismissTask(taskId: $taskId, note: $note, authorName: $authorName) {
|
|
640
|
-
__typename
|
|
641
|
-
... on Task {
|
|
642
|
-
id
|
|
643
|
-
}
|
|
644
|
-
... on NoActiveDevSessionError {
|
|
645
|
-
message
|
|
646
|
-
}
|
|
647
|
-
... on FindingNotDismissableError {
|
|
648
|
-
message
|
|
649
|
-
}
|
|
650
|
-
}
|
|
651
|
-
}
|
|
652
|
-
`),gp=18e4;async function Ss(e){let r=b();await x(r);let n=await hs(r),t=n.items.some(o=>o.kind==="finding");if(e.wait&&!t&&n.devSessionId!=null){await yp({cfg:r,devSessionId:n.devSessionId});let o=await hs(r);ks(o.items,e.format);return}ks(n.items,e.format)}async function hs(e){let n=(await d({config:e,document:ap,variables:{cwd:e.cwd,projectId:e.projectId}})).project?.devSession;return{devSessionId:n?.id??null,items:n?.tasks??[]}}function ks(e,r){if(r==="json"){process.stdout.write(`${JSON.stringify(e,null,2)}
|
|
653
|
-
`);return}let n=e.map(t=>({id:t.id,kind:t.kind,lastMessage:(t.messages??[]).at(-1)?.body??null,status:t.status,title:t.title}));process.stdout.write(`${$n(n)}
|
|
654
|
-
`)}function yp({cfg:e,devSessionId:r}){let n=bs({headers:{Authorization:`Bearer ${e.token}`},retryAttempts:1/0,url:`${e.ripploServerUrl}/graphql`});return new Promise(t=>{let o={settled:!1,timer:null,dispose:()=>{}},i=()=>{o.settled||(o.settled=!0,o.timer!=null&&clearTimeout(o.timer),o.dispose(),t())};o.timer=setTimeout(i,gp),o.dispose=n.subscribe({query:ws(vs),variables:{devSessionId:r}},{complete:i,error:()=>{i()},next:s=>{(s.data?.tasksChanged?.devSession?.tasks??[]).some(l=>l.kind==="finding")&&i()}})})}async function xs(){let e=b();await x(e);let n=(await d({config:e,document:lp,variables:{cwd:e.cwd,projectId:e.projectId}})).project?.devSession;if(n==null)throw new Error("dev session vanished between preflight and seed");let t=Pr(new Map,Cs(n.tasks??[])),o=bs({headers:{Authorization:`Bearer ${e.token}`},retryAttempts:1/0,url:`${e.ripploServerUrl}/graphql`});hp({devSessionId:n.id,seen:t.seen,sseClient:o}),await new Promise(()=>{})}function hp({devSessionId:e,seen:r,sseClient:n}){let t=r;n.subscribe({query:ws(vs),variables:{devSessionId:e}},{complete:()=>{},error:o=>{process.stderr.write(`task watch error: ${String(o)}
|
|
655
|
-
`)},next:o=>{let i=o.data?.tasksChanged?.devSession?.tasks??[],s=Pr(t,Cs(i));s.changes.forEach(a=>{process.stdout.write(`${Pn(a)}
|
|
656
|
-
`)}),t=s.seen}})}async function Rs(e){let r=b();await x(r);let t=(await d({config:r,document:dp,variables:{id:e.id}})).task;if(t==null&&(process.stderr.write(`${In(e.id)}
|
|
657
|
-
`),process.exit(1)),e.format==="json"){process.stdout.write(`${JSON.stringify(t,null,2)}
|
|
658
|
-
`);return}let o=[...new Set((t.messages??[]).flatMap(s=>s.runId==null?[]:[s.runId]))];await Promise.all(o.map(s=>ee(r.cwd,s).then(a=>a.isErr())));let i={id:t.id,kind:t.kind,lastMessage:(t.messages??[]).at(-1)?.body??null,messages:(t.messages??[]).map(s=>({author:s.author,authorName:s.authorName,body:s.body,element:s.runId==null||s.rrwebId==null?null:us({cwd:r.cwd,rrwebId:s.rrwebId,runId:s.runId}),frameMs:s.frameMs,rrwebId:s.rrwebId,runId:s.runId})),status:t.status,title:t.title};process.stdout.write(`${En(i)}
|
|
659
|
-
`)}function Cs(e){return e.map(r=>({fingerprint:`${r.id}:${String(r.updatedAt)}`,id:r.id,kind:r.kind,lastMessageAuthor:r.lastMessageAuthor,latestMessage:(r.messages??[]).at(-1)?.body??null,latestMessageKind:(r.messages??[]).at(-1)?.kind??null,title:r.title}))}async function $s(e){let r=b();if(await x(r),e.elementId!=null&&e.runId!=null){let t=cs({cwd:r.cwd,rrwebId:e.elementId,runId:e.runId}).match(()=>null,o=>o);t!=null&&t.kind!=="no-behavior"&&(process.stderr.write(`${kp(t,e.elementId,e.runId)}
|
|
660
|
-
`),process.exit(1))}let n=await d({config:r,document:cp,variables:{authorName:e.authorName??null,body:e.body,frameMs:e.offsetMs??null,rrwebId:e.elementId??null,runId:e.runId??null,taskId:e.id}});qe(n.agentCommentOnTask),process.stdout.write(`${An(e.id)}
|
|
661
|
-
`)}async function Es(e){let r=b();await x(r);let n=await d({config:r,document:up,variables:{authorName:e.authorName??null,note:e.note??null,runId:e.runId,taskId:e.id}});qe(n.agentResolveTask),process.stdout.write(`${Nn(e.id)}
|
|
662
|
-
`)}async function Ps(e){let r=b();await x(r);let n=await d({config:r,document:pp,variables:{taskId:e.id}});qe(n.agentStartTask),process.stdout.write(`${On(e.id)}
|
|
663
|
-
`)}async function Is(e){e.body.trim().length===0&&(process.stderr.write(`${Tn()}
|
|
664
|
-
`),process.exit(1));let r=b();await x(r);let n=await d({config:r,document:mp,variables:{authorName:e.authorName??null,body:e.body,taskId:e.id}});qe(n.agentSetNeedsClarification),process.stdout.write(`${Fn(e.id)}
|
|
665
|
-
`)}async function As(e){let r=b();await x(r);let t=(await d({config:r,document:fp,variables:{authorName:e.authorName??null,note:e.note??null,taskId:e.id}})).agentDismissTask;(t?.__typename==="FindingNotDismissableError"||t?.__typename==="NoActiveDevSessionError")&&(process.stderr.write(`${t.message}
|
|
666
|
-
`),process.exit(1)),process.stdout.write(`${Wn(e.id)}
|
|
667
|
-
`)}function qe(e){e?.__typename==="NoActiveDevSessionError"&&(process.stderr.write(`${e.message}
|
|
668
|
-
`),process.exit(1))}function kp(e,r,n){return e.kind==="text-node"?jn(r,e.parentId):e.kind==="not-found"?Mn(r,n):Ln(r)}function Ts(e){return e.command("list","List open tasks for this dev session",r=>r.option("format",{choices:["json","text"],default:"text",describe:"Output format"}).option("wait",{default:!1,describe:"Block until the first explorer finding lands (or a timeout)",type:"boolean"}),r=>Ss({format:r.format,wait:r.wait})).command("watch","Stream new tasks and user replies as they arrive (arm via Monitor from /ripplo:start)",r=>r,()=>xs()).command("show <id>","Show a task with its full message thread",r=>r.positional("id",{demandOption:!0,describe:"Task id",type:"string"}).option("format",{choices:["json","text"],default:"text",describe:"Output format"}),r=>Rs({format:r.format,id:r.id})).command("comment <id> <body>","Comment on a task, optionally anchored to a run frame and element. For visual fixes, anchor to the proof run's frame and element, both read from .ripplo/debug/<runId>/behavior.jsonl: --element takes the rrweb id of an ELEMENT node (a text node has no box and cannot be highlighted \u2014 use its parentId), and --offset takes the frame offset in ms (from recording start, same as `snapshot --offset`) where that element is present. Call once per comment.",r=>r.positional("id",{demandOption:!0,describe:"Task id",type:"string"}).positional("body",{demandOption:!0,describe:"Comment body",type:"string"}).option("run",{describe:"Run id to anchor the comment to",type:"string"}).option("offset",{describe:"Frame offset in ms from recording start",type:"number"}).option("element",{describe:"rrweb id of an element node to highlight (not a text node)",type:"number"}).option("as",{describe:"Agent display name shown on the comment",type:"string"}),r=>$s({authorName:r.as,body:r.body,elementId:r.element,id:r.id,offsetMs:r.offset,runId:r.run})).command("start <id>","Mark a task as picked up \u2014 flags it in progress until resolved, dismissed, or clarified",r=>r.positional("id",{demandOption:!0,describe:"Task id",type:"string"}),r=>Ps({id:r.id})).command("resolve <id>","Resolve a task with a proof run",r=>r.positional("id",{demandOption:!0,describe:"Task id",type:"string"}).option("run",{demandOption:!0,describe:"Proof run id",type:"string"}).option("note",{describe:"Optional resolution note",type:"string"}).option("as",{describe:"Agent display name shown on the message",type:"string"}),r=>Es({authorName:r.as,id:r.id,note:r.note,runId:r.run})).command("clarify <id> <body>","Mark a task as needing clarification from the user",r=>r.positional("id",{demandOption:!0,describe:"Task id",type:"string"}).positional("body",{demandOption:!0,describe:"What you need clarified",type:"string"}).option("as",{describe:"Agent display name shown on the message",type:"string"}),r=>Is({authorName:r.as,body:r.body,id:r.id})).command("dismiss <id>","Dismiss a task as not actionable",r=>r.positional("id",{demandOption:!0,describe:"Task id",type:"string"}).option("note",{describe:"Optional reason",type:"string"}).option("as",{describe:"Agent display name shown on the message",type:"string"}),r=>As({authorName:r.as,id:r.id,note:r.note})).demandCommand(1)}Ar();ne(process.cwd());Ur();async function Sp(){ue(w()),wp({pkg:{name:"ripplo",version:w()}}).notify({message:Rt()}),await bp(vp(process.argv)).scriptName("ripplo").version(w()).command(Cp()).command($p()).command(Pp()).command(Op()).command("auth <subcommand>","Manage authentication",qp).command("projects <subcommand>","List or create Ripplo projects",Up).command("hooks <subcommand>","Pause or resume Ripplo hooks",_p).command(Tp()).command("init","Scaffold .ripplo/ in this project",e=>e.option("project",{type:"string"}).option("env",{type:"string"}).option("app-url",{type:"string"}).option("engine-url",{type:"string"}),e=>ao({appUrl:e["app-url"],engineUrl:e["engine-url"],envFile:e.env,projectId:e.project})).command("run [ids..]","Run tests locally via the daemon (start it first with `npx ripplo daemon`)",Wp,e=>ho({all:e.all,headed:e.headed,ids:e.ids})).command(Mp()).command(Fp()).command(Lp()).command(Np()).command(jp()).command(Ip()).command(Ap()).command("sync","Push the compiled .ripplo/ resources to the server (no run)",()=>{},()=>$i()).command("compile","Compile the DSL, run static model analysis, and write .ripplo/ripplo.lock",e=>e.option("check",{default:!1,describe:"Exit non-zero if the lockfile is missing or stale (does not write)",type:"boolean"}),e=>jt({check:e.check})).command("update","Update ripplo to the latest published version (and hand the daemon off to it)",()=>{},()=>Oi()).command("doctor","Check project health",()=>{},()=>Vt()).command("status","Report stub tests and daemon status",e=>e.option("format",{choices:["json","summary"],default:"json",describe:"Output format"}),e=>bt({format:e.format})).command("scope <subcommand>","Manage testing scope",Dp).command("tasks <subcommand>","Manage tasks for this dev session",Ts).command("run-worker",!1,()=>{},()=>vo()).command("hook <name>","Internal: run a Claude Code plugin hook",e=>e.positional("name",{choices:Object.keys(Gn),demandOption:!0,type:"string"}),e=>Qn(e.name)).strict().help().parse()}Sp().catch(e=>{process.stderr.write(`${Jn(e)}
|
|
669
|
-
`),process.exit(1)});var xp=["start","stop","restart","status"],Rp="start";function Cp(){return{command:"daemon [action]",describe:"Run the long-lived local executor (IPC socket + run subscription)",builder:e=>e.positional("action",{choices:xp,default:Rp,describe:"Lifecycle action for this project's daemon"}).option("explore-debug",{default:!1,describe:"Print local explorer planner decisions",type:"boolean"}),handler:e=>Fi({action:e.action,exploreDebug:e["explore-debug"]})}}function $p(){return{command:"executor [mode]",describe:"Show or switch the run executor for the active dev session",builder:e=>e.positional("mode",{choices:["local","cloud"],describe:"Executor to switch to (omit to show the current one)"}),handler:e=>Ui({mode:e.mode})}}var Ep=["analyze","on","off"];function Pp(){return{command:"explore [state]",describe:"Show or toggle the background explorer for the active dev session",builder:e=>e.positional("state",{choices:Ep,describe:"Turn the explorer on or off, or analyze workflow coverage (omit to show current state)"}).option("json",{default:!1,describe:"Print machine-readable analysis",type:"boolean"}).option("trail",{describe:"Target steps per explored path",type:"number"}).option("workers",{describe:"Concurrent explorer workers",type:"number"}),handler:e=>rs({json:e.json,state:e.state,trail:e.trail,workers:e.workers})}}function Ip(){return{command:"explain <runId>",describe:"Explain a run's failing checks \u2014 what failed, where it came from, and what happened around it",builder:e=>e.positional("runId",{demandOption:!0,type:"string"}).option("json",{default:!1,describe:"Machine-readable output",type:"boolean"}).option("full",{default:!1,describe:"Also show the synthesized starting state and step-by-step run timeline",type:"boolean"}),handler:e=>qo({full:e.full,json:e.json,runId:e.runId})}}function Ap(){return{command:"replay <runId>",describe:"Re-run an explore finding's trail to confirm it's resolved",builder:e=>e.positional("runId",{demandOption:!0,type:"string"}),handler:e=>Qo({runId:e.runId})}}function Tp(){return{command:"setup",describe:"Install the Ripplo plugin for Claude Code and start a guided setup session",builder:e=>e,handler:()=>{yo()}}}function jp(){return{command:"pull <runId>",describe:"Download a run's behavior.jsonl from the server",builder:e=>e.positional("runId",{demandOption:!0,type:"string"}),handler:e=>Bo({runId:e.runId})}}function Mp(){return{command:"snapshot <runId>",describe:"Render a PNG of the page at a point in a run's rrweb recording",builder:e=>e.positional("runId",{demandOption:!0,type:"string"}).option("at",{describe:"Moment to render: epoch-ms timestamp exactly as found in behavior.jsonl",type:"number"}).option("offset",{describe:"Moment to render: ms from the start of the recording (alternative to --at)",type:"number"}).conflicts("at","offset"),handler:e=>ui({at:e.at,offset:e.offset,runId:e.runId})}}function Lp(){return{command:"capture",describe:"Open your signed-in browser, record a flow, and hand the log to Claude",builder:e=>e,handler:()=>vi()}}function Np(){return{command:"clickpath <runId>",describe:"Print the resolved, ordered user actions from a capture",builder:e=>e.positional("runId",{demandOption:!0,describe:"Capture run id (the capture-... folder under .ripplo/debug)",type:"string"}),handler:e=>{Ci({runId:e.runId})}}}function Op(){return{command:"concurrency [value]",describe:"Show or set max local concurrent runs (daemon applies live)",builder:e=>e.positional("value",{type:"number"}),handler:e=>Lt({value:e.value})}}function Fp(){return{command:"teleport <ref>",describe:"Open a live browser with starting state and earlier test steps applied",builder:e=>e.positional("ref",{demandOption:!0,describe:"Test ref: <workflow-slug>/<test-slug>",type:"string"}).option("step",{demandOption:!0,describe:"Step to land on \u2014 runs the test up to and including this step, then hands over",type:"number"}),handler:e=>gi({ref:e.ref,step:e.step})}}function Wp(e){let r=[];return e.positional("ids",{array:!0,default:r,describe:"Test ids to run",type:"string"}).option("all",{default:!1,describe:"Run every test in the suite (expensive)",type:"boolean"}).option("headed",{default:!1,describe:"Run with a visible browser window",type:"boolean"})}function Dp(e){return e.command("status","Print the current scope",r=>r.option("format",{choices:["json","text"],default:"text",describe:"Output format"}),r=>is({format:r.format})).command("add <test-ids..>","Bind one or more existing tests (stubs or implemented) to scope as agent intent",r=>{let n=[];return r.positional("test-ids",{array:!0,default:n,demandOption:!0,describe:"Slugs of existing workflows",type:"string"})},r=>ss({testIds:r["test-ids"]})).command("link <id> <test-id>","Link an existing scope item to a test",r=>r.positional("id",{demandOption:!0,describe:"Scope item id",type:"string"}).positional("test-id",{demandOption:!0,describe:"Slug of the workflow to link",type:"string"}),r=>as({id:r.id,testId:r["test-id"]})).command("remove <ids..>","Remove one or more scope items by id",r=>{let n=[];return r.positional("ids",{array:!0,default:n,demandOption:!0,describe:"Scope item ids",type:"string"})},r=>ls({ids:r.ids})).demandCommand(1)}function _p(e){return e.command("pause","Disable all Ripplo pre-edit gates and stop enforcement until resumed",()=>{},()=>zt()).command("resume","Re-enable Ripplo hooks paused via `ripplo hooks pause`",()=>{},()=>Kt()).demandCommand(1)}function Up(e){return e.command("list","List projects you have access to (JSON)",()=>{},()=>uo()).command("create <name>","Create a project (JSON)",r=>r.positional("name",{demandOption:!0,type:"string"}).option("org",{describe:"Organization id",type:"string"}),r=>po({name:r.name,orgId:r.org})).demandCommand(1)}function qp(e){return e.command("login","Authenticate via device flow",()=>{},()=>It()).command("status","Show authentication status",()=>{},()=>At()).command("logout","Remove the saved token",()=>{},()=>{Tt()}).demandCommand(1)}export{Sp as main};
|
|
67
|
+
`);async function to({codeReviewId:e}){let t=ft();t==null&&(process.stderr.write(`${ur()}
|
|
68
|
+
`),process.exit(1));let n=(await Ee({config:ht(t),document:jl,variables:{id:e}})).codeReview;n==null&&(process.stderr.write(`${Qn(e)}
|
|
69
|
+
`),process.exit(1));let o=n.publishedAttempt;o==null&&(process.stderr.write(`${eo(e)}
|
|
70
|
+
`),process.exit(1));let s={attemptId:o.id,codeReviewId:n.id,issues:o.issues,prUrl:n.prUrl,summary:o.summaryText,title:n.title,verdict:n.verdict};process.stdout.write(`${JSON.stringify(s,null,2)}
|
|
71
|
+
`);}var Bl=createRequire$1(import.meta.url);function ro(e,t){try{return Bl.resolve(e)}catch{return fileURLToPath(new URL(`assets/${t}`,import.meta.url))}}function no(e){let t;return ()=>(t??=readFile(e,"utf8"),t)}var ql={height:800,width:1280};async function oo(e){let t=await readFile(e,"utf8");return Pe(t).flatMap(r=>r.kind==="rrweb"?[r.event]:[])}var Wl=z.object({data:z.looseObject({height:z.number(),width:z.number()}),type:z.literal(4)});function dr(e){let t=e.flatMap(r=>{let n=Wl.safeParse(r);return n.success?[n.data]:[]})[0];return t==null?ql:{height:t.data.height,width:t.data.width}}function ao(){return import('playwright').then(({chromium:e})=>e.launch({args:["--no-sandbox"],headless:true})).catch(()=>null)}var io=no(ro("@ripplo/rrweb-bundle/replay","rrweb-replay.js"));var Gl=".replayer-mouse, .replayer-mouse-tail { display: none; }";function so(e){return `<!doctype html><html><head><style>
|
|
72
|
+
html, body { margin: 0; padding: 0; }
|
|
73
|
+
.replayer-wrapper { position: relative; }
|
|
74
|
+
${Gl}
|
|
75
|
+
iframe { border: none; }
|
|
76
|
+
</style></head><body></body></html>`}function lo({events:e,styleRules:t}){globalThis.__ripploSnapshotReplayer=new globalThis.__RipploReplayer(e,{insertStyleRules:t,mouseTail:false,root:document.body,showWarning:false});}function co(e){globalThis.__ripploSnapshotReplayer?.pause(e+.5);}async function uo({frameSelector:e}){let t=document.querySelector(e)?.contentDocument;t?.fonts!=null&&await t.fonts.ready,await new Promise(r=>{requestAnimationFrame(()=>requestAnimationFrame(()=>{r();}));});}function po({documentPrefix:e,frameSelector:t}){let r=globalThis.__ripploSnapshotReplayer,n=document.querySelector(t)?.contentDocument;if(r==null||n==null)return "";let o=r.getMirror();return [...n.querySelectorAll("*")].forEach(s=>{let c=o.getId(s);c!=null&&c>0&&(s.dataset.rrwebId=String(c));}),`${e}${n.documentElement.outerHTML}`}function mo({frameSelector:e}){let t=document.querySelector(e)?.contentDocument;if(t==null)return [];let r=o=>[...o.childNodes].filter(s=>s.nodeType===3).map(s=>s.textContent??"").join(" ").replaceAll(/\s+/gu," ").trim(),n=o=>{if(o==null)return null;let s=o.dataset.rrwebId;if(s==null)return null;let c=Number.parseInt(s,10);return Number.isSafeInteger(c)&&c>0?c:null};return [...t.querySelectorAll("*")].map(o=>({attributes:Object.fromEntries([...o.attributes].map(s=>[s.name,s.value])),directText:r(o),parentRrwebId:n(o.parentElement),rrwebId:n(o),tagName:o.tagName.toLowerCase()}))}var We=".replayer-wrapper iframe";var fo=`<!doctype html>
|
|
77
|
+
`;async function yo(e){await e.addInitScript(Kl);}function Kl(){Reflect.set(globalThis,"__name",e=>e);}var Xl=z.object({attributes:z.record(z.string(),z.string()),directText:z.string(),parentRrwebId:z.number().int().positive().nullable(),rrwebId:z.number().int().positive().nullable(),tagName:z.string().min(1)}),Ql=z.array(Xl);async function So({behaviorFile:e,moment:t,outDir:r,runId:n}){if(!existsSync(e))return err({kind:"run-not-found",runId:n});let o=await oo(e),s=o[0],c=o.at(-1);if(s==null||c==null)return err({kind:"no-rrweb-events",runId:n});let p=c.timestamp-s.timestamp,d=t.kind==="offset"?t.offsetMs:t.at-s.timestamp;if(d<0||d>p)return err({durationMs:p,firstTimestamp:s.timestamp,kind:"moment-out-of-range",lastTimestamp:c.timestamp,moment:t});let f=d,m=String(Math.round(f)),E=ir.join(r,`snapshot-${m}ms.png`),b=ir.join(r,`snapshot-${m}ms.html`);return (await ec({events:o,htmlPath:b,offsetMs:f,pngPath:E})).map(C=>({durationMs:p,elementIndex:C,htmlPath:b,offsetMs:f,pngPath:E,viewport:dr(o)}))}async function ec({events:e,htmlPath:t,offsetMs:r,pngPath:n}){let o=await ao();if(o==null)return err({detail:"chromium-launch",kind:"browser-failed"});try{let{elementIndex:s,html:c,png:p}=await tc({browser:o,events:e,offsetMs:r});return await writeFile(n,p),await writeFile(t,c,"utf8"),ok(s)}catch(s){return err({detail:s instanceof Error?s.message:String(s),kind:"browser-failed"})}finally{await o.close();}}async function tc({browser:e,events:t,offsetMs:r}){let n=dr(t),o=await e.newContext({viewport:n});await yo(o);let s=await o.newPage();await s.setContent(so()),await s.addScriptTag({content:await io()}),await s.evaluate(lo,{events:t,styleRules:[...Mt]}),await s.evaluate(co,r),await s.evaluate(uo,{frameSelector:We});let c=s.locator(We).first(),d=await(await c.count()>0?c:s).screenshot({type:"png"}),f=z.string().parse(await s.evaluate(po,{documentPrefix:fo,frameSelector:We}));return {elementIndex:Ql.parse(await s.evaluate(mo,{frameSelector:We})),html:f,png:d}}function Eo(){return "Pass exactly one of --at <epoch ms from behavior.jsonl> or --offset <ms from the start of the recording>."}function bo(e){switch(e.kind){case "run-not-found":return `No behavior.jsonl for run ${e.runId}.`;case "no-rrweb-events":return `Run ${e.runId} has no rrweb events, nothing to replay.`;case "moment-out-of-range":return `${e.moment.kind==="offset"?"--offset":"--at"} is outside the recording, which spans ${String(e.firstTimestamp)} to ${String(e.lastTimestamp)} (duration ${String(e.durationMs)}ms).`;case "browser-failed":return `Replay browser failed (${e.detail}). Try \`npx playwright install chromium\`.`}}async function Ro({at:e,offset:t,runId:r}){let n=rc({at:e,offset:t});n==null&&(process.stderr.write(`${Eo()}
|
|
78
|
+
`),process.exit(1));let o=await Et(r);o.isErr()&&(process.stderr.write(`${bt(o.error)}
|
|
79
|
+
`),process.exit(1)),(await So({behaviorFile:o.value,moment:n,outDir:sr(r),runId:r})).match(c=>{let p={durationMs:c.durationMs,htmlPath:c.htmlPath,offsetMs:c.offsetMs,pngPath:c.pngPath,viewport:c.viewport};process.stdout.write(`${JSON.stringify(p,null,2)}
|
|
80
|
+
`);},c=>{process.stderr.write(`${bo(c)}
|
|
81
|
+
`),process.exit(1);});}function rc({at:e,offset:t}){if(e!=null&&t==null)return {at:e,kind:"absolute"};if(t!=null&&e==null)return {kind:"offset",offsetMs:t}}function _o(e){return e instanceof Error?e.message:String(e)}or();async function ac(){$t(ar()),await nc(hideBin(process.argv)).scriptName("ripplo").version(ar()).command("login","Sign in through your browser",()=>{},()=>rr({lookupViewer:Wn,serverUrl:yt()})).command("logout","Remove the saved token",()=>{},()=>{nr(yt());}).command("review <codeReviewId>","Print the published issues of a code review (JSON)",e=>e.positional("codeReviewId",{demandOption:true,type:"string"}),e=>to({codeReviewId:e.codeReviewId})).command("explain <runId>","Print what failed in a run, step by step, with nearby evidence (JSON)",e=>e.positional("runId",{demandOption:true,type:"string"}),e=>Xn({runId:e.runId})).command("snapshot <runId>","Render the page at a moment of a run to PNG and rrweb-tagged HTML",e=>e.positional("runId",{demandOption:true,type:"string"}).option("at",{describe:"Epoch ms from behavior.jsonl",type:"number"}).option("offset",{describe:"Ms from the start of the recording",type:"number"}),e=>Ro({at:e.at,offset:e.offset,runId:e.runId})).strict().help().parse();}ac().catch(e=>{process.stderr.write(`${_o(e)}
|
|
82
|
+
`),process.exit(1);});export{ac as main};
|