@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
109 lines (83 loc) • 60.1 kB
JavaScript
#! /usr/bin/env node
"use strict";var kn=Object.create;var Ne=Object.defineProperty;var Pn=Object.getOwnPropertyDescriptor;var _n=Object.getOwnPropertyNames;var Nn=Object.getPrototypeOf,Dn=Object.prototype.hasOwnProperty;var u=(e,t)=>()=>(e&&(t=e(e=0)),t);var Yt=(e,t)=>{for(var r in t)Ne(e,r,{get:t[r],enumerable:!0})},Un=(e,t,r,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of _n(t))!Dn.call(e,s)&&s!==r&&Ne(e,s,{get:()=>t[s],enumerable:!(o=Pn(t,s))||o.enumerable});return e};var p=(e,t,r)=>(r=e!=null?kn(Nn(e)):{},Un(t||!e||!e.__esModule?Ne(r,"default",{value:e,enumerable:!0}):r,e));var n=u(()=>{"use strict"});var ae,Zt=u(()=>{"use strict";n();ae=class extends Error{}});var Qt,er=u(()=>{"use strict";n();Qt={guide:{ciBuildId:"https://docs.currents.dev/guides/ci-build-id",integration:"https://docs.currents.dev/integration-with-playwright/currents-playwright"}}});function tr(e){An.push(e)}var An,De=u(()=>{"use strict";n();An=[]});function nr(e){return{...e&&Object.prototype.hasOwnProperty.call(rr,e)?rr[e]:or}}var N,Fn,Ln,or,rr,ce=u(()=>{"use strict";n();N={None:"none",Summary:"summary",Detailed:"detailed"},Fn={introAndSummary:!1,testOutput:!1,progress:!1,tables:!1,warningsAndErrors:!1},Ln={introAndSummary:!0,testOutput:"line",progress:!1,tables:!1,warningsAndErrors:!0},or={introAndSummary:!0,testOutput:"full",progress:!0,tables:!0,warningsAndErrors:!0},rr={[N.None]:Fn,[N.Summary]:Ln,[N.Detailed]:or}});var sr,ir,ar=u(()=>{"use strict";n();sr=[],ir=[]});function Ae(e){Ue=e}function $n(e){return Ue?!!Ue[e]:!0}function M(e,t){tr(t),$n(e)&&console.log(t)}function Fe(e,t){return`${cr}8;;${e}${pr}${t}${cr}8;;${pr}`}var v,J,Ue,m,l,ur,w,pe,jn,K,di,fi,gi,mi,hi,yi,wi,Ti,Ci,a,bi,cr,pr,lr=u(()=>{"use strict";n();v=p(require("chalk")),J=p(require("util"));ce();R();De();ar();Ue=null;m=(...e)=>{M("introAndSummary",J.default.format(...e))},l=(...e)=>{let t=J.default.format(...e);ir.push(t),g("WARNING: ",t),M("warningsAndErrors",v.default.bgYellow.black(" WARNING ")+" "+t)},ur=(...e)=>{M("introAndSummary",v.default.green.bold(J.default.format(...e)))},w=(...e)=>{let t=J.default.format(...e);sr.push(t),g("ERROR: ",t),M("warningsAndErrors",v.default.bgRed.white(" ERROR ")+" "+t)},pe=()=>{M("introAndSummary",`
`+jn()+`
`)},jn=()=>v.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(`
`))},di=v.default.cyan,fi=v.default.blueBright,gi=v.default.red,mi=v.default.yellow,hi=v.default.green,yi=v.default.gray,wi=v.default.white,Ti=v.default.black,Ci=v.default.magenta,a=v.default.dim,bi=v.default.bold,cr="\x1B]",pr="\x1B\\"});var S=u(()=>{"use strict";n();De();lr()});function ue(e){if(!e)return;if(e==="false")return!1;let t=parseInt(e,10);if(isNaN(t)||t<1)throw new Le.CommanderError(255,"Invalid argument provided.","--pwc-cancel-after-failures must be a positive integer or 'false', provided: "+e);return t}function fr(e){if(!e)return;let t=["SIGUSR1","SIGUSR2"];if(!t.includes(e.toUpperCase().trim()))throw new Le.CommanderError(255,"Invalid argument provided.","--pwc-reset-signal must be one of ("+t.join(", ")+"), provided: "+e);return e.toUpperCase().trim()}function le(e){if(e===void 0)return;let t;if(typeof e=="number")t=e;else{let r=e.trim();if(r==="")return;t=Number(r)}if(!(!Number.isInteger(t)||t<0))return t}var Le,$e=u(()=>{"use strict";n();Le=require("commander")});function O(e){return C[e]?.env}function gr(e){let t=C[e];return"cli"in t?t.cli:void 0}function mr(e){return C[e].name}function je(){return{projectId:process.env[C.projectId.env],recordKey:process.env[C.recordKey.env],ciBuildId:process.env[C.ciBuildId.env],tag:process.env[C.tag.env]?process.env[C.tag.env]?.split(",").map(e=>e.trim()):void 0,environment:process.env[C.environment.env],cancelAfterFailures:ue(process.env[C.cancelAfterFailures.env]),disableTestTags:process.env[C.disableTestTags.env]||process.env[C.disableTitleTags.env],consoleOutput:process.env[C.consoleOutput.env],testSuiteFile:process.env[C.testSuiteFile.env],machineId:process.env[C.machineId.env],orchestrationId:process.env[C.orchestrationId.env],outputFile:process.env[C.outputFile.env],ciUrl:process.env[C.ciUrl.env]?.trim()||void 0,orchestration:{discoveryFile:process.env[C.discoveryFile.env],pendingChildExitTimeoutMs:le(process.env[C.pendingChildExitTimeoutMs.env])}}}var C,Me=u(()=>{"use strict";n();$e();C={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"},pendingChildExitTimeoutMs:{name:"Pending Child Exit Timeout",env:"CURRENTS_OR8N_PENDING_CHILD_EXIT_TIMEOUT_MS",cli:"--pwc-pending-child-exit-timeout-ms"},ciUrl:{name:"CI URL",env:"CURRENTS_CI_URL"}}});function de(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,pendingChildExitTimeoutMs:e.pwcPendingChildExitTimeoutMs},coverage:{projects:e.pwcCoverage,dir:e.pwcCoverageDir}}}function fe(){if(He)return He;if(process.env.CURRENTS_PWC_CLI_CONFIG_PATH)try{let e=JSON.parse(yr.default.readFileSync(process.env.CURRENTS_PWC_CLI_CONFIG_PATH).toString());return hr("Options from serialized CLI config file: %o",e),He=e,e}catch(e){return hr("Could not read CLI config file: %o",e),{}}return{}}var yr,hr,He,Be=u(()=>{"use strict";n();yr=p(require("fs"));R();hr=g.extend("cli-options-serializer");He=null});function ge(e,t,r={validationFn:Hn}){We("reporter options: %o",e),We("config file options: %o",t);let o={...E(qe),...E(t),...E(e),...E(fe()),...E(je()),orchestration:{...E(qe.orchestration),...E(t?.orchestration),...E(e?.orchestration),...E(fe().orchestration),...E(je().orchestration)},coverage:{...E(qe.coverage),...E(t?.coverage),...E(e?.coverage),...E(fe().coverage)}};o.disableTitleTags!==void 0&&(o.disableTestTags=o.disableTestTags||o.disableTitleTags),r.validationFn(o),V=o,Ae(nr(V?.consoleOutput)),We("resolved currents config: %o",V)}function Hn(e){Mn.forEach(t=>{if(!e[t])throw w(`${mr(t)} is required for Currents Reporter. Use the following methods:
- environment variable: ${a(O(t))}
- CLI flag: ${a(gr(t))}
- reporter configuration option ${a(t)} in ${a("playwright.config.ts")}
\u{1F4D6} ${Qt.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 k(){return V}function wr(){Ae(null),V=null}var We,Mn,qe,V,ze=u(()=>{"use strict";n();R();Zt();er();S();ce();Me();Be();ce();We=g.extend("config"),Mn=["projectId","recordKey"],qe={removeTitleTags:!1,disableTestTags:!1,consoleOutput:N.Detailed,orchestration:{skipReporterInjection:!1},coverage:{projects:!1}},V=null});var Bn,Tr=u(()=>{"use strict";n();Bn=require("lodash");S()});var D=u(()=>{"use strict";n();ze();Me();Be();Tr()});var br,Cr=u(()=>{br={name:"@currents/playwright",version:"2.4.0",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.1",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,Ge=u(()=>{"use strict";n();Cr();X=br.version});var Je,Rr,Or=u(()=>{"use strict";n();Je=()=>process.env.CURRENTS_API_URL??"https://cy.currents.dev",Rr=()=>3e4});var qn,aa,Ke=u(()=>{"use strict";n();qn=p(require("ws"));R();aa=g.extend("ws")});var vr,ha,xr,Sr=u(()=>{"use strict";n();vr=p(require("events"));ze();R();Ke();Ve();ha=g.extend("pubsub"),xr=new vr.default});var Xe,Ir,Er,kr,Pr=u(()=>{"use strict";n();S();Sr();Xe={cancellationReason:null},Ir=e=>{Xe.cancellationReason||(Xe.cancellationReason=e)},Er=()=>Xe.cancellationReason,kr=({showWarning:e=!0}={})=>{let t=Er();t&&(e&&l("%s",t),xr.emit("runCancelled",t))}});var Ve=u(()=>{"use strict";n();Pr()});var _r,Y,Ye=u(()=>{"use strict";n();_r=require("nanoid"),Y=(0,_r.customAlphabet)("abcdefghijklmnopqrstuvwxyz",10)});var Nr,zn,Dr,Ur=u(()=>{"use strict";n();Nr=require("ts-pattern"),zn={outcome:null,scannerConfig:null,currentsConfig:null,internalConfig:null},Dr=()=>zn});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=u(()=>{"use strict";n();Z=["ECONNABORTED","ECONNREFUSED","ECONNRESET","ETIMEDOUT","EPIPE","ENETUNREACH","EHOSTUNREACH","ENETRESET","ENOTFOUND","EAI_AGAIN"]});function $r(e){(0,x.match)(e).when(H,Gn).otherwise(()=>{l("Unexpected error while sending network request: %s",e)})}function Gn(e){let t=e.response?.config??e.config;return(0,x.match)(e).with({code:"ECONNABORTED"},()=>{l("Network connection aborted")}).with({code:"ECONNREFUSED"},()=>{l("Network connection aborted")}).with({code:"ECONNRESET"},()=>{l("Network connection reset")}).with({code:"EPIPE"},()=>{l("Network connection reset")}).with({code:"ENETUNREACH"},()=>{l("Network connection aborted")}).with({code:"EHOSTUNREACH"},()=>{l("Network connection aborted")}).with({code:"ETIMEDOUT"},()=>{l("Network connection timeout")}).with({response:x.P.not(x.P.nullish)},r=>{Jn(r,{status:r.response.status,data:r.response.data})}).otherwise(()=>{l(`[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 Jn(e,{status:t,data:r}){let o=e.response?.config??e.config,s=o?.method,i=o?.url;(0,x.match)(t).with(401,()=>{l(`[currents] ${s} ${i} - 401 Unauthorized Request from cloud service`)}).with(400,()=>{l(`[currents] ${s} ${i} - 400 Bad Request from cloud service:
%o`,r)}).with(429,()=>{l(`[currents] ${s} ${i} - 429 Too Many Requests from cloud service`)}).with(422,()=>{Kn(e,r)}).otherwise(()=>{l(`[currents] Unexpected network response: %s
%O`,e.message,{method:s,url:i,status:e.response?.status,requestId:Q(e)})})}function Kn(e,t){let r=e.response?.config??e.config;(0,x.match)(t).with({code:Ze.MISSING_SUITE,message:x.P.string,errors:x.P.array(x.P.string)},async o=>{let{message:s,errors:i}=o;K(1),w(...Ar(s,i)),me({id:Y(),text:(0,Fr.default)(Dr(),null,2)}).then(f=>{w(`Please share this URL with Currents support for further investigation:
${f}`)}).catch(f=>{l("Failed to upload debug artifact: %s",f)}),K(1)}).with({code:Ze.RUN_CANCELLED,message:x.P.string},o=>{Ir(o.message),kr()}).with({code:Ze.RUN_EXPIRED,message:x.P.string},o=>{l(o.message)}).with({message:x.P.string,errors:x.P.array(x.P.string)},o=>{let{message:s,errors:i}=o;K(1),l(...Ar(s,i)),K(1)}).otherwise(()=>{l(`[currents] Unexpected network response: %s
%O`,e.message,{method:r?.method,url:r?.url,status:e.response?.status,requestId:Q(e)})})}function Ar(e,t){return Lr.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 Fr,Lr,x,Ze,Qe=u(()=>{"use strict";n();Fr=p(require("json-stringify-safe")),Lr=p(require("lodash")),x=require("ts-pattern");Ve();Ye();S();et();Ur();B();Ze={RUN_CANCELLED:"RUN_CANCELLED",RUN_EXPIRED:"RUN_EXPIRED",MISSING_SUITE:"MISSING_SUITE"}});function Br(e,t,r){let o=r.method?.toUpperCase(),s=r.url,i=Q(t),f=(0,jr.default)(tt(e)),h=`Network request '${o} ${s}' failed: '${t.message}'.${i?` Request ID: ${i}.`:""} Next attempt is in ${f} (${e}/${r["transport-retry"]?.retries??rt()}).`;Mr(h),l(h)}var jr,Mr,tt,Hr,rt,Wr=u(()=>{"use strict";n();jr=p(require("pretty-ms"));R();S();Qe();B();Mr=g.extend("http"),tt=e=>{let t=[3e3,15e3,3e4];return t[Math.min(Math.max(e-1,0),t.length-1)]},Hr=e=>{if(Mr("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)},rt=()=>3});function Xn(e){let t=Gr.default.getProxyForUrl(e);if(t)return Vn("Using HTTP proxy %s for %s",t,e),qr===t&&he||(qr=t,he=new zr.ProxyAgent(t)),he}function Jr(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 Yn(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 Zn(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 Qn(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 es(e,t){if(!e.length)return null;if(Qn(e,t))try{return JSON.parse(e)}catch{return e}return e}function ts(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 Kr(e){if(!e||typeof e!="object")return;if(ts(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 Kr(t.cause);if(/connection reset|other side closed|terminated|socket hang up/i.test(r))return"ECONNRESET"}function rs(e){return e instanceof ot.Readable}function os(e){return rs(e)?{body:ot.Readable.toWeb(e),duplex:"half"}:{body:e}}async function ye(e,t,r){let o=Xn(e),s,i;try{let T={method:t.method,headers:t.headers,signal:t.signal};if(t.body!==void 0){let I=os(t.body);T.body=I.body,I.duplex&&(T.duplex=I.duplex)}o!==void 0&&(T.dispatcher=o),s=await fetch(e,T),i=await s.text()}catch(T){let I=Kr(T);throw{message:T instanceof Error?T.message:String(T),code:I,config:r}}let f=Yn(s.headers),h=Zn(f),b=es(i,h),y=s.status,P=s.statusText;if(!s.ok)throw{message:`Request failed with status code ${y}`,config:r,response:{status:y,statusText:P,headers:f,data:b,config:r}};return{data:b,status:y,statusText:P,headers:f,config:r}}var ot,zr,Gr,Vn,qr,he,nt=u(()=>{"use strict";n();ot=require("stream"),zr=require("undici");R();B();Gr=p(require("proxy-from-env")),Vn=g.extend("http:transport"),qr=null,he=null});function cs(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 ps(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 us(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 ls(...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 ds(e){let t={...as,...e.currentsOptions};return!t.enableCompression||e.data===void 0||Buffer.isBuffer(e.data)||typeof e.data=="string"||(0,Zr.default)(e.data)<=t.compressThresholdBytes?e:{...e,data:await is((0,st.default)(e.data)),headers:{...e.headers,"Content-Encoding":"gzip"}}}function fs(e){let{data:t}=e;if(t!==void 0)return Buffer.isBuffer(t)||typeof t=="string"?t:(0,st.default)(t)}async function gs(e){let t=e.baseURL??Je(),r=e["transport-retry"]?.retries??rt(),o=cs(e.headers)??(0,Yr.nanoid)(),s=await ds(e),i=fs(s),f=(s.method??"get").toUpperCase(),h=e.signal;if(h?.aborted)throw{message:h.reason?.message??"Request aborted",code:"ECONNABORTED",config:e};let b;for(let y=0;y<=r;y++){let P=s.timeout??Rr(),T=AbortSignal.timeout(P),I=h?ls(h,T):T,j=k(),_={...us(s.headers),...ss,"accept-encoding":"gzip, deflate, br","x-currents-idempotency-key":o,"x-pwc-request-attempt":String(y),"x-currents-key":j?.recordKey??""};j?.orchestrationId&&(_["x-currents-orchestration-id"]=j.orchestrationId),j?.machineId&&(_["x-currents-machine-id"]=j.machineId),ps(e.headers,"content-type")||(_["content-type"]=_["content-type"]??"application/json");let Sn={...s,method:f,url:e.url,baseURL:t,headers:_},En=Jr(t,e.url??""),Vt={method:f,url:e.url,headers:_,data:Buffer.isBuffer(i)?"buffer":i};y?Vr("network request retry: %o",Xr({...Vt,isRetry:!0})):Vr("network request: %o",Xr(Vt));try{return await ye(En,{method:f,headers:_,body:i,signal:I},Sn)}catch(_e){b=_e;let Xt=_e;if(!Hr(Xt)||y>=r)throw _e;Br(y+1,Xt,{...e,method:f}),await new Promise(In=>setTimeout(In,tt(y+1)))}}throw b}function ms(){return{request:e=>gs(e)}}function to(){return we||(we=ms(),we)}function Xr(e){return{method:e.method,baseUrl:Je(),url:e.url,data:e.isRetry?"<retry>":hs(e.data),headers:{...e.headers,"x-currents-key":"***"}}}function hs(e){let t=e;return t?.results?.raw?{...t,results:{...t.results,raw:"***"}}:e}var st,Yr,Zr,Qr,eo,Vr,ns,ss,is,as,we,ro=u(()=>{"use strict";n();st=p(require("json-stringify-safe")),Yr=require("nanoid"),Zr=p(require("object-sizeof")),Qr=require("util"),eo=p(require("zlib"));D();R();Ge();Or();Wr();nt();Vr=g.extend("http"),ns=1024*1024*1,ss={"x-pw-version":"0.0.0","x-pwc-version":X},is=(0,Qr.promisify)(eo.default.gzip),as={enableCompression:!1,compressThresholdBytes:ns},we=null});async function W(e,t=to){try{let r=await t().request(e);return oo("network response: %o",{...no.default.omit(r,"request","config"),url:r.config.url,method:r.config.method}),r}catch(r){let o=r;throw oo("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}),$r(o),o}}var no,oo,so=u(()=>{"use strict";n();no=p(require("lodash"));R();ro();Qe();oo=g.extend("http")});var it=u(()=>{"use strict";n();so();B()});var io={};Yt(io,{getDebugUrl:()=>ys});var ys,ao=u(()=>{"use strict";n();it();ys=({runId:e,type:t})=>W({method:"POST",url:"runs/debug-logs",data:{type:t,runId:e}}).then(r=>r.data)});function Ts(e,t){return go({path:e,name:null,uploadUrl:t,contentType:"text/plain"},"text/plain")}async function go(e,t,r){let o=await po.default.readFile(e.path);return at("Uploading file %s",e.uploadUrl,{buffer:Buffer.byteLength(o)}),mo(o,e.uploadUrl,t,r)}async function Cs(e,t,r){return at("Uploading buffer %s",e.name,{buffer:Buffer.byteLength(e.buffer)}),mo(e.buffer,e.uploadUrl,t,r)}function bs(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 Rs(e,t,r,o){let s=bs(t),i=e,f={"Content-Disposition":"inline","Content-Type":r};o?.compress&&(i=await ws(e),f["Content-Encoding"]="gzip"),await ye(s,{method:"PUT",headers:f,body:i},{method:"PUT",url:s,headers:f})}async function mo(e,t,r,o){await(0,co.default)(async()=>{await Rs(e,t,r,o)},{retries:5,onRetry:(s,i)=>{if(at(`Upload failed %d out of 5 attempts: %s
%o`,i,s.message,s.response?.data),i===5){w(`Cannot upload after ${i} times: ${s.message}`);return}l(`Upload failed ${i} out of 5 attempts: ${s.message}`)}})}var co,po,uo,lo,at,ws,fo,ho=u(()=>{"use strict";n();co=p(require("async-retry")),po=p(require("fs/promises")),uo=require("util"),lo=require("zlib");R();nt();S();at=g.extend("upload"),ws=(0,uo.promisify)(lo.gzip),fo=(s=>(s.PNG="image/png",s.WEBM="video/webm",s.TEXT="text/plain",s.ZIP="application/zip",s))(fo||{})});var yo={};Yt(yo,{ContentType:()=>fo,sendBuffer:()=>Cs,sendPath:()=>go,uploadText:()=>Ts});var wo=u(()=>{"use strict";n();ho()});async function me(e){let{getDebugUrl:t}=await Promise.resolve().then(()=>(ao(),io));try{let{readUrl:r,uploadUrl:o}=await t({runId:e.id,type:"pw-debug"}),{uploadText:s,sendBuffer:i}=await Promise.resolve().then(()=>(wo(),yo));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 ct,pt=u(()=>{"use strict";n();ct=p(require("debug"))});function Os(e){return e==="false"?!1:e==="remote"?"remote":e==="full"?"full":!!e}var To,F,ut=u(()=>{"use strict";n();To=require("@commander-js/extra-typings"),F=new To.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(Os).env("CURRENTS_DEBUG")});var Co,bo,Ro=u(()=>{"use strict";n();Co=require("@commander-js/extra-typings");ut();bo=()=>new Co.Command().allowUnknownOption().allowExcessArguments(!0).addOption(F).helpOption(!1)});var U,Oo,dt,vo,xo,lt,A,ee=u(()=>{"use strict";n();U=p(require("debug")),Oo=p(require("fs")),dt=p(require("path")),vo=p(require("util")),xo=require("fs/promises");Ye();S();Ro();pt();U.default.useColors=function(){return!1};lt=U.default.log,A=class e{constructor(t="core"){this.source=t;if(this.mode=bo().parse().opts().pwcDebug??!1,this.debug=(0,U.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(U.default.enable(r),!this.shouldUploadRemoteDebug())return this;let o=Y(),s=dt.default.resolve(".currents-debug"),i=dt.default.resolve(s,`${o}.log`);(0,xo.mkdir)(s,{recursive:!0}),m(a(`\u{1F47E} Initiated remote ${this.source} debug log collection:`),a(i));let f=Oo.default.createWriteStream(i,{flags:"a"});return U.default.log=(...h)=>{this.mode&&(f.write(`${vo.default.formatWithOptions({colors:!1},...h)}
`),this.shouldMuteLocalStdout()||lt(...h))},this.pipelines[o]={id:o,writeStream:f,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"),U.default.log=lt);for(let o of r)await this.uploadDebug(o,t??Y())}catch{}finally{U.default.log=lt}}async uploadDebug(t,r){let o=this.pipelines[t];if(!o){this.debug("No debug pipeline found for id %s",t);return}m(a(`\u{1F47E} ${o.type} debug log written:`),a(o?.tempFilePath));try{let s=await me({id:r,path:o.tempFilePath});o?.writeStream.end(),m(a(`\u{1F47E} ${o.type} debug log uploaded:`),a(s))}catch(s){l(`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 et=u(()=>{"use strict";n();pt();ee()});var g,R=u(()=>{"use strict";n();et();g=(0,ct.default)("currents")});n();var zu=require("source-map-support/register");n();var Kt=require("commander");R();S();ee();B();n();var Ko=p(require("fs"));D();R();n();var ft=p(require("fs")),So=require("tmp-promise"),Eo=async()=>{let{path:e}=await(0,So.file)();return e};n();var te=require("@commander-js/extra-typings"),Ce=p(require("chalk")),At=require("commander");Ge();S();n();var d=require("@commander-js/extra-typings"),gt=require("commander");D();$e();ut();var Te=new d.Option("--pwc-config <path>","path to currents config file (currents.config.[ts|js])").env(O("currentsConfigFile")),mt=new d.Option("--ci-build-id <id>","the unique run identifier").env(O("ciBuildId")),ht=new d.Option("-k, --key <record-key>","your secret Record Key obtained from Currents").env(O("recordKey")),yt=new d.Option("-p, --project-id <project>","the project ID for results reporting obtained from Currents").env(O("projectId")),wt=new d.Option("-t, --tag <tag>","comma-separated tag(s) for recorded runs in Currents").argParser(_t),Tt=new d.Option("--pwc-environment <name>","run-level environment name for Currents (e.g. staging, prod)").env(O("environment")),Ct=new d.Option("--pwc-remove-title-tags","remove tags from test names in Currents, e.g. `Test name @smoke` becomes `Test name` in the dashboard"),Io=new d.Option("--pwc-disable-title-tags","[DEPRECATED] Use --pwc-disable-test-tags instead"),bt=new d.Option("--pwc-disable-test-tags","disable reporting tags defined on the test or suite level, or extracted from the test title"),Rt=new d.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(O("cancelAfterFailures")).argParser(ue),Ot=new d.Option("--pwc-output-file <string>","path to the file where the run summary output will be written.").env(O("outputFile")),vt=new d.Option("--pwc-discovery-file <file>","path to the test discovery file shared by `pwc-p discover` and `pwc-p run`").env(O("discoveryFile")),ko=new d.Option("--list","ignored (discover always runs playwright with --list)").hideHelp(),Po=new d.Option("--reporter <reporters>","ignored (discover always runs playwright with --reporter=list)").hideHelp(),xt=new d.Option("--pwc-console-output <preset>","reporter console output: none (no stdout), summary (intro + one line per test + summary), detailed (full output)").choices(Object.values(N)).env(O("consoleOutput")),St=new d.Option("--pwc-test-suite-file <path>","path to the full test suite file for orchestration and reporting").env(O("testSuiteFile")).hideHelp(),Et=new d.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(O("machineId")),It=new d.Option("--pwc-orchestration-id <string>","unique identifier of the orchestration session this run belongs to. See: https://docs.currents.dev/?q=orchestrationId").env(O("orchestrationId")).hideHelp();var kt=new d.Option("--pwc-inspect","enable inspect mode, run playwright with --inspect-brk flag or developments and debugging").default(!1).hideHelp(),_o=new d.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(fr),Pt=new d.Option("--reporter <reporter>","Reporter to use, comma-separated").argParser(_t).hideHelp(),No=new d.Option("-c, --config <file>","Playwright configuration file path"),Do=new d.Option("--tsconfig <path>","path to a single tsconfig applicable to all imported files"),Xc=new d.Option("--test-list <file>","path to a file containing a list of tests to run (Playwright --test-list)"),Yc=new d.Option("--project <name...>","only run tests from the specified Playwright projects (variadic)"),Uo=new d.Option("-j, --workers <workers>","number of concurrent workers or percentage of logical CPU cores per shard"),Ao=new d.Option("--timeout <ms>","per-test timeout in milliseconds"),Fo=new d.Option("--headed","run tests in headed browsers"),Lo=new d.Option("--fully-parallel","run all tests in parallel (Playwright fullyParallel)"),$o=new d.Option("--output <dir>","directory for output artifacts"),jo=new d.Option("--ignore-snapshots","ignore screenshot and snapshot expectations"),Mo=new d.Option("--fail-on-flaky-tests","fail the run if any test is flagged as flaky");function Ho(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 Bo(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 Wo=new d.Option("--pwc-skip-reporter-injection","do not inject @currents/playwright reporter, use the reporters specified in the playwright configuration file");function _t(e,t=[]){return e?t.concat(e.split(",").map(r=>r.trim())):t}var Nt=new d.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(_t),Dt=new d.Option("--pwc-coverage-dir <path>","directory path for reading coverage reports"),qo=new d.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(O("batchSize")).argParser(e=>{if(e==="auto")return e;let t=Number(e);if(!isNaN(t)&&Number.isInteger(t)&&t>0)return t;throw new gt.InvalidArgumentError('Provide either "auto" or a positive integer.')}),zo=new d.Option("--pwc-pending-child-exit-timeout-ms <milliseconds>","force-exit pending Playwright child processes after orchestration finishes when they have not exited").env(O("pendingChildExitTimeoutMs")).argParser(e=>{let t=le(e);if(t===void 0)throw new gt.InvalidArgumentError("Must be a non-negative integer.");return t});var be=(e=Lt())=>e.version(X),Re=`----------------------------------------------------
\u{1F4D6} Documentation: https://docs.currents.dev
\u{1F919} Support: support@currents.dev
----------------------------------------------------`,vs=`
${Re}
${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")}
`,xs=`
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")}
`,Ss=`
${Re}${xs}`,Ut="https://docs.currents.dev/guides/ci-optimization/playwright-orchestration",Es=`
${Re}
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.`,Is="List Playwright tests, with filters and configuration of your choice; write results to a file for orchestration.",ks="Run Orchestration for the selected tests.",Ps=new Set(["--grep","-g","--grep-invert","-G","--last-failed"]);function Go(e){return/unknown option '?([^'\s]+)'?/i.exec(e)?.[1]??null}function Ft(e){return e.code==="commander.helpDisplayed"||e.code==="commander.help"||e.code==="commander.version"}function _s(e){if(!(e instanceof At.CommanderError))throw e;if(e.code==="commander.unknownOption"){let t=Go(e.message);t&&Ps.has(t)&&(w(`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"&&(w("--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")&&(w(`--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"&&(w(`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 Ns(e){if(!(e instanceof At.CommanderError))throw e;if(e.code==="commander.unknownOption"||e.code==="commander.unknownCommand"||e.code==="commander.excessArguments"){let r=e.code==="commander.unknownOption"?Go(e.message):null,o=r?`${r}`:"file matching argument";w(`${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: ${Fe(Ut,Ut)}`),process.exit(e.exitCode)}throw e}var Lt=()=>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
${vs}`).addOption(mt).addOption(ht).addOption(yt).addOption(wt).addOption(Tt).addOption(Te).addOption(Ct).addOption(bt).addOption(Io).addOption(Rt).addOption(Ot).addOption(xt).addOption(St).addOption(Et).addOption(It).addOption(kt).addOption(F).addOption(Nt).addOption(Dt).addOption(Pt).action(function(){this.opts().pwcDisableTitleTags&&l(`${a("--pwc-disable-title-tags")} has been renamed to ${a("--pwc-disable-test-tags")}.`)}),Ds=()=>new te.Command().name("discover").usage("[options] [playwright arguments and flags]").allowUnknownOption().allowExcessArguments(!0).showHelpAfterError("(add --help for additional information)").summary(Is).description(`List Playwright tests and write result to a file for orchestration.
${Re}
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 ${Fe(Ut,"documentation")} for more details.
`).addOption(Te).addOption(vt).addOption(ko).addOption(Po).addOption(F),Us=()=>be(Ds()),As=()=>new te.Command().name("run").usage("[options]").allowExcessArguments(!1).showHelpAfterError("(add --help for additional information)").exitOverride(_s).summary(ks).description(`\u2728 Orchestrate \u{1F3AD} Playwright tests on CI using https://currents.dev
${Ss}`).addOption(mt).addOption(ht).addOption(yt).addOption(No).addOption(wt).addOption(Tt).addOption(Uo).addOption(Fo).addOption(Lo).addOption($o).addOption(Ao).addOption(jo).addOption(Do).addOption(Mo).addOption(Te).addOption(Ct).addOption(bt).addOption(Rt).addOption(Ot).addOption(xt).addOption(St).addOption(Et).addOption(It).addOption(_o).addOption(kt).addOption(F).addOption(Pt).addOption(Wo).addOption(Nt).addOption(Dt).addOption(qo).addOption(zo).addOption(vt);function Jo(e){let t=new te.Command().name("pwc-p").version(X).description(`\u2728 Orchestrate \u{1F3AD} Playwright tests on CI using https://currents.dev
${Es}`).allowExcessArguments(!1).exitOverride(Ns).showHelpAfterError("(add --help for additional information)"),r=Us();r.action(async function(){await e.discover(this)});let o=be(As());return o.action(async function(){this.opts().pwcDisableTitleTags&&l(`${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 $t=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=be(Lt()),this.cliOptions=this.program.parse().opts();$t("CLI options: %o",this.cliOptions),this.parsedConfig=de(this.cliOptions),$t("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 Eo();return Ko.default.writeFileSync(t,JSON.stringify(this.parsedConfig)),$t("CLI options temp file path: %s",t),this.configFilePath=t,this.configFilePath}};n();var Zo=p(require("crypto")),z=p(require("fs")),Qo=p(require("os")),xe=p(require("path"));D();n();var re=p(require("path")),Vo=require("url"),Xo=p(require("jiti")),Yo=[".ts",".js",".mjs"];function Fs(e){return e.replace(/\\/g,"/")}function ve(e){e||(e="currents.config");let t=process.cwd(),r=(0,Xo.default)(t,{interopDefault:!0,cache:!1,extensions:[...Yo]}),o=Ls(e,{cwd:t,jiti:r});return o?{config:o.config,configFile:Fs(o.configFile)}:{config:{},configFile:""}}function Ls(e,t){let r=$s(e,t);if(!r)return null;let o=re.default.extname(r);if(!Yo.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 $s(e,t){let r=o=>{let s=t.jiti.esmResolve(o,{try:!0});return s?(0,Vo.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 jt;async function q(){if(jt)return jt;let{execa:e}=await import("execa");return jt=e,e}S();async function en(e){try{let t=e.opts(),r=ve(t.pwcConfig);ge(de(t),r.config,{validationFn:()=>{}});let o=k()?.orchestration?.discoveryFile,s=typeof o=="string"&&o.trim()||void 0,i=s?xe.default.resolve(process.cwd(),s):void 0;if(!i)return w("Discovery file is required. Set one of:"),m(""),m(a(" --pwc-discovery-file <file>")),m(""),m(a(" environment variable CURRENTS_DISCOVERY_FILE")),m(""),m(a(" currents.config: orchestration.discoveryFile")),m(""),1;let f=e.args;if(f.some(y=>y==="--shard"||y.startsWith("--shard=")))return w("--shard conflicts with pwc-p orchestration. Remove --shard; pwc-p distributes work via the orchestration session."),1;let b=xe.default.join(Qo.default.tmpdir(),`pwc-discover-${Zo.default.randomUUID()}.tmp`);try{let y=await q(),P=z.default.openSync(b,"w"),T;try{T=await y("playwright",["test","--list","--reporter=list",...f],{stdio:["inherit",P,"inherit"],reject:!1})}finally{z.default.closeSync(P)}if(T.exitCode!==0)return T.exitCode==null&&w(T.signal?`playwright discovery was terminated by signal ${T.signal}.`:"Failed to run `playwright test --list`. Is @playwright/test installed and on PATH?"),T.exitCode??1;try{z.default.mkdirSync(xe.default.dirname(i),{recursive:!0}),z.default.copyFileSync(b,i)}catch(I){return w("Failed to write discovery output: %o",I),1}}finally{z.default.rmSync(b,{force:!0})}return m(""),ur(`Discovery file written to: ${i}`),m(""),m("Execute orchestration for the discovered tests:"),m(a(` pwc-p run --key <record-key> --project-id <id> --ci-build-id <build-id> --pwc-discovery-file ${i}`)),0}finally{wr()}}n();var Rn=p(require("fs")),On=p(require("path")),Gt=require("ts-pattern");D();R();n();n();var tn={resetSignalReceived:null},rn=({resetSignalReceived:e})=>{tn.resetSignalReceived=e},on=()=>tn;S();n();var zt=require("ts-pattern");D();R();ee();n();Ke();n();var nn=p(require("http"));R();var sn=p(require("lil-http-terminator")),Se=require("ts-pattern"),an=p(require("ws")),G=g.extend("wss"),ne=null,oe=null,Mt=null,L=()=>(0,Se.match)(ne?.address()).with({port:Se.P.number},e=>e.port).otherwise(()=>0),cn=async()=>{if(G("terminating wss server: %d",L()),!Mt){G("no wss server");return}let{success:e,code:t,message:r,error:o}=await Mt.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())},pn=e=>{oe||(ne=nn.default.createServer().on("listening",()=>{if(!ne)throw new Error("Server not initialized");oe=new an.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(f=>f(i.toString()))})}),oe.on("close",()=>{G("wss closed"),oe=null})}).listen(),Mt=(0,sn.default)({server:ne}))};n();var wn=p(require("fs")),Ie=require("lodash"),qt=p(require("tmp")),Tn=p(require("regexp.escape"));D();R();n();var Ht={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"};n();var dn=p(require("json-stringify-safe"));n();var un=p(require("crypto"));function ln(e){return typeof e=="string"&&(e=Buffer.from(e)),un.default.createHash("md5").update(e).digest("hex")}function fn(e,t){return ln((0,dn.default)({groupId:e,specs:[...t].sort()}))}S();ee();n();it();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})})}};n();R();S();var gn=g.extend("or8n-spawned-task"),js=5e3;function Ms(e){let t=e?.pid;return typeof t=="number"&&Number.isInteger(t)&&t>0?t:void 0}function Hs(e){let t=e;if(!t||t.killed||t.exitCode!==void 0&&t.exitCode!==null)return!1;let r=t.pid;if(typeof r!="number"||!Number.isInteger(r)||r<=0)return!0;try{return process.kill(r,0),!0}catch(o){return o.code==="EPERM"}}function hn(e){let t=`[${e.groupId}] ${e.specs.join(", ")}`,r=Ms(e.subprocess);return r===void 0?t:`${t} (pid ${r})`}function Bs(e,t,r){let o=hn(e),s=t/1e3;r?l(`Force-exiting Playwright child after ${s}s; results and artifacts uploaded: ${o}`):l(`Force-exiting Playwright child after ${s}s; reporting did not complete (results/artifacts may be incomplete): ${o}`)}function Ws(e,t){let r=e.subprocess;if(!r?.kill)return;let o=hn(e);try{r.kill("SIGTERM")}catch(i){gn("Failed to send SIGTERM to spawned task %s: %o",o,i)}let s=setTimeout(()=>{try{r.kill?.("SIGKILL")}catch(i){gn("Failed to send SIGKILL to spawned task %s: %o",o,i)}t()},js);return s.unref?.(),s}function mn(e){e!==void 0&&clearTimeout(e)}var Bt=class{constructor(t,r){this.task=t;this.resolve=r}task;resolve;settled=!1;forceExitStarted=!1;exitTimer;killSignalTimer;wait(t){if(t!==void 0){let r=t;this.exitTimer=setTimeout(()=>{this.forceExit(r,this.task.taskReporterComplete)},r),this.exitTimer.unref?.()}this.task.promise.then(r=>this.finish(r),()=>this.finish({exitCode:1}))}resolveExitCode(t){return this.forceExitStarted?this.task.taskReporterComplete?0:1:t.exitCode??1}finish(t={}){this.settled||(this.settled=!0,mn(this.exitTimer),this.exitTimer=void 0,mn(this.killSignalTimer),this.killSignalTimer=void 0,this.resolve({exitCode:this.resolveExitCode(t)}))}forceExit(t,r){if(!this.settled){if(this.forceExitStarted=!0,!Hs(this.task.subprocess)){this.finish();return}Bs(this.task,t,r),this.killSignalTimer=Ws(this.task,()=>{this.finish()}),this.killSignalTimer===void 0&&this.finish()}}};function yn(e,t){return new Promise(r=>{new Bt(e,r).wait(t)})}var Wt=g.extend("or8n-task-executor"),Ee=class{constructor(t,r,o,s,i,f,h,b=new se){this.cliManager=t;this.or8nId=r;this.runId=o;this.machineId=s;this.suite=i;this.resolve=f;this.reject=h;this.batchedOrchestrationAPI=b;"CURRENTS_OR8N_EVENT_MODE"in