@earlyai/cli 2.4.2 → 2.4.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs +19 -18
- package/package.json +2 -2
package/dist/index.cjs
CHANGED
|
@@ -17,7 +17,7 @@ Expecting one of '${n.join(`', '`)}'`);return this._lifeCycleHooks[e]?this._life
|
|
|
17
17
|
- if the default executable name is not suitable, use the executableFile option to supply a custom name or path
|
|
18
18
|
- ${t?`searched for local subcommand relative to directory '${t}'`:`no directory for search for local subcommand, use .executableDir() to supply a custom directory`}`;throw Error(r)}_executeSubCommand(e,t){t=t.slice();let o=!1,s=[`.js`,`.ts`,`.tsx`,`.mjs`,`.cjs`];function l(e,t){let n=r.resolve(e,t);if(i.existsSync(n))return n;if(s.includes(r.extname(t)))return;let a=s.find(e=>i.existsSync(`${n}${e}`));if(a)return`${n}${a}`}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let u=e._executableFile||`${this._name}-${e._name}`,d=this._executableDir||``;if(this._scriptPath){let e;try{e=i.realpathSync(this._scriptPath)}catch{e=this._scriptPath}d=r.resolve(r.dirname(e),d)}if(d){let t=l(d,u);if(!t&&!e._executableFile&&this._scriptPath){let n=r.basename(this._scriptPath,r.extname(this._scriptPath));n!==this._name&&(t=l(d,`${n}-${e._name}`))}u=t||u}o=s.includes(r.extname(u));let f;a.platform===`win32`?(this._checkForMissingExecutable(u,d,e._name),t.unshift(u),t=h(a.execArgv).concat(t),f=n.spawn(a.execPath,t,{stdio:`inherit`})):o?(t.unshift(u),t=h(a.execArgv).concat(t),f=n.spawn(a.argv[0],t,{stdio:`inherit`})):f=n.spawn(u,t,{stdio:`inherit`}),f.killed||[`SIGUSR1`,`SIGUSR2`,`SIGTERM`,`SIGINT`,`SIGHUP`].forEach(e=>{a.on(e,()=>{f.killed===!1&&f.exitCode===null&&f.kill(e)})});let p=this._exitCallback;f.on(`close`,e=>{e??=1,p?p(new c(e,`commander.executeSubCommandAsync`,`(close)`)):a.exit(e)}),f.on(`error`,t=>{if(t.code===`ENOENT`)this._checkForMissingExecutable(u,d,e._name);else if(t.code===`EACCES`)throw Error(`'${u}' not executable`);if(!p)a.exit(1);else{let e=new c(1,`commander.executeSubCommandAsync`,`(error)`);e.nestedError=t,p(e)}}),this.runningCommand=f}_dispatchSubcommand(e,t,n){let r=this._findCommand(e);r||this.help({error:!0}),r._prepareForParse();let i;return i=this._chainOrCallSubCommandHook(i,r,`preSubcommand`),i=this._chainOrCall(i,()=>{if(r._executableHandler)this._executeSubCommand(r,t.concat(n));else return r._parseCommand(t,n)}),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=(e,t,n)=>{let r=t;if(t!==null&&e.parseArg){let i=`error: command-argument value '${t}' is invalid for argument '${e.name()}'.`;r=this._callParseArg(e,t,n,i)}return r};this._checkNumberOfArguments();let t=[];this.registeredArguments.forEach((n,r)=>{let i=n.defaultValue;n.variadic?r<this.args.length?(i=this.args.slice(r),n.parseArg&&(i=i.reduce((t,r)=>e(n,r,t),n.defaultValue))):i===void 0&&(i=[]):r<this.args.length&&(i=this.args[r],n.parseArg&&(i=e(n,i,n.defaultValue))),t[r]=i}),this.processedArgs=t}_chainOrCall(e,t){return e?.then&&typeof e.then==`function`?e.then(()=>t()):t()}_chainOrCallHooks(e,t){let n=e,r=[];return this._getCommandAndAncestors().reverse().filter(e=>e._lifeCycleHooks[t]!==void 0).forEach(e=>{e._lifeCycleHooks[t].forEach(t=>{r.push({hookedCommand:e,callback:t})})}),t===`postAction`&&r.reverse(),r.forEach(e=>{n=this._chainOrCall(n,()=>e.callback(e.hookedCommand,this))}),n}_chainOrCallSubCommandHook(e,t,n){let r=e;return this._lifeCycleHooks[n]!==void 0&&this._lifeCycleHooks[n].forEach(e=>{r=this._chainOrCall(r,()=>e(this,t))}),r}_parseCommand(e,t){let n=this.parseOptions(t);if(this._parseOptionsEnv(),this._parseOptionsImplied(),e=e.concat(n.operands),t=n.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(n.unknown),this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let r=()=>{n.unknown.length>0&&this.unknownOption(n.unknown[0])},i=`command:${this.name()}`;if(this._actionHandler){r(),this._processArguments();let n;return n=this._chainOrCallHooks(n,`preAction`),n=this._chainOrCall(n,()=>this._actionHandler(this.processedArgs)),this.parent&&(n=this._chainOrCall(n,()=>{this.parent.emit(i,e,t)})),n=this._chainOrCallHooks(n,`postAction`),n}if(this.parent?.listenerCount(i))r(),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():(r(),this._processArguments())}else this.commands.length?(r(),this.help({error:!0})):(r(),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(e=>{let t=e.attributeName();return this.getOptionValue(t)===void 0?!1:this.getOptionValueSource(t)!==`default`});e.filter(e=>e.conflictsWith.length>0).forEach(t=>{let n=e.find(e=>t.conflictsWith.includes(e.attributeName()));n&&this._conflictingOption(t,n)})}_checkForConflictingOptions(){this._getCommandAndAncestors().forEach(e=>{e._checkForConflictingLocalOptions()})}parseOptions(e){let t=[],n=[],r=t;function i(e){return e.length>1&&e[0]===`-`}let a=e=>/^-\d*\.?\d+(e[+-]?\d+)?$/.test(e)?!this._getCommandAndAncestors().some(e=>e.options.map(e=>e.short).some(e=>/^-\d$/.test(e))):!1,o=null,s=null,c=0;for(;c<e.length||s;){let l=s??e[c++];if(s=null,l===`--`){r===n&&r.push(l),r.push(...e.slice(c));break}if(o&&(!i(l)||a(l))){this.emit(`option:${o.name()}`,l);continue}if(o=null,i(l)){let t=this._findOption(l);if(t){if(t.required){let n=e[c++];n===void 0&&this.optionMissingArgument(t),this.emit(`option:${t.name()}`,n)}else if(t.optional){let n=null;c<e.length&&(!i(e[c])||a(e[c]))&&(n=e[c++]),this.emit(`option:${t.name()}`,n)}else this.emit(`option:${t.name()}`);o=t.variadic?t:null;continue}}if(l.length>2&&l[0]===`-`&&l[1]!==`-`){let e=this._findOption(`-${l[1]}`);if(e){e.required||e.optional&&this._combineFlagAndOptionalValue?this.emit(`option:${e.name()}`,l.slice(2)):(this.emit(`option:${e.name()}`),s=`-${l.slice(2)}`);continue}}if(/^--[^=]+=/.test(l)){let e=l.indexOf(`=`),t=this._findOption(l.slice(0,e));if(t&&(t.required||t.optional)){this.emit(`option:${t.name()}`,l.slice(e+1));continue}}if(r===t&&i(l)&&!(this.commands.length===0&&a(l))&&(r=n),(this._enablePositionalOptions||this._passThroughOptions)&&t.length===0&&n.length===0){if(this._findCommand(l)){t.push(l),n.push(...e.slice(c));break}else if(this._getHelpCommand()&&l===this._getHelpCommand().name()){t.push(l,...e.slice(c));break}else if(this._defaultCommandName){n.push(l,...e.slice(c));break}}if(this._passThroughOptions){r.push(l,...e.slice(c));break}r.push(l)}return{operands:t,unknown:n}}opts(){if(this._storeOptionsAsProperties){let e={},t=this.options.length;for(let n=0;n<t;n++){let t=this.options[n].attributeName();e[t]=t===this._versionOptionName?this._version:this[t]}return e}return this._optionValues}optsWithGlobals(){return this._getCommandAndAncestors().reduce((e,t)=>Object.assign(e,t.opts()),{})}error(e,t){this._outputConfiguration.outputError(`${e}\n`,this._outputConfiguration.writeErr),typeof this._showHelpAfterError==`string`?this._outputConfiguration.writeErr(`${this._showHelpAfterError}\n`):this._showHelpAfterError&&(this._outputConfiguration.writeErr(`
|
|
19
19
|
`),this.outputHelp({error:!0}));let n=t||{},r=n.exitCode||1,i=n.code||`commander.error`;this._exit(r,i,e)}_parseOptionsEnv(){this.options.forEach(e=>{if(e.envVar&&e.envVar in a.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()}`,a.env[e.envVar]):this.emit(`optionEnv:${e.name()}`))}})}_parseOptionsImplied(){let e=new f(this.options),t=e=>this.getOptionValue(e)!==void 0&&![`default`,`implied`].includes(this.getOptionValueSource(e));this.options.filter(n=>n.implied!==void 0&&t(n.attributeName())&&e.valueFromOption(this.getOptionValue(n.attributeName()),n)).forEach(e=>{Object.keys(e.implied).filter(e=>!t(e)).forEach(t=>{this.setOptionValueWithSource(t,e.implied[t],`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 n=e=>{let t=e.attributeName(),n=this.getOptionValue(t),r=this.options.find(e=>e.negate&&t===e.attributeName()),i=this.options.find(e=>!e.negate&&t===e.attributeName());return r&&(r.presetArg===void 0&&n===!1||r.presetArg!==void 0&&n===r.presetArg)?r:i||e},r=e=>{let t=n(e),r=t.attributeName();return this.getOptionValueSource(r)===`env`?`environment variable '${t.envVar}'`:`option '${t.flags}'`},i=`error: ${r(e)} cannot be used with ${r(t)}`;this.error(i,{code:`commander.conflictingOption`})}unknownOption(e){if(this._allowUnknownOption)return;let t=``;if(e.startsWith(`--`)&&this._showSuggestionAfterError){let n=[],r=this;do{let e=r.createHelp().visibleOptions(r).filter(e=>e.long).map(e=>e.long);n=n.concat(e),r=r.parent}while(r&&!r._enablePositionalOptions);t=p(e,n)}let n=`error: unknown option '${e}'${t}`;this.error(n,{code:`commander.unknownOption`})}_excessArguments(e){if(this._allowExcessArguments)return;let t=this.registeredArguments.length,n=t===1?``:`s`,r=`error: too many arguments${this.parent?` for '${this.name()}'`:``}. Expected ${t} argument${n} but got ${e.length}.`;this.error(r,{code:`commander.excessArguments`})}unknownCommand(){let e=this.args[0],t=``;if(this._showSuggestionAfterError){let n=[];this.createHelp().visibleCommands(this).forEach(e=>{n.push(e.name()),e.alias()&&n.push(e.alias())}),t=p(e,n)}let n=`error: unknown command '${e}'${t}`;this.error(n,{code:`commander.unknownCommand`})}version(e,t,n){if(e===void 0)return this._version;this._version=e,t||=`-V, --version`,n||=`output the version number`;let r=this.createOption(t,n);return this._versionOptionName=r.attributeName(),this._registerOption(r),this.on(`option:`+r.name(),()=>{this._outputConfiguration.writeOut(`${e}\n`),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 Error(`Command alias can't be the same as its name`);let n=this.parent?._findCommand(e);if(n){let t=[n.name()].concat(n.aliases()).join(`|`);throw Error(`cannot add alias '${e}' to command '${this.name()}' as already have command '${t}'`)}return t._aliases.push(e),this}aliases(e){return e===void 0?this._aliases:(e.forEach(e=>this.alias(e)),this)}usage(e){if(e===void 0){if(this._usage)return this._usage;let e=this.registeredArguments.map(e=>s(e));return[].concat(this.options.length||this._helpOption!==null?`[options]`:[],this.commands.length?`[command]`:[],this.registeredArguments.length?e:[]).join(` `)}return this._usage=e,this}name(e){return e===void 0?this._name:(this._name=e,this)}helpGroup(e){return e===void 0?this._helpGroupHeading??``:(this._helpGroupHeading=e,this)}commandsGroup(e){return e===void 0?this._defaultCommandGroup??``:(this._defaultCommandGroup=e,this)}optionsGroup(e){return e===void 0?this._defaultOptionGroup??``:(this._defaultOptionGroup=e,this)}_initOptionGroup(e){this._defaultOptionGroup&&!e.helpGroupHeading&&e.helpGroup(this._defaultOptionGroup)}_initCommandGroup(e){this._defaultCommandGroup&&!e.helpGroup()&&e.helpGroup(this._defaultCommandGroup)}nameFromFilename(e){return this._name=r.basename(e,r.extname(e)),this}executableDir(e){return e===void 0?this._executableDir:(this._executableDir=e,this)}helpInformation(e){let t=this.createHelp(),n=this._getOutputContext(e);t.prepareContext({error:n.error,helpWidth:n.helpWidth,outputHasColors:n.hasColors});let r=t.formatHelp(this,t);return n.hasColors?r:this._outputConfiguration.stripColor(r)}_getOutputContext(e){e||={};let t=!!e.error,n,r,i;return t?(n=e=>this._outputConfiguration.writeErr(e),r=this._outputConfiguration.getErrHasColors(),i=this._outputConfiguration.getErrHelpWidth()):(n=e=>this._outputConfiguration.writeOut(e),r=this._outputConfiguration.getOutHasColors(),i=this._outputConfiguration.getOutHelpWidth()),{error:t,write:e=>(r||(e=this._outputConfiguration.stripColor(e)),n(e)),hasColors:r,helpWidth:i}}outputHelp(e){let t;typeof e==`function`&&(t=e,e=void 0);let n=this._getOutputContext(e),r={error:n.error,write:n.write,command:this};this._getCommandAndAncestors().reverse().forEach(e=>e.emit(`beforeAllHelp`,r)),this.emit(`beforeHelp`,r);let i=this.helpInformation({error:n.error});if(t&&(i=t(i),typeof i!=`string`&&!Buffer.isBuffer(i)))throw Error(`outputHelp callback must return a string or a Buffer`);n.write(i),this._getHelpOption()?.long&&this.emit(this._getHelpOption().long),this.emit(`afterHelp`,r),this._getCommandAndAncestors().forEach(e=>e.emit(`afterAllHelp`,r))}helpOption(e,t){return typeof e==`boolean`?(e?(this._helpOption===null&&(this._helpOption=void 0),this._defaultOptionGroup&&this._initOptionGroup(this._getHelpOption())):this._helpOption=null,this):(this._helpOption=this.createOption(e??`-h, --help`,t??`display help for command`),(e||t)&&this._initOptionGroup(this._helpOption),this)}_getHelpOption(){return this._helpOption===void 0&&this.helpOption(void 0,void 0),this._helpOption}addHelpOption(e){return this._helpOption=e,this._initOptionGroup(e),this}help(e){this.outputHelp(e);let t=Number(a.exitCode??0);t===0&&e&&typeof e!=`function`&&e.error&&(t=1),this._exit(t,`commander.help`,`(outputHelp)`)}addHelpText(e,t){let n=[`beforeAll`,`before`,`after`,`afterAll`];if(!n.includes(e))throw Error(`Unexpected value for position to addHelpText.
|
|
20
|
-
Expecting one of '${n.join(`', '`)}'`);let r=`${e}Help`;return this.on(r,e=>{let n;n=typeof t==`function`?t({error:e.error,command:e.command}):t,n&&e.write(`${n}\n`)}),this}_outputHelpIfRequested(e){let t=this._getHelpOption();t&&e.find(e=>t.is(e))&&(this.outputHelp(),this._exit(0,`commander.helpDisplayed`,`(outputHelp)`))}};function h(e){return e.map(e=>{if(!e.startsWith(`--inspect`))return e;let t,n=`127.0.0.1`,r=`9229`,i;return(i=e.match(/^(--inspect(-brk)?)$/))===null?(i=e.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))===null?(i=e.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null&&(t=i[1],n=i[3],r=i[4]):(t=i[1],/^\d+$/.test(i[3])?r=i[3]:n=i[3]):t=i[1],t&&r!==`0`?`${t}=${n}:${parseInt(r)+1}`:e})}function g(){if(a.env.NO_COLOR||a.env.FORCE_COLOR===`0`||a.env.FORCE_COLOR===`false`)return!1;if(a.env.FORCE_COLOR||a.env.CLICOLOR_FORCE!==void 0)return!0}e.Command=m,e.useColor=g}));const{program:ne,createCommand:N,createArgument:P,createOption:F,CommanderError:I,InvalidArgumentError:re,InvalidOptionArgumentError:ie,Command:L,Argument:R,Option:ae,Help:z}=u(s((e=>{let{Argument:t}=A(),{Command:n}=M(),{CommanderError:r,InvalidArgumentError:i}=k(),{Help:a}=ee(),{Option:o}=j();e.program=new n,e.createCommand=e=>new n(e),e.createOption=(e,t)=>new o(e,t),e.createArgument=(e,n)=>new t(e,n),e.Command=n,e.Option=o,e.Argument=t,e.Help=a,e.CommanderError=r,e.InvalidArgumentError=i,e.InvalidOptionArgumentError=i}))(),1).default;var oe=`2.4.2`,se=s((e=>{let t=e=>e!=null,n=e=>typeof e==`object`&&!!e,r=e=>Array.isArray(e),i=e=>e instanceof Map,a=e=>e instanceof Set,o=e=>e instanceof Date,s=e=>typeof e==`number`,c=e=>typeof e==`string`,l=e=>typeof e==`boolean`,u=e=>e instanceof Error,d=e=>t(e)?c(e)||r(e)?e.length===0:i(e)||a(e)?e.size===0:o(e)?!1:n(e)?Object.keys(e).length===0:!1:!0,f=e=>u(e)?e.message:`error is not Instance of Error`,p=(e,t)=>{let n=new Set(e);for(let e of n)t.includes(e)||n.delete(e);return[...n]},m=async(e,t)=>{let n=await Promise.all(e.map(e=>t(e)));return e.filter((e,t)=>n[t])},h=(e,t)=>{let n=[];for(let r of e)n.some(e=>t(r,e))||n.push(r);return n},g=e=>[...new Set(e)],_=async e=>Promise.all(e.map(e=>new Promise((t,n)=>e().then(e=>e?t(e):n(e)).catch(e=>n(e))))).then(()=>!0).catch(e=>{if(!l(e))throw e;return e}),v=e=>e.trim().replaceAll(/([\da-z])([A-Z])/g,`$1-$2`).replaceAll(/([A-Z])([A-Z][\da-z])/g,`$1-$2`).replaceAll(/[\s_]+/g,`-`).toLowerCase(),y=e=>e.replaceAll(/[\s-]+/g,` `).split(` `).map(e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()).join(``),b=e=>{let t=0;for(let n=0;n<e.length;n++){let r=e.codePointAt(n)??0;t=Math.trunc(t*31+r)}return t>>>0},x=(...e)=>{let n={};for(let r of e)for(let e in r)t(r[e])&&(n[e]=r[e]);return n},S=(e,t)=>r(e)?e.map(e=>S(e,t)):n(e)?Object.fromEntries(Object.entries(e).filter(([e])=>!t.includes(e)).map(([e,n])=>[e,S(n,t)])):e,C=(e,t)=>{let n;return(...r)=>{clearTimeout(n),n=setTimeout(()=>e(...r),t)}},w=(e,t)=>{let n=!1;return(...r)=>{n||(e(...r),n=!0,setTimeout(()=>{n=!1},t))}};var T=class{listeners=[];addListener(e){this.listeners.push(e)}notifyAll(e){for(let t of this.listeners)t(e)}clear(){this.listeners.length=0}},E=class{set=new Set;constructor(e=[]){for(let t of e)this.safeAdd(t)}safeAdd(e){return t(e)?(this.set.add(e),!0):!1}has(e){return t(e)?this.set.has(e):!1}delete(e){return t(e)?this.set.delete(e):!1}clear(){this.set.clear()}get size(){return this.set.size}values(){return this.set.values()}toSet(){return structuredClone(this.set)}[Symbol.iterator](){return this.set[Symbol.iterator]()}concatSet(e){for(let t of e)this.safeAdd(t)}};e.Observer=T,e.SafeSet=E,e.arePromiseFnsTruthy=_,e.debounce=C,e.fastHash=b,e.filterAsync=m,e.getErrorMessage=f,e.intersection=p,e.isArray=r,e.isBoolean=l,e.isDate=o,e.isDefined=t,e.isEmpty=d,e.isError=u,e.isMap=i,e.isNumber=s,e.isObject=n,e.isSet=a,e.isString=c,e.merge=x,e.removeNestedField=S,e.throttle=w,e.toCamelCase=y,e.toKebabCase=v,e.uniq=g,e.uniqWith=h})),B=se();function ce(e,t,n,{key:r=``,prefix:i=`EARLY`,parser:a,def:o,isRequired:s=!1,envName:c}={}){let l=new ae(t,n);a&&l.argParser(a),s&&l.makeOptionMandatory(!0);let u=c??(()=>{let n=[];for(let t=e;t&&(0,B.isDefined)(t.name());t=t.parent)t.parent&&n.unshift(t.name());return[i,...n,r||t.split(/[ ,|]/)[1].replace(/^--?/,``)].join(`_`).replaceAll(/[- ]/g,`_`).toUpperCase()})();return l.env(u),(0,B.isDefined)(o)&&l.default(o),e.addOption(l),l}function le(e){return(typeof e==`object`&&!!e||typeof e==`function`)&&typeof e.then==`function`}function ue(e){switch(typeof e){case`string`:case`symbol`:return e.toString();case`function`:return e.name;default:throw Error(`Unexpected ${typeof e} service id type`)}}const de=Symbol.for(`@inversifyjs/common/islazyServiceIdentifier`);var fe=class{[de];#e;constructor(e){this.#e=e,this[de]=!0}static is(e){return typeof e==`object`&&!!e&&!0===e[de]}unwrap(){return this.#e()}};function pe(e,t,n){return Reflect.getOwnMetadata(t,e,n)}function me(e,t,n,r){Reflect.defineMetadata(t,n,e,r)}function he(e,t,n,r,i){let a=r(pe(e,t,i)??n());Reflect.defineMetadata(t,a,e,i)}function ge(e){return Object.getPrototypeOf(e.prototype)?.constructor}const _e=`@inversifyjs/container/bindingId`;function ve(){let e=pe(Object,_e)??0;return e===2**53-1?me(Object,_e,-(2**53-1)):he(Object,_e,()=>e,e=>e+1),e}const ye={Request:`Request`,Singleton:`Singleton`,Transient:`Transient`},be={ConstantValue:`ConstantValue`,DynamicValue:`DynamicValue`,Factory:`Factory`,Instance:`Instance`,Provider:`Provider`,ResolvedValue:`ResolvedValue`,ServiceRedirection:`ServiceRedirection`};function*xe(...e){for(let t of e)yield*t}var Se=class e{#e;#t;#n;constructor(e){this.#e=new Map,this.#t={};for(let t of Reflect.ownKeys(e))this.#t[t]=new Map;this.#n=e}add(e,t){this.#a(e).push(t);for(let n of Reflect.ownKeys(t))this.#o(n,t[n]).push(e)}clone(){let e=this.#r(),t=this.#i(),n=Reflect.ownKeys(this.#n),r=this._buildNewInstance(this.#n);this.#u(this.#e,r.#e,e,t);for(let t of n)this.#l(this.#t[t],r.#t[t],e);return r}get(e,t){return this.#t[e].get(t)}getAllKeys(e){return this.#t[e].keys()}removeByRelation(e,t){let n=this.get(e,t);if(n===void 0)return;let r=new Set(n);for(let n of r){let r=this.#e.get(n);if(r===void 0)throw Error(`Expecting model relation, none found`);for(let i of r)i[e]===t&&this.#d(n,i);this.#e.delete(n)}}_buildNewInstance(t){return new e(t)}_cloneModel(e){return e}_cloneRelation(e){return e}#r(){let e=new Map;for(let t of this.#e.keys()){let n=this._cloneModel(t);e.set(t,n)}return e}#i(){let e=new Map;for(let t of this.#e.values())for(let n of t){let t=this._cloneRelation(n);e.set(n,t)}return e}#a(e){let t=this.#e.get(e);return t===void 0&&(t=[],this.#e.set(e,t)),t}#o(e,t){let n=this.#t[e].get(t);return n===void 0&&(n=[],this.#t[e].set(t,n)),n}#s(e,t){let n=t.get(e);if(n===void 0)throw Error(`Expecting model to be cloned, none found`);return n}#c(e,t){let n=t.get(e);if(n===void 0)throw Error(`Expecting relation to be cloned, none found`);return n}#l(e,t,n){for(let[r,i]of e){let e=[];for(let t of i)e.push(this.#s(t,n));t.set(r,e)}}#u(e,t,n,r){for(let[i,a]of e){let e=[];for(let t of a)e.push(this.#c(t,r));t.set(this.#s(i,n),e)}}#d(e,t){for(let n of Reflect.ownKeys(t))this.#f(e,n,t[n])}#f(e,t,n){let r=this.#t[t].get(n);if(r!==void 0){let i=r.indexOf(e);i!==-1&&r.splice(i,1),r.length===0&&this.#t[t].delete(n)}}},Ce;(function(e){e.moduleId=`moduleId`,e.serviceId=`serviceId`})(Ce||={});var we=class e{#e;#t;constructor(e,t){this.#e=t??new Se({moduleId:{isOptional:!0},serviceId:{isOptional:!1}}),this.#t=e}static build(t){return new e(t)}add(e,t){this.#e.add(e,t)}clone(){return new e(this.#t,this.#e.clone())}get(e){let t=[],n=this.#e.get(Ce.serviceId,e);n!==void 0&&t.push(n);let r=this.#t()?.get(e);if(r!==void 0&&t.push(r),t.length!==0)return xe(...t)}removeAllByModuleId(e){this.#e.removeByRelation(Ce.moduleId,e)}removeAllByServiceId(e){this.#e.removeByRelation(Ce.serviceId,e)}};const Te=`@inversifyjs/core/classMetadataReflectKey`;function Ee(){return{constructorArguments:[],lifecycle:{postConstructMethodNames:new Set,preDestroyMethodNames:new Set},properties:new Map,scope:void 0}}const De=`@inversifyjs/core/pendingClassMetadataCountReflectKey`,Oe=Symbol.for(`@inversifyjs/core/InversifyCoreError`);var ke=class e extends Error{[Oe];kind;constructor(e,t,n){super(t,n),this[Oe]=!0,this.kind=e}static is(e){return typeof e==`object`&&!!e&&!0===e[Oe]}static isErrorOfKind(t,n){return e.is(t)&&t.kind===n}},Ae,je,Me,Ne,Pe;function Fe(e){let t=pe(e,Te)??Ee();if(!function(e){let t=pe(e,De);return t!==void 0&&t!==0}(e))return function(e,t){let n=[];if(t.length<e.length)throw new ke(Ae.missingInjectionDecorator,`Found unexpected missing metadata on type "${e.name}". "${e.name}" constructor requires at least ${e.length.toString()} arguments, found ${t.length.toString()} instead.\nAre you using @inject, @multiInject or @unmanaged decorators in every non optional constructor argument?\n\nIf you're using typescript and want to rely on auto injection, set "emitDecoratorMetadata" compiler option to true`);for(let e=0;e<t.length;++e)t[e]===void 0&&n.push(e);if(n.length>0)throw new ke(Ae.missingInjectionDecorator,`Found unexpected missing metadata on type "${e.name}" at constructor indexes "${n.join(`", "`)}".\n\nAre you using @inject, @multiInject or @unmanaged decorators at those indexes?\n\nIf you're using typescript and want to rely on auto injection, set "emitDecoratorMetadata" compiler option to true`)}(e,t.constructorArguments),t;(function(e,t){let n=[];for(let r=0;r<t.constructorArguments.length;++r){let i=t.constructorArguments[r];i!==void 0&&i.kind!==je.unknown||n.push(` - Missing or incomplete metadata for type "${e.name}" at constructor argument with index ${r.toString()}.\nEvery constructor parameter must be decorated either with @inject, @multiInject or @unmanaged decorator.`)}for(let[r,i]of t.properties)i.kind===je.unknown&&n.push(` - Missing or incomplete metadata for type "${e.name}" at property "${r.toString()}".\nThis property must be decorated either with @inject or @multiInject decorator.`);throw n.length===0?new ke(Ae.unknown,`Unexpected class metadata for type "${e.name}" with uncompletion traces.\nThis might be caused by one of the following reasons:\n\n1. A third party library is targeting inversify reflection metadata.\n2. A bug is causing the issue. Consider submiting an issue to fix it.`):new ke(Ae.missingInjectionDecorator,`Invalid class metadata at type ${e.name}:\n\n${n.join(`
|
|
20
|
+
Expecting one of '${n.join(`', '`)}'`);let r=`${e}Help`;return this.on(r,e=>{let n;n=typeof t==`function`?t({error:e.error,command:e.command}):t,n&&e.write(`${n}\n`)}),this}_outputHelpIfRequested(e){let t=this._getHelpOption();t&&e.find(e=>t.is(e))&&(this.outputHelp(),this._exit(0,`commander.helpDisplayed`,`(outputHelp)`))}};function h(e){return e.map(e=>{if(!e.startsWith(`--inspect`))return e;let t,n=`127.0.0.1`,r=`9229`,i;return(i=e.match(/^(--inspect(-brk)?)$/))===null?(i=e.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))===null?(i=e.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null&&(t=i[1],n=i[3],r=i[4]):(t=i[1],/^\d+$/.test(i[3])?r=i[3]:n=i[3]):t=i[1],t&&r!==`0`?`${t}=${n}:${parseInt(r)+1}`:e})}function g(){if(a.env.NO_COLOR||a.env.FORCE_COLOR===`0`||a.env.FORCE_COLOR===`false`)return!1;if(a.env.FORCE_COLOR||a.env.CLICOLOR_FORCE!==void 0)return!0}e.Command=m,e.useColor=g}));const{program:ne,createCommand:N,createArgument:P,createOption:F,CommanderError:I,InvalidArgumentError:re,InvalidOptionArgumentError:ie,Command:L,Argument:R,Option:ae,Help:z}=u(s((e=>{let{Argument:t}=A(),{Command:n}=M(),{CommanderError:r,InvalidArgumentError:i}=k(),{Help:a}=ee(),{Option:o}=j();e.program=new n,e.createCommand=e=>new n(e),e.createOption=(e,t)=>new o(e,t),e.createArgument=(e,n)=>new t(e,n),e.Command=n,e.Option=o,e.Argument=t,e.Help=a,e.CommanderError=r,e.InvalidArgumentError=i,e.InvalidOptionArgumentError=i}))(),1).default;var oe=`2.4.4`,se=s((e=>{let t=e=>e!=null,n=e=>typeof e==`object`&&!!e,r=e=>Array.isArray(e),i=e=>e instanceof Map,a=e=>e instanceof Set,o=e=>e instanceof Date,s=e=>typeof e==`number`,c=e=>typeof e==`string`,l=e=>typeof e==`boolean`,u=e=>e instanceof Error,d=e=>t(e)?c(e)||r(e)?e.length===0:i(e)||a(e)?e.size===0:o(e)?!1:n(e)?Object.keys(e).length===0:!1:!0,f=e=>u(e)?e.message:`error is not Instance of Error`,p=(e,t)=>{let n=new Set(e);for(let e of n)t.includes(e)||n.delete(e);return[...n]},m=async(e,t)=>{let n=await Promise.all(e.map(e=>t(e)));return e.filter((e,t)=>n[t])},h=(e,t)=>{let n=[];for(let r of e)n.some(e=>t(r,e))||n.push(r);return n},g=e=>[...new Set(e)],_=async e=>Promise.all(e.map(e=>new Promise((t,n)=>e().then(e=>e?t(e):n(e)).catch(e=>n(e))))).then(()=>!0).catch(e=>{if(!l(e))throw e;return e}),v=e=>e.trim().replaceAll(/([\da-z])([A-Z])/g,`$1-$2`).replaceAll(/([A-Z])([A-Z][\da-z])/g,`$1-$2`).replaceAll(/[\s_]+/g,`-`).toLowerCase(),y=e=>e.replaceAll(/[\s-]+/g,` `).split(` `).map(e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()).join(``),b=e=>{let t=0;for(let n=0;n<e.length;n++){let r=e.codePointAt(n)??0;t=Math.trunc(t*31+r)}return t>>>0},x=(...e)=>{let n={};for(let r of e)for(let e in r)t(r[e])&&(n[e]=r[e]);return n},S=(e,t)=>r(e)?e.map(e=>S(e,t)):n(e)?Object.fromEntries(Object.entries(e).filter(([e])=>!t.includes(e)).map(([e,n])=>[e,S(n,t)])):e,C=(e,t)=>{let n;return(...r)=>{clearTimeout(n),n=setTimeout(()=>e(...r),t)}},w=(e,t)=>{let n=!1;return(...r)=>{n||(e(...r),n=!0,setTimeout(()=>{n=!1},t))}};var T=class{listeners=[];addListener(e){this.listeners.push(e)}notifyAll(e){for(let t of this.listeners)t(e)}clear(){this.listeners.length=0}},E=class{set=new Set;constructor(e=[]){for(let t of e)this.safeAdd(t)}safeAdd(e){return t(e)?(this.set.add(e),!0):!1}has(e){return t(e)?this.set.has(e):!1}delete(e){return t(e)?this.set.delete(e):!1}clear(){this.set.clear()}get size(){return this.set.size}values(){return this.set.values()}toSet(){return structuredClone(this.set)}[Symbol.iterator](){return this.set[Symbol.iterator]()}concatSet(e){for(let t of e)this.safeAdd(t)}};e.Observer=T,e.SafeSet=E,e.arePromiseFnsTruthy=_,e.debounce=C,e.fastHash=b,e.filterAsync=m,e.getErrorMessage=f,e.intersection=p,e.isArray=r,e.isBoolean=l,e.isDate=o,e.isDefined=t,e.isEmpty=d,e.isError=u,e.isMap=i,e.isNumber=s,e.isObject=n,e.isSet=a,e.isString=c,e.merge=x,e.removeNestedField=S,e.throttle=w,e.toCamelCase=y,e.toKebabCase=v,e.uniq=g,e.uniqWith=h})),B=se();function ce(e,t,n,{key:r=``,prefix:i=`EARLY`,parser:a,def:o,isRequired:s=!1,envName:c}={}){let l=new ae(t,n);a&&l.argParser(a),s&&l.makeOptionMandatory(!0);let u=c??(()=>{let n=[];for(let t=e;t&&(0,B.isDefined)(t.name());t=t.parent)t.parent&&n.unshift(t.name());return[i,...n,r||t.split(/[ ,|]/)[1].replace(/^--?/,``)].join(`_`).replaceAll(/[- ]/g,`_`).toUpperCase()})();return l.env(u),(0,B.isDefined)(o)&&l.default(o),e.addOption(l),l}function le(e){return(typeof e==`object`&&!!e||typeof e==`function`)&&typeof e.then==`function`}function ue(e){switch(typeof e){case`string`:case`symbol`:return e.toString();case`function`:return e.name;default:throw Error(`Unexpected ${typeof e} service id type`)}}const de=Symbol.for(`@inversifyjs/common/islazyServiceIdentifier`);var fe=class{[de];#e;constructor(e){this.#e=e,this[de]=!0}static is(e){return typeof e==`object`&&!!e&&!0===e[de]}unwrap(){return this.#e()}};function pe(e,t,n){return Reflect.getOwnMetadata(t,e,n)}function me(e,t,n,r){Reflect.defineMetadata(t,n,e,r)}function he(e,t,n,r,i){let a=r(pe(e,t,i)??n());Reflect.defineMetadata(t,a,e,i)}function ge(e){return Object.getPrototypeOf(e.prototype)?.constructor}const _e=`@inversifyjs/container/bindingId`;function ve(){let e=pe(Object,_e)??0;return e===2**53-1?me(Object,_e,-(2**53-1)):he(Object,_e,()=>e,e=>e+1),e}const ye={Request:`Request`,Singleton:`Singleton`,Transient:`Transient`},be={ConstantValue:`ConstantValue`,DynamicValue:`DynamicValue`,Factory:`Factory`,Instance:`Instance`,Provider:`Provider`,ResolvedValue:`ResolvedValue`,ServiceRedirection:`ServiceRedirection`};function*xe(...e){for(let t of e)yield*t}var Se=class e{#e;#t;#n;constructor(e){this.#e=new Map,this.#t={};for(let t of Reflect.ownKeys(e))this.#t[t]=new Map;this.#n=e}add(e,t){this.#a(e).push(t);for(let n of Reflect.ownKeys(t))this.#o(n,t[n]).push(e)}clone(){let e=this.#r(),t=this.#i(),n=Reflect.ownKeys(this.#n),r=this._buildNewInstance(this.#n);this.#u(this.#e,r.#e,e,t);for(let t of n)this.#l(this.#t[t],r.#t[t],e);return r}get(e,t){return this.#t[e].get(t)}getAllKeys(e){return this.#t[e].keys()}removeByRelation(e,t){let n=this.get(e,t);if(n===void 0)return;let r=new Set(n);for(let n of r){let r=this.#e.get(n);if(r===void 0)throw Error(`Expecting model relation, none found`);for(let i of r)i[e]===t&&this.#d(n,i);this.#e.delete(n)}}_buildNewInstance(t){return new e(t)}_cloneModel(e){return e}_cloneRelation(e){return e}#r(){let e=new Map;for(let t of this.#e.keys()){let n=this._cloneModel(t);e.set(t,n)}return e}#i(){let e=new Map;for(let t of this.#e.values())for(let n of t){let t=this._cloneRelation(n);e.set(n,t)}return e}#a(e){let t=this.#e.get(e);return t===void 0&&(t=[],this.#e.set(e,t)),t}#o(e,t){let n=this.#t[e].get(t);return n===void 0&&(n=[],this.#t[e].set(t,n)),n}#s(e,t){let n=t.get(e);if(n===void 0)throw Error(`Expecting model to be cloned, none found`);return n}#c(e,t){let n=t.get(e);if(n===void 0)throw Error(`Expecting relation to be cloned, none found`);return n}#l(e,t,n){for(let[r,i]of e){let e=[];for(let t of i)e.push(this.#s(t,n));t.set(r,e)}}#u(e,t,n,r){for(let[i,a]of e){let e=[];for(let t of a)e.push(this.#c(t,r));t.set(this.#s(i,n),e)}}#d(e,t){for(let n of Reflect.ownKeys(t))this.#f(e,n,t[n])}#f(e,t,n){let r=this.#t[t].get(n);if(r!==void 0){let i=r.indexOf(e);i!==-1&&r.splice(i,1),r.length===0&&this.#t[t].delete(n)}}},Ce;(function(e){e.moduleId=`moduleId`,e.serviceId=`serviceId`})(Ce||={});var we=class e{#e;#t;constructor(e,t){this.#e=t??new Se({moduleId:{isOptional:!0},serviceId:{isOptional:!1}}),this.#t=e}static build(t){return new e(t)}add(e,t){this.#e.add(e,t)}clone(){return new e(this.#t,this.#e.clone())}get(e){let t=[],n=this.#e.get(Ce.serviceId,e);n!==void 0&&t.push(n);let r=this.#t()?.get(e);if(r!==void 0&&t.push(r),t.length!==0)return xe(...t)}removeAllByModuleId(e){this.#e.removeByRelation(Ce.moduleId,e)}removeAllByServiceId(e){this.#e.removeByRelation(Ce.serviceId,e)}};const Te=`@inversifyjs/core/classMetadataReflectKey`;function Ee(){return{constructorArguments:[],lifecycle:{postConstructMethodNames:new Set,preDestroyMethodNames:new Set},properties:new Map,scope:void 0}}const De=`@inversifyjs/core/pendingClassMetadataCountReflectKey`,Oe=Symbol.for(`@inversifyjs/core/InversifyCoreError`);var ke=class e extends Error{[Oe];kind;constructor(e,t,n){super(t,n),this[Oe]=!0,this.kind=e}static is(e){return typeof e==`object`&&!!e&&!0===e[Oe]}static isErrorOfKind(t,n){return e.is(t)&&t.kind===n}},Ae,je,Me,Ne,Pe;function Fe(e){let t=pe(e,Te)??Ee();if(!function(e){let t=pe(e,De);return t!==void 0&&t!==0}(e))return function(e,t){let n=[];if(t.length<e.length)throw new ke(Ae.missingInjectionDecorator,`Found unexpected missing metadata on type "${e.name}". "${e.name}" constructor requires at least ${e.length.toString()} arguments, found ${t.length.toString()} instead.\nAre you using @inject, @multiInject or @unmanaged decorators in every non optional constructor argument?\n\nIf you're using typescript and want to rely on auto injection, set "emitDecoratorMetadata" compiler option to true`);for(let e=0;e<t.length;++e)t[e]===void 0&&n.push(e);if(n.length>0)throw new ke(Ae.missingInjectionDecorator,`Found unexpected missing metadata on type "${e.name}" at constructor indexes "${n.join(`", "`)}".\n\nAre you using @inject, @multiInject or @unmanaged decorators at those indexes?\n\nIf you're using typescript and want to rely on auto injection, set "emitDecoratorMetadata" compiler option to true`)}(e,t.constructorArguments),t;(function(e,t){let n=[];for(let r=0;r<t.constructorArguments.length;++r){let i=t.constructorArguments[r];i!==void 0&&i.kind!==je.unknown||n.push(` - Missing or incomplete metadata for type "${e.name}" at constructor argument with index ${r.toString()}.\nEvery constructor parameter must be decorated either with @inject, @multiInject or @unmanaged decorator.`)}for(let[r,i]of t.properties)i.kind===je.unknown&&n.push(` - Missing or incomplete metadata for type "${e.name}" at property "${r.toString()}".\nThis property must be decorated either with @inject or @multiInject decorator.`);throw n.length===0?new ke(Ae.unknown,`Unexpected class metadata for type "${e.name}" with uncompletion traces.\nThis might be caused by one of the following reasons:\n\n1. A third party library is targeting inversify reflection metadata.\n2. A bug is causing the issue. Consider submiting an issue to fix it.`):new ke(Ae.missingInjectionDecorator,`Invalid class metadata at type ${e.name}:\n\n${n.join(`
|
|
21
21
|
|
|
22
22
|
`)}`)})(e,t)}function Ie(e,t){let n=Fe(t).scope??e.scope;return{cache:{isRight:!1,value:void 0},id:ve(),implementationType:t,isSatisfiedBy:()=>!0,moduleId:void 0,onActivation:void 0,onDeactivation:void 0,scope:n,serviceIdentifier:t,type:be.Instance}}function Le(e){return e.isRight?{isRight:!0,value:e.value}:e}function Re(e){switch(e.type){case be.ConstantValue:case be.DynamicValue:return function(e){return{cache:Le(e.cache),id:e.id,isSatisfiedBy:e.isSatisfiedBy,moduleId:e.moduleId,onActivation:e.onActivation,onDeactivation:e.onDeactivation,scope:e.scope,serviceIdentifier:e.serviceIdentifier,type:e.type,value:e.value}}(e);case be.Factory:return function(e){return{cache:Le(e.cache),factory:e.factory,id:e.id,isSatisfiedBy:e.isSatisfiedBy,moduleId:e.moduleId,onActivation:e.onActivation,onDeactivation:e.onDeactivation,scope:e.scope,serviceIdentifier:e.serviceIdentifier,type:e.type}}(e);case be.Instance:return function(e){return{cache:Le(e.cache),id:e.id,implementationType:e.implementationType,isSatisfiedBy:e.isSatisfiedBy,moduleId:e.moduleId,onActivation:e.onActivation,onDeactivation:e.onDeactivation,scope:e.scope,serviceIdentifier:e.serviceIdentifier,type:e.type}}(e);case be.Provider:return function(e){return{cache:Le(e.cache),id:e.id,isSatisfiedBy:e.isSatisfiedBy,moduleId:e.moduleId,onActivation:e.onActivation,onDeactivation:e.onDeactivation,provider:e.provider,scope:e.scope,serviceIdentifier:e.serviceIdentifier,type:e.type}}(e);case be.ResolvedValue:return function(e){return{cache:Le(e.cache),factory:e.factory,id:e.id,isSatisfiedBy:e.isSatisfiedBy,metadata:e.metadata,moduleId:e.moduleId,onActivation:e.onActivation,onDeactivation:e.onDeactivation,scope:e.scope,serviceIdentifier:e.serviceIdentifier,type:e.type}}(e);case be.ServiceRedirection:return function(e){return{id:e.id,isSatisfiedBy:e.isSatisfiedBy,moduleId:e.moduleId,serviceIdentifier:e.serviceIdentifier,targetServiceIdentifier:e.targetServiceIdentifier,type:e.type}}(e)}}(function(e){e[e.injectionDecoratorConflict=0]=`injectionDecoratorConflict`,e[e.missingInjectionDecorator=1]=`missingInjectionDecorator`,e[e.planning=2]=`planning`,e[e.resolution=3]=`resolution`,e[e.unknown=4]=`unknown`})(Ae||={}),function(e){e[e.unknown=32]=`unknown`}(je||={}),function(e){e.id=`id`,e.moduleId=`moduleId`,e.serviceId=`serviceId`}(Me||={});var ze=class e extends Se{_buildNewInstance(t){return new e(t)}_cloneModel(e){return Re(e)}},Be=class e{#e;#t;#n;constructor(e,t,n){this.#t=n??new ze({id:{isOptional:!1},moduleId:{isOptional:!0},serviceId:{isOptional:!1}}),this.#n=e,this.#e=t}static build(t,n){return new e(t,n)}clone(){return new e(this.#n,this.#e,this.#t.clone())}get(e){let t=this.getNonParentBindings(e)??this.#n()?.get(e);if(t!==void 0)return t;let n=this.#r(e);return n===void 0?n:[n]}*getChained(e){let t=this.getNonParentBindings(e);t!==void 0&&(yield*t);let n=this.#n();if(n===void 0){if(t===void 0){let t=this.#r(e);t!==void 0&&(yield t)}}else yield*n.getChained(e)}getBoundServices(){let e=new Set(this.#t.getAllKeys(Me.serviceId)),t=this.#n();if(t!==void 0)for(let n of t.getBoundServices())e.add(n);return e}getById(e){return this.#t.get(Me.id,e)??this.#n()?.getById(e)}getByModuleId(e){return this.#t.get(Me.moduleId,e)??this.#n()?.getByModuleId(e)}getNonParentBindings(e){return this.#t.get(Me.serviceId,e)}getNonParentBoundServices(){return this.#t.getAllKeys(Me.serviceId)}removeById(e){this.#t.removeByRelation(Me.id,e)}removeAllByModuleId(e){this.#t.removeByRelation(Me.moduleId,e)}removeAllByServiceId(e){this.#t.removeByRelation(Me.serviceId,e)}set(e){let t={[Me.id]:e.id,[Me.serviceId]:e.serviceIdentifier};e.moduleId!==void 0&&(t[Me.moduleId]=e.moduleId),this.#t.add(e,t)}#r(e){if(this.#e===void 0||typeof e!=`function`)return;let t=Ie(this.#e,e);return this.set(t),t}};(function(e){e.moduleId=`moduleId`,e.serviceId=`serviceId`})(Ne||={});var Ve=class e{#e;#t;constructor(e,t){this.#e=t??new Se({moduleId:{isOptional:!0},serviceId:{isOptional:!1}}),this.#t=e}static build(t){return new e(t)}add(e,t){this.#e.add(e,t)}clone(){return new e(this.#t,this.#e.clone())}get(e){let t=[],n=this.#e.get(Ne.serviceId,e);n!==void 0&&t.push(n);let r=this.#t()?.get(e);if(r!==void 0&&t.push(r),t.length!==0)return xe(...t)}removeAllByModuleId(e){this.#e.removeByRelation(Ne.moduleId,e)}removeAllByServiceId(e){this.#e.removeByRelation(Ne.serviceId,e)}};function He(){return 0}function V(e){return t=>{t!==void 0&&t.kind===je.unknown&&he(e,De,He,e=>e-1)}}function Ue(e,t){return(...n)=>r=>{if(r===void 0)return e(...n);if(r.kind===Pe.unmanaged)throw new ke(Ae.injectionDecoratorConflict,`Unexpected injection found. Multiple @inject, @multiInject or @unmanaged decorators found`);return t(r,...n)}}function We(e){if(e.kind!==je.unknown&&!0!==e.isFromTypescriptParamType)throw new ke(Ae.injectionDecoratorConflict,`Unexpected injection found. Multiple @inject, @multiInject or @unmanaged decorators found`)}(function(e){e[e.multipleInjection=0]=`multipleInjection`,e[e.singleInjection=1]=`singleInjection`,e[e.unmanaged=2]=`unmanaged`})(Pe||={});const Ge=Ue(function(e,t,n){return e===Pe.multipleInjection?{chained:n?.chained??!1,kind:e,name:void 0,optional:!1,tags:new Map,value:t}:{kind:e,name:void 0,optional:!1,tags:new Map,value:t}},function(e,t,n,r){return We(e),t===Pe.multipleInjection?{...e,chained:r?.chained??!1,kind:t,value:n}:{...e,kind:t,value:n}});function Ke(e,t){return n=>{let r=n.properties.get(t);return n.properties.set(t,e(r)),n}}var qe;function Je(e,t,n,r){if(ke.isErrorOfKind(r,Ae.injectionDecoratorConflict)){let i=function(e,t,n){if(n===void 0){if(t===void 0)throw new ke(Ae.unknown,`Unexpected undefined property and index values`);return{kind:qe.property,property:t,targetClass:e.constructor}}return typeof n==`number`?{index:n,kind:qe.parameter,targetClass:e}:{kind:qe.method,method:t,targetClass:e}}(e,t,n);throw new ke(Ae.injectionDecoratorConflict,`Unexpected injection error.\n\nCause:\n\n${r.message}\n\nDetails\n\n${function(e){switch(e.kind){case qe.method:return`[class: "${e.targetClass.name}", method: "${e.method.toString()}"]`;case qe.parameter:return`[class: "${e.targetClass.name}", index: "${e.index.toString()}"]`;case qe.property:return`[class: "${e.targetClass.name}", property: "${e.property.toString()}"]`}}(i)}`,{cause:r})}throw r}function Ye(e,t){return(n,r,i)=>{try{i===void 0?function(e,t){let n=Xe(e,t);return(e,t)=>{he(e.constructor,Te,Ee,Ke(n(e),t))}}(e,t)(n,r):typeof i==`number`?function(e,t){let n=Xe(e,t);return(e,t,r)=>{if(!function(e,t){return typeof e==`function`&&t===void 0}(e,t))throw new ke(Ae.injectionDecoratorConflict,`Found an @inject decorator in a non constructor parameter.\nFound @inject decorator at method "${t?.toString()??``}" at class "${e.constructor.name}"`);he(e,Te,Ee,function(e,t){return n=>{let r=n.constructorArguments[t];return n.constructorArguments[t]=e(r),n}}(n(e),r))}}(e,t)(n,r,i):function(e,t){let n=Xe(e,t);return(e,t,r)=>{if(!function(e){return e.set!==void 0}(r))throw new ke(Ae.injectionDecoratorConflict,`Found an @inject decorator in a non setter property method.\nFound @inject decorator at method "${t.toString()}" at class "${e.constructor.name}"`);he(e.constructor,Te,Ee,Ke(n(e),t))}}(e,t)(n,r,i)}catch(e){Je(n,r,i,e)}}}function Xe(e,t){return n=>{let r=t(n);return t=>(r(t),e(t))}}function Ze(e){return Ye(Ge(Pe.singleInjection,e),V)}(function(e){e[e.method=0]=`method`,e[e.parameter=1]=`parameter`,e[e.property=2]=`property`})(qe||={});const Qe=`@inversifyjs/core/classIsInjectableFlagReflectKey`,H=[Array,BigInt,Boolean,Function,Number,Object,String];function $e(e){let t=pe(e,`design:paramtypes`);t!==void 0&&he(e,Te,Ee,function(e){return t=>(e.forEach((e,n)=>{var r;t.constructorArguments[n]!==void 0||(r=e,H.includes(r))||(t.constructorArguments[n]=function(e){return{isFromTypescriptParamType:!0,kind:Pe.singleInjection,name:void 0,optional:!1,tags:new Map,value:e}}(e))}),t)}(t))}function et(e){return t=>{(function(e){if(pe(e,Qe)!==void 0)throw new ke(Ae.injectionDecoratorConflict,`Cannot apply @injectable decorator multiple times at class "${e.name}"`);me(e,Qe,!0)})(t),$e(t),e!==void 0&&he(t,Te,Ee,t=>({...t,scope:e}))}}function tt(e,t,n){let r;return e.extendConstructorArguments??!0?(r=[...t.constructorArguments],n.constructorArguments.map((e,t)=>{r[t]=e})):r=n.constructorArguments,r}function nt(e,t,n){return e?new Set([...t,...n]):n}function rt(e,t,n){let r=e.lifecycle?.extendPostConstructMethods??!0,i=nt(e.lifecycle?.extendPreDestroyMethods??!0,t.lifecycle.preDestroyMethodNames,n.lifecycle.preDestroyMethodNames);return{postConstructMethodNames:nt(r,t.lifecycle.postConstructMethodNames,n.lifecycle.postConstructMethodNames),preDestroyMethodNames:i}}function it(e,t,n){let r;return r=e.extendProperties??!0?new Map(xe(t.properties,n.properties)):n.properties,r}function at(e){return t=>{he(t,Te,Ee,function(e,t){return n=>({constructorArguments:tt(e,t,n),lifecycle:rt(e,t,n),properties:it(e,t,n),scope:n.scope})}(e,Fe(e.type)))}}function ot(e){return t=>{let n=ge(t);if(n===void 0)throw new ke(Ae.injectionDecoratorConflict,`Expected base type for type "${t.name}", none found.`);at({...e,type:n})(t)}}function st(e){return t=>{let n=[],r=ge(t);for(;r!==void 0&&r!==Object;){let e=r;n.push(e),r=ge(e)}n.reverse();for(let r of n)at({...e,type:r})(t)}}function U(e){return t=>{t===void 0&&he(e,De,He,e=>e+1)}}function ct(e){return t=>{let n=t??{kind:je.unknown,name:void 0,optional:!1,tags:new Map};if(n.kind===Pe.unmanaged)throw new ke(Ae.injectionDecoratorConflict,`Unexpected injection found. Found @unmanaged injection with additional @named, @optional, @tagged or @targetName injections`);return e(n)}}function lt(e){if(e.optional)throw new ke(Ae.injectionDecoratorConflict,`Unexpected duplicated optional decorator`);return e.optional=!0,e}function ut(){return Ye(ct(lt),U)}var dt;function ft(e){return e instanceof Error?e instanceof RangeError&&/stack space|call stack|too much recursion/i.test(e.message)||e.name===`InternalError`&&/too much recursion/.test(e.message):!1}function pt(e,t){if(ft(t)){let n=function(e){let t=[...e];return t.length===0?`(No dependency trace)`:t.map(ue).join(` -> `)}(function(e){let t=new Set;for(let n of e.servicesBranch){if(t.has(n))return[...t,n];t.add(n)}return[...t]}(e));throw new ke(Ae.planning,`Circular dependency found: ${n}`,{cause:t})}throw t}(function(e){e[e.multipleInjection=0]=`multipleInjection`,e[e.singleInjection=1]=`singleInjection`})(dt||={});const mt=Symbol.for(`@inversifyjs/core/LazyPlanServiceNode`);var ht=class{[mt];_serviceIdentifier;_serviceNode;constructor(e,t){this[mt]=!0,this._serviceNode=e,this._serviceIdentifier=t}get bindings(){return this._getNode().bindings}get isContextFree(){return this._getNode().isContextFree}get serviceIdentifier(){return this._serviceIdentifier}set bindings(e){this._getNode().bindings=e}set isContextFree(e){this._getNode().isContextFree=e}static is(e){return typeof e==`object`&&!!e&&!0===e[mt]}invalidate(){this._serviceNode=void 0}isExpanded(){return this._serviceNode!==void 0}_getNode(){return this._serviceNode===void 0&&(this._serviceNode=this._buildPlanServiceNode()),this._serviceNode}},gt=class e{#e;constructor(e){this.#e=e}get name(){return this.#e.elem.name}get serviceIdentifier(){return this.#e.elem.serviceIdentifier}get tags(){return this.#e.elem.tags}getAncestor(){if(this.#e.elem.getAncestorsCalled=!0,this.#e.previous!==void 0)return new e(this.#e.previous)}};function _t(e,t,n){let r=n?.customServiceIdentifier??t.serviceIdentifier,i=(!0===n?.chained?[...e.operations.getBindingsChained(r)]:[...e.operations.getBindings(r)??[]]).filter(e=>e.isSatisfiedBy(t));if(i.length===0&&e.autobindOptions!==void 0&&typeof r==`function`){let n=Ie(e.autobindOptions,r);e.operations.setBinding(n),n.isSatisfiedBy(t)&&i.push(n)}return i}var vt=class e{last;constructor(e){this.last=e}concat(t){return new e({elem:t,previous:this.last})}[Symbol.iterator](){let e=this.last;return{next:()=>{if(e===void 0)return{done:!0,value:void 0};let t=e.elem;return e=e.previous,{done:!1,value:t}}}}};function yt(e){let t=new Map;return e.rootConstraints.tag!==void 0&&t.set(e.rootConstraints.tag.key,e.rootConstraints.tag.value),new vt({elem:{getAncestorsCalled:!1,name:e.rootConstraints.name,serviceIdentifier:e.rootConstraints.serviceIdentifier,tags:t},previous:void 0})}function bt(e){return e.redirections!==void 0}function xt(e,t,n,r){let i=n.elem.serviceIdentifier,a=n.previous?.elem.serviceIdentifier;Array.isArray(e)?function(e,t,n,r,i,a){if(e.length!==0){let t=`Ambiguous bindings found for service: "${ue(a[a.length-1]??n)}".${Tt(a)}\n\nRegistered bindings:\n\n${e.map(e=>function(e){switch(e.type){case be.Instance:return`[ type: "${e.type}", serviceIdentifier: "${ue(e.serviceIdentifier)}", scope: "${e.scope}", implementationType: "${e.implementationType.name}" ]`;case be.ServiceRedirection:return`[ type: "${e.type}", serviceIdentifier: "${ue(e.serviceIdentifier)}", redirection: "${ue(e.targetServiceIdentifier)}" ]`;default:return`[ type: "${e.type}", serviceIdentifier: "${ue(e.serviceIdentifier)}", scope: "${e.scope}" ]`}}(e.binding)).join(`
|
|
23
23
|
`)}\n\nTrying to resolve bindings for "${Ct(n,r)}".${wt(i)}`;throw new ke(Ae.planning,t)}t||St(n,r,i,a)}(e,t,i,a,n.elem,r):function(e,t,n,r,i,a){e!==void 0||t||St(n,r,i,a)}(e,t,i,a,n.elem,r)}function St(e,t,n,r){let i=`No bindings found for service: "${ue(r[r.length-1]??e)}".\n\nTrying to resolve bindings for "${Ct(e,t)}".${Tt(r)}${wt(n)}`;throw new ke(Ae.planning,i)}function Ct(e,t){return t===void 0?`${ue(e)} (Root service)`:ue(t)}function wt(e){let t=e.tags.size===0?``:`\n- tags:\n - ${[...e.tags.keys()].map(e=>e.toString()).join(`
|
|
@@ -32002,7 +32002,7 @@ https://www.w3ctech.com/topic/2226`));let i=t(...r);return i.postcssPlugin=e,i.p
|
|
|
32002
32002
|
`);let t=new x(`!xml`),n=t,r=``,i=``,a=new S(this.options.processEntities);for(let o=0;o<e.length;o++)if(e[o]===`<`)if(e[o+1]===`/`){let t=L(e,`>`,o,`Closing Tag is not closed.`),a=e.substring(o+2,t).trim();if(this.options.removeNSPrefix){let e=a.indexOf(`:`);e!==-1&&(a=a.substr(e+1))}this.options.transformTagName&&(a=this.options.transformTagName(a)),n&&(r=this.saveTextToParentTag(r,n,i));let s=i.substring(i.lastIndexOf(`.`)+1);if(a&&this.options.unpairedTags.indexOf(a)!==-1)throw Error(`Unpaired tag can not be used as closing tag: </${a}>`);let c=0;s&&this.options.unpairedTags.indexOf(s)!==-1?(c=i.lastIndexOf(`.`,i.lastIndexOf(`.`)-1),this.tagsNodeStack.pop()):c=i.lastIndexOf(`.`),i=i.substring(0,c),n=this.tagsNodeStack.pop(),r=``,o=t}else if(e[o+1]===`?`){let t=R(e,o,!1,`?>`);if(!t)throw Error(`Pi Tag is not closed.`);if(r=this.saveTextToParentTag(r,n,i),!(this.options.ignoreDeclaration&&t.tagName===`?xml`||this.options.ignorePiTags)){let e=new x(t.tagName);e.add(this.options.textNodeName,``),t.tagName!==t.tagExp&&t.attrExpPresent&&(e[`:@`]=this.buildAttributesMap(t.tagExp,i,t.tagName)),this.addChild(n,e,i,o)}o=t.closeIndex+1}else if(e.substr(o+1,3)===`!--`){let t=L(e,`-->`,o+4,`Comment is not closed.`);if(this.options.commentPropName){let a=e.substring(o+4,t-2);r=this.saveTextToParentTag(r,n,i),n.add(this.options.commentPropName,[{[this.options.textNodeName]:a}])}o=t}else if(e.substr(o+1,2)===`!D`){let t=a.readDocType(e,o);this.docTypeEntities=t.entities,o=t.i}else if(e.substr(o+1,2)===`![`){let t=L(e,`]]>`,o,`CDATA is not closed.`)-2,a=e.substring(o+9,t);r=this.saveTextToParentTag(r,n,i);let s=this.parseTextData(a,n.tagname,i,!0,!1,!0,!0);s??=``,this.options.cdataPropName?n.add(this.options.cdataPropName,[{[this.options.textNodeName]:a}]):n.add(this.options.textNodeName,s),o=t+2}else{let a=R(e,o,this.options.removeNSPrefix),s=a.tagName,c=a.rawTagName,l=a.tagExp,u=a.attrExpPresent,d=a.closeIndex;this.options.transformTagName&&(s=this.options.transformTagName(s)),n&&r&&n.tagname!==`!xml`&&(r=this.saveTextToParentTag(r,n,i,!1));let f=n;f&&this.options.unpairedTags.indexOf(f.tagname)!==-1&&(n=this.tagsNodeStack.pop(),i=i.substring(0,i.lastIndexOf(`.`))),s!==t.tagname&&(i+=i?`.`+s:s);let p=o;if(this.isItStopNode(this.stopNodesExact,this.stopNodesWildcard,i,s)){let t=``;if(l.length>0&&l.lastIndexOf(`/`)===l.length-1)s[s.length-1]===`/`?(s=s.substr(0,s.length-1),i=i.substr(0,i.length-1),l=s):l=l.substr(0,l.length-1),o=a.closeIndex;else if(this.options.unpairedTags.indexOf(s)!==-1)o=a.closeIndex;else{let n=this.readStopNodeData(e,c,d+1);if(!n)throw Error(`Unexpected end of ${c}`);o=n.i,t=n.tagContent}let r=new x(s);s!==l&&u&&(r[`:@`]=this.buildAttributesMap(l,i,s)),t&&=this.parseTextData(t,s,i,!0,u,!0,!0),i=i.substr(0,i.lastIndexOf(`.`)),r.add(this.options.textNodeName,t),this.addChild(n,r,i,p)}else{if(l.length>0&&l.lastIndexOf(`/`)===l.length-1){s[s.length-1]===`/`?(s=s.substr(0,s.length-1),i=i.substr(0,i.length-1),l=s):l=l.substr(0,l.length-1),this.options.transformTagName&&(s=this.options.transformTagName(s));let e=new x(s);s!==l&&u&&(e[`:@`]=this.buildAttributesMap(l,i,s)),this.addChild(n,e,i,p),i=i.substr(0,i.lastIndexOf(`.`))}else{let e=new x(s);this.tagsNodeStack.push(n),s!==l&&u&&(e[`:@`]=this.buildAttributesMap(l,i,s)),this.addChild(n,e,i,p),n=e}r=``,o=d}}else r+=e[o];return t.child};function F(e,t,n,r){this.options.captureMetaData||(r=void 0);let i=this.options.updateTag(t.tagname,n,t[`:@`]);!1===i||(typeof i==`string`&&(t.tagname=i),e.addChild(t,r))}let I=function(e){if(this.options.processEntities){for(let t in this.docTypeEntities){let n=this.docTypeEntities[t];e=e.replace(n.regx,n.val)}for(let t in this.lastEntities){let n=this.lastEntities[t];e=e.replace(n.regex,n.val)}if(this.options.htmlEntities)for(let t in this.htmlEntities){let n=this.htmlEntities[t];e=e.replace(n.regex,n.val)}e=e.replace(this.ampEntity.regex,this.ampEntity.val)}return e};function re(e,t,n,r){return e&&=(r===void 0&&(r=t.child.length===0),(e=this.parseTextData(e,t.tagname,n,!1,!!t[`:@`]&&Object.keys(t[`:@`]).length!==0,r))!==void 0&&e!==``&&t.add(this.options.textNodeName,e),``),e}function ie(e,t,n,r){return!(!t||!t.has(r))||!(!e||!e.has(n))}function L(e,t,n,r){let i=e.indexOf(t,n);if(i===-1)throw Error(r);return i+t.length-1}function R(e,t,n,r=`>`){let i=function(e,t,n=`>`){let r,i=``;for(let a=t;a<e.length;a++){let t=e[a];if(r)t===r&&(r=``);else if(t===`"`||t===`'`)r=t;else if(t===n[0]){if(!n[1]||e[a+1]===n[1])return{data:i,index:a}}else t===` `&&(t=` `);i+=t}}(e,t+1,r);if(!i)return;let a=i.data,o=i.index,s=a.search(/\s/),c=a,l=!0;s!==-1&&(c=a.substring(0,s),a=a.substring(s+1).trimStart());let u=c;if(n){let e=c.indexOf(`:`);e!==-1&&(c=c.substr(e+1),l=c!==i.data.substr(e+1))}return{tagName:c,tagExp:a,closeIndex:o,attrExpPresent:l,rawTagName:u}}function ae(e,t,n){let r=n,i=1;for(;n<e.length;n++)if(e[n]===`<`)if(e[n+1]===`/`){let a=L(e,`>`,n,`${t} is not closed`);if(e.substring(n+2,a).trim()===t&&(i--,i===0))return{tagContent:e.substring(r,n),i:a};n=a}else if(e[n+1]===`?`)n=L(e,`?>`,n+1,`StopNode is not closed.`);else if(e.substr(n+1,3)===`!--`)n=L(e,`-->`,n+3,`StopNode is not closed.`);else if(e.substr(n+1,2)===`![`)n=L(e,`]]>`,n,`StopNode is not closed.`)-2;else{let r=R(e,n,`>`);r&&((r&&r.tagName)===t&&r.tagExp[r.tagExp.length-1]!==`/`&&i++,n=r.closeIndex)}}function z(e,t,n){if(t&&typeof e==`string`){let t=e.trim();return t===`true`||t!==`false`&&function(e,t={}){if(t=Object.assign({},O,t),!e||typeof e!=`string`)return e;let n=e.trim();if(t.skipLike!==void 0&&t.skipLike.test(n))return e;if(e===`0`)return 0;if(t.hex&&E.test(n))return function(e){if(parseInt)return parseInt(e,16);if(Number.parseInt)return Number.parseInt(e,16);if(window&&window.parseInt)return window.parseInt(e,16);throw Error(`parseInt, Number.parseInt, window.parseInt are not supported`)}(n);if(n.search(/.+[eE].+/)!==-1)return function(e,t,n){if(!n.eNotation)return e;let r=t.match(k);if(r){let i=r[1]||``,a=r[3].indexOf(`e`)===-1?`E`:`e`,o=r[2],s=i?e[o.length+1]===a:e[o.length]===a;return o.length>1&&s?e:o.length!==1||!r[3].startsWith(`.${a}`)&&r[3][0]!==a?n.leadingZeros&&!s?(t=(r[1]||``)+r[3],Number(t)):e:Number(t)}return e}(e,n,t);{let i=D.exec(n);if(i){let a=i[1]||``,o=i[2],s=((r=i[3])&&r.indexOf(`.`)!==-1&&((r=r.replace(/0+$/,``))===`.`?r=`0`:r[0]===`.`?r=`0`+r:r[r.length-1]===`.`&&(r=r.substring(0,r.length-1))),r),c=a?e[o.length+1]===`.`:e[o.length]===`.`;if(!t.leadingZeros&&(o.length>1||o.length===1&&!c))return e;{let r=Number(n),i=String(r);if(r===0||r===-0)return r;if(i.search(/[eE]/)!==-1)return t.eNotation?r:e;if(n.indexOf(`.`)!==-1)return i===`0`||i===s||i===`${a}${s}`?r:e;let c=o?s:n;return o?c===i||a+c===i?r:e:c===i||c===a+i?r:e}}return e}var r}(e,n)}return e===void 0?``:e}let oe=x.getMetaDataSymbol();function se(e,t){return B(e,t)}function B(e,t,n){let r,i={};for(let a=0;a<e.length;a++){let o=e[a],s=ce(o),c=``;if(c=n===void 0?s:n+`.`+s,s===t.textNodeName)r===void 0?r=o[s]:r+=``+o[s];else{if(s===void 0)continue;if(o[s]){let e=B(o[s],t,c),n=ue(e,t);o[oe]!==void 0&&(e[oe]=o[oe]),o[`:@`]?le(e,o[`:@`],c,t):Object.keys(e).length!==1||e[t.textNodeName]===void 0||t.alwaysCreateTextNode?Object.keys(e).length===0&&(t.alwaysCreateTextNode?e[t.textNodeName]=``:e=``):e=e[t.textNodeName],i[s]!==void 0&&i.hasOwnProperty(s)?(Array.isArray(i[s])||(i[s]=[i[s]]),i[s].push(e)):t.isArray(s,c,n)?i[s]=[e]:i[s]=e}}}return typeof r==`string`?r.length>0&&(i[t.textNodeName]=r):r!==void 0&&(i[t.textNodeName]=r),i}function ce(e){let t=Object.keys(e);for(let e=0;e<t.length;e++){let n=t[e];if(n!==`:@`)return n}}function le(e,t,n,r){if(t){let i=Object.keys(t),a=i.length;for(let o=0;o<a;o++){let a=i[o];r.isArray(a,n+`.`+a,!0,!0)?e[a]=[t[a]]:e[a]=t[a]}}}function ue(e,t){let{textNodeName:n}=t,r=Object.keys(e).length;return r===0||!(r!==1||!e[n]&&typeof e[n]!=`boolean`&&e[n]!==0)}class de{constructor(e){this.externalEntities={},this.options=function(e){return Object.assign({},y,e)}(e)}parse(e,t){if(typeof e!=`string`&&e.toString)e=e.toString();else if(typeof e!=`string`)throw Error(`XML data is accepted in String or Bytes[] form.`);if(t){!0===t&&(t={});let n=s(e,t);if(!0!==n)throw Error(`${n.err.msg}:${n.err.line}:${n.err.col}`)}let n=new ee(this.options);n.addExternalEntities(this.externalEntities);let r=n.parseXml(e);return this.options.preserveOrder||r===void 0?r:se(r,this.options)}addEntity(e,t){if(t.indexOf(`&`)!==-1)throw Error(`Entity value can't have '&'`);if(e.indexOf(`&`)!==-1||e.indexOf(`;`)!==-1)throw Error(`An entity must be set without '&' and ';'. Eg. use '#xD' for '
'`);if(t===`&`)throw Error(`An entity with value '&' is not permitted`);this.externalEntities[e]=t}static getMetaDataSymbol(){return x.getMetaDataSymbol()}}function fe(e,t){let n=``;return t.format&&t.indentBy.length>0&&(n=`
|
|
32003
32003
|
`),pe(e,t,``,n)}function pe(e,t,n,r){let i=``,a=!1;for(let o=0;o<e.length;o++){let s=e[o],c=me(s);if(c===void 0)continue;let l=``;if(l=n.length===0?c:`${n}.${c}`,c===t.textNodeName){let e=s[c];ge(l,t)||(e=t.tagValueProcessor(c,e),e=_e(e,t)),a&&(i+=r),i+=e,a=!1;continue}if(c===t.cdataPropName){a&&(i+=r),i+=`<![CDATA[${s[c][0][t.textNodeName]}]]>`,a=!1;continue}if(c===t.commentPropName){i+=r+`\x3c!--${s[c][0][t.textNodeName]}--\x3e`,a=!0;continue}if(c[0]===`?`){let e=he(s[`:@`],t),n=c===`?xml`?``:r,o=s[c][0][t.textNodeName];o=o.length===0?``:` `+o,i+=n+`<${c}${o}${e}?>`,a=!0;continue}let u=r;u!==``&&(u+=t.indentBy);let d=r+`<${c}${he(s[`:@`],t)}`,f=pe(s[c],t,l,u);t.unpairedTags.indexOf(c)===-1?f&&f.length!==0||!t.suppressEmptyNode?f&&f.endsWith(`>`)?i+=d+`>${f}${r}</${c}>`:(i+=d+`>`,f&&r!==``&&(f.includes(`/>`)||f.includes(`</`))?i+=r+t.indentBy+f+r:i+=f,i+=`</${c}>`):i+=d+`/>`:t.suppressUnpairedNode?i+=d+`>`:i+=d+`/>`,a=!0}return i}function me(e){let t=Object.keys(e);for(let n=0;n<t.length;n++){let r=t[n];if(e.hasOwnProperty(r)&&r!==`:@`)return r}}function he(e,t){let n=``;if(e&&!t.ignoreAttributes)for(let r in e){if(!e.hasOwnProperty(r))continue;let i=t.attributeValueProcessor(r,e[r]);i=_e(i,t),!0===i&&t.suppressBooleanAttributes?n+=` ${r.substr(t.attributeNamePrefix.length)}`:n+=` ${r.substr(t.attributeNamePrefix.length)}="${i}"`}return n}function ge(e,t){let n=(e=e.substr(0,e.length-t.textNodeName.length-1)).substr(e.lastIndexOf(`.`)+1);for(let r in t.stopNodes)if(t.stopNodes[r]===e||t.stopNodes[r]===`*.`+n)return!0;return!1}function _e(e,t){if(e&&e.length>0&&t.processEntities)for(let n=0;n<t.entities.length;n++){let r=t.entities[n];e=e.replace(r.regex,r.val)}return e}let ve={attributeNamePrefix:`@_`,attributesGroupName:!1,textNodeName:`#text`,ignoreAttributes:!0,cdataPropName:!1,format:!1,indentBy:` `,suppressEmptyNode:!1,suppressUnpairedNode:!0,suppressBooleanAttributes:!0,tagValueProcessor:function(e,t){return t},attributeValueProcessor:function(e,t){return t},preserveOrder:!1,commentPropName:!1,unpairedTags:[],entities:[{regex:RegExp(`&`,`g`),val:`&`},{regex:RegExp(`>`,`g`),val:`>`},{regex:RegExp(`<`,`g`),val:`<`},{regex:RegExp(`'`,`g`),val:`'`},{regex:RegExp(`"`,`g`),val:`"`}],processEntities:!0,stopNodes:[],oneListGroup:!1};function ye(e){this.options=Object.assign({},ve,e),!0===this.options.ignoreAttributes||this.options.attributesGroupName?this.isAttribute=function(){return!1}:(this.ignoreAttributesFn=A(this.options.ignoreAttributes),this.attrPrefixLen=this.options.attributeNamePrefix.length,this.isAttribute=Se),this.processTextOrObjNode=be,this.options.format?(this.indentate=xe,this.tagEndChar=`>
|
|
32004
32004
|
`,this.newLine=`
|
|
32005
|
-
`):(this.indentate=function(){return``},this.tagEndChar=`>`,this.newLine=``)}function be(e,t,n,r){let i=this.j2x(e,n+1,r.concat(t));return e[this.options.textNodeName]!==void 0&&Object.keys(e).length===1?this.buildTextValNode(e[this.options.textNodeName],t,i.attrStr,n):this.buildObjectNode(i.val,t,i.attrStr,n)}function xe(e){return this.options.indentBy.repeat(e)}function Se(e){return!(!e.startsWith(this.options.attributeNamePrefix)||e===this.options.textNodeName)&&e.substr(this.attrPrefixLen)}ye.prototype.build=function(e){return this.options.preserveOrder?fe(e,this.options):(Array.isArray(e)&&this.options.arrayNodeName&&this.options.arrayNodeName.length>1&&(e={[this.options.arrayNodeName]:e}),this.j2x(e,0,[]).val)},ye.prototype.j2x=function(e,t,n){let r=``,i=``,a=n.join(`.`);for(let o in e)if(Object.prototype.hasOwnProperty.call(e,o))if(e[o]===void 0)this.isAttribute(o)&&(i+=``);else if(e[o]===null)this.isAttribute(o)||o===this.options.cdataPropName?i+=``:o[0]===`?`?i+=this.indentate(t)+`<`+o+`?`+this.tagEndChar:i+=this.indentate(t)+`<`+o+`/`+this.tagEndChar;else if(e[o]instanceof Date)i+=this.buildTextValNode(e[o],o,``,t);else if(typeof e[o]!=`object`){let n=this.isAttribute(o);if(n&&!this.ignoreAttributesFn(n,a))r+=this.buildAttrPairStr(n,``+e[o]);else if(!n)if(o===this.options.textNodeName){let t=this.options.tagValueProcessor(o,``+e[o]);i+=this.replaceEntitiesValue(t)}else i+=this.buildTextValNode(e[o],o,``,t)}else if(Array.isArray(e[o])){let r=e[o].length,a=``,s=``;for(let c=0;c<r;c++){let r=e[o][c];if(r!==void 0)if(r===null)o[0]===`?`?i+=this.indentate(t)+`<`+o+`?`+this.tagEndChar:i+=this.indentate(t)+`<`+o+`/`+this.tagEndChar;else if(typeof r==`object`)if(this.options.oneListGroup){let e=this.j2x(r,t+1,n.concat(o));a+=e.val,this.options.attributesGroupName&&r.hasOwnProperty(this.options.attributesGroupName)&&(s+=e.attrStr)}else a+=this.processTextOrObjNode(r,o,t,n);else if(this.options.oneListGroup){let e=this.options.tagValueProcessor(o,r);e=this.replaceEntitiesValue(e),a+=e}else a+=this.buildTextValNode(r,o,``,t)}this.options.oneListGroup&&(a=this.buildObjectNode(a,o,s,t)),i+=a}else if(this.options.attributesGroupName&&o===this.options.attributesGroupName){let t=Object.keys(e[o]),n=t.length;for(let i=0;i<n;i++)r+=this.buildAttrPairStr(t[i],``+e[o][t[i]])}else i+=this.processTextOrObjNode(e[o],o,t,n);return{attrStr:r,val:i}},ye.prototype.buildAttrPairStr=function(e,t){return t=this.options.attributeValueProcessor(e,``+t),t=this.replaceEntitiesValue(t),this.options.suppressBooleanAttributes&&t===`true`?` `+e:` `+e+`="`+t+`"`},ye.prototype.buildObjectNode=function(e,t,n,r){if(e===``)return t[0]===`?`?this.indentate(r)+`<`+t+n+`?`+this.tagEndChar:this.indentate(r)+`<`+t+n+this.closeTag(t)+this.tagEndChar;{let i=`</`+t+this.tagEndChar,a=``;return t[0]===`?`&&(a=`?`,i=``),!n&&n!==``||e.indexOf(`<`)!==-1?!1!==this.options.commentPropName&&t===this.options.commentPropName&&a.length===0?this.indentate(r)+`\x3c!--${e}--\x3e`+this.newLine:this.indentate(r)+`<`+t+n+a+this.tagEndChar+e+this.indentate(r)+i:this.indentate(r)+`<`+t+n+a+`>`+e+i}},ye.prototype.closeTag=function(e){let t=``;return this.options.unpairedTags.indexOf(e)===-1?t=this.options.suppressEmptyNode?`/`:`></${e}`:this.options.suppressUnpairedNode||(t=`/`),t},ye.prototype.buildTextValNode=function(e,t,n,r){if(!1!==this.options.cdataPropName&&t===this.options.cdataPropName)return this.indentate(r)+`<![CDATA[${e}]]>`+this.newLine;if(!1!==this.options.commentPropName&&t===this.options.commentPropName)return this.indentate(r)+`\x3c!--${e}--\x3e`+this.newLine;if(t[0]===`?`)return this.indentate(r)+`<`+t+n+`?`+this.tagEndChar;{let i=this.options.tagValueProcessor(t,e);return i=this.replaceEntitiesValue(i),i===``?this.indentate(r)+`<`+t+n+this.closeTag(t)+this.tagEndChar:this.indentate(r)+`<`+t+n+`>`+i+`</`+t+this.tagEndChar}},ye.prototype.replaceEntitiesValue=function(e){if(e&&e.length>0&&this.options.processEntities)for(let t=0;t<this.options.entities.length;t++){let n=this.options.entities[t];e=e.replace(n.regex,n.val)}return e};let Ce={validate:s};t.exports=n})()})),cW=s((e=>{var t=Object.create,n=Object.defineProperty,r=Object.getOwnPropertyDescriptor,i=Object.getOwnPropertyNames,a=Object.getPrototypeOf,o=Object.prototype.hasOwnProperty,s=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),c=(e,t,a,s)=>{if(t&&typeof t==`object`||typeof t==`function`)for(var c=i(t),l=0,u=c.length,d;l<u;l++)d=c[l],!o.call(e,d)&&d!==a&&n(e,d,{get:(e=>t[e]).bind(null,d),enumerable:!(s=r(t,d))||s.enumerable});return e},l=(e,r,i)=>(i=e==null?{}:t(a(e)),c(r||!e||!e.__esModule?n(i,`default`,{value:e,enumerable:!0}):i,e));let u=l(Oi()),f=l(ki()),p=l(require(`node:fs/promises`)),m=l(require(`node:async_hooks`)),h=l(se()),g=l(Bi()),_=l(Rc()),v=l((Ol(),d(ll))),y=l(require(`node:crypto`)),b=l(iR()),x=l(pM()),S=l(fz()),C=l((Dj(),d(Ej))),w=l(require(`node:fs`)),T=l(Uz()),E=l(pV()),D=l(require(`node:child_process`)),O=l(require(`node:util`)),k=l(require(`@prisma/internals`)),A=l(lV()),ee=l(require(`node:zlib`)),j=l(cH()),te=l(uH()),M=l(mH()),ne=l(Eee()),N=l(require(`node:os`)),P=l(require(`node:events`)),F=l(gU()),I=l(tW()),re=l(Fee()),ie=l(oW()),L=l(sW()),R=l(_U()),ae=l(require(`node:process`));l(require(`node:readline`)),l(require(`node:tty`));let z=l(require(`node:path`)),oe=l(require(`@anthropic-ai/claude-agent-sdk`)),B={DELETE:`delete`,COMMENT_OUT:`comment out`,KEEP:`keep`,SKIP:`skip`},ce={GREEN:`Green`,GREY:`Grey`,RED:`Red`,NA:`NA`},le={GREEN:`Green`,GREY:`Grey`,RUNTIME_ERROR:`RuntimeError`},ue=function(e){return e.IDE=`IDE`,e.CLI=`CLI`,e}({}),de=function(e){return e.SIBLING_FOLDER=`siblingFolder`,e.ROOT_FOLDER=`rootFolder`,e}({}),fe=function(e){return e.JEST=`jest`,e.MOCHA=`mocha`,e.VITEST=`vitest`,e.PYTEST=`pytest`,e}({}),pe=function(e){return e.SPEC=`spec`,e.TEST=`test`,e}({}),me=function(e){return e.CAMEL_CASE=`camelCase`,e.KEBAB_CASE=`kebabCase`,e}({}),he=function(e){return e.NONE=`none`,e.CATEGORIES=`categories`,e}({}),ge=function(e){return e.NEW_CODE_FILE=`newCodeFile`,e.OVERRIDE_CODE_FILE=`overrideCodeFile`,e}({}),_e=function(e){return e.ON=`on`,e.OFF=`off`,e}({}),ve={DEFAULT:0,MIN:0,MAX:100},ye={DEFAULT:5,MIN:1,MAX:50};u.z.object({rootPath:u.z.string().default(process.cwd()),testStructure:u.z.enum(de).optional(),testFramework:u.z.enum(fe).optional(),testSuffix:u.z.enum(pe).optional(),testFileName:u.z.enum(me).optional(),calculateCoverage:u.z.enum(_e).optional(),coverageThreshold:u.z.number().min(ve.MIN).max(ve.MAX).default(ve.DEFAULT),requestSource:u.z.enum(ue).optional(),concurrency:u.z.number().min(ye.MIN).max(ye.MAX).default(ye.DEFAULT),backendURL:u.z.string().optional(),secretToken:u.z.string().optional(),modelName:u.z.string().optional(),context:u.z.object({git:u.z.object({ref_name:u.z.string(),repository:u.z.string(),owner:u.z.string(),sha:u.z.string(),workflowRunId:u.z.string(),remoteUrl:u.z.string(),topLevel:u.z.string()}).partial().optional()}).optional(),testCommand:u.z.string().optional(),coverageCommand:u.z.string().optional(),lintCommand:u.z.string().optional(),prettierCommand:u.z.string().optional(),disableLintRules:u.z.boolean().optional(),ignoreAsAnyLintErrors:u.z.boolean().optional(),includeEarlyTests:u.z.boolean().optional(),greyTestBehaviour:u.z.enum(B).optional(),redTestBehaviour:u.z.enum(B).optional(),keepErrorTests:u.z.boolean().optional(),keepFailedTests:u.z.boolean().optional(),conditionalKeep:u.z.boolean().optional(),continueOnTestErrors:u.z.boolean().optional(),perFunctionTimeout:u.z.number().positive().optional(),dynamicPromptIterations:u.z.number().min(0).max(10).optional(),removeComments:u.z.boolean().optional(),experimentalAgentSdk:u.z.boolean().optional(),agentSdkModel:u.z.string().optional(),agentSdkBudget:u.z.number().positive().optional(),debug:u.z.boolean().optional(),verbose:u.z.boolean().optional(),progressLogger:u.z.custom().optional()});var be=`@earlyai/ts-agent`,xe=`0.74.2`;let Se={VSCODE:`vscode`,GITHUB_ACTION:`github-action`,UNKNOWN:`unknown`},Ce=`$early_filename`,we=`$early_coverage_dir`,Te=`npx jest ${Ce} --no-coverage --silent --json --forceExit --maxWorkers=1`,Ee=`npx --no eslint ${Ce}`,De=`npx --no prettier ${Ce} --write`,Oe={rootPath:process.cwd(),isSiblingFolderStructured:!0,gitURL:`https://github.com/your-owner/your-repo`,testFramework:fe.JEST,greyTestBehaviour:B.DELETE,redTestBehaviour:B.DELETE,keepErrorTests:!1,keepFailedTests:!1,conditionalKeep:!1,continueOnTestErrors:!0,generatedTestStructure:he.CATEGORIES,isRootFolderStructured:!1,clientSource:Se.GITHUB_ACTION,backendURL:`https://api.startearly.ai`,requestSource:ue.CLI,userPrompt:``,testLocation:`__tests__`,coverageThreshold:ve.DEFAULT,concurrency:5,testFileFormat:`ts`,outputType:ge.NEW_CODE_FILE,shouldRefreshCoverage:!0,kebabCaseFileName:!1,earlyTestFilenameSuffix:`.early.${pe.TEST}`,testSuffix:pe.TEST,isAppendPrompt:!1,dynamicPromptIterations:3,wsServerEndpoint:`wss://api.startearly.ai`,secretToken:``,loggerConfig:{consoleEnabled:!1,azureEnabled:!0,azureConnectionString:`InstrumentationKey=8b9b0d6a-5400-44a3-ada6-3cd026de6cfe;IngestionEndpoint=https://eastus-8.in.applicationinsights.azure.com/;LiveEndpoint=https://eastus.livediagnostics.monitor.azure.com/;ApplicationId=d6e130b6-4aaa-4dcc-8d26-c1fa25d4656a`},context:void 0,includeEarlyTests:!1,lintCommand:Ee,prettierCommand:De,disableLintRules:!1,ignoreAsAnyLintErrors:!0,allowUndefinedLintErrors:!0,perFunctionTimeout:24e4,removeComments:!0,experimentalAgentSdk:!1,agentSdkModel:void 0,agentSdkBudget:void 0,debug:!1,verbose:!1},ke=e=>{let t=`testFramework.testSuffix.backendURL.requestSource.secretToken.concurrency.coverageThreshold.context.rootPath.testCommand.coverageCommand.lintCommand.prettierCommand.disableLintRules.greyTestBehaviour.redTestBehaviour.keepErrorTests.keepFailedTests.conditionalKeep.continueOnTestErrors.perFunctionTimeout.dynamicPromptIterations.removeComments.experimentalAgentSdk.agentSdkModel.agentSdkBudget.debug.verbose.progressLogger`.split(`.`).reduce((t,n)=>(0,h.isDefined)(e[n])?{...t,[n]:e[n]}:t,{}),n={...(0,h.isDefined)(e.testStructure)&&{isSiblingFolderStructured:e.testStructure===de.SIBLING_FOLDER,isRootFolderStructured:e.testStructure===de.ROOT_FOLDER},...(0,h.isDefined)(e.testFileName)&&{kebabCaseFileName:e.testFileName===me.KEBAB_CASE},...(0,h.isDefined)(e.calculateCoverage)&&{shouldRefreshCoverage:e.calculateCoverage===_e.ON},...(0,h.isDefined)(e.modelName)&&{fixTestsLLMModelName:e.modelName,generateTestsLLMModelName:e.modelName},...(0,h.isDefined)(e.testSuffix)&&{earlyTestFilenameSuffix:`.early.${e.testSuffix}`},...(0,h.isDefined)(e.requestSource)&&{clientSource:e.requestSource===ue.IDE?Se.VSCODE:Se.GITHUB_ACTION}};return{...t,...n}},Ae=new v.Chalk({level:1}),je=()=>{},Me={info:je,verbose:je,debug:je},Ne=[Ae.cyan,Ae.magenta,Ae.green,Ae.blue,Ae.redBright,Ae.cyanBright,Ae.magentaBright,Ae.greenBright];function Pe(e){let t=2166136261;for(let n=0;n<e.length;n++)t^=e.codePointAt(n)??0,t=Math.imul(t,16777619);return Ne[Math.abs(t)%Ne.length]}function Fe(e,t){let n=(0,h.isDefined)(t.parentName)?`${t.parentName}.${t.methodName}`:t.methodName,r=Pe(n)(`[${n}]`);return{info:(...t)=>e.info(r,...t),verbose:(...t)=>e.verbose(r,...t),debug:(...t)=>e.debug(r,...t)}}var Ie=s(((e,t)=>{function n(e,t){if(typeof Reflect==`object`&&typeof Reflect.metadata==`function`)return Reflect.metadata(e,t)}t.exports=n,t.exports.__esModule=!0,t.exports.default=t.exports})),Le=s(((e,t)=>{function n(e,t,n,r){var i=arguments.length,a=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r,o;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)a=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(o=e[s])&&(a=(i<3?o(a):i>3?o(t,n,a):o(t,n))||a);return i>3&&a&&Object.defineProperty(t,n,a),a}t.exports=n,t.exports.__esModule=!0,t.exports.default=t.exports})),Re=l(Ie()),ze=l(Le()),Be,Ve;let He=class{config;constructor(e,t={}){if(!(0,h.isDefined)(e)){this.config=Oe;return}let n=ke(e);this.config=(0,h.merge)(Oe,n,t)}getRootPath=()=>this.config.rootPath;isSiblingFolderStructured=()=>this.config.isSiblingFolderStructured;getGitURL=()=>this.config.context?.git?.remoteUrl??this.config.gitURL;getGitTopLevel=()=>this.config.context?.git?.topLevel??this.getRootPath();getTestFramework=()=>this.config.testFramework;getGreyTestBehaviour=()=>this.config.greyTestBehaviour;getRedTestBehaviour=()=>this.config.redTestBehaviour;shouldKeepErrorTests=()=>this.config.keepErrorTests;shouldKeepFailedTests=()=>this.config.keepFailedTests;shouldConditionalKeep=()=>this.config.conditionalKeep;getGeneratedTestStructure=()=>this.config.generatedTestStructure;getGenerateTestsLLMModelName=()=>this.config.generateTestsLLMModelName;isRootFolderStructured=()=>this.config.isRootFolderStructured;getLLMTemperature=()=>this.config.llmTemperature;getLLMTopP=()=>this.config.llmTopP;getClientSource=()=>this.config.clientSource;getBackendURL=()=>this.config.backendURL;getRequestSource=()=>this.config.requestSource;getUserPrompt=()=>this.config.userPrompt;getTestLocation=()=>this.config.testLocation;getCoverageThreshold=()=>this.config.coverageThreshold;getConcurrency=()=>this.config.concurrency;getTestFileFormat=()=>this.config.testFileFormat;getOutputType=()=>this.config.outputType;getShouldRefreshCoverage=()=>this.config.shouldRefreshCoverage;isKebabCaseFileName=()=>this.config.kebabCaseFileName;getEarlyTestFilenameSuffix=()=>this.config.earlyTestFilenameSuffix;getTestSuffix=()=>this.config.testSuffix;getIsAppendPrompt=()=>this.config.isAppendPrompt;getFixTestsLLMModelName=()=>this.config.fixTestsLLMModelName;getDynamicPromptIterations=()=>this.config.dynamicPromptIterations;getWSServerEndpoint=()=>this.config.backendURL.replace(`http://`,`ws://`).replace(`https://`,`wss://`);getAnthropicProxyUrl=()=>new URL(`/anthropic`,this.config.backendURL).href;getSecretToken=()=>this.config.secretToken;getLoggerConfig=()=>this.config.loggerConfig;getContext=()=>this.config.context;getTestCommand=()=>this.config.testCommand;getCoverageCommand=()=>this.config.coverageCommand;getLintCommand=()=>this.config.lintCommand;getPrettierCommand=()=>this.config.prettierCommand;shouldDisableLintRules=()=>this.config.disableLintRules;shouldIgnoreAsAnyLintErrors=()=>this.config.ignoreAsAnyLintErrors;allowUndefinedLintErrors=()=>this.config.allowUndefinedLintErrors;getIncludeEarlyTests=()=>this.config.includeEarlyTests??!1;shouldContinueOnTestErrors=()=>this.config.continueOnTestErrors;getPerFunctionTimeout=()=>this.config.perFunctionTimeout;shouldRemoveComments=()=>this.config.removeComments;getExperimentalAgentSdk=()=>this.config.experimentalAgentSdk;getAgentSdkModel=()=>this.config.agentSdkModel;getAgentSdkBudget=()=>this.config.agentSdkBudget;updateContext=e=>{this.config.context=(0,h.merge)(this.config.context??{},e??{})};updateRootPath=e=>{this.config.rootPath=e};isDebug=()=>this.config.debug??!1;isVerbose=()=>this.config.verbose??!1;getProgressLogger=e=>{let t=this.config.progressLogger??Me;return(0,h.isDefined)(e)?Fe(t,e):t}};He=(0,ze.default)([(0,_.injectable)(`Singleton`),(0,Re.default)(`design:paramtypes`,[typeof(Be=typeof Partial<`u`&&Partial)==`function`?Be:Object,typeof(Ve=typeof Partial<`u`&&Partial)==`function`?Ve:Object])],He);var V=new _.Container({autobind:!0,defaultScope:`Singleton`});let Ue=()=>V.get(He);var We=class{storage=new m.AsyncLocalStorage;isConsoleEnabled;constructor(e){this.isConsoleEnabled=e}orderedFlush={nextOrder:1,pending:new Map};resetOrder(){this.orderedFlush={nextOrder:1,pending:new Map}}async withBufferedPrinting(e,t){let n=[];try{return await this.storage.run(n,e)}finally{this.flushInOrder(t,n)}}printOrBuffer(e,t){let n=this.storage.getStore();if((0,h.isDefined)(n)){n.push({method:e,message:t});return}this.isConsoleEnabled&&console[e](t)}async flushInOrder(e,t){if(this.orderedFlush.nextOrder===e){this.flushBuffer(t),this.orderedFlush.nextOrder++,this.drainPendingFlushes();return}return new Promise(n=>{this.orderedFlush.pending.set(e,{buffer:t,resolve:n})})}drainPendingFlushes(){let e=this.orderedFlush.pending.get(this.orderedFlush.nextOrder);for(;(0,h.isDefined)(e);)this.orderedFlush.pending.delete(this.orderedFlush.nextOrder),this.flushBuffer(e.buffer),this.orderedFlush.nextOrder++,e.resolve(),e=this.orderedFlush.pending.get(this.orderedFlush.nextOrder)}flushBuffer(e){if(this.isConsoleEnabled)for(let t of e)console[t.method](t.message)}};let Ge=function(e){return e.DEFAULT=`default`,e.VERBOSE=`verbose`,e.DEBUG=`debug`,e}({}),Ke=function(e){return e.INFO=`info`,e.WARN=`warn`,e}({});function qe(){return(0,y.randomUUID)()}function Je(){let e=``;for(let t=0;t<8;t++)e+=`abcdefghijklmnopqrstuvwxyz0123456789`.charAt(Math.floor(Math.random()*36));return e}var Ye=l(Ie()),Xe=l(Le()),Ze=class{export(e,t){for(let t of e){let e=t.body;if((0,h.isString)(e))console.info(e);else try{console.info(JSON.stringify(e))}catch{console.info(String(e))}}t({code:0})}shutdown(){return Promise.resolve()}};let Qe=class{loggerProvider;config;constructor(e){this.config=e,this.loggerProvider=new S.LoggerProvider({resource:(0,x.resourceFromAttributes)({[C.ATTR_SERVICE_NAME]:be,[C.ATTR_SERVICE_VERSION]:xe})}),this.initializeExporters(),this.setGlobalLoggerProvider()}getLogger(e){return this.loggerProvider.getLogger(e)}initializeExporters(){let e=[];if(this.config.consoleEnabled){let t=new Ze;e.push(new S.SimpleLogRecordProcessor(t))}if(this.config.azureEnabled&&(0,h.isDefined)(this.config.azureConnectionString)){let t=new b.AzureMonitorLogExporter({connectionString:this.config.azureConnectionString});e.push(new S.BatchLogRecordProcessor(t))}this.loggerProvider=new S.LoggerProvider({processors:e})}setGlobalLoggerProvider(){g.logs.setGlobalLoggerProvider(this.loggerProvider)}};Qe=(0,Xe.default)([(0,_.injectable)(),(0,Ye.default)(`design:paramtypes`,[Object])],Qe),l(Ie()),l(Le());let H=new class{storage;otelService;otelLogger;isConsoleEnabled;printBuffer;default=this.createLogObject(Ge.DEFAULT);verbose=this.createLogObject(Ge.VERBOSE);constructor(e){this.storage=new m.AsyncLocalStorage,this.otelService=new Qe(e),this.otelLogger=this.otelService.getLogger(`ts-agent`),this.isConsoleEnabled=e.consoleEnabled,this.printBuffer=new We(e.consoleEnabled)}resetPrintOrder(){this.printBuffer.resetOrder()}async withBufferedPrinting(e,t){return this.printBuffer.withBufferedPrinting(e,t)}info={startLog:(e,...t)=>this.log(g.SeverityNumber.INFO,`Start ${e}`,...t),endLog:(e,...t)=>this.log(g.SeverityNumber.INFO,`End ${e}`,...t),failedLog:(e,...t)=>this.log(g.SeverityNumber.INFO,`Failed ${e}`,...t),defaultLog:(e,...t)=>this.log(g.SeverityNumber.INFO,e,...t)};debug={startLog:(e,...t)=>this.log(g.SeverityNumber.DEBUG,`Start ${e}`,...t),endLog:(e,...t)=>this.log(g.SeverityNumber.DEBUG,`End ${e}`,...t),failedLog:(e,...t)=>this.log(g.SeverityNumber.DEBUG,`Failed ${e}`,...t),defaultLog:(e,...t)=>this.log(g.SeverityNumber.DEBUG,e,...t)};error(e,t,...n){let r=t instanceof Error?`${e} ${t.message} ${t.stack}`:`${e} ${JSON.stringify(t)}`;this.log(g.SeverityNumber.ERROR,r,...n)}getRequestId(){return this.storage.getStore()?.requestId??``}getTraceId(){return this.storage.getStore()?.traceId??``}log(e,t,...n){let r=this.formatMessage(t,...n);this.logToOpenTelemetry(e,r),!(!this.isConsoleEnabled||!this.isLevelEnabled(Ge.DEBUG))&&console.info(r)}logToOpenTelemetry(e,t){let n=this.storage.getStore(),r={service:be,version:xe};(0,h.isDefined)(n)&&((0,h.isDefined)(n.traceId)&&(r.traceId=n.traceId),(0,h.isDefined)(n.requestId)&&(r.requestId=n.requestId),(0,h.isDefined)(n.category)&&(r.category=n.category),(0,h.isDefined)(n.subCategory)&&(r.subCategory=n.subCategory),(0,h.isDefined)(n.testedMethodClass)&&(r.testedMethodClass=n.testedMethodClass),(0,h.isDefined)(n.testedFunction)&&(r.testedFunction=n.testedFunction),(0,h.isDefined)(n.userId)&&(r.userId=n.userId.toString())),this.otelLogger.emit({severityNumber:e,severityText:this.getSeverityText(e),body:t,attributes:r})}getSeverityText(e){switch(e){case g.SeverityNumber.TRACE:return`TRACE`;case g.SeverityNumber.DEBUG:return`DEBUG`;case g.SeverityNumber.INFO:return`INFO`;case g.SeverityNumber.WARN:return`WARN`;case g.SeverityNumber.ERROR:return`ERROR`;case g.SeverityNumber.FATAL:return`FATAL`;default:return`INFO`}}formatMessage(e,...t){let n=this.formatPrefix(),r=(0,h.isDefined)(n)?`${n} ${e}`:e;return this.formatPrint(r,...t)}formatPrint(e,...t){return(0,h.isEmpty)(t)?e:`${e} ${t.map(e=>JSON.stringify(e)).join(` `)}`}withContext=(e,t,n)=>{let r=n.value,i=this.storage;return n.value=function(...e){let t=i.getStore();if(t){let n={...t};return i.run(n,()=>r.apply(this,e))}let n={traceId:Je(),requestId:qe()};return i.run(n,()=>r.apply(this,e))},n};addContext(e){let t=this.storage.getStore();(0,h.isDefined)(t)&&(t.category=e.category??t.category,t.subCategory=e.subCategory??t.subCategory,t.testedMethodClass=e.testedMethodClass??t.testedMethodClass,t.testedFunction=e.testedFunction??t.testedFunction,t.userId=e.userId??t.userId)}captureContext({withNewRequestId:e=!1}={}){let t=this.storage.getStore();return t?{...t,...e&&{requestId:qe()}}:void 0}async runWithContext(e,t){return(0,h.isDefined)(e)?this.storage.run(e,t):t()}isLevelEnabled(e){switch(e){case Ge.DEFAULT:return!0;case Ge.VERBOSE:return Ue().isVerbose()||Ue().isDebug();case Ge.DEBUG:return Ue().isDebug()}}createLogObject(e){return{info:(t,...n)=>{this.isLevelEnabled(e)&&this.printOrBuffer(Ke.INFO,this.formatPrint(t,...n))},warn:(t,...n)=>{this.isLevelEnabled(e)&&this.printOrBuffer(Ke.WARN,this.formatPrint(t,...n))}}}printOrBuffer(e,t){this.printBuffer.printOrBuffer(e,t)}formatPrefix(){let e=this.storage.getStore();if(!(0,h.isDefined)(e))return``;let t=[];return(0,h.isDefined)(e.traceId)&&t.push(`[${e.traceId}]`),(0,h.isDefined)(e.requestId)&&t.push(`[${e.requestId}]`),(0,h.isDefined)(e.category)&&t.push(`[${e.category}]`),(0,h.isDefined)(e.subCategory)&&t.push(`[${e.subCategory}]`),(0,h.isDefined)(e.testedMethodClass)&&t.push(`[${e.testedMethodClass}]`),(0,h.isDefined)(e.testedFunction)&&t.push(`[${e.testedFunction}]`),t.join(` `)}}({consoleEnabled:!1,azureEnabled:!0,azureConnectionString:`InstrumentationKey=c18a3332-f844-498f-98e0-d818996cf526;IngestionEndpoint=https://eastus2-3.in.applicationinsights.azure.com/;LiveEndpoint=https://eastus2.livediagnostics.monitor.azure.com/;ApplicationId=2150ffe0-cb0f-4b00-9562-d3385b383d74`});function $e(e){return function(t,n,r){return(0,h.isDefined)(e)&&H.addContext(e),H.withContext(t,n,r)}}var et=class e{rootPath;absolutePath;static EARLY_FILENAME_VAR=`$early_filename`;constructor(e){this.rootPath=f.default.normalizeTrim(Ue().getRootPath());let t=f.default.normalizeTrim(e),n=f.default.normalizeTrim(this.rootPath);if(t===n||t.startsWith(n+f.default.sep))this.absolutePath=t;else{let e=t.replace(/^\//,``);this.absolutePath=f.default.resolve(this.rootPath,e)}}static fromSourceFile(t){let n=f.default.normalizeTrim(t.getFilePath());return new e(f.default.relative(f.default.normalizeTrim(Ue().getRootPath()),n))}static fromAbsolutePath(t){let n=f.default.normalizeTrim(t);return new e(f.default.relative(f.default.normalizeTrim(Ue().getRootPath()),n))}static fromRelativePath(t){return new e(t)}getRelativeFilePath(){return f.default.relative(this.rootPath,this.absolutePath)}getAbsoluteFilePath(){return this.absolutePath}async isFileExists(){try{return(await p.default.stat(this.absolutePath)).isFile()}catch{return!1}}async isDirectoryExists(){try{return(await p.default.stat(this.absolutePath)).isDirectory()}catch{return!1}}async createDirectory(e){await p.default.mkdir(this.absolutePath,{recursive:e?.recursive??!0})}async getText(){try{return await p.default.readFile(this.absolutePath,`utf8`)}catch{return``}}async upsert(e){let t=f.default.dirname(this.absolutePath);await p.default.mkdir(t,{recursive:!0}),await(await this.isFileExists()?p.default.appendFile(this.absolutePath,e):p.default.writeFile(this.absolutePath,e)),H.info.defaultLog(`Upserted file`,{path:this.getRelativeFilePath()})}async replace(e){let t=f.default.dirname(this.absolutePath);await p.default.mkdir(t,{recursive:!0}),await p.default.writeFile(this.absolutePath,e),H.info.defaultLog(`Replaced file`,{path:this.getRelativeFilePath()})}async delete(){try{await p.default.unlink(this.absolutePath),H.info.defaultLog(`Deleted file`,{path:this.getRelativeFilePath()})}catch{}}};let tt={WIN32:`win32`,DARWIN:`darwin`,LINUX:`linux`},nt={JAVASCRIPT:`javascript`,TYPESCRIPT:`typescript`,PYTHON:`python`},rt=e=>{let t=Ue().getRootPath();return f.default.resolve(t,e)},it=e=>{let t=Ue().getRootPath(),n=f.default.normalize(e);return f.default.relative(t,n)},at=e=>({".js":`javascript`,".mjs":`javascript`,".cjs":`javascript`,".jsx":`javascript`,".ts":`typescript`,".tsx":`typescript`,".py":`python`})[e.toLowerCase()]??`javascript`;function ot(e){return at((0,f.extname)(e))}function st(e){return at((0,f.extname)(e))===`typescript`}function U(e){return at((0,f.extname)(e))===nt.PYTHON}function ct(e){let t=Ue().getRootPath();if(!(0,h.isDefined)(t))throw Error(`Workspace root path is not defined`);if((0,h.isEmpty)(e))return f.default.normalize(t);let n=f.default.normalize(t),r=f.default.normalize(e);if(process.platform===tt.WIN32){let t=n.split(`:`)[0].toUpperCase(),i=r.split(`:`)[0].toUpperCase();if(t!==i&&!i.startsWith(t))return e}return f.default.relative(n,r)}function lt(e){return e.startsWith(`../`)?`../${e}`:e.startsWith(`./`)?`.${e}`:e}function ut(e){let t=f.default.normalize(rt(e)),n=f.default.normalize((0,T.default)([`package.json`,`project.json`],{cwd:t})??``);if(!n)return``;let r=it((0,f.dirname)(n));return r.startsWith(`/`)?r.slice(1):r}function dt(e,t,n){if(!pt(e))return e;let r=n===``?t:t.replace(n,``),i=n===``?ht(r):mt(r),a=r.split(`/`).slice(0,-1),o=ft(e,`../`),s=o>0?a.slice(0,-o).join(`/`):(0,f.dirname)(r),c=e.replaceAll(`../`,``).replaceAll(`./`,``);return f.default.join(i,s,c)}function ft(e,t){return e.split(t).length-1}function pt(e){return e.startsWith(`../`)||e.startsWith(`./`)}function mt(e){let t=ft(e,`/`);return`../`.repeat(t-1)}function ht(e){let t=ft(e,`/`);return`../`.repeat(t+1)}function gt(e){return e?.includes(`node_modules/`)}let _t=e=>e.replaceAll(/[.*+?^${}()|[\]\\]/g,String.raw`\$&`);function vt(e,t){let n=f.default.isAbsolute(e)?e:rt(e);return(0,T.default)(t,{cwd:n})}function yt(e,t){let n=vt(e,t);if(!(0,h.isDefined)(n))return;let r=w.readFileSync(n,`utf8`);return JSON.parse(r)}function bt(e){return yt(e,`package.json`)}function xt(e,t){let{dependencies:n={},devDependencies:r={}}=e;return Object.keys({...r,...n}).includes(t)}let St=[{path:`eslint.config.js`,isFlat:!0},{path:`eslint.config.cjs`,isFlat:!0},{path:`eslint.config.mjs`,isFlat:!0},{path:`eslint.config.ts`,isFlat:!0},{path:`eslint.config.mts`,isFlat:!0},{path:`eslint.config.cts`,isFlat:!0},{path:`.eslintrc`,isFlat:!1},{path:`.eslintrc.js`,isFlat:!1},{path:`.eslintrc.cjs`,isFlat:!1},{path:`.eslintrc.mjs`,isFlat:!1},{path:`.eslintrc.json`,isFlat:!1},{path:`.eslintrc.yaml`,isFlat:!1},{path:`.eslintrc.yml`,isFlat:!1}],Ct=[`@typescript-eslint/no-undefined`,`unicorn/no-useless-undefined`,`no-undefined`];async function wt(e){for(let{path:t,isFlat:n}of St){let r=f.default.join(e,t);if(await et.fromAbsolutePath(r).isFileExists())return{path:r,isFlat:n}}return bt(e)?.eslint?{path:vt(e,`package.json`),isFlat:!1}:{path:null,isFlat:!1}}let Tt={GET_TESTABLES:`get-testables`,GET_COVERAGE:`get-coverage`,GENERATE_COVERAGE:`generate-coverage`,SET_COVERAGE:`set-coverage`,GENERATE_TESTS:`generate-tests`,INITIALIZATION:`initialization`,GET_TESTED_CODE_DATA_SOURCE:`get-tested-code-data-source`,DYNAMIC_PROMPT:`dynamic-prompt`,TEST_VALIDATION:`test-validation`},Et={CODE_EXTRACTOR:`code-extractor`,CODE_REFINEMENT:`code-refinement`,TEST_MANAGEMENT:`test-management`,TEST_VALIDATOR:`test-validator`,CONFIG_FILE:`config-file`,COMMAND_EXECUTION:`command-execution`},Dt=[`.jsx`,`.tsx`],Ot=[`it`,`test`,`it.each`,`test.each`],kt=function(e){return e.Default=`default`,e.ObjectDefault=`object-default`,e.Named=`named`,e.Unknown=`unknown`,e.NotExported=`not-exported`,e}({}),At=function(e){return e.PRIVATE=`private`,e.PROTECTED=`protected`,e.PUBLIC=`public`,e}({}),jt=function(e){return e.REACT=`react`,e.ANGULAR=`angular`,e}({}),Mt=`unknown`,Nt=(0,O.promisify)(D.default.exec);async function Pt(e,{cwd:t=Ue().getRootPath(),timeout:n=1e4}={}){return(await Nt(e,{cwd:t,maxBuffer:500*1024,timeout:n}))?.stdout?.toString()??``}let Ft=e=>{let t=rt(e);return(0,T.default)(`jest.config.+(js|ts|mjs|cjs|json)`,{cwd:t})},It=e=>(0,h.isObject)(e)&&(0,h.isString)(e.rootDir),Lt=async e=>{let t;if(H.addContext({subCategory:Et.CONFIG_FILE}),(0,h.isDefined)(e)){let n=Ft(e);n!==null&&(t=(0,f.dirname)(n))}t??=Ue().getRootPath();let n;try{if(n=await Pt(`npx jest --showConfig`,{cwd:t}),!(0,h.isString)(n))throw H.info.defaultLog(`Jest config return is not a string`,n),Error(`Jest config return is not a string`);let e=JSON.parse(n);if((0,h.isObject)(e)&&(0,h.isArray)(e.configs)&&e.configs.every(e=>It(e)))return{projectConfigs:e.configs,globalConfig:e.globalConfig,configs:e.configs}}catch(e){H.info.defaultLog(`Cannot read jest config`,(0,h.getErrorMessage)(e)),H.info.defaultLog(`Failed reading jest config`,e,(0,h.getErrorMessage)(e));return}H.info.defaultLog(`Invalid jest config or config in not supported format`)},Rt=async()=>{let e=[Ue().getRootPath()],t=f.default.join(`node_modules`,`.prisma`,`client`,`index.d.ts`),n=e.map(e=>f.default.join(e,t)).map(e=>et.fromAbsolutePath(e));return(await(0,h.filterAsync)(n,e=>e.isFileExists())).map(e=>e.getAbsoluteFilePath())},zt=async()=>{try{let e=Ue().getRootPath();if(!(0,h.isDefined)(e))return[];let t=await(0,k.getSchemaWithPathOptional)(``,``,{cwd:e});if(!(0,h.isDefined)(t))return[];let n=t.schemas.map(e=>e[1]),r=new Set;for(let e of n){let n=(await(0,k.getConfig)({datamodel:e,ignoreEnvVarErrors:!0})).generators;for(let e of n)if((0,h.isDefined)(e.output?.value)){let n=f.default.join(f.default.resolve(t.schemaRootDir,e.output.value),`index.d.ts`);await et.fromAbsolutePath(n).isFileExists()&&r.add(n)}}return[...r]}catch(e){return H.error(`Failed to get prisma typings paths`,e),[]}},Bt=async()=>(await Promise.all([Rt(),zt()])).flat(),Vt=async(e,t=!1,n)=>{let r=`!**/node_modules/**`;if(t)return new E.Project({useInMemoryFileSystem:!0,compilerOptions:n});let i=st(e),a=Ht((0,f.dirname)(rt(e)),Ue().isSiblingFolderStructured());if(!i&&!(0,h.isDefined)(a)){let t=await Wt(e);if(!(0,h.isDefined)(t)||(0,h.isEmpty)(t))throw Error(`Cannot find source code path in jest config`);let n=new E.Project({compilerOptions:{allowJs:!0,maxNodeModuleJsDepth:0},useInMemoryFileSystem:!1});return n.addSourceFilesAtPaths([...t,r]),n}if(!i&&(0,h.isDefined)(a)){let t=new E.Project({tsConfigFilePath:a,compilerOptions:{allowJs:!0,maxNodeModuleJsDepth:0}}),n=await Wt(e);return t.addSourceFilesAtPaths([...n,r]),t}let o=new E.Project({tsConfigFilePath:a,compilerOptions:{maxNodeModuleJsDepth:0}}),s=await Bt();for(let e of s)o.addSourceFileAtPath(e);return o},Ht=(e,t)=>{let n;try{n=Ut(e)}catch{t&&(n=Ut((0,f.dirname)(e)))}return n},Ut=e=>{let t=e,n=/^(tsconfig|jsconfig).*\.json$/;for(;t!==(0,f.dirname)(t);){let e=(0,f.join)(t,`tsconfig.json`),r=(0,f.join)(t,`jsconfig.json`);if(!(0,w.existsSync)(t))return Ut((0,f.dirname)(t));if((0,w.existsSync)(e))return e;if((0,w.existsSync)(r))return r;let i=(0,w.readdirSync)(t);for(let e of i)if(n.test(e))return(0,f.join)(t,e);t=(0,f.dirname)(t)}},Wt=async e=>{let t=await Lt(e);if((0,h.isDefined)(t)){let e=t?.configs[0].roots.map(e=>f.default.join(e,`**/*.{ts,js,tsx,jsx}`));if(!(0,h.isEmpty)(e))return e}return[rt(ut(e))]};var Gt=l(Ie()),Kt=l(Le());let qt=`The ts-morph project is not initialized.`,Jt=new class{storage=new m.AsyncLocalStorage;_project;clear(){this._project=void 0}async init(e,t,n){let r=rt(e);if((0,h.isDefined)(this._project))return this._project.addSourceFileAtPathIfExists(r);this._project=await Vt(e,t,n);let i=this.storage.getStore();if((0,h.isDefined)(i))return this._project.addSourceFileAtPathIfExists(r)}add(e,t){let n=rt(e),r=this.storage.getStore()?.getProject();if(!(0,h.isDefined)(r))throw Error(qt);return r.createSourceFile(n,t,{overwrite:!0})}update(e,t){let n=this.get(e);return n.replaceWithText(t),n}addFile(e){(0,h.isDefined)(this._project)&&this._project.addSourceFileAtPathIfExists(e)}removeFile(e){if(!(0,h.isDefined)(this._project))return;let t=this._project.getSourceFile(e);(0,h.isDefined)(t)&&this._project.removeSourceFile(t)}async refreshFromFileSystem(e){if(!(0,h.isDefined)(this._project))return;let t=rt(e),n=this._project?.getSourceFile(e)??this._project?.getSourceFile(t);if((0,h.isDefined)(n)){let e=n.getFilePath();this._project.removeSourceFile(n),this._project.addSourceFileAtPath(e)}}get(e){let t=rt(e),n=this.storage.getStore()?.getProject();if(!(0,h.isDefined)(n))throw Error(qt+` store`);let r=n.getSourceFile(t);if(!(0,h.isDefined)(r))throw Error(`The source file is absent. ${e}`);return r}async save(e){await this.get(e).save()}async delete(e){await this.get(e).deleteImmediately()}getOrUndefined(e){let t=rt(e);return this._project?.getSourceFile(t)}withContext=(e,t,n)=>{let r=n.value,i=this.storage;if((0,h.isDefined)(i.getStore()))return n;let a=()=>this._project;return n.value=function(...e){let t={getProject:a};return i.run(t,()=>r.apply(this,e))},n}},Yt=Jt.withContext,Xt=async e=>{class t{async fn(){return e()}}(0,Kt.default)([Yt,(0,Gt.default)(`design:type`,Function),(0,Gt.default)(`design:paramtypes`,[]),(0,Gt.default)(`design:returntype`,Promise)],t.prototype,`fn`,null),await new t().fn()},Zt=e=>{let t=e?.asKind(E.SyntaxKind.ExpressionStatement)?.getExpression();if(!(0,h.isDefined)(t))return;let n=t.asKind(E.SyntaxKind.CallExpression)?.getArguments()?.at(-1),r=n?.asKind(E.SyntaxKind.ArrowFunction)?.getBody(),i=n?.asKind(E.SyntaxKind.FunctionExpression)?.getBody();return r?.asKind(E.SyntaxKind.Block)??i?.asKind(E.SyntaxKind.Block)},Qt=e=>E.Node.isExpressionStatement(e)&&e.getFirstChildByKind(E.SyntaxKind.CallExpression)?.getFirstChildByKind(E.SyntaxKind.Identifier)?.getText()===`describe`,$t=e=>e.getStatements().filter(e=>Qt(e)),en=e=>{let t=e.getExpression().getFirstChild()?.getText();return!(0,h.isDefined)(t)||(0,h.isEmpty)(t)?!1:Ot.some(e=>t.startsWith(e))},tn=e=>{let t=Zt(e);return(0,h.isDefined)(t)?t.getChildrenOfKind(E.SyntaxKind.ExpressionStatement).some(e=>en(e)):!1},nn=e=>{let t=Zt(e);return(0,h.isDefined)(t)?t.getChildrenOfKind(E.SyntaxKind.ExpressionStatement).filter(e=>Qt(e)&&tn(e)):[]},rn=e=>{let t=Zt(e);if((0,h.isDefined)(t))return t.getChildrenOfKind(E.SyntaxKind.ExpressionStatement).find(e=>Qt(e)&&tn(e))},an=e=>{let t=rn(e);return(0,h.isDefined)(t)},on=e=>{let t=Zt(e);if(!(0,h.isDefined)(t))return!0;let n=t.getChildrenOfKind(E.SyntaxKind.ExpressionStatement);if((0,h.isEmpty)(n))return!0;let r=new Set([`beforeEach`,`afterEach`,`beforeAll`,`afterAll`]);return n.every(e=>{let t=e.getExpressionIfKind(E.SyntaxKind.CallExpression)?.getExpressionIfKind(E.SyntaxKind.Identifier);return(0,h.isDefined)(t)?r.has(t.getText()):!1})},sn=e=>{if(e.isNamedExport?.())return kt.Named;if(e.isDefaultExport?.())return kt.Default;let t=e?.getParent();if((0,h.isDefined)(t)){if(t.isNamedExport?.())return kt.Named;if(t.isDefaultExport?.())return kt.Default}return e.isExportDefaultObject?.()??ln(e.getSourceFile(),e.getName?.())?kt.ObjectDefault:kt.NotExported},cn=(e,t)=>(0,h.isDefined)(e)?sn(e):(0,h.isDefined)(t)?t.isNamedImport?kt.Named:kt.Default:kt.Unknown;function ln(e,t){let[n]=e.getExportAssignments()??[];return n?.getDescendantsOfKind(E.SyntaxKind.Identifier).some(e=>(e.getSymbol()?.getEscapedName()??e.getText())===t)}function un(e,t){let n=$t(Jt.get(e)),r=n.find(e=>e.getText().includes(t))??n[0],i=nn(r),a=[],o=(0,h.isEmpty)(i)?[r]:i;for(let e of o){let t=Zt(e);(0,h.isDefined)(t)&&a.push(...t.getChildrenOfKind(E.SyntaxKind.ExpressionStatement).filter(e=>en(e)))}return a}let dn=e=>e.getFirstDescendantByKind(E.SyntaxKind.StringLiteral)?.getLiteralValue(),W=e=>dn(e),fn=e=>dn(e),pn=(e,t)=>{let n=e.getFullText().slice(0,Math.max(0,t)).split(`
|
|
32005
|
+
`):(this.indentate=function(){return``},this.tagEndChar=`>`,this.newLine=``)}function be(e,t,n,r){let i=this.j2x(e,n+1,r.concat(t));return e[this.options.textNodeName]!==void 0&&Object.keys(e).length===1?this.buildTextValNode(e[this.options.textNodeName],t,i.attrStr,n):this.buildObjectNode(i.val,t,i.attrStr,n)}function xe(e){return this.options.indentBy.repeat(e)}function Se(e){return!(!e.startsWith(this.options.attributeNamePrefix)||e===this.options.textNodeName)&&e.substr(this.attrPrefixLen)}ye.prototype.build=function(e){return this.options.preserveOrder?fe(e,this.options):(Array.isArray(e)&&this.options.arrayNodeName&&this.options.arrayNodeName.length>1&&(e={[this.options.arrayNodeName]:e}),this.j2x(e,0,[]).val)},ye.prototype.j2x=function(e,t,n){let r=``,i=``,a=n.join(`.`);for(let o in e)if(Object.prototype.hasOwnProperty.call(e,o))if(e[o]===void 0)this.isAttribute(o)&&(i+=``);else if(e[o]===null)this.isAttribute(o)||o===this.options.cdataPropName?i+=``:o[0]===`?`?i+=this.indentate(t)+`<`+o+`?`+this.tagEndChar:i+=this.indentate(t)+`<`+o+`/`+this.tagEndChar;else if(e[o]instanceof Date)i+=this.buildTextValNode(e[o],o,``,t);else if(typeof e[o]!=`object`){let n=this.isAttribute(o);if(n&&!this.ignoreAttributesFn(n,a))r+=this.buildAttrPairStr(n,``+e[o]);else if(!n)if(o===this.options.textNodeName){let t=this.options.tagValueProcessor(o,``+e[o]);i+=this.replaceEntitiesValue(t)}else i+=this.buildTextValNode(e[o],o,``,t)}else if(Array.isArray(e[o])){let r=e[o].length,a=``,s=``;for(let c=0;c<r;c++){let r=e[o][c];if(r!==void 0)if(r===null)o[0]===`?`?i+=this.indentate(t)+`<`+o+`?`+this.tagEndChar:i+=this.indentate(t)+`<`+o+`/`+this.tagEndChar;else if(typeof r==`object`)if(this.options.oneListGroup){let e=this.j2x(r,t+1,n.concat(o));a+=e.val,this.options.attributesGroupName&&r.hasOwnProperty(this.options.attributesGroupName)&&(s+=e.attrStr)}else a+=this.processTextOrObjNode(r,o,t,n);else if(this.options.oneListGroup){let e=this.options.tagValueProcessor(o,r);e=this.replaceEntitiesValue(e),a+=e}else a+=this.buildTextValNode(r,o,``,t)}this.options.oneListGroup&&(a=this.buildObjectNode(a,o,s,t)),i+=a}else if(this.options.attributesGroupName&&o===this.options.attributesGroupName){let t=Object.keys(e[o]),n=t.length;for(let i=0;i<n;i++)r+=this.buildAttrPairStr(t[i],``+e[o][t[i]])}else i+=this.processTextOrObjNode(e[o],o,t,n);return{attrStr:r,val:i}},ye.prototype.buildAttrPairStr=function(e,t){return t=this.options.attributeValueProcessor(e,``+t),t=this.replaceEntitiesValue(t),this.options.suppressBooleanAttributes&&t===`true`?` `+e:` `+e+`="`+t+`"`},ye.prototype.buildObjectNode=function(e,t,n,r){if(e===``)return t[0]===`?`?this.indentate(r)+`<`+t+n+`?`+this.tagEndChar:this.indentate(r)+`<`+t+n+this.closeTag(t)+this.tagEndChar;{let i=`</`+t+this.tagEndChar,a=``;return t[0]===`?`&&(a=`?`,i=``),!n&&n!==``||e.indexOf(`<`)!==-1?!1!==this.options.commentPropName&&t===this.options.commentPropName&&a.length===0?this.indentate(r)+`\x3c!--${e}--\x3e`+this.newLine:this.indentate(r)+`<`+t+n+a+this.tagEndChar+e+this.indentate(r)+i:this.indentate(r)+`<`+t+n+a+`>`+e+i}},ye.prototype.closeTag=function(e){let t=``;return this.options.unpairedTags.indexOf(e)===-1?t=this.options.suppressEmptyNode?`/`:`></${e}`:this.options.suppressUnpairedNode||(t=`/`),t},ye.prototype.buildTextValNode=function(e,t,n,r){if(!1!==this.options.cdataPropName&&t===this.options.cdataPropName)return this.indentate(r)+`<![CDATA[${e}]]>`+this.newLine;if(!1!==this.options.commentPropName&&t===this.options.commentPropName)return this.indentate(r)+`\x3c!--${e}--\x3e`+this.newLine;if(t[0]===`?`)return this.indentate(r)+`<`+t+n+`?`+this.tagEndChar;{let i=this.options.tagValueProcessor(t,e);return i=this.replaceEntitiesValue(i),i===``?this.indentate(r)+`<`+t+n+this.closeTag(t)+this.tagEndChar:this.indentate(r)+`<`+t+n+`>`+i+`</`+t+this.tagEndChar}},ye.prototype.replaceEntitiesValue=function(e){if(e&&e.length>0&&this.options.processEntities)for(let t=0;t<this.options.entities.length;t++){let n=this.options.entities[t];e=e.replace(n.regex,n.val)}return e};let Ce={validate:s};t.exports=n})()})),cW=s((e=>{var t=Object.create,n=Object.defineProperty,r=Object.getOwnPropertyDescriptor,i=Object.getOwnPropertyNames,a=Object.getPrototypeOf,o=Object.prototype.hasOwnProperty,s=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),c=(e,t,a,s)=>{if(t&&typeof t==`object`||typeof t==`function`)for(var c=i(t),l=0,u=c.length,d;l<u;l++)d=c[l],!o.call(e,d)&&d!==a&&n(e,d,{get:(e=>t[e]).bind(null,d),enumerable:!(s=r(t,d))||s.enumerable});return e},l=(e,r,i)=>(i=e==null?{}:t(a(e)),c(r||!e||!e.__esModule?n(i,`default`,{value:e,enumerable:!0}):i,e));let u=l(Oi()),f=l(ki()),p=l(require(`node:fs/promises`)),m=l(require(`node:async_hooks`)),h=l(se()),g=l(Bi()),_=l(Rc()),v=l((Ol(),d(ll))),y=l(require(`node:crypto`)),b=l(iR()),x=l(pM()),S=l(fz()),C=l((Dj(),d(Ej))),w=l(require(`node:fs`)),T=l(Uz()),E=l(pV()),D=l(require(`node:child_process`)),O=l(require(`node:util`)),k=l(require(`@prisma/internals`)),A=l(lV()),ee=l(require(`node:zlib`)),j=l(cH()),te=l(uH()),M=l(mH()),ne=l(Eee()),N=l(require(`node:os`)),P=l(require(`node:events`)),F=l(gU()),I=l(tW()),re=l(Fee()),ie=l(oW()),L=l(sW()),R=l(_U()),ae=l(require(`node:process`));l(require(`node:readline`)),l(require(`node:tty`));let z=l(require(`node:path`)),oe=l(require(`@anthropic-ai/claude-agent-sdk`)),B={DELETE:`delete`,COMMENT_OUT:`comment out`,KEEP:`keep`,SKIP:`skip`},ce={GREEN:`Green`,GREY:`Grey`,RED:`Red`,NA:`NA`},le={GREEN:`Green`,GREY:`Grey`,RUNTIME_ERROR:`RuntimeError`},ue=function(e){return e.IDE=`IDE`,e.CLI=`CLI`,e}({}),de=function(e){return e.SIBLING_FOLDER=`siblingFolder`,e.ROOT_FOLDER=`rootFolder`,e}({}),fe=function(e){return e.JEST=`jest`,e.MOCHA=`mocha`,e.VITEST=`vitest`,e.PYTEST=`pytest`,e}({}),pe=function(e){return e.SPEC=`spec`,e.TEST=`test`,e}({}),me=function(e){return e.CAMEL_CASE=`camelCase`,e.KEBAB_CASE=`kebabCase`,e}({}),he=function(e){return e.NONE=`none`,e.CATEGORIES=`categories`,e}({}),ge=function(e){return e.NEW_CODE_FILE=`newCodeFile`,e.OVERRIDE_CODE_FILE=`overrideCodeFile`,e}({}),_e=function(e){return e.ON=`on`,e.OFF=`off`,e}({}),ve={DEFAULT:0,MIN:0,MAX:100},ye={DEFAULT:5,MIN:1,MAX:50};u.z.object({rootPath:u.z.string().default(process.cwd()),testStructure:u.z.enum(de).optional(),testFramework:u.z.enum(fe).optional(),testSuffix:u.z.enum(pe).optional(),testFileName:u.z.enum(me).optional(),calculateCoverage:u.z.enum(_e).optional(),coverageThreshold:u.z.number().min(ve.MIN).max(ve.MAX).default(ve.DEFAULT),requestSource:u.z.enum(ue).optional(),concurrency:u.z.number().min(ye.MIN).max(ye.MAX).default(ye.DEFAULT),backendURL:u.z.string().optional(),secretToken:u.z.string().optional(),modelName:u.z.string().optional(),context:u.z.object({git:u.z.object({ref_name:u.z.string(),repository:u.z.string(),owner:u.z.string(),sha:u.z.string(),workflowRunId:u.z.string(),remoteUrl:u.z.string(),topLevel:u.z.string()}).partial().optional()}).optional(),testCommand:u.z.string().optional(),coverageCommand:u.z.string().optional(),lintCommand:u.z.string().optional(),prettierCommand:u.z.string().optional(),disableLintRules:u.z.boolean().optional(),ignoreAsAnyLintErrors:u.z.boolean().optional(),includeEarlyTests:u.z.boolean().optional(),greyTestBehaviour:u.z.enum(B).optional(),redTestBehaviour:u.z.enum(B).optional(),keepErrorTests:u.z.boolean().optional(),keepFailedTests:u.z.boolean().optional(),conditionalKeep:u.z.boolean().optional(),continueOnTestErrors:u.z.boolean().optional(),perFunctionTimeout:u.z.number().positive().optional(),dynamicPromptIterations:u.z.number().min(0).max(10).optional(),removeComments:u.z.boolean().optional(),experimentalAgentSdk:u.z.boolean().optional(),agentSdkModel:u.z.string().optional(),agentSdkBudget:u.z.number().positive().optional(),debug:u.z.boolean().optional(),verbose:u.z.boolean().optional(),progressLogger:u.z.custom().optional()});var be=`@earlyai/ts-agent`,xe=`0.75.0`;let Se={VSCODE:`vscode`,GITHUB_ACTION:`github-action`,UNKNOWN:`unknown`},Ce=`$early_filename`,we=`$early_coverage_dir`,Te=`npx jest ${Ce} --no-coverage --silent --json --forceExit --maxWorkers=1`,Ee=`npx --no eslint ${Ce}`,De=`npx --no prettier ${Ce} --write`,Oe={rootPath:process.cwd(),isSiblingFolderStructured:!0,gitURL:`https://github.com/your-owner/your-repo`,testFramework:fe.JEST,greyTestBehaviour:B.DELETE,redTestBehaviour:B.DELETE,keepErrorTests:!1,keepFailedTests:!1,conditionalKeep:!1,continueOnTestErrors:!0,generatedTestStructure:he.CATEGORIES,isRootFolderStructured:!1,clientSource:Se.GITHUB_ACTION,backendURL:`https://api.startearly.ai`,requestSource:ue.CLI,userPrompt:``,testLocation:`__tests__`,coverageThreshold:ve.DEFAULT,concurrency:5,testFileFormat:`ts`,outputType:ge.NEW_CODE_FILE,shouldRefreshCoverage:!0,kebabCaseFileName:!1,earlyTestFilenameSuffix:`.early.${pe.TEST}`,testSuffix:pe.TEST,isAppendPrompt:!1,dynamicPromptIterations:3,wsServerEndpoint:`wss://api.startearly.ai`,secretToken:``,loggerConfig:{consoleEnabled:!1,azureEnabled:!0,azureConnectionString:`InstrumentationKey=8b9b0d6a-5400-44a3-ada6-3cd026de6cfe;IngestionEndpoint=https://eastus-8.in.applicationinsights.azure.com/;LiveEndpoint=https://eastus.livediagnostics.monitor.azure.com/;ApplicationId=d6e130b6-4aaa-4dcc-8d26-c1fa25d4656a`},context:void 0,includeEarlyTests:!1,lintCommand:Ee,prettierCommand:De,disableLintRules:!1,ignoreAsAnyLintErrors:!0,allowUndefinedLintErrors:!0,perFunctionTimeout:24e4,removeComments:!0,experimentalAgentSdk:!1,agentSdkModel:void 0,agentSdkBudget:void 0,debug:!1,verbose:!1},ke=e=>{let t=`testFramework.testSuffix.backendURL.requestSource.secretToken.concurrency.coverageThreshold.context.rootPath.testCommand.coverageCommand.lintCommand.prettierCommand.disableLintRules.greyTestBehaviour.redTestBehaviour.keepErrorTests.keepFailedTests.conditionalKeep.continueOnTestErrors.perFunctionTimeout.dynamicPromptIterations.removeComments.experimentalAgentSdk.agentSdkModel.agentSdkBudget.debug.verbose.progressLogger`.split(`.`).reduce((t,n)=>(0,h.isDefined)(e[n])?{...t,[n]:e[n]}:t,{}),n={...(0,h.isDefined)(e.testStructure)&&{isSiblingFolderStructured:e.testStructure===de.SIBLING_FOLDER,isRootFolderStructured:e.testStructure===de.ROOT_FOLDER},...(0,h.isDefined)(e.testFileName)&&{kebabCaseFileName:e.testFileName===me.KEBAB_CASE},...(0,h.isDefined)(e.calculateCoverage)&&{shouldRefreshCoverage:e.calculateCoverage===_e.ON},...(0,h.isDefined)(e.modelName)&&{fixTestsLLMModelName:e.modelName,generateTestsLLMModelName:e.modelName},...(0,h.isDefined)(e.testSuffix)&&{earlyTestFilenameSuffix:`.early.${e.testSuffix}`},...(0,h.isDefined)(e.requestSource)&&{clientSource:e.requestSource===ue.IDE?Se.VSCODE:Se.GITHUB_ACTION}};return{...t,...n}},Ae=new v.Chalk({level:1}),je=()=>{},Me={info:je,verbose:je,debug:je},Ne=[Ae.cyan,Ae.magenta,Ae.green,Ae.blue,Ae.redBright,Ae.cyanBright,Ae.magentaBright,Ae.greenBright];function Pe(e){let t=2166136261;for(let n=0;n<e.length;n++)t^=e.codePointAt(n)??0,t=Math.imul(t,16777619);return Ne[Math.abs(t)%Ne.length]}function Fe(e,t){let n=(0,h.isDefined)(t.parentName)?`${t.parentName}.${t.methodName}`:t.methodName,r=Pe(n)(`[${n}]`);return{info:(...t)=>e.info(r,...t),verbose:(...t)=>e.verbose(r,...t),debug:(...t)=>e.debug(r,...t)}}var Ie=s(((e,t)=>{function n(e,t){if(typeof Reflect==`object`&&typeof Reflect.metadata==`function`)return Reflect.metadata(e,t)}t.exports=n,t.exports.__esModule=!0,t.exports.default=t.exports})),Le=s(((e,t)=>{function n(e,t,n,r){var i=arguments.length,a=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r,o;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)a=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(o=e[s])&&(a=(i<3?o(a):i>3?o(t,n,a):o(t,n))||a);return i>3&&a&&Object.defineProperty(t,n,a),a}t.exports=n,t.exports.__esModule=!0,t.exports.default=t.exports})),Re=l(Ie()),ze=l(Le()),Be,Ve;let He=class{config;constructor(e,t={}){if(!(0,h.isDefined)(e)){this.config=Oe;return}let n=ke(e);this.config=(0,h.merge)(Oe,n,t)}getRootPath=()=>this.config.rootPath;isSiblingFolderStructured=()=>this.config.isSiblingFolderStructured;getGitURL=()=>this.config.context?.git?.remoteUrl??this.config.gitURL;getGitTopLevel=()=>this.config.context?.git?.topLevel??this.getRootPath();getTestFramework=()=>this.config.testFramework;getGreyTestBehaviour=()=>this.config.greyTestBehaviour;getRedTestBehaviour=()=>this.config.redTestBehaviour;shouldKeepErrorTests=()=>this.config.keepErrorTests;shouldKeepFailedTests=()=>this.config.keepFailedTests;shouldConditionalKeep=()=>this.config.conditionalKeep;getGeneratedTestStructure=()=>this.config.generatedTestStructure;getGenerateTestsLLMModelName=()=>this.config.generateTestsLLMModelName;isRootFolderStructured=()=>this.config.isRootFolderStructured;getLLMTemperature=()=>this.config.llmTemperature;getLLMTopP=()=>this.config.llmTopP;getClientSource=()=>this.config.clientSource;getBackendURL=()=>this.config.backendURL;getRequestSource=()=>this.config.requestSource;getUserPrompt=()=>this.config.userPrompt;getTestLocation=()=>this.config.testLocation;getCoverageThreshold=()=>this.config.coverageThreshold;getConcurrency=()=>this.config.concurrency;getTestFileFormat=()=>this.config.testFileFormat;getOutputType=()=>this.config.outputType;getShouldRefreshCoverage=()=>this.config.shouldRefreshCoverage;isKebabCaseFileName=()=>this.config.kebabCaseFileName;getEarlyTestFilenameSuffix=()=>this.config.earlyTestFilenameSuffix;getTestSuffix=()=>this.config.testSuffix;getIsAppendPrompt=()=>this.config.isAppendPrompt;getFixTestsLLMModelName=()=>this.config.fixTestsLLMModelName;getDynamicPromptIterations=()=>this.config.dynamicPromptIterations;getWSServerEndpoint=()=>this.config.backendURL.replace(`http://`,`ws://`).replace(`https://`,`wss://`);getAnthropicProxyUrl=()=>new URL(`/anthropic`,this.config.backendURL).href;getSecretToken=()=>this.config.secretToken;getLoggerConfig=()=>this.config.loggerConfig;getContext=()=>this.config.context;getTestCommand=()=>this.config.testCommand;getCoverageCommand=()=>this.config.coverageCommand;getLintCommand=()=>this.config.lintCommand;getPrettierCommand=()=>this.config.prettierCommand;shouldDisableLintRules=()=>this.config.disableLintRules;shouldIgnoreAsAnyLintErrors=()=>this.config.ignoreAsAnyLintErrors;allowUndefinedLintErrors=()=>this.config.allowUndefinedLintErrors;getIncludeEarlyTests=()=>this.config.includeEarlyTests??!1;shouldContinueOnTestErrors=()=>this.config.continueOnTestErrors;getPerFunctionTimeout=()=>this.config.perFunctionTimeout;shouldRemoveComments=()=>this.config.removeComments;getExperimentalAgentSdk=()=>this.config.experimentalAgentSdk;getAgentSdkModel=()=>this.config.agentSdkModel;getAgentSdkBudget=()=>this.config.agentSdkBudget;updateContext=e=>{this.config.context=(0,h.merge)(this.config.context??{},e??{})};updateRootPath=e=>{this.config.rootPath=e};isDebug=()=>this.config.debug??!1;isVerbose=()=>this.config.verbose??!1;getProgressLogger=e=>{let t=this.config.progressLogger??Me;return(0,h.isDefined)(e)?Fe(t,e):t}};He=(0,ze.default)([(0,_.injectable)(`Singleton`),(0,Re.default)(`design:paramtypes`,[typeof(Be=typeof Partial<`u`&&Partial)==`function`?Be:Object,typeof(Ve=typeof Partial<`u`&&Partial)==`function`?Ve:Object])],He);var V=new _.Container({autobind:!0,defaultScope:`Singleton`});let Ue=()=>V.get(He);var We=class{storage=new m.AsyncLocalStorage;isConsoleEnabled;constructor(e){this.isConsoleEnabled=e}orderedFlush={nextOrder:1,pending:new Map};resetOrder(){this.orderedFlush={nextOrder:1,pending:new Map}}async withBufferedPrinting(e,t){let n=[];try{return await this.storage.run(n,e)}finally{this.flushInOrder(t,n)}}printOrBuffer(e,t){let n=this.storage.getStore();if((0,h.isDefined)(n)){n.push({method:e,message:t});return}this.isConsoleEnabled&&console[e](t)}async flushInOrder(e,t){if(this.orderedFlush.nextOrder===e){this.flushBuffer(t),this.orderedFlush.nextOrder++,this.drainPendingFlushes();return}return new Promise(n=>{this.orderedFlush.pending.set(e,{buffer:t,resolve:n})})}drainPendingFlushes(){let e=this.orderedFlush.pending.get(this.orderedFlush.nextOrder);for(;(0,h.isDefined)(e);)this.orderedFlush.pending.delete(this.orderedFlush.nextOrder),this.flushBuffer(e.buffer),this.orderedFlush.nextOrder++,e.resolve(),e=this.orderedFlush.pending.get(this.orderedFlush.nextOrder)}flushBuffer(e){if(this.isConsoleEnabled)for(let t of e)console[t.method](t.message)}};let Ge=function(e){return e.DEFAULT=`default`,e.VERBOSE=`verbose`,e.DEBUG=`debug`,e}({}),Ke=function(e){return e.INFO=`info`,e.WARN=`warn`,e}({});function qe(){return(0,y.randomUUID)()}function Je(){let e=``;for(let t=0;t<8;t++)e+=`abcdefghijklmnopqrstuvwxyz0123456789`.charAt(Math.floor(Math.random()*36));return e}var Ye=l(Ie()),Xe=l(Le()),Ze=class{export(e,t){for(let t of e){let e=t.body;if((0,h.isString)(e))console.info(e);else try{console.info(JSON.stringify(e))}catch{console.info(String(e))}}t({code:0})}shutdown(){return Promise.resolve()}};let Qe=class{loggerProvider;config;constructor(e){this.config=e,this.loggerProvider=new S.LoggerProvider({resource:(0,x.resourceFromAttributes)({[C.ATTR_SERVICE_NAME]:be,[C.ATTR_SERVICE_VERSION]:xe})}),this.initializeExporters(),this.setGlobalLoggerProvider()}getLogger(e){return this.loggerProvider.getLogger(e)}initializeExporters(){let e=[];if(this.config.consoleEnabled){let t=new Ze;e.push(new S.SimpleLogRecordProcessor(t))}if(this.config.azureEnabled&&(0,h.isDefined)(this.config.azureConnectionString)){let t=new b.AzureMonitorLogExporter({connectionString:this.config.azureConnectionString});e.push(new S.BatchLogRecordProcessor(t))}this.loggerProvider=new S.LoggerProvider({processors:e})}setGlobalLoggerProvider(){g.logs.setGlobalLoggerProvider(this.loggerProvider)}};Qe=(0,Xe.default)([(0,_.injectable)(),(0,Ye.default)(`design:paramtypes`,[Object])],Qe),l(Ie()),l(Le());let H=new class{storage;otelService;otelLogger;isConsoleEnabled;printBuffer;default=this.createLogObject(Ge.DEFAULT);verbose=this.createLogObject(Ge.VERBOSE);constructor(e){this.storage=new m.AsyncLocalStorage,this.otelService=new Qe(e),this.otelLogger=this.otelService.getLogger(`ts-agent`),this.isConsoleEnabled=e.consoleEnabled,this.printBuffer=new We(e.consoleEnabled)}resetPrintOrder(){this.printBuffer.resetOrder()}async withBufferedPrinting(e,t){return this.printBuffer.withBufferedPrinting(e,t)}info={startLog:(e,...t)=>this.log(g.SeverityNumber.INFO,`Start ${e}`,...t),endLog:(e,...t)=>this.log(g.SeverityNumber.INFO,`End ${e}`,...t),failedLog:(e,...t)=>this.log(g.SeverityNumber.INFO,`Failed ${e}`,...t),defaultLog:(e,...t)=>this.log(g.SeverityNumber.INFO,e,...t)};debug={startLog:(e,...t)=>this.log(g.SeverityNumber.DEBUG,`Start ${e}`,...t),endLog:(e,...t)=>this.log(g.SeverityNumber.DEBUG,`End ${e}`,...t),failedLog:(e,...t)=>this.log(g.SeverityNumber.DEBUG,`Failed ${e}`,...t),defaultLog:(e,...t)=>this.log(g.SeverityNumber.DEBUG,e,...t)};error(e,t,...n){let r=t instanceof Error?`${e} ${t.message} ${t.stack}`:`${e} ${JSON.stringify(t)}`;this.log(g.SeverityNumber.ERROR,r,...n)}getRequestId(){return this.storage.getStore()?.requestId??``}getTraceId(){return this.storage.getStore()?.traceId??``}log(e,t,...n){let r=this.formatMessage(t,...n);this.logToOpenTelemetry(e,r),!(!this.isConsoleEnabled||!this.isLevelEnabled(Ge.DEBUG))&&console.info(r)}logToOpenTelemetry(e,t){let n=this.storage.getStore(),r={service:be,version:xe};(0,h.isDefined)(n)&&((0,h.isDefined)(n.traceId)&&(r.traceId=n.traceId),(0,h.isDefined)(n.requestId)&&(r.requestId=n.requestId),(0,h.isDefined)(n.category)&&(r.category=n.category),(0,h.isDefined)(n.subCategory)&&(r.subCategory=n.subCategory),(0,h.isDefined)(n.testedMethodClass)&&(r.testedMethodClass=n.testedMethodClass),(0,h.isDefined)(n.testedFunction)&&(r.testedFunction=n.testedFunction),(0,h.isDefined)(n.userId)&&(r.userId=n.userId.toString())),this.otelLogger.emit({severityNumber:e,severityText:this.getSeverityText(e),body:t,attributes:r})}getSeverityText(e){switch(e){case g.SeverityNumber.TRACE:return`TRACE`;case g.SeverityNumber.DEBUG:return`DEBUG`;case g.SeverityNumber.INFO:return`INFO`;case g.SeverityNumber.WARN:return`WARN`;case g.SeverityNumber.ERROR:return`ERROR`;case g.SeverityNumber.FATAL:return`FATAL`;default:return`INFO`}}formatMessage(e,...t){let n=this.formatPrefix(),r=(0,h.isDefined)(n)?`${n} ${e}`:e;return this.formatPrint(r,...t)}formatPrint(e,...t){return(0,h.isEmpty)(t)?e:`${e} ${t.map(e=>JSON.stringify(e)).join(` `)}`}withContext=(e,t,n)=>{let r=n.value,i=this.storage;return n.value=function(...e){let t=i.getStore();if(t){let n={...t};return i.run(n,()=>r.apply(this,e))}let n={traceId:Je(),requestId:qe()};return i.run(n,()=>r.apply(this,e))},n};addContext(e){let t=this.storage.getStore();(0,h.isDefined)(t)&&(t.category=e.category??t.category,t.subCategory=e.subCategory??t.subCategory,t.testedMethodClass=e.testedMethodClass??t.testedMethodClass,t.testedFunction=e.testedFunction??t.testedFunction,t.userId=e.userId??t.userId)}captureContext({withNewRequestId:e=!1}={}){let t=this.storage.getStore();return t?{...t,...e&&{requestId:qe()}}:void 0}async runWithContext(e,t){return(0,h.isDefined)(e)?this.storage.run(e,t):t()}isLevelEnabled(e){switch(e){case Ge.DEFAULT:return!0;case Ge.VERBOSE:return Ue().isVerbose()||Ue().isDebug();case Ge.DEBUG:return Ue().isDebug()}}createLogObject(e){return{info:(t,...n)=>{this.isLevelEnabled(e)&&this.printOrBuffer(Ke.INFO,this.formatPrint(t,...n))},warn:(t,...n)=>{this.isLevelEnabled(e)&&this.printOrBuffer(Ke.WARN,this.formatPrint(t,...n))}}}printOrBuffer(e,t){this.printBuffer.printOrBuffer(e,t)}formatPrefix(){let e=this.storage.getStore();if(!(0,h.isDefined)(e))return``;let t=[];return(0,h.isDefined)(e.traceId)&&t.push(`[${e.traceId}]`),(0,h.isDefined)(e.requestId)&&t.push(`[${e.requestId}]`),(0,h.isDefined)(e.category)&&t.push(`[${e.category}]`),(0,h.isDefined)(e.subCategory)&&t.push(`[${e.subCategory}]`),(0,h.isDefined)(e.testedMethodClass)&&t.push(`[${e.testedMethodClass}]`),(0,h.isDefined)(e.testedFunction)&&t.push(`[${e.testedFunction}]`),t.join(` `)}}({consoleEnabled:!1,azureEnabled:!0,azureConnectionString:`InstrumentationKey=c18a3332-f844-498f-98e0-d818996cf526;IngestionEndpoint=https://eastus2-3.in.applicationinsights.azure.com/;LiveEndpoint=https://eastus2.livediagnostics.monitor.azure.com/;ApplicationId=2150ffe0-cb0f-4b00-9562-d3385b383d74`});function $e(e){return function(t,n,r){return(0,h.isDefined)(e)&&H.addContext(e),H.withContext(t,n,r)}}var et=class e{rootPath;absolutePath;static EARLY_FILENAME_VAR=`$early_filename`;constructor(e){this.rootPath=f.default.normalizeTrim(Ue().getRootPath());let t=f.default.normalizeTrim(e),n=f.default.normalizeTrim(this.rootPath);if(t===n||t.startsWith(n+f.default.sep))this.absolutePath=t;else{let e=t.replace(/^\//,``);this.absolutePath=f.default.resolve(this.rootPath,e)}}static fromSourceFile(t){let n=f.default.normalizeTrim(t.getFilePath());return new e(f.default.relative(f.default.normalizeTrim(Ue().getRootPath()),n))}static fromAbsolutePath(t){let n=f.default.normalizeTrim(t);return new e(f.default.relative(f.default.normalizeTrim(Ue().getRootPath()),n))}static fromRelativePath(t){return new e(t)}getRelativeFilePath(){return f.default.relative(this.rootPath,this.absolutePath)}getAbsoluteFilePath(){return this.absolutePath}async isFileExists(){try{return(await p.default.stat(this.absolutePath)).isFile()}catch{return!1}}async isDirectoryExists(){try{return(await p.default.stat(this.absolutePath)).isDirectory()}catch{return!1}}async createDirectory(e){await p.default.mkdir(this.absolutePath,{recursive:e?.recursive??!0})}async getText(){try{return await p.default.readFile(this.absolutePath,`utf8`)}catch{return``}}async upsert(e){let t=f.default.dirname(this.absolutePath);await p.default.mkdir(t,{recursive:!0}),await(await this.isFileExists()?p.default.appendFile(this.absolutePath,e):p.default.writeFile(this.absolutePath,e)),H.info.defaultLog(`Upserted file`,{path:this.getRelativeFilePath()})}async replace(e){let t=f.default.dirname(this.absolutePath);await p.default.mkdir(t,{recursive:!0}),await p.default.writeFile(this.absolutePath,e),H.info.defaultLog(`Replaced file`,{path:this.getRelativeFilePath()})}async delete(){try{await p.default.unlink(this.absolutePath),H.info.defaultLog(`Deleted file`,{path:this.getRelativeFilePath()})}catch{}}};let tt={WIN32:`win32`,DARWIN:`darwin`,LINUX:`linux`},nt={JAVASCRIPT:`javascript`,TYPESCRIPT:`typescript`,PYTHON:`python`},rt=e=>{let t=Ue().getRootPath();return f.default.resolve(t,e)},it=e=>{let t=Ue().getRootPath(),n=f.default.normalize(e);return f.default.relative(t,n)},at=e=>({".js":`javascript`,".mjs":`javascript`,".cjs":`javascript`,".jsx":`javascript`,".ts":`typescript`,".tsx":`typescript`,".py":`python`})[e.toLowerCase()]??`javascript`;function ot(e){return at((0,f.extname)(e))}function st(e){return at((0,f.extname)(e))===`typescript`}function U(e){return at((0,f.extname)(e))===nt.PYTHON}function ct(e){let t=Ue().getRootPath();if(!(0,h.isDefined)(t))throw Error(`Workspace root path is not defined`);if((0,h.isEmpty)(e))return f.default.normalize(t);let n=f.default.normalize(t),r=f.default.normalize(e);if(process.platform===tt.WIN32){let t=n.split(`:`)[0].toUpperCase(),i=r.split(`:`)[0].toUpperCase();if(t!==i&&!i.startsWith(t))return e}return f.default.relative(n,r)}function lt(e){return e.startsWith(`../`)?`../${e}`:e.startsWith(`./`)?`.${e}`:e}function ut(e){let t=f.default.normalize(rt(e)),n=f.default.normalize((0,T.default)([`package.json`,`project.json`],{cwd:t})??``);if(!n)return``;let r=it((0,f.dirname)(n));return r.startsWith(`/`)?r.slice(1):r}function dt(e,t,n){if(!pt(e))return e;let r=n===``?t:t.replace(n,``),i=n===``?ht(r):mt(r),a=r.split(`/`).slice(0,-1),o=ft(e,`../`),s=o>0?a.slice(0,-o).join(`/`):(0,f.dirname)(r),c=e.replaceAll(`../`,``).replaceAll(`./`,``);return f.default.join(i,s,c)}function ft(e,t){return e.split(t).length-1}function pt(e){return e.startsWith(`../`)||e.startsWith(`./`)}function mt(e){let t=ft(e,`/`);return`../`.repeat(t-1)}function ht(e){let t=ft(e,`/`);return`../`.repeat(t+1)}function gt(e){return e?.includes(`node_modules/`)}let _t=e=>e.replaceAll(/[.*+?^${}()|[\]\\]/g,String.raw`\$&`);function vt(e,t){let n=f.default.isAbsolute(e)?e:rt(e);return(0,T.default)(t,{cwd:n})}function yt(e,t){let n=vt(e,t);if(!(0,h.isDefined)(n))return;let r=w.readFileSync(n,`utf8`);return JSON.parse(r)}function bt(e){return yt(e,`package.json`)}function xt(e,t){let{dependencies:n={},devDependencies:r={}}=e;return Object.keys({...r,...n}).includes(t)}let St=[{path:`eslint.config.js`,isFlat:!0},{path:`eslint.config.cjs`,isFlat:!0},{path:`eslint.config.mjs`,isFlat:!0},{path:`eslint.config.ts`,isFlat:!0},{path:`eslint.config.mts`,isFlat:!0},{path:`eslint.config.cts`,isFlat:!0},{path:`.eslintrc`,isFlat:!1},{path:`.eslintrc.js`,isFlat:!1},{path:`.eslintrc.cjs`,isFlat:!1},{path:`.eslintrc.mjs`,isFlat:!1},{path:`.eslintrc.json`,isFlat:!1},{path:`.eslintrc.yaml`,isFlat:!1},{path:`.eslintrc.yml`,isFlat:!1}],Ct=[`@typescript-eslint/no-undefined`,`unicorn/no-useless-undefined`,`no-undefined`];async function wt(e){for(let{path:t,isFlat:n}of St){let r=f.default.join(e,t);if(await et.fromAbsolutePath(r).isFileExists())return{path:r,isFlat:n}}return bt(e)?.eslint?{path:vt(e,`package.json`),isFlat:!1}:{path:null,isFlat:!1}}let Tt={GET_TESTABLES:`get-testables`,GET_COVERAGE:`get-coverage`,GENERATE_COVERAGE:`generate-coverage`,SET_COVERAGE:`set-coverage`,GENERATE_TESTS:`generate-tests`,INITIALIZATION:`initialization`,GET_TESTED_CODE_DATA_SOURCE:`get-tested-code-data-source`,DYNAMIC_PROMPT:`dynamic-prompt`,TEST_VALIDATION:`test-validation`},Et={CODE_EXTRACTOR:`code-extractor`,CODE_REFINEMENT:`code-refinement`,TEST_MANAGEMENT:`test-management`,TEST_VALIDATOR:`test-validator`,CONFIG_FILE:`config-file`,COMMAND_EXECUTION:`command-execution`},Dt=[`.jsx`,`.tsx`],Ot=[`it`,`test`,`it.each`,`test.each`],kt=function(e){return e.Default=`default`,e.ObjectDefault=`object-default`,e.Named=`named`,e.Unknown=`unknown`,e.NotExported=`not-exported`,e}({}),At=function(e){return e.PRIVATE=`private`,e.PROTECTED=`protected`,e.PUBLIC=`public`,e}({}),jt=function(e){return e.REACT=`react`,e.ANGULAR=`angular`,e}({}),Mt=`unknown`,Nt=(0,O.promisify)(D.default.exec);async function Pt(e,{cwd:t=Ue().getRootPath(),timeout:n=1e4}={}){return(await Nt(e,{cwd:t,maxBuffer:500*1024,timeout:n}))?.stdout?.toString()??``}let Ft=e=>{let t=rt(e);return(0,T.default)(`jest.config.+(js|ts|mjs|cjs|json)`,{cwd:t})},It=e=>(0,h.isObject)(e)&&(0,h.isString)(e.rootDir),Lt=async e=>{let t;if(H.addContext({subCategory:Et.CONFIG_FILE}),(0,h.isDefined)(e)){let n=Ft(e);n!==null&&(t=(0,f.dirname)(n))}t??=Ue().getRootPath();let n;try{if(n=await Pt(`npx jest --showConfig`,{cwd:t}),!(0,h.isString)(n))throw H.info.defaultLog(`Jest config return is not a string`,n),Error(`Jest config return is not a string`);let e=JSON.parse(n);if((0,h.isObject)(e)&&(0,h.isArray)(e.configs)&&e.configs.every(e=>It(e)))return{projectConfigs:e.configs,globalConfig:e.globalConfig,configs:e.configs}}catch(e){H.info.defaultLog(`Cannot read jest config`,(0,h.getErrorMessage)(e)),H.info.defaultLog(`Failed reading jest config`,e,(0,h.getErrorMessage)(e));return}H.info.defaultLog(`Invalid jest config or config in not supported format`)},Rt=async()=>{let e=[Ue().getRootPath()],t=f.default.join(`node_modules`,`.prisma`,`client`,`index.d.ts`),n=e.map(e=>f.default.join(e,t)).map(e=>et.fromAbsolutePath(e));return(await(0,h.filterAsync)(n,e=>e.isFileExists())).map(e=>e.getAbsoluteFilePath())},zt=async()=>{try{let e=Ue().getRootPath();if(!(0,h.isDefined)(e))return[];let t=await(0,k.getSchemaWithPathOptional)(``,``,{cwd:e});if(!(0,h.isDefined)(t))return[];let n=t.schemas.map(e=>e[1]),r=new Set;for(let e of n){let n=(await(0,k.getConfig)({datamodel:e,ignoreEnvVarErrors:!0})).generators;for(let e of n)if((0,h.isDefined)(e.output?.value)){let n=f.default.join(f.default.resolve(t.schemaRootDir,e.output.value),`index.d.ts`);await et.fromAbsolutePath(n).isFileExists()&&r.add(n)}}return[...r]}catch(e){return H.error(`Failed to get prisma typings paths`,e),[]}},Bt=async()=>(await Promise.all([Rt(),zt()])).flat(),Vt=async(e,t=!1,n)=>{let r=`!**/node_modules/**`;if(t)return new E.Project({useInMemoryFileSystem:!0,compilerOptions:n});let i=st(e),a=Ht((0,f.dirname)(rt(e)),Ue().isSiblingFolderStructured());if(!i&&!(0,h.isDefined)(a)){let t=await Wt(e);if(!(0,h.isDefined)(t)||(0,h.isEmpty)(t))throw Error(`Cannot find source code path in jest config`);let n=new E.Project({compilerOptions:{allowJs:!0,maxNodeModuleJsDepth:0},useInMemoryFileSystem:!1});return n.addSourceFilesAtPaths([...t,r]),n}if(!i&&(0,h.isDefined)(a)){let t=new E.Project({tsConfigFilePath:a,compilerOptions:{allowJs:!0,maxNodeModuleJsDepth:0}}),n=await Wt(e);return t.addSourceFilesAtPaths([...n,r]),t}let o=new E.Project({tsConfigFilePath:a,compilerOptions:{maxNodeModuleJsDepth:0}}),s=await Bt();for(let e of s)o.addSourceFileAtPath(e);return o},Ht=(e,t)=>{let n;try{n=Ut(e)}catch{t&&(n=Ut((0,f.dirname)(e)))}return n},Ut=e=>{let t=e,n=/^(tsconfig|jsconfig).*\.json$/;for(;t!==(0,f.dirname)(t);){let e=(0,f.join)(t,`tsconfig.json`),r=(0,f.join)(t,`jsconfig.json`);if(!(0,w.existsSync)(t))return Ut((0,f.dirname)(t));if((0,w.existsSync)(e))return e;if((0,w.existsSync)(r))return r;let i=(0,w.readdirSync)(t);for(let e of i)if(n.test(e))return(0,f.join)(t,e);t=(0,f.dirname)(t)}},Wt=async e=>{let t=await Lt(e);if((0,h.isDefined)(t)){let e=t?.configs[0].roots.map(e=>f.default.join(e,`**/*.{ts,js,tsx,jsx}`));if(!(0,h.isEmpty)(e))return e}return[rt(ut(e))]};var Gt=l(Ie()),Kt=l(Le());let qt=`The ts-morph project is not initialized.`,Jt=new class{storage=new m.AsyncLocalStorage;_project;clear(){this._project=void 0}async init(e,t,n){let r=rt(e);if((0,h.isDefined)(this._project))return this._project.addSourceFileAtPathIfExists(r);this._project=await Vt(e,t,n);let i=this.storage.getStore();if((0,h.isDefined)(i))return this._project.addSourceFileAtPathIfExists(r)}add(e,t){let n=rt(e),r=this.storage.getStore()?.getProject();if(!(0,h.isDefined)(r))throw Error(qt);return r.createSourceFile(n,t,{overwrite:!0})}update(e,t){let n=this.get(e);return n.replaceWithText(t),n}addFile(e){(0,h.isDefined)(this._project)&&this._project.addSourceFileAtPathIfExists(e)}removeFile(e){if(!(0,h.isDefined)(this._project))return;let t=this._project.getSourceFile(e);(0,h.isDefined)(t)&&this._project.removeSourceFile(t)}async refreshFromFileSystem(e){if(!(0,h.isDefined)(this._project))return;let t=rt(e),n=this._project?.getSourceFile(e)??this._project?.getSourceFile(t);if((0,h.isDefined)(n)){let e=n.getFilePath();this._project.removeSourceFile(n),this._project.addSourceFileAtPath(e)}}get(e){let t=rt(e),n=this.storage.getStore()?.getProject();if(!(0,h.isDefined)(n))throw Error(qt+` store`);let r=n.getSourceFile(t);if(!(0,h.isDefined)(r))throw Error(`The source file is absent. ${e}`);return r}async save(e){await this.get(e).save()}async delete(e){await this.get(e).deleteImmediately()}getOrUndefined(e){let t=rt(e);return this._project?.getSourceFile(t)}withContext=(e,t,n)=>{let r=n.value,i=this.storage;if((0,h.isDefined)(i.getStore()))return n;let a=()=>this._project;return n.value=function(...e){let t={getProject:a};return i.run(t,()=>r.apply(this,e))},n}},Yt=Jt.withContext,Xt=async e=>{class t{async fn(){return e()}}(0,Kt.default)([Yt,(0,Gt.default)(`design:type`,Function),(0,Gt.default)(`design:paramtypes`,[]),(0,Gt.default)(`design:returntype`,Promise)],t.prototype,`fn`,null),await new t().fn()},Zt=e=>{let t=e?.asKind(E.SyntaxKind.ExpressionStatement)?.getExpression();if(!(0,h.isDefined)(t))return;let n=t.asKind(E.SyntaxKind.CallExpression)?.getArguments()?.at(-1),r=n?.asKind(E.SyntaxKind.ArrowFunction)?.getBody(),i=n?.asKind(E.SyntaxKind.FunctionExpression)?.getBody();return r?.asKind(E.SyntaxKind.Block)??i?.asKind(E.SyntaxKind.Block)},Qt=e=>E.Node.isExpressionStatement(e)&&e.getFirstChildByKind(E.SyntaxKind.CallExpression)?.getFirstChildByKind(E.SyntaxKind.Identifier)?.getText()===`describe`,$t=e=>e.getStatements().filter(e=>Qt(e)),en=e=>{let t=e.getExpression().getFirstChild()?.getText();return!(0,h.isDefined)(t)||(0,h.isEmpty)(t)?!1:Ot.some(e=>t.startsWith(e))},tn=e=>{let t=Zt(e);return(0,h.isDefined)(t)?t.getChildrenOfKind(E.SyntaxKind.ExpressionStatement).some(e=>en(e)):!1},nn=e=>{let t=Zt(e);return(0,h.isDefined)(t)?t.getChildrenOfKind(E.SyntaxKind.ExpressionStatement).filter(e=>Qt(e)&&tn(e)):[]},rn=e=>{let t=Zt(e);if((0,h.isDefined)(t))return t.getChildrenOfKind(E.SyntaxKind.ExpressionStatement).find(e=>Qt(e)&&tn(e))},an=e=>{let t=rn(e);return(0,h.isDefined)(t)},on=e=>{let t=Zt(e);if(!(0,h.isDefined)(t))return!0;let n=t.getChildrenOfKind(E.SyntaxKind.ExpressionStatement);if((0,h.isEmpty)(n))return!0;let r=new Set([`beforeEach`,`afterEach`,`beforeAll`,`afterAll`]);return n.every(e=>{let t=e.getExpressionIfKind(E.SyntaxKind.CallExpression)?.getExpressionIfKind(E.SyntaxKind.Identifier);return(0,h.isDefined)(t)?r.has(t.getText()):!1})},sn=e=>{if(e.isNamedExport?.())return kt.Named;if(e.isDefaultExport?.())return kt.Default;let t=e?.getParent();if((0,h.isDefined)(t)){if(t.isNamedExport?.())return kt.Named;if(t.isDefaultExport?.())return kt.Default}return e.isExportDefaultObject?.()??ln(e.getSourceFile(),e.getName?.())?kt.ObjectDefault:kt.NotExported},cn=(e,t)=>(0,h.isDefined)(e)?sn(e):(0,h.isDefined)(t)?t.isNamedImport?kt.Named:kt.Default:kt.Unknown;function ln(e,t){let[n]=e.getExportAssignments()??[];return n?.getDescendantsOfKind(E.SyntaxKind.Identifier).some(e=>(e.getSymbol()?.getEscapedName()??e.getText())===t)}function un(e,t){let n=$t(Jt.get(e)),r=n.find(e=>e.getText().includes(t))??n[0],i=nn(r),a=[],o=(0,h.isEmpty)(i)?[r]:i;for(let e of o){let t=Zt(e);(0,h.isDefined)(t)&&a.push(...t.getChildrenOfKind(E.SyntaxKind.ExpressionStatement).filter(e=>en(e)))}return a}let dn=e=>e.getFirstDescendantByKind(E.SyntaxKind.StringLiteral)?.getLiteralValue(),W=e=>dn(e),fn=e=>dn(e),pn=(e,t)=>{let n=e.getFullText().slice(0,Math.max(0,t)).split(`
|
|
32006
32006
|
`);return{line:n.length,column:(n.at(-1)?.length??0)+1}},mn=(e,t)=>{let n=t.getStart(),r=t.getEnd(),{line:i,column:a}=pn(e,n),{line:o,column:s}=pn(e,r);return{startLine:i,startColumn:a,startIndex:n,endLine:o,endColumn:s,endIndex:r}},hn=e=>e.getDescendantsOfKind(E.SyntaxKind.ExpressionStatement).filter(e=>en(e)),gn=(e,t,n,r)=>{let i=r?`.tsx`:`.ts`,a=t+Date.now()+(0,y.randomUUID)()+i;return e.createSourceFile(a,n)},_n=e=>e.getDescendantsOfKind(E.SyntaxKind.CallExpression).reduce((e,t)=>{let n=t.getExpression(),r=n.getParentIfKind(E.SyntaxKind.VariableDeclaration);return(0,h.isDefined)(r)&&n.getText()===`require`&&e.push(r),e},[]),vn=e=>{let t=e.getFirstChildByKind(E.SyntaxKind.CallExpression);if(!(0,h.isDefined)(t))return;let[n]=t.getArguments();if(!(!(0,h.isDefined)(n)||n.getKind()!==E.SyntaxKind.StringLiteral))return n.getText().slice(1,-1)},yn=e=>{let t=[`${Ue().getEarlyTestFilenameSuffix()}.ts`,`.test.ts`,`.spec.ts`,`.test.tsx`,`.spec.tsx`,`.test.js`,`.spec.js`,`.test.jsx`,`.spec.jsx`],n=e.getFilePath(),r=`_`+(0,y.randomUUID)()+`_temp`;for(let e of t)if(n.endsWith(e))return n.slice(0,-e.length)+r+e;let i=n.split(`.`);return i[i.length-2]+=r,i.join(`.`)},bn=(e,t=e.getFullText())=>{let n=yn(e);return e.getProject().createSourceFile(n,t)},xn=e=>e.getSymbol()?.getDeclarations()?.[0]?.getSourceFile()??e.getAliasSymbol()?.getDeclarations()?.[0]?.getSourceFile(),Sn=(e,t)=>{let n=e.getRelativePathTo(t.getFilePath());n=n.replaceAll(`\\`,`/`);let r=f.default.extname(n);return n=n.replaceAll(r,``),n.startsWith(`.`)||(n=`./`+n),n},Cn=[E.SyntaxKind.JsxElement,E.SyntaxKind.JsxOpeningElement,E.SyntaxKind.JsxClosingElement,E.SyntaxKind.JsxExpression,E.SyntaxKind.JsxSelfClosingElement,E.SyntaxKind.JsxAttributes,E.SyntaxKind.JsxAttribute,E.SyntaxKind.JsxFragment,E.SyntaxKind.JsxOpeningFragment,E.SyntaxKind.JsxClosingFragment,E.SyntaxKind.JsxNamespacedName,E.SyntaxKind.JsxSpreadAttribute,E.SyntaxKind.JsxText,E.SyntaxKind.JsxTextAllWhiteSpaces],wn=e=>Cn.some(t=>(0,h.isDefined)(e.getFirstDescendantByKind(t))),G=e=>Cn.some(t=>(0,h.isDefined)(e.getParentIfKind(t))),Tn=e=>{let t=e.compilerType;if(`id`in t&&(0,h.isNumber)(t.id)){let e=t.id;return e===0?null:e}return null},En=new Set(`withRouter.connect.withAuth.withStyles.withTheme.forwardRef.styled.withErrorBoundary.withSuspense.withProps.withState.withHandlers.withContext.withApollo.withRedux.withIntl.withTranslation.withFormik.withViewport.withLogger.withMemo.withDefaults.withReduxForm.withPermissions.withData.withTracker.withServices.withFirebase.withNavigation.withHeader.withFooter`.split(`.`)),Dn=`anonymousFunction`;var On=class{exportedDeclarations;constructor(e,t){this.sourceFile=e,this.moduleInfo=t;let n=this.moduleInfo.getExports();this.exportedDeclarations=[n.defaultExport,...n.namedExports].filter(Boolean)}getAllTestables(){return[...this.getClassesWithMethods(),...this.getFunctionsDeclarations(),...this.getFunctionsExpressions(),...this.getArrowFunctionsExpressions(),...this.getHOCs(),...this.getObjectMethods()]}getAllSerializedTestables(){return this.getAllTestables().map(e=>(0,h.removeNestedField)(e,[`node`,`parent`]))}getAllMethodsCount(){return this.getAllTestables().filter(e=>e.type!==`class`).length}getHOCs(){return this.sourceFile.getVariableStatements().filter(e=>{let t=e.getFirstDescendantByKind(E.SyntaxKind.CallExpression),n=t?.getFirstDescendantByKind(E.SyntaxKind.PropertyAccessExpression),r=t?.getFirstDescendantByKind(E.SyntaxKind.Identifier);return[n?.getText(),r?.getText()].some(e=>(0,h.isDefined)(e)?[...En.values()].some(t=>e.includes(t)):!1)}).map(e=>{let t=e.getFirstDescendantByKind(E.SyntaxKind.VariableDeclaration)?.getFirstChildByKind(E.SyntaxKind.Identifier)?.getText(),n=this.isEntityExported(t)||e.isExported();return{...this.getLocationPivot(e),name:t,type:`function`,node:e,canCreateTests:n}})}getFunctionsDeclarations(){return this.sourceFile.getFunctions().map(e=>{let t=e.getName()??Dn,n=this.isEntityExported(t)||e.isExported();return{...this.getLocationPivot(e),name:t,type:`function`,node:e,canCreateTests:n}})}getFunctionsExpressions(){return this.sourceFile.getDescendantsOfKind(E.SyntaxKind.FunctionExpression).filter(e=>e.getParentIfKind(E.SyntaxKind.ExportAssignment)?.isExportEquals()??!(this.isCallbackFunction(e)||this.isInnerFunction(e)||this.isJSXFunction(e))).map(e=>{let t=e.getName()??this.getArrowFunctionName(e)??Dn,n=this.isEntityExported(t);return{...this.getLocationPivot(e),name:t,type:`function`,node:e,canCreateTests:n}})}getArrowFunctionsExpressions(){return this.sourceFile.getDescendantsOfKind(E.SyntaxKind.ArrowFunction).filter(e=>e.getParentIfKind(E.SyntaxKind.ExportAssignment)?.isExportEquals()??!(this.isCallbackFunction(e)||this.isInnerFunction(e)||this.isJSXFunction(e))).map(e=>{let t=this.getArrowFunctionName(e)??Dn,n=this.isEntityExported(t)||this.isEntityExportedWithThis(e);return{...this.getLocationPivot(e),name:t,type:`function`,node:e,canCreateTests:n}})}isCallbackFunction(e){return e.getParent()?.getKind()===E.SyntaxKind.CallExpression}isJSXFunction(e){return G(e)}isInnerFunction(e){let t=e.getParent(),n=0;for(;(0,h.isDefined)(t)&&t.getKind()!==E.SyntaxKind.SourceFile&&n<20;){if(t.getKind()===E.SyntaxKind.ArrowFunction)return!0;t=t.getParent(),n++}return!1}getArrowFunctionName(e){let t=e.getParent();if(t?.getKind()===E.SyntaxKind.BinaryExpression&&t?.getFirstChild()?.getKind()===E.SyntaxKind.PropertyAccessExpression)return e.getParent()?.getFirstChildByKind(E.SyntaxKind.PropertyAccessExpression)?.getName();let n=e.getFirstAncestorByKind(E.SyntaxKind.VariableDeclaration);if((0,h.isDefined)(n))return n.getName();let r=e.getFirstAncestorByKind(E.SyntaxKind.PropertyAssignment);if((0,h.isDefined)(r))return r.getName()}getClasses(){return this.sourceFile.getClasses().map(e=>{let t=e.getName(),n=this.isEntityExported(t)||e.isDefaultExport(),r=n?this.getClassMethods(e,n).some(e=>e.canCreateTests):!1;return{...this.getLocationPivot(e),name:t,type:`class`,node:e,canCreateTests:r}})}getClassesWithMethods(){return this.getClasses().flatMap(e=>[e,...this.getClassMethods(e.node,e.canCreateTests)])}getClassMethods(e,t){return e.getMethods().map(n=>{let r=n.hasModifier(E.SyntaxKind.PrivateKeyword),i=n.getName().startsWith(`#`),a=r||i;return{...this.getLocationPivot(n),parent:e,parentName:e.getName()??``,type:`method`,node:n,name:n.getName(),canCreateTests:t&&!a}})}getObjectMethods(){let e=this.sourceFile.getDescendantsOfKind(E.SyntaxKind.BinaryExpression).map(e=>e.getRight()).filter(e=>E.Node.isObjectLiteralExpression(e)),t=this.sourceFile.getExportAssignments().map(e=>e.getExpression()).filter(e=>E.Node.isObjectLiteralExpression(e));return[...e,...t].flatMap(e=>e.getProperties()).filter(e=>E.Node.isMethodDeclaration(e)).map(e=>({...this.getLocationPivot(e),type:`object-method`,node:e,name:e.getName(),canCreateTests:!0}))}getLocationPivot(e){return mn(this.sourceFile,e)}isEntityExported(e){return(0,h.isDefined)(e)&&!(0,h.isEmpty)(e)?this.exportedDeclarations.includes(e):!1}isEntityExportedWithThis(e){let t=e.getParent()?.getChildren()??[];return t[0]?.getFirstChild()?.getKind()===E.SyntaxKind.ThisKeyword&&t[1]?.getKind()===E.SyntaxKind.EqualsToken&&t[2]===e}findTestable(e,t,n){return this.getAllTestables().find(r=>r.name===t&&r.type===e?r.type===`method`?r.parentName===n:!0:!1)}};let kn=`default`;var An=class{constructor(e,t){this.sourceFile=e,this.isUsingJSX=t}getImports(){return[...this.getESMImportsNodes(),...this.getCJSImportsNodes()].map(e=>({name:`Import`,location:mn(this.sourceFile,e),node:e,type:`import`,sourceValue:(E.Node.isImportDeclaration(e)?e.getModuleSpecifierValue():e.getFirstDescendantByKind(E.SyntaxKind.StringLiteral)?.getLiteralValue())??``}))}getCJSImportsNodes(){return this.sourceFile.getVariableStatements().filter(e=>(e.getFirstDescendantByKind(E.SyntaxKind.CallExpression)?.getExpression())?.getText()===`require`)}getESMImportsNodes(){return this.sourceFile.getImportDeclarations()}isESM(){let e=this.sourceFile.getImportDeclarations().length>0,t=this.sourceFile.getExportDeclarations().length>0||this.sourceFile.getExportedDeclarations().size>0,n=this.sourceFile.getDescendantsOfKind(E.SyntaxKind.ExportAssignment).length>0;return e||t||n}getCJSExports(){let e=[],t=``,n=`module.exports`,r=`exports`;for(let i of this.sourceFile.getDescendantsOfKind(E.SyntaxKind.ExpressionStatement)){let a=i.getExpression(),o=a.getText().trim(),s=a.asKind(E.SyntaxKind.BinaryExpression);if(!o.startsWith(n)&&!o.startsWith(r)||!(0,h.isDefined)(s))continue;let c=s.getLeft(),l=c.getText(),u=c.asKind(E.SyntaxKind.PropertyAccessExpression),d=u?.getName()??``,f=c.getKind()===E.SyntaxKind.PropertyAccessExpression,p=s.getRight(),m=f&&u?.getExpression().getText()===n,g=f&&u?.getExpression().getText()===r;if(m&&d===kn){t=p.getText();continue}if(m||g){e.push(d);continue}if(l!==n)continue;let _=t=>{let n=t.asKind(E.SyntaxKind.ObjectLiteralExpression);if((0,h.isDefined)(n))for(let t of n.getProperties()){if(t.getKind()===E.SyntaxKind.PropertyAssignment||t.getKind()===E.SyntaxKind.ShorthandPropertyAssignment||t.getKind()===E.SyntaxKind.MethodDeclaration){let n=t.getName();e.push(n)}if(t.getKind()===E.SyntaxKind.PropertyAssignment){let e=t.getInitializer();(0,h.isDefined)(e)&&_(e)}}},v=t=>{let n=t.asKind(E.SyntaxKind.FunctionDeclaration)?.getBody()?.asKind(E.SyntaxKind.Block);if((0,h.isDefined)(n))for(let t of n.getStatements()){let n=((t.asKind(E.SyntaxKind.ExpressionStatement)?.getExpression())?.asKind(E.SyntaxKind.BinaryExpression)?.getLeft())?.asKind(E.SyntaxKind.PropertyAccessExpression);n?.getExpression().getKind()===E.SyntaxKind.ThisKeyword&&e.push(n.getName())}},y=t=>{let n=t.asKind(E.SyntaxKind.FunctionDeclaration)?.getName();if((0,h.isDefined)(n))for(let t of this.sourceFile.getStatements()){let r=((t.asKind(E.SyntaxKind.ExpressionStatement)?.getExpression())?.asKind(E.SyntaxKind.BinaryExpression)?.getLeft())?.asKind(E.SyntaxKind.PropertyAccessExpression);r?.getExpression().getText()===`${n}.prototype`&&e.push(r.getName())}};if(p.getKind()===E.SyntaxKind.ObjectLiteralExpression){_(p);continue}if(p.getKind()===E.SyntaxKind.Identifier){let t=p.asKind(E.SyntaxKind.Identifier),n=t?.findReferences().map(e=>e.getDefinition().getNode().getParent()).filter(e=>(0,h.isDefined)(e)).filter(e=>e.getKind()===E.SyntaxKind.VariableDeclaration);if(!(0,h.isDefined)(n))continue;for(let t of n){let n=t.getInitializer()?.asKind(E.SyntaxKind.ObjectLiteralExpression);if((0,h.isDefined)(n)){for(let t of n.getProperties())if(t.getKind()===E.SyntaxKind.PropertyAssignment||t.getKind()===E.SyntaxKind.ShorthandPropertyAssignment){let n=t.getName();e.push(n)}}}let r=t?.findReferences().map(e=>e.getDefinition().getNode().getParent()).filter(e=>e?.getKind()===E.SyntaxKind.FunctionDeclaration);if(!(0,h.isDefined)(r))continue;for(let e of r)v(e),y(e)}if(p.isKind(E.SyntaxKind.NewExpression)){let e=p.asKind(E.SyntaxKind.NewExpression);(0,h.isDefined)(e)&&(t=e.getExpression().getText());continue}t=p.getText()}return{namedExports:e,defaultExport:t}}getESMExports(){let e=``,t=[],n=!1;for(let r of this.sourceFile.getExportAssignments()){r.isExportEquals()||(n=!0);let i=r.getExpression();if(i.getKind()===E.SyntaxKind.Identifier){e=i.getText();continue}let a=r.getFirstChildByKind(E.SyntaxKind.ObjectLiteralExpression);if((0,h.isDefined)(a)){for(let e of a.getProperties())if(e.getKind()===E.SyntaxKind.PropertyAssignment||e.getKind()===E.SyntaxKind.ShorthandPropertyAssignment||e.getKind()===E.SyntaxKind.MethodDeclaration){let n=e.getName();t.push(n)}}}let r=this.sourceFile.getExportedDeclarations();if(!(n&&r.size===1&&[...r.keys()][0]===kn))for(let[n,i]of r)if(n===kn){let t=(i[0]?.getFirstChildByKind(E.SyntaxKind.Identifier))?.getText()?.trim()??Dn;(0,h.isDefined)(t)&&(e=t)}else t.push(n);return{defaultExport:e,namedExports:t}}hasRequire(){return this.sourceFile.getDescendantsOfKind(E.SyntaxKind.CallExpression).some(e=>e.getExpression().getText()===`require`)}transformRequiresToImports(){let e=gn(this.sourceFile.getProject(),`transformRequiresToImports`,this.sourceFile.getFullText(),this.isUsingJSX),t;try{let n=e.getVariableStatements();for(let e of n){let t=e.getFirstDescendantByKind(E.SyntaxKind.CallExpression),n=t?.getExpression();if(!(0,h.isDefined)(t)||!(0,h.isDefined)(n)||n.getText()!==`require`)continue;let r=t.getFirstDescendantByKind(E.SyntaxKind.StringLiteral)?.getLiteralValue();if(!(0,h.isDefined)(r))continue;let i=e.getDeclarations()?.[0]?.getNameNode()?.getText();if(!(0,h.isDefined)(i))continue;let a=`import ${i} from "${r}";`;e.replaceWithText(a)}t=e.getFullText()}finally{e.getProject().removeSourceFile(e)}return t}getExports(){return this.isESM()?this.getESMExports():this.getCJSExports()}},jn=class{tests;constructor(e){this.sourceFile=e}getDescribes(){return $t(this.sourceFile).map(e=>{let t=W(e);return(0,h.isDefined)(t)?{node:e,name:t,location:mn(this.sourceFile,e),type:`describe`}:null}).filter(e=>(0,h.isDefined)(e))}getTests(){return(0,h.isDefined)(this.tests)||(this.tests=hn(this.sourceFile).map(e=>{let t=mn(this.sourceFile,e),n=fn(e);return(0,h.isDefined)(n)?{node:e,name:n,location:t,type:`test`}:null}).filter(e=>(0,h.isDefined)(e))),this.tests}getDescribeTests(e){return hn(e.node).map(e=>{let t=fn(e);return(0,h.isDefined)(t)?{node:e,name:t,location:mn(this.sourceFile,e),type:`test`}:null}).filter(e=>(0,h.isDefined)(e))}},Mn=class{sourceFile;tests;testables;moduleInfo;constructor(e,t){this.filePath=t;let n=!0;try{let t=new E.Project({useInMemoryFileSystem:!0,skipAddingFilesFromTsConfig:!0,skipFileDependencyResolution:!0,skipLoadingLibFiles:!0}),r=gn(t,`ast`,e,!0);wn(r)?this.sourceFile=r:(t.removeSourceFile(r),this.sourceFile=gn(t,`ast`,e,!1),n=!1)}catch{throw Error(`Cannot parse file content`)}this.moduleInfo=new An(this.sourceFile,n),this.testables=new On(this.sourceFile,this.moduleInfo),this.tests=new jn(this.sourceFile)}isReactFile(){let e=(0,f.extname)(this.filePath??this.sourceFile.getFilePath());return Dt.includes(e)||this.isFileContainsImport(`react`)}isFileContainsImport(e){return this.moduleInfo.getImports().some(t=>t.sourceValue.includes(e))}checkIsJSDoc(e,t,n){return t===E.SyntaxKind.MultiLineCommentTrivia?e.slice(n,n+3)===`/**`&&e.slice(n,n+5)!==`/***/`:!1}getLineRange(e,t){let n=this.sourceFile.compilerNode,r=n.getLineStarts(),{line:i}=n.getLineAndCharacterOfPosition(e),{line:a}=n.getLineAndCharacterOfPosition(t);return{start:r[i]??0,end:r[a+1]??this.sourceFile.getEnd()}}stripComments(e=()=>!0){let t=new Set,n=[],r=this.sourceFile.getFullText(),i=(e,r)=>{for(let i of[...e.getLeadingCommentRanges(),...e.getTrailingCommentRanges()]){let e=i.getPos(),a=i.getEnd(),o=e+`,`+a;if(t.has(o))continue;t.add(o);let s=i.getText(),c=this.checkIsJSDoc(r,i.getKind(),e);n.push({start:e,end:a,text:s,width:i.getWidth(),isJSDoc:c})}};i(this.sourceFile,r),this.sourceFile.forEachDescendant(e=>i(e,r));let a=n.filter(e).map(e=>{let{start:t,end:n}=this.getLineRange(e.start,e.end);return(0,h.isEmpty)(r.slice(t,e.start).trim())&&(0,h.isEmpty)(r.slice(e.end,n).trim())?{start:t,end:n}:{start:e.start,end:e.end}}).toSorted((e,t)=>t.start-e.start);for(let e of a)this.sourceFile.removeText(e.start,e.end);return this.sourceFile.getFullText()}};let Nn=e=>{let{node:t,parent:n,...r}=e;return r};var Pn=class{GITIGNORE_FILE_NAME=`.gitignore`;gitignorePath;constructor(e){this.gitignorePath=(0,f.join)(e,this.GITIGNORE_FILE_NAME)}async add(e){try{let t=await p.default.readFile(this.gitignorePath,`utf8`);t.includes(e)||await p.default.writeFile(this.gitignorePath,`${t}\n${e}`)}catch(e){let t=e instanceof Error?e.message:`Unknown error`;H.info.defaultLog(`Error reading gitignore file`,{message:t})}}};let Fn=`.early.coverage`;var In=class{getCoverageDirectoryPath(){let e=Ue().getRootPath();return f.default.join(e,Fn,`v8`)}getCoverageDirectoryForCommand(){return this.getCoverageDirectoryPath()}getExecutionCwd(){return Ue().getRootPath()}},Ln=class extends In{getCoverageDirectoryForCommand(){let e=Ue().getGitTopLevel(),t=Ue().getRootPath(),n=f.default.relative(e,t);return f.default.join(n,Fn,`v8`)}};function Rn(){let e=Ue().getCoverageCommand()?.split(/\s+/).includes(`nx`)??!1;return H.info.defaultLog(`Coverage path strategy: `+(e?`nx`:`standard`)),e?new Ln:new In}var zn=class{report={};constructor(e,t){for(let[n,r]of Object.entries(e)){let e=f.default.normalize(n);if(e.toLowerCase().startsWith(t.toLowerCase())){let n=e.slice(t.length);this.report[n]=r}}}getEntries(){return Object.entries(this.report)}getStatsForTestable(e,t,n){let r=this.report[e];if(!(0,h.isDefined)(r))return null;let i=this.findFunctionDefinition(t,r.fnMap,n);if(!(0,h.isDefined)(i))return null;let a=0,o=0;for(let[e,t]of Object.entries(r.statementMap))if(this.isStatementInFunction(t,i)||this.isFunctionInStatement(t,i)){o++;let t=r.s[e];(0,h.isDefined)(t)&&t>0&&a++}return{percentage:this.toPercentage(a,o),totalStatements:o,coveredStatements:a}}getStatsForFile(e){let t=this.report[e];if(!(0,h.isDefined)(t))return{percentage:null,totalStatements:0,coveredStatements:0};let n=0,r=0;for(let[e]of Object.entries(t.statementMap)){r++;let i=t.s[e];(0,h.isDefined)(i)&&i>0&&n++}return{percentage:this.toPercentage(n,r),totalStatements:r,coveredStatements:n}}getStatsForDirectory(e){let t=0,n=0;for(let[r,i]of Object.entries(this.report))if(this.isSubdirectory(e,r)){n+=Object.keys(i.statementMap).length;for(let[e]of Object.entries(i.statementMap)){let n=i.s[e];(0,h.isDefined)(n)&&n>0&&t++}}return{percentage:this.toPercentage(t,n),totalStatements:n,coveredStatements:t}}calculateCoverageForFiles(e){let t=0,n=0,r=new Set(e.map(e=>this.normalizeFilePath(e)));for(let[e,i]of Object.entries(this.report)){let a=this.normalizeFilePath(e);if(r.has(a)){let e=Object.keys(i.statementMap).length;t+=e;for(let[e]of Object.entries(i.statementMap)){let t=i.s[e];(0,h.isDefined)(t)&&t>0&&n++}}}return{percentage:this.toPercentage(n,t),totalStatements:t,coveredStatements:n}}normalizeFilePath(e){return e.startsWith(`/`)?e.slice(1):e}isSubdirectory(e,t){let n=f.default.relative(e,t);return(0,h.isDefined)(n)?!n.startsWith(`..`)&&!f.default.isAbsolute(n):!1}isStatementInFunction(e,t){return!(e.start.line<t.loc.start.line||e.end.line>t.loc.end.line||e.start.line===t.loc.start.line&&e.start.column<t.loc.start.column||e.end.line===t.loc.end.line&&e.end.column>t.loc.end.column)}isFunctionInStatement(e,t){return!(t.loc.start.line<e.start.line||t.loc.end.line>e.end.line||t.loc.start.line===e.start.line&&t.loc.start.column<e.start.column||t.loc.end.line===e.end.line&&t.loc.end.column>e.end.column)}findFunctionDefinition(e,t,n){for(let[,n]of Object.entries(t))if(n.name===e)return n;return null}toPercentage(e,t,n=0){if(t===0)return null;let r=e/t;return Number(Math.round(r*100).toFixed(n))}};async function Bn(e){let t=Ue().getRootPath(),n=[];try{let e=new et(`.gitignore`);await e.isFileExists()&&(n=(await e.getText()).split(`
|
|
32007
32007
|
`).map(e=>e.trim()).filter(e=>(0,h.isDefined)(e)&&!e.startsWith(`#`)))}catch{}let r=[`node_modules`,`*.config.ts`,`**/*.mock.ts`,`**/*.mocks.ts`,`**/*.test.ts`,`**/*.spec.ts`,...n];return(await(0,A.default)(e,{cwd:t,absolute:!0,ignore:r})).map(e=>`/${f.default.relative(t,e)}`)}var Vn=class{nextSource=null;setNext(e){return this.nextSource=e,e}async getFromNext(e){return this.nextSource?this.nextSource.getFiles(e):[]}},Hn=class extends Vn{async getFiles(e){return Bn(`**/*.{js,ts,jsx,tsx}`)}};let Un=/\.[jt]sx?$/;var Wn=class extends Vn{async getFiles(e){let t=Object.keys(e).filter(e=>Un.test(e));return t.length>0?t:this.getFromNext(e)}};function Gn(){let e=new Wn,t=new Hn;return e.setNext(t),e}let Kn=String.raw`.*\.early\.(spec|test)\.[tj]sx?$`;var qn=class{EXEC_TIMEOUT_IN_MS=12e5;MAX_BUFFER_SIZE=2e4*1024;DEFAULT_ROOT_PATH=`/`;COVERAGE_ROOT_DIRECTORY_NAME=`.early.coverage`;COVERAGE_REPORT_FILE_NAME=`coverage-final.json`;pathStrategy=null;async init(){this.pathStrategy=Rn()}getCoverageDirectoryPath(){if(!(0,h.isDefined)(this.pathStrategy))throw Error(`Provider not initialized. Call init() first.`);return this.pathStrategy.getCoverageDirectoryPath()}getCoverageDirectoryForCommand(){if(!(0,h.isDefined)(this.pathStrategy))throw Error(`Provider not initialized. Call init() first.`);return this.pathStrategy.getCoverageDirectoryForCommand()}getExecutionCwd(){if(!(0,h.isDefined)(this.pathStrategy))throw Error(`Provider not initialized. Call init() first.`);return this.pathStrategy.getExecutionCwd()}getCoverageReportPath(){return f.default.join(this.getCoverageDirectoryPath(),this.COVERAGE_REPORT_FILE_NAME)}async getCommand(){return(Ue().getCoverageCommand()??await this.buildJestCoverageCommand()).replaceAll(we,this.getCoverageDirectoryForCommand())}async isReportExists(){try{return await p.default.access(this.getCoverageReportPath(),p.constants.R_OK),!0}catch{return!1}}async removeReport(){try{let e=et.fromAbsolutePath(this.getCoverageReportPath());await e.isFileExists()&&await e.delete()}catch(e){H.error(`Error removing coverage report`,e)}}async getReport(){try{let e=await et.fromAbsolutePath(this.getCoverageReportPath()).getText(),t=JSON.parse(e);return this.calculateCoverage(t)}catch{throw Error(`Coverage report file could not be read: ${this.getCoverageReportPath()}`)}}async generateReport(){H.info.defaultLog(`Coverage: generation started`),await this.removeReport();let e=await this.getCommand();H.info.defaultLog(`Coverage command: ${e}`);try{await Nt(e,{cwd:this.getExecutionCwd(),timeout:this.EXEC_TIMEOUT_IN_MS,maxBuffer:this.MAX_BUFFER_SIZE}),H.info.defaultLog(`Coverage command generation success`)}catch(t){let n=t instanceof Error&&`code`in t?{code:t.code,signal:t.signal,killed:t.killed}:{code:`UNKNOWN_ERROR`};throw H.info.defaultLog(`Coverage generation exited with error: "${e}".`,n),Error(`Failed to generate coverage report: ${t.message}\nCoverage command: "${e}"`)}finally{await new Pn(Ue().getGitTopLevel()).add(this.COVERAGE_ROOT_DIRECTORY_NAME)}}calculateCoverage(e){let t=new zn(e,f.default.normalize(Ue().getRootPath()).toLowerCase()),n=new Map;for(let[e,r]of t.getEntries()){let i=t.getStatsForFile(e),a=e.split(`/`).slice(0,-1);for(;a.length>0;){let e=a.join(`/`)||this.DEFAULT_ROOT_PATH;if(!n.has(e)){let r=t.getStatsForDirectory(e);n.set(e,{percentage:r.percentage,totalStatements:r.totalStatements,coveredStatements:r.coveredStatements})}a.pop()}let o=[];for(let{name:n}of Object.values(r.fnMap)){let r=t.getStatsForTestable(e,n);o.push({name:n,percentage:r?.percentage??null,totalStatements:r?.totalStatements??null,coveredStatements:r?.coveredStatements??null})}n.set(e,{percentage:i.percentage,totalStatements:i.totalStatements,coveredStatements:i.coveredStatements,testables:o})}return Object.fromEntries(n.entries())}async hasJestConfig(){let e=Ft(Ue().getRootPath());return(0,h.isDefined)(e)}async buildJestCoverageCommand(){let e=[`node_modules`,`dist`];Ue().getIncludeEarlyTests()||e.push(Kn);let t=e.map(e=>`"${e}"`).join(` `),n=Ue().getRootPath();return await this.hasJestConfig()?`npx jest --coverage --coverageProvider=v8 --coveragePathIgnorePatterns ${t} --coverageReporters=json --coverageDirectory=${we} --silent --passWithNoTests --maxWorkers=2`:`npx jest --coverage --coverageProvider=v8 --coveragePathIgnorePatterns ${t} --coverageReporters=json --coverageDirectory=${we} --rootDir="${n}" --silent --passWithNoTests --maxWorkers=2`}async getCoverageTree(e){let t=await Gn().getFiles(e),n=new Map;for(let r of t){let t=new Mn(await new et(r).getText(),`getCoverageTree`).testables.getAllTestables(),i=r.split(`/`).slice(0,-1);for(;!(0,h.isEmpty)(i);){let t=i.join(`/`)||this.DEFAULT_ROOT_PATH,r=e[t];n.has(t)||n.set(t,{percentage:r?.percentage??null,totalStatements:r?.totalStatements??null,coveredStatements:r?.coveredStatements??null}),i.pop()}let a=[],o=t.map(e=>Nn(e)),s=e[r];for(let e of o){let{name:t}=e;if(!(0,h.isDefined)(t))continue;let n=e.type===`method`?e.parentName:void 0,r=s?.testables?.find(e=>e.name===t),i={name:t,...(0,h.isDefined)(n)&&{parentName:n},percentage:r?.percentage??null,totalStatements:r?.totalStatements??null,coveredStatements:r?.coveredStatements??null};a.push(i)}n.set(r,{percentage:s?.percentage??null,totalStatements:s?.totalStatements??null,coveredStatements:s?.coveredStatements??null,testables:a})}return Object.fromEntries(n.entries())}getCoverageForFiles(e,t){let n=0,r=0,i=new Set(e.map(e=>this.normalizeFilePath(e)));for(let[e,a]of Object.entries(t)){let t=this.normalizeFilePath(e);i.has(t)&&(n+=a.totalStatements??0,r+=a.coveredStatements??0)}return{percentage:this.toPercentage(r,n),totalStatements:n,coveredStatements:r}}normalizeFilePath(e){return e.startsWith(`/`)?e.slice(1):e}toPercentage(e,t,n=0){if(t===0)return null;let r=e/t;return Number(Math.round(r*100).toFixed(n))}},Jn=class extends zn{constructor(e,t){super(e,t)}findFunctionDefinition(e,t,n){for(let r of Object.values(t))if(r.name===e||(0,h.isDefined)(n)&&r.name.startsWith(`(anonymous`)&&r.loc.start.line===n)return r;return null}};let Yn=`npx vitest run --coverage.enabled --coverage.exclude="${Kn}" --coverage.reportsDirectory=${we} --coverage.reportOnFailure=true --coverage.reporter=json --maxWorkers=2 --passWithNoTests`;var Xn=class extends qn{async init(){await super.init()}async getCommand(){return(Ue().getCoverageCommand()??Yn).replaceAll(we,this.getCoverageDirectoryForCommand())}async getReport(){try{let e=await et.fromAbsolutePath(this.getCoverageReportPath()).getText(),t=JSON.parse(e);return await this.calculateCoverageWithVitest(t)}catch{throw Error(`Coverage report file could not be read: ${this.getCoverageReportPath()}`)}}async calculateCoverageWithVitest(e){let t=f.default.normalize(Ue().getRootPath()).toLowerCase(),n=new Jn(e,t),r=this.buildAbsolutePathMap(e,t),i=[...n.getEntries()];return this.processEntries(i,n,r)}buildAbsolutePathMap(e,t){let n=new Map;for(let r of Object.keys(e)){let e=f.default.normalize(r);if(e.toLowerCase().startsWith(t.toLowerCase())){let i=e.slice(t.length);n.set(i,r)}}return n}async processEntries(e,t,n){let r=new Map;for(let[i]of e)this.addDirectoryCoverage(i,t,r),await this.addFileCoverage(i,t,n,r);return Object.fromEntries(r.entries())}addDirectoryCoverage(e,t,n){let r=e.split(`/`).slice(0,-1);for(;r.length>0;){let e=r.join(`/`)||`/`;if(!n.has(e)){let r=t.getStatsForDirectory(e);n.set(e,{percentage:r.percentage,totalStatements:r.totalStatements,coveredStatements:r.coveredStatements})}r.pop()}}async addFileCoverage(e,t,n,r){let i=t.getStatsForFile(e),a=n.get(e);if(!(0,h.isDefined)(a))return;let o=await this.readFileText(a);if(!(0,h.isDefined)(o)){r.set(e,{percentage:i.percentage,totalStatements:i.totalStatements,coveredStatements:i.coveredStatements,testables:[]});return}let s=this.extractTestables(o,e,t);r.set(e,{percentage:i.percentage,totalStatements:i.totalStatements,coveredStatements:i.coveredStatements,testables:s})}async readFileText(e){try{return await et.fromAbsolutePath(e).getText()}catch{return null}}extractTestables(e,t,n){let r=new Mn(e,`getReport`).testables.getAllTestables(),i=[];for(let e of r){let r=e.name??``,a=e.type===`method`?e.parentName:void 0,o=n.getStatsForTestable(t,r,e.startLine);i.push({name:r,...(0,h.isDefined)(a)&&{parentName:a},percentage:o?.percentage??null,totalStatements:o?.totalStatements??null,coveredStatements:o?.coveredStatements??null})}return i}},Zn=function(e){return e.JEST=`jest`,e.VITEST=`vitest`,e}(Zn||{}),Qn=class{provider=null;async create(){let e=await this.detectProjectType();return H.info.defaultLog(`Coverage: project type`,e),e===Zn.JEST?this.provider=new qn:e===Zn.VITEST&&(this.provider=new Xn),this.provider&&await this.provider.init(),H.info.defaultLog(`Coverage Provider: `+(e??`null`)),this.provider}async detectProjectType(){return await this.checkFileExists([`vitest.config.ts`,`vitest.config.js`])?Zn.VITEST:await this.checkFileExists([`package.json`,`jest.config.js`,`jest.config.ts`,`tsconfig.json`])?Zn.JEST:null}async checkFileExists(e){H.info.defaultLog(`Coverage: checking files`,e);for(let t of e)if(await new et(t).isFileExists())return!0;return!1}};let $n={};var er=class{provider=null;coverage=null;async init(){(0,h.isDefined)(this.provider)||(this.provider=await new Qn().create())}async consumeReport(){if((0,h.isDefined)(this.provider))try{this.coverage=await this.provider.getReport(),await this.provider.removeReport()}catch(e){H.info.defaultLog(`Error reading coverage report`,{error:e})}}async generateCoverage(){if(!(0,h.isDefined)(this.provider))return $n;try{await this.provider.generateReport()}catch(e){let t=await this.provider.isReportExists();if(!Ue().shouldContinueOnTestErrors()||!t)throw e;H.info.defaultLog(`Coverage: report exists but test command failed, continuing...`)}let e=null;try{await this.consumeReport()}catch(t){e=t instanceof Error?t:Error(String(t))}if(!(0,h.isDefined)(this.coverage))throw(0,h.isDefined)(e)?Error(`Coverage report is not available. Reason: ${e.message}`):Error(`Coverage report is not available`);return this.coverage}getCoverage(){return this.coverage}async getCoverageTree(){return!(0,h.isDefined)(this.provider)||!(0,h.isDefined)(this.coverage)?$n:this.provider.getCoverageTree(this.coverage)}setCoverage(e){this.coverage=e}getCoverageForFiles(e){if(!(0,h.isDefined)(this.provider))throw Error(`Coverage provider not initialized`);if(!(0,h.isDefined)(this.coverage))throw Error(`Coverage report not available`);return this.provider.getCoverageForFiles(e,this.coverage)}},tr=l(Ie()),nr=l(Le());let rr=class{coverageService=new er;async generateCoverage(){try{await this.coverageService.init(),await this.coverageService.generateCoverage()}catch(e){throw H.info.failedLog(`Failed to generate coverage`,e),e}}async setCoverage(e){try{await this.coverageService.init(),await this.coverageService.setCoverage(e)}catch(e){throw H.info.failedLog(`Failed to set coverage`,e),e}}async getCoverageTree(){try{await this.coverageService.init(),H.info.startLog(`Getting coverage tree`);let e=await this.coverageService.getCoverageTree();return H.info.endLog(`Getting coverage tree`),e??null}catch(e){throw H.info.failedLog(`Failed to get coverage tree`,e),e}}async getCoverageForFiles(e){try{return await this.coverageService.init(),this.coverageService.getCoverageForFiles(e)}catch(e){throw H.info.failedLog(`Failed to get coverage for files`,e),e}}};(0,nr.default)([$e({category:Tt.GENERATE_COVERAGE}),(0,tr.default)(`design:type`,Function),(0,tr.default)(`design:paramtypes`,[]),(0,tr.default)(`design:returntype`,Promise)],rr.prototype,`generateCoverage`,null),(0,nr.default)([$e({category:Tt.SET_COVERAGE}),(0,tr.default)(`design:type`,Function),(0,tr.default)(`design:paramtypes`,[Object]),(0,tr.default)(`design:returntype`,Promise)],rr.prototype,`setCoverage`,null),(0,nr.default)([$e({category:Tt.GET_COVERAGE}),(0,tr.default)(`design:type`,Function),(0,tr.default)(`design:paramtypes`,[]),(0,tr.default)(`design:returntype`,Promise)],rr.prototype,`getCoverageTree`,null),(0,nr.default)([$e({category:Tt.GET_COVERAGE}),(0,tr.default)(`design:type`,Function),(0,tr.default)(`design:paramtypes`,[Array]),(0,tr.default)(`design:returntype`,Promise)],rr.prototype,`getCoverageForFiles`,null),rr=(0,nr.default)([(0,_.injectable)()],rr);let ir=new class{safeTrackEvent(e,t){}},ar={EMPTY_TEST:`0000`,DESCRIBE_NOT_FOUND:`0001`,TESTED_CODE_DATA_SOURCE_ERROR:`0002`,GENERATING_TESTS_REQUEST_ERROR:`0003`,GET_VERSION_REQUEST_ERROR:`0004`,GENERATING_HELPER_REQUEST_ERROR:`0005`,PREPARATIONS_FOR_GENERATING_TEST_DTO_ERROR:`0006`,ENHANCE_TESTS_REQUEST_ERROR:`0011`,EMPTY_FIXED_TESTS:`1000`,TESTABLE_NOT_FOUND:`1001`,TESTED_CODE_FILE_PATH_NOT_FOUND:`1002`,PREEN_TESTS_ERROR:`2001`,ORGANIZE_IMPORTS_ERROR:`2002`,NOT_ENOUGH_BALANCE_ERROR:`3000`,UNSUPPORTED_MODEL_ERROR:`4000`,TOO_MANY_USERS_ERROR:`4001`,PAYLOAD_TOO_LARGE_ERROR:`4002`,TEST_SUMMARY_DB_REQUEST_ERROR:`5000`,TEST_SUMMARY_INVALID_CREATED_BY_ERROR:`5001`,TEST_SUMMARY_INVALID_GIT_REMOTE_ERROR:`5002`,TEST_SUMMARY_INVALID_GIT_BRANCH_ERROR:`5003`,WS_DYNAMIC_PROMPT_GENERAL_ERROR:`6000`,WS_DYNAMIC_PROMPT_AUTH_ERROR:`6001`,PREPARATIONS_FOR_DYNAMIC_PROMPT_ERROR:`6002`,WS_DYNAMIC_PROMPT_VALIDATION_FAILED_ERROR:`6003`,WS_DYNAMIC_PROMPT_TIMEOUT_ERROR:`6004`,GITHUB_ACTION_TEST_SUMMARY_DB_REQUEST_ERROR:`7000`,GITHUB_ACTION_TEST_SUMMARY_READ_CONF_FILE:`7001`,GITHUB_ACTION_TEST_SUMMARY_INVALID_GIT_REMOTE_ERROR:`7002`,GITHUB_ACTION_TEST_SUMMARY_INVALID_GIT_BRANCH_ERROR:`7003`,GITHUB_ACTION_TEST_SUMMARY_READ_CONF_FILE_EMPTY_OPTIONS:`7004`,GITHUB_ACTION_TEST_SUMMARY_NO_COVERAGE_FOUND:`7005`},or={[ar.EMPTY_TEST]:`Oops! No tests were generated for "{{methodName}}". Code:{{code}} - We're on it!`,[ar.DESCRIBE_NOT_FOUND]:`Oops! Test suite not found for "{{methodName}}". Code:{{code}} - We're on it!`,[ar.TESTED_CODE_DATA_SOURCE_ERROR]:`Cannot get testable data for "{{methodName}}". Code:{{code}} - We're on it!`,[ar.GENERATING_TESTS_REQUEST_ERROR]:`Generating tests for method "{{methodName}}" - failed: "{{errorMessage}}". Code:{{code}} - We're on it!`,[ar.PREPARATIONS_FOR_GENERATING_TEST_DTO_ERROR]:`Generating tests for method "{{methodName}}" - failed: "{{errorMessage}}". Code:{{code}} - We're on it!`,[ar.GET_VERSION_REQUEST_ERROR]:`Failed to make request. Code:{{code}} - We're on it!`,[ar.GENERATING_HELPER_REQUEST_ERROR]:`Generating helpers for method "{{methodName}}" - failed: "{{errorMessage}}". Code:{{code}} - We're on it!`,[ar.ENHANCE_TESTS_REQUEST_ERROR]:`Enhance tests for method "{{methodName}}" - failed: "{{errorMessage}}". Code:{{code}} - We're on it!`,[ar.EMPTY_FIXED_TESTS]:`Oops! We got an empty API response for "{{methodName}}" test fixes. Code:{{code}} - We're on it!`,[ar.TESTABLE_NOT_FOUND]:`Oops! Testable code not found for "{{methodName}}". Code:{{code}} - We're on it!`,[ar.TESTED_CODE_FILE_PATH_NOT_FOUND]:`Oops! Testable code file path not found for "{{methodName}}". Code:{{code}}`,[ar.PREEN_TESTS_ERROR]:`Encountered a problem while processing "{{methodName}}". Code:{{code}} - We're on it!`,[ar.ORGANIZE_IMPORTS_ERROR]:`There was an issue with the processing "{{methodName}}". Code:{{code}} - We're on it!`,[ar.NOT_ENOUGH_BALANCE_ERROR]:`Usage test generation limit reached.`,[ar.UNSUPPORTED_MODEL_ERROR]:`We do not support this model at the moment.`,[ar.TOO_MANY_USERS_ERROR]:`Users limit reached. Please contact support.`,[ar.PAYLOAD_TOO_LARGE_ERROR]:`We could not generate tests due to code size.`,[ar.TEST_SUMMARY_DB_REQUEST_ERROR]:`We could not save test summary to database.`,[ar.TEST_SUMMARY_INVALID_CREATED_BY_ERROR]:`Invalid created by field.`,[ar.TEST_SUMMARY_INVALID_GIT_REMOTE_ERROR]:`Invalid git remote.`,[ar.TEST_SUMMARY_INVALID_GIT_BRANCH_ERROR]:`Invalid git branch.`,[ar.GITHUB_ACTION_TEST_SUMMARY_DB_REQUEST_ERROR]:`We could not save test summary to database.`,[ar.GITHUB_ACTION_TEST_SUMMARY_READ_CONF_FILE]:`Failed to read github action config file.`,[ar.GITHUB_ACTION_TEST_SUMMARY_INVALID_GIT_REMOTE_ERROR]:`Invalid git remote.`,[ar.GITHUB_ACTION_TEST_SUMMARY_INVALID_GIT_BRANCH_ERROR]:`Invalid git branch.`,[ar.GITHUB_ACTION_TEST_SUMMARY_READ_CONF_FILE_EMPTY_OPTIONS]:`Failed to parse options from github action conf file.`,[ar.GITHUB_ACTION_TEST_SUMMARY_NO_COVERAGE_FOUND]:`No coverage found. Please run coverage first.`,[ar.WS_DYNAMIC_PROMPT_GENERAL_ERROR]:`Failed initializing dynamic prompt.`,[ar.WS_DYNAMIC_PROMPT_AUTH_ERROR]:`Failed authorizing dynamic prompt.`,[ar.PREPARATIONS_FOR_DYNAMIC_PROMPT_ERROR]:`Failed preparing init dynamic prompt.`,[ar.WS_DYNAMIC_PROMPT_VALIDATION_FAILED_ERROR]:`Failed validating dynamic prompt dto.`,[ar.WS_DYNAMIC_PROMPT_TIMEOUT_ERROR]:`Dynamic prompt operation timed out.`};var sr=class extends Error{constructor(e,t){let n=cr(e,t);super(n),this.code=e}};let cr=(e,t)=>{let n=or[e];for(let[r,i]of Object.entries({...t,code:e}))n=n.replace(`{{${r}}}`,i);return n},lr=`x-request-id`;var ur=class extends Error{constructor(){super(`Not authorized`)}};new TextEncoder;let dr=new TextDecoder;function fr(e){if(Uint8Array.fromBase64)return Uint8Array.fromBase64(e);let t=atob(e),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n}function pr(e){if(Uint8Array.fromBase64)return Uint8Array.fromBase64(typeof e==`string`?e:dr.decode(e),{alphabet:`base64url`});let t=e;t instanceof Uint8Array&&(t=dr.decode(t)),t=t.replace(/-/g,`+`).replace(/_/g,`/`);try{return fr(t)}catch{throw TypeError(`The input to be decoded is not correctly encoded.`)}}var mr=class extends Error{static code=`ERR_JOSE_GENERIC`;code=`ERR_JOSE_GENERIC`;constructor(e,t){super(e,t),this.name=this.constructor.name,Error.captureStackTrace?.(this,this.constructor)}},hr=class extends mr{static code=`ERR_JWT_INVALID`;code=`ERR_JWT_INVALID`};let gr=e=>typeof e==`object`&&!!e;function _r(e){if(!gr(e)||Object.prototype.toString.call(e)!==`[object Object]`)return!1;if(Object.getPrototypeOf(e)===null)return!0;let t=e;for(;Object.getPrototypeOf(t)!==null;)t=Object.getPrototypeOf(t);return Object.getPrototypeOf(e)===t}function vr(e){if(typeof e!=`string`)throw new hr(`JWTs must use Compact JWS serialization, JWT must be a string`);let{1:t,length:n}=e.split(`.`);if(n===5)throw new hr(`Only JWTs using Compact JWS serialization can be decoded`);if(n!==3)throw new hr(`Invalid JWT`);if(!t)throw new hr(`JWTs must contain a payload`);let r;try{r=pr(t)}catch{throw new hr(`Failed to base64url decode the payload`)}let i;try{i=JSON.parse(dr.decode(r))}catch{throw new hr(`Failed to parse the decoded payload as JSON`)}if(!_r(i))throw new hr(`Invalid JWT Claims Set`);return i}let yr=e=>{let t=vr(e).exp;return(0,h.isDefined)(t)?t*1e3:null},br=e=>{if(!(0,h.isDefined)(e))return!0;let t=yr(e);return(0,h.isDefined)(t)?t<Date.now():!0};var xr=l(Le());let Sr=class{jwtToken=null;refreshTokenCallback=null;observer=new h.Observer;refreshTokenMutex=new M.Mutex;setJWTToken(e){this.jwtToken=e,this.observer.notifyAll(e)}async getJWTToken(){return(0,h.isDefined)(this.jwtToken)?(this.isTokenValid()||await this.refreshTokenMutex.runExclusive(async()=>{if((0,h.isDefined)(this.refreshTokenCallback))return await this.refreshTokenCallback(),this.jwtToken}),this.jwtToken):null}async getJWTTokenOrThrow(){let e=await this.getJWTToken();if(!(0,h.isDefined)(e))throw new ur;return e}onJWTTokenSave(e){this.observer.addListener(e)}isTokenValid(){return!br(this.jwtToken)}setRefreshTokenCallback(e){this.refreshTokenCallback=e}};Sr=(0,xr.default)([(0,_.injectable)(`Singleton`)],Sr);var Cr=s(((e,t)=>{function n(e,t){return function(n,r){t(n,r,e)}}t.exports=n,t.exports.__esModule=!0,t.exports.default=t.exports})),wr=l(Ie()),Tr=l(Cr()),Er=l(Le()),Dr,Or;let kr=class{axiosInstance;constructor(e,t){this.authStorage=e,this.globalConfigService=t,this.axiosInstance=j.default.create({baseURL:this.globalConfigService.getBackendURL(),headers:{"x-client-name":`ts-agent`,"x-client-version":xe,"Content-Type":`application/json`,"Content-Encoding":`gzip`},transformRequest:[e=>{if((0,h.isDefined)(e)){let t=ee.default.createGzip();return t.write(JSON.stringify(e)),t.end(),t}else return e}]}),(0,te.default)(this.axiosInstance)}async apiCall({url:e,method:t,data:n,config:r}){let i=new j.AxiosHeaders({"x-request-source":this.globalConfigService.getRequestSource(),...r?.headers});if(!r?.ignoreAuth){let e=await this.authStorage.getJWTToken();(0,h.isDefined)(e)&&!(0,h.isEmpty)(e)&&(i.authorization=`Bearer ${e}`)}let a={...r,method:t,url:e,data:n,headers:i};try{return await this.axiosInstance.request(a)}catch(t){this.handleError(e,t,n)}}async get(e,t){return(await this.apiCall({url:e,method:`GET`,config:t})).data}async post(e,t,n){return(await this.apiCall({url:e,method:`POST`,data:t,config:n})).data}async put(e,t,n){return(await this.apiCall({url:e,method:`PUT`,data:t,config:n})).data}async delete(e,t){return(await this.apiCall({url:e,method:`DELETE`,config:t})).data}async patch(e,t,n){return(await this.apiCall({url:e,method:`PATCH`,data:t,config:n})).data}async head(e,t){return this.apiCall({url:e,method:`HEAD`,config:t})}async options(e,t){return this.apiCall({url:e,method:`OPTIONS`,config:t})}handleError(e,t,n){if(j.default.isAxiosError(t))if((0,h.isDefined)(t.response)){let{status:e,statusText:n,data:r}=t.response;throw e===j.HttpStatusCode.PaymentRequired?new sr(ar.NOT_ENOUGH_BALANCE_ERROR):Error(`API request failed: ${e} ${n} - ${JSON.stringify(r)}`)}else if((0,h.isDefined)(t.request))throw Error(`API request failed: No response received from ${e}`);else throw Error(`API request failed: ${t instanceof Error?t.message:`Unknown error`}`);else if(t instanceof Error)throw TypeError(`API request failed: ${t.message}`);else throw TypeError(`API request failed: Unknown error occurred`)}onLogin(e){this.authStorage.onJWTTokenSave(t=>{(0,h.isDefined)(t)&&e()})}};kr=(0,Er.default)([(0,_.injectable)(),(0,Tr.default)(0,(0,_.inject)(Sr)),(0,Tr.default)(1,(0,_.inject)(He)),(0,wr.default)(`design:paramtypes`,[typeof(Dr=Sr!==void 0&&Sr)==`function`?Dr:Object,typeof(Or=He!==void 0&&He)==`function`?Or:Object])],kr);let Ar={SUPER_ADMIN:1,ADMIN:2,USER:3},jr=[Ar.ADMIN,Ar.SUPER_ADMIN];var Mr=l(Ie()),Nr=l(Cr()),Pr=l(Le()),Fr;let Ir=class{mutex=new M.Mutex;user=null;constructor(e){this.apiService=e}async fetchUser(){let e=await this.apiService.get(`/api/v1/user/me`);return this.setUser(e),e}setUser(e){this.user=e,H.addContext({userId:e.id})}async getUser(){return(0,h.isDefined)(this.user)?this.user:await this.mutex.runExclusive(async()=>await this.fetchUser())}async isAdminUser(){let e=await this.getUser();return(0,h.isDefined)(e)?jr.includes(e?.role):!1}async isInOrganization(){let e=await this.getUser();return(0,h.isDefined)(e?.organization)}};Ir=(0,Pr.default)([(0,_.injectable)(),(0,Nr.default)(0,(0,_.inject)(kr)),(0,Mr.default)(`design:paramtypes`,[typeof(Fr=kr!==void 0&&kr)==`function`?Fr:Object])],Ir);let Lr=e=>(0,y.createHash)(`md5`).update(String(e)).digest(`hex`),Rr=e=>({...zr(e),testFrameworkReceived:(0,h.isDefined)(e.testFrameworkReceived)?Lr(e.testFrameworkReceived):void 0,testFrameworkExpected:(0,h.isDefined)(e.testFrameworkExpected)?Lr(e.testFrameworkExpected):void 0}),zr=e=>({errorCode:e.errorCode,shortDescription:Lr(e.shortDescription),fullDescription:Lr(e.fullDescription)}),Br=e=>({name:Lr(e.name),code:Lr(e.code),status:e.status,errors:e.errors?.map(e=>Rr(e)),lintErrors:e.lintErrors?.map(e=>Vr(e))??null}),Vr=e=>({errorCode:e.errorCode,fullDescription:Lr(e.fullDescription),shortDescription:Lr(e.shortDescription),severity:e.severity,exactCode:Lr(e.exactCode)}),Hr=({describe:e,stdout:t})=>({describe:{path:e.path,code:Lr(e.code),fullCode:Lr(e.fullCode),status:e.status,errors:e.errors?.map(e=>zr(e)),tests:e.tests.map(e=>Br(e)),lintErrors:e.lintErrors?.map(e=>Vr(e))??null},stdout:t});var Ur=l(Ie()),Wr=l(Cr()),Gr=l(Le()),Kr,qr,Jr;let Yr=class{constructor(e,t,n){this.apiService=e,this.userService=t,this.globalConfigService=n}async saveTestMetrics({requestId:e,timeElapsed:t,validationReport:n,...r}){try{let i={timeElapsed:t,...n,...r};await this.userService.isInOrganization()&&(H.debug.defaultLog(`Filtering private data for B2B user`),i.testResult=(0,h.isDefined)(n?.testResult)?Hr(n.testResult):void 0),H.debug.startLog(`Sending metrics with request id ${e}`),await this.apiService.post(`/api/v1/tests/update-operation-metrics`,i,{headers:{[lr]:e}}),H.debug.defaultLog(`Test metrics have been saved`)}catch(e){H.error(`Test metrics cannot be saved`,e)}H.debug.endLog(`Sending metrics with request id ${e}`)}registerStartTime(e){let t=Date.now();return async({...n})=>{let r=Date.now()-t;return await this.saveTestMetrics({...n,requestId:e,timeElapsed:r}),r}}async logPackageDependencies(e){try{if(await this.userService.isInOrganization())return;let t=bt(e);if(!(0,h.isDefined)(t))return;await this.updateRepositoryPackageJson(t)}catch(e){H.info.defaultLog(`Failed to log package dependencies.`,e);return}}async saveOperationMetricsTrace(e){let{parentRequestId:t,llmModel:n,testResultIteration:r=0,toolsOutput:i,testFileContent:a}=e;try{H.debug.startLog(`Sending operation metrics trace for testResultIteration ${r}`),await this.apiService.post(`/api/v1/tests/operation-metrics-trace`,{parentRequestId:t,iteration:r,llmModel:n,toolsOutput:i,testFileContent:a}),H.debug.defaultLog(`Operation metrics trace saved for testResultIteration ${r}`)}catch(e){H.error(`Failed to save operation metrics trace for testResultIteration ${r}`,e)}H.debug.endLog(`Sending operation metrics trace for testResultIteration ${r}`)}async updateRepositoryPackageJson(e){try{let t=this.globalConfigService.getContext();if(!(0,h.isDefined)(t?.git?.owner)||!(0,h.isDefined)(t?.git?.repository)){H.debug.defaultLog(`No git context available, skipping package.json update`);return}let n={owner:t.git.owner,repo:t.git.repository,packageJson:JSON.stringify(e)};await this.apiService.patch(`/api/v1/github-repos/package-json`,n),H.debug.defaultLog(`Successfully updated repository package.json`)}catch(e){H.info.defaultLog(`Failed to update repository package.json`,e)}}};Yr=(0,Gr.default)([(0,_.injectable)(),(0,Wr.default)(0,(0,_.inject)(kr)),(0,Wr.default)(1,(0,_.inject)(Ir)),(0,Wr.default)(2,(0,_.inject)(He)),(0,Ur.default)(`design:paramtypes`,[typeof(Kr=kr!==void 0&&kr)==`function`?Kr:Object,typeof(qr=Ir!==void 0&&Ir)==`function`?qr:Object,typeof(Jr=He!==void 0&&He)==`function`?Jr:Object])],Yr);var Xr=class{queue;activeProcesses=[];itemAddedObserver=new h.Observer;itemExecutedObserver=new h.Observer;itemAbortedObserver=new h.Observer;abortControllers=new Map;getItemKey;constructor({concurrency:e,getItemKey:t}){this.queue=new ne.default({concurrency:e}),this.getItemKey=t}async add(e,t){let n=this.getItemKey(e);if(this.activeProcesses.includes(n))return;let r=new AbortController,i=H.captureContext({withNewRequestId:!0});return this.abortControllers.set(n,r),this.activeProcesses.push(n),this.itemAddedObserver.notifyAll(n),this.queue.add(async()=>{await H.runWithContext(i,async()=>{await t(r.signal)})},{signal:r.signal}).then(()=>{this.itemExecutedObserver.notifyAll(n)}).finally(()=>{this.activeProcesses=this.activeProcesses.filter(e=>e!==n),this.abortControllers.delete(n)})}shouldQueue(){return this.queue.pending>=this.queue.concurrency}onIdleEmit(e){this.queue.on(`idle`,()=>{e()})}has(e){let t=this.getItemKey(e);return this.activeProcesses.includes(t)}getActiveProcesses(){return this.activeProcesses}getProcessing(){return this.activeProcesses.slice(0,this.queue.concurrency)}getQueued(){return this.activeProcesses.slice(this.queue.concurrency)}onDone(e){this.itemExecutedObserver.addListener(e)}onAdded(e){this.itemAddedObserver.addListener(e)}onAborted(e){this.itemAbortedObserver.addListener(e)}abortAll(){this.queue.clear();for(let[,e]of this.abortControllers)e.abort();this.abortControllers.clear();for(let e of this.activeProcesses)this.itemAbortedObserver.notifyAll(e);this.activeProcesses=[]}abort(e){let t=this.getItemKey(e);this.activeProcesses=this.activeProcesses.filter(e=>e!==t),this.itemAbortedObserver.notifyAll(t);let n=this.abortControllers.get(t);(0,h.isDefined)(n)&&(n.abort(),this.abortControllers.delete(t))}clearQueued(){this.queue.clear();let e=this.getQueued();for(let t of e){let e=this.abortControllers.get(t);(0,h.isDefined)(e)&&(e.abort(),this.abortControllers.delete(t)),this.itemAbortedObserver.notifyAll(t)}this.activeProcesses=this.getProcessing()}getIdlePromise(){return this.queue.onIdle()}};let Zr=`npx jest ${Ce} --coverage=false --verbose=false --watchAll=false --silent --json --forceExit --testPathIgnorePatterns=// --maxWorkers=1`;var Qr=class{fulfill(e){if(Ue().getTestFramework()!==fe.JEST)return!1;let t=e,n=null,r=0;for(;r<25;){r++;let e=vt(t,`package.json`);if(!(0,h.isDefined)(e)||e===n)return!1;let i=bt(t);if((0,h.isDefined)(i)&&xt(i,`jest`))return!0;n=e,t=f.default.dirname(f.default.dirname(e))}return!1}getTestCommand(){return{command:Ue().getTestCommand()??Zr,framework:fe.JEST}}};let $r=`npx vitest run ${Ce} --reporter=junit --silent --pool=threads --maxWorkers=1 --coverage.enabled=false`,ei=new class{constructor(e){this.providers=e}getTestCommand(e){let t=this.getProvider(e);if(!(0,h.isDefined)(t))throw Error(`No CmdProvider found for file: ${e}`);return t.getTestCommand()}getProvider(e){return this.providers.find(t=>t.fulfill(e))}}([new class{fulfill(e){if(Ue().getTestFramework()!==fe.VITEST)return!1;let t=e,n=null,r=0;for(;r<25;){r++;let e=vt(t,`package.json`);if(!(0,h.isDefined)(e)||e===n)return!1;let i=bt(t);if((0,h.isDefined)(i)&&xt(i,`vitest`))return!0;n=e,t=f.default.dirname(f.default.dirname(e))}return!1}getTestCommand(){return{command:Ue().getTestCommand()??$r,framework:fe.VITEST}}},new Qr]);var ti=class e{static of(...t){return new e(...t)}static all=e.of();static success=e.of(0);static suppress_1=e.of(0,1);allow(e){return this.allowed.length===0||this.allowed.includes(e)}allowed;constructor(...e){this.allowed=e}};let ni=`validate-tests`,ri=e=>e instanceof Error&&`code`in e&&typeof e.code==`number`;var ii=class e{constructor(e){this.relativePath=e}async runCommandOnFile(e,t=ti.success,n=!1){let r=n?_t(f.default.normalize(this.relativePath)):f.default.normalize(this.relativePath),i=e.replaceAll(Ce,`"${r}"`);try{H.debug.startLog(`Command been executed on test-file ${this.relativePath} ${e}`),H.info.defaultLog(`Running command on file ${this.relativePath}`,{renderedCommand:i});let{stdout:t,stderr:n}=await Nt(i,{cwd:Ue().getRootPath(),timeout:3e5}),r=t||n;return H.debug.endLog(`Command been executed on test-file ${this.relativePath} ${e}: ${r}`),r}catch(n){if(!(ri(n)&&(0,h.isDefined)(n.code)&&t.allow(n.code))){let t=`Failed run command "${e}" on file ${this.relativePath}`;throw H.error(t,n),n}let r=n.stdout||n.stderr;return H.debug.endLog(`Command been executed on test-file ${this.relativePath} ${e}: ${r}`),r}}getTempFileName(e,t,n){if(t){let t=f.default.join(N.default.tmpdir(),`early`),n=`${e}-${(0,y.randomUUID)()}`;return f.default.join(t,n)}let r=(0,h.isDefined)(n)&&!(0,h.isEmpty)(n),i=r&&f.default.isAbsolute(n)?f.default.dirname(n):f.default.join(Ue().getRootPath(),f.default.dirname(n??``));if(!(0,h.isDefined)(i))throw Error(`Workspace root path is not defined`);let a=`.${e}-${(0,y.randomUUID)()}-${r?f.default.basename(n):`.ts`}`;return f.default.join(i,a)}async runCommandWithContent(t,n,r,i=!1){H.addContext({subCategory:Et.COMMAND_EXECUTION});let a={filePrefix:`generated-content`,useTemporaryOSFolder:!(0,h.isDefined)(r?.predefinedPath),validExitCodes:ti.success,...r},o=this.getTempFileName(a.filePrefix,a.useTemporaryOSFolder,a.predefinedPath);try{H.info.defaultLog(`Creating temp file ${o}`),await p.default.mkdir(f.default.dirname(o),{recursive:!0}),await p.default.writeFile(o,t);let r=new e(o);return H.info.defaultLog(`Running command "${n}" on temp file`),await r.runCommandOnFile(n,a.validExitCodes,i)}catch(e){return H.error(`Failed running command "${n}" on temp file`,e),``}finally{try{await p.default.unlink(o)}catch(e){H.info.defaultLog(`Failed removing temp file`,e)}}}async runTestCommand(){H.addContext({subCategory:Et.COMMAND_EXECUTION});let e;try{e=ei.getTestCommand(this.relativePath)}catch(e){return e instanceof Error?e.message:`Framework is not supported yet`}return await this.runCommandOnFile(e.command,ti.suppress_1,!0)}async runTestCommandOnTempFile(e){H.addContext({subCategory:Et.COMMAND_EXECUTION});let t;try{t=ei.getTestCommand(this.relativePath)}catch(e){return e instanceof Error?e.message:`Framework is not supported yet`}return await this.runCommandWithContent(e,t.command,{validExitCodes:ti.suppress_1,filePrefix:ni,predefinedPath:this.relativePath},!0)}async runFormatCommand(){H.addContext({subCategory:Et.COMMAND_EXECUTION});let e=Ue().getPrettierCommand();H.debug.startLog(`format command: ${e}`);let t=await this.runCommandOnFile(e,ti.all);return H.debug.endLog(`format command: ${e}`),t}async runLintCommand(e=[]){H.addContext({subCategory:Et.COMMAND_EXECUTION});let t=Ue().getLintCommand(),n=e.length>0?t+` `+e.join(` `):t;H.debug.startLog(`lint command: ${n}`);let r=await this.runCommandOnFile(n,ti.all);return H.debug.endLog(`lint command: ${n}`),r}};let ai=e=>{let t=e.name??``,n=e.type;return{methodType:n,methodName:t,parentName:n===`method`?e.parentName:void 0}};async function oi(e,{methodType:t,methodName:n,parentName:r}){let i=new Mn(await new et(e).getText()).testables.findTestable(t,n,r);if(!(0,h.isDefined)(i))throw new sr(ar.TESTABLE_NOT_FOUND,{methodName:n});return i}function si(e,t){return(0,h.isDefined)(t)&&!(0,h.isEmpty)(t)?`${t}.${e}`:e}function ci(e){if(!e||e.trim()===``)return[];let t=e.indexOf(`[`),n=e.lastIndexOf(`]`),r=t!==-1&&n!==-1&&n>t?e.slice(t,n+1):e;try{return JSON.parse(r)}catch(e){return H.error(`Failed to parse eslint JSON output`,e),null}}var li=l(Le());let ui=class{contentCache=new Map;filePathIndex=new Map;computeContentHash(e){return Lr(e)}getContentCacheKey(e,t){return`${e}:${t?`fix`:`nofix`}`}evictOldest(){let e=this.contentCache.keys().next().value;(0,h.isDefined)(e)&&(this.contentCache.delete(e),H.debug.defaultLog(`Lint cache evicted oldest entry (FIFO)`))}get(e,t,n){let r=this.computeContentHash(t),i=this.getContentCacheKey(r,n),a=this.contentCache.get(i);return(0,h.isDefined)(a)?(H.debug.defaultLog(`Lint cache hit for ${e}`),a.results):null}set(e,t,n,r){let i=this.computeContentHash(t),a=Date.now(),o=this.getContentCacheKey(i,n);if(!this.contentCache.has(o)&&this.contentCache.size>=100&&this.evictOldest(),this.contentCache.set(o,{results:r,contentHash:i,withFix:n,timestamp:a}),n){let e=this.getContentCacheKey(i,!1);!this.contentCache.has(e)&&this.contentCache.size>=100&&this.evictOldest(),this.contentCache.set(e,{results:r,contentHash:i,withFix:!1,timestamp:a})}this.filePathIndex.set(e,i)}invalidate(e){let t=this.filePathIndex.get(e);if(!(0,h.isDefined)(t))return;let n=this.getContentCacheKey(t,!0),r=this.getContentCacheKey(t,!1),i=this.contentCache.delete(n),a=this.contentCache.delete(r);this.filePathIndex.delete(e),(i||a)&&H.debug.defaultLog(`Lint cache invalidated for ${e}`)}invalidateAll(){let e=this.contentCache.size;this.contentCache.clear(),this.filePathIndex.clear(),e>0&&H.debug.defaultLog(`Lint cache cleared: ${e} entries removed`)}};ui=(0,li.default)([(0,_.injectable)()],ui);let di=function(e){return e[e.ERROR=2]=`ERROR`,e[e.WARN=1]=`WARN`,e[e.OFF=0]=`OFF`,e}({});var fi=l(Ie()),pi=l(Cr()),mi=l(Le()),hi,gi;let _i=class{constructor(e,t){this.globalConfigService=e,this.lintCacheService=t}async disableRules(e){let t=[this.globalConfigService.shouldIgnoreAsAnyLintErrors()?`@typescript-eslint/no-explicit-any`:void 0,...this.globalConfigService.allowUndefinedLintErrors()?Ct:[]].filter(h.isDefined);this.globalConfigService.shouldDisableLintRules()?await this.disableAllLintRules(e):(0,h.isEmpty)(t)||await this.disableLintRules(e,t),await Jt.refreshFromFileSystem(e)}async disableAllLintRules(e){let t=await this.getRulesToDisable(e);if((0,h.isDefined)(t)){if((0,h.isEmpty)(t)){H.info.defaultLog(`No lint rules needed to be disabled`);return}await this.addDisableComment(e,t),H.info.defaultLog(`Added eslint-disable comment for rules: ${t.join(`, `)}`)}}async lintFiles(e,t){let n=et.fromRelativePath(e),r=await n.getText(),i=this.lintCacheService.get(e,r,t);if((0,h.isDefined)(i))return i;let a=t?[`--format`,`json`,`--fix`]:[`--format`,`json`],o=ci(await new ii(e).runLintCommand(a));if(!(0,h.isDefined)(o))return null;if(t){await Jt.refreshFromFileSystem(e);let r=await n.getText();this.lintCacheService.set(e,r,t,o)}else this.lintCacheService.set(e,r,t,o);return o}async lint(e,t){try{return await this.lintFiles(e,t)}catch(e){return H.error(`Failed to get lint results:`,e),null}}async fixLint(e){try{return await this.lint(e,!0)}catch(e){return H.error(`Failed to fix lint:`,e),null}}async getLintResults(e){try{return await this.lint(e,!1)}catch(e){return H.error(`Failed to get lint results:`,e),null}}async getRulesToDisable(e){let t=await this.getLintResults(e);if(!(0,h.isDefined)(t))return null;let n=(t[0]?.messages??[]).filter(e=>e.severity===di.ERROR);return[...new Set(n.map(e=>e.ruleId).filter(h.isDefined))]}async addDisableComment(e,t){let n=et.fromRelativePath(e),r=await n.getText(),i=`/* eslint-disable ${t.join(`, `)} */\n\n`;await n.replace(i+r),this.lintCacheService.invalidate(e)}hasDisableCommentForRules(e,t){let n=e.split(`
|
|
32008
32008
|
`);for(let e of n){let n=e.indexOf(`/*`),r=e.indexOf(`*/`);if(n===-1||r===-1)continue;let i=e.slice(n+2,r).trim();if(i.startsWith(`eslint-disable`)&&i.replace(`eslint-disable`,``).trim().split(`,`).map(e=>e.trim()).every(e=>t.includes(e)))return!0}return!1}async disableLintRules(e,t){if(!this.globalConfigService.shouldIgnoreAsAnyLintErrors())return;let n=et.fromRelativePath(e),r=await n.getText();if(this.hasDisableCommentForRules(r,t))return;let i=await this.getLintResults(e);if(!(0,h.isDefined)(i)){H.info.defaultLog(`No lint results returned`);return}let a=i[0]?.messages??[],o=t.filter(e=>a.some(t=>t.severity===di.ERROR&&t.ruleId===e));if((0,h.isEmpty)(o))return;let s=`/* eslint-disable ${o.join(`, `)} */\n\n`;await n.replace(s+r),this.lintCacheService.invalidate(e),H.info.defaultLog(`Added eslint-disable comment for ${o.join(`, `)} in ${e}`)}};_i=(0,mi.default)([(0,_.injectable)(),(0,pi.default)(0,(0,_.inject)(He)),(0,pi.default)(1,(0,_.inject)(ui)),(0,fi.default)(`design:paramtypes`,[typeof(hi=He!==void 0&&He)==`function`?hi:Object,typeof(gi=ui!==void 0&&ui)==`function`?gi:Object])],_i);let vi="${methodName}";`${vi}`,`${vi}`;function yi(e,t,n){let r=e.split(`
|
|
@@ -32066,24 +32066,24 @@ ${qd}${t.trimStart()}`),n=3+(0,O.stripVTControlCharacters)(t.trimStart()).length
|
|
|
32066
32066
|
`,n)+1)),`error`)}function Sf(e){return Cd.some(t=>t.test(e))}function Cf(e){return e.filter(e=>typeof e==`object`&&!!e&&`type`in e&&`text`in e).map(e=>e.text).join(`
|
|
32067
32067
|
`)}function wf(e){if(`stdout`in e)return((e.stdout??``)+(e.stderr??``)).trim();if(`output`in e)return String(e.output);if(`content`in e){let t=e.content;if(typeof t==`string`)return t;if(Array.isArray(t))return Cf(t)}return``}function Tf(e){let t=e.tool_response;return typeof t==`string`?t:Array.isArray(t)?Cf(t):typeof t==`object`&&t?wf(t):``}function Ef(e,t){return t===0&&e>0?`ALL ${String(e)} TESTS PASSED. Now run lint (with --fix) and typecheck to verify the test file is fully clean. If all checks pass, you are DONE — stop immediately. If any test has persistent lint or typecheck errors you cannot fix, DELETE that test and re-verify. You must NEVER finish with lint or typecheck errors.`:e>=6?`${String(e)} passed, ${String(t)} failed. Phase 5 (PRUNE): Delete ALL ${String(t)} failing test(s) now. Do NOT attempt to fix them. After pruning, run lint --fix, tests, and typecheck to confirm. If any remaining test has persistent lint or typecheck errors, delete it too. You must NEVER finish with lint or typecheck errors.`:`${String(e)} passed, ${String(t)} failed. Phase 4 (REPAIR): Read the error output and fix the failing tests, then return to Phase 3.`}function Df(e){return e===Sd||e===xd}function Of(e){let t=Tf(e);try{let e=JSON.parse(t);if(`testReport`in e&&(0,h.isDefined)(e.testReport))return e.testReport}catch{}}function kf(e,t){let n=yf(t);if(!(0,h.isDefined)(n))return Yd.debug(`Hook injected: Phase 3 fallback reminder (output not parseable, output length: ${String(t.length)})`),{hookSpecificOutput:{hookEventName:e.hook_event_name,additionalContext:wd}};let r=Ef(n.passed,n.failed);return Yd.debug(`Hook injected: Phase 3 directive (${String(n.passed)} passed, ${String(n.failed)} failed)`),{hookSpecificOutput:{hookEventName:e.hook_event_name,additionalContext:r}}}let Af=async(e,t,{signal:n})=>{if(n.aborted||!Qd(e))return{};if(Df(e.tool_name)){let t=Of(e);if(!(0,h.isDefined)(t))return Yd.debug(`Hook injected: Phase 3 fallback reminder (MCP response missing testReport)`),{hookSpecificOutput:{hookEventName:e.hook_event_name,additionalContext:wd}};let n=Ef(t.passed,t.failed);return Yd.debug(`Hook injected: Phase 3 directive (${String(t.passed)} passed, ${String(t.failed)} failed)`),{hookSpecificOutput:{hookEventName:e.hook_event_name,additionalContext:n}}}return Sf(nf(e))?kf(e,Tf(e)):{}};function jf(e){return e?e.stabilityConflict===!0?`check_all detected a lint/format stability conflict — lint and format commands keep changing the file. Report this to the user instead of retrying.`:`check_all failed. Fix the failing gates, then call check_all again.\n\nFailed gates:\n${e.gates.filter(e=>!e.passed&&!e.skipped).map(e=>{let t=(0,h.isDefined)(e.output)?`\n${e.output}`:``;return`- ${e.gate}: FAILED${t}`}).join(`
|
|
32068
32068
|
`)}`:`You have not called check_all yet. You must call check_all and get all gates passing before completing your task. Use check_lint, check_format, check_test, check_build to iterate, then call check_all for final verification.`}function Mf(e){return async()=>{let t=e.getLastCheckAllResult();return!t||!t.passed?{decision:`block`,reason:jf(t)}:{}}}var Nf=l(Ie()),Pf=l(Cr()),Ff=l(Le()),If,Lf;let Rf=function(e){return e.OPENAI=`OPENAI`,e.AZURE_OPENAI=`AZURE_OPENAI`,e.ANTHROPIC=`ANTHROPIC`,e}({}),zf=class{provider=Rf.ANTHROPIC;cachedConfig;constructor(e,t){this.apiService=e,this.globalConfigService=t}async getAgentSdkConfig(){if((0,h.isDefined)(this.cachedConfig))return this.cachedConfig;try{let e=await this.apiService.post(`/api/v1/llm-models/active-model`,{provider:this.provider});if((0,h.isDefined)(e))return this.cachedConfig=e,H.info.defaultLog(`Fetched active model config: { provider: ${this.provider}, modelName: ${e.modelName}, capPrice: ${e.capPrice} }`),this.cachedConfig}catch(e){H.default.warn(`Failed to fetch active model config: ${(0,h.getErrorMessage)(e)}`)}return{modelName:`claude-sonnet-4-5-20250929`,capPrice:2}}};zf=(0,Ff.default)([(0,_.injectable)(),(0,Pf.default)(0,(0,_.inject)(kr)),(0,Pf.default)(1,(0,_.inject)(He)),(0,Nf.default)(`design:paramtypes`,[typeof(If=kr!==void 0&&kr)==`function`?If:Object,typeof(Lf=He!==void 0&&He)==`function`?Lf:Object])],zf);function Bf({content:e}){return(0,h.isString)(e)?e:!(0,h.isArray)(e)||(0,h.isEmpty)(e)?``:e.map(e=>{if((0,h.isString)(e))return e;let t=e;return(0,h.isString)(t.text)?t.text:``}).filter(e=>!(0,h.isEmpty)(e)).join(`
|
|
32069
|
-
`)}let
|
|
32070
|
-
`).length}function
|
|
32071
|
-
`).filter(e=>e.trim()!==``).length}function
|
|
32072
|
-
`):JSON.stringify(e)}return JSON.stringify(e??``)}var
|
|
32069
|
+
`)}function Vf(e){let t=JSON.parse(e);if(!(0,h.isArray)(t)||(0,h.isEmpty)(t))return e;let n=Bf({type:`json`,content:t});return(0,h.isEmpty)(n)?e:n}let Hf=/Full output saved to:\s*(\S+\.(txt|json))/;function Uf(e){if(!e.includes(`<persisted-output>`))return e;let t=Hf.exec(e);if(!(0,h.isDefined)(t))return e;let n=t[1].trim();try{if((0,w.existsSync)(n)){let e=(0,w.readFileSync)(n,`utf8`);return n.endsWith(`.json`)?Vf(e):e}}catch{}return e}let Wf=[/\beslint\b/,/\bnpm\s+run\s+lint\b/,/\bnpx\s+eslint\b/];function Gf(e){return Cd.some(t=>t.test(e))}function Kf(e){return Wf.some(t=>t.test(e))}function qf(e){let t=e.input;if(!(0,h.isDefined)(t))return``;switch(e.name){case`Read`:case`Write`:case`Edit`:{let e=t.file_path;return typeof e==`string`?e:``}case`Bash`:{let e=t.command;return typeof e==`string`?e:``}case`Glob`:case`Grep`:{let e=t.pattern;return typeof e==`string`?e:``}default:return``}}function Jf(e){return e.split(`
|
|
32070
|
+
`).length}function Yf(e){return e.split(`
|
|
32071
|
+
`).filter(e=>e.trim()!==``).length}function Xf(e){if(typeof e==`string`)return e;if(Array.isArray(e)){let t=e.filter(e=>typeof e==`object`&&!!e&&typeof e.text==`string`).map(e=>e.text);return t.length>0?t.join(`
|
|
32072
|
+
`):JSON.stringify(e)}return JSON.stringify(e??``)}var Zf=class{iterationCount=0;toolUseMap=new Map;lastTestRunResult;lastLintErrorCount=0;lintToolUseIds=new Set;isVerbose;constructor(e=!1){this.isVerbose=e}logStart(e){e.model,e.budget}logMessage(e){switch(e.type){case`system`:this.handleSystemMessage(e);break;case`assistant`:this.handleAssistantMessage(e);break;case`user`:this.handleUserMessage(e);break;default:break}}logResult(e){e.subtype,e.num_turns;let t=e.total_cost_usd?.toFixed(4)??`N/A`,n=(e.duration_ms/1e3).toFixed(1);this.iterationCount,``+t,n+``}getIterationCount(){return this.iterationCount}buildValidationSummary(){let e=this.lastTestRunResult;return{greenTestsCount:e?.passed??0,redTestsCount:e?.failed??0,greyTestsCount:0,whiteTestsCount:0,naTestsCount:0,errorSuitsCount:e?.suitesFailed??0,lintErrorsCount:this.lastLintErrorCount}}handleSystemMessage(e){let t=cf(e);if(t.subtype!==`init`)return;let n=t.model??`unknown`,r=(0,h.isDefined)(t.session_id)?t.session_id.slice(0,8):`N/A`;Yd.debug(`Session `+r+` initialized | model: `+n)}handleAssistantMessage(e){let t=sf(e);if((0,h.isDefined)(t))for(let e of t)e.type===`text`&&typeof e.text==`string`&&e.text.trim()!==``?Yd.thinking(e.text.trim()):e.type===`tool_use`&&this.handleToolUse(e)}handleToolUse(e){let t=qf(e),n=e.name??`Unknown`;if((0,h.isDefined)(e.id)&&this.toolUseMap.set(e.id,n),n===`Bash`&&Gf(t)){this.iterationCount+=1,this.iterationCount>1&&Yd.iterationSeparator(),Yd.testRun(this.iterationCount,t);return}n===`Bash`&&Kf(t)&&(0,h.isDefined)(e.id)&&this.lintToolUseIds.add(e.id),Yd.tool(n,t),this.isVerbose&&this.logVerboseToolUse(n,e)}logVerboseToolUse(e,t){if(e!==`Edit`||!(0,h.isDefined)(t.input))return;let n=typeof t.input.file_path==`string`?t.input.file_path:``,r=typeof t.input.old_string==`string`?t.input.old_string:``,i=typeof t.input.new_string==`string`?t.input.new_string:``;n!==``&&r!==``&&i!==``&&Xd.editDiff(n,r,i)}handleUserMessage(e){let t=sf(e);if((0,h.isDefined)(t)){for(let e of t)if(e.type===`tool_result`){let t=this.toolUseMap.get(e.tool_use_id??``);this.toolUseMap.delete(e.tool_use_id??``),this.logToolResult(e,t)}}}logToolResult(e,t){let n=(0,h.isString)(e.content)?e.content:Bf(e),r=Uf(n),i=e.tool_use_id??``;if(t===xd){this.processCheckAllResult(r);return}this.lintToolUseIds.has(i)&&(this.lintToolUseIds.delete(i),this.lastLintErrorCount=xf(r));let a=bf(r);if((0,h.isDefined)(a)){let e=yf(r);(0,h.isDefined)(e)&&(this.lastTestRunResult=e),this.isVerbose&&Xd.rawOutput(n),r.includes(`failed`)?Yd.testFail(a):Yd.testPass(a);return}this.logToolSpecificResult(e,t,n),this.isVerbose&&t===`Bash`&&Xd.rawOutput(n)}processCheckAllResult(e){try{let t=JSON.parse(e),n=t.gates;if(!Array.isArray(n)){Yd.toolResult(xd,`completed`);return}let r=n.find(e=>e.gate===`testCommand`),i=n.find(e=>e.gate===`lintCommand`);if((0,h.isDefined)(r?.output)){let e=yf(r.output);(0,h.isDefined)(e)&&(this.lastTestRunResult=e);let t=bf(r.output);(0,h.isDefined)(t)&&(r.output.includes(`failed`)?Yd.testFail(t):Yd.testPass(t))}(0,h.isDefined)(i?.output)&&(this.lastLintErrorCount=xf(i.output)),Yd.toolResult(xd,t.passed===!0?`all gates passed`:`some gates failed`)}catch{Yd.toolResult(xd,`completed`)}}logToolSpecificResult(e,t,n){if(e.is_error===!0){Yd.warn((t??`Tool`)+` returned an error`),Yd.warn(`Error content: `+n.slice(0,500));return}switch(t){case`Read`:{let e=Jf(n);Yd.toolResult(`Read`,String(e)+` lines`),this.isVerbose&&Xd.filePreview(e,n);break}case`Edit`:Yd.toolResult(`Edit`,`applied successfully`);break;case`Write`:Yd.toolResult(`Write`,`file written`);break;case`Glob`:Yd.toolResult(`Glob`,String(Yf(n))+` files matched`),this.isVerbose&&Xd.searchResults(`Glob`,n);break;case`Grep`:Yd.toolResult(`Grep`,String(Yf(n))+` matches`),this.isVerbose&&Xd.searchResults(`Grep`,n);break;default:(0,h.isDefined)(t)&&t.startsWith(`mcp__`)&&(Yd.toolResult(t,`completed`),this.isVerbose&&Xd.rawOutput(Xf(e.content)));break}}};let Qf=function(e){return e.UNRESOLVED=`unresolved`,e.RESOLVED=`resolved`,e.VERIFIED=`verified`,e}({}),$f=function(e){return e.PASSED=`passed`,e.FAILED=`failed`,e.SKIPPED=`skipped`,e}({});var ep=class{static TRACED_TOOLS=new Set([`Bash`,xd]);testResultIteration=0;toolsOutputBuffer={};toolUseInfoMap=new Map;constructor(e,t,n,r){this.metricReportService=e,this.parentRequestId=t,this.llmModel=n,this.testFilePath=r}async processMessage(e){try{let{toolsOutput:t,hasTestFileEdit:n}=this.extractToolsOutput(e);Object.assign(this.toolsOutputBuffer,t),n&&Object.keys(this.toolsOutputBuffer).length>0&&(this.testResultIteration+=1,await this.metricReportService.saveOperationMetricsTrace({parentRequestId:this.parentRequestId,llmModel:this.llmModel,testResultIteration:this.testResultIteration,toolsOutput:this.toolsOutputBuffer,testFileContent:this.readTestFileContent()}),this.toolsOutputBuffer={})}catch{H.default.warn(`Failed to process operation metrics trace`)}}async flush(){try{if(Object.keys(this.toolsOutputBuffer).length===0)return;this.testResultIteration+=1,await this.metricReportService.saveOperationMetricsTrace({parentRequestId:this.parentRequestId,llmModel:this.llmModel,testResultIteration:this.testResultIteration,toolsOutput:this.toolsOutputBuffer,testFileContent:this.readTestFileContent()}),this.toolsOutputBuffer={}}catch{H.default.warn(`Failed to process operation metrics trace`)}}logSyntheticTool(e,t,n){let r=Date.now();this.toolsOutputBuffer[e]={tool:e,input:t,content:[{type:`text`,text:JSON.stringify(n,null,2)}],startedAt:r,completedAt:r}}addPreVerification(e,t,n){let r=[`testCommand`,`buildCommand`,`lintCommand`,`prettierCommand`].map(e=>{let n=t[e];return{gate:e,passed:n.status===$f.PASSED,skipped:n.status===$f.SKIPPED,...n.status!==$f.SKIPPED&&{command:n.command},...n.status===$f.FAILED&&{output:n.output}}});this.logSyntheticTool(`pre-verification`,e,{passed:t.passed,gates:r}),this.logSyntheticTool(`decision`,t,n)}readTestFileContent(){try{return(0,w.readFileSync)(this.testFilePath,`utf8`)}catch{return}}extractToolsOutput(e){let t=sf(e);if(!(0,h.isDefined)(t))return{toolsOutput:{},hasTestFileEdit:!1};let n={},r=!1;for(let e of t)e.type===`tool_result`&&(0,h.isDefined)(e.tool_use_id)&&this.processToolResultBlock(e.tool_use_id,e,n),e.type===`tool_use`&&(0,h.isDefined)(e.id)&&(0,h.isDefined)(e.name)&&(r=this.processToolUseBlock(e.id,e)||r);return{toolsOutput:n,hasTestFileEdit:r}}processToolResultBlock(e,t,n){let r=this.toolUseInfoMap.get(e);if(!(0,h.isDefined)(r))return;let i=Uf(Bf(t)),a;try{if(r.tool===`Bash`)a=yf(i);else if(r.tool===xd){let e=this.extractCheckAllTestOutput(i);a=(0,h.isDefined)(e)?yf(e):void 0}}catch{}n[e]={...r,content:i,is_error:t.is_error,completedAt:Date.now(),...(0,h.isDefined)(a)&&{testResult:a}},this.toolUseInfoMap.delete(e)}extractCheckAllTestOutput(e){return JSON.parse(e).gates?.find(e=>e.gate===`testCommand`)?.output}processToolUseBlock(e,t){let n=t.name??``,r=t.input;return this.toolUseInfoMap.set(e,{tool:n,input:r,startedAt:Date.now()}),(n===`Edit`||n===`Write`)&&r?.file_path===this.testFilePath}},tp=class extends Error{name=`SdkRunnerError`;constructor(e,t,n){super(`SDK runner failed: ${e}`),this.subtype=e,this.errors=t,this.costUsd=n}};let np=`test("placeholder", () => {
|
|
32073
32073
|
expect(true).toBe(true);
|
|
32074
32074
|
});
|
|
32075
|
-
`;function
|
|
32075
|
+
`;function rp(e){switch(e){case`jest`:case`vitest`:return np;case`mocha`:return`const assert = require("assert");
|
|
32076
32076
|
|
|
32077
32077
|
it("placeholder", () => {
|
|
32078
32078
|
assert.ok(true);
|
|
32079
32079
|
});
|
|
32080
|
-
`;default:return tp}}function rp(e){return(0,h.isDefined)(e)?{status:Zf.RESOLVED,command:e}:{status:Zf.UNRESOLVED}}function ip(e){return{testCommand:rp(e.testCommand),buildCommand:rp(e.typecheckCommand),lintCommand:rp(e.lintCommand),prettierCommand:rp(e.prettierCommand),packageManager:e.packageManager}}var ap=l(Le());let op=(0,O.promisify)(D.exec),sp=new Map,cp=[/Oops! Something went wrong/i,/ESLint couldn't find a?n? ?configuration/i,/Cannot find module/i,/MODULE_NOT_FOUND/,/ENOENT/,/command not found/i,/ERR_MODULE_NOT_FOUND/,/Cannot read config file/i,/No ESLint configuration found/i,/Error: No files matching/i];function lp(e){return cp.some(t=>t.test(e))}function up(e,t){let n=f.default.basename(t);return e.includes(n)}let dp=class{async verify(e){let{setup:t,workingDirectory:n}=e,[r,i,a,o]=await Promise.all([this.runGate(t.testCommand,n),this.runGate(t.buildCommand,n),this.runGate(t.lintCommand,n),this.runGate(t.prettierCommand,n)]);return{testCommand:r,buildCommand:i,lintCommand:a,prettierCommand:o,passed:r.status!==Qf.FAILED&&i.status!==Qf.FAILED&&a.status!==Qf.FAILED&&o.status!==Qf.FAILED}}async runGate(e,t){if(e.status===Zf.UNRESOLVED)return{status:Qf.SKIPPED,reason:`unresolved`};let n=`${e.command}::${t}`,r=sp.get(n);if(r)return H.default.info(`[test-verification] Reusing in-flight gate: ${e.command}`),r;let i=this.executeGate(e,t);sp.set(n,i);try{return await i}finally{sp.delete(n)}}async executeGate(e,t){try{return await op(e.command,{cwd:t,encoding:`utf8`,timeout:3e5,maxBuffer:10485760}),{status:Qf.PASSED,command:e.command}}catch(t){let n=t,r=((n.stdout??``)+(n.stderr??``)).trim();return H.default.warn(`[test-verification] Gate failed: ${e.command}\n${r}`),{status:Qf.FAILED,command:e.command,output:r}}}};dp=(0,ap.default)([(0,_.injectable)()],dp);function fp(e,t,n){let r=(e,t)=>e.status===Zf.UNRESOLVED?e:t.status===Qf.PASSED?{status:Zf.VERIFIED,command:e.command}:{status:Zf.UNRESOLVED},i=(e,t,r)=>e.status===Zf.UNRESOLVED?e:t.status===Qf.PASSED?{status:Zf.VERIFIED,command:e.command}:t.status===Qf.FAILED&&!lp(t.output)?(up(t.output,n)||H.default.warn(`[test-verification] ${r} failed on unrelated files — promoting anyway`),{status:Zf.VERIFIED,command:e.command}):{status:Zf.UNRESOLVED};return{testCommand:r(e.testCommand,t.testCommand),buildCommand:i(e.buildCommand,t.buildCommand,`build`),lintCommand:i(e.lintCommand,t.lintCommand,`lint`),prettierCommand:i(e.prettierCommand,t.prettierCommand,`prettier`),packageManager:e.packageManager}}let pp=[`jest.config.ts`,`jest.config.js`,`jest.config.mjs`,`jest.config.cjs`,`vitest.config.ts`,`vitest.config.js`,`vitest.config.mjs`],mp=[`tsconfig.json`],hp=[`.eslintrc`,`.eslintrc.js`,`.eslintrc.cjs`,`.eslintrc.json`,`.eslintrc.yml`,`.eslintrc.yaml`,`eslint.config.js`,`eslint.config.mjs`,`eslint.config.cjs`,`eslint.config.ts`],gp=[`.prettierrc`,`.prettierrc.js`,`.prettierrc.cjs`,`.prettierrc.mjs`,`.prettierrc.json`,`.prettierrc.yaml`,`.prettierrc.yml`,`prettier.config.js`,`prettier.config.cjs`,`prettier.config.mjs`,`prettier.config.ts`],_p=new Set([`build`,`compile`,`dist`,`prepublish`,`prepublishOnly`,`prepare`]),vp=[`test:unit`,`test:ci`,`test:run`],yp=[`check:ts`,`typecheck`,`type-check`,`tsc`],bp=[`check:lint`,`lint`],xp=[`check:prettier`,`format`,`prettier`];function Sp(e){let t=[],n=e,r=f.default.parse(n).root;for(;n!==r&&(t.push(n),!(0,w.existsSync)(f.default.join(n,`.git`)));)n=f.default.dirname(n);return t}function Cp(e){let t=[];for(let n of Sp(e)){let e=f.default.join(n,`package.json`);if((0,w.existsSync)(e))try{let r=JSON.parse((0,w.readFileSync)(e,`utf8`));t.push({dir:n,pkg:r})}catch{}}return t}function wp(e,t){for(let n of e)for(let e of t)if((0,w.existsSync)(f.default.join(n,e)))return!0;return!1}function Tp(e){for(let t of e)for(let e of pp)if((0,w.existsSync)(f.default.join(t,e)))return e.startsWith(`vitest`)?`vitest`:`jest`;return null}function Ep(e,t){let n=Tp(t);if((0,h.isDefined)(n))return n;for(let{pkg:t}of e){let e=Rp(t);if((0,h.isDefined)(e.vitest))return`vitest`;if((0,h.isDefined)(e.jest))return`jest`;if((0,h.isDefined)(e.mocha))return`mocha`}return Dp(t,`vitest`)?`vitest`:Dp(t,`jest`)?`jest`:null}function Dp(e,t){for(let n of e)if((0,w.existsSync)(f.default.join(n,`node_modules`,`.bin`,t)))return!0;return!1}function Op(e){for(let t of Sp(e)){if((0,w.existsSync)(f.default.join(t,`pnpm-lock.yaml`))||(0,w.existsSync)(f.default.join(t,`pnpm-workspace.yaml`)))return`pnpm`;if((0,w.existsSync)(f.default.join(t,`yarn.lock`)))return`yarn`;if((0,w.existsSync)(f.default.join(t,`bun.lockb`))||(0,w.existsSync)(f.default.join(t,`bun.lock`)))return`bun`}return`npm`}function kp(e,t){return e===`yarn`?`yarn ${t}`:`${e} run ${t}`}function Ap(e,t){return e.startsWith(`npx `)||e.startsWith(`yarn `)?`${e} ${t}`:`${e} -- ${t}`}let jp=/(?:^echo\b)|(?:no test specified)|(?:placeholder)/i;function Mp(e,t){let n=e.scripts??{},r=Rp(e),i=n.test;if((0,h.isDefined)(i)&&!jp.test(i))return kp(t,`test`);for(let e of vp)if((0,h.isDefined)(n[e]))return kp(t,e);for(let[e,r]of Object.entries(n))if(/\bjest\b/.test(r)||/\bvitest\b/.test(r))return kp(t,e);return(0,h.isDefined)(r.jest)?`npx jest`:(0,h.isDefined)(r.vitest)?`npx vitest`:null}function Np(e,t,n){for(let{pkg:t}of e){let e=Mp(t,n);if((0,h.isDefined)(e))return e}let r=Tp(t);return(0,h.isDefined)(r)?(H.info.defaultLog(`[project-setup] test: found config file for ${r}`),`npx ${r}`):Dp(t,`jest`)?(H.info.defaultLog(`[project-setup] test: found jest in node_modules`),`npx jest`):Dp(t,`vitest`)?(H.info.defaultLog(`[project-setup] test: found vitest in node_modules`),`npx vitest`):null}function Pp(e,t){let n=e.scripts??{},r=Rp(e);for(let e of yp)if((0,h.isDefined)(n[e]))return kp(t,e);for(let[e,r]of Object.entries(n))if(/\btsc\b/.test(r)&&!_p.has(e))return kp(t,e);return(0,h.isDefined)(r.typescript)?`npx tsc --noEmit`:null}function Fp(e,t,n){for(let{pkg:t}of e){let e=Pp(t,n);if((0,h.isDefined)(e))return e}return wp(t,mp)?(H.info.defaultLog(`[project-setup] typecheck: found tsconfig.json`),`npx tsc --noEmit`):Dp(t,`tsc`)?(H.info.defaultLog(`[project-setup] typecheck: found tsc in node_modules`),`npx tsc --noEmit`):null}function Ip(e,t,n){for(let{pkg:t}of e){let e=t.scripts??{},r=Rp(t);for(let t of bp)if((0,h.isDefined)(e[t]))return kp(n,t);for(let[t,r]of Object.entries(e))if(/\beslint\b/.test(r))return kp(n,t);if((0,h.isDefined)(r.eslint))return`npx eslint`}return wp(t,hp)?(H.info.defaultLog(`[project-setup] lint: found eslint config file`),`npx eslint`):Dp(t,`eslint`)?(H.info.defaultLog(`[project-setup] lint: found eslint in node_modules`),`npx eslint`):null}function Lp(e,t,n){for(let{pkg:t}of e){let e=t.scripts??{},r=Rp(t);for(let t of xp)if((0,h.isDefined)(e[t]))return kp(n,t);for(let[t,r]of Object.entries(e))if(/\bprettier\b/.test(r))return kp(n,t);if((0,h.isDefined)(r.prettier))return`npx prettier`}return wp(t,gp)?(H.info.defaultLog(`[project-setup] prettier: found prettier config file`),`npx prettier`):Dp(t,`prettier`)?(H.info.defaultLog(`[project-setup] prettier: found prettier in node_modules`),`npx prettier`):null}function Rp(e){return{...e.dependencies,...e.devDependencies}}function zp(e,t){let n=Sp(e),r=Cp(e),i=Op(e),a=(0,h.isDefined)(t)?f.default.relative(e,t):null,o=Np(r,n,i),s=(0,h.isDefined)(o)&&(0,h.isDefined)(a)?Ap(o,a):null,c=Ep(r,n),l=Fp(r,n,i),u=Ip(r,n,i),d=(0,h.isDefined)(u)&&(0,h.isDefined)(a)?`npx eslint ${a}`:null,p=Lp(r,n,i),m=(0,h.isDefined)(p)&&(0,h.isDefined)(a)?`npx prettier ${a} --write`:null,g=[];return(0,h.isDefined)(s)||g.push(`testCommand`),(0,h.isDefined)(l)||g.push(`typecheckCommand`),(0,h.isDefined)(d)||g.push(`lintCommand`),(0,h.isDefined)(m)||g.push(`prettierCommand`),{testCommand:s,testRunner:c,typecheckCommand:l,lintCommand:d,prettierCommand:m,packageManager:i,missing:g}}let Bp=(0,O.promisify)(D.exec),Vp={testCommand:`test`,buildCommand:`build`,lintCommand:`lint`,prettierCommand:`format`},Hp=function(e){return e.TEST=`testCommand`,e.BUILD=`buildCommand`,e.LINT=`lintCommand`,e.FORMAT=`prettierCommand`,e}({});var Up=class{setup;testFilePath;workingDirectory;lastCheckAllResult=null;mcpServer;progressLogger;constructor(e){this.setup=e.setup,this.testFilePath=e.testFilePath,this.workingDirectory=e.workingDirectory,this.progressLogger=e.progressLogger??Me,this.mcpServer=this.buildServer()}getLastCheckAllResult(){return this.lastCheckAllResult}getServer(){return this.mcpServer}buildValidationSummary(){if(!(0,h.isDefined)(this.lastCheckAllResult))return;let e=this.lastCheckAllResult.gates.find(e=>e.gate===Hp.TEST),t=this.lastCheckAllResult.gates.find(e=>e.gate===Hp.LINT),n=(0,h.isDefined)(e?.output)?yf(e.output):void 0,r=(0,h.isDefined)(t?.output)?xf(t.output):0;return{greenTestsCount:n?.passed??0,redTestsCount:n?.failed??0,greyTestsCount:0,whiteTestsCount:0,naTestsCount:0,errorSuitsCount:n?.suitesFailed??0,lintErrorsCount:r}}async runGate(e){let t=this.setup[e];if(t.status===Zf.UNRESOLVED)return{gate:e,passed:!0,skipped:!0};try{let{stdout:n,stderr:r}=await Bp(t.command,{cwd:this.workingDirectory,encoding:`utf8`,timeout:3e5,maxBuffer:10485760});return{gate:e,passed:!0,skipped:!1,output:af((n+r).trim())}}catch(t){let n=of(t);if(e===Hp.BUILD||e===Hp.LINT){let t=f.default.basename(this.testFilePath);if(!n.includes(t))return{gate:e,passed:!0,skipped:!1,output:`[warning] ${Vp[e]??e} failed on unrelated files — not blocking.\n${n}`}}return{gate:e,passed:!1,skipped:!1,output:n}}}async checkAll(){let e=this.setup.lintCommand.status!==Zf.UNRESOLVED,t=this.setup.prettierCommand.status!==Zf.UNRESOLVED,n=await this.runStabilityLoop(e,t);if(n.stabilityConflict===!0)return this.lastCheckAllResult=n,n;this.progressLogger.verbose(`validating...`);let[r,i]=await Promise.all([this.runGate(Hp.TEST),this.runGate(Hp.BUILD)]),a=!1;if(!r.passed&&(0,h.isDefined)(r.output)){let e=yf(r.output);(0,h.isDefined)(e)&&e.passed>=6&&(a=!0,r.passed=!0)}let o=[...n.gates,r,i],s={passed:o.every(e=>e.passed),gates:o},c=s.gates.find(e=>e.gate===Hp.TEST),l=(0,h.isDefined)(c?.output)?yf(c.output):void 0,u=s.gates.filter(e=>!e.skipped).map(e=>`${Vp[e.gate]??e.gate} ${e.passed?`✓`:`✗`}`).join(` `),d=[];(0,h.isDefined)(l)&&(d.push(`${l.passed} green, ${l.failed} red`),l.suitesFailed>0&&d.push(`${l.suitesFailed} suite errors`));let f=d.length>0?` — ${d.join(`, `)}`:``;return this.progressLogger.verbose(`Validation ${s.passed?`passed`:`failed`}:`,u+f),a&&(0,h.isDefined)(l)&&this.progressLogger.verbose(`Pruning tests — ${l.passed} passing, ${l.failed} failing`),this.lastCheckAllResult=s,s}async runStabilityLoop(e,t){let n={gate:Hp.LINT,passed:!0,skipped:!0},r={gate:Hp.FORMAT,passed:!0,skipped:!0};if(!e&&!t)return{passed:!0,gates:[n,r]};let i=await(0,p.readFile)(this.testFilePath,`utf8`);for(let a=0;a<2;a++){let o=await Promise.all([e?this.runGate(Hp.LINT):Promise.resolve(n),t?this.runGate(Hp.FORMAT):Promise.resolve(r)]);if(n=o[0],r=o[1],!n.passed||!r.passed)break;let s=await(0,p.readFile)(this.testFilePath,`utf8`);if(s===i)break;if(a===1)return{passed:!1,stabilityConflict:!0,gates:[n,r]};i=s}return{passed:n.passed&&r.passed,gates:[n,r]}}buildServer(){let e=(0,oe.tool)(`check_lint`,`Runs the lint command against the test file and returns pass/fail with output. Use during iteration to check lint status.`,{},async()=>{let e=await this.runGate(Hp.LINT);return{content:[{type:`text`,text:JSON.stringify(e,null,2)}]}}),t=(0,oe.tool)(`check_format`,`Runs the format/prettier command against the test file and returns pass/fail with output. Use during iteration to check formatting status.`,{},async()=>{let e=await this.runGate(Hp.FORMAT);return{content:[{type:`text`,text:JSON.stringify(e,null,2)}]}}),n=(0,oe.tool)(`check_test`,`Runs the test command and returns pass/fail with output. Use during iteration to check test status.`,{},async()=>{let e=await this.runGate(Hp.TEST),t=(0,h.isDefined)(e.output)?yf(e.output):void 0;return!e.passed&&(0,h.isDefined)(t)&&t.passed>=6&&(this.progressLogger.verbose(`Pruning tests — ${t.passed} passing, ${t.failed} failing`),e.passed=!0),e.testReport=t,{content:[{type:`text`,text:JSON.stringify(e,null,2)}]}}),r=(0,oe.tool)(`check_build`,`Runs the build command and returns pass/fail with output. Use during iteration to check build status.`,{},async()=>{let e=await this.runGate(Hp.BUILD);return{content:[{type:`text`,text:JSON.stringify(e,null,2)}]}}),i=(0,oe.tool)(`check_all`,[`Runs ALL verification gates with a lint/format stability check.`,`First runs lint+format in a loop (max 2 iterations) to ensure they stabilize.`,`Then runs test+build once. Returns combined pass/fail.`,`You MUST call this tool and get all-green before completing your task.`,`If it reports a stability conflict, inform the user — do not retry.`].join(` `),{},async()=>{let e=await this.checkAll(),t=e.gates.find(e=>e.gate===Hp.TEST);return e.testReport=(0,h.isDefined)(t?.output)?yf(t.output):void 0,{content:[{type:`text`,text:JSON.stringify(e,null,2)}]}}),a=(0,oe.tool)(`get_status`,`Returns the current verification state: last check_all result and whether you are cleared to finish.`,{},async()=>{let e=this.getLastCheckAllResult(),t={lastCheckAllResult:e,clearedToFinish:e?.passed===!0};return{content:[{type:`text`,text:JSON.stringify(t,null,2)}]}});return(0,oe.createSdkMcpServer)({name:`verification_gates`,version:`1.0.0`,tools:[e,t,n,r,i,a]})}},Wp=l(Ie()),Gp=l(Cr()),Kp=l(Le()),qp,Jp,Yp,Xp;function Zp(e){return(0,h.isEmpty)(e)||!(0,w.existsSync)(e)?``:(0,w.readFileSync)(e,`utf8`)}function Qp(e){return(e.duration_ms/1e3).toFixed(1),``}function $p(e,t){return e+[``,`---`,`IMPORTANT: A test file has been pre-created at: ${t}`,`Use the Edit tool to add your test cases to this file. Do NOT create a new file with the Write tool.`].join(`
|
|
32081
|
-
`)}function
|
|
32082
|
-
`)}function
|
|
32083
|
-
`)}function
|
|
32084
|
-
`)}let
|
|
32085
|
-
`)},hooks:{PreToolUse:[{matcher:`Write|Edit`,hooks:[t]},{matcher:`Read`,hooks:[df]},{matcher:`Bash`,hooks:[uf,lf]}]}}});for await(let e of u)if(a.logMessage(e),await s.processMessage(e),$d(e)){await s.flush(),a.logResult(e),H.info.defaultLog(`[cleanup] SDK model usage: `,e.modelUsage),ef(e)&&H.default.warn(`[cleanup] Agent finished with error: ${e.subtype}`);break}}async runGenerationQuery(e){let t=ff(e.testFilePath,e.workingDirectory),n=bd?new
|
|
32086
|
-
`)},...n&&{mcpServers:{verification_gates:n.getServer()}},hooks:{PreToolUse:[{matcher:`Write|Edit`,hooks:[t]},{matcher:`Read`,hooks:[df]},{matcher:`Bash`,hooks:[uf,lf]}],PostToolUse:[{matcher:`Bash`,hooks:[Af]},{matcher:`${Sd}|${xd}`,hooks:[Af]}],...r&&{Stop:[{hooks:[r]}]}}}});for await(let t of l)if(i.logMessage(t),await c.processMessage(t),$d(t)){if(await c.flush(),i.logResult(t),H.info.defaultLog(`SDK model usage: `,t.modelUsage),ef(t))throw new ep(t.subtype,t.errors,t.total_cost_usd);let r=Zp(e.testFilePath),a=n?.buildValidationSummary()??i.buildValidationSummary();if(H.info.defaultLog(`Validation summary: `,a),!(0,h.isEmpty)(r)){let n=Qp(t)+r;return(0,w.writeFileSync)(e.testFilePath,n,`utf8`),{code:n,costUsd:t.total_cost_usd,validationSummary:a}}return{code:r,costUsd:t.total_cost_usd,validationSummary:a}}return{code:Zp(e.testFilePath)}}};um=(0,Kp.default)([(0,_.injectable)(),(0,Gp.default)(0,(0,_.inject)(He)),(0,Gp.default)(1,(0,_.inject)(Sr)),(0,Gp.default)(2,(0,_.inject)(zf)),(0,Gp.default)(3,(0,_.inject)(Yr)),(0,Gp.default)(4,(0,_.inject)(dp)),(0,Wp.default)(`design:paramtypes`,[Object,typeof(qp=Sr!==void 0&&Sr)==`function`?qp:Object,typeof(Jp=zf!==void 0&&zf)==`function`?Jp:Object,typeof(Yp=Yr!==void 0&&Yr)==`function`?Yp:Object,typeof(Xp=dp!==void 0&&dp)==`function`?Xp:Object])],um);var dm=class{execute(e){let t=!1,n=new Set(e.getKnownDependenciesSnapshot().flatMap(t=>e.getParentParameterRelations(t).filter(e=>e.depthLevelInParent>0).map(e=>e.parameterParentId)));for(let r of e.getKnownDependenciesSnapshot())e.getParentParameterRelations(r).every(e=>n.has(e.parameterParentId))&&(t||=e.moveKnownDependencyToMissing(r.name));let r=e.getDataSource().testedCodeDataSource.codeDependencies.length;return e.getDataSource().testedCodeDataSource.codeDependencies=e.getDataSource().testedCodeDataSource.codeDependencies.filter(t=>!e.getParentParameterRelations(t).every(e=>e.depthLevelInParent>0)),e.getDataSource().testedCodeDataSource.codeDependencies.length!==r&&(t=!0),t}},fm=class{kindsToRemove;constructor(...e){this.kindsToRemove=new Set(e)}execute(e){let t=!1;for(let n of e.getKnownDependenciesSnapshot())this.kindsToRemove.has(n.kind)&&(t||=e.moveKnownDependencyToMissing(n.name));return t}},pm=class{execute(e){let t=e.getDataSource().testedCodeDataSource.testedMethodClass,n=t?.constructorMetadata?.parameters??[],r=t?.properties??[],i=[...n,...r];return e.moveKnownDependencyToMissingByParameters(i)}},mm=class{kinds;constructor(...e){this.kinds=new Set(e)}execute(e){let t=!1,n=e.getMissingDependenciesSnapshot();for(let[r,i]of n.entries())this.kinds.has(i.kind)&&(t||=e.removeCodeInMissingDependencyByIndex(r));return t}},hm=class{execute(e){let t=e.getDataSource().testedCodeDataSource.testedMethod.parameters??[];return e.moveKnownDependencyToMissingByParameters(t)}},gm=class{execute(e){let t=e.getDataSourceSnapshot(),n=this.getParameters(t),r=!1;for(let i=0;i<t.testedCodeDataSource.missingDependencies.length;i++){let a=t.testedCodeDataSource.missingDependencies[i];(0,h.isDefined)(a.dependencyMetadata)&&(this.isMockDependencyKept(a.dependencyMetadata,n)||(r||=e.removeMockDependencyByIndex(i)))}return r}isMockDependencyKept(e,t){if((0,h.isEmpty)(t))return!1;let n=this.getParametersIdsFromMockDependency(e),r=(0,h.intersection)([...t],[...n]);return!(0,h.isEmpty)(r)}getParametersIdsFromMockDependency(e){let t=new h.SafeSet;if(!(0,h.isDefined)(e))return t.toSet();for(let n of e?.methodsMetadata??[]){for(let e of n.parameters)t.safeAdd(e.id);t.safeAdd(n?.returnParam?.id)}for(let n of e?.classMetadata?.properties??[])t.safeAdd(n?.id);for(let n of e?.classMetadata?.constructorMetadata?.parameters??[])t.safeAdd(n?.id);return t.toSet()}getParameters(e){let t=e.testedCodeDataSource.testedMethod.parameters.map(e=>e.id),n=e.testedCodeDataSource.testedMethod.returnParam?.id,r=e.testedCodeDataSource.testedMethodClass?.constructorMetadata?.parameters.map(e=>e.id)??[],i=e.testedCodeDataSource.testedMethodClass?.properties.map(e=>e.id)??[];return new h.SafeSet([...t,n,...r,...i]).toSet()}},_m=class{execute(e){let t=e.getDataSourceSnapshot(),n=t.testedCodeDataSource.testedMethod.parameters.map(e=>e.id),r=t.testedCodeDataSource.testedMethod.returnParam?.id,i=t.testedCodeDataSource.testedMethodClass?.constructorMetadata?.parameters.map(e=>e.id)??[],a=new Set([...n,r,...i].filter(e=>(0,h.isDefined)(e))),o=!1;for(let t of e.getKnownDependenciesSnapshot())this.isDependencyKept(t,a)||(o||=e.moveKnownDependencyToMissing(t.name));return o}isDependencyKept(e,t){return e.kind===`file`||e.kind===`enum`?!0:e.parentParameterRelations.some(e=>e.depthLevelInParent===0&&t.has(e.parameterParentId))}},vm=class{execute(e){let t=e.getDataSource().testedCodeDataSource.testedMethod.returnParam?.id;return(0,h.isDefined)(t)?e.moveKnowDependencyToMissingByParameterId(t):!1}},ym=class{dataSource;getKnownDependenciesSnapshot(){return this.getDataSourceSnapshot().testedCodeDataSource.codeDependencies}getMissingDependenciesSnapshot(){return this.getDataSourceSnapshot().testedCodeDataSource.missingDependencies}constructor(e){this.dataSource=e}getDataSourceSnapshot(){return structuredClone(this.dataSource)}getDataSource(){return this.dataSource}getParentParameterRelations(e){return e.kind===`file`?[]:e.parentParameterRelations}moveKnownDependencyToMissingByParameters(e){let t=e.map(e=>e.id).filter(e=>(0,h.isString)(e)),n=!1;for(let e of t)n||=this.moveKnowDependencyToMissingByParameterId(e);return n}moveKnownDependencyToMissing(e){let t=this.dataSource.testedCodeDataSource.codeDependencies.findIndex(t=>t.name===e);if(t===-1)return!1;let n=this.dataSource.testedCodeDataSource.codeDependencies[t],r=`parentParameterRelations`in n?n.parentParameterRelations:[];if(r.length>1)return!1;let i=r[0]?.parameterParentId;return(0,h.isDefined)(i)?this.moveKnowDependencyToMissingByParameterId(i):this.moveKnowDependencyToMissingByIndex(t)}moveKnowDependencyToMissingByParameterId(e){let t=this.dataSource.testedCodeDataSource.codeDependencies.filter(t=>{let n=this.getParentParameterRelations(t);return n.length===1&&n[0].parameterParentId===e}),n=!1;for(let e of t){this.getParentParameterRelations(e)[0].depthLevelInParent===0&&(this.dataSource.testedCodeDataSource.missingDependencies.push(this.convertCodeDependencyToMissingDependency(e)),n=!0);let t=this.dataSource.testedCodeDataSource.codeDependencies.length;this.dataSource.testedCodeDataSource.codeDependencies=this.dataSource.testedCodeDataSource.codeDependencies.filter(t=>t.name!==e.name),this.dataSource.testedCodeDataSource.codeDependencies.length!==t&&(n=!0)}return n}moveKnowDependencyToMissingByIndex(e){if(e<0||this.dataSource.testedCodeDataSource.codeDependencies.length<=e)return!1;let t=this.dataSource.testedCodeDataSource.codeDependencies[e],n=this.convertCodeDependencyToMissingDependency(t);return this.dataSource.testedCodeDataSource.codeDependencies.splice(e,1),this.dataSource.testedCodeDataSource.missingDependencies.push(n),!0}convertCodeDependencyToMissingDependency(e){let t=(e.kind===`file`?!1:e.containedInTestedFile)??!1;return{name:e.name,kind:e.kind,importPath:e.importPath,code:e.code,isCoreModule:!1,exportType:kt.Unknown,containedInTestedFile:t,isDataObject:e.isDataObject??!1,parentParameterRelations:e.kind===`file`?[]:e.parentParameterRelations,isGenerated:e.isGenerated,baseTypeNames:e.kind===`file`?[]:e.baseTypeNames,ancestorDepthFromTestedClass:e.kind===`file`?void 0:e.ancestorDepthFromTestedClass,importUsageMetadata:e.kind===`file`?void 0:e.importUsageMetadata}}removeMockDependencyByIndex(e){let t=this.dataSource.testedCodeDataSource.missingDependencies?.[e];if(!(0,h.isDefined)(t))return!1;let n=t.dependencyMetadata;return(0,h.isDefined)(n)?(t.dependencyMetadata=void 0,!0):!1}removeCodeInMissingDependencyByIndex(e){let t=this.dataSource.testedCodeDataSource.missingDependencies?.[e];return(0,h.isEmpty)(t?.code)?!1:(t.code=``,!0)}},bm=class{modifierHandlers=[];modifierCount;constructor(){let e=new mm(`react-class-component`,`react-hook`,`react-forward-ref-component`,`react-function-component`,`react-css-in-js`),t=new fm(`class`),n=new _m,r=new pm,i=new hm,a=new vm,o=new dm,s=new gm;this.modifierHandlers.push(e,t,n,r,i,a,o,s),this.modifierCount=this.modifierHandlers.length}refine(e){let t=new ym(e);for(let e of this.modifierHandlers)if(e.execute(t))return!0;return!1}},xm=class e{testCodeDatasourceRefiner=new bm;sizeLimit=0;constructor(e){this.sizeLimit=e??this.sizeLimit}static async init(t){return new e(await t.getDataSourceOptimizerSizeLimit())}async optimize(e){if(this.sizeLimit===0)return e;try{let t=structuredClone(e);return await this.iterateOptimize(t,1)}catch{return e}}getSizeInKilobytes(e){let t=JSON.stringify(e);return Buffer.byteLength(t)/1024}async iterateOptimize(e,t){if(this.testCodeDatasourceRefiner.modifierCount<t||!this.testCodeDatasourceRefiner.refine(e))return e;let n=await this.iterateOptimize(e,t+1);return this.getSizeInKilobytes(n)<=this.sizeLimit?n:await this.iterateOptimize(e,t+1)}};let Sm=()=>Ue().getRequestSource()===ue.IDE;var Cm=l(Ie()),wm=l(Le()),Tm=class{sourceFileCache=new Map;constructor(e,t){this.testable=e,this.filePath=t}async getReferences(e=2){let t=Jt.get(this.filePath),n=this.findTargetNode(t);if(!n)return[];let r=n.findReferences(),i=[];for(let e of r)for(let t of e.getReferences()){if(t.isDefinition()??!1)continue;let e=t.getSourceFile().getFilePath();if(!/\.spec|\.test/g.test(e)){let e=await this.getReferencedTestables(t);i.push(...e)}}return(0,h.uniqWith)(i,(e,t)=>e.node===t.node).slice(0,e).map(e=>e.node.getText())}findTargetNode(e){return e.getDescendantsOfKind(E.SyntaxKind.Identifier).find(e=>e.getText()===this.testable.name)}async getTestables(e){let t=e.getSourceFile(),n=t.getFilePath(),r=this.sourceFileCache.get(n);if((0,h.isDefined)(r))return r;let i=new Mn(await et.fromSourceFile(t).getText()).testables.getAllTestables();return this.sourceFileCache.set(n,i),i}async getReferencedTestables(e){try{let t=e.getNode(),[n,r]=[t.getStart(),t.getEnd()];return(await this.getTestables(e)).filter(({type:e,node:t})=>e===`class`||e===`object-method`?!1:t.containsRange(n,r))}catch(e){return H.error(`Error while getting js usage reference code`,e),[]}}};(0,wm.default)([Yt,(0,Cm.default)(`design:type`,Function),(0,Cm.default)(`design:paramtypes`,[Object]),(0,Cm.default)(`design:returntype`,Promise)],Tm.prototype,`getReferences`,null);var Em=l(Ie()),Dm=l(Cr()),Om=l(Le()),km;let Am=class{constructor(e){this.dependenciesService=e}async getTestedCodeDataSource(e,t,n){await Jt.init(e);let{methodType:r,methodName:i,parentName:a}=ai(t);H.addContext({subCategory:Et.CODE_EXTRACTOR}),H.debug.defaultLog(`Get testable context for ${r} ${i}() in ${e}.`);try{let o=await new et(e).getText(),s=at((0,f.extname)(e)),c=zl(s),l=c.extract({methodName:i,methodType:r,parentName:a,filePath:e}),u=Sm(),d=await this.dependenciesService.getTestCodeDataSourceCore(l,e,u);if(s===`javascript`)return Wa(await this.getJsCodeDataSource(e,t,o,d,l,n));let p,m,g,_,v={name:`NA`,kind:`file`,code:o,importPath:e,dependencyType:`file`,isGenerated:!1},b=[];(0,h.isDefined)(d)?(p=d.codeDependencies,m=d.missingDependencies,g=d.testedMethod,_=d.testedMethodClass,v=d.fileCodeDependency,b=d.libraries):(H.info.defaultLog(`No data source for ${i} - ${r}`),m=[],p=[],g={name:i,isAsync:!1,isStatic:!1,parameters:[],decorators:[],code:o.slice(t.startIndex,t.endIndex),callExpressions:[],imports:[],accessModifierType:At.PUBLIC,extendedProperties:{},signature:``,parameterId:(0,y.randomUUID)(),kind:`any`,exportType:kt.Unknown});let x=await new Tm(t,e).getReferences();return m=await this.reevaluateMissingDependencies(m,d,c),Wa({gitUrl:Ue().getGitURL(),filePath:e,relativePathToTestFile:this.getRelativePathToTestFile(e,n),testFramework:Ue().getTestFramework(),language:s,testedMethod:g,testedMethodClass:_,missingDependencies:m,codeDependencies:[v,...p],usages:x,libraries:b})}catch(e){throw H.error(`Error occurred during getTestedCodeDataSource ${i}`,e,i),new sr(ar.TESTED_CODE_DATA_SOURCE_ERROR,{methodName:i})}}async getJsCodeDataSource(e,t,n,r,i,a){let{methodName:o}=ai(t),s={name:o,isAsync:!1,isStatic:!1,parameters:[],decorators:[],code:n.slice(t.startIndex,t.endIndex),callExpressions:[],imports:r?.testedMethod.imports??[],exportType:r?.testedMethod.exportType??kt.Named,accessModifierType:r?.testedMethod.accessModifierType??At.PUBLIC,extendedProperties:r?.testedMethod.extendedProperties,signature:``,parameterId:(0,y.randomUUID)(),kind:`any`},c={name:`NA`,kind:`file`,code:n,importPath:e,dependencyType:`file`,isGenerated:!1},l=await new Tm(t,e).getReferences(),u=[];if((0,h.isDefined)(i)){let t=await new sc(i,e).extract(),n=i.testedMethod.nestedReactComponents?.hooks??[],r=i.testedMethod.nestedReactComponents?.jsxElements??[],a=[...n,...r].map(t=>({name:t.name,kind:t.kind,importPath:t.importPath,isCoreModule:t.isCoreModule,code:t.code,containedInTestedFile:Za(e,t),exportType:t.exportType,isDataObject:!1,parentParameterIds:[],parentParameterRelations:[],dependenciesMetadata:[],isGenerated:t.isGenerated,baseTypeNames:[]})),o=t.filter(e=>[`function`,`react-function-component`].includes(e.kind)).map(e=>({name:e.name,kind:e.kind,importPath:e.importPath,isCoreModule:e.isCoreModule,code:e.code,containedInTestedFile:e.containedInTestedFile,exportType:e.exportType,isDataObject:!1,parentParameterIds:[],parentParameterRelations:[],dependenciesMetadata:[],isGenerated:e.isGenerated,baseTypeNames:[]}));u=(0,h.uniqWith)([...o,...a],(e,t)=>e.name===t.name)}return{gitUrl:Ue().getGitURL(),filePath:e,relativePathToTestFile:this.getRelativePathToTestFile(e,a),testFramework:Ue().getTestFramework(),language:`javascript`,testedMethod:s,testedMethodClass:void 0,missingDependencies:u,codeDependencies:[c],usages:l,libraries:r?.libraries??[]}}async getSecondLevelReactMissingDependencies(e,t){if(!(0,h.isDefined)(e))return[];let n=Sm(),r=e.missingDependencies.filter(e=>e.kind===`react-function-component`);return(await Promise.all(r.map(async e=>{let r=e.sourceFile;if(!(0,h.isDefined)(r))return null;let i=et.fromAbsolutePath(r.getFilePath()).getRelativeFilePath(),a=t.extract({methodName:e.name,methodType:`function`,filePath:i});return await this.dependenciesService.getTestCodeDataSourceCore(a,i,n)}))).filter(e=>(0,h.isDefined)(e))}async reevaluateMissingDependencies(e,t,n){if(!(0,h.isDefined)(t))return e;let r=t.testedMethod.parameterId,i=(e,t)=>({...e,parentParameterIds:[r,...e.parentParameterIds],parentParameterRelations:[{parameterParentId:r,depthLevelInParent:t},...e.parentParameterRelations]}),a=t.missingDependencies.map(e=>i(e,1)),o=(await this.getSecondLevelReactMissingDependencies(t,n)).flatMap(e=>e.missingDependencies.map(e=>i(e,2)));return(0,h.uniqWith)([...a,...o],(e,t)=>e.name===t.name&&e.kind===t.kind)}getRelativePathToTestFile(e,t){let n=Jt.get(e);return Jt.get(t).getRelativePathTo(n)}};(0,Om.default)([Yt,(0,Em.default)(`design:type`,Function),(0,Em.default)(`design:paramtypes`,[String,Object,String]),(0,Em.default)(`design:returntype`,Promise)],Am.prototype,`getTestedCodeDataSource`,null),Am=(0,Om.default)([(0,_.injectable)(),(0,Dm.default)(0,(0,_.inject)(Pc)),(0,Em.default)(`design:paramtypes`,[typeof(km=Pc!==void 0&&Pc)==`function`?km:Object])],Am);var jm=l(Ie()),Mm=l(Cr()),Nm=l(Le()),Pm,Fm;let Im=class{constructor(e,t,n){this.globalConfigService=e,this.featureFlagsService=t,this.testableContextService=n}async gatherDataSource(e){let t=await this.testableContextService.getTestedCodeDataSource(e.path,e.testable,e.testFilePath),n={...(0,h.isDefined)(this.globalConfigService.getGenerateTestsLLMModelName())&&{modelName:this.globalConfigService.getGenerateTestsLLMModelName()},...(0,h.isDefined)(this.globalConfigService.getLLMTemperature())&&{temperature:this.globalConfigService.getLLMTemperature()},...(0,h.isDefined)(this.globalConfigService.getLLMTopP())&&{topP:this.globalConfigService.getLLMTopP()}},r=H.getRequestId();return await this.prepareDTO({dataSource:t,llmConfig:n,userPrompt:(0,h.isDefined)(e.userPrompt)&&!(0,h.isEmpty)(e.userPrompt)?e.userPrompt:this.globalConfigService.getUserPrompt(),generatedTestStructure:this.globalConfigService.getGeneratedTestStructure()},r)}async prepareDTO(e,t){let n=e.dataSource.testedMethod.name;H.debug.defaultLog(`Preparing dto for method ${n}`);try{let t=Yl(e,await this.featureFlagsService.isRemovingDuplicatedCodeInDependencyMetadataEnabled());return(await xm.init(this.featureFlagsService)).optimize(t)}catch(e){throw H.info.defaultLog(`Failed making preparations for generate test dto`,e,t),new sr(ar.PREPARATIONS_FOR_GENERATING_TEST_DTO_ERROR,{methodName:n,errorMessage:`Failed making preparations for generate test dto`})}}};Im=(0,Nm.default)([(0,_.injectable)(),(0,Mm.default)(0,(0,_.inject)(He)),(0,Mm.default)(1,(0,_.inject)(kc)),(0,Mm.default)(2,(0,_.inject)(Am)),(0,jm.default)(`design:paramtypes`,[typeof(Pm=He!==void 0&&He)==`function`?Pm:Object,Object,typeof(Fm=Am!==void 0&&Am)==`function`?Fm:Object])],Im);var Lm=l(Ie()),Rm=l(Cr()),zm=l(Le()),Bm,Vm;let Hm=class{constructor(e,t,n){this.apiService=e,this.globalConfigService=t,this.agentSdkRunner=n}async generate(e,t,n,r,i,a){let o={...e,testedCodeDataSource:{...e.testedCodeDataSource,metadataCollectionTime:n}};if(this.globalConfigService.getExperimentalAgentSdk()){H.info.defaultLog(`[experimental] Using generate-prompt endpoint`);let e;try{e=await this.generatePrompt(o,t,r)}catch(e){throw this.globalConfigService.getProgressLogger(a).verbose(`Failed to analyze function — skipping`),e}return this.generateTestViaClaudeAgentSdk(e,i,r,a)}return this.generateViaBackend(o,t,r)}async generateViaBackend(e,t,n){return this.apiService.post(`/api/v1/tests/generate-tests`,e,{headers:{[lr]:t},signal:n})}async generatePrompt(e,t,n){return await this.apiService.post(`/api/v1/tests/generate-prompt`,e,{headers:{[lr]:t},signal:n})}async generateTestViaClaudeAgentSdk(e,t,n,r){if(!(0,h.isDefined)(t)||(0,h.isEmpty)(t))throw Error(`[agent-sdk] testFilePath is required for experimental SDK flow`);H.info.defaultLog(`[agent-sdk] Running Claude Agent SDK locally...`);let i=this.globalConfigService.getRootPath(),a=(bd?`You are an expert unit test generation agent. Your goal is to produce 7-12 high-quality, passing, type-safe, lint-clean unit tests for a given function or method.
|
|
32080
|
+
`;default:return np}}function ip(e){return(0,h.isDefined)(e)?{status:Qf.RESOLVED,command:e}:{status:Qf.UNRESOLVED}}function ap(e){return{testCommand:ip(e.testCommand),buildCommand:ip(e.typecheckCommand),lintCommand:ip(e.lintCommand),prettierCommand:ip(e.prettierCommand),packageManager:e.packageManager}}var op=l(Le());let sp=(0,O.promisify)(D.exec),cp=new Map,lp=[/Oops! Something went wrong/i,/ESLint couldn't find a?n? ?configuration/i,/Cannot find module/i,/MODULE_NOT_FOUND/,/ENOENT/,/command not found/i,/ERR_MODULE_NOT_FOUND/,/Cannot read config file/i,/No ESLint configuration found/i,/Error: No files matching/i];function up(e){return lp.some(t=>t.test(e))}function dp(e,t){let n=f.default.basename(t);return e.includes(n)}let fp=class{async verify(e){let{setup:t,workingDirectory:n}=e,[r,i,a,o]=await Promise.all([this.runGate(t.testCommand,n),this.runGate(t.buildCommand,n),this.runGate(t.lintCommand,n),this.runGate(t.prettierCommand,n)]);return{testCommand:r,buildCommand:i,lintCommand:a,prettierCommand:o,passed:r.status!==$f.FAILED&&i.status!==$f.FAILED&&a.status!==$f.FAILED&&o.status!==$f.FAILED}}async runGate(e,t){if(e.status===Qf.UNRESOLVED)return{status:$f.SKIPPED,reason:`unresolved`};let n=`${e.command}::${t}`,r=cp.get(n);if(r)return H.default.info(`[test-verification] Reusing in-flight gate: ${e.command}`),r;let i=this.executeGate(e,t);cp.set(n,i);try{return await i}finally{cp.delete(n)}}async executeGate(e,t){try{return await sp(e.command,{cwd:t,encoding:`utf8`,timeout:3e5,maxBuffer:10485760}),{status:$f.PASSED,command:e.command}}catch(t){let n=t,r=((n.stdout??``)+(n.stderr??``)).trim();return H.default.warn(`[test-verification] Gate failed: ${e.command}\n${r}`),{status:$f.FAILED,command:e.command,output:r}}}};fp=(0,op.default)([(0,_.injectable)()],fp);function pp(e,t,n){let r=(e,t)=>e.status===Qf.UNRESOLVED?e:t.status===$f.PASSED?{status:Qf.VERIFIED,command:e.command}:{status:Qf.UNRESOLVED},i=(e,t,r)=>e.status===Qf.UNRESOLVED?e:t.status===$f.PASSED?{status:Qf.VERIFIED,command:e.command}:t.status===$f.FAILED&&!up(t.output)?(dp(t.output,n)||H.default.warn(`[test-verification] ${r} failed on unrelated files — promoting anyway`),{status:Qf.VERIFIED,command:e.command}):{status:Qf.UNRESOLVED};return{testCommand:r(e.testCommand,t.testCommand),buildCommand:i(e.buildCommand,t.buildCommand,`build`),lintCommand:i(e.lintCommand,t.lintCommand,`lint`),prettierCommand:i(e.prettierCommand,t.prettierCommand,`prettier`),packageManager:e.packageManager}}let mp=[`jest.config.ts`,`jest.config.js`,`jest.config.mjs`,`jest.config.cjs`,`vitest.config.ts`,`vitest.config.js`,`vitest.config.mjs`],hp=[`tsconfig.json`],gp=[`.eslintrc`,`.eslintrc.js`,`.eslintrc.cjs`,`.eslintrc.json`,`.eslintrc.yml`,`.eslintrc.yaml`,`eslint.config.js`,`eslint.config.mjs`,`eslint.config.cjs`,`eslint.config.ts`],_p=[`.prettierrc`,`.prettierrc.js`,`.prettierrc.cjs`,`.prettierrc.mjs`,`.prettierrc.json`,`.prettierrc.yaml`,`.prettierrc.yml`,`prettier.config.js`,`prettier.config.cjs`,`prettier.config.mjs`,`prettier.config.ts`],vp=new Set([`build`,`compile`,`dist`,`prepublish`,`prepublishOnly`,`prepare`]),yp=[`test:unit`,`test:ci`,`test:run`],bp=[`check:ts`,`typecheck`,`type-check`,`tsc`],xp=[`check:lint`,`lint`],Sp=[`check:prettier`,`format`,`prettier`];function Cp(e){let t=[],n=e,r=f.default.parse(n).root;for(;n!==r&&(t.push(n),!(0,w.existsSync)(f.default.join(n,`.git`)));)n=f.default.dirname(n);return t}function wp(e){let t=[];for(let n of Cp(e)){let e=f.default.join(n,`package.json`);if((0,w.existsSync)(e))try{let r=JSON.parse((0,w.readFileSync)(e,`utf8`));t.push({dir:n,pkg:r})}catch{}}return t}function Tp(e,t){for(let n of e)for(let e of t)if((0,w.existsSync)(f.default.join(n,e)))return!0;return!1}function Ep(e){for(let t of e)for(let e of mp)if((0,w.existsSync)(f.default.join(t,e)))return e.startsWith(`vitest`)?`vitest`:`jest`;return null}function Dp(e,t){let n=Ep(t);if((0,h.isDefined)(n))return n;for(let{pkg:t}of e){let e=zp(t);if((0,h.isDefined)(e.vitest))return`vitest`;if((0,h.isDefined)(e.jest))return`jest`;if((0,h.isDefined)(e.mocha))return`mocha`}return Op(t,`vitest`)?`vitest`:Op(t,`jest`)?`jest`:null}function Op(e,t){for(let n of e)if((0,w.existsSync)(f.default.join(n,`node_modules`,`.bin`,t)))return!0;return!1}function kp(e){for(let t of Cp(e)){if((0,w.existsSync)(f.default.join(t,`pnpm-lock.yaml`))||(0,w.existsSync)(f.default.join(t,`pnpm-workspace.yaml`)))return`pnpm`;if((0,w.existsSync)(f.default.join(t,`yarn.lock`)))return`yarn`;if((0,w.existsSync)(f.default.join(t,`bun.lockb`))||(0,w.existsSync)(f.default.join(t,`bun.lock`)))return`bun`}return`npm`}function Ap(e,t){return e===`yarn`?`yarn ${t}`:`${e} run ${t}`}function jp(e,t){return e.startsWith(`npx `)||e.startsWith(`yarn `)?`${e} ${t}`:`${e} -- ${t}`}let Mp=/(?:^echo\b)|(?:no test specified)|(?:placeholder)/i;function Np(e,t){let n=e.scripts??{},r=zp(e),i=n.test;if((0,h.isDefined)(i)&&!Mp.test(i))return Ap(t,`test`);for(let e of yp)if((0,h.isDefined)(n[e]))return Ap(t,e);for(let[e,r]of Object.entries(n))if(/\bjest\b/.test(r)||/\bvitest\b/.test(r))return Ap(t,e);return(0,h.isDefined)(r.jest)?`npx jest`:(0,h.isDefined)(r.vitest)?`npx vitest`:null}function Pp(e,t,n){for(let{pkg:t}of e){let e=Np(t,n);if((0,h.isDefined)(e))return e}let r=Ep(t);return(0,h.isDefined)(r)?(H.info.defaultLog(`[project-setup] test: found config file for ${r}`),`npx ${r}`):Op(t,`jest`)?(H.info.defaultLog(`[project-setup] test: found jest in node_modules`),`npx jest`):Op(t,`vitest`)?(H.info.defaultLog(`[project-setup] test: found vitest in node_modules`),`npx vitest`):null}function Fp(e,t){let n=e.scripts??{},r=zp(e);for(let e of bp)if((0,h.isDefined)(n[e]))return Ap(t,e);for(let[e,r]of Object.entries(n))if(/\btsc\b/.test(r)&&!vp.has(e))return Ap(t,e);return(0,h.isDefined)(r.typescript)?`npx tsc --noEmit`:null}function Ip(e,t,n){for(let{pkg:t}of e){let e=Fp(t,n);if((0,h.isDefined)(e))return e}return Tp(t,hp)?(H.info.defaultLog(`[project-setup] typecheck: found tsconfig.json`),`npx tsc --noEmit`):Op(t,`tsc`)?(H.info.defaultLog(`[project-setup] typecheck: found tsc in node_modules`),`npx tsc --noEmit`):null}function Lp(e,t,n){for(let{pkg:t}of e){let e=t.scripts??{},r=zp(t);for(let t of xp)if((0,h.isDefined)(e[t]))return Ap(n,t);for(let[t,r]of Object.entries(e))if(/\beslint\b/.test(r))return Ap(n,t);if((0,h.isDefined)(r.eslint))return`npx eslint`}return Tp(t,gp)?(H.info.defaultLog(`[project-setup] lint: found eslint config file`),`npx eslint`):Op(t,`eslint`)?(H.info.defaultLog(`[project-setup] lint: found eslint in node_modules`),`npx eslint`):null}function Rp(e,t,n){for(let{pkg:t}of e){let e=t.scripts??{},r=zp(t);for(let t of Sp)if((0,h.isDefined)(e[t]))return Ap(n,t);for(let[t,r]of Object.entries(e))if(/\bprettier\b/.test(r))return Ap(n,t);if((0,h.isDefined)(r.prettier))return`npx prettier`}return Tp(t,_p)?(H.info.defaultLog(`[project-setup] prettier: found prettier config file`),`npx prettier`):Op(t,`prettier`)?(H.info.defaultLog(`[project-setup] prettier: found prettier in node_modules`),`npx prettier`):null}function zp(e){return{...e.dependencies,...e.devDependencies}}function Bp(e,t){let n=Cp(e),r=wp(e),i=kp(e),a=(0,h.isDefined)(t)?f.default.relative(e,t):null,o=Pp(r,n,i),s=(0,h.isDefined)(o)&&(0,h.isDefined)(a)?jp(o,a):null,c=Dp(r,n),l=Ip(r,n,i),u=Lp(r,n,i),d=(0,h.isDefined)(u)&&(0,h.isDefined)(a)?`npx eslint ${a}`:null,p=Rp(r,n,i),m=(0,h.isDefined)(p)&&(0,h.isDefined)(a)?`npx prettier ${a} --write`:null,g=[];return(0,h.isDefined)(s)||g.push(`testCommand`),(0,h.isDefined)(l)||g.push(`typecheckCommand`),(0,h.isDefined)(d)||g.push(`lintCommand`),(0,h.isDefined)(m)||g.push(`prettierCommand`),{testCommand:s,testRunner:c,typecheckCommand:l,lintCommand:d,prettierCommand:m,packageManager:i,missing:g}}let Vp=(0,O.promisify)(D.exec),Hp={testCommand:`test`,buildCommand:`build`,lintCommand:`lint`,prettierCommand:`format`},Up=function(e){return e.TEST=`testCommand`,e.BUILD=`buildCommand`,e.LINT=`lintCommand`,e.FORMAT=`prettierCommand`,e}({});var Wp=class{setup;testFilePath;workingDirectory;lastCheckAllResult=null;mcpServer;progressLogger;constructor(e){this.setup=e.setup,this.testFilePath=e.testFilePath,this.workingDirectory=e.workingDirectory,this.progressLogger=e.progressLogger??Me,this.mcpServer=this.buildServer()}getLastCheckAllResult(){return this.lastCheckAllResult}getServer(){return this.mcpServer}buildValidationSummary(){if(!(0,h.isDefined)(this.lastCheckAllResult))return;let e=this.lastCheckAllResult.gates.find(e=>e.gate===Up.TEST),t=this.lastCheckAllResult.gates.find(e=>e.gate===Up.LINT),n=(0,h.isDefined)(e?.output)?yf(e.output):void 0,r=(0,h.isDefined)(t?.output)?xf(t.output):0;return{greenTestsCount:n?.passed??0,redTestsCount:n?.failed??0,greyTestsCount:0,whiteTestsCount:0,naTestsCount:0,errorSuitsCount:n?.suitesFailed??0,lintErrorsCount:r}}async runGate(e){let t=this.setup[e];if(t.status===Qf.UNRESOLVED)return{gate:e,passed:!0,skipped:!0};try{let{stdout:n,stderr:r}=await Vp(t.command,{cwd:this.workingDirectory,encoding:`utf8`,timeout:3e5,maxBuffer:10485760});return{gate:e,passed:!0,skipped:!1,output:af((n+r).trim())}}catch(t){let n=of(t);if(e===Up.BUILD||e===Up.LINT){let t=f.default.basename(this.testFilePath);if(!n.includes(t))return{gate:e,passed:!0,skipped:!1,output:`[warning] ${Hp[e]??e} failed on unrelated files — not blocking.\n${n}`}}return{gate:e,passed:!1,skipped:!1,output:n}}}async checkAll(){let e=this.setup.lintCommand.status!==Qf.UNRESOLVED,t=this.setup.prettierCommand.status!==Qf.UNRESOLVED,n=await this.runStabilityLoop(e,t);if(n.stabilityConflict===!0)return this.lastCheckAllResult=n,n;this.progressLogger.verbose(`validating...`);let[r,i]=await Promise.all([this.runGate(Up.TEST),this.runGate(Up.BUILD)]),a=!1;if(!r.passed&&(0,h.isDefined)(r.output)){let e=yf(r.output);(0,h.isDefined)(e)&&e.passed>=6&&(a=!0,r.passed=!0)}let o=[...n.gates,r,i],s={passed:o.every(e=>e.passed),gates:o},c=s.gates.find(e=>e.gate===Up.TEST),l=(0,h.isDefined)(c?.output)?yf(c.output):void 0,u=s.gates.filter(e=>!e.skipped).map(e=>`${Hp[e.gate]??e.gate} ${e.passed?`✓`:`✗`}`).join(` `),d=[];(0,h.isDefined)(l)&&(d.push(`${l.passed} green, ${l.failed} red`),l.suitesFailed>0&&d.push(`${l.suitesFailed} suite errors`));let f=d.length>0?` — ${d.join(`, `)}`:``;return this.progressLogger.verbose(`Validation ${s.passed?`passed`:`failed`}:`,u+f),a&&(0,h.isDefined)(l)&&this.progressLogger.verbose(`Pruning tests — ${l.passed} passing, ${l.failed} failing`),this.lastCheckAllResult=s,s}async runStabilityLoop(e,t){let n={gate:Up.LINT,passed:!0,skipped:!0},r={gate:Up.FORMAT,passed:!0,skipped:!0};if(!e&&!t)return{passed:!0,gates:[n,r]};let i=await(0,p.readFile)(this.testFilePath,`utf8`);for(let a=0;a<2;a++){let o=await Promise.all([e?this.runGate(Up.LINT):Promise.resolve(n),t?this.runGate(Up.FORMAT):Promise.resolve(r)]);if(n=o[0],r=o[1],!n.passed||!r.passed)break;let s=await(0,p.readFile)(this.testFilePath,`utf8`);if(s===i)break;if(a===1)return{passed:!1,stabilityConflict:!0,gates:[n,r]};i=s}return{passed:n.passed&&r.passed,gates:[n,r]}}buildServer(){let e=(0,oe.tool)(`check_lint`,`Runs the lint command against the test file and returns pass/fail with output. Use during iteration to check lint status.`,{},async()=>{let e=await this.runGate(Up.LINT);return{content:[{type:`text`,text:JSON.stringify(e,null,2)}]}}),t=(0,oe.tool)(`check_format`,`Runs the format/prettier command against the test file and returns pass/fail with output. Use during iteration to check formatting status.`,{},async()=>{let e=await this.runGate(Up.FORMAT);return{content:[{type:`text`,text:JSON.stringify(e,null,2)}]}}),n=(0,oe.tool)(`check_test`,`Runs the test command and returns pass/fail with output. Use during iteration to check test status.`,{},async()=>{let e=await this.runGate(Up.TEST),t=(0,h.isDefined)(e.output)?yf(e.output):void 0;return!e.passed&&(0,h.isDefined)(t)&&t.passed>=6&&(this.progressLogger.verbose(`Pruning tests — ${t.passed} passing, ${t.failed} failing`),e.passed=!0),e.testReport=t,{content:[{type:`text`,text:JSON.stringify(e,null,2)}]}}),r=(0,oe.tool)(`check_build`,`Runs the build command and returns pass/fail with output. Use during iteration to check build status.`,{},async()=>{let e=await this.runGate(Up.BUILD);return{content:[{type:`text`,text:JSON.stringify(e,null,2)}]}}),i=(0,oe.tool)(`check_all`,[`Runs ALL verification gates with a lint/format stability check.`,`First runs lint+format in a loop (max 2 iterations) to ensure they stabilize.`,`Then runs test+build once. Returns combined pass/fail.`,`You MUST call this tool and get all-green before completing your task.`,`If it reports a stability conflict, inform the user — do not retry.`].join(` `),{},async()=>{let e=await this.checkAll(),t=e.gates.find(e=>e.gate===Up.TEST);return e.testReport=(0,h.isDefined)(t?.output)?yf(t.output):void 0,{content:[{type:`text`,text:JSON.stringify(e,null,2)}]}}),a=(0,oe.tool)(`get_status`,`Returns the current verification state: last check_all result and whether you are cleared to finish.`,{},async()=>{let e=this.getLastCheckAllResult(),t={lastCheckAllResult:e,clearedToFinish:e?.passed===!0};return{content:[{type:`text`,text:JSON.stringify(t,null,2)}]}});return(0,oe.createSdkMcpServer)({name:`verification_gates`,version:`1.0.0`,tools:[e,t,n,r,i,a]})}},Gp=l(Ie()),Kp=l(Cr()),qp=l(Le()),Jp,Yp,Xp,Zp;function Qp(e){return(0,h.isEmpty)(e)||!(0,w.existsSync)(e)?``:(0,w.readFileSync)(e,`utf8`)}function $p(e){return(e.duration_ms/1e3).toFixed(1),``}function em(e,t){return e+[``,`---`,`IMPORTANT: A test file has been pre-created at: ${t}`,`Use the Edit tool to add your test cases to this file. Do NOT create a new file with the Write tool.`].join(`
|
|
32081
|
+
`)}function tm(e){return[``,`<environment>`,`Your working directory is: \`${e}\``,`All tools (Bash, Read, Glob, Grep, Edit) operate relative to this directory automatically.`,"- Do NOT use `cd` to change directories before running commands. Commands like `npm run test` already run from the project root.","- Prefer using relative paths (e.g. `src/services/foo.ts`) instead of absolute paths.",`</environment>`].join(`
|
|
32082
|
+
`)}function nm(e){let t=[``,`<project-setup>`,`The following project tooling was verified. Use these commands directly.`,``];e.testCommand.status!==Qf.UNRESOLVED&&t.push(`- **Test command**: \`${e.testCommand.command}\``),e.buildCommand.status!==Qf.UNRESOLVED&&t.push(`- **Build command**: \`${e.buildCommand.command}\``),e.lintCommand.status!==Qf.UNRESOLVED&&t.push(`- **Lint command**: \`${e.lintCommand.command}\``),e.prettierCommand.status!==Qf.UNRESOLVED&&t.push(`- **Prettier command**: \`${e.prettierCommand.command}\``),t.push(`- **Package manager**: ${e.packageManager}`);let n=[];return e.testCommand.status===Qf.UNRESOLVED&&n.push(`testCommand`),e.buildCommand.status===Qf.UNRESOLVED&&n.push(`buildCommand`),e.lintCommand.status===Qf.UNRESOLVED&&n.push(`lintCommand`),e.prettierCommand.status===Qf.UNRESOLVED&&n.push(`prettierCommand`),(0,h.isEmpty)(n)||t.push(``,`The following commands could not be auto-discovered: ${n.join(`, `)}.`,`Search package.json and project config files to find these manually. Do NOT search for commands already listed above.`),t.push(`</project-setup>`),t.join(`
|
|
32083
|
+
`)}function rm(e){let t=[[`testCommand`,e.testCommand],[`buildCommand`,e.buildCommand],[`lintCommand`,e.lintCommand],[`prettierCommand`,e.prettierCommand]],n=[``,`<verification-results>`];for(let[e,r]of t)r.status===$f.FAILED?n.push(`${e}: FAILED`,`Output:\n${r.output.trim()}`,``):r.status===$f.PASSED?n.push(`${e}: PASSED`):n.push(`${e}: SKIPPED (command not configured)`);return n.push(`</verification-results>`),n.join(`
|
|
32084
|
+
`)}let im=[`testCommand`,`buildCommand`,`lintCommand`,`prettierCommand`],am={testCommand:`test`,buildCommand:`build`,lintCommand:`lint`,prettierCommand:`format`};function om(e){return e===$f.PASSED?`✓`:e===$f.FAILED?`✗`:`-`}function sm(e){return im.map(t=>`${am[t]} ${om(e[t].status)}`).join(` `)}function cm(e){return(0,h.isDefined)(e)?` — ${e.greenTestsCount} green, ${e.redTestsCount} red`:``}function lm(e,t){for(let n of im){let r=t[n];r.status===$f.FAILED&&e.debug(` ${am[n]} output: ${r.output}`)}}function um(e,t,n){let r=f.default.relative(t,n),i=e.getTestCommand(),a=e.getLintCommand(),o=e.getPrettierCommand(),s=Bp(t,n);return(0,h.isDefined)(i)&&i!==Te&&(s.testCommand=i.replaceAll(Ce,r),s.missing=s.missing.filter(e=>e!==`testCommand`)),a!==Ee&&(s.lintCommand=a.replaceAll(Ce,r),s.missing=s.missing.filter(e=>e!==`lintCommand`)),o!==De&&(s.prettierCommand=o.replaceAll(Ce,r),s.missing=s.missing.filter(e=>e!==`prettierCommand`)),s}let dm=class{constructor(e,t,n,r,i){this.globalConfigService=e,this.authStorage=t,this.llmModelService=n,this.metricReportService=r,this.verificationService=i}async run(e){let t=new AbortController,n=this.globalConfigService.getProgressLogger((0,h.isDefined)(e.methodName)?{parentName:e.parentName,methodName:e.methodName}:void 0);e.abortSignal&&e.abortSignal.addEventListener(`abort`,()=>t.abort());let{modelName:r,capPrice:i}=await this.llmModelService.getAgentSdkConfig(),a=um(this.globalConfigService,e.workingDirectory,e.testFilePath);H.info.defaultLog(`[precalc] Project setup resolved:\n${JSON.stringify(a,null,2)}`);let o=[[`test`,a.testCommand],[`build`,a.typecheckCommand],[`lint`,a.lintCommand],[`format`,a.prettierCommand]];n.verbose(`Discovered commands:`);for(let[e,t]of o)n.verbose(` ${(0,h.isDefined)(t)?`✓`:`✗`} ${e}: ${t??`not found`}`);let s=H.getRequestId(),c=new ep(this.metricReportService,s,r,e.testFilePath),l=this.globalConfigService.getPerFunctionTimeout(),u=setTimeout(()=>{let e=(l/6e4).toFixed(1);n.info(`Testable reached timeout after ${e} minutes, aborting`),c.logSyntheticTool(`timeout-abort`,{timeoutMs:l},{reason:`timeout`}),c.flush(),t.abort()},l);try{let o=ap(a),s=rp(a.testRunner);await(0,p.mkdir)(f.default.dirname(e.testFilePath),{recursive:!0}),await(0,p.writeFile)(e.testFilePath,s,`utf8`);let l=await this.verificationService.verify({setup:o,testFilePath:e.testFilePath,workingDirectory:e.workingDirectory});H.info.defaultLog(`[verification] Pre-generation: ${JSON.stringify(l,null,2)}`),n.verbose(`Pre-verification:`,sm(l)),lm(n,l);let u=o;if(o=pp(o,l,e.testFilePath),c.addPreVerification(u,l,o),l.testCommand.status===$f.FAILED){let t=l.testCommand.output;throw n.verbose(`Test command failed on dummy test — aborting`),H.default.warn(`[verification] Test command failed on dummy test — aborting.\n${t}`),await c.flush(),await(0,p.unlink)(e.testFilePath),new tp(`test_command_failed`,[`Test command failed: ${t.length>200?t.slice(0,200)+`...(truncated ${t.length-200} chars)`:t}`],0)}H.info.defaultLog(`[verification] Promoted setup: ${JSON.stringify(o,null,2)}`);let d=im.filter(e=>o[e].status!==Qf.UNRESOLVED).map(e=>am[e]),m=im.filter(e=>o[e].status===Qf.UNRESOLVED).map(e=>am[e]);n.verbose(`Verified:`,d.join(`, `)+((0,h.isEmpty)(m)?``:` (${m.join(`, `)} dropped)`));let g=await this.runGenerationQuery({...e,model:r,budget:i,verifiedSetup:o,abortController:t,metricsTracer:c,progressLogger:n}),_=await this.verificationService.verify({setup:o,testFilePath:e.testFilePath,workingDirectory:e.workingDirectory});if(H.info.defaultLog(`[verification] Post-generation: ${JSON.stringify(_,null,2)}`),n.verbose(`Post-verification ${_.passed?`passed`:`failed`}:`,sm(_)+cm(g.validationSummary)),_.passed)return g;H.default.warn(`[verification] Gates failed — running cleanup agent to salvage passing tests`),await this.runCleanupQuery({workingDirectory:e.workingDirectory,testFilePath:e.testFilePath,model:r,budget:i,verifiedSetup:o,abortController:t,postVerification:_});let v=await this.verificationService.verify({setup:o,testFilePath:e.testFilePath,workingDirectory:e.workingDirectory});return H.info.defaultLog(`[verification] Post-cleanup: ${JSON.stringify(v,null,2)}`),n.verbose(`Post-cleanup ${v.passed?`passed`:`failed`}:`,sm(v)),v.passed?{code:Qp(e.testFilePath),costUsd:g.costUsd,validationSummary:g.validationSummary}:(H.default.warn(`[verification] Cleanup failed — deleting test file: ${e.testFilePath}`),await(0,p.unlink)(e.testFilePath),{code:``,costUsd:g.costUsd,validationSummary:g.validationSummary})}finally{clearTimeout(u)}}async handleGenerationResult(e,t,n,r,i){if(await t.flush(),n.logResult(e),H.info.defaultLog(`SDK model usage: `,e.modelUsage),ef(e))throw new tp(e.subtype,e.errors,e.total_cost_usd);let a=Qp(i),o=r?.buildValidationSummary()??n.buildValidationSummary();if(H.info.defaultLog(`Validation summary: `,o),!(0,h.isEmpty)(a)){let t=$p(e)+a;return(0,w.writeFileSync)(i,t,`utf8`),{code:t,costUsd:e.total_cost_usd,validationSummary:o}}return{code:a,costUsd:e.total_cost_usd,validationSummary:o}}async runCleanupQuery(e){let t=ff(e.testFilePath,e.workingDirectory),n=await this.authStorage.getJWTToken()??``,r=Math.max(e.budget*.25,.25),i=[...yd],a=new Zf(!1),o=H.getRequestId(),s=new ep(this.metricReportService,o,e.model,e.testFilePath);a.logStart({model:e.model,budget:r,cwd:e.workingDirectory,testFile:e.testFilePath,tools:i,hooks:{pre:[`file-restriction`,`env-protection`,`dangerous-command`,`bash-exit-code`],post:[]},maxTurns:15});let c=[`You are a test cleanup agent.`,`The generated test file has failed quality checks (lint, typecheck, prettier, or test failures).`,`Your ONLY goal is to salvage passing tests by removing test cases that fail any check.`,`DO NOT generate new tests. DO NOT fix or modify the logic of any existing test.`,`DO NOT add new imports or describe blocks.`,`Run the available checks, identify failing test cases, and remove them from the file.`,`Keep all tests that pass every check. Leave the file with only clean, passing tests.`].join(` `),l=`The test file at ${e.testFilePath} has failed quality verification.\nThe verification results below were already collected — use them directly to identify failing tests.\nRemove only the failing test cases from the file. Do not generate new tests and do not fix any test.\nAfter removing failing tests, re-run all configured checks (all non-skipped commands) to confirm they all pass.`+rm(e.postVerification)+tm(e.workingDirectory)+nm(e.verifiedSetup),u=(0,oe.query)({prompt:l,options:{model:e.model,systemPrompt:c,allowedTools:[...yd],permissionMode:vd,allowDangerouslySkipPermissions:!0,maxBudgetUsd:r,maxTurns:15,cwd:e.workingDirectory,abortController:e.abortController,sessionId:(0,y.randomUUID)(),env:{...process.env,ANTHROPIC_BASE_URL:this.globalConfigService.getAnthropicProxyUrl(),ANTHROPIC_AUTH_TOKEN:n,ANTHROPIC_CUSTOM_HEADERS:[`x-request-id: `+H.getRequestId()].join(`
|
|
32085
|
+
`)},hooks:{PreToolUse:[{matcher:`Write|Edit`,hooks:[t]},{matcher:`Read`,hooks:[df]},{matcher:`Bash`,hooks:[uf,lf]}]}}});for await(let e of u)if(a.logMessage(e),await s.processMessage(e),$d(e)){await s.flush(),a.logResult(e),H.info.defaultLog(`[cleanup] SDK model usage: `,e.modelUsage),ef(e)&&H.default.warn(`[cleanup] Agent finished with error: ${e.subtype}`);break}}async runGenerationQuery(e){let t=ff(e.testFilePath,e.workingDirectory),n=bd?new Wp({setup:e.verifiedSetup,testFilePath:e.testFilePath,workingDirectory:e.workingDirectory,progressLogger:e.progressLogger}):void 0,r=n?Mf(n):void 0,i=new Zf(!1),a=[...yd];i.logStart({model:e.model,budget:e.budget,cwd:e.workingDirectory,testFile:e.testFilePath,tools:a,hooks:{pre:[`file-restriction`,`env-protection`,`dangerous-command`,`bash-exit-code`],post:[`test-prune`],...bd&&{stop:[`verification-gates`]}}});let o=em(e.userPrompt,e.testFilePath)+tm(e.workingDirectory)+nm(e.verifiedSetup),s=await this.authStorage.getJWTToken()??``,{metricsTracer:c}=e,l=(0,oe.query)({prompt:o,options:{model:e.model,systemPrompt:e.systemPrompt,allowedTools:a,permissionMode:vd,allowDangerouslySkipPermissions:!0,maxBudgetUsd:e.budget,cwd:e.workingDirectory,abortController:e.abortController,sessionId:(0,y.randomUUID)(),env:{...process.env,ANTHROPIC_BASE_URL:this.globalConfigService.getAnthropicProxyUrl(),ANTHROPIC_AUTH_TOKEN:s,ANTHROPIC_CUSTOM_HEADERS:[`x-request-id: `+H.getRequestId()].join(`
|
|
32086
|
+
`)},...n&&{mcpServers:{verification_gates:n.getServer()}},hooks:{PreToolUse:[{matcher:`Write|Edit`,hooks:[t]},{matcher:`Read`,hooks:[df]},{matcher:`Bash`,hooks:[uf,lf]}],PostToolUse:[{matcher:`Bash`,hooks:[Af]},{matcher:`${Sd}|${xd}`,hooks:[Af]}],...r&&{Stop:[{hooks:[r]}]}}}});for await(let t of l)if(i.logMessage(t),await c.processMessage(t),$d(t))return this.handleGenerationResult(t,c,i,n,e.testFilePath);return{code:Qp(e.testFilePath)}}};dm=(0,qp.default)([(0,_.injectable)(),(0,Kp.default)(0,(0,_.inject)(He)),(0,Kp.default)(1,(0,_.inject)(Sr)),(0,Kp.default)(2,(0,_.inject)(zf)),(0,Kp.default)(3,(0,_.inject)(Yr)),(0,Kp.default)(4,(0,_.inject)(fp)),(0,Gp.default)(`design:paramtypes`,[Object,typeof(Jp=Sr!==void 0&&Sr)==`function`?Jp:Object,typeof(Yp=zf!==void 0&&zf)==`function`?Yp:Object,typeof(Xp=Yr!==void 0&&Yr)==`function`?Xp:Object,typeof(Zp=fp!==void 0&&fp)==`function`?Zp:Object])],dm);var fm=class{execute(e){let t=!1,n=new Set(e.getKnownDependenciesSnapshot().flatMap(t=>e.getParentParameterRelations(t).filter(e=>e.depthLevelInParent>0).map(e=>e.parameterParentId)));for(let r of e.getKnownDependenciesSnapshot())e.getParentParameterRelations(r).every(e=>n.has(e.parameterParentId))&&(t||=e.moveKnownDependencyToMissing(r.name));let r=e.getDataSource().testedCodeDataSource.codeDependencies.length;return e.getDataSource().testedCodeDataSource.codeDependencies=e.getDataSource().testedCodeDataSource.codeDependencies.filter(t=>!e.getParentParameterRelations(t).every(e=>e.depthLevelInParent>0)),e.getDataSource().testedCodeDataSource.codeDependencies.length!==r&&(t=!0),t}},pm=class{kindsToRemove;constructor(...e){this.kindsToRemove=new Set(e)}execute(e){let t=!1;for(let n of e.getKnownDependenciesSnapshot())this.kindsToRemove.has(n.kind)&&(t||=e.moveKnownDependencyToMissing(n.name));return t}},mm=class{execute(e){let t=e.getDataSource().testedCodeDataSource.testedMethodClass,n=t?.constructorMetadata?.parameters??[],r=t?.properties??[],i=[...n,...r];return e.moveKnownDependencyToMissingByParameters(i)}},hm=class{kinds;constructor(...e){this.kinds=new Set(e)}execute(e){let t=!1,n=e.getMissingDependenciesSnapshot();for(let[r,i]of n.entries())this.kinds.has(i.kind)&&(t||=e.removeCodeInMissingDependencyByIndex(r));return t}},gm=class{execute(e){let t=e.getDataSource().testedCodeDataSource.testedMethod.parameters??[];return e.moveKnownDependencyToMissingByParameters(t)}},_m=class{execute(e){let t=e.getDataSourceSnapshot(),n=this.getParameters(t),r=!1;for(let i=0;i<t.testedCodeDataSource.missingDependencies.length;i++){let a=t.testedCodeDataSource.missingDependencies[i];(0,h.isDefined)(a.dependencyMetadata)&&(this.isMockDependencyKept(a.dependencyMetadata,n)||(r||=e.removeMockDependencyByIndex(i)))}return r}isMockDependencyKept(e,t){if((0,h.isEmpty)(t))return!1;let n=this.getParametersIdsFromMockDependency(e),r=(0,h.intersection)([...t],[...n]);return!(0,h.isEmpty)(r)}getParametersIdsFromMockDependency(e){let t=new h.SafeSet;if(!(0,h.isDefined)(e))return t.toSet();for(let n of e?.methodsMetadata??[]){for(let e of n.parameters)t.safeAdd(e.id);t.safeAdd(n?.returnParam?.id)}for(let n of e?.classMetadata?.properties??[])t.safeAdd(n?.id);for(let n of e?.classMetadata?.constructorMetadata?.parameters??[])t.safeAdd(n?.id);return t.toSet()}getParameters(e){let t=e.testedCodeDataSource.testedMethod.parameters.map(e=>e.id),n=e.testedCodeDataSource.testedMethod.returnParam?.id,r=e.testedCodeDataSource.testedMethodClass?.constructorMetadata?.parameters.map(e=>e.id)??[],i=e.testedCodeDataSource.testedMethodClass?.properties.map(e=>e.id)??[];return new h.SafeSet([...t,n,...r,...i]).toSet()}},vm=class{execute(e){let t=e.getDataSourceSnapshot(),n=t.testedCodeDataSource.testedMethod.parameters.map(e=>e.id),r=t.testedCodeDataSource.testedMethod.returnParam?.id,i=t.testedCodeDataSource.testedMethodClass?.constructorMetadata?.parameters.map(e=>e.id)??[],a=new Set([...n,r,...i].filter(e=>(0,h.isDefined)(e))),o=!1;for(let t of e.getKnownDependenciesSnapshot())this.isDependencyKept(t,a)||(o||=e.moveKnownDependencyToMissing(t.name));return o}isDependencyKept(e,t){return e.kind===`file`||e.kind===`enum`?!0:e.parentParameterRelations.some(e=>e.depthLevelInParent===0&&t.has(e.parameterParentId))}},ym=class{execute(e){let t=e.getDataSource().testedCodeDataSource.testedMethod.returnParam?.id;return(0,h.isDefined)(t)?e.moveKnowDependencyToMissingByParameterId(t):!1}},bm=class{dataSource;getKnownDependenciesSnapshot(){return this.getDataSourceSnapshot().testedCodeDataSource.codeDependencies}getMissingDependenciesSnapshot(){return this.getDataSourceSnapshot().testedCodeDataSource.missingDependencies}constructor(e){this.dataSource=e}getDataSourceSnapshot(){return structuredClone(this.dataSource)}getDataSource(){return this.dataSource}getParentParameterRelations(e){return e.kind===`file`?[]:e.parentParameterRelations}moveKnownDependencyToMissingByParameters(e){let t=e.map(e=>e.id).filter(e=>(0,h.isString)(e)),n=!1;for(let e of t)n||=this.moveKnowDependencyToMissingByParameterId(e);return n}moveKnownDependencyToMissing(e){let t=this.dataSource.testedCodeDataSource.codeDependencies.findIndex(t=>t.name===e);if(t===-1)return!1;let n=this.dataSource.testedCodeDataSource.codeDependencies[t],r=`parentParameterRelations`in n?n.parentParameterRelations:[];if(r.length>1)return!1;let i=r[0]?.parameterParentId;return(0,h.isDefined)(i)?this.moveKnowDependencyToMissingByParameterId(i):this.moveKnowDependencyToMissingByIndex(t)}moveKnowDependencyToMissingByParameterId(e){let t=this.dataSource.testedCodeDataSource.codeDependencies.filter(t=>{let n=this.getParentParameterRelations(t);return n.length===1&&n[0].parameterParentId===e}),n=!1;for(let e of t){this.getParentParameterRelations(e)[0].depthLevelInParent===0&&(this.dataSource.testedCodeDataSource.missingDependencies.push(this.convertCodeDependencyToMissingDependency(e)),n=!0);let t=this.dataSource.testedCodeDataSource.codeDependencies.length;this.dataSource.testedCodeDataSource.codeDependencies=this.dataSource.testedCodeDataSource.codeDependencies.filter(t=>t.name!==e.name),this.dataSource.testedCodeDataSource.codeDependencies.length!==t&&(n=!0)}return n}moveKnowDependencyToMissingByIndex(e){if(e<0||this.dataSource.testedCodeDataSource.codeDependencies.length<=e)return!1;let t=this.dataSource.testedCodeDataSource.codeDependencies[e],n=this.convertCodeDependencyToMissingDependency(t);return this.dataSource.testedCodeDataSource.codeDependencies.splice(e,1),this.dataSource.testedCodeDataSource.missingDependencies.push(n),!0}convertCodeDependencyToMissingDependency(e){let t=(e.kind===`file`?!1:e.containedInTestedFile)??!1;return{name:e.name,kind:e.kind,importPath:e.importPath,code:e.code,isCoreModule:!1,exportType:kt.Unknown,containedInTestedFile:t,isDataObject:e.isDataObject??!1,parentParameterRelations:e.kind===`file`?[]:e.parentParameterRelations,isGenerated:e.isGenerated,baseTypeNames:e.kind===`file`?[]:e.baseTypeNames,ancestorDepthFromTestedClass:e.kind===`file`?void 0:e.ancestorDepthFromTestedClass,importUsageMetadata:e.kind===`file`?void 0:e.importUsageMetadata}}removeMockDependencyByIndex(e){let t=this.dataSource.testedCodeDataSource.missingDependencies?.[e];if(!(0,h.isDefined)(t))return!1;let n=t.dependencyMetadata;return(0,h.isDefined)(n)?(t.dependencyMetadata=void 0,!0):!1}removeCodeInMissingDependencyByIndex(e){let t=this.dataSource.testedCodeDataSource.missingDependencies?.[e];return(0,h.isEmpty)(t?.code)?!1:(t.code=``,!0)}},xm=class{modifierHandlers=[];modifierCount;constructor(){let e=new hm(`react-class-component`,`react-hook`,`react-forward-ref-component`,`react-function-component`,`react-css-in-js`),t=new pm(`class`),n=new vm,r=new mm,i=new gm,a=new ym,o=new fm,s=new _m;this.modifierHandlers.push(e,t,n,r,i,a,o,s),this.modifierCount=this.modifierHandlers.length}refine(e){let t=new bm(e);for(let e of this.modifierHandlers)if(e.execute(t))return!0;return!1}},Sm=class e{testCodeDatasourceRefiner=new xm;sizeLimit=0;constructor(e){this.sizeLimit=e??this.sizeLimit}static async init(t){return new e(await t.getDataSourceOptimizerSizeLimit())}async optimize(e){if(this.sizeLimit===0)return e;try{let t=structuredClone(e);return await this.iterateOptimize(t,1)}catch{return e}}getSizeInKilobytes(e){let t=JSON.stringify(e);return Buffer.byteLength(t)/1024}async iterateOptimize(e,t){if(this.testCodeDatasourceRefiner.modifierCount<t||!this.testCodeDatasourceRefiner.refine(e))return e;let n=await this.iterateOptimize(e,t+1);return this.getSizeInKilobytes(n)<=this.sizeLimit?n:await this.iterateOptimize(e,t+1)}};let Cm=()=>Ue().getRequestSource()===ue.IDE;var wm=l(Ie()),Tm=l(Le()),Em=class{sourceFileCache=new Map;constructor(e,t){this.testable=e,this.filePath=t}async getReferences(e=2){let t=Jt.get(this.filePath),n=this.findTargetNode(t);if(!n)return[];let r=n.findReferences(),i=[];for(let e of r)for(let t of e.getReferences()){if(t.isDefinition()??!1)continue;let e=t.getSourceFile().getFilePath();if(!/\.spec|\.test/g.test(e)){let e=await this.getReferencedTestables(t);i.push(...e)}}return(0,h.uniqWith)(i,(e,t)=>e.node===t.node).slice(0,e).map(e=>e.node.getText())}findTargetNode(e){return e.getDescendantsOfKind(E.SyntaxKind.Identifier).find(e=>e.getText()===this.testable.name)}async getTestables(e){let t=e.getSourceFile(),n=t.getFilePath(),r=this.sourceFileCache.get(n);if((0,h.isDefined)(r))return r;let i=new Mn(await et.fromSourceFile(t).getText()).testables.getAllTestables();return this.sourceFileCache.set(n,i),i}async getReferencedTestables(e){try{let t=e.getNode(),[n,r]=[t.getStart(),t.getEnd()];return(await this.getTestables(e)).filter(({type:e,node:t})=>e===`class`||e===`object-method`?!1:t.containsRange(n,r))}catch(e){return H.error(`Error while getting js usage reference code`,e),[]}}};(0,Tm.default)([Yt,(0,wm.default)(`design:type`,Function),(0,wm.default)(`design:paramtypes`,[Object]),(0,wm.default)(`design:returntype`,Promise)],Em.prototype,`getReferences`,null);var Dm=l(Ie()),Om=l(Cr()),km=l(Le()),Am;let jm=class{constructor(e){this.dependenciesService=e}async getTestedCodeDataSource(e,t,n){await Jt.init(e);let{methodType:r,methodName:i,parentName:a}=ai(t);H.addContext({subCategory:Et.CODE_EXTRACTOR}),H.debug.defaultLog(`Get testable context for ${r} ${i}() in ${e}.`);try{let o=await new et(e).getText(),s=at((0,f.extname)(e)),c=zl(s),l=c.extract({methodName:i,methodType:r,parentName:a,filePath:e}),u=Cm(),d=await this.dependenciesService.getTestCodeDataSourceCore(l,e,u);if(s===`javascript`)return Wa(await this.getJsCodeDataSource(e,t,o,d,l,n));let p,m,g,_,v={name:`NA`,kind:`file`,code:o,importPath:e,dependencyType:`file`,isGenerated:!1},b=[];(0,h.isDefined)(d)?(p=d.codeDependencies,m=d.missingDependencies,g=d.testedMethod,_=d.testedMethodClass,v=d.fileCodeDependency,b=d.libraries):(H.info.defaultLog(`No data source for ${i} - ${r}`),m=[],p=[],g={name:i,isAsync:!1,isStatic:!1,parameters:[],decorators:[],code:o.slice(t.startIndex,t.endIndex),callExpressions:[],imports:[],accessModifierType:At.PUBLIC,extendedProperties:{},signature:``,parameterId:(0,y.randomUUID)(),kind:`any`,exportType:kt.Unknown});let x=await new Em(t,e).getReferences();return m=await this.reevaluateMissingDependencies(m,d,c),Wa({gitUrl:Ue().getGitURL(),filePath:e,relativePathToTestFile:this.getRelativePathToTestFile(e,n),testFramework:Ue().getTestFramework(),language:s,testedMethod:g,testedMethodClass:_,missingDependencies:m,codeDependencies:[v,...p],usages:x,libraries:b})}catch(e){throw H.error(`Error occurred during getTestedCodeDataSource ${i}`,e,i),new sr(ar.TESTED_CODE_DATA_SOURCE_ERROR,{methodName:i})}}async getJsCodeDataSource(e,t,n,r,i,a){let{methodName:o}=ai(t),s={name:o,isAsync:!1,isStatic:!1,parameters:[],decorators:[],code:n.slice(t.startIndex,t.endIndex),callExpressions:[],imports:r?.testedMethod.imports??[],exportType:r?.testedMethod.exportType??kt.Named,accessModifierType:r?.testedMethod.accessModifierType??At.PUBLIC,extendedProperties:r?.testedMethod.extendedProperties,signature:``,parameterId:(0,y.randomUUID)(),kind:`any`},c={name:`NA`,kind:`file`,code:n,importPath:e,dependencyType:`file`,isGenerated:!1},l=await new Em(t,e).getReferences(),u=[];if((0,h.isDefined)(i)){let t=await new sc(i,e).extract(),n=i.testedMethod.nestedReactComponents?.hooks??[],r=i.testedMethod.nestedReactComponents?.jsxElements??[],a=[...n,...r].map(t=>({name:t.name,kind:t.kind,importPath:t.importPath,isCoreModule:t.isCoreModule,code:t.code,containedInTestedFile:Za(e,t),exportType:t.exportType,isDataObject:!1,parentParameterIds:[],parentParameterRelations:[],dependenciesMetadata:[],isGenerated:t.isGenerated,baseTypeNames:[]})),o=t.filter(e=>[`function`,`react-function-component`].includes(e.kind)).map(e=>({name:e.name,kind:e.kind,importPath:e.importPath,isCoreModule:e.isCoreModule,code:e.code,containedInTestedFile:e.containedInTestedFile,exportType:e.exportType,isDataObject:!1,parentParameterIds:[],parentParameterRelations:[],dependenciesMetadata:[],isGenerated:e.isGenerated,baseTypeNames:[]}));u=(0,h.uniqWith)([...o,...a],(e,t)=>e.name===t.name)}return{gitUrl:Ue().getGitURL(),filePath:e,relativePathToTestFile:this.getRelativePathToTestFile(e,a),testFramework:Ue().getTestFramework(),language:`javascript`,testedMethod:s,testedMethodClass:void 0,missingDependencies:u,codeDependencies:[c],usages:l,libraries:r?.libraries??[]}}async getSecondLevelReactMissingDependencies(e,t){if(!(0,h.isDefined)(e))return[];let n=Cm(),r=e.missingDependencies.filter(e=>e.kind===`react-function-component`);return(await Promise.all(r.map(async e=>{let r=e.sourceFile;if(!(0,h.isDefined)(r))return null;let i=et.fromAbsolutePath(r.getFilePath()).getRelativeFilePath(),a=t.extract({methodName:e.name,methodType:`function`,filePath:i});return await this.dependenciesService.getTestCodeDataSourceCore(a,i,n)}))).filter(e=>(0,h.isDefined)(e))}async reevaluateMissingDependencies(e,t,n){if(!(0,h.isDefined)(t))return e;let r=t.testedMethod.parameterId,i=(e,t)=>({...e,parentParameterIds:[r,...e.parentParameterIds],parentParameterRelations:[{parameterParentId:r,depthLevelInParent:t},...e.parentParameterRelations]}),a=t.missingDependencies.map(e=>i(e,1)),o=(await this.getSecondLevelReactMissingDependencies(t,n)).flatMap(e=>e.missingDependencies.map(e=>i(e,2)));return(0,h.uniqWith)([...a,...o],(e,t)=>e.name===t.name&&e.kind===t.kind)}getRelativePathToTestFile(e,t){let n=Jt.get(e);return Jt.get(t).getRelativePathTo(n)}};(0,km.default)([Yt,(0,Dm.default)(`design:type`,Function),(0,Dm.default)(`design:paramtypes`,[String,Object,String]),(0,Dm.default)(`design:returntype`,Promise)],jm.prototype,`getTestedCodeDataSource`,null),jm=(0,km.default)([(0,_.injectable)(),(0,Om.default)(0,(0,_.inject)(Pc)),(0,Dm.default)(`design:paramtypes`,[typeof(Am=Pc!==void 0&&Pc)==`function`?Am:Object])],jm);var Mm=l(Ie()),Nm=l(Cr()),Pm=l(Le()),Fm,Im;let Lm=class{constructor(e,t,n){this.globalConfigService=e,this.featureFlagsService=t,this.testableContextService=n}async gatherDataSource(e){let t=await this.testableContextService.getTestedCodeDataSource(e.path,e.testable,e.testFilePath),n={...(0,h.isDefined)(this.globalConfigService.getGenerateTestsLLMModelName())&&{modelName:this.globalConfigService.getGenerateTestsLLMModelName()},...(0,h.isDefined)(this.globalConfigService.getLLMTemperature())&&{temperature:this.globalConfigService.getLLMTemperature()},...(0,h.isDefined)(this.globalConfigService.getLLMTopP())&&{topP:this.globalConfigService.getLLMTopP()}},r=H.getRequestId();return await this.prepareDTO({dataSource:t,llmConfig:n,userPrompt:(0,h.isDefined)(e.userPrompt)&&!(0,h.isEmpty)(e.userPrompt)?e.userPrompt:this.globalConfigService.getUserPrompt(),generatedTestStructure:this.globalConfigService.getGeneratedTestStructure()},r)}async prepareDTO(e,t){let n=e.dataSource.testedMethod.name;H.debug.defaultLog(`Preparing dto for method ${n}`);try{let t=Yl(e,await this.featureFlagsService.isRemovingDuplicatedCodeInDependencyMetadataEnabled());return(await Sm.init(this.featureFlagsService)).optimize(t)}catch(e){throw H.info.defaultLog(`Failed making preparations for generate test dto`,e,t),new sr(ar.PREPARATIONS_FOR_GENERATING_TEST_DTO_ERROR,{methodName:n,errorMessage:`Failed making preparations for generate test dto`})}}};Lm=(0,Pm.default)([(0,_.injectable)(),(0,Nm.default)(0,(0,_.inject)(He)),(0,Nm.default)(1,(0,_.inject)(kc)),(0,Nm.default)(2,(0,_.inject)(jm)),(0,Mm.default)(`design:paramtypes`,[typeof(Fm=He!==void 0&&He)==`function`?Fm:Object,Object,typeof(Im=jm!==void 0&&jm)==`function`?Im:Object])],Lm);var Rm=l(Ie()),zm=l(Cr()),Bm=l(Le()),Vm,Hm;let Um=class{constructor(e,t,n){this.apiService=e,this.globalConfigService=t,this.agentSdkRunner=n}async generate(e,t,n,r,i,a){let o={...e,testedCodeDataSource:{...e.testedCodeDataSource,metadataCollectionTime:n}};if(this.globalConfigService.getExperimentalAgentSdk()){H.info.defaultLog(`[experimental] Using generate-prompt endpoint`);let e;try{e=await this.generatePrompt(o,t,r)}catch(e){throw this.globalConfigService.getProgressLogger(a).verbose(`Failed to analyze function — skipping`),e}return this.generateTestViaClaudeAgentSdk(e,i,r,a)}return this.generateViaBackend(o,t,r)}async generateViaBackend(e,t,n){return this.apiService.post(`/api/v1/tests/generate-tests`,e,{headers:{[lr]:t},signal:n})}async generatePrompt(e,t,n){return await this.apiService.post(`/api/v1/tests/generate-prompt`,e,{headers:{[lr]:t},signal:n})}async generateTestViaClaudeAgentSdk(e,t,n,r){if(!(0,h.isDefined)(t)||(0,h.isEmpty)(t))throw Error(`[agent-sdk] testFilePath is required for experimental SDK flow`);H.info.defaultLog(`[agent-sdk] Running Claude Agent SDK locally...`);let i=this.globalConfigService.getRootPath(),a=(bd?`You are an expert unit test generation agent. Your goal is to produce 7-12 high-quality, passing, type-safe, lint-clean unit tests for a given function or method.
|
|
32087
32087
|
|
|
32088
32088
|
<use_parallel_tool_calls>
|
|
32089
32089
|
If you intend to call multiple tools and there are no dependencies between the calls, make all independent calls in parallel. For example, if you need to look up 3 type definitions, run 3 Grep calls simultaneously. Maximize parallel tool use to increase speed and reduce cost. However, if a call depends on a previous result (e.g. you need a file path before you can Read it), call them sequentially. Never use placeholders or guess missing parameters.
|
|
@@ -32356,7 +32356,7 @@ Available tools (ordered by token cost — prefer the cheapest tool that gets th
|
|
|
32356
32356
|
- \`Write\`: Create new files.
|
|
32357
32357
|
</tools>
|
|
32358
32358
|
|
|
32359
|
-
Start the workflow now with Phase 0 (read the provided project commands), then proceed with the given target file/function.`)||e.systemPrompt,o=await this.agentSdkRunner.run({userPrompt:e.prompt,workingDirectory:i,testFilePath:t,systemPrompt:a,abortSignal:n,parentName:r?.parentName,methodName:r?.methodName});return{code:o.code,prompt:e.prompt,requestId:e.requestId,validationSummary:o.validationSummary}}};Hm=(0,zm.default)([(0,_.injectable)(),(0,Rm.default)(0,(0,_.inject)(kr)),(0,Rm.default)(1,(0,_.inject)(He)),(0,Rm.default)(2,(0,_.inject)(um)),(0,Lm.default)(`design:paramtypes`,[typeof(Bm=kr!==void 0&&kr)==`function`?Bm:Object,Object,typeof(Vm=um!==void 0&&um)==`function`?Vm:Object])],Hm);var Um=l(Ie()),Wm=l(Cr()),Gm=l(Le()),Km,qm,Jm,Ym,Xm,Zm;let Qm=class{constructor(e,t,n,r,i,a,o){this.metricReportService=e,this.importSolverService=t,this.gatherDataSourceService=n,this.globalConfigService=r,this.lintRulesService=i,this.lintValidationService=a,this.testGeneratorProvider=o}async initGenerateTestFlow({filePath:e,testable:t,outputType:n,abortSignal:r,userPrompt:i}){let a=`Test generation was aborted`;return new Promise(async(o,s)=>{let{methodName:c,methodType:l,parentName:u}=ai(t);H.addContext({testedFunction:c,testedMethodClass:u});try{if((r?.aborted??!1)||((0,h.isDefined)(r)&&r.addEventListener(`abort`,()=>{s(a)}),r?.aborted??!1))return s(a);await Jt.init(e);let u=ut(e),d=await this.getEarlyTestFile(e,c,u,n),p=d.getFilePath(),m=null;Jt.add(p);let g=performance.now(),_=H.getRequestId();H.info.defaultLog(`Generating tests for method ${c}`);let v=this.metricReportService.registerStartTime(_);if(r?.aborted??!1)return s(a);let y=await this.gatherDataSourceService.gatherDataSource({path:e,testFilePath:p,outputType:n,testable:t,userPrompt:i}),b=performance.now()-g;H.debug.defaultLog(`with ${y.llmConfig.modelName??`default`} model, ${y.llmConfig.temperature??`default`} temperature, ${y.llmConfig.topP??`default`} top-p`);let x=this.globalConfigService.getExperimentalAgentSdk(),S;if(x)try{if(S=f.default.resolve(this.globalConfigService.getRootPath(),p),H.info.defaultLog(`[experimental] Pre-created test scaffold at ${S}`),H.info.defaultLog(`Calling BE for method ${c}`),r?.aborted??!1)return s(a);let{code:t,validationSummary:n}=await this.generateTest(y,_,b,r,S);if(r?.aborted??!1)return s(a);if((0,h.isEmpty)(t))throw new sr(ar.EMPTY_TEST,{methodName:c});H.info.defaultLog(`[experimental] Skipping code refinement for method "${c}"`);let i=await v({responseProcessingTime:performance.now()-g,gitUrl:this.globalConfigService.getGitURL()});return this.metricReportService.logPackageDependencies(e),H.info.endLog(`Generate Tests done: ${l} ${c} in ${e}. Duration: ${i}ms.`),o({shouldRefreshCoverage:this.globalConfigService.getShouldRefreshCoverage(),testFilePath:p,requestId:_,lintErrors:null,validationSummary:n})}catch(e){let t;if(e instanceof ep){let n=e.errors.length>0?`: `+e.errors.join(`, `):``;t=e.subtype+n+` ($`+e.costUsd.toFixed(4)+`)`}else t=String(e);H.error(`[experimental] SDK runner failed for method "${c}": ${t}`,void 0);try{await d.delete()}catch(e){H.info.defaultLog(`Failed to delete scaffold file for method "${c}"`,e)}return await v({responseProcessingTime:0,gitUrl:this.globalConfigService.getGitURL(),errorCause:t}),o({shouldRefreshCoverage:!1,testFilePath:``,requestId:_,lintErrors:null,validationSummary:{greenTestsCount:0,greyTestsCount:0,redTestsCount:0,naTestsCount:0,errorSuitsCount:0,lintErrorsCount:0,whiteTestsCount:0}})}if(H.info.defaultLog(`Calling BE for method ${c}`),r?.aborted??!1)return s(a);let{code:C,prompt:w,validationSummary:T}=await this.generateTest(y,_,b,r,S);if(r?.aborted??!1)return s(a);if((0,h.isEmpty)(C))throw new sr(ar.EMPTY_TEST,{methodName:c});let E=performance.now();if(r?.aborted??!1)return s(a);Jt.add(p,C),await new _a(this.importSolverService,e,p,t,u).refine({shouldResolveMockPaths:!0,shouldSolveImports:!0});let D=Jt.get(p).getFullText();if((0,h.isEmpty)(D))throw await v({responseProcessingTime:performance.now()-E,gitUrl:this.globalConfigService.getGitURL()}),new sr(ar.EMPTY_TEST,{methodName:c});if(r?.aborted??!1)return s(a);try{if(await d.replace(D),H.debug.defaultLog(`Done upserting test file for method "${c}"`),r?.aborted??!1)return s(a);await d.addPrompt(w),H.debug.defaultLog(`Added prompt for method "${c}"`),m=await this.lintValidationService.fixLintErrors(p),H.debug.defaultLog(`Ran lint command for method "${c}"`),await this.lintValidationService.addComplexitySuppressions(p)&&(H.info.defaultLog(`Complexity suppression comment added, refreshing file`),await Jt.refreshFromFileSystem(p));try{await this.lintRulesService.disableRules(p)}catch(e){H.info.defaultLog(`Failed disabling lint rules`,e)}try{if(r?.aborted??!1)return s(a);await d.runFormatCommand()}catch(e){H.info.defaultLog(`Failed formatting test file`,e)}H.debug.defaultLog(`Ran format command for method "${c}"`);let t=performance.now()-E;if(r?.aborted??!1)return s(a);let n=await v({responseProcessingTime:t,gitUrl:this.globalConfigService.getGitURL()});this.metricReportService.logPackageDependencies(e),await Jt.refreshFromFileSystem(p),H.info.endLog(`Generate Tests done: ${l} ${c} in ${e}. Duration: ${n}ms.`)}catch(e){if(r?.aborted??!1)return s(a);throw await v({responseProcessingTime:performance.now()-E,gitUrl:this.globalConfigService.getGitURL()}),e}return o({shouldRefreshCoverage:this.globalConfigService.getShouldRefreshCoverage(),testFilePath:p,requestId:_,lintErrors:m,validationSummary:T})}catch(e){return r?.aborted??!1?s(a):(H.info.defaultLog(`Unexpected Error generating tests`,e,[c,u]),s(e))}})}async generateTest(e,t,n,r,i){let a=e.testedCodeDataSource.testedMethod.name,o;try{o=await this.apiCall(e,t,n,r,i)}catch(e){if(H.info.defaultLog(`Failed making generateTest API Call`,e instanceof Error?e.message:e,t),e instanceof sr||e instanceof ep)throw e;let n=e instanceof Error?e.message:`Failed making API call`;throw new sr(ar.GENERATING_TESTS_REQUEST_ERROR,{methodName:a,errorMessage:n})}let{code:s,prompt:c}=o;return this.globalConfigService.getExperimentalAgentSdk()||H.debug.defaultLog(`Generating tests for method "${a}" - prompt: "${c}", LLM response: "${s}"`),o}async apiCall(e,t,n,r,i){let a=e.testedCodeDataSource.testedMethod.name,o=e.testedCodeDataSource.testedMethodClass?.name;try{return await this.testGeneratorProvider.generate(e,t,n,r,i,{parentName:o,methodName:a})}catch(e){if(H.info.defaultLog(`GenerateTestService failed to generate tests`,e instanceof Error?e.message:e),e instanceof sr||e instanceof ep)throw e;let t=e instanceof Error?e.message:`Failed making API call`;throw new sr(ar.GENERATING_TESTS_REQUEST_ERROR,{methodName:a,errorMessage:t})}}async getEarlyTestFile(e,t,n,r){if(r===ge.OVERRIDE_CODE_FILE){let n=await zi.getLatestTestFile(e,t);if((0,h.isDefined)(n))return new zi(ct(n))}return await zi.getNextTestFile(e,t,n)}};(0,Gm.default)([Yt,(0,Um.default)(`design:type`,Function),(0,Um.default)(`design:paramtypes`,[Object]),(0,Um.default)(`design:returntype`,Promise)],Qm.prototype,`initGenerateTestFlow`,null),Qm=(0,Gm.default)([(0,_.injectable)(),(0,Wm.default)(0,(0,_.inject)(Yr)),(0,Wm.default)(1,(0,_.inject)(Ia)),(0,Wm.default)(2,(0,_.inject)(Im)),(0,Wm.default)(3,(0,_.inject)(He)),(0,Wm.default)(4,(0,_.inject)(_i)),(0,Wm.default)(5,(0,_.inject)(vu)),(0,Wm.default)(6,(0,_.inject)(Hm)),(0,Um.default)(`design:paramtypes`,[typeof(Km=Yr!==void 0&&Yr)==`function`?Km:Object,typeof(qm=Ia!==void 0&&Ia)==`function`?qm:Object,typeof(Jm=Im!==void 0&&Im)==`function`?Jm:Object,Object,typeof(Ym=_i!==void 0&&_i)==`function`?Ym:Object,typeof(Xm=vu!==void 0&&vu)==`function`?Xm:Object,typeof(Zm=Hm!==void 0&&Hm)==`function`?Zm:Object])],Qm);var $m=l(Ie()),eh=l(Cr()),th=l(Le()),nh,rh,ih,ah,oh,sh;let ch=class{shouldTriggerRefreshCoverage=!1;queue;coverageService=new er;validationReports=new Map;testResults=new Map;constructor(e,t,n,r,i,a){this.generateTestService=e,this.dynamicPromptService=t,this.globalConfigService=n,this.testManagementService=r,this.metricReportService=i,this.lintValidationService=a,this.queue=new Xr({concurrency:this.globalConfigService.getConcurrency(),getItemKey:this.getQueueItemKey})}getQueueItemKey({filePath:e,methodType:t,methodName:n,parentName:r=``}){return`${e}:${t}:${r}:${n}`}decodeQueueItemKey(e){let[t,n,r,i]=e.split(`:`);return{filePath:t,methodType:n,parentName:r,methodName:i}}async clearTemporaryFiles(){let e=`**/.${ni}*`,t=await(0,A.default)(e);for(let e of t)try{await(0,p.unlink)(e)}catch(e){H.info.defaultLog(`Failed removing temp file:`,e)}}async getFinalValidationReport(e,t){return await this.testManagementService.getValidationReport(e,t)}buildEmptyTestCounters(){return{greenTestsCount:0,greyTestsCount:0,redTestsCount:0,naTestsCount:0,errorSuitsCount:0,lintErrorsCount:0,whiteTestsCount:0}}buildFinalTestCounters(e){return{greenTestsCount:e.greenTestsCount,greyTestsCount:e.greyTestsCount,redTestsCount:e.redTestsCount,naTestsCount:e.naTestsCount,errorSuitsCount:e.errorSuitsCount,lintErrorsCount:e.lintErrorsCount,whiteTestsCount:e.whiteTestsCount}}async handleSdkResult(e,t){let n=t.validationSummary??null;this.testResults.set(e,{testFilePath:t.testFilePath,requestId:t.requestId}),this.validationReports.set(e,n);let r=n?{greenTestsCount:n.greenTestsCount,greyTestsCount:n.greyTestsCount,redTestsCount:n.redTestsCount,naTestsCount:n.naTestsCount,errorSuitsCount:n.errorSuitsCount,lintErrorsCount:n.lintErrorsCount,whiteTestsCount:n.whiteTestsCount}:this.buildEmptyTestCounters();await this.metricReportService.saveTestMetrics({requestId:t.requestId,finalGreenTestsCount:r.greenTestsCount,finalTestCounters:r,gitUrl:this.globalConfigService.getGitURL()})}sanitizePath(e){return e.startsWith(`/`)?e.slice(1):e}async addGenerationToQueue({filePath:e,testable:t,outputType:n,userPrompt:r,progress:i}){let a=this.sanitizePath(e),{methodType:o,methodName:s,parentName:c}=ai(t),l={filePath:a,methodType:o,methodName:s,parentName:c};if(H.addContext({testedFunction:s,testedMethodClass:c}),this.queue.has(l)){H.info.defaultLog(`Test generation for "${t.name}" is already in progress`);return}H.info.defaultLog(`Generate Tests: ${t.name} in ${a}`),await this.queue.add(l,async e=>{await H.withBufferedPrinting(async()=>{H.default.info(``),H.default.info((0,h.isDefined)(i)?`Generating tests for ${t.name} - ${i.index} out of ${i.total} functions`:`Generating tests for ${t.name} in ${a}`),await Xt(async()=>{H.default.info(`Generating initial tests`);let i=await this.initGenerateTest({filePath:a,testable:t,outputType:n??this.globalConfigService.getOutputType(),abortSignal:e,userPrompt:r});if((0,h.isDefined)(i?.testFilePath)){let e=this.getQueueItemKey(l);if(this.globalConfigService.getExperimentalAgentSdk()){await this.handleSdkResult(e,i);return}let n=await this.testManagementService.getValidationReport(i.testFilePath,s);await this.metricReportService.saveTestMetrics({requestId:i.requestId,validationReport:n,gitUrl:this.globalConfigService.getGitURL()}),await this.dynamicPromptService.initDynamicPromptRecursively(t,i.testFilePath,i.requestId),H.default.info(``);let r=await this.getFinalValidationReport(i.testFilePath,s);if(H.default.info(`Test fixing complete`),H.default.info(`✅ ${r.greenTestsCount} tests passing`),H.default.info(`⚠️ ${r.redTestsCount} tests still failing (will be skipped)`),H.default.info(`❌ ${r.greyTestsCount} tests could not be fixed autonomously`),H.default.info(``),this.validationReports.set(e,r),this.testResults.set(e,{testFilePath:i.testFilePath,requestId:i.requestId}),this.testManagementService.needsRemoval(r)){await this.testManagementService.removeFailedTestFile(i.testFilePath),await this.metricReportService.saveTestMetrics({requestId:i.requestId,finalGreenTestsCount:0,finalTestCounters:this.buildEmptyTestCounters(),gitUrl:this.globalConfigService.getGitURL()});return}this.testManagementService.needsCleanup(r)?await this.testManagementService.cleanup(i.testFilePath,s):H.info.defaultLog(`No cleanup needed for method "${s}" in ${a}.\nGreen: ${r.greenTestsCount}, Grey: ${r.greyTestsCount}, Red: ${r.redTestsCount}, NA: ${r.naTestsCount}, Error Suits: ${r.errorSuitsCount}`),await this.testManagementService.removeTestComments(i.testFilePath),await this.testManagementService.cleanupPrettier(i.testFilePath),H.default.info(`▶️ Fixing lint and prettier issues`);let o=await this.getFinalValidationReport(i.testFilePath,s);if(H.default.info(`✔️ Tests finalized`),o.greenTestsCount>0?H.default.info(`🟢 Test generation complete`):o.greenTestsCount===0&&H.default.info(`🔴 Tests were generated but could not be validated successfully here`),H.default.info(``),H.default.info(`Summary:`),H.default.info(``),H.default.info(`✅ ${r.greenTestsCount} tests passing`),H.default.info(`⚠️ ${r.redTestsCount} tests skipped`),H.default.info(`❌ ${r.greyTestsCount} tests could not be fixed autonomously`),H.default.info(``),H.default.info(`----------------`),this.testManagementService.needsRemoval(o)){await this.testManagementService.removeFailedTestFile(i.testFilePath),await this.metricReportService.saveTestMetrics({requestId:i.requestId,finalGreenTestsCount:0,finalTestCounters:this.buildEmptyTestCounters(),gitUrl:this.globalConfigService.getGitURL()});return}await this.metricReportService.saveTestMetrics({requestId:i.requestId,finalGreenTestsCount:o.greenTestsCount,finalTestResult:o.testResult,finalTestCounters:this.buildFinalTestCounters(o),gitUrl:this.globalConfigService.getGitURL()})}else{let e=this.getQueueItemKey(l);this.validationReports.set(e,null)}})},i?.index??0)})}async bulkGenerateTests(e,t,n,r){let[{filePath:i}]=e;await Jt.init(i),(0,h.isDefined)(t)&&this.queue.onDone(n=>{let r=e.find(({filePath:e,testable:t})=>{let{methodName:r,methodType:i,parentName:a=``}=ai(t);return this.getQueueItemKey({filePath:e,methodType:i,methodName:r,parentName:a})===n});if((0,h.isDefined)(r))try{t(r,this.validationReports.get(n)??null,this.testResults.get(n)??null)}catch(e){H.error(`Callback execution failed for testable ${n}`,e)}finally{this.validationReports.delete(n),this.testResults.delete(n)}}),H.resetPrintOrder();for(let[t,{filePath:i,testable:a}]of e.entries())this.addGenerationToQueue({filePath:i,testable:a,userPrompt:n,progress:{index:t+1,total:e.length}}).catch(e=>{e instanceof sr&&(H.default.info(``),H.default.warn(`‼️ ${e.message}`),this.queue.clearQueued(),r?.(e))});await this.queue.getIdlePromise(),Jt.clear()}async initGenerateTest({filePath:e,testable:t,outputType:n,abortSignal:r,userPrompt:i}){let{methodName:a,parentName:o}=ai(t);try{if(r?.aborted)return;let s=Math.round(process.memoryUsage().heapUsed/1024/1024);ir.safeTrackEvent(`GenerateTestsInitiated`,{methodName:a,parentName:o,heapMemoryUsedMB:s});let{shouldRefreshCoverage:c,testFilePath:l,requestId:u,lintErrors:d,validationSummary:f}=await this.generateTestService.initGenerateTestFlow({filePath:e,testable:t,outputType:n,abortSignal:r,userPrompt:i});return r?.aborted?void 0:(c&&(this.shouldTriggerRefreshCoverage=!0),{shouldRefreshCoverage:c,testFilePath:l,requestId:u,lintErrors:d,validationSummary:f})}catch(e){if(!r.aborted){H.error(`Test generation failed.`,e);let t=new Map([[or[ar.NOT_ENOUGH_BALANCE_ERROR],ar.NOT_ENOUGH_BALANCE_ERROR]]);if(e instanceof sr&&t.has(e.message)){let n=t.get(e.message);throw ir.safeTrackEvent(`GenerateTestsError`,{errorCode:n}),e}}}}};(0,th.default)([Yt,(0,$m.default)(`design:type`,Function),(0,$m.default)(`design:paramtypes`,[Array,Object,String,typeof(sh=h.Fn!==void 0&&h.Fn)==`function`?sh:Object]),(0,$m.default)(`design:returntype`,Promise)],ch.prototype,`bulkGenerateTests`,null),(0,th.default)([$e({category:Tt.GENERATE_TESTS}),(0,$m.default)(`design:type`,Function),(0,$m.default)(`design:paramtypes`,[Object]),(0,$m.default)(`design:returntype`,Promise)],ch.prototype,`initGenerateTest`,null),ch=(0,th.default)([(0,_.injectable)(),(0,eh.default)(0,(0,_.inject)(Qm)),(0,eh.default)(1,(0,_.inject)(_d)),(0,eh.default)(2,(0,_.inject)(He)),(0,eh.default)(3,(0,_.inject)(sd)),(0,eh.default)(4,(0,_.inject)(Yr)),(0,eh.default)(5,(0,_.inject)(vu)),(0,$m.default)(`design:paramtypes`,[typeof(nh=Qm!==void 0&&Qm)==`function`?nh:Object,typeof(rh=_d!==void 0&&_d)==`function`?rh:Object,Object,typeof(ih=sd!==void 0&&sd)==`function`?ih:Object,typeof(ah=Yr!==void 0&&Yr)==`function`?ah:Object,typeof(oh=vu!==void 0&&vu)==`function`?oh:Object])],ch);var lh=l(Ie()),uh=l(Cr()),dh=l(Le()),fh;let ph=class{constructor(e){this.globalConfigService=e}async getFileTestables(e){try{let t=new et(e);return await t.isFileExists()?[e,new Mn(await t.getText()).testables.getAllTestables().filter(e=>e.canCreateTests&&e.type!==`class`)]:[e,[]]}catch(t){return H.info.defaultLog(`Failed reading file ${e}: check early.config.json`,t,{category:`Early config file`,subCategory:`Reading configuration`}),[e,[]]}}async getTestablesByPattern(e){try{let t=await Bn(e);return await Promise.all(t.map(e=>this.getFileTestables(e)))}catch(t){return H.info.defaultLog(`Failed reading file pattern ${e}: check early.config.json`,t),[]}}async getAllMethodsCount(e){try{let t=new et(e);return await t.isFileExists()?new Mn(await t.getText()).testables.getAllMethodsCount():0}catch(t){return H.info.failedLog(`Failed to get all methods count for ${e}`,t),0}}async resolveEarlyTestFile(e){let{absoluteFilePath:t,testableName:n}=e,r=this.globalConfigService.getRootPath(),i=ct(t),a=zi.fromTestablePath(i,n,r),o=await a.isFileExists(),s=f.default.resolve(r,a.getFilePath());return{...e,testFilePath:s,isExists:o}}async getTestableFileMap(e){if((0,h.isEmpty)(e))return{};let t=this.globalConfigService.getRootPath(),n=[...new Set(e.map(e=>this.toAbsolutePath(e,t)))],r={};for(let e of n){let[n,i]=await this.getFileTestables(e),a=this.toAbsolutePath(n,t);r[a]=await this.buildFilesTreeTestableEntries(i,a)}return r}toAbsolutePath(e,t){return f.default.isAbsolute(e)?e:f.default.resolve(t,e)}async buildFilesTreeTestableEntries(e,t){let n=[];for(let r of e){if(!(0,h.isDefined)(r.name)||r.type===`class`)continue;let e=await this.resolveEarlyTestFile({absoluteFilePath:t,testableName:r.name});n.push({testable:r,...e.isExists&&{testPath:e.testFilePath},testableFilePath:t})}return n}};ph=(0,dh.default)([(0,_.injectable)(),(0,uh.default)(0,(0,_.inject)(He)),(0,lh.default)(`design:paramtypes`,[typeof(fh=He!==void 0&&He)==`function`?fh:Object])],ph);var mh=l(Ie()),hh=l(Cr()),gh=l(Le()),_h;let vh=class{constructor(e){this.testablesService=e}async resolveEarlyTestFile(e){try{return await this.testablesService.resolveEarlyTestFile(e)}catch(t){return H.info.failedLog(`Failed to get test file exists`,t),{...e,testFilePath:``,isExists:!1}}}async getTestables(e){try{return await this.testablesService.getTestablesByPattern(e)}catch(e){return H.info.failedLog(`Failed to get testables`,e),[]}}async getAllMethodsCount(e){try{return await this.testablesService.getAllMethodsCount(e)}catch(e){return H.info.failedLog(`Failed to get all methods count`,e),0}}async getTestableFileMap(e){try{return await this.testablesService.getTestableFileMap(e)}catch(e){return H.error(`Failed to get files tree`,e),{}}}};vh=(0,gh.default)([(0,_.injectable)(),(0,hh.default)(0,(0,_.inject)(ph)),(0,mh.default)(`design:paramtypes`,[typeof(_h=ph!==void 0&&ph)==`function`?_h:Object])],vh);var yh=l(Ie()),bh=l(Cr()),xh=l(Le()),Sh,Ch,wh,Th,Eh,Dh,Oh,kh,Ah,jh;let Mh=class{constructor(e,t,n,r,i,a,o,s,c){this.testablesController=e,this.coverageController=t,this.generateTestController=n,this.authService=r,this.globalConfigService=i,this.testResultCounterService=a,this.testableContextService=o,this.dynamicPromptService=s,this.testValidatorService=c}async init(e){await this.authService.authorize(e)}async getTestables(e){return this.testablesController.getTestables(e)}async getAllMethodsCount(e){return this.testablesController.getAllMethodsCount(e)}async resolveEarlyTestFile(e){return this.testablesController.resolveEarlyTestFile(e)}async getTestableFileMap(e){return this.testablesController.getTestableFileMap(e)}async generateCoverage(){return this.coverageController.generateCoverage()}async setCoverage(e){return this.coverageController.setCoverage(e)}async getCoverageTree(){return this.coverageController.getCoverageTree()}async getCoverageForFiles(e){return this.coverageController.getCoverageForFiles(e)}async generateTests(e,t){return this.generateTestController.addGenerationToQueue({filePath:e,testable:t})}async bulkGenerateTests(e,t,n,r){return this.generateTestController.bulkGenerateTests(e,t,n,r)}updateContext(e){this.globalConfigService.updateContext(e)}updateRootPath(e){this.globalConfigService.updateRootPath(e)}async getValidationReport(e,t){return this.testResultCounterService.getValidationReport(e,t)}async getTestedCodeDataSource(e,t,n){return this.testableContextService.getTestedCodeDataSource(e,t,n)}async runDynamicPrompt(e,t,n){return(await this.dynamicPromptService.initDynamicPrompt(e,t,0,n))?.validationReport??null}async validateTestsByCode(e,t){return this.testValidatorService.validateTestsByCode(e,t)}};(0,xh.default)([$e({category:Tt.INITIALIZATION}),(0,yh.default)(`design:type`,Function),(0,yh.default)(`design:paramtypes`,[String]),(0,yh.default)(`design:returntype`,Promise)],Mh.prototype,`init`,null),(0,xh.default)([$e({category:Tt.GET_TESTABLES}),(0,yh.default)(`design:type`,Function),(0,yh.default)(`design:paramtypes`,[String]),(0,yh.default)(`design:returntype`,Promise)],Mh.prototype,`getTestables`,null),(0,xh.default)([$e({category:Tt.GET_TESTABLES}),(0,yh.default)(`design:type`,Function),(0,yh.default)(`design:paramtypes`,[String]),(0,yh.default)(`design:returntype`,Promise)],Mh.prototype,`getAllMethodsCount`,null),(0,xh.default)([$e({category:Tt.GET_TESTABLES}),(0,yh.default)(`design:type`,Function),(0,yh.default)(`design:paramtypes`,[Object]),(0,yh.default)(`design:returntype`,Promise)],Mh.prototype,`resolveEarlyTestFile`,null),(0,xh.default)([$e({category:Tt.GET_TESTABLES}),(0,yh.default)(`design:type`,Function),(0,yh.default)(`design:paramtypes`,[Array]),(0,yh.default)(`design:returntype`,Promise)],Mh.prototype,`getTestableFileMap`,null),(0,xh.default)([$e({category:Tt.GENERATE_COVERAGE}),(0,yh.default)(`design:type`,Function),(0,yh.default)(`design:paramtypes`,[]),(0,yh.default)(`design:returntype`,Promise)],Mh.prototype,`generateCoverage`,null),(0,xh.default)([$e({category:Tt.SET_COVERAGE}),(0,yh.default)(`design:type`,Function),(0,yh.default)(`design:paramtypes`,[Object]),(0,yh.default)(`design:returntype`,Promise)],Mh.prototype,`setCoverage`,null),(0,xh.default)([$e({category:Tt.GET_COVERAGE}),(0,yh.default)(`design:type`,Function),(0,yh.default)(`design:paramtypes`,[]),(0,yh.default)(`design:returntype`,Promise)],Mh.prototype,`getCoverageTree`,null),(0,xh.default)([$e({category:Tt.GET_COVERAGE}),(0,yh.default)(`design:type`,Function),(0,yh.default)(`design:paramtypes`,[Array]),(0,yh.default)(`design:returntype`,Promise)],Mh.prototype,`getCoverageForFiles`,null),(0,xh.default)([$e({category:Tt.GENERATE_TESTS}),(0,yh.default)(`design:type`,Function),(0,yh.default)(`design:paramtypes`,[String,Object]),(0,yh.default)(`design:returntype`,Promise)],Mh.prototype,`generateTests`,null),(0,xh.default)([$e({category:Tt.GENERATE_TESTS}),(0,yh.default)(`design:type`,Function),(0,yh.default)(`design:paramtypes`,[Array,Object,String,typeof(jh=h.Fn!==void 0&&h.Fn)==`function`?jh:Object]),(0,yh.default)(`design:returntype`,Promise)],Mh.prototype,`bulkGenerateTests`,null),(0,xh.default)([$e({category:Tt.GENERATE_TESTS}),(0,yh.default)(`design:type`,Function),(0,yh.default)(`design:paramtypes`,[String,String]),(0,yh.default)(`design:returntype`,Promise)],Mh.prototype,`getValidationReport`,null),(0,xh.default)([$e({category:Tt.GET_TESTED_CODE_DATA_SOURCE}),(0,yh.default)(`design:type`,Function),(0,yh.default)(`design:paramtypes`,[String,Object,String]),(0,yh.default)(`design:returntype`,Promise)],Mh.prototype,`getTestedCodeDataSource`,null),(0,xh.default)([$e({category:Tt.DYNAMIC_PROMPT}),(0,yh.default)(`design:type`,Function),(0,yh.default)(`design:paramtypes`,[String,Object,String]),(0,yh.default)(`design:returntype`,Promise)],Mh.prototype,`runDynamicPrompt`,null),(0,xh.default)([$e({category:Tt.TEST_VALIDATION}),(0,yh.default)(`design:type`,Function),(0,yh.default)(`design:paramtypes`,[String,String]),(0,yh.default)(`design:returntype`,Promise)],Mh.prototype,`validateTestsByCode`,null),Mh=(0,xh.default)([(0,_.injectable)(),(0,bh.default)(0,(0,_.inject)(vh)),(0,bh.default)(1,(0,_.inject)(rr)),(0,bh.default)(2,(0,_.inject)(ch)),(0,bh.default)(3,(0,_.inject)(gc)),(0,bh.default)(4,(0,_.inject)(He)),(0,bh.default)(5,(0,_.inject)(ed)),(0,bh.default)(6,(0,_.inject)(Am)),(0,bh.default)(7,(0,_.inject)(_d)),(0,bh.default)(8,(0,_.inject)(Lu)),(0,yh.default)(`design:paramtypes`,[typeof(Sh=vh!==void 0&&vh)==`function`?Sh:Object,typeof(Ch=rr!==void 0&&rr)==`function`?Ch:Object,typeof(wh=ch!==void 0&&ch)==`function`?wh:Object,typeof(Th=gc!==void 0&&gc)==`function`?Th:Object,typeof(Eh=He!==void 0&&He)==`function`?Eh:Object,typeof(Dh=ed!==void 0&&ed)==`function`?Dh:Object,typeof(Oh=Am!==void 0&&Am)==`function`?Oh:Object,typeof(kh=_d!==void 0&&_d)==`function`?kh:Object,typeof(Ah=Lu!==void 0&&Lu)==`function`?Ah:Object])],Mh),e.AST=Mn,e.AccessModifierType=At,e.AstModuleInfo=An,e.CONCURRENCY=ye,e.COVERAGE_THRESHOLD=ve,e.CalculateCoverageOption=_e,e.DEFAULT_TYPE_KIND=Mt,e.ExportType=kt,e.GenerateTestsOutputType=ge,e.GeneratedTestStructure=he,e.LibraryName=jt,e.RequestSource=ue,Object.defineProperty(e,`TSAgent`,{enumerable:!0,get:function(){return Mh}}),e.TestFileName=me,e.TestFramework=fe,e.TestStructureVariant=de,e.TestSuffix=pe,e.WithTsMorphManager=Yt,e.createTSAgent=(e={})=>(V.bind(He).toDynamicValue(()=>new He(e)).inSingletonScope(),V.get(Mh)),e.findLintConfigPath=wt,e.getUnitTests=un,e.tsMorphManager=Jt}))();const lW={TSAgent:Symbol.for(`TSAgent`),CliOptions:Symbol.for(`CliOptions`),SCMHostService:Symbol.for(`SCMHostService`)};var uW=u(ki());let dW=function(e){return e.PR=`generate-for-pr`,e.COMMIT=`generate-for-commit`,e.PROJECT=`generate-for-project`,e.COVERAGE=`generate-coverage`,e}({});const fW=Object.freeze({status:`aborted`});function pW(e,t,n){function r(n,r){var i;Object.defineProperty(n,`_zod`,{value:n._zod??{},enumerable:!1}),(i=n._zod).traits??(i.traits=new Set),n._zod.traits.add(e),t(n,r);for(let e in o.prototype)e in n||Object.defineProperty(n,e,{value:o.prototype[e].bind(n)});n._zod.constr=o,n._zod.def=r}let i=n?.Parent??Object;class a extends i{}Object.defineProperty(a,`name`,{value:e});function o(e){var t;let i=n?.Parent?new a:this;r(i,e),(t=i._zod).deferred??(t.deferred=[]);for(let e of i._zod.deferred)e();return i}return Object.defineProperty(o,`init`,{value:r}),Object.defineProperty(o,Symbol.hasInstance,{value:t=>n?.Parent&&t instanceof n.Parent?!0:t?._zod?.traits?.has(e)}),Object.defineProperty(o,`name`,{value:e}),o}var mW=class extends Error{constructor(){super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`)}},hW=class extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`),this.name=`ZodEncodeError`}};const gW={};function _W(e){return e&&Object.assign(gW,e),gW}function vW(e){let t=Object.values(e).filter(e=>typeof e==`number`);return Object.entries(e).filter(([e,n])=>t.indexOf(+e)===-1).map(([e,t])=>t)}function yW(e,t){return typeof t==`bigint`?t.toString():t}function bW(e){return{get value(){{let t=e();return Object.defineProperty(this,`value`,{value:t}),t}throw Error(`cached value already set`)}}}function xW(e){return e==null}function SW(e){let t=e.startsWith(`^`)?1:0,n=e.endsWith(`$`)?e.length-1:e.length;return e.slice(t,n)}function CW(e,t){let n=(e.toString().split(`.`)[1]||``).length,r=t.toString(),i=(r.split(`.`)[1]||``).length;if(i===0&&/\d?e-\d?/.test(r)){let e=r.match(/\d?e-(\d?)/);e?.[1]&&(i=Number.parseInt(e[1]))}let a=n>i?n:i;return Number.parseInt(e.toFixed(a).replace(`.`,``))%Number.parseInt(t.toFixed(a).replace(`.`,``))/10**a}const wW=Symbol(`evaluating`);function TW(e,t,n){let r;Object.defineProperty(e,t,{get(){if(r!==wW)return r===void 0&&(r=wW,r=n()),r},set(n){Object.defineProperty(e,t,{value:n})},configurable:!0})}function EW(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}function DW(...e){let t={};for(let n of e){let e=Object.getOwnPropertyDescriptors(n);Object.assign(t,e)}return Object.defineProperties({},t)}function OW(e){return JSON.stringify(e)}const kW=`captureStackTrace`in Error?Error.captureStackTrace:(...e)=>{};function AW(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}const jW=bW(()=>{if(typeof navigator<`u`&&navigator?.userAgent?.includes(`Cloudflare`))return!1;try{return Function(``),!0}catch{return!1}});function MW(e){if(AW(e)===!1)return!1;let t=e.constructor;if(t===void 0)return!0;let n=t.prototype;return!(AW(n)===!1||Object.prototype.hasOwnProperty.call(n,`isPrototypeOf`)===!1)}function NW(e){return MW(e)?{...e}:Array.isArray(e)?[...e]:e}const PW=new Set([`string`,`number`,`symbol`]);function FW(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}function IW(e,t,n){let r=new e._zod.constr(t??e._zod.def);return(!t||n?.parent)&&(r._zod.parent=e),r}function LW(e){let t=e;if(!t)return{};if(typeof t==`string`)return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,typeof t.error==`string`?{...t,error:()=>t.error}:t}function RW(e){return Object.keys(e).filter(t=>e[t]._zod.optin===`optional`&&e[t]._zod.optout===`optional`)}const Iee={safeint:[-(2**53-1),2**53-1],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]};function zW(e,t){let n=e._zod.def;return IW(e,DW(e._zod.def,{get shape(){let e={};for(let r in t){if(!(r in n.shape))throw Error(`Unrecognized key: "${r}"`);t[r]&&(e[r]=n.shape[r])}return EW(this,`shape`,e),e},checks:[]}))}function BW(e,t){let n=e._zod.def;return IW(e,DW(e._zod.def,{get shape(){let r={...e._zod.def.shape};for(let e in t){if(!(e in n.shape))throw Error(`Unrecognized key: "${e}"`);t[e]&&delete r[e]}return EW(this,`shape`,r),r},checks:[]}))}function VW(e,t){if(!MW(t))throw Error(`Invalid input to extend: expected a plain object`);let n=e._zod.def.checks;if(n&&n.length>0)throw Error("Object schemas containing refinements cannot be extended. Use `.safeExtend()` instead.");return IW(e,DW(e._zod.def,{get shape(){let n={...e._zod.def.shape,...t};return EW(this,`shape`,n),n},checks:[]}))}function HW(e,t){if(!MW(t))throw Error(`Invalid input to safeExtend: expected a plain object`);return IW(e,{...e._zod.def,get shape(){let n={...e._zod.def.shape,...t};return EW(this,`shape`,n),n},checks:e._zod.def.checks})}function UW(e,t){return IW(e,DW(e._zod.def,{get shape(){let n={...e._zod.def.shape,...t._zod.def.shape};return EW(this,`shape`,n),n},get catchall(){return t._zod.def.catchall},checks:[]}))}function WW(e,t,n){return IW(t,DW(t._zod.def,{get shape(){let r=t._zod.def.shape,i={...r};if(n)for(let t in n){if(!(t in r))throw Error(`Unrecognized key: "${t}"`);n[t]&&(i[t]=e?new e({type:`optional`,innerType:r[t]}):r[t])}else for(let t in r)i[t]=e?new e({type:`optional`,innerType:r[t]}):r[t];return EW(this,`shape`,i),i},checks:[]}))}function GW(e,t,n){return IW(t,DW(t._zod.def,{get shape(){let r=t._zod.def.shape,i={...r};if(n)for(let t in n){if(!(t in i))throw Error(`Unrecognized key: "${t}"`);n[t]&&(i[t]=new e({type:`nonoptional`,innerType:r[t]}))}else for(let t in r)i[t]=new e({type:`nonoptional`,innerType:r[t]});return EW(this,`shape`,i),i},checks:[]}))}function KW(e,t=0){if(e.aborted===!0)return!0;for(let n=t;n<e.issues.length;n++)if(e.issues[n]?.continue!==!0)return!0;return!1}function qW(e,t){return t.map(t=>{var n;return(n=t).path??(n.path=[]),t.path.unshift(e),t})}function JW(e){return typeof e==`string`?e:e?.message}function YW(e,t,n){let r={...e,path:e.path??[]};return e.message||(r.message=JW(e.inst?._zod.def?.error?.(e))??JW(t?.error?.(e))??JW(n.customError?.(e))??JW(n.localeError?.(e))??`Invalid input`),delete r.inst,delete r.continue,t?.reportInput||delete r.input,r}function XW(e){return Array.isArray(e)?`array`:typeof e==`string`?`string`:`unknown`}function ZW(...e){let[t,n,r]=e;return typeof t==`string`?{message:t,code:`custom`,input:n,inst:r}:{...t}}const QW=(e,t)=>{e.name=`$ZodError`,Object.defineProperty(e,`_zod`,{value:e._zod,enumerable:!1}),Object.defineProperty(e,`issues`,{value:t,enumerable:!1}),e.message=JSON.stringify(t,yW,2),Object.defineProperty(e,`toString`,{value:()=>e.message,enumerable:!1})},$W=pW(`$ZodError`,QW),eG=pW(`$ZodError`,QW,{Parent:Error});function tG(e,t=e=>e.message){let n={},r=[];for(let i of e.issues)i.path.length>0?(n[i.path[0]]=n[i.path[0]]||[],n[i.path[0]].push(t(i))):r.push(t(i));return{formErrors:r,fieldErrors:n}}function nG(e,t){let n=t||function(e){return e.message},r={_errors:[]},i=e=>{for(let t of e.issues)if(t.code===`invalid_union`&&t.errors.length)t.errors.map(e=>i({issues:e}));else if(t.code===`invalid_key`)i({issues:t.issues});else if(t.code===`invalid_element`)i({issues:t.issues});else if(t.path.length===0)r._errors.push(n(t));else{let e=r,i=0;for(;i<t.path.length;){let r=t.path[i];i===t.path.length-1?(e[r]=e[r]||{_errors:[]},e[r]._errors.push(n(t))):e[r]=e[r]||{_errors:[]},e=e[r],i++}}};return i(e),r}const rG=e=>(t,n,r,i)=>{let a=r?Object.assign(r,{async:!1}):{async:!1},o=t._zod.run({value:n,issues:[]},a);if(o instanceof Promise)throw new mW;if(o.issues.length){let t=new(i?.Err??e)(o.issues.map(e=>YW(e,a,_W())));throw kW(t,i?.callee),t}return o.value},iG=e=>async(t,n,r,i)=>{let a=r?Object.assign(r,{async:!0}):{async:!0},o=t._zod.run({value:n,issues:[]},a);if(o instanceof Promise&&(o=await o),o.issues.length){let t=new(i?.Err??e)(o.issues.map(e=>YW(e,a,_W())));throw kW(t,i?.callee),t}return o.value},aG=e=>(t,n,r)=>{let i=r?{...r,async:!1}:{async:!1},a=t._zod.run({value:n,issues:[]},i);if(a instanceof Promise)throw new mW;return a.issues.length?{success:!1,error:new(e??$W)(a.issues.map(e=>YW(e,i,_W())))}:{success:!0,data:a.value}},oG=aG(eG),sG=e=>async(t,n,r)=>{let i=r?Object.assign(r,{async:!0}):{async:!0},a=t._zod.run({value:n,issues:[]},i);return a instanceof Promise&&(a=await a),a.issues.length?{success:!1,error:new e(a.issues.map(e=>YW(e,i,_W())))}:{success:!0,data:a.value}},cG=sG(eG),lG=e=>(t,n,r)=>{let i=r?Object.assign(r,{direction:`backward`}):{direction:`backward`};return rG(e)(t,n,i)},uG=e=>(t,n,r)=>rG(e)(t,n,r),dG=e=>async(t,n,r)=>{let i=r?Object.assign(r,{direction:`backward`}):{direction:`backward`};return iG(e)(t,n,i)},Lee=e=>async(t,n,r)=>iG(e)(t,n,r),fG=e=>(t,n,r)=>{let i=r?Object.assign(r,{direction:`backward`}):{direction:`backward`};return aG(e)(t,n,i)},pG=e=>(t,n,r)=>aG(e)(t,n,r),mG=e=>async(t,n,r)=>{let i=r?Object.assign(r,{direction:`backward`}):{direction:`backward`};return sG(e)(t,n,i)},hG=e=>async(t,n,r)=>sG(e)(t,n,r),gG=/^[cC][^\s-]{8,}$/,_G=/^[0-9a-z]+$/,vG=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,yG=/^[0-9a-vA-V]{20}$/,bG=/^[A-Za-z0-9]{27}$/,xG=/^[a-zA-Z0-9_-]{21}$/,SG=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,Ree=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,CG=e=>e?RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/,wG=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;function TG(){return RegExp(`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`,`u`)}const zee=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,Bee=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/,EG=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,DG=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,OG=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,kG=/^[A-Za-z0-9_-]*$/,Vee=/^(?=.{1,253}\.?$)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[-0-9a-zA-Z]{0,61}[0-9a-zA-Z])?)*\.?$/,AG=/^\+(?:[0-9]){6,14}[0-9]$/,jG=`(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))`,MG=RegExp(`^${jG}$`);function NG(e){let t=`(?:[01]\\d|2[0-3]):[0-5]\\d`;return typeof e.precision==`number`?e.precision===-1?`${t}`:e.precision===0?`${t}:[0-5]\\d`:`${t}:[0-5]\\d\\.\\d{${e.precision}}`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}function PG(e){return RegExp(`^${NG(e)}$`)}function FG(e){let t=NG({precision:e.precision}),n=[`Z`];e.local&&n.push(``),e.offset&&n.push(`([+-](?:[01]\\d|2[0-3]):[0-5]\\d)`);let r=`${t}(?:${n.join(`|`)})`;return RegExp(`^${jG}T(?:${r})$`)}const IG=e=>{let t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??``}}`:`[\\s\\S]*`;return RegExp(`^${t}$`)},LG=/^-?\d+$/,RG=/^-?\d+(?:\.\d+)?/,zG=/^[^A-Z]*$/,BG=/^[^a-z]*$/,VG=pW(`$ZodCheck`,(e,t)=>{var n;e._zod??={},e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),HG={number:`number`,bigint:`bigint`,object:`date`},UG=pW(`$ZodCheckLessThan`,(e,t)=>{VG.init(e,t);let n=HG[typeof t.value];e._zod.onattach.push(e=>{let n=e._zod.bag,r=(t.inclusive?n.maximum:n.exclusiveMaximum)??1/0;t.value<r&&(t.inclusive?n.maximum=t.value:n.exclusiveMaximum=t.value)}),e._zod.check=r=>{(t.inclusive?r.value<=t.value:r.value<t.value)||r.issues.push({origin:n,code:`too_big`,maximum:t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),WG=pW(`$ZodCheckGreaterThan`,(e,t)=>{VG.init(e,t);let n=HG[typeof t.value];e._zod.onattach.push(e=>{let n=e._zod.bag,r=(t.inclusive?n.minimum:n.exclusiveMinimum)??-1/0;t.value>r&&(t.inclusive?n.minimum=t.value:n.exclusiveMinimum=t.value)}),e._zod.check=r=>{(t.inclusive?r.value>=t.value:r.value>t.value)||r.issues.push({origin:n,code:`too_small`,minimum:t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),GG=pW(`$ZodCheckMultipleOf`,(e,t)=>{VG.init(e,t),e._zod.onattach.push(e=>{var n;(n=e._zod.bag).multipleOf??(n.multipleOf=t.value)}),e._zod.check=n=>{if(typeof n.value!=typeof t.value)throw Error(`Cannot mix number and bigint in multiple_of check.`);(typeof n.value==`bigint`?n.value%t.value===BigInt(0):CW(n.value,t.value)===0)||n.issues.push({origin:typeof n.value,code:`not_multiple_of`,divisor:t.value,input:n.value,inst:e,continue:!t.abort})}}),KG=pW(`$ZodCheckNumberFormat`,(e,t)=>{VG.init(e,t),t.format=t.format||`float64`;let n=t.format?.includes(`int`),r=n?`int`:`number`,[i,a]=Iee[t.format];e._zod.onattach.push(e=>{let r=e._zod.bag;r.format=t.format,r.minimum=i,r.maximum=a,n&&(r.pattern=LG)}),e._zod.check=o=>{let s=o.value;if(n){if(!Number.isInteger(s)){o.issues.push({expected:r,format:t.format,code:`invalid_type`,continue:!1,input:s,inst:e});return}if(!Number.isSafeInteger(s)){s>0?o.issues.push({input:s,code:`too_big`,maximum:2**53-1,note:`Integers must be within the safe integer range.`,inst:e,origin:r,continue:!t.abort}):o.issues.push({input:s,code:`too_small`,minimum:-(2**53-1),note:`Integers must be within the safe integer range.`,inst:e,origin:r,continue:!t.abort});return}}s<i&&o.issues.push({origin:`number`,input:s,code:`too_small`,minimum:i,inclusive:!0,inst:e,continue:!t.abort}),s>a&&o.issues.push({origin:`number`,input:s,code:`too_big`,maximum:a,inst:e})}}),qG=pW(`$ZodCheckMaxLength`,(e,t)=>{var n;VG.init(e,t),(n=e._zod.def).when??(n.when=e=>{let t=e.value;return!xW(t)&&t.length!==void 0}),e._zod.onattach.push(e=>{let n=e._zod.bag.maximum??1/0;t.maximum<n&&(e._zod.bag.maximum=t.maximum)}),e._zod.check=n=>{let r=n.value;if(r.length<=t.maximum)return;let i=XW(r);n.issues.push({origin:i,code:`too_big`,maximum:t.maximum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),JG=pW(`$ZodCheckMinLength`,(e,t)=>{var n;VG.init(e,t),(n=e._zod.def).when??(n.when=e=>{let t=e.value;return!xW(t)&&t.length!==void 0}),e._zod.onattach.push(e=>{let n=e._zod.bag.minimum??-1/0;t.minimum>n&&(e._zod.bag.minimum=t.minimum)}),e._zod.check=n=>{let r=n.value;if(r.length>=t.minimum)return;let i=XW(r);n.issues.push({origin:i,code:`too_small`,minimum:t.minimum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),YG=pW(`$ZodCheckLengthEquals`,(e,t)=>{var n;VG.init(e,t),(n=e._zod.def).when??(n.when=e=>{let t=e.value;return!xW(t)&&t.length!==void 0}),e._zod.onattach.push(e=>{let n=e._zod.bag;n.minimum=t.length,n.maximum=t.length,n.length=t.length}),e._zod.check=n=>{let r=n.value,i=r.length;if(i===t.length)return;let a=XW(r),o=i>t.length;n.issues.push({origin:a,...o?{code:`too_big`,maximum:t.length}:{code:`too_small`,minimum:t.length},inclusive:!0,exact:!0,input:n.value,inst:e,continue:!t.abort})}}),XG=pW(`$ZodCheckStringFormat`,(e,t)=>{var n,r;VG.init(e,t),e._zod.onattach.push(e=>{let n=e._zod.bag;n.format=t.format,t.pattern&&(n.patterns??=new Set,n.patterns.add(t.pattern))}),t.pattern?(n=e._zod).check??(n.check=n=>{t.pattern.lastIndex=0,!t.pattern.test(n.value)&&n.issues.push({origin:`string`,code:`invalid_format`,format:t.format,input:n.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(r=e._zod).check??(r.check=()=>{})}),ZG=pW(`$ZodCheckRegex`,(e,t)=>{XG.init(e,t),e._zod.check=n=>{t.pattern.lastIndex=0,!t.pattern.test(n.value)&&n.issues.push({origin:`string`,code:`invalid_format`,format:`regex`,input:n.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),QG=pW(`$ZodCheckLowerCase`,(e,t)=>{t.pattern??=zG,XG.init(e,t)}),$G=pW(`$ZodCheckUpperCase`,(e,t)=>{t.pattern??=BG,XG.init(e,t)}),eK=pW(`$ZodCheckIncludes`,(e,t)=>{VG.init(e,t);let n=FW(t.includes),r=new RegExp(typeof t.position==`number`?`^.{${t.position}}${n}`:n);t.pattern=r,e._zod.onattach.push(e=>{let t=e._zod.bag;t.patterns??=new Set,t.patterns.add(r)}),e._zod.check=n=>{n.value.includes(t.includes,t.position)||n.issues.push({origin:`string`,code:`invalid_format`,format:`includes`,includes:t.includes,input:n.value,inst:e,continue:!t.abort})}}),tK=pW(`$ZodCheckStartsWith`,(e,t)=>{VG.init(e,t);let n=RegExp(`^${FW(t.prefix)}.*`);t.pattern??=n,e._zod.onattach.push(e=>{let t=e._zod.bag;t.patterns??=new Set,t.patterns.add(n)}),e._zod.check=n=>{n.value.startsWith(t.prefix)||n.issues.push({origin:`string`,code:`invalid_format`,format:`starts_with`,prefix:t.prefix,input:n.value,inst:e,continue:!t.abort})}}),nK=pW(`$ZodCheckEndsWith`,(e,t)=>{VG.init(e,t);let n=RegExp(`.*${FW(t.suffix)}$`);t.pattern??=n,e._zod.onattach.push(e=>{let t=e._zod.bag;t.patterns??=new Set,t.patterns.add(n)}),e._zod.check=n=>{n.value.endsWith(t.suffix)||n.issues.push({origin:`string`,code:`invalid_format`,format:`ends_with`,suffix:t.suffix,input:n.value,inst:e,continue:!t.abort})}}),rK=pW(`$ZodCheckOverwrite`,(e,t)=>{VG.init(e,t),e._zod.check=e=>{e.value=t.tx(e.value)}});var iK=class{constructor(e=[]){this.content=[],this.indent=0,this&&(this.args=e)}indented(e){this.indent+=1,e(this),--this.indent}write(e){if(typeof e==`function`){e(this,{execution:`sync`}),e(this,{execution:`async`});return}let t=e.split(`
|
|
32359
|
+
Start the workflow now with Phase 0 (read the provided project commands), then proceed with the given target file/function.`)||e.systemPrompt,o=await this.agentSdkRunner.run({userPrompt:e.prompt,workingDirectory:i,testFilePath:t,systemPrompt:a,abortSignal:n,parentName:r?.parentName,methodName:r?.methodName});return{code:o.code,prompt:e.prompt,requestId:e.requestId,validationSummary:o.validationSummary}}};Um=(0,Bm.default)([(0,_.injectable)(),(0,zm.default)(0,(0,_.inject)(kr)),(0,zm.default)(1,(0,_.inject)(He)),(0,zm.default)(2,(0,_.inject)(dm)),(0,Rm.default)(`design:paramtypes`,[typeof(Vm=kr!==void 0&&kr)==`function`?Vm:Object,Object,typeof(Hm=dm!==void 0&&dm)==`function`?Hm:Object])],Um);var Wm=l(Ie()),Gm=l(Cr()),Km=l(Le()),qm,Jm,Ym,Xm,Zm,Qm;let $m=class{constructor(e,t,n,r,i,a,o){this.metricReportService=e,this.importSolverService=t,this.gatherDataSourceService=n,this.globalConfigService=r,this.lintRulesService=i,this.lintValidationService=a,this.testGeneratorProvider=o}async initGenerateTestFlow({filePath:e,testable:t,outputType:n,abortSignal:r,userPrompt:i}){let a=`Test generation was aborted`;return new Promise(async(o,s)=>{let{methodName:c,methodType:l,parentName:u}=ai(t);H.addContext({testedFunction:c,testedMethodClass:u});try{if((r?.aborted??!1)||((0,h.isDefined)(r)&&r.addEventListener(`abort`,()=>{s(a)}),r?.aborted??!1))return s(a);await Jt.init(e);let u=ut(e),d=await this.getEarlyTestFile(e,c,u,n),p=d.getFilePath(),m=null;Jt.add(p);let g=performance.now(),_=H.getRequestId();H.info.defaultLog(`Generating tests for method ${c}`);let v=this.metricReportService.registerStartTime(_);if(r?.aborted??!1)return s(a);let y=await this.gatherDataSourceService.gatherDataSource({path:e,testFilePath:p,outputType:n,testable:t,userPrompt:i}),b=performance.now()-g;H.debug.defaultLog(`with ${y.llmConfig.modelName??`default`} model, ${y.llmConfig.temperature??`default`} temperature, ${y.llmConfig.topP??`default`} top-p`);let x=this.globalConfigService.getExperimentalAgentSdk(),S;if(x)try{if(S=f.default.resolve(this.globalConfigService.getRootPath(),p),H.info.defaultLog(`[experimental] Pre-created test scaffold at ${S}`),H.info.defaultLog(`Calling BE for method ${c}`),r?.aborted??!1)return s(a);let{code:t,validationSummary:n}=await this.generateTest(y,_,b,r,S);if(r?.aborted??!1)return s(a);if((0,h.isEmpty)(t))throw new sr(ar.EMPTY_TEST,{methodName:c});H.info.defaultLog(`[experimental] Skipping code refinement for method "${c}"`);let i=await v({responseProcessingTime:performance.now()-g,gitUrl:this.globalConfigService.getGitURL()});return this.metricReportService.logPackageDependencies(e),H.info.endLog(`Generate Tests done: ${l} ${c} in ${e}. Duration: ${i}ms.`),o({shouldRefreshCoverage:this.globalConfigService.getShouldRefreshCoverage(),testFilePath:p,requestId:_,lintErrors:null,validationSummary:n})}catch(e){let t;if(e instanceof tp){let n=e.errors.length>0?`: `+e.errors.join(`, `):``;t=e.subtype+n+` ($`+e.costUsd.toFixed(4)+`)`}else t=String(e);H.error(`[experimental] SDK runner failed for method "${c}": ${t}`,void 0);try{await d.delete()}catch(e){H.info.defaultLog(`Failed to delete scaffold file for method "${c}"`,e)}return await v({responseProcessingTime:0,gitUrl:this.globalConfigService.getGitURL(),errorCause:t}),o({shouldRefreshCoverage:!1,testFilePath:``,requestId:_,lintErrors:null,validationSummary:{greenTestsCount:0,greyTestsCount:0,redTestsCount:0,naTestsCount:0,errorSuitsCount:0,lintErrorsCount:0,whiteTestsCount:0}})}if(H.info.defaultLog(`Calling BE for method ${c}`),r?.aborted??!1)return s(a);let{code:C,prompt:w,validationSummary:T}=await this.generateTest(y,_,b,r,S);if(r?.aborted??!1)return s(a);if((0,h.isEmpty)(C))throw new sr(ar.EMPTY_TEST,{methodName:c});let E=performance.now();if(r?.aborted??!1)return s(a);Jt.add(p,C),await new _a(this.importSolverService,e,p,t,u).refine({shouldResolveMockPaths:!0,shouldSolveImports:!0});let D=Jt.get(p).getFullText();if((0,h.isEmpty)(D))throw await v({responseProcessingTime:performance.now()-E,gitUrl:this.globalConfigService.getGitURL()}),new sr(ar.EMPTY_TEST,{methodName:c});if(r?.aborted??!1)return s(a);try{if(await d.replace(D),H.debug.defaultLog(`Done upserting test file for method "${c}"`),r?.aborted??!1)return s(a);await d.addPrompt(w),H.debug.defaultLog(`Added prompt for method "${c}"`),m=await this.lintValidationService.fixLintErrors(p),H.debug.defaultLog(`Ran lint command for method "${c}"`),await this.lintValidationService.addComplexitySuppressions(p)&&(H.info.defaultLog(`Complexity suppression comment added, refreshing file`),await Jt.refreshFromFileSystem(p));try{await this.lintRulesService.disableRules(p)}catch(e){H.info.defaultLog(`Failed disabling lint rules`,e)}try{if(r?.aborted??!1)return s(a);await d.runFormatCommand()}catch(e){H.info.defaultLog(`Failed formatting test file`,e)}H.debug.defaultLog(`Ran format command for method "${c}"`);let t=performance.now()-E;if(r?.aborted??!1)return s(a);let n=await v({responseProcessingTime:t,gitUrl:this.globalConfigService.getGitURL()});this.metricReportService.logPackageDependencies(e),await Jt.refreshFromFileSystem(p),H.info.endLog(`Generate Tests done: ${l} ${c} in ${e}. Duration: ${n}ms.`)}catch(e){if(r?.aborted??!1)return s(a);throw await v({responseProcessingTime:performance.now()-E,gitUrl:this.globalConfigService.getGitURL()}),e}return o({shouldRefreshCoverage:this.globalConfigService.getShouldRefreshCoverage(),testFilePath:p,requestId:_,lintErrors:m,validationSummary:T})}catch(e){return r?.aborted??!1?s(a):(H.info.defaultLog(`Unexpected Error generating tests`,e,[c,u]),s(e))}})}async generateTest(e,t,n,r,i){let a=e.testedCodeDataSource.testedMethod.name,o;try{o=await this.apiCall(e,t,n,r,i)}catch(e){if(H.info.defaultLog(`Failed making generateTest API Call`,e instanceof Error?e.message:e,t),e instanceof sr||e instanceof tp)throw e;let n=e instanceof Error?e.message:`Failed making API call`;throw new sr(ar.GENERATING_TESTS_REQUEST_ERROR,{methodName:a,errorMessage:n})}let{code:s,prompt:c}=o;return this.globalConfigService.getExperimentalAgentSdk()||H.debug.defaultLog(`Generating tests for method "${a}" - prompt: "${c}", LLM response: "${s}"`),o}async apiCall(e,t,n,r,i){let a=e.testedCodeDataSource.testedMethod.name,o=e.testedCodeDataSource.testedMethodClass?.name;try{return await this.testGeneratorProvider.generate(e,t,n,r,i,{parentName:o,methodName:a})}catch(e){if(H.info.defaultLog(`GenerateTestService failed to generate tests`,e instanceof Error?e.message:e),e instanceof sr||e instanceof tp)throw e;let t=e instanceof Error?e.message:`Failed making API call`;throw new sr(ar.GENERATING_TESTS_REQUEST_ERROR,{methodName:a,errorMessage:t})}}async getEarlyTestFile(e,t,n,r){if(r===ge.OVERRIDE_CODE_FILE){let n=await zi.getLatestTestFile(e,t);if((0,h.isDefined)(n))return new zi(ct(n))}return await zi.getNextTestFile(e,t,n)}};(0,Km.default)([Yt,(0,Wm.default)(`design:type`,Function),(0,Wm.default)(`design:paramtypes`,[Object]),(0,Wm.default)(`design:returntype`,Promise)],$m.prototype,`initGenerateTestFlow`,null),$m=(0,Km.default)([(0,_.injectable)(),(0,Gm.default)(0,(0,_.inject)(Yr)),(0,Gm.default)(1,(0,_.inject)(Ia)),(0,Gm.default)(2,(0,_.inject)(Lm)),(0,Gm.default)(3,(0,_.inject)(He)),(0,Gm.default)(4,(0,_.inject)(_i)),(0,Gm.default)(5,(0,_.inject)(vu)),(0,Gm.default)(6,(0,_.inject)(Um)),(0,Wm.default)(`design:paramtypes`,[typeof(qm=Yr!==void 0&&Yr)==`function`?qm:Object,typeof(Jm=Ia!==void 0&&Ia)==`function`?Jm:Object,typeof(Ym=Lm!==void 0&&Lm)==`function`?Ym:Object,Object,typeof(Xm=_i!==void 0&&_i)==`function`?Xm:Object,typeof(Zm=vu!==void 0&&vu)==`function`?Zm:Object,typeof(Qm=Um!==void 0&&Um)==`function`?Qm:Object])],$m);var eh=l(Ie()),th=l(Cr()),nh=l(Le()),rh,ih,ah,oh,sh,ch;let lh=class{shouldTriggerRefreshCoverage=!1;queue;coverageService=new er;validationReports=new Map;testResults=new Map;constructor(e,t,n,r,i,a){this.generateTestService=e,this.dynamicPromptService=t,this.globalConfigService=n,this.testManagementService=r,this.metricReportService=i,this.lintValidationService=a,this.queue=new Xr({concurrency:this.globalConfigService.getConcurrency(),getItemKey:this.getQueueItemKey})}getQueueItemKey({filePath:e,methodType:t,methodName:n,parentName:r=``}){return`${e}:${t}:${r}:${n}`}decodeQueueItemKey(e){let[t,n,r,i]=e.split(`:`);return{filePath:t,methodType:n,parentName:r,methodName:i}}async clearTemporaryFiles(){let e=`**/.${ni}*`,t=await(0,A.default)(e);for(let e of t)try{await(0,p.unlink)(e)}catch(e){H.info.defaultLog(`Failed removing temp file:`,e)}}async getFinalValidationReport(e,t){return await this.testManagementService.getValidationReport(e,t)}buildEmptyTestCounters(){return{greenTestsCount:0,greyTestsCount:0,redTestsCount:0,naTestsCount:0,errorSuitsCount:0,lintErrorsCount:0,whiteTestsCount:0}}buildFinalTestCounters(e){return{greenTestsCount:e.greenTestsCount,greyTestsCount:e.greyTestsCount,redTestsCount:e.redTestsCount,naTestsCount:e.naTestsCount,errorSuitsCount:e.errorSuitsCount,lintErrorsCount:e.lintErrorsCount,whiteTestsCount:e.whiteTestsCount}}async handleSdkResult(e,t){let n=t.validationSummary??null;this.testResults.set(e,{testFilePath:t.testFilePath,requestId:t.requestId}),this.validationReports.set(e,n);let r=n?{greenTestsCount:n.greenTestsCount,greyTestsCount:n.greyTestsCount,redTestsCount:n.redTestsCount,naTestsCount:n.naTestsCount,errorSuitsCount:n.errorSuitsCount,lintErrorsCount:n.lintErrorsCount,whiteTestsCount:n.whiteTestsCount}:this.buildEmptyTestCounters();await this.metricReportService.saveTestMetrics({requestId:t.requestId,finalGreenTestsCount:r.greenTestsCount,finalTestCounters:r,gitUrl:this.globalConfigService.getGitURL()})}sanitizePath(e){return e.startsWith(`/`)?e.slice(1):e}async addGenerationToQueue({filePath:e,testable:t,outputType:n,userPrompt:r,progress:i}){let a=this.sanitizePath(e),{methodType:o,methodName:s,parentName:c}=ai(t),l={filePath:a,methodType:o,methodName:s,parentName:c};if(H.addContext({testedFunction:s,testedMethodClass:c}),this.queue.has(l)){H.info.defaultLog(`Test generation for "${t.name}" is already in progress`);return}H.info.defaultLog(`Generate Tests: ${t.name} in ${a}`),await this.queue.add(l,async e=>{await H.withBufferedPrinting(async()=>{H.default.info(``),H.default.info((0,h.isDefined)(i)?`Generating tests for ${t.name} - ${i.index} out of ${i.total} functions`:`Generating tests for ${t.name} in ${a}`),await Xt(async()=>{H.default.info(`Generating initial tests`);let i=await this.initGenerateTest({filePath:a,testable:t,outputType:n??this.globalConfigService.getOutputType(),abortSignal:e,userPrompt:r});if((0,h.isDefined)(i?.testFilePath)){let e=this.getQueueItemKey(l);if(this.globalConfigService.getExperimentalAgentSdk()){await this.handleSdkResult(e,i);return}let n=await this.testManagementService.getValidationReport(i.testFilePath,s);await this.metricReportService.saveTestMetrics({requestId:i.requestId,validationReport:n,gitUrl:this.globalConfigService.getGitURL()}),await this.dynamicPromptService.initDynamicPromptRecursively(t,i.testFilePath,i.requestId),H.default.info(``);let r=await this.getFinalValidationReport(i.testFilePath,s);if(H.default.info(`Test fixing complete`),H.default.info(`✅ ${r.greenTestsCount} tests passing`),H.default.info(`⚠️ ${r.redTestsCount} tests still failing (will be skipped)`),H.default.info(`❌ ${r.greyTestsCount} tests could not be fixed autonomously`),H.default.info(``),this.validationReports.set(e,r),this.testResults.set(e,{testFilePath:i.testFilePath,requestId:i.requestId}),this.testManagementService.needsRemoval(r)){await this.testManagementService.removeFailedTestFile(i.testFilePath),await this.metricReportService.saveTestMetrics({requestId:i.requestId,finalGreenTestsCount:0,finalTestCounters:this.buildEmptyTestCounters(),gitUrl:this.globalConfigService.getGitURL()});return}this.testManagementService.needsCleanup(r)?await this.testManagementService.cleanup(i.testFilePath,s):H.info.defaultLog(`No cleanup needed for method "${s}" in ${a}.\nGreen: ${r.greenTestsCount}, Grey: ${r.greyTestsCount}, Red: ${r.redTestsCount}, NA: ${r.naTestsCount}, Error Suits: ${r.errorSuitsCount}`),await this.testManagementService.removeTestComments(i.testFilePath),await this.testManagementService.cleanupPrettier(i.testFilePath),H.default.info(`▶️ Fixing lint and prettier issues`);let o=await this.getFinalValidationReport(i.testFilePath,s);if(H.default.info(`✔️ Tests finalized`),o.greenTestsCount>0?H.default.info(`🟢 Test generation complete`):o.greenTestsCount===0&&H.default.info(`🔴 Tests were generated but could not be validated successfully here`),H.default.info(``),H.default.info(`Summary:`),H.default.info(``),H.default.info(`✅ ${r.greenTestsCount} tests passing`),H.default.info(`⚠️ ${r.redTestsCount} tests skipped`),H.default.info(`❌ ${r.greyTestsCount} tests could not be fixed autonomously`),H.default.info(``),H.default.info(`----------------`),this.testManagementService.needsRemoval(o)){await this.testManagementService.removeFailedTestFile(i.testFilePath),await this.metricReportService.saveTestMetrics({requestId:i.requestId,finalGreenTestsCount:0,finalTestCounters:this.buildEmptyTestCounters(),gitUrl:this.globalConfigService.getGitURL()});return}await this.metricReportService.saveTestMetrics({requestId:i.requestId,finalGreenTestsCount:o.greenTestsCount,finalTestResult:o.testResult,finalTestCounters:this.buildFinalTestCounters(o),gitUrl:this.globalConfigService.getGitURL()})}else{let e=this.getQueueItemKey(l);this.validationReports.set(e,null)}})},i?.index??0)})}async bulkGenerateTests(e,t,n,r){let[{filePath:i}]=e;await Jt.init(i),(0,h.isDefined)(t)&&this.queue.onDone(n=>{let r=e.find(({filePath:e,testable:t})=>{let{methodName:r,methodType:i,parentName:a=``}=ai(t);return this.getQueueItemKey({filePath:e,methodType:i,methodName:r,parentName:a})===n});if((0,h.isDefined)(r))try{t(r,this.validationReports.get(n)??null,this.testResults.get(n)??null)}catch(e){H.error(`Callback execution failed for testable ${n}`,e)}finally{this.validationReports.delete(n),this.testResults.delete(n)}}),H.resetPrintOrder();for(let[t,{filePath:i,testable:a}]of e.entries())this.addGenerationToQueue({filePath:i,testable:a,userPrompt:n,progress:{index:t+1,total:e.length}}).catch(e=>{e instanceof sr&&(H.default.info(``),H.default.warn(`‼️ ${e.message}`),this.queue.clearQueued(),r?.(e))});await this.queue.getIdlePromise(),Jt.clear()}async initGenerateTest({filePath:e,testable:t,outputType:n,abortSignal:r,userPrompt:i}){let{methodName:a,parentName:o}=ai(t);try{if(r?.aborted)return;let s=Math.round(process.memoryUsage().heapUsed/1024/1024);ir.safeTrackEvent(`GenerateTestsInitiated`,{methodName:a,parentName:o,heapMemoryUsedMB:s});let{shouldRefreshCoverage:c,testFilePath:l,requestId:u,lintErrors:d,validationSummary:f}=await this.generateTestService.initGenerateTestFlow({filePath:e,testable:t,outputType:n,abortSignal:r,userPrompt:i});return r?.aborted?void 0:(c&&(this.shouldTriggerRefreshCoverage=!0),{shouldRefreshCoverage:c,testFilePath:l,requestId:u,lintErrors:d,validationSummary:f})}catch(e){if(!r.aborted){H.error(`Test generation failed.`,e);let t=new Map([[or[ar.NOT_ENOUGH_BALANCE_ERROR],ar.NOT_ENOUGH_BALANCE_ERROR]]);if(e instanceof sr&&t.has(e.message)){let n=t.get(e.message);throw ir.safeTrackEvent(`GenerateTestsError`,{errorCode:n}),e}}}}};(0,nh.default)([Yt,(0,eh.default)(`design:type`,Function),(0,eh.default)(`design:paramtypes`,[Array,Object,String,typeof(ch=h.Fn!==void 0&&h.Fn)==`function`?ch:Object]),(0,eh.default)(`design:returntype`,Promise)],lh.prototype,`bulkGenerateTests`,null),(0,nh.default)([$e({category:Tt.GENERATE_TESTS}),(0,eh.default)(`design:type`,Function),(0,eh.default)(`design:paramtypes`,[Object]),(0,eh.default)(`design:returntype`,Promise)],lh.prototype,`initGenerateTest`,null),lh=(0,nh.default)([(0,_.injectable)(),(0,th.default)(0,(0,_.inject)($m)),(0,th.default)(1,(0,_.inject)(_d)),(0,th.default)(2,(0,_.inject)(He)),(0,th.default)(3,(0,_.inject)(sd)),(0,th.default)(4,(0,_.inject)(Yr)),(0,th.default)(5,(0,_.inject)(vu)),(0,eh.default)(`design:paramtypes`,[typeof(rh=$m!==void 0&&$m)==`function`?rh:Object,typeof(ih=_d!==void 0&&_d)==`function`?ih:Object,Object,typeof(ah=sd!==void 0&&sd)==`function`?ah:Object,typeof(oh=Yr!==void 0&&Yr)==`function`?oh:Object,typeof(sh=vu!==void 0&&vu)==`function`?sh:Object])],lh);var uh=l(Ie()),dh=l(Cr()),fh=l(Le()),ph;let mh=class{constructor(e){this.globalConfigService=e}async getFileTestables(e){try{let t=new et(e);return await t.isFileExists()?[e,new Mn(await t.getText()).testables.getAllTestables().filter(e=>e.canCreateTests&&e.type!==`class`)]:[e,[]]}catch(t){return H.info.defaultLog(`Failed reading file ${e}: check early.config.json`,t,{category:`Early config file`,subCategory:`Reading configuration`}),[e,[]]}}async getTestablesByPattern(e){try{let t=await Bn(e);return await Promise.all(t.map(e=>this.getFileTestables(e)))}catch(t){return H.info.defaultLog(`Failed reading file pattern ${e}: check early.config.json`,t),[]}}async getAllMethodsCount(e){try{let t=new et(e);return await t.isFileExists()?new Mn(await t.getText()).testables.getAllMethodsCount():0}catch(t){return H.info.failedLog(`Failed to get all methods count for ${e}`,t),0}}async resolveEarlyTestFile(e){let{absoluteFilePath:t,testableName:n}=e,r=this.globalConfigService.getRootPath(),i=ct(t),a=zi.fromTestablePath(i,n,r),o=await a.isFileExists(),s=f.default.resolve(r,a.getFilePath());return{...e,testFilePath:s,isExists:o}}async getTestableFileMap(e){if((0,h.isEmpty)(e))return{};let t=this.globalConfigService.getRootPath(),n=[...new Set(e.map(e=>this.toAbsolutePath(e,t)))],r={};for(let e of n){let[n,i]=await this.getFileTestables(e),a=this.toAbsolutePath(n,t);r[a]=await this.buildFilesTreeTestableEntries(i,a)}return r}toAbsolutePath(e,t){return f.default.isAbsolute(e)?e:f.default.resolve(t,e)}async buildFilesTreeTestableEntries(e,t){let n=[];for(let r of e){if(!(0,h.isDefined)(r.name)||r.type===`class`)continue;let e=await this.resolveEarlyTestFile({absoluteFilePath:t,testableName:r.name});n.push({testable:r,...e.isExists&&{testPath:e.testFilePath},testableFilePath:t})}return n}};mh=(0,fh.default)([(0,_.injectable)(),(0,dh.default)(0,(0,_.inject)(He)),(0,uh.default)(`design:paramtypes`,[typeof(ph=He!==void 0&&He)==`function`?ph:Object])],mh);var hh=l(Ie()),gh=l(Cr()),_h=l(Le()),vh;let yh=class{constructor(e){this.testablesService=e}async resolveEarlyTestFile(e){try{return await this.testablesService.resolveEarlyTestFile(e)}catch(t){return H.info.failedLog(`Failed to get test file exists`,t),{...e,testFilePath:``,isExists:!1}}}async getTestables(e){try{return await this.testablesService.getTestablesByPattern(e)}catch(e){return H.info.failedLog(`Failed to get testables`,e),[]}}async getAllMethodsCount(e){try{return await this.testablesService.getAllMethodsCount(e)}catch(e){return H.info.failedLog(`Failed to get all methods count`,e),0}}async getTestableFileMap(e){try{return await this.testablesService.getTestableFileMap(e)}catch(e){return H.error(`Failed to get files tree`,e),{}}}};yh=(0,_h.default)([(0,_.injectable)(),(0,gh.default)(0,(0,_.inject)(mh)),(0,hh.default)(`design:paramtypes`,[typeof(vh=mh!==void 0&&mh)==`function`?vh:Object])],yh);var bh=l(Ie()),xh=l(Cr()),Sh=l(Le()),Ch,wh,Th,Eh,Dh,Oh,kh,Ah,jh,Mh;let Nh=class{constructor(e,t,n,r,i,a,o,s,c){this.testablesController=e,this.coverageController=t,this.generateTestController=n,this.authService=r,this.globalConfigService=i,this.testResultCounterService=a,this.testableContextService=o,this.dynamicPromptService=s,this.testValidatorService=c}async init(e){await this.authService.authorize(e)}async getTestables(e){return this.testablesController.getTestables(e)}async getAllMethodsCount(e){return this.testablesController.getAllMethodsCount(e)}async resolveEarlyTestFile(e){return this.testablesController.resolveEarlyTestFile(e)}async getTestableFileMap(e){return this.testablesController.getTestableFileMap(e)}async generateCoverage(){return this.coverageController.generateCoverage()}async setCoverage(e){return this.coverageController.setCoverage(e)}async getCoverageTree(){return this.coverageController.getCoverageTree()}async getCoverageForFiles(e){return this.coverageController.getCoverageForFiles(e)}async generateTests(e,t){return this.generateTestController.addGenerationToQueue({filePath:e,testable:t})}async bulkGenerateTests(e,t,n,r){return this.generateTestController.bulkGenerateTests(e,t,n,r)}updateContext(e){this.globalConfigService.updateContext(e)}updateRootPath(e){this.globalConfigService.updateRootPath(e)}async getValidationReport(e,t){return this.testResultCounterService.getValidationReport(e,t)}async getTestedCodeDataSource(e,t,n){return this.testableContextService.getTestedCodeDataSource(e,t,n)}async runDynamicPrompt(e,t,n){return(await this.dynamicPromptService.initDynamicPrompt(e,t,0,n))?.validationReport??null}async validateTestsByCode(e,t){return this.testValidatorService.validateTestsByCode(e,t)}};(0,Sh.default)([$e({category:Tt.INITIALIZATION}),(0,bh.default)(`design:type`,Function),(0,bh.default)(`design:paramtypes`,[String]),(0,bh.default)(`design:returntype`,Promise)],Nh.prototype,`init`,null),(0,Sh.default)([$e({category:Tt.GET_TESTABLES}),(0,bh.default)(`design:type`,Function),(0,bh.default)(`design:paramtypes`,[String]),(0,bh.default)(`design:returntype`,Promise)],Nh.prototype,`getTestables`,null),(0,Sh.default)([$e({category:Tt.GET_TESTABLES}),(0,bh.default)(`design:type`,Function),(0,bh.default)(`design:paramtypes`,[String]),(0,bh.default)(`design:returntype`,Promise)],Nh.prototype,`getAllMethodsCount`,null),(0,Sh.default)([$e({category:Tt.GET_TESTABLES}),(0,bh.default)(`design:type`,Function),(0,bh.default)(`design:paramtypes`,[Object]),(0,bh.default)(`design:returntype`,Promise)],Nh.prototype,`resolveEarlyTestFile`,null),(0,Sh.default)([$e({category:Tt.GET_TESTABLES}),(0,bh.default)(`design:type`,Function),(0,bh.default)(`design:paramtypes`,[Array]),(0,bh.default)(`design:returntype`,Promise)],Nh.prototype,`getTestableFileMap`,null),(0,Sh.default)([$e({category:Tt.GENERATE_COVERAGE}),(0,bh.default)(`design:type`,Function),(0,bh.default)(`design:paramtypes`,[]),(0,bh.default)(`design:returntype`,Promise)],Nh.prototype,`generateCoverage`,null),(0,Sh.default)([$e({category:Tt.SET_COVERAGE}),(0,bh.default)(`design:type`,Function),(0,bh.default)(`design:paramtypes`,[Object]),(0,bh.default)(`design:returntype`,Promise)],Nh.prototype,`setCoverage`,null),(0,Sh.default)([$e({category:Tt.GET_COVERAGE}),(0,bh.default)(`design:type`,Function),(0,bh.default)(`design:paramtypes`,[]),(0,bh.default)(`design:returntype`,Promise)],Nh.prototype,`getCoverageTree`,null),(0,Sh.default)([$e({category:Tt.GET_COVERAGE}),(0,bh.default)(`design:type`,Function),(0,bh.default)(`design:paramtypes`,[Array]),(0,bh.default)(`design:returntype`,Promise)],Nh.prototype,`getCoverageForFiles`,null),(0,Sh.default)([$e({category:Tt.GENERATE_TESTS}),(0,bh.default)(`design:type`,Function),(0,bh.default)(`design:paramtypes`,[String,Object]),(0,bh.default)(`design:returntype`,Promise)],Nh.prototype,`generateTests`,null),(0,Sh.default)([$e({category:Tt.GENERATE_TESTS}),(0,bh.default)(`design:type`,Function),(0,bh.default)(`design:paramtypes`,[Array,Object,String,typeof(Mh=h.Fn!==void 0&&h.Fn)==`function`?Mh:Object]),(0,bh.default)(`design:returntype`,Promise)],Nh.prototype,`bulkGenerateTests`,null),(0,Sh.default)([$e({category:Tt.GENERATE_TESTS}),(0,bh.default)(`design:type`,Function),(0,bh.default)(`design:paramtypes`,[String,String]),(0,bh.default)(`design:returntype`,Promise)],Nh.prototype,`getValidationReport`,null),(0,Sh.default)([$e({category:Tt.GET_TESTED_CODE_DATA_SOURCE}),(0,bh.default)(`design:type`,Function),(0,bh.default)(`design:paramtypes`,[String,Object,String]),(0,bh.default)(`design:returntype`,Promise)],Nh.prototype,`getTestedCodeDataSource`,null),(0,Sh.default)([$e({category:Tt.DYNAMIC_PROMPT}),(0,bh.default)(`design:type`,Function),(0,bh.default)(`design:paramtypes`,[String,Object,String]),(0,bh.default)(`design:returntype`,Promise)],Nh.prototype,`runDynamicPrompt`,null),(0,Sh.default)([$e({category:Tt.TEST_VALIDATION}),(0,bh.default)(`design:type`,Function),(0,bh.default)(`design:paramtypes`,[String,String]),(0,bh.default)(`design:returntype`,Promise)],Nh.prototype,`validateTestsByCode`,null),Nh=(0,Sh.default)([(0,_.injectable)(),(0,xh.default)(0,(0,_.inject)(yh)),(0,xh.default)(1,(0,_.inject)(rr)),(0,xh.default)(2,(0,_.inject)(lh)),(0,xh.default)(3,(0,_.inject)(gc)),(0,xh.default)(4,(0,_.inject)(He)),(0,xh.default)(5,(0,_.inject)(ed)),(0,xh.default)(6,(0,_.inject)(jm)),(0,xh.default)(7,(0,_.inject)(_d)),(0,xh.default)(8,(0,_.inject)(Lu)),(0,bh.default)(`design:paramtypes`,[typeof(Ch=yh!==void 0&&yh)==`function`?Ch:Object,typeof(wh=rr!==void 0&&rr)==`function`?wh:Object,typeof(Th=lh!==void 0&&lh)==`function`?Th:Object,typeof(Eh=gc!==void 0&&gc)==`function`?Eh:Object,typeof(Dh=He!==void 0&&He)==`function`?Dh:Object,typeof(Oh=ed!==void 0&&ed)==`function`?Oh:Object,typeof(kh=jm!==void 0&&jm)==`function`?kh:Object,typeof(Ah=_d!==void 0&&_d)==`function`?Ah:Object,typeof(jh=Lu!==void 0&&Lu)==`function`?jh:Object])],Nh),e.AST=Mn,e.AccessModifierType=At,e.AstModuleInfo=An,e.CONCURRENCY=ye,e.COVERAGE_THRESHOLD=ve,e.CalculateCoverageOption=_e,e.DEFAULT_TYPE_KIND=Mt,e.ExportType=kt,e.GenerateTestsOutputType=ge,e.GeneratedTestStructure=he,e.LibraryName=jt,e.RequestSource=ue,Object.defineProperty(e,`TSAgent`,{enumerable:!0,get:function(){return Nh}}),e.TestFileName=me,e.TestFramework=fe,e.TestStructureVariant=de,e.TestSuffix=pe,e.WithTsMorphManager=Yt,e.createTSAgent=(e={})=>(V.bind(He).toDynamicValue(()=>new He(e)).inSingletonScope(),V.get(Nh)),e.findLintConfigPath=wt,e.getUnitTests=un,e.tsMorphManager=Jt}))();const lW={TSAgent:Symbol.for(`TSAgent`),CliOptions:Symbol.for(`CliOptions`),SCMHostService:Symbol.for(`SCMHostService`)};var uW=u(ki());let dW=function(e){return e.PR=`generate-for-pr`,e.COMMIT=`generate-for-commit`,e.PROJECT=`generate-for-project`,e.COVERAGE=`generate-coverage`,e}({});const fW=Object.freeze({status:`aborted`});function pW(e,t,n){function r(n,r){var i;Object.defineProperty(n,`_zod`,{value:n._zod??{},enumerable:!1}),(i=n._zod).traits??(i.traits=new Set),n._zod.traits.add(e),t(n,r);for(let e in o.prototype)e in n||Object.defineProperty(n,e,{value:o.prototype[e].bind(n)});n._zod.constr=o,n._zod.def=r}let i=n?.Parent??Object;class a extends i{}Object.defineProperty(a,`name`,{value:e});function o(e){var t;let i=n?.Parent?new a:this;r(i,e),(t=i._zod).deferred??(t.deferred=[]);for(let e of i._zod.deferred)e();return i}return Object.defineProperty(o,`init`,{value:r}),Object.defineProperty(o,Symbol.hasInstance,{value:t=>n?.Parent&&t instanceof n.Parent?!0:t?._zod?.traits?.has(e)}),Object.defineProperty(o,`name`,{value:e}),o}var mW=class extends Error{constructor(){super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`)}},hW=class extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`),this.name=`ZodEncodeError`}};const gW={};function _W(e){return e&&Object.assign(gW,e),gW}function vW(e){let t=Object.values(e).filter(e=>typeof e==`number`);return Object.entries(e).filter(([e,n])=>t.indexOf(+e)===-1).map(([e,t])=>t)}function yW(e,t){return typeof t==`bigint`?t.toString():t}function bW(e){return{get value(){{let t=e();return Object.defineProperty(this,`value`,{value:t}),t}throw Error(`cached value already set`)}}}function xW(e){return e==null}function SW(e){let t=e.startsWith(`^`)?1:0,n=e.endsWith(`$`)?e.length-1:e.length;return e.slice(t,n)}function CW(e,t){let n=(e.toString().split(`.`)[1]||``).length,r=t.toString(),i=(r.split(`.`)[1]||``).length;if(i===0&&/\d?e-\d?/.test(r)){let e=r.match(/\d?e-(\d?)/);e?.[1]&&(i=Number.parseInt(e[1]))}let a=n>i?n:i;return Number.parseInt(e.toFixed(a).replace(`.`,``))%Number.parseInt(t.toFixed(a).replace(`.`,``))/10**a}const wW=Symbol(`evaluating`);function TW(e,t,n){let r;Object.defineProperty(e,t,{get(){if(r!==wW)return r===void 0&&(r=wW,r=n()),r},set(n){Object.defineProperty(e,t,{value:n})},configurable:!0})}function EW(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}function DW(...e){let t={};for(let n of e){let e=Object.getOwnPropertyDescriptors(n);Object.assign(t,e)}return Object.defineProperties({},t)}function OW(e){return JSON.stringify(e)}const kW=`captureStackTrace`in Error?Error.captureStackTrace:(...e)=>{};function AW(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}const jW=bW(()=>{if(typeof navigator<`u`&&navigator?.userAgent?.includes(`Cloudflare`))return!1;try{return Function(``),!0}catch{return!1}});function MW(e){if(AW(e)===!1)return!1;let t=e.constructor;if(t===void 0)return!0;let n=t.prototype;return!(AW(n)===!1||Object.prototype.hasOwnProperty.call(n,`isPrototypeOf`)===!1)}function NW(e){return MW(e)?{...e}:Array.isArray(e)?[...e]:e}const PW=new Set([`string`,`number`,`symbol`]);function FW(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}function IW(e,t,n){let r=new e._zod.constr(t??e._zod.def);return(!t||n?.parent)&&(r._zod.parent=e),r}function LW(e){let t=e;if(!t)return{};if(typeof t==`string`)return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,typeof t.error==`string`?{...t,error:()=>t.error}:t}function RW(e){return Object.keys(e).filter(t=>e[t]._zod.optin===`optional`&&e[t]._zod.optout===`optional`)}const Iee={safeint:[-(2**53-1),2**53-1],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]};function zW(e,t){let n=e._zod.def;return IW(e,DW(e._zod.def,{get shape(){let e={};for(let r in t){if(!(r in n.shape))throw Error(`Unrecognized key: "${r}"`);t[r]&&(e[r]=n.shape[r])}return EW(this,`shape`,e),e},checks:[]}))}function BW(e,t){let n=e._zod.def;return IW(e,DW(e._zod.def,{get shape(){let r={...e._zod.def.shape};for(let e in t){if(!(e in n.shape))throw Error(`Unrecognized key: "${e}"`);t[e]&&delete r[e]}return EW(this,`shape`,r),r},checks:[]}))}function VW(e,t){if(!MW(t))throw Error(`Invalid input to extend: expected a plain object`);let n=e._zod.def.checks;if(n&&n.length>0)throw Error("Object schemas containing refinements cannot be extended. Use `.safeExtend()` instead.");return IW(e,DW(e._zod.def,{get shape(){let n={...e._zod.def.shape,...t};return EW(this,`shape`,n),n},checks:[]}))}function HW(e,t){if(!MW(t))throw Error(`Invalid input to safeExtend: expected a plain object`);return IW(e,{...e._zod.def,get shape(){let n={...e._zod.def.shape,...t};return EW(this,`shape`,n),n},checks:e._zod.def.checks})}function UW(e,t){return IW(e,DW(e._zod.def,{get shape(){let n={...e._zod.def.shape,...t._zod.def.shape};return EW(this,`shape`,n),n},get catchall(){return t._zod.def.catchall},checks:[]}))}function WW(e,t,n){return IW(t,DW(t._zod.def,{get shape(){let r=t._zod.def.shape,i={...r};if(n)for(let t in n){if(!(t in r))throw Error(`Unrecognized key: "${t}"`);n[t]&&(i[t]=e?new e({type:`optional`,innerType:r[t]}):r[t])}else for(let t in r)i[t]=e?new e({type:`optional`,innerType:r[t]}):r[t];return EW(this,`shape`,i),i},checks:[]}))}function GW(e,t,n){return IW(t,DW(t._zod.def,{get shape(){let r=t._zod.def.shape,i={...r};if(n)for(let t in n){if(!(t in i))throw Error(`Unrecognized key: "${t}"`);n[t]&&(i[t]=new e({type:`nonoptional`,innerType:r[t]}))}else for(let t in r)i[t]=new e({type:`nonoptional`,innerType:r[t]});return EW(this,`shape`,i),i},checks:[]}))}function KW(e,t=0){if(e.aborted===!0)return!0;for(let n=t;n<e.issues.length;n++)if(e.issues[n]?.continue!==!0)return!0;return!1}function qW(e,t){return t.map(t=>{var n;return(n=t).path??(n.path=[]),t.path.unshift(e),t})}function JW(e){return typeof e==`string`?e:e?.message}function YW(e,t,n){let r={...e,path:e.path??[]};return e.message||(r.message=JW(e.inst?._zod.def?.error?.(e))??JW(t?.error?.(e))??JW(n.customError?.(e))??JW(n.localeError?.(e))??`Invalid input`),delete r.inst,delete r.continue,t?.reportInput||delete r.input,r}function XW(e){return Array.isArray(e)?`array`:typeof e==`string`?`string`:`unknown`}function ZW(...e){let[t,n,r]=e;return typeof t==`string`?{message:t,code:`custom`,input:n,inst:r}:{...t}}const QW=(e,t)=>{e.name=`$ZodError`,Object.defineProperty(e,`_zod`,{value:e._zod,enumerable:!1}),Object.defineProperty(e,`issues`,{value:t,enumerable:!1}),e.message=JSON.stringify(t,yW,2),Object.defineProperty(e,`toString`,{value:()=>e.message,enumerable:!1})},$W=pW(`$ZodError`,QW),eG=pW(`$ZodError`,QW,{Parent:Error});function tG(e,t=e=>e.message){let n={},r=[];for(let i of e.issues)i.path.length>0?(n[i.path[0]]=n[i.path[0]]||[],n[i.path[0]].push(t(i))):r.push(t(i));return{formErrors:r,fieldErrors:n}}function nG(e,t){let n=t||function(e){return e.message},r={_errors:[]},i=e=>{for(let t of e.issues)if(t.code===`invalid_union`&&t.errors.length)t.errors.map(e=>i({issues:e}));else if(t.code===`invalid_key`)i({issues:t.issues});else if(t.code===`invalid_element`)i({issues:t.issues});else if(t.path.length===0)r._errors.push(n(t));else{let e=r,i=0;for(;i<t.path.length;){let r=t.path[i];i===t.path.length-1?(e[r]=e[r]||{_errors:[]},e[r]._errors.push(n(t))):e[r]=e[r]||{_errors:[]},e=e[r],i++}}};return i(e),r}const rG=e=>(t,n,r,i)=>{let a=r?Object.assign(r,{async:!1}):{async:!1},o=t._zod.run({value:n,issues:[]},a);if(o instanceof Promise)throw new mW;if(o.issues.length){let t=new(i?.Err??e)(o.issues.map(e=>YW(e,a,_W())));throw kW(t,i?.callee),t}return o.value},iG=e=>async(t,n,r,i)=>{let a=r?Object.assign(r,{async:!0}):{async:!0},o=t._zod.run({value:n,issues:[]},a);if(o instanceof Promise&&(o=await o),o.issues.length){let t=new(i?.Err??e)(o.issues.map(e=>YW(e,a,_W())));throw kW(t,i?.callee),t}return o.value},aG=e=>(t,n,r)=>{let i=r?{...r,async:!1}:{async:!1},a=t._zod.run({value:n,issues:[]},i);if(a instanceof Promise)throw new mW;return a.issues.length?{success:!1,error:new(e??$W)(a.issues.map(e=>YW(e,i,_W())))}:{success:!0,data:a.value}},oG=aG(eG),sG=e=>async(t,n,r)=>{let i=r?Object.assign(r,{async:!0}):{async:!0},a=t._zod.run({value:n,issues:[]},i);return a instanceof Promise&&(a=await a),a.issues.length?{success:!1,error:new e(a.issues.map(e=>YW(e,i,_W())))}:{success:!0,data:a.value}},cG=sG(eG),lG=e=>(t,n,r)=>{let i=r?Object.assign(r,{direction:`backward`}):{direction:`backward`};return rG(e)(t,n,i)},uG=e=>(t,n,r)=>rG(e)(t,n,r),dG=e=>async(t,n,r)=>{let i=r?Object.assign(r,{direction:`backward`}):{direction:`backward`};return iG(e)(t,n,i)},Lee=e=>async(t,n,r)=>iG(e)(t,n,r),fG=e=>(t,n,r)=>{let i=r?Object.assign(r,{direction:`backward`}):{direction:`backward`};return aG(e)(t,n,i)},pG=e=>(t,n,r)=>aG(e)(t,n,r),mG=e=>async(t,n,r)=>{let i=r?Object.assign(r,{direction:`backward`}):{direction:`backward`};return sG(e)(t,n,i)},hG=e=>async(t,n,r)=>sG(e)(t,n,r),gG=/^[cC][^\s-]{8,}$/,_G=/^[0-9a-z]+$/,vG=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,yG=/^[0-9a-vA-V]{20}$/,bG=/^[A-Za-z0-9]{27}$/,xG=/^[a-zA-Z0-9_-]{21}$/,SG=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,Ree=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,CG=e=>e?RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/,wG=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;function TG(){return RegExp(`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`,`u`)}const zee=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,Bee=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/,EG=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,DG=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,OG=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,kG=/^[A-Za-z0-9_-]*$/,Vee=/^(?=.{1,253}\.?$)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[-0-9a-zA-Z]{0,61}[0-9a-zA-Z])?)*\.?$/,AG=/^\+(?:[0-9]){6,14}[0-9]$/,jG=`(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))`,MG=RegExp(`^${jG}$`);function NG(e){let t=`(?:[01]\\d|2[0-3]):[0-5]\\d`;return typeof e.precision==`number`?e.precision===-1?`${t}`:e.precision===0?`${t}:[0-5]\\d`:`${t}:[0-5]\\d\\.\\d{${e.precision}}`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}function PG(e){return RegExp(`^${NG(e)}$`)}function FG(e){let t=NG({precision:e.precision}),n=[`Z`];e.local&&n.push(``),e.offset&&n.push(`([+-](?:[01]\\d|2[0-3]):[0-5]\\d)`);let r=`${t}(?:${n.join(`|`)})`;return RegExp(`^${jG}T(?:${r})$`)}const IG=e=>{let t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??``}}`:`[\\s\\S]*`;return RegExp(`^${t}$`)},LG=/^-?\d+$/,RG=/^-?\d+(?:\.\d+)?/,zG=/^[^A-Z]*$/,BG=/^[^a-z]*$/,VG=pW(`$ZodCheck`,(e,t)=>{var n;e._zod??={},e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),HG={number:`number`,bigint:`bigint`,object:`date`},UG=pW(`$ZodCheckLessThan`,(e,t)=>{VG.init(e,t);let n=HG[typeof t.value];e._zod.onattach.push(e=>{let n=e._zod.bag,r=(t.inclusive?n.maximum:n.exclusiveMaximum)??1/0;t.value<r&&(t.inclusive?n.maximum=t.value:n.exclusiveMaximum=t.value)}),e._zod.check=r=>{(t.inclusive?r.value<=t.value:r.value<t.value)||r.issues.push({origin:n,code:`too_big`,maximum:t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),WG=pW(`$ZodCheckGreaterThan`,(e,t)=>{VG.init(e,t);let n=HG[typeof t.value];e._zod.onattach.push(e=>{let n=e._zod.bag,r=(t.inclusive?n.minimum:n.exclusiveMinimum)??-1/0;t.value>r&&(t.inclusive?n.minimum=t.value:n.exclusiveMinimum=t.value)}),e._zod.check=r=>{(t.inclusive?r.value>=t.value:r.value>t.value)||r.issues.push({origin:n,code:`too_small`,minimum:t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),GG=pW(`$ZodCheckMultipleOf`,(e,t)=>{VG.init(e,t),e._zod.onattach.push(e=>{var n;(n=e._zod.bag).multipleOf??(n.multipleOf=t.value)}),e._zod.check=n=>{if(typeof n.value!=typeof t.value)throw Error(`Cannot mix number and bigint in multiple_of check.`);(typeof n.value==`bigint`?n.value%t.value===BigInt(0):CW(n.value,t.value)===0)||n.issues.push({origin:typeof n.value,code:`not_multiple_of`,divisor:t.value,input:n.value,inst:e,continue:!t.abort})}}),KG=pW(`$ZodCheckNumberFormat`,(e,t)=>{VG.init(e,t),t.format=t.format||`float64`;let n=t.format?.includes(`int`),r=n?`int`:`number`,[i,a]=Iee[t.format];e._zod.onattach.push(e=>{let r=e._zod.bag;r.format=t.format,r.minimum=i,r.maximum=a,n&&(r.pattern=LG)}),e._zod.check=o=>{let s=o.value;if(n){if(!Number.isInteger(s)){o.issues.push({expected:r,format:t.format,code:`invalid_type`,continue:!1,input:s,inst:e});return}if(!Number.isSafeInteger(s)){s>0?o.issues.push({input:s,code:`too_big`,maximum:2**53-1,note:`Integers must be within the safe integer range.`,inst:e,origin:r,continue:!t.abort}):o.issues.push({input:s,code:`too_small`,minimum:-(2**53-1),note:`Integers must be within the safe integer range.`,inst:e,origin:r,continue:!t.abort});return}}s<i&&o.issues.push({origin:`number`,input:s,code:`too_small`,minimum:i,inclusive:!0,inst:e,continue:!t.abort}),s>a&&o.issues.push({origin:`number`,input:s,code:`too_big`,maximum:a,inst:e})}}),qG=pW(`$ZodCheckMaxLength`,(e,t)=>{var n;VG.init(e,t),(n=e._zod.def).when??(n.when=e=>{let t=e.value;return!xW(t)&&t.length!==void 0}),e._zod.onattach.push(e=>{let n=e._zod.bag.maximum??1/0;t.maximum<n&&(e._zod.bag.maximum=t.maximum)}),e._zod.check=n=>{let r=n.value;if(r.length<=t.maximum)return;let i=XW(r);n.issues.push({origin:i,code:`too_big`,maximum:t.maximum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),JG=pW(`$ZodCheckMinLength`,(e,t)=>{var n;VG.init(e,t),(n=e._zod.def).when??(n.when=e=>{let t=e.value;return!xW(t)&&t.length!==void 0}),e._zod.onattach.push(e=>{let n=e._zod.bag.minimum??-1/0;t.minimum>n&&(e._zod.bag.minimum=t.minimum)}),e._zod.check=n=>{let r=n.value;if(r.length>=t.minimum)return;let i=XW(r);n.issues.push({origin:i,code:`too_small`,minimum:t.minimum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),YG=pW(`$ZodCheckLengthEquals`,(e,t)=>{var n;VG.init(e,t),(n=e._zod.def).when??(n.when=e=>{let t=e.value;return!xW(t)&&t.length!==void 0}),e._zod.onattach.push(e=>{let n=e._zod.bag;n.minimum=t.length,n.maximum=t.length,n.length=t.length}),e._zod.check=n=>{let r=n.value,i=r.length;if(i===t.length)return;let a=XW(r),o=i>t.length;n.issues.push({origin:a,...o?{code:`too_big`,maximum:t.length}:{code:`too_small`,minimum:t.length},inclusive:!0,exact:!0,input:n.value,inst:e,continue:!t.abort})}}),XG=pW(`$ZodCheckStringFormat`,(e,t)=>{var n,r;VG.init(e,t),e._zod.onattach.push(e=>{let n=e._zod.bag;n.format=t.format,t.pattern&&(n.patterns??=new Set,n.patterns.add(t.pattern))}),t.pattern?(n=e._zod).check??(n.check=n=>{t.pattern.lastIndex=0,!t.pattern.test(n.value)&&n.issues.push({origin:`string`,code:`invalid_format`,format:t.format,input:n.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(r=e._zod).check??(r.check=()=>{})}),ZG=pW(`$ZodCheckRegex`,(e,t)=>{XG.init(e,t),e._zod.check=n=>{t.pattern.lastIndex=0,!t.pattern.test(n.value)&&n.issues.push({origin:`string`,code:`invalid_format`,format:`regex`,input:n.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),QG=pW(`$ZodCheckLowerCase`,(e,t)=>{t.pattern??=zG,XG.init(e,t)}),$G=pW(`$ZodCheckUpperCase`,(e,t)=>{t.pattern??=BG,XG.init(e,t)}),eK=pW(`$ZodCheckIncludes`,(e,t)=>{VG.init(e,t);let n=FW(t.includes),r=new RegExp(typeof t.position==`number`?`^.{${t.position}}${n}`:n);t.pattern=r,e._zod.onattach.push(e=>{let t=e._zod.bag;t.patterns??=new Set,t.patterns.add(r)}),e._zod.check=n=>{n.value.includes(t.includes,t.position)||n.issues.push({origin:`string`,code:`invalid_format`,format:`includes`,includes:t.includes,input:n.value,inst:e,continue:!t.abort})}}),tK=pW(`$ZodCheckStartsWith`,(e,t)=>{VG.init(e,t);let n=RegExp(`^${FW(t.prefix)}.*`);t.pattern??=n,e._zod.onattach.push(e=>{let t=e._zod.bag;t.patterns??=new Set,t.patterns.add(n)}),e._zod.check=n=>{n.value.startsWith(t.prefix)||n.issues.push({origin:`string`,code:`invalid_format`,format:`starts_with`,prefix:t.prefix,input:n.value,inst:e,continue:!t.abort})}}),nK=pW(`$ZodCheckEndsWith`,(e,t)=>{VG.init(e,t);let n=RegExp(`.*${FW(t.suffix)}$`);t.pattern??=n,e._zod.onattach.push(e=>{let t=e._zod.bag;t.patterns??=new Set,t.patterns.add(n)}),e._zod.check=n=>{n.value.endsWith(t.suffix)||n.issues.push({origin:`string`,code:`invalid_format`,format:`ends_with`,suffix:t.suffix,input:n.value,inst:e,continue:!t.abort})}}),rK=pW(`$ZodCheckOverwrite`,(e,t)=>{VG.init(e,t),e._zod.check=e=>{e.value=t.tx(e.value)}});var iK=class{constructor(e=[]){this.content=[],this.indent=0,this&&(this.args=e)}indented(e){this.indent+=1,e(this),--this.indent}write(e){if(typeof e==`function`){e(this,{execution:`sync`}),e(this,{execution:`async`});return}let t=e.split(`
|
|
32360
32360
|
`).filter(e=>e),n=Math.min(...t.map(e=>e.length-e.trimStart().length)),r=t.map(e=>e.slice(n)).map(e=>` `.repeat(this.indent*2)+e);for(let e of r)this.content.push(e)}compile(){let e=Function,t=this?.args,n=[...(this?.content??[``]).map(e=>` ${e}`)];return new e(...t,n.join(`
|
|
32361
32361
|
`))}};const aK={major:4,minor:1,patch:11},oK=pW(`$ZodType`,(e,t)=>{var n;e??={},e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=aK;let r=[...e._zod.def.checks??[]];e._zod.traits.has(`$ZodCheck`)&&r.unshift(e);for(let t of r)for(let n of t._zod.onattach)n(e);if(r.length===0)(n=e._zod).deferred??(n.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{let t=(e,t,n)=>{let r=KW(e),i;for(let a of t){if(a._zod.def.when){if(!a._zod.def.when(e))continue}else if(r)continue;let t=e.issues.length,o=a._zod.check(e);if(o instanceof Promise&&n?.async===!1)throw new mW;if(i||o instanceof Promise)i=(i??Promise.resolve()).then(async()=>{await o,e.issues.length!==t&&(r||=KW(e,t))});else{if(e.issues.length===t)continue;r||=KW(e,t)}}return i?i.then(()=>e):e},n=(n,i,a)=>{if(KW(n))return n.aborted=!0,n;let o=t(i,r,a);if(o instanceof Promise){if(a.async===!1)throw new mW;return o.then(t=>e._zod.parse(t,a))}return e._zod.parse(o,a)};e._zod.run=(i,a)=>{if(a.skipChecks)return e._zod.parse(i,a);if(a.direction===`backward`){let t=e._zod.parse({value:i.value,issues:[]},{...a,skipChecks:!0});return t instanceof Promise?t.then(e=>n(e,i,a)):n(t,i,a)}let o=e._zod.parse(i,a);if(o instanceof Promise){if(a.async===!1)throw new mW;return o.then(e=>t(e,r,a))}return t(o,r,a)}}e[`~standard`]={validate:t=>{try{let n=oG(e,t);return n.success?{value:n.data}:{issues:n.error?.issues}}catch{return cG(e,t).then(e=>e.success?{value:e.data}:{issues:e.error?.issues})}},vendor:`zod`,version:1}}),sK=pW(`$ZodString`,(e,t)=>{oK.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??IG(e._zod.bag),e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=String(n.value)}catch{}return typeof n.value==`string`||n.issues.push({expected:`string`,code:`invalid_type`,input:n.value,inst:e}),n}}),cK=pW(`$ZodStringFormat`,(e,t)=>{XG.init(e,t),sK.init(e,t)}),lK=pW(`$ZodGUID`,(e,t)=>{t.pattern??=Ree,cK.init(e,t)}),uK=pW(`$ZodUUID`,(e,t)=>{if(t.version){let e={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(e===void 0)throw Error(`Invalid UUID version: "${t.version}"`);t.pattern??=CG(e)}else t.pattern??=CG();cK.init(e,t)}),dK=pW(`$ZodEmail`,(e,t)=>{t.pattern??=wG,cK.init(e,t)}),fK=pW(`$ZodURL`,(e,t)=>{cK.init(e,t),e._zod.check=n=>{try{let r=n.value.trim(),i=new URL(r);t.hostname&&(t.hostname.lastIndex=0,t.hostname.test(i.hostname)||n.issues.push({code:`invalid_format`,format:`url`,note:`Invalid hostname`,pattern:Vee.source,input:n.value,inst:e,continue:!t.abort})),t.protocol&&(t.protocol.lastIndex=0,t.protocol.test(i.protocol.endsWith(`:`)?i.protocol.slice(0,-1):i.protocol)||n.issues.push({code:`invalid_format`,format:`url`,note:`Invalid protocol`,pattern:t.protocol.source,input:n.value,inst:e,continue:!t.abort})),t.normalize?n.value=i.href:n.value=r;return}catch{n.issues.push({code:`invalid_format`,format:`url`,input:n.value,inst:e,continue:!t.abort})}}}),pK=pW(`$ZodEmoji`,(e,t)=>{t.pattern??=TG(),cK.init(e,t)}),mK=pW(`$ZodNanoID`,(e,t)=>{t.pattern??=xG,cK.init(e,t)}),hK=pW(`$ZodCUID`,(e,t)=>{t.pattern??=gG,cK.init(e,t)}),Hee=pW(`$ZodCUID2`,(e,t)=>{t.pattern??=_G,cK.init(e,t)}),gK=pW(`$ZodULID`,(e,t)=>{t.pattern??=vG,cK.init(e,t)}),_K=pW(`$ZodXID`,(e,t)=>{t.pattern??=yG,cK.init(e,t)}),vK=pW(`$ZodKSUID`,(e,t)=>{t.pattern??=bG,cK.init(e,t)}),Uee=pW(`$ZodISODateTime`,(e,t)=>{t.pattern??=FG(t),cK.init(e,t)}),yK=pW(`$ZodISODate`,(e,t)=>{t.pattern??=MG,cK.init(e,t)}),Wee=pW(`$ZodISOTime`,(e,t)=>{t.pattern??=PG(t),cK.init(e,t)}),bK=pW(`$ZodISODuration`,(e,t)=>{t.pattern??=SG,cK.init(e,t)}),xK=pW(`$ZodIPv4`,(e,t)=>{t.pattern??=zee,cK.init(e,t),e._zod.onattach.push(e=>{let t=e._zod.bag;t.format=`ipv4`})}),SK=pW(`$ZodIPv6`,(e,t)=>{t.pattern??=Bee,cK.init(e,t),e._zod.onattach.push(e=>{let t=e._zod.bag;t.format=`ipv6`}),e._zod.check=n=>{try{new URL(`http://[${n.value}]`)}catch{n.issues.push({code:`invalid_format`,format:`ipv6`,input:n.value,inst:e,continue:!t.abort})}}}),CK=pW(`$ZodCIDRv4`,(e,t)=>{t.pattern??=EG,cK.init(e,t)}),wK=pW(`$ZodCIDRv6`,(e,t)=>{t.pattern??=DG,cK.init(e,t),e._zod.check=n=>{let r=n.value.split(`/`);try{if(r.length!==2)throw Error();let[e,t]=r;if(!t)throw Error();let n=Number(t);if(`${n}`!==t||n<0||n>128)throw Error();new URL(`http://[${e}]`)}catch{n.issues.push({code:`invalid_format`,format:`cidrv6`,input:n.value,inst:e,continue:!t.abort})}}});function TK(e){if(e===``)return!0;if(e.length%4!=0)return!1;try{return atob(e),!0}catch{return!1}}const EK=pW(`$ZodBase64`,(e,t)=>{t.pattern??=OG,cK.init(e,t),e._zod.onattach.push(e=>{e._zod.bag.contentEncoding=`base64`}),e._zod.check=n=>{TK(n.value)||n.issues.push({code:`invalid_format`,format:`base64`,input:n.value,inst:e,continue:!t.abort})}});function DK(e){if(!kG.test(e))return!1;let t=e.replace(/[-_]/g,e=>e===`-`?`+`:`/`);return TK(t.padEnd(Math.ceil(t.length/4)*4,`=`))}const OK=pW(`$ZodBase64URL`,(e,t)=>{t.pattern??=kG,cK.init(e,t),e._zod.onattach.push(e=>{e._zod.bag.contentEncoding=`base64url`}),e._zod.check=n=>{DK(n.value)||n.issues.push({code:`invalid_format`,format:`base64url`,input:n.value,inst:e,continue:!t.abort})}}),kK=pW(`$ZodE164`,(e,t)=>{t.pattern??=AG,cK.init(e,t)});function AK(e,t=null){try{let n=e.split(`.`);if(n.length!==3)return!1;let[r]=n;if(!r)return!1;let i=JSON.parse(atob(r));return!(`typ`in i&&i?.typ!==`JWT`||!i.alg||t&&(!(`alg`in i)||i.alg!==t))}catch{return!1}}const jK=pW(`$ZodJWT`,(e,t)=>{cK.init(e,t),e._zod.check=n=>{AK(n.value,t.alg)||n.issues.push({code:`invalid_format`,format:`jwt`,input:n.value,inst:e,continue:!t.abort})}}),MK=pW(`$ZodNumber`,(e,t)=>{oK.init(e,t),e._zod.pattern=e._zod.bag.pattern??RG,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=Number(n.value)}catch{}let i=n.value;if(typeof i==`number`&&!Number.isNaN(i)&&Number.isFinite(i))return n;let a=typeof i==`number`?Number.isNaN(i)?`NaN`:Number.isFinite(i)?void 0:`Infinity`:void 0;return n.issues.push({expected:`number`,code:`invalid_type`,input:i,inst:e,...a?{received:a}:{}}),n}}),NK=pW(`$ZodNumber`,(e,t)=>{KG.init(e,t),MK.init(e,t)}),PK=pW(`$ZodUnknown`,(e,t)=>{oK.init(e,t),e._zod.parse=e=>e}),FK=pW(`$ZodNever`,(e,t)=>{oK.init(e,t),e._zod.parse=(t,n)=>(t.issues.push({expected:`never`,code:`invalid_type`,input:t.value,inst:e}),t)});function IK(e,t,n){e.issues.length&&t.issues.push(...qW(n,e.issues)),t.value[n]=e.value}const LK=pW(`$ZodArray`,(e,t)=>{oK.init(e,t),e._zod.parse=(n,r)=>{let i=n.value;if(!Array.isArray(i))return n.issues.push({expected:`array`,code:`invalid_type`,input:i,inst:e}),n;n.value=Array(i.length);let a=[];for(let e=0;e<i.length;e++){let o=i[e],s=t.element._zod.run({value:o,issues:[]},r);s instanceof Promise?a.push(s.then(t=>IK(t,n,e))):IK(s,n,e)}return a.length?Promise.all(a).then(()=>n):n}});function RK(e,t,n,r){e.issues.length&&t.issues.push(...qW(n,e.issues)),e.value===void 0?n in r&&(t.value[n]=void 0):t.value[n]=e.value}function zK(e){let t=Object.keys(e.shape);for(let n of t)if(!e.shape?.[n]?._zod?.traits?.has(`$ZodType`))throw Error(`Invalid element at key "${n}": expected a Zod schema`);let n=RW(e.shape);return{...e,keys:t,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(n)}}function BK(e,t,n,r,i,a){let o=[],s=i.keySet,c=i.catchall._zod,l=c.def.type;for(let i of Object.keys(t)){if(s.has(i))continue;if(l===`never`){o.push(i);continue}let a=c.run({value:t[i],issues:[]},r);a instanceof Promise?e.push(a.then(e=>RK(e,n,i,t))):RK(a,n,i,t)}return o.length&&n.issues.push({code:`unrecognized_keys`,keys:o,input:t,inst:a}),e.length?Promise.all(e).then(()=>n):n}const VK=pW(`$ZodObject`,(e,t)=>{if(oK.init(e,t),!Object.getOwnPropertyDescriptor(t,`shape`)?.get){let e=t.shape;Object.defineProperty(t,`shape`,{get:()=>{let n={...e};return Object.defineProperty(t,`shape`,{value:n}),n}})}let n=bW(()=>zK(t));TW(e._zod,`propValues`,()=>{let e=t.shape,n={};for(let t in e){let r=e[t]._zod;if(r.values){n[t]??(n[t]=new Set);for(let e of r.values)n[t].add(e)}}return n});let r=AW,i=t.catchall,a;e._zod.parse=(t,o)=>{a??=n.value;let s=t.value;if(!r(s))return t.issues.push({expected:`object`,code:`invalid_type`,input:s,inst:e}),t;t.value={};let c=[],l=a.shape;for(let e of a.keys){let n=l[e]._zod.run({value:s[e],issues:[]},o);n instanceof Promise?c.push(n.then(n=>RK(n,t,e,s))):RK(n,t,e,s)}return i?BK(c,s,t,o,n.value,e):c.length?Promise.all(c).then(()=>t):t}}),HK=pW(`$ZodObjectJIT`,(e,t)=>{VK.init(e,t);let n=e._zod.parse,r=bW(()=>zK(t)),i=e=>{let t=new iK([`shape`,`payload`,`ctx`]),n=r.value,i=e=>{let t=OW(e);return`shape[${t}]._zod.run({ value: input[${t}], issues: [] }, ctx)`};t.write(`const input = payload.value;`);let a=Object.create(null),o=0;for(let e of n.keys)a[e]=`key_${o++}`;t.write(`const newResult = {};`);for(let e of n.keys){let n=a[e],r=OW(e);t.write(`const ${n} = ${i(e)};`),t.write(`
|
|
32362
32362
|
if (${n}.issues.length) {
|
|
@@ -32391,7 +32391,8 @@ var n=require(`buffer`),r=n.Buffer;function i(e,t){for(var n in e)t[n]=e[n]}r.fr
|
|
|
32391
32391
|
`))}_onEvent(e,t){function n(n){e===`error`&&!this.transports.includes(t)&&this.add(t),this.emit(e,n,t)}t[`__winston`+e]||(t[`__winston`+e]=n.bind(this),t.on(e,t[`__winston`+e]))}_addDefaultMeta(e){this.defaultMeta&&Object.assign(e,this.defaultMeta)}};function g(e,t){let n=e[t];return!n&&n!==0?null:n}Object.defineProperty(h.prototype,`transports`,{configurable:!1,enumerable:!0,get(){let{pipes:e}=this._readableState;return Array.isArray(e)?e:[e].filter(Boolean)}}),t.exports=h})),XZ=s(((e,t)=>{let{LEVEL:n}=pX(),r=RZ(),i=YZ(),a=jZ()(`winston:create-logger`);function o(e){return`is`+e.charAt(0).toUpperCase()+e.slice(1)+`Enabled`}t.exports=function(e={}){e.levels=e.levels||r.npm.levels;class t extends i{constructor(e){super(e)}}let s=new t(e);return Object.keys(e.levels).forEach(function(e){if(a(`Define prototype method for "%s"`,e),e===`log`){console.warn(`Level "log" not defined: conflicts with the method "log". Use a different level name.`);return}t.prototype[e]=function(...t){let r=this||s;if(t.length===1){let[i]=t,a=i&&i.message&&i||{message:i};return a.level=a[n]=e,r._addDefaultMeta(a),r.write(a),this||s}return t.length===0?(r.log(e,``),r):r.log(e,...t)},t.prototype[o(e)]=function(){return(this||s).isLevelEnabled(e)}}),s}})),ZZ=s(((e,t)=>{let n=XZ();t.exports=class{constructor(e={}){this.loggers=new Map,this.options=e}add(e,t){if(!this.loggers.has(e)){t=Object.assign({},t||this.options);let r=t.transports||this.options.transports;r?t.transports=Array.isArray(r)?r.slice():[r]:t.transports=[];let i=n(t);i.on(`close`,()=>this._delete(e)),this.loggers.set(e,i)}return this.loggers.get(e)}get(e,t){return this.add(e,t)}has(e){return!!this.loggers.has(e)}close(e){if(e)return this._removeLogger(e);this.loggers.forEach((e,t)=>this._removeLogger(t))}_removeLogger(e){this.loggers.has(e)&&(this.loggers.get(e).close(),this._delete(e))}_delete(e){this.loggers.delete(e)}}})),QZ=u(s((e=>{let t=MX(),{warn:n}=NX();e.version=PX().version,e.transports=LZ(),e.config=RZ(),e.addColors=t.levels,e.format=t.format,e.createLogger=XZ(),e.Logger=YZ(),e.ExceptionHandler=KZ(),e.RejectionHandler=JZ(),e.Container=ZZ(),e.Transport=XX(),e.loggers=new e.Container;let r=e.createLogger();Object.keys(e.config.npm.levels).concat([`log`,`query`,`stream`,`add`,`remove`,`clear`,`profile`,`startTimer`,`handleExceptions`,`unhandleExceptions`,`handleRejections`,`unhandleRejections`,`configure`,`child`]).forEach(t=>e[t]=(...e)=>r[t](...e)),Object.defineProperty(e,`level`,{get(){return r.level},set(e){r.level=e}}),Object.defineProperty(e,`exceptions`,{get(){return r.exceptions}}),Object.defineProperty(e,`rejections`,{get(){return r.rejections}}),[`exitOnError`].forEach(t=>{Object.defineProperty(e,t,{get(){return r[t]},set(e){r[t]=e}})}),Object.defineProperty(e,`default`,{get(){return{exceptionHandlers:r.exceptionHandlers,rejectionHandlers:r.rejectionHandlers,transports:r.transports}}}),n.deprecated(e,`setLevels`),n.forFunctions(e,`useFormat`,[`cli`]),n.forProperties(e,`useFormat`,[`padLevels`,`stripColors`]),n.forFunctions(e,`deprecated`,[`addRewriter`,`addFilter`,`clone`,`extend`]),n.forProperties(e,`deprecated`,[`emitErrs`,`levelLength`])}))());let $Z=function(e){return e.ERROR=`error`,e.WARN=`warn`,e.INFO=`info`,e.VERBOSE=`verbose`,e.DEBUG=`debug`,e}({});const eQ=$Z.INFO,tQ=$Z.VERBOSE,nQ=$Z.DEBUG;$Z.ERROR,$Z.WARN,$Z.INFO,$Z.VERBOSE,$Z.DEBUG;function rQ(e,t){if(typeof Reflect==`object`&&typeof Reflect.metadata==`function`)return Reflect.metadata(e,t)}function iQ(e,t){return function(n,r){t(n,r,e)}}function aQ(e,t,n,r){var i=arguments.length,a=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r,o;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)a=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(o=e[s])&&(a=(i<3?o(a):i>3?o(t,n,a):o(t,n))||a);return i>3&&a&&Object.defineProperty(t,n,a),a}function oQ(...e){return e.map(e=>typeof e==`object`&&e?(0,S.inspect)(e,{depth:4,breakLength:80}):String(e)).join(` `)}let sQ=class{logger;isDebugMode;constructor(e){this.isDebugMode=String(e?.debug)===`true`,this.logger=QZ.createLogger({level:this.getLogLevel(e),transports:[new QZ.transports.Console({format:QZ.format.printf(({message:e})=>String(e??``))})]})}error(...e){this.logger.error(oQ(...e))}warn(...e){this.logger.warn(oQ(...e))}info(...e){this.logger.info(oQ(...e))}verbose(...e){this.logger.verbose(oQ(...e))}debug(...e){this.logger.debug(oQ(...e))}getLogLevel(e){return String(e?.debug)===`true`?nQ:String(e?.verbose)===`true`?tQ:eQ}};sQ=aQ([et(),iQ(0,Ze(lW.CliOptions)),iQ(0,ut()),rQ(`design:paramtypes`,[Object])],sQ);let cQ=class{config;constructor(e,t){this.logger=t,this.config=this.initializeConfig(e)}getConfig(){return this.config}maskedConfig(){let e=this.config.gitTopLevel;return this.config.command===dW.PROJECT?{...this.config,secretToken:`xxxx`,token:`xxxx`,...(0,B.isDefined)(e)&&{rootPath:uW.default.relative(e,this.config.rootPath)},...(0,B.isDefined)(this.config.targetDirectory)&&{targetDirectory:uW.default.normalize(this.config.targetDirectory)}}:{...this.config,secretToken:`xxxx`,token:`xxxx`,...(0,B.isDefined)(e)&&{rootPath:uW.default.relative(e,this.config.rootPath)}}}isDev(){return process.env.IS_DEV===`true`}getConfigValue(e){return this.config[e]}updateConfigValue(e,t){this.config[e]=t}getConfigValueOrThrow(e,t){let n=this.config[e];if(!(0,B.isDefined)(n)){let n=t??`Configuration key ${e} is required but not configured`;throw Error(n)}return n}initializeConfig(e){let t=this.getRawConfigFromInputs(e),n=ZY.parse(t);return this.capMaxTestables(n),this.logger.verbose(`Configuration validated successfully`),this.logger.debug(`Configuration: ${JSON.stringify(n,null,2)}`),n}capMaxTestables(e){e.command===dW.COVERAGE||e.maxTestables<=10||(this.logger.warn(`Capping maxTestables from ${e.maxTestables} to 10 (maximum allowed).`),e.maxTestables=10)}getRawConfigFromInputs(e){if(!e)throw Error(`CLI options are required but not provided`);let t={command:e.command,testStructure:e.testStructure,testFramework:e.testFramework,testSuffix:e.testSuffix,testFileName:e.testFileNaming,requestSource:cW.RequestSource.CLI,concurrency:e.maxConcurrency,backendURL:e.baseHost,secretToken:e.apiKey,autoCommit:e.autoCommit,token:e.token,testCommand:e.testCommand,coverageCommand:e.coverageCommand,lintCommand:e.lintCommand,prettierCommand:e.prettierCommand,disableLintRules:e.disableLintRules,refName:e.refName,baseRef:e.baseRef,gitOrg:e.gitOrg,gitRepo:e.gitRepo,gitUserEmail:e.gitUserEmail,gitUserName:e.gitUserName,SCMProvider:e.scmProvider,prNumber:e.prNumber,commitHash:e.commitHash,targetDirectory:e.targetDirectory,frequency:e.frequency,startTime:e.startTime,keepErrorTests:e.keepErrorTests,keepFailedTests:e.keepFailedTests,conditionalKeep:e.conditionalKeep,continueOnTestErrors:e.continueOnTestErrors,changedMethodsOnly:e.changedMethodsOnly,skipCoverageAfter:e.skipCoverageAfter,maxTestables:e.maxTestables,autoCommitSkipCi:e.autoCommitSkipCi,perFunctionTimeout:e.perFunctionTimeout,coverageThreshold:e.coverageThreshold,reuseCoverage:e.reuseCoverage,reuseCoverageMaxRuns:e.reuseCoverageMaxRuns,experimentalAgentSdk:e.experimentalAgentSdk,agentSdkModel:e.agentSdkModel,agentSdkBudget:e.agentSdkBudget,verbose:e.verbose,debug:e.debug,...this.isDev()&&{rootPath:e.rootPath}};return Object.fromEntries(Object.entries(t).filter(([,e])=>!(0,B.isEmpty)(e)))}};cQ=aQ([et(`Singleton`),iQ(0,Ze(lW.CliOptions)),iQ(1,Ze(sQ)),rQ(`design:paramtypes`,[Object,Object])],cQ);var lQ;let uQ=class{constructor(e,t){this.configService=e,this.logger=t}data={warnings:[]};setChangedFilesData(e){this.data.changedFiles=e}setCoverageData(e,t){this.data.coverage={before:e,after:t}}setPRCoverageData(e,t){this.data.prCoverage={before:e,after:t}}setCoverageSkipped(){this.data.coverageSkipped=!0}setCoverageBeforeSkipped(){this.data.coverageBeforeSkipped=!0}setTestGenerationData(e){this.data.testGeneration=e}setAutoCommitStatus(e){this.data.autoCommit={enabled:e}}addWarning(e){this.data.warnings.push({message:e})}getWorkflowRunOutput(){return{filesCount:this.data.changedFiles?.changedFilesCount??0,codeFileCount:this.data.changedFiles?.candidateFilesCount??0,methodsCount:this.data.changedFiles?.functionCount??0,publicMethodCount:this.data.changedFiles?.publicMethodCount??0,publicMethodBelowCoverageCount:this.data.changedFiles?.testablesToGenerateCount??0,generatedMethodsCount:this.data.testGeneration?.generated??0,successMethodsCount:this.data.testGeneration?.successMethodsCount??0,committedFilesCount:this.data.testGeneration?.committedFilesCount??0,numberOfGreenTests:this.data.testGeneration?.greenTests??0,numberOfRedTests:this.data.testGeneration?.redTests??0,publicMethods:this.data.changedFiles?.publicMethods,changedMethods:this.data.changedFiles?.changedMethods,methodsBelowCoverage:this.data.changedFiles?.methodsBelowCoverage}}generateMarkdownSummary(){let e=[];for(let t of this.data.warnings)e.push(`⚠️ ${t.message}`);if(e.push(``,`🧪 **Early Test Generation Agent**`,``),this.data.changedFiles){let{changedFilesCount:t,candidateFilesCount:n,functionCount:r,testablesToGenerateCount:i}=this.data.changedFiles;e.push(`- Changed files: ${t}`,`- Files with testable code: ${n}`,`- Total methods detected: ${r}`,`- Public methods below coverage threshold: ${i}`)}if(this.data.testGeneration){let{successMethodsCount:t,greenTests:n,redTests:r,skippedMethods:i}=this.data.testGeneration;e.push(`- Generated tests for ${t} methods`,`- Generated ${n} green unit tests`,`- Filtered ${r} red unit tests`,...(0,B.isDefined)(i)&&i>0?[`- Skipped ${i} methods (already tested)`]:[],`**Action Taken**`,``,`✅ Unit tests automatically generated for ${t} public functions below threshold.`)}if((0,B.isDefined)(this.data.autoCommit)&&this.data.autoCommit.enabled&&e.push(`📦 Test files have been auto-committed to this branch.`),(0,B.isDefined)(this.data.prCoverage)){let t=this.data.coverageBeforeSkipped??!1,n=this.data.coverageSkipped??!1,r=t?`Skipped`:`${this.data.prCoverage.before.percentage??0}%`,i=n?`Skipped`:`${this.data.prCoverage.after.percentage??0}%`;switch(this.configService.getConfigValue(`command`)){case dW.PR:e.push(``,`**📊 PR coverage before: `+r+`. PR coverage after: `+i+`.**`);break;case dW.COMMIT:e.push(``,`**📊 Commit coverage before: `+r+`. Commit coverage after: `+i+`.**`);break;case dW.PROJECT:e.push(``,`**📊 Project coverage before: `+r+`. Project coverage after: `+i+`.**`);break}}return e.push(``,`Early Agent is now guarding your coverage.`,"Early Trace ID: `"+this.configService.getConfigValue(`traceId`)+"`"),e.join(`
|
|
32392
32392
|
`)}async addToJobSummary(){try{this.logger.info(`Successfully added summary to job summary`)}catch(e){this.logger.warn(`Failed to add summary to job summary: ${e instanceof Error?e.message:`Unknown error`}`)}}clear(){this.data={warnings:[]}}};uQ=aQ([et(),iQ(0,Ze(cQ)),iQ(1,Ze(sQ)),rQ(`design:paramtypes`,[typeof(lQ=cQ!==void 0&&cQ)==`function`?lQ:Object,Object])],uQ);const dQ={allowedExtensions:[`.ts`,`.tsx`,`.js`,`.jsx`,`.py`],excludePatterns:[`.test.`,`.spec.`,`.d.ts`,`jest.config`,`vitest.config`,`webpack.config`,`rollup.config`,`vite.config`,`tsconfig`,`eslint.config`,`prettier.config`,`babel.config`,`.eslintrc`,`.prettierrc`,`dist/`,`build/`,`out/`,`.next/`,`.nuxt/`,`.early.test`,`_test.py`,`conftest.py`,`__pycache__/`,`.venv/`]};let fQ=function(e){return e.Added=`added`,e.Modified=`modified`,e}({});var pQ,mQ;let hQ=class{constructor(e,t,n){this.configService=e,this.summaryService=t,this.logger=n}async safePostSummaryToPr(){try{if((0,B.isDefined)(this.configService.getConfigValue(`prNumber`)))await this.postSummaryToPr();else{let e=this.summaryService.generateMarkdownSummary();this.logger.info(e)}}catch(e){this.logger.error(`Failed to post summary to PR: ${e instanceof Error?e.message:`Unknown error`}`)}}async getChangedFilesWithStatus(){return(await this.getChangedFilesPR()).map(e=>({filePath:e,status:fQ.Modified}))}async getContributorAvatarUrl(){}};hQ=aQ([et(),iQ(0,Ze(cQ)),iQ(1,Ze(uQ)),iQ(2,Ze(sQ)),rQ(`design:paramtypes`,[typeof(pQ=cQ!==void 0&&cQ)==`function`?pQ:Object,typeof(mQ=uQ!==void 0&&uQ)==`function`?mQ:Object,Object])],hQ);const gQ=()=>H0.get(cQ),_Q=(0,S.promisify)(f.exec),vQ=async(e,t={})=>await _Q(e,{cwd:gQ().getConfig().rootPath,...t});var yQ,bQ;let xQ=class{constructor(e,t,n){this.configService=e,this.scmHostService=t,this.logger=n}async hydrateConfig(){let e=this.configService.getConfigValue(`commitHash`),t=await this.getGitInfo({authorSha:e});this.configService.updateConfigValue(`gitOrg`,t.owner),this.configService.updateConfigValue(`gitRepo`,t.repository),this.configService.updateConfigValue(`gitTopLevel`,t.topLevel),this.configService.updateConfigValue(`contributorName`,t.authorName),this.configService.updateConfigValue(`contributorEmail`,t.authorEmail)}async getGitInfo(e){try{let t=e?.authorSha,[n,r,i,a,o,s,c]=await Promise.all([this.getRefName(),this.getSha(),this.getRemoteUrl(),this.getTopLevel(),this.getCommitDate(),this.getCommitAuthorName(t),this.getCommitAuthorEmail(t)]),{owner:l,repository:u}=this.parseRemoteUrl(i);return{ref_name:n,repository:u,owner:l,sha:r,topLevel:a,remoteUrl:i,commitDate:o,authorName:s,authorEmail:c}}catch(e){return this.logger.warn(`Failed to get local Git info: ${e instanceof Error?e.message:`Unknown error`}`),{ref_name:``,repository:``,owner:``,sha:``,topLevel:``,remoteUrl:``,commitDate:``,authorName:``,authorEmail:``}}}async getRefName(){try{let{stdout:e}=await vQ(`git rev-parse --abbrev-ref HEAD`);return e.trim()}catch{return this.logger.warn(`Could not get ref_name from local Git`),``}}async getSha(){try{let{stdout:e}=await vQ(`git rev-parse HEAD`);return e.trim()}catch{return this.logger.warn(`Could not get SHA from local Git`),``}}async getRemoteUrl(){try{let{stdout:e}=await vQ(`git remote get-url origin`);return e.trim()}catch{return this.logger.warn(`Could not get remote URL from local Git`),``}}async getTopLevel(){try{let{stdout:e}=await vQ(`git rev-parse --show-toplevel`);return e.trim()}catch{return this.logger.warn(`Could not get top-level directory from local Git`),``}}parseRemoteUrl(e){if(!e)return{owner:``,repository:``};try{if(e.startsWith(`http`)){let t=new URL(e).pathname.split(`/`).filter(Boolean);if(t.length>=2)return{owner:t[0],repository:t[1].replace(`.git`,``)}}if(e.includes(`@`)&&e.includes(`:`)){let t=e.split(`:`);if(t.length===2){let e=t[1].split(`/`).filter(Boolean);if(e.length>=2)return{owner:e[0],repository:e[1].replace(`.git`,``)}}}return{owner:``,repository:``}}catch{return this.logger.warn(`Failed to parse remote URL: ${e}`),{owner:``,repository:``}}}async getEarlyFiles(e){let{stdout:t}=await vQ(`git ls-files --others --exclude-standard`),{stdout:n}=await vQ(`git diff --name-only --diff-filter=M`),r=[...new Set([...t.trim().split(`
|
|
32393
32393
|
`),...n.trim().split(`
|
|
32394
|
-
`)])].filter(Boolean).filter(e=>e.includes(`.early.`));return(0,B.isDefined)(e)&&e.absolute?r.map(e=>uW.default.resolve(this.configService.getConfigValue(`gitTopLevel`),e)):r}async commitFiles(e){try{await this.scmHostService.setupGit(),await vQ(`git fetch`),(0,B.isDefined)(e)&&(await vQ(`git checkout ${e}`),await vQ(`git branch --set-upstream-to=origin/${e}`),await vQ(`git pull`));let t=await this.getEarlyFiles();if(t.length===0)return this.logger.info(`No files to commit`),{committedFiles:[],error:``};
|
|
32394
|
+
`)])].filter(Boolean).filter(e=>e.includes(`.early.`)||uW.default.basename(e).startsWith(`test_early_`));return(0,B.isDefined)(e)&&e.absolute?r.map(e=>uW.default.resolve(this.configService.getConfigValue(`gitTopLevel`),e)):r}async commitFiles(e){try{await this.scmHostService.setupGit(),await vQ(`git fetch`),(0,B.isDefined)(e)&&(await vQ(`git checkout ${e}`),await vQ(`git branch --set-upstream-to=origin/${e}`),await vQ(`git pull`));let t=await this.getEarlyFiles();if(t.length===0)return this.logger.info(`No files to commit`),{committedFiles:[],error:``};let{stdout:n}=await vQ(`git ls-files --others --exclude-standard`),r=n.trim().split(`
|
|
32395
|
+
`).filter(Boolean),i=new Set(t.map(e=>uW.default.dirname(e))),a=new Set;for(let e of i){let t=e;for(;t&&t!==`.`;)a.add(t),t=uW.default.dirname(t)}let o=r.filter(e=>{let t=uW.default.basename(e);return t!==`__init__.py`&&t!==`conftest.py`?!1:a.has(uW.default.dirname(e))}),s=[...new Set([...t,...o])];for(let e of s)await vQ(`git add "${e}"`);let{name:c,email:l}=this.scmHostService.getGitCommiterInfo();await vQ(`git -c user.name="${c}" -c user.email="${l}" commit --no-verify -m "${this.configService.getConfigValue(`autoCommitSkipCi`)?`chore: add early-catch tests [skip ci]`:`chore: add early-catch tests`}"`),this.logger.info(`Committed ${t.length} files`),await vQ(`git push --no-verify`);let{stdout:u}=await vQ(`git rev-parse HEAD`);return{committedFiles:t,error:``,resultCommitSha:u.trim()}}catch(e){let t=e instanceof Error?e.message:`Unknown error`;return this.logger.error(`Failed to commit files: ${t}`),{committedFiles:[],error:t}}finally{await this.scmHostService.teardownGit()}}async checkRefExists(e){try{if(!e)return!1;let{origin:t}=this.scmHostService.getGitOrigin(),{stdout:n}=await vQ(`git ls-remote --heads --tags ${t} ${e}`);return n.trim().length>0}catch(t){return this.logger.warn(`Failed to check if reference '${e}' exists: ${t instanceof Error?t.message:`Unknown error`}`),!1}}async getChangedFilesForPR(e={}){return(await this.getChangedFilesForPRWithStatus(e)).map(e=>e.filePath)}async getChangedFilesForPRWithStatus(e={}){try{let t=await this.scmHostService.getChangedFilesWithStatus();if((0,B.isDefined)(e.absolute)&&e.absolute){let e=await this.getTopLevel();return t.map(t=>({filePath:uW.default.join(e,t.filePath),status:t.status}))}return t}catch(e){let t=e instanceof Error?e.message:`Unknown error`;throw this.logger.error(`Failed to get changed files for PR: ${t}`),Error(`Failed to get changed files for PR: ${t}`)}}async getChangedFilesForCommit(e={}){return(await this.getChangedFilesForCommitWithStatus(e)).map(e=>e.filePath)}async getChangedFilesForCommitWithStatus(e={}){let t=this.configService.getConfigValue(`commitHash`);if(!(0,B.isDefined)(t))throw Error(`commitHash config is required for commit file retrieval`);try{let n=this.configService.getConfigValue(`baseRef`),r;r=(0,B.isDefined)(n)?(await vQ(`git diff --name-status --diff-filter=AM "${await this.getBaseRevision({baseBranch:n})}...${t}"`)).stdout:(await vQ(`git diff-tree --no-commit-id --name-status -r --diff-filter=AM "${t}"`)).stdout;let i=r.trim().split(`
|
|
32395
32396
|
`).filter(Boolean).map(e=>{let[t,n]=e.split(` `),r=t===`A`?fQ.Added:fQ.Modified;return{filePath:n??``,status:r}}).filter(e=>e.filePath.length>0);if((0,B.isDefined)(e.absolute)&&e.absolute){let e=await this.getTopLevel();return i.map(t=>({filePath:uW.default.join(e,t.filePath),status:t.status}))}return i}catch(e){let t=e instanceof Error?e.message:`Unknown error`;throw this.logger.error(`Failed to get changed files for commit: ${t}`),Error(`Failed to get changed files for commit: ${t}`)}}async getShaByDatetime(e,t){try{let{stdout:n}=await vQ(`git rev-list -1 --before="${t}" ${e}`);return n.trim()}catch{return this.logger.warn(`Could not get SHA from local Git by datetime: ${t} for: ${e}`),``}}async checkout(e){try{await vQ(`git checkout ${e}`),this.logger.info(`Git checkedout to: ${e}`)}catch(t){throw this.logger.error(`Could not checkout to ref: ${e}`),t}}async getCommitDate(){try{let{stdout:e}=await vQ(`git show -s --format=%cI HEAD`);return e.trim()}catch{return this.logger.warn(`Could not get commit date from local Git`),``}}async getFileAtRevision(e,t){try{let{stdout:n}=await vQ(`git show "${t}:${e}"`);return n}catch(n){return n instanceof Error&&(n.message.includes(`does not exist`)||n.message.includes(`exists on disk, but not in`))||this.logger.warn(`Failed to get file ${e} at revision ${t}: ${n instanceof Error?n.message:`Unknown error`}`),null}}async getMergeBase(e){try{try{await vQ(`git fetch origin ${e} --depth=1`)}catch{this.logger.warn(`Could not fetch ${e}, attempting to use local ref`)}let{stdout:t}=await vQ(`git merge-base HEAD origin/${e}`);return t.trim()}catch(t){throw this.logger.warn(`Failed to get merge base for branch ${e}: ${t instanceof Error?t.message:`Unknown error`}`),t}}async getDefaultBranch(){try{let{stdout:e}=await vQ(`git symbolic-ref refs/remotes/origin/HEAD`);return e.trim().replace(`refs/remotes/origin/`,``)}catch(e){return this.logger.debug(`Failed to get default branch, falling back to 'main': ${e instanceof Error?e.message:`Unknown error`}`),`main`}}async getBaseRevision(e){if((0,B.isDefined)(e.baseCommit))return e.baseCommit;if((0,B.isDefined)(e.baseBranch))return await vQ(`git fetch --no-tags origin "${`refs/heads/${e.baseBranch}:refs/remotes/origin/${e.baseBranch}`}"`),`origin/${e.baseBranch}`;let t=await this.getDefaultBranch();return await this.getMergeBase(t)}async getCommitMessage(e){try{let{stdout:t}=await vQ(`git log -1 --format=%s ${e??`HEAD`}`);return t.trim()}catch{return this.logger.warn(`Could not get commit message from local Git`),``}}async getCommitAuthorName(e){try{let{stdout:t}=await vQ(`git log -1 --format=%an ${e??`HEAD`}`);return t.trim()}catch{return this.logger.warn(`Could not get commit author name from local Git`),``}}async getCommitAuthorEmail(e){try{let{stdout:t}=await vQ(`git log -1 --format=%ae ${e??`HEAD`}`);return t.trim()}catch{return this.logger.warn(`Could not get commit author email from local Git`),``}}};xQ=aQ([et(),iQ(0,Ze(cQ)),iQ(1,Ze(lW.SCMHostService)),iQ(2,Ze(sQ)),rQ(`design:paramtypes`,[typeof(yQ=cQ!==void 0&&cQ)==`function`?yQ:Object,typeof(bQ=hQ!==void 0&&hQ)==`function`?bQ:Object,Object])],xQ);function SQ(e,t){return function(){return e.apply(t,arguments)}}const{toString:CQ}=Object.prototype,{getPrototypeOf:wQ}=Object,{iterator:TQ,toStringTag:EQ}=Symbol,DQ=(e=>t=>{let n=CQ.call(t);return e[n]||(e[n]=n.slice(8,-1).toLowerCase())})(Object.create(null)),OQ=e=>(e=e.toLowerCase(),t=>DQ(t)===e),kQ=e=>t=>typeof t===e,{isArray:AQ}=Array,jQ=kQ(`undefined`);function MQ(e){return e!==null&&!jQ(e)&&e.constructor!==null&&!jQ(e.constructor)&&FQ(e.constructor.isBuffer)&&e.constructor.isBuffer(e)}const NQ=OQ(`ArrayBuffer`);function ote(e){let t;return t=typeof ArrayBuffer<`u`&&ArrayBuffer.isView?ArrayBuffer.isView(e):e&&e.buffer&&NQ(e.buffer),t}const PQ=kQ(`string`),FQ=kQ(`function`),IQ=kQ(`number`),LQ=e=>typeof e==`object`&&!!e,RQ=e=>e===!0||e===!1,zQ=e=>{if(DQ(e)!==`object`)return!1;let t=wQ(e);return(t===null||t===Object.prototype||Object.getPrototypeOf(t)===null)&&!(EQ in e)&&!(TQ in e)},BQ=e=>{if(!LQ(e)||MQ(e))return!1;try{return Object.keys(e).length===0&&Object.getPrototypeOf(e)===Object.prototype}catch{return!1}},VQ=OQ(`Date`),HQ=OQ(`File`),UQ=OQ(`Blob`),WQ=OQ(`FileList`),GQ=e=>LQ(e)&&FQ(e.pipe),KQ=e=>{let t;return e&&(typeof FormData==`function`&&e instanceof FormData||FQ(e.append)&&((t=DQ(e))===`formdata`||t===`object`&&FQ(e.toString)&&e.toString()===`[object FormData]`))},qQ=OQ(`URLSearchParams`),[JQ,YQ,XQ,ZQ]=[`ReadableStream`,`Request`,`Response`,`Headers`].map(OQ),QQ=e=>e.trim?e.trim():e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,``);function $Q(e,t,{allOwnKeys:n=!1}={}){if(e==null)return;let r,i;if(typeof e!=`object`&&(e=[e]),AQ(e))for(r=0,i=e.length;r<i;r++)t.call(null,e[r],r,e);else{if(MQ(e))return;let i=n?Object.getOwnPropertyNames(e):Object.keys(e),a=i.length,o;for(r=0;r<a;r++)o=i[r],t.call(null,e[o],o,e)}}function e$(e,t){if(MQ(e))return null;t=t.toLowerCase();let n=Object.keys(e),r=n.length,i;for(;r-- >0;)if(i=n[r],t===i.toLowerCase())return i;return null}const t$=typeof globalThis<`u`?globalThis:typeof self<`u`?self:typeof window<`u`?window:global,n$=e=>!jQ(e)&&e!==t$;function r$(){let{caseless:e,skipUndefined:t}=n$(this)&&this||{},n={},r=(r,i)=>{let a=e&&e$(n,i)||i;zQ(n[a])&&zQ(r)?n[a]=r$(n[a],r):zQ(r)?n[a]=r$({},r):AQ(r)?n[a]=r.slice():(!t||!jQ(r))&&(n[a]=r)};for(let e=0,t=arguments.length;e<t;e++)arguments[e]&&$Q(arguments[e],r);return n}const i$=(e,t,n,{allOwnKeys:r}={})=>($Q(t,(t,r)=>{n&&FQ(t)?e[r]=SQ(t,n):e[r]=t},{allOwnKeys:r}),e),a$=e=>(e.charCodeAt(0)===65279&&(e=e.slice(1)),e),o$=(e,t,n,r)=>{e.prototype=Object.create(t.prototype,r),e.prototype.constructor=e,Object.defineProperty(e,`super`,{value:t.prototype}),n&&Object.assign(e.prototype,n)},s$=(e,t,n,r)=>{let i,a,o,s={};if(t||={},e==null)return t;do{for(i=Object.getOwnPropertyNames(e),a=i.length;a-- >0;)o=i[a],(!r||r(o,e,t))&&!s[o]&&(t[o]=e[o],s[o]=!0);e=n!==!1&&wQ(e)}while(e&&(!n||n(e,t))&&e!==Object.prototype);return t},c$=(e,t,n)=>{e=String(e),(n===void 0||n>e.length)&&(n=e.length),n-=t.length;let r=e.indexOf(t,n);return r!==-1&&r===n},l$=e=>{if(!e)return null;if(AQ(e))return e;let t=e.length;if(!IQ(t))return null;let n=Array(t);for(;t-- >0;)n[t]=e[t];return n},u$=(e=>t=>e&&t instanceof e)(typeof Uint8Array<`u`&&wQ(Uint8Array)),ste=(e,t)=>{let n=(e&&e[TQ]).call(e),r;for(;(r=n.next())&&!r.done;){let n=r.value;t.call(e,n[0],n[1])}},d$=(e,t)=>{let n,r=[];for(;(n=e.exec(t))!==null;)r.push(n);return r},cte=OQ(`HTMLFormElement`),lte=e=>e.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(e,t,n){return t.toUpperCase()+n}),ute=(({hasOwnProperty:e})=>(t,n)=>e.call(t,n))(Object.prototype),dte=OQ(`RegExp`),f$=(e,t)=>{let n=Object.getOwnPropertyDescriptors(e),r={};$Q(n,(n,i)=>{let a;(a=t(n,i,e))!==!1&&(r[i]=a||n)}),Object.defineProperties(e,r)},p$=e=>{f$(e,(t,n)=>{if(FQ(e)&&[`arguments`,`caller`,`callee`].indexOf(n)!==-1)return!1;let r=e[n];if(FQ(r)){if(t.enumerable=!1,`writable`in t){t.writable=!1;return}t.set||=()=>{throw Error(`Can not rewrite read-only method '`+n+`'`)}}})},m$=(e,t)=>{let n={},r=e=>{e.forEach(e=>{n[e]=!0})};return AQ(e)?r(e):r(String(e).split(t)),n},h$=()=>{},g$=(e,t)=>e!=null&&Number.isFinite(e=+e)?e:t;function _$(e){return!!(e&&FQ(e.append)&&e[EQ]===`FormData`&&e[TQ])}const v$=e=>{let t=Array(10),n=(e,r)=>{if(LQ(e)){if(t.indexOf(e)>=0)return;if(MQ(e))return e;if(!(`toJSON`in e)){t[r]=e;let i=AQ(e)?[]:{};return $Q(e,(e,t)=>{let a=n(e,r+1);!jQ(a)&&(i[t]=a)}),t[r]=void 0,i}}return e};return n(e,0)},fte=OQ(`AsyncFunction`),pte=e=>e&&(LQ(e)||FQ(e))&&FQ(e.then)&&FQ(e.catch),y$=((e,t)=>e?setImmediate:t?((e,t)=>(t$.addEventListener(`message`,({source:n,data:r})=>{n===t$&&r===e&&t.length&&t.shift()()},!1),n=>{t.push(n),t$.postMessage(e,`*`)}))(`axios@${Math.random()}`,[]):e=>setTimeout(e))(typeof setImmediate==`function`,FQ(t$.postMessage));var b$={isArray:AQ,isArrayBuffer:NQ,isBuffer:MQ,isFormData:KQ,isArrayBufferView:ote,isString:PQ,isNumber:IQ,isBoolean:RQ,isObject:LQ,isPlainObject:zQ,isEmptyObject:BQ,isReadableStream:JQ,isRequest:YQ,isResponse:XQ,isHeaders:ZQ,isUndefined:jQ,isDate:VQ,isFile:HQ,isBlob:UQ,isRegExp:dte,isFunction:FQ,isStream:GQ,isURLSearchParams:qQ,isTypedArray:u$,isFileList:WQ,forEach:$Q,merge:r$,extend:i$,trim:QQ,stripBOM:a$,inherits:o$,toFlatObject:s$,kindOf:DQ,kindOfTest:OQ,endsWith:c$,toArray:l$,forEachEntry:ste,matchAll:d$,isHTMLForm:cte,hasOwnProperty:ute,hasOwnProp:ute,reduceDescriptors:f$,freezeMethods:p$,toObjectSet:m$,toCamelCase:lte,noop:h$,toFiniteNumber:g$,findKey:e$,global:t$,isContextDefined:n$,isSpecCompliantForm:_$,toJSONObject:v$,isAsyncFn:fte,isThenable:pte,setImmediate:y$,asap:typeof queueMicrotask<`u`?queueMicrotask.bind(t$):typeof process<`u`&&process.nextTick||y$,isIterable:e=>e!=null&&FQ(e[TQ])};function x$(e,t,n,r,i){Error.call(this),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=Error().stack,this.message=e,this.name=`AxiosError`,t&&(this.code=t),n&&(this.config=n),r&&(this.request=r),i&&(this.response=i,this.status=i.status?i.status:null)}b$.inherits(x$,Error,{toJSON:function(){return{message:this.message,name:this.name,description:this.description,number:this.number,fileName:this.fileName,lineNumber:this.lineNumber,columnNumber:this.columnNumber,stack:this.stack,config:b$.toJSONObject(this.config),code:this.code,status:this.status}}});const S$=x$.prototype,C$={};[`ERR_BAD_OPTION_VALUE`,`ERR_BAD_OPTION`,`ECONNABORTED`,`ETIMEDOUT`,`ERR_NETWORK`,`ERR_FR_TOO_MANY_REDIRECTS`,`ERR_DEPRECATED`,`ERR_BAD_RESPONSE`,`ERR_BAD_REQUEST`,`ERR_CANCELED`,`ERR_NOT_SUPPORT`,`ERR_INVALID_URL`].forEach(e=>{C$[e]={value:e}}),Object.defineProperties(x$,C$),Object.defineProperty(S$,`isAxiosError`,{value:!0}),x$.from=(e,t,n,r,i,a)=>{let o=Object.create(S$);b$.toFlatObject(e,o,function(e){return e!==Error.prototype},e=>e!==`isAxiosError`);let s=e&&e.message?e.message:`Error`,c=t==null&&e?e.code:t;return x$.call(o,s,c,n,r,i),e&&o.cause==null&&Object.defineProperty(o,`cause`,{value:e,configurable:!0}),o.name=e&&e.name||`Error`,a&&Object.assign(o,a),o};var w$=u(aH(),1).default;function T$(e){return b$.isPlainObject(e)||b$.isArray(e)}function E$(e){return b$.endsWith(e,`[]`)?e.slice(0,-2):e}function D$(e,t,n){return e?e.concat(t).map(function(e,t){return e=E$(e),!n&&t?`[`+e+`]`:e}).join(n?`.`:``):t}function O$(e){return b$.isArray(e)&&!e.some(T$)}const k$=b$.toFlatObject(b$,{},null,function(e){return/^is[A-Z]/.test(e)});function A$(e,t,n){if(!b$.isObject(e))throw TypeError(`target must be an object`);t||=new(w$||FormData),n=b$.toFlatObject(n,{metaTokens:!0,dots:!1,indexes:!1},!1,function(e,t){return!b$.isUndefined(t[e])});let r=n.metaTokens,i=n.visitor||l,a=n.dots,o=n.indexes,s=(n.Blob||typeof Blob<`u`&&Blob)&&b$.isSpecCompliantForm(t);if(!b$.isFunction(i))throw TypeError(`visitor must be a function`);function c(e){if(e===null)return``;if(b$.isDate(e))return e.toISOString();if(b$.isBoolean(e))return e.toString();if(!s&&b$.isBlob(e))throw new x$(`Blob is not supported. Use a Buffer instead.`);return b$.isArrayBuffer(e)||b$.isTypedArray(e)?s&&typeof Blob==`function`?new Blob([e]):Buffer.from(e):e}function l(e,n,i){let s=e;if(e&&!i&&typeof e==`object`){if(b$.endsWith(n,`{}`))n=r?n:n.slice(0,-2),e=JSON.stringify(e);else if(b$.isArray(e)&&O$(e)||(b$.isFileList(e)||b$.endsWith(n,`[]`))&&(s=b$.toArray(e)))return n=E$(n),s.forEach(function(e,r){!(b$.isUndefined(e)||e===null)&&t.append(o===!0?D$([n],r,a):o===null?n:n+`[]`,c(e))}),!1}return T$(e)?!0:(t.append(D$(i,n,a),c(e)),!1)}let u=[],d=Object.assign(k$,{defaultVisitor:l,convertValue:c,isVisitable:T$});function f(e,n){if(!b$.isUndefined(e)){if(u.indexOf(e)!==-1)throw Error(`Circular reference detected in `+n.join(`.`));u.push(e),b$.forEach(e,function(e,r){(!(b$.isUndefined(e)||e===null)&&i.call(t,e,b$.isString(r)?r.trim():r,n,d))===!0&&f(e,n?n.concat(r):[r])}),u.pop()}}if(!b$.isObject(e))throw TypeError(`data must be an object`);return f(e),t}function j$(e){let t={"!":`%21`,"'":`%27`,"(":`%28`,")":`%29`,"~":`%7E`,"%20":`+`,"%00":`\0`};return encodeURIComponent(e).replace(/[!'()~]|%20|%00/g,function(e){return t[e]})}function M$(e,t){this._pairs=[],e&&A$(e,this,t)}const N$=M$.prototype;N$.append=function(e,t){this._pairs.push([e,t])},N$.toString=function(e){let t=e?function(t){return e.call(this,t,j$)}:j$;return this._pairs.map(function(e){return t(e[0])+`=`+t(e[1])},``).join(`&`)};function P$(e){return encodeURIComponent(e).replace(/%3A/gi,`:`).replace(/%24/g,`$`).replace(/%2C/gi,`,`).replace(/%20/g,`+`)}function F$(e,t,n){if(!t)return e;let r=n&&n.encode||P$;b$.isFunction(n)&&(n={serialize:n});let i=n&&n.serialize,a;if(a=i?i(t,n):b$.isURLSearchParams(t)?t.toString():new M$(t,n).toString(r),a){let t=e.indexOf(`#`);t!==-1&&(e=e.slice(0,t)),e+=(e.indexOf(`?`)===-1?`?`:`&`)+a}return e}var I$=class{constructor(){this.handlers=[]}use(e,t,n){return this.handlers.push({fulfilled:e,rejected:t,synchronous:n?n.synchronous:!1,runWhen:n?n.runWhen:null}),this.handlers.length-1}eject(e){this.handlers[e]&&(this.handlers[e]=null)}clear(){this.handlers&&=[]}forEach(e){b$.forEach(this.handlers,function(t){t!==null&&e(t)})}},L$={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},mte=T.default.URLSearchParams;const R$=`abcdefghijklmnopqrstuvwxyz`,z$={DIGIT:`0123456789`,ALPHA:R$,ALPHA_DIGIT:R$+`ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789`};var B$={isNode:!0,classes:{URLSearchParams:mte,FormData:w$,Blob:typeof Blob<`u`&&Blob||null},ALPHABET:z$,generateString:(e=16,t=z$.ALPHA_DIGIT)=>{let n=``,{length:r}=t,i=new Uint32Array(e);x.default.randomFillSync(i);for(let a=0;a<e;a++)n+=t[i[a]%r];return n},protocols:[`http`,`https`,`file`,`data`]},V$=c({hasBrowserEnv:()=>H$,hasStandardBrowserEnv:()=>W$,hasStandardBrowserWebWorkerEnv:()=>G$,navigator:()=>U$,origin:()=>K$});const H$=typeof window<`u`&&typeof document<`u`,U$=typeof navigator==`object`&&navigator||void 0,W$=H$&&(!U$||[`ReactNative`,`NativeScript`,`NS`].indexOf(U$.product)<0),G$=typeof WorkerGlobalScope<`u`&&self instanceof WorkerGlobalScope&&typeof self.importScripts==`function`,K$=H$&&window.location.href||`http://localhost`;var q$={...V$,...B$};function J$(e,t){return A$(e,new q$.classes.URLSearchParams,{visitor:function(e,t,n,r){return q$.isNode&&b$.isBuffer(e)?(this.append(t,e.toString(`base64`)),!1):r.defaultVisitor.apply(this,arguments)},...t})}function Y$(e){return b$.matchAll(/\w+|\[(\w*)]/g,e).map(e=>e[0]===`[]`?``:e[1]||e[0])}function X$(e){let t={},n=Object.keys(e),r,i=n.length,a;for(r=0;r<i;r++)a=n[r],t[a]=e[a];return t}function Z$(e){function t(e,n,r,i){let a=e[i++];if(a===`__proto__`)return!0;let o=Number.isFinite(+a),s=i>=e.length;return a=!a&&b$.isArray(r)?r.length:a,s?(b$.hasOwnProp(r,a)?r[a]=[r[a],n]:r[a]=n,!o):((!r[a]||!b$.isObject(r[a]))&&(r[a]=[]),t(e,n,r[a],i)&&b$.isArray(r[a])&&(r[a]=X$(r[a])),!o)}if(b$.isFormData(e)&&b$.isFunction(e.entries)){let n={};return b$.forEachEntry(e,(e,r)=>{t(Y$(e),r,n,0)}),n}return null}function Q$(e,t,n){if(b$.isString(e))try{return(t||JSON.parse)(e),b$.trim(e)}catch(e){if(e.name!==`SyntaxError`)throw e}return(n||JSON.stringify)(e)}const $$={transitional:L$,adapter:[`xhr`,`http`,`fetch`],transformRequest:[function(e,t){let n=t.getContentType()||``,r=n.indexOf(`application/json`)>-1,i=b$.isObject(e);if(i&&b$.isHTMLForm(e)&&(e=new FormData(e)),b$.isFormData(e))return r?JSON.stringify(Z$(e)):e;if(b$.isArrayBuffer(e)||b$.isBuffer(e)||b$.isStream(e)||b$.isFile(e)||b$.isBlob(e)||b$.isReadableStream(e))return e;if(b$.isArrayBufferView(e))return e.buffer;if(b$.isURLSearchParams(e))return t.setContentType(`application/x-www-form-urlencoded;charset=utf-8`,!1),e.toString();let a;if(i){if(n.indexOf(`application/x-www-form-urlencoded`)>-1)return J$(e,this.formSerializer).toString();if((a=b$.isFileList(e))||n.indexOf(`multipart/form-data`)>-1){let t=this.env&&this.env.FormData;return A$(a?{"files[]":e}:e,t&&new t,this.formSerializer)}}return i||r?(t.setContentType(`application/json`,!1),Q$(e)):e}],transformResponse:[function(e){let t=this.transitional||$$.transitional,n=t&&t.forcedJSONParsing,r=this.responseType===`json`;if(b$.isResponse(e)||b$.isReadableStream(e))return e;if(e&&b$.isString(e)&&(n&&!this.responseType||r)){let n=!(t&&t.silentJSONParsing)&&r;try{return JSON.parse(e,this.parseReviver)}catch(e){if(n)throw e.name===`SyntaxError`?x$.from(e,x$.ERR_BAD_RESPONSE,this,null,this.response):e}}return e}],timeout:0,xsrfCookieName:`XSRF-TOKEN`,xsrfHeaderName:`X-XSRF-TOKEN`,maxContentLength:-1,maxBodyLength:-1,env:{FormData:q$.classes.FormData,Blob:q$.classes.Blob},validateStatus:function(e){return e>=200&&e<300},headers:{common:{Accept:`application/json, text/plain, */*`,"Content-Type":void 0}}};b$.forEach([`delete`,`get`,`head`,`post`,`put`,`patch`],e=>{$$.headers[e]={}});const hte=b$.toObjectSet([`age`,`authorization`,`content-length`,`content-type`,`etag`,`expires`,`from`,`host`,`if-modified-since`,`if-unmodified-since`,`last-modified`,`location`,`max-forwards`,`proxy-authorization`,`referer`,`retry-after`,`user-agent`]);var gte=e=>{let t={},n,r,i;return e&&e.split(`
|
|
32396
32397
|
`).forEach(function(e){i=e.indexOf(`:`),n=e.substring(0,i).trim().toLowerCase(),r=e.substring(i+1).trim(),!(!n||t[n]&&hte[n])&&(n===`set-cookie`?t[n]?t[n].push(r):t[n]=[r]:t[n]=t[n]?t[n]+`, `+r:r)}),t};const _te=Symbol(`internals`);function e1(e){return e&&String(e).trim().toLowerCase()}function t1(e){return e===!1||e==null?e:b$.isArray(e)?e.map(t1):String(e)}function n1(e){let t=Object.create(null),n=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g,r;for(;r=n.exec(e);)t[r[1]]=r[2];return t}const vte=e=>/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(e.trim());function r1(e,t,n,r,i){if(b$.isFunction(r))return r.call(this,t,n);if(i&&(t=n),b$.isString(t)){if(b$.isString(r))return t.indexOf(r)!==-1;if(b$.isRegExp(r))return r.test(t)}}function yte(e){return e.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(e,t,n)=>t.toUpperCase()+n)}function bte(e,t){let n=b$.toCamelCase(` `+t);[`get`,`set`,`has`].forEach(r=>{Object.defineProperty(e,r+n,{value:function(e,n,i){return this[r].call(this,t,e,n,i)},configurable:!0})})}var i1=class{constructor(e){e&&this.set(e)}set(e,t,n){let r=this;function i(e,t,n){let i=e1(t);if(!i)throw Error(`header name must be a non-empty string`);let a=b$.findKey(r,i);(!a||r[a]===void 0||n===!0||n===void 0&&r[a]!==!1)&&(r[a||t]=t1(e))}let a=(e,t)=>b$.forEach(e,(e,n)=>i(e,n,t));if(b$.isPlainObject(e)||e instanceof this.constructor)a(e,t);else if(b$.isString(e)&&(e=e.trim())&&!vte(e))a(gte(e),t);else if(b$.isObject(e)&&b$.isIterable(e)){let n={},r,i;for(let t of e){if(!b$.isArray(t))throw TypeError(`Object iterator must return a key-value pair`);n[i=t[0]]=(r=n[i])?b$.isArray(r)?[...r,t[1]]:[r,t[1]]:t[1]}a(n,t)}else e!=null&&i(t,e,n);return this}get(e,t){if(e=e1(e),e){let n=b$.findKey(this,e);if(n){let e=this[n];if(!t)return e;if(t===!0)return n1(e);if(b$.isFunction(t))return t.call(this,e,n);if(b$.isRegExp(t))return t.exec(e);throw TypeError(`parser must be boolean|regexp|function`)}}}has(e,t){if(e=e1(e),e){let n=b$.findKey(this,e);return!!(n&&this[n]!==void 0&&(!t||r1(this,this[n],n,t)))}return!1}delete(e,t){let n=this,r=!1;function i(e){if(e=e1(e),e){let i=b$.findKey(n,e);i&&(!t||r1(n,n[i],i,t))&&(delete n[i],r=!0)}}return b$.isArray(e)?e.forEach(i):i(e),r}clear(e){let t=Object.keys(this),n=t.length,r=!1;for(;n--;){let i=t[n];(!e||r1(this,this[i],i,e,!0))&&(delete this[i],r=!0)}return r}normalize(e){let t=this,n={};return b$.forEach(this,(r,i)=>{let a=b$.findKey(n,i);if(a){t[a]=t1(r),delete t[i];return}let o=e?yte(i):String(i).trim();o!==i&&delete t[i],t[o]=t1(r),n[o]=!0}),this}concat(...e){return this.constructor.concat(this,...e)}toJSON(e){let t=Object.create(null);return b$.forEach(this,(n,r)=>{n!=null&&n!==!1&&(t[r]=e&&b$.isArray(n)?n.join(`, `):n)}),t}[Symbol.iterator](){return Object.entries(this.toJSON())[Symbol.iterator]()}toString(){return Object.entries(this.toJSON()).map(([e,t])=>e+`: `+t).join(`
|
|
32397
32398
|
`)}getSetCookie(){return this.get(`set-cookie`)||[]}get[Symbol.toStringTag](){return`AxiosHeaders`}static from(e){return e instanceof this?e:new this(e)}static concat(e,...t){let n=new this(e);return t.forEach(e=>n.set(e)),n}static accessor(e){let t=(this[_te]=this[_te]={accessors:{}}).accessors,n=this.prototype;function r(e){let r=e1(e);t[r]||(bte(n,e),t[r]=!0)}return b$.isArray(e)?e.forEach(r):r(e),this}};i1.accessor([`Content-Type`,`Content-Length`,`Accept`,`Accept-Encoding`,`User-Agent`,`Authorization`]),b$.reduceDescriptors(i1.prototype,({value:e},t)=>{let n=t[0].toUpperCase()+t.slice(1);return{get:()=>e,set(e){this[n]=e}}}),b$.freezeMethods(i1);function a1(e,t){let n=this||$$,r=t||n,i=i1.from(r.headers),a=r.data;return b$.forEach(e,function(e){a=e.call(n,a,i.normalize(),t?t.status:void 0)}),i.normalize(),a}function o1(e){return!!(e&&e.__CANCEL__)}function s1(e,t,n){x$.call(this,e??`canceled`,x$.ERR_CANCELED,t,n),this.name=`CanceledError`}b$.inherits(s1,x$,{__CANCEL__:!0});function c1(e,t,n){let r=n.config.validateStatus;!n.status||!r||r(n.status)?e(n):t(new x$(`Request failed with status code `+n.status,[x$.ERR_BAD_REQUEST,x$.ERR_BAD_RESPONSE][Math.floor(n.status/100)-4],n.config,n.request,n))}function l1(e){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(e)}function xte(e,t){return t?e.replace(/\/?\/$/,``)+`/`+t.replace(/^\/+/,``):e}function u1(e,t,n){let r=!l1(t);return e&&(r||n==0)?xte(e,t):t}var d1=u(sH(),1),f1=u(oH(),1);const p1=`1.12.2`;function m1(e){let t=/^([-+\w]{1,25})(:?\/\/|:)/.exec(e);return t&&t[1]||``}const h1=/^(?:([^;]+);)?(?:[^;]+;)?(base64|),([\s\S]*)$/;function g1(e,t,n){let r=n&&n.Blob||q$.classes.Blob,i=m1(e);if(t===void 0&&r&&(t=!0),i===`data`){e=i.length?e.slice(i.length+1):e;let n=h1.exec(e);if(!n)throw new x$(`Invalid URL`,x$.ERR_INVALID_URL);let a=n[1],o=n[2],s=n[3],c=Buffer.from(decodeURIComponent(s),o?`base64`:`utf8`);if(t){if(!r)throw new x$(`Blob is not supported`,x$.ERR_NOT_SUPPORT);return new r([c],{type:a})}return c}throw new x$(`Unsupported protocol `+i,x$.ERR_NOT_SUPPORT)}const _1=Symbol(`internals`);var v1=class extends D.default.Transform{constructor(e){e=b$.toFlatObject(e,{maxRate:0,chunkSize:64*1024,minChunkSize:100,timeWindow:500,ticksRate:2,samplesCount:15},null,(e,t)=>!b$.isUndefined(t[e])),super({readableHighWaterMark:e.chunkSize});let t=this[_1]={timeWindow:e.timeWindow,chunkSize:e.chunkSize,maxRate:e.maxRate,minChunkSize:e.minChunkSize,bytesSeen:0,isCaptured:!1,notifiedBytesLoaded:0,ts:Date.now(),bytes:0,onReadCallback:null};this.on(`newListener`,e=>{e===`progress`&&(t.isCaptured||=!0)})}_read(e){let t=this[_1];return t.onReadCallback&&t.onReadCallback(),super._read(e)}_transform(e,t,n){let r=this[_1],i=r.maxRate,a=this.readableHighWaterMark,o=r.timeWindow,s=i/(1e3/o),c=r.minChunkSize===!1?0:Math.max(r.minChunkSize,s*.01),l=(e,t)=>{let n=Buffer.byteLength(e);r.bytesSeen+=n,r.bytes+=n,r.isCaptured&&this.emit(`progress`,r.bytesSeen),this.push(e)?process.nextTick(t):r.onReadCallback=()=>{r.onReadCallback=null,process.nextTick(t)}},u=(e,t)=>{let n=Buffer.byteLength(e),u=null,d=a,f,p=0;if(i){let e=Date.now();(!r.ts||(p=e-r.ts)>=o)&&(r.ts=e,f=s-r.bytes,r.bytes=f<0?-f:0,p=0),f=s-r.bytes}if(i){if(f<=0)return setTimeout(()=>{t(null,e)},o-p);f<d&&(d=f)}d&&n>d&&n-d>c&&(u=e.subarray(d),e=e.subarray(0,d)),l(e,u?()=>{process.nextTick(t,null,u)}:t)};u(e,function e(t,r){if(t)return n(t);r?u(r,e):n(null)})}};const{asyncIterator:y1}=Symbol,b1=async function*(e){e.stream?yield*e.stream():e.arrayBuffer?yield await e.arrayBuffer():e[y1]?yield*e[y1]():yield e},x1=q$.ALPHABET.ALPHA_DIGIT+`-_`,S1=typeof TextEncoder==`function`?new TextEncoder:new b.default.TextEncoder,C1=S1.encode(`\r
|
|
@@ -32408,7 +32409,7 @@ var n=require(`buffer`),r=n.Buffer;function i(e,t){for(var n in e)t[n]=e[n]}r.fr
|
|
|
32408
32409
|
`,`
|
|
32409
32410
|
`)!==a.replaceAll(`\r
|
|
32410
32411
|
`,`
|
|
32411
|
-
`)}extractMethodText(e,t){return t.slice(e.startIndex,e.endIndex)}createChangedMethod(e,t,n){return{name:t.name,type:t.type,parentName:`parentName`in t?t.parentName:void 0,changeType:n,filePath:e,canCreateTests:t.canCreateTests}}};K0=aQ([et(),iQ(0,Ze(sQ)),rQ(`design:paramtypes`,[Object])],K0);var jte,Mte,Nte;let q0=class{constructor(e,t,n,r){this.gitService=e,this.changedMethodsDetector=t,this.tsAgent=n,this.logger=r}async execute(e,t,n){if(!(0,B.isDefined)(t.baseRevision))return{kept:e};let r=[...new Set(e.map(e=>e.filePath))],i=await this.detectChangedMethods(r,t.baseRevision,t.projectRootPath),a=new Set(i.filter(e=>e.changeType!==`deleted`&&e.canCreateTests).map(e=>`${e.filePath}:${e.name}:${e.parentName??``}`)),o=[],s=[];for(let t of e){let e=`${t.filePath}:${t.testable.name}:${`parentName`in t.testable?t.testable.parentName??``:``}`;a.has(e)?o.push(t):s.push(t)}return{kept:[...o,...s]}}async detectChangedMethods(e,t,n){let r=await this.gitService.getTopLevel(),i=[];for(let a of e){let e=await this.detectChangedMethodsForFile(a,t,n,r);i.push(...e)}return i}async detectChangedMethodsForFile(e,t,n,r){let i=null;try{let a=uW.default.isAbsolute(e)?e:uW.default.join(n,e),o=uW.default.relative(r,a),s=await this.gitService.getFileAtRevision(o,t),c=await this.getBaseMethodsFromContent(s,a,n);(0,B.isDefined)(c.temporaryFilePath)&&(i=c.temporaryFilePath);let l=await this.getCurrentMethods(a),u=await g.readFile(a,`utf8`);return this.changedMethodsDetector.detectChanges(e,c.methods,l,s,u)}catch(t){this.logger.warn(`Failed to detect changed methods for `+e+`: `+(t instanceof Error?t.message:`Unknown error`)+`. Changed-function detection disabled for this file — all its functions will be treated as changed. Fix: add 'fetch-depth: 0' to your checkout step.`);try{let t=uW.default.isAbsolute(e)?e:uW.default.join(n,e);return(await this.getCurrentMethods(t)).map(t=>({filePath:e,name:t.name,type:t.type,parentName:`parentName`in t?t.parentName:void 0,changeType:`modified`,canCreateTests:t.canCreateTests}))}catch{return[]}}finally{await this.cleanupTemporaryFile(i)}}async getBaseMethodsFromContent(e,t,n){if(!(0,B.isDefined)(e)||(0,B.isEmpty)(e))return{methods:[],temporaryFilePath:null};let r=p.default.resolve(n,`.early-temp`);await g.mkdir(r,{recursive:!0});let i=p.default.join(r,`base-${Date.now()}-${p.default.basename(t)}`);await g.writeFile(i,e);let a=i.replaceAll(`\\`,`/`);return{methods:((await this.tsAgent.getTestables(a))[0]?.[1]??[]).filter(e=>e.canCreateTests&&e.type!==`class`),temporaryFilePath:i}}async getCurrentMethods(e){let t=e.replaceAll(`\\`,`/`);return((await this.tsAgent.getTestables(t))[0]?.[1]??[]).filter(e=>e.canCreateTests&&e.type!==`class`)}async cleanupTemporaryFile(e){if((0,B.isDefined)(e))try{await g.unlink(e)}catch{}}};q0=aQ([et(),iQ(0,Ze(xQ)),iQ(1,Ze(K0)),iQ(2,Ze(lW.TSAgent)),iQ(3,Ze(sQ)),rQ(`design:paramtypes`,[typeof(jte=xQ!==void 0&&xQ)==`function`?jte:Object,typeof(Mte=K0!==void 0&&K0)==`function`?Mte:Object,typeof(Nte=cW.TSAgent!==void 0&&cW.TSAgent)==`function`?Nte:Object,Object])],q0);var J0;let Y0=class{constructor(e){this.configService=e}async execute(e,t,n){let r=t.coverageReport?.tree,i=t.coverageReport?.threshold??this.configService.getConfigValue(`coverageThreshold`)??0;if(!(0,B.isDefined)(r))return{kept:e};let a=[];for(let t of e){let e=this.findFileCoverage(r,t.filePath);if(!(0,B.isDefined)(e?.testables)){a.push(t);continue}let o=t.testable.type===`method`?t.testable.parentName:void 0,s=e.testables.find(e=>e.name===t.testable.name&&((0,B.isDefined)(o)?e.parentName===o:!(0,B.isDefined)(e.parentName)));if(!(0,B.isDefined)(s)||!(0,B.isDefined)(s.percentage)){a.push(t);continue}if(s.percentage>i){n.push({filePath:t.filePath,testableName:t.testable.name,reason:`above-coverage-threshold`});continue}a.push(t)}return{kept:a}}findFileCoverage(e,t){return e[t.startsWith(`/`)?t:`/${t}`]??null}};Y0=aQ([et(),iQ(0,Ze(cQ)),rQ(`design:paramtypes`,[typeof(J0=cQ!==void 0&&cQ)==`function`?J0:Object])],Y0);let X0=class{async execute(e,t,n){let r=[];for(let i of e){let e=i.filePath.toLowerCase(),a=dQ.allowedExtensions.some(t=>e.endsWith(t)),o=uW.default.isAbsolute(i.filePath)?uW.default.relative(t.gitTopLevel,i.filePath):i.filePath;if(!a){n.push({filePath:o,reason:`not-code-file`});continue}if(dQ.excludePatterns.some(t=>e.includes(t.toLowerCase()))){n.push({filePath:o,reason:`excluded-pattern`});continue}r.push(i)}return{kept:r}}};X0=aQ([et()],X0);var Z0;let Q0=class{constructor(e){this.configService=e}async execute(e,t,n){let r=this.configService.getConfigValue(`maxTestables`)??1/0;if(e.length<=r)return{kept:e};let i=e.slice(0,r);for(let t=r;t<e.length;t++){let r=e[t];n.push({filePath:r.filePath,testableName:r.testable.name,reason:`limit-reached`})}return{kept:i}}};Q0=aQ([et(),iQ(0,Ze(cQ)),rQ(`design:paramtypes`,[typeof(Z0=cQ!==void 0&&cQ)==`function`?Z0:Object])],Q0);var $0=u(Uz());function e2(e,t){let n=uW.default.relative(e,t);return n===``||!n.startsWith(`..`)&&!uW.default.isAbsolute(n)}function t2(e,t,n){let r=uW.default.isAbsolute(e)&&e2(n,e)?e:uW.default.join(n,e),i=(0,$0.default)(t,{cwd:m.default.existsSync(r)&&m.default.statSync(r).isDirectory()?r:uW.default.dirname(r)});return i!==null&&!e2(n,i)?null:i}function Pte(e,t){let n=[t2(e,`package.json`,t),t2(e,`project.json`,t)].filter(B.isDefined).filter(e=>e2(t,e));if(n.length===0)return t;let r=n.reduce((e,t)=>e.length>t.length?e:t,n[0]);return uW.default.dirname(r)}const n2=[`pyproject.toml`,`setup.py`,`setup.cfg`,`requirements.txt`],r2=[`package.json`,`tsconfig.json`],i2=[`.py`],a2=[`.ts`,`.tsx`,`.js`,`.jsx`];function o2(e,t){return t.some(t=>e.endsWith(t))}function s2(e){if(o2(e,i2))return`python`;if(o2(e,a2))return`typescript`}function c2(e,t){if(e&&t)return`mixed`;if(e)return`python`;if(t)return`typescript`}function l2(e){let t=m.default.readdirSync(e,{recursive:!0});return c2(t.some(e=>o2(e,i2)),t.some(e=>o2(e,a2)))}function u2(e){return c2(n2.some(t=>m.default.existsSync(uW.default.join(e,t))),r2.some(t=>m.default.existsSync(uW.default.join(e,t))))}function d2(e,t){if(t!==void 0&&t!==``){let n=uW.default.isAbsolute(t)?t:uW.default.join(e,t);return m.default.existsSync(n)&&m.default.statSync(n).isFile()?s2(n):m.default.existsSync(n)&&m.default.statSync(n).isDirectory()?l2(n):s2(t)??u2(e)}return u2(e)}const f2={detectProjectRoot(e,t,n){if(t.length===0)return n.verbose(`No changed files provided, using root path`),e;let r=t[0],i=Pte(uW.default.isAbsolute(r)?r:uW.default.join(e,r),e);return i===uW.default.normalize(e)?(n.verbose(`Using workspace root path`),e):(n.info(`Detected nested project root: ${i} (from file: ${r})`),i)}};function p2(e,t){let n=uW.default.relative(e,t);return n!==``&&!n.startsWith(`..`)&&!uW.default.isAbsolute(n)}let m2=class{constructor(e){this.logger=e}async execute(e,t,n){if((0,B.isEmpty)(e))return{kept:[],projectRootPath:t.rootPath};let r=e.map(e=>uW.default.isAbsolute(e.filePath)?e.filePath:uW.default.join(t.rootPath,e.filePath)),i=f2.detectProjectRoot(t.rootPath,r,this.logger),a=[];for(let[t,o]of e.entries()){let e=r[t];if(!p2(i,e)){n.push({filePath:o.filePath,reason:`outside-project`});continue}let s=uW.default.relative(i,e);a.push({filePath:s,status:o.status})}return{kept:a,projectRootPath:i}}};m2=aQ([et(),iQ(0,Ze(sQ)),rQ(`design:paramtypes`,[Object])],m2);let h2=class{constructor(e){this.tsAgent=e}async execute(e,t,n){let r=e.map(e=>e.filePath);if((0,B.isEmpty)(r))return{kept:[]};let i=await this.tsAgent.getTestableFileMap(r),a=[];for(let e of r){let r=this.getEntriesForFile(e,i,t.projectRootPath);if(!(0,B.isDefined)(r)||(0,B.isEmpty)(r)){n.push({filePath:e,reason:`no-testables`});continue}this.processEntriesForFile(e,r,a,n)||n.push({filePath:e,reason:`no-testables`})}return{kept:a}}processEntriesForFile(e,t,n,r){let i=!1;for(let a of t){let{testable:t}=a;if(!t.canCreateTests||t.type===`class`)continue;if(i=!0,(0,B.isDefined)(a.testPath)){r.push({filePath:e,testableName:t.name,reason:`has-test-file`});continue}let o=e.startsWith(`/`)?e.slice(1):e;n.push({filePath:o,testable:t})}return i}getEntriesForFile(e,t,n){if((0,B.isDefined)(t[e]))return t[e];let r=uW.default.resolve(n,e);if((0,B.isDefined)(t[r]))return t[r]}};h2=aQ([et(),iQ(0,Ze(lW.TSAgent)),rQ(`design:paramtypes`,[Object])],h2);var Fte,g2,_2,v2,y2,b2,x2;function Ite(e,t){return{async execute(n,r,i){return e(r)?t.execute(n,r,i):{kept:n}}}}let S2=class{filters;constructor(e,t,n,r,i,a,o,s){this.configService=e,this.tsAgent=t,this.fileNameFilter=n,this.projectRootFilter=r,this.testableMapFilter=i,this.changedMethodsFilter=a,this.coverageFilter=o,this.limitFilter=s,this.filters=[this.fileNameFilter,this.projectRootFilter,this.testableMapFilter,Ite(e=>e.changedMethodsOnly&&e.hasDiffContext,this.changedMethodsFilter),this.coverageFilter,this.limitFilter]}async getTestablesToGenerate(e){let t={rootPath:e.rootPath,projectRootPath:e.rootPath,gitTopLevel:e.gitTopLevel,changedMethodsOnly:e.changedMethodsOnly??!1,hasDiffContext:e.hasDiffContext,baseRevision:e.baseRevision,coverageReport:e.coverageReport};return this.runPipeline([...e.changedFiles],t)}async runPipeline(e,t){let n=[],r=e,i=t.projectRootPath;for(let e of this.filters){let a={...t,projectRootPath:i},o=await e.execute(r,a,n);if((0,B.isDefined)(o.projectRootPath)&&!(0,B.isEmpty)(o.projectRootPath)&&(i=o.projectRootPath,this.tsAgent.updateRootPath(i),this.configService.updateConfigValue(`rootPath`,i)),(0,B.isEmpty)(o.kept))return{testables:[],filteredOut:n,projectRootPath:i};r=o.kept}return{testables:r,filteredOut:n,projectRootPath:i}}};S2=aQ([et(),iQ(0,Ze(cQ)),iQ(1,Ze(lW.TSAgent)),iQ(2,Ze(X0)),iQ(3,Ze(m2)),iQ(4,Ze(h2)),iQ(5,Ze(q0)),iQ(6,Ze(Y0)),iQ(7,Ze(Q0)),rQ(`design:paramtypes`,[typeof(Fte=cQ!==void 0&&cQ)==`function`?Fte:Object,Object,typeof(g2=X0!==void 0&&X0)==`function`?g2:Object,typeof(_2=m2!==void 0&&m2)==`function`?_2:Object,typeof(v2=h2!==void 0&&h2)==`function`?v2:Object,typeof(y2=q0!==void 0&&q0)==`function`?y2:Object,typeof(b2=Y0!==void 0&&Y0)==`function`?b2:Object,typeof(x2=Q0!==void 0&&Q0)==`function`?x2:Object])],S2);var C2=u(lH(),1);const w2=`axios-retry`;function T2(e){return e.response||!e.code||[`ERR_CANCELED`,`ECONNABORTED`].includes(e.code)?!1:(0,C2.default)(e)}const E2=[`get`,`head`,`options`],D2=E2.concat([`put`,`delete`]);function O2(e){return e.code!==`ECONNABORTED`&&(!e.response||e.response.status===429||e.response.status>=500&&e.response.status<=599)}function k2(e){return e.config?.method?O2(e)&&E2.indexOf(e.config.method)!==-1:!1}function A2(e){return e.config?.method?O2(e)&&D2.indexOf(e.config.method)!==-1:!1}function j2(e){return T2(e)||A2(e)}function M2(e=void 0){let t=e?.response?.headers[`retry-after`];if(!t)return 0;let n=(Number(t)||0)*1e3;return n===0&&(n=(new Date(t).valueOf()||0)-Date.now()),Math.max(0,n)}function Lte(e=0,t=void 0){return Math.max(0,M2(t))}function N2(e=0,t=void 0,n=100){let r=2**e*n,i=Math.max(r,M2(t));return i+i*.2*Math.random()}function Rte(e=100){return(t=0,n=void 0)=>{let r=t*e;return Math.max(r,M2(n))}}const zte={retries:3,retryCondition:j2,retryDelay:Lte,shouldResetTimeout:!1,onRetry:()=>{},onMaxRetryTimesExceeded:()=>{},validateResponse:null};function P2(e,t){return{...zte,...t,...e[w2]}}function F2(e,t,n=!1){let r=P2(e,t||{});return r.retryCount=r.retryCount||0,(!r.lastRequestTime||n)&&(r.lastRequestTime=Date.now()),e[w2]=r,r}function I2(e,t){e.defaults.agent===t.agent&&delete t.agent,e.defaults.httpAgent===t.httpAgent&&delete t.httpAgent,e.defaults.httpsAgent===t.httpsAgent&&delete t.httpsAgent}async function L2(e,t){let{retries:n,retryCondition:r}=e,i=(e.retryCount||0)<n&&r(t);if(typeof i==`object`)try{return await i!==!1}catch{return!1}return i}async function R2(e,t,n,r){t.retryCount+=1;let{retryDelay:i,shouldResetTimeout:a,onRetry:o}=t,s=i(t.retryCount,n);if(I2(e,r),!a&&r.timeout&&t.lastRequestTime){let e=Date.now()-t.lastRequestTime,i=r.timeout-e-s;if(i<=0)return Promise.reject(n);r.timeout=i}return r.transformRequest=[e=>e],await o(t.retryCount,n,r),r.signal?.aborted?Promise.resolve(e(r)):new Promise(t=>{let n=()=>{clearTimeout(i),t(e(r))},i=setTimeout(()=>{t(e(r)),r.signal?.removeEventListener&&r.signal.removeEventListener(`abort`,n)},s);r.signal?.addEventListener&&r.signal.addEventListener(`abort`,n,{once:!0})})}async function z2(e,t){e.retryCount>=e.retries&&await e.onMaxRetryTimesExceeded(t,e.retryCount)}const B2=(e,t)=>({requestInterceptorId:e.interceptors.request.use(e=>(F2(e,t,!0),e[w2]?.validateResponse&&(e.validateStatus=()=>!1),e)),responseInterceptorId:e.interceptors.response.use(null,async n=>{let{config:r}=n;if(!r)return Promise.reject(n);let i=F2(r,t);return n.response&&i.validateResponse?.(n.response)?n.response:await L2(i,n)?R2(e,i,n,r):(await z2(i,n),Promise.reject(n))})});B2.isNetworkError=T2,B2.isSafeRequestError=k2,B2.isIdempotentRequestError=A2,B2.isNetworkOrIdempotentRequestError=j2,B2.exponentialDelay=N2,B2.linearDelay=Rte,B2.isRetryableError=O2;const V2=Error(`request for lock canceled`);var H2=function(e,t,n,r){function i(e){return e instanceof n?e:new n(function(t){t(e)})}return new(n||=Promise)(function(n,a){function o(e){try{c(r.next(e))}catch(e){a(e)}}function s(e){try{c(r.throw(e))}catch(e){a(e)}}function c(e){e.done?n(e.value):i(e.value).then(o,s)}c((r=r.apply(e,t||[])).next())})},U2=class{constructor(e,t=V2){this._value=e,this._cancelError=t,this._queue=[],this._weightedWaiters=[]}acquire(e=1,t=0){if(e<=0)throw Error(`invalid weight ${e}: must be positive`);return new Promise((n,r)=>{let i={resolve:n,reject:r,weight:e,priority:t},a=W2(this._queue,e=>t<=e.priority);a===-1&&e<=this._value?this._dispatchItem(i):this._queue.splice(a+1,0,i)})}runExclusive(e){return H2(this,arguments,void 0,function*(e,t=1,n=0){let[r,i]=yield this.acquire(t,n);try{return yield e(r)}finally{i()}})}waitForUnlock(e=1,t=0){if(e<=0)throw Error(`invalid weight ${e}: must be positive`);return this._couldLockImmediately(e,t)?Promise.resolve():new Promise(n=>{this._weightedWaiters[e-1]||(this._weightedWaiters[e-1]=[]),Bte(this._weightedWaiters[e-1],{resolve:n,priority:t})})}isLocked(){return this._value<=0}getValue(){return this._value}setValue(e){this._value=e,this._dispatchQueue()}release(e=1){if(e<=0)throw Error(`invalid weight ${e}: must be positive`);this._value+=e,this._dispatchQueue()}cancel(){this._queue.forEach(e=>e.reject(this._cancelError)),this._queue=[]}_dispatchQueue(){for(this._drainUnlockWaiters();this._queue.length>0&&this._queue[0].weight<=this._value;)this._dispatchItem(this._queue.shift()),this._drainUnlockWaiters()}_dispatchItem(e){let t=this._value;this._value-=e.weight,e.resolve([t,this._newReleaser(e.weight)])}_newReleaser(e){let t=!1;return()=>{t||(t=!0,this.release(e))}}_drainUnlockWaiters(){if(this._queue.length===0)for(let e=this._value;e>0;e--){let t=this._weightedWaiters[e-1];t&&(t.forEach(e=>e.resolve()),this._weightedWaiters[e-1]=[])}else{let e=this._queue[0].priority;for(let t=this._value;t>0;t--){let n=this._weightedWaiters[t-1];if(!n)continue;let r=n.findIndex(t=>t.priority<=e);(r===-1?n:n.splice(0,r)).forEach((e=>e.resolve()))}}}_couldLockImmediately(e,t){return(this._queue.length===0||this._queue[0].priority<t)&&e<=this._value}};function Bte(e,t){let n=W2(e,e=>t.priority<=e.priority);e.splice(n+1,0,t)}function W2(e,t){for(let n=e.length-1;n>=0;n--)if(t(e[n]))return n;return-1}var G2=function(e,t,n,r){function i(e){return e instanceof n?e:new n(function(t){t(e)})}return new(n||=Promise)(function(n,a){function o(e){try{c(r.next(e))}catch(e){a(e)}}function s(e){try{c(r.throw(e))}catch(e){a(e)}}function c(e){e.done?n(e.value):i(e.value).then(o,s)}c((r=r.apply(e,t||[])).next())})},K2=class{constructor(e){this._semaphore=new U2(1,e)}acquire(){return G2(this,arguments,void 0,function*(e=0){let[,t]=yield this._semaphore.acquire(1,e);return t})}runExclusive(e,t=0){return this._semaphore.runExclusive(()=>e(),1,t)}isLocked(){return this._semaphore.isLocked()}waitForUnlock(e=0){return this._semaphore.waitForUnlock(1,e)}release(){this._semaphore.isLocked()&&this._semaphore.release()}cancel(){return this._semaphore.cancel()}};new TextEncoder;const q2=new TextDecoder;function J2(e){if(Uint8Array.fromBase64)return Uint8Array.fromBase64(e);let t=atob(e),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n}function Y2(e){if(Uint8Array.fromBase64)return Uint8Array.fromBase64(typeof e==`string`?e:q2.decode(e),{alphabet:`base64url`});let t=e;t instanceof Uint8Array&&(t=q2.decode(t)),t=t.replace(/-/g,`+`).replace(/_/g,`/`).replace(/\s/g,``);try{return J2(t)}catch{throw TypeError(`The input to be decoded is not correctly encoded.`)}}var X2=class extends Error{static code=`ERR_JOSE_GENERIC`;code=`ERR_JOSE_GENERIC`;constructor(e,t){super(e,t),this.name=this.constructor.name,Error.captureStackTrace?.(this,this.constructor)}},Z2=class extends X2{static code=`ERR_JWT_INVALID`;code=`ERR_JWT_INVALID`};Symbol.asyncIterator;function Q2(e){return typeof e==`object`&&!!e}var $2=e=>{if(!Q2(e)||Object.prototype.toString.call(e)!==`[object Object]`)return!1;if(Object.getPrototypeOf(e)===null)return!0;let t=e;for(;Object.getPrototypeOf(t)!==null;)t=Object.getPrototypeOf(t);return Object.getPrototypeOf(e)===t};function e4(e){if(typeof e!=`string`)throw new Z2(`JWTs must use Compact JWS serialization, JWT must be a string`);let{1:t,length:n}=e.split(`.`);if(n===5)throw new Z2(`Only JWTs using Compact JWS serialization can be decoded`);if(n!==3)throw new Z2(`Invalid JWT`);if(!t)throw new Z2(`JWTs must contain a payload`);let r;try{r=Y2(t)}catch{throw new Z2(`Failed to base64url decode the payload`)}let i;try{i=JSON.parse(q2.decode(r))}catch{throw new Z2(`Failed to parse the decoded payload as JSON`)}if(!$2(i))throw new Z2(`Invalid JWT Claims Set`);return i}const t4=e=>{let t=e4(e).exp;return(0,B.isDefined)(t)?t*1e3:null},n4=e=>{if(!(0,B.isDefined)(e))return!0;let t=t4(e);return(0,B.isDefined)(t)?t>Date.now():!0};let r4=class{jwtToken=null;refreshTokenCallback=null;observer=new B.Observer;refreshTokenMutex=new K2;setJWTToken(e){this.jwtToken=e,this.observer.notifyAll(e)}async getJWTToken(){return(0,B.isDefined)(this.jwtToken)?(this.isTokenValid()||await this.refreshTokenMutex.runExclusive(async()=>{if((0,B.isDefined)(this.refreshTokenCallback))return await this.refreshTokenCallback(),this.jwtToken}),this.jwtToken):null}onJWTTokenSave(e){this.observer.addListener(e)}isTokenValid(){return n4(this.jwtToken)}setRefreshTokenCallback(e){this.refreshTokenCallback=e}};r4=aQ([et(`Singleton`)],r4);var i4,a4;let o4=class{axiosInstance;constructor(e,t,n){this.configService=e,this.authStorage=t,this.logger=n,this.configService=e,this.axiosInstance=k0.create({baseURL:this.configService.getConfigValueOrThrow(`backendURL`),headers:{"Content-Type":`application/json`}}),B2(this.axiosInstance,{retries:3,retryDelay:B2.exponentialDelay,retryCondition:e=>k0.isAxiosError(e)&&B2.isNetworkOrIdempotentRequestError(e)||k0.isAxiosError(e)&&e.response?.status!==void 0&&e.response.status>=500||!1})}async getAuthHeaders(){let e={"x-request-source":cW.RequestSource.CLI},t=await this.authStorage.getJWTToken();return(0,B.isDefined)(t)&&(e.authorization=`Bearer ${t}`),e}async apiCall({url:e,method:t,data:n,config:r}){let i=new L0(await this.getAuthHeaders());if(r?.headers)for(let[e,t]of Object.entries(r.headers))i.set(e,t);let a={...r,method:t,url:e,data:n,headers:i};try{return await this.axiosInstance.request(a)}catch(t){this.handleError(e,t)}}async get(e,t){return(await this.apiCall({url:e,method:`GET`,config:t})).data}async post(e,t,n){return(await this.apiCall({url:e,method:`POST`,data:t,config:n})).data}async put(e,t,n){return(await this.apiCall({url:e,method:`PUT`,data:t,config:n})).data}async delete(e,t){return(await this.apiCall({url:e,method:`DELETE`,config:t})).data}async patch(e,t,n){return(await this.apiCall({url:e,method:`PATCH`,data:t,config:n})).data}async head(e,t){return this.apiCall({url:e,method:`HEAD`,config:t})}async options(e,t){return this.apiCall({url:e,method:`OPTIONS`,config:t})}handleCustomErrors(e,t){if(e===R0.Conflict){if(t===`workflow_is_cancelled`)throw this.logger.warn(`Agent flow canceled`),new W0(R0.Conflict,t);if(t===`duplicated_by_sha_workflow`)throw this.logger.warn(`Duplicated SHA workflow`),new G0(R0.Conflict,t)}}handleError(e,t){if(k0.isAxiosError(t))if((0,B.isDefined)(t.response)){let{status:e,statusText:n,data:r}=t.response;throw this.handleCustomErrors(e,r.message),new U0(e,`API request failed: ${e} ${n} - ${JSON.stringify(r)}`)}else if((0,B.isDefined)(t.request))throw Error(`API request failed: No response received from ${e}`);else throw Error(`API request failed: ${t instanceof Error?t.message:`Unknown error`}`);else if(t instanceof Error)throw TypeError(`API request failed: ${t.message}`);else throw TypeError(`API request failed: Unknown error occurred`)}};o4=aQ([et(),iQ(0,Ze(cQ)),iQ(1,Ze(r4)),iQ(2,Ze(sQ)),rQ(`design:paramtypes`,[typeof(i4=cQ!==void 0&&cQ)==`function`?i4:Object,typeof(a4=r4!==void 0&&r4)==`function`?a4:Object,Object])],o4);var s4,c4,l4;let u4=class{constructor(e,t,n){this.configService=e,this.apiService=t,this.authStorage=n,this.authStorage.setRefreshTokenCallback(async()=>{await this.login()})}async login(){let e=this.configService.getConfigValueOrThrow(`secretToken`,`API key is required but not configured`);try{let{idToken:t}=await this.apiService.post(`auth/v2/sign-in-with-secret-token`,{secret:e});return this.authStorage.setJWTToken(t),t}catch{throw Error(`Failed to get JWT token by secret`)}}};u4=aQ([et(),iQ(0,Ze(cQ)),iQ(1,Ze(o4)),iQ(2,Ze(r4)),rQ(`design:paramtypes`,[typeof(s4=cQ!==void 0&&cQ)==`function`?s4:Object,typeof(c4=o4!==void 0&&o4)==`function`?c4:Object,typeof(l4=r4!==void 0&&r4)==`function`?l4:Object])],u4);let d4=function(e){return e.PR=`PR`,e.COMMIT=`COMMIT`,e.PROJECT=`PROJECT`,e.COVERAGE=`COVERAGE`,e}({});var f4,p4;let m4=class{constructor(e,t){this.apiService=e,this.configService=t}mapCommandToType(e){switch(e){case dW.PR:return d4.PR;case dW.COMMIT:return d4.COMMIT;case dW.PROJECT:return d4.PROJECT;case dW.COVERAGE:return d4.COVERAGE}}async logStartOperation(e){let t=this.configService.getConfig(),n={type:this.mapCommandToType(t.command),owner:e.owner,repo:e.repository,sourceRef:e.ref_name,commitSha:e.sha,commitDate:e.commitDate,traceId:this.configService.getConfigValue(`traceId`),config:this.configService.maskedConfig(),operationStartedAt:new Date().toISOString(),version:t.cliVersion};return(await this.apiService.post(`api/v1/workflows/open`,n)).id}async logEndOperation(e,t,n,r){await this.apiService.patch(`api/v1/workflows/close/${e}`,{operationEndedAt:new Date().toISOString(),failureReason:t,runOutput:n,resultCommitSha:r})}async saveCoverageToWorkflow(e,t,{coverage:n,prCoverage:r,methodsAffected:i,committedFiles:a}){await this.apiService.patch(`api/v1/workflows/${e}/coverage`,{type:t,coverage:n,prCoverage:r,methodsAffected:i,committedFiles:a})}async getCoverageFromWorkflowOrUndefined(e){if(!this.configService.getConfigValue(`reuseCoverage`)||!(0,B.isDefined)(e))return;let t=this.configService.getConfigValue(`reuseCoverageMaxRuns`),n=await this.apiService.post(`api/v1/workflows/${e}/reuse-coverage`,{limit:t});if((0,B.isDefined)(n.coverageBefore))return n.coverageBefore}};m4=aQ([et(),iQ(0,Ze(o4)),iQ(1,Ze(cQ)),rQ(`design:paramtypes`,[typeof(f4=o4!==void 0&&o4)==`function`?f4:Object,typeof(p4=cQ!==void 0&&cQ)==`function`?p4:Object])],m4);var h4;let g4=class{constructor(e,t){this.tsAgent=e,this.logger=t}async analyzeChangedMethods(e,t,n){try{this.logger.info(`Analyzing coverage for ${t.length} changed methods with threshold ${n.coverageThreshold}%`);let r=[],i=0,a=0,o=0,s=this.groupChangedMethodsByFile(t);for(let[t,c]of Object.entries(s)){let s=this.findFileCoverage(e,t);if((0,B.isDefined)(s)){let e=this.processFileWithCoverage(t,c,s,n);r.push(...e.testables),i+=e.analyzed,a++}else{let e=this.processFileWithoutCoverage(t,c);r.push(...e.testables),i+=e.analyzed,o++}}let c={testables:r,totalAnalyzed:i,filteredCount:r.length,filesWithCoverage:a,filesWithoutCoverage:o};return this.logger.info(`Changed methods analysis complete: ${c.filteredCount}/${c.totalAnalyzed} methods below threshold across ${a+o} files`),c}catch(e){throw e instanceof Error?(this.logger.error(`Failed to analyze changed methods: ${e.message}`),e):Error(`Unknown error occurred while analyzing changed methods`)}}processFileWithCoverage(e,t,n,r){let i=[],a=0;for(let o of t){if(o.changeType===`deleted`||!o.canCreateTests)continue;let t=this.findTestableInCoverage(n,o);(0,B.isDefined)(t)?(a++,this.shouldIncludeTestable(t,r)&&i.push({name:t.name,percentage:t.percentage,filePath:e,reason:this.getFilterReason(t)})):(a++,i.push({name:o.name??`unknown`,percentage:null,filePath:e,reason:`no-coverage`}))}return{testables:i,analyzed:a}}processFileWithoutCoverage(e,t){let n=t.filter(e=>e.changeType!==`deleted`&&e.canCreateTests),r=n.map(t=>({name:t.name??`unknown`,percentage:null,filePath:e,reason:`no-coverage`}));return this.logger.debug(`No coverage data found for file: ${e}`),{testables:r,analyzed:n.length}}async analyzeChangedFiles(e,t,n){try{this.logger.info(`Analyzing coverage for ${t.length} changed files with threshold ${n.coverageThreshold}%`);let r=[],i=0,a=0,o=0;for(let s of t){let t=this.findFileCoverage(e,s);if((0,B.isDefined)(t)){a++;let e=await this.filterOutClasses(s,t.testables??[]),o=this.filterTestablesForFile(t,s,n),c=await this.filterOutClasses(s,o);r.push(...c),i+=e.length??0,(0,B.isEmpty)(c)||this.logger.debug(`File ${s}: ${c.length}/${e.length??0} testables below threshold`)}else o++,this.logger.debug(`No coverage data found for file: ${s}`)}let s={testables:r,totalAnalyzed:i,filteredCount:r.length,filesWithCoverage:a,filesWithoutCoverage:o};return this.logger.info(`Coverage analysis complete: ${s.filteredCount}/${s.totalAnalyzed} testables below threshold across ${s.filesWithCoverage} files`),s}catch(e){throw e instanceof Error?(this.logger.error(`Failed to analyze coverage: ${e.message}`),e):Error(`Unknown error occurred while analyzing coverage`)}}findFileCoverage(e,t){let n=t.startsWith(`/`)?t:`/${t}`;return(0,B.isDefined)(e[n])?e[n]:null}filterTestablesForFile(e,t,n){let r=[];for(let i of e.testables??[])if(this.shouldIncludeTestable(i,n)){let e=this.getFilterReason(i);r.push({name:i.name,percentage:i.percentage,filePath:t,reason:e})}return r}shouldIncludeTestable(e,t){return!!(e.percentage===null||e.percentage===0||(0,B.isDefined)(e.percentage)&&e.percentage<t.coverageThreshold)}getFilterReason(e){return e.percentage===null?`no-coverage`:e.percentage===0?`zero-coverage`:`below-threshold`}async calculatePRCoverage(e,t){if(!(0,B.isEmpty)(e))try{let n=await this.tsAgent.getCoverageForFiles(e),r=t?`before`:`after`;return this.logger.debug(`PR Coverage (${r}): ${n.percentage}% (${n.coveredStatements}/${n.totalStatements} statements)`),n}catch(e){this.logger.warn(`Failed to calculate PR coverage: ${e instanceof Error?e.message:`Unknown error`}`);return}}async filterOutClasses(e,t){let n=await this.tsAgent.getTestables(e);if((0,B.isEmpty)(n)||!(0,B.isDefined)(n[0]))return this.logger.warn(`getTestables returned empty for ${e}, keeping all testables`),t;let[,r]=n[0],i=r.filter(e=>e.type!==`class`),a=new Set(i.map(e=>e.name));return t.filter(e=>a.has(e.name))}groupChangedMethodsByFile(e){let t={};for(let n of e)(0,B.isDefined)(t[n.filePath])||(t[n.filePath]=[]),t[n.filePath].push(n);return t}findTestableInCoverage(e,t){return(0,B.isDefined)(e.testables)?e.testables.find(e=>{let n=e.name===t.name,r=`parentName`in e?e.parentName===t.parentName:!(0,B.isDefined)(t.parentName);return n&&r})??null:null}};g4=aQ([et(),iQ(0,Ze(lW.TSAgent)),iQ(1,Ze(sQ)),rQ(`design:paramtypes`,[typeof(h4=cW.TSAgent!==void 0&&cW.TSAgent)==`function`?h4:Object,Object])],g4);function _4(e,t){return t2(e,`package.json`,t)??void 0}function v4(e,t){try{return m.default.existsSync(e)?m.default.readFileSync(e,`utf8`):void 0}catch(n){t.warn(`Failed to read file ${e}: ${n instanceof Error?n.message:`Unknown error`}`);return}}async function y4(e,t,n){let r=_4(e,t),i=(await(0,cW.findLintConfigPath)(t)).path??void 0,a=(0,B.isDefined)(r)?v4(r,n):void 0,o=(0,B.isDefined)(i)?v4(i,n):void 0;return(0,B.isDefined)(r)&&n.info(`Found package.json at: ${r}`),(0,B.isDefined)(i)&&n.info(`Found lint config at: ${i}`),{packageJsonPath:r,packageJsonContent:a,lintConfigPath:i,lintConfigContent:o}}const b4={detectProjectConfigs:y4};var x4,S4;let C4=class{constructor(e,t,n){this.apiService=e,this.configService=t,this.logger=n}async detectAndSaveConfigs(e){try{let t=this.configService.getConfigValue(`rootPath`),n=await b4.detectProjectConfigs(t,t,this.logger);if(!(0,B.isDefined)(n.packageJsonContent)&&!(0,B.isDefined)(n.lintConfigContent))return;await this.apiService.patch(`api/v1/github-repos/configs`,{owner:e.owner,repo:e.repository,packageJson:n.packageJsonContent,lintConfig:n.lintConfigContent})}catch(e){this.logger.warn(`Failed to detect and save project configs: ${e instanceof Error?e.message:`Unknown error`}`)}}};C4=aQ([et(),iQ(0,Ze(o4)),iQ(1,Ze(cQ)),iQ(2,Ze(sQ)),rQ(`design:paramtypes`,[typeof(x4=o4!==void 0&&o4)==`function`?x4:Object,typeof(S4=cQ!==void 0&&cQ)==`function`?S4:Object,Object])],C4);var Vte,w4,T4,E4,D4,O4,k4,A4,j4;let M4=class{workflowRunId;initialCoverageTree;resultCommitSha;constructor(e,t,n,r,i,a,o,s,c,l){this.configService=e,this.authService=t,this.gitService=n,this.coverageAnalysisService=r,this.summaryService=i,this.tsAgent=a,this.workflowService=o,this.scmHostService=s,this.repoConfigService=c,this.logger=l}async login(){try{this.logger.info(`Trying login to API...`);let e=await this.authService.login();await this.tsAgent.init(e),this.logger.info(`Successfully authenticated with the API`)}catch(e){throw this.logger.error(`Failed to authenticate:`+(e instanceof Error?e.message:`Unknown error`)),e}}async logStart(){try{let e=await this.gitService.getGitInfo();this.logger.debug(`Git info: `+JSON.stringify(e));try{let t=await this.workflowService.logStartOperation(e);return this.tsAgent.updateContext({git:{...e,workflowRunId:t}}),this.workflowRunId=t,await this.repoConfigService.detectAndSaveConfigs(e),t}catch(e){throw e instanceof G0||e instanceof W0||this.logger.warn(`Failed to log start operation: ${e instanceof Error?e.message:`Unknown error`}`),e}}catch(e){throw e instanceof G0||e instanceof W0||this.logger.error(`Failed to retrieve git info or log start operation:`+(e instanceof Error?e.message:`Unknown error`)),e}}async generateInitialCoverage(){this.logger.verbose(`Try to reuse coverage...`);let e=await this.workflowService.getCoverageFromWorkflowOrUndefined(this.workflowRunId);if((0,B.isDefined)(e))return await this.tsAgent.setCoverage(e),this.initialCoverageTree=e,(0,B.isDefined)(this.workflowRunId)&&await this.workflowService.saveCoverageToWorkflow(this.workflowRunId,`before`,{}),this.logger.verbose(`Reused coverage: `+(e[`/`]?.percentage??0)+`%`),this.summaryService.setCoverageData(e[`/`]?.percentage??0,e[`/`]?.percentage??0),e;{this.logger.verbose(`Generating initial coverage...`),await this.tsAgent.generateCoverage();let e=await this.tsAgent.getCoverageTree();if(!(0,B.isDefined)(e))throw Error(`Failed to generate initial coverage tree`);return this.initialCoverageTree=e,(0,B.isDefined)(this.workflowRunId)&&await this.workflowService.saveCoverageToWorkflow(this.workflowRunId,`before`,{coverage:e}),this.logger.verbose(`Initial coverage: `+(e[`/`]?.percentage??0)+`%`),this.summaryService.setCoverageData(e[`/`]?.percentage??0,e[`/`]?.percentage??0),e}}async logEndOperation(e){if((0,B.isDefined)(this.workflowRunId))try{let t=this.summaryService.getWorkflowRunOutput();await this.workflowService.logEndOperation(this.workflowRunId,e,t,this.resultCommitSha),this.logger.info(`Successfully logged workflow end`)}catch(e){this.logger.warn(`Failed to log workflow end: `+(e instanceof Error?e.message:`Unknown error`))}}getWorkflowRunIdOrThrow(){if(!(0,B.isDefined)(this.workflowRunId))throw Error(`Workflow run ID is not set, call logStart() first`);return this.workflowRunId}getInitialCoverageTreeOrThrow(){if(!(0,B.isDefined)(this.initialCoverageTree))throw Error(`Initial coverage tree is not set, call generateInitialCoverage() first`);return this.initialCoverageTree}getInitialCoverageTreeOrUndefined(){return this.initialCoverageTree}async countAllMethodsInFiles(e){let t=(0,B.uniq)(e).map(async e=>{try{return await this.tsAgent.getAllMethodsCount(e)}catch(t){return this.logger.debug(`Failed to count methods in `+e+`: `+(t instanceof Error?t.message:`Unknown error`)),0}});return(await Promise.all(t)).reduce((e,t)=>e+t,0)}};M4=aQ([et(),iQ(0,Ze(cQ)),iQ(1,Ze(u4)),iQ(2,Ze(xQ)),iQ(3,Ze(g4)),iQ(4,Ze(uQ)),iQ(5,Ze(lW.TSAgent)),iQ(6,Ze(m4)),iQ(7,Ze(lW.SCMHostService)),iQ(8,Ze(C4)),iQ(9,Ze(sQ)),rQ(`design:paramtypes`,[typeof(Vte=cQ!==void 0&&cQ)==`function`?Vte:Object,typeof(w4=u4!==void 0&&u4)==`function`?w4:Object,typeof(T4=xQ!==void 0&&xQ)==`function`?T4:Object,typeof(E4=g4!==void 0&&g4)==`function`?E4:Object,typeof(D4=uQ!==void 0&&uQ)==`function`?D4:Object,typeof(O4=cW.TSAgent!==void 0&&cW.TSAgent)==`function`?O4:Object,typeof(k4=m4!==void 0&&m4)==`function`?k4:Object,typeof(A4=hQ!==void 0&&hQ)==`function`?A4:Object,typeof(j4=C4!==void 0&&C4)==`function`?j4:Object,Object])],M4);var N4;let P4=class extends M4{changedFiles=[];prCoverage={before:{percentage:null,totalStatements:0,coveredStatements:0},after:{percentage:null,totalStatements:0,coveredStatements:0}};testableToGenerateService;getWorkflowRunId(){return this.workflowRunId}async runFlow(e){let t=e?.shouldDeferPostGeneration??!1,n,r=!1,i;try{await this.login(),await this.logStart();let e=await this.getRawChangedFiles(),n=this.configService.getConfigValue(`rootPath`),r=this.configService.getConfigValue(`gitTopLevel`)??n;this.logger.info(`Discovering untested functions`);let a=await this.testableToGenerateService.getTestablesToGenerate({changedFiles:e,rootPath:n,gitTopLevel:r,hasDiffContext:this.hasDiffContext(),baseRevision:await this.getBaseRevision(),changedMethodsOnly:this.configService.getConfigValue(`changedMethodsOnly`),coverageReport:{tree:this.initialCoverageTree,threshold:this.configService.getConfigValue(`coverageThreshold`)}});if((0,B.isEmpty)(a.testables)){this.logFilteredOutTestables(a.filteredOut),this.handleNoFilteredTestables();return}if(this.updateRootPath(a.projectRootPath),this.changedFiles=a.testables.map(e=>e.filePath),await this.setSummaryChangedFilesData(e.length,a),a.filteredOut.filter(e=>e.reason===`limit-reached`).length>0){let e=this.configService.getConfigValue(`maxTestables`);this.summaryService.addWarning(`Limited to ${e} functions: test generation was capped due to maximum function limit.`)}this.logFilteredOutTestables(a.filteredOut),this.logTestablesToGenerate([...a.testables]);let o=[...a.testables];if(i=await this.generateTests(o),!t){let e=await this.performAutoCommit();this.summaryService.setTestGenerationData({generated:i.generated,succeeded:i.succeeded,failed:i.failed,successMethodsCount:i.successMethodsCount,committedFilesCount:e,greenTests:i.greenTests,redTests:i.redTests}),this.configService.getConfigValue(`skipCoverageAfter`)?(this.logger.verbose(`Skipping final coverage generation (--skip-coverage-after flag is set)`),this.summaryService.setCoverageSkipped()):await this.generateFinalCoverageAndLog({methodsAffected:o.length,committedFiles:e})}return i}catch(e){if(e instanceof G0){this.logger.warn(`Duplicate SHA execution detected. Skipping.`);return}if(e instanceof W0){this.logger.warn(`Workflow canceled. Skipping.`),r=!0;return}throw n=e instanceof Error?e.message:`Unknown error`,this.logger.error(`Agent flow failed: `+n),e}finally{!t&&(0,B.isDefined)(this.workflowRunId)&&!r&&(this.summaryService.setPRCoverageData(this.prCoverage.before,this.prCoverage.after),await this.scmHostService.safePostSummaryToPr(),await this.logEndOperation(n))}}async setSummaryChangedFilesData(e,t){let n=[...new Set([...t.testables.map(e=>e.filePath),...t.filteredOut.map(e=>e.filePath)])],r=await this.countAllMethodsInFiles(n);this.summaryService.setChangedFilesData({changedFilesCount:e,candidateFilesCount:n.length,functionCount:r,publicMethodCount:t.testables.length,testablesToGenerateCount:t.testables.length,publicMethods:t.testables.map(e=>({name:e.testable.name??`unknown`,filePath:e.filePath})),methodsBelowCoverage:t.testables.map(e=>({name:e.testable.name??`unknown`,filePath:e.filePath}))})}handleNoFilteredTestables(){this.logger.warn(`No filtered untested functions`),this.prCoverage.after=this.prCoverage.before}logFilteredOutTestables(e){if((0,B.isEmpty)(e))return;let t=e.length,n=t===1?`item`:`items`;this.logger.verbose(t+` `+n+` skipped:`);for(let t of e){let e=(0,B.isDefined)(t.testableName)?t.testableName+` in `+t.filePath:t.filePath;this.logger.verbose(` - `+e+`: `+t.reason)}}logTestablesToGenerate(e){this.logger.info(`Found ${e.length} public function${e.length===1?``:`s`} without Early AI tests`);for(let t of e)this.logger.info(` `+t.testable.name+` in `+t.filePath)}async performAutoCommit(){let e=this.configService.getConfigValueOrThrow(`autoCommit`);if(this.summaryService.setAutoCommitStatus(e),e){let e=this.configService.getConfigValue(`refName`),t=await this.gitService.commitFiles(e);return(0,B.isDefined)(t.resultCommitSha)&&(this.resultCommitSha=t.resultCommitSha),t.committedFiles.length}else return this.logger.info(`Auto-commit is disabled - skipping commit step`),0}async _generateInitialCoverageForTestGeneration(){await this.generateInitialCoverage(),await this.savePRCoverageBefore()}async savePRCoverageBefore(){if((0,B.isDefined)(this.workflowRunId))try{let e=await this.coverageAnalysisService.calculatePRCoverage(this.changedFiles,!0);(0,B.isDefined)(e)&&(this.prCoverage.before=e),await this.workflowService.saveCoverageToWorkflow(this.workflowRunId,`before`,{prCoverage:e}),this.logger.debug(`Successfully saved initial coverage to workflow run`)}catch(e){this.logger.warn(`Failed to save initial coverage: `+(e instanceof Error?e.message:`Unknown error`))}}async generateTests(e){let t=new Set(e),n=0,r=0,i=0,a=0;await this.tsAgent.bulkGenerateTests(e,(o,s)=>{a++;let c=uW.default.basename(o.filePath);(0,B.isDefined)(s)&&s.greenTestsCount>0?(t.delete(o),n+=s.greenTestsCount,r+=s.redTestsCount,i+=s.greyTestsCount,this.logger.info(` [${a}/${e.length}] ✓ ${o.testable.name} (${c}) — ${s.greenTestsCount} passing, ${s.redTestsCount} skipped`)):this.logger.info(` [${a}/${e.length}] ✗ ${o.testable.name} (${c}) — no tests generated`)});let o=e.length-t.size,s=t.size,c=await this.gitService.getEarlyFiles();return this.logger.info(``),this.logger.info(`✅ Test generation complete for ${o} functions`),s>0&&this.logger.info(`❌ ${s} functions were not generated`),this.logger.info(``),this.logger.info(`================`),this.logger.info(`Overall summary:`),this.logger.info(`================`),this.logger.info(``),this.logger.info(`✅ ${n} tests passing`),this.logger.info(`⚠️ ${r} tests skipped`),this.logger.info(`❌ ${i} tests could not be fixed autonomously (yet)`),this.logger.info(``),{generated:e.length,succeeded:o,failed:s,successMethodsCount:c.length,greenTests:n,redTests:r}}async generateFinalCoverageAndLog({methodsAffected:e,committedFiles:t}){let n=this.getWorkflowRunIdOrThrow();this.logger.verbose(`Generating final coverage...`),await this.tsAgent.generateCoverage();let r=await this.tsAgent.getCoverageTree();if(!(0,B.isDefined)(r))throw Error(`Failed to generate final coverage tree`);let i=r[`/`]?.percentage??0,a=this.getInitialCoverageTreeOrUndefined(),o=a?.[`/`]?.percentage??0;(0,B.isDefined)(a)||this.summaryService.setCoverageBeforeSkipped(),this.summaryService.setCoverageData(o,i);let s=(0,B.isDefined)(a)?`${o}% -> ${i}%`:`skipped`;this.logger.verbose(`Final coverage: `+i+`%, Coverage comparison: `+s);try{let i=await this.coverageAnalysisService.calculatePRCoverage(this.changedFiles,!1);(0,B.isDefined)(i)&&(this.prCoverage.after=i),await this.workflowService.saveCoverageToWorkflow(n,`after`,{coverage:r,prCoverage:i,methodsAffected:e,committedFiles:t}),this.logger.debug(`Successfully saved final coverage to workflow run`)}catch(e){this.logger.warn(`Failed to save final coverage: `+(e instanceof Error?e.message:`Unknown error`))}}updateRootPath(e){this.tsAgent.updateRootPath(e),this.configService.updateConfigValue(`rootPath`,e)}};aQ([Ze(S2),rQ(`design:type`,typeof(N4=S2!==void 0&&S2)==`function`?N4:Object)],P4.prototype,`testableToGenerateService`,void 0),P4=aQ([et(),st({extendConstructorArguments:!0,extendProperties:!0})],P4);let F4=class extends P4{async getRawChangedFiles(){return this.gitService.getChangedFilesForCommitWithStatus({absolute:!0})}hasDiffContext(){return!0}async getBaseRevision(){let e=this.configService.getConfigValue(`baseRef`);if((0,B.isDefined)(e))return this.gitService.getBaseRevision({baseBranch:e});let t=this.configService.getConfigValue(`commitHash`);if((0,B.isDefined)(t))return`${t}^`}async logStart(){try{let e=this.configService.getConfigValue(`commitHash`),t=await this.gitService.getCommitMessage(e);t&&this.configService.updateConfigValue(`commitName`,t)}catch(e){this.logger.warn(`Failed to retrieve commit message, continuing without it: `+(e instanceof Error?e.message:`Unknown error`))}try{let e=await this.scmHostService.getContributorAvatarUrl();(0,B.isDefined)(e)&&this.configService.updateConfigValue(`contributorAvatarUrl`,e)}catch(e){this.logger.warn(`Failed to retrieve contributor avatar, continuing without it: `+(e instanceof Error?e.message:`Unknown error`))}return await super.logStart()}};F4=aQ([et(),st({extendConstructorArguments:!0,extendProperties:!0})],F4);function Hte(e){let t=e.command(dW.COMMIT).alias(`generate-commit`).description(`Generate tests for the current project in commit context`);return ce(t,`--commit-hash <hash>`,`Commit hash`,{envName:`COMMIT_HASH`,isRequired:!0}),ce(t,`--ref-name <ref>`,`Head branch name for the commit`,{envName:`REF_NAME`,isRequired:!0}),ce(t,`--base-ref <ref>`,`optional base refrence for comparison`,{envName:`BASE_REF`}),ce(t,`-s, --test-structure <structure>`,`Test file structure`,{envName:`TEST_STRUCTURE`,def:`siblingFolder`}),ce(t,`-f, --test-framework <framework>`,`Test framework to use`,{envName:`TEST_FRAMEWORK`,def:`jest`}),ce(t,`--test-suffix <suffix>`,`Test file suffix`,{envName:`TEST_FILE_SUFFIX`,def:`test`}),ce(t,`--test-file-naming <naming>`,`Test file naming convention`,{envName:`TEST_FILE_NAMING`,def:`camelCase`}),ce(t,`-c, --max-concurrency <number>`,`Number of concurrent workers (1-4)`,{envName:`MAX_CONCURRENCY`,def:`3`}),ce(t,`--auto-commit <boolean>`,`Whether to auto-commit files`,{envName:`AUTO_COMMIT`,def:`true`}),ce(t,`--auto-commit-skip-ci <boolean>`,`Append [skip ci] to auto-commit message`,{envName:`AUTO_COMMIT_SKIP_CI`,def:`true`}),ce(t,`--test-command <command>`,`Custom test command to run`,{envName:`TEST_COMMAND`}),ce(t,`--coverage-command <command>`,`Custom coverage command to run`,{envName:`COVERAGE_COMMAND`}),ce(t,`--lint-command <command>`,`Custom lint command to run`,{envName:`LINT_COMMAND`}),ce(t,`--prettier-command <command>`,`Custom prettier command to run`,{envName:`PRETTIER_COMMAND`}),ce(t,`--disable-lint-rules <boolean>`,`Whether to disable failed lint rules in test files`,{envName:`DISABLE_LINT_RULES`,def:`false`}),ce(t,`--git-org <org>`,`Git organization name`,{envName:`GIT_ORG`}),ce(t,`--git-repo <repo>`,`Git repository name`,{envName:`GIT_REPO`}),ce(t,`--git-user-email <email>`,`Git user email for auto commit`,{envName:`GIT_USER_EMAIL`}),ce(t,`--git-user-name <name>`,`Git user name for auto commit`,{envName:`GIT_USER_NAME`}),ce(t,`--scm-provider <provider>`,`SCM provider (e.g., github, bitbucket)`,{envName:`SCM_PROVIDER`,def:`github`}),ce(t,`--keep-error-tests <boolean>`,`Whether to keep error tests`,{envName:`KEEP_ERROR_TESTS`,def:`false`}),ce(t,`--keep-failed-tests <boolean>`,`Whether to keep failed tests`,{envName:`KEEP_FAILED_TESTS`,def:`false`}),ce(t,`--conditional-keep <boolean>`,`Whether to return the last generated test result even when no green tests were produced`,{envName:`CONDITIONAL_KEEP`,def:`false`}),ce(t,`--continue-on-test-errors <boolean>`,`Whether to continue on test errors`,{envName:`CONTINUE_ON_TEST_ERRORS`,def:`false`}),ce(t,`--changed-methods-only <boolean>`,`Generate tests only for changed methods, not all methods in changed files`,{envName:`CHANGED_METHODS_ONLY`,def:`true`}),ce(t,`--skip-coverage-after <boolean>`,`Skip final coverage generation after test generation`,{envName:`SKIP_COVERAGE_AFTER`,def:`true`}),ce(t,`--max-testables <number>`,`Maximum number of testables to generate`,{envName:`MAX_TESTABLES`}),ce(t,`--per-function-timeout <number>`,`Per function timeout in milliseconds`,{envName:`PER_FUNCTION_TIMEOUT`}),ce(t,`--coverage-threshold <number>`,`Coverage threshold percentage (0-100)`,{envName:`COVERAGE_THRESHOLD`,def:`0`}),ce(t,`--reuse-coverage <boolean>`,`Whether to reuse coverage`,{envName:`REUSE_COVERAGE`,def:`false`}),ce(t,`--reuse-coverage-max-runs <number>`,`Max number of runs to reuse coverage (1-10)`,{envName:`REUSE_COVERAGE_MAX_RUNS`,def:`10`}),ce(t,`--experimental-agent-sdk <boolean>`,`Use experimental Agent SDK for test generation`,{envName:`EXPERIMENTAL_AGENT_SDK`,def:`true`}),t.addHelpText(`after`,`
|
|
32412
|
+
`)}extractMethodText(e,t){return t.slice(e.startIndex,e.endIndex)}createChangedMethod(e,t,n){return{name:t.name,type:t.type,parentName:`parentName`in t?t.parentName:void 0,changeType:n,filePath:e,canCreateTests:t.canCreateTests}}};K0=aQ([et(),iQ(0,Ze(sQ)),rQ(`design:paramtypes`,[Object])],K0);var jte,Mte,Nte;let q0=class{constructor(e,t,n,r){this.gitService=e,this.changedMethodsDetector=t,this.tsAgent=n,this.logger=r}async execute(e,t,n){if(!(0,B.isDefined)(t.baseRevision))return{kept:e};let r=[...new Set(e.map(e=>e.filePath))],i=await this.detectChangedMethods(r,t.baseRevision,t.projectRootPath),a=new Set(i.filter(e=>e.changeType!==`deleted`&&e.canCreateTests).map(e=>`${e.filePath}:${e.name}:${e.parentName??``}`)),o=[],s=[];for(let t of e){let e=`${t.filePath}:${t.testable.name}:${`parentName`in t.testable?t.testable.parentName??``:``}`;a.has(e)?o.push(t):s.push(t)}return{kept:[...o,...s]}}async detectChangedMethods(e,t,n){let r=await this.gitService.getTopLevel(),i=[];for(let a of e){let e=await this.detectChangedMethodsForFile(a,t,n,r);i.push(...e)}return i}async detectChangedMethodsForFile(e,t,n,r){let i=null;try{let a=uW.default.isAbsolute(e)?e:uW.default.join(n,e),o=uW.default.relative(r,a),s=await this.gitService.getFileAtRevision(o,t),c=await this.getBaseMethodsFromContent(s,a,n);(0,B.isDefined)(c.temporaryFilePath)&&(i=c.temporaryFilePath);let l=await this.getCurrentMethods(a),u=await g.readFile(a,`utf8`);return this.changedMethodsDetector.detectChanges(e,c.methods,l,s,u)}catch(t){this.logger.warn(`Failed to detect changed methods for `+e+`: `+(t instanceof Error?t.message:`Unknown error`)+`. Changed-function detection disabled for this file — all its functions will be treated as changed. Fix: add 'fetch-depth: 0' to your checkout step.`);try{let t=uW.default.isAbsolute(e)?e:uW.default.join(n,e);return(await this.getCurrentMethods(t)).map(t=>({filePath:e,name:t.name,type:t.type,parentName:`parentName`in t?t.parentName:void 0,changeType:`modified`,canCreateTests:t.canCreateTests}))}catch{return[]}}finally{await this.cleanupTemporaryFile(i)}}async getBaseMethodsFromContent(e,t,n){if(!(0,B.isDefined)(e)||(0,B.isEmpty)(e))return{methods:[],temporaryFilePath:null};let r=p.default.resolve(n,`.early-temp`);await g.mkdir(r,{recursive:!0});let i=p.default.join(r,`base-${Date.now()}-${p.default.basename(t)}`);await g.writeFile(i,e);let a=i.replaceAll(`\\`,`/`);return{methods:((await this.tsAgent.getTestables(a))[0]?.[1]??[]).filter(e=>e.canCreateTests&&e.type!==`class`),temporaryFilePath:i}}async getCurrentMethods(e){let t=e.replaceAll(`\\`,`/`);return((await this.tsAgent.getTestables(t))[0]?.[1]??[]).filter(e=>e.canCreateTests&&e.type!==`class`)}async cleanupTemporaryFile(e){if((0,B.isDefined)(e))try{await g.unlink(e)}catch{}}};q0=aQ([et(),iQ(0,Ze(xQ)),iQ(1,Ze(K0)),iQ(2,Ze(lW.TSAgent)),iQ(3,Ze(sQ)),rQ(`design:paramtypes`,[typeof(jte=xQ!==void 0&&xQ)==`function`?jte:Object,typeof(Mte=K0!==void 0&&K0)==`function`?Mte:Object,typeof(Nte=cW.TSAgent!==void 0&&cW.TSAgent)==`function`?Nte:Object,Object])],q0);var J0;let Y0=class{constructor(e){this.configService=e}async execute(e,t,n){let r=t.coverageReport?.tree,i=t.coverageReport?.threshold??this.configService.getConfigValue(`coverageThreshold`)??0;if(!(0,B.isDefined)(r))return{kept:e};let a=[];for(let t of e){let e=this.findFileCoverage(r,t.filePath);if(!(0,B.isDefined)(e?.testables)){a.push(t);continue}let o=t.testable.type===`method`?t.testable.parentName:void 0,s=e.testables.find(e=>e.name===t.testable.name&&((0,B.isDefined)(o)?e.parentName===o:!(0,B.isDefined)(e.parentName)));if(!(0,B.isDefined)(s)||!(0,B.isDefined)(s.percentage)){a.push(t);continue}if(s.percentage>i){n.push({filePath:t.filePath,testableName:t.testable.name,reason:`above-coverage-threshold`});continue}a.push(t)}return{kept:a}}findFileCoverage(e,t){return e[t.startsWith(`/`)?t:`/${t}`]??null}};Y0=aQ([et(),iQ(0,Ze(cQ)),rQ(`design:paramtypes`,[typeof(J0=cQ!==void 0&&cQ)==`function`?J0:Object])],Y0);let X0=class{async execute(e,t,n){let r=[];for(let i of e){let e=i.filePath.toLowerCase(),a=dQ.allowedExtensions.some(t=>e.endsWith(t)),o=uW.default.isAbsolute(i.filePath)?uW.default.relative(t.gitTopLevel,i.filePath):i.filePath;if(!a){n.push({filePath:o,reason:`not-code-file`});continue}if(dQ.excludePatterns.some(t=>e.includes(t.toLowerCase()))){n.push({filePath:o,reason:`excluded-pattern`});continue}r.push(i)}return{kept:r}}};X0=aQ([et()],X0);var Z0;let Q0=class{constructor(e){this.configService=e}async execute(e,t,n){let r=this.configService.getConfigValue(`maxTestables`)??1/0;if(e.length<=r)return{kept:e};let i=e.slice(0,r);for(let t=r;t<e.length;t++){let r=e[t];n.push({filePath:r.filePath,testableName:r.testable.name,reason:`limit-reached`})}return{kept:i}}};Q0=aQ([et(),iQ(0,Ze(cQ)),rQ(`design:paramtypes`,[typeof(Z0=cQ!==void 0&&cQ)==`function`?Z0:Object])],Q0);var $0=u(Uz());function e2(e,t){let n=uW.default.relative(e,t);return n===``||!n.startsWith(`..`)&&!uW.default.isAbsolute(n)}function t2(e,t,n){let r=uW.default.isAbsolute(e)&&e2(n,e)?e:uW.default.join(n,e),i=(0,$0.default)(t,{cwd:m.default.existsSync(r)&&m.default.statSync(r).isDirectory()?r:uW.default.dirname(r)});return i!==null&&!e2(n,i)?null:i}function Pte(e,t){let n=[t2(e,`package.json`,t),t2(e,`project.json`,t)].filter(B.isDefined).filter(e=>e2(t,e));if(n.length===0)return t;let r=n.reduce((e,t)=>e.length>t.length?e:t,n[0]);return uW.default.dirname(r)}const n2=[`pyproject.toml`,`setup.py`,`setup.cfg`,`requirements.txt`],r2=[`package.json`,`tsconfig.json`],i2=[`.py`],a2=[`.ts`,`.tsx`,`.js`,`.jsx`];function o2(e,t){return t.some(t=>e.endsWith(t))}function s2(e){if(o2(e,i2))return`python`;if(o2(e,a2))return`typescript`}function c2(e,t){if(e&&t)return`mixed`;if(e)return`python`;if(t)return`typescript`}function l2(e){let t=m.default.readdirSync(e,{recursive:!0});return c2(t.some(e=>o2(e,i2)),t.some(e=>o2(e,a2)))}function u2(e){return c2(n2.some(t=>m.default.existsSync(uW.default.join(e,t))),r2.some(t=>m.default.existsSync(uW.default.join(e,t))))}function d2(e,t){if(t!==void 0&&t!==``){let n=uW.default.isAbsolute(t)?t:uW.default.join(e,t);return m.default.existsSync(n)&&m.default.statSync(n).isFile()?s2(n):m.default.existsSync(n)&&m.default.statSync(n).isDirectory()?l2(n):s2(t)??u2(e)}return u2(e)}const f2={detectProjectRoot(e,t,n){if(t.length===0)return n.verbose(`No changed files provided, using root path`),e;let r=t[0],i=Pte(uW.default.isAbsolute(r)?r:uW.default.join(e,r),e);return i===uW.default.normalize(e)?(n.verbose(`Using workspace root path`),e):(n.info(`Detected nested project root: ${i} (from file: ${r})`),i)}};function p2(e,t){let n=uW.default.relative(e,t);return n!==``&&!n.startsWith(`..`)&&!uW.default.isAbsolute(n)}let m2=class{constructor(e){this.logger=e}async execute(e,t,n){if((0,B.isEmpty)(e))return{kept:[],projectRootPath:t.rootPath};let r=e.map(e=>uW.default.isAbsolute(e.filePath)?e.filePath:uW.default.join(t.rootPath,e.filePath)),i=f2.detectProjectRoot(t.rootPath,r,this.logger),a=[];for(let[t,o]of e.entries()){let e=r[t];if(!p2(i,e)){n.push({filePath:o.filePath,reason:`outside-project`});continue}let s=uW.default.relative(i,e);a.push({filePath:s,status:o.status})}return{kept:a,projectRootPath:i}}};m2=aQ([et(),iQ(0,Ze(sQ)),rQ(`design:paramtypes`,[Object])],m2);let h2=class{constructor(e){this.tsAgent=e}async execute(e,t,n){let r=e.map(e=>e.filePath);if((0,B.isEmpty)(r))return{kept:[]};let i=await this.tsAgent.getTestableFileMap(r),a=[];for(let e of r){let r=this.getEntriesForFile(e,i,t.projectRootPath);if(!(0,B.isDefined)(r)||(0,B.isEmpty)(r)){n.push({filePath:e,reason:`no-testables`});continue}this.processEntriesForFile(e,r,a,n)||n.push({filePath:e,reason:`no-testables`})}return{kept:a}}processEntriesForFile(e,t,n,r){let i=!1;for(let a of t){let{testable:t}=a;if(!t.canCreateTests||t.type===`class`)continue;if(i=!0,(0,B.isDefined)(a.testPath)){r.push({filePath:e,testableName:t.name,reason:`has-test-file`});continue}let o=e.startsWith(`/`)?e.slice(1):e;n.push({filePath:o,testable:t})}return i}getEntriesForFile(e,t,n){if((0,B.isDefined)(t[e]))return t[e];let r=uW.default.resolve(n,e);if((0,B.isDefined)(t[r]))return t[r]}};h2=aQ([et(),iQ(0,Ze(lW.TSAgent)),rQ(`design:paramtypes`,[Object])],h2);var Fte,g2,_2,v2,y2,b2,x2;function Ite(e,t){return{async execute(n,r,i){return e(r)?t.execute(n,r,i):{kept:n}}}}let S2=class{filters;constructor(e,t,n,r,i,a,o,s){this.configService=e,this.tsAgent=t,this.fileNameFilter=n,this.projectRootFilter=r,this.testableMapFilter=i,this.changedMethodsFilter=a,this.coverageFilter=o,this.limitFilter=s,this.filters=[this.fileNameFilter,this.projectRootFilter,this.testableMapFilter,Ite(e=>e.changedMethodsOnly&&e.hasDiffContext,this.changedMethodsFilter),this.coverageFilter,this.limitFilter]}async getTestablesToGenerate(e){let t={rootPath:e.rootPath,projectRootPath:e.rootPath,gitTopLevel:e.gitTopLevel,changedMethodsOnly:e.changedMethodsOnly??!1,hasDiffContext:e.hasDiffContext,baseRevision:e.baseRevision,coverageReport:e.coverageReport};return this.runPipeline([...e.changedFiles],t)}async runPipeline(e,t){let n=[],r=e,i=t.projectRootPath;for(let e of this.filters){let a={...t,projectRootPath:i},o=await e.execute(r,a,n);if((0,B.isDefined)(o.projectRootPath)&&!(0,B.isEmpty)(o.projectRootPath)&&(i=o.projectRootPath,this.tsAgent.updateRootPath(i),this.configService.updateConfigValue(`rootPath`,i)),(0,B.isEmpty)(o.kept))return{testables:[],filteredOut:n,projectRootPath:i};r=o.kept}return{testables:r,filteredOut:n,projectRootPath:i}}};S2=aQ([et(),iQ(0,Ze(cQ)),iQ(1,Ze(lW.TSAgent)),iQ(2,Ze(X0)),iQ(3,Ze(m2)),iQ(4,Ze(h2)),iQ(5,Ze(q0)),iQ(6,Ze(Y0)),iQ(7,Ze(Q0)),rQ(`design:paramtypes`,[typeof(Fte=cQ!==void 0&&cQ)==`function`?Fte:Object,Object,typeof(g2=X0!==void 0&&X0)==`function`?g2:Object,typeof(_2=m2!==void 0&&m2)==`function`?_2:Object,typeof(v2=h2!==void 0&&h2)==`function`?v2:Object,typeof(y2=q0!==void 0&&q0)==`function`?y2:Object,typeof(b2=Y0!==void 0&&Y0)==`function`?b2:Object,typeof(x2=Q0!==void 0&&Q0)==`function`?x2:Object])],S2);var C2=u(lH(),1);const w2=`axios-retry`;function T2(e){return e.response||!e.code||[`ERR_CANCELED`,`ECONNABORTED`].includes(e.code)?!1:(0,C2.default)(e)}const E2=[`get`,`head`,`options`],D2=E2.concat([`put`,`delete`]);function O2(e){return e.code!==`ECONNABORTED`&&(!e.response||e.response.status===429||e.response.status>=500&&e.response.status<=599)}function k2(e){return e.config?.method?O2(e)&&E2.indexOf(e.config.method)!==-1:!1}function A2(e){return e.config?.method?O2(e)&&D2.indexOf(e.config.method)!==-1:!1}function j2(e){return T2(e)||A2(e)}function M2(e=void 0){let t=e?.response?.headers[`retry-after`];if(!t)return 0;let n=(Number(t)||0)*1e3;return n===0&&(n=(new Date(t).valueOf()||0)-Date.now()),Math.max(0,n)}function Lte(e=0,t=void 0){return Math.max(0,M2(t))}function N2(e=0,t=void 0,n=100){let r=2**e*n,i=Math.max(r,M2(t));return i+i*.2*Math.random()}function Rte(e=100){return(t=0,n=void 0)=>{let r=t*e;return Math.max(r,M2(n))}}const zte={retries:3,retryCondition:j2,retryDelay:Lte,shouldResetTimeout:!1,onRetry:()=>{},onMaxRetryTimesExceeded:()=>{},validateResponse:null};function P2(e,t){return{...zte,...t,...e[w2]}}function F2(e,t,n=!1){let r=P2(e,t||{});return r.retryCount=r.retryCount||0,(!r.lastRequestTime||n)&&(r.lastRequestTime=Date.now()),e[w2]=r,r}function I2(e,t){e.defaults.agent===t.agent&&delete t.agent,e.defaults.httpAgent===t.httpAgent&&delete t.httpAgent,e.defaults.httpsAgent===t.httpsAgent&&delete t.httpsAgent}async function L2(e,t){let{retries:n,retryCondition:r}=e,i=(e.retryCount||0)<n&&r(t);if(typeof i==`object`)try{return await i!==!1}catch{return!1}return i}async function R2(e,t,n,r){t.retryCount+=1;let{retryDelay:i,shouldResetTimeout:a,onRetry:o}=t,s=i(t.retryCount,n);if(I2(e,r),!a&&r.timeout&&t.lastRequestTime){let e=Date.now()-t.lastRequestTime,i=r.timeout-e-s;if(i<=0)return Promise.reject(n);r.timeout=i}return r.transformRequest=[e=>e],await o(t.retryCount,n,r),r.signal?.aborted?Promise.resolve(e(r)):new Promise(t=>{let n=()=>{clearTimeout(i),t(e(r))},i=setTimeout(()=>{t(e(r)),r.signal?.removeEventListener&&r.signal.removeEventListener(`abort`,n)},s);r.signal?.addEventListener&&r.signal.addEventListener(`abort`,n,{once:!0})})}async function z2(e,t){e.retryCount>=e.retries&&await e.onMaxRetryTimesExceeded(t,e.retryCount)}const B2=(e,t)=>({requestInterceptorId:e.interceptors.request.use(e=>(F2(e,t,!0),e[w2]?.validateResponse&&(e.validateStatus=()=>!1),e)),responseInterceptorId:e.interceptors.response.use(null,async n=>{let{config:r}=n;if(!r)return Promise.reject(n);let i=F2(r,t);return n.response&&i.validateResponse?.(n.response)?n.response:await L2(i,n)?R2(e,i,n,r):(await z2(i,n),Promise.reject(n))})});B2.isNetworkError=T2,B2.isSafeRequestError=k2,B2.isIdempotentRequestError=A2,B2.isNetworkOrIdempotentRequestError=j2,B2.exponentialDelay=N2,B2.linearDelay=Rte,B2.isRetryableError=O2;const V2=Error(`request for lock canceled`);var H2=function(e,t,n,r){function i(e){return e instanceof n?e:new n(function(t){t(e)})}return new(n||=Promise)(function(n,a){function o(e){try{c(r.next(e))}catch(e){a(e)}}function s(e){try{c(r.throw(e))}catch(e){a(e)}}function c(e){e.done?n(e.value):i(e.value).then(o,s)}c((r=r.apply(e,t||[])).next())})},U2=class{constructor(e,t=V2){this._value=e,this._cancelError=t,this._queue=[],this._weightedWaiters=[]}acquire(e=1,t=0){if(e<=0)throw Error(`invalid weight ${e}: must be positive`);return new Promise((n,r)=>{let i={resolve:n,reject:r,weight:e,priority:t},a=W2(this._queue,e=>t<=e.priority);a===-1&&e<=this._value?this._dispatchItem(i):this._queue.splice(a+1,0,i)})}runExclusive(e){return H2(this,arguments,void 0,function*(e,t=1,n=0){let[r,i]=yield this.acquire(t,n);try{return yield e(r)}finally{i()}})}waitForUnlock(e=1,t=0){if(e<=0)throw Error(`invalid weight ${e}: must be positive`);return this._couldLockImmediately(e,t)?Promise.resolve():new Promise(n=>{this._weightedWaiters[e-1]||(this._weightedWaiters[e-1]=[]),Bte(this._weightedWaiters[e-1],{resolve:n,priority:t})})}isLocked(){return this._value<=0}getValue(){return this._value}setValue(e){this._value=e,this._dispatchQueue()}release(e=1){if(e<=0)throw Error(`invalid weight ${e}: must be positive`);this._value+=e,this._dispatchQueue()}cancel(){this._queue.forEach(e=>e.reject(this._cancelError)),this._queue=[]}_dispatchQueue(){for(this._drainUnlockWaiters();this._queue.length>0&&this._queue[0].weight<=this._value;)this._dispatchItem(this._queue.shift()),this._drainUnlockWaiters()}_dispatchItem(e){let t=this._value;this._value-=e.weight,e.resolve([t,this._newReleaser(e.weight)])}_newReleaser(e){let t=!1;return()=>{t||(t=!0,this.release(e))}}_drainUnlockWaiters(){if(this._queue.length===0)for(let e=this._value;e>0;e--){let t=this._weightedWaiters[e-1];t&&(t.forEach(e=>e.resolve()),this._weightedWaiters[e-1]=[])}else{let e=this._queue[0].priority;for(let t=this._value;t>0;t--){let n=this._weightedWaiters[t-1];if(!n)continue;let r=n.findIndex(t=>t.priority<=e);(r===-1?n:n.splice(0,r)).forEach((e=>e.resolve()))}}}_couldLockImmediately(e,t){return(this._queue.length===0||this._queue[0].priority<t)&&e<=this._value}};function Bte(e,t){let n=W2(e,e=>t.priority<=e.priority);e.splice(n+1,0,t)}function W2(e,t){for(let n=e.length-1;n>=0;n--)if(t(e[n]))return n;return-1}var G2=function(e,t,n,r){function i(e){return e instanceof n?e:new n(function(t){t(e)})}return new(n||=Promise)(function(n,a){function o(e){try{c(r.next(e))}catch(e){a(e)}}function s(e){try{c(r.throw(e))}catch(e){a(e)}}function c(e){e.done?n(e.value):i(e.value).then(o,s)}c((r=r.apply(e,t||[])).next())})},K2=class{constructor(e){this._semaphore=new U2(1,e)}acquire(){return G2(this,arguments,void 0,function*(e=0){let[,t]=yield this._semaphore.acquire(1,e);return t})}runExclusive(e,t=0){return this._semaphore.runExclusive(()=>e(),1,t)}isLocked(){return this._semaphore.isLocked()}waitForUnlock(e=0){return this._semaphore.waitForUnlock(1,e)}release(){this._semaphore.isLocked()&&this._semaphore.release()}cancel(){return this._semaphore.cancel()}};new TextEncoder;const q2=new TextDecoder;function J2(e){if(Uint8Array.fromBase64)return Uint8Array.fromBase64(e);let t=atob(e),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n}function Y2(e){if(Uint8Array.fromBase64)return Uint8Array.fromBase64(typeof e==`string`?e:q2.decode(e),{alphabet:`base64url`});let t=e;t instanceof Uint8Array&&(t=q2.decode(t)),t=t.replace(/-/g,`+`).replace(/_/g,`/`).replace(/\s/g,``);try{return J2(t)}catch{throw TypeError(`The input to be decoded is not correctly encoded.`)}}var X2=class extends Error{static code=`ERR_JOSE_GENERIC`;code=`ERR_JOSE_GENERIC`;constructor(e,t){super(e,t),this.name=this.constructor.name,Error.captureStackTrace?.(this,this.constructor)}},Z2=class extends X2{static code=`ERR_JWT_INVALID`;code=`ERR_JWT_INVALID`};Symbol.asyncIterator;function Q2(e){return typeof e==`object`&&!!e}var $2=e=>{if(!Q2(e)||Object.prototype.toString.call(e)!==`[object Object]`)return!1;if(Object.getPrototypeOf(e)===null)return!0;let t=e;for(;Object.getPrototypeOf(t)!==null;)t=Object.getPrototypeOf(t);return Object.getPrototypeOf(e)===t};function e4(e){if(typeof e!=`string`)throw new Z2(`JWTs must use Compact JWS serialization, JWT must be a string`);let{1:t,length:n}=e.split(`.`);if(n===5)throw new Z2(`Only JWTs using Compact JWS serialization can be decoded`);if(n!==3)throw new Z2(`Invalid JWT`);if(!t)throw new Z2(`JWTs must contain a payload`);let r;try{r=Y2(t)}catch{throw new Z2(`Failed to base64url decode the payload`)}let i;try{i=JSON.parse(q2.decode(r))}catch{throw new Z2(`Failed to parse the decoded payload as JSON`)}if(!$2(i))throw new Z2(`Invalid JWT Claims Set`);return i}const t4=e=>{let t=e4(e).exp;return(0,B.isDefined)(t)?t*1e3:null},n4=e=>{if(!(0,B.isDefined)(e))return!0;let t=t4(e);return(0,B.isDefined)(t)?t>Date.now():!0};let r4=class{jwtToken=null;refreshTokenCallback=null;observer=new B.Observer;refreshTokenMutex=new K2;setJWTToken(e){this.jwtToken=e,this.observer.notifyAll(e)}async getJWTToken(){return(0,B.isDefined)(this.jwtToken)?(this.isTokenValid()||await this.refreshTokenMutex.runExclusive(async()=>{if((0,B.isDefined)(this.refreshTokenCallback))return await this.refreshTokenCallback(),this.jwtToken}),this.jwtToken):null}onJWTTokenSave(e){this.observer.addListener(e)}isTokenValid(){return n4(this.jwtToken)}setRefreshTokenCallback(e){this.refreshTokenCallback=e}};r4=aQ([et(`Singleton`)],r4);var i4,a4;let o4=class{axiosInstance;constructor(e,t,n){this.configService=e,this.authStorage=t,this.logger=n,this.configService=e,this.axiosInstance=k0.create({baseURL:this.configService.getConfigValueOrThrow(`backendURL`),headers:{"Content-Type":`application/json`}}),B2(this.axiosInstance,{retries:3,retryDelay:B2.exponentialDelay,retryCondition:e=>k0.isAxiosError(e)&&B2.isNetworkOrIdempotentRequestError(e)||k0.isAxiosError(e)&&e.response?.status!==void 0&&e.response.status>=500||!1})}async getAuthHeaders(){let e={"x-request-source":cW.RequestSource.CLI},t=await this.authStorage.getJWTToken();return(0,B.isDefined)(t)&&(e.authorization=`Bearer ${t}`),e}async apiCall({url:e,method:t,data:n,config:r}){let i=new L0(await this.getAuthHeaders());if(r?.headers)for(let[e,t]of Object.entries(r.headers))i.set(e,t);let a={...r,method:t,url:e,data:n,headers:i};try{return await this.axiosInstance.request(a)}catch(t){this.handleError(e,t)}}async get(e,t){return(await this.apiCall({url:e,method:`GET`,config:t})).data}async post(e,t,n){return(await this.apiCall({url:e,method:`POST`,data:t,config:n})).data}async put(e,t,n){return(await this.apiCall({url:e,method:`PUT`,data:t,config:n})).data}async delete(e,t){return(await this.apiCall({url:e,method:`DELETE`,config:t})).data}async patch(e,t,n){return(await this.apiCall({url:e,method:`PATCH`,data:t,config:n})).data}async head(e,t){return this.apiCall({url:e,method:`HEAD`,config:t})}async options(e,t){return this.apiCall({url:e,method:`OPTIONS`,config:t})}handleCustomErrors(e,t){if(e===R0.Conflict){if(t===`workflow_is_cancelled`)throw this.logger.warn(`Agent flow canceled`),new W0(R0.Conflict,t);if(t===`duplicated_by_sha_workflow`)throw this.logger.warn(`Duplicated SHA workflow`),new G0(R0.Conflict,t)}}handleError(e,t){if(k0.isAxiosError(t))if((0,B.isDefined)(t.response)){let{status:e,statusText:n,data:r}=t.response;throw this.handleCustomErrors(e,r.message),new U0(e,`API request failed: ${e} ${n} - ${JSON.stringify(r)}`)}else if((0,B.isDefined)(t.request))throw Error(`API request failed: No response received from ${e}`);else throw Error(`API request failed: ${t instanceof Error?t.message:`Unknown error`}`);else if(t instanceof Error)throw TypeError(`API request failed: ${t.message}`);else throw TypeError(`API request failed: Unknown error occurred`)}};o4=aQ([et(),iQ(0,Ze(cQ)),iQ(1,Ze(r4)),iQ(2,Ze(sQ)),rQ(`design:paramtypes`,[typeof(i4=cQ!==void 0&&cQ)==`function`?i4:Object,typeof(a4=r4!==void 0&&r4)==`function`?a4:Object,Object])],o4);var s4,c4,l4;let u4=class{constructor(e,t,n){this.configService=e,this.apiService=t,this.authStorage=n,this.authStorage.setRefreshTokenCallback(async()=>{await this.login()})}async login(){let e=this.configService.getConfigValueOrThrow(`secretToken`,`API key is required but not configured`);try{let{idToken:t}=await this.apiService.post(`auth/v2/sign-in-with-secret-token`,{secret:e});return this.authStorage.setJWTToken(t),t}catch{throw Error(`Failed to get JWT token by secret`)}}};u4=aQ([et(),iQ(0,Ze(cQ)),iQ(1,Ze(o4)),iQ(2,Ze(r4)),rQ(`design:paramtypes`,[typeof(s4=cQ!==void 0&&cQ)==`function`?s4:Object,typeof(c4=o4!==void 0&&o4)==`function`?c4:Object,typeof(l4=r4!==void 0&&r4)==`function`?l4:Object])],u4);let d4=function(e){return e.PR=`PR`,e.COMMIT=`COMMIT`,e.PROJECT=`PROJECT`,e.COVERAGE=`COVERAGE`,e}({});var f4,p4;let m4=class{constructor(e,t){this.apiService=e,this.configService=t}mapCommandToType(e){switch(e){case dW.PR:return d4.PR;case dW.COMMIT:return d4.COMMIT;case dW.PROJECT:return d4.PROJECT;case dW.COVERAGE:return d4.COVERAGE}}async logStartOperation(e){let t=this.configService.getConfig(),n={type:this.mapCommandToType(t.command),owner:e.owner,repo:e.repository,sourceRef:e.ref_name,commitSha:e.sha,commitDate:e.commitDate,traceId:this.configService.getConfigValue(`traceId`),config:this.configService.maskedConfig(),operationStartedAt:new Date().toISOString(),version:t.cliVersion};return(await this.apiService.post(`api/v1/workflows/open`,n)).id}async logEndOperation(e,t,n,r){await this.apiService.patch(`api/v1/workflows/close/${e}`,{operationEndedAt:new Date().toISOString(),failureReason:t,runOutput:n,resultCommitSha:r})}async saveCoverageToWorkflow(e,t,{coverage:n,prCoverage:r,methodsAffected:i,committedFiles:a}){await this.apiService.patch(`api/v1/workflows/${e}/coverage`,{type:t,coverage:n,prCoverage:r,methodsAffected:i,committedFiles:a})}async getCoverageFromWorkflowOrUndefined(e){if(!this.configService.getConfigValue(`reuseCoverage`)||!(0,B.isDefined)(e))return;let t=this.configService.getConfigValue(`reuseCoverageMaxRuns`),n=await this.apiService.post(`api/v1/workflows/${e}/reuse-coverage`,{limit:t});if((0,B.isDefined)(n.coverageBefore))return n.coverageBefore}};m4=aQ([et(),iQ(0,Ze(o4)),iQ(1,Ze(cQ)),rQ(`design:paramtypes`,[typeof(f4=o4!==void 0&&o4)==`function`?f4:Object,typeof(p4=cQ!==void 0&&cQ)==`function`?p4:Object])],m4);var h4;let g4=class{constructor(e,t){this.tsAgent=e,this.logger=t}async analyzeChangedMethods(e,t,n){try{this.logger.info(`Analyzing coverage for ${t.length} changed methods with threshold ${n.coverageThreshold}%`);let r=[],i=0,a=0,o=0,s=this.groupChangedMethodsByFile(t);for(let[t,c]of Object.entries(s)){let s=this.findFileCoverage(e,t);if((0,B.isDefined)(s)){let e=this.processFileWithCoverage(t,c,s,n);r.push(...e.testables),i+=e.analyzed,a++}else{let e=this.processFileWithoutCoverage(t,c);r.push(...e.testables),i+=e.analyzed,o++}}let c={testables:r,totalAnalyzed:i,filteredCount:r.length,filesWithCoverage:a,filesWithoutCoverage:o};return this.logger.info(`Changed methods analysis complete: ${c.filteredCount}/${c.totalAnalyzed} methods below threshold across ${a+o} files`),c}catch(e){throw e instanceof Error?(this.logger.error(`Failed to analyze changed methods: ${e.message}`),e):Error(`Unknown error occurred while analyzing changed methods`)}}processFileWithCoverage(e,t,n,r){let i=[],a=0;for(let o of t){if(o.changeType===`deleted`||!o.canCreateTests)continue;let t=this.findTestableInCoverage(n,o);(0,B.isDefined)(t)?(a++,this.shouldIncludeTestable(t,r)&&i.push({name:t.name,percentage:t.percentage,filePath:e,reason:this.getFilterReason(t)})):(a++,i.push({name:o.name??`unknown`,percentage:null,filePath:e,reason:`no-coverage`}))}return{testables:i,analyzed:a}}processFileWithoutCoverage(e,t){let n=t.filter(e=>e.changeType!==`deleted`&&e.canCreateTests),r=n.map(t=>({name:t.name??`unknown`,percentage:null,filePath:e,reason:`no-coverage`}));return this.logger.debug(`No coverage data found for file: ${e}`),{testables:r,analyzed:n.length}}async analyzeChangedFiles(e,t,n){try{this.logger.info(`Analyzing coverage for ${t.length} changed files with threshold ${n.coverageThreshold}%`);let r=[],i=0,a=0,o=0;for(let s of t){let t=this.findFileCoverage(e,s);if((0,B.isDefined)(t)){a++;let e=await this.filterOutClasses(s,t.testables??[]),o=this.filterTestablesForFile(t,s,n),c=await this.filterOutClasses(s,o);r.push(...c),i+=e.length??0,(0,B.isEmpty)(c)||this.logger.debug(`File ${s}: ${c.length}/${e.length??0} testables below threshold`)}else o++,this.logger.debug(`No coverage data found for file: ${s}`)}let s={testables:r,totalAnalyzed:i,filteredCount:r.length,filesWithCoverage:a,filesWithoutCoverage:o};return this.logger.info(`Coverage analysis complete: ${s.filteredCount}/${s.totalAnalyzed} testables below threshold across ${s.filesWithCoverage} files`),s}catch(e){throw e instanceof Error?(this.logger.error(`Failed to analyze coverage: ${e.message}`),e):Error(`Unknown error occurred while analyzing coverage`)}}findFileCoverage(e,t){let n=t.startsWith(`/`)?t:`/${t}`;return(0,B.isDefined)(e[n])?e[n]:null}filterTestablesForFile(e,t,n){let r=[];for(let i of e.testables??[])if(this.shouldIncludeTestable(i,n)){let e=this.getFilterReason(i);r.push({name:i.name,percentage:i.percentage,filePath:t,reason:e})}return r}shouldIncludeTestable(e,t){return!!(e.percentage===null||e.percentage===0||(0,B.isDefined)(e.percentage)&&e.percentage<t.coverageThreshold)}getFilterReason(e){return e.percentage===null?`no-coverage`:e.percentage===0?`zero-coverage`:`below-threshold`}async calculatePRCoverage(e,t){if(!(0,B.isEmpty)(e))try{let n=await this.tsAgent.getCoverageForFiles(e),r=t?`before`:`after`;return this.logger.debug(`PR Coverage (${r}): ${n.percentage}% (${n.coveredStatements}/${n.totalStatements} statements)`),n}catch(e){this.logger.warn(`Failed to calculate PR coverage: ${e instanceof Error?e.message:`Unknown error`}`);return}}async filterOutClasses(e,t){let n=await this.tsAgent.getTestables(e);if((0,B.isEmpty)(n)||!(0,B.isDefined)(n[0]))return this.logger.warn(`getTestables returned empty for ${e}, keeping all testables`),t;let[,r]=n[0],i=r.filter(e=>e.type!==`class`),a=new Set(i.map(e=>e.name));return t.filter(e=>a.has(e.name))}groupChangedMethodsByFile(e){let t={};for(let n of e)(0,B.isDefined)(t[n.filePath])||(t[n.filePath]=[]),t[n.filePath].push(n);return t}findTestableInCoverage(e,t){return(0,B.isDefined)(e.testables)?e.testables.find(e=>{let n=e.name===t.name,r=`parentName`in e?e.parentName===t.parentName:!(0,B.isDefined)(t.parentName);return n&&r})??null:null}};g4=aQ([et(),iQ(0,Ze(lW.TSAgent)),iQ(1,Ze(sQ)),rQ(`design:paramtypes`,[typeof(h4=cW.TSAgent!==void 0&&cW.TSAgent)==`function`?h4:Object,Object])],g4);function _4(e,t){return t2(e,`package.json`,t)??void 0}function v4(e,t){try{return m.default.existsSync(e)?m.default.readFileSync(e,`utf8`):void 0}catch(n){t.warn(`Failed to read file ${e}: ${n instanceof Error?n.message:`Unknown error`}`);return}}async function y4(e,t,n){let r=_4(e,t),i=(await(0,cW.findLintConfigPath)(t)).path??void 0,a=(0,B.isDefined)(r)?v4(r,n):void 0,o=(0,B.isDefined)(i)?v4(i,n):void 0;return(0,B.isDefined)(r)&&n.info(`Found package.json at: ${r}`),(0,B.isDefined)(i)&&n.info(`Found lint config at: ${i}`),{packageJsonPath:r,packageJsonContent:a,lintConfigPath:i,lintConfigContent:o}}const b4={detectProjectConfigs:y4};var x4,S4;let C4=class{constructor(e,t,n){this.apiService=e,this.configService=t,this.logger=n}async detectAndSaveConfigs(e){try{let t=this.configService.getConfigValue(`rootPath`),n=await b4.detectProjectConfigs(t,t,this.logger);if(!(0,B.isDefined)(n.packageJsonContent)&&!(0,B.isDefined)(n.lintConfigContent))return;await this.apiService.patch(`api/v1/github-repos/configs`,{owner:e.owner,repo:e.repository,packageJson:n.packageJsonContent,lintConfig:n.lintConfigContent})}catch(e){this.logger.warn(`Failed to detect and save project configs: ${e instanceof Error?e.message:`Unknown error`}`)}}};C4=aQ([et(),iQ(0,Ze(o4)),iQ(1,Ze(cQ)),iQ(2,Ze(sQ)),rQ(`design:paramtypes`,[typeof(x4=o4!==void 0&&o4)==`function`?x4:Object,typeof(S4=cQ!==void 0&&cQ)==`function`?S4:Object,Object])],C4);var Vte,w4,T4,E4,D4,O4,k4,A4,j4;let M4=class{workflowRunId;initialCoverageTree;resultCommitSha;constructor(e,t,n,r,i,a,o,s,c,l){this.configService=e,this.authService=t,this.gitService=n,this.coverageAnalysisService=r,this.summaryService=i,this.tsAgent=a,this.workflowService=o,this.scmHostService=s,this.repoConfigService=c,this.logger=l}async login(){try{this.logger.info(`Trying login to API...`);let e=await this.authService.login();await this.tsAgent.init(e),this.logger.info(`Successfully authenticated with the API`)}catch(e){throw this.logger.error(`Failed to authenticate:`+(e instanceof Error?e.message:`Unknown error`)),e}}async logStart(){try{let e=await this.gitService.getGitInfo();this.logger.debug(`Git info: `+JSON.stringify(e));try{let t=await this.workflowService.logStartOperation(e);return this.tsAgent.updateContext({git:{...e,workflowRunId:t}}),this.workflowRunId=t,await this.repoConfigService.detectAndSaveConfigs(e),t}catch(e){throw e instanceof G0||e instanceof W0||this.logger.warn(`Failed to log start operation: ${e instanceof Error?e.message:`Unknown error`}`),e}}catch(e){throw e instanceof G0||e instanceof W0||this.logger.error(`Failed to retrieve git info or log start operation:`+(e instanceof Error?e.message:`Unknown error`)),e}}async generateInitialCoverage(){this.logger.verbose(`Try to reuse coverage...`);let e=await this.workflowService.getCoverageFromWorkflowOrUndefined(this.workflowRunId);if((0,B.isDefined)(e))return await this.tsAgent.setCoverage(e),this.initialCoverageTree=e,(0,B.isDefined)(this.workflowRunId)&&await this.workflowService.saveCoverageToWorkflow(this.workflowRunId,`before`,{}),this.logger.verbose(`Reused coverage: `+(e[`/`]?.percentage??0)+`%`),this.summaryService.setCoverageData(e[`/`]?.percentage??0,e[`/`]?.percentage??0),e;{this.logger.verbose(`Generating initial coverage...`),await this.tsAgent.generateCoverage();let e=await this.tsAgent.getCoverageTree();if(!(0,B.isDefined)(e))throw Error(`Failed to generate initial coverage tree`);return this.initialCoverageTree=e,(0,B.isDefined)(this.workflowRunId)&&await this.workflowService.saveCoverageToWorkflow(this.workflowRunId,`before`,{coverage:e}),this.logger.verbose(`Initial coverage: `+(e[`/`]?.percentage??0)+`%`),this.summaryService.setCoverageData(e[`/`]?.percentage??0,e[`/`]?.percentage??0),e}}async logEndOperation(e){if((0,B.isDefined)(this.workflowRunId))try{let t=this.summaryService.getWorkflowRunOutput();await this.workflowService.logEndOperation(this.workflowRunId,e,t,this.resultCommitSha),this.logger.info(`Successfully logged workflow end`)}catch(e){this.logger.warn(`Failed to log workflow end: `+(e instanceof Error?e.message:`Unknown error`))}}getWorkflowRunIdOrThrow(){if(!(0,B.isDefined)(this.workflowRunId))throw Error(`Workflow run ID is not set, call logStart() first`);return this.workflowRunId}getInitialCoverageTreeOrThrow(){if(!(0,B.isDefined)(this.initialCoverageTree))throw Error(`Initial coverage tree is not set, call generateInitialCoverage() first`);return this.initialCoverageTree}getInitialCoverageTreeOrUndefined(){return this.initialCoverageTree}async countAllMethodsInFiles(e){let t=(0,B.uniq)(e).map(async e=>{try{return await this.tsAgent.getAllMethodsCount(e)}catch(t){return this.logger.debug(`Failed to count methods in `+e+`: `+(t instanceof Error?t.message:`Unknown error`)),0}});return(await Promise.all(t)).reduce((e,t)=>e+t,0)}};M4=aQ([et(),iQ(0,Ze(cQ)),iQ(1,Ze(u4)),iQ(2,Ze(xQ)),iQ(3,Ze(g4)),iQ(4,Ze(uQ)),iQ(5,Ze(lW.TSAgent)),iQ(6,Ze(m4)),iQ(7,Ze(lW.SCMHostService)),iQ(8,Ze(C4)),iQ(9,Ze(sQ)),rQ(`design:paramtypes`,[typeof(Vte=cQ!==void 0&&cQ)==`function`?Vte:Object,typeof(w4=u4!==void 0&&u4)==`function`?w4:Object,typeof(T4=xQ!==void 0&&xQ)==`function`?T4:Object,typeof(E4=g4!==void 0&&g4)==`function`?E4:Object,typeof(D4=uQ!==void 0&&uQ)==`function`?D4:Object,typeof(O4=cW.TSAgent!==void 0&&cW.TSAgent)==`function`?O4:Object,typeof(k4=m4!==void 0&&m4)==`function`?k4:Object,typeof(A4=hQ!==void 0&&hQ)==`function`?A4:Object,typeof(j4=C4!==void 0&&C4)==`function`?j4:Object,Object])],M4);var N4;let P4=class extends M4{changedFiles=[];prCoverage={before:{percentage:null,totalStatements:0,coveredStatements:0},after:{percentage:null,totalStatements:0,coveredStatements:0}};testableToGenerateService;getWorkflowRunId(){return this.workflowRunId}async runFlow(e){let t=e?.shouldDeferPostGeneration??!1,n,r=!1,i;try{await this.login(),await this.logStart(),await this.validateCommitBranch();let e=await this.getRawChangedFiles(),n=this.configService.getConfigValue(`rootPath`),r=this.configService.getConfigValue(`gitTopLevel`)??n;this.logger.info(`Discovering untested functions`);let a=await this.testableToGenerateService.getTestablesToGenerate({changedFiles:e,rootPath:n,gitTopLevel:r,hasDiffContext:this.hasDiffContext(),baseRevision:await this.getBaseRevision(),changedMethodsOnly:this.configService.getConfigValue(`changedMethodsOnly`),coverageReport:{tree:this.initialCoverageTree,threshold:this.configService.getConfigValue(`coverageThreshold`)}});if((0,B.isEmpty)(a.testables)){this.logFilteredOutTestables(a.filteredOut),this.handleNoFilteredTestables();return}if(this.updateRootPath(a.projectRootPath),this.changedFiles=a.testables.map(e=>e.filePath),await this.setSummaryChangedFilesData(e.length,a),a.filteredOut.filter(e=>e.reason===`limit-reached`).length>0){let e=this.configService.getConfigValue(`maxTestables`);this.summaryService.addWarning(`Limited to ${e} functions: test generation was capped due to maximum function limit.`)}this.logFilteredOutTestables(a.filteredOut),this.logTestablesToGenerate([...a.testables]);let o=[...a.testables];if(i=await this.generateTests(o),!t){let e=await this.performAutoCommit();this.summaryService.setTestGenerationData({generated:i.generated,succeeded:i.succeeded,failed:i.failed,successMethodsCount:i.successMethodsCount,committedFilesCount:e,greenTests:i.greenTests,redTests:i.redTests}),this.configService.getConfigValue(`skipCoverageAfter`)?(this.logger.verbose(`Skipping final coverage generation (--skip-coverage-after flag is set)`),this.summaryService.setCoverageSkipped()):await this.generateFinalCoverageAndLog({methodsAffected:o.length,committedFiles:e})}return i}catch(e){if(e instanceof G0){this.logger.warn(`Duplicate SHA execution detected. Skipping.`);return}if(e instanceof W0){this.logger.warn(`Workflow canceled. Skipping.`),r=!0;return}throw n=e instanceof Error?e.message:`Unknown error`,this.logger.error(`Agent flow failed: `+n),e}finally{!t&&(0,B.isDefined)(this.workflowRunId)&&!r&&(this.summaryService.setPRCoverageData(this.prCoverage.before,this.prCoverage.after),await this.scmHostService.safePostSummaryToPr(),await this.logEndOperation(n))}}async setSummaryChangedFilesData(e,t){let n=[...new Set([...t.testables.map(e=>e.filePath),...t.filteredOut.map(e=>e.filePath)])],r=await this.countAllMethodsInFiles(n);this.summaryService.setChangedFilesData({changedFilesCount:e,candidateFilesCount:n.length,functionCount:r,publicMethodCount:t.testables.length,testablesToGenerateCount:t.testables.length,publicMethods:t.testables.map(e=>({name:e.testable.name??`unknown`,filePath:e.filePath})),methodsBelowCoverage:t.testables.map(e=>({name:e.testable.name??`unknown`,filePath:e.filePath}))})}handleNoFilteredTestables(){this.logger.warn(`No filtered untested functions`),this.prCoverage.after=this.prCoverage.before}logFilteredOutTestables(e){if((0,B.isEmpty)(e))return;let t=e.length,n=t===1?`item`:`items`;this.logger.verbose(t+` `+n+` skipped:`);for(let t of e){let e=(0,B.isDefined)(t.testableName)?t.testableName+` in `+t.filePath:t.filePath;this.logger.verbose(` - `+e+`: `+t.reason)}}logTestablesToGenerate(e){this.logger.info(`Found ${e.length} public function${e.length===1?``:`s`} without Early AI tests`);for(let t of e)this.logger.info(` `+t.testable.name+` in `+t.filePath)}async validateCommitBranch(){if(!this.configService.getConfigValue(`autoCommit`))return;let e=this.configService.getConfigValue(`refName`);if(e&&!await this.gitService.checkRefExists(e))throw Error(`Branch '${e}' does not exist on remote. Create it before running with --auto-commit.`)}async performAutoCommit(){let e=this.configService.getConfigValueOrThrow(`autoCommit`);if(this.summaryService.setAutoCommitStatus(e),e){let e=this.configService.getConfigValue(`refName`),t=await this.gitService.commitFiles(e);return(0,B.isDefined)(t.resultCommitSha)&&(this.resultCommitSha=t.resultCommitSha),t.committedFiles.length}else return this.logger.info(`Auto-commit is disabled - skipping commit step`),0}async _generateInitialCoverageForTestGeneration(){await this.generateInitialCoverage(),await this.savePRCoverageBefore()}async savePRCoverageBefore(){if((0,B.isDefined)(this.workflowRunId))try{let e=await this.coverageAnalysisService.calculatePRCoverage(this.changedFiles,!0);(0,B.isDefined)(e)&&(this.prCoverage.before=e),await this.workflowService.saveCoverageToWorkflow(this.workflowRunId,`before`,{prCoverage:e}),this.logger.debug(`Successfully saved initial coverage to workflow run`)}catch(e){this.logger.warn(`Failed to save initial coverage: `+(e instanceof Error?e.message:`Unknown error`))}}async generateTests(e){let t=new Set(e),n=0,r=0,i=0,a=0;try{await this.tsAgent.bulkGenerateTests(e,(o,s)=>{a++;let c=uW.default.basename(o.filePath);(0,B.isDefined)(s)&&s.greenTestsCount>0?(t.delete(o),n+=s.greenTestsCount,r+=s.redTestsCount,i+=s.greyTestsCount,this.logger.info(` [${a}/${e.length}] ✓ ${o.testable.name} (${c}) — ${s.greenTestsCount} passing, ${s.redTestsCount} skipped`)):this.logger.info(` [${a}/${e.length}] ✗ ${o.testable.name} (${c}) — no tests generated`)})}catch(e){if(e instanceof Error&&(e.message===`Operation aborted`||e.name===`AbortError`))this.logger.warn(`Test generation was partially aborted due to timeout`);else throw e}let o=e.length-t.size,s=t.size,c=await this.gitService.getEarlyFiles();return this.logger.info(``),this.logger.info(`✅ Test generation complete for ${o} functions`),s>0&&this.logger.info(`❌ ${s} functions were not generated`),this.logger.info(``),this.logger.info(`================`),this.logger.info(`Overall summary:`),this.logger.info(`================`),this.logger.info(``),this.logger.info(`✅ ${n} tests passing`),this.logger.info(`⚠️ ${r} tests skipped`),this.logger.info(`❌ ${i} tests could not be fixed autonomously (yet)`),this.logger.info(``),{generated:e.length,succeeded:o,failed:s,successMethodsCount:c.length,greenTests:n,redTests:r}}async generateFinalCoverageAndLog({methodsAffected:e,committedFiles:t}){let n=this.getWorkflowRunIdOrThrow();this.logger.verbose(`Generating final coverage...`),await this.tsAgent.generateCoverage();let r=await this.tsAgent.getCoverageTree();if(!(0,B.isDefined)(r))throw Error(`Failed to generate final coverage tree`);let i=r[`/`]?.percentage??0,a=this.getInitialCoverageTreeOrUndefined(),o=a?.[`/`]?.percentage??0;(0,B.isDefined)(a)||this.summaryService.setCoverageBeforeSkipped(),this.summaryService.setCoverageData(o,i);let s=(0,B.isDefined)(a)?`${o}% -> ${i}%`:`skipped`;this.logger.verbose(`Final coverage: `+i+`%, Coverage comparison: `+s);try{let i=await this.coverageAnalysisService.calculatePRCoverage(this.changedFiles,!1);(0,B.isDefined)(i)&&(this.prCoverage.after=i),await this.workflowService.saveCoverageToWorkflow(n,`after`,{coverage:r,prCoverage:i,methodsAffected:e,committedFiles:t}),this.logger.debug(`Successfully saved final coverage to workflow run`)}catch(e){this.logger.warn(`Failed to save final coverage: `+(e instanceof Error?e.message:`Unknown error`))}}updateRootPath(e){this.tsAgent.updateRootPath(e),this.configService.updateConfigValue(`rootPath`,e)}};aQ([Ze(S2),rQ(`design:type`,typeof(N4=S2!==void 0&&S2)==`function`?N4:Object)],P4.prototype,`testableToGenerateService`,void 0),P4=aQ([et(),st({extendConstructorArguments:!0,extendProperties:!0})],P4);let F4=class extends P4{async getRawChangedFiles(){return this.gitService.getChangedFilesForCommitWithStatus({absolute:!0})}hasDiffContext(){return!0}async getBaseRevision(){let e=this.configService.getConfigValue(`baseRef`);if((0,B.isDefined)(e))return this.gitService.getBaseRevision({baseBranch:e});let t=this.configService.getConfigValue(`commitHash`);if((0,B.isDefined)(t))return`${t}^`}async logStart(){try{let e=this.configService.getConfigValue(`commitHash`),t=await this.gitService.getCommitMessage(e);t&&this.configService.updateConfigValue(`commitName`,t)}catch(e){this.logger.warn(`Failed to retrieve commit message, continuing without it: `+(e instanceof Error?e.message:`Unknown error`))}try{let e=await this.scmHostService.getContributorAvatarUrl();(0,B.isDefined)(e)&&this.configService.updateConfigValue(`contributorAvatarUrl`,e)}catch(e){this.logger.warn(`Failed to retrieve contributor avatar, continuing without it: `+(e instanceof Error?e.message:`Unknown error`))}return await super.logStart()}};F4=aQ([et(),st({extendConstructorArguments:!0,extendProperties:!0})],F4);function Hte(e){let t=e.command(dW.COMMIT).alias(`generate-commit`).description(`Generate tests for the current project in commit context`);return ce(t,`--commit-hash <hash>`,`Commit hash`,{envName:`COMMIT_HASH`,isRequired:!0}),ce(t,`--ref-name <ref>`,`Head branch name for the commit`,{envName:`REF_NAME`,isRequired:!0}),ce(t,`--base-ref <ref>`,`optional base refrence for comparison`,{envName:`BASE_REF`}),ce(t,`-s, --test-structure <structure>`,`Test file structure`,{envName:`TEST_STRUCTURE`,def:`siblingFolder`}),ce(t,`-f, --test-framework <framework>`,`Test framework to use`,{envName:`TEST_FRAMEWORK`,def:`jest`}),ce(t,`--test-suffix <suffix>`,`Test file suffix`,{envName:`TEST_FILE_SUFFIX`,def:`test`}),ce(t,`--test-file-naming <naming>`,`Test file naming convention`,{envName:`TEST_FILE_NAMING`,def:`camelCase`}),ce(t,`-c, --max-concurrency <number>`,`Number of concurrent workers (1-4)`,{envName:`MAX_CONCURRENCY`,def:`3`}),ce(t,`--auto-commit <boolean>`,`Whether to auto-commit files`,{envName:`AUTO_COMMIT`,def:`true`}),ce(t,`--auto-commit-skip-ci <boolean>`,`Append [skip ci] to auto-commit message`,{envName:`AUTO_COMMIT_SKIP_CI`,def:`true`}),ce(t,`--test-command <command>`,`Custom test command to run`,{envName:`TEST_COMMAND`}),ce(t,`--coverage-command <command>`,`Custom coverage command to run`,{envName:`COVERAGE_COMMAND`}),ce(t,`--lint-command <command>`,`Custom lint command to run`,{envName:`LINT_COMMAND`}),ce(t,`--prettier-command <command>`,`Custom prettier command to run`,{envName:`PRETTIER_COMMAND`}),ce(t,`--disable-lint-rules <boolean>`,`Whether to disable failed lint rules in test files`,{envName:`DISABLE_LINT_RULES`,def:`false`}),ce(t,`--git-org <org>`,`Git organization name`,{envName:`GIT_ORG`}),ce(t,`--git-repo <repo>`,`Git repository name`,{envName:`GIT_REPO`}),ce(t,`--git-user-email <email>`,`Git user email for auto commit`,{envName:`GIT_USER_EMAIL`}),ce(t,`--git-user-name <name>`,`Git user name for auto commit`,{envName:`GIT_USER_NAME`}),ce(t,`--scm-provider <provider>`,`SCM provider (e.g., github, bitbucket)`,{envName:`SCM_PROVIDER`,def:`github`}),ce(t,`--keep-error-tests <boolean>`,`Whether to keep error tests`,{envName:`KEEP_ERROR_TESTS`,def:`false`}),ce(t,`--keep-failed-tests <boolean>`,`Whether to keep failed tests`,{envName:`KEEP_FAILED_TESTS`,def:`false`}),ce(t,`--conditional-keep <boolean>`,`Whether to return the last generated test result even when no green tests were produced`,{envName:`CONDITIONAL_KEEP`,def:`false`}),ce(t,`--continue-on-test-errors <boolean>`,`Whether to continue on test errors`,{envName:`CONTINUE_ON_TEST_ERRORS`,def:`false`}),ce(t,`--changed-methods-only <boolean>`,`Generate tests only for changed methods, not all methods in changed files`,{envName:`CHANGED_METHODS_ONLY`,def:`true`}),ce(t,`--skip-coverage-after <boolean>`,`Skip final coverage generation after test generation`,{envName:`SKIP_COVERAGE_AFTER`,def:`true`}),ce(t,`--max-testables <number>`,`Maximum number of testables to generate`,{envName:`MAX_TESTABLES`}),ce(t,`--per-function-timeout <number>`,`Per function timeout in milliseconds`,{envName:`PER_FUNCTION_TIMEOUT`}),ce(t,`--coverage-threshold <number>`,`Coverage threshold percentage (0-100)`,{envName:`COVERAGE_THRESHOLD`,def:`0`}),ce(t,`--reuse-coverage <boolean>`,`Whether to reuse coverage`,{envName:`REUSE_COVERAGE`,def:`false`}),ce(t,`--reuse-coverage-max-runs <number>`,`Max number of runs to reuse coverage (1-10)`,{envName:`REUSE_COVERAGE_MAX_RUNS`,def:`10`}),ce(t,`--experimental-agent-sdk <boolean>`,`Use experimental Agent SDK for test generation`,{envName:`EXPERIMENTAL_AGENT_SDK`,def:`true`}),t.addHelpText(`after`,`
|
|
32412
32413
|
Examples:
|
|
32413
32414
|
$ early generate-commit --api-key your-api-key --token your-token --commit-hash abc123 --ref-name feature/new-feature
|
|
32414
32415
|
$ early generate-commit -k your-api-key -f jest -s siblingFolder --test-command "npm run test -- $early_filename" --coverage-command "npm run coverage -- --coverageReporters=json --coverageDirectory=$early_coverage_dir"
|
|
@@ -32432,7 +32433,7 @@ Need help? → https://docs.startearly.ai
|
|
|
32432
32433
|
pip install earlyai-agent
|
|
32433
32434
|
# or: uv pip install earlyai-agent`);let e;try{await this.authService.login(),await this.gitService.hydrateConfig();let t=await this.gitService.getGitInfo();e=await this.workflowService.logStartOperation(t),this.logger.debug(`Workflow run opened: ${e}`)}catch(e){this.logger.warn(`Failed to open workflow run: ${e instanceof Error?e.message:`Unknown error`}`)}let t=await this.gitService.getChangedFilesForPR();this.logger.debug(`PR changed files (${t.length}): ${t.join(`, `)}`),this._summaryData={total:0,succeeded:0,failed:0},this._totalGreenTests=0,this._skippedMethods=0;let n=this._resolveClaudeCliJs(),r={...process.env,API_KEY:this.configService.getConfigValue(`secretToken`)??``,API_BASE_URL:this.configService.getConfigValue(`backendURL`)??`https://api.startearly.ai`,TEST_FRAMEWORK:`pytest`,TEST_STRUCTURE:this.configService.getConfigValue(`testStructure`)??`siblingFolder`,TEST_FILE_NAMING:this.configService.getConfigValue(`testFileName`)??`camelCase`,MAX_CONCURRENCY:String(this.configService.getConfigValue(`concurrency`)??3),MAX_TESTABLES:String(this.configService.getConfigValue(`maxTestables`)??``),BASE_REF:this.configService.getConfigValue(`baseRef`)??``,CHANGED_FILES:t.join(`
|
|
32434
32435
|
`),...e===void 0?{}:{WORKFLOW_RUN_ID:e},...n===void 0?{}:{CLAUDE_CLI_PATH:n},LOG_LEVEL:`WARNING`},i=this.configService.getConfigValue(`rootPath`);return await this._runSubprocess(`generate-pr`,r,i),{workflowRunId:e,testResults:{generated:this._summaryData.total,succeeded:this._summaryData.succeeded,failed:this._summaryData.failed,successMethodsCount:this._summaryData.succeeded,greenTests:this._totalGreenTests,redTests:this._summaryData.failed,skippedMethods:this._skippedMethods}}}_runSubprocess(e,t,n){return new Promise((r,i)=>{let a=(0,f.spawn)(`earlyai-agent`,[e],{env:t,cwd:n,stdio:[`ignore`,`pipe`,`pipe`]}),o=``;a.stdout.on(`data`,e=>{o+=e.toString();let t=o.split(`
|
|
32435
|
-
`);o=t.pop()??``;for(let e of t)if(e.trim())try{let t=JSON.parse(e);this._handleEvent(t)}catch{this.logger.debug(e)}}),a.stderr?.on(`data`,e=>{let t=e.toString().trim();t&&this.logger.debug(t)}),a.on(`close`,e=>{o.trim()&&this.logger.debug(o),e===0||e===1?r():i(Error(`earlyai-agent exited with code ${e}`))}),a.on(`error`,i)})}_handleEvent(e){switch(e.type){case`scan`:this._handleScan(e);break;case`extract`:this._handleExtract(e);break;case`start`:this._handleStart(e);break;case`skip`:this._handleSkip(e);break;case`progress`:this._handleProgress(e);break;case`done`:this._handleDone(e);break;case`error`:this._handleError(e);break;case`summary`:this._handleSummary(e);break;case`agent_hook`:this._handleAgentHook(e);break;default:this.logger.debug(`${JSON.stringify(e)}`)}}_handleScan(e){let t=e.files===1?``:`s`;this.logger.info(`Found ${e.files} source file${t}`)}_handleExtract(e){let t=e.functions??0,n=e.
|
|
32436
|
+
`);o=t.pop()??``;for(let e of t)if(e.trim())try{let t=JSON.parse(e);this._handleEvent(t)}catch{this.logger.debug(e)}}),a.stderr?.on(`data`,e=>{let t=e.toString().trim();t&&this.logger.debug(t)}),a.on(`close`,e=>{o.trim()&&this.logger.debug(o),e===0||e===1?r():i(Error(`earlyai-agent exited with code ${e}`))}),a.on(`error`,i)})}_handleEvent(e){switch(e.type){case`scan`:this._handleScan(e);break;case`extract`:this._handleExtract(e);break;case`start`:this._handleStart(e);break;case`skip`:this._handleSkip(e);break;case`progress`:this._handleProgress(e);break;case`done`:this._handleDone(e);break;case`error`:this._handleError(e);break;case`summary`:this._handleSummary(e);break;case`agent_hook`:this._handleAgentHook(e);break;default:this.logger.debug(`${JSON.stringify(e)}`)}}_handleScan(e){let t=e.files===1?``:`s`;this.logger.info(`Found ${e.files} source file${t}`)}_handleExtract(e){let t=e.functions??0,n=e.skipped??0;if(t===0&&n===0){this.logger.debug(` ${e.file} — 0 functions (skipped)`);return}if(t===0&&n>0){let t=n===1?``:`s`;this.logger.info(` ${e.file} — ${n} function${t} already tested (skipped)`);return}let r=t===1?``:`s`,i=[];e.changed!==void 0&&e.unchanged!==void 0&&i.push(`${e.changed} changed, ${e.unchanged} unchanged`),n>0&&i.push(`${n} already tested`);let a=i.length>0?` (${i.join(`, `)})`:``;this.logger.info(` ${e.file} — ${t} testable function${r}${a}`);let o=this._buildFilteredReasons(e);o.length>0&&this.logger.info(` ${o.join(`, `)}`)}_buildFilteredReasons(e){let t=[],n=e.classes_skipped??0,r=e.private_skipped??0;return n>0&&t.push(`${n} class${n===1?``:`es`} skipped`),r>0&&t.push(`${r} private function${r===1?``:`s`} skipped`),t}_handleStart(e){this._summaryData.total=e.total??0;let t=e.total??0,n=t===1?``:`s`,r=``;if(e.files!==void 0&&e.files>0){let t=e.files===1?``:`s`;r=` across ${e.files} file${t}`}this.logger.info(``),this.logger.info(`Generating tests for ${t} function${n}${r}...`)}_handleSkip(e){this._skippedMethods++;let t=e.file?.split(/[\\/]/).pop()??e.file;this.logger.info(` ⊘ ${e.method} (${t}) — already tested`)}_handleProgress(e){this._clearProgressTimer();let t=e.file?.split(/[\\/]/).pop()??e.file,n=` [${e.index}/${e.total}] ${e.method} (${t})`;this.logger.info(n),this._progressStartTime=Date.now(),this._progressTimer=setInterval(()=>{let t=Math.round((Date.now()-this._progressStartTime)/1e3);this.logger.info(` [${e.index}/${e.total}] ${e.method} — generating... (${t}s)`)},15e3)}_clearProgressTimer(){this._progressTimer&&=(clearInterval(this._progressTimer),null)}_handleDone(e){this._clearProgressTimer(),this._totalGreenTests+=e.tests_count??0;let t=``;if(e.tests_count!==void 0){let n=e.tests_count===1?``:`s`;t=` — ${e.tests_count} test${n}`}this.logger.info(` [${e.index}/${e.total}] ✓ ${e.method}${t} → ${e.test_file}`)}_handleError(e){if(this._clearProgressTimer(),e.method===void 0||e.method===``){this.logger.error(`${e.message}`);return}if(e.index===void 0){this.logger.error(`✗ ${e.method}: ${e.message}`);return}this.logger.error(` [${e.index}/${e.total}] ✗ ${e.method} — ${e.message}`)}_handleAgentHook(e){let t=e.passed??0,n=e.failed??0;switch(e.action){case`DONE`:this.logger.info(` ↳ all ${t} tests passed`);break;case`STOPPING`:this.logger.info(` ↳ stopping agent — all tests green`);break;case`BLOCKED`:this.logger.debug(` ↳ blocked tool ${e.tool??`unknown`} — generation complete`);break;case`PRUNE`:this.logger.info(` ↳ ${t} passed, ${n} failed → pruning`);break;case`REPAIR`:this.logger.info(` ↳ ${t} passed, ${n} failed → repairing`);break}}_handleSummary(e){this._clearProgressTimer(),this._summaryData.total=e.total??this._summaryData.total,this._summaryData.succeeded=e.succeeded??0,this._summaryData.failed=e.failed??0,this.logger.info(``),this.logger.info(`Done — ${e.succeeded}/${e.total} succeeded, ${e.failed} failed`)}};W4=U4=aQ([et(),iQ(0,Ze(cQ)),iQ(1,Ze(u4)),iQ(2,Ze(xQ)),iQ(3,Ze(m4)),iQ(4,Ze(sQ)),rQ(`design:paramtypes`,[typeof(z4=cQ!==void 0&&cQ)==`function`?z4:Object,typeof(B4=u4!==void 0&&u4)==`function`?B4:Object,typeof(V4=xQ!==void 0&&xQ)==`function`?V4:Object,typeof(H4=m4!==void 0&&m4)==`function`?H4:Object,Object])],W4);var G4,K4,q4,J4,Y4;let X4=class{constructor(e,t,n,r,i,a){this.gitService=e,this.configService=t,this.summaryService=n,this.scmHostService=r,this.workflowService=i,this.logger=a}async cleanupBlankEarlyFiles(){let e=await this.gitService.getEarlyFiles({absolute:!0}),t=[];for(let n of e)try{(await g.readFile(n,`utf8`)).trim().length===0&&(await g.unlink(n),t.push(n))}catch{this.logger.debug(`Could not read or remove file: ${n}`)}return t}async autoCommit(){if(!this.configService.getConfigValue(`autoCommit`))return this.logger.info(`Auto-commit is disabled — skipping commit step`),{committedFiles:[],error:``};let e=this.configService.getConfigValue(`refName`);return await this.gitService.commitFiles(e)}async finalize(e){if(this.summaryService.setTestGenerationData({generated:e.testResults.generated,succeeded:e.testResults.succeeded,failed:e.testResults.failed,successMethodsCount:e.testResults.successMethodsCount,committedFilesCount:e.committedFilesCount,greenTests:e.testResults.greenTests,redTests:e.testResults.redTests,skippedMethods:e.testResults.skippedMethods}),this.summaryService.setAutoCommitStatus(this.configService.getConfigValue(`autoCommit`)),await this.scmHostService.safePostSummaryToPr(),(0,B.isDefined)(e.workflowRunId))try{let t=this.summaryService.getWorkflowRunOutput();await this.workflowService.logEndOperation(e.workflowRunId,e.failureReason,t,e.resultCommitSha),this.logger.debug(`Successfully logged workflow end`)}catch(e){this.logger.warn(`Failed to log workflow end: ${e instanceof Error?e.message:`Unknown error`}`)}}};X4=aQ([et(),iQ(0,Ze(xQ)),iQ(1,Ze(cQ)),iQ(2,Ze(uQ)),iQ(3,Ze(lW.SCMHostService)),iQ(4,Ze(m4)),iQ(5,Ze(sQ)),rQ(`design:paramtypes`,[typeof(G4=xQ!==void 0&&xQ)==`function`?G4:Object,typeof(K4=cQ!==void 0&&cQ)==`function`?K4:Object,typeof(q4=uQ!==void 0&&uQ)==`function`?q4:Object,typeof(J4=hQ!==void 0&&hQ)==`function`?J4:Object,typeof(Y4=m4!==void 0&&m4)==`function`?Y4:Object,Object])],X4);function Z4(e){let t=e.command(dW.PR).alias(`generate-pr`).description(`Generate tests for the current project in pr context`);return ce(t,`--pr-number <number>`,`PR number`,{envName:`PR_NUMBER`,isRequired:!0}),ce(t,`--ref-name <ref>`,`Head reference for the PR`,{envName:`REF_NAME`,isRequired:!0}),ce(t,`--base-ref <ref>`,`Base reference for the PR`,{envName:`BASE_REF`}),ce(t,`-s, --test-structure <structure>`,`Test file structure`,{envName:`TEST_STRUCTURE`,def:`siblingFolder`}),ce(t,`-f, --test-framework <framework>`,`Test framework to use`,{envName:`TEST_FRAMEWORK`,def:`jest`}),ce(t,`--test-suffix <suffix>`,`Test file suffix`,{envName:`TEST_FILE_SUFFIX`,def:`test`}),ce(t,`--test-file-naming <naming>`,`Test file naming convention`,{envName:`TEST_FILE_NAMING`,def:`camelCase`}),ce(t,`-c, --max-concurrency <number>`,`Number of concurrent workers (1-4)`,{envName:`MAX_CONCURRENCY`,def:`3`}),ce(t,`--auto-commit <boolean>`,`Whether to auto-commit files`,{envName:`AUTO_COMMIT`,def:`true`}),ce(t,`--auto-commit-skip-ci <boolean>`,`Append [skip ci] to auto-commit message`,{envName:`AUTO_COMMIT_SKIP_CI`,def:`true`}),ce(t,`--test-command <command>`,`Custom test command to run`,{envName:`TEST_COMMAND`}),ce(t,`--coverage-command <command>`,`Custom coverage command to run`,{envName:`COVERAGE_COMMAND`}),ce(t,`--lint-command <command>`,`Custom lint command to run`,{envName:`LINT_COMMAND`}),ce(t,`--prettier-command <command>`,`Custom prettier command to run`,{envName:`PRETTIER_COMMAND`}),ce(t,`--disable-lint-rules <boolean>`,`Whether to disable failed lint rules in test files`,{envName:`DISABLE_LINT_RULES`,def:`false`}),ce(t,`--git-org <org>`,`Git organization name`,{envName:`GIT_ORG`}),ce(t,`--git-repo <repo>`,`Git repository name`,{envName:`GIT_REPO`}),ce(t,`--git-user-email <email>`,`Git user email for auto commit`,{envName:`GIT_USER_EMAIL`}),ce(t,`--git-user-name <name>`,`Git user name for auto commit`,{envName:`GIT_USER_NAME`}),ce(t,`--scm-provider <provider>`,`SCM provider (e.g., github, bitbucket)`,{envName:`SCM_PROVIDER`,def:`github`}),ce(t,`--keep-error-tests <boolean>`,`Whether to keep error tests`,{envName:`KEEP_ERROR_TESTS`,def:`false`}),ce(t,`--keep-failed-tests <boolean>`,`Whether to keep failed tests`,{envName:`KEEP_FAILED_TESTS`,def:`false`}),ce(t,`--conditional-keep <boolean>`,`Whether to return the last generated test result even when no green tests were produced`,{envName:`CONDITIONAL_KEEP`,def:`false`}),ce(t,`--continue-on-test-errors <boolean>`,`Whether to continue on test errors`,{envName:`CONTINUE_ON_TEST_ERRORS`,def:`false`}),ce(t,`--changed-methods-only <boolean>`,`Generate tests only for changed methods, not all methods in changed files`,{envName:`CHANGED_METHODS_ONLY`,def:`true`}),ce(t,`--skip-coverage-after <boolean>`,`Skip final coverage generation after test generation`,{envName:`SKIP_COVERAGE_AFTER`,def:`true`}),ce(t,`--max-testables <number>`,`Maximum number of testables to generate`,{envName:`MAX_TESTABLES`}),ce(t,`--per-function-timeout <number>`,`Per function timeout in milliseconds`,{envName:`PER_FUNCTION_TIMEOUT`}),ce(t,`--coverage-threshold <number>`,`Coverage threshold percentage (0-100)`,{envName:`COVERAGE_THRESHOLD`,def:`0`}),ce(t,`--reuse-coverage <boolean>`,`Whether to reuse coverage`,{envName:`REUSE_COVERAGE`,def:`false`}),ce(t,`--reuse-coverage-max-runs <number>`,`Max number of runs to reuse coverage (1-10)`,{envName:`REUSE_COVERAGE_MAX_RUNS`,def:`10`}),ce(t,`--experimental-agent-sdk <boolean>`,`Use experimental Agent SDK for test generation`,{envName:`EXPERIMENTAL_AGENT_SDK`,def:`true`}),t.addHelpText(`after`,`
|
|
32436
32437
|
Examples:
|
|
32437
32438
|
$ early generate-pr --api-key your-api-key --token your-token --pr-number 123 --ref-name feature/new-feature
|
|
32438
32439
|
$ early generate-pr -k your-api-key -f jest -s siblingFolder --test-command "npm run test -- $early_filename" --coverage-command "npm run coverage -- --coverageReporters=json --coverageDirectory=$early_coverage_dir"
|