@checksum-ai/runtime 1.0.78 → 1.0.79
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/checksum-root/checksum.config.ts +0 -2
- package/cli.js +5 -5
- package/index.js +43 -43
- package/package.json +2 -2
- package/test-run-monitor.js +3 -3
package/cli.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var
|
|
1
|
+
var C=Object.create;var d=Object.defineProperty;var R=Object.getOwnPropertyDescriptor;var P=Object.getOwnPropertyNames;var T=Object.getPrototypeOf,x=Object.prototype.hasOwnProperty;var u=(a,t)=>d(a,"name",{value:t,configurable:!0});var S=(a,t,e,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of P(t))!x.call(a,s)&&s!==e&&d(a,s,{get:()=>t[s],enumerable:!(o=R(t,s))||o.enumerable});return a};var A=(a,t,e)=>(e=a!=null?C(T(a)):{},S(t||!a||!a.__esModule?d(e,"default",{value:a,enumerable:!0}):e,a));var c=require("fs"),p=A(require("child_process")),n=require("path");var f="checksum";var w=!1;function y(a){w=a}u(y,"setLogToConsole");function l(...a){w&&console.log(...a)}u(l,"log");function k({isInit:a,excludeLogin:t}){return[...a?["example.checksum.spec.ts","github-actions.example.yml"]:[],...t?[]:["login.ts"],"checksum.config.ts","playwright.config.ts","README.md",".gitignore.example"]}u(k,"getRuntimeFiles");var m=class{constructor(){this.MAX_COMPLETION_WAIT=10*60*1e3;this.TEST_RUN_MONITOR_PATH=(0,n.join)(__dirname,"test-run-monitor.js");this.checksumApiUrl="https://api.checksum.ai";this.checksumAppUrl="https://app.checksum.ai";this.didFail=!1;this.isolationMode=!1;this.debugMode=!1;this.completeIndicators={upload:!1,tests:!1,report:!1};this.uploadProgress=0;this.guardReturn=async(t,e=1e3,o="guardReturnTimedOut")=>{let s="guard-timed-out",r=u(async()=>(await this.awaitSleep(e+1e3),s),"guard"),i=await Promise.race([t,r()]);if(typeof i=="string"&&i===s)throw new Error(o);return i};this.awaitSleep=t=>new Promise(e=>setTimeout(e,t));this.printError=t=>{console.log("\x1B[31m%s\x1B[0m",t)}}async execute(){switch(process.argv.find(t=>t==="--help"||t==="-h")&&(await this.printHelp(process.argv[2]),process.exit(0)),process.argv.find(t=>t==="--clidebug")&&(this.debugMode=!0,y(!0)),process.argv[2]){case"init":this.install();break;case"test":await this.test(process.argv.slice(3));break;case"show-report":this.showReport(process.argv.slice(3));break;default:await this.printHelp()}process.exit(0)}async execCmd(t,e={}){let o={...process.env,...e},s=await p.spawn(t,{env:o,shell:!0,stdio:"inherit"});return new Promise((i,g)=>{s.on("exit",h=>{h===0?i(!0):g(new Error(`Checksum failed execution with code: ${h} `))})})}async getCmdOutput(t){return new Promise(function(e,o){p.exec(t,(s,r,i)=>{if(s){o(`Error executing command: ${s.message}`);return}e(r)})})}async printHelp(t){switch(t){default:console.log(`
|
|
2
2
|
Checksum CLI
|
|
3
3
|
Usage: checksum [command] [options]
|
|
4
4
|
|
|
@@ -10,10 +10,10 @@ show-report [options] [report] show HTML report
|
|
|
10
10
|
`);break;case"test":try{let e="npx playwright test --help",o=(await this.getCmdOutput(e)).replace(/npx playwright/g,"yarn checksum").split(`
|
|
11
11
|
`);o.splice(5,0," --checksum-config=<config> Checksum configuration in JSON format").join(`
|
|
12
12
|
`),console.log(o.join(`
|
|
13
|
-
`))}catch(e){console.log("Error",e.message)}break;case"show-report":try{let e="npx playwright show-report --help",o=(await this.getCmdOutput(e)).replace(/npx playwright/g,"yarn checksum");console.log(o)}catch(e){console.log("Error",e.message)}break}}async showReport(t){let e=`npx playwright show-report ${t.join(" ")}`;try{await this.execCmd(e)}catch(o){console.log("Error showing report",o.message)}}async test(t){if(this.locateChecksumLibs(),this.processChecksumArguments(t),this.setChecksumConfig(),!await this.getSession())return;let e;try{e=await this.guardReturn(this.startTestRunMonitor(this.testSession),1e4,"test run monitor timeout")}catch{console.log("Error starting test run monitor. Test results will not be available on checksum.")}this.buildVolatileConfig();let o={CHECKSUM_ROOT_FOLDER:this.checksumRoot};e&&(o.CHECKSUM_UPLOAD_AGENT_PORT=e),this.config.options.hostReports&&(o.PW_TEST_HTML_REPORT_OPEN="never");let s=`npx playwright test --config ${this.getPlaywrightConfigFile()} ${t.map(
|
|
14
|
-
|
|
15
|
-
|
|
13
|
+
`))}catch(e){console.log("Error",e.message)}break;case"show-report":try{let e="npx playwright show-report --help",o=(await this.getCmdOutput(e)).replace(/npx playwright/g,"yarn checksum");console.log(o)}catch(e){console.log("Error",e.message)}break}}async showReport(t){let e=`npx playwright show-report ${t.join(" ")}`;try{await this.execCmd(e)}catch(o){console.log("Error showing report",o.message)}}async test(t){if(this.locateChecksumLibs(),this.processChecksumArguments(t),this.setChecksumConfig(),!await this.getSession())return;let e;try{e=await this.guardReturn(this.startTestRunMonitor(this.testSession),1e4,"test run monitor timeout")}catch{console.log("Error starting test run monitor. Test results will not be available on checksum.")}this.buildVolatileConfig();let o={CHECKSUM_ROOT_FOLDER:this.checksumRoot};e&&(o.CHECKSUM_UPLOAD_AGENT_PORT=e),this.config.options.hostReports&&(o.PW_TEST_HTML_REPORT_OPEN="never");let s=`npx playwright test --config ${this.getPlaywrightConfigFile()} ${t.map(r=>`"${r}"`).join(" ")}`;await this.patchPlaywright();try{await this.execCmd(s,o),console.log("Tests execution finished")}catch(r){this.didFail=!0,console.log("Error during test",r.message)}finally{this.sendReportUploadRequest(),await this.patchPlaywright(!0),this.completeIndicators.tests=!0,await this.handleCompleteMessage()}}sendReportUploadRequest(){this.isolationMode||console.log("Waiting for test files to upload to Checksum...");let t=this.getPlaywrightReportPath();if(!(0,c.existsSync)(t)){console.log(`Could not find report file at ${t}`);return}l("Sending report upload request",t),this.testRunMonitorProcess.stdin.write(`cli:report=${t}`)}async patchPlaywright(t=!1){l("Patching playwright",t);let e=`node ${(0,n.join)(__dirname,"scripts/patch.js")}${t?" off":""}`;try{await this.execCmd(e,{PROJECT_ROOT:this.projectRootDirectory})}catch(o){console.log("Error patching playwright",o.message)}}getPlaywrightReportPath(){var s;let t=u(r=>(l("Using report folder",r),(0,n.join)(r,"index.html")),"makeFilePath");if(process.env.PLAYWRIGHT_HTML_REPORT)return t(process.env.PLAYWRIGHT_HTML_REPORT);let e=((s=require(this.getPlaywrightConfigFile()))==null?void 0:s.default)||{},{reporter:o}=e;if(o instanceof Array){let i=o.filter(g=>g instanceof Array&&g[0]==="html").find(g=>{var h;return(h=g[1])==null?void 0:h.outputFolder});if(i)return t((0,n.join)(this.checksumRoot,i[1].outputFolder))}return t((0,n.join)(this.projectRootDirectory,"playwright-report"))}getPlaywrightConfigFile(){return(0,n.join)(this.checksumRoot,"playwright.config.ts")}startTestRunMonitor(t){return new Promise(e=>{console.log("Starting test run monitor"),this.testRunMonitorProcess=p.spawn("node",[this.TEST_RUN_MONITOR_PATH,JSON.stringify({sessionId:t,checksumApiURL:this.checksumApiUrl,apiKey:this.config.apiKey}),...this.isolationMode?["isolated"]:[]]),this.testRunMonitorProcess.stdout.on("data",o=>{let s=o.toString().trim();if(l("[trm] "+s),!s.startsWith("monitor"))return;let[r,i]=s.substring(s.indexOf(":")+1).split("=");r==="port"?e(i):this.handleTestRunMonitorMessage(r,i)}),this.testRunMonitorProcess.on("exit",(o,s)=>{console.log(`test run monitor process exited with code ${o} and signal ${s}`)}),this.testRunMonitorProcess.on("error",o=>{console.error(`Error starting test run monitor: ${o.message}`)})})}async handleTestRunMonitorMessage(t,e){switch(l(`Handling test run monitor message ${this.isolationMode?"(isolation mode)":""}`,t,e),t){case"complete-with-errors":console.log("Error uploading test files to Checksum"),this.sendProcessingError().then(()=>{this.completeIndicators.upload=!0});break;case"complete":this.isolationMode||console.log("Test files uploaded successfully"),this.sendUploadsComplete().then(()=>{this.completeIndicators.upload=!0});break;case"report-complete":{if(this.isolationMode){this.completeIndicators.report=!0;break}let o=e.slice(0,e.indexOf(":"))==="true",s=e.slice(e.indexOf(":")+1),r={};try{r=JSON.parse(s)}catch(i){console.log("Error parsing stats",i.message)}if(await this.sendTestRunEnd(r),this.completeIndicators.report=!0,o){let i=`Checksum report URL: ${this.checksumAppUrl}/#/test-runs/${this.testSession}`,g="*".repeat(i.length);console.log(`${g}
|
|
14
|
+
${i}
|
|
15
|
+
${g}`)}else console.log("An error occurred while uploading the test report to Checksum");break}case"upload-progress":{let o=parseInt(e);(o<this.uploadProgress||o>=this.uploadProgress+10||o===100&&this.uploadProgress!==100)&&(this.uploadProgress=o,console.log(`[ Uploads progress: ${this.uploadProgress}% ]`))}break;case"log":console.log(e);break;default:console.warn(`Unhandled test run monitor message: ${t}=${e}`)}}async handleCompleteMessage(){let t=Date.now();for(;;){if(Date.now()-t>this.MAX_COMPLETION_WAIT){console.log("An error occurred and Checksum wasn't able to complete processing and uploading the test run files."),this.shutdown(1);return}Object.keys(this.completeIndicators).find(e=>!this.completeIndicators[e])?(l(this.completeIndicators),await this.awaitSleep(1e3)):(console.log("Checksum test run complete"),this.shutdown(this.didFail?1:0))}}shutdown(t=0){this.cleanup(),process.exit(t)}buildVolatileConfig(){if(!this.volatileChecksumConfig)return;let t=this.getVolatileConfigPath(),e=`
|
|
16
16
|
import { RunMode, getChecksumConfig } from "@checksum-ai/runtime";
|
|
17
17
|
|
|
18
18
|
export default getChecksumConfig(${JSON.stringify(this.config,null,2)});
|
|
19
|
-
`;(0,
|
|
19
|
+
`;(0,c.writeFileSync)(t,e)}cleanup(){var t,e;this.deleteVolatileConfig(),(t=this.testRunMonitorProcess)==null||t.stdin.write("cli:shutdown"),(e=this.testRunMonitorProcess)==null||e.kill()}async getSession(){try{if(!this.config.options.hostReports)return this.setIsolatedMode(),!0;let t=this.config.apiKey;if(!t||t==="<API key>")return this.printError("No API key found in checksum config - please set it in the config file - checksum.config.ts"),this.shutdown(1),!1;let e=JSON.stringify(await this.getEnvInfo()),o=await fetch(`${this.checksumApiUrl}/client-api/test-runs`,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json",ChecksumAppCode:t},body:e});return this.testSession=(await o.json()).uuid,!0}catch{return console.log("Error connecting to Checksum, the report will not be hosted"),this.setIsolatedMode(),!0}}setIsolatedMode(){this.isolationMode=!0,this.testSession="isolated-session"}async sendTestRunEnd(t){if(!this.isolationMode)try{l("Sending test run end",t);let e=JSON.stringify({...t,endedAt:Date.now()});await this.updateTestRun(`${this.checksumApiUrl}/client-api/test-runs/${this.testSession}`,"PATCH",e)}catch(e){return console.log("Error sending test run end",e.message),null}}async sendUploadsComplete(){if(!this.isolationMode)try{await this.updateTestRun(`${this.checksumApiUrl}/client-api/test-runs/${this.testSession}/uploads-completed`,"PATCH")}catch(t){console.log("Error sending test run uploads complete",t.message)}}async sendProcessingError(){if(!this.isolationMode)try{await this.updateTestRun(`${this.checksumApiUrl}/client-api/test-runs/${this.testSession}/process-error`,"PATCH")}catch(t){console.log("Error sending test run processing error",t.message)}}async updateTestRun(t,e,o=void 0){let s=await fetch(t,{method:e,headers:{Accept:"application/json","Content-Type":"application/json",ChecksumAppCode:this.config.apiKey},body:o});return l("Received update test run response from url:",t),await this.logApiResponse(s),s}async logApiResponse(t){try{if(!t.ok){l("HTTP Error:",t.status,t.statusText);let o=await t.text();l("Error Details:",o);return}t.headers.get("Content-Type").includes("application/json")?t.json().then(o=>{l("API Response:",o)}):t.text().then(o=>{l("API Response:",o)})}catch(e){l("Error logging API response",e.message)}}async getEnvInfo(){let t={commitHash:"",branch:"branch",environment:process.env.CI?"CI":"local",name:"name",startedAt:Date.now()};try{t.commitHash=(await this.getCmdOutput("git rev-parse HEAD")).toString().trim()}catch(e){console.log("Error getting git hash",e.message)}try{t.branch=(await this.getCmdOutput("git rev-parse --abbrev-ref HEAD")).toString().trim()}catch(e){console.log("Error getting branch",e.message)}try{t.name=(await this.getCmdOutput("git log -1 --pretty=%B")).toString().trim()}catch(e){console.log("Error getting name",e.message)}return t}getVolatileConfigPath(){return(0,n.join)(this.checksumRoot,"checksum.config.tmp.ts")}deleteVolatileConfig(){let t=this.getVolatileConfigPath();(0,c.existsSync)(t)&&(0,c.rmSync)(t)}setChecksumConfig(){this.config={...require((0,n.join)(this.checksumRoot,"checksum.config.ts")).default||{},...this.volatileChecksumConfig||{}},this.debugMode&&(this.config.options.printLogs=!0),this.config.apiURL&&(this.checksumApiUrl=this.config.apiURL)}processChecksumArguments(t){this.deleteVolatileConfig();for(let e=0;e<t.length;e++){let o=t[e];if(o.startsWith("--checksum-config"))try{this.volatileChecksumConfig=JSON.parse(o.split("=")[1]),t.splice(e,1)}catch(s){console.log("Error parsing checksum config",s.message),this.volatileChecksumConfig=void 0}o==="--clidebug"&&t.splice(e,1)}}install(){console.log("Creating Checksum directory and necessary files to run your tests");try{this.findChecksumRootOrigin()}catch(o){console.log(o.message),process.exit(1)}let t=(0,n.join)(process.cwd(),f);if((0,c.existsSync)(t)||(0,c.mkdirSync)(t),!(0,c.existsSync)(this.getChecksumRootOrigin()))throw new Error("Could not find checksum root directory, please install @checksum-ai/runtime package");let e=(0,c.existsSync)((0,n.join)(t,"checksum.config.ts"));k({isInit:!e}).forEach(o=>{let s=(0,n.join)(t,o);(0,c.existsSync)(s)||(0,c.copyFileSync)((0,n.join)(this.getChecksumRootOrigin(),o),s)}),(0,c.mkdirSync)((0,n.join)(t,"tests"),{recursive:!0}),["esra","har","trace","log"].forEach(o=>{(0,c.mkdirSync)((0,n.join)(t,"test-data",o),{recursive:!0})})}getChecksumRootOrigin(){return(0,n.join)(this.projectRootDirectory,"node_modules","@checksum-ai","runtime","checksum-root")}locateChecksumLibs(){try{this.findChecksumRootOrigin(),this.findChecksumRoot(),l("Project root found at",this.projectRootDirectory),l("Checksum root found at",this.checksumRoot)}catch(t){console.log(t.message),process.exit(1)}}findChecksumRootOrigin(){let t=process.cwd();for(let e=0;e<6;e++){let o=(0,n.join)(t,"node_modules","@checksum-ai","runtime","checksum-root");if((0,c.existsSync)(o)){this.projectRootDirectory=t;return}if((0,n.parse)(t).root===t)break;t=(0,n.join)(t,"..")}throw new Error("Could not resolve checksum root origins")}findChecksumRoot(){let t=u(e=>{try{return(0,c.readdirSync)(e).includes("checksum.config.ts")}catch{return!1}},"containsChecksumConfig");try{let e=[this.projectRootDirectory];for(;e.length;){let o=e.pop(),s=(0,c.readdirSync)(o,{withFileTypes:!0});for(let r of s)if(r.isDirectory()){let i=(0,n.join)(o,r.name);if(r.name===f){if(t(i)){this.checksumRoot=i;return}}else e.push(i)}}}catch(e){throw e}throw new Error("Could not find checksum root folder. Run `npx checksumai init` to create one.")}};u(m,"ChecksumCLI");(async()=>await new m().execute())();
|