@earlyai/cli 2.2.0 → 2.2.1
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 +11 -11
- 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:M,createCommand:ee,createArgument:N,createOption:te,CommanderError:P,InvalidArgumentError:F,InvalidOptionArgumentError:I,Command:L,Argument:ne,Option:re,Help:R}=u(s((e=>{let{Argument:t}=D(),{Command:n}=j(),{CommanderError:r,InvalidArgumentError:i}=E(),{Help:a}=O(),{Option:o}=k();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 z=`2.2.0`,ie=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=ie();function ae(e,t,n,{key:r=``,prefix:i=`EARLY`,parser:a,def:o,isRequired:s=!1,envName:c}={}){let l=new re(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 oe(e){return(typeof e==`object`&&!!e||typeof e==`function`)&&typeof e.then==`function`}function se(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 ce=Symbol.for(`@inversifyjs/common/islazyServiceIdentifier`);var le=class{[ce];#e;constructor(e){this.#e=e,this[ce]=!0}static is(e){return typeof e==`object`&&!!e&&!0===e[ce]}unwrap(){return this.#e()}};function ue(e,t,n){return Reflect.getOwnMetadata(t,e,n)}function de(e,t,n,r){Reflect.defineMetadata(t,n,e,r)}function fe(e,t,n,r,i){let a=r(ue(e,t,i)??n());Reflect.defineMetadata(t,a,e,i)}function pe(e){return Object.getPrototypeOf(e.prototype)?.constructor}const me=`@inversifyjs/container/bindingId`;function he(){let e=ue(Object,me)??0;return e===2**53-1?de(Object,me,-(2**53-1)):fe(Object,me,()=>e,e=>e+1),e}const ge={Request:`Request`,Singleton:`Singleton`,Transient:`Transient`},_e={ConstantValue:`ConstantValue`,DynamicValue:`DynamicValue`,Factory:`Factory`,Instance:`Instance`,Provider:`Provider`,ResolvedValue:`ResolvedValue`,ServiceRedirection:`ServiceRedirection`};function*ve(...e){for(let t of e)yield*t}var ye=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)}}},be;(function(e){e.moduleId=`moduleId`,e.serviceId=`serviceId`})(be||={});var xe=class e{#e;#t;constructor(e,t){this.#e=t??new ye({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(be.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 ve(...t)}removeAllByModuleId(e){this.#e.removeByRelation(be.moduleId,e)}removeAllByServiceId(e){this.#e.removeByRelation(be.serviceId,e)}};const Se=`@inversifyjs/core/classMetadataReflectKey`;function Ce(){return{constructorArguments:[],lifecycle:{postConstructMethodNames:new Set,preDestroyMethodNames:new Set},properties:new Map,scope:void 0}}const we=`@inversifyjs/core/pendingClassMetadataCountReflectKey`,Te=Symbol.for(`@inversifyjs/core/InversifyCoreError`);var Ee=class e extends Error{[Te];kind;constructor(e,t,n){super(t,n),this[Te]=!0,this.kind=e}static is(e){return typeof e==`object`&&!!e&&!0===e[Te]}static isErrorOfKind(t,n){return e.is(t)&&t.kind===n}},De,Oe,ke,Ae,je;function Me(e){let t=ue(e,Se)??Ce();if(!function(e){let t=ue(e,we);return t!==void 0&&t!==0}(e))return function(e,t){let n=[];if(t.length<e.length)throw new Ee(De.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 Ee(De.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!==Oe.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===Oe.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 Ee(De.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 Ee(De.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:M,createCommand:ee,createArgument:N,createOption:te,CommanderError:P,InvalidArgumentError:F,InvalidOptionArgumentError:I,Command:L,Argument:ne,Option:re,Help:R}=u(s((e=>{let{Argument:t}=D(),{Command:n}=j(),{CommanderError:r,InvalidArgumentError:i}=E(),{Help:a}=O(),{Option:o}=k();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 z=`2.2.1`,ie=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=ie();function ae(e,t,n,{key:r=``,prefix:i=`EARLY`,parser:a,def:o,isRequired:s=!1,envName:c}={}){let l=new re(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 oe(e){return(typeof e==`object`&&!!e||typeof e==`function`)&&typeof e.then==`function`}function se(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 ce=Symbol.for(`@inversifyjs/common/islazyServiceIdentifier`);var le=class{[ce];#e;constructor(e){this.#e=e,this[ce]=!0}static is(e){return typeof e==`object`&&!!e&&!0===e[ce]}unwrap(){return this.#e()}};function ue(e,t,n){return Reflect.getOwnMetadata(t,e,n)}function de(e,t,n,r){Reflect.defineMetadata(t,n,e,r)}function fe(e,t,n,r,i){let a=r(ue(e,t,i)??n());Reflect.defineMetadata(t,a,e,i)}function pe(e){return Object.getPrototypeOf(e.prototype)?.constructor}const me=`@inversifyjs/container/bindingId`;function he(){let e=ue(Object,me)??0;return e===2**53-1?de(Object,me,-(2**53-1)):fe(Object,me,()=>e,e=>e+1),e}const ge={Request:`Request`,Singleton:`Singleton`,Transient:`Transient`},_e={ConstantValue:`ConstantValue`,DynamicValue:`DynamicValue`,Factory:`Factory`,Instance:`Instance`,Provider:`Provider`,ResolvedValue:`ResolvedValue`,ServiceRedirection:`ServiceRedirection`};function*ve(...e){for(let t of e)yield*t}var ye=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)}}},be;(function(e){e.moduleId=`moduleId`,e.serviceId=`serviceId`})(be||={});var xe=class e{#e;#t;constructor(e,t){this.#e=t??new ye({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(be.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 ve(...t)}removeAllByModuleId(e){this.#e.removeByRelation(be.moduleId,e)}removeAllByServiceId(e){this.#e.removeByRelation(be.serviceId,e)}};const Se=`@inversifyjs/core/classMetadataReflectKey`;function Ce(){return{constructorArguments:[],lifecycle:{postConstructMethodNames:new Set,preDestroyMethodNames:new Set},properties:new Map,scope:void 0}}const we=`@inversifyjs/core/pendingClassMetadataCountReflectKey`,Te=Symbol.for(`@inversifyjs/core/InversifyCoreError`);var Ee=class e extends Error{[Te];kind;constructor(e,t,n){super(t,n),this[Te]=!0,this.kind=e}static is(e){return typeof e==`object`&&!!e&&!0===e[Te]}static isErrorOfKind(t,n){return e.is(t)&&t.kind===n}},De,Oe,ke,Ae,je;function Me(e){let t=ue(e,Se)??Ce();if(!function(e){let t=ue(e,we);return t!==void 0&&t!==0}(e))return function(e,t){let n=[];if(t.length<e.length)throw new Ee(De.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 Ee(De.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!==Oe.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===Oe.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 Ee(De.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 Ee(De.missingInjectionDecorator,`Invalid class metadata at type ${e.name}:\n\n${n.join(`
|
|
21
21
|
|
|
22
22
|
`)}`)})(e,t)}function Ne(e,t){let n=Me(t).scope??e.scope;return{cache:{isRight:!1,value:void 0},id:he(),implementationType:t,isSatisfiedBy:()=>!0,moduleId:void 0,onActivation:void 0,onDeactivation:void 0,scope:n,serviceIdentifier:t,type:_e.Instance}}function Pe(e){return e.isRight?{isRight:!0,value:e.value}:e}function Fe(e){switch(e.type){case _e.ConstantValue:case _e.DynamicValue:return function(e){return{cache:Pe(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 _e.Factory:return function(e){return{cache:Pe(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 _e.Instance:return function(e){return{cache:Pe(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 _e.Provider:return function(e){return{cache:Pe(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 _e.ResolvedValue:return function(e){return{cache:Pe(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 _e.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`})(De||={}),function(e){e[e.unknown=32]=`unknown`}(Oe||={}),function(e){e.id=`id`,e.moduleId=`moduleId`,e.serviceId=`serviceId`}(ke||={});var Ie=class e extends ye{_buildNewInstance(t){return new e(t)}_cloneModel(e){return Fe(e)}},Le=class e{#e;#t;#n;constructor(e,t,n){this.#t=n??new Ie({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(ke.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(ke.id,e)??this.#n()?.getById(e)}getByModuleId(e){return this.#t.get(ke.moduleId,e)??this.#n()?.getByModuleId(e)}getNonParentBindings(e){return this.#t.get(ke.serviceId,e)}getNonParentBoundServices(){return this.#t.getAllKeys(ke.serviceId)}removeById(e){this.#t.removeByRelation(ke.id,e)}removeAllByModuleId(e){this.#t.removeByRelation(ke.moduleId,e)}removeAllByServiceId(e){this.#t.removeByRelation(ke.serviceId,e)}set(e){let t={[ke.id]:e.id,[ke.serviceId]:e.serviceIdentifier};e.moduleId!==void 0&&(t[ke.moduleId]=e.moduleId),this.#t.add(e,t)}#r(e){if(this.#e===void 0||typeof e!=`function`)return;let t=Ne(this.#e,e);return this.set(t),t}};(function(e){e.moduleId=`moduleId`,e.serviceId=`serviceId`})(Ae||={});var Re=class e{#e;#t;constructor(e,t){this.#e=t??new ye({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(Ae.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 ve(...t)}removeAllByModuleId(e){this.#e.removeByRelation(Ae.moduleId,e)}removeAllByServiceId(e){this.#e.removeByRelation(Ae.serviceId,e)}};function ze(){return 0}function Be(e){return t=>{t!==void 0&&t.kind===Oe.unknown&&fe(e,we,ze,e=>e-1)}}function Ve(e,t){return(...n)=>r=>{if(r===void 0)return e(...n);if(r.kind===je.unmanaged)throw new Ee(De.injectionDecoratorConflict,`Unexpected injection found. Multiple @inject, @multiInject or @unmanaged decorators found`);return t(r,...n)}}function He(e){if(e.kind!==Oe.unknown&&!0!==e.isFromTypescriptParamType)throw new Ee(De.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`})(je||={});const V=Ve(function(e,t,n){return e===je.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 He(e),t===je.multipleInjection?{...e,chained:r?.chained??!1,kind:t,value:n}:{...e,kind:t,value:n}});function Ue(e,t){return n=>{let r=n.properties.get(t);return n.properties.set(t,e(r)),n}}var We;function H(e,t,n,r){if(Ee.isErrorOfKind(r,De.injectionDecoratorConflict)){let i=function(e,t,n){if(n===void 0){if(t===void 0)throw new Ee(De.unknown,`Unexpected undefined property and index values`);return{kind:We.property,property:t,targetClass:e.constructor}}return typeof n==`number`?{index:n,kind:We.parameter,targetClass:e}:{kind:We.method,method:t,targetClass:e}}(e,t,n);throw new Ee(De.injectionDecoratorConflict,`Unexpected injection error.\n\nCause:\n\n${r.message}\n\nDetails\n\n${function(e){switch(e.kind){case We.method:return`[class: "${e.targetClass.name}", method: "${e.method.toString()}"]`;case We.parameter:return`[class: "${e.targetClass.name}", index: "${e.index.toString()}"]`;case We.property:return`[class: "${e.targetClass.name}", property: "${e.property.toString()}"]`}}(i)}`,{cause:r})}throw r}function Ge(e,t){return(n,r,i)=>{try{i===void 0?function(e,t){let n=Ke(e,t);return(e,t)=>{fe(e.constructor,Se,Ce,Ue(n(e),t))}}(e,t)(n,r):typeof i==`number`?function(e,t){let n=Ke(e,t);return(e,t,r)=>{if(!function(e,t){return typeof e==`function`&&t===void 0}(e,t))throw new Ee(De.injectionDecoratorConflict,`Found an @inject decorator in a non constructor parameter.\nFound @inject decorator at method "${t?.toString()??``}" at class "${e.constructor.name}"`);fe(e,Se,Ce,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=Ke(e,t);return(e,t,r)=>{if(!function(e){return e.set!==void 0}(r))throw new Ee(De.injectionDecoratorConflict,`Found an @inject decorator in a non setter property method.\nFound @inject decorator at method "${t.toString()}" at class "${e.constructor.name}"`);fe(e.constructor,Se,Ce,Ue(n(e),t))}}(e,t)(n,r,i)}catch(e){H(n,r,i,e)}}}function Ke(e,t){return n=>{let r=t(n);return t=>(r(t),e(t))}}function qe(e){return Ge(V(je.singleInjection,e),Be)}(function(e){e[e.method=0]=`method`,e[e.parameter=1]=`parameter`,e[e.property=2]=`property`})(We||={});const Je=`@inversifyjs/core/classIsInjectableFlagReflectKey`,Ye=[Array,BigInt,Boolean,Function,Number,Object,String];function Xe(e){let t=ue(e,`design:paramtypes`);t!==void 0&&fe(e,Se,Ce,function(e){return t=>(e.forEach((e,n)=>{var r;t.constructorArguments[n]!==void 0||(r=e,Ye.includes(r))||(t.constructorArguments[n]=function(e){return{isFromTypescriptParamType:!0,kind:je.singleInjection,name:void 0,optional:!1,tags:new Map,value:e}}(e))}),t)}(t))}function Ze(e){return t=>{(function(e){if(ue(e,Je)!==void 0)throw new Ee(De.injectionDecoratorConflict,`Cannot apply @injectable decorator multiple times at class "${e.name}"`);de(e,Je,!0)})(t),Xe(t),e!==void 0&&fe(t,Se,Ce,t=>({...t,scope:e}))}}function Qe(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 $e(e,t,n){return e?new Set([...t,...n]):n}function et(e,t,n){let r=e.lifecycle?.extendPostConstructMethods??!0,i=$e(e.lifecycle?.extendPreDestroyMethods??!0,t.lifecycle.preDestroyMethodNames,n.lifecycle.preDestroyMethodNames);return{postConstructMethodNames:$e(r,t.lifecycle.postConstructMethodNames,n.lifecycle.postConstructMethodNames),preDestroyMethodNames:i}}function tt(e,t,n){let r;return r=e.extendProperties??!0?new Map(ve(t.properties,n.properties)):n.properties,r}function nt(e){return t=>{fe(t,Se,Ce,function(e,t){return n=>({constructorArguments:Qe(e,t,n),lifecycle:et(e,t,n),properties:tt(e,t,n),scope:n.scope})}(e,Me(e.type)))}}function rt(e){return t=>{let n=pe(t);if(n===void 0)throw new Ee(De.injectionDecoratorConflict,`Expected base type for type "${t.name}", none found.`);nt({...e,type:n})(t)}}function it(e){return t=>{let n=[],r=pe(t);for(;r!==void 0&&r!==Object;){let e=r;n.push(e),r=pe(e)}n.reverse();for(let r of n)nt({...e,type:r})(t)}}var at;function ot(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 st(e,t){if(ot(t)){let n=function(e){let t=[...e];return t.length===0?`(No dependency trace)`:t.map(se).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 Ee(De.planning,`Circular dependency found: ${n}`,{cause:t})}throw t}(function(e){e[e.multipleInjection=0]=`multipleInjection`,e[e.singleInjection=1]=`singleInjection`})(at||={});const U=Symbol.for(`@inversifyjs/core/LazyPlanServiceNode`);var ct=class{[U];_serviceIdentifier;_serviceNode;constructor(e,t){this[U]=!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[U]}invalidate(){this._serviceNode=void 0}isExpanded(){return this._serviceNode!==void 0}_getNode(){return this._serviceNode===void 0&&(this._serviceNode=this._buildPlanServiceNode()),this._serviceNode}},lt=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 ut(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=Ne(e.autobindOptions,r);e.operations.setBinding(n),n.isSatisfiedBy(t)&&i.push(n)}return i}var dt=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 ft(e){let t=new Map;return e.rootConstraints.tag!==void 0&&t.set(e.rootConstraints.tag.key,e.rootConstraints.tag.value),new dt({elem:{getAncestorsCalled:!1,name:e.rootConstraints.name,serviceIdentifier:e.rootConstraints.serviceIdentifier,tags:t},previous:void 0})}function pt(e){return e.redirections!==void 0}function mt(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: "${se(a[a.length-1]??n)}".${vt(a)}\n\nRegistered bindings:\n\n${e.map(e=>function(e){switch(e.type){case _e.Instance:return`[ type: "${e.type}", serviceIdentifier: "${se(e.serviceIdentifier)}", scope: "${e.scope}", implementationType: "${e.implementationType.name}" ]`;case _e.ServiceRedirection:return`[ type: "${e.type}", serviceIdentifier: "${se(e.serviceIdentifier)}", redirection: "${se(e.targetServiceIdentifier)}" ]`;default:return`[ type: "${e.type}", serviceIdentifier: "${se(e.serviceIdentifier)}", scope: "${e.scope}" ]`}}(e.binding)).join(`
|
|
23
23
|
`)}\n\nTrying to resolve bindings for "${gt(n,r)}".${_t(i)}`;throw new Ee(De.planning,t)}t||ht(n,r,i,a)}(e,t,i,a,n.elem,r):function(e,t,n,r,i,a){e!==void 0||t||ht(n,r,i,a)}(e,t,i,a,n.elem,r)}function ht(e,t,n,r){let i=`No bindings found for service: "${se(r[r.length-1]??e)}".\n\nTrying to resolve bindings for "${gt(e,t)}".${vt(r)}${_t(n)}`;throw new Ee(De.planning,i)}function gt(e,t){return t===void 0?`${se(e)} (Root service)`:se(t)}function _t(e){let t=e.tags.size===0?``:`\n- tags:\n - ${[...e.tags.keys()].map(e=>e.toString()).join(`
|
|
@@ -31998,7 +31998,7 @@ https://www.w3ctech.com/topic/2226`));let i=t(...r);return i.postcssPlugin=e,i.p
|
|
|
31998
31998
|
`);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=R(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=z(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=R(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=R(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=z(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 I(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 L=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 ne(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 re(e,t,n,r){return!(!t||!t.has(r))||!(!e||!e.has(n))}function R(e,t,n,r){let i=e.indexOf(t,n);if(i===-1)throw Error(r);return i+t.length-1}function z(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 ie(e,t,n){let r=n,i=1;for(;n<e.length;n++)if(e[n]===`<`)if(e[n+1]===`/`){let a=R(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=R(e,`?>`,n+1,`StopNode is not closed.`);else if(e.substr(n+1,3)===`!--`)n=R(e,`-->`,n+3,`StopNode is not closed.`);else if(e.substr(n+1,2)===`![`)n=R(e,`]]>`,n,`StopNode is not closed.`)-2;else{let r=z(e,n,`>`);r&&((r&&r.tagName)===t&&r.tagExp[r.tagExp.length-1]!==`/`&&i++,n=r.closeIndex)}}function B(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 ae=x.getMetaDataSymbol();function oe(e,t){return se(e,t)}function se(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=se(o[s],t,c),n=ue(e,t);o[ae]!==void 0&&(e[ae]=o[ae]),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 j(this.options);n.addExternalEntities(this.externalEntities);let r=n.parseXml(e);return this.options.preserveOrder||r===void 0?r:oe(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=`
|
|
31999
31999
|
`),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=`>
|
|
32000
32000
|
`,this.newLine=`
|
|
32001
|
-
`):(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})()})),TU=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(xi()),f=l(Si()),p=l(require(`node:fs/promises`)),m=l(require(`node:async_hooks`)),h=l(ie()),g=l(Ni()),_=l(jc()),v=l(require(`node:crypto`)),y=l(lL()),b=l(gj()),x=l(_R()),S=l((AA(),d(kA))),C=l(require(`node:fs`)),w=l(JR()),T=l(_B()),E=l(require(`node:child_process`)),D=l(require(`node:util`)),O=l(require(`@prisma/internals`)),k=l(pB()),A=l(require(`node:zlib`)),j=l(yV()),M=l(xV()),ee=l(DV()),N=l(MV()),te=l(require(`node:os`)),P=l(require(`node:events`)),F=l(xee()),I=l(hU()),L=l(SU()),ne=l(CU()),re=l(wU()),R=l(AH()),z=l(require(`node:process`));l(require(`node:readline`)),l(require(`node:tty`));let B=l(require(`node:path`)),ae=l(require(`@anthropic-ai/claude-agent-sdk`)),oe={DELETE:`delete`,COMMENT_OUT:`comment out`,KEEP:`keep`,SKIP:`skip`},se={GREEN:`Green`,GREY:`Grey`,RED:`Red`,NA:`NA`},ce={GREEN:`Green`,GREY:`Grey`,RUNTIME_ERROR:`RuntimeError`},le=function(e){return e.IDE=`IDE`,e.CLI=`CLI`,e}({}),ue=function(e){return e.SIBLING_FOLDER=`siblingFolder`,e.ROOT_FOLDER=`rootFolder`,e}({}),de=function(e){return e.JEST=`jest`,e.MOCHA=`mocha`,e.VITEST=`vitest`,e.PYTEST=`pytest`,e}({}),fe=function(e){return e.SPEC=`spec`,e.TEST=`test`,e}({}),pe=function(e){return e.CAMEL_CASE=`camelCase`,e.KEBAB_CASE=`kebabCase`,e}({}),me=function(e){return e.NONE=`none`,e.CATEGORIES=`categories`,e}({}),he=function(e){return e.NEW_CODE_FILE=`newCodeFile`,e.OVERRIDE_CODE_FILE=`overrideCodeFile`,e}({}),ge=function(e){return e.ON=`on`,e.OFF=`off`,e}({}),_e={DEFAULT:0,MIN:0,MAX:100},ve={DEFAULT:5,MIN:1,MAX:50};u.z.object({rootPath:u.z.string().default(process.cwd()),testStructure:u.z.enum(ue).optional(),testFramework:u.z.enum(de).optional(),testSuffix:u.z.enum(fe).optional(),testFileName:u.z.enum(pe).optional(),calculateCoverage:u.z.enum(ge).optional(),coverageThreshold:u.z.number().min(_e.MIN).max(_e.MAX).default(_e.DEFAULT),requestSource:u.z.enum(le).optional(),concurrency:u.z.number().min(ve.MIN).max(ve.MAX).default(ve.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(oe).optional(),redTestBehaviour:u.z.enum(oe).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()});var ye=`@earlyai/ts-agent`,be=`0.71.0`;let xe={VSCODE:`vscode`,GITHUB_ACTION:`github-action`,UNKNOWN:`unknown`},Se=`$early_filename`,Ce=`$early_coverage_dir`,we=`npx --no eslint ${Se}`,Te=`npx --no prettier ${Se} --write`,Ee={rootPath:process.cwd(),isSiblingFolderStructured:!0,gitURL:`https://github.com/your-owner/your-repo`,testFramework:de.JEST,greyTestBehaviour:oe.DELETE,redTestBehaviour:oe.DELETE,keepErrorTests:!1,keepFailedTests:!1,conditionalKeep:!1,continueOnTestErrors:!0,generatedTestStructure:me.CATEGORIES,isRootFolderStructured:!1,clientSource:xe.GITHUB_ACTION,backendURL:`https://api.startearly.ai`,requestSource:le.CLI,userPrompt:``,testLocation:`__tests__`,coverageThreshold:_e.DEFAULT,concurrency:5,testFileFormat:`ts`,outputType:he.NEW_CODE_FILE,shouldRefreshCoverage:!0,kebabCaseFileName:!1,earlyTestFilenameSuffix:`.early.${fe.TEST}`,testSuffix:fe.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:we,prettierCommand:Te,disableLintRules:!1,ignoreAsAnyLintErrors:!0,allowUndefinedLintErrors:!0,perFunctionTimeout:24e4,removeComments:!0,experimentalAgentSdk:!1,agentSdkModel:void 0,agentSdkBudget:void 0,debug:!1,verbose:!1},De=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`.split(`.`).reduce((t,n)=>(0,h.isDefined)(e[n])?{...t,[n]:e[n]}:t,{}),n={...(0,h.isDefined)(e.testStructure)&&{isSiblingFolderStructured:e.testStructure===ue.SIBLING_FOLDER,isRootFolderStructured:e.testStructure===ue.ROOT_FOLDER},...(0,h.isDefined)(e.testFileName)&&{kebabCaseFileName:e.testFileName===pe.KEBAB_CASE},...(0,h.isDefined)(e.calculateCoverage)&&{shouldRefreshCoverage:e.calculateCoverage===ge.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===le.IDE?xe.VSCODE:xe.GITHUB_ACTION}};return{...t,...n}};var Oe=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})),ke=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})),Ae=l(Oe()),je=l(ke()),Me,Ne;let Pe=class{config;constructor(e,t={}){if(!(0,h.isDefined)(e)){this.config=Ee;return}let n=De(e);this.config=(0,h.merge)(Ee,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};Pe=(0,je.default)([(0,_.injectable)(`Singleton`),(0,Ae.default)(`design:paramtypes`,[typeof(Me=typeof Partial<`u`&&Partial)==`function`?Me:Object,typeof(Ne=typeof Partial<`u`&&Partial)==`function`?Ne:Object])],Pe);var Fe=new _.Container({autobind:!0,defaultScope:`Singleton`});let Ie=()=>Fe.get(Pe);var Le=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 Re=function(e){return e.DEFAULT=`default`,e.VERBOSE=`verbose`,e.DEBUG=`debug`,e}({}),ze=function(e){return e.INFO=`info`,e.WARN=`warn`,e}({});function Be(){return(0,v.randomUUID)()}function Ve(){let e=``;for(let t=0;t<8;t++)e+=`abcdefghijklmnopqrstuvwxyz0123456789`.charAt(Math.floor(Math.random()*36));return e}var He=l(Oe()),V=l(ke()),Ue=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 We=class{loggerProvider;config;constructor(e){this.config=e,this.loggerProvider=new x.LoggerProvider({resource:(0,b.resourceFromAttributes)({[S.ATTR_SERVICE_NAME]:ye,[S.ATTR_SERVICE_VERSION]:be})}),this.initializeExporters(),this.setGlobalLoggerProvider()}getLogger(e){return this.loggerProvider.getLogger(e)}initializeExporters(){let e=[];if(this.config.consoleEnabled){let t=new Ue;e.push(new x.SimpleLogRecordProcessor(t))}if(this.config.azureEnabled&&(0,h.isDefined)(this.config.azureConnectionString)){let t=new y.AzureMonitorLogExporter({connectionString:this.config.azureConnectionString});e.push(new x.BatchLogRecordProcessor(t))}this.loggerProvider=new x.LoggerProvider({processors:e})}setGlobalLoggerProvider(){g.logs.setGlobalLoggerProvider(this.loggerProvider)}};We=(0,V.default)([(0,_.injectable)(),(0,He.default)(`design:paramtypes`,[Object])],We),l(Oe()),l(ke());let H=new class{storage;otelService;otelLogger;isConsoleEnabled;printBuffer;default=this.createLogObject(Re.DEFAULT);verbose=this.createLogObject(Re.VERBOSE);constructor(e){this.storage=new m.AsyncLocalStorage,this.otelService=new We(e),this.otelLogger=this.otelService.getLogger(`ts-agent`),this.isConsoleEnabled=e.consoleEnabled,this.printBuffer=new Le(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(Re.DEBUG))&&console.info(r)}logToOpenTelemetry(e,t){let n=this.storage.getStore(),r={service:ye,version:be};(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:Ve(),requestId:Be()};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:Be()}}:void 0}async runWithContext(e,t){return(0,h.isDefined)(e)?this.storage.run(e,t):t()}isLevelEnabled(e){switch(e){case Re.DEFAULT:return!0;case Re.VERBOSE:return Ie().isVerbose()||Ie().isDebug();case Re.DEBUG:return Ie().isDebug()}}createLogObject(e){return{info:(t,...n)=>{this.isLevelEnabled(e)&&this.printOrBuffer(ze.INFO,this.formatPrint(t,...n))},warn:(t,...n)=>{this.isLevelEnabled(e)&&this.printOrBuffer(ze.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 Ge(e){return function(t,n,r){return(0,h.isDefined)(e)&&H.addContext(e),H.withContext(t,n,r)}}var Ke=class e{rootPath;absolutePath;static EARLY_FILENAME_VAR=`$early_filename`;constructor(e){this.rootPath=f.default.normalizeTrim(Ie().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(Ie().getRootPath()),n))}static fromAbsolutePath(t){let n=f.default.normalizeTrim(t);return new e(f.default.relative(f.default.normalizeTrim(Ie().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 qe={WIN32:`win32`,DARWIN:`darwin`,LINUX:`linux`},Je={JAVASCRIPT:`javascript`,TYPESCRIPT:`typescript`,PYTHON:`python`},Ye=e=>{let t=Ie().getRootPath();return f.default.resolve(t,e)},Xe=e=>{let t=Ie().getRootPath(),n=f.default.normalize(e);return f.default.relative(t,n)},Ze=e=>({".js":`javascript`,".mjs":`javascript`,".cjs":`javascript`,".jsx":`javascript`,".ts":`typescript`,".tsx":`typescript`,".py":`python`})[e.toLowerCase()]??`javascript`;function Qe(e){return Ze((0,f.extname)(e))}function $e(e){return Ze((0,f.extname)(e))===`typescript`}function et(e){return Ze((0,f.extname)(e))===Je.PYTHON}function tt(e){let t=Ie().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===qe.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 nt(e){return e.startsWith(`../`)?`../${e}`:e.startsWith(`./`)?`.${e}`:e}function rt(e){let t=f.default.normalize(Ye(e)),n=f.default.normalize((0,w.default)([`package.json`,`project.json`],{cwd:t})??``);return n?Xe((0,f.dirname)(n)).slice(1):``}function it(e,t,n){if(!ot(e))return e;let r=n===``?t:t.replace(n,``),i=n===``?U(r):st(r),a=r.split(`/`).slice(0,-1),o=at(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 at(e,t){return e.split(t).length-1}function ot(e){return e.startsWith(`../`)||e.startsWith(`./`)}function st(e){let t=at(e,`/`);return`../`.repeat(t-1)}function U(e){let t=at(e,`/`);return`../`.repeat(t+1)}function ct(e){return e?.includes(`node_modules/`)}let lt=e=>e.replaceAll(/[.*+?^${}()|[\]\\]/g,String.raw`\$&`);function ut(e,t){let n=f.default.isAbsolute(e)?e:Ye(e);return(0,w.default)(t,{cwd:n})}function dt(e,t){let n=ut(e,t);if(!(0,h.isDefined)(n))return;let r=C.readFileSync(n,`utf8`);return JSON.parse(r)}function ft(e){return dt(e,`package.json`)}function pt(e,t){let{dependencies:n={},devDependencies:r={}}=e;return Object.keys({...r,...n}).includes(t)}let mt=[{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}],ht=[`@typescript-eslint/no-undefined`,`unicorn/no-useless-undefined`,`no-undefined`];async function gt(e){for(let{path:t,isFlat:n}of mt){let r=f.default.join(e,t);if(await Ke.fromAbsolutePath(r).isFileExists())return{path:r,isFlat:n}}return ft(e)?.eslint?{path:ut(e,`package.json`),isFlat:!1}:{path:null,isFlat:!1}}let _t={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`},vt={CODE_EXTRACTOR:`code-extractor`,CODE_REFINEMENT:`code-refinement`,TEST_MANAGEMENT:`test-management`,TEST_VALIDATOR:`test-validator`,CONFIG_FILE:`config-file`,COMMAND_EXECUTION:`command-execution`},yt=[`.jsx`,`.tsx`],bt=[`it`,`test`,`it.each`,`test.each`],xt=function(e){return e.Default=`default`,e.ObjectDefault=`object-default`,e.Named=`named`,e.Unknown=`unknown`,e.NotExported=`not-exported`,e}({}),St=function(e){return e.PRIVATE=`private`,e.PROTECTED=`protected`,e.PUBLIC=`public`,e}({}),Ct=function(e){return e.REACT=`react`,e.ANGULAR=`angular`,e}({}),wt=`unknown`,Tt=(0,D.promisify)(E.default.exec);async function Et(e,{cwd:t=Ie().getRootPath(),timeout:n=1e4}={}){return(await Tt(e,{cwd:t,maxBuffer:500*1024,timeout:n}))?.stdout?.toString()??``}let Dt=e=>{let t=Ye(e);return(0,w.default)(`jest.config.+(js|ts|mjs|cjs|json)`,{cwd:t})},Ot=e=>(0,h.isObject)(e)&&(0,h.isString)(e.rootDir),kt=async e=>{let t;if(H.addContext({subCategory:vt.CONFIG_FILE}),(0,h.isDefined)(e)){let n=Dt(e);n!==null&&(t=(0,f.dirname)(n))}t??=Ie().getRootPath();let n;try{if(n=await Et(`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=>Ot(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`)},At=async()=>{let e=[Ie().getRootPath()],t=f.default.join(`node_modules`,`.prisma`,`client`,`index.d.ts`),n=e.map(e=>f.default.join(e,t)).map(e=>Ke.fromAbsolutePath(e));return(await(0,h.filterAsync)(n,e=>e.isFileExists())).map(e=>e.getAbsoluteFilePath())},jt=async()=>{try{let e=Ie().getRootPath();if(!(0,h.isDefined)(e))return[];let t=await(0,O.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,O.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 Ke.fromAbsolutePath(n).isFileExists()&&r.add(n)}}return[...r]}catch(e){return H.error(`Failed to get prisma typings paths`,e),[]}},Mt=async()=>(await Promise.all([At(),jt()])).flat(),Nt=async(e,t=!1,n)=>{let r=`!**/node_modules/**`;if(t)return new T.Project({useInMemoryFileSystem:!0,compilerOptions:n});let i=$e(e),a=Pt((0,f.dirname)(Ye(e)),Ie().isSiblingFolderStructured());if(!i&&!(0,h.isDefined)(a)){let t=await It(e);if(!(0,h.isDefined)(t)||(0,h.isEmpty)(t))throw Error(`Cannot find source code path in jest config`);let n=new T.Project({compilerOptions:{allowJs:!0,maxNodeModuleJsDepth:0},useInMemoryFileSystem:!1});return n.addSourceFilesAtPaths([...t,r]),n}if(!i&&(0,h.isDefined)(a)){let t=new T.Project({tsConfigFilePath:a,compilerOptions:{allowJs:!0,maxNodeModuleJsDepth:0}}),n=await It(e);return t.addSourceFilesAtPaths([...n,r]),t}let o=new T.Project({tsConfigFilePath:a,compilerOptions:{maxNodeModuleJsDepth:0}}),s=await Mt();for(let e of s)o.addSourceFileAtPath(e);return o},Pt=(e,t)=>{let n;try{n=Ft(e)}catch{t&&(n=Ft((0,f.dirname)(e)))}return n},Ft=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,C.existsSync)(t))return Ft((0,f.dirname)(t));if((0,C.existsSync)(e))return e;if((0,C.existsSync)(r))return r;let i=(0,C.readdirSync)(t);for(let e of i)if(n.test(e))return(0,f.join)(t,e);t=(0,f.dirname)(t)}},It=async e=>{let t=await kt(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[Ye(rt(e))]};var Lt=l(Oe()),Rt=l(ke());let zt=`The ts-morph project is not initialized.`,Bt=new class{storage=new m.AsyncLocalStorage;_project;clear(){this._project=void 0}async init(e,t,n){let r=Ye(e);if((0,h.isDefined)(this._project))return this._project.addSourceFileAtPathIfExists(r);this._project=await Nt(e,t,n);let i=this.storage.getStore();if((0,h.isDefined)(i))return this._project.addSourceFileAtPathIfExists(r)}add(e,t){let n=Ye(e),r=this.storage.getStore()?.getProject();if(!(0,h.isDefined)(r))throw Error(zt);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=Ye(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=Ye(e),n=this.storage.getStore()?.getProject();if(!(0,h.isDefined)(n))throw Error(zt+` 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=Ye(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}},Vt=Bt.withContext,Ht=async e=>{class t{async fn(){return e()}}(0,Rt.default)([Vt,(0,Lt.default)(`design:type`,Function),(0,Lt.default)(`design:paramtypes`,[]),(0,Lt.default)(`design:returntype`,Promise)],t.prototype,`fn`,null),await new t().fn()},Ut=e=>{let t=e?.asKind(T.SyntaxKind.ExpressionStatement)?.getExpression();if(!(0,h.isDefined)(t))return;let n=t.asKind(T.SyntaxKind.CallExpression)?.getArguments()?.at(-1),r=n?.asKind(T.SyntaxKind.ArrowFunction)?.getBody(),i=n?.asKind(T.SyntaxKind.FunctionExpression)?.getBody();return r?.asKind(T.SyntaxKind.Block)??i?.asKind(T.SyntaxKind.Block)},Wt=e=>T.Node.isExpressionStatement(e)&&e.getFirstChildByKind(T.SyntaxKind.CallExpression)?.getFirstChildByKind(T.SyntaxKind.Identifier)?.getText()===`describe`,Gt=e=>e.getStatements().filter(e=>Wt(e)),Kt=e=>{let t=e.getExpression().getFirstChild()?.getText();return!(0,h.isDefined)(t)||(0,h.isEmpty)(t)?!1:bt.some(e=>t.startsWith(e))},qt=e=>{let t=Ut(e);return(0,h.isDefined)(t)?t.getChildrenOfKind(T.SyntaxKind.ExpressionStatement).some(e=>Kt(e)):!1},Jt=e=>{let t=Ut(e);return(0,h.isDefined)(t)?t.getChildrenOfKind(T.SyntaxKind.ExpressionStatement).filter(e=>Wt(e)&&qt(e)):[]},Yt=e=>{let t=Ut(e);if((0,h.isDefined)(t))return t.getChildrenOfKind(T.SyntaxKind.ExpressionStatement).find(e=>Wt(e)&&qt(e))},Xt=e=>{let t=Yt(e);return(0,h.isDefined)(t)},Zt=e=>{let t=Ut(e);if(!(0,h.isDefined)(t))return!0;let n=t.getChildrenOfKind(T.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(T.SyntaxKind.CallExpression)?.getExpressionIfKind(T.SyntaxKind.Identifier);return(0,h.isDefined)(t)?r.has(t.getText()):!1})},Qt=e=>{if(e.isNamedExport?.())return xt.Named;if(e.isDefaultExport?.())return xt.Default;let t=e?.getParent();if((0,h.isDefined)(t)){if(t.isNamedExport?.())return xt.Named;if(t.isDefaultExport?.())return xt.Default}return e.isExportDefaultObject?.()??en(e.getSourceFile(),e.getName?.())?xt.ObjectDefault:xt.NotExported},$t=(e,t)=>(0,h.isDefined)(e)?Qt(e):(0,h.isDefined)(t)?t.isNamedImport?xt.Named:xt.Default:xt.Unknown;function en(e,t){let[n]=e.getExportAssignments()??[];return n?.getDescendantsOfKind(T.SyntaxKind.Identifier).some(e=>(e.getSymbol()?.getEscapedName()??e.getText())===t)}function tn(e,t){let n=Gt(Bt.get(e)),r=n.find(e=>e.getText().includes(t))??n[0],i=Jt(r),a=[],o=(0,h.isEmpty)(i)?[r]:i;for(let e of o){let t=Ut(e);(0,h.isDefined)(t)&&a.push(...t.getChildrenOfKind(T.SyntaxKind.ExpressionStatement).filter(e=>Kt(e)))}return a}let nn=e=>e.getFirstDescendantByKind(T.SyntaxKind.StringLiteral)?.getLiteralValue(),rn=e=>nn(e),an=e=>nn(e),on=(e,t)=>{let n=e.getFullText().slice(0,Math.max(0,t)).split(`
|
|
32001
|
+
`):(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})()})),TU=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(xi()),f=l(Si()),p=l(require(`node:fs/promises`)),m=l(require(`node:async_hooks`)),h=l(ie()),g=l(Ni()),_=l(jc()),v=l(require(`node:crypto`)),y=l(lL()),b=l(gj()),x=l(_R()),S=l((AA(),d(kA))),C=l(require(`node:fs`)),w=l(JR()),T=l(_B()),E=l(require(`node:child_process`)),D=l(require(`node:util`)),O=l(require(`@prisma/internals`)),k=l(pB()),A=l(require(`node:zlib`)),j=l(yV()),M=l(xV()),ee=l(DV()),N=l(MV()),te=l(require(`node:os`)),P=l(require(`node:events`)),F=l(xee()),I=l(hU()),L=l(SU()),ne=l(CU()),re=l(wU()),R=l(AH()),z=l(require(`node:process`));l(require(`node:readline`)),l(require(`node:tty`));let B=l(require(`node:path`)),ae=l(require(`@anthropic-ai/claude-agent-sdk`)),oe={DELETE:`delete`,COMMENT_OUT:`comment out`,KEEP:`keep`,SKIP:`skip`},se={GREEN:`Green`,GREY:`Grey`,RED:`Red`,NA:`NA`},ce={GREEN:`Green`,GREY:`Grey`,RUNTIME_ERROR:`RuntimeError`},le=function(e){return e.IDE=`IDE`,e.CLI=`CLI`,e}({}),ue=function(e){return e.SIBLING_FOLDER=`siblingFolder`,e.ROOT_FOLDER=`rootFolder`,e}({}),de=function(e){return e.JEST=`jest`,e.MOCHA=`mocha`,e.VITEST=`vitest`,e.PYTEST=`pytest`,e}({}),fe=function(e){return e.SPEC=`spec`,e.TEST=`test`,e}({}),pe=function(e){return e.CAMEL_CASE=`camelCase`,e.KEBAB_CASE=`kebabCase`,e}({}),me=function(e){return e.NONE=`none`,e.CATEGORIES=`categories`,e}({}),he=function(e){return e.NEW_CODE_FILE=`newCodeFile`,e.OVERRIDE_CODE_FILE=`overrideCodeFile`,e}({}),ge=function(e){return e.ON=`on`,e.OFF=`off`,e}({}),_e={DEFAULT:0,MIN:0,MAX:100},ve={DEFAULT:5,MIN:1,MAX:50};u.z.object({rootPath:u.z.string().default(process.cwd()),testStructure:u.z.enum(ue).optional(),testFramework:u.z.enum(de).optional(),testSuffix:u.z.enum(fe).optional(),testFileName:u.z.enum(pe).optional(),calculateCoverage:u.z.enum(ge).optional(),coverageThreshold:u.z.number().min(_e.MIN).max(_e.MAX).default(_e.DEFAULT),requestSource:u.z.enum(le).optional(),concurrency:u.z.number().min(ve.MIN).max(ve.MAX).default(ve.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(oe).optional(),redTestBehaviour:u.z.enum(oe).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()});var ye=`@earlyai/ts-agent`,be=`0.72.0`;let xe={VSCODE:`vscode`,GITHUB_ACTION:`github-action`,UNKNOWN:`unknown`},Se=`$early_filename`,Ce=`$early_coverage_dir`,we=`npx --no eslint ${Se}`,Te=`npx --no prettier ${Se} --write`,Ee={rootPath:process.cwd(),isSiblingFolderStructured:!0,gitURL:`https://github.com/your-owner/your-repo`,testFramework:de.JEST,greyTestBehaviour:oe.DELETE,redTestBehaviour:oe.DELETE,keepErrorTests:!1,keepFailedTests:!1,conditionalKeep:!1,continueOnTestErrors:!0,generatedTestStructure:me.CATEGORIES,isRootFolderStructured:!1,clientSource:xe.GITHUB_ACTION,backendURL:`https://api.startearly.ai`,requestSource:le.CLI,userPrompt:``,testLocation:`__tests__`,coverageThreshold:_e.DEFAULT,concurrency:5,testFileFormat:`ts`,outputType:he.NEW_CODE_FILE,shouldRefreshCoverage:!0,kebabCaseFileName:!1,earlyTestFilenameSuffix:`.early.${fe.TEST}`,testSuffix:fe.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:we,prettierCommand:Te,disableLintRules:!1,ignoreAsAnyLintErrors:!0,allowUndefinedLintErrors:!0,perFunctionTimeout:24e4,removeComments:!0,experimentalAgentSdk:!1,agentSdkModel:void 0,agentSdkBudget:void 0,debug:!1,verbose:!1},De=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`.split(`.`).reduce((t,n)=>(0,h.isDefined)(e[n])?{...t,[n]:e[n]}:t,{}),n={...(0,h.isDefined)(e.testStructure)&&{isSiblingFolderStructured:e.testStructure===ue.SIBLING_FOLDER,isRootFolderStructured:e.testStructure===ue.ROOT_FOLDER},...(0,h.isDefined)(e.testFileName)&&{kebabCaseFileName:e.testFileName===pe.KEBAB_CASE},...(0,h.isDefined)(e.calculateCoverage)&&{shouldRefreshCoverage:e.calculateCoverage===ge.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===le.IDE?xe.VSCODE:xe.GITHUB_ACTION}};return{...t,...n}};var Oe=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})),ke=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})),Ae=l(Oe()),je=l(ke()),Me,Ne;let Pe=class{config;constructor(e,t={}){if(!(0,h.isDefined)(e)){this.config=Ee;return}let n=De(e);this.config=(0,h.merge)(Ee,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};Pe=(0,je.default)([(0,_.injectable)(`Singleton`),(0,Ae.default)(`design:paramtypes`,[typeof(Me=typeof Partial<`u`&&Partial)==`function`?Me:Object,typeof(Ne=typeof Partial<`u`&&Partial)==`function`?Ne:Object])],Pe);var Fe=new _.Container({autobind:!0,defaultScope:`Singleton`});let Ie=()=>Fe.get(Pe);var Le=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 Re=function(e){return e.DEFAULT=`default`,e.VERBOSE=`verbose`,e.DEBUG=`debug`,e}({}),ze=function(e){return e.INFO=`info`,e.WARN=`warn`,e}({});function Be(){return(0,v.randomUUID)()}function Ve(){let e=``;for(let t=0;t<8;t++)e+=`abcdefghijklmnopqrstuvwxyz0123456789`.charAt(Math.floor(Math.random()*36));return e}var He=l(Oe()),V=l(ke()),Ue=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 We=class{loggerProvider;config;constructor(e){this.config=e,this.loggerProvider=new x.LoggerProvider({resource:(0,b.resourceFromAttributes)({[S.ATTR_SERVICE_NAME]:ye,[S.ATTR_SERVICE_VERSION]:be})}),this.initializeExporters(),this.setGlobalLoggerProvider()}getLogger(e){return this.loggerProvider.getLogger(e)}initializeExporters(){let e=[];if(this.config.consoleEnabled){let t=new Ue;e.push(new x.SimpleLogRecordProcessor(t))}if(this.config.azureEnabled&&(0,h.isDefined)(this.config.azureConnectionString)){let t=new y.AzureMonitorLogExporter({connectionString:this.config.azureConnectionString});e.push(new x.BatchLogRecordProcessor(t))}this.loggerProvider=new x.LoggerProvider({processors:e})}setGlobalLoggerProvider(){g.logs.setGlobalLoggerProvider(this.loggerProvider)}};We=(0,V.default)([(0,_.injectable)(),(0,He.default)(`design:paramtypes`,[Object])],We),l(Oe()),l(ke());let H=new class{storage;otelService;otelLogger;isConsoleEnabled;printBuffer;default=this.createLogObject(Re.DEFAULT);verbose=this.createLogObject(Re.VERBOSE);constructor(e){this.storage=new m.AsyncLocalStorage,this.otelService=new We(e),this.otelLogger=this.otelService.getLogger(`ts-agent`),this.isConsoleEnabled=e.consoleEnabled,this.printBuffer=new Le(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(Re.DEBUG))&&console.info(r)}logToOpenTelemetry(e,t){let n=this.storage.getStore(),r={service:ye,version:be};(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:Ve(),requestId:Be()};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:Be()}}:void 0}async runWithContext(e,t){return(0,h.isDefined)(e)?this.storage.run(e,t):t()}isLevelEnabled(e){switch(e){case Re.DEFAULT:return!0;case Re.VERBOSE:return Ie().isVerbose()||Ie().isDebug();case Re.DEBUG:return Ie().isDebug()}}createLogObject(e){return{info:(t,...n)=>{this.isLevelEnabled(e)&&this.printOrBuffer(ze.INFO,this.formatPrint(t,...n))},warn:(t,...n)=>{this.isLevelEnabled(e)&&this.printOrBuffer(ze.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 Ge(e){return function(t,n,r){return(0,h.isDefined)(e)&&H.addContext(e),H.withContext(t,n,r)}}var Ke=class e{rootPath;absolutePath;static EARLY_FILENAME_VAR=`$early_filename`;constructor(e){this.rootPath=f.default.normalizeTrim(Ie().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(Ie().getRootPath()),n))}static fromAbsolutePath(t){let n=f.default.normalizeTrim(t);return new e(f.default.relative(f.default.normalizeTrim(Ie().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 qe={WIN32:`win32`,DARWIN:`darwin`,LINUX:`linux`},Je={JAVASCRIPT:`javascript`,TYPESCRIPT:`typescript`,PYTHON:`python`},Ye=e=>{let t=Ie().getRootPath();return f.default.resolve(t,e)},Xe=e=>{let t=Ie().getRootPath(),n=f.default.normalize(e);return f.default.relative(t,n)},Ze=e=>({".js":`javascript`,".mjs":`javascript`,".cjs":`javascript`,".jsx":`javascript`,".ts":`typescript`,".tsx":`typescript`,".py":`python`})[e.toLowerCase()]??`javascript`;function Qe(e){return Ze((0,f.extname)(e))}function $e(e){return Ze((0,f.extname)(e))===`typescript`}function et(e){return Ze((0,f.extname)(e))===Je.PYTHON}function tt(e){let t=Ie().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===qe.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 nt(e){return e.startsWith(`../`)?`../${e}`:e.startsWith(`./`)?`.${e}`:e}function rt(e){let t=f.default.normalize(Ye(e)),n=f.default.normalize((0,w.default)([`package.json`,`project.json`],{cwd:t})??``);return n?Xe((0,f.dirname)(n)).slice(1):``}function it(e,t,n){if(!ot(e))return e;let r=n===``?t:t.replace(n,``),i=n===``?U(r):st(r),a=r.split(`/`).slice(0,-1),o=at(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 at(e,t){return e.split(t).length-1}function ot(e){return e.startsWith(`../`)||e.startsWith(`./`)}function st(e){let t=at(e,`/`);return`../`.repeat(t-1)}function U(e){let t=at(e,`/`);return`../`.repeat(t+1)}function ct(e){return e?.includes(`node_modules/`)}let lt=e=>e.replaceAll(/[.*+?^${}()|[\]\\]/g,String.raw`\$&`);function ut(e,t){let n=f.default.isAbsolute(e)?e:Ye(e);return(0,w.default)(t,{cwd:n})}function dt(e,t){let n=ut(e,t);if(!(0,h.isDefined)(n))return;let r=C.readFileSync(n,`utf8`);return JSON.parse(r)}function ft(e){return dt(e,`package.json`)}function pt(e,t){let{dependencies:n={},devDependencies:r={}}=e;return Object.keys({...r,...n}).includes(t)}let mt=[{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}],ht=[`@typescript-eslint/no-undefined`,`unicorn/no-useless-undefined`,`no-undefined`];async function gt(e){for(let{path:t,isFlat:n}of mt){let r=f.default.join(e,t);if(await Ke.fromAbsolutePath(r).isFileExists())return{path:r,isFlat:n}}return ft(e)?.eslint?{path:ut(e,`package.json`),isFlat:!1}:{path:null,isFlat:!1}}let _t={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`},vt={CODE_EXTRACTOR:`code-extractor`,CODE_REFINEMENT:`code-refinement`,TEST_MANAGEMENT:`test-management`,TEST_VALIDATOR:`test-validator`,CONFIG_FILE:`config-file`,COMMAND_EXECUTION:`command-execution`},yt=[`.jsx`,`.tsx`],bt=[`it`,`test`,`it.each`,`test.each`],xt=function(e){return e.Default=`default`,e.ObjectDefault=`object-default`,e.Named=`named`,e.Unknown=`unknown`,e.NotExported=`not-exported`,e}({}),St=function(e){return e.PRIVATE=`private`,e.PROTECTED=`protected`,e.PUBLIC=`public`,e}({}),Ct=function(e){return e.REACT=`react`,e.ANGULAR=`angular`,e}({}),wt=`unknown`,Tt=(0,D.promisify)(E.default.exec);async function Et(e,{cwd:t=Ie().getRootPath(),timeout:n=1e4}={}){return(await Tt(e,{cwd:t,maxBuffer:500*1024,timeout:n}))?.stdout?.toString()??``}let Dt=e=>{let t=Ye(e);return(0,w.default)(`jest.config.+(js|ts|mjs|cjs|json)`,{cwd:t})},Ot=e=>(0,h.isObject)(e)&&(0,h.isString)(e.rootDir),kt=async e=>{let t;if(H.addContext({subCategory:vt.CONFIG_FILE}),(0,h.isDefined)(e)){let n=Dt(e);n!==null&&(t=(0,f.dirname)(n))}t??=Ie().getRootPath();let n;try{if(n=await Et(`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=>Ot(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`)},At=async()=>{let e=[Ie().getRootPath()],t=f.default.join(`node_modules`,`.prisma`,`client`,`index.d.ts`),n=e.map(e=>f.default.join(e,t)).map(e=>Ke.fromAbsolutePath(e));return(await(0,h.filterAsync)(n,e=>e.isFileExists())).map(e=>e.getAbsoluteFilePath())},jt=async()=>{try{let e=Ie().getRootPath();if(!(0,h.isDefined)(e))return[];let t=await(0,O.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,O.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 Ke.fromAbsolutePath(n).isFileExists()&&r.add(n)}}return[...r]}catch(e){return H.error(`Failed to get prisma typings paths`,e),[]}},Mt=async()=>(await Promise.all([At(),jt()])).flat(),Nt=async(e,t=!1,n)=>{let r=`!**/node_modules/**`;if(t)return new T.Project({useInMemoryFileSystem:!0,compilerOptions:n});let i=$e(e),a=Pt((0,f.dirname)(Ye(e)),Ie().isSiblingFolderStructured());if(!i&&!(0,h.isDefined)(a)){let t=await It(e);if(!(0,h.isDefined)(t)||(0,h.isEmpty)(t))throw Error(`Cannot find source code path in jest config`);let n=new T.Project({compilerOptions:{allowJs:!0,maxNodeModuleJsDepth:0},useInMemoryFileSystem:!1});return n.addSourceFilesAtPaths([...t,r]),n}if(!i&&(0,h.isDefined)(a)){let t=new T.Project({tsConfigFilePath:a,compilerOptions:{allowJs:!0,maxNodeModuleJsDepth:0}}),n=await It(e);return t.addSourceFilesAtPaths([...n,r]),t}let o=new T.Project({tsConfigFilePath:a,compilerOptions:{maxNodeModuleJsDepth:0}}),s=await Mt();for(let e of s)o.addSourceFileAtPath(e);return o},Pt=(e,t)=>{let n;try{n=Ft(e)}catch{t&&(n=Ft((0,f.dirname)(e)))}return n},Ft=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,C.existsSync)(t))return Ft((0,f.dirname)(t));if((0,C.existsSync)(e))return e;if((0,C.existsSync)(r))return r;let i=(0,C.readdirSync)(t);for(let e of i)if(n.test(e))return(0,f.join)(t,e);t=(0,f.dirname)(t)}},It=async e=>{let t=await kt(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[Ye(rt(e))]};var Lt=l(Oe()),Rt=l(ke());let zt=`The ts-morph project is not initialized.`,Bt=new class{storage=new m.AsyncLocalStorage;_project;clear(){this._project=void 0}async init(e,t,n){let r=Ye(e);if((0,h.isDefined)(this._project))return this._project.addSourceFileAtPathIfExists(r);this._project=await Nt(e,t,n);let i=this.storage.getStore();if((0,h.isDefined)(i))return this._project.addSourceFileAtPathIfExists(r)}add(e,t){let n=Ye(e),r=this.storage.getStore()?.getProject();if(!(0,h.isDefined)(r))throw Error(zt);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=Ye(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=Ye(e),n=this.storage.getStore()?.getProject();if(!(0,h.isDefined)(n))throw Error(zt+` 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=Ye(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}},Vt=Bt.withContext,Ht=async e=>{class t{async fn(){return e()}}(0,Rt.default)([Vt,(0,Lt.default)(`design:type`,Function),(0,Lt.default)(`design:paramtypes`,[]),(0,Lt.default)(`design:returntype`,Promise)],t.prototype,`fn`,null),await new t().fn()},Ut=e=>{let t=e?.asKind(T.SyntaxKind.ExpressionStatement)?.getExpression();if(!(0,h.isDefined)(t))return;let n=t.asKind(T.SyntaxKind.CallExpression)?.getArguments()?.at(-1),r=n?.asKind(T.SyntaxKind.ArrowFunction)?.getBody(),i=n?.asKind(T.SyntaxKind.FunctionExpression)?.getBody();return r?.asKind(T.SyntaxKind.Block)??i?.asKind(T.SyntaxKind.Block)},Wt=e=>T.Node.isExpressionStatement(e)&&e.getFirstChildByKind(T.SyntaxKind.CallExpression)?.getFirstChildByKind(T.SyntaxKind.Identifier)?.getText()===`describe`,Gt=e=>e.getStatements().filter(e=>Wt(e)),Kt=e=>{let t=e.getExpression().getFirstChild()?.getText();return!(0,h.isDefined)(t)||(0,h.isEmpty)(t)?!1:bt.some(e=>t.startsWith(e))},qt=e=>{let t=Ut(e);return(0,h.isDefined)(t)?t.getChildrenOfKind(T.SyntaxKind.ExpressionStatement).some(e=>Kt(e)):!1},Jt=e=>{let t=Ut(e);return(0,h.isDefined)(t)?t.getChildrenOfKind(T.SyntaxKind.ExpressionStatement).filter(e=>Wt(e)&&qt(e)):[]},Yt=e=>{let t=Ut(e);if((0,h.isDefined)(t))return t.getChildrenOfKind(T.SyntaxKind.ExpressionStatement).find(e=>Wt(e)&&qt(e))},Xt=e=>{let t=Yt(e);return(0,h.isDefined)(t)},Zt=e=>{let t=Ut(e);if(!(0,h.isDefined)(t))return!0;let n=t.getChildrenOfKind(T.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(T.SyntaxKind.CallExpression)?.getExpressionIfKind(T.SyntaxKind.Identifier);return(0,h.isDefined)(t)?r.has(t.getText()):!1})},Qt=e=>{if(e.isNamedExport?.())return xt.Named;if(e.isDefaultExport?.())return xt.Default;let t=e?.getParent();if((0,h.isDefined)(t)){if(t.isNamedExport?.())return xt.Named;if(t.isDefaultExport?.())return xt.Default}return e.isExportDefaultObject?.()??en(e.getSourceFile(),e.getName?.())?xt.ObjectDefault:xt.NotExported},$t=(e,t)=>(0,h.isDefined)(e)?Qt(e):(0,h.isDefined)(t)?t.isNamedImport?xt.Named:xt.Default:xt.Unknown;function en(e,t){let[n]=e.getExportAssignments()??[];return n?.getDescendantsOfKind(T.SyntaxKind.Identifier).some(e=>(e.getSymbol()?.getEscapedName()??e.getText())===t)}function tn(e,t){let n=Gt(Bt.get(e)),r=n.find(e=>e.getText().includes(t))??n[0],i=Jt(r),a=[],o=(0,h.isEmpty)(i)?[r]:i;for(let e of o){let t=Ut(e);(0,h.isDefined)(t)&&a.push(...t.getChildrenOfKind(T.SyntaxKind.ExpressionStatement).filter(e=>Kt(e)))}return a}let nn=e=>e.getFirstDescendantByKind(T.SyntaxKind.StringLiteral)?.getLiteralValue(),rn=e=>nn(e),an=e=>nn(e),on=(e,t)=>{let n=e.getFullText().slice(0,Math.max(0,t)).split(`
|
|
32002
32002
|
`);return{line:n.length,column:(n.at(-1)?.length??0)+1}},sn=(e,t)=>{let n=t.getStart(),r=t.getEnd(),{line:i,column:a}=on(e,n),{line:o,column:s}=on(e,r);return{startLine:i,startColumn:a,startIndex:n,endLine:o,endColumn:s,endIndex:r}},cn=e=>e.getDescendantsOfKind(T.SyntaxKind.ExpressionStatement).filter(e=>Kt(e)),ln=(e,t,n,r)=>{let i=r?`.tsx`:`.ts`,a=t+Date.now()+(0,v.randomUUID)()+i;return e.createSourceFile(a,n)},un=e=>e.getDescendantsOfKind(T.SyntaxKind.CallExpression).reduce((e,t)=>{let n=t.getExpression(),r=n.getParentIfKind(T.SyntaxKind.VariableDeclaration);return(0,h.isDefined)(r)&&n.getText()===`require`&&e.push(r),e},[]),dn=e=>{let t=e.getFirstChildByKind(T.SyntaxKind.CallExpression);if(!(0,h.isDefined)(t))return;let[n]=t.getArguments();if(!(!(0,h.isDefined)(n)||n.getKind()!==T.SyntaxKind.StringLiteral))return n.getText().slice(1,-1)},W=e=>{let t=[`${Ie().getEarlyTestFilenameSuffix()}.ts`,`.test.ts`,`.spec.ts`,`.test.tsx`,`.spec.tsx`,`.test.js`,`.spec.js`,`.test.jsx`,`.spec.jsx`],n=e.getFilePath(),r=`_`+(0,v.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(`.`)},fn=(e,t=e.getFullText())=>{let n=W(e);return e.getProject().createSourceFile(n,t)},pn=e=>e.getSymbol()?.getDeclarations()?.[0]?.getSourceFile()??e.getAliasSymbol()?.getDeclarations()?.[0]?.getSourceFile(),mn=(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},hn=[T.SyntaxKind.JsxElement,T.SyntaxKind.JsxOpeningElement,T.SyntaxKind.JsxClosingElement,T.SyntaxKind.JsxExpression,T.SyntaxKind.JsxSelfClosingElement,T.SyntaxKind.JsxAttributes,T.SyntaxKind.JsxAttribute,T.SyntaxKind.JsxFragment,T.SyntaxKind.JsxOpeningFragment,T.SyntaxKind.JsxClosingFragment,T.SyntaxKind.JsxNamespacedName,T.SyntaxKind.JsxSpreadAttribute,T.SyntaxKind.JsxText,T.SyntaxKind.JsxTextAllWhiteSpaces],gn=e=>hn.some(t=>(0,h.isDefined)(e.getFirstDescendantByKind(t))),_n=e=>hn.some(t=>(0,h.isDefined)(e.getParentIfKind(t))),vn=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},yn=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(`.`)),bn=`anonymousFunction`;var xn=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(T.SyntaxKind.CallExpression),n=t?.getFirstDescendantByKind(T.SyntaxKind.PropertyAccessExpression),r=t?.getFirstDescendantByKind(T.SyntaxKind.Identifier);return[n?.getText(),r?.getText()].some(e=>(0,h.isDefined)(e)?[...yn.values()].some(t=>e.includes(t)):!1)}).map(e=>{let t=e.getFirstDescendantByKind(T.SyntaxKind.VariableDeclaration)?.getFirstChildByKind(T.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()??bn,n=this.isEntityExported(t)||e.isExported();return{...this.getLocationPivot(e),name:t,type:`function`,node:e,canCreateTests:n}})}getFunctionsExpressions(){return this.sourceFile.getDescendantsOfKind(T.SyntaxKind.FunctionExpression).filter(e=>e.getParentIfKind(T.SyntaxKind.ExportAssignment)?.isExportEquals()??!(this.isCallbackFunction(e)||this.isInnerFunction(e)||this.isJSXFunction(e))).map(e=>{let t=e.getName()??this.getArrowFunctionName(e)??bn,n=this.isEntityExported(t);return{...this.getLocationPivot(e),name:t,type:`function`,node:e,canCreateTests:n}})}getArrowFunctionsExpressions(){return this.sourceFile.getDescendantsOfKind(T.SyntaxKind.ArrowFunction).filter(e=>e.getParentIfKind(T.SyntaxKind.ExportAssignment)?.isExportEquals()??!(this.isCallbackFunction(e)||this.isInnerFunction(e)||this.isJSXFunction(e))).map(e=>{let t=this.getArrowFunctionName(e)??bn,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()===T.SyntaxKind.CallExpression}isJSXFunction(e){return _n(e)}isInnerFunction(e){let t=e.getParent(),n=0;for(;(0,h.isDefined)(t)&&t.getKind()!==T.SyntaxKind.SourceFile&&n<20;){if(t.getKind()===T.SyntaxKind.ArrowFunction)return!0;t=t.getParent(),n++}return!1}getArrowFunctionName(e){let t=e.getParent();if(t?.getKind()===T.SyntaxKind.BinaryExpression&&t?.getFirstChild()?.getKind()===T.SyntaxKind.PropertyAccessExpression)return e.getParent()?.getFirstChildByKind(T.SyntaxKind.PropertyAccessExpression)?.getName();let n=e.getFirstAncestorByKind(T.SyntaxKind.VariableDeclaration);if((0,h.isDefined)(n))return n.getName();let r=e.getFirstAncestorByKind(T.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(T.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(T.SyntaxKind.BinaryExpression).map(e=>e.getRight()).filter(e=>T.Node.isObjectLiteralExpression(e)),t=this.sourceFile.getExportAssignments().map(e=>e.getExpression()).filter(e=>T.Node.isObjectLiteralExpression(e));return[...e,...t].flatMap(e=>e.getProperties()).filter(e=>T.Node.isMethodDeclaration(e)).map(e=>({...this.getLocationPivot(e),type:`object-method`,node:e,name:e.getName(),canCreateTests:!0}))}getLocationPivot(e){return sn(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()===T.SyntaxKind.ThisKeyword&&t[1]?.getKind()===T.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 Sn=`default`;var Cn=class{constructor(e,t){this.sourceFile=e,this.isUsingJSX=t}getImports(){return[...this.getESMImportsNodes(),...this.getCJSImportsNodes()].map(e=>({name:`Import`,location:sn(this.sourceFile,e),node:e,type:`import`,sourceValue:(T.Node.isImportDeclaration(e)?e.getModuleSpecifierValue():e.getFirstDescendantByKind(T.SyntaxKind.StringLiteral)?.getLiteralValue())??``}))}getCJSImportsNodes(){return this.sourceFile.getVariableStatements().filter(e=>(e.getFirstDescendantByKind(T.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(T.SyntaxKind.ExportAssignment).length>0;return e||t||n}getCJSExports(){let e=[],t=``,n=`module.exports`,r=`exports`;for(let i of this.sourceFile.getDescendantsOfKind(T.SyntaxKind.ExpressionStatement)){let a=i.getExpression(),o=a.getText().trim(),s=a.asKind(T.SyntaxKind.BinaryExpression);if(!o.startsWith(n)&&!o.startsWith(r)||!(0,h.isDefined)(s))continue;let c=s.getLeft(),l=c.getText(),u=c.asKind(T.SyntaxKind.PropertyAccessExpression),d=u?.getName()??``,f=c.getKind()===T.SyntaxKind.PropertyAccessExpression,p=s.getRight(),m=f&&u?.getExpression().getText()===n,g=f&&u?.getExpression().getText()===r;if(m&&d===Sn){t=p.getText();continue}if(m||g){e.push(d);continue}if(l!==n)continue;let _=t=>{let n=t.asKind(T.SyntaxKind.ObjectLiteralExpression);if((0,h.isDefined)(n))for(let t of n.getProperties()){if(t.getKind()===T.SyntaxKind.PropertyAssignment||t.getKind()===T.SyntaxKind.ShorthandPropertyAssignment||t.getKind()===T.SyntaxKind.MethodDeclaration){let n=t.getName();e.push(n)}if(t.getKind()===T.SyntaxKind.PropertyAssignment){let e=t.getInitializer();(0,h.isDefined)(e)&&_(e)}}},v=t=>{let n=t.asKind(T.SyntaxKind.FunctionDeclaration)?.getBody()?.asKind(T.SyntaxKind.Block);if((0,h.isDefined)(n))for(let t of n.getStatements()){let n=((t.asKind(T.SyntaxKind.ExpressionStatement)?.getExpression())?.asKind(T.SyntaxKind.BinaryExpression)?.getLeft())?.asKind(T.SyntaxKind.PropertyAccessExpression);n?.getExpression().getKind()===T.SyntaxKind.ThisKeyword&&e.push(n.getName())}},y=t=>{let n=t.asKind(T.SyntaxKind.FunctionDeclaration)?.getName();if((0,h.isDefined)(n))for(let t of this.sourceFile.getStatements()){let r=((t.asKind(T.SyntaxKind.ExpressionStatement)?.getExpression())?.asKind(T.SyntaxKind.BinaryExpression)?.getLeft())?.asKind(T.SyntaxKind.PropertyAccessExpression);r?.getExpression().getText()===`${n}.prototype`&&e.push(r.getName())}};if(p.getKind()===T.SyntaxKind.ObjectLiteralExpression){_(p);continue}if(p.getKind()===T.SyntaxKind.Identifier){let t=p.asKind(T.SyntaxKind.Identifier),n=t?.findReferences().map(e=>e.getDefinition().getNode().getParent()).filter(e=>(0,h.isDefined)(e)).filter(e=>e.getKind()===T.SyntaxKind.VariableDeclaration);if(!(0,h.isDefined)(n))continue;for(let t of n){let n=t.getInitializer()?.asKind(T.SyntaxKind.ObjectLiteralExpression);if((0,h.isDefined)(n)){for(let t of n.getProperties())if(t.getKind()===T.SyntaxKind.PropertyAssignment||t.getKind()===T.SyntaxKind.ShorthandPropertyAssignment){let n=t.getName();e.push(n)}}}let r=t?.findReferences().map(e=>e.getDefinition().getNode().getParent()).filter(e=>e?.getKind()===T.SyntaxKind.FunctionDeclaration);if(!(0,h.isDefined)(r))continue;for(let e of r)v(e),y(e)}if(p.isKind(T.SyntaxKind.NewExpression)){let e=p.asKind(T.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()===T.SyntaxKind.Identifier){e=i.getText();continue}let a=r.getFirstChildByKind(T.SyntaxKind.ObjectLiteralExpression);if((0,h.isDefined)(a)){for(let e of a.getProperties())if(e.getKind()===T.SyntaxKind.PropertyAssignment||e.getKind()===T.SyntaxKind.ShorthandPropertyAssignment||e.getKind()===T.SyntaxKind.MethodDeclaration){let n=e.getName();t.push(n)}}}let r=this.sourceFile.getExportedDeclarations();if(!(n&&r.size===1&&[...r.keys()][0]===Sn))for(let[n,i]of r)if(n===Sn){let t=(i[0]?.getFirstChildByKind(T.SyntaxKind.Identifier))?.getText()?.trim()??bn;(0,h.isDefined)(t)&&(e=t)}else t.push(n);return{defaultExport:e,namedExports:t}}hasRequire(){return this.sourceFile.getDescendantsOfKind(T.SyntaxKind.CallExpression).some(e=>e.getExpression().getText()===`require`)}transformRequiresToImports(){let e=ln(this.sourceFile.getProject(),`transformRequiresToImports`,this.sourceFile.getFullText(),this.isUsingJSX),t;try{let n=e.getVariableStatements();for(let e of n){let t=e.getFirstDescendantByKind(T.SyntaxKind.CallExpression),n=t?.getExpression();if(!(0,h.isDefined)(t)||!(0,h.isDefined)(n)||n.getText()!==`require`)continue;let r=t.getFirstDescendantByKind(T.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()}},wn=class{tests;constructor(e){this.sourceFile=e}getDescribes(){return Gt(this.sourceFile).map(e=>{let t=rn(e);return(0,h.isDefined)(t)?{node:e,name:t,location:sn(this.sourceFile,e),type:`describe`}:null}).filter(e=>(0,h.isDefined)(e))}getTests(){return(0,h.isDefined)(this.tests)||(this.tests=cn(this.sourceFile).map(e=>{let t=sn(this.sourceFile,e),n=an(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 cn(e.node).map(e=>{let t=an(e);return(0,h.isDefined)(t)?{node:e,name:t,location:sn(this.sourceFile,e),type:`test`}:null}).filter(e=>(0,h.isDefined)(e))}},G=class{sourceFile;tests;testables;moduleInfo;constructor(e,t){this.filePath=t;let n=!0;try{let t=new T.Project({useInMemoryFileSystem:!0,skipAddingFilesFromTsConfig:!0,skipFileDependencyResolution:!0,skipLoadingLibFiles:!0}),r=ln(t,`ast`,e,!0);gn(r)?this.sourceFile=r:(t.removeSourceFile(r),this.sourceFile=ln(t,`ast`,e,!1),n=!1)}catch{throw Error(`Cannot parse file content`)}this.moduleInfo=new Cn(this.sourceFile,n),this.testables=new xn(this.sourceFile,this.moduleInfo),this.tests=new wn(this.sourceFile)}isReactFile(){let e=(0,f.extname)(this.filePath??this.sourceFile.getFilePath());return yt.includes(e)||this.isFileContainsImport(`react`)}isFileContainsImport(e){return this.moduleInfo.getImports().some(t=>t.sourceValue.includes(e))}checkIsJSDoc(e,t,n){return t===T.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 Tn=e=>{let{node:t,parent:n,...r}=e;return r};var En=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 Dn=`.early.coverage`;var On=class{getCoverageDirectoryPath(){let e=Ie().getRootPath();return f.default.join(e,Dn,`v8`)}getCoverageDirectoryForCommand(){return this.getCoverageDirectoryPath()}getExecutionCwd(){return Ie().getRootPath()}},kn=class extends On{getCoverageDirectoryForCommand(){let e=Ie().getGitTopLevel(),t=Ie().getRootPath(),n=f.default.relative(e,t);return f.default.join(n,Dn,`v8`)}};function An(){let e=Ie().getCoverageCommand()?.split(/\s+/).includes(`nx`)??!1;return H.info.defaultLog(`Coverage path strategy: `+(e?`nx`:`standard`)),e?new kn:new On}var jn=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 Mn(e){let t=Ie().getRootPath(),n=[];try{let e=new Ke(`.gitignore`);await e.isFileExists()&&(n=(await e.getText()).split(`
|
|
32003
32003
|
`).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,k.default)(e,{cwd:t,absolute:!0,ignore:r})).map(e=>`/${f.default.relative(t,e)}`)}var Nn=class{nextSource=null;setNext(e){return this.nextSource=e,e}async getFromNext(e){return this.nextSource?this.nextSource.getFiles(e):[]}},Pn=class extends Nn{async getFiles(e){return Mn(`**/*.{js,ts,jsx,tsx}`)}};let Fn=/\.[jt]sx?$/;var In=class extends Nn{async getFiles(e){let t=Object.keys(e).filter(e=>Fn.test(e));return t.length>0?t:this.getFromNext(e)}};function Ln(){let e=new In,t=new Pn;return e.setNext(t),e}let Rn=String.raw`.*\.early\.(spec|test)\.[tj]sx?$`;var zn=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=An()}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(Ie().getCoverageCommand()??await this.buildJestCoverageCommand()).replaceAll(Ce,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=Ke.fromAbsolutePath(this.getCoverageReportPath());await e.isFileExists()&&await e.delete()}catch(e){H.error(`Error removing coverage report`,e)}}async getReport(){try{let e=await Ke.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 Tt(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 En(Ie().getGitTopLevel()).add(this.COVERAGE_ROOT_DIRECTORY_NAME)}}calculateCoverage(e){let t=new jn(e,f.default.normalize(Ie().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=Dt(Ie().getRootPath());return(0,h.isDefined)(e)}async buildJestCoverageCommand(){let e=[`node_modules`,`dist`];Ie().getIncludeEarlyTests()||e.push(Rn);let t=e.map(e=>`"${e}"`).join(` `),n=Ie().getRootPath();return await this.hasJestConfig()?`npx jest --coverage --coverageProvider=v8 --coveragePathIgnorePatterns ${t} --coverageReporters=json --coverageDirectory=${Ce} --silent --passWithNoTests --maxWorkers=2`:`npx jest --coverage --coverageProvider=v8 --coveragePathIgnorePatterns ${t} --coverageReporters=json --coverageDirectory=${Ce} --rootDir="${n}" --silent --passWithNoTests --maxWorkers=2`}async getCoverageTree(e){let t=await Ln().getFiles(e),n=new Map;for(let r of t){let t=new G(await new Ke(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=>Tn(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))}},Bn=class extends jn{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 Vn=`npx vitest run --coverage.enabled --coverage.exclude="${Rn}" --coverage.reportsDirectory=${Ce} --coverage.reportOnFailure=true --coverage.reporter=json --maxWorkers=2 --passWithNoTests`;var Hn=class extends zn{async init(){await super.init()}async getCommand(){return(Ie().getCoverageCommand()??Vn).replaceAll(Ce,this.getCoverageDirectoryForCommand())}async getReport(){try{let e=await Ke.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(Ie().getRootPath()).toLowerCase(),n=new Bn(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 Ke.fromAbsolutePath(e).getText()}catch{return null}}extractTestables(e,t,n){let r=new G(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}},Un=function(e){return e.JEST=`jest`,e.VITEST=`vitest`,e}(Un||{}),Wn=class{provider=null;async create(){let e=await this.detectProjectType();return H.info.defaultLog(`Coverage: project type`,e),e===Un.JEST?this.provider=new zn:e===Un.VITEST&&(this.provider=new Hn),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`])?Un.VITEST:await this.checkFileExists([`package.json`,`jest.config.js`,`jest.config.ts`,`tsconfig.json`])?Un.JEST:null}async checkFileExists(e){H.info.defaultLog(`Coverage: checking files`,e);for(let t of e)if(await new Ke(t).isFileExists())return!0;return!1}};let Gn={};var Kn=class{provider=null;coverage=null;async init(){(0,h.isDefined)(this.provider)||(this.provider=await new Wn().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 Gn;try{await this.provider.generateReport()}catch(e){let t=await this.provider.isReportExists();if(!Ie().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)?Gn: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)}},qn=l(Oe()),Jn=l(ke());let Yn=class{coverageService=new Kn;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,Jn.default)([Ge({category:_t.GENERATE_COVERAGE}),(0,qn.default)(`design:type`,Function),(0,qn.default)(`design:paramtypes`,[]),(0,qn.default)(`design:returntype`,Promise)],Yn.prototype,`generateCoverage`,null),(0,Jn.default)([Ge({category:_t.SET_COVERAGE}),(0,qn.default)(`design:type`,Function),(0,qn.default)(`design:paramtypes`,[Object]),(0,qn.default)(`design:returntype`,Promise)],Yn.prototype,`setCoverage`,null),(0,Jn.default)([Ge({category:_t.GET_COVERAGE}),(0,qn.default)(`design:type`,Function),(0,qn.default)(`design:paramtypes`,[]),(0,qn.default)(`design:returntype`,Promise)],Yn.prototype,`getCoverageTree`,null),(0,Jn.default)([Ge({category:_t.GET_COVERAGE}),(0,qn.default)(`design:type`,Function),(0,qn.default)(`design:paramtypes`,[Array]),(0,qn.default)(`design:returntype`,Promise)],Yn.prototype,`getCoverageForFiles`,null),Yn=(0,Jn.default)([(0,_.injectable)()],Yn);let Xn=new class{safeTrackEvent(e,t){}},Zn={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`},Qn={[Zn.EMPTY_TEST]:`Oops! No tests were generated for "{{methodName}}". Code:{{code}} - We're on it!`,[Zn.DESCRIBE_NOT_FOUND]:`Oops! Test suite not found for "{{methodName}}". Code:{{code}} - We're on it!`,[Zn.TESTED_CODE_DATA_SOURCE_ERROR]:`Cannot get testable data for "{{methodName}}". Code:{{code}} - We're on it!`,[Zn.GENERATING_TESTS_REQUEST_ERROR]:`Generating tests for method "{{methodName}}" - failed: "{{errorMessage}}". Code:{{code}} - We're on it!`,[Zn.PREPARATIONS_FOR_GENERATING_TEST_DTO_ERROR]:`Generating tests for method "{{methodName}}" - failed: "{{errorMessage}}". Code:{{code}} - We're on it!`,[Zn.GET_VERSION_REQUEST_ERROR]:`Failed to make request. Code:{{code}} - We're on it!`,[Zn.GENERATING_HELPER_REQUEST_ERROR]:`Generating helpers for method "{{methodName}}" - failed: "{{errorMessage}}". Code:{{code}} - We're on it!`,[Zn.ENHANCE_TESTS_REQUEST_ERROR]:`Enhance tests for method "{{methodName}}" - failed: "{{errorMessage}}". Code:{{code}} - We're on it!`,[Zn.EMPTY_FIXED_TESTS]:`Oops! We got an empty API response for "{{methodName}}" test fixes. Code:{{code}} - We're on it!`,[Zn.TESTABLE_NOT_FOUND]:`Oops! Testable code not found for "{{methodName}}". Code:{{code}} - We're on it!`,[Zn.TESTED_CODE_FILE_PATH_NOT_FOUND]:`Oops! Testable code file path not found for "{{methodName}}". Code:{{code}}`,[Zn.PREEN_TESTS_ERROR]:`Encountered a problem while processing "{{methodName}}". Code:{{code}} - We're on it!`,[Zn.ORGANIZE_IMPORTS_ERROR]:`There was an issue with the processing "{{methodName}}". Code:{{code}} - We're on it!`,[Zn.NOT_ENOUGH_BALANCE_ERROR]:`Usage test generation limit reached.`,[Zn.UNSUPPORTED_MODEL_ERROR]:`We do not support this model at the moment.`,[Zn.TOO_MANY_USERS_ERROR]:`Users limit reached. Please contact support.`,[Zn.PAYLOAD_TOO_LARGE_ERROR]:`We could not generate tests due to code size.`,[Zn.TEST_SUMMARY_DB_REQUEST_ERROR]:`We could not save test summary to database.`,[Zn.TEST_SUMMARY_INVALID_CREATED_BY_ERROR]:`Invalid created by field.`,[Zn.TEST_SUMMARY_INVALID_GIT_REMOTE_ERROR]:`Invalid git remote.`,[Zn.TEST_SUMMARY_INVALID_GIT_BRANCH_ERROR]:`Invalid git branch.`,[Zn.GITHUB_ACTION_TEST_SUMMARY_DB_REQUEST_ERROR]:`We could not save test summary to database.`,[Zn.GITHUB_ACTION_TEST_SUMMARY_READ_CONF_FILE]:`Failed to read github action config file.`,[Zn.GITHUB_ACTION_TEST_SUMMARY_INVALID_GIT_REMOTE_ERROR]:`Invalid git remote.`,[Zn.GITHUB_ACTION_TEST_SUMMARY_INVALID_GIT_BRANCH_ERROR]:`Invalid git branch.`,[Zn.GITHUB_ACTION_TEST_SUMMARY_READ_CONF_FILE_EMPTY_OPTIONS]:`Failed to parse options from github action conf file.`,[Zn.GITHUB_ACTION_TEST_SUMMARY_NO_COVERAGE_FOUND]:`No coverage found. Please run coverage first.`,[Zn.WS_DYNAMIC_PROMPT_GENERAL_ERROR]:`Failed initializing dynamic prompt.`,[Zn.WS_DYNAMIC_PROMPT_AUTH_ERROR]:`Failed authorizing dynamic prompt.`,[Zn.PREPARATIONS_FOR_DYNAMIC_PROMPT_ERROR]:`Failed preparing init dynamic prompt.`,[Zn.WS_DYNAMIC_PROMPT_VALIDATION_FAILED_ERROR]:`Failed validating dynamic prompt dto.`,[Zn.WS_DYNAMIC_PROMPT_TIMEOUT_ERROR]:`Dynamic prompt operation timed out.`};var $n=class extends Error{constructor(e,t){let n=er(e,t);super(n),this.code=e}};let er=(e,t)=>{let n=Qn[e];for(let[r,i]of Object.entries({...t,code:e}))n=n.replace(`{{${r}}}`,i);return n},tr=`x-request-id`;var nr=class extends Error{constructor(){super(`Not authorized`)}};new TextEncoder;let rr=new TextDecoder;function ir(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 ar(e){if(Uint8Array.fromBase64)return Uint8Array.fromBase64(typeof e==`string`?e:rr.decode(e),{alphabet:`base64url`});let t=e;t instanceof Uint8Array&&(t=rr.decode(t)),t=t.replace(/-/g,`+`).replace(/_/g,`/`);try{return ir(t)}catch{throw TypeError(`The input to be decoded is not correctly encoded.`)}}var or=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)}},sr=class extends or{static code=`ERR_JWT_INVALID`;code=`ERR_JWT_INVALID`};let cr=e=>typeof e==`object`&&!!e;function lr(e){if(!cr(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 ur(e){if(typeof e!=`string`)throw new sr(`JWTs must use Compact JWS serialization, JWT must be a string`);let{1:t,length:n}=e.split(`.`);if(n===5)throw new sr(`Only JWTs using Compact JWS serialization can be decoded`);if(n!==3)throw new sr(`Invalid JWT`);if(!t)throw new sr(`JWTs must contain a payload`);let r;try{r=ar(t)}catch{throw new sr(`Failed to base64url decode the payload`)}let i;try{i=JSON.parse(rr.decode(r))}catch{throw new sr(`Failed to parse the decoded payload as JSON`)}if(!lr(i))throw new sr(`Invalid JWT Claims Set`);return i}let dr=e=>{let t=ur(e).exp;return(0,h.isDefined)(t)?t*1e3:null},fr=e=>{if(!(0,h.isDefined)(e))return!0;let t=dr(e);return(0,h.isDefined)(t)?t<Date.now():!0};var pr=l(ke());let mr=class{jwtToken=null;refreshTokenCallback=null;observer=new h.Observer;refreshTokenMutex=new ee.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 nr;return e}onJWTTokenSave(e){this.observer.addListener(e)}isTokenValid(){return!fr(this.jwtToken)}setRefreshTokenCallback(e){this.refreshTokenCallback=e}};mr=(0,pr.default)([(0,_.injectable)(`Singleton`)],mr);var hr=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})),gr=l(Oe()),_r=l(hr()),vr=l(ke()),yr,br;let xr=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":be,"Content-Type":`application/json`,"Content-Encoding":`gzip`},transformRequest:[e=>{if((0,h.isDefined)(e)){let t=A.default.createGzip();return t.write(JSON.stringify(e)),t.end(),t}else return e}]}),(0,M.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 $n(Zn.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()})}};xr=(0,vr.default)([(0,_.injectable)(),(0,_r.default)(0,(0,_.inject)(mr)),(0,_r.default)(1,(0,_.inject)(Pe)),(0,gr.default)(`design:paramtypes`,[typeof(yr=mr!==void 0&&mr)==`function`?yr:Object,typeof(br=Pe!==void 0&&Pe)==`function`?br:Object])],xr);let Sr={SUPER_ADMIN:1,ADMIN:2,USER:3},Cr=[Sr.ADMIN,Sr.SUPER_ADMIN];var wr=l(Oe()),Tr=l(hr()),Er=l(ke()),Dr;let Or=class{mutex=new ee.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)?Cr.includes(e?.role):!1}async isInOrganization(){let e=await this.getUser();return(0,h.isDefined)(e?.organization)}};Or=(0,Er.default)([(0,_.injectable)(),(0,Tr.default)(0,(0,_.inject)(xr)),(0,wr.default)(`design:paramtypes`,[typeof(Dr=xr!==void 0&&xr)==`function`?Dr:Object])],Or);let kr=e=>(0,v.createHash)(`md5`).update(String(e)).digest(`hex`),Ar=e=>({...jr(e),testFrameworkReceived:(0,h.isDefined)(e.testFrameworkReceived)?kr(e.testFrameworkReceived):void 0,testFrameworkExpected:(0,h.isDefined)(e.testFrameworkExpected)?kr(e.testFrameworkExpected):void 0}),jr=e=>({errorCode:e.errorCode,shortDescription:kr(e.shortDescription),fullDescription:kr(e.fullDescription)}),Mr=e=>({name:kr(e.name),code:kr(e.code),status:e.status,errors:e.errors?.map(e=>Ar(e)),lintErrors:e.lintErrors?.map(e=>Nr(e))??null}),Nr=e=>({errorCode:e.errorCode,fullDescription:kr(e.fullDescription),shortDescription:kr(e.shortDescription),severity:e.severity,exactCode:kr(e.exactCode)}),Pr=({describe:e,stdout:t})=>({describe:{path:e.path,code:kr(e.code),fullCode:kr(e.fullCode),status:e.status,errors:e.errors?.map(e=>jr(e)),tests:e.tests.map(e=>Mr(e)),lintErrors:e.lintErrors?.map(e=>Nr(e))??null},stdout:t});var Fr=l(Oe()),Ir=l(hr()),Lr=l(ke()),Rr,zr,Br;let Vr=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)?Pr(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:{[tr]: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=ft(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)}}};Vr=(0,Lr.default)([(0,_.injectable)(),(0,Ir.default)(0,(0,_.inject)(xr)),(0,Ir.default)(1,(0,_.inject)(Or)),(0,Ir.default)(2,(0,_.inject)(Pe)),(0,Fr.default)(`design:paramtypes`,[typeof(Rr=xr!==void 0&&xr)==`function`?Rr:Object,typeof(zr=Or!==void 0&&Or)==`function`?zr:Object,typeof(Br=Pe!==void 0&&Pe)==`function`?Br:Object])],Vr);var Hr=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 N.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 Ur=`npx jest ${Se} --coverage=false --verbose=false --watchAll=false --silent --json --forceExit --testPathIgnorePatterns=// --maxWorkers=1`;var Wr=class{fulfill(e){if(Ie().getTestFramework()!==de.JEST)return!1;let t=e,n=null,r=0;for(;r<25;){r++;let e=ut(t,`package.json`);if(!(0,h.isDefined)(e)||e===n)return!1;let i=ft(t);if((0,h.isDefined)(i)&&pt(i,`jest`))return!0;n=e,t=f.default.dirname(f.default.dirname(e))}return!1}getTestCommand(){return{command:Ie().getTestCommand()??Ur,framework:de.JEST}}};let Gr=`npx vitest run ${Se} --reporter=junit --silent --pool=threads --maxWorkers=1 --coverage.enabled=false`,Kr=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(Ie().getTestFramework()!==de.VITEST)return!1;let t=e,n=null,r=0;for(;r<25;){r++;let e=ut(t,`package.json`);if(!(0,h.isDefined)(e)||e===n)return!1;let i=ft(t);if((0,h.isDefined)(i)&&pt(i,`vitest`))return!0;n=e,t=f.default.dirname(f.default.dirname(e))}return!1}getTestCommand(){return{command:Ie().getTestCommand()??Gr,framework:de.VITEST}}},new Wr]);var qr=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 Jr=`validate-tests`,Yr=e=>e instanceof Error&&`code`in e&&typeof e.code==`number`;var Xr=class e{constructor(e){this.relativePath=e}async runCommandOnFile(e,t=qr.success,n=!1){let r=n?lt(f.default.normalize(this.relativePath)):f.default.normalize(this.relativePath),i=e.replaceAll(Se,`"${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 Tt(i,{cwd:Ie().getRootPath(),timeout:3e5}),r=t||n;return H.debug.endLog(`Command been executed on test-file ${this.relativePath} ${e}: ${r}`),r}catch(n){if(!(Yr(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(te.default.tmpdir(),`early`),n=`${e}-${(0,v.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(Ie().getRootPath(),f.default.dirname(n??``));if(!(0,h.isDefined)(i))throw Error(`Workspace root path is not defined`);let a=`.${e}-${(0,v.randomUUID)()}-${r?f.default.basename(n):`.ts`}`;return f.default.join(i,a)}async runCommandWithContent(t,n,r,i=!1){H.addContext({subCategory:vt.COMMAND_EXECUTION});let a={filePrefix:`generated-content`,useTemporaryOSFolder:!(0,h.isDefined)(r?.predefinedPath),validExitCodes:qr.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:vt.COMMAND_EXECUTION});let e;try{e=Kr.getTestCommand(this.relativePath)}catch(e){return e instanceof Error?e.message:`Framework is not supported yet`}return await this.runCommandOnFile(e.command,qr.suppress_1,!0)}async runTestCommandOnTempFile(e){H.addContext({subCategory:vt.COMMAND_EXECUTION});let t;try{t=Kr.getTestCommand(this.relativePath)}catch(e){return e instanceof Error?e.message:`Framework is not supported yet`}return await this.runCommandWithContent(e,t.command,{validExitCodes:qr.suppress_1,filePrefix:Jr,predefinedPath:this.relativePath},!0)}async runFormatCommand(){H.addContext({subCategory:vt.COMMAND_EXECUTION});let e=Ie().getPrettierCommand();H.debug.startLog(`format command: ${e}`);let t=await this.runCommandOnFile(e,qr.all);return H.debug.endLog(`format command: ${e}`),t}async runLintCommand(e=[]){H.addContext({subCategory:vt.COMMAND_EXECUTION});let t=Ie().getLintCommand(),n=e.length>0?t+` `+e.join(` `):t;H.debug.startLog(`lint command: ${n}`);let r=await this.runCommandOnFile(n,qr.all);return H.debug.endLog(`lint command: ${n}`),r}};let Zr=e=>{let t=e.name??``,n=e.type;return{methodType:n,methodName:t,parentName:n===`method`?e.parentName:void 0}};async function Qr(e,{methodType:t,methodName:n,parentName:r}){let i=new G(await new Ke(e).getText()).testables.findTestable(t,n,r);if(!(0,h.isDefined)(i))throw new $n(Zn.TESTABLE_NOT_FOUND,{methodName:n});return i}function $r(e,t){return(0,h.isDefined)(t)&&!(0,h.isEmpty)(t)?`${t}.${e}`:e}function ei(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 ti=l(ke());let ni=class{contentCache=new Map;filePathIndex=new Map;computeContentHash(e){return kr(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`)}};ni=(0,ti.default)([(0,_.injectable)()],ni);let ri=function(e){return e[e.ERROR=2]=`ERROR`,e[e.WARN=1]=`WARN`,e[e.OFF=0]=`OFF`,e}({});var ii=l(Oe()),ai=l(hr()),oi=l(ke()),si,ci;let li=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()?ht:[]].filter(h.isDefined);this.globalConfigService.shouldDisableLintRules()?await this.disableAllLintRules(e):(0,h.isEmpty)(t)||await this.disableLintRules(e,t),await Bt.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=Ke.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=ei(await new Xr(e).runLintCommand(a));if(!(0,h.isDefined)(o))return null;if(t){await Bt.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===ri.ERROR);return[...new Set(n.map(e=>e.ruleId).filter(h.isDefined))]}async addDisableComment(e,t){let n=Ke.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(`
|
|
32004
32004
|
`);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=Ke.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===ri.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}`)}};li=(0,oi.default)([(0,_.injectable)(),(0,ai.default)(0,(0,_.inject)(Pe)),(0,ai.default)(1,(0,_.inject)(ni)),(0,ii.default)(`design:paramtypes`,[typeof(si=Pe!==void 0&&Pe)==`function`?si:Object,typeof(ci=ni!==void 0&&ni)==`function`?ci:Object])],li);let ui="${methodName}";`${ui}`,`${ui}`;function di(e,t,n){let r=e.split(`
|
|
@@ -32065,21 +32065,21 @@ ${Ld}${t.trimStart()}`),n=3+(0,D.stripVTControlCharacters)(t.trimStart()).length
|
|
|
32065
32065
|
`)}let kf=/Full output saved to:\s*(\S+\.(txt|json))/;function Af(e){if(!e.includes(`<persisted-output>`))return e;let t=kf.exec(e);if(!(0,h.isDefined)(t))return e;let n=t[1].trim();try{if((0,C.existsSync)(n))return(0,C.readFileSync)(n,`utf8`)}catch{}return e}let jf=[/\beslint\b/,/\bnpm\s+run\s+lint\b/,/\bnpx\s+eslint\b/];function Mf(e){return md.some(t=>t.test(e))}function Nf(e){return jf.some(t=>t.test(e))}function Pf(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 Ff(e){return e.split(`
|
|
32066
32066
|
`).length}function If(e){return e.split(`
|
|
32067
32067
|
`).filter(e=>e.trim()!==``).length}function Lf(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(`
|
|
32068
|
-
`):JSON.stringify(e)}return JSON.stringify(e??``)}var Rf=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=Yd(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`;zd.debug(`Session `+r+` initialized | model: `+n)}handleAssistantMessage(e){let t=Jd(e);if((0,h.isDefined)(t))for(let e of t)e.type===`text`&&typeof e.text==`string`&&e.text.trim()!==``?zd.thinking(e.text.trim()):e.type===`tool_use`&&this.handleToolUse(e)}handleToolUse(e){let t=Pf(e),n=e.name??`Unknown`;if((0,h.isDefined)(e.id)&&this.toolUseMap.set(e.id,n),n===`Bash`&&Mf(t)){this.iterationCount+=1,this.iterationCount>1&&zd.iterationSeparator(),zd.testRun(this.iterationCount,t);return}n===`Bash`&&Nf(t)&&(0,h.isDefined)(e.id)&&this.lintToolUseIds.add(e.id),zd.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!==``&&Bd.editDiff(n,r,i)}handleUserMessage(e){let t=Jd(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:Of(e),r=Af(n),i=e.tool_use_id??``;if(t===fd){this.processCheckAllResult(r);return}this.lintToolUseIds.has(i)&&(this.lintToolUseIds.delete(i),this.lastLintErrorCount=lf(r));let a=cf(r);if((0,h.isDefined)(a)){let e=sf(r);(0,h.isDefined)(e)&&(this.lastTestRunResult=e),this.isVerbose&&Bd.rawOutput(n),r.includes(`failed`)?zd.testFail(a):zd.testPass(a);return}this.logToolSpecificResult(e,t,n),this.isVerbose&&t===`Bash`&&Bd.rawOutput(n)}processCheckAllResult(e){try{let t=JSON.parse(e),n=t.gates;if(!Array.isArray(n)){zd.toolResult(fd,`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=sf(r.output);(0,h.isDefined)(e)&&(this.lastTestRunResult=e);let t=cf(r.output);(0,h.isDefined)(t)&&(r.output.includes(`failed`)?zd.testFail(t):zd.testPass(t))}(0,h.isDefined)(i?.output)&&(this.lastLintErrorCount=lf(i.output)),zd.toolResult(fd,t.passed===!0?`all gates passed`:`some gates failed`)}catch{zd.toolResult(fd,`completed`)}}logToolSpecificResult(e,t,n){if(e.is_error===!0){zd.warn((t??`Tool`)+` returned an error`),zd.warn(`Error content: `+n.slice(0,500));return}switch(t){case`Read`:{let e=Ff(n);zd.toolResult(`Read`,String(e)+` lines`),this.isVerbose&&Bd.filePreview(e,n);break}case`Edit`:zd.toolResult(`Edit`,`applied successfully`);break;case`Write`:zd.toolResult(`Write`,`file written`);break;case`Glob`:zd.toolResult(`Glob`,String(If(n))+` files matched`),this.isVerbose&&Bd.searchResults(`Glob`,n);break;case`Grep`:zd.toolResult(`Grep`,String(If(n))+` matches`),this.isVerbose&&Bd.searchResults(`Grep`,n);break;default:(0,h.isDefined)(t)&&t.startsWith(`mcp__`)&&(zd.toolResult(t,`completed`),this.isVerbose&&Bd.rawOutput(Lf(e.content)));break}}}
|
|
32068
|
+
`):JSON.stringify(e)}return JSON.stringify(e??``)}var Rf=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=Yd(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`;zd.debug(`Session `+r+` initialized | model: `+n)}handleAssistantMessage(e){let t=Jd(e);if((0,h.isDefined)(t))for(let e of t)e.type===`text`&&typeof e.text==`string`&&e.text.trim()!==``?zd.thinking(e.text.trim()):e.type===`tool_use`&&this.handleToolUse(e)}handleToolUse(e){let t=Pf(e),n=e.name??`Unknown`;if((0,h.isDefined)(e.id)&&this.toolUseMap.set(e.id,n),n===`Bash`&&Mf(t)){this.iterationCount+=1,this.iterationCount>1&&zd.iterationSeparator(),zd.testRun(this.iterationCount,t);return}n===`Bash`&&Nf(t)&&(0,h.isDefined)(e.id)&&this.lintToolUseIds.add(e.id),zd.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!==``&&Bd.editDiff(n,r,i)}handleUserMessage(e){let t=Jd(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:Of(e),r=Af(n),i=e.tool_use_id??``;if(t===fd){this.processCheckAllResult(r);return}this.lintToolUseIds.has(i)&&(this.lintToolUseIds.delete(i),this.lastLintErrorCount=lf(r));let a=cf(r);if((0,h.isDefined)(a)){let e=sf(r);(0,h.isDefined)(e)&&(this.lastTestRunResult=e),this.isVerbose&&Bd.rawOutput(n),r.includes(`failed`)?zd.testFail(a):zd.testPass(a);return}this.logToolSpecificResult(e,t,n),this.isVerbose&&t===`Bash`&&Bd.rawOutput(n)}processCheckAllResult(e){try{let t=JSON.parse(e),n=t.gates;if(!Array.isArray(n)){zd.toolResult(fd,`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=sf(r.output);(0,h.isDefined)(e)&&(this.lastTestRunResult=e);let t=cf(r.output);(0,h.isDefined)(t)&&(r.output.includes(`failed`)?zd.testFail(t):zd.testPass(t))}(0,h.isDefined)(i?.output)&&(this.lastLintErrorCount=lf(i.output)),zd.toolResult(fd,t.passed===!0?`all gates passed`:`some gates failed`)}catch{zd.toolResult(fd,`completed`)}}logToolSpecificResult(e,t,n){if(e.is_error===!0){zd.warn((t??`Tool`)+` returned an error`),zd.warn(`Error content: `+n.slice(0,500));return}switch(t){case`Read`:{let e=Ff(n);zd.toolResult(`Read`,String(e)+` lines`),this.isVerbose&&Bd.filePreview(e,n);break}case`Edit`:zd.toolResult(`Edit`,`applied successfully`);break;case`Write`:zd.toolResult(`Write`,`file written`);break;case`Glob`:zd.toolResult(`Glob`,String(If(n))+` files matched`),this.isVerbose&&Bd.searchResults(`Glob`,n);break;case`Grep`:zd.toolResult(`Grep`,String(If(n))+` matches`),this.isVerbose&&Bd.searchResults(`Grep`,n);break;default:(0,h.isDefined)(t)&&t.startsWith(`mcp__`)&&(zd.toolResult(t,`completed`),this.isVerbose&&Bd.rawOutput(Lf(e.content)));break}}};let zf=function(e){return e.UNRESOLVED=`unresolved`,e.RESOLVED=`resolved`,e.VERIFIED=`verified`,e}({}),Bf=function(e){return e.PASSED=`passed`,e.FAILED=`failed`,e.SKIPPED=`skipped`,e}({});var Vf=class{static TRACED_TOOLS=new Set([`Bash`,fd]);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){this.toolsOutputBuffer[e]={tool:e,input:t,content:[{type:`text`,text:JSON.stringify(n,null,2)}]}}addPreVerification(e,t,n){let r=[`testCommand`,`buildCommand`,`lintCommand`,`prettierCommand`].map(e=>{let n=t[e];return{gate:e,passed:n.status===Bf.PASSED,skipped:n.status===Bf.SKIPPED,...n.status!==Bf.SKIPPED&&{command:n.command},...n.status===Bf.FAILED&&{output:n.output}}});this.logSyntheticTool(`pre-verification`,e,{passed:t.passed,gates:r}),this.logSyntheticTool(`decision`,t,n)}readTestFileContent(){try{return(0,C.readFileSync)(this.testFilePath,`utf8`)}catch{return}}extractToolsOutput(e){let t=Jd(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;try{if(r.tool===`Bash`)i=sf(String(t.content));else if(r.tool===fd){let e=this.extractCheckAllTestOutput(t.content);i=(0,h.isDefined)(e)?sf(e):void 0}}catch{}n[e]={...r,content:t.content,is_error:t.is_error,...(0,h.isDefined)(i)&&{testResult:i}},this.toolUseInfoMap.delete(e)}extractCheckAllTestOutput(e){let t=Array.isArray(e)?e.find(e=>typeof e==`object`&&!!e&&typeof e.text==`string`)?.text??``:String(e);return JSON.parse(t).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}),(n===`Edit`||n===`Write`)&&r?.file_path===this.testFilePath}},Hf=class extends Error{name=`SdkRunnerError`;constructor(e,t,n){super(`SDK runner failed: ${e}`),this.subtype=e,this.errors=t,this.costUsd=n}};let Uf=`test("placeholder", () => {
|
|
32069
32069
|
expect(true).toBe(true);
|
|
32070
32070
|
});
|
|
32071
|
-
`;function
|
|
32071
|
+
`;function Wf(e){switch(e){case`jest`:case`vitest`:return Uf;case`mocha`:return`const assert = require("assert");
|
|
32072
32072
|
|
|
32073
32073
|
it("placeholder", () => {
|
|
32074
32074
|
assert.ok(true);
|
|
32075
32075
|
});
|
|
32076
|
-
`;default:return Vf}}let Uf=function(e){return e.UNRESOLVED=`unresolved`,e.RESOLVED=`resolved`,e.VERIFIED=`verified`,e}({}),Wf=function(e){return e.PASSED=`passed`,e.FAILED=`failed`,e.SKIPPED=`skipped`,e}({});function Gf(e){return(0,h.isDefined)(e)?{status:Uf.RESOLVED,command:e}:{status:Uf.UNRESOLVED}}function Kf(e){return{testCommand:Gf(e.testCommand),buildCommand:Gf(e.typecheckCommand),lintCommand:Gf(e.lintCommand),prettierCommand:Gf(e.prettierCommand),packageManager:e.packageManager}}var qf=l(ke());let Jf=(0,D.promisify)(E.exec),Yf=[/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 Xf(e){return Yf.some(t=>t.test(e))}let Zf=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!==Wf.FAILED&&i.status!==Wf.FAILED&&a.status!==Wf.FAILED&&o.status!==Wf.FAILED}}async runGate(e,t){if(e.status===Uf.UNRESOLVED)return{status:Wf.SKIPPED,reason:`unresolved`};try{return await Jf(e.command,{cwd:t,encoding:`utf8`,timeout:6e4}),{status:Wf.PASSED}}catch(t){let n=t,r=((n.stdout??``)+(n.stderr??``)).trim();return H.default.warn(`[test-verification] Gate failed: ${e.command}\n${r}`),{status:Wf.FAILED,output:r}}}};Zf=(0,qf.default)([(0,_.injectable)()],Zf);function Qf(e,t){let n=(e,t)=>e.status===Uf.UNRESOLVED?e:t.status===Wf.PASSED?{status:Uf.VERIFIED,command:e.command}:{status:Uf.UNRESOLVED},r=(e,t)=>e.status===Uf.UNRESOLVED?e:t.status===Wf.PASSED||t.status===Wf.FAILED&&!Xf(t.output)?{status:Uf.VERIFIED,command:e.command}:{status:Uf.UNRESOLVED};return{testCommand:n(e.testCommand,t.testCommand),buildCommand:r(e.buildCommand,t.buildCommand),lintCommand:r(e.lintCommand,t.lintCommand),prettierCommand:r(e.prettierCommand,t.prettierCommand),packageManager:e.packageManager}}let $f=[`jest.config.ts`,`jest.config.js`,`jest.config.mjs`,`jest.config.cjs`,`vitest.config.ts`,`vitest.config.js`,`vitest.config.mjs`],ep=[`tsconfig.json`],tp=[`.eslintrc`,`.eslintrc.js`,`.eslintrc.cjs`,`.eslintrc.json`,`.eslintrc.yml`,`.eslintrc.yaml`,`eslint.config.js`,`eslint.config.mjs`,`eslint.config.cjs`,`eslint.config.ts`],np=[`.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`],rp=new Set([`build`,`compile`,`dist`,`prepublish`,`prepublishOnly`,`prepare`]),ip=[`test:unit`,`test:ci`,`test:run`],ap=[`check:ts`,`typecheck`,`type-check`,`tsc`],op=[`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,C.existsSync)(f.default.join(n,`.git`)));)n=f.default.dirname(n);return t}function lp(e){let t=[];for(let n of cp(e)){let e=f.default.join(n,`package.json`);if((0,C.existsSync)(e))try{let r=JSON.parse((0,C.readFileSync)(e,`utf8`));t.push({dir:n,pkg:r})}catch{}}return t}function up(e,t){for(let n of e)for(let e of t)if((0,C.existsSync)(f.default.join(n,e)))return!0;return!1}function dp(e){for(let t of e)for(let e of $f)if((0,C.existsSync)(f.default.join(t,e)))return e.startsWith(`vitest`)?`vitest`:`jest`;return null}function fp(e,t){let n=dp(t);if((0,h.isDefined)(n))return n;for(let{pkg:t}of e){let e=wp(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 pp(t,`vitest`)?`vitest`:pp(t,`jest`)?`jest`:null}function pp(e,t){for(let n of e)if((0,C.existsSync)(f.default.join(n,`node_modules`,`.bin`,t)))return!0;return!1}function mp(e){for(let t of cp(e)){if((0,C.existsSync)(f.default.join(t,`pnpm-lock.yaml`))||(0,C.existsSync)(f.default.join(t,`pnpm-workspace.yaml`)))return`pnpm`;if((0,C.existsSync)(f.default.join(t,`yarn.lock`)))return`yarn`;if((0,C.existsSync)(f.default.join(t,`bun.lockb`))||(0,C.existsSync)(f.default.join(t,`bun.lock`)))return`bun`}return`npm`}function hp(e,t){return e===`yarn`?`yarn ${t}`:`${e} run ${t}`}function gp(e,t){return e.startsWith(`npx `)||e.startsWith(`yarn `)?`${e} ${t}`:`${e} -- ${t}`}let _p=/(?:^echo\b)|(?:no test specified)|(?:placeholder)/i;function vp(e,t){let n=e.scripts??{},r=wp(e),i=n.test;if((0,h.isDefined)(i)&&!_p.test(i))return hp(t,`test`);for(let e of ip)if((0,h.isDefined)(n[e]))return hp(t,e);for(let[e,r]of Object.entries(n))if(/\bjest\b/.test(r)||/\bvitest\b/.test(r))return hp(t,e);return(0,h.isDefined)(r.jest)?`npx jest`:(0,h.isDefined)(r.vitest)?`npx vitest`:null}function yp(e,t,n){for(let{pkg:t}of e){let e=vp(t,n);if((0,h.isDefined)(e))return e}let r=dp(t);return(0,h.isDefined)(r)?(H.info.defaultLog(`[project-setup] test: found config file for ${r}`),`npx ${r}`):pp(t,`jest`)?(H.info.defaultLog(`[project-setup] test: found jest in node_modules`),`npx jest`):pp(t,`vitest`)?(H.info.defaultLog(`[project-setup] test: found vitest in node_modules`),`npx vitest`):null}function bp(e,t){let n=e.scripts??{},r=wp(e);for(let e of ap)if((0,h.isDefined)(n[e]))return hp(t,e);for(let[e,r]of Object.entries(n))if(/\btsc\b/.test(r)&&!rp.has(e))return hp(t,e);return(0,h.isDefined)(r.typescript)?`npx tsc --noEmit`:null}function xp(e,t,n){for(let{pkg:t}of e){let e=bp(t,n);if((0,h.isDefined)(e))return e}return up(t,ep)?(H.info.defaultLog(`[project-setup] typecheck: found tsconfig.json`),`npx tsc --noEmit`):pp(t,`tsc`)?(H.info.defaultLog(`[project-setup] typecheck: found tsc in node_modules`),`npx tsc --noEmit`):null}function Sp(e,t,n){for(let{pkg:t}of e){let e=t.scripts??{},r=wp(t);for(let t of op)if((0,h.isDefined)(e[t]))return hp(n,t);for(let[t,r]of Object.entries(e))if(/\beslint\b/.test(r))return hp(n,t);if((0,h.isDefined)(r.eslint))return`npx eslint`}return up(t,tp)?(H.info.defaultLog(`[project-setup] lint: found eslint config file`),`npx eslint`):pp(t,`eslint`)?(H.info.defaultLog(`[project-setup] lint: found eslint in node_modules`),`npx eslint`):null}function Cp(e,t,n){for(let{pkg:t}of e){let e=t.scripts??{},r=wp(t);for(let t of sp)if((0,h.isDefined)(e[t]))return hp(n,t);for(let[t,r]of Object.entries(e))if(/\bprettier\b/.test(r))return hp(n,t);if((0,h.isDefined)(r.prettier))return`npx prettier`}return up(t,np)?(H.info.defaultLog(`[project-setup] prettier: found prettier config file`),`npx prettier`):pp(t,`prettier`)?(H.info.defaultLog(`[project-setup] prettier: found prettier in node_modules`),`npx prettier`):null}function wp(e){return{...e.dependencies,...e.devDependencies}}function Tp(e,t){let n=cp(e),r=lp(e),i=mp(e),a=(0,h.isDefined)(t)?f.default.relative(e,t):null,o=yp(r,n,i),s=(0,h.isDefined)(o)&&(0,h.isDefined)(a)?gp(o,a):null,c=fp(r,n),l=xp(r,n,i),u=Sp(r,n,i),d=(0,h.isDefined)(u)&&(0,h.isDefined)(a)?`npx eslint ${a}`:null,p=Cp(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 Ep=(0,D.promisify)(E.exec),Dp=4e3;function Op(e,t){return e.length<=t?e:`... (truncated, ${e.length-t} chars omitted)\n`+e.slice(-t)}let kp=function(e){return e.TEST=`testCommand`,e.BUILD=`buildCommand`,e.LINT=`lintCommand`,e.FORMAT=`prettierCommand`,e}({});var Ap=class{setup;testFilePath;workingDirectory;lastCheckAllResult=null;mcpServer;constructor(e){this.setup=e.setup,this.testFilePath=e.testFilePath,this.workingDirectory=e.workingDirectory,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===kp.TEST),t=this.lastCheckAllResult.gates.find(e=>e.gate===kp.LINT),n=(0,h.isDefined)(e?.output)?sf(e.output):void 0,r=(0,h.isDefined)(t?.output)?lf(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===Uf.UNRESOLVED)return{gate:e,passed:!0,skipped:!0};try{let{stdout:n,stderr:r}=await Ep(t.command,{cwd:this.workingDirectory,encoding:`utf8`,timeout:6e4});return{gate:e,passed:!0,skipped:!1,output:Op((n+r).trim(),Dp)}}catch(t){return{gate:e,passed:!1,skipped:!1,output:Op(qd(t),Dp)}}}async checkAll(){let e=this.setup.lintCommand.status!==Uf.UNRESOLVED,t=this.setup.prettierCommand.status!==Uf.UNRESOLVED,n=await this.runStabilityLoop(e,t);if(n.stabilityConflict===!0)return this.lastCheckAllResult=n,n;let[r,i]=await Promise.all([this.runGate(kp.TEST),this.runGate(kp.BUILD)]);if(!r.passed&&(0,h.isDefined)(r.output)){let e=sf(r.output);(0,h.isDefined)(e)&&e.passed>=6&&(r.passed=!0)}let a=[...n.gates,r,i],o={passed:a.every(e=>e.passed),gates:a};return this.lastCheckAllResult=o,o}async runStabilityLoop(e,t){let n={gate:kp.LINT,passed:!0,skipped:!0},r={gate:kp.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(kp.LINT):Promise.resolve(n),t?this.runGate(kp.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,ae.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(kp.LINT);return{content:[{type:`text`,text:JSON.stringify(e,null,2)}]}}),t=(0,ae.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(kp.FORMAT);return{content:[{type:`text`,text:JSON.stringify(e,null,2)}]}}),n=(0,ae.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(kp.TEST),t=(0,h.isDefined)(e.output)?sf(e.output):void 0;return!e.passed&&(0,h.isDefined)(t)&&t.passed>=6&&(e.passed=!0),e.testReport=t,{content:[{type:`text`,text:JSON.stringify(e,null,2)}]}}),r=(0,ae.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(kp.BUILD);return{content:[{type:`text`,text:JSON.stringify(e,null,2)}]}}),i=(0,ae.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===kp.TEST);return e.testReport=(0,h.isDefined)(t?.output)?sf(t.output):void 0,{content:[{type:`text`,text:JSON.stringify(e,null,2)}]}}),a=(0,ae.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,ae.createSdkMcpServer)({name:`verification_gates`,version:`1.0.0`,tools:[e,t,n,r,i,a]})}},jp=l(Oe()),Mp=l(hr()),Np=l(ke()),Pp,Fp,Ip,Lp;function Rp(e){return(0,h.isEmpty)(e)||!(0,C.existsSync)(e)?``:(0,C.readFileSync)(e,`utf8`)}function zp(e){return(e.duration_ms/1e3).toFixed(1),``}function Bp(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(`
|
|
32076
|
+
`;default:return Uf}}function Gf(e){return(0,h.isDefined)(e)?{status:zf.RESOLVED,command:e}:{status:zf.UNRESOLVED}}function Kf(e){return{testCommand:Gf(e.testCommand),buildCommand:Gf(e.typecheckCommand),lintCommand:Gf(e.lintCommand),prettierCommand:Gf(e.prettierCommand),packageManager:e.packageManager}}var qf=l(ke());let Jf=(0,D.promisify)(E.exec),Yf=[/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 Xf(e){return Yf.some(t=>t.test(e))}let Zf=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!==Bf.FAILED&&i.status!==Bf.FAILED&&a.status!==Bf.FAILED&&o.status!==Bf.FAILED}}async runGate(e,t){if(e.status===zf.UNRESOLVED)return{status:Bf.SKIPPED,reason:`unresolved`};try{return await Jf(e.command,{cwd:t,encoding:`utf8`,timeout:6e4}),{status:Bf.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:Bf.FAILED,command:e.command,output:r.slice(0,100)}}}};Zf=(0,qf.default)([(0,_.injectable)()],Zf);function Qf(e,t){let n=(e,t)=>e.status===zf.UNRESOLVED?e:t.status===Bf.PASSED?{status:zf.VERIFIED,command:e.command}:{status:zf.UNRESOLVED},r=(e,t)=>e.status===zf.UNRESOLVED?e:t.status===Bf.PASSED||t.status===Bf.FAILED&&!Xf(t.output)?{status:zf.VERIFIED,command:e.command}:{status:zf.UNRESOLVED};return{testCommand:n(e.testCommand,t.testCommand),buildCommand:r(e.buildCommand,t.buildCommand),lintCommand:r(e.lintCommand,t.lintCommand),prettierCommand:r(e.prettierCommand,t.prettierCommand),packageManager:e.packageManager}}let $f=[`jest.config.ts`,`jest.config.js`,`jest.config.mjs`,`jest.config.cjs`,`vitest.config.ts`,`vitest.config.js`,`vitest.config.mjs`],ep=[`tsconfig.json`],tp=[`.eslintrc`,`.eslintrc.js`,`.eslintrc.cjs`,`.eslintrc.json`,`.eslintrc.yml`,`.eslintrc.yaml`,`eslint.config.js`,`eslint.config.mjs`,`eslint.config.cjs`,`eslint.config.ts`],np=[`.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`],rp=new Set([`build`,`compile`,`dist`,`prepublish`,`prepublishOnly`,`prepare`]),ip=[`test:unit`,`test:ci`,`test:run`],ap=[`check:ts`,`typecheck`,`type-check`,`tsc`],op=[`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,C.existsSync)(f.default.join(n,`.git`)));)n=f.default.dirname(n);return t}function lp(e){let t=[];for(let n of cp(e)){let e=f.default.join(n,`package.json`);if((0,C.existsSync)(e))try{let r=JSON.parse((0,C.readFileSync)(e,`utf8`));t.push({dir:n,pkg:r})}catch{}}return t}function up(e,t){for(let n of e)for(let e of t)if((0,C.existsSync)(f.default.join(n,e)))return!0;return!1}function dp(e){for(let t of e)for(let e of $f)if((0,C.existsSync)(f.default.join(t,e)))return e.startsWith(`vitest`)?`vitest`:`jest`;return null}function fp(e,t){let n=dp(t);if((0,h.isDefined)(n))return n;for(let{pkg:t}of e){let e=wp(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 pp(t,`vitest`)?`vitest`:pp(t,`jest`)?`jest`:null}function pp(e,t){for(let n of e)if((0,C.existsSync)(f.default.join(n,`node_modules`,`.bin`,t)))return!0;return!1}function mp(e){for(let t of cp(e)){if((0,C.existsSync)(f.default.join(t,`pnpm-lock.yaml`))||(0,C.existsSync)(f.default.join(t,`pnpm-workspace.yaml`)))return`pnpm`;if((0,C.existsSync)(f.default.join(t,`yarn.lock`)))return`yarn`;if((0,C.existsSync)(f.default.join(t,`bun.lockb`))||(0,C.existsSync)(f.default.join(t,`bun.lock`)))return`bun`}return`npm`}function hp(e,t){return e===`yarn`?`yarn ${t}`:`${e} run ${t}`}function gp(e,t){return e.startsWith(`npx `)||e.startsWith(`yarn `)?`${e} ${t}`:`${e} -- ${t}`}let _p=/(?:^echo\b)|(?:no test specified)|(?:placeholder)/i;function vp(e,t){let n=e.scripts??{},r=wp(e),i=n.test;if((0,h.isDefined)(i)&&!_p.test(i))return hp(t,`test`);for(let e of ip)if((0,h.isDefined)(n[e]))return hp(t,e);for(let[e,r]of Object.entries(n))if(/\bjest\b/.test(r)||/\bvitest\b/.test(r))return hp(t,e);return(0,h.isDefined)(r.jest)?`npx jest`:(0,h.isDefined)(r.vitest)?`npx vitest`:null}function yp(e,t,n){for(let{pkg:t}of e){let e=vp(t,n);if((0,h.isDefined)(e))return e}let r=dp(t);return(0,h.isDefined)(r)?(H.info.defaultLog(`[project-setup] test: found config file for ${r}`),`npx ${r}`):pp(t,`jest`)?(H.info.defaultLog(`[project-setup] test: found jest in node_modules`),`npx jest`):pp(t,`vitest`)?(H.info.defaultLog(`[project-setup] test: found vitest in node_modules`),`npx vitest`):null}function bp(e,t){let n=e.scripts??{},r=wp(e);for(let e of ap)if((0,h.isDefined)(n[e]))return hp(t,e);for(let[e,r]of Object.entries(n))if(/\btsc\b/.test(r)&&!rp.has(e))return hp(t,e);return(0,h.isDefined)(r.typescript)?`npx tsc --noEmit`:null}function xp(e,t,n){for(let{pkg:t}of e){let e=bp(t,n);if((0,h.isDefined)(e))return e}return up(t,ep)?(H.info.defaultLog(`[project-setup] typecheck: found tsconfig.json`),`npx tsc --noEmit`):pp(t,`tsc`)?(H.info.defaultLog(`[project-setup] typecheck: found tsc in node_modules`),`npx tsc --noEmit`):null}function Sp(e,t,n){for(let{pkg:t}of e){let e=t.scripts??{},r=wp(t);for(let t of op)if((0,h.isDefined)(e[t]))return hp(n,t);for(let[t,r]of Object.entries(e))if(/\beslint\b/.test(r))return hp(n,t);if((0,h.isDefined)(r.eslint))return`npx eslint`}return up(t,tp)?(H.info.defaultLog(`[project-setup] lint: found eslint config file`),`npx eslint`):pp(t,`eslint`)?(H.info.defaultLog(`[project-setup] lint: found eslint in node_modules`),`npx eslint`):null}function Cp(e,t,n){for(let{pkg:t}of e){let e=t.scripts??{},r=wp(t);for(let t of sp)if((0,h.isDefined)(e[t]))return hp(n,t);for(let[t,r]of Object.entries(e))if(/\bprettier\b/.test(r))return hp(n,t);if((0,h.isDefined)(r.prettier))return`npx prettier`}return up(t,np)?(H.info.defaultLog(`[project-setup] prettier: found prettier config file`),`npx prettier`):pp(t,`prettier`)?(H.info.defaultLog(`[project-setup] prettier: found prettier in node_modules`),`npx prettier`):null}function wp(e){return{...e.dependencies,...e.devDependencies}}function Tp(e,t){let n=cp(e),r=lp(e),i=mp(e),a=(0,h.isDefined)(t)?f.default.relative(e,t):null,o=yp(r,n,i),s=(0,h.isDefined)(o)&&(0,h.isDefined)(a)?gp(o,a):null,c=fp(r,n),l=xp(r,n,i),u=Sp(r,n,i),d=(0,h.isDefined)(u)&&(0,h.isDefined)(a)?`npx eslint ${a}`:null,p=Cp(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 Ep=(0,D.promisify)(E.exec),Dp=4e3;function Op(e,t){return e.length<=t?e:`... (truncated, ${e.length-t} chars omitted)\n`+e.slice(-t)}let kp=function(e){return e.TEST=`testCommand`,e.BUILD=`buildCommand`,e.LINT=`lintCommand`,e.FORMAT=`prettierCommand`,e}({});var Ap=class{setup;testFilePath;workingDirectory;lastCheckAllResult=null;mcpServer;constructor(e){this.setup=e.setup,this.testFilePath=e.testFilePath,this.workingDirectory=e.workingDirectory,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===kp.TEST),t=this.lastCheckAllResult.gates.find(e=>e.gate===kp.LINT),n=(0,h.isDefined)(e?.output)?sf(e.output):void 0,r=(0,h.isDefined)(t?.output)?lf(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 Ep(t.command,{cwd:this.workingDirectory,encoding:`utf8`,timeout:6e4});return{gate:e,passed:!0,skipped:!1,output:Op((n+r).trim(),Dp)}}catch(t){return{gate:e,passed:!1,skipped:!1,output:Op(qd(t),Dp)}}}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;let[r,i]=await Promise.all([this.runGate(kp.TEST),this.runGate(kp.BUILD)]);if(!r.passed&&(0,h.isDefined)(r.output)){let e=sf(r.output);(0,h.isDefined)(e)&&e.passed>=6&&(r.passed=!0)}let a=[...n.gates,r,i],o={passed:a.every(e=>e.passed),gates:a};return this.lastCheckAllResult=o,o}async runStabilityLoop(e,t){let n={gate:kp.LINT,passed:!0,skipped:!0},r={gate:kp.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(kp.LINT):Promise.resolve(n),t?this.runGate(kp.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,ae.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(kp.LINT);return{content:[{type:`text`,text:JSON.stringify(e,null,2)}]}}),t=(0,ae.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(kp.FORMAT);return{content:[{type:`text`,text:JSON.stringify(e,null,2)}]}}),n=(0,ae.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(kp.TEST),t=(0,h.isDefined)(e.output)?sf(e.output):void 0;return!e.passed&&(0,h.isDefined)(t)&&t.passed>=6&&(e.passed=!0),e.testReport=t,{content:[{type:`text`,text:JSON.stringify(e,null,2)}]}}),r=(0,ae.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(kp.BUILD);return{content:[{type:`text`,text:JSON.stringify(e,null,2)}]}}),i=(0,ae.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===kp.TEST);return e.testReport=(0,h.isDefined)(t?.output)?sf(t.output):void 0,{content:[{type:`text`,text:JSON.stringify(e,null,2)}]}}),a=(0,ae.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,ae.createSdkMcpServer)({name:`verification_gates`,version:`1.0.0`,tools:[e,t,n,r,i,a]})}},jp=l(Oe()),Mp=l(hr()),Np=l(ke()),Pp,Fp,Ip,Lp;function Rp(e){return(0,h.isEmpty)(e)||!(0,C.existsSync)(e)?``:(0,C.readFileSync)(e,`utf8`)}function zp(e){return(e.duration_ms/1e3).toFixed(1),``}function Bp(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(`
|
|
32077
32077
|
`)}function Vp(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(`
|
|
32078
|
-
`)}function Hp(e){let t=[``,`<project-setup>`,`The following project tooling was verified. Use these commands directly.`,``];e.testCommand.status!==
|
|
32079
|
-
`)}function Up(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===
|
|
32080
|
-
`)}function Wp(e,t,n){let r=f.default.relative(t,n),i=e.getTestCommand(),a=e.getLintCommand(),o=e.getPrettierCommand(),s=Tp(t,n);return(0,h.isDefined)(i)&&(s.testCommand=i.replaceAll(Se,r),s.missing=s.missing.filter(e=>e!==`testCommand`)),a!==we&&(s.lintCommand=a.replaceAll(Se,r),s.missing=s.missing.filter(e=>e!==`lintCommand`)),o!==Te&&(s.prettierCommand=o.replaceAll(Se,r),s.missing=s.missing.filter(e=>e!==`prettierCommand`)),s}let Gp=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;e.abortSignal&&e.abortSignal.addEventListener(`abort`,()=>t.abort());let{modelName:n,capPrice:r}=await this.llmModelService.getAgentSdkConfig(),i=Wp(this.globalConfigService,e.workingDirectory,e.testFilePath);H.info.defaultLog(`[precalc] Project setup resolved:\n${JSON.stringify(i,null,2)}`);let a=Kf(i),
|
|
32081
|
-
`)},hooks:{PreToolUse:[{matcher:`Write|Edit`,hooks:[t]},{matcher:`Read`,hooks:[Qd]},{matcher:`Bash`,hooks:[Zd,Xd]}]}}});for await(let e of u)if(a.logMessage(e),await s.processMessage(e),Ud(e)){await s.flush(),a.logResult(e),H.info.defaultLog(`[cleanup] SDK model usage: `,e.modelUsage),Wd(e)&&H.default.warn(`[cleanup] Agent finished with error: ${e.subtype}`);break}}async runGenerationQuery(e){let t=$d(e.testFilePath,e.workingDirectory),n=dd?new Ap({setup:e.verifiedSetup,testFilePath:e.testFilePath,workingDirectory:e.workingDirectory}):void 0,r=n?bf(n):void 0,i=new Rf(!1),a=[...ud];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`],...dd&&{stop:[`verification-gates`]}}});let o=Bp(e.userPrompt,e.testFilePath)+Vp(e.workingDirectory)+Hp(e.verifiedSetup),s=await this.authStorage.getJWTToken()??``,c=
|
|
32082
|
-
`)},...n&&{mcpServers:{verification_gates:n.getServer()}},hooks:{PreToolUse:[{matcher:`Write|Edit`,hooks:[t]},{matcher:`Read`,hooks:[Qd]},{matcher:`Bash`,hooks:[Zd,Xd]}],PostToolUse:[{matcher:`Bash`,hooks:[vf]},{matcher:`${pd}|${fd}`,hooks:[vf]}],...r&&{Stop:[{hooks:[r]}]}}}});for await(let t of u)if(i.logMessage(t),await l.processMessage(t),Ud(t)){if(await l.flush(),i.logResult(t),H.info.defaultLog(`SDK model usage: `,t.modelUsage),Wd(t))throw new Bf(t.subtype,t.errors,t.total_cost_usd);let r=Rp(e.testFilePath),a=n?.buildValidationSummary()??i.buildValidationSummary();if(H.info.defaultLog(`Validation summary: `,a),!(0,h.isEmpty)(r)){let n=zp(t)+r;return(0,C.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:Rp(e.testFilePath)}}};Gp=(0,Np.default)([(0,_.injectable)(),(0,Mp.default)(0,(0,_.inject)(Pe)),(0,Mp.default)(1,(0,_.inject)(mr)),(0,Mp.default)(2,(0,_.inject)(Df)),(0,Mp.default)(3,(0,_.inject)(Vr)),(0,Mp.default)(4,(0,_.inject)(Zf)),(0,jp.default)(`design:paramtypes`,[Object,typeof(Pp=mr!==void 0&&mr)==`function`?Pp:Object,typeof(Fp=Df!==void 0&&Df)==`function`?Fp:Object,typeof(Ip=Vr!==void 0&&Vr)==`function`?Ip:Object,typeof(Lp=Zf!==void 0&&Zf)==`function`?Lp:Object])],Gp);var Kp=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}},qp=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}},Jp=class{execute(e){let t=e.getDataSource().testedCodeDataSource.testedMethodClass,n=t?.constructorMetadata?.parameters??[],r=t?.properties??[],i=[...n,...r];return e.moveKnownDependencyToMissingByParameters(i)}},Yp=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}},Xp=class{execute(e){let t=e.getDataSource().testedCodeDataSource.testedMethod.parameters??[];return e.moveKnownDependencyToMissingByParameters(t)}},Zp=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()}},Qp=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))}},$p=class{execute(e){let t=e.getDataSource().testedCodeDataSource.testedMethod.returnParam?.id;return(0,h.isDefined)(t)?e.moveKnowDependencyToMissingByParameterId(t):!1}},em=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:xt.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)}},tm=class{modifierHandlers=[];modifierCount;constructor(){let e=new Yp(`react-class-component`,`react-hook`,`react-forward-ref-component`,`react-function-component`,`react-css-in-js`),t=new qp(`class`),n=new Qp,r=new Jp,i=new Xp,a=new $p,o=new Kp,s=new Zp;this.modifierHandlers.push(e,t,n,r,i,a,o,s),this.modifierCount=this.modifierHandlers.length}refine(e){let t=new em(e);for(let e of this.modifierHandlers)if(e.execute(t))return!0;return!1}},nm=class e{testCodeDatasourceRefiner=new tm;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 rm=()=>Ie().getRequestSource()===le.IDE;var im=l(Oe()),am=l(ke()),om=class{sourceFileCache=new Map;constructor(e,t){this.testable=e,this.filePath=t}async getReferences(e=2){let t=Bt.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(T.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 G(await Ke.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,am.default)([Vt,(0,im.default)(`design:type`,Function),(0,im.default)(`design:paramtypes`,[Object]),(0,im.default)(`design:returntype`,Promise)],om.prototype,`getReferences`,null);var sm=l(Oe()),cm=l(hr()),lm=l(ke()),um;let dm=class{constructor(e){this.dependenciesService=e}async getTestedCodeDataSource(e,t,n){await Bt.init(e);let{methodType:r,methodName:i,parentName:a}=Zr(t);H.addContext({subCategory:vt.CODE_EXTRACTOR}),H.debug.defaultLog(`Get testable context for ${r} ${i}() in ${e}.`);try{let o=await new Ke(e).getText(),s=Ze((0,f.extname)(e)),c=kl(s),l=c.extract({methodName:i,methodType:r,parentName:a,filePath:e}),u=rm(),d=await this.dependenciesService.getTestCodeDataSourceCore(l,e,u);if(s===`javascript`)return La(await this.getJsCodeDataSource(e,t,o,d,l,n));let p,m,g,_,y={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,y=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:St.PUBLIC,extendedProperties:{},signature:``,parameterId:(0,v.randomUUID)(),kind:`any`,exportType:xt.Unknown});let x=await new om(t,e).getReferences();return m=await this.reevaluateMissingDependencies(m,d,c),La({gitUrl:Ie().getGitURL(),filePath:e,relativePathToTestFile:this.getRelativePathToTestFile(e,n),testFramework:Ie().getTestFramework(),language:s,testedMethod:g,testedMethodClass:_,missingDependencies:m,codeDependencies:[y,...p],usages:x,libraries:b})}catch(e){throw H.error(`Error occurred during getTestedCodeDataSource ${i}`,e,i),new $n(Zn.TESTED_CODE_DATA_SOURCE_ERROR,{methodName:i})}}async getJsCodeDataSource(e,t,n,r,i,a){let{methodName:o}=Zr(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??xt.Named,accessModifierType:r?.testedMethod.accessModifierType??St.PUBLIC,extendedProperties:r?.testedMethod.extendedProperties,signature:``,parameterId:(0,v.randomUUID)(),kind:`any`},c={name:`NA`,kind:`file`,code:n,importPath:e,dependencyType:`file`,isGenerated:!1},l=await new om(t,e).getReferences(),u=[];if((0,h.isDefined)(i)){let t=await new $s(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:Ua(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:Ie().getGitURL(),filePath:e,relativePathToTestFile:this.getRelativePathToTestFile(e,a),testFramework:Ie().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=rm(),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=Ke.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=Bt.get(e);return Bt.get(t).getRelativePathTo(n)}};(0,lm.default)([Vt,(0,sm.default)(`design:type`,Function),(0,sm.default)(`design:paramtypes`,[String,Object,String]),(0,sm.default)(`design:returntype`,Promise)],dm.prototype,`getTestedCodeDataSource`,null),dm=(0,lm.default)([(0,_.injectable)(),(0,cm.default)(0,(0,_.inject)(Ec)),(0,sm.default)(`design:paramtypes`,[typeof(um=Ec!==void 0&&Ec)==`function`?um:Object])],dm);var fm=l(Oe()),pm=l(hr()),mm=l(ke()),hm,gm;let _m=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=zl(e,await this.featureFlagsService.isRemovingDuplicatedCodeInDependencyMetadataEnabled());return(await nm.init(this.featureFlagsService)).optimize(t)}catch(e){throw H.info.defaultLog(`Failed making preparations for generate test dto`,e,t),new $n(Zn.PREPARATIONS_FOR_GENERATING_TEST_DTO_ERROR,{methodName:n,errorMessage:`Failed making preparations for generate test dto`})}}};_m=(0,mm.default)([(0,_.injectable)(),(0,pm.default)(0,(0,_.inject)(Pe)),(0,pm.default)(1,(0,_.inject)(xc)),(0,pm.default)(2,(0,_.inject)(dm)),(0,fm.default)(`design:paramtypes`,[typeof(hm=Pe!==void 0&&Pe)==`function`?hm:Object,Object,typeof(gm=dm!==void 0&&dm)==`function`?gm:Object])],_m);var vm=l(Oe()),ym=l(hr()),bm=l(ke()),xm,Sm;let Cm=class{constructor(e,t,n){this.apiService=e,this.globalConfigService=t,this.agentSdkRunner=n}async generate(e,t,n,r,i){let a={...e,testedCodeDataSource:{...e.testedCodeDataSource,metadataCollectionTime:n}};if(this.globalConfigService.getExperimentalAgentSdk()){H.info.defaultLog(`[experimental] Using generate-prompt endpoint`);let e=await this.generatePrompt(a,t,r);return this.generateTestViaClaudeAgentSdk(e,i,r)}return this.generateViaBackend(a,t,r)}async generateViaBackend(e,t,n){return this.apiService.post(`/api/v1/tests/generate-tests`,e,{headers:{[tr]:t},signal:n})}async generatePrompt(e,t,n){return await this.apiService.post(`/api/v1/tests/generate-prompt`,e,{headers:{[tr]:t},signal:n})}async generateTestViaClaudeAgentSdk(e,t,n){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 r=this.globalConfigService.getRootPath(),i=(dd?`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.
|
|
32078
|
+
`)}function Hp(e){let t=[``,`<project-setup>`,`The following project tooling was verified. Use these commands directly.`,``];e.testCommand.status!==zf.UNRESOLVED&&t.push(`- **Test command**: \`${e.testCommand.command}\``),e.buildCommand.status!==zf.UNRESOLVED&&t.push(`- **Build command**: \`${e.buildCommand.command}\``),e.lintCommand.status!==zf.UNRESOLVED&&t.push(`- **Lint command**: \`${e.lintCommand.command}\``),e.prettierCommand.status!==zf.UNRESOLVED&&t.push(`- **Prettier command**: \`${e.prettierCommand.command}\``),t.push(`- **Package manager**: ${e.packageManager}`);let n=[];return e.testCommand.status===zf.UNRESOLVED&&n.push(`testCommand`),e.buildCommand.status===zf.UNRESOLVED&&n.push(`buildCommand`),e.lintCommand.status===zf.UNRESOLVED&&n.push(`lintCommand`),e.prettierCommand.status===zf.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(`
|
|
32079
|
+
`)}function Up(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===Bf.FAILED?n.push(`${e}: FAILED`,`Output:\n${r.output.trim()}`,``):r.status===Bf.PASSED?n.push(`${e}: PASSED`):n.push(`${e}: SKIPPED (command not configured)`);return n.push(`</verification-results>`),n.join(`
|
|
32080
|
+
`)}function Wp(e,t,n){let r=f.default.relative(t,n),i=e.getTestCommand(),a=e.getLintCommand(),o=e.getPrettierCommand(),s=Tp(t,n);return(0,h.isDefined)(i)&&(s.testCommand=i.replaceAll(Se,r),s.missing=s.missing.filter(e=>e!==`testCommand`)),a!==we&&(s.lintCommand=a.replaceAll(Se,r),s.missing=s.missing.filter(e=>e!==`lintCommand`)),o!==Te&&(s.prettierCommand=o.replaceAll(Se,r),s.missing=s.missing.filter(e=>e!==`prettierCommand`)),s}let Gp=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;e.abortSignal&&e.abortSignal.addEventListener(`abort`,()=>t.abort());let{modelName:n,capPrice:r}=await this.llmModelService.getAgentSdkConfig(),i=Wp(this.globalConfigService,e.workingDirectory,e.testFilePath);H.info.defaultLog(`[precalc] Project setup resolved:\n${JSON.stringify(i,null,2)}`);let a=H.getRequestId(),o=new Vf(this.metricReportService,a,n,e.testFilePath),s=Kf(i),c=Wf(i.testRunner);await(0,p.mkdir)(f.default.dirname(e.testFilePath),{recursive:!0}),await(0,p.writeFile)(e.testFilePath,c,`utf8`);let l=await this.verificationService.verify({setup:s,testFilePath:e.testFilePath,workingDirectory:e.workingDirectory});if(H.info.defaultLog(`[verification] Pre-generation: ${JSON.stringify(l,null,2)}`),l.testCommand.status===Bf.FAILED){let t=l.testCommand.output;throw H.default.warn(`[verification] Test command failed on dummy test — aborting.\n${t}`),await(0,p.unlink)(e.testFilePath),new Hf(`test_command_failed`,[`Test command failed: ${t.slice(0,200)}`],0)}let u=s;s=Qf(s,l),o.addPreVerification(u,l,s),H.info.defaultLog(`[verification] Promoted setup: ${JSON.stringify(s,null,2)}`);let d=await this.runGenerationQuery({...e,model:n,budget:r,verifiedSetup:s,abortController:t,metricsTracer:o}),m=await this.verificationService.verify({setup:s,testFilePath:e.testFilePath,workingDirectory:e.workingDirectory});if(H.info.defaultLog(`[verification] Post-generation: ${JSON.stringify(m,null,2)}`),m.passed)return d;H.default.warn(`[verification] Gates failed — running cleanup agent to salvage passing tests`),await this.runCleanupQuery({workingDirectory:e.workingDirectory,testFilePath:e.testFilePath,model:n,budget:r,verifiedSetup:s,abortController:t,postVerification:m});let h=await this.verificationService.verify({setup:s,testFilePath:e.testFilePath,workingDirectory:e.workingDirectory});return H.info.defaultLog(`[verification] Post-cleanup: ${JSON.stringify(h,null,2)}`),h.passed?{code:Rp(e.testFilePath),costUsd:d.costUsd,validationSummary:d.validationSummary}:(H.default.warn(`[verification] Cleanup failed — deleting test file: ${e.testFilePath}`),await(0,p.unlink)(e.testFilePath),{code:``,costUsd:d.costUsd,validationSummary:d.validationSummary})}async runCleanupQuery(e){let t=$d(e.testFilePath,e.workingDirectory),n=await this.authStorage.getJWTToken()??``,r=Math.max(e.budget*.25,.25),i=[...ud],a=new Rf(!1),o=H.getRequestId(),s=new Vf(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.`+Up(e.postVerification)+Vp(e.workingDirectory)+Hp(e.verifiedSetup),u=(0,ae.query)({prompt:l,options:{model:e.model,systemPrompt:c,allowedTools:[...ud],permissionMode:ld,allowDangerouslySkipPermissions:!0,maxBudgetUsd:r,maxTurns:15,cwd:e.workingDirectory,abortController:e.abortController,sessionId:(0,v.randomUUID)(),env:{...process.env,ANTHROPIC_BASE_URL:this.globalConfigService.getAnthropicProxyUrl(),ANTHROPIC_AUTH_TOKEN:n,ANTHROPIC_CUSTOM_HEADERS:[`x-request-id: `+H.getRequestId()].join(`
|
|
32081
|
+
`)},hooks:{PreToolUse:[{matcher:`Write|Edit`,hooks:[t]},{matcher:`Read`,hooks:[Qd]},{matcher:`Bash`,hooks:[Zd,Xd]}]}}});for await(let e of u)if(a.logMessage(e),await s.processMessage(e),Ud(e)){await s.flush(),a.logResult(e),H.info.defaultLog(`[cleanup] SDK model usage: `,e.modelUsage),Wd(e)&&H.default.warn(`[cleanup] Agent finished with error: ${e.subtype}`);break}}async runGenerationQuery(e){let t=$d(e.testFilePath,e.workingDirectory),n=dd?new Ap({setup:e.verifiedSetup,testFilePath:e.testFilePath,workingDirectory:e.workingDirectory}):void 0,r=n?bf(n):void 0,i=new Rf(!1),a=[...ud];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`],...dd&&{stop:[`verification-gates`]}}});let o=Bp(e.userPrompt,e.testFilePath)+Vp(e.workingDirectory)+Hp(e.verifiedSetup),s=await this.authStorage.getJWTToken()??``,{metricsTracer:c}=e,l=(0,ae.query)({prompt:o,options:{model:e.model,systemPrompt:e.systemPrompt,allowedTools:a,permissionMode:ld,allowDangerouslySkipPermissions:!0,maxBudgetUsd:e.budget,cwd:e.workingDirectory,abortController:e.abortController,sessionId:(0,v.randomUUID)(),env:{...process.env,ANTHROPIC_BASE_URL:this.globalConfigService.getAnthropicProxyUrl(),ANTHROPIC_AUTH_TOKEN:s,ANTHROPIC_CUSTOM_HEADERS:[`x-request-id: `+H.getRequestId()].join(`
|
|
32082
|
+
`)},...n&&{mcpServers:{verification_gates:n.getServer()}},hooks:{PreToolUse:[{matcher:`Write|Edit`,hooks:[t]},{matcher:`Read`,hooks:[Qd]},{matcher:`Bash`,hooks:[Zd,Xd]}],PostToolUse:[{matcher:`Bash`,hooks:[vf]},{matcher:`${pd}|${fd}`,hooks:[vf]}],...r&&{Stop:[{hooks:[r]}]}}}});for await(let t of l)if(i.logMessage(t),await c.processMessage(t),Ud(t)){if(await c.flush(),i.logResult(t),H.info.defaultLog(`SDK model usage: `,t.modelUsage),Wd(t))throw new Hf(t.subtype,t.errors,t.total_cost_usd);let r=Rp(e.testFilePath),a=n?.buildValidationSummary()??i.buildValidationSummary();if(H.info.defaultLog(`Validation summary: `,a),!(0,h.isEmpty)(r)){let n=zp(t)+r;return(0,C.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:Rp(e.testFilePath)}}};Gp=(0,Np.default)([(0,_.injectable)(),(0,Mp.default)(0,(0,_.inject)(Pe)),(0,Mp.default)(1,(0,_.inject)(mr)),(0,Mp.default)(2,(0,_.inject)(Df)),(0,Mp.default)(3,(0,_.inject)(Vr)),(0,Mp.default)(4,(0,_.inject)(Zf)),(0,jp.default)(`design:paramtypes`,[Object,typeof(Pp=mr!==void 0&&mr)==`function`?Pp:Object,typeof(Fp=Df!==void 0&&Df)==`function`?Fp:Object,typeof(Ip=Vr!==void 0&&Vr)==`function`?Ip:Object,typeof(Lp=Zf!==void 0&&Zf)==`function`?Lp:Object])],Gp);var Kp=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}},qp=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}},Jp=class{execute(e){let t=e.getDataSource().testedCodeDataSource.testedMethodClass,n=t?.constructorMetadata?.parameters??[],r=t?.properties??[],i=[...n,...r];return e.moveKnownDependencyToMissingByParameters(i)}},Yp=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}},Xp=class{execute(e){let t=e.getDataSource().testedCodeDataSource.testedMethod.parameters??[];return e.moveKnownDependencyToMissingByParameters(t)}},Zp=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()}},Qp=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))}},$p=class{execute(e){let t=e.getDataSource().testedCodeDataSource.testedMethod.returnParam?.id;return(0,h.isDefined)(t)?e.moveKnowDependencyToMissingByParameterId(t):!1}},em=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:xt.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)}},tm=class{modifierHandlers=[];modifierCount;constructor(){let e=new Yp(`react-class-component`,`react-hook`,`react-forward-ref-component`,`react-function-component`,`react-css-in-js`),t=new qp(`class`),n=new Qp,r=new Jp,i=new Xp,a=new $p,o=new Kp,s=new Zp;this.modifierHandlers.push(e,t,n,r,i,a,o,s),this.modifierCount=this.modifierHandlers.length}refine(e){let t=new em(e);for(let e of this.modifierHandlers)if(e.execute(t))return!0;return!1}},nm=class e{testCodeDatasourceRefiner=new tm;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 rm=()=>Ie().getRequestSource()===le.IDE;var im=l(Oe()),am=l(ke()),om=class{sourceFileCache=new Map;constructor(e,t){this.testable=e,this.filePath=t}async getReferences(e=2){let t=Bt.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(T.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 G(await Ke.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,am.default)([Vt,(0,im.default)(`design:type`,Function),(0,im.default)(`design:paramtypes`,[Object]),(0,im.default)(`design:returntype`,Promise)],om.prototype,`getReferences`,null);var sm=l(Oe()),cm=l(hr()),lm=l(ke()),um;let dm=class{constructor(e){this.dependenciesService=e}async getTestedCodeDataSource(e,t,n){await Bt.init(e);let{methodType:r,methodName:i,parentName:a}=Zr(t);H.addContext({subCategory:vt.CODE_EXTRACTOR}),H.debug.defaultLog(`Get testable context for ${r} ${i}() in ${e}.`);try{let o=await new Ke(e).getText(),s=Ze((0,f.extname)(e)),c=kl(s),l=c.extract({methodName:i,methodType:r,parentName:a,filePath:e}),u=rm(),d=await this.dependenciesService.getTestCodeDataSourceCore(l,e,u);if(s===`javascript`)return La(await this.getJsCodeDataSource(e,t,o,d,l,n));let p,m,g,_,y={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,y=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:St.PUBLIC,extendedProperties:{},signature:``,parameterId:(0,v.randomUUID)(),kind:`any`,exportType:xt.Unknown});let x=await new om(t,e).getReferences();return m=await this.reevaluateMissingDependencies(m,d,c),La({gitUrl:Ie().getGitURL(),filePath:e,relativePathToTestFile:this.getRelativePathToTestFile(e,n),testFramework:Ie().getTestFramework(),language:s,testedMethod:g,testedMethodClass:_,missingDependencies:m,codeDependencies:[y,...p],usages:x,libraries:b})}catch(e){throw H.error(`Error occurred during getTestedCodeDataSource ${i}`,e,i),new $n(Zn.TESTED_CODE_DATA_SOURCE_ERROR,{methodName:i})}}async getJsCodeDataSource(e,t,n,r,i,a){let{methodName:o}=Zr(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??xt.Named,accessModifierType:r?.testedMethod.accessModifierType??St.PUBLIC,extendedProperties:r?.testedMethod.extendedProperties,signature:``,parameterId:(0,v.randomUUID)(),kind:`any`},c={name:`NA`,kind:`file`,code:n,importPath:e,dependencyType:`file`,isGenerated:!1},l=await new om(t,e).getReferences(),u=[];if((0,h.isDefined)(i)){let t=await new $s(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:Ua(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:Ie().getGitURL(),filePath:e,relativePathToTestFile:this.getRelativePathToTestFile(e,a),testFramework:Ie().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=rm(),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=Ke.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=Bt.get(e);return Bt.get(t).getRelativePathTo(n)}};(0,lm.default)([Vt,(0,sm.default)(`design:type`,Function),(0,sm.default)(`design:paramtypes`,[String,Object,String]),(0,sm.default)(`design:returntype`,Promise)],dm.prototype,`getTestedCodeDataSource`,null),dm=(0,lm.default)([(0,_.injectable)(),(0,cm.default)(0,(0,_.inject)(Ec)),(0,sm.default)(`design:paramtypes`,[typeof(um=Ec!==void 0&&Ec)==`function`?um:Object])],dm);var fm=l(Oe()),pm=l(hr()),mm=l(ke()),hm,gm;let _m=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=zl(e,await this.featureFlagsService.isRemovingDuplicatedCodeInDependencyMetadataEnabled());return(await nm.init(this.featureFlagsService)).optimize(t)}catch(e){throw H.info.defaultLog(`Failed making preparations for generate test dto`,e,t),new $n(Zn.PREPARATIONS_FOR_GENERATING_TEST_DTO_ERROR,{methodName:n,errorMessage:`Failed making preparations for generate test dto`})}}};_m=(0,mm.default)([(0,_.injectable)(),(0,pm.default)(0,(0,_.inject)(Pe)),(0,pm.default)(1,(0,_.inject)(xc)),(0,pm.default)(2,(0,_.inject)(dm)),(0,fm.default)(`design:paramtypes`,[typeof(hm=Pe!==void 0&&Pe)==`function`?hm:Object,Object,typeof(gm=dm!==void 0&&dm)==`function`?gm:Object])],_m);var vm=l(Oe()),ym=l(hr()),bm=l(ke()),xm,Sm;let Cm=class{constructor(e,t,n){this.apiService=e,this.globalConfigService=t,this.agentSdkRunner=n}async generate(e,t,n,r,i){let a={...e,testedCodeDataSource:{...e.testedCodeDataSource,metadataCollectionTime:n}};if(this.globalConfigService.getExperimentalAgentSdk()){H.info.defaultLog(`[experimental] Using generate-prompt endpoint`);let e=await this.generatePrompt(a,t,r);return this.generateTestViaClaudeAgentSdk(e,i,r)}return this.generateViaBackend(a,t,r)}async generateViaBackend(e,t,n){return this.apiService.post(`/api/v1/tests/generate-tests`,e,{headers:{[tr]:t},signal:n})}async generatePrompt(e,t,n){return await this.apiService.post(`/api/v1/tests/generate-prompt`,e,{headers:{[tr]:t},signal:n})}async generateTestViaClaudeAgentSdk(e,t,n){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 r=this.globalConfigService.getRootPath(),i=(dd?`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.
|
|
32083
32083
|
|
|
32084
32084
|
<use_parallel_tool_calls>
|
|
32085
32085
|
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.
|
|
@@ -32352,7 +32352,7 @@ Available tools (ordered by token cost — prefer the cheapest tool that gets th
|
|
|
32352
32352
|
- \`Write\`: Create new files.
|
|
32353
32353
|
</tools>
|
|
32354
32354
|
|
|
32355
|
-
Start the workflow now with Phase 0 (read the provided project commands), then proceed with the given target file/function.`)||e.systemPrompt,a=await this.agentSdkRunner.run({userPrompt:e.prompt,workingDirectory:r,testFilePath:t,systemPrompt:i,abortSignal:n});return{code:a.code,prompt:e.prompt,requestId:e.requestId,validationSummary:a.validationSummary}}};Cm=(0,bm.default)([(0,_.injectable)(),(0,ym.default)(0,(0,_.inject)(xr)),(0,ym.default)(1,(0,_.inject)(Pe)),(0,ym.default)(2,(0,_.inject)(Gp)),(0,vm.default)(`design:paramtypes`,[typeof(xm=xr!==void 0&&xr)==`function`?xm:Object,Object,typeof(Sm=Gp!==void 0&&Gp)==`function`?Sm:Object])],Cm);var wm=l(Oe()),Tm=l(hr()),Em=l(ke()),Dm,Om,km,Am,jm,Mm;let Nm=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}=Zr(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 Bt.init(e);let u=rt(e),d=await this.getEarlyTestFile(e,c,u,n),p=d.getFilePath(),m=null;Bt.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(),u,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 $n(Zn.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 Bf){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 $n(Zn.EMPTY_TEST,{methodName:c});let E=performance.now();if(r?.aborted??!1)return s(a);Bt.add(p,C),await new la(this.importSolverService,e,p,t,u).refine({shouldResolveMockPaths:!0,shouldSolveImports:!0});let D=Bt.get(p).getFullText();if((0,h.isEmpty)(D))throw await v({responseProcessingTime:performance.now()-E,gitUrl:this.globalConfigService.getGitURL()}),new $n(Zn.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 Bt.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 Bt.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 $n||e instanceof Bf)throw e;let n=e instanceof Error?e.message:`Failed making API call`;throw new $n(Zn.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;try{return await this.testGeneratorProvider.generate(e,t,n,r,i)}catch(e){if(H.info.defaultLog(`GenerateTestService failed to generate tests`,e instanceof Error?e.message:e),e instanceof $n||e instanceof Bf)throw e;let t=e instanceof Error?e.message:`Failed making API call`;throw new $n(Zn.GENERATING_TESTS_REQUEST_ERROR,{methodName:a,errorMessage:t})}}async getEarlyTestFile(e,t,n,r){if(r===he.OVERRIDE_CODE_FILE){let n=await ji.getLatestTestFile(e,t);if((0,h.isDefined)(n))return new ji(tt(n))}return await ji.getNextTestFile(e,t,n)}};(0,Em.default)([Vt,(0,wm.default)(`design:type`,Function),(0,wm.default)(`design:paramtypes`,[Object]),(0,wm.default)(`design:returntype`,Promise)],Nm.prototype,`initGenerateTestFlow`,null),Nm=(0,Em.default)([(0,_.injectable)(),(0,Tm.default)(0,(0,_.inject)(Vr)),(0,Tm.default)(1,(0,_.inject)(Oa)),(0,Tm.default)(2,(0,_.inject)(_m)),(0,Tm.default)(3,(0,_.inject)(Pe)),(0,Tm.default)(4,(0,_.inject)(li)),(0,Tm.default)(5,(0,_.inject)(cu)),(0,Tm.default)(6,(0,_.inject)(Cm)),(0,wm.default)(`design:paramtypes`,[typeof(Dm=Vr!==void 0&&Vr)==`function`?Dm:Object,typeof(Om=Oa!==void 0&&Oa)==`function`?Om:Object,typeof(km=_m!==void 0&&_m)==`function`?km:Object,Object,typeof(Am=li!==void 0&&li)==`function`?Am:Object,typeof(jm=cu!==void 0&&cu)==`function`?jm:Object,typeof(Mm=Cm!==void 0&&Cm)==`function`?Mm:Object])],Nm);var Pm=l(Oe()),Fm=l(hr()),Im=l(ke()),Lm,Rm,zm,Bm,Vm,Hm;let Um=class{shouldTriggerRefreshCoverage=!1;queue;coverageService=new Kn;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 Hr({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=`**/.${Jr}*`,t=await(0,k.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}=Zr(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 Ht(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 Bt.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=``}=Zr(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 $n&&(H.default.info(``),H.default.warn(`‼️ ${e.message}`),this.queue.clearQueued(),r?.(e))});await this.queue.getIdlePromise(),Bt.clear()}async initGenerateTest({filePath:e,testable:t,outputType:n,abortSignal:r,userPrompt:i}){let{methodName:a,parentName:o}=Zr(t);try{if(r?.aborted)return;let s=Math.round(process.memoryUsage().heapUsed/1024/1024);Xn.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([[Qn[Zn.NOT_ENOUGH_BALANCE_ERROR],Zn.NOT_ENOUGH_BALANCE_ERROR]]);if(e instanceof $n&&t.has(e.message)){let n=t.get(e.message);throw Xn.safeTrackEvent(`GenerateTestsError`,{errorCode:n}),e}}}}};(0,Im.default)([Vt,(0,Pm.default)(`design:type`,Function),(0,Pm.default)(`design:paramtypes`,[Array,Object,String,typeof(Hm=h.Fn!==void 0&&h.Fn)==`function`?Hm:Object]),(0,Pm.default)(`design:returntype`,Promise)],Um.prototype,`bulkGenerateTests`,null),(0,Im.default)([Ge({category:_t.GENERATE_TESTS}),(0,Pm.default)(`design:type`,Function),(0,Pm.default)(`design:paramtypes`,[Object]),(0,Pm.default)(`design:returntype`,Promise)],Um.prototype,`initGenerateTest`,null),Um=(0,Im.default)([(0,_.injectable)(),(0,Fm.default)(0,(0,_.inject)(Nm)),(0,Fm.default)(1,(0,_.inject)(cd)),(0,Fm.default)(2,(0,_.inject)(Pe)),(0,Fm.default)(3,(0,_.inject)(Zu)),(0,Fm.default)(4,(0,_.inject)(Vr)),(0,Fm.default)(5,(0,_.inject)(cu)),(0,Pm.default)(`design:paramtypes`,[typeof(Lm=Nm!==void 0&&Nm)==`function`?Lm:Object,typeof(Rm=cd!==void 0&&cd)==`function`?Rm:Object,Object,typeof(zm=Zu!==void 0&&Zu)==`function`?zm:Object,typeof(Bm=Vr!==void 0&&Vr)==`function`?Bm:Object,typeof(Vm=cu!==void 0&&cu)==`function`?Vm:Object])],Um);var Wm=l(Oe()),Gm=l(hr()),Km=l(ke()),qm;let Jm=class{constructor(e){this.globalConfigService=e}async getFileTestables(e){try{let t=new Ke(e);return await t.isFileExists()?[e,new G(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 Mn(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 Ke(e);return await t.isFileExists()?new G(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=tt(t),a=ji.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}};Jm=(0,Km.default)([(0,_.injectable)(),(0,Gm.default)(0,(0,_.inject)(Pe)),(0,Wm.default)(`design:paramtypes`,[typeof(qm=Pe!==void 0&&Pe)==`function`?qm:Object])],Jm);var Ym=l(Oe()),Xm=l(hr()),Zm=l(ke()),Qm;let $m=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),{}}}};$m=(0,Zm.default)([(0,_.injectable)(),(0,Xm.default)(0,(0,_.inject)(Jm)),(0,Ym.default)(`design:paramtypes`,[typeof(Qm=Jm!==void 0&&Jm)==`function`?Qm:Object])],$m);var eh=l(Oe()),th=l(hr()),nh=l(ke()),rh,ih,ah,oh,sh,ch,lh,uh,dh,fh;let ph=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,nh.default)([Ge({category:_t.INITIALIZATION}),(0,eh.default)(`design:type`,Function),(0,eh.default)(`design:paramtypes`,[String]),(0,eh.default)(`design:returntype`,Promise)],ph.prototype,`init`,null),(0,nh.default)([Ge({category:_t.GET_TESTABLES}),(0,eh.default)(`design:type`,Function),(0,eh.default)(`design:paramtypes`,[String]),(0,eh.default)(`design:returntype`,Promise)],ph.prototype,`getTestables`,null),(0,nh.default)([Ge({category:_t.GET_TESTABLES}),(0,eh.default)(`design:type`,Function),(0,eh.default)(`design:paramtypes`,[String]),(0,eh.default)(`design:returntype`,Promise)],ph.prototype,`getAllMethodsCount`,null),(0,nh.default)([Ge({category:_t.GET_TESTABLES}),(0,eh.default)(`design:type`,Function),(0,eh.default)(`design:paramtypes`,[Object]),(0,eh.default)(`design:returntype`,Promise)],ph.prototype,`resolveEarlyTestFile`,null),(0,nh.default)([Ge({category:_t.GET_TESTABLES}),(0,eh.default)(`design:type`,Function),(0,eh.default)(`design:paramtypes`,[Array]),(0,eh.default)(`design:returntype`,Promise)],ph.prototype,`getTestableFileMap`,null),(0,nh.default)([Ge({category:_t.GENERATE_COVERAGE}),(0,eh.default)(`design:type`,Function),(0,eh.default)(`design:paramtypes`,[]),(0,eh.default)(`design:returntype`,Promise)],ph.prototype,`generateCoverage`,null),(0,nh.default)([Ge({category:_t.SET_COVERAGE}),(0,eh.default)(`design:type`,Function),(0,eh.default)(`design:paramtypes`,[Object]),(0,eh.default)(`design:returntype`,Promise)],ph.prototype,`setCoverage`,null),(0,nh.default)([Ge({category:_t.GET_COVERAGE}),(0,eh.default)(`design:type`,Function),(0,eh.default)(`design:paramtypes`,[]),(0,eh.default)(`design:returntype`,Promise)],ph.prototype,`getCoverageTree`,null),(0,nh.default)([Ge({category:_t.GET_COVERAGE}),(0,eh.default)(`design:type`,Function),(0,eh.default)(`design:paramtypes`,[Array]),(0,eh.default)(`design:returntype`,Promise)],ph.prototype,`getCoverageForFiles`,null),(0,nh.default)([Ge({category:_t.GENERATE_TESTS}),(0,eh.default)(`design:type`,Function),(0,eh.default)(`design:paramtypes`,[String,Object]),(0,eh.default)(`design:returntype`,Promise)],ph.prototype,`generateTests`,null),(0,nh.default)([Ge({category:_t.GENERATE_TESTS}),(0,eh.default)(`design:type`,Function),(0,eh.default)(`design:paramtypes`,[Array,Object,String,typeof(fh=h.Fn!==void 0&&h.Fn)==`function`?fh:Object]),(0,eh.default)(`design:returntype`,Promise)],ph.prototype,`bulkGenerateTests`,null),(0,nh.default)([Ge({category:_t.GENERATE_TESTS}),(0,eh.default)(`design:type`,Function),(0,eh.default)(`design:paramtypes`,[String,String]),(0,eh.default)(`design:returntype`,Promise)],ph.prototype,`getValidationReport`,null),(0,nh.default)([Ge({category:_t.GET_TESTED_CODE_DATA_SOURCE}),(0,eh.default)(`design:type`,Function),(0,eh.default)(`design:paramtypes`,[String,Object,String]),(0,eh.default)(`design:returntype`,Promise)],ph.prototype,`getTestedCodeDataSource`,null),(0,nh.default)([Ge({category:_t.DYNAMIC_PROMPT}),(0,eh.default)(`design:type`,Function),(0,eh.default)(`design:paramtypes`,[String,Object,String]),(0,eh.default)(`design:returntype`,Promise)],ph.prototype,`runDynamicPrompt`,null),(0,nh.default)([Ge({category:_t.TEST_VALIDATION}),(0,eh.default)(`design:type`,Function),(0,eh.default)(`design:paramtypes`,[String,String]),(0,eh.default)(`design:returntype`,Promise)],ph.prototype,`validateTestsByCode`,null),ph=(0,nh.default)([(0,_.injectable)(),(0,th.default)(0,(0,_.inject)($m)),(0,th.default)(1,(0,_.inject)(Yn)),(0,th.default)(2,(0,_.inject)(Um)),(0,th.default)(3,(0,_.inject)(cc)),(0,th.default)(4,(0,_.inject)(Pe)),(0,th.default)(5,(0,_.inject)(Wu)),(0,th.default)(6,(0,_.inject)(dm)),(0,th.default)(7,(0,_.inject)(cd)),(0,th.default)(8,(0,_.inject)(Du)),(0,eh.default)(`design:paramtypes`,[typeof(rh=$m!==void 0&&$m)==`function`?rh:Object,typeof(ih=Yn!==void 0&&Yn)==`function`?ih:Object,typeof(ah=Um!==void 0&&Um)==`function`?ah:Object,typeof(oh=cc!==void 0&&cc)==`function`?oh:Object,typeof(sh=Pe!==void 0&&Pe)==`function`?sh:Object,typeof(ch=Wu!==void 0&&Wu)==`function`?ch:Object,typeof(lh=dm!==void 0&&dm)==`function`?lh:Object,typeof(uh=cd!==void 0&&cd)==`function`?uh:Object,typeof(dh=Du!==void 0&&Du)==`function`?dh:Object])],ph),e.AST=G,e.AccessModifierType=St,e.AstModuleInfo=Cn,e.CONCURRENCY=ve,e.COVERAGE_THRESHOLD=_e,e.CalculateCoverageOption=ge,e.DEFAULT_TYPE_KIND=wt,e.ExportType=xt,e.GenerateTestsOutputType=he,e.GeneratedTestStructure=me,e.LibraryName=Ct,e.RequestSource=le,Object.defineProperty(e,`TSAgent`,{enumerable:!0,get:function(){return ph}}),e.TestFileName=pe,e.TestFramework=de,e.TestStructureVariant=ue,e.TestSuffix=fe,e.WithTsMorphManager=Vt,e.createTSAgent=(e={})=>(Fe.bind(Pe).toDynamicValue(()=>new Pe(e)).inSingletonScope(),Fe.get(ph)),e.findLintConfigPath=gt,e.getUnitTests=tn,e.tsMorphManager=Bt}))();const EU={TSAgent:Symbol.for(`TSAgent`),CliOptions:Symbol.for(`CliOptions`),SCMHostService:Symbol.for(`SCMHostService`)};var DU=u(Si());let OU=function(e){return e.PR=`generate-for-pr`,e.COMMIT=`generate-for-commit`,e.PROJECT=`generate-for-project`,e.COVERAGE=`generate-coverage`,e}({});const kU=Object.freeze({status:`aborted`});function AU(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 jU=class extends Error{constructor(){super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`)}},MU=class extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`),this.name=`ZodEncodeError`}};const NU={};function PU(e){return e&&Object.assign(NU,e),NU}function See(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 FU(e,t){return typeof t==`bigint`?t.toString():t}function IU(e){return{get value(){{let t=e();return Object.defineProperty(this,`value`,{value:t}),t}throw Error(`cached value already set`)}}}function LU(e){return e==null}function RU(e){let t=e.startsWith(`^`)?1:0,n=e.endsWith(`$`)?e.length-1:e.length;return e.slice(t,n)}function zU(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 BU=Symbol(`evaluating`);function VU(e,t,n){let r;Object.defineProperty(e,t,{get(){if(r!==BU)return r===void 0&&(r=BU,r=n()),r},set(n){Object.defineProperty(e,t,{value:n})},configurable:!0})}function HU(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}function UU(...e){let t={};for(let n of e){let e=Object.getOwnPropertyDescriptors(n);Object.assign(t,e)}return Object.defineProperties({},t)}function WU(e){return JSON.stringify(e)}const GU=`captureStackTrace`in Error?Error.captureStackTrace:(...e)=>{};function KU(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}const qU=IU(()=>{if(typeof navigator<`u`&&navigator?.userAgent?.includes(`Cloudflare`))return!1;try{return Function(``),!0}catch{return!1}});function JU(e){if(KU(e)===!1)return!1;let t=e.constructor;if(t===void 0)return!0;let n=t.prototype;return!(KU(n)===!1||Object.prototype.hasOwnProperty.call(n,`isPrototypeOf`)===!1)}function YU(e){return JU(e)?{...e}:Array.isArray(e)?[...e]:e}const XU=new Set([`string`,`number`,`symbol`]);function ZU(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}function QU(e,t,n){let r=new e._zod.constr(t??e._zod.def);return(!t||n?.parent)&&(r._zod.parent=e),r}function $U(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 eW(e){return Object.keys(e).filter(t=>e[t]._zod.optin===`optional`&&e[t]._zod.optout===`optional`)}const tW={safeint:[-(2**53-1),2**53-1],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]};function nW(e,t){let n=e._zod.def;return QU(e,UU(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 HU(this,`shape`,e),e},checks:[]}))}function rW(e,t){let n=e._zod.def;return QU(e,UU(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 HU(this,`shape`,r),r},checks:[]}))}function iW(e,t){if(!JU(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 QU(e,UU(e._zod.def,{get shape(){let n={...e._zod.def.shape,...t};return HU(this,`shape`,n),n},checks:[]}))}function aW(e,t){if(!JU(t))throw Error(`Invalid input to safeExtend: expected a plain object`);return QU(e,{...e._zod.def,get shape(){let n={...e._zod.def.shape,...t};return HU(this,`shape`,n),n},checks:e._zod.def.checks})}function oW(e,t){return QU(e,UU(e._zod.def,{get shape(){let n={...e._zod.def.shape,...t._zod.def.shape};return HU(this,`shape`,n),n},get catchall(){return t._zod.def.catchall},checks:[]}))}function sW(e,t,n){return QU(t,UU(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 HU(this,`shape`,i),i},checks:[]}))}function cW(e,t,n){return QU(t,UU(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 HU(this,`shape`,i),i},checks:[]}))}function lW(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 uW(e,t){return t.map(t=>{var n;return(n=t).path??(n.path=[]),t.path.unshift(e),t})}function dW(e){return typeof e==`string`?e:e?.message}function fW(e,t,n){let r={...e,path:e.path??[]};return e.message||(r.message=dW(e.inst?._zod.def?.error?.(e))??dW(t?.error?.(e))??dW(n.customError?.(e))??dW(n.localeError?.(e))??`Invalid input`),delete r.inst,delete r.continue,t?.reportInput||delete r.input,r}function pW(e){return Array.isArray(e)?`array`:typeof e==`string`?`string`:`unknown`}function mW(...e){let[t,n,r]=e;return typeof t==`string`?{message:t,code:`custom`,input:n,inst:r}:{...t}}const hW=(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,FU,2),Object.defineProperty(e,`toString`,{value:()=>e.message,enumerable:!1})},gW=AU(`$ZodError`,hW),_W=AU(`$ZodError`,hW,{Parent:Error});function Cee(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 vW(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 yW=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 jU;if(o.issues.length){let t=new(i?.Err??e)(o.issues.map(e=>fW(e,a,PU())));throw GU(t,i?.callee),t}return o.value},bW=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=>fW(e,a,PU())));throw GU(t,i?.callee),t}return o.value},xW=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 jU;return a.issues.length?{success:!1,error:new(e??gW)(a.issues.map(e=>fW(e,i,PU())))}:{success:!0,data:a.value}},SW=xW(_W),CW=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=>fW(e,i,PU())))}:{success:!0,data:a.value}},wW=CW(_W),TW=e=>(t,n,r)=>{let i=r?Object.assign(r,{direction:`backward`}):{direction:`backward`};return yW(e)(t,n,i)},EW=e=>(t,n,r)=>yW(e)(t,n,r),DW=e=>async(t,n,r)=>{let i=r?Object.assign(r,{direction:`backward`}):{direction:`backward`};return bW(e)(t,n,i)},OW=e=>async(t,n,r)=>bW(e)(t,n,r),kW=e=>(t,n,r)=>{let i=r?Object.assign(r,{direction:`backward`}):{direction:`backward`};return xW(e)(t,n,i)},AW=e=>(t,n,r)=>xW(e)(t,n,r),jW=e=>async(t,n,r)=>{let i=r?Object.assign(r,{direction:`backward`}):{direction:`backward`};return CW(e)(t,n,i)},MW=e=>async(t,n,r)=>CW(e)(t,n,r),NW=/^[cC][^\s-]{8,}$/,PW=/^[0-9a-z]+$/,FW=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,IW=/^[0-9a-vA-V]{20}$/,wee=/^[A-Za-z0-9]{27}$/,Tee=/^[a-zA-Z0-9_-]{21}$/,LW=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,RW=/^([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})$/,zW=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)$/,BW=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;function VW(){return RegExp(`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`,`u`)}const HW=/^(?:(?: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])$/,UW=/^(([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}|:))$/,WW=/^((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])$/,GW=/^(([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])$/,Eee=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,KW=/^[A-Za-z0-9_-]*$/,qW=/^(?=.{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])?)*\.?$/,Dee=/^\+(?:[0-9]){6,14}[0-9]$/,JW=`(?:(?:\\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])))`,YW=RegExp(`^${JW}$`);function XW(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 ZW(e){return RegExp(`^${XW(e)}$`)}function QW(e){let t=XW({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(`^${JW}T(?:${r})$`)}const $W=e=>{let t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??``}}`:`[\\s\\S]*`;return RegExp(`^${t}$`)},eG=/^-?\d+$/,tG=/^-?\d+(?:\.\d+)?/,nG=/^[^A-Z]*$/,rG=/^[^a-z]*$/,iG=AU(`$ZodCheck`,(e,t)=>{var n;e._zod??={},e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),aG={number:`number`,bigint:`bigint`,object:`date`},oG=AU(`$ZodCheckLessThan`,(e,t)=>{iG.init(e,t);let n=aG[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})}}),sG=AU(`$ZodCheckGreaterThan`,(e,t)=>{iG.init(e,t);let n=aG[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})}}),cG=AU(`$ZodCheckMultipleOf`,(e,t)=>{iG.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):zU(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})}}),lG=AU(`$ZodCheckNumberFormat`,(e,t)=>{iG.init(e,t),t.format=t.format||`float64`;let n=t.format?.includes(`int`),r=n?`int`:`number`,[i,a]=tW[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=eG)}),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})}}),uG=AU(`$ZodCheckMaxLength`,(e,t)=>{var n;iG.init(e,t),(n=e._zod.def).when??(n.when=e=>{let t=e.value;return!LU(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=pW(r);n.issues.push({origin:i,code:`too_big`,maximum:t.maximum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),dG=AU(`$ZodCheckMinLength`,(e,t)=>{var n;iG.init(e,t),(n=e._zod.def).when??(n.when=e=>{let t=e.value;return!LU(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=pW(r);n.issues.push({origin:i,code:`too_small`,minimum:t.minimum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),fG=AU(`$ZodCheckLengthEquals`,(e,t)=>{var n;iG.init(e,t),(n=e._zod.def).when??(n.when=e=>{let t=e.value;return!LU(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=pW(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})}}),pG=AU(`$ZodCheckStringFormat`,(e,t)=>{var n,r;iG.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=()=>{})}),mG=AU(`$ZodCheckRegex`,(e,t)=>{pG.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})}}),hG=AU(`$ZodCheckLowerCase`,(e,t)=>{t.pattern??=nG,pG.init(e,t)}),gG=AU(`$ZodCheckUpperCase`,(e,t)=>{t.pattern??=rG,pG.init(e,t)}),_G=AU(`$ZodCheckIncludes`,(e,t)=>{iG.init(e,t);let n=ZU(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})}}),vG=AU(`$ZodCheckStartsWith`,(e,t)=>{iG.init(e,t);let n=RegExp(`^${ZU(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})}}),yG=AU(`$ZodCheckEndsWith`,(e,t)=>{iG.init(e,t);let n=RegExp(`.*${ZU(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})}}),bG=AU(`$ZodCheckOverwrite`,(e,t)=>{iG.init(e,t),e._zod.check=e=>{e.value=t.tx(e.value)}});var xG=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(`
|
|
32355
|
+
Start the workflow now with Phase 0 (read the provided project commands), then proceed with the given target file/function.`)||e.systemPrompt,a=await this.agentSdkRunner.run({userPrompt:e.prompt,workingDirectory:r,testFilePath:t,systemPrompt:i,abortSignal:n});return{code:a.code,prompt:e.prompt,requestId:e.requestId,validationSummary:a.validationSummary}}};Cm=(0,bm.default)([(0,_.injectable)(),(0,ym.default)(0,(0,_.inject)(xr)),(0,ym.default)(1,(0,_.inject)(Pe)),(0,ym.default)(2,(0,_.inject)(Gp)),(0,vm.default)(`design:paramtypes`,[typeof(xm=xr!==void 0&&xr)==`function`?xm:Object,Object,typeof(Sm=Gp!==void 0&&Gp)==`function`?Sm:Object])],Cm);var wm=l(Oe()),Tm=l(hr()),Em=l(ke()),Dm,Om,km,Am,jm,Mm;let Nm=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}=Zr(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 Bt.init(e);let u=rt(e),d=await this.getEarlyTestFile(e,c,u,n),p=d.getFilePath(),m=null;Bt.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(),u,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 $n(Zn.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 Hf){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 $n(Zn.EMPTY_TEST,{methodName:c});let E=performance.now();if(r?.aborted??!1)return s(a);Bt.add(p,C),await new la(this.importSolverService,e,p,t,u).refine({shouldResolveMockPaths:!0,shouldSolveImports:!0});let D=Bt.get(p).getFullText();if((0,h.isEmpty)(D))throw await v({responseProcessingTime:performance.now()-E,gitUrl:this.globalConfigService.getGitURL()}),new $n(Zn.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 Bt.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 Bt.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 $n||e instanceof Hf)throw e;let n=e instanceof Error?e.message:`Failed making API call`;throw new $n(Zn.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;try{return await this.testGeneratorProvider.generate(e,t,n,r,i)}catch(e){if(H.info.defaultLog(`GenerateTestService failed to generate tests`,e instanceof Error?e.message:e),e instanceof $n||e instanceof Hf)throw e;let t=e instanceof Error?e.message:`Failed making API call`;throw new $n(Zn.GENERATING_TESTS_REQUEST_ERROR,{methodName:a,errorMessage:t})}}async getEarlyTestFile(e,t,n,r){if(r===he.OVERRIDE_CODE_FILE){let n=await ji.getLatestTestFile(e,t);if((0,h.isDefined)(n))return new ji(tt(n))}return await ji.getNextTestFile(e,t,n)}};(0,Em.default)([Vt,(0,wm.default)(`design:type`,Function),(0,wm.default)(`design:paramtypes`,[Object]),(0,wm.default)(`design:returntype`,Promise)],Nm.prototype,`initGenerateTestFlow`,null),Nm=(0,Em.default)([(0,_.injectable)(),(0,Tm.default)(0,(0,_.inject)(Vr)),(0,Tm.default)(1,(0,_.inject)(Oa)),(0,Tm.default)(2,(0,_.inject)(_m)),(0,Tm.default)(3,(0,_.inject)(Pe)),(0,Tm.default)(4,(0,_.inject)(li)),(0,Tm.default)(5,(0,_.inject)(cu)),(0,Tm.default)(6,(0,_.inject)(Cm)),(0,wm.default)(`design:paramtypes`,[typeof(Dm=Vr!==void 0&&Vr)==`function`?Dm:Object,typeof(Om=Oa!==void 0&&Oa)==`function`?Om:Object,typeof(km=_m!==void 0&&_m)==`function`?km:Object,Object,typeof(Am=li!==void 0&&li)==`function`?Am:Object,typeof(jm=cu!==void 0&&cu)==`function`?jm:Object,typeof(Mm=Cm!==void 0&&Cm)==`function`?Mm:Object])],Nm);var Pm=l(Oe()),Fm=l(hr()),Im=l(ke()),Lm,Rm,zm,Bm,Vm,Hm;let Um=class{shouldTriggerRefreshCoverage=!1;queue;coverageService=new Kn;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 Hr({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=`**/.${Jr}*`,t=await(0,k.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}=Zr(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 Ht(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 Bt.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=``}=Zr(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 $n&&(H.default.info(``),H.default.warn(`‼️ ${e.message}`),this.queue.clearQueued(),r?.(e))});await this.queue.getIdlePromise(),Bt.clear()}async initGenerateTest({filePath:e,testable:t,outputType:n,abortSignal:r,userPrompt:i}){let{methodName:a,parentName:o}=Zr(t);try{if(r?.aborted)return;let s=Math.round(process.memoryUsage().heapUsed/1024/1024);Xn.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([[Qn[Zn.NOT_ENOUGH_BALANCE_ERROR],Zn.NOT_ENOUGH_BALANCE_ERROR]]);if(e instanceof $n&&t.has(e.message)){let n=t.get(e.message);throw Xn.safeTrackEvent(`GenerateTestsError`,{errorCode:n}),e}}}}};(0,Im.default)([Vt,(0,Pm.default)(`design:type`,Function),(0,Pm.default)(`design:paramtypes`,[Array,Object,String,typeof(Hm=h.Fn!==void 0&&h.Fn)==`function`?Hm:Object]),(0,Pm.default)(`design:returntype`,Promise)],Um.prototype,`bulkGenerateTests`,null),(0,Im.default)([Ge({category:_t.GENERATE_TESTS}),(0,Pm.default)(`design:type`,Function),(0,Pm.default)(`design:paramtypes`,[Object]),(0,Pm.default)(`design:returntype`,Promise)],Um.prototype,`initGenerateTest`,null),Um=(0,Im.default)([(0,_.injectable)(),(0,Fm.default)(0,(0,_.inject)(Nm)),(0,Fm.default)(1,(0,_.inject)(cd)),(0,Fm.default)(2,(0,_.inject)(Pe)),(0,Fm.default)(3,(0,_.inject)(Zu)),(0,Fm.default)(4,(0,_.inject)(Vr)),(0,Fm.default)(5,(0,_.inject)(cu)),(0,Pm.default)(`design:paramtypes`,[typeof(Lm=Nm!==void 0&&Nm)==`function`?Lm:Object,typeof(Rm=cd!==void 0&&cd)==`function`?Rm:Object,Object,typeof(zm=Zu!==void 0&&Zu)==`function`?zm:Object,typeof(Bm=Vr!==void 0&&Vr)==`function`?Bm:Object,typeof(Vm=cu!==void 0&&cu)==`function`?Vm:Object])],Um);var Wm=l(Oe()),Gm=l(hr()),Km=l(ke()),qm;let Jm=class{constructor(e){this.globalConfigService=e}async getFileTestables(e){try{let t=new Ke(e);return await t.isFileExists()?[e,new G(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 Mn(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 Ke(e);return await t.isFileExists()?new G(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=tt(t),a=ji.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}};Jm=(0,Km.default)([(0,_.injectable)(),(0,Gm.default)(0,(0,_.inject)(Pe)),(0,Wm.default)(`design:paramtypes`,[typeof(qm=Pe!==void 0&&Pe)==`function`?qm:Object])],Jm);var Ym=l(Oe()),Xm=l(hr()),Zm=l(ke()),Qm;let $m=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),{}}}};$m=(0,Zm.default)([(0,_.injectable)(),(0,Xm.default)(0,(0,_.inject)(Jm)),(0,Ym.default)(`design:paramtypes`,[typeof(Qm=Jm!==void 0&&Jm)==`function`?Qm:Object])],$m);var eh=l(Oe()),th=l(hr()),nh=l(ke()),rh,ih,ah,oh,sh,ch,lh,uh,dh,fh;let ph=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,nh.default)([Ge({category:_t.INITIALIZATION}),(0,eh.default)(`design:type`,Function),(0,eh.default)(`design:paramtypes`,[String]),(0,eh.default)(`design:returntype`,Promise)],ph.prototype,`init`,null),(0,nh.default)([Ge({category:_t.GET_TESTABLES}),(0,eh.default)(`design:type`,Function),(0,eh.default)(`design:paramtypes`,[String]),(0,eh.default)(`design:returntype`,Promise)],ph.prototype,`getTestables`,null),(0,nh.default)([Ge({category:_t.GET_TESTABLES}),(0,eh.default)(`design:type`,Function),(0,eh.default)(`design:paramtypes`,[String]),(0,eh.default)(`design:returntype`,Promise)],ph.prototype,`getAllMethodsCount`,null),(0,nh.default)([Ge({category:_t.GET_TESTABLES}),(0,eh.default)(`design:type`,Function),(0,eh.default)(`design:paramtypes`,[Object]),(0,eh.default)(`design:returntype`,Promise)],ph.prototype,`resolveEarlyTestFile`,null),(0,nh.default)([Ge({category:_t.GET_TESTABLES}),(0,eh.default)(`design:type`,Function),(0,eh.default)(`design:paramtypes`,[Array]),(0,eh.default)(`design:returntype`,Promise)],ph.prototype,`getTestableFileMap`,null),(0,nh.default)([Ge({category:_t.GENERATE_COVERAGE}),(0,eh.default)(`design:type`,Function),(0,eh.default)(`design:paramtypes`,[]),(0,eh.default)(`design:returntype`,Promise)],ph.prototype,`generateCoverage`,null),(0,nh.default)([Ge({category:_t.SET_COVERAGE}),(0,eh.default)(`design:type`,Function),(0,eh.default)(`design:paramtypes`,[Object]),(0,eh.default)(`design:returntype`,Promise)],ph.prototype,`setCoverage`,null),(0,nh.default)([Ge({category:_t.GET_COVERAGE}),(0,eh.default)(`design:type`,Function),(0,eh.default)(`design:paramtypes`,[]),(0,eh.default)(`design:returntype`,Promise)],ph.prototype,`getCoverageTree`,null),(0,nh.default)([Ge({category:_t.GET_COVERAGE}),(0,eh.default)(`design:type`,Function),(0,eh.default)(`design:paramtypes`,[Array]),(0,eh.default)(`design:returntype`,Promise)],ph.prototype,`getCoverageForFiles`,null),(0,nh.default)([Ge({category:_t.GENERATE_TESTS}),(0,eh.default)(`design:type`,Function),(0,eh.default)(`design:paramtypes`,[String,Object]),(0,eh.default)(`design:returntype`,Promise)],ph.prototype,`generateTests`,null),(0,nh.default)([Ge({category:_t.GENERATE_TESTS}),(0,eh.default)(`design:type`,Function),(0,eh.default)(`design:paramtypes`,[Array,Object,String,typeof(fh=h.Fn!==void 0&&h.Fn)==`function`?fh:Object]),(0,eh.default)(`design:returntype`,Promise)],ph.prototype,`bulkGenerateTests`,null),(0,nh.default)([Ge({category:_t.GENERATE_TESTS}),(0,eh.default)(`design:type`,Function),(0,eh.default)(`design:paramtypes`,[String,String]),(0,eh.default)(`design:returntype`,Promise)],ph.prototype,`getValidationReport`,null),(0,nh.default)([Ge({category:_t.GET_TESTED_CODE_DATA_SOURCE}),(0,eh.default)(`design:type`,Function),(0,eh.default)(`design:paramtypes`,[String,Object,String]),(0,eh.default)(`design:returntype`,Promise)],ph.prototype,`getTestedCodeDataSource`,null),(0,nh.default)([Ge({category:_t.DYNAMIC_PROMPT}),(0,eh.default)(`design:type`,Function),(0,eh.default)(`design:paramtypes`,[String,Object,String]),(0,eh.default)(`design:returntype`,Promise)],ph.prototype,`runDynamicPrompt`,null),(0,nh.default)([Ge({category:_t.TEST_VALIDATION}),(0,eh.default)(`design:type`,Function),(0,eh.default)(`design:paramtypes`,[String,String]),(0,eh.default)(`design:returntype`,Promise)],ph.prototype,`validateTestsByCode`,null),ph=(0,nh.default)([(0,_.injectable)(),(0,th.default)(0,(0,_.inject)($m)),(0,th.default)(1,(0,_.inject)(Yn)),(0,th.default)(2,(0,_.inject)(Um)),(0,th.default)(3,(0,_.inject)(cc)),(0,th.default)(4,(0,_.inject)(Pe)),(0,th.default)(5,(0,_.inject)(Wu)),(0,th.default)(6,(0,_.inject)(dm)),(0,th.default)(7,(0,_.inject)(cd)),(0,th.default)(8,(0,_.inject)(Du)),(0,eh.default)(`design:paramtypes`,[typeof(rh=$m!==void 0&&$m)==`function`?rh:Object,typeof(ih=Yn!==void 0&&Yn)==`function`?ih:Object,typeof(ah=Um!==void 0&&Um)==`function`?ah:Object,typeof(oh=cc!==void 0&&cc)==`function`?oh:Object,typeof(sh=Pe!==void 0&&Pe)==`function`?sh:Object,typeof(ch=Wu!==void 0&&Wu)==`function`?ch:Object,typeof(lh=dm!==void 0&&dm)==`function`?lh:Object,typeof(uh=cd!==void 0&&cd)==`function`?uh:Object,typeof(dh=Du!==void 0&&Du)==`function`?dh:Object])],ph),e.AST=G,e.AccessModifierType=St,e.AstModuleInfo=Cn,e.CONCURRENCY=ve,e.COVERAGE_THRESHOLD=_e,e.CalculateCoverageOption=ge,e.DEFAULT_TYPE_KIND=wt,e.ExportType=xt,e.GenerateTestsOutputType=he,e.GeneratedTestStructure=me,e.LibraryName=Ct,e.RequestSource=le,Object.defineProperty(e,`TSAgent`,{enumerable:!0,get:function(){return ph}}),e.TestFileName=pe,e.TestFramework=de,e.TestStructureVariant=ue,e.TestSuffix=fe,e.WithTsMorphManager=Vt,e.createTSAgent=(e={})=>(Fe.bind(Pe).toDynamicValue(()=>new Pe(e)).inSingletonScope(),Fe.get(ph)),e.findLintConfigPath=gt,e.getUnitTests=tn,e.tsMorphManager=Bt}))();const EU={TSAgent:Symbol.for(`TSAgent`),CliOptions:Symbol.for(`CliOptions`),SCMHostService:Symbol.for(`SCMHostService`)};var DU=u(Si());let OU=function(e){return e.PR=`generate-for-pr`,e.COMMIT=`generate-for-commit`,e.PROJECT=`generate-for-project`,e.COVERAGE=`generate-coverage`,e}({});const kU=Object.freeze({status:`aborted`});function AU(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 jU=class extends Error{constructor(){super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`)}},MU=class extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`),this.name=`ZodEncodeError`}};const NU={};function PU(e){return e&&Object.assign(NU,e),NU}function See(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 FU(e,t){return typeof t==`bigint`?t.toString():t}function IU(e){return{get value(){{let t=e();return Object.defineProperty(this,`value`,{value:t}),t}throw Error(`cached value already set`)}}}function LU(e){return e==null}function RU(e){let t=e.startsWith(`^`)?1:0,n=e.endsWith(`$`)?e.length-1:e.length;return e.slice(t,n)}function zU(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 BU=Symbol(`evaluating`);function VU(e,t,n){let r;Object.defineProperty(e,t,{get(){if(r!==BU)return r===void 0&&(r=BU,r=n()),r},set(n){Object.defineProperty(e,t,{value:n})},configurable:!0})}function HU(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}function UU(...e){let t={};for(let n of e){let e=Object.getOwnPropertyDescriptors(n);Object.assign(t,e)}return Object.defineProperties({},t)}function WU(e){return JSON.stringify(e)}const GU=`captureStackTrace`in Error?Error.captureStackTrace:(...e)=>{};function KU(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}const qU=IU(()=>{if(typeof navigator<`u`&&navigator?.userAgent?.includes(`Cloudflare`))return!1;try{return Function(``),!0}catch{return!1}});function JU(e){if(KU(e)===!1)return!1;let t=e.constructor;if(t===void 0)return!0;let n=t.prototype;return!(KU(n)===!1||Object.prototype.hasOwnProperty.call(n,`isPrototypeOf`)===!1)}function YU(e){return JU(e)?{...e}:Array.isArray(e)?[...e]:e}const XU=new Set([`string`,`number`,`symbol`]);function ZU(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}function QU(e,t,n){let r=new e._zod.constr(t??e._zod.def);return(!t||n?.parent)&&(r._zod.parent=e),r}function $U(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 eW(e){return Object.keys(e).filter(t=>e[t]._zod.optin===`optional`&&e[t]._zod.optout===`optional`)}const tW={safeint:[-(2**53-1),2**53-1],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]};function nW(e,t){let n=e._zod.def;return QU(e,UU(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 HU(this,`shape`,e),e},checks:[]}))}function rW(e,t){let n=e._zod.def;return QU(e,UU(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 HU(this,`shape`,r),r},checks:[]}))}function iW(e,t){if(!JU(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 QU(e,UU(e._zod.def,{get shape(){let n={...e._zod.def.shape,...t};return HU(this,`shape`,n),n},checks:[]}))}function aW(e,t){if(!JU(t))throw Error(`Invalid input to safeExtend: expected a plain object`);return QU(e,{...e._zod.def,get shape(){let n={...e._zod.def.shape,...t};return HU(this,`shape`,n),n},checks:e._zod.def.checks})}function oW(e,t){return QU(e,UU(e._zod.def,{get shape(){let n={...e._zod.def.shape,...t._zod.def.shape};return HU(this,`shape`,n),n},get catchall(){return t._zod.def.catchall},checks:[]}))}function sW(e,t,n){return QU(t,UU(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 HU(this,`shape`,i),i},checks:[]}))}function cW(e,t,n){return QU(t,UU(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 HU(this,`shape`,i),i},checks:[]}))}function lW(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 uW(e,t){return t.map(t=>{var n;return(n=t).path??(n.path=[]),t.path.unshift(e),t})}function dW(e){return typeof e==`string`?e:e?.message}function fW(e,t,n){let r={...e,path:e.path??[]};return e.message||(r.message=dW(e.inst?._zod.def?.error?.(e))??dW(t?.error?.(e))??dW(n.customError?.(e))??dW(n.localeError?.(e))??`Invalid input`),delete r.inst,delete r.continue,t?.reportInput||delete r.input,r}function pW(e){return Array.isArray(e)?`array`:typeof e==`string`?`string`:`unknown`}function mW(...e){let[t,n,r]=e;return typeof t==`string`?{message:t,code:`custom`,input:n,inst:r}:{...t}}const hW=(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,FU,2),Object.defineProperty(e,`toString`,{value:()=>e.message,enumerable:!1})},gW=AU(`$ZodError`,hW),_W=AU(`$ZodError`,hW,{Parent:Error});function Cee(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 vW(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 yW=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 jU;if(o.issues.length){let t=new(i?.Err??e)(o.issues.map(e=>fW(e,a,PU())));throw GU(t,i?.callee),t}return o.value},bW=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=>fW(e,a,PU())));throw GU(t,i?.callee),t}return o.value},xW=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 jU;return a.issues.length?{success:!1,error:new(e??gW)(a.issues.map(e=>fW(e,i,PU())))}:{success:!0,data:a.value}},SW=xW(_W),CW=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=>fW(e,i,PU())))}:{success:!0,data:a.value}},wW=CW(_W),TW=e=>(t,n,r)=>{let i=r?Object.assign(r,{direction:`backward`}):{direction:`backward`};return yW(e)(t,n,i)},EW=e=>(t,n,r)=>yW(e)(t,n,r),DW=e=>async(t,n,r)=>{let i=r?Object.assign(r,{direction:`backward`}):{direction:`backward`};return bW(e)(t,n,i)},OW=e=>async(t,n,r)=>bW(e)(t,n,r),kW=e=>(t,n,r)=>{let i=r?Object.assign(r,{direction:`backward`}):{direction:`backward`};return xW(e)(t,n,i)},AW=e=>(t,n,r)=>xW(e)(t,n,r),jW=e=>async(t,n,r)=>{let i=r?Object.assign(r,{direction:`backward`}):{direction:`backward`};return CW(e)(t,n,i)},MW=e=>async(t,n,r)=>CW(e)(t,n,r),NW=/^[cC][^\s-]{8,}$/,PW=/^[0-9a-z]+$/,FW=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,IW=/^[0-9a-vA-V]{20}$/,wee=/^[A-Za-z0-9]{27}$/,Tee=/^[a-zA-Z0-9_-]{21}$/,LW=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,RW=/^([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})$/,zW=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)$/,BW=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;function VW(){return RegExp(`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`,`u`)}const HW=/^(?:(?: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])$/,UW=/^(([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}|:))$/,WW=/^((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])$/,GW=/^(([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])$/,Eee=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,KW=/^[A-Za-z0-9_-]*$/,qW=/^(?=.{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])?)*\.?$/,Dee=/^\+(?:[0-9]){6,14}[0-9]$/,JW=`(?:(?:\\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])))`,YW=RegExp(`^${JW}$`);function XW(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 ZW(e){return RegExp(`^${XW(e)}$`)}function QW(e){let t=XW({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(`^${JW}T(?:${r})$`)}const $W=e=>{let t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??``}}`:`[\\s\\S]*`;return RegExp(`^${t}$`)},eG=/^-?\d+$/,tG=/^-?\d+(?:\.\d+)?/,nG=/^[^A-Z]*$/,rG=/^[^a-z]*$/,iG=AU(`$ZodCheck`,(e,t)=>{var n;e._zod??={},e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),aG={number:`number`,bigint:`bigint`,object:`date`},oG=AU(`$ZodCheckLessThan`,(e,t)=>{iG.init(e,t);let n=aG[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})}}),sG=AU(`$ZodCheckGreaterThan`,(e,t)=>{iG.init(e,t);let n=aG[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})}}),cG=AU(`$ZodCheckMultipleOf`,(e,t)=>{iG.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):zU(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})}}),lG=AU(`$ZodCheckNumberFormat`,(e,t)=>{iG.init(e,t),t.format=t.format||`float64`;let n=t.format?.includes(`int`),r=n?`int`:`number`,[i,a]=tW[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=eG)}),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})}}),uG=AU(`$ZodCheckMaxLength`,(e,t)=>{var n;iG.init(e,t),(n=e._zod.def).when??(n.when=e=>{let t=e.value;return!LU(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=pW(r);n.issues.push({origin:i,code:`too_big`,maximum:t.maximum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),dG=AU(`$ZodCheckMinLength`,(e,t)=>{var n;iG.init(e,t),(n=e._zod.def).when??(n.when=e=>{let t=e.value;return!LU(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=pW(r);n.issues.push({origin:i,code:`too_small`,minimum:t.minimum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),fG=AU(`$ZodCheckLengthEquals`,(e,t)=>{var n;iG.init(e,t),(n=e._zod.def).when??(n.when=e=>{let t=e.value;return!LU(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=pW(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})}}),pG=AU(`$ZodCheckStringFormat`,(e,t)=>{var n,r;iG.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=()=>{})}),mG=AU(`$ZodCheckRegex`,(e,t)=>{pG.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})}}),hG=AU(`$ZodCheckLowerCase`,(e,t)=>{t.pattern??=nG,pG.init(e,t)}),gG=AU(`$ZodCheckUpperCase`,(e,t)=>{t.pattern??=rG,pG.init(e,t)}),_G=AU(`$ZodCheckIncludes`,(e,t)=>{iG.init(e,t);let n=ZU(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})}}),vG=AU(`$ZodCheckStartsWith`,(e,t)=>{iG.init(e,t);let n=RegExp(`^${ZU(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})}}),yG=AU(`$ZodCheckEndsWith`,(e,t)=>{iG.init(e,t);let n=RegExp(`.*${ZU(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})}}),bG=AU(`$ZodCheckOverwrite`,(e,t)=>{iG.init(e,t),e._zod.check=e=>{e.value=t.tx(e.value)}});var xG=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(`
|
|
32356
32356
|
`).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(`
|
|
32357
32357
|
`))}};const SG={major:4,minor:1,patch:11},CG=AU(`$ZodType`,(e,t)=>{var n;e??={},e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=SG;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=lW(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 jU;if(i||o instanceof Promise)i=(i??Promise.resolve()).then(async()=>{await o,e.issues.length!==t&&(r||=lW(e,t))});else{if(e.issues.length===t)continue;r||=lW(e,t)}}return i?i.then(()=>e):e},n=(n,i,a)=>{if(lW(n))return n.aborted=!0,n;let o=t(i,r,a);if(o instanceof Promise){if(a.async===!1)throw new jU;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 jU;return o.then(e=>t(e,r,a))}return t(o,r,a)}}e[`~standard`]={validate:t=>{try{let n=SW(e,t);return n.success?{value:n.data}:{issues:n.error?.issues}}catch{return wW(e,t).then(e=>e.success?{value:e.data}:{issues:e.error?.issues})}},vendor:`zod`,version:1}}),wG=AU(`$ZodString`,(e,t)=>{CG.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??$W(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}}),TG=AU(`$ZodStringFormat`,(e,t)=>{pG.init(e,t),wG.init(e,t)}),EG=AU(`$ZodGUID`,(e,t)=>{t.pattern??=RW,TG.init(e,t)}),DG=AU(`$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??=zW(e)}else t.pattern??=zW();TG.init(e,t)}),OG=AU(`$ZodEmail`,(e,t)=>{t.pattern??=BW,TG.init(e,t)}),kG=AU(`$ZodURL`,(e,t)=>{TG.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:qW.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})}}}),AG=AU(`$ZodEmoji`,(e,t)=>{t.pattern??=VW(),TG.init(e,t)}),jG=AU(`$ZodNanoID`,(e,t)=>{t.pattern??=Tee,TG.init(e,t)}),MG=AU(`$ZodCUID`,(e,t)=>{t.pattern??=NW,TG.init(e,t)}),Oee=AU(`$ZodCUID2`,(e,t)=>{t.pattern??=PW,TG.init(e,t)}),NG=AU(`$ZodULID`,(e,t)=>{t.pattern??=FW,TG.init(e,t)}),PG=AU(`$ZodXID`,(e,t)=>{t.pattern??=IW,TG.init(e,t)}),FG=AU(`$ZodKSUID`,(e,t)=>{t.pattern??=wee,TG.init(e,t)}),kee=AU(`$ZodISODateTime`,(e,t)=>{t.pattern??=QW(t),TG.init(e,t)}),Aee=AU(`$ZodISODate`,(e,t)=>{t.pattern??=YW,TG.init(e,t)}),IG=AU(`$ZodISOTime`,(e,t)=>{t.pattern??=ZW(t),TG.init(e,t)}),LG=AU(`$ZodISODuration`,(e,t)=>{t.pattern??=LW,TG.init(e,t)}),RG=AU(`$ZodIPv4`,(e,t)=>{t.pattern??=HW,TG.init(e,t),e._zod.onattach.push(e=>{let t=e._zod.bag;t.format=`ipv4`})}),jee=AU(`$ZodIPv6`,(e,t)=>{t.pattern??=UW,TG.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})}}}),Mee=AU(`$ZodCIDRv4`,(e,t)=>{t.pattern??=WW,TG.init(e,t)}),zG=AU(`$ZodCIDRv6`,(e,t)=>{t.pattern??=GW,TG.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 BG(e){if(e===``)return!0;if(e.length%4!=0)return!1;try{return atob(e),!0}catch{return!1}}const VG=AU(`$ZodBase64`,(e,t)=>{t.pattern??=Eee,TG.init(e,t),e._zod.onattach.push(e=>{e._zod.bag.contentEncoding=`base64`}),e._zod.check=n=>{BG(n.value)||n.issues.push({code:`invalid_format`,format:`base64`,input:n.value,inst:e,continue:!t.abort})}});function Nee(e){if(!KW.test(e))return!1;let t=e.replace(/[-_]/g,e=>e===`-`?`+`:`/`);return BG(t.padEnd(Math.ceil(t.length/4)*4,`=`))}const HG=AU(`$ZodBase64URL`,(e,t)=>{t.pattern??=KW,TG.init(e,t),e._zod.onattach.push(e=>{e._zod.bag.contentEncoding=`base64url`}),e._zod.check=n=>{Nee(n.value)||n.issues.push({code:`invalid_format`,format:`base64url`,input:n.value,inst:e,continue:!t.abort})}}),UG=AU(`$ZodE164`,(e,t)=>{t.pattern??=Dee,TG.init(e,t)});function WG(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 GG=AU(`$ZodJWT`,(e,t)=>{TG.init(e,t),e._zod.check=n=>{WG(n.value,t.alg)||n.issues.push({code:`invalid_format`,format:`jwt`,input:n.value,inst:e,continue:!t.abort})}}),KG=AU(`$ZodNumber`,(e,t)=>{CG.init(e,t),e._zod.pattern=e._zod.bag.pattern??tG,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}}),qG=AU(`$ZodNumber`,(e,t)=>{lG.init(e,t),KG.init(e,t)}),JG=AU(`$ZodUnknown`,(e,t)=>{CG.init(e,t),e._zod.parse=e=>e}),YG=AU(`$ZodNever`,(e,t)=>{CG.init(e,t),e._zod.parse=(t,n)=>(t.issues.push({expected:`never`,code:`invalid_type`,input:t.value,inst:e}),t)});function XG(e,t,n){e.issues.length&&t.issues.push(...uW(n,e.issues)),t.value[n]=e.value}const ZG=AU(`$ZodArray`,(e,t)=>{CG.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=>XG(t,n,e))):XG(s,n,e)}return a.length?Promise.all(a).then(()=>n):n}});function QG(e,t,n,r){e.issues.length&&t.issues.push(...uW(n,e.issues)),e.value===void 0?n in r&&(t.value[n]=void 0):t.value[n]=e.value}function $G(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=eW(e.shape);return{...e,keys:t,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(n)}}function eK(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=>QG(e,n,i,t))):QG(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 tK=AU(`$ZodObject`,(e,t)=>{if(CG.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=IU(()=>$G(t));VU(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=KU,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=>QG(n,t,e,s))):QG(n,t,e,s)}return i?eK(c,s,t,o,n.value,e):c.length?Promise.all(c).then(()=>t):t}}),nK=AU(`$ZodObjectJIT`,(e,t)=>{tK.init(e,t);let n=e._zod.parse,r=IU(()=>$G(t)),i=e=>{let t=new xG([`shape`,`payload`,`ctx`]),n=r.value,i=e=>{let t=WU(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=WU(e);t.write(`const ${n} = ${i(e)};`),t.write(`
|
|
32358
32358
|
if (${n}.issues.length) {
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@earlyai/cli",
|
|
3
|
-
"version": "2.2.
|
|
3
|
+
"version": "2.2.1",
|
|
4
4
|
"description": "early cli",
|
|
5
5
|
"main": "dist/index.cjs",
|
|
6
6
|
"bin": {
|
|
@@ -55,7 +55,7 @@
|
|
|
55
55
|
},
|
|
56
56
|
"devDependencies": {
|
|
57
57
|
"@earlyai/core": "^1.5.0",
|
|
58
|
-
"@earlyai/ts-agent": "^0.
|
|
58
|
+
"@earlyai/ts-agent": "^0.72.0",
|
|
59
59
|
"@eslint/compat": "^1.3.2",
|
|
60
60
|
"@eslint/eslintrc": "^3.3.1",
|
|
61
61
|
"@eslint/js": "^9.34.0",
|