@checksum-ai/runtime 1.0.19 → 1.0.20

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/cli.js CHANGED
@@ -1,4 +1,4 @@
1
- var m=Object.create;var p=Object.defineProperty;var f=Object.getOwnPropertyDescriptor;var C=Object.getOwnPropertyNames;var w=Object.getPrototypeOf,y=Object.prototype.hasOwnProperty;var k=(c,t,e,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of C(t))!y.call(c,o)&&o!==e&&p(c,o,{get:()=>t[o],enumerable:!(s=f(t,o))||s.enumerable});return c};var P=(c,t,e)=>(e=c!=null?m(w(c)):{},k(t||!c||!c.__esModule?p(e,"default",{value:c,enumerable:!0}):e,c));var n=require("fs"),l=P(require("child_process")),r=require("path");var d="checksum";var g=class{constructor(){this.UPLOAD_AGENT_PATH=(0,r.join)(__dirname,"upload-agent.js");this.CHECKSUM_API_URL="http://localhost:3000";this.didFail=!1;this.mock=!0;this.completeIndicators={upload:!1,tests:!1,report:!1};this.guardReturn=async(t,e=1e3,s="action hang guard timed out")=>{let o="guard-timed-out",i=async()=>(await this.awaitSleep(e+1e3),o),a=await Promise.race([t,i()]);if(typeof a=="string"&&a===o)throw new Error(s);return a};this.awaitSleep=t=>new Promise(e=>setTimeout(e,t))}async execute(){var t;switch(process.argv[2]){case"init":this.install();break;case"test":if(((t=process.argv)==null?void 0:t[3])==="--help"){await this.printHelp("test");break}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){let e=await l.spawn(t,{shell:!0,stdio:"inherit"});return new Promise((o,i)=>{e.on("exit",a=>{a===0?o(!0):i(new Error(`Checsum failed execution with code: ${a} `))})})}async getCmdOutput(t){return new Promise(function(e,s){l.exec(t,(o,i,a)=>{if(o){s(`Error executing command: ${o.message}`);return}e(i)})})}async printHelp(t){switch(t){default:console.log(`
1
+ var f=Object.create;var p=Object.defineProperty;var C=Object.getOwnPropertyDescriptor;var w=Object.getOwnPropertyNames;var y=Object.getPrototypeOf,k=Object.prototype.hasOwnProperty;var u=(r,t)=>p(r,"name",{value:t,configurable:!0});var P=(r,t,e,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of w(t))!k.call(r,o)&&o!==e&&p(r,o,{get:()=>t[o],enumerable:!(s=C(t,o))||s.enumerable});return r};var R=(r,t,e)=>(e=r!=null?f(y(r)):{},P(t||!r||!r.__esModule?p(e,"default",{value:r,enumerable:!0}):e,r));var n=require("fs"),l=R(require("child_process")),a=require("path");var m="checksum";var h=class{constructor(){this.UPLOAD_AGENT_PATH=(0,a.join)(__dirname,"upload-agent.js");this.CHECKSUM_API_URL="http://localhost:3000";this.didFail=!1;this.mock=!0;this.completeIndicators={upload:!1,tests:!1,report:!1};this.guardReturn=async(t,e=1e3,s="action hang guard timed out")=>{let o="guard-timed-out",i=u(async()=>(await this.awaitSleep(e+1e3),o),"guard"),c=await Promise.race([t,i()]);if(typeof c=="string"&&c===o)throw new Error(s);return c};this.awaitSleep=t=>new Promise(e=>setTimeout(e,t))}async execute(){switch(process.argv.find(t=>t==="--help"||t==="-h")&&(await this.printHelp(process.argv[2]),process.exit(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){let e=await l.spawn(t,{shell:!0,stdio:"inherit"});return new Promise((o,i)=>{e.on("exit",c=>{c===0?o(!0):i(new Error(`Checsum failed execution with code: ${c} `))})})}async getCmdOutput(t){return new Promise(function(e,s){l.exec(t,(o,i,c)=>{if(o){s(`Error executing command: ${o.message}`);return}e(i)})})}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",s=(await this.getCmdOutput(e)).replace(/npx playwright/g,"yarn checksum").split(`
11
11
  `);s.splice(5,0," --checksum-config=<config> Checksum configuration in JSON format").join(`
12
12
  `),console.log(s.join(`
13
- `))}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(s){console.log("Error showing report",s.message)}}async test(t){t=this.getChecksumConfigFromCommand(t),this.setChecksumConfig(),await this.getSession();let e;try{let{uuid:o,uploadURL:i}=this.testSession;e=await this.guardReturn(this.startUploadAgent(o,i),1e4,"Upload agent timeout")}catch{console.log("Error starting upload agent. Test results will not be available on checksum.")}this.buildVolatileConfig();let s=`${e?`CHECKSUM_UPLOAD_AGENT_PORT=${e} `:""} PWDEBUG=console npx playwright test --config ${this.getPlaywrightConfigFile()} ${t.join(" ")}`;try{await this.execCmd(s)}catch(o){this.didFail=!0,console.log("Error during test",o.message)}finally{let o=this.getPlaywrightReportPath();(0,n.existsSync)(o)?this.uploadAgent.stdin.write(`cli:report=${o}`):console.log(`Could not find report file at ${o}`),this.completeIndicators.tests=!0,await this.handleCompleteMessage()}}getPlaywrightReportPath(){var o,i;let t=(0,r.join)(process.cwd(),"playwright-report"),e=require(this.getPlaywrightConfigFile()),{reporter:s}=e;return s instanceof Array&&s.length>1&&((o=s[1])!=null&&o.outputFolder)&&(t=(i=s[1])==null?void 0:i.outputFolder),process.env.PLAYWRIGHT_HTML_REPORT&&(t=process.env.PLAYWRIGHT_HTML_REPORT),(0,r.join)(t,"index.html")}getPlaywrightConfigFile(){return(0,r.join)(this.getRootDirPath(),"playwright.config.ts")}startUploadAgent(t,e){return new Promise((s,o)=>{console.log("Starting upload agent"),this.uploadAgent=l.spawn("node",[this.UPLOAD_AGENT_PATH,JSON.stringify({sessionId:t,checksumApiURL:this.CHECKSUM_API_URL,apiKey:this.config.apiKey}),...this.mock?["mock"]:[]]),this.uploadAgent.stdout.on("data",i=>{let a=i.toString().trim();if(!a.startsWith("upag:"))return;let[u,h]=a.substring(5).split("=");u==="port"?(console.log("Received port from upload agent",h),s(h)):this.handleUploadAgentMessage(u,h)}),this.uploadAgent.on("exit",(i,a)=>{console.log(`upload agent process exited with code ${i} and signal ${a}`)}),this.uploadAgent.on("error",i=>{console.error(`Error starting upload agent: ${i.message}`)})})}async handleUploadAgentMessage(t,e){switch(t){case"complete":this.sendUploadsComplete().then(()=>{this.completeIndicators.upload=!0});break;case"report-uploaded":let s=await this.sendTestrunEnd();this.completeIndicators.report=!0,s&&console.log(`*******************
13
+ `))}catch(e){console.log("Error",e.message)}break;case"show-report":try{let e="npx playwright show-report --help",s=(await this.getCmdOutput(e)).replace(/npx playwright/g,"yarn checksum");console.log(s)}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(s){console.log("Error showing report",s.message)}}async test(t){t=this.getChecksumConfigFromCommand(t),this.setChecksumConfig(),await this.getSession();let e;try{let{uuid:o,uploadURL:i}=this.testSession;e=await this.guardReturn(this.startUploadAgent(o,i),1e4,"Upload agent timeout")}catch{console.log("Error starting upload agent. Test results will not be available on checksum.")}this.buildVolatileConfig();let s=`${e?`CHECKSUM_UPLOAD_AGENT_PORT=${e} `:""} PWDEBUG=console npx playwright test --config ${this.getPlaywrightConfigFile()} ${t.join(" ")}`;try{await this.execCmd(s)}catch(o){this.didFail=!0,console.log("Error during test",o.message)}finally{let o=this.getPlaywrightReportPath();(0,n.existsSync)(o)?this.uploadAgent.stdin.write(`cli:report=${o}`):console.log(`Could not find report file at ${o}`),this.completeIndicators.tests=!0,await this.handleCompleteMessage()}}getPlaywrightReportPath(){var o,i;let t=(0,a.join)(process.cwd(),"playwright-report"),e=require(this.getPlaywrightConfigFile()),{reporter:s}=e;return s instanceof Array&&s.length>1&&((o=s[1])!=null&&o.outputFolder)&&(t=(i=s[1])==null?void 0:i.outputFolder),process.env.PLAYWRIGHT_HTML_REPORT&&(t=process.env.PLAYWRIGHT_HTML_REPORT),(0,a.join)(t,"index.html")}getPlaywrightConfigFile(){return(0,a.join)(this.getRootDirPath(),"playwright.config.ts")}startUploadAgent(t,e){return new Promise((s,o)=>{console.log("Starting upload agent"),this.uploadAgent=l.spawn("node",[this.UPLOAD_AGENT_PATH,JSON.stringify({sessionId:t,checksumApiURL:this.CHECKSUM_API_URL,apiKey:this.config.apiKey}),...this.mock?["mock"]:[]]),this.uploadAgent.stdout.on("data",i=>{let c=i.toString().trim();if(!c.startsWith("upag:"))return;let[d,g]=c.substring(5).split("=");d==="port"?(console.log("Received port from upload agent",g),s(g)):this.handleUploadAgentMessage(d,g)}),this.uploadAgent.on("exit",(i,c)=>{console.log(`upload agent process exited with code ${i} and signal ${c}`)}),this.uploadAgent.on("error",i=>{console.error(`Error starting upload agent: ${i.message}`)})})}async handleUploadAgentMessage(t,e){switch(t){case"complete":this.sendUploadsComplete().then(()=>{this.completeIndicators.upload=!0});break;case"report-uploaded":let s=await this.sendTestrunEnd();this.completeIndicators.report=!0,s&&console.log(`*******************
14
14
  * Checksum report URL: ${s}
15
15
  *******************`);break;default:console.warn(`Unhandled upload agent message: ${t}=${e}`)}}async handleCompleteMessage(){for(;;)Object.keys(this.completeIndicators).find(t=>!this.completeIndicators[t])?await this.awaitSleep(1e3):(console.log("Tests 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,n.writeFileSync)(t,e)}cleanup(){this.deleteVolatileConfig(),this.uploadAgent.stdin.write("cli:shutdown"),this.uploadAgent.kill()}async getSession(){try{if(this.mock){this.testSession={uuid:"session-id-1234",uploadURL:"http://localhost:3000/upload"};return}let t=this.config.apiKey;(!t||t==="<API key>")&&(console.error("No API key found in checksum config"),this.shutdown(1));let e=JSON.stringify(await this.getEnvInfo()),s=await fetch(`${this.CHECKSUM_API_URL}/client-api/test-runs`,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json",ChecksumAppCode:t},body:e});this.testSession=await s.json()}catch(t){console.error("Error getting checksum test session",t),this.shutdown(1)}}async sendTestrunEnd(){try{if(this.mock)return"https://mock.report.url";let{uuid:t}=this.testSession,e=JSON.stringify({failed:this.didFail?1:0,passed:0,healed:0,endedAt:Date.now()}),{reportURL:s}=await this.updateTestRun(`${this.CHECKSUM_API_URL}/client-api/test-runs/${t}`,"PATCH",e);return s}catch(t){return console.log("Error sending test run end",t.message),null}}async sendUploadsComplete(){if(!this.mock)try{let{uuid:t}=this.testSession;await this.updateTestRun(`${this.CHECKSUM_API_URL}/client-api/test-runs/${t}/uploads-completed`,"PATCH")}catch(t){console.log("Error sending test run uploads complete",t.message)}}async updateTestRun(t,e,s=void 0){return(await fetch(t,{method:e,headers:{Accept:"application/json","Content-Type":"application/json",ChecksumAppCode:this.config.apiKey},body:s})).json()}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 name",e.message)}return t}getVolatileConfigPath(){return(0,r.join)(this.getRootDirPath(),"checksum.config.tmp.ts")}deleteVolatileConfig(){let t=this.getVolatileConfigPath();(0,n.existsSync)(t)&&(0,n.rmSync)(t)}setChecksumConfig(){this.config={...require((0,r.join)(this.getRootDirPath(),"checksum.config.ts")).default||{},...this.volatileChecksumConfig||{}}}getChecksumConfigFromCommand(t){this.deleteVolatileConfig();for(let e of t)if(e.startsWith("--checksum-config"))try{return this.volatileChecksumConfig=JSON.parse(e.split("=")[1]),t.filter(s=>s!==e)}catch(s){console.log("Error parsing checksum config",s.message),this.volatileChecksumConfig=void 0}return t}install(){console.log("Creating Checksum directory and necessary files to run your tests");let t=this.getRootDirPath();if((0,n.existsSync)(this.getRootDirPath())||(0,n.mkdirSync)(t),!(0,n.existsSync)(this.getChecksumRootOrigin()))throw new Error("Could not find checksum root directory, please install @checksum-ai/runtime package");["checksum.config.ts","playwright.config.ts","login.ts","README.md"].forEach(e=>{(0,n.copyFileSync)((0,r.join)(this.getChecksumRootOrigin(),e),(0,r.join)(t,e))}),(0,n.mkdirSync)((0,r.join)(t,"tests"),{recursive:!0}),["esra","har","trace","log"].forEach(e=>{(0,n.mkdirSync)((0,r.join)(t,"test-data",e),{recursive:!0})})}getRootDirPath(){return(0,r.join)(process.cwd(),d)}getChecksumRootOrigin(){return(0,r.join)(process.cwd(),"node_modules","@checksum-ai","runtime","checksum-root")}};(async()=>await new g().execute())();
19
+ `;(0,n.writeFileSync)(t,e)}cleanup(){this.deleteVolatileConfig(),this.uploadAgent.stdin.write("cli:shutdown"),this.uploadAgent.kill()}async getSession(){try{if(this.mock){this.testSession={uuid:"session-id-1234",uploadURL:"http://localhost:3000/upload"};return}let t=this.config.apiKey;(!t||t==="<API key>")&&(console.error("No API key found in checksum config"),this.shutdown(1));let e=JSON.stringify(await this.getEnvInfo()),s=await fetch(`${this.CHECKSUM_API_URL}/client-api/test-runs`,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json",ChecksumAppCode:t},body:e});this.testSession=await s.json()}catch(t){console.error("Error getting checksum test session",t),this.shutdown(1)}}async sendTestrunEnd(){try{if(this.mock)return"https://mock.report.url";let{uuid:t}=this.testSession,e=JSON.stringify({failed:this.didFail?1:0,passed:0,healed:0,endedAt:Date.now()}),{reportURL:s}=await this.updateTestRun(`${this.CHECKSUM_API_URL}/client-api/test-runs/${t}`,"PATCH",e);return s}catch(t){return console.log("Error sending test run end",t.message),null}}async sendUploadsComplete(){if(!this.mock)try{let{uuid:t}=this.testSession;await this.updateTestRun(`${this.CHECKSUM_API_URL}/client-api/test-runs/${t}/uploads-completed`,"PATCH")}catch(t){console.log("Error sending test run uploads complete",t.message)}}async updateTestRun(t,e,s=void 0){return(await fetch(t,{method:e,headers:{Accept:"application/json","Content-Type":"application/json",ChecksumAppCode:this.config.apiKey},body:s})).json()}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 name",e.message)}return t}getVolatileConfigPath(){return(0,a.join)(this.getRootDirPath(),"checksum.config.tmp.ts")}deleteVolatileConfig(){let t=this.getVolatileConfigPath();(0,n.existsSync)(t)&&(0,n.rmSync)(t)}setChecksumConfig(){this.config={...require((0,a.join)(this.getRootDirPath(),"checksum.config.ts")).default||{},...this.volatileChecksumConfig||{}}}getChecksumConfigFromCommand(t){this.deleteVolatileConfig();for(let e of t)if(e.startsWith("--checksum-config"))try{return this.volatileChecksumConfig=JSON.parse(e.split("=")[1]),t.filter(s=>s!==e)}catch(s){console.log("Error parsing checksum config",s.message),this.volatileChecksumConfig=void 0}return t}install(){console.log("Creating Checksum directory and necessary files to run your tests");let t=this.getRootDirPath();if((0,n.existsSync)(this.getRootDirPath())||(0,n.mkdirSync)(t),!(0,n.existsSync)(this.getChecksumRootOrigin()))throw new Error("Could not find checksum root directory, please install @checksum-ai/runtime package");["checksum.config.ts","playwright.config.ts","login.ts","README.md"].forEach(e=>{(0,n.copyFileSync)((0,a.join)(this.getChecksumRootOrigin(),e),(0,a.join)(t,e))}),(0,n.mkdirSync)((0,a.join)(t,"tests"),{recursive:!0}),["esra","har","trace","log"].forEach(e=>{(0,n.mkdirSync)((0,a.join)(t,"test-data",e),{recursive:!0})})}getRootDirPath(){return(0,a.join)(process.cwd(),m)}getChecksumRootOrigin(){return(0,a.join)(process.cwd(),"node_modules","@checksum-ai","runtime","checksum-root")}};u(h,"ChecksumCLI");(async()=>await new h().execute())();