@currents/cmd 2.2.0 → 3.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/bin/index.js CHANGED
@@ -1,69 +1,73 @@
1
1
  #! /usr/bin/env node
2
- "use strict";var cp=Object.create;var yr=Object.defineProperty;var pp=Object.getOwnPropertyDescriptor;var dp=Object.getOwnPropertyNames;var mp=Object.getPrototypeOf,up=Object.prototype.hasOwnProperty;var lp=(t,e)=>{for(var r in e)yr(t,r,{get:e[r],enumerable:!0})},fp=(t,e,r,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of dp(e))!up.call(t,n)&&n!==r&&yr(t,n,{get:()=>e[n],enumerable:!(o=pp(e,n))||o.enumerable});return t};var l=(t,e,r)=>(r=t!=null?cp(mp(t)):{},fp(e||!t||!t.__esModule?yr(r,"default",{value:t,enumerable:!0}):r,t));var Fx=require("source-map-support/register");var sp=require("@commander-js/extra-typings");var Go={name:"@currents/cmd",version:"2.2.0",main:"./dist/index.js",author:{name:"Currents Software Inc",email:"hello@currents.dev"},license:"MIT",repository:{type:"git",url:"https://github.com/currents-dev/currents-reporter"},description:"Currents CLI tools",engines:{node:">=20"},scripts:{test:"vitest",rm:"rimraf dist",lint:'TIMING=1 eslint "**/*.ts*"',types:"tsc --noEmit",build:"tsup-node --minify --dts",dev:"tsup-node --watch --dts",release:"release-it","publish:npm":"npm run rm && npm run build && ./publish.js"},devDependencies:{"@jest/reporters":"^30.4.1","@jest/types":"^30.4.1","@release-it/conventional-changelog":"^12.0.0","release-it":"^21.0.2","@types/archiver":"^6.0.3","@types/async-retry":"^1.4.9","@types/debug":"^4.1.12","@types/fs-extra":"^11.0.4","@types/getos":"^3.0.4","@types/lodash":"^4.17.16","@types/node":"^25.5.0","@types/proxy-from-env":"^1.0.4","@types/semver":"^7.5.8","@types/tmp":"^0.2.6","@types/unzipper":"^0.10.11","@types/uuid":"^10.0.0","@types/xml2js":"^0.4.14","@types/xxhashjs":"^0.2.4",jest:"^30.4.2","jest-cli":"^30.4.2","jest-config":"^30.4.2",rimraf:"^6.0.1",tsup:"^8.3.5",typescript:"^5.9.3",vitest:"^4.1.11"},dependencies:{"@commander-js/extra-typings":"^14.0.0","@currents/commit-info":"2.0.0",archiver:"^7.0.1","async-retry":"^1.3.3",axios:"1.20.0","axios-retry":"4.5.0",chalk:"^4.1.2",commander:"^14.0.0",debug:"^4.4.0",dotenv:"^17.4.2",execa:"^9.5.1","fs-extra":"^11.3.4",getos:"^3.2.1",globby:"^11.1.0","https-proxy-agent":"^7.0.4",lodash:"^4.18.1",nanoid:"^3.3.8","pretty-ms":"^7.0.1","proxy-from-env":"^1.1.0",semver:"^7.8.5","source-map-support":"^0.5.21",tmp:"^0.2.7","tmp-promise":"^3.0.3","ts-pattern":"^5.8.0",unzipper:"^0.12.3",uuid:"11.1.1",xml2js:"^0.6.2",xxhashjs:"^0.2.2"},bin:{currents:"./dist/bin/index.js","currents-cli":"./dist/bin/index.js"},files:["dist","docs","!**/*.map","!**/*/*.map"],keywords:["cloud test dashboard","test reporter","test results","currents","currents dashboard","ci"],exports:{".":{import:"./dist/index.js",require:"./dist/index.js",types:"./dist/index.d.ts"},"./discovery/jest":{import:"./dist/services/upload/discovery/jest/reporter.js",require:"./dist/services/upload/discovery/jest/reporter.js",types:"./dist/services/upload/discovery/jest/reporter.d.ts"},"./package.json":"./package.json"},"release-it":{npm:{publish:!1},github:{release:!0,releaseName:"${npm.name} v${version}"},plugins:{"@release-it/conventional-changelog":{preset:{name:"conventionalcommits"},header:"# Changelog",ignoreVersion:!0,infile:"./CHANGELOG.md"}},git:{commitMessage:"chore: release ${npm.name} v${version}",tagName:"${npm.name}-v${version}"}}};var At=Go.version;var lo=require("@commander-js/extra-typings");var hp=[];function Rr(t){hp.push(t)}var N=l(require("chalk")),q=l(require("util"));var wr=require("debug"),Ep=l(require("fs-extra")),p=(0,wr.debug)("currents"),Ip=null;function Ko(){wr.debug.enable("currents,currents:*")}function Ho(t){Ip=t}var Jo=[],Vo=[];var ce=(...t)=>{let e=q.default.format(...t);Rr(e),console.log(e)},Yo=(...t)=>{let e=q.default.format(...t);Rr(e),console.error(e)},T=ce,I=(...t)=>{let e=q.default.format(...t);return Vo.push(e),p("WARNING: ",e),ce(N.default.bgYellow.black(" WARNING "),e)},gt=(...t)=>{let e=q.default.format(...Wo(t));return p("WARNING: ",q.default.format(...t)),ce(N.default.bgYellow.black(" WARNING "),e)},pe=(...t)=>Yo(N.default.bgYellow.black(" WARNING "),q.default.format(...t)),de=(...t)=>ce(N.default.green.bold(q.default.format(...t))),C=(...t)=>{let e=q.default.format(...Wo(t));return Jo.push(e),p("ERROR: ",q.default.format(...t)),Yo(N.default.bgRed.white(" ERROR "),e)};var Wo=t=>t.map(e=>e instanceof Error?e.message:e),me=(t=2)=>console.log(Array(t).fill("").join(`
3
- `)),Il=N.default.cyan,Cl=N.default.blueBright,Tl=N.default.red,yl=N.default.yellow,Rl=N.default.green,wl=N.default.gray,_l=N.default.white,Ol=N.default.black,xl=N.default.magenta,x=N.default.dim,Sl=N.default.bold;var qo=80,_r=" ",Tp=" ";function yp(t){let e=t.match(/"[^"]*"|'[^']*'|\S+/g)??[],r=[];for(let o of e){let n=r[r.length-1];n?.startsWith("-")&&!n.includes(" ")&&!o.startsWith("-")?r[r.length-1]=`${n} ${o}`:r.push(o)}return r}function Rp(t){if(t.includes(`
2
+ "use strict";var xu=Object.create;var Yr=Object.defineProperty;var Su=Object.getOwnPropertyDescriptor;var Au=Object.getOwnPropertyNames;var bu=Object.getPrototypeOf,Pu=Object.prototype.hasOwnProperty;var Uu=(t,e)=>{for(var r in e)Yr(t,r,{get:e[r],enumerable:!0})},Du=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Au(e))!Pu.call(t,o)&&o!==r&&Yr(t,o,{get:()=>e[o],enumerable:!(n=Su(e,o))||n.enumerable});return t};var g=(t,e,r)=>(r=t!=null?xu(bu(t)):{},Du(e||!t||!t.__esModule?Yr(r,"default",{value:t,enumerable:!0}):r,t));var wt={name:"@currents/cmd",version:"3.0.0",main:"./dist/index.js",author:{name:"Currents Software Inc",email:"hello@currents.dev"},license:"MIT",repository:{type:"git",url:"https://github.com/currents-dev/currents-reporter"},description:"Currents CLI tools",engines:{node:">=22.13"},scripts:{test:"vitest",rm:"rimraf dist",lint:'TIMING=1 eslint "**/*.ts*"',types:"tsc --noEmit",build:"tsup-node --minify --dts",dev:"tsup-node --watch --dts",release:"release-it","publish:npm":"npm run rm && npm run build && ./publish.js"},devDependencies:{"@jest/reporters":"^30.5.2","@jest/types":"^30.4.1","@release-it/conventional-changelog":"^12.0.0","release-it":"^21.0.2","@types/debug":"^4.1.12","@types/fs-extra":"^11.0.4","@types/lodash":"^4.17.16","@types/node":"^25.5.0","@types/semver":"^7.5.8","@types/xml2js":"^0.4.14","@types/yauzl":"3.4.0","@types/yazl":"3.3.1","fs-extra":"^11.3.4",jest:"^30.4.2","jest-cli":"^30.4.2","jest-config":"^30.4.2",rimraf:"^6.0.1",tsup:"^8.3.5",typescript:"^5.9.3",vitest:"^4.1.11"},dependencies:{"@commander-js/extra-typings":"^14.0.0","@currents/commit-info":"3.0.0","@currents/rules":"0.1.0",commander:"^14.0.0",debug:"^4.4.0",dotenv:"17.4.2",lodash:"^4.18.1","proxy-from-env":"2.1.0",semver:"^7.8.5",tinyglobby:"^0.2.17",undici:"7.30.1",xml2js:"^0.6.2",yauzl:"3.4.0",yazl:"3.3.1"},bin:{currents:"./dist/bin/index.js","currents-cli":"./dist/bin/index.js"},files:["dist","docs","!**/*.map","!**/*/*.map"],keywords:["cloud test dashboard","test reporter","test results","currents","currents dashboard","ci"],exports:{".":{import:"./dist/index.js",require:"./dist/index.js",types:"./dist/index.d.ts"},"./discovery/jest":{import:"./dist/services/upload/discovery/jest/reporter.js",require:"./dist/services/upload/discovery/jest/reporter.js",types:"./dist/services/upload/discovery/jest/reporter.d.ts"},"./package.json":"./package.json"},"release-it":{npm:{publish:!1},github:{release:!0,releaseName:"${npm.name} v${version}"},plugins:{"@release-it/conventional-changelog":{preset:{name:"conventionalcommits"},header:"# Changelog",ignoreVersion:!0,infile:"./CHANGELOG.md"}},git:{commitMessage:"chore: release ${npm.name} v${version}",tagName:"${npm.name}-v${version}"}}};function Io(t=process.versions.node){let[e,r=0]=Wr(wt.engines.node.replace(">=","")),[n,o]=Wr(t);if(n>e||n===e&&o>=r)return;let s=Wr(wt.version)[0]-1;throw new Error(`${wt.name} requires Node.js ${e}.${r} or later. This is Node.js ${t}. Upgrade Node.js, or use ${wt.name}@${s} with older Node.js versions.`)}function Wr(t){return t.replace(/^v/,"").split(".").map(Number)}try{Io()}catch(t){console.error(t.message),process.exit(1)}var bP=require("dotenv/config");var wu=require("@commander-js/extra-typings");var Bt=wt.version;var Jn=require("@commander-js/extra-typings");var vu=[];function zr(t){vu.push(t)}var V=g(require("util"));var Qr=require("debug"),Lu=g(require("fs")),d=(0,Qr.debug)("currents"),Bu=null;function To(){Qr.debug.enable("currents,currents:*")}function Co(t){Bu=t}var yo=[],Ro=[];var k=(...t)=>(...e)=>{let r=e.join(" ");return r?t.reduceRight((n,o)=>(0,V.styleText)(o,n),r):""},Ue=(...t)=>{let e=V.default.format(...t);zr(e),console.log(e)},wo=(...t)=>{let e=V.default.format(...t);zr(e),console.error(e)},C=Ue,I=(...t)=>{let e=V.default.format(...t);return Ro.push(e),d("WARNING: ",e),Ue(k("bgYellow","black")(" WARNING "),e)},_t=(...t)=>{let e=V.default.format(..._o(t));return d("WARNING: ",V.default.format(...t)),Ue(k("bgYellow","black")(" WARNING "),e)},De=(...t)=>wo(k("bgYellow","black")(" WARNING "),V.default.format(...t)),Ne=(...t)=>Ue(k("green","bold")(V.default.format(...t))),T=(...t)=>{let e=V.default.format(..._o(t));return yo.push(e),d("ERROR: ",V.default.format(...t)),wo(k("bgRed","white")(" ERROR "),e)};var _o=t=>t.map(e=>e instanceof Error?e.message:e),ve=(t=2)=>console.log(Array(t).fill("").join(`
3
+ `)),th=k("cyan"),eh=k("blueBright"),rh=k("red"),nh=k("yellow"),oh=k("green"),sh=k("gray"),ih=k("white"),ah=k("black"),ch=k("magenta"),b=k("dim"),ph=k("bold");var Oo=80,Xr=" ",ku=" ";function Mu(t){let e=t.match(/"[^"]*"|'[^']*'|\S+/g)??[],r=[];for(let n of e){let o=r[r.length-1];o?.startsWith("-")&&!o.includes(" ")&&!n.startsWith("-")?r[r.length-1]=`${o} ${n}`:r.push(n)}return r}function $u(t){if(t.includes(`
4
4
  `))return t.split(`
5
- `).map(o=>_r+o);let e=[],r=_r;for(let o of yp(t)){let n=r.trim()==="";!n&&r.length+1+o.length+2>qo?(e.push(`${r} \\`),r=Tp+o):r=n?r+o:`${r} ${o}`}return[...e,r]}function wp(t){let e=`${_r}# `,r=[],o=e;for(let n of t.split(" "))o!==e&&o.length+1+n.length>qo?(r.push(o),o=e+n):o=o===e?o+n:`${o} ${n}`;return[...r,o].map(n=>x(n))}function y(t){return`
5
+ `).map(n=>Xr+n);let e=[],r=Xr;for(let n of Mu(t)){let o=r.trim()==="";!o&&r.length+1+n.length+2>Oo?(e.push(`${r} \\`),r=ku+n):r=o?r+n:`${r} ${n}`}return[...e,r]}function ju(t){let e=`${Xr}# `,r=[],n=e;for(let o of t.split(" "))n!==e&&n.length+1+o.length>Oo?(r.push(n),n=e+o):n=n===e?n+o:`${n} ${o}`;return[...r,n].map(o=>b(o))}function y(t){return`
6
6
  Examples:
7
- ${t.map(r=>[...wp(r.comment),...r.commands.flatMap(Rp)].join(`
7
+ ${t.map(r=>[...ju(r.comment),...r.commands.flatMap($u)].join(`
8
8
  `)).join(`
9
9
 
10
10
  `)}
11
- `}var Or=l(require("lodash")),_p=["apiKey","recordKey","key"];function zo(t,e){return Or.default.isPlainObject(t)?Or.default.mapValues(t,(r,o)=>e.includes(o)&&r!==void 0?"*****":zo(r,e)):t}function h(t){return zo(t,_p)}var z=class extends Error{};var K=l(require("fs-extra")),ht=require("path"),Qo=require("uuid");async function Et(t){try{return await K.default.readJson(t)}catch(e){throw C("Error while reading JSON file: %s",t,e),C}}async function It(t,e){try{return await K.default.writeFile(t,e,"utf8"),t}catch(r){throw C(`Error writing file at ${t}:`,r),r}}async function Yt(t,e){try{try{return await K.default.access(t),t}catch{return await K.default.writeFile(t,e,"utf8"),t}}catch(r){throw C(`Error writing file at ${t}:`,r),r}}async function Xo(t,e){if(e){await K.default.ensureDir(t);return}let r=(0,ht.dirname)(t);await K.default.ensureDir(r)}function Op(){let t=new Date().toISOString().replace(/[:.]/g,"-"),e=(0,Qo.v4)();return`${t}-${e}`}async function Zo(t,e){let r=Op(),o=(0,ht.join)(t,e,r);return Ct(o)}async function Ct(t){try{return await K.default.ensureDir(t),p("Folder created",t),t}catch(e){throw C(`Failed to create folder at ${t}:`,e),e}}async function ue(t,e){try{return await K.default.ensureDir((0,ht.dirname)(e)),await K.default.copy(t,e),p("File copied from %s to %s",t,e),e}catch(r){throw C(`Failed to copy file from ${t} to ${e}:`,r),r}}function le(t,e){let r=e;for(;!K.default.existsSync((0,ht.join)(r,t));){let o=(0,ht.dirname)(r);if(o===r)return;r=o}return r}var tn=l(require("crypto"));function et(t){return tn.createHash("sha256").update(t).digest("base64").slice(0,8).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}var fe={};lp(fe,{getNanoid:()=>Sr,userFacingNanoid:()=>Ar});var xr=require("nanoid"),en="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",Sr=(t=16)=>(0,xr.customAlphabet)(en,t)(),Ar=(0,xr.customAlphabet)(en,12);function Dr(t){return t.replace(/^([a-z][a-z0-9+.-]*:\/\/)[^/?#\s]*@/i,"$1")}function Dt(t){return Dr(t).replace(/[?#].*$/,"")}function xp(t){return Object.entries(t??{}).reduce((e,[r,o])=>o===void 0?e:{...e,[r]:o},{})}function rn(t){if(!(t===void 0||t.trim()===""))return!["false","0","no","off"].includes(t.trim().toLowerCase())}function L(t,e){return"env"in t[e]&&t[e].env?t[e].env:""}function ge(t,e){return t[e].cli}function he(t,e){return t[e].name}function U(t,e,r,o){let n=xp(r);return e.forEach(s=>{if(!n[s]){let i=s,c=L(t,i);throw C(`${he(t,i)} is required: pass ${x(ge(t,i))}${c?` or set ${x(c)}`:""}`),new z("Missing required config variable")}}),typeof o=="function"&&o(n),n}var _={apiKey:{name:"API key",env:"CURRENTS_API_KEY",cli:"--api-key"},recordKey:{name:"Record key",env:"CURRENTS_RECORD_KEY",cli:"--key"},projectId:{name:"Project ID",env:"CURRENTS_PROJECT_ID",cli:"--project-id"},ciBuildId:{name:"CI build ID",env:"CURRENTS_CI_BUILD_ID",cli:"--ci-build-id"},machineId:{name:"Machine ID",env:"CURRENTS_MACHINE_ID",cli:"--machine-id"},tag:{name:"Tag",cli:"--tag"},debug:{name:"Debug",env:"CURRENTS_DEBUG",cli:"--debug"}};var{apiKey:Sp,debug:Ap,ciBuildId:Dp,projectId:Up,tag:Pp}=_,Ee={apiKey:Sp,debug:Ap,ciBuildId:Dp,projectId:Up,tag:Pp,branch:{name:"Branch",cli:"--branch"},output:{name:"Output file",env:"CURRENTS_OUTPUT",cli:"--output"}};var bp=p.extend("config"),Np=["apiKey","projectId"],Lp=t=>{let{ciBuildId:e,tag:r,branch:o}=t;if(!([e,r,o].filter(Boolean).length===1||r&&o&&!e))throw C("Pass --ci-build-id, or --branch, --tag or both"),new z("Missing or invalid parameters")},Ur=null;function on(t){Ur=U(Ee,Np,t,Lp),bp("Resolved config: %o",h(Ur))}function Ie(){return Ur}var Mn=require("fs/promises");function Ut({apiKey:t,recordKey:e}){return e?{"x-currents-key":e}:t?{Authorization:`Bearer ${t}`}:{}}var yn=l(require("lodash"));var ln=l(require("axios")),fn=l(require("axios-retry")),vr=l(require("lodash"));var nn=()=>process.env.CURRENTS_API_URL??"https://cy.currents.dev",Wt=()=>process.env.CURRENTS_REST_API_URL??"https://api.currents.dev",sn=()=>3e4;var Ce=require("axios"),Pr=l(require("pretty-ms"));var cn=p.extend("http"),an=[3*1e3,15*1e3,30*1e3],pn=60*1e3;function Re(t,e=Date.now()){let r=t?.response?.headers?.["retry-after"];if(r==null||r==="")return;let o=Number(r);if(Number.isFinite(o))return Math.max(0,o*1e3);let n=Date.parse(String(r));return Number.isNaN(n)?void 0:Math.max(0,n-e)}var Te=(t,e)=>{let r=an[Math.min(t,an.length)-1],o=Re(e);return o===void 0?r:Math.min(Math.max(o,r),pn)},br=t=>(cn("isRetriableError: %o",{message:t.message,code:"code"in t?t.code:void 0,status:"response"in t?t.response?.status:void 0,headers:"response"in t?t.response?.headers:void 0,data:"response"in t?t.response?.data:void 0,isAxiosError:(0,Ce.isAxiosError)(t)}),"code"in t&&t.code&&["ECONNABORTED","ECONNREFUSED","ECONNRESET","ETIMEDOUT","ENETRESET"].includes(t.code)?!0:(0,Ce.isAxiosError)(t)?[408,429,502,503,504].includes(t.response?.status??0):!1),vp=["get","head","options","put","delete"],dn=t=>{if(!(0,Ce.isAxiosError)(t))return!1;let e=t.response?.status;if(e===429){let r=Re(t);return r===void 0||r<=pn}return vp.includes(t.config?.method?.toLowerCase()??"get")?br(t):e===408||t.code==="ECONNREFUSED"||t.code==="ENOTFOUND"},ye=()=>3;function mn(t,e,r){cn("Network request '%s' failed: '%s'. Next attempt is in %s (%d/%d).",`${r.method?.toUpperCase()} ${r.url}`,e.message,(0,Pr.default)(Te(t,e)??0),t,ye()),I("Network request '%s' failed: '%s'. Next attempt is in %s (%d/%d).",`${r.method?.toUpperCase()} ${r.url}`,e.message,(0,Pr.default)(Te(t,e)??0),t,ye())}var Nr=p.extend("http");var Lr={api:null,restApi:null};function Bp(t){let e=t==="api"?nn():Wt();Nr("client base url: %s",e);let r=ln.default.create({baseURL:e,timeout:sn(),transitional:{clarifyTimeoutError:!0}});return r.interceptors.request.use(o=>{let n=o["axios-retry"]?.retryCount??0;o.headers.set({"x-cmd-version":At}),o.headers.get("Content-Type")||o.headers.set("Content-Type","application/json");let s={...vr.default.pick(o,"method","url","headers"),baseURL:e,data:Buffer.isBuffer(o.data)?"buffer":o.data,params:o.params};return n?Nr("network request retry: %o",un({...s,baseURL:e,isRetry:!0})):Nr("network request: %o",un(s)),o}),(0,fn.default)(r,{retries:ye(),retryCondition:t==="restApi"?dn:br,retryDelay:(o,n)=>Te(o,n),shouldResetTimeout:!0,onRetry:mn}),r}function Pt(t){return Lr[t]===null&&(Lr[t]=Bp(t)),Lr[t]}function un(t){return{method:t.method,baseURL:t.baseURL,url:t.url,data:t.isRetry?"<retry>":Fp(t.data),params:t.isRetry?"<retry>":t.params,headers:{...t.headers,Authorization:"Bearer ***","x-currents-key":"***"}}}function Fp(t){if(t?.results?.raw)return h({...t,results:{...t.results,raw:"***"}});if(typeof t=="string")try{return h(JSON.parse(t))}catch{return t}return vr.default.isPlainObject(t)?h(t):t}var En=require("axios"),In=l(require("lodash")),B=require("ts-pattern");function Cn(t){(0,B.match)(t).when(En.isAxiosError,Mp).otherwise(()=>{I("Unexpected error while sending network request: %s",t)})}function Mp(t){return(0,B.match)(t).with({code:"ECONNABORTED"},()=>{I("Network connection aborted")}).with({code:"ECONNREFUSED"},()=>{I("Network connection aborted")}).with({code:"ECONNRESET"},()=>{I("Network connection reset")}).with({code:"ETIMEDOUT"},()=>{I("Network connection timeout")}).with({response:B.P.not(B.P.nullish)},e=>{kp(e,{status:e.response.status,data:e.response.data})}).otherwise(e=>{I(`[currents] Unexpected network error: %s
12
- %O`,t.message,{method:t.response?.config.method,url:t.response?.config.url,status:t.response?.status,payload:t.response?.config.data})})}function kp(t,{status:e,data:r}){(0,B.match)(e).with(401,()=>{I(`[currents] ${t.response?.config.method} ${t.response?.config.url} - 401 Unauthorized Request from cloud service`)}).with(400,()=>{I(`[currents] ${t.response?.config.method} ${t.response?.config.url} - 400 Bad Request from cloud service:
13
- %o`,r)}).with(404,()=>{I(`[currents] ${t.response?.config.method} ${t.response?.config.url} - 404 Not Found from cloud service`)}).with(429,()=>{I(`[currents] ${t.response?.config.method} ${t.response?.config.url} - 429 Too Many Requests from cloud service`)}).with(422,()=>{jp(t,r)}).otherwise(()=>{I(`[currents] Unexpected network response: %s
14
- %O`,t.message,{method:t.response?.config.method,url:t.response?.config.url,status:t.response?.status})})}function jp(t,e){(0,B.match)(e).with({code:gn.MISSING_SUITE,message:B.P.string,errors:B.P.array(B.P.string)},async r=>{let{message:o,errors:n}=r;me(1),C(...hn(o,n))}).with({code:gn.RUN_EXPIRED,message:B.P.string},r=>{I(r.message)}).with({message:B.P.string,errors:B.P.array(B.P.string)},r=>{let{message:o,errors:n}=r;me(1),I(...hn(o,n)),me(1)}).otherwise(()=>{I(`[currents] Unexpected network response: %s
15
- %O`,t.message,{method:t.response?.config.method,url:t.response?.config.url,status:t.response?.status})})}var gn={RUN_CANCELLED:"RUN_CANCELLED",RUN_EXPIRED:"RUN_EXPIRED",MISSING_SUITE:"MISSING_SUITE"};function hn(t,e){return In.default.isString(t)?e?.length===0?[t]:[t,`
11
+ `}var Zr=g(require("lodash")),Hu=["apiKey","recordKey","key"];function xo(t,e){return Zr.default.isPlainObject(t)?Zr.default.mapValues(t,(r,n)=>e.includes(n)&&r!==void 0?"*****":xo(r,e)):t}function E(t){return xo(t,Hu)}var Q=class extends Error{};var tn=require("crypto"),So=require("fs"),q=g(require("fs/promises")),Ao=require("os"),gt=require("path");function Le(t){let e=0,r=[];return async n=>{e<t?e++:await new Promise(o=>r.push(o));try{return await n()}finally{let o=r.shift();o?o():e--}}}var ct=Le(32);async function pt(t){let e=await q.default.readFile(t,"utf8");try{return JSON.parse(e.replace(/^\uFEFF/,""))}catch(r){throw r.message=`${t}: ${r.message}`,r}}function P(t){return q.default.access(t).then(()=>!0,()=>!1)}async function Ot(t){try{return await pt(t)}catch(e){throw T("Error while reading JSON file: %s",t,e),T}}async function xt(t,e){try{return await q.default.writeFile(t,e,"utf8"),t}catch(r){throw T(`Error writing file at ${t}:`,r),r}}async function St(t,e){try{try{return await q.default.access(t),t}catch{return await q.default.writeFile(t,e,"utf8"),t}}catch(r){throw T(`Error writing file at ${t}:`,r),r}}async function bo(t,e){if(e){await q.default.mkdir(t,{recursive:!0});return}let r=(0,gt.dirname)(t);await q.default.mkdir(r,{recursive:!0})}async function Be(t=""){let e=(0,gt.join)((0,Ao.tmpdir)(),`currents-${(0,tn.randomUUID)()}${t}`);return await q.default.writeFile(e,"",{flag:"wx",mode:384}),e}function Gu(){let t=new Date().toISOString().replace(/[:.]/g,"-"),e=(0,tn.randomUUID)();return`${t}-${e}`}async function Po(t,e){let r=Gu(),n=(0,gt.join)(t,e,r);return At(n)}async function At(t){try{return await q.default.mkdir(t,{recursive:!0}),d("Folder created",t),t}catch(e){throw T(`Failed to create folder at ${t}:`,e),e}}async function Fe(t,e){try{return await q.default.mkdir((0,gt.dirname)(e),{recursive:!0}),await q.default.cp(t,e,{recursive:!0,verbatimSymlinks:!0}),d("File copied from %s to %s",t,e),e}catch(r){throw T(`Failed to copy file from ${t} to ${e}:`,r),r}}function ke(t,e){let r=e;for(;!(0,So.existsSync)((0,gt.join)(r,t));){let n=(0,gt.dirname)(r);if(n===r)return;r=n}return r}var Uo=g(require("crypto"));function X(t){return Uo.createHash("sha256").update(t).digest("base64").slice(0,8).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}var $e={};Uu($e,{getNanoid:()=>Me,userFacingNanoid:()=>en});var No=require("crypto"),Do="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",Me=(t=16)=>Array.from({length:t},()=>Do[(0,No.randomInt)(Do.length)]).join(""),en=()=>Me(12);function rn(t){return t.replace(/^([a-z][a-z0-9+.-]*:\/\/)[^/?#\s]*@/i,"$1")}function Ft(t){return rn(t).replace(/[?#].*$/,"")}function Ku(t){return Object.entries(t??{}).reduce((e,[r,n])=>n===void 0?e:{...e,[r]:n},{})}function vo(t){if(!(t===void 0||t.trim()===""))return!["false","0","no","off"].includes(t.trim().toLowerCase())}function U(t,e){return"env"in t[e]&&t[e].env?t[e].env:""}function je(t,e){return t[e].cli}function He(t,e){return t[e].name}function D(t,e,r,n){let o=Ku(r);return e.forEach(s=>{if(!o[s]){let i=s,a=U(t,i);throw T(`${He(t,i)} is required: pass ${b(je(t,i))}${a?` or set ${b(a)}`:""}`),new Q("Missing required config variable")}}),typeof n=="function"&&n(o),o}var x={apiKey:{name:"API key",env:"CURRENTS_API_KEY",cli:"--api-key"},recordKey:{name:"Record key",env:"CURRENTS_RECORD_KEY",cli:"--key"},projectId:{name:"Project ID",env:"CURRENTS_PROJECT_ID",cli:"--project-id"},ciBuildId:{name:"CI build ID",env:"CURRENTS_CI_BUILD_ID",cli:"--ci-build-id"},machineId:{name:"Machine ID",env:"CURRENTS_MACHINE_ID",cli:"--machine-id"},tag:{name:"Tag",cli:"--tag"},debug:{name:"Debug",env:"CURRENTS_DEBUG",cli:"--debug"}};var{apiKey:Ju,debug:Vu,ciBuildId:qu,projectId:Yu,tag:Wu}=x,Ge={apiKey:Ju,debug:Vu,ciBuildId:qu,projectId:Yu,tag:Wu,branch:{name:"Branch",cli:"--branch"},output:{name:"Output file",env:"CURRENTS_OUTPUT",cli:"--output"}};var zu=d.extend("config"),Qu=["apiKey","projectId"],Xu=t=>{let{ciBuildId:e,tag:r,branch:n}=t;if(!([e,r,n].filter(Boolean).length===1||r&&n&&!e))throw T("Pass --ci-build-id, or --branch, --tag or both"),new Q("Missing or invalid parameters")},nn=null;function Lo(t){nn=D(Ge,Qu,t,Xu),zu("Resolved config: %o",E(nn))}function Ke(){return nn}var Ls=require("fs/promises");function kt({apiKey:t,recordKey:e}){return e?{"x-currents-key":e}:t?{Authorization:`Bearer ${t}`}:{}}var ds=require("timers/promises"),ln=g(require("lodash"));var Bo=()=>process.env.CURRENTS_API_URL??"https://cy.currents.dev",ie=()=>process.env.CURRENTS_REST_API_URL??"https://api.currents.dev",Fo=()=>3e4;var ts=require("http"),pn=require("stream"),ae=require("util"),$t=g(require("zlib")),es=require("undici");var Mt=require("undici");var Yo=require("proxy-from-env");var Zu=new Set(["localhost","0.0.0.0"]),$o=t=>{let e=t.length;for(;e&&t.charCodeAt(e-1)===46;)e--;return e===t.length?t:t.slice(0,e)},jo=t=>{let e=t.split(".");return e.length!==4||e[0]!=="127"?!1:e.every(r=>/^\d+$/.test(r)&&Number(r)>=0&&Number(r)<=255)},on=t=>{if(/^0[xX][0-9a-fA-F]+$/.test(t)){let e=parseInt(t.slice(2),16);return Number.isFinite(e)?e:null}if(t.length>1&&/^0[0-7]+$/.test(t)){let e=parseInt(t,8);return Number.isFinite(e)?e:null}if(t.length>1&&/^0[0-9]+$/.test(t))return null;if(/^[0-9]+$/.test(t)){let e=parseInt(t,10);return Number.isFinite(e)?e:null}return null},Ho=t=>{if(typeof t!="string"||!t||t.indexOf(":")!==-1)return t;let e=t;if(e.charAt(0)==="["&&e.charAt(e.length-1)==="]"&&(e=e.slice(1,-1)),e=$o(e),!/^[0-9.xXa-fA-F]+$/.test(e))return t;let r=e.split(".");if(r.some(l=>l===""))return t;if(r.length===4){let l=r.map(on);return l.some(m=>m===null||m<0||m>255)?t:l.join(".")}if(r.length>4||r.length===1)return t;let n=r.slice(0,-1),o=r[r.length-1],s=4-n.length,i=on(o);if(i===null)return t;let a=(1<<8*s)-1;if(i<0||i>a)return t;let u=new Array(s).fill(0);for(let l=s-1,m=i;l>=0;l--,m>>=8)u[l]=m&255;let p=n.map(on);return p.some(l=>l===null||l<0||l>255)?t:[...p,...u].join(".")},sn=t=>/^0{1,4}$/.test(t),td=t=>{if(t==="::")return!0;let e=t.indexOf("::");if(e!==-1){if(e!==t.lastIndexOf("::"))return!1;let n=t.slice(0,e),o=t.slice(e+2),s=n?n.split(":"):[],i=o?o.split(":"):[];return s.length+i.length<8&&s.every(sn)&&i.every(sn)}let r=t.split(":");return r.length===8&&r.every(sn)},ed=t=>{if(t==="::1")return!0;let e=t.match(/^::ffff:(\d+\.\d+\.\d+\.\d+)$/i);if(e)return jo(e[1]);let r=t.match(/^::ffff:([0-9a-f]{1,4}):([0-9a-f]{1,4})$/i);if(r){let o=parseInt(r[1],16);return o>=32512&&o<=32767}let n=t.split(":");if(n.length===8){for(let o=0;o<7;o++)if(!/^0+$/.test(n[o]))return!1;return/^0*1$/.test(n[7])}return!1},ko=t=>t?Zu.has(t)||jo(t)||td(t)?!0:ed(t):!1,rd={http:80,https:443,ws:80,wss:443,ftp:21},nd=t=>{let e=t,r=0;if(e.charAt(0)==="["){let s=e.indexOf("]");if(s!==-1){let i=e.slice(1,s),a=e.slice(s+1);return a.charAt(0)===":"&&/^\d+$/.test(a.slice(1))&&(r=Number.parseInt(a.slice(1),10)),[i,r]}}let n=e.indexOf(":"),o=e.lastIndexOf(":");return n!==-1&&n===o&&/^\d+$/.test(e.slice(o+1))&&(r=Number.parseInt(e.slice(o+1),10),e=e.slice(0,o)),[e,r]},od=/^(?:::|(?:0{1,4}:){1,4}:|(?:0{1,4}:){5})ffff:(\d+\.\d+\.\d+\.\d+)$/i,sd=/^(?:::|(?:0{1,4}:){1,4}:|(?:0{1,4}:){5})ffff:([0-9a-f]{1,4}):([0-9a-f]{1,4})$/i,Go=t=>{if(typeof t!="string"||t.indexOf(":")===-1)return t;let e=t.match(od);if(e)return e[1];let r=t.match(sd);if(r){let n=parseInt(r[1],16),o=parseInt(r[2],16);return`${n>>8}.${n&255}.${o>>8}.${o&255}`}return t},id=/^(?:0|[1-9]\d{0,2})$/,Ko=t=>{let e=t.split(".");return e.length===4&&e.every(r=>id.test(r)&&Number(r)<=255)?e.map(Number):null},ad=/^[0-9a-f]{1,4}$/i,cd=t=>{let e=t.split("::");if(e.length>2)return null;let r=e[0]?e[0].split(":"):[];if(e.length===2){let n=e[1]?e[1].split(":"):[],o=8-r.length-n.length;if(o<1)return null;r.push(...new Array(o).fill("0"),...n)}return r.length!==8||r.some(n=>!ad.test(n))?null:r.flatMap(n=>{let o=Number.parseInt(n,16);return[o>>8&255,o&255]})},Jo=t=>typeof t!="string"||!t?null:t.indexOf(":")!==-1?cd(t):Ko(t),Mo=t=>{if(!t)return t;t.charAt(0)==="["&&t.charAt(t.length-1)==="]"&&(t=t.slice(1,-1));let e=$o(t),r=Ho(e);return r!==e?r:Go(e)},pd=t=>{let e=t,r=e.charAt(0)==="[",n=e.charAt(e.length-1)==="]",o=e.includes("[")||e.includes("]");if(r||n){if(!r||!n||(e=e.slice(1,-1),e.indexOf(":")===-1||e.includes("[")||e.includes("]")))return null}else if(o)return null;if(!e||e.charAt(e.length-1)===".")return null;let s=e.indexOf(":")!==-1;if(s)try{e=new URL(`http://[${e}]/`).hostname.slice(1,-1)}catch{return null}else if(e=Ho(e),!Ko(e))return null;return{normalized:Go(e),wasIPv6:s}},ud=/^(.+)\/(0|[1-9]\d{0,2})$/,dd=t=>{if(t.indexOf("/")===-1)return;let e=ud.exec(t);if(!e)return null;let r=Number(e[2]),n=pd(e[1]);if(!n)return null;let{normalized:o,wasIPv6:s}=n;if(s&&o.indexOf(":")===-1){if(r<96)return null;r-=96}let i=Jo(o);return!i||r>i.length*8?null:{bytes:i,prefix:r}},md=(t,e,r)=>{let n=r>>3;for(let s=0;s<n;s++)if(t[s]!==e[s])return!1;let o=r&7;if(o){let s=255<<8-o&255;if((t[n]&s)!==(e[n]&s))return!1}return!0};function Vo(t,e){let r;try{r=new URL(t)}catch{return!1}let n=e.toLowerCase();if(!n)return!1;if(n==="*")return!0;let o=Number.parseInt(r.port,10)||rd[r.protocol.split(":",1)[0]]||0,s=Mo(r.hostname.toLowerCase()),i=Jo(s);return n.split(/[\s,]+/).some(a=>{if(!a)return!1;if(a==="*")return!0;let u=dd(a);if(u!==void 0)return u!==null&&!!i&&i.length===u.bytes.length&&md(i,u.bytes,u.prefix);let[p,l]=nd(a);return p=Mo(p),!p||l&&l!==o?!1:(p.charAt(0)==="*"&&(p=p.slice(1)),p.charAt(0)==="."?s.endsWith(p):s===p||ko(s)&&ko(p))})}var ld=d.extend("http");function fd(t){return process.env[t.toLowerCase()]||process.env[t.toUpperCase()]||""}function gd(t){let e=(0,Yo.getProxyForUrl)(t);return!e||Vo(t,fd("no_proxy"))?"":e}var an={headersTimeout:0,bodyTimeout:0},hd=new Mt.Agent({...an,connect:{timeout:0}}),qo=new Map;function Ed(t){let e=qo.get(t);if(e)return e;let{username:r,password:n}=new URL(t);return e=new Mt.ProxyAgent({uri:t,token:r||n?`Basic ${Buffer.from(`${decodeURIComponent(r)}:${decodeURIComponent(n)}`).toString("base64")}`:void 0,proxyTunnel:!1,proxyTls:{timeout:0},...an,factory:(o,s)=>new Mt.Pool(o,{...s,...an})}),qo.set(t,e),e}function Wo(t){let e=gd(t);return e?(ld("Using HTTP proxy %s for %s",Ft(e),Ft(t)),Ed(e)):hd}var H=class extends Error{constructor(r,n,o,s){super(r);this.code=n;this.config=o;this.response=s;this.name="HttpError"}get status(){return this.response?.status}};function L(t){return t instanceof H}var Id=21,Td=/^(?:(?:proxy-)?authorization|cookie)$/i;async function bt(t){let e={method:t.method.toLowerCase(),url:t.url,data:t.body},{res:r,method:n}=await Cd(t,e),o=await xd(r,n,t.responseType??"json",e);if(o.status<200||o.status>=300)throw new H(`Request failed with status code ${o.status}`,o.status<500?"ERR_BAD_REQUEST":"ERR_BAD_RESPONSE",e,o);return o}async function Cd(t,e){let r=t.timeout??0,n=new AbortController,o=yd(t,n.signal,r),s,i=new Promise((a,u)=>{r<=0||(s=setTimeout(()=>{u(new H(`timeout of ${r}ms exceeded`,"ETIMEDOUT",e)),n.abort(),o.then(({res:p})=>p.body.destroy(),()=>{})},r))});try{return await Promise.race([o,i])}catch(a){throw a instanceof H?a:Sd(a,e)}finally{clearTimeout(s)}}async function yd(t,e,r){let{url:n,body:o}=t,s=t.method.toUpperCase(),i=Rd(t.headers??{},o);for(let a=0;;a++){let u=await(0,es.request)(n,{method:s,headers:i,body:o,signal:e,bodyTimeout:r,dispatcher:Wo(n),reset:!1}),p=u.headers.location;if(u.statusCode<300||u.statusCode>=400||typeof p!="string"||o instanceof pn.Readable)return{res:u,method:s};if(await u.body.dump(),a>=Id)throw Object.assign(new Error("Maximum number of redirects exceeded"),{code:"ERR_FR_TOO_MANY_REDIRECTS"});((u.statusCode===301||u.statusCode===302)&&s==="POST"||u.statusCode===303&&!/^(?:GET|HEAD)$/.test(s))&&(s="GET",o=void 0,i=zo(i,/^content-/i));let l=new URL(n),m=new URL(p,l);(m.protocol!==l.protocol&&m.protocol!=="https:"||m.host!==l.host&&!m.host.endsWith(`.${l.host}`))&&(i=zo(i,Td)),n=m.href}}function Rd(t,e){let r={accept:"application/json, text/plain, */*","user-agent":"axios/1.20.0","accept-encoding":"gzip, compress, deflate, br"};e&&!(e instanceof pn.Readable)&&(r["content-length"]=String(Buffer.byteLength(e)));for(let[n,o]of Object.entries(t))r[n.toLowerCase()]=o;return r}function zo(t,e){return Object.fromEntries(Object.entries(t).filter(([r])=>!e.test(r)))}var Qo=(0,ae.promisify)($t.default.unzip),wd=(0,ae.promisify)($t.default.inflateRaw),_d=(0,ae.promisify)($t.default.brotliDecompress),cn=typeof $t.default.zstdDecompress=="function"?(0,ae.promisify)($t.default.zstdDecompress):void 0,Xo=t=>["gzip","x-gzip","compress","x-compress","deflate","br"].includes(t)||t==="zstd"&&cn!==void 0;function Od(t,e){return e==="br"?_d(t):e==="zstd"&&cn?cn(t):e==="deflate"?Qo(t).catch(()=>wd(t)):Qo(t)}async function xd(t,e,r,n){let o={...t.headers},s=String(o["content-encoding"]??"").toLowerCase();s&&Xo(s)&&delete o["content-encoding"];let i={status:t.statusCode,statusText:t.statusText,headers:o};if(e==="HEAD"||t.statusCode===204||t.statusCode===304)return delete o["content-encoding"],await t.body.dump(),{...i,data:Zo(Buffer.alloc(0),r)};let a;try{a=Buffer.from(await t.body.arrayBuffer())}catch{throw new H("stream has been aborted","ERR_BAD_RESPONSE",n,{...i,data:void 0})}if(s&&Xo(s)&&a.length>0)try{a=await Od(a,s)}catch(u){let p=u;throw new H(p.message,p.code,n,{...i,data:void 0})}return{...i,data:Zo(a,r)}}function Zo(t,e){if(e==="buffer")return t;let r=t.toString("utf8").replace(/^\uFEFF/,"");if(e==="text"||!r)return r;try{return JSON.parse(r)}catch{return r}}function Sd(t,e){let r=t,n=Ad(r);if(n)return new H(`Request failed with status code ${n}`,n<500?"ERR_BAD_REQUEST":"ERR_BAD_RESPONSE",e,{status:n,statusText:ts.STATUS_CODES[n]??"",headers:{},data:""});if(r.code==="UND_ERR_SOCKET")return new H("socket hang up","ECONNRESET",e);let o=!r.message&&r.errors?r.errors.map(s=>s.message).join("; "):r.message;return new H(o,r.code,e)}function Ad(t){let e=t.message?.match(/^Proxy response \((\d{3})\) !== 200 when HTTP Tunneling$/)??t.message?.match(/^Proxy Authentication Required \((407)\)$/);return e?Number(e[1]):void 0}function rs(t){return["UND_ERR_INVALID_ARG","UND_ERR_NOT_SUPPORTED","UND_ERR_REQ_CONTENT_LENGTH_MISMATCH"].includes(t.code??"")}var ss=d.extend("http"),ns=[3*1e3,15*1e3,30*1e3],is=60*1e3;function qe(t,e=Date.now()){let r=t?.response?.headers?.["retry-after"];if(r==null||r==="")return;let n=Number(r);if(Number.isFinite(n))return Math.max(0,n*1e3);let o=Date.parse(String(r));return Number.isNaN(o)?void 0:Math.max(0,o-e)}var Je=(t,e)=>{let r=ns[Math.min(t,ns.length)-1],n=qe(e);return n===void 0?r:Math.min(Math.max(n,r),is)},un=t=>(ss("isRetriableError: %o",{message:t.message,code:"code"in t?t.code:void 0,status:"response"in t?t.response?.status:void 0,headers:"response"in t?t.response?.headers:void 0,data:"response"in t?t.response?.data:void 0,isHttpError:L(t)}),"code"in t&&t.code&&["ECONNABORTED","ECONNREFUSED","ECONNRESET","ETIMEDOUT","ENETRESET"].includes(t.code)?!0:L(t)?[408,429,502,503,504].includes(t.response?.status??0):!1),bd=["get","head","options","put","delete"],as=t=>{if(!L(t))return!1;let e=t.response?.status;if(e===429){let r=qe(t);return r===void 0||r<=is}return bd.includes(t.config?.method?.toLowerCase()??"get")?un(t):e===408||t.code==="ECONNREFUSED"||t.code==="ENOTFOUND"},Ve=()=>3;function os(t){let e=[],r=Math.trunc(t/36e5),n=Math.trunc(t/6e4)%60;if(r&&e.push(`${r}h`),n&&e.push(`${n}m`),t<1e3){let o=t>=1?Math.round(t):Math.ceil(t);o&&e.push(`${o}ms`)}else{let o=Math.floor(t/1e3%60*10+1e-7)/10;o&&e.push(`${o}s`)}return e.join(" ")||"0ms"}function cs(t,e,r){ss("Network request '%s' failed: '%s'. Next attempt is in %s (%d/%d).",`${r.method?.toUpperCase()} ${r.url}`,e.message,os(Je(t,e)??0),t,Ve()),I("Network request '%s' failed: '%s'. Next attempt is in %s (%d/%d).",`${r.method?.toUpperCase()} ${r.url}`,e.message,os(Je(t,e)??0),t,Ve())}var mn=d.extend("http");var dn={api:null,restApi:null};function Pd(t){let e=t==="api"?Bo():ie();mn("client base url: %s",e);let r=Ve(),n=t==="restApi"?as:un;return{async request(o){let s={"content-type":"application/json",...ln.default.mapKeys(o.headers??{},(u,p)=>p.toLowerCase()),"x-cmd-version":Bt},i=Ud(o.data),a=Dd(e,o.url,o.params);for(let u=0;;u++){vd(e,o,s,u>0);try{return await bt({method:o.method,url:a,headers:s,body:i,timeout:Fo(),responseType:o.responseType})}catch(p){if(p instanceof H&&(p.config.url=o.url),!(u<r&&n(p)))throw p;cs(u+1,p,o),await(0,ds.setTimeout)(Je(u+1,p))}}}}}function jt(t){return dn[t]===null&&(dn[t]=Pd(t)),dn[t]}function Ud(t){if(t!==void 0)return typeof t=="string"||Buffer.isBuffer(t)?t:JSON.stringify(t)}function Dd(t,e,r){let n=new URL(`${t.replace(/\/?\/$/,"")}/${e.replace(/^\/+/,"")}`),o=r instanceof URLSearchParams?r.toString():r?Nd(r):"";return o?`${n.origin}${n.pathname}${n.search}${n.search?"&":"?"}${o}`:n.href}function Nd(t){let e=[];for(let[r,n]of Object.entries(t))if(n!=null)if(Array.isArray(n))for(let o of n)o!=null&&e.push([`${r.trim()}[]`,String(o)]);else e.push([r.trim(),String(n)]);return e.map(([r,n])=>`${ps(r)}=${ps(n)}`).join("&")}function ps(t){return encodeURIComponent(t).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+")}function vd(t,e,r,n){let o={method:e.method.toLowerCase(),baseURL:t,url:e.url,headers:r,data:Buffer.isBuffer(e.data)?"buffer":e.data,params:e.params,isRetry:n};mn(n?"network request retry: %o":"network request: %o",us(o))}function us(t){return{method:t.method,baseURL:t.baseURL,url:t.url,data:t.isRetry?"<retry>":Ld(t.data),params:t.isRetry?"<retry>":t.params,headers:{...t.headers,authorization:"Bearer ***","x-currents-key":"***"}}}function Ld(t){if(t?.results?.raw)return E({...t,results:{...t.results,raw:"***"}});if(typeof t=="string")try{return E(JSON.parse(t))}catch{return t}return ln.default.isPlainObject(t)?E(t):t}var Ht=g(require("lodash"));function gs(t){if(!L(t)){I("Unexpected error while sending network request: %s",t);return}switch(t.code){case"ECONNABORTED":case"ECONNREFUSED":I("Network connection aborted");return;case"ECONNRESET":I("Network connection reset");return;case"ETIMEDOUT":I("Network connection timeout");return}if(t.response){Bd(t,t.response.status,t.response.data);return}I(`[currents] Unexpected network error: %s
12
+ %O`,t.message,{method:void 0,url:void 0,status:void 0,payload:void 0})}function Bd(t,e,r){let{method:n,url:o}=t.config;switch(e){case 401:I(`[currents] ${n} ${o} - 401 Unauthorized Request from cloud service`);return;case 400:I(`[currents] ${n} ${o} - 400 Bad Request from cloud service:
13
+ %o`,r);return;case 404:I(`[currents] ${n} ${o} - 404 Not Found from cloud service`);return;case 429:I(`[currents] ${n} ${o} - 429 Too Many Requests from cloud service`);return;case 422:Fd(t,r);return;default:hs(t)}}function hs(t){I(`[currents] Unexpected network response: %s
14
+ %O`,t.message,{method:t.config.method,url:t.config.url,status:t.response?.status})}var ms=t=>Array.isArray(t)&&t.every(Ht.default.isString);function Fd(t,e){let{code:r,message:n,errors:o}=e??{};if(r===ls.MISSING_SUITE&&Ht.default.isString(n)&&ms(o)){ve(1),T(...fs(n,o));return}if(r===ls.RUN_EXPIRED&&Ht.default.isString(n)){I(n);return}if(Ht.default.isString(n)&&ms(o)){ve(1),I(...fs(n,o)),ve(1);return}hs(t)}var ls={RUN_CANCELLED:"RUN_CANCELLED",RUN_EXPIRED:"RUN_EXPIRED",MISSING_SUITE:"MISSING_SUITE"};function fs(t,e){return Ht.default.isString(t)?e?.length===0?[t]:[t,`
16
15
  ${(e??[]).map(r=>` - ${r}`).join(`
17
16
  `)}
18
- `]:["Unexpected network error"]}var Tn=p.extend("http");async function Q(t,e,r=Pt){try{let o=await r(t).request(e);return Tn("network response: %o",{...yn.default.omit(o,"request","config"),url:o.config.url,method:o.config.method}),o}catch(o){let n=o;throw Tn("network error: %o",{code:n.code,message:n.message,url:n.config?.url,method:n.config?.method,status:n.response?.status,headers:n.response?.headers,data:n.response?.data}),Cn(n),n}}var bt=p.extend("api");async function Rn(t){try{return bt("Request params: %o",h(t)),Q("api",{url:"cache/upload",method:"POST",data:t}).then(e=>e.data)}catch(e){throw bt("Failed to create cache:",e),e}}async function wn(t){try{return bt("Request params: %o",h(t)),Q("api",{url:"cache/v2/download",method:"POST",data:t}).then(e=>e.data)}catch(e){throw bt("Failed to retrieve cache:",e),e}}async function _n(t){try{return bt("Request params: %o",h(t)),Q("api",{url:"cache/meta",method:"POST",data:t}).then(e=>e.data)}catch(e){throw bt("Failed to retrieve reference cache meta:",e),e}}var $p=p.extend("api");async function On(t){return $p("Cancel params: %o",h(t)),(await Q("api",{url:"v1/runs/cancel",method:"POST",data:t})).data}var Sn=require("util"),An=require("zlib");var xn=p.extend("api"),Gp=(0,Sn.promisify)(An.gzip);async function Dn(t){try{xn("Run params: %o",h(t));let e=await Kp(JSON.stringify(t));return Q("api",{url:"v1/runs",method:"POST",headers:{"Content-Type":"application/json","Content-Encoding":"gzip"},data:e}).then(r=>r.data)}catch(e){throw xn("Failed to create the run:",e),e}}async function Kp(t){try{return await Gp(t)}catch(e){throw C("Failed to compress run payload:",e),e}}var Un=p.extend("api");async function Pn(t,e){try{return Un("Run params: %o",e),Q("restApi",{url:"v1/runs/find",params:e,method:"GET",headers:{"Content-Type":"application/json",...Ut({apiKey:t})}}).then(r=>r.data)}catch(r){throw Un("Failed to obtain run data:",r),r}}var bn=require("axios");var Nn=p.extend("api");function Hp(t){if(!(0,bn.isAxiosError)(t)||!t.response)return t;let e=t.response.data,r=[`${t.response.status}`];e?.code&&r.push(e.code);let o=e?.error??t.message,n=Re(t),s=n?` Retry in ${Math.ceil(n/1e3)} seconds.`:"",i=Jp(e?.candidates);return new Error(`${r.join(" ")}: ${o}${s}${i}`)}function Jp(t){return!Array.isArray(t)||t.length===0?"":`
17
+ `]:["Unexpected network error"]}var Es=d.extend("http");async function Y(t,e,r=jt){try{let n=await r(t).request(e);return Es("network response: %o",{...n,url:e.url,method:e.method.toLowerCase()}),n}catch(n){let o=n;throw Es("network error: %o",{code:o.code,message:o.message,url:o.config?.url,method:o.config?.method,status:o.response?.status,headers:o.response?.headers,data:o.response?.data}),gs(o),o}}var Gt=d.extend("api");async function Is(t){try{return Gt("Request params: %o",E(t)),Y("api",{url:"cache/upload",method:"POST",data:t}).then(e=>e.data)}catch(e){throw Gt("Failed to create cache:",e),e}}async function Ts(t){try{return Gt("Request params: %o",E(t)),Y("api",{url:"cache/v2/download",method:"POST",data:t}).then(e=>e.data)}catch(e){throw Gt("Failed to retrieve cache:",e),e}}async function Cs(t){try{return Gt("Request params: %o",E(t)),Y("api",{url:"cache/meta",method:"POST",data:t}).then(e=>e.data)}catch(e){throw Gt("Failed to retrieve reference cache meta:",e),e}}var kd=d.extend("api");async function ys(t){return kd("Cancel params: %o",E(t)),(await Y("api",{url:"v1/runs/cancel",method:"POST",data:t})).data}var ws=require("util"),_s=require("zlib");var Rs=d.extend("api"),Md=(0,ws.promisify)(_s.gzip);async function Os(t){try{Rs("Run params: %o",E(t));let e=await $d(JSON.stringify(t));return Y("api",{url:"v1/runs",method:"POST",headers:{"Content-Type":"application/json","Content-Encoding":"gzip"},data:e}).then(r=>r.data)}catch(e){throw Rs("Failed to create the run:",e),e}}async function $d(t){try{return await Md(t)}catch(e){throw T("Failed to compress run payload:",e),e}}var xs=d.extend("api");async function Ss(t,e){try{return xs("Run params: %o",e),Y("restApi",{url:"v1/runs/find",params:e,method:"GET",headers:{"Content-Type":"application/json",...kt({apiKey:t})}}).then(r=>r.data)}catch(r){throw xs("Failed to obtain run data:",r),r}}function As(t,e){return jt("restApi").request({...e,headers:{...kt({apiKey:t}),...e.headers},responseType:"text"})}var jd=d.extend("api");async function bs(t,e){try{return await Y("api",{url:`rules/project/${encodeURIComponent(t)}`,method:"GET",headers:{"x-currents-key":e}}).then(r=>r.data.rules)}catch(r){throw jd("Failed to get the project actions:",r),r}}var Ps=d.extend("api");function Hd(t){if(!L(t)||!t.response)return t;let e=t.response.data,r=[`${t.response.status}`];e?.code&&r.push(e.code);let n=e?.error??t.message,o=qe(t),s=o?` Retry in ${Math.ceil(o/1e3)} seconds.`:"",i=Gd(e?.candidates);return new Error(`${r.join(" ")}: ${n}${s}${i}`)}function Gd(t){return!Array.isArray(t)||t.length===0?"":`
19
18
  Matches:
20
- ${t.map(({spec:r,title:o,instanceId:n,testId:s,runId:i,ciBuildId:c})=>i?` - run ${i} (CI build ID ${c})`:` - ${[r,o].filter(Boolean).join(" > ")} (instance ${n}${s?`, test ${s}`:""})`).join(`
21
- `)}`}async function zt(t,e,r){try{return(await Pt("restApi").post(t,r,{headers:Ut(e)})).data.data}catch(o){throw Hp(o)}}function Ln(t,e){return Nn("Create session params: %o",e),zt("v1/sessions",t,e)}function vn(t,e,r,o){return Nn("Create attachments: %o",{owner:e,target:r,attachments:o}),"sessionId"in e?zt(`v1/sessions/${encodeURIComponent(e.sessionId)}/attachments`,t,{attachments:o}):"runId"in e?zt(`v1/runs/${encodeURIComponent(e.runId)}/attachments`,t,{...r,attachments:o}):zt("v1/runs/attachments",t,{...e,...r,attachments:o})}function Bn(t,e){return zt("v1/share",t,e)}function Fn(t,e){return Pt("restApi").request({...e,headers:{...Ut({apiKey:t}),...e.headers},responseType:"text",transformResponse:r=>r})}async function Br(){try{let t=Ie();if(!t)throw new Error("Config is missing!");let e=t.ciBuildId?{projectId:t.projectId,ciBuildId:t.ciBuildId,pwLastRun:t.pwLastRun}:{projectId:t.projectId,branch:t.branch,tag:t.tag,pwLastRun:t.pwLastRun},r=await Pn(t.apiKey,e);if(t.pwLastRun&&!r.data.pwLastRun)throw new Error("The API answered without the status and failed tests of the run (pwLastRun). Nothing was written.");await Vp(t.pwLastRun?r.data.pwLastRun:r.data,t)}catch(t){throw p("Failed to get run data"),t}}async function Vp(t,e){let r=JSON.stringify(t,null,2);e.output?(await Xo(e.output),await(0,Mn.writeFile)(e.output,r,"utf-8"),T(`Successfully written to ${e.output}`)):process.stdout.write(r+`
22
- `)}var vs=require("axios"),Wr=l(require("path"));var F=require("@commander-js/extra-typings");var kn=require("@commander-js/extra-typings");function we(t,e=[]){return t?e.concat(t.split(",").map(r=>r.trim())):e}function jn(t){for(let e of t.options){let r=e.attributeName();if(!e.envVar||!e.isBoolean()||t.getOptionValueSource(r)!=="env")continue;let o=rn(process.env[e.envVar]);t.setOptionValueWithSource(r,o??e.defaultValue,o===void 0?"default":"env")}}function Yp(t,e){if(!Array.isArray(t))return String(t)===e;let r=o=>o.map(n=>n.trim()).filter(Boolean).join(",");return r(t.map(String))===r(e.split(","))}function $n(t){for(let e of t.options){let r=e.attributeName(),o=e.envVar?process.env[e.envVar]:void 0,n=t.getOptionValue(r);!o||e.isBoolean()||t.getOptionValueSource(r)!=="cli"||Yp(n,o)||pe(`${e.long} and ${e.envVar} are set to different values; using ${e.long}`)}}function Nt(){console.log=(...t)=>console.error(...t)}async function R(t,e){try{e.debug&&Ko(),await t(e),process.exit(0)}catch(r){C(r.message);let o=r instanceof kn.CommanderError?r.exitCode:1;process.exit(o)}}function Qt(t){return new Promise((e,r)=>process.stdout.write(t,o=>o?r(o):e()))}var Gn="Without it the ID comes from the CI job: on GitHub Actions the repository, the run ID and --matrix-index; on GitLab the pipeline ID and the job name; on other CI the variables that identify the pipeline and the job, and --matrix-index. When no CI job is detected the ID is random, so pass --id",Kn=new F.Option("--id <id>",`the ID to save the files under. ${Gn}`),Hn=new F.Option("--id <id>",`the ID the files were saved under. ${Gn}`),Jn=new F.Option("--path <path>",'comma-separated paths or glob patterns of the files to save, inside the current folder; quote globs, e.g. "dist/**/*". At most 50 MB zipped').argParser(we),Xt=(e=>(e.lastRun="last-run",e))(Xt||{}),Vn=new F.Option("--preset <preset-name>",'"last-run" saves the Playwright .last-run.json files of --pw-output-dir, to rerun only the failed tests').choices(Object.values(Xt)),Yn=new F.Option("--preset <preset-name>",'"last-run" restores the saved .last-run.json files and writes the Playwright options for the rerun to --preset-output').choices(Object.values(Xt)),Wn=new F.Option("--output-dir <folder>","the folder to restore the files to; by default the current folder"),qn=new F.Option("--pw-output-dir <folder>","the Playwright output folder that holds .last-run.json").default("test-results"),Zt=".currents_env",zn=new F.Option("--preset-output <path>",'the file the "last-run" preset writes, relative to the current folder. On GitHub Actions and CircleCI it holds options for "playwright test"; on GitLab the shell variables EXTRA_PW_FLAGS, EXTRA_PWCP_FLAGS and RUN_ATTEMPT, to source. Nothing is written on other CI').default(Zt),Fr=new F.Option("--matrix-index <number>","the index of this job among parallel jobs, from 1; each job has its own cache. Pass it when the CI does not tell the jobs apart, as in a GitHub Actions matrix").default(1).argParser(Qn),Mr=new F.Option("--matrix-total <number>","GitHub Actions only: the number of jobs in the matrix, for the shards that the last-run preset writes").default(1).argParser(Qn);function Qn(t){let e=parseInt(t,10);if(isNaN(e)||e<=0||!Number.isInteger(e))throw new F.InvalidArgumentError("A positive integer is expected.");return e}var Xn=new F.Option("--continue","exit with 0 when the cache is not found").default(!1),Zn=new F.Option("--continue","exit with 0 when no files are found, and save the cache without files").default(!1);var Wp={recordKey:_.recordKey,debug:_.debug},qp={id:{name:"Cache id",cli:"--id"},preset:{name:"Preset",cli:"--preset"},pwOutputDir:{name:"Playwright output folder",cli:"--pw-output-dir"},presetOutput:{name:"Preset output path",cli:"--preset-output"},path:{name:"Paths to cache",cli:"--path"},matrixIndex:{name:"Matrix index",cli:"--matrix-index"},matrixTotal:{name:"Matrix total",cli:"--matrix-total"},continue:{name:"Continue when upload path missing",cli:"--continue"}},zp={id:{name:"Cache id",cli:"--id"},preset:{name:"Preset",cli:"--preset"},outputDir:{name:"Output folder",cli:"--output-dir"},matrixIndex:{name:"Matrix index",cli:"--matrix-index"},matrixTotal:{name:"Matrix total",cli:"--matrix-total"},continue:{name:"Continue on cache miss",cli:"--continue"}},kr={...Wp,...qp,...zp};var ts=p.extend("config"),es=["recordKey"],Tt;function rs(t){Tt={type:"SET_COMMAND_CONFIG",values:U(kr,es,t)},ts("Resolved config: %o",{...Tt,values:h(Tt.values)})}function os(t){Tt={type:"GET_COMMAND_CONFIG",values:U(kr,es,t)},ts("Resolved config: %o",{...Tt,values:h(Tt.values)})}function dt(){return Tt}function ns(t){return{recordKey:t.key,id:t.id,preset:t.preset,outputDir:t.outputDir,presetOutput:t.presetOutput,debug:t.debug,matrixIndex:t.matrixIndex,matrixTotal:t.matrixTotal,continue:t.continue}}function ss(t){return{recordKey:t.key,id:t.id,preset:t.preset,pwOutputDir:t.pwOutputDir,path:t.path,debug:t.debug,matrixIndex:t.matrixIndex,matrixTotal:t.matrixTotal,continue:t.continue}}var w=require("lodash");var _e=p.extend("ci"),Qp=(t,e)=>(0,w.set)(t,(0,w.camelCase)(e),process.env[e]),P=t=>(0,w.transform)(t,Qp,{}),Xp=()=>process.env.TF_BUILD&&process.env.AZURE_HTTP_USER_AGENT,Zp=()=>(0,w.some)(process.env,(t,e)=>/^CODEBUILD_/.test(e)),td=()=>process.env.bamboo_buildNumber,ed=()=>(0,w.some)(process.env,(t,e)=>/^CONCOURSE_/.test(e)),rd=()=>process.env.GITLAB_CI||process.env.CI_SERVER_NAME&&/^GitLab/.test(process.env.CI_SERVER_NAME),od=()=>!!(process.env.BUILD_ID&&process.env.PROJECT_ID&&process.env.PROJECT_NUMBER||process.env.GCP_PROJECT||process.env.GCLOUD_PROJECT||process.env.GOOGLE_CLOUD_PROJECT),nd=()=>process.env.JENKINS_URL||process.env.JENKINS_HOME||process.env.JENKINS_VERSION||process.env.HUDSON_URL||process.env.HUDSON_HOME,sd={appveyor:"APPVEYOR",azure:Xp,awsCodeBuild:Zp,bamboo:td,bitbucket:"BITBUCKET_BUILD_NUMBER",buildkite:"BUILDKITE",circle:"CIRCLECI",concourse:ed,codeFresh:"CF_BUILD_ID",drone:"DRONE",githubActions:"GITHUB_ACTIONS",gitlab:rd,goCD:"GO_JOB_NAME",jenkins:nd,googleCloud:od,semaphore:"SEMAPHORE",teamcity:"TEAMCITY_VERSION",travis:"TRAVIS",netlify:"NETLIFY"};function id(){let{env:t}=process;return(0,w.findKey)(sd,e=>{if((0,w.isString)(e))return t[e];if((0,w.isFunction)(e))return e()})}var is=()=>({appveyor:P(["APPVEYOR_JOB_ID","APPVEYOR_ACCOUNT_NAME","APPVEYOR_PROJECT_SLUG","APPVEYOR_BUILD_NUMBER","APPVEYOR_BUILD_VERSION","APPVEYOR_PULL_REQUEST_NUMBER","APPVEYOR_PULL_REQUEST_HEAD_REPO_BRANCH"]),azure:P(["AGENT_BUILDDIRECTORY","AGENT_ID","AGENT_JOBNAME","AGENT_JOBSTATUS","AGENT_MACHINENAME","AGENT_NAME","AGENT_OS","AGENT_OSARCHITECTURE","BUILD_BUILDID","BUILD_BUILDNUMBER","BUILD_BUILDURI","BUILD_CONTAINERID","BUILD_CRONSCHEDULE_DISPLAYNAME","BUILD_DEFINITIONNAME","BUILD_DEFINITIONVERSION","BUILD_QUEUEDBY","BUILD_QUEUEDBYID","BUILD_REASON","BUILD_REPOSITORY_ID","BUILD_REPOSITORY_NAME","BUILD_REPOSITORY_PROVIDER","BUILD_REPOSITORY_URI","BUILD_REQUESTEDFOR","BUILD_REQUESTEDFOREMAIL","BUILD_REQUESTEDFORID","BUILD_SOURCEBRANCH","BUILD_SOURCEBRANCHNAME","BUILD_SOURCESDIRECTORY","BUILD_SOURCEVERSION","BUILD_SOURCEVERSIONAUTHOR","BUILD_SOURCEVERSIONMESSAGE","BUILD_STAGINGDIRECTORY","BUILD_TRIGGEREDBY_BUILDID","BUILD_TRIGGEREDBY_BUILDNUMBER","BUILD_TRIGGEREDBY_DEFINITIONID","BUILD_TRIGGEREDBY_DEFINITIONNAME","BUILD_TRIGGEREDBY_PROJECTID","COMMON_TESTRESULTSDIRECTORY","PIPELINE_WORKSPACE","SYSTEM_COLLECTIONID","SYSTEM_COLLECTIONURI","SYSTEM_DEFAULTWORKINGDIRECTORY","SYSTEM_DEFINITIONID","SYSTEM_HOSTTYPE","SYSTEM_JOBATTEMPT","SYSTEM_JOBDISPLAYNAME","SYSTEM_JOBID","SYSTEM_JOBNAME","SYSTEM_PHASEATTEMPT","SYSTEM_PHASEDISPLAYNAME","SYSTEM_PHASENAME","SYSTEM_PLANID","SYSTEM_PULLREQUEST_ISFORK","SYSTEM_PULLREQUEST_PULLREQUESTID","SYSTEM_PULLREQUEST_PULLREQUESTNUMBER","SYSTEM_PULLREQUEST_SOURCEREPOSITORYURI","SYSTEM_PULLREQUEST_SOURCEBRANCH","SYSTEM_PULLREQUEST_SOURCECOMMITID","SYSTEM_PULLREQUEST_TARGETBRANCH","SYSTEM_PULLREQUEST_TARGETBRANCHNAME","SYSTEM_STAGEATTEMPT","SYSTEM_STAGEDISPLAYNAME","SYSTEM_STAGENAME","SYSTEM_TEAMFOUNDATIONCOLLECTIONURI","SYSTEM_TEAMPROJECT","SYSTEM_TEAMPROJECTID","SYSTEM_TIMELINEID"]),awsCodeBuild:P(["AWS_DEFAULT_REGION","AWS_REGION","CODEBUILD_BATCH_BUILD_IDENTIFIER","CODEBUILD_BUILD_ARN","CODEBUILD_BUILD_ID","CODEBUILD_BUILD_IMAGE","CODEBUILD_BUILD_NUMBER","CODEBUILD_BUILD_SUCCEEDING","CODEBUILD_BUILD_URL","CODEBUILD_INITIATOR","CODEBUILD_PROJECT_ARN","CODEBUILD_PUBLIC_BUILD_URL","CODEBUILD_RESOLVED_SOURCE_VERSION","CODEBUILD_SOURCE_REPO_URL","CODEBUILD_SOURCE_VERSION","CODEBUILD_SRC_DIR","CODEBUILD_START_TIME","CODEBUILD_WEBHOOK_ACTOR_ACCOUNT_ID","CODEBUILD_WEBHOOK_BASE_REF","CODEBUILD_WEBHOOK_EVENT","CODEBUILD_WEBHOOK_HEAD_REF","CODEBUILD_WEBHOOK_MERGE_COMMIT","CODEBUILD_WEBHOOK_PREV_COMMIT","CODEBUILD_WEBHOOK_TRIGGER","CODEBUILD_WEBHOOK_LABEL","CODEBUILD_WEBHOOK_RUN_ID","CODEBUILD_WEBHOOK_JOB_ID","CODEBUILD_WEBHOOK_WORKFLOW_NAME","CODEBUILD_RUNNER_OWNER","CODEBUILD_RUNNER_REPO","CODEBUILD_RUNNER_REPO_DOMAIN","CODEBUILD_RUNNER_WITH_BUILDSPEC"]),bamboo:P(["bamboo_buildNumber","bamboo_buildResultsUrl","bamboo_planRepository_repositoryUrl","bamboo_buildKey"]),bitbucket:P(["CI","BITBUCKET_WORKSPACE","BITBUCKET_REPO_SLUG","BITBUCKET_REPO_UUID","BITBUCKET_REPO_FULL_NAME","BITBUCKET_REPO_IS_PRIVATE","BITBUCKET_REPO_OWNER","BITBUCKET_REPO_OWNER_UUID","BITBUCKET_PROJECT_KEY","BITBUCKET_PROJECT_UUID","BITBUCKET_BUILD_NUMBER","BITBUCKET_PIPELINE_UUID","BITBUCKET_STEP_UUID","BITBUCKET_STEP_RUN_NUMBER","BITBUCKET_STEP_TRIGGERER_UUID","BITBUCKET_PARALLEL_STEP","BITBUCKET_PARALLEL_STEP_COUNT","BITBUCKET_CLONE_DIR","BITBUCKET_COMMIT","BITBUCKET_BRANCH","BITBUCKET_TAG","BITBUCKET_BOOKMARK","BITBUCKET_GIT_HTTP_ORIGIN","BITBUCKET_GIT_SSH_ORIGIN","BITBUCKET_PR_ID","BITBUCKET_PR_DESTINATION_BRANCH","BITBUCKET_PR_DESTINATION_COMMIT","BITBUCKET_DEPLOYMENT_ENVIRONMENT","BITBUCKET_DEPLOYMENT_ENVIRONMENT_UUID","BITBUCKET_EXIT_CODE"]),buildkite:P(["BUILDKITE_ORGANIZATION_SLUG","BUILDKITE_PIPELINE_ID","BUILDKITE_PIPELINE_NAME","BUILDKITE_PIPELINE_SLUG","BUILDKITE_PIPELINE_DEFAULT_BRANCH","BUILDKITE_REPO","BUILDKITE_SOURCE","BUILDKITE_BRANCH","BUILDKITE_TAG","BUILDKITE_COMMIT","BUILDKITE_MESSAGE","BUILDKITE_BUILD_AUTHOR","BUILDKITE_BUILD_AUTHOR_EMAIL","BUILDKITE_JOB_ID","BUILDKITE_BUILD_ID","BUILDKITE_BUILD_URL","BUILDKITE_BUILD_NUMBER","BUILDKITE_LABEL","BUILDKITE_COMMAND","BUILDKITE_STEP_ID","BUILDKITE_STEP_KEY","BUILDKITE_PARALLEL_JOB","BUILDKITE_PARALLEL_JOB_COUNT","BUILDKITE_RETRY_COUNT","BUILDKITE_COMPUTE_TYPE","BUILDKITE_CLUSTER_NAME","BUILDKITE_PULL_REQUEST","BUILDKITE_PULL_REQUEST_REPO","BUILDKITE_PULL_REQUEST_BASE_BRANCH","BUILDKITE_PULL_REQUEST_DRAFT","BUILDKITE_PULL_REQUEST_LABELS","BUILDKITE_MERGE_QUEUE_BASE_BRANCH","BUILDKITE_MERGE_QUEUE_BASE_COMMIT","BUILDKITE_REBUILT_FROM_BUILD_ID","BUILDKITE_REBUILT_FROM_BUILD_NUMBER","BUILDKITE_TRIGGERED_FROM_BUILD_ID","BUILDKITE_TRIGGERED_FROM_BUILD_NUMBER","BUILDKITE_TRIGGERED_FROM_BUILD_PIPELINE_SLUG"]),circle:P(["CI","CIRCLECI","CIRCLE_BRANCH","CIRCLE_BUILD_NUM","CIRCLE_BUILD_URL","CIRCLE_PREVIOUS_BUILD_NUM","CIRCLE_JOB","CIRCLE_WORKFLOW_ID","CIRCLE_WORKFLOW_JOB_ID","CIRCLE_WORKFLOW_WORKSPACE_ID","CIRCLE_PIPELINE_ID","CIRCLE_ORGANIZATION_ID","CIRCLE_PROJECT_ID","CIRCLE_PROJECT_REPONAME","CIRCLE_PROJECT_USERNAME","CIRCLE_REPOSITORY_URL","CIRCLE_WORKING_DIRECTORY","CIRCLE_SHA1","CIRCLE_TAG","CIRCLE_USERNAME","CIRCLE_NODE_INDEX","CIRCLE_NODE_TOTAL","CIRCLE_PR_NUMBER","CIRCLE_PR_REPONAME","CIRCLE_PR_USERNAME","CIRCLE_PULL_REQUEST","CIRCLE_PULL_REQUESTS","CI_PULL_REQUEST"]),concourse:P(["BUILD_ID","BUILD_NAME","BUILD_JOB_NAME","BUILD_PIPELINE_NAME","BUILD_TEAM_NAME","ATC_EXTERNAL_URL"]),codeFresh:P(["CF_BUILD_ID","CF_BUILD_URL","CF_CURRENT_ATTEMPT","CF_STEP_NAME","CF_PIPELINE_NAME","CF_PIPELINE_TRIGGER_ID","CF_PULL_REQUEST_ID","CF_PULL_REQUEST_IS_FORK","CF_PULL_REQUEST_NUMBER","CF_PULL_REQUEST_TARGET"]),drone:P(["DRONE_BUILD_LINK","DRONE_BUILD_NUMBER","DRONE_PULL_REQUEST"]),githubActions:P(["CI","GITHUB_ACTIONS","GITHUB_WORKFLOW","GITHUB_WORKFLOW_REF","GITHUB_WORKFLOW_SHA","GITHUB_ACTION","GITHUB_ACTION_PATH","GITHUB_ACTION_REPOSITORY","GITHUB_JOB","GITHUB_EVENT_NAME","GITHUB_EVENT_PATH","GITHUB_RUN_ID","GITHUB_RUN_NUMBER","GITHUB_RUN_ATTEMPT","GITHUB_REPOSITORY","GITHUB_REPOSITORY_ID","GITHUB_REPOSITORY_OWNER","GITHUB_REPOSITORY_OWNER_ID","GITHUB_REF","GITHUB_REF_NAME","GITHUB_REF_TYPE","GITHUB_REF_PROTECTED","GITHUB_BASE_REF","GITHUB_HEAD_REF","GITHUB_SHA","GITHUB_ACTOR","GITHUB_ACTOR_ID","GITHUB_TRIGGERING_ACTOR","GITHUB_SERVER_URL","GITHUB_API_URL","GITHUB_GRAPHQL_URL","GITHUB_WORKSPACE","GITHUB_RETENTION_DAYS","RUNNER_OS","RUNNER_ARCH","RUNNER_NAME","RUNNER_ENVIRONMENT","RUNNER_DEBUG"]),gitlab:P(["CI_PIPELINE_ID","CI_PIPELINE_URL","CI_BUILD_ID","CI_JOB_ID","CI_JOB_URL","CI_JOB_NAME","CI_NODE_INDEX","CI_NODE_TOTAL","GITLAB_HOST","CI_PROJECT_ID","CI_PROJECT_URL","CI_REPOSITORY_URL","CI_ENVIRONMENT_URL","CI_DEFAULT_BRANCH","RUN_ATTEMPT","CI_MERGE_REQUEST_IID","CI_MERGE_REQUEST_PROJECT_URL","CI_MERGE_REQUEST_TITLE","CI_MERGE_REQUEST_SOURCE_BRANCH_NAME","CI_MERGE_REQUEST_TARGET_BRANCH_NAME","CI_OPEN_MERGE_REQUESTS"]),goCD:P(["GO_SERVER_URL","GO_ENVIRONMENT_NAME","GO_PIPELINE_NAME","GO_PIPELINE_COUNTER","GO_PIPELINE_LABEL","GO_STAGE_NAME","GO_STAGE_COUNTER","GO_JOB_NAME","GO_TRIGGER_USER","GO_REVISION","GO_TO_REVISION","GO_FROM_REVISION","GO_MATERIAL_HAS_CHANGED"]),googleCloud:P(["BUILD_ID","PROJECT_ID","REPO_NAME","BRANCH_NAME","TAG_NAME","COMMIT_SHA","SHORT_SHA"]),jenkins:P(["BRANCH_NAME","BUILD_DISPLAY_NAME","BUILD_ID","BUILD_NUMBER","BUILD_TAG","BUILD_URL","CHANGE_AUTHOR","CHANGE_AUTHOR_DISPLAY_NAME","CHANGE_AUTHOR_EMAIL","CHANGE_BRANCH","CHANGE_FORK","CHANGE_ID","CHANGE_TARGET","CHANGE_TITLE","CHANGE_URL","CI","EXECUTOR_NUMBER","JAVA_HOME","JENKINS_HOME","JENKINS_URL","JOB_BASE_NAME","JOB_NAME","JOB_URL","NODE_LABELS","NODE_NAME","RUN_ARTIFACTS_DISPLAY_URL","RUN_CHANGES_DISPLAY_URL","TAG_NAME","WORKSPACE","WORKSPACE_TMP","GIT_AUTHOR_EMAIL","GIT_AUTHOR_NAME","GIT_BRANCH","GIT_COMMIT","GIT_COMMITTER_EMAIL","GIT_COMMITTER_NAME","GIT_LOCAL_BRANCH","GIT_PREVIOUS_COMMIT","GIT_PREVIOUS_SUCCESSFUL_COMMIT","GIT_URL","ghprbActualCommit","ghprbGhRepository","ghprbPullId","ghprbPullLink","ghprbSourceBranch","ghprbTargetBranch","ghprbTriggerAuthorLogin"]),semaphore:P(["SEMAPHORE_BRANCH_ID","SEMAPHORE_BUILD_NUMBER","SEMAPHORE_CURRENT_JOB","SEMAPHORE_CURRENT_THREAD","SEMAPHORE_EXECUTABLE_UUID","SEMAPHORE_GIT_BRANCH","SEMAPHORE_GIT_DIR","SEMAPHORE_GIT_REF","SEMAPHORE_GIT_REF_TYPE","SEMAPHORE_GIT_REPO_SLUG","SEMAPHORE_GIT_SHA","SEMAPHORE_GIT_URL","SEMAPHORE_JOB_COUNT","SEMAPHORE_JOB_ID","SEMAPHORE_JOB_NAME","SEMAPHORE_JOB_UUID","SEMAPHORE_PIPELINE_ID","SEMAPHORE_PLATFORM","SEMAPHORE_PROJECT_DIR","SEMAPHORE_PROJECT_HASH_ID","SEMAPHORE_PROJECT_ID","SEMAPHORE_PROJECT_NAME","SEMAPHORE_PROJECT_UUID","SEMAPHORE_REPO_SLUG","SEMAPHORE_TRIGGER_SOURCE","SEMAPHORE_WORKFLOW_ID","PULL_REQUEST_NUMBER"]),teamcity:null,travis:P(["TRAVIS_JOB_ID","TRAVIS_BUILD_ID","TRAVIS_BUILD_WEB_URL","TRAVIS_REPO_SLUG","TRAVIS_JOB_NUMBER","TRAVIS_EVENT_TYPE","TRAVIS_COMMIT_RANGE","TRAVIS_BUILD_NUMBER","TRAVIS_PULL_REQUEST","TRAVIS_PULL_REQUEST_BRANCH","TRAVIS_PULL_REQUEST_SHA"]),netlify:P(["BUILD_ID","CONTEXT","URL","DEPLOY_URL","DEPLOY_PRIME_URL","DEPLOY_ID"])}),ad=t=>{let e=as();return e?(0,w.chain)(t()).get(e).value():{}};function cd(){return(0,w.chain)(is()).omitBy(w.isNull).keys().value()}function pd(t){return t&&cd().includes(t)}function as(){let t=id();return _e("detected CI provider name: %s",t),t||null}function dd(){let t=ad(is);return(0,w.mapValues)(t,e=>(0,w.isString)(e)?Dr(e):e)}function rt(t){let e=dd(),r=as(),o=md(t,r);return _e("detected CI provider: %s",r),_e("detected CI params: %O",e),_e("detected CI build ID: %o",o),{params:e,provider:r,ciBuildId:o}}function md(t,e){return t?{source:"user",value:t}:pd(e)?{source:"server",value:null}:{source:"random",value:`auto:${Ar()}`}}var cs=l(require("archiver")),ps=l(require("fs-extra")),jr=l(require("path")),ds=l(require("unzipper"));var ud=50*1024*1024;async function ms(t,e=ud){return new Promise((r,o)=>{let n=(0,cs.default)("zip",{zlib:{level:9}}),s=[],i=0;n.on("data",d=>{s.push(d),i+=d.length,i>e&&o(new Error(`Zip size exceeded the limit of ${e} bytes`))}),n.on("warning",d=>{d.code==="ENOENT"?I(d):o(d)}),n.on("error",d=>o(d)),n.on("end",()=>{let d=Buffer.concat(s);r(d)});let c=async d=>{let f=process.cwd(),u=jr.default.normalize(d),E=jr.default.relative(f,u),g=await ps.default.stat(d);g.isDirectory()?n.directory(d,E):n.file(d,{name:E,stats:g})};(async d=>{for(let f of d)await c(f);await n.finalize()})(t).catch(o)})}async function us(t,e){return ds.default.Open.buffer(t).then(r=>r.extract({path:e,concurrency:3}))}var ls=require("lodash");var ld={githubActions:[],gitlab:[],appveyor:["APPVEYOR_ACCOUNT_NAME","APPVEYOR_PROJECT_SLUG","APPVEYOR_BUILD_NUMBER"],azure:["SYSTEM_COLLECTIONID","BUILD_BUILDID"],awsCodeBuild:["CODEBUILD_BUILD_ID"],bamboo:["bamboo_buildKey","bamboo_buildNumber"],bitbucket:["BITBUCKET_PIPELINE_UUID"],buildkite:["BUILDKITE_BUILD_ID"],circle:["CIRCLE_WORKFLOW_WORKSPACE_ID"],concourse:["BUILD_ID"],codeFresh:["CF_BUILD_ID"],drone:["DRONE_BUILD_LINK"],goCD:["GO_PIPELINE_NAME","GO_PIPELINE_COUNTER"],googleCloud:["BUILD_ID"],jenkins:["JOB_NAME","BUILD_NUMBER"],semaphore:["SEMAPHORE_PIPELINE_ID"],travis:["TRAVIS_JOB_ID"],netlify:["BUILD_ID"]};function fd({provider:t,params:e}){let r=t?ld[t]:null;return!r||!e?!1:r.every(o=>!!e[(0,ls.camelCase)(o)])}function Oe(t,e){e||fd(t)||pe("No CI job detected: without --id the cache ID is random, so cache get does not find what cache set saved. Pass --id to save and restore the same cache.")}var Is=l(require("async-retry")),Cs=l(require("fs")),Ts=require("stream"),te=require("axios");var fs=l(require("axios")),gs=require("https-proxy-agent"),hs=l(require("proxy-from-env"));var gd=p.extend("axios");function $r(t={}){let e=fs.default.create(t);return e.interceptors.request.use(r=>{let o={...r},n=e.getUri(r),s=hs.default.getProxyForUrl(n);return s&&(gd("Using HTTP proxy %s for %s",Dt(s),Dt(n)),o.proxy=!1,o.httpsAgent=hd(s)),o}),e}var xe=null;function hd(t){return xe||(xe=new gs.HttpsProxyAgent(t),xe)}var ee=p.extend("upload"),Se=5;async function Gr(t,e,r){return ee("Uploading buffer %s",t.name,{buffer:Buffer.byteLength(t.buffer)}),Os(t.buffer,t.uploadUrl,e,r,t.headers,Rs(Buffer.byteLength(t.buffer)))}var Ed=256*1024,Id=120*1e3;async function ys(t){return ee("Uploading file %s",t.name,{bytes:t.sizeBytes}),Os(()=>t.sizeBytes>0?Cs.default.createReadStream(t.path,{end:t.sizeBytes-1}):Ts.Readable.from([]),t.uploadUrl,t.contentType,void 0,{...t.headers??{"Content-Type":t.contentType},"Content-Length":String(t.sizeBytes)},Rs(t.sizeBytes))}function Rs(t){return Id+Math.ceil(t/Ed)*1e3}async function Cd(t,e,r,o,n,s){return $r().request({method:"put",url:e,timeout:s,data:typeof t=="function"?t():t,...typeof t=="function"&&{maxRedirects:0},onUploadProgress:o,headers:n??{"Content-Disposition":"inline","Content-Type":r}})}async function Kr(t,e){try{let r=await $r().get(t,{responseType:"arraybuffer",onDownloadProgress:e});return Buffer.isBuffer(r.data)?r.data:Buffer.from(r.data)}catch(r){throw(0,te.isAxiosError)(r)&&ee("Failed to download %s: %s",Dt(t),r.message),r}}var Td=["RequestTimeout","OperationAborted","SlowDown"];function ws(t){if(t)return t.replace(/[\u0000-\u001f\u007f-\u009f]/g,"").replace(/\b[a-z][a-z0-9+.-]*:\/\/\S+/gi,e=>Dt(e)).slice(0,200)}function _s(t){let e=(0,te.isAxiosError)(t)?t.response?.data:void 0,r=typeof e=="string"?e:"";return{code:r.match(/<Code>([^<]*)<\/Code>/)?.[1],message:ws(r.match(/<Message>([^<]*)<\/Message>/)?.[1])}}function yd(t){let e=(0,te.isAxiosError)(t)?t.response?.status:void 0;if(e===void 0||e<400||e>=500||e===408||e===429)return!1;let{code:r}=_s(t);return!(r&&Td.includes(r))}function Rd(t){if(!(0,te.isAxiosError)(t)||!t.response)return t instanceof Error?t:new Error(String(t));let{code:e,message:r}=_s(t),o=[ws(e),r].filter(Boolean).join(": ");return new Error(`storage answered ${t.response.status}${o?` ${o}`:""}`)}async function Os(...t){try{await wd(t)}catch(e){throw Rd(e)}}async function wd(t){await(0,Is.default)(async e=>{try{await Cd(...t)}catch(r){if(yd(r)){e(r);return}throw r}},{retries:Se,onRetry:(e,r)=>{if(ee("Upload failed %d out of %d attempts: %s",r,Se,e.message),r===Se){C(`Cannot upload after ${r} times: ${e.message}`);return}I(`Upload failed ${r} out of ${Se} attempts: ${e.message}`)}})}var Hr=t=>({total:e,loaded:r})=>{ee("Uploading %s: %d / %d",t,Es(r),Es(e??0))};function Es(t){return t/1e3/1e3}var Yr=l(require("lodash"));var ot=l(require("path")),Vr=l(require("globby"));var xs=require("lodash");function Jr({config:t,cacheId:e,orgId:r,path:o,ci:n,cacheKey:s,metaCacheKey:i}){let c={id:e,orgId:r,config:(0,xs.omit)(t,"recordKey"),path:o,ci:n,createdAt:new Date().toISOString(),cacheKey:s,metaCacheKey:i};return Buffer.from(JSON.stringify(c))}function Ss(t,e){t instanceof Error?gt("%s. %s.",e,t.message):gt("%s. %s.",e,"Unknown error")}var As=async t=>{let e=ot.default.resolve(t??"./test-results"),r=[ot.default.posix.join(e.replace(/\\/g,"/"),"**/.last-run.json"),ot.default.posix.join(e.replace(/\\/g,"/"),".last-run.json")];return Vr.sync(r)},Ds=async(t=[])=>{let e=_d(t);return e.length===0?[]:Vr.sync(e.map(r=>r.replace(/\\/g,"/")))};function _d(t){let e=process.cwd();return t.filter(r=>{let o=ot.default.relative(e,ot.default.resolve(r));return o===".."||o.startsWith(`..${ot.default.sep}`)||ot.default.isAbsolute(o)?(Ss(null,`Invalid path: "${r}". Path traversal detected. The path was skipped.`),!1):!0})}function Ae(t){return t?t.path.some(e=>ot.default.basename(e)===".last-run.json"):!1}async function Us(t,e){switch(e.provider){case"githubActions":await Ns(t,e);break;case"gitlab":await bs(t,e);break;case"circle":await Ls(t,e);break;default:break}}async function Ps(t,e,r){switch(e.provider){case"githubActions":await Ns(t,e,r);break;case"gitlab":await bs(t,e,r);break;case"circle":await Ls(t,e,r);break;default:break}}async function bs(t,e,r=null){let o=e.params,n=r?.ci.params,i=(n?Lt(n.runAttempt,0):0)+1,c=Lt(o.ciNodeIndex,1),m=Lt(o.ciNodeTotal,1),d=Ae(r),f=i>1&&d,u=f?"--last-failed":"",E="";m>1&&(E=f?"--shard=1/1":`--shard=${c}/${m}`);let g=[u,E].filter(Boolean).join(" ");await It(t.presetOutput??Zt,`EXTRA_PW_FLAGS="${g}"
23
- EXTRA_PWCP_FLAGS="${u}"
19
+ ${t.map(({spec:r,title:n,instanceId:o,testId:s,runId:i,ciBuildId:a})=>i?` - run ${i} (CI build ID ${a})`:` - ${[r,n].filter(Boolean).join(" > ")} (instance ${o}${s?`, test ${s}`:""})`).join(`
20
+ `)}`}async function Us(t,e){try{return(await jt("restApi").request({...e,headers:kt(t)})).data.data}catch(r){throw Hd(r)}}function ce(t,e,r){return Us(e,{method:"POST",url:t,data:r})}function Ds(t,e){return Ps("Create session params: %o",e),ce("v1/sessions",t,e)}function Ns(t,e,r,n){return Ps("Create attachments: %o",{owner:e,target:r,attachments:n}),"sessionId"in e?ce(`v1/sessions/${encodeURIComponent(e.sessionId)}/attachments`,t,{attachments:n}):"runId"in e?ce(`v1/runs/${encodeURIComponent(e.runId)}/attachments`,t,{...r,attachments:n}):ce("v1/runs/attachments",t,{...e,...r,attachments:n})}function fn(t,e){return ce("v1/share",t,e)}function vs(t,e){return Us(t,{method:"GET",url:`v1/instances/${encodeURIComponent(e)}`})}async function gn(){try{let t=Ke();if(!t)throw new Error("Config is missing!");let e=t.ciBuildId?{projectId:t.projectId,ciBuildId:t.ciBuildId,pwLastRun:t.pwLastRun}:{projectId:t.projectId,branch:t.branch,tag:t.tag,pwLastRun:t.pwLastRun},r=await Ss(t.apiKey,e);if(t.pwLastRun&&!r.data.pwLastRun)throw new Error("The API answered without the status and failed tests of the run (pwLastRun). Nothing was written.");await Kd(t.pwLastRun?r.data.pwLastRun:r.data,t)}catch(t){throw d("Failed to get run data"),t}}async function Kd(t,e){let r=JSON.stringify(t,null,2);e.output?(await bo(e.output),await(0,Ls.writeFile)(e.output,r,"utf-8"),C(`Successfully written to ${e.output}`)):process.stdout.write(r+`
21
+ `)}var Sn=g(require("path"));var $=require("@commander-js/extra-typings");var Bs=require("@commander-js/extra-typings");function Ye(t,e=[]){return t?e.concat(t.split(",").map(r=>r.trim())):e}function Fs(t){for(let e of t.options){let r=e.attributeName();if(!e.envVar||!e.isBoolean()||t.getOptionValueSource(r)!=="env")continue;let n=vo(process.env[e.envVar]);t.setOptionValueWithSource(r,n??e.defaultValue,n===void 0?"default":"env")}}function Jd(t,e){if(!Array.isArray(t))return String(t)===e;let r=n=>n.map(o=>o.trim()).filter(Boolean).join(",");return r(t.map(String))===r(e.split(","))}function ks(t){for(let e of t.options){let r=e.attributeName(),n=e.envVar?process.env[e.envVar]:void 0,o=t.getOptionValue(r);!n||e.isBoolean()||t.getOptionValueSource(r)!=="cli"||Jd(o,n)||De(`${e.long} and ${e.envVar} are set to different values; using ${e.long}`)}}function Jt(){console.log=(...t)=>console.error(...t)}async function R(t,e){try{e.debug&&To(),await t(e),process.exit(0)}catch(r){T(r.message);let n=r instanceof Bs.CommanderError?r.exitCode:1;process.exit(n)}}function pe(t){return new Promise((e,r)=>process.stdout.write(t,n=>n?r(n):e()))}var Ms="Without it the ID comes from the CI job: on GitHub Actions the repository, the run ID and --matrix-index; on GitLab the pipeline ID and the job name; on other CI the variables that identify the pipeline and the job, and --matrix-index. When no CI job is detected the ID is random, so pass --id",$s=new $.Option("--id <id>",`the ID to save the files under. ${Ms}`),js=new $.Option("--id <id>",`the ID the files were saved under. ${Ms}`),Hs=new $.Option("--path <path>",'comma-separated paths or glob patterns of the files to save, inside the current folder; quote globs, e.g. "dist/**/*". At most 50 MB zipped').argParser(Ye),ue=(e=>(e.lastRun="last-run",e))(ue||{}),Gs=new $.Option("--preset <preset-name>",'"last-run" saves the Playwright .last-run.json files of --pw-output-dir, to rerun only the failed tests').choices(Object.values(ue)),Ks=new $.Option("--preset <preset-name>",'"last-run" restores the saved .last-run.json files and writes the Playwright options for the rerun to --preset-output').choices(Object.values(ue)),Js=new $.Option("--output-dir <folder>","the folder to restore the files to; by default the current folder"),Vs=new $.Option("--pw-output-dir <folder>","the Playwright output folder that holds .last-run.json").default("test-results"),de=".currents_env",qs=new $.Option("--preset-output <path>",'the file the "last-run" preset writes, relative to the current folder. On GitHub Actions and CircleCI it holds options for "playwright test"; on GitLab the shell variables EXTRA_PW_FLAGS, EXTRA_PWCP_FLAGS and RUN_ATTEMPT, to source. Nothing is written on other CI').default(de),hn=new $.Option("--matrix-index <number>","the index of this job among parallel jobs, from 1; each job has its own cache. Pass it when the CI does not tell the jobs apart, as in a GitHub Actions matrix").default(1).argParser(Ys),En=new $.Option("--matrix-total <number>","GitHub Actions only: the number of jobs in the matrix, for the shards that the last-run preset writes").default(1).argParser(Ys);function Ys(t){let e=parseInt(t,10);if(isNaN(e)||e<=0||!Number.isInteger(e))throw new $.InvalidArgumentError("A positive integer is expected.");return e}var Ws=new $.Option("--continue","exit with 0 when the cache is not found").default(!1),zs=new $.Option("--continue","exit with 0 when no files are found, and save the cache without files").default(!1);var Vd={recordKey:x.recordKey,debug:x.debug},qd={id:{name:"Cache id",cli:"--id"},preset:{name:"Preset",cli:"--preset"},pwOutputDir:{name:"Playwright output folder",cli:"--pw-output-dir"},presetOutput:{name:"Preset output path",cli:"--preset-output"},path:{name:"Paths to cache",cli:"--path"},matrixIndex:{name:"Matrix index",cli:"--matrix-index"},matrixTotal:{name:"Matrix total",cli:"--matrix-total"},continue:{name:"Continue when upload path missing",cli:"--continue"}},Yd={id:{name:"Cache id",cli:"--id"},preset:{name:"Preset",cli:"--preset"},outputDir:{name:"Output folder",cli:"--output-dir"},matrixIndex:{name:"Matrix index",cli:"--matrix-index"},matrixTotal:{name:"Matrix total",cli:"--matrix-total"},continue:{name:"Continue on cache miss",cli:"--continue"}},In={...Vd,...qd,...Yd};var Qs=d.extend("config"),Xs=["recordKey"],Pt;function Zs(t){Pt={type:"SET_COMMAND_CONFIG",values:D(In,Xs,t)},Qs("Resolved config: %o",{...Pt,values:E(Pt.values)})}function ti(t){Pt={type:"GET_COMMAND_CONFIG",values:D(In,Xs,t)},Qs("Resolved config: %o",{...Pt,values:E(Pt.values)})}function ht(){return Pt}function ei(t){return{recordKey:t.key,id:t.id,preset:t.preset,outputDir:t.outputDir,presetOutput:t.presetOutput,debug:t.debug,matrixIndex:t.matrixIndex,matrixTotal:t.matrixTotal,continue:t.continue}}function ri(t){return{recordKey:t.key,id:t.id,preset:t.preset,pwOutputDir:t.pwOutputDir,path:t.path,debug:t.debug,matrixIndex:t.matrixIndex,matrixTotal:t.matrixTotal,continue:t.continue}}var w=require("lodash");var We=d.extend("ci"),Wd=(t,e)=>(0,w.set)(t,(0,w.camelCase)(e),process.env[e]),v=t=>(0,w.transform)(t,Wd,{}),zd=()=>process.env.TF_BUILD&&process.env.AZURE_HTTP_USER_AGENT,Qd=()=>(0,w.some)(process.env,(t,e)=>/^CODEBUILD_/.test(e)),Xd=()=>process.env.bamboo_buildNumber,Zd=()=>(0,w.some)(process.env,(t,e)=>/^CONCOURSE_/.test(e)),tm=()=>process.env.GITLAB_CI||process.env.CI_SERVER_NAME&&/^GitLab/.test(process.env.CI_SERVER_NAME),em=()=>!!(process.env.BUILD_ID&&process.env.PROJECT_ID&&process.env.PROJECT_NUMBER||process.env.GCP_PROJECT||process.env.GCLOUD_PROJECT||process.env.GOOGLE_CLOUD_PROJECT),rm=()=>process.env.JENKINS_URL||process.env.JENKINS_HOME||process.env.JENKINS_VERSION||process.env.HUDSON_URL||process.env.HUDSON_HOME,nm={appveyor:"APPVEYOR",azure:zd,awsCodeBuild:Qd,bamboo:Xd,bitbucket:"BITBUCKET_BUILD_NUMBER",buildkite:"BUILDKITE",circle:"CIRCLECI",concourse:Zd,codeFresh:"CF_BUILD_ID",drone:"DRONE",githubActions:"GITHUB_ACTIONS",gitlab:tm,goCD:"GO_JOB_NAME",jenkins:rm,googleCloud:em,semaphore:"SEMAPHORE",teamcity:"TEAMCITY_VERSION",travis:"TRAVIS",netlify:"NETLIFY"};function om(){let{env:t}=process;return(0,w.findKey)(nm,e=>{if((0,w.isString)(e))return t[e];if((0,w.isFunction)(e))return e()})}var ni=()=>({appveyor:v(["APPVEYOR_JOB_ID","APPVEYOR_ACCOUNT_NAME","APPVEYOR_PROJECT_SLUG","APPVEYOR_BUILD_NUMBER","APPVEYOR_BUILD_VERSION","APPVEYOR_PULL_REQUEST_NUMBER","APPVEYOR_PULL_REQUEST_HEAD_REPO_BRANCH"]),azure:v(["AGENT_BUILDDIRECTORY","AGENT_ID","AGENT_JOBNAME","AGENT_JOBSTATUS","AGENT_MACHINENAME","AGENT_NAME","AGENT_OS","AGENT_OSARCHITECTURE","BUILD_BUILDID","BUILD_BUILDNUMBER","BUILD_BUILDURI","BUILD_CONTAINERID","BUILD_CRONSCHEDULE_DISPLAYNAME","BUILD_DEFINITIONNAME","BUILD_DEFINITIONVERSION","BUILD_QUEUEDBY","BUILD_QUEUEDBYID","BUILD_REASON","BUILD_REPOSITORY_ID","BUILD_REPOSITORY_NAME","BUILD_REPOSITORY_PROVIDER","BUILD_REPOSITORY_URI","BUILD_REQUESTEDFOR","BUILD_REQUESTEDFOREMAIL","BUILD_REQUESTEDFORID","BUILD_SOURCEBRANCH","BUILD_SOURCEBRANCHNAME","BUILD_SOURCESDIRECTORY","BUILD_SOURCEVERSION","BUILD_SOURCEVERSIONAUTHOR","BUILD_SOURCEVERSIONMESSAGE","BUILD_STAGINGDIRECTORY","BUILD_TRIGGEREDBY_BUILDID","BUILD_TRIGGEREDBY_BUILDNUMBER","BUILD_TRIGGEREDBY_DEFINITIONID","BUILD_TRIGGEREDBY_DEFINITIONNAME","BUILD_TRIGGEREDBY_PROJECTID","COMMON_TESTRESULTSDIRECTORY","PIPELINE_WORKSPACE","SYSTEM_COLLECTIONID","SYSTEM_COLLECTIONURI","SYSTEM_DEFAULTWORKINGDIRECTORY","SYSTEM_DEFINITIONID","SYSTEM_HOSTTYPE","SYSTEM_JOBATTEMPT","SYSTEM_JOBDISPLAYNAME","SYSTEM_JOBID","SYSTEM_JOBNAME","SYSTEM_PHASEATTEMPT","SYSTEM_PHASEDISPLAYNAME","SYSTEM_PHASENAME","SYSTEM_PLANID","SYSTEM_PULLREQUEST_ISFORK","SYSTEM_PULLREQUEST_PULLREQUESTID","SYSTEM_PULLREQUEST_PULLREQUESTNUMBER","SYSTEM_PULLREQUEST_SOURCEREPOSITORYURI","SYSTEM_PULLREQUEST_SOURCEBRANCH","SYSTEM_PULLREQUEST_SOURCECOMMITID","SYSTEM_PULLREQUEST_TARGETBRANCH","SYSTEM_PULLREQUEST_TARGETBRANCHNAME","SYSTEM_STAGEATTEMPT","SYSTEM_STAGEDISPLAYNAME","SYSTEM_STAGENAME","SYSTEM_TEAMFOUNDATIONCOLLECTIONURI","SYSTEM_TEAMPROJECT","SYSTEM_TEAMPROJECTID","SYSTEM_TIMELINEID"]),awsCodeBuild:v(["AWS_DEFAULT_REGION","AWS_REGION","CODEBUILD_BATCH_BUILD_IDENTIFIER","CODEBUILD_BUILD_ARN","CODEBUILD_BUILD_ID","CODEBUILD_BUILD_IMAGE","CODEBUILD_BUILD_NUMBER","CODEBUILD_BUILD_SUCCEEDING","CODEBUILD_BUILD_URL","CODEBUILD_INITIATOR","CODEBUILD_PROJECT_ARN","CODEBUILD_PUBLIC_BUILD_URL","CODEBUILD_RESOLVED_SOURCE_VERSION","CODEBUILD_SOURCE_REPO_URL","CODEBUILD_SOURCE_VERSION","CODEBUILD_SRC_DIR","CODEBUILD_START_TIME","CODEBUILD_WEBHOOK_ACTOR_ACCOUNT_ID","CODEBUILD_WEBHOOK_BASE_REF","CODEBUILD_WEBHOOK_EVENT","CODEBUILD_WEBHOOK_HEAD_REF","CODEBUILD_WEBHOOK_MERGE_COMMIT","CODEBUILD_WEBHOOK_PREV_COMMIT","CODEBUILD_WEBHOOK_TRIGGER","CODEBUILD_WEBHOOK_LABEL","CODEBUILD_WEBHOOK_RUN_ID","CODEBUILD_WEBHOOK_JOB_ID","CODEBUILD_WEBHOOK_WORKFLOW_NAME","CODEBUILD_RUNNER_OWNER","CODEBUILD_RUNNER_REPO","CODEBUILD_RUNNER_REPO_DOMAIN","CODEBUILD_RUNNER_WITH_BUILDSPEC"]),bamboo:v(["bamboo_buildNumber","bamboo_buildResultsUrl","bamboo_planRepository_repositoryUrl","bamboo_buildKey"]),bitbucket:v(["CI","BITBUCKET_WORKSPACE","BITBUCKET_REPO_SLUG","BITBUCKET_REPO_UUID","BITBUCKET_REPO_FULL_NAME","BITBUCKET_REPO_IS_PRIVATE","BITBUCKET_REPO_OWNER","BITBUCKET_REPO_OWNER_UUID","BITBUCKET_PROJECT_KEY","BITBUCKET_PROJECT_UUID","BITBUCKET_BUILD_NUMBER","BITBUCKET_PIPELINE_UUID","BITBUCKET_STEP_UUID","BITBUCKET_STEP_RUN_NUMBER","BITBUCKET_STEP_TRIGGERER_UUID","BITBUCKET_PARALLEL_STEP","BITBUCKET_PARALLEL_STEP_COUNT","BITBUCKET_CLONE_DIR","BITBUCKET_COMMIT","BITBUCKET_BRANCH","BITBUCKET_TAG","BITBUCKET_BOOKMARK","BITBUCKET_GIT_HTTP_ORIGIN","BITBUCKET_GIT_SSH_ORIGIN","BITBUCKET_PR_ID","BITBUCKET_PR_DESTINATION_BRANCH","BITBUCKET_PR_DESTINATION_COMMIT","BITBUCKET_DEPLOYMENT_ENVIRONMENT","BITBUCKET_DEPLOYMENT_ENVIRONMENT_UUID","BITBUCKET_EXIT_CODE"]),buildkite:v(["BUILDKITE_ORGANIZATION_SLUG","BUILDKITE_PIPELINE_ID","BUILDKITE_PIPELINE_NAME","BUILDKITE_PIPELINE_SLUG","BUILDKITE_PIPELINE_DEFAULT_BRANCH","BUILDKITE_REPO","BUILDKITE_SOURCE","BUILDKITE_BRANCH","BUILDKITE_TAG","BUILDKITE_COMMIT","BUILDKITE_MESSAGE","BUILDKITE_BUILD_AUTHOR","BUILDKITE_BUILD_AUTHOR_EMAIL","BUILDKITE_JOB_ID","BUILDKITE_BUILD_ID","BUILDKITE_BUILD_URL","BUILDKITE_BUILD_NUMBER","BUILDKITE_LABEL","BUILDKITE_COMMAND","BUILDKITE_STEP_ID","BUILDKITE_STEP_KEY","BUILDKITE_PARALLEL_JOB","BUILDKITE_PARALLEL_JOB_COUNT","BUILDKITE_RETRY_COUNT","BUILDKITE_COMPUTE_TYPE","BUILDKITE_CLUSTER_NAME","BUILDKITE_PULL_REQUEST","BUILDKITE_PULL_REQUEST_REPO","BUILDKITE_PULL_REQUEST_BASE_BRANCH","BUILDKITE_PULL_REQUEST_DRAFT","BUILDKITE_PULL_REQUEST_LABELS","BUILDKITE_MERGE_QUEUE_BASE_BRANCH","BUILDKITE_MERGE_QUEUE_BASE_COMMIT","BUILDKITE_REBUILT_FROM_BUILD_ID","BUILDKITE_REBUILT_FROM_BUILD_NUMBER","BUILDKITE_TRIGGERED_FROM_BUILD_ID","BUILDKITE_TRIGGERED_FROM_BUILD_NUMBER","BUILDKITE_TRIGGERED_FROM_BUILD_PIPELINE_SLUG"]),circle:v(["CI","CIRCLECI","CIRCLE_BRANCH","CIRCLE_BUILD_NUM","CIRCLE_BUILD_URL","CIRCLE_PREVIOUS_BUILD_NUM","CIRCLE_JOB","CIRCLE_WORKFLOW_ID","CIRCLE_WORKFLOW_JOB_ID","CIRCLE_WORKFLOW_WORKSPACE_ID","CIRCLE_PIPELINE_ID","CIRCLE_ORGANIZATION_ID","CIRCLE_PROJECT_ID","CIRCLE_PROJECT_REPONAME","CIRCLE_PROJECT_USERNAME","CIRCLE_REPOSITORY_URL","CIRCLE_WORKING_DIRECTORY","CIRCLE_SHA1","CIRCLE_TAG","CIRCLE_USERNAME","CIRCLE_NODE_INDEX","CIRCLE_NODE_TOTAL","CIRCLE_PR_NUMBER","CIRCLE_PR_REPONAME","CIRCLE_PR_USERNAME","CIRCLE_PULL_REQUEST","CIRCLE_PULL_REQUESTS","CI_PULL_REQUEST"]),concourse:v(["BUILD_ID","BUILD_NAME","BUILD_JOB_NAME","BUILD_PIPELINE_NAME","BUILD_TEAM_NAME","ATC_EXTERNAL_URL"]),codeFresh:v(["CF_BUILD_ID","CF_BUILD_URL","CF_CURRENT_ATTEMPT","CF_STEP_NAME","CF_PIPELINE_NAME","CF_PIPELINE_TRIGGER_ID","CF_PULL_REQUEST_ID","CF_PULL_REQUEST_IS_FORK","CF_PULL_REQUEST_NUMBER","CF_PULL_REQUEST_TARGET"]),drone:v(["DRONE_BUILD_LINK","DRONE_BUILD_NUMBER","DRONE_PULL_REQUEST"]),githubActions:v(["CI","GITHUB_ACTIONS","GITHUB_WORKFLOW","GITHUB_WORKFLOW_REF","GITHUB_WORKFLOW_SHA","GITHUB_ACTION","GITHUB_ACTION_PATH","GITHUB_ACTION_REPOSITORY","GITHUB_JOB","GITHUB_EVENT_NAME","GITHUB_EVENT_PATH","GITHUB_RUN_ID","GITHUB_RUN_NUMBER","GITHUB_RUN_ATTEMPT","GITHUB_REPOSITORY","GITHUB_REPOSITORY_ID","GITHUB_REPOSITORY_OWNER","GITHUB_REPOSITORY_OWNER_ID","GITHUB_REF","GITHUB_REF_NAME","GITHUB_REF_TYPE","GITHUB_REF_PROTECTED","GITHUB_BASE_REF","GITHUB_HEAD_REF","GITHUB_SHA","GITHUB_ACTOR","GITHUB_ACTOR_ID","GITHUB_TRIGGERING_ACTOR","GITHUB_SERVER_URL","GITHUB_API_URL","GITHUB_GRAPHQL_URL","GITHUB_WORKSPACE","GITHUB_RETENTION_DAYS","RUNNER_OS","RUNNER_ARCH","RUNNER_NAME","RUNNER_ENVIRONMENT","RUNNER_DEBUG"]),gitlab:v(["CI_PIPELINE_ID","CI_PIPELINE_URL","CI_BUILD_ID","CI_JOB_ID","CI_JOB_URL","CI_JOB_NAME","CI_NODE_INDEX","CI_NODE_TOTAL","GITLAB_HOST","CI_PROJECT_ID","CI_PROJECT_URL","CI_REPOSITORY_URL","CI_ENVIRONMENT_URL","CI_DEFAULT_BRANCH","RUN_ATTEMPT","CI_MERGE_REQUEST_IID","CI_MERGE_REQUEST_PROJECT_URL","CI_MERGE_REQUEST_TITLE","CI_MERGE_REQUEST_SOURCE_BRANCH_NAME","CI_MERGE_REQUEST_TARGET_BRANCH_NAME","CI_OPEN_MERGE_REQUESTS"]),goCD:v(["GO_SERVER_URL","GO_ENVIRONMENT_NAME","GO_PIPELINE_NAME","GO_PIPELINE_COUNTER","GO_PIPELINE_LABEL","GO_STAGE_NAME","GO_STAGE_COUNTER","GO_JOB_NAME","GO_TRIGGER_USER","GO_REVISION","GO_TO_REVISION","GO_FROM_REVISION","GO_MATERIAL_HAS_CHANGED"]),googleCloud:v(["BUILD_ID","PROJECT_ID","REPO_NAME","BRANCH_NAME","TAG_NAME","COMMIT_SHA","SHORT_SHA"]),jenkins:v(["BRANCH_NAME","BUILD_DISPLAY_NAME","BUILD_ID","BUILD_NUMBER","BUILD_TAG","BUILD_URL","CHANGE_AUTHOR","CHANGE_AUTHOR_DISPLAY_NAME","CHANGE_AUTHOR_EMAIL","CHANGE_BRANCH","CHANGE_FORK","CHANGE_ID","CHANGE_TARGET","CHANGE_TITLE","CHANGE_URL","CI","EXECUTOR_NUMBER","JAVA_HOME","JENKINS_HOME","JENKINS_URL","JOB_BASE_NAME","JOB_NAME","JOB_URL","NODE_LABELS","NODE_NAME","RUN_ARTIFACTS_DISPLAY_URL","RUN_CHANGES_DISPLAY_URL","TAG_NAME","WORKSPACE","WORKSPACE_TMP","GIT_AUTHOR_EMAIL","GIT_AUTHOR_NAME","GIT_BRANCH","GIT_COMMIT","GIT_COMMITTER_EMAIL","GIT_COMMITTER_NAME","GIT_LOCAL_BRANCH","GIT_PREVIOUS_COMMIT","GIT_PREVIOUS_SUCCESSFUL_COMMIT","GIT_URL","ghprbActualCommit","ghprbGhRepository","ghprbPullId","ghprbPullLink","ghprbSourceBranch","ghprbTargetBranch","ghprbTriggerAuthorLogin"]),semaphore:v(["SEMAPHORE_BRANCH_ID","SEMAPHORE_BUILD_NUMBER","SEMAPHORE_CURRENT_JOB","SEMAPHORE_CURRENT_THREAD","SEMAPHORE_EXECUTABLE_UUID","SEMAPHORE_GIT_BRANCH","SEMAPHORE_GIT_DIR","SEMAPHORE_GIT_REF","SEMAPHORE_GIT_REF_TYPE","SEMAPHORE_GIT_REPO_SLUG","SEMAPHORE_GIT_SHA","SEMAPHORE_GIT_URL","SEMAPHORE_JOB_COUNT","SEMAPHORE_JOB_ID","SEMAPHORE_JOB_NAME","SEMAPHORE_JOB_UUID","SEMAPHORE_PIPELINE_ID","SEMAPHORE_PLATFORM","SEMAPHORE_PROJECT_DIR","SEMAPHORE_PROJECT_HASH_ID","SEMAPHORE_PROJECT_ID","SEMAPHORE_PROJECT_NAME","SEMAPHORE_PROJECT_UUID","SEMAPHORE_REPO_SLUG","SEMAPHORE_TRIGGER_SOURCE","SEMAPHORE_WORKFLOW_ID","PULL_REQUEST_NUMBER"]),teamcity:null,travis:v(["TRAVIS_JOB_ID","TRAVIS_BUILD_ID","TRAVIS_BUILD_WEB_URL","TRAVIS_REPO_SLUG","TRAVIS_JOB_NUMBER","TRAVIS_EVENT_TYPE","TRAVIS_COMMIT_RANGE","TRAVIS_BUILD_NUMBER","TRAVIS_PULL_REQUEST","TRAVIS_PULL_REQUEST_BRANCH","TRAVIS_PULL_REQUEST_SHA"]),netlify:v(["BUILD_ID","CONTEXT","URL","DEPLOY_URL","DEPLOY_PRIME_URL","DEPLOY_ID"])}),sm=t=>{let e=oi();return e?(0,w.chain)(t()).get(e).value():{}};function im(){return(0,w.chain)(ni()).omitBy(w.isNull).keys().value()}function am(t){return t&&im().includes(t)}function oi(){let t=om();return We("detected CI provider name: %s",t),t||null}function cm(){let t=sm(ni);return(0,w.mapValues)(t,e=>(0,w.isString)(e)?rn(e):e)}function ut(t){let e=cm(),r=oi(),n=pm(t,r);return We("detected CI provider: %s",r),We("detected CI params: %O",e),We("detected CI build ID: %o",n),{params:e,provider:r,ciBuildId:n}}function pm(t,e){return t?{source:"user",value:t}:am(e)?{source:"server",value:null}:{source:"random",value:`auto:${en()}`}}var yn=g(require("path")),pi=g(require("yazl"));var Vt=g(require("fs")),me=g(require("path")),si=require("stream/promises"),ze=require("util"),Tn=g(require("yauzl")),um=(0,ze.promisify)(Tn.default.open),dm=(0,ze.promisify)(Tn.default.fromBuffer);async function le(t,e,r){let n=r.split(me.default.sep).join("/").replace(/^(\.\.\/|\/)+/,"");if(!(await Vt.default.promises.stat(e)).isDirectory()){t.addFile(e,n);return}n&&t.addEmptyDirectory(n);for(let s of await Vt.default.promises.readdir(e))await le(t,me.default.join(e,s),n?`${n}/${s}`:s)}function Qe(t){let e=t.outputStream;return t.on("error",r=>e.destroy(r)),t.end(),e}function ii(t,e){return new Promise((r,n)=>{t.on("error",n),t.on("end",()=>r()),t.on("entry",o=>{Promise.resolve(e(o)).then(()=>t.readEntry()).catch(s=>{t.close(),n(s)})}),t.readEntry()})}function ai(t){let e={lazyEntries:!0};return typeof t=="string"?um(t,e):dm(t,e)}async function ci(t){let e=await ai(t),r=[];return await ii(e,n=>{r.push(n.fileName)}),r}async function Cn(t,e){let r=await ai(t),n=(0,ze.promisify)(r.openReadStream.bind(r));await ii(r,async o=>{let s=me.default.join(e,o.fileName);if(o.fileName.endsWith("/")){await Vt.default.promises.mkdir(s,{recursive:!0});return}await Vt.default.promises.mkdir(me.default.dirname(s),{recursive:!0}),await(0,si.pipeline)(await n(o),Vt.default.createWriteStream(s))})}var mm=50*1024*1024;async function ui(t,e=mm){let r=new pi.default.ZipFile;for(let i of t)await le(r,i,yn.default.relative(process.cwd(),yn.default.normalize(i)));let n=[],o=0,s=Qe(r);for await(let i of s){if(o+=i.length,o>e)throw s.destroy(),new Error(`Zip size exceeded the limit of ${e} bytes`);n.push(i)}return Buffer.concat(n)}var di=require("lodash");var lm={githubActions:[],gitlab:[],appveyor:["APPVEYOR_ACCOUNT_NAME","APPVEYOR_PROJECT_SLUG","APPVEYOR_BUILD_NUMBER"],azure:["SYSTEM_COLLECTIONID","BUILD_BUILDID"],awsCodeBuild:["CODEBUILD_BUILD_ID"],bamboo:["bamboo_buildKey","bamboo_buildNumber"],bitbucket:["BITBUCKET_PIPELINE_UUID"],buildkite:["BUILDKITE_BUILD_ID"],circle:["CIRCLE_WORKFLOW_WORKSPACE_ID"],concourse:["BUILD_ID"],codeFresh:["CF_BUILD_ID"],drone:["DRONE_BUILD_LINK"],goCD:["GO_PIPELINE_NAME","GO_PIPELINE_COUNTER"],googleCloud:["BUILD_ID"],jenkins:["JOB_NAME","BUILD_NUMBER"],semaphore:["SEMAPHORE_PIPELINE_ID"],travis:["TRAVIS_JOB_ID"],netlify:["BUILD_ID"]};function fm({provider:t,params:e}){let r=t?lm[t]:null;return!r||!e?!1:r.every(n=>!!e[(0,di.camelCase)(n)])}function Xe(t,e){e||fm(t)||De("No CI job detected: without --id the cache ID is random, so cache get does not find what cache set saved. Pass --id to save and restore the same cache.")}var li=g(require("fs")),fi=require("stream"),gi=require("timers/promises");var ge=d.extend("upload"),fe=5;async function Rn(t,e,r){return ge("Uploading buffer %s",t.name,{buffer:Buffer.byteLength(t.buffer)}),Ci(t.buffer,t.uploadUrl,e,r,t.headers,Ei(Buffer.byteLength(t.buffer)))}var gm=256*1024,hm=120*1e3;async function hi(t){return ge("Uploading file %s",t.name,{bytes:t.sizeBytes}),Ci(()=>t.sizeBytes>0?li.default.createReadStream(t.path,{end:t.sizeBytes-1}):fi.Readable.from([]),t.uploadUrl,t.contentType,void 0,{...t.headers??{"Content-Type":t.contentType},"Content-Length":String(t.sizeBytes)},Ei(t.sizeBytes))}function Ei(t){return hm+Math.ceil(t/gm)*1e3}async function Em(t,e,r,n,o,s){let i=typeof t=="function"?t():t;await bt({method:"PUT",url:e,timeout:s,body:i,headers:o??{"Content-Disposition":"inline","Content-Type":r}}),Buffer.isBuffer(i)&&n?.({loaded:i.length,total:i.length})}async function wn(t){try{return(await bt({method:"GET",url:t,responseType:"buffer"})).data}catch(e){throw L(e)&&ge("Failed to download %s: %s",Ft(t),e.message),e}}var Im=["RequestTimeout","OperationAborted","SlowDown"];function Ii(t){if(t)return t.replace(/[\u0000-\u001f\u007f-\u009f]/g,"").replace(/\b[a-z][a-z0-9+.-]*:\/\/\S+/gi,e=>Ft(e)).slice(0,200)}function Ti(t){let e=L(t)?t.response?.data:void 0,r=typeof e=="string"?e:"";return{code:r.match(/<Code>([^<]*)<\/Code>/)?.[1],message:Ii(r.match(/<Message>([^<]*)<\/Message>/)?.[1])}}function Tm(t){let e=L(t)?t.response?.status:void 0;if(e===void 0||e<400||e>=500||e===408||e===429)return!1;let{code:r}=Ti(t);return!(r&&Im.includes(r))}function Cm(t){if(!L(t)||!t.response)return t instanceof Error?t:new Error(String(t));let{code:e,message:r}=Ti(t),n=[Ii(e),r].filter(Boolean).join(": ");return new Error(`storage answered ${t.response.status}${n?` ${n}`:""}`)}async function Ci(...t){try{await wm(t)}catch(e){throw Cm(e)}}function ym(){return Array.from({length:fe},(t,e)=>Math.round((Math.random()+1)*1e3*2**e)).sort((t,e)=>t-e)}function Rm(t){let e=new Map,r=t[0],n=0;for(let o of t){let s=(e.get(o.message)??0)+1;e.set(o.message,s),s>=n&&(r=o,n=s)}return r}async function wm(t){let e=ym(),r=[];for(let n=1;;n++)try{return await Em(...t)}catch(o){if(Tm(o))throw o;if(r.push(o),n>fe)throw Rm(r);_m(o,n),await(0,gi.setTimeout)(e[n-1])}}function _m(t,e){if(ge("Upload failed %d out of %d attempts: %s",e,fe,t.message),e===fe){T(`Cannot upload after ${e} times: ${t.message}`);return}I(`Upload failed ${e} out of ${fe} attempts: ${t.message}`)}var _n=t=>({total:e,loaded:r})=>{ge("Uploading %s: %d / %d",t,mi(r),mi(e??0))};function mi(t){return t/1e3/1e3}var xn=g(require("lodash"));var dt=g(require("path"));var Ri=require("path"),wi=require("tinyglobby");function he(t){let e=t.map(xm),r=e.filter(o=>o.startsWith("!")).map(o=>o.slice(1)),n=e.filter(o=>!o.startsWith("!")).flatMap(o=>(0,wi.globSync)(o,{absolute:(0,Ri.isAbsolute)(o),ignore:r}).sort());return[...new Set(n)]}var Om=/(?<!\\)\{(-?\d+)\.\.(-?\d+)(?:\.\.(-?\d+))?\}/g,yi=1e3;function xm(t){return t.replace(Om,(e,r,n,o)=>{let s=Sm(r,n,o);return s.length===1?s[0]:`{${s.join(",")}}`})}function Sm(t,e,r="1"){let n=Number(t),o=Number(e),s=Math.abs(Number(r))||1,i=Math.floor(Math.abs(o-n)/s)+1;if(i>yi){let l=[t,e,...r==="1"?[]:[r]].join("..");throw new Error(`{${l}} expands to more than ${yi} values`)}let a=n<=o?1:-1,p=[t,e].some(l=>/^-?0\d/.test(l))?Math.max(t.length,e.length):0;return Array.from({length:i},(l,m)=>{let h=n+m*a*s,f=h<0?"-":"";return f+String(Math.abs(h)).padStart(p-f.length,"0")})}var _i=require("lodash");function On({config:t,cacheId:e,orgId:r,path:n,ci:o,cacheKey:s,metaCacheKey:i}){let a={id:e,orgId:r,config:(0,_i.omit)(t,"recordKey"),path:n,ci:o,createdAt:new Date().toISOString(),cacheKey:s,metaCacheKey:i};return Buffer.from(JSON.stringify(a))}function Oi(t,e){t instanceof Error?_t("%s. %s.",e,t.message):_t("%s. %s.",e,"Unknown error")}var xi=async t=>{let e=dt.default.resolve(t??"./test-results"),r=[dt.default.posix.join(e.replace(/\\/g,"/"),"**/.last-run.json"),dt.default.posix.join(e.replace(/\\/g,"/"),".last-run.json")];return he(r)},Si=async(t=[])=>{let e=Am(t);return e.length===0?[]:he(e.map(r=>r.replace(/\\/g,"/")))};function Am(t){let e=process.cwd();return t.filter(r=>{let n=dt.default.relative(e,dt.default.resolve(r));return n===".."||n.startsWith(`..${dt.default.sep}`)||dt.default.isAbsolute(n)?(Oi(null,`Invalid path: "${r}". Path traversal detected. The path was skipped.`),!1):!0})}function Ze(t){return t?t.path.some(e=>dt.default.basename(e)===".last-run.json"):!1}async function Ai(t,e){switch(e.provider){case"githubActions":await Ui(t,e);break;case"gitlab":await Pi(t,e);break;case"circle":await Di(t,e);break;default:break}}async function bi(t,e,r){switch(e.provider){case"githubActions":await Ui(t,e,r);break;case"gitlab":await Pi(t,e,r);break;case"circle":await Di(t,e,r);break;default:break}}async function Pi(t,e,r=null){let n=e.params,o=r?.ci.params,i=(o?qt(o.runAttempt,0):0)+1,a=qt(n.ciNodeIndex,1),u=qt(n.ciNodeTotal,1),p=Ze(r),l=i>1&&p,m=l?"--last-failed":"",h="";u>1&&(h=l?"--shard=1/1":`--shard=${a}/${u}`);let f=[m,h].filter(Boolean).join(" ");await xt(t.presetOutput??de,`EXTRA_PW_FLAGS="${f}"
22
+ EXTRA_PWCP_FLAGS="${m}"
24
23
  RUN_ATTEMPT=${i}
25
- `)}async function Ns(t,e,r=null){let{matrixIndex:o,matrixTotal:n}=t,s=e.params,i=Lt(s.githubRunAttempt,1),c=Ae(r),m=i>1&&c,d=m?"--last-failed":"",f="";n>1&&(f=m?"--shard=1/1":`--shard=${o}/${n}`);let u=[d,f].filter(Boolean).join(" "),E=t.presetOutput??Zt;await It(E,u),p('Dumped PW config: "%s" for GHA to %s',u,E)}async function Ls(t,e,r=null){let o=e.params,n=r?.ci.params,s=n?.circleWorkflowId,i=n?.circleWorkflowWorkspaceId,c=Lt(o.circleNodeIndex,0),m=Lt(o.circleNodeTotal,1),d=i==o.circleWorkflowWorkspaceId&&s!==o.circleWorkflowId,f=Ae(r),u=d&&f,E=u?"--last-failed":"",g="";m>1&&(g=u?"--shard=1/1":`--shard=${c+1}/${m}`);let A=[E,g].filter(Boolean).join(" "),Y=t.presetOutput??Zt;await It(Y,A),p('Dumped PW config: "%s" for Circle to %s',A,Y)}var Lt=(t,e)=>{let r=Yr.default.toNumber(t);return Yr.default.isNaN(r)?e:r};async function qr(){let t=dt();if(t.type!=="GET_COMMAND_CONFIG"||!t.values)throw new Error("Config is missing!");let{recordKey:e,id:r,preset:o,matrixIndex:n,matrixTotal:s,continue:i}=t.values,c=t.values.outputDir,m=rt();Oe(m,r),o==="last-run"&&await Us(t.values,m);let{cacheId:d,refMetaReadUrl:f}=await _n({recordKey:e,ci:m,id:r,config:{matrixIndex:n,matrixTotal:s}});try{let u=await Sd(f),{readUrl:E}=await wn({recordKey:e,cacheKey:u.cacheKey}),g=await Od({readUrl:E,outputDir:c});o==="last-run"&&await Ps(t.values,m,u),T(x("- restoring cache to"),g),de("Cache restored. Cache ID: %s",d)}catch(u){if((0,vs.isAxiosError)(u)&&(u.response?.status===403||u.response?.status===404)){let E=`Cache with ID "${d}" not found`;if(i){gt(E);return}throw new Error(E)}throw u}}async function Od({readUrl:t,outputDir:e}){let r=await Kr(t),o=xd(e);return await us(r,o),p("Cache downloaded",{readUrl:t,destination:o}),o}function xd(t){let e=t??process.cwd();return Wr.default.isAbsolute(e)?e:Wr.default.resolve(process.cwd(),e)}async function Sd(t){let e=await Kr(t),r=JSON.parse(e.toString("utf-8"));return p("Meta file downloaded: %O",r),r}var Fs=require("lodash");async function zr(){let t=dt();if(t.type!=="SET_COMMAND_CONFIG"||!t.values)throw new Error("Config is missing!");let{recordKey:e,id:r,preset:o,pwOutputDir:n,matrixIndex:s,matrixTotal:i,continue:c}=t.values,m=await Ds(t.values.path),d=t.values.path||[],f=rt();if(Oe(f,r),o==="last-run"&&(d.push(n),m.push(...await As(n))),m.length===0){let Y=`No files available to upload: ${d.filter(Boolean).join(",")}`;if(!c)throw new Error(Y);gt(Y)}let u=await Rn({recordKey:e,ci:f,id:r,config:{matrixIndex:s,matrixTotal:i}});p("Cache upload url created",{result:u});let E=Dd(f),g=m.length>0?await ms(m):null,A=[];g&&A.push(Ad({archive:g,cacheId:u.cacheId,uploadUrl:u.uploadUrl}).then(()=>{Ud(m),p("Cache archive uploaded",{uploadUrl:u.uploadUrl})})),A.push(Bs({meta:Jr({cacheId:u.cacheId,config:t.values,ci:E,orgId:u.orgId,path:m}),cacheId:u.cacheId,uploadUrl:u.metaUploadUrl}).then(()=>p("Meta uploaded",{uploadUrl:u.metaUploadUrl})),Bs({meta:Jr({cacheId:u.cacheId,config:t.values,ci:E,orgId:u.orgId,path:m,cacheKey:u.cacheKey,metaCacheKey:u.metaCacheKey}),cacheId:u.cacheId,uploadUrl:u.refMetaUploadUrl}).then(()=>p("Ref meta uploaded",{uploadUrl:u.refMetaUploadUrl}))),await Promise.all(A),de("Cache uploaded. Cache ID: %s",u.cacheId)}async function Ad({archive:t,cacheId:e,uploadUrl:r}){try{let o="application/zip";await Gr({buffer:t,contentType:o,name:e,uploadUrl:r},o,Hr(e)),p("Cache archive uploaded",{cacheId:e})}catch(o){throw p("Failed to upload cache archive",o),o}}async function Bs({meta:t,cacheId:e,uploadUrl:r}){try{let o=`${e}_meta`,n="application/json";await Gr({buffer:t,contentType:n,name:o,uploadUrl:r},n,Hr(o)),p("Cache meta uploaded",{cacheId:e})}catch(o){throw p("Failed to upload cache meta",o),o}}function Dd(t){return t.ciBuildId.source==="server"||t.ciBuildId.source==="random"?(0,Fs.omit)(t,"ciBuildId"):t}function Ud(t){T(`Cache upload paths:
26
- `+t.map(e=>`${x("- uploading")} ${e}`).join(`
27
- `))}var{recordKey:Pd,projectId:bd,ciBuildId:Nd,debug:Ld}=_,X={recordKey:Pd,projectId:bd,ciBuildId:Nd,runId:{name:"Run ID",env:"CURRENTS_RUN_ID",cli:"--run-id"},debug:Ld};var vd=p.extend("config"),Bd=["recordKey","projectId"];function Fd(t){if(!(t.runId||t.ciBuildId))throw C(`${he(X,"runId")} or ${he(X,"ciBuildId")} is required: pass ${x(ge(X,"runId"))} or ${x(ge(X,"ciBuildId"))}, or set ${x(L(X,"runId"))} or ${x(L(X,"ciBuildId"))}`),new z("Missing required config variable")}var Qr=null;function Ms(t){Qr=U(X,Bd,t,Fd),vd("Resolved config: %o",h(Qr))}function De(){return Qr}async function Xr(){let t=De();if(!t)throw new Error("Config is missing!");let e=t.runId?`runId: ${t.runId}`:`ciBuildId: ${t.ciBuildId}`;try{let r=await On({recordKey:t.recordKey,projectId:t.projectId,ciBuildId:t.ciBuildId,runId:t.runId});return r.data.runId?T('Run "%s" (%s) is cancelled',r.data.runId,e):T('No run to cancel (%s) in project "%s"',e,t.projectId),r}catch(r){throw p("Failed to cancel the run"),r}}var ks=require("@currents/commit-info"),js=require("lodash");var Md=p.extend("git"),kd=async()=>{let t=await(0,ks.commitInfo)();return Md("commit: %O",t),{branch:t.branch,remoteOrigin:t.remote,authorEmail:t.email,authorName:t.author,message:t.message,sha:t.sha,ghaEventData:t.ghaEventData??null}},Ue=(0,js.memoize)(kd);var $s=l(require("getos")),Gs=require("lodash"),H=require("os"),Ks=require("util"),jd=async()=>{if((0,H.platform)()==="linux")try{let t=await(0,Ks.promisify)($s.default)();return"dist"in t&&"release"in t?[t.dist,t.release].join(" - "):(0,H.release)()}catch{return(0,H.release)()}return(0,H.release)()},$d=async()=>{let t=await jd();return{osName:(0,H.platform)(),osVersion:t,osCpus:[],osMemory:{free:(0,H.freemem)(),total:(0,H.totalmem)()}}},Hs=(0,Gs.memoize)($d);var ji=l(require("axios")),ao=l(require("fs-extra")),$e=l(require("path")),$i=l(require("semver"));var{debug:Gd,ciBuildId:Kd,recordKey:Hd,projectId:Jd,machineId:Vd}=_,nt={debug:Gd,ciBuildId:Kd,recordKey:Hd,projectId:Jd,machineId:Vd,tag:{..._.tag,env:"CURRENTS_TAG"},disableTitleTags:{name:"Disable title tags",env:"CURRENTS_DISABLE_TITLE_TAGS",cli:"--disable-title-tags"},removeTitleTags:{name:"Remove title tags",env:"CURRENTS_REMOVE_TITLE_TAGS",cli:"--remove-title-tags"},reportDir:{name:"Report folder",env:"CURRENTS_REPORT_DIR",cli:"--report-dir"}};var Yd=p.extend("config"),Wd=["projectId","recordKey"],Zr=null;function Js(t){Zr=U(nt,Wd,t),Yd("Resolved Currents config: %o",h(Zr))}function Pe(){return Zr}function Vs(t){return{ciBuildId:t.ciBuildId,projectId:t.projectId,recordKey:t.key,tag:t.tag,removeTitleTags:t.removeTitleTags,disableTitleTags:t.disableTitleTags,debug:t.debug,machineId:t.machineId,reportDir:t.reportDir}}var oo=l(require("fs-extra")),st=require("path");var Ys=l(require("path")),to={".png":{type:"screenshot",contentType:"image/png"},".jpg":{type:"screenshot",contentType:"image/jpeg"},".jpeg":{type:"screenshot",contentType:"image/jpeg"},".webp":{type:"screenshot",contentType:"image/webp"},".gif":{type:"screenshot",contentType:"image/gif"},".mp4":{type:"video",contentType:"video/mp4"},".webm":{type:"video",contentType:"video/webm"},".svg":{type:"attachment",contentType:"image/svg+xml"},".log":{type:"attachment",contentType:"text/plain"},".txt":{type:"attachment",contentType:"text/plain"},".yml":{type:"attachment",contentType:"text/plain"},".yaml":{type:"attachment",contentType:"text/plain"},".md":{type:"attachment",contentType:"text/markdown"},".html":{type:"attachment",contentType:"text/html"},".csv":{type:"attachment",contentType:"text/csv"},".json":{type:"attachment",contentType:"application/json"},".pdf":{type:"attachment",contentType:"application/pdf"},".gz":{type:"attachment",contentType:"application/gzip"},".viewhierarchy":{type:"attachment",contentType:"application/xml"}},eo=t=>to[Ys.default.extname(t).toLowerCase()];var Ws=l(require("fs-extra")),qs=require("path"),ro=p.extend("detox"),qd="detox.json";function zs(t){return[...t].sort((e,r)=>(e.session??0)-(r.session??0)||e.invocations-r.invocations)}async function Qs(t){let e=(0,qs.join)(t,qd);try{let r=await Ws.default.readJson(e);if(typeof r?.artifactsRootDir!="string"||!Array.isArray(r?.tests)){ro("Unexpected Detox manifest contents at %s",e);return}return ro("Detox manifest: %o",r),r}catch{ro("No Detox manifest at %s",e);return}}var be=require("path"),zd=p.extend("detox"),Xs=255,Qd=/[/\\?<>:*|"$\u0000-\u001f]/g,Zs=4;function ti(t){return Xd(t)??Zd(t)}function Xd({rootDir:t,fullName:e,status:r,invocations:o}){try{let n=require.resolve("detox/src/artifacts/utils/ArtifactPathBuilder",{paths:[process.cwd()]}),s=require(n),i=new s({rootDir:t});return(0,be.dirname)(i.buildPathForTestArtifact("test.mp4",{fullName:e,status:r,invocations:o}))}catch(n){zd("Detox path builder is not available: %o",n);return}}function Zd({rootDir:t,fullName:e,status:r,invocations:o}){let n=em(r),s=o>1?` (${o})`:"",i=e.slice(-Xs+n.length+s.length),c=`${n}${i}${s}`.replace(Qd,"_");return(0,be.join)(t,tm(c,Xs))}function tm(t,e){let r=Buffer.from(t,"utf8");return r.length<=e?t:r.subarray(0,e).toString("utf8").replace(/\uFFFD$/,"")}function em(t){switch(t){case"passed":return"\u2713 ";case"failed":return"\u2717 ";default:return""}}var ri=l(require("fs-extra")),oi=require("path"),ei=p.extend("detox"),Ne="detox.trace.json",rm="ws-client-invocation";async function ni(t){let e=(0,oi.join)(t,Ne),r=new Map,o;try{o=await ri.default.readJson(e)}catch{return ei("No Detox trace at %s",e),r}if(!Array.isArray(o))return ei("Unexpected Detox trace contents at %s",e),r;let n=om(o);return sm(o).forEach(({pid:i,ts:c,step:m})=>{n.filter(f=>f.pid===i&&c>=f.startTs&&c<=f.endTs).sort((f,u)=>f.startTs-u.startTs).pop()?.steps.push(m)}),n.forEach(({fullName:i,invocations:c,steps:m})=>{let d=r.get(i)??[];d.push({fullName:i,invocations:c,steps:m.sort((f,u)=>+new Date(f.startTime)-+new Date(u.startTime))}),r.set(i,d)}),r}function om(t){let e=new Map,r=[];t.forEach(n=>{let s=`${n.pid}:${n.tid}`,i=e.get(s)??[];if(e.set(s,i),n.ph==="B"){i.push(nm(n));return}if(n.ph==="E"){let c=i.pop();c&&r.push({...c,endTs:Number(n.ts)})}});let o=[...e.values()].flatMap(n=>n.filter(s=>s!==void 0));return[...r,...o]}function nm(t){let e=t.args?.fullName;if(!(t.args?.context!=="test"||typeof e!="string"))return{fullName:e,invocations:Number(t.args?.invocations??1),pid:Number(t.pid),startTs:Number(t.ts),endTs:Number.MAX_SAFE_INTEGER,steps:[]}}function sm(t){let e=new Map,r=[];return t.forEach(o=>{if(!o.cat?.includes(rm))return;let n=`${o.pid}:${o.tid}`,s=e.get(n)??[];if(o.ph==="B"){s.push({name:o.name??"action",cat:o.cat,ts:Number(o.ts)}),e.set(n,s);return}if(o.ph==="E"){let i=s.pop();if(!i)return;r.push({pid:Number(o.pid),ts:i.ts,step:{title:i.name,category:"detox",startTime:new Date(i.ts/1e3).toISOString(),duration:Math.round((Number(o.ts)-i.ts)/1e3),steps:[]}})}}),r}var re=p.extend("detox"),si="artifacts",im=[".mp4",".png",".jpg",".log",".txt",".json",".viewhierarchy"],am=t=>{let e=(0,st.extname)(t);return im.includes(e)?to[e]:void 0};async function ii({instances:t,reportDir:e,manifest:r}){let o=pm(r),n=await ni(r.artifactsRootDir),s=await Ct((0,st.join)(e,si)),i={artifacts:0,steps:0};for(let c of t)for(let m of c.results.tests){let d=o.get(m.testId);if(!d){re("No Detox manifest entry for %s",m.testId);continue}await dm({test:m,manifestTest:d,rootDir:r.artifactsRootDir,artifactsDir:s,traceSlices:n.get(d.fullName)??[],result:i})}return i.artifacts+=await cm({instances:t,rootDir:r.artifactsRootDir,artifactsDir:s}),i}async function cm({instances:t,rootDir:e,artifactsDir:r}){if(!await oo.default.pathExists((0,st.join)(e,Ne)))return 0;let[o]=await ai(e,[Ne],r),n=t.map(s=>s.results.tests[0]).filter(s=>s!==void 0);return n.forEach(s=>{s.artifacts=[...s.artifacts??[],o]}),n.length}function pm(t){let e=new Map;return t.tests.forEach(r=>{e.set(r.fullName,[...e.get(r.fullName)??[],r.testId])}),new Map(t.tests.filter(r=>{let o=e.get(r.fullName)?.length===1;return o||re("Ambiguous Detox test name, skipping: %s",r.fullName),o}).map(r=>[r.testId,r]))}async function dm({test:t,manifestTest:e,rootDir:r,artifactsDir:o,traceSlices:n,result:s}){let i=[...t.attempts].sort((d,f)=>d.attempt-f.attempt),c=zs(e.attempts),m=1;for(let[d,f]of c.entries()){let u=i[d];if(!u){re("No reported attempt %d of %s",d,e.fullName);continue}let E=await mm({fullName:e.fullName,status:f.status,rootDir:r,artifactsDir:o,fromInvocation:m});E&&(m=E.invocation+1,u.artifacts=[...u.artifacts??[],...E.artifacts],s.artifacts+=E.artifacts.length);let g=lm(n,d,E?.invocation);g.length&&(u.steps=[...u.steps??[],...g],s.steps+=g.length)}}async function mm({fullName:t,status:e,rootDir:r,artifactsDir:o,fromInvocation:n}){for(let s=n;s<n+Zs;s++){let i=ti({rootDir:r,fullName:t,status:e,invocations:s}),c=await um(i);if(c)return{invocation:s,artifacts:await ai(i,c,o)}}re("No Detox artifacts for %s [%s]",t,e)}async function um(t){try{return(await oo.default.readdir(t)).sort()}catch{return}}async function ai(t,e,r){let o=[];for(let n of e){let s=am(n);if(!s){re("Skipping unsupported Detox artifact %s",n);continue}let i=(0,st.join)(t,n),c=`${et(i)}${(0,st.extname)(n)}`;await ue(i,(0,st.join)(r,c)),o.push({...s,path:(0,st.join)(si,c),name:n})}return o}function lm(t,e,r){return((r===void 0?void 0:t.find(s=>s.invocations===r))??[...t].sort((s,i)=>s.invocations-i.invocations)[e])?.steps??[]}var mt=class{constructor(e){this.config=e}async getFullTestSuite(){return[]}};var gm=l(require("crypto"));var ci=l(require("fs-extra")),fm=l(require("path"));async function Le(t){let e=await ci.default.pathExists(t);if(!e)throw new Error("File does not exist");return e}function pi(){return"root"}function di(t){let e=(t.join(" ").match(/@(\S+)/g)??[]).filter(Boolean).map(r=>r);return Array.from(new Set([...e].map(r=>r.trim()).map(r=>r.replace("@",""))))}var hm=/^[0-9a-f]{32}$/;function mi(t){let e=[];for(let r of t){let o=e.find(n=>n.name===r.groupId);o||(o={name:r.groupId,tags:[],tests:[]},e.push(o)),o.tests.push(...li(r))}return e.length===1&&hm.test(e[0].name)&&(e[0].name=pi()),e}function ui(t,e,r){let o=[];for(let{projectId:n,spec:s}of e){let i=r.find(m=>m.spec===s&&m.groupId===n)??(t.length===1?r.find(m=>m.spec===s):void 0);if(!i){o.push(s);continue}let c=t.length===1?t[0]:t.find(m=>m.name===n);c||(c={name:n,tags:[],tests:[]},t.push(c)),c.tests.push(...li(i))}return o}function li(t){return t.results.tests.map(e=>({spec:t.spec,testId:e.testId,title:e.title,tags:e.tags??di(e.title)}))}var Ai=l(require("fs-extra")),Di=l(require("tmp"));var xi=require("lodash");function fi(t){let e=[];for(let[r,o]of Object.entries(t))r==="_"||r==="$0"||r.includes("-")||(typeof o=="boolean"?o&&e.push(`--${r}`):Array.isArray(o)?o.forEach(n=>{e.push(`--${r}=${n}`)}):e.push(`--${r}=${o}`));return e.join(" ")}var gi=require("lodash"),Em=["bail","clearCache","collectCoverage","collectCoverageFrom","color","colors","config","coverage","coverageDirectory","coveragePathIgnorePatterns","coverageProvider","coverageReporters","coverageThreshold","debug","detectLeaks","detectOpenHandles","errorOnDeprecated","expand","forceExit","json","listTests","logHeapUsage","noStackTrace","notify","notifyMode","openHandlesTimeout","outputFile","reporters","runner","shard","showConfig","showSeed","silent","testFailureExitCode","testNamePattern","verbose","waitNextEventLoopTurnForUnhandledRejectionEvents","watch","watchAll","watchPathIgnorePatterns","watchman"];function hi(t){return(0,gi.omit)(t,...Em)}var _i=l(require("fs")),Me=require("lodash"),so=l(require("path"));var no=l(require("fs")),ve=require("module"),Be=l(require("path")),Ei=l(require("semver")),Im=">=29.5.0";function Cm(){let t=(0,ve.createRequire)(Be.default.join(process.cwd(),"package.json"));if(Tm(t)==="jest-cli")return t.resolve("jest-cli");try{return(0,ve.createRequire)(t.resolve("jest")).resolve("jest-cli")}catch{}try{return t.resolve("jest-cli")}catch{throw new Error(`Jest discovery needs the "jest" package, and it is not installed in ${process.cwd()}. Run the command from the folder of the project that ran the tests, or install Jest 29.5 or later: npm install --save-dev jest`)}}function Tm(t){for(let e of t.resolve.paths("jest")??[]){if(no.default.existsSync(Be.default.join(e,"jest","package.json")))return"jest";if(no.default.existsSync(Be.default.join(e,"jest-cli","package.json")))return"jest-cli"}return null}function Ii(){let t=(0,ve.createRequire)(Cm()),{version:e}=t("jest-cli/package.json");if(!Ei.default.satisfies(e,Im,{includePrerelease:!0}))throw new Error(`Jest discovery needs Jest 29.5 or later, and ${process.cwd()} has Jest ${e}. Update Jest: npm install --save-dev jest@latest`);return t}function Ci(){return Ii()("jest-cli")}function Ti(){return Ii()("jest-config")}function Fe(t,e){return(...r)=>new Promise((o,n)=>{let s=0,i=()=>{s++;try{let c=t(...r);o(c)}catch(c){if(s>=e.length)n(c);else{let m=e[s-1];setTimeout(i,m)}}};i()})}var yi=p.extend("jest-discovery");function Ri(t){return["testEnvironment","globalSetup","globalTeardown"].some(e=>String(t[e]??"").includes("detox"))}function wi(t){return{...(0,Me.omit)(t,["globalSetup","globalTeardown","testEnvironmentOptions"]),testEnvironment:"node"}}async function Oi(t,e){let r=e.detox;try{let{readInitialOptions:o}=Ti(),{config:n,configPath:s}=await o(t);r||=[n,...n.projects??[]].some(E=>typeof E!="string"&&Ri(E));let i=["collectCoverage","collectCoverageFrom","coverageDirectory","coveragePathIgnorePatterns","coverageProvider","coverageReporters","coverageThreshold","errorOnDeprecated","forceCoverageMatch","notify","notifyMode","openHandlesTimeout","reporters","runner","showSeed","testFailureExitCode","verbose","watchPathIgnorePatterns","watchPlugins","watchman","bail","clearCache","color","colors","debug","detectLeaks","detectOpenHandles","expand","forceExit","json","listTests","logHeapUsage","noStackTrace","outputFile","shard","showConfig","silent","testNamePattern","waitNextEventLoopTurnForUnhandledRejectionEvents","watch","watchAll"],c=["collectCoverageFrom","coverageDirectory","coveragePathIgnorePatterns","detectLeaks","detectOpenHandles","errorOnDeprecated","forceCoverageMatch","openHandlesTimeout","runner","watchPathIgnorePatterns"],m=E=>e.detox||Ri(E),d=(0,Me.omit)(n,i);if(m(d)&&(d=wi(d)),d.projects&&(d.projects=d.projects.map(E=>{if(typeof E=="string")return E;let g=(0,Me.omit)(E,c);return m(g)?wi(g):g})),d.rootDir&&Object.keys(d).length===1)return null;let f=so.default.resolve(s?so.default.dirname(s):process.cwd(),`.jest-scanner-${new Date().getTime()}.config.cjs`),u=`module.exports=${JSON.stringify(d,null,2)}`;return yi("configFileContent: %O",u),_i.default.writeFileSync(f,u),await Fe(Le,[200,200,200,200,200,1e3])(f),f}catch(o){if(yi("error %o",o),r)throw new Error(`Failed to recreate the Jest config for discovery: ${o.message}`);return C("Failed to recreate the config file"),null}}async function Si(t,e){let r="!!##ThisPatternWillNotMatchAnyTestName##!!",o=t.options,n=hi(o),s=fi(n),i=o.config,c=await Oi(i,e);return{cliArgs:[s,"--testNamePattern",r,"--reporters",require.resolve("@currents/cmd/discovery/jest"),"--shard=1/1","--testFailureExitCode=0",c?`--config=${c}`:"",...t.args].filter(d=>!(0,xi.isEmpty)(d)),configFilePath:c}}var ym=p.extend("jest-discovery");async function Ui(t,e){console.time(x("@currents/jest:fullTestSuite-ready"));let{run:r}=Ci(),{cliArgs:o,configFilePath:n}=await Si(t,e);try{let s=Di.default.fileSync({postfix:".json"});return ym("running scanner: %o",o),process.env.CURRENTS_DISCOVERY_PATH=s.name,await r(o.concat(["--openHandlesTimeout=0"])),await Fe(Le,Array.from({length:300},()=>100))(s.name),console.timeEnd(x("@currents/jest:fullTestSuite-ready")),await Et(s.name)}catch(s){return C("Failed to obtain the jest full test suite:",s),{fullTestSuite:[],specsWithoutResults:[]}}finally{n&&Ai.default.unlinkSync(n)}}var Pi=p.extend("jest-discovery"),ke=class extends mt{constructor(r,o){super(r);this.instances=o}async getFullTestSuite(){if(!this.config.frameworkConfig?.shard)return Pi("Not a sharded run, listing the tests of the results"),mi(this.instances);let{fullTestSuite:r,specsWithoutResults:o}=await Ui(this.config.cliArgs,{detox:this.config.frameworkConfig.originFramework==="detox"});if(o.length===0)return r;for(let{spec:s,message:i}of o)I("Discovery could not load %s: %s",s,Rm(i));let n=ui(r,o,this.instances);return I("The tests of these files are listed from the results of the shard that ran them. Currents can show the run as finished before the other shards upload."),Pi("Files that did not run on this shard: %o",n),r.filter(s=>s.tests.length>0)}};function Rm(t){return t.split(`
28
- `).map(e=>e.trim()).find(e=>e&&!e.startsWith("\u25CF"))??""}var Ni=l(require("fs-extra"));var bi=l(require("path"));function yt(t){return bi.default.join(t,"fullTestSuite.json")}var wm=p.extend("junit-discovery");async function Li(t){console.time(x("@currents/junit:fullTestSuite-ready"));try{wm("running scanner: %o",t);let e=yt(t);process.env.CURRENTS_DISCOVERY_PATH=e;let r=Ni.default.readFileSync(e,"utf-8");return JSON.parse(r)}catch(e){return C("Failed to obtain the junit full test suite:",e),[]}}var je=class extends mt{constructor(e,r){super(e),this.reportDir=r}async getFullTestSuite(){return Li(this.reportDir)}};function vi(t,e,r){switch(t.framework){case"jest":return new ke(t,r);case"junit":return new je(t,e);default:return new mt(t)}}var ut=l(require("fs-extra")),it=l(require("path"));async function Bi(t){let e=await _m(t?.reportDir);return{reportDir:e,configFilePath:t?.configFilePath??it.default.join(e,"config.json")}}async function _m(t){if(t){if(!await ut.default.pathExists(t))throw new Error(`No reports found: the folder "${t}" does not exist.`);return t}let e=(0,it.join)(process.cwd(),".currents"),r=await ut.default.pathExists(e)?await Om(e):null;if(!r)throw new Error(`No reports found: there is no report folder in "${e}". Run the tests with a Currents reporter first, or pass --report-dir with the folder of the reports.`);return r}async function Om(t){let e=await ut.default.readdir(t),r=null;for(let o of e){let n=it.default.join(t,o),s=await ut.default.stat(n);s.isDirectory()&&(!r||s.birthtime>r.birthtime)&&(r={name:o,birthtime:s.birthtime})}return r?(0,it.resolve)(t,r.name):null}async function io(t){try{return await ut.default.pathExists(t)}catch{return C("Error checking if path exists:",C),!1}}async function Fi(t){let e=it.default.join(t,"instances");return xm(e)}async function xm(t){let e=await ut.default.readdir(t),r=[];for(let o of e){let n=it.default.join(t,o);(await ut.default.stat(n)).isFile()&&r.push(n)}return r}var Sm=t=>Buffer.byteLength(JSON.stringify(t),"utf8"),Mi=(t,e=1048576)=>{let r=[],o=[],n=0;for(let s of t){let i=Sm(s);n+i>e&&(r.push(o),o=[],n=0),o.push(s),n+=i}return o.length>0&&r.push(o),r};var Am=3e4;async function co(){let t=Pe();if(!t)throw new Error("Currents config is missing!");let e=await Bi(t);Ho(Um(e.reportDir)),p("Reporter options: %o",e),T("Report directory: %s",e.reportDir);let r=await Et(e.configFilePath);p("Report config: %o",r);let o=await Fi(e.reportDir);p("Found %d instance results in the reportDir: %s",o.length,e.reportDir);let n=Dm(e.reportDir),s=await io(n),i=yt(e.reportDir),c=null;if(s){let D=await Et(n);I("Marker file detected. The report was already uploaded: %o",{runUrl:D.response.runUrl,isoDate:D.isoDate})}let m=[];for(let D of o)m.push(await Et(D));if(c=await Pm(i),c)p("Full test suite file detected: %s",i);else{let W=await vi(r,e.reportDir,m).getFullTestSuite();if(!Gi(W)||Ki(W))throw new Error("Failed to discover the full test suite!");c=W,await It(i,JSON.stringify(c))}let d=c.length===1?c[0].name:null,f={currents:t},u={type:r.framework,version:r.frameworkVersion,clientVersion:At,frameworkConfig:{originFramework:r.frameworkConfig?.originFramework,originFrameworkVersion:r.frameworkConfig?.originFrameworkVersion}},E=fe.userFacingNanoid(),g=rt(t.ciBuildId),A={};for(let D of m)A[D.groupId]||(A[D.groupId]=[]),A[D.groupId].push(D);let Y=await Qs(e.reportDir);if(Y){let D=await ii({instances:Object.values(A).flat(),reportDir:e.reportDir,manifest:Y});T("[currents] Attached %d Detox artifacts and %d steps",D.artifacts,D.steps)}let St=new Map;Object.values(A).forEach(D=>{D.forEach(W=>{W.artifacts?.forEach(G=>{G&&St.set(G.path,G.contentType)}),W.results.tests.forEach(G=>{G.artifacts?.forEach(j=>{j&&St.set(j.path,j.contentType)}),G.attempts.forEach(j=>{j.artifacts?.forEach(ft=>{ft&&St.set(ft.path,ft.contentType)})})})})});for await(let D of Object.keys(A)){let W=A[D],G=D;d&&(p("Default group found: %s, overwriting the group in the results",d),G=d,W=W.map(j=>({...j,groupId:d})));try{let j=Mi(W),ft=await ki({ci:g,group:G,instances:[],fullTestSuite:c,config:f,machineId:E,framework:u});for(let Cr=0;Cr<j.length;Cr++){let Tr=await ki({ci:g,group:G,instances:j[Cr],fullTestSuite:[],config:f,machineId:E,framework:u});Tr.artifactUploadUrls&&Tr.artifactUploadUrls.length>0&&await bm(Tr.artifactUploadUrls,e.reportDir,St)}p("Api response: %o",ft),T("[%s] Run created: %s",G,ft.runUrl);let ap={response:ft,isoDate:new Date().toISOString()};await It(n,JSON.stringify(ap)),p("Marker file %s: %s",s?"overwritten":"created",n)}catch(j){throw p("Failed to upload the results to the dashboard"),j}}}async function ki({ci:t,group:e,instances:r,fullTestSuite:o,config:n,machineId:s,framework:i}){let c=await Ue(),m=await Hs(),d={browserName:"node",browserVersion:$i.default.coerce(process.version)?.version},{currents:f}=n,E={platform:{...d,...m},ci:t,commit:c,group:e,fullTestSuite:o,config:n,projectId:f.projectId,recordKey:f.recordKey,ciBuildId:t.ciBuildId.value??void 0,tags:f.tag??[],machineId:f.machineId??s,framework:i,instances:r,previousCiBuildId:process.env.CURRENTS_PREVIOUS_CI_BUILD_ID};return p("Creating run: %o",h(E)),Dn(E)}function Dm(t){return $e.default.join(t,"upload.marker.json")}function Um(t){return $e.default.join(t,`.debug-${new Date().toISOString()}.log`)}async function Pm(t){if(!await io(t))return null;try{let e=await Et(t);return!Gi(e)||Ki(e)?(I("Ignoring %s, it is not a list of projects and tests",t),null):e}catch(e){return I("Ignoring %s, it is not valid JSON: %s",t,e),null}}function Gi(t){return Array.isArray(t)&&t.every(e=>typeof e?.name=="string"&&Array.isArray(e.tests)&&e.tests.every(r=>typeof r?.spec=="string"&&typeof r.testId=="string"&&Array.isArray(r.title)&&r.title.every(o=>typeof o=="string")))}function Ki(t){return t.length===0||t.some(e=>e.tests.length===0)}async function bm(t,e,r){p("Uploading %d artifacts",t.length),await Promise.all(t.map(o=>{let n=$e.default.join(e,o.path),s=r.get(o.path)||"application/octet-stream";return Nm(n,s,o.uploadUrl)}))}var Nm=async(t,e,r)=>{try{if(!await ao.default.pathExists(t)){I("Artifact file not found: %s",t);return}let o=await ao.default.readFile(t);await ji.default.put(r,o,{headers:{"Content-Type":e},timeout:Am})}catch(o){p("Failed to upload artifact %s: %o",t,o)}};var Lm=p.extend("cli");async function Hi(t,e){await R(async r=>{r.output||Nt(),e.getOptionValueSource("ciBuildId")==="env"&&(r.branch||r.tag)&&(r={...r,ciBuildId:void 0}),on(r);let n=Ie();Lm("Config: %o",h(n)),await Br()},t)}var Z=require("@commander-js/extra-typings");var Yi=require("axios"),Wi=l(require("fs-extra"));var vm=p.extend("api");function Bm(t){if(/^[a-z][a-z0-9+.-]*:\/\//i.test(t))throw new Error(`Pass a path such as /v1/runs/<run-id>, not a URL. The CLI sends requests to ${Wt()}`);let e=t.replace(/^\/+/,""),r=o=>/^(\.|%2e){1,2}$/i.test(o);if(e.split(/[?#]/)[0].split("/").some(r))throw new Error(`The path cannot hold "." or ".." segments: ${t}`);return/^v1(\/|\?|$)/.test(e)?e:`v1/${e}`}function Fm(t){let e=Object.create(null);for(let[r,o]of t)if(r.endsWith("[]")){let n=r.slice(0,-2);e[n]=[...Array.isArray(e[n])?e[n]:[],o]}else e[r]=o;return e}function Mm(t){let e=new URLSearchParams;for(let[r,o]of t)e.append(r,String(o));return e}async function km(t){let e=t==="-"?await new Promise((r,o)=>{let n="";process.stdin.setEncoding("utf8"),process.stdin.on("data",s=>n+=s),process.stdin.on("end",()=>r(n)),process.stdin.on("error",o)}):await Wi.default.readFile(t,"utf8");try{return JSON.parse(e)}catch(r){throw new Error(`--input ${t} is not valid JSON: ${r.message}`)}}async function jm(t,e){let r=[...e.field??[],...e.rawField??[]],o=e.input!==void 0,n=e.method??(o||r.length>0?"POST":"GET"),s=o||n==="GET"||n==="HEAD";return{method:n,url:Bm(t),params:s&&r.length>0?Mm(r):void 0,data:o?JSON.stringify(await km(e.input)):!s&&r.length>0?JSON.stringify(Fm(r)):void 0,headers:Object.fromEntries(e.header??[])}}function Ji(t){let e=Object.entries(t.headers).map(([r,o])=>`${r}: ${Array.isArray(o)?o.join(", "):o}`);return[`HTTP/1.1 ${t.status} ${t.statusText}`,...e,"",""].join(`
29
- `)}function Vi(t,e){let r=t.data??"",o=String(t.headers["content-type"]??"").toLowerCase().includes("json");if(!e||!o||!r)return r;try{return JSON.stringify(JSON.parse(r),null,2)+`
30
- `}catch{return r}}async function qi(t,e){let{apiKey:r}=U(_,["apiKey"],e),o=s=>s?.map(([i])=>i);vm("Options: %o",h({...e,field:o(e.field),rawField:o(e.rawField),header:o(e.header)}));let n=await jm(t,e);try{let s=await Fn(r,n);e.include&&process.stdout.write(Ji(s)),process.stdout.write(Vi(s,!!process.stdout.isTTY))}catch(s){if(!(0,Yi.isAxiosError)(s))throw s;let i=s.response;if(!i)throw new Error(`Could not reach the REST API at ${Wt()}: ${s.message}`);e.include&&process.stderr.write(Ji(i));let c=Vi(i,!!process.stderr.isTTY);throw c&&process.stderr.write(c.endsWith(`
31
- `)?c:`${c}
32
- `),new Error(`${n.method} ${n.url.split("?")[0]} failed: the REST API answered ${i.status} ${i.statusText}`)}}var zi=["GET","POST","PUT","PATCH","DELETE","HEAD"];function po(t,e){let r=t.indexOf(e),o=r<0?"":t.slice(0,r).trim();if(!o)throw new Z.InvalidArgumentError(`Expected key${e}value.`);let n=t.slice(r+1);return[o,e===":"?n.trim():n]}function $m(t){if(t==="true")return!0;if(t==="false")return!1;if(t==="null")return null;if(/^-?\d+(\.\d+)?$/.test(t)){let e=Number(t);if(t.includes(".")?Number.isFinite(e):Number.isSafeInteger(e))return e}return t}var Gm=(t,e=[])=>{let[r,o]=po(t,"=");return[...e,[r,$m(o)]]},Km=(t,e=[])=>[...e,po(t,"=")],Hm=(t,e=[])=>[...e,po(t,":")],Qi=new Z.Option("-X, --method <method>","the HTTP method; GET by default, POST when --field, --raw-field or --input is given").argParser(t=>{let e=t.toUpperCase();if(!zi.includes(e))throw new Z.InvalidArgumentError(`Use one of ${zi.join(", ")}.`);return e}),Xi=new Z.Option("-f, --field <key=value>","a request parameter; repeat for more. Sent in the query string of a GET and in the JSON body otherwise. true, false, null and numbers are sent as JSON values; in a JSON body, key[]=value adds the value to an array").argParser(Gm),Zi=new Z.Option("-F, --raw-field <key=value>","like --field, but the value is always a string").argParser(Km),ta=new Z.Option("--input <file>",'send the JSON in this file as the body, or the JSON from stdin with "-"; fields then go to the query string'),ea=new Z.Option("-H, --header <key:value>","an HTTP header to send; repeat for more").argParser(Hm),ra=new Z.Option("-i, --include","print the HTTP status line and the response headers before the body");async function oa(t,e){await R(async r=>{Nt(),await qi(t,r)},e)}var Rt=require("@commander-js/extra-typings");var mo="(required)",M=(t=mo)=>new Rt.Option("-k, --key <record-key>",`the record key from the Currents dashboard ${t}`).env(_.recordKey.env),at=(t=mo)=>new Rt.Option("--api-key <api-key>",`an API key from the Currents dashboard ${t}`).env(_.apiKey.env),tt=()=>new Rt.Option("-p, --project-id <id>",`the project ID from the Currents dashboard ${mo}`).env(_.projectId.env),vt=t=>new Rt.Option("--ci-build-id <id>",`the CI build ID the run was recorded with${t}`).env(_.ciBuildId.env),Bt=t=>new Rt.Option("-t, --tag <tag>",`${t}; comma-separated or repeated`).argParser(we),b=()=>new Rt.Option("--debug","print debug logs; keys are hidden in them").env(_.debug.env).default(!1);var Ge=require("@commander-js/extra-typings");var na=new Ge.Option("-o, --output <path>","write the JSON to this file instead of stdout").env(L(Ee,"output")),sa=vt("; cannot be combined with --branch or --tag. The environment variable is ignored when --branch or --tag is set"),ia=Bt("find the last run with these tags"),aa=new Ge.Option("-b, --branch <branch>","find the last run of this git branch"),ca=new Ge.Option("--pw-last-run","print only the status and the failed tests of the run, in the format of Playwright's .last-run.json");var Ke="get",uo="run",fo=t=>[{comment:"Get the data of the run recorded under a CI build ID",commands:[`${t} ${uo} ${Ke} --api-key <api-key> --project-id <project-id> --ci-build-id <ci-build-id>`]},{comment:"Get the data of the last run of a branch with the tags tagA and tagB",commands:[`${t} ${uo} ${Ke} --api-key <api-key> --project-id <project-id> --branch <branch> --tag tagA,tagB`]},{comment:'Save the failed tests of a run where Playwright reads them, for "playwright test --last-failed"',commands:[`${t} ${uo} ${Ke} --api-key <api-key> --project-id <project-id> --ci-build-id <ci-build-id> --pw-last-run --output test-results/.last-run.json`]}],Jm=t=>[{comment:"Get a run, with the API key in CURRENTS_API_KEY",commands:[`${t} api /v1/runs/<run-id>`]},{comment:"List the failed runs of the main branch of a project",commands:[`${t} api /v1/projects/<project-id>/runs -X GET -f "branches[]=main" -f status=FAILED -f limit=20`]},{comment:"Cancel a run",commands:[`${t} api /v1/runs/<run-id>/cancel -X PUT`]},{comment:"Create a webhook from the JSON in webhook.json",commands:[`${t} api /v1/webhooks -X POST -F projectId=<project-id> --input webhook.json`]}],pa=t=>new lo.Command().name("api").summary("Make an authenticated request to the Currents REST API").description(`Make an authenticated request to the Currents REST API and print the response body. The path is a REST API route, such as /v1/runs/<run-id>; v1/runs/<run-id> and runs/<run-id> are the same route. A response that is not 2xx prints its body on stderr and exits with 1.
24
+ `)}async function Ui(t,e,r=null){let{matrixIndex:n,matrixTotal:o}=t,s=e.params,i=qt(s.githubRunAttempt,1),a=Ze(r),u=i>1&&a,p=u?"--last-failed":"",l="";o>1&&(l=u?"--shard=1/1":`--shard=${n}/${o}`);let m=[p,l].filter(Boolean).join(" "),h=t.presetOutput??de;await xt(h,m),d('Dumped PW config: "%s" for GHA to %s',m,h)}async function Di(t,e,r=null){let n=e.params,o=r?.ci.params,s=o?.circleWorkflowId,i=o?.circleWorkflowWorkspaceId,a=qt(n.circleNodeIndex,0),u=qt(n.circleNodeTotal,1),p=i==n.circleWorkflowWorkspaceId&&s!==n.circleWorkflowId,l=Ze(r),m=p&&l,h=m?"--last-failed":"",f="";u>1&&(f=m?"--shard=1/1":`--shard=${a+1}/${u}`);let O=[h,f].filter(Boolean).join(" "),j=t.presetOutput??de;await xt(j,O),d('Dumped PW config: "%s" for Circle to %s',O,j)}var qt=(t,e)=>{let r=xn.default.toNumber(t);return xn.default.isNaN(r)?e:r};async function An(){let t=ht();if(t.type!=="GET_COMMAND_CONFIG"||!t.values)throw new Error("Config is missing!");let{recordKey:e,id:r,preset:n,matrixIndex:o,matrixTotal:s,continue:i}=t.values,a=t.values.outputDir,u=ut();Xe(u,r),n==="last-run"&&await Ai(t.values,u);let{cacheId:p,refMetaReadUrl:l}=await Cs({recordKey:e,ci:u,id:r,config:{matrixIndex:o,matrixTotal:s}});try{let m=await Um(l),{readUrl:h}=await Ts({recordKey:e,cacheKey:m.cacheKey}),f=await bm({readUrl:h,outputDir:a});n==="last-run"&&await bi(t.values,u,m),C(b("- restoring cache to"),f),Ne("Cache restored. Cache ID: %s",p)}catch(m){if(L(m)&&(m.response?.status===403||m.response?.status===404)){let h=`Cache with ID "${p}" not found`;if(i){_t(h);return}throw new Error(h)}throw m}}async function bm({readUrl:t,outputDir:e}){let r=await wn(t),n=Pm(e);return await Cn(r,n),d("Cache downloaded",{readUrl:t,destination:n}),n}function Pm(t){let e=t??process.cwd();return Sn.default.isAbsolute(e)?e:Sn.default.resolve(process.cwd(),e)}async function Um(t){let e=await wn(t),r=JSON.parse(e.toString("utf-8"));return d("Meta file downloaded: %O",r),r}var vi=require("lodash");async function bn(){let t=ht();if(t.type!=="SET_COMMAND_CONFIG"||!t.values)throw new Error("Config is missing!");let{recordKey:e,id:r,preset:n,pwOutputDir:o,matrixIndex:s,matrixTotal:i,continue:a}=t.values,u=await Si(t.values.path),p=t.values.path||[],l=ut();if(Xe(l,r),n==="last-run"&&(p.push(o),u.push(...await xi(o))),u.length===0){let j=`No files available to upload: ${p.filter(Boolean).join(",")}`;if(!a)throw new Error(j);_t(j)}let m=await Is({recordKey:e,ci:l,id:r,config:{matrixIndex:s,matrixTotal:i}});d("Cache upload url created",{result:m});let h=Nm(l),f=u.length>0?await ui(u):null,O=[];f&&O.push(Dm({archive:f,cacheId:m.cacheId,uploadUrl:m.uploadUrl}).then(()=>{vm(u),d("Cache archive uploaded",{uploadUrl:m.uploadUrl})})),O.push(Ni({meta:On({cacheId:m.cacheId,config:t.values,ci:h,orgId:m.orgId,path:u}),cacheId:m.cacheId,uploadUrl:m.metaUploadUrl}).then(()=>d("Meta uploaded",{uploadUrl:m.metaUploadUrl})),Ni({meta:On({cacheId:m.cacheId,config:t.values,ci:h,orgId:m.orgId,path:u,cacheKey:m.cacheKey,metaCacheKey:m.metaCacheKey}),cacheId:m.cacheId,uploadUrl:m.refMetaUploadUrl}).then(()=>d("Ref meta uploaded",{uploadUrl:m.refMetaUploadUrl}))),await Promise.all(O),Ne("Cache uploaded. Cache ID: %s",m.cacheId)}async function Dm({archive:t,cacheId:e,uploadUrl:r}){try{let n="application/zip";await Rn({buffer:t,contentType:n,name:e,uploadUrl:r},n,_n(e)),d("Cache archive uploaded",{cacheId:e})}catch(n){throw d("Failed to upload cache archive",n),n}}async function Ni({meta:t,cacheId:e,uploadUrl:r}){try{let n=`${e}_meta`,o="application/json";await Rn({buffer:t,contentType:o,name:n,uploadUrl:r},o,_n(n)),d("Cache meta uploaded",{cacheId:e})}catch(n){throw d("Failed to upload cache meta",n),n}}function Nm(t){return t.ciBuildId.source==="server"||t.ciBuildId.source==="random"?(0,vi.omit)(t,"ciBuildId"):t}function vm(t){C(`Cache upload paths:
25
+ `+t.map(e=>`${b("- uploading")} ${e}`).join(`
26
+ `))}var{recordKey:Lm,projectId:Bm,ciBuildId:Fm,debug:km}=x,nt={recordKey:Lm,projectId:Bm,ciBuildId:Fm,runId:{name:"Run ID",env:"CURRENTS_RUN_ID",cli:"--run-id"},debug:km};var Mm=d.extend("config"),$m=["recordKey","projectId"];function jm(t){if(!(t.runId||t.ciBuildId))throw T(`${He(nt,"runId")} or ${He(nt,"ciBuildId")} is required: pass ${b(je(nt,"runId"))} or ${b(je(nt,"ciBuildId"))}, or set ${b(U(nt,"runId"))} or ${b(U(nt,"ciBuildId"))}`),new Q("Missing required config variable")}var Pn=null;function Li(t){Pn=D(nt,$m,t,jm),Mm("Resolved config: %o",E(Pn))}function tr(){return Pn}async function Un(){let t=tr();if(!t)throw new Error("Config is missing!");let e=t.runId?`runId: ${t.runId}`:`ciBuildId: ${t.ciBuildId}`;try{let r=await ys({recordKey:t.recordKey,projectId:t.projectId,ciBuildId:t.ciBuildId,runId:t.runId});return r.data.runId?C('Run "%s" (%s) is cancelled',r.data.runId,e):C('No run to cancel (%s) in project "%s"',e,t.projectId),r}catch(r){throw d("Failed to cancel the run"),r}}var Bi=require("@currents/commit-info"),Fi=require("lodash");var Hm=d.extend("git"),Gm=async()=>{let t=await(0,Bi.commitInfo)();return Hm("commit: %O",t),{branch:t.branch,remoteOrigin:t.remote,authorEmail:t.email,authorName:t.author,message:t.message,sha:t.sha,ghaEventData:t.ghaEventData??null}},Ee=(0,Fi.memoize)(Gm);var ji=require("child_process"),Nn=g(require("fs/promises")),Hi=require("lodash"),Z=require("os"),Gi=g(require("path")),Km=[["/etc/fedora-release",["Fedora"]],["/etc/redhat-release",["RHEL","RHAS","Red Hat Linux","Scientific Linux","ScientificSL","ScientificCERNSLC","ScientificFermiLTS","ScientificSLF","CentOS"]],["/etc/redhat_version",["RHEL","RHAS","Red Hat Linux","Scientific Linux","ScientificSL","ScientificCERNSLC","ScientificFermiLTS","ScientificSLF"]],["/etc/SuSE-release",["SUSE Linux"]],["/etc/lsb-release",["Ubuntu","Chakra","IYCC","Linux Mint","elementary OS","Arch Linux","Manjaro Linux","KDE neon","Zorin"]],["/etc/debian_version",["Debian"]],["/etc/debian_release",["Debian"]],["/etc/arch-release",["Arch Linux"]],["/etc/NIXOS",["NixOS"]],["/etc/annvix-release",["Annvix"]],["/etc/arklinux-release",["Arklinux"]],["/etc/aurox-release",["Aurox Linux"]],["/etc/blackcat-release",["BlackCat"]],["/etc/cobalt-release",["Cobalt"]],["/etc/conectiva-release",["Conectiva"]],["/etc/eos-version",["FreeEOS"]],["/etc/gentoo-release",["Gentoo Linux"]],["/etc/hlfs-release",["HLFS"]],["/etc/hlfs_version",["HFLS"]],["/etc/immunix-release",["Immunix"]],["/knoppix_version",["Knoppix"]],["/etc/lfs-release",["Linux-From-Scratch"]],["/etc/lfs_version",["Linux-From-Scratch"]],["/etc/linuxppc-release",["Linux-PPC"]],["/etc/mageia-release",["Mageia"]],["/etc/mandriva-release",["Mandriva Linux","Mandrake Linux"]],["/etc/mandakelinux-release",["Mandriva Linux","Mandrake Linux"]],["/etc/mandrake-release",["Mandrake","Mandriva Linux","Mandrake Linux"]],["/etc/mklinux-release",["MkLinux"]],["/etc/nld-release",["Novell Linux Desktop"]],["/etc/pld-release",["PLD Linux"]],["/etc/rubix-version",["Rubix"]],["/etc/slackware-version",["Slackware"]],["/etc/slackware-release",["Slackware"]],["/etc/e-smith-release",["SME Server"]],["/etc/release",["Solaris SPARC"]],["/etc/sun-release",["Sun JDS"]],["/etc/novell-release",["SUSE Linux"]],["/etc/sles-release",["SUSE Linux ES9"]],["/etc/synoinfo.conf",["Synology"]],["/etc/tinysofa-release",["Tiny Sofa"]],["/etc/trustix-release",["Trustix"]],["/etc/trustix-version",["Trustix"]],["/etc/turbolinux-release",["TurboLinux"]],["/etc/ultrapenguin-release",["UltraPenguin"]],["/etc/UnitedLinux-release",["UnitedLinux"]],["/etc/va-release",["VA-Linux/RH-VALE"]],["/etc/yellowdog-release",["Yellow Dog"]],["/etc/alpine-release",["Alpine Linux"]],["/etc/system-release",["Amazon Linux"]],["/etc/os-release",["Raspbian"]]],Yt=/distrib_release=(.*)/,ki=/release ([^ ]+)/,Mi=/(.*)/,Jm={alpine:Mi,amazon:/release (.*)/,arch:Yt,centos:ki,debian:Mi,fedora:/release (..)/,kde:Yt,manjaro:Yt,mint:Yt,raspbian:/VERSION_ID="(.*)"/,red:ki,suse:/VERSION = (.*)\n/,ubuntu:Yt,zorin:Yt};function $i(t){return t.split(" ").map(e=>e.toLowerCase()).find(e=>e!=="linux")}function Dn(t,e){let r=Jm[t];return r?e.match(r)?.[1]:void 0}function Vm(){return new Promise((t,e)=>(0,ji.execFile)("lsb_release",["-a"],(r,n)=>r?e(r):t(n)))}async function qm(t){try{return(await Vm()).match(/Release:\t(.*)/)?.[1]}catch{return Dn("debian",t)}}async function Ym(t){for(let[e,r]of Km){let n=Gi.default.join(t,e);if((await Nn.default.stat(n).catch(()=>null))?.isFile())return{filePath:n,candidates:r}}return null}async function Wm(t="/"){let e=await Ym(t);if(!e)return;let r=await Nn.default.readFile(e.filePath,"utf8"),[n]=e.candidates,o;if(e.candidates.length===1){let s=$i(n);o=s==="debian"?await qm(r):Dn(s,r)}else{let s=r.toLowerCase();for(let i of e.candidates){let a=$i(i);s.includes(a)&&(n=i,o=Dn(a,s)??o)}}return o===void 0?void 0:`${n} - ${o}`}var zm=async()=>{if((0,Z.platform)()==="linux")try{return await Wm()??(0,Z.release)()}catch{return(0,Z.release)()}return(0,Z.release)()},Qm=async()=>{let t=await zm();return{osName:(0,Z.platform)(),osVersion:t,osCpus:[],osMemory:{free:(0,Z.freemem)(),total:(0,Z.totalmem)()}}},Ki=(0,Hi.memoize)(Qm);var Ja=g(require("fs/promises")),mr=g(require("path")),Va=g(require("semver"));var{debug:Xm,ciBuildId:Zm,recordKey:tl,projectId:el,machineId:rl}=x,tt={debug:Xm,ciBuildId:Zm,recordKey:tl,projectId:el,machineId:rl,tag:{...x.tag,env:"CURRENTS_TAG"},disableTitleTags:{name:"Disable title tags",env:"CURRENTS_DISABLE_TITLE_TAGS",cli:"--disable-title-tags"},removeTitleTags:{name:"Remove title tags",env:"CURRENTS_REMOVE_TITLE_TAGS",cli:"--remove-title-tags"},environment:{name:"Environment",env:"CURRENTS_ENVIRONMENT",cli:"--environment"},failOnFailures:{name:"Fail on failures",env:"CURRENTS_FAIL_ON_FAILURES",cli:"--fail-on-failures"},reportDir:{name:"Report folder",env:"CURRENTS_REPORT_DIR",cli:"--report-dir"}};var nl=d.extend("config"),ol=["projectId","recordKey"],vn=null;function Ji(t){vn=D(tt,ol,t),nl("Resolved Currents config: %o",E(vn))}function er(){return vn}function Vi(t){return{ciBuildId:t.ciBuildId,projectId:t.projectId,recordKey:t.key,tag:t.tag,removeTitleTags:t.removeTitleTags,disableTitleTags:t.disableTitleTags,debug:t.debug,machineId:t.machineId,environment:t.environment,reportDir:t.reportDir,failOnFailures:t.failOnFailures}}var B=require("@currents/rules");var rr=d.extend("actions"),sl=512;async function Wi(t,e){try{let r=await bs(t,e);if(!Array.isArray(r))throw new Error("The project actions are not a list");return rr("Fetched %d project actions",r.length),r}catch(r){return I("Failed to fetch the project actions, uploading without them"),rr("Failed to fetch the project actions: %o",r),[]}}function zi({actions:t,instances:e,fullTestSuite:r,gitInfo:n,runTags:o,disableTitleTags:s=!1,group:i}){let a={skipped:0,quarantined:0,tagged:0};if(t.length===0)return a;let u=new B.RulesEvalBase(t,rr);for(let p of e){let l=i??p.groupId;for(let m of p.results.tests){let h=s?[]:ta(r,{groupId:l,spec:p.spec,testId:m.testId})?.test.tags??[],f=u.getMatchedRules(il({groupId:l,spec:p.spec,test:m,gitInfo:n,tags:[...h,...o]}));if(f.length===0)continue;rr("Test %s matched actions: %j",m.testId,f);let O=al(m,f);O.length>0&&(cl(r,{groupId:l,spec:p.spec,testId:m.testId,tags:O}),a.tagged++);let j=qi(f,B.ACTION_TYPE.SKIP),Lt=qi(f,B.ACTION_TYPE.QUARANTINE);j?(Yi(m,j,B.ACTION_ANNOTATIONS.SKIP_POST),a.skipped++):Lt&&m.state==="failed"&&(Yi(m,Lt,B.ACTION_ANNOTATIONS.QUARANTINE_POST),a.quarantined++)}}return a}function Qi(t){t.skipped+t.quarantined+t.tagged!==0&&C("[currents] Actions: %d tests skipped, %d quarantined, %d tagged",t.skipped,t.quarantined,t.tagged)}function il({groupId:t,spec:e,test:r,gitInfo:n,tags:o}){return{title:r.title[r.title.length-1],titlePath:[e,...r.title],file:e,project:t,testId:r.testId,tag:Array.from(new Set([...r.tags??[],...o])),gitInfo:n&&{branch:n.branch,authorName:n.authorName,authorEmail:n.authorEmail,remoteOrigin:n.remoteOrigin,message:n.message},errors:r.attempts.flatMap(s=>s.errors).filter(s=>!!s.message).map(s=>({message:s.message}))}}function qi(t,e){return t.find(r=>r.action.some(n=>n.op===e))}function al(t,e){let r=[];for(let n of e)for(let o of n.action){if(o.op!==B.ACTION_TYPE.TAG)continue;let s=(0,B.normalizeTagMatcherValue)(o.details?.tags??[]);s.length!==0&&(Xi(t,B.ACTION_ANNOTATIONS.TAG,Zi({action:n,type:B.ACTION_TYPE.TAG,testId:t.testId,extraDetails:{tags:s}})),r.push(...(0,B.normalizeTagMatcherValue)(s,{removeAtPrefix:!0})))}return r.length>0&&(t.tags=Array.from(new Set([...t.tags??[],...r]))),r}function Yi(t,e,r){let n=t.state;Xi(t,r,Zi({action:e,type:r===B.ACTION_ANNOTATIONS.SKIP_POST?B.ACTION_TYPE.SKIP:B.ACTION_TYPE.QUARANTINE,testId:t.testId,extraDetails:{status:n}})),t.state="pending"}function Xi(t,e,r){t.annotations=[...t.annotations??[],{type:e,description:JSON.stringify(r),source:"test"}]}function Zi({action:t,type:e,testId:r,extraDetails:n}){return{rule:{v:t.v,id:t._id,name:t.name.slice(0,sl),type:e,extraDetails:n,appliedAt:Date.now()},testInfo:{testId:r,status:n.status}}}function ta(t,{groupId:e,spec:r,testId:n}){let o=t.find(i=>i.name===e),s=o?.tests.find(i=>i.spec===r&&i.testId===n);return o&&s?{project:o,test:s}:null}function cl(t,{groupId:e,spec:r,testId:n,tags:o}){let s=ta(t,{groupId:e,spec:r,testId:n});s&&(s.test.tags=Array.from(new Set([...s.test.tags,...o])))}var da=g(require("fs/promises")),mt=require("path");var ea=g(require("path")),Ln={".png":{type:"screenshot",contentType:"image/png"},".jpg":{type:"screenshot",contentType:"image/jpeg"},".jpeg":{type:"screenshot",contentType:"image/jpeg"},".webp":{type:"screenshot",contentType:"image/webp"},".gif":{type:"screenshot",contentType:"image/gif"},".mp4":{type:"video",contentType:"video/mp4"},".webm":{type:"video",contentType:"video/webm"},".svg":{type:"attachment",contentType:"image/svg+xml"},".log":{type:"attachment",contentType:"text/plain"},".txt":{type:"attachment",contentType:"text/plain"},".yml":{type:"attachment",contentType:"text/plain"},".yaml":{type:"attachment",contentType:"text/plain"},".md":{type:"attachment",contentType:"text/markdown"},".html":{type:"attachment",contentType:"text/html"},".csv":{type:"attachment",contentType:"text/csv"},".json":{type:"attachment",contentType:"application/json"},".pdf":{type:"attachment",contentType:"application/pdf"},".gz":{type:"attachment",contentType:"application/gzip"},".viewhierarchy":{type:"attachment",contentType:"application/xml"}},Bn=t=>Ln[ea.default.extname(t).toLowerCase()];var ra=require("path"),Fn=d.extend("detox"),pl="detox.json";function na(t){return[...t].sort((e,r)=>(e.session??0)-(r.session??0)||e.invocations-r.invocations)}async function oa(t){let e=(0,ra.join)(t,pl);try{let r=await pt(e);if(typeof r?.artifactsRootDir!="string"||!Array.isArray(r?.tests)){Fn("Unexpected Detox manifest contents at %s",e);return}return Fn("Detox manifest: %o",r),r}catch{Fn("No Detox manifest at %s",e);return}}var nr=require("path"),ul=d.extend("detox"),sa=255,dl=/[/\\?<>:*|"$\u0000-\u001f]/g,ia=4;function aa(t){return ml(t)??ll(t)}function ml({rootDir:t,fullName:e,status:r,invocations:n}){try{let o=require.resolve("detox/src/artifacts/utils/ArtifactPathBuilder",{paths:[process.cwd()]}),s=require(o),i=new s({rootDir:t});return(0,nr.dirname)(i.buildPathForTestArtifact("test.mp4",{fullName:e,status:r,invocations:n}))}catch(o){ul("Detox path builder is not available: %o",o);return}}function ll({rootDir:t,fullName:e,status:r,invocations:n}){let o=gl(r),s=n>1?` (${n})`:"",i=e.slice(-sa+o.length+s.length),a=`${o}${i}${s}`.replace(dl,"_");return(0,nr.join)(t,fl(a,sa))}function fl(t,e){let r=Buffer.from(t,"utf8");return r.length<=e?t:r.subarray(0,e).toString("utf8").replace(/\uFFFD$/,"")}function gl(t){switch(t){case"passed":return"\u2713 ";case"failed":return"\u2717 ";default:return""}}var pa=require("path"),ca=d.extend("detox"),or="detox.trace.json",hl="ws-client-invocation";async function ua(t){let e=(0,pa.join)(t,or),r=new Map,n;try{n=await pt(e)}catch{return ca("No Detox trace at %s",e),r}if(!Array.isArray(n))return ca("Unexpected Detox trace contents at %s",e),r;let o=El(n);return Tl(n).forEach(({pid:i,ts:a,step:u})=>{o.filter(l=>l.pid===i&&a>=l.startTs&&a<=l.endTs).sort((l,m)=>l.startTs-m.startTs).pop()?.steps.push(u)}),o.forEach(({fullName:i,invocations:a,steps:u})=>{let p=r.get(i)??[];p.push({fullName:i,invocations:a,steps:u.sort((l,m)=>+new Date(l.startTime)-+new Date(m.startTime))}),r.set(i,p)}),r}function El(t){let e=new Map,r=[];t.forEach(o=>{let s=`${o.pid}:${o.tid}`,i=e.get(s)??[];if(e.set(s,i),o.ph==="B"){i.push(Il(o));return}if(o.ph==="E"){let a=i.pop();a&&r.push({...a,endTs:Number(o.ts)})}});let n=[...e.values()].flatMap(o=>o.filter(s=>s!==void 0));return[...r,...n]}function Il(t){let e=t.args?.fullName;if(!(t.args?.context!=="test"||typeof e!="string"))return{fullName:e,invocations:Number(t.args?.invocations??1),pid:Number(t.pid),startTs:Number(t.ts),endTs:Number.MAX_SAFE_INTEGER,steps:[]}}function Tl(t){let e=new Map,r=[];return t.forEach(n=>{if(!n.cat?.includes(hl))return;let o=`${n.pid}:${n.tid}`,s=e.get(o)??[];if(n.ph==="B"){s.push({name:n.name??"action",cat:n.cat,ts:Number(n.ts)}),e.set(o,s);return}if(n.ph==="E"){let i=s.pop();if(!i)return;r.push({pid:Number(n.pid),ts:i.ts,step:{title:i.name,category:"detox",startTime:new Date(i.ts/1e3).toISOString(),duration:Math.round((Number(n.ts)-i.ts)/1e3),steps:[]}})}}),r}var Ie=d.extend("detox"),ma="artifacts",Cl=[".mp4",".png",".jpg",".log",".txt",".json",".viewhierarchy"],yl=t=>{let e=(0,mt.extname)(t);return Cl.includes(e)?Ln[e]:void 0};async function la({instances:t,reportDir:e,manifest:r}){let n=wl(r),o=await ua(r.artifactsRootDir),s=await At((0,mt.join)(e,ma)),i={artifacts:0,steps:0};for(let a of t)for(let u of a.results.tests){let p=n.get(u.testId);if(!p){Ie("No Detox manifest entry for %s",u.testId);continue}await _l({test:u,manifestTest:p,rootDir:r.artifactsRootDir,artifactsDir:s,traceSlices:o.get(p.fullName)??[],result:i})}return i.artifacts+=await Rl({instances:t,rootDir:r.artifactsRootDir,artifactsDir:s}),i}async function Rl({instances:t,rootDir:e,artifactsDir:r}){if(!await P((0,mt.join)(e,or)))return 0;let[n]=await fa(e,[or],r),o=t.map(s=>s.results.tests[0]).filter(s=>s!==void 0);return o.forEach(s=>{s.artifacts=[...s.artifacts??[],n]}),o.length}function wl(t){let e=new Map;return t.tests.forEach(r=>{e.set(r.fullName,[...e.get(r.fullName)??[],r.testId])}),new Map(t.tests.filter(r=>{let n=e.get(r.fullName)?.length===1;return n||Ie("Ambiguous Detox test name, skipping: %s",r.fullName),n}).map(r=>[r.testId,r]))}async function _l({test:t,manifestTest:e,rootDir:r,artifactsDir:n,traceSlices:o,result:s}){let i=[...t.attempts].sort((p,l)=>p.attempt-l.attempt),a=na(e.attempts),u=1;for(let[p,l]of a.entries()){let m=i[p];if(!m){Ie("No reported attempt %d of %s",p,e.fullName);continue}let h=await Ol({fullName:e.fullName,status:l.status,rootDir:r,artifactsDir:n,fromInvocation:u});h&&(u=h.invocation+1,m.artifacts=[...m.artifacts??[],...h.artifacts],s.artifacts+=h.artifacts.length);let f=Sl(o,p,h?.invocation);f.length&&(m.steps=[...m.steps??[],...f],s.steps+=f.length)}}async function Ol({fullName:t,status:e,rootDir:r,artifactsDir:n,fromInvocation:o}){for(let s=o;s<o+ia;s++){let i=aa({rootDir:r,fullName:t,status:e,invocations:s}),a=await xl(i);if(a)return{invocation:s,artifacts:await fa(i,a,n)}}Ie("No Detox artifacts for %s [%s]",t,e)}async function xl(t){try{return(await da.default.readdir(t)).sort()}catch{return}}async function fa(t,e,r){let n=[];for(let o of e){let s=yl(o);if(!s){Ie("Skipping unsupported Detox artifact %s",o);continue}let i=(0,mt.join)(t,o),a=`${X(i)}${(0,mt.extname)(o)}`;await Fe(i,(0,mt.join)(r,a)),n.push({...s,path:(0,mt.join)(ma,a),name:o})}return n}function Sl(t,e,r){return((r===void 0?void 0:t.find(s=>s.invocations===r))??[...t].sort((s,i)=>s.invocations-i.invocations)[e])?.steps??[]}var Et=class{constructor(e){this.config=e}async getFullTestSuite(){return[]}};var bl=g(require("crypto"));var Al=g(require("path"));async function sr(t){let e=await P(t);if(!e)throw new Error("File does not exist");return e}function ga(){return"root"}function ha(t){let e=(t.join(" ").match(/@(\S+)/g)??[]).filter(Boolean).map(r=>r);return Array.from(new Set([...e].map(r=>r.trim()).map(r=>r.replace("@",""))))}var Pl=/^[0-9a-f]{32}$/;function Ea(t){let e=[];for(let r of t){let n=e.find(o=>o.name===r.groupId);n||(n={name:r.groupId,tags:[],tests:[]},e.push(n)),n.tests.push(...Ta(r))}return e.length===1&&Pl.test(e[0].name)&&(e[0].name=ga()),e}function Ia(t,e,r){let n=[];for(let{projectId:o,spec:s}of e){let i=r.find(u=>u.spec===s&&u.groupId===o)??(t.length===1?r.find(u=>u.spec===s):void 0);if(!i){n.push(s);continue}let a=t.length===1?t[0]:t.find(u=>u.name===o);a||(a={name:o,tags:[],tests:[]},t.push(a)),a.tests.push(...Ta(i))}return n}function Ta(t){return t.results.tests.map(e=>({spec:t.spec,testId:e.testId,title:e.title,tags:e.tags??ha(e.title)}))}var va=g(require("fs"));var Da=require("lodash");function Ca(t){let e=[];for(let[r,n]of Object.entries(t))r==="_"||r==="$0"||r.includes("-")||(typeof n=="boolean"?n&&e.push(`--${r}`):Array.isArray(n)?n.forEach(o=>{e.push(`--${r}=${o}`)}):e.push(`--${r}=${n}`));return e.join(" ")}var ya=require("lodash"),Ul=["bail","clearCache","collectCoverage","collectCoverageFrom","color","colors","config","coverage","coverageDirectory","coveragePathIgnorePatterns","coverageProvider","coverageReporters","coverageThreshold","debug","detectLeaks","detectOpenHandles","errorOnDeprecated","expand","forceExit","json","listTests","logHeapUsage","noStackTrace","notify","notifyMode","openHandlesTimeout","outputFile","reporters","runner","shard","showConfig","showSeed","silent","testFailureExitCode","testNamePattern","verbose","waitNextEventLoopTurnForUnhandledRejectionEvents","watch","watchAll","watchPathIgnorePatterns","watchman"];function Ra(t){return(0,ya.omit)(t,...Ul)}var Pa=g(require("fs")),pr=require("lodash"),Mn=g(require("path"));var kn=g(require("fs")),ir=require("module"),ar=g(require("path")),wa=g(require("semver")),Dl=">=29.5.0";function Nl(){let t=(0,ir.createRequire)(ar.default.join(process.cwd(),"package.json"));if(vl(t)==="jest-cli")return t.resolve("jest-cli");try{return(0,ir.createRequire)(t.resolve("jest")).resolve("jest-cli")}catch{}try{return t.resolve("jest-cli")}catch{throw new Error(`Jest discovery needs the "jest" package, and it is not installed in ${process.cwd()}. Run the command from the folder of the project that ran the tests, or install Jest 29.5 or later: npm install --save-dev jest`)}}function vl(t){for(let e of t.resolve.paths("jest")??[]){if(kn.default.existsSync(ar.default.join(e,"jest","package.json")))return"jest";if(kn.default.existsSync(ar.default.join(e,"jest-cli","package.json")))return"jest-cli"}return null}function _a(){let t=(0,ir.createRequire)(Nl()),{version:e}=t("jest-cli/package.json");if(!wa.default.satisfies(e,Dl,{includePrerelease:!0}))throw new Error(`Jest discovery needs Jest 29.5 or later, and ${process.cwd()} has Jest ${e}. Update Jest: npm install --save-dev jest@latest`);return t}function Oa(){return _a()("jest-cli")}function xa(){return _a()("jest-config")}function cr(t,e){return(...r)=>new Promise((n,o)=>{let s=0,i=()=>{s++;try{let a=t(...r);n(a)}catch(a){if(s>=e.length)o(a);else{let u=e[s-1];setTimeout(i,u)}}};i()})}var Sa=d.extend("jest-discovery");function Aa(t){return["testEnvironment","globalSetup","globalTeardown"].some(e=>String(t[e]??"").includes("detox"))}function ba(t){return{...(0,pr.omit)(t,["globalSetup","globalTeardown","testEnvironmentOptions"]),testEnvironment:"node"}}async function Ua(t,e){let r=e.detox;try{let{readInitialOptions:n}=xa(),{config:o,configPath:s}=await n(t);r||=[o,...o.projects??[]].some(h=>typeof h!="string"&&Aa(h));let i=["collectCoverage","collectCoverageFrom","coverageDirectory","coveragePathIgnorePatterns","coverageProvider","coverageReporters","coverageThreshold","errorOnDeprecated","forceCoverageMatch","notify","notifyMode","openHandlesTimeout","reporters","runner","showSeed","testFailureExitCode","verbose","watchPathIgnorePatterns","watchPlugins","watchman","bail","clearCache","color","colors","debug","detectLeaks","detectOpenHandles","expand","forceExit","json","listTests","logHeapUsage","noStackTrace","outputFile","shard","showConfig","silent","testNamePattern","waitNextEventLoopTurnForUnhandledRejectionEvents","watch","watchAll"],a=["collectCoverageFrom","coverageDirectory","coveragePathIgnorePatterns","detectLeaks","detectOpenHandles","errorOnDeprecated","forceCoverageMatch","openHandlesTimeout","runner","watchPathIgnorePatterns"],u=h=>e.detox||Aa(h),p=(0,pr.omit)(o,i);if(u(p)&&(p=ba(p)),p.projects&&(p.projects=p.projects.map(h=>{if(typeof h=="string")return h;let f=(0,pr.omit)(h,a);return u(f)?ba(f):f})),p.rootDir&&Object.keys(p).length===1)return null;let l=Mn.default.resolve(s?Mn.default.dirname(s):process.cwd(),`.jest-scanner-${new Date().getTime()}.config.cjs`),m=`module.exports=${JSON.stringify(p,null,2)}`;return Sa("configFileContent: %O",m),Pa.default.writeFileSync(l,m),await cr(sr,[200,200,200,200,200,1e3])(l),l}catch(n){if(Sa("error %o",n),r)throw new Error(`Failed to recreate the Jest config for discovery: ${n.message}`);return T("Failed to recreate the config file"),null}}async function Na(t,e){let r="!!##ThisPatternWillNotMatchAnyTestName##!!",n=t.options,o=Ra(n),s=Ca(o),i=n.config,a=await Ua(i,e);return{cliArgs:[s,"--testNamePattern",r,"--reporters",require.resolve("@currents/cmd/discovery/jest"),"--shard=1/1","--testFailureExitCode=0",a?`--config=${a}`:"",...t.args].filter(p=>!(0,Da.isEmpty)(p)),configFilePath:a}}var Ll=d.extend("jest-discovery");async function La(t,e){console.time(b("@currents/jest:fullTestSuite-ready"));let{run:r}=Oa(),{cliArgs:n,configFilePath:o}=await Na(t,e);try{let s=await Be(".json");return Ll("running scanner: %o",n),process.env.CURRENTS_DISCOVERY_PATH=s,await r(n.concat(["--openHandlesTimeout=0"])),await cr(sr,Array.from({length:300},()=>100))(s),console.timeEnd(b("@currents/jest:fullTestSuite-ready")),await Ot(s)}catch(s){return T("Failed to obtain the jest full test suite:",s),{fullTestSuite:[],specsWithoutResults:[]}}finally{o&&va.default.unlinkSync(o)}}var Ba=d.extend("jest-discovery"),ur=class extends Et{constructor(r,n){super(r);this.instances=n}async getFullTestSuite(){if(!this.config.frameworkConfig?.shard)return Ba("Not a sharded run, listing the tests of the results"),Ea(this.instances);let{fullTestSuite:r,specsWithoutResults:n}=await La(this.config.cliArgs,{detox:this.config.frameworkConfig.originFramework==="detox"});if(n.length===0)return r;for(let{spec:s,message:i}of n)I("Discovery could not load %s: %s",s,Bl(i));let o=Ia(r,n,this.instances);return I("The tests of these files are listed from the results of the shard that ran them. Currents can show the run as finished before the other shards upload."),Ba("Files that did not run on this shard: %o",o),r.filter(s=>s.tests.length>0)}};function Bl(t){return t.split(`
27
+ `).map(e=>e.trim()).find(e=>e&&!e.startsWith("\u25CF"))??""}var ka=g(require("fs"));var Fa=g(require("path"));function It(t){return Fa.default.join(t,"fullTestSuite.json")}var Fl=d.extend("junit-discovery");async function Ma(t){console.time(b("@currents/junit:fullTestSuite-ready"));try{Fl("running scanner: %o",t);let e=It(t);process.env.CURRENTS_DISCOVERY_PATH=e;let r=ka.default.readFileSync(e,"utf-8");return JSON.parse(r)}catch(e){return T("Failed to obtain the junit full test suite:",e),[]}}var dr=class extends Et{constructor(e,r){super(e),this.reportDir=r}async getFullTestSuite(){return Ma(this.reportDir)}};function $a(t,e,r){switch(t.framework){case"jest":return new ur(t,r);case"junit":return new dr(t,e);default:return new Et(t)}}var Te=g(require("fs/promises")),lt=g(require("path"));async function ja(t){let e=await kl(t?.reportDir);return{reportDir:e,configFilePath:t?.configFilePath??lt.default.join(e,"config.json")}}async function kl(t){if(t){if(!await P(t))throw new Error(`No reports found: the folder "${t}" does not exist.`);return t}let e=(0,lt.join)(process.cwd(),".currents"),r=await P(e)?await Ml(e):null;if(!r)throw new Error(`No reports found: there is no report folder in "${e}". Run the tests with a Currents reporter first, or pass --report-dir with the folder of the reports.`);return r}async function Ml(t){let e=await Te.default.readdir(t),r=null;for(let n of e){let o=lt.default.join(t,n),s=await Te.default.stat(o);s.isDirectory()&&(!r||s.birthtime>r.birthtime)&&(r={name:n,birthtime:s.birthtime})}return r?(0,lt.resolve)(t,r.name):null}async function $n(t){try{return await P(t)}catch{return T("Error checking if path exists:",T),!1}}async function Ha(t){let e=lt.default.join(t,"instances");return $l(e)}async function $l(t){let e=await Te.default.readdir(t),r=[];for(let n of e){let o=lt.default.join(t,n);(await Te.default.stat(o)).isFile()&&r.push(o)}return r}var jl=t=>Buffer.byteLength(JSON.stringify(t),"utf8"),Ga=(t,e=1048576)=>{let r=[],n=[],o=0;for(let s of t){let i=jl(s);o+i>e&&(r.push(n),n=[],o=0),n.push(s),o+=i}return n.length>0&&r.push(n),r};var Hl=3e4,Gl=Le(64);async function jn(){let t=er();if(!t)throw new Error("Currents config is missing!");let e=await ja(t);Co(Yl(e.reportDir)),d("Reporter options: %o",e),C("Report directory: %s",e.reportDir);let r=await Ot(e.configFilePath);d("Report config: %o",r);let n=await Ha(e.reportDir);d("Found %d instance results in the reportDir: %s",n.length,e.reportDir);let o=ql(e.reportDir),s=await $n(o),i=It(e.reportDir),a=null;if(s){let S=await Ot(o);I("Marker file detected. The report was already uploaded: %o",{runUrl:S.response.runUrl,isoDate:S.isoDate})}let u=[];for(let S of n)u.push(await Ot(S));if(a=await Wl(i),a)d("Full test suite file detected: %s",i);else{let rt=await $a(r,e.reportDir,u).getFullTestSuite();if(!qa(rt)||Ya(rt))throw new Error("Failed to discover the full test suite!");a=rt,await xt(i,JSON.stringify(a))}t.environment&&(a=a.map(S=>({...S,environment:S.environment??t.environment})));let p=a.length===1?a[0].name:null,l={currents:t},m={type:r.framework,version:r.frameworkVersion,clientVersion:Bt,frameworkConfig:{originFramework:r.frameworkConfig?.originFramework,originFrameworkVersion:r.frameworkConfig?.originFrameworkVersion}},h=$e.userFacingNanoid(),f=ut(t.ciBuildId),O={};for(let S of u)O[S.groupId]||(O[S.groupId]=[]),O[S.groupId].push(S);let j=await oa(e.reportDir);if(j){let S=await la({instances:Object.values(O).flat(),reportDir:e.reportDir,manifest:j});C("[currents] Attached %d Detox artifacts and %d steps",S.artifacts,S.steps)}let Lt=await Wi(t.projectId,t.recordKey);Qi(zi({actions:Lt,instances:Object.values(O).flat(),fullTestSuite:a,gitInfo:await Ee(),runTags:t.tag??[],disableTitleTags:t.disableTitleTags,group:p}));let Pe=new Map;Object.values(O).forEach(S=>{S.forEach(rt=>{rt.artifacts?.forEach(z=>{z&&Pe.set(z.path,z.contentType)}),rt.results.tests.forEach(z=>{z.artifacts?.forEach(J=>{J&&Pe.set(J.path,J.contentType)}),z.attempts.forEach(J=>{J.artifacts?.forEach(Rt=>{Rt&&Pe.set(Rt.path,Rt.contentType)})})})})});for await(let S of Object.keys(O)){let rt=O[S],z=S;p&&(d("Default group found: %s, overwriting the group in the results",p),z=p,rt=rt.map(J=>({...J,groupId:p})));try{let J=Ga(rt),Rt=await Ka({ci:f,group:z,instances:[],fullTestSuite:a,config:l,machineId:h,framework:m});for(let Vr=0;Vr<J.length;Vr++){let qr=await Ka({ci:f,group:z,instances:J[Vr],fullTestSuite:[],config:l,machineId:h,framework:m});qr.artifactUploadUrls&&qr.artifactUploadUrls.length>0&&await zl(qr.artifactUploadUrls,e.reportDir,Pe)}d("Api response: %o",Rt),C("[%s] Run created: %s",z,Rt.runUrl);let Ou={response:Rt,isoDate:new Date().toISOString()};await xt(o,JSON.stringify(Ou)),d("Marker file %s: %s",s?"overwritten":"created",o)}catch(J){throw d("Failed to upload the results to the dashboard"),J}}t.failOnFailures&&Jl(u)}var Kl=10;function Jl(t){let e=t.flatMap(o=>o.results.tests.filter(s=>s.state==="failed").map(s=>`${o.spec}: ${Vl(s.title,o.spec)}`));if(e.length===0)return;let r=e.slice(0,Kl),n=e.length-r.length;throw new Error([`${e.length} ${e.length===1?"test":"tests"} failed (--fail-on-failures):`,...r.map(o=>` - ${o}`),...n>0?[` and ${n} more`]:[]].join(`
28
+ `))}function Vl(t,e){return(t[0]===e?t.slice(1):t).join(" > ")}async function Ka({ci:t,group:e,instances:r,fullTestSuite:n,config:o,machineId:s,framework:i}){let a=await Ee(),u=await Ki(),p={browserName:"node",browserVersion:Va.default.coerce(process.version)?.version},{currents:l}=o,h={platform:{...p,...u},ci:t,commit:a,group:e,fullTestSuite:n,config:o,projectId:l.projectId,recordKey:l.recordKey,ciBuildId:t.ciBuildId.value??void 0,tags:l.tag??[],machineId:l.machineId??s,framework:i,instances:r,previousCiBuildId:process.env.CURRENTS_PREVIOUS_CI_BUILD_ID};return d("Creating run: %o",E(h)),Os(h)}function ql(t){return mr.default.join(t,"upload.marker.json")}function Yl(t){return mr.default.join(t,`.debug-${new Date().toISOString()}.log`)}async function Wl(t){if(!await $n(t))return null;try{let e=await Ot(t);return!qa(e)||Ya(e)?(I("Ignoring %s, it is not a list of projects and tests",t),null):e}catch(e){return I("Ignoring %s, it is not valid JSON: %s",t,e),null}}function qa(t){return Array.isArray(t)&&t.every(e=>typeof e?.name=="string"&&Array.isArray(e.tests)&&e.tests.every(r=>typeof r?.spec=="string"&&typeof r.testId=="string"&&Array.isArray(r.title)&&r.title.every(n=>typeof n=="string")))}function Ya(t){return t.length===0||t.some(e=>e.tests.length===0)}async function zl(t,e,r){d("Uploading %d artifacts",t.length),await Promise.all(t.map(n=>{let o=mr.default.join(e,n.path),s=r.get(n.path)||"application/octet-stream";return Gl(()=>Ql(o,s,n.uploadUrl))}))}var Ql=async(t,e,r)=>{try{if(!await P(t)){I("Artifact file not found: %s",t);return}let n=await Ja.default.readFile(t);await bt({method:"PUT",url:r,body:n,headers:{"Content-Type":e},timeout:Hl})}catch(n){d("Failed to upload artifact %s: %o",t,n)}};var Xl=d.extend("cli");async function Wa(t,e){await R(async r=>{r.output||Jt(),e.getOptionValueSource("ciBuildId")==="env"&&(r.branch||r.tag)&&(r={...r,ciBuildId:void 0}),Lo(r);let o=Ke();Xl("Config: %o",E(o)),await gn()},t)}var ot=require("@commander-js/extra-typings");var Xa=g(require("fs/promises"));var Zl=d.extend("api");function tf(t){if(/^[a-z][a-z0-9+.-]*:\/\//i.test(t))throw new Error(`Pass a path such as /v1/runs/<run-id>, not a URL. The CLI sends requests to ${ie()}`);let e=t.replace(/^\/+/,""),r=n=>/^(\.|%2e){1,2}$/i.test(n);if(e.split(/[?#]/)[0].split("/").some(r))throw new Error(`The path cannot hold "." or ".." segments: ${t}`);return/^v1(\/|\?|$)/.test(e)?e:`v1/${e}`}function ef(t){let e=Object.create(null);for(let[r,n]of t)if(r.endsWith("[]")){let o=r.slice(0,-2);e[o]=[...Array.isArray(e[o])?e[o]:[],n]}else e[r]=n;return e}function rf(t){let e=new URLSearchParams;for(let[r,n]of t)e.append(r,String(n));return e}async function nf(t){let e=t==="-"?await new Promise((r,n)=>{let o="";process.stdin.setEncoding("utf8"),process.stdin.on("data",s=>o+=s),process.stdin.on("end",()=>r(o)),process.stdin.on("error",n)}):await Xa.default.readFile(t,"utf8");try{return JSON.parse(e)}catch(r){throw new Error(`--input ${t} is not valid JSON: ${r.message}`)}}async function of(t,e){let r=[...e.field??[],...e.rawField??[]],n=e.input!==void 0,o=e.method??(n||r.length>0?"POST":"GET"),s=n||o==="GET"||o==="HEAD";return{method:o,url:tf(t),params:s&&r.length>0?rf(r):void 0,data:n?JSON.stringify(await nf(e.input)):!s&&r.length>0?JSON.stringify(ef(r)):void 0,headers:Object.fromEntries(e.header??[])}}function za(t){let e=Object.entries(t.headers).map(([r,n])=>`${r}: ${Array.isArray(n)?n.join(", "):n}`);return[`HTTP/1.1 ${t.status} ${t.statusText}`,...e,"",""].join(`
29
+ `)}function Qa(t,e){let r=t.data??"",n=String(t.headers["content-type"]??"").toLowerCase().includes("json");if(!e||!n||!r)return r;try{return JSON.stringify(JSON.parse(r),null,2)+`
30
+ `}catch{return r}}async function Za(t,e){let{apiKey:r}=D(x,["apiKey"],e),n=s=>s?.map(([i])=>i);Zl("Options: %o",E({...e,field:n(e.field),rawField:n(e.rawField),header:n(e.header)}));let o=await of(t,e);try{let s=await As(r,o);e.include&&process.stdout.write(za(s)),process.stdout.write(Qa(s,!!process.stdout.isTTY))}catch(s){if(!L(s))throw s;let i=s.response;if(!i&&rs(s))throw new Error(`The request was not sent: ${s.message}`);if(!i)throw new Error(`Could not reach the REST API at ${ie()}: ${s.message}`);e.include&&process.stderr.write(za(i));let a=Qa(i,!!process.stderr.isTTY);throw a&&process.stderr.write(a.endsWith(`
31
+ `)?a:`${a}
32
+ `),new Error(`${o.method} ${o.url.split("?")[0]} failed: the REST API answered ${i.status} ${i.statusText}`)}}var tc=["GET","POST","PUT","PATCH","DELETE","HEAD"];function Hn(t,e){let r=t.indexOf(e),n=r<0?"":t.slice(0,r).trim();if(!n)throw new ot.InvalidArgumentError(`Expected key${e}value.`);let o=t.slice(r+1);return[n,e===":"?o.trim():o]}function sf(t){if(t==="true")return!0;if(t==="false")return!1;if(t==="null")return null;if(/^-?\d+(\.\d+)?$/.test(t)){let e=Number(t);if(t.includes(".")?Number.isFinite(e):Number.isSafeInteger(e))return e}return t}var af=(t,e=[])=>{let[r,n]=Hn(t,"=");return[...e,[r,sf(n)]]},cf=(t,e=[])=>[...e,Hn(t,"=")],pf=(t,e=[])=>[...e,Hn(t,":")],ec=new ot.Option("-X, --method <method>","the HTTP method; GET by default, POST when --field, --raw-field or --input is given").argParser(t=>{let e=t.toUpperCase();if(!tc.includes(e))throw new ot.InvalidArgumentError(`Use one of ${tc.join(", ")}.`);return e}),rc=new ot.Option("-f, --field <key=value>","a request parameter; repeat for more. Sent in the query string of a GET and in the JSON body otherwise. true, false, null and numbers are sent as JSON values; in a JSON body, key[]=value adds the value to an array").argParser(af),nc=new ot.Option("-F, --raw-field <key=value>","like --field, but the value is always a string").argParser(cf),oc=new ot.Option("--input <file>",'send the JSON in this file as the body, or the JSON from stdin with "-"; fields then go to the query string'),sc=new ot.Option("-H, --header <key:value>","an HTTP header to send; repeat for more").argParser(pf),ic=new ot.Option("-i, --include","print the HTTP status line and the response headers before the body");async function ac(t,e){await R(async r=>{Jt(),await Za(t,r)},e)}var Ut=require("@commander-js/extra-typings");var Gn="(required)",G=(t=Gn)=>new Ut.Option("-k, --key <record-key>",`the record key from the Currents dashboard ${t}`).env(x.recordKey.env),st=(t=Gn)=>new Ut.Option("--api-key <api-key>",`an API key from the Currents dashboard ${t}`).env(x.apiKey.env),it=()=>new Ut.Option("-p, --project-id <id>",`the project ID from the Currents dashboard ${Gn}`).env(x.projectId.env),Wt=t=>new Ut.Option("--ci-build-id <id>",`the CI build ID the run was recorded with${t}`).env(x.ciBuildId.env),zt=t=>new Ut.Option("-t, --tag <tag>",`${t}; comma-separated or repeated`).argParser(Ye),N=()=>new Ut.Option("--debug","print debug logs; keys are hidden in them").env(x.debug.env).default(!1);var lr=require("@commander-js/extra-typings");var cc=new lr.Option("-o, --output <path>","write the JSON to this file instead of stdout").env(U(Ge,"output")),pc=Wt("; cannot be combined with --branch or --tag. The environment variable is ignored when --branch or --tag is set"),uc=zt("find the last run with these tags"),dc=new lr.Option("-b, --branch <branch>","find the last run of this git branch"),mc=new lr.Option("--pw-last-run","print only the status and the failed tests of the run, in the format of Playwright's .last-run.json");var fr="get",Kn="run",Vn=t=>[{comment:"Get the data of the run recorded under a CI build ID",commands:[`${t} ${Kn} ${fr} --api-key <api-key> --project-id <project-id> --ci-build-id <ci-build-id>`]},{comment:"Get the data of the last run of a branch with the tags tagA and tagB",commands:[`${t} ${Kn} ${fr} --api-key <api-key> --project-id <project-id> --branch <branch> --tag tagA,tagB`]},{comment:'Save the failed tests of a run where Playwright reads them, for "playwright test --last-failed"',commands:[`${t} ${Kn} ${fr} --api-key <api-key> --project-id <project-id> --ci-build-id <ci-build-id> --pw-last-run --output test-results/.last-run.json`]}],uf=t=>[{comment:"Get a run, with the API key in CURRENTS_API_KEY",commands:[`${t} api /v1/runs/<run-id>`]},{comment:"List the failed runs of the main branch of a project",commands:[`${t} api /v1/projects/<project-id>/runs -X GET -f "branches[]=main" -f status=FAILED -f limit=20`]},{comment:"Cancel a run",commands:[`${t} api /v1/runs/<run-id>/cancel -X PUT`]},{comment:"Create a webhook from the JSON in webhook.json",commands:[`${t} api /v1/webhooks -X POST -F projectId=<project-id> --input webhook.json`]}],lc=t=>new Jn.Command().name("api").summary("Make an authenticated request to the Currents REST API").description(`Make an authenticated request to the Currents REST API and print the response body. The path is a REST API route, such as /v1/runs/<run-id>; v1/runs/<run-id> and runs/<run-id> are the same route. A response that is not 2xx prints its body on stderr and exits with 1.
33
33
 
34
- The REST API routes: https://docs.currents.dev/resources/api/api-resources`).usage("<path> [options]").argument("<path>","the REST API route, such as /v1/runs/<run-id>").enablePositionalOptions().helpCommand(!1).addOption(at()).addOption(Qi).addOption(Xi).addOption(Zi).addOption(ta).addOption(ea).addOption(ra).addOption(b()).addHelpText("after",y(Jm(t))).showHelpAfterError("(add --help for additional information)").addCommand(go(t).name("get-run"),{hidden:!0}).action((r,o,n)=>r==="help"?n.help():oa(r,o)),go=t=>new lo.Command().name(Ke).summary("Get the data of a run from the Currents API").description("Get the data of a run from the Currents API and print it as JSON, or write it to --output. Find the run by --ci-build-id, or the last run by --branch, --tag or both").addHelpText("after",y(fo(t))).allowUnknownOption().addOption(at()).addOption(b()).addOption(sa).addOption(tt()).addOption(aa).addOption(ia).addOption(na).addOption(ca).action(Hi);var He=require("@commander-js/extra-typings");var Vm=p.extend("cli");async function da(t){await R(async e=>{os(ns(e));let r=dt();Vm("Config: %o",h(r.values)),await qr()},t)}var Ym=p.extend("cli");async function ma(t){await R(async e=>{rs(ss(e));let r=dt();Ym("Config: %o",h(r.values)),await zr()},t)}var Ft="cache",Je=t=>[{comment:"Save files to the cache under an ID",commands:[`${t} ${Ft} set --key <record-key> --id <id> --path <path-1,path-2,...path-n>`]},{comment:"Save Playwright's .last-run.json to the cache",commands:[`${t} ${Ft} set --key <record-key> --preset last-run`]}],Ve=t=>[{comment:"Restore the files saved in the cache under an ID",commands:[`${t} ${Ft} get --key <record-key> --id <id>`]},{comment:"Restore Playwright's .last-run.json from the cache, to rerun only the failed tests",commands:[`${t} ${Ft} get --key <record-key> --preset last-run`]},{comment:"Restore Playwright's .last-run.json to another folder",commands:[`${t} ${Ft} get --key <record-key> --preset last-run --output-dir <output-dir>`]}],ua=t=>new He.Command().command(Ft).summary("Save files to the Currents cache and restore them").description("Save files to the Currents cache and restore them, e.g. in another CI job").addHelpText("after",y([...Je(t),...Ve(t)])).showHelpAfterError("(add --help for additional information)").allowUnknownOption().addCommand(Wm(t)).addCommand(qm(t)),Wm=t=>new He.Command().name("set").description("Save files to the cache").addHelpText("after",y(Je(t))).allowUnknownOption().addOption(M()).addOption(Kn).addOption(Vn).addOption(Jn).addOption(b()).addOption(qn).addOption(Fr).addOption(Mr).addOption(Zn).action(ma),qm=t=>new He.Command().name("get").description("Restore files from the cache").addHelpText("after",y(Ve(t))).allowUnknownOption().addOption(M()).addOption(Hn).addOption(Yn).addOption(Wn).addOption(zn).addOption(b()).addOption(Fr).addOption(Mr).addOption(Xn).action(da);var Ea=require("@commander-js/extra-typings");var zm=p.extend("cli");async function la(t){await R(async({key:e,...r})=>{Ms({...r,recordKey:e});let o=De();zm("Config: %o",h(o??{})),await Xr()},t)}var fa=require("@commander-js/extra-typings");var ga=vt(" (required unless --run-id is set)"),ha=new fa.Option("--run-id <id>","the ID of the run to cancel, as printed when the run was created; wins over --ci-build-id").env(L(X,"runId"));var Mt="cancel",Ye="run",oe=t=>[{comment:"Cancel the run recorded under a CI build ID",commands:[`${t} ${Ye} ${Mt} --key <record-key> --project-id <id> --ci-build-id <build-id>`]},{comment:"Cancel a run by its ID, as printed when the run was created",commands:[`${t} ${Ye} ${Mt} --key <record-key> --project-id <id> --run-id <run-id>`]},{comment:"Cancel the run when a GitHub Actions workflow is cancelled (workflow step). It reads CURRENTS_RECORD_KEY, CURRENTS_PROJECT_ID and CURRENTS_CI_BUILD_ID from the environment",commands:[`- if: \${{ cancelled() }}
35
- run: npx ${t} ${Ye} ${Mt}`]}],We=(t,{deprecated:e=!1}={})=>{let r=new Ea.Command().name(Mt).summary("Cancel a run in progress").description("Cancel a run in progress, e.g. when the CI job it belongs to is cancelled").addHelpText("after",y(oe(t))).allowUnknownOption().addOption(M()).addOption(tt()).addOption(ga).addOption(ha).addOption(b()).action(la);return e&&r.hook("preAction",()=>{process.stderr.write(`'${t} ${Mt}' is deprecated and will be removed in a future version. Use '${t} ${Ye} ${Mt}'.
36
- `)}),r};var ka=require("@commander-js/extra-typings");var Ia={debug:_.debug,inputFormat:{name:"Input format",cli:"--input-format"},inputFiles:{name:"Input file",cli:"--input-file"},outputDir:{name:"Output folder",cli:"--output-dir"},framework:{name:"Framework",cli:"--framework"},frameworkVersion:{name:"Framework version",cli:"--framework-version"}};var Qm=p.extend("config"),Xm=["inputFormat","inputFiles","framework"],ho=null;function Ca(t){ho=U(Ia,Xm,t),Qm("Resolved config: %o",ho)}function qe(){return ho}function Ta(t){return{inputFiles:t.inputFile,inputFormat:t.inputFormat,outputDir:t.outputDir,framework:t.framework,frameworkVersion:t.frameworkVersion,debug:t.debug}}var _o=l(require("fs-extra")),v=require("path");var Oa=require("lodash"),xa=l(require("crypto"));var J=require("path"),Qe=async(t,e,r,o)=>{if(t)for(let n of t)try{let s=(0,J.resolve)(o,n.path),i=(0,J.relative)(o,s);if(i.startsWith("..")||(0,J.isAbsolute)(i)){p("Skipping artifact outside workspace: %s (resolved: %s)",n.path,s);continue}let c=`${et(e+n.path)}.${(0,J.extname)(n.path).slice(1)||"bin"}`;await ue(s,(0,J.join)(r,c)),n.path=(0,J.join)("artifacts",c)}catch(s){p("Failed to copy artifact %s: %o",n.path,s)}};function Ra(t){let e=_a(t.properties?.property??t.property);return ze(e,"currents.artifact.instance.","spec")}function wa(t){let e=_a(t.properties?.property),r=ze(e,"currents.artifact.test.","test"),o=new Map;Zm(e).forEach((i,c)=>{o.has(c)||o.set(c,[]),o.get(c).push(...i)});let s=ze(e,"currents.artifact.attempt.","attempt");return s.length>0&&(o.has(0)||o.set(0,[]),o.get(0).push(...s)),{testArtifacts:r,attemptArtifacts:o}}function Zm(t){let e=new Map,r=/^currents\.artifact\.attempt\.(\d+)\.(.+)$/,o=new Map;for(let n of t){let s=n.value??n._;if(!n.name||!s)continue;let i=n.name.match(r);if(!i)continue;let[,c,m]=i,d=parseInt(c,10);o.has(d)||o.set(d,[]),o.get(d).push({name:`currents.artifact.attempt.${m}`,value:s})}for(let[n,s]of o.entries()){let i=ze(s,"currents.artifact.attempt.","attempt");i.length>0&&e.set(n,i)}return e}function ze(t,e,r){let o=[],n={};for(let s of t){let i=s.value??s._;if(!s.name||!i||!s.name.startsWith(e))continue;let c=s.name.slice(e.length);/^\d+\./.test(c)||["path","type","contentType","name"].includes(c)&&(n[c]&&(ya(n)&&o.push({...n,level:r}),n={}),n[c]=i)}return ya(n)&&o.push({...n,level:r}),o}function ya(t){return!!(t.path&&t.type&&t.contentType)}function _a(t){return t?Array.isArray(t)?t:[t]:[]}function Sa(t,e,r,o){let n=wt(t.failure),s=n.length>0,i=e?.timestamp??"",c="skipped"in t,m=c?"pending":s?"failed":"passed",{testArtifacts:d,attemptArtifacts:f}=wa(t);return{_t:Xe(i),testId:To(ne(t.name,o).join(", "),o),title:ne(t.name,o),state:m,isFlaky:tu(),expectedStatus:"passed",timeout:eu(),location:ru(e?.file??""),retries:ou(n),artifacts:d,attempts:nu(t,n,yo(i),r,f,c)}}function To(t,e){let r=`${t}${e}`;return xa.default.createHash("sha256").update(r).digest("hex").substring(0,16)}function Xe(t){return Aa(t)?new Date(t).getTime():new Date().getTime()}function yo(t){return Aa(t)?new Date(t).toISOString():new Date().toISOString()}function Aa(t){let e=new Date(t);return!isNaN(e.getTime())}function ne(t,e){return[e,t].filter(Boolean)}function tu(){return!1}function eu(){return 0}function ru(t){return{column:1,file:t,line:1}}function ou(t){let e=0;return t.forEach(r=>{typeof r!="string"&&e++}),e}function nu(t,e,r,o,n,s){let i=t.time?Ze(t.time):0;if(s)return[{_s:"pending",attempt:0,startTime:r,steps:[],duration:i,status:"skipped",stdout:Eo(t?.["system-out"]),stderr:Io(t?.["system-err"]),artifacts:n.get(0),errors:[],error:void 0}];if(e.length===0){let c=[];return n.forEach(m=>{c.push(...m)}),[{_s:"passed",attempt:0,startTime:r,steps:[],duration:i,status:"passed",stdout:Eo(t?.["system-out"]),stderr:Io(t?.["system-err"]),artifacts:c,errors:[],error:void 0}]}return e.reduce((c,m,d)=>{if(m!=="true"&&m!=="false"){let f=su(m);c.push({_s:"failed",attempt:d,startTime:iu(o,r),steps:[],duration:i,status:"failed",stdout:Eo(t?.["system-out"]),stderr:Io(t?.["system-err"]),artifacts:n.get(d),errors:f,error:f[0]})}return c},[])}function Eo(t){return t?[t]:[]}function Io(t){return t?[t]:[]}function su(t){return t==="true"||t==="false"?[]:[typeof t=="string"?{message:t}:{message:t.message,stack:t._,value:t.type}]}function iu(t,e){let r=Xe(e)+t;return new Date(r).toISOString()}function wt(t){return t?Array.isArray(t)?t:[t]:[]}function au(t){return Math.round(t*1e3)}function Ze(t){let e=parseFloat(t);return isNaN(e)?0:au(e)}function tr(t,e,r){let o=(0,Oa.isNumber)(r)&&r>0,n=!!t.id&&Co(e,"id",t.id);if(t.file){let s=Co(e,"file",t.file);return s&&!n?`${t.file} - ${t.id}`:s&&o?`${t.file} - ${r}`:t.file}if(t.name){let s=Co(e,"name",t.name);return s&&!n?`${t.name} - ${t.id}`:s&&o?`${t.name} - ${r}`:t.name}return t.id?n&&o?`${t.id} - ${r}`:t.id:o?`unknown - ${r}`:"unknown"}function Co(t,e,r){return t.filter(n=>n[e]===r).length>1}function Da(t){let e=[];return t.forEach(r=>{let o=wt(r.testsuites?.testsuite),n={name:r.testsuites?.name??"No name",tags:[],tests:[]};o?.forEach(s=>{let i=tr(s,o);wt(s?.testcase)?.forEach(m=>{let d={title:ne(m.name,i),spec:i,tags:[],testId:To(ne(m.name,i).join(", "),i)};n.tests.push(d)})}),e.push(n)}),e}var lt=require("@commander-js/extra-typings"),Ua=l(require("globby")),Ro=(e=>(e.junit="junit",e))(Ro||{}),er=t=>new lt.Option("--input-format <format>",["the format of the reports to convert",t].filter(Boolean).join(" ")).choices(Object.values(Ro)),rr=t=>new lt.Option("--input-file <patterns>",`comma-separated glob patterns of the report files, e.g. "reports/*.xml,other.xml"; quote them so that the shell does not expand them ${t}`).argParser(cu),or=new lt.Option("-o, --output-dir <folder>","the folder to save the converted reports to; it must be empty, not exist, or hold only the reports being converted"),wo=(n=>(n.postman="postman",n.node="node",n.vitest="vitest",n.wdio="wdio",n))(wo||{}),nr=t=>new lt.Option("--framework <framework>",`the test framework that wrote the reports ${t}`).choices(Object.values(wo)),sr=new lt.Option("--framework-version <version>","the version of the test framework that wrote the reports");function cu(t){let e=t.split(",").map(o=>o.trim()),r=Ua.sync(e);if(r.length===0)throw new lt.InvalidArgumentError("No files found with the provided patterns");return r}async function V(t){let e=new Map;return t.forEach(r=>{let o=wt(r.testsuites?.testsuite),n=r.testsuites?.name??"No name";o.forEach((s,i)=>{let c=tr(s,o,i),m=pu(s,n,c),d=et(n+c);m.results.tests.length!==0&&e.set(d,m)})}),e}function pu(t,e,r){let o=yo(t.timestamp??""),n=t.time?Ze(t.time):0,s=new Date(Xe(t.timestamp??"")+n),i=wt(t.testcase),c=[t["system-out"],t["system-err"],...i.flatMap(g=>[g["system-out"],g["system-err"]])].filter(g=>g).join(`
37
- `),m=0,d=i.filter(g=>"failure"in g).length,f=i.filter(g=>"skipped"in g).length,u=i.length-d-f;return{groupId:e,spec:r,startTime:o,artifacts:Ra(t),_stdout:c,results:{stats:{suites:1,tests:i.length,passes:u,pending:f,skipped:0,failures:d,flaky:0,wallClockStartedAt:o,wallClockEndedAt:s.toISOString(),wallClockDuration:n},tests:i?.map(g=>(i[0]?.time&&(m+=Ze(i[0].time)),Sa(g,t,m,r)))}}}async function Pa({inputFormat:t,framework:e,parsedXMLArray:r}){return t==="junit"?du(e,r):new Map}async function du(t,e){switch(t){case"node":return V(e);case"postman":return V(e);case"vitest":return V(e);case"wdio":return V(e);default:return I("Unsupported framework: %s",t),new Map}}var ba=require("fs-extra"),Na=require("xml2js");async function La(t){let e=await Promise.all(t.map(o=>(0,ba.readFile)(o,"utf-8"))),r=(await Promise.all(e.map(mu))).filter(Boolean);return e.length!==r.length&&I("Some files could not be parsed. Enable debug logging for more details"),r}async function mu(t){let e=t.trim();if(!e)return null;try{return await(0,Na.parseStringPromise)(e,{explicitArray:!1,mergeAttrs:!0})||null}catch(r){return p("Error parsing XML input",r),null}}function va(t){return{framework:t.inputFormat,frameworkVersion:t.frameworkVersion??null,frameworkConfig:{originFramework:t.framework,originFrameworkVersion:t.frameworkVersion}}}async function Ba(){try{let t=qe();if(!t)throw new Error("Config is missing!");t.outputDir&&await uu(t.outputDir,t.inputFiles);let e=t.outputDir?await Ct(t.outputDir):await Zo(process.cwd(),".currents"),r=await Ct((0,v.join)(e,"instances")),o=va(t);p("Report config:",o),T("[currents] Convertion files: %s",t.inputFiles.join(", ")),await Yt((0,v.join)(e,"config.json"),JSON.stringify(o));let n=await La(t.inputFiles);if(n.length===0)throw new Error("No valid XML JUnit report was found.");let s=Da(n);await Yt(yt(e),JSON.stringify(s));let i=await Pa({inputFormat:t.inputFormat,framework:t.framework,parsedXMLArray:n}),c=await Ct((0,v.join)(e,"artifacts")),m=process.cwd();return await Promise.all(Array.from(i.values()).map(async d=>{if(await Qe(d.artifacts,d.spec,c,m),d._stdout){let f=`${et(d.spec)}.stdout.txt`;await Yt((0,v.join)(c,f),d._stdout),d.artifacts||(d.artifacts=[]),d.artifacts.push({path:(0,v.join)("artifacts",f),type:"stdout",contentType:"text/plain",level:"spec"}),delete d._stdout}for(let f of d.results.tests){await Qe(f.artifacts,f.testId,c,m);for(let u of f.attempts)await Qe(u.artifacts,f.testId+u.attempt,c,m)}})),await Promise.all(Array.from(i.entries()).map(([d,f])=>Yt((0,v.join)(r,`${et(d)}.json`),JSON.stringify(f)))),T("[currents] Conversion completed, report saved to: %s",e),e}catch(t){throw p("Failed to convert: %o",t),t}}async function uu(t,e){let r=(0,v.resolve)(t),o=new Set(e.map(c=>(0,v.resolve)(c))),n=[(0,v.join)(r,"config.json"),yt(r),(0,v.join)(r,"instances"),(0,v.join)(r,"artifacts")],s=[...o].find(c=>n.some(m=>c===m||c.startsWith(m+v.sep)));if(s)throw new Error(`The report "${s}" is where the conversion writes its own files. Move the reports out of "${t}", or leave out --output-dir to convert into a new folder in .currents.`);if(await _o.default.pathExists(r)?await Fa(r,o):void 0)throw new Error(`The folder "${t}" is not empty. Reports already in it would be uploaded with the converted ones. Remove the folder, or leave out --output-dir to convert into a new folder in .currents.`)}async function Fa(t,e){for(let r of await _o.default.readdir(t,{withFileTypes:!0})){let o=(0,v.join)(t,r.name),n=r.isDirectory()?await Fa(o,e):e.has(o)?void 0:o;if(n)return n}}var lu=p.extend("cli");async function Oo(t){return Ca(Ta(t)),lu("Config: %o",qe()),Ba()}async function Ma(t){await R(async e=>{await Oo(e)},t)}var xo="convert",fu=t=>[{comment:"Convert JUnit test reports to the Currents format, to check the result before an upload",commands:[`${t} ${xo} --input-format junit --input-file "./*.xml" --framework postman`]}],ja=t=>new ka.Command().name(xo).command(xo).showHelpAfterError("(add --help for additional information)").allowUnknownOption().summary("Convert JUnit XML reports to the Currents format").description("Convert JUnit XML reports to the Currents format, without uploading them. The converted reports are saved to --output-dir or a new folder in .currents").addHelpText("after",y(fu(t))).addOption(b()).addOption(er("(required)")).addOption(rr("(required)")).addOption(or).addOption(nr("(required)")).addOption(sr).action(r=>Ma(r));var Ka=require("@commander-js/extra-typings");var So=l(require("fs-extra")),ir=l(require("path"));function gu(t=__dirname){let e=le("package.json",t);if(!e)throw new Error("The docs folder is missing from this package");return ir.default.join(e,"docs")}function hu(t,e){let r=e.match(/^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n)+/),o=r?.[1].match(/^description:[ \t]*(.+?)\r?$/m)?.[1];if(!r||!o)throw new Error(`docs/${t}.md has no description in its front matter`);return{name:t,description:o,body:e.slice(r[0].length)}}async function Eu(t=gu()){let e=(await So.default.readdir(t)).filter(r=>r.endsWith(".md")).sort();return Promise.all(e.map(async r=>hu(ir.default.basename(r,".md"),await So.default.readFile(ir.default.join(t,r),"utf8"))))}function $a(t){let e=Math.max(...t.map(r=>r.name.length));return t.map(r=>` ${r.name.padEnd(e)} ${r.description}
38
- `).join("")}async function Ga(t,e){let r=await Eu();if(!e){await Qt(`Topics:
39
- ${$a(r)}
34
+ The REST API routes: https://docs.currents.dev/resources/api/api-resources`).usage("<path> [options]").argument("<path>","the REST API route, such as /v1/runs/<run-id>").enablePositionalOptions().helpCommand(!1).addOption(st()).addOption(ec).addOption(rc).addOption(nc).addOption(oc).addOption(sc).addOption(ic).addOption(N()).addHelpText("after",y(uf(t))).showHelpAfterError("(add --help for additional information)").addCommand(qn(t).name("get-run"),{hidden:!0}).action((r,n,o)=>r==="help"?o.help():ac(r,n)),qn=t=>new Jn.Command().name(fr).summary("Get the data of a run from the Currents API").description("Get the data of a run from the Currents API and print it as JSON, or write it to --output. Find the run by --ci-build-id, or the last run by --branch, --tag or both").addHelpText("after",y(Vn(t))).allowUnknownOption().addOption(st()).addOption(N()).addOption(pc).addOption(it()).addOption(dc).addOption(uc).addOption(cc).addOption(mc).action(Wa);var gr=require("@commander-js/extra-typings");var df=d.extend("cli");async function fc(t){await R(async e=>{ti(ei(e));let r=ht();df("Config: %o",E(r.values)),await An()},t)}var mf=d.extend("cli");async function gc(t){await R(async e=>{Zs(ri(e));let r=ht();mf("Config: %o",E(r.values)),await bn()},t)}var Qt="cache",hr=t=>[{comment:"Save files to the cache under an ID",commands:[`${t} ${Qt} set --key <record-key> --id <id> --path <path-1,path-2,...path-n>`]},{comment:"Save Playwright's .last-run.json to the cache",commands:[`${t} ${Qt} set --key <record-key> --preset last-run`]}],Er=t=>[{comment:"Restore the files saved in the cache under an ID",commands:[`${t} ${Qt} get --key <record-key> --id <id>`]},{comment:"Restore Playwright's .last-run.json from the cache, to rerun only the failed tests",commands:[`${t} ${Qt} get --key <record-key> --preset last-run`]},{comment:"Restore Playwright's .last-run.json to another folder",commands:[`${t} ${Qt} get --key <record-key> --preset last-run --output-dir <output-dir>`]}],hc=t=>new gr.Command().command(Qt).summary("Save files to the Currents cache and restore them").description("Save files to the Currents cache and restore them, e.g. in another CI job").addHelpText("after",y([...hr(t),...Er(t)])).showHelpAfterError("(add --help for additional information)").allowUnknownOption().addCommand(lf(t)).addCommand(ff(t)),lf=t=>new gr.Command().name("set").description("Save files to the cache").addHelpText("after",y(hr(t))).allowUnknownOption().addOption(G()).addOption($s).addOption(Gs).addOption(Hs).addOption(N()).addOption(Vs).addOption(hn).addOption(En).addOption(zs).action(gc),ff=t=>new gr.Command().name("get").description("Restore files from the cache").addHelpText("after",y(Er(t))).allowUnknownOption().addOption(G()).addOption(js).addOption(Ks).addOption(Js).addOption(qs).addOption(N()).addOption(hn).addOption(En).addOption(Ws).action(fc);var yc=require("@commander-js/extra-typings");var gf=d.extend("cli");async function Ec(t){await R(async({key:e,...r})=>{Li({...r,recordKey:e});let n=tr();gf("Config: %o",E(n??{})),await Un()},t)}var Ic=require("@commander-js/extra-typings");var Tc=Wt(" (required unless --run-id is set)"),Cc=new Ic.Option("--run-id <id>","the ID of the run to cancel, as printed when the run was created; wins over --ci-build-id").env(U(nt,"runId"));var Xt="cancel",Ir="run",Ce=t=>[{comment:"Cancel the run recorded under a CI build ID",commands:[`${t} ${Ir} ${Xt} --key <record-key> --project-id <id> --ci-build-id <build-id>`]},{comment:"Cancel a run by its ID, as printed when the run was created",commands:[`${t} ${Ir} ${Xt} --key <record-key> --project-id <id> --run-id <run-id>`]},{comment:"Cancel the run when a GitHub Actions workflow is cancelled (workflow step). It reads CURRENTS_RECORD_KEY, CURRENTS_PROJECT_ID and CURRENTS_CI_BUILD_ID from the environment",commands:[`- if: \${{ cancelled() }}
35
+ run: npx ${t} ${Ir} ${Xt}`]}],Tr=(t,{deprecated:e=!1}={})=>{let r=new yc.Command().name(Xt).summary("Cancel a run in progress").description("Cancel a run in progress, e.g. when the CI job it belongs to is cancelled").addHelpText("after",y(Ce(t))).allowUnknownOption().addOption(G()).addOption(it()).addOption(Tc).addOption(Cc).addOption(N()).action(Ec);return e&&r.hook("preAction",()=>{process.stderr.write(`'${t} ${Xt}' is deprecated and will be removed in a future version. Use '${t} ${Ir} ${Xt}'.
36
+ `)}),r};var Vc=require("@commander-js/extra-typings");var Tt=require("@commander-js/extra-typings");var ye=(r=>(r.junit="junit",r.cypressJson="cypress-json",r))(ye||{}),Cr=t=>new Tt.Option("--input-format <format>",["the format of the reports to convert",t].filter(Boolean).join(" ")).choices(Object.values(ye)),yr=t=>new Tt.Option("--input-file <patterns>",`comma-separated glob patterns of the report files, e.g. "reports/*.xml,other.xml"; quote them so that the shell does not expand them ${t}`).argParser(hf),Rr=new Tt.Option("-o, --output-dir <folder>","the folder to save the converted reports to; it must be empty, not exist, or hold only the reports being converted"),Re=(s=>(s.cypress="cypress",s.postman="postman",s.node="node",s.vitest="vitest",s.wdio="wdio",s))(Re||{}),wr=t=>new Tt.Option("--framework <framework>",`the test framework that wrote the reports ${t}`).choices(Object.values(Re)),_r=new Tt.Option("--framework-version <version>","the version of the test framework that wrote the reports");function hf(t){let e=t.split(",").map(n=>n.trim()),r=he(e);if(r.length===0)throw new Tt.InvalidArgumentError("No files found with the provided patterns");return r}var Rc={debug:x.debug,inputFormat:{name:"Input format",cli:"--input-format"},inputFiles:{name:"Input file",cli:"--input-file"},outputDir:{name:"Output folder",cli:"--output-dir"},framework:{name:"Framework",cli:"--framework"},frameworkVersion:{name:"Framework version",cli:"--framework-version"}};var Ef=d.extend("config"),If=["inputFormat","inputFiles","framework"],Yn=null;function wc(t){Yn=D(Rc,If,{...t,framework:t?.framework??(t?.inputFormat==="cypress-json"?"cypress":void 0)}),Ef("Resolved config: %o",Yn)}function Or(){return Yn}function _c(t){return{inputFiles:t.inputFile,inputFormat:t.inputFormat,outputDir:t.outputDir,framework:t.framework,frameworkVersion:t.frameworkVersion,debug:t.debug}}var Hc=g(require("fs/promises")),F=require("path");var bc=require("lodash"),Pc=g(require("crypto"));var et=require("path"),Sr=async(t,e,r,n)=>{if(t)for(let o of t)try{let s=(0,et.resolve)(n,o.path),i=(0,et.relative)(n,s);if(i.startsWith("..")||(0,et.isAbsolute)(i)){d("Skipping artifact outside workspace: %s (resolved: %s)",o.path,s);continue}let a=`${X(e+o.path)}.${(0,et.extname)(o.path).slice(1)||"bin"}`;await Fe(s,(0,et.join)(r,a)),o.path=(0,et.join)("artifacts",a)}catch(s){d("Failed to copy artifact %s: %o",o.path,s)}};function xc(t){let e=Ac(t.properties?.property??t.property);return xr(e,"currents.artifact.instance.","spec")}function Sc(t){let e=Ac(t.properties?.property),r=xr(e,"currents.artifact.test.","test"),n=new Map;Tf(e).forEach((i,a)=>{n.has(a)||n.set(a,[]),n.get(a).push(...i)});let s=xr(e,"currents.artifact.attempt.","attempt");return s.length>0&&(n.has(0)||n.set(0,[]),n.get(0).push(...s)),{testArtifacts:r,attemptArtifacts:n}}function Tf(t){let e=new Map,r=/^currents\.artifact\.attempt\.(\d+)\.(.+)$/,n=new Map;for(let o of t){let s=o.value??o._;if(!o.name||!s)continue;let i=o.name.match(r);if(!i)continue;let[,a,u]=i,p=parseInt(a,10);n.has(p)||n.set(p,[]),n.get(p).push({name:`currents.artifact.attempt.${u}`,value:s})}for(let[o,s]of n.entries()){let i=xr(s,"currents.artifact.attempt.","attempt");i.length>0&&e.set(o,i)}return e}function xr(t,e,r){let n=[],o={};for(let s of t){let i=s.value??s._;if(!s.name||!i||!s.name.startsWith(e))continue;let a=s.name.slice(e.length);/^\d+\./.test(a)||["path","type","contentType","name"].includes(a)&&(o[a]&&(Oc(o)&&n.push({...o,level:r}),o={}),o[a]=i)}return Oc(o)&&n.push({...o,level:r}),n}function Oc(t){return!!(t.path&&t.type&&t.contentType)}function Ac(t){return t?Array.isArray(t)?t:[t]:[]}function Uc(t,e,r,n){let o=at(t.failure),s=o.length>0,i=e?.timestamp??"",a="skipped"in t,u=a?"pending":s?"failed":"passed",{testArtifacts:p,attemptArtifacts:l}=Sc(t);return{_t:Pr(i),testId:Ar(we(t.name,n).join(", "),n),title:we(t.name,n),state:u,isFlaky:Cf(),expectedStatus:"passed",timeout:yf(),location:Rf(e?.file??""),retries:wf(o),artifacts:p,attempts:_f(t,o,Xn(i),r,l,a)}}function Ar(t,e){let r=`${t}${e}`;return Pc.default.createHash("sha256").update(r).digest("hex").substring(0,16)}function br(t,e){let r=t.slice(0,-1).join(" "),n=t[t.length-1];return Ar([r,n].filter(Boolean).join(", "),e)}function Pr(t){return Dc(t)?new Date(t).getTime():new Date().getTime()}function Xn(t){return Dc(t)?new Date(t).toISOString():new Date().toISOString()}function Dc(t){let e=new Date(t);return!isNaN(e.getTime())}function we(t,e){return[e,t].filter(Boolean)}function Cf(){return!1}function yf(){return 0}function Rf(t){return{column:1,file:t,line:1}}function wf(t){let e=0;return t.forEach(r=>{typeof r!="string"&&e++}),e}function _f(t,e,r,n,o,s){let i=t.time?Ur(t.time):0,a=Array.from(o.values()).flat();return s?[{_s:"pending",attempt:0,startTime:r,steps:[],duration:i,status:"skipped",stdout:Wn(t?.["system-out"]),stderr:zn(t?.["system-err"]),artifacts:a,errors:[],error:void 0}]:e.length===0?[{_s:"passed",attempt:0,startTime:r,steps:[],duration:i,status:"passed",stdout:Wn(t?.["system-out"]),stderr:zn(t?.["system-err"]),artifacts:a,errors:[],error:void 0}]:e.reduce((u,p,l)=>{if(p!=="true"&&p!=="false"){let m=Of(p);u.push({_s:"failed",attempt:l,startTime:xf(n,r),steps:[],duration:i,status:"failed",stdout:Wn(t?.["system-out"]),stderr:zn(t?.["system-err"]),artifacts:o.get(l),errors:m,error:m[0]})}return u},[])}function Wn(t){return t?[t]:[]}function zn(t){return t?[t]:[]}function Of(t){return t==="true"||t==="false"?[]:[typeof t=="string"?{message:t}:{message:t.message,stack:t._,value:t.type}]}function xf(t,e){let r=Pr(e)+t;return new Date(r).toISOString()}function at(t){return t?Array.isArray(t)?t:[t]:[]}function Sf(t){return Math.round(t*1e3)}function Ur(t){let e=parseFloat(t);return isNaN(e)?0:Sf(e)}function Dr(t,e,r){let n=(0,bc.isNumber)(r)&&r>0,o=!!t.id&&Qn(e,"id",t.id);if(t.file){let s=Qn(e,"file",t.file);return s&&!o?`${t.file} - ${t.id}`:s&&n?`${t.file} - ${r}`:t.file}if(t.name){let s=Qn(e,"name",t.name);return s&&!o?`${t.name} - ${t.id}`:s&&n?`${t.name} - ${r}`:t.name}return t.id?o&&n?`${t.id} - ${r}`:t.id:n?`unknown - ${r}`:"unknown"}function Qn(t,e,r){return t.filter(o=>o[e]===r).length>1}function Nc(t){let e=[];return t.forEach(r=>{let n=at(r.testsuites?.testsuite),o={name:r.testsuites?.name??"No name",tags:[],tests:[]};n?.forEach(s=>{let i=Dr(s,n);at(s?.testcase)?.forEach(u=>{let p={title:we(u.name,i),spec:i,tags:[],testId:Ar(we(u.name,i).join(", "),i)};o.tests.push(p)})}),e.push(o)}),e}function Zn(t){let e=new Map;return t.forEach(({groupId:r,spec:n,results:o})=>{let s=e.get(r)??{name:r,tags:[],tests:[]};e.set(r,s),o.tests.forEach(({title:i,testId:a})=>{s.tests.push({title:i,spec:n,tags:[],testId:a})})}),Array.from(e.values())}var Zt=require("path");async function Lc(t){return Promise.all(t.map(async e=>{let r=await ct(()=>pt(e));if(!Array.isArray(r?.runs))throw new Error(`${e} is not a Cypress run result: it has no "runs" list. Save the results of the "after:run" event or of cypress.run().`);return r}))}function Bc(t){let e=new Map;for(let r of t)for(let n of r.runs){if(n.tests.length===0){n.error&&I("Skipping %s, Cypress could not load it and it has no test results: %s",n.spec.relative,Uf(n.error));continue}let o=Af(n,r.browserName),s=`${o.groupId}${o.spec}`;if(e.has(s))throw new Error(`The results have ${o.spec} in ${o.groupId} more than once. Upload the results of each spec file once: split the spec files between the machines, or upload the files of each run with its own --ci-build-id.`);e.set(s,o)}return e}function Af(t,e){let r=t.spec.relative,n=t.spec.absolute.slice(0,-r.length),o=p=>(0,Zt.relative)(n,p),s=t.screenshots.map(p=>({...p,path:o(p.path)})),i=[],a=new Date(t.stats.startedAt).getTime(),u=t.tests.map(p=>{let l=bf(p,r,a);return a+=p.duration,l});for(let p of s){let l={path:p.path,type:"screenshot",contentType:"image/png",name:(0,Zt.basename)(p.path)},m=Pf(p.path,t.tests),h=m&&u[m.testIndex].attempts[m.attempt];h?h.artifacts=[...h.artifacts??[],l]:i.push(l)}if(t.video){let p={path:o(t.video),type:"video",contentType:"video/mp4",name:(0,Zt.basename)(t.video)},l=u.flatMap(m=>m.attempts).filter(m=>m.status==="failed");for(let m of l)m.artifacts=[...m.artifacts??[],{...p}];l.length===0&&i.push(p)}return{groupId:e,spec:r,startTime:t.stats.startedAt,artifacts:i,results:{stats:{suites:t.stats.suites,tests:t.stats.tests,passes:t.stats.passes,pending:t.stats.pending,skipped:t.stats.skipped,failures:t.stats.failures,flaky:u.filter(p=>p.isFlaky).length,wallClockStartedAt:t.stats.startedAt,wallClockEndedAt:t.stats.endedAt,wallClockDuration:t.stats.duration},tests:u}}}function bf(t,e,r){let n=Math.round(t.duration/t.attempts.length),o=t.attempts.map(i=>i.state).lastIndexOf("failed"),s=t.attempts.map((i,a)=>{let u=a===o&&t.displayError?[Df(t.displayError)]:[];return{_s:vc(i.state),attempt:a,startTime:new Date(r+a*n).toISOString(),steps:[],duration:n,status:Nf(i.state),artifacts:[],errors:u,error:u[0]}});return{_t:r,testId:br(t.title,e),title:t.title,state:vc(t.state),isFlaky:t.state==="passed"&&t.attempts.some(i=>i.state==="failed"),retries:t.attempts.length-1,expectedStatus:"passed",timeout:0,location:{file:e,line:1,column:1},artifacts:[],attempts:s}}function Pf(t,e){let r=(0,Zt.basename)(t,".png").match(/^(.*?)(?: \(failed\))?(?: \(attempt (\d+)\))?$/);if(!r)return null;let[,n,o]=r,s=e.findIndex(i=>i.title.join(" -- ")===n);return s===-1?null:{testIndex:s,attempt:o?Number(o)-1:0}}function Uf(t){let e=t.split(`
37
+ `).map(r=>r.trim());return e.find(r=>/^\w*Error\b/.test(r))??e[0]}function Df(t){let[e]=t.split(`
38
+ `),r=e.match(/^(\w*Error): (.*)$/);return{message:r?r[2]:e,value:r?.[1],stack:t}}function vc(t){return t==="passed"||t==="failed"?t:"pending"}function Nf(t){return t==="passed"||t==="failed"?t:"skipped"}async function K(t){let e=new Map;return t.forEach(r=>{let n=at(r.testsuites?.testsuite),o=r.testsuites?.name??"No name";n.forEach((s,i)=>{let a=Dr(s,n,i),u=to(s,o,a),p=X(o+a);u.results.tests.length!==0&&e.set(p,u)})}),e}function to(t,e,r){let n=Xn(t.timestamp??""),o=t.time?Ur(t.time):0,s=new Date(Pr(t.timestamp??"")+o),i=at(t.testcase),a=[t["system-out"],t["system-err"],...i.flatMap(f=>[f["system-out"],f["system-err"]])].filter(f=>f).join(`
39
+ `),u=0,p=i.filter(f=>"failure"in f).length,l=i.filter(f=>"skipped"in f).length,m=i.length-p-l;return{groupId:e,spec:r,startTime:n,artifacts:xc(t),_stdout:a,results:{stats:{suites:1,tests:i.length,passes:m,pending:l,skipped:0,failures:p,flaky:0,wallClockStartedAt:n,wallClockEndedAt:s.toISOString(),wallClockDuration:o},tests:i?.map(f=>(i[0]?.time&&(u+=Ur(i[0].time)),Uc(f,t,u,r)))}}}async function Fc(t){let e=new Map;for(let r of t){let n=at(r.testsuites?.testsuite),o=n.find(u=>u.file)?.file;if(!o){(await K([r])).forEach((p,l)=>e.set(l,p));continue}let s=r.testsuites?.name??"No name",i=n.flatMap(u=>at(u.testcase)),a=to({...n[0],file:o,timestamp:Lf(n[0].timestamp),time:r.testsuites?.time,testcase:i},s,o);a.results.tests.forEach((u,p)=>{u.title=vf(i[p]),u.testId=br(u.title,o)}),a.results.tests.length!==0&&e.set(X(s+o),a)}return e}function vf({name:t="",classname:e=""}){return!e||!t.endsWith(e)?[t||e]:[t.slice(0,-e.length).trim(),e].filter(Boolean)}function Lf(t){return!t||/(Z|[+-]\d\d:?\d\d)$/.test(t)?t:`${t}Z`}async function kc({inputFormat:t,framework:e,parsedXMLArray:r}){return t==="junit"?Bf(e,r):new Map}async function Bf(t,e){switch(t){case"cypress":return Fc(e);case"node":return K(e);case"postman":return K(e);case"vitest":return K(e);case"wdio":return K(e);default:return I("Unsupported framework: %s",t),new Map}}var Mc=require("fs/promises"),$c=require("xml2js");async function jc(t){let e=await Promise.all(t.map(n=>ct(()=>(0,Mc.readFile)(n,"utf-8")))),r=(await Promise.all(e.map(Ff))).filter(Boolean);return e.length!==r.length&&I("Some files could not be parsed. Enable debug logging for more details"),r}async function Ff(t){let e=t.trim();if(!e)return null;try{return await(0,$c.parseStringPromise)(e,{explicitArray:!1,mergeAttrs:!0})||null}catch(r){return d("Error parsing XML input",r),null}}function eo(t){return{framework:"junit",frameworkVersion:t.frameworkVersion??null,frameworkConfig:{originFramework:t.framework,originFrameworkVersion:t.frameworkVersion}}}async function Gc(){try{let t=Or();if(!t)throw new Error("Config is missing!");t.outputDir&&await $f(t.outputDir,t.inputFiles);let e=t.outputDir?await At(t.outputDir):await Po(process.cwd(),".currents"),r=await At((0,F.join)(e,"instances")),n=t.inputFormat==="cypress-json"?await Mf(t,e):await kf(t,e);if(n.size===0)throw new Error(`No test results found in ${t.inputFiles.join(", ")}. Check that the tests ran and that the reports are the files the tests wrote.`);let o=await At((0,F.join)(e,"artifacts")),s=process.cwd();return await Promise.all(Array.from(n.values()).map(i=>ct(async()=>{if(await Sr(i.artifacts,i.spec,o,s),i._stdout){let a=`${X(i.spec)}.stdout.txt`;await St((0,F.join)(o,a),i._stdout),i.artifacts||(i.artifacts=[]),i.artifacts.push({path:(0,F.join)("artifacts",a),type:"stdout",contentType:"text/plain",level:"spec"}),delete i._stdout}for(let a of i.results.tests){await Sr(a.artifacts,a.testId,o,s);for(let u of a.attempts)await Sr(u.artifacts,a.testId+u.attempt,o,s)}}))),await Promise.all(Array.from(n.entries()).map(([i,a])=>ct(()=>St((0,F.join)(r,`${X(i)}.json`),JSON.stringify(a))))),C("[currents] Conversion completed, report saved to: %s",e),e}catch(t){throw d("Failed to convert: %o",t),t}}async function kf(t,e){let r=eo(t);d("Report config:",r),C("[currents] Convertion files: %s",t.inputFiles.join(", ")),await St((0,F.join)(e,"config.json"),JSON.stringify(r));let n=await jc(t.inputFiles);if(n.length===0)throw new Error("No valid XML JUnit report was found.");let o=await kc({inputFormat:t.inputFormat,framework:t.framework,parsedXMLArray:n}),s=t.framework==="cypress"?Zn(o):Nc(n);return await St(It(e),JSON.stringify(s)),o}async function Mf(t,e){C("[currents] Convertion files: %s",t.inputFiles.join(", "));let r=await Lc(t.inputFiles),n=eo({...t,frameworkVersion:t.frameworkVersion??r[0]?.cypressVersion});d("Report config:",n),await St((0,F.join)(e,"config.json"),JSON.stringify(n));let o=Bc(r);return await St(It(e),JSON.stringify(Zn(o))),o}async function $f(t,e){let r=(0,F.resolve)(t),n=new Set(e.map(a=>(0,F.resolve)(a))),o=[(0,F.join)(r,"config.json"),It(r),(0,F.join)(r,"instances"),(0,F.join)(r,"artifacts")],s=[...n].find(a=>o.some(u=>a===u||a.startsWith(u+F.sep)));if(s)throw new Error(`The report "${s}" is where the conversion writes its own files. Move the reports out of "${t}", or leave out --output-dir to convert into a new folder in .currents.`);if(await P(r)?await Kc(r,n):void 0)throw new Error(`The folder "${t}" is not empty. Reports already in it would be uploaded with the converted ones. Remove the folder, or leave out --output-dir to convert into a new folder in .currents.`)}async function Kc(t,e){for(let r of await Hc.default.readdir(t,{withFileTypes:!0})){let n=(0,F.join)(t,r.name),o=r.isDirectory()?await Kc(n,e):e.has(n)?void 0:n;if(o)return o}}var jf=d.extend("cli");async function ro(t){return wc(_c(t)),jf("Config: %o",Or()),Gc()}async function Jc(t){await R(async e=>{await ro(e)},t)}var no="convert",Hf=t=>[{comment:"Convert JUnit test reports to the Currents format, to check the result before an upload",commands:[`${t} ${no} --input-format junit --input-file "./*.xml" --framework postman`]}],qc=t=>new Vc.Command().name(no).command(no).showHelpAfterError("(add --help for additional information)").allowUnknownOption().summary("Convert JUnit XML reports to the Currents format").description("Convert JUnit XML reports to the Currents format, without uploading them. The converted reports are saved to --output-dir or a new folder in .currents").addHelpText("after",y(Hf(t))).addOption(N()).addOption(Cr("(required)")).addOption(yr("(required)")).addOption(Rr).addOption(wr("(required, except with cypress-json)")).addOption(_r).action(r=>Jc(r));var zc=require("@commander-js/extra-typings");var oo=g(require("fs/promises")),Nr=g(require("path"));function Gf(t=__dirname){let e=ke("package.json",t);if(!e)throw new Error("The docs folder is missing from this package");return Nr.default.join(e,"docs")}function Kf(t,e){let r=e.match(/^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n)+/),n=r?.[1].match(/^description:[ \t]*(.+?)\r?$/m)?.[1];if(!r||!n)throw new Error(`docs/${t}.md has no description in its front matter`);return{name:t,description:n,body:e.slice(r[0].length)}}async function Jf(t=Gf()){let e=(await oo.default.readdir(t)).filter(r=>r.endsWith(".md")).sort();return Promise.all(e.map(async r=>Kf(Nr.default.basename(r,".md"),await oo.default.readFile(Nr.default.join(t,r),"utf8"))))}function Yc(t){let e=Math.max(...t.map(r=>r.name.length));return t.map(r=>` ${r.name.padEnd(e)} ${r.description}
40
+ `).join("")}async function Wc(t,e){let r=await Jf();if(!e){await pe(`Topics:
41
+ ${Yc(r)}
40
42
  Run '${t} docs <topic>' to print a guide.
41
- `);return}let o=r.find(n=>n.name===e);if(!o)throw new Error(`Unknown topic "${e}". Topics:
42
- ${$a(r)}`);await Qt(o.body)}var Ao="docs",Iu=t=>[{comment:"List the topics",commands:[`${t} ${Ao}`]},{comment:"Print the guide to CI setup",commands:[`${t} ${Ao} ci-setup`]}],Ha=t=>new Ka.Command().name(Ao).summary("Print a guide, such as the CI setup steps").description("Print the guide of a topic as Markdown. Without a topic, list the topics.").argument("[topic]","the topic of the guide").addHelpText("after",y(Iu(t))).action(async e=>{await R(()=>Ga(t,e),{})});var jo=require("@commander-js/extra-typings");var{apiKey:Cu,recordKey:Tu,projectId:yu,ciBuildId:Ru,machineId:wu,debug:_u}=_,k={apiKey:Cu,recordKey:Tu,projectId:yu,ciBuildId:Ru,machineId:wu,sessionId:{name:"Session ID",env:"CURRENTS_SESSION_ID",cli:"--session-id"},title:{name:"Title",cli:"--title"},debug:_u};var ar=p.extend("config");function Ja(t){let e=U(k,["projectId","title"],t,cr);return ar("Resolved config: %o",h(e)),e}function Va(t){let e=U(k,[],t,cr);return ar("Resolved config: %o",h(e)),e}function Ya(t){let e=U(k,[],t,cr);return ar("Resolved config: %o",h(e)),e}function Wa(t){let e=U(k,["projectId"],t,cr);return ar("Resolved config: %o",h(e)),e}function cr(t){if(!(t.recordKey||t.apiKey))throw new z(`${k.recordKey.name} or ${k.apiKey.name} is required. Set ${k.recordKey.env} or ${k.apiKey.env}, or pass ${k.recordKey.cli} or ${k.apiKey.cli}`)}var se=l(require("fs-extra")),Ot=l(require("path"));var za=l(require("path"));var qa=["trace","screenshot","video","attachment"];var Ou=["image/png","image/jpeg","image/webp","image/gif"],Qa=t=>za.default.extname(t).toLowerCase()===".zip";function Xa(t){return qa.includes(t)}function Do(t){return Qa(t)?"application/zip":eo(t)?.contentType??"application/octet-stream"}function xu(t){return Qa(t)?"trace":eo(t)?.type??"attachment"}function Uo(t,e){let r=xu(t);return e.includes(r)?r:"attachment"}function Za(t,e,r){if(!r.includes(e))throw new Error(`Cannot attach "${t}" as type "${e}" here. The target takes: ${r.join(", ")}`)}function tc(t,e){let r=Do(t);if(!(e==="attachment"||e==="trace"&&r==="application/zip"||e==="screenshot"&&Ou.includes(r)||e==="video"&&r.startsWith("video/")))throw new Error(`Cannot attach "${t}" as type "${e}": its content type is ${r}`)}var ec=l(require("archiver")),_t=l(require("fs-extra")),pr=l(require("path")),rc=l(require("unzipper")),oc=require("tmp-promise");async function nc(t){try{return(await rc.default.Open.file(t)).files.some(r=>/^(trace|test|\d+-trace)\.trace$/.test(r.path))}catch{return!1}}var sc=/^trace-.*\.trace$/,Su=/^trace-.*\.network$/;async function Po(t){return(await _t.default.readdir(t)).some(r=>sc.test(r))}function Au(t){if(!t)return!1;try{let e=JSON.parse(t),r=e.snapshot?.response;if(e.type!=="resource-snapshot"||!r)return!0;let o=r.status>=200&&r.status<400,n=/javascript|ecmascript/i.test(r.content?.mimeType??"");return!(o&&n)}catch{return!0}}async function ic(t,e){return(await _t.default.readdir(t)).filter(o=>e.test(o)).sort().map(o=>pr.default.join(t,o))}async function Du(t){return(await Promise.all((await ic(t,sc)).map(r=>_t.default.readFile(r,"utf8")))).map(r=>r.endsWith(`
43
+ `);return}let n=r.find(o=>o.name===e);if(!n)throw new Error(`Unknown topic "${e}". Topics:
44
+ ${Yc(r)}`);await pe(n.body)}var so="docs",Vf=t=>[{comment:"List the topics",commands:[`${t} ${so}`]},{comment:"Print the guide to CI setup",commands:[`${t} ${so} ci-setup`]}],Qc=t=>new zc.Command().name(so).summary("Print a guide, such as the CI setup steps").description("Print the guide of a topic as Markdown. Without a topic, list the topics.").argument("[topic]","the topic of the guide").addHelpText("after",y(Vf(t))).action(async e=>{await R(()=>Wc(t,e),{})});var Hr=require("@commander-js/extra-typings");var{apiKey:qf,recordKey:Yf,projectId:Wf,ciBuildId:zf,machineId:Qf,debug:Xf}=x,M={apiKey:qf,recordKey:Yf,projectId:Wf,ciBuildId:zf,machineId:Qf,sessionId:{name:"Session ID",env:"CURRENTS_SESSION_ID",cli:"--session-id"},title:{name:"Title",cli:"--title"},debug:Xf};var _e=d.extend("config");function Xc(t){let e=D(M,["projectId","title"],t,vr);return _e("Resolved config: %o",E(e)),e}function Zc(t){let e=D(M,[],t,vr);return _e("Resolved config: %o",E(e)),e}function tp(t){let e=D(M,[],t,vr);return _e("Resolved config: %o",E(e)),e}function ep(t){let e=D(M,["projectId"],t,vr);return _e("Resolved config: %o",E(e)),e}function rp(t){let e=D(M,[],t,Zf);return _e("Resolved config: %o",E(e)),e}function Zf(t){if(!t.apiKey)throw new Q(`run share needs an API key (${M.apiKey.cli} or ${M.apiKey.env}). A record key can share only sessions.`)}function vr(t){if(!(t.recordKey||t.apiKey))throw new Q(`${M.recordKey.name} or ${M.apiKey.name} is required. Set ${M.recordKey.env} or ${M.apiKey.env}, or pass ${M.recordKey.cli} or ${M.apiKey.cli}`)}var xe=g(require("fs/promises")),Nt=g(require("path"));var op=g(require("path"));var np=["trace","screenshot","video","attachment"];var tg=["image/png","image/jpeg","image/webp","image/gif"],sp=t=>op.default.extname(t).toLowerCase()===".zip";function ip(t){return np.includes(t)}function io(t){return sp(t)?"application/zip":Bn(t)?.contentType??"application/octet-stream"}function eg(t){return sp(t)?"trace":Bn(t)?.type??"attachment"}function ao(t,e){let r=eg(t);return e.includes(r)?r:"attachment"}function ap(t,e,r){if(!r.includes(e))throw new Error(`Cannot attach "${t}" as type "${e}" here. The target takes: ${r.join(", ")}`)}function cp(t,e){let r=io(t);if(!(e==="attachment"||e==="trace"&&r==="application/zip"||e==="screenshot"&&tg.includes(r)||e==="video"&&r.startsWith("video/")))throw new Error(`Cannot attach "${t}" as type "${e}": its content type is ${r}`)}var pp=require("fs"),Dt=g(require("fs/promises")),up=g(require("os")),Oe=g(require("path")),dp=require("stream/promises"),mp=g(require("yazl"));async function lp(t){try{return(await ci(t)).some(r=>/^(trace|test|\d+-trace)\.trace$/.test(r))}catch{return!1}}var fp=/^trace-.*\.trace$/,rg=/^trace-.*\.network$/;async function co(t){return(await Dt.default.readdir(t)).some(r=>fp.test(r))}function ng(t){if(!t)return!1;try{let e=JSON.parse(t),r=e.snapshot?.response;if(e.type!=="resource-snapshot"||!r)return!0;let n=r.status>=200&&r.status<400,o=/javascript|ecmascript/i.test(r.content?.mimeType??"");return!(n&&o)}catch{return!0}}async function gp(t,e){return(await Dt.default.readdir(t)).filter(n=>e.test(n)).sort().map(n=>Oe.default.join(t,n))}async function og(t){return(await Promise.all((await gp(t,fp)).map(r=>ct(()=>Dt.default.readFile(r,"utf8"))))).map(r=>r.endsWith(`
43
45
  `)?r:r+`
44
- `).join("")}async function Uu(t){let e=await ic(t,Su),r=[];for(let o of e)r.push(...(await _t.default.readFile(o,"utf8")).split(`
45
- `));return r.filter(Au).join(`
46
- `)}async function ac(t){let{path:e,cleanup:r}=await(0,oc.dir)({unsafeCleanup:!0}),o=pr.default.join(e,"trace.zip");try{let n=(0,ec.default)("zip",{zlib:{level:9}}),s=_t.default.createWriteStream(o),i=new Promise((c,m)=>{s.on("close",()=>c()),s.on("error",m),n.on("error",m)});n.pipe(s),n.append(await Du(t),{name:"trace.trace"}),n.append(await Uu(t),{name:"trace.network"});for(let c of["screencast","resources"]){let m=pr.default.join(t,c);await _t.default.pathExists(m)&&n.directory(m,c)}await n.finalize(),await i}catch(n){throw await r(),n}return{zipPath:o,cleanup:r}}var Pu=1024**3,cc=/^\.env($|[._-])|^\.envrc$|\.env$/i,bu=/\.(pem|key)$|^id_(rsa|ed25519|ecdsa|dsa)/i;function Nu(t){if(cc.test(t))throw new Error(`"${t}" looks like an environment file with secrets and is not attached`)}async function bo(t,e,r){Nu(e);let o=r.type??Uo(e,r.allowedTypes);r.type?(tc(e,r.type),Za(e,r.type,r.allowedTypes)):o==="trace"&&!await nc(t)&&(o="attachment");let n=await se.default.stat(t);if(n.size>Pu)throw new Error(`"${e}" is larger than 1 GiB`);if(n.size===0)throw new Error(`"${e}" is empty`);return{path:t,name:e,type:o,contentType:Do(e),sizeBytes:n.size}}async function Lu(t,e,r){let o=[],n=async s=>{for(let i of await se.default.readdir(s,{withFileTypes:!0})){let c=Ot.default.join(s,i.name),m=Ot.default.relative(t,c).split(Ot.default.sep).join("/");if(i.name.startsWith("."))I(`Skipping the hidden file "${c}"`);else if(bu.test(i.name)||cc.test(i.name))I(`Skipping "${c}", which looks like a key or secrets file`);else if(i.isSymbolicLink())I(`Skipping the link "${c}"`);else if(i.isDirectory())await Po(c)?await r(c,Ot.default.posix.dirname(m)):await n(c);else if(i.isFile()){if((await se.default.stat(c)).size===0){I(`Skipping the empty file "${c}"`);continue}o.push(await bo(c,m,e))}}};return await n(t),o}async function pc(t,e){let r=[],o=[],n=async()=>{await Promise.all(o.map(i=>i()))},s=async(i,c=".")=>{let m=await ac(i);o.push(m.cleanup);let d=Ot.default.posix.join(c,`trace-${Sr(8)}.zip`);r.push(await bo(m.zipPath,d,{...e,type:e.type??Uo("trace.zip",e.allowedTypes)}))};try{for(let i of t){let c=await se.default.stat(i).catch(()=>null);if(!c)throw new Error(`"${i}" does not exist`);if(!c.isDirectory()){r.push(await bo(i,Ot.default.basename(i),e));continue}if(await Po(i)){await s(i);continue}r.push(...await Lu(i,e,s))}}catch(i){throw await n(),i}if(r.length===0)throw new Error("There are no files to attach");return{files:r,cleanup:n}}var dc={run:["attachment"],instance:["attachment","video","screenshot"],test:["attachment"],attempt:["attachment","video","screenshot","trace"]},mc=["attachment","video","screenshot","trace"];function uc(t){return t.testId||t.testTitle?t.attempt===void 0?"test":"attempt":t.instanceId||t.spec?"instance":"run"}var lc=4;async function fc(t){let e=[];for(let r=0;r<t.length;r+=lc)e.push(...await Promise.all(t.slice(r,r+lc).map(async({file:o,uploadUrl:n,uploadHeaders:s})=>{try{return await ys({name:o.name,path:o.path,sizeBytes:o.sizeBytes,uploadUrl:n,contentType:o.contentType,headers:s}),{file:o}}catch(i){return{file:o,error:i}}})));return e}var vu=p.extend("files");function Bu(t=[]){let e=new Map;for(let r of t){let o=r.indexOf("=");if(o<1)throw new Error(`--meta expects key=value, got "${r}"`);let n=r.slice(0,o);if(!/^[A-Za-z0-9_-]{1,64}$/.test(n))throw new Error(`--meta key "${n}" can only hold up to 64 letters, digits, "_" and "-"`);let s=r.slice(o+1);if(s.length>256)throw new Error(`--meta value of "${n}" is longer than 256 characters`);e.set(n,s)}return e.size>0?Object.fromEntries(e):void 0}function Fu(t){if(t!==void 0){if(!Xa(t))throw new Error(`--type must be one of trace, screenshot, video, attachment, got "${t}"`);return t}}var Mu=50,ku=100*1024**2,gc=200;function ju(t,e={count:Mu,bytes:ku}){let r=[],o=0;for(let n of t){let s=r[r.length-1];!s||s.length>=e.count||o+n.sizeBytes>e.bytes?(r.push([n]),o=n.sizeBytes):(s.push(n),o+=n.sizeBytes)}return r}async function No(t){if(!t.credentials.apiKey&&!t.credentials.recordKey)throw new Error("Pass an API key or a record key");let e=Fu(t.type),r=Bu(t.meta),o=t.target??{},n="sessionId"in t.owner?mc:dc[uc(o)],{files:s,cleanup:i}=await pc(t.paths,{type:e,allowedTypes:n});if(s.length>gc)throw await i(),new Error(`Found ${s.length} files to attach; the API takes at most ${gc}. Pass the folders or files you need instead`);let c=[],m=[];try{for(let d of ju(s)){let f=d.map(g=>({name:g.name,type:g.type,contentType:g.contentType,sizeBytes:g.sizeBytes,caption:t.caption,meta:r})),u;try{u=await vn(t.credentials,t.owner,o,f)}catch(g){throw new Error(`${g.message}
47
- ${c.length} of ${s.length} files were attached before this`)}if(vu("Created %d attachments at level %s",u.attachments.length,u.level??"session"),u.attachments.length!==d.length)throw new Error(`The API returned ${u.attachments.length} upload URLs for ${d.length} files`);let E=await fc(d.map((g,A)=>{if(u.attachments[A].name!==g.name)throw new Error(`The API answered "${u.attachments[A].name}" where "${g.name}" was declared`);let{uploadUrl:Y,uploadHeaders:St}=u.attachments[A];return{file:g,uploadUrl:Y,uploadHeaders:St}}));for(let g of E)g.error?(C("Failed %s: %s",g.file.name,g.error.message),m.push(g)):(T("Attached %s (%s)",g.file.name,g.file.type),c.push(g.file))}}finally{await i().catch(d=>I("Could not remove temporary files: %s",d.message))}if(m.length>0)throw new Error(`${m.length} of ${s.length} files could not be uploaded`);return{files:c.map(({name:d,type:f,sizeBytes:u})=>({name:d,type:f,sizeBytes:u}))}}var xt=l(require("fs-extra")),ie=l(require("path")),$u=".currents-session",hc=()=>ie.default.join(process.cwd(),$u,"session.json");async function Gu(t){let e=ie.default.join(t,".gitignore");await xt.default.pathExists(e)||await xt.default.writeFile(e,`*
48
- `)}async function Ec(t){let e=hc();await xt.default.ensureDir(ie.default.dirname(e)),await Gu(ie.default.dirname(e)),await xt.default.writeJson(e,t,{spaces:2})}async function Ku(){let t=hc();if(!await xt.default.pathExists(t))return null;let e=await xt.default.readJson(t),r=e?.sessionId||e?.runId;if(typeof r!="string"||!r.trim())return null;let o=typeof e.projectId=="string"?e.projectId:void 0;return{sessionId:r,projectId:o}}async function Lo(t){if(t)return t;let e=await Ku();if(!e)throw new Error('No session found. Run "currents session start" first, or pass --session-id');return e.sessionId}var Hu=p.extend("session");async function Ju(){try{let{sha:t,branch:e,message:r,authorName:o,authorEmail:n,remoteOrigin:s}=await Ue();return{sha:t,branch:e,message:r,authorName:o,authorEmail:n,remoteOrigin:s}}catch(t){Hu("No git info: %o",t);return}}function Vu(t){if(t)return/^\d+$/.test(t)?{id:t}:{link:t}}function Ic(){let{provider:t,params:e}=rt();return{provider:t,params:e}}function Yu(){if(rt().ciBuildId.source!=="server")throw new Error("The CI build ID is unknown. Pass --ci-build-id or set CURRENTS_CI_BUILD_ID to the value the run was recorded with")}async function Cc(t){let e=await Ln({apiKey:t.apiKey,recordKey:t.recordKey},{projectId:t.projectId,title:t.title,status:t.status,error:t.error,tags:t.tag,commit:await Ju(),ci:Ic(),pr:Vu(t.pr)});return await Ec({sessionId:e.sessionId,projectId:t.projectId}),t.json?process.stdout.write(JSON.stringify({sessionId:e.sessionId})+`
49
- `):T("Session started: %s",e.sessionId),e}async function Tc(t,e){let r=await Lo(t.sessionId);return No({credentials:{apiKey:t.apiKey,recordKey:t.recordKey},owner:{sessionId:r},paths:e,type:t.type,caption:t.caption,meta:t.meta})}async function yc(t){let e=await Lo(t.sessionId),r=await Bn({apiKey:t.apiKey,recordKey:t.recordKey},{sessionId:e,purpose:"report",expiresInDays:t.expiresInDays});return T(r.pageUrl),T("Markdown: %s",r.url),r}async function Rc(t,e){if(t.testTitle&&!t.spec)throw new Error("--test-title needs --spec, the spec file of the test");if(t.attempt!==void 0&&!t.testTitle)throw new Error("--attempt needs --test-title");if(t.group&&!t.spec)throw new Error("--group needs --spec: it picks the spec file of a group");return t.ciBuildId||Yu(),No({credentials:{apiKey:t.apiKey,recordKey:t.recordKey},owner:t.ciBuildId?{projectId:t.projectId,ciBuildId:t.ciBuildId}:{projectId:t.projectId,ci:Ic()},target:{spec:t.spec,testTitle:t.testTitle,groupId:t.group,attempt:t.attempt,machineId:t.spec?void 0:t.machineId},paths:e,type:t.type,caption:t.caption,meta:t.meta})}var S=require("@commander-js/extra-typings");var wc=t=>L(k,t),kt="(required unless --api-key is set)",jt="(used when --key is not set; needs write access)",_c=vt(". Leave it out only if the run was recorded without one, on a CI the reporters recognize"),Oc=new S.Option("--machine-id <id>","the CI machine the files come from; run-level files are listed by machine when it is set").env(wc("machineId")),Bo=new S.Option("--session-id <id>",'the session to use instead of the one saved by "session start"').env(wc("sessionId")),xc=new S.Option("--title <text>","what the session shows, used as the session title (required)"),Sc=new S.Option("--status <status>","the result of the session").choices(["passed","failed"]).default("passed"),Ac=new S.Option("--error <text>","what went wrong, for a failed session"),Dc=Bt("tags to add to the session"),Uc=new S.Option("--pr <url|number>","the pull request the session is about; by default taken from the CI environment"),Pc=new S.Option("--json",'print the session ID as JSON on stdout, e.g. {"sessionId": "..."}'),bc=new S.Option("--spec <spec>","attach to this spec file of the run"),Nc=new S.Option("--test-title <title>",'attach to this test of --spec: the full title joined with " > ", or its last part'),Lc=new S.Option("--group <id>","the group of the spec file; a spec that runs once per Playwright project matches more than once without it"),vc=new S.Option("--attempt <n>","attach to this attempt of the test; the first attempt is 0").argParser(t=>{let e=Number(t);if(!Number.isInteger(e)||e<0)throw new Error("--attempt must be a whole number from 0");return e}),Bc=["trace","screenshot","video","attachment"],Fc="by default taken from the file: a .zip holding trace.trace is a trace; .png, .jpg, .jpeg, .webp and .gif are screenshots; .webm and .mp4 are videos; anything else is an attachment",Mc=new S.Option("--type <type>",`the type of every file; ${Fc}`).choices(Bc),kc=new S.Option("--type <type>",`the type of every file; ${Fc}. The whole run and a test take attachments only, a spec file also takes screenshots and videos, and an attempt (--attempt) takes all four types, including traces. A file of a type its target does not take is attached as an attachment, and a --type the target does not take is an error`).choices(Bc),dr="files or folders to attach. A folder adds every file under it, named by its path in the folder, such as login-chromium/trace.zip, so a Playwright test-results folder attaches in one go; hidden files and folders, links and empty files in it are skipped. A folder of Playwright MCP trace-*.trace files, at the top or inside, is packed into one trace and nothing else in it is attached. At most 200 files, each at most 1 GiB; files named .env or .env.* are refused",mr=new S.Option("--caption <text>","a short description shown with each file"),Wu=(t,e=[])=>[...e,t],ur=new S.Option("--meta <key=value>","a label for each file; repeat for more").argParser(Wu),vo=["1","3","7"],jc=new S.Option("--expires-in-days <days>","the number of days the link works").choices(vo).default(7).argParser(t=>{if(!vo.includes(t))throw new S.InvalidArgumentError(`Allowed choices are ${vo.join(", ")}.`);return Number(t)});var Xc=require("@commander-js/extra-typings");var $t=require("@commander-js/extra-typings");var $c=new $t.Option("--ci-build-id <id>","the CI build ID to record the run with; by default taken from the CI environment, or a random value").env(L(nt,"ciBuildId")),Gc=Bt("tags to add to the run").env(L(nt,"tag")),Kc=new $t.Option("--remove-title-tags","remove tags from test names in Currents, e.g. `Test name @smoke` becomes `Test name` in the dashboard").env(L(nt,"removeTitleTags")).default(!1),Hc=new $t.Option("--disable-title-tags","do not read tags from test names, e.g. `Test name @smoke` is not tagged with `smoke` in the dashboard").env(L(nt,"disableTitleTags")).default(!1),Jc=new $t.Option("--machine-id <id>","the ID of the machine that ran the tests; by default a random value").env(L(nt,"machineId")),Vc=new $t.Option("--report-dir <folder>","the folder of the reports to upload; by default the newest folder in .currents").env(L(nt,"reportDir"));var Mo=require("path");var qc=l(require("fs"));var Yc=require("tmp-promise"),Wc=async()=>{let{path:t}=await(0,Yc.file)();return t};var Fo=p.extend("cli"),lr=class{constructor(e){this.configFilePath=null;this.cliOptions=e,Fo("CLI options: %o",h(this.cliOptions)),this.parsedConfig=Vs(this.cliOptions),Fo("Parsed config from CLI options: %o",h(this.parsedConfig))}async getConfigFilePath(){if(this.configFilePath)return this.configFilePath;let e=await Wc();return qc.default.writeFileSync(e,JSON.stringify(this.parsedConfig)),Fo("CLI options temp file path: %s",e),this.configFilePath=e,e}};async function zc(t){await R(async e=>{let r=e.inputFormat?await qu(e):e.reportDir,o=new lr({...e,reportDir:r});Js(o.parsedConfig);let n=Pe();T("Currents config: %o",h(n)),await co()},t)}async function qu({inputFormat:t,inputFile:e,framework:r,frameworkVersion:o,outputDir:n,reportDir:s,debug:i}){if(n&&s&&(0,Mo.resolve)(n)!==(0,Mo.resolve)(s))throw new Error("--output-dir and --report-dir name different folders. With --input-format, the converted reports are saved to one folder and uploaded from it: pass one of the two options.");return Oo({inputFormat:t,inputFile:e,framework:r,frameworkVersion:o,outputDir:n??s,debug:i})}var Gt="upload",Qc="(required with --input-format)",fr="run",Kt=t=>[{comment:"Upload test results to Currents",commands:[`${t} ${fr} ${Gt} --key <record-key> --project-id <id> --ci-build-id <build-id>`]},{comment:"Convert JUnit XML reports to the Currents format, then upload them",commands:[`${t} ${fr} ${Gt} --key <record-key> --project-id <id> --ci-build-id <build-id> --input-format junit --input-file "./*.xml" --framework postman`]},{comment:'Upload test results and add the tags "tagA" and "tagB" to the run',commands:[`${t} ${fr} ${Gt} --key <record-key> --project-id <id> --ci-build-id <build-id> --tag tagA --tag tagB`]},{comment:"Upload test results from another folder",commands:[`${t} ${fr} ${Gt} --key <record-key> --project-id <id> --ci-build-id <build-id> --report-dir <report-dir>`]}],gr=t=>new Xc.Command().name(Gt).command(Gt).showHelpAfterError("(add --help for additional information)").allowUnknownOption().summary("Upload test results of Currents reporters or JUnit").description(`Upload test results created by Currents reporters to https://currents.dev
46
+ `).join("")}async function sg(t){let e=await gp(t,rg),r=[];for(let n of e)r.push(...(await Dt.default.readFile(n,"utf8")).split(`
47
+ `));return r.filter(ng).join(`
48
+ `)}async function hp(t){let e=await Dt.default.mkdtemp(Oe.default.join(up.default.tmpdir(),"currents-trace-")),r=()=>Dt.default.rm(e,{recursive:!0,force:!0}),n=Oe.default.join(e,"trace.zip");try{let o=new mp.default.ZipFile;o.addBuffer(Buffer.from(await og(t)),"trace.trace"),o.addBuffer(Buffer.from(await sg(t)),"trace.network");for(let s of["screencast","resources"]){let i=Oe.default.join(t,s);await P(i)&&await le(o,i,s)}await(0,dp.pipeline)(Qe(o),(0,pp.createWriteStream)(n))}catch(o){throw await r(),o}return{zipPath:n,cleanup:r}}var ig=1024**3,Ep=/^\.env($|[._-])|^\.envrc$|\.env$/i,ag=/\.(pem|key)$|^id_(rsa|ed25519|ecdsa|dsa)/i;function cg(t){if(Ep.test(t))throw new Error(`"${t}" looks like an environment file with secrets and is not attached`)}async function po(t,e,r){cg(e);let n=r.type??ao(e,r.allowedTypes);r.type?(cp(e,r.type),ap(e,r.type,r.allowedTypes)):n==="trace"&&!await lp(t)&&(n="attachment");let o=await xe.default.stat(t);if(o.size>ig)throw new Error(`"${e}" is larger than 1 GiB`);if(o.size===0)throw new Error(`"${e}" is empty`);return{path:t,name:e,type:n,contentType:io(e),sizeBytes:o.size}}async function pg(t,e,r){let n=[],o=async s=>{for(let i of await xe.default.readdir(s,{withFileTypes:!0})){let a=Nt.default.join(s,i.name),u=Nt.default.relative(t,a).split(Nt.default.sep).join("/");if(i.name.startsWith("."))I(`Skipping the hidden file "${a}"`);else if(ag.test(i.name)||Ep.test(i.name))I(`Skipping "${a}", which looks like a key or secrets file`);else if(i.isSymbolicLink())I(`Skipping the link "${a}"`);else if(i.isDirectory())await co(a)?await r(a,Nt.default.posix.dirname(u)):await o(a);else if(i.isFile()){if((await xe.default.stat(a)).size===0){I(`Skipping the empty file "${a}"`);continue}n.push(await po(a,u,e))}}};return await o(t),n}async function Ip(t,e){let r=[],n=[],o=async()=>{await Promise.all(n.map(i=>i()))},s=async(i,a=".")=>{let u=await hp(i);n.push(u.cleanup);let p=Nt.default.posix.join(a,`trace-${Me(8)}.zip`);r.push(await po(u.zipPath,p,{...e,type:e.type??ao("trace.zip",e.allowedTypes)}))};try{for(let i of t){let a=await xe.default.stat(i).catch(()=>null);if(!a)throw new Error(`"${i}" does not exist`);if(!a.isDirectory()){r.push(await po(i,Nt.default.basename(i),e));continue}if(await co(i)){await s(i);continue}r.push(...await pg(i,e,s))}}catch(i){throw await o(),i}if(r.length===0)throw new Error("There are no files to attach");return{files:r,cleanup:o}}var Tp={run:["attachment"],instance:["attachment","video","screenshot"],test:["attachment"],attempt:["attachment","video","screenshot","trace"]},Cp=["attachment","video","screenshot","trace"];function yp(t){return t.testId||t.testTitle?t.attempt===void 0?"test":"attempt":t.instanceId||t.spec?"instance":"run"}var Rp=4;async function wp(t){let e=[];for(let r=0;r<t.length;r+=Rp)e.push(...await Promise.all(t.slice(r,r+Rp).map(async({file:n,uploadUrl:o,uploadHeaders:s})=>{try{return await hi({name:n.name,path:n.path,sizeBytes:n.sizeBytes,uploadUrl:o,contentType:n.contentType,headers:s}),{file:n}}catch(i){return{file:n,error:i}}})));return e}var ug=d.extend("files");function dg(t=[]){let e=new Map;for(let r of t){let n=r.indexOf("=");if(n<1)throw new Error(`--meta expects key=value, got "${r}"`);let o=r.slice(0,n);if(!/^[A-Za-z0-9_-]{1,64}$/.test(o))throw new Error(`--meta key "${o}" can only hold up to 64 letters, digits, "_" and "-"`);let s=r.slice(n+1);if(s.length>256)throw new Error(`--meta value of "${o}" is longer than 256 characters`);e.set(o,s)}return e.size>0?Object.fromEntries(e):void 0}function mg(t){if(t!==void 0){if(!ip(t))throw new Error(`--type must be one of trace, screenshot, video, attachment, got "${t}"`);return t}}var lg=50,fg=100*1024**2,_p=200;function gg(t,e={count:lg,bytes:fg}){let r=[],n=0;for(let o of t){let s=r[r.length-1];!s||s.length>=e.count||n+o.sizeBytes>e.bytes?(r.push([o]),n=o.sizeBytes):(s.push(o),n+=o.sizeBytes)}return r}async function uo(t){if(!t.credentials.apiKey&&!t.credentials.recordKey)throw new Error("Pass an API key or a record key");let e=mg(t.type),r=dg(t.meta),n=t.target??{},o="sessionId"in t.owner?Cp:Tp[yp(n)],{files:s,cleanup:i}=await Ip(t.paths,{type:e,allowedTypes:o});if(s.length>_p)throw await i(),new Error(`Found ${s.length} files to attach; the API takes at most ${_p}. Pass the folders or files you need instead`);let a=[],u=[];try{for(let p of gg(s)){let l=p.map(f=>({name:f.name,type:f.type,contentType:f.contentType,sizeBytes:f.sizeBytes,caption:t.caption,meta:r})),m;try{m=await Ns(t.credentials,t.owner,n,l)}catch(f){throw new Error(`${f.message}
49
+ ${a.length} of ${s.length} files were attached before this`)}if(ug("Created %d attachments at level %s",m.attachments.length,m.level??"session"),m.attachments.length!==p.length)throw new Error(`The API returned ${m.attachments.length} upload URLs for ${p.length} files`);let h=await wp(p.map((f,O)=>{if(m.attachments[O].name!==f.name)throw new Error(`The API answered "${m.attachments[O].name}" where "${f.name}" was declared`);let{uploadUrl:j,uploadHeaders:Lt}=m.attachments[O];return{file:f,uploadUrl:j,uploadHeaders:Lt}}));for(let f of h)f.error?(T("Failed %s: %s",f.file.name,f.error.message),u.push(f)):(C("Attached %s (%s)",f.file.name,f.file.type),a.push(f.file))}}finally{await i().catch(p=>I("Could not remove temporary files: %s",p.message))}if(u.length>0)throw new Error(`${u.length} of ${s.length} files could not be uploaded`);return{files:a.map(({name:p,type:l,sizeBytes:m})=>({name:p,type:l,sizeBytes:m}))}}var Lr=g(require("fs/promises")),Se=g(require("path")),hg=".currents-session",Op=()=>Se.default.join(process.cwd(),hg,"session.json");async function Eg(t){let e=Se.default.join(t,".gitignore");await P(e)||await Lr.default.writeFile(e,`*
50
+ `)}async function xp(t){let e=Op();await Lr.default.mkdir(Se.default.dirname(e),{recursive:!0}),await Eg(Se.default.dirname(e)),await Lr.default.writeFile(e,JSON.stringify(t,null,2)+`
51
+ `)}async function Ig(){let t=Op();if(!await P(t))return null;let e=await pt(t),r=e?.sessionId||e?.runId;if(typeof r!="string"||!r.trim())return null;let n=typeof e.projectId=="string"?e.projectId:void 0;return{sessionId:r,projectId:n}}async function mo(t){if(t)return t;let e=await Ig();if(!e)throw new Error('No session found. Run "currents session start" first, or pass --session-id');return e.sessionId}var Tg=d.extend("session");async function Cg(){try{let{sha:t,branch:e,message:r,authorName:n,authorEmail:o,remoteOrigin:s}=await Ee();return{sha:t,branch:e,message:r,authorName:n,authorEmail:o,remoteOrigin:s}}catch(t){Tg("No git info: %o",t);return}}function yg(t){if(t)return/^\d+$/.test(t)?{id:t}:{link:t}}function Sp(){let{provider:t,params:e}=ut();return{provider:t,params:e}}function Rg(){if(ut().ciBuildId.source!=="server")throw new Error("The CI build ID is unknown. Pass --ci-build-id or set CURRENTS_CI_BUILD_ID to the value the run was recorded with")}async function Ap(t){let e=await Ds({apiKey:t.apiKey,recordKey:t.recordKey},{projectId:t.projectId,title:t.title,status:t.status,error:t.error,tags:t.tag,commit:await Cg(),ci:Sp(),pr:yg(t.pr)});return await xp({sessionId:e.sessionId,projectId:t.projectId}),t.json?process.stdout.write(JSON.stringify({sessionId:e.sessionId})+`
52
+ `):C("Session started: %s",e.sessionId),e}async function bp(t,e){let r=await mo(t.sessionId);return uo({credentials:{apiKey:t.apiKey,recordKey:t.recordKey},owner:{sessionId:r},paths:e,type:t.type,caption:t.caption,meta:t.meta})}async function Pp(t){let e=await mo(t.sessionId),r=await fn({apiKey:t.apiKey,recordKey:t.recordKey},{sessionId:e,purpose:"report",expiresInDays:t.expiresInDays});return Up(r),r}function Up(t){C(t.pageUrl),C("Markdown: %s",t.url)}async function Dp(t){let{runId:e,instanceId:r,testId:n,attempt:o,purpose:s}=t;for(let[p,l]of[["<run-id>",e],["--instance-id",r],["--test-id",n]])if(l!==void 0&&l.trim()==="")throw new Error(`${p} must not be empty`);if(n&&!r)throw new Error("--test-id needs --instance-id, the spec file of the test");if(o!==void 0&&!n)throw new Error("--attempt needs --test-id");if(o!==void 0&&s!=="fix")throw new Error("--attempt needs --purpose fix: a report holds every attempt");let i={apiKey:t.apiKey},a={runId:e,instanceId:r};if(r&&n){let p=await vs(i,r);if(p.runId!==e)throw new Error(`Instance ${r} belongs to run ${p.runId}, not run ${e}`);a={instanceId:r,testId:n,attempt:o}}let u=await fn(i,{...a,purpose:s,expiresInDays:t.expiresInDays});return Up(u),u}async function Np(t,e){if(t.testTitle&&!t.spec)throw new Error("--test-title needs --spec, the spec file of the test");if(t.attempt!==void 0&&!t.testTitle)throw new Error("--attempt needs --test-title");if(t.group&&!t.spec)throw new Error("--group needs --spec: it picks the spec file of a group");return t.ciBuildId||Rg(),uo({credentials:{apiKey:t.apiKey,recordKey:t.recordKey},owner:t.ciBuildId?{projectId:t.projectId,ciBuildId:t.ciBuildId}:{projectId:t.projectId,ci:Sp()},target:{spec:t.spec,testTitle:t.testTitle,groupId:t.group,attempt:t.attempt,machineId:t.spec?void 0:t.machineId},paths:e,type:t.type,caption:t.caption,meta:t.meta})}var _=require("@commander-js/extra-typings");var vp=t=>U(M,t),te="(required unless --api-key is set)",ee="(used when --key is not set; needs write access)",Lp=Wt(". Leave it out only if the run was recorded without one, on a CI the reporters recognize"),Bp=new _.Option("--machine-id <id>","the CI machine the files come from; run-level files are listed by machine when it is set").env(vp("machineId")),fo=new _.Option("--session-id <id>",'the session to use instead of the one saved by "session start"').env(vp("sessionId")),Fp=new _.Option("--title <text>","what the session shows, used as the session title (required)"),kp=new _.Option("--status <status>","the result of the session").choices(["passed","failed"]).default("passed"),Mp=new _.Option("--error <text>","what went wrong, for a failed session"),$p=zt("tags to add to the session"),jp=new _.Option("--pr <url|number>","the pull request the session is about; by default taken from the CI environment"),Hp=new _.Option("--json",'print the session ID as JSON on stdout, e.g. {"sessionId": "..."}'),Gp=new _.Option("--spec <spec>","attach to this spec file of the run"),Kp=new _.Option("--test-title <title>",'attach to this test of --spec: the full title joined with " > ", or its last part'),Jp=new _.Option("--group <id>","the group of the spec file; a spec that runs once per Playwright project matches more than once without it");function Vp(t){let e=Number(t);if(!Number.isInteger(e)||e<0)throw new Error("--attempt must be a whole number from 0");return e}var qp=new _.Option("--attempt <n>","attach to this attempt of the test; the first attempt is 0").argParser(Vp),Yp=["trace","screenshot","video","attachment"],Wp="by default taken from the file: a .zip holding trace.trace is a trace; .png, .jpg, .jpeg, .webp and .gif are screenshots; .webm and .mp4 are videos; anything else is an attachment",zp=new _.Option("--type <type>",`the type of every file; ${Wp}`).choices(Yp),Qp=new _.Option("--type <type>",`the type of every file; ${Wp}. The whole run and a test take attachments only, a spec file also takes screenshots and videos, and an attempt (--attempt) takes all four types, including traces. A file of a type its target does not take is attached as an attachment, and a --type the target does not take is an error`).choices(Yp),Br="files or folders to attach. A folder adds every file under it, named by its path in the folder, such as login-chromium/trace.zip, so a Playwright test-results folder attaches in one go; hidden files and folders, links and empty files in it are skipped. A folder of Playwright MCP trace-*.trace files, at the top or inside, is packed into one trace and nothing else in it is attached. At most 200 files, each at most 1 GiB; files named .env or .env.* are refused",Fr=new _.Option("--caption <text>","a short description shown with each file"),wg=(t,e=[])=>[...e,t],kr=new _.Option("--meta <key=value>","a label for each file; repeat for more").argParser(wg),lo=["1","3","7"],Xp=t=>new _.Option("--expires-in-days <days>",t).choices(lo).argParser(e=>{if(!lo.includes(e))throw new _.InvalidArgumentError(`Allowed choices are ${lo.join(", ")}.`);return Number(e)}),Zp=Xp("the number of days the link works").default(7),tu=Xp("the number of days the link works; by default 7 for report and 1 for fix"),eu=new _.Option("--instance-id <id>","one spec file of the run (default: the whole run)"),ru=new _.Option("--test-id <id>","one test of the spec file; needs --instance-id"),nu=new _.Option("--attempt <n>","one attempt of the test, from 0; needs --test-id and --purpose fix (default: the last attempt that failed)").argParser(Vp),ou=new _.Option("--purpose <purpose>",`report: every test with its attempts and files, for a person
53
+ fix: the failure context, for an agent fixing the tests`).choices(["report","fix"]).default("report");var gu=require("@commander-js/extra-typings");var Ct=require("@commander-js/extra-typings");var su=new Ct.Option("--ci-build-id <id>","the CI build ID to record the run with; by default taken from the CI environment, or a random value").env(U(tt,"ciBuildId")),iu=zt("tags to add to the run").env(U(tt,"tag")),au=new Ct.Option("--remove-title-tags","remove tags from test names in Currents, e.g. `Test name @smoke` becomes `Test name` in the dashboard").env(U(tt,"removeTitleTags")).default(!1),cu=new Ct.Option("--disable-title-tags","do not read tags from test names, e.g. `Test name @smoke` is not tagged with `smoke` in the dashboard").env(U(tt,"disableTitleTags")).default(!1),pu=new Ct.Option("--environment <name>","the environment to label the run with, e.g. staging").env(U(tt,"environment")),uu=new Ct.Option("--machine-id <id>","the ID of the machine that ran the tests; by default a random value").env(U(tt,"machineId")),du=new Ct.Option("--fail-on-failures","exit with 1 when a test failed, after the results are uploaded; a test quarantined or skipped by a Currents action does not count").env(U(tt,"failOnFailures")).default(!1),mu=new Ct.Option("--report-dir <folder>","the folder of the reports to upload; by default the newest folder in .currents").env(U(tt,"reportDir"));var ho=require("path");var lu=g(require("fs"));var go=d.extend("cli"),Mr=class{constructor(e){this.configFilePath=null;this.cliOptions=e,go("CLI options: %o",E(this.cliOptions)),this.parsedConfig=Vi(this.cliOptions),go("Parsed config from CLI options: %o",E(this.parsedConfig))}async getConfigFilePath(){if(this.configFilePath)return this.configFilePath;let e=await Be();return lu.default.writeFileSync(e,JSON.stringify(this.parsedConfig)),go("CLI options temp file path: %s",e),this.configFilePath=e,e}};async function fu(t){await R(async e=>{let r=e.inputFormat?await _g(e):e.reportDir,n=new Mr({...e,reportDir:r});Ji(n.parsedConfig);let o=er();C("Currents config: %o",E(o)),await jn()},t)}async function _g({inputFormat:t,inputFile:e,framework:r,frameworkVersion:n,outputDir:o,reportDir:s,debug:i}){if(o&&s&&(0,ho.resolve)(o)!==(0,ho.resolve)(s))throw new Error("--output-dir and --report-dir name different folders. With --input-format, the converted reports are saved to one folder and uploaded from it: pass one of the two options.");return ro({inputFormat:t,inputFile:e,framework:r,frameworkVersion:n,outputDir:o??s,debug:i})}var vt="upload",Og="(required with --input-format)",Ae="run",re=t=>[{comment:"Upload test results to Currents",commands:[`${t} ${Ae} ${vt} --key <record-key> --project-id <id> --ci-build-id <build-id>`]},{comment:"Convert JUnit XML reports to the Currents format, then upload them",commands:[`${t} ${Ae} ${vt} --key <record-key> --project-id <id> --ci-build-id <build-id> --input-format junit --input-file "./*.xml" --framework postman`]},{comment:'Upload test results and add the tags "tagA" and "tagB" to the run',commands:[`${t} ${Ae} ${vt} --key <record-key> --project-id <id> --ci-build-id <build-id> --tag tagA --tag tagB`]},{comment:"Upload test results, then fail if a test failed that no Currents action quarantined or skipped",commands:[`${t} ${Ae} ${vt} --key <record-key> --project-id <id> --ci-build-id <build-id> --fail-on-failures`]},{comment:"Upload test results from another folder",commands:[`${t} ${Ae} ${vt} --key <record-key> --project-id <id> --ci-build-id <build-id> --report-dir <report-dir>`]}],$r=t=>new gu.Command().name(vt).command(vt).showHelpAfterError("(add --help for additional information)").allowUnknownOption().summary("Upload test results of Currents reporters or JUnit").description(`Upload test results created by Currents reporters to https://currents.dev
50
54
 
51
55
  With --input-format, first convert the reports in --input-file to the Currents
52
56
  format, then upload the converted reports. They are saved to --output-dir, or
53
57
  --report-dir, or a new folder in .currents. A folder you name may hold only the
54
- reports being converted.`).addHelpText("after",y(Kt(t))).addOption($c).addOption(M()).addOption(tt()).addOption(Gc).addOption(Kc).addOption(Hc).addOption(Jc).addOption(b()).addOption(Vc).addOption(er()).addOption(rr(Qc)).addOption(nr(Qc)).addOption(sr).addOption(or).action(r=>zc(r));var ko="run",hr=t=>[{comment:"Attach the Docker logs of a CI machine to the run, after the tests finished",commands:[`${t} ${ko} attach --key <record-key> --project-id <id> --ci-build-id <build-id> --machine-id shard-1 docker-logs.zip`]},{comment:"Attach a screenshot to the first attempt of a test",commands:[`${t} ${ko} attach --key <record-key> --project-id <id> --ci-build-id <build-id> --spec tests/cart.spec.ts --test-title "adds an item" --attempt 0 screenshot.png`]}],zu=t=>new jo.Command().name("attach").addHelpText("after",y(hr(t))).description("Upload files to a run recorded in CI").argument("<paths...>",dr).addOption(M(kt)).addOption(at(jt)).addOption(tt()).addOption(_c).addOption(Oc).addOption(bc).addOption(Lc).addOption(Nc).addOption(vc).addOption(kc).addOption(mr).addOption(ur).addOption(b()).action(async(e,r)=>{await R(async({key:o,...n})=>{await Rc(Wa({...n,recordKey:o}),e)},r)}),Zc=t=>new jo.Command().name(ko).summary("Upload test results, attach files, get or cancel a run").description("Upload test results to a run, attach files to it, get its data or cancel it").addHelpText("after",y([...Kt(t).slice(0,2),hr(t)[0],fo(t)[0],oe(t)[0]])).showHelpAfterError("(add --help for additional information)").addCommand(gr(t)).addCommand(zu(t)).addCommand(go(t)).addCommand(We(t));var ae=require("@commander-js/extra-typings");var Er="session",Ht=t=>{let e=`${t} ${Er} start --api-key <api-key> --project-id <id> --title "Checkout fails on empty cart" --status failed`,r=`${t} ${Er} attach before.png .playwright-mcp/traces`,o=`${t} ${Er} share --expires-in-days 7`;return{session:[{comment:"Start a session, attach what you captured and get a link to share",commands:[e,r,o]}],start:[{comment:"Start a session for a failed check",commands:[e]}],attach:[{comment:"Attach a screenshot and a Playwright MCP trace folder",commands:[r]}],share:[{comment:"Print a link that expires in 7 days",commands:[o]}]}},Qu=t=>new ae.Command().name("start").addHelpText("after",y(Ht(t).start)).summary("Create a session").description('Create a session and save its ID to .currents-session/session.json in the current folder, where "attach" and "share" read it').addOption(M(kt)).addOption(at(jt)).addOption(tt()).addOption(xc).addOption(Sc).addOption(Ac).addOption(Dc).addOption(Uc).addOption(Pc).addOption(b()).action(async e=>{await R(async({key:r,...o})=>{o.json&&Nt(),await Cc(Ja({...o,recordKey:r}))},e)}),Xu=t=>new ae.Command().name("attach").summary("Upload screenshots, traces and other files").addHelpText("after",y(Ht(t).attach)).description("Upload files, folders or a Playwright MCP trace folder to the session").argument("<paths...>",dr).addOption(M(kt)).addOption(at(jt)).addOption(Bo).addOption(Mc).addOption(mr).addOption(ur).addOption(b()).action(async(e,r)=>{await R(async({key:o,...n})=>{await Tc(Va({...n,recordKey:o}),e)},r)}),Zu=t=>new ae.Command().name("share").addHelpText("after",y(Ht(t).share)).summary("Print a public link to the session page").description('Create a public link to the session page and print it. The second line, "Markdown: <url>", is the address of the same content as Markdown, for agents').addOption(M(kt)).addOption(at(jt)).addOption(Bo).addOption(jc).addOption(b()).action(async e=>{await R(async({key:r,...o})=>{await yc(Ya({...o,recordKey:r}))},e)}),tp=t=>new ae.Command().name(Er).summary("Capture agent or browser sessions as evidence").description("Capture ad-hoc, one-off agent or browser sessions as evidence: a bug before and after a fix, or proof that something works. Create a session, attach screenshots, traces, videos and other files to it, and print a link to share it.").addHelpText("after",y(Ht(t).session)).showHelpAfterError("(add --help for additional information)").addCommand(Qu(t)).addCommand(Xu(t)).addCommand(Zu(t));var Vt=require("@commander-js/extra-typings");var ct=l(require("fs-extra")),$=l(require("path"));var pt="currents-cli",Jt=$.default.join(".agents","skills");function ep(t=__dirname){let e=$.default.join("skills",pt),r=le($.default.join(e,"SKILL.md"),t);if(!r)throw new Error(`The ${pt} skill is missing from this package`);return $.default.join(r,e)}async function $o(t,e=""){let r=[];for(let o of await ct.default.readdir($.default.join(t,e),{withFileTypes:!0})){let n=$.default.join(e,o.name);o.isDirectory()?r.push(...await $o(t,n)):r.push(n)}return r.sort()}async function tl(t,e){let[r,o]=await Promise.all([$o(t),$o(e)]);if(r.join(`
55
- `)!==o.join(`
56
- `))return!1;for(let n of r){let[s,i]=await Promise.all([ct.default.readFile($.default.join(t,n)),ct.default.readFile($.default.join(e,n))]);if(!s.equals(i))return!1}return!0}async function rp(){await Qt(await ct.default.readFile($.default.join(ep(),"SKILL.md"),"utf8"))}async function op({dir:t=Jt,force:e=!1}){let r=ep(),o=$.default.resolve(t,pt),n=$.default.relative(process.cwd(),o)||".";if(await ct.default.pathExists(o)){if(!(await ct.default.stat(o)).isDirectory())throw new Error(`${n} exists and is not a folder`);if(await tl(r,o))return T("The %s skill is already in %s",pt,n),o;if(!e)throw new Error(`${n} exists and differs from the skill of this version. Pass --force to replace it`);await ct.default.remove(o)}return await ct.default.copy(r,o),T("Wrote the %s skill to %s",pt,n),o}var Ir="skill",el=t=>[{comment:"Print the skill",commands:[`${t} ${Ir}`]},{comment:`Add the skill to the project, in ${Jt}/${pt}`,commands:[`${t} ${Ir} --install`]},{comment:"Add the skill for Claude Code",commands:[`${t} ${Ir} --install --dir .claude/skills`]}],np=t=>new Vt.Command().name(Ir).summary("Print or install the agent skill for this CLI").description(`Print SKILL.md of the ${pt} skill, which tells coding agents how to use this CLI, or install the skill in the project.
58
+ reports being converted.`).addHelpText("after",y(re(t))).addOption(su).addOption(G()).addOption(it()).addOption(iu).addOption(au).addOption(cu).addOption(pu).addOption(uu).addOption(du).addOption(N()).addOption(mu).addOption(Cr()).addOption(yr(Og)).addOption(wr("(required with --input-format junit)")).addOption(_r).addOption(Rr).action(r=>fu(r));var jr="run",Gr=t=>[{comment:"Attach the Docker logs of a CI machine to the run, after the tests finished",commands:[`${t} ${jr} attach --key <record-key> --project-id <id> --ci-build-id <build-id> --machine-id shard-1 docker-logs.zip`]},{comment:"Attach a screenshot to the first attempt of a test",commands:[`${t} ${jr} attach --key <record-key> --project-id <id> --ci-build-id <build-id> --spec tests/cart.spec.ts --test-title "adds an item" --attempt 0 screenshot.png`]}],xg=t=>new Hr.Command().name("attach").addHelpText("after",y(Gr(t))).description("Upload files to a run recorded in CI").argument("<paths...>",Br).addOption(G(te)).addOption(st(ee)).addOption(it()).addOption(Lp).addOption(Bp).addOption(Gp).addOption(Jp).addOption(Kp).addOption(qp).addOption(Qp).addOption(Fr).addOption(kr).addOption(N()).action(async(e,r)=>{await R(async({key:n,...o})=>{await Np(ep({...o,recordKey:n}),e)},r)}),hu=t=>{let e=`${t} ${jr} share <run-id>`,r=`${e} --instance-id <instance-id> --test-id <test-id> --purpose fix`;return[{comment:"Share a whole run with a reviewer or a colleague outside Currents",commands:[e]},{comment:"Give an agent the failures of a whole run",commands:[`${e} --purpose fix`]},{comment:"Share one spec file, e.g. the copy that ran in the firefox group",commands:[`${e} --instance-id <instance-id>`]},{comment:"Give an agent one failing test (its last failed attempt)",commands:[r]},{comment:"Give an agent one specific attempt of a test",commands:[`${r} --attempt 0`]}]},Sg=t=>new Hr.Command().name("share").usage("<run-id> [options]").summary("Print a public link to a run, a spec file or a test").description('Create a public link to a run, or to one spec file or test of it, and print it. The second line, "Markdown: <url>", is the same content as Markdown, for agents').addHelpText("after",y(hu(t))).argument("<run-id>","the run to share").addOption(eu).addOption(ru).addOption(nu).addOption(ou).addOption(tu).addOption(st("(required; needs write access)")).addOption(N()).action(async(e,r)=>{await R(async n=>{await Dp(rp({...n,runId:e}))},r)}),Eu=t=>new Hr.Command().name(jr).summary("Upload results, attach files, get, share or cancel a run").description("Upload test results to a run, attach files to it, get its data, share a link to it or cancel it").addHelpText("after",y([...re(t).slice(0,2),Gr(t)[0],Vn(t)[0],hu(t)[0],Ce(t)[0]])).showHelpAfterError("(add --help for additional information)").addCommand($r(t)).addCommand(xg(t)).addCommand(qn(t)).addCommand(Sg(t)).addCommand(Tr(t));var be=require("@commander-js/extra-typings");var Kr="session",ne=t=>{let e=`${t} ${Kr} start --api-key <api-key> --project-id <id> --title "Checkout fails on empty cart" --status failed`,r=`${t} ${Kr} attach before.png .playwright-mcp/traces`,n=`${t} ${Kr} share --expires-in-days 7`;return{session:[{comment:"Start a session, attach what you captured and get a link to share",commands:[e,r,n]}],start:[{comment:"Start a session for a failed check",commands:[e]}],attach:[{comment:"Attach a screenshot and a Playwright MCP trace folder",commands:[r]}],share:[{comment:"Print a link that expires in 7 days",commands:[n]}]}},Ag=t=>new be.Command().name("start").addHelpText("after",y(ne(t).start)).summary("Create a session").description('Create a session and save its ID to .currents-session/session.json in the current folder, where "attach" and "share" read it').addOption(G(te)).addOption(st(ee)).addOption(it()).addOption(Fp).addOption(kp).addOption(Mp).addOption($p).addOption(jp).addOption(Hp).addOption(N()).action(async e=>{await R(async({key:r,...n})=>{n.json&&Jt(),await Ap(Xc({...n,recordKey:r}))},e)}),bg=t=>new be.Command().name("attach").summary("Upload screenshots, traces and other files").addHelpText("after",y(ne(t).attach)).description("Upload files, folders or a Playwright MCP trace folder to the session").argument("<paths...>",Br).addOption(G(te)).addOption(st(ee)).addOption(fo).addOption(zp).addOption(Fr).addOption(kr).addOption(N()).action(async(e,r)=>{await R(async({key:n,...o})=>{await bp(Zc({...o,recordKey:n}),e)},r)}),Pg=t=>new be.Command().name("share").addHelpText("after",y(ne(t).share)).summary("Print a public link to the session page").description('Create a public link to the session page and print it. The second line, "Markdown: <url>", is the address of the same content as Markdown, for agents').addOption(G(te)).addOption(st(ee)).addOption(fo).addOption(Zp).addOption(N()).action(async e=>{await R(async({key:r,...n})=>{await Pp(tp({...n,recordKey:r}))},e)}),Iu=t=>new be.Command().name(Kr).summary("Capture agent or browser sessions as evidence").description("Capture ad-hoc, one-off agent or browser sessions as evidence: a bug before and after a fix, or proof that something works. Create a session, attach screenshots, traces, videos and other files to it, and print a link to share it.").addHelpText("after",y(ne(t).session)).showHelpAfterError("(add --help for additional information)").addCommand(Ag(t)).addCommand(bg(t)).addCommand(Pg(t));var se=require("@commander-js/extra-typings");var yt=g(require("fs/promises")),W=g(require("path"));var ft="currents-cli",oe=W.default.join(".agents","skills");function Tu(t=__dirname){let e=W.default.join("skills",ft),r=ke(W.default.join(e,"SKILL.md"),t);if(!r)throw new Error(`The ${ft} skill is missing from this package`);return W.default.join(r,e)}async function Eo(t,e=""){let r=[];for(let n of await yt.default.readdir(W.default.join(t,e),{withFileTypes:!0})){let o=W.default.join(e,n.name);n.isDirectory()?r.push(...await Eo(t,o)):r.push(o)}return r.sort()}async function Ug(t,e){let[r,n]=await Promise.all([Eo(t),Eo(e)]);if(r.join(`
59
+ `)!==n.join(`
60
+ `))return!1;for(let o of r){let[s,i]=await Promise.all([yt.default.readFile(W.default.join(t,o)),yt.default.readFile(W.default.join(e,o))]);if(!s.equals(i))return!1}return!0}async function Cu(){await pe(await yt.default.readFile(W.default.join(Tu(),"SKILL.md"),"utf8"))}async function yu({dir:t=oe,force:e=!1}){let r=Tu(),n=W.default.resolve(t,ft),o=W.default.relative(process.cwd(),n)||".";if(await P(n)){if(!(await yt.default.stat(n)).isDirectory())throw new Error(`${o} exists and is not a folder`);if(await Ug(r,n))return C("The %s skill is already in %s",ft,o),n;if(!e)throw new Error(`${o} exists and differs from the skill of this version. Pass --force to replace it`);await yt.default.rm(n,{recursive:!0,force:!0})}return await yt.default.cp(r,n,{recursive:!0,verbatimSymlinks:!0}),C("Wrote the %s skill to %s",ft,o),n}var Jr="skill",Dg=t=>[{comment:"Print the skill",commands:[`${t} ${Jr}`]},{comment:`Add the skill to the project, in ${oe}/${ft}`,commands:[`${t} ${Jr} --install`]},{comment:"Add the skill for Claude Code",commands:[`${t} ${Jr} --install --dir .claude/skills`]}],Ru=t=>new se.Command().name(Jr).summary("Print or install the agent skill for this CLI").description(`Print SKILL.md of the ${ft} skill, which tells coding agents how to use this CLI, or install the skill in the project.
57
61
 
58
62
  Agents read project skills from these folders:
59
- Codex, Cursor ${Jt}
60
- Claude Code .claude/skills`).addHelpText("after",y(el(t))).addOption(new Vt.Option("--install",`write the skill folder to <dir>/${pt}`)).addOption(new Vt.Option("--dir <path>","the skills folder to install to").default(Jt)).addOption(new Vt.Option("--force","replace an installed copy of the skill that differs from this version")).action(async e=>{await R(async r=>{if(!r.install&&(r.force||r.dir!==Jt))throw new Error("--dir and --force work with --install only");r.install?await op({dir:r.dir,force:r.force}):await rp()},e)});var O="currents",ip=()=>{let t=gr(O),e=new sp.Command(O).version(At).description("Currents CLI: upload test results and files to Currents, get and cancel runs, capture agent or browser sessions as evidence, and cache files between CI jobs").showHelpAfterError(`(run '${O} --help' for usage)`).enablePositionalOptions().hook("preAction",(i,c)=>{jn(c),$n(c)}).addCommand(t,{hidden:!0}).addCommand(ja(O),{hidden:!0}).addCommand(We(O,{deprecated:!0}),{hidden:!0}).commandsGroup("Test runs:").addCommand(Zc(O)).commandsGroup("Evidence:").addCommand(tp(O)).commandsGroup("CI utilities:").addCommand(ua(O)).commandsGroup("Other:").addCommand(pa(O)).addCommand(Ha(O)).addCommand(np(O)).helpCommand(!0).addHelpText("after",`${y([Kt(O)[0],Kt(O)[1],Je(O)[1],Ve(O)[1],oe(O)[0],hr(O)[0],...Ht(O).session])}
61
- Run '${O} <command> --help' for the options and examples of a command.
63
+ Codex, Cursor ${oe}
64
+ Claude Code .claude/skills`).addHelpText("after",y(Dg(t))).addOption(new se.Option("--install",`write the skill folder to <dir>/${ft}`)).addOption(new se.Option("--dir <path>","the skills folder to install to").default(oe)).addOption(new se.Option("--force","replace an installed copy of the skill that differs from this version")).action(async e=>{await R(async r=>{if(!r.install&&(r.force||r.dir!==oe))throw new Error("--dir and --force work with --install only");r.install?await yu({dir:r.dir,force:r.force}):await Cu()},e)});var A="currents",_u=()=>{let t=$r(A),e=new wu.Command(A).version(Bt).description("Currents CLI: upload test results and files to Currents, get, share and cancel runs, capture agent or browser sessions as evidence, and cache files between CI jobs").showHelpAfterError(`(run '${A} --help' for usage)`).enablePositionalOptions().hook("preAction",(i,a)=>{Fs(a),ks(a)}).addCommand(t,{hidden:!0}).addCommand(qc(A),{hidden:!0}).addCommand(Tr(A,{deprecated:!0}),{hidden:!0}).commandsGroup("Test runs:").addCommand(Eu(A)).commandsGroup("Evidence:").addCommand(Iu(A)).commandsGroup("CI utilities:").addCommand(hc(A)).commandsGroup("Other:").addCommand(lc(A)).addCommand(Qc(A)).addCommand(Ru(A)).helpCommand(!0).addHelpText("after",`${y([re(A)[0],re(A)[1],hr(A)[1],Er(A)[1],Ce(A)[0],Gr(A)[0],...ne(A).session])}
65
+ Run '${A} <command> --help' for the options and examples of a command.
62
66
 
63
- Agent skill: ${O} skill --install
67
+ Agent skill: ${A} skill --install
64
68
  Documentation: https://docs.currents.dev
65
69
  Support: support@currents.dev
66
- `),r=`upload is no longer the default command. Run '${O} run upload ...' instead.`,o=t.options.flatMap(i=>[i.long,i.short]),n=e,s=n.unknownOption.bind(e);return n.unknownOption=i=>{if(!o.includes(i.split("=")[0]))return s(i);e.error(r)},e.addHelpText("before",({error:i})=>i&&(process.env.CURRENTS_RECORD_KEY||process.env.CURRENTS_PROJECT_ID)?`error: ${r}
67
- `:""),e};import("dotenv/config");function rl(){ip().parse()}rl();
70
+ `),r=`upload is no longer the default command. Run '${A} run upload ...' instead.`,n=t.options.flatMap(i=>[i.long,i.short]),o=e,s=o.unknownOption.bind(e);return o.unknownOption=i=>{if(!n.includes(i.split("=")[0]))return s(i);e.error(r)},e.addHelpText("before",({error:i})=>i&&(process.env.CURRENTS_RECORD_KEY||process.env.CURRENTS_PROJECT_ID)?`error: ${r}
71
+ `:""),e};function Ng(){_u().parse()}Ng();
68
72
  /*! For license information please see index.js.LEGAL.txt */
69
73
  //# sourceMappingURL=index.js.map