ripplo 0.5.3 → 0.5.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +51 -49
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,26 +1,26 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
var na=Object.create;var fr=Object.defineProperty;var oa=Object.getOwnPropertyDescriptor;var ia=Object.getOwnPropertyNames;var sa=Object.getPrototypeOf,aa=Object.prototype.hasOwnProperty;var la=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),ca=(e,t)=>{for(var r in t)fr(e,r,{get:t[r],enumerable:!0})},mr=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of ia(t))!aa.call(e,o)&&o!==r&&fr(e,o,{get:()=>t[o],enumerable:!(n=oa(t,o))||n.enumerable});return e},gr=(e,t,r)=>(mr(e,t,"default"),r&&mr(r,t,"default")),yr=(e,t,r)=>(r=e!=null?na(sa(e)):{},mr(t||!e||!e.__esModule?fr(r,"default",{value:e,enumerable:!0}):r,e));var Et=la((
|
|
2
|
+
var na=Object.create;var fr=Object.defineProperty;var oa=Object.getOwnPropertyDescriptor;var ia=Object.getOwnPropertyNames;var sa=Object.getPrototypeOf,aa=Object.prototype.hasOwnProperty;var la=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),ca=(e,t)=>{for(var r in t)fr(e,r,{get:t[r],enumerable:!0})},mr=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of ia(t))!aa.call(e,o)&&o!==r&&fr(e,o,{get:()=>t[o],enumerable:!(n=oa(t,o))||n.enumerable});return e},gr=(e,t,r)=>(mr(e,t,"default"),r&&mr(r,t,"default")),yr=(e,t,r)=>(r=e!=null?na(sa(e)):{},mr(t||!e||!e.__esModule?fr(r,"default",{value:e,enumerable:!0}):r,e));var Et=la((Eb,mo)=>{"use strict";var Rl=(function(){function e(r,n){if(typeof r!="function")throw new TypeError("DataLoader must be constructed with a function which accepts "+("Array<key> and returns Promise<Array<value>>, but got: "+r+"."));this._batchLoadFn=r,this._maxBatchSize=Cl(n),this._batchScheduleFn=Tl(n),this._cacheKeyFn=Al(n),this._cacheMap=Il(n),this._batch=null,this.name=$l(n)}var t=e.prototype;return t.load=function(n){if(n==null)throw new TypeError("The loader.load() function must be called with a value, "+("but got: "+String(n)+"."));var o=xl(this),i=this._cacheMap,s;if(i){s=this._cacheKeyFn(n);var a=i.get(s);if(a){var l=o.cacheHits||(o.cacheHits=[]);return new Promise(function(p){l.push(function(){p(a)})})}}o.keys.push(n);var c=new Promise(function(p,m){o.callbacks.push({resolve:p,reject:m})});return i&&i.set(s,c),c},t.loadMany=function(n){if(!po(n))throw new TypeError("The loader.loadMany() function must be called with Array<key> "+("but got: "+n+"."));for(var o=[],i=0;i<n.length;i++)o.push(this.load(n[i]).catch(function(s){return s}));return Promise.all(o)},t.clear=function(n){var o=this._cacheMap;if(o){var i=this._cacheKeyFn(n);o.delete(i)}return this},t.clearAll=function(){var n=this._cacheMap;return n&&n.clear(),this},t.prime=function(n,o){var i=this._cacheMap;if(i){var s=this._cacheKeyFn(n);if(i.get(s)===void 0){var a;o instanceof Error?(a=Promise.reject(o),a.catch(function(){})):a=Promise.resolve(o),i.set(s,a)}}return this},e})(),Pl=typeof process=="object"&&typeof process.nextTick=="function"?function(e){Nr||(Nr=Promise.resolve()),Nr.then(function(){process.nextTick(e)})}:typeof setImmediate=="function"?function(e){setImmediate(e)}:function(e){setTimeout(e)},Nr;function xl(e){var t=e._batch;if(t!==null&&!t.hasDispatched&&t.keys.length<e._maxBatchSize)return t;var r={hasDispatched:!1,keys:[],callbacks:[]};return e._batch=r,e._batchScheduleFn(function(){El(e,r)}),r}function El(e,t){if(t.hasDispatched=!0,t.keys.length===0){Dr(t);return}var r;try{r=e._batchLoadFn(t.keys)}catch(n){return Or(e,t,new TypeError("DataLoader must be constructed with a function which accepts Array<key> and returns Promise<Array<value>>, but the function "+("errored synchronously: "+String(n)+".")))}if(!r||typeof r.then!="function")return Or(e,t,new TypeError("DataLoader must be constructed with a function which accepts Array<key> and returns Promise<Array<value>>, but the function did "+("not return a Promise: "+String(r)+".")));r.then(function(n){if(!po(n))throw new TypeError("DataLoader must be constructed with a function which accepts Array<key> and returns Promise<Array<value>>, but the function did "+("not return a Promise of an Array: "+String(n)+"."));if(n.length!==t.keys.length)throw new TypeError("DataLoader must be constructed with a function which accepts Array<key> and returns Promise<Array<value>>, but the function did not return a Promise of an Array of the same length as the Array of keys."+(`
|
|
3
3
|
|
|
4
4
|
Keys:
|
|
5
5
|
`+String(t.keys))+(`
|
|
6
6
|
|
|
7
7
|
Values:
|
|
8
|
-
`+String(n)));Dr(t);for(var o=0;o<t.callbacks.length;o++){var i=n[o];i instanceof Error?t.callbacks[o].reject(i):t.callbacks[o].resolve(i)}}).catch(function(n){Or(e,t,n)})}function Or(e,t,r){Dr(t);for(var n=0;n<t.keys.length;n++)e.clear(t.keys[n]),t.callbacks[n].reject(r)}function Dr(e){if(e.cacheHits)for(var t=0;t<e.cacheHits.length;t++)e.cacheHits[t]()}function Cl(e){var t=!e||e.batch!==!1;if(!t)return 1;var r=e&&e.maxBatchSize;if(r===void 0)return 1/0;if(typeof r!="number"||r<1)throw new TypeError("maxBatchSize must be a positive number: "+r);return r}function Tl(e){var t=e&&e.batchScheduleFn;if(t===void 0)return Pl;if(typeof t!="function")throw new TypeError("batchScheduleFn must be a function: "+t);return t}function
|
|
9
|
-
`&&(p(),l="",c=0,r=!1);if(!g.scan(m))break;if(s=!0,x=g.scan($a)||"name",g.scan(Ta),x==="="?(F=g.scanUntil(Un),g.scan(Un),g.scanUntil(h)):x==="{"?(F=g.scanUntil(T),g.scan(
|
|
8
|
+
`+String(n)));Dr(t);for(var o=0;o<t.callbacks.length;o++){var i=n[o];i instanceof Error?t.callbacks[o].reject(i):t.callbacks[o].resolve(i)}}).catch(function(n){Or(e,t,n)})}function Or(e,t,r){Dr(t);for(var n=0;n<t.keys.length;n++)e.clear(t.keys[n]),t.callbacks[n].reject(r)}function Dr(e){if(e.cacheHits)for(var t=0;t<e.cacheHits.length;t++)e.cacheHits[t]()}function Cl(e){var t=!e||e.batch!==!1;if(!t)return 1;var r=e&&e.maxBatchSize;if(r===void 0)return 1/0;if(typeof r!="number"||r<1)throw new TypeError("maxBatchSize must be a positive number: "+r);return r}function Tl(e){var t=e&&e.batchScheduleFn;if(t===void 0)return Pl;if(typeof t!="function")throw new TypeError("batchScheduleFn must be a function: "+t);return t}function Al(e){var t=e&&e.cacheKeyFn;if(t===void 0)return function(r){return r};if(typeof t!="function")throw new TypeError("cacheKeyFn must be a function: "+t);return t}function Il(e){var t=!e||e.cache!==!1;if(!t)return null;var r=e&&e.cacheMap;if(r===void 0)return new Map;if(r!==null){var n=["get","set","delete","clear"],o=n.filter(function(i){return r&&typeof r[i]!="function"});if(o.length!==0)throw new TypeError("Custom cacheMap missing methods: "+o.join(", "))}return r}function $l(e){return e&&e.name?e.name:null}function po(e){return typeof e=="object"&&e!==null&&typeof e.length=="number"&&(e.length===0||e.length>0&&Object.prototype.hasOwnProperty.call(e,e.length-1))}mo.exports=Rl});import{execFileSync as ua}from"child_process";import da from"fs";import vt from"path";function hr(e){let t=ma(e);return t??Dn(e)}function Dn(e){let t=vt.dirname(e);return pa(vt.join(e,".ripplo"))?e:t===e?null:Dn(t)}function pa(e){try{return da.statSync(e).isDirectory()}catch{return!1}}function ma(e){let t=fa(["rev-parse","--show-toplevel"],e);if(t==null)return null;let r=t.trim();return r.length===0?null:vt.isAbsolute(r)?r:vt.resolve(e,r)}function fa(e,t){try{return ua("git",e,{cwd:t,encoding:"utf8",stdio:["ignore","pipe","ignore"]})}catch{return null}}import _a from"path";import{AsyncLocalStorage as ga}from"async_hooks";import ya from"path";var ha=new ga;function Ln(){let e=ha.getStore();return e!=null?e.fixturesDir:ya.join(process.cwd(),".ripplo","fixtures")}async function ye(e,t,r){let n,o=new Promise((i,s)=>{n=setTimeout(()=>{s(new Error(`${r} timed out after ${String(t)}ms`))},t)});try{return await Promise.race([e,o])}finally{n!=null&&clearTimeout(n)}}var wa=5e3;async function St({fn:e,label:t,page:r,timeoutMs:n}){let o=n??wa,i=await ye(r.context().newCDPSession(r),o,`${t} (newCDPSession)`);try{return await ye(e(i),o,t)}finally{await i.detach().catch(()=>{})}}async function J({awaitPromise:e,expression:t,label:r,page:n,timeoutMs:o}){return St({label:r??"evaluateViaCdp",page:n,timeoutMs:o,fn:async i=>{let s=await i.send("Runtime.evaluate",{awaitPromise:e,expression:t,returnByValue:!0});if(s.exceptionDetails==null)return s.result.value}})}var ba=Object.prototype.toString,Oe=Array.isArray||function(t){return ba.call(t)==="[object Array]"};function br(e){return typeof e=="function"}function va(e){return Oe(e)?"array":typeof e}function wr(e){return e.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g,"\\$&")}function _n(e,t){return e!=null&&typeof e=="object"&&t in e}function Sa(e,t){return e!=null&&typeof e!="object"&&e.hasOwnProperty&&e.hasOwnProperty(t)}var ka=RegExp.prototype.test;function Ra(e,t){return ka.call(e,t)}var Pa=/\S/;function xa(e){return!Ra(Pa,e)}var Ea={"&":"&","<":"<",">":">",'"':""","'":"'","/":"/","`":"`","=":"="};function Ca(e){return String(e).replace(/[&<>"'`=\/]/g,function(r){return Ea[r]})}var Ta=/\s*/,Aa=/\s+/,Un=/\s*=/,Ia=/\s*\}/,$a=/#|\^|\/|>|\{|&|=|!/;function ja(e,t){if(!e)return[];var r=!1,n=[],o=[],i=[],s=!1,a=!1,l="",c=0;function p(){if(s&&!a)for(;i.length;)delete o[i.pop()];else i=[];s=!1,a=!1}var m,h,T;function $(L){if(typeof L=="string"&&(L=L.split(Aa,2)),!Oe(L)||L.length!==2)throw new Error("Invalid tags: "+L);m=new RegExp(wr(L[0])+"\\s*"),h=new RegExp("\\s*"+wr(L[1])),T=new RegExp("\\s*"+wr("}"+L[1]))}$(t||te.tags);for(var g=new rt(e),H,x,F,Ae,j,W;!g.eos();){if(H=g.pos,F=g.scanUntil(m),F)for(var ge=0,pr=F.length;ge<pr;++ge)Ae=F.charAt(ge),xa(Ae)?(i.push(o.length),l+=Ae):(a=!0,r=!0,l+=" "),o.push(["text",Ae,H,H+1]),H+=1,Ae===`
|
|
9
|
+
`&&(p(),l="",c=0,r=!1);if(!g.scan(m))break;if(s=!0,x=g.scan($a)||"name",g.scan(Ta),x==="="?(F=g.scanUntil(Un),g.scan(Un),g.scanUntil(h)):x==="{"?(F=g.scanUntil(T),g.scan(Ia),g.scanUntil(h),x="&"):F=g.scanUntil(h),!g.scan(h))throw new Error("Unclosed tag at "+g.pos);if(x==">"?j=[x,F,H,g.pos,l,c,r]:j=[x,F,H,g.pos],c++,o.push(j),x==="#"||x==="^")n.push(j);else if(x==="/"){if(W=n.pop(),!W)throw new Error('Unopened section "'+F+'" at '+H);if(W[1]!==F)throw new Error('Unclosed section "'+W[1]+'" at '+H)}else x==="name"||x==="{"||x==="&"?a=!0:x==="="&&$(F)}if(p(),W=n.pop(),W)throw new Error('Unclosed section "'+W[1]+'" at '+g.pos);return Oa(Na(o))}function Na(e){for(var t=[],r,n,o=0,i=e.length;o<i;++o)r=e[o],r&&(r[0]==="text"&&n&&n[0]==="text"?(n[1]+=r[1],n[3]=r[3]):(t.push(r),n=r));return t}function Oa(e){for(var t=[],r=t,n=[],o,i,s=0,a=e.length;s<a;++s)switch(o=e[s],o[0]){case"#":case"^":r.push(o),n.push(o),r=o[4]=[];break;case"/":i=n.pop(),i[5]=o[2],r=n.length>0?n[n.length-1][4]:t;break;default:r.push(o)}return t}function rt(e){this.string=e,this.tail=e,this.pos=0}rt.prototype.eos=function(){return this.tail===""};rt.prototype.scan=function(t){var r=this.tail.match(t);if(!r||r.index!==0)return"";var n=r[0];return this.tail=this.tail.substring(n.length),this.pos+=n.length,n};rt.prototype.scanUntil=function(t){var r=this.tail.search(t),n;switch(r){case-1:n=this.tail,this.tail="";break;case 0:n="";break;default:n=this.tail.substring(0,r),this.tail=this.tail.substring(r)}return this.pos+=n.length,n};function Ne(e,t){this.view=e,this.cache={".":this.view},this.parent=t}Ne.prototype.push=function(t){return new Ne(t,this)};Ne.prototype.lookup=function(t){var r=this.cache,n;if(r.hasOwnProperty(t))n=r[t];else{for(var o=this,i,s,a,l=!1;o;){if(t.indexOf(".")>0)for(i=o.view,s=t.split("."),a=0;i!=null&&a<s.length;)a===s.length-1&&(l=_n(i,s[a])||Sa(i,s[a])),i=i[s[a++]];else i=o.view[t],l=_n(o.view,t);if(l){n=i;break}o=o.parent}r[t]=n}return br(n)&&(n=n.call(this.view)),n};function G(){this.templateCache={_cache:{},set:function(t,r){this._cache[t]=r},get:function(t){return this._cache[t]},clear:function(){this._cache={}}}}G.prototype.clearCache=function(){typeof this.templateCache<"u"&&this.templateCache.clear()};G.prototype.parse=function(t,r){var n=this.templateCache,o=t+":"+(r||te.tags).join(":"),i=typeof n<"u",s=i?n.get(o):void 0;return s==null&&(s=ja(t,r),i&&n.set(o,s)),s};G.prototype.render=function(t,r,n,o){var i=this.getConfigTags(o),s=this.parse(t,i),a=r instanceof Ne?r:new Ne(r,void 0);return this.renderTokens(s,a,n,t,o)};G.prototype.renderTokens=function(t,r,n,o,i){for(var s="",a,l,c,p=0,m=t.length;p<m;++p)c=void 0,a=t[p],l=a[0],l==="#"?c=this.renderSection(a,r,n,o,i):l==="^"?c=this.renderInverted(a,r,n,o,i):l===">"?c=this.renderPartial(a,r,n,i):l==="&"?c=this.unescapedValue(a,r):l==="name"?c=this.escapedValue(a,r,i):l==="text"&&(c=this.rawValue(a)),c!==void 0&&(s+=c);return s};G.prototype.renderSection=function(t,r,n,o,i){var s=this,a="",l=r.lookup(t[1]);function c(h){return s.render(h,r,n,i)}if(l){if(Oe(l))for(var p=0,m=l.length;p<m;++p)a+=this.renderTokens(t[4],r.push(l[p]),n,o,i);else if(typeof l=="object"||typeof l=="string"||typeof l=="number")a+=this.renderTokens(t[4],r.push(l),n,o,i);else if(br(l)){if(typeof o!="string")throw new Error("Cannot use higher-order sections without the original template");l=l.call(r.view,o.slice(t[3],t[5]),c),l!=null&&(a+=l)}else a+=this.renderTokens(t[4],r,n,o,i);return a}};G.prototype.renderInverted=function(t,r,n,o,i){var s=r.lookup(t[1]);if(!s||Oe(s)&&s.length===0)return this.renderTokens(t[4],r,n,o,i)};G.prototype.indentPartial=function(t,r,n){for(var o=r.replace(/[^ \t]/g,""),i=t.split(`
|
|
10
10
|
`),s=0;s<i.length;s++)i[s].length&&(s>0||!n)&&(i[s]=o+i[s]);return i.join(`
|
|
11
|
-
`)};G.prototype.renderPartial=function(t,r,n,o){if(n){var i=this.getConfigTags(o),s=br(n)?n(t[1]):n[t[1]];if(s!=null){var a=t[6],l=t[5],c=t[4],p=s;l==0&&c&&(p=this.indentPartial(s,c,a));var m=this.parse(p,i);return this.renderTokens(m,r,n,p,o)}}};G.prototype.unescapedValue=function(t,r){var n=r.lookup(t[1]);if(n!=null)return n};G.prototype.escapedValue=function(t,r,n){var o=this.getConfigEscape(n)||te.escape,i=r.lookup(t[1]);if(i!=null)return typeof i=="number"&&o===te.escape?String(i):o(i)};G.prototype.rawValue=function(t){return t[1]};G.prototype.getConfigTags=function(t){return Oe(t)?t:t&&typeof t=="object"?t.tags:void 0};G.prototype.getConfigEscape=function(t){if(t&&typeof t=="object"&&!Oe(t))return t.escape};var te={name:"mustache.js",version:"4.2.0",tags:["{{","}}"],clearCache:void 0,escape:void 0,parse:void 0,render:void 0,Scanner:void 0,Context:void 0,Writer:void 0,set templateCache(e){tt.templateCache=e},get templateCache(){return tt.templateCache}},tt=new G;te.clearCache=function(){return tt.clearCache()};te.parse=function(t,r){return tt.parse(t,r)};te.render=function(t,r,n,o){if(typeof t!="string")throw new TypeError('Invalid template! Template should be a "string" but "'+va(t)+'" was given as the first argument for mustache#render(template, view, partials)');return tt.render(t,r,n,o)};te.escape=Ca;te.Scanner=rt;te.Context=Ne;te.Writer=G;var Vn=te;function vr({defs:e}){return e==null?{}:Object.fromEntries(Object.entries(e).map(([t,r])=>[t,La({def:r,name:t})]))}var Da={boolean:!1,number:0,string:""};function La({def:e,name:t}){if(e.type==="env"){let r=process.env[e.key];if(r==null)throw new Error(`Environment variable "${e.key}" not set for variable "${t}"`);return r}return e.default??Da[e.type]??""}function kt({ref:e,variables:t}){if(e.type==="static")return e.value;let r=t[e.name];if(r==null||typeof r=="object")throw new Error(`Variable "${e.name}" is not defined`);return r}function Y({ref:e,variables:t}){let r=String(kt({ref:e,variables:t}));return Pt({raw:r,variables:t})}function Rt({ref:e,variables:t}){let r=kt({ref:e,variables:t});return typeof r=="string"?Pt({raw:r,variables:t}):r}function Pt({raw:e,variables:t}){return Vn.render(e,t,{},{escape:r=>r})}function Sr({ref:e,variables:t}){let r=kt({ref:e,variables:t});if(typeof r=="number")return r;let n=Number(r);if(Number.isNaN(n))throw new TypeError(`Cannot convert "${String(r)}" to number`);return n}function De({name:e,store:t,value:r}){return{...t,[e]:r}}function U({locator:e,page:t,variables:r}){switch(e.by){case"testId":return t.getByTestId(Fn(e.value,r));case"role":return t.getByRole(e.role,{exact:!0,name:e.name==null?void 0:Fn(e.name,r)})}}function Fn(e,t){return t==null?e:Pt({raw:e,variables:t})}async function Mn({node:e,page:t,timeout:r}){await U({locator:e.source,page:t,variables:void 0}).dragTo(U({locator:e.target,page:t,variables:void 0}),{timeout:r})}async function Bn({node:e,page:t,timeout:r}){await U({locator:e.locator,page:t,variables:void 0}).click({button:"right",timeout:r})}function Hn({node:e,page:t,variables:r}){return t.once("dialog",async n=>{e.action==="accept"?await n.accept(e.promptText??void 0):await n.dismiss()}),{variables:r}}async function Wn({node:e,page:t,variables:r}){if(e.action==="write"){if(e.value==null)throw new Error("clipboard write requires a value");let o=Y({ref:e.value,variables:r}),i=JSON.stringify(o);return await J({awaitPromise:!0,expression:`navigator.clipboard.writeText(${i})`,label:"clipboard.writeText",page:t,timeoutMs:void 0}),{variables:r}}if(e.variable==null)throw new Error("clipboard read requires a variable name to store the result");let n=await J({awaitPromise:!0,expression:"navigator.clipboard.readText()",label:"clipboard.readText",page:t,timeoutMs:void 0})??"";return{variables:De({name:e.variable,store:r,value:n})}}async function qn({node:e,page:t}){let r=t.context();e.state==="granted"?await r.grantPermissions([e.permission]):await r.clearPermissions()}async function kr({node:e,page:t,timeout:r,variables:n}){switch(e.type){case"click":return await U({locator:e.locator,page:t,variables:n}).click({modifiers:e.modifier==null?void 0:[e.modifier],timeout:r}),{variables:n};case"check":case"uncheck":case"clear":case"dblclick":case"focus":case"hover":case"scrollIntoView":return Va({node:e,page:t,timeout:r,variables:n});case"rightClick":return await Bn({node:e,page:t,timeout:r}),{variables:n};case"goto":{let o=Y({ref:e.url,variables:n});return await t.goto(o,{timeout:r,waitUntil:"domcontentloaded"}),await t.waitForLoadState("load",{timeout:r}),await t.waitForFunction("document.body != null && document.body.childElementCount > 0 && (document.body.textContent?.trim().length ?? 0) > 0",void 0,{timeout:r}),await J({awaitPromise:!0,expression:"new Promise((resolve) => { requestAnimationFrame(() => requestAnimationFrame(() => resolve(undefined))); })",label:"goto raf-settle",page:t,timeoutMs:void 0}),{variables:n}}case"fill":return Ma({node:e,page:t,timeout:r,variables:n});case"select":return Ba({node:e,page:t,timeout:r,variables:n});case"type":return Ha({node:e,page:t,timeout:r,variables:n});case"press":return await Fa({node:e,page:t,timeout:r}),{variables:n};case"drag":return await Mn({node:e,page:t,timeout:r}),{variables:n};case"upload":return Wa({node:e,page:t,timeout:r,variables:n});case"extractText":return za({node:e,page:t,timeout:r,variables:n});case"setVariable":{let o=Rt({ref:e.value,variables:n});return{variables:De({name:e.variable,store:n,value:o})}}case"fail":throw new Error(e.message);case"setViewport":return await t.setViewportSize({height:e.height,width:e.width}),{variables:n};case"handleDialog":return Hn({node:e,page:t,variables:n});case"clipboard":return Wn({node:e,page:t,variables:n});case"setPermission":return await qn({node:e,page:t}),{variables:n}}}var Ua={check:"check",clear:"clear",click:"click",dblclick:"dblclick",focus:"focus",hover:"hover",scrollIntoView:"scrollIntoViewIfNeeded",uncheck:"uncheck"};async function Va({node:e,page:t,timeout:r,variables:n}){return await U({locator:e.locator,page:t,variables:n})[Ua[e.type]]({timeout:r}),{variables:n}}async function Fa({node:e,page:t,timeout:r}){e.locator==null?await t.keyboard.press(e.key):await U({locator:e.locator,page:t,variables:void 0}).press(e.key,{timeout:r})}async function Ma({node:e,page:t,timeout:r,variables:n}){let o=Y({ref:e.value,variables:n});return await U({locator:e.locator,page:t,variables:n}).fill(o,{timeout:r}),{variables:n}}async function Ba({node:e,page:t,timeout:r,variables:n}){let o=Y({ref:e.value,variables:n});return await U({locator:e.locator,page:t,variables:n}).selectOption(o,{timeout:r}),{variables:n}}async function Ha({node:e,page:t,timeout:r,variables:n}){let o=Y({ref:e.value,variables:n});return await U({locator:e.locator,page:t,variables:n}).pressSequentially(o,{timeout:r}),{variables:n}}async function Wa({node:e,page:t,timeout:r,variables:n}){let o=e.files.map(i=>qa(i));return await U({locator:e.locator,page:t,variables:n}).setInputFiles(o,{timeout:r}),{variables:n}}function qa(e){return _a.join(Ln(),e)}async function za({node:e,page:t,timeout:r,variables:n}){let o=await U({locator:e.locator,page:t,variables:n}).textContent({timeout:r});if(o==null)throw new Error("extractText: element had no text content");return{variables:De({name:e.variable,store:n,value:o})}}var q={};ca(q,{default:()=>Ga});gr(q,zw);import*as zw from"playwright/test";import{default as Ga}from"playwright/test";async function Rr({expected:e,locator:t,operator:r,timeout:n}){return await nt({expected:e,operator:r,timeout:n,read:async()=>await t.textContent()??""}),ot({expected:e,label:"Text",operator:r,read:async()=>await t.textContent()??""})}async function Pr({expected:e,operator:t,page:r,timeout:n}){return await nt({expected:e,operator:t,timeout:n,read:()=>Promise.resolve(r.url())}),ot({expected:e,label:"URL",operator:t,read:()=>Promise.resolve(r.url())})}async function zn({expected:e,operator:t,page:r,timeout:n}){return await nt({expected:e,operator:t,timeout:n,read:()=>r.title()}),ot({expected:e,label:"Title",operator:t,read:()=>r.title()})}async function xr({expected:e,locator:t,operator:r,timeout:n}){await q.expect.poll(async()=>no({actual:await t.count(),expected:e,operator:r}),{timeout:n}).toBe(!0).catch(()=>{});let o=await t.count();return ro({actual:o,expected:e,label:"Count",operator:r})}async function Er({expected:e,locator:t,operator:r,timeout:n}){return await nt({expected:e,operator:r,timeout:n,read:()=>t.inputValue()}),ot({expected:e,label:"Value",operator:r,read:()=>t.inputValue()})}async function Cr({locator:e,timeout:t}){return he({description:"Element is visible",failureDetail:"Element not visible",run:()=>(0,q.expect)(e).toBeVisible({timeout:t})})}async function Tr({locator:e,timeout:t}){return he({description:"Element is not visible",failureDetail:"Element still visible",run:()=>(0,q.expect)(e).toBeHidden({timeout:t})})}async function Gn({attribute:e,expected:t,locator:r,operator:n,timeout:o}){return await nt({expected:t,operator:n,timeout:o,read:async()=>await r.getAttribute(e)??""}),ot({expected:t,label:`Attribute "${e}"`,operator:n,read:async()=>await r.getAttribute(e)??""})}async function Kn({locator:e,timeout:t}){return he({description:"Element is enabled",failureDetail:"Element is disabled or not found",run:()=>(0,q.expect)(e).toBeEnabled({timeout:t})})}async function Jn({locator:e,timeout:t}){return he({description:"Element is disabled",failureDetail:"Element is enabled or not found",run:()=>(0,q.expect)(e).toBeDisabled({timeout:t})})}async function Yn({locator:e,timeout:t}){return he({description:"Element is checked",failureDetail:"Element is not checked",run:()=>(0,q.expect)(e).toBeChecked({timeout:t})})}async function Xn({locator:e,timeout:t}){return he({description:"Element is not checked",failureDetail:"Element is checked",run:()=>(0,q.expect)(e).not.toBeChecked({timeout:t})})}async function Qn({locator:e,timeout:t}){return he({description:"Element is focused",failureDetail:"Element is not focused",run:()=>(0,q.expect)(e).toBeFocused({timeout:t})})}async function Zn({locator:e,timeout:t}){return he({description:"Element is not focused",failureDetail:"Element is focused",run:()=>(0,q.expect)(e).not.toBeFocused({timeout:t})})}async function he({description:e,failureDetail:t,run:r}){try{return await r(),{description:e,detail:void 0,status:"passed"}}catch{return{description:e,detail:t,status:"failed"}}}async function nt({expected:e,operator:t,read:r,timeout:n}){await q.expect.poll(async()=>{let o=await r().catch(()=>"");return to({actual:o,expected:e,operator:t})},{timeout:n}).toBe(!0).catch(()=>{})}async function ot({expected:e,label:t,operator:r,read:n}){try{let o=await n();return eo({actual:o,expected:e,label:t,operator:r})}catch(o){let i=`${t} ${r} "${e}"`,s=o instanceof Error?o.message:String(o);return{description:i,detail:`Read failed: ${Ka(s)}`,status:"failed"}}}function Ka(e){let t=e.indexOf(`
|
|
12
|
-
`);return t===-1?e:e.slice(0,t)}function eo(e){let t=`${e.label} ${e.operator} "${e.expected}"`,r=to(e),n=r?void 0:`Got: "${e.actual}"`;return{description:t,detail:n,status:r?"passed":"failed"}}function to({actual:e,expected:t,operator:r}){return r==="equals"?e===t:r==="notEquals"?e!==t:r==="contains"?e.includes(t):r==="startsWith"?e.startsWith(t):r==="endsWith"?e.endsWith(t):new RegExp(t).test(e)}function ro(e){let t=`${e.label} ${e.operator} ${String(e.expected)}`,r=no(e),n=r?void 0:`Got: ${String(e.actual)}`;return{description:t,detail:n,status:r?"passed":"failed"}}function no({actual:e,expected:t,operator:r}){return r==="equals"?e===t:r==="notEquals"?e!==t:r==="greaterThan"?e>t:r==="greaterThanOrEqual"?e>=t:r==="lessThan"?e<t:e<=t}import{execFile as Ya}from"child_process";import{createRequire as Xa}from"module";import oo from"fs";import io from"path";import{chromium as so}from"playwright";import
|
|
11
|
+
`)};G.prototype.renderPartial=function(t,r,n,o){if(n){var i=this.getConfigTags(o),s=br(n)?n(t[1]):n[t[1]];if(s!=null){var a=t[6],l=t[5],c=t[4],p=s;l==0&&c&&(p=this.indentPartial(s,c,a));var m=this.parse(p,i);return this.renderTokens(m,r,n,p,o)}}};G.prototype.unescapedValue=function(t,r){var n=r.lookup(t[1]);if(n!=null)return n};G.prototype.escapedValue=function(t,r,n){var o=this.getConfigEscape(n)||te.escape,i=r.lookup(t[1]);if(i!=null)return typeof i=="number"&&o===te.escape?String(i):o(i)};G.prototype.rawValue=function(t){return t[1]};G.prototype.getConfigTags=function(t){return Oe(t)?t:t&&typeof t=="object"?t.tags:void 0};G.prototype.getConfigEscape=function(t){if(t&&typeof t=="object"&&!Oe(t))return t.escape};var te={name:"mustache.js",version:"4.2.0",tags:["{{","}}"],clearCache:void 0,escape:void 0,parse:void 0,render:void 0,Scanner:void 0,Context:void 0,Writer:void 0,set templateCache(e){tt.templateCache=e},get templateCache(){return tt.templateCache}},tt=new G;te.clearCache=function(){return tt.clearCache()};te.parse=function(t,r){return tt.parse(t,r)};te.render=function(t,r,n,o){if(typeof t!="string")throw new TypeError('Invalid template! Template should be a "string" but "'+va(t)+'" was given as the first argument for mustache#render(template, view, partials)');return tt.render(t,r,n,o)};te.escape=Ca;te.Scanner=rt;te.Context=Ne;te.Writer=G;var Vn=te;function vr({defs:e}){return e==null?{}:Object.fromEntries(Object.entries(e).map(([t,r])=>[t,La({def:r,name:t})]))}var Da={boolean:!1,number:0,string:""};function La({def:e,name:t}){if(e.type==="env"){let r=process.env[e.key];if(r==null)throw new Error(`Environment variable "${e.key}" not set for variable "${t}"`);return r}return e.default??Da[e.type]??""}function kt({ref:e,variables:t}){if(e.type==="static")return e.value;let r=t[e.name];if(r==null||typeof r=="object")throw new Error(`Variable "${e.name}" is not defined`);return r}function Y({ref:e,variables:t}){let r=String(kt({ref:e,variables:t}));return Pt({raw:r,variables:t})}function Rt({ref:e,variables:t}){let r=kt({ref:e,variables:t});return typeof r=="string"?Pt({raw:r,variables:t}):r}function Pt({raw:e,variables:t}){return Vn.render(e,t,{},{escape:r=>r})}function Sr({ref:e,variables:t}){let r=kt({ref:e,variables:t});if(typeof r=="number")return r;let n=Number(r);if(Number.isNaN(n))throw new TypeError(`Cannot convert "${String(r)}" to number`);return n}function De({name:e,store:t,value:r}){return{...t,[e]:r}}function U({locator:e,page:t,variables:r}){switch(e.by){case"testId":return t.getByTestId(Fn(e.value,r));case"role":return t.getByRole(e.role,{exact:!0,name:e.name==null?void 0:Fn(e.name,r)})}}function Fn(e,t){return t==null?e:Pt({raw:e,variables:t})}async function Mn({node:e,page:t,timeout:r}){await U({locator:e.source,page:t,variables:void 0}).dragTo(U({locator:e.target,page:t,variables:void 0}),{timeout:r})}async function Bn({node:e,page:t,timeout:r}){await U({locator:e.locator,page:t,variables:void 0}).click({button:"right",timeout:r})}function Hn({node:e,page:t,variables:r}){return t.once("dialog",async n=>{e.action==="accept"?await n.accept(e.promptText??void 0):await n.dismiss()}),{variables:r}}async function Wn({node:e,page:t,variables:r}){if(e.action==="write"){if(e.value==null)throw new Error("clipboard write requires a value");let o=Y({ref:e.value,variables:r}),i=JSON.stringify(o);return await J({awaitPromise:!0,expression:`navigator.clipboard.writeText(${i})`,label:"clipboard.writeText",page:t,timeoutMs:void 0}),{variables:r}}if(e.variable==null)throw new Error("clipboard read requires a variable name to store the result");let n=await J({awaitPromise:!0,expression:"navigator.clipboard.readText()",label:"clipboard.readText",page:t,timeoutMs:void 0})??"";return{variables:De({name:e.variable,store:r,value:n})}}async function qn({node:e,page:t}){let r=t.context();e.state==="granted"?await r.grantPermissions([e.permission]):await r.clearPermissions()}async function kr({node:e,page:t,timeout:r,variables:n}){switch(e.type){case"click":return await U({locator:e.locator,page:t,variables:n}).click({modifiers:e.modifier==null?void 0:[e.modifier],timeout:r}),{variables:n};case"check":case"uncheck":case"clear":case"dblclick":case"focus":case"hover":case"scrollIntoView":return Va({node:e,page:t,timeout:r,variables:n});case"rightClick":return await Bn({node:e,page:t,timeout:r}),{variables:n};case"goto":{let o=Y({ref:e.url,variables:n});return await t.goto(o,{timeout:r,waitUntil:"domcontentloaded"}),await t.waitForLoadState("load",{timeout:r}),await t.waitForFunction("document.body != null && document.body.childElementCount > 0 && (document.body.textContent?.trim().length ?? 0) > 0",void 0,{timeout:r}),await J({awaitPromise:!0,expression:"new Promise((resolve) => { requestAnimationFrame(() => requestAnimationFrame(() => resolve(undefined))); })",label:"goto raf-settle",page:t,timeoutMs:void 0}),{variables:n}}case"fill":return Ma({node:e,page:t,timeout:r,variables:n});case"select":return Ba({node:e,page:t,timeout:r,variables:n});case"type":return Ha({node:e,page:t,timeout:r,variables:n});case"press":return await Fa({node:e,page:t,timeout:r}),{variables:n};case"drag":return await Mn({node:e,page:t,timeout:r}),{variables:n};case"upload":return Wa({node:e,page:t,timeout:r,variables:n});case"extractText":return za({node:e,page:t,timeout:r,variables:n});case"setVariable":{let o=Rt({ref:e.value,variables:n});return{variables:De({name:e.variable,store:n,value:o})}}case"fail":throw new Error(e.message);case"setViewport":return await t.setViewportSize({height:e.height,width:e.width}),{variables:n};case"handleDialog":return Hn({node:e,page:t,variables:n});case"clipboard":return Wn({node:e,page:t,variables:n});case"setPermission":return await qn({node:e,page:t}),{variables:n}}}var Ua={check:"check",clear:"clear",click:"click",dblclick:"dblclick",focus:"focus",hover:"hover",scrollIntoView:"scrollIntoViewIfNeeded",uncheck:"uncheck"};async function Va({node:e,page:t,timeout:r,variables:n}){return await U({locator:e.locator,page:t,variables:n})[Ua[e.type]]({timeout:r}),{variables:n}}async function Fa({node:e,page:t,timeout:r}){e.locator==null?await t.keyboard.press(e.key):await U({locator:e.locator,page:t,variables:void 0}).press(e.key,{timeout:r})}async function Ma({node:e,page:t,timeout:r,variables:n}){let o=Y({ref:e.value,variables:n});return await U({locator:e.locator,page:t,variables:n}).fill(o,{timeout:r}),{variables:n}}async function Ba({node:e,page:t,timeout:r,variables:n}){let o=Y({ref:e.value,variables:n});return await U({locator:e.locator,page:t,variables:n}).selectOption(o,{timeout:r}),{variables:n}}async function Ha({node:e,page:t,timeout:r,variables:n}){let o=Y({ref:e.value,variables:n});return await U({locator:e.locator,page:t,variables:n}).pressSequentially(o,{timeout:r}),{variables:n}}async function Wa({node:e,page:t,timeout:r,variables:n}){let o=e.files.map(i=>qa(i));return await U({locator:e.locator,page:t,variables:n}).setInputFiles(o,{timeout:r}),{variables:n}}function qa(e){return _a.join(Ln(),e)}async function za({node:e,page:t,timeout:r,variables:n}){let o=await U({locator:e.locator,page:t,variables:n}).textContent({timeout:r});if(o==null)throw new Error("extractText: element had no text content");return{variables:De({name:e.variable,store:n,value:o})}}var q={};ca(q,{default:()=>Ga});gr(q,Kw);import*as Kw from"playwright/test";import{default as Ga}from"playwright/test";async function Rr({expected:e,locator:t,operator:r,timeout:n}){return await nt({expected:e,operator:r,timeout:n,read:async()=>await t.textContent()??""}),ot({expected:e,label:"Text",operator:r,read:async()=>await t.textContent()??""})}async function Pr({expected:e,operator:t,page:r,timeout:n}){return await nt({expected:e,operator:t,timeout:n,read:()=>Promise.resolve(r.url())}),ot({expected:e,label:"URL",operator:t,read:()=>Promise.resolve(r.url())})}async function zn({expected:e,operator:t,page:r,timeout:n}){return await nt({expected:e,operator:t,timeout:n,read:()=>r.title()}),ot({expected:e,label:"Title",operator:t,read:()=>r.title()})}async function xr({expected:e,locator:t,operator:r,timeout:n}){await q.expect.poll(async()=>no({actual:await t.count(),expected:e,operator:r}),{timeout:n}).toBe(!0).catch(()=>{});let o=await t.count();return ro({actual:o,expected:e,label:"Count",operator:r})}async function Er({expected:e,locator:t,operator:r,timeout:n}){return await nt({expected:e,operator:r,timeout:n,read:()=>t.inputValue()}),ot({expected:e,label:"Value",operator:r,read:()=>t.inputValue()})}async function Cr({locator:e,timeout:t}){return he({description:"Element is visible",failureDetail:"Element not visible",run:()=>(0,q.expect)(e).toBeVisible({timeout:t})})}async function Tr({locator:e,timeout:t}){return he({description:"Element is not visible",failureDetail:"Element still visible",run:()=>(0,q.expect)(e).toBeHidden({timeout:t})})}async function Gn({attribute:e,expected:t,locator:r,operator:n,timeout:o}){return await nt({expected:t,operator:n,timeout:o,read:async()=>await r.getAttribute(e)??""}),ot({expected:t,label:`Attribute "${e}"`,operator:n,read:async()=>await r.getAttribute(e)??""})}async function Kn({locator:e,timeout:t}){return he({description:"Element is enabled",failureDetail:"Element is disabled or not found",run:()=>(0,q.expect)(e).toBeEnabled({timeout:t})})}async function Jn({locator:e,timeout:t}){return he({description:"Element is disabled",failureDetail:"Element is enabled or not found",run:()=>(0,q.expect)(e).toBeDisabled({timeout:t})})}async function Yn({locator:e,timeout:t}){return he({description:"Element is checked",failureDetail:"Element is not checked",run:()=>(0,q.expect)(e).toBeChecked({timeout:t})})}async function Xn({locator:e,timeout:t}){return he({description:"Element is not checked",failureDetail:"Element is checked",run:()=>(0,q.expect)(e).not.toBeChecked({timeout:t})})}async function Qn({locator:e,timeout:t}){return he({description:"Element is focused",failureDetail:"Element is not focused",run:()=>(0,q.expect)(e).toBeFocused({timeout:t})})}async function Zn({locator:e,timeout:t}){return he({description:"Element is not focused",failureDetail:"Element is focused",run:()=>(0,q.expect)(e).not.toBeFocused({timeout:t})})}async function he({description:e,failureDetail:t,run:r}){try{return await r(),{description:e,detail:void 0,status:"passed"}}catch{return{description:e,detail:t,status:"failed"}}}async function nt({expected:e,operator:t,read:r,timeout:n}){await q.expect.poll(async()=>{let o=await r().catch(()=>"");return to({actual:o,expected:e,operator:t})},{timeout:n}).toBe(!0).catch(()=>{})}async function ot({expected:e,label:t,operator:r,read:n}){try{let o=await n();return eo({actual:o,expected:e,label:t,operator:r})}catch(o){let i=`${t} ${r} "${e}"`,s=o instanceof Error?o.message:String(o);return{description:i,detail:`Read failed: ${Ka(s)}`,status:"failed"}}}function Ka(e){let t=e.indexOf(`
|
|
12
|
+
`);return t===-1?e:e.slice(0,t)}function eo(e){let t=`${e.label} ${e.operator} "${e.expected}"`,r=to(e),n=r?void 0:`Got: "${e.actual}"`;return{description:t,detail:n,status:r?"passed":"failed"}}function to({actual:e,expected:t,operator:r}){return r==="equals"?e===t:r==="notEquals"?e!==t:r==="contains"?e.includes(t):r==="startsWith"?e.startsWith(t):r==="endsWith"?e.endsWith(t):new RegExp(t).test(e)}function ro(e){let t=`${e.label} ${e.operator} ${String(e.expected)}`,r=no(e),n=r?void 0:`Got: ${String(e.actual)}`;return{description:t,detail:n,status:r?"passed":"failed"}}function no({actual:e,expected:t,operator:r}){return r==="equals"?e===t:r==="notEquals"?e!==t:r==="greaterThan"?e>t:r==="greaterThanOrEqual"?e>=t:r==="lessThan"?e<t:e<=t}import{execFile as Ya}from"child_process";import{createRequire as Xa}from"module";import oo from"fs";import io from"path";import{chromium as so}from"playwright";import Zw from"fs";import tb from"path";import Ja from"pino";var f=Ja({level:process.env.LOG_LEVEL??"info",transport:{options:{ignore:"pid,hostname"},target:"pino-pretty"}});async function Le({headed:e}){process.env.PW_TEST_SCREENSHOT_NO_FONTS_READY="1";try{return await so.launch({headless:!e})}catch(t){throw Qa(t)?new Error(`Playwright browsers are not installed. Run:
|
|
13
13
|
|
|
14
14
|
npx playwright install chromium
|
|
15
|
-
`):t}}async function
|
|
15
|
+
`):t}}async function Ar(){let e=so.executablePath();if(oo.existsSync(e))return;f.info("Chromium not found. Installing via Playwright...");let t=Xa(import.meta.url),r=io.dirname(t.resolve("playwright/package.json")),n=io.join(r,"cli.js");if(await new Promise((o,i)=>{Ya(process.execPath,[n,"install","chromium"],s=>{if(s!=null){i(new Error(`Playwright install failed: ${s.message}`));return}o()})}),!oo.existsSync(e))throw new Error(`Playwright browser installation failed. Try running manually:
|
|
16
16
|
|
|
17
17
|
npx playwright install chromium
|
|
18
|
-
`);f.info("\u2713 Chromium installed")}function Qa(e){return e instanceof Error?e.message.includes("Executable doesn't exist"):!1}import{readdir as ol,rm as il,stat as sl}from"fs/promises";import
|
|
18
|
+
`);f.info("\u2713 Chromium installed")}function Qa(e){return e instanceof Error?e.message.includes("Executable doesn't exist"):!1}import{readdir as ol,rm as il,stat as sl}from"fs/promises";import gb from"os";import co from"path";import{graphql as al}from"gql.tada";import{print as Za}from"graphql";var el=15e3,_e=class extends Error{errors;constructor(t){super(t.map(r=>r.message).join(", ")),this.name="GqlRequestError",this.errors=t}};async function y(e){let t=Za(e.document),r=JSON.stringify({query:t,variables:e.variables}),n=`${e.config.ripploServerUrl}/graphql`,o;try{o=await fetch(n,{body:r,headers:{Authorization:`Bearer ${e.config.token}`,"Content-Type":"application/json"},method:"POST",signal:AbortSignal.timeout(el)})}catch(s){let a=s instanceof Error?s.message:String(s);throw new Error(`Failed to connect to Ripplo server at ${e.config.ripploServerUrl}. Check the server is running and reachable. Details: ${a}`)}let i=await tl({res:o,url:n});if(!rl(i))throw new Error("Invalid GraphQL response");if(nl(i))throw new _e(i.errors);if(i.data==null)throw new Error("No data returned from server");return i.data}async function tl({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 rl(e){return typeof e=="object"&&e!=null&&("data"in e||"errors"in e)}function nl(e){return Array.isArray(e.errors)&&e.errors.length>0}var ao=co.join(process.cwd(),".ripplo","debug"),lo=360*60*1e3,vb=al(`
|
|
19
19
|
mutation RevokeCurrentCliToken {
|
|
20
20
|
revokeCurrentCliToken
|
|
21
21
|
}
|
|
22
|
-
`);async function xt({maxRuns:e}){try{let r=(await ol(ao,{withFileTypes:!0})).filter(c=>c.isDirectory()),n=Date.now(),o=await Promise.all(r.map(async c=>{let p=co.join(ao,c.name),m=await sl(p);return{dirPath:p,mtime:m.mtimeMs}})),i=o.filter(c=>n-c.mtime>lo),a=o.filter(c=>n-c.mtime<=lo).toSorted((c,p)=>p.mtime-c.mtime).slice(e),l=[...i,...a];if(l.length===0)return;await Promise.allSettled(l.map(c=>il(c.dirPath,{force:!0,recursive:!0}))),f.debug("Pruned %d old debug run(s)",l.length)}catch{f.warn("Debug run pruning failed, ignoring")}}var ll=15e3,cl=2,ul=250,dl=3e4,
|
|
23
|
-
`))}async function ml(e,t){let r=performance.now();try{return await fetch(e,{method:"HEAD",signal:AbortSignal.timeout(ll)}),f.debug("App URL reachability check ok (attempt %d, %dms)",t+1,Math.round(performance.now()-r)),null}catch(n){return f.debug("App URL reachability check attempt %d failed after %dms: %s",t+1,Math.round(performance.now()-r),n instanceof Error?n.message:String(n)),n}}function fl(e){return new Promise(t=>setTimeout(t,e))}import{Agent as gl,RetryAgent as yl,setGlobalDispatcher as hl}from"undici";var wl=1500,bl=4e3,vl=3,Sl=50,kl=100,uo=!1;function jr(){if(uo)return;uo=!0;let e=new gl({connections:kl,keepAliveMaxTimeout:bl,keepAliveTimeout:wl}),t=new yl(e,{errorCodes:["ECONNRESET","ECONNREFUSED","EPIPE","ETIMEDOUT","UND_ERR_REQ_CONTENT_LENGTH_MISMATCH","UND_ERR_SOCKET"],maxRetries:vl,methods:["GET","POST","HEAD","OPTIONS","PUT","DELETE"],minTimeout:Sl});hl(t)}var Do=yr(Et(),1);import{z as Gu}from"zod";import{z as Ct}from"zod";var jl=Ct.object({__codec:Ct.string().min(1),data:Ct.unknown(),version:Ct.number().int().positive()}),Tt=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}},It=class extends Error{constructor(t){super(`Codec mismatch: expected "${t.expected}", got "${t.got}"`),this.name="CodecMismatchError"}};function At(e){return fo({legacy:void 0,migrators:[],name:e,schemas:[]})}function fo(e){return{initial:t=>Lr(t,{...e,schemas:[t]}),legacy:t=>fo({...e,legacy:t})}}function Lr(e,t){return{build:()=>Nl(e,t),legacy:r=>Lr(e,{...t,legacy:r}),upgrade:(r,n)=>{let o=n;return Lr(r,{...t,migrators:[...t.migrators,o],schemas:[...t.schemas,r]})}}}function Nl(e,t){let r=t.schemas.length;return{currentVersion:r,name:t.name,decode:n=>Ol(e,t,n),encode:n=>({__codec:t.name,data:n,version:r})}}function Ol(e,t,r){let{data:n,version:o}=Dl(t,r),i=go(t,n,o);return e.parse(i)}function Dl(e,t){let r=jl.safeParse(t);if(r.success){if(r.data.__codec!==e.name)throw new It({expected:e.name,got:r.data.__codec});return{data:r.data.data,version:r.data.version}}if(e.legacy!=null&&e.legacy.detect(t))return{data:t,version:e.legacy.assumedVersion};throw new Error(`Cannot decode "${e.name}": value is not a codec envelope and no legacy detector matched.`)}function go(e,t,r){let n=e.schemas.length;if(r>n)throw new Tt({codec:e.name,currentVersion:n,gotVersion:r});if(r===n)return t;let o=e.schemas[r-1];if(o==null)throw new Error(`Codec "${e.name}" missing schema for v${String(r)}; cannot migrate.`);let i=o.parse(t),s=e.migrators[r-1];if(s==null)throw new Error(`Codec "${e.name}" missing migrator v${String(r)} \u2192 v${String(r+1)}.`);return go(e,s(i),r+1)}import{z as bo}from"zod";import{z as Ue}from"zod";var _r=Ue.object({depends:Ue.array(Ue.string().min(1)).optional().describe("Names of other preconditions that must be satisfied first. Resolved via topological sort; cycles are rejected at validation time."),description:Ue.string().min(1).describe("Human-readable description of what this precondition ensures"),returns:Ue.array(Ue.string().min(1)).optional().describe("Keys that the execute response's data field will contain. e.g. ['projectId', 'workflowId']. These are used for route param interpolation ({{projectId}}) and workflow variables. Declared here so generated types are strongly typed per precondition.")}).describe("A named precondition declared at the graph level. States reference these by name.");import{z as u}from"zod";import{z as we}from"zod";var Ll=we.object({by:we.literal("testId"),value:we.string().min(1)}),_l=we.object({by:we.literal("role"),name:we.string().optional(),role:we.string().min(1)}),R=we.discriminatedUnion("by",[Ll,_l]);import{z as yo}from"zod";var be=yo.enum(["equals","notEquals","contains","startsWith","endsWith","matches"]),$t=yo.enum(["equals","notEquals","greaterThan","greaterThanOrEqual","lessThan","lessThanOrEqual"]);import{z as N}from"zod";var Ul=N.object({type:N.literal("static"),value:N.union([N.string(),N.number(),N.boolean()])}),jt=N.object({name:N.string().min(1),type:N.literal("variable")}),Nt=N.discriminatedUnion("type",[Ul,jt]),X=N.discriminatedUnion("type",[N.object({type:N.literal("static"),value:N.string()}),jt]),Ot=N.discriminatedUnion("type",[N.object({type:N.literal("static"),value:N.number().int().nonnegative()}),jt]),Ur=N.discriminatedUnion("type",[N.object({type:N.literal("static"),value:N.union([N.string(),N.number(),N.boolean()])}),jt]);import{z as Q}from"zod";var Dt=Q.discriminatedUnion("type",[Q.object({default:Q.string().optional(),type:Q.literal("string")}),Q.object({default:Q.number().optional(),type:Q.literal("number")}),Q.object({default:Q.boolean().optional(),type:Q.literal("boolean")}),Q.object({key:Q.string().min(1),type:Q.literal("env")})]);var v={id:u.string().min(1).max(200),label:u.string().max(500).optional(),next:u.string().max(200).optional(),uiOnly:u.boolean().optional()},ho=500,Vl=u.object({...v,type:u.literal("goto"),url:X}),Fl=u.object({...v,locator:R,modifier:u.enum(["Alt","Control","Meta","Shift"]).optional(),type:u.literal("click")}),Ml=u.object({...v,locator:R,type:u.literal("fill"),value:X}),Bl=u.object({...v,locator:R,type:u.literal("select"),value:X}),Hl=u.object({...v,locator:R,type:u.literal("hover")}),Wl=u.object({...v,key:u.string().min(1),locator:R.optional(),type:u.literal("press")}),ql=u.object({...v,locator:R,type:u.literal("check")}),zl=u.object({...v,locator:R,type:u.literal("uncheck")}),Gl=u.object({...v,height:u.number().int().positive(),type:u.literal("setViewport"),width:u.number().int().positive()}),Kl=u.object({...v,message:u.string().min(1),type:u.literal("fail")}),Jl=u.object({...v,type:u.literal("setVariable"),value:Nt,variable:u.string().min(1)}),Yl=u.object({...v,locator:R,type:u.literal("extractText"),variable:u.string().min(1)}),Xl=u.object({...v,files:u.array(u.string()).min(1),locator:R,type:u.literal("upload")}),Ql=u.object({...v,locator:R,type:u.literal("dblclick")}),Zl=u.object({...v,source:R,target:R,type:u.literal("drag")}),ec=u.object({...v,locator:R,type:u.literal("scrollIntoView")}),tc=u.object({...v,locator:R,type:u.literal("type"),value:X}),rc=u.object({...v,locator:R,type:u.literal("focus")}),nc=u.object({...v,locator:R,type:u.literal("clear")}),oc=u.object({...v,locator:R,type:u.literal("rightClick")}),ic=u.object({...v,action:u.enum(["accept","dismiss"]),promptText:u.string().optional(),type:u.literal("handleDialog")}),sc=u.object({...v,action:u.enum(["read","write"]),type:u.literal("clipboard"),value:X.optional(),variable:u.string().min(1).optional()}),ac=u.object({...v,permission:u.string().min(1),state:u.enum(["granted","prompt"]),type:u.literal("setPermission")}),lc=u.object({...v,locator:R,type:u.literal("assertVisible")}),cc=u.object({...v,locator:R,type:u.literal("assertNotVisible")}),uc=u.object({...v,expected:X,locator:R,operator:be,type:u.literal("assertText")}),dc=u.object({...v,expected:X,operator:be,type:u.literal("assertUrl")}),pc=u.object({...v,expected:Ot,locator:R,operator:$t,type:u.literal("assertCount")}),mc=u.object({...v,expected:X,locator:R,operator:be,type:u.literal("assertValue")}),fc=u.object({...v,attribute:u.string().min(1),expected:X,locator:R,operator:be,type:u.literal("assertAttribute")}),gc=u.object({...v,locator:R,type:u.literal("assertEnabled")}),yc=u.object({...v,locator:R,type:u.literal("assertDisabled")}),hc=u.object({...v,expected:X,operator:be,type:u.literal("assertTitle")}),wc=u.object({...v,locator:R,type:u.literal("assertChecked")}),bc=u.object({...v,locator:R,type:u.literal("assertNotChecked")}),vc=u.object({...v,locator:R,type:u.literal("assertFocused")}),Sc=u.object({...v,locator:R,type:u.literal("assertNotFocused")}),kc=u.object({...v,budget:u.enum(["fast","slow","async"]),observer:u.string().min(1).max(200),params:u.record(u.string().max(200),Ur),type:u.literal("assertObserver")}),wo=u.discriminatedUnion("type",[Vl,Fl,Ml,Bl,Hl,Wl,ql,zl,lc,cc,uc,dc,pc,mc,fc,gc,yc,Gl,Kl,Jl,Yl,Xl,Ql,Zl,ec,tc,rc,nc,oc,ic,sc,ac,hc,wc,bc,vc,Sc,kc]),Lt=u.object({entryNode:u.string().min(1).max(200),nodes:u.record(u.string().max(200),wo).refine(e=>Object.keys(e).length<=ho,`Workflow has more than ${String(ho)} nodes`),uiOnly:u.boolean().optional(),variableNamespaces:u.record(u.string().max(200),u.string().max(500)).optional(),variables:u.record(u.string().max(200),Dt).optional()});var Rc=bo.record(bo.string().max(200),_r),Pc={assumedVersion:1,detect:e=>typeof e=="object"&&e!==null&&"entryNode"in e&&"nodes"in e},xc={assumedVersion:1,detect:e=>typeof e=="object"&&e!==null&&!Array.isArray(e)&&!("__codec"in e)},Vr=At("workflow-spec").legacy(Pc).initial(Lt).build(),Ec=At("precondition-map").legacy(xc).initial(Rc).build();import{z as Fr}from"zod";var vo=["fast","slow","async"],Cc=Fr.object({budget:Fr.enum(vo).describe("Polling budget tier: fast | slow | async"),description:Fr.string().min(1).describe("Human-readable description of what this observer checks")}).describe("A named backend state observer. Tests assert against it with assert.backend(observer, params). Implementation lives on the user's server.");function _t(e){return e.label??`${e.type} (${e.id})`}import{graphql as Lo,readFragment as Ku}from"gql.tada";function ko(){let e,t=!1;function r(o){e=o,t&&So(o)}async function n(){t||(t=!0,e!=null&&await So(e))}return{attachContext:r,fire:n,fired:()=>t}}async function So(e){await e.close().catch(t=>{let r=t instanceof Error?t.message:String(t);f.warn("Failed to close browser context during abort: %s",r)})}import{mkdir as Mr,writeFile as ne}from"fs/promises";import K from"path";import{z as re}from"zod";async function Po({context:e,page:t,runId:r,stepIndex:n,stepResult:o}){try{let i=K.join(process.cwd(),".ripplo","debug",r,"steps",String(n));await Mr(i,{recursive:!0});let s={assertions:o.assertions,detail:o.detail,duration:o.duration,nodeId:o.nodeId,nodeType:o.nodeType,snapshotTimestamp:o.snapshotTimestamp,status:o.status,stepIndex:o.stepIndex,title:o.title,url:o.url};await Promise.all([ne(K.join(i,"info.json"),JSON.stringify(s,null,2)),Ic(Ac({context:e,page:t,stepDir:i}),Tc,`capturePageState step ${String(n)}`)])}catch(i){let s=i instanceof Error?i.message:String(i);f.warn("Failed to write step debug data for step %d: %s",n,s)}}var Tc=15e3;async function Ic(e,t,r){let n,o=new Promise((i,s)=>{n=setTimeout(()=>{s(new Error(`${r} timed out after ${String(t)}ms`))},t)});try{return await Promise.race([e,o])}finally{n!=null&&clearTimeout(n)}}async function Ac({context:e,page:t,stepDir:r}){let[n,o,i,s,a]=await Promise.all([Nc(t),Lc(t),Bc({context:e,page:t}),Fc(t),jc(t)]);await Promise.all([ne(K.join(r,"dom.html"),n),ne(K.join(r,"accessibility-tree.full.json"),JSON.stringify(o,null,2)),ne(K.join(r,"accessibility-tree.json"),_c(o)),ne(K.join(r,"storage.json"),JSON.stringify(i,null,2)),ne(K.join(r,"rrweb-elements.ndjson"),a),ne(K.join(r,"screenshot.png"),s)])}var $c=`
|
|
22
|
+
`);async function xt({maxRuns:e}){try{let r=(await ol(ao,{withFileTypes:!0})).filter(c=>c.isDirectory()),n=Date.now(),o=await Promise.all(r.map(async c=>{let p=co.join(ao,c.name),m=await sl(p);return{dirPath:p,mtime:m.mtimeMs}})),i=o.filter(c=>n-c.mtime>lo),a=o.filter(c=>n-c.mtime<=lo).toSorted((c,p)=>p.mtime-c.mtime).slice(e),l=[...i,...a];if(l.length===0)return;await Promise.allSettled(l.map(c=>il(c.dirPath,{force:!0,recursive:!0}))),f.debug("Pruned %d old debug run(s)",l.length)}catch{f.warn("Debug run pruning failed, ignoring")}}var ll=15e3,cl=2,ul=250,dl=3e4,Ir=new Map;function $r({appUrl:e}){let t=Date.now(),r=Ir.get(e);if(r!=null&&r.expiresAt>t)return r.promise;let n=pl(e).catch(o=>{throw Ir.delete(e),o});return Ir.set(e,{expiresAt:t+dl,promise:n}),n}async function pl(e){let t=null,r=0;for(;r<=cl;){r>0&&await fl(ul);let o=await ml(e,r);if(o==null)return;t=o,r+=1}let n=t instanceof Error?t.message:String(t);throw f.debug("App URL unreachable after retries: %s",n),new Error([`Could not reach your dev server at ${e}.`,"","Troubleshooting:",` 1. Make sure your app is running at ${e}`," 2. Check RIPPLO_APP_URL in the env file declared in .ripplo/project.json"," 3. If you're in a git worktree, RIPPLO_APP_URL and RIPPLO_ENGINE_URL must point at this worktree's dev server port (not main's)"].join(`
|
|
23
|
+
`))}async function ml(e,t){let r=performance.now();try{return await fetch(e,{method:"HEAD",signal:AbortSignal.timeout(ll)}),f.debug("App URL reachability check ok (attempt %d, %dms)",t+1,Math.round(performance.now()-r)),null}catch(n){return f.debug("App URL reachability check attempt %d failed after %dms: %s",t+1,Math.round(performance.now()-r),n instanceof Error?n.message:String(n)),n}}function fl(e){return new Promise(t=>setTimeout(t,e))}import{Agent as gl,RetryAgent as yl,setGlobalDispatcher as hl}from"undici";var wl=1500,bl=4e3,vl=3,Sl=50,kl=100,uo=!1;function jr(){if(uo)return;uo=!0;let e=new gl({connections:kl,keepAliveMaxTimeout:bl,keepAliveTimeout:wl}),t=new yl(e,{errorCodes:["ECONNRESET","ECONNREFUSED","EPIPE","ETIMEDOUT","UND_ERR_REQ_CONTENT_LENGTH_MISMATCH","UND_ERR_SOCKET"],maxRetries:vl,methods:["GET","POST","HEAD","OPTIONS","PUT","DELETE"],minTimeout:Sl});hl(t)}var Do=yr(Et(),1);import{z as Gu}from"zod";import{z as Ct}from"zod";var jl=Ct.object({__codec:Ct.string().min(1),data:Ct.unknown(),version:Ct.number().int().positive()}),Tt=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}},At=class extends Error{constructor(t){super(`Codec mismatch: expected "${t.expected}", got "${t.got}"`),this.name="CodecMismatchError"}};function It(e){return fo({legacy:void 0,migrators:[],name:e,schemas:[]})}function fo(e){return{initial:t=>Lr(t,{...e,schemas:[t]}),legacy:t=>fo({...e,legacy:t})}}function Lr(e,t){return{build:()=>Nl(e,t),legacy:r=>Lr(e,{...t,legacy:r}),upgrade:(r,n)=>{let o=n;return Lr(r,{...t,migrators:[...t.migrators,o],schemas:[...t.schemas,r]})}}}function Nl(e,t){let r=t.schemas.length;return{currentVersion:r,name:t.name,decode:n=>Ol(e,t,n),encode:n=>({__codec:t.name,data:n,version:r})}}function Ol(e,t,r){let{data:n,version:o}=Dl(t,r),i=go(t,n,o);return e.parse(i)}function Dl(e,t){let r=jl.safeParse(t);if(r.success){if(r.data.__codec!==e.name)throw new At({expected:e.name,got:r.data.__codec});return{data:r.data.data,version:r.data.version}}if(e.legacy!=null&&e.legacy.detect(t))return{data:t,version:e.legacy.assumedVersion};throw new Error(`Cannot decode "${e.name}": value is not a codec envelope and no legacy detector matched.`)}function go(e,t,r){let n=e.schemas.length;if(r>n)throw new Tt({codec:e.name,currentVersion:n,gotVersion:r});if(r===n)return t;let o=e.schemas[r-1];if(o==null)throw new Error(`Codec "${e.name}" missing schema for v${String(r)}; cannot migrate.`);let i=o.parse(t),s=e.migrators[r-1];if(s==null)throw new Error(`Codec "${e.name}" missing migrator v${String(r)} \u2192 v${String(r+1)}.`);return go(e,s(i),r+1)}import{z as bo}from"zod";import{z as Ue}from"zod";var _r=Ue.object({depends:Ue.array(Ue.string().min(1)).optional().describe("Names of other preconditions that must be satisfied first. Resolved via topological sort; cycles are rejected at validation time."),description:Ue.string().min(1).describe("Human-readable description of what this precondition ensures"),returns:Ue.array(Ue.string().min(1)).optional().describe("Keys that the execute response's data field will contain. e.g. ['projectId', 'workflowId']. These are used for route param interpolation ({{projectId}}) and workflow variables. Declared here so generated types are strongly typed per precondition.")}).describe("A named precondition declared at the graph level. States reference these by name.");import{z as u}from"zod";import{z as we}from"zod";var Ll=we.object({by:we.literal("testId"),value:we.string().min(1)}),_l=we.object({by:we.literal("role"),name:we.string().optional(),role:we.string().min(1)}),R=we.discriminatedUnion("by",[Ll,_l]);import{z as yo}from"zod";var be=yo.enum(["equals","notEquals","contains","startsWith","endsWith","matches"]),$t=yo.enum(["equals","notEquals","greaterThan","greaterThanOrEqual","lessThan","lessThanOrEqual"]);import{z as N}from"zod";var Ul=N.object({type:N.literal("static"),value:N.union([N.string(),N.number(),N.boolean()])}),jt=N.object({name:N.string().min(1),type:N.literal("variable")}),Nt=N.discriminatedUnion("type",[Ul,jt]),X=N.discriminatedUnion("type",[N.object({type:N.literal("static"),value:N.string()}),jt]),Ot=N.discriminatedUnion("type",[N.object({type:N.literal("static"),value:N.number().int().nonnegative()}),jt]),Ur=N.discriminatedUnion("type",[N.object({type:N.literal("static"),value:N.union([N.string(),N.number(),N.boolean()])}),jt]);import{z as Q}from"zod";var Dt=Q.discriminatedUnion("type",[Q.object({default:Q.string().optional(),type:Q.literal("string")}),Q.object({default:Q.number().optional(),type:Q.literal("number")}),Q.object({default:Q.boolean().optional(),type:Q.literal("boolean")}),Q.object({key:Q.string().min(1),type:Q.literal("env")})]);var v={id:u.string().min(1).max(200),label:u.string().max(500).optional(),next:u.string().max(200).optional(),uiOnly:u.boolean().optional()},ho=500,Vl=u.object({...v,type:u.literal("goto"),url:X}),Fl=u.object({...v,locator:R,modifier:u.enum(["Alt","Control","Meta","Shift"]).optional(),type:u.literal("click")}),Ml=u.object({...v,locator:R,type:u.literal("fill"),value:X}),Bl=u.object({...v,locator:R,type:u.literal("select"),value:X}),Hl=u.object({...v,locator:R,type:u.literal("hover")}),Wl=u.object({...v,key:u.string().min(1),locator:R.optional(),type:u.literal("press")}),ql=u.object({...v,locator:R,type:u.literal("check")}),zl=u.object({...v,locator:R,type:u.literal("uncheck")}),Gl=u.object({...v,height:u.number().int().positive(),type:u.literal("setViewport"),width:u.number().int().positive()}),Kl=u.object({...v,message:u.string().min(1),type:u.literal("fail")}),Jl=u.object({...v,type:u.literal("setVariable"),value:Nt,variable:u.string().min(1)}),Yl=u.object({...v,locator:R,type:u.literal("extractText"),variable:u.string().min(1)}),Xl=u.object({...v,files:u.array(u.string()).min(1),locator:R,type:u.literal("upload")}),Ql=u.object({...v,locator:R,type:u.literal("dblclick")}),Zl=u.object({...v,source:R,target:R,type:u.literal("drag")}),ec=u.object({...v,locator:R,type:u.literal("scrollIntoView")}),tc=u.object({...v,locator:R,type:u.literal("type"),value:X}),rc=u.object({...v,locator:R,type:u.literal("focus")}),nc=u.object({...v,locator:R,type:u.literal("clear")}),oc=u.object({...v,locator:R,type:u.literal("rightClick")}),ic=u.object({...v,action:u.enum(["accept","dismiss"]),promptText:u.string().optional(),type:u.literal("handleDialog")}),sc=u.object({...v,action:u.enum(["read","write"]),type:u.literal("clipboard"),value:X.optional(),variable:u.string().min(1).optional()}),ac=u.object({...v,permission:u.string().min(1),state:u.enum(["granted","prompt"]),type:u.literal("setPermission")}),lc=u.object({...v,locator:R,type:u.literal("assertVisible")}),cc=u.object({...v,locator:R,type:u.literal("assertNotVisible")}),uc=u.object({...v,expected:X,locator:R,operator:be,type:u.literal("assertText")}),dc=u.object({...v,expected:X,operator:be,type:u.literal("assertUrl")}),pc=u.object({...v,expected:Ot,locator:R,operator:$t,type:u.literal("assertCount")}),mc=u.object({...v,expected:X,locator:R,operator:be,type:u.literal("assertValue")}),fc=u.object({...v,attribute:u.string().min(1),expected:X,locator:R,operator:be,type:u.literal("assertAttribute")}),gc=u.object({...v,locator:R,type:u.literal("assertEnabled")}),yc=u.object({...v,locator:R,type:u.literal("assertDisabled")}),hc=u.object({...v,expected:X,operator:be,type:u.literal("assertTitle")}),wc=u.object({...v,locator:R,type:u.literal("assertChecked")}),bc=u.object({...v,locator:R,type:u.literal("assertNotChecked")}),vc=u.object({...v,locator:R,type:u.literal("assertFocused")}),Sc=u.object({...v,locator:R,type:u.literal("assertNotFocused")}),kc=u.object({...v,budget:u.enum(["fast","slow","async"]),observer:u.string().min(1).max(200),params:u.record(u.string().max(200),Ur),type:u.literal("assertObserver")}),wo=u.discriminatedUnion("type",[Vl,Fl,Ml,Bl,Hl,Wl,ql,zl,lc,cc,uc,dc,pc,mc,fc,gc,yc,Gl,Kl,Jl,Yl,Xl,Ql,Zl,ec,tc,rc,nc,oc,ic,sc,ac,hc,wc,bc,vc,Sc,kc]),Lt=u.object({entryNode:u.string().min(1).max(200),nodes:u.record(u.string().max(200),wo).refine(e=>Object.keys(e).length<=ho,`Workflow has more than ${String(ho)} nodes`),uiOnly:u.boolean().optional(),variableNamespaces:u.record(u.string().max(200),u.string().max(500)).optional(),variables:u.record(u.string().max(200),Dt).optional()});var Rc=bo.record(bo.string().max(200),_r),Pc={assumedVersion:1,detect:e=>typeof e=="object"&&e!==null&&"entryNode"in e&&"nodes"in e},xc={assumedVersion:1,detect:e=>typeof e=="object"&&e!==null&&!Array.isArray(e)&&!("__codec"in e)},Vr=It("workflow-spec").legacy(Pc).initial(Lt).build(),Ec=It("precondition-map").legacy(xc).initial(Rc).build();import{z as Fr}from"zod";var vo=["fast","slow","async"],Cc=Fr.object({budget:Fr.enum(vo).describe("Polling budget tier: fast | slow | async"),description:Fr.string().min(1).describe("Human-readable description of what this observer checks")}).describe("A named backend state observer. Tests assert against it with assert.backend(observer, params). Implementation lives on the user's server.");function _t(e){return e.label??`${e.type} (${e.id})`}import{graphql as Lo,readFragment as Ku}from"gql.tada";function ko(){let e,t=!1;function r(o){e=o,t&&So(o)}async function n(){t||(t=!0,e!=null&&await So(e))}return{attachContext:r,fire:n,fired:()=>t}}async function So(e){await e.close().catch(t=>{let r=t instanceof Error?t.message:String(t);f.warn("Failed to close browser context during abort: %s",r)})}import{mkdir as Mr,writeFile as ne}from"fs/promises";import K from"path";import{z as re}from"zod";async function Po({context:e,page:t,runId:r,stepIndex:n,stepResult:o}){try{let i=K.join(process.cwd(),".ripplo","debug",r,"steps",String(n));await Mr(i,{recursive:!0});let s={assertions:o.assertions,detail:o.detail,duration:o.duration,nodeId:o.nodeId,nodeType:o.nodeType,snapshotTimestamp:o.snapshotTimestamp,status:o.status,stepIndex:o.stepIndex,title:o.title,url:o.url};await Promise.all([ne(K.join(i,"info.json"),JSON.stringify(s,null,2)),Ac(Ic({context:e,page:t,stepDir:i}),Tc,`capturePageState step ${String(n)}`)])}catch(i){let s=i instanceof Error?i.message:String(i);f.warn("Failed to write step debug data for step %d: %s",n,s)}}var Tc=15e3;async function Ac(e,t,r){let n,o=new Promise((i,s)=>{n=setTimeout(()=>{s(new Error(`${r} timed out after ${String(t)}ms`))},t)});try{return await Promise.race([e,o])}finally{n!=null&&clearTimeout(n)}}async function Ic({context:e,page:t,stepDir:r}){let[n,o,i,s,a]=await Promise.all([Nc(t),Lc(t),Bc({context:e,page:t}),Fc(t),jc(t)]);await Promise.all([ne(K.join(r,"dom.html"),n),ne(K.join(r,"accessibility-tree.full.json"),JSON.stringify(o,null,2)),ne(K.join(r,"accessibility-tree.json"),_c(o)),ne(K.join(r,"storage.json"),JSON.stringify(i,null,2)),ne(K.join(r,"rrweb-elements.ndjson"),a),ne(K.join(r,"screenshot.png"),s)])}var $c=`
|
|
24
24
|
(function () {
|
|
25
25
|
try {
|
|
26
26
|
var rrweb = window.rrweb || globalThis.rrweb;
|
|
@@ -105,10 +105,10 @@ ${r}`].join(`
|
|
|
105
105
|
`);await Promise.all([ne(K.join(o,"error.txt"),i),ne(K.join(o,"summary.txt"),s),ne(K.join(o,"manifest.md"),a)]),f.info("Debug error artifacts written to .ripplo/debug/%s/",t)}catch(o){let i=o instanceof Error?o.message:String(o);f.warn("Failed to write error debug artifacts: %s",i)}}import{readFileSync as qc}from"fs";import{createRequire as zc}from"module";import Co from"path";import{gzipSync as Gc}from"zlib";var Kc=zc(import.meta.url),Jc=Kc.resolve("rrweb"),Yc=Co.join(Co.dirname(Jc),"rrweb.umd.min.cjs"),Xc=qc(Yc,"utf8"),Qc=[";(function() {"," try {"," if (window.__ripploRrwebLoaded) return;"," window.__ripploRrwebLoaded = true;"," window.__ripploRrwebBuffer = [];"," window.__ripploRrwebDrain = function() {"," var out = window.__ripploRrwebBuffer;"," window.__ripploRrwebBuffer = [];"," return out;"," };"," var r = window.rrweb;"," if (r == null || r.record == null) {"," console.warn('[ripplo] rrweb global not found');"," return;"," }"," function startRecording() {"," if (window.__ripploRrwebStartedAt != null) return;"," window.__ripploRrwebStartedAt = Date.now();"," var stop = r.record({"," emit: function(event) { window.__ripploRrwebBuffer.push(event); },"," recordCanvas: false,"," recordCrossOriginIframes: false,"," });"," window.__ripploRrwebStop = stop;"," }"," window.__ripploRrwebStart = startRecording;"," // Auto-start on every bootstrap run so agent-driven tests (which don't"," // emit a 'first step' signal before navigating) capture from the start."," startRecording();"," } catch (err) {"," console.error('[ripplo] rrweb bootstrap failed', err && err.message ? err.message : err);"," }","})();"].join(`
|
|
106
106
|
`),Zc=Xc+`
|
|
107
107
|
`+Qc;async function To(e){let t,r=0;async function n(){await e.addScriptTag({content:Zc})}await n(),e.on("load",()=>{n().catch(l=>{let c=l instanceof Error?l.message:String(l);f.warn("rrweb re-injection on navigation failed: %s",c)})});async function o(){await J({awaitPromise:!1,expression:"globalThis.__ripploRrwebStart && globalThis.__ripploRrwebStart()",label:"rrweb start",page:e,timeoutMs:void 0});let l=await J({awaitPromise:!1,expression:"globalThis.__ripploRrwebStartedAt",label:"rrweb startedAt",page:e,timeoutMs:void 0});typeof l=="number"&&(t??=l)}function i(){if(t!=null)return Date.now()-t}async function s(){let l=await J({awaitPromise:!1,expression:"globalThis.__ripploRrwebDrain ? globalThis.__ripploRrwebDrain() : []",label:"rrweb drain",page:e,timeoutMs:void 0})??[],c=l[0],p=l.at(-1);if(c==null||p==null)return;t??=c.timestamp;let m=t,h=l.map(g=>JSON.stringify(g)).join(`
|
|
108
|
-
`),$={body:Gc(Buffer.from(h,"utf8")),chunkIndex:r,endTimestamp:p.timestamp-m,eventCount:l.length,startTimestamp:c.timestamp-m};return r+=1,$}async function a(){await J({awaitPromise:!1,expression:"globalThis.__ripploRrwebStop && globalThis.__ripploRrwebStop()",label:"rrweb stop",page:e,timeoutMs:void 0})}return{currentOffsetMs:i,detach:a,start:o,takeChunk:s}}import{z as oe}from"zod";import
|
|
108
|
+
`),$={body:Gc(Buffer.from(h,"utf8")),chunkIndex:r,endTimestamp:p.timestamp-m,eventCount:l.length,startTimestamp:c.timestamp-m};return r+=1,$}async function a(){await J({awaitPromise:!1,expression:"globalThis.__ripploRrwebStop && globalThis.__ripploRrwebStop()",label:"rrweb stop",page:e,timeoutMs:void 0})}return{currentOffsetMs:i,detach:a,start:o,takeChunk:s}}import{z as oe}from"zod";import Ao from"crypto";import{Webhook as eu}from"standardwebhooks";function ve({body:e,secret:t}){let r=new eu(t),n=`msg_${Ao.randomUUID()}`,o=new Date,i=r.sign(n,o,e),s=Math.floor(o.getTime()/1e3);return{"webhook-id":n,"webhook-signature":i,"webhook-timestamp":String(s)}}function Br(){return`whsec_${Ao.randomBytes(24).toString("base64")}`}var tu=15e4,ru={async:{backoffMs:[500,1e3,2e3,5e3],timeoutMs:12e4},fast:{backoffMs:[100,250,500,1e3],timeoutMs:5e3},slow:{backoffMs:[250,500,1e3,2e3],timeoutMs:3e4}},nu=oe.discriminatedUnion("kind",[oe.object({kind:oe.literal("pass")}),oe.object({kind:oe.literal("retry"),reason:oe.string()}),oe.object({kind:oe.literal("fail"),reason:oe.string()})]),ou=oe.object({error:oe.string().optional(),outcome:nu.optional(),success:oe.boolean()});async function Io({apiUrl:e,budget:t,observer:r,params:n,webhookSecret:o}){let i=ru[t],s=performance.now(),a={lastReason:void 0,pollCount:0};for(;performance.now()-s<i.timeoutMs;){a.pollCount+=1;let l=await su({apiUrl:e,observer:r,params:n,webhookSecret:o}),c=iu({observer:r,outcome:l,start:s,state:a});if(c!=null)return c;let p=i.timeoutMs-(performance.now()-s);if(p<=0)break;let m=Math.min(au({backoff:i.backoffMs,pollCount:a.pollCount}),p);await lu(m)}return{description:`observer "${r}"`,detail:`budget "${t}" exhausted after ${String(a.pollCount)} poll(s) (${$o(s)}); last: ${a.lastReason??"no retry reason"}
|
|
109
109
|
\u2192 /ripplo:debug \u2014 check .ripplo/debug/<runId>/ artifacts`,status:"failed"}}function iu({observer:e,outcome:t,start:r,state:n}){return t.kind==="transport-error"?{description:`observer "${e}"`,detail:`transport error after ${String(n.pollCount)} poll(s): ${t.reason}
|
|
110
110
|
Load \`/ripplo:setup\` skill for instructions on engine endpoint + webhook secret wiring.`,status:"failed"}:t.kind==="pass"?{description:`observer "${e}"`,detail:n.pollCount>1?`passed after ${String(n.pollCount)} polls (${$o(r)})`:void 0,status:"passed"}:t.kind==="fail"?{description:`observer "${e}"`,detail:`failed (invariant): ${t.reason} (after ${String(n.pollCount)} poll(s)) \u2014 ctx.fail stops polling immediately and is reserved for invariant violations (wrong shape, contradictory/forbidden state). For transient conditions like "not yet committed", "status not yet X", or "row not found", use ctx.retry(reason) so the runtime keeps polling until the budget expires.
|
|
111
|
-
Load \`/ripplo:create\` skill for instructions.`,status:"failed"}:(n.lastReason=t.reason,null)}async function su({apiUrl:e,observer:t,params:r,webhookSecret:n}){let o=JSON.stringify({observer:t,params:r});try{let i=await fetch(`${e}/execute-observer`,{body:o,headers:{"Content-Type":"application/json",...ve({body:o,secret:n})},method:"PUT",signal:AbortSignal.timeout(tu)});if(!i.ok){let l=await i.text().catch(()=>"");return{kind:"transport-error",reason:`status ${String(i.status)}: ${l.slice(0,200)}`}}let s=await i.json(),a=ou.safeParse(s);return a.success?!a.data.success||a.data.outcome==null?{kind:"transport-error",reason:a.data.error??"engine reported failure without outcome"}:a.data.outcome:{kind:"transport-error",reason:`invalid response shape: ${a.error.message}`}}catch(i){let s=i instanceof Error?i.message:String(i);return f.error("observer request failed: %s",s),{kind:"transport-error",reason:s}}}function au({backoff:e,pollCount:t}){let r=Math.min(t-1,e.length-1);return e[r]??1e3}function $o(e){return`${String(Math.round(performance.now()-e))}ms`}async function lu(e){return new Promise(t=>setTimeout(t,e))}var Vt=15e3;async function Hr({failFast:e,getRecordingOffsetMs:t,observerTransport:r,onStep:n,page:o,spec:i,variables:s}){let a=performance.now();return uu({currentId:i.entryNode,failFast:e,getRecordingOffsetMs:t,observerTransport:r,onStep:n,page:o,runStartTime:a,spec:i,variables:s})}function cu({onStep:e,steps:t,target:r}){t.forEach(n=>{let o={...n,stepIndex:r.length};r.push(o),e?.(o)})}async function uu({currentId:e,failFast:t,getRecordingOffsetMs:r,observerTransport:n,onStep:o,page:i,runStartTime:s,spec:a,variables:l}){let c=[],p=l,m=e;for(;m!=null;){let h=a.nodes[m];if(h==null)throw new Error(`Node "${m}" not found in spec`);let T=m,$=_t(h);f.info("Executing node: %s [%s]",$,h.type);let g=await du({getRecordingOffsetMs:r,node:h,nodeId:T,observerTransport:n,page:i,runStartTime:s,variables:p});if(cu({onStep:o,steps:[g],target:c}),p=g.variables,t&&g.status==="failed")break;m=h.next}return{steps:c,variables:p}}async function du({getRecordingOffsetMs:e,node:t,nodeId:r,observerTransport:n,page:o,runStartTime:i,variables:s}){let a=performance.now(),l=e?.(),c=_t(t),p=Vt;try{let m=await pu({node:t,observerTransport:n,page:o,timeout:p,variables:s}),h=Math.round(performance.now()-a),T=m.assertions.some(g=>g.status==="failed"),$=e?.();return{assertions:m.assertions,detail:void 0,duration:h,nodeId:r,nodeType:t.type,recordingEndMs:$,recordingStartMs:l,snapshotTimestamp:Math.round(performance.now()-i),status:T?"failed":"passed",stepIndex:0,title:c,url:o.url(),variables:m.variables}}catch(m){let h=Math.round(performance.now()-a),T=m instanceof Error?m.message:String(m),$=e?.();return{assertions:[],detail:T,duration:h,nodeId:r,nodeType:t.type,recordingEndMs:$,recordingStartMs:l,snapshotTimestamp:Math.round(performance.now()-i),status:"failed",stepIndex:0,title:c,url:o.url(),variables:s}}}async function pu({node:e,observerTransport:t,page:r,timeout:n,variables:o}){if(mu(e)){let s=await kr({node:e,page:r,timeout:n,variables:o});return{assertions:[],variables:s.variables}}return{assertions:await gu({node:e,observerTransport:t,page:r,timeout:n,variables:o}),variables:o}}function mu(e){return["goto","click","dblclick","fill","select","hover","press","check","uncheck","clear","rightClick","handleDialog","clipboard","setPermission","setViewport","fail","setVariable","extractText","upload","drag","scrollIntoView","type","focus"].includes(e.type)}function fu(e){return e.type.startsWith("assert")}async function gu({node:e,observerTransport:t,page:r,timeout:n,variables:o}){if(!fu(e))throw new Error(`Unknown node type: ${e.type}`);let i=e;switch(i.type){case"assertVisible":case"assertNotVisible":case"assertEnabled":case"assertDisabled":case"assertChecked":case"assertNotChecked":case"assertFocused":case"assertNotFocused":return hu({assertNode:i,page:r,timeout:n,variables:o});case"assertText":{let s=Y({ref:i.expected,variables:o});return[await Rr({expected:s,locator:U({locator:i.locator,page:r,variables:o}),operator:i.operator,timeout:n})]}case"assertUrl":{let s=Y({ref:i.expected,variables:o});return[await Pr({expected:s,operator:i.operator,page:r,timeout:n})]}case"assertTitle":{let s=Y({ref:i.expected,variables:o});return[await zn({expected:s,operator:i.operator,page:r,timeout:n})]}case"assertCount":{let s=Sr({ref:i.expected,variables:o});return[await xr({expected:s,locator:U({locator:i.locator,page:r,variables:o}),operator:i.operator,timeout:n})]}case"assertValue":{let s=Y({ref:i.expected,variables:o});return[await Er({expected:s,locator:U({locator:i.locator,page:r,variables:o}),operator:i.operator,timeout:n})]}case"assertAttribute":{let s=Y({ref:i.expected,variables:o});return[await Gn({attribute:i.attribute,expected:s,locator:U({locator:i.locator,page:r,variables:o}),operator:i.operator,timeout:n})]}case"assertObserver":{if(t==null)return[{description:`observer "${i.observer}"`,detail:"observer transport not configured \u2014 set engineUrl + webhookSecret in ripplo.config",status:"failed"}];let s={};return Object.entries(i.params).forEach(([a,l])=>{s[a]=Rt({ref:l,variables:o})}),[await Ao({apiUrl:t.apiUrl,budget:i.budget,observer:i.observer,params:s,webhookSecret:t.webhookSecret})]}}}var yu={assertChecked:Yn,assertDisabled:Jn,assertEnabled:Kn,assertFocused:Qn,assertNotChecked:Xn,assertNotFocused:Zn,assertNotVisible:Tr,assertVisible:Cr};async function hu({assertNode:e,page:t,timeout:r,variables:n}){let o=yu[e.type];return[await o({locator:U({locator:e.locator,page:t,variables:n}),timeout:r})]}var wu=5e3,bu=2e3;async function Wr({abort:e,baseUrl:t,browser:r,cookies:n,extraVariables:o,observerTransport:i,onRecordingChunk:s,onStep:a,runId:l,spec:c}){let p=await r.newContext({baseURL:t});e.attachContext(p),p.setDefaultTimeout(Vt),p.setDefaultNavigationTimeout(Vt),n.length>0&&await p.addCookies(n);let m=await p.newPage(),h=await To(m);async function T(){let j=await h.takeChunk();j!=null&&s?.(j)}let $=setInterval(()=>{T().catch(j=>{let W=j instanceof Error?j.message:String(j);f.warn("rrweb chunk flush failed: %s",W)})},2e3),g=[],H=!1;function x(j){a?.(j),H||(H=!0,h.start().catch(W=>{let ge=W instanceof Error?W.message:String(W);f.warn("rrweb recorder start failed: %s",ge)})),g.push(Po({context:p,page:m,runId:l,stepIndex:j.stepIndex,stepResult:j}))}let F=vu(o,c.variableNamespaces),Ie={...vr({defs:c.variables}),...F};try{let j=await Hr({failFast:!0,getRecordingOffsetMs:h.currentOffsetMs,observerTransport:i,onStep:x,page:m,spec:c,variables:Ie});clearInterval($);let W=j.steps.filter(L=>L.status==="passed").length,ge=j.steps.filter(L=>L.status==="failed").length,pr={duration:j.steps.reduce((L,et)=>L+et.duration,0),failCount:ge,passCount:W,runId:l,status:ge>0?"failed":"passed",workflowName:""};return await ye(Promise.allSettled([Promise.allSettled(g).then(()=>xo({runId:l,steps:j.steps,summary:pr})),h.detach().then(T).catch(L=>{let et=L instanceof Error?L.message:String(L);f.warn("Recorder detach failed: %s",et)})]),wu,"post-run cleanup").catch(L=>{let et=L instanceof Error?L.message:String(L);f.warn("Post-run cleanup did not finish in budget: %s",et)}),j.steps}finally{clearInterval($),await ye(p.close(),bu,"context.close").catch(j=>{let W=j instanceof Error?j.message:String(j);f.warn("Context close failed: %s",W)})}}function vu(e,t){if(e==null||t==null)return{};let r=new Map;Object.entries(t).forEach(([o,i])=>{r.set(i,o)});let n={};return Object.entries(e).forEach(([o,i])=>{let s=r.get(o);s!=null&&(n[s]={...n[s],...i})}),n}async function de({fn:e,label:t}){let r=performance.now(),n=await e();return f.debug("%s: %dms",t,Math.round(performance.now()-r)),n}var Gr=yr(Et(),1);import{z as S}from"zod";var Su=S.union([S.string(),S.number(),S.boolean()]),ku=S.record(S.string(),S.record(S.string(),Su)),Ru=S.object({domain:S.string().optional(),expires:S.number().optional(),httpOnly:S.boolean().optional(),name:S.string(),path:S.string().optional(),sameSite:S.enum(["lax","none","strict"]).optional(),secure:S.boolean().optional(),value:S.string()}),Pu=S.discriminatedUnion("ok",[S.object({cookies:S.array(Ru),data:ku,executed:S.array(S.string()),ok:S.literal(!0),runId:S.string()}),S.object({error:S.string(),ok:S.literal(!1),runId:S.string()})]),xu=S.object({results:S.array(Pu)}),Eu=S.object({results:S.array(S.object({error:S.string().optional(),ok:S.boolean(),runId:S.string()}))}),jo=3e4;async function Kr({apiUrl:e,data:t,executed:r,runId:n,webhookSecret:o}){if(r.length!==0)try{await Au({apiUrl:e,webhookSecret:o}).load({data:t,preconditions:r,runId:n})}catch(i){let s=i instanceof Error?i.message:String(i);f.error("Teardown request failed: %s",s)}}async function Ft({engineBaseUrl:e,preconditionNames:t,runId:r,webhookSecret:n}){let o=e.length===0?void 0:e;return o==null||t.length===0?{apiUrl:o,cookies:[],data:{},executed:[]}:Cu({apiUrl:o,preconditionNames:t,runId:r,webhookSecret:n})}async function Cu({apiUrl:e,preconditionNames:t,runId:r,webhookSecret:n}){return{...await Tu({apiUrl:e,webhookSecret:n}).load({preconditionNames:t,runId:r}),apiUrl:e}}function Jr(){qr.clear(),zr.clear()}var qr=new Map;function Tu({apiUrl:e,webhookSecret:t}){let r=`${e}::${t}`,n=qr.get(r);if(n!=null)return n;let o=new Gr.default(i=>Iu({apiUrl:e,keys:i,webhookSecret:t}),{cache:!1,batchScheduleFn:i=>{setTimeout(i,200)},cacheKeyFn:i=>i.runId});return qr.set(r,o),o}async function Iu({apiUrl:e,keys:t,webhookSecret:r}){let n=performance.now(),o=JSON.stringify({batch:t.map(p=>({preconditions:[...p.preconditionNames],runId:p.runId}))}),i=await fetch(`${e}/execute-preconditions`,{body:o,headers:{"Content-Type":"application/json",...ve({body:o,secret:r})},method:"PUT",signal:AbortSignal.timeout(jo)});if(!i.ok){let p=await Nu(i),m=new Error(`execute-preconditions returned ${String(i.status)}: ${p}`);return t.map(()=>m)}let s=await i.json(),a=xu.safeParse(s);if(!a.success){let p=new Error(`execute-preconditions response has invalid shape: ${a.error.message}`);return t.map(()=>p)}let l=new URL(e).hostname,c=new Map(a.data.results.map(p=>[p.runId,p]));return f.debug({batchSize:t.length,elapsedMs:Math.round(performance.now()-n),op:"execute-preconditions"},"batched op flushed"),t.map(p=>{let m=c.get(p.runId);return m==null?new Error(`execute-preconditions response missing runId ${p.runId}`):m.ok?(f.info("Preconditions resolved: %s",m.executed.join(", ")),{cookies:m.cookies.map(h=>Lu({cookie:h,domain:l})),data:m.data,executed:m.executed}):new Error(`Precondition batch failed: ${m.error}`)})}var zr=new Map;function Au({apiUrl:e,webhookSecret:t}){let r=`${e}::${t}`,n=zr.get(r);if(n!=null)return n;let o=new Gr.default(i=>$u({apiUrl:e,keys:i,webhookSecret:t}),{cache:!1,batchScheduleFn:i=>{setTimeout(i,200)},cacheKeyFn:i=>i.runId});return zr.set(r,o),o}async function $u({apiUrl:e,keys:t,webhookSecret:r}){let n=JSON.stringify({batch:t.map(l=>({data:l.data,preconditions:[...l.preconditions],runId:l.runId}))}),o=await fetch(`${e}/teardown-preconditions`,{body:n,headers:{"Content-Type":"application/json",...ve({body:n,secret:r})},method:"PUT",signal:AbortSignal.timeout(jo)});if(!o.ok){let l=new Error(`teardown-preconditions returned ${String(o.status)}`);return t.map(()=>l)}let i=await o.json(),s=Eu.safeParse(i);if(!s.success){let l=new Error(`teardown-preconditions response has invalid shape: ${s.error.message}`);return t.map(()=>l)}let a=new Map(s.data.results.map(l=>[l.runId,l]));return t.map(l=>{let c=a.get(l.runId);if(c==null)return new Error(`teardown-preconditions response missing runId ${l.runId}`);if(!c.ok)return new Error(`Teardown failed: ${c.error??"unknown error"}`)})}var ju=S.object({error:S.string()});async function Nu(e){let t=await e.text().catch(()=>"");if(t.length===0)return"no body";let r=Ou(t),n=r==null?null:ju.safeParse(r);return n!=null&&n.success?n.data.error:t.slice(0,500)}function Ou(e){try{return JSON.parse(e)}catch{return null}}var Du={lax:"Lax",none:"None",strict:"Strict"};function Lu({cookie:e,domain:t}){let r={domain:e.domain??t,httpOnly:e.httpOnly??!1,name:e.name,path:e.path??"/",secure:e.secure??!1,value:e.value};return e.sameSite!=null&&(r.sameSite=Du[e.sameSite]??"Lax"),e.expires!=null&&(r.expires=e.expires),r}var it=yr(Et(),1);import{graphql as Ve}from"gql.tada";async function Yr({config:e,runId:t}){let r=_u(e);await r.start.load(t);let n=[];function o(c){return n.push(c.catch(()=>{})),c}function i(c){o(r.steps.load({runId:t,step:c})).catch(p=>{f.error(p,"submitRunSteps failed")})}function s(c){o(Fu({chunk:c,config:e,runId:t})).catch(p=>{f.error(p,"submitRunRecordingChunk failed")})}async function a(){for(;n.length>0;){let c=n.splice(0);await Promise.all(c)}}async function l({flush:c,statusOverride:p,steps:m,summary:h}){c&&await de({label:"flushSteps",fn:()=>a()});let T=m.filter(x=>x.status==="passed").length,$=m.filter(x=>x.status==="failed").length,g=m.reduce((x,F)=>x+F.duration,0),H=p??($>0?"failed":"passed");await de({label:"completeRun",fn:()=>r.complete.load({duration:g,failCount:$,passCount:T,runId:t,status:H,summary:h??null,warnCount:0})})}return{complete:l,enqueueRecordingChunk:s,enqueueStep:i,flushSteps:a,runId:t}}async function Xr({config:e,reason:t,runId:r}){await y({config:e,document:Bu,variables:{reason:t,runId:r}})}var No=new Map;function _u(e){let t=`${e.ripploServerUrl}::${e.token}`,r=No.get(t);if(r!=null)return r;let n={artifactsUploaded:new it.default(async o=>(await Mt({config:e,document:Mu,opName:"markRunArtifactsUploadedBatch",size:o.length,variables:{runIds:[...o]}}),o.map(()=>!0)),{cache:!1}),complete:new it.default(async o=>(await Mt({config:e,document:zu,opName:"completeRunsBatch",size:o.length,variables:{items:[...o]}}),o.map(()=>!0)),{cache:!1}),start:new it.default(async o=>(await Mt({config:e,document:Hu,opName:"startRunsBatch",size:o.length,variables:{runIds:[...o]}}),o.map(()=>!0)),{cache:!1,batchScheduleFn:o=>{setTimeout(o,200)}}),steps:new it.default(async o=>(await Mt({config:e,document:Wu,opName:"submitRunStepsBatch",size:o.length,variables:{items:Uu(o)}}),o.map(()=>!0)),{cache:!1,batchScheduleFn:o=>{setTimeout(o,200)}})};return No.set(t,n),n}async function Mt({config:e,document:t,opName:r,size:n,variables:o}){let i=performance.now();await y({config:e,document:t,variables:o}),f.debug({batchSize:n,elapsedMs:Math.round(performance.now()-i),op:r},"batched op flushed")}function Uu(e){let t=new Map;return e.forEach(({runId:r,step:n})=>{let o=Vu(n),i=t.get(r);if(i==null){t.set(r,[o]);return}i.push(o)}),[...t.entries()].map(([r,n])=>({runId:r,steps:n}))}function Vu(e){return{assertions:e.assertions.map(t=>({description:t.description,detail:t.detail??null,status:t.status})),detail:e.detail??null,duration:e.duration,nodeType:e.nodeType,recordingEndMs:e.recordingEndMs??null,recordingStartMs:e.recordingStartMs??null,snapshotTimestamp:e.snapshotTimestamp,status:e.status,stepIndex:e.stepIndex,title:e.title,url:e.url}}async function Fu({chunk:e,config:t,runId:r}){await y({config:t,document:qu,variables:{input:{bodyBase64:e.body.toString("base64"),chunkIndex:e.chunkIndex,endTimestamp:e.endTimestamp,eventCount:e.eventCount,runId:r,startTimestamp:e.startTimestamp}}})}var Mu=Ve(`
|
|
111
|
+
Load \`/ripplo:create\` skill for instructions.`,status:"failed"}:(n.lastReason=t.reason,null)}async function su({apiUrl:e,observer:t,params:r,webhookSecret:n}){let o=JSON.stringify({observer:t,params:r});try{let i=await fetch(`${e}/execute-observer`,{body:o,headers:{"Content-Type":"application/json",...ve({body:o,secret:n})},method:"PUT",signal:AbortSignal.timeout(tu)});if(!i.ok){let l=await i.text().catch(()=>"");return{kind:"transport-error",reason:`status ${String(i.status)}: ${l.slice(0,200)}`}}let s=await i.json(),a=ou.safeParse(s);return a.success?!a.data.success||a.data.outcome==null?{kind:"transport-error",reason:a.data.error??"engine reported failure without outcome"}:a.data.outcome:{kind:"transport-error",reason:`invalid response shape: ${a.error.message}`}}catch(i){let s=i instanceof Error?i.message:String(i);return f.error("observer request failed: %s",s),{kind:"transport-error",reason:s}}}function au({backoff:e,pollCount:t}){let r=Math.min(t-1,e.length-1);return e[r]??1e3}function $o(e){return`${String(Math.round(performance.now()-e))}ms`}async function lu(e){return new Promise(t=>setTimeout(t,e))}var Vt=15e3;async function Hr({failFast:e,getRecordingOffsetMs:t,observerTransport:r,onStep:n,page:o,spec:i,variables:s}){let a=performance.now();return uu({currentId:i.entryNode,failFast:e,getRecordingOffsetMs:t,observerTransport:r,onStep:n,page:o,runStartTime:a,spec:i,variables:s})}function cu({onStep:e,steps:t,target:r}){t.forEach(n=>{let o={...n,stepIndex:r.length};r.push(o),e?.(o)})}async function uu({currentId:e,failFast:t,getRecordingOffsetMs:r,observerTransport:n,onStep:o,page:i,runStartTime:s,spec:a,variables:l}){let c=[],p=l,m=e;for(;m!=null;){let h=a.nodes[m];if(h==null)throw new Error(`Node "${m}" not found in spec`);let T=m,$=_t(h);f.info("Executing node: %s [%s]",$,h.type);let g=await du({getRecordingOffsetMs:r,node:h,nodeId:T,observerTransport:n,page:i,runStartTime:s,variables:p});if(cu({onStep:o,steps:[g],target:c}),p=g.variables,t&&g.status==="failed")break;m=h.next}return{steps:c,variables:p}}async function du({getRecordingOffsetMs:e,node:t,nodeId:r,observerTransport:n,page:o,runStartTime:i,variables:s}){let a=performance.now(),l=e?.(),c=_t(t),p=Vt;try{let m=await pu({node:t,observerTransport:n,page:o,timeout:p,variables:s}),h=Math.round(performance.now()-a),T=m.assertions.some(g=>g.status==="failed"),$=e?.();return{assertions:m.assertions,detail:void 0,duration:h,nodeId:r,nodeType:t.type,recordingEndMs:$,recordingStartMs:l,snapshotTimestamp:Math.round(performance.now()-i),status:T?"failed":"passed",stepIndex:0,title:c,url:o.url(),variables:m.variables}}catch(m){let h=Math.round(performance.now()-a),T=m instanceof Error?m.message:String(m),$=e?.();return{assertions:[],detail:T,duration:h,nodeId:r,nodeType:t.type,recordingEndMs:$,recordingStartMs:l,snapshotTimestamp:Math.round(performance.now()-i),status:"failed",stepIndex:0,title:c,url:o.url(),variables:s}}}async function pu({node:e,observerTransport:t,page:r,timeout:n,variables:o}){if(mu(e)){let s=await kr({node:e,page:r,timeout:n,variables:o});return{assertions:[],variables:s.variables}}return{assertions:await gu({node:e,observerTransport:t,page:r,timeout:n,variables:o}),variables:o}}function mu(e){return["goto","click","dblclick","fill","select","hover","press","check","uncheck","clear","rightClick","handleDialog","clipboard","setPermission","setViewport","fail","setVariable","extractText","upload","drag","scrollIntoView","type","focus"].includes(e.type)}function fu(e){return e.type.startsWith("assert")}async function gu({node:e,observerTransport:t,page:r,timeout:n,variables:o}){if(!fu(e))throw new Error(`Unknown node type: ${e.type}`);let i=e;switch(i.type){case"assertVisible":case"assertNotVisible":case"assertEnabled":case"assertDisabled":case"assertChecked":case"assertNotChecked":case"assertFocused":case"assertNotFocused":return hu({assertNode:i,page:r,timeout:n,variables:o});case"assertText":{let s=Y({ref:i.expected,variables:o});return[await Rr({expected:s,locator:U({locator:i.locator,page:r,variables:o}),operator:i.operator,timeout:n})]}case"assertUrl":{let s=Y({ref:i.expected,variables:o});return[await Pr({expected:s,operator:i.operator,page:r,timeout:n})]}case"assertTitle":{let s=Y({ref:i.expected,variables:o});return[await zn({expected:s,operator:i.operator,page:r,timeout:n})]}case"assertCount":{let s=Sr({ref:i.expected,variables:o});return[await xr({expected:s,locator:U({locator:i.locator,page:r,variables:o}),operator:i.operator,timeout:n})]}case"assertValue":{let s=Y({ref:i.expected,variables:o});return[await Er({expected:s,locator:U({locator:i.locator,page:r,variables:o}),operator:i.operator,timeout:n})]}case"assertAttribute":{let s=Y({ref:i.expected,variables:o});return[await Gn({attribute:i.attribute,expected:s,locator:U({locator:i.locator,page:r,variables:o}),operator:i.operator,timeout:n})]}case"assertObserver":{if(t==null)return[{description:`observer "${i.observer}"`,detail:"observer transport not configured \u2014 set engineUrl + webhookSecret in ripplo.config",status:"failed"}];let s={};return Object.entries(i.params).forEach(([a,l])=>{s[a]=Rt({ref:l,variables:o})}),[await Io({apiUrl:t.apiUrl,budget:i.budget,observer:i.observer,params:s,webhookSecret:t.webhookSecret})]}}}var yu={assertChecked:Yn,assertDisabled:Jn,assertEnabled:Kn,assertFocused:Qn,assertNotChecked:Xn,assertNotFocused:Zn,assertNotVisible:Tr,assertVisible:Cr};async function hu({assertNode:e,page:t,timeout:r,variables:n}){let o=yu[e.type];return[await o({locator:U({locator:e.locator,page:t,variables:n}),timeout:r})]}var wu=5e3,bu=2e3;async function Wr({abort:e,baseUrl:t,browser:r,cookies:n,extraVariables:o,observerTransport:i,onRecordingChunk:s,onStep:a,runId:l,spec:c}){let p=await r.newContext({baseURL:t});e.attachContext(p),p.setDefaultTimeout(Vt),p.setDefaultNavigationTimeout(Vt),n.length>0&&await p.addCookies(n);let m=await p.newPage(),h=await To(m);async function T(){let j=await h.takeChunk();j!=null&&s?.(j)}let $=setInterval(()=>{T().catch(j=>{let W=j instanceof Error?j.message:String(j);f.warn("rrweb chunk flush failed: %s",W)})},2e3),g=[],H=!1;function x(j){a?.(j),H||(H=!0,h.start().catch(W=>{let ge=W instanceof Error?W.message:String(W);f.warn("rrweb recorder start failed: %s",ge)})),g.push(Po({context:p,page:m,runId:l,stepIndex:j.stepIndex,stepResult:j}))}let F=vu(o,c.variableNamespaces),Ae={...vr({defs:c.variables}),...F};try{let j=await Hr({failFast:!0,getRecordingOffsetMs:h.currentOffsetMs,observerTransport:i,onStep:x,page:m,spec:c,variables:Ae});clearInterval($);let W=j.steps.filter(L=>L.status==="passed").length,ge=j.steps.filter(L=>L.status==="failed").length,pr={duration:j.steps.reduce((L,et)=>L+et.duration,0),failCount:ge,passCount:W,runId:l,status:ge>0?"failed":"passed",workflowName:""};return await ye(Promise.allSettled([Promise.allSettled(g).then(()=>xo({runId:l,steps:j.steps,summary:pr})),h.detach().then(T).catch(L=>{let et=L instanceof Error?L.message:String(L);f.warn("Recorder detach failed: %s",et)})]),wu,"post-run cleanup").catch(L=>{let et=L instanceof Error?L.message:String(L);f.warn("Post-run cleanup did not finish in budget: %s",et)}),j.steps}finally{clearInterval($),await ye(p.close(),bu,"context.close").catch(j=>{let W=j instanceof Error?j.message:String(j);f.warn("Context close failed: %s",W)})}}function vu(e,t){if(e==null||t==null)return{};let r=new Map;Object.entries(t).forEach(([o,i])=>{r.set(i,o)});let n={};return Object.entries(e).forEach(([o,i])=>{let s=r.get(o);s!=null&&(n[s]={...n[s],...i})}),n}async function de({fn:e,label:t}){let r=performance.now(),n=await e();return f.debug("%s: %dms",t,Math.round(performance.now()-r)),n}var Gr=yr(Et(),1);import{z as S}from"zod";var Su=S.union([S.string(),S.number(),S.boolean()]),ku=S.record(S.string(),S.record(S.string(),Su)),Ru=S.object({domain:S.string().optional(),expires:S.number().optional(),httpOnly:S.boolean().optional(),name:S.string(),path:S.string().optional(),sameSite:S.enum(["lax","none","strict"]).optional(),secure:S.boolean().optional(),value:S.string()}),Pu=S.discriminatedUnion("ok",[S.object({cookies:S.array(Ru),data:ku,executed:S.array(S.string()),ok:S.literal(!0),runId:S.string()}),S.object({error:S.string(),ok:S.literal(!1),runId:S.string()})]),xu=S.object({results:S.array(Pu)}),Eu=S.object({results:S.array(S.object({error:S.string().optional(),ok:S.boolean(),runId:S.string()}))}),jo=3e4;async function Kr({apiUrl:e,data:t,executed:r,runId:n,webhookSecret:o}){if(r.length!==0)try{await Iu({apiUrl:e,webhookSecret:o}).load({data:t,preconditions:r,runId:n})}catch(i){let s=i instanceof Error?i.message:String(i);f.error("Teardown request failed: %s",s)}}async function Ft({engineBaseUrl:e,preconditionNames:t,runId:r,webhookSecret:n}){let o=e.length===0?void 0:e;return o==null||t.length===0?{apiUrl:o,cookies:[],data:{},executed:[]}:Cu({apiUrl:o,preconditionNames:t,runId:r,webhookSecret:n})}async function Cu({apiUrl:e,preconditionNames:t,runId:r,webhookSecret:n}){return{...await Tu({apiUrl:e,webhookSecret:n}).load({preconditionNames:t,runId:r}),apiUrl:e}}function Jr(){qr.clear(),zr.clear()}var qr=new Map;function Tu({apiUrl:e,webhookSecret:t}){let r=`${e}::${t}`,n=qr.get(r);if(n!=null)return n;let o=new Gr.default(i=>Au({apiUrl:e,keys:i,webhookSecret:t}),{cache:!1,batchScheduleFn:i=>{setTimeout(i,200)},cacheKeyFn:i=>i.runId});return qr.set(r,o),o}async function Au({apiUrl:e,keys:t,webhookSecret:r}){let n=performance.now(),o=JSON.stringify({batch:t.map(p=>({preconditions:[...p.preconditionNames],runId:p.runId}))}),i=await fetch(`${e}/execute-preconditions`,{body:o,headers:{"Content-Type":"application/json",...ve({body:o,secret:r})},method:"PUT",signal:AbortSignal.timeout(jo)});if(!i.ok){let p=await Nu(i),m=new Error(`execute-preconditions returned ${String(i.status)}: ${p}`);return t.map(()=>m)}let s=await i.json(),a=xu.safeParse(s);if(!a.success){let p=new Error(`execute-preconditions response has invalid shape: ${a.error.message}`);return t.map(()=>p)}let l=new URL(e).hostname,c=new Map(a.data.results.map(p=>[p.runId,p]));return f.debug({batchSize:t.length,elapsedMs:Math.round(performance.now()-n),op:"execute-preconditions"},"batched op flushed"),t.map(p=>{let m=c.get(p.runId);return m==null?new Error(`execute-preconditions response missing runId ${p.runId}`):m.ok?(f.info("Preconditions resolved: %s",m.executed.join(", ")),{cookies:m.cookies.map(h=>Lu({cookie:h,domain:l})),data:m.data,executed:m.executed}):new Error(`Precondition batch failed: ${m.error}`)})}var zr=new Map;function Iu({apiUrl:e,webhookSecret:t}){let r=`${e}::${t}`,n=zr.get(r);if(n!=null)return n;let o=new Gr.default(i=>$u({apiUrl:e,keys:i,webhookSecret:t}),{cache:!1,batchScheduleFn:i=>{setTimeout(i,200)},cacheKeyFn:i=>i.runId});return zr.set(r,o),o}async function $u({apiUrl:e,keys:t,webhookSecret:r}){let n=JSON.stringify({batch:t.map(l=>({data:l.data,preconditions:[...l.preconditions],runId:l.runId}))}),o=await fetch(`${e}/teardown-preconditions`,{body:n,headers:{"Content-Type":"application/json",...ve({body:n,secret:r})},method:"PUT",signal:AbortSignal.timeout(jo)});if(!o.ok){let l=new Error(`teardown-preconditions returned ${String(o.status)}`);return t.map(()=>l)}let i=await o.json(),s=Eu.safeParse(i);if(!s.success){let l=new Error(`teardown-preconditions response has invalid shape: ${s.error.message}`);return t.map(()=>l)}let a=new Map(s.data.results.map(l=>[l.runId,l]));return t.map(l=>{let c=a.get(l.runId);if(c==null)return new Error(`teardown-preconditions response missing runId ${l.runId}`);if(!c.ok)return new Error(`Teardown failed: ${c.error??"unknown error"}`)})}var ju=S.object({error:S.string()});async function Nu(e){let t=await e.text().catch(()=>"");if(t.length===0)return"no body";let r=Ou(t),n=r==null?null:ju.safeParse(r);return n!=null&&n.success?n.data.error:t.slice(0,500)}function Ou(e){try{return JSON.parse(e)}catch{return null}}var Du={lax:"Lax",none:"None",strict:"Strict"};function Lu({cookie:e,domain:t}){let r={domain:e.domain??t,httpOnly:e.httpOnly??!1,name:e.name,path:e.path??"/",secure:e.secure??!1,value:e.value};return e.sameSite!=null&&(r.sameSite=Du[e.sameSite]??"Lax"),e.expires!=null&&(r.expires=e.expires),r}var it=yr(Et(),1);import{graphql as Ve}from"gql.tada";async function Yr({config:e,runId:t}){let r=_u(e);await r.start.load(t);let n=[];function o(c){return n.push(c.catch(()=>{})),c}function i(c){o(r.steps.load({runId:t,step:c})).catch(p=>{f.error(p,"submitRunSteps failed")})}function s(c){o(Fu({chunk:c,config:e,runId:t})).catch(p=>{f.error(p,"submitRunRecordingChunk failed")})}async function a(){for(;n.length>0;){let c=n.splice(0);await Promise.all(c)}}async function l({flush:c,statusOverride:p,steps:m,summary:h}){c&&await de({label:"flushSteps",fn:()=>a()});let T=m.filter(x=>x.status==="passed").length,$=m.filter(x=>x.status==="failed").length,g=m.reduce((x,F)=>x+F.duration,0),H=p??($>0?"failed":"passed");await de({label:"completeRun",fn:()=>r.complete.load({duration:g,failCount:$,passCount:T,runId:t,status:H,summary:h??null,warnCount:0})})}return{complete:l,enqueueRecordingChunk:s,enqueueStep:i,flushSteps:a,runId:t}}async function Xr({config:e,reason:t,runId:r}){await y({config:e,document:Bu,variables:{reason:t,runId:r}})}var No=new Map;function _u(e){let t=`${e.ripploServerUrl}::${e.token}`,r=No.get(t);if(r!=null)return r;let n={artifactsUploaded:new it.default(async o=>(await Mt({config:e,document:Mu,opName:"markRunArtifactsUploadedBatch",size:o.length,variables:{runIds:[...o]}}),o.map(()=>!0)),{cache:!1}),complete:new it.default(async o=>(await Mt({config:e,document:zu,opName:"completeRunsBatch",size:o.length,variables:{items:[...o]}}),o.map(()=>!0)),{cache:!1}),start:new it.default(async o=>(await Mt({config:e,document:Hu,opName:"startRunsBatch",size:o.length,variables:{runIds:[...o]}}),o.map(()=>!0)),{cache:!1,batchScheduleFn:o=>{setTimeout(o,200)}}),steps:new it.default(async o=>(await Mt({config:e,document:Wu,opName:"submitRunStepsBatch",size:o.length,variables:{items:Uu(o)}}),o.map(()=>!0)),{cache:!1,batchScheduleFn:o=>{setTimeout(o,200)}})};return No.set(t,n),n}async function Mt({config:e,document:t,opName:r,size:n,variables:o}){let i=performance.now();await y({config:e,document:t,variables:o}),f.debug({batchSize:n,elapsedMs:Math.round(performance.now()-i),op:r},"batched op flushed")}function Uu(e){let t=new Map;return e.forEach(({runId:r,step:n})=>{let o=Vu(n),i=t.get(r);if(i==null){t.set(r,[o]);return}i.push(o)}),[...t.entries()].map(([r,n])=>({runId:r,steps:n}))}function Vu(e){return{assertions:e.assertions.map(t=>({description:t.description,detail:t.detail??null,status:t.status})),detail:e.detail??null,duration:e.duration,nodeType:e.nodeType,recordingEndMs:e.recordingEndMs??null,recordingStartMs:e.recordingStartMs??null,snapshotTimestamp:e.snapshotTimestamp,status:e.status,stepIndex:e.stepIndex,title:e.title,url:e.url}}async function Fu({chunk:e,config:t,runId:r}){await y({config:t,document:qu,variables:{input:{bodyBase64:e.body.toString("base64"),chunkIndex:e.chunkIndex,endTimestamp:e.endTimestamp,eventCount:e.eventCount,runId:r,startTimestamp:e.startTimestamp}}})}var Mu=Ve(`
|
|
112
112
|
mutation MarkRunArtifactsUploadedBatchCLI($runIds: [String!]!) {
|
|
113
113
|
markRunArtifactsUploadedBatch(runIds: $runIds)
|
|
114
114
|
}
|
|
@@ -164,7 +164,7 @@ Load \`/ripplo:create\` skill for instructions.`,status:"failed"}:(n.lastReason=
|
|
|
164
164
|
}
|
|
165
165
|
`,[_o]);async function Qr({baseUrl:e,browser:t,config:r,headed:n,preconditionNames:o,runId:i,webhookSecret:s}){let a="unknown",l,c,p=!1,m=ko(),h=performance.now();try{p=t==null,c=Qu({externalBrowser:t,headed:n});let T=o==null?void 0:Ft({engineBaseUrl:r.engineUrl,preconditionNames:o,runId:i,webhookSecret:s}),[{engineBaseUrl:$,workflow:g},H]=await Promise.all([de({label:"Run context resolved",fn:()=>od({config:r,runId:i})}),de({label:"Streaming run started",fn:()=>Yr({config:r,runId:i})}),$r({appUrl:e})]);a=g.name,l=H;let x=id(g.spec);f.info("Executing workflow: %s",g.name),await ld(ed({abort:m,baseUrl:e,browserPromise:c,engineBaseUrl:$,preconditionPromise:T,runId:i,specData:x,streaming:l,webhookSecret:s,workflow:g}),ad(),m)}catch(T){throw cd(T)?T:(await ye(Zu({browserPromise:c,config:r,error:T,ownsBrowser:p,runId:i,streaming:l,workflowName:a}),Yu,"post-deadline cleanup").catch($=>{let g=$ instanceof Error?$.message:String($);f.warn("Post-deadline cleanup did not finish in budget: %s",g)}),new Bt(T))}finally{f.debug({elapsedMs:Math.round(performance.now()-h),runId:i},"run finished (totalMs=%d)",Math.round(performance.now()-h))}}var Bt=class extends Error{cause;constructor(t){let r=t instanceof Error?t.message:String(t);super(r),this.name="RunReportedError",this.cause=t}};function Qu({externalBrowser:e,headed:t}){return e!=null?Promise.resolve(e):de({label:"Browser launched",fn:()=>Le({headed:t})})}async function Zu({browserPromise:e,config:t,error:r,ownsBrowser:n,runId:o,streaming:i,workflowName:s}){let a=r instanceof Error?r.message:String(r),l=r instanceof Error?r.stack:void 0;await Eo({error:a,runId:o,stack:l,workflowName:s}),i==null?await Xr({config:t,reason:a,runId:o}).catch(()=>{}):await i.complete({flush:!1,statusOverride:"failed",steps:[],summary:a}).catch(()=>{}),n&&e!=null&&await(await e.catch(()=>{}))?.close()}async function ed({abort:e,baseUrl:t,browserPromise:r,engineBaseUrl:n,preconditionPromise:o,runId:i,specData:s,streaming:a,webhookSecret:l,workflow:c}){let p=o??Ft({engineBaseUrl:n,preconditionNames:c.preconditions,runId:i,webhookSecret:l}),[m,h]=await Promise.all([p,r]);await td({abort:e,baseUrl:t,browser:h,preconditionResult:m,runId:i,specData:s,streaming:a,webhookSecret:l})}async function td({abort:e,baseUrl:t,browser:r,preconditionResult:n,runId:o,specData:i,streaming:s,webhookSecret:a}){let l=await de({label:"Spec executed",fn:()=>Wr({abort:e,baseUrl:t,browser:r,cookies:n.cookies,extraVariables:n.data,observerTransport:n.apiUrl==null?void 0:{apiUrl:n.apiUrl,webhookSecret:a},onRecordingChunk:s.enqueueRecordingChunk,onStep:s.enqueueStep,runId:o,spec:i})});await nd({preconditionResult:n,runId:o,webhookSecret:a}),await s.complete({flush:!0,statusOverride:void 0,steps:l,summary:rd(l)});let c=l.filter(m=>m.status==="passed").length,p=l.filter(m=>m.status==="failed").length;f.info("Run complete: %d passed, %d failed",c,p)}function rd(e){let t=e.find(o=>o.status==="failed");if(t==null)return;let n=t.assertions.find(o=>o.status==="failed")?.detail??t.detail;return n==null||n.length===0?t.title:`${t.title} \u2014 ${n}`}async function nd({preconditionResult:e,runId:t,webhookSecret:r}){e.apiUrl!=null&&await Kr({apiUrl:e.apiUrl,data:e.data,executed:e.executed,runId:t,webhookSecret:r})}async function od({config:e,runId:t}){let r=await ud(e).load(t);if(r.workflow==null)throw new Error(`Run ${t} not found`);let n=Ku(_o,r.workflow),o=r.workflow.project?.engineBaseUrl??"";return{engineBaseUrl:e.engineUrl.length>0?e.engineUrl:o,workflow:n}}function id(e){if(e==null)throw new Error("Workflow has no spec");return Vr.decode(e)}var sd=Gu.coerce.number().int().positive().catch(Ju);function ad(){return sd.parse(process.env.RIPPLO_RUN_TIMEOUT_MS)}async function ld(e,t,r){let n,o=new Promise((i,s)=>{n=setTimeout(()=>{r.fire(),s(new Error(`Run timed out after ${String(t)}ms`))},t)});try{await Promise.race([e,o])}finally{n!=null&&clearTimeout(n)}}function cd(e){return e instanceof _e?e.errors.some(t=>t.extensions?.code==="THROTTLED"):!1}var Oo=new Map;function ud(e){let t=`${e.ripploServerUrl}::${e.token}`,r=Oo.get(t);if(r!=null)return r;let n=new Do.default(async o=>{let i=performance.now(),s=await y({config:e,document:Xu,variables:{ids:[...o]}}),a=new Map(s.runsByIds?.map(l=>[l.id,l])??[]);return f.debug({batchSize:o.length,elapsedMs:Math.round(performance.now()-i),op:"runsByIds"},"batched op flushed"),o.map(l=>a.get(l)??new Error(`Run ${l} not found`))},{cache:!1,batchScheduleFn:o=>{setTimeout(o,200)}});return Oo.set(t,n),n}import ct from"fs";import $e from"fs";import dd from"os";import st from"path";var pd=".local",md=".ripplo";function Zr(e){return st.join(e,".ripplo",pd)}function at(e){let t=Zr(e);$e.existsSync(t)||$e.mkdirSync(t,{recursive:!0});let r=st.join(t,".gitignore");return $e.existsSync(r)||$e.writeFileSync(r,`*
|
|
166
166
|
`),t}function lt(e,t){return st.join(Zr(e),t)}function en(){return st.join(dd.homedir(),md)}function tn(){let e=en();return $e.existsSync(e)?$e.chmodSync(e,448):$e.mkdirSync(e,{mode:448,recursive:!0}),e}function Se(e){return st.join(en(),e)}function ie(){let e=process.env.RIPPLO_TOKEN;if(e!=null&&e.trim().length>0)return e.trim();let t=Se("token");if(!ct.existsSync(t))return null;let r=ct.readFileSync(t,"utf8").trim();return r.length===0?null:r}function rn(e){tn(),ct.writeFileSync(Se("token"),e+`
|
|
167
|
-
`,{mode:384})}function nn(){let e=Se("token");return ct.existsSync(e)?(ct.unlinkSync(e),!0):!1}import{graphql as ut}from"gql.tada";var
|
|
167
|
+
`,{mode:384})}function nn(){let e=Se("token");return ct.existsSync(e)?(ct.unlinkSync(e),!0):!1}import{graphql as ut}from"gql.tada";var FS=ut(`
|
|
168
168
|
query AgentReviewContextWorker($reviewId: String!) {
|
|
169
169
|
agentReview(id: $reviewId) {
|
|
170
170
|
id
|
|
@@ -178,11 +178,11 @@ Load \`/ripplo:create\` skill for instructions.`,status:"failed"}:(n.lastReason=
|
|
|
178
178
|
}
|
|
179
179
|
}
|
|
180
180
|
}
|
|
181
|
-
`);var
|
|
181
|
+
`);var MS=ut(`
|
|
182
182
|
mutation StartAgentReviewWorker($reviewId: String!) {
|
|
183
183
|
startAgentReview(reviewId: $reviewId)
|
|
184
184
|
}
|
|
185
|
-
`);var
|
|
185
|
+
`);var BS=ut(`
|
|
186
186
|
mutation CompleteAgentReviewWorker(
|
|
187
187
|
$reviewId: String!
|
|
188
188
|
$markdown: String!
|
|
@@ -196,11 +196,11 @@ Load \`/ripplo:create\` skill for instructions.`,status:"failed"}:(n.lastReason=
|
|
|
196
196
|
comments: $comments
|
|
197
197
|
)
|
|
198
198
|
}
|
|
199
|
-
`);var
|
|
199
|
+
`);var HS=ut(`
|
|
200
200
|
mutation UpdateAgentReviewProgressWorker($reviewId: String!, $text: String!) {
|
|
201
201
|
updateAgentReviewProgress(reviewId: $reviewId, text: $text)
|
|
202
202
|
}
|
|
203
|
-
`);var
|
|
203
|
+
`);var WS=ut(`
|
|
204
204
|
mutation FailAgentReviewWorker($reviewId: String!, $reason: String!) {
|
|
205
205
|
failAgentReview(reviewId: $reviewId, reason: $reason)
|
|
206
206
|
}
|
|
@@ -214,7 +214,7 @@ ${o}
|
|
|
214
214
|
If you're in a git worktree, the env file may not have been copied from the main checkout \u2014 recreate it (or symlink to a shared file outside the working tree).`:"";throw new Error(`ripplo: env config invalid:
|
|
215
215
|
${r}
|
|
216
216
|
|
|
217
|
-
Add missing values to the env file(s) declared in .ripplo/project.json.${i}`)}let t=e.data;return{appUrl:t.RIPPLO_APP_URL,engineUrl:t.RIPPLO_ENGINE_URL,webhookSecret:t.RIPPLO_WEBHOOK_SECRET}}function dn(e){let r=cn(e)?.envFiles??[],n=qt.join(e,".ripplo");return r.map(o=>qt.resolve(n,o)).filter(o=>!Fo.existsSync(o))}import
|
|
217
|
+
Add missing values to the env file(s) declared in .ripplo/project.json.${i}`)}let t=e.data;return{appUrl:t.RIPPLO_APP_URL,engineUrl:t.RIPPLO_ENGINE_URL,webhookSecret:t.RIPPLO_WEBHOOK_SECRET}}function dn(e){let r=cn(e)?.envFiles??[],n=qt.join(e,".ripplo");return r.map(o=>qt.resolve(n,o)).filter(o=>!Fo.existsSync(o))}import dw from"yargs";import{hideBin as pw}from"yargs/helpers";import{graphql as Nd}from"gql.tada";import{exec as Rd}from"child_process";import{createAuthClient as bd}from"better-auth/client";import{deviceAuthorizationClient as vd}from"better-auth/client/plugins";function Bo({baseURL:e}){return bd({baseURL:e,fetchOptions:{headers:{"User-Agent":"Ripplo CLI"}},plugins:[vd()]})}import{z as pn}from"zod";var Sd="https://ripplo.ai";function Z(){return zt().RIPPLO_SERVER_URL}function Wo(){return zt().RIPPLO_PROJECT_ID}var kd=pn.object({RIPPLO_PROJECT_ID:pn.string().min(1).optional(),RIPPLO_SERVER_URL:pn.string().min(1).default(Sd)}),Ho;function zt(){return Ho??=kd.parse(process.env),Ho}var Pd=5e3,qo="ripplo-cli";async function zo({onDeviceCode:e,url:t}){let r=t??zt().RIPPLO_SERVER_URL,n=Bo({baseURL:r}),o=await n.device.code({client_id:qo});if(o.error!=null)throw new Error(`Failed to request device code: ${o.error.error_description}`);let{device_code:i,user_code:s,verification_uri_complete:a}=o.data;e({userCode:s,verificationUrl:a}),Id(a);let l=await xd({authClient:n,deviceCode:i});return rn(l),l}async function xd({authClient:e,deviceCode:t}){for(;;){await Td(Pd);let r=await e.device.token({client_id:qo,device_code:t,grant_type:"urn:ietf:params:oauth:grant-type:device_code"});if(r.data?.access_token!=null)return r.data.access_token;if(r.error==null)continue;if(!Cd(r.error.error))throw new Error(`Authorization failed: ${r.error.error_description}`)}}var Ed=new Set(["authorization_pending","slow_down"]);function Cd(e){return Ed.has(e)}function Td(e){return new Promise(t=>{setTimeout(t,e)})}function Ad(){return process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open"}function Id(e){let t=Ad();Rd(`${t} "${e}"`,()=>{})}function ke({serverUrl:e,token:t}){return{appUrl:"",cwd:process.cwd(),engineUrl:"",projectId:"",ripploServerUrl:e,token:t,webhookSecret:""}}import $d from"fs";import jd from"path";function A(e){return $d.existsSync(jd.join(e,".ripplo"))}var Od=Nd(`
|
|
218
218
|
query AuthViewer {
|
|
219
219
|
currentUser {
|
|
220
220
|
name
|
|
@@ -229,15 +229,15 @@ Add missing values to the env file(s) declared in .ripplo/project.json.${i}`)}le
|
|
|
229
229
|
`),process.stdout.write(`Verification code: ${s.userCode}
|
|
230
230
|
|
|
231
231
|
`),process.stdout.write(`Waiting for you to approve...
|
|
232
|
-
`)}}),n=await mn({serverUrl:e,token:r}),o=
|
|
232
|
+
`)}}),n=await mn({serverUrl:e,token:r}),o=A(process.cwd()),i=o?"Welcome back":"Welcome to Ripplo";process.stdout.write(`
|
|
233
233
|
`),process.stdout.write(n==null?`${i}.
|
|
234
234
|
`:`${i}, ${Dd(n)}.
|
|
235
235
|
`),process.stdout.write(`Session saved to ${Se("token")}.
|
|
236
236
|
`),o||(process.stdout.write("\nNext: run `/ripplo:setup` in Claude Code to wire Ripplo into this project,\n"),process.stdout.write("or `npx ripplo init` to set it up by hand.\n"))}function Dd(e){let t=e.name.trim().split(/\s+/)[0];return t!=null&&t.length>0?t:e.email}async function mn({serverUrl:e,token:t}){try{let n=(await y({config:ke({serverUrl:e,token:t}),document:Od,variables:void 0})).currentUser;return n==null?null:{email:n.email,name:n.name}}catch{return null}}async function Ko(){let e=ie();e==null&&(process.stdout.write("Not authenticated. Run `ripplo auth login`.\n"),process.exit(1));let t=Z(),r=await mn({serverUrl:t,token:e});r==null&&(process.stdout.write("Token rejected. Run `ripplo auth login` to re-authenticate.\n"),process.exit(1)),process.stdout.write(`Authenticated as ${r.name} <${r.email}> (${t})
|
|
237
237
|
`)}function Jo(){if(!nn()){process.stdout.write(`No token to remove.
|
|
238
238
|
`);return}process.stdout.write(`Removed ${Se("token")}
|
|
239
|
-
`)}import{createHash as Ld}from"crypto";import pt from"fs/promises";import Be from"path";import{z as Gt}from"zod";import{z as Yo}from"zod";import{z as Me}from"zod";import{z as d}from"zod";import{z as Re}from"zod";import{z as ri}from"zod";import{z as O}from"zod";import{z as ee}from"zod";import{z as fn}from"zod";import{z as E}from"zod";var _d=Gt.object({__codec:Gt.string().min(1),data:Gt.unknown(),version:Gt.number().int().positive()}),Ud=class extends Error{codec;currentVersion;gotVersion;constructor(e){super(`Unsupported ${e.codec} version ${String(e.gotVersion)} (current ${String(e.currentVersion)}). Upgrade Ripplo or rebuild with a compatible CLI.`),this.name="CodecVersionError",this.codec=e.codec,this.currentVersion=e.currentVersion,this.gotVersion=e.gotVersion}},Vd=class extends Error{constructor(e){super(`Codec mismatch: expected "${e.expected}", got "${e.got}"`),this.name="CodecMismatchError"}};function hn(e){return ei({legacy:void 0,migrators:[],name:e,schemas:[]})}function Fd(e,t){let r=JSON.parse(t);return e.decode(r)}function ei(e){return{initial:t=>gn(t,{...e,schemas:[t]}),legacy:t=>ei({...e,legacy:t})}}function gn(e,t){return{build:()=>Md(e,t),legacy:r=>gn(e,{...t,legacy:r}),upgrade:(r,n)=>{let o=n;return gn(r,{...t,migrators:[...t.migrators,o],schemas:[...t.schemas,r]})}}}function Md(e,t){let r=t.schemas.length;return{currentVersion:r,name:t.name,decode:n=>Bd(e,t,n),encode:n=>({__codec:t.name,data:n,version:r})}}function Bd(e,t,r){let{data:n,version:o}=Hd(t,r),i=ti(t,n,o);return e.parse(i)}function Hd(e,t){let r=_d.safeParse(t);if(r.success){if(r.data.__codec!==e.name)throw new Vd({expected:e.name,got:r.data.__codec});return{data:r.data.data,version:r.data.version}}if(e.legacy!=null&&e.legacy.detect(t))return{data:t,version:e.legacy.assumedVersion};throw new Error(`Cannot decode "${e.name}": value is not a codec envelope and no legacy detector matched.`)}function ti(e,t,r){let n=e.schemas.length;if(r>n)throw new Ud({codec:e.name,currentVersion:n,gotVersion:r});if(r===n)return t;let o=e.schemas[r-1];if(o==null)throw new Error(`Codec "${e.name}" missing schema for v${String(r)}; cannot migrate.`);let i=o.parse(t),s=e.migrators[r-1];if(s==null)throw new Error(`Codec "${e.name}" missing migrator v${String(r)} \u2192 v${String(r+1)}.`);return ti(e,s(i),r+1)}var wn=Me.object({depends:Me.array(Me.string().min(1)).optional().describe("Names of other preconditions that must be satisfied first. Resolved via topological sort; cycles are rejected at validation time."),description:Me.string().min(1).describe("Human-readable description of what this precondition ensures"),returns:Me.array(Me.string().min(1)).optional().describe("Keys that the execute response's data field will contain. e.g. ['projectId', 'workflowId']. These are used for route param interpolation ({{projectId}}) and workflow variables. Declared here so generated types are strongly typed per precondition.")}).describe("A named precondition declared at the graph level. States reference these by name."),Wd=Re.object({by:Re.literal("testId"),value:Re.string().min(1)}),qd=Re.object({by:Re.literal("role"),name:Re.string().optional(),role:Re.string().min(1)}),C=Re.discriminatedUnion("by",[Wd,qd]),mt=ri.enum(["equals","notEquals","contains","startsWith","endsWith","matches"]),zd=ri.enum(["equals","notEquals","greaterThan","greaterThanOrEqual","lessThan","lessThanOrEqual"]),Gd=O.object({type:O.literal("static"),value:O.union([O.string(),O.number(),O.boolean()])}),Kt=O.object({name:O.string().min(1),type:O.literal("variable")}),Kd=O.discriminatedUnion("type",[Gd,Kt]),se=O.discriminatedUnion("type",[O.object({type:O.literal("static"),value:O.string()}),Kt]),Jd=O.discriminatedUnion("type",[O.object({type:O.literal("static"),value:O.number().int().nonnegative()}),Kt]),Yd=O.discriminatedUnion("type",[O.object({type:O.literal("static"),value:O.union([O.string(),O.number(),O.boolean()])}),Kt]),Xd=ee.discriminatedUnion("type",[ee.object({default:ee.string().optional(),type:ee.literal("string")}),ee.object({default:ee.number().optional(),type:ee.literal("number")}),ee.object({default:ee.boolean().optional(),type:ee.literal("boolean")}),ee.object({key:ee.string().min(1),type:ee.literal("env")})]),k={id:d.string().min(1).max(200),label:d.string().max(500).optional(),next:d.string().max(200).optional(),uiOnly:d.boolean().optional()},Xo=500,Qd=d.object({...k,type:d.literal("goto"),url:se}),Zd=d.object({...k,locator:C,modifier:d.enum(["Alt","Control","Meta","Shift"]).optional(),type:d.literal("click")}),ep=d.object({...k,locator:C,type:d.literal("fill"),value:se}),tp=d.object({...k,locator:C,type:d.literal("select"),value:se}),rp=d.object({...k,locator:C,type:d.literal("hover")}),np=d.object({...k,key:d.string().min(1),locator:C.optional(),type:d.literal("press")}),op=d.object({...k,locator:C,type:d.literal("check")}),ip=d.object({...k,locator:C,type:d.literal("uncheck")}),sp=d.object({...k,height:d.number().int().positive(),type:d.literal("setViewport"),width:d.number().int().positive()}),ap=d.object({...k,message:d.string().min(1),type:d.literal("fail")}),lp=d.object({...k,type:d.literal("setVariable"),value:Kd,variable:d.string().min(1)}),cp=d.object({...k,locator:C,type:d.literal("extractText"),variable:d.string().min(1)}),up=d.object({...k,files:d.array(d.string()).min(1),locator:C,type:d.literal("upload")}),dp=d.object({...k,locator:C,type:d.literal("dblclick")}),pp=d.object({...k,source:C,target:C,type:d.literal("drag")}),mp=d.object({...k,locator:C,type:d.literal("scrollIntoView")}),fp=d.object({...k,locator:C,type:d.literal("type"),value:se}),gp=d.object({...k,locator:C,type:d.literal("focus")}),yp=d.object({...k,locator:C,type:d.literal("clear")}),hp=d.object({...k,locator:C,type:d.literal("rightClick")}),wp=d.object({...k,action:d.enum(["accept","dismiss"]),promptText:d.string().optional(),type:d.literal("handleDialog")}),bp=d.object({...k,action:d.enum(["read","write"]),type:d.literal("clipboard"),value:se.optional(),variable:d.string().min(1).optional()}),vp=d.object({...k,permission:d.string().min(1),state:d.enum(["granted","prompt"]),type:d.literal("setPermission")}),Sp=d.object({...k,locator:C,type:d.literal("assertVisible")}),kp=d.object({...k,locator:C,type:d.literal("assertNotVisible")}),Rp=d.object({...k,expected:se,locator:C,operator:mt,type:d.literal("assertText")}),Pp=d.object({...k,expected:se,operator:mt,type:d.literal("assertUrl")}),xp=d.object({...k,expected:Jd,locator:C,operator:zd,type:d.literal("assertCount")}),Ep=d.object({...k,expected:se,locator:C,operator:mt,type:d.literal("assertValue")}),Cp=d.object({...k,attribute:d.string().min(1),expected:se,locator:C,operator:mt,type:d.literal("assertAttribute")}),Tp=d.object({...k,locator:C,type:d.literal("assertEnabled")}),
|
|
240
|
-
`}async function Jt({cwd:e}){let t=Be.join(e,ae),r=await Yp(t);return r==null?null:Fd(ai,r)}var Qo=10*1024*1024,Zo=50*1024*1024;async function le({cwd:e,result:t}){let r=await Gp({cwd:e,result:t}),n=li(r),o=Be.join(e,ae);await pt.mkdir(Be.dirname(o),{recursive:!0}),await pt.writeFile(o,yn(n),"utf8")}async function Gp({cwd:e,result:t}){let r=Jp(t);if(r.size===0)return{...t,fixtures:{}};let n=Be.join(e,Mp),o=[...r].toSorted((a,l)=>a.localeCompare(l)),i=await Promise.all(o.map(async a=>{let l=await Kp({fixturesRoot:n,name:a});if(l.size>Qo)throw new Error(`Fixture "${a}" is ${String(l.size)} bytes; exceeds per-file limit of ${String(Qo)} bytes`);return[a,l]}));if(i.reduce((a,[,l])=>a+l.size,0)>Zo)throw new Error(`Total fixtures size exceeds limit of ${String(Zo)} bytes`);return{...t,fixtures:Object.fromEntries(i)}}async function Kp({fixturesRoot:e,name:t}){if(t.includes("..")||Be.isAbsolute(t))throw new Error(`Invalid fixture name "${t}": must be a path under .ripplo/fixtures/`);let r=Be.join(e,t),n=await pt.lstat(r).catch(s=>{throw ci(s)&&s.code==="ENOENT"?new Error(`Fixture "${t}" not found at ${r}`):s});if(n.isSymbolicLink())throw new Error(`Fixture "${t}" is a symlink; symlinks are not allowed`);if(!n.isFile())throw new Error(`Fixture "${t}" is not a regular file`);let o=await pt.readFile(r);return{sha256:Ld("sha256").update(o).digest("hex"),size:o.byteLength}}function Jp(e){let t=new Set;return e.tests.forEach(r=>{Object.values(r.spec.nodes).forEach(n=>{n.type==="upload"&&n.files.forEach(o=>t.add(o))})}),t}function Yt({compiled:e,existing:t}){if(t==null)return"missing";let r=yn(li(e)),n=yn(t);return r===n?"match":"stale"}async function Yp(e){try{return await pt.readFile(e,"utf8")}catch(t){if(ci(t)&&t.code==="ENOENT")return null;throw t}}function ci(e){return e instanceof Error&&"code"in e}function Xp(e){return function(r,n){return n===e||!Qp(n)?n:Object.fromEntries(Object.entries(n).toSorted(([o],[i])=>o.localeCompare(i)))}}function Qp(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}import ft from"fs";import Zt from"path";var bn=["**/src/**","**/app/**","**/apps/**","**/pages/**","**/routes/**","**/components/**","**/server/**","**/api/**","**/backend/**","**/features/**","**/modules/**","**/views/**","**/ui/**","**/hooks/**","**/contexts/**","**/providers/**","**/controllers/**","**/handlers/**","**/resolvers/**","**/services/**","**/middleware/**","**/lib/**"],Pe=["**/*.gen.*","**/generated/**","**/*.d.ts","**/*.test.*","**/*.spec.*","**/node_modules/**","**/dist/**","**/build/**",".ripplo/**","**/*.md","**/.next/**","**/.turbo/**","**/.vercel/**","**/.svelte-kit/**","**/.nuxt/**","**/.astro/**","**/coverage/**","**/storybook-static/**","**/*.stories.*","**/*.story.*","**/cli/**","**/scripts/**","**/tools/**","**/__tests__/**","**/__mocks__/**","**/__fixtures__/**","**/*.config.*","**/*.setup.*","**/public/**","**/static/**","**/assets/**","**/migrations/**","**/prisma/migrations/**","**/scripts/**"];function ui(e){return e.data}function di(e){return{as(t){return{data:{label:t,node:e}}}}}function Xt(e){let t=e.getPreconditions(),r=e.getObservers(),n=e.getTests();Zp(n);let o={};t.forEach(a=>{o[a.name]={depends:[...a.dependsOn],description:a.description,returns:[...a.returns]}});let i={};r.forEach(a=>{i[a.name]={budget:a.budget,description:a.description}});let s=n.map(a=>em(a,t));return{fixtures:{},observers:i,preconditions:o,tests:s}}function Zp(e){let t=new Map;e.forEach(r=>{let n=t.get(r.id);if(n!=null)throw new Error(`Duplicate test id "${r.id}" used by "${n}" and "${r.name}"`);t.set(r.id,r.name)})}function em(e,t){let r=e.id,{accessedKeys:n,vars:o}=rm(e.requiresKeys),i=e.startsAtFn==null?void 0:e.startsAtFn(o),s=e.stepsFn==null?[]:e.stepsFn(o),a=i==null?s:[tm(i),...s],l=nm(a,n,e.requiresKeys,e.uiOnly),c=[];Object.keys(e.requiresKeys).length>0&&n.size===0&&e.implemented&&c.push("Test requires preconditions but never references their data \u2014 destructure and use precondition data in steps()");let m=im(e.requires,t);return{additionalChecks:[],coverage:e.coverage,description:e.description,expectedOutcome:e.expectedOutcome,implemented:e.implemented,name:e.name,preconditions:m,requiresKeys:{...e.requiresKeys},slug:r,sourcePath:e.sourcePath,spec:l,warnings:c}}function tm(e){return di({type:"goto",url:{type:"static",value:e}}).as(`navigate to ${e}`)}function rm(e){let t=new Set,r={};return Object.keys(e).forEach(n=>{r[n]=new Proxy({},{get(o,i){if(typeof i=="string"){let s=`${n}.${i}`;return t.add(s),`{{${s}}}`}}})}),{accessedKeys:t,vars:r}}function nm(e,t,r,n){let o={};e.forEach((a,l)=>{let c=`step-${String(l)}`,p=l<e.length-1?`step-${String(l+1)}`:void 0;o[c]=om(a,c,p)});let i={};t.forEach(a=>{i[a]={default:`test-${a}`,type:"string"}});let s={...r};return{entryNode:"step-0",nodes:o,uiOnly:n,variableNamespaces:s,variables:i}}function om(e,t,r){let{label:n,node:o}=ui(e);return{...o,id:t,label:n,next:r}}function im(e,t){let r=new Map(t.map(s=>[s.name,s])),n=[],o=new Set;function i(s){o.has(s)||(o.add(s),r.get(s)?.dependsOn.forEach(a=>{i(a)}),n.push(s))}return e.forEach(s=>{i(s)}),n}import{Webhook as IR,WebhookVerificationError as AR}from"standardwebhooks";import{z as D}from"zod";var pi=D.union([D.string(),D.number(),D.boolean()]),sm=D.record(D.string(),D.record(D.string(),pi)),jR=D.object({batch:D.array(D.object({preconditions:D.array(D.string().min(1)),runId:D.string().min(1)})).min(1)}),NR=D.object({batch:D.array(D.object({data:sm,preconditions:D.array(D.string().min(1)),runId:D.string().min(1)})).min(1)}),OR=D.object({observer:D.string().min(1).max(200),params:D.record(D.string().max(200),pi)});function He(e){let t=[];return e.tests.forEach(r=>{let n=am(r),o=i=>{t.push({...i,test:r.slug})};Am.forEach(i=>{i(n,r,o)})}),{diagnostics:t}}function am(e){let t=[],r=e.spec.entryNode,n=new Set;for(;r!=null&&!n.has(r);){n.add(r);let o=e.spec.nodes[r];if(o==null)break;t.push(o),r=o.next}return t}function lm(e,t,r){e.forEach(n=>{n.type==="assertText"&&"operator"in n&&n.operator!=="equals"&&r({message:`${n.type} uses operator "${n.operator}" \u2014 only "equals" is allowed for determinism`,rule:"exact-text-match",step:n.label??n.id})})}function cm(e,t,r){Object.keys(t.spec.variables??{}).length>0&&e.forEach(o=>{if(o.type==="fill"&&fi(o.value)){let i=o.value.value;!gi(i)&&ym(i)&&r({message:`fill() uses hardcoded value "${i}" \u2014 consider using precondition data via {{namespace.key}}`,rule:"no-hardcoded-data",step:o.label??o.id})}})}function um(e,t,r){if(Object.keys(t.spec.variables??{}).length===0)return;e.some(i=>JSON.stringify(i).includes("{{"))||r({message:"Test requires preconditions but steps() never references precondition data \u2014 destructure and use it",rule:"prefer-precondition-data",step:void 0})}function dm(e,t,r){e.forEach(n=>{(n.label==null||n.label.length===0)&&r({message:`Step "${n.id}" lacks .as("...") label \u2014 every step must be labeled`,rule:"missing-label",step:n.id})})}function pm(e,t,r){let n=new Map;e.forEach(o=>{if(o.label==null)return;let i=n.get(o.label);i==null?n.set(o.label,o.id):r({message:`Duplicate label "${o.label}" \u2014 also used by ${i}`,rule:"no-duplicate-labels",step:o.label})})}function mm(e,t,r){let n=0;e.forEach((o,i)=>{if(!(i===0&&o.type==="goto")){if(We(o)){n=0;return}n++,n===3&&r({message:"3+ consecutive actions without an assertion \u2014 add verification between actions",rule:"assert-after-action",step:o.label??o.id})}})}function fm(e,t,r){if(e.length===0)return;let n=e.at(-1);n!=null&&!We(n)&&r({message:"Last step is an action, not an assertion \u2014 expectedOutcome should be verified by assertions at the end",rule:"assert-matches-outcome",step:n.label??n.id})}function gm(e,t,r){t.implemented&&e.length===0&&r({message:"Test has zero steps",rule:"no-empty-steps",step:void 0})}function fi(e){return!(typeof e!="object"||e==null||!("type"in e)||e.type!=="static"||!("value"in e)||typeof e.value!="string")}function gi(e){return e.includes("{{")}function ym(e){return e.includes("@")||/\b[a-f0-9]{8,}\b/.test(e)||/^(test|ripplo|example|sample|demo)/i.test(e)}function We(e){return e.type.startsWith("assert")}var hm=new Set(["assertText","assertValue","assertCount","assertUrl","assertNotVisible","assertChecked","assertNotChecked","assertAttribute","assertDisabled","assertEnabled"]);function wm(e){return hm.has(e.type)}function bm(e,t,r){!t.implemented||e.length===0||e.some(n=>We(n))||r({message:"Test has zero assertion steps \u2014 cannot verify expectedOutcome. Add assert.* steps.",rule:"no-assertions",step:void 0})}function vm(e,t,r){if(!t.implemented||e.length<=3)return;let n=e.filter(i=>We(i)).length;if(n===0)return;let o=n/e.length;if(o<.15){let i=Math.round(o*100);r({message:`Only ${String(n)}/${String(e.length)} steps are assertions (${String(i)}%) \u2014 add more verification between actions`,rule:"low-assertion-ratio",step:void 0})}}function vn(e){if(!("locator"in e)||e.locator==null)return;let t=e.locator;return t.by==="role"?`role:${t.role}:${t.name??""}`:`testId:${t.value}`}function Sm(e,t,r){e.forEach((n,o)=>{if(n.type!=="click")return;let i=vn(n);if(i==null)return;let s=e.slice(o+1,o+4);s.find(c=>c.type==="assertVisible"&&vn(c)===i)==null||s.some(c=>wm(c)||We(c)&&vn(c)!==i)||r({message:`click "${n.label??n.id}" is followed only by assert.visible on the same locator \u2014 verifies nothing about the click's effect`,rule:"tautological-post-click-assert",step:n.label??n.id})})}var km=new Set(["the","is","a","an","and","or","of","to","in","on","at","for","that","this","with","be","are","was","were","it","its","as","by","from","after","before","should","will","can","still","but","not","no","so","if","then","than","user","users","page","view","shows","show","see","click","clicks","clicked","clickable","visible","appears","appear","displayed","stays","remains"]);function Sn(e){return e.toLowerCase().split(/[^a-z0-9]+/).filter(t=>t.length>=3&&!km.has(t))}function Rm(e){let t=e.label==null?[]:Sn(e.label);if(!("locator"in e)||e.locator==null)return t;let r=e.locator,n=r.by==="role"?r.name??"":r.value;return[...t,...Sn(n)]}function Pm(e,t,r){if(!t.implemented||e.length===0)return;let n=new Set(Sn(t.expectedOutcome));if(n.size===0)return;let o=e.filter(s=>We(s));if(o.length===0)return;o.some(s=>Rm(s).some(a=>n.has(a)))||r({message:`No assertion references any keyword from expectedOutcome (${[...n].join(", ")}) \u2014 the outcome may not actually be verified`,rule:"expected-outcome-keyword-coverage",step:void 0})}var xm=/save|submit|create|delete|remove|send|invite|update|confirm|publish|apply|pay|subscribe|upgrade|cancel|archive|rename/i;function mi(e){if(e.type==="upload")return!0;if(e.type!=="click")return!1;let t=e.locator,r=t.by==="role"?t.name??"":t.value;return xm.test(r)}function Em(e,t,r){!t.implemented||t.spec.uiOnly===!0||e.forEach((n,o)=>{if(!mi(n)||"uiOnly"in n&&n.uiOnly===!0)return;let i=e.slice(o+1),s=i.findIndex(p=>mi(p)),a=s===-1?i.length:s;i.slice(0,a).some(p=>p.type==="assertObserver")||r({message:`"${n.label??n.id}" looks like it mutates backend state but no assert.backend(...) observer verifies it \u2014 the test can pass while the server is broken. You need to add an observer that checks the persisted result (see .ripplo/observers/ for examples). Only if this action truly does NOT change any server state (pure client-side interaction, presentation toggle, etc.) should you fall back to marking the step { uiOnly: true } to silence this rule.`,rule:"mutation-without-observer-coverage",step:n.label??n.id})})}function Cm(e,t,r){Object.keys(t.spec.variables??{}).length!==0&&e.forEach(o=>{if(o.type!=="assertObserver")return;let i=Object.entries(o.params);i.length===0||i.some(([,a])=>fi(a)&&gi(a.value))||r({message:`assert.backend "${o.label??o.id}" passes only hardcoded params while the test defines precondition variables \u2014 observer assertions should reference {{namespace.key}} so they match the actual precondition data`,rule:"observer-params-reference-variables",step:o.label??o.id})})}function Tm(e,t,r){e.forEach(n=>{n.type==="upload"&&n.files.forEach(o=>{if(o.length===0){r({message:`upload "${n.label??n.id}" references an empty fixture name`,rule:"upload-fixture-name",step:n.label??n.id});return}(o.includes("..")||o.startsWith("/"))&&r({message:`upload "${n.label??n.id}" references "${o}" \u2014 fixture names must be relative paths under .ripplo/fixtures/, no ".." or absolute paths`,rule:"upload-fixture-name",step:n.label??n.id})})})}function Im(e,t,r){let n=new Set(Object.keys(t.spec.variables??{})),o=/\{\{([^{}]+?)\}\}/g;e.forEach(i=>{let a=[...JSON.stringify(i).matchAll(o)],l=[...new Set(a.map(m=>m[1]).filter(m=>m!=null&&!n.has(m)))];if(l.length===0)return;let c=l.map(m=>`{{${m}}}`).join(", "),p=[...new Set(l.map(m=>m.split(".")[0]??m))].join(", ");r({message:`"${i.label??i.id}" contains literal template string(s) ${c} \u2014 destructure the proxy in .steps(({ ${p} }) => \u2026) and pass the proxy value (e.g. \`${l[0]??""}\`) directly. Writing the template as a string bypasses type-checking and silently accepts typos.`,rule:"no-literal-template-strings",step:i.label??i.id})})}var Am=[lm,cm,Im,um,dm,pm,mm,fm,gm,bm,vm,Sm,Pm,Em,Cm,Tm];import tf from"picomatch";import{execFileSync as $m,spawnSync as jm}from"child_process";function z(e,t){return $m("git",[...e],{cwd:t,encoding:"utf8",stdio:["ignore","pipe","pipe"]})}function yi(e,t){let r=jm("git",["show",e],{cwd:t,encoding:"utf8",stdio:["ignore","pipe","pipe"]});if(r.status===0)return r.stdout;if(r.status===128)return null;throw new Error(`git show ${e} failed (${String(r.status)}): ${r.stderr}`)}import b from"typescript";import*as hi from"remeda";var wi=[["onClick","click"],["onContextMenu","click"],["onKeyDown","click"],["onKeyPress","click"],["onKeyUp","click"],["onSelect","click"],["onOpenChange","click"],["onPress","click"],["onActivate","click"],["onToggle","click"],["onOpen","click"],["onClose","click"],["onDismiss","click"],["onConfirm","click"],["onCancel","click"],["onApply","click"],["onClear","click"],["onSubmit","submit"],["onReset","submit"],["onDrop","drag"],["onDragEnd","drag"],["onDragEnter","drag"],["onDragLeave","drag"],["onDragOver","drag"],["onDragStart","drag"],["onValueChange","select"],["onSelectionChange","select"],["onChange","input"],["onCheckedChange","input"],["onInput","input"]],Nm=new Map([["button","click"],["link","navigate"],["textbox","input"],["searchbox","input"],["combobox","select"],["listbox","select"]]),Om=[[/(?:^|[a-z])Button$/,"click"],[/(?:^|[a-z])(?:Link|NavLink|Anchor)$/,"navigate"],[/(?:^|[a-z])(?:Textarea|TextArea|Input|Field|SearchBox)$/,"input"],[/(?:^|[a-z])(?:Select|Combobox|ComboBox|Dropdown)$/,"select"],[/(?:^|[a-z])Form$/,"submit"]];function Qt({filePath:e,source:t}){let r=b.createSourceFile(e,t,b.ScriptTarget.Latest,!0,b.ScriptKind.TSX);return r.statements.flatMap(n=>Dm({filePath:e,sf:r,stmt:n}))}function Dm({filePath:e,sf:t,stmt:r}){let n=_m(r);if(n==null||Lm(n))return[];let o=bi(r,t).map(i=>({id:`${e}#${n}.${i.kind}[${i.label}]`,line:i.line}));return hi.uniqueBy(o,i=>i.id)}function Lm(e){return e.endsWith("Fragment")||e.endsWith("Skeleton")||/^use[A-Z]/.test(e)||/^[A-Z][A-Z0-9_]*$/.test(e)}function _m(e){if(b.isExportAssignment(e))return Um(e.expression);if(!Vm(e))return null;if(b.isFunctionDeclaration(e)||b.isClassDeclaration(e))return e.name?.text??null;if(b.isVariableStatement(e)){let t=e.declarationList.declarations[0];return t!=null&&b.isIdentifier(t.name)?t.name.text:null}return null}function Um(e){return b.isIdentifier(e)?e.text:(b.isFunctionExpression(e)||b.isClassExpression(e))&&e.name!=null?e.name.text:"default"}function Vm(e){if(!b.canHaveModifiers(e))return!1;let t=b.getModifiers(e);return t!=null&&t.some(r=>r.kind===b.SyntaxKind.ExportKeyword)}function bi(e,t){let r=Fm(e,t),n=e.getChildren(t).flatMap(o=>bi(o,t));return r==null?n:[r,...n]}function Fm(e,t){let r=Mm(e);if(r==null)return null;let n=Bm(r);if(n==null)return null;let o=Gm(r,n);return o==null?null:{kind:n,label:o,line:ef(t,e.getStart(t))}}function Mm(e){return b.isJsxSelfClosingElement(e)&&b.isIdentifier(e.tagName)?{attrs:e.attributes,children:[],tag:e.tagName.text}:b.isJsxElement(e)&&b.isIdentifier(e.openingElement.tagName)?{attrs:e.openingElement.attributes,children:e.children,tag:e.openingElement.tagName.text}:null}function Bm({attrs:e,tag:t}){let r=ce(e,"role");return r!=null?Nm.get(r)??null:Wm(t,e)??qm(t)??zm(e)}var Hm=new Map([["button",()=>"click"],["a",e=>ce(e,"href")==null?null:"navigate"],["input",e=>ce(e,"type")==="file"?"upload":"input"],["textarea",()=>"input"],["select",()=>"select"],["form",()=>"submit"]]);function Wm(e,t){return Hm.get(e)?.(t)??null}function qm(e){return/^[A-Z]/.test(e)?Om.find(([t])=>t.test(e))?.[1]??null:null}function zm(e){return wi.find(([t])=>Ym(e,t))?.[1]??null}function Gm({attrs:e,children:t,tag:r},n){return n==="navigate"?ce(e,"href")??ce(e,"to"):ce(e,"aria-label")??ce(e,"label")??ce(e,"title")??ce(e,"name")??ce(e,"placeholder")??(Km(r)?void 0:Zm(t))??Jm(e,n)}function Km(e){return e==="input"||e==="textarea"||e==="select"}function Jm(e,t){let r=wi.find(([,o])=>o===t)?.[0];if(r==null)return;let n=Xm(e,r);if(n!=null){if(b.isIdentifier(n))return n.text;if(b.isArrowFunction(n)||b.isFunctionExpression(n))return vi(n.body)}}function vi(e){if(b.isCallExpression(e)){let t=e.expression;return b.isIdentifier(t)?t.text:b.isPropertyAccessExpression(t)?t.name.text:void 0}return b.forEachChild(e,vi)}function Ym(e,t){return e.properties.some(r=>b.isJsxAttribute(r)&&b.isIdentifier(r.name)&&r.name.text===t)}function Si(e,t){return e.properties.find(r=>b.isJsxAttribute(r)&&b.isIdentifier(r.name)&&r.name.text===t)}function ce(e,t){let r=Si(e,t);return r==null?void 0:Qm(r.initializer)}function Xm(e,t){let r=Si(e,t);if(!(r?.initializer==null||!b.isJsxExpression(r.initializer)))return r.initializer.expression}function Qm(e){if(e==null)return"";if(b.isStringLiteral(e))return e.text;if(b.isJsxExpression(e))return Ri(e.expression)}function Zm(e){let t=e.flatMap(r=>ki(r)).join(" ").trim();return t.length===0?void 0:t}function ki(e){if(b.isJsxText(e)){let t=e.text.trim();return t.length===0?[]:[t]}if(b.isJsxExpression(e)){let t=Ri(e.expression);return t==null?[]:[t]}return b.isJsxElement(e)?e.children.flatMap(t=>ki(t)):[]}function Ri(e){if(e!=null){if(b.isStringLiteral(e)||b.isNoSubstitutionTemplateLiteral(e))return e.text;if(b.isCallExpression(e)&&e.arguments.length===1){let t=e.arguments[0];if(t!=null&&(b.isStringLiteral(t)||b.isNoSubstitutionTemplateLiteral(t)))return t.text}}}function ef(e,t){return e.getLineAndCharacterOfPosition(t).line+1}var rf=Zt.join(".ripplo","coverage.d.ts");function qe({cwd:e}){nf({cwd:e,ignorePaths:Pe})}function nf({cwd:e,ignorePaths:t}){let r=ze({cwd:e,ignorePaths:t});af({content:sf(r),cwd:e})}function ze({cwd:e,ignorePaths:t}){let n=of({cwd:e,ignorePaths:t}).flatMap(o=>kn({cwd:e,file:o}));return[...new Set(n)].sort((o,i)=>o.localeCompare(i))}function of({cwd:e,ignorePaths:t}){let r=z(["ls-files","--cached","--others","--exclude-standard","-z"],e),n=tf([...t]);return r.split("\0").filter(o=>o.length>0&&/\.(tsx|jsx)$/.test(o)).filter(o=>!n(o)).filter(o=>ft.existsSync(Zt.join(e,o)))}function kn({cwd:e,file:t}){let r=ft.readFileSync(Zt.join(e,t),"utf8");return Qt({filePath:t,source:r}).map(n=>n.id)}function sf(e){let t=`// GENERATED \u2014 do not edit
|
|
239
|
+
`)}import{createHash as Ld}from"crypto";import pt from"fs/promises";import Be from"path";import{z as Gt}from"zod";import{z as Yo}from"zod";import{z as Me}from"zod";import{z as d}from"zod";import{z as Re}from"zod";import{z as ri}from"zod";import{z as O}from"zod";import{z as ee}from"zod";import{z as fn}from"zod";import{z as E}from"zod";var _d=Gt.object({__codec:Gt.string().min(1),data:Gt.unknown(),version:Gt.number().int().positive()}),Ud=class extends Error{codec;currentVersion;gotVersion;constructor(e){super(`Unsupported ${e.codec} version ${String(e.gotVersion)} (current ${String(e.currentVersion)}). Upgrade Ripplo or rebuild with a compatible CLI.`),this.name="CodecVersionError",this.codec=e.codec,this.currentVersion=e.currentVersion,this.gotVersion=e.gotVersion}},Vd=class extends Error{constructor(e){super(`Codec mismatch: expected "${e.expected}", got "${e.got}"`),this.name="CodecMismatchError"}};function hn(e){return ei({legacy:void 0,migrators:[],name:e,schemas:[]})}function Fd(e,t){let r=JSON.parse(t);return e.decode(r)}function ei(e){return{initial:t=>gn(t,{...e,schemas:[t]}),legacy:t=>ei({...e,legacy:t})}}function gn(e,t){return{build:()=>Md(e,t),legacy:r=>gn(e,{...t,legacy:r}),upgrade:(r,n)=>{let o=n;return gn(r,{...t,migrators:[...t.migrators,o],schemas:[...t.schemas,r]})}}}function Md(e,t){let r=t.schemas.length;return{currentVersion:r,name:t.name,decode:n=>Bd(e,t,n),encode:n=>({__codec:t.name,data:n,version:r})}}function Bd(e,t,r){let{data:n,version:o}=Hd(t,r),i=ti(t,n,o);return e.parse(i)}function Hd(e,t){let r=_d.safeParse(t);if(r.success){if(r.data.__codec!==e.name)throw new Vd({expected:e.name,got:r.data.__codec});return{data:r.data.data,version:r.data.version}}if(e.legacy!=null&&e.legacy.detect(t))return{data:t,version:e.legacy.assumedVersion};throw new Error(`Cannot decode "${e.name}": value is not a codec envelope and no legacy detector matched.`)}function ti(e,t,r){let n=e.schemas.length;if(r>n)throw new Ud({codec:e.name,currentVersion:n,gotVersion:r});if(r===n)return t;let o=e.schemas[r-1];if(o==null)throw new Error(`Codec "${e.name}" missing schema for v${String(r)}; cannot migrate.`);let i=o.parse(t),s=e.migrators[r-1];if(s==null)throw new Error(`Codec "${e.name}" missing migrator v${String(r)} \u2192 v${String(r+1)}.`);return ti(e,s(i),r+1)}var wn=Me.object({depends:Me.array(Me.string().min(1)).optional().describe("Names of other preconditions that must be satisfied first. Resolved via topological sort; cycles are rejected at validation time."),description:Me.string().min(1).describe("Human-readable description of what this precondition ensures"),returns:Me.array(Me.string().min(1)).optional().describe("Keys that the execute response's data field will contain. e.g. ['projectId', 'workflowId']. These are used for route param interpolation ({{projectId}}) and workflow variables. Declared here so generated types are strongly typed per precondition.")}).describe("A named precondition declared at the graph level. States reference these by name."),Wd=Re.object({by:Re.literal("testId"),value:Re.string().min(1)}),qd=Re.object({by:Re.literal("role"),name:Re.string().optional(),role:Re.string().min(1)}),C=Re.discriminatedUnion("by",[Wd,qd]),mt=ri.enum(["equals","notEquals","contains","startsWith","endsWith","matches"]),zd=ri.enum(["equals","notEquals","greaterThan","greaterThanOrEqual","lessThan","lessThanOrEqual"]),Gd=O.object({type:O.literal("static"),value:O.union([O.string(),O.number(),O.boolean()])}),Kt=O.object({name:O.string().min(1),type:O.literal("variable")}),Kd=O.discriminatedUnion("type",[Gd,Kt]),se=O.discriminatedUnion("type",[O.object({type:O.literal("static"),value:O.string()}),Kt]),Jd=O.discriminatedUnion("type",[O.object({type:O.literal("static"),value:O.number().int().nonnegative()}),Kt]),Yd=O.discriminatedUnion("type",[O.object({type:O.literal("static"),value:O.union([O.string(),O.number(),O.boolean()])}),Kt]),Xd=ee.discriminatedUnion("type",[ee.object({default:ee.string().optional(),type:ee.literal("string")}),ee.object({default:ee.number().optional(),type:ee.literal("number")}),ee.object({default:ee.boolean().optional(),type:ee.literal("boolean")}),ee.object({key:ee.string().min(1),type:ee.literal("env")})]),k={id:d.string().min(1).max(200),label:d.string().max(500).optional(),next:d.string().max(200).optional(),uiOnly:d.boolean().optional()},Xo=500,Qd=d.object({...k,type:d.literal("goto"),url:se}),Zd=d.object({...k,locator:C,modifier:d.enum(["Alt","Control","Meta","Shift"]).optional(),type:d.literal("click")}),ep=d.object({...k,locator:C,type:d.literal("fill"),value:se}),tp=d.object({...k,locator:C,type:d.literal("select"),value:se}),rp=d.object({...k,locator:C,type:d.literal("hover")}),np=d.object({...k,key:d.string().min(1),locator:C.optional(),type:d.literal("press")}),op=d.object({...k,locator:C,type:d.literal("check")}),ip=d.object({...k,locator:C,type:d.literal("uncheck")}),sp=d.object({...k,height:d.number().int().positive(),type:d.literal("setViewport"),width:d.number().int().positive()}),ap=d.object({...k,message:d.string().min(1),type:d.literal("fail")}),lp=d.object({...k,type:d.literal("setVariable"),value:Kd,variable:d.string().min(1)}),cp=d.object({...k,locator:C,type:d.literal("extractText"),variable:d.string().min(1)}),up=d.object({...k,files:d.array(d.string()).min(1),locator:C,type:d.literal("upload")}),dp=d.object({...k,locator:C,type:d.literal("dblclick")}),pp=d.object({...k,source:C,target:C,type:d.literal("drag")}),mp=d.object({...k,locator:C,type:d.literal("scrollIntoView")}),fp=d.object({...k,locator:C,type:d.literal("type"),value:se}),gp=d.object({...k,locator:C,type:d.literal("focus")}),yp=d.object({...k,locator:C,type:d.literal("clear")}),hp=d.object({...k,locator:C,type:d.literal("rightClick")}),wp=d.object({...k,action:d.enum(["accept","dismiss"]),promptText:d.string().optional(),type:d.literal("handleDialog")}),bp=d.object({...k,action:d.enum(["read","write"]),type:d.literal("clipboard"),value:se.optional(),variable:d.string().min(1).optional()}),vp=d.object({...k,permission:d.string().min(1),state:d.enum(["granted","prompt"]),type:d.literal("setPermission")}),Sp=d.object({...k,locator:C,type:d.literal("assertVisible")}),kp=d.object({...k,locator:C,type:d.literal("assertNotVisible")}),Rp=d.object({...k,expected:se,locator:C,operator:mt,type:d.literal("assertText")}),Pp=d.object({...k,expected:se,operator:mt,type:d.literal("assertUrl")}),xp=d.object({...k,expected:Jd,locator:C,operator:zd,type:d.literal("assertCount")}),Ep=d.object({...k,expected:se,locator:C,operator:mt,type:d.literal("assertValue")}),Cp=d.object({...k,attribute:d.string().min(1),expected:se,locator:C,operator:mt,type:d.literal("assertAttribute")}),Tp=d.object({...k,locator:C,type:d.literal("assertEnabled")}),Ap=d.object({...k,locator:C,type:d.literal("assertDisabled")}),Ip=d.object({...k,expected:se,operator:mt,type:d.literal("assertTitle")}),$p=d.object({...k,locator:C,type:d.literal("assertChecked")}),jp=d.object({...k,locator:C,type:d.literal("assertNotChecked")}),Np=d.object({...k,locator:C,type:d.literal("assertFocused")}),Op=d.object({...k,locator:C,type:d.literal("assertNotFocused")}),Dp=d.object({...k,budget:d.enum(["fast","slow","async"]),observer:d.string().min(1).max(200),params:d.record(d.string().max(200),Yd),type:d.literal("assertObserver")}),Lp=d.discriminatedUnion("type",[Qd,Zd,ep,tp,rp,np,op,ip,Sp,kp,Rp,Pp,xp,Ep,Cp,Tp,Ap,sp,ap,lp,cp,up,dp,pp,mp,fp,gp,yp,hp,wp,bp,vp,Ip,$p,jp,Np,Op,Dp]),ni=d.object({entryNode:d.string().min(1).max(200),nodes:d.record(d.string().max(200),Lp).refine(e=>Object.keys(e).length<=Xo,`Workflow has more than ${String(Xo)} nodes`),uiOnly:d.boolean().optional(),variableNamespaces:d.record(d.string().max(200),d.string().max(500)).optional(),variables:d.record(d.string().max(200),Xd).optional()}),_p=Yo.record(Yo.string().max(200),wn),Up={assumedVersion:1,detect:e=>typeof e=="object"&&e!==null&&"entryNode"in e&&"nodes"in e},Vp={assumedVersion:1,detect:e=>typeof e=="object"&&e!==null&&!Array.isArray(e)&&!("__codec"in e)},bR=hn("workflow-spec").legacy(Up).initial(ni).build(),vR=hn("precondition-map").legacy(Vp).initial(_p).build(),Fp=["fast","slow","async"],oi=fn.object({budget:fn.enum(Fp).describe("Polling budget tier: fast | slow | async"),description:fn.string().min(1).describe("Human-readable description of what this observer checks")}).describe("A named backend state observer. Tests assert against it with assert.backend(observer, params). Implementation lives on the user's server."),ae=".ripplo/ripplo.lock",Mp=".ripplo/fixtures",ii=5e3,Bp=E.record(E.string().max(200),E.string().max(200)),si=E.object({coverage:E.array(E.string().max(500)).max(2e3).default([]),expectedOutcome:E.string().max(2e3),name:E.string().max(200),preconditions:E.array(E.string().max(200)).max(1e3),requiresKeys:Bp,slug:E.string().max(200),sourcePath:E.string().max(500).optional(),spec:ni}),Hp=E.object({sha256:E.string().regex(/^[0-9a-f]{64}$/u),size:E.number().int().nonnegative()}),Wp=E.record(E.string().min(1).max(500),Hp),qp=E.object({observers:E.record(E.string().max(200),oi),preconditions:E.record(E.string().max(200),wn),tests:E.array(si).max(ii)}),zp=E.object({fixtures:Wp,observers:E.record(E.string().max(200),oi),preconditions:E.record(E.string().max(200),wn),tests:E.array(si).max(ii)}),ai=hn("ripplo-lockfile").initial(qp).upgrade(zp,e=>({...e,fixtures:{}})).build();function li(e){return{fixtures:{...e.fixtures},observers:e.observers,preconditions:e.preconditions,tests:e.tests.filter(t=>t.implemented).map(t=>({coverage:[...t.coverage],expectedOutcome:t.expectedOutcome,name:t.name,preconditions:[...t.preconditions],requiresKeys:{...t.requiresKeys},slug:t.slug,sourcePath:t.sourcePath,spec:t.spec}))}}function yn(e){let t=ai.encode(e);return`${JSON.stringify(t,Xp(t),2)}
|
|
240
|
+
`}async function Jt({cwd:e}){let t=Be.join(e,ae),r=await Yp(t);return r==null?null:Fd(ai,r)}var Qo=10*1024*1024,Zo=50*1024*1024;async function le({cwd:e,result:t}){let r=await Gp({cwd:e,result:t}),n=li(r),o=Be.join(e,ae);await pt.mkdir(Be.dirname(o),{recursive:!0}),await pt.writeFile(o,yn(n),"utf8")}async function Gp({cwd:e,result:t}){let r=Jp(t);if(r.size===0)return{...t,fixtures:{}};let n=Be.join(e,Mp),o=[...r].toSorted((a,l)=>a.localeCompare(l)),i=await Promise.all(o.map(async a=>{let l=await Kp({fixturesRoot:n,name:a});if(l.size>Qo)throw new Error(`Fixture "${a}" is ${String(l.size)} bytes; exceeds per-file limit of ${String(Qo)} bytes`);return[a,l]}));if(i.reduce((a,[,l])=>a+l.size,0)>Zo)throw new Error(`Total fixtures size exceeds limit of ${String(Zo)} bytes`);return{...t,fixtures:Object.fromEntries(i)}}async function Kp({fixturesRoot:e,name:t}){if(t.includes("..")||Be.isAbsolute(t))throw new Error(`Invalid fixture name "${t}": must be a path under .ripplo/fixtures/`);let r=Be.join(e,t),n=await pt.lstat(r).catch(s=>{throw ci(s)&&s.code==="ENOENT"?new Error(`Fixture "${t}" not found at ${r}`):s});if(n.isSymbolicLink())throw new Error(`Fixture "${t}" is a symlink; symlinks are not allowed`);if(!n.isFile())throw new Error(`Fixture "${t}" is not a regular file`);let o=await pt.readFile(r);return{sha256:Ld("sha256").update(o).digest("hex"),size:o.byteLength}}function Jp(e){let t=new Set;return e.tests.forEach(r=>{Object.values(r.spec.nodes).forEach(n=>{n.type==="upload"&&n.files.forEach(o=>t.add(o))})}),t}function Yt({compiled:e,existing:t}){if(t==null)return"missing";let r=yn(li(e)),n=yn(t);return r===n?"match":"stale"}async function Yp(e){try{return await pt.readFile(e,"utf8")}catch(t){if(ci(t)&&t.code==="ENOENT")return null;throw t}}function ci(e){return e instanceof Error&&"code"in e}function Xp(e){return function(r,n){return n===e||!Qp(n)?n:Object.fromEntries(Object.entries(n).toSorted(([o],[i])=>o.localeCompare(i)))}}function Qp(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}import ft from"fs";import Zt from"path";var bn=["**/src/**","**/app/**","**/apps/**","**/pages/**","**/routes/**","**/components/**","**/server/**","**/api/**","**/backend/**","**/features/**","**/modules/**","**/views/**","**/ui/**","**/hooks/**","**/contexts/**","**/providers/**","**/controllers/**","**/handlers/**","**/resolvers/**","**/services/**","**/middleware/**","**/lib/**"],Pe=["**/*.gen.*","**/generated/**","**/*.d.ts","**/*.test.*","**/*.spec.*","**/node_modules/**","**/dist/**","**/build/**",".ripplo/**","**/*.md","**/.next/**","**/.turbo/**","**/.vercel/**","**/.svelte-kit/**","**/.nuxt/**","**/.astro/**","**/coverage/**","**/storybook-static/**","**/*.stories.*","**/*.story.*","**/cli/**","**/scripts/**","**/tools/**","**/__tests__/**","**/__mocks__/**","**/__fixtures__/**","**/*.config.*","**/*.setup.*","**/public/**","**/static/**","**/assets/**","**/migrations/**","**/prisma/migrations/**","**/scripts/**"];function ui(e){return e.data}function di(e){return{as(t){return{data:{label:t,node:e}}}}}function Xt(e){let t=e.getPreconditions(),r=e.getObservers(),n=e.getTests();Zp(n);let o={};t.forEach(a=>{o[a.name]={depends:[...a.dependsOn],description:a.description,returns:[...a.returns]}});let i={};r.forEach(a=>{i[a.name]={budget:a.budget,description:a.description}});let s=n.map(a=>em(a,t));return{fixtures:{},observers:i,preconditions:o,tests:s}}function Zp(e){let t=new Map;e.forEach(r=>{let n=t.get(r.id);if(n!=null)throw new Error(`Duplicate test id "${r.id}" used by "${n}" and "${r.name}"`);t.set(r.id,r.name)})}function em(e,t){let r=e.id,{accessedKeys:n,vars:o}=rm(e.requiresKeys),i=e.startsAtFn==null?void 0:e.startsAtFn(o),s=e.stepsFn==null?[]:e.stepsFn(o),a=i==null?s:[tm(i),...s],l=nm(a,n,e.requiresKeys,e.uiOnly),c=[];Object.keys(e.requiresKeys).length>0&&n.size===0&&e.implemented&&c.push("Test requires preconditions but never references their data \u2014 destructure and use precondition data in steps()");let m=im(e.requires,t);return{additionalChecks:[],coverage:e.coverage,description:e.description,expectedOutcome:e.expectedOutcome,implemented:e.implemented,name:e.name,preconditions:m,requiresKeys:{...e.requiresKeys},slug:r,sourcePath:e.sourcePath,spec:l,warnings:c}}function tm(e){return di({type:"goto",url:{type:"static",value:e}}).as(`navigate to ${e}`)}function rm(e){let t=new Set,r={};return Object.keys(e).forEach(n=>{r[n]=new Proxy({},{get(o,i){if(typeof i=="string"){let s=`${n}.${i}`;return t.add(s),`{{${s}}}`}}})}),{accessedKeys:t,vars:r}}function nm(e,t,r,n){let o={};e.forEach((a,l)=>{let c=`step-${String(l)}`,p=l<e.length-1?`step-${String(l+1)}`:void 0;o[c]=om(a,c,p)});let i={};t.forEach(a=>{i[a]={default:`test-${a}`,type:"string"}});let s={...r};return{entryNode:"step-0",nodes:o,uiOnly:n,variableNamespaces:s,variables:i}}function om(e,t,r){let{label:n,node:o}=ui(e);return{...o,id:t,label:n,next:r}}function im(e,t){let r=new Map(t.map(s=>[s.name,s])),n=[],o=new Set;function i(s){o.has(s)||(o.add(s),r.get(s)?.dependsOn.forEach(a=>{i(a)}),n.push(s))}return e.forEach(s=>{i(s)}),n}import{Webhook as $R,WebhookVerificationError as jR}from"standardwebhooks";import{z as D}from"zod";var pi=D.union([D.string(),D.number(),D.boolean()]),sm=D.record(D.string(),D.record(D.string(),pi)),OR=D.object({batch:D.array(D.object({preconditions:D.array(D.string().min(1)),runId:D.string().min(1)})).min(1)}),DR=D.object({batch:D.array(D.object({data:sm,preconditions:D.array(D.string().min(1)),runId:D.string().min(1)})).min(1)}),LR=D.object({observer:D.string().min(1).max(200),params:D.record(D.string().max(200),pi)});function He(e){let t=[];return e.tests.forEach(r=>{let n=am(r),o=i=>{t.push({...i,test:r.slug})};Im.forEach(i=>{i(n,r,o)})}),{diagnostics:t}}function am(e){let t=[],r=e.spec.entryNode,n=new Set;for(;r!=null&&!n.has(r);){n.add(r);let o=e.spec.nodes[r];if(o==null)break;t.push(o),r=o.next}return t}function lm(e,t,r){e.forEach(n=>{n.type==="assertText"&&"operator"in n&&n.operator!=="equals"&&r({message:`${n.type} uses operator "${n.operator}" \u2014 only "equals" is allowed for determinism`,rule:"exact-text-match",step:n.label??n.id})})}function cm(e,t,r){Object.keys(t.spec.variables??{}).length>0&&e.forEach(o=>{if(o.type==="fill"&&fi(o.value)){let i=o.value.value;!gi(i)&&ym(i)&&r({message:`fill() uses hardcoded value "${i}" \u2014 consider using precondition data via {{namespace.key}}`,rule:"no-hardcoded-data",step:o.label??o.id})}})}function um(e,t,r){if(Object.keys(t.spec.variables??{}).length===0)return;e.some(i=>JSON.stringify(i).includes("{{"))||r({message:"Test requires preconditions but steps() never references precondition data \u2014 destructure and use it",rule:"prefer-precondition-data",step:void 0})}function dm(e,t,r){e.forEach(n=>{(n.label==null||n.label.length===0)&&r({message:`Step "${n.id}" lacks .as("...") label \u2014 every step must be labeled`,rule:"missing-label",step:n.id})})}function pm(e,t,r){let n=new Map;e.forEach(o=>{if(o.label==null)return;let i=n.get(o.label);i==null?n.set(o.label,o.id):r({message:`Duplicate label "${o.label}" \u2014 also used by ${i}`,rule:"no-duplicate-labels",step:o.label})})}function mm(e,t,r){let n=0;e.forEach((o,i)=>{if(!(i===0&&o.type==="goto")){if(We(o)){n=0;return}n++,n===3&&r({message:"3+ consecutive actions without an assertion \u2014 add verification between actions",rule:"assert-after-action",step:o.label??o.id})}})}function fm(e,t,r){if(e.length===0)return;let n=e.at(-1);n!=null&&!We(n)&&r({message:"Last step is an action, not an assertion \u2014 expectedOutcome should be verified by assertions at the end",rule:"assert-matches-outcome",step:n.label??n.id})}function gm(e,t,r){t.implemented&&e.length===0&&r({message:"Test has zero steps",rule:"no-empty-steps",step:void 0})}function fi(e){return!(typeof e!="object"||e==null||!("type"in e)||e.type!=="static"||!("value"in e)||typeof e.value!="string")}function gi(e){return e.includes("{{")}function ym(e){return e.includes("@")||/\b[a-f0-9]{8,}\b/.test(e)||/^(test|ripplo|example|sample|demo)/i.test(e)}function We(e){return e.type.startsWith("assert")}var hm=new Set(["assertText","assertValue","assertCount","assertUrl","assertNotVisible","assertChecked","assertNotChecked","assertAttribute","assertDisabled","assertEnabled"]);function wm(e){return hm.has(e.type)}function bm(e,t,r){!t.implemented||e.length===0||e.some(n=>We(n))||r({message:"Test has zero assertion steps \u2014 cannot verify expectedOutcome. Add assert.* steps.",rule:"no-assertions",step:void 0})}function vm(e,t,r){if(!t.implemented||e.length<=3)return;let n=e.filter(i=>We(i)).length;if(n===0)return;let o=n/e.length;if(o<.15){let i=Math.round(o*100);r({message:`Only ${String(n)}/${String(e.length)} steps are assertions (${String(i)}%) \u2014 add more verification between actions`,rule:"low-assertion-ratio",step:void 0})}}function vn(e){if(!("locator"in e)||e.locator==null)return;let t=e.locator;return t.by==="role"?`role:${t.role}:${t.name??""}`:`testId:${t.value}`}function Sm(e,t,r){e.forEach((n,o)=>{if(n.type!=="click")return;let i=vn(n);if(i==null)return;let s=e.slice(o+1,o+4);s.find(c=>c.type==="assertVisible"&&vn(c)===i)==null||s.some(c=>wm(c)||We(c)&&vn(c)!==i)||r({message:`click "${n.label??n.id}" is followed only by assert.visible on the same locator \u2014 verifies nothing about the click's effect`,rule:"tautological-post-click-assert",step:n.label??n.id})})}var km=new Set(["the","is","a","an","and","or","of","to","in","on","at","for","that","this","with","be","are","was","were","it","its","as","by","from","after","before","should","will","can","still","but","not","no","so","if","then","than","user","users","page","view","shows","show","see","click","clicks","clicked","clickable","visible","appears","appear","displayed","stays","remains"]);function Sn(e){return e.toLowerCase().split(/[^a-z0-9]+/).filter(t=>t.length>=3&&!km.has(t))}function Rm(e){let t=e.label==null?[]:Sn(e.label);if(!("locator"in e)||e.locator==null)return t;let r=e.locator,n=r.by==="role"?r.name??"":r.value;return[...t,...Sn(n)]}function Pm(e,t,r){if(!t.implemented||e.length===0)return;let n=new Set(Sn(t.expectedOutcome));if(n.size===0)return;let o=e.filter(s=>We(s));if(o.length===0)return;o.some(s=>Rm(s).some(a=>n.has(a)))||r({message:`No assertion references any keyword from expectedOutcome (${[...n].join(", ")}) \u2014 the outcome may not actually be verified`,rule:"expected-outcome-keyword-coverage",step:void 0})}var xm=/save|submit|create|delete|remove|send|invite|update|confirm|publish|apply|pay|subscribe|upgrade|cancel|archive|rename/i;function mi(e){if(e.type==="upload")return!0;if(e.type!=="click")return!1;let t=e.locator,r=t.by==="role"?t.name??"":t.value;return xm.test(r)}function Em(e,t,r){!t.implemented||t.spec.uiOnly===!0||e.forEach((n,o)=>{if(!mi(n)||"uiOnly"in n&&n.uiOnly===!0)return;let i=e.slice(o+1),s=i.findIndex(p=>mi(p)),a=s===-1?i.length:s;i.slice(0,a).some(p=>p.type==="assertObserver")||r({message:`"${n.label??n.id}" looks like it mutates backend state but no assert.backend(...) observer verifies it \u2014 the test can pass while the server is broken. You need to add an observer that checks the persisted result (see .ripplo/observers/ for examples). Only if this action truly does NOT change any server state (pure client-side interaction, presentation toggle, etc.) should you fall back to marking the step { uiOnly: true } to silence this rule.`,rule:"mutation-without-observer-coverage",step:n.label??n.id})})}function Cm(e,t,r){Object.keys(t.spec.variables??{}).length!==0&&e.forEach(o=>{if(o.type!=="assertObserver")return;let i=Object.entries(o.params);i.length===0||i.some(([,a])=>fi(a)&&gi(a.value))||r({message:`assert.backend "${o.label??o.id}" passes only hardcoded params while the test defines precondition variables \u2014 observer assertions should reference {{namespace.key}} so they match the actual precondition data`,rule:"observer-params-reference-variables",step:o.label??o.id})})}function Tm(e,t,r){e.forEach(n=>{n.type==="upload"&&n.files.forEach(o=>{if(o.length===0){r({message:`upload "${n.label??n.id}" references an empty fixture name`,rule:"upload-fixture-name",step:n.label??n.id});return}(o.includes("..")||o.startsWith("/"))&&r({message:`upload "${n.label??n.id}" references "${o}" \u2014 fixture names must be relative paths under .ripplo/fixtures/, no ".." or absolute paths`,rule:"upload-fixture-name",step:n.label??n.id})})})}function Am(e,t,r){let n=new Set(Object.keys(t.spec.variables??{})),o=/\{\{([^{}]+?)\}\}/g;e.forEach(i=>{let a=[...JSON.stringify(i).matchAll(o)],l=[...new Set(a.map(m=>m[1]).filter(m=>m!=null&&!n.has(m)))];if(l.length===0)return;let c=l.map(m=>`{{${m}}}`).join(", "),p=[...new Set(l.map(m=>m.split(".")[0]??m))].join(", ");r({message:`"${i.label??i.id}" contains literal template string(s) ${c} \u2014 destructure the proxy in .steps(({ ${p} }) => \u2026) and pass the proxy value (e.g. \`${l[0]??""}\`) directly. Writing the template as a string bypasses type-checking and silently accepts typos.`,rule:"no-literal-template-strings",step:i.label??i.id})})}var Im=[lm,cm,Am,um,dm,pm,mm,fm,gm,bm,vm,Sm,Pm,Em,Cm,Tm];import tf from"picomatch";import{execFileSync as $m,spawnSync as jm}from"child_process";function z(e,t){return $m("git",[...e],{cwd:t,encoding:"utf8",stdio:["ignore","pipe","pipe"]})}function yi(e,t){let r=jm("git",["show",e],{cwd:t,encoding:"utf8",stdio:["ignore","pipe","pipe"]});if(r.status===0)return r.stdout;if(r.status===128)return null;throw new Error(`git show ${e} failed (${String(r.status)}): ${r.stderr}`)}import b from"typescript";import*as hi from"remeda";var wi=[["onClick","click"],["onContextMenu","click"],["onKeyDown","click"],["onKeyPress","click"],["onKeyUp","click"],["onSelect","click"],["onOpenChange","click"],["onPress","click"],["onActivate","click"],["onToggle","click"],["onOpen","click"],["onClose","click"],["onDismiss","click"],["onConfirm","click"],["onCancel","click"],["onApply","click"],["onClear","click"],["onSubmit","submit"],["onReset","submit"],["onDrop","drag"],["onDragEnd","drag"],["onDragEnter","drag"],["onDragLeave","drag"],["onDragOver","drag"],["onDragStart","drag"],["onValueChange","select"],["onSelectionChange","select"],["onChange","input"],["onCheckedChange","input"],["onInput","input"]],Nm=new Map([["button","click"],["link","navigate"],["textbox","input"],["searchbox","input"],["combobox","select"],["listbox","select"]]),Om=[[/(?:^|[a-z])Button$/,"click"],[/(?:^|[a-z])(?:Link|NavLink|Anchor)$/,"navigate"],[/(?:^|[a-z])(?:Textarea|TextArea|Input|Field|SearchBox)$/,"input"],[/(?:^|[a-z])(?:Select|Combobox|ComboBox|Dropdown)$/,"select"],[/(?:^|[a-z])Form$/,"submit"]];function Qt({filePath:e,source:t}){let r=b.createSourceFile(e,t,b.ScriptTarget.Latest,!0,b.ScriptKind.TSX);return r.statements.flatMap(n=>Dm({filePath:e,sf:r,stmt:n}))}function Dm({filePath:e,sf:t,stmt:r}){let n=_m(r);if(n==null||Lm(n))return[];let o=bi(r,t).map(i=>({id:`${e}#${n}.${i.kind}[${i.label}]`,line:i.line}));return hi.uniqueBy(o,i=>i.id)}function Lm(e){return e.endsWith("Fragment")||e.endsWith("Skeleton")||/^use[A-Z]/.test(e)||/^[A-Z][A-Z0-9_]*$/.test(e)}function _m(e){if(b.isExportAssignment(e))return Um(e.expression);if(!Vm(e))return null;if(b.isFunctionDeclaration(e)||b.isClassDeclaration(e))return e.name?.text??null;if(b.isVariableStatement(e)){let t=e.declarationList.declarations[0];return t!=null&&b.isIdentifier(t.name)?t.name.text:null}return null}function Um(e){return b.isIdentifier(e)?e.text:(b.isFunctionExpression(e)||b.isClassExpression(e))&&e.name!=null?e.name.text:"default"}function Vm(e){if(!b.canHaveModifiers(e))return!1;let t=b.getModifiers(e);return t!=null&&t.some(r=>r.kind===b.SyntaxKind.ExportKeyword)}function bi(e,t){let r=Fm(e,t),n=e.getChildren(t).flatMap(o=>bi(o,t));return r==null?n:[r,...n]}function Fm(e,t){let r=Mm(e);if(r==null)return null;let n=Bm(r);if(n==null)return null;let o=Gm(r,n);return o==null?null:{kind:n,label:o,line:ef(t,e.getStart(t))}}function Mm(e){return b.isJsxSelfClosingElement(e)&&b.isIdentifier(e.tagName)?{attrs:e.attributes,children:[],tag:e.tagName.text}:b.isJsxElement(e)&&b.isIdentifier(e.openingElement.tagName)?{attrs:e.openingElement.attributes,children:e.children,tag:e.openingElement.tagName.text}:null}function Bm({attrs:e,tag:t}){let r=ce(e,"role");return r!=null?Nm.get(r)??null:Wm(t,e)??qm(t)??zm(e)}var Hm=new Map([["button",()=>"click"],["a",e=>ce(e,"href")==null?null:"navigate"],["input",e=>ce(e,"type")==="file"?"upload":"input"],["textarea",()=>"input"],["select",()=>"select"],["form",()=>"submit"]]);function Wm(e,t){return Hm.get(e)?.(t)??null}function qm(e){return/^[A-Z]/.test(e)?Om.find(([t])=>t.test(e))?.[1]??null:null}function zm(e){return wi.find(([t])=>Ym(e,t))?.[1]??null}function Gm({attrs:e,children:t,tag:r},n){return n==="navigate"?ce(e,"href")??ce(e,"to"):ce(e,"aria-label")??ce(e,"label")??ce(e,"title")??ce(e,"name")??ce(e,"placeholder")??(Km(r)?void 0:Zm(t))??Jm(e,n)}function Km(e){return e==="input"||e==="textarea"||e==="select"}function Jm(e,t){let r=wi.find(([,o])=>o===t)?.[0];if(r==null)return;let n=Xm(e,r);if(n!=null){if(b.isIdentifier(n))return n.text;if(b.isArrowFunction(n)||b.isFunctionExpression(n))return vi(n.body)}}function vi(e){if(b.isCallExpression(e)){let t=e.expression;return b.isIdentifier(t)?t.text:b.isPropertyAccessExpression(t)?t.name.text:void 0}return b.forEachChild(e,vi)}function Ym(e,t){return e.properties.some(r=>b.isJsxAttribute(r)&&b.isIdentifier(r.name)&&r.name.text===t)}function Si(e,t){return e.properties.find(r=>b.isJsxAttribute(r)&&b.isIdentifier(r.name)&&r.name.text===t)}function ce(e,t){let r=Si(e,t);return r==null?void 0:Qm(r.initializer)}function Xm(e,t){let r=Si(e,t);if(!(r?.initializer==null||!b.isJsxExpression(r.initializer)))return r.initializer.expression}function Qm(e){if(e==null)return"";if(b.isStringLiteral(e))return e.text;if(b.isJsxExpression(e))return Ri(e.expression)}function Zm(e){let t=e.flatMap(r=>ki(r)).join(" ").trim();return t.length===0?void 0:t}function ki(e){if(b.isJsxText(e)){let t=e.text.trim();return t.length===0?[]:[t]}if(b.isJsxExpression(e)){let t=Ri(e.expression);return t==null?[]:[t]}return b.isJsxElement(e)?e.children.flatMap(t=>ki(t)):[]}function Ri(e){if(e!=null){if(b.isStringLiteral(e)||b.isNoSubstitutionTemplateLiteral(e))return e.text;if(b.isCallExpression(e)&&e.arguments.length===1){let t=e.arguments[0];if(t!=null&&(b.isStringLiteral(t)||b.isNoSubstitutionTemplateLiteral(t)))return t.text}}}function ef(e,t){return e.getLineAndCharacterOfPosition(t).line+1}var rf=Zt.join(".ripplo","coverage.d.ts");function qe({cwd:e}){nf({cwd:e,ignorePaths:Pe})}function nf({cwd:e,ignorePaths:t}){let r=ze({cwd:e,ignorePaths:t});af({content:sf(r),cwd:e})}function ze({cwd:e,ignorePaths:t}){let n=of({cwd:e,ignorePaths:t}).flatMap(o=>kn({cwd:e,file:o}));return[...new Set(n)].sort((o,i)=>o.localeCompare(i))}function of({cwd:e,ignorePaths:t}){let r=z(["ls-files","--cached","--others","--exclude-standard","-z"],e),n=tf([...t]);return r.split("\0").filter(o=>o.length>0&&/\.(tsx|jsx)$/.test(o)).filter(o=>!n(o)).filter(o=>ft.existsSync(Zt.join(e,o)))}function kn({cwd:e,file:t}){let r=ft.readFileSync(Zt.join(e,t),"utf8");return Qt({filePath:t,source:r}).map(n=>n.id)}function sf(e){let t=`// GENERATED \u2014 do not edit
|
|
241
241
|
import "@ripplo/testing";
|
|
242
242
|
|
|
243
243
|
declare module "@ripplo/testing" {
|
|
@@ -255,7 +255,7 @@ declare module "@ripplo/testing" {
|
|
|
255
255
|
`);return}let i=o==="missing"?"missing":"out of date";process.stderr.write(`${ae} is ${i} \u2014 run \`ripplo compile\` and commit the result
|
|
256
256
|
`),process.stderr.write(`${w("setup")}
|
|
257
257
|
`),process.exit(1)}await le({cwd:t,result:r.result}),qe({cwd:t}),process.stdout.write(`wrote ${ae}
|
|
258
|
-
`)}import pe from"process";import gf from"fs";import yf from"path";import hf from"picomatch";function Ci({compileResult:e,cwd:t,ignorePaths:r}){let n=new Set(ze({cwd:t,ignorePaths:r})),o=
|
|
258
|
+
`)}import pe from"process";import gf from"fs";import yf from"path";import hf from"picomatch";function Ci({compileResult:e,cwd:t,ignorePaths:r}){let n=new Set(ze({cwd:t,ignorePaths:r})),o=Ii(e),i=wf({cwd:t,ignorePaths:r});return Ai({acknowledged:o,allStatements:n,unacked:i})}function Ti({compileResult:e,cwd:t,ignorePaths:r}){let n=new Set(ze({cwd:t,ignorePaths:r})),o=Ii(e);return Ai({acknowledged:o,allStatements:n,unacked:n})}function Ai({acknowledged:e,allStatements:t,unacked:r}){let n=[...r].filter(i=>!e.has(i)).map(i=>({id:i,kind:"unacknowledged"})),o=[...e].filter(i=>!t.has(i)).map(i=>({id:i,kind:"stale"}));return[...n,...o]}function Ii(e){return new Set(e.tests.flatMap(t=>t.coverage))}function wf({cwd:e,ignorePaths:t}){let r=bf({cwd:e,ignorePaths:t}),n=new Set(r.flatMap(i=>vf({cwd:e,file:i}))),o=new Set(r.flatMap(i=>Sf({cwd:e,file:i})?kn({cwd:e,file:i}):[]));return new Set([...o].filter(i=>!n.has(i)))}function bf({cwd:e,ignorePaths:t}){let r=z(["diff","--name-only","HEAD","-z"],e),n=z(["ls-files","--others","--exclude-standard","-z"],e),o=hf([...t]);return[...new Set([...r.split("\0"),...n.split("\0")])].filter(i=>i.length>0&&/\.(tsx|jsx)$/.test(i)).filter(i=>!o(i))}function vf({cwd:e,file:t}){let r=yi(`HEAD:${t}`,e);return r==null?[]:Qt({filePath:t,source:r}).map(n=>n.id)}function Sf({cwd:e,file:t}){return gf.existsSync(yf.join(e,t))}async function $i(){let e=pe.cwd(),t=await P(e);t.ok||(pe.stderr.write(`Compilation failed: ${t.error}
|
|
259
259
|
`),pe.exit(1));let r=ze({cwd:e,ignorePaths:Pe}),n=Ti({compileResult:t.result,cwd:e,ignorePaths:Pe}),o=n.filter(a=>a.kind==="unacknowledged"),i=n.filter(a=>a.kind==="stale"),s=r.length-o.length;pe.stdout.write(`Coverage: ${String(s)}/${String(r.length)} statements acknowledged
|
|
260
260
|
`),o.length>0&&(pe.stdout.write(`
|
|
261
261
|
Unacknowledged (${String(o.length)}):
|
|
@@ -272,7 +272,7 @@ Stale claims (${String(i.length)}):
|
|
|
272
272
|
}
|
|
273
273
|
}
|
|
274
274
|
}
|
|
275
|
-
`);function Li(e){switch(e.status){case"active":return e.gitMidOperation?"\u2713 Dev session: ripplo watch is live (hooks auto-paused \u2014 git is mid-merge/rebase/cherry-pick; resumes when the operation completes or aborts)":"\u2713 Dev session: ripplo watch is live for this directory";case"starting":return"! Dev session: `ripplo watch` is running locally but hasn't registered with the server yet. Wait a few seconds and re-run `npx ripplo doctor`. If it persists, check the watch process output for auth/network errors.";case"missing":return"\u2717 Dev session: no active ripplo watch. Start `npx ripplo watch` as a background process (separate from your app's dev server). Without it, `ripplo run` will refuse to dispatch and scope/coverage hooks won't arm."}}async function _i(e){let t=Ge(e),r=er(e),n;try{n=M(e)}catch{return{gitMidOperation:r,status:t?"starting":"missing",type:"dev-session"}}return(await y({config:n,document:Cf,variables:{cwd:n.cwd,projectId:n.projectId}}).catch(()=>null))?.project?.devSession!=null?{gitMidOperation:r,status:"active",type:"dev-session"}:{gitMidOperation:r,status:t?"starting":"missing",type:"dev-session"}}function Ui(e){switch(e.type){case"settings":return $f(e);case"env-files":return jf(e);case"token":return Nf(e);case"dev-server":return Of(e);case"dev-session":return Li(e);case"preconditions":return _f(e);case"webhook-verification":return Df(e);case"preconditions-validation":return Uf(e);case"workflows":return Vf(e);case"browser":return Lf(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 Tf(e);case"lockfile":return
|
|
275
|
+
`);function Li(e){switch(e.status){case"active":return e.gitMidOperation?"\u2713 Dev session: ripplo watch is live (hooks auto-paused \u2014 git is mid-merge/rebase/cherry-pick; resumes when the operation completes or aborts)":"\u2713 Dev session: ripplo watch is live for this directory";case"starting":return"! Dev session: `ripplo watch` is running locally but hasn't registered with the server yet. Wait a few seconds and re-run `npx ripplo doctor`. If it persists, check the watch process output for auth/network errors.";case"missing":return"\u2717 Dev session: no active ripplo watch. Start `npx ripplo watch` as a background process (separate from your app's dev server). Without it, `ripplo run` will refuse to dispatch and scope/coverage hooks won't arm."}}async function _i(e){let t=Ge(e),r=er(e),n;try{n=M(e)}catch{return{gitMidOperation:r,status:t?"starting":"missing",type:"dev-session"}}return(await y({config:n,document:Cf,variables:{cwd:n.cwd,projectId:n.projectId}}).catch(()=>null))?.project?.devSession!=null?{gitMidOperation:r,status:"active",type:"dev-session"}:{gitMidOperation:r,status:t?"starting":"missing",type:"dev-session"}}function Ui(e){switch(e.type){case"settings":return $f(e);case"env-files":return jf(e);case"token":return Nf(e);case"dev-server":return Of(e);case"dev-session":return Li(e);case"preconditions":return _f(e);case"webhook-verification":return Df(e);case"preconditions-validation":return Uf(e);case"workflows":return Vf(e);case"browser":return Lf(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 Tf(e);case"lockfile":return Af(e);case"pre-commit-hook":return If(e)}}function Tf(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 Af(e){switch(e.status){case"match":return`\u2713 Lockfile: ${ae} is up to date`;case"missing":return`\u2717 Lockfile: ${ae} is missing \u2014 run \`ripplo compile\` and commit it`;case"stale":return`\u2717 Lockfile: ${ae} is out of date \u2014 run \`ripplo compile\` and commit it`}}function If(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 $f(e){return e.valid?"\u2713 Settings: Project configured":`\u2717 Settings: Missing fields: ${e.missingFields.join(", ")}`}function jf(e){return e.missing.length===0?"\u2713 Env files: declared files present":`\u2717 Env files: declared in .ripplo/project.json but missing:
|
|
276
276
|
${e.missing.map(r=>` ${r}`).join(`
|
|
277
277
|
`)}
|
|
278
278
|
If you're in a git worktree, copy the env file from the main checkout (or symlink to a shared file outside the working tree).`}function Nf(e){switch(e.status){case"valid":return`\u2713 Auth: Signed in as ${e.email??"unknown"}`;case"missing":return"\u2717 Auth: No token found. Run `ripplo` to authenticate.";case"invalid":return"\u2717 Auth: Saved token rejected by server. Run `ripplo auth login` to re-authenticate.";case"unreachable":return`! Auth: Could not reach ${Z()} to validate token.`}}function Of(e){return e.reachable?`\u2713 Dev server: ${e.appUrl} is reachable`:`\u2717 Dev server: ${e.appUrl} is not responding. Make sure your dev server is running.`}function Df(e){return e.rejectsUnsigned?"\u2713 Webhook verification: Unsigned requests are correctly rejected":"\u2717 Webhook verification: Endpoint accepted an unsigned request \u2014 webhook signature verification may be missing or misconfigured."}function Lf(e){return e.installed?"\u2713 Browser: Chromium installed":"\u2717 Browser: Chromium not installed. Run: npx playwright install chromium"}function _f(e){return e.count===0?"! Preconditions: None defined":e.configured?e.endpointReachable===void 0?`! Preconditions: ${String(e.count)} defined (could not verify endpoint)`:`\u2713 Preconditions: ${String(e.count)} defined, endpoint configured`:`\u2717 Preconditions: ${String(e.count)} defined but RIPPLO_ENGINE_URL is not set in your env file`}function Uf(e){if(!e.found)return"\u2717 State graph: DSL compilation failed";if(e.valid)return"\u2713 State graph: Valid";let t=e.errors.map(r=>` - ${r.path===""?"":r.path+": "}${r.message}`);return`\u2717 State graph: ${String(e.errorCount)} validation error${e.errorCount===1?"":"s"}
|
|
@@ -309,8 +309,8 @@ ${t.join(`
|
|
|
309
309
|
hooksPaused
|
|
310
310
|
}
|
|
311
311
|
}
|
|
312
|
-
`);async function yt(e){let t=dg(e.compiled);return mg({config:e.config,cwd:e.cwd,payload:t})}async function me(e,t){let r=await P(e);if(!r.ok)throw new Error(`DSL compilation failed: ${r.error}`);let n=await yt({compiled:r.result,config:t,cwd:e});return{compiled:r.result,devSessionId:n.devSessionId}}function dg(e){return{preconditions:Object.entries(e.preconditions).map(([t,r])=>({depends:[...r.depends??[]],description:r.description,name:t,returns:[...r.returns??[]]})),workflows:e.tests.map(t=>({expectedOutcome:t.expectedOutcome,name:t.name,preconditions:[...t.preconditions],requiresKeys:Object.entries(t.requiresKeys).map(([r,n])=>({namespace:r,preconditionName:n})),slug:t.slug,sourcePath:t.sourcePath??null,spec:t.implemented?JSON.stringify(t.spec):null}))}}function pg(e){return lg.createHash("sha256").update(JSON.stringify(e)).digest("hex")}async function mg({config:e,cwd:t,payload:r}){let n=pg(r),o=tr(t),i=await y({config:e,document:ug,variables:{branch:o??null,cwd:t,preconditions:r.preconditions.map(s=>({depends:[...s.depends],description:s.description,name:s.name,returns:[...s.returns]})),projectId:e.projectId,workflows:r.workflows.map(s=>({expectedOutcome:s.expectedOutcome,name:s.name,preconditions:[...s.preconditions],requiresKeys:s.requiresKeys.map(a=>({namespace:a.namespace,preconditionName:a.preconditionName})),slug:s.slug,sourcePath:s.sourcePath,spec:s.spec??null}))}});if(i.syncDevSession==null)throw new Error("syncDevSession returned null");return{devSessionId:i.syncDevSession.id,hash:n,hooksPaused:i.syncDevSession.hooksPaused}}import{graphql as ht,readFragment as wg}from"gql.tada";import{createHash as zi}from"crypto";import{mkdirSync as fg,readFileSync as
|
|
313
|
-
`).filter(n=>n.length>0).filter(n=>yg.some(o=>n.endsWith(o))).toSorted((n,o)=>n.localeCompare(o)).forEach(n=>{t.update(n),t.update("\0"),t.update(hg(rr.join(e,n))),t.update("\0")}),t.digest("hex")}function Gi(e){let t=rr.join(e,".ripplo","ripplo.lock");try{let r=
|
|
312
|
+
`);async function yt(e){let t=dg(e.compiled);return mg({config:e.config,cwd:e.cwd,payload:t})}async function me(e,t){let r=await P(e);if(!r.ok)throw new Error(`DSL compilation failed: ${r.error}`);let n=await yt({compiled:r.result,config:t,cwd:e});return{compiled:r.result,devSessionId:n.devSessionId}}function dg(e){return{preconditions:Object.entries(e.preconditions).map(([t,r])=>({depends:[...r.depends??[]],description:r.description,name:t,returns:[...r.returns??[]]})),workflows:e.tests.map(t=>({expectedOutcome:t.expectedOutcome,name:t.name,preconditions:[...t.preconditions],requiresKeys:Object.entries(t.requiresKeys).map(([r,n])=>({namespace:r,preconditionName:n})),slug:t.slug,sourcePath:t.sourcePath??null,spec:t.implemented?JSON.stringify(t.spec):null}))}}function pg(e){return lg.createHash("sha256").update(JSON.stringify(e)).digest("hex")}async function mg({config:e,cwd:t,payload:r}){let n=pg(r),o=tr(t),i=await y({config:e,document:ug,variables:{branch:o??null,cwd:t,preconditions:r.preconditions.map(s=>({depends:[...s.depends],description:s.description,name:s.name,returns:[...s.returns]})),projectId:e.projectId,workflows:r.workflows.map(s=>({expectedOutcome:s.expectedOutcome,name:s.name,preconditions:[...s.preconditions],requiresKeys:s.requiresKeys.map(a=>({namespace:a.namespace,preconditionName:a.preconditionName})),slug:s.slug,sourcePath:s.sourcePath,spec:s.spec??null}))}});if(i.syncDevSession==null)throw new Error("syncDevSession returned null");return{devSessionId:i.syncDevSession.id,hash:n,hooksPaused:i.syncDevSession.hooksPaused}}import{graphql as ht,readFragment as wg}from"gql.tada";import{createHash as zi}from"crypto";import{mkdirSync as fg,readFileSync as An,writeFileSync as gg}from"fs";import rr from"path";var yg=[".ts",".tsx",".js",".jsx"];function xe(e){let t=zi("sha256");return t.update(z(["rev-parse","HEAD"],e)),t.update("\0"),t.update(z(["diff","HEAD"],e)),t.update("\0"),z(["ls-files","--others","--exclude-standard"],e).split(`
|
|
313
|
+
`).filter(n=>n.length>0).filter(n=>yg.some(o=>n.endsWith(o))).toSorted((n,o)=>n.localeCompare(o)).forEach(n=>{t.update(n),t.update("\0"),t.update(hg(rr.join(e,n))),t.update("\0")}),t.digest("hex")}function Gi(e){let t=rr.join(e,".ripplo","ripplo.lock");try{let r=An(t);return zi("sha256").update(r).digest("hex")}catch{return null}}function Ke(e,t){try{return An(Ki(e,t),"utf8").trim()}catch{return null}}function Je(e,t,r){let n=Ki(e,t);fg(rr.dirname(n),{recursive:!0}),gg(n,r)}function Ki(e,t){return rr.join(e,".ripplo",".local",`${t}.hash`)}function hg(e){try{return An(e)}catch{return Buffer.alloc(0)}}import Ji from"figures";var je={cross:Ji.cross,tick:Ji.tick};var Xi=ht(`
|
|
314
314
|
fragment WorkflowIdMCP on Workflow {
|
|
315
315
|
id
|
|
316
316
|
slug
|
|
@@ -380,7 +380,7 @@ ${a.summary}`).join(`
|
|
|
380
380
|
|
|
381
381
|
`);return{results:i,summary:s}}async function Rg({config:e,ids:t,presynced:r}){let n=r??await me(e.cwd,e),o=await y({config:e,document:bg,variables:{cwd:e.cwd,projectId:e.projectId}});if(o.project==null)throw new Error("Project not found");let i=o.project.devSession;if(i==null)throw new Error("No active dev session. Start one by running `ripplo` (or `npx ripplo`) in your terminal, then try again.");await y({config:e,document:vg,variables:{devSessionId:i.id,projectId:e.projectId}});let s=(i.workflows??[]).map(l=>wg(Xi,l));if(t.length===0)return s.map(l=>({id:l.slug,workflowId:l.id}));let a=n.compiled.tests.map(l=>l.slug);return t.map(l=>{let c=s.find(p=>p.slug===l);if(c==null)throw new Error(Pg({compiledSlugs:a,slug:l}));return{id:l,workflowId:c.id}})}function Pg({compiledSlugs:e,slug:t}){if(e.includes(t))return`Test "${t}" was synced from .ripplo/ but the server didn't return it. This is likely a server-state bug \u2014 check the server logs for the SyncDevSession mutation.`;let r=xg({compiledSlugs:e,limit:3,slug:t}),n=r.length>0?`
|
|
382
382
|
Did you mean: ${r.join(", ")}?`:"";return`Test "${t}" is not registered in this dev session.${n}
|
|
383
|
-
Tests must be exported from .ripplo/tests/index.ts. (ripplo run already syncs on demand \u2014 restarting the dev server will not help.)`}function xg({compiledSlugs:e,limit:t,slug:r}){let n=new Set(r.split("-"));return e.map(i=>({candidate:i,score:Eg(n,i)})).filter(i=>i.score>0).toSorted((i,s)=>s.score-i.score).slice(0,t).map(i=>i.candidate)}function Eg(e,t){return t.split("-").filter(r=>e.has(r)).length}function Cg({config:e,id:t,runId:r}){let n=e.ripploServerUrl.replace(/:3000\b/,":3001"),o=new URL(n.endsWith("/")?n:`${n}/`);return new URL(`projects/${e.projectId}/workflows/${t}/runs/${r}`,o).toString()}async function Tg({config:e,workflowId:t}){let r=await y({config:e,document:Sg,variables:{lockfileHash:Gi(e.cwd),repoHash:
|
|
383
|
+
Tests must be exported from .ripplo/tests/index.ts. (ripplo run already syncs on demand \u2014 restarting the dev server will not help.)`}function xg({compiledSlugs:e,limit:t,slug:r}){let n=new Set(r.split("-"));return e.map(i=>({candidate:i,score:Eg(n,i)})).filter(i=>i.score>0).toSorted((i,s)=>s.score-i.score).slice(0,t).map(i=>i.candidate)}function Eg(e,t){return t.split("-").filter(r=>e.has(r)).length}function Cg({config:e,id:t,runId:r}){let n=e.ripploServerUrl.replace(/:3000\b/,":3001"),o=new URL(n.endsWith("/")?n:`${n}/`);return new URL(`projects/${e.projectId}/workflows/${t}/runs/${r}`,o).toString()}async function Tg({config:e,workflowId:t}){let r=await y({config:e,document:Sg,variables:{lockfileHash:Gi(e.cwd),repoHash:Ag(e.cwd),workflowId:t}});if(r.createRun==null)throw new Error("Failed to create run");return r.createRun.id}function Ag(e){try{return xe(e)}catch{return null}}var Ig=2e3,Yi=150;async function $g({config:e,runId:t}){let r=0;for(;r<Yi;){await Og(Ig),r+=1;let o=(await y({config:e,document:kg,variables:{id:t}})).run;if(o==null)throw new Error(`Run ${t} not found`);if(!(o.status==="pending"||o.status==="running"))return jg({run:o,runId:t})}return`Run ${t} timed out after polling ${String(Yi)} times.`}function jg({run:e,runId:t}){let r=[`Run ${t}: ${e.status.toUpperCase()}`],n=Ng(e);return n!=null&&r.push(n),r.push(` ${e.status}: ${String(e.passCount)} passed, ${String(e.failCount)} failed (${String(e.duration??0)}ms)`),e.summary!=null&&r.push(` Summary: ${e.summary}`),e.traceEntries.forEach(o=>{let i=o.status==="passed"?je.tick:je.cross,s=o.detail==null?"":` \u2014 ${o.detail}`;r.push(` ${i} ${o.title} (${String(o.duration)}ms)${s}`),o.assertions.forEach(a=>{let l=a.status==="passed"?je.tick:je.cross,c=a.detail==null?"":` \u2014 ${a.detail}`;r.push(` ${l} ${a.description}${c}`)})}),r.join(`
|
|
384
384
|
`)}function Ng(e){if(e.caughtKind==null)return null;let t=e.workflow?.slug??"workflow";return e.caughtKind==="new_test"?` ${je.tick} ripplo caught a bug \u2014 new test "${t}" surfaced an issue in your app code`:` ${je.tick} ripplo caught a regression in "${t}"`}function Og(e){return new Promise(t=>{setTimeout(t,e)})}import{graphql as Dg}from"gql.tada";var Lg=Dg(`
|
|
385
385
|
query DevSessionCheckPreflight($projectId: String!, $cwd: String!) {
|
|
386
386
|
project(id: $projectId) {
|
|
@@ -406,7 +406,7 @@ Tests must be exported from .ripplo/tests/index.ts. (ripplo run already syncs on
|
|
|
406
406
|
}
|
|
407
407
|
`);async function Zi(){process.stdin.isTTY||(process.stderr.write("`ripplo hooks pause` must be invoked interactively from a terminal \u2014 refusing non-TTY invocation. Bypassing the gate is a human decision, not an agent decision.\n"),process.exit(1));let e=process.cwd();at(e);let t=Ee(e);if(or.existsSync(t)){process.stdout.write("Hooks already paused. Run `ripplo hooks resume` to re-enable.\n");return}or.writeFileSync(t,""),await ts(e,!0),process.stdout.write("Hooks paused. Pre-edit gates and stop enforcement are off until you run `ripplo hooks resume`.\n")}async function es(){let e=process.cwd(),t=Ee(e);if(!or.existsSync(t)){process.stdout.write(`Hooks already active.
|
|
408
408
|
`);return}or.unlinkSync(t),await ts(e,!1),process.stdout.write(`Hooks resumed.
|
|
409
|
-
`)}async function ts(e,t){let r;try{r=M(e)}catch{return}await y({config:r,document:Vg,variables:{paused:t,projectId:r.projectId}}).catch(()=>null)}import Ye from"fs";import Xe from"path";import{input as os,select as is}from"@inquirer/prompts";import{graphql as iy}from"gql.tada";import{exec as Fg}from"child_process";import V from"fs";import B from"path";import{promisify as Mg}from"util";var Bg=["@ripplo/testing"],rs=".ripplo/ripplo.lock linguist-generated=true",Hg=[".ripplo/debug/",".ripplo/.local/"],Wg=Mg(Fg);async function ns({cwd:e,onStep:t}){t("Scaffolding project files..."),Qg({cwd:e}),t("Updating .gitignore..."),Zg(e),t("Marking ripplo.lock as generated..."),Gg(e),t("Installing dependencies...");let r=await qg(e),n=[];if(r.ok||n.push({manualCommand:r.cmd,message:`Couldn't auto-install dev dependencies (${r.reason}). Run the command below, then run \`ripplo lint\` to compile the lockfile.`}),r.ok){t("Compiling initial lockfile...");let o=await zg(e);o!=null&&n.push({manualCommand:void 0,message:o})}return t("Setting up browser..."),await
|
|
409
|
+
`)}async function ts(e,t){let r;try{r=M(e)}catch{return}await y({config:r,document:Vg,variables:{paused:t,projectId:r.projectId}}).catch(()=>null)}import Ye from"fs";import Xe from"path";import{input as os,select as is}from"@inquirer/prompts";import{graphql as iy}from"gql.tada";import{exec as Fg}from"child_process";import V from"fs";import B from"path";import{promisify as Mg}from"util";var Bg=["@ripplo/testing"],rs=".ripplo/ripplo.lock linguist-generated=true",Hg=[".ripplo/debug/",".ripplo/.local/"],Wg=Mg(Fg);async function ns({cwd:e,onStep:t}){t("Scaffolding project files..."),Qg({cwd:e}),t("Updating .gitignore..."),Zg(e),t("Marking ripplo.lock as generated..."),Gg(e),t("Installing dependencies...");let r=await qg(e),n=[];if(r.ok||n.push({manualCommand:r.cmd,message:`Couldn't auto-install dev dependencies (${r.reason}). Run the command below, then run \`ripplo lint\` to compile the lockfile.`}),r.ok){t("Compiling initial lockfile...");let o=await zg(e);o!=null&&n.push({manualCommand:void 0,message:o})}return t("Setting up browser..."),await Ar(),n}async function qg(e){let t=Kg({cwd:e,pm:Xg(e)});f.info("Installing dependencies: %s",t);try{return await Wg(t,{cwd:e}),{ok:!0}}catch(r){let n=r instanceof Error?r.message.split(`
|
|
410
410
|
`)[0]??r.message:String(r);return f.warn("Install failed (%s): %s",t,n),{cmd:t,ok:!1,reason:n}}}async function zg(e){try{let t=await P(e);if(!t.ok)return;await le({cwd:e,result:t.result});return}catch(t){return`Couldn't compile initial lockfile: ${t instanceof Error?t.message:String(t)}.`}}function Gg(e){let t=B.join(e,".gitattributes"),r=V.existsSync(t)?V.readFileSync(t,"utf8"):"";if(r.includes(rs))return;let n=r.length===0||r.endsWith(`
|
|
411
411
|
`)?"":`
|
|
412
412
|
`;V.writeFileSync(t,`${r}${n}${rs}
|
|
@@ -479,7 +479,7 @@ export const tests = [] as const;
|
|
|
479
479
|
name
|
|
480
480
|
}
|
|
481
481
|
}
|
|
482
|
-
`),
|
|
482
|
+
`),In=["../.env.local","../.env"];async function ss(e=cy()){let t=process.cwd(),r=ie();r==null&&(process.stdout.write("Not authenticated. Run `ripplo auth login` first.\n"),process.exit(1));let n=Z();ay(t)&&(process.stdout.write(`\`.ripplo/index.ts\` already exists at ${t}. Delete it first if you want to re-init.
|
|
483
483
|
`),process.exit(1));let o=await ly({serverUrl:n,token:r});o.length===0&&(process.stdout.write("No projects found. Create one in the dashboard first, then re-run `ripplo init`.\n"),process.exit(1));let i=await dy(o,e.projectId),s=await py(t,e.envFile),a=await my(e.appUrl),l=uy(a,e.engineUrl),c=Xe.resolve(Xe.join(t,".ripplo"),s);Vo({cwd:t,envFiles:[s],projectId:i}),yy({appUrl:a,engineUrl:l,filePath:c});let p=await ns({cwd:t,onStep:m=>{process.stdout.write(` ${m}
|
|
484
484
|
`)}});if(p.length>0){process.stdout.write(`Done with warnings:
|
|
485
485
|
`),p.forEach(m=>{process.stdout.write(` - ${m.message}
|
|
@@ -490,7 +490,7 @@ export const tests = [] as const;
|
|
|
490
490
|
`),r.id}if(e.length===1){let r=e[0];if(r==null)throw new Error("unreachable");return process.stdout.write(`Using project: ${r.name} (${r.id})
|
|
491
491
|
`),r.id}return is({choices:e.map(r=>({name:r.name,value:r.id})),message:"Select a project"})}async function py(e,t){return t!=null?(t.trim().length===0&&(process.stdout.write(`--env must not be empty
|
|
492
492
|
`),process.exit(1)),t):fy(e)}async function my(e){if(e!=null){try{new URL(e)}catch{process.stdout.write(`--app-url is not a valid URL: ${e}
|
|
493
|
-
`),process.exit(1)}return e}return gy()}async function fy(e){let t=Xe.join(e,".ripplo"),r=
|
|
493
|
+
`),process.exit(1)}return e}return gy()}async function fy(e){let t=Xe.join(e,".ripplo"),r=In.find(o=>Ye.existsSync(Xe.resolve(t,o))),n=await is({choices:[...In.map(o=>({name:r===o?`${o} (detected)`:o,value:o})),{name:"custom path",value:"__custom__"}],default:r??In[0],message:"Which env file should ripplo write RIPPLO_APP_URL, RIPPLO_ENGINE_URL, RIPPLO_WEBHOOK_SECRET, and ENABLE_RIPPLO_TESTING to?"});return n!=="__custom__"?n:os({message:"Path to env file (relative to .ripplo/, e.g. ../apps/server/.env)",validate:o=>o.trim().length>0?!0:"required"})}async function gy(){return os({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 yy({appUrl:e,engineUrl:t,filePath:r}){Ye.mkdirSync(Xe.dirname(r),{recursive:!0});let n=Ye.existsSync(r)?Ye.readFileSync(r,"utf8"):"",o=[];if(/^RIPPLO_APP_URL=/m.test(n)||o.push(`RIPPLO_APP_URL=${e}`),/^RIPPLO_ENGINE_URL=/m.test(n)||o.push(`RIPPLO_ENGINE_URL=${t}`),/^RIPPLO_WEBHOOK_SECRET=/m.test(n)||o.push(`RIPPLO_WEBHOOK_SECRET=${Br()}`),/^ENABLE_RIPPLO_TESTING=/m.test(n)||o.push("ENABLE_RIPPLO_TESTING=true"),o.length===0)return;let i=n.length===0||n.endsWith(`
|
|
494
494
|
`)?"":`
|
|
495
495
|
`;Ye.writeFileSync(r,`${n}${i}${o.join(`
|
|
496
496
|
`)}
|
|
@@ -548,10 +548,10 @@ ${String(m)} error(s)
|
|
|
548
548
|
}
|
|
549
549
|
}
|
|
550
550
|
`);async function ds({all:e,ids:t}){e&&t.length>0&&(process.stderr.write(`Pass either --all or test ids, not both.
|
|
551
|
-
`),process.exit(1));let r=ue();await fe(r);let n=await
|
|
551
|
+
`),process.exit(1));let r=ue();await fe(r);let n=await Ay({all:e,cwd:r.cwd,ids:t});n==null&&process.exit(1);let{results:o,summary:i}=await nr({config:r,ids:n,presynced:void 0});process.stdout.write(`${i}
|
|
552
552
|
`);let s=o.some(a=>a.summary.includes("FAILED")||a.summary.includes("ERROR"));s&&(process.stderr.write(`Artifacts in .ripplo/debug/<runId>/ \u2014 read before re-running.
|
|
553
553
|
`),process.stderr.write(`${w("debug")}
|
|
554
|
-
`)),process.exit(s?1:0)}async function
|
|
554
|
+
`)),process.exit(s?1:0)}async function Ay({all:e,cwd:t,ids:r}){return r.length>0?r:e?[]:Iy(t)}async function Iy(e){let t=ue(),r=await P(e);if(r.ok){let{addedSlugs:a}=await Qe({compileResult:r,cwd:e});a.length>0&&process.stdout.write(`Auto-scoped ${a.join(", ")} (dirty tests).
|
|
555
555
|
`)}let o=(await y({config:t,document:ir,variables:{cwd:t.cwd,projectId:t.projectId}})).project?.devSession?.scopeItems??[],i=o.flatMap(a=>a.workflow!=null&&a.workflow.spec!=null?[a.workflow.slug]:[]),s=o.flatMap(a=>a.workflow==null?[`[intent] ${a.label??"(no label)"}`]:a.workflow.spec==null?[`[stub] ${a.workflow.slug}`]:[]);return s.length>0&&process.stdout.write(`Skipped non-runnable scope items: ${s.join(", ")}
|
|
556
556
|
`),i.length===0?(process.stderr.write("No runnable tests in scope. Add tests with `ripplo scope add <id>`, or run the full suite with `ripplo run --all`.\n"),process.stderr.write(`${w("scope")}
|
|
557
557
|
`),null):i}async function ps(){let e=process.cwd(),t=M(e);try{let r=await me(t.cwd,t),n=r.compiled.tests.length,o=Object.keys(r.compiled.preconditions).length;process.stdout.write(`synced ${String(n)} tests, ${String(o)} preconditions to dev session ${r.devSessionId}
|
|
@@ -644,13 +644,13 @@ ${String(m)} error(s)
|
|
|
644
644
|
`),process.exit(1)),n.id}async function Rs(e){let t=process.cwd(),r=await P(t);r.ok||(process.stderr.write(`Compilation failed: ${r.error}
|
|
645
645
|
`),process.exit(1));let{tests:n}=r.builder.getUnimplemented();if(e.format==="summary"){n.length>0&&process.stdout.write(`tests: ${n.join(", ")}
|
|
646
646
|
`);return}let o={tests:n.map(i=>({id:i,implemented:!1}))};process.stdout.write(`${JSON.stringify(o,null,2)}
|
|
647
|
-
`)}import{z as uh}from"zod";function
|
|
647
|
+
`)}import{z as uh}from"zod";function I(e,t){let r=uh.custom(n=>typeof n=="object"&&n!==null&&"hook_event_name"in n&&n.hook_event_name===e);return{event:e,run:async n=>await t(r.parse(n))??void 0}}import{createHash as oT}from"crypto";import Ps from"picomatch";function dh(e){return z(["diff","--name-only","HEAD"],e).split(`
|
|
648
648
|
`).filter(t=>t.length>0)}function xs({cwd:e,ignoreGlobs:t,watchGlobs:r}){let n=Ps([...r]),o=Ps([...t]);return dh(e).filter(i=>n(i)&&!o(i))}function lr(e,...t){return z(["diff","--name-only","HEAD","--",...t],e).split(`
|
|
649
|
-
`).filter(r=>r.length>0)}function Te(){return{ignorePaths:Pe,watchPaths:bn}}var Es=
|
|
650
|
-
`),hookEventName:"UserPromptSubmit"}}});import fh from"path";import
|
|
651
|
-
${w("create","DSL authoring + lint rules")}`};
|
|
649
|
+
`).filter(r=>r.length>0)}function Te(){return{ignorePaths:Pe,watchPaths:bn}}var Es=I("UserPromptSubmit",e=>{let{cwd:t}=e;if(!A(t)||!_(t))return;let r=xe(t);if(Ke(t,"coverage-nudge")===r)return;let{ignorePaths:n,watchPaths:o}=Te(),i=xs({cwd:t,ignoreGlobs:n,watchGlobs:o});if(Je(t,"coverage-nudge",r),!(i.length===0||lr(t,".ripplo/tests",".ripplo/preconditions",".ripplo/observers").length>0))return{hookSpecificOutput:{additionalContext:`SCOPE DRIFT: ${String(i.length)} app file(s) changed without .ripplo/tests updates. ${w("scope")}`,hookEventName:"UserPromptSubmit"}}});import cr from"fs";import ph from"os";import Cs from"path";var Ts=I("PreToolUse",e=>{if(e.tool_name!=="ExitPlanMode"||!_(e.cwd))return;let t=mh();if(t==null)return;let r=cr.readFileSync(t,"utf8");if(!/\.ripplo\/tests|Tests to implement|No e2e coverage needed/.test(r))return{hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:`Plan must cite ripplo test stubs. Add a "Tests to implement" section listing .ripplo/tests/<id>.ts per affected flow, OR add "No e2e coverage needed: <reason>" if this plan touches no user-facing behavior. ${w("explore")}`}}});function mh(){let e=Cs.join(ph.homedir(),".claude","plans");return cr.existsSync(e)?cr.readdirSync(e).filter(r=>r.endsWith(".md")).map(r=>Cs.join(e,r)).map(r=>({full:r,mtime:cr.statSync(r).mtimeMs})).sort((r,n)=>n.mtime-r.mtime)[0]?.full??null:null}var As=I("UserPromptSubmit",async e=>{if(e.permission_mode!=="plan"||!A(e.cwd)||!_(e.cwd))return;let t=await P(e.cwd);if(!t.ok)return;let{tests:r}=t.builder.getUnimplemented(),n=['Plan must include "Tests to implement" with .ripplo/tests/<id>.ts per affected flow (ExitPlanMode blocks otherwise).'];return r.length>0&&n.push(`Existing stubs: ${r.join(", ")}`),{hookSpecificOutput:{additionalContext:n.join(`
|
|
650
|
+
`),hookEventName:"UserPromptSubmit"}}});import fh from"path";import Is from"picomatch";import{z as $s}from"zod";var gh=$s.looseObject({file_path:$s.string()}),js=I("PostToolUse",async e=>{let t=gh.safeParse(e.tool_input);if(!t.success)return;let r=t.data.file_path,{cwd:n}=e;if(!A(n)||!_(n))return;let o=fh.relative(n,r);if(o.startsWith(".."))return;let{ignorePaths:i,watchPaths:s}=Te(),a=Is([...s]),l=Is([...i]);if(!a(o)||l(o))return;let c=await P(n);if(!c.ok)return;let{tests:p}=c.builder.getUnimplemented();if(p.length!==0)return{hookSpecificOutput:{additionalContext:`Reminder: .notImplemented() stubs still present \u2014 tests: ${p.join(", ")}`,hookEventName:"PostToolUse"}}});import{z as Ns}from"zod";var yh=Ns.looseObject({file_path:Ns.string()}),Os=I("PostToolUse",async e=>{let t=yh.safeParse(e.tool_input);if(!t.success)return;let r=t.data.file_path;if(!/\/\.ripplo\/.*\.ts$/.test(r))return;let{cwd:n}=e;if(!A(n))return;if(!_(n))return{hookSpecificOutput:{additionalContext:"Ripplo hooks are paused \u2014 DSL lint, lockfile sync, and coverage codegen did not run for this edit. Resume with `npx ripplo hooks resume` when ready.",hookEventName:"PostToolUse"}};let o=await P(n);return o.ok?(await le({cwd:n,result:o.result}),qe({cwd:n}),await hh({compileResult:o,cwd:n})):{decision:"block",reason:`Compilation failed: ${o.error}
|
|
651
|
+
${w("create","DSL authoring + lint rules")}`}});async function hh({compileResult:e,cwd:t}){let{diagnostics:r}=He(e.result);if(r.length>0)return{decision:"block",reason:`${r.map(i=>{let s=i.step==null?"":` at "${i.step}"`;return` [${i.rule}]${s} ${i.test}: ${i.message}`}).join(`
|
|
652
652
|
`)}
|
|
653
|
-
${w("create")}`}});import{z as Ds}from"zod";var
|
|
653
|
+
${w("create")}`};let{addedSlugs:n}=await Qe({compileResult:e,cwd:t});if(n.length!==0)return{hookSpecificOutput:{additionalContext:`Auto-scoped ${n.join(", ")} (dirty tests).`,hookEventName:"PostToolUse"}}}import{z as Ds}from"zod";var wh=Ds.looseObject({command:Ds.string()}),bh=/\bripplo\s+hooks\s+pause\b/,Ls=I("PreToolUse",e=>{if(e.tool_name!=="Bash")return;let t=wh.safeParse(e.tool_input);if(!t.success||!bh.test(t.data.command))return;let{cwd:r}=e;if(A(r))return{hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:"`ripplo hooks pause` is a human-only escape hatch \u2014 agents can't bypass Ripplo guardrails on their own. If watch genuinely can't start (auth, server down, intentional offline work), surface the blocker to the user and ask them to run `npx ripplo hooks pause` themselves from their terminal."}}});import{parse as Ph}from"shell-quote";import{z as Vs}from"zod";import{existsSync as vh,mkdirSync as Sh,rmSync as tA,writeFileSync as kh}from"fs";import On from"path";function _s(e,t,r){let n=Us(e,t,r);Sh(On.dirname(n),{recursive:!0}),kh(n,"")}function ur(e,t,r){return vh(Us(e,t,r))}function Rh(e,t){return On.join(e,".ripplo",".local","skills-loaded",t)}function Us(e,t,r){return On.join(Rh(e,t),r)}var xh=Vs.looseObject({command:Vs.string()}),Eh="debug",Ch=new Set(["tail","head","less","more","wc","sort","uniq","awk","sed","grep"]),Ms=I("PreToolUse",e=>{if(e.tool_name!=="Bash")return;let t=xh.safeParse(e.tool_input);if(!t.success)return;let r=Th(t.data.command);if(!Ah(r))return;let{cwd:n}=e;if(!A(n)||!_(n))return;let o=$h(r);if(o!=null)return Fs(`Don't pipe \`ripplo run\` through \`${o}\` \u2014 buffering filters hold all stdout until EOF, hiding live progress; if you kill the pipeline mid-run the run is orphaned on the server. Redirect to a file instead: \`ripplo run <id> > /tmp/run.log 2>&1\` and Read the file, or use \`run_in_background: true\`.`);if(!ur(n,e.session_id,Eh))return Fs("Running `ripplo run` requires the `/ripplo:debug` skill loaded first. Load `/ripplo:debug` then retry \u2014 it carries the artifact-read order, the 3-strike rule, and the no-grep-piping guidance for run failures.")});function Th(e){try{return Ph(e)}catch{return[]}}function Ah(e){return e.some((t,r)=>t==="ripplo"&&e[r+1]==="run")}function Ih(e){return typeof e=="object"&&"op"in e&&e.op==="|"}function $h(e){let t=e.find((r,n)=>{let o=e[n-1];return o!=null&&Ih(o)&&typeof r=="string"&&Ch.has(r)});return typeof t=="string"?t:null}function Fs(e){return{hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:e}}}import jh from"path";import{z as Bs}from"zod";var Nh=new Set(["Edit","Write","NotebookEdit"]),Oh=Bs.looseObject({file_path:Bs.string()}),Dh="create",Hs=I("PreToolUse",e=>{if(!Nh.has(e.tool_name))return;let t=Oh.safeParse(e.tool_input);if(!t.success)return;let{cwd:r}=e;if(!A(r)||!_(r))return;let n=jh.relative(r,t.data.file_path);if(!(n.startsWith("..")||n!==".ripplo"&&!n.startsWith(".ripplo/"))&&!ur(r,e.session_id,Dh))return{hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:`Editing \`.ripplo/\` files (${n}) requires the \`/ripplo:create\` skill loaded first. Load \`/ripplo:create\` then retry \u2014 it carries the DSL builder shape, lint rules, and the parallelization guidance you'll need.`}}});import Lh from"path";import Ws from"picomatch";import{graphql as _h}from"gql.tada";import{z as qs}from"zod";var Uh=new Set(["Edit","Write","NotebookEdit"]),Vh=qs.looseObject({file_path:qs.string()}),Fh=_h(`
|
|
654
654
|
query PreEditScopeGate($projectId: String!, $cwd: String!) {
|
|
655
655
|
project(id: $projectId) {
|
|
656
656
|
id
|
|
@@ -662,7 +662,9 @@ ${w("create")}`}});import{z as Ds}from"zod";var hh=Ds.looseObject({command:Ds.st
|
|
|
662
662
|
}
|
|
663
663
|
}
|
|
664
664
|
}
|
|
665
|
-
`),zs=
|
|
665
|
+
`),zs=I("PreToolUse",async e=>{if(!Uh.has(e.tool_name))return;let t=Vh.safeParse(e.tool_input);if(!t.success)return;let{cwd:r}=e;if(!A(r)||!_(r))return;let n=Lh.relative(r,t.data.file_path);if(n.startsWith("..")||n===".ripplo"||n.startsWith(".ripplo/")||!Mh(n))return;let o=await Bh(r);return o.populated?o.degradedReason!=null?{hookSpecificOutput:{additionalContext:`Scope check skipped (${o.degradedReason}) \u2014 edit allowed through, but the scope guardrail isn't enforcing on this edit.`,hookEventName:"PreToolUse"}}:void 0:{hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:`Scope empty; edit touches app code (${n}). Stub a test or \`scope add\` an existing one before proceeding \u2014 or acknowledge "no user-facing behavior" if pure refactor. Hook re-fires until scope is populated (or hooks paused via the web UI). ${xi(["scope","create"])}`}}});function Mh(e){let{ignorePaths:t,watchPaths:r}=Te(),n=Ws([...r]),o=Ws([...t]);return n(e)&&!o(e)}async function Bh(e){let t;try{t=M(e)}catch{return{degradedReason:"no project config \u2014 `ripplo init` not run here",populated:!0}}let r=await y({config:t,document:Fh,variables:{cwd:t.cwd,projectId:t.projectId}}).catch(()=>null);return r==null?{degradedReason:"server unreachable",populated:!0}:{degradedReason:null,populated:(r.project?.devSession?.scopeItems??[]).length>0}}import Hh from"fs";import Wh from"path";import{z as Gs}from"zod";var qh=new Set(["Edit","Write","NotebookEdit"]),zh=Gs.looseObject({file_path:Gs.string()}),Ks=I("PreToolUse",async e=>{if(!qh.has(e.tool_name))return;let t=Gh(e);if(t==null)return;let{cwd:r}=e;if(Hh.existsSync(Ee(r))||Ge(r))return;let n=await P(r);return n.ok?{hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:`\`ripplo watch\` is not running, so this edit to \`${t}\` won't sync to the server and dev-mode guardrails won't fire. Run \`/ripplo:start\` (or spawn \`npx ripplo watch\` directly via Bash with run_in_background), then retry. The app's dev server also needs to be running \u2014 \`npx ripplo doctor\` reports both. If watch can't start (auth, server down, intentional offline work), the user can run \`npx ripplo hooks pause\` to bypass this gate; \`npx ripplo hooks resume\` re-enables it. ${w("start")}`}}:{hookSpecificOutput:{additionalContext:`\`ripplo watch\` isn't running and the DSL is currently failing to compile, so the watch gate is letting this edit through \u2014 fix the compile error before relying on dev-mode guardrails. Compile error:
|
|
666
|
+
${n.error}
|
|
667
|
+
${w("create","DSL authoring + lint rules")}`,hookEventName:"PreToolUse"}}});function Gh(e){let t=zh.safeParse(e.tool_input);if(!t.success||!A(e.cwd))return null;let r=Wh.relative(e.cwd,t.data.file_path);return r.startsWith("..")||r!==".ripplo"&&!r.startsWith(".ripplo/")?null:r}import{graphql as Kh}from"gql.tada";var Jh=Kh(`
|
|
666
668
|
query ScopeReminder($projectId: String!, $cwd: String!) {
|
|
667
669
|
project(id: $projectId) {
|
|
668
670
|
id
|
|
@@ -679,9 +681,9 @@ ${w("create")}`}});import{z as Ds}from"zod";var hh=Ds.looseObject({command:Ds.st
|
|
|
679
681
|
}
|
|
680
682
|
}
|
|
681
683
|
}
|
|
682
|
-
`),Js=
|
|
684
|
+
`),Js=I("UserPromptSubmit",async e=>{let{cwd:t}=e;if(!A(t)||!_(t))return;let r=xe(t);if(Ke(t,"scope-reminder")===r)return;let n;try{n=M(t)}catch{return}let o=await y({config:n,document:Jh,variables:{cwd:n.cwd,projectId:n.projectId}}).catch(()=>null);if(o==null)return;Je(t,"scope-reminder",r);let i=o.project?.devSession?.scopeItems??[];return{hookSpecificOutput:{additionalContext:i.length===0?`RIPPLO SCOPE: empty. ${w("scope")}`:`RIPPLO SCOPE (${String(i.length)}):
|
|
683
685
|
${i.map(a=>{let l=a.workflow;return l==null?` [intent] (${a.id}) ${a.label??""}`:` [${l.spec==null?"stub":"implemented"}] (${a.id}) ${l.slug}`}).join(`
|
|
684
|
-
`)}`,hookEventName:"UserPromptSubmit"}}});var
|
|
686
|
+
`)}`,hookEventName:"UserPromptSubmit"}}});var Yh="# Ripplo \u2014 always-on session context\n\nEvery user-facing change in this repo ships with a deterministic, backend-aware test that proves it works end-to-end.\n\n## Load the right skill before acting \u2014 this is critical\n\nThe skills below carry the procedural detail you need to do Ripplo work correctly: precondition isolation, observer budget tiers, coverage IDs, scope discipline, artifact-read order on failures, parallelization patterns. **None of that is reproduced in this preamble** \u2014 only the always-on guardrails are. If you act on a Ripplo task without loading the matching skill, you will skip rules that exist to prevent specific past failure modes (cross-run data leakage, \"passing\" tests that never asserted backend state, cleared coverage gates without proof, etc.).\n\nMatch the task to a skill from the triage table; if unsure between two, load both. If completely unsure, load `/ripplo:explore` or `/ripplo:create`. Loading is cheap; acting under-informed is not.\n\n## Skill triage\n\n- Load `/ripplo:setup` skill for instructions on initializing Ripplo in a project; `ripplo doctor` reports the engine endpoint missing.\n- Load `/ripplo:explore` skill for instructions on planning/stubbing test coverage for a new project or new feature area.\n- Load `/ripplo:scope` skill for instructions on managing the working set of tests this session is responsible for.\n- Load `/ripplo:create` skill for instructions on authoring a single test spec for a user flow.\n- Load `/ripplo:run` skill for instructions on executing existing tests.\n- Load `/ripplo:debug` skill for instructions on a failed run; read artifacts in `.ripplo/debug/<runId>/` before re-running.\n- Load `/ripplo:flake-detect` skill for instructions on intermittent failures; parallelizes N runs (only use with evidence of flake).\n\n## Universal rules\n\n- **Two background processes must be running before feature work.** (1) The app's dev server, so the app is reachable; (2) `npx ripplo watch` (run `/ripplo:start` to spawn it, or invoke it directly via Bash with `run_in_background`), so the dev session is live. Without watch, scope/coverage hooks don't arm and `ripplo run` refuses to dispatch. Without the dev server, runs fail when they try to hit the app. `npx ripplo doctor` reports both.\n- **Two funnels.** Definitions \u2192 `createRipplo({ preconditions, observers, tests })` in `.ripplo/index.ts`. Implementations \u2192 `createEngine(ripplo, { preconditions, observers })` in your app server's `test/engine.ts`. Never call either elsewhere. TS enforces exhaustiveness across both.\n- **\"Done\" = app code delivers the behavior AND a passing test proves it.** Both halves. Shipping without a test isn't done; writing a test against broken UI/API isn't done.\n- **Scope is your job.** For any non-trivial change, enumerate every flow it could affect and either `scope add` existing tests or stub `.notImplemented()` tests. Don't wait to be told.\n- **`scope remove` is never for size/effort.** Valid only when an item is genuinely out of scope (wrong flow, duplicate, user said \"not this session,\" feature cut). \"Too many stubs\" \u2192 parallelize with subagents. Don't present \"implement vs. remove\" as a neutral A/B.\n- **Stub gates are not a question.** When `stop-enforce` blocks on `.notImplemented()` stubs, implement them \u2014 don't ask the user \"implement or defer?\", don't propose pausing hooks as option B. The fix isn't done until the test is. New scaffolding (precondition, observer, engine impl) is in-scope work, not follow-up.\n- **`uiOnly: true` is not a stub.** Observer wiring is in-scope for mutation flows; don't use it to silence observer lint.\n- **Never weaken a test to make it pass.** No `contains`/regex for exact text, no removed assertions, no fabricated locators. App lacks an accessible name \u2192 add one to the app, don't fall back to `testId()`. App bug \u2192 report with evidence.\n- **Artifacts first, re-run last.** Failed runs produce DOM, a11y tree, console, network, screenshots under `.ripplo/debug/<runId>/`. Read them. Never pipe `ripplo run` through `grep`/`tail`/`head`. Form a hypothesis citing an artifact line, make ONE change, re-run once.\n- **3-strike rule.** Same failure after 3 targeted fixes \u2192 stop and report. Repeated failure on the same step almost always means the diagnosis is wrong.\n- **`.ripplo/ripplo.lock` is committed, never hand-edited.** `ripplo lint` / `ripplo compile` regenerates it. Pre-commit runs `ripplo compile --check`.\n- **Scratch files live in `.ripplo/.local/`.** Never loose in `.ripplo/`.\n- **Worktrees are self-contained.** Each worktree has its own `.ripplo/` checkout, DevSession, scope, and debug artifacts. Auth and projectId are shared globally. Env files (typically gitignored) won't carry over to a fresh worktree \u2014 copy from main or point at a shared file. **If sibling worktrees run dev servers on different ports, the worktree's env file MUST update both `RIPPLO_APP_URL` and `RIPPLO_ENGINE_URL` to match the port that worktree's dev server is bound to** (e.g. main on `:3000`, this worktree on `:3001` \u2192 set `RIPPLO_APP_URL=http://localhost:3001` and `RIPPLO_ENGINE_URL=http://localhost:3001/ripplo` in the worktree's env file). Mismatched ports = `npx ripplo watch` (whether started via `/ripplo:start` or manually) talks to the wrong server, runs silently fail or hit the sibling worktree's app.\n- **DSL locators are semantic.** No `css` / `placeholder` / `waitFor` / `group`.\n- **New backend assertion?** Declare in `.ripplo/observers/index.ts`, implement in your app server's `engine.ts` (TS flags the missing impl).\n\n## Key files\n\n- `.ripplo/index.ts` \u2014 `createRipplo` call.\n- `.ripplo/{preconditions,observers,tests}/index.ts` \u2014 registry aggregators.\n- `.ripplo/project.json` \u2014 project id + env-file pointers.\n- `<app>/src/test/engine.ts` \u2014 single impl funnel via `createEngine`.\n- `packages/testing/README.md` (or the npm page for `@ripplo/testing`) \u2014 DSL reference.\n",Ys=I("SessionStart",e=>{if(A(e.cwd))return{hookSpecificOutput:{additionalContext:Yh,hookEventName:"SessionStart"}}});import{execFileSync as Xh}from"child_process";import Qh from"path";import Xs from"process";import{graphql as Zh}from"gql.tada";import{z as dr}from"zod";var ew=Zh(`
|
|
685
687
|
query ScopeEnforce($projectId: String!, $cwd: String!) {
|
|
686
688
|
project(id: $projectId) {
|
|
687
689
|
id
|
|
@@ -700,14 +702,14 @@ ${i.map(a=>{let l=a.workflow;return l==null?` [intent] (${a.id}) ${a.label??""}
|
|
|
700
702
|
}
|
|
701
703
|
}
|
|
702
704
|
}
|
|
703
|
-
`),Zs=
|
|
705
|
+
`),Zs=I("Stop",async e=>{let{cwd:t}=e;if(!A(t)||!_(t))return;let r=xe(t),n=Ke(t,"stop-enforce")===r;if(n&&!e.stop_hook_active)return;let o=tw(t),i=await rw(t,o);if(Je(t,"stop-enforce",r),i.length!==0)return n&&e.stop_hook_active?{continue:!1,stopReason:`Stop-enforce: same repo state across consecutive stop attempts; agent appears stuck. Errors:
|
|
704
706
|
${i.join(`
|
|
705
707
|
|
|
706
708
|
`)}`}:{decision:"block",reason:i.join(`
|
|
707
709
|
|
|
708
|
-
`)}});function
|
|
710
|
+
`)}});function tw(e){return lr(e,".ripplo/tests").filter(t=>t.endsWith(".ts")).map(t=>Qh.basename(t,".ts")).filter(t=>t!=="index")}async function rw(e,t){let r=await P(e);if(!r.ok)return[`--- Compilation failed ---
|
|
709
711
|
${r.error}
|
|
710
|
-
${w("create")}`];await le({cwd:e,result:r.result}),qe({cwd:e});let n=await
|
|
712
|
+
${w("create")}`];await le({cwd:e,result:r.result}),qe({cwd:e});let n=await ow(e),o=iw(r,t),i=sw(r),s=nw(e,r),l=t.length>0||n.hasRunnable?aw(e):null;return[o,i,s,l,n.error].filter(c=>c!=null)}function nw(e,t){let{ignorePaths:r}=Te(),n=Ci({compileResult:t.result,cwd:e,ignorePaths:r});if(n.length===0)return null;let o=n.filter(a=>a.kind==="unacknowledged"),i=n.filter(a=>a.kind==="stale"),s=[];if(o.length>0){let a=o.map(l=>` ${l.id}`).join(`
|
|
711
713
|
`);s.push(`Unacknowledged interactions (add to a test's .coverage(...)):
|
|
712
714
|
${a}`)}if(i.length>0){let a=i.map(l=>` ${l.id}`).join(`
|
|
713
715
|
`);s.push(`Stale .coverage(...) claims (id no longer exists in source):
|
|
@@ -715,23 +717,23 @@ ${a}`)}return`--- Exhaustiveness ---
|
|
|
715
717
|
${s.join(`
|
|
716
718
|
|
|
717
719
|
`)}
|
|
718
|
-
${w("create")}`}async function
|
|
720
|
+
${w("create")}`}async function ow(e){let t;try{t=M(e)}catch{return{error:null,hasRunnable:!1}}let n=(await y({config:t,document:ew,variables:{cwd:t.cwd,projectId:t.projectId}}).catch(()=>null))?.project?.devSession?.scopeItems??[],o=n.flatMap(a=>{let l=a.workflow;return l==null?[` [intent] ${a.label??"(no label)"} \u2014 stub a test for this flow`]:l.spec==null?[` [stub] ${l.slug} \u2014 implement \`${l.name}\``]:[]}),i=n.some(a=>a.workflow?.spec!=null);return{error:o.length===0?null:`--- Testing Scope ---
|
|
719
721
|
${o.join(`
|
|
720
722
|
`)}
|
|
721
|
-
${w("create")}`,hasRunnable:i}}function
|
|
723
|
+
${w("create")}`,hasRunnable:i}}function iw(e,t){let{diagnostics:r}=He(e.result),n=new Set(e.builder.getUnimplemented().tests),o=t.filter(a=>n.has(a));if(r.length===0&&o.length===0)return null;let i=r.map(a=>{let l=a.step==null?"":` at "${a.step}"`;return` [${a.rule}]${l} ${a.test}: ${a.message}`}),s=o.map(a=>` [not-implemented] ${a} is still marked .notImplemented()`);return`--- Ripplo Lint ---
|
|
722
724
|
${[...i,...s].join(`
|
|
723
725
|
`)}
|
|
724
|
-
${w("create")}`}function
|
|
726
|
+
${w("create")}`}function sw(e){let{tests:t}=e.builder.getUnimplemented();return t.length===0?null:`--- Unimplemented stubs ---
|
|
725
727
|
${t.join(", ")}
|
|
726
728
|
Implement the stub now. Do not ask the user "implement or defer?" \u2014 that framing is forbidden by /ripplo:create. New scaffolding (precondition, observer, engine impl) is in-scope, not follow-up.
|
|
727
|
-
${w("create")}`}function
|
|
729
|
+
${w("create")}`}function aw(e){let t=cw(["run"],e);if(t.code===0)return null;let r=t.output.split(`
|
|
728
730
|
`).filter(n=>/FAILED/.test(n)).join(`
|
|
729
731
|
`);return r.length===0?null:`--- Ripplo Run Failures (scope) ---
|
|
730
732
|
${r}
|
|
731
|
-
Artifacts: .ripplo/debug/<runId>/. ${w("debug")}`}var
|
|
732
|
-
`),process.exit(1));let r=await
|
|
733
|
-
`),process.exit(1)});function
|
|
734
|
-
`))}export{
|
|
733
|
+
Artifacts: .ripplo/debug/<runId>/. ${w("debug")}`}var lw=dr.object({status:dr.number().nullish(),stderr:dr.unknown().optional(),stdout:dr.unknown().optional()});function Qs(e){return e instanceof Buffer?e.toString("utf8"):typeof e=="string"?e:""}function cw(e,t){let r=Xs.argv[1];if(r==null)return{code:1,output:""};try{return{code:0,output:Xh(Xs.execPath,[r,...e],{cwd:t,encoding:"utf8",stdio:["ignore","pipe","pipe"]})}}catch(n){let o=lw.safeParse(n);if(!o.success)return{code:1,output:""};let i=`${Qs(o.data.stdout)}${Qs(o.data.stderr)}`;return{code:o.data.status??1,output:i}}}import{z as ea}from"zod";var uw=ea.looseObject({skill:ea.string()}),ta=I("PostToolUse",e=>{if(e.tool_name!=="Skill")return;let t=uw.safeParse(e.tool_input);if(!t.success)return;let r=/^ripplo:(.+)$/.exec(t.data.skill);if(r==null)return;let n=r[1];n!=null&&A(e.cwd)&&_s(e.cwd,e.session_id,n)});vw();Mo(process.cwd());jr();var ra={"coverage-nudge":Es,"exit-plan-gate":Ts,"plan-reminder":As,"post-edit-flag-stubs":js,"post-edit-lint":Os,"pre-bash-hooks-pause-gate":Ls,"pre-bash-run-gate":Ms,"pre-edit-ripplo-skill-gate":Hs,"pre-edit-scope-gate":zs,"pre-edit-watch-gate":Ks,"scope-reminder":Js,"session-preamble":Ys,"stop-enforce":Zs,"track-skill-load":ta};async function mw(){await dw(pw(process.argv)).scriptName("ripplo").version("0.5.4").command("watch","Watch for run requests and execute locally",()=>{},()=>hs()).command("auth <subcommand>","Manage authentication",bw).command("projects <subcommand>","Inspect Ripplo projects",ww).command("hooks <subcommand>","Pause or resume Ripplo hooks",hw).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=>ss({appUrl:e["app-url"],engineUrl:e["engine-url"],envFile:e.env,projectId:e.project})).command("run [ids..]","Run tests (defaults to scope; auto-adds dirty tests)",e=>{let t=[];return e.positional("ids",{array:!0,default:t,describe:"Test ids to run (defaults to dev-session scope)",type:"string"}).option("all",{default:!1,describe:"Run every test in the dev session (expensive)",type:"boolean"})},e=>ds({all:e.all,ids:e.ids})).command("lint [ids..]","Compile and lint tests (all or specific ids)",e=>{let t=[];return e.positional("ids",{array:!0,default:t,describe:"Test ids to lint (all if omitted)",type:"string"}).option("require-implemented",{array:!0,default:t,describe:"Test ids that must not be .notImplemented() \u2014 fails if any still are",type:"string"})},e=>cs({ids:e.ids,requireImplemented:e["require-implemented"]})).command("flake-detect <id>","Run N times to detect flakiness",e=>e.positional("id",{demandOption:!0,type:"string"}).option("runs",{default:10,type:"number"}),e=>Qi({id:e.id,runs:e.runs})).command("sync","Push the compiled .ripplo/ resources to the server (no run)",()=>{},()=>ps()).command("compile","Compile the DSL 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=>Ei({check:e.check})).command("cover","Audit all coverage statements",()=>{},()=>$i()).command("doctor","Check project health",()=>{},()=>qi()).command("status","Report unimplemented tests and preconditions",e=>e.option("format",{choices:["json","summary"],default:"json",describe:"Output format"}),e=>Rs({format:e.format})).command("scope <subcommand>","Manage testing scope",yw).command("hook <name>","Internal: run a Claude Code plugin hook",e=>e.positional("name",{choices:Object.keys(ra),demandOption:!0,type:"string"}),e=>fw(e.name)).strict().help().parse()}async function fw(e){let t=ra[e];t==null&&(process.stderr.write(`Unknown hook: ${e}
|
|
734
|
+
`),process.exit(1));let r=await gw(),n=r.trim()===""?{}:JSON.parse(r),o=await t.run(n);o!=null&&process.stdout.write(JSON.stringify(o))}function gw(){return new Promise((e,t)=>{if(process.stdin.isTTY){e("");return}let r=[];process.stdin.on("data",n=>r.push(n)),process.stdin.on("end",()=>{e(Buffer.concat(r).toString("utf8"))}),process.stdin.on("error",t)})}mw().catch(e=>{process.stderr.write(`${e instanceof Error?e.message:String(e)}
|
|
735
|
+
`),process.exit(1)});function yw(e){return e.command("status","Print the current scope",t=>t.option("format",{choices:["json","text"],default:"text",describe:"Output format"}),t=>bs({format:t.format})).command("add <test-ids..>","Bind one or more existing tests (stubs or implemented) to scope as agent intent",t=>{let r=[];return t.positional("test-ids",{array:!0,default:r,demandOption:!0,describe:"Slugs of existing workflows",type:"string"})},t=>vs({testIds:t["test-ids"]})).command("link <id> <test-id>","Link an existing scope item to a test",t=>t.positional("id",{demandOption:!0,describe:"Scope item id",type:"string"}).positional("test-id",{demandOption:!0,describe:"Slug of the workflow to link",type:"string"}),t=>Ss({id:t.id,testId:t["test-id"]})).command("remove <ids..>","Remove one or more scope items by id",t=>{let r=[];return t.positional("ids",{array:!0,default:r,demandOption:!0,describe:"Scope item ids",type:"string"})},t=>ks({ids:t.ids})).demandCommand(1)}function hw(e){return e.command("pause","Disable all Ripplo pre-edit gates and stop enforcement until resumed",()=>{},()=>Zi()).command("resume","Re-enable Ripplo hooks paused via `ripplo hooks pause`",()=>{},()=>es()).demandCommand(1)}function ww(e){return e.command("list","List projects you have access to (JSON)",()=>{},()=>us()).demandCommand(1)}function bw(e){return e.command("login","Authenticate via device flow",()=>{},()=>Go()).command("status","Show authentication status",()=>{},()=>Ko()).command("logout","Remove the saved token",()=>{},()=>{Jo()}).demandCommand(1)}function vw(){let e=process.cwd(),t=hr(e);t!=null&&t!==e&&(process.chdir(t),process.stderr.write(`ripplo: resolved .ripplo/ at ${t}
|
|
736
|
+
`))}export{mw as main};
|
|
735
737
|
/*! Bundled license information:
|
|
736
738
|
|
|
737
739
|
mustache/mustache.mjs:
|