agenqa 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/README.md +92 -0
  2. package/dist/cli.cjs +43 -0
  3. package/package.json +26 -0
package/README.md ADDED
@@ -0,0 +1,92 @@
1
+ # AgenQA
2
+
3
+ Run your AgenQA tests from any terminal with a clean, predictable workflow.
4
+
5
+ **Quick Start**
6
+ - Install: `npm i -g agenqa`
7
+ - Import a project: `agenqa import --project <projectId> --key-secret <secret>`
8
+ - Run tests: `agenqa run-project --project <projectId>`
9
+
10
+ ## Project Management
11
+
12
+ ### Import a Project (Step by Step)
13
+
14
+ 1) Open AgenQA, go to Project settings → Cloud Sync, and copy:
15
+ - Project ID
16
+ - Key Secret
17
+ Only the project owner can view and create key secrets.
18
+
19
+ 2) In your terminal, run:
20
+
21
+ ```bash
22
+ agenqa import --project <projectId> --key-secret <secret>
23
+ ```
24
+
25
+ 3) Confirm that you trust the source.
26
+ 4) Choose whether to enable local cache on this machine (required for cloud cache).
27
+ 5) If local cache is enabled, choose whether to enable cloud cache (see the warning below).
28
+ 6) You’ll see a sync summary once the import completes.
29
+
30
+ You’re done — the project is now ready to run.
31
+
32
+ ### List Stored Projects
33
+
34
+ ```bash
35
+ agenqa list
36
+ ```
37
+
38
+ Displays imported projects with base URL, cache status, and import time.
39
+
40
+ ### Remove a Project
41
+
42
+ ```bash
43
+ agenqa remove-project --project <projectId>
44
+ ```
45
+
46
+ Removes the local config and synced files for the project. This does not delete the cloud project.
47
+
48
+ ## Run Tests
49
+
50
+ ```bash
51
+ agenqa run-project --project <projectId>
52
+ agenqa run-folder --project <projectId> --folder <folderId>
53
+ agenqa run-test --project <projectId> --test <testId>
54
+ ```
55
+
56
+ ### Silent Mode
57
+
58
+ Suppress non-error logs (still exits non-zero on failures):
59
+
60
+ ```bash
61
+ agenqa run-project --project <projectId> --silent
62
+ ```
63
+
64
+ ## Cache Controls
65
+
66
+ Use cache per run:
67
+
68
+ ```bash
69
+ agenqa run-project --project <projectId> --cache
70
+ agenqa run-project --project <projectId> --no-cache
71
+ ```
72
+
73
+ Or set it once for a project (cloud cache):
74
+
75
+ ```bash
76
+ agenqa cache --project <projectId> --enable
77
+ agenqa cache --project <projectId> --disable
78
+ ```
79
+
80
+ Clear local cache for a project (includes downloaded cloud cache and local-only cache):
81
+
82
+ ```bash
83
+ agenqa reset-cache --project <projectId>
84
+ ```
85
+
86
+ **Warning:** cloud cache reuses generated steps from collaborators. Enable it only if you trust the owner and every collaborator.
87
+ Note: disabling local cache during import also disables cloud cache.
88
+
89
+ ## Troubleshooting
90
+
91
+ - “Project is not imported”: run the import command again.
92
+ - “Key is invalid or expired”: re-import with a fresh key.
package/dist/cli.cjs ADDED
@@ -0,0 +1,43 @@
1
+ #!/usr/bin/env node
2
+ var br=Object.create;var Ke=Object.defineProperty;var Cr=Object.getOwnPropertyDescriptor;var Er=Object.getOwnPropertyNames;var vr=Object.getPrototypeOf,xr=Object.prototype.hasOwnProperty;var Ar=(s,e)=>()=>(s&&(e=s(s=0)),e);var Z=(s,e)=>()=>(e||s((e={exports:{}}).exports,e),e.exports),$r=(s,e)=>{for(var t in e)Ke(s,t,{get:e[t],enumerable:!0})},Or=(s,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of Er(e))!xr.call(s,n)&&n!==t&&Ke(s,n,{get:()=>e[n],enumerable:!(r=Cr(e,n))||r.enumerable});return s};var I=(s,e,t)=>(t=s!=null?br(vr(s)):{},Or(e||!s||!s.__esModule?Ke(t,"default",{value:s,enumerable:!0}):t,s));var we=Z(ze=>{var Oe=class extends Error{constructor(e,t,r){super(r),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=t,this.exitCode=e,this.nestedError=void 0}},Ye=class extends Oe{constructor(e){super(1,"commander.invalidArgument",e),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}};ze.CommanderError=Oe;ze.InvalidArgumentError=Ye});var je=Z(Xe=>{var{InvalidArgumentError:jr}=we(),Qe=class{constructor(e,t){switch(this.description=t||"",this.variadic=!1,this.parseArg=void 0,this.defaultValue=void 0,this.defaultValueDescription=void 0,this.argChoices=void 0,e[0]){case"<":this.required=!0,this._name=e.slice(1,-1);break;case"[":this.required=!1,this._name=e.slice(1,-1);break;default:this.required=!0,this._name=e;break}this._name.length>3&&this._name.slice(-3)==="..."&&(this.variadic=!0,this._name=this._name.slice(0,-3))}name(){return this._name}_concatValue(e,t){return t===this.defaultValue||!Array.isArray(t)?[e]:t.concat(e)}default(e,t){return this.defaultValue=e,this.defaultValueDescription=t,this}argParser(e){return this.parseArg=e,this}choices(e){return this.argChoices=e.slice(),this.parseArg=(t,r)=>{if(!this.argChoices.includes(t))throw new jr(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._concatValue(t,r):t},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}};function kr(s){let e=s.name()+(s.variadic===!0?"...":"");return s.required?"<"+e+">":"["+e+"]"}Xe.Argument=Qe;Xe.humanReadableArgName=kr});var et=Z(Ot=>{var{humanReadableArgName:Pr}=je(),Ze=class{constructor(){this.helpWidth=void 0,this.sortSubcommands=!1,this.sortOptions=!1,this.showGlobalOptions=!1}visibleCommands(e){let t=e.commands.filter(n=>!n._hidden),r=e._getHelpCommand();return r&&!r._hidden&&t.push(r),this.sortSubcommands&&t.sort((n,i)=>n.name().localeCompare(i.name())),t}compareOptions(e,t){let r=n=>n.short?n.short.replace(/^-/,""):n.long.replace(/^--/,"");return r(e).localeCompare(r(t))}visibleOptions(e){let t=e.options.filter(n=>!n.hidden),r=e._getHelpOption();if(r&&!r.hidden){let n=r.short&&e._findOption(r.short),i=r.long&&e._findOption(r.long);!n&&!i?t.push(r):r.long&&!i?t.push(e.createOption(r.long,r.description)):r.short&&!n&&t.push(e.createOption(r.short,r.description))}return this.sortOptions&&t.sort(this.compareOptions),t}visibleGlobalOptions(e){if(!this.showGlobalOptions)return[];let t=[];for(let r=e.parent;r;r=r.parent){let n=r.options.filter(i=>!i.hidden);t.push(...n)}return this.sortOptions&&t.sort(this.compareOptions),t}visibleArguments(e){return e._argsDescription&&e.registeredArguments.forEach(t=>{t.description=t.description||e._argsDescription[t.name()]||""}),e.registeredArguments.find(t=>t.description)?e.registeredArguments:[]}subcommandTerm(e){let t=e.registeredArguments.map(r=>Pr(r)).join(" ");return e._name+(e._aliases[0]?"|"+e._aliases[0]:"")+(e.options.length?" [options]":"")+(t?" "+t:"")}optionTerm(e){return e.flags}argumentTerm(e){return e.name()}longestSubcommandTermLength(e,t){return t.visibleCommands(e).reduce((r,n)=>Math.max(r,t.subcommandTerm(n).length),0)}longestOptionTermLength(e,t){return t.visibleOptions(e).reduce((r,n)=>Math.max(r,t.optionTerm(n).length),0)}longestGlobalOptionTermLength(e,t){return t.visibleGlobalOptions(e).reduce((r,n)=>Math.max(r,t.optionTerm(n).length),0)}longestArgumentTermLength(e,t){return t.visibleArguments(e).reduce((r,n)=>Math.max(r,t.argumentTerm(n).length),0)}commandUsage(e){let t=e._name;e._aliases[0]&&(t=t+"|"+e._aliases[0]);let r="";for(let n=e.parent;n;n=n.parent)r=n.name()+" "+r;return r+t+" "+e.usage()}commandDescription(e){return e.description()}subcommandDescription(e){return e.summary()||e.description()}optionDescription(e){let t=[];return e.argChoices&&t.push(`choices: ${e.argChoices.map(r=>JSON.stringify(r)).join(", ")}`),e.defaultValue!==void 0&&(e.required||e.optional||e.isBoolean()&&typeof e.defaultValue=="boolean")&&t.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),e.presetArg!==void 0&&e.optional&&t.push(`preset: ${JSON.stringify(e.presetArg)}`),e.envVar!==void 0&&t.push(`env: ${e.envVar}`),t.length>0?`${e.description} (${t.join(", ")})`:e.description}argumentDescription(e){let t=[];if(e.argChoices&&t.push(`choices: ${e.argChoices.map(r=>JSON.stringify(r)).join(", ")}`),e.defaultValue!==void 0&&t.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),t.length>0){let r=`(${t.join(", ")})`;return e.description?`${e.description} ${r}`:r}return e.description}formatHelp(e,t){let r=t.padWidth(e,t),n=t.helpWidth||80,i=2,o=2;function a(g,m){if(m){let w=`${g.padEnd(r+o)}${m}`;return t.wrap(w,n-i,r+o)}return g}function c(g){return g.join(`
3
+ `).replace(/^/gm," ".repeat(i))}let l=[`Usage: ${t.commandUsage(e)}`,""],u=t.commandDescription(e);u.length>0&&(l=l.concat([t.wrap(u,n,0),""]));let d=t.visibleArguments(e).map(g=>a(t.argumentTerm(g),t.argumentDescription(g)));d.length>0&&(l=l.concat(["Arguments:",c(d),""]));let h=t.visibleOptions(e).map(g=>a(t.optionTerm(g),t.optionDescription(g)));if(h.length>0&&(l=l.concat(["Options:",c(h),""])),this.showGlobalOptions){let g=t.visibleGlobalOptions(e).map(m=>a(t.optionTerm(m),t.optionDescription(m)));g.length>0&&(l=l.concat(["Global Options:",c(g),""]))}let p=t.visibleCommands(e).map(g=>a(t.subcommandTerm(g),t.subcommandDescription(g)));return p.length>0&&(l=l.concat(["Commands:",c(p),""])),l.join(`
4
+ `)}padWidth(e,t){return Math.max(t.longestOptionTermLength(e,t),t.longestGlobalOptionTermLength(e,t),t.longestSubcommandTermLength(e,t),t.longestArgumentTermLength(e,t))}wrap(e,t,r,n=40){let i=" \\f\\t\\v\xA0\u1680\u2000-\u200A\u202F\u205F\u3000\uFEFF",o=new RegExp(`[\\n][${i}]+`);if(e.match(o))return e;let a=t-r;if(a<n)return e;let c=e.slice(0,r),l=e.slice(r).replace(`\r
5
+ `,`
6
+ `),u=" ".repeat(r),h="\\s\u200B",p=new RegExp(`
7
+ |.{1,${a-1}}([${h}]|$)|[^${h}]+?([${h}]|$)`,"g"),g=l.match(p)||[];return c+g.map((m,w)=>m===`
8
+ `?"":(w>0?u:"")+m.trimEnd()).join(`
9
+ `)}};Ot.Help=Ze});var st=Z(nt=>{var{InvalidArgumentError:Dr}=we(),tt=class{constructor(e,t){this.flags=e,this.description=t||"",this.required=e.includes("<"),this.optional=e.includes("["),this.variadic=/\w\.\.\.[>\]]$/.test(e),this.mandatory=!1;let r=Nr(e);this.short=r.shortFlag,this.long=r.longFlag,this.negate=!1,this.long&&(this.negate=this.long.startsWith("--no-")),this.defaultValue=void 0,this.defaultValueDescription=void 0,this.presetArg=void 0,this.envVar=void 0,this.parseArg=void 0,this.hidden=!1,this.argChoices=void 0,this.conflictsWith=[],this.implied=void 0}default(e,t){return this.defaultValue=e,this.defaultValueDescription=t,this}preset(e){return this.presetArg=e,this}conflicts(e){return this.conflictsWith=this.conflictsWith.concat(e),this}implies(e){let t=e;return typeof e=="string"&&(t={[e]:!0}),this.implied=Object.assign(this.implied||{},t),this}env(e){return this.envVar=e,this}argParser(e){return this.parseArg=e,this}makeOptionMandatory(e=!0){return this.mandatory=!!e,this}hideHelp(e=!0){return this.hidden=!!e,this}_concatValue(e,t){return t===this.defaultValue||!Array.isArray(t)?[e]:t.concat(e)}choices(e){return this.argChoices=e.slice(),this.parseArg=(t,r)=>{if(!this.argChoices.includes(t))throw new Dr(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._concatValue(t,r):t},this}name(){return this.long?this.long.replace(/^--/,""):this.short.replace(/^-/,"")}attributeName(){return Fr(this.name().replace(/^no-/,""))}is(e){return this.short===e||this.long===e}isBoolean(){return!this.required&&!this.optional&&!this.negate}},rt=class{constructor(e){this.positiveOptions=new Map,this.negativeOptions=new Map,this.dualOptions=new Set,e.forEach(t=>{t.negate?this.negativeOptions.set(t.attributeName(),t):this.positiveOptions.set(t.attributeName(),t)}),this.negativeOptions.forEach((t,r)=>{this.positiveOptions.has(r)&&this.dualOptions.add(r)})}valueFromOption(e,t){let r=t.attributeName();if(!this.dualOptions.has(r))return!0;let n=this.negativeOptions.get(r).presetArg,i=n!==void 0?n:!1;return t.negate===(i===e)}};function Fr(s){return s.split("-").reduce((e,t)=>e+t[0].toUpperCase()+t.slice(1))}function Nr(s){let e,t,r=s.split(/[ |,]+/);return r.length>1&&!/^[[<]/.test(r[1])&&(e=r.shift()),t=r.shift(),!e&&/^-[^-]$/.test(t)&&(e=t,t=void 0),{shortFlag:e,longFlag:t}}nt.Option=tt;nt.DualOptions=rt});var kt=Z(jt=>{function Lr(s,e){if(Math.abs(s.length-e.length)>3)return Math.max(s.length,e.length);let t=[];for(let r=0;r<=s.length;r++)t[r]=[r];for(let r=0;r<=e.length;r++)t[0][r]=r;for(let r=1;r<=e.length;r++)for(let n=1;n<=s.length;n++){let i=1;s[n-1]===e[r-1]?i=0:i=1,t[n][r]=Math.min(t[n-1][r]+1,t[n][r-1]+1,t[n-1][r-1]+i),n>1&&r>1&&s[n-1]===e[r-2]&&s[n-2]===e[r-1]&&(t[n][r]=Math.min(t[n][r],t[n-2][r-2]+1))}return t[s.length][e.length]}function Rr(s,e){if(!e||e.length===0)return"";e=Array.from(new Set(e));let t=s.startsWith("--");t&&(s=s.slice(2),e=e.map(o=>o.slice(2)));let r=[],n=3,i=.4;return e.forEach(o=>{if(o.length<=1)return;let a=Lr(s,o),c=Math.max(s.length,o.length);(c-a)/c>i&&(a<n?(n=a,r=[o]):a===n&&r.push(o))}),r.sort((o,a)=>o.localeCompare(a)),t&&(r=r.map(o=>`--${o}`)),r.length>1?`
10
+ (Did you mean one of ${r.join(", ")}?)`:r.length===1?`
11
+ (Did you mean ${r[0]}?)`:""}jt.suggestSimilar=Rr});var Lt=Z(Nt=>{var Ir=require("node:events").EventEmitter,it=require("node:child_process"),ee=require("node:path"),ot=require("node:fs"),j=require("node:process"),{Argument:Tr,humanReadableArgName:Vr}=je(),{CommanderError:at}=we(),{Help:Ur}=et(),{Option:Pt,DualOptions:Hr}=st(),{suggestSimilar:Dt}=kt(),ct=class s extends Ir{constructor(e){super(),this.commands=[],this.options=[],this.parent=null,this._allowUnknownOption=!1,this._allowExcessArguments=!0,this.registeredArguments=[],this._args=this.registeredArguments,this.args=[],this.rawArgs=[],this.processedArgs=[],this._scriptPath=null,this._name=e||"",this._optionValues={},this._optionValueSources={},this._storeOptionsAsProperties=!1,this._actionHandler=null,this._executableHandler=!1,this._executableFile=null,this._executableDir=null,this._defaultCommandName=null,this._exitCallback=null,this._aliases=[],this._combineFlagAndOptionalValue=!0,this._description="",this._summary="",this._argsDescription=void 0,this._enablePositionalOptions=!1,this._passThroughOptions=!1,this._lifeCycleHooks={},this._showHelpAfterError=!1,this._showSuggestionAfterError=!0,this._outputConfiguration={writeOut:t=>j.stdout.write(t),writeErr:t=>j.stderr.write(t),getOutHelpWidth:()=>j.stdout.isTTY?j.stdout.columns:void 0,getErrHelpWidth:()=>j.stderr.isTTY?j.stderr.columns:void 0,outputError:(t,r)=>r(t)},this._hidden=!1,this._helpOption=void 0,this._addImplicitHelpCommand=void 0,this._helpCommand=void 0,this._helpConfiguration={}}copyInheritedSettings(e){return this._outputConfiguration=e._outputConfiguration,this._helpOption=e._helpOption,this._helpCommand=e._helpCommand,this._helpConfiguration=e._helpConfiguration,this._exitCallback=e._exitCallback,this._storeOptionsAsProperties=e._storeOptionsAsProperties,this._combineFlagAndOptionalValue=e._combineFlagAndOptionalValue,this._allowExcessArguments=e._allowExcessArguments,this._enablePositionalOptions=e._enablePositionalOptions,this._showHelpAfterError=e._showHelpAfterError,this._showSuggestionAfterError=e._showSuggestionAfterError,this}_getCommandAndAncestors(){let e=[];for(let t=this;t;t=t.parent)e.push(t);return e}command(e,t,r){let n=t,i=r;typeof n=="object"&&n!==null&&(i=n,n=null),i=i||{};let[,o,a]=e.match(/([^ ]+) *(.*)/),c=this.createCommand(o);return n&&(c.description(n),c._executableHandler=!0),i.isDefault&&(this._defaultCommandName=c._name),c._hidden=!!(i.noHelp||i.hidden),c._executableFile=i.executableFile||null,a&&c.arguments(a),this._registerCommand(c),c.parent=this,c.copyInheritedSettings(this),n?this:c}createCommand(e){return new s(e)}createHelp(){return Object.assign(new Ur,this.configureHelp())}configureHelp(e){return e===void 0?this._helpConfiguration:(this._helpConfiguration=e,this)}configureOutput(e){return e===void 0?this._outputConfiguration:(Object.assign(this._outputConfiguration,e),this)}showHelpAfterError(e=!0){return typeof e!="string"&&(e=!!e),this._showHelpAfterError=e,this}showSuggestionAfterError(e=!0){return this._showSuggestionAfterError=!!e,this}addCommand(e,t){if(!e._name)throw new Error(`Command passed to .addCommand() must have a name
12
+ - specify the name in Command constructor or using .name()`);return t=t||{},t.isDefault&&(this._defaultCommandName=e._name),(t.noHelp||t.hidden)&&(e._hidden=!0),this._registerCommand(e),e.parent=this,e._checkForBrokenPassThrough(),this}createArgument(e,t){return new Tr(e,t)}argument(e,t,r,n){let i=this.createArgument(e,t);return typeof r=="function"?i.default(n).argParser(r):i.default(r),this.addArgument(i),this}arguments(e){return e.trim().split(/ +/).forEach(t=>{this.argument(t)}),this}addArgument(e){let t=this.registeredArguments.slice(-1)[0];if(t&&t.variadic)throw new Error(`only the last argument can be variadic '${t.name()}'`);if(e.required&&e.defaultValue!==void 0&&e.parseArg===void 0)throw new Error(`a default value for a required argument is never used: '${e.name()}'`);return this.registeredArguments.push(e),this}helpCommand(e,t){if(typeof e=="boolean")return this._addImplicitHelpCommand=e,this;e=e??"help [command]";let[,r,n]=e.match(/([^ ]+) *(.*)/),i=t??"display help for command",o=this.createCommand(r);return o.helpOption(!1),n&&o.arguments(n),i&&o.description(i),this._addImplicitHelpCommand=!0,this._helpCommand=o,this}addHelpCommand(e,t){return typeof e!="object"?(this.helpCommand(e,t),this):(this._addImplicitHelpCommand=!0,this._helpCommand=e,this)}_getHelpCommand(){return this._addImplicitHelpCommand??(this.commands.length&&!this._actionHandler&&!this._findCommand("help"))?(this._helpCommand===void 0&&this.helpCommand(void 0,void 0),this._helpCommand):null}hook(e,t){let r=["preSubcommand","preAction","postAction"];if(!r.includes(e))throw new Error(`Unexpected value for event passed to hook : '${e}'.
13
+ Expecting one of '${r.join("', '")}'`);return this._lifeCycleHooks[e]?this._lifeCycleHooks[e].push(t):this._lifeCycleHooks[e]=[t],this}exitOverride(e){return e?this._exitCallback=e:this._exitCallback=t=>{if(t.code!=="commander.executeSubCommandAsync")throw t},this}_exit(e,t,r){this._exitCallback&&this._exitCallback(new at(e,t,r)),j.exit(e)}action(e){let t=r=>{let n=this.registeredArguments.length,i=r.slice(0,n);return this._storeOptionsAsProperties?i[n]=this:i[n]=this.opts(),i.push(this),e.apply(this,i)};return this._actionHandler=t,this}createOption(e,t){return new Pt(e,t)}_callParseArg(e,t,r,n){try{return e.parseArg(t,r)}catch(i){if(i.code==="commander.invalidArgument"){let o=`${n} ${i.message}`;this.error(o,{exitCode:i.exitCode,code:i.code})}throw i}}_registerOption(e){let t=e.short&&this._findOption(e.short)||e.long&&this._findOption(e.long);if(t){let r=e.long&&this._findOption(e.long)?e.long:e.short;throw new Error(`Cannot add option '${e.flags}'${this._name&&` to command '${this._name}'`} due to conflicting flag '${r}'
14
+ - already used by option '${t.flags}'`)}this.options.push(e)}_registerCommand(e){let t=n=>[n.name()].concat(n.aliases()),r=t(e).find(n=>this._findCommand(n));if(r){let n=t(this._findCommand(r)).join("|"),i=t(e).join("|");throw new Error(`cannot add command '${i}' as already have command '${n}'`)}this.commands.push(e)}addOption(e){this._registerOption(e);let t=e.name(),r=e.attributeName();if(e.negate){let i=e.long.replace(/^--no-/,"--");this._findOption(i)||this.setOptionValueWithSource(r,e.defaultValue===void 0?!0:e.defaultValue,"default")}else e.defaultValue!==void 0&&this.setOptionValueWithSource(r,e.defaultValue,"default");let n=(i,o,a)=>{i==null&&e.presetArg!==void 0&&(i=e.presetArg);let c=this.getOptionValue(r);i!==null&&e.parseArg?i=this._callParseArg(e,i,c,o):i!==null&&e.variadic&&(i=e._concatValue(i,c)),i==null&&(e.negate?i=!1:e.isBoolean()||e.optional?i=!0:i=""),this.setOptionValueWithSource(r,i,a)};return this.on("option:"+t,i=>{let o=`error: option '${e.flags}' argument '${i}' is invalid.`;n(i,o,"cli")}),e.envVar&&this.on("optionEnv:"+t,i=>{let o=`error: option '${e.flags}' value '${i}' from env '${e.envVar}' is invalid.`;n(i,o,"env")}),this}_optionEx(e,t,r,n,i){if(typeof t=="object"&&t instanceof Pt)throw new Error("To add an Option object use addOption() instead of option() or requiredOption()");let o=this.createOption(t,r);if(o.makeOptionMandatory(!!e.mandatory),typeof n=="function")o.default(i).argParser(n);else if(n instanceof RegExp){let a=n;n=(c,l)=>{let u=a.exec(c);return u?u[0]:l},o.default(i).argParser(n)}else o.default(n);return this.addOption(o)}option(e,t,r,n){return this._optionEx({},e,t,r,n)}requiredOption(e,t,r,n){return this._optionEx({mandatory:!0},e,t,r,n)}combineFlagAndOptionalValue(e=!0){return this._combineFlagAndOptionalValue=!!e,this}allowUnknownOption(e=!0){return this._allowUnknownOption=!!e,this}allowExcessArguments(e=!0){return this._allowExcessArguments=!!e,this}enablePositionalOptions(e=!0){return this._enablePositionalOptions=!!e,this}passThroughOptions(e=!0){return this._passThroughOptions=!!e,this._checkForBrokenPassThrough(),this}_checkForBrokenPassThrough(){if(this.parent&&this._passThroughOptions&&!this.parent._enablePositionalOptions)throw new Error(`passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`)}storeOptionsAsProperties(e=!0){if(this.options.length)throw new Error("call .storeOptionsAsProperties() before adding options");if(Object.keys(this._optionValues).length)throw new Error("call .storeOptionsAsProperties() before setting option values");return this._storeOptionsAsProperties=!!e,this}getOptionValue(e){return this._storeOptionsAsProperties?this[e]:this._optionValues[e]}setOptionValue(e,t){return this.setOptionValueWithSource(e,t,void 0)}setOptionValueWithSource(e,t,r){return this._storeOptionsAsProperties?this[e]=t:this._optionValues[e]=t,this._optionValueSources[e]=r,this}getOptionValueSource(e){return this._optionValueSources[e]}getOptionValueSourceWithGlobals(e){let t;return this._getCommandAndAncestors().forEach(r=>{r.getOptionValueSource(e)!==void 0&&(t=r.getOptionValueSource(e))}),t}_prepareUserArgs(e,t){if(e!==void 0&&!Array.isArray(e))throw new Error("first parameter to parse must be array or undefined");if(t=t||{},e===void 0&&t.from===void 0){j.versions?.electron&&(t.from="electron");let n=j.execArgv??[];(n.includes("-e")||n.includes("--eval")||n.includes("-p")||n.includes("--print"))&&(t.from="eval")}e===void 0&&(e=j.argv),this.rawArgs=e.slice();let r;switch(t.from){case void 0:case"node":this._scriptPath=e[1],r=e.slice(2);break;case"electron":j.defaultApp?(this._scriptPath=e[1],r=e.slice(2)):r=e.slice(1);break;case"user":r=e.slice(0);break;case"eval":r=e.slice(1);break;default:throw new Error(`unexpected parse option { from: '${t.from}' }`)}return!this._name&&this._scriptPath&&this.nameFromFilename(this._scriptPath),this._name=this._name||"program",r}parse(e,t){let r=this._prepareUserArgs(e,t);return this._parseCommand([],r),this}async parseAsync(e,t){let r=this._prepareUserArgs(e,t);return await this._parseCommand([],r),this}_executeSubCommand(e,t){t=t.slice();let r=!1,n=[".js",".ts",".tsx",".mjs",".cjs"];function i(u,d){let h=ee.resolve(u,d);if(ot.existsSync(h))return h;if(n.includes(ee.extname(d)))return;let p=n.find(g=>ot.existsSync(`${h}${g}`));if(p)return`${h}${p}`}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let o=e._executableFile||`${this._name}-${e._name}`,a=this._executableDir||"";if(this._scriptPath){let u;try{u=ot.realpathSync(this._scriptPath)}catch{u=this._scriptPath}a=ee.resolve(ee.dirname(u),a)}if(a){let u=i(a,o);if(!u&&!e._executableFile&&this._scriptPath){let d=ee.basename(this._scriptPath,ee.extname(this._scriptPath));d!==this._name&&(u=i(a,`${d}-${e._name}`))}o=u||o}r=n.includes(ee.extname(o));let c;j.platform!=="win32"?r?(t.unshift(o),t=Ft(j.execArgv).concat(t),c=it.spawn(j.argv[0],t,{stdio:"inherit"})):c=it.spawn(o,t,{stdio:"inherit"}):(t.unshift(o),t=Ft(j.execArgv).concat(t),c=it.spawn(j.execPath,t,{stdio:"inherit"})),c.killed||["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach(d=>{j.on(d,()=>{c.killed===!1&&c.exitCode===null&&c.kill(d)})});let l=this._exitCallback;c.on("close",u=>{u=u??1,l?l(new at(u,"commander.executeSubCommandAsync","(close)")):j.exit(u)}),c.on("error",u=>{if(u.code==="ENOENT"){let d=a?`searched for local subcommand relative to directory '${a}'`:"no directory for search for local subcommand, use .executableDir() to supply a custom directory",h=`'${o}' does not exist
15
+ - if '${e._name}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
16
+ - if the default executable name is not suitable, use the executableFile option to supply a custom name or path
17
+ - ${d}`;throw new Error(h)}else if(u.code==="EACCES")throw new Error(`'${o}' not executable`);if(!l)j.exit(1);else{let d=new at(1,"commander.executeSubCommandAsync","(error)");d.nestedError=u,l(d)}}),this.runningCommand=c}_dispatchSubcommand(e,t,r){let n=this._findCommand(e);n||this.help({error:!0});let i;return i=this._chainOrCallSubCommandHook(i,n,"preSubcommand"),i=this._chainOrCall(i,()=>{if(n._executableHandler)this._executeSubCommand(n,t.concat(r));else return n._parseCommand(t,r)}),i}_dispatchHelpCommand(e){e||this.help();let t=this._findCommand(e);return t&&!t._executableHandler&&t.help(),this._dispatchSubcommand(e,[],[this._getHelpOption()?.long??this._getHelpOption()?.short??"--help"])}_checkNumberOfArguments(){this.registeredArguments.forEach((e,t)=>{e.required&&this.args[t]==null&&this.missingArgument(e.name())}),!(this.registeredArguments.length>0&&this.registeredArguments[this.registeredArguments.length-1].variadic)&&this.args.length>this.registeredArguments.length&&this._excessArguments(this.args)}_processArguments(){let e=(r,n,i)=>{let o=n;if(n!==null&&r.parseArg){let a=`error: command-argument value '${n}' is invalid for argument '${r.name()}'.`;o=this._callParseArg(r,n,i,a)}return o};this._checkNumberOfArguments();let t=[];this.registeredArguments.forEach((r,n)=>{let i=r.defaultValue;r.variadic?n<this.args.length?(i=this.args.slice(n),r.parseArg&&(i=i.reduce((o,a)=>e(r,a,o),r.defaultValue))):i===void 0&&(i=[]):n<this.args.length&&(i=this.args[n],r.parseArg&&(i=e(r,i,r.defaultValue))),t[n]=i}),this.processedArgs=t}_chainOrCall(e,t){return e&&e.then&&typeof e.then=="function"?e.then(()=>t()):t()}_chainOrCallHooks(e,t){let r=e,n=[];return this._getCommandAndAncestors().reverse().filter(i=>i._lifeCycleHooks[t]!==void 0).forEach(i=>{i._lifeCycleHooks[t].forEach(o=>{n.push({hookedCommand:i,callback:o})})}),t==="postAction"&&n.reverse(),n.forEach(i=>{r=this._chainOrCall(r,()=>i.callback(i.hookedCommand,this))}),r}_chainOrCallSubCommandHook(e,t,r){let n=e;return this._lifeCycleHooks[r]!==void 0&&this._lifeCycleHooks[r].forEach(i=>{n=this._chainOrCall(n,()=>i(this,t))}),n}_parseCommand(e,t){let r=this.parseOptions(t);if(this._parseOptionsEnv(),this._parseOptionsImplied(),e=e.concat(r.operands),t=r.unknown,this.args=e.concat(t),e&&this._findCommand(e[0]))return this._dispatchSubcommand(e[0],e.slice(1),t);if(this._getHelpCommand()&&e[0]===this._getHelpCommand().name())return this._dispatchHelpCommand(e[1]);if(this._defaultCommandName)return this._outputHelpIfRequested(t),this._dispatchSubcommand(this._defaultCommandName,e,t);this.commands.length&&this.args.length===0&&!this._actionHandler&&!this._defaultCommandName&&this.help({error:!0}),this._outputHelpIfRequested(r.unknown),this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let n=()=>{r.unknown.length>0&&this.unknownOption(r.unknown[0])},i=`command:${this.name()}`;if(this._actionHandler){n(),this._processArguments();let o;return o=this._chainOrCallHooks(o,"preAction"),o=this._chainOrCall(o,()=>this._actionHandler(this.processedArgs)),this.parent&&(o=this._chainOrCall(o,()=>{this.parent.emit(i,e,t)})),o=this._chainOrCallHooks(o,"postAction"),o}if(this.parent&&this.parent.listenerCount(i))n(),this._processArguments(),this.parent.emit(i,e,t);else if(e.length){if(this._findCommand("*"))return this._dispatchSubcommand("*",e,t);this.listenerCount("command:*")?this.emit("command:*",e,t):this.commands.length?this.unknownCommand():(n(),this._processArguments())}else this.commands.length?(n(),this.help({error:!0})):(n(),this._processArguments())}_findCommand(e){if(e)return this.commands.find(t=>t._name===e||t._aliases.includes(e))}_findOption(e){return this.options.find(t=>t.is(e))}_checkForMissingMandatoryOptions(){this._getCommandAndAncestors().forEach(e=>{e.options.forEach(t=>{t.mandatory&&e.getOptionValue(t.attributeName())===void 0&&e.missingMandatoryOptionValue(t)})})}_checkForConflictingLocalOptions(){let e=this.options.filter(r=>{let n=r.attributeName();return this.getOptionValue(n)===void 0?!1:this.getOptionValueSource(n)!=="default"});e.filter(r=>r.conflictsWith.length>0).forEach(r=>{let n=e.find(i=>r.conflictsWith.includes(i.attributeName()));n&&this._conflictingOption(r,n)})}_checkForConflictingOptions(){this._getCommandAndAncestors().forEach(e=>{e._checkForConflictingLocalOptions()})}parseOptions(e){let t=[],r=[],n=t,i=e.slice();function o(c){return c.length>1&&c[0]==="-"}let a=null;for(;i.length;){let c=i.shift();if(c==="--"){n===r&&n.push(c),n.push(...i);break}if(a&&!o(c)){this.emit(`option:${a.name()}`,c);continue}if(a=null,o(c)){let l=this._findOption(c);if(l){if(l.required){let u=i.shift();u===void 0&&this.optionMissingArgument(l),this.emit(`option:${l.name()}`,u)}else if(l.optional){let u=null;i.length>0&&!o(i[0])&&(u=i.shift()),this.emit(`option:${l.name()}`,u)}else this.emit(`option:${l.name()}`);a=l.variadic?l:null;continue}}if(c.length>2&&c[0]==="-"&&c[1]!=="-"){let l=this._findOption(`-${c[1]}`);if(l){l.required||l.optional&&this._combineFlagAndOptionalValue?this.emit(`option:${l.name()}`,c.slice(2)):(this.emit(`option:${l.name()}`),i.unshift(`-${c.slice(2)}`));continue}}if(/^--[^=]+=/.test(c)){let l=c.indexOf("="),u=this._findOption(c.slice(0,l));if(u&&(u.required||u.optional)){this.emit(`option:${u.name()}`,c.slice(l+1));continue}}if(o(c)&&(n=r),(this._enablePositionalOptions||this._passThroughOptions)&&t.length===0&&r.length===0){if(this._findCommand(c)){t.push(c),i.length>0&&r.push(...i);break}else if(this._getHelpCommand()&&c===this._getHelpCommand().name()){t.push(c),i.length>0&&t.push(...i);break}else if(this._defaultCommandName){r.push(c),i.length>0&&r.push(...i);break}}if(this._passThroughOptions){n.push(c),i.length>0&&n.push(...i);break}n.push(c)}return{operands:t,unknown:r}}opts(){if(this._storeOptionsAsProperties){let e={},t=this.options.length;for(let r=0;r<t;r++){let n=this.options[r].attributeName();e[n]=n===this._versionOptionName?this._version:this[n]}return e}return this._optionValues}optsWithGlobals(){return this._getCommandAndAncestors().reduce((e,t)=>Object.assign(e,t.opts()),{})}error(e,t){this._outputConfiguration.outputError(`${e}
18
+ `,this._outputConfiguration.writeErr),typeof this._showHelpAfterError=="string"?this._outputConfiguration.writeErr(`${this._showHelpAfterError}
19
+ `):this._showHelpAfterError&&(this._outputConfiguration.writeErr(`
20
+ `),this.outputHelp({error:!0}));let r=t||{},n=r.exitCode||1,i=r.code||"commander.error";this._exit(n,i,e)}_parseOptionsEnv(){this.options.forEach(e=>{if(e.envVar&&e.envVar in j.env){let t=e.attributeName();(this.getOptionValue(t)===void 0||["default","config","env"].includes(this.getOptionValueSource(t)))&&(e.required||e.optional?this.emit(`optionEnv:${e.name()}`,j.env[e.envVar]):this.emit(`optionEnv:${e.name()}`))}})}_parseOptionsImplied(){let e=new Hr(this.options),t=r=>this.getOptionValue(r)!==void 0&&!["default","implied"].includes(this.getOptionValueSource(r));this.options.filter(r=>r.implied!==void 0&&t(r.attributeName())&&e.valueFromOption(this.getOptionValue(r.attributeName()),r)).forEach(r=>{Object.keys(r.implied).filter(n=>!t(n)).forEach(n=>{this.setOptionValueWithSource(n,r.implied[n],"implied")})})}missingArgument(e){let t=`error: missing required argument '${e}'`;this.error(t,{code:"commander.missingArgument"})}optionMissingArgument(e){let t=`error: option '${e.flags}' argument missing`;this.error(t,{code:"commander.optionMissingArgument"})}missingMandatoryOptionValue(e){let t=`error: required option '${e.flags}' not specified`;this.error(t,{code:"commander.missingMandatoryOptionValue"})}_conflictingOption(e,t){let r=o=>{let a=o.attributeName(),c=this.getOptionValue(a),l=this.options.find(d=>d.negate&&a===d.attributeName()),u=this.options.find(d=>!d.negate&&a===d.attributeName());return l&&(l.presetArg===void 0&&c===!1||l.presetArg!==void 0&&c===l.presetArg)?l:u||o},n=o=>{let a=r(o),c=a.attributeName();return this.getOptionValueSource(c)==="env"?`environment variable '${a.envVar}'`:`option '${a.flags}'`},i=`error: ${n(e)} cannot be used with ${n(t)}`;this.error(i,{code:"commander.conflictingOption"})}unknownOption(e){if(this._allowUnknownOption)return;let t="";if(e.startsWith("--")&&this._showSuggestionAfterError){let n=[],i=this;do{let o=i.createHelp().visibleOptions(i).filter(a=>a.long).map(a=>a.long);n=n.concat(o),i=i.parent}while(i&&!i._enablePositionalOptions);t=Dt(e,n)}let r=`error: unknown option '${e}'${t}`;this.error(r,{code:"commander.unknownOption"})}_excessArguments(e){if(this._allowExcessArguments)return;let t=this.registeredArguments.length,r=t===1?"":"s",i=`error: too many arguments${this.parent?` for '${this.name()}'`:""}. Expected ${t} argument${r} but got ${e.length}.`;this.error(i,{code:"commander.excessArguments"})}unknownCommand(){let e=this.args[0],t="";if(this._showSuggestionAfterError){let n=[];this.createHelp().visibleCommands(this).forEach(i=>{n.push(i.name()),i.alias()&&n.push(i.alias())}),t=Dt(e,n)}let r=`error: unknown command '${e}'${t}`;this.error(r,{code:"commander.unknownCommand"})}version(e,t,r){if(e===void 0)return this._version;this._version=e,t=t||"-V, --version",r=r||"output the version number";let n=this.createOption(t,r);return this._versionOptionName=n.attributeName(),this._registerOption(n),this.on("option:"+n.name(),()=>{this._outputConfiguration.writeOut(`${e}
21
+ `),this._exit(0,"commander.version",e)}),this}description(e,t){return e===void 0&&t===void 0?this._description:(this._description=e,t&&(this._argsDescription=t),this)}summary(e){return e===void 0?this._summary:(this._summary=e,this)}alias(e){if(e===void 0)return this._aliases[0];let t=this;if(this.commands.length!==0&&this.commands[this.commands.length-1]._executableHandler&&(t=this.commands[this.commands.length-1]),e===t._name)throw new Error("Command alias can't be the same as its name");let r=this.parent?._findCommand(e);if(r){let n=[r.name()].concat(r.aliases()).join("|");throw new Error(`cannot add alias '${e}' to command '${this.name()}' as already have command '${n}'`)}return t._aliases.push(e),this}aliases(e){return e===void 0?this._aliases:(e.forEach(t=>this.alias(t)),this)}usage(e){if(e===void 0){if(this._usage)return this._usage;let t=this.registeredArguments.map(r=>Vr(r));return[].concat(this.options.length||this._helpOption!==null?"[options]":[],this.commands.length?"[command]":[],this.registeredArguments.length?t:[]).join(" ")}return this._usage=e,this}name(e){return e===void 0?this._name:(this._name=e,this)}nameFromFilename(e){return this._name=ee.basename(e,ee.extname(e)),this}executableDir(e){return e===void 0?this._executableDir:(this._executableDir=e,this)}helpInformation(e){let t=this.createHelp();return t.helpWidth===void 0&&(t.helpWidth=e&&e.error?this._outputConfiguration.getErrHelpWidth():this._outputConfiguration.getOutHelpWidth()),t.formatHelp(this,t)}_getHelpContext(e){e=e||{};let t={error:!!e.error},r;return t.error?r=n=>this._outputConfiguration.writeErr(n):r=n=>this._outputConfiguration.writeOut(n),t.write=e.write||r,t.command=this,t}outputHelp(e){let t;typeof e=="function"&&(t=e,e=void 0);let r=this._getHelpContext(e);this._getCommandAndAncestors().reverse().forEach(i=>i.emit("beforeAllHelp",r)),this.emit("beforeHelp",r);let n=this.helpInformation(r);if(t&&(n=t(n),typeof n!="string"&&!Buffer.isBuffer(n)))throw new Error("outputHelp callback must return a string or a Buffer");r.write(n),this._getHelpOption()?.long&&this.emit(this._getHelpOption().long),this.emit("afterHelp",r),this._getCommandAndAncestors().forEach(i=>i.emit("afterAllHelp",r))}helpOption(e,t){return typeof e=="boolean"?(e?this._helpOption=this._helpOption??void 0:this._helpOption=null,this):(e=e??"-h, --help",t=t??"display help for command",this._helpOption=this.createOption(e,t),this)}_getHelpOption(){return this._helpOption===void 0&&this.helpOption(void 0,void 0),this._helpOption}addHelpOption(e){return this._helpOption=e,this}help(e){this.outputHelp(e);let t=j.exitCode||0;t===0&&e&&typeof e!="function"&&e.error&&(t=1),this._exit(t,"commander.help","(outputHelp)")}addHelpText(e,t){let r=["beforeAll","before","after","afterAll"];if(!r.includes(e))throw new Error(`Unexpected value for position to addHelpText.
22
+ Expecting one of '${r.join("', '")}'`);let n=`${e}Help`;return this.on(n,i=>{let o;typeof t=="function"?o=t({error:i.error,command:i.command}):o=t,o&&i.write(`${o}
23
+ `)}),this}_outputHelpIfRequested(e){let t=this._getHelpOption();t&&e.find(n=>t.is(n))&&(this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)"))}};function Ft(s){return s.map(e=>{if(!e.startsWith("--inspect"))return e;let t,r="127.0.0.1",n="9229",i;return(i=e.match(/^(--inspect(-brk)?)$/))!==null?t=i[1]:(i=e.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null?(t=i[1],/^\d+$/.test(i[3])?n=i[3]:r=i[3]):(i=e.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null&&(t=i[1],r=i[3],n=i[4]),t&&n!=="0"?`${t}=${r}:${parseInt(n)+1}`:e})}Nt.Command=ct});var Vt=Z(W=>{var{Argument:Rt}=je(),{Command:lt}=Lt(),{CommanderError:qr,InvalidArgumentError:It}=we(),{Help:Br}=et(),{Option:Tt}=st();W.program=new lt;W.createCommand=s=>new lt(s);W.createOption=(s,e)=>new Tt(s,e);W.createArgument=(s,e)=>new Rt(s,e);W.Command=lt;W.Option=Tt;W.Argument=Rt;W.Help=Br;W.CommanderError=qr;W.InvalidArgumentError=It;W.InvalidOptionArgumentError=It});var qt=Z((is,Mr)=>{Mr.exports={name:"dotenv",version:"16.6.1",description:"Loads environment variables from .env file",main:"lib/main.js",types:"lib/main.d.ts",exports:{".":{types:"./lib/main.d.ts",require:"./lib/main.js",default:"./lib/main.js"},"./config":"./config.js","./config.js":"./config.js","./lib/env-options":"./lib/env-options.js","./lib/env-options.js":"./lib/env-options.js","./lib/cli-options":"./lib/cli-options.js","./lib/cli-options.js":"./lib/cli-options.js","./package.json":"./package.json"},scripts:{"dts-check":"tsc --project tests/types/tsconfig.json",lint:"standard",pretest:"npm run lint && npm run dts-check",test:"tap run --allow-empty-coverage --disable-coverage --timeout=60000","test:coverage":"tap run --show-full-coverage --timeout=60000 --coverage-report=text --coverage-report=lcov",prerelease:"npm test",release:"standard-version"},repository:{type:"git",url:"git://github.com/motdotla/dotenv.git"},homepage:"https://github.com/motdotla/dotenv#readme",funding:"https://dotenvx.com",keywords:["dotenv","env",".env","environment","variables","config","settings"],readmeFilename:"README.md",license:"BSD-2-Clause",devDependencies:{"@types/node":"^18.11.3",decache:"^4.6.2",sinon:"^14.0.1",standard:"^17.0.0","standard-version":"^9.5.0",tap:"^19.2.0",typescript:"^4.8.4"},engines:{node:">=12"},browser:{fs:!1}}});var Jt=Z((os,te)=>{var ut=require("fs"),ke=require("path"),Wr=require("os"),Gr=require("crypto"),Jr=qt(),dt=Jr.version,Kr=/(?:^|^)\s*(?:export\s+)?([\w.-]+)(?:\s*=\s*?|:\s+?)(\s*'(?:\\'|[^'])*'|\s*"(?:\\"|[^"])*"|\s*`(?:\\`|[^`])*`|[^#\r\n]+)?\s*(?:#.*)?(?:$|$)/mg;function Yr(s){let e={},t=s.toString();t=t.replace(/\r\n?/mg,`
24
+ `);let r;for(;(r=Kr.exec(t))!=null;){let n=r[1],i=r[2]||"";i=i.trim();let o=i[0];i=i.replace(/^(['"`])([\s\S]*)\1$/mg,"$2"),o==='"'&&(i=i.replace(/\\n/g,`
25
+ `),i=i.replace(/\\r/g,"\r")),e[n]=i}return e}function zr(s){s=s||{};let e=Gt(s);s.path=e;let t=F.configDotenv(s);if(!t.parsed){let o=new Error(`MISSING_DATA: Cannot parse ${e} for an unknown reason`);throw o.code="MISSING_DATA",o}let r=Wt(s).split(","),n=r.length,i;for(let o=0;o<n;o++)try{let a=r[o].trim(),c=Xr(t,a);i=F.decrypt(c.ciphertext,c.key);break}catch(a){if(o+1>=n)throw a}return F.parse(i)}function Qr(s){console.log(`[dotenv@${dt}][WARN] ${s}`)}function _e(s){console.log(`[dotenv@${dt}][DEBUG] ${s}`)}function Mt(s){console.log(`[dotenv@${dt}] ${s}`)}function Wt(s){return s&&s.DOTENV_KEY&&s.DOTENV_KEY.length>0?s.DOTENV_KEY:process.env.DOTENV_KEY&&process.env.DOTENV_KEY.length>0?process.env.DOTENV_KEY:""}function Xr(s,e){let t;try{t=new URL(e)}catch(a){if(a.code==="ERR_INVALID_URL"){let c=new Error("INVALID_DOTENV_KEY: Wrong format. Must be in valid uri format like dotenv://:key_1234@dotenvx.com/vault/.env.vault?environment=development");throw c.code="INVALID_DOTENV_KEY",c}throw a}let r=t.password;if(!r){let a=new Error("INVALID_DOTENV_KEY: Missing key part");throw a.code="INVALID_DOTENV_KEY",a}let n=t.searchParams.get("environment");if(!n){let a=new Error("INVALID_DOTENV_KEY: Missing environment part");throw a.code="INVALID_DOTENV_KEY",a}let i=`DOTENV_VAULT_${n.toUpperCase()}`,o=s.parsed[i];if(!o){let a=new Error(`NOT_FOUND_DOTENV_ENVIRONMENT: Cannot locate environment ${i} in your .env.vault file.`);throw a.code="NOT_FOUND_DOTENV_ENVIRONMENT",a}return{ciphertext:o,key:r}}function Gt(s){let e=null;if(s&&s.path&&s.path.length>0)if(Array.isArray(s.path))for(let t of s.path)ut.existsSync(t)&&(e=t.endsWith(".vault")?t:`${t}.vault`);else e=s.path.endsWith(".vault")?s.path:`${s.path}.vault`;else e=ke.resolve(process.cwd(),".env.vault");return ut.existsSync(e)?e:null}function Bt(s){return s[0]==="~"?ke.join(Wr.homedir(),s.slice(1)):s}function Zr(s){let e=!!(s&&s.debug),t=s&&"quiet"in s?s.quiet:!0;(e||!t)&&Mt("Loading env from encrypted .env.vault");let r=F._parseVault(s),n=process.env;return s&&s.processEnv!=null&&(n=s.processEnv),F.populate(n,r,s),{parsed:r}}function en(s){let e=ke.resolve(process.cwd(),".env"),t="utf8",r=!!(s&&s.debug),n=s&&"quiet"in s?s.quiet:!0;s&&s.encoding?t=s.encoding:r&&_e("No encoding is specified. UTF-8 is used by default");let i=[e];if(s&&s.path)if(!Array.isArray(s.path))i=[Bt(s.path)];else{i=[];for(let l of s.path)i.push(Bt(l))}let o,a={};for(let l of i)try{let u=F.parse(ut.readFileSync(l,{encoding:t}));F.populate(a,u,s)}catch(u){r&&_e(`Failed to load ${l} ${u.message}`),o=u}let c=process.env;if(s&&s.processEnv!=null&&(c=s.processEnv),F.populate(c,a,s),r||!n){let l=Object.keys(a).length,u=[];for(let d of i)try{let h=ke.relative(process.cwd(),d);u.push(h)}catch(h){r&&_e(`Failed to load ${d} ${h.message}`),o=h}Mt(`injecting env (${l}) from ${u.join(",")}`)}return o?{parsed:a,error:o}:{parsed:a}}function tn(s){if(Wt(s).length===0)return F.configDotenv(s);let e=Gt(s);return e?F._configVault(s):(Qr(`You set DOTENV_KEY but you are missing a .env.vault file at ${e}. Did you forget to build it?`),F.configDotenv(s))}function rn(s,e){let t=Buffer.from(e.slice(-64),"hex"),r=Buffer.from(s,"base64"),n=r.subarray(0,12),i=r.subarray(-16);r=r.subarray(12,-16);try{let o=Gr.createDecipheriv("aes-256-gcm",t,n);return o.setAuthTag(i),`${o.update(r)}${o.final()}`}catch(o){let a=o instanceof RangeError,c=o.message==="Invalid key length",l=o.message==="Unsupported state or unable to authenticate data";if(a||c){let u=new Error("INVALID_DOTENV_KEY: It must be 64 characters long (or more)");throw u.code="INVALID_DOTENV_KEY",u}else if(l){let u=new Error("DECRYPTION_FAILED: Please check your DOTENV_KEY");throw u.code="DECRYPTION_FAILED",u}else throw o}}function nn(s,e,t={}){let r=!!(t&&t.debug),n=!!(t&&t.override);if(typeof e!="object"){let i=new Error("OBJECT_REQUIRED: Please check the processEnv argument being passed to populate");throw i.code="OBJECT_REQUIRED",i}for(let i of Object.keys(e))Object.prototype.hasOwnProperty.call(s,i)?(n===!0&&(s[i]=e[i]),r&&_e(n===!0?`"${i}" is already defined and WAS overwritten`:`"${i}" is already defined and was NOT overwritten`)):s[i]=e[i]}var F={configDotenv:en,_configVault:Zr,_parseVault:zr,config:tn,decrypt:rn,parse:Yr,populate:nn};te.exports.configDotenv=F.configDotenv;te.exports._configVault=F._configVault;te.exports._parseVault=F._parseVault;te.exports.config=F.config;te.exports.decrypt=F.decrypt;te.exports.parse=F.parse;te.exports.populate=F.populate;te.exports=F});var zt={};$r(zt,{baseDir:()=>Pe,configPath:()=>ht,ensureDir:()=>me,fileExists:()=>Fe,getProjectDir:()=>ne,loadConfig:()=>re,readJson:()=>q,removeProjectCache:()=>De,removeProjectData:()=>ft,saveConfig:()=>be,writeJson:()=>le});async function me(s){await pe.default.mkdir(s,{recursive:!0})}async function q(s,e){try{let t=await pe.default.readFile(s,"utf8");return JSON.parse(t)}catch(t){if(t&&t.code==="ENOENT")return e;throw t}}async function le(s,e){let t=fe.default.dirname(s);await me(t);let r=JSON.stringify(e,null,2);await pe.default.writeFile(s,r,"utf8")}async function re(){return await me(Pe),await q(ht,{projects:{}})}async function be(s){await le(ht,s)}function ne(s){return fe.default.join(Pe,"projects",s)}async function ft(s){let e=ne(s);await pe.default.rm(e,{recursive:!0,force:!0})}async function De(s){let e=ne(s),t=fe.default.join(e,"cache.json");await pe.default.rm(t,{force:!0})}async function Fe(s){try{return await pe.default.access(s),!0}catch{return!1}}var pe,Yt,fe,Pe,ht,ge=Ar(()=>{pe=I(require("node:fs/promises"),1),Yt=I(require("node:os"),1),fe=I(require("node:path"),1),Pe=process.env.AGENQA_CLI_HOME?fe.default.resolve(process.env.AGENQA_CLI_HOME):fe.default.join(Yt.default.homedir(),".agenqa-cli"),ht=fe.default.join(Pe,"config.json")});var wr=I(require("node:path"),1);var Ut=I(Vt(),1),{program:Kn,createCommand:Yn,createArgument:zn,createOption:Qn,CommanderError:Xn,InvalidArgumentError:Zn,InvalidOptionArgumentError:es,Command:Ht,Argument:ts,Option:rs,Help:ns}=Ut.default;var Is=I(Jt(),1);var Kt=I(require("node:readline/promises"),1),Se=require("node:process");async function he(s,{required:e=!1}={}){let t=Kt.default.createInterface({input:Se.stdin,output:Se.stdout});try{for(;;){let r=(await t.question(`${s} `)).trim().toLowerCase();if(!r&&!e)return null;if(["y","yes"].includes(r))return!0;if(["n","no"].includes(r))return!1;Se.stdout.write(`Please answer yes or no.
26
+ `)}}finally{t.close()}}ge();var gt=I(require("node:fs/promises"),1),er=require("node:fs"),J=I(require("node:path"),1),tr=I(require("node:crypto"),1);var sn="https://www.agenqa.com/api",on=/\/api(\/|$)/;function pt(s){if(!s)return"";let e=s.replace(/\/+$/,"");return e?on.test(e)?e:/^https?:\/\/[^/]+$/.test(e)?`${e}/api`:e:""}function Ce(s,e){let t=s.projects?.[e],r=process.env.AGENQA_API_BASE_URL||sn||"";return pt(t?.baseUrl||s.baseUrl||r||"")}function Ne(s,e){let t={"X-Cloud-Key-Token":s.keyToken};return e&&(t["X-Cloud-Project-Id"]=e),t}function mt(s,e){let t=new Error(`Request failed with status code ${s.status}`);return t.status=s.status,t.body=e,t.contentType=s.headers.get("content-type")||"",t}async function Ee(s,e={}){let t=await fetch(s,{...e,headers:{Accept:"application/json",...e.headers||{}}});if(!t.ok){let r=await t.text();throw mt(t,r)}return await t.json()}async function Qt(s,e={}){let t=await fetch(s,e);if(!t.ok){let i=await t.text();throw mt(t,i)}let r=Buffer.from(await t.arrayBuffer()),n=Object.fromEntries(t.headers.entries());return{buffer:r,headers:n}}async function Le(s,{formData:e,headers:t={},signal:r}={}){let n={Accept:"application/json",...t},i=await fetch(s,{method:"POST",headers:n,body:e,signal:r});if(!i.ok){let a=await i.text();throw mt(i,a)}return await i.json()}function Xt(s){return s&&(s.status===401||s.status===403)}ge();async function an(s){let e=tr.default.createHash("sha256");return new Promise((t,r)=>{let n=(0,er.createReadStream)(s);n.on("data",i=>e.update(i)),n.on("error",r),n.on("end",()=>t(e.digest("hex")))})}function Zt(s){return!s||typeof s!="object"?null:s.id||s.cloudId||s.cloud_id||null}async function Re(s,e,t={}){let r=s.projects?.[e];if(!r)throw new Error(`Project ${e} is not imported. Run "agenqa import" first.`);let n=Ce(s,e);if(!n)throw new Error("API base URL is not configured. Set AGENQA_API_BASE_URL.");let i=Ne(r,e),o=ne(e);await me(o);let a=await Ee(`${n}/cloud/cli/projects/${e}`,{headers:i}),c={id:a.project?.id,name:a.project?.name,version:a.project?.version,ownerId:a.project?.owner_id,readOnly:a.project?.read_only||!1,synced_at:new Date().toISOString()},l=a.project?.structure_json||{},u=!!l?.disableCacheGlobally;await le(J.default.join(o,"project.json"),c),await le(J.default.join(o,"structure.json"),l);let d=await cn({baseUrl:n,projectId:e,headers:i,projectDir:o,serverFiles:rr(a.project?.structure_json)}),h=a.project?.cache_version||null,p={downloaded:0,skipped:0,total:0,version:h,updated:!1},g=t?.cacheOverride??null,m=u||g===!1?!1:typeof r.cacheCloudEnabled=="boolean"?r.cacheCloudEnabled:!!r.cacheEnabled,w=u||g===!1?!1:typeof r.cacheLocalEnabled=="boolean"?r.cacheLocalEnabled:!!r.cacheEnabled;if(m&&w){let y=J.default.join(o,"cache.json"),A=(await q(y,{entries:[],version:null})).version||null;!h&&A?(await le(y,{version:null,entries:{}}),p={downloaded:0,skipped:0,total:0,version:null,updated:!0}):!!h&&h!==A?p=await ln({baseUrl:n,projectId:e,headers:i,projectDir:o}):p={downloaded:0,skipped:0,total:0,version:A,updated:!1}}return{project:c,files:d,cache:p,cacheDisabledGlobally:u}}function rr(s){let e=new Map,t=(r,n=null)=>{if(Array.isArray(r))for(let i of r)!i?.id||e.has(i.id)||e.set(i.id,{...i,mime_type:i.mime_type??i.type,size_bytes:i.size_bytes??i.size,test_case_id:n||i?.test_case_id||i?.testCaseId||null})};return Array.isArray(s?.documents)&&s.documents.forEach(r=>t(r?.files||[],Zt(r))),Array.isArray(s?.testFolders)&&s.testFolders.forEach(r=>{Array.isArray(r?.documents)&&r.documents.forEach(n=>t(n?.files,Zt(n)))}),Array.from(e.values())}async function cn({baseUrl:s,projectId:e,headers:t,projectDir:r,serverFiles:n}){let i=J.default.join(r,"files");await me(i);let o=J.default.join(r,"files.json"),c=(await q(o,{files:{}})).files||{},l=Array.isArray(n)?n:[];if(!l.length){let m=await Ee(`${s}/cloud/cli/projects/${e}`,{headers:t});l=rr(m.project?.structure_json)}let u={files:{}},d=new Set,h=0,p=0,g=0;for(let m of l){d.add(m.id);let w=m?.test_case_id||m?.testCaseId||m?.test_id||m?.testId||null;if(!w)throw new Error(`Missing test case ID for file ${m?.name||m?.id||"unknown"}`);let y=typeof m.name=="string"&&m.name.trim().length>0?m.name:null;if(!y)throw new Error(`Missing file name for file ${m?.id||"unknown"}`);let C=String(w),A=J.default.join("files",C,y),f=J.default.join(r,"files",C);await me(f),u.files[m.id]={name:m.name,mime_type:m.mime_type,size_bytes:m.size_bytes,content_hash:m.content_hash,created_at:m.created_at,test_case_id:w||null,path:A};let b=J.default.join(r,A),E=await Fe(b),k=E?await an(b):null;if(!E||!k||m.content_hash!==k)try{let V=await Ee(`${s}/cloud/cli/projects/${e}/files/${m.id}/presign-download`,{headers:t});if(!V?.download_url){console.warn(`Warning: missing download URL for file ${m.name||m.id}. Skipping.`),p++;continue}let D=await Qt(V.download_url,{headers:V.headers||{}});await gt.default.writeFile(b,D.buffer),h++}catch(V){if(V?.status===404){console.warn(`Warning: cloud file not found (${m.name||m.id}). Skipping.`),p++;continue}throw V}else p++}for(let[m]of Object.entries(c))if(!d.has(m)){let w=c[m]||{};if(!w.path){console.warn(`Warning: missing stored path for file ${m}, skipping removal.`);continue}let y=J.default.join(r,w.path);await Fe(y)&&await gt.default.unlink(y),g++}return await le(o,u),{downloaded:h,skipped:p,removed:g,total:l.length}}async function ln({baseUrl:s,projectId:e,headers:t,projectDir:r}){let n=J.default.join(r,"cache.json"),o=(await q(n,{entries:[]})).version||null,a=await Ee(`${s}/cloud/cli/projects/${e}/cache`,{headers:t}),c=Array.isArray(a.entries)?a.entries:[],l=un(c);if(l&&o&&l===o)return{downloaded:0,skipped:c.length,total:c.length,version:l,updated:!1};let u={version:l,entries:[]},d=0,h=0;for(let p of c)!p?.key||typeof p.value>"u"||(u.entries.push({key:p.key,value:p.value,meta:p.meta||{},createdAt:Date.now(),expiresAt:null}),d++);return await le(n,u),{downloaded:d,skipped:h,total:c.length,version:l,updated:!0}}function un(s){if(!Array.isArray(s)||s.length===0)return null;let e=null;for(let t of s){let r=t?.updated_at;if(!r)continue;let n=Date.parse(r);Number.isNaN(n)||(!e||n>e)&&(e=n)}return e?new Date(e).toISOString():null}var Et=I(require("node:path"),1);var dn={info:"INFO",success:"SUCCESS",warning:"WARN",error:"ERROR"},Ie=class{constructor(e={}){this.logs=[],this.silent=!!e.silent}addLog(e,t,r,n=null,i=null){let o={testId:e,level:t,message:r,details:n,extra:i,timestamp:new Date().toISOString()};if(this.logs.push(o),!this.silent||t==="error"){let a=dn[t]||t?.toUpperCase?.()||"LOG",c=e?`[${a}] [${e}]`:`[${a}]`;console.log(`${c} ${r}`),n&&console.log(n)}}convertScreenshotToDataUrl(){return null}getLogs(){return this.logs}};var yt=I(require("node:vm"),1),Te=I(require("node:path"),1),xe=require("node:url"),sr=require("playwright"),ir=require("playwright/test"),x=null,ve=new Map,or=new Set,Ve="EXECUTION_STOPPED";function hn(s,e,t,r){if(!x)return!0;switch(e){case"never":return!1;case"testFolder":return x.projectId!==r||x.testFolderId!==t;case"test":default:return x.sessionTestId!==s}}async function ie(){if(x){try{x.browser&&await x.browser.close()}catch{}x=null}}async function Ue(){if(!x||!x.context)return null;try{let s=await x.context.storageState(),e={cookies:s.cookies||[],localStorage:{},sessionStorage:{}};return s.origins&&s.origins.forEach(t=>{t.localStorage&&t.localStorage.length>0&&(e.localStorage[t.origin]={},t.localStorage.forEach(r=>{e.localStorage[t.origin][r.name]=r.value})),t.sessionStorage&&t.sessionStorage.length>0&&(e.sessionStorage[t.origin]={},t.sessionStorage.forEach(r=>{e.sessionStorage[t.origin][r.name]=r.value}))}),e}catch{return null}}async function ar(s,e){try{let t={cookies:[],origins:[]},r=null;try{r=await Ue()}catch{if(x?.browserState)try{r=JSON.parse(JSON.stringify(x.browserState))}catch{r=x.browserState}else r=null}let n=null;if(s)try{n=JSON.parse(JSON.stringify(s))}catch{n=null}let i=[];r?.cookies?.length&&i.push(...r.cookies),n?.cookies?.length&&n.cookies.forEach(a=>{if(a?.name&&a?.value&&a?.domain){let c=i.findIndex(l=>l.name===a.name&&l.domain===a.domain&&(l.path||"/")===(a.path||"/"));c>=0&&i.splice(c,1),i.push(a)}}),t.cookies=i.filter(a=>a?.name&&a?.value&&a?.domain).map(a=>{let c=a.domain.includes(":")?a.domain.split(":")[0]:a.domain,l={name:a.name,value:String(a.value),domain:c,path:a.path||"/"};if(a.expires){let u=new Date(a.expires);Number.isNaN(u.getTime())||(l.expires=Math.floor(u.getTime()/1e3))}else typeof a.expires=="number"&&(l.expires=a.expires);return typeof a.httpOnly=="boolean"&&(l.httpOnly=a.httpOnly),typeof a.secure=="boolean"&&(l.secure=a.secure),a.sameSite&&(l.sameSite=a.sameSite),l});let o={};if(r?.localStorage)for(let[a,c]of Object.entries(r.localStorage))o[a]||(o[a]={localStorage:{},sessionStorage:{}}),Object.assign(o[a].localStorage,c);if(r?.sessionStorage)for(let[a,c]of Object.entries(r.sessionStorage))o[a]||(o[a]={localStorage:{},sessionStorage:{}}),Object.assign(o[a].sessionStorage,c);if(n?.localStorage)for(let[a,c]of Object.entries(n.localStorage)){let l=a==="default"?e?new xe.URL(e).origin:null:a;l&&(o[l]||(o[l]={localStorage:{},sessionStorage:{}}),Object.assign(o[l].localStorage,c))}if(n?.sessionStorage)for(let[a,c]of Object.entries(n.sessionStorage)){let l=a==="default"?e?new xe.URL(e).origin:null:a;l&&(o[l]||(o[l]={localStorage:{},sessionStorage:{}}),Object.assign(o[l].sessionStorage,c))}for(let[a,c]of Object.entries(o)){let l={origin:a};l.localStorage=Object.entries(c.localStorage||{}).map(([u,d])=>({name:u,value:String(d)})),l.sessionStorage=Object.entries(c.sessionStorage||{}).map(([u,d])=>({name:u,value:String(d)})),(l.localStorage.length>0||l.sessionStorage.length>0)&&t.origins.push(l)}return t.cookies.length>0||t.origins.length>0?t:null}catch{return null}}async function fn(s,e,t){if(!s||!e)return;let r=t||s.url||null;if(!r){let n=Object.keys(e.localStorage||{})[0]||Object.keys(e.sessionStorage||{})[0]||null;if(n)r=n;else if(e.cookies?.length){let i=e.cookies[0];if(i.domain){let o=i.secure?"https":"http",a=i.domain.startsWith(".")?i.domain.substring(1):i.domain;r=`${o}://${a}`}}}try{let n=await ar(e,r);if(!n){s.browserState=JSON.parse(JSON.stringify(e));return}if(n.cookies?.length&&s.context){let i=n.cookies.map(o=>({name:o.name,value:String(o.value),domain:o.domain,path:o.path||"/",expires:typeof o.expires=="number"?o.expires:void 0,httpOnly:typeof o.httpOnly=="boolean"?o.httpOnly:void 0,secure:typeof o.secure=="boolean"?o.secure:void 0,sameSite:o.sameSite||void 0}));try{await s.context.addCookies(i)}catch{}}if(n.origins?.length&&s.page)try{await s.page.addInitScript(({origins:i})=>{try{let o=window.location.origin,a=i.find(c=>c.origin===o);if(!a)return;Array.isArray(a.localStorage)&&a.localStorage.forEach(({name:c,value:l})=>{try{window.localStorage.setItem(c,l)}catch{}}),Array.isArray(a.sessionStorage)&&a.sessionStorage.forEach(({name:c,value:l})=>{try{window.sessionStorage.setItem(c,l)}catch{}})}catch{}},{origins:n.origins})}catch{}try{let i=await Ue();s.browserState=i||JSON.parse(JSON.stringify(e))}catch{s.browserState=e}}catch{s.browserState=e}}async function pn(s,e,t){if(!s||!e)return;let r=(()=>{try{return t?new xe.URL(t).origin:new xe.URL(s.url()).origin}catch{return null}})(),n=(a={})=>{let c=[];for(let[l,u]of Object.entries(a)){let d=l==="default"&&r?r:l;if(!(!d||r&&d!==r))for(let[h,p]of Object.entries(u||{}))c.push({key:h,value:String(p)})}return c},i=n(e.localStorage),o=n(e.sessionStorage);try{await s.evaluate(({localEntries:a,sessionEntries:c})=>{try{Array.isArray(a)&&a.forEach(({key:l,value:u})=>{try{window.localStorage.setItem(l,u)}catch{}}),Array.isArray(c)&&c.forEach(({key:l,value:u})=>{try{window.sessionStorage.setItem(l,u)}catch{}})}catch{}},{localEntries:i,sessionEntries:o})}catch{}if(Array.isArray(e.cookies)&&e.cookies.length>0)try{await s.evaluate(a=>{try{a.forEach(c=>{if(c&&c.name&&c.value){let l=[`${c.name}=${c.value}`];c.path&&l.push(`path=${c.path}`),c.domain&&!c.domain.startsWith(".")&&l.push(`domain=${c.domain}`),c.secure&&l.push("Secure"),c.sameSite&&l.push(`SameSite=${c.sameSite}`),document.cookie=l.join("; ")}})}catch{}},e.cookies)}catch{}}function mn(s){let e=new Set;for(let t of s)typeof t=="string"?e.add(Te.default.resolve(t)):t&&typeof t=="object"&&t.path&&e.add(Te.default.resolve(t.path));return function(r){if(!r||typeof r!="string")return!1;let n=Te.default.resolve(r);return e.has(n)}}function gn(s,e){let t=mn(e);return new Proxy(s,{get(r,n){let i=r[n];return n==="constructor"?i:n==="locator"&&typeof i=="function"?function(...o){let a=i.apply(r,o),c=a.setInputFiles;return c&&(a.setInputFiles=function(l){if(Array.isArray(l)){let u=l.map(d=>{if(!t(d))throw new Error(`Access denied: File not in allowed test files: ${d}`);return d});return c.call(this,u)}if(typeof l=="string"){if(!t(l))throw new Error(`Access denied: File not in allowed test files: ${l}`);return c.call(this,l)}return c.call(this,l)}),a}:typeof i=="function"?i.bind(r):i}})}function yn(s){s&&or.add(s)}function T(s){return!!s&&or.has(s)}function se(s){let e=new Error("Test execution stopped by user");return e.code=Ve,e.testId=s,e}function cr(s){if(!s)return null;let e=null,t=100;return{promise:new Promise((i,o)=>{let a=()=>{T(s)&&(e&&clearInterval(e),ie().catch(()=>{}),o(se(s)))};a(),e=setInterval(a,t)}),cancel:()=>{e&&(clearInterval(e),e=null)}}}async function wn(s){yn(s);let e=ve.get(s),t=!1;if(e){if(e.vmContext)try{e.vmContext=null}catch{}e.abortController&&e.abortController.abort(),await ie(),t=!0}if(x&&(!s||x.sessionTestId===s))try{await ie(),t=!0}catch{}return ve.delete(s),t||T(s)}function nr(s){return typeof s=="string"&&s.length>0&&s!=="about:blank"&&!s.startsWith("data:")}async function _n(s){let e=()=>nr(s.url());if(e())return s.url();try{await s.waitForLoadState("domcontentloaded",{timeout:1e4})}catch{}if(e())return s.url();try{await s.waitForURL(t=>nr(t),{timeout:1e4})}catch{}if(e())return s.url();try{await s.waitForLoadState("load",{timeout:5e3})}catch{}return s.url()}function Sn(s){if(!s||!s.message)return!1;let e=s.message.toLowerCase(),t=(s.name||"").toLowerCase(),r=(s.constructor?.name||"").toLowerCase();return e.includes("strict mode violation")?!1:e.includes("expect(")||e.includes("expected")&&e.includes("received")||e.includes("assertion")||t==="assertionerror"||r==="assertionerror"||t==="expectationerror"||r==="expectationerror"||t==="testerror"||r==="testerror"||e.includes("tobevisible")||e.includes("tobehidden")||e.includes("tobeenabled")||e.includes("tobedisabled")||e.includes("tobechecked")||e.includes("tobeattached")||e.includes("tobedetached")||e.includes("tobeempty")||e.includes("tobefocused")||e.includes("tohavetext")||e.includes("tohavevalue")||e.includes("tohaveattribute")||e.includes("tohaveclass")||e.includes("tohavecount")||e.includes("tohaveurl")||e.includes("tohavetitle")||e.includes("tocontain")||e.includes("toequal")||e.includes("tomatch")||e.includes("tobetruthy")||e.includes("tobefalsy")||e.includes("tobenan")||e.includes("tobenull")||e.includes("tobeundefined")||e.includes("timed out")&&(e.includes("waiting for expect(")||e.includes("ms waiting for expect(")||e.includes("call log:")&&e.includes("expect("))||e.includes("unexpected value")||e.includes("assertion failed")||e.includes("expectation failed")||e.includes("test failed")||e.includes("element not found")&&e.includes("expected")||e.includes("selector")&&e.includes("not found")&&e.includes("expected")}function wt(s,e=null){let t=s||"the requested page",r=new Error(`It is impossible to reach ${t}. Please verify your internet connection or confirm the site allows automated browsing.`);return e&&(r.cause=e),r}async function lr(s,e,t=null){if(T(t))throw se(t);try{await s.goto(e,{waitUntil:"networkidle",timeout:3e4})}catch(r){if(T(t))throw se(t);try{let n=await s.evaluate(()=>document.readyState);if(n==="complete"||n==="interactive")return}catch{throw wt(e,r)}throw wt(e,r)}if(T(t))throw se(t)}async function He(s,e,t=null,r=3,n="test",i=null,o=null){if(T(s))throw se(s);let a=hn(s,n,i,o);if(!x||a){await ie();let c=null;for(let l=1;l<=r;l++){if(T(s))throw se(s);try{let u=await sr.chromium.launch(),d={viewport:{width:1920,height:1080},ignoreHTTPSErrors:!0};if(t){let g=await ar(t,e);g&&(d.storageState=g)}let h=await u.newContext(d);if(t?.sessionStorage&&Object.keys(t.sessionStorage).length>0){let g=`
27
+ (function() {
28
+ const currentOrigin = window.location.origin;
29
+ const sessionStorageData = ${JSON.stringify(t.sessionStorage)};
30
+ if (sessionStorageData[currentOrigin]) {
31
+ Object.entries(sessionStorageData[currentOrigin]).forEach(([key, value]) => {
32
+ try { sessionStorage.setItem(key, String(value)); } catch {}
33
+ });
34
+ }
35
+ })();
36
+ `;await h.addInitScript(g)}let p=await h.newPage();if(e)try{let g=cr(s);try{let m=p.goto(e);g?await Promise.race([m,g.promise]):await m}finally{g?.cancel()}}catch(g){throw wt(e,g)}x={sessionTestId:s,testFolderId:i,projectId:o,resetStateOption:n,browser:u,context:h,page:p,url:e,browserState:t};try{let g=await Ue();g&&(x.browserState=g)}catch{}break}catch(u){if(c=u,await ie(),T(s))throw se(s);if(l===r)throw new Error(`Failed to initialize browser session after ${r} attempts: ${c.message}`);let d=Math.min(1e3*Math.pow(2,l-1),5e3);await new Promise(h=>setTimeout(h,d))}}}if(t&&x&&!a&&await fn(x,t,e||x.url||null),x&&e&&(x.url=e),T(s))throw se(s);return x}async function bn(s,e,t,r=null,n=3e5,i=!1,o=[],a="test",c=null,l=null,u=!1){let d=new AbortController,h=null;ve.set(s,{vmContext:null,abortController:d});try{let p=await He(s,e,r,3,a,c,l),{page:g}=p;await _n(g);let w={page:gn(g,o),expect:ir.expect,files:o};h=yt.default.createContext(w),ve.set(s,{vmContext:h,abortController:d});try{let y=await yt.default.runInContext(`(async () => { ${t} })();`,h,{timeout:n}),C=null;if(i&&x?.page)try{C=await x.page.screenshot({type:"jpeg",fullPage:!0})}catch{}return{success:!0,message:"Test executed successfully",result:y,finalScreenshot:C}}catch(y){let C=T(s),A=Sn(y),f=C||A,b=!!u&&A&&!C,E=null;return C?(await ie(),{success:!1,error:y.message,errorType:"stopped",stack:y.stack,isExpectFailure:!1,shouldStopTest:!0,tracePath:E,cancelled:!0}):f?(b||await ie(),{success:!1,error:y.message,errorType:"assertion",stack:y.stack,isExpectFailure:!0,shouldStopTest:!0,tracePath:E}):{success:!1,error:y.message,errorType:"execution",stack:y.stack,isExpectFailure:!1,shouldStopTest:!1}}}catch(p){let g=T(s)||p.code===Ve;return await ie(),{success:!1,error:p.message,errorType:g?"stopped":"browser",stack:p.stack,isExpectFailure:!1,shouldStopTest:!0,tracePath:null,cancelled:g}}finally{ve.delete(s)}}async function ur(s,e=null,t=null,r="test",n=null,i=null){if(T(s))return{success:!1,cancelled:!0,error:"Test execution stopped by user"};try{let o;if(e){o=await He(s,e,t,3,r,n,i);let{page:u}=o;await lr(u,e,s)}else{if(!x||x.sessionTestId!==s)return{success:!1,error:"No active session found for this test. Provide a URL to create a new session."};o=x}let{page:a}=o,c=await a.content(),l=await a.screenshot({type:"jpeg",fullPage:!0});return{success:!0,html:c,screenshot:l}}catch(o){return o.code===Ve?{success:!1,cancelled:!0,error:o.message}:{success:!1,error:o.message}}}async function dr(s,e,t=null,r="test",n=null,i=null){if(T(s))return{success:!1,cancelled:!0,error:"Test execution stopped by user",url:e};try{let o=await He(s,e,t,3,r,n,i),{page:a}=o,c=cr(s);try{let l=lr(a,e,s);c?await Promise.race([l,c.promise]):await l}finally{c?.cancel()}if(t){if(T(s))throw se(s);await pn(a,t,e)}return{success:!0,message:`Successfully navigated to ${e}`,url:a.url()}}catch(o){return o.code===Ve?{success:!1,cancelled:!0,error:o.message,url:e}:{success:!1,error:o.message,url:e}}}async function Cn(s,e,t=null,r="test",n=null,i=null){return dr(s,e,t,r,n,i)}async function En(s){return await ur(s)}function vn(){return x}async function xn(s,e,t=null,r=3,n="test",i=null,o=null){return await He(s,e,t,r,n,i,o)}var B={cleanupSession:ie,forceStopTestExecution:wn,executePlaywrightCode:bn,getPageState:ur,navigateToUrl:dr,navigateToUrlWithState:Cn,getCurrentState:En,captureCurrentBrowserState:Ue,getCurrentSession:vn,getOrCreateContinuousRecordingSession:xn};function An(s,e,t,r,n){if(!s)return!0;switch(t){case"never":return!1;case"testFolder":return n!==r;case"test":default:return s!==e}}var _t=class{constructor(){this.currentPlaywrightSession=null,this.lastTestFolderId=null,this.currentExecutionGroupId=null,this.executionGroupStartTime=null}startExecutionGroup(){let e=Date.now();return this.currentExecutionGroupId=`group-${e}-${Math.random().toString(36).substring(2,9)}`,this.executionGroupStartTime=e,this.currentExecutionGroupId}generateSessionId(e,t,r){let n=e.projectId||"unknown-project",i=e.testFolderId||"unknown-folder",o=e.id||e.testId||"unknown-test";if(t==="never")return`session-project-${n}-${r}`;if(t==="testFolder")return`session-folder-${i}-${r}`;let a=Date.now().toString()+Math.random().toString(36).substring(2,9);return`session-test-${o}-${a}`}shouldResetSession(e,t){return!this.currentPlaywrightSession||this.currentPlaywrightSession===e.sessionId?!1:An(this.currentPlaywrightSession,e.sessionId,t,e.testFolderId,this.lastTestFolderId)}updateSessionTracking(e,t){this.currentPlaywrightSession=e,this.lastTestFolderId=t}resetSessionTracking(){this.currentPlaywrightSession=null}async cleanupSession(){try{return await B.cleanupSession(),this.resetSessionTracking(),{success:!0}}catch(e){return{success:!1,error:e.message}}}},Y=new _t;var z=new Map,Be=!1,St=null,hr=null,qe=null,$n=null,On=500;function jn(s){return Array.isArray(s)?s:[]}function kn(s,e){return e&&e.expiresAt&&e.expiresAt<=Date.now()?(z.delete(s),!0):!1}function fr(s={},e=!1,t={}){if(Be=!!e,St=t.cachePath||null,hr=t.cacheVersion||null,z=new Map,!Be)return;jn(s).forEach(n=>{!n?.key||typeof n.value>"u"||n.expiresAt&&n.expiresAt<=Date.now()||z.set(n.key,{key:n.key,value:n.value,meta:n.meta||{},createdAt:n.createdAt||Date.now(),expiresAt:n.expiresAt||null})})}async function Me(s){if(!Be||!s)return null;let e=z.get(s);return!e||kn(s,e)?null:e.value}function We(s,e,t={},r={}){if(!Be||!s)return;let n=typeof r.ttl=="number"?r.ttl:$n,i=typeof n=="number"&&n>0?Date.now()+n:null;z.set(s,{key:s,value:e,meta:t,createdAt:Date.now(),expiresAt:i}),bt()}function pr(s=null,e=null){let t=0;for(let[r,n]of z.entries()){let i=n?.meta||{},o=s?i.projectId===s:!1,a=e?i.testId===e:!1;(o||a)&&(z.delete(r),t++)}return t>0&&bt(),t}function mr(s){if(!s)return 0;let e=0;for(let[t,r]of z.entries())(r?.meta||{}).sessionId===s&&(z.delete(t),e++);return e>0&&bt(),e}function bt(){St&&(qe&&clearTimeout(qe),qe=setTimeout(()=>{qe=null;let s=Array.from(z.values()),e={version:hr,entries:s};Promise.resolve().then(()=>(ge(),zt)).then(({writeJson:t})=>t(St,e)).catch(()=>{})},On))}var Ge=class{constructor(e,t){this.logger=e,this.apiConfig=t,this.retryErrorContext=null}async executeTestSteps(e,t,r,n={}){let i=n?.enableCache!==!1,o={cacheEnabled:i,usedCache:!1},a=1,c="",l=!1,u=t.html,d=t.screenshot,h=0,p=3,g=0,m=[5,30,60],w=[5e3,15e3],y=0;for(;!l||h>0;){let A=(new Date-e.startedAt)/1e3;if(A>e.testTimeout){let f=new Error(`Test execution timeout: exceeded ${e.testTimeout} seconds (${A.toFixed(1)}s elapsed)`);if(this.isRetryableError(f.message)&&h<p){h++,this.logger.addLog(e.id,"warning",`Test timeout (attempt ${h}/${p}): ${f.message}`),this.retryErrorContext=`Test timeout (attempt ${h}): ${f.message}`;let b=await this._capturePageState(e.sessionId,e.id);b&&(u=b.html,d=b.screenshot);continue}throw f.shouldRetryWithoutCache=o.usedCache,f.cacheUsed=o.usedCache,f}if(a>e.maxSteps){let f=new Error(`Test reached maximum steps limit (${e.maxSteps}) without completing.`);throw f.isLogged=!0,f.shouldRetryWithoutCache=o.usedCache,f.cacheUsed=o.usedCache,this.logger.addLog(e.id,"error",f.message),f}try{let f=await this._executeStep(e,a,u,d,c,r,o);if(g=0,f.forceFailure){let b=f.forceFailureReason||f.description;if(f.fromCache&&y<w.length){let k=w[y];y++,this.logger.addLog(e.id,"warning",`Cache retry ${y}/2 after failure - waiting ${Math.round(k/1e3)}s before retrying step ${a} from cache`),await this._sleep(k);let v=await this._capturePageState(e.sessionId,e.id);v&&(u=v.html,d=v.screenshot),h=0;continue}this._logStepDetails(e.id,a,f.description,d,f.userExperienceRate,f.userExperienceAdvices,f.fromCache),this.logger.addLog(e.id,"error",`Step ${a} - Test failed: ${b}`);let E=new Error(`Test failed due to unresolvable issue at step ${a}: ${b}`);throw E.isLogged=!0,E.shouldRetryWithoutCache=o.usedCache,E.cacheUsed=o.usedCache,E}if(l=f.isFinalStep,f.playwrightCode){let b=!!f.fromCache&&y<w.length,E=await this._executePlaywrightCode(e,a,f,r,b),k=E.cancelled?"cancelled":E.success?"success":"failed";if(E.cancelled)return{success:!1,reason:"stopped",finalScreenshot:E.finalScreenshot||d};if(E.success){l&&E.finalScreenshot&&(d=E.finalScreenshot),!f.fromCache&&f.cacheKey&&f.cacheMeta&&We(f.cacheKey,{playwrightCode:f.playwrightCode,description:f.description,isFinalStep:f.isFinalStep,forceFailure:f.forceFailure,forceFailureReason:f.forceFailureReason,userExperienceRate:f.userExperienceRate,userExperienceAdvices:f.userExperienceAdvices},f.cacheMeta);let v=null;l||(v=await this._capturePageState(e.sessionId,e.id),v&&(u=v.html,d=v.screenshot)),this._logStepDetails(e.id,a,f.description,d,f.userExperienceRate,f.userExperienceAdvices,f.fromCache),this.logger.addLog(e.id,"success",`Step ${a} executed successfully`),c+=`Step ${a}: ${f.description}
37
+ `,l?h=0:(a++,h=0,y=0)}else{let{shouldRetry:v,error:V}=await this._handleExecutionFailure(e,a,E,h,p,c,f.description,i,o);if(v){h++;let D=await this._capturePageState(e.sessionId,e.id);D&&(u=D.html,d=D.screenshot);continue}if(f.fromCache&&y<w.length){let D=w[y];y++,this.logger.addLog(e.id,"warning",`Cache retry ${y}/2 after failure - waiting ${Math.round(D/1e3)}s before retrying step ${a} from cache`),await this._sleep(D);let S=await this._capturePageState(e.sessionId,e.id);S&&(u=S.html,d=S.screenshot),h=0;continue}throw V}}else if(this._logStepDetails(e.id,a,f.description,d,f.userExperienceRate,f.userExperienceAdvices,f.fromCache),c+=`Step ${a}: ${f.description}
38
+ `,l||(a++,y=0),h=0,!l)continue}catch(f){if(this._isNetworkError(f)){if(g<m.length){let b=m[g],E=g+1;g++;let k=f.message||"Unknown network error";this.logger.addLog(e.id,"warning",`Network error during step ${a} (attempt ${E})`,`Retrying in ${b}s: ${k}`),await this._sleep(b*1e3);continue}this.logger.addLog(e.id,"error",`Network error persisted after ${m.length} retries`,f.message||"Unknown network error")}throw f.isLogged||(this.logger.addLog(e.id,"error","Test execution error",f.message),f.isLogged=!0),f.shouldRetryWithoutCache=o.usedCache,f.cacheUsed=o.usedCache,f}}return{success:!0,stepNumber:a-1,finalScreenshot:d}}async _executeStep(e,t,r,n,i,o,a){let c=i;this.retryErrorContext&&(c+=(c?`
39
+ `:"")+this.retryErrorContext,this.retryErrorContext=null);let l=a?.cacheEnabled?await this._buildStepCacheKey(e,t,r,n,c,o):null;if(l){let p=await Me(l);if(p)return a.usedCache=!0,{playwrightCode:p.playwrightCode,description:p.description,isFinalStep:p.isFinalStep,forceFailure:p.forceFailure,forceFailureReason:p.forceFailureReason,userExperienceRate:p.userExperienceRate,userExperienceAdvices:p.userExperienceAdvices,fromCache:!0,cacheKey:l,cacheMeta:{projectId:e.projectId,testId:e.testId||e.sourceTestId||e.id,sessionId:e.sessionId,timing:"step",level:"test",actionId:null,testFolderId:e.testFolderId||null}}}let u=new FormData;u.append("test_name",e.testName||"Untitled Test"),u.append("test_description",e.testDescription||""),u.append("html_code",r||"");let d=new Blob([n],{type:"image/jpeg"});u.append("screenshot",d,"screenshot.jpeg"),c&&u.append("previous_steps",c),Array.isArray(e.files)&&e.files.length>0&&e.files.forEach((p,g)=>{u.append(`files[${g}][name]`,p.name||""),u.append(`files[${g}][description]`,p.description||"")});let h=await Le(this.apiConfig.runTestUrl,{formData:u,headers:this.apiConfig.headers});return{playwrightCode:h.playwright_code,description:h.description,isFinalStep:h.is_final_step,forceFailure:h.force_failure,forceFailureReason:h.force_failure_reason,userExperienceRate:h.user_experience_rate,userExperienceAdvices:h.user_experience_advices,fromCache:!1,cacheKey:l,cacheMeta:{projectId:e.projectId,testId:e.testId||e.sourceTestId||e.id,sessionId:e.sessionId,timing:"step",level:"test",actionId:null,testFolderId:e.testFolderId||null}}}async _executePlaywrightCode(e,t,r,n,i=!1){try{let o=await this._prepareTestFiles(e);return await B.executePlaywrightCode(e.sessionId,e.url,r.playwrightCode,null,e.actionTimeout*1e3,r.isFinalStep,o,n,e.testFolderId,e.projectId,i)}catch(o){throw o.isLogged||(this.logger.addLog(e.id,"error",`Step ${t} execution error`,o.message),o.isLogged=!0),o}}async _prepareTestFiles(e){let t=[];if(Array.isArray(e.files))for(let r=0;r<e.files.length;r++){let n=e.files[r];n?.path&&n?.name?t[r]={name:n.name,description:n.description||"",path:n.path}:t[r]=null}return t}async _handleExecutionFailure(e,t,r,n,i,o,a,c,l){let u=`Step ${t} failed`,d=r.error;if(r.isExpectFailure){u=typeof a=="string"&&a.trim().length>0?`Step ${t} failed - ${a.trim()}`:`Step ${t} assertion failed`,this.logger.addLog(e.id,"error",u,d);let m=new Error(`${u}: ${d}`);return m.isLogged=!0,m.shouldRetryWithoutCache=l?.usedCache||!1,m.cacheUsed=l?.usedCache||!1,{shouldRetry:!1,error:m}}if(this.isRetryableError(r.error)&&n<i)return this.logger.addLog(e.id,"warning",`Step ${t} failed (attempt ${n+1}/${i}): ${r.error}`,d),this.retryErrorContext=`Step ${t} (attempt ${n+1}): Failed with error: ${r.error}`,{shouldRetry:!0};r.errorType==="execution"?u=`Step ${t} code execution failed`:r.errorType==="browser"&&(u=`Step ${t} browser error`),this.logger.addLog(e.id,"error",u,d);let p=new Error(`${u}: ${d}`);return p.isLogged=!0,p.shouldRetryWithoutCache=l?.usedCache||!1,p.cacheUsed=l?.usedCache||!1,{shouldRetry:!1,error:p}}_logStepDetails(e,t,r,n,i,o,a=!1){let c=r||"No description provided",l=a?" (cache)":"",u={};typeof i<"u"&&(u.user_experience_rate=i),typeof o<"u"&&(u.user_experience_advices=o),a&&(u.from_cache=!0),this.logger.addLog(e,"info",`Step ${t}${l}: ${c}`,null,u)}async _buildStepCacheKey(e,t,r,n,i,o){let a="v1",c=e.testId||e.sourceTestId||e.id||"unknown-test",l=e.projectId||"unknown-project",u=await this._hashString(i||""),d=this._buildFilesSignature(e.files),h=e.testFolderId||"",p=JSON.stringify({cacheVersion:a,projectId:l,sourceTestId:c,url:e.url||"",resetStateOption:o||"",maxSteps:e.maxSteps,actionTimeout:e.actionTimeout,environment:e.environment||"",role:e.role||"",previousStepsHash:u,filesSignature:d,testFolderId:h,stepNumber:t}),g=await this._hashString(p);return`step:${a}:${l}:${c}:${t}:${g}`}_buildFilesSignature(e){if(!Array.isArray(e)||e.length===0)return"no-files";let t=e.map(r=>({name:r?.name||"",description:r?.description||"",id:r?.id||""}));return this._simpleHash(JSON.stringify(t))}async _hashString(e){if(typeof e!="string")return"no-string";try{if(typeof crypto<"u"&&crypto.subtle?.digest){let r=new TextEncoder().encode(e),n=await crypto.subtle.digest("SHA-256",r);return Array.from(new Uint8Array(n)).map(i=>i.toString(16).padStart(2,"0")).join("")}}catch{}return this._simpleHash(e)}_simpleHash(e){let t=0,r=String(e);for(let n=0;n<r.length;n++)t=(t<<5)-t+r.charCodeAt(n),t|=0;return Math.abs(t).toString(16)}async _capturePageState(e,t){try{let r=await B.getCurrentState(e);if(r&&r.success)return{html:r.html,screenshot:r.screenshot}}catch(r){this.logger.addLog(t,"warning","Failed to capture page state",r.message)}return null}_sleep(e){return new Promise(t=>setTimeout(t,e))}_isNetworkError(e){if(!e||e.code==="ERR_CANCELED")return!1;if(e.isAxiosError&&!e.response)return!0;let t=typeof e.message=="string"?e.message.toLowerCase():"",r=typeof e.code=="string"?e.code.toLowerCase():"",n=["network error","net::err_","failed to fetch","getaddrinfo","socket hang up","econnreset","econnrefused","timed out","etimedout","ehostunreach","enotfound","network is unreachable"];return!!(n.some(i=>t.includes(i))||r&&n.some(i=>r.includes(i)))}isRetryableError(e){if(!e||typeof e!="string")return!1;let t=e.toLowerCase();return t.includes("strict mode violation")?!0:!(t.includes("assertion failed")||t.includes("expect(")&&!t.includes("timed out")||t.includes("expected")&&t.includes("received")&&!t.includes("timed out")||t.includes("assertionerror")||t.includes("expectation failed"))}};var Je=class{constructor(e,t,r=()=>!1,n=()=>{}){this.logger=e,this.apiConfig=t,this.retryErrorContext=null,this.isStopRequested=r,this.executedProjectBeforeActions=new Map,this.recordActionCode=typeof n=="function"?n:()=>{}}async executeActions(e,t,r,n,i="test",o=null,a=null,c={}){let l=c?.enableCache!==!1,u=r.filter(m=>n==="before"&&!m.executeAfter||n==="after"&&m.executeAfter);if(this.isStopRequested())return this.logger.addLog(t,"warning",`${n} actions cancelled by user request`),{success:!1,message:`${n} actions cancelled by user`,cancelled:!0,usedCache:!1};if(u.length===0)return this.logger.addLog(t,"info",`No ${n} actions to execute`),{success:!0,message:`No ${n} actions to execute`,usedCache:!1};this.logger.addLog(t,"info",`Executing ${u.length} ${n} action(s) in inheritance order (Project->Test Folder->Test)`);let d=0,h=0,p=!1;for(let m=0;m<u.length;m++){if(this.isStopRequested())return this.logger.addLog(t,"warning",`Cancelled remaining ${n} actions after user stop request`),{success:!1,message:`${n} actions cancelled by user`,cancelled:!0,usedCache:p};let w=u[m];if(this._shouldSkipProjectBeforeAction(e,w,n,i)){this.logger.addLog(t,"info",`Skipping project-level ${n} action "${w.name}" for persistent session`);continue}try{let y=this._resolveActionUrl(w);this.logger.addLog(t,"info",`[${m+1}/${u.length}] Executing ${n} action: "${w.name}" (${w.level} level) - URL: ${y}`);let C=this._resolveActionStorage(w),A=(C?.cookies?.length||0)>0||Object.keys(C?.localStorage||{}).length>0||Object.keys(C?.sessionStorage||{}).length>0,f=null;if(A?f=await this._navigateWithBrowserState(e,w,y,t,i,o,a):f=await B.navigateToUrl(e,y,null,i,o,a),f?.cancelled)return this.logger.addLog(t,"warning",`${n} action "${w.name}" cancelled during navigation`),{success:!1,cancelled:!0,usedCache:p};if(f&&f.success===!1){let k=this._formatDetails(f.error,"Navigation failed");this.logger.addLog(t,"warning",`\u2717 ${n} action "${w.name}" navigation failed`,k),h++;continue}if(this.isStopRequested())return this.logger.addLog(t,"warning",`Cancelled ${n} action "${w.name}" due to user stop request`),{success:!1,message:`${n} actions cancelled by user`,cancelled:!0,usedCache:p};let b=typeof w.description=="string"?w.description.trim():"";if(!b){this._recordProjectBeforeActionSuccess(e,w,n,i);let v=!!w.storageOnly?`\u2713 ${n} action "${w.name}" storage configuration applied (no AI instructions)`:`\u2713 ${n} action "${w.name}" navigation completed (no description to execute)`;this.logger.addLog(t,"success",v),d++;continue}let E=await this._executeActionWithAI(e,{...w,description:b},y,t,n,i,o,a,m+1,{enableCache:l,testId:c?.testId,projectId:c?.projectId});if(E?.cacheUsed&&(p=!0),!E||E.cancelled)return{success:!1,cancelled:!0,usedCache:p};E.success?(d++,this._recordProjectBeforeActionSuccess(e,w,n,i)):h++}catch(y){let C=this._formatDetails(y);this.logger.addLog(t,"warning",`\u2717 ${n} action "${w.name}" failed with unexpected error`,C),h++}}let g=h===0;return{success:g,message:g?`${n} actions completed`:`${n} actions failed`,usedCache:p}}async _navigateWithBrowserState(e,t,r,n,i,o,a){let c=this._resolveActionStorage(t);this.logger.addLog(n,"info",`Action "${t.name}" includes browser state: ${t.cookies?.length||0} cookies, ${Object.keys(t.localStorage||{}).length} localStorage items, ${Object.keys(t.sessionStorage||{}).length} sessionStorage items`);let l=JSON.parse(JSON.stringify(c));return await B.navigateToUrlWithState(e,r,l,i,o,a)}async _executeActionWithAI(e,t,r,n,i,o,a,c,l=1,u={}){let d=u?.enableCache!==!1,h=!1,p=u?.testId||n,g=u?.projectId||c;if(this.isStopRequested())return this.logger.addLog(n,"warning",`${i} action "${t.name}" cancelled before execution`),{success:!1,cancelled:!0};let m=typeof t.actionTimeout=="number"?t.actionTimeout*1e3:6e4,w=typeof t.maxSteps=="number"?t.maxSteps:10,y=await B.getCurrentState(e);if(!y||!y.success){let D=this._formatDetails(y?.error);return this.logger.addLog(n,"warning",`\u2717 ${i} action "${t.name}" failed to capture page state: ${D}`,D),{success:!1}}let C=1,A="",f=!1,b=0,E=3,k=[5e3,15e3],v=0;for(;(!f||b>0)&&C<=w;){if(this.isStopRequested())return this.logger.addLog(n,"warning",`${i} action "${t.name}" cancelled by user`),{success:!1,cancelled:!0};try{let D=(t.description||"").trim(),S=A;this.retryErrorContext&&(S+=(S?`
40
+ `:"")+this.retryErrorContext,this.retryErrorContext=null);let $=d?await this._buildActionCacheKey({action:t,timing:i,stepNumber:C,pageStateResult:y,previousStepsContext:S,resetStateOption:o,projectId:g,testId:p,sessionId:e,actionTimeoutMs:m,maxSteps:w,testFolderId:a}):null,N,O,G,U,Q,M,_,H=!1;if($){let P=await Me($);P&&(h=!0,H=!0,{playwrightCode:N,description:O,isFinalStep:G,forceFailure:U,forceFailureReason:Q,userExperienceRate:M,userExperienceAdvices:_}=P)}if(!H){let P=new FormData;P.append("test_name",`${i} action: ${t.name}`),P.append("test_description",D),P.append("html_code",y.html);let L=new Blob([y.screenshot],{type:"image/jpeg"});P.append("screenshot",L,"screenshot.jpeg"),S&&P.append("previous_steps",S),{playwright_code:N,description:O,is_final_step:G,forceFailure:U,forceFailureReason:Q,user_experience_rate:M,user_experience_advices:_}=await Le(this.apiConfig.runTestUrl,{formData:P,headers:this.apiConfig.headers})}if(U){let P=Q||O;if(H&&v<k.length&&!this.isStopRequested()){let L=k[v];v++,this.logger.addLog(n,"warning",`Cache retry ${v}/2 after failure - waiting ${Math.round(L/1e3)}s before retrying ${i} action "${t.name}" step ${C} from cache`),await new Promise(ce=>setTimeout(ce,L));let ae=await this._capturePageState(e,n);ae&&(y=ae),b=0;continue}return this._logActionDetails(n,t.name,O,y.screenshot,M,_,H),this.logger.addLog(n,"warning",`\u2717 ${i} action "${t.name}" failed: ${P}`,P),{success:!1,cacheUsed:h}}if(f=!!G,N){if(this.isStopRequested())return this.logger.addLog(n,"warning",`${i} action "${t.name}" cancelled before executing Playwright code`),{success:!1,cancelled:!0,cacheUsed:h};let P=H&&v<k.length&&!this.isStopRequested(),L=await B.executePlaywrightCode(e,r,N,null,m,f,[],o,a,c,P),ae=L.cancelled?"cancelled":L.success?"success":"failed";if(this.recordActionCode({executionId:n,timing:i,actionName:t.name,actionLevel:t.level,actionOrder:l,stepNumber:C,attempt:b+1,description:O,code:N,status:ae}),L.cancelled)return{success:!1,cancelled:!0};if(L.success){let R=await this._capturePageState(e,n);if(R&&(y=R),!H&&$&&We($,{playwrightCode:N,description:O,isFinalStep:G,forceFailure:U,forceFailureReason:Q,userExperienceRate:M,userExperienceAdvices:_},{projectId:g,testId:p,sessionId:e,timing:i,level:t.level,actionId:t.id||null,testFolderId:a||null}),H&&(h=!0),this._logActionDetails(n,t.name,O,y.screenshot,M,_,H),A+=`Step ${C}: ${O}
41
+ `,!f){C++,b=0,v=0;continue}return this.logger.addLog(n,"success",`\u2713 ${i} action "${t.name}" executed successfully`),{success:!0,cacheUsed:h}}let ce=!!L.isExpectFailure,X=!ce&&this.isRetryableError(L.error),de=this._formatDetails(L.error);if(X&&b<E){b++,this.logger.addLog(n,"warning",`${i} action "${t.name}" step ${C} failed (attempt ${b}/${E}): ${L.error}`,de),this.retryErrorContext=`Step ${C} (attempt ${b}): Failed with error: ${L.error}`;let R=await this._capturePageState(e,n);R&&(y=R);continue}if(H&&v<k.length&&!this.isStopRequested()){let R=k[v];v++,this.logger.addLog(n,"warning",`Cache retry ${v}/2 after failure - waiting ${Math.round(R/1e3)}s before retrying ${i} action "${t.name}" step ${C} from cache`),await new Promise(Sr=>setTimeout(Sr,R));let $t=await this._capturePageState(e,n);$t&&(y=$t),b=0;continue}let ye=ce?"assertion failed":"execution failed";return this.logger.addLog(n,"warning",`\u2717 ${i} action "${t.name}" step ${C} ${ye}: ${L.error}`,de),{success:!1,cacheUsed:h}}let oe=await this._capturePageState(e,n);if(oe&&(y=oe),this._logActionDetails(n,t.name,O,y.screenshot,M,_,H),A+=`Step ${C}: ${O}
42
+ `,!f){C++,b=0,v=0;continue}return this.logger.addLog(n,"success",`\u2713 ${i} action "${t.name}" completed`),{success:!0,cacheUsed:h}}catch(D){let S=this._formatDetails(D);return this.logger.addLog(n,"warning",`\u2717 ${i} action "${t.name}" API failed: ${D.message}`,S),{success:!1,cacheUsed:h}}}let V=`Maximum of ${w} steps reached without completing action "${t.name}"`;return this.logger.addLog(n,"warning",`\u2717 ${i} action "${t.name}" reached maximum steps limit (${w}) without completing`,V),{success:!1,cacheUsed:h}}async _capturePageState(e,t){try{let r=await B.getCurrentState(e);if(r&&r.success)return r}catch(r){let n=this._formatDetails(r);this.logger.addLog(t,"warning","Failed to capture page state for action logging",n)}return null}_logActionDetails(e,t,r,n,i,o,a=!1){let c=a?" (cache)":"",l={};typeof i<"u"&&(l.user_experience_rate=i),typeof o<"u"&&(l.user_experience_advices=o),a&&(l.from_cache=!0),this.logger.addLog(e,"info",`${t}${c}: ${r||"No description provided"}`,null,l)}_formatDetails(e,t="Unknown error"){if(e instanceof Error)return e.stack||e.message||t;if(typeof e=="string")return e||t;if(e==null)return t;if(typeof e=="object")try{return JSON.stringify(e,null,2)}catch{return String(e)}return String(e)}async _buildActionCacheKey({action:e,timing:t,stepNumber:r,pageStateResult:n,previousStepsContext:i,resetStateOption:o,projectId:a,testId:c,sessionId:l,actionTimeoutMs:u,maxSteps:d,testFolderId:h}){let p="v1",g=await this._hashString(i||""),m=JSON.stringify({cacheVersion:p,actionId:e.id||"",actionName:e.name||"",actionUrl:e.url||"",actionLevel:e.level||"",timing:t,stepNumber:r,resetStateOption:o,actionTimeoutMs:u,maxSteps:d,projectId:a||"unknown-project",testId:c||"unknown-test",description:(e.description||"").trim(),storageOnly:!!e.storageOnly,testFolderId:h||e.testFolderId||"",cookies:e.cookies||[],localStorage:e.localStorage||{},sessionStorage:e.sessionStorage||{},previousStepsHash:g}),w=await this._hashString(m);return`action:${p}:${a||"project"}:${c||"test"}:${t}:${e.id||e.name||"unnamed"}:${w}`}async _hashString(e){if(typeof e!="string")return"no-string";try{if(typeof crypto<"u"&&crypto.subtle?.digest){let r=new TextEncoder().encode(e),n=await crypto.subtle.digest("SHA-256",r);return Array.from(new Uint8Array(n)).map(i=>i.toString(16).padStart(2,"0")).join("")}}catch{}return this._simpleHash(e)}_simpleHash(e){let t=0,r=String(e);for(let n=0;n<r.length;n++)t=(t<<5)-t+r.charCodeAt(n),t|=0;return Math.abs(t).toString(16)}_shouldSkipProjectBeforeAction(e,t,r,n){if(!e||r!=="before"||t.level!=="project"||!t.id||n==="test")return!1;let i=this.executedProjectBeforeActions.get(e);return i?i.has(t.id):!1}_recordProjectBeforeActionSuccess(e,t,r,n){!e||r!=="before"||t.level!=="project"||!t.id||n!=="test"&&(this.executedProjectBeforeActions.has(e)||this.executedProjectBeforeActions.set(e,new Set),this.executedProjectBeforeActions.get(e).add(t.id))}_resolveActionUrl(e){let t=typeof e?.cloudReplaceUrl=="string"?e.cloudReplaceUrl.trim():"";return e?.cloudUseLocalUrl===!1&&t?t:typeof e?.url=="string"?e.url.trim():""}_resolveActionStorage(e){return e?.cloudUseLocalStorage===!1&&e.cloudStorage?e.cloudStorage:{cookies:e.cookies||[],localStorage:e.localStorage||{},sessionStorage:e.sessionStorage||{}}}isRetryableError(e){if(!e||typeof e!="string")return!1;let t=e.toLowerCase();return t.includes("strict mode violation")?!0:!(t.includes("assertion failed")||t.includes("expect(")&&!t.includes("timed out")||t.includes("expected")&&t.includes("received")&&!t.includes("timed out")||t.includes("assertionerror")||t.includes("expectation failed"))}};ge();var Ae=I(require("node:path"),1);ge();async function gr(s){let e=await q(Ae.default.join(s,"structure.json"),{}),t=await q(Ae.default.join(s,"project.json"),{}),r=await q(Ae.default.join(s,"files.json"),{files:{}}),n=await q(Ae.default.join(s,"cache.json"),{entries:[]});return{structure:e,projectMeta:t,filesIndex:r,cacheData:n}}function ue(s){return typeof s!="string"?"":s.trim()}function Pn(s,e){let t=ue(s),r=ue(e);if(!r)return t;let n=t.replace(/\/+$/,""),i=r.replace(/^\/+/,"");return n?`${n}/${i}`:`/${i}`}function Dn(s,e,t){let r=ue(s?.replaceUrl);if(r)return r;let n=ue(s?.url);if(n)return n;let i=ue(t?.replaceUrl);return i||Pn(e?.baseUrl||"",t?.path||"")}function Fn(s,e,t){let r=ue(s?.cloudReplaceUrl);if(s?.cloudUseLocalUrl===!1&&r)return r;let n=ue(t?.cloudReplaceUrl);if(t?.cloudUseLocalUrl===!1&&n)return n;let i=ue(e?.cloudReplaceUrl);return e?.cloudUseLocalUrl===!1&&i?i:Dn(s,e,t)}function Ct(s=[],e){return s.map(t=>({...t,level:e}))}function Nn(s,e,t){let r=[];return Array.isArray(s.actions)&&r.push(...Ct(s.actions,"project")),e&&Array.isArray(e.actions)&&r.push(...Ct(e.actions,"testFolder")),Array.isArray(t.actions)&&r.push(...Ct(t.actions,"test")),r}function Ln(s,e,t){return Array.isArray(s.files)?s.files.map(r=>{if(!r?.id)return null;let n=e.files?.[r.id];if(!n?.path)throw new Error(`Missing stored file path for ${r.name||r.id}`);let i=Et.default.join(t,n.path);return{id:r.id,name:r.name||n?.name||"",description:r.description||"",path:i}}).filter(Boolean):[]}function Rn(s){let e=[],t=Array.isArray(s.documents)?s.documents:[];for(let n of t)e.push({...n,testFolder:null});let r=Array.isArray(s.testFolders)?s.testFolders:[];for(let n of r){let i=Array.isArray(n.documents)?n.documents:[];for(let o of i)e.push({...o,testFolder:n})}return e}function In(s,e,t){let r=Rn(s);return e==="project"?r:e==="folder"?r.filter(n=>n.testFolder?.cloudId===t):e==="test"?r.filter(n=>n.cloudId===t):[]}async function yr({projectId:s,targetType:e,targetId:t,apiConfig:r,cacheEnabled:n,silent:i=!1}){let o=new Ie({silent:i}),a=ne(s),{structure:c,filesIndex:l,cacheData:u}=await gr(a),d=c||{},h=d.id||s,p=In(c,e,t);if(!p.length)throw new Error("No tests found for the selected target.");let g=Et.default.join(a,"cache.json");fr(u.entries||{},n,{cachePath:g,cacheVersion:u.version||null});let m=new Je(o,r),w=new Ge(o,r),y=Y.startExecutionGroup(),C=d?.queueFailureBehavior==="continueQueue"?"continueQueue":"stopQueue",A=[],f=new Map,b=0,E=0;for(let S of p){let $=S.testFolder,N=S.resetStateOption||d?.resetStateForEachTest||"test";if(!(S.executeOnCloud!==!1)){E++,o.addLog(S.cloudId||S.id||"unknown-test","info",`Skipping "${S.name||"Untitled Test"}" (set to run in app only).`);continue}let G=Y.generateSessionId({...S,projectId:h,testFolderId:$?.id||null},N,y),U=S.id||S.testId||S.cloudId,Q=S.name||"Untitled Test",M=Fn(S,d,$);if(!Q.trim()||!S.description?.trim()||!M||!M.trim()){b++,o.addLog(U||"unknown-test","warning","Skipping test missing required name, description, or URL.");continue}A.push({testEntry:S,testFolder:$,resetStateOption:N,sessionId:G,testId:U,testName:Q,testUrl:M}),f.set(G,(f.get(G)||0)+1)}if(!A.length)throw new Error("No valid tests found for the selected target.");b>0&&o.addLog("system","warning",`Skipping ${b} test(s) without required name, description, or URL.`),E>0&&o.addLog("system","info",`Skipping ${E} test(s) marked for app-only execution.`);let k=0,v=0,V=S=>{if(!S)return;let $=f.get(S);if(!$)return;let N=$-1;N<=0?f.delete(S):f.set(S,N)},D=async(S,$,N=!1)=>{let O=$||S.resetStateOption||"test";if(O!=="never"){if(O==="testFolder"){if(N){await Y.cleanupSession();return}if((f.get(S.sessionId)||0)>1)return}await Y.cleanupSession()}};try{for(let S of A){let{testEntry:$,testFolder:N,resetStateOption:O,sessionId:G,testId:U,testName:Q,testUrl:M}=S,_={id:U,testId:U,sessionId:G,testName:Q,testDescription:$.description||"",projectId:h,testFolderId:N?.id||null,testFolderName:N?.name||null,url:M,actionTimeout:$.actionTimeout||60,testTimeout:$.testTimeout||300,maxSteps:$.maxSteps||50,actions:Array.isArray($.actions)?[...$.actions]:[],files:Ln($,l,a),environment:$.environment||"",role:$.role||"",resetStateOption:O,startedAt:new Date};o.addLog(_.id,"info",`Started executing test "${_.testName}"`);let H=Nn(d,N,_);try{let oe=0,P=!1,L=4,ae=!1,ce=!1;for(;oe<L;){Y.shouldResetSession(_,O)&&await Y.cleanupSession(),Y.updateSessionTracking(_.sessionId,_.testFolderId);try{let X=await m.executeActions(_.sessionId,_.id,H,"before",O,_.testFolderId,_.projectId,{enableCache:!P,projectId:h,testId:U});if(!X?.success){let R=new Error(`Before actions failed: ${X?.message||"Unknown error"}`);throw R.shouldRetryWithoutCache=!0,X?.usedCache&&(R.cacheUsed=!0),R}let de=await B.getPageState(_.sessionId,_.url,null,O,_.testFolderId,_.projectId);if(!de?.success)throw new Error(de?.error||"Failed to capture initial page state");await w.executeTestSteps(_,de,O,{enableCache:!P});let ye=await m.executeActions(_.sessionId,_.id,H,"after",O,_.testFolderId,_.projectId,{enableCache:!P,projectId:h,testId:U});if(!ye?.success){let R=new Error(`After actions failed: ${ye?.message||"Unknown error"}`);throw R.shouldRetryWithoutCache=!0,ye?.usedCache&&(R.cacheUsed=!0),R}o.addLog(_.id,"success",`Test "${_.testName}" completed successfully`),ae=!0;break}catch(X){if(!P&&!!X?.shouldRetryWithoutCache){P=!0,pr(_.projectId,U||null),mr(_.sessionId),o.addLog(_.id,"warning",`Cache invalidated after failure - retrying test "${_.testName}" without cache`),await Y.cleanupSession(),_.startedAt=new Date,oe++;continue}o.addLog(_.id,"error",`Test "${_.testName}" failed`,X.message||String(X)),ce=!0;break}}ae?k++:ce&&v++,await D(_,O,ce&&C==="stopQueue"),V(_.sessionId)}catch(oe){o.addLog(_.id,"error",`Test "${_.testName}" failed`,oe.message||String(oe)),v++,await D(_,O,C==="stopQueue"),V(_.sessionId)}if(v>0&&C==="stopQueue")break}}finally{await Y.cleanupSession()}return v>0?{success:!1,passed:k,failed:v,total:A.length}:{success:!0,passed:k,failed:v,total:A.length}}var K=new Ht;K.name("agenqa").description("Agenqa CLI for cloud projects").version("0.1.0");process.on("SIGINT",()=>{console.log(`
43
+ Interrupted. Exiting.`),process.exit(130)});function _r(s,e,t){let r=pt(t||Ce(s,e));if(!r)throw new Error("API base URL is not configured in this build.");return r}function vt(s){console.log(`Synced project ${s.project?.name||s.project?.id}`),console.log(`Files: ${s.files.downloaded} downloaded, ${s.files.skipped} skipped, ${s.files.removed} removed.`),s.cache&&(s.cacheDisabledGlobally?console.log("Cache disabled globally for this project."):console.log("Cache synced."))}function Tn(s){return typeof s?.cacheCloudEnabled=="boolean"?s.cacheCloudEnabled:!!s?.cacheEnabled}function Vn(s){return typeof s?.cacheLocalEnabled=="boolean"?s.cacheLocalEnabled:!!s?.cacheEnabled}async function $e(s){throw Xt(s)&&(console.error("Cloud key is invalid or expired. Please re-import the project."),process.exit(2)),s}K.command("import").description("Import a cloud project using project id and secret key").requiredOption("-p, --project <projectId>","Cloud project id").requiredOption("-s, --key-secret <secret>","Cloud key secret").action(async s=>{let e=await re(),t=s.project.trim(),r=s.keySecret.trim(),n=_r(e,t);await he("Importing projects from unknown sources can expose you to risks. Do you confirm you trust this project? (yes/no)",{required:!0})!==!0&&(console.error("Import cancelled."),process.exit(1));let a=await he("Enable local cache on this machine? (required for cloud cache) (yes/no)")===!0,c=!1;a&&(c=await he("Enable cloud cache? (warning: reuses collaborators' cached steps; only enable if you trust them to avoid security risks) (yes/no)")===!0);let l={keyToken:r,cacheCloudEnabled:c,cacheLocalEnabled:a,baseUrl:n,importedAt:new Date().toISOString()};e.projects[t]=l,await be(e),await De(t);try{let u=await Re(e,t);vt(u),console.log("Import completed.")}catch(u){await $e(u),console.error(u.message||String(u)),process.exit(1)}});K.command("list").description("List stored projects").action(async()=>{let s=await re(),e=Object.entries(s.projects||{});if(e.length===0){console.log("No projects imported.");return}let t=[];for(let[a,c]of e){let l=null;try{l=await q(wr.default.join(ne(a),"project.json"),null)}catch(p){console.error(`Warning: failed to read metadata for project ${a}: ${p.message||p}`)}let u=Tn(c)?"enabled":"disabled",d=c.importedAt||"import time unknown",h=Ce(s,a)||"base URL not set";t.push([a,l?.name||"",h,u,d])}let r=["Project ID","Name","Base URL","Cache","Imported At"],n=r.map((a,c)=>Math.max(a.length,...t.map(l=>(l[c]||"").length))),i=n.map(a=>"-".repeat(a)).join("-+-"),o=a=>a.map((c,l)=>String(c||"").padEnd(n[l]," ")).join(" | ");console.log("Stored projects:"),console.log(o(r)),console.log(i),t.forEach(a=>console.log(o(a)))});K.command("sync").description("Sync a cloud project locally").requiredOption("-p, --project <projectId>","Cloud project id").action(async s=>{let e=await re(),t=s.project.trim();try{let r=await Re(e,t);vt(r)}catch(r){await $e(r),console.error(r.message||String(r)),process.exit(1)}});K.command("remove-project").description("Remove an imported project and local data").requiredOption("-p, --project <projectId>","Cloud project id").action(async s=>{let e=s.project.trim(),t=await re();t.projects?.[e]||(console.error(`Project ${e} is not imported. Run "agenqa import" first.`),process.exit(1)),await he(`Remove local data for project ${e}? This does not delete the cloud project. (yes/no)`,{required:!0})||(console.error("Remove cancelled."),process.exit(1)),delete t.projects[e],await be(t),await ft(e),console.log(`Removed local data for project ${e}.`)});K.command("cache").description("Enable or disable cloud cache for a project").requiredOption("-p, --project <projectId>","Project id").option("--enable","Enable cache").option("--disable","Disable cache").action(async s=>{let e=s.project.trim(),t=s.enable===!0?!0:s.disable===!0?!1:null;t===null&&(console.error("Choose either --enable or --disable."),process.exit(1));let r=await re(),n=r.projects?.[e];n||(console.error(`Project ${e} is not imported. Run "agenqa import" first.`),process.exit(1)),t&&(console.log("Warning: cache reuses generated steps from collaborators. Enable only if you trust the project sources."),await he("Do you want to enable cache? (yes/no)",{required:!0})||(console.error("Cache enable cancelled."),process.exit(1))),n.cacheCloudEnabled=t,n.cacheEnabled!==void 0&&(n.cacheEnabled=t),await be(r),console.log(`Cache ${t?"enabled":"disabled"} for project ${e}.`)});K.command("reset-cache").description("Clear local cache (cloud cache downloads and local-only cache)").requiredOption("-p, --project <projectId>","Project id").action(async s=>{let e=s.project.trim();(await re()).projects?.[e]||(console.error(`Project ${e} is not imported. Run "agenqa import" first.`),process.exit(1)),await he(`Reset local cache for project ${e}? (yes/no)`,{required:!0})||(console.error("Reset cache cancelled."),process.exit(1)),await De(e),console.log(`Local cache cleared for project ${e}.`)});async function xt({projectId:s,targetType:e,targetId:t,cacheOverride:r,silent:n}){let i=await re(),o=i.projects?.[s];if(!o)throw new Error(`Project ${s} is not imported. Run "agenqa import" first.`);let a=_r(i,s,o.baseUrl),c=await Re(i,s,{cacheOverride:r}),l=!!c?.cacheDisabledGlobally;if(c?.project?.readOnly)throw new Error("This cloud project is read-only on your current plan. Convert to local-only to run tests.");n||vt(c);let u=l?!1:r!==null?r:Vn(o),d=Ne(o,s),h=await yr({projectId:s,targetType:e,targetId:t,cacheEnabled:u,silent:n,apiConfig:{runTestUrl:`${a}/cloud/cli/run-test`,headers:d}});n||console.log(`Summary: ${h.passed}/${h.total} passed, ${h.failed} failed.`),h.success||process.exit(1)}function At(s){return s.cache===void 0?null:!!s.cache}K.command("run-project").description("Execute a cloud project").requiredOption("-p, --project <projectId>","Cloud project id").option("--cache","Enable cache").option("--no-cache","Disable cache").option("--silent","Suppress non-error logs").action(async s=>{try{await xt({projectId:s.project.trim(),targetType:"project",targetId:null,cacheOverride:At(s),silent:!!s.silent})}catch(e){await $e(e),console.error(e.message||String(e)),process.exit(1)}});K.command("run-folder").description("Execute a cloud test folder").requiredOption("-p, --project <projectId>","Cloud project id").requiredOption("-f, --folder <folderId>","Cloud test folder id").option("--cache","Enable cache").option("--no-cache","Disable cache").option("--silent","Suppress non-error logs").action(async s=>{try{await xt({projectId:s.project.trim(),targetType:"folder",targetId:s.folder.trim(),cacheOverride:At(s),silent:!!s.silent})}catch(e){await $e(e),console.error(e.message||String(e)),process.exit(1)}});K.command("run-test").description("Execute a single cloud test case").requiredOption("-p, --project <projectId>","Cloud project id").requiredOption("-t, --test <testId>","Cloud test case id").option("--cache","Enable cache").option("--no-cache","Disable cache").option("--silent","Suppress non-error logs").action(async s=>{try{await xt({projectId:s.project.trim(),targetType:"test",targetId:s.test.trim(),cacheOverride:At(s),silent:!!s.silent})}catch(e){await $e(e),console.error(e.message||String(e)),process.exit(1)}});K.parseAsync(process.argv);
package/package.json ADDED
@@ -0,0 +1,26 @@
1
+ {
2
+ "name": "agenqa",
3
+ "version": "1.0.0",
4
+ "description": "AgenQA CLI for running cloud projects",
5
+ "type": "module",
6
+ "bin": {
7
+ "agenqa": "dist/cli.cjs"
8
+ },
9
+ "files": [
10
+ "dist"
11
+ ],
12
+ "scripts": {
13
+ "dev": "node src/cli.js",
14
+ "build": "node ./scripts/build.js",
15
+ "prepare": "node ./scripts/build.js",
16
+ "postinstall": "npx playwright install --with-deps chromium"
17
+ },
18
+ "dependencies": {
19
+ "commander": "^12.1.0",
20
+ "dotenv": "^16.4.5",
21
+ "playwright": "^1.46.0"
22
+ },
23
+ "devDependencies": {
24
+ "esbuild": "^0.23.0"
25
+ }
26
+ }