@earlyai/cli 2.8.0 → 2.8.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.
Files changed (2) hide show
  1. package/dist/index.cjs +3 -3
  2. package/package.json +1 -1
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:j,createCommand:te,createArgument:M,createOption:ne,CommanderError:N,InvalidArgumentError:P,InvalidOptionArgumentError:F,Command:I,Argument:re,Option:L,Help:R}=u(s((e=>{let{Argument:t}=D(),{Command:n}=ee(),{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 ie=`2.8.0`,ae=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})),z=ae();function oe(e,t,n,{key:r=``,prefix:i=`EARLY`,parser:a,def:o,isRequired:s=!1,envName:c}={}){let l=new L(t,n);a&&l.argParser(a),s&&l.makeOptionMandatory(!0);let u=c??(()=>{let n=[];for(let t=e;t&&(0,z.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,z.isDefined)(o)&&l.default(o),e.addOption(l),l}function se(e){return(typeof e==`object`&&!!e||typeof e==`function`)&&typeof e.then==`function`}function B(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:j,createCommand:te,createArgument:M,createOption:ne,CommanderError:N,InvalidArgumentError:P,InvalidOptionArgumentError:F,Command:I,Argument:re,Option:L,Help:R}=u(s((e=>{let{Argument:t}=D(),{Command:n}=ee(),{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 ie=`2.8.1`,ae=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})),z=ae();function oe(e,t,n,{key:r=``,prefix:i=`EARLY`,parser:a,def:o,isRequired:s=!1,envName:c}={}){let l=new L(t,n);a&&l.argParser(a),s&&l.makeOptionMandatory(!0);let u=c??(()=>{let n=[];for(let t=e;t&&(0,z.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,z.isDefined)(o)&&l.default(o),e.addOption(l),l}function se(e){return(typeof e==`object`&&!!e||typeof e==`function`)&&typeof e.then==`function`}function B(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 Ge(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 Ke(e,t){return(n,r,i)=>{try{i===void 0?function(e,t){let n=qe(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=qe(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=qe(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){Ge(n,r,i,e)}}}function qe(e,t){return n=>{let r=t(n);return t=>(r(t),e(t))}}function Je(e){return Ke(V(je.singleInjection,e),Be)}(function(e){e[e.method=0]=`method`,e[e.parameter=1]=`parameter`,e[e.property=2]=`property`})(We||={});const Ye=`@inversifyjs/core/classIsInjectableFlagReflectKey`,Xe=[Array,BigInt,Boolean,Function,Number,Object,String];function Ze(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,Xe.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 Qe(e){return t=>{(function(e){if(ue(e,Ye)!==void 0)throw new Ee(De.injectionDecoratorConflict,`Cannot apply @injectable decorator multiple times at class "${e.name}"`);de(e,Ye,!0)})(t),Ze(t),e!==void 0&&fe(t,Se,Ce,t=>({...t,scope:e}))}}function $e(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 et(e,t,n){return e?new Set([...t,...n]):n}function tt(e,t,n){let r=e.lifecycle?.extendPostConstructMethods??!0,i=et(e.lifecycle?.extendPreDestroyMethods??!0,t.lifecycle.preDestroyMethodNames,n.lifecycle.preDestroyMethodNames);return{postConstructMethodNames:et(r,t.lifecycle.postConstructMethodNames,n.lifecycle.postConstructMethodNames),preDestroyMethodNames:i}}function nt(e,t,n){let r;return r=e.extendProperties??!0?new Map(ve(t.properties,n.properties)):n.properties,r}function rt(e){return t=>{fe(t,Se,Ce,function(e,t){return n=>({constructorArguments:$e(e,t,n),lifecycle:tt(e,t,n),properties:nt(e,t,n),scope:n.scope})}(e,Me(e.type)))}}function it(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.`);rt({...e,type:n})(t)}}function at(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)rt({...e,type:r})(t)}}function ot(e){return t=>{t===void 0&&fe(e,we,ze,e=>e+1)}}function st(e){return t=>{let n=t??{kind:Oe.unknown,name:void 0,optional:!1,tags:new Map};if(n.kind===je.unmanaged)throw new Ee(De.injectionDecoratorConflict,`Unexpected injection found. Found @unmanaged injection with additional @named, @optional, @tagged or @targetName injections`);return e(n)}}function ct(e){if(e.optional)throw new Ee(De.injectionDecoratorConflict,`Unexpected duplicated optional decorator`);return e.optional=!0,e}function H(){return Ke(st(ct),ot)}var lt;function ut(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 dt(e,t){if(ut(t)){let n=function(e){let t=[...e];return t.length===0?`(No dependency trace)`:t.map(B).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`})(lt||={});const ft=Symbol.for(`@inversifyjs/core/LazyPlanServiceNode`);var pt=class{[ft];_serviceIdentifier;_serviceNode;constructor(e,t){this[ft]=!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[ft]}invalidate(){this._serviceNode=void 0}isExpanded(){return this._serviceNode!==void 0}_getNode(){return this._serviceNode===void 0&&(this._serviceNode=this._buildPlanServiceNode()),this._serviceNode}},mt=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 ht(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 gt=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 _t(e){let t=new Map;return e.rootConstraints.tag!==void 0&&t.set(e.rootConstraints.tag.key,e.rootConstraints.tag.value),new gt({elem:{getAncestorsCalled:!1,name:e.rootConstraints.name,serviceIdentifier:e.rootConstraints.serviceIdentifier,tags:t},previous:void 0})}function vt(e){return e.redirections!==void 0}function yt(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: "${B(a[a.length-1]??n)}".${Ct(a)}\n\nRegistered bindings:\n\n${e.map(e=>function(e){switch(e.type){case _e.Instance:return`[ type: "${e.type}", serviceIdentifier: "${B(e.serviceIdentifier)}", scope: "${e.scope}", implementationType: "${e.implementationType.name}" ]`;case _e.ServiceRedirection:return`[ type: "${e.type}", serviceIdentifier: "${B(e.serviceIdentifier)}", redirection: "${B(e.targetServiceIdentifier)}" ]`;default:return`[ type: "${e.type}", serviceIdentifier: "${B(e.serviceIdentifier)}", scope: "${e.scope}" ]`}}(e.binding)).join(`
23
23
  `)}\n\nTrying to resolve bindings for "${xt(n,r)}".${St(i)}`;throw new Ee(De.planning,t)}t||bt(n,r,i,a)}(e,t,i,a,n.elem,r):function(e,t,n,r,i,a){e!==void 0||t||bt(n,r,i,a)}(e,t,i,a,n.elem,r)}function bt(e,t,n,r){let i=`No bindings found for service: "${B(r[r.length-1]??e)}".\n\nTrying to resolve bindings for "${xt(e,t)}".${Ct(r)}${St(n)}`;throw new Ee(De.planning,i)}function xt(e,t){return t===void 0?`${B(e)} (Root service)`:B(t)}function St(e){let t=e.tags.size===0?``:`\n- tags:\n - ${[...e.tags.keys()].map(e=>e.toString()).join(`
@@ -32406,7 +32406,7 @@ var n=require(`buffer`),r=n.Buffer;function i(e,t){for(var n in e)t[n]=e[n]}r.fr
32406
32406
  `),stack:e&&e.stack,exception:!0,date:new Date().toString(),process:this.getProcessInfo(),os:this.getOsInfo(),trace:this.getTrace(e)}}getProcessInfo(){return{pid:process.pid,uid:process.getuid?process.getuid():null,gid:process.getgid?process.getgid():null,cwd:process.cwd(),execPath:process.execPath,version:process.version,argv:process.argv,memoryUsage:process.memoryUsage()}}getOsInfo(){return{loadavg:n.loadavg(),uptime:n.uptime()}}getTrace(e){return(e?o.parse(e):o.get()).map(e=>({column:e.getColumnNumber(),file:e.getFileName(),function:e.getFunctionName(),line:e.getLineNumber(),method:e.getMethodName(),native:e.isNative()}))}_addHandler(e){if(!this.handlers.has(e)){e.handleExceptions=!0;let t=new s(e);this.handlers.set(e,t),this.logger.pipe(t)}}_uncaughtException(e){let t=this.getAllInfo(e),n=this._getExceptionHandlers(),o=typeof this.logger.exitOnError==`function`?this.logger.exitOnError(e):this.logger.exitOnError,s;!n.length&&o&&(console.warn(`winston: exitOnError cannot be true with no exception handlers.`),console.warn(`winston: not exiting process.`),o=!1);function c(){i(`doExit`,o),i(`process._exiting`,process._exiting),o&&!process._exiting&&(s&&clearTimeout(s),process.exit(1))}if(!n||n.length===0)return process.nextTick(c);r(n,(e,t)=>{let n=a(t),r=e.transport||e;function o(e){return()=>{i(e),n()}}r._ending=!0,r.once(`finish`,o(`finished`)),r.once(`error`,o(`error`))},()=>o&&c()),this.logger.log(t),o&&(s=setTimeout(c,3e3))}_getExceptionHandlers(){return this.logger.transports.filter(e=>(e.transport||e).handleExceptions)}}})),oZ=s(((e,t)=>{let{Writable:n}=WX();t.exports=class extends n{constructor(e){if(super({objectMode:!0}),!e)throw Error(`RejectionStream requires a TransportStream instance.`);this.handleRejections=!0,this.transport=e}_write(e,t,n){return e.rejection?this.transport.log(e,n):(n(),!0)}}})),sZ=s(((e,t)=>{let n=require(`os`),r=eZ(),i=GX()(`winston:rejection`),a=nZ(),o=rZ(),s=oZ();t.exports=class{constructor(e){if(!e)throw Error(`Logger is required to handle rejections`);this.logger=e,this.handlers=new Map}handle(...e){e.forEach(e=>{if(Array.isArray(e))return e.forEach(e=>this._addHandler(e));this._addHandler(e)}),this.catcher||(this.catcher=this._unhandledRejection.bind(this),process.on(`unhandledRejection`,this.catcher))}unhandle(){this.catcher&&(process.removeListener(`unhandledRejection`,this.catcher),this.catcher=!1,Array.from(this.handlers.values()).forEach(e=>this.logger.unpipe(e)))}getAllInfo(e){let t=null;return e&&(t=typeof e==`string`?e:e.message),{error:e,level:`error`,message:[`unhandledRejection: ${t||`(no error message)`}`,e&&e.stack||` No stack trace`].join(`
32407
32407
  `),stack:e&&e.stack,rejection:!0,date:new Date().toString(),process:this.getProcessInfo(),os:this.getOsInfo(),trace:this.getTrace(e)}}getProcessInfo(){return{pid:process.pid,uid:process.getuid?process.getuid():null,gid:process.getgid?process.getgid():null,cwd:process.cwd(),execPath:process.execPath,version:process.version,argv:process.argv,memoryUsage:process.memoryUsage()}}getOsInfo(){return{loadavg:n.loadavg(),uptime:n.uptime()}}getTrace(e){return(e?o.parse(e):o.get()).map(e=>({column:e.getColumnNumber(),file:e.getFileName(),function:e.getFunctionName(),line:e.getLineNumber(),method:e.getMethodName(),native:e.isNative()}))}_addHandler(e){if(!this.handlers.has(e)){e.handleRejections=!0;let t=new s(e);this.handlers.set(e,t),this.logger.pipe(t)}}_unhandledRejection(e){let t=this.getAllInfo(e),n=this._getRejectionHandlers(),o=typeof this.logger.exitOnError==`function`?this.logger.exitOnError(e):this.logger.exitOnError,s;!n.length&&o&&(console.warn(`winston: exitOnError cannot be true with no rejection handlers.`),console.warn(`winston: not exiting process.`),o=!1);function c(){i(`doExit`,o),i(`process._exiting`,process._exiting),o&&!process._exiting&&(s&&clearTimeout(s),process.exit(1))}if(!n||n.length===0)return process.nextTick(c);r(n,(e,t)=>{let n=a(t),r=e.transport||e;function o(e){return()=>{i(e),n()}}r._ending=!0,r.once(`finish`,o(`finished`)),r.once(`error`,o(`error`))},()=>o&&c()),this.logger.log(t),o&&(s=setTimeout(c,3e3))}_getRejectionHandlers(){return this.logger.transports.filter(e=>(e.transport||e).handleRejections)}}})),cZ=s(((e,t)=>{t.exports=class{constructor(e){let t=lZ();if(typeof e!=`object`||Array.isArray(e)||!(e instanceof t))throw Error(`Logger is required for profiling`);this.logger=e,this.start=Date.now()}done(...e){typeof e[e.length-1]==`function`&&(console.warn(`Callback function no longer supported as of winston@3.0.0`),e.pop());let t=typeof e[e.length-1]==`object`?e.pop():{};return t.level=t.level||`info`,t.durationMs=Date.now()-this.start,this.logger.write(t)}}})),lZ=s(((e,t)=>{let{Stream:n,Transform:r}=WX(),i=eZ(),{LEVEL:a,SPLAT:o}=wY(),s=YX(),c=aZ(),l=sZ(),u=uX(),d=cZ(),{warn:f}=KY(),p=ZX(),m=/%[scdjifoO%]/g;var h=class extends r{constructor(e){super({objectMode:!0}),this.configure(e)}child(e){let t=this;return Object.create(t,{write:{value:function(n){let r=Object.assign({},e,n);n instanceof Error&&(r.stack=n.stack,r.message=n.message,r.cause=n.cause),t.write(r)}}})}configure({silent:e,format:t,defaultMeta:n,levels:r,level:i=`info`,exitOnError:a=!0,transports:o,colors:s,emitErrs:u,formatters:d,padLevels:f,rewriters:m,stripColors:h,exceptionHandlers:g,rejectionHandlers:_}={}){if(this.transports.length&&this.clear(),this.silent=e,this.format=t||this.format||NY()(),this.defaultMeta=n||null,this.levels=r||this.levels||p.npm.levels,this.level=i,this.exceptions&&this.exceptions.unhandle(),this.rejections&&this.rejections.unhandle(),this.exceptions=new c(this),this.rejections=new l(this),this.profilers={},this.exitOnError=a,o&&(o=Array.isArray(o)?o:[o],o.forEach(e=>this.add(e))),s||u||d||f||m||h)throw Error([`{ colors, emitErrs, formatters, padLevels, rewriters, stripColors } were removed in winston@3.0.0.`,`Use a custom winston.format(function) instead.`,`See: https://github.com/winstonjs/winston/tree/master/UPGRADE-3.0.md`].join(`
32408
32408
  `));g&&this.exceptions.handle(g),_&&this.rejections.handle(_)}getHighestLogLevel(){let e=g(this.levels,this.level);return!this.transports||this.transports.length===0?e:this.transports.reduce((e,t)=>{let n=g(this.levels,t.level);return n!==null&&n>e?n:e},e)}isLevelEnabled(e){let t=g(this.levels,e);if(t===null)return!1;let n=g(this.levels,this.level);return n===null?!1:!this.transports||this.transports.length===0?n>=t:this.transports.findIndex(e=>{let r=g(this.levels,e.level);return r===null&&(r=n),r>=t})!==-1}log(e,t,...n){if(arguments.length===1)return e[a]=e.level,this._addDefaultMeta(e),this.write(e),this;if(arguments.length===2)return t&&typeof t==`object`?(t[a]=t.level=e,this._addDefaultMeta(t),this.write(t),this):(t={[a]:e,level:e,message:t},this._addDefaultMeta(t),this.write(t),this);let[r]=n;if(typeof r==`object`&&r&&!(t&&t.match&&t.match(m))){let i=Object.assign({},this.defaultMeta,r,{[a]:e,[o]:n,level:e,message:t});return r.message&&(i.message=`${i.message} ${r.message}`),r.stack&&(i.stack=r.stack),r.cause&&(i.cause=r.cause),this.write(i),this}return this.write(Object.assign({},this.defaultMeta,{[a]:e,[o]:n,level:e,message:t})),this}_transform(e,t,n){if(this.silent)return n();e[a]||(e[a]=e.level),!this.levels[e[a]]&&this.levels[e[a]]!==0&&console.error(`[winston] Unknown logger level: %s`,e[a]),this._readableState.pipes||console.error(`[winston] Attempt to write logs with no transports, which can increase memory usage: %j`,e);try{this.push(this.format.transform(e,this.format.options))}finally{this._writableState.sync=!1,n()}}_final(e){i(this.transports.slice(),(e,t)=>{if(!e||e.finished)return setImmediate(t);e.once(`finish`,t),e.end()},e)}add(e){let t=!s(e)||e.log.length>2?new u({transport:e}):e;if(!t._writableState||!t._writableState.objectMode)throw Error(`Transports must WritableStreams in objectMode. Set { objectMode: true }.`);return this._onEvent(`error`,t),this._onEvent(`warn`,t),this.pipe(t),e.handleExceptions&&this.exceptions.handle(),e.handleRejections&&this.rejections.handle(),this}remove(e){if(!e)return this;let t=e;return(!s(e)||e.log.length>2)&&(t=this.transports.filter(t=>t.transport===e)[0]),t&&this.unpipe(t),this}clear(){return this.unpipe(),this}close(){return this.exceptions.unhandle(),this.rejections.unhandle(),this.clear(),this.emit(`close`),this}setLevels(){f.deprecated(`setLevels`)}query(e,t){typeof e==`function`&&(t=e,e={}),e||={};let n={},r=Object.assign({},e.query||{});function a(t,n){e.query&&typeof t.formatQuery==`function`&&(e.query=t.formatQuery(r)),t.query(e,(r,i)=>{if(r)return n(r);typeof t.formatResults==`function`&&(i=t.formatResults(i,e.format)),n(null,i)})}function o(e,t){a(e,(r,i)=>{t&&(i=r||i,i&&(n[e.name]=i),t()),t=null})}i(this.transports.filter(e=>!!e.query),o,()=>t(null,n))}stream(e={}){let t=new n,r=[];return t._streams=r,t.destroy=()=>{let e=r.length;for(;e--;)r[e].destroy()},this.transports.filter(e=>!!e.stream).forEach(n=>{let i=n.stream(e);i&&(r.push(i),i.on(`log`,e=>{e.transport=e.transport||[],e.transport.push(n.name),t.emit(`log`,e)}),i.on(`error`,e=>{e.transport=e.transport||[],e.transport.push(n.name),t.emit(`error`,e)}))}),t}startTimer(){return new d(this)}profile(e,...t){let n=Date.now();if(this.profilers[e]){let r=this.profilers[e];delete this.profilers[e],typeof t[t.length-2]==`function`&&(console.warn(`Callback function no longer supported as of winston@3.0.0`),t.pop());let i=typeof t[t.length-1]==`object`?t.pop():{};return i.level=i.level||`info`,i.durationMs=n-r,i.message=i.message||e,this.write(i)}return this.profilers[e]=n,this}handleExceptions(...e){console.warn(`Deprecated: .handleExceptions() will be removed in winston@4. Use .exceptions.handle()`),this.exceptions.handle(...e)}unhandleExceptions(...e){console.warn(`Deprecated: .unhandleExceptions() will be removed in winston@4. Use .exceptions.unhandle()`),this.exceptions.unhandle(...e)}cli(){throw Error([`Logger.cli() was removed in winston@3.0.0`,`Use a custom winston.formats.cli() instead.`,`See: https://github.com/winstonjs/winston/tree/master/UPGRADE-3.0.md`].join(`
32409
- `))}_onEvent(e,t){function n(n){e===`error`&&!this.transports.includes(t)&&this.add(t),this.emit(e,n,t)}t[`__winston`+e]||(t[`__winston`+e]=n.bind(this),t.on(e,t[`__winston`+e]))}_addDefaultMeta(e){this.defaultMeta&&Object.assign(e,this.defaultMeta)}};function g(e,t){let n=e[t];return!n&&n!==0?null:n}Object.defineProperty(h.prototype,`transports`,{configurable:!1,enumerable:!0,get(){let{pipes:e}=this._readableState;return Array.isArray(e)?e:[e].filter(Boolean)}}),t.exports=h})),uZ=s(((e,t)=>{let{LEVEL:n}=wY(),r=ZX(),i=lZ(),a=GX()(`winston:create-logger`);function o(e){return`is`+e.charAt(0).toUpperCase()+e.slice(1)+`Enabled`}t.exports=function(e={}){e.levels=e.levels||r.npm.levels;class t extends i{constructor(e){super(e)}}let s=new t(e);return Object.keys(e.levels).forEach(function(e){if(a(`Define prototype method for "%s"`,e),e===`log`){console.warn(`Level "log" not defined: conflicts with the method "log". Use a different level name.`);return}t.prototype[e]=function(...t){let r=this||s;if(t.length===1){let[i]=t,a=i&&i.message&&i||{message:i};return a.level=a[n]=e,r._addDefaultMeta(a),r.write(a),this||s}return t.length===0?(r.log(e,``),r):r.log(e,...t)},t.prototype[o(e)]=function(){return(this||s).isLevelEnabled(e)}}),s}})),dZ=s(((e,t)=>{let n=uZ();t.exports=class{constructor(e={}){this.loggers=new Map,this.options=e}add(e,t){if(!this.loggers.has(e)){t=Object.assign({},t||this.options);let r=t.transports||this.options.transports;r?t.transports=Array.isArray(r)?r.slice():[r]:t.transports=[];let i=n(t);i.on(`close`,()=>this._delete(e)),this.loggers.set(e,i)}return this.loggers.get(e)}get(e,t){return this.add(e,t)}has(e){return!!this.loggers.has(e)}close(e){if(e)return this._removeLogger(e);this.loggers.forEach((e,t)=>this._removeLogger(t))}_removeLogger(e){this.loggers.has(e)&&(this.loggers.get(e).close(),this._delete(e))}_delete(e){this.loggers.delete(e)}}})),fZ=u(s((e=>{let t=GY(),{warn:n}=KY();e.version=qY().version,e.transports=Qee(),e.config=ZX(),e.addColors=t.levels,e.format=t.format,e.createLogger=uZ(),e.Logger=lZ(),e.ExceptionHandler=aZ(),e.RejectionHandler=sZ(),e.Container=dZ(),e.Transport=dX(),e.loggers=new e.Container;let r=e.createLogger();Object.keys(e.config.npm.levels).concat([`log`,`query`,`stream`,`add`,`remove`,`clear`,`profile`,`startTimer`,`handleExceptions`,`unhandleExceptions`,`handleRejections`,`unhandleRejections`,`configure`,`child`]).forEach(t=>e[t]=(...e)=>r[t](...e)),Object.defineProperty(e,`level`,{get(){return r.level},set(e){r.level=e}}),Object.defineProperty(e,`exceptions`,{get(){return r.exceptions}}),Object.defineProperty(e,`rejections`,{get(){return r.rejections}}),[`exitOnError`].forEach(t=>{Object.defineProperty(e,t,{get(){return r[t]},set(e){r[t]=e}})}),Object.defineProperty(e,`default`,{get(){return{exceptionHandlers:r.exceptionHandlers,rejectionHandlers:r.rejectionHandlers,transports:r.transports}}}),n.deprecated(e,`setLevels`),n.forFunctions(e,`useFormat`,[`cli`]),n.forProperties(e,`useFormat`,[`padLevels`,`stripColors`]),n.forFunctions(e,`deprecated`,[`addRewriter`,`addFilter`,`clone`,`extend`]),n.forProperties(e,`deprecated`,[`emitErrs`,`levelLength`])}))());let pZ=function(e){return e.ERROR=`error`,e.WARN=`warn`,e.INFO=`info`,e.VERBOSE=`verbose`,e.DEBUG=`debug`,e}({});const mZ=pZ.INFO,hZ=pZ.VERBOSE,gZ=pZ.DEBUG;pZ.ERROR,pZ.WARN,pZ.INFO,pZ.VERBOSE,pZ.DEBUG;function _Z(e,t){if(typeof Reflect==`object`&&typeof Reflect.metadata==`function`)return Reflect.metadata(e,t)}function vZ(e,t){return function(n,r){t(n,r,e)}}function yZ(e,t,n,r){var i=arguments.length,a=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r,o;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)a=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(o=e[s])&&(a=(i<3?o(a):i>3?o(t,n,a):o(t,n))||a);return i>3&&a&&Object.defineProperty(t,n,a),a}function bZ(...e){return e.map(e=>typeof e==`object`&&e?(0,y.inspect)(e,{depth:4,breakLength:80}):String(e)).join(` `)}let xZ=class{logger;isDebugMode;constructor(e){this.isDebugMode=String(e?.debug)===`true`,this.logger=fZ.createLogger({level:this.getLogLevel(e),transports:[new fZ.transports.Console({format:fZ.format.printf(({message:e})=>String(e??``))})]})}error(...e){this.logger.error(bZ(...e))}warn(...e){this.logger.warn(bZ(...e))}info(...e){this.logger.info(bZ(...e))}verbose(...e){this.logger.verbose(bZ(...e))}debug(...e){this.logger.debug(bZ(...e))}getLogLevel(e){return String(e?.debug)===`true`?gZ:String(e?.verbose)===`true`?hZ:mZ}};xZ=yZ([Qe(),vZ(0,Je(CU.CliOptions)),vZ(0,H()),_Z(`design:paramtypes`,[Object])],xZ);let SZ=class{config;constructor(e,t){this.logger=t,this.config=this.initializeConfig(e)}getConfig(){return this.config}maskedConfig(){let e=this.config.gitTopLevel;return this.config.command===TU.PROJECT?{...this.config,secretToken:`xxxx`,token:`xxxx`,...(0,z.isDefined)(e)&&{rootPath:wU.default.relative(e,this.config.rootPath)},...(0,z.isDefined)(this.config.targetDirectory)&&{targetDirectory:wU.default.normalize(this.config.targetDirectory)}}:{...this.config,secretToken:`xxxx`,token:`xxxx`,...(0,z.isDefined)(e)&&{rootPath:wU.default.relative(e,this.config.rootPath)}}}isDev(){return process.env.IS_DEV===`true`}getConfigValue(e){return this.config[e]}updateConfigValue(e,t){this.config[e]=t}getConfigValueOrThrow(e,t){let n=this.config[e];if(!(0,z.isDefined)(n)){let n=t??`Configuration key ${e} is required but not configured`;throw Error(n)}return n}initializeConfig(e){let t=this.getRawConfigFromInputs(e),n=qee.parse(t);return this.capMaxTestables(n),this.logger.verbose(`Configuration validated successfully`),this.logger.debug(`Configuration: ${JSON.stringify(n,null,2)}`),n}capMaxTestables(e){e.command===TU.COVERAGE||e.command===TU.GATHER_STATS||e.maxTestables<=10||(this.logger.warn(`Capping maxTestables from ${e.maxTestables} to 10 (maximum allowed).`),e.maxTestables=10)}getRawConfigFromInputs(e){if(!e)throw Error(`CLI options are required but not provided`);let t={command:e.command,testStructure:e.testStructure,testFramework:e.testFramework,testSuffix:e.testSuffix,testFileName:e.testFileNaming,requestSource:SU.RequestSource.CLI,concurrency:e.maxConcurrency,backendURL:e.baseHost,secretToken:e.apiKey,autoCommit:e.autoCommit,token:e.token,testCommand:e.testCommand,coverageCommand:e.coverageCommand,lintCommand:e.lintCommand,prettierCommand:e.prettierCommand,disableLintRules:e.disableLintRules,refName:e.refName,baseRef:e.baseRef,gitOrg:e.gitOrg,gitRepo:e.gitRepo,gitUserEmail:e.gitUserEmail,gitUserName:e.gitUserName,SCMProvider:e.scmProvider,prNumber:e.prNumber,commitHash:e.commitHash,targetDirectory:e.targetDirectory,frequency:e.frequency,startTime:e.startTime,keepErrorTests:e.keepErrorTests,keepFailedTests:e.keepFailedTests,conditionalKeep:e.conditionalKeep,continueOnTestErrors:e.continueOnTestErrors,changedMethodsOnly:e.changedMethodsOnly,skipCoverageAfter:e.skipCoverageAfter,maxTestables:e.maxTestables,autoCommitSkipCi:e.autoCommitSkipCi,perFunctionTimeout:e.perFunctionTimeout,coverageThreshold:e.coverageThreshold,reuseCoverage:e.reuseCoverage,reuseCoverageMaxRuns:e.reuseCoverageMaxRuns,experimentalAgentSdk:e.experimentalAgentSdk,compressOutput:e.compressOutput,agentSdkModel:e.agentSdkModel,agentSdkBudget:e.agentSdkBudget,verbose:e.verbose,debug:e.debug,backfill:e.backfill,...this.isDev()&&{rootPath:e.rootPath}};return Object.fromEntries(Object.entries(t).filter(([,e])=>!(0,z.isEmpty)(e)))}};SZ=yZ([Qe(`Singleton`),vZ(0,Je(CU.CliOptions)),vZ(1,Je(xZ)),_Z(`design:paramtypes`,[Object,Object])],SZ);let CZ=function(e){return e.Success=`success`,e.Failed=`failed`,e.Skipped=`skipped`,e.NoGeneration=`no_generation`,e}({});var wZ;let TZ=class{constructor(e,t){this.configService=e,this.logger=t}data={warnings:[]};setChangedFilesData(e){this.data.changedFiles=e}setCoverageData(e,t){this.data.coverage={before:e,after:t}}setPRCoverageData(e,t){this.data.prCoverage={before:e,after:t}}setCoverageSkipped(){this.data.coverageSkipped=!0}setCoverageBeforeSkipped(){this.data.coverageBeforeSkipped=!0}setCoverageState(e,t){this.data.coverageState=e,this.data.coverageFailureReason=t}setTestGenerationData(e){this.data.testGeneration=e}setAutoCommitStatus(e){this.data.autoCommit={enabled:e}}addWarning(e){this.data.warnings.push({message:e})}getWorkflowRunOutput(){return{filesCount:this.data.changedFiles?.changedFilesCount??0,codeFileCount:this.data.changedFiles?.candidateFilesCount??0,methodsCount:this.data.changedFiles?.functionCount??0,publicMethodCount:this.data.changedFiles?.publicMethodCount??0,publicMethodBelowCoverageCount:this.data.changedFiles?.testablesToGenerateCount??0,generatedMethodsCount:this.data.testGeneration?.generated??0,successMethodsCount:this.data.testGeneration?.successMethodsCount??0,committedFilesCount:this.data.testGeneration?.committedFilesCount??0,numberOfGreenTests:this.data.testGeneration?.greenTests??0,numberOfRedTests:this.data.testGeneration?.redTests??0,publicMethods:this.data.changedFiles?.publicMethods,changedMethods:this.data.changedFiles?.changedMethods,methodsBelowCoverage:this.data.changedFiles?.methodsBelowCoverage}}generateMarkdownSummary(){let e=[];for(let t of this.data.warnings)e.push(`⚠️ ${t.message}`);if(e.push(``,`🧪 **Early Test Generation Agent**`,``),this.data.changedFiles){let{changedFilesCount:t,candidateFilesCount:n,functionCount:r,testablesToGenerateCount:i}=this.data.changedFiles;e.push(`- Changed files: ${t}`,`- Files with testable code: ${n}`,`- Total methods detected: ${r}`,`- Public methods below coverage threshold: ${i}`)}if(this.data.testGeneration){let{successMethodsCount:t,greenTests:n,redTests:r,skippedMethods:i}=this.data.testGeneration;e.push(`- Generated tests for ${t} methods`,`- Generated ${n} green unit tests`,`- Filtered ${r} red unit tests`,...(0,z.isDefined)(i)&&i>0?[`- Skipped ${i} methods (already tested)`]:[],`**Action Taken**`,``,`✅ Unit tests automatically generated for ${t} public functions below threshold.`)}if((0,z.isDefined)(this.data.autoCommit)&&this.data.autoCommit.enabled&&e.push(`📦 Test files have been auto-committed to this branch.`),(0,z.isDefined)(this.data.coverageState))switch(this.data.coverageState){case CZ.Failed:e.push(``,`**📊 No coverage data**`),(0,z.isDefined)(this.data.coverageFailureReason)&&e.push(`reason: ${this.truncateReason(this.data.coverageFailureReason)}`);break;case CZ.Skipped:e.push(``,`**📊 Coverage skipped**`);break;case CZ.NoGeneration:if((0,z.isDefined)(this.data.prCoverage)){let t=this.data.prCoverage.before.percentage??0,n=this.getCommandLabel();e.push(``,`**📊 ${n} coverage: ${t}% (no changes)**`)}else e.push(``,`**📊 No tests were generated**`);break;case CZ.Success:this.appendCoverageLine(e,this.data.prCoverage);break}else if((0,z.isDefined)(this.data.prCoverage)){let t=this.data.coverageBeforeSkipped??!1,n=this.data.coverageSkipped??!1,r=t?`Skipped`:`${this.data.prCoverage.before.percentage??0}%`,i=n?`Skipped`:`${this.data.prCoverage.after.percentage??0}%`;this.appendCoverageLine(e,void 0,r,i)}return e.push(``,`Early Agent is now guarding your coverage.`,"Early Trace ID: `"+this.configService.getConfigValue(`traceId`)+"`"),e.join(`
32409
+ `))}_onEvent(e,t){function n(n){e===`error`&&!this.transports.includes(t)&&this.add(t),this.emit(e,n,t)}t[`__winston`+e]||(t[`__winston`+e]=n.bind(this),t.on(e,t[`__winston`+e]))}_addDefaultMeta(e){this.defaultMeta&&Object.assign(e,this.defaultMeta)}};function g(e,t){let n=e[t];return!n&&n!==0?null:n}Object.defineProperty(h.prototype,`transports`,{configurable:!1,enumerable:!0,get(){let{pipes:e}=this._readableState;return Array.isArray(e)?e:[e].filter(Boolean)}}),t.exports=h})),uZ=s(((e,t)=>{let{LEVEL:n}=wY(),r=ZX(),i=lZ(),a=GX()(`winston:create-logger`);function o(e){return`is`+e.charAt(0).toUpperCase()+e.slice(1)+`Enabled`}t.exports=function(e={}){e.levels=e.levels||r.npm.levels;class t extends i{constructor(e){super(e)}}let s=new t(e);return Object.keys(e.levels).forEach(function(e){if(a(`Define prototype method for "%s"`,e),e===`log`){console.warn(`Level "log" not defined: conflicts with the method "log". Use a different level name.`);return}t.prototype[e]=function(...t){let r=this||s;if(t.length===1){let[i]=t,a=i&&i.message&&i||{message:i};return a.level=a[n]=e,r._addDefaultMeta(a),r.write(a),this||s}return t.length===0?(r.log(e,``),r):r.log(e,...t)},t.prototype[o(e)]=function(){return(this||s).isLevelEnabled(e)}}),s}})),dZ=s(((e,t)=>{let n=uZ();t.exports=class{constructor(e={}){this.loggers=new Map,this.options=e}add(e,t){if(!this.loggers.has(e)){t=Object.assign({},t||this.options);let r=t.transports||this.options.transports;r?t.transports=Array.isArray(r)?r.slice():[r]:t.transports=[];let i=n(t);i.on(`close`,()=>this._delete(e)),this.loggers.set(e,i)}return this.loggers.get(e)}get(e,t){return this.add(e,t)}has(e){return!!this.loggers.has(e)}close(e){if(e)return this._removeLogger(e);this.loggers.forEach((e,t)=>this._removeLogger(t))}_removeLogger(e){this.loggers.has(e)&&(this.loggers.get(e).close(),this._delete(e))}_delete(e){this.loggers.delete(e)}}})),fZ=u(s((e=>{let t=GY(),{warn:n}=KY();e.version=qY().version,e.transports=Qee(),e.config=ZX(),e.addColors=t.levels,e.format=t.format,e.createLogger=uZ(),e.Logger=lZ(),e.ExceptionHandler=aZ(),e.RejectionHandler=sZ(),e.Container=dZ(),e.Transport=dX(),e.loggers=new e.Container;let r=e.createLogger();Object.keys(e.config.npm.levels).concat([`log`,`query`,`stream`,`add`,`remove`,`clear`,`profile`,`startTimer`,`handleExceptions`,`unhandleExceptions`,`handleRejections`,`unhandleRejections`,`configure`,`child`]).forEach(t=>e[t]=(...e)=>r[t](...e)),Object.defineProperty(e,`level`,{get(){return r.level},set(e){r.level=e}}),Object.defineProperty(e,`exceptions`,{get(){return r.exceptions}}),Object.defineProperty(e,`rejections`,{get(){return r.rejections}}),[`exitOnError`].forEach(t=>{Object.defineProperty(e,t,{get(){return r[t]},set(e){r[t]=e}})}),Object.defineProperty(e,`default`,{get(){return{exceptionHandlers:r.exceptionHandlers,rejectionHandlers:r.rejectionHandlers,transports:r.transports}}}),n.deprecated(e,`setLevels`),n.forFunctions(e,`useFormat`,[`cli`]),n.forProperties(e,`useFormat`,[`padLevels`,`stripColors`]),n.forFunctions(e,`deprecated`,[`addRewriter`,`addFilter`,`clone`,`extend`]),n.forProperties(e,`deprecated`,[`emitErrs`,`levelLength`])}))());let pZ=function(e){return e.ERROR=`error`,e.WARN=`warn`,e.INFO=`info`,e.VERBOSE=`verbose`,e.DEBUG=`debug`,e}({});const mZ=pZ.INFO,hZ=pZ.VERBOSE,gZ=pZ.DEBUG;pZ.ERROR,pZ.WARN,pZ.INFO,pZ.VERBOSE,pZ.DEBUG;function _Z(e,t){if(typeof Reflect==`object`&&typeof Reflect.metadata==`function`)return Reflect.metadata(e,t)}function vZ(e,t){return function(n,r){t(n,r,e)}}function yZ(e,t,n,r){var i=arguments.length,a=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r,o;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)a=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(o=e[s])&&(a=(i<3?o(a):i>3?o(t,n,a):o(t,n))||a);return i>3&&a&&Object.defineProperty(t,n,a),a}function bZ(...e){return e.map(e=>typeof e==`object`&&e?(0,y.inspect)(e,{depth:4,breakLength:80}):String(e)).join(` `)}let xZ=class{logger;isDebugMode;constructor(e){this.isDebugMode=String(e?.debug)===`true`,this.logger=fZ.createLogger({level:this.getLogLevel(e),transports:[new fZ.transports.Console({format:fZ.format.printf(({message:e})=>String(e??``))})]})}error(...e){this.logger.error(bZ(...e))}warn(...e){this.logger.warn(bZ(...e))}info(...e){this.logger.info(bZ(...e))}verbose(...e){this.logger.verbose(bZ(...e))}debug(...e){this.logger.debug(bZ(...e))}getLogLevel(e){return String(e?.debug)===`true`?gZ:String(e?.verbose)===`true`?hZ:mZ}};xZ=yZ([Qe(),vZ(0,Je(CU.CliOptions)),vZ(0,H()),_Z(`design:paramtypes`,[Object])],xZ);let SZ=class{config;constructor(e,t){this.logger=t,this.config=this.initializeConfig(e)}getConfig(){return this.config}maskedConfig(){let e=this.config.gitTopLevel;return this.config.command===TU.PROJECT?{...this.config,secretToken:`xxxx`,token:`xxxx`,...(0,z.isDefined)(e)&&{rootPath:wU.default.relative(e,this.config.rootPath)},...(0,z.isDefined)(this.config.targetDirectory)&&{targetDirectory:wU.default.normalize(this.config.targetDirectory)}}:{...this.config,secretToken:`xxxx`,token:`xxxx`,...(0,z.isDefined)(e)&&{rootPath:wU.default.relative(e,this.config.rootPath)}}}isDev(){return process.env.IS_DEV===`true`}getConfigValue(e){return this.config[e]}updateConfigValue(e,t){this.config[e]=t}getConfigValueOrThrow(e,t){let n=this.config[e];if(!(0,z.isDefined)(n)){let n=t??`Configuration key ${e} is required but not configured`;throw Error(n)}return n}initializeConfig(e){let t=this.getRawConfigFromInputs(e),n=qee.parse(t);return this.capMaxTestables(n),this.logger.verbose(`Configuration validated successfully`),this.logger.debug(`Configuration: ${JSON.stringify(n,null,2)}`),n}capMaxTestables(e){e.command===TU.COVERAGE||e.command===TU.GATHER_STATS||e.maxTestables<=10||(this.logger.warn(`Capping maxTestables from ${e.maxTestables} to 10 (maximum allowed).`),e.maxTestables=10)}getRawConfigFromInputs(e){if(!e)throw Error(`CLI options are required but not provided`);let t={command:e.command,testStructure:e.testStructure,testFramework:e.testFramework,testSuffix:e.testSuffix,testFileName:e.testFileNaming,requestSource:SU.RequestSource.CLI,concurrency:e.maxConcurrency,backendURL:e.baseHost,secretToken:e.apiKey,autoCommit:e.autoCommit,token:e.token,testCommand:e.testCommand,coverageCommand:e.coverageCommand,lintCommand:e.lintCommand,prettierCommand:e.prettierCommand,disableLintRules:e.disableLintRules,refName:e.refName,baseRef:e.baseRef,gitOrg:e.gitOrg,gitRepo:e.gitRepo,gitUserEmail:e.gitUserEmail,gitUserName:e.gitUserName,SCMProvider:e.scmProvider,prNumber:e.prNumber,commitHash:e.commitHash,targetDirectory:e.targetDirectory,frequency:e.frequency,startTime:e.startTime,keepErrorTests:e.keepErrorTests,keepFailedTests:e.keepFailedTests,conditionalKeep:e.conditionalKeep,continueOnTestErrors:e.continueOnTestErrors,changedMethodsOnly:e.changedMethodsOnly,skipCoverageAfter:e.skipCoverageAfter,maxTestables:e.maxTestables,autoCommitSkipCi:e.autoCommitSkipCi,perFunctionTimeout:e.perFunctionTimeout,coverageThreshold:e.coverageThreshold,reuseCoverage:e.reuseCoverage,reuseCoverageMaxRuns:e.reuseCoverageMaxRuns,experimentalAgentSdk:e.experimentalAgentSdk,compressOutput:e.compressOutput,agentSdkModel:e.agentSdkModel,agentSdkBudget:e.agentSdkBudget,verbose:e.verbose,debug:e.debug,backfill:e.backfill,...this.isDev()&&{rootPath:e.rootPath}};return Object.fromEntries(Object.entries(t).filter(([,e])=>!(0,z.isEmpty)(e)))}};SZ=yZ([Qe(`Singleton`),vZ(0,Je(CU.CliOptions)),vZ(1,Je(xZ)),_Z(`design:paramtypes`,[Object,Object])],SZ);let CZ=function(e){return e.Success=`success`,e.Failed=`failed`,e.Skipped=`skipped`,e.NoGeneration=`no_generation`,e}({});var wZ;let TZ=class{constructor(e,t){this.configService=e,this.logger=t}data={warnings:[]};setChangedFilesData(e){this.data.changedFiles=e}setCoverageData(e,t){this.data.coverage={before:e,after:t}}setPRCoverageData(e,t){this.data.prCoverage={before:e,after:t}}setCoverageSkipped(){this.data.coverageSkipped=!0}setCoverageBeforeSkipped(){this.data.coverageBeforeSkipped=!0}setCoverageState(e,t){this.data.coverageState=e,this.data.coverageFailureReason=t}setTestGenerationData(e){this.data.testGeneration=e}setAutoCommitStatus(e){this.data.autoCommit={enabled:e}}addWarning(e){this.data.warnings.push({message:e})}getWorkflowRunOutput(){return{filesCount:this.data.changedFiles?.changedFilesCount??0,codeFileCount:this.data.changedFiles?.candidateFilesCount??0,methodsCount:this.data.changedFiles?.functionCount??0,publicMethodCount:this.data.changedFiles?.publicMethodCount??0,methodsWithTestFileCount:this.data.changedFiles?.methodsWithTestFileCount??0,publicMethodWithoutTestFile:this.data.changedFiles?.publicMethodWithoutTestFile??0,generatedMethodsCount:this.data.testGeneration?.generated??0,successMethodsCount:this.data.testGeneration?.successMethodsCount??0,committedFilesCount:this.data.testGeneration?.committedFilesCount??0,numberOfGreenTests:this.data.testGeneration?.greenTests??0,numberOfRedTests:this.data.testGeneration?.redTests??0,publicMethods:this.data.changedFiles?.publicMethods,changedMethods:this.data.changedFiles?.changedMethods,methodsWithoutTestFile:this.data.changedFiles?.methodsWithoutTestFile}}generateMarkdownSummary(){let e=[];for(let t of this.data.warnings)e.push(`⚠️ ${t.message}`);if(e.push(``,`🧪 **Early Test Generation Agent**`,``),this.data.changedFiles){let{changedFilesCount:t,candidateFilesCount:n,functionCount:r,publicMethodCount:i,methodsWithTestFileCount:a,publicMethodWithoutTestFile:o}=this.data.changedFiles;e.push(`- Changed files: ${t}`,`- Files with testable code: ${n}`,`- Total methods detected: ${r}`,`- Public methods: ${i}`,`- Public methods with existing Early tests: ${a}`,`- Public methods without Early tests: ${o}`)}if(this.data.testGeneration){let{successMethodsCount:t,greenTests:n,redTests:r,skippedMethods:i}=this.data.testGeneration;e.push(`- Generated tests for ${t} methods`,`- Generated ${n} green unit tests`,`- Filtered ${r} red unit tests`,...(0,z.isDefined)(i)&&i>0?[`- Skipped ${i} methods (already tested)`]:[],`**Action Taken**`,``,`✅ Unit tests automatically generated for ${t} public functions without Early tests.`)}if((0,z.isDefined)(this.data.autoCommit)&&this.data.autoCommit.enabled&&e.push(`📦 Test files have been auto-committed to this branch.`),(0,z.isDefined)(this.data.coverageState))switch(this.data.coverageState){case CZ.Failed:e.push(``,`**📊 No coverage data**`),(0,z.isDefined)(this.data.coverageFailureReason)&&e.push(`reason: ${this.truncateReason(this.data.coverageFailureReason)}`);break;case CZ.Skipped:e.push(``,`**📊 Coverage skipped**`);break;case CZ.NoGeneration:if((0,z.isDefined)(this.data.prCoverage)){let t=this.data.prCoverage.before.percentage??0,n=this.getCommandLabel();e.push(``,`**📊 ${n} coverage: ${t}% (no changes)**`)}else e.push(``,`**📊 No tests were generated**`);break;case CZ.Success:this.appendCoverageLine(e,this.data.prCoverage);break}else if((0,z.isDefined)(this.data.prCoverage)){let t=this.data.coverageBeforeSkipped??!1,n=this.data.coverageSkipped??!1,r=t?`Skipped`:`${this.data.prCoverage.before.percentage??0}%`,i=n?`Skipped`:`${this.data.prCoverage.after.percentage??0}%`;this.appendCoverageLine(e,void 0,r,i)}let t=(0,z.isDefined)(this.data.testGeneration)?`Early Agent is now protecting you from regression.`:`Early Agent confirmed you are protected from regression.`;return e.push(``,t,"Early Trace ID: `"+this.configService.getConfigValue(`traceId`)+"`"),e.join(`
32410
32410
  `)}truncateReason(e,t=5){let n=e.split(`
32411
32411
  `),r=n.length>t;return`${(r?n.slice(0,t):n).join(`
32412
32412
  `)}${r?`
@@ -32489,7 +32489,7 @@ var n=require(`buffer`),r=n.Buffer;function i(e,t){for(var n in e)t[n]=e[n]}r.fr
32489
32489
  `,`
32490
32490
  `)!==a.replaceAll(`\r
32491
32491
  `,`
32492
- `)}extractMethodText(e,t){return t.slice(e.startIndex,e.endIndex)}createChangedMethod(e,t,n){return{name:t.name,type:t.type,parentName:`parentName`in t?t.parentName:void 0,changeType:n,filePath:e,canCreateTests:t.canCreateTests}}};i2=yZ([Qe(),vZ(0,Je(xZ)),_Z(`design:paramtypes`,[Object])],i2);var a2,o2,s2;let c2=class{constructor(e,t,n,r){this.gitService=e,this.changedMethodsDetector=t,this.tsAgent=n,this.logger=r}async execute(e,t,n){if(!(0,z.isDefined)(t.baseRevision))return{kept:e};let r=[...new Set(e.map(e=>e.filePath))],i=await this.detectChangedMethods(r,t.baseRevision,t.projectRootPath),a=new Set(i.filter(e=>e.changeType!==`deleted`&&e.canCreateTests).map(e=>`${e.filePath}:${e.name}:${e.parentName??``}`)),o=[],s=[];for(let t of e){let e=`${t.filePath}:${t.testable.name}:${`parentName`in t.testable?t.testable.parentName??``:``}`;a.has(e)?o.push(t):s.push(t)}return{kept:[...o,...s]}}async detectChangedMethods(e,t,n){let r=await this.gitService.getTopLevel(),i=[];for(let a of e){let e=await this.detectChangedMethodsForFile(a,t,n,r);i.push(...e)}return i}async detectChangedMethodsForFile(e,t,n,r){let i=null;try{let a=wU.default.isAbsolute(e)?e:wU.default.join(n,e),o=wU.default.relative(r,a),s=await this.gitService.getFileAtRevision(o,t),c=await this.getBaseMethodsFromContent(s,a,n);(0,z.isDefined)(c.temporaryFilePath)&&(i=c.temporaryFilePath);let l=await this.getCurrentMethods(a),u=await h.readFile(a,`utf8`);return this.changedMethodsDetector.detectChanges(e,c.methods,l,s,u)}catch(t){this.logger.warn(`Failed to detect changed methods for `+e+`: `+(t instanceof Error?t.message:`Unknown error`)+`. Changed-function detection disabled for this file — all its functions will be treated as changed. Fix: add 'fetch-depth: 0' to your checkout step.`);try{let t=wU.default.isAbsolute(e)?e:wU.default.join(n,e);return(await this.getCurrentMethods(t)).map(t=>({filePath:e,name:t.name,type:t.type,parentName:`parentName`in t?t.parentName:void 0,changeType:`modified`,canCreateTests:t.canCreateTests}))}catch{return[]}}finally{await this.cleanupTemporaryFile(i)}}async getBaseMethodsFromContent(e,t,n){if(!(0,z.isDefined)(e)||(0,z.isEmpty)(e))return{methods:[],temporaryFilePath:null};let r=p.default.resolve(n,`.early-temp`);await h.mkdir(r,{recursive:!0});let i=p.default.join(r,`base-${Date.now()}-${p.default.basename(t)}`);await h.writeFile(i,e);let a=i.replaceAll(`\\`,`/`);return{methods:((await this.tsAgent.getTestables(a))[0]?.[1]??[]).filter(e=>e.canCreateTests&&e.type!==`class`),temporaryFilePath:i}}async getCurrentMethods(e){let t=e.replaceAll(`\\`,`/`);return((await this.tsAgent.getTestables(t))[0]?.[1]??[]).filter(e=>e.canCreateTests&&e.type!==`class`)}async cleanupTemporaryFile(e){if((0,z.isDefined)(e))try{await h.unlink(e)}catch{}}};c2=yZ([Qe(),vZ(0,Je(IZ)),vZ(1,Je(i2)),vZ(2,Je(CU.TSAgent)),vZ(3,Je(xZ)),_Z(`design:paramtypes`,[typeof(a2=IZ!==void 0&&IZ)==`function`?a2:Object,typeof(o2=i2!==void 0&&i2)==`function`?o2:Object,typeof(s2=SU.TSAgent!==void 0&&SU.TSAgent)==`function`?s2:Object,Object])],c2);var l2;let u2=class{constructor(e){this.configService=e}async execute(e,t,n){let r=t.coverageReport?.tree,i=t.coverageReport?.threshold??this.configService.getConfigValue(`coverageThreshold`)??0;if(!(0,z.isDefined)(r))return{kept:e};let a=[];for(let t of e){let e=this.findFileCoverage(r,t.filePath);if(!(0,z.isDefined)(e?.testables)){a.push(t);continue}let o=t.testable.type===`method`?t.testable.parentName:void 0,s=e.testables.find(e=>e.name===t.testable.name&&((0,z.isDefined)(o)?e.parentName===o:!(0,z.isDefined)(e.parentName)));if(!(0,z.isDefined)(s)||!(0,z.isDefined)(s.percentage)){a.push(t);continue}if(s.percentage>i){n.push({filePath:t.filePath,testableName:t.testable.name,reason:`above-coverage-threshold`});continue}a.push(t)}return{kept:a}}findFileCoverage(e,t){return e[t.startsWith(`/`)?t:`/${t}`]??null}};u2=yZ([Qe(),vZ(0,Je(SZ)),_Z(`design:paramtypes`,[typeof(l2=SZ!==void 0&&SZ)==`function`?l2:Object])],u2);let d2=class{async execute(e,t,n){let r=[];for(let i of e){let e=i.filePath.toLowerCase(),a=EZ.allowedExtensions.some(t=>e.endsWith(t)),o=wU.default.isAbsolute(i.filePath)?wU.default.relative(t.gitTopLevel,i.filePath):i.filePath;if(!a){n.push({filePath:o,reason:`not-code-file`});continue}if(EZ.excludePatterns.some(t=>e.includes(t.toLowerCase()))){n.push({filePath:o,reason:`excluded-pattern`});continue}r.push(i)}return{kept:r}}};d2=yZ([Qe()],d2);var f2;let p2=class{constructor(e){this.configService=e}async execute(e,t,n){let r=this.configService.getConfigValue(`maxTestables`)??1/0;if(e.length<=r)return{kept:e};let i=e.slice(0,r);for(let t=r;t<e.length;t++){let r=e[t];n.push({filePath:r.filePath,testableName:r.testable.name,reason:`limit-reached`})}return{kept:i}}};p2=yZ([Qe(),vZ(0,Je(SZ)),_Z(`design:paramtypes`,[typeof(f2=SZ!==void 0&&SZ)==`function`?f2:Object])],p2);var Ote=u($R());function m2(e,t){let n=wU.default.relative(e,t);return n===``||!n.startsWith(`..`)&&!wU.default.isAbsolute(n)}function h2(e,t,n){let r=wU.default.isAbsolute(e)&&m2(n,e)?e:wU.default.join(n,e),i=(0,Ote.default)(t,{cwd:m.default.existsSync(r)&&m.default.statSync(r).isDirectory()?r:wU.default.dirname(r)});return i!==null&&!m2(n,i)?null:i}function g2(e,t){let n=[h2(e,`package.json`,t),h2(e,`project.json`,t)].filter(z.isDefined).filter(e=>m2(t,e));if(n.length===0)return t;let r=n.reduce((e,t)=>e.length>t.length?e:t,n[0]);return wU.default.dirname(r)}const _2=[`pyproject.toml`,`setup.py`,`setup.cfg`,`requirements.txt`],v2=[`package.json`,`tsconfig.json`],y2=[`.py`],kte=[`.ts`,`.tsx`,`.js`,`.jsx`];function b2(e,t){return t.some(t=>e.endsWith(t))}function Ate(e){if(b2(e,y2))return`python`;if(b2(e,kte))return`typescript`}function x2(e,t){if(e&&t)return`mixed`;if(e)return`python`;if(t)return`typescript`}function S2(e){let t=m.default.readdirSync(e,{recursive:!0});return x2(t.some(e=>b2(e,y2)),t.some(e=>b2(e,kte)))}function C2(e){return x2(_2.some(t=>m.default.existsSync(wU.default.join(e,t))),v2.some(t=>m.default.existsSync(wU.default.join(e,t))))}function w2(e,t){if(t!==void 0&&t!==``){let n=wU.default.isAbsolute(t)?t:wU.default.join(e,t);return m.default.existsSync(n)&&m.default.statSync(n).isFile()?Ate(n):m.default.existsSync(n)&&m.default.statSync(n).isDirectory()?S2(n):Ate(t)??C2(e)}return C2(e)}const T2={detectProjectRoot(e,t,n){if(t.length===0)return n.verbose(`No changed files provided, using root path`),e;let r=t[0],i=g2(wU.default.isAbsolute(r)?r:wU.default.join(e,r),e);return i===wU.default.normalize(e)?(n.verbose(`Using workspace root path`),e):(n.info(`Detected nested project root: ${i} (from file: ${r})`),i)}};function E2(e,t){let n=wU.default.relative(e,t);return n!==``&&!n.startsWith(`..`)&&!wU.default.isAbsolute(n)}let D2=class{constructor(e){this.logger=e}async execute(e,t,n){if((0,z.isEmpty)(e))return{kept:[],projectRootPath:t.rootPath};let r=e.map(e=>wU.default.isAbsolute(e.filePath)?e.filePath:wU.default.join(t.rootPath,e.filePath)),i=T2.detectProjectRoot(t.rootPath,r,this.logger),a=[];for(let[t,o]of e.entries()){let e=r[t];if(!E2(i,e)){n.push({filePath:o.filePath,reason:`outside-project`});continue}let s=wU.default.relative(i,e);a.push({filePath:s,status:o.status})}return{kept:a,projectRootPath:i}}};D2=yZ([Qe(),vZ(0,Je(xZ)),_Z(`design:paramtypes`,[Object])],D2);let O2=class{constructor(e){this.tsAgent=e}async execute(e,t,n){let r=e.map(e=>e.filePath);if((0,z.isEmpty)(r))return{kept:[]};let i=await this.tsAgent.getTestableFileMap(r),a=[];for(let e of r){let r=this.getEntriesForFile(e,i,t.projectRootPath);if(!(0,z.isDefined)(r)||(0,z.isEmpty)(r)){n.push({filePath:e,reason:`no-testables`});continue}this.processEntriesForFile(e,r,a,n)||n.push({filePath:e,reason:`no-testables`})}return{kept:a}}processEntriesForFile(e,t,n,r){let i=!1;for(let a of t){let{testable:t}=a;if(!t.canCreateTests||t.type===`class`)continue;if(i=!0,(0,z.isDefined)(a.testPath)){r.push({filePath:e,testableName:t.name,reason:`has-test-file`});continue}let o=e.startsWith(`/`)?e.slice(1):e;n.push({filePath:o,testable:t})}return i}getEntriesForFile(e,t,n){if((0,z.isDefined)(t[e]))return t[e];let r=wU.default.resolve(n,e);if((0,z.isDefined)(t[r]))return t[r]}};O2=yZ([Qe(),vZ(0,Je(CU.TSAgent)),_Z(`design:paramtypes`,[Object])],O2);var k2,A2,j2,M2,N2,P2,F2;function I2(e,t){return{async execute(n,r,i){return e(r)?t.execute(n,r,i):{kept:n}}}}let L2=class{filters;constructor(e,t,n,r,i,a,o,s){this.configService=e,this.tsAgent=t,this.fileNameFilter=n,this.projectRootFilter=r,this.testableMapFilter=i,this.changedMethodsFilter=a,this.coverageFilter=o,this.limitFilter=s,this.filters=[this.fileNameFilter,this.projectRootFilter,this.testableMapFilter,I2(e=>e.changedMethodsOnly&&e.hasDiffContext,this.changedMethodsFilter),this.coverageFilter,this.limitFilter]}async getTestablesToGenerate(e){let t={rootPath:e.rootPath,projectRootPath:e.rootPath,gitTopLevel:e.gitTopLevel,changedMethodsOnly:e.changedMethodsOnly??!1,hasDiffContext:e.hasDiffContext,baseRevision:e.baseRevision,coverageReport:e.coverageReport};return this.runPipeline([...e.changedFiles],t)}async runPipeline(e,t){let n=[],r=e,i=t.projectRootPath;for(let e of this.filters){let a={...t,projectRootPath:i},o=await e.execute(r,a,n);if((0,z.isDefined)(o.projectRootPath)&&!(0,z.isEmpty)(o.projectRootPath)&&(i=o.projectRootPath,this.tsAgent.updateRootPath(i),this.configService.updateConfigValue(`rootPath`,i)),(0,z.isEmpty)(o.kept))return{testables:[],filteredOut:n,projectRootPath:i};r=o.kept}return{testables:r,filteredOut:n,projectRootPath:i}}};L2=yZ([Qe(),vZ(0,Je(SZ)),vZ(1,Je(CU.TSAgent)),vZ(2,Je(d2)),vZ(3,Je(D2)),vZ(4,Je(O2)),vZ(5,Je(c2)),vZ(6,Je(u2)),vZ(7,Je(p2)),_Z(`design:paramtypes`,[typeof(k2=SZ!==void 0&&SZ)==`function`?k2:Object,Object,typeof(A2=d2!==void 0&&d2)==`function`?A2:Object,typeof(j2=D2!==void 0&&D2)==`function`?j2:Object,typeof(M2=O2!==void 0&&O2)==`function`?M2:Object,typeof(N2=c2!==void 0&&c2)==`function`?N2:Object,typeof(P2=u2!==void 0&&u2)==`function`?P2:Object,typeof(F2=p2!==void 0&&p2)==`function`?F2:Object])],L2);var R2,z2,B2;let V2=class{constructor(e,t,n){this.configService=e,this.apiService=t,this.authStorage=n,this.authStorage.setRefreshTokenCallback(async()=>{await this.login()})}async login(){let e=this.configService.getConfigValueOrThrow(`secretToken`,`API key is required but not configured`);try{let{idToken:t}=await this.apiService.post(`auth/v2/sign-in-with-secret-token`,{secret:e});return this.authStorage.setJWTToken(t),t}catch{throw Error(`Failed to get JWT token by secret`)}}};V2=yZ([Qe(),vZ(0,Je(SZ)),vZ(1,Je(Y0)),vZ(2,Je(K0)),_Z(`design:paramtypes`,[typeof(R2=SZ!==void 0&&SZ)==`function`?R2:Object,typeof(z2=Y0!==void 0&&Y0)==`function`?z2:Object,typeof(B2=K0!==void 0&&K0)==`function`?B2:Object])],V2);var H2;let U2=class{constructor(e,t){this.tsAgent=e,this.logger=t}async analyzeChangedMethods(e,t,n){try{this.logger.info(`Analyzing coverage for ${t.length} changed methods with threshold ${n.coverageThreshold}%`);let r=[],i=0,a=0,o=0,s=this.groupChangedMethodsByFile(t);for(let[t,c]of Object.entries(s)){let s=this.findFileCoverage(e,t);if((0,z.isDefined)(s)){let e=this.processFileWithCoverage(t,c,s,n);r.push(...e.testables),i+=e.analyzed,a++}else{let e=this.processFileWithoutCoverage(t,c);r.push(...e.testables),i+=e.analyzed,o++}}let c={testables:r,totalAnalyzed:i,filteredCount:r.length,filesWithCoverage:a,filesWithoutCoverage:o};return this.logger.info(`Changed methods analysis complete: ${c.filteredCount}/${c.totalAnalyzed} methods below threshold across ${a+o} files`),c}catch(e){throw e instanceof Error?(this.logger.error(`Failed to analyze changed methods: ${e.message}`),e):Error(`Unknown error occurred while analyzing changed methods`)}}processFileWithCoverage(e,t,n,r){let i=[],a=0;for(let o of t){if(o.changeType===`deleted`||!o.canCreateTests)continue;let t=this.findTestableInCoverage(n,o);(0,z.isDefined)(t)?(a++,this.shouldIncludeTestable(t,r)&&i.push({name:t.name,percentage:t.percentage,filePath:e,reason:this.getFilterReason(t)})):(a++,i.push({name:o.name??`unknown`,percentage:null,filePath:e,reason:`no-coverage`}))}return{testables:i,analyzed:a}}processFileWithoutCoverage(e,t){let n=t.filter(e=>e.changeType!==`deleted`&&e.canCreateTests),r=n.map(t=>({name:t.name??`unknown`,percentage:null,filePath:e,reason:`no-coverage`}));return this.logger.debug(`No coverage data found for file: ${e}`),{testables:r,analyzed:n.length}}async analyzeChangedFiles(e,t,n){try{this.logger.info(`Analyzing coverage for ${t.length} changed files with threshold ${n.coverageThreshold}%`);let r=[],i=0,a=0,o=0;for(let s of t){let t=this.findFileCoverage(e,s);if((0,z.isDefined)(t)){a++;let e=await this.filterOutClasses(s,t.testables??[]),o=this.filterTestablesForFile(t,s,n),c=await this.filterOutClasses(s,o);r.push(...c),i+=e.length??0,(0,z.isEmpty)(c)||this.logger.debug(`File ${s}: ${c.length}/${e.length??0} testables below threshold`)}else o++,this.logger.debug(`No coverage data found for file: ${s}`)}let s={testables:r,totalAnalyzed:i,filteredCount:r.length,filesWithCoverage:a,filesWithoutCoverage:o};return this.logger.info(`Coverage analysis complete: ${s.filteredCount}/${s.totalAnalyzed} testables below threshold across ${s.filesWithCoverage} files`),s}catch(e){throw e instanceof Error?(this.logger.error(`Failed to analyze coverage: ${e.message}`),e):Error(`Unknown error occurred while analyzing coverage`)}}findFileCoverage(e,t){let n=t.startsWith(`/`)?t:`/${t}`;return(0,z.isDefined)(e[n])?e[n]:null}filterTestablesForFile(e,t,n){let r=[];for(let i of e.testables??[])if(this.shouldIncludeTestable(i,n)){let e=this.getFilterReason(i);r.push({name:i.name,percentage:i.percentage,filePath:t,reason:e})}return r}shouldIncludeTestable(e,t){return!!(e.percentage===null||e.percentage===0||(0,z.isDefined)(e.percentage)&&e.percentage<t.coverageThreshold)}getFilterReason(e){return e.percentage===null?`no-coverage`:e.percentage===0?`zero-coverage`:`below-threshold`}async calculatePRCoverage(e,t){if(!(0,z.isEmpty)(e))try{let n=await this.tsAgent.getCoverageForFiles(e),r=t?`before`:`after`;return this.logger.debug(`PR Coverage (${r}): ${n.percentage}% (${n.coveredStatements}/${n.totalStatements} statements)`),n}catch(e){this.logger.warn(`Failed to calculate PR coverage: ${e instanceof Error?e.message:`Unknown error`}`);return}}async filterOutClasses(e,t){let n=await this.tsAgent.getTestables(e);if((0,z.isEmpty)(n)||!(0,z.isDefined)(n[0]))return this.logger.warn(`getTestables returned empty for ${e}, keeping all testables`),t;let[,r]=n[0],i=r.filter(e=>e.type!==`class`),a=new Set(i.map(e=>e.name));return t.filter(e=>a.has(e.name))}groupChangedMethodsByFile(e){let t={};for(let n of e)(0,z.isDefined)(t[n.filePath])||(t[n.filePath]=[]),t[n.filePath].push(n);return t}findTestableInCoverage(e,t){return(0,z.isDefined)(e.testables)?e.testables.find(e=>{let n=e.name===t.name,r=`parentName`in e?e.parentName===t.parentName:!(0,z.isDefined)(t.parentName);return n&&r})??null:null}};U2=yZ([Qe(),vZ(0,Je(CU.TSAgent)),vZ(1,Je(xZ)),_Z(`design:paramtypes`,[typeof(H2=SU.TSAgent!==void 0&&SU.TSAgent)==`function`?H2:Object,Object])],U2);function W2(e,t){return h2(e,`package.json`,t)??void 0}function G2(e,t){try{return m.default.existsSync(e)?m.default.readFileSync(e,`utf8`):void 0}catch(n){t.warn(`Failed to read file ${e}: ${n instanceof Error?n.message:`Unknown error`}`);return}}async function K2(e,t,n){let r=W2(e,t),i=(await(0,SU.findLintConfigPath)(t)).path??void 0,a=(0,z.isDefined)(r)?G2(r,n):void 0,o=(0,z.isDefined)(i)?G2(i,n):void 0;return(0,z.isDefined)(r)&&n.info(`Found package.json at: ${r}`),(0,z.isDefined)(i)&&n.info(`Found lint config at: ${i}`),{packageJsonPath:r,packageJsonContent:a,lintConfigPath:i,lintConfigContent:o}}const q2={detectProjectConfigs:K2};var J2,Y2;let X2=class{constructor(e,t,n){this.apiService=e,this.configService=t,this.logger=n}async detectAndSaveConfigs(e){try{let t=this.configService.getConfigValue(`rootPath`),n=await q2.detectProjectConfigs(t,t,this.logger);if(!(0,z.isDefined)(n.packageJsonContent)&&!(0,z.isDefined)(n.lintConfigContent))return;await this.apiService.patch(`api/v1/github-repos/configs`,{owner:e.owner,repo:e.repository,packageJson:n.packageJsonContent,lintConfig:n.lintConfigContent})}catch(e){this.logger.warn(`Failed to detect and save project configs: ${e instanceof Error?e.message:`Unknown error`}`)}}};X2=yZ([Qe(),vZ(0,Je(Y0)),vZ(1,Je(SZ)),vZ(2,Je(xZ)),_Z(`design:paramtypes`,[typeof(J2=Y0!==void 0&&Y0)==`function`?J2:Object,typeof(Y2=SZ!==void 0&&SZ)==`function`?Y2:Object,Object])],X2);var Z2,Q2,jte,$2,e4,t4,n4,r4,i4,a4;let o4=class{workflowRunId;teamId;initialCoverageTree;resultCommitSha;constructor(e,t,n,r,i,a,o,s,c,l,u){this.configService=e,this.authService=t,this.apiService=n,this.gitService=r,this.coverageAnalysisService=i,this.summaryService=a,this.tsAgent=o,this.workflowService=s,this.scmHostService=c,this.repoConfigService=l,this.logger=u}async login(){try{this.logger.info(`Trying login to API...`);let e=await this.authService.login();await this.tsAgent.init(e),this.logger.info(`Successfully authenticated with the API`);try{this.teamId=(await this.apiService.get(`api/v1/user/me`)).team?.id}catch(e){this.logger.warn(`Failed to fetch user info: `+(e instanceof Error?e.message:`Unknown error`))}}catch(e){throw this.logger.error(`Failed to authenticate:`+(e instanceof Error?e.message:`Unknown error`)),e}}async logStart(){try{let e=await this.gitService.getGitInfo();this.logger.debug(`Git info: `+JSON.stringify(e));try{let t=await this.workflowService.logStartOperation(e);return this.tsAgent.updateContext({git:{...e,workflowRunId:t}}),this.workflowRunId=t,await this.repoConfigService.detectAndSaveConfigs(e),t}catch(e){throw e instanceof o0||e instanceof a0||this.logger.warn(`Failed to log start operation: ${e instanceof Error?e.message:`Unknown error`}`),e}}catch(e){throw e instanceof o0||e instanceof a0||this.logger.error(`Failed to retrieve git info or log start operation:`+(e instanceof Error?e.message:`Unknown error`)),e}}async generateInitialCoverage(){this.logger.verbose(`Try to reuse coverage...`);let e=await this.workflowService.getCoverageFromWorkflowOrUndefined(this.workflowRunId);if((0,z.isDefined)(e))return await this.tsAgent.setCoverage(e),this.initialCoverageTree=e,(0,z.isDefined)(this.workflowRunId)&&await this.workflowService.saveCoverageToWorkflow(this.workflowRunId,`before`,{}),this.logger.verbose(`Reused coverage: `+(e[`/`]?.percentage??0)+`%`),this.summaryService.setCoverageData(e[`/`]?.percentage??0,e[`/`]?.percentage??0),e;{this.logger.verbose(`Generating initial coverage...`),await this.tsAgent.generateCoverage();let e=await this.tsAgent.getCoverageTree();if(!(0,z.isDefined)(e))throw Error(`Failed to generate initial coverage tree`);return this.initialCoverageTree=e,(0,z.isDefined)(this.workflowRunId)&&await this.workflowService.saveCoverageToWorkflow(this.workflowRunId,`before`,{coverage:e}),this.logger.verbose(`Initial coverage: `+(e[`/`]?.percentage??0)+`%`),this.summaryService.setCoverageData(e[`/`]?.percentage??0,e[`/`]?.percentage??0),e}}async logEndOperation(e){if((0,z.isDefined)(this.workflowRunId))try{let t=this.summaryService.getWorkflowRunOutput();await this.workflowService.logEndOperation(this.workflowRunId,e,t,this.resultCommitSha),this.logger.info(`Successfully logged workflow end`)}catch(e){this.logger.warn(`Failed to log workflow end: `+(e instanceof Error?e.message:`Unknown error`))}}getWorkflowRunIdOrThrow(){if(!(0,z.isDefined)(this.workflowRunId))throw Error(`Workflow run ID is not set, call logStart() first`);return this.workflowRunId}getInitialCoverageTreeOrThrow(){if(!(0,z.isDefined)(this.initialCoverageTree))throw Error(`Initial coverage tree is not set, call generateInitialCoverage() first`);return this.initialCoverageTree}getInitialCoverageTreeOrUndefined(){return this.initialCoverageTree}async countAllMethodsInFiles(e){let t=(0,z.uniq)(e).map(async e=>{try{return await this.tsAgent.getAllMethodsCount(e)}catch(t){return this.logger.debug(`Failed to count methods in `+e+`: `+(t instanceof Error?t.message:`Unknown error`)),0}});return(await Promise.all(t)).reduce((e,t)=>e+t,0)}};o4=yZ([Qe(),vZ(0,Je(SZ)),vZ(1,Je(V2)),vZ(2,Je(Y0)),vZ(3,Je(IZ)),vZ(4,Je(U2)),vZ(5,Je(TZ)),vZ(6,Je(CU.TSAgent)),vZ(7,Je(Q0)),vZ(8,Je(CU.SCMHostService)),vZ(9,Je(X2)),vZ(10,Je(xZ)),_Z(`design:paramtypes`,[typeof(Z2=SZ!==void 0&&SZ)==`function`?Z2:Object,typeof(Q2=V2!==void 0&&V2)==`function`?Q2:Object,typeof(jte=Y0!==void 0&&Y0)==`function`?jte:Object,typeof($2=IZ!==void 0&&IZ)==`function`?$2:Object,typeof(e4=U2!==void 0&&U2)==`function`?e4:Object,typeof(t4=TZ!==void 0&&TZ)==`function`?t4:Object,typeof(n4=SU.TSAgent!==void 0&&SU.TSAgent)==`function`?n4:Object,typeof(r4=Q0!==void 0&&Q0)==`function`?r4:Object,typeof(i4=AZ!==void 0&&AZ)==`function`?i4:Object,typeof(a4=X2!==void 0&&X2)==`function`?a4:Object,Object])],o4);var s4,c4,l4;const u4=e=>e instanceof Error&&(e.message===`Operation aborted`||e.name===`AbortError`);let d4=class extends o4{changedFiles=[];prCoverage={before:{percentage:null,totalStatements:0,coveredStatements:0},after:{percentage:null,totalStatements:0,coveredStatements:0}};_successSourceFiles=[];_successTestFiles=[];testableToGenerateService;postGenerationService;postCommitCoverageService;getWorkflowRunId(){return this.workflowRunId}getSuccessSourceFiles(){return this._successSourceFiles}getSuccessTestFiles(){return this._successTestFiles}getChangedFiles(){return this.changedFiles}async runFlow(e){let t=e?.shouldDeferPostGeneration??!1,n,r=!1,i=!1,a;try{if(await this.login(),await this.logStart(),await this.isOwnCommit()){this.logger.info(`Skipping: commit was generated by Early AI`),i=!0;return}await this.validateCommitBranch();let e=await this.getRawChangedFiles(),n=this.configService.getConfigValue(`rootPath`),r=this.configService.getConfigValue(`gitTopLevel`)??n;this.logger.info(`Discovering untested functions`);let o=await this.testableToGenerateService.getTestablesToGenerate({changedFiles:e,rootPath:n,gitTopLevel:r,hasDiffContext:this.hasDiffContext(),baseRevision:await this.getBaseRevision(),changedMethodsOnly:this.configService.getConfigValue(`changedMethodsOnly`),coverageReport:{tree:this.initialCoverageTree,threshold:this.configService.getConfigValue(`coverageThreshold`)}});if((0,z.isEmpty)(o.testables)){this.logFilteredOutTestables(o.filteredOut),this.handleNoFilteredTestables();let e=[...new Set(o.filteredOut.map(e=>e.filePath))];await this.runCoverageIfEnabled({changedSourceFiles:e,successState:CZ.NoGeneration});return}if(this.updateRootPath(o.projectRootPath),this.changedFiles=[...new Set([...o.testables.map(e=>e.filePath),...o.filteredOut.filter(e=>e.reason===`has-test-file`).map(e=>e.filePath)])],await this.setSummaryChangedFilesData(e.length,o),o.filteredOut.filter(e=>e.reason===`limit-reached`).length>0){let e=this.configService.getConfigValue(`maxTestables`);this.summaryService.addWarning(`Limited to ${e} functions: test generation was capped due to maximum function limit.`)}this.logFilteredOutTestables(o.filteredOut),this.logTestablesToGenerate([...o.testables]);let s=[...o.testables];if(a=await this.generateTests(s),!t){let e=await this.performAutoCommit();this.summaryService.setTestGenerationData({generated:a.generated,succeeded:a.succeeded,failed:a.failed,successMethodsCount:a.successMethodsCount,committedFilesCount:e,greenTests:a.greenTests,redTests:a.redTests}),await this.runCoverageIfEnabled({changedSourceFiles:[...this.changedFiles],successTestFiles:this._successTestFiles,successState:CZ.Success})}return a}catch(e){if(e instanceof o0){this.logger.warn(`Duplicate SHA execution detected. Skipping.`);return}if(e instanceof a0){this.logger.warn(`Workflow canceled. Skipping.`),r=!0;return}return u4(e)?(n=`Operation timed out`,this.logger.warn(`Workflow aborted due to timeout`)):(n=e instanceof Error?e.message:`Unknown error`,this.logger.error(`Agent flow failed: `+n)),a}finally{!t&&(0,z.isDefined)(this.workflowRunId)&&!r&&!i&&(this.summaryService.setPRCoverageData(this.prCoverage.before,this.prCoverage.after),await this.scmHostService.safePostSummaryToPr(),await this.logEndOperation(n))}}async setSummaryChangedFilesData(e,t){let n=[...new Set([...t.testables.map(e=>e.filePath),...t.filteredOut.map(e=>e.filePath)])],r=await this.countAllMethodsInFiles(n);this.summaryService.setChangedFilesData({changedFilesCount:e,candidateFilesCount:n.length,functionCount:r,publicMethodCount:t.testables.length,testablesToGenerateCount:t.testables.length,publicMethods:t.testables.map(e=>({name:e.testable.name??`unknown`,filePath:e.filePath})),methodsBelowCoverage:t.testables.map(e=>({name:e.testable.name??`unknown`,filePath:e.filePath}))})}async isOwnCommit(){try{let e=this.configService.getConfigValue(`commitHash`);return(await this.gitService.getCommitMessage(e)).startsWith(`chore: add early-catch tests`)}catch{return!1}}handleNoFilteredTestables(){this.logger.warn(`No filtered untested functions`),this.prCoverage.after=this.prCoverage.before}logFilteredOutTestables(e){if((0,z.isEmpty)(e))return;let t=e.length,n=t===1?`item`:`items`;this.logger.verbose(t+` `+n+` skipped:`);for(let t of e){let e=(0,z.isDefined)(t.testableName)?t.testableName+` in `+t.filePath:t.filePath;this.logger.verbose(` - `+e+`: `+t.reason)}}logTestablesToGenerate(e){this.logger.info(`Found ${e.length} public function${e.length===1?``:`s`} without Early AI tests`);for(let t of e)this.logger.info(` `+t.testable.name+` in `+t.filePath)}async validateCommitBranch(){if(!this.configService.getConfigValue(`autoCommit`))return;let e=this.configService.getConfigValue(`refName`);if(e&&!await this.gitService.checkRefExists(e))throw Error(`Branch '${e}' does not exist on remote. Create it before running with --auto-commit.`)}async runCoverageIfEnabled(e){if(this.configService.getConfigValue(`skipCoverageAfter`)){this.logger.verbose(`Skipping final coverage generation (--skip-coverage-after flag is set)`),this.summaryService.setCoverageState(CZ.Skipped);return}let t=await this.postCommitCoverageService.calculateCoverage({changedSourceFiles:e.changedSourceFiles,successTestFiles:e.successTestFiles});t.success?(this.prCoverage={before:t.before.prCoverage,after:t.after.prCoverage},this.summaryService.setPRCoverageData(t.before.prCoverage,t.after.prCoverage),(0,z.isDefined)(this.workflowRunId)&&(await this.workflowService.saveCoverageToWorkflow(this.workflowRunId,`before`,{prCoverage:t.before.prCoverage}),await this.workflowService.saveCoverageToWorkflow(this.workflowRunId,`after`,{prCoverage:t.after.prCoverage})),this.summaryService.setCoverageState(e.successState)):((0,z.isDefined)(this.workflowRunId)&&(await this.workflowService.saveCoverageToWorkflow(this.workflowRunId,`before`,{}),await this.workflowService.saveCoverageToWorkflow(this.workflowRunId,`after`,{})),this.summaryService.setCoverageState(CZ.Failed,t.reason))}async performAutoCommit(){let e=this.configService.getConfigValueOrThrow(`autoCommit`);if(this.summaryService.setAutoCommitStatus(e),e){await this.postGenerationService.cleanupBlankEarlyFiles();let e=this.configService.getConfigValue(`refName`),t=await this.gitService.commitFiles(e);return(0,z.isDefined)(t.resultCommitSha)&&(this.resultCommitSha=t.resultCommitSha),t.committedFiles.length}else return this.logger.info(`Auto-commit is disabled - skipping commit step`),0}async _generateInitialCoverageForTestGeneration(){await this.generateInitialCoverage(),await this.savePRCoverageBefore()}async savePRCoverageBefore(){if((0,z.isDefined)(this.workflowRunId))try{let e=await this.coverageAnalysisService.calculatePRCoverage(this.changedFiles,!0);(0,z.isDefined)(e)&&(this.prCoverage.before=e),await this.workflowService.saveCoverageToWorkflow(this.workflowRunId,`before`,{prCoverage:e}),this.logger.debug(`Successfully saved initial coverage to workflow run`)}catch(e){this.logger.warn(`Failed to save initial coverage: `+(e instanceof Error?e.message:`Unknown error`))}}async generateTests(e){let t=new Set(e),n=[],r=0,i=0,a=0,o=0;try{await this.tsAgent.bulkGenerateTests(e,(s,c,l)=>{o++;let u=wU.default.basename(s.filePath);(0,z.isDefined)(c)&&c.greenTestsCount>0?(t.delete(s),r+=c.greenTestsCount,i+=c.redTestsCount,a+=c.greyTestsCount,this._successSourceFiles.push(s.filePath),(0,z.isDefined)(l)&&l.testFilePath&&this._successTestFiles.push(l.testFilePath),this.logger.info(` [${o}/${e.length}] ✓ ${s.testable.name} (${u}) — ${c.greenTestsCount} passing, ${c.redTestsCount} skipped`)):((0,z.isDefined)(l)&&l.testFilePath&&n.push(l.testFilePath),this.logger.info(` [${o}/${e.length}] ✗ ${s.testable.name} (${u}) — no tests generated`))})}catch(e){if(u4(e))this.logger.warn(`Test generation was partially aborted due to timeout`);else throw e}for(let e of n)try{await h.unlink(e),this.logger.debug(`Removed failed test file: ${e}`)}catch{this.logger.debug(`Could not remove failed test file: ${e}`)}let s=e.length-t.size,c=t.size,l=await this.gitService.getEarlyFiles();return this.logger.info(``),this.logger.info(`✅ Test generation complete for ${s} functions`),c>0&&this.logger.info(`❌ ${c} functions were not generated`),this.logger.info(``),this.logger.info(`================`),this.logger.info(`Overall summary:`),this.logger.info(`================`),this.logger.info(``),this.logger.info(`✅ ${r} tests passing`),this.logger.info(`⚠️ ${i} tests skipped`),this.logger.info(`❌ ${a} tests could not be fixed autonomously (yet)`),this.logger.info(``),{generated:e.length,succeeded:s,failed:c,successMethodsCount:l.length,greenTests:r,redTests:i}}async generateFinalCoverageAndLog({methodsAffected:e,committedFiles:t}){let n=this.getWorkflowRunIdOrThrow();this.logger.verbose(`Generating final coverage...`),await this.tsAgent.generateCoverage();let r=await this.tsAgent.getCoverageTree();if(!(0,z.isDefined)(r))throw Error(`Failed to generate final coverage tree`);let i=r[`/`]?.percentage??0,a=this.getInitialCoverageTreeOrUndefined(),o=a?.[`/`]?.percentage??0;(0,z.isDefined)(a)||this.summaryService.setCoverageBeforeSkipped(),this.summaryService.setCoverageData(o,i);let s=(0,z.isDefined)(a)?`${o}% -> ${i}%`:`skipped`;this.logger.verbose(`Final coverage: `+i+`%, Coverage comparison: `+s);try{let i=await this.coverageAnalysisService.calculatePRCoverage(this.changedFiles,!1);(0,z.isDefined)(i)&&(this.prCoverage.after=i),await this.workflowService.saveCoverageToWorkflow(n,`after`,{coverage:r,prCoverage:i,methodsAffected:e,committedFiles:t}),this.logger.debug(`Successfully saved final coverage to workflow run`)}catch(e){this.logger.warn(`Failed to save final coverage: `+(e instanceof Error?e.message:`Unknown error`))}}updateRootPath(e){this.tsAgent.updateRootPath(e),this.configService.updateConfigValue(`rootPath`,e)}};yZ([Je(L2),_Z(`design:type`,typeof(s4=L2!==void 0&&L2)==`function`?s4:Object)],d4.prototype,`testableToGenerateService`,void 0),yZ([Je(r2),_Z(`design:type`,typeof(c4=r2!==void 0&&r2)==`function`?c4:Object)],d4.prototype,`postGenerationService`,void 0),yZ([Je(l0),_Z(`design:type`,typeof(l4=l0!==void 0&&l0)==`function`?l4:Object)],d4.prototype,`postCommitCoverageService`,void 0),d4=yZ([Qe(),at({extendConstructorArguments:!0,extendProperties:!0})],d4);let f4=class extends d4{async getRawChangedFiles(){return this.gitService.getChangedFilesForCommitWithStatus({absolute:!0})}hasDiffContext(){return!0}async getBaseRevision(){let e=this.configService.getConfigValue(`baseRef`);if((0,z.isDefined)(e))return this.gitService.getBaseRevision({baseBranch:e});let t=this.configService.getConfigValue(`commitHash`);if((0,z.isDefined)(t))return`${t}^`}async logStart(){try{let e=this.configService.getConfigValue(`commitHash`),t=await this.gitService.getCommitMessage(e);t&&this.configService.updateConfigValue(`commitName`,t)}catch(e){this.logger.warn(`Failed to retrieve commit message, continuing without it: `+(e instanceof Error?e.message:`Unknown error`))}try{let e=await this.scmHostService.getContributorAvatarUrl();(0,z.isDefined)(e)&&this.configService.updateConfigValue(`contributorAvatarUrl`,e)}catch(e){this.logger.warn(`Failed to retrieve contributor avatar, continuing without it: `+(e instanceof Error?e.message:`Unknown error`))}return await super.logStart()}};f4=yZ([Qe(),at({extendConstructorArguments:!0,extendProperties:!0})],f4);function p4(e){let t=e.command(TU.COMMIT).alias(`generate-commit`).description(`Generate tests for the current project in commit context`);return oe(t,`--commit-hash <hash>`,`Commit hash`,{envName:`COMMIT_HASH`,isRequired:!0}),oe(t,`--ref-name <ref>`,`Head branch name for the commit`,{envName:`REF_NAME`,isRequired:!0}),oe(t,`--base-ref <ref>`,`optional base refrence for comparison`,{envName:`BASE_REF`}),oe(t,`-s, --test-structure <structure>`,`Test file structure`,{envName:`TEST_STRUCTURE`,def:`siblingFolder`}),oe(t,`-f, --test-framework <framework>`,`Test framework to use`,{envName:`TEST_FRAMEWORK`,def:`jest`}),oe(t,`--test-suffix <suffix>`,`Test file suffix`,{envName:`TEST_FILE_SUFFIX`,def:`test`}),oe(t,`--test-file-naming <naming>`,`Test file naming convention`,{envName:`TEST_FILE_NAMING`,def:`camelCase`}),oe(t,`-c, --max-concurrency <number>`,`Number of concurrent workers (1-4)`,{envName:`MAX_CONCURRENCY`,def:`3`}),oe(t,`--auto-commit <boolean>`,`Whether to auto-commit files`,{envName:`AUTO_COMMIT`,def:`true`}),oe(t,`--auto-commit-skip-ci <boolean>`,`Append [skip ci] to auto-commit message`,{envName:`AUTO_COMMIT_SKIP_CI`,def:`true`}),oe(t,`--test-command <command>`,`Custom test command to run`,{envName:`TEST_COMMAND`}),oe(t,`--coverage-command <command>`,`Custom coverage command to run`,{envName:`COVERAGE_COMMAND`}),oe(t,`--lint-command <command>`,`Custom lint command to run`,{envName:`LINT_COMMAND`}),oe(t,`--prettier-command <command>`,`Custom prettier command to run`,{envName:`PRETTIER_COMMAND`}),oe(t,`--disable-lint-rules <boolean>`,`Whether to disable failed lint rules in test files`,{envName:`DISABLE_LINT_RULES`,def:`false`}),oe(t,`--git-org <org>`,`Git organization name`,{envName:`GIT_ORG`}),oe(t,`--git-repo <repo>`,`Git repository name`,{envName:`GIT_REPO`}),oe(t,`--git-user-email <email>`,`Git user email for auto commit`,{envName:`GIT_USER_EMAIL`}),oe(t,`--git-user-name <name>`,`Git user name for auto commit`,{envName:`GIT_USER_NAME`}),oe(t,`--scm-provider <provider>`,`SCM provider (e.g., github, bitbucket)`,{envName:`SCM_PROVIDER`,def:`github`}),oe(t,`--keep-error-tests <boolean>`,`Whether to keep error tests`,{envName:`KEEP_ERROR_TESTS`,def:`false`}),oe(t,`--keep-failed-tests <boolean>`,`Whether to keep failed tests`,{envName:`KEEP_FAILED_TESTS`,def:`false`}),oe(t,`--conditional-keep <boolean>`,`Whether to return the last generated test result even when no green tests were produced`,{envName:`CONDITIONAL_KEEP`,def:`false`}),oe(t,`--continue-on-test-errors <boolean>`,`Whether to continue on test errors`,{envName:`CONTINUE_ON_TEST_ERRORS`,def:`true`}),oe(t,`--changed-methods-only <boolean>`,`Generate tests only for changed methods, not all methods in changed files`,{envName:`CHANGED_METHODS_ONLY`,def:`true`}),oe(t,`--skip-coverage-after <boolean>`,`Skip final coverage generation after test generation`,{envName:`SKIP_COVERAGE_AFTER`,def:`false`}),oe(t,`--max-testables <number>`,`Maximum number of testables to generate`,{envName:`MAX_TESTABLES`}),oe(t,`--per-function-timeout <number>`,`Per function timeout in milliseconds`,{envName:`PER_FUNCTION_TIMEOUT`}),oe(t,`--coverage-threshold <number>`,`Coverage threshold percentage (0-100)`,{envName:`COVERAGE_THRESHOLD`,def:`0`}),oe(t,`--reuse-coverage <boolean>`,`Whether to reuse coverage`,{envName:`REUSE_COVERAGE`,def:`false`}),oe(t,`--reuse-coverage-max-runs <number>`,`Max number of runs to reuse coverage (1-10)`,{envName:`REUSE_COVERAGE_MAX_RUNS`,def:`10`}),oe(t,`--experimental-agent-sdk <boolean>`,`Use experimental Agent SDK for test generation`,{envName:`EXPERIMENTAL_AGENT_SDK`,def:`true`}),oe(t,`--compress-output <boolean>`,`Compress test runner output to reduce token consumption`,{envName:`COMPRESS_OUTPUT`,def:`false`}),t.addHelpText(`after`,`
32492
+ `)}extractMethodText(e,t){return t.slice(e.startIndex,e.endIndex)}createChangedMethod(e,t,n){return{name:t.name,type:t.type,parentName:`parentName`in t?t.parentName:void 0,changeType:n,filePath:e,canCreateTests:t.canCreateTests}}};i2=yZ([Qe(),vZ(0,Je(xZ)),_Z(`design:paramtypes`,[Object])],i2);var a2,o2,s2;let c2=class{constructor(e,t,n,r){this.gitService=e,this.changedMethodsDetector=t,this.tsAgent=n,this.logger=r}async execute(e,t,n){if(!(0,z.isDefined)(t.baseRevision))return{kept:e};let r=[...new Set(e.map(e=>e.filePath))],i=await this.detectChangedMethods(r,t.baseRevision,t.projectRootPath),a=new Set(i.filter(e=>e.changeType!==`deleted`&&e.canCreateTests).map(e=>`${e.filePath}:${e.name}:${e.parentName??``}`)),o=[],s=[];for(let t of e){let e=`${t.filePath}:${t.testable.name}:${`parentName`in t.testable?t.testable.parentName??``:``}`;a.has(e)?o.push(t):s.push(t)}return{kept:[...o,...s]}}async detectChangedMethods(e,t,n){let r=await this.gitService.getTopLevel(),i=[];for(let a of e){let e=await this.detectChangedMethodsForFile(a,t,n,r);i.push(...e)}return i}async detectChangedMethodsForFile(e,t,n,r){let i=null;try{let a=wU.default.isAbsolute(e)?e:wU.default.join(n,e),o=wU.default.relative(r,a),s=await this.gitService.getFileAtRevision(o,t),c=await this.getBaseMethodsFromContent(s,a,n);(0,z.isDefined)(c.temporaryFilePath)&&(i=c.temporaryFilePath);let l=await this.getCurrentMethods(a),u=await h.readFile(a,`utf8`);return this.changedMethodsDetector.detectChanges(e,c.methods,l,s,u)}catch(t){this.logger.warn(`Failed to detect changed methods for `+e+`: `+(t instanceof Error?t.message:`Unknown error`)+`. Changed-function detection disabled for this file — all its functions will be treated as changed. Fix: add 'fetch-depth: 0' to your checkout step.`);try{let t=wU.default.isAbsolute(e)?e:wU.default.join(n,e);return(await this.getCurrentMethods(t)).map(t=>({filePath:e,name:t.name,type:t.type,parentName:`parentName`in t?t.parentName:void 0,changeType:`modified`,canCreateTests:t.canCreateTests}))}catch{return[]}}finally{await this.cleanupTemporaryFile(i)}}async getBaseMethodsFromContent(e,t,n){if(!(0,z.isDefined)(e)||(0,z.isEmpty)(e))return{methods:[],temporaryFilePath:null};let r=p.default.resolve(n,`.early-temp`);await h.mkdir(r,{recursive:!0});let i=p.default.join(r,`base-${Date.now()}-${p.default.basename(t)}`);await h.writeFile(i,e);let a=i.replaceAll(`\\`,`/`);return{methods:((await this.tsAgent.getTestables(a))[0]?.[1]??[]).filter(e=>e.canCreateTests&&e.type!==`class`),temporaryFilePath:i}}async getCurrentMethods(e){let t=e.replaceAll(`\\`,`/`);return((await this.tsAgent.getTestables(t))[0]?.[1]??[]).filter(e=>e.canCreateTests&&e.type!==`class`)}async cleanupTemporaryFile(e){if((0,z.isDefined)(e))try{await h.unlink(e)}catch{}}};c2=yZ([Qe(),vZ(0,Je(IZ)),vZ(1,Je(i2)),vZ(2,Je(CU.TSAgent)),vZ(3,Je(xZ)),_Z(`design:paramtypes`,[typeof(a2=IZ!==void 0&&IZ)==`function`?a2:Object,typeof(o2=i2!==void 0&&i2)==`function`?o2:Object,typeof(s2=SU.TSAgent!==void 0&&SU.TSAgent)==`function`?s2:Object,Object])],c2);var l2;let u2=class{constructor(e){this.configService=e}async execute(e,t,n){let r=t.coverageReport?.tree,i=t.coverageReport?.threshold??this.configService.getConfigValue(`coverageThreshold`)??0;if(!(0,z.isDefined)(r))return{kept:e};let a=[];for(let t of e){let e=this.findFileCoverage(r,t.filePath);if(!(0,z.isDefined)(e?.testables)){a.push(t);continue}let o=t.testable.type===`method`?t.testable.parentName:void 0,s=e.testables.find(e=>e.name===t.testable.name&&((0,z.isDefined)(o)?e.parentName===o:!(0,z.isDefined)(e.parentName)));if(!(0,z.isDefined)(s)||!(0,z.isDefined)(s.percentage)){a.push(t);continue}if(s.percentage>i){n.push({filePath:t.filePath,testableName:t.testable.name,reason:`above-coverage-threshold`});continue}a.push(t)}return{kept:a}}findFileCoverage(e,t){return e[t.startsWith(`/`)?t:`/${t}`]??null}};u2=yZ([Qe(),vZ(0,Je(SZ)),_Z(`design:paramtypes`,[typeof(l2=SZ!==void 0&&SZ)==`function`?l2:Object])],u2);let d2=class{async execute(e,t,n){let r=[];for(let i of e){let e=i.filePath.toLowerCase(),a=EZ.allowedExtensions.some(t=>e.endsWith(t)),o=wU.default.isAbsolute(i.filePath)?wU.default.relative(t.gitTopLevel,i.filePath):i.filePath;if(!a){n.push({filePath:o,reason:`not-code-file`});continue}if(EZ.excludePatterns.some(t=>e.includes(t.toLowerCase()))){n.push({filePath:o,reason:`excluded-pattern`});continue}r.push(i)}return{kept:r}}};d2=yZ([Qe()],d2);var f2;let p2=class{constructor(e){this.configService=e}async execute(e,t,n){let r=this.configService.getConfigValue(`maxTestables`)??1/0;if(e.length<=r)return{kept:e};let i=e.slice(0,r);for(let t=r;t<e.length;t++){let r=e[t];n.push({filePath:r.filePath,testableName:r.testable.name,reason:`limit-reached`})}return{kept:i}}};p2=yZ([Qe(),vZ(0,Je(SZ)),_Z(`design:paramtypes`,[typeof(f2=SZ!==void 0&&SZ)==`function`?f2:Object])],p2);var Ote=u($R());function m2(e,t){let n=wU.default.relative(e,t);return n===``||!n.startsWith(`..`)&&!wU.default.isAbsolute(n)}function h2(e,t,n){let r=wU.default.isAbsolute(e)&&m2(n,e)?e:wU.default.join(n,e),i=(0,Ote.default)(t,{cwd:m.default.existsSync(r)&&m.default.statSync(r).isDirectory()?r:wU.default.dirname(r)});return i!==null&&!m2(n,i)?null:i}function g2(e,t){let n=[h2(e,`package.json`,t),h2(e,`project.json`,t)].filter(z.isDefined).filter(e=>m2(t,e));if(n.length===0)return t;let r=n.reduce((e,t)=>e.length>t.length?e:t,n[0]);return wU.default.dirname(r)}const _2=[`pyproject.toml`,`setup.py`,`setup.cfg`,`requirements.txt`],v2=[`package.json`,`tsconfig.json`],y2=[`.py`],kte=[`.ts`,`.tsx`,`.js`,`.jsx`];function b2(e,t){return t.some(t=>e.endsWith(t))}function Ate(e){if(b2(e,y2))return`python`;if(b2(e,kte))return`typescript`}function x2(e,t){if(e&&t)return`mixed`;if(e)return`python`;if(t)return`typescript`}function S2(e){let t=m.default.readdirSync(e,{recursive:!0});return x2(t.some(e=>b2(e,y2)),t.some(e=>b2(e,kte)))}function C2(e){return x2(_2.some(t=>m.default.existsSync(wU.default.join(e,t))),v2.some(t=>m.default.existsSync(wU.default.join(e,t))))}function w2(e,t){if(t!==void 0&&t!==``){let n=wU.default.isAbsolute(t)?t:wU.default.join(e,t);return m.default.existsSync(n)&&m.default.statSync(n).isFile()?Ate(n):m.default.existsSync(n)&&m.default.statSync(n).isDirectory()?S2(n):Ate(t)??C2(e)}return C2(e)}const T2={detectProjectRoot(e,t,n){if(t.length===0)return n.verbose(`No changed files provided, using root path`),e;let r=t[0],i=g2(wU.default.isAbsolute(r)?r:wU.default.join(e,r),e);return i===wU.default.normalize(e)?(n.verbose(`Using workspace root path`),e):(n.info(`Detected nested project root: ${i} (from file: ${r})`),i)}};function E2(e,t){let n=wU.default.relative(e,t);return n!==``&&!n.startsWith(`..`)&&!wU.default.isAbsolute(n)}let D2=class{constructor(e){this.logger=e}async execute(e,t,n){if((0,z.isEmpty)(e))return{kept:[],projectRootPath:t.rootPath};let r=e.map(e=>wU.default.isAbsolute(e.filePath)?e.filePath:wU.default.join(t.rootPath,e.filePath)),i=T2.detectProjectRoot(t.rootPath,r,this.logger),a=[];for(let[t,o]of e.entries()){let e=r[t];if(!E2(i,e)){n.push({filePath:o.filePath,reason:`outside-project`});continue}let s=wU.default.relative(i,e);a.push({filePath:s,status:o.status})}return{kept:a,projectRootPath:i}}};D2=yZ([Qe(),vZ(0,Je(xZ)),_Z(`design:paramtypes`,[Object])],D2);let O2=class{constructor(e){this.tsAgent=e}async execute(e,t,n){let r=e.map(e=>e.filePath);if((0,z.isEmpty)(r))return{kept:[]};let i=await this.tsAgent.getTestableFileMap(r),a=[];for(let e of r){let r=this.getEntriesForFile(e,i,t.projectRootPath);if(!(0,z.isDefined)(r)||(0,z.isEmpty)(r)){n.push({filePath:e,reason:`no-testables`});continue}this.processEntriesForFile(e,r,a,n)||n.push({filePath:e,reason:`no-testables`})}return{kept:a}}processEntriesForFile(e,t,n,r){let i=!1;for(let a of t){let{testable:t}=a;if(!t.canCreateTests||t.type===`class`)continue;if(i=!0,(0,z.isDefined)(a.testPath)){r.push({filePath:e,testableName:t.name,reason:`has-test-file`});continue}let o=e.startsWith(`/`)?e.slice(1):e;n.push({filePath:o,testable:t})}return i}getEntriesForFile(e,t,n){if((0,z.isDefined)(t[e]))return t[e];let r=wU.default.resolve(n,e);if((0,z.isDefined)(t[r]))return t[r]}};O2=yZ([Qe(),vZ(0,Je(CU.TSAgent)),_Z(`design:paramtypes`,[Object])],O2);var k2,A2,j2,M2,N2,P2,F2;function I2(e,t){return{async execute(n,r,i){return e(r)?t.execute(n,r,i):{kept:n}}}}let L2=class{filters;constructor(e,t,n,r,i,a,o,s){this.configService=e,this.tsAgent=t,this.fileNameFilter=n,this.projectRootFilter=r,this.testableMapFilter=i,this.changedMethodsFilter=a,this.coverageFilter=o,this.limitFilter=s,this.filters=[this.fileNameFilter,this.projectRootFilter,this.testableMapFilter,I2(e=>e.changedMethodsOnly&&e.hasDiffContext,this.changedMethodsFilter),this.coverageFilter,this.limitFilter]}async getTestablesToGenerate(e){let t={rootPath:e.rootPath,projectRootPath:e.rootPath,gitTopLevel:e.gitTopLevel,changedMethodsOnly:e.changedMethodsOnly??!1,hasDiffContext:e.hasDiffContext,baseRevision:e.baseRevision,coverageReport:e.coverageReport};return this.runPipeline([...e.changedFiles],t)}async runPipeline(e,t){let n=[],r=e,i=t.projectRootPath;for(let e of this.filters){let a={...t,projectRootPath:i},o=await e.execute(r,a,n);if((0,z.isDefined)(o.projectRootPath)&&!(0,z.isEmpty)(o.projectRootPath)&&(i=o.projectRootPath,this.tsAgent.updateRootPath(i),this.configService.updateConfigValue(`rootPath`,i)),(0,z.isEmpty)(o.kept))return{testables:[],filteredOut:n,projectRootPath:i};r=o.kept}return{testables:r,filteredOut:n,projectRootPath:i}}};L2=yZ([Qe(),vZ(0,Je(SZ)),vZ(1,Je(CU.TSAgent)),vZ(2,Je(d2)),vZ(3,Je(D2)),vZ(4,Je(O2)),vZ(5,Je(c2)),vZ(6,Je(u2)),vZ(7,Je(p2)),_Z(`design:paramtypes`,[typeof(k2=SZ!==void 0&&SZ)==`function`?k2:Object,Object,typeof(A2=d2!==void 0&&d2)==`function`?A2:Object,typeof(j2=D2!==void 0&&D2)==`function`?j2:Object,typeof(M2=O2!==void 0&&O2)==`function`?M2:Object,typeof(N2=c2!==void 0&&c2)==`function`?N2:Object,typeof(P2=u2!==void 0&&u2)==`function`?P2:Object,typeof(F2=p2!==void 0&&p2)==`function`?F2:Object])],L2);var R2,z2,B2;let V2=class{constructor(e,t,n){this.configService=e,this.apiService=t,this.authStorage=n,this.authStorage.setRefreshTokenCallback(async()=>{await this.login()})}async login(){let e=this.configService.getConfigValueOrThrow(`secretToken`,`API key is required but not configured`);try{let{idToken:t}=await this.apiService.post(`auth/v2/sign-in-with-secret-token`,{secret:e});return this.authStorage.setJWTToken(t),t}catch{throw Error(`Failed to get JWT token by secret`)}}};V2=yZ([Qe(),vZ(0,Je(SZ)),vZ(1,Je(Y0)),vZ(2,Je(K0)),_Z(`design:paramtypes`,[typeof(R2=SZ!==void 0&&SZ)==`function`?R2:Object,typeof(z2=Y0!==void 0&&Y0)==`function`?z2:Object,typeof(B2=K0!==void 0&&K0)==`function`?B2:Object])],V2);var H2;let U2=class{constructor(e,t){this.tsAgent=e,this.logger=t}async analyzeChangedMethods(e,t,n){try{this.logger.info(`Analyzing coverage for ${t.length} changed methods with threshold ${n.coverageThreshold}%`);let r=[],i=0,a=0,o=0,s=this.groupChangedMethodsByFile(t);for(let[t,c]of Object.entries(s)){let s=this.findFileCoverage(e,t);if((0,z.isDefined)(s)){let e=this.processFileWithCoverage(t,c,s,n);r.push(...e.testables),i+=e.analyzed,a++}else{let e=this.processFileWithoutCoverage(t,c);r.push(...e.testables),i+=e.analyzed,o++}}let c={testables:r,totalAnalyzed:i,filteredCount:r.length,filesWithCoverage:a,filesWithoutCoverage:o};return this.logger.info(`Changed methods analysis complete: ${c.filteredCount}/${c.totalAnalyzed} methods below threshold across ${a+o} files`),c}catch(e){throw e instanceof Error?(this.logger.error(`Failed to analyze changed methods: ${e.message}`),e):Error(`Unknown error occurred while analyzing changed methods`)}}processFileWithCoverage(e,t,n,r){let i=[],a=0;for(let o of t){if(o.changeType===`deleted`||!o.canCreateTests)continue;let t=this.findTestableInCoverage(n,o);(0,z.isDefined)(t)?(a++,this.shouldIncludeTestable(t,r)&&i.push({name:t.name,percentage:t.percentage,filePath:e,reason:this.getFilterReason(t)})):(a++,i.push({name:o.name??`unknown`,percentage:null,filePath:e,reason:`no-coverage`}))}return{testables:i,analyzed:a}}processFileWithoutCoverage(e,t){let n=t.filter(e=>e.changeType!==`deleted`&&e.canCreateTests),r=n.map(t=>({name:t.name??`unknown`,percentage:null,filePath:e,reason:`no-coverage`}));return this.logger.debug(`No coverage data found for file: ${e}`),{testables:r,analyzed:n.length}}async analyzeChangedFiles(e,t,n){try{this.logger.info(`Analyzing coverage for ${t.length} changed files with threshold ${n.coverageThreshold}%`);let r=[],i=0,a=0,o=0;for(let s of t){let t=this.findFileCoverage(e,s);if((0,z.isDefined)(t)){a++;let e=await this.filterOutClasses(s,t.testables??[]),o=this.filterTestablesForFile(t,s,n),c=await this.filterOutClasses(s,o);r.push(...c),i+=e.length??0,(0,z.isEmpty)(c)||this.logger.debug(`File ${s}: ${c.length}/${e.length??0} testables below threshold`)}else o++,this.logger.debug(`No coverage data found for file: ${s}`)}let s={testables:r,totalAnalyzed:i,filteredCount:r.length,filesWithCoverage:a,filesWithoutCoverage:o};return this.logger.info(`Coverage analysis complete: ${s.filteredCount}/${s.totalAnalyzed} testables below threshold across ${s.filesWithCoverage} files`),s}catch(e){throw e instanceof Error?(this.logger.error(`Failed to analyze coverage: ${e.message}`),e):Error(`Unknown error occurred while analyzing coverage`)}}findFileCoverage(e,t){let n=t.startsWith(`/`)?t:`/${t}`;return(0,z.isDefined)(e[n])?e[n]:null}filterTestablesForFile(e,t,n){let r=[];for(let i of e.testables??[])if(this.shouldIncludeTestable(i,n)){let e=this.getFilterReason(i);r.push({name:i.name,percentage:i.percentage,filePath:t,reason:e})}return r}shouldIncludeTestable(e,t){return!!(e.percentage===null||e.percentage===0||(0,z.isDefined)(e.percentage)&&e.percentage<t.coverageThreshold)}getFilterReason(e){return e.percentage===null?`no-coverage`:e.percentage===0?`zero-coverage`:`below-threshold`}async calculatePRCoverage(e,t){if(!(0,z.isEmpty)(e))try{let n=await this.tsAgent.getCoverageForFiles(e),r=t?`before`:`after`;return this.logger.debug(`PR Coverage (${r}): ${n.percentage}% (${n.coveredStatements}/${n.totalStatements} statements)`),n}catch(e){this.logger.warn(`Failed to calculate PR coverage: ${e instanceof Error?e.message:`Unknown error`}`);return}}async filterOutClasses(e,t){let n=await this.tsAgent.getTestables(e);if((0,z.isEmpty)(n)||!(0,z.isDefined)(n[0]))return this.logger.warn(`getTestables returned empty for ${e}, keeping all testables`),t;let[,r]=n[0],i=r.filter(e=>e.type!==`class`),a=new Set(i.map(e=>e.name));return t.filter(e=>a.has(e.name))}groupChangedMethodsByFile(e){let t={};for(let n of e)(0,z.isDefined)(t[n.filePath])||(t[n.filePath]=[]),t[n.filePath].push(n);return t}findTestableInCoverage(e,t){return(0,z.isDefined)(e.testables)?e.testables.find(e=>{let n=e.name===t.name,r=`parentName`in e?e.parentName===t.parentName:!(0,z.isDefined)(t.parentName);return n&&r})??null:null}};U2=yZ([Qe(),vZ(0,Je(CU.TSAgent)),vZ(1,Je(xZ)),_Z(`design:paramtypes`,[typeof(H2=SU.TSAgent!==void 0&&SU.TSAgent)==`function`?H2:Object,Object])],U2);function W2(e,t){return h2(e,`package.json`,t)??void 0}function G2(e,t){try{return m.default.existsSync(e)?m.default.readFileSync(e,`utf8`):void 0}catch(n){t.warn(`Failed to read file ${e}: ${n instanceof Error?n.message:`Unknown error`}`);return}}async function K2(e,t,n){let r=W2(e,t),i=(await(0,SU.findLintConfigPath)(t)).path??void 0,a=(0,z.isDefined)(r)?G2(r,n):void 0,o=(0,z.isDefined)(i)?G2(i,n):void 0;return(0,z.isDefined)(r)&&n.info(`Found package.json at: ${r}`),(0,z.isDefined)(i)&&n.info(`Found lint config at: ${i}`),{packageJsonPath:r,packageJsonContent:a,lintConfigPath:i,lintConfigContent:o}}const q2={detectProjectConfigs:K2};var J2,Y2;let X2=class{constructor(e,t,n){this.apiService=e,this.configService=t,this.logger=n}async detectAndSaveConfigs(e){try{let t=this.configService.getConfigValue(`rootPath`),n=await q2.detectProjectConfigs(t,t,this.logger);if(!(0,z.isDefined)(n.packageJsonContent)&&!(0,z.isDefined)(n.lintConfigContent))return;await this.apiService.patch(`api/v1/github-repos/configs`,{owner:e.owner,repo:e.repository,packageJson:n.packageJsonContent,lintConfig:n.lintConfigContent})}catch(e){this.logger.warn(`Failed to detect and save project configs: ${e instanceof Error?e.message:`Unknown error`}`)}}};X2=yZ([Qe(),vZ(0,Je(Y0)),vZ(1,Je(SZ)),vZ(2,Je(xZ)),_Z(`design:paramtypes`,[typeof(J2=Y0!==void 0&&Y0)==`function`?J2:Object,typeof(Y2=SZ!==void 0&&SZ)==`function`?Y2:Object,Object])],X2);var Z2,Q2,jte,$2,e4,t4,n4,r4,i4,a4;let o4=class{workflowRunId;teamId;initialCoverageTree;resultCommitSha;constructor(e,t,n,r,i,a,o,s,c,l,u){this.configService=e,this.authService=t,this.apiService=n,this.gitService=r,this.coverageAnalysisService=i,this.summaryService=a,this.tsAgent=o,this.workflowService=s,this.scmHostService=c,this.repoConfigService=l,this.logger=u}async login(){try{this.logger.info(`Trying login to API...`);let e=await this.authService.login();await this.tsAgent.init(e),this.logger.info(`Successfully authenticated with the API`);try{this.teamId=(await this.apiService.get(`api/v1/user/me`)).team?.id}catch(e){this.logger.warn(`Failed to fetch user info: `+(e instanceof Error?e.message:`Unknown error`))}}catch(e){throw this.logger.error(`Failed to authenticate:`+(e instanceof Error?e.message:`Unknown error`)),e}}async logStart(){try{let e=await this.gitService.getGitInfo();this.logger.debug(`Git info: `+JSON.stringify(e));try{let t=await this.workflowService.logStartOperation(e);return this.tsAgent.updateContext({git:{...e,workflowRunId:t}}),this.workflowRunId=t,await this.repoConfigService.detectAndSaveConfigs(e),t}catch(e){throw e instanceof o0||e instanceof a0||this.logger.warn(`Failed to log start operation: ${e instanceof Error?e.message:`Unknown error`}`),e}}catch(e){throw e instanceof o0||e instanceof a0||this.logger.error(`Failed to retrieve git info or log start operation:`+(e instanceof Error?e.message:`Unknown error`)),e}}async generateInitialCoverage(){this.logger.verbose(`Try to reuse coverage...`);let e=await this.workflowService.getCoverageFromWorkflowOrUndefined(this.workflowRunId);if((0,z.isDefined)(e))return await this.tsAgent.setCoverage(e),this.initialCoverageTree=e,(0,z.isDefined)(this.workflowRunId)&&await this.workflowService.saveCoverageToWorkflow(this.workflowRunId,`before`,{}),this.logger.verbose(`Reused coverage: `+(e[`/`]?.percentage??0)+`%`),this.summaryService.setCoverageData(e[`/`]?.percentage??0,e[`/`]?.percentage??0),e;{this.logger.verbose(`Generating initial coverage...`),await this.tsAgent.generateCoverage();let e=await this.tsAgent.getCoverageTree();if(!(0,z.isDefined)(e))throw Error(`Failed to generate initial coverage tree`);return this.initialCoverageTree=e,(0,z.isDefined)(this.workflowRunId)&&await this.workflowService.saveCoverageToWorkflow(this.workflowRunId,`before`,{coverage:e}),this.logger.verbose(`Initial coverage: `+(e[`/`]?.percentage??0)+`%`),this.summaryService.setCoverageData(e[`/`]?.percentage??0,e[`/`]?.percentage??0),e}}async logEndOperation(e){if((0,z.isDefined)(this.workflowRunId))try{let t=this.summaryService.getWorkflowRunOutput();await this.workflowService.logEndOperation(this.workflowRunId,e,t,this.resultCommitSha),this.logger.info(`Successfully logged workflow end`)}catch(e){this.logger.warn(`Failed to log workflow end: `+(e instanceof Error?e.message:`Unknown error`))}}getWorkflowRunIdOrThrow(){if(!(0,z.isDefined)(this.workflowRunId))throw Error(`Workflow run ID is not set, call logStart() first`);return this.workflowRunId}getInitialCoverageTreeOrThrow(){if(!(0,z.isDefined)(this.initialCoverageTree))throw Error(`Initial coverage tree is not set, call generateInitialCoverage() first`);return this.initialCoverageTree}getInitialCoverageTreeOrUndefined(){return this.initialCoverageTree}async countAllMethodsInFiles(e){let t=(0,z.uniq)(e).map(async e=>{try{return await this.tsAgent.getAllMethodsCount(e)}catch(t){return this.logger.debug(`Failed to count methods in `+e+`: `+(t instanceof Error?t.message:`Unknown error`)),0}});return(await Promise.all(t)).reduce((e,t)=>e+t,0)}};o4=yZ([Qe(),vZ(0,Je(SZ)),vZ(1,Je(V2)),vZ(2,Je(Y0)),vZ(3,Je(IZ)),vZ(4,Je(U2)),vZ(5,Je(TZ)),vZ(6,Je(CU.TSAgent)),vZ(7,Je(Q0)),vZ(8,Je(CU.SCMHostService)),vZ(9,Je(X2)),vZ(10,Je(xZ)),_Z(`design:paramtypes`,[typeof(Z2=SZ!==void 0&&SZ)==`function`?Z2:Object,typeof(Q2=V2!==void 0&&V2)==`function`?Q2:Object,typeof(jte=Y0!==void 0&&Y0)==`function`?jte:Object,typeof($2=IZ!==void 0&&IZ)==`function`?$2:Object,typeof(e4=U2!==void 0&&U2)==`function`?e4:Object,typeof(t4=TZ!==void 0&&TZ)==`function`?t4:Object,typeof(n4=SU.TSAgent!==void 0&&SU.TSAgent)==`function`?n4:Object,typeof(r4=Q0!==void 0&&Q0)==`function`?r4:Object,typeof(i4=AZ!==void 0&&AZ)==`function`?i4:Object,typeof(a4=X2!==void 0&&X2)==`function`?a4:Object,Object])],o4);var s4,c4,l4;const u4=e=>e instanceof Error&&(e.message===`Operation aborted`||e.name===`AbortError`);let d4=class extends o4{changedFiles=[];prCoverage={before:{percentage:null,totalStatements:0,coveredStatements:0},after:{percentage:null,totalStatements:0,coveredStatements:0}};_successSourceFiles=[];_successTestFiles=[];testableToGenerateService;postGenerationService;postCommitCoverageService;getWorkflowRunId(){return this.workflowRunId}getSuccessSourceFiles(){return this._successSourceFiles}getSuccessTestFiles(){return this._successTestFiles}getChangedFiles(){return this.changedFiles}async runFlow(e){let t=e?.shouldDeferPostGeneration??!1,n,r=!1,i=!1,a;try{if(await this.login(),await this.logStart(),await this.isOwnCommit()){this.logger.info(`Skipping: commit was generated by Early AI`),i=!0;return}await this.validateCommitBranch();let e=await this.getRawChangedFiles(),n=this.configService.getConfigValue(`rootPath`),r=this.configService.getConfigValue(`gitTopLevel`)??n;this.logger.info(`Discovering untested functions`);let o=await this.testableToGenerateService.getTestablesToGenerate({changedFiles:e,rootPath:n,gitTopLevel:r,hasDiffContext:this.hasDiffContext(),baseRevision:await this.getBaseRevision(),changedMethodsOnly:this.configService.getConfigValue(`changedMethodsOnly`),coverageReport:{tree:this.initialCoverageTree,threshold:this.configService.getConfigValue(`coverageThreshold`)}});if((0,z.isEmpty)(o.testables)){this.logPublicMethodsSummary(o.testables,o.filteredOut),await this.setSummaryChangedFilesData(e.length,o),this.handleNoFilteredTestables();let t=[...new Set(o.filteredOut.map(e=>e.filePath))];await this.runCoverageIfEnabled({changedSourceFiles:t,successState:CZ.NoGeneration});return}if(this.updateRootPath(o.projectRootPath),this.changedFiles=[...new Set([...o.testables.map(e=>e.filePath),...o.filteredOut.filter(e=>e.reason===`has-test-file`).map(e=>e.filePath)])],await this.setSummaryChangedFilesData(e.length,o),o.filteredOut.filter(e=>e.reason===`limit-reached`).length>0){let e=this.configService.getConfigValue(`maxTestables`);this.summaryService.addWarning(`Limited to ${e} functions: test generation was capped due to maximum function limit.`)}this.logPublicMethodsSummary(o.testables,o.filteredOut);let s=[...o.testables];if(a=await this.generateTests(s),!t){let e=await this.performAutoCommit();this.summaryService.setTestGenerationData({generated:a.generated,succeeded:a.succeeded,failed:a.failed,successMethodsCount:a.successMethodsCount,committedFilesCount:e,greenTests:a.greenTests,redTests:a.redTests}),await this.runCoverageIfEnabled({changedSourceFiles:[...this.changedFiles],successTestFiles:this._successTestFiles,successState:CZ.Success})}return a}catch(e){if(e instanceof o0){this.logger.warn(`Duplicate SHA execution detected. Skipping.`);return}if(e instanceof a0){this.logger.warn(`Workflow canceled. Skipping.`),r=!0;return}return u4(e)?(n=`Operation timed out`,this.logger.warn(`Workflow aborted due to timeout`)):(n=e instanceof Error?e.message:`Unknown error`,this.logger.error(`Agent flow failed: `+n)),a}finally{!t&&(0,z.isDefined)(this.workflowRunId)&&!r&&!i&&(this.summaryService.setPRCoverageData(this.prCoverage.before,this.prCoverage.after),await this.scmHostService.safePostSummaryToPr(),await this.logEndOperation(n))}}async setSummaryChangedFilesData(e,t){let n=[...new Set([...t.testables.map(e=>e.filePath),...t.filteredOut.map(e=>e.filePath)])],r=await this.countAllMethodsInFiles(n),i=t.filteredOut.filter(e=>e.reason===`has-test-file`||e.reason===`above-coverage-threshold`||e.reason===`limit-reached`),a=t.filteredOut.filter(e=>e.reason===`has-test-file`);this.summaryService.setChangedFilesData({changedFilesCount:e,candidateFilesCount:n.length,functionCount:r,publicMethodCount:t.testables.length+i.length,methodsWithTestFileCount:a.length,publicMethodWithoutTestFile:t.testables.length,publicMethods:[...t.testables.map(e=>({name:e.testable.name??`unknown`,filePath:e.filePath})),...i.map(e=>({name:e.testableName??`unknown`,filePath:e.filePath}))],methodsWithoutTestFile:t.testables.map(e=>({name:e.testable.name??`unknown`,filePath:e.filePath}))})}async isOwnCommit(){try{let e=this.configService.getConfigValue(`commitHash`);return(await this.gitService.getCommitMessage(e)).startsWith(`chore: add early-catch tests`)}catch{return!1}}handleNoFilteredTestables(){this.logger.warn(`No filtered untested functions`),this.prCoverage.after=this.prCoverage.before}logPublicMethodsSummary(e,t){let n=new Set([`has-test-file`,`above-coverage-threshold`,`limit-reached`]),r=t.filter(e=>n.has(e.reason)),i=t.filter(e=>!n.has(e.reason)),a=e.length+r.length,o=new Set([...e.map(e=>e.filePath),...r.map(e=>e.filePath)]).size;a>0&&(this.logger.info(``),this.logger.info(`📊 Public methods summary (${a} method${a===1?``:`s`} across ${o} file${o===1?``:`s`}):`),this.logger.info(``)),(0,z.isEmpty)(e)||this.logMethodTree(`🔧 Generating tests for`,e.map(e=>({filePath:e.filePath,name:e.testable.name??`unknown`})));let s=r.filter(e=>e.reason===`has-test-file`);(0,z.isEmpty)(s)||this.logMethodTree(`🧪 With existing Early tests`,s.map(e=>({filePath:e.filePath,name:e.testableName??`unknown`})));let c=r.filter(e=>e.reason===`above-coverage-threshold`);(0,z.isEmpty)(c)||this.logMethodTree(`✅ Above coverage threshold`,c.map(e=>({filePath:e.filePath,name:e.testableName??`unknown`})));let l=r.filter(e=>e.reason===`limit-reached`);(0,z.isEmpty)(l)||this.logMethodTree(`⚠️ Skipped - over limit`,l.map(e=>({filePath:e.filePath,name:e.testableName??`unknown`}))),(0,z.isEmpty)(i)||this.logFileTree(i)}logMethodTree(e,t){this.logger.info(`${e} (${t.length}):`);let n=new Map;for(let e of t){let t=n.get(e.filePath)??[];t.push(e.name),n.set(e.filePath,t)}let r=[...n.entries()];for(let e=0;e<r.length;e++){let[t,n]=r[e],i=e===r.length-1,a=i?` └── `:` ├── `,o=i?` `:` │ `;this.logger.info(`${a}${t} (${n.length}):`);for(let e=0;e<n.length;e++){let t=e===n.length-1?`└── `:`├── `;this.logger.info(`${o}${t}${n[e]}`)}}this.logger.info(``)}logFileTree(e){let t=new Map;for(let n of e){let e=t.get(n.reason)??[];e.push(n.filePath),t.set(n.reason,e)}let n={"not-code-file":`not-code-file`,"excluded-pattern":`excluded-pattern`,"outside-project":`outside-project`,"no-testables":`no-testables`,"private-method":`private-method`,"method-not-changed":`method-not-changed`};this.logger.info(`📁 Files skipped (${e.length}):`);let r=[...t.entries()];for(let e=0;e<r.length;e++){let[t,i]=r[e],a=e===r.length-1,o=a?` └── `:` ├── `,s=a?` `:` │ `,c=n[t]??t;this.logger.info(`${o}${c} (${i.length}):`);for(let e=0;e<i.length;e++){let t=e===i.length-1?`└── `:`├── `;this.logger.info(`${s}${t}${i[e]}`)}}this.logger.info(``)}async validateCommitBranch(){if(!this.configService.getConfigValue(`autoCommit`))return;let e=this.configService.getConfigValue(`refName`);if(e&&!await this.gitService.checkRefExists(e))throw Error(`Branch '${e}' does not exist on remote. Create it before running with --auto-commit.`)}async runCoverageIfEnabled(e){if(this.configService.getConfigValue(`skipCoverageAfter`)){this.logger.verbose(`Skipping final coverage generation (--skip-coverage-after flag is set)`),this.summaryService.setCoverageState(CZ.Skipped);return}let t=await this.postCommitCoverageService.calculateCoverage({changedSourceFiles:e.changedSourceFiles,successTestFiles:e.successTestFiles});t.success?(this.prCoverage={before:t.before.prCoverage,after:t.after.prCoverage},this.summaryService.setPRCoverageData(t.before.prCoverage,t.after.prCoverage),(0,z.isDefined)(this.workflowRunId)&&(await this.workflowService.saveCoverageToWorkflow(this.workflowRunId,`before`,{prCoverage:t.before.prCoverage}),await this.workflowService.saveCoverageToWorkflow(this.workflowRunId,`after`,{prCoverage:t.after.prCoverage})),this.summaryService.setCoverageState(e.successState)):((0,z.isDefined)(this.workflowRunId)&&(await this.workflowService.saveCoverageToWorkflow(this.workflowRunId,`before`,{}),await this.workflowService.saveCoverageToWorkflow(this.workflowRunId,`after`,{})),this.summaryService.setCoverageState(CZ.Failed,t.reason))}async performAutoCommit(){let e=this.configService.getConfigValueOrThrow(`autoCommit`);if(this.summaryService.setAutoCommitStatus(e),e){await this.postGenerationService.cleanupBlankEarlyFiles();let e=this.configService.getConfigValue(`refName`),t=await this.gitService.commitFiles(e);return(0,z.isDefined)(t.resultCommitSha)&&(this.resultCommitSha=t.resultCommitSha),t.committedFiles.length}else return this.logger.info(`Auto-commit is disabled - skipping commit step`),0}async _generateInitialCoverageForTestGeneration(){await this.generateInitialCoverage(),await this.savePRCoverageBefore()}async savePRCoverageBefore(){if((0,z.isDefined)(this.workflowRunId))try{let e=await this.coverageAnalysisService.calculatePRCoverage(this.changedFiles,!0);(0,z.isDefined)(e)&&(this.prCoverage.before=e),await this.workflowService.saveCoverageToWorkflow(this.workflowRunId,`before`,{prCoverage:e}),this.logger.debug(`Successfully saved initial coverage to workflow run`)}catch(e){this.logger.warn(`Failed to save initial coverage: `+(e instanceof Error?e.message:`Unknown error`))}}async generateTests(e){let t=new Set(e),n=[],r=0,i=0,a=0,o=0;try{await this.tsAgent.bulkGenerateTests(e,(s,c,l)=>{o++;let u=wU.default.basename(s.filePath);(0,z.isDefined)(c)&&c.greenTestsCount>0?(t.delete(s),r+=c.greenTestsCount,i+=c.redTestsCount,a+=c.greyTestsCount,this._successSourceFiles.push(s.filePath),(0,z.isDefined)(l)&&(0,z.isDefined)(l.testFilePath)&&this._successTestFiles.push(l.testFilePath),this.logger.info(` [${o}/${e.length}] ✓ ${s.testable.name} (${u}) — ${c.greenTestsCount} passing, ${c.redTestsCount} skipped`)):((0,z.isDefined)(l)&&(0,z.isDefined)(l.testFilePath)&&n.push(l.testFilePath),this.logger.info(` [${o}/${e.length}] ✗ ${s.testable.name} (${u}) — no tests generated`))})}catch(e){if(u4(e))this.logger.warn(`Test generation was partially aborted due to timeout`);else throw e}for(let e of n)try{await h.unlink(e),this.logger.debug(`Removed failed test file: ${e}`)}catch{this.logger.debug(`Could not remove failed test file: ${e}`)}let s=e.length-t.size,c=t.size,l=await this.gitService.getEarlyFiles();return this.logger.info(``),this.logger.info(`✅ Test generation complete for ${s} functions`),c>0&&this.logger.info(`❌ ${c} functions were not generated`),this.logger.info(``),this.logger.info(`================`),this.logger.info(`Overall summary:`),this.logger.info(`================`),this.logger.info(``),this.logger.info(`✅ ${r} tests passing`),this.logger.info(`⚠️ ${i} tests skipped`),this.logger.info(`❌ ${a} tests could not be fixed autonomously (yet)`),this.logger.info(``),{generated:e.length,succeeded:s,failed:c,successMethodsCount:l.length,greenTests:r,redTests:i}}async generateFinalCoverageAndLog({methodsAffected:e,committedFiles:t}){let n=this.getWorkflowRunIdOrThrow();this.logger.verbose(`Generating final coverage...`),await this.tsAgent.generateCoverage();let r=await this.tsAgent.getCoverageTree();if(!(0,z.isDefined)(r))throw Error(`Failed to generate final coverage tree`);let i=r[`/`]?.percentage??0,a=this.getInitialCoverageTreeOrUndefined(),o=a?.[`/`]?.percentage??0;(0,z.isDefined)(a)||this.summaryService.setCoverageBeforeSkipped(),this.summaryService.setCoverageData(o,i);let s=(0,z.isDefined)(a)?`${o}% -> ${i}%`:`skipped`;this.logger.verbose(`Final coverage: `+i+`%, Coverage comparison: `+s);try{let i=await this.coverageAnalysisService.calculatePRCoverage(this.changedFiles,!1);(0,z.isDefined)(i)&&(this.prCoverage.after=i),await this.workflowService.saveCoverageToWorkflow(n,`after`,{coverage:r,prCoverage:i,methodsAffected:e,committedFiles:t}),this.logger.debug(`Successfully saved final coverage to workflow run`)}catch(e){this.logger.warn(`Failed to save final coverage: `+(e instanceof Error?e.message:`Unknown error`))}}updateRootPath(e){this.tsAgent.updateRootPath(e),this.configService.updateConfigValue(`rootPath`,e)}};yZ([Je(L2),_Z(`design:type`,typeof(s4=L2!==void 0&&L2)==`function`?s4:Object)],d4.prototype,`testableToGenerateService`,void 0),yZ([Je(r2),_Z(`design:type`,typeof(c4=r2!==void 0&&r2)==`function`?c4:Object)],d4.prototype,`postGenerationService`,void 0),yZ([Je(l0),_Z(`design:type`,typeof(l4=l0!==void 0&&l0)==`function`?l4:Object)],d4.prototype,`postCommitCoverageService`,void 0),d4=yZ([Qe(),at({extendConstructorArguments:!0,extendProperties:!0})],d4);let f4=class extends d4{async getRawChangedFiles(){return this.gitService.getChangedFilesForCommitWithStatus({absolute:!0})}hasDiffContext(){return!0}async getBaseRevision(){let e=this.configService.getConfigValue(`baseRef`);if((0,z.isDefined)(e))return this.gitService.getBaseRevision({baseBranch:e});let t=this.configService.getConfigValue(`commitHash`);if((0,z.isDefined)(t))return`${t}^`}async logStart(){try{let e=this.configService.getConfigValue(`commitHash`),t=await this.gitService.getCommitMessage(e);t&&this.configService.updateConfigValue(`commitName`,t)}catch(e){this.logger.warn(`Failed to retrieve commit message, continuing without it: `+(e instanceof Error?e.message:`Unknown error`))}try{let e=await this.scmHostService.getContributorAvatarUrl();(0,z.isDefined)(e)&&this.configService.updateConfigValue(`contributorAvatarUrl`,e)}catch(e){this.logger.warn(`Failed to retrieve contributor avatar, continuing without it: `+(e instanceof Error?e.message:`Unknown error`))}return await super.logStart()}};f4=yZ([Qe(),at({extendConstructorArguments:!0,extendProperties:!0})],f4);function p4(e){let t=e.command(TU.COMMIT).alias(`generate-commit`).description(`Generate tests for the current project in commit context`);return oe(t,`--commit-hash <hash>`,`Commit hash`,{envName:`COMMIT_HASH`,isRequired:!0}),oe(t,`--ref-name <ref>`,`Head branch name for the commit`,{envName:`REF_NAME`,isRequired:!0}),oe(t,`--base-ref <ref>`,`optional base refrence for comparison`,{envName:`BASE_REF`}),oe(t,`-s, --test-structure <structure>`,`Test file structure`,{envName:`TEST_STRUCTURE`,def:`siblingFolder`}),oe(t,`-f, --test-framework <framework>`,`Test framework to use`,{envName:`TEST_FRAMEWORK`,def:`jest`}),oe(t,`--test-suffix <suffix>`,`Test file suffix`,{envName:`TEST_FILE_SUFFIX`,def:`test`}),oe(t,`--test-file-naming <naming>`,`Test file naming convention`,{envName:`TEST_FILE_NAMING`,def:`camelCase`}),oe(t,`-c, --max-concurrency <number>`,`Number of concurrent workers (1-4)`,{envName:`MAX_CONCURRENCY`,def:`3`}),oe(t,`--auto-commit <boolean>`,`Whether to auto-commit files`,{envName:`AUTO_COMMIT`,def:`true`}),oe(t,`--auto-commit-skip-ci <boolean>`,`Append [skip ci] to auto-commit message`,{envName:`AUTO_COMMIT_SKIP_CI`,def:`true`}),oe(t,`--test-command <command>`,`Custom test command to run`,{envName:`TEST_COMMAND`}),oe(t,`--coverage-command <command>`,`Custom coverage command to run`,{envName:`COVERAGE_COMMAND`}),oe(t,`--lint-command <command>`,`Custom lint command to run`,{envName:`LINT_COMMAND`}),oe(t,`--prettier-command <command>`,`Custom prettier command to run`,{envName:`PRETTIER_COMMAND`}),oe(t,`--disable-lint-rules <boolean>`,`Whether to disable failed lint rules in test files`,{envName:`DISABLE_LINT_RULES`,def:`false`}),oe(t,`--git-org <org>`,`Git organization name`,{envName:`GIT_ORG`}),oe(t,`--git-repo <repo>`,`Git repository name`,{envName:`GIT_REPO`}),oe(t,`--git-user-email <email>`,`Git user email for auto commit`,{envName:`GIT_USER_EMAIL`}),oe(t,`--git-user-name <name>`,`Git user name for auto commit`,{envName:`GIT_USER_NAME`}),oe(t,`--scm-provider <provider>`,`SCM provider (e.g., github, bitbucket)`,{envName:`SCM_PROVIDER`,def:`github`}),oe(t,`--keep-error-tests <boolean>`,`Whether to keep error tests`,{envName:`KEEP_ERROR_TESTS`,def:`false`}),oe(t,`--keep-failed-tests <boolean>`,`Whether to keep failed tests`,{envName:`KEEP_FAILED_TESTS`,def:`false`}),oe(t,`--conditional-keep <boolean>`,`Whether to return the last generated test result even when no green tests were produced`,{envName:`CONDITIONAL_KEEP`,def:`false`}),oe(t,`--continue-on-test-errors <boolean>`,`Whether to continue on test errors`,{envName:`CONTINUE_ON_TEST_ERRORS`,def:`true`}),oe(t,`--changed-methods-only <boolean>`,`Generate tests only for changed methods, not all methods in changed files`,{envName:`CHANGED_METHODS_ONLY`,def:`true`}),oe(t,`--skip-coverage-after <boolean>`,`Skip final coverage generation after test generation`,{envName:`SKIP_COVERAGE_AFTER`,def:`false`}),oe(t,`--max-testables <number>`,`Maximum number of testables to generate`,{envName:`MAX_TESTABLES`}),oe(t,`--per-function-timeout <number>`,`Per function timeout in milliseconds`,{envName:`PER_FUNCTION_TIMEOUT`}),oe(t,`--coverage-threshold <number>`,`Coverage threshold percentage (0-100)`,{envName:`COVERAGE_THRESHOLD`,def:`0`}),oe(t,`--reuse-coverage <boolean>`,`Whether to reuse coverage`,{envName:`REUSE_COVERAGE`,def:`false`}),oe(t,`--reuse-coverage-max-runs <number>`,`Max number of runs to reuse coverage (1-10)`,{envName:`REUSE_COVERAGE_MAX_RUNS`,def:`10`}),oe(t,`--experimental-agent-sdk <boolean>`,`Use experimental Agent SDK for test generation`,{envName:`EXPERIMENTAL_AGENT_SDK`,def:`true`}),oe(t,`--compress-output <boolean>`,`Compress test runner output to reduce token consumption`,{envName:`COMPRESS_OUTPUT`,def:`false`}),t.addHelpText(`after`,`
32493
32493
  Examples:
32494
32494
  $ early generate-commit --api-key your-api-key --token your-token --commit-hash abc123 --ref-name feature/new-feature
32495
32495
  $ early generate-commit -k your-api-key -f jest -s siblingFolder --test-command "npm run test -- $early_filename" --coverage-command "npm run coverage -- --coverageReporters=json --coverageDirectory=$early_coverage_dir"
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@earlyai/cli",
3
- "version": "2.8.0",
3
+ "version": "2.8.1",
4
4
  "description": "early cli",
5
5
  "main": "dist/index.cjs",
6
6
  "bin": {