saffron-ai 1.0.0 → 1.0.1
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/CHANGELOG.md +546 -0
- package/README.md +3 -4
- package/dist-pkg/cli.js +290 -266
- package/package.json +1 -1
- package/skills/saffron/SKILL.md +34 -7
- package/skills/saffron/references/config.md +2 -0
- package/skills/saffron/references/syntax.md +27 -5
- package/textmate/saffron/syntaxes/saffron.tmLanguage.json +12 -3
package/dist-pkg/cli.js
CHANGED
|
@@ -1,59 +1,67 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import
|
|
3
|
-
`||
|
|
4
|
-
`&&
|
|
5
|
-
`)){let r
|
|
6
|
-
`),n=new Map,r=new Map,s;return{source:t.map((i
|
|
7
|
-
`),definitions:n,invocations:r}}function
|
|
8
|
-
`).filter(
|
|
2
|
+
import Fe from"node:fs";import G from"node:path";import dS from"node:readline";import{Command as uS}from"commander";import Qh from"node:fs";import Xh from"node:path";import{AstBuilder as em,dialects as Wl,GherkinClassicTokenMatcher as tm,Parser as nm}from"@cucumber/gherkin";import{IdGenerator as rm,StepKeywordType as co}from"@cucumber/messages";import Ml from"node:fs";import Fh from"node:path";import br from"node:fs";import nn from"node:path";var Ae=/\{data:([A-Za-z0-9_-]+(?:\.[A-Za-z0-9_-]+)+)\}/g,vr=nn.resolve("data"),Vt,Il=process.cwd(),eo=new Map;function Mt(e,t="data",n){Il=nn.resolve(e),vr=nn.isAbsolute(t)?t:nn.join(e,t),Vt=n?.trim()||void 0,eo.clear()}var et=()=>({dir:vr,env:Vt,root:Il});function Nl(e,t){let n=s=>s!==null&&typeof s=="object"&&!Array.isArray(s);if(!n(e)||!n(t))return t;let r={...e};for(let[s,o]of Object.entries(t))r[s]=s in e?Nl(e[s],o):o;return r}function Pl(e,t){try{return JSON.parse(br.readFileSync(e,"utf8"))}catch(n){throw new Error(`data file ${t} is not valid JSON: ${n instanceof Error?n.message:String(n)}`)}}function Mh(e){if(eo.has(e))return eo.get(e);let t=nn.join(vr,`${e}.json`),n=Vt?nn.join(vr,`${e}.${Vt}.json`):void 0,r=br.existsSync(t),s=n!==void 0&&br.existsSync(n);if(!r&&!s)throw new Error(`data file ${nn.relative(process.cwd(),t)||t} does not exist${Vt?` (nor ${e}.${Vt}.json for the "${Vt}" environment)`:""}`);let o=r?Pl(t,`${e}.json`):void 0;if(s){let a=Pl(n,`${e}.${Vt}.json`);o=r?Nl(o,a):a}return eo.set(e,o),o}function qn(e){let[t,...n]=e.split("."),r=Mh(t),s=[t];for(let o of n){let a=r,i=a&&typeof a=="object"?Array.isArray(a)?a[Number(o)]:Object.hasOwn(a,o)?a[o]:void 0:void 0;if(i===void 0)throw new Error(`"${o}" does not exist under ${s.join(".")} (in ${t}.json)`);r=i,s.push(o)}return r}function qe(e){let t;try{t=qn(e)}catch(n){throw new Error(`{data:${e}}: ${n instanceof Error?n.message:String(n)}`)}if(t===null||typeof t=="object")throw new Error(`{data:${e}} is ${Array.isArray(t)?"a list":"an object"}, not a single value. Point at one entry, for example {data:${e}.${Array.isArray(t)?"0":Object.keys(t??{})[0]??"key"}}`);return String(t)}function $n(e){let t;try{t=qn(e)}catch(s){throw new Error(`{data:${e}}: ${s instanceof Error?s.message:String(s)}`)}let n=Array.isArray(t)?t:[t];if(n.length===0)throw new Error(`{data:${e}} is an empty list: there is nothing to check`);let r=n.find(s=>s===null||typeof s=="object");if(r!==void 0)throw new Error(`{data:${e}} must be a list of plain values (text, numbers); it contains ${Array.isArray(r)?"a list":"an object"}`);return n.map(String)}function to(e){$n(e)}function jl(e){return e.replace(Ae,(t,n)=>{let r=$n(n);return Array.isArray(qn(n))?`${t} (a data list, currently: ${r.map(o=>`"${o}"`).join(", ")})`:r[0]})}function Dh(e){let t=[],n=[],r="",s=!1,o=!1,a=-1,i=()=>{n.push(a>=0?r.slice(0,a)+r.slice(a).trim():r.trim()),r="",a=-1},c=()=>{i(),(o||n.some(l=>l!==""))&&t.push(n),n=[],o=!1};for(let l=0;l<e.length;l++){let d=e[l];s?d==='"'&&e[l+1]==='"'?(r+='"',l++):d==='"'?(s=!1,a=r.length):r+=d:d==='"'&&r.trim()===""?(r="",s=o=!0):d===","?i():d===`
|
|
3
|
+
`||d==="\r"?(d==="\r"&&e[l+1]===`
|
|
4
|
+
`&&l++,c()):r+=d}return c(),t}function no(e){let t=i=>{throw new Error(`Examples: {data:${e}}: ${i}`)},n=Vt?nn.join(vr,`${e}.${Vt}.csv`):void 0,r=n&&br.existsSync(n)?n:nn.join(vr,`${e}.csv`);if(!e.includes(".")&&br.existsSync(r)){let[i,...c]=Dh(br.readFileSync(r,"utf8"));(!i||c.length===0)&&t(`${e}.csv needs a header row and at least one data row`);let l=c.findIndex(d=>d.length>i.length);return l>=0&&t(`${e}.csv row ${l+2} has ${c[l].length} fields for ${i.length} columns: quote a value that holds a comma`),{headers:i,rows:c.map(d=>Object.fromEntries(i.map((f,p)=>[f,d[p]??""])))}}let s;try{s=qn(e)}catch(i){return t(`${i instanceof Error?i.message:String(i)} (looked for ${e.split(".")[0]}.csv and ${e.split(".")[0]}.json in the data folder)`)}(!Array.isArray(s)||s.length===0||s.some(i=>i===null||typeof i!="object"||Array.isArray(i)))&&t('must be a non-empty list of records, like [{ "role": "Admin", "menu": "Users" }]');let o=s,a=[...new Set(o.flatMap(i=>Object.keys(i)))];return{headers:a,rows:o.map(i=>Object.fromEntries(a.map(c=>[c,i[c]===void 0||i[c]===null?"":String(i[c])])))}}function Dt(e){return e.replace(Ae,(t,n)=>qe(n))}function rn(e){let t=new Set;for(let n of e)if(n)for(let r of n.matchAll(Ae))t.add(r[1]);return t}function xr(e){let t=new Map;for(let n of rn(e))try{t.set(n,qe(n))}catch{}return t}function ro(e,t,n=new Set){let r=new Map;for(let[c,l]of t)r.set(l,[...r.get(l)??[],c]);let s=[];for(let[c,l]of r){let d=l.length===1?l:l.filter(f=>n.has(f));d.length===1&&s.push([d[0],c])}s.sort((c,l)=>l[1].length-c[1].length);for(let[c,l]of s)if(l!==""&&e===l)return`{data:${c}}`;let o=new Map(s.filter(([,c])=>c.length>=3).map(([c,l])=>[l,`{data:${c}}`]));if(o.size===0)return e;let a=[...o.keys()].map(c=>{let l=c.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return c.length>=4?l:`(?<![\\p{L}\\p{N}])${l}(?![\\p{L}\\p{N}])`}).join("|"),i=new RegExp(a,"gu");return e.split(/(\{(?:env|data|unique|date)[^{}]*\}|<[^<>\s]+>)/).map((c,l)=>l%2?c:c.replace(i,d=>o.get(d))).join("")}var Ce=/\{env:([A-Za-z_][A-Za-z0-9_]*)\}/g;function oo(e,t){return e.replace(Ce,(n,r)=>{if(!t.has(r))throw new Error(`{env:${r}} is not referenced by this scenario: a recording can only use the environment variables its scenario names`);let s=process.env[r];if(s===void 0)throw new Error(`environment variable ${r} is not set (referenced as {env:${r}}): export it or add it to .env`);return s})}function Ji(e){let t=new Set;for(let n of e)if(n)for(let r of n.matchAll(Ce))t.add(r[1]);return t}function lt(e){let t=[];for(let n of e.steps){t.push(n.text,n.resolvedText),n.docString&&t.push(n.docString),n.resolvedDocString&&t.push(n.resolvedDocString);for(let r of n.table??[])t.push(...r);for(let r of n.resolvedTable??[])t.push(...r)}return t}function es(e){let t=[];for(let n of rn(e))try{t.push(...$n(n))}catch{}return t}function tt(e){let t=lt(e);return Ji([...t,...es(t)])}function Pe(e){let t=new Map;for(let n of tt(e)){let r=process.env[n];r!==void 0&&t.set(n,r)}return t}var kn=3,Vi=String.raw`\{(?:env:[A-Za-z_][A-Za-z0-9_]*|data:[A-Za-z0-9_-]+(?:\.[A-Za-z0-9_-]+)+|unique:[A-Za-z0-9_-]+(?::digits)?)\\?\}`,Lh=/\{(env:[A-Za-z_][A-Za-z0-9_]*|data:[A-Za-z0-9_-]+(?:\.[A-Za-z0-9_-]+)+)\\\}/g,Ll=e=>`${e.slice(0,-1)}\\}`,Bl=e=>e.replace(Lh,"{$1}"),so={'"':'\\"',"\\":"\\\\","\b":"\\b","\f":"\\f","\n":"\\n","\r":"\\r"," ":"\\t"};function qi(e,t,n,r){let s="";for(let o of e.split("")){let a=o.charCodeAt(0);if(t?.test(o)||a<32&&!so[o]){let i=a.toString(16).padStart(4,"0");s+="\\u"+(n?i.toUpperCase():i)}else so[o]?s+=so[o]:o==="/"&&r?s+="\\/":s+=o}return s}function Bh(e){return[e,e.replace(/%[0-9A-F]{2}/g,t=>t.toLowerCase())]}function Dl(e,t,n){return e.replace(/[&<>"'+]|[^\x00-\x7f]/gu,r=>t[r]??(n&&r>"\x7F"?n(r.codePointAt(0)):r))}function Uh(e,t){let n="";for(let r of e){let s=r<=" "||r>="\x7F"||t.test(r);n+=s?[...Buffer.from(r,"utf8")].map(o=>"%"+o.toString(16).toUpperCase().padStart(2,"0")).join(""):r}return n}var zh=[/["#<>']/,/["#<>?^`{}]/,/["#<>?^`{|}]/,/["#<>?^`{}/:;=@[\\\]|]/,/["#<>?^`{}/:;=@[\\\]|']/];function Hh(e){let t=/[^\x00-\x7f]/,n=new Set([e]);for(let[o,a,i]of[[void 0,!1,!1],[void 0,!1,!0],[t,!1,!1],[t,!0,!1],[t,!1,!0],[/[<>&\u2028\u2029]/,!1,!1],[/[^\x00-\x7f]|[<>&'+`"]/,!0,!1]])n.add(qi(e,o,a,i));let r=o=>qi(o,void 0,!1,!1).replaceAll('\\"','"').replaceAll("'","\\'");for(let o of[e,be(e),be(e).replaceAll("/","\\/")])for(let a of[o,r(o),o.replaceAll("'","\\'")])n.add(a),n.add(qi(a,void 0,!1,!1));let s=o=>{try{for(let a of Bh(o()))n.add(a)}catch{}};s(()=>encodeURIComponent(e)),s(()=>encodeURIComponent(e).replaceAll("'","%27")),s(()=>encodeURI(e)),s(()=>new URLSearchParams([["",e]]).toString().slice(1));for(let o of zh)s(()=>Uh(e,o));for(let o of[{"&":"&","<":"<",">":">"},{"&":"&","<":"<",">":">",'"':""","'":"'"},{"&":"&","<":"<",">":">",'"':""","'":"'"},{"&":"&","<":"<",">":">",'"':""","'":"'"},{"&":"&","<":"<",">":">",'"':""","'":"'"},{"&":"&","<":"<",">":">",'"':""","'":"'","+":"+"}])n.add(Dl(e,o));return n.add(Dl(e,{"&":"&","<":"<",">":">",'"':""","'":"'","+":"+"},o=>`&#x${o.toString(16).toUpperCase()};`)),[...n]}var ts=e=>e.map(t=>`{env:${t}}`).join(""),be=e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),Wi=e=>be(e).replace(/%[0-9a-f]{2}/gi,t=>t.replace(/[a-f]/gi,n=>`[${n.toUpperCase()}${n.toLowerCase()}]`)),qh=e=>Buffer.from(e,"utf8").toString("latin1");function Rn(e,t={}){let n=[...e.entries()].filter(([,y])=>y.length>=kn).sort((y,w)=>w[1].length-y[1].length),r=y=>t.encodings?y.replace(/%[0-9a-f]{2}/gi,w=>w.toUpperCase()):y,s=t.encodings?Wi:be,o=new Map,a=new Set;for(let[y,w]of n){t.standaloneBelow!==void 0&&w.length<t.standaloneBelow&&a.add(w);let v=t.encodings?Hh(w):[w];for(let x of v){let $=t.bytes?[qh(x),.../^[\x00-\xff]*$/.test(x)?[x]:[]]:[x];for(let E of $)o.has(r(E))||o.set(r(E),y)}}let i=new Set(n.map(([,y])=>y)),c=new Map(n.filter(([,y])=>/^\d{6,}$/.test(y)).map(([y,w])=>[w,y])),l=[...c.keys()].map(y=>`(?<!\\d)${[...y].join("[\\s\\u00a0\\u202f-]?")}(?!\\d)`),d=y=>o.get(r(y))??c.get(y.replace(/\D/g,"")),f=new Set(["u"]);for(let[,y]of n)for(let w of y){let v=so[w]??(w==="/"?"\\/":void 0);v&&f.add(v.slice(1))}let p=new RegExp(`\\\\[${[...f].map(be).join("")}]`);if(o.size===0)return{empty:!0,mask:y=>y,matches:()=>[],occursIn:()=>!1,isValue:()=>!1,hiddenByEscape:p};let u=[...o.keys()].sort((y,w)=>w.length-y.length).map(y=>a.has(y)?`(?<![A-Za-z0-9])${s(y)}(?![A-Za-z0-9])`:s(y)).concat(l).join("|"),h=new RegExp(`(${Vi})|${u}`,"g"),b=new RegExp(`(${Vi})|${u}`,"y"),g=new RegExp(u),S=y=>{let w=[];h.lastIndex=0;for(let v=h.exec(y);v!==null;v=h.exec(y)){if(v[1]!==void 0)continue;let x=v.index,$=x+v[0].length,E=[d(v[0])];for(let R=x+1;R<$;R++){b.lastIndex=R;let k=b.exec(y);k&&k[1]===void 0&&R+k[0].length>$&&($=R+k[0].length,E.push(d(k[0])))}w.push({start:x,end:$,names:[...new Set(E)]}),h.lastIndex=$}return w};return{empty:!1,hiddenByEscape:p,occursIn:y=>g.test(y),isValue:y=>i.has(y),matches:S,mask(y){let w="",v=0;for(let x of S(y))w+=y.slice(v,x.start)+ts(x.names),v=x.end;return v===0?y:w+y.slice(v)}}}function Gi(e,t,n=r=>r){let r=new Map;for(let a of e)for(let i of a.split(/[\s"'`]+/)){let c=i.replace(/^[.,;:!?()[\]]+|[.,;:!?()[\]]+$/g,""),l=[...c.matchAll(Ce)].map(p=>p[1]);if(l.length===0||l.some(p=>!t.has(p)))continue;let d=c.replace(Ce,(p,u)=>t.get(u));if(d===c||d.length<kn||c===`{env:${l[0]}}`)continue;let f=n(d);r.has(f)||r.set(f,c.split(/(\{env:[A-Za-z_][A-Za-z0-9_]*\})/).map((p,u)=>u%2?p:n(p)).join(""))}if(r.size===0)return a=>a;let s=[...r.keys()].sort((a,i)=>i.length-a.length).map(be).join("|"),o=new RegExp(`(${Vi})|${s}`,"g");return a=>a.replace(o,(i,c)=>c!==void 0?i:r.get(i))}var Fl=new WeakMap;function nt(e,t){let n=Fl.get(t);return n||(n=Rn(t,{encodings:!0}),Fl.set(t,n)),n.mask(e)}function Ul(e){for(let[t,n]of Object.entries(Ki(e)))process.env[t]===void 0&&(process.env[t]=n)}function Ki(e){let t=Fh.join(e,".env"),n=Object.create(null);if(!Ml.existsSync(t))return n;for(let r of Ml.readFileSync(t,"utf8").split(`
|
|
5
|
+
`)){let s=r.trim().replace(/^export\s+/,"");if(!s||s.startsWith("#"))continue;let o=s.indexOf("=");if(o<=0)continue;let a=s.slice(0,o).trim();if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(a))continue;let i=s.slice(o+1).trim(),c=/^(?:"((?:\\.|[^"\\])*)"|'([^']*)')\s*(?:#.*)?$/.exec(i);c?i=c[1]!==void 0?c[1].replace(/\\(["\\])/g,"$1"):c[2]:i=i.replace(/\s+#.*$/,""),n[a]=i}return n}function Vn(e,t){return e.replace(/<([^<>]+)>/g,(n,r)=>Object.hasOwn(t,r)?t[r]:n)}function rt(e){if(!e||e.length===0)return{};let t={};if(e.every(n=>n.length===2)){for(let[n,r]of e)t[`table:${n}`]=r;return t}if(e.length>=2){let[n,...r]=e;if(n.some(s=>!s))return{};r.forEach((s,o)=>{n.forEach((a,i)=>{s[i]!==void 0&&(t[`table:${o+1}:${a}`]=s[i])})})}return t}function Jn(e){return e!==void 0?{docstring:e}:{}}function Tn(e){let t=new Map;for(let r of e){let s={...rt(r.resolvedTable??r.table),...Jn(r.resolvedDocString??r.docString)};for(let[o,a]of Object.entries(s)){let i=t.get(o);i||t.set(o,i=new Set),i.add(a)}}let n={};for(let[r,s]of t)s.size===1&&(n[r]=[...s][0]);return n}function Yi(e){return e.replace(/\\.|["'`]|>>/g,t=>t[0]==="\\"?t:t===">>"?"\\>\\>":`\\${t}`)}var ue={quoted:e=>JSON.stringify(e).slice(1,-1),regex:e=>Yi(be(e).replaceAll("/","\\/")),pattern:e=>be(e)};function Wn(e,t,n=s=>s,r=!1){let s="",o=0;for(let a of e.matchAll(/"((?:[^"\\]|\\.)*)"|=\/((?:[^/\\]|\\.)*)\/([a-z]*)/g)){let[i,c,l,d]=a;!r&&c===void 0&&/[uv]/.test(d)||(s+=n(e.slice(o,a.index))+(c!==void 0?`"${t(c,"quoted")}"`:`=/${t(l,"regex")}/${d}`),o=a.index+i.length)}return s+n(e.slice(o))}var Zi=/^As "([^"]+)"\s+(?=\S)/,Ft="default",dt=e=>e||Ft;function Lt(e){return Zi.exec(e)?.[1].trim()||void 0}function zl(e,t){let n=Zi.exec(e)?.[0],r=fe(t);return n?`${n}${r}`:r}var fe=e=>e.replace(Zi,"");function Ye(e,t){let n=t;return e.map(r=>{let s=Lt(r);return s!==void 0&&(n=s===Ft?void 0:s),n})}function Hl(e){if(!(!/^As\s+"[^"]*"\s+\S/.test(e)||Lt(e)!==void 0))return`"${e}" starts like a browser session but names none. Write As "name" and the step after one space, as in As "buyer" I open the cart; the name cannot be empty.`}var pe=e=>e??"";function An(e){return new Set(e.map(t=>pe(t.session))).size>1}function ns(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")||"session"}function io(e,t=[],n){let r,s,o,a=!1,i=!1,c;return e.map((l,d)=>{let f=r,p=/^\s*("""|```)/.exec(l)?.[1];if(p)return c?c===p&&(c=void 0):c=p,f;if(c)return f;if(/^\s*Feature:/.test(l))r=s=o=void 0,a=i=!1;else if(/^\s*Rule:/.test(l))a=!0,i=!1,r=o=s;else if(/^\s*Background:/.test(l))i=!0,r=a?s:void 0;else if(n?.has(d)||/^\s*(?:Scenario(?: Outline| Template)?|Example):/.test(l))i=!1,r=a?o:s;else if(/^\s*StepSet:/.test(l))i=!1,r=void 0;else{let u=/^\s*(?:Given|When|Then|And|But|\*)\s+(.+?)\s*$/.exec(l)?.[1],h=/^\s*StepSet\s+([^\s:].*?)\s*$/.exec(l)?.[1],b=u?[u]:t.find(g=>g.name===h)?.steps;b?.length&&(r=Ye(b,r).at(-1),i&&(a?o=r:s=r))}return f})}function ql(e,t,n){if(!n)return;let r=[...new Set(e)].filter(o=>o!==Ft&&!t.includes(o)).sort();return r.length<2?void 0:`${`${r.slice(0,-1).join(", ")} and ${r.at(-1)}`} ${r.length===2?"both":"all"} start signed in from storageState (${n}), as the same person; give each its own sessions entry in saffron.config.json.`}import rs from"node:fs";import ao from"node:path";import{AstBuilder as Vh,GherkinClassicTokenMatcher as Jh,Parser as Wh}from"@cucumber/gherkin";import{IdGenerator as Gh}from"@cucumber/messages";var Le=class extends Error{},Kh=/^(\s*)StepSet:\s*(.+?)\s*$/,Yh=/^(\s*)StepSet\s+([^\s:].*?)\s*$/;function Qi(e){let t=e.split(`
|
|
6
|
+
`),n=new Map,r=new Map,s;return{source:t.map((a,i)=>{let c=/^\s*("""|```)/.exec(a)?.[1];if(s)return c===s&&(s=void 0),a;if(c)return s=c,a;let l=a.match(Kh);if(l)return n.set(i+1,l[2]),`${l[1]}Scenario: ${l[2]}`;let d=a.match(Yh);return d?(r.set(i+1,d[2]),`${d[1]}* StepSet ${d[2]}`):a}).join(`
|
|
7
|
+
`),definitions:n,invocations:r}}function Zh(e){return new Wh(new Vh(Gh.uuid()),new Jh).parse(e)}function Jl(e,t){for(let n of e)n.scenario?t(n.scenario):"rule"in n&&n.rule&&Jl(n.rule.children,t)}function sn(e,t){let n=new Map;for(let r of e){let s=ao.relative(t,r),o=Qi(rs.readFileSync(r,"utf8"));if(o.definitions.size===0)continue;let a=Zh(o.source);a.feature&&Jl(a.feature.children,i=>{let c=o.definitions.get(i.location.line);if(c===void 0)return;let l=n.get(c);if(l)throw new Le(`StepSet "${c}" is defined twice: ${l.file}:${l.line} and ${s}:${i.location.line}. Set names are unique across the project. If line ${i.location.line} was meant to INVOKE the set inside a scenario, remove the colon: "StepSet ${c}".`);if(i.examples.length>0)throw new Le(`StepSet "${c}" (${s}:${i.location.line}) has an Examples table: step sets take their values from the invoking scenario.`);for(let d of i.steps)if(o.invocations.has(d.location.line))throw new Le(`StepSet "${c}" (${s}:${i.location.line}) invokes another step set at line ${d.location.line}, and step sets cannot be nested.`);n.set(c,{name:c,file:s,line:i.location.line,steps:[...i.steps]})})}return n}var Xi=[".feature",".saffron"];function on(e){return Xi.some(t=>e.endsWith(t))}function ut(e,t,n){let r=ao.isAbsolute(t.features??"features")?t.features:ao.join(e,t.features??"features"),s=new Set(Gn(r));for(let o of n)o.endsWith(".saffron")&&s.add(o);return sn([...s].sort(),e)}var Vl=new Set([".saffron","node_modules",".git"]);function an(e,t){if(!rs.existsSync(e))return[];let n=[],r=new Set,s=[],o=c=>["ENOENT","ELOOP"].includes(c.code??""),a=c=>{try{return rs.statSync(c)}catch(l){if(o(l))return;throw l}},i=(c,l=!1)=>{let d,f;try{if(d=rs.realpathSync(c),r.has(d))return;f=rs.readdirSync(c,{withFileTypes:!0})}catch(p){if(l&&o(p))return;throw p}r.add(d);for(let p of f){let u=ao.join(c,p.name);if(p.isSymbolicLink()){let h=a(u);h?.isDirectory()?Vl.has(p.name)||s.push(u):h?.isFile()&&t(p.name)&&n.push(u)}else p.isDirectory()?Vl.has(p.name)||i(u):p.isFile()&&t(p.name)&&n.push(u)}};i(e);for(let c=0;c<s.length;c++)i(s[c],!0);return n.sort()}function Gn(e){return an(e,t=>t.endsWith(".saffron"))}function Gl(e,t,n){return e.map(({step:r,source:s})=>{let o;switch(r.keywordType){case co.OUTCOME:n.setup=!1,o="assertion";break;case co.CONTEXT:case co.ACTION:n.setup=r.keywordType===co.CONTEXT,o="action";break;default:o=n.value}n.value=o;let a=r.dataTable?r.dataTable.rows.map(c=>c.cells.map(l=>l.value)):void 0,i=r.docString?.content;return{setup:n.setup,keyword:r.keyword.trim(),kind:o,text:r.text,resolvedText:Vn(r.text,t),table:a,resolvedTable:a?.map(c=>c.map(l=>Vn(l,t))),docString:i,resolvedDocString:i!==void 0?Vn(i,t):void 0,source:s}})}function Kl(e,t,n,r,s){let o=[];for(let a of e){let i=r.get(a.location.line);if(i===void 0){o.push({step:a,source:{file:t,line:a.location.line,fromBackground:n}});continue}let c=s?.get(i);if(!c)throw new Le(`${t}:${a.location.line} invokes StepSet "${i}", which is not defined anywhere in the project.`);for(let l of c.steps)o.push({step:l,source:{file:c.file,line:l.location.line,fromStepSet:c.name,fromBackground:n}})}return o}function sm(e,t,n,r,s,o=!1,a=[]){let i=[...new Set([...a,...e.tags.map(l=>l.name)])],c=[];if(e.examples.length===0)c.push({params:{},label:"",tags:i});else{let l=0;for(let d of e.examples){let f=[...new Set([...i,...d.tags.map(h=>h.name)])],p=d.name.trim().match(/^\{data:([A-Za-z0-9_.-]+)\}$/);if(p&&!d.tableHeader){let h=`${t}:${d.location.line}`;if(!o)throw new Le(`${h} reads Examples from a data file, which only .saffron files understand. Rename the file to ${t.replace(/\.feature$/,".saffron")}: nothing else needs to change.`);let b;try{b=no(p[1])}catch(y){throw new Le(`${h} ${y instanceof Error?y.message:String(y)}`)}let S=[...new Set([...r,...s].flatMap(y=>[y.step.text,y.step.docString?.content??"",...y.step.dataTable?.rows.flatMap(w=>w.cells.map(v=>v.value))??[]].flatMap(w=>[...w.matchAll(/<([^<>]+)>/g)].map(v=>v[1]))))].filter(y=>!b.headers.includes(y)&&!y.startsWith("table:")&&y!=="docstring");if(S.length>0)throw new Le(`${h} the scenario uses <${S.join(">, <")}>, but {data:${p[1]}} has the columns ${b.headers.map(y=>`"${y}"`).join(", ")}.`);for(let y of b.rows)l+=1,c.push({params:y,label:` (example ${l})`,tags:f});continue}let u=d.tableHeader?.cells.map(h=>h.value)??[];for(let h of d.tableBody){l+=1;let b={};h.cells.forEach((g,S)=>{b[u[S]]=g.value}),c.push({params:b,label:` (example ${l})`,line:h.location.line,tags:f})}}}return c.map(({params:l,label:d,line:f,tags:p})=>{let u={value:"action",setup:!1},h=[...Gl(r,l,u),...Gl(s,l,u)];for(let g of h){let S=Hl(g.resolvedText);if(S){let y=g.source?`${g.source.file}:${g.source.line}`:t;throw new Le(`${y} ${S}${g.text!==g.resolvedText?` (with the Examples values of "${e.name}${d}")`:""}`)}}let b=Ye(h.map(g=>g.resolvedText));return{featurePath:t,featureName:n,name:e.name,displayName:`${e.name}${d}`,tags:p,steps:h.map((g,S)=>b[S]===void 0?g:{...g,session:b[S]}),params:l,...e.examples.length>0?{exampleRows:c.map(g=>g.params)}:{},line:e.location.line,...f!==void 0?{exampleLine:f}:{}}})}function Yl(e,t){let n=Qh.readFileSync(e,"utf8"),r=e.endsWith(".saffron"),s=r?Qi(n):{source:n,definitions:new Map,invocations:new Map},o=new nm(new em(rm.uuid()),new tm),a=Xh.relative(t,e),i;try{i=o.parse(s.source)}catch(c){let l=(c instanceof Error?c.message:String(c)).split(`
|
|
8
|
+
`).filter(f=>/^\(\d+:\d+\)/.test(f)).map(f=>`${a}${f.replace(/^\((\d+):(\d+)\)/,":$1:$2")}`),d=!r&&/^\s*StepSet\b/m.test(n);throw new Le(d?`${a} uses StepSet, which only .saffron files understand. Rename it to ${a.replace(/\.feature$/,".saffron")}: nothing else needs to change (a .saffron file accepts everything a .feature file does).`:`${a} is not valid Gherkin:
|
|
9
9
|
${l.join(`
|
|
10
|
-
`)||(c instanceof Error?c.message:String(c))}`)}return{doc:
|
|
10
|
+
`)||(c instanceof Error?c.message:String(c))}`)}return{doc:i,pre:s,relPath:a,isSaffron:r,lineCount:n.split(`
|
|
11
11
|
`).length-(n.endsWith(`
|
|
12
|
-
`)?1:0)}}function Bc(e,t){let{doc:n,pre:r,lineCount:s}=Fc(e,t),o=[],i=(c,l)=>Math.min(l,...c.map(d=>d.location.line)),a=c=>{for(let l of c)if(l.background){let{name:d,location:u}=l.background;o.push({kind:"background",name:d,line:u.line,start:u.line,rows:[]})}else if(l.scenario){let{name:d,location:u,tags:g,examples:f}=l.scenario,p=r.definitions.has(u.line)?"stepSet":"scenario",m=f.flatMap(h=>h.tableBody.map(w=>w.location.line));o.push({kind:p,name:d,line:u.line,start:i(g,u.line),rows:m})}else if("rule"in l&&l.rule){let{name:d,location:u,tags:g}=l.rule;o.push({kind:"rule",name:d,line:u.line,start:i(g,u.line),rows:[]}),a(l.rule.children)}};return n.feature&&a(n.feature.children),{blocks:o,lineCount:s}}function Ir(e){let t=e.split(/\r?\n/),n=t.findIndex(c=>c.trim()!==""&&!c.trim().startsWith("#")),r=(n<0?t:t.slice(0,n)).map(c=>/^\s*#\s*language\s*:\s*([\w-]+)/.exec(c)?.[1]).find(Boolean),s=r&&jc[r]||jc.en,o=[...s.scenario,...s.scenarioOutline].map(c=>`${c.trim()}:`),i=[],a;return t.forEach((c,l)=>{let d=c.trim(),u=['"""',"```"].find(f=>d.startsWith(f));if(u){a?a===u&&(a=void 0):a=u;return}if(a)return;let g=o.find(f=>d.startsWith(f));g&&i.push({line:l+1,name:d.slice(g.length).trim()})}),i}function Ze(e,t,n){let{doc:r,pre:s,relPath:o,isSaffron:i}=Fc(e,t);if(!r.feature)return[];let a=r.feature.name,c=[],l=(d,u,g)=>{let f=u;for(let p of d)if(p.background)f=[...u,...Mc(p.background.steps,o,!0,s.invocations,n)];else if(p.scenario){if(s.definitions.has(p.scenario.location.line))continue;c.push(...fg(p.scenario,o,a,f,Mc(p.scenario.steps,o,!1,s.invocations,n),i,g))}else"rule"in p&&p.rule&&l(p.rule.children,f,[...g,...p.rule.tags.map(m=>m.name)])};return l(r.feature.children,[],r.feature.tags.map(d=>d.name)),c}import ul from"node:fs";import js from"node:path";import il from"node:fs";import al from"node:path";import{createHash as Yc}from"node:crypto";import Et from"node:fs";import Tt from"node:path";import{createHash as mg}from"node:crypto";var ug=/\{date([+-]\d+)?(?::([^}]+))?\}/g;function pg(e,t){let n=String(e.getFullYear()),r=String(e.getMonth()+1).padStart(2,"0"),s=String(e.getDate()).padStart(2,"0");return t.replaceAll("YYYY",n).replaceAll("MM",r).replaceAll("DD",s).replaceAll("M",String(e.getMonth()+1)).replaceAll("D",String(e.getDate()))}function It(e,t=new Date){return e.replace(ug,(n,r,s)=>{let o=new Date(t);return o.setDate(o.getDate()+(r?parseInt(r,10):0)),pg(o,s??"YYYY-MM-DD")})}var gg=/\b(\d{4})-(\d{2})-(\d{2})\b/g,hg=400;function Lc(e,t=new Date,n=[]){let r=new Date(t.getFullYear(),t.getMonth(),t.getDate());return e.replace(gg,(s,o,i,a)=>{if(n.some(d=>d.includes(s)))return s;let c=new Date(Number(o),Number(i)-1,Number(a));if(Number.isNaN(c.getTime()))return s;let l=Math.round((c.getTime()-r.getTime())/864e5);return Math.abs(l)>hg?s:l===0?"{date}":`{date${l>0?"+":""}${l}}`})}function Rt(e,t){let n=r=>typeof r=="string"?r.includes(t):Array.isArray(r)?r.some(n):r&&typeof r=="object"?Object.entries(r).some(([s,o])=>s!=="pageFingerprint"&&n(o)):!1;return e.some(n)}function jr(e){return[e.action==="expectDiffers"?void 0:e.value,e.url,e.urlPattern,e.pattern,e.promptText,e.each,...[e.target,e.toTarget].flatMap(t=>[t?.name,t?.nameRegex,t?.label,t?.text,t?.placeholder,t?.testId,t?.frame,...t?.fallbackSelectors??[]])]}function Qt(e){return[...jr(e),e.status,e.method,e.attribute]}function Xt(e,t){if(t.trim()==="")return!1;let{exact:n,loose:r}=qc(t),s=r.map(i=>en(i,"iu")),o=i=>{let a=i.replace(Ue," ").replace(Ie," "),c=a.replace(/<[^<>]+>/g," ").normalize("NFC");return/[<>]/.test(t)?[c,a.normalize("NFC")]:[c]};return e.some(i=>Qt(i).some(a=>a!==void 0&&o(a).some(c=>{let l=t.length<3?c.replace(ci," "):c;return n.some(d=>l.includes(d))||s.some(d=>d.test(l))})))}function Pn(e,t,n,r,s,o){let i=s?Date.parse(s):NaN,a=Object.keys(n),c=_s(t,o,a),l=(d,u)=>ai(d,o,u);for(let[d,u]of a.entries())for(let g of a.slice(d+1))if(!(r[u]===void 0||r[g]===void 0||l(n[u],i)==="")&&!(l(n[u],i)!==l(n[g],i)||l(r[u])===l(r[g]))&&(Rt(e,`<${u}>`)||Rt(e,`<${g}>`)))return!0;for(let d of a.filter(u=>/\{env:/.test(n[u])&&r[u]!==void 0))if([...n[d].matchAll(Ue)].map(([g])=>g).some(g=>!t.includes(g)&&Rt(e,g))){for(let g of a)if(!(g===d||/\{env:/.test(n[g])||r[g]===void 0||!t.includes(`<${g}>`)||Rt(e,`<${g}>`))&&l(r[g])!==l(r[d]))return!0}return Object.entries(n).some(([d,u])=>{let g=r[d];if(g===void 0)return!1;let f=u.includes("{date")&&!Number.isNaN(i);if(g===u&&(!f||It(u,new Date(i))===It(g)))return!1;let p=t.includes(`<${d}>`);if(u.trim()==="")return p&&g.trim()!==""&&!Rt(e,`<${d}>`);let m=new Set(g===u?[]:_s(u,o,a));if(f){let h=u.replace(/\{date([+-]\d+)?:[^}]*\}/g,"{date$1}");h!==u&&p&&g!==u&&m.add(h);for(let w of[0,1])for(let b of new Set([u,h])){let y=It(b,new Date(i-w*864e5));(p||/(?<!\d)\d{4}(?!\d)/.test(y))&&m.add(y)}}return[...m].some(h=>h.trim()!==""&&(p||!c.some(w=>en(h).test(w)))&&Hc(e,h,p,w=>_s(w,o,a)))})}function zc(e,t,n={}){let r=/\{env:|\{date/;if(e.some(i=>Qt(i).some(a=>a!==void 0&&(r.test(a)||/\{data:/.test(a))))||Object.values(t).some(i=>i.trim()==="")&&e.some(i=>i.value===""))return!0;let s=Object.values(t).filter(i=>i.trim()!=="");if(new Set(s).size<s.length)return!0;let o=i=>[i.replace(Xn(Object.keys(t))," ").normalize("NFC")];return Object.values(t).some(i=>{if(r.test(i)||[...i.matchAll(Ie)].some(([,c])=>!(c in n)))return!0;let a=i.replace(Ie,(c,l)=>n[l]);return[i,a].some(c=>c.trim()!==""&&Hc(e,c,!0,o))})}function Hc(e,t,n,r){if(t.length<3&&!n)return!1;let{exact:s,loose:o}=qc(t),i=n&&t.length>=3,a=s.map(u=>Ps(t,u,"u",n)),c=o.map(u=>en(u,"iu")),l=u=>{let g=t.length<3?u.replace(ci," "):u;return a.some(f=>f.test(g))||(i?o.some(f=>g.toLowerCase().includes(f)):c.some(f=>f.test(g)))},d=u=>n?Qt(u):jr(u);return e.some(u=>d(u).some(g=>g!==void 0&&r(g).some(l)))}function Ps(e,t=e,n="gu",r=!0){let s=t.normalize("NFC");return r&&e.length>=3?new RegExp(je(s),n):en(s,n)}function Qn(e,t,n,r=t){let s=e.normalize("NFC");return s.includes(r.normalize("NFC"))?Ps(t,r,"u",n).test(t.length<3?s.replace(ci," "):s):!1}function ai(e,t,n){return It(_s(e,t,[]).at(-1),n===void 0||Number.isNaN(n)?new Date:new Date(n))}function Nr(e,t,n,r,s){let o=r?Date.parse(r):NaN;return e.find(i=>{let a=t[i],c=n[i];return a===void 0||c===void 0?!0:a!==c&&ai(a,s,o)!==ai(c,s)})}function Xn(e){return new RegExp(`<(?:table:[^<>]+|docstring${[...e].map(t=>`|${je(t)}`).join("")})>`,"g")}var Dc=String.raw`[\p{L}\p{N}\p{M}]`,Uc=/[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Thai}\p{Script=Lao}\p{Script=Khmer}\p{Script=Myanmar}]/u,ci=/:nth-[a-z-]+\([^)]*\)|\bnth=-?\d+|\bh[1-6]\b/gi;function en(e,t="u"){let n=[...e],r=n.length>=2&&Uc.test(n[0])?"":`(?<!${Dc})`,s=n.length>=2&&Uc.test(n[n.length-1])?"":`(?!${Dc})`;return new RegExp(`${r}${e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}${s}`,t)}function qc(e){let t=e.normalize("NFC"),n=[...new Set([t,...Object.values(we).map(i=>i(t))])],r=t.toLowerCase(),s=new Set([r]);try{s.add(encodeURIComponent(t).toLowerCase()),s.add(encodeURIComponent(t).replaceAll("%20","+").toLowerCase())}catch{}let o=r.split(/[^\p{L}\p{N}\p{M}]+/u).filter(Boolean);if(o.length>1)for(let i of["-","_",""])s.add(o.join(i));return{exact:n,loose:[...s]}}function li(e){return e.length>=5||e.length>=3&&/\p{N}/u.test(e)}function _s(e,t,n){let r=(e??"").replace(n?Xn(n):/<[^<>]+>/g," ").normalize("NFC"),s=r.replace(Ie,(o,i)=>t?.[i]??wg(i)??o).replace(Ue,(o,i)=>process.env[i]??o);return s===r?[r]:[r,s]}function wg(e){try{return Je(e)}catch{return}}function Vc(e,t){return e===t?"bare":e===`^${t}$`?"anchored":void 0}function er(e){if(!/\{(?:env|data):/.test(e))return;let t=!1,n=e.replace(Ie,(s,o)=>{try{return Je(o)}catch{return t=!0,s}});if(!new RegExp(Ue.source).test(n))return;let r=n.replace(Ue,(s,o)=>{let i=process.env[o];return i===void 0&&(t=!0),i??s});return t?void 0:mg("sha256").update(r).digest("hex")}var at=new Set(["expectVisible","expectNotVisible","expectText","expectUrl","expectValue","expectDiffers","expectMatches","expectAttribute","expectResponse","expectEach"]);function Mr(e){if((e.rowBound?.length??0)>0||Ke(e.steps.map(n=>n.gherkin)).some(n=>n!==void 0)||e.examples&&e.steps.some(n=>zc(n.actions,e.examples,e.data)))return 2;let t=n=>n.clickCount!==void 0&&n.clickCount!==1||n.button!==void 0&&n.button!=="left"||(n.modifiers?.length??0)>0||n.clearSelection===!0||n.action==="selectOption"&&(n.value??"").includes(`
|
|
13
|
-
`)||[n.status,n.method,n.attribute].some(r=>r!==void 0&&/<[^<>]+>|\{(?:data|env|date|unique)[^{}]*\}/.test(r));return e.steps.some(n=>n.actions.some(t))?2:1}import Jc from"node:path";var Os=2,yg=new Set(["goto","click","fill","press","selectOption","check","uncheck","hover","waitFor","captureText","handleDialog","uploadFile","dragTo","waitForResponse","switchTab","closeTab","newTab",...at]),bg=["role","name","nameRegex","label","text","testId","placeholder","frame"],vg=["value","url","saveAs","compareTo","each","pattern","attribute","promptText","urlPattern","method","status","pageFingerprint"],di=/[\u0000-\u001f\u007f-\u009f]/,ge=class extends Error{constructor(n,r){super(`${n}: ${r}`);this.file=n;this.problem=r}file;problem},Qe=e=>e!==null&&typeof e=="object"&&!Array.isArray(e);function J(e,t,n){if(!e)throw new ge(t,n)}function Wc(e,t,n){J(Qe(e),t,`${n} must be an object`);for(let r of bg)J(e[r]===void 0||typeof e[r]=="string",t,`${n}.${r} must be a string`);e.fallbackSelectors!==void 0&&J(Array.isArray(e.fallbackSelectors)&&e.fallbackSelectors.every(r=>typeof r=="string"),t,`${n}.fallbackSelectors must be a list of selectors`)}var xg=e=>["role","label","text","testId","placeholder"].some(t=>typeof e[t]=="string"&&e[t]!=="")||Array.isArray(e.fallbackSelectors)&&e.fallbackSelectors.some(t=>typeof t=="string"&&t.trim().length>0),Sg={goto:["url"],click:["target"],fill:["target","value"],press:["value"],selectOption:["target","valueOrClear"],check:["target"],uncheck:["target"],hover:["target"],waitFor:["targetOrValue"],captureText:["target","saveAs"],handleDialog:[],uploadFile:["value"],dragTo:["target","toTarget"],waitForResponse:["urlPattern"],switchTab:["value"],closeTab:[],newTab:[],expectVisible:["target"],expectNotVisible:["target"],expectText:["target","value"],expectUrl:["urlOrValue"],expectValue:["target","value"],expectDiffers:["compareTo","targetOrValue"],expectMatches:["target","pattern"],expectAttribute:["target","attribute","pattern"],expectResponse:["urlPattern"],expectEach:["target","each"]};function $g(e,t,n){let r=o=>typeof e[o]=="string",s=o=>Qe(e[o])&&xg(e[o]);for(let o of Sg[e.action])switch(o){case"target":case"toTarget":J(s(o),t,`${n} (${e.action}) needs a ${o} with a role, name, label, text, test id, placeholder or selector`);break;case"urlOrValue":J(r("url")||r("value"),t,`${n} (${e.action}) needs a url`);break;case"targetOrValue":J(s("target")||r("value"),t,`${n} (${e.action}) needs a target or a value`);break;case"valueOrClear":J(r("value")||e.clearSelection===!0,t,`${n} (${e.action}) needs value`);break;default:J(r(o),t,`${n} (${e.action}) needs ${o}`)}for(let o of["target","toTarget"])e[o]!==void 0&&J(s(o),t,`${n}.${o} has no usable locator`);if(e.action==="expectUrl"){let o=e.url??e.value;J(typeof o=="string"&&o.length>0,t,`${n} (expectUrl) needs a non-empty url or value`)}for(let o of["url","saveAs","compareTo","each","pattern","attribute","urlPattern"])e[o]!==void 0&&J(e[o].length>0,t,`${n}.${o} must not be empty`);["press","uploadFile","switchTab","expectText"].includes(e.action)&&J(typeof e.value=="string"&&e.value.length>0,t,`${n} (${e.action}) needs a non-empty value`)}function kg(e,t,n){J(Qe(e),t,`${n} must be an object`),J(typeof e.action=="string",t,`${n}.action is missing`),J(yg.has(e.action),t,`${n}.action "${e.action}" is not an action this runner knows. Recorded by a newer saffron-ai? Update, or re-record with --rerecord`);for(let r of vg)J(e[r]===void 0||typeof e[r]=="string",t,`${n}.${r} must be a string`);J(e.opensTab===void 0||typeof e.opensTab=="boolean",t,`${n}.opensTab must be true or false`),J(e.clearSelection===void 0||typeof e.clearSelection=="boolean",t,`${n}.clearSelection must be true or false`),J(e.clickCount===void 0||Number.isInteger(e.clickCount)&&e.clickCount>=1,t,`${n}.clickCount must be a whole number from 1`),J(e.button===void 0||["left","right","middle"].includes(e.button),t,`${n}.button must be "left", "right" or "middle"`),J(e.modifiers===void 0||Array.isArray(e.modifiers)&&e.modifiers.every(r=>["Alt","Control","ControlOrMeta","Meta","Shift"].includes(r)),t,`${n}.modifiers must be a list of Alt, Control, ControlOrMeta, Meta or Shift`),e.target!==void 0&&Wc(e.target,t,`${n}.target`),e.toTarget!==void 0&&Wc(e.toTarget,t,`${n}.toTarget`),$g(e,t,n)}function Rg(e,t,n){J(Qe(e),t,`${n} must be an object`),J(typeof e.gherkin=="string"&&e.gherkin.length>0,t,`${n}.gherkin (the step text) is missing`),J(typeof e.keyword=="string",t,`${n}.keyword is missing`),J(e.kind==="action"||e.kind==="assertion",t,`${n}.kind must be "action" or "assertion"`),J(Array.isArray(e.actions),t,`${n}.actions must be a list (empty for a recorded no-op)`),e.actions.forEach((r,s)=>kg(r,t,`${n}.actions[${s}]`)),e.table!==void 0&&J(Array.isArray(e.table)&&e.table.every(r=>Array.isArray(r)&&r.every(s=>typeof s=="string")),t,`${n}.table must be rows of strings`),J(e.docString===void 0||typeof e.docString=="string",t,`${n}.docString must be a string`),J(e.fromStepSet===void 0||typeof e.fromStepSet=="string",t,`${n}.fromStepSet must be a string`)}function fi(e,t){if(J(Qe(e),t,"is not a JSON object"),J(e.version!==void 0,t,"has no version: not a Saffron recording"),J(e.version===1||e.version===Os,t,typeof e.version=="number"&&e.version>Os?`is schema version ${e.version}; this saffron-ai reads versions 1 to ${Os}. Update saffron-ai to the release that wrote it`:`has schema version ${JSON.stringify(e.version)}; this saffron-ai reads versions 1 to ${Os}`),J(typeof e.feature=="string"&&e.feature.length>0,t,"feature (the feature file path) is missing"),J(!Jc.isAbsolute(e.feature)&&!Jc.win32.isAbsolute(e.feature)&&!e.feature.split(/[\\/]/).includes(".."),t,`names a feature file outside the project: ${JSON.stringify(e.feature)}`),J(typeof e.scenario=="string"&&e.scenario.length>0,t,"scenario (the scenario name) is missing"),J(e.recordedAt===void 0||typeof e.recordedAt=="string",t,"recordedAt must be a string"),J(e.recordedBy===void 0||e.recordedBy==="agent"||e.recordedBy==="manual",t,'recordedBy must be "agent" or "manual"'),J(Array.isArray(e.steps),t,"steps must be a list"),e.steps.forEach((n,r)=>Rg(n,t,`steps[${r}]`)),e.data!==void 0&&J(Qe(e.data)&&Object.values(e.data).every(n=>typeof n=="string"),t,"data must map references to strings"),e.examples!==void 0&&J(Qe(e.examples)&&Object.values(e.examples).every(n=>typeof n=="string"),t,"examples must map columns to strings"),e.rowBound!==void 0){let n=e.steps.length;J(Array.isArray(e.rowBound)&&e.rowBound.every(r=>Qe(r)&&typeof r.column=="string"&&Number.isInteger(r.step)&&r.step>=0&&r.step<n&&(r.reason==="list"||r.reason==="glued"||r.reason==="data"||r.reason==="value"||r.reason==="reads")&&(r.valueSha===void 0||typeof r.valueSha=="string"&&/^[0-9a-f]{64}$/.test(r.valueSha))),t,'rowBound must be a list of { column, step, reason: "list" | "glued" | "data" | "value" | "reads", valueSha? } naming steps of this recording'),J(Qe(e.examples),t,"rowBound needs examples, the row it was recorded on")}return e}function Gc(e,t){J(Qe(e),t,"is not a JSON object"),J(Qe(e.meta),t,"meta is missing: not a Saffron proposal");let n=e.meta;J(n.mode==="record"||n.mode==="heal",t,'meta.mode must be "record" or "heal"'),J(typeof n.narrative=="string",t,"meta.narrative must be a string"),J(Array.isArray(n.adaptations)&&n.adaptations.every(r=>typeof r=="string"),t,"meta.adaptations must be a list of strings"),J(n.verified===void 0||typeof n.verified=="boolean",t,"meta.verified must be true or false"),J(Qe(n.usage),t,"meta.usage is missing"),n.featureEdits!==void 0&&(J(Array.isArray(n.featureEdits)&&n.featureEdits.every(r=>Qe(r)&&typeof r.index=="number"&&typeof r.text=="string"),t,"meta.featureEdits must be a list of { index, text }"),n.featureEdits.forEach((r,s)=>J(r.text.trim().length>0,t,`meta.featureEdits[${s}].text is empty: a feature edit must give the step's new text`)),n.featureEdits.forEach((r,s)=>J(!di.test(r.text),t,`meta.featureEdits[${s}].text holds a line break or another control character`))),n.bound!==void 0&&J(Qe(n.bound)&&["scenario","committed","recording"].every(r=>typeof n.bound[r]=="string"),t,"meta.bound must hold the scenario, committed and recording digests"),fi(e.cache,`${t} (cache)`)}var Zc=".saffron",Qc=e=>Yc("sha1").update(e).digest("hex").slice(0,8),pi=e=>e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"");function Xc(e){return pi(e)||`unnamed-${Qc(e)}`}var el=e=>pi(e)||"unnamed";function tl(e){let t=pi(e);return t&&/[^\x00-\x7f]/.test(e)?`${t}-${Qc(e)}`:Xc(e)}function nl(e,t,n,r){let s;try{s=Et.readFileSync(e,"utf8")}catch{return!0}try{return t(JSON.parse(s))}catch{return r.some(o=>new RegExp(`"${n}"\\s*:\\s*${je(JSON.stringify(o))}`).test(s))}}function Tg(e,t,n){let r=Tt.join(e,`${tl(t)}.json`),s=Tt.join(e,`${el(t)}.json`);return s===r||Et.existsSync(r)||!Et.existsSync(s)?r:nl(s,o=>n(o)===t,"scenario",[t])?s:r}var Kc=new Map;function rl(e){let t=Tt.join(e,"saffron.config.json"),n=Et.statSync(t,{throwIfNoEntry:!1}),r=n?`${n.mtimeMs}:${n.ctimeMs}:${n.size}:${n.ino}`:"none",s=Kc.get(e);if(s?.stamp===r)return s.top;let o="features";try{let c=JSON.parse(Et.readFileSync(t,"utf8"));typeof c?.features=="string"&&c.features.trim()&&(o=c.features)}catch{}let i=Tt.relative(e,Tt.resolve(e,o)),a=i.startsWith("..")||Tt.isAbsolute(i)?void 0:i.split(/[\\/]/)[0];return Kc.set(e,{stamp:r,top:a}),a}function ui(e,t,n=Xc){let r=e.split(/[\\/]/).filter(Boolean),s=r.pop()??"unnamed",o=t===void 0||r[0]===t?r.slice(1):r,i=n([...o,Tt.basename(s,".feature")].join("-"));if(o.length===0)return i;let a=Yc("sha1").update(e.replace(/\\/g,"/")).digest("hex").slice(0,6);return`${i}-${a}`}function sl(e,t,n,r,s){let o=d=>Tg(Tt.join(e,Zc,t,d),r,u=>s(u)?.scenario),i=o(ui(n,rl(e))),a=o(ui(n,void 0,el));if(a===i||Et.existsSync(i)||!Et.existsSync(a))return i;let c=d=>typeof d=="string"?d.replace(/\\/g,"/"):d;return nl(a,d=>c(s(d)?.feature)===c(n),"feature",[n,c(n)])?a:i}function fe(e,t,n){return sl(e,"cache",t,n,r=>r)}function ol(e,t){let n=new Map;for(let r of t){let s=fe(e,r.featurePath,r.name),o=n.get(s)??new Set;o.add(`${r.featurePath} \u203A ${r.name}${r.line?` (line ${r.line})`:""}`),n.set(s,o)}return[...n.entries()].filter(([,r])=>r.size>1).map(([r,s])=>`${[...s].join(" and ")} both map to ${Tt.relative(e,r)}. Rename one scenario or one file.`)}var On="owner.json";function tn(e,t,n){return Tt.join(e,Zc,"artifacts",ui(t,rl(e)),tl(n))}function ct(e,t,n){return sl(e,"proposals",t,n,r=>r?.cache)}function jt(e,t){try{return He(e)}catch(n){if(!(n instanceof ge))throw n;t?.(e,n.problem);return}}function He(e){if(!Et.existsSync(e))return;let t;try{t=JSON.parse(Et.readFileSync(e,"utf8"))}catch(n){throw new ge(e,`is not valid JSON: ${n instanceof Error?n.message:String(n)}`)}return fi(t,e)}function tr(e,t){Et.mkdirSync(Tt.dirname(e),{recursive:!0}),Et.writeFileSync(e,`${JSON.stringify({...t,version:Mr(t)},null,2)}
|
|
14
|
-
`)}function
|
|
15
|
-
${t}`;function
|
|
16
|
-
`)
|
|
17
|
-
`)
|
|
18
|
-
`
|
|
19
|
-
`
|
|
20
|
-
`)
|
|
12
|
+
`)?1:0)}}function Zl(e,t){let{doc:n,pre:r,lineCount:s}=Yl(e,t),o=[],a=(c,l)=>Math.min(l,...c.map(d=>d.location.line)),i=c=>{for(let l of c)if(l.background){let{name:d,location:f}=l.background;o.push({kind:"background",name:d,line:f.line,start:f.line,rows:[]})}else if(l.scenario){let{name:d,location:f,tags:p,examples:u}=l.scenario,h=r.definitions.has(f.line)?"stepSet":"scenario",b=u.flatMap(g=>g.tableBody.map(S=>S.location.line));o.push({kind:h,name:d,line:f.line,start:a(p,f.line),rows:b})}else if("rule"in l&&l.rule){let{name:d,location:f,tags:p}=l.rule;o.push({kind:"rule",name:d,line:f.line,start:a(p,f.line),rows:[]}),i(l.rule.children)}};return n.feature&&i(n.feature.children),{blocks:o,lineCount:s}}function ss(e){let t=e.split(/\r?\n/),n=t.findIndex(c=>c.trim()!==""&&!c.trim().startsWith("#")),r=(n<0?t:t.slice(0,n)).map(c=>/^\s*#\s*language\s*:\s*([\w-]+)/.exec(c)?.[1]).find(Boolean),s=r&&Wl[r]||Wl.en,o=[...s.scenario,...s.scenarioOutline].map(c=>`${c.trim()}:`),a=[],i;return t.forEach((c,l)=>{let d=c.trim(),f=['"""',"```"].find(u=>d.startsWith(u));if(f){i?i===f&&(i=void 0):i=f;return}if(i)return;let p=o.find(u=>d.startsWith(u));p&&a.push({line:l+1,name:d.slice(p.length).trim()})}),a}function ft(e,t,n){let{doc:r,pre:s,relPath:o,isSaffron:a}=Yl(e,t);if(!r.feature)return[];let i=r.feature.name,c=[],l=(d,f,p)=>{let u=f;for(let h of d)if(h.background)u=[...f,...Kl(h.background.steps,o,!0,s.invocations,n)];else if(h.scenario){if(s.definitions.has(h.scenario.location.line))continue;c.push(...sm(h.scenario,o,i,u,Kl(h.scenario.steps,o,!1,s.invocations,n),a,p))}else"rule"in h&&h.rule&&l(h.rule.children,u,[...p,...h.rule.tags.map(b=>b.name)])};return l(r.feature.children,[],r.feature.tags.map(d=>d.name)),c}import zd from"node:fs";import bo from"node:path";import Md from"node:fs";import Dd from"node:path";import{createHash as dm,randomBytes as um,scryptSync as fd}from"node:crypto";var uo="__saffron_date_clock",Sr=/\{date(?:([+-]\d+)(?:([^\d{}:]+?)([+-]\d+))?)?(?::([^}]+))?\}/g,Xl="YYYY|YY|MMMM|MMM|MM|M|DD|D|dddd|ddd",ea=new RegExp(Xl,"g"),om=new Set(["YYYY","MM","M","DD","D"]),ed=/^[a-z]{2,3}(?:-[A-Za-z0-9]{1,8})*$/,lo={locale:"en-US"},ta=e=>{let t=!1;try{t=ed.test(e)&&Intl.DateTimeFormat.supportedLocalesOf(e).length>0}catch{}return t?void 0:`"${e}" is not a locale this Node.js knows: use a tag such as en-US or de-DE`};function td(e="en-US",t){let n=ta(e);if(n)throw new Error(`dateLocale in saffron.config.json: ${n}`);if(t!==void 0){let r;try{r=new Intl.DateTimeFormat("en-US",{timeZone:t}).resolvedOptions().timeZone}catch{throw new Error(`timezone in saffron.config.json: "${t}" is not a time zone: use an IANA name such as Europe/Berlin`)}if(r.toLowerCase()===t.toLowerCase()&&r!==t)throw new Error(`timezone in saffron.config.json: write "${t}" as "${r}", as browsers require`);if(!/^[A-Za-z]/.test(r))throw new Error(`timezone in saffron.config.json: "${t}" is an offset, which browsers do not take: use an IANA name such as Europe/Berlin, or Etc/GMT-2 for a fixed +02:00`)}lo={locale:e,timeZone:t}}function na(e){if(e===void 0)return{format:"YYYY-MM-DD"};let t=e.lastIndexOf(":"),n=e.slice(t+1);return t>=0&&ed.test(n)?{format:e.slice(0,t),locale:n}:{format:e}}function nd(e){if(!lo.timeZone)return[e.getFullYear(),e.getMonth(),e.getDate()];let t=new Intl.DateTimeFormat("en-US",{timeZone:lo.timeZone,year:"numeric",month:"numeric",day:"numeric"}).formatToParts(e),n=r=>Number(t.find(s=>s.type===r).value);return[n("year"),n("month")-1,n("day")]}var Ql=(e,t)=>{let[n,r,s]=nd(e);return new Date(Date.UTC(n,r,s+t))};function im(e,t,n,r){let s=n.match(ea)??[],o=t[0]==="M"?"month":"weekday",a={timeZone:"UTC",calendar:"gregory",[o]:t.length===4?"long":"short"};return s.some(i=>i[0]==="D")&&(a.day="numeric"),s.some(i=>i[0]==="Y")&&(a.year="numeric"),o==="weekday"&&s.some(i=>i[0]==="M")&&(a.month=s.includes("MMMM")?"long":s.includes("MMM")?"short":"numeric"),new Intl.DateTimeFormat(r,a).formatToParts(e).find(i=>i.type===o)?.value??t}function rd(e,t,n,r){switch(t){case"YYYY":return String(e.getUTCFullYear());case"YY":return String(e.getUTCFullYear()%100).padStart(2,"0");case"MM":return String(e.getUTCMonth()+1).padStart(2,"0");case"M":return String(e.getUTCMonth()+1);case"DD":return String(e.getUTCDate()).padStart(2,"0");case"D":return String(e.getUTCDate());default:return im(e,t,n,r)}}var sd=(e,t,n)=>t.replace(ea,r=>rd(e,r,t,n));function am(e,t,n,r,s){let o=n.split(new RegExp(`(${Xl})`)),a=e.getUTCFullYear()!==t.getUTCFullYear(),i=a||e.getUTCMonth()!==t.getUTCMonth(),c=i||e.getUTCDate()!==t.getUTCDate(),l=h=>h[0]==="Y"?a:h[0]==="M"?i:c,d=o.flatMap((h,b)=>b%2&&l(h)?[b]:[]);if(d.length===0)return sd(e,n,s);let f=(h,b,g)=>o.slice(b,g).map((S,y)=>(b+y)%2?rd(h,S,n,s):S).join(""),p=d[d.length-1],u=/^[^\s,/-]*/.exec(o[p+1]??"")[0];return`${f(e,0,p+1)}${u}${r}${f(t,d[0],o.length)}`}function Ve(e,t=new Date){return e.replace(Sr,(n,r,s,o,a)=>{let{format:i,locale:c=lo.locale}=na(a);if(ta(c))return n;let l=Ql(t,Number(r??0));return o===void 0?sd(l,i,c):am(l,Ql(t,Number(o)),i,s,c)})}function fo(e){let t=new RegExp(`^${Sr.source}$`).exec(e);if(!t)return`${e} is not a date Saffron can resolve: write {date+N}, {date+N:FORMAT}, {date+N:FORMAT:LOCALE}, or a range such as {date+7 - +9:MMM D, YYYY}`;if([t[1],t[3]].some(o=>o!==void 0&&Math.abs(Number(o))>36600))return`${e} is more than a hundred years away: Saffron counts days within 36600 of today`;let{locale:n}=na(t[4]),r=n===void 0?void 0:ta(n);if(r)return`${e}: ${r}`;let s=t[4]?.includes(":")?t[4].slice(t[4].lastIndexOf(":")+1):void 0;if(n===void 0&&s!==void 0&&/^[A-Za-z]{2,3}(?:[-_][A-Za-z0-9]{1,8})*$/.test(s)&&!/^[YMDd]+$/.test(s))return`${e}: "${s}" is not a locale this Node.js knows: use a tag such as en-US or de-DE`}var ra=/\{date(?=[}:]|\s*[+-]\s*\d)[^{}]*\}/g,od=e=>e.match(ra)??[];function Kn(e){return[...e.matchAll(Sr)].some(({3:t,4:n})=>{let{format:r,locale:s}=na(n);return t!==void 0||s!==void 0||(r.match(ea)??[]).some(o=>!om.has(o))})}var cm=/\b(\d{4})-(\d{2})-(\d{2})\b/g,lm=400;function id(e,t=new Date,n=[]){let[r,s,o]=nd(t),a=Date.UTC(r,s,o);return e.replace(cm,(i,c,l,d)=>{if(n.some(p=>p.includes(i)))return i;let f=(Date.UTC(Number(c),Number(l)-1,Number(d))-a)/864e5;return Math.abs(f)>lm?i:f===0?"{date}":`{date${f>0?"+":""}${f}}`})}function vt(e){let t=e.replace(/(\d)[\s\u00a0\u202f'\u2019](?=\d{3}(?!\d))/g,"$1"),n=[...t.matchAll(/[-\u2212\u2013]?\d(?:[\d.,]*\d)?/g)];if(n.length!==1)return;let[r]=n,s=t.slice(0,r.index),o=t.slice(r.index+r[0].length),a=/[.,]$/.test(s)&&!/\d[.,]$/.test(s)&&/^\d+$/.test(r[0]),i=a?s.slice(0,-1):s,c=/^[-\u2212\u2013]/.test(r[0])||a&&/[-\u2212\u2013]$/.test(i)||/(?:^|[\s(:])[-\u2212\u2013][^\d\s.,()\-\u2212\u2013]{1,4}\s?$/.test(i)||/^[-\u2212\u2013](?!\d)/.test(o)||/\(\s?[^\d\s.,()]{0,4}\s?$/.test(i)&&/^\s?[^\d\s.,()]{0,4}\s?\)/.test(o)&&(/[.,]/.test(r[0])||/[^\d\s.,()]\s?$/.test(i)||/^\s?[^\d\s.,()]/.test(o)),l=a?`0${s.slice(-1)}${r[0]}`:r[0].replace(/^[-\u2212\u2013]/,""),d=Math.max(l.lastIndexOf("."),l.lastIndexOf(",")),f=d<0?l:l.slice(0,d),p=d<0?"":l.slice(d+1),u=d>=0&&(p.length!==3||/^0?$/.test(f)||f.includes(l[d]==="."?",":".")),h=u?f:l,b=h.split(/[.,]/),g=new Set(h.match(/[.,]/g)??[]);if(g.size>1||u&&g.has(l[d])||b[0]===""||b.slice(1).some(y=>y.length!==3))return;let S=+`${c?"-":""}${b.join("")}${u?`.${p}`:""}`;return Number.isFinite(S)?S:void 0}var En=(e,t)=>Math.abs(e-t)<.005,cd=e=>e.toFixed(2);function po(e,t){let n=e.trim(),r=ad(n,/^ ([+-]) /);if(/\s[-+*×]$|^[+*×]\s/.test(n)||r.some(o=>o.text.trim()===""))return{problem:`"${e}" is not an amount expression: write terms such as "before" + "breakfast"`};let s=0;for(let o of r){let a=1;for(let{text:i}of ad(o.text,/^ ([*×]) /)){let c=i.trim(),l=/^"([^"]+)"$/.exec(c)?.[1];if(l===void 0&&c.includes('"'))return{problem:`"${e}" is not an amount expression: write each captured name in double quotes on its own, operators between spaces, as in "before" + "breakfast"`};let d=l===void 0?c:t(l);if(d===void 0)return{problem:`no captured value named "${l}"`};let f=vt(d);if(f===void 0)return{problem:l===void 0?`"${c}" is not an amount`:`"${l}" (${d}) does not hold exactly one amount`};a*=f}s+=o.op==="-"?-a:a}return{amount:s}}function Yn(e,t,n=r=>r){return e.split(/("[^"]*")/).map((r,s)=>s%2===1?`"${n(r.slice(1,-1))}"`:t(r)??r).join("")}function sa(e){return e?e.replace(/"[^"]*"/g," ").split(/\s[-+*\u00d7]\s/).flatMap(t=>/[<{]/.test(t)?[]:[vt(t.trim())]).filter(t=>t!==void 0):[]}function ld(e,t){if(t.length===0)return e;let n=e.split(/(\s[-+*\u00d7]\s)/),r=(o,a)=>{if(a%2===1||/[<{]/.test(o))return;let i=vt(o.trim()),c=i===void 0?[]:t.filter(([,l])=>En(l,i));return c.length===1?c[0][0]:void 0},s=n.map(r);return n.map((o,a)=>s[a]!==void 0&&s.filter(i=>i===s[a]).length===1?o.replace(o.trim(),`<${s[a]}>`):o).join("")}function ad(e,t){let n=[],r="+",s=0,o=!1;for(let a=0;a<e.length;a++){if(e[a]==='"'&&(o=!o),o)continue;let i=t.exec(e.slice(a));i&&(n.push({op:r,text:e.slice(s,a)}),r=i[1],s=a+i[0].length,a=s-1)}return n.push({op:r,text:e.slice(s)}),n}function $r(e,t,n){let r=o=>pt(t,`<${o}>`)||/^\{(?:env|data):[^{}]+\}$/.test(n[o]??"")&&pt(t,n[o]),s=o=>Object.keys(n).some(a=>a!==o&&n[a]===n[o]&&r(a));return[...new Set([...fe(e).matchAll(/<([^<>]+)>/g)].map(o=>o[1]))].filter(o=>!r(o)&&!s(o))}function pd(e,t){if(t.trim()==="")return!1;let n=Tr(t).exact;return e.flatMap(s=>Et(s)).filter(s=>s!==void 0).some(s=>n.some(o=>t.length>=3?aa(o).test(s):xe(o).test(s)))||gd(e,t)}function aa(e){let t=/^\p{Lu}/u.test(e)?"(?<!\\p{Lu})":/^\p{L}/u.test(e)?"(?<!\\p{L})":/^\p{N}/u.test(e)?"(?<!\\p{N})":"",n=/\p{L}$/u.test(e)?"(?!\\p{Ll})":/\p{N}$/u.test(e)?"(?!\\p{N})":"";return new RegExp(`${t}${be(e)}${n}`,"u")}function gd(e,t){let n=vt(t);return e.some(r=>[r.target?.role,r.toTarget?.role].includes(t.trim())||n!==void 0&&r.action==="expectAmount"&&sa(r.value??"").some(s=>En(s,n)))}function On(e,t){return t.length>=3?cn(e,t)||gd(e,t):pd(e,t)}function os(e,t,n,r=[],s){for(let[,o]of e.matchAll(/\{data:([^{}]*<[^<>{}]+>[^{}]*)\}/g)){let a=p=>{try{return qe(o.replace(/<([^<>]+)>/g,(u,h)=>p[h]??u))}catch{return}},i=a(t),c=a(n);if(i===void 0||c===void 0||i===c)continue;if(s!==void 0){if(!xe(i).test(s)&&ca(r,i))return!0;continue}if(i.trim()===""?c.trim()!=="":On(r,i))return!0;let l=`{data:${o}}`,d=e.replace(/\{[^{}]*\}|<[^<>]+>/g," ");if((xe(i).test(d)||i.length>=4&&d.includes(i))&&JSON.stringify(r).split(l).length>e.split(l).length)return!0}return!1}var kr=e=>e.length>0&&e.filter(t=>Se.has(t.action)).every(t=>![t.value,t.action==="expectAttribute"?void 0:t.pattern].some(n=>n!==void 0&&n.trim()!=="")),ca=(e,t)=>{if(pd(e,t))return!0;if(t.trim()==="")return!1;let n=e.flatMap(r=>Et(r)).filter(r=>r!==void 0);return Tr(t).loose.some(r=>r!==""&&n.some(s=>xe(r,"iu").test(s)))};function go(e,t,n){return fe(e.replace(/\{data:[^{}]*\}/g," ")).includes(`<${t}>`)?!1:[...e.matchAll(/\{data:([^{}]*<[^<>{}]+>[^{}]*)\}/g)].filter(r=>r[1].includes(`<${t}>`)).every(r=>{try{return qe(r[1].replace(/<([^<>]+)>/g,(s,o)=>n[o]??s)).trim()===""}catch{return!1}})}function pt(e,t){let n=r=>typeof r=="string"?r.includes(t):Array.isArray(r)?r.some(n):r&&typeof r=="object"?Object.entries(r).some(([s,o])=>s!=="pageFingerprint"&&n(o)):!1;return e.some(n)}function _n(e){return[e.action==="expectDiffers"?void 0:e.action==="expectAmount"?e.value?.replace(/"[^"]*"/g,'""'):e.value,e.url,e.urlPattern,e.pattern,e.promptText,e.each,...[e.target,e.toTarget].flatMap(t=>[t?.name,t?.nameRegex,t?.label,t?.text,t?.placeholder,t?.testId,t?.frame,...t?.fallbackSelectors??[]])]}function Et(e){return[..._n(e),e.status,e.method,e.attribute]}function cn(e,t){if(t.trim()==="")return!1;let{exact:n,loose:r}=Tr(t),s=r.map(a=>xe(a,"iu")),o=a=>{let i=a.replace(Ce," ").replace(Ae," "),c=i.replace(/<[^<>]+>/g," ").normalize("NFC");return/[<>]/.test(t)?[c,i.normalize("NFC")]:[c]};return e.some(a=>Et(a).some(i=>i!==void 0&&o(i).some(c=>{let l=t.length<3?c.replace(la," "):c;return n.some(d=>l.includes(d))||s.some(d=>d.test(l))})))}function Zn(e,t,n,r,s,o){let a=s?Date.parse(s):NaN,i=Object.keys(n),c=oa(t,o,i),l=(d,f)=>ia(d,o,f);for(let[d,f]of i.entries())for(let p of i.slice(d+1))if(!(r[f]===void 0||r[p]===void 0||l(n[f],a)==="")&&!(l(n[f],a)!==l(n[p],a)||l(r[f])===l(r[p]))&&(pt(e,`<${f}>`)||pt(e,`<${p}>`)))return!0;for(let d of i.filter(f=>/\{env:/.test(n[f])&&r[f]!==void 0))if([...n[d].matchAll(Ce)].map(([p])=>p).some(p=>!t.includes(p)&&pt(e,p))){for(let p of i)if(!(p===d||/\{env:/.test(n[p])||r[p]===void 0||!t.includes(`<${p}>`)||pt(e,`<${p}>`))&&l(r[p])!==l(r[d]))return!0}return Object.entries(n).some(([d,f])=>{let p=r[d];if(p===void 0)return!1;let u=f.includes("{date")&&!Number.isNaN(a);if(p===f&&(!u||Ve(f,new Date(a))===Ve(p)))return!1;let h=t.includes(`<${d}>`),b=l(f,a),g=l(p);if(b.trim()==="")return g.trim()!==""&&!pt(e,`<${d}>`)&&e.some(x=>_n(x).some($=>$!==void 0));let S=vt(b),y=!h&&c.some(x=>(x.match(/[-\u2212\u2013]?\d[\d.,]*/g)??[]).some($=>En(vt($)??NaN,S??NaN))),w=x=>x.action==="expectAmount"?sa(x.value):x.value!==void 0&&/^expect/.test(x.action)?[vt(x.value)].filter($=>$!==void 0):[];if(S!==void 0&&!y&&e.some(x=>w(x).some($=>En($,S)))){let x=vt(g);if(x===void 0||!En(x,S))return!0}if(b!==g&&e.some(x=>_n(x).some($=>$!==void 0&&/^\{(?:env|data):[^{}]+\}$/.test($)&&t.includes($)&&l($,a)===b))||b!==g&&e.some(x=>[x.target?.role,x.toTarget?.role].includes(b)))return!0;let v=new Set(p===f?[]:oa(f,o,i));if(u){let x=f.replace(/\{date([+-]\d+)?:[^}]*\}/g,"{date$1}");x!==f&&h&&p!==f&&v.add(x);for(let $ of[0,1])for(let E of new Set([f,x])){let R=Ve(E,new Date(a-$*864e5));v.add(R)}}return[...v].some(x=>x.trim()!==""&&(h||!c.some($=>xe(x).test($)))&&wd(e,x,h||u,$=>oa($,o,i)))})}function hd(e,t){let n=Object.keys(t).filter(r=>t[r].trim()==="");return n.length>0&&e.some(r=>_n(r).some(s=>s!==void 0))&&n.some(r=>!pt(e,`<${r}>`))}function md(e,t,n={}){let r=/\{env:|\{date/;if(e.some(a=>Et(a).some(i=>i!==void 0&&(r.test(i)||/\{data:/.test(i))))||Object.values(t).some(a=>a.trim()==="")&&e.some(a=>a.value===""))return!0;let s=Object.values(t).filter(a=>a.trim()!=="");if(new Set(s).size<s.length)return!0;let o=a=>[a.replace(Qn(Object.keys(t))," ").normalize("NFC")];return Object.values(t).some(a=>{if(r.test(a)||[...a.matchAll(Ae)].some(([,c])=>!(c in n)))return!0;let i=a.replace(Ae,(c,l)=>n[l]);return[a,i].some(c=>c.trim()!==""&&wd(e,c,!0,o))})}function wd(e,t,n,r){let{exact:s,loose:o}=Tr(t),a=n&&t.length>=3,i=s.map(f=>ho(t,f,"u",n)),c=o.map(f=>xe(f,"iu")),l=f=>{let p=t.length<3?f.replace(la," "):f;return/^\{(?:env|data|unique|date)[^{}]*\}$/.test(t)&&p.includes(t)||i.some(u=>u.test(p))||(a?o.some(u=>p.toLowerCase().includes(u)):c.some(u=>u.test(p)))},d=f=>n?Et(f):_n(f);return e.some(f=>d(f).some(p=>p!==void 0&&r(p).some(l)))}function ho(e,t=e,n="gu",r=!0){let s=t.normalize("NFC");return r&&e.length>=3?new RegExp(be(s),n):xe(s,n)}function Rr(e,t,n,r=t){let s=e.normalize("NFC");return s.includes(r.normalize("NFC"))?ho(t,r,"u",n).test(t.length<3?s.replace(la," "):s):!1}function ia(e,t,n){return Ve(e,n===void 0||Number.isNaN(n)?new Date:new Date(n)).replace(Ae,(r,s)=>t?.[s]??yd(s)??r).replace(Ce,(r,s)=>process.env[s]??r)}function is(e,t,n,r,s){let o=r?Date.parse(r):NaN;return e.find(a=>{let i=t[a],c=n[a];return i===void 0||c===void 0?!0:i!==c&&ia(i,s,o)!==ia(c,s)})}function Qn(e){return new RegExp(`<(?:table:[^<>]+|docstring${[...e].map(t=>`|${be(t)}`).join("")})>`,"g")}var dd=String.raw`[\p{L}\p{N}\p{M}]`,ud=/[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Thai}\p{Script=Lao}\p{Script=Khmer}\p{Script=Myanmar}]/u,la=/:nth-[a-z-]+\([^)]*\)|\bnth=-?\d+|\bh[1-6]\b/gi;function xe(e,t="u"){let n=[...e],r=n.length>=2&&ud.test(n[0])?"":`(?<!${dd})`,s=n.length>=2&&ud.test(n[n.length-1])?"":`(?!${dd})`;return new RegExp(`${r}${e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}${s}`,t)}function Tr(e){let t=e.normalize("NFC"),n=[...new Set([t,...Object.values(ue).map(a=>a(t))])],r=t.toLowerCase(),s=new Set([r]);try{s.add(encodeURIComponent(t).toLowerCase()),s.add(encodeURIComponent(t).replaceAll("%20","+").toLowerCase())}catch{}let o=r.split(/[^\p{L}\p{N}\p{M}]+/u).filter(Boolean);if(o.length>1)for(let a of["-","_",""])s.add(o.join(a));return{exact:n,loose:[...s]}}function da(e){return e.length>=5||e.length>=3&&/\p{N}/u.test(e)}function oa(e,t,n){let r=(e??"").replace(n?Qn(n):/<[^<>]+>/g," ").normalize("NFC"),s=r.replace(Ae,(o,a)=>t?.[a]??yd(a)??o).replace(Ce,(o,a)=>process.env[a]??o);return s===r?[r]:[r,s]}function yd(e){try{return qe(e)}catch{return}}function bd(e,t){return e===t?"bare":e===`^${t}$`?"anchored":void 0}function vd(e){let t=xd(e);if(t===void 0)return;let n=um(16).toString("hex");return`s1:${n}:${fd(t,n,32).toString("hex")}`}function mo(e,t){let n=xd(e);if(n===void 0)return!1;let r=/^s1:([0-9a-f]{32}):([0-9a-f]{64})$/.exec(t);return r?fd(n,r[1],32).toString("hex")===r[2]:dm("sha256").update(n).digest("hex")===t}function xd(e){if(!/\{(?:env|data):/.test(e))return;let t=!1,n=e.replace(Ae,(s,o)=>{try{return qe(o)}catch{return t=!0,s}});if(!new RegExp(Ce.source).test(n))return;let r=n.replace(Ce,(s,o)=>{let a=process.env[o];return a===void 0&&(t=!0),a??s});return t?void 0:r}var Se=new Set(["expectVisible","expectNotVisible","expectText","expectUrl","expectValue","expectDiffers","expectMatches","expectAttribute","expectResponse","expectEach","expectDownload","expectAmount"]);function as(e){if(e.steps.some(n=>n.actions.some(r=>r.action==="waitForDownload"&&(r.downloads??1)>1)))return 4;if(e.rowsUseNewDates||Kn(JSON.stringify([e.steps,e.examples??{},e.data??{}]))||Object.values(e.data??{}).some(n=>n.includes("{date"))||e.examples&&e.steps.some(n=>hd(n.actions,e.examples))||e.rowBound?.some(n=>n.reason==="container"||n.reason==="session"||n.reason==="unwritten"||n.valueSha?.startsWith("s1:")))return 3;if((e.rowBound?.length??0)>0||Ye(e.steps.map(n=>n.gherkin)).some(n=>n!==void 0)||e.examples&&e.steps.some(n=>md(n.actions,e.examples,e.data)))return 2;let t=n=>n.clickCount!==void 0&&n.clickCount!==1||n.button!==void 0&&n.button!=="left"||(n.modifiers?.length??0)>0||n.clearSelection===!0||n.action==="selectOption"&&(n.value??"").includes(`
|
|
13
|
+
`)||[n.status,n.method,n.attribute].some(r=>r!==void 0&&/<[^<>]+>|\{(?:data|env|date|unique)[^{}]*\}/.test(r));return e.steps.some(n=>n.actions.some(t))?2:1}import{createHash as Td}from"node:crypto";import Ut from"node:fs";import Bt from"node:path";import Sd from"node:path";var wo=4,fm=new Set(["goto","click","fill","press","selectOption","check","uncheck","hover","waitFor","captureText","handleDialog","uploadFile","dragTo","waitForResponse","switchTab","closeTab","newTab","waitForDownload",...Se]),pm=["role","name","nameRegex","label","text","testId","placeholder","frame"],gm=["value","url","saveAs","compareTo","each","pattern","attribute","promptText","urlPattern","method","status","pageFingerprint"],ua=/[\u0000-\u001f\u007f-\u009f]/,$e=class extends Error{constructor(n,r){super(`${n}: ${r}`);this.file=n;this.problem=r}file;problem},gt=e=>e!==null&&typeof e=="object"&&!Array.isArray(e);function K(e,t,n){if(!e)throw new $e(t,n)}function $d(e,t,n){K(gt(e),t,`${n} must be an object`);for(let r of pm)K(e[r]===void 0||typeof e[r]=="string",t,`${n}.${r} must be a string`);e.fallbackSelectors!==void 0&&K(Array.isArray(e.fallbackSelectors)&&e.fallbackSelectors.every(r=>typeof r=="string"),t,`${n}.fallbackSelectors must be a list of selectors`)}var hm=e=>["role","label","text","testId","placeholder"].some(t=>typeof e[t]=="string"&&e[t]!=="")||Array.isArray(e.fallbackSelectors)&&e.fallbackSelectors.some(t=>typeof t=="string"&&t.trim().length>0),mm={goto:["url"],click:["target"],fill:["target","value"],press:["value"],selectOption:["target","valueOrClear"],check:["target"],uncheck:["target"],hover:["target"],waitFor:["targetOrValue"],captureText:["target","saveAs"],handleDialog:[],uploadFile:["value"],dragTo:["target","toTarget"],waitForResponse:["urlPattern"],switchTab:["value"],closeTab:[],newTab:[],waitForDownload:[],expectVisible:["target"],expectNotVisible:["target"],expectText:["target","value"],expectUrl:["urlOrValue"],expectValue:["target","value"],expectDiffers:["compareTo","targetOrValue"],expectMatches:["target","pattern"],expectAttribute:["target","attribute","pattern"],expectResponse:["urlPattern"],expectEach:["target","each"],expectDownload:["valueOrPattern"],expectAmount:["target","value"]};function wm(e,t,n){let r=o=>typeof e[o]=="string",s=o=>gt(e[o])&&hm(e[o]);for(let o of mm[e.action])switch(o){case"target":case"toTarget":K(s(o),t,`${n} (${e.action}) needs a ${o} with a role, name, label, text, test id, placeholder or selector`);break;case"urlOrValue":K(r("url")||r("value"),t,`${n} (${e.action}) needs a url`);break;case"targetOrValue":K(s("target")||r("value"),t,`${n} (${e.action}) needs a target or a value`);break;case"valueOrClear":K(r("value")||e.clearSelection===!0,t,`${n} (${e.action}) needs value`);break;case"valueOrPattern":K(r("value")&&e.value!==""||r("pattern"),t,`${n} (${e.action}) needs a non-empty value or a pattern`);break;default:K(r(o),t,`${n} (${e.action}) needs ${o}`)}for(let o of["target","toTarget"])e[o]!==void 0&&K(s(o),t,`${n}.${o} has no usable locator`);if(e.downloads!==void 0&&K(e.action==="waitForDownload"&&Number.isInteger(e.downloads)&&e.downloads>=2&&e.downloads<=999,t,`${n}.downloads must be a whole number from 2, on a waitForDownload`),e.action==="expectUrl"){let o=e.url??e.value;K(typeof o=="string"&&o.length>0,t,`${n} (expectUrl) needs a non-empty url or value`)}for(let o of["url","saveAs","compareTo","each","pattern","attribute","urlPattern"])e[o]!==void 0&&K(e[o].length>0,t,`${n}.${o} must not be empty`);["press","uploadFile","switchTab","expectText"].includes(e.action)&&K(typeof e.value=="string"&&e.value.length>0,t,`${n} (${e.action}) needs a non-empty value`)}function ym(e,t,n){K(gt(e),t,`${n} must be an object`),K(typeof e.action=="string",t,`${n}.action is missing`),K(fm.has(e.action),t,`${n}.action "${e.action}" is not an action this runner knows. Recorded by a newer saffron-ai? Update, or re-record with --rerecord`);for(let r of gm)K(e[r]===void 0||typeof e[r]=="string",t,`${n}.${r} must be a string`);K(e.opensTab===void 0||typeof e.opensTab=="boolean",t,`${n}.opensTab must be true or false`),K(e.clearSelection===void 0||typeof e.clearSelection=="boolean",t,`${n}.clearSelection must be true or false`),K(e.clickCount===void 0||Number.isInteger(e.clickCount)&&e.clickCount>=1,t,`${n}.clickCount must be a whole number from 1`),K(e.button===void 0||["left","right","middle"].includes(e.button),t,`${n}.button must be "left", "right" or "middle"`),K(e.modifiers===void 0||Array.isArray(e.modifiers)&&e.modifiers.every(r=>["Alt","Control","ControlOrMeta","Meta","Shift"].includes(r)),t,`${n}.modifiers must be a list of Alt, Control, ControlOrMeta, Meta or Shift`),e.target!==void 0&&$d(e.target,t,`${n}.target`),e.toTarget!==void 0&&$d(e.toTarget,t,`${n}.toTarget`),wm(e,t,n)}function bm(e,t,n){K(gt(e),t,`${n} must be an object`),K(typeof e.gherkin=="string"&&e.gherkin.length>0,t,`${n}.gherkin (the step text) is missing`),K(typeof e.keyword=="string",t,`${n}.keyword is missing`),K(e.kind==="action"||e.kind==="assertion",t,`${n}.kind must be "action" or "assertion"`),K(Array.isArray(e.actions),t,`${n}.actions must be a list (empty for a recorded no-op)`),e.actions.forEach((r,s)=>ym(r,t,`${n}.actions[${s}]`)),e.table!==void 0&&K(Array.isArray(e.table)&&e.table.every(r=>Array.isArray(r)&&r.every(s=>typeof s=="string")),t,`${n}.table must be rows of strings`),K(e.docString===void 0||typeof e.docString=="string",t,`${n}.docString must be a string`),K(e.fromStepSet===void 0||typeof e.fromStepSet=="string",t,`${n}.fromStepSet must be a string`)}function fa(e,t){if(K(gt(e),t,"is not a JSON object"),K(e.version!==void 0,t,"has no version: not a Saffron recording"),K(Number.isInteger(e.version)&&e.version>=1&&e.version<=wo,t,typeof e.version=="number"&&e.version>wo?`is schema version ${e.version}; this saffron-ai reads versions 1 to ${wo}. Update saffron-ai to the release that wrote it`:`has schema version ${JSON.stringify(e.version)}; this saffron-ai reads versions 1 to ${wo}`),K(typeof e.feature=="string"&&e.feature.length>0,t,"feature (the feature file path) is missing"),K(!Sd.isAbsolute(e.feature)&&!Sd.win32.isAbsolute(e.feature)&&!e.feature.split(/[\\/]/).includes(".."),t,`names a feature file outside the project: ${JSON.stringify(e.feature)}`),K(typeof e.scenario=="string"&&e.scenario.length>0,t,"scenario (the scenario name) is missing"),K(e.recordedAt===void 0||typeof e.recordedAt=="string",t,"recordedAt must be a string"),K(e.recordedBy===void 0||e.recordedBy==="agent"||e.recordedBy==="manual",t,'recordedBy must be "agent" or "manual"'),K(Array.isArray(e.steps),t,"steps must be a list"),e.steps.forEach((n,r)=>bm(n,t,`steps[${r}]`)),e.data!==void 0&&K(gt(e.data)&&Object.values(e.data).every(n=>typeof n=="string"),t,"data must map references to strings"),e.examples!==void 0&&K(gt(e.examples)&&Object.values(e.examples).every(n=>typeof n=="string"),t,"examples must map columns to strings"),K(e.rowsUseNewDates===void 0||e.rowsUseNewDates===!0,t,"rowsUseNewDates must be true when present"),e.rowBound!==void 0){let n=e.steps.length;K(Array.isArray(e.rowBound)&&e.rowBound.every(r=>gt(r)&&typeof r.column=="string"&&Number.isInteger(r.step)&&r.step>=0&&r.step<n&&(r.reason==="list"||r.reason==="glued"||r.reason==="data"||r.reason==="value"||r.reason==="reads"||r.reason==="container"||r.reason==="session"||r.reason==="unwritten")&&(r.valueSha===void 0||typeof r.valueSha=="string"&&/^(?:[0-9a-f]{64}|s1:[0-9a-f]{32}:[0-9a-f]{64})$/.test(r.valueSha))),t,'rowBound must be a list of { column, step, reason: "list" | "glued" | "data" | "value" | "reads" | "container" | "session" | "unwritten", valueSha? } naming steps of this recording'),K(gt(e.examples),t,"rowBound needs examples, the row it was recorded on")}return e}function kd(e,t){K(gt(e),t,"is not a JSON object"),K(gt(e.meta),t,"meta is missing: not a Saffron proposal");let n=e.meta;K(n.mode==="record"||n.mode==="heal",t,'meta.mode must be "record" or "heal"'),K(typeof n.narrative=="string",t,"meta.narrative must be a string"),K(Array.isArray(n.adaptations)&&n.adaptations.every(r=>typeof r=="string"),t,"meta.adaptations must be a list of strings"),K(n.verified===void 0||typeof n.verified=="boolean",t,"meta.verified must be true or false"),K(gt(n.usage),t,"meta.usage is missing"),n.featureEdits!==void 0&&(K(Array.isArray(n.featureEdits)&&n.featureEdits.every(r=>gt(r)&&typeof r.index=="number"&&typeof r.text=="string"),t,"meta.featureEdits must be a list of { index, text }"),n.featureEdits.forEach((r,s)=>K(r.text.trim().length>0,t,`meta.featureEdits[${s}].text is empty: a feature edit must give the step's new text`)),n.featureEdits.forEach((r,s)=>K(!ua.test(r.text),t,`meta.featureEdits[${s}].text holds a line break or another control character`))),n.bound!==void 0&&K(gt(n.bound)&&["scenario","committed","recording"].every(r=>typeof n.bound[r]=="string"),t,"meta.bound must hold the scenario, committed and recording digests"),fa(e.cache,`${t} (cache)`)}var Ad=".saffron",Ed=e=>Td("sha1").update(e).digest("hex").slice(0,8),ga=e=>e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"");function _d(e){return ga(e)||`unnamed-${Ed(e)}`}var Od=e=>ga(e)||"unnamed";function Cd(e){let t=ga(e);return t&&/[^\x00-\x7f]/.test(e)?`${t}-${Ed(e)}`:_d(e)}function Pd(e,t,n,r){let s;try{s=Ut.readFileSync(e,"utf8")}catch{return!0}try{return t(JSON.parse(s))}catch{return r.some(o=>new RegExp(`"${n}"\\s*:\\s*${be(JSON.stringify(o))}`).test(s))}}function vm(e,t,n){let r=Bt.join(e,`${Cd(t)}.json`),s=Bt.join(e,`${Od(t)}.json`);return s===r||Ut.existsSync(r)||!Ut.existsSync(s)?r:Pd(s,o=>n(o)===t,"scenario",[t])?s:r}var Rd=new Map;function Id(e){let t=Bt.join(e,"saffron.config.json"),n=Ut.statSync(t,{throwIfNoEntry:!1}),r=n?`${n.mtimeMs}:${n.ctimeMs}:${n.size}:${n.ino}`:"none",s=Rd.get(e);if(s?.stamp===r)return s.top;let o="features";try{let c=JSON.parse(Ut.readFileSync(t,"utf8"));typeof c?.features=="string"&&c.features.trim()&&(o=c.features)}catch{}let a=Bt.relative(e,Bt.resolve(e,o)),i=a.startsWith("..")||Bt.isAbsolute(a)?void 0:a.split(/[\\/]/)[0];return Rd.set(e,{stamp:r,top:i}),i}function pa(e,t,n=_d){let r=e.split(/[\\/]/).filter(Boolean),s=r.pop()??"unnamed",o=t===void 0||r[0]===t?r.slice(1):r,a=n([...o,Bt.basename(s,".feature")].join("-"));if(o.length===0)return a;let i=Td("sha1").update(e.replace(/\\/g,"/")).digest("hex").slice(0,6);return`${a}-${i}`}function Nd(e,t,n,r,s){let o=d=>vm(Bt.join(e,Ad,t,d),r,f=>s(f)?.scenario),a=o(pa(n,Id(e))),i=o(pa(n,void 0,Od));if(i===a||Ut.existsSync(a)||!Ut.existsSync(i))return a;let c=d=>typeof d=="string"?d.replace(/\\/g,"/"):d;return Pd(i,d=>c(s(d)?.feature)===c(n),"feature",[n,c(n)])?i:a}function me(e,t,n){return Nd(e,"cache",t,n,r=>r)}function jd(e,t){let n=new Map;for(let r of t){let s=me(e,r.featurePath,r.name),o=n.get(s)??new Set;o.add(`${r.featurePath} \u203A ${r.name}${r.line?` (line ${r.line})`:""}`),n.set(s,o)}return[...n.entries()].filter(([,r])=>r.size>1).map(([r,s])=>`${[...s].join(" and ")} both map to ${Bt.relative(e,r)}. Rename one scenario or one file.`)}var Xn="owner.json";function ln(e,t,n){return Bt.join(e,Ad,"artifacts",pa(t,Id(e)),Cd(n))}function xt(e,t,n){return Nd(e,"proposals",t,n,r=>r?.cache)}function Jt(e,t){try{return st(e)}catch(n){if(!(n instanceof $e))throw n;t?.(e,n.problem);return}}function st(e){if(!Ut.existsSync(e))return;let t;try{t=JSON.parse(Ut.readFileSync(e,"utf8"))}catch(n){throw new $e(e,`is not valid JSON: ${n instanceof Error?n.message:String(n)}`)}return fa(t,e)}function Ar(e,t){Ut.mkdirSync(Bt.dirname(e),{recursive:!0}),Ut.writeFileSync(e,`${JSON.stringify({...t,version:as(t)},null,2)}
|
|
14
|
+
`)}function yo(e){let t=[];return{pattern:e.replace(/"((?:[^"\\]|\\.)*)"/g,(r,s)=>(t.push(s),`"\xAB${t.length-1}\xBB"`)),args:t}}function ha(e,t){let n=r=>JSON.stringify(r.map(({pageFingerprint:s,...o})=>o));return n(e)===n(t)}function xm(e){let t=new Set,n=r=>{if(r)for(let s of r.matchAll(/<([^<>]+)>/g))t.add(s[1])};for(let r of e.actions)Et(r).forEach(n);return n(e.gherkin),t}var Ld=/<[^<>]+>/,dn=(e,t)=>`${pe(e)}
|
|
15
|
+
${t}`;function Wt(e){let t=Dd.join(e,".saffron","cache"),n=new Map,r=new Map,s=new Map,o=new Map,a=new Set,i=0;if(Md.existsSync(t))for(let d of Md.readdirSync(t,{recursive:!0})){let f=String(d);if(!f.endsWith(".json"))continue;let p=Jt(Dd.join(t,f));if(!p)continue;i++;let u=Ye(p.steps.map(b=>b.gherkin)),h=Tn(p.steps);for(let[b,g]of p.steps.entries()){let S=g.gherkin,y=JSON.stringify(g.actions.map(({pageFingerprint:m,...A})=>A)),w=dn(u[b],S),v=o.get(w)??new Set;v.add(y),o.set(w,v),v.size>1&&a.add(S);let x=n.get(S),$=Math.max(v.size,x?.variants??0),E={gherkin:g.gherkin,kind:g.kind,...p.examples||p.steps.some(m=>/<[^<>\s]+>/.test(m.gherkin))?{outline:!0}:{},table:g.table,docString:g.docString,actions:g.actions,sourceParams:h,sourceData:p.data,...p.examples?{examples:p.examples}:{},...p.rowBound?.some(m=>m.step===b)?{rowBound:p.rowBound.filter(m=>m.step===b).map(m=>m.column)}:{},...p.rowBound?.some(m=>m.step===b&&m.valueSha)?{rowBoundValues:Object.fromEntries(p.rowBound.filter(m=>m.step===b&&m.valueSha).map(m=>[m.column,m.valueSha]))}:{},feature:p.feature,scenario:p.scenario,recordedAt:p.recordedAt??"",variants:$,...u[b]?{session:u[b]}:{}};!x||E.recordedAt>x.recordedAt?n.set(S,E):x.variants=$;let R=n.get(S),k=fe(S),C=s.get(k);if((!C||C.recordedAt<=R.recordedAt)&&s.set(k,R),u[b]?.match(Ld))continue;let P=r.get(w);!P||P.recordedAt<=E.recordedAt?r.set(w,{...E,variants:v.size}):P.variants=v.size}}let c=[...a],l=new Map;for(let d of r.values()){let{pattern:f,args:p}=yo(d.gherkin);if(p.length===0)continue;let u=dn(d.session,f),h=l.get(u);(!h||d.recordedAt>h.recordedAt)&&l.set(u,{...d,args:p})}return{steps:n,seeds:r,bare:s,patterns:l,divergent:c,scannedCaches:i}}function Fd(e,t,n){if(t.kind!==void 0&&e.kind!==void 0&&t.kind!==e.kind||!!e.table!=!!t.table)return!1;if(e.table&&t.table){let o=Object.keys(rt(e.table)),a=Object.keys(rt(t.table));if(o.length>0&&a.length>0){if(JSON.stringify(o)!==JSON.stringify(a))return!1}else if(JSON.stringify(e.table)!==JSON.stringify(t.table))return!1}if(e.docString!==void 0!=(t.docString!==void 0)||e.docString!==void 0&&t.docString!==void 0&&e.docString!==t.docString&&(!e.actions.some(o=>[o.value,o.url,o.pattern].some(a=>a?.includes("<docstring>")))||cn(e.actions,e.docString)))return!1;if(e.table&&t.table){let o=rt(e.table),a=rt(t.table);for(let i of Object.keys(o))if(o[i]!==a[i]&&(!pt(e.actions,`<${i}>`)||cn(e.actions,o[i])))return!1}for(let[o,a]of Object.entries(e.sourceParams??{}))if(o in n&&n[o]!==a&&cn(e.actions,a))return!1;if((e.kind!=="assertion"||kr(e.actions))&&$r(e.gherkin,e.actions,e.examples??{}).some(o=>o in n&&(!e.examples||e.examples[o]!==n[o])))return!1;if(e.sourceData&&e.outline&&Object.keys(n).length>0){let o=e.examples?Object.entries(e.examples).filter(([d,f])=>n[d]!==void 0&&n[d]!==f).map(([,d])=>d):void 0,a=d=>o===void 0||o.some(f=>f!==""&&d.includes(f)),i=[t.text,...t.table?.flat()??[],t.docString??""].join(`
|
|
16
|
+
`).replace(/\{[^{}]*\}|<[^<>]+>/g," "),c=d=>{try{return new RegExp(d).test("")}catch{return!1}},l=e.actions.some(d=>Se.has(d.action)&&(d.value===""||d.pattern!==void 0&&c(d.pattern)));for(let[d,f]of Object.entries(e.sourceData))if(a(d)&&(f.trim()===""?l:!xe(f).test(i)&&On(e.actions,f)))return!1}if(e.rowBound&&(!e.examples||is(e.rowBound,e.examples,n,e.recordedAt,e.sourceData)!==void 0)||e.rowBoundValues&&Object.entries(e.rowBoundValues).some(([o,a])=>!mo(n[o]??"",a)))return!1;if(e.examples){let o=[t.text,...t.table?.flat()??[],t.docString??""].join(`
|
|
17
|
+
`);if(Zn(e.actions,o,e.examples,n,e.recordedAt,e.sourceData)||os(o,e.examples,n,e.actions))return!1}for(let[o,a]of Object.entries(e.sourceData??{})){let i;try{i=qe(o)}catch{continue}if(i!==a&&(On(e.actions,a)||e.gherkin.includes(`{data:${o}}`)&&!pt(e.actions,`{data:${o}}`)))return!1}let r={...n,...rt(t.resolvedTable??t.table),...Jn(t.resolvedDocString??t.docString)},s=xm({gherkin:e.gherkin,keyword:"",kind:"action",actions:e.actions});for(let o of s)if(!(o in r))return!1;return!0}function Bd(e,t,n){let r=t.text,[s]=Ye([r],t.session),o=s?.match(Ld)?t.session:s,a=e.seeds.get(dn(o,r));if(a)return Fd(a,t,n)?a:void 0;let{pattern:i,args:c}=yo(r);if(c.length===0)return;let l=e.patterns.get(dn(o,i));if(!l)return;let d=new Map;for(let y=0;y<c.length;y++){let w=l.args[y],v=c[y],x=d.get(w);if(x!==void 0&&x!==v)return;d.set(w,v)}let f=new Map([...d].filter(([y,w])=>y!==w)),p=l.actions.flatMap(y=>[y.saveAs,y.compareTo,y.action==="expectDiffers"?y.value:void 0,...y.action==="expectAmount"?[...(y.value??"").matchAll(/"([^"]*)"/g)].map(w=>w[1]):[]]);if([...f.keys()].some(y=>p.includes(y)))return;let u=y=>[y?.name,y?.nameRegex,y?.label,y?.text,y?.placeholder];for(let y of f.keys())if(!l.actions.some(v=>[v.value,v.url,v.pattern,v.urlPattern,v.promptText,v.status,v.method,v.attribute,...u(v.target),...u(v.toTarget)].includes(y)))return;let h=y=>{let w=v=>v?{...v,name:y(v.name),nameRegex:y(v.nameRegex),label:y(v.label),text:y(v.text),placeholder:y(v.placeholder)}:void 0;return l.actions.map(({pageFingerprint:v,...x})=>({...x,value:y(x.value),url:y(x.url),pattern:y(x.pattern),urlPattern:y(x.urlPattern),promptText:y(x.promptText),status:y(x.status),method:y(x.method),attribute:y(x.attribute),target:w(x.target),toTarget:w(x.toTarget)}))},b=h(y=>y!==void 0&&f.has(y)?"":y),g=y=>{if(l.sourceData?.[y]!==void 0)return l.sourceData[y];try{return qe(y)}catch{return}};for(let y of f.keys()){if(cn(b,y))return;let w=y.replace(Ae,(v,x)=>g(x)??v);if(w!==y&&cn(b,w))return}for(let y of f.keys())for(let[w]of y.matchAll(/<[^<>]+>|\{(?:data|env):[^{}]+\}/g))if(pt(b,w))return;if(l.examples){let y={...l.examples};for(let[w,v]of f){let x=w.match(/^<([^<>]+)>$/)?.[1];if(x!==void 0&&x in y)y[x]=v;else if(/<[^<>]+>/.test(w))return}if(Zn(l.actions,l.gherkin,l.examples,y,l.recordedAt,l.sourceData))return}let S={...l,gherkin:t.text,actions:h(y=>y!==void 0&&f.has(y)?f.get(y):y)};return Fd(S,t,n)?S:void 0}function Ud(e,t){let n=[];return e.forEach((r,s)=>{if(r.actions.length!==0&&!(t.steps.has(r.gherkin)||t.bare.has(fe(r.gherkin)))){for(let o of t.steps.values())if(!(o.variants>1)&&o.actions.length!==0&&Lt(o.gherkin)===Lt(r.gherkin)&&ha(r.actions,o.actions)){n.push({index:s,from:r.gherkin,to:o.gherkin,feature:o.feature,scenario:o.scenario});break}}}),n}function ma(e){return an(e,on)}function Gt(e,t,n,r){let s=bo.isAbsolute(t)?t:bo.join(e,t),o=ma(s),a=n??sn(o.filter(b=>b.endsWith(".saffron")),e),i=new Map,c=new Map;for(let b of o)for(let g of r?.get(b)??ft(b,e,a)){let S=`${g.featurePath}::${g.name}`;for(let y of g.steps){let w=fe(y.text),v=i.get(w);if(v||(v={text:w,prefixed:new Set,keywords:new Map,kind:y.kind,scenarios:new Set,files:new Set,fromStepSet:y.source?.fromStepSet},i.set(w,v)),y.text!==w&&v.prefixed.add(y.text),v.keywords.set(y.keyword,(v.keywords.get(y.keyword)??0)+1),v.scenarios.add(S),y.source&&v.files.add(y.source.file),y.source?.fromStepSet){let x=c.get(y.source.fromStepSet);x||c.set(y.source.fromStepSet,x=new Set),x.add(S)}}}let l=Wt(e),d=new Map;for(let[b,g]of l.seeds){let S=fe(g.gherkin),y=d.get(S)??{};y[b]=g.variants>1?"divergent":"recorded",d.set(S,y)}for(let[b,g]of Sm(e)){let S=fe(b.slice(b.indexOf(`
|
|
18
|
+
`)+1));d.set(S,{...d.get(S),[b]:g})}let f=b=>d.get(fe(b))?.[dn(Ye([b])[0],b)]??"unrecorded",p=b=>{let g=Object.values(d.get(b)??{});return g.includes("divergent")?"divergent":g.length?"recorded":"unrecorded"},u=[...i.values()].map(b=>({text:b.text,keyword:[...b.keywords.entries()].sort((g,S)=>S[1]-g[1])[0][0],kind:b.kind,status:p(b.text),recordings:d.get(b.text)??{},...b.prefixed.size?{sessions:Object.fromEntries([...b.prefixed].sort().map(g=>[g,f(g)]))}:{},usage:b.scenarios.size,files:[...b.files].sort(),fromStepSet:b.fromStepSet})).sort((b,g)=>g.usage-b.usage||b.text.localeCompare(g.text)),h=[...a.values()].map(b=>({name:b.name,file:b.file,line:b.line,steps:b.steps.map(g=>g.text),usage:c.get(b.name)?.size??0})).sort((b,g)=>g.usage-b.usage||b.name.localeCompare(g.name));return{steps:u,stepSets:h,scannedFiles:o.length,scannedCaches:l.scannedCaches}}function Sm(e){let t=bo.join(e,".saffron","cache"),n=new Map;if(!zd.existsSync(t))return new Map;for(let r of zd.readdirSync(t,{recursive:!0})){if(!String(r).endsWith(".json"))continue;let s=Jt(bo.join(t,String(r)));if(!s)continue;let o=Ye(s.steps.map(a=>a.gherkin));s.steps.forEach((a,i)=>{if(!o[i]?.match(/<[^<>]+>/))return;let c=dn(o[i],a.gherkin),l=n.get(c)??new Set;l.add(JSON.stringify(a.actions.map(({pageFingerprint:d,...f})=>f))),n.set(c,l)})}return new Map([...n].map(([r,s])=>[r,s.size>1?"divergent":"recorded"]))}function vo(e,t){let n=t.toLowerCase();return{...e,steps:e.steps.filter(r=>r.text.toLowerCase().includes(n)),stepSets:e.stepSets.filter(r=>r.name.toLowerCase().includes(n)||r.steps.some(s=>s.toLowerCase().includes(n)))}}function Hd(e){let t={},n="saffron,feature,gherkin,cucumber";for(let r of e.steps)t[`step: ${r.text}`]={scope:n,prefix:r.text,body:[r.text.replace(/\$/g,"\\$")],description:`${r.status} \xB7 used in ${r.usage} scenario(s)`};for(let r of e.stepSets)t[`StepSet: ${r.name}`]={scope:n,prefix:`StepSet ${r.name}`,body:[`StepSet ${r.name}`],description:`step set (${r.steps.length} steps) in ${r.file}`};return JSON.stringify(t,null,2)+`
|
|
19
|
+
`}import{Server as Hy}from"@modelcontextprotocol/sdk/server/index.js";import{StdioServerTransport as qy}from"@modelcontextprotocol/sdk/server/stdio.js";import{CallToolRequestSchema as Vy,ListToolsRequestSchema as Jy}from"@modelcontextprotocol/sdk/types.js";import Qt from"node:fs";import yt from"node:path";import qd from"node:fs";import $m from"node:path";function Ee(e){Ul(e);let t=$m.join(e,"saffron.config.json"),n=qd.existsSync(t)?JSON.parse(qd.readFileSync(t,"utf8")):{};return typeof n.features=="string"&&!n.features.trim()&&(n.features=Er.features),Mt(e,n.dataDir,process.env.SAFFRON_ENV??n.env),td(n.dateLocale,n.timezone),n}var Er={provider:"claude",features:"features",dataDir:"data",actionTimeoutMs:5e3,pollIntervalMs:100,retries:1,screenshot:"viewport",maxTurns:100,strict:!1,verifyProposals:!0,snapshotMode:"none",reuseSteps:!0,browser:"chromium",workers:1,agentWorkers:1,assertionPolicy:"strict",hookTimeoutMs:3e5,trace:"off"};function Vd(e){return{...Er,...Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0))}}import xo from"node:fs";import _r from"node:path";import{fileURLToPath as Jd}from"node:url";function Wd(e,t){for(let n=0;n<6;n++){let r=_r.join(e,"package.json");if(xo.existsSync(r))try{if(JSON.parse(xo.readFileSync(r,"utf8")).name===t)return e}catch{}e=_r.dirname(e)}}function So(){return Wd(_r.dirname(Jd(import.meta.url)),"saffron-ai")}function Gd(e){try{let t=Wd(_r.dirname(Jd(import.meta.resolve(e))),e),n=t&&JSON.parse(xo.readFileSync(_r.join(t,"package.json"),"utf8")).version;return typeof n=="string"?n:void 0}catch{return}}function ot(){let e=So();if(!e)return"unknown";try{return JSON.parse(xo.readFileSync(_r.join(e,"package.json"),"utf8")).version??"unknown"}catch{return"unknown"}}import ht from"node:fs";import Ge from"node:path";import We from"node:fs";import{createHash as Tm}from"node:crypto";import Kd from"node:os";import Or from"node:path";import un from"node:fs";import Cn from"node:path";import{createHash as km,randomBytes as Rm}from"node:crypto";function _t(e,t){try{if(!un.statSync(t).isFile())return!1;let n=Cn.relative(un.realpathSync(e),un.realpathSync(t));return n!==""&&n!==".."&&!n.startsWith(".."+Cn.sep)&&!Cn.isAbsolute(n)}catch{return!1}}var Be=(e,t)=>Cn.relative(e,t).split(Cn.sep).join("/");function zt(e){return km("sha256").update(e).digest("hex")}function Je(e,t,n){un.mkdirSync(Cn.dirname(e),{recursive:!0});let r=`${e}.${process.pid}-${Rm(4).toString("hex")}.partial`;try{un.writeFileSync(r,t),n!==void 0&&un.chmodSync(r,n),un.renameSync(r,e)}catch(s){throw un.rmSync(r,{force:!0}),s}}function Pn(e,t){let n=Cn.join(e,t.file);if(_t(Cn.join(e,".saffron","artifacts"),n))try{let r=un.readFileSync(n);return t.sha256&&zt(r)!==t.sha256?void 0:r}catch{return}}function Yd(e,t){We.mkdirSync(Or.dirname(e),{recursive:!0});let n=Buffer.from(`${JSON.stringify(t,null,2)}
|
|
20
|
+
`);return Cr(e,()=>Je(e,n)),ba(n)}var Am=6e4,Em=5e3,_m=60*6e4,Om=new Int32Array(new SharedArrayBuffer(4)),er=class extends Error{};function Cr(e,t,n=1e4){let r=`${e}.lock`,s=Date.now()+n,o;for(;;){o=JSON.stringify({pid:process.pid,host:Kd.hostname(),at:new Date().toISOString()});try{We.writeFileSync(r,o,{flag:"wx"});break}catch(a){let i=a.code,c=i==="EPERM"&&process.platform==="win32";if(i!=="EEXIST"&&!c)throw a;if(Date.now()>=s)throw c?a:new er(`${e} is being decided by another process. Try again.`);Cm(r)||Atomics.wait(Om,0,0,25)}}try{return t()}finally{wa(r)===o&&We.rmSync(r,{force:!0})}}function wa(e){try{return We.readFileSync(e,"utf8")}catch{return}}function Cm(e){let t=wa(e);if(t===void 0)return!1;let n={};try{n=JSON.parse(t)||{}}catch{}let r=Date.parse(n.at??""),s=Am;if(Number.isNaN(r)){try{r=We.statSync(e).mtimeMs}catch{return!1}s=Em}let o=n.host===Kd.hostname()&&typeof n.pid=="number";return o&&Pm(n.pid)&&Date.now()-r<_m||!o&&Date.now()-r<s||wa(e)!==t?!1:(We.rmSync(e,{force:!0}),!0)}function Pm(e){try{return process.kill(e,0),!0}catch(t){return t.code!=="ESRCH"}}function $o(e,t,n){return We.existsSync(e)?Cr(e,()=>We.existsSync(e)?t():n()):n()}function ya(e){let t=/^(.+)#([0-9a-f]{64})$/i.exec(e);return t?{file:t[1],revision:t[2].toLowerCase()}:{file:e}}function Ot(e){return ba(We.readFileSync(e))}var ba=e=>Tm("sha256").update(e.includes(13)?Buffer.from(e.toString("utf8").replace(/\r\n/g,`
|
|
21
|
+
`)):e).digest("hex"),Zd=e=>Or.join(e,".saffron","reports","filed.json");function Qd(e){let t;try{t=JSON.parse(We.readFileSync(Zd(e),"utf8"))}catch{return{}}return!t||typeof t!="object"||Array.isArray(t)?{}:Object.fromEntries(Object.entries(t).filter(([,n])=>typeof n=="string"))}function Xd(e,t,n){return Qd(e)[Be(e,t)]===n}function eu(e,t,n){let r=Qd(e);r[Be(e,t)]=n;for(let[s,o]of Object.entries(r)){try{if(Ot(Or.join(e,s))===o)continue}catch{}delete r[s]}Je(Zd(e),`${JSON.stringify(r,null,2)}
|
|
22
|
+
`)}function Pr(e){return ko(e).proposal}function ko(e){return va(We.readFileSync(e),e)}function va(e,t){let n;try{n=JSON.parse(e.toString("utf8"))}catch(r){throw new $e(t,`is not valid JSON: ${r instanceof Error?r.message:String(r)}`)}return kd(n,t),{proposal:n,revision:ba(e),bytes:e}}function Kt(e,t){let n=Or.join(e,".saffron","proposals");if(!We.existsSync(n))return[];let r=[];for(let s of We.readdirSync(n)){let o=Or.join(n,s);if(We.statSync(o).isDirectory())for(let a of We.readdirSync(o)){if(!a.endsWith(".json"))continue;let i=Or.join(o,a);try{r.push({file:i,...ko(i)})}catch(c){if(!t||!(c instanceof $e))throw c;t(i,c.problem)}}}return r}function Ro(e,t){let n=Pr(t),r=me(e,n.cache.feature,n.cache.scenario);return Ar(r,n.cache),We.rmSync(t),r}function To(e){We.rmSync(e)}var xa=(e,t)=>Ge.relative(e,t).split(Ge.sep).join("/");function tu(e){return ht.existsSync(e)?[...ht.readdirSync(e,{recursive:!0})].map(String).filter(t=>t.endsWith(".json")).map(t=>Ge.join(e,t)).sort():[]}function nu(e){try{let t=JSON.parse(ht.readFileSync(e,"utf8")),n="cache"in t&&t.cache?t.cache:t;return{feature:n.feature,scenario:n.scenario}}catch{return{}}}function ru(e){try{let t=JSON.parse(ht.readFileSync(Ge.join(e,Xn),"utf8"));return{feature:typeof t.feature=="string"?t.feature:void 0,scenario:typeof t.scenario=="string"?t.scenario:void 0}}catch{return{}}}function Eo(e,t,n){let r=Ge.isAbsolute(t)?t:Ge.join(e,t),s=new Set(an(r,on));for(let l of["cache","proposals"])for(let d of tu(Ge.join(e,".saffron",l))){let{feature:f}=nu(d);if(typeof f=="string"){let p=Ge.resolve(e,f);ht.existsSync(p)&&s.add(p)}}for(let l of Ao(Ge.join(e,".saffron","artifacts")))for(let d of Ao(l)){let f=ru(d).feature;if(f){let p=Ge.resolve(e,f);ht.existsSync(p)&&s.add(p)}}let o=[...n?.unreadable??[]],a=[...s].filter(l=>!n?.parsedFiles.has(l)),i=new Map;if(a.length>0)try{i=sn([...new Set([...Gn(r),...s].filter(l=>l.endsWith(".saffron")))],e)}catch(l){o.push(l instanceof Error?l.message:String(l))}let c=new Set(n?.owned??[]);for(let l of a){let d;try{d=ft(l,e,i)}catch(f){o.push(`${xa(e,l)}: ${f instanceof Error?f.message:String(f)}`);continue}for(let f of d)c.add(me(e,f.featurePath,f.name)),c.add(xt(e,f.featurePath,f.name)),c.add(ln(e,f.featurePath,f.displayName))}return{...Im(e,c),unreadable:o}}function Im(e,t){let n=[],r=0;for(let o of["cache","proposal"]){let a=Ge.join(e,".saffron",o==="cache"?"cache":"proposals");for(let i of tu(a)){if(t.has(i)){r++;continue}let{feature:c,scenario:l}=nu(i),d=c?Ge.join(e,c):void 0;n.push({file:xa(e,i),kind:o,feature:c,scenario:l,reason:c?ht.existsSync(d)?"scenario-gone":"feature-gone":"unknown"})}}let s=Ge.join(e,".saffron","artifacts");for(let o of Ao(s))for(let a of Ao(o)){let{feature:i,scenario:c}=ru(a),l=i&&c?ln(e,i,c):void 0;if(t.has(a)||l&&t.has(l)&&l!==a&&!ht.existsSync(l)){r++;continue}n.push({file:xa(e,a),kind:"artifact",feature:i,scenario:c,reason:i?ht.existsSync(Ge.join(e,i))?"scenario-gone":"feature-gone":"unknown"})}return{orphans:n,kept:r}}function Ao(e){try{return ht.readdirSync(e,{withFileTypes:!0}).filter(t=>t.isDirectory()).map(t=>Ge.join(e,t.name)).sort()}catch{return[]}}function su(e,t){let n=[],r=new Set;for(let s of t){let o=Ge.join(e,s.file);try{s.kind==="proposal"?Cr(o,()=>ht.rmSync(o)):ht.rmSync(o,{recursive:s.kind==="artifact"}),n.push(s.file),r.add(Ge.dirname(o))}catch{}}for(let s of r)try{ht.readdirSync(s).length===0&&ht.rmdirSync(s)}catch{}return n}function ou(e){if(e.kind==="artifact")return`${e.file}/
|
|
21
23
|
failure screenshots of a scenario that no longer exists`;let t=e.feature&&e.scenario?`${e.feature} \u203A ${e.scenario}`:"an unreadable recording",n=e.reason==="feature-gone"?"the feature file is gone":e.reason==="scenario-gone"?"the scenario is gone from that file":"it names no scenario";return`${e.file}
|
|
22
|
-
${e.kind==="proposal"?"pending proposal for ":""}${t}: ${n}`}import
|
|
24
|
+
${e.kind==="proposal"?"pending proposal for ":""}${t}: ${n}`}import Ma from"node:fs";import ws from"node:path";import{createHash as Nm,randomBytes as jm}from"node:crypto";var iu=/\{unique:([A-Za-z0-9_-]+)(?::(digits))?\}/g,Ct="__saffron_unique_seed",fn=()=>`${Date.now().toString(36)}${jm(4).toString("hex")}`;function au(e,t,n=!1){let r=Nm("sha1").update(`${e}:${t}`).digest();if(n){let o=r.readUInt32BE(0)*65536+r.readUInt16BE(4);return String(1e8+o%9e8)}let s=BigInt(`0x${r.subarray(0,8).toString("hex")}`).toString(36).padStart(9,"0").slice(-9);return`${"abcdefghijklmnopqrstuvwxyz"[r[8]%26]}${s}`}function Yt(e,t){return e.replace(iu,(n,r,s)=>au(t,r,s==="digits"))}function Ir(e,t){let n=new Map;for(let r of e)if(r)for(let s of r.matchAll(iu))n.set(s[0],au(t,s[1],s[2]==="digits"));return n}function cu(e,t){let n=e;for(let[r,s]of t)n=n.split(s).join(r);return n}import{createHash as Mm}from"node:crypto";async function _o(e){let t;try{t=await e.locator("body").ariaSnapshot({timeout:3e3})}catch{return"sha256:unavailable"}let n=t.replace(/\d+/g,"#").replace(/\s+/g," ").trim();return`sha256:${Mm("sha256").update(n).digest("hex")}`}var Dm=/^[a-z][a-z\d+.-]*:|^\/\//i,lu=e=>e.pathname.replace(/\/+$/,"");function cs(e,t){if(!t)return e;let n,r;try{n=new URL(e),r=new URL(t)}catch{return e}if(n.origin!==r.origin)return e;let s=lu(r),o=n.pathname,a;if(o===r.pathname||o===s||o===`${s}/`)a="/";else if(o.startsWith(`${s}/`))a=o.slice(s.length);else return e;let i=n.search===r.search?"":n.search||"?",c=a!=="/"?n.hash:n.hash===r.hash?"":n.hash||(r.hash?"#":"");return`${a}${i}${c}`}function Sa(e,t){if(Dm.test(e))return e;if(!t)throw new Error(`relative navigation "${e}" needs a base URL (set baseURL or pass --base-url)`);let n=new URL(t),r=e.indexOf("#"),s=r>=0?e.slice(r):void 0,o=r>=0?e.slice(0,r):e,a=o.indexOf("?"),i=a>=0?o.slice(a):void 0,c=a>=0?o.slice(0,a):o,l=c===""||c==="/",d=new URL(n.href);return d.pathname=l?n.pathname:`${lu(n)}${c.startsWith("/")?c:`/${c}`}`,d.search=i===void 0?n.search:i==="?"?"":i,d.hash=s==="#"?"":s!==void 0?s:l?n.hash:"",d.toString()}import $a from"node:fs";import Fm from"node:os";import mt from"node:path";import{Client as Lm}from"@modelcontextprotocol/sdk/client/index.js";import{AjvJsonSchemaValidator as Bm}from"@modelcontextprotocol/sdk/validation/ajv";import{StdioClientTransport as Um}from"@modelcontextprotocol/sdk/client/stdio.js";import{McpServer as zm}from"@modelcontextprotocol/sdk/server/mcp.js";import{CallToolRequestSchema as Hm,ListToolsRequestSchema as qm}from"@modelcontextprotocol/sdk/types.js";var ka=6e4;function du(){return $a.mkdtempSync(mt.join(Fm.tmpdir(),"saffron-mcp-"))}var Ra=1e8,uu=new Set(["browser_navigate","browser_click","browser_type","browser_press_sequentially","browser_fill_form","browser_select_option","browser_check","browser_uncheck","browser_press_key","browser_hover","browser_drag","browser_file_upload","browser_handle_dialog","browser_tabs","browser_snapshot","browser_find","browser_wait_for","browser_take_screenshot","browser_console_messages","browser_network_requests","browser_network_request","browser_evaluate"]);function Vm(e){return{...e,tools:e.tools.filter(t=>uu.has(t.name))}}function Jm(e){return uu.has(e)?void 0:{isError:!0,content:[{type:"text",text:`${e} is not available in a Saffron session.`}]}}var Oo=e=>({isError:!0,content:[{type:"text",text:e}]}),Wm=new Set(["http:","https:"]);function ls(e){if(typeof e!="string"||/^localhost(:\d+)?(\/|$)/i.test(e))return;let t=`${e} is not a web page; a Saffron session only opens http(s) URLs.`,n;try{n=new URL(e)}catch{return/^[a-z][a-z\d+.-]*:/i.test(e.replace(/^[\u0000- ]+/,"").replace(/[\t\n\r]/g,""))?t:void 0}return Wm.has(n.protocol)||n.href==="about:blank"?void 0:t}function Ta(e,t){if(!Array.isArray(e))return;let n=a=>{try{return $a.realpathSync(a)}catch{return}},r=n(t)??mt.resolve(t),s=a=>{let i=mt.relative(r,a);return i.startsWith("..")||mt.isAbsolute(i)?void 0:i},o=a=>a.split(mt.sep).some(i=>i.startsWith(".")&&i!=="..");for(let a of e){if(typeof a!="string")continue;let i=mt.resolve(a),c=n(i),l=n(mt.dirname(i)),d=s(c??(l?mt.join(l,mt.basename(i)):i));if(d===void 0&&!c&&!l){let f=mt.relative(mt.resolve(t),i);!f.startsWith("..")&&!mt.isAbsolute(f)&&(d=f)}if(d===void 0)return`${a} is outside the project; uploads come from files inside it.`;if(o(d)||o(mt.relative(mt.resolve(t),i)))return`${a} is a hidden file; a Saffron session does not upload dotfiles.`;if(!c)return`${a} does not exist; uploads come from files inside the project.`;if($a.statSync(c).isDirectory())return`${a} is a folder; a Saffron session uploads single files only.`}}function Gm(e,t,n=process.cwd()){if(!t)return{args:t};let r=e==="browser_navigate"||e==="browser_tabs"?ls(t.url):e==="browser_file_upload"?Ta(t.paths,n):void 0;if(r)return{args:t,refused:Oo(r)};if(e==="browser_tabs"&&t.isolatedContext!==void 0)return{args:t,refused:Oo(`isolatedContext is not available in a Saffron session: open the tab in the scenario's own context. Another person's browser is an As "name" step.`)};if("filename"in t){let{filename:s,...o}=t;return{args:o}}return{args:t}}var Km=/^### (?:Ran Playwright code|Open tabs|Events)\r?$/;function Ym(e,t=ka){if(!Array.isArray(e.content)||e.content.reduce((o,a)=>o+(a.type==="text"&&typeof a.text=="string"?a.text.length:0),0)<=t)return e;let r=t,s=e.content.map(o=>{if(o.type!=="text"||typeof o.text!="string")return o;let a=o.text;if(a.length<=r)return r-=a.length,o;let i=[...a.matchAll(/^### .*$/gm)],c=i.map((p,u)=>({start:p.index,stop:i[u+1]?.index??a.length,recorded:Km.test(p[0])})),l=r;for(let p of c)p.recorded&&p.start<l&&p.stop>l&&(l=p.start);l>0&&/[\uD800-\uDBFF]/.test(a[l-1])&&(l-=1),r-=l;let d=c.filter(p=>p.recorded&&p.start>=l).map(p=>a.slice(p.start,p.stop).trimEnd()),f=`
|
|
23
25
|
|
|
24
|
-
[Saffron cut this result at ${
|
|
25
|
-
|
|
26
|
-
`)
|
|
27
|
-
`)?$h(i,t):void 0,g=d??u;if(g!==void 0)return g===i?void 0:Buffer.from(o+g,"utf8")}let c=e.toString("latin1"),l=n.mask(c);return l===c?void 0:Buffer.from(l,"latin1")}function Xl(e,t){try{JSON.parse(e)}catch(n){if(n instanceof SyntaxError)return;throw n}return!t.occursIn(e)&&!t.hiddenByEscape.test(e)?e:Oi(e,t,{keys:!0,numbers:!0})}function $h(e,t){let n=e.split(`
|
|
28
|
-
`),
|
|
29
|
-
`)}
|
|
30
|
-
|
|
31
|
-
`)
|
|
32
|
-
`)}var
|
|
33
|
-
|
|
34
|
-
${
|
|
35
|
-
`,!(!t||!M)&&(v++,_=M,I&&T.includes(`
|
|
36
|
-
`)&&(
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
`)
|
|
41
|
-
`))
|
|
42
|
-
`)
|
|
43
|
-
`)
|
|
44
|
-
`)
|
|
45
|
-
`)
|
|
46
|
-
`)[0],browser:o.browser}));return{runId:t.toISOString(),startedAt:t.toISOString(),finishedAt:new Date().toISOString(),baseURL:r,green:s.filter(o=>o.status==="green").length,yellow:s.filter(o=>o.status==="yellow").length,red:s.filter(o=>o.status==="red").length,aiCalls:s.reduce((o,i)=>o+i.aiCalls,0),costUsd:s.reduce((o,i)=>o+i.costUsd,0),divergentSteps:n,scenarios:s}}function Ki(e,t){let n=Wi(e);Fn.mkdirSync(vd.dirname(n),{recursive:!0}),Fn.appendFileSync(n,`${JSON.stringify(t)}
|
|
47
|
-
`)
|
|
48
|
-
`)
|
|
26
|
+
[Saffron cut this result at ${l} of ${a.length} characters: whole, it would not fit the agent's context. Ask for less: a snapshot of one region, a filtered request list, or a saffron_assert on the field you need instead of the whole body.]`;return{...o,text:a.slice(0,l)+f+d.map(p=>`
|
|
27
|
+
|
|
28
|
+
${p}`).join("")}});return{...e,content:s}}function Zm(e){if(!e.isError||!Array.isArray(e.content))return e;let t=!1,n=e.content.map(o=>{if(o.type!=="text"||typeof o.text!="string")return o;let a=o.text.split(/^### Events\r?$/m)[1]?.split(/^### /m)[0]??"",i=/^### Error\r?\n([\s\S]*?)(?=^### |(?![\s\S]))/m.exec(o.text);return!i||!/^- Downloading file .* \.\.\.\r?$/m.test(a)||i[1].split(`
|
|
29
|
+
`).filter(l=>l.trim()!==""&&!/^(?:Error: )?download\.saveAs: /.test(l)&&!/^\s+at /.test(l)).length>0?o:(t=!0,{...o,text:o.text.slice(0,i.index)+o.text.slice(i.index+i[0].length)})});if(!t)return e;let{isError:r,...s}=e;return{...s,content:n}}async function fu(e,t,n={}){let r=new Lm({name:"saffron-cap",version:"1"}),s=Object.fromEntries(Object.entries(process.env).filter(a=>a[1]!==void 0));await r.connect(new Um({...e,env:s,stderr:"ignore"}));let o=Aa(r,void 0,t,n);return{config:{type:"sdk",name:"playwright",instance:o},close:async()=>{await Promise.allSettled([r.close(),o.close()])}}}function Aa(e,t=(s,o,a)=>a(),n,r={}){let s=new zm({name:"playwright",version:"1"},{capabilities:{tools:{}}});return s.server.setRequestHandler(qm,async()=>Vm(await e.listTools())),s.server.setRequestHandler(Hm,async(o,a)=>{let i=Jm(o.params.name);if(i)return i;let c=Gm(o.params.name,o.params.arguments,n);if(c.refused)return c.refused;let l={...o.params,arguments:c.args};return Ym(await t(l.name,l.arguments,async()=>{let d=async w=>Zm(await e.callTool(w,void 0,{timeout:Ra,signal:a.signal})),f=l.arguments?.fields,p=l.name==="browser_fill_form"&&Array.isArray(f)&&f.length>1,u=(l.name==="browser_type"||l.name==="browser_press_sequentially")&&l.arguments?.submit===!0;if(!p&&!u)return d(l);let h=(await e.listTools()).tools.find(w=>w.name===l.name);if(!h)return Oo(`${l.name} is not available in this browser session.`);let b=new Bm().getValidator(h.inputSchema)(l.arguments);if(!b.valid)return Oo(`Invalid ${l.name} arguments: ${b.errorMessage}`);let g=p?f.map(w=>({...l,arguments:{...l.arguments,fields:[w]}})):[{...l,arguments:{...l.arguments,submit:!1}},l.name==="browser_type"?{...l,arguments:{...l.arguments,text:"",slowly:!0,submit:!0}}:{name:"browser_press_key",arguments:{key:"Enter"}}],S=[],y=!1;try{for(let w of g){a.signal.throwIfAborted(),r.beforeAction?.();let v=await d(w);if(v.isError)return v;S.push(v)}return y=!0,{...S.at(-1),content:S.flatMap(w=>Array.isArray(w.content)?w.content:[])}}finally{if(!y)for(let w of S)r.onPartialResult?.(w)}}))}),s}import us from"node:fs";import rw from"node:os";import Ea from"node:path";import wt from"node:fs";import Qm from"node:path";import{createHash as Xm,randomBytes as ew}from"node:crypto";import Po from"node:zlib";var In=4294967295,gu=67324752,hu=33639248,mu=101010256;function wu(e){return ds(e).map(t=>({name:t.name,data:t.read()}))}function yu(e,t){let n=Math.max(0,t-22-65535),r=e(n,t-n),s=-1;for(let l=r.length-22;l>=0;l--)if(r.readUInt32LE(l)===mu){s=l;break}if(s<0)throw new Error("not a zip file: no central directory");let o=r.readUInt16LE(s+10),a=e(r.readUInt32LE(s+16),r.readUInt32LE(s+12)),i=0,c=[];for(let l=0;l<o;l++){if(a.readUInt32LE(i)!==hu)throw new Error("not a zip file: bad central directory entry");let d=a.readUInt16LE(i+10),f=a.readUInt32LE(i+16),p=a.readUInt32LE(i+20),u=a.readUInt32LE(i+24),h=a.readUInt16LE(i+28),b=a.readUInt16LE(i+30),g=a.readUInt16LE(i+32),S=a.readUInt32LE(i+42),y=a.subarray(i+46,i+46+h).toString("utf8");i+=46+h+b+g;let w=e(S,30);if(w.length<30||w.readUInt32LE(0)!==gu)throw new Error(`not a zip file: bad local header for ${y}`);let v=S+30+w.readUInt16LE(26)+w.readUInt16LE(28);if(!y.endsWith("/")){if(d!==0&&d!==8)throw new Error(`zip entry ${y} uses compression method ${d}, which is not supported`);c.push({name:y,method:d,crc:f,size:u,compressedSize:p,start:v})}}return c}function ds(e){return yu((t,n)=>e.subarray(t,t+n),e.length).map(({name:t,method:n,crc:r,size:s,compressedSize:o,start:a})=>{let i=e.subarray(a,a+o);return{name:t,method:n,crc:r,size:s,raw:i,read:()=>n===0?Buffer.from(i):Po.inflateRawSync(i)}})}function tw(e,t,n){let r=wt.openSync(e,"r");try{let s=Buffer.alloc(n),o=0;for(;o<n;){let a=wt.readSync(r,s,o,n-o,t+o);if(a===0)break;o+=a}return s.subarray(0,o)}finally{wt.closeSync(r)}}function bu(e){let t=wt.statSync(e).size,n=(r,s)=>tw(e,r,Math.max(0,Math.min(s,t-r)));return yu(n,t).map(r=>({...r,raw:()=>n(r.start,r.compressedSize)}))}var nw=(()=>{let e=new Uint32Array(256);for(let t=0;t<256;t++){let n=t;for(let r=0;r<8;r++)n=n&1?3988292384^n>>>1:n>>>1;e[t]=n>>>0}return e})();function Co(e,t=0){let n=Po.crc32;if(n)return n(e,t)>>>0;let r=(t^4294967295)>>>0;for(let s of e)r=nw[(r^s)&255]^r>>>8;return(r^4294967295)>>>0}var pu=1024*1024;function vu(e,t){let n=wt.openSync(e,"r");try{let r=Buffer.alloc(pu);for(let s;(s=wt.readSync(n,r,0,pu,null))>0;)t(r.subarray(0,s))}finally{wt.closeSync(n)}}function Io(e){let t=Xm("sha256"),n=0,r=0;return vu(e,s=>{n=Co(s,n),r+=s.length,t.update(s)}),{crc:n,size:r,sha256:t.digest("hex")}}function xu(e,t,n,r,s,o){let a=Buffer.alloc(30);a.writeUInt32LE(gu,0),a.writeUInt16LE(20,4),a.writeUInt16LE(2048,6),a.writeUInt16LE(t,8),a.writeUInt32LE(0,10),a.writeUInt32LE(n,14),a.writeUInt32LE(r,18),a.writeUInt32LE(s,22),a.writeUInt16LE(e.length,26),a.writeUInt16LE(0,28);let i=Buffer.alloc(46);return i.writeUInt32LE(hu,0),i.writeUInt16LE(20,4),i.writeUInt16LE(20,6),i.writeUInt16LE(2048,8),i.writeUInt16LE(t,10),i.writeUInt32LE(0,12),i.writeUInt32LE(n,16),i.writeUInt32LE(r,20),i.writeUInt32LE(s,24),i.writeUInt16LE(e.length,28),i.writeUInt16LE(0,30),i.writeUInt16LE(0,32),i.writeUInt16LE(0,34),i.writeUInt16LE(0,36),i.writeUInt32LE(0,38),i.writeUInt32LE(o,42),{local:a,central:i}}function Su(e,t,n){let r=Buffer.alloc(22);return r.writeUInt32LE(mu,0),r.writeUInt16LE(0,4),r.writeUInt16LE(0,6),r.writeUInt16LE(e,8),r.writeUInt16LE(e,10),r.writeUInt32LE(t,12),r.writeUInt32LE(n,16),r.writeUInt16LE(0,20),r}var $u=e=>new Error(`cannot write a zip of ${e} files: one holds at most 65,535`),ku=e=>new Error(`cannot write ${e} into a zip: a zip holds at most 4 GB, and this one would be larger`),Ru=()=>new Error("cannot write the zip: a zip holds at most 4 GB, and this one would be larger");function Tu(e){if(e.length>65535)throw $u(e.length);let t=[],n=[],r=0;for(let o of e){let a="raw"in o,i=a?o.raw:Po.deflateRawSync(o.data),c=a?o.size:o.data.length,l=Buffer.from(o.name,"utf8");if(c>In||r+30+l.length+i.length>In)throw ku(o.name);let{local:d,central:f}=xu(l,a?o.method:8,a?o.crc:Co(o.data),i.length,c,r);t.push(d,l,i),n.push(f,l),r+=d.length+l.length+i.length}let s=n.reduce((o,a)=>o+a.length,0);if(r+s>In)throw Ru();return Buffer.concat([...t,...n,Su(e.length,s,r)])}function Nr(e,t){for(let n=0;n<t.length;)n+=wt.writeSync(e,t,n,t.length-n)}function Au(e,t){if(t.length>65535)throw $u(t.length);wt.mkdirSync(Qm.dirname(e),{recursive:!0});let n=`${e}.${process.pid}-${ew(4).toString("hex")}.partial`,r=wt.openSync(n,"w");try{let s=[],o=0;for(let i of t){let c=Buffer.from(i.name,"utf8"),l="file"in i,d=l&&(i.crc===void 0||i.size===void 0)?Io(i.file):void 0,f=l?void 0:Po.deflateRawSync(i.data),p=l?d?.crc??i.crc:Co(i.data),u=l?d?.size??i.size:i.data.length,h=f?.length??u;if(u>In||o+30+c.length+h>In)throw ku(i.name);let{local:b,central:g}=xu(c,l?0:8,p,h,u,o);if(Nr(r,b),Nr(r,c),f)Nr(r,f);else{let S=0,y=0;if(vu(i.file,w=>{S+w.length>u||(Nr(r,w),S+=w.length,y=Co(w,y))}),S!==u||y!==p)throw new Error(`${i.name} changed while it was being packed`)}s.push(g,c),o+=b.length+c.length+h}let a=s.reduce((i,c)=>i+c.length,0);if(o+a>In)throw Ru();for(let i of s)Nr(r,i);Nr(r,Su(t.length,a,o)),wt.closeSync(r),wt.renameSync(n,e)}catch(s){try{wt.closeSync(r)}catch{}throw wt.rmSync(n,{force:!0}),s}}var _a=["off","on","retain-on-failure"],Oa="trace.zip";async function _u(e,t){await e.tracing.start({screenshots:!0,snapshots:!0,sources:!1,title:t})}async function No(e,t){t&&us.mkdirSync(Ea.dirname(t),{recursive:!0}),await e.tracing.stop(t?{path:t}:void 0)}async function jo(e,t,n){let r;try{r=us.mkdtempSync(Ea.join(rw.tmpdir(),"saffron-trace-"));let s=Ea.join(r,Oa);await e.tracing.stop({path:s});let o=hw(us.readFileSync(s),n);return Je(t,o),zt(o)}catch{try{us.rmSync(t,{force:!0})}catch{console.warn("Could not remove the execution trace artifact.")}console.warn("Could not save the execution trace; no trace was attached to this run.");return}finally{if(r)try{us.rmSync(r,{recursive:!0,force:!0})}catch{console.warn("Could not remove the private temporary trace directory.")}}}async function Ou(e,t,n,r){if(!t)return r();let s=e.context().tracing;await s.group(n).catch(()=>{});try{return await r()}finally{await s.groupEnd().catch(()=>{})}}var sw=new Set(["callId","parentId","pageId","frameId","contextId","pageref","_frameref","snapshotName","beforeSnapshot","afterSnapshot","inputSnapshot","sha1","_sha1"]),ow=new Set(["before","action","after"]),iw=/^\[saffron:(?:agent|replay|pending|action):-?\d+\] /,aw=new Set(["type","class","method"]),cw=new Set(["__playwright_bounding_rect__","__playwright_scroll_top_","__playwright_scroll_left_","__playwright_target__","__playwright_checked_","__playwright_selected_","__playwright_popover_open_","__playwright_dialog_open_","__playwright_shadow_root_","__playwright_custom_elements__"]),lw=new Set(["style","__playwright_style_sheet_"]),dw=new Set(["srcset","imagesrcset"]),uw=/^(?:image\/(?!svg)|font\/|audio\/|video\/)/i,fw=/\.(?:jpe?g|png|gif|webp|avif|bmp|ico|woff2?|ttf|otf|eot|mp3|mp4|m4a|wav|ogg|webm)$/i,pw=/^text\/css\b/i,gw=/\.css$/i;function hw(e,t){let n=Rn(t,{encodings:!0});if(n.empty)return e;let r=Rn(t,{encodings:!0,bytes:!0}),s=ds(e),o=new Set(s.filter(u=>u.name.includes("/")).map(u=>u.name));for(let u of s)u.name.startsWith("resources/")&&o.add(u.name.slice(10));let a={names:o,pieces:Tw(t)},i=new Set,c=new Set,l=u=>{for(let h of[u.snapshot?.response?.content,u.snapshot?.request?.postData]){if(!h)continue;let b=h._file??(h._sha1&&`resources/${h._sha1}`);if(!b)continue;let g=String(h.mimeType??"");uw.test(g)?i.add(b):pw.test(g)&&c.add(b)}},d=[...s],f=!1,p=(u,h)=>{h&&(d[u]={name:s[u].name,data:h},f=!0)};return s.forEach((u,h)=>{/\.(?:trace|network)$/.test(u.name)?p(h,mw(u.read(),n,a,u.name.endsWith(".network")?l:void 0)):u.name.endsWith(".stacks")&&p(h,ww(u.read(),n,a))}),s.forEach((u,h)=>{/\.(?:trace|network|stacks)$/.test(u.name)||i.has(u.name)||fw.test(u.name)||p(h,yw(u.read(),n,r,c.has(u.name)||gw.test(u.name)))}),f?Tu(d):e}function mw(e,t,n,r){let s=e.toString("utf8").split(`
|
|
30
|
+
`),o=!1;for(let a=0;a<s.length;a++){let i=s[a];if(!i.trim())continue;let c=JSON.parse(i);if(r?.(c),!t.occursIn(i)&&!t.hiddenByEscape.test(i))continue;let l=Pa(i,t,{keys:!1,numbers:!1,playwright:n});l!==i&&(s[a]=l,o=!0)}return o?Buffer.from(s.join(`
|
|
31
|
+
`),"utf8"):void 0}function ww(e,t,n){let r=e.toString("utf8");if(JSON.parse(r),!t.occursIn(r)&&!t.hiddenByEscape.test(r))return;let s=Pa(r,t,{keys:!1,numbers:!1,playwright:n});return s===r?void 0:Buffer.from(s,"utf8")}function yw(e,t,n,r=!1){if(r){let d=e.toString("latin1"),f=Nu(d,n);return f===d?void 0:Buffer.from(f,"latin1")}let s=e.toString("utf8"),o=s.startsWith("\uFEFF")?"\uFEFF":"",a=s.slice(o.length);if(!s.includes("\uFFFD")||Buffer.from(s,"utf8").equals(e)){let d=/^\s*[[{"]/.test(a)?Cu(a,t):void 0,f=d===void 0&&/^\s*(?:[[{"\d-]|true|false|null)/.test(a)&&a.trim().includes(`
|
|
32
|
+
`)?bw(a,t):void 0,p=d??f;if(p!==void 0)return p===a?void 0:Buffer.from(o+p,"utf8")}let c=e.toString("latin1"),l=n.mask(c);return l===c?void 0:Buffer.from(l,"latin1")}function Cu(e,t){try{JSON.parse(e)}catch(n){if(n instanceof SyntaxError)return;throw n}return!t.occursIn(e)&&!t.hiddenByEscape.test(e)?e:Pa(e,t,{keys:!0,numbers:!0})}function bw(e,t){let n=e.split(`
|
|
33
|
+
`),r=[];for(let s of n){if(!s.trim()){r.push(s);continue}let a=Cu(s,t);if(a===void 0)return;r.push(a)}return r.join(`
|
|
34
|
+
`)}var Pu=/^([a-z][a-z0-9+.-]*:\/\/)([^/?#]*@)?([^/?#]*)/i;function Iu(e,t=0,n=e.length){let r=Pu.exec(e.slice(t,n));if(!r)return;let[s,o,a=""]=r,i=t+o.length+a.length;return c=>c>=t&&c<t+o.length||c>=i-(a?1:0)&&c<=t+s.length&&c<n}function vw(e,t,n){let r="",s=0;for(let o of t.matches(e)){let{token:a,kept:i=()=>!1}=n(o),c="";for(let l=o.start;l<o.end;){if(i(l)){c+=e[l++];continue}for(;l<o.end&&!i(l);)l++;c+=a(o.names)}c!==e.slice(o.start,o.end)&&(r+=e.slice(s,o.start)+c,s=o.end)}return s===0?e:r+e.slice(s)}var xw=e=>e.map(t=>`%7Benv:${t}%7D`).join(""),Sw=e=>e.map(t=>`\\{env\\:${t}\\}`).join("");function Ca(e,t,n,r){let s=n.map(([a,i])=>({start:a,end:i,kept:Iu(e,a,i)})),o=0;return vw(e,t,a=>{for(;o<s.length&&s[o].end<a.end;)o++;let i=s[o];return i&&i.start<=a.start&&a.end<=i.end?{token:xw,kept:i.kept}:{token:r}})}function $w(e,t){return Iu(e)?Ca(e,t,[[0,e.length]],ts):t.mask(e)}var kw=/url\(\s*(?:"([^"]*)"|'([^']*)'|([^)\s'"]*))|@import\s+(?:"([^"]*)"|'([^']*)')/dgi;function Nu(e,t){if(!t.occursIn(e))return e;let n=[...e.matchAll(kw)].map(r=>r.indices.slice(1).find(s=>s!==void 0));return Ca(e,t,n,Sw)}function Rw(e,t){let n=[];for(let r=0;r<e.length;){for(;r<e.length&&/[\s,]/.test(e[r]);)r++;let s=r;for(;s<e.length&&!/\s/.test(e[s]);)s++;let o=s;for(;o>r&&e[o-1]===",";)o--;if(o>r&&n.push([r,o]),r=s,o===s)for(;r<e.length&&e[r]!==",";)r++}return Ca(e,t,n,ts)}function Tw(e){let t=new Map;for(let[n,r]of e)if(!(r.length<kn||!Pu.test(r)||!URL.canParse(r)))for(let s of new URL(r).searchParams.values())s.length>=kn&&!t.has(s)&&t.set(s,n);return t}var Eu=e=>e===" "||e===" "||e===`
|
|
35
|
+
`||e==="\r";function Pa(e,t,n){let r=[],s=0,o,a=[],i=c=>{let l=c-1;for(;l>=0&&Eu(e[l]);)l--;return e[l]};for(let c=0;c<e.length;c++){let l=e[c];if(l==="{"||l==="["){let d=a.at(-1),f=i(c)===":"?o:void 0;a.push({dom:(d?.dom??!1)||f==="html",logged:(d?.logged??!1)||f==="value"});continue}if(l==="}"||l==="]"){a.pop();continue}if(l==='"'){let d=c++,f=!1;for(;c<e.length&&e[c]!=='"';c++)e[c]==="\\"&&(f=!0,c++);let p=c+1,u=p;for(;u<e.length&&Eu(e[u]);)u++;let h=e[u]===":",b=f?JSON.parse(e.slice(d,p)):e.slice(d+1,c),g=a.at(-1),S=!h&&i(d)===":"?o:void 0,y=x=>t.mask(x);if(h){if(o=b,!n.keys)continue}else if(n.playwright){if(a.length===1&&S!==void 0&&aw.has(S)||n.playwright.names.has(b))continue;let{pieces:x}=n.playwright;if(y=$=>x.has($)?ts([x.get($)]):$w($,t),g?.dom){if(i(d)==="["){g.tag=b.toUpperCase();continue}let $=S===void 0?g.tag:a.at(-2)?.tag;if(S!==void 0&&cw.has(S)||S==="src"&&($==="IFRAME"||$==="FRAME"))continue;S===void 0&&$==="STYLE"||S!==void 0&&lw.has(S)?y=E=>Nu(E,t):S!==void 0&&dw.has(S)&&(y=E=>Rw(E,t))}else if(S!==void 0&&sw.has(S)||S==="phase"&&ow.has(b))continue}let w=n.playwright&&a.length===1&&S==="title"?iw.exec(b)?.[0]??"":"",v=w+y(b.slice(w.length));v!==b&&(r.push(e.slice(s,d),JSON.stringify(v)),s=p)}else if(l==="-"||l>="0"&&l<="9"){let d=c+1;for(;d<e.length&&/[0-9eE.+-]/.test(e[d]);)d++;(n.numbers||(a.at(-1)?.logged??!1)||i(c)===":"&&o==="value")&&t.isValue(e.slice(c,d))&&(r.push(e.slice(s,c),JSON.stringify(t.mask(e.slice(c,d)))),s=d),c=d-1}}return r.length?r.join("")+e.slice(s):e}function ce(e,t=200){let n=e.replace(/\x1b\[[0-?]*[ -/]*[@-~]|\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)?|\x1b[@-_]?/g,"").replace(/[\x00-\x1f\x7f-\x9f]/g,"");return n.length>t?`${n.slice(0,t-3)}...`:n}function ps(e){return Array.isArray(e)?e.map(ps):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).filter(([t,n])=>n!==void 0&&t!=="pageFingerprint").sort(([t],[n])=>t.localeCompare(n)).map(([t,n])=>[t,ps(n)])):e}var Ia=e=>JSON.stringify(ps(e));function Na(e,t="",n={}){if(Array.isArray(e))n[t]=e.map(r=>String(r)).join(", ");else if(e&&typeof e=="object")for(let[r,s]of Object.entries(e))Na(s,t?`${t}.${r}`:r,n);else t&&(n[t]=String(e));return n}function Aw(e,t){let n=Na(ps(e)),r=Na(ps(t)),s=[...new Set([...Object.keys(n),...Object.keys(r)])].sort(),o=[];for(let a of s){if(a==="action"||n[a]===r[a])continue;let i=a.replace(/^target\./,"").replace(/^toTarget\./,"destination ");n[a]===void 0?o.push(`${i}: added "${r[a]}"`):r[a]===void 0?o.push(`${i}: removed "${n[a]}"`):o.push(`${i}: "${n[a]}" \u2192 "${r[a]}"`)}return o}function Fu(e,t,n){let r=e.map(n),s=t.map(n),o=Array.from({length:r.length+1},()=>new Array(s.length+1).fill(0));for(let l=r.length-1;l>=0;l--)for(let d=s.length-1;d>=0;d--)o[l][d]=r[l]===s[d]?o[l+1][d+1]+1:Math.max(o[l+1][d],o[l][d+1]);let a=[],i=0,c=0;for(;i<r.length&&c<s.length;)r[i]===s[c]?(a.push({before:e[i],after:t[c]}),i++,c++):o[i+1][c]>=o[i][c+1]?(a.push({before:e[i]}),i++):(a.push({after:t[c]}),c++);for(;i<r.length;i++)a.push({before:e[i]});for(;c<s.length;c++)a.push({after:t[c]});return a}function ju(e){if(!e)return"";let t=[];if(e.role){let n=e.name?` "${e.name}"`:e.nameRegex?` matching /${e.nameRegex}/`:"";t.push(`${e.role}${n}`)}else e.label?t.push(`label "${e.label}"`):e.text?t.push(`text "${e.text}"`):e.placeholder?t.push(`placeholder "${e.placeholder}"`):e.testId&&t.push(`test id ${e.testId}`);return e.fallbackSelectors?.length&&t.push(`[${e.fallbackSelectors.join(", ")}]`),e.frame&&t.push(`inside frame ${e.frame}`),t.join(" ")}var Mu=e=>`${e.method??"any"} /${e.urlPattern}/ ${e.status??"2xx"}`+(e.pattern?` with a body matching /${e.pattern}/`:"");function it(e){let t=ju(e.target),n=e.value??"",r=(()=>{switch(e.action){case"goto":return`go to ${e.url}`;case"click":{let s=[e.clickCount===2?"double ":e.clickCount&&e.clickCount>2?`${e.clickCount}x `:"",e.button&&e.button!=="left"?`${e.button}-`:""].join("");return`${e.modifiers?.length?`${e.modifiers.join("+")}+`:""}${s}click ${t}`}case"fill":return`fill ${t} with "${n}"`;case"press":return t?`press ${n} on ${t}`:`press ${n}`;case"selectOption":return e.clearSelection?`clear the selection in ${t}`:`select ${n.split(`
|
|
36
|
+
`).map(s=>`"${s}"`).join(", ")} in ${t}`;case"check":return`check ${t}`;case"uncheck":return`uncheck ${t}`;case"hover":return`hover ${t}`;case"waitFor":return t?`wait for ${t}`:`wait ${n}ms`;case"captureText":return`remember ${t} as "${e.saveAs}"`;case"handleDialog":return`${n} the dialog${e.promptText?` with "${e.promptText}"`:""}`;case"uploadFile":return`upload ${n}`;case"dragTo":return`drag ${t} onto ${ju(e.toTarget)}`;case"waitForResponse":return`wait for ${Mu(e)}`;case"switchTab":return`switch to tab ${n}`;case"closeTab":return`close tab ${n||"(the current one)"}`;case"newTab":return`open a new tab${e.url?` at ${e.url}`:""}`;case"waitForDownload":return e.downloads&&e.downloads>1?`expect the next action to download ${e.downloads} files (the latest is checked)`:"expect the next action to download a file";case"expectAmount":return`expect ${t} to show the amount ${n}`;case"expectVisible":return`expect ${t} to be visible`;case"expectNotVisible":return`expect ${t} to be gone`;case"expectText":return`expect ${t} to contain "${n}"`;case"expectUrl":return`expect the URL to contain "${e.url??n}"`;case"expectValue":return`expect ${t} to hold "${n}"`;case"expectDiffers":return`expect ${t||`"${n}"`} to differ from "${e.compareTo}"`;case"expectMatches":return`expect ${t} to match /${e.pattern}/`;case"expectAttribute":return`expect ${t} ${e.attribute} to match /${e.pattern}/`;case"expectResponse":return`expect a response ${Mu(e)}`;case"expectEach":return`expect ${t} to show every value of ${e.each}`;case"expectDownload":return`expect the downloaded file to ${[e.value?`contain "${n}"`:"",e.pattern?`match /${e.pattern}/`:""].filter(Boolean).join(" and ")}`;default:return e.action}})();return e.opensTab?`${r}, opening a tab`:r}var fs=e=>Se.has(e.action);function Ew(e,t){let n=Fu(e,t,Ia),r=[];for(let s=0;s<n.length;s++){let o=n[s];if(o.before&&o.after){r.push({change:"same",before:it(o.before),after:it(o.after),assertion:fs(o.after)});continue}let a=n[s+1];if(o.before&&a?.after&&!a.before){r.push({change:"changed",before:it(o.before),after:it(a.after),details:Aw(o.before,a.after),assertion:fs(o.before)||fs(a.after)}),s++;continue}o.before&&r.push({change:"removed",before:it(o.before),assertion:fs(o.before)}),o.after&&r.push({change:"added",after:it(o.after),assertion:fs(o.after)})}return r}var _w=e=>`${e.kind}\0${e.gherkin}`;function Nn(e,t,n=[]){let r=Fu(e?.steps??[],t.steps,_w),s=[],o={added:0,removed:0,changed:0,assertions:0};for(let i of r){let c=i.after??i.before,l=Ew(i.before?.actions??[],i.after?.actions??[]);for(let f of l)f.change==="added"?o.added++:f.change==="removed"?o.removed++:f.change==="changed"&&o.changed++,f.change!=="same"&&f.assertion&&o.assertions++;let d=e&&i.before?i.after?l.some(f=>f.change!=="same")?"changed":"same":"removed":"added";s.push({gherkin:c.gherkin,kind:c.kind,fromStepSet:c.fromStepSet,change:d,actions:l})}let a=Ow(e,t);return{feature:t.feature,scenario:t.scenario,hasCommitted:e!==void 0,steps:s,summary:o,...a.length>0?{recording:a}:{},...n.length>0?{featureEdits:n.map(i=>{let c=t.steps[i.index]?.gherkin??`step ${i.index+1}`;return{index:i.index,from:c,to:i.text,fromStepSet:t.steps[i.index]?.fromStepSet,...Lt(c)!==Lt(i.text)?{skipped:'it changes which browser session the step runs in (its As "...")'}:{}}})}:{}}}function Ow(e,t){let n=[],r=a=>`<${a.column}> at step ${a.step+1} (${a.reason})`,s=new Set((e?.rowBound??[]).map(r)),o=new Set((t.rowBound??[]).map(r));for(let a of s)o.has(a)||n.push(`row binding dropped: ${a}. Other Examples rows are no longer refused there; check they cannot pass on this row's data.`);for(let a of o)s.has(a)||n.push(`row binding${e?" added":""}: ${a}. Rows typing that column differently are refused.`);e&&JSON.stringify(e.examples??null)!==JSON.stringify(t.examples??null)&&n.push(`recorded on another Examples row: ${JSON.stringify(e.examples??{})} \u2192 ${JSON.stringify(t.examples??{})}`);for(let a of new Set([...Object.keys(e?.data??{}),...Object.keys(t.data??{})])){let i=e?.data?.[a],c=t.data?.[a];e&&i!==c&&n.push(`{data:${a}} recorded as ${c===void 0?"nothing":JSON.stringify(c)}, was ${i===void 0?"nothing":JSON.stringify(i)}`)}return!!e?.rowsUseNewDates!=!!t.rowsUseNewDates&&e&&n.push(t.rowsUseNewDates?"marked as using new date syntax in another row (written as version 3)":"no longer marked as using new date syntax in another row: it may be written as an older version"),n}var Du=new Set(["goto","click","press","newTab","switchTab","closeTab"]);function Lu(e,t){let n=[],r=s=>`${s} navigation action${s===1?"":"s"}`;for(let s=0;s<Math.min(e.length,t.length);s++){let o=e[s].actions.filter(f=>Du.has(f.action)),i=[...t[s].actions.filter(f=>Du.has(f.action))],c=[];for(let f of o){let p=i.findIndex(u=>Ia(u)===Ia(f));p>=0?i.splice(p,1):c.push(f)}let l=i;for(let f=c.length-1;f>=0;f--){let p=l.findIndex(u=>u.action===c[f].action);p>=0&&(l.splice(p,1),c.splice(f,1))}let d=`step ${s+1} ("${e[s].gherkin}")`;c.length>0&&n.push(`flow change: ${d} no longer performs ${r(c.length)} from the committed recording: ${c.map(it).join("; ")}. A page or navigation step may have been removed or merged.`),l.length>0&&n.push(`flow change: ${d} now performs ${r(l.length)} the committed recording did not: ${l.map(it).join("; ")}. A page or navigation step may have been added or reordered.`)}return n}function Mo(e){let t=[];t.push(`${e.feature} \u203A ${e.scenario}`),t.push(e.hasCommitted?"Comparing the committed recording with the proposed one.":"First recording for this scenario: there is nothing to compare against."),t.push("");for(let a of e.steps){let i=a.change==="removed"?"- ":a.change==="added"&&e.hasCommitted?"+ ":" ";t.push(`${i}${a.kind==="assertion"?"[assertion] ":""}${a.gherkin}`+(a.fromStepSet?` (from step set "${a.fromStepSet}")`:""));for(let c of a.actions)if(c.change==="same")t.push(` ${c.before}`);else if(c.change==="added")t.push(` + ${c.after}`);else if(c.change==="removed")t.push(` - ${c.before}`);else{t.push(` - ${c.before}`),t.push(` + ${c.after}`);for(let l of c.details??[])t.push(` ${l}`)}t.push("")}if(e.featureEdits?.length){t.push("Feature file edits, applied only by saffron accept --with-feature-edit:");for(let a of e.featureEdits){let i=a.fromStepSet?` (step set "${a.fromStepSet}": every scenario that uses it)`:"";t.push(` - ${a.from}${i}`,` + ${a.to}`),a.skipped&&t.push(` (accept skips this edit: ${a.skipped})`)}t.push("")}if(e.recording?.length){t.push("Beside the steps:");for(let a of e.recording)t.push(` ! ${a}`);t.push("")}let{added:n,removed:r,changed:s,assertions:o}=e.summary;return t.push(n+r+s===0?e.recording?.length?"No action changed, but the recording did (above): read that first.":"No action changed.":`${s} changed, ${n} added, ${r} removed.`+(o>0?` ${o} of them ${o===1?"is an assertion":"are assertions"}: read those first.`:"")),t.map(a=>ce(a,1/0)).join(`
|
|
37
|
+
`)}var Ua=e=>new Promise(t=>setTimeout(t,e)),Da=class{entries=[];lastMatch;seq=0;prevStepSeq=0;curStepSeq=0;requestSeq=0;actionSeq=0;requests=new WeakMap;onRequest=t=>{let n=t.redirectedFrom();this.requests.set(t,n?this.requests.get(n)??0:++this.requestSeq);let r=t.resourceType?.();(r==="fetch"||r==="xhr")&&this.inFlight.add(t)};inFlight=new Set;onDone=t=>{this.inFlight.delete(t)};async quiet(t){let n=Date.now()+t;for(await new Promise(r=>setTimeout(r,Math.min(150,t)));this.inFlight.size>0&&Date.now()<n;)await new Promise(r=>setTimeout(r,25))}listener;context;attach(t,n){this.context=t,this.listener=r=>{let s={seq:++this.seq,requestSeq:this.requests.get(r.request())??0,url:r.url(),method:r.request().method(),status:r.status()};if(this.entries.push(s),n){let o=r.headers()["content-type"]??"";/json|text|xml/i.test(o)&&r.text().then(a=>{s.body=a}).catch(()=>{})}},t.on("request",this.onRequest),t.on("response",this.listener),t.on("requestfinished",this.onDone),t.on("requestfailed",this.onDone)}detach(){this.context&&this.listener&&(this.context.off("response",this.listener),this.context.off("request",this.onRequest),this.context.off("requestfinished",this.onDone),this.context.off("requestfailed",this.onDone))}markStep(){this.prevStepSeq=this.curStepSeq,this.curStepSeq=this.seq}sincePreviousStep(){return this.entries.filter(t=>t.seq>this.prevStepSeq)}markAction(){this.actionSeq=this.requestSeq}sinceAction(){return this.entries.filter(t=>t.requestSeq>this.actionSeq)}all(){return this.entries}};function Cw(e,t){if(!t)return e>=200&&e<300;let n=/^([1-5])xx$/i.exec(t.trim());if(n){let r=Number(n[1])*100;return e>=r&&e<r+100}return e===Number(t.trim())}function Bu(e,t,n,r,s){return!(!t.test(e.url)&&!t.test(La(e.url))||n&&e.method.toUpperCase()!==n.toUpperCase()||!Cw(e.status,r)||s&&(e.body===void 0||!s.test(e.body)))}var Pw=(e,t)=>`response matching ${e.method??"any-method"} /${t}/ status ${e.status??"2xx"}${e.pattern?` body /${e.pattern}/`:""}`,Do=new Set(["click","fill","press","selectOption","check","uncheck","hover","dragTo","uploadFile"]),za=/(?<=(?:^|[^\\])(?:\\\\)*)(\\?)(<[^<>]+>|\{(?:env|data|date)[^{}]*\})/g;function Gu(e,t){return e===void 0?!1:[...e.matchAll(za)].some(({2:n,index:r})=>{let s=e.slice(Math.max(0,r-2),r);return!(n.startsWith("<")&&(s==="(?"||s==="\\k"))&&t(n).trim()===""})}function Uu(e){let t=[...e.matchAll(/(?:has-text\(\s*|(?:internal:)?(?:has-)?text=)"((?:[^"\\]|\\.)*)"(?!s)/g)].map(s=>s[1]),n=[...e.matchAll(/contains\(\s*(?:\.|text\(\))\s*,\s*(?:'((?:[^'\\]|\\.)*)'|"((?:[^"\\]|\\.)*)")\s*\)/g)].map(s=>s[1]??s[2]),r=e.split(">>").flatMap(s=>s.trim().match(/^(?:internal:)?text=(?!["/])(.*)$/s)?.[1]??[]);return[...t,...n,...r]}var Fa=(e,t)=>new Error(`${e} "${t}" holds an empty row or data value, so it would match more than it means. Give that cell or data value a value, or give the blank case its own Scenario.`);function St(e,t,n,r){return e===void 0||e.trim()===""?!1:t.trim()===""?!0:r!==void 0&&r.test("")&&r.test("\u2063zq9")&&[...e.matchAll(za)].some(({2:s,index:o})=>{let a=e.slice(Math.max(0,o-2),o);return!(s.startsWith("<")&&(a==="(?"||a==="\\k"))&&n(s).trim()===""})}var Mn=String.raw`(?:<[^<>]+>|\{(?:data|env|unique|date)[^{}]*\})`;function jr(e,t,n){if(!e.includes(t))return!1;let r=n!==void 0&&new RegExp(`^\\s*${Mn}`).test(n)&&/^[\p{L}\p{N}\p{M}]/u.test(t),s=n!==void 0&&new RegExp(`${Mn}\\s*$`).test(n)&&/[\p{L}\p{N}\p{M}]$/u.test(t);return!r&&!s?!0:new RegExp(`${r?"(?<![\\p{L}\\p{N}\\p{M}])":""}${be(t)}${s?"(?![\\p{L}\\p{N}\\p{M}])":""}`,"u").test(e)}function ja(e,t){let n=new RegExp(`^\\s*${Mn}`).test(e)&&/^[\p{L}\p{N}\p{M}]/u.test(t),r=new RegExp(`${Mn}\\s*$`).test(e)&&/[\p{L}\p{N}\p{M}]$/u.test(t);return!n&&!r?t:new RegExp(`${n?"(?<![\\p{L}\\p{N}\\p{M}])":""}${be(t.trim())}${r?"(?![\\p{L}\\p{N}\\p{M}])":""}`,"iu")}var La=e=>{try{return decodeURIComponent(e)}catch{return e}},Pt=(e,t)=>new Error(`${e} "${t}" is empty for this row, so it would hold for anything. Give that cell or data value a value, or give the check its own Scenario.`);function pn(e,t,n,r,s){let o=(c,l,d)=>c.replace(l,f=>{let p=d(f);return p.trim()===""&&r?.(),p}),a=o(e,/<[^<>]+>/g,c=>Vn(c,t)),i=Ve(o(a,Ae,Dt),s);return Bl(o(i,Ce,c=>oo(c,n)))}function Dn(e,t,n,r=!1,s=!1){return e.replace(za,(o,a,i,c)=>{let l=e.slice(Math.max(0,c-2),c);if(i.startsWith("<")&&(l==="(?"||l==="\\k"))return o;let d=t(i);if(d===i)return o;if(!r)return a+n(d);let f=!1,p=-1;for(let w=0;w<c;w++){if(e[w]==="\\"){w++;continue}e[w]==="["&&(f=!0),e[w]==="]"&&(f=!1),!f&&e[w]==="{"&&(p=w),!f&&e[w]==="}"&&(p=-1)}if(f)return n(d).replace(/-/g,"\\x2d");if(p>=0&&e.indexOf("}",c+o.length)>=0)throw new Error("A regex quantifier cannot contain a row or data token. Use a separate Scenario with a literal repeat count.");if(!s)return n(d);let u=e.slice(0,c),h=e.slice(c+o.length),b=/[\p{L}\p{N}\p{M}]$/u.test(u)||/(?:\\[dDwWsSpP]|(?<!\\)[.\])}*+?])$/.test(u),g=Ku(h),S=/^[\p{L}\p{N}\p{M}]/u.test(d)&&!b?String.raw`(?<![\p{L}\p{N}\p{M}])`:"",y=/[\p{L}\p{N}\p{M}]$/u.test(d)&&!g?String.raw`(?![\p{L}\p{N}\p{M}])`:"";return S+n(d)+y})}function Ku(e){if(/^[\p{L}\p{N}\p{M}]/u.test(e)||/^(?:\\[dDwWsSpP]|[.*+?{])/.test(e))return!0;let t=/^\((?:\?:|\?<[A-Za-z_]\w*>)?/.exec(e);if(t)return Ku(e.slice(t[0].length));let n=/^\[((?:\\.|[^\]\\])*)\]/.exec(e);return n!==null&&(/[\p{L}\p{N}]/u.test(n[1].replace(/\\./g,""))||/\\[dDwWpP]/.test(n[1])||n[1].startsWith("^"))}function Ht(e,t=""){return(/[uv]/.test(t)||e.includes(String.raw`[\p{L}\p{N}\p{M}]`))&&(e=e.replace(/\\.|[\s\S]/g,n=>/^\\['"`>\-]$/.test(n)?`\\x${n.charCodeAt(1).toString(16)}`:n),/[uv]/.test(t)||(t+="u")),new RegExp(e,t)}function Ba(e,t){return Wn(e,(r,s)=>Dn(r,t,ue[s],s==="regex",!0),t,!0).replace(/"((?:[^"\\]|\\.)*)"|=\/((?:[^/\\]|\\.)*)\/([a-z]*)/g,(r,s,o,a)=>s!==void 0?r:`=${Ht(o,a).toString()}`)}function zu(e,t,n,r=!1,s=!0,o=new Set,a){let i=p=>pn(p,n,o,void 0,a);for(let p of["name","text","label","placeholder","testId"]){if(St(t[p],i(t[p]??""),i))throw Pt(`The target's ${p}`,t[p]);if((p==="text"||p==="label"||p==="placeholder")&&Gu(t[p],i))throw Fa(`The target's ${p}`,t[p])}if(t.role&&t.nameRegex!==void 0){let p=Dn(t.nameRegex,i,ue.pattern,!0,!0);if(St(t.nameRegex,p,i,Ht(p,"i")))throw Pt("The target's name",t.nameRegex)}let c=p=>p.split(">>").map(u=>u.trim().startsWith("internal:")?u:u.replace(/(\[\s*[\w-]+\s*=\s*)(["'])((?:(?!\2)[^\\]|\\.)*)\2(\s*[is]?\s*\])/g,"$1$2$2$4")).join(">>");for(let p of[...t.fallbackSelectors??[],...t.frame?[t.frame]:[]]){let u=c(p);Wn(u,(S,y)=>{let w=Dn(S,i,ue[y],y==="regex",!0),v;try{v=y==="regex"?Ht(w):void 0}catch{}if(St(S,w,i,v))throw Pt("The text in selector",p);return S},S=>S,!0);let h=[...u.matchAll(/'((?:[^'\\]|\\.)*)'/g)].map(S=>S[1]),b=u.split(">>").flatMap(S=>S.trim().match(/^(?:internal:)?text=(?!["/])(.*)$/s)?.[1]??[]);for(let S of[...h,...b])if(St(S,i(S),i))throw Pt("The text in selector",p);let g=new RegExp(`^\\s*(${Mn})|(${Mn})\\s*$`,"g");for(let S of Uu(p))if([...S.matchAll(g)].some(w=>i(w[1]??w[2]).trim()==="")&&i(S).trim()!=="")throw Fa("The text in selector",p)}let l=[],d=p=>Ba(p,i),f=p=>{if(t.role){let u=t.nameRegex?Ht(Dn(t.nameRegex,i,ue.pattern,!0,!0),"i"):t.name?i(t.name):void 0,h=t.role;u===void 0&&!!(t.label||t.placeholder||t.text||t.testId||t.fallbackSelectors?.length)?t.text&&l.push(p.getByRole(h).filter({hasText:ja(t.text,i(t.text))})):typeof u=="string"?(l.push(p.getByRole(h,{name:u,exact:!0})),s&&l.push(p.getByRole(h,{name:u,exact:!1}))):l.push(p.getByRole(h,{name:u,exact:!1}))}t.label&&l.push(p.getByLabel(i(t.label))),t.placeholder&&l.push(p.getByPlaceholder(i(t.placeholder))),t.text&&!t.role&&l.push(p.getByText(ja(t.text,i(t.text)))),t.testId&&l.push(p.getByTestId(i(t.testId)));for(let u of t.fallbackSelectors??[]){let h=u.split(">>").pop()??u,b=p.locator(d(u)),g=typeof b.filter!="function"?b:Uu(h).reduce((S,y)=>new RegExp(`^\\s*${Mn}|${Mn}\\s*$`).test(y)?S.filter({hasText:ja(y,i(y))}):S,b);l.push(g)}};if(t.frame)f(e.frameLocator(d(t.frame)));else if(f(e),r)for(let p of e.frames())p!==e.mainFrame()&&f(p);if(l.length===0)throw new Error("Action target has neither role nor fallback selectors");return l}var Yu=100,Iw=500;async function Nw(e,t,n,r){let s=Date.now()+t,o;for(;Date.now()<s;){try{if(await e())return}catch(a){o=a}await Ua(r)}throw new Error(`Timed out waiting for ${n}${o?` (${String(o)})`:""}`)}async function Zt(e,t,n=!1){let r;for(let s of e)try{await t(s.first());return}catch(o){if(r=o,n&&await s.first().count().catch(()=>0)>0)throw o}throw r}var jw=20,Ze=e=>e.replace(/\s+/g," ").trim(),jn=new WeakMap,hs=new WeakMap;async function Hu(e,t){let n={element:t};if(await e.count()!==1)return n;let r=await t.ownerFrame();if(!r)return n;let s=await t.getAttribute("id"),o=await t.getAttribute("data-testid"),a=[o?r.getByTestId(o):void 0,s?r.locator(`#${await t.evaluate(i=>i.ownerDocument.defaultView.CSS.escape(i.id))}`):void 0];for(let i of a)if(i&&await i.count()===1){n.stable=i;break}return n}async function Mw(e){if(!await e.element.evaluate(n=>n.isConnected).catch(()=>!1)&&e.stable&&await e.stable.count()===1){let n=await e.stable.elementHandle({timeout:100});n&&(await e.element.dispose().catch(()=>{}),e.element=n)}return Ze((await e.element.evaluate(tr,!1)).text)}var ms=new WeakMap,gs=new WeakMap,qu="__saffron_download",Vu=5*1024*1024;async function Ha(e,t,n){let r=e.suggestedFilename(),s,o=new Promise(l=>{s=setTimeout(()=>l(`it did not finish within ${n} ms`),n)}),a=await Promise.race([e.failure(),o]).finally(()=>clearTimeout(s));if(a)throw e.cancel().catch(()=>{}),new Error(`waitForDownload failed: the download of ${r} failed (${a})`);if(!t)return e.path();let i=ws.basename(r).replace(/[\u0000-\u001f<>:"/\\|?*]/g,"_"),c=ws.join(t,i===""||i==="."||i===".."?"download":i);return await Ma.promises.mkdir(t,{recursive:!0}),await e.saveAs(c),c}async function qa(e){let t=ws.basename(e),{size:n}=await Ma.promises.stat(e);if(n>Vu)throw new Error(`the downloaded file ${t} is ${n} bytes; a content check reads text files up to ${Vu} bytes`);let r=await Ma.promises.readFile(e),s;try{if(r.includes(0))throw new Error("NUL byte");s=new TextDecoder("utf-8",{fatal:!0}).decode(r)}catch{throw new Error(`the downloaded file ${t} is not a UTF-8 text file, so its content cannot be checked`)}return s=s.replace(/^\uFEFF/,"").replace(/\r\n?/g,`
|
|
38
|
+
`),/\.(ics|ical|ifb|vcf|vcs)$/i.test(t)?s.replace(/\n[ \t]/g,""):s}function Lo(e,t,n,r){let s=o=>pn(o,t,n,void 0,r);return{value:e.value===void 0?void 0:s(e.value),pattern:e.pattern===void 0?void 0:Dn(e.pattern,s,ue.pattern,!0,!0)}}function Va(e,t,n,r){if(!e.value&&!e.pattern)return"expectDownload needs a value or a pattern";let s=l=>pn(l,t,n,void 0,r),{value:o,pattern:a}=Lo(e,t,n,r);if(St(e.value,o??"",s))return Pt("The text the downloaded file must contain",e.value).message;if(a!==void 0&&St(e.pattern,a,s,Ht(a,"m")))return Pt("The pattern the downloaded file must match",e.pattern).message;let i=!1;if(e.value!==void 0&&pn(e.value,t,n,()=>{i=!0},r),i)return"The text the downloaded file must contain holds an empty row or data value. Give it a value, or give the blank case its own Scenario with explicit text.";let c=!1;if(e.pattern!==void 0&&(Dn(e.pattern,l=>pn(l,t,n,()=>{c=!0},r),ue.pattern,!0),c&&!Ht(a,"m").test("")))return"The pattern the downloaded file must match holds an empty row or data value. Give it a value, or give the blank case its own Scenario with an explicit pattern."}function Ja(e,t,n,r,s){if(n&&!jr(e,n,s))return`the downloaded file ${t} does not contain "${n}"`;if(r!==void 0&&!Ht(r,"m").test(e))return`the downloaded file ${t} does not match /${r}/m`}function tr(e,t=!1){if(!e.isConnected)return{text:"",pieces:[],kept:!1};let n=e.ownerDocument,r=n.defaultView,s=S=>r.getComputedStyle(S),o=S=>S.checkVisibility?.({contentVisibilityAuto:!1,visibilityProperty:!1,opacityProperty:!1})??S.getClientRects().length>0,a=S=>S.replace(/\s+/g," ").trim(),i=new Set,c=S=>{S&&i.add(S)},l=n.createRange(),d=!1,f=!1;for(let S=e.parentElement;S&&!f;S=S.parentElement)f=s(S).contentVisibility==="auto";let p=(S,y,w,v)=>{if(S.tagName==="BR")return["",`
|
|
39
|
+
`,""];if(S.tagName==="TEXTAREA"){let A=y.visibility==="visible"?String(S.value??""):"";return[A,A,t?a(A):""]}let x=y.visibility!=="visible"||y.contentVisibility==="hidden"||S.tagName==="DETAILS"&&!S.open,$=/^(pre|pre-wrap|pre-line|break-spaces)$/.test(y.whiteSpace),E=v||y.contentVisibility==="auto",R="",k="",C="",P=0;for(let A of Array.from(S.childNodes)){if(A.nodeType===3){if(x)continue;let I=A.nodeValue??"",L=/\S/.test(I);if(L&&!w){l.selectNodeContents(A);let H=!!S.shadowRoot||/^(CANVAS|VIDEO|AUDIO|OBJECT|IFRAME)$/.test(S.tagName);if(l.getClientRects().length===0&&(!E||H))continue}let j=I.replace(/[ \t\n\r\f]+/g," ");$?L&&I!==j&&(d=!0):I=j,R+=I,k+=I,L&&(P+=2);continue}if(A.nodeType!==1)continue;let O=s(A);if(O.display==="none"||w&&A.hidden||!w&&O.display!=="contents"&&!o(A))continue;let[T,_,N]=p(A,O,w||A.tagName==="SELECT",E);R+=T;let F=A.tagName!=="OPTION"&&/^(inline|contents)/.test(O.display);k+=F?_:`
|
|
40
|
+
${_}
|
|
41
|
+
`,!(!t||!N)&&(P++,C=N,F&&_.includes(`
|
|
42
|
+
`)&&(c(a(_.slice(0,_.indexOf(`
|
|
43
|
+
`)))),c(a(_.slice(_.lastIndexOf(`
|
|
44
|
+
`)+1)))))}if(!t)return[R,k,""];let m=P===1?C:a(k);return c(m),[R,k,m]},u=e.closest("select"),h;if(u){h=u.getClientRects().length>0&&o(u);for(let S=e;h&&S!==u;S=S.parentElement)(S.hidden||s(S).display==="none")&&(h=!1)}else{let S=e;for(;S&&s(S).display==="contents";)S=S.parentElement;h=!S||o(S)}if(!h)return{text:"",pieces:[],kept:!1};let[b,g]=p(e,s(e),!!u,f);if(t)for(let S of g.split(`
|
|
45
|
+
`))c(a(S));return{text:b,pieces:[...i],kept:d}}function Dw(e,[t,n]){let r=(0,eval)("("+n+")"),s=i=>{for(let c=i;c;c=c.parentElement??c.getRootNode().host)if(c.hidden||c.ownerDocument.defaultView.getComputedStyle(c).display==="none")return!0;return!1},o=i=>String(i.textContent??"").replace(/\s+/g," ").trim(),a=i=>s(i)||o(i)!==""&&!/\S/.test(r(i).text);if(e.length===0||!a(e[0]))return 0;for(let i=1;i<Math.min(e.length,t);i++)if(!a(e[i]))return o(e[i])===o(e[0])?i:0;return 0}async function Ju(e,t){let{text:n,kept:r}=await e.evaluate(tr,!1,t);if(/\S/.test(n)||await e.isVisible())return{text:n,kept:r}}async function ys(e,t,n,r,s,o=new Map,a,i=Yu,c=new Set,l){let d=(m,A,O)=>Nw(m,A,O,i),f=gs.get(e);if(f!==void 0&&(Do.has(t.action)&&!(t.action==="uploadFile"&&!t.target)||t.action==="goto"||t.action==="newTab")){gs.delete(e);let m=jn.get(e),A=e.context(),O=[],T=()=>{},_=F=>{O.push(F),O.length>=f&&T()},N=F=>{F.on("download",_)};A.pages().forEach(N),A.on("page",N);try{let F;try{F=await ys(e,t,n,r,s,o,a,i,c,l)}catch(I){if(!/Download is starting/.test(I instanceof Error?I.message:String(I)))throw I}if(O.length<f&&await new Promise(I=>{let L=setTimeout(I,r);T=()=>{clearTimeout(L),I()}}),O.length===0)throw new Error(`waitForDownload failed: the ${t.action} after it started no download within ${r} ms`);if(O.length<f)throw new Error(`waitForDownload failed: the ${t.action} after it started ${O.length} of the ${f} downloads it started when recorded, within ${r} ms`);return o.set(qu,await Ha(O[O.length-1],l,r)),F}catch(F){throw gs.set(e,f),m&&!jn.has(e)&&jn.set(e,m),F}finally{A.off("page",N);for(let F of A.pages())F.off("download",_)}}let p=jn.get(e);if(p&&Do.has(t.action)&&t.action!=="uploadFile"){jn.delete(e);let m,A=T=>{m??=T};e.on("filechooser",A);let O;try{if(O=await ys(e,t,n,r,s,o,a,i,c,l),m||await e.waitForEvent("filechooser",{timeout:r}).then(A,()=>{}),!m)throw new Error(`uploadFile failed: the ${t.action} after it opened no file chooser within ${r} ms`);try{await m.setFiles(p,{timeout:r})}catch(T){throw new Error(`uploadFile failed: ${T instanceof Error?T.message:String(T)}`)}}catch(T){throw jn.set(e,p),T}finally{e.off("filechooser",A)}return O}o.has(Ct)||o.set(Ct,fn()),(Do.has(t.action)||t.action==="goto"||t.action==="newTab"||t.action==="closeTab")&&a?.markAction();let u=o.get(Ct),h=m=>typeof m=="string"?Yt(m,u):Array.isArray(m)?m.map(h):m&&typeof m=="object"?Object.fromEntries(Object.entries(m).map(([A,O])=>[A,h(O)])):m;t=h(t),n=h(n),o.has(uo)||o.set(uo,String(Date.now()));let b=new Date(Number(o.get(uo))),g=m=>pn(m,n,c,void 0,b),S=()=>JSON.stringify(Object.fromEntries(Object.entries(t.target??{}).sort(([m],[A])=>m.localeCompare(A)).map(([m,A])=>Array.isArray(A)?[m,A.map(O=>Ba(O,g))]:A===void 0||m==="role"?[m,A]:m==="nameRegex"?[m,Dn(A,g,ue.pattern,!0,!0)]:m==="frame"?[m,Ba(A,g)]:[m,g(A)]))),y=(m,A)=>Dn(m,O=>pn(O,n,c,A,b),ue.pattern,!0,!0),w=!1,v=t.value!==void 0&&t.action!=="expectAmount"?pn(t.value,n,c,()=>{w=!0},b):void 0,x=t.url!==void 0?g(t.url):void 0,$=t.action==="expectVisible"||t.action==="expectText"||t.action==="expectValue"||t.action==="expectMatches"||t.action==="expectAttribute"||t.action==="expectEach"||t.action==="expectDiffers"||t.action==="expectAmount"||t.action==="captureText",E=t.target?zu(e,t.target,n,$,!Do.has(t.action)&&!Se.has(t.action),c,b):[],R={timeout:r},k={timeout:Math.min(1e3,r)},C=async m=>{let A=await m.evaluateAll(Dw,[jw,tr.toString()]);return A>0?m.nth(A):m.first()},P=m=>async()=>{for(let A of E)try{if(await m(await C(A)))return!0}catch{}return!1};switch(t.action){case"goto":{if(!x)throw new Error("goto requires url");let m=ls(x);if(m)throw new Error(m);await e.goto(Sa(x,s),R);return}case"click":{let{clickCount:m,button:A,modifiers:O}=t,T={...R,clickCount:m,button:A,modifiers:O};return Zt(E,_=>_.click(T),!0)}case"fill":return Zt(E,m=>m.fill(v??"",R),!0);case"press":return E.length>0?Zt(E,m=>m.press(v??"",R),!0):e.keyboard.press(v??"");case"selectOption":return Zt(E,async m=>{if(t.clearSelection){await m.selectOption([],R);return}let A=(v??"").split(`
|
|
46
|
+
`);await m.selectOption(A.length>1?A:A[0],R)},!0);case"check":return Zt(E,m=>m.check(R),!0);case"uncheck":return Zt(E,m=>m.uncheck(R),!0);case"hover":return Zt(E,m=>m.hover(R),!0);case"waitFor":return E.length>0?Zt(E,m=>m.waitFor({state:"visible",timeout:r})):Ua(Math.min(Number(v??"0"),r));case"expectVisible":return d(P(m=>m.isVisible()),r,"target to be visible");case"expectNotVisible":return d(async()=>{for(let m of E){let A=await m.count();for(let O=0;O<A;O++)if(await m.nth(O).isVisible())return!1}return!0},r,`every match of every recorded locator to be hidden (${E.length} locator(s))`);case"expectText":if(Ze(v??"")!==""&&w)throw new Error("The expected text contains an empty row or data value. Give it a value, or give the blank case its own Scenario with explicit expected text.");return d(P(async m=>{let A=await Ju(m,k);return A===void 0?Ze(v??"")==="":Ze(v??"")===""?Ze(A.text)==="":jr(Ze(A.text),Ze(v??""),t.value)||A.kept&&jr(A.text,v??"",t.value)}),r,`text "${v}"`);case"expectEach":{let m=(t.each!==void 0?Vn(t.each,n):void 0)?.match(/^\{data:([^}]+)\}$/)?.[1];if(!m)throw new Error(`expectEach needs a {data:...} list reference, got ${JSON.stringify(t.each)}`);let A=$n(m),O=async _=>{let{pieces:N}=await _.evaluate(tr,!0,k),F=new Set(N.map(I=>I.toLowerCase()));if(await _.isVisible())for(let I of(await _.innerText(k)).split(`
|
|
47
|
+
`))F.has(Ze(I).toLowerCase())&&N.push(Ze(I));return new Set(N)},T=A;return d(async()=>{for(let _ of E)try{let N=await O(await C(_)),F=A.filter(I=>!N.has(I.replace(/\s+/g," ").trim()));if(F.length<T.length&&(T=F),F.length===0)return!0}catch{}return!1},r,`every value of ${t.each} to be shown`).catch(()=>{throw new Error(`${T.map(_=>`"${_}"`).join(", ")} from ${t.each} ${T.length===1?"is":"are"} not shown in the target (${A.length-T.length} of ${A.length} found)`)})}case"expectValue":return d(P(async m=>await m.isVisible()&&await m.inputValue(k)===(v??"")),r,`input value "${v}"`);case"expectUrl":{let m=x??v??"";if(m.trim()==="")throw Pt("The expected URL",t.url??t.value??"");if(Gu(t.url??t.value,g))throw Fa("The expected URL",t.url??t.value??"");return d(async()=>jr(e.url(),m,t.url??t.value)||jr(La(e.url()),m,t.url??t.value)||jr(La(e.url().replace(/\+/g,"%20")),m,t.url??t.value),r,`URL containing "${m}" on the active page (${e.url()})`)}case"handleDialog":{let m=(v??"accept")!=="dismiss",A=t.promptText?g(t.promptText):void 0,O=ms.get(e);O&&e.off("dialog",O);let T=_=>{ms.delete(e),(m?_.accept(A):_.dismiss()).catch(()=>{})};ms.set(e,T),e.once("dialog",T);return}case"uploadFile":{let m=et().root,A=(v??"").split(`
|
|
48
|
+
`).filter(Boolean).map(T=>ws.resolve(m,T));if(A.length===0)throw new Error("uploadFile requires a path");let O=Ta(A,m);if(O)throw new Error(O);if(E.length>0)return Zt(E,T=>T.setInputFiles(A,R),!0);jn.set(e,A);return}case"waitForDownload":gs.set(e,t.downloads??1);return;case"expectDownload":{let m=o.get(qu);if(!m)throw new Error("expectDownload: no file was downloaded in this scenario before this check");let A=Va(t,n,c,b);if(A)throw new Error(A);let O=Lo(t,n,c,b),T=Ja(await qa(m),ws.basename(m),O.value,O.pattern,t.value);if(T)throw new Error(T);return}case"dragTo":{if(!t.toTarget)throw new Error("dragTo requires toTarget");let m=zu(e,t.toTarget,n,!1,!1,c,b);return Zt(E,A=>A.dragTo(m[0].first(),R),!0)}case"captureText":{if(!t.saveAs)throw new Error("captureText requires saveAs");await a?.quiet(Math.min(r/2,3e3));let m=Math.min(Iw,r/4),A=Date.now()+r-m,O;return d(async()=>{for(let T of E){let _;try{if(_=await(await C(T)).elementHandle(k)??void 0,!_)continue;let N=Ze((await _.evaluate(tr,!1)).text);if(N==="")continue;let F=Date.now();if(O?.text!==N&&(O={text:N,since:F}),F-O.since<m&&F<A)return!1;let I=await Hu(T,_),L=hs.get(o);return L||hs.set(o,L=new Map),await L.get(t.saveAs)?.tracked.element.dispose().catch(()=>{}),L.set(t.saveAs,{page:e,key:S(),value:N,tracked:I}),_=void 0,o.set(t.saveAs,N),!0}catch{}finally{await _?.dispose().catch(()=>{})}}return!1},r,`non-empty text to capture as "${t.saveAs}"`)}case"expectAmount":{let m=Yn(t.value??"",T=>pn(T,n,c,void 0,b)),A=po(m,T=>o.get(T));if("problem"in A)throw new Error(`expectAmount: ${A.problem}`);let O;try{return await d(P(async T=>{O=Ze((await T.evaluate(tr,!1,k)).text);let _=vt(O);return _!==void 0&&En(_,A.amount)}),r,/\{env:/.test(t.value??"")?`the amount ${t.value}`:`the amount ${cd(A.amount)} (${m})`)}catch(T){throw new Error(`${T instanceof Error?T.message:String(T)}${O===void 0?"":`; the target shows "${O}"`}`)}}case"expectDiffers":{if(!t.compareTo)throw new Error("expectDiffers requires compareTo");let m=o.get(t.compareTo);if(m===void 0)throw new Error(`expectDiffers: no captured value named "${t.compareTo}"`);if(E.length>0){let T=hs.get(o)?.get(t.compareTo),_=T?.page===e&&T.value===m&&T.key===S()?T.tracked:void 0,N=_;try{return await d(async()=>{if(N){let F=await Mw(N);if(F===""||F===m)return!1;for(let I of E)try{if(await I.evaluateAll((L,j)=>L.includes(j),N.element))return!0}catch{}return!1}for(let F of E){let I;try{if(I=await(await C(F)).elementHandle(k)??void 0,!I)continue;let L=Ze((await I.evaluate(tr,!1)).text);if(L==="")continue;return N=await Hu(F,I),L!==m}catch{}finally{I&&I!==N?.element&&await I.dispose().catch(()=>{})}}return!1},r,`target text to differ from "${t.compareTo}" (${m})`)}finally{N&&N!==_&&await N.element.dispose().catch(()=>{})}}let A=v??"",O=o.get(A);if(O===void 0)throw new Error(`expectDiffers: no captured value named "${A}"`);if(O===m)throw new Error(`expectDiffers: "${A}" (${O}) equals "${t.compareTo}" (${m})`);return}case"expectAttribute":{if(!t.attribute)throw new Error("expectAttribute requires attribute");if(!t.pattern)throw new Error("expectAttribute requires pattern");let m=!1,A=y(t.pattern,()=>{m=!0}),O=Ht(A);if(m&&A!==""&&!O.test(""))throw new Error("The attribute pattern contains an empty row or data value. Give it a value, or give the blank case its own Scenario with an explicit pattern.");let T=g(t.attribute);if(St(t.attribute,T,g))throw Pt("The attribute name",t.attribute);let _=St(t.pattern,A,g,O),N=O.test("")&&O.test("false")&&!O.test("true");return d(P(async F=>{let I=await F.getAttribute(T,k);return _?(I??"").trim()==="":I===null?N:O.test(I)}),r,`attribute ${T} to match /${t.pattern}/`)}case"expectMatches":{if(!t.pattern)throw new Error("expectMatches requires pattern");let m=!1,A=y(t.pattern,()=>{m=!0}),O=Ht(A,"i");if(m&&Ze(A)!==""&&!O.test(""))throw new Error("The expected text pattern contains an empty row or data value. Give it a value, or give the blank case its own Scenario with an explicit pattern.");let T=Ze(A)===""||St(t.pattern,A,g,O);return d(P(async _=>{let N=await Ju(_,k);return N===void 0?T:T?Ze(N.text)==="":O.test(Ze(N.text))||N.kept&&O.test(N.text)}),r,`target text to match /${t.pattern}/i`)}case"switchTab":{let m=Number.parseInt(v??"",10),A=()=>e.context().pages().filter(T=>!T.isClosed());await d(async()=>A().length>m,r,`tab ${v} to exist (${A().length} open: ${A().map(T=>T.url()).join(", ")})`);let O=A()[m];return await O.bringToFront(),O}case"closeTab":{let m=e.context().pages().filter(T=>!T.isClosed()),A=v===void 0?e:m[Number.parseInt(v,10)];if(!A)throw new Error(`tab ${v} does not exist (${m.length} open)`);await A.close();let O=e.context().pages().filter(T=>!T.isClosed());if(O.length===0)throw new Error("closed the last tab; nothing left to drive");return O[O.length-1]}case"newTab":{let m=x?ls(x):void 0;if(m)throw new Error(m);let A=await e.context().newPage();return x&&await A.goto(Sa(x,s),R),A}case"waitForResponse":case"expectResponse":{if(!t.urlPattern)throw new Error(`${t.action} requires urlPattern`);let m=y(t.urlPattern),A=Ht(m),O=t.status!==void 0?g(t.status):void 0,T=t.method!==void 0?g(t.method):void 0,_=!1,N=t.pattern?y(t.pattern,()=>{_=!0}):void 0,F=N!==void 0?Ht(N):void 0;if(_&&N!==""&&F&&!F.test(""))throw new Error("The response body pattern contains an empty row or data value. Give it a value, or give the blank case its own Scenario with an explicit pattern.");if(St(t.urlPattern,m,g,A))throw Pt("The response URL pattern",t.urlPattern);if(St(t.status,O??"",g))throw Pt("The response status",t.status);if(St(t.method,T??"",g))throw Pt("The response method",t.method);if(F&&St(t.pattern,N,g,F))throw Pt("The response body pattern",t.pattern);if(!a){await e.waitForResponse(async L=>{let j={seq:0,url:L.url(),method:L.request().method(),status:L.status()};if(!Bu(j,A,T,O,void 0))return!1;if(!F)return!0;let H=await L.text().catch(()=>{});return H!==void 0&&F.test(H)},R);return}let I=()=>t.action==="expectResponse"?a.sinceAction():a.sincePreviousStep();return d(async()=>{let L=I().find(j=>Bu(j,A,T,O,F));return L&&(a.lastMatch=L),L!==void 0},r,Pw({...t,status:O,method:T},t.urlPattern))}default:throw new Error(`Unknown action type: ${t.action}`)}}var Fo=(e,t)=>pt(e.actions,t);function Fw(e,t){let n=e.examples;return n?e.steps.some(r=>r.actions.some(s=>Et(s).some(o=>o!==void 0&&[...o.matchAll(/\{data:([^{}]*<[^<>{}]+>[^{}]*)\}/g)].some(([,a])=>a.replace(/<([^<>]+)>/g,(i,c)=>n[c]??"\0")===t)))):!1}var Wu=(e,t)=>cn(e.actions,t);function Fn(e,t){if(!t.rowBound?.length||!t.examples||t.steps.length!==e.steps.length||t.steps.some((g,S)=>g.gherkin!==e.steps[S].text||g.kind!==e.steps[S].kind)||t.steps.some((g,S)=>JSON.stringify(g.table??null)!==JSON.stringify(e.steps[S].table??null)||(g.docString??null)!==(e.steps[S].docString??null))&&!Mr(e,t))return;let r=t.rowBound.filter(g=>g.column in e.params),s=is([...new Set(r.map(g=>g.column))],t.examples,e.params,t.recordedAt,t.data);if(s===void 0){let g=r.find(w=>w.valueSha!==void 0&&!mo(e.params[w.column]??"",w.valueSha));if(!g)return;let{keyword:S,gherkin:y}=t.steps[g.step];return`This Outline was recorded with ${g.column} as ${t.examples[g.column]}, which resolves to another value now (or is not set), and step ${g.step+1} ("${S?`${S.trim()} `:""}${y}") still holds the value it had, so the recording cannot check this row. Record the Outline again with saffron run --rerecord.`}let{step:o,reason:a}=r.find(g=>g.column===s),i=t.examples[s],c=`this row, where ${s} is "${e.params[s]}"`,{keyword:l,gherkin:d}=t.steps[o],f=`step ${o+1} ("${l?`${l.trim()} `:""}${d}")`,p=d.includes(`<${s}>`),u=[...new Set(r.map(g=>g.column))],b=(e.exampleRows??[]).every(g=>is(u,t.examples,g,t.recordedAt,t.data)!==void 0)?` No Examples row has ${s} "${i}" any more: record the Outline again with saffron run --rerecord.`:" Or record the Outline again on another row with saffron run --rerecord.";return(a==="unwritten"&&t.steps[o].kind==="assertion"?`This Outline was recorded on the row where ${s} is "${i}", and ${f} names <${s}> but only checks that something is shown or in a state, which reads the same whoever <${s}> is, so it cannot prove ${c}. Make the check show the value: write <${s}> in the text the step expects (\`Then the dashboard greets "<${s}>"\`), then record again with saffron run --rerecord. Or give each value its own Scenario.`:a==="unwritten"?`This Outline was recorded on the row where ${s} is "${i}", and ${f} names <${s}> but recorded no action that writes it (on that row the page already was that way, or the action holds no row value, like ticking a box), so on ${c} it would do what it did for "${i}". Give each value its own Scenario, or, where the value is what the step picks (an option or radio labelled with it), record the step picking it even when it already is.`:a==="session"?`This Outline was recorded on the row where ${s} is "${i}", and ${f} runs in the browser session <${s}> names and types a value the step does not write, which was that person's: on ${c} the other person would type it too. Write that value in the step, or give it an Examples column and write <column> there, or give each person's flow its own Scenario.`:a==="container"?`This Outline was recorded on the row where ${s} is "${i}", and ${f} acts in the section <${s}> names without being scoped to it, so on ${c} it would act in whichever such section comes first. Record the Outline again so that step's target names its section, or the dialog its action opened (saffron run --rerecord), or give each section its own Scenario.`:a==="list"?`This Outline was recorded on the row where ${s} is "${i}", and ${f} holds other rows' ${s} values too, so one recording cannot check ${c}. Give that check its own Scenario, or give the text it holds an Examples column of its own and write that column in the step.`:a==="reads"?`This Outline was recorded on the row where ${s} is "${i}", and ${f} checks a response status, method or attribute against what a {data:...} reference keyed by <${s}> reads on that row, so one recording cannot check ${c}. Give the expected value an Examples column of its own and name it in that step, or give that check its own Scenario.`:a==="value"?`This Outline was recorded on the row where ${s} is "${i}", and ${f} checks "${i}" as a response status, method or attribute without naming <${s}>, so one recording cannot check ${c}. If that check follows the row, name <${s}> in that step; if the value only coincides, give the check its own Scenario.`:a==="data"?`This Outline was recorded on the row where ${s} is "${i}", and ${f} reads a {data:...} entry that more than one of the Outline's {data:...} references chose on that row, so one recording cannot check ${c}. Write the {data:...} reference that step needs in its own text, or give that check its own Scenario.`:p?`This Outline was recorded on the row where ${s} is "${i}", and ${f} holds "${i}" spelled otherwise or inside other text (an attribute's name, a {data:...} path), where <${s}> cannot follow the row, so one recording cannot check ${c}. Spell the value as the cell does, give it an Examples column of its own, or give that check its own Scenario.`:`This Outline was recorded on the row where ${s} is "${i}", and ${f} writes "${i}" inside other text without naming <${s}>, so one recording cannot check ${c}. Put <${s}> in that step, or give that check its own Scenario.`)+b}function Lw(e){let t=JSON.stringify([e.params,e.exampleRows??[],e.steps.map(n=>[n.text,n.table??[],n.docString??""])]);if(Kn(t))return!0;try{let n=Dt(t);return(n.match(/\{date/g)??[]).length>(t.match(/\{date/g)??[]).length?!0:Kn(n)}catch{return!1}}function Mr(e,t){if(t.steps.length!==e.steps.length||t.version<3&&Lw(e))return!1;let n=t.examples?[t.examples]:Object.keys(e.params).length>0?e.exampleRows??[]:[];for(let[r,s]of Object.entries(t.data??{})){let o;try{o=qe(r)}catch{continue}if(o===s)continue;let a=t.steps.some(c=>Fo(c,`{data:${r}}`))||Fw(t,r),i=t.steps.some(c=>On(c.actions,s));if(!a||i)return!1}return t.steps.every((r,s)=>{let o=e.steps[s];if(r.gherkin!==o.text||r.kind!==o.kind)return!1;if(n.length>0){let c=[o.text,...o.table?.flat()??[],o.docString??""].join(`
|
|
49
|
+
`);if(n.some(d=>Zn(r.actions,c,d,e.params,t.recordedAt)||os(c,d,e.params,r.actions)))return!1;{let d=e.steps.filter((p,u)=>u!==s).map(p=>[p.text,...p.table?.flat()??[],p.docString??""].join(`
|
|
50
|
+
`)).join(`
|
|
51
|
+
`),f=c.replace(/\{[^{}]*\}|<[^<>]+>/g," ");if(n.some(p=>os(d,p,e.params,r.actions,f)))return!1}let l=d=>r.kind==="assertion"&&!kr(r.actions)&&!(e.params[d]??"").includes("{date");if((t.examples!==void 0||r.actions.length===0)&&n.some(d=>$r(r.gherkin,r.actions,d).some(f=>!l(f)&&!go(c,f,e.params)&&d[f]!==void 0&&d[f]!==e.params[f])))return!1}let a=r.table,i=o.table;if(!!a!=!!i)return!1;if(a&&i){let c=Object.keys(rt(a)),l=Object.keys(rt(i));if(c.length>0&&l.length>0){if(JSON.stringify(c)!==JSON.stringify(l))return!1;let d=rt(a),f=rt(i);for(let p of c){if(d[p]===f[p])continue;let u=`<${p}>`,h=t.steps.some(g=>Fo(g,u)),b=t.steps.some(g=>Wu(g,d[p]));if(!h||b)return!1}}else if(JSON.stringify(a)!==JSON.stringify(i))return!1}if(r.docString!==void 0!=(o.docString!==void 0))return!1;if(r.docString!==void 0&&o.docString!==void 0&&r.docString!==o.docString){let c=t.steps.some(d=>Fo(d,"<docstring>")),l=t.steps.some(d=>Fo(d,r.docString)||Wu(d,r.docString));if(!c||l)return!1}return!0})}function Wa(e,t){let n=e.steps[t],r=n?.resolvedTable??n?.table;return{...e.params,...Tn(e.steps),...rt(r),...Jn(n?.resolvedDocString??n?.docString)}}async function Bo(e,t,n,r={}){let s=r.actionTimeoutMs??5e3,o=r.retries??1,a=Math.max(10,r.pollIntervalMs??Yu),i=[],c=r.envNames??tt(t),l=r.vars??new Map;r.uniqueSeed&&l.set(Ct,r.uniqueSeed);let d=()=>Object.fromEntries(l),f=n.steps.some(P=>P.actions.some(m=>(m.action==="waitForResponse"||m.action==="expectResponse")&&m.pattern!==void 0)),p=r.sessions??new Map;p.set(pe(t.steps[0]?.session),e);let u=new Map,h=P=>{let m=P.context();for(let _ of m.pages()){jn.delete(_),gs.delete(_);let N=ms.get(_);N&&_.off("dialog",N),ms.delete(_)}let A=new Da;A.attach(m,f);let O=[],T=_=>O.push(_);return m.on("page",T),{context:m,active:P,seen:new Set(m.pages()),opened:O,onPage:T,netLog:A}},b=async P=>{let m=u.get(P);if(m)return m;let A=p.get(P);if(!A||A.isClosed()){if(!r.openSession)throw new Error(`browser session "${P}" cannot be opened in this replay`);A=await r.openSession(P),p.set(P,A)}let O=h(A);return u.set(P,O),O},g=await b(pe(t.steps[0]?.session)),S=!1,y=()=>(S=r.keepResponseLog===!0,S?{responses:g.netLog}:{}),w=()=>{for(let[P,m]of u)m.active.isClosed()||p.set(P,m.active);return{activePage:g.active.isClosed()?void 0:g.active,sessions:p}},v=P=>new Promise(m=>{let A=g.context,O=()=>{clearTimeout(T),A.off("page",O),m()},T=setTimeout(O,P);A.on("page",O)}),x=[],E=!n.steps.some(P=>P.actions.some(m=>m.opensTab))&&n.steps.some(P=>P.actions.some(m=>m.action==="switchTab"||m.action==="closeTab"||m.action==="newTab")),R=()=>{let P=g.context.pages();for(let m of P)g.seen.has(m)||(g.seen.add(m),m.isClosed()||(g.active=m));if(g.active.isClosed()){let m=P.filter(A=>!A.isClosed());m.length>0&&(g.active=m[m.length-1])}},k=()=>{for(let P of u.values())P.context.off("page",P.onPage),S&&P===g||P.netLog.detach()};if(!Mr(t,n))return k(),{status:"stale",stepResults:i,captured:d()};let C=P=>{for(let m=P+1;m<n.steps.length;m++)i.push({gherkin:n.steps[m].gherkin,kind:n.steps[m].kind,status:"skipped"})};try{for(let P=0;P<n.steps.length;P++){let m=n.steps[P],A=Wa(t,P),O=!1,T=0,_=[],N=[];try{g=await b(pe(t.steps[P]?.session))}catch(j){let H=`Could not open browser session "${dt(pe(t.steps[P]?.session))}": ${j instanceof Error?j.message.split(`
|
|
52
|
+
`)[0]:String(j)}`;return i.push({gherkin:m.gherkin,fromStepSet:m.fromStepSet,kind:m.kind,status:"failed",error:H}),C(P),{status:"failed",failure:{stepIndex:P,actionIndex:0,stepText:m.gherkin,kind:m.kind,error:H},stepResults:i,captured:d(),tabOpeners:x,...w(),activePage:void 0}}for(let j of u.values())j.netLog.markStep();let F=(j,H)=>{let Z=g.context.pages().filter(z=>!z.isClosed()),Q=Z.filter(z=>!H.has(z)).at(-1),M=Q??g.active;if(M===j||M.isClosed())return;let U=Q?"opened":j.isClosed()?"closed":"switched";_.push({how:U,tab:Z.indexOf(M)+1,url:M.url()})},I=g.context;r.trace&&await I.tracing.group(`[saffron:${r.tracePhase??"replay"}:${P+(r.traceStepOffset??0)}] ${m.keyword} ${m.gherkin}`).catch(()=>{});let L=async()=>{r.trace&&await I.tracing.groupEnd().catch(()=>{})};try{if(m.kind==="assertion"&&!m.actions.some(j=>Se.has(j.action))){let j=`Assertion step "${m.gherkin}" recorded ${m.actions.length===0?"nothing":"only setup actions"}, so nothing was checked. Re-record the scenario (saffron run --rerecord) so the agent records what must be true.`;return i.push({gherkin:m.gherkin,fromStepSet:m.fromStepSet,kind:m.kind,status:"failed",drift:O,error:j}),C(P),{status:"failed",failure:{stepIndex:P,actionIndex:0,stepText:m.gherkin,kind:m.kind,error:j},stepResults:i,captured:d(),tabOpeners:x,...w(),...y()}}for(let j=0;j<m.actions.length;j++){let H=m.actions[j];R();let Z=g.active,Q=new Set(g.context.pages());g.netLog.lastMatch=void 0,H.pageFingerprint&&await _o(g.active)!==H.pageFingerprint&&(O=!0);let M,U=!1;for(let z=0;z<=o&&!U;z++){z>0&&(T++,await Ua(250*z),R());try{let V=z>0?`${it(H)} (attempt ${z+1})`:it(H),ee=await Ou(g.active,r.trace,`[saffron:action:${j}] ${V}`,()=>ys(g.active,H,A,s,r.baseURL,l,g.netLog,a,c,r.downloadsDir));ee&&(g.active=ee,g.seen.add(ee));let Ie=H.action==="click"||H.action==="press";if(g.opened.length===0&&H.opensTab?await g.context.waitForEvent("page",{timeout:s}).catch(()=>{}):g.opened.length===0&&Ie&&E&&await v(150),H.opensTab&&g.opened.length===0)throw new Error("this action opened a new tab when it was recorded, and none opened now; the flow has changed");g.opened.length>0&&x.push({stepIndex:P,actionIndex:j});let Ke=H.action==="click"&&((H.modifiers?.length??0)>0||H.button==="middle");for(;g.opened.length>0;){let Te=g.opened.shift();Ke&&g.seen.add(Te),await Te.waitForLoadState("domcontentloaded",{timeout:s}).catch(()=>{})}U=!0,F(Z,Q);let Ne=g.netLog.lastMatch;Ne&&(H.action==="waitForResponse"||H.action==="expectResponse")&&N.push({action:H.action,method:Ne.method,url:Ne.url,status:Ne.status})}catch(V){M=V}}if(!U){let z=M instanceof Error?M.message:String(M);i.push({gherkin:m.gherkin,fromStepSet:m.fromStepSet,kind:m.kind,status:"failed",drift:O,...T?{retries:T}:{},..._.length?{tabs:_}:{},...N.length?{responses:N}:{},failedActionIndex:j,error:z}),C(P);let V={stepIndex:P,actionIndex:j,stepText:m.gherkin,kind:m.kind,error:z,pageUrl:g.active.isClosed()?void 0:g.active.url()};return await r.onFailure?.(g.active,V).catch(()=>{}),{status:"failed",failure:V,stepResults:i,captured:d(),tabOpeners:x,...w(),...y()}}}i.push({gherkin:m.gherkin,fromStepSet:m.fromStepSet,kind:m.kind,status:"passed",drift:O,...T?{retries:T}:{},..._.length?{tabs:_}:{},...N.length?{responses:N}:{}})}finally{await L()}}return{status:"passed",stepResults:i,captured:d(),tabOpeners:x,...w()}}finally{if(k(),!r.vars){for(let P of hs.get(l)?.values()??[])await P.tracked.element.dispose().catch(()=>{});hs.delete(l)}}}import{createHash as Bw}from"node:crypto";import Uw from"node:path";var Ga=e=>Bw("sha1").update(JSON.stringify(e)).digest("hex").slice(0,16);function Zu(e){return{steps:e.steps.map(t=>({...t,actions:t.actions.map(({pageFingerprint:n,...r})=>r)})),data:e.data??null,...e.examples?{examples:e.examples}:{},...e.rowBound?{rowBound:e.rowBound}:{},...e.rowsUseNewDates?{rowsUseNewDates:!0}:{}}}var Qu=e=>Ga(e.map(t=>[t.kind,t.text,t.table??null,t.docString??null])),bs=e=>e?Ga(Zu(e)):"none",Xu=(e,t)=>Ga({contract:Zu(e),featureEdits:t??null});function ef(e,t,n,r){return{scenario:Qu(e.steps),committed:bs(t),recording:Xu(n,r)}}function $t(e,t,n){let r=t.meta.bound;if(!r)return;let s=[],{feature:o,scenario:a}=t.cache,i;if(n&&!(n instanceof Map))i=n;else try{i=ft(Uw.join(e,o),e,n).find(l=>l.name===a)}catch(l){s.push(`${o} no longer parses: ${l instanceof Error?l.message.split(`
|
|
53
|
+
`)[0]:String(l)}`)}s.length||(i?Qu(i.steps)!==r.scenario&&s.push(zw(i,t.cache)):s.push(`scenario "${a}" is no longer in ${o}`));let c;try{c=st(me(e,o,a))}catch(l){if(!(l instanceof $e))throw l;return s.push(`the committed recording cannot be read (${l.problem})`),s.join("; ")}return bs(c)!==r.committed&&s.push(r.committed==="none"?"a recording was committed for this scenario after the proposal was filed, so the diff you would review is not the one that was made":c?"the committed recording changed after the proposal was filed (an accepted heal, a propagated locator fix or a pull), so the diff you would review is not the one that was made":"the committed recording the proposal was diffed against is gone"),Xu(t.cache,t.meta.featureEdits)!==r.recording&&s.push("the proposal's recording or feature edits were edited after it was filed"),s.length>0?s.join("; "):void 0}function zw(e,t){let n=e.steps,r=t.steps;if(n.length!==r.length)return`the scenario has ${n.length} steps now and had ${r.length} when the proposal was filed`;let s=n.findIndex((o,a)=>o.text!==r[a].gherkin||o.kind!==r[a].kind);return s<0?"the scenario's steps changed since the proposal was filed":`step ${s+1} now reads "${n[s].text}" and was "${r[s].gherkin}" when the proposal was filed`}var Uo="not bound: filed by a runner older than 0.8.5, so changes since cannot be detected";import or from"node:fs";import sf from"node:path";function zo(e){return`$${e.toFixed(e>=1?2:4)}`}function Ka(e,t){let n=e===void 0?"?":`${Math.round(e)}%`,r=t===void 0?"?":`${Math.round(t)}%`;return`${n} \u2192 ${r}`}function kt(e){return e.costUsd>0||e.aiCalls===0}function Ya(e){return kt(e)?e.plan?` \xB7 5-hour window ${Ka(e.plan.fiveHourBefore,e.plan.fiveHourAfter)} (${e.plan.subscriptionType} plan) \xB7 \u2248 ${zo(e.costUsd)} at API rates`:` \xB7 ${zo(e.costUsd)}`:" \xB7 cost not reported by the provider"}function tf(e,t){return e?t?`\u2248 ${zo(e)}`:zo(e):""}function nf(e){if(!e)return"";let t=new Date(e);return Number.isNaN(t.getTime())?"":`resets ${t.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})}`}function Za(e){let t=e.costUsd===void 0?"":` \xB7 cost ${e.costUsd>=0?"+":"-"}$${Math.abs(e.costUsd).toFixed(4)}`;return`vs previous run: pass rate ${e.passRatePp>=0?"+":""}${e.passRatePp}pp${t} \xB7 AI calls ${e.aiCalls>=0?"+":""}${e.aiCalls}`}function rf(e,t){return`${e} pending review${t>0?` (${t} whose proof replay failed)`:""}`}var nr=e=>e.status==="yellow"&&e.verified===!1,Qa=(e,t)=>e.green+e.yellow-t.filter(nr).length;function rr(e,t){let n=e.green+e.yellow+e.red;return n===0?0:Math.round(Qa(e,t)/n*100)}function sr(e,t){if(e.name)return e.name;let n=e.scenario.replace(/ \(example \d+\)$/,"");return t&&(t(e.scenario)||!t(n))?e.scenario:n}function Ho(e,t=e.provider){if(!e.provider)return"no agent (--no-agent)";let n=(r,s,o)=>r&&`${o} ${r.name} (${r.source==="flag"?s:"saffron.config.json"})`;return[`${t} agent${e.sdk?` on ${e.sdk.name} ${e.sdk.version}`:""}`,n(e.model,"--model","model")??`${t}'s default model`,n(e.healModel,"--heal-model","heal model")].filter(Boolean).join(" \xB7 ")}function of(e,t){return e.feature===t.feature&&e.scenario===t.scenario&&(e.browser===void 0||t.browser===void 0||e.browser===t.browser)}function ec(e){let t=r=>`${r.feature}\0${r.scenario}`,n=new Map;for(let r of e)r.browser&&n.set(t(r),(n.get(t(r))??new Set).add(r.browser));return r=>{let s=[...n.get(t(r))??[]];return s.length<2?[{key:t(r)}]:(r.browser?[r.browser]:s).map(o=>({key:`${t(r)}\0${o}`,browser:o}))}}function tc(e){return sf.join(e,".saffron","history.jsonl")}function nc(e,t,n,r){let s=e.map(o=>({feature:o.scenario.featurePath,scenario:o.scenario.displayName,name:o.scenario.name,tags:[...o.scenario.tags],status:o.status,source:o.source,durationMs:o.durationMs,verified:o.verified,seededSteps:o.seededSteps,adaptations:o.adaptations.length,driftSteps:o.stepResults.filter(a=>a.drift).length,aiCalls:o.usage.aiCalls,tokensInOut:o.usage.inputTokens+o.usage.outputTokens,cacheRead:o.usage.cacheReadTokens,cacheWrite:o.usage.cacheCreationTokens,costUsd:o.usage.costUsd??0,error:o.error?.split(`
|
|
54
|
+
`)[0],browser:o.browser}));return{runId:t.toISOString(),startedAt:t.toISOString(),finishedAt:new Date().toISOString(),baseURL:r,green:s.filter(o=>o.status==="green").length,yellow:s.filter(o=>o.status==="yellow").length,red:s.filter(o=>o.status==="red").length,aiCalls:s.reduce((o,a)=>o+a.aiCalls,0),costUsd:s.reduce((o,a)=>o+a.costUsd,0),divergentSteps:n,scenarios:s}}function rc(e,t){let n=tc(e);or.mkdirSync(sf.dirname(n),{recursive:!0}),or.appendFileSync(n,`${JSON.stringify(t)}
|
|
55
|
+
`)}function af(e,t){let n=tc(e);if(!or.existsSync(n))return rc(e,t);let r=or.readFileSync(n,"utf8").split(`
|
|
56
|
+
`).filter(a=>a.trim()),s=!1,o=r.map(a=>{try{if(JSON.parse(a).runId===t.runId)return s=!0,JSON.stringify(t)}catch{}return a});s||o.push(JSON.stringify(t)),or.writeFileSync(n,`${o.join(`
|
|
49
57
|
`)}
|
|
50
|
-
`)}function
|
|
51
|
-
`).filter(Boolean),s=[],o=0;for(let
|
|
52
|
-
<path d="${
|
|
53
|
-
<path d="${
|
|
54
|
-
</svg>`}function
|
|
58
|
+
`)}function vs(e,t=50){let n=tc(e);if(!or.existsSync(n))return[];let r=or.readFileSync(n,"utf8").trim().split(`
|
|
59
|
+
`).filter(Boolean),s=[],o=0;for(let a=r.length-1;a>=0&&o<t;a--)try{let i=JSON.parse(r[a]);s.push(i),i.partial||o++}catch{}return s.reverse()}var Xa=e=>rr(e,e.scenarios);function sc(e,t){let n=e.filter(u=>!u.partial),r=[...n,t],s=r.slice(-20),o=r.slice(-10),a=n.at(-1),i=a?{passRatePp:Xa(t)-Xa(a),costUsd:kt(t)&&kt(a)?t.costUsd-a.costUsd:void 0,aiCalls:t.aiCalls-a.aiCalls,red:t.red-a.red}:void 0,c=new Map,l=ec(o.flatMap(u=>u.scenarios));for(let u of o)for(let h of u.scenarios)for(let{key:b,browser:g}of l(h)){let S=c.get(b)??{feature:h.feature,scenario:g?`${h.scenario} [${g}]`:h.scenario,heals:0,reds:0,runs:0};S.runs++,h.source==="agent-heal"&&h.status==="yellow"&&S.heals++,h.status==="red"&&S.reds++,c.set(b,S)}let d=[...c.values()].filter(u=>u.heals>=2||u.reds>=3).sort((u,h)=>h.heals+h.reds-(u.heals+u.reds)),f=new Map;for(let u of s)for(let h of u.scenarios)h.status==="red"&&h.error&&f.set(h.error,(f.get(h.error)??0)+1);let p=[...f.entries()].sort((u,h)=>h[1]-u[1]).slice(0,3).map(([u,h])=>({message:u,count:h}));return{prev:i,series:{passRate:s.map(Xa),costUsd:s.map(u=>kt(u)?Number(u.costUsd.toFixed(4)):null),aiCalls:s.map(u=>u.aiCalls)},chronic:d,divergentSteps:t.divergentSteps,topIssues:p}}var cf=20,Hw=10,qw=e=>e.scenarios.filter(nr).length,df=e=>e.replace(/\\/g,"/"),Dr=(e,t)=>`${df(e)}\0${t}`,Vw=(e,t)=>t===0?0:Math.round(e/t*100),lf=e=>Math.max(0,Date.parse(e.finishedAt)-Date.parse(e.startedAt))||0;function uf(e,t){let n=new Map;for(let T of e)for(let _ of T.scenarios)n.set(Dr(T.path,_.name),{feature:T.path,scenario:_.name,tags:_.tags});let r=T=>sr(T,_=>n.has(Dr(T.feature,_))),s=T=>n.has(Dr(T.feature,r(T))),o=e.flatMap(T=>T.scenarios),a=t.filter(T=>!T.partial),i=T=>a.at(-T)?.startedAt??"",c=a.slice(-cf),l=a.at(-1),d=new Set((l?.scenarios??[]).flatMap(T=>T.browser?[T.browser]:[])),f=T=>T===""||d.size===0||d.has(T),p=new Map,u=t.filter(T=>T.startedAt>=i(cf)),h=ec(u.flatMap(T=>T.scenarios));for(let T of u)for(let _ of T.scenarios){if(!s(_))continue;let N=r(_);for(let{key:F,browser:I}of h(_)){let L=p.get(F)??{ref:{feature:df(_.feature),scenario:_.scenario,...N!==_.scenario?{name:N}:{},...I?{browser:I}:{}},results:[]};L.results.push({at:T.startedAt,s:_,target:T.baseURL??""}),p.set(F,L)}}let b=[],g=[],S=[];for(let{ref:T,results:_}of p.values()){if(T.browser&&!f(T.browser))continue;let N=new Map,F=0,I=0,L=0;for(let H of _){if(H.s.source==="agent-record")continue;let Z=H.s.status==="red";L++,Z&&I++;let Q=N.get(H.target);Q!==void 0&&Q!==Z&&F++,N.set(H.target,Z)}F>=2&&b.push({...T,runs:L,reds:I,flips:F,last:_.at(-1).s.status});let j=_.filter(H=>H.s.source==="agent-heal"&&H.s.status==="yellow");j.length>=2&&g.push({...T,runs:_.length,heals:j.length,unverified:j.filter(H=>nr(H.s)).length}),S.push({...T,avgMs:Math.round(_.reduce((H,Z)=>H+Z.s.durationMs,0)/_.length),lastMs:_.at(-1).s.durationMs,runs:_.length})}b.sort((T,_)=>_.flips-T.flips||_.reds-T.reds),g.sort((T,_)=>_.heals-T.heals),S.sort((T,_)=>_.avgMs-T.avgMs);let y=[],w=new Set(t.filter(T=>T.startedAt>=i(Hw)).map(T=>T.startedAt));for(let{ref:T,results:_}of p.values()){if(T.browser&&!f(T.browser))continue;let N=_.findLast(L=>L.s.status==="red");if(!N||!w.has(N.at))continue;let F=_.at(-1).s.status==="red",I=0;for(let L=_.length-1;L>=0&&_[L].s.status==="red";L--)I++;y.push({...T,at:N.at,error:N.s.error,stillFailing:F,streak:I})}y.sort((T,_)=>Number(_.stillFailing)-Number(T.stillFailing)||_.at.localeCompare(T.at));let v={green:0,yellow:1,unverified:2,red:3},x=new Map;for(let T of t)for(let _ of T.scenarios){let N=Dr(_.feature,r(_)),F=x.get(N)??new Map,I=F.get(_.scenario)??new Map;_.browser?I.delete(""):I.clear(),I.set(_.browser??"",nr(_)?"unverified":_.status),F.set(_.scenario,I),x.set(N,F)}let $=new Map;for(let T of e)for(let _ of T.scenarios){let N=Array.from({length:_.rows},(F,I)=>`${_.name} (example ${I+1})`);$.set(Dr(T.path,_.name),new Set(_.outline===!0?N:_.outline===!1?[_.name]:[_.name,...N]))}let E=new Map;for(let[T,_]of x){let N=$.get(T),F=[..._].filter(([I])=>!N||N.has(I)).flatMap(([,I])=>{let L=[...I],j=L.filter(([H])=>f(H));return(j.length>0?j:L).map(([,H])=>H)});F.length>0&&E.set(T,F.reduce((I,L)=>v[L]>v[I]?L:I))}let R=new Set(E.keys()),k=new Set((l?.scenarios??[]).map(T=>Dr(T.feature,r(T)))),C=[],P=[];for(let[T,_]of n){let N={feature:_.feature,scenario:_.scenario};R.has(T)?l&&!k.has(T)&&P.push(N):C.push(N)}let m=l?(()=>{let T=l.scenarios.length,_=qw(l);return{startedAt:l.startedAt,durationMs:lf(l),ran:T,green:l.green,yellow:l.yellow,red:l.red,unverified:_,passRate:rr(l,l.scenarios),replayRate:Vw(l.scenarios.filter(N=>N.source==="cache"&&N.status==="green").length,T)}})():void 0,A={green:0,yellow:0,unverified:0,red:0,neverRun:0},O=new Map;for(let[T,_]of n){let N=E.get(T)??"neverRun";A[N]++;for(let F of _.tags){let I=O.get(F)??{tag:F,scenarios:0,green:0,yellow:0,unverified:0,red:0,neverRun:0};I.scenarios++,I[N]++,O.set(F,I)}}return{historyRuns:t.length,suite:{features:e.length,scenarios:o.length,tests:o.reduce((T,_)=>T+_.rows,0),recorded:o.filter(T=>T.cacheState===void 0?T.cached:T.cacheState==="valid").length,...A},lastRun:m,trend:c.map(T=>({startedAt:T.startedAt,passRate:rr(T,T.scenarios),durationMs:lf(T),red:T.red,tests:T.green+T.yellow+T.red})),flaky:b,healing:g,recentFailures:y,notInLastRun:P,neverRun:C,slowest:S.slice(0,10),tags:[...O.values()].sort((T,_)=>_.red-T.red||_.scenarios-T.scenarios||T.tag.localeCompare(_.tag))}}import{execFileSync as py}from"node:child_process";import{createHash as gy,randomBytes as wc}from"node:crypto";import se from"node:fs";import ge from"node:path";import hy from"node:zlib";var B=e=>String(e).replaceAll("&","&").replaceAll("<","<").replaceAll(">",">").replaceAll('"',"""),pf="M11 14 L10 4.5 L17.5 9.5 L24 2.5 L30.5 9.5 L38 4.5 L37 14 Z",Jw="M24.085 45.646L24.085 45.646Q20.719 45.646 18.407 44.575Q16.095 43.504 14.905 41.651Q13.715 39.798 13.715 37.384L13.715 37.384L19.121 37.384Q19.121 38.336 19.648 39.152Q20.175 39.968 21.263 40.461Q22.351 40.954 24.085 40.954L24.085 40.954Q25.649 40.954 26.703 40.546Q27.757 40.138 28.301 39.407Q28.845 38.676 28.845 37.724L28.845 37.724Q28.845 36.534 27.825 35.837Q26.805 35.140 24.527 34.936L24.527 34.936L22.657 34.766Q18.951 34.460 16.741 32.454Q14.531 30.448 14.531 27.150L14.531 27.150Q14.531 24.770 15.670 23.036Q16.809 21.302 18.849 20.367Q20.889 19.432 23.677 19.432L23.677 19.432Q26.601 19.432 28.692 20.435Q30.783 21.438 31.905 23.257Q33.027 25.076 33.027 27.524L33.027 27.524L27.587 27.524Q27.587 26.606 27.145 25.841Q26.703 25.076 25.836 24.600Q24.969 24.124 23.677 24.124L23.677 24.124Q22.453 24.124 21.620 24.532Q20.787 24.940 20.379 25.637Q19.971 26.334 19.971 27.150L19.971 27.150Q19.971 28.204 20.719 28.986Q21.467 29.768 23.167 29.904L23.167 29.904L25.071 30.074Q27.791 30.312 29.865 31.247Q31.939 32.182 33.112 33.797Q34.285 35.412 34.285 37.724L34.285 37.724Q34.285 40.104 33.044 41.889Q31.803 43.674 29.525 44.660Q27.247 45.646 24.085 45.646Z";function ir(e){return`<svg viewBox="0 0 48 48" width="${e}" height="${e}" aria-hidden="true">
|
|
60
|
+
<path d="${pf}" fill="#F4A300"/>
|
|
61
|
+
<path d="${Jw}" fill="#E7E9EC"/>
|
|
62
|
+
</svg>`}function Ss(e){return`<svg viewBox="8 1 32 15" height="${e}" aria-hidden="true"><path d="${pf}" fill="#F4A300"/></svg>`}function Ww(e){let t=e.imported;if(!t)return"";let n=t.shards?` \xB7 shard${t.shards.imported.length===1?"":"s"} ${t.shards.imported.join(", ")} of ${t.shards.total}`:"",r=t.headCommit??t.commit,s=`imported from ${t.run?`run ${t.run}`:"another machine"}${t.branch?` \xB7 ${t.branch}`:""}${r?` @ ${r.slice(0,7)}`:""}${n}`;return t.url&&/^https?:\/\//i.test(t.url)?`<a class="chip" href="${B(t.url)}" target="_blank" rel="noopener noreferrer">${B(s)}</a>`:`<span class="chip">${B(s)}</span>`}var $s=`<link rel="preconnect" href="https://fonts.googleapis.com">
|
|
55
63
|
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
|
|
56
|
-
<link href="https://fonts.googleapis.com/css2?family=Bricolage+Grotesque:opsz,wght@12..96,500;12..96,600;12..96,700&family=Geist:wght@400;500;600&family=JetBrains+Mono:wght@400;500;600&display=swap" rel="stylesheet">`,
|
|
64
|
+
<link href="https://fonts.googleapis.com/css2?family=Bricolage+Grotesque:opsz,wght@12..96,500;12..96,600;12..96,700&family=Geist:wght@400;500;600&family=JetBrains+Mono:wght@400;500;600&display=swap" rel="stylesheet">`,ks=` :root {
|
|
57
65
|
--bg: #131416;
|
|
58
66
|
--card: #1A1B1E;
|
|
59
67
|
--card-2: #16171A;
|
|
@@ -163,21 +171,21 @@ ${T}
|
|
|
163
171
|
code { font-family: var(--mono); font-size: 11px; background: var(--bg); border: 1px solid var(--border-2); padding: 1px 6px; border-radius: 4px; color: var(--text-dim); }
|
|
164
172
|
|
|
165
173
|
footer { margin-top: 42px; display: flex; align-items: center; justify-content: center; gap: 8px; color: var(--faint); font-family: var(--mono); font-size: 10.5px; letter-spacing: .08em; }
|
|
166
|
-
`,
|
|
174
|
+
`,Gw={green:"passed",yellow:"pending review",red:"failed"};function Kw(e){return e.hooks?.length?`<div class="panel"><div class="panel-title">setup and teardown</div>${e.hooks.map(n=>{let r=n.exitCode===0,s=r?"ok":n.timedOut?"timed out":n.exitCode===null?"could not start":`exit ${n.exitCode}`;return`<div class="mono">${r?"\u2713":"\u2717"} ${B(String(n.phase))} \xB7 ${B(n.command)} \xB7 ${B(s)} \xB7 ${B(Qe(n.durationMs))}</div>`}).join("")}</div>`:""}function oc(e,t=5){return[...e.scenarios].sort((n,r)=>Number(r.durationMs)-Number(n.durationMs)).slice(0,t)}function ic(e,t=0){let n=Number(e.spanMs??t);return n>0?`${Math.min(100,Math.round(Number(e.busyMs)/n*100))}%`:"\u2013"}function Yw(e){let t=e.timing?.workers??[],n=Number(e.timing?.wallMs??0),r=t.length>1&&n>0?t.map(o=>`<div class="mono">worker ${B(o.worker)} \xB7 ${Number(o.runs)} run${Number(o.runs)===1?"":"s"} \xB7 ${B(Qe(Number(o.busyMs)))} busy \xB7 ${B(ic(o,n))}</div>`).join(""):"",s=e.scenarios.length>1?oc(e).map(o=>`<div class="mono">${B(Qe(Number(o.durationMs)))} \xB7 ${B(o.feature)} \u203A ${B(o.scenario)}${e.browsers&&o.browser?` \xB7 ${B(o.browser)}`:""}${o.worker&&t.length>1?` \xB7 worker ${B(o.worker)}`:""}</div>`).join(""):"";return!r&&!s?"":`<div class="panel"><div class="panel-title">timing${n>0?` \xB7 ${B(Qe(n))} from the first scenario to the last`:""}</div>${r}${r&&s?'<div class="panel-hint">slowest scenarios</div>':""}${s}</div>`}function Qe(e){return e>=1e3?`${(e/1e3).toFixed(1)}s`:`${e}ms`}function xs(e){return e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e4?`${(e/1e3).toFixed(1)}k`:Number(e).toLocaleString()}function ve(e,t,n,r="",s="",o=""){return`<div class="kpi">
|
|
167
175
|
<div class="kpi-label">${e}</div>
|
|
168
176
|
<div class="kpi-value ${r}">${t}</div>
|
|
169
177
|
<div class="kpi-sub ${s}">${n}</div>${o}
|
|
170
|
-
</div>`}function
|
|
171
|
-
${
|
|
172
|
-
${
|
|
173
|
-
${
|
|
174
|
-
${
|
|
175
|
-
${
|
|
176
|
-
${
|
|
177
|
-
${n.plan?
|
|
178
|
-
</section>`}function
|
|
179
|
-
`)}</section>`:""}function
|
|
180
|
-
${
|
|
178
|
+
</div>`}function Fr(e,t){let n=e.filter(l=>l!==null);if(n.length<2)return"";let r=108,s=22,o=Math.min(...n),i=Math.max(...n)-o||1,c=e.map((l,d)=>{if(l===null)return"";let f=`${(d/(e.length-1)*r).toFixed(1)},${(s-2-(l-o)/i*(s-4)).toFixed(1)}`;return d===0||e[d-1]===null?`M${f}h0`:`L${f}`}).join("");return`<svg class="spark" viewBox="0 0 ${r} ${s}" width="${r}" height="${s}" aria-hidden="true"><path d="${c}" fill="none" stroke="${t}" stroke-width="1.8" stroke-linejoin="round" stroke-linecap="round"/></svg>`}var ff=(e,t="",n=0)=>`${e>=0?"+":"\u2212"}${Math.abs(e).toFixed(n)}${t} vs prev`;function Zw(e){let t=e.filter(r=>r.status==="yellow");return t.length===0?"nothing to review":`\u25B2 ${[[t.filter(r=>r.verified===!0).length,"proof passed"],[t.filter(r=>r.verified===!1).length,"proof failed"],[t.filter(r=>r.verified===void 0).length,"not proved"]].filter(([r])=>r>0).map(([r,s])=>`${r} ${s}`).join(" \xB7 ")}`}function Qw(e,t){let n=e.totals,r=e.trends,[s,o,a,i]=[n.scenarios,n.green,n.yellow,n.red].map(Number),c=Qa({green:o,yellow:a},e.scenarios),l=s===0?0:Math.round(c/s*100),d=n.red>0?"red":n.yellow>0?"gold":"green",f=n.inputTokens+n.outputTokens,p=r?.prev?`${ff(r.prev.passRatePp,"pp")} \xB7 ${c} of ${s}`:`${c} of ${s} scenarios`,u=r?.prev?.costUsd!==void 0?`${ff(r.prev.costUsd,"",4).replace("+","+$").replace("\u2212","\u2212$")} \xB7 ${Qe(t)}`:`${Qe(t)} total runtime`;return`<section class="kpis">
|
|
179
|
+
${ve("pass rate",`${l}<span class="unit">%</span>`,p,d,r?.prev?r.prev.passRatePp>=0?"green":"red":"",Fr(r?.series.passRate??[],"var(--green)"))}
|
|
180
|
+
${ve("passed",String(o),"deterministic replay","green",o>0?"green":"")}
|
|
181
|
+
${ve("pending",String(a),Zw(e.scenarios),a>0?"gold":"",a>0?"gold":"")}
|
|
182
|
+
${ve("failed",String(i),i>0?"\u25BC needs attention":"all clear",i>0?"red":"",i>0?"red":"green")}
|
|
183
|
+
${ve("ai calls",String(Number(n.aiCalls)),`${xs(f)} in+out tokens`,n.aiCalls>0?"":"green")}
|
|
184
|
+
${ve("cache traffic",xs(n.cacheReadTokens+n.cacheCreationTokens),n.cacheReadTokens+n.cacheCreationTokens>0?`${xs(n.cacheReadTokens)} read \xB7 ${xs(n.cacheCreationTokens)} written`:"zero (fully cached run)","",n.cacheReadTokens+n.cacheCreationTokens>0?"":"green")}
|
|
185
|
+
${n.plan?ve("plan usage",`${Ka(n.plan.fiveHourBefore,n.plan.fiveHourAfter)}`,[`5-hour window \xB7 ${B(n.plan.subscriptionType)} plan`,nf(n.plan.resetsAt)].filter(Boolean).join(" \xB7 "),"gold","")+ve("api-equivalent",`<span class="unit">\u2248 $</span>${n.costUsd.toFixed(n.costUsd>=1?2:4)}`,`what this run costs on an API key \xB7 ${u}`,"","",Fr(r?.series.costUsd??[],"var(--gold)")):ve("ai cost",kt(n)?`<span class="unit">$</span>${n.costUsd.toFixed(n.costUsd>=1?2:4)}`:"n/a",kt(n)?u:"not reported by the provider","","",kt(n)?Fr(r?.series.costUsd??[],"var(--gold)"):"")}
|
|
186
|
+
</section>`}function Xw(e){let t=e.trends;if(!t)return"";let n=[];return t.chronic.length>0&&n.push(`<div class="panel accent-gold"><div class="panel-title gold">chronic scenarios: stop paying for heals</div><ul>${t.chronic.map(r=>`<li>${B(r.feature)} \u203A ${B(r.scenario)}: ${Number(r.heals)} heal(s), ${Number(r.reds)} red(s) in the last ${Number(r.runs)} run(s). Re-record it or fix the feature text.</li>`).join("")}</ul></div>`),t.divergentSteps>0&&n.push(`<div class="panel"><div class="panel-title">step divergence (level-2 signal)</div><p>${Number(t.divergentSteps)} step text(s) currently have divergent recordings across caches.</p></div>`),t.topIssues.length>0&&n.push(`<div class="panel accent-red"><div class="panel-title red">recurring failure themes (last 20 runs)</div><ul>${t.topIssues.map(r=>`<li>${Number(r.count)}\xD7: ${B(r.message)}</li>`).join("")}</ul></div>`),n.length>0?`<section class="trends">${n.join(`
|
|
187
|
+
`)}</section>`:""}function ey(e){let t=Array.isArray(e.sessions)?e.sessions:[];return`<ol class="steps">${e.steps.map((r,s)=>{let o=typeof t[s]=="string"&&(s===0||t[s]!==t[s-1])?t[s]:void 0,a=r.status==="passed"?'<span class="dot green"></span>':r.status==="failed"?'<span class="dot red"></span>':'<span class="dot idle"></span>';return`<li class="step ${B(r.status)}">
|
|
188
|
+
${a}
|
|
181
189
|
<div class="step-body">
|
|
182
190
|
<span class="step-text">${B(r.gherkin)}</span>
|
|
183
191
|
${o?`<span class="tag indigo" title="the browser session this step and the ones after it run in, each a browser of its own">session: ${B(o)}</span>`:""}
|
|
@@ -188,53 +196,54 @@ ${T}
|
|
|
188
196
|
${r.error?`<div class="step-error">${B(r.error)}</div>`:""}
|
|
189
197
|
</div>
|
|
190
198
|
</li>`}).join(`
|
|
191
|
-
`)}</ol>`}function
|
|
199
|
+
`)}</ol>`}function ty(e){return e.featureEdits&&e.featureEdits.length>0?`<div class="panel">
|
|
192
200
|
<div class="panel-title gold">suggested .feature edit</div>
|
|
193
201
|
<div class="diff">${e.featureEdits.map(n=>{let r=e.steps[n.index]?.gherkin??`step ${n.index}`;return`<div class="diff-line del">\u2212 ${B(r)}</div><div class="diff-line add">+ ${B(n.text)}</div>`}).join("")}</div>
|
|
194
202
|
<div class="panel-hint">apply with <code>saffron accept --with-feature-edit</code></div>
|
|
195
|
-
</div>`:e.suggestedFeatureEdit?`<div class="panel"><div class="panel-title gold">suggested .feature edit</div><pre>${B(e.suggestedFeatureEdit)}</pre></div>`:""}function
|
|
203
|
+
</div>`:e.suggestedFeatureEdit?`<div class="panel"><div class="panel-title gold">suggested .feature edit</div><pre>${B(e.suggestedFeatureEdit)}</pre></div>`:""}function ny(e){let t=e.proposalDiff;if(!t)return"";let n=t.steps.filter(l=>l.change!=="same"||!t.hasCommitted).map(l=>{let d=`<div class="diff-step">${l.kind==="assertion"?'<span class="pill gold">assertion</span> ':""}${B(l.gherkin)}${l.fromStepSet?` <span class="mono">(step set "${B(l.fromStepSet)}")</span>`:""}</div>`,f=l.actions.flatMap(p=>p.change==="same"?[`<div class="diff-line"> ${B(p.before??"")}</div>`]:p.change==="added"?[`<div class="diff-line add">+ ${B(p.after??"")}</div>`]:p.change==="removed"?[`<div class="diff-line del">\u2212 ${B(p.before??"")}</div>`]:[`<div class="diff-line del">\u2212 ${B(p.before??"")}</div>`,`<div class="diff-line add">+ ${B(p.after??"")}</div>`,...(p.details??[]).map(u=>`<div class="diff-line detail">${B(u)}</div>`)]).join("");return`${d}<div class="diff">${f}</div>`}).join(""),{added:r,removed:s,changed:o,assertions:a}=t.summary,i=t.recording?.length?`<div class="diff">${t.recording.map(l=>`<div class="diff-line del">! ${B(l)}</div>`).join("")}</div>`:"",c=r+s+o===0?t.recording?.length?"No action changed, but the recording did: read the lines above first.":"No action changed.":`${o} changed, ${r} added, ${s} removed.${a>0?` ${a} touch the scenario's verdict.`:""}`;return`<div class="panel accent-gold"><div class="panel-title gold">what this proposal changes</div>${t.hasCommitted?"":'<p class="panel-hint">First recording: there is nothing to compare against.</p>'}${n}${i}<div class="panel-hint">${B(c)}</div></div>`}function ry(e,t){let n=e.usage.inputTokens+e.usage.outputTokens;if(e.usage.aiCalls===0)return'<span class="pill green">0 tokens</span>';let r=tf(e.usage.costUsd,t),s=r?` \xB7 ${r}`:"";return`<span class="pill gold">${Number(e.usage.aiCalls)} ai \xB7 ${xs(n)} tok${s}</span>`}function sy(e,t,n,r=!1,s){let o=e.ranAt!==void 0&&s!==void 0&&Date.parse(e.ranAt)<Date.parse(s);return`<details class="card" ${e.status!=="green"?"open":""}>
|
|
196
204
|
<summary>
|
|
197
|
-
<span class="pill ${e.status==="green"?"green":e.status==="yellow"?"gold":"red"}">${
|
|
205
|
+
<span class="pill ${e.status==="green"?"green":e.status==="yellow"?"gold":"red"}">${Gw[e.status]}</span>
|
|
198
206
|
<span class="card-title">${B(e.scenario)}</span>
|
|
199
207
|
<span class="card-meta">
|
|
200
208
|
<span class="m">${B(e.feature)}</span>
|
|
201
209
|
<span class="m-sep">\xB7</span>
|
|
202
210
|
<span class="m">${B(e.source)}</span>
|
|
203
211
|
<span class="m-sep">\xB7</span>
|
|
204
|
-
<span class="m">${
|
|
212
|
+
<span class="m">${Qe(Number(e.durationMs))}</span>
|
|
205
213
|
${r&&e.browser?`<span class="m-sep">\xB7</span><span class="chip">${B(e.browser)}</span>`:""}
|
|
206
|
-
${
|
|
214
|
+
${o?`<span class="m-sep">\xB7</span><span class="chip" title="Kept from an earlier run: this run did not run this scenario">from the run of ${B(new Date(e.ranAt).toISOString().replace("T"," ").slice(0,16))} UTC</span>`:""}
|
|
215
|
+
${ry(e,t)}
|
|
207
216
|
</span>
|
|
208
217
|
</summary>
|
|
209
218
|
<div class="card-body">
|
|
210
|
-
${
|
|
219
|
+
${ey(e)}
|
|
211
220
|
${e.narrative?`<div class="panel"><div class="panel-title">agent narrative</div><p>${B(e.narrative)}</p></div>`:""}
|
|
212
|
-
${e.adaptations.length>0?`<div class="panel accent-gold"><div class="panel-title gold">adaptations</div><ul>${e.adaptations.map(
|
|
213
|
-
${
|
|
214
|
-
${
|
|
221
|
+
${e.adaptations.length>0?`<div class="panel accent-gold"><div class="panel-title gold">adaptations</div><ul>${e.adaptations.map(a=>`<li>${B(a)}</li>`).join("")}</ul></div>`:""}
|
|
222
|
+
${ty(e)}
|
|
223
|
+
${ny(e)}
|
|
215
224
|
${e.proposalFile?`<div class="panel"><div class="panel-title">cache proposal pending${e.verified===!0?' <span class="pill green">verified</span>':e.verified===!1?' <span class="pill red">unverified</span>':""}</div><p class="mono">${B(e.proposalFile)}</p>${e.verified===!1&&e.proofError?`<p class="mono" style="color:var(--red)">proof replay failed: ${B(e.proofError.split(`
|
|
216
225
|
`)[0])}</p>`:""}<div class="panel-hint">review with <code>saffron accept</code> / <code>saffron reject</code></div></div>`:""}
|
|
217
226
|
${e.error&&e.status==="red"?`<div class="panel accent-red"><div class="panel-title red">failure</div><p>${B(e.error)}</p></div>`:""}
|
|
218
|
-
${e.uniques&&e.status!=="green"?`<div class="panel"><div class="panel-title">unique values in this run</div>${Object.entries(e.uniques).map(([
|
|
219
|
-
${e.proofUniques&&e.status!=="green"?`<div class="panel"><div class="panel-title">unique values in the proof replay</div>${Object.entries(e.proofUniques).map(([
|
|
220
|
-
${
|
|
227
|
+
${e.uniques&&e.status!=="green"?`<div class="panel"><div class="panel-title">unique values in this run</div>${Object.entries(e.uniques).map(([a,i])=>`<div class="mono">${B(a)} = ${B(i)}</div>`).join("")}</div>`:""}
|
|
228
|
+
${e.proofUniques&&e.status!=="green"?`<div class="panel"><div class="panel-title">unique values in the proof replay</div>${Object.entries(e.proofUniques).map(([a,i])=>`<div class="mono">${B(a)} = ${B(i)}</div>`).join("")}</div>`:""}
|
|
229
|
+
${oy(e,n,r)}
|
|
221
230
|
</div>
|
|
222
|
-
</details>`}function
|
|
231
|
+
</details>`}function oy(e,t,n=!1){let r=(e.evidence??[]).filter(i=>i.kind==="trace"),o=r[0]?`<div class="panel accent-gold"><div class="panel-title gold">execution replay</div><div>Step through this run with the page inspectable at every action:</div><div class="mono" style="margin-top:6px">npx saffron trace ${B(iy(`${e.feature}:${e.scenario}${n&&e.browser?`@${e.browser}`:""}`))}</div><div class="panel-hint">${r.map(i=>B(i.file)).join(" \xB7 ")}</div></div>`:"",a=(e.evidence??[]).flatMap(i=>{if(!t||i.kind!=="failure"&&i.kind!=="before-heal")return[];let c=Pn(t,i);if(!c)return[];try{let l=c.toString("base64"),d=i.kind==="failure"?"the page when it failed":"the page when the cached step stopped working, before the agent took over";return[`<figure class="shot"><figcaption>${B(d)}${i.step?`: <span class="mono">${B(i.step)}</span>`:""}</figcaption><a href="data:image/jpeg;base64,${l}" target="_blank" rel="noopener"><img alt="${B(d)}" src="data:image/jpeg;base64,${l}"/></a><div class="panel-hint">${B(i.file)}</div></figure>`]}catch{return[]}});return a.length===0?o:`<div class="panel ${e.status==="red"?"accent-red":"accent-gold"}"><div class="panel-title ${e.status==="red"?"red":"gold"}">screenshot</div>${a.join("")}</div>${o}`}var iy=e=>/[^A-Za-z0-9_./:-]/.test(e)?`'${e.replace(/'/g,"'\\''")}'`:e;function Ln(e,t){let n=e.totals,r=new Date(e.startedAt),s=new Date(e.finishedAt).getTime()-r.getTime(),o=r.toLocaleString("en-GB",{day:"2-digit",month:"short",year:"numeric",hour:"2-digit",minute:"2-digit"});return`<!doctype html>
|
|
223
232
|
<html lang="en">
|
|
224
233
|
<head>
|
|
225
234
|
<meta charset="utf-8"/>
|
|
226
235
|
<meta name="viewport" content="width=device-width, initial-scale=1"/>
|
|
227
236
|
<title>Saffron run report</title>
|
|
228
|
-
${
|
|
237
|
+
${$s}
|
|
229
238
|
<style>
|
|
230
|
-
${
|
|
239
|
+
${ks}</style>
|
|
231
240
|
</head>
|
|
232
241
|
<body>
|
|
233
242
|
<div class="topline"></div>
|
|
234
243
|
<div class="wrap">
|
|
235
244
|
<header class="top">
|
|
236
245
|
<div class="brand">
|
|
237
|
-
${
|
|
246
|
+
${ir(38)}
|
|
238
247
|
<div>
|
|
239
248
|
<div class="brand-name">saffron</div>
|
|
240
249
|
<div class="brand-sub">test run report</div>
|
|
@@ -243,143 +252,157 @@ ${Qr}</style>
|
|
|
243
252
|
<div class="run-meta">
|
|
244
253
|
<span>${B(o)}</span>
|
|
245
254
|
<span>\xB7</span>
|
|
246
|
-
<span>${
|
|
255
|
+
<span>${Qe(s)}</span>
|
|
247
256
|
${e.baseURL?`<span class="chip base">${B(e.baseURL)}</span>`:""}
|
|
248
257
|
${e.shards?`<span class="chip">merged from ${Number(e.shards)} shards</span>`:""}
|
|
249
|
-
${e.browsers?.length?`<span class="chip">${e.browsers.map(
|
|
250
|
-
${
|
|
258
|
+
${e.browsers?.length?`<span class="chip">${e.browsers.map(a=>B(a)).join(" \xB7 ")}</span>`:""}
|
|
259
|
+
${Ww(e)}
|
|
260
|
+
${e.provenance?`<span class="chip">${B(Ho(e.provenance))}</span>`:""}
|
|
261
|
+
${e.interrupted?`<span class="pill red" title="Ctrl-C stopped the run: the scenarios that did not run are not counted, as failed or otherwise">interrupted \xB7 ${Number(e.notRun)} not run</span>`:""}
|
|
251
262
|
</div>
|
|
252
263
|
</header>
|
|
253
264
|
|
|
254
|
-
${
|
|
255
|
-
${
|
|
256
|
-
${
|
|
257
|
-
${
|
|
265
|
+
${Qw(e,s)}
|
|
266
|
+
${Xw(e)}
|
|
267
|
+
${Kw(e)}
|
|
268
|
+
${Yw(e)}
|
|
258
269
|
|
|
259
270
|
<div class="section-head">
|
|
260
271
|
<span class="section-title">scenarios \xB7 ${Number(n.scenarios)}</span>
|
|
261
272
|
<span class="section-title">saffron v${B(e.version)}</span>
|
|
262
273
|
</div>
|
|
263
|
-
${e.scenarios.map(
|
|
274
|
+
${e.scenarios.map(a=>sy(a,!!e.totals.plan,t,!!e.browsers,e.startedAt)).join(`
|
|
264
275
|
`)}
|
|
265
276
|
|
|
266
|
-
<footer>${
|
|
277
|
+
<footer>${Ss(11)} generated by saffron v${B(e.version)} \xB7 ${B(new Date(e.finishedAt).toLocaleString("en-GB",{dateStyle:"medium",timeStyle:"medium"}))}</footer>
|
|
267
278
|
</div>
|
|
268
279
|
</body>
|
|
269
280
|
</html>
|
|
270
|
-
`}import
|
|
271
|
-
`),
|
|
272
|
-
${d.name}`;o.set(
|
|
273
|
-
`)).digest("hex").slice(0,12);return{scenarios:c.map(d=>e[d]),info:{index:t.index,total:t.total,by:n,suite:l,suiteSize:e.length,positions:c}}}function
|
|
274
|
-
`),r}var
|
|
275
|
-
`));let
|
|
276
|
-
`)??[]).map(r=>r.split(/\s+/)[1]).filter(Boolean);return[...new Set(n.map(
|
|
281
|
+
`}import Vo from"node:fs";import Jo from"node:path";function Wo(e){let t={scenarios:e.length,green:0,yellow:0,red:0,aiCalls:0,inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheCreationTokens:0,costUsd:0},n=new Set;for(let r of e){for(let s of r.usage.models??[])n.add(s);t[r.status]+=1,t.aiCalls+=r.usage.aiCalls,t.inputTokens+=r.usage.inputTokens,t.outputTokens+=r.usage.outputTokens,t.cacheReadTokens+=r.usage.cacheReadTokens,t.cacheCreationTokens+=r.usage.cacheCreationTokens??0,t.costUsd+=r.usage.costUsd??0}return n.size>0&&(t.models=[...n].sort()),t}function cc(e,t,n){return{tool:"saffron",version:ot(),startedAt:t.toISOString(),finishedAt:new Date().toISOString(),baseURL:n,totals:Wo(e),scenarios:e.map(r=>({feature:r.scenario.featurePath,scenario:r.scenario.displayName,name:r.scenario.name,tags:[...r.scenario.tags],status:r.status,source:r.source,proposalReplay:r.proposalReplay,durationMs:r.durationMs,usage:r.usage,steps:r.stepResults,sessions:An(r.scenario.steps)?r.scenario.steps.map(s=>dt(pe(s.session))):void 0,narrative:r.narrative,adaptations:r.adaptations,suggestedFeatureEdit:r.suggestedFeatureEdit,featureEdits:r.featureEdits,verified:r.verified,proofError:r.proofError,proposalFile:r.proposalFile,proposalRevision:r.proposalRevision,proposalDiff:r.proposalDiff,error:r.error,evidence:r.evidence,uniques:r.uniques,proofUniques:r.proofUniques,worker:r.worker,browser:r.browser,ranAt:t.toISOString()}))}}var Rt=e=>!!e&&typeof e=="object"&&!Array.isArray(e),qo=(e,t)=>t.find(n=>typeof e[n]!="number"),Rs=e=>e===void 0||typeof e=="number",ay=["scenarios","green","yellow","red","aiCalls","inputTokens","outputTokens","cacheReadTokens","costUsd"],cy=["aiCalls","inputTokens","outputTokens","cacheReadTokens"],ac=e=>typeof e=="string"&&/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(\.\d+)?(Z|[+-]\d\d:\d\d)$/.test(e)&&!Number.isNaN(Date.parse(e));function lc(e){if(!Rt(e)||e.tool!=="saffron")return"is not a Saffron run report";if(!ac(e.startedAt)||!ac(e.finishedAt))return"has no start or finish time";if(!Rt(e.totals))return"has no totals";let t=qo(e.totals,ay);if(t)return`has totals.${t} that is not a number`;if(!Array.isArray(e.scenarios))return"has no list of scenarios";for(let[i,c]of e.scenarios.entries()){let l=`scenarios[${i}]`;if(!Rt(c)||typeof c.feature!="string"||typeof c.scenario!="string")return`has ${l} without a feature and scenario name`;if(!["green","yellow","red"].includes(c.status))return`has ${l}.status ${JSON.stringify(c.status)}, which this saffron-ai does not know`;if(!Rt(c.usage)||qo(c.usage,cy))return`has ${l}.usage without its token counts`;if(!Array.isArray(c.steps))return`has ${l}.steps that is not a list`;let d=c.steps.findIndex(p=>!Rt(p)||typeof p.gherkin!="string"||typeof p.kind!="string"||typeof p.status!="string");if(d>=0)return`has ${l}.steps[${d}] without its gherkin, kind and status`;for(let[p,u]of c.steps.entries()){if(!["passed","failed","skipped"].includes(u.status))return`has ${l}.steps[${p}].status ${JSON.stringify(u.status)}, which this saffron-ai does not know`;let h=["retries","failedActionIndex"].find(b=>!Rs(u[b]));if(h)return`has ${l}.steps[${p}].${h} that is not a number`}let f=["browser","worker"].find(p=>c[p]!==void 0&&typeof c[p]!="string");if(f)return`has ${l}.${f} that is not text`;if(c.ranAt!==void 0&&!ac(c.ranAt))return`has ${l}.ranAt that is not a time`;if(c.evidence!==void 0&&!(Array.isArray(c.evidence)&&c.evidence.every(p=>Rt(p)&&typeof p.file=="string"&&typeof p.kind=="string")))return`has ${l}.evidence that is not a list of files`}if(!Rs(e.notRun)||e.interrupted!==void 0&&(e.interrupted!==!0||typeof e.notRun!="number"))return"has interrupted without a count of the scenarios that did not run";let n=e.provenance,r=i=>i===void 0||Rt(i)&&typeof i.name=="string"&&typeof i.source=="string";if(n!==void 0&&!(Rt(n)&&(n.provider===void 0||typeof n.provider=="string")&&r(n.model)&&r(n.healModel)&&(n.sdk===void 0||Rt(n.sdk)&&typeof n.sdk.name=="string"&&typeof n.sdk.version=="string")))return"has provenance whose names are not text";if(e.browsers!==void 0&&!(Array.isArray(e.browsers)&&e.browsers.every(i=>typeof i=="string")))return"has browsers that is not a list of names";let s=e.timing;if(s!==void 0&&!(Rt(s)&&typeof s.wallMs=="number"&&Array.isArray(s.workers)&&s.workers.every(i=>Rt(i)&&typeof i.worker=="string"&&!qo(i,["runs","busyMs"])&&Rs(i.spanMs))))return"has timing whose workers are not a list of named counts";let o=e.trends,a=(i,c)=>Array.isArray(i)&&i.every(l=>Rt(l)&&!qo(l,c));if(o!==void 0&&!(Rt(o)&&Rs(o.divergentSteps)&&a(o.chronic,["heals","reds","runs"])&&a(o.topIssues,["count"])&&(o.prev===void 0||a([o.prev],["passRatePp","aiCalls","red"])&&Rs(o.prev.costUsd))))return"has trends whose counts are not numbers"}var dc=e=>lc(e)===void 0;function uc(e){try{let t=JSON.parse(Vo.readFileSync(Jo.join(e,".saffron","reports","latest.json"),"utf8"));return dc(t)?t:void 0}catch{return}}function fc(e,t){if(!e||e.imported||e.interrupted||e.baseURL!==t.baseURL)return t;let n=new Set,r=e.scenarios.flatMap(b=>{let g=t.scenarios.find(S=>of(b,S));return g?n.has(g)?[]:(n.add(g),[g]):[{...b,ranAt:b.ranAt??e.startedAt}]}),s=r.filter(b=>!n.has(b)),o=t.totals.aiCalls>0;if(o&&s.some(b=>b.usage.aiCalls>0)&&!t.totals.plan!=!e.totals.plan)return t;r.push(...t.scenarios.filter(b=>!n.has(b)));let a=[...new Set(r.flatMap(b=>b.browser?[b.browser]:[]))],{trends:i,shards:c,hooks:l,timing:d,browsers:f,provenance:p,...u}=e,h=o?t.totals.plan:e.totals.plan;return{...u,version:t.version,startedAt:t.startedAt,finishedAt:t.finishedAt,totals:{...Wo(r),...h?{plan:h}:{}},scenarios:r,...t.interrupted?{interrupted:!0,notRun:t.notRun}:{},...t.provenance?{provenance:t.provenance}:{},...t.shards?{shards:t.shards}:{},...t.hooks?{hooks:t.hooks}:{},...t.timing?{timing:t.timing}:{},...a.length>1?{browsers:a}:{}}}function Ts(e,t){let n=Jo.join(e,".saffron","reports");Vo.mkdirSync(n,{recursive:!0});let r=Jo.join(n,"latest.json"),s=Jo.join(n,"latest.html"),o=Ln(t,e);return Vo.writeFileSync(r,`${JSON.stringify(t,null,2)}
|
|
282
|
+
`),Vo.writeFileSync(s,o),{json:r,html:s}}import ly from"node:crypto";import As from"node:fs";import Go from"node:path";var gf=["scenario","file"];function mf(e){let t=/^\s*(\d+)\s*\/\s*(\d+)\s*$/.exec(e),n=t?Number(t[1]):NaN,r=t?Number(t[2]):NaN;if(!t||r<1||n<1||n>r)throw new Error(`invalid --shard "${e}": use <index>/<total>, e.g. --shard 2/4 (index from 1 to total)`);return{index:n,total:r}}function wf(e){if(!gf.includes(e))throw new Error(`invalid --shard-by "${e}": use ${gf.map(t=>`"${t}"`).join(" or ")}`);return e}function pc(e){return`shard-${e.index}-of-${e.total}`}var dy=e=>`${e.featurePath}${e.displayName}`;function yf(e,t){let n=t.by??"scenario",r=e.map(dy),s=new Set,o=new Map;e.forEach((d,f)=>{let p=n==="file"?d.featurePath:`${d.featurePath}
|
|
283
|
+
${d.name}`;o.set(p,[...o.get(p)??[],f])});let a=new Array(t.total).fill(0),i=[...o].sort((d,f)=>f[1].length-d[1].length||(d[0]<f[0]?-1:d[0]>f[0]?1:0));for(let[,d]of i){let f=a.indexOf(Math.min(...a));if(a[f]+=d.length,f===t.index-1)for(let p of d)s.add(p)}let c=e.map((d,f)=>f).filter(d=>s.has(d)),l=ly.createHash("sha256").update([...r].sort().join(`
|
|
284
|
+
`)).digest("hex").slice(0,12);return{scenarios:c.map(d=>e[d]),info:{index:t.index,total:t.total,by:n,suite:l,suiteSize:e.length,positions:c}}}function Ko(e=process.env){return e.SAFFRON_RUN_ID||e.GITHUB_RUN_ID&&`github:${e.GITHUB_RUN_ID}`||e.CI_PIPELINE_ID&&`gitlab:${e.CI_PIPELINE_ID}`||e.BUILD_BUILDID&&`azure:${e.BUILD_BUILDID}`||e.CIRCLE_WORKFLOW_ID&&`circleci:${e.CIRCLE_WORKFLOW_ID}`||void 0}var Yo=(e=process.env)=>e.GITHUB_RUN_ATTEMPT||e.SYSTEM_JOBATTEMPT||void 0;function gc(e,t){let n=Go.join(e,".saffron","reports");As.mkdirSync(n,{recursive:!0});let r=Go.join(n,`${pc(t.shard)}.json`);return As.writeFileSync(r,`${JSON.stringify(t,null,2)}
|
|
285
|
+
`),r}var hf=e=>typeof e=="number"&&Number.isFinite(e),Lr=(e,t)=>e===void 0||t(e),ar=e=>typeof e=="string",uy=e=>{let t=e;return!!t&&typeof t=="object"&&ar(t.feature)&&ar(t.scenario)&&Lr(t.name,ar)&&Lr(t.tags,n=>Array.isArray(n)&&n.every(ar))&&["green","yellow","red"].includes(t.status)&&ar(t.source)&&[t.durationMs,t.adaptations,t.driftSteps,t.aiCalls,t.tokensInOut,t.cacheRead,t.cacheWrite,t.costUsd].every(hf)&&Lr(t.verified,n=>typeof n=="boolean")&&Lr(t.seededSteps,hf)&&Lr(t.error,ar)&&Lr(t.browser,ar)},Es=e=>{let t=e;return!!t&&t.tool==="saffron"&&!!t.shard&&typeof t.shard.index=="number"&&typeof t.shard.total=="number"&&Array.isArray(t.shard.positions)&&(t.shard.browser===void 0||typeof t.shard.browser=="string")&&Array.isArray(t.scenarios)&&!!t.history&&Array.isArray(t.history.scenarios)&&t.history.scenarios.every(uy)},fy=/^shard-\d+-of-\d+\.json$/;function bf(e){let t=[],n=(r,s)=>{let o=As.statSync(r,{throwIfNoEntry:!1});if(!o)throw new Error(`not found: ${r}`);if(o.isDirectory())for(let a of As.readdirSync(r).sort())n(Go.join(r,a),!1);else(s||fy.test(Go.basename(r)))&&t.push(r)};for(let r of e)n(r,!0);return t.map(r=>{let s;try{s=JSON.parse(As.readFileSync(r,"utf8"))}catch(o){throw new Error(`cannot read shard report ${r}: ${o instanceof Error?o.message:String(o)}`)}if(!Es(s))throw new Error(`${r} is not a shard report (written by saffron run --shard)`);return{file:r,report:s}})}var cr=class extends Error{};function Zo(e,t={}){if(e.length===0)throw new cr("no shard reports found. Shards write .saffron/reports/shard-<i>-of-<n>.json");let n=m=>Number(m.report.shard.attempt)||0,r=m=>{let{ciRun:A,index:O,total:T,suite:_,suiteSize:N,by:F,browser:I}=m.report.shard;return JSON.stringify([A??"",O,T,_,N,F??"scenario",m.report.baseURL??"",I??""])},s=new Map;for(let m of e)s.set(r(m),Math.max(s.get(r(m))??0,n(m)));let o=e.filter(m=>n(m)<s.get(r(m)));e=e.filter(m=>!o.includes(m));let a=e[0].report.shard,i=[],c=m=>m.map(A=>A.file).join(", "),l=new Set(e.map(m=>m.report.shard.total));l.size>1&&i.push(`shards disagree on the shard count (${[...l].sort().join(", ")}): ${c(e)}`),new Set(e.map(m=>`${m.report.shard.suite}/${m.report.shard.suiteSize}`)).size>1&&i.push("shards ran different suites (different scenarios or filters). Every shard must run the same paths and --filter");let f=new Set(e.map(m=>m.report.shard.by??"scenario"));f.size>1&&i.push(`shards split the suite in different ways (--shard-by ${[...f].sort().join(" and ")}): every shard must use the same`);let p=new Set(e.map(m=>m.report.shard.ciRun??""));p.size>1&&i.push(`shards come from different CI runs (${[...p].map(m=>m||"none recorded").join(", ")})`);let u=[...new Set(e.map(m=>m.report.baseURL??"(no base URL)"))];u.length>1&&i.push(`the shards ran against different base URLs: ${u.join(", ")}. Merge the shards of one environment at a time`);let h=[...new Set(e.map(m=>m.report.shard.browser??"(no browser recorded)"))];h.length>1&&i.push(`the shards ran in different browsers: ${h.join(", ")}. Merge the shards of one browser at a time`);let b=new Map;for(let m of e)b.set(m.report.shard.index,[...b.get(m.report.shard.index)??[],m]);for(let[m,A]of[...b].sort((O,T)=>O[0]-T[0]))A.length>1&&i.push(`shard ${m}/${a.total} appears ${A.length} times: ${c(A)}`);if(l.size===1&&!t.partial){let m=Array.from({length:a.total},(A,O)=>O+1).filter(A=>!b.has(A));m.length>0&&i.push(`missing ${m.length===1?"shard":"shards"} ${m.map(A=>`${A}/${a.total}`).join(", ")}. A merge without ${m.length===1?"it":"them"} would under-count the run`)}if(!t.partial)for(let m of e)m.report.interrupted&&i.push(`${m.file} is from a run that was interrupted (${Number(m.report.notRun)} scenario(s) did not run). Run shard ${m.report.shard.index}/${m.report.shard.total} again`);if(i.length===0){let m=new Set,A=0;for(let O of e){let{positions:T}=O.report.shard;(T.length!==O.report.scenarios.length||T.length!==O.report.history.scenarios.length)&&i.push(`${O.file} is inconsistent: ${T.length} positions for ${O.report.scenarios.length} scenarios`);for(let _ of T)m.has(_)&&i.push(`two shards both ran scenario ${_+1} of the suite`),m.add(_);A+=T.length}i.length===0&&!t.partial&&A!==a.suiteSize&&i.push(`the shards hold ${A} scenarios but the suite has ${a.suiteSize}`)}if(i.length>0)throw new cr(i.join(`
|
|
286
|
+
`));let g=e.sort((m,A)=>m.report.shard.index-A.report.shard.index).flatMap(({report:m})=>m.shard.positions.map((A,O)=>({position:A,scenario:m.scenarios[O].worker?{...m.scenarios[O],worker:`${m.shard.index}/${m.shard.total} \xB7 ${m.scenarios[O].worker}`}:m.scenarios[O],history:m.history.scenarios[O]}))).sort((m,A)=>m.position-A.position),S=e.map(m=>m.report),y=S.map(m=>m.startedAt).sort()[0],w=S.map(m=>m.finishedAt).sort().at(-1),v=g.map(m=>m.scenario),x=S.flatMap(m=>m.hooks??[]),$={tool:"saffron",version:S[0].version,startedAt:y,finishedAt:w,baseURL:S.find(m=>m.baseURL)?.baseURL,totals:Wo(v),scenarios:v,shards:e.length};x.length>0&&($.hooks=x);let E=S.reduce((m,A)=>m+(A.interrupted?Number(A.notRun):0),0);S.some(m=>m.interrupted)&&Object.assign($,{interrupted:!0,notRun:E}),S[0].provenance&&new Set(S.map(m=>JSON.stringify(m.provenance??null))).size===1&&($.provenance=S[0].provenance);let R=e.filter(m=>m.report.timing).sort((m,A)=>m.report.shard.index-A.report.shard.index);R.length>0&&($.timing={wallMs:Math.max(...R.map(m=>m.report.timing.wallMs)),workers:R.flatMap(m=>m.report.timing.workers.map(A=>({...A,worker:`${m.report.shard.index}/${m.report.shard.total} \xB7 ${A.worker}`})))});let k=g.map(m=>m.history),P={runId:a.ciRun?`${a.ciRun}:${a.suite}:${$.baseURL??""}${a.browser?`:${a.browser}`:""}`:y,startedAt:y,finishedAt:w,baseURL:$.baseURL,green:k.filter(m=>m.status==="green").length,yellow:k.filter(m=>m.status==="yellow").length,red:k.filter(m=>m.status==="red").length,aiCalls:k.reduce((m,A)=>m+A.aiCalls,0),costUsd:k.reduce((m,A)=>m+A.costUsd,0),divergentSteps:Math.max(...S.map(m=>m.history.divergentSteps)),...S.some(m=>m.history.partial)?{partial:!0}:{},scenarios:k};return{report:$,history:P,replaced:o.map(m=>m.file)}}var Qo=1,W=class extends Error{constructor(n,r){super(ce(n,1/0));this.kind=r}kind},lr=e=>e instanceof Error?e.message:String(e);function gn(e,t){try{return py("git",t,{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:1e4}).trim()||void 0}catch{return}}function Tf(e){let t=e.trim();if(/^[a-z]:[\\/]/i.test(t))return;let n,r;if(/^[a-z][a-z0-9+.-]*:\/\//i.test(t)){let o;try{o=new URL(t)}catch{return}if(o.protocol==="file:")return;n=o.hostname,r=o.pathname}else{let o=/^(?:[^@/\s]+@)?([^:/\s]+):(.+)$/.exec(t);if(!o)return;n=o[1],r=o[2]}try{r=decodeURIComponent(r)}catch{}r=r.replace(/^\/+|\/+$/g,"").replace(/\.git$/i,""),n=n.toLowerCase();let s=/^v3\/([^/]+)\/([^/]+)\/([^/]+)$/.exec(r);return s?(n="dev.azure.com",r=`${s[1]}/${s[2]}/_git/${s[3]}`):n.endsWith(".visualstudio.com")&&(r=`${n.slice(0,-17)}/${r.replace(/^DefaultCollection\//i,"")}`,n="dev.azure.com"),r?`${n}/${r}`.toLowerCase():void 0}function ei(e){let n=(gn(e,["remote","-v"])?.split(`
|
|
287
|
+
`)??[]).map(r=>r.split(/\s+/)[1]).filter(Boolean);return[...new Set(n.map(Tf).filter(r=>r!==void 0))]}var vf=e=>e?.replace(/^refs\/heads\//,"")||void 0,Af=e=>e.GITHUB_EVENT_NAME==="pull_request"||!!e.GITHUB_EVENT_NAME?.startsWith("pull_request_review");function my(e){if(!e.GITHUB_EVENT_PATH||!Af(e))return{};let t=n=>typeof n=="string"&&n?n:void 0;try{let n=JSON.parse(se.readFileSync(e.GITHUB_EVENT_PATH,"utf8"))?.pull_request?.head;return{sha:t(n?.sha),ref:t(n?.ref)}}catch{return{}}}function yc(e,t){return[...(gn(e,["cat-file","-p",t])??"").split(`
|
|
277
288
|
|
|
278
|
-
`)[0].matchAll(/^parent ([0-9a-f]+)$/gm)].map(r=>r[1])}function
|
|
279
|
-
`)??[],r=n.includes("origin")?"origin":n[0],s=t.GITHUB_SERVER_URL&&t.GITHUB_REPOSITORY?`${t.GITHUB_SERVER_URL}/${t.GITHUB_REPOSITORY}`:void 0,o=[r&&
|
|
280
|
-
`):c.bytes;r.push({name:"report.json",data:
|
|
281
|
-
`)},...r]),{file:p,manifest:f,proposals:o,missing:d,dropped:u,unreadable:n}}var po="[a-z0-9-]+",Vd=new RegExp(`^proposals/${po}/${po}\\.json$`),xm="(?:chromium|chrome|msedge|firefox|webkit)/",Sm=new RegExp(`^artifacts/${po}/${po}/(?:${xm})?[A-Za-z0-9][A-Za-z0-9._-]*$`),ia=1024**3,da=8*1024**3,$m="the bundles to import add up to more than 8 GB unzipped",Ld=Math.min(da,yn),Dd=100,km=1024**2,Rm=6e5;function Tm(e){try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}}function fa(e){let t=ce.join(e,".saffron","reports");for(let o of ne.existsSync(t)?ne.readdirSync(t):[]){let i=Number(/^run-download-(\d+)-/.exec(o)?.[1]),a=ce.join(t,o),c=i?ne.statSync(a,{throwIfNoEntry:!1}):void 0;c&&Date.now()-c.mtimeMs>36e5&&!Tm(i)&&ne.rmSync(a,{recursive:!0,force:!0})}let n=ce.join(t,`run-download-${process.pid}-${ca(4).toString("hex")}`),r=ne.mkdirSync(n,{recursive:!0});return{dir:n,remove:()=>{ne.rmSync(n,{recursive:!0,force:!0});for(let o=t;r&&o.startsWith(r);o=ce.dirname(o))try{ne.rmdirSync(o)}catch{break}}}}async function Em(e,t){let n=r=>new H(r?.name==="TimeoutError"?`cannot download ${e}: it did not finish within 10 minutes`:`cannot download ${e}: ${Un(r)}`);try{let r=await fetch(e,{redirect:"follow",signal:AbortSignal.timeout(Rm)});if(!r.ok||!r.body)throw new H(`cannot download ${e}: HTTP ${r.status}`);let s=ne.openSync(t,"w");try{let o=0;for await(let i of r.body){if(o+=i.length,o>da)throw new H(`cannot download ${e}: it is over 8 GB`);ne.writeSync(s,i)}}finally{ne.closeSync(s)}}catch(r){throw r instanceof H?r:n(r)}}async function Am(e,t){if(/^https?:\/\//i.test(e)){let s=ce.join(t(),`url-${ca(4).toString("hex")}.zip`);return await Em(e,s),[{source:e,file:s}]}let n=ne.statSync(e,{throwIfNoEntry:!1});if(!n)throw new H(`not found: ${e}`);let r=n.isDirectory()?ne.readdirSync(e,{recursive:!0}).map(String).filter(s=>/^saffron-(bundle|summary).*\.zip$/.test(ce.basename(s))).sort().map(s=>ce.join(e,s)):[e];if(r.length===0)throw new H(`no saffron-bundle*.zip or saffron-summary*.zip under ${e}`);return r.map(s=>({source:s,file:s}))}function Cm(e,t){let n;try{n=Ul(t)}catch(s){throw new H(`${e} is not a Saffron bundle: ${Un(s)}`)}let r=new Map;for(let s of n){if(r.has(s.name))throw new H(`${e} is damaged: it holds ${ue(s.name)} twice`);r.set(s.name,s)}return{source:e,file:t,entries:r}}var _m=1024*1024;function Ud(e,t,n){let r=gm("sha256"),s=ne.openSync(e,"r");try{let o=Buffer.alloc(Math.max(1,Math.min(_m,t.size)));for(let i=0;i<t.size;){let a=ne.readSync(s,o,0,Math.min(o.length,t.size-i),t.start+i);if(a===0)throw new Error("the file ends early");let c=o.subarray(0,a);r.update(c),n?.(c),i+=a}}finally{ne.closeSync(s)}return r.digest("hex")}function Pm(e){try{return Ws(e).sha256}catch{return}}function Om({source:e,file:t,entries:n}){let r=f=>new H(`${e} ${f}`);for(let f of n.values()){if(f.size>ia||f.compressedSize>ia)throw r(`is damaged: ${ue(f.name)} is too large`);if(f.method!==0&&f.size>km&&f.size>Dd*f.compressedSize)throw r(`is damaged: ${ue(f.name)} claims to unzip to over ${Dd} times its size`)}let s=f=>{let p=n.get(f);if(!p)throw r(`is damaged: ${f} is missing`);let m;try{let h=p.raw();if(h.length!==p.compressedSize)throw new Error("the file ends early");m=p.method===0?h:hm.inflateRawSync(h,{maxOutputLength:Math.max(p.size,1)})}catch(h){throw r(`is damaged: ${f} cannot be read (${Un(h)})`)}if(m.length!==p.size)throw r(`is damaged: ${f} is truncated`);return m},o=f=>{let p=n.get(f);if(!(!p||p.method!==0)){if(p.compressedSize!==p.size)throw r(`is damaged: ${f} is truncated`);return p}},i=f=>{let p=o(f);if(!p)return At(s(f));try{return Ud(t,p)}catch(m){throw r(`is damaged: ${f} cannot be read (${Un(m)})`)}},a=(f,p,m)=>{let h=o(f),w=()=>new Error(ue(`${e} is damaged: ${f} changed while it was imported`,1/0));if(!h){let S=s(f);if(At(S)!==m)throw w();Ne(p,S);return}ne.mkdirSync(ce.dirname(p),{recursive:!0});let b=`${p}.${process.pid}-${ca(4).toString("hex")}.partial`,y=ne.openSync(b,"w");try{let S;try{S=Ud(t,h,x=>{for(let C=0;C<x.length;)C+=ne.writeSync(y,x,C,x.length-C)})}finally{ne.closeSync(y)}if(S!==m)throw w();ne.renameSync(b,p)}catch(S){throw ne.rmSync(b,{force:!0}),S}},c=f=>{try{return JSON.parse(s(f).toString("utf8"))}catch(p){throw p instanceof H?p:r(`is damaged: ${f} is not JSON`)}};if(!n.has("manifest.json"))throw r("is not a Saffron bundle: it has no manifest.json");let l=c("manifest.json");if(!l||l.tool!=="saffron"||typeof l.format!="number")throw r("is not a Saffron bundle");for(let f of["runner","createdAt","repository","branch","commit","headCommit","run","attempt","url"])if(l[f]!==void 0){if(typeof l[f]!="string")throw r(`is damaged: its manifest's ${f} is not text`);if(l[f].length>2048)throw r(`is damaged: its manifest's ${f} is over 2048 characters`);l[f]=ue(l[f],2048)}if(l.format>uo)throw r(`is bundle format ${l.format}, made by saffron-ai ${l.runner}; this saffron-ai (${Xe()}) reads format ${uo}. Update saffron-ai to import it`);if(l.format!==uo)throw r(`has bundle format ${l.format}, which this saffron-ai does not read`);if(!Array.isArray(l.proposals)||!Array.isArray(l.evidence))throw r("is damaged: its manifest has no proposal or evidence list");if(l.summary!==void 0&&l.summary!==!0)throw r("is damaged: its manifest's summary is not true");if(l.summary&&l.proposals.length>0)throw r("is damaged: it is a summary and lists proposals");let{shard:d}=l;if(d!==void 0&&!(Number.isInteger(d?.index)&&Number.isInteger(d?.total)&&d.index>=1&&d.index<=d.total))throw r("is damaged: its manifest's shard is not <index> of <total>");let u=new Map;for(let f of l.proposals){if(!f||typeof f.entry!="string"||!Vd.test(f.entry)||typeof f.revision!="string")throw r(`is damaged: its manifest lists a proposal at ${ue(JSON.stringify(f?.entry)??"nothing")}`);typeof f.feature=="string"&&(f.feature=ue(f.feature)),typeof f.scenario=="string"&&(f.scenario=ue(f.scenario));let p=s(f.entry);if(At(p)!==f.revision)throw r(`is damaged: ${f.entry} is not the proposal its manifest names`);u.set(f.entry,p)}for(let f of l.evidence){if(!f||typeof f.entry!="string"||!Sm.test(f.entry)||typeof f.sha256!="string")throw r(`is damaged: its manifest lists evidence at ${ue(JSON.stringify(f?.entry)??"nothing")}`);if(i(f.entry)!==f.sha256)throw r(`is damaged: ${f.entry} is not the file its manifest names`)}let g;if(l.report!==void 0){if(l.report!=="report.json")throw r(`is damaged: its manifest names the report ${JSON.stringify(l.report)}`);let f=c("report.json"),p=ea(f);if(p)throw r(`is damaged: report.json ${p}`);try{vn(f)}catch(m){throw r(`is damaged: report.json cannot be shown (${Un(m)})`)}g=f}if(d&&!(g&&ts(g)))throw r("is damaged: it is a shard's bundle without the shard's report");return{source:e,manifest:l,report:g,files:u,read:s,write:a}}function Im(e,t){let n=t.headCommit??t.commit,r=sn(e,["rev-parse","HEAD"]);if(!n||!r||r===n)return;let s=`${n.slice(0,7)}${t.branch?` on ${t.branch}`:""}`;if(!/^[0-9a-f]{7,64}$/i.test(n)||!sn(e,["rev-parse","--verify","--quiet",`${n}^{commit}`]))return`this checkout is at ${r.slice(0,7)}, and the bundle was made at ${s}, which this clone does not have: fetch it to review against the same files`;let[o,i]=(sn(e,["rev-list","--left-right","--count",`HEAD...${n}`,"--"])??"").split(/\s+/).map(Number),a=[o?`${o} commit${o===1?"":"s"} ahead of`:"",i?`${i} commit${i===1?"":"s"} behind`:""].filter(Boolean).join(" and ");return`this checkout (${r.slice(0,7)}) is ${a||"not at"} the commit the bundle was made at, ${s}`}function aa(e){let{repository:t,branch:n,commit:r,headCommit:s,run:o,attempt:i,url:a}=e;return Object.fromEntries(Object.entries({repository:t,branch:n,commit:r,headCommit:s,run:o,attempt:i,url:a}).filter(([,c])=>typeof c=="string"))}var Jd=e=>ce.join(e,".saffron","reports","imported.json");function on(e){let t;try{t=JSON.parse(ne.readFileSync(Jd(e),"utf8"))}catch{return{}}return!t||typeof t!="object"||Array.isArray(t)?{}:Object.fromEntries(Object.entries(t).filter(([,n])=>!!n&&typeof n.revision=="string"&&!!n.from&&typeof n.from=="object"))}function jm(e,t){try{return ne.readFileSync(e).equals(t)}catch{return!1}}function Wd(e,t,n,r,s){let o;try{o=vi(t,n)}catch(w){let b={file:`.saffron/${n}`,feature:"",scenario:""},y=`cannot be read: ${w instanceof ge?w.problem:Un(w)}`;return{verdict:{...b,outcome:"refused",reason:y},shown:b,file:ce.join(e,".saffron",n),revision:"",verified:!1}}let{proposal:i,revision:a}=o,{feature:c,scenario:l}=i.cache,d=ct(e,c,l),u={file:Ae(e,d),feature:ue(c),scenario:ue(l)},g=w=>({verdict:w,shown:u,file:d,revision:a,verified:i.meta.verified===!0}),f=w=>g({...u,outcome:"refused",reason:w});if(!i.meta.bound)return f("carries no binding (a runner older than 0.8.5 filed it), so nothing can tell whether it fits this checkout");let p=s?`. ${s}`:"";if(!ne.existsSync(ce.join(e,c)))return f(`is for ${u.feature}, which is not in this checkout${p}`);let m=jt(fe(e,c,l));if(m&&Jr(m)===Jr(i.cache))return g({...u,outcome:"unchanged",reason:"already accepted here: the committed recording is this proposal's"});let h;try{h=dt(e,i,r)}catch(w){h=`cannot be checked: ${Un(w)}`}return h?f(`does not fit this checkout: ${ue(h,1e3)}${p}`):g()}function Gd(e,t){if(ne.existsSync(e.file)){if(mt(e.file)===e.revision)return{...e.shown,outcome:"unchanged"};if(!t)return{...e.shown,outcome:"refused",reason:"differs from the proposal already pending here for this scenario: review that one first (saffron diff), or import with --overwrite to replace it"}}}function Nm(e,t,n,r,s,o){let i=Wd(e,t,n,r,o);if(i.verdict)return i.verdict;ne.mkdirSync(ce.dirname(i.file),{recursive:!0});try{return sr(i.file,()=>{let a=Gd(i,s);return a||(Ne(i.file,t),{...i.shown,outcome:"imported"})})}catch(a){if(a instanceof In)return{...i.shown,outcome:"refused",reason:"is being decided by another process. Try again."};throw a}}async function Kd(e,t,n,r={}){let s;try{let o=Zd(await Qd(t,()=>(s??=fa(e)).dir,r.describe));return Fm(e,o,n,r)}finally{s?.remove()}}function Yd(e){let t=e.report&&ts(e.report)?e.report.shard:void 0,n=[...new Set([t?.browser,...(e.report?.scenarios??[]).map(r=>r.browser)].filter(Boolean))].sort();return JSON.stringify([e.manifest.repository??"",e.manifest.run??"",e.manifest.shard?.index??0,t?.suite??"",t?.total??0,t?t.by??"scenario":"",n,e.report?.baseURL??""])}function Zd(e){let t=r=>`${Yd(r)}|${Number(r.manifest.attempt)||0}`,n=new Set(e.filter(r=>!r.manifest.summary&&r.report).map(t));return e.filter(r=>!r.manifest.summary||!n.has(t(r)))}async function Qd(e,t,n){let r=[];for(let s of e)for(let o of await Am(s,t))r.push(Cm(n?.(o.source)??o.source,o.file));if(r.reduce((s,o)=>s+[...o.entries.values()].reduce((i,a)=>i+a.size,0),0)>da)throw new H($m);return r.map(Om)}function Mm(e){let t=[...new Set(e)].sort((n,r)=>n-r);return t.length>1?`${t.slice(0,-1).join(", ")} and ${t[t.length-1]}`:String(t[0]??"")}function Xd(e,t,n){let r=t;if(r.length===0)throw new H("no bundle to import");let s=new Set,o=go(e);for(let g of r){if(n.run!==void 0&&g.manifest.run!==n.run)throw new H(`${g.source} was made by ${g.manifest.run?`run ${g.manifest.run}`:"no CI run"}, not by ${n.run}, the run it was downloaded from. If that is expected, download the artifact and import the file`);let f=g.manifest.repository;if(!f&&!n.allowUnknownRepository)throw new H(`${g.source} does not say which repository it comes from (it was made outside a git checkout). Import it with --allow-unknown-repository to check it by its proposals' bindings only`);if(!f)s.add(`${g.source} does not say which repository it comes from: it is checked by its proposals' bindings only`);else if(o.length===0)s.add(`this project has no git remote to compare ${f} with: the bundle is checked by its proposals' bindings only`);else if(!o.includes(f)){let p=h=>h.slice(h.indexOf("/")),m=o.find(h=>p(h)===p(f));if(!m)throw new H(`${g.source} comes from ${f}, and this checkout is ${o.join(", ")}. Import it into a checkout of ${f}`);s.add(`${r.length===1?"the bundle comes":"the bundles come"} from ${f}, and this checkout is ${m}: the same repository under another host name (an SSH host alias, or a mirror), so each proposal is checked by its binding`)}}if(r.length>1){let g=new Set(r.map(y=>y.manifest.run??""));if(g.size>1)throw new H(`these bundles come from different runs (${[...g].map(y=>y||"none recorded").join(", ")}). Import one run at a time`);let f=y=>Number(y.manifest.attempt)||0,p=Yd,m=y=>y.manifest.shard?.index??0,h=y=>r.filter(S=>m(S)===m(y)&&(!y.report||p(S)===p(y))).reduce((S,x)=>f(x)>f(S)?x:S),w=r.filter(y=>f(y)<f(h(y)));for(let y of w){let S=y.manifest.shard?`shard ${y.manifest.shard.index}`:"the whole run";s.add(`${y.source} is ${S} of attempt ${f(y)}, which attempt ${f(h(y))} ran again: left out`)}r=r.filter(y=>!w.includes(y));let b=r.filter(y=>!y.manifest.shard);if(b.length>0&&r.length>1)throw new H(`${b.map(y=>y.source).join(", ")} ${b.length===1?"holds a whole run, not a shard of one":"hold whole runs, not shards of one"}: import one run at a time`)}let i,a=r.filter(g=>g.report);if(r.length===1&&a.length===1){let{shard:g,history:f,...p}=a[0].report;i=p}else if(a.length>0)try{let g=fo(a.map(f=>({file:f.source,report:f.report})),{partial:!0});if(g.replaced.length>0)throw new Dn(`${g.replaced.join(", ")} holds a shard that another bundle of the same attempt holds too`);i=g.report}catch(g){throw g instanceof Dn?new H(`these shard bundles do not belong together: ${g.message.split(`
|
|
282
|
-
`).join("; ")}`):
|
|
283
|
-
`))?l="unchanged":(
|
|
284
|
-
`),{bundles:s.map(
|
|
285
|
-
`),
|
|
286
|
-
`)[0]:void 0,failedStep:(
|
|
287
|
-
`)[0]}`:""}`)}if(e.tags.length&&console.log(`tags: ${e.tags.map(
|
|
289
|
+
`)[0].matchAll(/^parent ([0-9a-f]+)$/gm)].map(r=>r[1])}function wy(e,t=process.env){let n=gn(e,["remote"])?.split(`
|
|
290
|
+
`)??[],r=n.includes("origin")?"origin":n[0],s=t.GITHUB_SERVER_URL&&t.GITHUB_REPOSITORY?`${t.GITHUB_SERVER_URL}/${t.GITHUB_REPOSITORY}`:void 0,o=[r&&gn(e,["remote","get-url",r]),s,t.BUILD_REPOSITORY_URI].map(h=>h?Tf(h):void 0).find(Boolean),a=gn(e,["rev-parse","--abbrev-ref","HEAD"]),i=my(t),c=(Af(t)?t.GITHUB_HEAD_REF||i.ref:void 0)||(t.GITHUB_EVENT_NAME==="pull_request_target"?t.GITHUB_BASE_REF:void 0)||(t.GITHUB_REF_TYPE==="tag"?void 0:t.GITHUB_REF_NAME)||vf(t.SYSTEM_PULLREQUEST_SOURCEBRANCH)||(t.BUILD_SOURCEBRANCH?.startsWith("refs/heads/")?vf(t.BUILD_SOURCEBRANCH):void 0)||(a!=="HEAD"?a:void 0),l=gn(e,["rev-parse","HEAD"])||t.GITHUB_SHA||t.BUILD_SOURCEVERSION,d=i.sha||t.SYSTEM_PULLREQUEST_SOURCECOMMITID,f=d&&l&&yc(e,l)[1]===d?d:void 0,p=t.GITHUB_SERVER_URL&&t.GITHUB_REPOSITORY&&t.GITHUB_RUN_ID?`${t.GITHUB_SERVER_URL}/${t.GITHUB_REPOSITORY}/actions/runs/${t.GITHUB_RUN_ID}`:t.SYSTEM_COLLECTIONURI&&t.SYSTEM_TEAMPROJECT&&t.BUILD_BUILDID?`${t.SYSTEM_COLLECTIONURI.replace(/\/?$/,"/")}${encodeURIComponent(t.SYSTEM_TEAMPROJECT)}/_build/results?buildId=${t.BUILD_BUILDID}`:void 0,u={repository:o,branch:c,commit:l,headCommit:f&&f!==l?f:void 0,run:t.GITHUB_RUN_ID&&`github:${t.GITHUB_RUN_ID}`||t.BUILD_BUILDID&&`azure:${t.BUILD_BUILDID}`||Ko(t),attempt:Yo(t),url:p};return Object.fromEntries(Object.entries(u).filter(([,h])=>h!==void 0))}function _s(e){let t=e.headCommit??e.commit;return[e.run?`run ${e.run}${e.attempt&&e.attempt!=="1"?` (attempt ${e.attempt})`:""}`:"a local run",e.branch||t?`${e.branch??"detached"}${t?` @ ${t.slice(0,7)}`:""}`:void 0,e.repository].filter(Boolean).join(" \xB7 ")}var yy=/^(latest|shard-\d+-of-\d+)\.json$/;function by(e){let t=ge.join(e,".saffron","reports"),n;try{n=se.readdirSync(t).filter(s=>yy.test(s)).sort()}catch{return}let r;for(let s of n)try{let o=se.readFileSync(ge.join(t,s)),a=JSON.parse(o.toString("utf8"));dc(a)&&(!r||a.finishedAt>r.report.finishedAt)&&(r={bytes:o,report:a})}catch{}return r}function vy(e,t,n=!1){let r=n?"saffron-summary":"saffron-bundle";return ge.join(e,".saffron","reports",t?`${r}-${pc(t)}.zip`:`${r}.zip`)}var xf=e=>`${(e/1024**3).toFixed(1)} GB`,Sf='Keep fewer traces ("trace": "retain-on-failure" in saffron.config.json, or --trace retain-on-failure) and run again';function Ef(e,t={}){let n=[],r=[],s=[],o=[],a=ge.join(e,".saffron","proposals"),i=t.summary===!0;for(let{file:b,proposal:g,revision:S,bytes:y}of i?[]:Kt(e,(w,v)=>n.push({file:Be(e,w),problem:v}))){let w=`proposals/${Be(a,b)}`;r.push({name:w,data:y}),s.push({entry:w,feature:g.cache.feature,scenario:g.cache.scenario,revision:S,bound:g.meta.bound}),o.push({file:b,proposal:g,bytes:y})}let c=by(e),l=[],d=[],f=[];if(c){let b=i?Buffer.from(`${JSON.stringify({...c.report,scenarios:c.report.scenarios.map(w=>({...w,evidence:w.evidence?.filter(v=>v.kind!=="trace")}))},null,2)}
|
|
291
|
+
`):c.bytes;r.push({name:"report.json",data:b});let g=[],S=new Set;for(let w of c.report.scenarios)for(let v of w.evidence??[]){if(S.has(v.file)||i&&v.kind==="trace")continue;S.add(v.file);let x=v.file.startsWith(".saffron/artifacts/")?se.statSync(ge.join(e,v.file),{throwIfNoEntry:!1}):void 0;if(!x?.isFile()){d.push(v.file);continue}let $=w.status==="green"&&v.kind==="trace";if(x.size>hc){if($){f.push(v.file);continue}throw new W(`${v.file} is ${xf(x.size)}, over the 1 GB a bundle holds per file. ${Sf}`)}g.push({e:v,size:x.size,greenTrace:$})}let y=()=>r.reduce((w,v)=>w+("data"in v?v.data.length:v.size??0)+1024,0)+g.reduce((w,v)=>w+v.size+1024,0);if(y()>$f)for(let w of g.filter(v=>v.greenTrace))g.splice(g.indexOf(w),1),f.push(w.e.file);if(y()>$f)throw new W(`the bundle would hold ${xf(y())}${f.length?" even without the traces of green scenarios":""}, over the 4 GB one bundle holds. ${Sf}, or split the run into shards (--shard)`);for(let{e:w}of g){let v=ge.join(e,w.file),x;try{x=_t(ge.join(e,".saffron","artifacts"),v)?Io(v):void 0}catch{x=void 0}if(!x||w.sha256&&x.sha256!==w.sha256){d.push(w.file);continue}let $=w.file.slice(9);r.push({name:$,file:v,crc:x.crc,size:x.size}),l.push({entry:$,sha256:x.sha256})}}if(!c&&(i||s.length===0))throw new W(`nothing to export: no run report${i?"":" and no pending proposals"} under .saffron. Run \`saffron run\` first.`);let p=c&&Es(c.report)?{index:c.report.shard.index,total:c.report.shard.total}:void 0,u={tool:"saffron",format:Qo,runner:ot(),createdAt:new Date().toISOString(),...wy(e,t.env),...p?{shard:p}:{},...c?{report:"report.json"}:{},...i?{summary:!0}:{},proposals:s,evidence:l},h=t.out??vy(e,p,i);if(se.existsSync(h)&&se.statSync(h).isDirectory())throw new W(`${h} is a folder: give --out a file name, such as ${ge.join(h,"saffron-bundle.zip")}`);return Au(h,[{name:"manifest.json",data:Buffer.from(`${JSON.stringify(u,null,2)}
|
|
292
|
+
`)},...r]),{file:h,manifest:u,proposals:o,missing:d,dropped:f,unreadable:n}}var Xo="[a-z0-9-]+",_f=new RegExp(`^proposals/${Xo}/${Xo}\\.json$`),xy="(?:chromium|chrome|msedge|firefox|webkit)/",Sy=new RegExp(`^artifacts/${Xo}/${Xo}/(?:${xy})?[A-Za-z0-9][A-Za-z0-9._-]*$`),hc=1024**3,bc=8*1024**3,$y="the bundles to import add up to more than 8 GB unzipped",$f=Math.min(bc,In),kf=100,ky=1024**2,Ry=6e5;function Ty(e){try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}}function vc(e){let t=ge.join(e,".saffron","reports");for(let o of se.existsSync(t)?se.readdirSync(t):[]){let a=Number(/^run-download-(\d+)-/.exec(o)?.[1]),i=ge.join(t,o),c=a?se.statSync(i,{throwIfNoEntry:!1}):void 0;c&&Date.now()-c.mtimeMs>36e5&&!Ty(a)&&se.rmSync(i,{recursive:!0,force:!0})}let n=ge.join(t,`run-download-${process.pid}-${wc(4).toString("hex")}`),r=se.mkdirSync(n,{recursive:!0});return{dir:n,remove:()=>{se.rmSync(n,{recursive:!0,force:!0});for(let o=t;r&&o.startsWith(r);o=ge.dirname(o))try{se.rmdirSync(o)}catch{break}}}}async function Ay(e,t){let n=r=>new W(r?.name==="TimeoutError"?`cannot download ${e}: it did not finish within 10 minutes`:`cannot download ${e}: ${lr(r)}`);try{let r=await fetch(e,{redirect:"follow",signal:AbortSignal.timeout(Ry)});if(!r.ok||!r.body)throw new W(`cannot download ${e}: HTTP ${r.status}`);let s=se.openSync(t,"w");try{let o=0;for await(let a of r.body){if(o+=a.length,o>bc)throw new W(`cannot download ${e}: it is over 8 GB`);se.writeSync(s,a)}}finally{se.closeSync(s)}}catch(r){throw r instanceof W?r:n(r)}}async function Ey(e,t){if(/^https?:\/\//i.test(e)){let s=ge.join(t(),`url-${wc(4).toString("hex")}.zip`);return await Ay(e,s),[{source:e,file:s}]}let n=se.statSync(e,{throwIfNoEntry:!1});if(!n)throw new W(`not found: ${e}`);let r=n.isDirectory()?se.readdirSync(e,{recursive:!0}).map(String).filter(s=>/^saffron-(bundle|summary).*\.zip$/.test(ge.basename(s))).sort().map(s=>ge.join(e,s)):[e];if(r.length===0)throw new W(`no saffron-bundle*.zip or saffron-summary*.zip under ${e}`);return r.map(s=>({source:s,file:s}))}function _y(e,t){let n;try{n=bu(t)}catch(s){throw new W(`${e} is not a Saffron bundle: ${lr(s)}`)}let r=new Map;for(let s of n){if(r.has(s.name))throw new W(`${e} is damaged: it holds ${ce(s.name)} twice`);r.set(s.name,s)}return{source:e,file:t,entries:r}}var Oy=1024*1024;function Rf(e,t,n){let r=gy("sha256"),s=se.openSync(e,"r");try{let o=Buffer.alloc(Math.max(1,Math.min(Oy,t.size)));for(let a=0;a<t.size;){let i=se.readSync(s,o,0,Math.min(o.length,t.size-a),t.start+a);if(i===0)throw new Error("the file ends early");let c=o.subarray(0,i);r.update(c),n?.(c),a+=i}}finally{se.closeSync(s)}return r.digest("hex")}function Cy(e){try{return Io(e).sha256}catch{return}}function Py({source:e,file:t,entries:n}){let r=u=>new W(`${e} ${u}`);for(let u of n.values()){if(u.size>hc||u.compressedSize>hc)throw r(`is damaged: ${ce(u.name)} is too large`);if(u.method!==0&&u.size>ky&&u.size>kf*u.compressedSize)throw r(`is damaged: ${ce(u.name)} claims to unzip to over ${kf} times its size`)}let s=u=>{let h=n.get(u);if(!h)throw r(`is damaged: ${u} is missing`);let b;try{let g=h.raw();if(g.length!==h.compressedSize)throw new Error("the file ends early");b=h.method===0?g:hy.inflateRawSync(g,{maxOutputLength:Math.max(h.size,1)})}catch(g){throw r(`is damaged: ${u} cannot be read (${lr(g)})`)}if(b.length!==h.size)throw r(`is damaged: ${u} is truncated`);return b},o=u=>{let h=n.get(u);if(!(!h||h.method!==0)){if(h.compressedSize!==h.size)throw r(`is damaged: ${u} is truncated`);return h}},a=u=>{let h=o(u);if(!h)return zt(s(u));try{return Rf(t,h)}catch(b){throw r(`is damaged: ${u} cannot be read (${lr(b)})`)}},i=(u,h,b)=>{let g=o(u),S=()=>new Error(ce(`${e} is damaged: ${u} changed while it was imported`,1/0));if(!g){let v=s(u);if(zt(v)!==b)throw S();Je(h,v);return}se.mkdirSync(ge.dirname(h),{recursive:!0});let y=`${h}.${process.pid}-${wc(4).toString("hex")}.partial`,w=se.openSync(y,"w");try{let v;try{v=Rf(t,g,x=>{for(let $=0;$<x.length;)$+=se.writeSync(w,x,$,x.length-$)})}finally{se.closeSync(w)}if(v!==b)throw S();se.renameSync(y,h)}catch(v){throw se.rmSync(y,{force:!0}),v}},c=u=>{try{return JSON.parse(s(u).toString("utf8"))}catch(h){throw h instanceof W?h:r(`is damaged: ${u} is not JSON`)}};if(!n.has("manifest.json"))throw r("is not a Saffron bundle: it has no manifest.json");let l=c("manifest.json");if(!l||l.tool!=="saffron"||typeof l.format!="number")throw r("is not a Saffron bundle");for(let u of["runner","createdAt","repository","branch","commit","headCommit","run","attempt","url"])if(l[u]!==void 0){if(typeof l[u]!="string")throw r(`is damaged: its manifest's ${u} is not text`);if(l[u].length>2048)throw r(`is damaged: its manifest's ${u} is over 2048 characters`);l[u]=ce(l[u],2048)}if(l.format>Qo)throw r(`is bundle format ${l.format}, made by saffron-ai ${l.runner}; this saffron-ai (${ot()}) reads format ${Qo}. Update saffron-ai to import it`);if(l.format!==Qo)throw r(`has bundle format ${l.format}, which this saffron-ai does not read`);if(!Array.isArray(l.proposals)||!Array.isArray(l.evidence))throw r("is damaged: its manifest has no proposal or evidence list");if(l.summary!==void 0&&l.summary!==!0)throw r("is damaged: its manifest's summary is not true");if(l.summary&&l.proposals.length>0)throw r("is damaged: it is a summary and lists proposals");let{shard:d}=l;if(d!==void 0&&!(Number.isInteger(d?.index)&&Number.isInteger(d?.total)&&d.index>=1&&d.index<=d.total))throw r("is damaged: its manifest's shard is not <index> of <total>");let f=new Map;for(let u of l.proposals){if(!u||typeof u.entry!="string"||!_f.test(u.entry)||typeof u.revision!="string")throw r(`is damaged: its manifest lists a proposal at ${ce(JSON.stringify(u?.entry)??"nothing")}`);typeof u.feature=="string"&&(u.feature=ce(u.feature)),typeof u.scenario=="string"&&(u.scenario=ce(u.scenario));let h=s(u.entry);if(zt(h)!==u.revision)throw r(`is damaged: ${u.entry} is not the proposal its manifest names`);f.set(u.entry,h)}for(let u of l.evidence){if(!u||typeof u.entry!="string"||!Sy.test(u.entry)||typeof u.sha256!="string")throw r(`is damaged: its manifest lists evidence at ${ce(JSON.stringify(u?.entry)??"nothing")}`);if(a(u.entry)!==u.sha256)throw r(`is damaged: ${u.entry} is not the file its manifest names`)}let p;if(l.report!==void 0){if(l.report!=="report.json")throw r(`is damaged: its manifest names the report ${JSON.stringify(l.report)}`);let u=c("report.json"),h=lc(u);if(h)throw r(`is damaged: report.json ${h}`);try{Ln(u)}catch(b){throw r(`is damaged: report.json cannot be shown (${lr(b)})`)}p=u}if(d&&!(p&&Es(p)))throw r("is damaged: it is a shard's bundle without the shard's report");return{source:e,manifest:l,report:p,files:f,read:s,write:i}}function Iy(e,t){let n=t.headCommit??t.commit,r=gn(e,["rev-parse","HEAD"]);if(!n||!r||r===n)return;let s=`${n.slice(0,7)}${t.branch?` on ${t.branch}`:""}`;if(!/^[0-9a-f]{7,64}$/i.test(n)||!gn(e,["rev-parse","--verify","--quiet",`${n}^{commit}`]))return`this checkout is at ${r.slice(0,7)}, and the bundle was made at ${s}, which this clone does not have: fetch it to review against the same files`;let[o,a]=(gn(e,["rev-list","--left-right","--count",`HEAD...${n}`,"--"])??"").split(/\s+/).map(Number),i=[o?`${o} commit${o===1?"":"s"} ahead of`:"",a?`${a} commit${a===1?"":"s"} behind`:""].filter(Boolean).join(" and ");return`this checkout (${r.slice(0,7)}) is ${i||"not at"} the commit the bundle was made at, ${s}`}function mc(e){let{repository:t,branch:n,commit:r,headCommit:s,run:o,attempt:a,url:i}=e;return Object.fromEntries(Object.entries({repository:t,branch:n,commit:r,headCommit:s,run:o,attempt:a,url:i}).filter(([,c])=>typeof c=="string"))}var Of=e=>ge.join(e,".saffron","reports","imported.json");function hn(e){let t;try{t=JSON.parse(se.readFileSync(Of(e),"utf8"))}catch{return{}}return!t||typeof t!="object"||Array.isArray(t)?{}:Object.fromEntries(Object.entries(t).filter(([,n])=>!!n&&typeof n.revision=="string"&&!!n.from&&typeof n.from=="object"))}function Ny(e,t){try{return se.readFileSync(e).equals(t)}catch{return!1}}function Cf(e,t,n,r,s){let o;try{o=va(t,n)}catch(S){let y={file:`.saffron/${n}`,feature:"",scenario:""},w=`cannot be read: ${S instanceof $e?S.problem:lr(S)}`;return{verdict:{...y,outcome:"refused",reason:w},shown:y,file:ge.join(e,".saffron",n),revision:"",verified:!1}}let{proposal:a,revision:i}=o,{feature:c,scenario:l}=a.cache,d=xt(e,c,l),f={file:Be(e,d),feature:ce(c),scenario:ce(l)},p=S=>({verdict:S,shown:f,file:d,revision:i,verified:a.meta.verified===!0}),u=S=>p({...f,outcome:"refused",reason:S});if(!a.meta.bound)return u("carries no binding (a runner older than 0.8.5 filed it), so nothing can tell whether it fits this checkout");let h=s?`. ${s}`:"";if(!se.existsSync(ge.join(e,c)))return u(`is for ${f.feature}, which is not in this checkout${h}`);let b=Jt(me(e,c,l));if(b&&bs(b)===bs(a.cache))return p({...f,outcome:"unchanged",reason:"already accepted here: the committed recording is this proposal's"});let g;try{g=$t(e,a,r)}catch(S){g=`cannot be checked: ${lr(S)}`}return g?u(`does not fit this checkout: ${ce(g,1e3)}${h}`):p()}function Pf(e,t){if(se.existsSync(e.file)){if(Ot(e.file)===e.revision)return{...e.shown,outcome:"unchanged"};if(!t)return{...e.shown,outcome:"refused",reason:"differs from the proposal already pending here for this scenario: review that one first (saffron diff), or import with --overwrite to replace it"}}}function jy(e,t,n,r,s,o){let a=Cf(e,t,n,r,o);if(a.verdict)return a.verdict;se.mkdirSync(ge.dirname(a.file),{recursive:!0});try{return Cr(a.file,()=>{let i=Pf(a,s);return i||(Je(a.file,t),{...a.shown,outcome:"imported"})})}catch(i){if(i instanceof er)return{...a.shown,outcome:"refused",reason:"is being decided by another process. Try again."};throw i}}async function If(e,t,n,r={}){let s;try{let o=jf(await Mf(t,()=>(s??=vc(e)).dir,r.describe));return Dy(e,o,n,r)}finally{s?.remove()}}function Nf(e){let t=e.report&&Es(e.report)?e.report.shard:void 0,n=[...new Set([t?.browser,...(e.report?.scenarios??[]).map(r=>r.browser)].filter(Boolean))].sort();return JSON.stringify([e.manifest.repository??"",e.manifest.run??"",e.manifest.shard?.index??0,t?.suite??"",t?.total??0,t?t.by??"scenario":"",n,e.report?.baseURL??""])}function jf(e){let t=r=>`${Nf(r)}|${Number(r.manifest.attempt)||0}`,n=new Set(e.filter(r=>!r.manifest.summary&&r.report).map(t));return e.filter(r=>!r.manifest.summary||!n.has(t(r)))}async function Mf(e,t,n){let r=[];for(let s of e)for(let o of await Ey(s,t))r.push(_y(n?.(o.source)??o.source,o.file));if(r.reduce((s,o)=>s+[...o.entries.values()].reduce((a,i)=>a+i.size,0),0)>bc)throw new W($y);return r.map(Py)}function My(e){let t=[...new Set(e)].sort((n,r)=>n-r);return t.length>1?`${t.slice(0,-1).join(", ")} and ${t[t.length-1]}`:String(t[0]??"")}function Df(e,t,n){let r=t;if(r.length===0)throw new W("no bundle to import");let s=new Set,o=ei(e);for(let p of r){if(n.run!==void 0&&p.manifest.run!==n.run)throw new W(`${p.source} was made by ${p.manifest.run?`run ${p.manifest.run}`:"no CI run"}, not by ${n.run}, the run it was downloaded from. If that is expected, download the artifact and import the file`);let u=p.manifest.repository;if(!u&&!n.allowUnknownRepository)throw new W(`${p.source} does not say which repository it comes from (it was made outside a git checkout). Import it with --allow-unknown-repository to check it by its proposals' bindings only`);if(!u)s.add(`${p.source} does not say which repository it comes from: it is checked by its proposals' bindings only`);else if(o.length===0)s.add(`this project has no git remote to compare ${u} with: the bundle is checked by its proposals' bindings only`);else if(!o.includes(u)){let h=g=>g.slice(g.indexOf("/")),b=o.find(g=>h(g)===h(u));if(!b)throw new W(`${p.source} comes from ${u}, and this checkout is ${o.join(", ")}. Import it into a checkout of ${u}`);s.add(`${r.length===1?"the bundle comes":"the bundles come"} from ${u}, and this checkout is ${b}: the same repository under another host name (an SSH host alias, or a mirror), so each proposal is checked by its binding`)}}if(r.length>1){let p=new Set(r.map(w=>w.manifest.run??""));if(p.size>1)throw new W(`these bundles come from different runs (${[...p].map(w=>w||"none recorded").join(", ")}). Import one run at a time`);let u=w=>Number(w.manifest.attempt)||0,h=Nf,b=w=>w.manifest.shard?.index??0,g=w=>r.filter(v=>b(v)===b(w)&&(!w.report||h(v)===h(w))).reduce((v,x)=>u(x)>u(v)?x:v),S=r.filter(w=>u(w)<u(g(w)));for(let w of S){let v=w.manifest.shard?`shard ${w.manifest.shard.index}`:"the whole run";s.add(`${w.source} is ${v} of attempt ${u(w)}, which attempt ${u(g(w))} ran again: left out`)}r=r.filter(w=>!S.includes(w));let y=r.filter(w=>!w.manifest.shard);if(y.length>0&&r.length>1)throw new W(`${y.map(w=>w.source).join(", ")} ${y.length===1?"holds a whole run, not a shard of one":"hold whole runs, not shards of one"}: import one run at a time`)}let a,i=r.filter(p=>p.report);if(r.length===1&&i.length===1){let{shard:p,history:u,...h}=i[0].report;a=h}else if(i.length>0)try{let p=Zo(i.map(u=>({file:u.source,report:u.report})),{partial:!0});if(p.replaced.length>0)throw new cr(`${p.replaced.join(", ")} holds a shard that another bundle of the same attempt holds too`);a=p.report}catch(p){throw p instanceof cr?new W(`these shard bundles do not belong together: ${p.message.split(`
|
|
293
|
+
`).join("; ")}`):p}let c=r[0].manifest,l=Iy(e,c);l&&s.add(l),c.headCommit&&c.commit&&s.add(`the run tested ${c.commit.slice(0,7)}, a pull request's merge commit, not the head of ${c.branch??"its branch"} (${c.headCommit.slice(0,7)}): each proposal is checked against this checkout by its binding`);let d=c.headCommit??c.commit,f=l&&d?`The bundle was made at ${d.slice(0,7)}${c.branch?` on ${c.branch}`:""}: check that out and import again`:void 0;if(a){let p=r.flatMap(u=>u.manifest.shard?[u.manifest.shard]:[]);a.imported={...mc(c),...p.length>0?{shards:{imported:p.map(u=>u.index).sort((u,h)=>u-h),total:p[0].total}}:{}}}return{bundles:r,report:a,warnings:s,hint:f}}function Ff(e,t,n){let r={written:0,unchanged:0},s=new Map;for(let o of n?.scenarios??[])for(let a of o.evidence??[])s.set(ge.posix.dirname(a.file),{feature:o.feature,scenario:o.scenario});for(let o of t)for(let{entry:a,sha256:i}of o.manifest.evidence){let c=ge.join(e,".saffron",...a.split("/"));if(Cy(c)===i){r.unchanged++;continue}o.write(a,c,i),r.written++;let l=s.get(`.saffron/${ge.posix.dirname(a)}`);l&&se.writeFileSync(ge.join(e,".saffron",...a.split("/").slice(0,3),Xn),JSON.stringify(l,null,2))}return r}function Lf(e){let t=new Map;for(let s of e)for(let o of s.manifest.proposals){let a=t.get(o.entry)??{revisions:new Set,shards:[]};a.revisions.add(o.revision),s.manifest.shard&&a.shards.push(s.manifest.shard.index),t.set(o.entry,a)}let n=[],r=new Set;for(let s of e)for(let o of s.manifest.proposals){let a=t.get(o.entry);if(a.revisions.size===1){n.push({b:s,p:o});continue}r.has(o.entry)||(r.add(o.entry),n.push({b:s,p:o,conflict:{file:`.saffron/${o.entry}`,feature:typeof o.feature=="string"?o.feature:"",scenario:typeof o.scenario=="string"?o.scenario:"",outcome:"refused",reason:`is a conflict between the run's shards: shards ${My(a.shards)} filed different proposals for this scenario (a Scenario Outline's rows split across shards), so no proposal for it was imported. Run the scenario again on one machine and import that run`}}))}return n}function Dy(e,t,n,r){let{bundles:s,report:o,warnings:a,hint:i}=Df(e,t,r);if(s.every(u=>u.manifest.summary))throw new W(`${s[0].source} is a summary (saffron export --report-only): the run's results, which saffron report --run shows, and no proposals. Import the run's full bundle (saffron-bundle*)`);let c=Ff(e,s,o),l;if(o){for(let h of o.scenarios){let b=typeof h.proposalFile=="string"?h.proposalFile.split(/[\\/]/).slice(-2):[];_f.test(`proposals/${b.join("/")}`)&&(h.proposalFile=`.saffron/proposals/${b.join("/")}`)}let u=ge.join(e,".saffron","reports","latest.json");Ny(u,Buffer.from(`${JSON.stringify(o,null,2)}
|
|
294
|
+
`))?l="unchanged":(Ts(e,o),l="written")}let d=[],f=hn(e),p=JSON.stringify(f);for(let{b:u,p:h,conflict:b}of Lf(s)){if(b){d.push(b);continue}let g=jy(e,u.files.get(h.entry),h.entry,n,r.overwrite===!0,i),S=g.reason===void 0?g:{...g,reason:ce(g.reason,1/0)};d.push(S),(S.outcome==="imported"||S.outcome==="unchanged"&&!S.reason)&&(f[S.file]={revision:h.revision,from:{...mc(u.manifest),...u.manifest.shard?{shard:u.manifest.shard}:{}}})}for(let[u,h]of Object.entries(f)){let b;try{b=Ot(ge.join(e,u))}catch{b=void 0}b!==h.revision&&delete f[u]}return JSON.stringify(f)!==p&&Je(Of(e),`${JSON.stringify(f,null,2)}
|
|
295
|
+
`),{bundles:s.map(u=>{let{runner:h,createdAt:b,shard:g}=u.manifest;return{source:u.source,runner:h,createdAt:b,origin:mc(u.manifest),...g?{shard:{index:g.index,total:g.total}}:{}}}),warnings:[...a],proposals:d,evidence:c,...l?{report:l}:{}}}async function Bf(e,t,n,r,s={}){let o=jf(await Mf(n,()=>{throw new W("a viewed run is read from its downloaded folder")},s.describe)),{bundles:a,report:i,warnings:c,hint:l}=Df(e,o,{run:s.run});Ff(t,a,i);let d=Lf(a).map(({b:f,p,conflict:u})=>{if(u)return{feature:u.feature,scenario:u.scenario,verified:!1,importable:!1,reason:u.reason};let h=Cf(e,f.files.get(p.entry),p.entry,r,l),b=h.verdict??Pf(h,!1),{feature:g,scenario:S}=h.shown,y={feature:g||(typeof p.feature=="string"?p.feature:""),scenario:S||(typeof p.scenario=="string"?p.scenario:""),verified:h.verified};return b?{...y,importable:!1,reason:ce(b.reason??"already pending here",1/0)}:{...y,importable:!0}});return{report:i,warnings:[...c],proposals:d,summaryOnly:a.every(f=>f.manifest.summary===!0)}}var Fy=/^\s*StepSet:/;function Bn(e,t){return yt.relative(e,t).split(yt.sep).join("/")}function Ly(e,t){let n={green:0,yellow:1,red:2};return!e||n[t]>n[e]?t:e}function Os(e,t,n={}){let r=t.features??"features",s=yt.isAbsolute(r)?r:yt.join(e,r),o=yt.join(e,".saffron","reports","latest.json"),a=yt.join(e,".saffron","reports","latest.html"),i;try{i=JSON.parse(Qt.readFileSync(o,"utf8"))}catch{i=void 0}let c=new Map;for(let R of i?.scenarios??[])c.set(R.feature,[...c.get(R.feature)??[],R]);let l=new Map,d;try{l=sn(Gn(s),e)}catch(R){d=R instanceof Error?R.message:String(R)}let f=an(s,on),p=[],u=new Map,h=new Map,b={parsedFiles:new Set,owned:new Set,unreadable:d?[d]:[]};for(let R of f){let k=Bn(e,R),C="";try{C=Qt.readFileSync(R,"utf8")}catch(L){p.push({path:k,name:k,scenarios:[],stepSets:0,error:String(L)}),b.unreadable.push(`${k}: ${String(L)}`);continue}let P=C.split(`
|
|
296
|
+
`),m=P.filter(L=>Fy.test(L)).length,A=P.find(L=>/^\s*Feature:/.test(L)),O=A?A.replace(/^\s*Feature:\s*/,"").trim():k,T;try{T=ft(R,e,l)}catch(L){p.push({path:k,name:O,scenarios:[],stepSets:m,error:d??(L instanceof Error?L.message:String(L))}),b.unreadable.push(`${k}: ${L instanceof Error?L.message:String(L)}`);continue}b.parsedFiles.add(R),h.set(R,T);let _=new Set(T.map(L=>L.name)),N=new Map;for(let L of(T[0]&&c.get(T[0].featurePath))??[]){let j=sr(L,H=>_.has(H));N.set(j,Ly(N.get(j),L.status))}let F=new Map,I=new Map;for(let L of T){b.owned.add(ln(e,L.featurePath,L.displayName));let j=F.get(L.name);if(j){j.rows+=1;let U=I.get(L.name),z=U?Fn(L,U):void 0;z!==void 0&&(j.refused??=z,j.refusedRows=(j.refusedRows??0)+1);for(let V of L.tags)j.tags.includes(V)||(j.tags.push(V),u.set(V,(u.get(V)??0)+1));continue}let H=me(e,L.featurePath,L.name);b.owned.add(H),b.owned.add(xt(e,L.featurePath,L.name));let Z="missing",Q,M;if(Qt.existsSync(H))try{let U=st(H);U&&I.set(L.name,U),M=U?Fn(L,U):void 0,Z=U&&(Mr(L,U)||M!==void 0)?"valid":"stale"}catch(U){Z="invalid",Q=U instanceof $e?U.problem:U instanceof Error?U.message:String(U)}F.set(L.name,{name:L.name,line:L.line,tags:[...L.tags],outline:Object.keys(L.params).length>0,rows:1,cached:Z!=="missing",cacheState:Z,...Q?{cacheProblem:Q}:{},...M!==void 0?{refused:M,refusedRows:1}:{},proposal:Qt.existsSync(xt(e,L.featurePath,L.name)),lastStatus:N.get(L.name)});for(let U of L.tags)u.set(U,(u.get(U)??0)+1)}p.push({path:k,name:O,scenarios:[...F.values()],stepSets:m})}let g=[],S=hn(e),y=Kt(e,(R,k)=>g.push({file:Bn(e,R),problem:k})).map(({file:R,proposal:k,revision:C})=>({file:Bn(e,R),feature:k.cache.feature,scenario:k.cache.scenario,mode:k.meta.mode,createdAt:k.meta.createdAt,verified:k.meta.verified,proofError:k.meta.proofError,stale:k.meta.bound?$t(e,k,l):void 0,unbound:k.meta.bound?void 0:!0,revision:C,adaptations:k.meta.adaptations??[],narrative:k.meta.narrative,suggestedFeatureEdit:k.meta.suggestedFeatureEdit,recordedFor:k.meta.recordedFor,aiCalls:k.meta.usage?.aiCalls??0,costUsd:k.meta.usage&&kt({costUsd:k.meta.usage.costUsd??0,aiCalls:k.meta.usage.aiCalls})?k.meta.usage.costUsd:void 0,importedFrom:S[Bn(e,R)]?.revision===C?S[Bn(e,R)].from:void 0})).sort((R,k)=>R.file.localeCompare(k.file)),w;try{w=Gt(e,r,l,h)}catch{w={steps:[],stepSets:[],scannedFiles:0,scannedCaches:0}}let v=zy(e),x=vs(e,Math.max(100,n.historyLimit??30)),$=x.filter(R=>!R.partial).slice(-(n.historyLimit??30)).map(R=>({startedAt:R.startedAt,green:R.green,yellow:R.yellow,red:R.red,passRate:rr(R,R.scenarios),aiCalls:R.aiCalls,costUsd:kt(R)?R.costUsd:void 0})),E=yt.join(e,"saffron.config.json");return{tool:"saffron",version:ot(),projectRoot:e,packageInstalled:By(e),config:{file:Qt.existsSync(E)?"saffron.config.json":void 0,effective:Vd(t)},featuresDir:(yt.relative(e,s)||".").split(yt.sep).join("/"),features:p,tags:[...u.entries()].map(([R,k])=>({tag:R,scenarios:k})).sort((R,k)=>R.tag.localeCompare(k.tag)),proposals:y,unreadableProposals:g,lastRun:i?{startedAt:i.startedAt,finishedAt:i.finishedAt,totals:{...i.totals,costUsd:kt(i.totals)?i.totals.costUsd:void 0},...i.interrupted?{interrupted:!0,notRun:i.notRun}:{},reportHtml:Qt.existsSync(a)?Bn(e,a):void 0,...i.browsers?.length?{browsers:i.browsers}:{},attention:i.scenarios.filter(R=>R.status!=="green").map(R=>({feature:R.feature,scenario:R.scenario,baseScenario:sr(R,k=>p.some(C=>C.path===R.feature&&C.scenarios.some(P=>P.name===k))),status:R.status,...R.browser?{browser:R.browser}:{},error:R.status==="red"?R.error?.split(`
|
|
297
|
+
`)[0]:void 0,failedStep:(R.steps??[]).find(k=>k.status==="failed")?.gherkin??R.evidence?.find(k=>k.step)?.step,evidence:(R.evidence??[]).filter(k=>k.kind==="trace"?Qt.existsSync(yt.join(e,k.file)):Pn(e,k)!==void 0).map(k=>({kind:k.kind,file:k.file,...k.step?{step:k.step}:{},...k.sha256?{sha256:k.sha256}:{},...k.proof===!0?{proof:!0}:{},...typeof k.session=="string"?{session:k.session}:{}}))})).sort((R,k)=>R.status===k.status?0:R.status==="red"?-1:1)}:void 0,history:$,quality:uf(p,x),vocabulary:{steps:w.steps.length,recorded:w.steps.filter(R=>R.status==="recorded").length,unrecorded:w.steps.filter(R=>R.status==="unrecorded").length,stepSets:w.stepSets.length,divergent:w.steps.filter(R=>R.status==="divergent").map(R=>R.text),duplicateWordings:v.slice(0,50)},data:(()=>{let R=et(),k=[],C=new Set;for(let[P,m]of h)for(let A of m)for(let O of rn(lt(A)))if(!C.has(O)){C.add(O);try{to(O)}catch(T){k.push({ref:O,reason:T instanceof Error?T.message:String(T),feature:Bn(e,P),scenario:A.name})}}return{dir:Bn(e,R.dir),env:R.env,files:Qt.existsSync(R.dir)?Qt.readdirSync(R.dir).filter(P=>/\.(json|csv)$/.test(P)).sort():[],unresolved:k}})(),...(()=>{let R=Eo(e,r,b),k=R.unreadable.length===0;return{orphans:k?R.orphans:[],orphanScan:{complete:k,errors:R.unreadable}}})()}}function By(e){for(let t=yt.resolve(e);;t=yt.dirname(t)){if(Qt.existsSync(yt.join(t,"node_modules","saffron-ai")))return!0;if(yt.dirname(t)===t)return!1}}function zf(e){let t=e.features.reduce((i,c)=>i+c.scenarios.length,0),n=e.features.reduce((i,c)=>i+c.scenarios.filter(l=>l.cacheState==="valid"&&l.refused===void 0).length,0),r=e.features.reduce((i,c)=>i+c.scenarios.filter(l=>l.refused!==void 0).length,0),s=e.features.reduce((i,c)=>i+c.scenarios.filter(l=>l.cacheState==="stale").length,0),o=e.features.reduce((i,c)=>i+c.scenarios.filter(l=>l.cacheState==="invalid").length,0);console.log(`saffron ${e.version} \xB7 ${e.features.length} feature file(s) \xB7 ${t} scenario(s), ${n} replay from cache`+(s?`, ${s} stale (\u26A0) and will re-record`:"")+(o?`, ${o} unreadable (\u26A0): fix the file or run with --rerecord`:"")+(r?`, ${r} refused (\u2717) by a recording bound to another Examples row`:""));for(let i of e.features){let c=i.scenarios.map(l=>l.proposal?"\u25D0":l.refused!==void 0?"\u2717":l.cacheState==="valid"?"\u25CF":l.cacheState==="missing"?"\u25CB":"\u26A0").join("");console.log(` ${i.path} ${c}${i.error?` \u2717 ${i.error.split(`
|
|
298
|
+
`)[0]}`:""}`)}if(e.tags.length&&console.log(`tags: ${e.tags.map(i=>`${i.tag} (${i.scenarios})`).join(", ")}`),console.log(e.proposals.length?`${e.proposals.length} proposal(s) pending review: ${e.proposals.map(i=>i.file).join(", ")}`:"no proposals pending review",...e.unreadableProposals.map(i=>`\u26A0 proposal ${i.file} cannot be read: ${i.problem}`),...e.features.flatMap(i=>i.scenarios.filter(c=>c.cacheProblem).map(c=>`\u26A0 recording of ${i.path} \u203A ${c.name} cannot be read: ${c.cacheProblem}`)),...e.features.flatMap(i=>i.scenarios.filter(c=>c.refused!==void 0).map(c=>`\u2717 ${i.path} \u203A ${c.name} is refused on ${c.rows>1?`${c.refusedRows??1} of its ${c.rows} rows`:"this row"}: ${c.refused}`))),e.lastRun){let i=e.lastRun.totals;console.log(`last run ${e.lastRun.finishedAt}: ${i.green} passed \xB7 ${i.yellow} pending review \xB7 ${i.red} failed \xB7 ${i.costUsd===void 0?"cost not reported":`$${i.costUsd.toFixed(2)}`}${e.lastRun.interrupted?` \xB7 interrupted, ${e.lastRun.notRun} not run`:""}`)}let a=e.vocabulary;console.log(`vocabulary: ${a.steps} steps (${a.recorded} recorded, ${a.unrecorded} unrecorded), ${a.stepSets} step sets, ${a.divergent.length} divergent, ${a.duplicateWordings.length} duplicate wording group(s)`),e.orphanScan.complete?e.orphans.length&&console.log(`${e.orphans.length} recording(s) belong to no scenario: run \`saffron prune\` to see them`):console.log(`orphaned recordings not checked: ${e.orphanScan.errors[0]}`),(e.data.files.length||e.data.unresolved.length)&&console.log(`test data: ${e.data.files.length} file(s) in ${e.data.dir}/${e.data.env?` \xB7 environment "${e.data.env}"`:""}`+(e.data.unresolved.length?` \xB7 ${e.data.unresolved.length} reference(s) do not resolve: ${e.data.unresolved.map(i=>`{data:${i.ref}}`).join(", ")}`:"")),console.log(`config: ${e.config.file??"(defaults, no saffron.config.json)"}`)}var Uy=/^(<[^>]+>|\{env:[^}]+\}|\{date[^}]*\})$/;function Uf(e){return e?e.role?`${e.role}${e.name?` "${e.name}"`:e.nameRegex?` /${e.nameRegex}/`:""}`:e.label?`label "${e.label}"`:e.text?`text "${e.text}"`:e.testId?`testid ${e.testId}`:e.placeholder?`placeholder "${e.placeholder}"`:e.fallbackSelectors?.length?e.fallbackSelectors[0]:"":""}function zy(e){let t;try{t=Wt(e)}catch{return[]}let n=new Map;for(let r of t.steps.values()){if(r.actions.length===0)continue;let s=fe(r.gherkin),o=yo(s).pattern,a=[...s.matchAll(/"([^"]*)"/g)].map(p=>p[1]),i=p=>p!==void 0&&(a.includes(p)||Uy.test(p))?"\xABarg\xBB":p,c=r.actions.map(p=>{let{pageFingerprint:u,value:h,promptText:b,...g}=p;return{...g,value:i(h),promptText:i(b)}}),l=JSON.stringify(c),d=r.actions.map(p=>`${p.action}${Uf(p.target)?` ${Uf(p.target)}`:p.url?` ${p.url}`:""}`).join(" \xB7 "),f=n.get(l)??{steps:new Map,actions:d};f.steps.has(o)||f.steps.set(o,r.gherkin),n.set(l,f)}return[...n.values()].filter(r=>r.steps.size>1).map(r=>({steps:[...r.steps.values()].sort(),actions:r.actions})).sort((r,s)=>s.steps.length-r.steps.length||r.steps[0].localeCompare(s.steps[0]))}async function Hf(e,t){let n=new Hy({name:"saffron",version:ot()},{capabilities:{tools:{}}});n.setRequestHandler(Jy,async()=>({tools:[{name:"search_steps",description:"Search the project's step vocabulary. Returns known Gherkin steps with status (recorded = replays at zero tokens, divergent, unrecorded), usage counts, and source files. ALWAYS reuse an existing wording exactly instead of inventing a near-duplicate: exact step text is the replay-cache identity, so a new wording costs a fresh AI recording.",inputSchema:{type:"object",properties:{query:{type:"string",description:"Case-insensitive substring filter over step text; omit to list everything."}}}},{name:"list_step_sets",description:"List the project's StepSet definitions (named reusable step sequences from .saffron files) with their steps, defining file, and usage. Invoke one inside a scenario with a line reading exactly: StepSet <name>",inputSchema:{type:"object",properties:{}}},{name:"project_status",description:"The project overview (same data as `saffron status --json`): every feature file with its scenarios (header line, tags, outline rows, cached / proposal pending / last run status), the tag list, pending proposals with narrative and proof-replay verdict (and, for one imported from CI with `saffron import`, the run, branch and commit it came from, as importedFrom), the last run's totals, run history, vocabulary health (divergent steps, duplicate wordings proven by identical recordings) and the effective config. Call it before editing tests to see what is already recorded and what awaits review. Other scenarios reuse only accepted recordings, never a pending proposal's steps: accept a shared setup before recording more scenarios that use it.",inputSchema:{type:"object",properties:{}}}]})),n.setRequestHandler(Vy,async r=>Wy(r.params.name,r.params.arguments,e)),await n.connect(new qy)}function Wy(e,t,n){let r=a=>({content:[{type:"text",text:JSON.stringify(a,null,2)}]}),s=Ee(n),o=s.features??Er.features;if(e==="search_steps"){let a=Gt(n,o),i=typeof t?.query=="string"?t.query:void 0,c=i?vo(a,i):a;return r({steps:c.steps.map(({sessions:l,recordings:d,...f})=>f),scannedFiles:c.scannedFiles,scannedCaches:c.scannedCaches})}if(e==="list_step_sets"){let a=Gt(n,o);return r({stepSets:a.stepSets})}return e==="project_status"?r(Os(n,s)):{content:[{type:"text",text:`Unknown tool: ${e}`}],isError:!0}}import{query as Gy}from"@anthropic-ai/claude-agent-sdk";function qf(e,t){let n=t.steps.map(s=>`- [${s.status}] ${s.keyword} ${s.text}`).join(`
|
|
288
299
|
`),r=t.stepSets.map(s=>`- StepSet ${s.name}
|
|
289
300
|
${s.steps.map(o=>` ${o}`).join(`
|
|
290
301
|
`)}`).join(`
|
|
291
302
|
`);return["Draft a Saffron feature file from the requirements below.","","EXISTING STEP VOCABULARY \u2014 reuse these wordings EXACTLY (character for character) wherever they express what a step needs to do. Steps marked [recorded] or [divergent] already have replay recordings: reusing them makes the new file replay almost for free. Only invent a new wording when nothing in the vocabulary expresses the intent, and then follow the same style:",n.length>0?n:"(none yet \u2014 this is the project's first file)","",t.stepSets.length>0?`EXISTING STEP SETS \u2014 for .saffron output, invoke with a line reading exactly \`StepSet <name>\` instead of repeating their steps:
|
|
292
303
|
${r}`:void 0,"","RULES:","1. Output ONLY the feature file content \u2014 no prose, no code fences, no explanations.","2. Gherkin/.saffron syntax: Feature:, Scenario:, Scenario Outline: + Examples, Given/When/Then/And/But. Prefer concrete scenarios; use an Outline only when the requirements list variations of the same flow.","3. Then steps are assertions \u2014 state exactly what must be true, one condition per step. End every scenario with at least one Then.","4. In .saffron, reuse a StepSet for a repeated flow (first step a guard, last step an exit assertion). Definition uses a colon (StepSet: Name), invocation does not (StepSet Name). If the requirements request .feature, use standard Gherkin without StepSets or file-backed Examples.",'5. Use 2-column data tables for key/value input, header tables for lists of records, and """ doc strings for free text.',"6. Steps are natural language for an AI browser agent \u2014 never CSS selectors or code.","7. One independently testable behavior per scenario and one clear intent per step; keep necessary setup and waits without a fixed step-count limit. When translating existing tests, preserve intended coverage but split independent changes. Do not assume every intermediate value must differ from every earlier value.",'8. Name every captured value explicitly, e.g. I record the displayed price for the selected date as "beforePrice", then the displayed price for the selected date should differ from "beforePrice". Reuse that exact name; never say only "the price I noted". Capture before the change, compare the same target afterwards, and never recreate the baseline or change application state inside a final assertion.','9. Captures store text, not parsed numbers. For an amount change, capture amount-only text rather than a whole label containing currency, date or guest count. Calling a capture "numeric" does not enable arithmetic.',"10. Use observable waits from the supplied evidence: the relevant UI state or API response, not a fixed sleep or an unspecified 'finished loading'. Distinguish a selector's option code (GBP) from the price's display symbol (\xA3); selecting a currency alone does not prove prices refreshed.","11. Use {env:VAR} for secrets, existing {data:file.key} references for shared data, and named captures for changing display values. Establish the relevant starting state and document required fixtures. Do not invent data-file keys or application behavior.","12. This is a draft-only call with no browser inspection or execution. Use supplied observations and vocabulary; flag missing UI evidence, prerequisites, or uncertain expectations in Gherkin comments for inspection before recording. Never claim the draft was inspected, recorded, verified, or passed. Completion requires targeted recording, review of verified proposals for faithful assertions, acceptance, and replay with --no-agent; those happen after this call.","","REQUIREMENTS:",e.trim()].filter(s=>s!==void 0).join(`
|
|
293
|
-
`)}var
|
|
294
|
-
`}import
|
|
295
|
-
${o.name}`,r=new Set(e.map(n)),s=new Set(e);return[...e,...t.filter(o=>!s.has(o)&&r.has(n(o)))]}function
|
|
304
|
+
`)}var Vf="You are Saffron's feature-file author. You write clean, assertive Gherkin that reuses the project's exact step vocabulary. You output only file content.";async function Wf(e,t,n,r){let s={aiCalls:0,inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheCreationTokens:0,costUsd:0},o="";if(r)return await r({systemPrompt:Vf,prompt:qf(e,t),model:n,maxTurns:1,mcpServers:{},mcpToken:"",usage:s,lastOutput:i=>{o=i},finished:()=>!1}),{content:Jf(o),usage:s};let a=Gy({prompt:qf(e,t),options:{model:n,maxTurns:1,tools:[],persistSession:!1,settingSources:[],strictMcpConfig:!0,settings:{disableClaudeAiConnectors:!0},allowedTools:[],systemPrompt:Vf}});for await(let i of a)if(i.type==="assistant")for(let c of i.message.content)c.type==="text"&&(o+=c.text);else i.type==="result"&&(s.aiCalls=i.num_turns,s.costUsd=i.total_cost_usd,"usage"in i&&i.usage&&(s.inputTokens=i.usage.input_tokens??0,s.outputTokens=i.usage.output_tokens??0,s.cacheReadTokens=i.usage.cache_read_input_tokens??0,s.cacheCreationTokens=i.usage.cache_creation_input_tokens??0));return{content:Jf(o),usage:s}}function Jf(e){return e.replace(/^\s*```(?:gherkin|saffron)?\s*\n/,"").replace(/\n```\s*$/,"").trim()+`
|
|
305
|
+
`}import It from"node:fs";import{fileURLToPath as Un,pathToFileURL as $c}from"node:url";import ke from"node:path";import{createConnection as eb,ProposedFeatures as tb,TextDocuments as nb,TextDocumentSyncKind as rb,DidChangeWatchedFilesNotification as sb,WatchKind as ob,CompletionItemKind as zn,InsertTextFormat as np,DiagnosticSeverity as Ur,MarkupKind as rp}from"vscode-languageserver/node";import{TextDocument as ib}from"vscode-languageserver-textdocument";import{createRequire as ab}from"node:module";import Gf from"node:path";var Cs=class extends Error{},xc=new Set(["and","or","not","(",")"]);function Ky(e){let t=[...e.matchAll(/[(),|]|[^\s(),|]+(?:\([^\s(),|]*\))*/g)].flatMap(([s])=>{let o=/^(and|or|not)\((.*)\)$/i.exec(s);return o?[o[1],"(",o[2],")"].filter(Boolean):[s]}),n=s=>s===","||s==="|",r=[];return t.forEach((s,o)=>{let a=r.at(-1),i=t[o+1];n(s)&&(a===void 0||n(a)||a==="("||i===void 0||n(i)||i===")")||r.push(s)}),r.map(s=>n(s)?"or":xc.has(s.toLowerCase())?s.toLowerCase():s.startsWith("@")?s:`@${s}`)}function Yy(e){let t=Ky(e),n=0,r=()=>t[n],s=d=>{throw new Cs(`--filter "${e}": ${d}`)},o=!t.some(d=>d==="and"||d==="not"||d==="("||d===")"),a=()=>{let d=i();for(;r()==="or"||o&&r()!==void 0&&r()!==")";){r()==="or"&&n++;let f=i(),p=d;d=u=>p(u)||f(u)}return d},i=()=>{let d=c();for(;r()==="and";){n++;let f=c(),p=d;d=u=>p(u)&&f(u)}return d},c=()=>{let d=r();if(d===void 0)return s("expected a tag at the end");if(d==="not"){n++;let f=c();return p=>!f(p)}if(d==="("){n++;let f=a();return r()!==")"?s("missing a closing parenthesis"):(n++,f)}return xc.has(d)?s(`expected a tag, found "${d}"`):(n++,f=>f.has(d))},l=a();return n<t.length?s(xc.has(t[n])?`unexpected "${t[n]}"`:`unexpected "${t[n]}": with and, not or parentheses, join every tag with and/or`):l}function Kf(e){let t=(e===void 0?[]:Array.isArray(e)?e:[e]).map(r=>r.trim()).filter(Boolean);if(t.length===0)return;let n=t.map(Yy);return{text:t.length===1?t[0]:t.map(r=>`(${r})`).join(" or "),matches:r=>{let s=new Set(r);return n.some(o=>o(s))}}}function Yf(e,t){return t?e.filter(n=>t.matches(n.tags)):e}function Zf(e,t){return[...t??[],e]}var Zy=new RegExp(`^(.+?(?:${Xi.map(e=>e.replace(".","\\.")).join("|")})):(.+)$`),Sc=/^\d+(?::\d+)*$/;function Qf(e){let t=[],n=new Map;for(let r of e){let s=Zy.exec(r);if(!s){t.push(r);continue}let o=Sc.test(s[2])?s[2].split(":").map(Number):[s[2]];n.set(s[1],[...n.get(s[1])??[],...o])}return{plain:t,picks:n}}var dr=class extends Error{};function Xf(e,t){let n=o=>`${o.featurePath}
|
|
306
|
+
${o.name}`,r=new Set(e.map(n)),s=new Set(e);return[...e,...t.filter(o=>!s.has(o)&&r.has(n(o)))]}function ep(e){let t=e.length>10?[...e.slice(0,10),`\u2026 (${e.length} in all)`]:e;return t.length===1?t[0]:`${t.slice(0,-1).join(", ")} and ${t.at(-1)}`}function Qy(e,t,n,r){let s=n.filter(c=>c.kind==="scenario").map(c=>String(c.line)),o=s.length===0?" It has no scenarios.":` Its scenario${s.length===1?" starts at line":"s start at lines"} ${ep(s)}.`,a=c=>{throw new dr(`${e}:${t} ${c}.${o}`)};t<1&&a("is not a line: lines count from 1"),t>r&&a(`is past the end of the file, which has ${r} lines`);let i=n.filter(c=>c.start<=t).at(-1);return i?(i.kind==="background"&&a("is in the Background, which runs before every scenario, not in a scenario"),i.kind==="stepSet"&&a(`is in StepSet "${i.name}", which runs where a scenario invokes it, not in a scenario`),i.kind==="rule"&&a(`is the header of Rule "${i.name}", not a scenario`),{line:i.rows.includes(t)?t:i.line,block:i}):a("is in the feature's header, not in a scenario")}function Xy(e,t,n){let r=n.filter(a=>a.kind==="scenario"),s=r.find(a=>a.name===t);if(s)return{line:s.line,block:s};let o=r.map(a=>`"${a.name}"`);throw new dr(`${e}:${t} names no scenario.${o.length===0?" It has no scenarios.":` Its scenario${o.length===1?" is":"s are"} ${ep(o)}.`}`)}function tp(e,t,n,r){let s=new Map,o=new Map;for(let[i,c]of n){let l=Gf.resolve(t,i);if(r.has(l))continue;let{blocks:d,lineCount:f}=Zl(l,t),p=Gf.relative(t,l),u=s.get(p)??new Map;for(let h of c){if(typeof h=="string"&&!d.some(y=>y.kind==="scenario"&&y.name===h)&&e.some(y=>y.featurePath===p&&y.displayName===h)){o.set(p,(o.get(p)??new Set).add(h));continue}let{line:g,block:S}=typeof h=="number"?Qy(i,h,d,f):Xy(i,h,d);u.set(g,`${i}:${h} is in Scenario Outline "${S.name}", whose Examples have no rows yet: nothing to run`)}s.set(p,u)}let a=e.filter(i=>{let c=s.get(i.featurePath);return!c||c.has(i.line??0)||c.has(i.exampleLine??0)||o.get(i.featurePath)?.has(i.displayName)===!0});for(let[i,c]of s)for(let[l,d]of c)if(!a.some(f=>f.featurePath===i&&(f.line===l||f.exampleLine===l)))throw new dr(`${d}.`);return a}var sp=/^(\s*)(Given|When|Then|And|But|\*)\s+(.+?)\s*$/,cb=/^\s*StepSet:\s*(.+?)\s*$/,kc=/^(\s*)(StepSet)\s+([^\s:].*?)\s*$/,Rc={recorded:"\u25CF recorded: replays at zero tokens",divergent:"\u25CF divergent: same text, different recordings",unrecorded:"\u25CB written, not recorded yet"};function lb(e,t){let n=a=>new Set(a.toLowerCase().replace(/"[^"]*"/g,'"x"').split(/[^a-z0-9"<>]+/).filter(Boolean)),r=n(e),s=n(t);if(r.size===0||s.size===0)return 0;let o=0;for(let a of r)s.has(a)&&o++;return o/(r.size+s.size-o)}function op(e){try{return JSON.parse(It.readFileSync(ke.join(e,"saffron.config.json"),"utf8"))}catch{return{}}}function ip(e){try{let t=JSON.parse(It.readFileSync(ke.join(e,"saffron.config.json"),"utf8"));return typeof t.features=="string"&&t.features.trim()!==""?t.features:void 0}catch{return}}function Br(e,t){let n=ke.dirname(e),r=ke.resolve(t);for(;;){if(It.existsSync(ke.join(n,"saffron.config.json")))return n;if(n===r||ke.dirname(n)===n)return t;n=ke.dirname(n)}}function Ps(e,t,n){return e.recordings?e.recordings[dn(Ye([t],n)[0],t)]??"unrecorded":t===e.text?e.status:e.sessions?.[t]??"unrecorded"}function db(e,t,n){return`${Rc[Ps(e,t,n)]}
|
|
296
307
|
|
|
297
308
|
Used in ${e.usage} place(s): ${e.files.join(", ")}${e.fromStepSet?`
|
|
298
309
|
|
|
299
|
-
Defined in StepSet **${e.fromStepSet}**`:""}`}function
|
|
300
|
-
`),
|
|
301
|
-
`),
|
|
302
|
-
`),
|
|
303
|
-
`);return{contents:{kind:
|
|
310
|
+
Defined in StepSet **${e.fromStepSet}**`:""}`}function fp(e,t,n={}){let r=e,s=t,o=e,a=!1,i=!1,c=k=>{if(!k.startsWith("file:"))return;let C=Br(Un(k),o);if(C===r)return;y(C);let P=g.get(C);if(!P||!a||S.has(C))return v();({vocab:u,registry:h,files:b}=P);for(let m of p.all())d(m)&&R(m)},l=k=>{if(!k.startsWith("file:"))return;let C=Un(k),P=Br(C,o);g.get(P)?.files.has(C)||S.add(P)},d=k=>!k.uri.startsWith("file:")||Br(Un(k.uri),o)===r,f=eb(tb.all,process.stdin,process.stdout),p=new nb(ib),u={steps:[],stepSets:[],scannedFiles:0,scannedCaches:0},h=new Map,b=new Set,g=new Map,S=new Set,y=k=>{r=k,s=ip(k)??(It.existsSync(ke.join(k,"saffron.config.json"))?"features":t);try{let C=op(k);Mt(k,C.dataDir,ap(k,C.env))}catch(C){f.console.warn(`saffron vocabulary rebuild: ${String(C)}`)}},w,v=()=>{try{let k=ke.isAbsolute(s)?s:ke.join(r,s),C=op(r);Mt(r,C.dataDir,ap(r,C.env)),h=sn(Gn(k),r),u=Gt(r,s,h),b=new Set(ma(k)),g.set(r,{vocab:u,registry:h,files:b}),S.delete(r)}catch(k){f.console.warn(`saffron vocabulary rebuild: ${String(k)}`),{vocab:u,registry:h,files:b}=g.get(r)??{vocab:{steps:[],stepSets:[],scannedFiles:0,scannedCaches:0},registry:new Map,files:new Set}}for(let k of p.all())d(k)&&R(k)},x=()=>{clearTimeout(w),w=setTimeout(()=>{let k=r,C=new Set(p.all().filter(P=>P.uri.startsWith("file:")).map(P=>Br(Un(P.uri),o)));for(let P of g.keys())!C.has(P)&&P!==k&&g.delete(P);C.delete(k);for(let P of[...C,k])y(P),v()},300)};function $(k){let C=fe(k);return u.steps.find(P=>P.text===C)}function E(k,C){let P=$(k);return P&&Ps(P,k,C)}function R(k){let C=k.getText().split(`
|
|
311
|
+
`),P=[...mb(C),...wb(C)];if(!k.uri.endsWith(".saffron")){f.sendDiagnostics({uri:k.uri,diagnostics:P});return}let m=io(C,u.stepSets,new Set(ss(k.getText()).map(O=>O.line-1))),A=new Map;for(let O=0;O<C.length;O++){let T=C[O],_={start:{line:O,character:0},end:{line:O,character:T.length}},N=T.match(kc);N&&!h.has(N[3])&&P.push({range:_,severity:Ur.Error,source:"saffron",message:`StepSet "${N[3]}" is not defined anywhere in the project.`});let F=T.match(cb);if(F){let j=h.get(F[1]),H=ke.relative(r,Un(k.uri)).replace(/\\/g,"/");(A.has(F[1])||j&&j.file.replace(/\\/g,"/")!==H)&&P.push({range:_,severity:Ur.Error,source:"saffron",message:`StepSet "${F[1]}" is defined twice. Set names are project-wide. If this line was meant to INVOKE the set, remove the colon: "StepSet ${F[1]}".`}),A.set(F[1],O)}let I=T.trim();if(I&&!N&&!F){for(let[j]of h)if(I.toLowerCase()===j.toLowerCase()){P.push({range:_,severity:Ur.Warning,source:"saffron",message:`Did you mean "StepSet ${j}"? Invoking a step set needs the StepSet keyword, like a step needs Given/When/Then.`});break}}let L=T.match(sp);if(L&&E(L[3],m[O])!=="recorded"){let j=fe(L[3]);for(let H of u.steps)if(!(H.text===j||Ps(H,H.text,m[O])==="unrecorded")&&lb(H.text,j)>=.7){P.push({range:{start:{line:O,character:T.indexOf(L[3])},end:{line:O,character:T.length}},severity:Ur.Information,source:"saffron",message:`Similar to the ${Ps(H,H.text,m[O])} step "${H.text}" (\xD7${H.usage}). Reusing the exact wording replays at zero tokens; a new wording costs a fresh AI recording.`});break}}}f.sendDiagnostics({uri:k.uri,diagnostics:P})}f.onInitialize(k=>{if(n.rootFromClient){let C=k.workspaceFolders?.[0]?.uri??k.rootUri??void 0;if(C&&C.startsWith("file:")){let P=Un(C);It.existsSync(P)&&(o=r=P,s=ip(P)??t)}}return a=k.capabilities.workspace?.didChangeWatchedFiles?.dynamicRegistration===!0,i=k.initializationOptions?.runLenses===!0,v(),{capabilities:{textDocumentSync:rb.Incremental,completionProvider:{triggerCharacters:[" ",":","."]},definitionProvider:!0,hoverProvider:!0,...i?{codeLensProvider:{resolveProvider:!1}}:{}}}}),f.onCodeLens(k=>{let C=p.get(k.textDocument.uri);if(!i||!C||!C.uri.startsWith("file:"))return[];let P=Un(C.uri),m=fb(P,o);return m?!P.endsWith(".saffron")&&!It.existsSync(ke.join(m,"saffron.config.json"))?[]:pb(P,C.getText(),m):[]}),f.onInitialized(()=>{if(!a)return;let k=[...["**/*.saffron","**/*.feature","**/saffron.config.json","**/.saffron/cache/**","**/data/**"].map(C=>({globPattern:C})),{globPattern:"**",kind:ob.Delete}];f.client.register(sb.type,{watchers:k}).catch(()=>{a=!1})}),f.onCompletion(k=>{let C=p.get(k.textDocument.uri);if(!C)return[];c(C.uri);let P=C.getText({start:{line:k.position.line,character:0},end:k.position}),m=yb(P);if(m)return m;let A=C.getText({start:k.position,end:{line:k.position.line+1,character:0}}).replace(/\r?\n$/,"");return bb(C.uri,P,k.position.line,u,A,io(C.getText().split(`
|
|
312
|
+
`),u.stepSets,new Set(ss(C.getText()).map(O=>O.line-1)))[k.position.line])}),f.onDefinition(k=>{let C=p.get(k.textDocument.uri);if(!C)return;c(C.uri);let P=C.getText({start:{line:k.position.line,character:0},end:{line:k.position.line+1,character:0}}).replace(/\n$/,""),m=cp(P,k.position.character);if(m){let N=hb(m.ref);return N?{uri:$c(N.file).href,range:{start:{line:N.line,character:0},end:{line:N.line,character:0}}}:void 0}let A=dp(P,k.position.character);if(A){let N=up(r,A.name);return N?{uri:$c(N.file).href,range:{start:{line:N.line,character:0},end:{line:N.line,character:0}}}:void 0}let O=P.match(kc);if(!O)return;let T=h.get(O[3]);return T?{uri:$c(ke.join(r,T.file)).href,range:{start:{line:T.line-1,character:0},end:{line:T.line-1,character:0}}}:void 0}),f.onHover(k=>{let C=p.get(k.textDocument.uri);if(!C)return;c(C.uri);{let T=C.getText({start:{line:k.position.line,character:0},end:{line:k.position.line+1,character:0}}).replace(/\n$/,""),_=cp(T,k.position.character);if(_)return{contents:{kind:"markdown",value:pp(_.ref)}};let N=dp(T,k.position.character);if(N){let F=up(r,N.name),I=F?`defined in ${ke.relative(r,F.file)} (line ${F.line+1}); the value is resolved at replay and never shown here`:"not found in .env or .env.example; export it in the shell or add it to a git-ignored .env";return{contents:{kind:"markdown",value:`**{env:${N.name}}** ${I}.`}}}}let P=C.getText({start:{line:k.position.line,character:0},end:{line:k.position.line+1,character:0}}).replace(/\n$/,""),m=io(C.getText().split(`
|
|
313
|
+
`),u.stepSets,new Set(ss(C.getText()).map(T=>T.line-1)))[k.position.line],A=P.match(kc);if(A){let T=u.stepSets.find(F=>F.name===A[3]);if(!T)return;let _=Ye(T.steps,m),N=T.steps.map((F,I)=>`- ${Rc[E(F,_[I])??"unrecorded"][0]} ${F}`).join(`
|
|
314
|
+
`);return{contents:{kind:rp.Markdown,value:`**StepSet ${T.name}** expands to:
|
|
304
315
|
|
|
305
|
-
${
|
|
306
|
-
`),
|
|
307
|
-
`).
|
|
308
|
-
`)
|
|
316
|
+
${N}`}}}let O=P.match(sp);if(O){let T=$(O[3]);return T?{contents:{kind:rp.Markdown,value:db(T,O[3],m)}}:void 0}}),p.onDidOpen(k=>{if(l(k.document.uri),k.document.uri.startsWith("file:")){let C=Un(k.document.uri);Br(C,o)===r&&!b.has(C)&&x()}c(k.document.uri),R(k.document)}),p.onDidClose(k=>l(k.document.uri)),p.onDidChangeContent(k=>{c(k.document.uri),R(k.document)}),p.onDidSave(()=>x()),f.onDidChangeWatchedFiles(()=>x()),p.listen(f),f.listen()}var ub="saffron.runScenario";function fb(e,t){let n=Br(e,t),r=ke.relative(ke.resolve(t),n);return r.split(/[\\/]/)[0]===".."||ke.isAbsolute(r)?void 0:n}function pb(e,t,n){let r=ke.relative(n,e).split(ke.sep).join("/");if(r.startsWith("../")||ke.isAbsolute(r))return[];let s=ss(t);return s.flatMap(({line:o,name:a})=>{let i={start:{line:o-1,character:0},end:{line:o-1,character:0}},c=s.filter(d=>d.name===a).length>1,l=(d,f)=>{let p=a&&!Sc.test(a)&&!c?`${r}:${a}`:`${r}:${o}`;return{range:i,command:{title:d,command:ub,arguments:[{root:n,target:p,scenario:a,mode:f}]}}};return[l("\u25B6 Run scenario","run"),l("Replay only","replay"),l("Headed","headed")]})}function ap(e,t){return process.env.SAFFRON_ENV??Ki(e).SAFFRON_ENV??t}function cp(e,t){let n=/\{data:([A-Za-z0-9_.-]+)\}/g,r;for(;r=n.exec(e);)if(t>=r.index&&t<=r.index+r[0].length)return{ref:r[1],start:r.index,end:r.index+r[0].length}}var gb=e=>/^\s*Examples:/.test(e);function pp(e,t=!1){let{env:n}=et(),r=n?` (environment "${n}")`:"";try{if(t||!e.includes(".")){let{headers:a,rows:i}=no(e);return`**{data:${e}}** ${i.length} Examples row(s), columns ${a.map(c=>`\`${c}\``).join(", ")}${r}.`}let s=$n(e);return Array.isArray(qn(e))?`**{data:${e}}** a list of ${s.length}: ${s.map(a=>`"${a}"`).join(", ")}${r}. Use it with "every": replay checks each value, so adding one needs no re-record.`:`**{data:${e}}** = "${s[0]}"${r}. Resolved at replay: change the file and the next run uses the new value at zero tokens.`}catch(s){return`**{data:${e}}** does not resolve: ${s instanceof Error?s.message:String(s)}`}}function hb(e){let{dir:t,env:n}=et(),[r,...s]=e.split("."),o=[n&&`${r}.${n}.json`,`${r}.json`,n&&`${r}.${n}.csv`,`${r}.csv`].filter(Boolean),a=[...s].reverse().find(c=>!/^\d+$/.test(c)),i;for(let c of o){let l=ke.join(t,c);if(!It.existsSync(l))continue;let d=It.readFileSync(l,"utf8").split(`
|
|
317
|
+
`),f=a?d.findIndex(p=>p.includes(`"${a}"`)):0;if(f>=0)return{file:l,line:f};i??={file:l,line:0}}return i}function mb(e){let t=[];return e.forEach((n,r)=>{for(let s of n.matchAll(/\{data:([A-Za-z0-9_.-]+)\}/g)){let o=pp(s[1],gb(n));o.includes("does not resolve")&&t.push({range:{start:{line:r,character:s.index??0},end:{line:r,character:(s.index??0)+s[0].length}},severity:Ur.Error,source:"saffron",message:o.replace(/\*\*/g,"")})}}),t}var lp=ab(import.meta.url)("@cucumber/gherkin").dialects;function wb(e){let t,n=e.map(i=>{let c=/^\s*("""|```)/.exec(i)?.[1];return c&&(t===void 0||t===c)?(t=t===void 0?c:void 0,!0):t!==void 0}),r=/^\s*#\s*language:\s*(\S+)/m.exec(e.slice(0,5).join(`
|
|
318
|
+
`))?.[1]??"en",s=lp[r]??lp.en,o=[...s.given,...s.when,...s.then,...s.and,...s.but],a=(i,c)=>n[c]||/^\s*\|/.test(i)||o.some(l=>i.trimStart().startsWith(l));return e.flatMap((i,c)=>a(i,c)?[...i.matchAll(ra)].flatMap(l=>{let d=fo(l[0]),f=l.index??0;return d?[{range:{start:{line:c,character:f},end:{line:c,character:f+l[0].length}},severity:Ur.Error,source:"saffron",message:d}]:[]}):[])}function yb(e){let t=e.match(/\{data:([A-Za-z0-9_.-]*)$/);if(!t)return;let n=t[1],{dir:r}=et(),s=n.split(".");if(s.length===1)return(It.existsSync(r)?[...new Set(It.readdirSync(r).filter(a=>/\.(json|csv)$/.test(a)).map(a=>a.split(".")[0]))].sort():[]).map(a=>({label:a,kind:zn.File,detail:"data file",insertText:a}));try{let o=qn(s.slice(0,-1).join("."));return o===null||typeof o!="object"?[]:Object.entries(o).map(([a,i])=>({label:a,kind:i!==null&&typeof i=="object"?zn.Module:zn.Value,detail:Array.isArray(i)?`list of ${i.length}`:i!==null&&typeof i=="object"?"object":JSON.stringify(i),insertText:a}))}catch{return[]}}function dp(e,t){let n=/\{env:([A-Za-z_][A-Za-z0-9_]*)\}/g,r;for(;r=n.exec(e);)if(t>=r.index&&t<=r.index+r[0].length)return{name:r[1],start:r.index,end:r.index+r[0].length}}function up(e,t){for(let n of[".env",".env.example"]){let r=ke.join(e,n);if(!It.existsSync(r))continue;let o=It.readFileSync(r,"utf8").split(`
|
|
319
|
+
`).findIndex(a=>new RegExp(`^\\s*(?:export\\s+)?${t}\\s*=`).test(a));if(o!==-1)return{file:r,line:o}}}function bb(e,t,n,r,s="",o){let a=e.endsWith(".saffron"),i=t.length+s.trimEnd().length,c=h=>({start:{line:n,character:h},end:{line:n,character:i}}),l=/^\s*StepSet\s+/.exec(t);if(l&&a)return r.stepSets.map(h=>({textEdit:{range:c(l[0].length),newText:h.name},label:h.name,kind:zn.Function,detail:`step set \xB7 ${h.steps.length} step(s) \xB7 \xD7${h.usage}`,documentation:h.steps.join(`
|
|
320
|
+
`)}));let d=/^\s*(?:Given|When|Then|And|But|\*)\s+(As "[^"]+"\s+)?/,f=d.test(t)?d.exec(t+s):null;if(f&&f[0].length>t.length)return[];if(f)return r.steps.map((h,b)=>({textEdit:{range:c(f[0].length),newText:h.text},label:h.text,kind:zn.Text,detail:`${Rc[Ps(h,`${f[1]??""}${h.text}`,o)]} \xB7 \xD7${h.usage}`,sortText:String(b).padStart(5,"0"),filterText:h.text}));let u=t.replace(/^\s*/,"").trimEnd().toLowerCase().replace(/\s+/g,"");if(u.length>0&&("stepset:".startsWith(u)||u.startsWith("stepset"))&&a){let h={start:{line:n,character:t.length-t.replace(/^\s*/,"").length},end:{line:n,character:t.length}},b=[{label:"StepSet: \u2026",kind:zn.Keyword,detail:"define a reusable step set",documentation:`StepSet: Name
|
|
309
321
|
Given \u2026
|
|
310
322
|
When \u2026
|
|
311
323
|
|
|
312
|
-
Invoke it anywhere with: StepSet Name`,filterText:"step set stepset:",sortText:"0",insertTextFormat:
|
|
313
|
-
`),filterText:`step set ${
|
|
314
|
-
|
|
315
|
-
`)
|
|
316
|
-
`);for(let a of i.
|
|
317
|
-
`)
|
|
318
|
-
`);
|
|
319
|
-
`).
|
|
320
|
-
|
|
321
|
-
`),
|
|
322
|
-
`),k=p.actions.flatMap(T=>jr(T)).flatMap(T=>T===void 0?[]:[l(T,$,C).normalize("NFC")]),_=p.actions.flatMap(T=>T.each!==void 0&&!x.includes(T.each)?T.each.match(/^\{data:([^{}]+)\}$/)?.slice(1)??[]:[]).map(T=>T.toLowerCase()),v=p.actions.flatMap(T=>T.attribute!==void 0?[T.attribute]:[]),A=T=>[T,T.replace(/\s+/g,"-"),T.replace(/\s+/g,"_")].some(M=>_.some(I=>I.includes(M))||v.some(I=>va(M,"i").test(I))),O=p.actions.flatMap(T=>[T.status,T.method,T.attribute]).flatMap(T=>T===void 0?[]:[l(T,$,C).trim().toLowerCase()]),P=new Set;for(let[T,M]of Object.entries(i)){let I=M.trim().toLowerCase();h.has(T)||/\{(?:date|unique)/.test(t.params[T]??"")||I===""||!O.includes(I)||(d.push({column:T,step:m,reason:"value",...f(T)}),P.add(T))}for(let[T,M]of Object.entries(i)){if(P.has(T)||/\{(?:date|unique)/.test(t.params[T]??""))continue;let I=M.trim().toLowerCase();I.length<3||!A(I)||(d.push({column:T,step:m,reason:"glued",...f(T)}),P.add(T))}for(let{used:T,value:M}of u)if(O.includes(M))for(let I of T)P.has(I)||(d.push({column:I,step:m,reason:"reads",...f(I)}),P.add(I));for(let[T,M]of b){if(P.has(T))continue;let I=Df(c,T,M,h);I.length>0&&k.some(F=>Qn(F,M,y.has(M))&&I.some(z=>Qn(F,z,y.has(M))))?d.push({column:T,step:m,reason:"list",...f(T)}):!h.has(T)&&M.length>=3&&k.some(F=>F.includes(M.normalize("NFC")))&&d.push({column:T,step:m,reason:"glued",...f(T)})}let E=T=>d.some(M=>M.column===T&&M.step===m);for(let[T,M]of Object.entries(t.params)){let I=i[T]??"";if(E(T)||I.trim()===""||/\{(?:date|unique)/.test(M))continue;let F=Object.keys(i).filter(N=>i[N]===I&&!/\{(?:date|unique)/.test(t.params[N]??""));if(F.length>1&&r.some(N=>new Set(F.map(L=>o(N[L]??""))).size>1))continue;let z={...t.params,...Object.fromEntries(F.map(N=>[N,"\u2063another row\u2063"]))};Pn(p.actions,x,t.params,z)&&d.push({column:T,step:m,reason:"glued",...f(T)})}if(p.kind==="assertion")for(let[T,M]of Object.entries(t.params)){let I=(i[T]??"").trim();E(T)||h.has(T)||I===""||I.length>2||/\{(?:date|unique)/.test(M)||en(I,"u").test(x)||p.actions.some(F=>jr(F).some(z=>z!==void 0&&Qn(l(z,$,C),I,!1)))&&d.push({column:T,step:m,reason:"glued",...f(T)})}}),d}function Aw(e,t,n=[],r=t,s=i=>i,o=[]){let i=d=>wo(o.length>0?o:[t],d,s),a=new Map,c=d=>a.get(d)??a.set(d,wo(o.length>0?o:[t],d,u=>u)).get(d),l=Object.keys(t);return e.map((d,u)=>{let g=$a(d.gherkin,n[u]),f=[...g].filter(v=>v in t&&(r[v]??t[v])===""),p=f.length===1?`<${f[0]}>`:void 0,m=Ra(t,g,r,ka(n[u],s),i),h=Object.entries(m).map(([v,A])=>[v,A.includes("{date")?A:r[v]??A]).filter(([v,A])=>A.length>=3||A!==""&&g.has(v));if(h.length===0&&!p)return d;let w=new Set(h.filter(([v])=>g.has(v)).map(([,v])=>v)),b=(v,A)=>Ps(A,v,"gu",w.has(A)),y=(v,A,O)=>Lf(v,A,O)??mo(v,A,b,O,l),x=[...h.filter(([v])=>g.has(v))].sort((v,A)=>A[1].length-v[1].length),C=v=>v===void 0?v:x.reduce((A,[O,P])=>A.replace(va(P,"gi"),(E,T)=>`${T}<${O}>`),v),$=(v,A=O=>O)=>{if(v===void 0)return;let O=y(v,h,A),P=O.replace(Xn(l)," "),E=h.filter(([T,M])=>!/\{(?:env|data|unique|date)/.test(t[T])&&Qn(v,M,w.has(M),A(M))&&Df(c,T,M,g).some(I=>Qn(P,I,w.has(M),A(I))));return E.length===0?O:y(v,h.filter(T=>!E.includes(T)),A)},k=v=>$(v,we.pattern),R=v=>v===void 0?void 0:Ew(v,(A,O)=>$(A,we[O]),A=>mo(A,h,b,void 0,l)),_=v=>v?{...v,name:$(v.name),nameRegex:k(v.nameRegex),label:$(v.label),text:$(v.text),placeholder:$(v.placeholder),testId:$(v.testId),frame:R(v.frame),fallbackSelectors:v.fallbackSelectors?.map(A=>R(A))}:void 0;return{...d,actions:d.actions.map(v=>({...v,value:v.action==="expectDiffers"?v.value:(v.action==="fill"||at.has(v.action))&&v.value===""&&p?p:$(v.value),url:$(v.url),pattern:k(v.pattern),urlPattern:k(v.urlPattern),promptText:$(v.promptText),each:v.each!==void 0&&!d.gherkin.includes(v.each)?v.each.replace(/^\{data:([^{}]+)\}$/,(A,O)=>`{data:${x.reduce((P,[E,T])=>P.replace(va(T,"g"),(M,I)=>`${I}<${E}>`),O)}}`):v.each,status:C(v.status),method:C(v.method),attribute:C(v.attribute),target:_(v.target),toTarget:_(v.toTarget)}))}})}function Cw(e,t,n=r=>r){let r=pn(t.steps);return e.map((s,o)=>{let i=t.steps[o],a=i?.resolvedTable??i?.table,c=i?.resolvedDocString??i?.docString,l={...ze(a),...An(c)},d=new Set,u=Object.entries({...r,...l}).map(([h,w])=>{let b=n(w);return w.includes("{date")&&d.add(h),[h,b]}).filter(([h,w])=>w.length>=3&&(!d.has(h)||h in l||xa(w))),g=new Set(u.map(([,h])=>h).filter((h,w,b)=>b.indexOf(h)!==w)),f=u.filter(([,h])=>!g.has(h)).sort((h,w)=>w[1].length-h[1].length);if(f.length===0)return s;let p=(h,w=y=>y,b=!1)=>h===void 0?void 0:f.reduce((y,[S,x])=>gr(y,{[S]:x},w,b||d.has(S)),h),m=h=>h?{...h,name:p(h.name),nameRegex:p(h.nameRegex,we.pattern),label:p(h.label),text:p(h.text),placeholder:p(h.placeholder),testId:p(h.testId,void 0,!0),frame:p(h.frame,void 0,!0),fallbackSelectors:h.fallbackSelectors?.map(w=>Cn(w,(b,y)=>p(b,we[y])??b))}:void 0;return{...s,actions:s.actions.map(h=>({...h,value:h.action==="expectDiffers"?h.value:p(h.value),url:p(h.url),pattern:p(h.pattern,we.pattern),urlPattern:p(h.urlPattern,we.pattern),promptText:p(h.promptText),target:m(h.target),toTarget:m(h.toTarget)}))}})}var xa=e=>/(?<!\d)\d{4}(?!\d)/.test(e);function _w(e,t=new Date,n=[]){return e.map(r=>({...r,actions:r.actions.map(s=>hr(s,o=>Lc(o,t,n)))}))}function hr(e,t,n,r=t){let s=(l,d,u=t)=>{let g={...l};for(let f of d)typeof l[f]=="string"&&(g[f]=u(l[f]));return g},o=l=>n?n(l,"pattern"):t(l),i=l=>{let d=s(s(l,["name","label","text","placeholder","testId","frame"]),["nameRegex"],o);return l.fallbackSelectors&&(d.fallbackSelectors=l.fallbackSelectors.map(u=>n?Cn(u,n,t):t(u))),d},a=e.action==="expectDiffers"?["url","promptText"]:["value","url","promptText"],c=s(s(s(e,a),["status","method","attribute","each"],r),["pattern","urlPattern"],o);return e.target&&(c.target=i(e.target)),e.toTarget&&(c.toTarget=i(e.toTarget)),c}function Pw(e,t){if(t.length===0)return e;let n=new Map(t.map(([o,i])=>[i,o])),r=[...n.keys()].sort((o,i)=>i.length-o.length).map(je).join("|"),s=new RegExp(String.raw`(?<=^|[^A-Za-z0-9\\]|\\[A-Za-z])(?:${r})(?![A-Za-z0-9])`,"g");return e.split(/(\{(?:env|data|unique|date)[^{}]*\})/).map((o,i)=>i%2?o:o.replace(s,a=>`{env:${n.get(a)}}`)).join("")}function Ow(e,t){let n=We(t),r=Gt(st(t)),s=new RegExp(`${Ue.source}|${Ie.source}`,"g"),o=i=>i.replace(s,(a,c,l)=>(c!==void 0?n.has(c):r.has(l))?a:Tc(a));return e.map(i=>({...i,actions:i.actions.map(a=>({...hr(a,o),...a.each!==void 0?{each:a.each}:{}}))}))}function Iw(e,t,n=[]){if(t.size===0)return e;let r=ti(n,t),s=un(t,{standaloneBelow:6}),o=p=>s.mask(r(p)),i=[...t].filter(([,p])=>p.length>=Tn),a=p=>{let m=ti(n,t,we[p]),h=un(new Map(i.filter(([,b])=>b.length>=6).map(([b,y])=>[b,we[p](y)]))),w=i.filter(([,b])=>b.length<6).map(([b,y])=>[b,we[p](y)]);return b=>o(Pw(h.mask(m(b)),w))},c={quoted:a("quoted"),regex:a("regex"),pattern:a("pattern")},l=new Set(e.flatMap(p=>p.actions.flatMap(m=>[m.saveAs,m.compareTo,m.action==="expectDiffers"?m.value:void 0].filter(h=>h!==void 0)))),d=un(t,{encodings:!0}),u=new Map,g=new Set(l);for(let p of l){let m=d.mask(p);if(m===p)continue;let h=`capture-${yw("sha256").update(m).digest("hex")}`;if(g.has(h)||d.mask(h)!==h)throw new Error("Secret-bearing capture names cannot be safely distinguished. Record again with distinct capture names that contain no secrets.");g.add(h),u.set(p,h)}let f=p=>p===void 0?void 0:u.get(p)??p;return e.map(p=>({...p,actions:p.actions.map(m=>({...hr(m,o,(h,w)=>c[w](h)),...m.saveAs!==void 0?{saveAs:f(m.saveAs)}:{},...m.compareTo!==void 0?{compareTo:f(m.compareTo)}:{},...m.action==="expectDiffers"&&m.value!==void 0?{value:f(m.value)}:{}}))}))}function zf(e,t,n="",r=new Date){let s=st(t),o=ot(t),i=r,a=S=>It(Ar(jn(S,n)),i).replace(Ue,(x,C)=>o.get(C)??x),c=Object.fromEntries(Object.entries(t.params).map(([S,x])=>{try{return[S,a(x)]}catch{return[S,x]}})),l=e.map((S,x)=>$a(S.gherkin,t.steps[x])),d=l.map((S,x)=>Ra(t.params,S,c,ka(t.steps[x],a),C=>wo(t.exampleRows??[t.params],C,a))),u=Object.entries(t.params).filter(([,S])=>S.includes("{date")).map(([S,x])=>[S,x,c[S]]),g=S=>u.filter(([x,,C])=>x in(d[S]??{})&&(l[S]?.has(x)||xa(C))),f=Aw(Cw(Ow(e,t),t,S=>It(Ar(jn(S,n)),i)),t.params,t.steps,c,a,t.exampleRows),p=[...s,...Cr(s),...o.values()],m=f.map((S,x)=>{let C=u.filter(([$,,k])=>l[x]?.has($)||xa(k)).map(([,,$])=>$);return _w([S],i,[...p,...C])[0]}),h=Iw(Nw(Mw(m,Zn(s)),ir(s,n)),o,s),w=Object.fromEntries(Object.entries(t.params).filter(([,S])=>!S.includes("{date")&&/\{(?:env|data|unique):/.test(S))),b=Object.keys(t.params),y=jw(h,t);return Object.keys(w).length===0&&u.length===0?y:y.map((S,x)=>{let C=g(x),$={...Object.fromEntries(Object.entries(w).filter(([O])=>O in(d[x]??{}))),...Object.fromEntries(C.map(([O,P])=>[O,P]))},k=Object.fromEntries(C.filter(([,,O])=>!O.includes("{date")).map(([O,,P])=>[O,P])),R=Object.entries(k).filter(([,O])=>O.length<3),_=(O,P)=>{let E=R.find(([,T])=>O===(P?P(T):T));return E?`<${E[0]}>`:gr(O,k,P,!0,b)},v=O=>_(gr(O,$,void 0,!1,b)),A=(O,P)=>{let E=gr(O,$,void 0,!1,b);return(P==="pattern"?Lf(E,R):void 0)??_(E,we[P])};return{...S,actions:S.actions.map(O=>hr(O,v,A))}})}function Hf(e){let t=e.steps.map(o=>[o.text,...o.table?.flat()??[],o.docString??""]),n=t.flat(),r=t.map(()=>new Map),s=new Map;return t.forEach((o,i)=>{for(let a of o)for(let[c,l]of a.matchAll(/\{data:([^{}]*<[^<>{}]+>[^{}]*)\}/g)){let d=!0,u=`{data:${l.replace(/<([^<>]+)>/g,(g,f)=>{let p=e.params[f];return(p===void 0||/[{}<>]/.test(p))&&(d=!1),p??""})}}`;if(!(!d||n.some(g=>g.includes(u))))for(let g of[r[i],s])(g.get(u)??g.set(u,new Set).get(u)).add(c)}}),{own:r,all:s}}function jw(e,t){let{own:n,all:r}=Hf(t),s=i=>[...i].filter(([,a])=>a.size===1).map(([a,c])=>[a,[...c][0]]),o=s(r);return o.length===0&&n.every(i=>i.size===0)?e:e.map((i,a)=>{let c=new Map([...o,...s(n[a]??new Map)]);if(c.size===0)return i;let l=d=>{let u=d;for(let[g,f]of c)u=u.split(g).join(f);return u};return{...i,actions:i.actions.map(d=>hr(d,l,u=>l(u)))}})}function Nw(e,t){if(t.size===0)return e;let n=r=>typeof r=="string"?Cl(r,t):Array.isArray(r)?r.map(n):r&&typeof r=="object"?Object.fromEntries(Object.entries(r).map(([s,o])=>[s,s==="pageFingerprint"?o:n(o)])):r;return e.map(r=>({...r,actions:r.actions.map(s=>n(s))}))}function Mw(e,t){return t.size===0?e:e.map(n=>{let r=new Set([...n.gherkin.matchAll(Ie)].map(d=>d[1])),s=d=>Zo(d,t,r),o=d=>new Map([...t].filter(([,u])=>u.length>=4).map(([u,g])=>[u,we[d](g)])),i={quoted:o("quoted"),regex:o("regex"),pattern:o("pattern")},a=d=>d.split(/(\{(?:env|data|unique|date)[^{}]*\})/).map((u,g)=>g%2?u:s(u)).join(""),c=(d,u)=>a(Zo(d,i[u],r)),l=d=>{let u=[...t].filter(([g,f])=>r.has(g)&&f===d);return u.length===1?`{data:${u[0][0]}}`:d};return{...n,actions:n.actions.map(d=>hr(d,s,c,l))}})}function qf(e,t,n){if(e!=="mcp__playwright__browser_tabs")return;let r=t??{},s=typeof r.index=="number"?String(r.index):void 0;switch(r.action){case"select":return s===void 0?void 0:{action:"switchTab",value:s};case"close":return s===void 0?{action:"closeTab"}:{action:"closeTab",value:s};case"new":return typeof r.url=="string"&&r.url?{action:"newTab",url:Fr(r.url,n)}:{action:"newTab"};default:return}}function Vf(e,t){let n=t??{};if(e==="mcp__playwright__browser_handle_dialog"){let r={action:"handleDialog",value:n.accept?"accept":"dismiss"};return typeof n.promptText=="string"&&n.promptText&&(r.promptText=n.promptText),r}if(e==="mcp__playwright__browser_file_upload"){let r=Array.isArray(n.paths)?n.paths:[];if(r.length===0)return;let s=Ve().root+ww.sep;return{action:"uploadFile",value:r.map(i=>typeof i=="string"&&i.startsWith(s)?i.slice(s.length):i).join(`
|
|
323
|
-
`)
|
|
324
|
-
`)
|
|
325
|
-
|
|
326
|
-
`)
|
|
327
|
-
`)[0];throw new pt(`${this.options.device?`--device "${this.options.device}"`:"--viewport"} cannot run in ${t}: ${s}`)}}}async stop(){await this.browser?.close(),this.browser=void 0}resolveStorageState(t=this.options.storageState){if(!t)return;let n=ut.isAbsolute(t)?t:ut.join(this.options.projectRoot,t);if(!zt.existsSync(n))throw new pt(`storageState file not found: ${n}. Generate one with: npx playwright open --save-storage=${t} <url>`);return n}contextOptions(t){let{defaultBrowserType:n,...r}=this.options.device?Ea[this.options.device]??{}:{},s=t===void 0?void 0:this.options.sessions?.[t]?.storageState;return{storageState:this.resolveStorageState(s??this.options.storageState),...r,...this.options.viewport?{viewport:this.options.viewport}:{}}}artifacts(t){let n=tn(this.options.projectRoot,t.featurePath,t.displayName);return this.options.artifactsPerBrowser?ut.join(n,this.options.browser??"chromium"):n}buildCandidateCache(t,n){let r={version:1,feature:t.featurePath,scenario:t.name,recordedAt:new Date().toISOString(),recordedBy:"agent",steps:n,...Jf(t,n)};return{...r,version:Mr(r)}}tabWatcher(){return t=>{let n=r=>t(r);return this.tabListeners.add(n),()=>{this.tabListeners.delete(n)}}}async newContext(t,n){let r=await this.browser.newContext(this.contextOptions(t||void 0));return r.on("page",()=>{if(!this.openingOwnPages.has(r))for(let s of this.tabListeners)s(t)}),this.armDialogs?.(r),n&&this.options.trace!==void 0&&this.options.trace!=="off"&&await Zl(r,n),r}sessionsFor(t,n,r){return new bo(n,de(t.steps[0]?.session),s=>this.newContext(s,`${r} \xB7 session "${Ge(s)}"`),async s=>{this.openingOwnPages.add(s);try{return await s.newPage()}finally{this.openingOwnPages.delete(s)}})}sessionHooks(t,n,r){return{sessionPage:n.pageOf,onActiveTab:(s,o)=>n.selectTab(o,s),takeFingerprint:async s=>qs(Ta(n,s)??r)}}namedSession(t,n){return gn(n)?{session:Ge(t.mainKey)}:{}}async saveSessionTraces(t,n,r,s){let o=[],i=ot(t),a=new Set;for(let[c,l]of n.opened()){if(!r){await Gs(l).catch(()=>{});continue}let d=Pr(Ge(c));for(let f=2;a.has(d);f++)d=`${Pr(Ge(c))}-${f}`;a.add(d);let u=ut.join(this.artifacts(t),`${r}.${d}.zip`),g=await Ks(l,u,i);g&&(this.claimArtifactDir(t),o.push({...s,kind:"trace",file:Ae(this.options.projectRoot,u),sha256:g,session:Ge(c)}))}return o}async proofReplay(t,n,r,s){let o=this.options.trace!==void 0&&this.options.trace!=="off",i=s?t.displayName:`${t.displayName} (proof replay)`,a=await this.newContext(de(t.steps[0]?.session),i),c=this.sessionsFor(t,a,i),l=await a.newPage();return{result:await Vr(l,t,n,{sessions:c.pages,openSession:c.pageOf,baseURL:this.options.baseURL,actionTimeoutMs:this.options.actionTimeoutMs,retries:this.options.retries,pollIntervalMs:this.options.pollIntervalMs,uniqueSeed:r,trace:o,tracePhase:s}),context:a,page:l,sessions:c}}async runScenario(t,n={}){let r=await this.runScenarioInner(t,n),s=ot(t);if(s.size>0){let o=a=>a===void 0?a:it(a,s);r.error=o(r.error),r.narrative=o(r.narrative),r.proofError=o(r.proofError),r.suggestedFeatureEdit=o(r.suggestedFeatureEdit),r.adaptations=r.adaptations.map(a=>it(a,s));let i=[r.stepResults,r.executionStepResults,...(r.evidence??[]).map(a=>a.traceSteps)];for(let a of i.flatMap(c=>c??[])){a.error=o(a.error);for(let c of a.tabs??[])c.url=it(c.url,s);for(let c of a.responses??[])c.url=it(c.url,s)}}return r}async screenshot(t,n,r,s){let o=this.options.screenshot??"viewport";if(o!=="off")try{let i=this.artifacts(n);this.claimArtifactDir(n);let a=ut.join(i,`${r}.jpg`),c=await t.screenshot({path:a,type:"jpeg",quality:80,fullPage:o==="full-page",timeout:5e3});return{kind:r,file:Ae(this.options.projectRoot,a),step:s,sha256:At(c)}}catch{return}}claimArtifactDir(t){let n=tn(this.options.projectRoot,t.featurePath,t.displayName);zt.mkdirSync(this.artifacts(t),{recursive:!0}),zt.writeFileSync(ut.join(n,On),JSON.stringify({feature:t.featurePath,scenario:t.displayName},null,2))}async runScenarioInner(t,n={}){if(!this.browser)throw new Error("Orchestrator not started");let r=Date.now(),{projectRoot:s,baseURL:o,actionTimeoutMs:i,retries:a,pollIntervalMs:c}=this.options,l=fe(s,t.featurePath,t.name),d;try{d=He(l)}catch(E){if(!(E instanceof ge))throw E;return{scenario:t,status:"red",source:"cache",stepResults:[],adaptations:[],usage:an,durationMs:Date.now()-r,error:`The recording cannot be read: ${E.problem}. Fix the file, or re-record it with saffron run --rerecord.`}}let u=ct(s,t.featurePath,t.name),g=Ae(s,u),f,p;if(zt.existsSync(u))try{({proposal:f,revision:p}=Ls(u))}catch(E){if(!(E instanceof ge)&&E.code!=="ENOENT")throw E;f=void 0}let m=!1;f&&!vl(s,u,p)&&(m=!this.options.rerecord,f=void 0),f&&dt(s,f,t)&&(f=void 0),f&&this.options.rerecord&&this.filedThisRun.get(u)!==p&&cr(t,f.cache)&&(f=void 0);let h=d&&cr(t,d)||f&&cr(t,f.cache);if(h)return{scenario:t,status:"red",source:"cache",stepResults:[],adaptations:[],usage:an,durationMs:Date.now()-r,error:h};let w=E=>E.status==="stale"?"the committed recording no longer matches the scenario":`the committed recording failed${E.failure?` at "${E.failure.stepText}"`:""}`,b=E=>{let T=on(s)[g],M=T?.revision===p?` from ${ue(ns(T.from))}`:"",I=E?w(E):"";return{scenario:t,status:"yellow",source:d?"cache":"agent-record",stepResults:E?.stepResults??[],narrative:(I?`${I[0].toUpperCase()}${I.slice(1)}. `:"")+`A proposal${M} is pending review at ${g}. It was not filed on this machine, so this run does not replay it, heal or record over it. Review it with saffron diff ${g}, then saffron accept or saffron reject it.`,adaptations:[],proposalFile:g,proposalRevision:p,usage:an,durationMs:Date.now()-r}};if(zt.rmSync(this.artifacts(t),{recursive:!0,force:!0}),this.options.artifactsPerBrowser){let E=tn(s,t.featurePath,t.displayName);for(let T of zt.existsSync(E)?zt.readdirSync(E,{withFileTypes:!0}):[])T.isFile()&&T.name!==On&&zt.rmSync(ut.join(E,T.name),{force:!0})}if(m&&!d)return b();let y=(E,T)=>({scenario:t,status:"yellow",source:"agent-record",proposalReplay:!0,stepResults:E.stepResults,narrative:`Replayed the pending proposal recorded for "${f.meta.recordedFor??t.name}" at zero AI${T?` instead of ${T.status==="stale"?"recording":"healing"} again: ${w(T)}`:""}; accept it to go green.`,adaptations:[],verified:!0,proposalFile:g,proposalRevision:p,usage:an,durationMs:Date.now()-r}),S=this.options.trace??"off",x=S!=="off",C=await this.newContext(de(t.steps[0]?.session),t.displayName),$=this.sessionsFor(t,C,t.displayName),k=!x,R,_,v=await C.newPage(),A=wn(),O=[],P=(E,T)=>this.screenshot(E,t,"before-heal",T.stepText).then(M=>{M&&O.push(M)});try{let E=await(async()=>{let I;if(f&&!d){let U=await Vr(v,t,f.cache,{sessions:$.pages,openSession:$.pageOf,baseURL:o,actionTimeoutMs:i,retries:a,pollIntervalMs:c,uniqueSeed:A,trace:x,tracePhase:"pending"}),Y=f.meta.recordedFor??t.name;if(U.status==="passed")return y(U);if(Object.keys(t.params).length>0&&Y!==t.displayName){let Z=U.failure;return{scenario:t,status:"red",source:"agent-record",proposalReplay:!0,stepResults:U.stepResults,adaptations:[],proposalFile:g,proposalRevision:p,usage:an,durationMs:Date.now()-r,error:`The pending proposal recorded for "${Y}" does not replay for this Examples row`+(Z?` (step "${Z.stepText}": ${Z.error.split(`
|
|
328
|
-
`)[
|
|
329
|
-
`)[
|
|
330
|
-
`)
|
|
331
|
-
`)[0]}
|
|
332
|
-
`)[0]}`,gt=I.failure.stepIndex,rt=I.stepResults.map((Re,Tr)=>Tr===gt?{...Re,status:"failed",error:qt}:Re);return{scenario:t,status:"red",source:"agent-heal",stepResults:rt,executionStepResults:rt.map((Re,Tr)=>Tr>gt&&Re.status==="skipped"?{...Re,status:"passed"}:Re),narrative:L.narrative,adaptations:L.adaptations,suggestedFeatureEdit:L.suggestedFeatureEdit,usage:L.usage,durationMs:Date.now()-r,error:qt}}finally{G?.detach()}}return G?.detach(),await this.finalizeAgentRun(t,L,z,d,r,N,z?I?.failure:void 0,A)})(),T=O.find(I=>I.kind==="before-heal");if(E.source==="cache"&&T){let I=T.file.replace(/before-heal\.jpg$/,"failure.jpg");try{zt.renameSync(ut.join(s,T.file),ut.join(s,I)),T.file=I}catch{}T.kind="failure"}else if(E.status==="red"){let I=E.stepResults.findIndex(L=>L.status==="failed"),F=E.stepResults[I]?.gherkin,z=de(t.steps[Math.max(I,0)]?.session),N=await this.screenshot(Ta(_??$,z)??v,t,"failure",F);N&&O.push(N)}let M=ir(st(t),A);if(M.size>0&&(E.uniques=Object.fromEntries(M)),O.push(...E.evidence??[]),x){let F=S==="on"||E.status!=="green"?ut.join(this.artifacts(t),_i):void 0;k=!0;let z=R??C;F||await Gs(z).catch(()=>{});let N=F?await Ks(z,F,ot(t)):void 0,L=ot(t),G=(E.executionStepResults??E.stepResults).map(V=>({...V,error:V.error&&it(V.error,L)})),U=_??$,Y=await this.saveSessionTraces(t,U,F&&N?ut.basename(F,".zip"):void 0,{traceSteps:G});F&&N&&(this.claimArtifactDir(t),O.unshift({kind:"trace",file:Ae(s,F),sha256:N,traceSteps:G,...this.namedSession(U,t.steps)},...Y))}return O.length>0&&(E.status!=="green"||O.some(I=>I.kind==="trace"))&&(E.evidence=O),E}finally{k||await Gs(C).catch(()=>{}),await _?.close(),await R?.close(),await $.close(),await C.close()}}async finalizeAgentRun(t,n,r,s,o,i=0,a,c=wn()){let l=r?"agent-heal":"agent-record",d=n.success?n.recordedSteps.map(N=>({gherkin:N.gherkin,kind:N.kind,status:"passed"})):Xf(n.recordedSteps,n.announcedSteps??[],a&&{stepIndex:a.stepIndex,error:a.error},n.narrative);if(!n.success)return{scenario:t,status:"red",source:l,stepResults:d,narrative:n.narrative,adaptations:n.adaptations,usage:n.usage,durationMs:Date.now()-o,error:n.narrative};let u=r?Wf(s.steps,n.recordedSteps,this.options.assertionPolicy==="adaptable-mid",a?{stepIndex:a.stepIndex,actionIndex:a.actionIndex}:void 0):n.recordedSteps,g=[...n.adaptations,...r&&a?Gf(n.recordedSteps,a.stepIndex):[]],f={...n.usage},p,m,h,w,b=[],y=0,S=new Set,x,C=async({context:N,sessions:L},G,U=G.stepResults)=>{if(!S.has(N)){S.add(N);try{if(this.options.trace&&this.options.trace!=="off"){let Y=`proof-${++y}`,V=ut.join(this.artifacts(t),`${Y}.zip`),Z=ot(t),oe=await Ks(N,V,Z),ve=G.captured[wt],qt=ve?ir(st(t),ve):new Map,gt={proof:!0,traceSteps:U.map(Re=>({...Re,error:Re.error&&it(Re.error,Z)})),traceUniques:qt.size?Object.fromEntries(qt):void 0},rt=await this.saveSessionTraces(t,L,oe?Y:void 0,gt);oe&&(this.claimArtifactDir(t),b.push({kind:"trace",file:Ae(this.options.projectRoot,V),sha256:oe,...gt,...this.namedSession(L,t.steps)},...rt))}}finally{await L.close(),await N.close()}}};if(this.options.verifyProposals!==!1){let N=await this.proofReplay(t,this.buildCandidateCache(t,u),wn());w=N.result.captured[wt];try{if(N.result.status!=="passed"&&N.result.failure){let L=N.result.failure;if(this.options.agent&&!(r&&L.kind==="assertion"&&(this.options.assertionPolicy!=="adaptable-mid"||vo(s.steps,L.stepIndex))))try{let U=N.sessions.contextOf(de(t.steps[L.stepIndex]?.session))??N.context,Y=await yo(this.browser,N.result.activePage??mr(U,L.pageUrl)??N.page,N.sessions.contexts()),V=await this.withDialogsVisible(()=>this.options.agent.run({scenario:t,baseURL:this.options.baseURL,traceContext:this.options.trace&&this.options.trace!=="off"?N.context:void 0,mode:"refine",model:r?this.options.healModel:void 0,cdpEndpoint:this.cdpEndpoint,projectRoot:this.options.projectRoot,assertionPolicy:this.options.assertionPolicy,completedSteps:N.result.stepResults.filter(Z=>Z.status==="passed").map(Z=>Z.gherkin),failedStep:{text:L.stepText,kind:L.kind,error:L.error,pageUrl:L.pageUrl,stepIndex:L.stepIndex},liveTab:Y,uniqueSeed:N.result.captured[wt],onTabOpened:this.tabWatcher(),...this.sessionHooks(t,N.sessions,N.page)}));f=Kf(f,V.usage),x=qw(N.result.stepResults,L,V),V.success&&(g.push(...V.adaptations),g.push(...Gf(V.recordedSteps,L.stepIndex)),u=r?Wf(u,V.recordedSteps,this.options.assertionPolicy==="adaptable-mid",{stepIndex:L.stepIndex,actionIndex:0}):Hw(u,V.recordedSteps,L.stepIndex),await C(N,N.result,x),x=void 0,N=await this.proofReplay(t,this.buildCandidateCache(t,u),wn()),w=N.result.captured[wt])}catch{}}for(let L of N.result.tabOpeners??[]){let G=u[L.stepIndex]?.actions[L.actionIndex];G&&(G.opensTab=!0)}p=N.result.status==="passed",p||(m=N.result.failure?.error??`proof replay ${N.result.status}`,h=N.result.stepResults)}finally{await C(N,N.result,x).catch(()=>{})}}r&&s&&g.push(...zw(s.steps,u,a,this.options.baseURL));let $=N=>r&&t.steps[N]?.kind==="assertion"&&(this.options.assertionPolicy!=="adaptable-mid"||vo(s.steps,N)),k=n.featureEdits.filter(N=>!$(N.index));for(let N of fl(u,Nt(this.options.projectRoot)))g.push(`duplicate wording: "${N.from}" recorded exactly the same actions as the existing step "${N.to}" (${N.feature} \u203A ${N.scenario}). Accept with --with-feature-edit to converge on the canonical wording.`),k.some(L=>L.index===N.index)||k.push({index:N.index,text:N.to});let R=Bf(u);R.length>0&&(p=!1,m=[m,...R].filter(Boolean).join(" "));let _=ot(t),v=N=>_.size>0?it(N,_):N;g=g.map(v);let A=k.map(N=>({index:N.index,text:v(N.text)})),O=v(n.narrative),P=n.suggestedFeatureEdit?v(n.suggestedFeatureEdit):void 0,E={version:1,feature:t.featurePath,scenario:t.name,recordedAt:new Date().toISOString(),recordedBy:"agent",steps:u,...Jf(t,u)},T={...E,version:Mr(E)},M={meta:{createdAt:T.recordedAt,mode:r?"heal":"record",narrative:O,adaptations:g,suggestedFeatureEdit:P,featureEdits:A.length>0?A:void 0,verified:p,proofError:m?v(m):void 0,seededSteps:i>0?i:void 0,recordedFor:t.displayName,usage:f,bound:wd(t,s,T,A.length>0?A:void 0)},cache:T},I=ct(this.options.projectRoot,t.featurePath,t.name),F=wl(I,M);xl(this.options.projectRoot,I,F),this.filedThisRun.set(I,F);let z=He(fe(this.options.projectRoot,t.featurePath,t.name));return{proposalDiff:bn(z,M.cache),scenario:t,status:"yellow",source:l,stepResults:h??d,executionStepResults:d,evidence:b,proofUniques:(()=>{let N=w?ir(st(t),w):void 0;return N&&N.size>0?Object.fromEntries(N):void 0})(),narrative:O,adaptations:g,suggestedFeatureEdit:P,featureEdits:A.length>0?A:void 0,verified:p,proofError:m,seededSteps:i>0?i:void 0,proposalFile:Ae(this.options.projectRoot,I),proposalRevision:F,usage:f,durationMs:Date.now()-o}}};import jo from"node:fs";import qy from"node:os";import _u from"node:path";import{query as hy}from"@anthropic-ai/claude-agent-sdk";import{McpServer as Vw}from"@modelcontextprotocol/sdk/server/mcp.js";import{z as X}from"zod";var De=e=>({content:[{type:"text",text:e}]});function yr(e,t,n,r){let s=async o=>{let i=await r(o);return i.content[0]?.text.startsWith("ERROR:")?{...i,isError:!0}:i};return o=>{o.registerTool(e,{description:t,inputSchema:n},s)}}function Jw(e){let t=new Vw({name:e.name,version:e.version});for(let n of e.tools)n(t);return{type:"sdk",name:e.name,instance:t}}function eu(e){let t={};return e.role&&(t.role=e.role),e.name&&(t.name=e.name),e.nameRegex&&(t.nameRegex=e.nameRegex),e.label&&(t.label=e.label),e.text&&(t.text=e.text),e.selector&&(t.fallbackSelectors=[e.selector]),e.frame&&(t.frame=e.frame),Object.keys(t).length>0?t:void 0}var Ww=new Set(["main","banner","contentinfo","status","alert","alertdialog","dialog","search"]);function tu(e){if(!e?.role)return;let{role:t,frame:n,...r}=e;if(!(Object.keys(r).length>0||Ww.has(t)))return`ERROR: role="${t}" alone matches every ${t} on the page, and replay would use the first one. Add a name (or nameRegex), text, label or selector that picks exactly the element you checked, then call again.`}function Gw(e,t){return t.index>=e.steps.length?`ERROR: there is no step ${t.index}: this scenario's steps are numbered from 0 to ${e.steps.length-1}. Call saffron_step again with the zero-based index of the step you are about to perform.`:(e.announce(t.index,t.text,t.adaptation),t.index<e.firstStep?`Step ${t.index} already ran before you took over and keeps its recording; nothing you do under it is recorded. Do not redo it: continue from step ${e.firstStep} on the page as it is.`:`Recording step ${t.index}: ${t.text}`)}var nu=new WeakSet;function Kw(e,t){if(t.success&&!nu.has(e)){let n=[...e.announced].filter(r=>r>=e.firstStep&&e.steps[r]?.kind==="assertion"&&!e.steps[r].actions.some(s=>at.has(s.action))).sort((r,s)=>r-s);if(n.length>0)return nu.add(e),`ERROR: not finalized. Assertion step ${n.join(", ")} recorded no check, so replay would verify nothing. Record what you verified with saffron_assert under that step (saffron_step first if you moved on), then call saffron_done again. If the condition does not hold, call saffron_done with success=false.`}return e.done=!0,e.success=t.success,e.narrative=t.narrative,e.suggestedFeatureEdit=t.suggestedFeatureEdit,e.featureEdits=(t.featureEdits??[]).filter(n=>!di.test(n.text)&&n.text.trim()!==""),"Run finalized."}var ru={role:X.string().optional().describe("ARIA role of the element"),name:X.string().optional().describe("Accessible name \u2014 use the SHORTEST stable substring; never include volatile content like prices or dates"),nameRegex:X.string().optional().describe("Regex for the accessible name when it embeds volatile content, e.g. 'Select \\\\{date\\\\+1\\\\} as checkin' cannot work \u2014 instead use nameRegex 'Select .* as checkin'"),label:X.string().optional().describe("Form-label text for getByLabel \u2014 the literal <label> text only, never a free-text description"),text:X.string().optional().describe("getByText locator text"),selector:X.string().optional().describe("CSS fallback selector"),frame:X.string().optional().describe(`CSS selector of the iframe hosting the element, e.g. 'iframe[title="Feedback widget"]' \u2014 REQUIRED whenever the element lives inside an iframe; without it replay looks only at the top-level page`)};function So(e){return Jw({name:"saffron",version:"0.1.0",tools:[yr("saffron_step","Announce the Gherkin step you are about to perform. MUST be called before executing browser actions for each step, with the step's zero-based index and exact text.",{index:X.number().int().min(0),text:X.string(),adaptation:X.string().optional().describe("If the written step does not match the real UI and you are deviating from it, describe the deviation in one sentence: the kind of change (a locator or label change on the same page, a page removed or merged, a page added or flow reordered) and the page it happened on.")},async t=>De(Gw(e,t))),yr("saffron_capture",`Record a captureText action for the current step: at replay time, the target element's text is read and stored under saveAs for later expectDiffers comparisons. Use for steps like 'I record the displayed price as "X"'. The target must select exactly the element whose text is the value.`,{saveAs:X.string().describe("Name to store the captured text under"),...ru},async t=>{let n=eu(t);if(!n)return De("ERROR: capture needs a target (role/name, nameRegex, label, text, or selector).");let r=tu(n);return r?De(r):(e.addActions([{action:"captureText",target:n,saveAs:t.saveAs}]),De(`Capture recorded as "${t.saveAs}".`))}),yr("saffron_dialog","Record how a native dialog (alert/confirm/prompt) must be handled at replay. Call this IMMEDIATELY whenever an action triggers a native dialog \u2014 whether you handled it via browser_handle_dialog or the browser reported it as already handled. At replay Saffron arms this handler BEFORE the triggering action, so without this call the replay will auto-dismiss the dialog and diverge from what you saw.",{accept:X.boolean().describe("true = accept/OK the dialog, false = dismiss/cancel"),promptText:X.string().optional().describe("Text typed into a prompt() before accepting")},async t=>(e.addArmedAction({action:"handleDialog",value:t.accept?"accept":"dismiss",...t.promptText?{promptText:t.promptText}:{}}),De(`Dialog handling recorded (${t.accept?"accept":"dismiss"}).`))),yr("saffron_wait_api","Record a network wait for the current step: replay will block until a matching API response is observed (responses from the triggering step count). Call AFTER you verified via browser_network_requests that the response actually occurred with the expected status/body. Use a path-only urlPattern regex and never literal volatile IDs (/api/orders/\\d+, not /api/orders/8842).",{urlPattern:X.string().describe("Regex matched against the response URL \u2014 path-only for portability"),method:X.string().optional().describe("HTTP method to match (any if omitted)"),status:X.string().optional().describe("Expected status \u2014 exact ('201') or class ('2xx'); default any 2xx"),bodyPattern:X.string().optional().describe(`Regex the response body must match, e.g. '"status"\\s*:\\s*"READY"' for polling waits`)},async t=>(e.addActions([{action:"waitForResponse",urlPattern:t.urlPattern,...t.method?{method:t.method}:{},...t.status?{status:t.status}:{},...t.bodyPattern?{pattern:t.bodyPattern}:{}}]),De("Network wait recorded."))),yr("saffron_assert","Record a verified assertion for the current Then step. Call ONLY after you have confirmed the condition holds via a page snapshot. If the condition does NOT hold, do not call this \u2014 call saffron_done with success=false instead. NEVER record volatile content (prices, dates, counters) as literal expected text \u2014 use kind=matches with a pattern, or kind=differs against captured values.",{kind:X.enum(["visible","notVisible","text","url","value","differs","matches","attribute","response","each"]),...ru,expected:X.string().optional().describe("Expected text/value for kind=text|value \u2014 stable text only, never volatile values"),url:X.string().optional().describe("URL substring for kind=url (path only, no host)"),pattern:X.string().optional().describe("kind=matches|attribute: regex the target's text (or attribute) must match, e.g. 'NOK [\\\\d,]+' for a price"),attribute:X.string().optional().describe("kind=attribute: attribute name to check, e.g. 'href' for link-target assertions \u2014 use this for 'X should link to Y' instead of clicking through"),capture:X.string().optional().describe("kind=differs: name of the captured value on the LEFT of the comparison (omit when comparing the target element's live text)"),urlPattern:X.string().optional().describe("kind=response: regex matched against the response URL \u2014 path-only for portability, never literal volatile IDs (use /api/orders/\\d+)"),method:X.string().optional().describe("kind=response: HTTP method to match (any if omitted)"),status:X.string().optional().describe("kind=response: expected status \u2014 exact ('201') or class ('2xx'); default any 2xx"),bodyPattern:X.string().optional().describe("kind=response: regex the response body must match (verify via browser_network_requests first)"),each:X.string().optional().describe("kind=each: the data-list token exactly as the step writes it, e.g. '{data:enums.OrderStatus}'. The target is the CONTAINER (dropdown, table, list) that must show every value of that list. Never pass the values themselves."),compareTo:X.string().optional().describe("kind=differs: name of the captured value to compare against")},async t=>{let n=eu(t),r=tu(n);if(r)return De(r);let s;switch(t.kind){case"visible":s={action:"expectVisible",target:n};break;case"notVisible":s={action:"expectNotVisible",target:n};break;case"text":s={action:"expectText",target:n,value:t.expected??""};break;case"value":s={action:"expectValue",target:n,value:t.expected??""};break;case"url":s={action:"expectUrl",url:t.url??""};break;case"differs":if(!t.compareTo)return De("ERROR: kind=differs requires compareTo.");if(!t.capture&&!n)return De("ERROR: kind=differs needs either capture (a stored name) or a target element.");s={action:"expectDiffers",target:n,value:t.capture,compareTo:t.compareTo};break;case"matches":if(!t.pattern)return De("ERROR: kind=matches requires pattern.");s={action:"expectMatches",target:n,pattern:t.pattern};break;case"attribute":if(!t.attribute||!t.pattern)return De("ERROR: kind=attribute requires attribute and pattern.");s={action:"expectAttribute",target:n,attribute:t.attribute,pattern:t.pattern};break;case"each":if(!t.each||!/^\{data:[^}]+\}$/.test(t.each))return De("ERROR: kind=each requires each='{data:file.list}', the token exactly as the step writes it (not the values).");s={action:"expectEach",target:n,each:t.each};break;case"response":if(!t.urlPattern)return De("ERROR: kind=response requires urlPattern.");s={action:"expectResponse",urlPattern:t.urlPattern,...t.method?{method:t.method}:{},...t.status?{status:t.status}:{},...t.bodyPattern?{pattern:t.bodyPattern}:{}};break}return!["url","differs","response"].includes(t.kind)&&!n?De("ERROR: assertion needs a target (role/name, nameRegex, label, text, or selector)."):(e.addActions([s]),De("Assertion recorded."))}),yr("saffron_done","Finalize the run. Call exactly once, after the final step: success=true only if every step's intent was achieved and every assertion verified.",{success:X.boolean(),narrative:X.string().describe("2-4 sentence summary of the run: what happened, and why it failed if it did. After a heal, say what kind of change the app went through (a locator change, or a page removed, merged, added or reordered) and on which page."),suggestedFeatureEdit:X.string().optional().describe("If you adapted any steps: the corrected Gherkin for those steps, as you would rewrite them in the .feature file (free text, for the human report)."),featureEdits:X.array(X.object({index:X.number().int().min(0).describe("zero-based step index"),text:X.string().min(1).regex(/\S/,"a step text cannot be blank").describe("replacement step text WITHOUT the Given/When/Then keyword")})).optional().describe("Machine-applicable version of the suggested edits: one entry per adapted step. Provide this whenever you adapted a step.")},async t=>De(Kw(e,t)))]})}function ko(e={}){let t=e.deliberateSnapshots?`
|
|
324
|
+
Invoke it anywhere with: StepSet Name`,filterText:"step set stepset:",sortText:"0",insertTextFormat:np.Snippet,textEdit:{range:h,newText:"StepSet: ${1:Name}\n "}}];r.stepSets.length===0&&b.push({label:"StepSet \u2026",kind:zn.Keyword,detail:"invoke a step set (none defined yet)",filterText:"step set stepset",sortText:"1",insertTextFormat:np.Snippet,textEdit:{range:h,newText:"StepSet ${1:Name}"}});for(let g of r.stepSets)b.push({label:`StepSet ${g.name}`,kind:zn.Function,detail:`invoke step set \xB7 ${g.steps.length} step(s)`,documentation:g.steps.join(`
|
|
325
|
+
`),filterText:`step set ${g.name}`,sortText:`1${g.name}`,textEdit:{range:h,newText:`StepSet ${g.name}`}});return b}return[]}async function Tc(e,t,n){let r=[...e],s;if(await Promise.all(Array.from({length:Math.min(t,r.length)},async(o,a)=>{for(let i=r.shift();i&&!s;i=r.shift())for(let c of i){if(s)return;try{await n(c,a)}catch(l){s??={error:l};return}}})),s)throw s.error}function gp(e,t){let n=new Map;for(let r of e)n.set(t(r),[...n.get(t(r))??[],r]);return[...n.values()]}import Xt from"node:fs";import Kb from"node:net";import bt from"node:path";import{chromium as Yb,devices as Lc,firefox as Zb,webkit as Qb}from"playwright";import vb from"node:path";import{createHash as xb}from"node:crypto";var hp=5e3,Sb=new Set(["click","press","selectOption","check","uncheck","hover","dragTo"]);function xp(e){return e.mode==="heal"||e.mode==="refine"}function Nc(e){return e.mode==="heal"||e.mode==="refine"?e.failedStep?.stepIndex??e.completedSteps?.length??0:e.recordOnly?e.recordOnly.from:e.completedSteps?.length??0}var mp=/^\s*(?:[\w-]+\s+)?(?:section|form|card|dialog|modal|panel|row|table|list|region|area|tab|popup|menu|group|box|column|drawer|sidebar|block)s?\b/i,$b=/\b(?:field|input|selector|select|dropdown|picker|checkbox|radio|button|link|option|flag|toggle|switch|label|error|message|price|total|amount|heading|title|badge)s?\s*$/i;function Is(e,t=!1){let n=[];for(let r of e.matchAll(/\b(in|inside|within|under)\s+(?:the\s+)?"([^"]+)"/gi)){let s=e.slice(0,r.index),o=e.slice(r.index+r[0].length),a=r[1].toLowerCase();(a==="inside"||a==="within"||mp.test(o)||!t&&(/"[^"]*"/.test(s)&&!/\b(?:fill|type|log|sign)\s*$/i.test(s)||$b.test(s)))&&n.push(r[2])}for(let r of e.matchAll(/\bthe\s+"([^"]+)"/gi))mp.test(e.slice(r.index+r[0].length))&&!n.includes(r[1])&&n.push(r[1]);return n}var kb=e=>e?Pc([e.name,e.nameRegex,e.label,e.text,e.placeholder,e.testId,e.frame,...e.fallbackSelectors??[]].join(`
|
|
326
|
+
`).replace(/\\/g,"")):"",Pc=e=>e.toLowerCase().replace(/[-_ ]+/g," "),Rb=/^(?:option|menuitem|menuitemradio|menuitemcheckbox|treeitem|dialog|alertdialog)$/,Tb=/role=(?:option|menuitem\w*|treeitem|(?:alert)?dialog)\b|\[role=["']?(?:option|menuitem\w*|treeitem|(?:alert)?dialog)\b/;function jc(e,t,n=!1,r=!1){let s=Pc(t);if(!r&&e.some(i=>i.value!==void 0&&Pc(i.value).includes(s)))return[];let o=!1,a=i=>i.target!==void 0&&Se.has(i.action)&&(r||[i.target.name,i.target.nameRegex,i.target.label,i.target.text,i.target.placeholder,i.target.testId,...i.target.fallbackSelectors??[]].some(c=>c!==void 0&&c!==""));return e.filter(i=>Hr(i)&&i.action!=="waitFor"||oi(i)||n&&a(i)).filter(i=>{if(kb(i.target).includes(s))return o=!0,!1;let c=Rb.test(i.target?.role??"")||Tb.test((i.target?.fallbackSelectors??[]).join(`
|
|
327
|
+
`));return!(o&&c)})}function Ac(e){let t=e.target;if(!t)return;let n=[...(t.fallbackSelectors?.[0]??"").split(">>").pop().matchAll(/(?:name|data-testid|label|text)=\\?"((?:[^"\\]|\\.)*)\\?"/g)].pop()?.[1],r=t.name??t.label??t.text??t.placeholder??t.testId??n;return r===void 0||r===""?void 0:r.toLowerCase()}var wp=new Set(["waitForDownload","handleDialog","uploadFile"]),Hr=e=>e.target!==void 0&&!Se.has(e.action)&&e.action!=="captureText",oi=e=>e.action==="captureText"&&e.target!==void 0,Ec=e=>`${e} action${e===1?"":"s"}`,_c=e=>e.map(it).join("; "),ti=class{firstStep;lastStep;discardBeforeAnnounce;preAnnounce=[];discarded=[];carried;pendingTabOpen=!1;pendingTabFallback;lastOpener;lastOpenerAt=0;lastOpenerSession="";sessionKeys;inFlight=new Set;redoing=new Map;redoBase=new Map;replaced=[];lastFiled;setupSteps;steps;resolvedTexts;currentStepIndex=-1;done=!1;success=!1;narrative="";adaptations=[];suggestedFeatureEdit;featureEdits=[];announced=new Set;pendingFingerprint;lastDownload;downloadUnarmed=!1;params;envNames;startedAt;uniqueSeed;constructor(t,n={}){this.setupSteps=t.steps.map(r=>r.setup),this.params=t.params,this.envNames=tt(t),this.startedAt=n.startedAt??new Date,this.uniqueSeed=n.uniqueSeed??"",this.firstStep=Math.max(n.firstStep??0,0),this.lastStep=n.lastStep,this.discardBeforeAnnounce=n.discardBeforeAnnounce??!1,this.sessionKeys=t.steps.map(r=>pe(r.session)),this.steps=t.steps.map(r=>({gherkin:r.text,keyword:r.keyword,kind:r.kind,table:r.table,docString:r.docString,fromStepSet:r.source?.fromStepSet,actions:[]})),this.resolvedTexts=t.steps.map(r=>r.resolvedText??r.text)}redo(t){for(let{index:n,actions:r}of t){let s=this.steps[n]?.actions??[];this.redoBase.set(n,new Set(s));let o=[];for(let a of[...r].sort((i,c)=>s.indexOf(i)-s.indexOf(c))){let i=s.indexOf(a);if(i<0)continue;let c=[a];for(;i>0&&wp.has(s[i-1].action)&&!(s[i-1].action==="uploadFile"&&s[i-1].target);)c.unshift(s[--i]);o.push(c)}this.redoing.set(n,o)}}addArmedAction(t){if(this.done)return;let n=this.destination();if(this.lastFiled&&!n?.includes(this.lastFiled)){let i=this.steps.findIndex((c,l)=>l>=this.firstStep&&c.actions.includes(this.lastFiled));i>=0&&(n=this.steps[i].actions)}if(!n){this.discard([t],this.refusalReason());return}let r=this.lastFiled?n.indexOf(this.lastFiled):-1,s=r>=0?r:Math.max(n.length-1,0),o=n[s-1];if(t.action==="waitForDownload"&&o?.action==="waitForDownload"){o.downloads=(o.downloads??1)+(t.downloads??1);return}o!==void 0&&o.action===t.action&&o.value===t.value&&o.promptText===t.promptText||n.splice(s,0,t)}destination(){if(this.currentStepIndex<0)return this.discardBeforeAnnounce?void 0:this.firstStep===0?this.steps[0]?.actions:this.preAnnounce;if(!(this.currentStepIndex<this.firstStep))return this.steps[this.currentStepIndex]?.actions}refusalReason(){let t=this.currentStepIndex;return t<0?`before announcing the failed step (step ${this.firstStep+1}); a heal records nothing until it announces that step, so this exploration was not filed under any step`:`under step ${t+1} ("${this.steps[t]?.gherkin??""}"), which had already run before the agent took over, so its recording was kept`}discard(t,n){if(t.length===0)return;let r=this.discarded.find(s=>s.why===n);r?r.actions.push(...t):this.discarded.push({actions:[...t],why:n})}announce(t,n,r){if(this.currentStepIndex=t,this.announced.add(t),r){let o=`Step ${t+1} (`;this.adaptations=this.adaptations.filter(a=>!a.startsWith(o)),this.adaptations.push(`${o}"${n}"): ${r}`)}let s=this.steps[t];this.preAnnounce.length>0&&t>=this.firstStep&&s&&(s.actions.unshift(...this.preAnnounce),this.carried={index:t,actions:this.preAnnounce},this.preAnnounce=[])}attributionNotes(){let t=[];if(this.carried){let{index:r,actions:s}=this.carried;t.push(`recording: ${Ec(s.length)} the agent performed before announcing a step ${s.length===1?"was":"were"} filed under step ${r+1} ("${this.steps[r]?.gherkin??""}"), the first step it recorded: ${_c(s)}.`)}let n=this.preAnnounce.length>0?[{actions:this.preAnnounce,why:"before announcing a step this session records"}]:[];for(let{actions:r,why:s}of[...this.discarded,...n])t.push(`recording: discarded ${Ec(r.length)} the agent performed ${s}: ${_c(r)}.`);for(let{index:r,actions:s}of this.replaced)t.push(`recording: step ${r+1} ("${this.steps[r]?.gherkin??""}") was performed again when Saffron asked, replacing ${Ec(s.length)}: ${_c(s)}.`);return t}beginToolCall(t){this.inFlight.add(t)}endToolCall(t,n){this.inFlight.delete(t)&&(this.pendingTabOpen&&n&&(this.pendingTabFallback=void 0),this.inFlight.size===0&&this.pendingTabOpen&&(this.pendingTabFallback&&(this.pendingTabFallback.opensTab=!0),this.pendingTabOpen=!1,this.pendingTabFallback=void 0))}markTabOpened(t){let r=Date.now()-this.lastOpenerAt<=hp&&(t===void 0||t===this.lastOpenerSession)?this.lastOpener:void 0,s=t!==void 0&&t!==this.sessionOf(this.currentStepIndex);if(this.inFlight.size===0||s){r&&(r.opensTab=!0);return}this.pendingTabOpen=!0,this.pendingTabFallback=r}creditLateDownload(){let t=Date.now()-this.lastOpenerAt<=hp?this.lastOpener:void 0;if(!t)return!1;for(let n of this.steps){let r=n.actions.indexOf(t);if(r<0)continue;let s=n.actions[r-1];return s?.action==="waitForDownload"?s.downloads=(s.downloads??1)+1:n.actions.splice(r,0,{action:"waitForDownload"}),!0}return!1}sessionOf(t){return this.sessionKeys[t>=0?t:this.firstStep]??""}addActions(t){if(this.done||t.length===0)return;if(this.currentStepIndex<0&&this.firstStep>0&&!this.discardBeforeAnnounce){let i=t.filter(c=>c.action==="switchTab");if(this.discard(i,"before announcing its first step (replay is already on the live page when the agent takes over)"),t=t.filter(c=>c.action!=="switchTab"),t.length===0)return}let n=this.destination();if(!n){this.pendingFingerprint=void 0,this.discard(t,this.refusalReason());return}this.pendingFingerprint&&t[0]&&(t[0].pageFingerprint=this.pendingFingerprint,this.pendingFingerprint=void 0);let r=this.redoing.get(this.currentStepIndex),s=i=>oi(i)?"capture":Hr(i)&&i.action!=="waitFor"?"interaction":i.target!==void 0&&Se.has(i.action)?"check":void 0,o=(r??[]).map(i=>({flagged:i[i.length-1],actions:i.filter(c=>n.includes(c))})).filter(i=>i.actions.length>0);if(o.length>0){let i=new Map,c=[];for(let u of t){let h=s(u);if(h===void 0)continue;let b=Ac(u),g=o.findIndex(w=>s(w.flagged)===h&&(b===void 0||Ac(w.flagged)===void 0||Ac(w.flagged)===b));if(g<0)continue;let[S]=o.splice(g,1),y={action:"waitFor"};n.splice(n.indexOf(S.actions[0]),0,y);for(let w of S.actions)n.splice(n.indexOf(w),1);i.set(u,y),c.push(...S.actions)}let l=(u,h)=>JSON.stringify({...u,pageFingerprint:void 0})===JSON.stringify({...h,pageFingerprint:void 0}),d=(u,h,b=0)=>{let g=u-1;for(;g>=0&&s(n[g])!=="interaction";)g--;let S=h.findIndex(x=>s(x)!==void 0),y=h[S],w=x=>JSON.stringify([x.action,x.target,x.toTarget,x.clickCount,x.button,x.modifiers,x.value]);if(g>=0&&y!==void 0&&s(y)==="interaction"&&!i.has(y)&&this.redoBase.get(this.currentStepIndex)?.has(n[g])&&w(y)===w(n[g])){let x=g;for(;x>0&&wp.has(n[x-1].action)&&!(n[x-1].action==="uploadFile"&&n[x-1].target);)x--;c.push(...n.slice(x,g+1)),n.splice(x,g+1-x,...h.slice(0,S+1)),u+=S-(g-x),h=h.slice(S+1)}let v=n.slice(g+1,u);h=h.filter(x=>i.has(x)||s(x)==="interaction"||!v.some($=>l(x,$))),n.splice(u,b,...h)},f=[];for(let u of t){f.push(u);let h=i.get(u);h&&(d(n.indexOf(h),f,1),f=[])}let p=o[0]?.actions[0];if(f.length>0&&d(p?n.indexOf(p):n.length,f),c.length>0){let u=this.replaced[this.replaced.length-1];u?.index===this.currentStepIndex?u.actions.push(...c):this.replaced.push({index:this.currentStepIndex,actions:c})}o.length>0?this.redoing.set(this.currentStepIndex,o.map(u=>u.actions)):this.redoing.delete(this.currentStepIndex)}else this.redoing.delete(this.currentStepIndex),n.push(...t);this.lastFiled=[...t].reverse().find(i=>Hr(i)&&i.action!=="waitFor"&&n.includes(i))??t[t.length-1];let a=[...t].reverse().find(i=>Sb.has(i.action));a&&(this.lastOpener=a,this.lastOpenerAt=Date.now(),this.lastOpenerSession=this.sessionOf(this.currentStepIndex),this.pendingTabOpen&&(a.opensTab=!0,this.pendingTabOpen=!1,this.pendingTabFallback=void 0))}},Ab={n:`
|
|
328
|
+
`,r:"\r",t:" ",b:"\b",f:"\f",v:"\v",0:"\0"},Nt=e=>e.replace(/\\(?:x([0-9a-fA-F]{2})|u\{([0-9a-fA-F]+)\}|u([0-9a-fA-F]{4})|([\s\S]))/g,(t,n,r,s,o)=>r!==void 0?String.fromCodePoint(parseInt(r,16)):n!==void 0||s!==void 0?String.fromCharCode(parseInt(n??s,16)):Ab[o]??o);function Eb(e){let t=e.match(/'((?:[^'\\]|\\.)*)'/);return t?Nt(t[1]):void 0}function Sp(e){let t=[],n=0;for(;n<e.length;){let r=/^\.?([A-Za-z]+)\(/.exec(e.slice(n));if(!r)return;let s=n+r[0].length,o=s,a=1,i;for(;s<e.length&&a>0;s++){let c=e[s];if(i)c==="\\"?s++:c===i&&(i=void 0);else if(c==="'"||c==='"'||c==="`")i=c;else if(c==="/"&&/[(,:]\s*$/.test(e.slice(o-1,s)))for(s++;s<e.length&&e[s]!=="/";s++)e[s]==="\\"&&s++;else c==="("||c==="{"||c==="["?a++:(c===")"||c==="}"||c==="]")&&a--}if(a!==0)return;t.push({method:r[1],args:e.slice(o,s-1)}),n=s}return t}function Oc(e,t){let n=/^'((?:[^'\\]|\\.)*)'$/.exec(e.trim());if(n)return`${JSON.stringify(Nt(n[1]))}${t?"s":"i"}`;let r=/^\/((?:[^/\\]|\\.)*)\/([a-z]*)$/.exec(e.trim());if(!r)return;let s=Yi(r[1]);return s!==r[1]&&/[uv]/.test(r[2])?void 0:`/${s}/${r[2]}`}var _b=new Set(["checked","disabled","selected","expanded","includeHidden","level","pressed","busy"]);function yp(e,t){let n=/exact:\s*true/.test(t),r=/^\s*('(?:[^'\\]|\\.)*'|\/(?:[^/\\]|\\.)*\/[a-z]*)/.exec(t)?.[1];switch(e){case"locator":{let s=/^\s*'((?:[^'\\]|\\.)*)'\s*$/.exec(t);return s?Nt(s[1]):void 0}case"getByRole":{let s=/^\s*'([^']+)'/.exec(t)?.[1];if(!s)return;let o="";for(let[,a,i]of t.matchAll(/(\w+):\s*('(?:[^'\\]|\\.)*'|\/(?:[^/\\]|\\.)*\/[a-z]*|[^,}\s]+)/g))if(a==="name"||a==="description"){let c=Oc(i,n);if(c===void 0)return;o+=`[${a}=${c}]`}else if(_b.has(a))o+=`[${a==="includeHidden"?"include-hidden":a}=${i.replace(/^'(.*)'$/,"$1")}]`;else if(a!=="exact")return;return`internal:role=${s}${o}`}case"getByText":case"getByLabel":case"getByPlaceholder":case"getByAltText":case"getByTitle":{let s=r===void 0?void 0:Oc(r,n);return s===void 0?void 0:e==="getByText"?`internal:text=${s}`:e==="getByLabel"?`internal:label=${s}`:`internal:attr=[${{getByPlaceholder:"placeholder",getByAltText:"alt",getByTitle:"title"}[e]}=${s}]`}case"getByTestId":{let s=r&&/^'/.test(r)?Nt(r.slice(1,-1)):void 0;return s===void 0?void 0:`internal:testid=[data-testid=${JSON.stringify(s)}s]`}case"first":return"nth=0";case"last":return"nth=-1";case"nth":return/^\s*-?\d+\s*$/.test(t)?`nth=${t.trim()}`:void 0;case"filter":{let s=/hasText:\s*('(?:[^'\\]|\\.)*'|\/(?:[^/\\]|\\.)*\/[a-z]*)/.exec(t);if(!s||!/^\s*\{\s*\}\s*$/.test(t.replace(s[0],"")))return;let o=Oc(s[1],!1);return o===void 0?void 0:`internal:has-text=${o}`}default:return}}function Ob({method:e,args:t}){let n=String.raw`'(?:[^'\\]|\\.)*'`;return e==="getByRole"?new RegExp(String.raw`^\s*'[^']+'\s*(?:,\s*\{\s*(?:name:\s*${n}\s*(?:,\s*exact:\s*true\s*)?)?\}\s*)?$`).test(t):["getByText","getByLabel","getByPlaceholder","getByTestId","locator"].includes(e)&&new RegExp(String.raw`^\s*${n}\s*$`).test(t)}function Cc(e){let t={},n=e.match(/(?:frameLocator\('((?:[^'\\]|\\.)*)'\)|locator\('((?:[^'\\]|\\.)*)'\)\.contentFrame\(\))/);n&&(t.frame=Nt(n[1]??n[2]),e=e.slice((n.index??0)+n[0].length));let r=Sp(e.replace(/^\./,"")),s=r?.filter((c,l)=>!(c.method==="first"&&l===r.length-1));if(s&&s.length>1){let c=s.map(l=>yp(l.method,l.args));return c.some(l=>l===void 0)?void 0:{...t,fallbackSelectors:[c.join(" >> ")]}}if(s?.length===1&&!Ob(s[0])){let c=yp(s[0].method,s[0].args);return c===void 0?void 0:{...t,fallbackSelectors:[c]}}let o=e.match(/getByRole\('([^']+)'(?:,\s*\{([^}]*)\})?\)/);if(o){t.role=o[1];let c=(o[2]??"").match(/name:\s*'((?:[^'\\]|\\.)*)'/);c&&(t.name=Nt(c[1]))}let a=[[/getByLabel\('((?:[^'\\]|\\.)*)'\)/,"label"],[/getByText\('((?:[^'\\]|\\.)*)'\)/,"text"],[/getByTestId\('((?:[^'\\]|\\.)*)'\)/,"testId"],[/getByPlaceholder\('((?:[^'\\]|\\.)*)'\)/,"placeholder"]];for(let[c,l]of a){let d=e.match(c);d&&(t[l]=Nt(d[1]))}let i=e.match(/(?:^|\.)locator\('((?:[^'\\]|\\.)*)'\)/);return i&&(t.fallbackSelectors=[Nt(i[1])]),Object.keys(t).length>0?t:void 0}var bp={click:"click",dblclick:"click",fill:"fill",pressSequentially:"fill",type:"fill",press:"press",check:"check",uncheck:"uncheck",hover:"hover",selectOption:"selectOption"};function Cb(e,t){let n=e.match(/page\.goto\('((?:[^'\\]|\\.)*)'\)/);if(n)return{action:"goto",url:cs(Nt(n[1]),t)};let r=e.match(/page\.keyboard\.press\('((?:[^'\\]|\\.)*)'\)/);if(r)return{action:"press",value:Nt(r[1])};let s=e.match(/await\s+page\.(.+)\.dragTo\(page\.(.+?)\);?\s*$/);if(s){let b=Cc(s[1]),g=Cc(s[2]);if(b&&g)return{action:"dragTo",target:b,toTarget:g}}let o=/await\s+page\.(.*\))\s*;?\s*$/.exec(e)?.[1],a=o===void 0?void 0:Sp(o),i=a?.[a.length-1];if(!a||!i||a.length<2||!Object.hasOwn(bp,i.method))return;let{method:c,args:l}=i,d=a.slice(0,-1).map(b=>`${b.method}(${b.args})`).join("."),f=Cc(d);if(!f||c==="pressSequentially"&&/^\s*''\s*\)?\s*;?\s*$/.test(l))return;let p={action:bp[c],target:f};if(c==="click"||c==="dblclick"){let b=/clickCount:\s*(\d+)/.exec(l)?.[1];c==="dblclick"?p.clickCount=2:b&&b!=="1"&&(p.clickCount=Number(b));let g=/button:\s*'(left|right|middle)'/.exec(l)?.[1];g&&g!=="left"&&(p.button=g);let S=/modifiers:\s*\[([^\]]*)\]/.exec(l)?.[1],y=S?[...S.matchAll(/'((?:[^'\\]|\\.)*)'/g)].map(w=>Nt(w[1])):[];return y.length>0&&(p.modifiers=y),p}let u=c==="selectOption"?/^\s*\[((?:'(?:[^'\\]|\\.)*'|[^\]'])*)\]/.exec(l)?.[1]:void 0;if(u!==void 0&&!u.trim())return{...p,clearSelection:!0};let h=u?.trim()?[...u.matchAll(/'((?:[^'\\]|\\.)*)'/g)].map(b=>Nt(b[1])).join(`
|
|
329
|
+
`):Eb(l);return h!==void 0&&(p.value=h),p}function $p(e){let t=Array.isArray(e)?e:e?.content,n=typeof e=="string"?[e]:Array.isArray(t)?t.flatMap(r=>typeof r?.text=="string"?[r.text]:[]):[];for(let r of n){let s=r.split(/^### Open tabs\r?$/m)[1]?.split(/^### /m)[0];if(!s)continue;let o=/^- (\d+): \(current\) /m.exec(s)?.[1];if(o!==void 0)return Number(o)}}function kp(e){let t=Array.isArray(e)?e:e?.content;return(typeof e=="string"?[e]:Array.isArray(t)?t.flatMap(r=>typeof r?.text=="string"?[r.text]:[]):[]).reduce((r,s)=>r+[...(s.split(/^### Events\r?$/m)[1]?.split(/^### /m)[0]??"").matchAll(/^- Downloading file .* \.\.\.\r?$/gm)].length,0)}function Pb(e){if(typeof e=="string")return[e];let t=Array.isArray(e)?e:e?.content;return Array.isArray(t)?t.flatMap(n=>typeof n?.text=="string"?[n.text]:[]):[]}function Rp(e){let t=new Map;for(let n of Pb(e).flatMap(r=>r.split(/^### Snapshot[ \t\r]*$/m).slice(1).map(s=>s.split(/^### /m)[0])))for(let r of n.matchAll(/^\s*-\s+([a-z]+)\s+"((?:[^"\\\n]|\\.)*)"((?:[ \t]+\[[^\]\n]*\])+)/gm)){let s=/\[ref=([^\]]+)\]/.exec(r[3])?.[1];if(!s)continue;let o=r[2];try{o=JSON.parse(`"${r[2]}"`)}catch{}t.set(s,{role:r[1],name:o})}return t}function Tp(e){let t=s=>{let o=s?.ref??s?.target;return typeof o=="string"&&/^(?:f\d+)?e\d+$/.test(o)?o:void 0},n=e?.fields;if(Array.isArray(n))return n.map(t);let r=t(e)??t({ref:e?.startRef});return r?[r]:[]}function Ap(e,t,n){let r=s=>s.toLowerCase().replace(/\s+/g," ").trim();e.filter(Hr).forEach((s,o)=>{let a=t.length===1?t[0]:t[o],i=a===void 0?void 0:n.get(a),c=s.target;!i||c.role!==i.role||c.name===void 0||c.name===i.name||c.name.trim()===""||r(i.name).includes(r(c.name))&&(c.name=i.name)})}function Ep(e,t){let n=[],r=Array.isArray(e)?e:e?.content;if(Array.isArray(r))for(let o of r){let a=o?.text;typeof a=="string"&&n.push(a)}else typeof e=="string"&&n.push(e);let s=[];for(let o of n){let a=o.split(/^### Ran Playwright code[ \t\r]*$/m).slice(1).map(i=>i.split(/^### /m)[0]).join(`
|
|
330
|
+
`);for(let i of a.split(`
|
|
331
|
+
`)){let c=Cb(i.trim(),t);c&&s.push(c)}}return Ib(s)}function Ib(e){return e.filter((t,n)=>{let r=e[n+1];return!(t.action==="fill"&&(t.value??"")===""&&r?.action==="fill"&&JSON.stringify(r.target)===JSON.stringify(t.target))})}function _p(e){let t=[];for(let n of e){if(n.kind==="assertion"&&n.actions.length===0){t.push(`Step "${n.gherkin}" is an assertion but recorded no check, so nothing would be verified. Re-record with: saffron run --rerecord`);continue}let r=fe(n.gherkin),s=r.replace(/"[^"]*"|<[^<>]+>/g," "),o=/\b(?:clear|clears|clearing|erase|erases|wipe|wipes)\b/i.test(s)||/(?<!\b(?:the|is|are)\s+)\b(?:empty|empties|blank)\b/i.test(s);if(!/"[^"]+"|<[^<>]+>/.test(r)||o)continue;n.actions.filter(i=>i.action==="fill"&&(i.value??"")==="").length>(r.match(/""/g)??[]).length&&t.push(`Step "${n.gherkin}" recorded a fill with an empty value although the step passes one; the typed value was lost. Re-record with: saffron run --rerecord`)}return t}function Op(e,t,n=ue.pattern){for(let[r,s]of t){let o=bd(e,n(s));if(o)return o==="bare"?`<${r}>`:`^<${r}>$`}}function zr(e,t,n=o=>o,r=!1,s=Object.keys(t)){let o=Object.entries(t).filter(([,i])=>i.length>=3);if(!r)return ni(e,o,i=>new RegExp(i.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),n,s);let a=o.find(([,i])=>!da(i)&&e===n(i));return a?`<${a[0]}>`:ni(e,o.filter(([,i])=>da(i)),i=>xe(i,"gu"),n,s)}function ni(e,t,n,r=o=>o,s=t.map(([o])=>o)){let o=new RegExp(`(${Qn(s).source}|\\{(?:env|data|unique|date)[^{}<]*<[^{}]*\\})`);return[...t].sort((a,i)=>i[1].length-a[1].length).reduce((a,[i,c])=>a.split(o).map((l,d)=>{if(d%2)return l;let f=l.normalize("NFC"),p=f.replace(n(r(c).normalize("NFC"),c),()=>`<${i}>`);return p===f?l:p}).join(""),e)}function Nb(e,t,n){if(/^\s*(?:xpath=|\/\/)/.test(e))return e.replace(/'([^']*)'|"([^"]*)"/g,(o,a,i)=>a!==void 0?`'${n(a)}'`:`"${n(i)}"`);let r,s=!0;return Wn(e,t,o=>o.split(/(>>)/).map((a,i)=>i%2?a:((s||i>0)&&(r=a.match(/^\s*([a-z_-]+(?::[a-z_-]+)?)=/i)?.[1]?.toLowerCase()),s=!1,r===void 0?a.replace(/([#.])((?:[\p{L}\p{N}\p{M}_-]|\\.)+)/gu,(c,l,d)=>l+n(d)):/^(?:id|data-testid|data-test-id|data-test)$/.test(r)?a.replace(/=(.*)$/s,(c,l)=>`=${n(l)}`):a)).join(""))}function ii(e,t){let n=[fe(e??""),fe(t?.text??""),...t?.table?.flat()??[],t?.docString??""].join(`
|
|
332
|
+
`);return new Set([...n.matchAll(/<([^<>]+)>/g)].map(r=>r[1]))}function Ns(e,t){let n=[e?.text??"",...e?.table?.flat()??[],e?.docString??""].join(`
|
|
333
|
+
`).replace(/<[^<>]+>/g," ");try{return t(n)}catch{return n}}function Mc(e,t,n=e,r="",s=o=>[n[o]??e[o]]){let o=new Map;for(let a of Object.keys(e))o.set(n[a]??e[a],[...o.get(n[a]??e[a])??[],a]);return Object.fromEntries(Object.entries(e).filter(([a,i])=>{let c=n[a]??i;if(c!==""&&xe(c).test(r)&&(!t.has(a)||!s(a).every(d=>xe(d).test(r))))return!1;let l=o.get(c);return l.length>1&&l.some(d=>/\{env:/.test(e[d]))?!1:(l.find(d=>t.has(d))??l[0])===a}))}function ri(e,t,n){let r=e.flatMap(s=>{let o=s[t];if(o===void 0)return[];try{return[n(o)]}catch{return[o]}});return[...new Set(r)].filter(s=>s.trim()!=="")}function Cp(e,t,n,r){return e(t).filter(s=>s!==n&&!/\{(?:env|data|unique|date)/.test(s)&&(s.length>=3||r.has(t)))}function Ic(e,t){return new RegExp(`(^|[-_:.])${be(e)}(?=$|[-_:.])`,t)}function Pp(e,t){let n=Object.keys(t.params);if(n.length===0)return[];let r=Ye(e.map(w=>w.gherkin)),s=new Date().toISOString(),o=t.exampleRows??[t.params],a=xr(o.flatMap(w=>Object.values(w))),i=w=>w.replace(Ae,(v,x)=>a.get(x)??v).replace(Ce,(v,x)=>process.env[x]??v),c=Object.fromEntries(Object.entries(t.params).map(([w,v])=>[w,i(v)])),l=w=>!/\{(?:env|data|unique|date)/.test(w),d=w=>ri(o,w,i),f=(w,v,x)=>{let $=w.trim(),E=`${v}
|
|
334
|
+
${v.replace(Ae,(k,C)=>x.get(C)??k)}`.toLowerCase(),R=k=>v.includes(k)&&($===k||$.startsWith(k)&&/^[/?#]/.test($.slice(k.length))||E.includes($.toLowerCase()));return w.replace(Qn(n)," ").replace(Ae,(k,C)=>R(k)?k:a.get(C)??x.get(C)??k).replace(Ce,(k,C)=>R(k)?k:process.env[C]??k).replace(/\{(?:env|data|unique|date)[^{}]*\}/g," ")},p=[],u=[...new Set(t.steps.flatMap(w=>[w.text,...w.table?.flat()??[],w.docString??""]).flatMap(w=>[...w.matchAll(/\{data:([^{}]*<[^<>{}]+>[^{}]*)\}/g)].map(v=>v[1])))].flatMap(w=>{let v=[...w.matchAll(/<([^<>]+)>/g)].map(E=>E[1]).filter(E=>E in t.params),$=(E=>{if(!v.some(R=>/[{}<>]/.test(E[R]??"{")))try{return qe(w.replace(/<([^<>]+)>/g,(R,k)=>E[k]??R))}catch{return}})(t.params);return v.length===0||$===void 0||$.trim()===""?[]:[{used:v,value:$.trim().toLowerCase()}]}),h=[...js(t).all].filter(([,w])=>w.size>1);h.length>0&&e.forEach((w,v)=>{let x=w.actions.flatMap($=>Et($)).filter($=>$!==void 0);for(let[$,E]of h){if(!x.some(k=>k.includes($)))continue;let R=new Set([...E].flatMap(k=>[...k.matchAll(/<([^<>]+)>/g)].map(C=>C[1])));for(let k of R)k in t.params&&p.push({column:k,step:v,reason:"data"})}});let{own:b,all:g}=js(t),S=[...si(g)];S.length>0&&e.forEach((w,v)=>{let x=si(b[v]??new Map),$=Ns(t.steps[v],R=>R).replace(/\{[^{}]*\}/g," "),E=w.actions.flatMap(R=>Et(R)).filter(R=>R!==void 0);for(let[R,k]of S){let C=x.get(R),P=R.trim()!==""&&(xe(R).test($)||R.length>=4&&$.includes(R));if(!C&&P)continue;let m=C??k,A=Tr(R).exact,O=I=>R.trim()===""?I.trim()==="":A.some(L=>R.length>=3?I.includes(L):xe(L).test(I)),T=[t.steps[v]?.text??w.gherkin,...t.steps[v]?.table?.flat()??[],t.steps[v]?.docString??""].join(`
|
|
335
|
+
`),_=[...m].some(I=>JSON.stringify(w.actions).split(I).length>T.split(I).length);if(!(C===void 0?ca(w.actions,R):m.size>1&&E.some(O)||P&&(E.some(O)||_)||On(w.actions,R)))continue;let F=new Set([...m].flatMap(I=>[...I.matchAll(/<([^<>]+)>/g)].map(L=>L[1])));for(let I of F)I in t.params&&!p.some(L=>L.column===I&&L.step===v)&&p.push({column:I,step:v,reason:"data"})}});let y=w=>{let v=vd(t.params[w]);return v?{valueSha:v}:{}};return e.forEach((w,v)=>{let x=ii(w.gherkin,t.steps[v]),$=Mc(c,x,c,Ns(t.steps[v],M=>M),d),E=Object.entries($).filter(([M,U])=>l(U)&&U.trim()!==""&&(U.length>=3||x.has(M))),R=new Set(E.filter(([M])=>x.has(M)).map(([,M])=>M)),k=t.steps[v],C=[k?.text??w.gherkin,...k?.table?.flat()??[],k?.docString??""].join(`
|
|
336
|
+
`),P=xr([C]),m=[C,...P.values()].join(`
|
|
337
|
+
`),A=w.actions.flatMap(M=>_n(M)).flatMap(M=>M===void 0?[]:[f(M,m,P).normalize("NFC")]),T=w.actions.flatMap(M=>M.each!==void 0&&!C.includes(M.each)?M.each.match(/^\{data:([^{}]+)\}$/)?.slice(1)??[]:[]).map(M=>M.toLowerCase()),_=w.actions.flatMap(M=>M.attribute!==void 0?[M.attribute]:[]),N=M=>[M,M.replace(/\s+/g,"-"),M.replace(/\s+/g,"_")].some(U=>T.some(z=>z.includes(U))||_.some(z=>Ic(U,"i").test(z))),F=w.actions.flatMap(M=>[M.status,M.method,M.attribute]).flatMap(M=>M===void 0?[]:[f(M,m,P).trim().toLowerCase()]),I=new Set;for(let[M,U]of Object.entries(c)){let z=U.trim().toLowerCase();x.has(M)||/\{(?:date|unique)/.test(t.params[M]??"")||z===""||!F.includes(z)||(p.push({column:M,step:v,reason:"value",...y(M)}),I.add(M))}for(let[M,U]of Object.entries(c)){if(I.has(M)||/\{(?:date|unique)/.test(t.params[M]??""))continue;let z=U.trim().toLowerCase();z.length<3||!N(z)||(p.push({column:M,step:v,reason:"glued",...y(M)}),I.add(M))}for(let{used:M,value:U}of u)if(F.includes(U))for(let z of M)I.has(z)||(p.push({column:z,step:v,reason:"reads",...y(z)}),I.add(z));for(let[M,U]of E){if(I.has(M))continue;let z=Cp(d,M,U,x);z.length>0&&A.some(V=>Rr(V,U,R.has(U))&&z.some(ee=>Rr(V,ee,R.has(U))))?p.push({column:M,step:v,reason:"list",...y(M)}):!x.has(M)&&U.length>=3&&A.some(V=>aa(U.normalize("NFC")).test(V))&&p.push({column:M,step:v,reason:"glued",...y(M)})}let L=M=>p.some(U=>U.column===M&&U.step===v);for(let M of Object.keys(t.params)){let U=c[M]??"";if(L(M)||U.trim()==="")continue;let z=Object.keys(c).filter(ee=>c[ee]===U);if(z.length>1&&o.some(ee=>new Set(z.map(Ie=>i(ee[Ie]??""))).size>1))continue;let V={...t.params,...Object.fromEntries(z.map(ee=>[ee,"\u2063another row\u2063"]))};Zn(w.actions,C,t.params,V,s)&&p.push({column:M,step:v,reason:"glued",...y(M)})}if(w.actions.some(M=>M.target!==void 0)){let M=new Set(Is(w.gherkin,!0));for(let U of Is(w.gherkin))for(let[,z]of U.matchAll(/<([^<>]+)>/g))!(z in t.params)||L(z)||jc(w.actions,`<${z}>`,w.kind==="assertion",M.has(U)).length===0||p.push({column:z,step:v,reason:"container",...y(z)})}let j=M=>w.kind==="assertion"&&!kr(w.actions)&&!(t.params[M]??"").includes("{date"),H=[t.steps[v]?.text??w.gherkin,...t.steps[v]?.table?.flat()??[],t.steps[v]?.docString??""].join(`
|
|
338
|
+
`),Z=M=>go(H,M,c);for(let M of $r(w.gherkin,w.actions,t.params).filter(U=>!j(U)&&!Z(U)))M in t.params&&!L(M)&&(c[M]??"").trim()!==""&&p.push({column:M,step:v,reason:"unwritten",...y(M)});let Q=r[v];if(Q!==void 0&&/<[^<>]+>/.test(Q)){let M=`${C}
|
|
339
|
+
${C.replace(Ae,(V,ee)=>P.get(ee)??V).replace(Ce,(V,ee)=>process.env[ee]??V)}`,U=V=>new RegExp(Qn(n).source).test(V)||/\{(?:date[^{}]*|unique:[^{}]+)\}/.test(V);if(w.actions.some(V=>(V.action==="fill"||V.action==="selectOption")&&(V.value??"").trim()!==""&&!U(V.value)&&!xe(V.value).test(M)))for(let[,V]of Q.matchAll(/<([^<>]+)>/g))V in t.params&&!L(V)&&p.push({column:V,step:v,reason:"session",...y(V)})}if(w.kind==="assertion")for(let[M,U]of Object.entries(t.params)){let z=(c[M]??"").trim();L(M)||x.has(M)||z===""||z.length>2||/\{(?:date|unique)/.test(U)||xe(z,"u").test(C)||w.actions.some(V=>_n(V).some(ee=>ee!==void 0&&Rr(f(ee,m,P),z,!1)))&&p.push({column:M,step:v,reason:"glued",...y(M)})}}),p}function jb(e,t,n=[],r=t,s=a=>a,o=[]){let a=d=>ri(o.length>0?o:[t],d,s),i=new Map,c=d=>i.get(d)??i.set(d,ri(o.length>0?o:[t],d,f=>f)).get(d),l=Object.keys(t);return e.map((d,f)=>{let p=ii(d.gherkin,n[f]),u=[...p].filter(m=>m in t&&(r[m]??t[m])===""),h=u.length===1?`<${u[0]}>`:void 0,b=Mc(t,p,r,Ns(n[f],s),a),g=Object.entries(b).map(([m,A])=>[m,A.includes("{date")?A:r[m]??A]).filter(([m,A])=>A.length>=3||A!==""&&p.has(m));if(g.length===0&&!h)return d;let S=new Set(g.filter(([m])=>p.has(m)).map(([,m])=>m)),y=(m,A)=>ho(A,m,"gu",S.has(A)),w=(m,A,O)=>Op(m,A,O)??ni(m,A,y,O,l),v=[...p].flatMap(m=>{let A=m in b?vt(r[m]??t[m]):void 0;return A===void 0?[]:[[m,A]]}),$=[...g.filter(([m])=>p.has(m))].sort((m,A)=>A[1].length-m[1].length),E=m=>m===void 0?m:$.reduce((A,[O,T])=>A.replace(Ic(T,"gi"),(_,N)=>`${N}<${O}>`),m),R=(m,A=O=>O)=>{if(m===void 0)return;let O=w(m,g,A),T=O.replace(Qn(l)," "),_=g.filter(([N,F])=>!/\{(?:env|data|unique|date)/.test(t[N])&&Rr(m,F,S.has(F),A(F))&&Cp(c,N,F,p).some(I=>Rr(T,I,S.has(F),A(I))));return _.length===0?O:w(m,g.filter(N=>!_.includes(N)),A)},k=m=>R(m,ue.pattern),C=m=>m===void 0?void 0:Nb(m,(A,O)=>R(A,ue[O]),A=>ni(A,g,y,void 0,l)),P=m=>m?{...m,name:R(m.name),nameRegex:k(m.nameRegex),label:R(m.label),text:R(m.text),placeholder:R(m.placeholder),testId:R(m.testId),frame:C(m.frame),fallbackSelectors:m.fallbackSelectors?.map(A=>C(A))}:void 0;return{...d,actions:d.actions.map(m=>({...m,value:m.action==="expectDiffers"?m.value:m.action==="expectAmount"&&m.value!==void 0?Yn(m.value,A=>ld(R(A)??A,v)):(m.action==="fill"||Se.has(m.action))&&m.value===""&&h?h:R(m.value),url:R(m.url),pattern:k(m.pattern),urlPattern:k(m.urlPattern),promptText:R(m.promptText),each:m.each!==void 0&&!d.gherkin.includes(m.each)?m.each.replace(/^\{data:([^{}]+)\}$/,(A,O)=>`{data:${$.reduce((T,[_,N])=>T.replace(Ic(N,"g"),(F,I)=>`${I}<${_}>`),O)}}`):m.each,status:E(m.status),method:E(m.method),attribute:E(m.attribute),target:P(m.target),toTarget:P(m.toTarget)}))}})}function Mb(e,t,n=r=>r){let r=Tn(t.steps);return e.map((s,o)=>{let a=t.steps[o],i=a?.resolvedTable??a?.table,c=a?.resolvedDocString??a?.docString,l={...rt(i),...Jn(c)},d=new Set,f=Object.entries({...r,...l}).map(([g,S])=>{let y=n(S);return S.includes("{date")&&d.add(g),[g,y]}).filter(([g,S])=>S.length>=3&&(!d.has(g)||g in l||Ip(S))).filter(([g,S])=>g in l||!(a?.resolvedText??a?.text??"").includes(S)),p=new Set(f.map(([,g])=>g).filter((g,S,y)=>y.indexOf(g)!==S)),u=f.filter(([,g])=>!p.has(g)).sort((g,S)=>S[1].length-g[1].length);if(u.length===0)return s;let h=(g,S=w=>w,y=!1)=>g===void 0?void 0:u.reduce((w,[v,x])=>zr(w,{[v]:x},S,y||d.has(v)),g),b=g=>g?{...g,name:h(g.name),nameRegex:h(g.nameRegex,ue.pattern),label:h(g.label),text:h(g.text),placeholder:h(g.placeholder),testId:h(g.testId,void 0,!0),frame:h(g.frame,void 0,!0),fallbackSelectors:g.fallbackSelectors?.map(S=>Wn(S,(y,w)=>h(y,ue[w])??y))}:void 0;return{...s,actions:s.actions.map(g=>({...g,value:g.action==="expectDiffers"?g.value:g.action==="expectAmount"&&g.value!==void 0?Yn(g.value,S=>h(S)):h(g.value),url:h(g.url),pattern:h(g.pattern,ue.pattern),urlPattern:h(g.urlPattern,ue.pattern),promptText:h(g.promptText),target:b(g.target),toTarget:b(g.toTarget)}))}})}var Ip=e=>/(?<!\d)\d{4}(?!\d)/.test(e);function Db(e,t){for(let n=1;n<=400;n++){let r=new Date(t.getTime()+n*864e5),s=Ve(e[0],r);if(e.some(o=>Ve(o,r)!==s))return!1}return!0}function Fb(e){let t=new RegExp(`^${Sr.source}$`).exec(e)?.[4],n=t===void 0?"YYYY-MM-DD":t.replace(/:[a-z]{2,3}(?:-[A-Za-z0-9]{1,8})*$/,"");return/Y/.test(n)&&/[MD]/.test(n)}var Lb=["DD/MM/YYYY","MM/DD/YYYY","DD.MM.YYYY","D MMM YYYY","MMM D, YYYY","D MMMM YYYY","MMMM D, YYYY"];function Bb(e,t,n,r=[],s=[]){let o=t.steps.map(c=>[c.text,...c.table?.flat()??[],c.docString??""].flatMap(l=>l.match(Sr)??[])),a=(c,l)=>c.map(d=>[d,Ve(d,n)]).filter(([,d])=>!r.some(f=>f.includes(d))&&!(s[l]??[]).includes(d)),i=o.flat().filter(Fb).flatMap(c=>[c,.../^\{date(?:[+-]\d+)?\}$/.test(c)?Lb.map(l=>`${c.slice(0,-1)}:${l}}`):[]]);return e.map((c,l)=>{let d=[...new Map([...a(o[l]??[],l),...a(i,l)])],f=new Map;for(let[h,b]of d)f.set(b,[...f.get(b)??[],h]);let p=d.filter(([h,b])=>{let g=f.get(b);return g.length===1||g[0]===h&&Db(g,n)}).sort((h,b)=>b[1].length-h[1].length);if(p.length===0)return c;let u=(h,b=g=>g)=>p.find(([,g])=>h===b(g))?.[0]??p.filter(([,g])=>g.length>=3).reduce((g,[S,y])=>g.split(/(\{(?:env|data|unique|date)[^{}]*\}|<[^<>{}]+>)/).map((w,v)=>v%2?w:w.replace(xe(b(y),"gu"),()=>S)).join(""),h);return{...c,actions:c.actions.map(h=>mn(h,b=>u(b),(b,g)=>u(b,ue[g])))}})}function Ub(e,t=new Date,n=[]){return e.map(r=>({...r,actions:r.actions.map(s=>mn(s,o=>id(o,t,n)))}))}function mn(e,t,n,r=t,s=t){let o=(d,f,p=t)=>{let u={...d};for(let h of f)typeof d[h]=="string"&&(u[h]=p(d[h]));return u},a=d=>n?n(d,"pattern"):t(d),i=d=>{let f=o(o(d,["name","label","text","placeholder","testId","frame"]),["nameRegex"],a);return d.fallbackSelectors&&(f.fallbackSelectors=d.fallbackSelectors.map(p=>n?Wn(p,n,s):t(p))),f},c=e.action==="expectDiffers"?["url","promptText"]:["value","url","promptText"],l=o(o(o(e,c),["status","method","attribute","each"],r),["pattern","urlPattern"],a);return e.action==="expectAmount"&&e.value!==void 0&&(l.value=Yn(e.value,t)),e.target&&(l.target=i(e.target)),e.toTarget&&(l.toTarget=i(e.toTarget)),l}function zb(e,t){if(t.length===0)return e;let n=new Map(t.map(([o,a])=>[a,o])),r=[...n.keys()].sort((o,a)=>a.length-o.length).map(be).join("|"),s=new RegExp(String.raw`(?<=^|[^A-Za-z0-9\\]|\\[A-Za-z])(?:${r})(?![A-Za-z0-9])`,"g");return e.split(/(\{(?:env|data|unique|date)[^{}]*\})/).map((o,a)=>a%2?o:o.replace(s,i=>`{env:${n.get(i)}}`)).join("")}function Hb(e,t){let n=tt(t),r=rn(lt(t)),s=new RegExp(`${Ce.source}|${Ae.source}`,"g"),o=a=>a.replace(s,(i,c,l)=>(c!==void 0?n.has(c):r.has(l))?i:Ll(i));return e.map(a=>({...a,actions:a.actions.map(i=>({...mn(i,o),...i.each!==void 0?{each:i.each}:{}}))}))}function vp(e,t,n=[]){if(t.size===0)return e;let r=Gi(n,t),s=Rn(t,{standaloneBelow:6}),o=v=>{let x=encodeURIComponent(v),$=x.replace(/[!'()*]/g,E=>`%${E.charCodeAt(0).toString(16).toUpperCase()}`);return[...new Set([x,$,x.replace(/%20/g,"+"),$.replace(/%20/g,"+"),encodeURI(v)])].filter(E=>E!==v)},a=v=>v.length>=6&&v.toLowerCase()!==v.toUpperCase(),i=[...t].filter(([,v])=>v.length>=kn).flatMap(([v,x])=>o(x).map($=>[v,$,a(x)])).sort((v,x)=>x[1].length-v[1].length),c=(v,x=$=>$)=>i.reduce(($,[E,R,k])=>{let C=Wi(x(R));return $.replace(new RegExp(C,k?"gi":"g"),()=>`{env:${E}}`)},v),l=[...t].filter(([,v])=>a(v)).sort((v,x)=>x[1].length-v[1].length).map(([v,x])=>[v,new RegExp(be(x),"gi")]),d=v=>l.reduce((x,[$,E])=>x.split(/(\{[^{}]*\})/).map((R,k)=>k%2?R:R.replace(E,`{env:${$}}`)).join(""),v),f=v=>d(s.mask(r(c(v)))),p=[...t].filter(([,v])=>v.length>=kn),u=v=>{let x=Gi(n,t,ue[v]),$=Rn(new Map(p.filter(([,R])=>R.length>=6).map(([R,k])=>[R,ue[v](k)]))),E=p.filter(([,R])=>R.length<6).map(([R,k])=>[R,ue[v](k)]);return R=>f(zb($.mask(x(c(R,ue[v]))),E))},h={quoted:u("quoted"),regex:u("regex"),pattern:u("pattern")},b=new Set(e.flatMap(v=>v.actions.flatMap(x=>[x.saveAs,x.compareTo,x.action==="expectDiffers"?x.value:void 0,...x.action==="expectAmount"?[...(x.value??"").matchAll(/"([^"]*)"/g)].map($=>$[1]):[]].filter($=>$!==void 0)))),g=Rn(t,{encodings:!0}),S=new Map,y=new Set(b);for(let v of b){let x=g.mask(v);if(x===v)continue;let $=`capture-${xb("sha256").update(x).digest("hex")}`;if(y.has($)||g.mask($)!==$)throw new Error("Secret-bearing capture names cannot be safely distinguished. Record again with distinct capture names that contain no secrets.");y.add($),S.set(v,$)}let w=v=>v===void 0?void 0:S.get(v)??v;return e.map(v=>({...v,actions:v.actions.map(x=>{let $=mn(x,f,(E,R)=>h[R](E));return{...$,...x.saveAs!==void 0?{saveAs:w(x.saveAs)}:{},...x.compareTo!==void 0?{compareTo:w(x.compareTo)}:{},...x.action==="expectDiffers"&&x.value!==void 0?{value:w(x.value)}:{},...x.action==="expectAmount"&&$.value!==void 0?{value:Yn($.value,E=>E,E=>w(E))}:{}}})}))}function Np(e,t,n="",r=new Date){let s=lt(t),o=Pe(t),a=r,i=E=>Ve(Dt(Yt(E,n)),a).replace(Ce,(R,k)=>o.get(k)??R),c=Object.fromEntries(Object.entries(t.params).map(([E,R])=>{try{return[E,i(R)]}catch{return[E,R]}})),l=e.map((E,R)=>ii(E.gherkin,t.steps[R])),d=l.map((E,R)=>Mc(t.params,E,c,Ns(t.steps[R],i),k=>ri(t.exampleRows??[t.params],k,i))),f=Object.entries(t.params).filter(([,E])=>E.includes("{date")).map(([E,R])=>[E,R,c[E]]),p=(E,R)=>Ip(R)||/\{date[^{}]*:[^{}]*(?:MMM|ddd)/.test(E),u=E=>f.filter(([R,k,C])=>R in(d[E]??{})&&(l[E]?.has(R)||p(k,C))),b=jb(Mb(Hb(qb(Jb(vp(e,o,s),t,c,o),t),t),t,E=>Ve(Dt(Yt(E,n)),a)),t.params,t.steps,c,i,t.exampleRows).map((E,R)=>{let k=[...l[R]].flatMap(C=>{let P=c[C];if(P===void 0||P.length<3)return[];let m=encodeURIComponent(P);return m===P?[]:[...new Set([m,m.replace(/%20/g,"+")])].map(A=>[A,`<${C}>`])});return k.length===0?E:{...E,actions:E.actions.map(C=>C.url===void 0?C:{...C,url:k.reduce((P,[m,A])=>P.split(m).join(A),C.url)})}}),g=[...s,...es(s),...o.values()],S=e.map((E,R)=>f.filter(([k])=>l[R]?.has(k)).map(([,,k])=>k)),y=Bb(b,t,a,g,S).map((E,R)=>{let k=f.filter(([C,P,m])=>l[R]?.has(C)||p(P,m)).map(([,,C])=>C);return Ub([E],a,[...g,...k])[0]}),w=vp(Wb(Gb(y,new Map([...xr(s)].map(([E,R])=>[E,R.includes("{date")?Ve(R,a):R]))),Ir(s,n)),o,s),v=Object.fromEntries(Object.entries(t.params).filter(([,E])=>!E.includes("{date")&&/\{(?:env|data|unique):/.test(E))),x=Object.keys(t.params),$=Vb(w,t);return Object.keys(v).length===0&&f.length===0?$:$.map((E,R)=>{let k=u(R),C={...Object.fromEntries(Object.entries(v).filter(([_])=>_ in(d[R]??{}))),...Object.fromEntries(k.map(([_,N])=>[_,N]))},P=Object.fromEntries(k.filter(([,,_])=>!_.includes("{date")).map(([_,,N])=>[_,N])),m=Object.entries(P).filter(([,_])=>_.length<3),A=(_,N)=>{let F=m.find(([,I])=>_===(N?N(I):I));return F?`<${F[0]}>`:zr(_,P,N,!0,x)},O=_=>A(zr(_,C,void 0,!1,x)),T=(_,N)=>{let F=zr(_,C,void 0,!1,x);return(N==="pattern"?Op(F,m):void 0)??A(F,ue[N])};return{...E,actions:E.actions.map(_=>mn(_,O,T))}})}function js(e){let t=e.steps.map(o=>[o.text,...o.table?.flat()??[],o.docString??""]),n=t.flat(),r=t.map(()=>new Map),s=new Map;return t.forEach((o,a)=>{for(let i of o)for(let[c,l]of i.matchAll(/\{data:([^{}]*<[^<>{}]+>[^{}]*)\}/g)){let d=!0,f=`{data:${l.replace(/<([^<>]+)>/g,(p,u)=>{let h=e.params[u];return(h===void 0||/[{}<>]/.test(h))&&(d=!1),h??""})}}`;if(!(!d||n.some(p=>p.includes(f))))for(let p of[r[a],s])(p.get(f)??p.set(f,new Set).get(f)).add(c)}}),{own:r,all:s}}function si(e){let t=new Map;for(let[n,r]of e){let s;try{s=qe(n.slice(6,-1))}catch{continue}let o=Ve(s.replace(Ce,(a,i)=>process.env[i]??a));for(let a of new Set([s,o]))for(let i of r)(t.get(a)??t.set(a,new Set).get(a)).add(i)}return t}function qb(e,t){let{own:n}=js(t),r=s=>[...si(s)].flatMap(([o,a])=>a.size===1&&o.trim()!==""?[[o,[...a][0]]]:[]);return e.map((s,o)=>{let a=Ns(t.steps[o],l=>l).replace(/\{[^{}]*\}/g," "),i=new Map(r(n[o]??new Map).filter(([l])=>!xe(l).test(a)));if(i.size===0)return s;let c=l=>{let d=i.get(l);if(d!==void 0)return d;let f=l;for(let[p,u]of i)f=f.split(/(\{[^{}]*\}|<[^<>\s]+>)/).map((h,b)=>b%2?h:h.replace(xe(p,"gu"),u)).join("");return f};return{...s,actions:s.actions.map(l=>mn(l,c,d=>d,c,d=>jp(d,c)))}})}function Vb(e,t){let{own:n,all:r}=js(t),s=a=>[...a].filter(([,i])=>i.size===1).map(([i,c])=>[i,[...c][0]]),o=s(r);return o.length===0&&n.every(a=>a.size===0)?e:e.map((a,i)=>{let c=new Map([...o,...s(n[i]??new Map)]);if(c.size===0)return a;let l=d=>{let f=d;for(let[p,u]of c)f=f.split(p).join(u);return f};return{...a,actions:a.actions.map(d=>mn(d,l,f=>l(f)))}})}function jp(e,t){let n=[],r=e.replace(/(^|[\s>+~,(])([A-Za-z][\w-]*)(?=$|[.#[:\s>+~,)])/g,(s,o,a)=>`${o}\0${n.push(a)-1}\0`);return t(r).replace(/\u0000(\d+)\u0000/g,(s,o)=>n[Number(o)])}function Jb(e,t,n,r){if(r.size===0)return e;let{own:s}=js(t),o=[...r].sort((c,l)=>l[1].length-c[1].length),a=c=>c.replace(/\{env:([A-Za-z_][A-Za-z0-9_]*)\}/g,(l,d)=>r.get(d)??l),i=c=>c.split(/(<[^<>\s]+>|\{[^{}]*\})/).map((l,d)=>d%2?l:o.reduce((f,[p,u])=>u===""?f:f.split(u).join(`{env:${p}}`),l)).join("");return e.map((c,l)=>{let d=ii(c.gherkin,t.steps[l]),f=[c.gherkin,...c.table?.flat()??[],c.docString??""].join(`
|
|
340
|
+
`),p=si(s[l]??new Map),u=[...d].flatMap(g=>{let S=n[g],y=!fe(f.replace(/\{data:[^{}]*\}/g," ")).includes(`<${g}>`);return S===void 0||S.length<3||y||/\{env:/.test(t.params[g]??"")||p.has(S)?[]:[...r].filter(([v,x])=>x!==""&&S.includes(x)&&!f.includes(`{env:${v}}`)).length===0?[]:Object.entries(t.params).some(([v,x])=>/\{env:/.test(x)&&n[v]===S)?[]:[[g,S]]}),h=new Map([...p].filter(([g,S])=>S.size===1&&g.trim()!=="").map(([g,S])=>[g,[...S][0]]));if(u.length===0&&h.size===0)return c;let b=g=>{let S=a(g),y=h.get(S);if(y!==void 0&&S!==g)return y;let w=S===g?S:[...h].filter(([x])=>x.length>=4).reduce((x,[$,E])=>x.split($).join(E),S),v=u.reduce((x,[$,E])=>x.split(E).join(`<${$}>`),w);return v===S?g:i(v)};return{...c,actions:c.actions.map(g=>mn(g,b,S=>b(S)))}})}function Wb(e,t){if(t.size===0)return e;let n=r=>typeof r=="string"?cu(r,t):Array.isArray(r)?r.map(n):r&&typeof r=="object"?Object.fromEntries(Object.entries(r).map(([s,o])=>[s,s==="pageFingerprint"?o:n(o)])):r;return e.map(r=>({...r,actions:r.actions.map(s=>n(s))}))}function Gb(e,t){return t.size===0?e:e.map(n=>{let r=new Set([...n.gherkin.matchAll(Ae)].map(b=>b[1])),s=[n.gherkin,...n.table?.flat()??[],n.docString??""].join(`
|
|
341
|
+
`).replace(/\{[^{}]*\}|<[^<>]+>/g," "),a=!/\{data:/.test(n.gherkin)?new Map([...t].filter(([,b])=>b===""||!xe(b).test(s))):t,i=[...new Set((s.match(/[\p{L}\p{N}]+(?:[-'][\p{L}\p{N}]+)*/gu)??[]).filter(b=>[...a.values()].some(g=>g.length>=4&&b!==g&&b.includes(g))))],c=i.length>0?new RegExp(`(${i.sort((b,g)=>g.length-b.length).map(be).join("|")})`):void 0,l=b=>c?b.split(c).map((g,S)=>S%2?g:ro(g,a,r)).join(""):ro(b,a,r),d=b=>new Map([...a].filter(([,g])=>g.length>=4).map(([g,S])=>[g,ue[b](S)])),f={quoted:d("quoted"),regex:d("regex"),pattern:d("pattern")},p=b=>b.split(/(\{(?:env|data|unique|date)[^{}]*\})/).map((g,S)=>S%2?g:l(g)).join(""),u=(b,g)=>p(ro(b,f[g],r)),h=b=>{let g=[...a].filter(([S,y])=>r.has(S)&&y===b);return g.length===1?`{data:${g[0][0]}}`:b};return{...n,actions:n.actions.map(b=>mn(b,l,u,h,g=>jp(g,p)))}})}function Dc(e,t,n){if(e!=="mcp__playwright__browser_tabs")return;let r=t??{},s=typeof r.index=="number"?String(r.index):void 0;switch(r.action){case"select":return s===void 0?void 0:{action:"switchTab",value:s};case"close":return s===void 0?{action:"closeTab"}:{action:"closeTab",value:s};case"new":return typeof r.url=="string"&&r.url?{action:"newTab",url:cs(r.url,n)}:{action:"newTab"};default:return}}function Mp(e,t){let n=t??{};if(e==="mcp__playwright__browser_handle_dialog"){let r={action:"handleDialog",value:n.accept?"accept":"dismiss"};return typeof n.promptText=="string"&&n.promptText&&(r.promptText=n.promptText),r}if(e==="mcp__playwright__browser_file_upload"){let r=Array.isArray(n.paths)?n.paths:[];if(r.length===0)return;let s=et().root+vb.sep;return{action:"uploadFile",value:r.map(a=>typeof a=="string"&&a.startsWith(s)?a.slice(s.length):a).join(`
|
|
342
|
+
`)}}}function qr(e,t){let n=e.pages().filter(s=>!s.isClosed()),r=s=>[...n].reverse().find(s);return(t?r(s=>s.url()===t):void 0)??r(s=>s.url()!=="about:blank")??n.at(-1)}async function ai(e,t,n=[]){let r=t.context();for(let o of e.contexts())if(!(o===r||n.includes(o)))for(let a of o.pages())await a.close().catch(()=>{});await t.bringToFront().catch(()=>{});let s=r.pages().filter(o=>!o.isClosed());return{index:Math.max(s.indexOf(t),0),count:s.length,url:t.url()}}var ci=class{constructor(t,n,r,s=o=>o.newPage()){this.main=t;this.mainKey=n;this.create=r;this.newPage=s;this.follow(t,n)}main;mainKey;create;newPage;pages=new Map;others=new Map;follow(t,n){t.on("page",r=>this.pages.set(n,r))}contextOf(t){return t===this.mainKey?this.main:this.others.get(t)}contexts(){return[this.main,...this.others.values()]}opened(){return[...this.others]}async open(t){let n=await this.create(t);this.others.set(t,n),this.follow(n,t);let r=await this.newPage(n);return this.pages.set(t,r),r}livePage(t){let n=this.pages.get(t);if(n&&!n.isClosed())return n;let r=this.contextOf(t);return r&&qr(r)}pageOf=async t=>{let n=this.livePage(t);if(n)return this.pages.set(t,n),n;let r=this.contextOf(t);if(!r)return this.open(t);let s=await this.newPage(r);return this.pages.set(t,s),s};selectTab(t,n){t??=this.mainKey;let r=this.contextOf(t)?.pages().filter(s=>!s.isClosed())[n];r&&this.pages.set(t,r)}async blank(){for(let[t,n]of this.others){let r=qr(n)??await this.newPage(n);await r.goto("about:blank").catch(()=>{}),this.pages.set(t,r)}}async close(){for(let t of this.others.values())await t.close().catch(()=>{});this.others.clear()}};var Ms="Agent session error: ";var zc=["chromium","chrome","msedge","firefox","webkit"],Bc={chrome:{label:"Google Chrome"},msedge:{label:"Microsoft Edge"}};function Up(e){return zc.includes(e)}function ur(e){return e==="chromium"||Bc[e]!==void 0}var Tt=class extends Error{},Uc=class extends Tt{},Hc=Object.keys(Lc);function zp(e){let t=/^(\d{2,5})x(\d{2,5})$/.exec(e.trim());return t?{width:Number(t[1]),height:Number(t[2])}:void 0}var Xb=/usage limit|insufficient_quota|exceeded your (?:current )?quota|quota exceeded|credit balance is too low/i,ev=/per min(?:ute)?\b|\b[TR]PM\b|(?:re)?try (?:again )?(?:in|after) \d+(?:\.\d+)?\s*(?:ms|s|sec|seconds?)\b/i,tv=e=>Xb.test(e)&&!ev.test(e);function Vr(e,t){return nt(e,t).split(`
|
|
343
|
+
`)[0]}function nv(e,t){let n=(r,s)=>{t.reason!==void 0||!tv(r)||(t.reason=Vr(r,Pe(s.scenario)).replace(/\.$/,""),console.log(` \u26A0 the agent's provider reported a usage limit; no new AI session starts in this run: ${t.reason}`))};return{run:async r=>{if(t.reason!==void 0)throw new Error(`the agent's provider reported a usage limit earlier in this run: ${t.reason}`);try{let s=await e.run(r);return!s.success&&s.narrative.startsWith(Ms)&&n(s.narrative.slice(Ms.length),r),s}catch(s){throw n(s instanceof Error?s.message:String(s),r),s}},...e.planUsage?{planUsage:()=>e.planUsage()}:{}}}var wn={aiCalls:0,inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheCreationTokens:0,costUsd:0};async function rv(){return new Promise((e,t)=>{let n=Kb.createServer();n.listen(0,"127.0.0.1",()=>{let{port:r}=n.address();n.close(()=>e(r))}),n.on("error",t)})}function sv(e){try{return`${e}
|
|
344
|
+
${Dt(e)}`}catch{return e}}function Dp(e,t){let n=xr(lt(e)),r=Pp(t,e);return{...n.size>0?{data:Object.fromEntries([...n].sort(([s],[o])=>s.localeCompare(o)))}:{},...Object.keys(e.params).length>0?{examples:e.params}:{},...r.length>0?{rowBound:r}:{},...(e.exampleRows??[]).some(s=>Kn(sv(JSON.stringify(s))))?{rowsUseNewDates:!0}:{}}}function Fc(e,t){return e.livePage(t??e.mainKey)}function Hp(e){let t=e.length;for(let n=e.length-1;n>=0&&e[n].kind==="assertion";n--)t=n;return t}function li(e,t){return e[t]?.kind==="assertion"&&t>=Hp(e)}function Fp(e,t,n=!1,r){let s=Hp(e);return e.map((o,a)=>{if(r&&a<r.stepIndex)return o;let i=t[a],c=i&&i.actions.length>0;return o.kind==="assertion"&&!(n&&a<s)||!c?o:r&&a===r.stepIndex&&r.actionIndex>0?{...i,actions:[...o.actions.slice(0,r.actionIndex),...i.actions]}:i})}function ov(e,t,n,r){let s=Lu(e,t);return s.length===0||!n?.pageUrl?s:[`page at failure: replay stopped at step ${n.stepIndex+1} ("${n.stepText}") on ${cs(n.pageUrl,r)}, where the heal started.`,...s]}function iv(e,t,n=0){return e.map((r,s)=>{if(s<n)return r;let o=t[s];return o&&o.actions.length>0?o:r})}function Lp(e,t){let n=[];for(let r=0;r<Math.min(t,e.length);r++){let s=e[r].actions.length;s!==0&&n.push(`recording: kept the existing recording of step ${r+1} ("${e[r].gherkin}"), which ran before the agent took over; ignored ${s} action${s===1?"":"s"} the agent's session held for it.`)}return n}function qp(e,t,n,r){let s=t.filter(c=>c>=0&&c<e.length),o=s.length>0?Math.max(...s):0,a=Math.min(n&&n.stepIndex>=o?n.stepIndex:o,e.length-1),i=n&&a===n.stepIndex?n.error:r;return e.map((c,l)=>({gherkin:c.gherkin,kind:c.kind,status:l<a?"passed":l===a?"failed":"skipped",...l===a&&i?{error:i}:{}}))}function av(e,t,n){let r=n.success?e.map(s=>({gherkin:s.gherkin,kind:s.kind,status:"passed"})):qp(e,n.announcedSteps??[],t,n.narrative);return e.map((s,o)=>o<t.stepIndex?s:r[o])}function Bp(e,t){return{aiCalls:e.aiCalls+t.aiCalls,inputTokens:e.inputTokens+t.inputTokens,outputTokens:e.outputTokens+t.outputTokens,cacheReadTokens:e.cacheReadTokens+t.cacheReadTokens,cacheCreationTokens:e.cacheCreationTokens+t.cacheCreationTokens,costUsd:(e.costUsd??0)+(t.costUsd??0),models:e.models||t.models?[...new Set([...e.models??[],...t.models??[]])]:void 0}}var di=class{constructor(t){this.options=t;this.filedThisRun=t.filedThisRun??new Map,this.agentHalt=t.agentHalt??{},t.agent&&(this.options={...t,agent:nv(t.agent,this.agentHalt)})}options;browser;cdpEndpoint;stepIndex;tabListeners=new Set;downloadListeners=new Set;armDialogs;openingOwnPages=new Set;filedThisRun;agentHalt;get agent(){return this.options.agent}getStepIndex(){if(!this.stepIndex&&(this.stepIndex=Wt(this.options.projectRoot),this.stepIndex.steps.size>0)){let t=this.stepIndex.divergent.length>0?` \xB7 ${this.stepIndex.divergent.length} step(s) have divergent recordings (Level-2 signal)`:"";console.log(`step index: ${this.stepIndex.steps.size} reusable steps from ${this.stepIndex.scannedCaches} cache(s)${t}`)}return this.stepIndex}async recordWithSeeding(t,n,r,s){let o=this.getStepIndex(),a=t.steps.length,i={...t.params,...Tn(t.steps)},c=t.steps.map(x=>{let $=o.steps.size>0?Bd(o,x,i):void 0;return $?{gherkin:x.text,keyword:x.keyword,kind:x.kind,table:x.table,docString:x.docString,fromStepSet:x.source?.fromStepSet,actions:$.actions}:void 0}),l=t.steps.map(x=>({gherkin:x.text,keyword:x.keyword,kind:x.kind,table:x.table,docString:x.docString,fromStepSet:x.source?.fromStepSet,actions:[]})),d=new Map;d.set(Ct,r);let f=[],p=[],u=[],h=[],b={...wn},g=x=>s.pageOf(pe(t.steps[x]?.session)),S=0,y=0,w=0,v=(x,$)=>({success:x,narrative:p.join(" ")||"Composed entirely from seeded recordings.",adaptations:f,suggestedFeatureEdit:h.length>0?h.join(`
|
|
345
|
+
`):void 0,featureEdits:u,recordedSteps:l,announcedSteps:$===void 0?[]:Array.from({length:$+1},(E,R)=>R),usage:b,seededCount:S});for(;w<a;){if(c[w]){let C=w;for(;C<a&&c[C];)C++;let P=c.slice(w,C),m={...t,steps:t.steps.slice(w,C)},A=await Bo(await g(w),m,this.buildCandidateCache(t,P),{sessions:s.pages,openSession:s.pageOf,downloadsDir:this.downloads(t),baseURL:this.options.baseURL,actionTimeoutMs:this.options.actionTimeoutMs,retries:this.options.retries,pollIntervalMs:this.options.pollIntervalMs,vars:d,trace:this.options.trace!==void 0&&this.options.trace!=="off",traceStepOffset:w,envNames:tt(t)}),O=A.status==="passed"?C-w:A.failure?.stepIndex??0;for(let _=0;_<O;_++)l[w+_]=P[_];if(S+=O,A.status==="passed"){w=C;continue}let T=w+O;f.push(`Seeded recording for "${t.steps[T].text}" did not replay in this scenario's context; the agent re-recorded it fresh. Divergence signal.`),c[T]=void 0,w=T;continue}if(!this.options.agent)return v(!1,w);y++;let x=w;for(;x<a&&!c[x];)x++;y>=3&&(x=a);let $=await ai(this.browser,await g(w),s.contexts()),E=await this.withDialogsVisible(()=>this.options.agent.run({scenario:t,baseURL:this.options.baseURL,traceContext:this.options.trace&&this.options.trace!=="off"?n.context():void 0,mode:"record",cdpEndpoint:this.cdpEndpoint,projectRoot:this.options.projectRoot,assertionPolicy:this.options.assertionPolicy,completedSteps:w>0?t.steps.slice(0,w).map(C=>C.resolvedText):void 0,recordOnly:x<a?{from:w,to:x-1}:void 0,liveTab:$,uniqueSeed:d.get(Ct),onTabOpened:this.tabWatcher(),onDownload:this.downloadWatcher(),...this.sessionHooks(t,s,n)}));if(b=Bp(b,E.usage),p.push(E.narrative),f.push(...E.adaptations),u.push(...E.featureEdits),E.suggestedFeatureEdit&&h.push(E.suggestedFeatureEdit),!E.success){let C=E.announcedSteps.filter(P=>P>=w&&P<a);return v(!1,C.length>0?Math.max(...C):w)}let R=E.announcedSteps.filter(C=>C>=w&&C<a),k=Math.min(a-1,Math.max(R.length>0?Math.max(...R):x-1,w));for(let C=w;C<=k;C++)l[C]=E.recordedSteps[C];w=k+1}return v(!0)}async withDialogsVisible(t){let n=()=>{},r=[],s=[],o=i=>{i.on("dialog",n),r.push(i)},a=i=>{i.on("page",o),s.push(i);for(let c of i.pages())o(c)};for(let i of this.browser?.contexts()??[])a(i);this.armDialogs=a;try{return await t()}finally{this.armDialogs=void 0;for(let i of s)i.off("page",o);for(let i of r)try{i.off("dialog",n)}catch{}}}async start(){let t=this.options.browser??"chromium";if(ur(t)){let r=await rv();try{this.browser=await Yb.launch({headless:!this.options.headed,channel:Bc[t]?t:void 0,args:[`--remote-debugging-port=${r}`],handleSIGINT:!1})}catch(s){let o=s instanceof Error?s.message:String(s),a=Bc[t];throw a&&/is not found at|distribution .* is not found/i.test(o)?new Uc(`${a.label} is not installed on this machine, so --browser ${t} cannot run.
|
|
346
|
+
Install it (npx playwright install ${t} does that), or use --browser chromium, which Saffron ships with.`):s}this.cdpEndpoint=`http://127.0.0.1:${r}`}else this.browser=await(t==="firefox"?Zb:Qb).launch({headless:!this.options.headed,handleSIGINT:!1}),this.cdpEndpoint=void 0;let n;try{n=this.contextOptions();let r=this.options.sessions??{},s=i=>typeof i=="object"&&i!==null&&!Array.isArray(i);if(!s(r))throw new Tt('"sessions" in saffron.config.json must map session names to their settings, such as { "buyer": { "storageState": ".auth/buyer.json" } }.');for(let[i,c]of Object.entries(r)){let l=`{ "storageState": ".auth/${ns(i)}.json" }`;if(!s(c)||Object.keys(c).some(d=>d!=="storageState"))throw new Tt(`sessions."${i}" in saffron.config.json takes only a storageState, such as ${l}.`);if(c.storageState!==void 0&&(typeof c.storageState!="string"||c.storageState.trim()===""))throw new Tt(`sessions."${i}".storageState in saffron.config.json must be a file path, such as ".auth/${ns(i)}.json".`);if(i===Ft&&c.storageState!==void 0&&bt.resolve(this.options.projectRoot,c.storageState)!==n.storageState)throw new Tt(`sessions."${Ft}".storageState in saffron.config.json is never read: the default session signs in with the top-level storageState. Set that instead, or make the two the same.`);i!==Ft&&this.contextOptions(i)}let o=new Set([n.storageState,...Object.keys(r).filter(i=>i!==Ft).map(i=>this.contextOptions(i).storageState)]),a=this.browser;await Promise.all([...o].filter(i=>typeof i=="string").map(async i=>{try{let c=JSON.parse(Xt.readFileSync(i,"utf8"));if(!c||typeof c!="object"||Array.isArray(c))throw new Error("it is not a JSON object");await(await a.newContext({storageState:i})).close()}catch(c){throw new Tt(`storageState file ${i} cannot be used: ${(c instanceof Error?c.message:String(c)).split(`
|
|
347
|
+
`)[0]}. Generate it again with: npx playwright open --save-storage=${Be(this.options.projectRoot,i)} <url>`)}}))}catch(r){throw await this.stop(),r}if(this.options.device||this.options.viewport){if(t==="firefox"&&this.options.device&&Lc[this.options.device]?.isMobile)throw await this.stop(),new Tt(`--device "${this.options.device}" is a mobile profile, and Playwright does not emulate mobile devices in Firefox. Run it in chromium or webkit, or give Firefox a --viewport instead.`);try{await(await this.browser.newContext(n)).close()}catch(r){await this.stop();let s=(r instanceof Error?r.message:String(r)).split(`
|
|
348
|
+
`)[0];throw new Tt(`${this.options.device?`--device "${this.options.device}"`:"--viewport"} cannot run in ${t}: ${s}`)}}}async stop(){await this.browser?.close(),this.browser=void 0}resolveStorageState(t=this.options.storageState){if(!t)return;let n=bt.isAbsolute(t)?t:bt.join(this.options.projectRoot,t);if(!Xt.existsSync(n))throw new Tt(`storageState file not found: ${n}. Generate one with: npx playwright open --save-storage=${t} <url>`);return n}contextOptions(t){let{defaultBrowserType:n,...r}=this.options.device?Lc[this.options.device]??{}:{},s=t===void 0?void 0:this.options.sessions?.[t]?.storageState;return{storageState:this.resolveStorageState(s??this.options.storageState),...r,...this.options.viewport?{viewport:this.options.viewport}:{},...this.options.timezone?{timezoneId:this.options.timezone}:{}}}artifacts(t){let n=ln(this.options.projectRoot,t.featurePath,t.displayName);return this.options.artifactsPerBrowser?bt.join(n,this.options.browser??"chromium"):n}downloads(t){return bt.join(this.artifacts(t),"downloads")}buildCandidateCache(t,n){let r={version:1,feature:t.featurePath,scenario:t.name,recordedAt:new Date().toISOString(),recordedBy:"agent",steps:n,...Dp(t,n)};return{...r,version:as(r)}}tabWatcher(){return t=>{let n=r=>t(r);return this.tabListeners.add(n),()=>{this.tabListeners.delete(n)}}}downloadWatcher(){return t=>(this.downloadListeners.add(t),()=>{this.downloadListeners.delete(t)})}async newContext(t,n){let r=await this.browser.newContext(this.contextOptions(t||void 0));return r.on("page",()=>{if(!this.openingOwnPages.has(r))for(let s of this.tabListeners)s(t)}),r.on("page",s=>s.on("download",o=>{for(let a of this.downloadListeners)a(o)})),this.armDialogs?.(r),n&&this.options.trace!==void 0&&this.options.trace!=="off"&&await _u(r,n),r}sessionsFor(t,n,r){return new ci(n,pe(t.steps[0]?.session),s=>this.newContext(s,`${r} \xB7 session "${dt(s)}"`),async s=>{this.openingOwnPages.add(s);try{return await s.newPage()}finally{this.openingOwnPages.delete(s)}})}sessionHooks(t,n,r){return{sessionPage:n.pageOf,onActiveTab:(s,o)=>n.selectTab(o,s),takeFingerprint:async s=>_o(Fc(n,s)??r)}}namedSession(t,n){return An(n)?{session:dt(t.mainKey)}:{}}async saveSessionTraces(t,n,r,s){let o=[],a=Pe(t),i=new Set;for(let[c,l]of n.opened()){if(!r){await No(l).catch(()=>{});continue}let d=ns(dt(c));for(let u=2;i.has(d);u++)d=`${ns(dt(c))}-${u}`;i.add(d);let f=bt.join(this.artifacts(t),`${r}.${d}.zip`),p=await jo(l,f,a);p&&(this.claimArtifactDir(t),o.push({...s,kind:"trace",file:Be(this.options.projectRoot,f),sha256:p,session:dt(c)}))}return o}async proofReplay(t,n,r,s){let o=this.options.trace!==void 0&&this.options.trace!=="off",a=s?t.displayName:`${t.displayName} (proof replay)`,i=await this.newContext(pe(t.steps[0]?.session),a),c=this.sessionsFor(t,i,a),l=await i.newPage();return{result:await Bo(l,t,n,{sessions:c.pages,openSession:c.pageOf,downloadsDir:this.downloads(t),baseURL:this.options.baseURL,actionTimeoutMs:this.options.actionTimeoutMs,retries:this.options.retries,pollIntervalMs:this.options.pollIntervalMs,uniqueSeed:r,trace:o,tracePhase:s}),context:i,page:l,sessions:c}}async runScenario(t,n={}){let r=await this.runScenarioInner(t,n),s=Pe(t);if(s.size>0){let o=i=>i===void 0?i:nt(i,s);r.error=o(r.error),r.narrative=o(r.narrative),r.proofError=o(r.proofError),r.suggestedFeatureEdit=o(r.suggestedFeatureEdit),r.adaptations=r.adaptations.map(i=>nt(i,s));let a=[r.stepResults,r.executionStepResults,...(r.evidence??[]).map(i=>i.traceSteps)];for(let i of a.flatMap(c=>c??[])){i.error=o(i.error);for(let c of i.tabs??[])c.url=nt(c.url,s);for(let c of i.responses??[])c.url=nt(c.url,s)}}return r}async screenshot(t,n,r,s){let o=this.options.screenshot??"viewport";if(o!=="off")try{let a=this.artifacts(n);this.claimArtifactDir(n);let i=bt.join(a,`${r}.jpg`),c=await t.screenshot({path:i,type:"jpeg",quality:80,fullPage:o==="full-page",timeout:5e3});return{kind:r,file:Be(this.options.projectRoot,i),step:s,sha256:zt(c)}}catch{return}}claimArtifactDir(t){let n=ln(this.options.projectRoot,t.featurePath,t.displayName);Xt.mkdirSync(this.artifacts(t),{recursive:!0}),Xt.writeFileSync(bt.join(n,Xn),JSON.stringify({feature:t.featurePath,scenario:t.displayName},null,2))}async runScenarioInner(t,n={}){if(!this.browser)throw new Error("Orchestrator not started");let r=Date.now(),{projectRoot:s,baseURL:o,actionTimeoutMs:a,retries:i,pollIntervalMs:c}=this.options,l=me(s,t.featurePath,t.name),d;try{d=st(l)}catch(_){if(!(_ instanceof $e))throw _;return{scenario:t,status:"red",source:"cache",stepResults:[],adaptations:[],usage:wn,durationMs:Date.now()-r,error:`The recording cannot be read: ${_.problem}. Fix the file, or re-record it with saffron run --rerecord.`}}let f=xt(s,t.featurePath,t.name),p=Be(s,f),u,h;if(Xt.existsSync(f))try{({proposal:u,revision:h}=ko(f))}catch(_){if(!(_ instanceof $e)&&_.code!=="ENOENT")throw _;u=void 0}let b=!1;u&&!Xd(s,f,h)&&(b=!this.options.rerecord,u=void 0),u&&$t(s,u,t)&&(u=void 0),u&&this.options.rerecord&&this.filedThisRun.get(f)!==h&&(u=void 0);let g=d&&Fn(t,d)||u&&Fn(t,u.cache);if(g)return{scenario:t,status:"red",source:"cache",stepResults:[],adaptations:[],usage:wn,durationMs:Date.now()-r,error:g};let S=_=>_.status==="stale"?"the committed recording no longer matches the scenario":`the committed recording failed${_.failure?` at "${_.failure.stepText}"`:""}`,y=_=>{let N=hn(s)[p],F=N?.revision===h?` from ${ce(_s(N.from))}`:"",I=_?S(_):"";return{scenario:t,status:"yellow",source:d?"cache":"agent-record",stepResults:_?.stepResults??[],narrative:(I?`${I[0].toUpperCase()}${I.slice(1)}. `:"")+`A proposal${F} is pending review at ${p}. It was not filed on this machine, so this run does not replay it, heal or record over it. Review it with saffron diff ${p}, then saffron accept or saffron reject it.`,adaptations:[],proposalFile:p,proposalRevision:h,usage:wn,durationMs:Date.now()-r}};if(Xt.rmSync(this.artifacts(t),{recursive:!0,force:!0}),this.options.artifactsPerBrowser){let _=ln(s,t.featurePath,t.displayName);for(let N of Xt.existsSync(_)?Xt.readdirSync(_,{withFileTypes:!0}):[])N.isFile()&&N.name!==Xn&&Xt.rmSync(bt.join(_,N.name),{force:!0})}if(b&&!d)return y();let w=(_,N)=>({scenario:t,status:"yellow",source:"agent-record",proposalReplay:!0,stepResults:_.stepResults,narrative:`Replayed the pending proposal recorded for "${u.meta.recordedFor??t.name}" at zero AI${N?` instead of ${N.status==="stale"?"recording":"healing"} again: ${S(N)}`:""}; accept it to go green.`,adaptations:[],verified:!0,proposalFile:p,proposalRevision:h,usage:wn,durationMs:Date.now()-r}),v=this.options.trace??"off",x=v!=="off",$=await this.newContext(pe(t.steps[0]?.session),t.displayName),E=this.sessionsFor(t,$,t.displayName),R=new Map,k=!x,C,P,m=await $.newPage(),A=fn(),O=[],T=(_,N)=>this.screenshot(_,t,"before-heal",N.stepText).then(F=>{F&&O.push(F)});try{let _=await(async()=>{let I;if(u&&!d){let M=fn(),U=await this.proofReplay(t,u.cache,M,"pending"),z=U.result,V=u.meta.recordedFor??t.name,ee=Object.keys(t.params).length>0&&V!==t.displayName;if(z.status==="passed"||ee?(C=U.context,P=U.sessions,A=M):(await U.sessions.close(),await U.context.close()),z.status==="passed")return w(z);if(ee){let Ie=z.failure,Ke=u.cache.examples??{},Ne=Ie?t.steps[Ie.stepIndex]?.text??"":"",Te=Object.keys(t.params).filter(at=>at in Ke&&Ke[at]!==t.params[at]).sort((at,Sn)=>Number(Ne.includes(`<${Sn}>`))-Number(Ne.includes(`<${at}>`))),qt=Te.slice(0,3).map(at=>`<${at}> is ${JSON.stringify(t.params[at])} here, ${JSON.stringify(Ke[at])} there${Ne.includes(`<${at}>`)?" (the failing step uses it)":""}`);return{scenario:t,status:"red",source:"agent-record",proposalReplay:!0,stepResults:z.stepResults,adaptations:[],proposalFile:p,proposalRevision:h,usage:wn,durationMs:Date.now()-r,error:`The pending proposal recorded for "${V}" does not replay for this Examples row`+(Ie?` (step "${Ie.stepText}": ${Vr(Ie.error,Pe(t))})`:"")+(qt.length>0?`. This row differs from it where ${qt.join("; ")}${Te.length>3?`; and ${Te.length-3} more column(s)`:""}`:"")+`. Check whether that step recorded the other row's value instead of a <placeholder> or acts on the wrong element (saffron diff ${p}); if so, reject it and re-record with saffron run --rerecord.`}}console.log(nt(` \u21BA pending proposal for "${t.displayName}" did not replay`+(z.failure?` (step "${z.failure.stepText}": ${Vr(z.failure.error,Pe(t))})`:"")+"; recording again",Pe(t)))}if(d){if(I=await Bo(m,t,d,{vars:R,sessions:E.pages,openSession:E.pageOf,downloadsDir:this.downloads(t),baseURL:o,actionTimeoutMs:a,retries:i,pollIntervalMs:c,uniqueSeed:A,trace:x,onFailure:T,keepResponseLog:!0}),I.status==="passed")return{scenario:t,status:"green",source:"cache",stepResults:I.stepResults,adaptations:[],usage:wn,durationMs:Date.now()-r};if(b)return I.responses?.detach(),y(I);let M=U=>d.steps[U].kind==="assertion"&&(this.options.assertionPolicy!=="adaptable-mid"||li(d.steps,U));if(u&&I.status==="failed"&&d.steps.some((U,z)=>M(z)&&!ha(u.cache.steps[z]?.actions??[],U.actions))&&(u=void 0),u){let U=fn(),z=await this.proofReplay(t,u.cache,U,"pending");if(z.result.status==="passed")return I.responses?.detach(),C=z.context,P=z.sessions,A=U,w(z.result,I);await z.sessions.close(),await z.context.close(),console.log(nt(` \u21BA pending proposal for "${t.displayName}" did not replay`+(z.result.failure?` (step "${z.result.failure.stepText}": ${Vr(z.result.failure.error,Pe(t))})`:"")+(I.status==="failed"?"; healing":"; recording again"),Pe(t)))}}if(!(this.options.agent!==void 0&&this.cdpEndpoint!==void 0&&!n.agentDisabled&&this.agentHalt.reason===void 0)){let M=this.options.agent!==void 0&&!n.agentDisabled&&this.agentHalt.reason!==void 0?`the agent's provider reported a usage limit earlier in this run, so no AI session was started for it: ${this.agentHalt.reason}. Run it again once the limit resets.`:this.options.agent!==void 0&&this.cdpEndpoint===void 0&&!n.agentDisabled?`recording/healing needs a Chromium-family browser (the agent attaches over CDP). Record with --browser chromium (the default), chrome or msedge, then replay with --browser ${this.options.browser}.`:this.options.agent!==void 0&&n.agentDisabled?this.cdpEndpoint===void 0?`recording/healing needs a Chromium-family browser (the agent attaches over CDP). Record with --browser chromium (the default), chrome or msedge, then replay with --browser ${this.options.browser}.`:"this run was started without the agent (--no-agent), so nothing records it.":"no agent is configured.";I?.responses?.detach();let U=d!==void 0&&d.examples===void 0&&Object.keys(t.params).length>0&&d.steps.length===t.steps.length&&d.steps.every((z,V)=>{let ee=t.steps[V];return z.gherkin===ee.text&&z.kind===ee.kind&&z.docString===ee.docString&&JSON.stringify(z.table)===JSON.stringify(ee.table)})&&Object.entries(d.data??{}).every(([z,V])=>{try{return qe(z)===V}catch{return!0}});return{scenario:t,status:"red",source:"cache",stepResults:I?.stepResults??[],adaptations:[],usage:wn,durationMs:Date.now()-r,error:d?I?.status==="stale"?U?`The recording was made by an older saffron-ai and still holds another Examples row's value, so this row needs it recorded again once, and ${M}`:`Cache is stale (feature file changed) and ${M}`:`Replay failed and ${M} ${I?.failure?.error??""}`.trimEnd():`No cache exists and ${M}`}}let j=d!==void 0&&I!==void 0&&I.status==="failed",H=0,Z,Q;try{if(j){Q=I.responses;let M=E.contextOf(pe(t.steps[I.failure.stepIndex]?.session))??m.context(),U=await ai(this.browser,I.activePage??qr(M,I.failure.pageUrl)??m,E.contexts());Z=await this.withDialogsVisible(()=>this.options.agent.run({scenario:t,baseURL:o,traceContext:x?m.context():void 0,mode:"heal",onBrowserAction:z=>{z===pe(t.steps[I.failure.stepIndex]?.session)&&Q?.markAction()},liveTab:U,model:this.options.healModel,cdpEndpoint:this.cdpEndpoint,projectRoot:this.options.projectRoot,assertionPolicy:this.options.assertionPolicy,completedSteps:I.stepResults.filter(z=>z.status==="passed").map(z=>z.gherkin),failedStep:{text:I.failure.stepText,kind:I.failure.kind,error:I.failure.error,pageUrl:I.failure.pageUrl,stepIndex:I.failure.stepIndex},uniqueSeed:A,onTabOpened:this.tabWatcher(),onDownload:this.downloadWatcher(),...this.sessionHooks(t,E,m)}))}else if(await m.goto("about:blank"),await E.blank(),E.pages.set(E.mainKey,m),this.options.reuseSteps!==!1){let M=await this.recordWithSeeding(t,m,A,E);H=M.seededCount,Z=M}else Z=await this.withDialogsVisible(()=>this.options.agent.run({scenario:t,baseURL:o,traceContext:x?m.context():void 0,mode:"record",cdpEndpoint:this.cdpEndpoint,projectRoot:this.options.projectRoot,assertionPolicy:this.options.assertionPolicy,uniqueSeed:A,onTabOpened:this.tabWatcher(),onDownload:this.downloadWatcher(),...this.sessionHooks(t,E,m)}))}catch(M){Q?.detach();let U=M instanceof Error?M.message:String(M);return{scenario:t,status:"red",source:j?"agent-heal":"agent-record",stepResults:I?.stepResults??[],adaptations:[],usage:wn,durationMs:Date.now()-r,error:`Agent invocation failed: ${Vr(U,Pe(t))}`}}if(Z.success&&j&&I.failure.kind==="assertion"&&(this.options.assertionPolicy!=="adaptable-mid"||li(d.steps,I.failure.stepIndex))){let M=d.steps[I.failure.stepIndex],U=Fc(E,pe(t.steps[I.failure.stepIndex]?.session))??m,z=Wa(t,I.failure.stepIndex);try{for(let V of M.actions)await ys(U,V,z,this.options.actionTimeoutMs??5e3,o,R,Q,void 0,tt(t))}catch(V){let ee=V instanceof Error?V.message:String(V),Ie=`Assertion failed as written: "${M.gherkin}". Saffron never adapts assertions. If this change is intended, update the .feature file or re-record the scenario (saffron run --rerecord --filter @tag). If the recording itself looks wrong (an empty value, a wrong target), re-record it the same way. Verification error: ${Vr(ee,Pe(t))}`,Ke=I.failure.stepIndex,Ne=I.stepResults.map((Te,qt)=>qt===Ke?{...Te,status:"failed",error:Ie}:Te);return{scenario:t,status:"red",source:"agent-heal",stepResults:Ne,executionStepResults:Ne.map((Te,qt)=>qt>Ke&&Te.status==="skipped"?{...Te,status:"passed"}:Te),narrative:Z.narrative,adaptations:Z.adaptations,suggestedFeatureEdit:Z.suggestedFeatureEdit,usage:Z.usage,durationMs:Date.now()-r,error:Ie}}finally{Q?.detach()}}return Q?.detach(),await this.finalizeAgentRun(t,Z,j,d,r,H,j?I?.failure:void 0,A)})(),N=O.find(I=>I.kind==="before-heal");if(_.source==="cache"&&N){let I=N.file.replace(/before-heal\.jpg$/,"failure.jpg");try{Xt.renameSync(bt.join(s,N.file),bt.join(s,I)),N.file=I}catch{}N.kind="failure"}else if(_.status==="red"){let I=_.stepResults.findIndex(Z=>Z.status==="failed"),L=_.stepResults[I]?.gherkin,j=pe(t.steps[Math.max(I,0)]?.session),H=await this.screenshot(Fc(P??E,j)??m,t,"failure",L);H&&O.push(H)}let F=Ir(lt(t),A);if(F.size>0&&(_.uniques=Object.fromEntries(F)),O.push(..._.evidence??[]),x){let L=v==="on"||_.status!=="green"?bt.join(this.artifacts(t),Oa):void 0;k=!0;let j=C??$;L||await No(j).catch(()=>{});let H=L?await jo(j,L,Pe(t)):void 0,Z=Pe(t),Q=(_.executionStepResults??_.stepResults).map(z=>({...z,error:z.error&&nt(z.error,Z)})),M=P??E,U=await this.saveSessionTraces(t,M,L&&H?bt.basename(L,".zip"):void 0,{traceSteps:Q});L&&H&&(this.claimArtifactDir(t),O.unshift({kind:"trace",file:Be(s,L),sha256:H,traceSteps:Q,...this.namedSession(M,t.steps)},...U))}return O.length>0&&(_.status!=="green"||O.some(I=>I.kind==="trace"))&&(_.evidence=O),_}finally{k||await No($).catch(()=>{}),await P?.close(),await C?.close(),await E.close(),await $.close()}}async finalizeAgentRun(t,n,r,s,o,a=0,i,c=fn()){let l=r?"agent-heal":"agent-record",d=n.success?n.recordedSteps.map(j=>({gherkin:j.gherkin,kind:j.kind,status:"passed"})):qp(n.recordedSteps,n.announcedSteps??[],i&&{stepIndex:i.stepIndex,error:i.error},n.narrative);if(!n.success)return{scenario:t,status:"red",source:l,stepResults:d,narrative:n.narrative,adaptations:n.adaptations,usage:n.usage,durationMs:Date.now()-o,error:n.narrative};let f=r?Fp(s.steps,n.recordedSteps,this.options.assertionPolicy==="adaptable-mid",i?{stepIndex:i.stepIndex,actionIndex:i.actionIndex}:void 0):n.recordedSteps,p=[...n.adaptations,...r&&i?Lp(n.recordedSteps,i.stepIndex):[]],u={...n.usage},h,b,g,S,y=[],w=0,v=new Set,x,$=async({context:j,sessions:H},Z,Q=Z.stepResults)=>{if(!v.has(j)){v.add(j);try{if(this.options.trace&&this.options.trace!=="off"){let M=`proof-${++w}`,U=bt.join(this.artifacts(t),`${M}.zip`),z=Pe(t),V=await jo(j,U,z),ee=Z.captured[Ct],Ie=ee?Ir(lt(t),ee):new Map,Ke={proof:!0,traceSteps:Q.map(Te=>({...Te,error:Te.error&&nt(Te.error,z)})),traceUniques:Ie.size?Object.fromEntries(Ie):void 0},Ne=await this.saveSessionTraces(t,H,V?M:void 0,Ke);V&&(this.claimArtifactDir(t),y.push({kind:"trace",file:Be(this.options.projectRoot,U),sha256:V,...Ke,...this.namedSession(H,t.steps)},...Ne))}}finally{await H.close(),await j.close()}}};if(this.options.verifyProposals!==!1){let j=await this.proofReplay(t,this.buildCandidateCache(t,f),fn());S=j.result.captured[Ct];try{if(j.result.status!=="passed"&&j.result.failure){let H=j.result.failure;if(this.options.agent&&!(r&&H.kind==="assertion"&&(this.options.assertionPolicy!=="adaptable-mid"||li(s.steps,H.stepIndex))))try{let Q=j.sessions.contextOf(pe(t.steps[H.stepIndex]?.session))??j.context,M=await ai(this.browser,j.result.activePage??qr(Q,H.pageUrl)??j.page,j.sessions.contexts()),U=await this.withDialogsVisible(()=>this.options.agent.run({scenario:t,baseURL:this.options.baseURL,traceContext:this.options.trace&&this.options.trace!=="off"?j.context:void 0,mode:"refine",model:r?this.options.healModel:void 0,cdpEndpoint:this.cdpEndpoint,projectRoot:this.options.projectRoot,assertionPolicy:this.options.assertionPolicy,completedSteps:j.result.stepResults.filter(z=>z.status==="passed").map(z=>z.gherkin),failedStep:{text:H.stepText,kind:H.kind,error:H.error,pageUrl:H.pageUrl,stepIndex:H.stepIndex},liveTab:M,uniqueSeed:j.result.captured[Ct],onTabOpened:this.tabWatcher(),onDownload:this.downloadWatcher(),...this.sessionHooks(t,j.sessions,j.page)}));u=Bp(u,U.usage),x=av(j.result.stepResults,H,U),U.success&&(p.push(...U.adaptations),p.push(...Lp(U.recordedSteps,H.stepIndex)),f=r?Fp(f,U.recordedSteps,this.options.assertionPolicy==="adaptable-mid",{stepIndex:H.stepIndex,actionIndex:0}):iv(f,U.recordedSteps,H.stepIndex),await $(j,j.result,x),x=void 0,j=await this.proofReplay(t,this.buildCandidateCache(t,f),fn()),S=j.result.captured[Ct])}catch{}}for(let H of j.result.tabOpeners??[]){let Z=f[H.stepIndex]?.actions[H.actionIndex];Z&&(Z.opensTab=!0)}h=j.result.status==="passed",h||(b=j.result.failure?.error??`proof replay ${j.result.status}`,g=j.result.stepResults)}finally{await $(j,j.result,x).catch(()=>{})}}r&&s&&p.push(...ov(s.steps,f,i,this.options.baseURL));let E=j=>r&&t.steps[j]?.kind==="assertion"&&(this.options.assertionPolicy!=="adaptable-mid"||li(s.steps,j)),R=n.featureEdits.filter(j=>!E(j.index));for(let j of Ud(f,Wt(this.options.projectRoot)))p.push(`duplicate wording: "${j.from}" recorded exactly the same actions as the existing step "${j.to}" (${j.feature} \u203A ${j.scenario}). Accept with --with-feature-edit to converge on the canonical wording.`),R.some(H=>H.index===j.index)||R.push({index:j.index,text:j.to});let k=_p(f);k.length>0&&(h=!1,b=[b,...k].filter(Boolean).join(" "));let C=Pe(t),P=j=>C.size>0?nt(j,C):j;p=p.map(P);let m=R.map(j=>({index:j.index,text:P(j.text)})),A=P(n.narrative),O=n.suggestedFeatureEdit?P(n.suggestedFeatureEdit):void 0,T={version:1,feature:t.featurePath,scenario:t.name,recordedAt:new Date().toISOString(),recordedBy:"agent",steps:f,...Dp(t,f)},_={...T,version:as(T)},N={meta:{createdAt:_.recordedAt,mode:r?"heal":"record",narrative:A,adaptations:p,suggestedFeatureEdit:O,featureEdits:m.length>0?m:void 0,verified:h,proofError:b?P(b):void 0,seededSteps:a>0?a:void 0,recordedFor:t.displayName,usage:u,bound:ef(t,s,_,m.length>0?m:void 0)},cache:_},F=xt(this.options.projectRoot,t.featurePath,t.name),I=Yd(F,N);eu(this.options.projectRoot,F,I),this.filedThisRun.set(F,I);let L=st(me(this.options.projectRoot,t.featurePath,t.name));return{proposalDiff:Nn(L,N.cache),scenario:t,status:"yellow",source:l,stepResults:g??d,executionStepResults:d,evidence:y,proofUniques:(()=>{let j=S?Ir(lt(t),S):void 0;return j&&j.size>0?Object.fromEntries(j):void 0})(),narrative:A,adaptations:p,suggestedFeatureEdit:O,featureEdits:m.length>0?m:void 0,verified:h,proofError:b,seededSteps:a>0?a:void 0,proposalFile:Be(this.options.projectRoot,F),proposalRevision:I,usage:u,durationMs:Date.now()-o}}};import ki from"node:fs";import mx from"node:os";import Sg from"node:path";import{query as Bv}from"@anthropic-ai/claude-agent-sdk";import{createRequire as cv}from"node:module";import lv from"node:path";import{McpServer as dv}from"@modelcontextprotocol/sdk/server/mcp.js";import{z as ne}from"zod";var _e=e=>({content:[{type:"text",text:e}]});function Jr(e,t,n,r){let s=async o=>{let a=await r(o);return a.content[0]?.text.startsWith("ERROR:")?{...a,isError:!0}:a};return o=>{o.registerTool(e,{description:t,inputSchema:n},s)}}function uv(e){let t=new dv({name:e.name,version:e.version});for(let n of e.tools)n(t);return{type:"sdk",name:e.name,instance:t}}function Vp(e){let t={};return e.role&&(t.role=e.role),e.name&&(t.name=e.name),e.nameRegex&&(t.nameRegex=e.nameRegex),e.label&&(t.label=e.label),e.text&&(t.text=e.text),e.selector&&(t.fallbackSelectors=[e.selector]),e.frame&&(t.frame=e.frame),Object.keys(t).length>0?t:void 0}var fv=new Set(["main","banner","contentinfo","status","alert","alertdialog","dialog","search"]);function Jp(e){if(!e?.role)return;let{role:t,frame:n,...r}=e;if(!(Object.keys(r).length>0||fv.has(t)))return`ERROR: role="${t}" alone matches every ${t} on the page, and replay would use the first one. Add a name (or nameRegex), text, label or selector that picks exactly the element you checked, then call again.`}function pv(e,t){if(t.index>=e.steps.length)return`ERROR: there is no step ${t.index}: this scenario's steps are numbered from 0 to ${e.steps.length-1}. Call saffron_step again with the zero-based index of the step you are about to perform.`;if(e.announce(t.index,t.text,t.adaptation),t.index<e.firstStep)return`Step ${t.index} already ran before you took over and keeps its recording; nothing you do under it is recorded. Do not redo it: continue from step ${e.firstStep} on the page as it is.`;let n=e.steps[t.index].kind==="assertion"?"verify it from a snapshot and record the check with saffron_assert":"do it now with the browser tools";return`Recording step ${t.index}: ${t.text}. This only files the browser calls that follow under the step; it performs nothing itself, so ${n}.`}function gv(e){let t=Math.max(-1,...e.announced,e.lastStep??-1),n=[],r=[],s=c=>[...fe(e.steps[c]?.gherkin??"").matchAll(/<([^<>]+)>/g)].some(l=>e.params?.[l[1]]!==void 0),o=[...new Set([...e.announced,...e.lastStep===void 0?[]:e.steps.map((c,l)=>l).filter(c=>c<=e.lastStep)])].filter(c=>c>=e.firstStep&&e.steps[c]?.kind==="assertion"&&!e.steps[c].actions.some(l=>Se.has(l.action))).sort((c,l)=>c-l);o.length>0&&n.push(`Assertion step ${o.join(", ")} recorded no check, so replay would verify nothing. Record what you verified with saffron_assert under that step (saffron_step first if you moved on).`);let a=[],i=!1;for(let c=0;c<=t;c++){let l=e.steps[c],d=l?.keyword.trim().toLowerCase(),f=d===void 0?void 0:hv.get(d);if(e.setupSteps[c]!==void 0?i=e.setupSteps[c]:f!==void 0&&(i=f==="given"),c<e.firstStep||l?.kind!=="action"&&l?.kind!=="assertion")continue;let p=l.kind==="assertion";if(!p&&l.actions.length===0){(!i||s(c))&&a.push(c);continue}if(l.actions.filter(b=>Hr(b)||oi(b)||p&&b.target!==void 0&&Se.has(b.action)).length===0)continue;let h=new Set(Is(e.resolvedTexts[c]??"",!0));for(let b of Is(e.resolvedTexts[c]??"")){let g;try{g=Dt(b)}catch{continue}let S=/[{}<>]/.test(g)?[]:jc(l.actions,g,p,h.has(b));if(S.length!==0){r.push({index:c,actions:S}),n.push(`Step ${c} acts in "${g}", but ${S.length===1?"this target does":"these targets do"} not name it (${S.map(it).join("; ")}). Replay would act on the first match, which on a page with two such sections is the wrong one. If its element is still on the page, call saffron_step ${c} again and perform only ${S.length===1?"that action":"those actions"} once more with a target scoped to that container, e.g. selector 'role=region[name="${g}"] >> role=textbox[name="..."]' (a snapshot ref is not scoped; a capture or a check is saffron_capture or saffron_assert again with that selector): the new action takes the old one's place, and the step's other actions stay. An element of a dialog or menu that a scoped action opened is not in the section: scope it to that dialog instead ('role=dialog >> role=button[name="..."]'). If the page has moved on, do not go back for it.`);break}}}if(a.length>0){let c=a.filter(s);n.push(`Action step ${a.join(", ")} recorded no browser action. saffron_step performs nothing: perform the step with a browser tool right after announcing it, or, for a step that waits for the page, record what it waits for with saffron_assert so replay waits too. If you already performed its action under another step, do not perform it again: replay runs it there. `+(c.length===a.length?"":"If the page already was in the state the step asks for, it needs nothing. ")+(c.length===0?"":`Step ${c.join(", ")} names an Examples column, which other rows set to other values: even if the page already shows this row's value, call saffron_step again and pick it (click the option or radio labelled with it), so replay picks each row's own. Left empty, every row replays this row's page.`))}return{problems:n,redo:r}}var hv=(()=>{let e=cv(import.meta.url)("@cucumber/gherkin").dialects,t=new Map;for(let n of Object.values(e))for(let r of["when","then","given"])for(let s of n[r])s.trim()!=="*"&&t.set(s.trim().toLowerCase(),r);return t})(),Wp=new WeakSet;function mv(e,t){if(t.success&&!Wp.has(e)){let{problems:n,redo:r}=gv(e);if(n.length>0)return Wp.add(e),e.redo(r),`ERROR: not finalized. ${n.join(" ")} Then call saffron_done again. If a condition does not hold, call saffron_done with success=false.`}return e.done=!0,e.success=t.success,e.narrative=t.narrative,e.suggestedFeatureEdit=t.suggestedFeatureEdit,e.featureEdits=(t.featureEdits??[]).filter(n=>!ua.test(n.text)&&n.text.trim()!==""),"Run finalized."}function wv(e,t){let n=new Set(e.steps.flatMap(a=>a.actions.flatMap(i=>i.action==="captureText"&&i.saveAs?[i.saveAs]:[]))),r=e.resolvedTexts.slice(0,Math.min(e.firstStep,Math.max(e.currentStepIndex,0))).join(`
|
|
349
|
+
`),s=t;try{s=Dt(t)}catch{}let o=po(s,a=>n.has(a)||r.includes(`"${a}"`)?"0":void 0);if("problem"in o)return`ERROR: kind=amount: ${o.problem}. Capture each value first with saffron_capture (its saveAs), then name it in double quotes, operators between spaces: '"before" + "breakfast"'.`}async function yv(e,t,n){if(e.downloadUnarmed)return"ERROR: the latest download began when no action of yours was running and none could be credited with it, so replay would not wait for it. Announce the step that downloads it, perform that action again, then record the check.";if(!e.lastDownload)return e.firstStep===0?'ERROR: nothing was downloaded in this session. Perform the action that downloads the file first (its result lists "Downloading file"), then record the check.':void 0;let r=await e.lastDownload;if(!r)return"ERROR: the file this session downloaded last did not finish downloading, so its content cannot be checked.";let s,o;try{let i=p=>p===void 0||p===""?void 0:Yt(p,e.uniqueSeed),c=Object.fromEntries(Object.entries(e.params).map(([p,u])=>[p,Yt(u,e.uniqueSeed)])),l={value:i(t),pattern:i(n)},d=Va(l,c,e.envNames,e.startedAt);if(d)return`ERROR: ${d} Not recorded.`;s=await qa(r);let f=Lo(l,c,e.envNames,e.startedAt);o=Ja(s,lv.basename(r),f.value,f.pattern,l.value)}catch(i){return`ERROR: ${i instanceof Error?i.message:String(i)}.`}if(!o)return;let a=2e3;return`ERROR: ${o}. Not recorded. Its text${s.length>a?` begins (${a} of ${s.length} characters)`:" is"}:
|
|
350
|
+
${s.slice(0,a)}
|
|
351
|
+
Record the check the step asks for as the file holds it. If the file does not hold what the step says, call saffron_done with success=false.`}var Gp={role:ne.string().optional().describe("ARIA role of the element"),name:ne.string().optional().describe("Full accessible name (exact match). For volatile content like prices or dates, use nameRegex instead."),nameRegex:ne.string().optional().describe("Regex for the accessible name when it embeds volatile content, e.g. 'Select \\\\{date\\\\+1\\\\} as checkin' cannot work \u2014 instead use nameRegex 'Select .* as checkin'"),label:ne.string().optional().describe("Form-label text for getByLabel \u2014 the literal <label> text only, never a free-text description"),text:ne.string().optional().describe("getByText locator text"),selector:ne.string().optional().describe("CSS fallback selector"),frame:ne.string().optional().describe(`CSS selector of the iframe hosting the element, e.g. 'iframe[title="Feedback widget"]' \u2014 REQUIRED whenever the element lives inside an iframe; without it replay looks only at the top-level page`)};function ui(e){return uv({name:"saffron",version:"0.1.0",tools:[Jr("saffron_step","Announce the Gherkin step you are about to perform. MUST be called before executing browser actions for each step, with the step's zero-based index and exact text.",{index:ne.number().int().min(0),text:ne.string(),adaptation:ne.string().optional().describe("If the written step does not match the real UI and you are deviating from it, describe the deviation in one sentence: the kind of change (a locator or label change on the same page, a page removed or merged, a page added or flow reordered) and the page it happened on.")},async t=>_e(pv(e,t))),Jr("saffron_capture",`Record a captureText action for the current step: at replay time, the target element's text is read and stored under saveAs for later expectDiffers comparisons. Use for steps like 'I record the displayed price as "X"'. The target must select exactly the element whose text is the value.`,{saveAs:ne.string().describe("Name to store the captured text under"),...Gp},async t=>{let n=Vp(t);if(!n)return _e("ERROR: capture needs a target (role/name, nameRegex, label, text, or selector).");let r=Jp(n);return r?_e(r):(e.addActions([{action:"captureText",target:n,saveAs:t.saveAs}]),_e(`Capture recorded as "${t.saveAs}".`))}),Jr("saffron_dialog","Record how a native dialog (alert/confirm/prompt) must be handled at replay. Call this IMMEDIATELY whenever an action triggers a native dialog \u2014 whether you handled it via browser_handle_dialog or the browser reported it as already handled. At replay Saffron arms this handler BEFORE the triggering action, so without this call the replay will auto-dismiss the dialog and diverge from what you saw.",{accept:ne.boolean().describe("true = accept/OK the dialog, false = dismiss/cancel"),promptText:ne.string().optional().describe("Text typed into a prompt() before accepting")},async t=>(e.addArmedAction({action:"handleDialog",value:t.accept?"accept":"dismiss",...t.promptText?{promptText:t.promptText}:{}}),_e(`Dialog handling recorded (${t.accept?"accept":"dismiss"}).`))),Jr("saffron_wait_api","Record a network wait for the current step: replay will block until a matching API response is observed (responses from the triggering step count). Call AFTER you verified via browser_network_requests that the response actually occurred with the expected status/body. Use a path-only urlPattern regex and never literal volatile IDs (/api/orders/\\d+, not /api/orders/8842).",{urlPattern:ne.string().describe("Regex matched against the response URL \u2014 path-only for portability"),method:ne.string().optional().describe("HTTP method to match (any if omitted)"),status:ne.string().optional().describe("Expected status \u2014 exact ('201') or class ('2xx'); default any 2xx"),bodyPattern:ne.string().optional().describe(`Regex the response body must match, e.g. '"status"\\s*:\\s*"READY"' for polling waits`)},async t=>(e.addActions([{action:"waitForResponse",urlPattern:t.urlPattern,...t.method?{method:t.method}:{},...t.status?{status:t.status}:{},...t.bodyPattern?{pattern:t.bodyPattern}:{}}]),_e("Network wait recorded."))),Jr("saffron_assert","Record a verified assertion for the current Then step. Call ONLY after you have confirmed the condition holds via a page snapshot. If the condition does NOT hold, do not call this: call saffron_done with success=false instead. NEVER record volatile content the step does not state (prices, counters, a date the step does not give) as literal expected text: use kind=matches with a pattern, kind=differs against captured values, or kind=amount. A value or date the step itself states, record exactly as the step shows it to you: Saffron turns a date back into the step's token, so it moves with the calendar.",{kind:ne.enum(["visible","notVisible","text","url","value","differs","matches","attribute","response","each","download","amount"]),...Gp,expected:ne.string().optional().describe(`Required for kind=text|value. Stable expected text/value; use an explicit empty string only for an empty check. kind=download: text the downloaded file must contain, e.g. 'DTSTART;VALUE=DATE:{date+7:YYYYMMDD}' (write a date as the step writes it). kind=amount: the amount the target must show, as arithmetic over values captured with saffron_capture (their saveAs in double quotes) and written amounts, operators between spaces, e.g. '"before" + "breakfast"', '"night" * 2', '"total" - "discount"'; compared to the cent, whatever the currency format`),url:ne.string().optional().describe("URL substring for kind=url (path only, no host)"),pattern:ne.string().optional().describe("kind=matches|attribute: regex the target's text (or attribute) must match, e.g. 'NOK [\\\\d,]+' for a price. Attribute patterns are case-sensitive. kind=download: regex the downloaded file's text must match (case-sensitive, ^ and $ at each line)"),attribute:ne.string().optional().describe("kind=attribute: attribute name to check, e.g. 'href' for link-target assertions \u2014 use this for 'X should link to Y' instead of clicking through"),capture:ne.string().optional().describe("kind=differs: name of the captured value on the LEFT of the comparison (omit when comparing the target element's live text)"),urlPattern:ne.string().optional().describe("kind=response: regex matched against the response URL. Check before the next browser interaction or navigation; only requests started since the latest action qualify. Use a path for portability, never literal volatile IDs (use /api/orders/\\d+)."),method:ne.string().optional().describe("kind=response: HTTP method to match (any if omitted)"),status:ne.string().optional().describe("kind=response: expected status \u2014 exact ('201') or class ('2xx'); default any 2xx"),bodyPattern:ne.string().optional().describe("kind=response: regex the response body must match (verify via browser_network_requests first)"),each:ne.string().optional().describe("kind=each: the data-list token exactly as the step writes it, e.g. '{data:enums.OrderStatus}'. The target is the CONTAINER (dropdown, table, list) that must show every value of that list. Never pass the values themselves."),compareTo:ne.string().optional().describe("kind=differs: name of the captured value to compare against")},async t=>{let n=Vp(t),r=Jp(n);if(r)return _e(r);if((t.kind==="text"||t.kind==="value")&&t.expected===void 0)return _e(`ERROR: kind=${t.kind} requires expected. Use an explicit empty string only to check that the element is empty.`);let s;switch(t.kind){case"visible":s={action:"expectVisible",target:n};break;case"notVisible":s={action:"expectNotVisible",target:n};break;case"text":s={action:"expectText",target:n,value:t.expected??""};break;case"value":s={action:"expectValue",target:n,value:t.expected??""};break;case"url":s={action:"expectUrl",url:t.url??""};break;case"differs":if(!t.compareTo)return _e("ERROR: kind=differs requires compareTo.");if(!t.capture&&!n)return _e("ERROR: kind=differs needs either capture (a stored name) or a target element.");s={action:"expectDiffers",target:n,value:t.capture,compareTo:t.compareTo};break;case"matches":if(!t.pattern)return _e("ERROR: kind=matches requires pattern.");s={action:"expectMatches",target:n,pattern:t.pattern};break;case"attribute":if(!t.attribute||!t.pattern)return _e("ERROR: kind=attribute requires attribute and pattern.");s={action:"expectAttribute",target:n,attribute:t.attribute,pattern:t.pattern};break;case"each":if(!t.each||!/^\{data:[^}]+\}$/.test(t.each))return _e("ERROR: kind=each requires each='{data:file.list}', the token exactly as the step writes it (not the values).");s={action:"expectEach",target:n,each:t.each};break;case"amount":{if(!t.expected)return _e(`ERROR: kind=amount requires expected: the amount as arithmetic over captured names in double quotes and written amounts, e.g. '"before" + "breakfast"'.`);let o=wv(e,t.expected);if(o)return _e(o);s={action:"expectAmount",target:n,value:t.expected};break}case"download":{if(!t.expected&&!t.pattern)return _e("ERROR: kind=download requires expected (text the file contains) or pattern (a regex its text matches).");s={action:"expectDownload",...t.expected?{value:t.expected}:{},...t.pattern?{pattern:t.pattern}:{}};let o=await yv(e,t.expected,t.pattern);if(o)return _e(o);break}case"response":if(!t.urlPattern)return _e("ERROR: kind=response requires urlPattern.");s={action:"expectResponse",urlPattern:t.urlPattern,...t.method?{method:t.method}:{},...t.status?{status:t.status}:{},...t.bodyPattern?{pattern:t.bodyPattern}:{}};break}return!["url","differs","response","download"].includes(t.kind)&&!n?_e("ERROR: assertion needs a target (role/name, nameRegex, label, text, or selector)."):(e.addActions([s]),_e("Assertion recorded."))}),Jr("saffron_done","Finalize the run. Call exactly once, after the final step: success=true only if every step's intent was achieved and every assertion verified.",{success:ne.boolean(),narrative:ne.string().describe("2-4 sentence summary of the run: what happened, and why it failed if it did. After a heal, say what kind of change the app went through (a locator change, or a page removed, merged, added or reordered) and on which page."),suggestedFeatureEdit:ne.string().optional().describe("If you adapted any steps: the corrected Gherkin for those steps, as you would rewrite them in the .feature file (free text, for the human report)."),featureEdits:ne.array(ne.object({index:ne.number().int().min(0).describe("zero-based step index"),text:ne.string().min(1).regex(/\S/,"a step text cannot be blank").describe("replacement step text WITHOUT the Given/When/Then keyword")})).optional().describe("Machine-applicable version of the suggested edits: one entry per adapted step. Provide this whenever you adapted a step.")},async t=>_e(mv(e,t)))]})}function pi(e={}){let t=e.deliberateSnapshots?`
|
|
333
352
|
8. Tool responses do NOT include a page snapshot. Take snapshots deliberately with browser_snapshot, and only when you actually need to see the page: after navigation, before locating an element you haven't seen yet, and when verifying an assertion. Do NOT snapshot after actions whose outcome is predictable (filling a field you just located, pressing Enter, a click whose result you will verify later anyway). Every snapshot is expensive.
|
|
334
353
|
9. Minimize round-trips: batch tool calls in a single response whenever they don't depend on each other's results \u2014 saffron_step together with that step's browser actions, several fills in one turn, bookkeeping calls (saffron_capture, saffron_assert) alongside the actions they belong to. Only stop and wait when you genuinely need a result before deciding your next call. Do not write narration between tool calls.`:"";return`You are Saffron's test execution agent. You execute Gherkin scenarios in a real browser using the playwright MCP tools, while Saffron records your actions into a deterministic replay cache.
|
|
335
354
|
|
|
336
355
|
Non-negotiable rules:
|
|
337
|
-
1. Before performing each step, call saffron_step with the step's index and exact text. Only then perform the browser actions for that step.
|
|
356
|
+
1. Before performing each step, call saffron_step with the step's index and exact text. Only then perform the browser actions for that step. saffron_step performs nothing: it only files the browser calls that follow under that step. A field is filled or a button clicked only by a browser tool call, so never report a step as done without one. Announce the steps in order, each right before its own actions: an action performed before its step is announced is filed under the previous step.
|
|
338
357
|
2. ${e.adaptableMidAssertions?"Steps marked [assertion:final] are sacred \u2014 they are the scenario's verdict. Verify them against a page snapshot; if the condition does not hold, the scenario FAILS: call saffron_done with success=false. Never manipulate the page to force them, never weaken or substitute them. Steps marked [assertion] (mid-scenario checkpoints) MAY be adapted under this project's policy when the written condition no longer matches a legitimately changed UI \u2014 record the equivalent verified condition via saffron_assert AND report the deviation via saffron_step's adaptation field plus featureEdits. An application defect is still a failure, not an adaptation.":'Steps marked [assertion] or [assertion:final] are sacred. Verify them against a page snapshot. If the condition holds, record it with saffron_assert. If it does not hold, the scenario FAILS: call saffron_done with success=false. Never click, navigate, or otherwise manipulate the page to force an assertion to become true, and never weaken or substitute the asserted condition for a "close enough" one.'}
|
|
339
|
-
3. A Given step (or a StepSet guard) that describes a state the page is ALREADY in needs no action and is NOT an adaptation: confirm it from the current snapshot and continue. Only report an adaptation when you had to do something different from what the step says.
|
|
358
|
+
3. A Given step (or a StepSet guard) that describes a state the page is ALREADY in needs no action and is NOT an adaptation: confirm it from the current snapshot and continue. Only report an adaptation when you had to do something different from what the step says. A step whose text carries an Examples value (a <param>, as "someone else" or "myself") is different: other rows give it other values, so perform the action that picks this row's value (click the option or radio labelled with it) even when the page already shows it. Left empty, every row would replay this row's page.
|
|
340
359
|
3a. Steps marked [action] may be adapted if the written step does not match the real UI (e.g. a step refers to a control that does not exist, or a required intermediate step is missing). Adapt minimally to achieve the step's evident intent, and report the deviation via saffron_step's "adaptation" field. Before adapting, take a snapshot and decide: is this UI drift (adapt) or an application defect (fail with saffron_done success=false and explain)?
|
|
341
360
|
4. Do not pursue goals beyond the scenario. Do not retry an assertion more than twice.
|
|
342
361
|
5. Prefer stable, semantic element references: role + accessible name. Avoid positional or generated-id selectors. Record the accessible name AS IT READS, in full: a shortened name is ambiguous ("Save" also matches "Save draft", and replay may then act on the wrong control). When an accessible name embeds volatile content (prices, dates, counters), use nameRegex with only the volatile part wildcarded. When you click, type into or otherwise act on an element, pass the ref from your latest browser_snapshot as its target, not a selector string: a ref records as role + name, which replays the way this rule asks. Write a selector only when no snapshot ref reaches the element.
|
|
343
|
-
5a. For "X should link to Y" assertions, use saffron_assert kind=attribute (attribute='href', pattern for the URL) on the link element \u2014 do NOT click through and assert the page URL; the recorded assertion must be verifiable without navigation. NEVER bake volatile values into the recording. For steps that store a displayed value ('I record the price as "X"'), use saffron_capture. For comparisons ('X should differ from Y'), verify yourself from snapshots, then record with saffron_assert kind=differs referencing the captured names. For 'something dynamic should be visible', use kind=matches with a pattern (e.g. 'NOK [\\d,]+') instead of literal text.
|
|
362
|
+
5a. For "X should link to Y" assertions, use saffron_assert kind=attribute (attribute='href', pattern for the URL) on the link element \u2014 do NOT click through and assert the page URL; the recorded assertion must be verifiable without navigation. NEVER bake volatile values into the recording. For steps that store a displayed value ('I record the price as "X"'), use saffron_capture. For comparisons ('X should differ from Y'), verify yourself from snapshots, then record with saffron_assert kind=differs referencing the captured names. For arithmetic ('the total should be "before" plus "breakfast"', 'the price should be twice "night"'), capture each input with saffron_capture where the step says (amount-only text), verify the sum yourself, then record saffron_assert kind=amount on the element showing the result, expected '"before" + "breakfast"' or '"night" * 2'. For 'something dynamic should be visible', use kind=matches with a pattern (e.g. 'NOK [\\d,]+') instead of literal text.
|
|
344
363
|
5a2. When a Then step quotes the expected text (or carries a <param> that resolves to it), pass EXACTLY that quoted text as the expected argument of saffron_assert. Replay checks containment, so the step's own wording is enough; never substitute the page's longer sentence, and never a value from a different Examples row.
|
|
345
364
|
5b. Literal ISO dates (YYYY-MM-DD) in recorded locators are auto-templated to {date\xB1N} relative to today, so date-picker recordings stay valid tomorrow. For non-ISO date formats in names, use nameRegex.
|
|
346
365
|
6. When all steps are done, call saffron_done exactly once. If you adapted steps, include BOTH suggestedFeatureEdit (human-readable corrected Gherkin) AND featureEdits (one {index, text} entry per adapted step, text without the keyword) so the correction can be applied automatically.
|
|
347
366
|
5a3. DATA LISTS: when a step shows a token followed by '(a data list, currently: \u2026)', e.g. "should list every {data:enums.OrderStatus} (a data list, currently: "New", "Paid")", verify from a snapshot that EVERY listed value is shown inside one container (the dropdown, table, list or menu the step is about), then record ONE assertion: saffron_assert kind=each, each='{data:enums.OrderStatus}' (the token exactly as written, never the values), targeting that container. Do NOT record one assertion per value: replay reads the list from the data file, so values added to it later are checked without recording again. If any listed value is missing, the step FAILS.
|
|
348
367
|
5c. Real-world page furniture is supported: elements inside IFRAMES record and replay fine (interact normally) \u2014 but when a saffron_assert targets an element INSIDE an iframe, you MUST pass the iframe's CSS selector as the 'frame' argument (e.g. frame='iframe[title="Feedback widget"]'); replay cannot see into frames otherwise. File uploads: use browser_file_upload with the file path. Drag-and-drop: use browser_drag. All of these are recorded and replay deterministically.
|
|
349
368
|
5d. NATIVE DIALOGS (alert/confirm/prompt): when an action opens one, the page blocks and the snapshot reports a modal state \u2014 resolve it with browser_handle_dialog (accept true/false; promptText for prompt()). That call is recorded automatically as an armed handler replay places BEFORE the triggering action, so do NOT also call saffron_dialog. After handling, verify the post-dialog state as usual. If a step's wording says to confirm/accept, accept; if it says cancel/dismiss, dismiss.
|
|
350
|
-
5e. NETWORK WAITS: when a step says to wait for an API call ("wait for the order API to succeed", "until the job API reports READY"), do it verify-first: perform the trigger, check via browser_network_requests that the matching response actually occurred with the expected status/body, then record it with saffron_wait_api. For Then steps about API contracts ("the request should have returned 201") verify the same way and record with saffron_assert kind=response. urlPattern is a path-only regex \u2014 NEVER a literal volatile ID (/api/orders/\\d+, not /api/orders/8842) and never the host. browser_network_request returns a whole response body, which Saffron cuts at ${
|
|
369
|
+
5e. NETWORK WAITS: when a step says to wait for an API call ("wait for the order API to succeed", "until the job API reports READY"), do it verify-first: perform the trigger, check via browser_network_requests that the matching response actually occurred with the expected status/body, then record it with saffron_wait_api. For Then steps about API contracts ("the request should have returned 201") verify the same way and record with saffron_assert kind=response. urlPattern is a path-only regex \u2014 NEVER a literal volatile ID (/api/orders/\\d+, not /api/orders/8842) and never the host. browser_network_request returns a whole response body, which Saffron cuts at ${ka.toLocaleString("en-US")} characters: fetch a body only when the step is about its content, and prefer a saffron_assert kind=response on the field you need.
|
|
351
370
|
5f. TABS: a click that opens a new tab needs nothing extra, replay follows the new tab by itself. When a step says to switch to another tab, go back to the first tab, or close a tab, do it with browser_tabs (list first if unsure of the index); select, close and new are recorded and replay in the same order. Steps that assert on the other tab's content are ordinary assertions after the switch.
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
371
|
+
5g. SCOPE: when a step names the section, dialog, card or form it acts in ('in "Your contact information"', 'inside the "Compact Double" room card'), scope the target to that container even when only one match is visible now, e.g. selector 'role=region[name="Your contact information"] >> role=textbox[name="E-mail (required)"]'. A snapshot ref records the element alone, unscoped: for these steps pass the scoped selector instead of the ref. Another Examples row or page state can show a second form with the same labels. An option of a dropdown that renders outside the container may be targeted on its own once the scoped trigger opened it, and a button of a dialog it opened is scoped to that dialog instead ('role=dialog >> role=button[name="Yes, cancel"]').
|
|
372
|
+
5h. READINESS: a step that waits for the page ("I wait until the prices have loaded", "until the dialog's fields are filled") must record what it waits for: saffron_assert kind=visible, notVisible, matches or value on the element that shows the page is ready (a price, a loaded field, a spinner gone). Replay waits for that condition; a step with no recorded action waits for nothing.
|
|
373
|
+
5i. STALE REFS: when a ref no longer resolves (the page re-rendered since the snapshot), take a fresh browser_snapshot and use its ref. Never reuse or guess an old ref.
|
|
374
|
+
5j. DOWNLOADS: a click that downloads a file needs nothing extra: its result lists "Downloading file ..." and Saffron records the download with that click, so replay waits for it and keeps the file. For a step about what the file says (an .ics calendar entry, a .csv export, a text receipt), record saffron_assert kind=download, no target, with expected (text the file must contain) and/or pattern (a regex its text matches). You cannot open the file yourself: Saffron checks it when you record and, when the check does not hold, replies with the start of the file. Write a date exactly as the step shows it to you (the day it names, e.g. DTSTART;VALUE=DATE:20261024): Saffron turns that day back into the step's date token, so the check moves with the calendar. Never a pattern that would accept any date. A link's href or download file name is still kind=attribute.
|
|
375
|
+
7. Never ask the user questions; you are unattended.${t}`}function bv(e,t){if(e[t].kind!=="assertion")return"action";let n=e.length;for(let r=e.length-1;r>=0&&e[r].kind==="assertion";r--)n=r;return t>=n?"assertion:final":"assertion"}var vv=`When you heal, tell the reviewer WHAT KIND of change you adapted to, in saffron_step's adaptation and again in saffron_done's narrative, and name the page (its URL path) where it happened. Pick the kind that fits: (1) locator or label change: the same control on the same page, found differently (renamed button, new test id, native select instead of a custom one); (2) page removed or merged: a page no longer exists and its fields or controls now live on another page, so a navigation step (e.g. a 'Continue' click) is no longer needed; (3) page added or flow reordered: a new intermediate page, dialog or step order; (4) timing only: nothing changed, the element was slow. When you skip or add a click, key press or navigation the step used to perform, say so explicitly, e.g. "The guest information page is gone: its fields are now on /checkout, so the 'Continue to payment' click was dropped." Never describe a flow change as a locator change.`,xv=`BROWSER SESSIONS: this scenario runs in several browser sessions, one per person, each a separate browser with its own cookies, login and tabs. [session: ...] on each step names its session ("default" for the steps before the first As "..."). Your browser tools act in the session of the step you announced last with saffron_step, so always announce a step before acting for it, and when the next step is in another session, call saffron_step for it on its own and wait for its reply before any browser call; browser_tabs lists that session's tabs only. A session keeps its page while you work in another one: when you come back to it, take a snapshot before acting. Never sign one session in as another session's person.`;function fi(e){let t=e.liveTab;if(t)return t.count<=1?`Live page: the only open tab, at ${t.url}. Work on it; do not open or select another tab to start over.`:`Live page: tab ${t.index} of ${t.count} open tabs, at ${t.url}. This is where replay left off. If browser_tabs shows another tab as current, select tab ${t.index} before anything else (Saffron does not record that selection); never start over on another tab.`}function Kp(e){let t=e.failedStep?.stepIndex;return`ANNOUNCE FIRST: call saffron_step for ${t===void 0?"the failed step":`the failed step (index ${t})`} BEFORE any state-changing browser action (click, type, select, key press, navigation, tab change). To diagnose, look with browser_snapshot, never with clicks or navigation: Saffron discards every action made before that announcement, and going back through earlier steps changes the state replay reached.`}function gi(e,t=new Date){let{scenario:n}=e,r=tt(n),s=An(n.steps),o=n.steps.map((i,c)=>{let l=b=>oo(Ve(jl(Yt(b,e.uniqueSeed??"")),t),r),d=s?` [session: ${dt(pe(i.session))}]`:"",f=`${c}. [${bv(n.steps,c)}]${d} ${i.keyword} ${l(i.resolvedText)}`,p=i.resolvedTable??i.table,u=i.resolvedDocString??i.docString,h=f;return p&&(h+=`
|
|
376
|
+
${p.map(b=>` | ${b.map(l).join(" | ")} |`).join(`
|
|
377
|
+
`)}`),u!==void 0&&(h+=`
|
|
355
378
|
"""
|
|
356
|
-
${
|
|
357
|
-
`).map(
|
|
379
|
+
${l(u).split(`
|
|
380
|
+
`).map(b=>` ${b}`).join(`
|
|
358
381
|
`)}
|
|
359
|
-
"""`),
|
|
360
|
-
`),
|
|
361
|
-
`:void 0];if(e.mode==="refine")
|
|
382
|
+
"""`),h}).join(`
|
|
383
|
+
`),a=[`Feature: ${n.featureName} (${n.featurePath})`,`Scenario: ${n.displayName}`,e.baseURL?`Base URL: ${e.baseURL}`:void 0,"",s?"Steps (index. [kind] [session] keyword text):":"Steps (index. [kind] keyword text):",o,"",s?`${xv}
|
|
384
|
+
`:void 0];if(e.mode==="refine")a.push("MODE: REFINE. You (or a previous agent session) just recorded this scenario and it completed successfully \u2014 but the deterministic zero-AI replay of that recording FAILED at the step below. The application is working; the RECORDING is not replayable.","The browser tab shows the state where the proof replay stopped.",fi(e),"",`Steps that replayed fine:
|
|
362
385
|
${(e.completedSteps??[]).map(i=>` \u2713 ${i}`).join(`
|
|
363
|
-
`)||" (none)"}`,"",`Failed step: [${e.failedStep?.kind}] ${e.failedStep?.text}`,`Replay failure: ${e.failedStep?.error}`,"","Typical causes: a locator that only matched during your session (volatile accessible name \u2014 use nameRegex or a shorter stable name), a literal dynamic value baked into an assertion (use kind=matches/differs/captureText), or an assertion that cannot be checked without navigation (use kind=attribute for link targets).","Re-perform and re-record the failed step and every step after it in a REPLAYABLE form via saffron_step + browser tools / saffron_capture / saffron_assert. Express the SAME conditions the steps state \u2014 do not weaken them.","If a step genuinely cannot be expressed replayably, call saffron_done success=false and explain why.",
|
|
386
|
+
`)||" (none)"}`,"",`Failed step: [${e.failedStep?.kind}] ${e.failedStep?.text}`,`Replay failure: ${e.failedStep?.error}`,"","Typical causes: a locator that only matched during your session (volatile accessible name \u2014 use nameRegex or a shorter stable name), a literal dynamic value baked into an assertion (use kind=matches/differs/captureText), or an assertion that cannot be checked without navigation (use kind=attribute for link targets).","Re-perform and re-record the failed step and every step after it in a REPLAYABLE form via saffron_step + browser tools / saffron_capture / saffron_assert. Express the SAME conditions the steps state \u2014 do not weaken them.","If a step genuinely cannot be expressed replayably, call saffron_done success=false and explain why.",Kp(e));else if(e.mode==="heal")a.push("MODE: HEAL. A cached deterministic replay of this scenario failed mid-run.","The browser tab already holds the page state reached so far \u2014 do NOT restart from step 0; verify where you are with a snapshot and continue from the failed step.",fi(e),"",`Steps already completed by replay:
|
|
364
387
|
${(e.completedSteps??[]).map(i=>` \u2713 ${i}`).join(`
|
|
365
|
-
`)||" (none)"}`,"",`Failed step: [${e.failedStep?.kind}] ${e.failedStep?.text}`,`Failure: ${e.failedStep?.error}`,e.failedStep?.pageUrl?`Page when replay failed: ${e.failedStep.pageUrl}`:void 0,"","First diagnose: did the UI legitimately change (heal: adapt the actions, record via saffron_step + browser tools), or is the application broken (fail: saffron_done success=false with your diagnosis)?",
|
|
366
|
-
${e.completedSteps.map(
|
|
367
|
-
`)}`:"You are starting from a blank page."
|
|
368
|
-
`),"",`The browser currently shows the state after those ${i} step(s) (verify with a snapshot if unsure). Do NOT redo them and do NOT navigate away from the current state
|
|
369
|
-
`)}import{query as
|
|
370
|
-
`);if(!V.includes(cu))throw new Error(V.replace(/^### Error\s*/,"").trim()||"the browser backend did not start");let Z=P.pages().filter(ve=>!ve.isClosed()),oe=E?Z.indexOf(E):-1;if(oe>0&&(await N.callTool({name:"browser_tabs",arguments:{action:"list"}}),(await N.callTool({name:"browser_tabs",arguments:{action:"select",index:oe}})).isError))throw new Hn(`could not start on the session's tab ${oe}`)}catch(G){throw await Promise.allSettled([N.close(),z?.close()]),F(!1),G}let L=z;return{context:P,client:N,close:async()=>{await Promise.allSettled([N.close()]),await Promise.allSettled([L.close()])},release:F}},p=0,m=P=>{p++;let E=!1,T=()=>{E||(E=!0,clearTimeout(I),P.off("close",M),--p===0&&d())},M=()=>{setTimeout(T,1e3).unref()},I=setTimeout(T,3e5);return I.unref(),P.on("close",M),T},h=new Map,w=new Set,b=!1,y=!1,S=P=>{let E=h.get(P);if(!E){if(b)return Promise.reject(new Hn("the agent session is over"));E=o?o.pageOf(P).then(T=>f(T.context(),T),T=>{throw new Hn(`browser session "${Ge(P)}" could not open: ${T instanceof Error?T.message:String(T)}`)}):f(e),h.set(P,E),E.then(T=>{y?T.close().finally(()=>T.release(!1)):w.add(T)},()=>{}),E.catch(()=>{h.get(P)===E&&h.delete(P)})}return E},x=()=>o?.keyOf()??"",C;try{C=await S(x())}catch(P){throw d(),P}let $=Promise.resolve(),k,R=(P,E)=>{let T=$.then(async()=>{let M=x(),I=await S(M);k=M;try{return await ja(I.context,t(),P,E)}finally{k=void 0}});return $=T.then(()=>{},()=>{}),T},v=Ei({listTools:(...P)=>C.client.listTools(...P),callTool:async(...P)=>(await S(k??x())).client.callTool(...P)},(P,E,T)=>R(ly(P,E),T),s.projectRoot),A=async()=>{let P=[...u];if(P.length===0)return;let E=Promise.all(P.map(M=>M.path().then(()=>!0,()=>!0))),T=!await Promise.race([E,as(oy).then(()=>!1)]);T&&Ia++;try{T&&(await Promise.allSettled(P.map(M=>M.cancel())),await Promise.allSettled(P.map(M=>M.failure()))),await as(0),await as(0)}finally{T&&Ia--}};return{config:{type:"sdk",name:"playwright",instance:v},close:async()=>{b=!0,await Promise.race([$,as(au)]),await A().catch(()=>{});let P=Promise.allSettled([...h.values()]);await Promise.race([P.then(iy),as(au).then(ay)]);let E=[...w];y=!0;for(let T of E)await T.close();await Promise.allSettled([v.close()]);for(let T of E)T.release(!0)},grouped:(P,E)=>R(P,E)}}var fy=dy(import.meta.url),pu="This scenario runs in several browser sessions, and the agent needs Playwright's in-process browser tools to act in each of them; they could not start";function uy(){let e=fy.resolve("@playwright/mcp/package.json");return uu.join(uu.dirname(e),"cli.js")}var py=new Set(["mcp__playwright__browser_navigate","mcp__playwright__browser_click","mcp__playwright__browser_type","mcp__playwright__browser_fill_form","mcp__playwright__browser_select_option","mcp__playwright__browser_press_key"]),gy=new Set(["mcp__playwright__browser_snapshot","mcp__playwright__browser_find","mcp__playwright__browser_wait_for","mcp__playwright__browser_take_screenshot","mcp__playwright__browser_console_messages","mcp__playwright__browser_network_requests","mcp__playwright__browser_network_request","mcp__saffron__saffron_step","mcp__saffron__saffron_capture","mcp__saffron__saffron_dialog","mcp__saffron__saffron_wait_api","mcp__saffron__saffron_assert","mcp__saffron__saffron_done"]);function Na(e,t){if(gy.has(e))return!1;if(e==="mcp__playwright__browser_tabs"){let n=t?.action;return!(n==="list"||n==="select"||n==="close")}return!0}var br=class e{constructor(t,n){this.ctx=t;this.snapshotMode=n;this.state=new ho(t.scenario,{firstStep:Sa(t),discardBeforeAnnounce:jf(t)})}ctx;snapshotMode;state;usage={aiCalls:0,inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheCreationTokens:0};resultText="";traced;capped;outputDir=Ol();get projectRoot(){return this.ctx.projectRoot??process.cwd()}stopTabWatch;startedAt=new Date;static async open(t,n,r){let s=new e(t,n);try{return await e.attach(s,t,n,r)}catch(o){throw fu.rmSync(s.outputDir,{recursive:!0,force:!0}),o}}static async attach(t,n,r,s){let o=gn(n.scenario.steps)?n.sessionPage:void 0;if(o&&s.traceBridgeUnavailable)throw new Error(pu);if((n.traceContext||o)&&!s.traceBridgeUnavailable){let i=ot(n.scenario),a=n.traceContext??(await o(t.sessionKey())).context();try{let c=o&&{keyOf:()=>t.sessionKey(),pageOf:o};t.traced=await du(a,()=>t.currentStep(),r,l=>{let d=l instanceof Error?l.message:String(l);console.warn(`A promise rejected during the agent session and nothing handled it: ${it(d,i)}`)},{outputDir:t.outputDir,projectRoot:t.projectRoot},c)}catch(c){if(c instanceof Hn)throw c;let l=it(c instanceof Error?c.message:String(c),i);if(o)throw new Error(`${pu} (${l})`);s.traceBridgeUnavailable=!0,console.warn(`Agent tracing could not start (${l}). Continuing through the standard browser connection; agent calls will be absent from these traces.`)}}return t}sessionKey(){let t=this.state.currentStepIndex>=0?this.state.currentStepIndex:Sa(this.ctx);return de(this.ctx.scenario.steps[t]?.session)}currentStep(){let t=this.state.currentStepIndex,n=this.ctx.scenario.steps[t];return{index:t,title:n?`${n.keyword} ${n.text}`:"Agent exploration"}}async playwrightServer(){return this.traced?this.traced.config:(this.capped??=await jl(this.playwrightStdio(),this.projectRoot),this.capped.config)}playwrightStdio(){return{command:process.execPath,args:[uy(),"--cdp-endpoint",this.ctx.cdpEndpoint,"--snapshot-mode",this.snapshotMode,"--image-responses","omit","--output-dir",this.outputDir]}}noteThePage(t){let n="note the page for the recording";return this.traced?this.traced.grouped(n,t):this.ctx.traceContext?ja(this.ctx.traceContext,this.currentStep(),n,t):t()}async beforeTool(t,n){if(this.state.beginToolCall(t),py.has(n)&&this.ctx.takeFingerprint&&!this.state.pendingFingerprint)try{let r=this.ctx.takeFingerprint;this.state.pendingFingerprint=await this.noteThePage(()=>r(this.sessionKey()))}catch{}}afterTool(t,n,r,s){let o=Vf(n,r);o&&this.state.addArmedAction(o);let i=qf(n,r,this.ctx.baseURL);if(i&&this.state.addActions([i]),n.startsWith("mcp__playwright__")){let a=Mf(s);a!==void 0&&this.ctx.onActiveTab?.(a,this.sessionKey()),this.state.addActions(Ff(s,this.ctx.baseURL)),this.state.pendingFingerprint=void 0}this.state.endToolCall(t,Na(n,r))}failedTool(t,n,r){n.startsWith("mcp__playwright__")&&(this.state.pendingFingerprint=void 0),this.state.endToolCall(t,Na(n,r))}watchTabs(){this.stopTabWatch=this.ctx.onTabOpened?.(t=>this.state.markTabOpened(t))}sessionError(t){if(this.state.done)return;let n=t instanceof Error?t.message:String(t);this.state.done=!0,this.state.success=!1,this.state.narrative=`Agent session error: ${n}`}async close(){this.stopTabWatch?.(),this.stopTabWatch=void 0,await this.traced?.close(),await this.capped?.close(),fu.rmSync(this.outputDir,{recursive:!0,force:!0})}result(){let{ctx:t,state:n}=this;return n.done||(n.success=!1,n.narrative=n.narrative||`Agent session ended without finalizing the run. Last output: ${this.resultText.slice(0,500)}`),{success:n.success,narrative:n.narrative,adaptations:[...n.adaptations,...n.attributionNotes()],suggestedFeatureEdit:n.suggestedFeatureEdit,featureEdits:n.featureEdits.map(r=>{let s=gr(r.text,t.scenario.params),o=t.scenario.steps[r.index];return{index:r.index,text:o?Cc(o.text,s):s}}),recordedSteps:zf(n.steps,t.scenario,t.uniqueSeed,this.startedAt),announcedSteps:[...n.announced].sort((r,s)=>r-s),usage:this.usage}}};var Eo=class{constructor(t={}){this.opts=t}opts;planBefore;traceBridgeUnavailable=!1;async planUsage(){if(!this.planBefore)return;let t=await this.planBefore;if(!t)return;let n=await ou();return{subscriptionType:t.subscriptionType,fiveHourBefore:t.utilization,fiveHourAfter:n?.utilization,resetsAt:n?.resetsAt??t.resetsAt}}async run(t){let n=await br.open(t,this.opts.snapshotMode??"none",this),r;try{r=hy({prompt:Ro(t),options:{systemPrompt:ko({deliberateSnapshots:n.snapshotMode==="none",adaptableMidAssertions:t.assertionPolicy==="adaptable-mid"}),model:t.model??this.opts.model,maxTurns:this.opts.maxTurns??100,tools:[],permissionMode:"bypassPermissions",allowDangerouslySkipPermissions:!0,persistSession:!1,settingSources:[],strictMcpConfig:!0,settings:{disableClaudeAiConnectors:!0},mcpServers:{playwright:await n.playwrightServer(),saffron:So(n.state)},hooks:{PreToolUse:[{hooks:[async s=>{let o=s;return await n.beforeTool(o.tool_use_id,o.tool_name),{continue:!0}}]}],PostToolUse:[{hooks:[async s=>{let o=s;return n.afterTool(o.tool_use_id,o.tool_name,o.tool_input,o.tool_response),{continue:!0}}]}],PostToolUseFailure:[{hooks:[async s=>{let o=s;return n.failedTool(o.tool_use_id,o.tool_name,o.tool_input),{continue:!0}}]}]}}})}catch(s){throw await n.close(),s}this.planBefore||(this.planBefore=Oa(r)),n.watchTabs();try{for await(let s of r)s.type==="result"&&(n.usage.aiCalls=s.num_turns,n.usage.costUsd=s.total_cost_usd,"modelUsage"in s&&s.modelUsage&&(n.usage.models=Object.keys(s.modelUsage)),"usage"in s&&s.usage&&(n.usage.inputTokens=s.usage.input_tokens??0,n.usage.outputTokens=s.usage.output_tokens??0,n.usage.cacheReadTokens=s.usage.cache_read_input_tokens??0,n.usage.cacheCreationTokens=s.usage.cache_creation_input_tokens??0),s.subtype==="success"&&(n.resultText=s.result))}catch(s){n.sessionError(s)}finally{await n.close()}return n.result()}};import my from"node:http";import{randomBytes as wy,randomUUID as yy,timingSafeEqual as by}from"node:crypto";import{Client as vy}from"@modelcontextprotocol/sdk/client/index.js";import{InMemoryTransport as xy}from"@modelcontextprotocol/sdk/inMemory.js";import{Server as Sy}from"@modelcontextprotocol/sdk/server/index.js";import{StreamableHTTPServerTransport as $y}from"@modelcontextprotocol/sdk/server/streamableHttp.js";import{CallToolRequestSchema as ky,ListToolsRequestSchema as Ry}from"@modelcontextprotocol/sdk/types.js";async function Ty(e,t){let n=wy(16).toString("hex"),r=Buffer.from(`Bearer ${n}`),s=u=>{let g=Buffer.from(u??"");return g.length===r.length&&by(g,r)},o=Promise.resolve(),i=!1,a=u=>{let g=o.then(u);return o=g.catch(()=>{}),g},c=(u,g)=>{let f=new Sy({name:u,version:"1"},{capabilities:{tools:{}}});return f.setRequestHandler(Ry,p=>g.listTools(p.params)),f.setRequestHandler(ky,(p,m)=>a(async()=>{if(i||m.signal.aborted)throw new Error(i?"the agent session is over":"the call was cancelled before its turn came");let h=yy(),w=`mcp__${u}__${p.params.name}`,b=p.params.arguments??{};await t.beforeTool(h,w);try{let y=await g.callTool(p.params,void 0,{timeout:Ri});return y.isError?t.failedTool(h,w,b):t.afterTool(h,w,b,y),y}catch(y){throw t.failedTool(h,w,b),y}})),f},l=my.createServer(async(u,g)=>{let f=(u.url??"").split("?")[0].slice(1),p=s(u.headers.authorization)?e[f]:void 0;if(!p)return void g.writeHead(404).end();if(u.method!=="POST")return void g.writeHead(405,{Allow:"POST"}).end();let m=c(f,p),h=new $y({sessionIdGenerator:void 0,enableJsonResponse:!0});g.on("close",()=>{Promise.allSettled([h.close(),m.close()])});try{await m.connect(h),await h.handleRequest(u,g)}catch{g.headersSent||g.writeHead(500).end()}});l.requestTimeout=0,await new Promise((u,g)=>{l.once("error",g),l.listen(0,"127.0.0.1",()=>u())});let{port:d}=l.address();return{urls:Object.fromEntries(Object.keys(e).map(u=>[u,`http://127.0.0.1:${d}/${u}`])),token:n,close:async()=>{i=!0,l.closeAllConnections(),await new Promise(u=>l.close(()=>u()))}}}async function gu(e){let[t,n]=xy.createLinkedPair();await e.connect(n);let r=new vy({name:"saffron-gateway",version:"1"});return await r.connect(t),r}async function hu(e){let t=[];try{let n=await gu((await e.playwrightServer()).instance);t.push(n);let r=await gu(So(e.state).instance);t.push(r);let s=await Ty({playwright:n,saffron:r},e);return{urls:s.urls,token:s.token,close:async()=>{await s.close(),await Promise.allSettled(t.map(o=>o.close()))}}}catch(n){throw await Promise.allSettled(t.map(r=>r.close())),n}}var Ao=class{constructor(t,n={},r=()=>{}){this.drive=t;this.opts=n;this.blocker=r}drive;opts;blocker;traceBridgeUnavailable=!1;async run(t){let n=this.blocker();if(n)throw new Error(n);let r=await br.open(t,this.opts.snapshotMode??"none",this),s;try{s=await hu(r)}catch(o){throw await r.close(),o}r.watchTabs();try{await this.drive({systemPrompt:ko({deliberateSnapshots:r.snapshotMode==="none",adaptableMidAssertions:t.assertionPolicy==="adaptable-mid"}),prompt:Ro(t),model:t.model??this.opts.model,maxTurns:this.opts.maxTurns??100,mcpServers:s.urls,mcpToken:s.token,usage:r.usage,lastOutput:o=>{r.resultText=o},finished:()=>r.state.done})}catch(o){r.sessionError(o)}finally{await s.close(),await r.close()}return r.result()}};async function ls(e,t){try{return await import(e)}catch(n){let r=n.code;throw(r==="ERR_MODULE_NOT_FOUND"||r==="MODULE_NOT_FOUND")&&String(n.message).includes(`'${e}'`)?new Error(`the ${t} provider needs ${e}: npm install --save-dev ${e}`):n}}function vr(e){return`stopped after ${e} tool calls, the session's turn limit: raise maxTurns in saffron.config.json, or look at what the agent kept retrying`}import xr from"node:fs";import Ma from"node:os";import Ht from"node:path";import{createHash as Ey}from"node:crypto";import{createRequire as mu}from"node:module";function Ay(){try{let e=mu(import.meta.resolve("@openai/codex-sdk")).resolve("@openai/codex/package.json"),t=mu(e).resolve(`@openai/codex-${process.platform}-${process.arch}/package.json`),n=Ht.join(Ht.dirname(t),"vendor");for(let r of xr.readdirSync(n))for(let s of[Ht.join(n,r,"bin","codex"),Ht.join(n,r,"codex","codex")])if(xr.existsSync(s))return s}catch{}}function Co(e=process.platform){return e==="win32"?"the codex provider is not available on Windows yet: Saffron must run Codex without your ~/.codex/config.toml (your own MCP servers, plugins and hooks), and cannot on Windows":void 0}function Cy(e){return`'${e.replaceAll("'","'\\''")}'`}function _y(){let e=Co();if(e)throw new Error(e);let t=Ay();if(!t)throw new Error("the Codex binary is missing from @openai/codex-sdk's install: reinstall it with npm install --save-dev @openai/codex-sdk");let n=Ht.join(process.env.XDG_CACHE_HOME||Ht.join(Ma.homedir(),".cache"),"saffron");xr.mkdirSync(n,{recursive:!0});let r=Ht.join(n,`codex-${Ey("sha256").update(t).digest("hex").slice(0,12)}`);return Ne(r,`#!/bin/sh
|
|
388
|
+
`)||" (none)"}`,"",`Failed step: [${e.failedStep?.kind}] ${e.failedStep?.text}`,`Failure: ${e.failedStep?.error}`,e.failedStep?.pageUrl?`Page when replay failed: ${e.failedStep.pageUrl}`:void 0,"","First diagnose: did the UI legitimately change (heal: adapt the actions, record via saffron_step + browser tools), or is the application broken (fail: saffron_done success=false with your diagnosis)?",vv,e.assertionPolicy==="adaptable-mid"?"If the failed step is an [assertion:final]: you may re-verify the SAME condition once against the live page (timing), but if it does not hold AS WRITTEN, the run FAILS \u2014 call saffron_done success=false; never substitute it. If the failed step is a mid-scenario [assertion]: this project's policy allows adapting it \u2014 verify the equivalent condition on the legitimately-changed UI, record it via saffron_assert, and report the deviation via saffron_step's adaptation field plus featureEdits. An application defect still fails.":"If the failed step is an [assertion] or [assertion:final]: you may re-verify the SAME condition once against the live page (it may have been a timing issue). If the condition AS WRITTEN does not hold, the run FAILS \u2014 call saffron_done success=false. Do NOT substitute a different element, text, or URL that 'means the same thing'; suggesting a corrected assertion belongs in suggestedFeatureEdit of your failure report, never in saffron_assert.","Announce (saffron_step) and perform only the failed step and the steps after it. Earlier steps keep their recordings.",Kp(e));else if(e.mode==="record"&&e.recordOnly){let{from:i,to:c}=e.recordOnly;a.push("MODE: RECORD (segment). This scenario is being composed from existing recordings plus your work.",e.completedSteps&&e.completedSteps.length>0?`Already executed against the live browser (do NOT redo):
|
|
389
|
+
${e.completedSteps.map(l=>` \u2713 ${l}`).join(`
|
|
390
|
+
`)}`:"You are starting from a blank page.",fi(e),"",`Record ONLY steps ${i} through ${c} (inclusive).`,`CRITICAL STOP RULE: the steps AFTER step ${c} already have recordings and will be replayed automatically the moment you stop. After completing step ${c}, immediately call saffron_done \u2014 do NOT perform, verify, or navigate into any later step. Executing a later step yourself would make the automatic replay run it TWICE.`)}else if(e.completedSteps&&e.completedSteps.length>0){let i=e.completedSteps.length;a.push("MODE: RECORD (seeded). No cache exists for this scenario yet, but its first steps matched existing recordings and were ALREADY EXECUTED against the live browser by zero-AI replay:",e.completedSteps.map(c=>` \u2713 ${c}`).join(`
|
|
391
|
+
`),"",`The browser currently shows the state after those ${i} step(s) (verify with a snapshot if unsure). Do NOT redo them and do NOT navigate away from the current state.`,fi(e),`Start with saffron_step for step index ${i} and record from there to the end.`)}else a.push("MODE: RECORD. No cache exists for this scenario yet.","Execute every step in order, starting at step 0. Navigate to the base URL first if the scenario implies a starting page.");return a.filter(i=>i!==void 0).join(`
|
|
392
|
+
`)}import{query as Sv}from"@anthropic-ai/claude-agent-sdk";var $v="usage_EXPERIMENTAL_MAY_CHANGE_DO_NOT_RELY_ON_THIS_API_YET";async function qc(e,t=8e3){let n=e?.[$v];if(typeof n!="function")return;let r;try{let s=await Promise.race([n.call(e,{skipBehaviors:!0}),new Promise(o=>{r=setTimeout(()=>o(void 0),t),r.unref?.()})]);return kv(s)}catch{return}finally{r&&clearTimeout(r)}}function kv(e){if(!e||!e.rate_limits_available||!e.subscription_type)return;let t=e.rate_limits?.five_hour;return{subscriptionType:e.subscription_type,utilization:typeof t?.utilization=="number"?t.utilization:void 0,resetsAt:t?.resets_at??void 0}}async function Yp(){let e=()=>{},t=new Promise(s=>e=s);async function*n(){await t}let r;try{let s=Sv({prompt:n(),options:{maxTurns:1,tools:[],settingSources:[],persistSession:!1}});r=s;let o=(async()=>{try{for await(let i of s);}catch{}})(),a=await qc(s);return e(),r.close?.(),await o,a}catch{e(),r?.close?.();return}}import ng from"node:fs";import Wc from"node:path";import{createRequire as Iv}from"node:module";import{createRequire as Zp}from"node:module";var Rv=Zp(import.meta.url),hi=Zp(Rv.resolve("playwright/package.json"));import{Client as Tv}from"@modelcontextprotocol/sdk/client/index.js";import{InMemoryTransport as Av}from"@modelcontextprotocol/sdk/inMemory.js";var Qp=1e4,Ev=5e3,Xp="saffron_connection_check",_v=()=>!0,Ov=()=>!1,Ds=e=>new Promise(t=>{setTimeout(t,e).unref()}),Fs=new Set,Vc=0,eg=e=>{Vc===0&&[...Fs].at(-1)?.(e)};function Cv(e){let t=n=>e(n);return Fs.size===0&&process.on("unhandledRejection",eg),Fs.add(t),()=>{Fs.delete(t)&&Fs.size===0&&process.off("unhandledRejection",eg)}}async function Jc(e,t,n,r){await e.tracing.group(`[saffron:agent:${t.index}] ${t.title}`).catch(()=>{});try{await e.tracing.group(n).catch(()=>{});try{return await r()}finally{await e.tracing.groupEnd().catch(()=>{})}}finally{await e.tracing.groupEnd().catch(()=>{})}}function Pv(e,t={}){let n=o=>typeof o=="string"&&o.trim()?o.trim():void 0,r=n(t.element)??"an element",s=(()=>{switch(e){case"browser_snapshot":return"read the page";case"browser_find":return n(t.text)?`find "${n(t.text)}" on the page`:n(t.regex)?`find ${n(t.regex)} on the page`:"search the page";case"browser_click":return`${t.doubleClick?"double-click":"click"} ${r}`;case"browser_hover":return`hover ${r}`;case"browser_type":return`type into ${r}`;case"browser_fill_form":return"fill in the form";case"browser_select_option":return`select in ${r}`;case"browser_press_key":return n(t.key)?`press ${n(t.key)}`:"press a key";case"browser_navigate":return n(t.url)?`go to ${n(t.url)}`:"navigate";case"browser_navigate_back":return"go back";case"browser_wait_for":return n(t.text)?`wait for "${n(t.text)}"`:n(t.textGone)?`wait for "${n(t.textGone)}" to go`:`wait ${t.time??""}s`.replace(" s","");case"browser_tabs":return n(t.action)?`tabs: ${n(t.action)}`:"list the tabs";case"browser_drag":return`drag ${n(t.startElement)??"an element"} to ${n(t.endElement)??"an element"}`;case"browser_file_upload":return"upload files";case"browser_handle_dialog":return`${t.accept?"accept":"dismiss"} the dialog`;case"browser_evaluate":case"browser_run_code":case"browser_run_code_unsafe":return"run a script in the page";case"browser_take_screenshot":return"take a screenshot";case"browser_console_messages":return"read the console";case"browser_network_requests":return"read the network log";default:return}})();return s?`${s} \xB7 ${e}`:e}var fr=class extends Error{};async function tg(e,t,n="none",r=()=>{},s={},o){let{createConnection:a,resolveCLIConfigForMCP:i}=hi("playwright-core/lib/coreBundle").tools,c=await i?.({},process.env)??{},l={...c,browser:{...c.browser,isolated:!1},sharedBrowserContext:!0,imageResponses:"omit",...s.outputDir?{outputDir:s.outputDir}:{},snapshot:{...c.snapshot,mode:n}},d=Cv(r),f=new Set,p=O=>{f.add(O)},u=async(O,T)=>{let _=O.browser(),N=new Set(_?.listeners("disconnected")??[]),F=Z=>{Z.on("download",p)};for(let Z of O.pages())F(Z);O.on("page",F);let I=Z=>{O.off("page",F);for(let Q of O.pages())Q.off("download",p);for(let Q of _?.listeners("disconnected")??[])N.has(Q)||_.off("disconnected",Q);return Z?b(O):void 0},L,j=new Tv({name:"saffron-trace",version:"1"});try{L=await a(l,async()=>O);let[Z,Q]=Av.createLinkedPair();await L.connect(Q),await j.connect(Z);let U=((await j.callTool({name:Xp,arguments:{}})).content??[]).map(ee=>ee.text??"").join(`
|
|
393
|
+
`);if(!U.includes(Xp))throw new Error(U.replace(/^### Error\s*/,"").trim()||"the browser backend did not start");let z=O.pages().filter(ee=>!ee.isClosed()),V=T?z.indexOf(T):-1;if(V>0&&(await j.callTool({name:"browser_tabs",arguments:{action:"list"}}),(await j.callTool({name:"browser_tabs",arguments:{action:"select",index:V}})).isError))throw new fr(`could not start on the session's tab ${V}`)}catch(Z){throw await Promise.allSettled([j.close(),L?.close()]),I(!1),Z}let H=L;return{context:O,client:j,close:async()=>{await Promise.allSettled([j.close()]),await Promise.allSettled([H.close()])},release:I}},h=0,b=O=>{h++;let T=!1,_=()=>{T||(T=!0,clearTimeout(F),O.off("close",N),--h===0&&d())},N=()=>{setTimeout(_,1e3).unref()},F=setTimeout(_,3e5);return F.unref(),O.on("close",N),_},g=new Map,S=new Set,y=!1,w=!1,v=O=>{let T=g.get(O);if(!T){if(y)return Promise.reject(new fr("the agent session is over"));T=o?o.pageOf(O).then(_=>u(_.context(),_),_=>{throw new fr(`browser session "${dt(O)}" could not open: ${_ instanceof Error?_.message:String(_)}`)}):u(e),g.set(O,T),T.then(_=>{w?_.close().finally(()=>_.release(!1)):S.add(_)},()=>{}),T.catch(()=>{g.get(O)===T&&g.delete(O)})}return T},x=()=>o?.keyOf()??"",$;try{$=await v(x())}catch(O){throw d(),O}let E=Promise.resolve(),R,k=(O,T)=>{let _=E.then(async()=>{let N=x(),F=await v(N);R=N;try{return await Jc(F.context,t(),O,T)}finally{R=void 0}});return E=_.then(()=>{},()=>{}),_},P=Aa({listTools:(...O)=>$.client.listTools(...O),callTool:async(...O)=>(await v(R??x())).client.callTool(...O)},(O,T,_)=>k(Pv(O,T),_),s.projectRoot,s.toolHooks),m=async()=>{let O=[...f];if(O.length===0)return;let T=Promise.all(O.map(N=>N.path().then(()=>!0,()=>!0))),_=!await Promise.race([T,Ds(Ev).then(()=>!1)]);_&&Vc++;try{_&&(await Promise.allSettled(O.map(N=>N.cancel())),await Promise.allSettled(O.map(N=>N.failure()))),await Ds(0),await Ds(0)}finally{_&&Vc--}};return{config:{type:"sdk",name:"playwright",instance:P},close:async()=>{y=!0,await Promise.race([E,Ds(Qp)]),await m().catch(()=>{});let O=Promise.allSettled([...g.values()]);await Promise.race([O.then(_v),Ds(Qp).then(Ov)]);let T=[...S];w=!0;for(let _ of T)await _.close();await Promise.allSettled([P.close()]);for(let _ of T)_.release(!0)},grouped:(O,T)=>k(O,T)}}var Nv=Iv(import.meta.url),jv=3e4,rg="This scenario runs in several browser sessions, and the agent needs Playwright's in-process browser tools to act in each of them; they could not start";function Mv(){let e=Nv.resolve("@playwright/mcp/package.json");return Wc.join(Wc.dirname(e),"cli.js")}var og=new Set(["mcp__playwright__browser_navigate","mcp__playwright__browser_click","mcp__playwright__browser_type","mcp__playwright__browser_fill_form","mcp__playwright__browser_select_option","mcp__playwright__browser_press_key"]),Dv=new Set([...og,"mcp__playwright__browser_press_sequentially","mcp__playwright__browser_check","mcp__playwright__browser_uncheck","mcp__playwright__browser_hover","mcp__playwright__browser_drag","mcp__playwright__browser_file_upload"]),Fv=new Set(["mcp__playwright__browser_network_requests","mcp__playwright__browser_network_request","mcp__playwright__browser_console_messages"]),sg=e=>e.startsWith("mcp__playwright__")&&!Fv.has(e),Lv=new Set(["mcp__playwright__browser_snapshot","mcp__playwright__browser_find","mcp__playwright__browser_wait_for","mcp__playwright__browser_take_screenshot","mcp__playwright__browser_console_messages","mcp__playwright__browser_network_requests","mcp__playwright__browser_network_request","mcp__saffron__saffron_step","mcp__saffron__saffron_capture","mcp__saffron__saffron_dialog","mcp__saffron__saffron_wait_api","mcp__saffron__saffron_assert","mcp__saffron__saffron_done"]);function mi(e,t){if(Lv.has(e))return!1;if(e==="mcp__playwright__browser_tabs"){let n=t?.action;return!(n==="list"||n==="select"||n==="close")}return!0}var Wr=class e{constructor(t,n){this.ctx=t;this.snapshotMode=n;this.state=new ti(t.scenario,{firstStep:Nc(t),discardBeforeAnnounce:xp(t),startedAt:this.startedAt,uniqueSeed:t.uniqueSeed,lastStep:t.recordOnly?t.recordOnly.to:t.mode==="record"?t.scenario.steps.length-1:void 0})}ctx;snapshotMode;state;usage={aiCalls:0,inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheCreationTokens:0};resultText="";toolCalls=0;traced;seenNames=new Map;capped;outputDir=du();get projectRoot(){return this.ctx.projectRoot??process.cwd()}stopTabWatch;stopDownloadWatch;downloadsHeard=0;heardAt=new Map;startedAt=new Date;static async open(t,n,r){let s=new e(t,n);try{return await e.attach(s,t,n,r)}catch(o){throw ng.rmSync(s.outputDir,{recursive:!0,force:!0}),o}}static async attach(t,n,r,s){let o=An(n.scenario.steps)?n.sessionPage:void 0;if(o&&s.traceBridgeUnavailable)throw new Error(rg);if((n.traceContext||o)&&!s.traceBridgeUnavailable){let a=Pe(n.scenario),i=n.traceContext??(await o(t.sessionKey())).context();try{let c=o&&{keyOf:()=>t.sessionKey(),pageOf:o};t.traced=await tg(i,()=>t.currentStep(),r,l=>{let d=l instanceof Error?l.message:String(l);console.warn(`A promise rejected during the agent session and nothing handled it: ${nt(d,a)}`)},{outputDir:t.outputDir,projectRoot:t.projectRoot,toolHooks:t.browserHooks},c)}catch(c){if(c instanceof fr)throw c;let l=nt(c instanceof Error?c.message:String(c),a);if(o)throw new Error(`${rg} (${l})`);s.traceBridgeUnavailable=!0,console.warn(`Agent tracing could not start (${l}). Continuing through the standard browser connection; agent calls will be absent from these traces.`)}}return t}sessionKey(){let t=this.state.currentStepIndex>=0?this.state.currentStepIndex:Nc(this.ctx);return pe(this.ctx.scenario.steps[t]?.session)}currentStep(){let t=this.state.currentStepIndex,n=this.ctx.scenario.steps[t];return{index:t,title:n?`${n.keyword} ${n.text}`:"Agent exploration"}}async playwrightServer(){return this.traced?this.traced.config:(this.capped??=await fu(this.playwrightStdio(),this.projectRoot,this.browserHooks),this.capped.config)}playwrightStdio(){return{command:process.execPath,args:[Mv(),"--cdp-endpoint",this.ctx.cdpEndpoint,"--snapshot-mode",this.snapshotMode,"--image-responses","omit","--output-dir",this.outputDir]}}noteThePage(t){let n="note the page for the recording";return this.traced?this.traced.grouped(n,t):this.ctx.traceContext?Jc(this.ctx.traceContext,this.currentStep(),n,t):t()}async beforeTool(t,n,r){this.toolCalls++;let s=Dc(n,r);if((Dv.has(n)||s?.action==="newTab"||s?.action==="closeTab")&&this.ctx.onBrowserAction?.(this.sessionKey()),this.state.beginToolCall(t),n.startsWith("mcp__playwright__")&&mi(n,r)&&this.heardAt.set(t,this.downloadsHeard),og.has(n)&&this.ctx.takeFingerprint&&!this.traced&&!this.state.pendingFingerprint)try{let o=this.ctx.takeFingerprint;this.state.pendingFingerprint=await this.noteThePage(()=>o(this.sessionKey()))}catch{}}afterTool(t,n,r,s){let o=Mp(n,r);o&&this.state.addArmedAction(o);let a=Dc(n,r,this.ctx.baseURL);a&&this.state.addActions([a]);let i=this.heardAt.get(t);if(this.heardAt.delete(t),sg(n)&&this.recordBrowserResult(s,i===void 0?void 0:this.downloadsHeard-i,Tp(r)),sg(n)){let c=this.seenNames.get(this.sessionKey())??new Map;for(let[l,d]of Rp(s))c.set(l,d);this.seenNames.set(this.sessionKey(),c)}this.state.endToolCall(t,mi(n,r))}browserHooks={beforeAction:()=>this.ctx.onBrowserAction?.(this.sessionKey()),onPartialResult:t=>this.recordBrowserResult(t)};recordBrowserResult(t,n,r=[]){let s=$p(t);s!==void 0&&this.ctx.onActiveTab?.(s,this.sessionKey());let o=Ep(t,this.ctx.baseURL);r.length>0&&Ap(o,r,this.seenNames.get(this.sessionKey())??new Map),this.state.addActions(o),this.state.pendingFingerprint=void 0;let i=this.stopDownloadWatch!==void 0?n??0:kp(t);i>0&&(this.state.addArmedAction({action:"waitForDownload",...i>1?{downloads:i}:{}}),this.state.downloadUnarmed=!1)}failedTool(t,n,r){this.heardAt.delete(t),n.startsWith("mcp__playwright__")&&(this.state.pendingFingerprint=void 0),this.state.endToolCall(t,mi(n,r))}watchTabs(){this.stopTabWatch=this.ctx.onTabOpened?.(n=>this.state.markTabOpened(n));let t=0;this.stopDownloadWatch=this.ctx.onDownload?.(n=>{this.downloadsHeard++,this.heardAt.size===0&&(this.state.downloadUnarmed=!this.state.creditLateDownload()),this.state.lastDownload=Ha(n,Wc.join(this.outputDir,"downloads",String(++t)),jv).catch(()=>{})})}sessionError(t){if(this.state.done)return;let n=t instanceof Error?t.message:String(t);this.state.done=!0,this.state.success=!1,this.state.narrative=`${Ms}${n}`}async close(){this.stopTabWatch?.(),this.stopTabWatch=void 0,this.stopDownloadWatch?.(),this.stopDownloadWatch=void 0,await this.traced?.close(),await this.capped?.close(),ng.rmSync(this.outputDir,{recursive:!0,force:!0})}result(){let{ctx:t,state:n}=this;if(!n.done){n.success=!1;let r=this.toolCalls===0?" The agent made no browser or Saffron tool call, so its tools did not reach it: check the provider's SDK version and its login.":"";n.narrative=n.narrative||`Agent session ended without finalizing the run.${r} Last output: ${nt(this.resultText,Pe(t.scenario)).slice(0,500)}`}return{success:n.success,narrative:n.narrative,adaptations:[...n.adaptations,...n.attributionNotes()],suggestedFeatureEdit:n.suggestedFeatureEdit,featureEdits:n.featureEdits.map(r=>{let s=zr(r.text,t.scenario.params),o=t.scenario.steps[r.index];return{index:r.index,text:o?zl(o.text,s):s}}),recordedSteps:Np(n.steps,t.scenario,t.uniqueSeed,this.startedAt),announcedSteps:[...n.announced].sort((r,s)=>r-s),usage:this.usage}}};var wi=class{constructor(t={}){this.opts=t}opts;planBefore;traceBridgeUnavailable=!1;async planUsage(){if(!this.planBefore)return;let t=await this.planBefore;if(!t)return;let n=await Yp();return{subscriptionType:t.subscriptionType,fiveHourBefore:t.utilization,fiveHourAfter:n?.utilization,resetsAt:n?.resetsAt??t.resetsAt}}async run(t){let n=await Wr.open(t,this.opts.snapshotMode??"none",this),r;try{r=Bv({prompt:gi(t,n.startedAt),options:{systemPrompt:pi({deliberateSnapshots:n.snapshotMode==="none",adaptableMidAssertions:t.assertionPolicy==="adaptable-mid"}),model:t.model??this.opts.model,maxTurns:this.opts.maxTurns??100,tools:[],permissionMode:"bypassPermissions",allowDangerouslySkipPermissions:!0,persistSession:!1,settingSources:[],strictMcpConfig:!0,settings:{disableClaudeAiConnectors:!0},mcpServers:{playwright:await n.playwrightServer(),saffron:ui(n.state)},hooks:{PreToolUse:[{hooks:[async s=>{let o=s;return await n.beforeTool(o.tool_use_id,o.tool_name,o.tool_input),{continue:!0}}]}],PostToolUse:[{hooks:[async s=>{let o=s;return n.afterTool(o.tool_use_id,o.tool_name,o.tool_input,o.tool_response),{continue:!0}}]}],PostToolUseFailure:[{hooks:[async s=>{let o=s;return n.failedTool(o.tool_use_id,o.tool_name,o.tool_input),{continue:!0}}]}]}}})}catch(s){throw await n.close(),s}this.planBefore||(this.planBefore=qc(r)),n.watchTabs();try{let s;for await(let o of r){let a=o.type==="rate_limit_event"?o.rate_limit_info:void 0;if(a?.status==="rejected"&&!a.isUsingOverage&&a.overageStatus!=="allowed"&&a.overageStatus!=="allowed_warning"){let i=a.resetsAt;s=`Claude usage limit reached${i?`; it resets at ${new Date(i*1e3).toISOString()}`:""}`}o.type==="result"&&o.is_error&&(s??=`Claude: ${"result"in o&&o.result?o.result:o.subtype}`),o.type==="result"&&(n.usage.aiCalls=o.num_turns,n.usage.costUsd=o.total_cost_usd,"modelUsage"in o&&o.modelUsage&&(n.usage.models=Object.keys(o.modelUsage)),"usage"in o&&o.usage&&(n.usage.inputTokens=o.usage.input_tokens??0,n.usage.outputTokens=o.usage.output_tokens??0,n.usage.cacheReadTokens=o.usage.cache_read_input_tokens??0,n.usage.cacheCreationTokens=o.usage.cache_creation_input_tokens??0),o.subtype==="success"&&(n.resultText=o.result))}s&&n.sessionError(new Error(s))}catch(s){n.sessionError(s)}finally{await n.close()}return n.result()}};import Uv from"node:http";import{randomBytes as zv,randomUUID as Hv,timingSafeEqual as qv}from"node:crypto";import{Client as Vv}from"@modelcontextprotocol/sdk/client/index.js";import{InMemoryTransport as Jv}from"@modelcontextprotocol/sdk/inMemory.js";import{Server as Wv}from"@modelcontextprotocol/sdk/server/index.js";import{StreamableHTTPServerTransport as Gv}from"@modelcontextprotocol/sdk/server/streamableHttp.js";import{CallToolRequestSchema as Kv,ListToolsRequestSchema as Yv}from"@modelcontextprotocol/sdk/types.js";var Zv=5e3;async function Qv(e,t){let n=zv(16).toString("hex"),r=Buffer.from(`Bearer ${n}`),s=u=>{let h=Buffer.from(u??"");return h.length===r.length&&qv(h,r)},o=Promise.resolve(),a=!1,i=new AbortController,c,l=u=>{let h=o.then(u);return o=h.catch(()=>{}),h},d=(u,h)=>{let b=new Wv({name:u,version:"1"},{capabilities:{tools:{}}});return b.setRequestHandler(Yv,g=>h.listTools(g.params)),b.setRequestHandler(Kv,(g,S)=>l(async()=>{if(a||S.signal.aborted)throw new Error(a?"the agent session is over":"the call was cancelled before its turn came");let y=Hv(),w=`mcp__${u}__${g.params.name}`,v=g.params.arguments??{};await t.beforeTool(y,w,v);try{i.signal.throwIfAborted();let x=await h.callTool(g.params,void 0,{timeout:Ra,signal:i.signal});return x.isError?t.failedTool(y,w,v):t.afterTool(y,w,v,x),x}catch(x){throw t.failedTool(y,w,v),x}})),b},f=Uv.createServer(async(u,h)=>{let b=(u.url??"").split("?")[0].slice(1),g=s(u.headers.authorization)?e[b]:void 0;if(!g)return void h.writeHead(404).end();if(u.method!=="POST")return void h.writeHead(405,{Allow:"POST"}).end();let S=d(b,g),y=new Gv({sessionIdGenerator:void 0,enableJsonResponse:!0});h.on("close",()=>{Promise.allSettled([y.close(),S.close()])});try{await S.connect(y),await y.handleRequest(u,h)}catch{h.headersSent||h.writeHead(500).end()}});f.requestTimeout=0,await new Promise((u,h)=>{f.once("error",h),f.listen(0,"127.0.0.1",()=>u())});let{port:p}=f.address();return{urls:Object.fromEntries(Object.keys(e).map(u=>[u,`http://127.0.0.1:${p}/${u}`])),token:n,close:()=>c??=(async()=>{a=!0,f.closeAllConnections(),await new Promise(h=>f.close(()=>h()));let u;try{await Promise.race([o,new Promise((h,b)=>{u=setTimeout(()=>{let g=new Error("Agent shutdown timed out after 5 seconds waiting for a browser tool; the incomplete recording cannot be used.");i.abort(g),b(g)},Zv),u.unref()})])}finally{clearTimeout(u)}})()}}async function ig(e){let[t,n]=Jv.createLinkedPair();await e.connect(n);let r=new Vv({name:"saffron-gateway",version:"1"});return await r.connect(t),r}async function ag(e,t=e){let n=[];try{let r=await ig((await e.playwrightServer()).instance);n.push(r);let s=await ig(ui(e.state).instance);n.push(s);let o=await Qv({playwright:r,saffron:s},t);return{urls:o.urls,token:o.token,close:async()=>{try{await o.close()}finally{await Promise.allSettled(n.map(a=>a.close()))}}}}catch(r){throw await Promise.allSettled(n.map(s=>s.close())),r}}var yi=class{constructor(t,n={},r=()=>{}){this.drive=t;this.opts=n;this.blocker=r}drive;opts;blocker;traceBridgeUnavailable=!1;async run(t){let n=this.blocker();if(n)throw new Error(n);let r=await Wr.open(t,this.opts.snapshotMode??"none",this),s=this.opts.maxTurns??100,o=new AbortController,a=0,i;try{i=await ag(r,{beforeTool:async(l,d,f)=>{if(++a>s)throw o.abort(new Error(pr(s))),o.signal.reason;await r.beforeTool(l,d,f)},afterTool:r.afterTool.bind(r),failedTool:r.failedTool.bind(r)})}catch(l){throw await r.close(),l}r.watchTabs();let c;try{if(await this.drive({systemPrompt:pi({deliberateSnapshots:r.snapshotMode==="none",adaptableMidAssertions:t.assertionPolicy==="adaptable-mid"}),prompt:gi(t,r.startedAt),model:t.model??this.opts.model,maxTurns:s,signal:o.signal,mcpServers:i.urls,mcpToken:i.token,usage:r.usage,lastOutput:l=>{r.resultText=l},finished:()=>r.state.done}),o.signal.aborted)throw o.signal.reason}catch(l){c={error:l}}finally{try{try{await i.close()}catch(l){c={error:l},r.state.done=!1}c&&r.sessionError(c.error)}finally{await r.close()}}return r.result()}};async function Ls(e,t){try{return await import(e)}catch(n){let r=n.code;throw(r==="ERR_MODULE_NOT_FOUND"||r==="MODULE_NOT_FOUND")&&String(n.message).includes(`'${e}'`)?new Error(`the ${t} provider needs ${e}: npm install --save-dev ${e}`):n}}function pr(e){return`stopped after ${e} tool calls, the session's turn limit: raise maxTurns in saffron.config.json, or look at what the agent kept retrying`}import Gr from"node:fs";import Gc from"node:os";import en from"node:path";import{createHash as Xv}from"node:crypto";import{createRequire as cg}from"node:module";function ex(){try{let e=cg(import.meta.resolve("@openai/codex-sdk")).resolve("@openai/codex/package.json"),t=cg(e).resolve(`@openai/codex-${process.platform}-${process.arch}/package.json`),n=en.join(en.dirname(t),"vendor");for(let r of Gr.readdirSync(n))for(let s of[en.join(n,r,"bin","codex"),en.join(n,r,"codex","codex")])if(Gr.existsSync(s))return s}catch{}}function bi(e=process.platform){return e==="win32"?"the codex provider is not available on Windows yet: Saffron must run Codex without your ~/.codex/config.toml (your own MCP servers, plugins and hooks), and cannot on Windows":void 0}function tx(e){return`'${e.replaceAll("'","'\\''")}'`}function nx(){let e=bi();if(e)throw new Error(e);let t=ex();if(!t)throw new Error("the Codex binary is missing from @openai/codex-sdk's install: reinstall it with npm install --save-dev @openai/codex-sdk");let n=en.join(process.env.XDG_CACHE_HOME||en.join(Gc.homedir(),".cache"),"saffron");Gr.mkdirSync(n,{recursive:!0});let r=en.join(n,`codex-${Xv("sha256").update(t).digest("hex").slice(0,12)}`);return Je(r,`#!/bin/sh
|
|
371
394
|
sub="$1"; shift
|
|
372
|
-
exec ${
|
|
373
|
-
`,493),r}var
|
|
374
|
-
`,c)}catch(l){let d=l.code;throw!
|
|
375
|
-
`).at(-1)||(t.error?.message??"no answer");throw new Error(`agy could not list your models (${r}): run agy once and sign in with your Google AI Pro or Ultra account`)}let n=
|
|
395
|
+
exec ${tx(t)} "$sub" --ignore-user-config --ephemeral "$@"
|
|
396
|
+
`,493),r}var lg="SAFFRON_MCP_TOKEN",rx=["cli_auth_credentials_store","forced_login_method","forced_chatgpt_workspace_id"];function sx(e){let t=e.split(/^\s*\[/m)[0],n={};for(let r of rx){let s=new RegExp(`^\\s*${r}\\s*=\\s*(?:"([^"]*)"|'([^']*)')`,"m").exec(t);s&&(n[r]=s[1]??s[2])}return n}function Kc(){try{return sx(Gr.readFileSync(en.join(process.env.CODEX_HOME??en.join(Gc.homedir(),".codex"),"config.toml"),"utf8"))}catch{return{}}}var dg=async e=>{let{Codex:t}=await Ls("@openai/codex-sdk","codex"),n=Gr.mkdtempSync(en.join(Gc.tmpdir(),"saffron-codex-"));try{let r=Object.fromEntries(Object.entries(process.env).filter(d=>d[1]!==void 0)),o=new t({codexPathOverride:nx(),env:{...r,[lg]:e.mcpToken},config:{...Kc(),developer_instructions:e.systemPrompt,include_permissions_instructions:!1,include_apps_instructions:!1,include_collaboration_mode_instructions:!1,include_environment_context:!1,project_doc_max_bytes:0,skills:{include_instructions:!1},mcp_servers:Object.fromEntries(Object.entries(e.mcpServers).map(([d,f])=>[d,{url:f,bearer_token_env_var:lg,required:!0,default_tools_approval_mode:"approve",startup_timeout_sec:30,tool_timeout_sec:600}])),features:{shell_tool:!1,view_image:!1,apps:!1,plugins:!1,hooks:!1,memories:!1,goals:!1,image_generation:!1,tool_suggest:!1,browser_use:!1,computer_use:!1,unified_exec:!1,multi_agent:!1,code_mode_host:!0,in_app_browser:!1,browser_use_external:!1}}}).startThread({model:e.model,workingDirectory:n,skipGitRepoCheck:!0,sandboxMode:"read-only",approvalPolicy:"never",webSearchMode:"disabled"}),a=new AbortController,i=e.signal?AbortSignal.any([a.signal,e.signal]):a.signal,c=0,l;try{let{events:d}=await o.runStreamed(e.prompt,{signal:i});for await(let f of d)if(f.type==="item.started"&&f.item.type==="mcp_tool_call")++c>e.maxTurns&&!i.aborted&&(l=pr(e.maxTurns),a.abort());else if(f.type==="item.completed")(f.item.type==="mcp_tool_call"||f.item.type==="agent_message")&&e.usage.aiCalls++,f.item.type==="agent_message"&&e.lastOutput(f.item.text);else if(f.type==="turn.completed"){let p=f.usage;e.usage.inputTokens=p.input_tokens-p.cached_input_tokens,e.usage.cacheReadTokens=p.cached_input_tokens,e.usage.cacheCreationTokens=p.cache_write_input_tokens??0,e.usage.outputTokens=p.output_tokens}else f.type==="turn.failed"&&!i.aborted?l=f.error.message:f.type==="error"&&!i.aborted&&(l??=f.message)}catch(d){if(!i.aborted&&!l)throw d}if(e.signal?.aborted&&(l=String(e.signal.reason instanceof Error?e.signal.reason.message:e.signal.reason)),e.usage.models=[`codex/${e.model??"default"}`],l&&!e.finished()){let d=/auth|log ?in|401|unauthori[sz]ed/i.test(l)?". Sign in with your ChatGPT plan: npx @openai/codex login":"";throw new Error(`Codex: ${l}${d}`)}}finally{Gr.rmSync(n,{recursive:!0,force:!0})}};import{spawn as ox,spawnSync as ix}from"node:child_process";import Me from"node:fs";import xi from"node:os";import Ue from"node:path";import ax from"node:readline";var vi="install the Antigravity CLI (curl -fsSL https://antigravity.google/cli/install.sh | bash), then run `agy` once to sign in with your Google account";function Si(){for(let e of[...(process.env.PATH??"").split(Ue.delimiter),Ue.join(xi.homedir(),".local","bin")]){let t=Ue.join(e,process.platform==="win32"?"agy.exe":"agy");if(e&&Me.existsSync(t))return t}}var Kr={playwright:"saffron_browser",saffron:"saffron_tools"},ug=Object.values(Kr).map(e=>`mcp(${e}/*)`),Yc=()=>Ue.join(xi.homedir(),".gemini","antigravity-cli","settings.json");function fg(e){if(!Me.existsSync(e))return{};try{let t=JSON.parse(Me.readFileSync(e,"utf8"));if(t&&typeof t=="object"&&!Array.isArray(t))return t}catch{}throw new Error(`${e} is not a JSON object Saffron can add to: fix it (or ask agy to rewrite it), then run npx saffron login antigravity again`)}function $i(e=Yc()){let t;try{t=fg(e).permissions?.allow}catch{return ug}return ug.filter(n=>!(Array.isArray(t)&&t.includes(n)))}function cx(e=Yc()){let t=fg(e),n=$i(e);if(n.length===0)return[];let r=t.permissions&&typeof t.permissions=="object"?t.permissions:{},s=Array.isArray(r.allow)?r.allow:[],o={...t,permissions:{...r,allow:[...s,...n]}},a=Me.lstatSync(e,{throwIfNoEntry:!1})?.isSymbolicLink()??!1,i=lx(e),c=Me.existsSync(i)?Me.statSync(i).mode&4095:void 0;try{Je(i,JSON.stringify(o,null,2)+`
|
|
397
|
+
`,c)}catch(l){let d=l.code;throw!a||!["EACCES","EPERM","EROFS"].includes(d??"")?l:new Error(`${e} links to ${i}, which Saffron cannot write: add ${n.join(" and ")} to permissions.allow there, then run npx saffron login antigravity again`)}return n}function lx(e){let t=e;for(let n=0;n<40&&Me.lstatSync(t,{throwIfNoEntry:!1})?.isSymbolicLink();n++)t=Ue.resolve(Me.realpathSync(Ue.dirname(t)),Me.readlinkSync(t));return Me.existsSync(t)?Me.realpathSync(t):t}async function pg(){let e=Si();if(!e)throw new Error(`the antigravity provider needs the agy command: ${vi}`);let t=ix(e,["models"],{encoding:"utf8",timeout:6e4});if(t.status!==0){let r=`${t.stderr??""}${t.stdout??""}`.trim().split(`
|
|
398
|
+
`).at(-1)||(t.error?.message??"no answer");throw new Error(`agy could not list your models (${r}): run agy once and sign in with your Google AI Pro or Ultra account`)}let n=cx();console.log(n.length>0?`Antigravity: allowed Saffron's tools in ${Yc()}: ${n.join(", ")}. Remove those lines to take it back.`:"Antigravity: Saffron's tools are already allowed.")}var gg=Ue.join(xi.homedir(),".gemini","antigravity-cli","mcp"),dx=Object.values(Kr).map(e=>Ue.join(gg,e)),ux=`const path=require("path");const DIRS=${JSON.stringify(dx)};const SERVERS=${JSON.stringify(Object.values(Kr))};
|
|
376
399
|
let s="";process.stdin.on("data",d=>s+=d).on("end",()=>{let t={};try{t=JSON.parse(s).toolCall||{}}catch{}const a=t.args||{};
|
|
377
400
|
const file=typeof a.AbsolutePath==="string"?path.resolve(a.AbsolutePath):"";
|
|
378
401
|
const dir=typeof a.DirectoryPath==="string"?path.resolve(a.DirectoryPath):"";
|
|
379
402
|
const ok=(t.name==="call_mcp_tool"&&SERVERS.includes(a.ServerName))||(t.name==="view_file"&&DIRS.includes(path.dirname(file)))||(t.name==="list_dir"&&DIRS.includes(dir));
|
|
380
|
-
process.stdout.write(JSON.stringify(ok?{decision:"allow"}:{decision:"deny",reason:"Only Saffron's browser and saffron tools are available in a Saffron session."}))})`,
|
|
403
|
+
process.stdout.write(JSON.stringify(ok?{decision:"allow"}:{decision:"deny",reason:"Only Saffron's browser and saffron tools are available in a Saffron session."}))})`,fx=(e,t)=>`let s="";process.stdin.on("data",d=>s+=d).on("end",()=>{let i=0;try{i=JSON.parse(s).invocationNum}catch{}
|
|
381
404
|
const stop=i+1>=${e};if(stop)require("fs").writeFileSync(${JSON.stringify(t)},"");
|
|
382
|
-
process.stdout.write(JSON.stringify(stop?{terminationBehavior:"terminate"}:{}))})
|
|
405
|
+
process.stdout.write(JSON.stringify(stop?{terminationBehavior:"terminate"}:{}))})`,hg=async e=>{let t=Si();if(!t)throw new Error(`the antigravity provider needs the agy command: ${vi}`);if(Object.keys(e.mcpServers).length>0&&$i().length>0)throw new Error("agy does not allow Saffron's tools yet: run npx saffron login antigravity once");let n=Me.mkdtempSync(Ue.join(xi.tmpdir(),"saffron-agy-"));try{let r=Ue.join(n,".agents");Me.mkdirSync(Ue.join(r,"agents"),{recursive:!0}),Me.writeFileSync(Ue.join(r,"agents","saffron.md"),`---
|
|
383
406
|
name: saffron
|
|
384
407
|
description: Saffron's browser test agent.
|
|
385
408
|
mainAgent: true
|
|
@@ -389,15 +412,15 @@ commandExecutionPolicy: off
|
|
|
389
412
|
|
|
390
413
|
${e.systemPrompt}
|
|
391
414
|
|
|
392
|
-
Your tools are MCP tools, called with call_mcp_tool: the browser_* tools are on the ${
|
|
393
|
-
`),
|
|
394
|
-
`).at(-1)||`agy exited with ${
|
|
415
|
+
Your tools are MCP tools, called with call_mcp_tool: the browser_* tools are on the ${Kr.playwright} server and the saffron_* tools on the ${Kr.saffron} server. Before a tool's first call, read its parameters with view_file from ${Ue.join(gg,"<server>","<tool>.json")}. No other tool is available.
|
|
416
|
+
`),Me.writeFileSync(Ue.join(r,"mcp_config.json"),JSON.stringify({mcpServers:Object.fromEntries(Object.entries(e.mcpServers).map(([g,S])=>[Kr[g]??g,{serverUrl:S,headers:{Authorization:`Bearer ${e.mcpToken}`}}]))}));let s=(g,S)=>{let y=Ue.join(n,g);return Me.writeFileSync(y,S),`${JSON.stringify(process.execPath)} ${JSON.stringify(y)}`};Me.writeFileSync(Ue.join(r,"hooks.json"),JSON.stringify({"saffron-gate":{PreToolUse:[{matcher:"",hooks:[{type:"command",command:s("gate.cjs",ux)}]}]},"saffron-turns":{PostInvocation:[{type:"command",command:s("turns.cjs",fx(e.maxTurns,Ue.join(n,"turn-limit")))}]}}));let a=["--output-format","stream-json","--agent","saffron","--print-timeout",`${Math.max(30,2*e.maxTurns)}m`,"--sandbox"];e.model&&a.push("--model",e.model);let i=ox(t,a,{cwd:n,stdio:["pipe","pipe","pipe"]});i.stdin.on("error",()=>{}),i.stdin.end(e.prompt);let c="";i.stderr.on("data",g=>{c=(c+g).slice(-4e3)});let l=new Promise((g,S)=>i.once("error",y=>S(new Error(`Antigravity: could not start ${t}: ${y.message}. ${vi}`)))),d=new Promise(g=>i.once("close",g)),f="",p,u,h=(async()=>{for await(let g of ax.createInterface({input:i.stdout})){let S;try{S=JSON.parse(g)}catch{continue}let y=S.step_update;y?(y.state==="DONE"&&y.usage&&e.usage.aiCalls++,y.step_type==="agent_response"&&typeof y.text_delta=="string"&&(y.step_index!==p&&([f,p]=["",y.step_index]),f+=y.text_delta,e.lastOutput(f))):S.event==="result"&&(u=S.result)}})();await Promise.race([h,l]);let b=await Promise.race([d,l]);if(u?.usage&&(e.usage.inputTokens+=Math.max(0,(u.usage.input_tokens??0)-(u.usage.cache_read_tokens??0)),e.usage.outputTokens+=u.usage.output_tokens??0,e.usage.cacheReadTokens+=u.usage.cache_read_tokens??0),e.usage.models=[`antigravity/${e.model??"default"}`],u?.response&&e.lastOutput(u.response),!e.finished()&&Me.existsSync(Ue.join(n,"turn-limit")))throw new Error(`Antigravity: ${pr(e.maxTurns)}`);if((u?.status!=="SUCCESS"||b!==0)&&!e.finished()){let g=typeof u?.error=="string"?u.error:c.trim().split(`
|
|
417
|
+
`).at(-1)||`agy exited with ${b}`;throw new Error(`Antigravity: ${g}${/auth/i.test(g)?`. ${vi}`:""}`)}}finally{Me.rmSync(n,{recursive:!0,force:!0})}};import mg from"node:fs";import px from"node:os";import gx from"node:path";var yg="@cursor/sdk";function Bs(e=process.versions.node){let[t,n]=e.split(".").map(Number);return t>22||t===22&&n>=13?void 0:`the cursor provider needs Node.js 22.13 or newer (this is ${e})`}var bg=async e=>{let t=Bs();if(t)throw new Error(t);let{Agent:n,JsonlLocalAgentStore:r}=await Ls(yg,"cursor"),s=mg.mkdtempSync(gx.join(px.tmpdir(),"saffron-cursor-")),o=a=>n.create({model:{id:e.model??"auto"},...a?{systemPrompt:a}:{},tools:["mcp"],mcpServers:Object.fromEntries(Object.entries(e.mcpServers).map(([i,c])=>[i,{type:"http",url:c,headers:{Authorization:`Bearer ${e.mcpToken}`}}])),local:{cwd:s,settingSources:[],store:new r(s)}});try{let a=await wg(await o(e.systemPrompt),e.prompt,e);if(a.status==="error"&&/system.?prompt/i.test(a.error?.message??"")&&(a=await wg(await o(void 0),`${e.systemPrompt}
|
|
395
418
|
|
|
396
419
|
---
|
|
397
420
|
|
|
398
|
-
${e.prompt}`,e)),
|
|
399
|
-
`)),{calls:r,order:s,events:o}=
|
|
400
|
-
`)){if(!r.trim())continue;let s;try{s=JSON.parse(r)}catch{continue}if(s.type!=="resource-snapshot"||!s.snapshot)continue;let o=s.snapshot,
|
|
421
|
+
${e.prompt}`,e)),a.status==="error"&&!e.finished())throw new Error(`Cursor: ${a.error?.message??"the run failed"}${hx(a.error?.message)}`)}finally{mg.rmSync(s,{recursive:!0,force:!0})}};async function wg(e,t,n){try{let r=await e.send(t),s="",o=new Set,a=!1;for await(let c of r.stream())if(c.type==="usage")n.usage.aiCalls++;else if(c.type==="assistant"){for(let l of c.message.content)l.type==="text"&&(s+=l.text);n.lastOutput(s)}else c.type==="tool_call"&&(s="",c.status==="running"&&o.add(c.call_id??`#${o.size}`),o.size>n.maxTurns&&!a&&(a=!0,await r.cancel()));let i=await r.wait();if(i.usage&&(n.usage.inputTokens+=i.usage.inputTokens,n.usage.outputTokens+=i.usage.outputTokens,n.usage.cacheReadTokens+=i.usage.cacheReadTokens,n.usage.cacheCreationTokens+=i.usage.cacheWriteTokens),i.model&&(n.usage.models=[...new Set([...n.usage.models??[],`cursor/${i.model.id}`])]),i.result&&n.lastOutput(i.result),a&&!n.finished())throw new Error(`Cursor: ${pr(n.maxTurns)}`);return i}finally{e.close()}}function hx(e=""){return/api key|unauthenticated|unauthori[sz]ed|logged.?out/i.test(e)?". Sign in once with: npx saffron login cursor":""}async function vg(){let e=Bs();if(e)throw new Error(e);let{Cursor:t}=await Ls(yg,"cursor"),n=await t.auth.status();if(n.status==="logged-in"){console.log(`Cursor: already signed in${n.email?` as ${n.email}`:""}.`);return}await t.auth.login({onLoginUrl:r=>console.log(`Opening ${r}`)}),console.log("Cursor: signed in. Saffron runs will use your Cursor plan.")}var Zc=["claude","codex","antigravity","cursor"];function $g(e){return Zc.includes(e)}var Qc={codex:dg,antigravity:hg,cursor:bg};function kg(e,t){return e==="claude"?new wi(t):new yi(Qc[e],t,()=>{let n=Ti(e);return n.length>0?`${yn[e]} cannot start here: ${n.join("; ")}`:void 0})}var Ri=(...e)=>Sg.join(mx.homedir(),...e);function xg(e){try{return import.meta.resolve(e),!0}catch{return!1}}function Ti(e){switch(e){case"claude":return[];case"codex":{let t=bi();return t?[t]:xg("@openai/codex-sdk")?[]:["npm install --save-dev @openai/codex-sdk"]}case"antigravity":return Si()?$i().length>0?["Saffron's tools allowed in agy, once: npx saffron login antigravity"]:[]:["the Antigravity CLI: curl -fsSL https://antigravity.google/cli/install.sh | bash","then run `agy` once to sign in with your Google AI Pro or Ultra account"];case"cursor":{let t=Bs();return t?[t]:xg("@cursor/sdk")?[]:["npm install --save-dev @cursor/sdk"]}}}function Xc(e){let t=process.env,n=Ti(e);if(e==="claude")t.ANTHROPIC_API_KEY||t.CLAUDE_CODE_OAUTH_TOKEN||t.CLAUDE_CODE_USE_BEDROCK||t.CLAUDE_CODE_USE_VERTEX||ki.existsSync(Ri(".claude",".credentials.json"))||ki.existsSync(Ri(".claude.json"))||n.push("ANTHROPIC_API_KEY=sk-ant-... (console.anthropic.com \u2192 API keys)","or a Claude Code login on this machine");else if(e==="codex"&&!bi()){let r=Sg.join(t.CODEX_HOME??Ri(".codex"),"auth.json");!["keyring","auto"].includes(Kc().cli_auth_credentials_store??"")&&!ki.existsSync(r)&&n.push("a Codex login with your ChatGPT plan: npx @openai/codex login")}else e==="cursor"&&!Bs()&&!t.CURSOR_API_KEY&&!ki.existsSync(Ri(".cursor","sdk","auth.json"))&&n.push("a Cursor sign-in for Saffron (once per machine): npx saffron login cursor");return n}var yn={claude:"Claude",codex:"Codex",antigravity:"Antigravity",cursor:"Cursor"},Rg={claude:"@anthropic-ai/claude-agent-sdk",codex:"@openai/codex-sdk",cursor:"@cursor/sdk"};var Hn=(e,t=0)=>typeof e=="number"?e:t,he=e=>typeof e=="string"?e:void 0;function wx(e,t){if(!t)return;let n=he(t.selector);if(n)return yx(n);let r=he(t.url);if(r)return r;if(e==="press"||e==="keyboardPress")return he(t.key)}function yx(e){return e.replace(/internal:role=([a-z]+)\[name="((?:[^"\\]|\\.)*)"[is]?\]/g,(t,n,r)=>`${n} "${r}"`).replace(/internal:role=([a-z]+)/g,"$1").replace(/internal:label="((?:[^"\\]|\\.)*)"[is]?/g,'label "$1"').replace(/internal:text="((?:[^"\\]|\\.)*)"[is]?/g,'text "$1"').replace(/internal:attr=\[placeholder="((?:[^"\\]|\\.)*)"[is]?\]/g,'placeholder "$1"').replace(/internal:testid=\[data-testid="((?:[^"\\]|\\.)*)"s?\]/g,'test id "$1"').replace(/internal:has-text="((?:[^"\\]|\\.)*)"[is]?/g,'with text "$1"').replace(/ >> nth=0$/,"").replace(/ >> /g," \u203A ").replace(/nth=(\d+)/g,"#$1")}function bx(e){let t=new Map,n=[],r=[];for(let s of e){if(!s.trim())continue;let o;try{o=JSON.parse(s)}catch{continue}r.push(o);let a=he(o.callId);switch(o.type){case"before":{if(!a)break;let i=he(o.method)??"",c=o.class==="Tracing"&&i==="tracingGroup",l=i==="__waitInfo__";t.set(a,{callId:a,method:l?he(o.title)??"wait":i,subject:wx(i,o.params),selector:he(o.params?.selector),startTime:Hn(o.startTime),log:[],pageId:he(o.pageId),before:el(o,"beforeSnapshot"),calls:[],parentId:he(o.parentId),isGroup:c,title:he(o.title),isWait:l}),n.push(a);break}case"input":{let i=a?t.get(a):void 0;if(i){i.input=el({...o,pageId:i.pageId},"inputSnapshot");let c=o.point,l=o.box,d=c??(l?{x:l.x+l.width/2,y:l.y+l.height/2}:void 0);i.input&&d?i.input.point=d:d&&(i.inputPoint=d)}break}case"frame-snapshot":{let i=o.snapshot,c=i?.callId?t.get(i.callId):void 0;if(c&&i?.phase&&i.pageId&&i.isMainFrame!==!1){let l=i.phase,d={pageId:i.pageId,name:`${l}@${i.callId}`,callId:i.callId,phase:l};if(c.pageId||(c.pageId=i.pageId),l==="before"&&!c.before)c.before=d;else if(l==="after")c.after=d;else if(l==="action"&&!c.input){let f=c.inputPoint;c.input=f?{...d,point:f}:d}}break}case"log":{let i=a?t.get(a):void 0,c=he(o.message);i&&c&&i.log.push(c);break}case"after":{let i=a?t.get(a):void 0;if(!i)break;i.endTime=Hn(o.endTime,i.startTime);let c=o.error;c?.message&&(i.error=c.message);let l=el({...o,pageId:i.pageId},"afterSnapshot");l&&(i.after=l);break}default:break}}return{calls:t,order:n,events:r}}function el(e,t){let n=he(e[t]),r=he(e.pageId);return n&&r?{pageId:r,name:n}:void 0}function Tg(e){return tl(wu(e))}function tl(e){let n=e.filter(w=>w.name.endsWith(".trace")).flatMap(w=>w.data.toString("utf8").split(`
|
|
422
|
+
`)),{calls:r,order:s,events:o}=bx(n),a=new Map;for(let w of o){let v=w.snapshot;if(w.type!=="frame-snapshot"||!v?.isMainFrame||!v.pageId||!v.frameUrl)continue;let x=v.snapshotName??(v.callId&&v.phase?`${v.phase}@${v.callId}`:void 0);x&&a.set(`${v.pageId}/${x}`,v.frameUrl)}for(let w of r.values())for(let v of[w.before,w.input,w.after])v&&(v.url=a.get(`${v.pageId}/${v.name}`));let i=[];for(let w of s){let v=r.get(w),x=v.parentId?r.get(v.parentId):void 0;x?x.calls.push(v):i.push(w)}let c=w=>{let{parentId:v,isGroup:x,title:$,isWait:E,...R}=w;return{...R,calls:R.calls.map(k=>c(k))}},l=w=>w.find(v=>v.error&&!v.isWait)?.error,d=[],f=[];for(let w of i){let v=r.get(w);if(!v.isGroup){f.push(c(v));continue}let x={title:v.title??"",startTime:v.startTime,endTime:v.endTime,error:v.error,actions:[],calls:[]},$=/^\[saffron:(agent|replay|pending):(-?\d+)\] (.*)$/.exec(x.title);$&&(x.phase=$[1],x.stepIndex=Number($[2]),x.title=$[3]);let E=[];for(let R of v.calls)if(R.isGroup){let k={title:R.title??"",startTime:R.startTime,endTime:R.endTime,error:R.error??l(R.calls),calls:R.calls.map(P=>c(P))},C=/^\[saffron:action:(\d+)\] ([\s\S]*)$/.exec(k.title);C&&(k.actionIndex=Number(C[1]),k.title=C[2]),x.actions.push(k)}else E.push(R),x.calls.push(c(R));x.error||(x.error=x.actions.find(R=>R.error)?.error??l(E)),d.push(x)}let p=[],u=new Map,h,b,g,S=Number.POSITIVE_INFINITY,y=0;for(let w of o)if(w.type==="context-options")h=he(w.title),b=he(w.browserName),g=Number(w.version)||void 0,S=Math.min(S,Hn(w.monotonicTime,S));else if(w.type==="screencast-frame"){let v=he(w.file)??(he(w.sha1)?`resources/${he(w.sha1)}`:""),x={pageId:he(w.pageId)??"",file:v,sha1:v.slice(v.lastIndexOf("/")+1),timestamp:Hn(w.timestamp),width:Hn(w.width),height:Hn(w.height)};p.push(x),u.has(x.pageId)||u.set(x.pageId,{pageId:x.pageId})}else if(w.type==="event"&&w.class==="BrowserContext"&&w.method==="page"){let v=he(w.params?.pageId);v&&u.set(v,{...u.get(v),pageId:v,openedAt:Hn(w.time)})}else if(w.type==="event"&&w.class==="BrowserContext"&&w.method==="pageClosed"){let v=he(w.params?.pageId);v&&u.set(v,{...u.get(v),pageId:v,closedAt:Hn(w.time)})}else if(w.type==="frame-snapshot"){let v=w.snapshot;if(v?.pageId){let x=u.get(v.pageId)??{pageId:v.pageId};v.isMainFrame&&v.frameUrl&&(x.url=v.frameUrl),u.set(v.pageId,x)}}for(let w of r.values())S=Math.min(S,w.startTime),y=Math.max(y,w.endTime??w.startTime);for(let w of p)y=Math.max(y,w.timestamp);return Number.isFinite(S)||(S=0),{format:g,title:h,browserName:b,startTime:S,endTime:y,steps:d,calls:f,frames:p,requests:vx(e),pages:[...u.values()],resources:e.filter(w=>w.name.startsWith("resources/")).map(w=>w.name.slice(10))}}function vx(e){let t=[];for(let n of e.filter(r=>r.name.endsWith(".network")))for(let r of n.data.toString("utf8").split(`
|
|
423
|
+
`)){if(!r.trim())continue;let s;try{s=JSON.parse(r)}catch{continue}if(s.type!=="resource-snapshot"||!s.snapshot)continue;let o=s.snapshot,a=o.request,i=o.response,c=o._monotonicTime;t.push({pageId:he(o.pageref),method:he(a?.method)??"GET",url:he(a?.url)??"",status:Number.isFinite(i?.status)?i?.status:void 0,mimeType:he(i?.content?.mimeType),startedAt:Date.parse(he(o.startedDateTime)??"")||0,time:typeof o.time=="number"?o.time:void 0,timestamp:typeof c=="number"?c:void 0})}return t}import Yr from"node:fs";import{createHash as xx,randomBytes as Mg}from"node:crypto";import Ag from"node:fs";import bn from"node:path";var Eg="This run has no reviewable proposal identity. Run the scenario again to review from replay.",nl="The proposal does not belong to this replay.",_g=e=>e instanceof Error?e.message:String(e),Og=(e,t)=>`No pending proposal at ${bn.relative(e,t)}: it has been accepted, rejected or removed since this run.`;function Cg(e,t){let n=/ \(example \d+\)$/.exec(t.scenario),r=n?[t.scenario,t.scenario.slice(0,n.index)]:[t.scenario],s=t.proposalFile,o=i=>i.split(/[\\/]/).slice(-2).join("/"),a=bn.win32.isAbsolute(s)?i=>o(i)===o(s):i=>bn.resolve(i)===bn.resolve(e,s);return r.map(i=>xt(e,t.feature,i)).find(a)}function Pg(e,t,n){if(Ot(n)!==t.proposalRevision)return{available:!1,reason:"The proposal changed since this run. Open the latest run before reviewing it."};let r=i=>({available:!1,reason:i,rejectable:!0}),s;try{s=Pr(n)}catch(i){if(i instanceof $e)return r(`The proposal cannot be read: ${bn.relative(e,n)}: ${i.problem}`);throw i}let{feature:o,scenario:a}=s.cache;if(bn.resolve(xt(e,o,a))!==bn.resolve(n)||o!==t.feature||!(t.scenario===a||t.scenario===s.meta.recordedFor||t.scenario.startsWith(a+" (example ")))return{available:!1,reason:nl};try{if(!Ag.existsSync(bn.resolve(e,o)))return r(`STALE: ${o} no longer exists`);let i=ut(e,Ee(e),[bn.resolve(e,o)]),c=$t(e,s,i);if(c)return r(`STALE: ${c}`);let l=t.status==="red",d=s.meta.verified===!0&&!l,f=l?t.error??"This run replayed the proposal and it failed.":s.meta.proofError;return{available:!0,verified:d,...!d&&f?{proofError:f}:{},unbound:!s.meta.bound,diff:Nn(st(me(e,o,a)),s.cache),featureEdits:s.meta.featureEdits??[]}}catch(i){return r(_g(i))}}function Ig(e,t){if(!t.proposalFile||!t.proposalRevision)return{available:!1,reason:Eg};try{let n=Cg(e,{...t,proposalFile:t.proposalFile});return n?Ag.existsSync(n)?Pg(e,t,n):{available:!1,reason:Og(e,n)}:{available:!1,reason:nl}}catch(n){return{available:!1,reason:_g(n)}}}function Ng(e,t,n,r=!1){if(!t.proposalFile||!t.proposalRevision)throw new Error(Eg);let s=Cg(e,{...t,proposalFile:t.proposalFile});if(!s)throw new Error(nl);$o(s,()=>{let o=Pg(e,t,s);if(n==="reject"){if(!o.available&&!o.rejectable)throw new Error(o.reason);To(s)}else{if(!o.available)throw new Error(o.reason);if(!o.verified&&!r)throw new Error("Confirm that you want to accept a proposal without successful proof replay.");Ro(e,s)}},()=>{throw new Error(Og(e,s))})}import Sx from"node:http";import hr from"node:path";function jg(){return`<!DOCTYPE html>
|
|
401
424
|
<html lang="en">
|
|
402
425
|
<head>
|
|
403
426
|
<meta charset="utf-8">
|
|
@@ -484,7 +507,7 @@ ${e.prompt}`,e)),i.status==="error"&&!e.finished())throw new Error(`Cursor: ${i.
|
|
|
484
507
|
</head>
|
|
485
508
|
<body>
|
|
486
509
|
<header>
|
|
487
|
-
${
|
|
510
|
+
${ir(26)}
|
|
488
511
|
<div><div class="name" id="title">Saffron replay</div><div class="sub" id="subtitle"></div></div>
|
|
489
512
|
<span class="status" id="status"></span>
|
|
490
513
|
<label id="scenarioPicker" hidden>Scenario <select id="scenarioSelect" aria-label="Scenario"></select></label>
|
|
@@ -1119,9 +1142,9 @@ ${e.prompt}`,e)),i.status==="error"&&!e.finished())throw new Error(`Cursor: ${i.
|
|
|
1119
1142
|
})();
|
|
1120
1143
|
</script>
|
|
1121
1144
|
</body>
|
|
1122
|
-
</html>`}var Vn=class extends Error{},Vu="This trace is gone, or a later run replaced it (one that stopped before writing its report). Run the scenario again to replay it.",Zy=4;function Ja(e,t){let n=Jn.join(e,t.file);try{$r.accessSync(n,$r.constants.R_OK)}catch(s){let o=s.code;if(o==="ENOENT"||o==="ENOTDIR")return;throw s}if(!ht(Jn.join(e,".saffron","artifacts"),n))throw new Error(`${t.file} is not a file under .saffron/artifacts`);let r=$r.readFileSync(n);return t.sha256&&At(r)!==t.sha256?void 0:r}function Qy(){let e=To.resolve("playwright-core/package.json");return Jn.join(Jn.dirname(e),"lib","vite","traceViewer")}var ln={".html":"text/html; charset=utf-8",".js":"text/javascript; charset=utf-8",".css":"text/css; charset=utf-8",".json":"application/json; charset=utf-8",".svg":"image/svg+xml",".png":"image/png",".jpeg":"image/jpeg",".jpg":"image/jpeg",".ttf":"font/ttf",".webmanifest":"application/manifest+json",".zip":"application/zip"},Xy=new Set([".png",".jpeg",".jpg"]),Va={"Content-Security-Policy":"sandbox","X-Content-Type-Options":"nosniff"};function eb(e){let t=/<script>([\s\S]*?)<\/script>/.exec(e)[1];return["default-src 'self'",`script-src 'sha256-${Ky("sha256").update(t).digest("base64")}'`,"style-src 'self' 'unsafe-inline'","worker-src 'self'","connect-src 'self'","frame-src 'self'","object-src 'none'","base-uri 'none'","form-action 'none'","frame-ancestors 'none'"].join("; ")}async function Ju(e){let t=e.entries?[...e.entries]:[{scenario:e.scenario,traces:[{file:e.traceFile,data:e.traceData,label:e.label??"Execution",proof:e.proof,steps:e.scenario.steps,uniques:e.scenario.uniques},...(e.additionalTraces??[]).map(b=>({...b,proof:b.proof??!0}))]}],n=e.start??0;if(!t[n])throw new Error("No scenario to replay");let r=b=>{let y=Lr(b),S=Ha(y.map(x=>({name:x.name,get data(){return x.read()}})));return{zip:b,model:S,resources:new Map(y.filter(x=>x.name.includes("/")).map(x=>[x.name,x.read]))}},s=b=>{try{return b.data?b.data:!b.read&&!$r.existsSync(b.file)?new Vn(Vu):(b.read?b.read():$r.readFileSync(b.file))??new Vn(Vu)}catch(y){return y instanceof Vn?y:new Vn(`This trace cannot be read: ${y instanceof Error?y.message:String(y)}`)}},o=[];{let b=t[n],y=b.traces.map(s),S=b.traces.map((x,C)=>({t:x,data:y[C]})).filter(({data:x},C)=>C===0||Buffer.isBuffer(x));for(let[x,C]of b.traces.entries()){let $=y[x];x>0&&!Buffer.isBuffer($)&&o.push({file:C.file,reason:$.message})}t[n]={...b,traces:S.map(({t:x,data:C})=>({...x,data:Buffer.isBuffer(C)?C:void 0,read:Buffer.isBuffer(C)?void 0:()=>{throw C}}))}}let i=new Map,a=(b,y)=>{let S=`${b}:${y}`,x=i.get(S);if(x)i.delete(S);else{let C=s(t[b].traces[y]);if(!Buffer.isBuffer(C))throw C;x=r(C);let $=[...i.keys()].filter(k=>{let[R,_]=k.split(":").map(Number),v=t[R].traces[_];return R!==n&&(v.data!==void 0||v.checked===!0)});b!==n&&$.length>=Zy&&i.delete($[0])}return i.set(S,x),x},c=new Map,l=(b,y)=>{let S=t[b].scenario.screenshots?.find($=>$.file===y);if(!S)return;let x=`${b}:${y}`;if(c.has(x))return c.get(x);let C=mn(e.projectRoot,S);return(b===n||!S.sha256)&&c.set(x,C),C};try{a(n,0)}catch(b){if(t.length===1)throw b}for(let b of t[n].scenario.screenshots??[])l(n,b.file);let d=Qy(),u=Hu(),g={"Content-Security-Policy":eb(u)},f=qu(32).toString("hex"),p=qu(8).toString("hex"),m=t.map(b=>({feature:b.scenario.feature,scenario:b.scenario.scenario,status:b.scenario.status,browser:b.scenario.browser})),h=Yy.createServer((b,y)=>{let S=(x,C,$,k={})=>{y.writeHead(x,{"Content-Type":$,"Cache-Control":"no-store",...k}),y.end(C)};try{let x=b.headers.host??"";if(!/^(?:127\.0\.0\.1|localhost)(?::\d+)?$/i.test(x))return S(403,"Invalid host","text/plain");let C=new URL(b.url??"/",`http://${x}`),$=Number(C.searchParams.get("scenario")??n),k=Number.isInteger($)?t[$]:void 0,R=Number(C.searchParams.get("session")??"0"),_=k&&Number.isInteger(R)?k.traces[R]:void 0,v=()=>S(404,k?"No such trace session":"No such scenario","text/plain");if(C.pathname.startsWith("/api/review/")&&!e.viewOnly){if(b.method!=="POST")return S(405,"Use POST","text/plain");if(b.headers.origin!==`http://${x}`||b.headers["x-saffron-review"]!==f)return S(403,"Review must come from this replay page","text/plain");if(!k||!_)return v();let A=C.pathname.slice(12);if(A!=="accept"&&A!=="reject")return S(404,"Unknown decision","text/plain");try{return zu(e.projectRoot,k.scenario,A,b.headers["x-saffron-unverified"]==="yes"),S(200,JSON.stringify({decision:A}),ln[".json"])}catch(O){return S(409,JSON.stringify({error:O instanceof Error?O.message:String(O)}),ln[".json"])}}if(b.method!=="GET"&&b.method!=="HEAD")return S(405,"Use GET","text/plain");if(C.pathname==="/"||C.pathname==="/index.html")return S(200,u,ln[".html"],g);if(C.pathname==="/api/replay"){let A=k?$:n,O=_?R:0,P=t[A],E=P.traces[O],T={scenarios:m,scenarioIndex:A,sessions:P.traces.map(F=>F.label),session:O,proof:E.proof===!0,instance:p},M;try{M=a(A,O).model}catch(F){let z=F instanceof Vn?F.message:`This trace cannot be read: ${F instanceof Error?F.message:String(F)}`;return S(200,JSON.stringify({...T,scenario:P.scenario,unavailable:z}),ln[".json"])}let I=e.viewOnly?{review:{available:!1,reason:e.viewOnly}}:{review:Uu(e.projectRoot,P.scenario),reviewToken:f};return S(200,JSON.stringify({...T,scenario:{...P.scenario,steps:E.steps,uniques:E.uniques,traceSession:E.browserSession},trace:M,...I}),ln[".json"])}if(C.pathname.startsWith("/artifact/")){let A=C.searchParams.get("v");if(A!==null&&A!==p)return S(410,"This replay was restarted. Reload the page.","text/plain");if(!k||!_)return v();if(C.pathname==="/artifact/trace.zip")return S(200,a($,R).zip,ln[".zip"],Va);if(C.pathname.startsWith("/artifact/resource/")){let O=decodeURIComponent(C.pathname.slice(19)),P=a($,R).resources,E=(P.get(O)??(O.includes("/")?void 0:P.get(`resources/${O}`)))?.();if(!E)return S(404,"no such resource","text/plain");let T=Jn.extname(C.pathname).toLowerCase();return S(200,E,Xy.has(T)?ln[T]:"application/octet-stream",Va)}if(C.pathname.startsWith("/artifact/screenshot/")){let O=l($,decodeURIComponent(C.pathname.slice(21)));return O?S(200,O,ln[".jpg"],Va):S(404,"no such file","text/plain")}}if(C.pathname==="/trace/ping")return S(200,"ok","text/plain");if(C.pathname.startsWith("/trace/")){let A=C.pathname.slice(7)||"index.html",O=Jn.join(d,A);if(!ht(d,O))return S(404,"not found","text/plain");let P=Jn.extname(O).toLowerCase(),E=$r.readFileSync(O);return y.writeHead(200,{"Content-Type":ln[P]??"application/octet-stream","Service-Worker-Allowed":"/trace/"}),y.end(E)}S(404,"not found","text/plain")}catch{y.headersSent?y.destroy():S(400,"Invalid request","text/plain")}});return await new Promise((b,y)=>{h.once("error",y),h.listen(e.port??0,"127.0.0.1",()=>b())}),{url:`http://127.0.0.1:${h.address().port}/`,skipped:o,close:()=>new Promise(b=>h.close(()=>b()))}}import Wu from"node:fs";import Mo from"node:path";function Fo(e){return JSON.stringify([e.role??null,e.name??null,e.nameRegex??null,e.label??null,e.text??null,e.testId??null,e.placeholder??null,e.frame??null,e.role||e.name||e.nameRegex||e.label||e.text||e.testId||e.placeholder?null:e.fallbackSelectors??[]])}function Gu(e,t){let n=new Map,r=new Set,s=new Map,o=Math.min(e.steps.length,t.steps.length);for(let a=0;a<o;a++){if(e.steps[a].kind==="assertion"||t.steps[a].kind==="assertion"||e.steps[a].gherkin!==t.steps[a].gherkin)continue;let c=e.steps[a].actions,l=t.steps[a].actions;if(c.length===l.length)for(let d=0;d<c.length;d++){let u=c[d],g=l[d];if(u.action!==g.action||at.has(u.action)||!u.target||!g.target)continue;let f=Fo(u.target),p=JSON.stringify(g.target);s.has(f)&&s.get(f)!==p&&r.add(f),s.set(f,p),f!==Fo(g.target)&&n.set(f,{from:u.target,to:g.target})}}let i=[...n.entries()];return{changes:i.filter(([a])=>!r.has(a)).map(([,a])=>a),ambiguous:i.filter(([a])=>r.has(a)).map(([,a])=>a.from)}}function tb(e){let t=Mo.join(e,".saffron","cache");if(!Wu.existsSync(t))return[];let n=[];for(let r of Wu.readdirSync(t,{recursive:!0})){let s=String(r);s.endsWith(".json")&&n.push(Mo.join(t,s))}return n}function Ku(e,t,n,r){if(t.length===0)return[];let s=new Map,o=new Set;for(let a of t){let c=Fo(a.from),l=s.get(c);l&&JSON.stringify(l.to)!==JSON.stringify(a.to)&&o.add(c),s.set(c,a)}for(let a of o)s.delete(a);let i=[];for(let a of tb(e)){if(Mo.resolve(a)===Mo.resolve(n))continue;let c=jt(a);if(!c)continue;let l=[],d=!1;for(let u of c.steps){if(u.kind==="assertion")continue;let g=0;for(let f of u.actions){if(!f.target||at.has(f.action))continue;let p=s.get(Fo(f.target));p&&(g++,r||(f.target=structuredClone(p.to),d=!0))}g>0&&l.push({gherkin:u.gherkin,count:g})}l.length>0&&(d&&tr(a,c),i.push({file:a,scenario:c.scenario,feature:c.feature,steps:l}))}return i}function Bo(e){return e.role?`${e.role} "${e.name??e.nameRegex??""}"`:e.label?`label "${e.label}"`:e.text?`text "${e.text}"`:e.testId?`testId "${e.testId}"`:(e.fallbackSelectors??[]).join(",")||"(empty target)"}import Yu from"node:fs";import Lo from"node:path";function Zu(e,t,n,r,s){let o=Ze(Lo.join(e,t),e,s).find(c=>c.name===n);if(!o)return`scenario "${n}" is no longer in ${t}`;let i=o.steps.map(c=>c.text);if(i.length!==r.length)return`the scenario has ${i.length} steps now and had ${r.length} when this was recorded`;let a=i.findIndex((c,l)=>c!==r[l]);return a<0?void 0:`step ${a+1} now reads "${i[a]}" and was recorded as "${r[a]}"`}function Qu(e,t,n,r,s,o){let i={applied:[],skipped:[],appliedIndices:[]},a=r.filter(f=>f.text.trim()!==""?!0:(i.skipped.push({index:f.index,reason:"the edit has no step text"}),!1)),c=Ze(Lo.join(e,t),e,s).find(f=>f.name===n);if(!c){for(let f of a)i.skipped.push({index:f.index,reason:`scenario "${n}" not found in ${t}`});return i}let l=new Map;for(let f of a){let p=c.steps[f.index]?.source;if(!p||p.fromBackground)continue;let m=`${p.file}:${p.line}`;l.set(m,(l.get(m)??new Set).add(f.text))}let d=We(c),u=new Map,g=new Set;for(let f of a){let p=c.steps[f.index];if(!p?.source){i.skipped.push({index:f.index,reason:`no step at index ${f.index}`});continue}let m=[...ei([f.text,...Cr([f.text])])].filter(v=>!d.has(v));if(m.length>0){i.skipped.push({index:f.index,reason:`it would make the scenario name ${m.map(v=>`{env:${v}}`).join(", ")}, which it does not reference now; a recording can only use the environment variables its scenario names, so edit the feature file by hand if you mean it`});continue}if(kt(f.text)!==kt(p.text)){i.skipped.push({index:f.index,reason:'it would change which browser session the step runs in (its As "..."); edit the feature file by hand if you mean it'});continue}if(o&&o[f.index]!==p.text){i.skipped.push({index:f.index,reason:`step ${f.index+1} now reads "${p.text}", not the "${o[f.index]??"(nothing)"}" this edit was written for`});continue}let{file:h,line:w,fromStepSet:b,fromBackground:y}=p.source;if(y){i.skipped.push({index:f.index,reason:`"${p.text}" is a Background step shared across scenarios; edit it manually`});continue}let S=`${h}:${w}`,x=l.get(S);if(x.size>1){i.skipped.push({index:f.index,reason:`${S}${b?` (StepSet "${b}")`:""} is reached by several steps and the edits disagree: ${[...x].map(v=>`"${v}"`).join(" vs ")}. Decide the wording in the definition by hand`});continue}let C=c.steps.findIndex((v,A)=>v.source?.file===h&&v.source.line===w&&v.text!==f.text&&!a.some(O=>O.index===A&&O.text===f.text));if(C>=0){i.skipped.push({index:f.index,reason:`${S} is also used at step ${C+1}, which has no agreeing edit; edit the shared definition by hand`});continue}if(g.has(S)){i.appliedIndices.push(f.index);continue}let $=u.get(h);$||($=Yu.readFileSync(Lo.join(e,h),"utf8").split(`
|
|
1123
|
-
`),
|
|
1124
|
-
`));return
|
|
1145
|
+
</html>`}var gr=class extends Error{},Dg="This trace is gone, or a later run replaced it (one that stopped before writing its report). Run the scenario again to replay it.",$x=4;function sl(e,t){let n=hr.join(e,t.file);try{Yr.accessSync(n,Yr.constants.R_OK)}catch(s){let o=s.code;if(o==="ENOENT"||o==="ENOTDIR")return;throw s}if(!_t(hr.join(e,".saffron","artifacts"),n))throw new Error(`${t.file} is not a file under .saffron/artifacts`);let r=Yr.readFileSync(n);return t.sha256&&zt(r)!==t.sha256?void 0:r}function kx(){let e=hi.resolve("playwright-core/package.json");return hr.join(hr.dirname(e),"lib","vite","traceViewer")}var vn={".html":"text/html; charset=utf-8",".js":"text/javascript; charset=utf-8",".css":"text/css; charset=utf-8",".json":"application/json; charset=utf-8",".svg":"image/svg+xml",".png":"image/png",".jpeg":"image/jpeg",".jpg":"image/jpeg",".ttf":"font/ttf",".webmanifest":"application/manifest+json",".zip":"application/zip"},Rx=new Set([".png",".jpeg",".jpg"]),rl={"Content-Security-Policy":"sandbox","X-Content-Type-Options":"nosniff"};function Tx(e){let t=/<script>([\s\S]*?)<\/script>/.exec(e)[1];return["default-src 'self'",`script-src 'sha256-${xx("sha256").update(t).digest("base64")}'`,"style-src 'self' 'unsafe-inline'","worker-src 'self'","connect-src 'self'","frame-src 'self'","object-src 'none'","base-uri 'none'","form-action 'none'","frame-ancestors 'none'"].join("; ")}async function Fg(e){let t=e.entries?[...e.entries]:[{scenario:e.scenario,traces:[{file:e.traceFile,data:e.traceData,label:e.label??"Execution",proof:e.proof,steps:e.scenario.steps,uniques:e.scenario.uniques},...(e.additionalTraces??[]).map(y=>({...y,proof:y.proof??!0}))]}],n=e.start??0;if(!t[n])throw new Error("No scenario to replay");let r=y=>{let w=ds(y),v=tl(w.map(x=>({name:x.name,get data(){return x.read()}})));return{zip:y,model:v,resources:new Map(w.filter(x=>x.name.includes("/")).map(x=>[x.name,x.read]))}},s=y=>{try{return y.data?y.data:!y.read&&!Yr.existsSync(y.file)?new gr(Dg):(y.read?y.read():Yr.readFileSync(y.file))??new gr(Dg)}catch(w){return w instanceof gr?w:new gr(`This trace cannot be read: ${w instanceof Error?w.message:String(w)}`)}},o=[];{let y=t[n],w=y.traces.map(s),v=y.traces.map((x,$)=>({t:x,data:w[$]})).filter(({data:x},$)=>$===0||Buffer.isBuffer(x));for(let[x,$]of y.traces.entries()){let E=w[x];x>0&&!Buffer.isBuffer(E)&&o.push({file:$.file,reason:E.message})}t[n]={...y,traces:v.map(({t:x,data:$})=>({...x,data:Buffer.isBuffer($)?$:void 0,read:Buffer.isBuffer($)?void 0:()=>{throw $}}))}}let a=new Map,i=(y,w)=>{let v=`${y}:${w}`,x=a.get(v);if(x)a.delete(v);else{let $=s(t[y].traces[w]);if(!Buffer.isBuffer($))throw $;x=r($);let E=[...a.keys()].filter(R=>{let[k,C]=R.split(":").map(Number),P=t[k].traces[C];return k!==n&&(P.data!==void 0||P.checked===!0)});y!==n&&E.length>=$x&&a.delete(E[0])}return a.set(v,x),x},c=new Map,l=(y,w)=>{let v=t[y].scenario.screenshots?.find(E=>E.file===w);if(!v)return;let x=`${y}:${w}`;if(c.has(x))return c.get(x);let $=Pn(e.projectRoot,v);return(y===n||!v.sha256)&&c.set(x,$),$};try{i(n,0)}catch(y){if(t.length===1)throw y}for(let y of t[n].scenario.screenshots??[])l(n,y.file);let d=kx(),f=jg(),p={"Content-Security-Policy":Tx(f)},u=Mg(32).toString("hex"),h=Mg(8).toString("hex"),b=t.map(y=>({feature:y.scenario.feature,scenario:y.scenario.scenario,status:y.scenario.status,browser:y.scenario.browser})),g=Sx.createServer((y,w)=>{let v=(x,$,E,R={})=>{w.writeHead(x,{"Content-Type":E,"Cache-Control":"no-store",...R}),w.end($)};try{let x=y.headers.host??"";if(!/^(?:127\.0\.0\.1|localhost)(?::\d+)?$/i.test(x))return v(403,"Invalid host","text/plain");let $=new URL(y.url??"/",`http://${x}`),E=Number($.searchParams.get("scenario")??n),R=Number.isInteger(E)?t[E]:void 0,k=Number($.searchParams.get("session")??"0"),C=R&&Number.isInteger(k)?R.traces[k]:void 0,P=()=>v(404,R?"No such trace session":"No such scenario","text/plain");if($.pathname.startsWith("/api/review/")&&!e.viewOnly){if(y.method!=="POST")return v(405,"Use POST","text/plain");if(y.headers.origin!==`http://${x}`||y.headers["x-saffron-review"]!==u)return v(403,"Review must come from this replay page","text/plain");if(!R||!C)return P();let m=$.pathname.slice(12);if(m!=="accept"&&m!=="reject")return v(404,"Unknown decision","text/plain");try{return Ng(e.projectRoot,R.scenario,m,y.headers["x-saffron-unverified"]==="yes"),v(200,JSON.stringify({decision:m}),vn[".json"])}catch(A){return v(409,JSON.stringify({error:A instanceof Error?A.message:String(A)}),vn[".json"])}}if(y.method!=="GET"&&y.method!=="HEAD")return v(405,"Use GET","text/plain");if($.pathname==="/"||$.pathname==="/index.html")return v(200,f,vn[".html"],p);if($.pathname==="/api/replay"){let m=R?E:n,A=C?k:0,O=t[m],T=O.traces[A],_={scenarios:b,scenarioIndex:m,sessions:O.traces.map(I=>I.label),session:A,proof:T.proof===!0,instance:h},N;try{N=i(m,A).model}catch(I){let L=I instanceof gr?I.message:`This trace cannot be read: ${I instanceof Error?I.message:String(I)}`;return v(200,JSON.stringify({..._,scenario:O.scenario,unavailable:L}),vn[".json"])}let F=e.viewOnly?{review:{available:!1,reason:e.viewOnly}}:{review:Ig(e.projectRoot,O.scenario),reviewToken:u};return v(200,JSON.stringify({..._,scenario:{...O.scenario,steps:T.steps,uniques:T.uniques,traceSession:T.browserSession},trace:N,...F}),vn[".json"])}if($.pathname.startsWith("/artifact/")){let m=$.searchParams.get("v");if(m!==null&&m!==h)return v(410,"This replay was restarted. Reload the page.","text/plain");if(!R||!C)return P();if($.pathname==="/artifact/trace.zip")return v(200,i(E,k).zip,vn[".zip"],rl);if($.pathname.startsWith("/artifact/resource/")){let A=decodeURIComponent($.pathname.slice(19)),O=i(E,k).resources,T=(O.get(A)??(A.includes("/")?void 0:O.get(`resources/${A}`)))?.();if(!T)return v(404,"no such resource","text/plain");let _=hr.extname($.pathname).toLowerCase();return v(200,T,Rx.has(_)?vn[_]:"application/octet-stream",rl)}if($.pathname.startsWith("/artifact/screenshot/")){let A=l(E,decodeURIComponent($.pathname.slice(21)));return A?v(200,A,vn[".jpg"],rl):v(404,"no such file","text/plain")}}if($.pathname==="/trace/ping")return v(200,"ok","text/plain");if($.pathname.startsWith("/trace/")){let m=$.pathname.slice(7)||"index.html",A=hr.join(d,m);if(!_t(d,A))return v(404,"not found","text/plain");let O=hr.extname(A).toLowerCase(),T=Yr.readFileSync(A);return w.writeHead(200,{"Content-Type":vn[O]??"application/octet-stream","Service-Worker-Allowed":"/trace/"}),w.end(T)}v(404,"not found","text/plain")}catch{w.headersSent?w.destroy():v(400,"Invalid request","text/plain")}});return await new Promise((y,w)=>{g.once("error",w),g.listen(e.port??0,"127.0.0.1",()=>y())}),{url:`http://127.0.0.1:${g.address().port}/`,skipped:o,close:()=>new Promise(y=>g.close(()=>y()))}}import Lg from"node:fs";import Ai from"node:path";function Ei(e){return JSON.stringify([e.role??null,e.name??null,e.nameRegex??null,e.label??null,e.text??null,e.testId??null,e.placeholder??null,e.frame??null,e.role||e.name||e.nameRegex||e.label||e.text||e.testId||e.placeholder?null:e.fallbackSelectors??[]])}function Bg(e,t){let n=new Map,r=new Set,s=new Map,o=Math.min(e.steps.length,t.steps.length);for(let i=0;i<o;i++){if(e.steps[i].kind==="assertion"||t.steps[i].kind==="assertion"||e.steps[i].gherkin!==t.steps[i].gherkin)continue;let c=e.steps[i].actions,l=t.steps[i].actions;if(c.length===l.length)for(let d=0;d<c.length;d++){let f=c[d],p=l[d];if(f.action!==p.action||Se.has(f.action)||!f.target||!p.target)continue;let u=Ei(f.target),h=JSON.stringify(p.target);s.has(u)&&s.get(u)!==h&&r.add(u),s.set(u,h),u!==Ei(p.target)&&n.set(u,{from:f.target,to:p.target})}}let a=[...n.entries()];return{changes:a.filter(([i])=>!r.has(i)).map(([,i])=>i),ambiguous:a.filter(([i])=>r.has(i)).map(([,i])=>i.from)}}function Ax(e){let t=Ai.join(e,".saffron","cache");if(!Lg.existsSync(t))return[];let n=[];for(let r of Lg.readdirSync(t,{recursive:!0})){let s=String(r);s.endsWith(".json")&&n.push(Ai.join(t,s))}return n}function Ug(e,t,n,r){if(t.length===0)return[];let s=new Map,o=new Set,a=c=>new Set(JSON.stringify(c).match(/<[^<>"]+>/g)??[]);for(let c of t){let l=a(c.from);if([...a(c.to)].some(p=>!l.has(p)))continue;let d=Ei(c.from),f=s.get(d);f&&JSON.stringify(f.to)!==JSON.stringify(c.to)&&o.add(d),s.set(d,c)}for(let c of o)s.delete(c);let i=[];for(let c of Ax(e)){if(Ai.resolve(c)===Ai.resolve(n))continue;let l=Jt(c);if(!l)continue;let d=[],f=!1;for(let p of l.steps){if(p.kind==="assertion")continue;let u=0;for(let h of p.actions){if(!h.target||Se.has(h.action))continue;let b=s.get(Ei(h.target));b&&(u++,r||(h.target=structuredClone(b.to),f=!0))}u>0&&d.push({gherkin:p.gherkin,count:u})}d.length>0&&(f&&Ar(c,l),i.push({file:c,scenario:l.scenario,feature:l.feature,steps:d}))}return i}function _i(e){return e.role?`${e.role} "${e.name??e.nameRegex??""}"`:e.label?`label "${e.label}"`:e.text?`text "${e.text}"`:e.testId?`testId "${e.testId}"`:(e.fallbackSelectors??[]).join(",")||"(empty target)"}import zg from"node:fs";import Oi from"node:path";function Hg(e,t,n,r,s){let o=ft(Oi.join(e,t),e,s).find(c=>c.name===n);if(!o)return`scenario "${n}" is no longer in ${t}`;let a=o.steps.map(c=>c.text);if(a.length!==r.length)return`the scenario has ${a.length} steps now and had ${r.length} when this was recorded`;let i=a.findIndex((c,l)=>c!==r[l]);return i<0?void 0:`step ${i+1} now reads "${a[i]}" and was recorded as "${r[i]}"`}function qg(e,t,n,r,s,o){let a={applied:[],skipped:[],appliedIndices:[]},i=r.filter(u=>u.text.trim()!==""?!0:(a.skipped.push({index:u.index,reason:"the edit has no step text"}),!1)),c=ft(Oi.join(e,t),e,s).find(u=>u.name===n);if(!c){for(let u of i)a.skipped.push({index:u.index,reason:`scenario "${n}" not found in ${t}`});return a}let l=new Map;for(let u of i){let h=c.steps[u.index]?.source;if(!h||h.fromBackground)continue;let b=`${h.file}:${h.line}`;l.set(b,(l.get(b)??new Set).add(u.text))}let d=tt(c),f=new Map,p=new Set;for(let u of i){let h=c.steps[u.index];if(!h?.source){a.skipped.push({index:u.index,reason:`no step at index ${u.index}`});continue}let b=[...Ji([u.text,...es([u.text])])].filter(P=>!d.has(P));if(b.length>0){a.skipped.push({index:u.index,reason:`it would make the scenario name ${b.map(P=>`{env:${P}}`).join(", ")}, which it does not reference now; a recording can only use the environment variables its scenario names, so edit the feature file by hand if you mean it`});continue}if(Lt(u.text)!==Lt(h.text)){a.skipped.push({index:u.index,reason:'it would change which browser session the step runs in (its As "..."); edit the feature file by hand if you mean it'});continue}if(o&&o[u.index]!==h.text){a.skipped.push({index:u.index,reason:`step ${u.index+1} now reads "${h.text}", not the "${o[u.index]??"(nothing)"}" this edit was written for`});continue}let{file:g,line:S,fromStepSet:y,fromBackground:w}=h.source;if(w){a.skipped.push({index:u.index,reason:`"${h.text}" is a Background step shared across scenarios; edit it manually`});continue}let v=`${g}:${S}`,x=l.get(v);if(x.size>1){a.skipped.push({index:u.index,reason:`${v}${y?` (StepSet "${y}")`:""} is reached by several steps and the edits disagree: ${[...x].map(P=>`"${P}"`).join(" vs ")}. Decide the wording in the definition by hand`});continue}let $=c.steps.findIndex((P,m)=>P.source?.file===g&&P.source.line===S&&P.text!==u.text&&!i.some(A=>A.index===m&&A.text===u.text));if($>=0){a.skipped.push({index:u.index,reason:`${v} is also used at step ${$+1}, which has no agreeing edit; edit the shared definition by hand`});continue}if(p.has(v)){a.appliedIndices.push(u.index);continue}let E=f.get(g);E||(E=zg.readFileSync(Oi.join(e,g),"utf8").split(`
|
|
1146
|
+
`),f.set(g,E));let R=E[S-1],k=R?.match(/^(\s*)(\S+)\s+(.*)$/);if(!k||k[3]!==h.text){a.skipped.push({index:u.index,reason:`${g}:${S} no longer matches the recorded step text`});continue}let C=`${k[1]}${k[2]} ${u.text}`;E[S-1]=C,p.add(v),a.appliedIndices.push(u.index),a.applied.push({file:g,line:S,from:R.trim(),to:C.trim(),fromStepSet:y})}for(let[u,h]of f)a.applied.some(b=>b.file===u)&&zg.writeFileSync(Oi.join(e,u),h.join(`
|
|
1147
|
+
`));return a}import{spawn as Ex}from"node:child_process";function ol(e,t){if(e==null)return[];let n=Array.isArray(e)?e:[e];for(let r of n)if(typeof r!="string"||r.trim()==="")throw new Error(`"${t}" in saffron.config.json must be a command, or a list of commands, e.g. "${t}": "npm run seed"`);return n}function _x(e,t,n){let r=Date.now();return new Promise(s=>{let o=process.platform!=="win32",a=Ex(t,{cwd:n.cwd,shell:!0,detached:o,env:{...process.env,...n.env},stdio:["ignore",process.stderr,process.stderr]}),i=!1,c=!1,l,d=()=>{try{o&&a.pid?process.kill(-a.pid,"SIGKILL"):a.kill("SIGKILL")}catch{}},f=setTimeout(()=>{i=!0,d()},n.timeoutMs),p=()=>{c=!0,d()};n.signal?.addEventListener("abort",p,{once:!0});let u=h=>{clearTimeout(f),n.signal?.removeEventListener("abort",p),s({phase:e,command:t,exitCode:h,durationMs:Date.now()-r,...i?{timedOut:i}:{},...c?{cancelled:c}:{},...l?{signal:l}:{}})};a.on("error",()=>u(null)),a.on("exit",(h,b)=>{b&&!i&&!c&&(l=b),u(i||c?null:h)})})}var Ci=e=>e.exitCode!==0;async function il(e,t,n){let r=[];for(let s of t){if(n.signal?.aborted)break;console.error(`saffron ${e}: ${s}`);let o=await _x(e,s,n);if(r.push(o),o.cancelled||Ci(o)&&(console.error(`saffron ${e} failed: ${al(o,n.timeoutMs)}`),e==="setup"))break}return r}function al(e,t){return e.cancelled?`"${e.command}" was interrupted`:e.timedOut?`"${e.command}" was stopped after ${Math.round(t/1e3)}s (hookTimeoutMs)`:e.signal?`"${e.command}" was killed by ${e.signal}`:e.exitCode===null?`"${e.command}" could not be started`:`"${e.command}" exited with code ${e.exitCode}`}var Ox=`
|
|
1125
1148
|
.wrap { max-width: 1180px; }
|
|
1126
1149
|
.grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(340px, 1fr)); gap: 0 14px; align-items: start; }
|
|
1127
1150
|
.panel { min-width: 0; }
|
|
@@ -1163,42 +1186,42 @@ ${e.prompt}`,e)),i.status==="error"&&!e.finished())throw new Error(`Cursor: ${i.
|
|
|
1163
1186
|
details.more summary { padding: 6px 0 0; font-family: var(--mono); font-size: 10.5px; color: var(--muted); }
|
|
1164
1187
|
details.more summary:hover { background: none; color: var(--text); }
|
|
1165
1188
|
@media (max-width: 560px) { .wrap { padding: 14px 12px 40px; } .grid { grid-template-columns: 1fr; } .kpis { grid-template-columns: repeat(2, 1fr); } }
|
|
1166
|
-
`,
|
|
1167
|
-
${
|
|
1168
|
-
${
|
|
1169
|
-
${
|
|
1170
|
-
${
|
|
1171
|
-
${
|
|
1172
|
-
${
|
|
1173
|
-
${
|
|
1174
|
-
${
|
|
1175
|
-
</section>`,d=`<div class="panel"><div class="panel-title">suite health \xB7 each scenario's latest result</div>${
|
|
1176
|
-
${
|
|
1177
|
-
${
|
|
1178
|
-
</div>`,
|
|
1189
|
+
`,ae=e=>String(Number(e)),cl=e=>B(Qe(Number(e))),mr=(e,t)=>`${ae(e)} ${t}${Number(e)===1?"":"s"}`,ll=e=>new Date(e).toLocaleString("en-GB",{day:"2-digit",month:"short",year:"numeric",hour:"2-digit",minute:"2-digit"}),dl=e=>new Date(e).toLocaleString("en-GB",{day:"2-digit",month:"short",hour:"2-digit",minute:"2-digit"});function Us(e,t=""){let n=e.name??e.scenario;return`<div class="row-main"><div class="scn" data-f="${B(e.feature)}" data-s="${B(n)}" title="${B(`${e.feature} \u203A ${e.scenario}`)}">${B(e.scenario)}</div><div class="feat">${B(e.feature)}${e.browser?` \xB7 ${B(e.browser)}`:""}</div>${t}</div>`}function xn(e,t,n,r,s,o=""){return`<div class="panel${o?` accent-${o}`:""}"><div class="panel-head"><div class="panel-title${n?` ${n}`:""}">${B(e)}</div>${t===void 0?"":`<span class="count${t>0&&n?` ${n}`:""}">${ae(t)}</span>`}</div>${r||`<div class="empty">${B(s)}</div>`}</div>`}function Vg(e){let t=e.reduce((n,[r])=>n+r,0)||1;return`<div class="stack">${e.filter(([n])=>n>0).map(([n,r,s])=>`<span style="width:${(n/t*100).toFixed(2)}%;background:${s??`var(${r})`}"></span>`).join("")}</div>`}function Jg(e,t,n,r){if(e.length===0)return'<div class="empty">No runs yet.</div>';let s=Math.max(1,...e.map(t)),o=10,a=e.map((i,c)=>{let l=Math.max(2,t(i)/s*62);return`<rect x="${c*o+1.5}" y="${(64-l).toFixed(1)}" width="${o-3}" height="${l.toFixed(1)}" rx="1.5" fill="var(${r(i)})"><title>${B(n(i))}</title></rect>`}).join("");return`<svg class="bars" viewBox="0 0 ${e.length*o} 64" preserveAspectRatio="none" aria-hidden="true">${a}</svg><div class="axis"><span>${B(dl(e[0].startedAt))}</span><span>${B(dl(e.at(-1).startedAt))}</span></div>`}var zs=e=>e.length?`<ul class="rows">${e.join("")}</ul>`:"";function Wg(e,t){let n=e.suite,r=n.green+n.yellow+n.unverified+n.red,s=r===0?void 0:Math.round((n.green+n.yellow)/r*100),o=x=>x>0?` \xB7 ${ae(x)} unverified`:"",a=n.red,i=e.lastRun,c=s===void 0?"":s>=95?"green":s>=80?"gold":"red",l=`<section class="kpis">
|
|
1190
|
+
${ve("tests",ae(n.tests),`${mr(n.scenarios,"scenario")} \xB7 ${mr(n.features,"feature")}`)}
|
|
1191
|
+
${ve("passing",s===void 0?"\u2013":`${s}<span class="unit">%</span>`,`${ae(n.green+n.yellow)} of ${ae(r)} \xB7 latest results${o(n.unverified)}`,c,"",Fr(e.trend.map(x=>x.passRate),"var(--green)"))}
|
|
1192
|
+
${ve("failing",ae(a),a>0?"\u25BC red the last time they ran":"all clear",a>0?"red":"",a>0?"red":"green")}
|
|
1193
|
+
${ve("flaky",ae(e.flaky.length),e.flaky.length>0?"pass and fail by turns on one base URL":"none in 20 runs",e.flaky.length>0?"gold":"",e.flaky.length>0?"gold":"green")}
|
|
1194
|
+
${ve("never run",ae(e.neverRun.length),e.neverRun.length>0?"in no recorded run":"every scenario has run",e.neverRun.length>0?"gold":"",e.neverRun.length>0?"gold":"green")}
|
|
1195
|
+
${ve("last run",i?cl(i.durationMs):"\u2013",i?`${mr(i.ran,"test")} \xB7 ${ae(i.passRate)}% passed${o(i.unverified)}`:"no run yet","","",Fr(e.trend.map(x=>x.durationMs),"var(--muted)"))}
|
|
1196
|
+
${ve("zero-ai replay",i?`${ae(i.replayRate)}<span class="unit">%</span>`:"\u2013","replayed from recordings, last run",i&&i.replayRate>=90?"green":"")}
|
|
1197
|
+
${ve("recorded",n.scenarios?`${Math.round(n.recorded/n.scenarios*100)}<span class="unit">%</span>`:"\u2013",n.scenarios-n.recorded>0?`${ae(n.scenarios-n.recorded)} still need the agent`:"every scenario has a current recording",n.recorded===n.scenarios?"green":"")}
|
|
1198
|
+
</section>`,d=`<div class="panel"><div class="panel-title">suite health \xB7 each scenario's latest result</div>${Vg([[n.green,"--green"],[n.yellow,"--gold"],[n.unverified,"--gold","repeating-linear-gradient(135deg, var(--gold) 0 4px, var(--gold-soft) 4px 8px)"],[n.red,"--red"],[n.neverRun,"--faint"]])}<div class="legend"><span><i class="dot green"></i>${ae(n.green)} passed</span><span><i class="dot gold"></i>${ae(n.yellow)} healed</span>${n.unverified>0?`<span><i class="dot unverified"></i>${ae(n.unverified)} healed, unverified</span>`:""}<span><i class="dot red"></i>${ae(n.red)} failed</span><span><i class="dot faint"></i>${ae(n.neverRun)} never run</span></div></div>`,f=`<div class="grid">
|
|
1199
|
+
${xn(`pass rate \xB7 last ${mr(e.trend.length,"run")}`,void 0,"",Jg(e.trend,x=>x.passRate,x=>`${ll(x.startedAt)}: ${ae(x.passRate)}% of ${ae(x.tests)} passed, ${ae(x.red)} failed`,x=>x.red>0?"--red":"--green"),"")}
|
|
1200
|
+
${xn(`execution time \xB7 last ${mr(e.trend.length,"run")}`,void 0,"",Jg(e.trend,x=>x.durationMs,x=>`${ll(x.startedAt)}: ${Qe(Number(x.durationMs))} for ${mr(x.tests,"test")}`,()=>"--muted"),"")}
|
|
1201
|
+
</div>`,p=zs(e.recentFailures.map(x=>`<li><i class="dot ${x.stillFailing?"red":"green"}"></i>${Us(x,x.error?`<div class="err" title="${B(x.error)}">${B(x.error)}</div>`:"")}<div class="row-side">${x.stillFailing?`<span class="red">${ae(x.streak)} run${Number(x.streak)===1?"":"s"} in a row</span>`:'<span class="green">passed since</span>'}<br>${B(dl(x.at))}</div></li>`)),u=zs(e.flaky.map(x=>`<li><i class="dot gold"></i>${Us(x)}<div class="row-side">flipped ${ae(x.flips)}\xD7 in ${ae(x.runs)} runs<br>${ae(x.reds)} red \xB7 last <span class="${x.last==="red"?"red":"green"}">${x.last==="red"?"failed":"passed"}</span></div></li>`)),h=zs(e.healing.map(x=>`<li><i class="dot gold"></i>${Us(x)}<div class="row-side">healed ${ae(x.heals)}\xD7${x.unverified>0?` <span class="gold">(${ae(x.unverified)} unverified)</span>`:""}<br>in ${ae(x.runs)} runs</div></li>`)),b=Math.max(1,...e.slowest.map(x=>x.avgMs)),g=zs(e.slowest.map(x=>`<li>${Us(x,`<div class="meter" style="width:${(x.avgMs/b*100).toFixed(1)}%"></div>`)}<div class="row-side">avg ${cl(x.avgMs)}<br>last ${cl(x.lastMs)}</div></li>`)),S=e.tags.length?`<table class="tags">${e.tags.map(x=>{let $=x.scenarios-x.neverRun,E=x.red>0?`<span style="color:var(--red)">${ae(x.red)} red</span>`:$===0?"never run":`${Math.round((x.green+x.yellow)/$*100)}%`;return`<tr><td class="tagname">${B(x.tag)}</td><td class="num">${ae(x.scenarios)}</td><td class="stackcell">${Vg([[x.green,"--green"],[x.yellow,"--gold"],[x.unverified,"--gold","repeating-linear-gradient(135deg, var(--gold) 0 4px, var(--gold-soft) 4px 8px)"],[x.red,"--red"],[x.neverRun,"--faint"]])}</td><td class="num">${E}</td></tr>`}).join("")}</table>`:"",y=(x,$)=>zs(x.map(E=>`<li><i class="dot ${$}"></i>${Us(E)}</li>`)),w=e.notInLastRun.length?`<details class="more"><summary>left out by tags or paths \xB7 show ${ae(e.notInLastRun.length)}</summary>${y(e.notInLastRun,"idle")}</details>`:"",v=e.historyRuns===0?"no runs recorded yet":`${mr(e.historyRuns,"run")} in .saffron/history.jsonl`;return`<!doctype html>
|
|
1179
1202
|
<html lang="en">
|
|
1180
1203
|
<head>
|
|
1181
1204
|
<meta charset="utf-8"/>
|
|
1182
1205
|
<meta name="viewport" content="width=device-width, initial-scale=1"/>
|
|
1183
1206
|
<title>Saffron dashboard</title>
|
|
1184
|
-
${
|
|
1207
|
+
${$s}
|
|
1185
1208
|
<style>
|
|
1186
|
-
${
|
|
1209
|
+
${ks}${Ox}</style>
|
|
1187
1210
|
</head>
|
|
1188
1211
|
<body>
|
|
1189
1212
|
<div class="topline"></div>
|
|
1190
1213
|
<div class="wrap">
|
|
1191
1214
|
<header class="top">
|
|
1192
1215
|
<div class="brand">
|
|
1193
|
-
${
|
|
1216
|
+
${ir(38)}
|
|
1194
1217
|
<div>
|
|
1195
1218
|
<div class="brand-name">saffron</div>
|
|
1196
1219
|
<div class="brand-sub">suite quality</div>
|
|
1197
1220
|
</div>
|
|
1198
1221
|
</div>
|
|
1199
1222
|
<div class="run-meta">
|
|
1200
|
-
<span>${B(
|
|
1201
|
-
${
|
|
1223
|
+
<span>${B(v)}</span>
|
|
1224
|
+
${i?`<span>\xB7</span><span>last run ${B(ll(i.startedAt))}</span>`:""}
|
|
1202
1225
|
</div>
|
|
1203
1226
|
</header>
|
|
1204
1227
|
|
|
@@ -1206,24 +1229,24 @@ ${Qr}${sb}</style>
|
|
|
1206
1229
|
${d}
|
|
1207
1230
|
|
|
1208
1231
|
<div class="section-head"><span class="section-title">trends</span></div>
|
|
1209
|
-
${
|
|
1232
|
+
${f}
|
|
1210
1233
|
|
|
1211
1234
|
<div class="section-head"><span class="section-title">stability</span></div>
|
|
1212
1235
|
<div class="grid">
|
|
1213
|
-
${
|
|
1214
|
-
${
|
|
1215
|
-
${
|
|
1216
|
-
${
|
|
1236
|
+
${xn("recent failures \xB7 last 10 runs",e.recentFailures.length,"red",p,"Nothing failed in the last 10 runs.",a>0?"red":"")}
|
|
1237
|
+
${xn("flaky \xB7 last 20 runs",e.flaky.length,"gold",u,"No scenario passed and failed by turns.",e.flaky.length>0?"gold":"")}
|
|
1238
|
+
${xn("healed again and again",e.healing.length,"gold",h?`<div class="note">The page keeps changing under these: review the heals, or fix the step.</div>${h}`:"","No scenario needed the agent twice in the last 20 runs.")}
|
|
1239
|
+
${xn("slowest \xB7 average over 20 runs",void 0,"",g,"No timings yet.")}
|
|
1217
1240
|
</div>
|
|
1218
1241
|
|
|
1219
1242
|
<div class="section-head"><span class="section-title">coverage</span></div>
|
|
1220
1243
|
<div class="grid">
|
|
1221
|
-
${
|
|
1222
|
-
${
|
|
1223
|
-
${
|
|
1244
|
+
${xn("tags \xB7 latest results",e.tags.length,"",S,"No tags in the feature files.")}
|
|
1245
|
+
${xn("never run",e.neverRun.length,"gold",y(e.neverRun,"faint"),"Every scenario has run at least once.")}
|
|
1246
|
+
${xn("not in the last run",e.notInLastRun.length,"",w,"The last run ran every scenario that has run before.")}
|
|
1224
1247
|
</div>
|
|
1225
1248
|
|
|
1226
|
-
<footer>${
|
|
1249
|
+
<footer>${Ss(11)} generated by saffron v${B(t)}</footer>
|
|
1227
1250
|
</div>
|
|
1228
1251
|
<script>
|
|
1229
1252
|
if (typeof window.saffronOpen === "function") document.body.classList.add("linked");
|
|
@@ -1234,7 +1257,7 @@ ${Qr}${sb}</style>
|
|
|
1234
1257
|
</script>
|
|
1235
1258
|
</body>
|
|
1236
1259
|
</html>
|
|
1237
|
-
`}import{spawnSync as
|
|
1260
|
+
`}import{spawnSync as fh}from"node:child_process";import jt from"node:fs";import gh from"node:os";import Re from"node:path";import{spawnSync as Kg}from"node:child_process";import Oe from"node:fs";import le from"node:path";import Cx from"node:fs";import ul from"node:path";var Px=`
|
|
1238
1261
|
.wrap { max-width: 1060px; }
|
|
1239
1262
|
.acts { display: none; gap: 8px; flex-wrap: wrap; margin-top: 10px; }
|
|
1240
1263
|
.linked .acts { display: flex; }
|
|
@@ -1263,41 +1286,41 @@ ${Qr}${sb}</style>
|
|
|
1263
1286
|
.ok { color: var(--green); } .no { color: var(--muted); }
|
|
1264
1287
|
details.more summary { padding: 2px 0; font-family: var(--mono); font-size: 10.5px; color: var(--muted); cursor: pointer; }
|
|
1265
1288
|
details.more summary:hover { color: var(--text); }
|
|
1266
|
-
`;function
|
|
1267
|
-
`).map(t=>t.trim()).find(Boolean);function
|
|
1268
|
-
<div class="scn">${B(
|
|
1269
|
-
<div class="feat">${B(
|
|
1270
|
-
${
|
|
1271
|
-
${
|
|
1272
|
-
${
|
|
1273
|
-
${
|
|
1274
|
-
<div class="acts">${
|
|
1275
|
-
</div>`},
|
|
1289
|
+
`;function Ix(e,t){if(!(!t||!_t(ul.join(e,".saffron","ci"),ul.join(e,t))))try{let n=Cx.readFileSync(ul.join(e,t));return n.length<=4*1024**2?`data:image/${/\.png$/i.test(t)?"png":"jpeg"};base64,${n.toString("base64")}`:void 0}catch{return}}var Hs=(e,t,n,r=!1)=>`<button class="act${r?" primary":""}" data-act="${B(e)}"${n?` data-f="${B(n.feature)}" data-s="${B(n.scenario)}"${n.browser?` data-b="${B(n.browser)}"`:""}`:""}>${B(t)}</button>`,Gg=e=>e?.split(`
|
|
1290
|
+
`).map(t=>t.trim()).find(Boolean);function Pi(e,t,n){let{run:r}=e,s=`${r.name??"CI run"} \xB7 run ${r.id}${r.attempt>1?`, attempt ${r.attempt}`:""}`,o=[r.status==="completed"?r.conclusion??"completed":r.status.replace("_"," "),r.branch&&`${r.branch}${r.commit?` @ ${r.commit.slice(0,7)}`:""}`,r.createdAt&&new Date(r.createdAt).toLocaleString("en-GB",{day:"2-digit",month:"short",hour:"2-digit",minute:"2-digit"})].filter(Boolean),a;if(!e.bundle)a=`<div class="panel"><div class="panel-title">no results</div><div class="note">${B(e.reason??"This run has no Saffron results.")}</div></div>`;else{let i=e.scenarios??[],c=e.totals??{green:0,yellow:0,red:0,aiCalls:0,costUsd:0},l=`<div class="kpis">${ve("passed",String(c.green),"green","green")}${ve("pending review",String(c.yellow),"healed or recorded",c.yellow?"gold":"")}${ve("failed",String(c.red),"red",c.red?"red":"")}${ve("agent",c.costUsd>0?`$${c.costUsd.toFixed(2)}`:String(c.aiCalls),c.costUsd>0?`${c.aiCalls} AI calls`:"AI calls")}</div>`,d=e.warnings.length?`<div class="panel accent-gold"><div class="panel-title gold">warnings</div>${e.warnings.map($=>`<div class="note">${B($)}</div>`).join("")}</div>`:"",f=e.bundle.summaryOnly?'<div class="panel"><div class="note">This run uploaded only a summary (saffron export --report-only): its results and screenshots, no traces to replay and nothing to import.</div></div>':"",p=$=>{let E=Ix(t,$.screenshot),R={feature:$.feature,scenario:$.displayName,browser:$.browser},k={feature:$.feature,scenario:$.scenario,browser:$.browser};return`<div class="card ${$.status==="red"?"red":"yellow"}">
|
|
1291
|
+
<div class="scn">${B($.displayName)}</div>
|
|
1292
|
+
<div class="feat">${B($.feature)}${$.browser?` \xB7 ${B($.browser)}`:""} \xB7 ${B(Qe($.durationMs))}${$.verified===!1?" \xB7 unverified":$.verified?" \xB7 verified":""}</div>
|
|
1293
|
+
${$.failingStep?`<div class="step">${$.status==="red"?"failed at":"changed at"}: ${B(Gg($.failingStep)??"")}</div>`:""}
|
|
1294
|
+
${$.error?`<div class="err">${B($.error)}</div>`:""}
|
|
1295
|
+
${$.narrative?`<div class="story">${B($.narrative)}</div>`:""}
|
|
1296
|
+
${E?`<details class="shot-full"><summary><img class="shot" src="${E}" alt="screenshot of ${B($.displayName)}"></summary></details>`:""}
|
|
1297
|
+
<div class="acts">${$.trace?Hs("trace","Open trace",R,!0):""}${Hs("open","Open scenario",k)}</div>
|
|
1298
|
+
</div>`},u=i.filter($=>$.status==="red"),h=i.filter($=>$.status==="yellow"),b=i.filter($=>$.status==="green"),g=($,E)=>E.length?`<div class="section-head"><span class="section-title">${B($)}</span></div><div class="cards">${E.map(p).join("")}</div>`:"",S=b.length?`<div class="section-head"><span class="section-title">passed</span></div><div class="panel"><details class="more"><summary>${b.length} scenario${b.length===1?"":"s"} passed</summary><ul class="rows">${b.map($=>`<li><span class="grow">${B($.displayName)}</span><span class="why">${B($.feature)}${$.browser?` \xB7 ${B($.browser)}`:""}</span></li>`).join("")}</ul></details></div>`:"",y=e.proposals??[],w=y.filter($=>$.importable).length,v=y.length?`<div class="section-head"><span class="section-title">proposals</span></div><div class="panel"><div class="note">${y.length} proposal${y.length===1?"":"s"}, ${w} importable here. Import files them for review in this checkout.</div><ul class="rows">${y.map($=>`<li><span class="${$.importable?"ok":"no"}">${$.importable?"\u2713":"\xB7"}</span><span class="grow">${B($.feature)} \u203A ${B($.scenario)}</span><span class="why">${B($.importable?$.verified?"verified":"unverified":Gg($.reason)??"not importable")}</span></li>`).join("")}</ul>${w?`<div class="acts">${Hs("import","Import",void 0,!0)}</div>`:""}</div>`:"",x=e.interrupted?`<div class="panel"><p><b>Run interrupted:</b> ${Number(e.notRun??0)} scenario${e.notRun===1?"":"s"} did not run, and count as neither passed nor failed.</p></div>`:"";a=`${l}${x}${d}${f}${g("failed",u)}${g("pending review",h)}${S}${v}`}return`<!doctype html>
|
|
1276
1299
|
<html lang="en">
|
|
1277
1300
|
<head>
|
|
1278
1301
|
<meta charset="utf-8"/>
|
|
1279
1302
|
<meta name="viewport" content="width=device-width, initial-scale=1"/>
|
|
1280
1303
|
<title>${B(s)}</title>
|
|
1281
|
-
${
|
|
1304
|
+
${$s}
|
|
1282
1305
|
<style>
|
|
1283
|
-
${
|
|
1306
|
+
${ks}${Px}</style>
|
|
1284
1307
|
</head>
|
|
1285
1308
|
<body>
|
|
1286
1309
|
<div class="topline"></div>
|
|
1287
1310
|
<div class="wrap">
|
|
1288
1311
|
<header class="top">
|
|
1289
1312
|
<div class="brand">
|
|
1290
|
-
${
|
|
1313
|
+
${ir(38)}
|
|
1291
1314
|
<div>
|
|
1292
1315
|
<div class="brand-name">saffron</div>
|
|
1293
1316
|
<div class="brand-sub">${B(s)}</div>
|
|
1294
1317
|
</div>
|
|
1295
1318
|
</div>
|
|
1296
|
-
<div class="run-meta">${o.map(
|
|
1319
|
+
<div class="run-meta">${o.map(i=>`<span>${B(i)}</span>`).join("<span>\xB7</span>")}</div>
|
|
1297
1320
|
</header>
|
|
1298
|
-
<div class="acts">${e.reportHtml?
|
|
1299
|
-
${
|
|
1300
|
-
<footer>${
|
|
1321
|
+
<div class="acts">${e.reportHtml?Hs("report","Open report"):""}${r.url?Hs("run","Open run page"):""}</div>
|
|
1322
|
+
${a}
|
|
1323
|
+
<footer>${Ss(11)} generated by saffron v${B(n)}</footer>
|
|
1301
1324
|
</div>
|
|
1302
1325
|
<script>
|
|
1303
1326
|
if (typeof window.saffronAct === "function") document.body.classList.add("linked");
|
|
@@ -1308,63 +1331,64 @@ ${Qr}${ib}</style>
|
|
|
1308
1331
|
</script>
|
|
1309
1332
|
</body>
|
|
1310
1333
|
</html>
|
|
1311
|
-
`}var
|
|
1312
|
-
${e.stdout}`,
|
|
1313
|
-
`).map(n=>n.trim()).find(n=>n&&!/^WARNING:/.test(n))??t;function Rr(e){return e.missing?{kind:"missing-tool",message:"the GitHub CLI (gh) is not installed here: install it from cli.github.com and sign in with gh auth login"}:e.timedOut?{kind:"failed",message:"gh did not finish within 10 minutes"}:/gh auth login|not logged in|authentication required/i.test(gs(e))?{kind:"signed-out",message:"gh is not signed in: run gh auth login"}:/none of the git remotes|no git remotes|not a git repository/i.test(gs(e))?{kind:"not-a-repository",message:ec(e,"not a GitHub repository")}:{kind:"failed",message:ec(e,`gh exited with ${e.status}`)}}function Gn(e){if(e.missing)return{kind:"missing-tool",message:"the Azure CLI (az) is not installed here: install it, add its azure-devops extension (az extension add --name azure-devops) and sign in (az login, or AZURE_DEVOPS_EXT_PAT)"};if(e.timedOut)return{kind:"failed",message:"az did not finish within 10 minutes"};let t=gs(e);return/azure-devops|'pipelines' is (misspelled|not in)|not in the 'az' command group/i.test(t)&&!/login/i.test(t)?{kind:"missing-tool",message:"the Azure CLI has no azure-devops extension: az extension add --name azure-devops"}:/az login|az devops login|TF400813|not authorized|authentication failed|\b401\b/i.test(t)?{kind:"signed-out",message:"az is not signed in to Azure DevOps: run az login, or set AZURE_DEVOPS_EXT_PAT"}:/--organization|--org\b|--project|must be specified|could not detect/i.test(t)?{kind:"not-a-repository",message:"cannot tell which Azure DevOps organization and project: run this in a clone of an Azure Repos repository, or set ci.organization and ci.project in saffron.config.json"}:{kind:"failed",message:ec(e,`az exited with ${e.status}`)}}function rc(e,t,n){let r=n??t.ci?.provider;if(r!==void 0){if(!cb.includes(r))throw new H(`unknown CI provider "${r}": use "github" or "azure"`);return r}return go(e).some(s=>s.startsWith("dev.azure.com/"))?"azure":"github"}var ms=e=>[...e.ci?.organization?["--organization",e.ci.organization]:[],...e.ci?.project?["--project",e.ci.project]:[]];function db(e,t){let n=_e("git",["rev-parse","--abbrev-ref","HEAD"],e,t),r=n.status===0?n.stdout.trim():"";return r&&r!=="HEAD"?r:void 0}function fb(e){let t=new Map;for(let[n,r]of Object.entries(on(e))){try{if(mt(ae.join(e,n))!==r.revision)continue}catch{continue}r.from.run&&t.set(r.from.run,(t.get(r.from.run)??0)+1)}return t}function ap(e,t=Date.now()){let n=e?t-Date.parse(e):NaN;if(!(n>=0))return;let r=Math.round(n/6e4);if(r<60)return`${r} min ago`;let s=Math.round(r/60);return s<48?`${s} h ago`:`${Math.round(s/24)} days ago`}var re=e=>typeof e=="string"&&e?e:void 0,op=e=>re(e)?.replace(/^refs\/(heads|tags)\//,""),ip="databaseId,number,attempt,displayTitle,workflowName,status,conclusion,event,headBranch,headSha,createdAt,startedAt,url";function ub(e){let t=e.status==="completed"?"completed":e.status==="in_progress"?"in_progress":"queued";return{id:String(e.databaseId),name:re(e.workflowName)??"workflow",number:String(e.number??""),title:re(e.displayTitle),status:t,conclusion:t==="completed"?re(e.conclusion):void 0,event:re(e.event),branch:re(e.headBranch),commit:re(e.headSha),createdAt:re(e.createdAt),url:re(e.url),attempt:typeof e.attempt=="number"?e.attempt:void 0}}var pb={completed:"completed",inProgress:"in_progress",cancelling:"in_progress"},gb={succeeded:"success",partiallySucceeded:"partial",failed:"failure",canceled:"cancelled"},hb={individualCI:"push",batchedCI:"push",pullRequest:"pull_request",schedule:"schedule",manual:"manual"};function cp(e){let t=e.triggerInfo??{};return op(t["pr.sourceBranch"])??op(e.sourceBranch)}function lp(e){let t=e.triggerInfo??{},n=pb[String(e.status)]??"queued",r=re(e.result);return{id:String(e.id),name:re(e.definition?.name)??"pipeline",number:String(e.buildNumber??e.id),status:n,conclusion:n==="completed"&&r?gb[r]??r:void 0,event:re(e.reason)?hb[String(e.reason)]??String(e.reason):void 0,branch:cp(e),commit:re(t["pr.sourceSha"])??re(e.sourceVersion),createdAt:re(e.queueTime),url:re((e._links??{}).web?.href)}}function zo(e){try{let t=JSON.parse(e);return t&&typeof t=="object"&&!Array.isArray(t)?t:void 0}catch{return}}function sc(e){try{let t=JSON.parse(e);return Array.isArray(t)?t.filter(n=>!!n&&typeof n=="object"):void 0}catch{return}}function mb(e){return new Set(e.map(t=>t.startsWith("dev.azure.com/")?t.slice(t.lastIndexOf("/_git/")+6):t.slice(t.indexOf("/")+1)))}function wb(e,t,n,r,s,o,i=Math.min(Math.max(o,50),500)){for(let a=i;;a=Math.min(a*2,500)){let c=_e("az",["pipelines","runs","list","--top",String(a),...r,"--output","json",...ms(t)],e,n);if(c.missing||c.status!==0)return Gn(c);let l=sc(c.stdout);if(!l)return{kind:"failed",message:"az answered with something other than a list of runs"};let d=l.filter(s);if(d.length>=o||l.length<a||a>=500)return d}}function dp(e,t,n={}){let r=n.env??process.env,s=rc(e,t,n.provider),o=n.branch??db(e,r),i=o===void 0?void 0:kr(o),a=n.limit??20,c,l=new Map;if(s==="github"){let g=m=>_e("gh",["run","list","--limit",String(a),"--json",m,...i?["--branch",i]:[]],e,r),f=g(ip);if(!f.missing&&f.status!==0&&/startedAt/.test(`${f.stderr??""}${f.stdout??""}`)&&(f=g(ip.replace(",startedAt",""))),f.missing||f.status!==0)return{provider:s,branch:i,runs:[],problem:Rr(f)};let p=sc(f.stdout);if(!p)return{provider:s,branch:i,runs:[],problem:{kind:"failed",message:"gh answered with something other than a list of runs"}};c=p.map(ub);for(let m of p)l.set(String(m.databaseId),Date.parse(re(m.startedAt)??""))}else{let g=mb(go(e)),f=w=>{let b=re(w.repository?.name)?.toLowerCase();return g.size===0||!b||g.has(b)},p=w=>f(w)&&(!i||cp(w)===i),m=i?[["--branch",`refs/heads/${i}`],["--branch",`refs/tags/${i}`],["--reason","pullRequest"]]:[[]],h=new Map;for(let w of m){let b=wb(e,t,r,w,p,a);if(!Array.isArray(b))return{provider:s,branch:i,runs:[],problem:b};for(let y of b)h.set(String(y.id),y)}c=[...h.values()].sort((w,b)=>(Date.parse(re(b.queueTime)??"")||0)-(Date.parse(re(w.queueTime)??"")||0)).slice(0,a).map(lp)}let d=fb(e),u=s==="github"?yb(e,r,c,l):new Map;return{provider:s,branch:i,runs:c.map(g=>{let f=u.get(g.id);return{...g,pending:d.get(`${s}:${g.id}`)??0,...f?{results:f}:{}}})}}function yb(e,t,n,r){let s=new Map;for(let d of n)d.status!=="completed"&&s.set(d.id,{kind:"running",label:sp("running")});let o=n.filter(d=>d.status==="completed");if(o.length===0)return s;let i=Math.min(...o.map(d=>Date.parse(d.createdAt??"")||0)),a=new Map,c=!1;for(let d=1;d<=5&&!c;d++){let u=_e("gh",["api",`repos/{owner}/{repo}/actions/artifacts?per_page=100&page=${d}`],e,t),g=u.missing||u.status!==0?void 0:zo(u.stdout)?.artifacts;if(!Array.isArray(g))break;for(let f of g.filter(p=>!!p&&typeof p=="object")){let p=String((f.workflow_run??{}).id??"");p&&a.set(p,[...a.get(p)??[],f]);let m=Date.parse(re(f.created_at)??"");!Number.isNaN(m)&&m<i&&(c=!0)}g.length<100&&(c=!0)}let l=d=>d.reduce((u,g)=>u+(Number(g.size_in_bytes)||0),0);for(let d of o){let u=bb(a.get(d.id)??[],(d.attempt??1)>1?r.get(d.id):void 0),g=w=>u.filter(b=>typeof b.name=="string"&&w.test(b.name)),f=g(up),p=g(nc),m=w=>w.filter(b=>b.expired!==!0),h=(w,b)=>s.set(d.id,{kind:w,...b!==void 0?{sizeBytes:b}:{},label:sp(w,b)});m(f).length>0?h("full",l(m(f))):m(p).length>0?h("summary",l(m(p))):f.length+p.length>0?h("expired"):c&&h("none")}return s}function bb(e,t){if(t===void 0||Number.isNaN(t))return e;let n=o=>String(o.name).replace(/^saffron-(bundle|summary)/,""),r=o=>Date.parse(re(o.created_at)??"")>=t,s=new Set(e.filter(r).map(n));return e.filter(o=>r(o)||!s.has(n(o)))}var tc=e=>`run ${e} has no Saffron bundle: none was uploaded, or it expired. Its workflow needs saffron export and an upload of saffron-bundle* (see the guide, section 19)`;function fp(e,t,n,r,s,o){let i,a;if(n==="github"){let c=_e("gh",["api",`repos/{owner}/{repo}/actions/runs/${r}`],e,s);if(c.missing||c.status!==0)throw new H(Rr(c).message,Rr(c).kind);let l=zo(c.stdout),d=re(l?.repository?.full_name);if(!l||String(l.id)!==r||!d)throw new H(`gh answered with something other than run ${r}`);let u=re(l.head_repository?.full_name);u?.toLowerCase()!==d.toLowerCase()&&(i={event:re(l.event),from:u});let g=l.status==="completed"?"completed":l.status==="in_progress"?"in_progress":"queued";a={provider:n,id:r,attempt:typeof l.run_attempt=="number"?l.run_attempt:1,name:re(l.name),branch:re(l.head_branch),commit:re(l.head_sha),url:re(l.html_url),status:g,conclusion:g==="completed"?re(l.conclusion):void 0,createdAt:re(l.created_at)}}else{let c=_e("az",["pipelines","runs","show","--id",r,"--output","json",...ms(t)],e,s);if(c.missing||c.status!==0)throw new H(Gn(c).message,Gn(c).kind);let l=zo(c.stdout);if(!l||String(l.id)!==r)throw new H(`az answered with something other than run ${r}`);let d=lp(l);/^true$/i.test(String((l.triggerInfo??{})["pr.isFork"]))&&(i={event:d.event}),a={provider:n,id:r,attempt:1,name:d.name,branch:d.branch,commit:d.commit,url:d.url,status:d.status,conclusion:d.conclusion,createdAt:d.createdAt}}if(i&&!o)throw new H(`run ${r}${i.event?` (${i.event})`:""} comes from ${i.from?`the fork ${i.from}`:"a fork"}: code from outside this repository made its bundle, and could have put anything in it. Read that pull request, then import with --allow-fork if you trust it`,"fork");return a}var up=/^saffron-bundle[\w.-]*$/,nc=/^saffron-summary[\w.-]*$/;function pp(e,t,n,r,s){let o;if(n==="github"){o=[];for(let i=1;o;i++){let a=_e("gh",["api",`repos/{owner}/{repo}/actions/runs/${r}/artifacts?per_page=100&page=${i}`],e,s);if(a.missing||a.status!==0)throw new H(Rr(a).message,Rr(a).kind);let c=zo(a.stdout)?.artifacts;if(!Array.isArray(c))o=void 0;else if(o.push(...c.filter(l=>!!l&&typeof l=="object")),c.length<100)break}}else{let i=_e("az",["pipelines","runs","artifact","list","--run-id",r,"--output","json",...ms(t)],e,s);if(i.missing||i.status!==0)throw new H(Gn(i).message,Gn(i).kind);o=sc(i.stdout)}if(!o)throw new H(`${n==="github"?"gh":"az"} answered with something other than a list of artifacts`);return o.filter(i=>typeof i.name=="string"&&(up.test(i.name)||nc.test(i.name))).map(i=>({name:i.name,sizeBytes:Number(i.size_in_bytes??((i.resource??{}).properties??{}).artifactsize)||0,expired:i.expired===!0,summary:nc.test(i.name)}))}function gp(e,t,n,r,s,o,i){if(i.length===0)throw new H(tc(r));for(let a of i){let c=n==="github"?_e("gh",["run","download",r,"-n",a,"--dir",ae.join(s,a)],e,o):_e("az",["pipelines","runs","artifact","download","--run-id",r,"--artifact-name",a,"--path",ae.join(s,a),...ms(t)],e,o);if(c.missing||c.status!==0)throw n==="github"&&/no (valid )?artifact/i.test(gs(c))?new H(tc(r)):new H(`cannot download ${a}: ${(n==="github"?Rr(c):Gn(c)).message}`)}}function hp(e,t,n,r={}){mp(n);let s=r.env??process.env,o=rc(e,t,r.provider),i=fp(e,t,o,n,s,r.allowFork===!0),a=wp(e,o,n,i.attempt);if(i.status==="completed"&&be.existsSync(a))return{provider:o,dir:ae.join(a,"bundles"),remove:()=>{}};let c=pp(e,t,o,n,s).filter(u=>!u.expired).map(u=>u.name);if(c.length===0)throw new H(tc(n));let{dir:l,remove:d}=fa(e);try{return gp(e,t,o,n,l,s,c),{provider:o,dir:l,remove:d}}catch(u){throw d(),u}}function mp(e){if(!/^\d+$/.test(e))throw new H(`--run takes the run's id, a number as saffron runs lists it, not "${e}"`)}var oc=e=>ae.join(e,".saffron","ci"),wp=(e,t,n,r)=>ae.join(oc(e),`${t}-${n}`,`attempt-${r}`),vb=10,xb=1024**3;function Sb(e){let t=0;for(let n of be.readdirSync(e,{recursive:!0})){let r=be.lstatSync(ae.join(e,String(n)),{throwIfNoEntry:!1});r?.isFile()&&(t+=r.size)}return t}function $b(e,t){let n=oc(e),r=be.readdirSync(n,{withFileTypes:!0}).filter(i=>i.isDirectory()).map(i=>ae.join(n,i.name)).map(i=>({run:i,mtime:be.statSync(i).mtimeMs,bytes:Sb(i)})).sort((i,a)=>+(a.run===t)-+(i.run===t)||a.mtime-i.mtime),s=0,o=0;for(let i of r){if(i.run!==t&&(s+1>vb||o+i.bytes>xb)){be.rmSync(i.run,{recursive:!0,force:!0});continue}s++,o+=i.bytes}}var hs=class extends H{constructor(n,r){super(`this run's results are ${Math.ceil(n/1024**2)} MB, over --max-download ${Math.round(r/1024**2)} MB. Run again with a higher --max-download to download them`,"too-large");this.sizeBytes=n}sizeBytes};function ic(e,t,n,r={}){mp(n);let s=r.env??process.env,o=rc(e,t,r.provider),i=fp(e,t,o,n,s,r.allowFork===!0);if(i.status!=="completed")return{run:i,artifacts:[],reasonKind:"running",reason:`run ${n} has not finished: its results are uploaded when it does`};let a=pp(e,t,o,n,s),c=a.filter(w=>!w.expired),l=c.map(({name:w,sizeBytes:b})=>({name:w,sizeBytes:b})),d=wp(e,o,n,i.attempt),u=new Date;if(be.existsSync(d))return be.utimesSync(ae.dirname(d),u,u),{run:i,folder:d,cached:!0,artifacts:l};if(c.length===0)return a.length>0?{run:i,artifacts:l,reasonKind:"expired",reason:`run ${n}'s Saffron bundle expired: the service keeps artifacts for a limited time`}:{run:i,artifacts:l,reasonKind:"none",reason:`run ${n} uploaded no Saffron bundle. The guide's workflow exports only when a run fails; set if: always() on the export and upload steps to keep every run's results`};let g=c.reduce((w,b)=>w+b.sizeBytes,0);if(r.maxDownloadBytes!==void 0&&g>r.maxDownloadBytes)throw new hs(g,r.maxDownloadBytes);let f=oc(e);be.mkdirSync(f,{recursive:!0});let p=ae.join(f,".gitignore");be.existsSync(p)||be.writeFileSync(p,`*
|
|
1314
|
-
`),
|
|
1315
|
-
`).map(t=>t.trim()).find(Boolean);async function
|
|
1316
|
-
`),
|
|
1317
|
-
`).slice(-3).join(" ")}`);return e.stdout}function
|
|
1334
|
+
`}var Nx=["github","azure"],Ni={github:"GitHub Actions",azure:"Azure Pipelines"};function Yg(e,t){let n={full:"results",summary:"summary only",expired:"results expired",none:"no results uploaded",running:"still running"}[e];if(!t)return n;let r=t/1024**2;return`${n}, ${r<1?"under 1":Math.round(r)} MB`}function Zr(e){if(e.startsWith("@")||/[\x00-\x1f\x7f]/.test(e))throw new W(`${JSON.stringify(e)} is not a branch name Saffron passes on`);return e}function jx(e){let t=e.replace(/(\\*)"/g,'$1$1\\"').replace(/(\\*)$/,"$1$1");return t=`"${t}"`,t=t.replace(/[()%!^"<>&|;, ]/g,"^$&"),t.replace(/[()%!^"<>&|;, ]/g,"^$&")}function ze(e,t,n,r,s){let o=process.platform==="win32"&&e==="az",a=o?Kg("az.cmd",t.map(jx),{cwd:n,env:r,input:s,encoding:"utf8",shell:!0,windowsVerbatimArguments:!0,timeout:6e5,maxBuffer:64*1024*1024}):Kg(e,t,{cwd:n,env:r,input:s,encoding:"utf8",timeout:6e5,maxBuffer:64*1024*1024}),i=a.error?.code,c=i==="ENOENT"||o&&a.status===9009;return{status:a.status,stdout:(a.stdout??"").trim(),stderr:(a.stderr??"").trim(),missing:c,timedOut:i==="ETIMEDOUT"}}var qs=e=>`${e.stderr}
|
|
1335
|
+
${e.stdout}`,fl=(e,t)=>qs(e).split(`
|
|
1336
|
+
`).map(n=>n.trim()).find(n=>n&&!/^WARNING:/.test(n))??t;function Qr(e){return e.missing?{kind:"missing-tool",message:"the GitHub CLI (gh) is not installed here: install it from cli.github.com and sign in with gh auth login"}:e.timedOut?{kind:"failed",message:"gh did not finish within 10 minutes"}:/gh auth login|not logged in|authentication required/i.test(qs(e))?{kind:"signed-out",message:"gh is not signed in: run gh auth login"}:/none of the git remotes|no git remotes|not a git repository/i.test(qs(e))?{kind:"not-a-repository",message:fl(e,"not a GitHub repository")}:{kind:"failed",message:fl(e,`gh exited with ${e.status}`)}}function wr(e){if(e.missing)return{kind:"missing-tool",message:"the Azure CLI (az) is not installed here: install it, add its azure-devops extension (az extension add --name azure-devops) and sign in (az login, or AZURE_DEVOPS_EXT_PAT)"};if(e.timedOut)return{kind:"failed",message:"az did not finish within 10 minutes"};let t=qs(e);return/azure-devops|'pipelines' is (misspelled|not in)|not in the 'az' command group/i.test(t)&&!/login/i.test(t)?{kind:"missing-tool",message:"the Azure CLI has no azure-devops extension: az extension add --name azure-devops"}:/az login|az devops login|TF400813|not authorized|authentication failed|\b401\b/i.test(t)?{kind:"signed-out",message:"az is not signed in to Azure DevOps: run az login, or set AZURE_DEVOPS_EXT_PAT"}:/--organization|--org\b|--project|must be specified|could not detect/i.test(t)?{kind:"not-a-repository",message:"cannot tell which Azure DevOps organization and project: run this in a clone of an Azure Repos repository, or set ci.organization and ci.project in saffron.config.json"}:{kind:"failed",message:fl(e,`az exited with ${e.status}`)}}function hl(e,t,n){let r=n??t.ci?.provider;if(r!==void 0){if(!Nx.includes(r))throw new W(`unknown CI provider "${r}": use "github" or "azure"`);return r}return ei(e).some(s=>s.startsWith("dev.azure.com/"))?"azure":"github"}var Js=e=>[...e.ci?.organization?["--organization",e.ci.organization]:[],...e.ci?.project?["--project",e.ci.project]:[]];function Mx(e,t){let n=ze("git",["rev-parse","--abbrev-ref","HEAD"],e,t),r=n.status===0?n.stdout.trim():"";return r&&r!=="HEAD"?r:void 0}function Dx(e){let t=new Map;for(let[n,r]of Object.entries(hn(e))){try{if(Ot(le.join(e,n))!==r.revision)continue}catch{continue}r.from.run&&t.set(r.from.run,(t.get(r.from.run)??0)+1)}return t}function Xg(e,t=Date.now()){let n=e?t-Date.parse(e):NaN;if(!(n>=0))return;let r=Math.round(n/6e4);if(r<60)return`${r} min ago`;let s=Math.round(r/60);return s<48?`${s} h ago`:`${Math.round(s/24)} days ago`}var ie=e=>typeof e=="string"&&e?e:void 0,Zg=e=>ie(e)?.replace(/^refs\/(heads|tags)\//,""),Qg="databaseId,number,attempt,displayTitle,workflowName,status,conclusion,event,headBranch,headSha,createdAt,startedAt,url";function Fx(e){let t=e.status==="completed"?"completed":e.status==="in_progress"?"in_progress":"queued";return{id:String(e.databaseId),name:ie(e.workflowName)??"workflow",number:String(e.number??""),title:ie(e.displayTitle),status:t,conclusion:t==="completed"?ie(e.conclusion):void 0,event:ie(e.event),branch:ie(e.headBranch),commit:ie(e.headSha),createdAt:ie(e.createdAt),url:ie(e.url),attempt:typeof e.attempt=="number"?e.attempt:void 0}}var Lx={completed:"completed",inProgress:"in_progress",cancelling:"in_progress"},Bx={succeeded:"success",partiallySucceeded:"partial",failed:"failure",canceled:"cancelled"},Ux={individualCI:"push",batchedCI:"push",pullRequest:"pull_request",schedule:"schedule",manual:"manual"};function eh(e){let t=e.triggerInfo??{};return Zg(t["pr.sourceBranch"])??Zg(e.sourceBranch)}function th(e){let t=e.triggerInfo??{},n=Lx[String(e.status)]??"queued",r=ie(e.result);return{id:String(e.id),name:ie(e.definition?.name)??"pipeline",number:String(e.buildNumber??e.id),status:n,conclusion:n==="completed"&&r?Bx[r]??r:void 0,event:ie(e.reason)?Ux[String(e.reason)]??String(e.reason):void 0,branch:eh(e),commit:ie(t["pr.sourceSha"])??ie(e.sourceVersion),createdAt:ie(e.queueTime),url:ie((e._links??{}).web?.href)}}function Ii(e){try{let t=JSON.parse(e);return t&&typeof t=="object"&&!Array.isArray(t)?t:void 0}catch{return}}function ml(e){try{let t=JSON.parse(e);return Array.isArray(t)?t.filter(n=>!!n&&typeof n=="object"):void 0}catch{return}}function zx(e){return new Set(e.map(t=>t.startsWith("dev.azure.com/")?t.slice(t.lastIndexOf("/_git/")+6):t.slice(t.indexOf("/")+1)))}function Hx(e,t,n,r,s,o,a=Math.min(Math.max(o,50),500)){for(let i=a;;i=Math.min(i*2,500)){let c=ze("az",["pipelines","runs","list","--top",String(i),...r,"--output","json",...Js(t)],e,n);if(c.missing||c.status!==0)return wr(c);let l=ml(c.stdout);if(!l)return{kind:"failed",message:"az answered with something other than a list of runs"};let d=l.filter(s);if(d.length>=o||l.length<i||i>=500)return d}}function nh(e,t,n={}){let r=n.env??process.env,s=hl(e,t,n.provider),o=n.branch??Mx(e,r),a=o===void 0?void 0:Zr(o),i=n.limit??20,c,l=new Map;if(s==="github"){let p=b=>ze("gh",["run","list","--limit",String(i),"--json",b,...a?["--branch",a]:[]],e,r),u=p(Qg);if(!u.missing&&u.status!==0&&/startedAt/.test(`${u.stderr??""}${u.stdout??""}`)&&(u=p(Qg.replace(",startedAt",""))),u.missing||u.status!==0)return{provider:s,branch:a,runs:[],problem:Qr(u)};let h=ml(u.stdout);if(!h)return{provider:s,branch:a,runs:[],problem:{kind:"failed",message:"gh answered with something other than a list of runs"}};c=h.map(Fx);for(let b of h)l.set(String(b.databaseId),Date.parse(ie(b.startedAt)??""))}else{let p=zx(ei(e)),u=S=>{let y=ie(S.repository?.name)?.toLowerCase();return p.size===0||!y||p.has(y)},h=S=>u(S)&&(!a||eh(S)===a),b=a?[["--branch",`refs/heads/${a}`],["--branch",`refs/tags/${a}`],["--reason","pullRequest"]]:[[]],g=new Map;for(let S of b){let y=Hx(e,t,r,S,h,i);if(!Array.isArray(y))return{provider:s,branch:a,runs:[],problem:y};for(let w of y)g.set(String(w.id),w)}c=[...g.values()].sort((S,y)=>(Date.parse(ie(y.queueTime)??"")||0)-(Date.parse(ie(S.queueTime)??"")||0)).slice(0,i).map(th)}let d=Dx(e),f=s==="github"?qx(e,r,c,l):new Map;return{provider:s,branch:a,runs:c.map(p=>{let u=f.get(p.id);return{...p,pending:d.get(`${s}:${p.id}`)??0,...u?{results:u}:{}}})}}function qx(e,t,n,r){let s=new Map;for(let d of n)d.status!=="completed"&&s.set(d.id,{kind:"running",label:Yg("running")});let o=n.filter(d=>d.status==="completed");if(o.length===0)return s;let a=Math.min(...o.map(d=>Date.parse(d.createdAt??"")||0)),i=new Map,c=!1;for(let d=1;d<=5&&!c;d++){let f=ze("gh",["api",`repos/{owner}/{repo}/actions/artifacts?per_page=100&page=${d}`],e,t),p=f.missing||f.status!==0?void 0:Ii(f.stdout)?.artifacts;if(!Array.isArray(p))break;for(let u of p.filter(h=>!!h&&typeof h=="object")){let h=String((u.workflow_run??{}).id??"");h&&i.set(h,[...i.get(h)??[],u]);let b=Date.parse(ie(u.created_at)??"");!Number.isNaN(b)&&b<a&&(c=!0)}p.length<100&&(c=!0)}let l=d=>d.reduce((f,p)=>f+(Number(p.size_in_bytes)||0),0);for(let d of o){let f=Vx(i.get(d.id)??[],(d.attempt??1)>1?r.get(d.id):void 0),p=S=>f.filter(y=>typeof y.name=="string"&&S.test(y.name)),u=p(sh),h=p(gl),b=S=>S.filter(y=>y.expired!==!0),g=(S,y)=>s.set(d.id,{kind:S,...y!==void 0?{sizeBytes:y}:{},label:Yg(S,y)});b(u).length>0?g("full",l(b(u))):b(h).length>0?g("summary",l(b(h))):u.length+h.length>0?g("expired"):c&&g("none")}return s}function Vx(e,t){if(t===void 0||Number.isNaN(t))return e;let n=o=>String(o.name).replace(/^saffron-(bundle|summary)/,""),r=o=>Date.parse(ie(o.created_at)??"")>=t,s=new Set(e.filter(r).map(n));return e.filter(o=>r(o)||!s.has(n(o)))}var pl=e=>`run ${e} has no Saffron bundle: none was uploaded, or it expired. Its workflow needs saffron export and an upload of saffron-bundle* (see the guide, section 19)`;function rh(e,t,n,r,s,o){let a,i;if(n==="github"){let c=ze("gh",["api",`repos/{owner}/{repo}/actions/runs/${r}`],e,s);if(c.missing||c.status!==0)throw new W(Qr(c).message,Qr(c).kind);let l=Ii(c.stdout),d=ie(l?.repository?.full_name);if(!l||String(l.id)!==r||!d)throw new W(`gh answered with something other than run ${r}`);let f=ie(l.head_repository?.full_name);f?.toLowerCase()!==d.toLowerCase()&&(a={event:ie(l.event),from:f});let p=l.status==="completed"?"completed":l.status==="in_progress"?"in_progress":"queued";i={provider:n,id:r,attempt:typeof l.run_attempt=="number"?l.run_attempt:1,name:ie(l.name),branch:ie(l.head_branch),commit:ie(l.head_sha),url:ie(l.html_url),status:p,conclusion:p==="completed"?ie(l.conclusion):void 0,createdAt:ie(l.created_at)}}else{let c=ze("az",["pipelines","runs","show","--id",r,"--output","json",...Js(t)],e,s);if(c.missing||c.status!==0)throw new W(wr(c).message,wr(c).kind);let l=Ii(c.stdout);if(!l||String(l.id)!==r)throw new W(`az answered with something other than run ${r}`);let d=th(l);/^true$/i.test(String((l.triggerInfo??{})["pr.isFork"]))&&(a={event:d.event}),i={provider:n,id:r,attempt:1,name:d.name,branch:d.branch,commit:d.commit,url:d.url,status:d.status,conclusion:d.conclusion,createdAt:d.createdAt}}if(a&&!o)throw new W(`run ${r}${a.event?` (${a.event})`:""} comes from ${a.from?`the fork ${a.from}`:"a fork"}: code from outside this repository made its bundle, and could have put anything in it. Read that pull request, then import with --allow-fork if you trust it`,"fork");return i}var sh=/^saffron-bundle[\w.-]*$/,gl=/^saffron-summary[\w.-]*$/;function oh(e,t,n,r,s){let o;if(n==="github"){o=[];for(let a=1;o;a++){let i=ze("gh",["api",`repos/{owner}/{repo}/actions/runs/${r}/artifacts?per_page=100&page=${a}`],e,s);if(i.missing||i.status!==0)throw new W(Qr(i).message,Qr(i).kind);let c=Ii(i.stdout)?.artifacts;if(!Array.isArray(c))o=void 0;else if(o.push(...c.filter(l=>!!l&&typeof l=="object")),c.length<100)break}}else{let a=ze("az",["pipelines","runs","artifact","list","--run-id",r,"--output","json",...Js(t)],e,s);if(a.missing||a.status!==0)throw new W(wr(a).message,wr(a).kind);o=ml(a.stdout)}if(!o)throw new W(`${n==="github"?"gh":"az"} answered with something other than a list of artifacts`);return o.filter(a=>typeof a.name=="string"&&(sh.test(a.name)||gl.test(a.name))).map(a=>({name:a.name,sizeBytes:Number(a.size_in_bytes??((a.resource??{}).properties??{}).artifactsize)||0,expired:a.expired===!0,summary:gl.test(a.name)}))}function ih(e,t,n,r,s,o,a){if(a.length===0)throw new W(pl(r));for(let i of a){let c=n==="github"?ze("gh",["run","download",r,"-n",i,"--dir",le.join(s,i)],e,o):ze("az",["pipelines","runs","artifact","download","--run-id",r,"--artifact-name",i,"--path",le.join(s,i),...Js(t)],e,o);if(c.missing||c.status!==0)throw n==="github"&&/no (valid )?artifact/i.test(qs(c))?new W(pl(r)):new W(`cannot download ${i}: ${(n==="github"?Qr(c):wr(c)).message}`)}}function ah(e,t,n,r={}){ch(n);let s=r.env??process.env,o=hl(e,t,r.provider),a=rh(e,t,o,n,s,r.allowFork===!0),i=lh(e,o,n,a.attempt);if(a.status==="completed"&&Oe.existsSync(i))return{provider:o,dir:le.join(i,"bundles"),remove:()=>{}};let c=oh(e,t,o,n,s).filter(f=>!f.expired).map(f=>f.name);if(c.length===0)throw new W(pl(n));let{dir:l,remove:d}=vc(e);try{return ih(e,t,o,n,l,s,c),{provider:o,dir:l,remove:d}}catch(f){throw d(),f}}function ch(e){if(!/^\d+$/.test(e))throw new W(`--run takes the run's id, a number as saffron runs lists it, not "${e}"`)}var wl=e=>le.join(e,".saffron","ci"),lh=(e,t,n,r)=>le.join(wl(e),`${t}-${n}`,`attempt-${r}`),Jx=10,Wx=1024**3;function Gx(e){let t=0;for(let n of Oe.readdirSync(e,{recursive:!0})){let r=Oe.lstatSync(le.join(e,String(n)),{throwIfNoEntry:!1});r?.isFile()&&(t+=r.size)}return t}function Kx(e,t){let n=wl(e),r=Oe.readdirSync(n,{withFileTypes:!0}).filter(a=>a.isDirectory()).map(a=>le.join(n,a.name)).map(a=>({run:a,mtime:Oe.statSync(a).mtimeMs,bytes:Gx(a)})).sort((a,i)=>+(i.run===t)-+(a.run===t)||i.mtime-a.mtime),s=0,o=0;for(let a of r){if(a.run!==t&&(s+1>Jx||o+a.bytes>Wx)){Oe.rmSync(a.run,{recursive:!0,force:!0});continue}s++,o+=a.bytes}}var Vs=class extends W{constructor(n,r){super(`this run's results are ${Math.ceil(n/1024**2)} MB, over --max-download ${Math.round(r/1024**2)} MB. Run again with a higher --max-download to download them`,"too-large");this.sizeBytes=n}sizeBytes};function yl(e,t,n,r={}){ch(n);let s=r.env??process.env,o=hl(e,t,r.provider),a=rh(e,t,o,n,s,r.allowFork===!0);if(a.status!=="completed")return{run:a,artifacts:[],reasonKind:"running",reason:`run ${n} has not finished: its results are uploaded when it does`};let i=oh(e,t,o,n,s),c=i.filter(S=>!S.expired),l=c.map(({name:S,sizeBytes:y})=>({name:S,sizeBytes:y})),d=lh(e,o,n,a.attempt),f=new Date;if(Oe.existsSync(d))return Oe.utimesSync(le.dirname(d),f,f),{run:a,folder:d,cached:!0,artifacts:l};if(c.length===0)return i.length>0?{run:a,artifacts:l,reasonKind:"expired",reason:`run ${n}'s Saffron bundle expired: the service keeps artifacts for a limited time`}:{run:a,artifacts:l,reasonKind:"none",reason:`run ${n} uploaded no Saffron bundle. The guide's workflow exports only when a run fails; set if: always() on the export and upload steps to keep every run's results`};let p=c.reduce((S,y)=>S+y.sizeBytes,0);if(r.maxDownloadBytes!==void 0&&p>r.maxDownloadBytes)throw new Vs(p,r.maxDownloadBytes);let u=wl(e);Oe.mkdirSync(u,{recursive:!0});let h=le.join(u,".gitignore");Oe.existsSync(h)||Oe.writeFileSync(h,`*
|
|
1337
|
+
`),Oe.mkdirSync(le.dirname(d),{recursive:!0});let b=Oe.mkdtempSync(`${d}.partial-`);try{ih(e,t,o,n,le.join(b,"bundles"),s,c.map(S=>S.name));try{Oe.renameSync(b,d)}catch(S){if(!Oe.existsSync(d))throw S;return Oe.utimesSync(le.dirname(d),f,f),{run:a,folder:d,cached:!0,artifacts:l}}}finally{Oe.rmSync(b,{recursive:!0,force:!0})}let g=Date.now()-1440*60*1e3;for(let S of Oe.readdirSync(le.dirname(d))){let y=le.join(le.dirname(d),S),w=/^attempt-(\d+)$/.exec(S),v=/^attempt-\d+\.partial$/.test(S)||/^attempt-\d+\.partial-/.test(S)&&(Oe.statSync(y,{throwIfNoEntry:!1})?.mtimeMs??1/0)<g;(w&&Number(w[1])<a.attempt||v)&&Oe.rmSync(y,{recursive:!0,force:!0})}return Oe.utimesSync(le.dirname(d),f,f),Kx(e,le.dirname(d)),{run:a,folder:d,cached:!1,artifacts:l}}async function bl(e,t,n){let{run:r,folder:s}=t;return Bf(e,s,[le.join(s,"bundles")],n,{run:`${r.provider}:${r.id}`,describe:o=>`${Ni[r.provider]} run ${r.id} (${le.basename(le.dirname(o))})`})}var Yx=e=>e?.split(`
|
|
1338
|
+
`).map(t=>t.trim()).find(Boolean);async function dh(e,t,n,r,s={}){let o=yl(e,t,r,s);if(!o.folder)return{results:{run:o.run,bundle:null,reasonKind:o.reasonKind,reason:o.reason,warnings:[]}};let a=o.folder,i=await bl(e,{...o,folder:a},n),c=u=>Be(e,le.join(a,u)),l={run:o.run,bundle:{folder:Be(e,a),cached:o.cached===!0,artifacts:o.artifacts,...i.summaryOnly?{summaryOnly:!0}:{}},warnings:i.warnings},{report:d}=i;if(d){let{green:u,yellow:h,red:b,aiCalls:g,costUsd:S}=d.totals;l.totals={green:u,yellow:h,red:b,aiCalls:g,costUsd:S},d.interrupted&&Object.assign(l,{interrupted:!0,notRun:d.notRun??0}),d.browsers?.length&&(l.browsers=d.browsers),l.scenarios=d.scenarios.map(y=>{let w=(y.evidence??[]).filter(R=>R.kind==="trace"?_t(le.join(a,".saffron","artifacts"),le.join(a,R.file)):Pn(a,R)!==void 0),v=w.filter(R=>R.kind!=="trace"),x=v.find(R=>R.kind==="failure")??v.find(R=>R.kind==="before-heal")??v[0],$=w.filter(R=>R.kind==="trace"),E=$.find(R=>!R.proof)??$[0];return{feature:y.feature,scenario:sr(y),displayName:y.scenario,tags:y.tags,status:y.status,durationMs:y.durationMs,verified:y.verified,failingStep:y.steps.find(R=>R.status==="failed")?.gherkin,error:Yx(y.error),narrative:y.narrative,screenshot:x&&c(x.file),trace:E&&c(E.file),...y.browser?{browser:y.browser}:{}}}),Je(le.join(a,"report.json"),`${JSON.stringify(d,null,2)}
|
|
1339
|
+
`),Je(le.join(a,"report.html"),Ln(d,a)),l.reportHtml=c("report.html")}else l.scenarios=[];l.proposals=i.proposals,Je(le.join(a,"panel.html"),Pi(l,e,ot())),l.panelHtml=c("panel.html");let{warnings:f,...p}=l;return{results:{...p,warnings:f},report:d}}function uh(e,t,n,r){let s=ze("az",["repos","pr","create","--draft","true","--source-branch",`refs/heads/${Zr(n.branch)}`,"--target-branch",`refs/heads/${Zr(n.base)}`,"--title",n.title,"--description",`@${n.bodyFile}`,"--output","json",...Js(t)],e,r);if(s.missing||s.status!==0)return{problem:`az repos pr create failed: ${wr(s).message}`};try{let o=JSON.parse(s.stdout),a=o.repository?.webUrl;return{url:a&&o.pullRequestId!==void 0?`${a}/pullrequest/${o.pullRequestId}`:void 0}}catch{return{}}}function ph(e,t,n){if(e.missing)throw new W(`${n}: ${t} is not installed here`);if(e.timedOut)throw new W(`${n}: ${t} did not finish within 10 minutes`);if(e.status!==0)throw new W(`${n}: ${(e.stderr||e.stdout||`exit ${e.status}`).split(`
|
|
1340
|
+
`).slice(-3).join(" ")}`);return e.stdout}function Zx(e,t){let n=a=>ze("git",["config",a],e,t).stdout,r=t.GIT_AUTHOR_NAME||n("user.name"),s=t.GIT_AUTHOR_EMAIL||n("user.email"),o=t.GITHUB_ACTIONS==="true"?{name:"github-actions[bot]",email:"41898282+github-actions[bot]@users.noreply.github.com"}:{name:"Saffron",email:"saffron@localhost"};return{...t,GIT_AUTHOR_NAME:r||o.name,GIT_AUTHOR_EMAIL:s||o.email,GIT_COMMITTER_NAME:t.GIT_COMMITTER_NAME||r||o.name,GIT_COMMITTER_EMAIL:t.GIT_COMMITTER_EMAIL||s||o.email}}var ji=(e,t)=>`${e} ${t}${e===1?"":"s"}`,Ws=e=>`\`${e.replaceAll("`","'")}\``,vl=e=>{let t=e.startsWith("-")?`./${e}`:e;return/^[\w./-]+$/.test(t)?t:`'${t.replaceAll("'","'\\''")}'`};function xl(e,t=""){let n=Math.max(0,...[...e.matchAll(/`+/g)].map(s=>s[0].length)),r="`".repeat(Math.max(3,n+1));return`${r}${t}
|
|
1318
1341
|
${e}
|
|
1319
|
-
${r}`}var
|
|
1320
|
-
`),"bash"),"","Then mark this pull request ready for review. `accept --all` leaves UNVERIFIED proposals out: read one, and accept it by file if it is right. `saffron accept` refuses a proposal whose scenario or recording changed since it was filed."],
|
|
1321
|
-
`).length;for(let[
|
|
1322
|
-
`)
|
|
1323
|
-
`);if(
|
|
1342
|
+
${r}`}var hh={github:6e4,azure:3800};function Qx(e,t,n,r="",s=hh.github){let{manifest:o,proposals:a}=t,i=o.run?o.url&&/^https?:\/\//i.test(o.url)?`[run ${o.run}](${o.url})`:`run ${Ws(o.run)}`:"a run",c=o.headCommit??o.commit,l=[o.branch&&`on ${Ws(o.branch)}`,c&&`at ${Ws(c.slice(0,7))}`].filter(Boolean).join(" "),d=[`Saffron filed ${ji(a.length,"proposal")} in ${i}${l?` ${l}`:""}. This pull request carries ${a.length===1?"the proposal, not the recording":"the proposals, not the recordings"}: nothing is accepted until you accept it.`,"","**To review and accept** (no agent runs on your machine):","",xl([`git fetch origin ${vl(n)} && git switch ${vl(n)}`,...r?[`cd ${vl(r.replace(/\/$/,""))}`]:[],"npx -y -p saffron-ai saffron diff","npx -y -p saffron-ai saffron accept --all",'git add -A .saffron/cache && git add -u .saffron/proposals && git commit -m "Accept Saffron proposals" && git push'].join(`
|
|
1343
|
+
`),"bash"),"","Then mark this pull request ready for review. `accept --all` leaves UNVERIFIED proposals out: read one, and accept it by file if it is right. `saffron accept` refuses a proposal whose scenario or recording changed since it was filed."],f=d.join(`
|
|
1344
|
+
`).length;for(let[p,{proposal:u}]of a.entries()){let{feature:h,scenario:b}=u.cache,{mode:g,verified:S,proofError:y,narrative:w,adaptations:v}=u.meta,x=S===!0?"**verified \u2713**: a zero-AI proof replay passed":S===!1?"**UNVERIFIED \u2717**: its proof replay failed":"not verified: proof replays were off",$=[w,...v.map(k=>`\u26A0 ${k}`),...S===!1&&y?[`Proof replay: ${y}`]:[]].filter(Boolean).join(`
|
|
1345
|
+
`),E=Mo(Nn(Jt(me(e,h,b)),u.cache,u.meta.featureEdits)),R=["",`### ${Ws(h)} \u203A ${Ws(b)}`,"",`${g==="heal"?"Heal":"First recording"}, ${x}`,"",...$?[xl($,"text"),""]:[],xl(E,"diff")].join(`
|
|
1346
|
+
`);if(f+R.length>s){d.push("",`\u2026and ${ji(a.length-p,"more proposal")}: run \`saffron diff\` on the branch to see ${a.length-p===1?"it":"them"}.`);break}d.push(R),f+=R.length+1}return`${d.join(`
|
|
1324
1347
|
`)}
|
|
1325
|
-
`}var
|
|
1326
|
-
`)[0]:String(
|
|
1327
|
-
`)}function
|
|
1328
|
-
`).slice(-2).join(" ")}`,failed:!0}:{...
|
|
1329
|
-
`).pop()}}import
|
|
1330
|
-
`)}function
|
|
1348
|
+
`}var Sl=e=>e.split(/[\\/]/).join("/");function Xx(e,t,n,r,s,o){let a=jt.mkdtempSync(Re.join(gh.tmpdir(),"saffron-head-")),i=h=>{let b=fh("git",["show",`${n}:${r}${Sl(h)}`],{cwd:e,env:s,timeout:6e5,maxBuffer:67108864});return b.status===0?b.stdout:void 0},c=h=>{let b=Re.relative(e,Re.resolve(e,h));return!b.startsWith("..")&&!Re.isAbsolute(b)?Sl(b):void 0},l=c(o.features??"features"),d=c(o.dataDir??"data"),f=fh("git",["ls-tree","-r","-z","--full-tree","--name-only",n,"--",...[l,d].flatMap(h=>h===void 0?[]:[`${r}${h}`||"."])],{cwd:e,env:s,encoding:"utf8",timeout:6e5,maxBuffer:64*1024*1024}),p=et(),u=[];try{for(let b of(l!==void 0||d!==void 0)&&f.status===0?f.stdout.split("\0").filter(Boolean):[]){let g=b.slice(r.length);if(!(d!==void 0&&(d===""||g.startsWith(`${d}/`)))&&!g.endsWith(".saffron"))continue;let y=i(g);y!==void 0&&(jt.mkdirSync(Re.dirname(Re.join(a,g)),{recursive:!0}),jt.writeFileSync(Re.join(a,g),y))}d!==void 0&&Mt(a,d,p.env);let h;try{h=ut(a,o,[])}catch(b){let g=`cannot be checked: the StepSets at ${n.slice(0,7)} do not parse: ${b instanceof Error?b.message.split(`
|
|
1349
|
+
`)[0]:String(b)}`;return t.proposals.map(({file:S})=>({file:S,reason:g}))}for(let{file:b,proposal:g}of t.proposals){let{feature:S,scenario:y}=g.cache,w=i(S);if(!w){u.push({file:b,reason:`is for ${S}, which is not in ${n.slice(0,7)}`});continue}jt.mkdirSync(Re.dirname(Re.join(a,S)),{recursive:!0}),jt.writeFileSync(Re.join(a,S),w);let v=Sl(Re.relative(e,me(e,S,y))),x=i(v);jt.rmSync(Re.join(a,v),{force:!0}),x&&(jt.mkdirSync(Re.dirname(Re.join(a,v)),{recursive:!0}),jt.writeFileSync(Re.join(a,v),x));let $;try{$=$t(a,g,h)}catch(E){$=`cannot be checked: ${E instanceof Error?E.message:String(E)}`}$&&u.push({file:b,reason:`does not fit ${n.slice(0,7)}: ${$}`})}}finally{d!==void 0&&Mt(e,p.dir,p.env),jt.rmSync(a,{recursive:!0,force:!0})}return u}function eS(e){let{manifest:t,proposals:n}=e;return[`Saffron: ${ji(n.length,"proposal")} to review${t.run?` from run ${t.run}`:""}`,"",...n.map(({proposal:r})=>`${r.cache.feature} \u203A ${r.cache.scenario} (${r.meta.mode}${r.meta.verified===!0?", verified":r.meta.verified===!1?", UNVERIFIED":""})`),"","Proposals only: nothing is accepted until someone runs saffron accept."].join(`
|
|
1350
|
+
`)}function Gs(e,t){if(t!==void 0&&/[$`;|&<>()\s'"\\]/.test(t))throw new W(`${e} ${JSON.stringify(t)}: a branch name with a space, a quote or any of $ \` ; | & < > ( ) \\ is not accepted, as the pull request gives it to a shell`)}function mh(e,t,n,r={}){let s=r.env??process.env,o=($,E,R={})=>ph(ze("git",E,e,R.env??s,R.input),"git",$),{manifest:a}=t;if(t.proposals.length===0)throw new W("there are no pending proposals to push");let i=r.base??a.branch;if(!i)throw new W("cannot tell which branch the pull request is for: pass --base <branch>");if(Zr(i),Zr(n),Gs("--branch",n),Gs("--base",r.base),n===i)throw new W(`--branch ${n} is the branch the proposals are for: name a new one, e.g. saffron/heal-<run id>`);if(n.startsWith("-"))throw new W(`${n} is not a branch name git accepts`);o(`${n} is not a branch name git accepts`,["check-ref-format","--branch",n]);let c=a.headCommit??a.commit;if(!c||!/^[0-9a-f]{40}([0-9a-f]{24})?$/i.test(c))throw new W("cannot tell which commit the run tested: run it in a git checkout");let l=o("not a git checkout",["rev-parse","HEAD"]);if(c!==l&&!yc(e,l).includes(c)&&ze("git",["merge-base","--is-ancestor",c,l],e,s).status!==0)throw new W(`${c.slice(0,7)}, the commit the branch would start on, is not this checkout's HEAD, a commit it merged or one it descends from: run export --branch in the checkout the run tested`);ze("git",["cat-file","-e",`${c}^{commit}`],e,s).status!==0&&o(`the commit to build on, ${c.slice(0,7)}, is not in this clone and could not be fetched`,["fetch","--quiet","--no-tags","--depth=1","origin",c]);let d=ze("git",["ls-remote","--exit-code","--heads","origin",`refs/heads/${n}`],e,s);if(d.status===0)throw new W(`branch ${n} already exists on origin: give each run its own, e.g. saffron/heal-<run id>-<attempt>`);d.status!==2&&ph(d,"git","cannot reach origin");let f=o("not a git checkout",["rev-parse","--show-prefix"]),p=Xx(e,t,c,f,s,r.config??{}),u={...t,proposals:t.proposals.filter($=>!p.some(E=>E.file===$.file))};if(u.proposals.length===0)throw new W(`no proposal fits ${c.slice(0,7)}, the commit the branch would start on: ${p.map($=>`${Re.relative(e,$.file)} ${$.reason}`).join("; ")}`);let h=jt.mkdtempSync(Re.join(gh.tmpdir(),"saffron-index-")),b={...s,GIT_INDEX_FILE:Re.join(h,"index")},g;try{o("cannot read the tested commit",["read-tree",c],{env:b});for(let{file:E,bytes:R}of u.proposals){let k=o("cannot store a proposal",["hash-object","-w","--stdin"],{input:R}),C=`${f}${Re.relative(e,E).split(Re.sep).join("/")}`;o("cannot stage a proposal",["update-index","--add","--cacheinfo",`100644,${k},${C}`],{env:b})}let $=o("cannot write the tree",["write-tree"],{env:b});g=o("cannot commit the proposals",["commit-tree",$,"-p",c,"-m",eS(u)],{env:Zx(e,s)})}finally{jt.rmSync(h,{recursive:!0,force:!0})}o(`cannot push ${n} to origin`,["push","--quiet","origin",`${g}:refs/heads/${n}`]);let S=a.repository?.startsWith("github.com/")?"github":a.repository?.startsWith("dev.azure.com/")?"azure":s.GITHUB_ACTIONS==="true"?"github":s.TF_BUILD==="True"?"azure":void 0,y=Re.join(Re.dirname(u.file),"saffron-pull-request.md");jt.writeFileSync(y,Qx(e,u,n,f,hh[S??"github"]));let w={branch:n,base:i,commit:g,parent:c,bodyFile:y,leftOut:p};if(!S)return{...w,noPullRequest:`${a.repository??"this repository"} is not on GitHub or Azure DevOps`};let v=`Saffron: ${ji(u.proposals.length,"proposal")} to review for ${i}`;if(S==="azure"){let $=uh(e,r.config??{},{branch:n,base:i,title:v,bodyFile:y},s);return $.problem?{...w,noPullRequest:$.problem,failed:!0}:$.url?{...w,pullRequest:$.url}:{...w,noPullRequest:"az created it but did not say where",failed:!0}}let x=ze("gh",["pr","create","--draft","--base",i,"--head",n,"--title",v,"--body-file",y],e,s);return x.missing?{...w,noPullRequest:"the gh CLI is not installed here",failed:!0}:x.status!==0?{...w,noPullRequest:`gh pr create failed: ${(x.stderr||x.stdout).split(`
|
|
1351
|
+
`).slice(-2).join(" ")}`,failed:!0}:{...w,pullRequest:x.stdout.split(`
|
|
1352
|
+
`).pop()}}import X from"node:fs";import re from"node:path";var Ks={claude:".claude/skills",agents:".agents/skills",copilot:".github/skills",cursor:".cursor/skills"},tS=["claude","agents"],bh="<!-- saffron:start -->",kl="<!-- saffron:end -->";function nS(){return[bh,"## Saffron end-to-end tests","","UI tests are plain-language `.feature` / `.saffron` files under `features/`,","run by Saffron (`npx saffron run`). No step definitions exist: an AI agent","records each scenario once; later runs replay at zero tokens.","","- Exact step text is the recording's identity: run `npx saffron steps` and"," reuse recorded wordings instead of inventing synonyms.","- `Then` steps are never healed: write them as the verdict, last.","- Never hand-edit `.saffron/cache/` or `.saffron/proposals/`; change the"," scenario text and re-run. Review with `npx saffron accept` / `reject`.","- Secrets only as `{env:VAR}` tokens, never in files or `data/`.","","When asked to create, translate, or edit Saffron scenarios in `.saffron`","or `.feature` files, load the `saffron` skill and follow its authoring","workflow: inspect the relevant UI, reuse recorded vocabulary, name","captures explicitly, and use observable waits and final assertions.","A working test requires reviewing its verified proposal and passing","the affected scenarios with `--no-agent`. For draft-only requests or","unavailable execution, report the validation still needed.","","This authoring workflow does not apply to ordinary application changes","or requests only to run tests, inspect reports, review proposals, or","configure Saffron. Never hand-edit generated caches or proposals to","make a test pass.",kl,""].join(`
|
|
1353
|
+
`)}function wh(e,t){if(!X.existsSync(e))return X.writeFileSync(e,t),"created";let n=X.readFileSync(e,"utf8"),r=n.indexOf(bh),s=n.indexOf(kl);if(r!==-1&&s!==-1&&s>r){let a=n.slice(0,r)+t.trimEnd()+n.slice(s+kl.length);return a===n?"unchanged":(X.writeFileSync(e,a),"updated")}let o=n.endsWith(`
|
|
1331
1354
|
`)?`
|
|
1332
1355
|
`:`
|
|
1333
1356
|
|
|
1334
|
-
`;return
|
|
1335
|
-
`),s?"updated":"created")}function
|
|
1336
|
-
`),n.scaffolded.push("saffron.config.json"));let{features:o}=
|
|
1337
|
-
`).some(
|
|
1357
|
+
`;return X.writeFileSync(e,n+o+t),"updated"}var $l={command:"npx",args:["saffron","mcp"]},rS={claude:{file:".mcp.json",key:"mcpServers",entry:$l},cursor:{file:".cursor/mcp.json",key:"mcpServers",entry:$l},copilot:{file:".vscode/mcp.json",key:"servers",entry:{type:"stdio",...$l}}},yh={agents:"codex mcp add saffron -- npx saffron mcp (Codex; other hosts: see their MCP settings)"};function sS(e,t){let n=re.join(e,t.file),r={},s=X.existsSync(n);if(s)try{r=JSON.parse(X.readFileSync(n,"utf8"))}catch{throw new Error(`${t.file} is not valid JSON: fix it or remove it, then re-run`)}let o=r[t.key]??{};return JSON.stringify(o.saffron)===JSON.stringify(t.entry)?"unchanged":(o.saffron=t.entry,r[t.key]=o,X.mkdirSync(re.dirname(n),{recursive:!0}),X.writeFileSync(n,JSON.stringify(r,null,2)+`
|
|
1358
|
+
`),s?"updated":"created")}function vh(e,t){X.mkdirSync(t,{recursive:!0});for(let n of X.readdirSync(e,{withFileTypes:!0})){let r=re.join(e,n.name),s=re.join(t,n.name);n.isDirectory()?vh(r,s):X.copyFileSync(r,s)}}function xh(e){let t=re.join(e.packageRoot,"skills","saffron");if(!X.existsSync(re.join(t,"SKILL.md")))throw new Error(`bundled skill not found at ${t}`);let n={skillDirs:[],instructionFiles:[],scaffolded:[],mcpFiles:[],mcpHints:[]},r=e.targets??tS;for(let s of r){let o=re.join(e.projectRoot,Ks[s],"saffron");X.existsSync(o)&&X.rmSync(o,{recursive:!0,force:!0}),vh(t,o),n.skillDirs.push(re.relative(e.projectRoot,o))}if(e.mcp!==!1)for(let s of r){let o=rS[s];o?n.mcpFiles.push({file:o.file,outcome:sS(e.projectRoot,o)}):yh[s]&&n.mcpHints.push(yh[s])}if(e.instructions!==!1){let s=nS(),o=re.join(e.projectRoot,"AGENTS.md");n.instructionFiles.push({file:"AGENTS.md",outcome:wh(o,s)});let a=re.join(e.projectRoot,"CLAUDE.md");X.existsSync(a)&&n.instructionFiles.push({file:"CLAUDE.md",outcome:wh(a,s)})}if(e.examples){n.examples=oS(e.projectRoot,e.packageRoot,Mi(e.projectRoot));for(let s of n.examples.files)n.scaffolded.push(s)}if(e.scaffold!==!1){let s=re.join(e.projectRoot,"saffron.config.json");X.existsSync(s)||(X.writeFileSync(s,JSON.stringify({baseURL:"http://localhost:3000",features:"features"},null,2)+`
|
|
1359
|
+
`),n.scaffolded.push("saffron.config.json"));let{features:o}=Mi(e.projectRoot),a=re.resolve(e.projectRoot,o);!X.existsSync(a)&&Sh(e.projectRoot,a)&&(X.mkdirSync(a,{recursive:!0}),n.scaffolded.push(`${o}/`));let i=re.join(e.projectRoot,".gitignore"),c=[".saffron/reports/",".saffron/artifacts/",".saffron/ci/",...e.examples?[".env"]:[]],l=X.existsSync(i)?X.readFileSync(i,"utf8"):"",d=[];for(let f of c)l.split(`
|
|
1360
|
+
`).some(p=>p.trim()===f)||(l+=(l&&!l.endsWith(`
|
|
1338
1361
|
`)?`
|
|
1339
|
-
`:"")+
|
|
1340
|
-
`,d.push(
|
|
1341
|
-
`),n.push(`saffron.config.json (+ ${
|
|
1342
|
-
`)}import{spawn as
|
|
1343
|
-
`))}function Op(e,t){let n=e.provider??"claude";return t===n?{model:e.model,healModel:e.healModel}:((e.model||e.healModel)&&console.error(`note: model and healModel in saffron.config.json name ${qn[n]??n} models; this ${qn[t]} run uses its default models (--model and --heal-model pick others).`),{})}function hc(e,t){let n=e??t??"claude";return Pu(n)||(console.error(`invalid provider "${n}": use ${La.map(r=>`"${r}"`).join(", ")}`),process.exit(2)),n}async function Ub(e){let t=Bb.createInterface({input:process.stdin,output:process.stdout});try{let n=await new Promise(r=>t.question(e,r));return/^y(es)?$/i.test(n.trim())}finally{t.close()}}function Jo(e){console.error(`saffron: ${e.message}`),process.exit(2)}function gc(e){return e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e4?`${(e/1e3).toFixed(1)}k`:e.toLocaleString()}var zb={green:"\x1B[32m",yellow:"\x1B[33m",red:"\x1B[31m"},Hb="\x1B[0m",Q=new Lb().name("saffron").description("AI-fallback test runner for end-to-end tests written in plain language: zero-token cached replay, runtime AI healing.").version(Xe()).option("-p, --project-root <dir>","project root",process.cwd());Q.command("run").description("Run feature files (cached replay; AI records/heals on demand)").argument("[paths...]",'feature files or directories (default: features/); file:line runs the scenario at that line, Cucumber-style (login.saffron:12, or :12:30 for two); file:name the scenario of that name ("login.saffron:Successful login")').option("--base-url <url>","base URL of the app under test").option("--env <name>","data environment: data/<file>.<name>.json is laid over data/<file>.json (also SAFFRON_ENV, or env in the config)").option("--headed","run the browser headed").option("--filter <tags>",'only run scenarios whose @tags match: a list ("@smoke,@WA-TC1" runs either) or an expression ("@e2e and not @wip", parentheses allowed); repeat the flag for "or"',gf).option("--no-agent","disable AI fallback (cache misses/failures go red)").option("--rerecord","discard the committed caches of the selected scenarios and let the agent record them fresh, over a pending proposal this machine did not file too (the honest fix for a wrong recording)").option("--provider <name>",'whose agent records and heals: "claude" (default), "codex", "antigravity" or "cursor", on its login on this machine').option("--model <model>","model for the agent").option("--storage-state <file>","Playwright storageState JSON for authenticated sessions").option("--strict","treat passed-with-adaptation (yellow) as failure until its proposal is reviewed").option("--no-verify","skip the zero-AI proof replay of agent recordings before filing proposals").option("--no-reuse","disable Level-1 step reuse (seeding new recordings from existing step recordings)").option("--browser <name>",'browser: "chromium" (default), "chrome", "msedge", "firefox" or "webkit". Recording and healing need one of the first three. A list ("chromium,firefox,webkit") runs the suite in each, into one report').option("--device <name>",'run under a Playwright device profile, e.g. "iPhone 15" or "Pixel 7"').option("--viewport <size>","viewport as WIDTHxHEIGHT, e.g. 1280x720 (over the device's)").option("--heal-model <model>","cheaper model for heal sessions").option("--workers <n>","parallel replay workers").option("--agent-workers <n>","agent sessions (recording, healing) that may run at once, each in a browser of its own (default 1)").option("--shard <index/total>","run one part of the suite, e.g. 2/4 on the second of four CI machines; combine the parts with `saffron report --merge`").option("--shard-by <mode>",'how --shard splits the suite: "scenario" (default, spreads every file) or "file" (each feature file stays on one machine)').option("--no-hooks","skip the setup and teardown commands from the config").option("--trace <mode>",'execution trace per scenario: "off" (default), "on" or "retain-on-failure"; open one with saffron trace').option("--assertion-policy <policy>",'assertion adaptability: "strict" (default) or "adaptable-mid" (mid-scenario assertions may be adapted; the final assertion block never is)').action(async(e,t)=>{let n=q.resolve(Q.opts().projectRoot),r=ye(n);t.env&&Ot(n,r.dataDir,t.env);let s=t.baseUrl??r.baseURL,o=hf(e),i=e.length===0?pc(n,r.features?[r.features]:[]):o.plain.length>0?pc(n,o.plain):[],a=[...o.picks.keys()].map(j=>q.resolve(n,j)),c=[...o.plain,...o.picks.keys()].find(j=>!ke.existsSync(q.resolve(n,j)));c!==void 0&&(console.error(`${c} does not exist (in ${n}).`),process.exit(2));let l=[...new Set([...i,...a])].sort();l.length===0&&(console.error("No .feature/.saffron files found."),process.exit(2));let d=l.find(j=>{let D=q.relative(n,j);return D.split(/[\\/]/)[0]===".."||q.isAbsolute(D)});d&&(console.error(`${d} is outside the project (${n}). Run saffron from the project that holds it, or point --project-root at it.`),process.exit(2));let u=hc(t.provider,r.provider),g=Op(r,u);t.agent!==!1&&Db(u);let f;try{let j=Ye(n,r,l);f=l.flatMap(D=>Ze(D,n,j))}catch(j){throw j instanceof Ee&&Jo(j),j}let p=f;if(e.length===0){let j=new Set(p.flatMap(D=>D.steps.flatMap(W=>W.session===void 0?[]:[W.session])));for(let D of Object.keys(r.sessions??{}))D===$t?console.warn(`saffron.config.json sets up the browser session "${$t}", which takes storageState (or --storage-state) like every scenario: "sessions" is for named sessions.`):j.has(D)||console.warn(`saffron.config.json sets up the browser session "${D}", and no step names it with As "${D}". Check the spelling.`)}let m=Pc(p.flatMap(j=>j.steps.flatMap(D=>D.session===void 0?[]:[D.session])),Object.keys(r.sessions??{}),t.storageState??r.storageState);if(m&&console.warn(m),o.picks.size>0)try{f=yf(f,n,o.picks,new Set(i))}catch(j){if(!(j instanceof zn))throw j;console.error(j.message),process.exit(2)}let h;try{h=uf(t.filter)}catch(j){if(!(j instanceof ss))throw j;console.error(`${j.message}. Write tags joined with and, or, not and parentheses: "@smoke and not @wip".`),process.exit(2)}if(h&&(f=pf(f,h),f.length===0&&(console.error(`No scenarios match --filter "${h.text}" in ${l.length} feature file(s).`),process.exit(2))),t.agent!==!1){let j=ee=>{try{let xe=He(fe(n,ee.featurePath,ee.name));return!!xe&&(lr(ee,xe)||cr(ee,xe)!==void 0)}catch{return!1}},D=f.filter(ee=>t.rerecord||!j(ee)),W=mf(D,p).filter(ee=>!f.includes(ee));W.length>0&&(console.log(`${W.length} more Examples row(s) share a recording this run ${t.rerecord?"replaces":"records"}, and run to replay it`),f=[...f,...W])}let w=(()=>{let j=t.browser??r.browser??"chromium",D=(Array.isArray(j)?j:String(j).split(",")).map(ee=>String(ee).trim()).filter(Boolean),W=D.find(ee=>!Yf(ee));return(W!==void 0||D.length===0)&&(console.error(`invalid --browser "${W??""}": use ${_a.map(ee=>`"${ee}"`).join(", ")}, or a list of them`),process.exit(2)),[...new Set(D)].sort((ee,xe)=>+!wr(ee)-+!wr(xe))})(),b=w.length>1,y;if(t.shardBy!==void 0&&t.shard===void 0&&(console.error("saffron: --shard-by needs --shard, e.g. --shard 2/4 --shard-by file"),process.exit(2)),t.shard!==void 0){try{let j=Id(String(t.shardBy??r.shardBy??"scenario")),D=jd(f,{...Od(String(t.shard)),by:j});if(f=D.scenarios,b)throw new Error("saffron: a browser matrix and --shard do not mix: give each shard job one --browser (a CI matrix runs them side by side)");y={...D.info,ciRun:co(),attempt:lo(),browser:w[0]}}catch(j){console.error(j instanceof Error?j.message:String(j)),process.exit(2)}if(console.log(`shard ${y.index}/${y.total}${y.by==="file"?" (by file)":""}: ${f.length} of ${y.suiteSize} scenario(s)`),f.length===0){let j=new Date,D=Xi([],j,s),W=Gi([],j,Nt(n).divergent.length,s);console.log(`report: ${oa(n,{...D,shard:y,history:W})}`),process.exit(0)}}t.rerecord&&t.agent===!1&&(console.error("saffron: --rerecord needs the agent; drop --no-agent"),process.exit(2));{let j=f;try{let W=[...new Set([...pc(n,r.features?[r.features]:[]),...l])],ee=Ye(n,r,W);j=W.flatMap(xe=>{try{return Ze(xe,n,ee)}catch{return[]}})}catch{}let D=ol(n,j);if(D.length>0){console.error("cache path collision:");for(let W of D)console.error(` ${W}`);process.exit(2)}}{let j=new Map;for(let W of f)for(let ee of We(W))process.env[ee]===void 0&&!j.has(ee)&&j.set(ee,W.displayName);let D=new Map;for(let W of f)for(let ee of Gt(st(W)))if(!D.has(ee))try{ks(ee)}catch(xe){D.set(ee,`${xe instanceof Error?xe.message:String(xe)} (used by "${W.displayName}")`)}if(D.size>0){for(let W of D.values())console.error(W);process.exit(2)}if(j.size>0){for(let[W,ee]of j)console.error(`missing environment variable ${W} (referenced as {env:${W}} by "${ee}")`);console.error("set the variable(s), or add them to a git-ignored .env in the project root"),process.exit(2)}}let S=[],x=[];if(t.hooks!==!1)try{S=Wa(r.setup,"setup"),x=Wa(r.teardown,"teardown")}catch(j){console.error(j instanceof Error?j.message:String(j)),process.exit(2)}let C=t.device??r.device,$=C===void 0?void 0:String(C);if($!==void 0&&(typeof C!="string"||!Pa.includes($))){let j=Pa.filter(D=>D.toLowerCase().includes($.toLowerCase().split(" ")[0])).slice(0,8);console.error(`unknown --device "${$}". ${j.length>0?`Close: ${j.map(D=>`"${D}"`).join(", ")}`:'Use a Playwright device name, e.g. "iPhone 15", "Pixel 7" or "Desktop Chrome"'}`),process.exit(2)}let k=t.viewport??r.viewport,R=k===void 0?void 0:Zf(String(k));k!==void 0&&!R&&(console.error(`invalid --viewport "${k}": use WIDTHxHEIGHT, e.g. 1280x720`),process.exit(2));let _=j=>Math.max(1,Number.parseInt(String(j??1),10)||1),v=_(t.workers??r.workers),A=_(t.agentWorkers??r.agentWorkers),O=t.agent?Ou(u,{model:t.model??g.model,maxTurns:r.maxTurns,snapshotMode:r.snapshotMode}):void 0,P=(()=>{let j=t.trace??r.trace??"off";return Ci.includes(j)||(console.error(`invalid --trace "${j}": use ${Ci.map(D=>`"${D}"`).join(", ")}`),process.exit(2)),j})(),E=(()=>{let j=t.assertionPolicy??r.assertionPolicy??"strict";return j!=="strict"&&j!=="adaptable-mid"&&(console.error(`invalid --assertion-policy "${j}": use "strict" or "adaptable-mid"`),process.exit(2)),j})(),T=new Map,M=j=>new xo({filedThisRun:T,projectRoot:n,baseURL:s,headed:t.headed,actionTimeoutMs:r.actionTimeoutMs,pollIntervalMs:r.pollIntervalMs,screenshot:r.screenshot,trace:P,retries:r.retries,storageState:t.storageState??r.storageState,sessions:r.sessions,browser:j,device:$,viewport:R,artifactsPerBrowser:b,healModel:t.healModel??g.healModel,rerecord:t.rerecord===!0,verifyProposals:t.verify===!1?!1:r.verifyProposals,reuseSteps:t.reuse===!1?!1:r.reuseSteps,assertionPolicy:E,agent:O}),I=new Set,F=async j=>{let D=M(j);return I.add(D),await D.start(),D},z=async j=>{for(let D of[...j])I.delete(D),await D.stop()},N=new Date,L=[],G=new Map,U=new Map,Y=async(j,D,W,ee,xe)=>{let Vt=b?`${D} \xB7 ${W}`:W,St=Date.now(),ie=await j.runScenario(ee,xe),qe=Date.now(),Be=G.get(Vt)??{worker:Vt,runs:0,busyMs:0,spanMs:0,browser:D};G.set(Vt,Be),Be.runs++,Be.busyMs+=qe-St;let Jt=U.get(D)??{first:St,last:qe};return U.set(D,{first:Math.min(Jt.first,St),last:Math.max(Jt.last,qe)}),ie.worker=Vt,ie.browser=D,ie},V=j=>{let D=j.scenario,W=zb[j.status],ee=j.usage.inputTokens+j.usage.outputTokens,xe=j.usage.cacheReadTokens+j.usage.cacheCreationTokens,Vt=xe>0?`, ${gc(xe)} cache traffic`:"";console.log(`${W}${j.status.toUpperCase().padEnd(7)}${Hb}${D.displayName}${b?` [${j.browser}]`:""} (${j.source}, ${j.durationMs}ms, ${j.usage.aiCalls} AI calls, ${ee} tokens${Vt})`);for(let ie of j.adaptations)console.log(` \u26A0 ${ie}`);j.status==="yellow"&&j.usage.aiCalls===0&&j.narrative&&console.log(` ${j.narrative}`),j.seededSteps&&console.log(` \u26A1 ${j.seededSteps}/${j.stepResults.length} steps seeded from existing recordings (zero AI)`);let St=j.stepResults.reduce((ie,qe)=>ie+(qe.retries??0),0);St&&console.log(` \u21BB ${St} action ${St===1?"retry":"retries"} absorbed before settling (retries: ${r.retries??1} per action)`),j.verified===!0?console.log(" \u2713 proposal verified by zero-AI proof replay"):j.verified===!1&&console.log(` \u2717 proposal UNVERIFIED, proof replay failed: ${j.proofError?.split(`
|
|
1344
|
-
`)[0]}`),
|
|
1345
|
-
|
|
1346
|
-
|
|
1347
|
-
${
|
|
1348
|
-
|
|
1349
|
-
|
|
1350
|
-
|
|
1351
|
-
`)[0
|
|
1352
|
-
`)[0]
|
|
1353
|
-
|
|
1354
|
-
|
|
1355
|
-
`)
|
|
1356
|
-
`))});
|
|
1362
|
+
`:"")+f+`
|
|
1363
|
+
`,d.push(f));d.length>0&&(X.writeFileSync(i,l),n.scaffolded.push(`.gitignore (+ ${d.join(", ")})`))}return n}function Mi(e){let t={};try{t=JSON.parse(X.readFileSync(re.join(e,"saffron.config.json"),"utf8"))}catch{}let n=(r,s)=>typeof r=="string"&&r.trim()?r.trim().replace(/(.)[\\/]+$/,"$1"):s;return{features:n(t?.features,"features"),data:n(t?.dataDir,"data")}}function Sh(e,t){let n=re.relative(re.resolve(e),re.resolve(t));return n===""||n!==".."&&!n.startsWith(".."+re.sep)&&!re.isAbsolute(n)}function oS(e,t,n={features:"features",data:"data"}){let r=re.join(t,"templates","saucedemo");if(!X.existsSync(re.join(r,"features")))return{installed:!1,files:[],reason:`bundled examples not found at ${r}`};let s=re.resolve(e,n.features),o=re.resolve(e,n.data);for(let[f,p]of[[s,n.features],[o,n.data]]){if(!Sh(e,f))return{installed:!1,files:[],reason:`${p} is outside the project; examples are only installed inside it`};if(X.existsSync(f)&&!X.statSync(f).isDirectory())return{installed:!1,files:[],reason:`${p} is a file, not a folder; examples are installed into a folder`}}if(X.existsSync(s)&&X.readdirSync(s).length>0)return{installed:!1,files:[],reason:`${n.features}/ is not empty; examples are only installed into an empty features directory`};let a=[];X.mkdirSync(s,{recursive:!0});for(let f of X.readdirSync(re.join(r,"features")))X.copyFileSync(re.join(r,"features",f),re.join(s,f)),a.push(`${n.features}/${f}`);let i=re.join(r,"data");if(X.existsSync(i)){X.mkdirSync(o,{recursive:!0});for(let f of X.readdirSync(i)){let p=re.join(o,f);X.existsSync(p)||(X.copyFileSync(re.join(i,f),p),a.push(`${n.data}/${f}`))}}let c=re.join(e,"saffron.config.json"),l;X.existsSync(c)?l=iS(c,re.join(r,"saffron.config.json"),a):(X.copyFileSync(re.join(r,"saffron.config.json"),c),a.push("saffron.config.json (baseURL https://www.saucedemo.com, retries 1)"));let d=re.join(e,".env.example");return X.existsSync(d)||(X.copyFileSync(re.join(r,".env.example"),d),a.push(".env.example")),{installed:!0,files:a,...l?{note:l}:{}}}function iS(e,t,n){let r;try{r=JSON.parse(X.readFileSync(e,"utf8"))}catch{return}if(!r||typeof r!="object"||Array.isArray(r))return;let s=JSON.parse(X.readFileSync(t,"utf8")),o=s.baseURL;if(r.baseURL!==void 0)return r.baseURL===o?void 0:`the examples target ${o}, but saffron.config.json keeps your baseURL ${String(r.baseURL)}; set "baseURL": "${o}" to run them`;let a=Object.keys(s).filter(i=>i!=="features"&&!(i in r));for(let i of a)r[i]=s[i];X.writeFileSync(e,JSON.stringify(r,null,2)+`
|
|
1364
|
+
`),n.push(`saffron.config.json (+ ${a.map(i=>`${i} ${String(s[i])}`).join(", ")})`)}import aS from"node:path";function $h(e){return["saffron lsp is a language server: it speaks LSP over stdio and is meant","to be launched by your editor, not run by hand (nothing happens here).","","JetBrains (IntelliJ, WebStorm, PyCharm, Rider, incl. Community):"," Easiest: install the Saffron plugin from the JetBrains Marketplace"," (https://plugins.jetbrains.com/plugin/34240-saffron): highlighting,"," this language server, run configurations and the Saffron tool window,"," in one click. Manual setup instead:"," 1. Completion, diagnostics, hover, go-to-definition: install the free"," LSP4IJ plugin, then Settings \u2192 Languages & Frameworks \u2192 Language"," Servers \u2192 +: command `npx saffron lsp`, working dir = project root,"," file patterns *.saffron and *.feature."," 2. Syntax highlighting comes from a TextMate bundle, not the LSP:"," Settings \u2192 Editor \u2192 TextMate Bundles \u2192 + and pick this folder:",` ${e?aS.join(e,"textmate","saffron"):"node_modules/saffron-ai/textmate/saffron"}`,"","Neovim / other LSP editors: cmd = { 'npx', 'saffron', 'lsp' },","filetypes = { 'saffron', 'feature' }.","","VS Code: install the extension instead:"," code --install-extension ChathurangaJayasinghe.saffron-vscode"].join(`
|
|
1365
|
+
`)}import{spawn as cS}from"node:child_process";function lS(e,t=process.platform){return t==="win32"?{command:'start "" "%SAFFRON_BROWSER_TARGET%"',args:[],options:{detached:!0,stdio:"ignore",shell:!0,windowsHide:!0,env:{...process.env,SAFFRON_BROWSER_TARGET:e}}}:{command:t==="darwin"?"open":"xdg-open",args:[e],options:{detached:!0,stdio:"ignore"}}}function Ys(e){let{command:t,args:n,options:r}=lS(e),s=t.split(" ")[0],o=cS(t,n,r);o.on("error",()=>console.error(`Could not open a browser (${s} is not available here). Open the address above yourself.`)),o.unref()}function Rl(e,t){let n=t.length>0?t:["features"],r=[];for(let s of n){let o=G.isAbsolute(s)?s:G.join(e,s);Fe.existsSync(o)&&(Fe.statSync(o).isDirectory()?r.push(...an(o,on)):on(o)&&r.push(o))}return r.sort()}function fS(e){let t=Xc(e);t.length!==0&&console.error([`note: the ${yn[e]} agent is not set up here. Cached scenarios replay fine`,"without AI, but recording and healing need:",...t.map(n=>` \xB7 ${n}`),"Replay-only runs: add --no-agent to silence this note.",""].join(`
|
|
1366
|
+
`))}function kh(e,t){let n=e.provider??"claude";return t===n?{model:e.model,healModel:e.healModel}:((e.model||e.healModel)&&console.error(`note: model and healModel in saffron.config.json name ${yn[n]??n} models; this ${yn[t]} run uses its default models (--model and --heal-model pick others).`),{})}function Al(e,t){let n=e??t??"claude";return $g(n)||(console.error(`invalid provider "${n}": use ${Zc.map(r=>`"${r}"`).join(", ")}`),process.exit(2)),n}async function pS(e){let t=dS.createInterface({input:process.stdin,output:process.stdout});try{let n=await new Promise(r=>t.question(e,r));return/^y(es)?$/i.test(n.trim())}finally{t.close()}}function Di(e){console.error(`saffron: ${e.message}`),process.exit(2)}function Tl(e){return e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e4?`${(e/1e3).toFixed(1)}k`:e.toLocaleString()}var gS={green:"\x1B[32m",yellow:"\x1B[33m",red:"\x1B[31m"},hS="\x1B[0m",te=new uS().name("saffron").description("AI-fallback test runner for end-to-end tests written in plain language: zero-token cached replay, runtime AI healing.").version(ot()).option("-p, --project-root <dir>","project root",process.cwd());te.command("run").description("Run feature files (cached replay; AI records/heals on demand)").argument("[paths...]",'feature files or directories (default: features/); file:line runs the scenario at that line, Cucumber-style (login.saffron:12, or :12:30 for two); file:name the scenario of that name ("login.saffron:Successful login")').option("--base-url <url>","base URL of the app under test").option("--env <name>","data environment: data/<file>.<name>.json is laid over data/<file>.json (also SAFFRON_ENV, or env in the config)").option("--headed","run the browser headed").option("--filter <tags>",'only run scenarios whose @tags match: a list ("@smoke,@WA-TC1" runs either) or an expression ("@e2e and not @wip", parentheses allowed); repeat the flag for "or"',Zf).option("--no-agent","disable AI fallback (cache misses/failures go red)").option("--rerecord","discard the committed caches of the selected scenarios and let the agent record them fresh, over a pending proposal this machine did not file too (the honest fix for a wrong recording)").option("--provider <name>",'whose agent records and heals: "claude" (default), "codex", "antigravity" or "cursor", on its login on this machine').option("--model <model>","model for the agent").option("--storage-state <file>","Playwright storageState JSON for authenticated sessions").option("--strict","treat passed-with-adaptation (yellow) as failure until its proposal is reviewed").option("--no-verify","skip the zero-AI proof replay of agent recordings before filing proposals").option("--no-reuse","disable Level-1 step reuse (seeding new recordings from existing step recordings)").option("--browser <name>",'browser: "chromium" (default), "chrome", "msedge", "firefox" or "webkit". Recording and healing need one of the first three. A list ("chromium,firefox,webkit") runs the suite in each, into one report').option("--device <name>",'run under a Playwright device profile, e.g. "iPhone 15" or "Pixel 7"').option("--viewport <size>","viewport as WIDTHxHEIGHT, e.g. 1280x720 (over the device's)").option("--heal-model <model>","cheaper model for heal sessions").option("--workers <n>","parallel replay workers").option("--agent-workers <n>","agent sessions (recording, healing) that may run at once, each in a browser of its own (default 1)").option("--shard <index/total>","run one part of the suite, e.g. 2/4 on the second of four CI machines; combine the parts with `saffron report --merge`").option("--shard-by <mode>",'how --shard splits the suite: "scenario" (default, spreads every file) or "file" (each feature file stays on one machine)').option("--no-hooks","skip the setup and teardown commands from the config").option("--trace <mode>",'execution trace per scenario: "off" (default), "on" or "retain-on-failure"; open one with saffron trace').option("--assertion-policy <policy>",'assertion adaptability: "strict" (default) or "adaptable-mid" (mid-scenario assertions may be adapted; the final assertion block never is)').action(async(e,t)=>{let n=G.resolve(te.opts().projectRoot),r=Ee(n);t.env&&Mt(n,r.dataDir,t.env);let s=t.baseUrl??r.baseURL,o=Qf(e),a=e.length===0?Rl(n,r.features?[r.features]:[]):o.plain.length>0?Rl(n,o.plain):[],i=[...o.picks.keys()].map(D=>G.resolve(n,D)),c=[...o.plain,...o.picks.keys()].find(D=>!Fe.existsSync(G.resolve(n,D)));c!==void 0&&(console.error(`${c} does not exist (in ${n}).`),process.exit(2));let l=[...new Set([...a,...i])].sort();l.length===0&&(console.error("No .feature/.saffron files found."),process.exit(2));let d=l.find(D=>{let q=G.relative(n,D);return q.split(/[\\/]/)[0]===".."||G.isAbsolute(q)});d&&(console.error(`${d} is outside the project (${n}). Run saffron from the project that holds it, or point --project-root at it.`),process.exit(2));let f=Al(t.provider,r.provider),p=kh(r,f);t.agent!==!1&&fS(f);let u;try{let D=ut(n,r,l);u=l.flatMap(q=>ft(q,n,D))}catch(D){throw D instanceof Le&&Di(D),D}let h=u;if(e.length===0){let D=new Set(h.flatMap(q=>q.steps.flatMap(Y=>Y.session===void 0?[]:[Y.session])));for(let q of Object.keys(r.sessions??{}))q===Ft?console.warn(`saffron.config.json sets up the browser session "${Ft}", which takes storageState (or --storage-state) like every scenario: "sessions" is for named sessions.`):D.has(q)||console.warn(`saffron.config.json sets up the browser session "${q}", and no step names it with As "${q}". Check the spelling.`)}let b=ql(h.flatMap(D=>D.steps.flatMap(q=>q.session===void 0?[]:[q.session])),Object.keys(r.sessions??{}),t.storageState??r.storageState);if(b&&console.warn(b),o.picks.size>0)try{u=tp(u,n,o.picks,new Set(a))}catch(D){if(!(D instanceof dr))throw D;console.error(D.message),process.exit(2)}let g;try{g=Kf(t.filter)}catch(D){if(!(D instanceof Cs))throw D;console.error(`${D.message}. Write tags joined with and, or, not and parentheses: "@smoke and not @wip".`),process.exit(2)}if(g&&(u=Yf(u,g),u.length===0&&(console.error(`No scenarios match --filter "${g.text}" in ${l.length} feature file(s).`),process.exit(2))),t.agent!==!1){let D=J=>{try{let de=st(me(n,J.featurePath,J.name));return!!de&&(Mr(J,de)||Fn(J,de)!==void 0)}catch{return!1}},q=u.filter(J=>t.rerecord||!D(J)),Y=Xf(q,h).filter(J=>!u.includes(J));Y.length>0&&(console.log(`${Y.length} more Examples row(s) share a recording this run ${t.rerecord?"replaces":"records"}, and run to replay it`),u=[...u,...Y])}let S=(()=>{let D=t.browser??r.browser??"chromium",q=(Array.isArray(D)?D:String(D).split(",")).map(J=>String(J).trim()).filter(Boolean),Y=q.find(J=>!Up(J));return(Y!==void 0||q.length===0)&&(console.error(`invalid --browser "${Y??""}": use ${zc.map(J=>`"${J}"`).join(", ")}, or a list of them`),process.exit(2)),[...new Set(q)].sort((J,de)=>+!ur(J)-+!ur(de))})(),y=S.length>1,w;if(t.shardBy!==void 0&&t.shard===void 0&&(console.error("saffron: --shard-by needs --shard, e.g. --shard 2/4 --shard-by file"),process.exit(2)),t.shard!==void 0){try{let D=wf(String(t.shardBy??r.shardBy??"scenario")),q=yf(u,{...mf(String(t.shard)),by:D});if(u=q.scenarios,y)throw new Error("saffron: a browser matrix and --shard do not mix: give each shard job one --browser (a CI matrix runs them side by side)");w={...q.info,ciRun:Ko(),attempt:Yo(),browser:S[0]}}catch(D){console.error(D instanceof Error?D.message:String(D)),process.exit(2)}if(console.log(`shard ${w.index}/${w.total}${w.by==="file"?" (by file)":""}: ${u.length} of ${w.suiteSize} scenario(s)`),u.length===0){let D=new Date,q=cc([],D,s),Y=nc([],D,Wt(n).divergent.length,s);console.log(`report: ${gc(n,{...q,shard:w,history:Y})}`),process.exit(0)}}t.rerecord&&t.agent===!1&&(console.error("saffron: --rerecord needs the agent; drop --no-agent"),process.exit(2)),t.rerecord&&!S.some(ur)&&(console.error(`saffron: --rerecord needs a browser that can record (chromium, chrome or msedge); ${S.join(", ")} only replay`),process.exit(2));let v=t.rerecord?Ti(f):[];v.length>0&&(console.error(`saffron: --rerecord needs the agent, and ${yn[f]} cannot start here: ${v.join("; ")}`),process.exit(2));{let D=u;try{let Y=[...new Set([...Rl(n,r.features?[r.features]:[]),...l])],J=ut(n,r,Y);D=Y.flatMap(de=>{try{return ft(de,n,J)}catch{return[]}})}catch{}let q=jd(n,D);if(q.length>0){console.error("cache path collision:");for(let Y of q)console.error(` ${Y}`);process.exit(2)}}let x=[],$=[];if(t.hooks!==!1)try{x=ol(r.setup,"setup"),$=ol(r.teardown,"teardown")}catch(D){console.error(D instanceof Error?D.message:String(D)),process.exit(2)}let E=t.device??r.device,R=E===void 0?void 0:String(E);if(R!==void 0&&(typeof E!="string"||!Hc.includes(R))){let D=Hc.filter(q=>q.toLowerCase().includes(R.toLowerCase().split(" ")[0])).slice(0,8);console.error(`unknown --device "${R}". ${D.length>0?`Close: ${D.map(q=>`"${q}"`).join(", ")}`:'Use a Playwright device name, e.g. "iPhone 15", "Pixel 7" or "Desktop Chrome"'}`),process.exit(2)}let k=t.viewport??r.viewport,C=k===void 0?void 0:zp(String(k));k!==void 0&&!C&&(console.error(`invalid --viewport "${k}": use WIDTHxHEIGHT, e.g. 1280x720`),process.exit(2));let P=D=>Math.max(1,Number.parseInt(String(D??1),10)||1),m=P(t.workers??r.workers),A=P(t.agentWorkers??r.agentWorkers),O=t.agent?kg(f,{model:t.model??p.model,maxTurns:r.maxTurns,snapshotMode:r.snapshotMode}):void 0,T=(D,q)=>D!==void 0?{name:D,source:"flag"}:q!==void 0?{name:q,source:"config"}:void 0,_=Rg[f],N=_&&Gd(_),F=O?{provider:f,model:T(t.model,p.model),healModel:T(t.healModel,p.healModel),..._&&N?{sdk:{name:_,version:N}}:{}}:{},I=(()=>{let D=t.trace??r.trace??"off";return _a.includes(D)||(console.error(`invalid --trace "${D}": use ${_a.map(q=>`"${q}"`).join(", ")}`),process.exit(2)),D})(),L=(()=>{let D=t.assertionPolicy??r.assertionPolicy??"strict";return D!=="strict"&&D!=="adaptable-mid"&&(console.error(`invalid --assertion-policy "${D}": use "strict" or "adaptable-mid"`),process.exit(2)),D})(),j=new Map,H={},Z=D=>new di({filedThisRun:j,agentHalt:H,projectRoot:n,baseURL:s,headed:t.headed,actionTimeoutMs:r.actionTimeoutMs,pollIntervalMs:r.pollIntervalMs,screenshot:r.screenshot,trace:I,retries:r.retries,storageState:t.storageState??r.storageState,sessions:r.sessions,browser:D,device:R,viewport:C,timezone:r.timezone,artifactsPerBrowser:y,healModel:t.healModel??p.healModel,rerecord:t.rerecord===!0,verifyProposals:t.verify===!1?!1:r.verifyProposals,reuseSteps:t.reuse===!1?!1:r.reuseSteps,assertionPolicy:L,agent:O}),Q=new AbortController,M=()=>new Promise(()=>{}),U=new Set,z=async D=>{if(Q.signal.aborted)return M();let q=Z(D);return U.add(q),await q.start(),q},V=async D=>{for(let q of[...D])U.delete(q),await q.stop()},ee=new Date,Ie=[],Ke=new Map,Ne=new Map,Te=async(D,q,Y,J,de)=>{if(Q.signal.aborted)return M();let At=y?`${q} \xB7 ${Y}`:Y,Xe=Date.now(),oe;try{oe=await D.runScenario(J,de)}catch(zi){if(Q.signal.aborted)return M();throw zi}if(Q.signal.aborted)return M();let He=Date.now(),je=Ke.get(At)??{worker:At,runs:0,busyMs:0,spanMs:0,browser:q};Ke.set(At,je),je.runs++,je.busyMs+=He-Xe;let ye=Ne.get(q)??{first:Xe,last:He};return Ne.set(q,{first:Math.min(ye.first,Xe),last:Math.max(ye.last,He)}),oe.worker=At,oe.browser=q,oe},qt=D=>{let q=D.scenario,Y=gS[D.status],J=D.usage.inputTokens+D.usage.outputTokens,de=D.usage.cacheReadTokens+D.usage.cacheCreationTokens,At=de>0?`, ${Tl(de)} cache traffic`:"";console.log(`${Y}${D.status.toUpperCase().padEnd(7)}${hS}${q.displayName}${y?` [${D.browser}]`:""} (${D.source}, ${D.durationMs}ms, ${D.usage.aiCalls} AI calls, ${J} tokens${At})`);for(let oe of D.adaptations)console.log(` \u26A0 ${oe}`);D.status==="yellow"&&D.usage.aiCalls===0&&D.narrative&&console.log(` ${D.narrative}`),D.seededSteps&&console.log(` \u26A1 ${D.seededSteps}/${D.stepResults.length} steps seeded from existing recordings (zero AI)`);let Xe=D.stepResults.reduce((oe,He)=>oe+(He.retries??0),0);Xe&&console.log(` \u21BB ${Xe} action ${Xe===1?"retry":"retries"} absorbed before settling (retries: ${r.retries??1} per action)`),D.verified===!0?console.log(" \u2713 proposal verified by zero-AI proof replay"):D.verified===!1&&console.log(` \u2717 proposal UNVERIFIED, proof replay failed: ${D.proofError?.split(`
|
|
1367
|
+
`)[0]}`),D.error&&console.log(` ${D.error}`)};console.log(`saffron-ai ${ot()} \xB7 ${Ho(F,yn[f])}`);let at={cwd:n,timeoutMs:r.hookTimeoutMs??Er.hookTimeoutMs,env:{SAFFRON_BASE_URL:s,SAFFRON_ENV:et().env,SAFFRON_SHARD:w?`${w.index}/${w.total}`:void 0}},Sn=[],Ph,yr=()=>Ph??=il("teardown",$,at).then(D=>{Sn.push(...D)}),Fi=Promise.resolve([]),El=!1,Li=o.picks.size>0,_l=async D=>{El=!0;let q=D.flat().filter(we=>we!==void 0),Y=u.length*S.length-q.length,J=cc(q,ee,s);if(Y>0&&Object.assign(J,{interrupted:!0,notRun:Y}),J.provenance=F,Sn.length>0&&(J.hooks=Sn),Ke.size>0){let we=[...Ne.values()];J.timing={wallMs:Math.max(...we.map(ct=>ct.last))-Math.min(...we.map(ct=>ct.first)),workers:[...Ke.values()].sort((ct,tn)=>S.indexOf(ct.browser)-S.indexOf(tn.browser)||ct.worker.localeCompare(tn.worker,void 0,{numeric:!0})).map(({browser:ct,...tn})=>({...tn,spanMs:Ne.get(ct).last-Ne.get(ct).first}))}}y&&(J.browsers=S);let de=Wt(n).divergent.length,At=Li||Y>0,Xe={...nc(q,ee,de,s),...At?{partial:!0}:{}};w||(At||(J.trends=sc(vs(n),Xe)),rc(n,Xe)),J.totals.aiCalls>0&&(J.totals.plan=await O?.planUsage?.());let oe,He=!1,je=0;if(w){let we=w.positions.filter(($S,jh)=>D[0]?.[jh]!==void 0),ct=gc(n,{...J,shard:{...w,positions:we},history:Xe}),tn=ct.replace(/\.json$/,".html");Fe.writeFileSync(tn,Ln(J,n)),oe=`${tn}
|
|
1368
|
+
${ct}`}else{let we=Li?fc(uc(n),J):J;He=we!==J,je=we.scenarios.length-J.scenarios.length;let{html:ct,json:tn}=Ts(n,we);oe=`${ct}
|
|
1369
|
+
${tn}`}let ye=J.totals,zi=ye.cacheReadTokens+ye.cacheCreationTokens;console.log(`
|
|
1370
|
+
${ye.green} passed, ${rf(ye.yellow,J.scenarios.filter(nr).length)}, ${ye.red} failed \xB7 ${ye.aiCalls} AI calls \xB7 ${(ye.inputTokens+ye.outputTokens).toLocaleString()} tokens in+out${zi>0?` \xB7 ${Tl(ye.cacheReadTokens)} cache read \xB7 ${Tl(ye.cacheCreationTokens)} cache written`:""}${Ya(ye)}${ye.models?.length?` \xB7 ${ye.models.join(", ")}`:""}`);let Xr=J.timing;Xr&&Xr.workers.length>1&&Xr.wallMs>0&&console.log(`workers over ${Qe(Xr.wallMs)}: ${Xr.workers.map(we=>`${we.worker} ${ic(we)} busy`).join(" \xB7 ")}`),J.scenarios.length>3&&console.log(`slowest: ${oc(J,3).map(we=>`${we.scenario}${J.browsers&&we.browser?` [${we.browser}]`:""} ${Qe(we.durationMs)}`).join(" \xB7 ")}`);let Hi=J.trends;Hi?.prev&&console.log(Za(Hi.prev));for(let we of Hi?.chronic??[])console.log(`\u26A0 chronic: ${we.feature} \u203A ${we.scenario}: ${we.heals} heal(s), ${we.reds} red(s) in last ${we.runs} run(s); re-record or fix the feature text instead of paying for more heals`);return Y>0&&console.log(`interrupted: the report is partial. ${q.length} scenario(s) finished; ${Y} did not run, and count as neither passed nor failed`),console.log(`report: ${oe}`),Li&&!w&&console.log(Ah(He,je)),w&&console.log(`shard report, not a whole run: history and trends wait for \`saffron report --merge\` over all ${w.total} shard-*-of-${w.total}.json files`),J};process.on("SIGINT",()=>{if(El){console.error(`
|
|
1371
|
+
the report is being written, then Saffron exits`);return}if(Q.signal.aborted){console.error($.length>0?"still cleaning up: teardown finishes, then Saffron exits":"still stopping: Saffron writes the report, then exits");return}let D=Ie.map(q=>Array.from(q));console.error(`
|
|
1372
|
+
interrupted: stopping${$.length>0?", then running teardown":""}, then writing the report of what finished`),Q.abort(),Fi.then(()=>V(U)).catch(()=>{}).then(yr).then(async()=>{D.flat().some(q=>q!==void 0)?await _l(D):console.log("interrupted before any scenario finished: the last report and history were kept as they were")}).catch(q=>console.error(`saffron: the report was not written: ${q instanceof Error?q.message:String(q)}`)).finally(()=>process.exit(130))}),x.length>0&&(Fi=il("setup",x,{...at,signal:Q.signal}),Sn.push(...await Fi),Q.signal.aborted&&await M(),Sn.some(Ci)&&(console.error("No scenario was run: the application is not in the state the suite expects."),await yr(),process.exit(2)));let Bi=et();Mt(Bi.root,Bi.dir,Bi.env);{let D=new Map;for(let Y of u)for(let J of tt(Y))process.env[J]===void 0&&!D.has(J)&&D.set(J,Y.displayName);let q=new Map;for(let Y of u){for(let J of rn(lt(Y)))if(!q.has(J))try{to(J)}catch(de){q.set(J,`${de instanceof Error?de.message:String(de)} (used by "${Y.displayName}")`)}for(let J of lt(Y).flatMap(de=>od(de))){let de=q.has(J)?void 0:fo(J);de&&q.set(J,`${de} (used by "${Y.displayName}")`)}}if(q.size>0){for(let Y of q.values())console.error(Y);await yr(),process.exit(2)}if(D.size>0){for(let[Y,J]of D)console.error(`missing environment variable ${Y} (referenced as {env:${Y}} by "${J}")`);console.error("set the variable(s), or add them to a git-ignored .env in the project root"),await yr(),process.exit(2)}}let Qs=new Map;try{for(let D of S)Qs.set(D,await z(D))}catch(D){throw await V(U).catch(()=>{}),await yr(),D instanceof Tt&&(console.error(D.message),process.exit(2)),D}let Ih=async D=>{let q=Qs.get(D),Y=new Array(u.length);if(Ie.push(Y),m===1&&A===1||u.length===1){for(let oe=0;oe<u.length;oe++)Y[oe]=await Te(q,D,"1",u[oe]),qt(Y[oe]);return Y}let J=O!==void 0&&ur(D),de=[];await Tc(u.map((oe,He)=>[{s:oe,i:He}]),m,async(oe,He)=>{let je=await Te(q,D,String(He+1),oe.s,{agentDisabled:!0});je.status==="red"&&J?de.push(oe):(Y[oe.i]=je,qt(je))});let At=gp(de.sort((oe,He)=>oe.i-He.i),oe=>me(n,oe.s.featurePath,oe.s.name)),Xe=[];try{for(let je=1;je<Math.min(A,At.length);je++)try{Xe.push(await z(D))}catch(ye){console.log(` \u26A0 agent worker ${je+1} could not start a browser (${(ye instanceof Error?ye.message:String(ye)).split(`
|
|
1373
|
+
`)[0]}); going on with ${je}`);break}let oe=[q,...Xe],He=oe.length;await Tc(At,He,async(je,ye)=>{Y[je.i]=await Te(oe[ye],D,He>1?`agent ${ye+1}`:"agent",je.s),qt(Y[je.i])})}finally{await V(Xe)}return Y};try{if(t.rerecord){let D=0;for(let q of u){let Y=me(n,q.featurePath,q.name);Fe.existsSync(Y)&&(Fe.rmSync(Y),D++)}console.log(`rerecord: removed ${D} cache file(s) for ${u.length} scenario(s); the agent records them fresh (seeded from the other recordings). Restore with git if needed.`)}for(let D of S)y&&console.log(`
|
|
1374
|
+
${D}${ur(D)?"":" (replay only: recording and healing need a Chromium-family browser)"}`),await Ih(D),await V([Qs.get(D)]),Qs.delete(D)}finally{Q.signal.aborted&&await M(),await V(U),await yr()}Q.signal.aborted&&await M();let Xs=(await _l(Ie)).totals,Ol=Kt(G.resolve(te.opts().projectRoot),Zs);Ol.length>0&&console.log(`${Ol.length} cache proposal(s) pending. Review with: saffron accept | saffron reject. Until a proposal is accepted, other scenarios do not reuse its steps: accept a shared setup before recording more scenarios that use it.`);let Cl=t.strict??r.strict??!1;Cl&&Xs.yellow>0&&console.log(`strict mode: ${Xs.yellow} scenario(s) pending review treated as failure. Review proposals to go green.`);let Nh=Xs.red>0||Cl&&Xs.yellow>0,Ui=Sn.filter(D=>D.phase==="teardown"&&Ci(D));Ui.length>0&&console.log(`teardown failed: ${Ui.map(D=>al(D,at.timeoutMs)).join("; ")}. The environment may hold data from this run.`),process.exit(Nh?1:Ui.length>0?2:0)});te.command("accept").description("Promote pending cache proposals to committed caches").argument("[files...]","proposal file(s) (default with --all: every pending proposal, less those --all leaves out)").option("--all","accept every pending proposal that is verified and was not imported from a CI run (see --include-unverified, --include-imported)").option("--with-feature-edit","also apply the proposal's suggested .feature step rewrites").option("--propagate","apply the same locator fixes to every other cache using the same locator").option("--include-unverified","with --all: also accept proposals that are unverified or not checked (their proof replay failed, or did not run)").option("--include-imported","with --all: also accept proposals imported from a CI run (saffron import), which --all leaves for review by file").action((e,t)=>{let n=G.resolve(te.opts().projectRoot),r=Ee(n),s=t.all&&!t.includeImported?hn(n):{},o=0,a=e.length>0?e.map(ya).map(i=>({...i,file:G.resolve(i.file)})):t.all?Kt(n,Zs).map(i=>({file:i.file,revision:void 0})):[];if(a.length===0){Ch(n);return}try{for(let{file:i,revision:c}of a){let l=w=>{console.log(`not accepted: ${G.basename(i)} ${De(w)}`),process.exitCode=1},d=Oh(n,i,c!==void 0,()=>{if(c&&Ot(i)!==c)return l(_h);let w=s[G.relative(n,i).split(G.sep).join("/")];if(w&&Ot(i)===w.revision){o++;return}let v;try{v=Pr(i)}catch(E){if(!(E instanceof $e))throw E;return l(`cannot be read: ${E.problem}`)}if(v.meta.bound){let E=$t(n,v,ut(n,r,[]));if(E)return l(`is stale: ${E}. Run the scenario again for a proposal made against what is there now, or reject this one.`)}else console.log(`\u26A0 ${G.basename(i)} is ${Uo}; accepting as it is.`);if(v.meta.verified!==!0&&t.all&&!t.includeUnverified){let E=v.meta.verified===!1?v.meta.proofError?.split(`
|
|
1375
|
+
`)[0]:"not checked: no proof replay ran";console.log(`skipped UNVERIFIED ${G.basename(i)} (${De(E)}). Re-record it (saffron run --rerecord), or accept it explicitly by file, or pass --include-unverified.`);return}v.meta.verified===!1&&console.log(`\u26A0 accepting UNVERIFIED proposal (proof replay failed: ${De(v.meta.proofError?.split(`
|
|
1376
|
+
`)[0])}): expect a heal or red on the next run.`);let x=v.cache.steps.map(E=>E.gherkin);if(t.withFeatureEdit&&(v.meta.featureEdits??[]).length>0){let E=Hg(n,v.cache.feature,v.cache.scenario,x,ut(n,r,[]));if(E)return l(`carries feature edits, and ${E}. Run the scenario again for a fresh proposal, or accept this one without --with-feature-edit.`)}let $=st(me(n,v.cache.feature,v.cache.scenario));return{proposal:v,recordedSteps:x,oldCache:$,cacheFile:Ro(n,i)}},l);if(!d)continue;let{proposal:f,recordedSteps:p,oldCache:u,cacheFile:h}=d;console.log(`accepted \u2192 ${h}`);let b=u?Bg(u,f.cache):{changes:[],ambiguous:[]},g=b.changes;for(let w of b.ambiguous)console.log(` locator fix for ${De(_i(w))} not propagated: this heal sent it to more than one place, so other caches are left alone.`);if(g.length>0){let w=Ug(n,g,h,!t.propagate);for(let v of g)console.log(` locator fix: ${De(_i(v.from))} \u2192 ${De(_i(v.to))}`);if(w.length===0)console.log(" no other caches use this locator.");else if(t.propagate)for(let v of w)console.log(` propagated \u2192 ${v.feature} \u203A ${v.scenario} (${v.steps.map(x=>`"${x.gherkin}"`).join(", ")})`);else{console.log(` ${w.length} other cache(s) use the same locator: re-run with --propagate to fix them too:`);for(let v of w)console.log(` \xB7 ${v.feature} \u203A ${v.scenario}`)}}let S=f.meta.featureEdits??[];if(!t.withFeatureEdit||S.length===0)continue;let y=qg(n,f.cache.feature,f.cache.scenario,S,ut(n,r,[]),p);for(let w of y.applied){let v=w.fromStepSet?`${w.file}:${w.line} (StepSet "${w.fromStepSet}", fixes every invoking scenario)`:`${w.file}:${w.line}`;console.log(` feature edit ${v}:`),console.log(` - ${w.from}`),console.log(` + ${De(w.to)}`)}for(let w of y.skipped)console.log(` skipped edit [${w.index}]: ${De(w.reason)}`);if(y.appliedIndices.length>0){let w=new Set(y.appliedIndices),v=st(h);for(let x of S)w.has(x.index)&&x.text.trim()!==""&&v.steps[x.index]&&(v.steps[x.index].gherkin=x.text);Ar(h,v)}}}catch(i){throw i instanceof Le&&Di(i),i}o>0&&console.log(`skipped ${o} proposal${o===1?"":"s"} imported from a CI run: review ${o===1?"it":"them"} (saffron diff) and accept by file, or pass --include-imported.`)});te.command("steps").description("List/search the project's step vocabulary (files + caches): what exists, what's recorded, what to reuse").argument("[search]","case-insensitive substring filter").option("--json","machine-readable vocabulary").option("--snippets","write .vscode/saffron.code-snippets for native VS Code completion").action((e,t)=>{let n=G.resolve(te.opts().projectRoot),r=Ee(n),s;try{s=Gt(n,r.features??"features")}catch(a){throw a instanceof Le&&Di(a),a}if(e&&(s=vo(s,e)),t.json){console.log(JSON.stringify(s,null,2));return}if(t.snippets){let a=G.join(n,".vscode","saffron.code-snippets");Fe.mkdirSync(G.dirname(a),{recursive:!0}),Fe.writeFileSync(a,Hd(s)),console.log(`wrote ${s.steps.length} step + ${s.stepSets.length} StepSet snippet(s) \u2192 ${a}`),console.log("re-run after recording sessions to keep completions current");return}let o={recorded:"\x1B[32m\u25CF\x1B[0m",divergent:"\x1B[33m\u25CF\x1B[0m",unrecorded:"\u25CB"};if(s.stepSets.length>0){console.log("step sets:");for(let a of s.stepSets)console.log(` ${a.name} (${a.steps.length} steps, ${a.usage} scenario(s)), ${a.file}:${a.line}`);console.log("")}for(let a of s.steps){let i=a.fromStepSet?` [${a.fromStepSet}]`:"";console.log(`${o[a.status]} ${a.keyword} ${a.text} \xD7${a.usage}${i}`)}console.log(`
|
|
1377
|
+
${s.steps.length} step(s) across ${s.scannedFiles} file(s) \xB7 ${s.scannedCaches} cache(s) \xB7 \x1B[32m\u25CF\x1B[0m recorded (replays free) \xB7 \x1B[33m\u25CF\x1B[0m divergent \xB7 \u25CB unrecorded`)});te.command("author").description("Draft a feature file from plain-paragraph requirements, reusing the project's step vocabulary (AI)").argument("<prose-file>","text/markdown file with the requirements").option("-o, --out <file>","output path (default: features/<name>.saffron)").option("--provider <name>",'whose agent writes the draft: "claude" (default), "codex", "antigravity" or "cursor"').option("--model <model>","model for authoring").action(async(e,t)=>{let n=G.resolve(te.opts().projectRoot),r=Ee(n),s=Al(t.provider,r.provider),o=Fe.readFileSync(G.resolve(e),"utf8"),a;try{a=Gt(n,r.features??"features")}catch(d){throw d instanceof Le&&Di(d),d}console.log(`authoring with ${a.steps.length} known step(s) and ${a.stepSets.length} step set(s) as vocabulary\u2026`);let i=await Wf(o,a,t.model??kh(r,s).model,s==="claude"?void 0:Qc[s]),c=t.out?G.resolve(t.out):G.join(n,r.features??"features",`${G.basename(e).replace(/\.[^.]+$/,"")}.saffron`);Fe.existsSync(c)&&(console.error(`refusing to overwrite ${c}: pass --out for a new path`),process.exit(1)),Fe.mkdirSync(G.dirname(c),{recursive:!0}),Fe.writeFileSync(c,i.content);let l=i.content.split(`
|
|
1378
|
+
`).map(d=>d.trim().replace(/^(Given|When|Then|And|But|\*)\s+/,"")).filter(d=>a.steps.some(f=>f.text===fe(d))).length;console.log(`wrote ${c}`),console.log(`${l} step line(s) reuse the existing vocabulary (seedable)${i.usage.costUsd?` \xB7 $${i.usage.costUsd.toFixed(4)}`:""}`),console.log("draft only: browser behavior and replay have not been validated."),console.log("inspect the relevant UI, resolve assumptions, then record affected scenarios: saffron run "+G.relative(process.cwd(),c)+":<line>"),console.log("review with saffron diff; accept only faithful, verified proposals, then replay the affected scenarios with --no-agent.")});te.command("login").description("Check or set up an AI provider's login on this machine (Cursor: a one-time sign-in for Saffron; Antigravity: allows Saffron's tools in agy)").argument("[provider]",'"claude", "codex", "antigravity" or "cursor" (default: the configured provider)').action(async e=>{let t=G.resolve(te.opts().projectRoot),n=Al(e,Ee(t).provider),r=n==="cursor"?vg:n==="antigravity"?pg:void 0;if(r)try{await r()}catch(o){console.error(o instanceof Error?o.message:String(o)),process.exit(1)}let s=Xc(n);if(s.length===0){console.log(`${yn[n]}: ready to record and heal.`);return}console.log([`${yn[n]} still needs:`,...s.map(o=>` \xB7 ${o}`)].join(`
|
|
1379
|
+
`)),process.exit(1)});te.command("mcp").description("Serve the step vocabulary to AI assistants over stdio MCP (search_steps, list_step_sets)").action(async()=>{let e=G.resolve(te.opts().projectRoot),t=Ee(e);await Hf(e,t.features??"features")});te.command("lsp").description("Run the Saffron language server over stdio (completion, go-to-definition, hover, diagnostics). For JetBrains (LSP4IJ / Ultimate LSP API), Neovim, and any LSP-capable editor").action(()=>{process.stdin.isTTY&&(console.error($h(So())),process.exit(2));let e=G.resolve(te.opts().projectRoot),t=Ee(e),n=process.argv.includes("-p")||process.argv.some(r=>r.startsWith("--project-root"));fp(e,t.features??"features",{rootFromClient:!n})});te.command("reject").description("Discard pending cache proposals (AI will retry next run)").argument("[files...]","proposal file(s)").option("--all","reject all pending proposals").action((e,t)=>{let n=G.resolve(te.opts().projectRoot),r=e.length>0?e.map(ya).map(s=>({...s,file:G.resolve(s.file)})):t.all?Kt(n,Zs).map(s=>({file:s.file,revision:void 0})):[];if(r.length===0){Ch(n);return}for(let{file:s,revision:o}of r){let a=Oh(n,s,o!==void 0,()=>{if(o&&Ot(s)!==o)return _h;To(s)},i=>i);if(a){console.log(`not rejected: ${G.basename(s)} ${a}`),process.exitCode=1;continue}console.log(`rejected ${s}`)}});te.command("init").description("Make the project agent-ready: install the bundled Saffron skill into agent directories, add instructions to AGENTS.md, scaffold config").option("--agents <list>",`comma-separated targets: ${Object.keys(Ks).join(", ")} (default: claude,agents)`).option("--no-instructions","do not touch AGENTS.md / CLAUDE.md").option("--no-scaffold","do not create saffron.config.json, features/, .gitignore entry").option("--no-mcp","do not register `saffron mcp` in project MCP configs (.mcp.json, .cursor/mcp.json, .vscode/mcp.json)").option("--examples","install the Saucedemo example suite (features, config, .env.example) for a guided first run").option("--no-examples","never install the example suite (skips the prompt)").action(async e=>{let t=G.resolve(te.opts().projectRoot),n=So();n||(console.error("saffron: cannot locate the installed package root"),process.exit(2));let r=e.agents?String(e.agents).split(",").map(a=>a.trim()).filter(Boolean):void 0;for(let a of r??[])a in Ks||(console.error(`saffron: unknown agent target "${a}" (expected one of ${Object.keys(Ks).join(", ")})`),process.exit(2));let s=e.examples===!0;e.examples===void 0&&process.stdin.isTTY&&process.stdout.isTTY&&(s=await pS(`Install the Saucedemo example tests (login, cart, checkout) into ${Mi(t).features}/ for a guided first run? [y/N] `));let o=xh({projectRoot:t,packageRoot:n,targets:r,instructions:e.instructions,scaffold:e.scaffold,mcp:e.mcp,examples:s});for(let a of o.skillDirs)console.log(`skill \u2192 ${a}/`);for(let a of o.mcpFiles)console.log(`${a.outcome.padEnd(9)} \u2192 ${a.file} (saffron mcp server)`);for(let a of o.mcpHints)console.log(`mcp hint \u2192 ${a}`);for(let a of o.instructionFiles)console.log(`${a.outcome.padEnd(9)} \u2192 ${a.file} (managed Saffron block)`);for(let a of o.scaffolded)console.log(`created \u2192 ${a}`);o.examples&&!o.examples.installed&&console.log(`examples \u2192 not installed: ${o.examples.reason}`),o.examples?.note&&console.log(`examples \u2192 note: ${o.examples.note}`),console.log("\nAgents now load the saffron skill when writing tests. Re-run after `npm update saffron-ai` to refresh it."),o.examples?.installed&&console.log(["","Your guided first run (recording needs Claude credentials; replays never do):"," cp .env.example .env # public demo credentials, resolved at replay"," npx playwright install chromium"," npx saffron run --filter @smoke # the agent records two scenarios (about $3 of AI usage), files proposals"," npx saffron accept --all # review, then promote them to caches"," npx saffron run --filter @smoke # replays at zero tokens","Then try the rest: npx saffron run (login errors outline, checkout with a data table)"].join(`
|
|
1380
|
+
`))});te.command("export").description("Pack the pending proposals, the last run's report and its screenshots and traces into one bundle, for review on another checkout (CI uploads it as an artifact)").option("-o, --out <file>","where to write the bundle (default: .saffron/reports/saffron-bundle.zip)").option("--branch <name>","also commit the pending proposals (not the caches) onto the commit the run tested as a new branch, push it to origin, and open a draft pull request (GitHub through gh, Azure DevOps through az)").option("--base <branch>","with --branch: the branch the pull request is for (default: the branch the run tested)").option("--report-only","a summary instead: the last run's report and screenshots, no proposals and no traces (default: .saffron/reports/saffron-summary.zip). Small enough to upload on every run, so editors can show any run's results; a run that left only summaries has nothing to import").action(e=>{let t=G.resolve(te.opts().projectRoot);e.base!==void 0&&e.branch===void 0&&(console.error("saffron export: --base needs --branch"),process.exit(2)),e.reportOnly&&e.branch!==void 0&&(console.error("saffron export: --report-only holds no proposals, so there is nothing for --branch to push"),process.exit(2));try{Gs("--branch",e.branch),Gs("--base",e.base)}catch(i){console.error(`saffron export: ${i.message}`),process.exit(2)}let n;try{n=Ef(t,{out:e.out?G.resolve(e.out):void 0,summary:e.reportOnly===!0})}catch(i){console.error(`saffron export: ${i instanceof Error?i.message:String(i)}`),process.exit(2)}for(let i of n.unreadable)console.error(`\u26A0 proposal ${i.file} cannot be read: ${De(i.problem)}. Left out of the bundle.`);let r=n.manifest;if(console.log(`${r.summary?"summary":"bundle"}: ${n.file}`),console.log(r.summary?` the run's report \xB7 ${r.evidence.length} screenshot(s)${r.shard?` \xB7 shard ${r.shard.index}/${r.shard.total}`:""}`:` ${r.proposals.length} proposal(s) \xB7 ${r.evidence.length} screenshot and trace file(s) \xB7 ${r.report?"the run's report":"no run report"}${r.shard?` \xB7 shard ${r.shard.index}/${r.shard.total}`:""}`),console.log(` from ${_s(r)}`),n.missing.length>0&&console.log(` ${n.missing.length} file(s) the report names are gone, or were replaced by a later run: left out`),n.dropped.length>0&&console.log(` ${n.dropped.length} trace(s) of green scenarios left out: with them the bundle would be over the 4 GB one bundle holds`),r.summary){console.log("Upload it as a saffron-summary* artifact: saffron runs marks the run, and saffron report --run <id> shows its results.");return}if(console.log("Review it in a checkout of this repository with: saffron import <bundle>"),e.branch===void 0)return;if(n.proposals.length===0){console.log("No pending proposals: no branch to push.");return}let s;try{let i=Ee(t);s=mh(t,n,String(e.branch),{base:e.base,config:i})}catch(i){console.error(`saffron export: the bundle is written, but no branch was pushed: ${i instanceof Error?i.message:String(i)}`),process.exit(2)}for(let i of s.leftOut)console.error(`\u26A0 left out of the branch: ${G.relative(t,i.file)} ${i.reason}`);let o=n.proposals.length-s.leftOut.length,a=o===1?"the proposal":`${o} proposals`;console.log(`branch: ${s.branch} pushed to origin (${s.commit.slice(0,7)}: ${a} on top of ${s.parent.slice(0,7)})`),s.pullRequest?console.log(`draft pull request: ${s.pullRequest}`):(console.log(`no pull request: ${s.noPullRequest}. Open one from ${s.branch} to ${s.base}; its description is in ${s.bodyFile}`),s.failed&&(process.exitCode=1))});te.command("runs").description("List the CI runs of the checkout's branch (GitHub Actions through gh, Azure Pipelines through az), with how many of each run's proposals are pending here; import one with saffron import --run <id>").option("--branch <name>","another branch (default: the checkout's; every branch on a detached HEAD)").option("--limit <n>","how many runs (default 20)").option("--provider <name>",`"github" or "azure" (default: ci.provider in the config, else the repository's host)`).option("--json","machine-readable output").action(e=>{let t=G.resolve(te.opts().projectRoot),n=e.limit===void 0?void 0:Number(e.limit);n!==void 0&&!(Number.isInteger(n)&&n>0)&&(console.error(`invalid --limit "${e.limit}": use a whole number above 0`),process.exit(2));let r;try{r=nh(t,Ee(t),{provider:e.provider,branch:e.branch,limit:n})}catch(a){let i=a instanceof Error?a.message:String(a);e.json?console.log(JSON.stringify({error:i},null,2)):console.error(`saffron runs: ${i}`),process.exit(2)}if(r.problem&&(process.exitCode=2),e.json){console.log(JSON.stringify(r.problem?{...r,error:r.problem.message}:r,null,2));return}if(r.problem){console.error(`saffron runs: ${r.problem.message}`);return}let s=`${Ni[r.provider]} runs ${r.branch?`on ${r.branch}`:"on every branch"}`;if(r.runs.length===0){console.log(`No ${s}.`);return}let o=a=>a.status!=="completed"?"\u25CF":a.conclusion==="success"?"\u2713":a.conclusion==="failure"?"\u2717":"\u25CB";console.log(`${s}:`);for(let a of r.runs){let i=[`${a.name} #${a.number}`,a.status==="completed"?a.conclusion:a.status.replace("_"," "),Xg(a.createdAt),a.commit?.slice(0,7),a.pending?`${a.pending} proposal${a.pending===1?"":"s"} pending here`:void 0,a.results?.kind==="running"?void 0:a.results?.label].filter(Boolean);console.log(` ${a.id.padStart(12)} ${o(a)} ${i.join(" \xB7 ")}`)}console.log("Import one with: saffron import --run <id>")});te.command("import").description("Bring a bundle from `saffron export` (a CI run) into this checkout: its proposals, each checked against the files here, and the run's report, screenshots and traces. Then review and accept as usual").argument("[bundles...]","bundle files, folders holding saffron-bundle*.zip (a CI artifact download), or http(s) URLs").option("--run <id>","instead: download the bundles of this CI run (an id from saffron runs) through gh or az, and import them").option("--provider <name>",`with --run: "github" or "azure" (default: ci.provider in the config, else the repository's host)`).option("--allow-fork","with --run: import a run a fork's pull request started (code from outside this repository made its bundle); read that pull request first").option("--overwrite","replace a different proposal already pending here for the same scenario").option("--allow-unknown-repository","import a bundle that does not say which repository it comes from (made outside a git checkout); its proposals are still checked by their bindings").option("--json","machine-readable output").action(async(e,t)=>{let n=G.resolve(te.opts().projectRoot);function r(d,f=!1){t.json?console.log(JSON.stringify({error:d},null,2)):console.error(`saffron import: ${d}${f?"":". Nothing was imported."}`),process.exit(2)}t.run===void 0==(e.length===0)&&r("give bundle files, folders or URLs, or --run <id>, and not both"),t.provider!==void 0&&t.run===void 0&&r("--provider goes with --run"),t.allowFork&&t.run===void 0&&r("--allow-fork goes with --run");let s,o,a;try{let d=Ee(n),f=ut(n,d,[]);t.run!==void 0&&(a=ah(n,d,String(t.run),{provider:t.provider,allowFork:t.allowFork===!0}));let p=a?[a.dir]:e.map(h=>/^https?:\/\//i.test(h)?h:G.resolve(h)),u=a;s=await If(n,p,f,{overwrite:t.overwrite===!0,allowUnknownRepository:t.allowUnknownRepository===!0,describe:u?h=>`${Ni[u.provider]} run ${t.run} (${G.basename(G.dirname(h))})`:void 0,run:u?`${u.provider}:${t.run}`:void 0})}catch(d){o=d}finally{a?.remove()}if((o instanceof W||o instanceof Le)&&r(o.message),(o!==void 0||!s)&&r(o instanceof Error?o.message:String(o),!0),s.proposals.some(d=>d.outcome==="refused")&&(process.exitCode=1),t.json){console.log(JSON.stringify(a?{run:{provider:a.provider,id:String(t.run)},...s}:s,null,2));return}for(let d of s.bundles)console.log(`bundle: ${d.source}`),console.log(` from ${_s(d.origin)}${d.shard?` \xB7 shard ${d.shard.index}/${d.shard.total}`:""} \xB7 saffron-ai ${d.runner}`);for(let d of s.warnings)console.log(`\u26A0 ${d}`);for(let d of s.proposals){let f=d.feature?`${d.feature} \u203A ${d.scenario}`:d.file;d.outcome==="imported"?console.log(`imported \u2192 ${d.file} (${f})`):d.outcome==="unchanged"?console.log(`unchanged: ${f}: ${d.reason??"already pending here"}`):console.log(`not imported: ${f} ${d.reason}`)}let{written:i,unchanged:c}=s.evidence;i>0&&console.log(`evidence: ${i} screenshot and trace file(s) written${c?`, ${c} already here`:""}`),s.report==="written"&&console.log("report: .saffron/reports/latest.html now shows the imported run (saffron report, saffron trace)");let l=s.proposals.filter(d=>d.outcome==="imported").length;l===0&&i===0&&s.report!=="written"&&!s.proposals.some(d=>d.outcome==="refused")?console.log("Nothing changed: this was already imported."):l>0&&console.log("Review with: saffron diff \xB7 accept with: saffron accept <file> | --all --include-imported \xB7 then commit the caches with your git tools")});te.command("diff").description("Show what a pending proposal changes in the committed recording: the action list a reviewer is approving, not just the narrative, and the feature file edits it would apply").argument("[files...]","proposal file(s); default: every pending proposal").option("--json","machine-readable output").action((e,t)=>{let n=G.resolve(te.opts().projectRoot),r=e.length>0?e.map(o=>G.resolve(o)):Kt(n,Zs).map(o=>o.file);if(r.length===0){console.log("No pending proposals.");return}let s=r.map(o=>{let a=Pr(o),i=st(me(n,a.cache.feature,a.cache.scenario));return{file:G.relative(n,o),verified:a.meta.verified,stale:a.meta.bound?Eh(n,a):Uo,...Nn(i,a.cache,a.meta.featureEdits)}});if(t.json){console.log(JSON.stringify(s.length===1?s[0]:s,null,2));return}console.log(s.map(o=>`${Mo(o)}${o.stale?`
|
|
1357
1381
|
|
|
1358
|
-
STALE: ${
|
|
1382
|
+
STALE: ${De(o.stale)}`:""}`).join(`
|
|
1359
1383
|
|
|
1360
|
-
`))});
|
|
1384
|
+
`))});te.command("trace").description("Open the execution replay of a scenario from the last run: its Given / When / Then, the page at every action, the network alongside, and what the agent changed").argument("[scenario]","scenario name, feature path, or feature:scenario; default: every traced scenario, opening on a red one, else a yellow one").option("--port <n>","listen on a fixed port (default: a free one)").option("--no-open","print the URL without opening a browser").option("--json","print the parsed trace as JSON instead of serving it").option("--run <startedAt|id>","only if the last run is this one (its startedAt): an editor's row names the run it lists. Or a CI run's id (from saffron runs): replay that run's traces without importing it, view only").option("--provider <name>",`with a CI run's id: "github" or "azure" (default: ci.provider in the config, else the repository's host)`).option("--allow-fork","with a CI run's id: view a run a fork's pull request started").option("--max-download <MB>","with a CI run's id: refuse to download more than this many megabytes (default: no limit)").action(async(e,t)=>{let n=t.port===void 0?void 0:Number(t.port);n!==void 0&&(!Number.isInteger(n)||n<0||n>65535)&&(console.error(`invalid --port "${t.port}": use a whole number from 0 to 65535`),process.exit(2));let r=G.resolve(te.opts().projectRoot),s=typeof t.run=="string"&&/^\d+$/.test(t.run)?t.run:void 0,o=s?`CI run ${s}`:"the last run",a=r,i,c;if(s){let $=Rh("trace",t.json===!0),E=Th(t.maxDownload,$);try{let R=Ee(r),k=yl(r,R,s,{provider:t.provider,allowFork:t.allowFork===!0,maxDownloadBytes:E});if(!k.folder)throw new W(k.reason??`run ${s} has no Saffron bundle`);let C=await bl(r,{...k,folder:k.folder},ut(r,R,[]));if(!C.report)throw new W(`run ${s}'s bundle holds no run report`);a=k.folder,i=C.report}catch(R){return $(R)}c=`Viewed from CI run ${s}: nothing is filed here, so there is nothing to accept or reject. To review its proposals, import the run (saffron import --run ${s}).`}else{(t.provider!==void 0||t.allowFork||t.maxDownload!==void 0)&&(console.error("saffron trace: --provider, --allow-fork and --max-download go with --run <CI run id>"),process.exit(2));let $=G.join(r,".saffron","reports","latest.json");Fe.existsSync($)||(console.error("No report found. Run `saffron run` first."),process.exit(2)),i=JSON.parse(Fe.readFileSync($,"utf8")),t.run!==void 0&&i.startedAt!==t.run&&(console.error(`The last run changed since this was listed: it is now the run of ${i.startedAt}. Refresh the panel to replay it.`),process.exit(2))}let l=i.scenarios.filter($=>$.evidence?.some(E=>E.kind==="trace"));l.length===0&&(console.error(`${s?o:"The last run"} kept no execution trace. Set "trace": "retain-on-failure" (or "on") in saffron.config.json, or run with --trace retain-on-failure, then run again.`),process.exit(2));let d=e?.trim(),f=l;if(d){let $=l.filter(E=>E.scenario===d||E.feature===d||`${E.feature}:${E.scenario}`===d||`${E.feature}:${E.scenario}@${E.browser}`===d||`${E.scenario}@${E.browser}`===d);f=$.length>0?$:l.filter(E=>E.scenario.toLowerCase().includes(d.toLowerCase()))}if(f.length===0||t.json&&d&&f.length>1){console.error(f.length===0?`No traced scenario matches "${d}". Traced in ${o}:`:`--json prints one trace. Traced in ${o}:`);for(let $ of l)console.error(` ${ce($.status).padEnd(6)} ${ce($.feature)}:${ce($.scenario)}${i.browsers&&$.browser?`@${ce($.browser)}`:""}`);console.error('Name one: saffron trace "<scenario name>", or "<feature>:<scenario name>" as listed'),process.exit(2)}let p=f.findIndex($=>$.status==="red"),u=f.findIndex($=>$.status==="yellow"),h=p>=0?p:u>=0?u:0,b=f[h],g=$=>G.basename($,".zip").split(".")[0].replace("proof-","Proof replay "),S=$=>{let E=$.evidence.filter(C=>C.kind==="trace"),R=$.sessions?.[$.steps.findIndex(C=>C.status==="failed")],k=E.find(C=>!C.proof&&R!==void 0&&C.session===R)??E.find(C=>!C.proof)??E[0];return[k,...E.filter(C=>C!==k)]},[y]=S(b),w;if(f.length===1||t.json){let $=G.join(a,y.file);try{w=sl(a,y)}catch(E){console.error(`The trace cannot be read: ${E instanceof Error?E.message:String(E)}`),process.exit(2)}if(w||(console.error(Fe.existsSync($)?"The trace on disk is from a later run than the last report (a run that stopped before writing its report). Run the scenario again to replay it.":`The trace file is gone: ${$}. Run the scenario again.`),process.exit(2)),t.json){console.log(JSON.stringify({...Tg(w),...y.session?{session:y.session}:{}},null,2));return}}let v=f.map(($,E)=>{let[R,...k]=S($);return{scenario:{feature:$.feature,scenario:$.scenario,status:$.status,error:$.error,adaptations:$.adaptations,narrative:$.narrative,proposalDiff:$.proposalDiff,proposalFile:$.proposalFile,proposalRevision:$.proposalRevision,screenshots:$.evidence?.filter(C=>C.kind!=="trace"),ranAt:$.ranAt??i.startedAt,source:["cache","agent-record","agent-heal"].find(C=>C===$.source),proposalReplay:$.proposalReplay===!0?!0:void 0,usage:$.usage,browser:i.browsers?$.browser:void 0,stepSessions:$.sessions},traces:[R,...k].map((C,P)=>({file:G.join(a,C.file),data:E===h&&P===0?w:void 0,read:()=>sl(a,C),checked:C.sha256!==void 0,label:`${C.proof?g(C.file):"Execution"}${C.session?` \xB7 session "${C.session}"`:""}`,proof:C.proof===!0,steps:C.proof?C.traceSteps:C.traceSteps??$.steps,uniques:C.proof?C.traceUniques:$.uniques,browserSession:C.session}))}}),x;try{x=await Fg({entries:v,start:h,projectRoot:a,port:n,viewOnly:c})}catch($){console.error(`Could not start the replay: ${$ instanceof Error?$.message:String($)}`),process.exit(2)}for(let{file:$,reason:E}of x.skipped)console.error(`Skipping ${G.relative(a,$)}. ${E}`);console.log(`Saffron replay: ${f.length===1?`${ce(b.feature)} \u203A ${ce(b.scenario)}`:`${f.length} scenarios, opening on ${ce(b.scenario)}`}
|
|
1361
1385
|
${x.url}
|
|
1362
|
-
Press Ctrl-C to stop.`),t.open!==!1&&
|
|
1363
|
-
`)),process.exit(2));let s=e.yes&&!e.check?
|
|
1364
|
-
`))}e.check&&r.orphans.length>0&&process.exit(1)});
|
|
1365
|
-
${
|
|
1366
|
-
`)[0]:String(n)}`}}var
|
|
1367
|
-
`);for(let{file:n,proposal:r}of t){console.log(` ${n}`);let s=r.meta.verified===!0?" \xB7 verified \u2713":r.meta.verified===!1?" \xB7 UNVERIFIED \u2717":"";console.log(` ${
|
|
1386
|
+
Press Ctrl-C to stop.`),t.open!==!1&&Ys(x.url),await new Promise($=>{process.once("SIGINT",()=>{x.close().finally($)})}),process.exit(0)});te.command("prune").description("List (and with --yes remove) recordings whose scenario no longer exists: caches and pending proposals left behind by a deleted scenario or feature file").option("--json","machine-readable output").option("--yes","actually delete the files listed").option("--check","exit 1 when anything is orphaned, delete nothing (for CI)").action(e=>{let t=G.resolve(te.opts().projectRoot),n=Ee(t),r=Eo(t,n.features??"features");r.unreadable.length>0&&(e.json?console.log(JSON.stringify({...r,removed:[]},null,2)):console.error(["saffron: cannot tell what is orphaned while a feature file fails to parse.",...r.unreadable.map(o=>` ${o}`),"Fix these first: a syntax error hides every scenario in the file."].join(`
|
|
1387
|
+
`)),process.exit(2));let s=e.yes&&!e.check?su(t,r.orphans):[];if(e.json)console.log(JSON.stringify({...r,removed:s},null,2));else if(r.orphans.length===0)console.log(`Nothing to prune. All ${r.kept} recordings belong to a scenario.`);else{let o=r.orphans.filter(c=>c.kind==="cache").length,a=r.orphans.filter(c=>c.kind==="proposal").length,i=r.orphans.length-o-a;console.log([`${r.orphans.length} orphaned ${r.orphans.length===1?"file":"files"} (${o} cache, ${a} proposal, ${i} screenshot ${i===1?"folder":"folders"}), ${r.kept} still owned:`,"",...r.orphans.map(c=>` ${e.yes&&!e.check?s.includes(c.file)?"removed ":"NOT removed ":""}${ou(c)}`),"",s.length===0?e.yes&&!e.check?"Nothing could be deleted: check the files' permissions.":"Nothing was deleted. Run `saffron prune --yes` to remove them.":s.length<r.orphans.length?`Deleted ${s.length} of ${r.orphans.length}; the others could not be removed (check their permissions).`:"Deleted. Re-record by running the scenarios again if you deleted something by mistake."].join(`
|
|
1388
|
+
`))}e.check&&r.orphans.length>0&&process.exit(1),e.yes&&!e.check&&s.length<r.orphans.length&&process.exit(1)});te.command("status").description("Project overview for dashboards and IDE panels: feature files and scenarios with cache state, tags, pending proposals, last run, history, vocabulary health, effective config").option("--json","machine-readable output").action(e=>{let t=G.resolve(te.opts().projectRoot),n=Ee(t),r=Os(t,n);if(e.json){console.log(JSON.stringify(r,null,2));return}zf(r)});te.command("report").description("Open the latest HTML report, or merge shard reports into it, or view a CI run's results without importing them (--run)").argument("[paths...]","with --merge: shard report files or folders to search (default: .saffron)").option("--open","open in the default browser",!0).option("--merge","combine the shard-<i>-of-<n>.json reports of one sharded run into latest.json, latest.html and one history line").option("--run <id>","view a CI run's results (an id from saffron runs): downloaded once into .saffron/ci/, checked like an import, nothing filed. Import it with saffron import --run").option("--provider <name>",`with --run: "github" or "azure" (default: ci.provider in the config, else the repository's host)`).option("--allow-fork","with --run: view a run a fork's pull request started").option("--max-download <MB>","with --run: refuse to download more than this many megabytes (default: no limit)").option("--json","with --run: machine-readable output").option("--panel","with --run: print the run's results as one page (what the editors' CI results panel shows); a failure is {error} as with --json").action(async(e,t)=>{let n=G.resolve(te.opts().projectRoot);if(t.run!==void 0){t.json&&t.panel&&(console.error("saffron report: --json and --panel print different things: pick one"),process.exit(2)),await mS(n,String(t.run),t);return}for(let s of["provider","allowFork","maxDownload","json","panel"])t[s]!==void 0&&(console.error(`saffron report: --${s.replace(/[A-Z]/g,o=>`-${o.toLowerCase()}`)} goes with --run`),process.exit(2));if(t.merge){wS(n,e);return}e.length>0&&(console.error("saffron report: paths are only read with --merge"),process.exit(2));let r=G.join(n,".saffron","reports","latest.html");Fe.existsSync(r)||(console.error("No report found. Run `saffron run` first."),process.exit(2)),console.log(r),Ys(r)});function Rh(e,t){return n=>{let r=n instanceof Error?n.message:String(n);if(t){let s=n instanceof W?n.kind:void 0;console.log(JSON.stringify({error:r,...s?{kind:s}:{},...n instanceof Vs?{sizeBytes:n.sizeBytes}:{}},null,2))}else console.error(`saffron ${e}: ${r}`);process.exit(2)}}function Th(e,t){let n=e===void 0?void 0:Number(e);return n!==void 0&&!(n>0)&&t(`invalid --max-download "${e}": use a number of megabytes above 0`),n===void 0?void 0:n*1024**2}async function mS(e,t,n){let r=Rh("report",n.json===!0||n.panel===!0),s=Th(n.maxDownload,r),o;try{let l=Ee(e);o=await dh(e,l,ut(e,l,[]),t,{provider:n.provider,allowFork:n.allowFork===!0,maxDownloadBytes:s})}catch(l){return r(l)}let{results:a}=o;if(n.json){console.log(JSON.stringify(a,null,2));return}if(n.panel){process.stdout.write(Pi(a,e,ot()));return}if(!a.bundle){console.log(a.reason);return}for(let l of a.warnings)console.log(`\u26A0 ${l}`);a.bundle.summaryOnly&&console.log(`run ${t} uploaded only a summary: its results and screenshots, no traces to replay and nothing to import`);let i=a.proposals??[];if(i.length>0&&console.log(`${i.length} proposal${i.length===1?"":"s"}, ${i.filter(l=>l.importable).length} importable: saffron import --run ${t}`),!a.reportHtml){console.log(`run ${t}'s bundle holds no run report`);return}let c=G.join(e,a.reportHtml);console.log(c),Ys(c)}te.command("dashboard").description("Open the suite's quality dashboard: tests, failing, flaky and never-run scenarios, healing, timing and tags, from the run history").option("--stdout","print the page instead of writing and opening it (what the IDE panels read)").option("--no-open","write the page without opening a browser").action(e=>{let t=G.resolve(te.opts().projectRoot),n=Os(t,Ee(t)),r=Wg(n.quality,n.version);if(e.stdout){process.stdout.write(r);return}let s=G.join(t,".saffron","reports","dashboard.html");Fe.mkdirSync(G.dirname(s),{recursive:!0}),Fe.writeFileSync(s,r),console.log(s),e.open!==!1&&Ys(s)});function Ah(e,t=0){return`named scenarios only: ${e?`the report shows them in place of their last results, beside ${t} row(s) kept from earlier runs, each marked with the time it ran`:"the report holds just them: the last report was missing, imported from CI, interrupted, for another base URL or billed another way"}; their history line counts for them, not as a run of the suite`}function wS(e,t){let n=t.length>0?t.map(b=>G.resolve(b)):[G.join(e,".saffron")],r;try{r=Zo(bf(n))}catch(b){console.error(`saffron report --merge: ${b instanceof Error?b.message:String(b)}`),process.exit(2)}let{report:s,history:o,replaced:a}=r;for(let b of a)console.log(`\u26A0 ${b} is a shard a later attempt of the run ran again: left out`);let i=vs(e),c=i.find(b=>b.runId===o.runId),l=c?i.filter(b=>b.runId!==o.runId):i;o.partial||(s.trends=sc(l,o));let d=c!==void 0&&JSON.stringify(c)===JSON.stringify(o);d||af(e,o);let f=o.partial?fc(uc(e),s):s,{html:p,json:u}=Ts(e,f),h=s.totals;console.log(`merged ${s.shards} shard(s): ${h.scenarios} scenario(s) \xB7 ${h.green} passed, ${h.yellow} pending review, ${h.red} failed \xB7 ${h.aiCalls} AI calls${Ya(h)}`),d?console.log("history already holds this run: not appended again"):c&&console.log("history already held this run: its line is replaced with these results"),s.trends?.prev&&console.log(Za(s.trends.prev));for(let b of s.trends?.chronic??[])console.log(`\u26A0 chronic: ${b.feature} \u203A ${b.scenario}: ${b.heals} heal(s), ${b.reds} red(s) in last ${b.runs} run(s)`);o.partial&&console.log(Ah(f!==s,f.scenarios.length-s.scenarios.length)),console.log(`report: ${p}
|
|
1389
|
+
${u}`)}function Eh(e,t){try{return $t(e,t,ut(e,Ee(e),[]))}catch(n){return`cannot check: ${n instanceof Error?n.message.split(`
|
|
1390
|
+
`)[0]:String(n)}`}}var De=e=>ce(String(e??""),1/0),Zs=(e,t)=>console.error(`\u26A0 proposal ${e} cannot be read: ${De(t)}`),yS="is no longer pending: it was accepted, rejected or removed since it was listed.",bS="is not a pending proposal.",vS="is not a proposal file under .saffron/proposals.",_h="changed since it was listed. Refresh and review it again.",xS="is being decided by another process. Try again.";function Oh(e,t,n,r,s){if(!t.endsWith(".json")||Fe.existsSync(t)&&!_t(G.join(e,".saffron","proposals"),t))return s(vS);try{return $o(t,r,()=>s(n?yS:bS))}catch(o){if(!(o instanceof er))throw o;return s(xS)}}function Ch(e){let t=Kt(e,Zs);if(t.length===0){console.log("No pending proposals.");return}console.log(`Pending proposals:
|
|
1391
|
+
`);for(let{file:n,proposal:r}of t){console.log(` ${n}`);let s=r.meta.verified===!0?" \xB7 verified \u2713":r.meta.verified===!1?" \xB7 UNVERIFIED \u2717":"";console.log(` ${De(r.cache.feature)} \u203A ${De(r.cache.scenario)} (${De(r.meta.mode)}, ${De(r.meta.createdAt)}${s})`);let o=r.meta.bound?Eh(e,r):Uo;o&&console.log(` \u2717 STALE: ${De(o)}`),console.log(` ${De(r.meta.narrative)}`);for(let a of r.meta.adaptations)console.log(` \u26A0 ${De(a)}`);r.meta.suggestedFeatureEdit&&console.log(` suggested .feature edit:
|
|
1368
1392
|
${r.meta.suggestedFeatureEdit.split(`
|
|
1369
|
-
`).map(
|
|
1370
|
-
`)}`),console.log()}console.log("Accept with: saffron accept <file> | --all")}
|
|
1393
|
+
`).map(a=>` ${De(a)}`).join(`
|
|
1394
|
+
`)}`),console.log()}console.log("Accept with: saffron accept <file> | --all")}te.parseAsync().catch(e=>{process.env.SAFFRON_DEBUG?console.error(e):console.error(`saffron: ${e instanceof Error?e.message:String(e)}`),process.exit(2)});
|