ripplo 0.15.2 → 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 -664
- package/package.json +8 -45
- 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-3BPQWAUL.js +0 -4
- package/dist/chunk-47LLHHJH.js +0 -9
- package/dist/chunk-5HFJIZLI.js +0 -4
- package/dist/chunk-5RKZ44OU.js +0 -4
- package/dist/chunk-7WZ3VIUU.js +0 -4
- package/dist/chunk-AXROBTLA.js +0 -4
- package/dist/chunk-BFAWQ5U2.js +0 -61
- package/dist/chunk-BGY5F3IU.js +0 -5
- package/dist/chunk-BIB4JJKD.js +0 -84
- package/dist/chunk-C7SV6AR2.js +0 -48
- package/dist/chunk-CI6273ZU.js +0 -107
- package/dist/chunk-FEHVIHVA.js +0 -5
- package/dist/chunk-G6J2WIHJ.js +0 -4
- package/dist/chunk-HEOMRXZE.js +0 -4
- package/dist/chunk-HN55QF5N.js +0 -405
- package/dist/chunk-JJ4QQPAV.js +0 -4
- package/dist/chunk-JQ2CRYVX.js +0 -4
- package/dist/chunk-JS3DLVVI.js +0 -4
- package/dist/chunk-KH4QH23U.js +0 -4
- package/dist/chunk-KMZ3L5YA.js +0 -4
- package/dist/chunk-KOKEEAEF.js +0 -6
- package/dist/chunk-LCCJPRT5.js +0 -5
- package/dist/chunk-MHNGR6M7.js +0 -4
- package/dist/chunk-NNH3YVVO.js +0 -4
- package/dist/chunk-OQ6KNYPG.js +0 -4
- package/dist/chunk-PYDYI3AA.js +0 -23
- package/dist/chunk-Q2TF5WLS.js +0 -6
- package/dist/chunk-QEE4CNMY.js +0 -6
- package/dist/chunk-R4ZTRVDQ.js +0 -4
- package/dist/chunk-RIASQHPG.js +0 -4
- package/dist/chunk-RLB66SU3.js +0 -4
- package/dist/chunk-SXVWB7TZ.js +0 -6
- package/dist/chunk-T6WA2F3S.js +0 -16
- package/dist/chunk-TZPYILZK.js +0 -4
- package/dist/chunk-VHFITVRX.js +0 -13
- package/dist/chunk-W3CXPVVB.js +0 -7
- package/dist/chunk-WB3HHOCG.js +0 -11
- package/dist/chunk-XA6BMQTW.js +0 -8
- package/dist/chunk-XAMVRZJH.js +0 -23
- package/dist/chunk-Y52M43LO.js +0 -8
- package/dist/chunk-YD4VBOBY.js +0 -4
- package/dist/chunk-YRU6BOIP.js +0 -9
- package/dist/chunk-ZSD6QDYB.js +0 -56
- package/dist/cli-error-UYWIDE4L.js +0 -4
- package/dist/compile-write-QNV2EA5B.js +0 -4
- package/dist/daemon-D4UCHMHS.js +0 -175
- package/dist/daemon-LZTY7W4M.js +0 -4
- package/dist/daemon-lock-RPKO5SNE.js +0 -4
- package/dist/dsl-loader-G2CRA252.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-EDDIUY43.js +0 -4
- package/dist/post-edit-4CM5P2G2.js +0 -4
- package/dist/post-edit-analyze-HKOTNA2H.js +0 -4
- package/dist/post-edit-flag-stubs-2HZMK4NQ.js +0 -4
- package/dist/pre-bash-run-gate-CDFNAIK3.js +0 -4
- package/dist/pre-edit-JZX36QX6.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-T2TWL66C.js +0 -4
- package/dist/prompt-submit-GVZHK3CI.js +0 -4
- package/dist/scope-reminder-A6GVTTVE.js +0 -4
- package/dist/session-preamble-IZQPIWST.js +0 -4
- package/dist/status-CNSPYNYP.js +0 -4
- package/dist/stop-enforce-NKKP2X4U.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,690 +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
|
-
`),
|
|
18
|
-
`),process.stdout.write(o.kind==="ok"?`${s}, ${sa(o.viewer)}.
|
|
19
|
-
`:`${s}.
|
|
20
|
-
`),process.stdout.write(`Session saved to ${rr(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 ia(e,r){let n=await ur({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 ${rr(e)}.
|
|
30
|
-
`)}async function ur({serverUrl:e,token:r}){try{let t=(await d({config:L({serverUrl:e,token:r}),document:oa,variables:void 0})).currentUser;return t==null?{kind:"rejected"}:{kind:"ok",viewer:{email:t.email,name:t.name}}}catch(n){return zr(n)==="UNAUTHENTICATED"?{kind:"rejected"}:{kind:"unreachable",message:n instanceof Error?n.message:String(n)}}}function sa(e){let r=e.name.trim().split(/\s+/)[0];return r!=null&&r.length>0?r:e.email}import{readFile as aa,writeFile as la}from"fs/promises";import da from"path";async function qt(e){let r=process.cwd(),n=await ye(r);n.isErr()&&Ce(Y(n.error));let t=n.value,o=we({cwd:r,lockfile:t});o.length>0&&Ce(ve(o));let i=await X(r,t),s=tn(j,i),a=da.join(r,J);if(e.check){await ca(a,i);return}await la(a,s),pn(r,s),await I("compile_succeeded"),pa(i)}function Ce(e){process.stderr.write(`${e}
|
|
31
|
-
`),process.exit(1)}async function ca(e,r){let n=await aa(e,"utf8").catch(()=>null);n==null&&Ce(ir("missing")),ua(n,r)||Ce(ir("stale")),process.stdout.write(`${Ln()}
|
|
32
|
-
`)}function ua(e,r){try{let n=N(j,e);return n.checks==null?!1:Pn(n,r)}catch{return!1}}function pa(e){let r=e.workflows.reduce((t,o)=>t+o.tests.length,0),n=[On(),Nn(r)];process.stdout.write(`${n.join(`
|
|
33
|
-
`)}
|
|
34
|
-
`)}import{graphql as Bt}from"gql.tada";function pr(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 ma}from"gql.tada";var fa=ma(`
|
|
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(`${x("setup")}
|
|
45
|
-
`),process.exit(1)})}async function R(e){(await d({config:e,document:fa,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(`${x("setup")}
|
|
46
|
-
`),process.exit(1))}var ga=Bt(`
|
|
47
|
-
mutation CliUpdateMaxLocalConcurrentRuns($value: Int!) {
|
|
48
|
-
updateMaxLocalConcurrentRuns(value: $value) {
|
|
49
|
-
id
|
|
50
|
-
maxLocalConcurrentRuns
|
|
51
|
-
}
|
|
52
|
-
}
|
|
53
|
-
`),ya=Bt(`
|
|
54
|
-
query CliMaxLocalConcurrentRuns {
|
|
55
|
-
currentUser {
|
|
56
|
-
id
|
|
57
|
-
maxLocalConcurrentRuns
|
|
58
|
-
}
|
|
59
|
-
}
|
|
60
|
-
`);async function Ht({value:e}){let r=b();if(e==null){let t=await d({config:r,document:ya,variables:{}});process.stdout.write(`${pr(t.currentUser?.maxLocalConcurrentRuns)}
|
|
61
|
-
`);return}let n=await d({config:r,document:ga,variables:{value:e}});process.stdout.write(`${pr(n.updateMaxLocalConcurrentRuns?.maxLocalConcurrentRuns)}
|
|
62
|
-
`)}function zt(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 (${ha(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 ha(e){let r=e.localFingerprint??"unset",n=e.serverFingerprint??"unknown";return`yours ${r}, Ripplo's ${n}`}function Gt(e){switch(e.type){case"settings":return ka(e);case"env-files":return wa(e);case"token":return ba(e);case"dev-server":return va(e);case"dev-session":return dt(e);case"state-sources":return Sa(e);case"webhook-verification":return xa(e);case"model-validation":return Ra(e);case"workflows":return Ca(e);case"browser":return $a(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 Pa(e);case"lockfile":return Ia(e);case"pre-commit-hook":return Aa(e);case"plugin-version":return Ta(e);case"stale-build":return ja(e);case"webhook-secret":return zt(e)}}function ka(e){return e.valid?"\u2713 Settings: project configured":`\u2717 Settings: missing fields: ${e.missingFields.join(", ")}`}function wa(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 ba(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 va(e){return e.reachable?`\u2713 Dev server: ${e.appUrl} is reachable`:`\u2717 Dev server: ${e.appUrl} is not responding. Start your dev server.`}function Sa(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 xa(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 Ra(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 Ca(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=>Ea(n));return`\u2717 Tests: ${String(e.invalidNames.length)} invalid
|
|
68
|
-
${r.join(`
|
|
69
|
-
`)}`}function Ea(e){let r=e.errors.map(n=>" - "+(n.path===""?"":n.path+": ")+n.message);return" "+e.name+`:
|
|
70
|
-
`+r.join(`
|
|
71
|
-
`)}function $a(e){return e.installed?"\u2713 Browser: Chromium installed":"\u2717 Browser: Chromium not installed. Run `npx playwright install chromium`."}function Pa(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 Ia(e){switch(e.status){case"match":return`\u2713 Lockfile: ${J} is up to date`;case"missing":return`\u2717 Lockfile: ${J} is missing \u2014 run \`npx ripplo compile\` and commit it`;case"stale":return`\u2717 Lockfile: ${J} is out of date \u2014 run \`npx ripplo compile\` and commit it`}}function Aa(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 Ta(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 ja(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 $e from"fs";import Va from"os";import mr from"path";import{z as W}from"zod";import Ma from"latest-version";import Kt from"semver";async function Ee(e){try{return await Promise.race([Ma("ripplo"),new Promise(r=>setTimeout(()=>{r(void 0)},e))])}catch{return}}function Jt(e){return e.filter(r=>Kt.valid(r)!=null).toSorted(Kt.rcompare)[0]}import{createHash as La}from"crypto";import{graphql as Oa}from"gql.tada";var Na=Oa(`
|
|
72
|
-
query ProjectWebhookSecret($projectId: String!) {
|
|
73
|
-
project(id: $projectId) {
|
|
74
|
-
id
|
|
75
|
-
webhookSecret
|
|
76
|
-
}
|
|
77
|
-
}
|
|
78
|
-
`);async function Zt(e){let r=y(e).unwrapOr(void 0),n=r==null?null:Qt(r.webhookSecret);if(r==null||n==null)return{localFingerprint:null,serverFingerprint:null,status:"missing-local",type:"webhook-secret"};let t=await Wa(r),o=t==null?null:Qt(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 Qt(e){return e.length===0?null:La("sha256").update(e).digest("hex").slice(0,Fa)}var Fa=8;async function Wa(e){return(await d({config:e,document:Na,variables:{projectId:e.projectId}}).catch(()=>null))?.project?.webhookSecret??null}import{graphql as Da}from"gql.tada";var _a=Da(`
|
|
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=>Gt(i));process.stdout.write(t.join(`
|
|
87
|
-
`)+`
|
|
88
|
-
`);let o=n.some(i=>Yt(i));process.exit(o?1:0)}import Pe from"fs";import{graphql as al}from"gql.tada";var ll=al(`
|
|
89
|
-
mutation CliSetHooksPaused($projectId: String!, $paused: Boolean!) {
|
|
90
|
-
setHooksPaused(projectId: $projectId, paused: $paused) {
|
|
91
|
-
id
|
|
92
|
-
}
|
|
93
|
-
}
|
|
94
|
-
`);async function to(){let e=process.cwd();Kr(e);let r=nr(e);if(Pe.existsSync(r)){process.stdout.write("Hooks already paused. Run `npx ripplo hooks resume` to re-enable.\n");return}Pe.writeFileSync(r,""),await io(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 oo(){let e=process.cwd(),r=nr(e);if(!Pe.existsSync(r)){process.stdout.write(`Hooks already active.
|
|
95
|
-
`);return}Pe.unlinkSync(r),await io(e,!1),process.stdout.write(`Hooks resumed.
|
|
96
|
-
`)}async function io(e,r){let n=y(e).unwrapOr(void 0);n!=null&&await d({config:n,document:ll,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 re from"fs";import ne from"path";import{input as ho,select as ko}from"@inquirer/prompts";import{graphql as Bl}from"gql.tada";import{exec as dl,execFile as cl}from"child_process";import{err as ul,ok as so}from"neverthrow";import f from"fs";import{createRequire as pl}from"module";import k from"path";import{promisify as co}from"util";import{minVersion as ml}from"semver";import{z as h}from"zod";var fl=["ripplo","@ripplo/testing","@ripplo/instrument"],ao=[h.core.version.major,h.core.version.minor,h.core.version.patch].map(String).join("."),gl=4,lo=".ripplo/ripplo.lock linguist-generated=true",yl=[".ripplo/debug/",".ripplo/.local/"],hl=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()}),kl=co(dl),wl=co(cl);async function uo({cwd:e,onStep:r}){let n=fo(e);r("Scaffolding project files..."),Tl({cwd:e,zodImportPath:n.importPath}),r("Updating .gitignore..."),Ml(e),r("Marking ripplo.lock as generated..."),El(e),r("Installing dependencies...");let t=w(),o=await vl({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?po(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 Cl(e);l!=null&&i.push({manualCommand:void 0,message:l})}return r("Setting up browser..."),(await bl()).map(()=>i)}async function bl(){let{chromium:e}=await import("playwright"),r=e.executablePath();if(f.existsSync(r))return so(void 0);G.info("Chromium not found. Installing via Playwright...");let n=pl(import.meta.url),t=k.dirname(n.resolve("playwright/package.json")),o=k.join(t,"cli.js");return await wl(process.execPath,[o,"install","chromium"]),f.existsSync(r)?so(void 0):ul({kind:"playwright-install-failed"})}async function vl({cwd:e,version:r}){let n=fr({cwd:e,pm:gr(e),version:r});G.info("Installing dependencies: %s",n);try{return await kl(n,{cwd:e}),{ok:!0}}catch(t){let o=Rl(t);return G.warn("Install failed (%s): %s",n,o),{cmd:n,ok:!1,reason:o}}}var Sl=h.object({version:h.string()});function po(e){let r=k.join(e,"node_modules","ripplo","package.json");if(!f.existsSync(r)){let n=k.dirname(e);return n===e?void 0:po(n)}try{let n=Sl.safeParse(JSON.parse(f.readFileSync(r,"utf8")));return n.success?n.data.version:void 0}catch{return}}var xl=h.object({stderr:h.string().optional(),stdout:h.string().optional()});function Rl(e){let r=xl.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(-gl);return t.length>0?t.join(" "):e instanceof Error?e.message:String(e)}async function Cl(e){try{await In(e);return}catch(r){return`Couldn't compile initial lockfile: ${r instanceof Error?r.message:String(r)}.`}}function El(e){let r=k.join(e,".gitattributes"),n=f.existsSync(r)?f.readFileSync(r,"utf8"):"";if(n.includes(lo))return;let t=n.length===0||n.endsWith(`
|
|
99
|
-
`)?"":`
|
|
100
|
-
`;f.writeFileSync(r,`${n}${t}${lo}
|
|
101
|
-
`)}function fr({cwd:e,pm:r,version:n}){let t=fl.map(s=>`${s}@${n}`),o=fo(e),i=[...t,o.installSpec].join(" ");return r==="pnpm"?$l(e)?`pnpm add -wD --save-exact ${i}`:`pnpm add -D --save-exact ${i}`:r==="yarn"?Pl({cwd:e,deps:i}):r==="bun"?`bun add -d --exact ${i}`:`npm install -D --save-exact ${i}`}function gr(e){return f.existsSync(k.join(e,"pnpm-lock.yaml"))?"pnpm":f.existsSync(k.join(e,"yarn.lock"))?"yarn":f.existsSync(k.join(e,"bun.lockb"))||f.existsSync(k.join(e,"bun.lock"))?"bun":"npm"}function $l(e){return f.existsSync(k.join(e,"pnpm-workspace.yaml"))||f.existsSync(k.join(e,"pnpm-workspace.yml"))}function Pl({cwd:e,deps:r}){return Il(e)?`yarn add -D --exact ${r}`:Al(e)?`yarn add -WD --exact ${r}`:`yarn add -D --exact ${r}`}function Il(e){if(f.existsSync(k.join(e,".yarnrc.yml"))||f.existsSync(k.join(e,".pnp.cjs"))||f.existsSync(k.join(e,".pnp.js")))return!0;let r=k.join(e,"package.json");if(!f.existsSync(r))return!1;try{let n=JSON.parse(f.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 Al(e){let r=k.join(e,"package.json");if(!f.existsSync(r))return!1;try{let n=JSON.parse(f.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 Tl({cwd:e,zodImportPath:r}){let n=k.join(e,".ripplo");mo({zodImportPath:r}).forEach(({content:t,relPath:o})=>{let i=k.join(n,o);f.mkdirSync(k.dirname(i),{recursive:!0}),jl(i,t)})}function jl(e,r){f.existsSync(e)||f.writeFileSync(e,r)}function Ml(e){let r=k.join(e,".gitignore");if(!f.existsSync(r))return;let n=f.readFileSync(r,"utf8"),t=yl.filter(i=>!n.includes(i));if(t.length===0)return;let o=n.endsWith(`
|
|
102
|
-
`)?"":`
|
|
103
|
-
`;f.writeFileSync(r,n+o+t.join(`
|
|
104
|
-
`)+`
|
|
105
|
-
`)}var Ll=`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 Ol(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 Nl=`export const facts = [] as const;
|
|
125
|
-
`,Fl=`export const workflows = [] as const;
|
|
126
|
-
`,Wl=`{
|
|
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
|
-
`,Dl=`// 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 mo({zodImportPath:e}){return[{content:Ll,relPath:"index.ts"},{content:Ol(e),relPath:"state.ts"},{content:Nl,relPath:"facts.ts"},{content:Fl,relPath:"workflows/index.ts"},{content:Wl,relPath:"tsconfig.json"},{content:Dl,relPath:"eslint.config.js"}]}var hg=mo({zodImportPath:"zod/v4"});function fo(e){return _l(e)?{importPath:"zod4",installSpec:`zod4@npm:zod@${ao}`}:{importPath:"zod/v4",installSpec:`zod@${ao}`}}function _l(e){let r=k.join(e,"package.json");if(!f.existsSync(r))return!1;let n=JSON.parse(f.readFileSync(r,"utf8")),t=hl.parse(n);return[t.dependencies?.zod,t.devDependencies?.zod,t.optionalDependencies?.zod,t.peerDependencies?.zod].filter(i=>i!=null).some(i=>!Ul(i))}function Ul(e){let r=e.replace(/^workspace:/,"").replace(/^npm:zod@/,"");return ml(r)?.major===4}import Ie from"fs";import go from"path";import{z as yr}from"zod";var Vl={autoUpdate:!0,source:{repo:"ripplo/claude-plugin",source:"github"}},yo=yr.record(yr.string(),yr.unknown());function Ae(e){let r=go.join(e,".claude","settings.json"),n=ql(r);if(n==null)return"unparseable";let t=yo.safeParse(n.extraKnownMarketplaces??{});if(!t.success)return"unparseable";if(t.data.ripplo!=null)return"already-present";let o={...n,extraKnownMarketplaces:{...t.data,ripplo:Vl}};return Ie.mkdirSync(go.dirname(r),{recursive:!0}),Ie.writeFileSync(r,`${JSON.stringify(o,null,2)}
|
|
156
|
-
`),"written"}function ql(e){if(!Ie.existsSync(e))return{};try{let r=yo.safeParse(JSON.parse(Ie.readFileSync(e,"utf8")));return r.success?r.data:void 0}catch{return}}function Te(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 Hl=Bl(`
|
|
157
|
-
query InitProjects {
|
|
158
|
-
projects {
|
|
159
|
-
id
|
|
160
|
-
name
|
|
161
|
-
}
|
|
162
|
-
}
|
|
163
|
-
`),hr=["../.env.local","../.env"];async function wo(e=Kl()){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)),zl(r)&&(process.stdout.write(`\`.ripplo/index.ts\` already exists at ${r}. To re-init, delete it first.
|
|
164
|
-
`),process.exit(1));let o=await Gl({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 Ql(o,e.projectId),s=await Zl(r,e.envFile),a=await Yl(e.appUrl),l=Jl(a,e.engineUrl),c=ne.resolve(ne.join(r,".ripplo"),s);Ur({cwd:r,envFiles:[s],projectId:i}),rd({appUrl:a,engineUrl:l,filePath:c}),process.stdout.write(`${Te(Ae(r))}
|
|
165
|
-
`);let m=(await uo({cwd:r,onStep:p=>{process.stdout.write(` ${p}
|
|
166
|
-
`)}})).match(p=>p,p=>{process.stderr.write(`${S(p)}
|
|
167
|
-
`),process.exit(1)});if(m.length>0){process.stdout.write(`Done with warnings:
|
|
168
|
-
`),m.forEach(p=>{process.stdout.write(` - ${p.message}
|
|
169
|
-
`),p.manualCommand!=null&&process.stdout.write(` run: ${p.manualCommand}
|
|
170
|
-
`)});return}await I("cli_init_completed"),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 zl(e){return re.existsSync(ne.join(e,".ripplo","index.ts"))}async function Gl({serverUrl:e,token:r}){return((await d({config:L({serverUrl:e,token:r}),document:Hl,variables:void 0})).projects??[]).map(t=>({id:t.id,name:t.name}))}function Kl(){return{appUrl:void 0,engineUrl:void 0,envFile:void 0,projectId:void 0}}function Jl(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 Ql(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 ko({choices:e.map(n=>({name:n.name,value:n.id})),message:"Select a project"})}async function Zl(e,r){return r!=null?(r.trim().length===0&&(process.stdout.write(`--env must not be empty
|
|
175
|
-
`),process.exit(1)),r):Xl(e)}async function Xl(e){let r=ne.join(e,".ripplo"),n=hr.find(o=>re.existsSync(ne.resolve(r,o))),t=await ko({choices:[...hr.map(o=>({name:n===o?`${o} (detected)`:o,value:o})),{name:"custom path",value:"__custom__"}],default:n??hr[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:ho({message:"Path to env file (relative to .ripplo/, e.g. ../apps/server/.env)",validate:o=>o.trim().length>0?!0:"required"})}async function Yl(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 ed()}async function ed(){return ho({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 rd({appUrl:e,engineUrl:r,filePath:n}){re.mkdirSync(ne.dirname(n),{recursive:!0});let t=re.existsSync(n)?re.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=${Yr()}`),/^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
|
-
`;re.writeFileSync(n,`${t}${i}${o.join(`
|
|
179
|
-
`)}
|
|
180
|
-
`)}import{graphql as br}from"gql.tada";function kr(){return"Not signed in. Run `npx ripplo auth login` first."}function bo(){return"No organization found for your account. Sign in to the dashboard once, then retry."}function vo(e){return["You belong to multiple organizations \u2014 pass `--org <id>`:",...e.map(n=>` ${n.id} ${n.name}`)].join(`
|
|
181
|
-
`)}function wr(e){return`Could not create the project \u2014 ${e}`}var nd=br(`
|
|
182
|
-
query ProjectsList {
|
|
183
|
-
projects {
|
|
184
|
-
id
|
|
185
|
-
name
|
|
186
|
-
}
|
|
187
|
-
}
|
|
188
|
-
`),td=br(`
|
|
189
|
-
query OrganizationsList {
|
|
190
|
-
organizations {
|
|
191
|
-
id
|
|
192
|
-
name
|
|
193
|
-
}
|
|
194
|
-
}
|
|
195
|
-
`),od=br(`
|
|
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 So(){let e=C(),r=P(e);r==null&&(process.stderr.write(`${kr()}
|
|
212
|
-
`),process.exit(1));let t=((await d({config:L({serverUrl:e,token:r}),document:nd,variables:void 0})).projects??[]).map(o=>({id:o.id,name:o.name}));process.stdout.write(`${JSON.stringify({projects:t},null,2)}
|
|
213
|
-
`)}async function xo({name:e,orgId:r}){let n=C(),t=P(n);t==null&&(process.stderr.write(`${kr()}
|
|
214
|
-
`),process.exit(1));let o=L({serverUrl:n,token:t}),i=r??await id(o),a=(await d({config:o,document:od,variables:{name:e,organizationId:i}}).catch(l=>{throw l instanceof Hr&&(process.stderr.write(`${wr(l.message)}
|
|
215
|
-
`),process.exit(1)),l})).createProject;if(a?.__typename!=="Project"){let l=a?.message??"unknown error";process.stderr.write(`${wr(l)}
|
|
216
|
-
`),process.exit(1)}process.stdout.write(`${JSON.stringify({project:{id:a.id,name:a.name}},null,2)}
|
|
217
|
-
`)}async function id(e){let n=((await d({config:e,document:td,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?bo():vo(n)}
|
|
218
|
-
`),process.exit(1)}import{spawnSync as je}from"child_process";function Ro(){if(je("claude",["--version"],{stdio:"ignore"}).error!=null)return{kind:"claude-missing"};je("claude",["plugin","marketplace","add","ripplo/claude-plugin"],{stdio:"ignore"});let r=je("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:je("claude",["/ripplo:setup"],{stdio:"inherit"}).status??0,kind:"launched"}}function Co(){return"Installing the Ripplo plugin for Claude Code, then handing off to a guided setup session."}function Eo(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 $o(){process.stdout.write(`${Co()}
|
|
220
|
-
`);let e=Ro();e.kind!=="launched"&&(process.stderr.write(`${Eo(e)}
|
|
221
|
-
`),process.exit(1)),process.exit(e.exitCode)}import sd from"path";import{CancellationTokenSource as ad}from"vscode-jsonrpc/node";function Me(e){return`ripplo: workspace build is stale (${e.join(", ")}) \u2014 rebuilding`}function Le(){return"ripplo: workspace build failed \u2014 fix the build, then rerun"}function te(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 Po({all:e,headed:r,ids:n}){let t=process.cwd(),o=process.argv[1];o==null&&D(xe({kind:"spawn-failed",message:"process.argv[1] missing"})),cd();let i=await et(t);i!=null&&D(tt(i));let a=(await Qn({cliEntry:o,cwd:t})).match(p=>p,p=>D(xe(p)));a.versionNote?.kind==="stale-busy"&&D(lr(a.versionNote)),a.versionNote!=null&&process.stderr.write(`${lr(a.versionNote)}
|
|
222
|
-
`);let l=new ad;process.once("SIGINT",()=>{l.cancel(),a.socket.destroy(),process.exit(130)});let c=sd.join(t,".ripplo","debug"),m=(await Zn({connection:a,onEvent:ld(c),request:{all:e,headed:r,tests:[...n]},token:l.token})).match(p=>p,p=>D(xe(p)));await dd({connection:a,result:m})}function ld(e){let r=!1;return n=>{let t=nt({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 dd({connection:e,result:r}){await new Promise(n=>{e.socket.end(n)}),r.kind==="daemon-error"&&D(ot(r.error)),await I("first_run_finished"),process.stdout.write(`${rt(r)}
|
|
224
|
-
`),r.failed>0&&process.exit(1),process.exit(r.notRun>0?2:0)}function D(e){process.stderr.write(`${e}
|
|
225
|
-
`),process.exit(1)}function cd(){let e=F();if(e.kind==="fresh")return;if(e.kind==="foreign-binary"){let n=te(e);D(n??"foreign binary in the ripplo workspace")}process.stderr.write(`${Me(e.packages)}
|
|
226
|
-
`),Se(e.workspaceRoot)||D(Le())}import B from"path";import gd from"os";import{mkdtempSync as yd,rmSync as hd}from"fs";import{err as Fe,ok as xr}from"neverthrow";import{readdir as ud,rm as pd,stat as md}from"fs/promises";import{existsSync as fd}from"fs";import vr from"path";async function Sr(e,r){let t=(await ud(e,{withFileTypes:!0}).catch(()=>[])).filter(s=>s.isDirectory()).map(s=>s.name).filter(s=>s.startsWith("replay-")||s.startsWith("explore-")||fd(vr.join(e,s,Gr)));if(t.length<=r)return;let i=(await Promise.all(t.map(async s=>({mtime:(await md(vr.join(e,s)).catch(()=>null))?.mtimeMs??0,name:s})))).toSorted((s,a)=>a.mtime-s.mtime).slice(r);await Promise.all(i.map(s=>pd(vr.join(e,s.name),{force:!0,recursive:!0}).catch(()=>{})))}var Io=50,kd=15e3,wd=15e3;async function Ao(){fe(w());let e=process.cwd(),r=G.child({worker:process.pid}),n=Rt(),t=yd(B.join(gd.tmpdir(),"ripplo-browser-cache-")),o=ke({cacheDir:t,clientVersion:w(),debugDir:B.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)},kd).unref(),Rd(i).then(()=>o.close().catch(()=>{})).then(()=>{hd(t,{force:!0,recursive:!0}),process.exit(l)})};bd({exit:a,workerLogger:r}),n.onRequest(ht,async(l,c)=>{let g=ft.safeParse(l);if(!g.success)return Oe("bad-run-assign");let m=g.data;ie(e);let p=y(e).match(v=>v,v=>v.kind);if(typeof p=="string")return Oe(`config:${p}`);let $=await To(n);if($.isErr())return Oe(`lockfile-unavailable:${$.error}`);let T=$.value,E=Z(T).find(v=>v.ref===m.testRef);if(E==null)return Oe(`no-test:${m.testRef}`);let me=Et({config:p,intervalMs:wd,runId:m.runId});try{let{outcome:v,persisted:er,progress:Hs}=await $t({config:p,cwd:e,errorSettle:"settle",fixturesDir:B.join(e,se),headed:m.headed,lockfile:T,onProgress:vd({connection:n,runId:m.runId}),runId:m.runId,session:o,signal:dr(c),test:E.test}),Dr=B.join(e,".ripplo","debug");return s(Promise.allSettled([er]).then(()=>Sd({config:p,debugDir:Dr,progress:Hs,runId:m.runId})).then(()=>Sr(Dr,Io)).catch(()=>{})),{outcome:mt(v),serverNotified:!0}}catch(v){let er=B.join(e,".ripplo","debug");if(s(ee({config:p,debugDir:er,runId:m.runId}).catch(()=>{})),v instanceof Br)return{outcome:{detail:v.message,kind:"infra-error"},serverNotified:!1};throw v}finally{me()}}),n.onRequest(bt,(l,c)=>Cd({connection:n,cwd:e,raw:l,session:o,token:c,track:s})),n.onNotification(vt,l=>{let c=gt.safeParse(l);c.success&&o.injectSpan(c.data.runId,c.data.span)}),n.onNotification(xt,()=>{a(0)}),n.sendNotification(yt),await new Promise(()=>{})}function bd({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 vd({connection:e,runId:r}){return n=>{e.sendNotification(St,{runId:r,signal:n})}}async function Sd({config:e,debugDir:r,progress:n,runId:t}){n?.report({activity:{kind:"uploadingReplay"},deadlineAt:null,retry:null}),await n?.flush(),n!=null&&Pt({debugDir:r,history:n.history(),runId:t}),await ee({config:e,debugDir:r,runId:t})}function Oe(e){return{outcome:{detail:e,kind:"error"},serverNotified:!1}}var xd=5e3;async function Rd(e){e.size!==0&&await Promise.race([Promise.allSettled(e),new Promise(r=>{setTimeout(r,xd)})])}async function Cd({connection:e,cwd:r,raw:n,session:t,token:o,track:i}){let s=wt.safeParse(n);if(!s.success)return{error:{reason:"format-unsupported",source:"assignment-rejected"},kind:"error"};let{assign:a,currentTargetGeneration:l,devSessionId:c}=s.data;ie(r);let g=y(r).match(v=>v,v=>v.kind);if(typeof g=="string")return{error:{detail:g,source:"config"},kind:"error"};let m=await To(e);if(m.isErr())return{error:{source:"lockfile-stale"},kind:"error"};let p=m.value,$=await be(r);if($==null)return{error:{source:"lockfile-stale"},kind:"error"};let T=B.join(g.cwd,".ripplo","debug"),E=await It({assign:a,config:g,currentModelHash:$,currentTargetGeneration:l,debugDir:T,devSessionId:c??void 0,fixturesDir:B.join(g.cwd,se),headed:!1,lockfile:p,report:!0,session:t,signal:dr(o)}),me=(E.kind==="finding"||E.kind==="coverage-gap")&&E.runId!=null?ee({config:g,debugDir:T,runId:E.runId}):Promise.resolve();return i(me.then(()=>Sr(T,Io)).catch(()=>{})),E}async function To(e){return(await Ed(e)).andThen(n=>n.unavailable!=null?Fe(n.unavailable):n.lockfileJson==null?Fe("empty-reply"):$d(n.lockfileJson))}async function Ed(e){try{return xr(await e.sendRequest(kt))}catch(r){return Fe(`transport:${r instanceof Error?r.message:"unknown"}`)}}var Ne;function $d(e){if(Ne!==void 0&&Ne.json===e)return xr(Ne.lockfile);try{let r=ln(N(j,e));return Ne={json:e,lockfile:r},xr(r)}catch(r){return Fe(`worker-decode-failed:${r instanceof Error?r.message.slice(0,200):"unknown"}`)}}async function jo(){await Ao()}import{existsSync as Fd}from"fs";import Wd from"path";import{ok as Dd}from"neverthrow";import{gunzipSync as Pd}from"zlib";import{mkdir as Id,writeFile as Ad}from"fs/promises";import Mo from"path";import{graphql as Td}from"gql.tada";import{err as le,ok as jd}from"neverthrow";var Md=31,Ld=139;async function We(e,r){let n=y(e).match(s=>s,s=>s.kind);if(typeof n=="string")return le({detail:n,kind:"config"});let t=await d({config:n,document:Od,variables:{id:r}}).catch(()=>null);if(t==null)return le({kind:"request-failed"});if(t.run==null)return le({kind:"not-found"});if(t.run.behaviorUrl==null)return le({kind:"not-uploaded"});let o=await fetch(t.run.behaviorUrl);if(!o.ok)return le({kind:"download-failed",status:o.status});let i=Mo.join(e,".ripplo","debug",r,"behavior.jsonl");return await Id(Mo.dirname(i),{recursive:!0}),await Ad(i,Nd(Buffer.from(await o.arrayBuffer()))),jd({path:i,runId:r})}var Od=Td(`
|
|
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 Bo=" \u203A ",Sc=["fact ","data rule ","step "];function Go(e){if(e.failures.length===0)return xc(e);let r=e.viewport==null?"":` (viewport ${String(e.viewport.width)}\xD7${String(e.viewport.height)})`,n=`${e.runId} \u2014 ${M(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 ${sr(o.signal)}`)],s=Rc(e.failures).map(a=>Cc(a,e.runId));return[n,...t,...i,"",...s,x("tasks")].join(`
|
|
249
|
-
`)}function Ko(e){return`${u.bad("fail")} \u2014 no artifacts for ${e.runId}. Run \`npx ripplo pull ${e.runId}\` first.`}function xc(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: ${sr(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 Rc(e){return[...new Set(e.map(n=>n.step))].map(n=>({failures:e.filter(t=>t.step===n),step:n}))}function Cc(e,r){let n=e.failures[0];if(n==null)return"";let t=Ec(e,r);if(t!=null)return t;let o=[...new Set(e.failures.map(s=>s.error==null?Qo(s.label):Q(s.error)))].join(", "),i=u.dim(`(${n.runWorkflow})`);return[`${u.bad("\u2717")} ${Pc(e.step)} ${i}`,` ${u.dim("failed")} ${o}`,...Ic(e),...Mc(n),...Lc(n.causes),` ${u.dim("frame")} npx ripplo snapshot ${r} --at ${String(n.snapshotAt)}`,""].join(`
|
|
250
|
-
`)}function Ec(e,r){let n=e.failures[0],t=e.failures.flatMap(c=>c.browserMismatch==null?[]:[c.browserMismatch])[0],o=Jo(e.failures.flatMap(c=>c.rules));if(n==null||t==null||o.length===0)return null;let i=Qo(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 Jo(e){let r=e.map(n=>[$c(n),n]);return[...new Map(r).values()]}function $c(e){return`${e.url}|${e.when}|${e.origins.map(r=>r.intent).join(",")}`}function Qo(e){let r=Sc.find(n=>e.startsWith(n));return r==null?e:e.slice(r.length)}function Pc(e){let r=e.split(Bo);return r.length<2?e:r.slice(1).join(Bo)}function Ic(e){let r=Jo(e.failures.flatMap(n=>n.rules));return r.length===0?[]:[...r.flatMap(n=>Ac(n)),...jc(e,r)]}function Ac(e){let r=e.origins.length===0?u.dim("origin not in lockfile"):e.origins.map(n=>Tc(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 Tc(e){if(e.sourcePath==null)return e.intent;let r=u.dim(`(${e.sourcePath})`);return`${e.intent} ${r}`}function jc(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 Mc(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 Lc(e){if(e.length===0)return[];let r=Oc(e),n=e.flatMap(t=>Nc(t,r));return n.length===0?[]:[` ${u.dim("nearby")} ${n.join(" \xB7 ")}`]}function Oc(e){let r=e.flatMap(n=>n.detail.kind==="span"&&n.detail.traceId!=null?[[n.detail.traceId,n.detail]]:[]);return new Map(r)}function Nc(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 ${$r(t)}`;return[zo(n,`${$r(n)}${o}`)]}return[zo(n,$r(n))]}function $r(e){return e.kind==="network"?`${e.method} ${String(e.status)} ${Fc(e.url)}`:e.kind==="console"?`console.${e.level} ${Ho(e.text)}`:e.kind==="error"?`error ${Ho(e.message)}`:`span ${e.name} ${e.statusCode} ${String(Math.round(e.durationMs))}ms`}function Fc(e){let r=e.split("?")[0]??e;return r.length>60?`\u2026${r.slice(-57)}`:r}function Ho(e){let r=e.replaceAll(/\s+/g," ").trim();return r.length>100?`${r.slice(0,97)}\u2026`:r}function zo(e,r){return Wc(e)?u.bad(r):r}function Wc(e){return e.kind==="network"?e.status>=400:e.kind==="console"?e.level==="error":e.kind==="error"||e.statusCode==="error"}function Zo(e){return[Dc(e.test),"",Uc(e.factOrigins),Vc(e.timeline,e.factOrigins)].filter(r=>r.length>0).join(`
|
|
252
|
-
`)}function Dc(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: ${_c(e)}`]].join(`
|
|
253
|
-
`)}function _c(e){return e.actor.kind==="user"?`signed in as ${e.actor.alias}`:"signed out"}function Uc(e){return e.length===0?"":["facts checked here were declared in",...e.map(n=>` - ${n}`),""].join(`
|
|
254
|
-
`)}function Vc(e,r){return e.length===0?u.dim("timeline (no steps captured)"):["what happened, step by step",...e.map(t=>qc(t,r))].join(`
|
|
255
|
-
`)}function qc(e,r){let n=` ${String(e.index+1)}. ${e.title}${Bc(e.workflow)}${Hc(e.url)}`,t=e.changes.length===0?[]:[` \u0394 ${e.changes.join(", ")}`],o=e.failures.map(s=>` ${u.bad("\u2717")} ${zc(s,r)}`),i=e.checksHeld===0?[]:[u.dim(` ${String(e.checksHeld)} checks held`)];return[n,...t,...o,...i].join(`
|
|
256
|
-
`)}function Bc(e){if(e==null)return"";let r=`(${e})`;return` ${u.dim(r)}`}function Hc(e){if(e==null)return"";let r=`@ ${e}`;return` ${u.dim(r)}`}function zc(e,r){switch(e.kind){case"check":{let n=e.event.origin.kind==="fact"?Gc(r):"";return`${wn(e.event)}${n}`}case"stepError":return`run error \u2014 ${Q(e.event.error)}`;case"finding":return Kc(e.payload)}}function Gc(e){if(e.length===0)return"";let r=`(fact from ${e.join(", ")})`;return` ${u.dim(r)}`}function Kc(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 Xo(e){return`Saved behavior.jsonl to ${e.path}`}function U(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 Yo({full:e,json:r,runId:n}){let t=process.cwd(),o=await _(t,n);o.isErr()&&(process.stderr.write(`${U(o.error)}
|
|
257
|
-
`),process.exit(1));let i=Wo(t,n).match(s=>s,s=>(process.stderr.write(`${Ko(s)}
|
|
258
|
-
`),process.exit(1)));process.stdout.write(`${r?JSON.stringify(i,null,2):Go(i)}
|
|
259
|
-
`),e&&!r&&await Jc(t,n,Qc(i))}async function Jc(e,r,n){let t=y(e).unwrapOr(void 0);if(t==null)return;let o=await qo(e,r,t);process.stdout.write(`
|
|
260
|
-
${Zo({...o,factOrigins:n})}
|
|
261
|
-
`)}function Qc(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 ei({runId:e}){(await We(process.cwd(),e)).match(n=>{process.stdout.write(`${Xo(n)}
|
|
262
|
-
`)},n=>{process.stderr.write(`${U(n)}
|
|
263
|
-
`),process.exit(1)})}import{randomUUID as Zc}from"crypto";import{existsSync as Xc,readFileSync as Yc}from"fs";import Pr from"path";import{graphql as ni}from"gql.tada";import{err as _e,ok as ri}from"neverthrow";async function ti(e,r,n){let t=eu(e);if(t.kind==="error")return _e(t.error);let o=t.config,i=await ge(e);if(i.result.isErr())return _e({kind:"compile-failed"});let s=await ru({config:o,runId:r});if(s.kind==="error")return _e(s.error);let{repro:a,reproJson:l}=s,c=await X(e,i.result.value),g=Mn(c);await jn({config:o,cwd:e,lockfile:c});let m=`replay-${Zc()}`,p=Pr.join(e,".ripplo","debug"),$=[],T=ke({cacheDir:void 0,clientVersion:w(),debugDir:p,headed:!1,writeOtlpPortFile:!1});try{let E=await $n({capture:!0,lockfile:c,options:{baseUrl:o.appUrl,engineUrl:o.engineUrl,fixturesDir:Pr.join(e,se),generate:nn,headed:!1,secret:o.webhookSecret},repro:a,runId:m,session:T,signal:n,onEvent:v=>{$.push(v)}});return(await tu({config:o,debugDir:p,events:$,lockfileHash:g,outcome:E,replayRunId:m,reproJson:l,stepSources:nu({lockfile:c,repro:a})})).map(()=>({outcome:E,recordingCaptured:ou(p,m),replayRunId:m}))}finally{await T.close()}}function eu(e){return y(e).match(r=>({config:r,kind:"found"}),r=>({error:{detail:r.kind,kind:"config"},kind:"error"}))}async function ru({config:e,runId:r}){let n=await d({config:e,document:iu,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=he(t);return o.kind==="rejected"?{error:{kind:"stale-repro",reason:"format-unsupported"},kind:"error"}:{kind:"found",repro:o.repro,reproJson:t}}function nu({lockfile:e,repro:r}){let n=gn(e);return r.steps.map(t=>n.find(o=>o.id===t.transitionId)?.test??null)}async function tu({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 ri(void 0);try{return await d({config:e,document:su,variables:{lockfileHash:t,projectId:e.projectId,reproJson:s,runId:i}}),await Ct({config:e,debugDir:r,events:n,recordingOptional:!0,runId:i,stepSources:a}),await ee({config:e,debugDir:r,runId:i}),ri(void 0)}catch{return _e({kind:"report-failed"})}}function ou(e,r){let n=Pr.join(e,r,"behavior.jsonl");return Xc(n)?Yc(n,"utf8").split(`
|
|
264
|
-
`).some(t=>t.includes('"kind":"rrweb"')):!1}var iu=ni(`
|
|
265
|
-
query RunRepro($id: String!) {
|
|
266
|
-
run(id: $id) {
|
|
267
|
-
id
|
|
268
|
-
reproJson
|
|
269
|
-
}
|
|
270
|
-
}
|
|
271
|
-
`),su=ni(`
|
|
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 oi({outcome:e,recordingCaptured:r,replayRunId:n}){let t=au(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 au(e){switch(e.kind){case"resolved":return"\u2713 Resolved \u2014 the finding's trail ran clean.";case"still-fails":return`\u2717 Still failing \u2014 ${M(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 ii(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 si(e){return e.kind==="resolved"}async function ai({runId:e}){(await ti(process.cwd(),e,new AbortController().signal)).match(n=>{process.stdout.write(`${oi(n)}
|
|
290
|
-
`),process.exit(si(n.outcome)?0:1)},n=>{process.stderr.write(`${ii(n)}
|
|
291
|
-
`),process.exit(1)})}import ui from"path";import{existsSync as fu}from"fs";import{writeFile as li}from"fs/promises";import di from"path";import{err as ce,ok as gu}from"neverthrow";import{readFile as lu}from"fs/promises";import{z as de}from"zod";var du={height:800,width:1280};async function Ue(e){let r=await lu(e,"utf8");return K(r).flatMap(n=>n.kind==="rrweb"?[n.event]:[])}var cu=de.object({data:de.looseObject({height:de.number(),width:de.number()}),type:de.literal(4)});function oe(e){let r=e.flatMap(n=>{let t=cu.safeParse(n);return t.success?[t.data]:[]})[0];return r==null?du:{height:r.data.height,width:r.data.width}}var uu='<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>',pu=`.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,${uu}');
|
|
300
|
-
}`,mu=".replayer-mouse, .replayer-mouse-tail { display: none; }";function Ve(e){return`<!doctype html><html><head><style>
|
|
301
|
-
html, body { margin: 0; padding: 0; }
|
|
302
|
-
.replayer-wrapper { position: relative; }
|
|
303
|
-
${e?pu:mu}
|
|
304
|
-
iframe { border: none; }
|
|
305
|
-
</style></head><body></body></html>`}function qe(){return`(() => {
|
|
306
|
-
const doc = document.querySelector(".replayer-wrapper iframe")?.contentDocument;
|
|
307
|
-
if (doc == null || doc.querySelector("style[data-ripplo-replay-styles]") != null) {
|
|
308
|
-
return;
|
|
309
|
-
}
|
|
310
|
-
const style = doc.createElement("style");
|
|
311
|
-
style.setAttribute("data-ripplo-replay-styles", "");
|
|
312
|
-
style.textContent = ${JSON.stringify(un.join(`
|
|
313
|
-
`))};
|
|
314
|
-
(doc.head ?? doc.documentElement).appendChild(style);
|
|
315
|
-
})()`}function Be(){return`(async () => {
|
|
316
|
-
const doc = document.querySelector(".replayer-wrapper iframe")?.contentDocument;
|
|
317
|
-
if (doc?.fonts != null) {
|
|
318
|
-
await doc.fonts.ready;
|
|
319
|
-
}
|
|
320
|
-
await new Promise((resolve) => requestAnimationFrame(() => requestAnimationFrame(resolve)));
|
|
321
|
-
})()`}function He(){return import("playwright").then(({chromium:e})=>e.launch({args:["--no-sandbox"],headless:!0})).catch(()=>null)}var ze=Rn(xn("@ripplo/rrweb-bundle/replay","rrweb-replay.js"));async function ci({jsonlPath:e,moment:r,outDir:n,runId:t}){if(!fu(e))return ce({kind:"run-not-found",runId:t});let o=await Ue(e),i=o[0],s=o.at(-1);if(i==null||s==null)return ce({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 ce({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)),m=di.join(n,`snapshot-${g}ms.png`),p=di.join(n,`snapshot-${g}ms.html`);return(await yu({events:o,htmlPath:p,offsetMs:c,pngPath:m})).map(()=>({durationMs:a,htmlPath:p,offsetMs:c,pngPath:m,viewport:oe(o)}))}async function yu({events:e,htmlPath:r,offsetMs:n,pngPath:t}){let o=await He();if(o==null)return ce({detail:"chromium launch",kind:"browser-failed"});try{let{html:i,png:s}=await hu({browser:o,events:e,offsetMs:n});return await li(t,s),await li(r,i,"utf8"),gu(void 0)}catch(i){return ce({detail:i instanceof Error?i.message:String(i),kind:"browser-failed"})}finally{await o.close()}}async function hu({browser:e,events:r,offsetMs:n}){let t=oe(r),o=await e.newPage({viewport:t});await o.setContent(Ve(!1)),await o.addScriptTag({content:await ze()}),await o.evaluate(ku({events:r,offsetMs:n})),await o.evaluate(qe()),await o.evaluate(Be());let i=o.locator(".replayer-wrapper iframe").first(),a=await(await i.count()>0?i:o).screenshot({type:"png"});return{html:await o.evaluate(wu()),png:a}}function ku({events:e,offsetMs:r}){return`(() => {
|
|
322
|
-
const replayer = new globalThis.__RipploReplayer(${JSON.stringify(e)}, {
|
|
323
|
-
mouseTail: false,
|
|
324
|
-
root: document.body,
|
|
325
|
-
showWarning: false,
|
|
326
|
-
});
|
|
327
|
-
replayer.pause(${String(r+.5)});
|
|
328
|
-
globalThis.__ripploSnapshotReplayer = replayer;
|
|
329
|
-
})()`}function wu(){return`(() => {
|
|
330
|
-
const replayer = globalThis.__ripploSnapshotReplayer;
|
|
331
|
-
if (replayer == null) {
|
|
332
|
-
return "";
|
|
333
|
-
}
|
|
334
|
-
const mirror = replayer.getMirror();
|
|
335
|
-
const iframe = document.querySelector(".replayer-wrapper iframe");
|
|
336
|
-
const doc = iframe == null ? null : iframe.contentDocument;
|
|
337
|
-
if (doc == null) {
|
|
338
|
-
return "";
|
|
339
|
-
}
|
|
340
|
-
Array.from(doc.querySelectorAll("*")).forEach((el) => {
|
|
341
|
-
const id = mirror.getId(el);
|
|
342
|
-
if (id != null && id > 0) {
|
|
343
|
-
el.setAttribute("data-rrweb-id", String(id));
|
|
344
|
-
}
|
|
345
|
-
});
|
|
346
|
-
return "<!doctype html>\\n" + doc.documentElement.outerHTML;
|
|
347
|
-
})()`}function pi({cwd:e,moment:r,runId:n}){let t=ui.join(e,".ripplo","debug",n);return ci({jsonlPath:ui.join(t,"behavior.jsonl"),moment:r,outDir:t,runId:n})}function mi(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(`
|
|
348
|
-
`)}function fi(e){return`${u.bad("fail")} \u2014 ${bu(e)}`}function gi(){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 bu(e){switch(e.kind){case"run-not-found":return`no debug artifacts for run ${e.runId} (.ripplo/debug/${e.runId}/behavior.jsonl missing). ${x("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 yi({at:e,offset:r,runId:n}){let t=vu({at:e,offset:r});t==null&&(process.stderr.write(`${gi()}
|
|
349
|
-
`),process.exit(1));let o=await _(process.cwd(),n);o.isErr()&&(process.stderr.write(`${U(o.error)}
|
|
350
|
-
`),process.exit(1)),(await pi({cwd:process.cwd(),moment:t,runId:n})).match(s=>{process.stdout.write(`${mi(s)}
|
|
351
|
-
`)},s=>{process.stderr.write(`${fi(s)}
|
|
352
|
-
`),process.exit(1)})}function vu({at:e,offset:r}){if(e!=null&&r==null)return{at:e,kind:"absolute"};if(r!=null&&e==null)return{kind:"offset",offsetMs:r}}import wi from"path";import{spawn as Su}from"child_process";import{existsSync as xu}from"fs";import{mkdtemp as Ru,rm as Cu,writeFile as Eu}from"fs/promises";import $u from"os";import Ge from"path";import{err as H,ok as hi}from"neverthrow";var Ke=12;async function ki({ffmpegPath:e,jsonlPath:r,outDir:n,runId:t}){if(!xu(r))return H({kind:"run-not-found",runId:t});let o=await Ue(r),i=o[0],s=o.at(-1);if(i==null||s==null)return H({kind:"no-rrweb-events",runId:t});let a=s.timestamp-i.timestamp,l=Pu(a),c=Ge.join(n,"replay.mp4"),g=await Ru(Ge.join($u.tmpdir(),"ripplo-video-"));try{let m=await Iu({events:o,framesDir:g,offsets:l});return m.isErr()?H(m.error):(await Lu({ffmpegPath:e,framesDir:g,mp4Path:c})).map(()=>({durationMs:a,frameCount:l.length,mp4Path:c,viewport:oe(o)}))}finally{await Cu(g,{force:!0,recursive:!0})}}function Pu(e){let r=1e3/Ke,n=Math.max(1,Math.floor(e/r)+1);return Array.from({length:n},(t,o)=>Math.min(o*r,e))}async function Iu({events:e,framesDir:r,offsets:n}){let t=await He();if(t==null)return H({detail:"chromium launch",kind:"browser-failed"});try{return await Au({browser:t,events:e,framesDir:r,offsets:n}),hi(void 0)}catch(o){return H({detail:o instanceof Error?o.message:String(o),kind:"browser-failed"})}finally{await t.close()}}async function Au({browser:e,events:r,framesDir:n,offsets:t}){let o=await e.newPage({viewport:oe(r)});await o.setContent(Ve(!0)),await o.addScriptTag({content:await ze()}),await o.evaluate(Tu(r)),await o.evaluate(Be());let i=o.locator(".replayer-wrapper").first(),s=await i.count()>0?i:o;await t.reduce(async(a,l,c)=>{await a,await o.evaluate(ju(l)),await o.evaluate(qe());let g=await s.screenshot({type:"png"});await Eu(Ge.join(n,Mu(c)),g)},Promise.resolve())}function Tu(e){return`(() => {
|
|
353
|
-
const replayer = new globalThis.__RipploReplayer(${JSON.stringify(e)}, {
|
|
354
|
-
mouseTail: false,
|
|
355
|
-
root: document.body,
|
|
356
|
-
showWarning: false,
|
|
357
|
-
});
|
|
358
|
-
replayer.pause(0.5);
|
|
359
|
-
globalThis.__ripploVideoReplayer = replayer;
|
|
360
|
-
})()`}function ju(e){return`globalThis.__ripploVideoReplayer.pause(${String(e+.5)})`}function Mu(e){return`frame-${String(e).padStart(5,"0")}.png`}async function Lu({ffmpegPath:e,framesDir:r,mp4Path:n}){try{let{code:t,stderr:o}=await Ou({ffmpegPath:e,framesDir:r,mp4Path:n});return t===0?hi(void 0):H({detail:o.trim().slice(-400),kind:"encode-failed"})}catch(t){return H({detail:t instanceof Error?t.message:String(t),kind:"encode-failed"})}}function Ou({ffmpegPath:e,framesDir:r,mp4Path:n}){return new Promise((t,o)=>{let i=["-y","-framerate",String(Ke),"-i",Ge.join(r,"frame-%05d.png"),"-c:v","libx264","-pix_fmt","yuv420p","-vf","pad=ceil(iw/2)*2:ceil(ih/2)*2",n],s=Su(e,i,{stdio:["ignore","ignore","pipe"]}),a=[];s.stderr.on("data",l=>a.push(l)),s.on("error",o),s.on("close",l=>{t({code:l,stderr:Buffer.concat(a).toString("utf8")})})})}import bi from"ffmpeg-static";import{err as Nu}from"neverthrow";async function vi({cwd:e,runId:r}){if(bi==null)return Nu({kind:"ffmpeg-missing"});let n=wi.join(e,".ripplo","debug",r);return ki({ffmpegPath:bi,jsonlPath:wi.join(n,"behavior.jsonl"),outDir:n,runId:r})}function Si(e){return[`${u.good("ok")} \u2014 rendered ${String(e.frameCount)} frames at ${String(Ke)} fps (duration ${String(Math.round(e.durationMs))}ms, viewport ${String(e.viewport.width)}\xD7${String(e.viewport.height)})`,e.mp4Path,"The MP4 covers the whole recording. Layout and text are faithful \u2014 URL-referenced images may be blank if the dev server is down."].join(`
|
|
361
|
-
`)}function xi(e){return`${u.bad("fail")} \u2014 ${Fu(e)}`}function Fu(e){switch(e.kind){case"run-not-found":return`no debug artifacts for run ${e.runId} (.ripplo/debug/${e.runId}/behavior.jsonl missing). ${x("run")}`;case"no-rrweb-events":return`run ${e.runId} has a behavior.jsonl but no rrweb events \u2014 nothing to replay.`;case"browser-failed":return`replay browser failed (${e.detail}). Is chromium installed? Try \`npx playwright install chromium\`.`;case"encode-failed":return`ffmpeg failed to encode the video (${e.detail}).`;case"ffmpeg-missing":return"the bundled ffmpeg has no binary for this platform. Install ffmpeg and set FFMPEG_BIN to its path."}}async function Ri({runId:e}){let r=await _(process.cwd(),e);r.isErr()&&(process.stderr.write(`${U(r.error)}
|
|
362
|
-
`),process.exit(1)),(await vi({cwd:process.cwd(),runId:e})).match(t=>{process.stdout.write(`${Si(t)}
|
|
363
|
-
`)},t=>{process.stderr.write(`${xi(t)}
|
|
364
|
-
`),process.exit(1)})}function Ci(e,r){switch(e.kind){case"config-failed":return S(e.failure);case"compile-failed":return Y(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: ${Q(e.error)}`;case"done":return Wu(e.result,r)}}function Ei(e){return e.kind==="done"&&e.result.kind==="handed-over"}function $i(e,r){return`landed at step ${String(e)} of ${r} \u2014 close the window to tear down`}function Wu(e,r){return e.kind==="failed"?`couldn't reach the step \u2014 the run failed first.
|
|
365
|
-
|
|
366
|
-
${e.contradictions.map(t=>kn({contradiction:t,evidencePath:void 0})).join(`
|
|
367
|
-
|
|
368
|
-
`)}`:`torn down \u2014 teleport session for ${r} ended`}async function Pi({ref:e,step:r}){let n=new AbortController;process.once("SIGINT",()=>{n.abort()});let t=()=>{process.stdout.write(`${$i(r,e)}
|
|
369
|
-
`)},o=await At({cwd:process.cwd(),onReady:t,signal:n.signal,step:r,target:{kind:"test",ref:e}});process.stdout.write(`${Ci(o,e)}
|
|
370
|
-
`),process.exit(Ei(o)?0:1)}import Ii from"path";import{randomUUID as Du}from"crypto";async function Ai({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-${Du()}`;return(await Cn({clientVersion:w(),debugDir:Ii.join(t.cwd,".ripplo","debug"),onReady:r,profileDir:Ii.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 Ti(){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 ji(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.":_u(e.behaviorPath,e.runId)}function Mi(e){return e.kind==="done"}function _u(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(`
|
|
371
|
-
`)}async function Li(){let e=new AbortController;process.once("SIGINT",()=>{e.abort()});let r=await Ai({cwd:process.cwd(),onReady:Uu,signal:e.signal});process.stdout.write(`${ji(r)}
|
|
372
|
-
`),process.exit(Mi(r)?0:1)}function Uu(){process.stdout.write(`${Ti()}
|
|
373
|
-
`)}import{existsSync as Vu,readFileSync as qu}from"fs";import Bu from"path";function Oi(e,r){let n=Bu.join(e,".ripplo","debug",r,"behavior.jsonl");return Vu(n)?{actions:En(qu(n,{encoding:"utf8"})),kind:"ok"}:{kind:"not-found",runId:r}}function Ni(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)=>Hu(r,n)).join(`
|
|
374
|
-
`)}function Fi(e){return e.kind==="ok"}function Hu(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 Wi({runId:e}){let r=Oi(process.cwd(),e);process.stdout.write(`${Ni(r)}
|
|
375
|
-
`),process.exit(Fi(r)?0:1)}async function Di(){let e=b();try{let n=(await ae(e.cwd,e)).match(t=>t,t=>{process.stderr.write(`${S(t)}
|
|
376
|
-
`),process.exit(1)});await I("lockfile_synced"),process.stdout.write(`Synced ${String(n.lockfile.workflows.length)} workflows to dev session ${n.devSessionId}
|
|
377
|
-
`)}catch(r){let n=r instanceof Error?r.message:String(r);process.stderr.write(`ripplo sync failed: ${n}
|
|
378
|
-
`),process.stderr.write(`${x("setup","verify auth + server reachability")}
|
|
379
|
-
`),process.exit(1)}}import{spawnSync as Ju}from"child_process";import Qu from"fs";import Zu from"path";import Xu from"semver";import ue from"fs";import zu from"os";import z from"path";function _i(e){let r=e.split(z.sep);return r.includes("_npx")?"npx":e.includes(z.join("packages","cli"))?"workspace":Gu(r)?"local":"global"}function Ui(){let e=z.join(zu.homedir(),".npm","_npx");return ue.existsSync(e)?ue.readdirSync(e).map(r=>z.join(e,r)).filter(r=>ue.existsSync(z.join(r,"node_modules","ripplo"))).map(r=>(ue.rmSync(r,{force:!0,recursive:!0}),r)):[]}function Gu(e){let r=e.lastIndexOf("node_modules");if(r<1)return!1;let n=e.slice(0,r).join(z.sep);return ue.existsSync(z.join(n,"package.json"))}import{spawnSync as Vi}from"child_process";var Ku=["user","project","local"];function Ir(){return Vi("claude",["--version"],{stdio:"ignore"}).error!=null?"claude-missing":Ku.find(n=>Vi("claude",["plugin","update","ripplo","--scope",n],{stdio:"ignore"}).status===0)==null?"not-installed":"updated"}function qi(e){return`ripplo v${e} is already the latest version.`}function Bi(e){return`ripplo v${e}: could not reach the npm registry to check for updates.`}function Ar({evicted:e,latest:r,mode:n}){return n==="npx"?`ripplo: ${e===0?"npx cache had no stale copy":`cleared ${M(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 Hi(){return"ripplo: this is a workspace build (packages/cli/dist) \u2014 update via git pull + `pnpm --filter ripplo build`."}function zi(e){return`ripplo: installed as a project dependency \u2014 update it with your package manager: \`${e}\``}function Gi(e){return`ripplo: \`npm install -g ripplo@latest\` failed: ${e}`}function Tr(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 Ki(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 Yu=1e4;async function Ji(){let e=w(),r=process.argv[1];ep(process.cwd());let n=await Ee(Yu);process.stdout.write(`${Re({current:e,latest:n})}
|
|
380
|
-
`),n==null&&(process.stderr.write(`${Bi(e)}
|
|
381
|
-
`),process.exit(1)),Xu.gt(n,e)||(process.stdout.write(`${qi(e)}
|
|
382
|
-
`),process.stdout.write(`${Tr(Ir())}
|
|
383
|
-
`),process.exit(0));let t=r==null?"global":_i(r);rp({latest:n,mode:t}),process.stdout.write(`${Tr(Ir())}
|
|
384
|
-
`),await tp(process.cwd()),process.exit(0)}function ep(e){if(!Qu.existsSync(Zu.join(e,".ripplo")))return;let r=Ae(e);r==="written"&&process.stdout.write(`${Te(r).trim()}
|
|
385
|
-
`)}function rp({latest:e,mode:r}){if(r==="workspace"&&(process.stdout.write(`${Hi()}
|
|
386
|
-
`),process.exit(0)),r==="local"){let n=process.cwd(),t=fr({cwd:n,pm:gr(n),version:e});process.stdout.write(`${zi(t)}
|
|
387
|
-
`),process.exit(0)}if(r==="npx"){let n=Ui();process.stdout.write(`${Ar({evicted:n.length,latest:e,mode:r})}
|
|
388
|
-
`);return}np(e)}function np(e){let r=`ripplo@${e}`,n=Ju("npm",["install","-g",r],{stdio:"inherit"});if(n.status!==0){let t=`exit ${String(n.status)}`;process.stderr.write(`${Gi(t)}
|
|
389
|
-
`),process.exit(1)}process.stdout.write(`${Ar({evicted:0,latest:e,mode:"global"})}
|
|
390
|
-
`)}async function tp(e){if((await Yn(e)).kind==="not-running")return;let n=await Xn(e);process.stdout.write(`${Ki(n)}
|
|
391
|
-
`)}async function Qi({action:e,exploreDebug:r}){if(e==="status"){let{statusCommand:t}=await import("./status-CNSPYNYP.js");await t({format:"summary"});return}if(e==="stop"||e==="restart"){let t=await op();(e==="stop"||!t)&&process.exit(t?0:1)}ip();let{runDaemon:n}=await import("./daemon-D4UCHMHS.js");await n({exploreDebug:r})}async function op(){let{stopDevDaemon:e}=await import("./daemon-lock-RPKO5SNE.js"),{renderDaemonStopResult:r}=await import("./daemon-LZTY7W4M.js"),n=await e(process.cwd());return process.stdout.write(`${r(n)}
|
|
392
|
-
`),n.kind!=="timeout"}function ip(){let e=te(F());e!=null&&process.stderr.write(`${e}
|
|
393
|
-
`)}function Zi(e){return`executor: ${e}`}function Xi(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 Yi(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 es({mode:e}){let r=y(process.cwd()).match(t=>t,t=>{process.stderr.write(`${S(t)}
|
|
394
|
-
`),process.exit(1)});(e==null?await jt(r):await Mt(r,e)).match(t=>{process.stdout.write(`${e==null?Zi(t):Xi(t)}
|
|
395
|
-
`)},t=>{process.stderr.write(`${Yi(t)}
|
|
396
|
-
`),process.exit(1)})}import{spawnSync as yp}from"child_process";import{graphql as rs}from"gql.tada";import{err as jr,ok as Mr}from"neverthrow";var sp=rs(`
|
|
397
|
-
query ExploreState($devSessionId: String!) {
|
|
398
|
-
exploration(devSessionId: $devSessionId) {
|
|
399
|
-
active
|
|
400
|
-
autoCreateTasks
|
|
401
|
-
cloudWorkers
|
|
402
|
-
localWorkers
|
|
403
|
-
maxTrailLength
|
|
404
|
-
unhealthySince
|
|
405
|
-
}
|
|
406
|
-
}
|
|
407
|
-
`),ap=rs(`
|
|
408
|
-
mutation SetExploration(
|
|
409
|
-
$devSessionId: String!
|
|
410
|
-
$active: Boolean!
|
|
411
|
-
$autoCreateTasks: Boolean!
|
|
412
|
-
$cloudWorkers: Int!
|
|
413
|
-
$localWorkers: Int!
|
|
414
|
-
$maxTrailLength: Int!
|
|
415
|
-
) {
|
|
416
|
-
setExploration(
|
|
417
|
-
devSessionId: $devSessionId
|
|
418
|
-
active: $active
|
|
419
|
-
autoCreateTasks: $autoCreateTasks
|
|
420
|
-
cloudWorkers: $cloudWorkers
|
|
421
|
-
localWorkers: $localWorkers
|
|
422
|
-
maxTrailLength: $maxTrailLength
|
|
423
|
-
) {
|
|
424
|
-
active
|
|
425
|
-
autoCreateTasks
|
|
426
|
-
cloudWorkers
|
|
427
|
-
localWorkers
|
|
428
|
-
maxTrailLength
|
|
429
|
-
unhealthySince
|
|
430
|
-
}
|
|
431
|
-
}
|
|
432
|
-
`);async function ns(e){let r=await os(e);if(r.isErr())return jr(r.error);let n=await is(e,r.value.id);return Mr(ss(r.value.executor,n))}async function ts(e,r){let n=await os(e);if(n.isErr())return jr(n.error);let t=await is(e,n.value.id),o=lp(n.value.executor,t,r),i=await d({config:e,document:ap,variables:{devSessionId:n.value.id,...o}});return Mr(ss(n.value.executor,i.setExploration))}async function os(e){let r=await lt(e);return r.kind==="active"?Mr({executor:r.executor,id:r.id}):jr({kind:r.kind==="starting"?"starting":"no-session"})}async function is(e,r){return(await d({config:e,document:sp,variables:{devSessionId:r}})).exploration??null}function ss(e,r){let n=e==="local";return{active:r?.active??!1,executor:e,maxTrailLength:r?.maxTrailLength??cr,unhealthy:r?.unhealthySince!=null,workers:(n?r?.localWorkers:r?.cloudWorkers)??0}}function lp(e,r,n){let t=e==="local",o=(t?r?.localWorkers:r?.cloudWorkers)??0,i=(t?r?.cloudWorkers:r?.localWorkers)??0,s=dp(n,o);return{active:n.active,autoCreateTasks:r?.autoCreateTasks??!1,cloudWorkers:t?i:s,localWorkers:t?s:i,maxTrailLength:n.trail??r?.maxTrailLength??cr}}function dp(e,r){return e.active?e.workers!=null?e.workers:r>0?r:Lt:r}function as(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}
|
|
433
|
-
explorer is hitting infra errors \u2014 it pauses if this persists`:r}function ls(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 ds(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 cp=32;async function cs({cwd:e,maxTrailLength:r}){let n=await ge(e);if(n.result.isErr())return{kind:"error",reason:"compile-failed"};let t=await be(e);if(t==null)return{kind:"error",reason:"no-lockfile"};let o=await X(e,n.result.value),i=vn(o);return i.kind==="model-empty"?{kind:"error",reason:"model-empty"}:{analysis:await Sn({attempts:cp,modelHash:t,prepared:i.value,strategy:r==null?or("even"):{...or("even"),maxAttemptLength:r}}),kind:"ok"}}function ps(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.`,up(e),pp(e),mp(e),fp(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.`,...us({heading:"Targets without a proved path:",transitions:e.isolatedTransitions}),...us({heading:"Targets reached in one planned path:",transitions:e.weaklyConnectedTransitions}),...gp(e.recommendations)].join(`
|
|
434
|
-
`)}function ms(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 up(e){let r=e.planningDepth;return`Path length target: ${String(r.targetSteps)} steps. Planned ${pe(r.averagePlannedSteps)} on average and ${String(r.maxPlannedSteps)} at most after searching ${pe(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 pe(e){return String(Math.round(e))}function pp(e){let r=e.planningPerformance;return`Planner average: ${V(r.total.averageMs)} total, ${V(r.envelopes.averageMs)} starting states, ${V(r.search.averageMs)} search, and ${V(r.selection.averageMs)} selection. Total p95: ${V(r.total.p95Ms)}.`}function V(e){return`${String(Math.round(e))} ms`}function mp(e){let r=e.planningPerformance;return`Search average: ${V(r.expansion.averageMs)} proving runnable steps, ${V(r.candidates.averageMs)} scoring candidates, and ${V(r.beam.averageMs)} retaining the beam.`}function fp(e){let r=e.planningWork;return`Search average: ${pe(r.averageExpandedNodes)} expanded nodes after considering ${pe(r.averageRulesConsidered)} transitions and ${pe(r.averageParameterAttempts)} parameter attempts.`}function us({heading:e,transitions:r}){return r.length===0?[]:[e,...r.map(n=>`- ${n.test}: ${n.action}`)]}function gp(e){return e.length===0?["No workflow coverage improvements are required by this analysis."]:["Recommendations:",...e.map(r=>`- ${r}`)]}async function fs({json:e,state:r,trail:n,workers:t}){if(r==="analyze"){hp();let s=await cs({cwd:process.cwd(),maxTrailLength:n});s.kind==="error"&&(process.stderr.write(`${ms(s.reason)}
|
|
435
|
-
`),process.exit(1)),process.stdout.write(`${e?JSON.stringify(s.analysis,null,2):ps(s.analysis)}
|
|
436
|
-
`);return}let o=y(process.cwd()).match(s=>s,s=>{process.stderr.write(`${S(s)}
|
|
437
|
-
`),process.exit(1)});(r==null?await ns(o):await ts(o,{active:r==="on",trail:n,workers:t})).match(s=>{process.stdout.write(`${r==null?as(s):ls(s)}
|
|
438
|
-
`)},s=>{process.stderr.write(`${ds(s)}
|
|
439
|
-
`),process.exit(1)})}function hp(){let e=F();e.kind!=="fresh"&&(e.kind==="foreign-binary"&&Je(te(e)??"This command is not using the workspace CLI."),process.stderr.write(`${Me(e.packages)}
|
|
440
|
-
`),Se(e.workspaceRoot)||Je(Le()),kp())}function Je(e){process.stderr.write(`${e}
|
|
441
|
-
`),process.exit(1)}function kp(){let e=process.argv[1];e==null&&Je("Ripplo rebuilt the workspace but could not find the CLI entry point.");let r=yp(process.execPath,[e,...process.argv.slice(2)],{cwd:process.cwd(),stdio:"inherit"});r.error!=null&&Je(`Ripplo rebuilt the workspace but could not restart analysis: ${r.error.message}`),process.exit(r.status??1)}import{graphql as Qe}from"gql.tada";function gs(){return"No scope items added \u2014 matched tests already in scope (`npx ripplo scope status`)."}function ys(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`.",x("create")].join(`
|
|
442
|
-
`)}import{graphql as wp}from"gql.tada";var hs=wp(`
|
|
443
|
-
query ScopeStatus($projectId: String!, $cwd: String!) {
|
|
444
|
-
project(id: $projectId) {
|
|
445
|
-
id
|
|
446
|
-
devSession(cwd: $cwd) {
|
|
447
|
-
id
|
|
448
|
-
scopeItems {
|
|
449
|
-
id
|
|
450
|
-
label
|
|
451
|
-
source
|
|
452
|
-
workflow {
|
|
453
|
-
id
|
|
454
|
-
slug
|
|
455
|
-
name
|
|
456
|
-
spec
|
|
457
|
-
}
|
|
458
|
-
}
|
|
459
|
-
}
|
|
460
|
-
}
|
|
461
|
-
}
|
|
462
|
-
`);var bp=Qe(`
|
|
463
|
-
query ScopeWorkflowBySlug($projectId: String!, $cwd: String!, $slug: String!) {
|
|
464
|
-
project(id: $projectId) {
|
|
465
|
-
id
|
|
466
|
-
devSession(cwd: $cwd) {
|
|
467
|
-
id
|
|
468
|
-
workflows(where: { slug: $slug }) {
|
|
469
|
-
id
|
|
470
|
-
slug
|
|
471
|
-
}
|
|
472
|
-
}
|
|
473
|
-
}
|
|
474
|
-
}
|
|
475
|
-
`),vp=Qe(`
|
|
476
|
-
mutation ScopeAddDirtyTests($projectId: String!, $cwd: String!, $workflowSlugs: [String!]!) {
|
|
477
|
-
addDirtyTestsToScope(projectId: $projectId, cwd: $cwd, workflowSlugs: $workflowSlugs) {
|
|
478
|
-
__typename
|
|
479
|
-
... on MutationAddDirtyTestsToScopeSuccess {
|
|
480
|
-
data {
|
|
481
|
-
id
|
|
482
|
-
workflow {
|
|
483
|
-
id
|
|
484
|
-
slug
|
|
485
|
-
}
|
|
486
|
-
}
|
|
487
|
-
}
|
|
488
|
-
... on NoActiveDevSessionError {
|
|
489
|
-
message
|
|
490
|
-
}
|
|
491
|
-
... on UnknownWorkflowSlugsError {
|
|
492
|
-
message
|
|
493
|
-
slugs
|
|
494
|
-
}
|
|
495
|
-
}
|
|
496
|
-
}
|
|
497
|
-
`),Sp=Qe(`
|
|
498
|
-
mutation ScopeLink($id: ID!, $workflowId: String!) {
|
|
499
|
-
linkScopeItem(id: $id, workflowId: $workflowId) {
|
|
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) {
|
|
500
43
|
id
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
removeScopeItems(ids: $ids)
|
|
506
|
-
}
|
|
507
|
-
`);async function ks(e){let r=b();await R(r);let t=(await d({config:r,document:hs,variables:{cwd:r.cwd,projectId:r.projectId}})).project?.devSession?.scopeItems??[];if(e.format==="json"){process.stdout.write(`${JSON.stringify(t,null,2)}
|
|
508
|
-
`);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??""}
|
|
509
|
-
`);return}let s=i.spec==null?"stub":"implemented";process.stdout.write(` [${s}] (${o.id}) ${i.slug} \u2014 ${i.name}
|
|
510
|
-
`)})}async function ws({testIds:e}){let r=b();await R(r),(await ae(r.cwd,r)).match(()=>{},a=>{process.stderr.write(`${S(a)}
|
|
511
|
-
`),process.exit(1)});let o=(await d({config:r,document:vp,variables:{cwd:r.cwd,projectId:r.projectId,workflowSlugs:e.map(a=>cn(a))}})).addDirtyTestsToScope;o?.__typename==="NoActiveDevSessionError"&&(process.stderr.write(`${o.message}
|
|
512
|
-
`),process.exit(1)),o?.__typename==="UnknownWorkflowSlugsError"&&(process.stderr.write(`${ys(o.slugs)}
|
|
513
|
-
`),process.exit(1));let i=o?.__typename==="MutationAddDirtyTestsToScopeSuccess"?o.data:[];if(i.length===0){process.stdout.write(`${gs()}
|
|
514
|
-
`);return}let s=i.map(a=>a.workflow?.slug??"?").join(", ");process.stdout.write(`Added ${M(i.length,"scope item")}: ${s}
|
|
515
|
-
`)}async function bs({id:e,testId:r}){let n=b();await R(n),(await ae(n.cwd,n)).match(()=>{},i=>{process.stderr.write(`${S(i)}
|
|
516
|
-
`),process.exit(1)});let o=await Rp({cfg:n,slug:r});await d({config:n,document:Sp,variables:{id:e,workflowId:o}}),process.stdout.write(`Linked scope item ${e} to ${r}
|
|
517
|
-
`)}async function vs({ids:e}){let r=b();await R(r);let t=(await d({config:r,document:xp,variables:{ids:[...e]}})).removeScopeItems??0;process.stdout.write(`Removed ${M(t,"scope item")}
|
|
518
|
-
`)}async function Rp({cfg:e,slug:r}){let t=(await d({config:e,document:bp,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.
|
|
519
|
-
`),process.stderr.write(`${x("create")}
|
|
520
|
-
`),process.exit(1)),t.id}import{graphql as O}from"gql.tada";import{print as js}from"graphql";import{createClient as Ms}from"graphql-sse";import Lr from"fs";import Cp from"path";import{err as Ze,ok as Ep}from"neverthrow";function xs({cwd:e,rrwebId:r,runId:n}){let t=Cs(e,n);if(!Lr.existsSync(t))return Ze({kind:"no-behavior"});let o=Is(Ps(t,r));if(o==null)return Ze({kind:"not-found"});let i=Nr(o.node.type);return i===3?Ze({kind:"text-node",parentId:Nr(o.parent?.id)}):i!==2?Ze({kind:"non-element",nodeType:i??-1}):Ep({tagName:A(o.node.tagName)})}function Rs({cwd:e,rrwebId:r,runId:n}){let t=Ps(Cs(e,n),r);if(t==null)return null;let o=Is(t);return o==null||Nr(o.node.type)!==2?null:$p(t)}function Cs(e,r){return Cp.join(e,".ripplo","debug",r,"behavior.jsonl")}function $p(e){let r=e.at(-1)??{},n=Fr(r.attributes)??{},t=A(r.tagName);return{ariaName:A(n["aria-label"]),role:A(n.role),selector:Ip(e),tagName:t==null?null:t.toLowerCase(),testId:A(n["data-testid"]),text:Lp(Mp(r))}}var Pp=6;function Ip(e){let r=Es(e,e.length-1,Pp);return r.length===0?null:r.join(" > ")}function Es(e,r,n){let t=e[r];if(t==null||n<=0)return[];let o=Ap(t);if(o!=null)return[o];let i=Tp(t,e[r-1]);return r===0||n===1?[i]:[...Es(e,r-1,n-1),i]}function Ap(e){let r=Fr(e.attributes)??{},n=A(r["data-testid"]);if(n!=null)return`[data-testid="${n}"]`;let t=A(r.id);return t!=null&&t.length>0?`#${t}`:null}function Tp(e,r){let n=(A(e.tagName)??"*").toLowerCase(),t=$s(r).filter(i=>(A(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 $s(e){let r=e?.childNodes;return Array.isArray(r)?r.filter(n=>Xe(n)):[]}function Ps(e,r){return Lr.existsSync(e)?Lr.readFileSync(e,"utf8").split(`
|
|
521
|
-
`).reduce((t,o)=>t!=null||o.length===0?t:jp(o,r),null):null}function jp(e,r){let n=on(e);if(n?.kind!=="rrweb")return null;let t=Fr(n.event.data),o=Or(t?.node,r);if(o!=null)return o;let i=t?.adds;return Array.isArray(i)?i.reduce((s,a)=>s??(Xe(a)?Or(a.node,r):null),null):null}function Or(e,r){if(!Xe(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??Or(i,r),null);return t==null?null:[e,...t]}function Is(e){let r=e?.at(-1);return r==null?null:{node:r,parent:e?.at(-2)}}var Ss=80;function Mp(e){let r=$s(e).filter(n=>n.type===3).map(n=>A(n.textContent)).filter(n=>n!=null);return r.length===0?null:r.join(" ")}function A(e){return typeof e=="string"?e:null}function Lp(e){let r=e==null?"":e.replaceAll(/\s+/g," ").trim();return r.length===0?null:r.length>Ss?`${r.slice(0,Ss)}\u2026`:r}function Fr(e){return Xe(e)?e:void 0}function Xe(e){return typeof e=="object"&&e!=null}function Nr(e){return typeof e=="number"?e:null}function Wr(e,r){let n=r.flatMap(o=>Op(e,o)),t=new Map(r.map(o=>[o.id,o.fingerprint]));return{changes:n,seen:t}}function Op(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 Np=O(`
|
|
522
|
-
query WorkList($projectId: String!, $cwd: String!) {
|
|
523
|
-
project(id: $projectId) {
|
|
524
|
-
id
|
|
525
|
-
devSession(cwd: $cwd) {
|
|
526
|
-
id
|
|
527
|
-
tasks(status: open) {
|
|
528
|
-
id
|
|
529
|
-
kind
|
|
530
|
-
status
|
|
531
|
-
title
|
|
532
|
-
messages {
|
|
533
|
-
body
|
|
534
|
-
}
|
|
535
|
-
}
|
|
536
|
-
}
|
|
537
|
-
}
|
|
538
|
-
}
|
|
539
|
-
`),Fp=O(`
|
|
540
|
-
query WatchSeed($projectId: String!, $cwd: String!) {
|
|
541
|
-
project(id: $projectId) {
|
|
542
|
-
id
|
|
543
|
-
devSession(cwd: $cwd) {
|
|
544
|
-
id
|
|
545
|
-
tasks(status: open) {
|
|
546
|
-
id
|
|
547
|
-
kind
|
|
548
|
-
title
|
|
549
|
-
updatedAt
|
|
550
|
-
lastMessageAuthor
|
|
551
|
-
messages {
|
|
552
|
-
body
|
|
553
|
-
kind
|
|
554
|
-
}
|
|
555
|
-
}
|
|
556
|
-
}
|
|
557
|
-
}
|
|
558
|
-
}
|
|
559
|
-
`),Ls=O(`
|
|
560
|
-
subscription WatchTasks($devSessionId: String!) {
|
|
561
|
-
tasksChanged(devSessionId: $devSessionId) {
|
|
562
|
-
devSession {
|
|
44
|
+
title
|
|
45
|
+
verdict
|
|
46
|
+
prUrl
|
|
47
|
+
publishedAttempt {
|
|
563
48
|
id
|
|
564
|
-
|
|
49
|
+
status
|
|
50
|
+
summaryText
|
|
51
|
+
issues {
|
|
565
52
|
id
|
|
566
53
|
kind
|
|
567
54
|
title
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
|
|
571
|
-
|
|
572
|
-
|
|
55
|
+
body
|
|
56
|
+
workflowSlugs
|
|
57
|
+
evidence {
|
|
58
|
+
runId
|
|
59
|
+
testRef
|
|
60
|
+
frameMs
|
|
61
|
+
rrwebId
|
|
573
62
|
}
|
|
574
63
|
}
|
|
575
64
|
}
|
|
576
65
|
}
|
|
577
66
|
}
|
|
578
|
-
`)
|
|
579
|
-
|
|
580
|
-
|
|
581
|
-
|
|
582
|
-
|
|
583
|
-
|
|
584
|
-
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
|
|
589
|
-
|
|
590
|
-
|
|
591
|
-
|
|
592
|
-
|
|
593
|
-
|
|
594
|
-
}
|
|
595
|
-
`),Dp=O(`
|
|
596
|
-
mutation WorkComment(
|
|
597
|
-
$taskId: String!
|
|
598
|
-
$body: String!
|
|
599
|
-
$runId: String
|
|
600
|
-
$frameMs: Int
|
|
601
|
-
$rrwebId: Int
|
|
602
|
-
$authorName: String
|
|
603
|
-
) {
|
|
604
|
-
agentCommentOnTask(
|
|
605
|
-
taskId: $taskId
|
|
606
|
-
body: $body
|
|
607
|
-
runId: $runId
|
|
608
|
-
frameMs: $frameMs
|
|
609
|
-
rrwebId: $rrwebId
|
|
610
|
-
authorName: $authorName
|
|
611
|
-
) {
|
|
612
|
-
__typename
|
|
613
|
-
... on Task {
|
|
614
|
-
id
|
|
615
|
-
}
|
|
616
|
-
... on NoActiveDevSessionError {
|
|
617
|
-
message
|
|
618
|
-
}
|
|
619
|
-
}
|
|
620
|
-
}
|
|
621
|
-
`),_p=O(`
|
|
622
|
-
mutation WorkResolve($taskId: String!, $runId: String!, $note: String, $authorName: String) {
|
|
623
|
-
agentResolveTask(taskId: $taskId, runId: $runId, note: $note, authorName: $authorName) {
|
|
624
|
-
__typename
|
|
625
|
-
... on Task {
|
|
626
|
-
id
|
|
627
|
-
}
|
|
628
|
-
... on NoActiveDevSessionError {
|
|
629
|
-
message
|
|
630
|
-
}
|
|
631
|
-
}
|
|
632
|
-
}
|
|
633
|
-
`),Up=O(`
|
|
634
|
-
mutation WorkStart($taskId: String!) {
|
|
635
|
-
agentStartTask(taskId: $taskId) {
|
|
636
|
-
__typename
|
|
637
|
-
... on Task {
|
|
638
|
-
id
|
|
639
|
-
agentStartedAt
|
|
640
|
-
}
|
|
641
|
-
... on NoActiveDevSessionError {
|
|
642
|
-
message
|
|
643
|
-
}
|
|
644
|
-
}
|
|
645
|
-
}
|
|
646
|
-
`),Vp=O(`
|
|
647
|
-
mutation WorkClarify($taskId: String!, $body: String!, $authorName: String) {
|
|
648
|
-
agentSetNeedsClarification(taskId: $taskId, body: $body, authorName: $authorName) {
|
|
649
|
-
__typename
|
|
650
|
-
... on Task {
|
|
651
|
-
id
|
|
652
|
-
}
|
|
653
|
-
... on NoActiveDevSessionError {
|
|
654
|
-
message
|
|
655
|
-
}
|
|
656
|
-
}
|
|
657
|
-
}
|
|
658
|
-
`),qp=O(`
|
|
659
|
-
mutation WorkDismiss($taskId: String!, $note: String, $authorName: String) {
|
|
660
|
-
agentDismissTask(taskId: $taskId, note: $note, authorName: $authorName) {
|
|
661
|
-
__typename
|
|
662
|
-
... on Task {
|
|
663
|
-
id
|
|
664
|
-
}
|
|
665
|
-
... on NoActiveDevSessionError {
|
|
666
|
-
message
|
|
667
|
-
}
|
|
668
|
-
... on FindingNotDismissableError {
|
|
669
|
-
message
|
|
670
|
-
}
|
|
671
|
-
}
|
|
672
|
-
}
|
|
673
|
-
`),Bp=18e4;async function Os(e){let r=b();await R(r);let n=await As(r),t=n.items.some(o=>o.kind==="finding");if(e.wait&&!t&&n.devSessionId!=null){await Hp({cfg:r,devSessionId:n.devSessionId});let o=await As(r);Ts(o.items,e.format);return}Ts(n.items,e.format)}async function As(e){let n=(await d({config:e,document:Np,variables:{cwd:e.cwd,projectId:e.projectId}})).project?.devSession;return{devSessionId:n?.id??null,items:n?.tasks??[]}}function Ts(e,r){if(r==="json"){process.stdout.write(`${JSON.stringify(e,null,2)}
|
|
674
|
-
`);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(`${Fn(n)}
|
|
675
|
-
`)}function Hp({cfg:e,devSessionId:r}){let n=Ms({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,Bp),o.dispose=n.subscribe({query:js(Ls),variables:{devSessionId:r}},{complete:i,error:()=>{i()},next:s=>{(s.data?.tasksChanged?.devSession?.tasks??[]).some(l=>l.kind==="finding")&&i()}})})}async function Ns(){let e=b();await R(e);let n=(await d({config:e,document:Fp,variables:{cwd:e.cwd,projectId:e.projectId}})).project?.devSession;if(n==null)throw new Error("dev session vanished between preflight and seed");let t=Wr(new Map,Ws(n.tasks??[])),o=Ms({headers:{Authorization:`Bearer ${e.token}`},retryAttempts:1/0,url:`${e.ripploServerUrl}/graphql`});zp({devSessionId:n.id,seen:t.seen,sseClient:o}),await new Promise(()=>{})}function zp({devSessionId:e,seen:r,sseClient:n}){let t=r;n.subscribe({query:js(Ls),variables:{devSessionId:e}},{complete:()=>{},error:o=>{process.stderr.write(`task watch error: ${String(o)}
|
|
676
|
-
`)},next:o=>{let i=o.data?.tasksChanged?.devSession?.tasks??[],s=Wr(t,Ws(i));s.changes.forEach(a=>{process.stdout.write(`${Dn(a)}
|
|
677
|
-
`)}),t=s.seen}})}async function Fs(e){let r=b();await R(r);let t=(await d({config:r,document:Wp,variables:{id:e.id}})).task;if(t==null&&(process.stderr.write(`${_n(e.id)}
|
|
678
|
-
`),process.exit(1)),e.format==="json"){process.stdout.write(`${JSON.stringify(t,null,2)}
|
|
679
|
-
`);return}let o=[...new Set((t.messages??[]).flatMap(s=>s.runId==null?[]:[s.runId]))];await Promise.all(o.map(s=>_(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:Rs({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(`${Wn(i)}
|
|
680
|
-
`)}function Ws(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 Ds(e){let r=b();if(await R(r),e.elementId!=null&&e.runId!=null){let t=xs({cwd:r.cwd,rrwebId:e.elementId,runId:e.runId}).match(()=>null,o=>o);t!=null&&t.kind!=="no-behavior"&&(process.stderr.write(`${Gp(t,e.elementId,e.runId)}
|
|
681
|
-
`),process.exit(1))}let n=await d({config:r,document:Dp,variables:{authorName:e.authorName??null,body:e.body,frameMs:e.offsetMs??null,rrwebId:e.elementId??null,runId:e.runId??null,taskId:e.id}});Ye(n.agentCommentOnTask),process.stdout.write(`${Un(e.id)}
|
|
682
|
-
`)}async function _s(e){let r=b();await R(r);let n=await d({config:r,document:_p,variables:{authorName:e.authorName??null,note:e.note??null,runId:e.runId,taskId:e.id}});Ye(n.agentResolveTask),process.stdout.write(`${zn(e.id)}
|
|
683
|
-
`)}async function Us(e){let r=b();await R(r);let n=await d({config:r,document:Up,variables:{taskId:e.id}});Ye(n.agentStartTask),process.stdout.write(`${Gn(e.id)}
|
|
684
|
-
`)}async function Vs(e){e.body.trim().length===0&&(process.stderr.write(`${Vn()}
|
|
685
|
-
`),process.exit(1));let r=b();await R(r);let n=await d({config:r,document:Vp,variables:{authorName:e.authorName??null,body:e.body,taskId:e.id}});Ye(n.agentSetNeedsClarification),process.stdout.write(`${Kn(e.id)}
|
|
686
|
-
`)}async function qs(e){let r=b();await R(r);let t=(await d({config:r,document:qp,variables:{authorName:e.authorName??null,note:e.note??null,taskId:e.id}})).agentDismissTask;(t?.__typename==="FindingNotDismissableError"||t?.__typename==="NoActiveDevSessionError")&&(process.stderr.write(`${t.message}
|
|
687
|
-
`),process.exit(1)),process.stdout.write(`${Jn(e.id)}
|
|
688
|
-
`)}function Ye(e){e?.__typename==="NoActiveDevSessionError"&&(process.stderr.write(`${e.message}
|
|
689
|
-
`),process.exit(1))}function Gp(e,r,n){return e.kind==="text-node"?qn(r,e.parentId):e.kind==="not-found"?Bn(r,n):Hn(r)}function Bs(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=>Os({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,()=>Ns()).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=>Fs({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=>Ds({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=>Us({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=>_s({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=>Vs({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=>qs({authorName:r.as,id:r.id,note:r.note})).demandCommand(1)}_r();ie(process.cwd());Zr();async function Zp(){fe(w()),Kp({pkg:{name:"ripplo",version:w()}}).notify({message:Ot()}),await Jp(Qp(process.argv)).scriptName("ripplo").version(w()).command(em()).command(rm()).command(tm()).command(pm()).command("auth <subcommand>","Manage authentication",km).command("projects <subcommand>","List or create Ripplo projects",hm).command("hooks <subcommand>","Pause or resume Ripplo hooks",ym).command(sm()).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=>wo({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`)",fm,e=>Po({all:e.all,headed:e.headed,ids:e.ids})).command(lm()).command(dm()).command(mm()).command(cm()).command(um()).command(am()).command(om()).command(im()).command("sync","Push the compiled .ripplo/ resources to the server (no run)",()=>{},()=>Di()).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=>qt({check:e.check})).command("update","Update ripplo to the latest published version (and hand the daemon off to it)",()=>{},()=>Ji()).command("doctor","Check project health",()=>{},()=>no()).command("status","Report stub tests and daemon status",e=>e.option("format",{choices:["json","summary"],default:"json",describe:"Output format"}),e=>Tt({format:e.format})).command("scope <subcommand>","Manage testing scope",gm).command("tasks <subcommand>","Manage tasks for this dev session",Bs).command("run-worker",!1,()=>{},()=>jo()).command("hook <name>","Internal: run a Claude Code plugin hook",e=>e.positional("name",{choices:Object.keys(it),demandOption:!0,type:"string"}),e=>at(e.name)).strict().help().parse()}Zp().catch(e=>{process.stderr.write(`${st(e)}
|
|
690
|
-
`),process.exit(1)});var Xp=["start","stop","restart","status"],Yp="start";function em(){return{command:"daemon [action]",describe:"Run the long-lived local executor (IPC socket + run subscription)",builder:e=>e.positional("action",{choices:Xp,default:Yp,describe:"Lifecycle action for this project's daemon"}).option("explore-debug",{default:!1,describe:"Print local explorer planner decisions",type:"boolean"}),handler:e=>Qi({action:e.action,exploreDebug:e["explore-debug"]})}}function rm(){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=>es({mode:e.mode})}}var nm=["analyze","on","off"];function tm(){return{command:"explore [state]",describe:"Show or toggle the background explorer for the active dev session",builder:e=>e.positional("state",{choices:nm,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=>fs({json:e.json,state:e.state,trail:e.trail,workers:e.workers})}}function om(){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=>Yo({full:e.full,json:e.json,runId:e.runId})}}function im(){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=>ai({runId:e.runId})}}function sm(){return{command:"setup",describe:"Install the Ripplo plugin for Claude Code and start a guided setup session",builder:e=>e,handler:()=>{$o()}}}function am(){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=>ei({runId:e.runId})}}function lm(){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=>yi({at:e.at,offset:e.offset,runId:e.runId})}}function dm(){return{command:"video <runId>",describe:"Render an MP4 of a run's rrweb recording",builder:e=>e.positional("runId",{demandOption:!0,type:"string"}),handler:e=>Ri({runId:e.runId})}}function cm(){return{command:"capture",describe:"Open your signed-in browser, record a flow, and hand the log to Claude",builder:e=>e,handler:()=>Li()}}function um(){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=>{Wi({runId:e.runId})}}}function pm(){return{command:"concurrency [value]",describe:"Show or set max local concurrent runs (daemon applies live)",builder:e=>e.positional("value",{type:"number"}),handler:e=>Ht({value:e.value})}}function mm(){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=>Pi({ref:e.ref,step:e.step})}}function fm(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 gm(e){return e.command("status","Print the current scope",r=>r.option("format",{choices:["json","text"],default:"text",describe:"Output format"}),r=>ks({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=>ws({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=>bs({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=>vs({ids:r.ids})).demandCommand(1)}function ym(e){return e.command("pause","Disable all Ripplo pre-edit gates and stop enforcement until resumed",()=>{},()=>to()).command("resume","Re-enable Ripplo hooks paused via `ripplo hooks pause`",()=>{},()=>oo()).demandCommand(1)}function hm(e){return e.command("list","List projects you have access to (JSON)",()=>{},()=>So()).command("create <name>","Create a project (JSON)",r=>r.positional("name",{demandOption:!0,type:"string"}).option("org",{describe:"Organization id",type:"string"}),r=>xo({name:r.name,orgId:r.org})).demandCommand(1)}function km(e){return e.command("login","Authenticate via device flow",()=>{},()=>_t()).command("status","Show authentication status",()=>{},()=>Ut()).command("logout","Remove the saved token",()=>{},()=>{Vt()}).demandCommand(1)}export{Zp 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};
|