@currents/playwright
Version:
[Currents](https://currents.dev/playwright) is the most popular and advanced cloud-based platform for Playwright - debugging, error analysis, real-time analytics, orchestration, and more
111 lines (85 loc) • 56.3 kB
JavaScript
#! /usr/bin/env node
"use strict";var wn=Object.create;var De=Object.defineProperty;var Cn=Object.getOwnPropertyDescriptor;var Tn=Object.getOwnPropertyNames;var bn=Object.getPrototypeOf,On=Object.prototype.hasOwnProperty;var p=(e,t)=>()=>(e&&(t=e(e=0)),t);var Jt=(e,t)=>{for(var r in t)De(e,r,{get:t[r],enumerable:!0})},Rn=(e,t,r,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of Tn(t))!On.call(e,s)&&s!==r&&De(e,s,{get:()=>t[s],enumerable:!(o=Cn(t,s))||o.enumerable});return e};var u=(e,t,r)=>(r=e!=null?wn(bn(e)):{},Rn(t||!e||!e.__esModule?De(r,"default",{value:e,enumerable:!0}):r,e));var n=p(()=>{"use strict"});var ae,Kt=p(()=>{"use strict";n();ae=class extends Error{}});var Vt,Xt=p(()=>{"use strict";n();Vt={guide:{ciBuildId:"https://docs.currents.dev/guides/ci-build-id",integration:"https://docs.currents.dev/integration-with-playwright/currents-playwright"}}});function Yt(e){vn.push(e)}var vn,_e=p(()=>{"use strict";n();vn=[]});function er(e){return{...e&&Object.prototype.hasOwnProperty.call(Zt,e)?Zt[e]:Qt}}var D,Sn,xn,Qt,Zt,ce=p(()=>{"use strict";n();D={None:"none",Summary:"summary",Detailed:"detailed"},Sn={introAndSummary:!1,testOutput:!1,progress:!1,tables:!1,warningsAndErrors:!1},xn={introAndSummary:!0,testOutput:"line",progress:!1,tables:!1,warningsAndErrors:!0},Qt={introAndSummary:!0,testOutput:"full",progress:!0,tables:!0,warningsAndErrors:!0},Zt={[D.None]:Sn,[D.Summary]:xn,[D.Detailed]:Qt}});var tr,rr,or=p(()=>{"use strict";n();tr=[],rr=[]});function Ue(e){Ne=e}function En(e){return Ne?!!Ne[e]:!0}function M(e,t){Yt(t),En(e)&&console.log(t)}function Ae(e,t){return`${nr}8;;${e}${sr}${t}${nr}8;;${sr}`}var R,J,Ne,h,f,ir,y,pe,In,K,Xs,Ys,Zs,Qs,ei,ti,ri,oi,ni,a,si,nr,sr,ar=p(()=>{"use strict";n();R=u(require("chalk")),J=u(require("util"));ce();O();_e();or();Ne=null;h=(...e)=>{M("introAndSummary",J.default.format(...e))},f=(...e)=>{let t=J.default.format(...e);rr.push(t),g("WARNING: ",t),M("warningsAndErrors",R.default.bgYellow.black(" WARNING ")+" "+t)},ir=(...e)=>{M("introAndSummary",R.default.green.bold(J.default.format(...e)))},y=(...e)=>{let t=J.default.format(...e);tr.push(t),g("ERROR: ",t),M("warningsAndErrors",R.default.bgRed.white(" ERROR ")+" "+t)},pe=()=>{M("introAndSummary",`
`+In()+`
`)},In=()=>R.default.dim(Array(64).fill("=").join("")),K=(e=2)=>{let t=Math.max(0,Math.floor(e));t!==0&&M("introAndSummary",Array(t).fill("").join(`
`))},Xs=R.default.cyan,Ys=R.default.blueBright,Zs=R.default.red,Qs=R.default.yellow,ei=R.default.green,ti=R.default.gray,ri=R.default.white,oi=R.default.black,ni=R.default.magenta,a=R.default.dim,si=R.default.bold,nr="\x1B]",sr="\x1B\\"});var x=p(()=>{"use strict";n();_e();ar()});function ue(e){if(!e)return;if(e==="false")return!1;let t=parseInt(e,10);if(isNaN(t)||t<1)throw new Fe.CommanderError(255,"Invalid argument provided.","--pwc-cancel-after-failures must be a positive integer or 'false', provided: "+e);return t}function pr(e){if(!e)return;let t=["SIGUSR1","SIGUSR2"];if(!t.includes(e.toUpperCase().trim()))throw new Fe.CommanderError(255,"Invalid argument provided.","--pwc-reset-signal must be one of ("+t.join(", ")+"), provided: "+e);return e.toUpperCase().trim()}var Fe,Le=p(()=>{"use strict";n();Fe=require("commander")});function v(e){return T[e]?.env}function ur(e){let t=T[e];return"cli"in t?t.cli:void 0}function lr(e){return T[e].name}function je(){return{projectId:process.env[T.projectId.env],recordKey:process.env[T.recordKey.env],ciBuildId:process.env[T.ciBuildId.env],tag:process.env[T.tag.env]?process.env[T.tag.env]?.split(",").map(e=>e.trim()):void 0,environment:process.env[T.environment.env],cancelAfterFailures:ue(process.env[T.cancelAfterFailures.env]),disableTestTags:process.env[T.disableTestTags.env]||process.env[T.disableTitleTags.env],consoleOutput:process.env[T.consoleOutput.env],testSuiteFile:process.env[T.testSuiteFile.env],machineId:process.env[T.machineId.env],orchestrationId:process.env[T.orchestrationId.env],outputFile:process.env[T.outputFile.env],ciUrl:process.env[T.ciUrl.env]?.trim()||void 0,orchestration:{discoveryFile:process.env[T.discoveryFile.env]}}}var T,$e=p(()=>{"use strict";n();Le();T={currentsConfigFile:{name:"Currents Config File Path",env:"CURRENTS_CONFIG_FILE_PATH",cli:"--pwc-config"},ciBuildId:{name:"CI Build ID",env:"CURRENTS_CI_BUILD_ID",cli:"--ci-build-id"},recordKey:{name:"Record Key",env:"CURRENTS_RECORD_KEY",cli:"--key"},projectId:{name:"Project ID",env:"CURRENTS_PROJECT_ID",cli:"--project-id"},tag:{name:"Currents Tag",env:"CURRENTS_TAG",cli:"--tag"},environment:{name:"Currents Environment",env:"CURRENTS_ENVIRONMENT",cli:"--pwc-environment"},cancelAfterFailures:{name:"Currents Cancel After Failures",env:"CURRENTS_CANCEL_AFTER_FAILURES",cli:"--pwc-cancel-after-failures"},disableTestTags:{name:"Disable Test Tags",env:"CURRENTS_DISABLE_TEST_TAGS",cli:"--pwc-disable-test-tags"},disableTitleTags:{name:"Disable Title Tags",env:"CURRENTS_DISABLE_TITLE_TAGS",cli:"--pwc-disable-title-tags"},testSuiteFile:{name:"Test Suite File",env:"CURRENTS_TEST_SUITE_FILE",cli:"--pwc-test-suite-file"},machineId:{name:"Machine ID",env:"CURRENTS_MACHINE_ID",cli:"--pwc-machine-id"},orchestrationId:{name:"Orchestration ID",env:"CURRENTS_ORCHESTRATION_ID",cli:"--pwc-orchestration-id"},outputFile:{name:"Output File",env:"CURRENTS_OUTPUT_FILE",cli:"--pwc-output-file"},consoleOutput:{name:"Console Output",env:"CURRENTS_CONSOLE_OUTPUT",cli:"--pwc-console-output"},batchSize:{name:"Batch Size",env:"CURRENTS_BATCH_SIZE",cli:"--pwc-batch-size"},discoveryFile:{name:"Discovery File",env:"CURRENTS_DISCOVERY_FILE",cli:"--pwc-discovery-file"},ciUrl:{name:"CI URL",env:"CURRENTS_CI_URL"}}});function le(e){return{ciBuildId:e.ciBuildId,projectId:e.projectId,recordKey:e.key,tag:e.tag,environment:e.pwcEnvironment,removeTitleTags:e.pwcRemoveTitleTags,cancelAfterFailures:e.pwcCancelAfterFailures,disableTestTags:e.pwcDisableTestTags||e.pwcDisableTitleTags,testSuiteFile:e.pwcTestSuiteFile,machineId:e.pwcMachineId,outputFile:e.pwcOutputFile,consoleOutput:e.pwcConsoleOutput,pwcConfigPath:e.pwcConfig,orchestration:{resetSignal:e.pwcResetSignal,skipReporterInjection:e.pwcSkipReporterInjection,batchSize:e.pwcBatchSize,discoveryFile:e.pwcDiscoveryFile},coverage:{projects:e.pwcCoverage,dir:e.pwcCoverageDir}}}function de(){if(Me)return Me;if(process.env.CURRENTS_PWC_CLI_CONFIG_PATH)try{let e=JSON.parse(fr.default.readFileSync(process.env.CURRENTS_PWC_CLI_CONFIG_PATH).toString());return dr("Options from serialized CLI config file: %o",e),Me=e,e}catch(e){return dr("Could not read CLI config file: %o",e),{}}return{}}var fr,dr,Me,He=p(()=>{"use strict";n();fr=u(require("fs"));O();dr=g.extend("cli-options-serializer");Me=null});function fe(e,t,r={validationFn:kn}){Be("reporter options: %o",e),Be("config file options: %o",t);let o={...E(We),...E(t),...E(e),...E(de()),...E(je()),orchestration:{...E(We.orchestration),...E(t?.orchestration),...E(e?.orchestration),...E(de().orchestration),...E(je().orchestration)},coverage:{...E(We.coverage),...E(t?.coverage),...E(e?.coverage),...E(de().coverage)}};o.disableTitleTags!==void 0&&(o.disableTestTags=o.disableTestTags||o.disableTitleTags),r.validationFn(o),V=o,Ue(er(V?.consoleOutput)),Be("resolved currents config: %o",V)}function kn(e){Pn.forEach(t=>{if(!e[t])throw y(`${lr(t)} is required for Currents Reporter. Use the following methods:
- environment variable: ${a(v(t))}
- CLI flag: ${a(ur(t))}
- reporter configuration option ${a(t)} in ${a("playwright.config.ts")}
\u{1F4D6} ${Vt.guide.integration}`),new ae("Missing required config variable")})}function E(e){return Object.entries(e??{}).reduce((t,[r,o])=>o===void 0?t:{...t,[r]:o},{})}function I(){return V}function gr(){Ue(null),V=null}var Be,Pn,We,V,qe=p(()=>{"use strict";n();O();Kt();Xt();x();ce();$e();He();ce();Be=g.extend("config"),Pn=["projectId","recordKey"],We={removeTitleTags:!1,disableTestTags:!1,consoleOutput:D.Detailed,orchestration:{skipReporterInjection:!1},coverage:{projects:!1}},V=null});var Dn,mr=p(()=>{"use strict";n();Dn=require("lodash");x()});var _=p(()=>{"use strict";n();qe();$e();He();mr()});var yr,hr=p(()=>{yr={name:"@currents/playwright",version:"2.3.3",main:"./dist/index.js",author:{name:"Currents Software Inc",email:"hello@currents.dev",url:"https://currents.dev"},license:"MIT",homepage:"https://currents.dev",repository:{type:"git",url:"https://github.com/currents-dev/currents-playwright-changelog.git"},scripts:{test:"vitest",rm:"rimraf dist",lint:'TIMING=1 eslint "**/*.ts*"',build:"tsup-node --minify --dts",dev:"tsup-node --watch --dts",release:"release-it --verbose","publish:npm":"npm run rm && npm run build && ./publish.js","release-ci":"npm run rm && npm run build && ./publish.js -t latest"},bin:{pwc:"./dist/bin/pwc.js","pwc-p":"./dist/bin/pwc-p.js"},devDependencies:{"@playwright/test":"^1.56.1","@release-it/conventional-changelog":"^11.0.1","@types/async-retry":"^1.4.5","@types/babel__code-frame":"^7.0.3","@types/debug":"^4.1.13","@types/getos":"^3.0.4","@types/istanbul-lib-coverage":"^2.0.6","@types/json-stringify-safe":"^5.0.3","@types/lodash":"^4.17.24","@types/pluralize":"^0.0.33","@types/proxy-from-env":"^1.0.4","@types/regexp.escape":"^2.0.0","@types/stack-utils":"^2.0.3","@types/tmp":"^0.2.6","@types/ws":"^8.18.1",eslint:"^10.5.0","eslint-config-custom":"*",msw:"^2.14.2","release-it":"^20.2.0",rimraf:"^6.1.3",tsup:"^8.5.0",typescript:"^6.0.3",vitest:"^4.1.9"},dependencies:{"@babel/code-frame":"^7.29.7","@commander-js/extra-typings":"^13.1.0","@currents/commit-info":"1.0.1-beta.0","async-retry":"^1.3.3",chalk:"^4.1.2",commander:"^13.1.0","date-fns":"^4.3.0",debug:"^4.4.3",dotenv:"^17.4.2",execa:"^9.6.0",getos:"^3.2.1","istanbul-lib-coverage":"^3.2.2",jiti:"2.7.0","json-stringify-safe":"^5.0.1","lil-http-terminator":"^1.2.3",lodash:"^4.18.1",nanoid:"^3.3.8","object-sizeof":"^2.6.5","p-debounce":"^2.1.0","p-map":"^4.0.0","p-queue":"6.6.2",pluralize:"^8.0.0","pretty-ms":"^7.0.1","proxy-from-env":"^1.1.0","regexp.escape":"^2.0.1","safe-regex2":"^5.1.1","source-map-support":"^0.5.21","stack-utils":"^2.0.6",tmp:"^0.2.7","tmp-promise":"^3.0.3","ts-pattern":"^5.8.0",undici:"^6.27.0",ws:"^8.21.0"},files:["dist","!**/*.map","!**/*/*.map","**/*.LEGAL.txt","!src/*.md","!src/**/*.md","LICENSE.md","README.md","CHANGELOG.md"],keywords:["playwright","playwright dashboard","cloud dashboard","reporter","currents","tests reporter","sorry cypress","ci"],exports:{".":{import:"./dist/index.js",require:"./dist/index.js"},"./discovery":{import:"./dist/reporters/discovery.js",require:"./dist/reporters/discovery.js"},"./orchestration":{import:"./dist/orchestration/index.js",require:"./dist/orchestration/index.js"},"./package.json":"./package.json"},engines:{node:">=18.17"},publishConfig:{access:"public",registry:"https://registry.npmjs.org"},"release-it":{npm:{publish:!1},github:{release:!0},plugins:{"@release-it/conventional-changelog":{preset:"angular",header:"# Changelog",ignoreVersion:!0,infile:"../../CHANGELOG.md"}},git:{commitMessage:"chore: release v${version}",tagName:"v${version}"},hooks:{"before:github:release":"npm run --prefix ../../ update-public-changelog"}}}});var X,ze=p(()=>{"use strict";n();hr();X=yr.version});var Ge,wr,Cr=p(()=>{"use strict";n();Ge=()=>process.env.CURRENTS_API_URL??"https://cy.currents.dev",wr=()=>3e4});var Nn,zi,Je=p(()=>{"use strict";n();Nn=u(require("ws"));O();zi=g.extend("ws")});var Tr,ea,br,Or=p(()=>{"use strict";n();Tr=u(require("events"));qe();O();Je();Ke();ea=g.extend("pubsub"),br=new Tr.default});var Ve,vr,Rr,Sr,xr=p(()=>{"use strict";n();x();Or();Ve={cancellationReason:null},vr=e=>{Ve.cancellationReason||(Ve.cancellationReason=e)},Rr=()=>Ve.cancellationReason,Sr=({showWarning:e=!0}={})=>{let t=Rr();t&&(e&&f("%s",t),br.emit("runCancelled",t))}});var Ke=p(()=>{"use strict";n();xr()});var Er,Y,Xe=p(()=>{"use strict";n();Er=require("nanoid"),Y=(0,Er.customAlphabet)("abcdefghijklmnopqrstuvwxyz",10)});var Ir,Un,Pr,kr=p(()=>{"use strict";n();Ir=require("ts-pattern"),Un={outcome:null,scannerConfig:null,currentsConfig:null,internalConfig:null},Pr=()=>Un});function H(e){if(e===null||typeof e!="object")return!1;let t=e;return typeof t.message!="string"?!1:t.response!==void 0&&t.response!==null?!(typeof t.response.status!="number"||t.response.headers!==void 0&&typeof t.response.headers!="object"):!!(typeof t.code=="string"&&Z.includes(t.code))}var Z,B=p(()=>{"use strict";n();Z=["ECONNABORTED","ECONNREFUSED","ECONNRESET","ETIMEDOUT","EPIPE","ENETUNREACH","EHOSTUNREACH","ENETRESET","ENOTFOUND","EAI_AGAIN"]});function Ur(e){(0,S.match)(e).when(H,An).otherwise(()=>{f("Unexpected error while sending network request: %s",e)})}function An(e){let t=e.response?.config??e.config;return(0,S.match)(e).with({code:"ECONNABORTED"},()=>{f("Network connection aborted")}).with({code:"ECONNREFUSED"},()=>{f("Network connection aborted")}).with({code:"ECONNRESET"},()=>{f("Network connection reset")}).with({code:"EPIPE"},()=>{f("Network connection reset")}).with({code:"ENETUNREACH"},()=>{f("Network connection aborted")}).with({code:"EHOSTUNREACH"},()=>{f("Network connection aborted")}).with({code:"ETIMEDOUT"},()=>{f("Network connection timeout")}).with({response:S.P.not(S.P.nullish)},r=>{Fn(r,{status:r.response.status,data:r.response.data})}).otherwise(()=>{f(`[currents] Unexpected network error: %s
%O`,e.message,{method:t?.method,url:t?.url,status:e.response?.status,payload:t?.data,requestId:Q(e)})})}function Fn(e,{status:t,data:r}){let o=e.response?.config??e.config,s=o?.method,i=o?.url;(0,S.match)(t).with(401,()=>{f(`[currents] ${s} ${i} - 401 Unauthorized Request from cloud service`)}).with(400,()=>{f(`[currents] ${s} ${i} - 400 Bad Request from cloud service:
%o`,r)}).with(429,()=>{f(`[currents] ${s} ${i} - 429 Too Many Requests from cloud service`)}).with(422,()=>{Ln(e,r)}).otherwise(()=>{f(`[currents] Unexpected network response: %s
%O`,e.message,{method:s,url:i,status:e.response?.status,requestId:Q(e)})})}function Ln(e,t){let r=e.response?.config??e.config;(0,S.match)(t).with({code:Ye.MISSING_SUITE,message:S.P.string,errors:S.P.array(S.P.string)},async o=>{let{message:s,errors:i}=o;K(1),y(...Dr(s,i)),ge({id:Y(),text:(0,_r.default)(Pr(),null,2)}).then(d=>{y(`Please share this URL with Currents support for further investigation:
${d}`)}).catch(d=>{f("Failed to upload debug artifact: %s",d)}),K(1)}).with({code:Ye.RUN_CANCELLED,message:S.P.string},o=>{vr(o.message),Sr()}).with({code:Ye.RUN_EXPIRED,message:S.P.string},o=>{f(o.message)}).with({message:S.P.string,errors:S.P.array(S.P.string)},o=>{let{message:s,errors:i}=o;K(1),f(...Dr(s,i)),K(1)}).otherwise(()=>{f(`[currents] Unexpected network response: %s
%O`,e.message,{method:r?.method,url:r?.url,status:e.response?.status,requestId:Q(e)})})}function Dr(e,t){return Nr.default.isString(e)?t?.length===0?[e]:[e,`
${(t??[]).map(r=>` - ${r}`).join(`
`)}
`]:["Unexpected network error"]}function Q(e){let t=e?.response?.headers;if(!(!t||typeof t!="object")){for(let[r,o]of Object.entries(t))if(r.toLowerCase()==="apigw-requestid")return Array.isArray(o)?o[0]:o}}var _r,Nr,S,Ye,Ze=p(()=>{"use strict";n();_r=u(require("json-stringify-safe")),Nr=u(require("lodash")),S=require("ts-pattern");Ke();Xe();x();Qe();kr();B();Ye={RUN_CANCELLED:"RUN_CANCELLED",RUN_EXPIRED:"RUN_EXPIRED",MISSING_SUITE:"MISSING_SUITE"}});function jr(e,t,r){let o=r.method?.toUpperCase(),s=r.url,i=Q(t),d=(0,Ar.default)(et(e)),m=`Network request '${o} ${s}' failed: '${t.message}'.${i?` Request ID: ${i}.`:""} Next attempt is in ${d} (${e}/${r["transport-retry"]?.retries??tt()}).`;Fr(m),f(m)}var Ar,Fr,et,Lr,tt,$r=p(()=>{"use strict";n();Ar=u(require("pretty-ms"));O();x();Ze();B();Fr=g.extend("http"),et=e=>{let t=[3e3,15e3,3e4];return t[Math.min(Math.max(e-1,0),t.length-1)]},Lr=e=>{if(Fr("isRetriableError: %o",{message:e.message,code:"code"in e?e.code:void 0,status:"response"in e?e.response?.status:void 0,headers:"response"in e?e.response?.headers:void 0,data:"response"in e?e.response?.data:void 0}),"code"in e&&e.code&&Z.includes(e.code))return!0;if(!H(e)||!e.response)return!1;let t=e.response.headers;return t==null||typeof t!="object"?!1:[429,500,502,503,504].includes(e.response.status??0)},tt=()=>3});function $n(e){let t=Br.default.getProxyForUrl(e);if(t)return jn("Using HTTP proxy %s for %s",t,e),Mr===t&&me||(Mr=t,me=new Hr.ProxyAgent(t)),me}function Wr(e,t){if(/^https?:\/\//i.test(t))return t;let r=e??"",o=r.endsWith("/")?r:`${r}/`,s=t.replace(/^\/+/,"");return new URL(s,o).href}function Mn(e){let t={};return e.forEach((r,o)=>{let s=t[o];s===void 0?t[o]=r:Array.isArray(s)?s.push(r):t[o]=[String(s),r]}),t}function Hn(e){for(let[t,r]of Object.entries(e))if(t.toLowerCase()==="content-type"){let o=Array.isArray(r)?r[0]:r;return typeof o!="string"?"":o.split(";")[0]?.trim()?.toLowerCase()??""}return""}function Bn(e,t){let r=t.toLowerCase();if(r.includes("application/json")||r.endsWith("+json"))return!0;let o=e.trim();return o.length?/^(?:\{|\[|"|-?\d|true$|false$|null$)/.test(o):!1}function Wn(e,t){if(!e.length)return null;if(Bn(e,t))try{return JSON.parse(e)}catch{return e}return e}function qn(e){let t=e;for(let r=0;r<8&&t&&typeof t=="object";r++){let o=t;if(o.name==="AbortError"||o.name==="TimeoutError"||typeof o.message=="string"&&/aborted|timeout/i.test(o.message))return!0;t=o.cause}return!1}function qr(e){if(!e||typeof e!="object")return;if(qn(e))return"ETIMEDOUT";let t=e,r=typeof t.message=="string"?t.message:"";if(t.name==="AbortError"||t.code==="UND_ERR_ABORTED"||t.code==="ABORT_ERR"||/aborted|timeout/i.test(r)||t.code==="UND_ERR_CONNECT_TIMEOUT"||t.code==="UND_ERR_HEADERS_TIMEOUT"||t.code==="UND_ERR_BODY_TIMEOUT")return"ETIMEDOUT";if(t.code==="UND_ERR_SOCKET")return"ECONNRESET";if(typeof t.code=="string"&&Z.includes(t.code))return t.code;if(t.cause)return qr(t.cause);if(/connection reset|other side closed|terminated|socket hang up/i.test(r))return"ECONNRESET"}function zn(e){return e instanceof rt.Readable}function Gn(e){return zn(e)?{body:rt.Readable.toWeb(e),duplex:"half"}:{body:e}}async function he(e,t,r){let o=$n(e),s,i;try{let C={method:t.method,headers:t.headers,signal:t.signal};if(t.body!==void 0){let P=Gn(t.body);C.body=P.body,P.duplex&&(C.duplex=P.duplex)}o!==void 0&&(C.dispatcher=o),s=await fetch(e,C),i=await s.text()}catch(C){let P=qr(C);throw{message:C instanceof Error?C.message:String(C),code:P,config:r}}let d=Mn(s.headers),m=Hn(d),b=Wn(i,m),w=s.status,A=s.statusText;if(!s.ok)throw{message:`Request failed with status code ${w}`,config:r,response:{status:w,statusText:A,headers:d,data:b,config:r}};return{data:b,status:w,statusText:A,headers:d,config:r}}var rt,Hr,Br,jn,Mr,me,ot=p(()=>{"use strict";n();rt=require("stream"),Hr=require("undici");O();B();Br=u(require("proxy-from-env")),jn=g.extend("http:transport"),Mr=null,me=null});function Yn(e){if(e){for(let[t,r]of Object.entries(e))if(t.toLowerCase()==="x-currents-idempotency-key"&&r!==void 0)return Array.isArray(r)?r[0]:String(r)}}function Zn(e,t){if(!e)return;let r=t.toLowerCase();for(let[o,s]of Object.entries(e))if(o.toLowerCase()===r&&s!==void 0)return Array.isArray(s)?s[0]:String(s)}function Qn(e){let t={};if(!e)return t;for(let[r,o]of Object.entries(e))o!==void 0&&(t[r.toLowerCase()]=Array.isArray(o)?o.join(", "):String(o));return t}function es(...e){if(typeof AbortSignal.any=="function")return AbortSignal.any(e);let t=new AbortController;for(let r of e){if(r.aborted)return t.abort(r.reason),t.signal;r.addEventListener("abort",()=>t.abort(r.reason),{once:!0})}return t.signal}async function ts(e){let t={...Xn,...e.currentsOptions};return!t.enableCompression||e.data===void 0||Buffer.isBuffer(e.data)||typeof e.data=="string"||(0,Kr.default)(e.data)<=t.compressThresholdBytes?e:{...e,data:await Vn((0,nt.default)(e.data)),headers:{...e.headers,"Content-Encoding":"gzip"}}}function rs(e){let{data:t}=e;if(t!==void 0)return Buffer.isBuffer(t)||typeof t=="string"?t:(0,nt.default)(t)}async function os(e){let t=e.baseURL??Ge(),r=e["transport-retry"]?.retries??tt(),o=Yn(e.headers)??(0,Jr.nanoid)(),s=await ts(e),i=rs(s),d=(s.method??"get").toUpperCase(),m=e.signal;if(m?.aborted)throw{message:m.reason?.message??"Request aborted",code:"ECONNABORTED",config:e};let b;for(let w=0;w<=r;w++){let A=s.timeout??wr(),C=AbortSignal.timeout(A),P=m?es(m,C):C,$=I(),k={...Qn(s.headers),...Kn,"accept-encoding":"gzip, deflate, br","x-currents-idempotency-key":o,"x-pwc-request-attempt":String(w),"x-currents-key":$?.recordKey??""};$?.orchestrationId&&(k["x-currents-orchestration-id"]=$.orchestrationId),$?.machineId&&(k["x-currents-machine-id"]=$.machineId),Zn(e.headers,"content-type")||(k["content-type"]=k["content-type"]??"application/json");let mn={...s,method:d,url:e.url,baseURL:t,headers:k},hn=Wr(t,e.url??""),zt={method:d,url:e.url,headers:k,data:Buffer.isBuffer(i)?"buffer":i};w?zr("network request retry: %o",Gr({...zt,isRetry:!0})):zr("network request: %o",Gr(zt));try{return await he(hn,{method:d,headers:k,body:i,signal:P},mn)}catch(ke){b=ke;let Gt=ke;if(!Lr(Gt)||w>=r)throw ke;jr(w+1,Gt,{...e,method:d}),await new Promise(yn=>setTimeout(yn,et(w+1)))}}throw b}function ns(){return{request:e=>os(e)}}function Yr(){return ye||(ye=ns(),ye)}function Gr(e){return{method:e.method,baseUrl:Ge(),url:e.url,data:e.isRetry?"<retry>":ss(e.data),headers:{...e.headers,"x-currents-key":"***"}}}function ss(e){let t=e;return t?.results?.raw?{...t,results:{...t.results,raw:"***"}}:e}var nt,Jr,Kr,Vr,Xr,zr,Jn,Kn,Vn,Xn,ye,Zr=p(()=>{"use strict";n();nt=u(require("json-stringify-safe")),Jr=require("nanoid"),Kr=u(require("object-sizeof")),Vr=require("util"),Xr=u(require("zlib"));_();O();ze();Cr();$r();ot();zr=g.extend("http"),Jn=1024*1024*1,Kn={"x-pw-version":"0.0.0","x-pwc-version":X},Vn=(0,Vr.promisify)(Xr.default.gzip),Xn={enableCompression:!1,compressThresholdBytes:Jn},ye=null});async function W(e,t=Yr){try{let r=await t().request(e);return Qr("network response: %o",{...eo.default.omit(r,"request","config"),url:r.config.url,method:r.config.method}),r}catch(r){let o=r;throw Qr("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}),Ur(o),o}}var eo,Qr,to=p(()=>{"use strict";n();eo=u(require("lodash"));O();Zr();Ze();Qr=g.extend("http")});var st=p(()=>{"use strict";n();to();B()});var ro={};Jt(ro,{getDebugUrl:()=>is});var is,oo=p(()=>{"use strict";n();st();is=({runId:e,type:t})=>W({method:"POST",url:"runs/debug-logs",data:{type:t,runId:e}}).then(r=>r.data)});function cs(e,t){return po({path:e,name:null,uploadUrl:t,contentType:"text/plain"},"text/plain")}async function po(e,t,r){let o=await so.default.readFile(e.path);return it("Uploading file %s",e.uploadUrl,{buffer:Buffer.byteLength(o)}),uo(o,e.uploadUrl,t,r)}async function ps(e,t,r){return it("Uploading buffer %s",e.name,{buffer:Buffer.byteLength(e.buffer)}),uo(e.buffer,e.uploadUrl,t,r)}function us(e){let t;try{t=new URL(e)}catch{throw new Error(`Invalid upload URL: ${e}`)}if(!["http:","https:"].includes(t.protocol))throw new Error(`Unsupported upload URL protocol: ${t.protocol||"unknown"}`);return e}async function ls(e,t,r,o){let s=us(t),i=e,d={"Content-Disposition":"inline","Content-Type":r};o?.compress&&(i=await as(e),d["Content-Encoding"]="gzip"),await he(s,{method:"PUT",headers:d,body:i},{method:"PUT",url:s,headers:d})}async function uo(e,t,r,o){await(0,no.default)(async()=>{await ls(e,t,r,o)},{retries:5,onRetry:(s,i)=>{if(it(`Upload failed %d out of 5 attempts: %s
%o`,i,s.message,s.response?.data),i===5){y(`Cannot upload after ${i} times: ${s.message}`);return}f(`Upload failed ${i} out of 5 attempts: ${s.message}`)}})}var no,so,io,ao,it,as,co,lo=p(()=>{"use strict";n();no=u(require("async-retry")),so=u(require("fs/promises")),io=require("util"),ao=require("zlib");O();ot();x();it=g.extend("upload"),as=(0,io.promisify)(ao.gzip),co=(s=>(s.PNG="image/png",s.WEBM="video/webm",s.TEXT="text/plain",s.ZIP="application/zip",s))(co||{})});var fo={};Jt(fo,{ContentType:()=>co,sendBuffer:()=>ps,sendPath:()=>po,uploadText:()=>cs});var go=p(()=>{"use strict";n();lo()});async function ge(e){let{getDebugUrl:t}=await Promise.resolve().then(()=>(oo(),ro));try{let{readUrl:r,uploadUrl:o}=await t({runId:e.id,type:"pw-debug"}),{uploadText:s,sendBuffer:i}=await Promise.resolve().then(()=>(go(),fo));return"text"in e&&await i({name:`${e.id}-discovery-debug.log`,buffer:Buffer.from(e.text,"utf-8"),contentType:"text/plain",uploadUrl:o},"text/plain"),"path"in e&&await s(e.path,o),r}catch{return null}}var at,ct=p(()=>{"use strict";n();at=u(require("debug"))});function ds(e){return e==="false"?!1:e==="remote"?"remote":e==="full"?"full":!!e}var mo,F,pt=p(()=>{"use strict";n();mo=require("@commander-js/extra-typings"),F=new mo.Option("--pwc-debug [boolean | 'remote' | 'full']","enable debug logs. Specify 'remote' to upload logs to Currents. Specify 'full' to dump the debug logs to stdout and upload to Currents.").argParser(ds).env("CURRENTS_DEBUG")});var ho,yo,wo=p(()=>{"use strict";n();ho=require("@commander-js/extra-typings");pt();yo=()=>new ho.Command().allowUnknownOption().allowExcessArguments(!0).addOption(F).helpOption(!1)});var N,Co,lt,To,bo,ut,U,ee=p(()=>{"use strict";n();N=u(require("debug")),Co=u(require("fs")),lt=u(require("path")),To=u(require("util")),bo=require("fs/promises");Xe();x();wo();ct();N.default.useColors=function(){return!1};ut=N.default.log,U=class e{constructor(t="core"){this.source=t;if(this.mode=yo().parse().opts().pwcDebug??!1,this.debug=(0,N.default)(`currents:remote-debug:${this.source}`),!this.mode)return this;if(!this.shouldEnableDebug())return this;let r=process.env.DEBUG?`${process.env.DEBUG},currents*`:"currents*";if(N.default.enable(r),!this.shouldUploadRemoteDebug())return this;let o=Y(),s=lt.default.resolve(".currents-debug"),i=lt.default.resolve(s,`${o}.log`);(0,bo.mkdir)(s,{recursive:!0}),h(a(`\u{1F47E} Initiated remote ${this.source} debug log collection:`),a(i));let d=Co.default.createWriteStream(i,{flags:"a"});return N.default.log=(...m)=>{this.mode&&(d.write(`${To.default.formatWithOptions({colors:!1},...m)}
`),this.shouldMuteLocalStdout()||ut(...m))},this.pipelines[o]={id:o,writeStream:d,type:this.source,tempFilePath:i},this}source;static instance;static factory(t="core"){return this.instance||(this.instance=new e(t)),this.instance}pipelines={};mode;debug;getDebugMode(){return this.mode}async finalize({runId:t}={runId:void 0}){try{let r=Object.keys(this.pipelines);r.length===0&&(this.debug("No debug pipelines found"),N.default.log=ut);for(let o of r)await this.uploadDebug(o,t??Y())}catch{}finally{N.default.log=ut}}async uploadDebug(t,r){let o=this.pipelines[t];if(!o){this.debug("No debug pipeline found for id %s",t);return}h(a(`\u{1F47E} ${o.type} debug log written:`),a(o?.tempFilePath));try{let s=await ge({id:r,path:o.tempFilePath});o?.writeStream.end(),h(a(`\u{1F47E} ${o.type} debug log uploaded:`),a(s))}catch(s){f(`Failed to upload ${o.type}} debug log ${a(o.tempFilePath)}: ${s.message}`)}}shouldEnableDebug(){return this.mode==="full"||this.mode==="remote"||this.mode===!0}shouldUploadRemoteDebug(){return this.mode==="full"||this.mode==="remote"}shouldMuteLocalStdout(){return this.mode==="remote"}}});var Qe=p(()=>{"use strict";n();ct();ee()});var g,O=p(()=>{"use strict";n();Qe();g=(0,at.default)("currents")});n();var yu=require("source-map-support/register");n();var qt=require("commander");O();x();ee();B();n();var qo=u(require("fs"));_();O();n();var dt=u(require("fs")),Oo=require("tmp-promise"),Ro=async()=>{let{path:e}=await(0,Oo.file)();return e};n();var te=require("@commander-js/extra-typings"),Ce=u(require("chalk")),Nt=require("commander");ze();x();n();var l=require("@commander-js/extra-typings"),vo=require("commander");_();Le();pt();var we=new l.Option("--pwc-config <path>","path to currents config file (currents.config.[ts|js])").env(v("currentsConfigFile")),ft=new l.Option("--ci-build-id <id>","the unique run identifier").env(v("ciBuildId")),gt=new l.Option("-k, --key <record-key>","your secret Record Key obtained from Currents").env(v("recordKey")),mt=new l.Option("-p, --project-id <project>","the project ID for results reporting obtained from Currents").env(v("projectId")),ht=new l.Option("-t, --tag <tag>","comma-separated tag(s) for recorded runs in Currents").argParser(Pt),yt=new l.Option("--pwc-environment <name>","run-level environment name for Currents (e.g. staging, prod)").env(v("environment")),wt=new l.Option("--pwc-remove-title-tags","remove tags from test names in Currents, e.g. `Test name @smoke` becomes `Test name` in the dashboard"),So=new l.Option("--pwc-disable-title-tags","[DEPRECATED] Use --pwc-disable-test-tags instead"),Ct=new l.Option("--pwc-disable-test-tags","disable reporting tags defined on the test or suite level, or extracted from the test title"),Tt=new l.Option("--pwc-cancel-after-failures <number | false>","abort the cloud run after the specified number of failed tests detected. Overrides the default Currents Project settings. If set, must be a positive integer or 'false' to disable automatic cancellations").env(v("cancelAfterFailures")).argParser(ue),bt=new l.Option("--pwc-output-file <string>","path to the file where the run summary output will be written.").env(v("outputFile")),Ot=new l.Option("--pwc-discovery-file <file>","path to the test discovery file shared by `pwc-p discover` and `pwc-p run`").env(v("discoveryFile")),xo=new l.Option("--list","ignored (discover always runs playwright with --list)").hideHelp(),Eo=new l.Option("--reporter <reporters>","ignored (discover always runs playwright with --reporter=list)").hideHelp(),Rt=new l.Option("--pwc-console-output <preset>","reporter console output: none (no stdout), summary (intro + one line per test + summary), detailed (full output)").choices(Object.values(D)).env(v("consoleOutput")),vt=new l.Option("--pwc-test-suite-file <path>","path to the full test suite file for orchestration and reporting").env(v("testSuiteFile")).hideHelp(),St=new l.Option("--pwc-machine-id <string>","unique identifier of the machine running the tests. If not provided, it will be generated automatically. See: https://docs.currents.dev/?q=machineId").env(v("machineId")),xt=new l.Option("--pwc-orchestration-id <string>","unique identifier of the orchestration session this run belongs to. See: https://docs.currents.dev/?q=orchestrationId").env(v("orchestrationId")).hideHelp();var Et=new l.Option("--pwc-inspect","enable inspect mode, run playwright with --inspect-brk flag or developments and debugging").default(!1).hideHelp(),Io=new l.Option("--pwc-reset-signal <'SIGUSR1' | 'SIGUSR2'>","specify a process signal to listen for to trigger a reset of the current in progress tests. Only avaiable on OSes with POSIX signal support.").argParser(pr),It=new l.Option("--reporter <reporter>","Reporter to use, comma-separated").argParser(Pt).hideHelp(),Po=new l.Option("-c, --config <file>","Playwright configuration file path"),ko=new l.Option("--tsconfig <path>","path to a single tsconfig applicable to all imported files"),Uc=new l.Option("--test-list <file>","path to a file containing a list of tests to run (Playwright --test-list)"),Ac=new l.Option("--project <name...>","only run tests from the specified Playwright projects (variadic)"),Do=new l.Option("-j, --workers <workers>","number of concurrent workers or percentage of logical CPU cores per shard"),_o=new l.Option("--timeout <ms>","per-test timeout in milliseconds"),No=new l.Option("--headed","run tests in headed browsers"),Uo=new l.Option("--fully-parallel","run all tests in parallel (Playwright fullyParallel)"),Ao=new l.Option("--output <dir>","directory for output artifacts"),Fo=new l.Option("--ignore-snapshots","ignore screenshot and snapshot expectations"),Lo=new l.Option("--fail-on-flaky-tests","fail the run if any test is flagged as flaky");function jo(e){return[...e.config?["--config",e.config]:[],...e.tsconfig?["--tsconfig",e.tsconfig]:[],...e.testList?["--test-list",e.testList]:[],...(e.project??[]).flatMap(t=>["--project",t])]}function $o(e){return[...e.config?["--config",e.config]:[],...e.tsconfig?["--tsconfig",e.tsconfig]:[],...e.testList?["--test-list",e.testList]:[],...e.workers?["--workers",e.workers]:[],...e.timeout?["--timeout",e.timeout]:[],...e.headed?["--headed"]:[],...e.fullyParallel?["--fully-parallel"]:[],...e.output?["--output",e.output]:[],...e.ignoreSnapshots?["--ignore-snapshots"]:[],...e.failOnFlakyTests?["--fail-on-flaky-tests"]:[]]}var Mo=new l.Option("--pwc-skip-reporter-injection","do not inject @currents/playwright reporter, use the reporters specified in the playwright configuration file");function Pt(e,t=[]){return e?t.concat(e.split(",").map(r=>r.trim())):t}var kt=new l.Option("--pwc-coverage [projects...]","comma-separated list of projects to collect coverage for, e.g. `project1,project2`. If no projects are specified, coverage will be collected for all projects.").argParser(Pt),Dt=new l.Option("--pwc-coverage-dir <path>","directory path for reading coverage reports"),Ho=new l.Option("--pwc-batch-size <'auto' | number>","set the number of parallel workers for orchestration; Use 'auto' to match the number of Playwright workers. If a number is provided, it must be a positive integer.").default("auto").env(v("batchSize")).argParser(e=>{if(e==="auto")return e;let t=Number(e);if(!isNaN(t)&&Number.isInteger(t)&&t>0)return t;throw new vo.InvalidArgumentError('Provide either "auto" or a positive integer.')});var Te=(e=At())=>e.version(X),be=`----------------------------------------------------
\u{1F4D6} Documentation: https://docs.currents.dev
\u{1F919} Support: support@currents.dev
----------------------------------------------------`,fs=`
${be}
${Ce.default.bold("Examples")}
Run all tests in the current directory:
${a("pwc --key <record-key> --project-id <id> --ci-build-id <build-id>")}
Run only tests filtered by the tag "@smoke":
${a("pwc --key <record-key> --project-id <id> --ci-build-id <build-id> --grep smoke")}
Run playwright tests and add tags "tagA", "tagB" to the recorded run:
${a("pwc --key <record-key> --project-id <id> --ci-build-id <build-id> --tag tagA --tag tagB")}
Provide playwright arguments and flags:
${a("pwc --key <record-key> --project-id <id> --ci-build-id <build-id> -- --workers 2 --timeout 10000 --shard 1/2")}
`,gs=`
Orchestration is a two-step process:
1. Select tests for orchestration: ${a("pwc-p discover --pwc-discovery-file <path>")}
2. Orchestrate the selected tests: ${a("pwc-p run --key <record-key> --project-id <id> --ci-build-id <build-id> --pwc-discovery-file <path>")}
Discovery file can be set by:
${a("--pwc-discovery-file <path>")} CLI flag
${a("CURRENTS_DISCOVERY_FILE")} environment variable
${a("orchestration.discoveryFile")} in currents.config
${Ce.default.bold("Examples")} (assuming you have a discovery file at tests.txt)
Orchestrate the selected tests:
${a("pwc-p run --key <record-key> --project-id <id> --ci-build-id <build-id> --pwc-discovery-file tests.txt")}
Extra Playwright runtime flags (supported subset only):
${a("pwc-p run --pwc-discovery-file tests.txt --key <record-key> --project-id <id> --ci-build-id <build-id> -j 4 --timeout 60000")}
Add tags "tagA", "tagB" to the recorded run:
${a("pwc-p run --pwc-discovery-file tests.txt --key <record-key> --project-id <id> --ci-build-id <build-id> --tag tagA --tag tagB")}
`,ms=`
${be}${gs}`,_t="https://docs.currents.dev/guides/ci-optimization/playwright-orchestration",hs=`
${be}
Orchestration is a two-step process:
1. Select tests for orchestration: ${a("pwc-p discover --pwc-discovery-file <path>")}
2. Orchestrate the selected tests: ${a("pwc-p run --key <record-key> --project-id <id> --ci-build-id <build-id> --pwc-discovery-file <path>")}
See ${a("pwc-p discover --help")} / ${a("pwc-p run --help")} for more details.`,ys="List Playwright tests, with filters and configuration of your choice; write results to a file for orchestration.",ws="Run Orchestration for the selected tests.",Cs=new Set(["--grep","-g","--grep-invert","-G","--last-failed"]);function Bo(e){return/unknown option '?([^'\s]+)'?/i.exec(e)?.[1]??null}function Ut(e){return e.code==="commander.helpDisplayed"||e.code==="commander.help"||e.code==="commander.version"}function Ts(e){if(!(e instanceof Nt.CommanderError))throw e;if(e.code==="commander.unknownOption"){let t=Bo(e.message);t&&Cs.has(t)&&(y(`pwc-p run does not accept Playwright filter flags (${t}) directly.
Run discovery first, then pass the list to pwc-p run:
`+a(" pwc-p discover --pwc-discovery-file tests.txt [...filters]")+`
`+a(" pwc-p run ... --pwc-discovery-file tests.txt")),process.exit(e.exitCode)),t==="--shard"&&(y("--shard conflicts with pwc-p orchestration. Remove --shard; pwc-p distributes work via the orchestration session."),process.exit(e.exitCode)),(t==="--update-snapshots"||t==="-u")&&(y(`--update-snapshots is not supported under pwc-p run (parallel shards would race on snapshot files).
Update snapshots in a single-process run instead:
`+a(" pwc --update-snapshots ...")+`
`+a(" playwright test --update-snapshots ...")),process.exit(e.exitCode))}throw e.code==="commander.excessArguments"&&(y(`pwc-p run does not support positional arguments (spec paths or test names).
Run discovery first, then pass the list to pwc-p run:
`+a(" pwc-p discover --pwc-discovery-file tests.txt [...]")+`
`+a(" pwc-p run ... --pwc-discovery-file tests.txt")),process.exit(e.exitCode)),e}function bs(e){if(!(e instanceof Nt.CommanderError))throw e;if(e.code==="commander.unknownOption"||e.code==="commander.unknownCommand"||e.code==="commander.excessArguments"){let r=e.code==="commander.unknownOption"?Bo(e.message):null,o=r?`${r}`:"file matching argument";y(`${o} should be used with pwc-p discover command.
pwc-p requires running "discover" command first. Example:
`+a(" pwc-p discover --pwc-discovery-file <filepath> [...filters]")+`
`+a(" pwc-p run --key <record-key> --project-id <id> --ci-build-id <build-id> --pwc-discovery-file <filepath>")+`
Documentation: ${Ae(_t,_t)}`),process.exit(e.exitCode)}throw e}var At=()=>new te.Command().name("pwc").usage("[options] [playwright arguments and flags]").allowUnknownOption().allowExcessArguments(!0).showHelpAfterError("(add --help for additional information)").description(`\u{1F3AD} Run Playwright tests on CI using https://currents.dev
${fs}`).addOption(ft).addOption(gt).addOption(mt).addOption(ht).addOption(yt).addOption(we).addOption(wt).addOption(Ct).addOption(So).addOption(Tt).addOption(bt).addOption(Rt).addOption(vt).addOption(St).addOption(xt).addOption(Et).addOption(F).addOption(kt).addOption(Dt).addOption(It).action(function(){this.opts().pwcDisableTitleTags&&f(`${a("--pwc-disable-title-tags")} has been renamed to ${a("--pwc-disable-test-tags")}.`)}),Os=()=>new te.Command().name("discover").usage("[options] [playwright arguments and flags]").allowUnknownOption().allowExcessArguments(!0).showHelpAfterError("(add --help for additional information)").summary(ys).description(`List Playwright tests and write result to a file for orchestration.
${be}
Destination file can be set by:
${a("--pwc-discovery-file <path>")} CLI flag
${a("CURRENTS_DISCOVERY_FILE")} environment variable
${a("orchestration.discoveryFile")} in currents.config
All CLI arguments and flags are forwarded to Playwright's ${a("list")} command: (${a("--grep")}, ${a("--config")}, ${a("--last-failed")}, ${a("--project")}, etc.)
${Ce.default.bold("Examples")}
List all tests, writing the list to a file:
${a("pwc-p discover --pwc-discovery-file tests.txt")}
List only tests matching a tag and playwright project:
${a("pwc-p discover --pwc-discovery-file tests.txt --grep @smoke --project chromium")}
Use the discovery file with ${a("pwc-p run")} command. See ${Ae(_t,"documentation")} for more details.
`).addOption(we).addOption(Ot).addOption(xo).addOption(Eo).addOption(F),Rs=()=>Te(Os()),vs=()=>new te.Command().name("run").usage("[options]").allowExcessArguments(!1).showHelpAfterError("(add --help for additional information)").exitOverride(Ts).summary(ws).description(`\u2728 Orchestrate \u{1F3AD} Playwright tests on CI using https://currents.dev
${ms}`).addOption(ft).addOption(gt).addOption(mt).addOption(Po).addOption(ht).addOption(yt).addOption(Do).addOption(No).addOption(Uo).addOption(Ao).addOption(_o).addOption(Fo).addOption(ko).addOption(Lo).addOption(we).addOption(wt).addOption(Ct).addOption(Tt).addOption(bt).addOption(Rt).addOption(vt).addOption(St).addOption(xt).addOption(Io).addOption(Et).addOption(F).addOption(It).addOption(Mo).addOption(kt).addOption(Dt).addOption(Ho).addOption(Ot);function Wo(e){let t=new te.Command().name("pwc-p").version(X).description(`\u2728 Orchestrate \u{1F3AD} Playwright tests on CI using https://currents.dev
${hs}`).allowExcessArguments(!1).exitOverride(bs).showHelpAfterError("(add --help for additional information)"),r=Rs();r.action(async function(){await e.discover(this)});let o=Te(vs());return o.action(async function(){this.opts().pwcDisableTitleTags&&f(`${a("--pwc-disable-title-tags")} has been renamed to ${a("--pwc-disable-test-tags")}.`),await e.run(this)}),t.addCommand(r),t.addCommand(o),t}var Ft=g.extend("cli-manager"),Oe=class{program;cliOptions;parsedConfig;configFilePath=null;constructor(t={isOrchestration:!1}){if(t.isOrchestration){if(!t.runCommand)throw new Error("CLIManager: orchestration mode requires `runCommand` (parsed `pwc-p run` Commander instance).");this.program=t.runCommand,this.cliOptions=t.runCommand.opts()}else this.program=Te(At()),this.cliOptions=this.program.parse().opts();Ft("CLI options: %o",this.cliOptions),this.parsedConfig=le(this.cliOptions),Ft("Parsed config from CLI options: %o",this.parsedConfig)}getCLIReporters(){return this.cliOptions.reporter?.filter(t=>!/@currents/.test(t))||[]}async getConfigFilePath(){if(this.configFilePath)return this.configFilePath;let t=await Ro();return qo.default.writeFileSync(t,JSON.stringify(this.parsedConfig)),Ft("CLI options temp file path: %s",t),this.configFilePath=t,this.configFilePath}};n();var Ko=u(require("crypto")),z=u(require("fs")),Vo=u(require("os")),ve=u(require("path"));_();n();var re=u(require("path")),zo=require("url"),Go=u(require("jiti")),Jo=[".ts",".js",".mjs"];function Ss(e){return e.replace(/\\/g,"/")}function Re(e){e||(e="currents.config");let t=process.cwd(),r=(0,Go.default)(t,{interopDefault:!0,cache:!1,extensions:[...Jo]}),o=xs(e,{cwd:t,jiti:r});return o?{config:o.config,configFile:Ss(o.configFile)}:{config:{},configFile:""}}function xs(e,t){let r=Es(e,t);if(!r)return null;let o=re.default.extname(r);if(!Jo.includes(o))return null;let s;try{s=t.jiti(r)}catch{return null}let i=s?.default??s??null;if(i instanceof Function){try{i=i()}catch{return null}i&&i instanceof Promise&&(i=null)}return{config:i??{},configFile:r}}function Es(e,t){let r=o=>{let s=t.jiti.esmResolve(o,{try:!0});return s?(0,zo.fileURLToPath)(s):void 0};return r(re.default.resolve(t.cwd,e))||r(re.default.resolve(t.cwd,".config",e.replace(/\.config$/,"")))||r(re.default.resolve(t.cwd,".config",e))||e}n();var Lt;async function q(){if(Lt)return Lt;let{execa:e}=await import("execa");return Lt=e,e}x();async function Xo(e){try{let t=e.opts(),r=Re(t.pwcConfig);fe(le(t),r.config,{validationFn:()=>{}});let o=I()?.orchestration?.discoveryFile,s=typeof o=="string"&&o.trim()||void 0,i=s?ve.default.resolve(process.cwd(),s):void 0;if(!i)return y("Discovery file is required. Set one of:"),h(""),h(a(" --pwc-discovery-file <file>")),h(""),h(a(" environment variable CURRENTS_DISCOVERY_FILE")),h(""),h(a(" currents.config: orchestration.discoveryFile")),h(""),1;let d=e.args;if(d.some(w=>w==="--shard"||w.startsWith("--shard=")))return y("--shard conflicts with pwc-p orchestration. Remove --shard; pwc-p distributes work via the orchestration session."),1;let b=ve.default.join(Vo.default.tmpdir(),`pwc-discover-${Ko.default.randomUUID()}.tmp`);try{let w=await q(),A=z.default.openSync(b,"w"),C;try{C=await w("playwright",["test","--list","--reporter=list",...d],{stdio:["inherit",A,"inherit"],reject:!1})}finally{z.default.closeSync(A)}if(C.exitCode!==0)return C.exitCode==null&&y(C.signal?`playwright discovery was terminated by signal ${C.signal}.`:"Failed to run `playwright test --list`. Is @playwright/test installed and on PATH?"),C.exitCode??1;try{z.default.mkdirSync(ve.default.dirname(i),{recursive:!0}),z.default.copyFileSync(b,i)}catch(P){return y("Failed to write discovery output: %o",P),1}}finally{z.default.rmSync(b,{force:!0})}return h(""),ir(`Discovery file written to: ${i}`),h(""),h("Execute orchestration for the discovered tests:"),h(a(` pwc-p run --key <record-key> --project-id <id> --ci-build-id <build-id> --pwc-discovery-file ${i}`)),0}finally{gr()}}n();var ln=u(require("fs")),dn=u(require("path")),Bt=require("ts-pattern");_();O();n();n();var Yo={resetSignalReceived:null},Zo=({resetSignalReceived:e})=>{Yo.resetSignalReceived=e},Qo=()=>Yo;x();n();var Ht=require("ts-pattern");_();O();ee();n();Je();n();var en=u(require("http"));O();var tn=u(require("lil-http-terminator")),Se=require("ts-pattern"),rn=u(require("ws")),G=g.extend("wss"),ne=null,oe=null,jt=null,L=()=>(0,Se.match)(ne?.address()).with({port:Se.P.number},e=>e.port).otherwise(()=>0),on=async()=>{if(G("terminating wss server: %d",L()),!jt){G("no wss server");return}let{success:e,code:t,message:r,error:o}=await jt.terminate();e||(t==="TIMED_OUT"&&o(r),t==="SERVER_ERROR"&&o(r,o),t==="INTERNAL_ERROR"&&o(r,o)),G("terminated wss server: %d",L())},nn=e=>{oe||(ne=en.default.createServer().on("listening",()=>{if(!ne)throw new Error("Server not initialized");oe=new rn.WebSocketServer({server:ne});let t=`wss://localhost:${L()}`;G("starting wss",t),oe.on("connection",function(o){o.on("message",function(i){G("received %s: %o",t,JSON.parse(i.toString())?.type),e.forEach(d=>d(i.toString()))})}),oe.on("close",()=>{G("wss closed"),oe=null})}).listen(),jt=(0,tn.default)({server:ne}))};n();var an=u(require("fs")),Ee=require("lodash"),Mt=u(require("tmp")),cn=u(require("regexp.escape"));_();O();n();var $t={OR8N_SUITE_FILE_PREFIX:"currents-or8n-",FIXTURES_DIR_PREFIX:"currents-fixtures-",FIXTURES_CONFIG_ERR_FILE:"config_fixture_error.log",FIXTURES_WARNING_FILE_PREFIX:"config_fixture_warning"};x();ee();n();st();var se=class{async create(t){return W({url:"/orchestration-v1",method:"POST",data:JSON.stringify(t)})}async createTask(t){return W({url:`/orchestration-v1/${t.id}/task`,method:"POST",data:JSON.stringify({machineId:t.machineId,runId:t.runId})})}async resetRun(t){return W({url:`/runs/v1/${t.runId}/reset`,method:"PUT",data:JSON.stringify({...t,isBatchedOr8n:!0})})}};var sn=g.extend("or8n-task-executor"),xe=class{constructor(t,r,o,s,i,d,m,b=new se){this.cliManager=t;this.or8nId=r;this.runId=o;this.machineId=s;this.suite=i;this.resolve=d;this.reject=m;this.batchedOrchestrationAPI=b;"CURRENTS_OR8N_EVENT_MODE"in process.env&&(this.runInEventMode=process.env.CURRENTS_OR8N_EVENT_MODE==="true")}cliManager;or8nId;runId;machineId;suite;resolve;reject;batchedOrchestrationAPI;suiteFile=null;fixturesDir=null;taskResultList=[];taskResultPromiseList=[];orchestrationStatus=Is;runInEventMode=!0;runOrchestrationLoop(){return this.suiteFile||(this.suiteFile=Mt.default.fileSync({prefix:$t.OR8N_SUITE_FILE_PREFIX,postfix:".json"}),an.default.writeFileSync(this.suiteFile.name,JSON.stringify(this.suite,null,2))),this.fixturesDir||(this.fixturesDir=Mt.default.dirSync({prefix:$t.FIXTURES_DIR_PREFIX,unsafeCleanup:!0})),this.batchTaskLoopImpl()}async batchTaskLoopImpl(){try{if(Qo().resetSignalReceived){pe(),h(`\u{1F6A5} Machine ${a(this.machineId)} has stopped processing tasks due to a reset signal.`),this.resolveTaskLoop();return}let{data:t}=await this.batchedOrchestrationAPI.createTask({machineId:this.machineId,id:this.or8nId,runId:this.runId});if(t.run&&(this.orchestrationStatus.specs=t.run.progress.specs,this.orchestrationStatus.tests=t.run.progress.tests,pe(),h([` Orchestration progress: ${a(`${t.run?.progress?.specs?.completed??"-"}/${t.run?.progress?.specs?.overall??"-"} spec files completed`)}`].join(`
`))),!t.batch){await this.gracefullyResolveTaskLoop(),pe(),h("\u{1F3C1} Orchestration session finished");return}let r=t.batch.groupId,o=(0,Ee.orderBy)(t.batch.tasks,"score","desc"),s=t.batch?.tasks?.[0]?.batchSize;h(["",`\u{1F310} Executing orchestrated task: ${a(`[${r}] ${o.map(m=>m.spec).join(", ")} `)}`,`\u2139\uFE0F Batch size: ${s}`].join(`
`));let i=this.runPWTask({task:{spec:o.map(m=>({spec:m.spec,workerIndex:m.workerIndex})),groupId:r},suiteFilePath:this.suiteFile.name,fixturesDir:this.fixturesDir.name});this.taskResultPromiseList.push(i);let d=await i;o.forEach(m=>{this.taskResultList.push({task:{spec:m.spec,groupId:r},exitStatus:d.exitCode??1})})}catch(t){this.reject(t)}this.runInEventMode||(sn("Running in loop mode, executing the orchestration loop again"),this.runOrchestrationLoop())}async runPWTask({task:t,suiteFilePath:r,fixturesDir:o}){let s=I(),i=this.cliManager.cliOptions,d=["test",...s?.orchestration?.skipReporterInjection?[]:["--reporter",[...this.cliManager.getCLIReporters(),"@currents/playwright"].join(",")],`--project=${t.groupId}`,...$o(i),...this.orderSpecsByWorkerIndex(t.spec).map(b=>(0,cn.default)(b))],m={...process.env,CURRENTS_PWCP_WSS_PORT:L().toString(),CURRENTS_MACHINE_ID:this.machineId,CURRENTS_ORCHESTRATION_ID:this.or8nId,CURRENTS_PWC_CLI_CONFIG_PATH:await this.cliManager.getConfigFilePath(),CURRENTS_TEST_SUITE_FILE:r,CURRENTS_FIXTURES_TMP_DIR:o,CURRENTS_CI_BUILD_ID:s?.ciBuildId,CURRENTS_DEBUG:String(U.factory("pwc-p").getDebugMode()),CURRENTS_OR8N_EVENT_MODE:this.runInEventMode};return s?.outputFile&&(m.CURRENTS_OR8N_SEND_RESULTS_TO_WSS="true"),sn("Running task %o",d),(await q())("playwright",d,{stdio:"inherit",reject:!1,env:m})}orderSpecsByWorkerIndex(t){let r=(0,Ee.groupBy)(t,o=>o.workerIndex.toString());return Object.keys(r).sort().map(o=>r[o]).flat().map(o=>o.spec)}async g