allwright 1.2.1 → 1.2.2

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/bin/allwright.js +14 -14
  2. package/package.json +1 -1
package/bin/allwright.js CHANGED
@@ -20,7 +20,7 @@ Expecting one of '${n.join("', '")}'`);return this._lifeCycleHooks[e]?this._life
20
20
  `),this.outputHelp({error:!0}));let n=t||{},s=n.exitCode||1,i=n.code||"commander.error";this._exit(s,i,e)}_parseOptionsEnv(){this.options.forEach(e=>{if(e.envVar&&e.envVar in se.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()}`,se.env[e.envVar]):this.emit(`optionEnv:${e.name()}`))}})}_parseOptionsImplied(){let e=new Od(this.options),t=n=>this.getOptionValue(n)!==void 0&&!["default","implied"].includes(this.getOptionValueSource(n));this.options.filter(n=>n.implied!==void 0&&t(n.attributeName())&&e.valueFromOption(this.getOptionValue(n.attributeName()),n)).forEach(n=>{Object.keys(n.implied).filter(s=>!t(s)).forEach(s=>{this.setOptionValueWithSource(s,n.implied[s],"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=o=>{let a=o.attributeName(),c=this.getOptionValue(a),l=this.options.find(p=>p.negate&&a===p.attributeName()),d=this.options.find(p=>!p.negate&&a===p.attributeName());return l&&(l.presetArg===void 0&&c===!1||l.presetArg!==void 0&&c===l.presetArg)?l:d||o},s=o=>{let a=n(o),c=a.attributeName();return this.getOptionValueSource(c)==="env"?`environment variable '${a.envVar}'`:`option '${a.flags}'`},i=`error: ${s(e)} cannot be used with ${s(t)}`;this.error(i,{code:"commander.conflictingOption"})}unknownOption(e){if(this._allowUnknownOption)return;let t="";if(e.startsWith("--")&&this._showSuggestionAfterError){let s=[],i=this;do{let o=i.createHelp().visibleOptions(i).filter(a=>a.long).map(a=>a.long);s=s.concat(o),i=i.parent}while(i&&!i._enablePositionalOptions);t=ca(e,s)}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",i=`error: too many arguments${this.parent?` for '${this.name()}'`:""}. Expected ${t} argument${n} but got ${e.length}.`;this.error(i,{code:"commander.excessArguments"})}unknownCommand(){let e=this.args[0],t="";if(this._showSuggestionAfterError){let s=[];this.createHelp().visibleCommands(this).forEach(i=>{s.push(i.name()),i.alias()&&s.push(i.alias())}),t=ca(e,s)}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=t||"-V, --version",n=n||"output the version number";let s=this.createOption(t,n);return this._versionOptionName=s.attributeName(),this._registerOption(s),this.on("option:"+s.name(),()=>{this._outputConfiguration.writeOut(`${e}
21
21
  `),this._exit(0,"commander.version",e)}),this}description(e,t){return e===void 0&&t===void 0?this._description:(this._description=e,t&&(this._argsDescription=t),this)}summary(e){return e===void 0?this._summary:(this._summary=e,this)}alias(e){if(e===void 0)return this._aliases[0];let t=this;if(this.commands.length!==0&&this.commands[this.commands.length-1]._executableHandler&&(t=this.commands[this.commands.length-1]),e===t._name)throw new Error("Command alias can't be the same as its name");let n=this.parent?._findCommand(e);if(n){let s=[n.name()].concat(n.aliases()).join("|");throw new Error(`cannot add alias '${e}' to command '${this.name()}' as already have command '${s}'`)}return t._aliases.push(e),this}aliases(e){return e===void 0?this._aliases:(e.forEach(t=>this.alias(t)),this)}usage(e){if(e===void 0){if(this._usage)return this._usage;let t=this.registeredArguments.map(n=>Pd(n));return[].concat(this.options.length||this._helpOption!==null?"[options]":[],this.commands.length?"[command]":[],this.registeredArguments.length?t:[]).join(" ")}return this._usage=e,this}name(e){return e===void 0?this._name:(this._name=e,this)}nameFromFilename(e){return this._name=Qe.basename(e,Qe.extname(e)),this}executableDir(e){return e===void 0?this._executableDir:(this._executableDir=e,this)}helpInformation(e){let t=this.createHelp();return t.helpWidth===void 0&&(t.helpWidth=e&&e.error?this._outputConfiguration.getErrHelpWidth():this._outputConfiguration.getOutHelpWidth()),t.formatHelp(this,t)}_getHelpContext(e){e=e||{};let t={error:!!e.error},n;return t.error?n=s=>this._outputConfiguration.writeErr(s):n=s=>this._outputConfiguration.writeOut(s),t.write=e.write||n,t.command=this,t}outputHelp(e){let t;typeof e=="function"&&(t=e,e=void 0);let n=this._getHelpContext(e);this._getCommandAndAncestors().reverse().forEach(i=>i.emit("beforeAllHelp",n)),this.emit("beforeHelp",n);let s=this.helpInformation(n);if(t&&(s=t(s),typeof s!="string"&&!Buffer.isBuffer(s)))throw new Error("outputHelp callback must return a string or a Buffer");n.write(s),this._getHelpOption()?.long&&this.emit(this._getHelpOption().long),this.emit("afterHelp",n),this._getCommandAndAncestors().forEach(i=>i.emit("afterAllHelp",n))}helpOption(e,t){return typeof e=="boolean"?(e?this._helpOption=this._helpOption??void 0:this._helpOption=null,this):(e=e??"-h, --help",t=t??"display help for command",this._helpOption=this.createOption(e,t),this)}_getHelpOption(){return this._helpOption===void 0&&this.helpOption(void 0,void 0),this._helpOption}addHelpOption(e){return this._helpOption=e,this}help(e){this.outputHelp(e);let t=se.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 new Error(`Unexpected value for position to addHelpText.
22
22
  Expecting one of '${n.join("', '")}'`);let s=`${e}Help`;return this.on(s,i=>{let o;typeof t=="function"?o=t({error:i.error,command:i.command}):o=t,o&&i.write(`${o}
23
- `)}),this}_outputHelpIfRequested(e){let t=this._getHelpOption();t&&e.find(s=>t.is(s))&&(this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)"))}};function la(r){return r.map(e=>{if(!e.startsWith("--inspect"))return e;let t,n="127.0.0.1",s="9229",i;return(i=e.match(/^(--inspect(-brk)?)$/))!==null?t=i[1]:(i=e.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null?(t=i[1],/^\d+$/.test(i[3])?s=i[3]:n=i[3]):(i=e.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null&&(t=i[1],n=i[3],s=i[4]),t&&s!=="0"?`${t}=${n}:${parseInt(s)+1}`:e})}da.Command=vi});var ga=Y(Ee=>{var{Argument:fa}=Qn(),{Command:bi}=ha(),{CommanderError:Nd,InvalidArgumentError:pa}=vn(),{Help:Md}=di(),{Option:ma}=mi();Ee.program=new bi;Ee.createCommand=r=>new bi(r);Ee.createOption=(r,e)=>new ma(r,e);Ee.createArgument=(r,e)=>new fa(r,e);Ee.Command=bi;Ee.Option=ma;Ee.Argument=fa;Ee.Help=Md;Ee.CommanderError=Nd;Ee.InvalidArgumentError=pa;Ee.InvalidOptionArgumentError=pa});var xn=Y(te=>{"use strict";Object.defineProperty(te,"__esModule",{value:!0});te.getParsedType=te.ZodParsedType=te.objectUtil=te.util=void 0;var Ei;(function(r){r.assertEqual=s=>{};function e(s){}r.assertIs=e;function t(s){throw new Error}r.assertNever=t,r.arrayToEnum=s=>{let i={};for(let o of s)i[o]=o;return i},r.getValidEnumValues=s=>{let i=r.objectKeys(s).filter(a=>typeof s[s[a]]!="number"),o={};for(let a of i)o[a]=s[a];return r.objectValues(o)},r.objectValues=s=>r.objectKeys(s).map(function(i){return s[i]}),r.objectKeys=typeof Object.keys=="function"?s=>Object.keys(s):s=>{let i=[];for(let o in s)Object.prototype.hasOwnProperty.call(s,o)&&i.push(o);return i},r.find=(s,i)=>{for(let o of s)if(i(o))return o},r.isInteger=typeof Number.isInteger=="function"?s=>Number.isInteger(s):s=>typeof s=="number"&&Number.isFinite(s)&&Math.floor(s)===s;function n(s,i=" | "){return s.map(o=>typeof o=="string"?`'${o}'`:o).join(i)}r.joinValues=n,r.jsonStringifyReplacer=(s,i)=>typeof i=="bigint"?i.toString():i})(Ei||(te.util=Ei={}));var za;(function(r){r.mergeShapes=(e,t)=>({...e,...t})})(za||(te.objectUtil=za={}));te.ZodParsedType=Ei.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]);var ef=r=>{switch(typeof r){case"undefined":return te.ZodParsedType.undefined;case"string":return te.ZodParsedType.string;case"number":return Number.isNaN(r)?te.ZodParsedType.nan:te.ZodParsedType.number;case"boolean":return te.ZodParsedType.boolean;case"function":return te.ZodParsedType.function;case"bigint":return te.ZodParsedType.bigint;case"symbol":return te.ZodParsedType.symbol;case"object":return Array.isArray(r)?te.ZodParsedType.array:r===null?te.ZodParsedType.null:r.then&&typeof r.then=="function"&&r.catch&&typeof r.catch=="function"?te.ZodParsedType.promise:typeof Map<"u"&&r instanceof Map?te.ZodParsedType.map:typeof Set<"u"&&r instanceof Set?te.ZodParsedType.set:typeof Date<"u"&&r instanceof Date?te.ZodParsedType.date:te.ZodParsedType.object;default:return te.ZodParsedType.unknown}};te.getParsedType=ef});var hs=Y(Tt=>{"use strict";Object.defineProperty(Tt,"__esModule",{value:!0});Tt.ZodError=Tt.quotelessJson=Tt.ZodIssueCode=void 0;var Ua=xn();Tt.ZodIssueCode=Ua.util.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]);var tf=r=>JSON.stringify(r,null,2).replace(/"([^"]+)":/g,"$1:");Tt.quotelessJson=tf;var Cn=class r extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=n=>{this.issues=[...this.issues,n]},this.addIssues=(n=[])=>{this.issues=[...this.issues,...n]};let t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name="ZodError",this.issues=e}format(e){let t=e||function(i){return i.message},n={_errors:[]},s=i=>{for(let o of i.issues)if(o.code==="invalid_union")o.unionErrors.map(s);else if(o.code==="invalid_return_type")s(o.returnTypeError);else if(o.code==="invalid_arguments")s(o.argumentsError);else if(o.path.length===0)n._errors.push(t(o));else{let a=n,c=0;for(;c<o.path.length;){let l=o.path[c];c===o.path.length-1?(a[l]=a[l]||{_errors:[]},a[l]._errors.push(t(o))):a[l]=a[l]||{_errors:[]},a=a[l],c++}}};return s(this),n}static assert(e){if(!(e instanceof r))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,Ua.util.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=t=>t.message){let t={},n=[];for(let s of this.issues)if(s.path.length>0){let i=s.path[0];t[i]=t[i]||[],t[i].push(e(s))}else n.push(e(s));return{formErrors:n,fieldErrors:t}}get formErrors(){return this.flatten()}};Tt.ZodError=Cn;Cn.create=r=>new Cn(r)});var Ai=Y(Ii=>{"use strict";Object.defineProperty(Ii,"__esModule",{value:!0});var fe=hs(),Yt=xn(),rf=(r,e)=>{let t;switch(r.code){case fe.ZodIssueCode.invalid_type:r.received===Yt.ZodParsedType.undefined?t="Required":t=`Expected ${r.expected}, received ${r.received}`;break;case fe.ZodIssueCode.invalid_literal:t=`Invalid literal value, expected ${JSON.stringify(r.expected,Yt.util.jsonStringifyReplacer)}`;break;case fe.ZodIssueCode.unrecognized_keys:t=`Unrecognized key(s) in object: ${Yt.util.joinValues(r.keys,", ")}`;break;case fe.ZodIssueCode.invalid_union:t="Invalid input";break;case fe.ZodIssueCode.invalid_union_discriminator:t=`Invalid discriminator value. Expected ${Yt.util.joinValues(r.options)}`;break;case fe.ZodIssueCode.invalid_enum_value:t=`Invalid enum value. Expected ${Yt.util.joinValues(r.options)}, received '${r.received}'`;break;case fe.ZodIssueCode.invalid_arguments:t="Invalid function arguments";break;case fe.ZodIssueCode.invalid_return_type:t="Invalid function return type";break;case fe.ZodIssueCode.invalid_date:t="Invalid date";break;case fe.ZodIssueCode.invalid_string:typeof r.validation=="object"?"includes"in r.validation?(t=`Invalid input: must include "${r.validation.includes}"`,typeof r.validation.position=="number"&&(t=`${t} at one or more positions greater than or equal to ${r.validation.position}`)):"startsWith"in r.validation?t=`Invalid input: must start with "${r.validation.startsWith}"`:"endsWith"in r.validation?t=`Invalid input: must end with "${r.validation.endsWith}"`:Yt.util.assertNever(r.validation):r.validation!=="regex"?t=`Invalid ${r.validation}`:t="Invalid";break;case fe.ZodIssueCode.too_small:r.type==="array"?t=`Array must contain ${r.exact?"exactly":r.inclusive?"at least":"more than"} ${r.minimum} element(s)`:r.type==="string"?t=`String must contain ${r.exact?"exactly":r.inclusive?"at least":"over"} ${r.minimum} character(s)`:r.type==="number"?t=`Number must be ${r.exact?"exactly equal to ":r.inclusive?"greater than or equal to ":"greater than "}${r.minimum}`:r.type==="bigint"?t=`Number must be ${r.exact?"exactly equal to ":r.inclusive?"greater than or equal to ":"greater than "}${r.minimum}`:r.type==="date"?t=`Date must be ${r.exact?"exactly equal to ":r.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(r.minimum))}`:t="Invalid input";break;case fe.ZodIssueCode.too_big:r.type==="array"?t=`Array must contain ${r.exact?"exactly":r.inclusive?"at most":"less than"} ${r.maximum} element(s)`:r.type==="string"?t=`String must contain ${r.exact?"exactly":r.inclusive?"at most":"under"} ${r.maximum} character(s)`:r.type==="number"?t=`Number must be ${r.exact?"exactly":r.inclusive?"less than or equal to":"less than"} ${r.maximum}`:r.type==="bigint"?t=`BigInt must be ${r.exact?"exactly":r.inclusive?"less than or equal to":"less than"} ${r.maximum}`:r.type==="date"?t=`Date must be ${r.exact?"exactly":r.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(r.maximum))}`:t="Invalid input";break;case fe.ZodIssueCode.custom:t="Invalid input";break;case fe.ZodIssueCode.invalid_intersection_types:t="Intersection results could not be merged";break;case fe.ZodIssueCode.not_multiple_of:t=`Number must be a multiple of ${r.multipleOf}`;break;case fe.ZodIssueCode.not_finite:t="Number must be finite";break;default:t=e.defaultError,Yt.util.assertNever(r)}return{message:t}};Ii.default=rf});var fs=Y(xt=>{"use strict";var nf=xt&&xt.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(xt,"__esModule",{value:!0});xt.defaultErrorMap=void 0;xt.setErrorMap=sf;xt.getErrorMap=of;var qa=nf(Ai());xt.defaultErrorMap=qa.default;var Ba=qa.default;function sf(r){Ba=r}function of(){return Ba}});var $i=Y(X=>{"use strict";var af=X&&X.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(X,"__esModule",{value:!0});X.isAsync=X.isValid=X.isDirty=X.isAborted=X.OK=X.DIRTY=X.INVALID=X.ParseStatus=X.EMPTY_PATH=X.makeIssue=void 0;X.addIssueToContext=lf;var uf=fs(),Fa=af(Ai()),cf=r=>{let{data:e,path:t,errorMaps:n,issueData:s}=r,i=[...t,...s.path||[]],o={...s,path:i};if(s.message!==void 0)return{...s,path:i,message:s.message};let a="",c=n.filter(l=>!!l).slice().reverse();for(let l of c)a=l(o,{data:e,defaultError:a}).message;return{...s,path:i,message:a}};X.makeIssue=cf;X.EMPTY_PATH=[];function lf(r,e){let t=(0,uf.getErrorMap)(),n=(0,X.makeIssue)({issueData:e,data:r.data,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,t,t===Fa.default?void 0:Fa.default].filter(s=>!!s)});r.common.issues.push(n)}var Ri=class r{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,t){let n=[];for(let s of t){if(s.status==="aborted")return X.INVALID;s.status==="dirty"&&e.dirty(),n.push(s.value)}return{status:e.value,value:n}}static async mergeObjectAsync(e,t){let n=[];for(let s of t){let i=await s.key,o=await s.value;n.push({key:i,value:o})}return r.mergeObjectSync(e,n)}static mergeObjectSync(e,t){let n={};for(let s of t){let{key:i,value:o}=s;if(i.status==="aborted"||o.status==="aborted")return X.INVALID;i.status==="dirty"&&e.dirty(),o.status==="dirty"&&e.dirty(),i.value!=="__proto__"&&(typeof o.value<"u"||s.alwaysSet)&&(n[i.value]=o.value)}return{status:e.value,value:n}}};X.ParseStatus=Ri;X.INVALID=Object.freeze({status:"aborted"});var df=r=>({status:"dirty",value:r});X.DIRTY=df;var hf=r=>({status:"valid",value:r});X.OK=hf;var ff=r=>r.status==="aborted";X.isAborted=ff;var pf=r=>r.status==="dirty";X.isDirty=pf;var mf=r=>r.status==="valid";X.isValid=mf;var gf=r=>typeof Promise<"u"&&r instanceof Promise;X.isAsync=gf});var Ka=Y(Za=>{"use strict";Object.defineProperty(Za,"__esModule",{value:!0})});var Ha=Y(ps=>{"use strict";Object.defineProperty(ps,"__esModule",{value:!0});ps.errorUtil=void 0;var Va;(function(r){r.errToObj=e=>typeof e=="string"?{message:e}:e||{},r.toString=e=>typeof e=="string"?e:e?.message})(Va||(ps.errorUtil=Va={}))});var iu=Y(y=>{"use strict";Object.defineProperty(y,"__esModule",{value:!0});y.discriminatedUnion=y.date=y.boolean=y.bigint=y.array=y.any=y.coerce=y.ZodFirstPartyTypeKind=y.late=y.ZodSchema=y.Schema=y.ZodReadonly=y.ZodPipeline=y.ZodBranded=y.BRAND=y.ZodNaN=y.ZodCatch=y.ZodDefault=y.ZodNullable=y.ZodOptional=y.ZodTransformer=y.ZodEffects=y.ZodPromise=y.ZodNativeEnum=y.ZodEnum=y.ZodLiteral=y.ZodLazy=y.ZodFunction=y.ZodSet=y.ZodMap=y.ZodRecord=y.ZodTuple=y.ZodIntersection=y.ZodDiscriminatedUnion=y.ZodUnion=y.ZodObject=y.ZodArray=y.ZodVoid=y.ZodNever=y.ZodUnknown=y.ZodAny=y.ZodNull=y.ZodUndefined=y.ZodSymbol=y.ZodDate=y.ZodBoolean=y.ZodBigInt=y.ZodNumber=y.ZodString=y.ZodType=void 0;y.NEVER=y.void=y.unknown=y.union=y.undefined=y.tuple=y.transformer=y.symbol=y.string=y.strictObject=y.set=y.record=y.promise=y.preprocess=y.pipeline=y.ostring=y.optional=y.onumber=y.oboolean=y.object=y.number=y.nullable=y.null=y.never=y.nativeEnum=y.nan=y.map=y.literal=y.lazy=y.intersection=y.instanceof=y.function=y.enum=y.effect=void 0;y.datetimeRegex=Xa;y.custom=eu;var C=hs(),ms=fs(),O=Ha(),_=$i(),E=xn(),Pe=class{constructor(e,t,n,s){this._cachedPath=[],this.parent=e,this.data=t,this._path=n,this._key=s}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},Ga=(r,e)=>{if((0,_.isValid)(e))return{success:!0,data:e.value};if(!r.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let t=new C.ZodError(r.common.issues);return this._error=t,this._error}}};function B(r){if(!r)return{};let{errorMap:e,invalid_type_error:t,required_error:n,description:s}=r;if(e&&(t||n))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:s}:{errorMap:(o,a)=>{let{message:c}=r;return o.code==="invalid_enum_value"?{message:c??a.defaultError}:typeof a.data>"u"?{message:c??n??a.defaultError}:o.code!=="invalid_type"?{message:a.defaultError}:{message:c??t??a.defaultError}},description:s}}var F=class{get description(){return this._def.description}_getType(e){return(0,E.getParsedType)(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:(0,E.getParsedType)(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new _.ParseStatus,ctx:{common:e.parent.common,data:e.data,parsedType:(0,E.getParsedType)(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let t=this._parse(e);if((0,_.isAsync)(t))throw new Error("Synchronous parse encountered promise.");return t}_parseAsync(e){let t=this._parse(e);return Promise.resolve(t)}parse(e,t){let n=this.safeParse(e,t);if(n.success)return n.data;throw n.error}safeParse(e,t){let n={common:{issues:[],async:t?.async??!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:(0,E.getParsedType)(e)},s=this._parseSync({data:e,path:n.path,parent:n});return Ga(n,s)}"~validate"(e){let t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:(0,E.getParsedType)(e)};if(!this["~standard"].async)try{let n=this._parseSync({data:e,path:[],parent:t});return(0,_.isValid)(n)?{value:n.value}:{issues:t.common.issues}}catch(n){n?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then(n=>(0,_.isValid)(n)?{value:n.value}:{issues:t.common.issues})}async parseAsync(e,t){let n=await this.safeParseAsync(e,t);if(n.success)return n.data;throw n.error}async safeParseAsync(e,t){let n={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:(0,E.getParsedType)(e)},s=this._parse({data:e,path:n.path,parent:n}),i=await((0,_.isAsync)(s)?s:Promise.resolve(s));return Ga(n,i)}refine(e,t){let n=s=>typeof t=="string"||typeof t>"u"?{message:t}:typeof t=="function"?t(s):t;return this._refinement((s,i)=>{let o=e(s),a=()=>i.addIssue({code:C.ZodIssueCode.custom,...n(s)});return typeof Promise<"u"&&o instanceof Promise?o.then(c=>c?!0:(a(),!1)):o?!0:(a(),!1)})}refinement(e,t){return this._refinement((n,s)=>e(n)?!0:(s.addIssue(typeof t=="function"?t(n,s):t),!1))}_refinement(e){return new ke({schema:this,typeName:L.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:t=>this["~validate"](t)}}optional(){return $e.create(this,this._def)}nullable(){return He.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return ut.create(this)}promise(){return It.create(this,this._def)}or(e){return sr.create([this,e],this._def)}and(e){return ir.create(this,e,this._def)}transform(e){return new ke({...B(this._def),schema:this,typeName:L.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let t=typeof e=="function"?e:()=>e;return new lr({...B(this._def),innerType:this,defaultValue:t,typeName:L.ZodDefault})}brand(){return new En({typeName:L.ZodBranded,type:this,...B(this._def)})}catch(e){let t=typeof e=="function"?e:()=>e;return new dr({...B(this._def),innerType:this,catchValue:t,typeName:L.ZodCatch})}describe(e){let t=this.constructor;return new t({...this._def,description:e})}pipe(e){return In.create(this,e)}readonly(){return hr.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}};y.ZodType=F;y.Schema=F;y.ZodSchema=F;var yf=/^c[^\s-]{8,}$/i,_f=/^[0-9a-z]+$/,vf=/^[0-9A-HJKMNP-TV-Z]{26}$/i,bf=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,wf=/^[a-z0-9_-]{21}$/i,kf=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Sf=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,Tf=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,xf="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",Pi,Cf=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,Ef=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,If=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,Af=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,Rf=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,$f=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Ja="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",Pf=new RegExp(`^${Ja}$`);function Ya(r){let e="[0-5]\\d";r.precision?e=`${e}\\.\\d{${r.precision}}`:r.precision==null&&(e=`${e}(\\.\\d+)?`);let t=r.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${t}`}function jf(r){return new RegExp(`^${Ya(r)}$`)}function Xa(r){let e=`${Ja}T${Ya(r)}`,t=[];return t.push(r.local?"Z?":"Z"),r.offset&&t.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${t.join("|")})`,new RegExp(`^${e}$`)}function Of(r,e){return!!((e==="v4"||!e)&&Cf.test(r)||(e==="v6"||!e)&&If.test(r))}function Nf(r,e){if(!kf.test(r))return!1;try{let[t]=r.split(".");if(!t)return!1;let n=t.replace(/-/g,"+").replace(/_/g,"/").padEnd(t.length+(4-t.length%4)%4,"="),s=JSON.parse(atob(n));return!(typeof s!="object"||s===null||"typ"in s&&s?.typ!=="JWT"||!s.alg||e&&s.alg!==e)}catch{return!1}}function Mf(r,e){return!!((e==="v4"||!e)&&Ef.test(r)||(e==="v6"||!e)&&Af.test(r))}var Ct=class r extends F{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==E.ZodParsedType.string){let i=this._getOrReturnCtx(e);return(0,_.addIssueToContext)(i,{code:C.ZodIssueCode.invalid_type,expected:E.ZodParsedType.string,received:i.parsedType}),_.INVALID}let n=new _.ParseStatus,s;for(let i of this._def.checks)if(i.kind==="min")e.data.length<i.value&&(s=this._getOrReturnCtx(e,s),(0,_.addIssueToContext)(s,{code:C.ZodIssueCode.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),n.dirty());else if(i.kind==="max")e.data.length>i.value&&(s=this._getOrReturnCtx(e,s),(0,_.addIssueToContext)(s,{code:C.ZodIssueCode.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),n.dirty());else if(i.kind==="length"){let o=e.data.length>i.value,a=e.data.length<i.value;(o||a)&&(s=this._getOrReturnCtx(e,s),o?(0,_.addIssueToContext)(s,{code:C.ZodIssueCode.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}):a&&(0,_.addIssueToContext)(s,{code:C.ZodIssueCode.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}),n.dirty())}else if(i.kind==="email")Tf.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,_.addIssueToContext)(s,{validation:"email",code:C.ZodIssueCode.invalid_string,message:i.message}),n.dirty());else if(i.kind==="emoji")Pi||(Pi=new RegExp(xf,"u")),Pi.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,_.addIssueToContext)(s,{validation:"emoji",code:C.ZodIssueCode.invalid_string,message:i.message}),n.dirty());else if(i.kind==="uuid")bf.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,_.addIssueToContext)(s,{validation:"uuid",code:C.ZodIssueCode.invalid_string,message:i.message}),n.dirty());else if(i.kind==="nanoid")wf.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,_.addIssueToContext)(s,{validation:"nanoid",code:C.ZodIssueCode.invalid_string,message:i.message}),n.dirty());else if(i.kind==="cuid")yf.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,_.addIssueToContext)(s,{validation:"cuid",code:C.ZodIssueCode.invalid_string,message:i.message}),n.dirty());else if(i.kind==="cuid2")_f.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,_.addIssueToContext)(s,{validation:"cuid2",code:C.ZodIssueCode.invalid_string,message:i.message}),n.dirty());else if(i.kind==="ulid")vf.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,_.addIssueToContext)(s,{validation:"ulid",code:C.ZodIssueCode.invalid_string,message:i.message}),n.dirty());else if(i.kind==="url")try{new URL(e.data)}catch{s=this._getOrReturnCtx(e,s),(0,_.addIssueToContext)(s,{validation:"url",code:C.ZodIssueCode.invalid_string,message:i.message}),n.dirty()}else i.kind==="regex"?(i.regex.lastIndex=0,i.regex.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,_.addIssueToContext)(s,{validation:"regex",code:C.ZodIssueCode.invalid_string,message:i.message}),n.dirty())):i.kind==="trim"?e.data=e.data.trim():i.kind==="includes"?e.data.includes(i.value,i.position)||(s=this._getOrReturnCtx(e,s),(0,_.addIssueToContext)(s,{code:C.ZodIssueCode.invalid_string,validation:{includes:i.value,position:i.position},message:i.message}),n.dirty()):i.kind==="toLowerCase"?e.data=e.data.toLowerCase():i.kind==="toUpperCase"?e.data=e.data.toUpperCase():i.kind==="startsWith"?e.data.startsWith(i.value)||(s=this._getOrReturnCtx(e,s),(0,_.addIssueToContext)(s,{code:C.ZodIssueCode.invalid_string,validation:{startsWith:i.value},message:i.message}),n.dirty()):i.kind==="endsWith"?e.data.endsWith(i.value)||(s=this._getOrReturnCtx(e,s),(0,_.addIssueToContext)(s,{code:C.ZodIssueCode.invalid_string,validation:{endsWith:i.value},message:i.message}),n.dirty()):i.kind==="datetime"?Xa(i).test(e.data)||(s=this._getOrReturnCtx(e,s),(0,_.addIssueToContext)(s,{code:C.ZodIssueCode.invalid_string,validation:"datetime",message:i.message}),n.dirty()):i.kind==="date"?Pf.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,_.addIssueToContext)(s,{code:C.ZodIssueCode.invalid_string,validation:"date",message:i.message}),n.dirty()):i.kind==="time"?jf(i).test(e.data)||(s=this._getOrReturnCtx(e,s),(0,_.addIssueToContext)(s,{code:C.ZodIssueCode.invalid_string,validation:"time",message:i.message}),n.dirty()):i.kind==="duration"?Sf.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,_.addIssueToContext)(s,{validation:"duration",code:C.ZodIssueCode.invalid_string,message:i.message}),n.dirty()):i.kind==="ip"?Of(e.data,i.version)||(s=this._getOrReturnCtx(e,s),(0,_.addIssueToContext)(s,{validation:"ip",code:C.ZodIssueCode.invalid_string,message:i.message}),n.dirty()):i.kind==="jwt"?Nf(e.data,i.alg)||(s=this._getOrReturnCtx(e,s),(0,_.addIssueToContext)(s,{validation:"jwt",code:C.ZodIssueCode.invalid_string,message:i.message}),n.dirty()):i.kind==="cidr"?Mf(e.data,i.version)||(s=this._getOrReturnCtx(e,s),(0,_.addIssueToContext)(s,{validation:"cidr",code:C.ZodIssueCode.invalid_string,message:i.message}),n.dirty()):i.kind==="base64"?Rf.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,_.addIssueToContext)(s,{validation:"base64",code:C.ZodIssueCode.invalid_string,message:i.message}),n.dirty()):i.kind==="base64url"?$f.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,_.addIssueToContext)(s,{validation:"base64url",code:C.ZodIssueCode.invalid_string,message:i.message}),n.dirty()):E.util.assertNever(i);return{status:n.value,value:e.data}}_regex(e,t,n){return this.refinement(s=>e.test(s),{validation:t,code:C.ZodIssueCode.invalid_string,...O.errorUtil.errToObj(n)})}_addCheck(e){return new r({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...O.errorUtil.errToObj(e)})}url(e){return this._addCheck({kind:"url",...O.errorUtil.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...O.errorUtil.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...O.errorUtil.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...O.errorUtil.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...O.errorUtil.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...O.errorUtil.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...O.errorUtil.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...O.errorUtil.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...O.errorUtil.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...O.errorUtil.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...O.errorUtil.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...O.errorUtil.errToObj(e)})}datetime(e){return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...O.errorUtil.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof e?.precision>"u"?null:e?.precision,...O.errorUtil.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...O.errorUtil.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...O.errorUtil.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t?.position,...O.errorUtil.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...O.errorUtil.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...O.errorUtil.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...O.errorUtil.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...O.errorUtil.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...O.errorUtil.errToObj(t)})}nonempty(e){return this.min(1,O.errorUtil.errToObj(e))}trim(){return new r({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new r({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new r({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}};y.ZodString=Ct;Ct.create=r=>new Ct({checks:[],typeName:L.ZodString,coerce:r?.coerce??!1,...B(r)});function Df(r,e){let t=(r.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,s=t>n?t:n,i=Number.parseInt(r.toFixed(s).replace(".","")),o=Number.parseInt(e.toFixed(s).replace(".",""));return i%o/10**s}var Xt=class r extends F{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==E.ZodParsedType.number){let i=this._getOrReturnCtx(e);return(0,_.addIssueToContext)(i,{code:C.ZodIssueCode.invalid_type,expected:E.ZodParsedType.number,received:i.parsedType}),_.INVALID}let n,s=new _.ParseStatus;for(let i of this._def.checks)i.kind==="int"?E.util.isInteger(e.data)||(n=this._getOrReturnCtx(e,n),(0,_.addIssueToContext)(n,{code:C.ZodIssueCode.invalid_type,expected:"integer",received:"float",message:i.message}),s.dirty()):i.kind==="min"?(i.inclusive?e.data<i.value:e.data<=i.value)&&(n=this._getOrReturnCtx(e,n),(0,_.addIssueToContext)(n,{code:C.ZodIssueCode.too_small,minimum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),s.dirty()):i.kind==="max"?(i.inclusive?e.data>i.value:e.data>=i.value)&&(n=this._getOrReturnCtx(e,n),(0,_.addIssueToContext)(n,{code:C.ZodIssueCode.too_big,maximum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),s.dirty()):i.kind==="multipleOf"?Df(e.data,i.value)!==0&&(n=this._getOrReturnCtx(e,n),(0,_.addIssueToContext)(n,{code:C.ZodIssueCode.not_multiple_of,multipleOf:i.value,message:i.message}),s.dirty()):i.kind==="finite"?Number.isFinite(e.data)||(n=this._getOrReturnCtx(e,n),(0,_.addIssueToContext)(n,{code:C.ZodIssueCode.not_finite,message:i.message}),s.dirty()):E.util.assertNever(i);return{status:s.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,O.errorUtil.toString(t))}gt(e,t){return this.setLimit("min",e,!1,O.errorUtil.toString(t))}lte(e,t){return this.setLimit("max",e,!0,O.errorUtil.toString(t))}lt(e,t){return this.setLimit("max",e,!1,O.errorUtil.toString(t))}setLimit(e,t,n,s){return new r({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:n,message:O.errorUtil.toString(s)}]})}_addCheck(e){return new r({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:O.errorUtil.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:O.errorUtil.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:O.errorUtil.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:O.errorUtil.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:O.errorUtil.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:O.errorUtil.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:O.errorUtil.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:O.errorUtil.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:O.errorUtil.toString(e)})}get minValue(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&E.util.isInteger(e.value))}get isFinite(){let e=null,t=null;for(let n of this._def.checks){if(n.kind==="finite"||n.kind==="int"||n.kind==="multipleOf")return!0;n.kind==="min"?(t===null||n.value>t)&&(t=n.value):n.kind==="max"&&(e===null||n.value<e)&&(e=n.value)}return Number.isFinite(t)&&Number.isFinite(e)}};y.ZodNumber=Xt;Xt.create=r=>new Xt({checks:[],typeName:L.ZodNumber,coerce:r?.coerce||!1,...B(r)});var Qt=class r extends F{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==E.ZodParsedType.bigint)return this._getInvalidInput(e);let n,s=new _.ParseStatus;for(let i of this._def.checks)i.kind==="min"?(i.inclusive?e.data<i.value:e.data<=i.value)&&(n=this._getOrReturnCtx(e,n),(0,_.addIssueToContext)(n,{code:C.ZodIssueCode.too_small,type:"bigint",minimum:i.value,inclusive:i.inclusive,message:i.message}),s.dirty()):i.kind==="max"?(i.inclusive?e.data>i.value:e.data>=i.value)&&(n=this._getOrReturnCtx(e,n),(0,_.addIssueToContext)(n,{code:C.ZodIssueCode.too_big,type:"bigint",maximum:i.value,inclusive:i.inclusive,message:i.message}),s.dirty()):i.kind==="multipleOf"?e.data%i.value!==BigInt(0)&&(n=this._getOrReturnCtx(e,n),(0,_.addIssueToContext)(n,{code:C.ZodIssueCode.not_multiple_of,multipleOf:i.value,message:i.message}),s.dirty()):E.util.assertNever(i);return{status:s.value,value:e.data}}_getInvalidInput(e){let t=this._getOrReturnCtx(e);return(0,_.addIssueToContext)(t,{code:C.ZodIssueCode.invalid_type,expected:E.ZodParsedType.bigint,received:t.parsedType}),_.INVALID}gte(e,t){return this.setLimit("min",e,!0,O.errorUtil.toString(t))}gt(e,t){return this.setLimit("min",e,!1,O.errorUtil.toString(t))}lte(e,t){return this.setLimit("max",e,!0,O.errorUtil.toString(t))}lt(e,t){return this.setLimit("max",e,!1,O.errorUtil.toString(t))}setLimit(e,t,n,s){return new r({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:n,message:O.errorUtil.toString(s)}]})}_addCheck(e){return new r({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:O.errorUtil.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:O.errorUtil.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:O.errorUtil.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:O.errorUtil.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:O.errorUtil.toString(t)})}get minValue(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}};y.ZodBigInt=Qt;Qt.create=r=>new Qt({checks:[],typeName:L.ZodBigInt,coerce:r?.coerce??!1,...B(r)});var er=class extends F{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==E.ZodParsedType.boolean){let n=this._getOrReturnCtx(e);return(0,_.addIssueToContext)(n,{code:C.ZodIssueCode.invalid_type,expected:E.ZodParsedType.boolean,received:n.parsedType}),_.INVALID}return(0,_.OK)(e.data)}};y.ZodBoolean=er;er.create=r=>new er({typeName:L.ZodBoolean,coerce:r?.coerce||!1,...B(r)});var tr=class r extends F{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==E.ZodParsedType.date){let i=this._getOrReturnCtx(e);return(0,_.addIssueToContext)(i,{code:C.ZodIssueCode.invalid_type,expected:E.ZodParsedType.date,received:i.parsedType}),_.INVALID}if(Number.isNaN(e.data.getTime())){let i=this._getOrReturnCtx(e);return(0,_.addIssueToContext)(i,{code:C.ZodIssueCode.invalid_date}),_.INVALID}let n=new _.ParseStatus,s;for(let i of this._def.checks)i.kind==="min"?e.data.getTime()<i.value&&(s=this._getOrReturnCtx(e,s),(0,_.addIssueToContext)(s,{code:C.ZodIssueCode.too_small,message:i.message,inclusive:!0,exact:!1,minimum:i.value,type:"date"}),n.dirty()):i.kind==="max"?e.data.getTime()>i.value&&(s=this._getOrReturnCtx(e,s),(0,_.addIssueToContext)(s,{code:C.ZodIssueCode.too_big,message:i.message,inclusive:!0,exact:!1,maximum:i.value,type:"date"}),n.dirty()):E.util.assertNever(i);return{status:n.value,value:new Date(e.data.getTime())}}_addCheck(e){return new r({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:O.errorUtil.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:O.errorUtil.toString(t)})}get minDate(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e!=null?new Date(e):null}};y.ZodDate=tr;tr.create=r=>new tr({checks:[],coerce:r?.coerce||!1,typeName:L.ZodDate,...B(r)});var Fr=class extends F{_parse(e){if(this._getType(e)!==E.ZodParsedType.symbol){let n=this._getOrReturnCtx(e);return(0,_.addIssueToContext)(n,{code:C.ZodIssueCode.invalid_type,expected:E.ZodParsedType.symbol,received:n.parsedType}),_.INVALID}return(0,_.OK)(e.data)}};y.ZodSymbol=Fr;Fr.create=r=>new Fr({typeName:L.ZodSymbol,...B(r)});var rr=class extends F{_parse(e){if(this._getType(e)!==E.ZodParsedType.undefined){let n=this._getOrReturnCtx(e);return(0,_.addIssueToContext)(n,{code:C.ZodIssueCode.invalid_type,expected:E.ZodParsedType.undefined,received:n.parsedType}),_.INVALID}return(0,_.OK)(e.data)}};y.ZodUndefined=rr;rr.create=r=>new rr({typeName:L.ZodUndefined,...B(r)});var nr=class extends F{_parse(e){if(this._getType(e)!==E.ZodParsedType.null){let n=this._getOrReturnCtx(e);return(0,_.addIssueToContext)(n,{code:C.ZodIssueCode.invalid_type,expected:E.ZodParsedType.null,received:n.parsedType}),_.INVALID}return(0,_.OK)(e.data)}};y.ZodNull=nr;nr.create=r=>new nr({typeName:L.ZodNull,...B(r)});var Et=class extends F{constructor(){super(...arguments),this._any=!0}_parse(e){return(0,_.OK)(e.data)}};y.ZodAny=Et;Et.create=r=>new Et({typeName:L.ZodAny,...B(r)});var at=class extends F{constructor(){super(...arguments),this._unknown=!0}_parse(e){return(0,_.OK)(e.data)}};y.ZodUnknown=at;at.create=r=>new at({typeName:L.ZodUnknown,...B(r)});var Le=class extends F{_parse(e){let t=this._getOrReturnCtx(e);return(0,_.addIssueToContext)(t,{code:C.ZodIssueCode.invalid_type,expected:E.ZodParsedType.never,received:t.parsedType}),_.INVALID}};y.ZodNever=Le;Le.create=r=>new Le({typeName:L.ZodNever,...B(r)});var Zr=class extends F{_parse(e){if(this._getType(e)!==E.ZodParsedType.undefined){let n=this._getOrReturnCtx(e);return(0,_.addIssueToContext)(n,{code:C.ZodIssueCode.invalid_type,expected:E.ZodParsedType.void,received:n.parsedType}),_.INVALID}return(0,_.OK)(e.data)}};y.ZodVoid=Zr;Zr.create=r=>new Zr({typeName:L.ZodVoid,...B(r)});var ut=class r extends F{_parse(e){let{ctx:t,status:n}=this._processInputParams(e),s=this._def;if(t.parsedType!==E.ZodParsedType.array)return(0,_.addIssueToContext)(t,{code:C.ZodIssueCode.invalid_type,expected:E.ZodParsedType.array,received:t.parsedType}),_.INVALID;if(s.exactLength!==null){let o=t.data.length>s.exactLength.value,a=t.data.length<s.exactLength.value;(o||a)&&((0,_.addIssueToContext)(t,{code:o?C.ZodIssueCode.too_big:C.ZodIssueCode.too_small,minimum:a?s.exactLength.value:void 0,maximum:o?s.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:s.exactLength.message}),n.dirty())}if(s.minLength!==null&&t.data.length<s.minLength.value&&((0,_.addIssueToContext)(t,{code:C.ZodIssueCode.too_small,minimum:s.minLength.value,type:"array",inclusive:!0,exact:!1,message:s.minLength.message}),n.dirty()),s.maxLength!==null&&t.data.length>s.maxLength.value&&((0,_.addIssueToContext)(t,{code:C.ZodIssueCode.too_big,maximum:s.maxLength.value,type:"array",inclusive:!0,exact:!1,message:s.maxLength.message}),n.dirty()),t.common.async)return Promise.all([...t.data].map((o,a)=>s.type._parseAsync(new Pe(t,o,t.path,a)))).then(o=>_.ParseStatus.mergeArray(n,o));let i=[...t.data].map((o,a)=>s.type._parseSync(new Pe(t,o,t.path,a)));return _.ParseStatus.mergeArray(n,i)}get element(){return this._def.type}min(e,t){return new r({...this._def,minLength:{value:e,message:O.errorUtil.toString(t)}})}max(e,t){return new r({...this._def,maxLength:{value:e,message:O.errorUtil.toString(t)}})}length(e,t){return new r({...this._def,exactLength:{value:e,message:O.errorUtil.toString(t)}})}nonempty(e){return this.min(1,e)}};y.ZodArray=ut;ut.create=(r,e)=>new ut({type:r,minLength:null,maxLength:null,exactLength:null,typeName:L.ZodArray,...B(e)});function Br(r){if(r instanceof _e){let e={};for(let t in r.shape){let n=r.shape[t];e[t]=$e.create(Br(n))}return new _e({...r._def,shape:()=>e})}else return r instanceof ut?new ut({...r._def,type:Br(r.element)}):r instanceof $e?$e.create(Br(r.unwrap())):r instanceof He?He.create(Br(r.unwrap())):r instanceof Ve?Ve.create(r.items.map(e=>Br(e))):r}var _e=class r extends F{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape(),t=E.util.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==E.ZodParsedType.object){let l=this._getOrReturnCtx(e);return(0,_.addIssueToContext)(l,{code:C.ZodIssueCode.invalid_type,expected:E.ZodParsedType.object,received:l.parsedType}),_.INVALID}let{status:n,ctx:s}=this._processInputParams(e),{shape:i,keys:o}=this._getCached(),a=[];if(!(this._def.catchall instanceof Le&&this._def.unknownKeys==="strip"))for(let l in s.data)o.includes(l)||a.push(l);let c=[];for(let l of o){let d=i[l],p=s.data[l];c.push({key:{status:"valid",value:l},value:d._parse(new Pe(s,p,s.path,l)),alwaysSet:l in s.data})}if(this._def.catchall instanceof Le){let l=this._def.unknownKeys;if(l==="passthrough")for(let d of a)c.push({key:{status:"valid",value:d},value:{status:"valid",value:s.data[d]}});else if(l==="strict")a.length>0&&((0,_.addIssueToContext)(s,{code:C.ZodIssueCode.unrecognized_keys,keys:a}),n.dirty());else if(l!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let l=this._def.catchall;for(let d of a){let p=s.data[d];c.push({key:{status:"valid",value:d},value:l._parse(new Pe(s,p,s.path,d)),alwaysSet:d in s.data})}}return s.common.async?Promise.resolve().then(async()=>{let l=[];for(let d of c){let p=await d.key,v=await d.value;l.push({key:p,value:v,alwaysSet:d.alwaysSet})}return l}).then(l=>_.ParseStatus.mergeObjectSync(n,l)):_.ParseStatus.mergeObjectSync(n,c)}get shape(){return this._def.shape()}strict(e){return O.errorUtil.errToObj,new r({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(t,n)=>{let s=this._def.errorMap?.(t,n).message??n.defaultError;return t.code==="unrecognized_keys"?{message:O.errorUtil.errToObj(e).message??s}:{message:s}}}:{}})}strip(){return new r({...this._def,unknownKeys:"strip"})}passthrough(){return new r({...this._def,unknownKeys:"passthrough"})}extend(e){return new r({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new r({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:L.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new r({...this._def,catchall:e})}pick(e){let t={};for(let n of E.util.objectKeys(e))e[n]&&this.shape[n]&&(t[n]=this.shape[n]);return new r({...this._def,shape:()=>t})}omit(e){let t={};for(let n of E.util.objectKeys(this.shape))e[n]||(t[n]=this.shape[n]);return new r({...this._def,shape:()=>t})}deepPartial(){return Br(this)}partial(e){let t={};for(let n of E.util.objectKeys(this.shape)){let s=this.shape[n];e&&!e[n]?t[n]=s:t[n]=s.optional()}return new r({...this._def,shape:()=>t})}required(e){let t={};for(let n of E.util.objectKeys(this.shape))if(e&&!e[n])t[n]=this.shape[n];else{let i=this.shape[n];for(;i instanceof $e;)i=i._def.innerType;t[n]=i}return new r({...this._def,shape:()=>t})}keyof(){return Qa(E.util.objectKeys(this.shape))}};y.ZodObject=_e;_e.create=(r,e)=>new _e({shape:()=>r,unknownKeys:"strip",catchall:Le.create(),typeName:L.ZodObject,...B(e)});_e.strictCreate=(r,e)=>new _e({shape:()=>r,unknownKeys:"strict",catchall:Le.create(),typeName:L.ZodObject,...B(e)});_e.lazycreate=(r,e)=>new _e({shape:r,unknownKeys:"strip",catchall:Le.create(),typeName:L.ZodObject,...B(e)});var sr=class extends F{_parse(e){let{ctx:t}=this._processInputParams(e),n=this._def.options;function s(i){for(let a of i)if(a.result.status==="valid")return a.result;for(let a of i)if(a.result.status==="dirty")return t.common.issues.push(...a.ctx.common.issues),a.result;let o=i.map(a=>new C.ZodError(a.ctx.common.issues));return(0,_.addIssueToContext)(t,{code:C.ZodIssueCode.invalid_union,unionErrors:o}),_.INVALID}if(t.common.async)return Promise.all(n.map(async i=>{let o={...t,common:{...t.common,issues:[]},parent:null};return{result:await i._parseAsync({data:t.data,path:t.path,parent:o}),ctx:o}})).then(s);{let i,o=[];for(let c of n){let l={...t,common:{...t.common,issues:[]},parent:null},d=c._parseSync({data:t.data,path:t.path,parent:l});if(d.status==="valid")return d;d.status==="dirty"&&!i&&(i={result:d,ctx:l}),l.common.issues.length&&o.push(l.common.issues)}if(i)return t.common.issues.push(...i.ctx.common.issues),i.result;let a=o.map(c=>new C.ZodError(c));return(0,_.addIssueToContext)(t,{code:C.ZodIssueCode.invalid_union,unionErrors:a}),_.INVALID}}get options(){return this._def.options}};y.ZodUnion=sr;sr.create=(r,e)=>new sr({options:r,typeName:L.ZodUnion,...B(e)});var ot=r=>r instanceof or?ot(r.schema):r instanceof ke?ot(r.innerType()):r instanceof ar?[r.value]:r instanceof ur?r.options:r instanceof cr?E.util.objectValues(r.enum):r instanceof lr?ot(r._def.innerType):r instanceof rr?[void 0]:r instanceof nr?[null]:r instanceof $e?[void 0,...ot(r.unwrap())]:r instanceof He?[null,...ot(r.unwrap())]:r instanceof En||r instanceof hr?ot(r.unwrap()):r instanceof dr?ot(r._def.innerType):[],gs=class r extends F{_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==E.ZodParsedType.object)return(0,_.addIssueToContext)(t,{code:C.ZodIssueCode.invalid_type,expected:E.ZodParsedType.object,received:t.parsedType}),_.INVALID;let n=this.discriminator,s=t.data[n],i=this.optionsMap.get(s);return i?t.common.async?i._parseAsync({data:t.data,path:t.path,parent:t}):i._parseSync({data:t.data,path:t.path,parent:t}):((0,_.addIssueToContext)(t,{code:C.ZodIssueCode.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),_.INVALID)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,t,n){let s=new Map;for(let i of t){let o=ot(i.shape[e]);if(!o.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let a of o){if(s.has(a))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(a)}`);s.set(a,i)}}return new r({typeName:L.ZodDiscriminatedUnion,discriminator:e,options:t,optionsMap:s,...B(n)})}};y.ZodDiscriminatedUnion=gs;function ji(r,e){let t=(0,E.getParsedType)(r),n=(0,E.getParsedType)(e);if(r===e)return{valid:!0,data:r};if(t===E.ZodParsedType.object&&n===E.ZodParsedType.object){let s=E.util.objectKeys(e),i=E.util.objectKeys(r).filter(a=>s.indexOf(a)!==-1),o={...r,...e};for(let a of i){let c=ji(r[a],e[a]);if(!c.valid)return{valid:!1};o[a]=c.data}return{valid:!0,data:o}}else if(t===E.ZodParsedType.array&&n===E.ZodParsedType.array){if(r.length!==e.length)return{valid:!1};let s=[];for(let i=0;i<r.length;i++){let o=r[i],a=e[i],c=ji(o,a);if(!c.valid)return{valid:!1};s.push(c.data)}return{valid:!0,data:s}}else return t===E.ZodParsedType.date&&n===E.ZodParsedType.date&&+r==+e?{valid:!0,data:r}:{valid:!1}}var ir=class extends F{_parse(e){let{status:t,ctx:n}=this._processInputParams(e),s=(i,o)=>{if((0,_.isAborted)(i)||(0,_.isAborted)(o))return _.INVALID;let a=ji(i.value,o.value);return a.valid?(((0,_.isDirty)(i)||(0,_.isDirty)(o))&&t.dirty(),{status:t.value,value:a.data}):((0,_.addIssueToContext)(n,{code:C.ZodIssueCode.invalid_intersection_types}),_.INVALID)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([i,o])=>s(i,o)):s(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}};y.ZodIntersection=ir;ir.create=(r,e,t)=>new ir({left:r,right:e,typeName:L.ZodIntersection,...B(t)});var Ve=class r extends F{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==E.ZodParsedType.array)return(0,_.addIssueToContext)(n,{code:C.ZodIssueCode.invalid_type,expected:E.ZodParsedType.array,received:n.parsedType}),_.INVALID;if(n.data.length<this._def.items.length)return(0,_.addIssueToContext)(n,{code:C.ZodIssueCode.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),_.INVALID;!this._def.rest&&n.data.length>this._def.items.length&&((0,_.addIssueToContext)(n,{code:C.ZodIssueCode.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());let i=[...n.data].map((o,a)=>{let c=this._def.items[a]||this._def.rest;return c?c._parse(new Pe(n,o,n.path,a)):null}).filter(o=>!!o);return n.common.async?Promise.all(i).then(o=>_.ParseStatus.mergeArray(t,o)):_.ParseStatus.mergeArray(t,i)}get items(){return this._def.items}rest(e){return new r({...this._def,rest:e})}};y.ZodTuple=Ve;Ve.create=(r,e)=>{if(!Array.isArray(r))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Ve({items:r,typeName:L.ZodTuple,rest:null,...B(e)})};var ys=class r extends F{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==E.ZodParsedType.object)return(0,_.addIssueToContext)(n,{code:C.ZodIssueCode.invalid_type,expected:E.ZodParsedType.object,received:n.parsedType}),_.INVALID;let s=[],i=this._def.keyType,o=this._def.valueType;for(let a in n.data)s.push({key:i._parse(new Pe(n,a,n.path,a)),value:o._parse(new Pe(n,n.data[a],n.path,a)),alwaysSet:a in n.data});return n.common.async?_.ParseStatus.mergeObjectAsync(t,s):_.ParseStatus.mergeObjectSync(t,s)}get element(){return this._def.valueType}static create(e,t,n){return t instanceof F?new r({keyType:e,valueType:t,typeName:L.ZodRecord,...B(n)}):new r({keyType:Ct.create(),valueType:e,typeName:L.ZodRecord,...B(t)})}};y.ZodRecord=ys;var Kr=class extends F{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==E.ZodParsedType.map)return(0,_.addIssueToContext)(n,{code:C.ZodIssueCode.invalid_type,expected:E.ZodParsedType.map,received:n.parsedType}),_.INVALID;let s=this._def.keyType,i=this._def.valueType,o=[...n.data.entries()].map(([a,c],l)=>({key:s._parse(new Pe(n,a,n.path,[l,"key"])),value:i._parse(new Pe(n,c,n.path,[l,"value"]))}));if(n.common.async){let a=new Map;return Promise.resolve().then(async()=>{for(let c of o){let l=await c.key,d=await c.value;if(l.status==="aborted"||d.status==="aborted")return _.INVALID;(l.status==="dirty"||d.status==="dirty")&&t.dirty(),a.set(l.value,d.value)}return{status:t.value,value:a}})}else{let a=new Map;for(let c of o){let l=c.key,d=c.value;if(l.status==="aborted"||d.status==="aborted")return _.INVALID;(l.status==="dirty"||d.status==="dirty")&&t.dirty(),a.set(l.value,d.value)}return{status:t.value,value:a}}}};y.ZodMap=Kr;Kr.create=(r,e,t)=>new Kr({valueType:e,keyType:r,typeName:L.ZodMap,...B(t)});var Vr=class r extends F{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==E.ZodParsedType.set)return(0,_.addIssueToContext)(n,{code:C.ZodIssueCode.invalid_type,expected:E.ZodParsedType.set,received:n.parsedType}),_.INVALID;let s=this._def;s.minSize!==null&&n.data.size<s.minSize.value&&((0,_.addIssueToContext)(n,{code:C.ZodIssueCode.too_small,minimum:s.minSize.value,type:"set",inclusive:!0,exact:!1,message:s.minSize.message}),t.dirty()),s.maxSize!==null&&n.data.size>s.maxSize.value&&((0,_.addIssueToContext)(n,{code:C.ZodIssueCode.too_big,maximum:s.maxSize.value,type:"set",inclusive:!0,exact:!1,message:s.maxSize.message}),t.dirty());let i=this._def.valueType;function o(c){let l=new Set;for(let d of c){if(d.status==="aborted")return _.INVALID;d.status==="dirty"&&t.dirty(),l.add(d.value)}return{status:t.value,value:l}}let a=[...n.data.values()].map((c,l)=>i._parse(new Pe(n,c,n.path,l)));return n.common.async?Promise.all(a).then(c=>o(c)):o(a)}min(e,t){return new r({...this._def,minSize:{value:e,message:O.errorUtil.toString(t)}})}max(e,t){return new r({...this._def,maxSize:{value:e,message:O.errorUtil.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}};y.ZodSet=Vr;Vr.create=(r,e)=>new Vr({valueType:r,minSize:null,maxSize:null,typeName:L.ZodSet,...B(e)});var _s=class r extends F{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==E.ZodParsedType.function)return(0,_.addIssueToContext)(t,{code:C.ZodIssueCode.invalid_type,expected:E.ZodParsedType.function,received:t.parsedType}),_.INVALID;function n(a,c){return(0,_.makeIssue)({data:a,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,(0,ms.getErrorMap)(),ms.defaultErrorMap].filter(l=>!!l),issueData:{code:C.ZodIssueCode.invalid_arguments,argumentsError:c}})}function s(a,c){return(0,_.makeIssue)({data:a,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,(0,ms.getErrorMap)(),ms.defaultErrorMap].filter(l=>!!l),issueData:{code:C.ZodIssueCode.invalid_return_type,returnTypeError:c}})}let i={errorMap:t.common.contextualErrorMap},o=t.data;if(this._def.returns instanceof It){let a=this;return(0,_.OK)(async function(...c){let l=new C.ZodError([]),d=await a._def.args.parseAsync(c,i).catch(S=>{throw l.addIssue(n(c,S)),l}),p=await Reflect.apply(o,this,d);return await a._def.returns._def.type.parseAsync(p,i).catch(S=>{throw l.addIssue(s(p,S)),l})})}else{let a=this;return(0,_.OK)(function(...c){let l=a._def.args.safeParse(c,i);if(!l.success)throw new C.ZodError([n(c,l.error)]);let d=Reflect.apply(o,this,l.data),p=a._def.returns.safeParse(d,i);if(!p.success)throw new C.ZodError([s(d,p.error)]);return p.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new r({...this._def,args:Ve.create(e).rest(at.create())})}returns(e){return new r({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,t,n){return new r({args:e||Ve.create([]).rest(at.create()),returns:t||at.create(),typeName:L.ZodFunction,...B(n)})}};y.ZodFunction=_s;var or=class extends F{get schema(){return this._def.getter()}_parse(e){let{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}};y.ZodLazy=or;or.create=(r,e)=>new or({getter:r,typeName:L.ZodLazy,...B(e)});var ar=class extends F{_parse(e){if(e.data!==this._def.value){let t=this._getOrReturnCtx(e);return(0,_.addIssueToContext)(t,{received:t.data,code:C.ZodIssueCode.invalid_literal,expected:this._def.value}),_.INVALID}return{status:"valid",value:e.data}}get value(){return this._def.value}};y.ZodLiteral=ar;ar.create=(r,e)=>new ar({value:r,typeName:L.ZodLiteral,...B(e)});function Qa(r,e){return new ur({values:r,typeName:L.ZodEnum,...B(e)})}var ur=class r extends F{_parse(e){if(typeof e.data!="string"){let t=this._getOrReturnCtx(e),n=this._def.values;return(0,_.addIssueToContext)(t,{expected:E.util.joinValues(n),received:t.parsedType,code:C.ZodIssueCode.invalid_type}),_.INVALID}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){let t=this._getOrReturnCtx(e),n=this._def.values;return(0,_.addIssueToContext)(t,{received:t.data,code:C.ZodIssueCode.invalid_enum_value,options:n}),_.INVALID}return(0,_.OK)(e.data)}get options(){return this._def.values}get enum(){let e={};for(let t of this._def.values)e[t]=t;return e}get Values(){let e={};for(let t of this._def.values)e[t]=t;return e}get Enum(){let e={};for(let t of this._def.values)e[t]=t;return e}extract(e,t=this._def){return r.create(e,{...this._def,...t})}exclude(e,t=this._def){return r.create(this.options.filter(n=>!e.includes(n)),{...this._def,...t})}};y.ZodEnum=ur;ur.create=Qa;var cr=class extends F{_parse(e){let t=E.util.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==E.ZodParsedType.string&&n.parsedType!==E.ZodParsedType.number){let s=E.util.objectValues(t);return(0,_.addIssueToContext)(n,{expected:E.util.joinValues(s),received:n.parsedType,code:C.ZodIssueCode.invalid_type}),_.INVALID}if(this._cache||(this._cache=new Set(E.util.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let s=E.util.objectValues(t);return(0,_.addIssueToContext)(n,{received:n.data,code:C.ZodIssueCode.invalid_enum_value,options:s}),_.INVALID}return(0,_.OK)(e.data)}get enum(){return this._def.values}};y.ZodNativeEnum=cr;cr.create=(r,e)=>new cr({values:r,typeName:L.ZodNativeEnum,...B(e)});var It=class extends F{unwrap(){return this._def.type}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==E.ZodParsedType.promise&&t.common.async===!1)return(0,_.addIssueToContext)(t,{code:C.ZodIssueCode.invalid_type,expected:E.ZodParsedType.promise,received:t.parsedType}),_.INVALID;let n=t.parsedType===E.ZodParsedType.promise?t.data:Promise.resolve(t.data);return(0,_.OK)(n.then(s=>this._def.type.parseAsync(s,{path:t.path,errorMap:t.common.contextualErrorMap})))}};y.ZodPromise=It;It.create=(r,e)=>new It({type:r,typeName:L.ZodPromise,...B(e)});var ke=class extends F{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===L.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:t,ctx:n}=this._processInputParams(e),s=this._def.effect||null,i={addIssue:o=>{(0,_.addIssueToContext)(n,o),o.fatal?t.abort():t.dirty()},get path(){return n.path}};if(i.addIssue=i.addIssue.bind(i),s.type==="preprocess"){let o=s.transform(n.data,i);if(n.common.async)return Promise.resolve(o).then(async a=>{if(t.value==="aborted")return _.INVALID;let c=await this._def.schema._parseAsync({data:a,path:n.path,parent:n});return c.status==="aborted"?_.INVALID:c.status==="dirty"||t.value==="dirty"?(0,_.DIRTY)(c.value):c});{if(t.value==="aborted")return _.INVALID;let a=this._def.schema._parseSync({data:o,path:n.path,parent:n});return a.status==="aborted"?_.INVALID:a.status==="dirty"||t.value==="dirty"?(0,_.DIRTY)(a.value):a}}if(s.type==="refinement"){let o=a=>{let c=s.refinement(a,i);if(n.common.async)return Promise.resolve(c);if(c instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return a};if(n.common.async===!1){let a=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return a.status==="aborted"?_.INVALID:(a.status==="dirty"&&t.dirty(),o(a.value),{status:t.value,value:a.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(a=>a.status==="aborted"?_.INVALID:(a.status==="dirty"&&t.dirty(),o(a.value).then(()=>({status:t.value,value:a.value}))))}if(s.type==="transform")if(n.common.async===!1){let o=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!(0,_.isValid)(o))return _.INVALID;let a=s.transform(o.value,i);if(a instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:t.value,value:a}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(o=>(0,_.isValid)(o)?Promise.resolve(s.transform(o.value,i)).then(a=>({status:t.value,value:a})):_.INVALID);E.util.assertNever(s)}};y.ZodEffects=ke;y.ZodTransformer=ke;ke.create=(r,e,t)=>new ke({schema:r,typeName:L.ZodEffects,effect:e,...B(t)});ke.createWithPreprocess=(r,e,t)=>new ke({schema:e,effect:{type:"preprocess",transform:r},typeName:L.ZodEffects,...B(t)});var $e=class extends F{_parse(e){return this._getType(e)===E.ZodParsedType.undefined?(0,_.OK)(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};y.ZodOptional=$e;$e.create=(r,e)=>new $e({innerType:r,typeName:L.ZodOptional,...B(e)});var He=class extends F{_parse(e){return this._getType(e)===E.ZodParsedType.null?(0,_.OK)(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};y.ZodNullable=He;He.create=(r,e)=>new He({innerType:r,typeName:L.ZodNullable,...B(e)});var lr=class extends F{_parse(e){let{ctx:t}=this._processInputParams(e),n=t.data;return t.parsedType===E.ZodParsedType.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:t.path,parent:t})}removeDefault(){return this._def.innerType}};y.ZodDefault=lr;lr.create=(r,e)=>new lr({innerType:r,typeName:L.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...B(e)});var dr=class extends F{_parse(e){let{ctx:t}=this._processInputParams(e),n={...t,common:{...t.common,issues:[]}},s=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return(0,_.isAsync)(s)?s.then(i=>({status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new C.ZodError(n.common.issues)},input:n.data})})):{status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new C.ZodError(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};y.ZodCatch=dr;dr.create=(r,e)=>new dr({innerType:r,typeName:L.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...B(e)});var Hr=class extends F{_parse(e){if(this._getType(e)!==E.ZodParsedType.nan){let n=this._getOrReturnCtx(e);return(0,_.addIssueToContext)(n,{code:C.ZodIssueCode.invalid_type,expected:E.ZodParsedType.nan,received:n.parsedType}),_.INVALID}return{status:"valid",value:e.data}}};y.ZodNaN=Hr;Hr.create=r=>new Hr({typeName:L.ZodNaN,...B(r)});y.BRAND=Symbol("zod_brand");var En=class extends F{_parse(e){let{ctx:t}=this._processInputParams(e),n=t.data;return this._def.type._parse({data:n,path:t.path,parent:t})}unwrap(){return this._def.type}};y.ZodBranded=En;var In=class r extends F{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{let i=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return i.status==="aborted"?_.INVALID:i.status==="dirty"?(t.dirty(),(0,_.DIRTY)(i.value)):this._def.out._parseAsync({data:i.value,path:n.path,parent:n})})();{let s=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return s.status==="aborted"?_.INVALID:s.status==="dirty"?(t.dirty(),{status:"dirty",value:s.value}):this._def.out._parseSync({data:s.value,path:n.path,parent:n})}}static create(e,t){return new r({in:e,out:t,typeName:L.ZodPipeline})}};y.ZodPipeline=In;var hr=class extends F{_parse(e){let t=this._def.innerType._parse(e),n=s=>((0,_.isValid)(s)&&(s.value=Object.freeze(s.value)),s);return(0,_.isAsync)(t)?t.then(s=>n(s)):n(t)}unwrap(){return this._def.innerType}};y.ZodReadonly=hr;hr.create=(r,e)=>new hr({innerType:r,typeName:L.ZodReadonly,...B(e)});function Wa(r,e){let t=typeof r=="function"?r(e):typeof r=="string"?{message:r}:r;return typeof t=="string"?{message:t}:t}function eu(r,e={},t){return r?Et.create().superRefine((n,s)=>{let i=r(n);if(i instanceof Promise)return i.then(o=>{if(!o){let a=Wa(e,n),c=a.fatal??t??!0;s.addIssue({code:"custom",...a,fatal:c})}});if(!i){let o=Wa(e,n),a=o.fatal??t??!0;s.addIssue({code:"custom",...o,fatal:a})}}):Et.create()}y.late={object:_e.lazycreate};var L;(function(r){r.ZodString="ZodString",r.ZodNumber="ZodNumber",r.ZodNaN="ZodNaN",r.ZodBigInt="ZodBigInt",r.ZodBoolean="ZodBoolean",r.ZodDate="ZodDate",r.ZodSymbol="ZodSymbol",r.ZodUndefined="ZodUndefined",r.ZodNull="ZodNull",r.ZodAny="ZodAny",r.ZodUnknown="ZodUnknown",r.ZodNever="ZodNever",r.ZodVoid="ZodVoid",r.ZodArray="ZodArray",r.ZodObject="ZodObject",r.ZodUnion="ZodUnion",r.ZodDiscriminatedUnion="ZodDiscriminatedUnion",r.ZodIntersection="ZodIntersection",r.ZodTuple="ZodTuple",r.ZodRecord="ZodRecord",r.ZodMap="ZodMap",r.ZodSet="ZodSet",r.ZodFunction="ZodFunction",r.ZodLazy="ZodLazy",r.ZodLiteral="ZodLiteral",r.ZodEnum="ZodEnum",r.ZodEffects="ZodEffects",r.ZodNativeEnum="ZodNativeEnum",r.ZodOptional="ZodOptional",r.ZodNullable="ZodNullable",r.ZodDefault="ZodDefault",r.ZodCatch="ZodCatch",r.ZodPromise="ZodPromise",r.ZodBranded="ZodBranded",r.ZodPipeline="ZodPipeline",r.ZodReadonly="ZodReadonly"})(L||(y.ZodFirstPartyTypeKind=L={}));var Lf=(r,e={message:`Input not instance of ${r.name}`})=>eu(t=>t instanceof r,e);y.instanceof=Lf;var tu=Ct.create;y.string=tu;var ru=Xt.create;y.number=ru;var zf=Hr.create;y.nan=zf;var Uf=Qt.create;y.bigint=Uf;var nu=er.create;y.boolean=nu;var qf=tr.create;y.date=qf;var Bf=Fr.create;y.symbol=Bf;var Ff=rr.create;y.undefined=Ff;var Zf=nr.create;y.null=Zf;var Kf=Et.create;y.any=Kf;var Vf=at.create;y.unknown=Vf;var Hf=Le.create;y.never=Hf;var Gf=Zr.create;y.void=Gf;var Wf=ut.create;y.array=Wf;var Jf=_e.create;y.object=Jf;var Yf=_e.strictCreate;y.strictObject=Yf;var Xf=sr.create;y.union=Xf;var Qf=gs.create;y.discriminatedUnion=Qf;var ep=ir.create;y.intersection=ep;var tp=Ve.create;y.tuple=tp;var rp=ys.create;y.record=rp;var np=Kr.create;y.map=np;var sp=Vr.create;y.set=sp;var ip=_s.create;y.function=ip;var op=or.create;y.lazy=op;var ap=ar.create;y.literal=ap;var up=ur.create;y.enum=up;var cp=cr.create;y.nativeEnum=cp;var lp=It.create;y.promise=lp;var su=ke.create;y.effect=su;y.transformer=su;var dp=$e.create;y.optional=dp;var hp=He.create;y.nullable=hp;var fp=ke.createWithPreprocess;y.preprocess=fp;var pp=In.create;y.pipeline=pp;var mp=()=>tu().optional();y.ostring=mp;var gp=()=>ru().optional();y.onumber=gp;var yp=()=>nu().optional();y.oboolean=yp;y.coerce={string:(r=>Ct.create({...r,coerce:!0})),number:(r=>Xt.create({...r,coerce:!0})),boolean:(r=>er.create({...r,coerce:!0})),bigint:(r=>Qt.create({...r,coerce:!0})),date:(r=>tr.create({...r,coerce:!0}))};y.NEVER=_.INVALID});var Oi=Y(je=>{"use strict";var _p=je&&je.__createBinding||(Object.create?(function(r,e,t,n){n===void 0&&(n=t);var s=Object.getOwnPropertyDescriptor(e,t);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(r,n,s)}):(function(r,e,t,n){n===void 0&&(n=t),r[n]=e[t]})),Gr=je&&je.__exportStar||function(r,e){for(var t in r)t!=="default"&&!Object.prototype.hasOwnProperty.call(e,t)&&_p(e,r,t)};Object.defineProperty(je,"__esModule",{value:!0});Gr(fs(),je);Gr($i(),je);Gr(Ka(),je);Gr(xn(),je);Gr(iu(),je);Gr(hs(),je)});var uu=Y(ve=>{"use strict";var ou=ve&&ve.__createBinding||(Object.create?(function(r,e,t,n){n===void 0&&(n=t);var s=Object.getOwnPropertyDescriptor(e,t);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(r,n,s)}):(function(r,e,t,n){n===void 0&&(n=t),r[n]=e[t]})),vp=ve&&ve.__setModuleDefault||(Object.create?(function(r,e){Object.defineProperty(r,"default",{enumerable:!0,value:e})}):function(r,e){r.default=e}),bp=ve&&ve.__importStar||function(r){if(r&&r.__esModule)return r;var e={};if(r!=null)for(var t in r)t!=="default"&&Object.prototype.hasOwnProperty.call(r,t)&&ou(e,r,t);return vp(e,r),e},wp=ve&&ve.__exportStar||function(r,e){for(var t in r)t!=="default"&&!Object.prototype.hasOwnProperty.call(e,t)&&ou(e,r,t)};Object.defineProperty(ve,"__esModule",{value:!0});ve.z=void 0;var au=bp(Oi());ve.z=au;wp(Oi(),ve);ve.default=au});var Se=Y(h=>{"use strict";Object.defineProperty(h,"__esModule",{value:!0});h.EpicListResultMsg=h.EpicChild=h.EpicListMsg=h.BoardTriggerResultMsg=h.BoardTriggerMsg=h.BoardFetchResultMsg=h.BoardFetchMsg=h.ChatLoadResultMsg=h.ChatLoadMsg=h.ChatListResultMsg=h.ChatListMsg=h.ChatStreamMsg=h.JiraUsersResultMsg=h.DeployClaimResultMsg=h.DeployClaimMsg=h.RuleDiagnoseResultMsg=h.ProjectTestResultMsg=h.RunStatusMsg=h.RunLogMsg=h.RunClaimMsg=h.HeartbeatMsg=h.HelloMsg=h.RuleConfig=h.ProjectConfig=h.ActionConfig=h.DeployAction=h.EnvironmentConfig=h.PromotionMode=h.DeployStep=h.RespondAction=h.ImplementAction=h.PlanOnlyAction=h.TriggerConfig=h.StatusChangedTrigger=h.CommentKeywordTrigger=h.LabelAddedTrigger=h.ActionType=h.TriggerType=h.ACTIVE_RUN_STATUSES=h.RunStatus=h.needsInputMarkerIn=h.LEGACY_NEEDS_INPUT_COMMENT_MARKERS=h.NEEDS_INPUT_COMMENT_MARKER=h.NEEDS_INPUT_LABEL=h.NEEDS_INPUT_MARKER=h.BRANCH_DEPLOY_ISSUE_KEY=h.REQUIRED_AGENT_CAPABILITIES=h.DEFAULT_AGENT_ID=h.REGISTERED_AGENTS=h.PROTOCOL_VERSION=void 0;h.DEFAULT_IMPLEMENT_PROMPT_TEMPLATE=h.DEFAULT_PLAN_PROMPT_TEMPLATE=h.EnrollResponse=h.EnrollRequest=h.ServerToRunnerMsg=h.JiraUsersMsg=h.DeploySuggestMsg=h.DeployStartMsg=h.RunRetryPushMsg=h.RunRejectedMsg=h.RunApprovedMsg=h.RunCancelMsg=h.RuleDiagnoseMsg=h.ProjectTestMsg=h.RunClaimResultMsg=h.ConfigMsg=h.HelloAckMsg=h.RunnerToServerMsg=h.SetupStatusResultMsg=h.SetupStatusMsg=h.DeploySuggestResultMsg=h.EnvPreflightResultMsg=h.EnvPreflightMsg=h.ChatCreateTicketResultMsg=h.ChatCreateTicketMsg=h.ChatTurnResultMsg=h.ChatTurnMsg=h.ChatFile=h.TeamCredsResultMsg=h.TeamCredsMsg=h.KnowledgeSaveResultMsg=h.KnowledgeSaveMsg=h.KnowledgeListResultMsg=h.KnowledgeFile=h.KnowledgeListMsg=h.AuditReviewResultMsg=h.AuditReviewMsg=h.AuditGetResultMsg=h.AuditGetMsg=h.AuditListResultMsg=h.AuditListMsg=h.AuditStartResultMsg=h.AuditStartMsg=h.AuditRecord=h.AuditFinding=h.AuditScope=h.AuditSeverity=h.AuditRole=h.EpicSuggestResultMsg=h.EpicSuggestMsg=void 0;h.DEFAULT_DEPLOY_SUGGEST_PROMPT_TEMPLATE=h.DEPLOY_DOC_SUGGEST_PROMPT_TEMPLATE=h.PROMPT_PRESETS=h.DEFAULT_RESPOND_PROMPT_TEMPLATE=h.BUGFIX_IMPLEMENT_PROMPT_TEMPLATE=h.BUG_INVESTIGATION_PROMPT_TEMPLATE=h.TECHNICAL_PLAN_PROMPT_TEMPLATE=h.MEMORY_UPDATE_PROMPT=void 0;h.missingAgentCapabilities=kp;h.parseRunnerMsg=Tp;h.parseServerMsg=xp;var u=uu();h.PROTOCOL_VERSION="1.22";h.REGISTERED_AGENTS=[{id:"claude-code",displayName:"Claude Code",capabilities:{readOnlyJail:!0,editNoShellJail:!0,sessionResume:!0,costReporting:!0,modelSelection:!0,loginProfiles:!0},suggestedModels:["claude-fable-5","claude-opus-5","claude-sonnet-5","claude-haiku-4-5-20251001"],experimental:!1},{id:"codex",displayName:"OpenAI Codex CLI (experimental)",capabilities:{readOnlyJail:!0,editNoShellJail:!1,sessionResume:!1,costReporting:!1,modelSelection:!0,loginProfiles:!1},suggestedModels:[],experimental:!0}];h.DEFAULT_AGENT_ID="claude-code";h.REQUIRED_AGENT_CAPABILITIES={plan_only:["readOnlyJail","sessionResume"],respond:["readOnlyJail"],implement:["editNoShellJail","sessionResume"],deploy:[]};function kp(r,e){let t=h.REGISTERED_AGENTS.find(n=>n.id===r);return t?(h.REQUIRED_AGENT_CAPABILITIES[e]??[]).filter(n=>!t.capabilities[n]):null}h.BRANCH_DEPLOY_ISSUE_KEY="(branch deploy)";h.NEEDS_INPUT_MARKER="NEEDS-INPUT";h.NEEDS_INPUT_LABEL="agent-needs-input";h.NEEDS_INPUT_COMMENT_MARKER="Allwright needs your input";h.LEGACY_NEEDS_INPUT_COMMENT_MARKERS=["TicketPilot needs your input"];var Sp=r=>r.includes(h.NEEDS_INPUT_COMMENT_MARKER)||h.LEGACY_NEEDS_INPUT_COMMENT_MARKERS.some(e=>r.includes(e));h.needsInputMarkerIn=Sp;h.RunStatus=u.z.enum(["queued","running","posting","awaiting_approval","needs_input","succeeded","failed","timed_out"]);h.ACTIVE_RUN_STATUSES=["queued","running","posting","awaiting_approval"];h.TriggerType=u.z.enum(["label_added","comment_keyword","status_changed"]);h.ActionType=u.z.enum(["plan_only","implement","respond","deploy"]);h.LabelAddedTrigger=u.z.object({type:u.z.literal("label_added"),label:u.z.string().min(1),doneLabel:u.z.string().min(1).default("agent-planned"),failedLabel:u.z.string().min(1).default("agent-failed")});h.CommentKeywordTrigger=u.z.object({type:u.z.literal("comment_keyword"),keyword:u.z.string().min(1),doneLabel:u.z.string().min(1).default("agent-implemented"),failedLabel:u.z.string().min(1).default("agent-failed")});h.StatusChangedTrigger=u.z.object({type:u.z.literal("status_changed"),status:u.z.string().min(1),doneLabel:u.z.string().min(1).default("agent-deployed"),failedLabel:u.z.string().min(1).default("agent-failed")});h.TriggerConfig=u.z.discriminatedUnion("type",[h.LabelAddedTrigger,h.CommentKeywordTrigger,h.StatusChangedTrigger]);h.PlanOnlyAction=u.z.object({type:u.z.literal("plan_only"),promptTemplate:u.z.string().min(1),timeoutSeconds:u.z.number().int().positive().max(3600).default(900),agent:u.z.string().default(h.DEFAULT_AGENT_ID),model:u.z.string().default("")});h.ImplementAction=u.z.object({type:u.z.literal("implement"),promptTemplate:u.z.string().min(1),timeoutSeconds:u.z.number().int().positive().max(7200).default(1800),maxTurns:u.z.number().int().positive().max(500).default(120),requireApproval:u.z.boolean().default(!0),branchTemplate:u.z.string().min(1).default("agent/{{issueKey}}").refine(r=>r.includes("{{issueKey}}"),{message:"branchTemplate must contain {{issueKey}}"}),baseBranch:u.z.string().min(1).default("main"),jiraTransition:u.z.string().optional(),jiraTransitionOnStart:u.z.string().optional(),jiraTransitionOnMerge:u.z.string().optional(),agent:u.z.string().default(h.DEFAULT_AGENT_ID),model:u.z.string().default(""),updateMemory:u.z.boolean().default(!1)});h.RespondAction=u.z.object({type:u.z.literal("respond"),promptTemplate:u.z.string().min(1),timeoutSeconds:u.z.number().int().positive().max(3600).default(600),agent:u.z.string().default(h.DEFAULT_AGENT_ID),model:u.z.string().default("")});h.DeployStep=u.z.object({name:u.z.string().min(1).max(120),run:u.z.string().min(1).max(4e3),continueOnError:u.z.boolean().default(!1)});h.PromotionMode=u.z.enum(["deploy_only","merge_and_deploy"]);h.EnvironmentConfig=u.z.object({id:u.z.string(),projectId:u.z.string(),name:u.z.string(),rank:u.z.number().int().nonnegative(),auditBeforeDeploy:u.z.enum(["","security","testing"]).default(""),branch:u.z.string().default(""),useDedicatedCheckout:u.z.boolean().default(!1),promotionMode:h.PromotionMode.default("deploy_only"),ticketBranchTemplate:u.z.string().default("agent/{{issueKey}}"),steps:u.z.array(h.DeployStep).default([]),workdir:u.z.string().default(""),timeoutSeconds:u.z.number().int().positive().max(21600).default(1800),requiredSecrets:u.z.array(u.z.string()).default([]),requireApproval:u.z.boolean().default(!1),requireSyncCheck:u.z.boolean().default(!1),previousEnvBranch:u.z.string().optional(),deployFromColumn:u.z.string().default(""),deployToColumn:u.z.string().default("")});h.DeployAction=u.z.object({type:u.z.literal("deploy"),envSelection:u.z.enum(["fixed","from_comment"]).default("from_comment"),environmentId:u.z.string().optional(),requireStatus:u.z.string().optional()});h.ActionConfig=u.z.discriminatedUnion("type",[h.PlanOnlyAction,h.ImplementAction,h.RespondAction,h.DeployAction]);h.ProjectConfig=u.z.object({id:u.z.string(),name:u.z.string(),jiraProjectKey:u.z.string(),repoName:u.z.string(),componentRoutes:u.z.array(u.z.object({component:u.z.string().min(1),repoName:u.z.string().min(1)})).default([])});h.RuleConfig=u.z.object({id:u.z.string(),projectId:u.z.string(),name:u.z.string(),enabled:u.z.boolean(),trigger:h.TriggerConfig,action:h.ActionConfig});h.HelloMsg=u.z.object({type:u.z.literal("hello"),protocolVersion:u.z.string(),runnerVersion:u.z.string(),platform:u.z.string(),justBooted:u.z.boolean().optional()});h.HeartbeatMsg=u.z.object({type:u.z.literal("heartbeat"),ts:u.z.string()});h.RunClaimMsg=u.z.object({type:u.z.literal("run.claim"),requestId:u.z.string(),ruleId:u.z.string(),issueKey:u.z.string(),issueSummary:u.z.string().default(""),triggerFingerprint:u.z.string(),dedupKey:u.z.string().optional(),triggeredByAccountId:u.z.string().optional()});h.RunLogMsg=u.z.object({type:u.z.literal("run.log"),runId:u.z.string(),seq:u.z.number().int().nonnegative(),ts:u.z.string(),level:u.z.enum(["info","warn","error","agent"]),message:u.z.string().max(16384)});h.RunStatusMsg=u.z.object({type:u.z.literal("run.status"),runId:u.z.string(),status:h.RunStatus,error:u.z.string().optional(),errorKind:u.z.enum(["guard"]).optional(),costUsd:u.z.number().nonnegative().optional(),inputTokens:u.z.number().int().nonnegative().optional(),outputTokens:u.z.number().int().nonnegative().optional(),resultSummary:u.z.string().max(2e3).optional(),billingMode:u.z.enum(["subscription","api","unknown"]).optional(),model:u.z.string().max(200).optional(),prUrl:u.z.string().optional(),headSha:u.z.string().optional(),deployedRef:u.z.string().optional(),retryAvailable:u.z.boolean().optional()});h.ProjectTestResultMsg=u.z.object({type:u.z.literal("project.test.result"),requestId:u.z.string(),ok:u.z.boolean(),checks:u.z.array(u.z.object({name:u.z.string(),ok:u.z.boolean(),detail:u.z.string()}))});h.RuleDiagnoseResultMsg=u.z.object({type:u.z.literal("rule.diagnose.result"),requestId:u.z.string(),checks:u.z.array(u.z.object({name:u.z.string(),ok:u.z.boolean(),detail:u.z.string()})),matchedCount:u.z.number().int().nonnegative(),excludedCount:u.z.number().int().nonnegative(),excludedSample:u.z.array(u.z.string()).max(5)});h.DeployClaimMsg=u.z.object({type:u.z.literal("deploy.claim"),requestId:u.z.string(),projectId:u.z.string(),ruleId:u.z.string(),issueKey:u.z.string(),issueSummary:u.z.string().default(""),environmentName:u.z.string(),requestedByAccountId:u.z.string().optional(),requestedByDisplayName:u.z.string().default(""),dedupKey:u.z.string(),triggerFingerprint:u.z.string()});h.DeployClaimResultMsg=u.z.object({type:u.z.literal("deploy.claim.result"),requestId:u.z.string(),accepted:u.z.boolean(),runId:u.z.string().optional(),environment:h.EnvironmentConfig.optional(),reason:u.z.string().optional(),code:u.z.enum(["ok","duplicate","unknown_environment","not_permitted","unlinked_jira_account","promotion_order","jira_disabled","rule_disabled","cap"]).optional()});h.JiraUsersResultMsg=u.z.object({type:u.z.literal("jira.users.result"),requestId:u.z.string(),ok:u.z.boolean(),users:u.z.array(u.z.object({accountId:u.z.string(),displayName:u.z.string(),email:u.z.string().default(""),active:u.z.boolean().default(!0)})).default([]),error:u.z.string().optional()});h.ChatStreamMsg=u.z.object({type:u.z.literal("chat.stream"),requestId:u.z.string(),seq:u.z.number().int().nonnegative(),text:u.z.string().max(8e3)});h.ChatListMsg=u.z.object({type:u.z.literal("chat.list"),requestId:u.z.string(),projectId:u.z.string()});h.ChatListResultMsg=u.z.object({type:u.z.literal("chat.list.result"),requestId:u.z.string(),sessions:u.z.array(u.z.object({sessionId:u.z.string(),title:u.z.string().default(""),updatedAt:u.z.string().default(""),messageCount:u.z.number().int().nonnegative().default(0)})).default([])});h.ChatLoadMsg=u.z.object({type:u.z.literal("chat.load"),requestId:u.z.string(),sessionId:u.z.string()});h.ChatLoadResultMsg=u.z.object({type:u.z.literal("chat.load.result"),requestId:u.z.string(),ok:u.z.boolean(),projectId:u.z.string().default(""),messages:u.z.array(u.z.object({role:u.z.enum(["user","agent"]),text:u.z.string()})).default([]),error:u.z.string().optional()});h.BoardFetchMsg=u.z.object({type:u.z.literal("board.fetch"),requestId:u.z.string(),projectId:u.z.string()});h.BoardFetchResultMsg=u.z.object({type:u.z.literal("board.fetch.result"),requestId:u.z.string(),ok:u.z.boolean(),browseBaseUrl:u.z.string().default(""),columns:u.z.array(u.z.object({name:u.z.string(),issues:u.z.array(u.z.object({key:u.z.string(),summary:u.z.string(),labels:u.z.array(u.z.string()).default([])})).default([])})).default([]),error:u.z.string().optional()});h.BoardTriggerMsg=u.z.object({type:u.z.literal("board.trigger"),requestId:u.z.string(),projectId:u.z.string(),issueKey:u.z.string(),comment:u.z.string().max(2e3).default(""),removeLabel:u.z.string().default(""),requestedBy:u.z.string().default(""),requestedByEmail:u.z.string().default(""),reimplement:u.z.boolean().default(!1)});h.BoardTriggerResultMsg=u.z.object({type:u.z.literal("board.trigger.result"),requestId:u.z.string(),ok:u.z.boolean(),error:u.z.string().optional()});h.EpicListMsg=u.z.object({type:u.z.literal("epic.list"),requestId:u.z.string(),projectId:u.z.string(),epicKey:u.z.string().default("")});h.EpicChild=u.z.object({key:u.z.string(),summary:u.z.string(),status:u.z.string(),statusCategory:u.z.string(),labels:u.z.array(u.z.string()).default([])});h.EpicListResultMsg=u.z.object({type:u.z.literal("epic.list.result"),requestId:u.z.string(),ok:u.z.boolean(),error:u.z.string().optional(),epics:u.z.array(u.z.object({key:u.z.string(),summary:u.z.string(),status:u.z.string()})).default([]),children:u.z.array(h.EpicChild).default([])});h.EpicSuggestMsg=u.z.object({type:u.z.literal("epic.suggest"),requestId:u.z.string(),projectId:u.z.string(),epicKey:u.z.string().min(1),model:u.z.string().default("")});h.EpicSuggestResultMsg=u.z.object({type:u.z.literal("epic.suggest.result"),requestId:u.z.string(),ok:u.z.boolean(),error:u.z.string().optional(),issueKey:u.z.string().default(""),reason:u.z.string().default(""),considered:u.z.number().int().default(0)});h.AuditRole=u.z.enum(["security","testing","architecture"]);h.AuditSeverity=u.z.enum(["critical","high","medium","low","info"]);h.AuditScope=u.z.object({kind:u.z.enum(["repo","ticket","branch"]).default("repo"),ref:u.z.string().default("")});h.AuditFinding=u.z.object({id:u.z.string().min(1),title:u.z.string().min(1),ruleId:u.z.string().max(20).default(""),severity:h.AuditSeverity,area:u.z.string().default(""),evidence:u.z.array(u.z.object({file:u.z.string().min(1),line:u.z.number().int().positive().optional(),note:u.z.string().default("")})).min(1),fix:u.z.string().default("")});h.AuditRecord=u.z.object({id:u.z.string(),role:h.AuditRole,createdAt:u.z.string(),model:u.z.string().default(""),summary:u.z.string().default(""),packNames:u.z.array(u.z.string()).default([]),findings:u.z.array(h.AuditFinding).default([]),costUsd:u.z.number().default(0),review:u.z.object({selected:u.z.array(u.z.string()),updatedAt:u.z.string()}).optional(),verdicts:u.z.record(u.z.object({verdict:u.z.enum(["valid","false-positive","wont-fix"]),note:u.z.string().default(""),by:u.z.string().default(""),at:u.z.string().default("")})).default({}),lessonsWritten:u.z.array(u.z.string()).default([]),ticketed:u.z.record(u.z.string()).default({}),scope:h.AuditScope.default({kind:"repo",ref:""}),testRun:u.z.array(u.z.object({command:u.z.string(),exitCode:u.z.number().int(),durationMs:u.z.number().int().default(0),tail:u.z.string().default("")})).optional()});h.AuditStartMsg=u.z.object({type:u.z.literal("audit.start"),requestId:u.z.string(),projectId:u.z.string(),role:h.AuditRole,model:u.z.string().default(""),scope:h.AuditScope.default({kind:"repo",ref:""})});h.AuditStartResultMsg=u.z.object({type:u.z.literal("audit.start.result"),requestId:u.z.string(),ok:u.z.boolean(),error:u.z.string().optional(),audit:h.AuditRecord.optional()});h.AuditListMsg=u.z.object({type:u.z.literal("audit.list"),requestId:u.z.string(),projectId:u.z.string()});h.AuditListResultMsg=u.z.object({type:u.z.literal("audit.list.result"),requestId:u.z.string(),ok:u.z.boolean(),error:u.z.string().optional(),audits:u.z.array(u.z.object({id:u.z.string(),role:h.AuditRole,createdAt:u.z.string(),findingCount:u.z.number().int(),bySeverity:u.z.record(u.z.number().int()).default({})})).default([])});h.AuditGetMsg=u.z.object({type:u.z.literal("audit.get"),requestId:u.z.string(),projectId:u.z.string(),auditId:u.z.string()});h.AuditGetResultMsg=u.z.object({type:u.z.literal("audit.get.result"),requestId:u.z.string(),ok:u.z.boolean(),error:u.z.string().optional(),audit:h.AuditRecord.optional()});h.AuditReviewMsg=u.z.object({type:u.z.literal("audit.review"),requestId:u.z.string(),projectId:u.z.string(),auditId:u.z.string(),selected:u.z.array(u.z.string()).optional(),ticketed:u.z.array(u.z.object({findingId:u.z.string(),issueKey:u.z.string()})).default([]),verdicts:u.z.array(u.z.object({findingId:u.z.string(),verdict:u.z.enum(["valid","false-positive","wont-fix"]),note:u.z.string().max(2e3).default("")})).default([]),verdictBy:u.z.string().default("")});h.AuditReviewResultMsg=u.z.object({type:u.z.literal("audit.review.result"),requestId:u.z.string(),ok:u.z.boolean(),error:u.z.string().optional(),audit:h.AuditRecord.optional()});h.KnowledgeListMsg=u.z.object({type:u.z.literal("knowledge.list"),requestId:u.z.string(),projectId:u.z.string()});h.KnowledgeFile=u.z.object({role:h.AuditRole,level:u.z.enum(["global","org","project"]),source:u.z.enum(["pack","lessons"]),name:u.z.string(),content:u.z.string(),editable:u.z.boolean().default(!1)});h.KnowledgeListResultMsg=u.z.object({type:u.z.literal("knowledge.list.result"),requestId:u.z.string(),ok:u.z.boolean(),error:u.z.string().optional(),files:u.z.array(h.KnowledgeFile).default([])});h.KnowledgeSaveMsg=u.z.object({type:u.z.literal("knowledge.save"),requestId:u.z.string(),projectId:u.z.string(),role:h.AuditRole,level:u.z.enum(["org","project"]),source:u.z.enum(["pack","lessons"]),name:u.z.string().min(1).max(100),content:u.z.string().max(6e4),append:u.z.boolean().default(!1),by:u.z.string().default("")});h.KnowledgeSaveResultMsg=u.z.object({type:u.z.literal("knowledge.save.result"),requestId:u.z.string(),ok:u.z.boolean(),error:u.z.string().optional()});h.TeamCredsMsg=u.z.object({type:u.z.literal("team.creds"),requestId:u.z.string(),emails:u.z.array(u.z.string()).max(200)});h.TeamCredsResultMsg=u.z.object({type:u.z.literal("team.creds.result"),requestId:u.z.string(),ok:u.z.boolean(),error:u.z.string().optional(),githubShared:u.z.boolean().default(!1),sharedGithubLogin:u.z.string().default(""),entries:u.z.array(u.z.object({email:u.z.string(),jira:u.z.enum(["own","runner-account","missing"]),jiraAs:u.z.string().default(""),github:u.z.enum(["own","shared","missing"]),githubAs:u.z.string().default("")})).default([])});h.ChatFile=u.z.object({name:u.z.string().min(1).max(255),contentBase64:u.z.string().min(1).max(6e6)});h.ChatTurnMsg=u.z.object({type:u.z.literal("chat.turn"),requestId:u.z.string(),projectId:u.z.string(),sessionId:u.z.string().optional(),message:u.z.string().min(1).max(2e4),userName:u.z.string().default(""),model:u.z.string().default(""),files:u.z.array(h.ChatFile).max(8).default([])});h.ChatTurnResultMsg=u.z.object({type:u.z.literal("chat.turn.result"),requestId:u.z.string(),ok:u.z.boolean(),sessionId:u.z.string().default(""),reply:u.z.string().default(""),error:u.z.string().optional()});h.ChatCreateTicketMsg=u.z.object({type:u.z.literal("chat.create.ticket"),requestId:u.z.string(),projectId:u.z.string(),summary:u.z.string().min(1).max(250),description:u.z.string().default(""),triggerComment:u.z.string().default(""),requestedBy:u.z.string().default(""),requestedByEmail:u.z.string().default(""),asEpic:u.z.boolean().default(!1),children:u.z.array(u.z.object({summary:u.z.string().min(1),description:u.z.string().default("")})).max(20).default([]),files:u.z.array(h.ChatFile).max(8).default([])});h.ChatCreateTicketResultMsg=u.z.object({type:u.z.literal("chat.create.ticket.result"),requestId:u.z.string(),ok:u.z.boolean(),issueKey:u.z.string().default(""),error:u.z.string().optional(),childKeys:u.z.array(u.z.string()).default([])});h.EnvPreflightMsg=u.z.object({type:u.z.literal("env.preflight"),requestId:u.z.string(),projectId:u.z.string(),environmentName:u.z.string().default(""),steps:u.z.array(h.DeployStep).default([]),requiredSecrets:u.z.array(u.z.string()).default([]),workdir:u.z.string().default(""),branch:u.z.string().default("")});h.EnvPreflightResultMsg=u.z.object({type:u.z.literal("env.preflight.result"),requestId:u.z.string(),ok:u.z.boolean(),checks:u.z.array(u.z.object({name:u.z.string(),ok:u.z.boolean(),detail:u.z.string().default("")})).default([])});h.DeploySuggestResultMsg=u.z.object({type:u.z.literal("deploy.suggest.result"),requestId:u.z.string(),ok:u.z.boolean(),steps:u.z.array(h.DeployStep).default([]),requiredSecrets:u.z.array(u.z.string()).default([]),notes:u.z.string().default(""),error:u.z.string().optional()});h.SetupStatusMsg=u.z.object({type:u.z.literal("setup.status"),requestId:u.z.string(),repoNames:u.z.array(u.z.string()).max(100).default([])});h.SetupStatusResultMsg=u.z.object({type:u.z.literal("setup.status.result"),requestId:u.z.string(),ok:u.z.boolean(),error:u.z.string().optional(),jiraConfigured:u.z.boolean().default(!1),jiraEmail:u.z.string().default(""),claude:u.z.object({installed:u.z.boolean(),version:u.z.string().default(""),loggedIn:u.z.boolean()}).optional(),githubTokenSet:u.z.boolean().default(!1),githubLogin:u.z.string().default(""),deploysEnabled:u.z.boolean().default(!1),jiraUserCount:u.z.number().int().default(0),repos:u.z.array(u.z.object({repoName:u.z.string(),mapped:u.z.boolean(),pathExists:u.z.boolean().default(!1),isGit:u.z.boolean().default(!1),claudeMd:u.z.boolean().default(!1),deployMd:u.z.boolean().default(!1),testMd:u.z.boolean().default(!1)})).default([])});h.RunnerToServerMsg=u.z.discriminatedUnion("type",[h.HelloMsg,h.HeartbeatMsg,h.RunClaimMsg,h.RunLogMsg,h.RunStatusMsg,h.ProjectTestResultMsg,h.RuleDiagnoseResultMsg,h.DeployClaimMsg,h.DeploySuggestResultMsg,h.EnvPreflightResultMsg,h.ChatTurnResultMsg,h.ChatStreamMsg,h.ChatCreateTicketResultMsg,h.ChatListResultMsg,h.ChatLoadResultMsg,h.BoardFetchResultMsg,h.BoardTriggerResultMsg,h.TeamCredsResultMsg,h.AuditStartResultMsg,h.AuditListResultMsg,h.AuditGetResultMsg,h.AuditReviewResultMsg,h.KnowledgeListResultMsg,h.KnowledgeSaveResultMsg,h.EpicListResultMsg,h.EpicSuggestResultMsg,h.JiraUsersResultMsg,h.SetupStatusResultMsg]);h.HelloAckMsg=u.z.object({type:u.z.literal("hello.ack"),runnerId:u.z.string(),runnerName:u.z.string(),serverTime:u.z.string()});h.ConfigMsg=u.z.object({type:u.z.literal("config"),projects:u.z.array(h.ProjectConfig),rules:u.z.array(h.RuleConfig),environments:u.z.array(h.EnvironmentConfig).default([]),pollingPaused:u.z.boolean().default(!1)});h.RunClaimResultMsg=u.z.object({type:u.z.literal("run.claim.result"),requestId:u.z.string(),accepted:u.z.boolean(),runId:u.z.string().optional(),reason:u.z.string().optional(),claudeProfile:u.z.string().optional(),actorEmail:u.z.string().optional()});h.ProjectTestMsg=u.z.object({type:u.z.literal("project.test"),requestId:u.z.string(),projectId:u.z.string()});h.RuleDiagnoseMsg=u.z.object({type:u.z.literal("rule.diagnose"),requestId:u.z.string(),ruleId:u.z.string()});h.RunCancelMsg=u.z.object({type:u.z.literal("run.cancel"),runId:u.z.string()});h.RunApprovedMsg=u.z.object({type:u.z.literal("run.approved"),runId:u.z.string(),headSha:u.z.string().optional()});h.RunRejectedMsg=u.z.object({type:u.z.literal("run.rejected"),runId:u.z.string()});h.RunRetryPushMsg=u.z.object({type:u.z.literal("run.retryPush"),runId:u.z.string()});h.DeployStartMsg=u.z.object({type:u.z.literal("deploy.start"),runId:u.z.string(),projectId:u.z.string(),issueKey:u.z.string(),issueSummary:u.z.string().default(""),environment:h.EnvironmentConfig,requestedBy:u.z.string().default(""),attempt:u.z.number().int().positive().default(1)});h.DeploySuggestMsg=u.z.object({type:u.z.literal("deploy.suggest"),requestId:u.z.string(),projectId:u.z.string(),environmentName:u.z.string(),notes:u.z.string().default(""),timeoutSeconds:u.z.number().int().positive().max(1800).default(300)});h.JiraUsersMsg=u.z.object({type:u.z.literal("jira.users"),requestId:u.z.string(),query:u.z.string().default("")});h.ServerToRunnerMsg=u.z.discriminatedUnion("type",[h.HelloAckMsg,h.ConfigMsg,h.RunClaimResultMsg,h.ProjectTestMsg,h.RuleDiagnoseMsg,h.RunCancelMsg,h.RunApprovedMsg,h.RunRejectedMsg,h.RunRetryPushMsg,h.DeployClaimResultMsg,h.DeployStartMsg,h.DeploySuggestMsg,h.EnvPreflightMsg,h.ChatTurnMsg,h.ChatCreateTicketMsg,h.ChatListMsg,h.ChatLoadMsg,h.BoardFetchMsg,h.BoardTriggerMsg,h.TeamCredsMsg,h.AuditStartMsg,h.AuditListMsg,h.AuditGetMsg,h.AuditReviewMsg,h.KnowledgeListMsg,h.KnowledgeSaveMsg,h.EpicListMsg,h.EpicSuggestMsg,h.JiraUsersMsg,h.SetupStatusMsg]);h.EnrollRequest=u.z.object({enrollToken:u.z.string().min(10),name:u.z.string().min(1).max(100),platform:u.z.string(),runnerVersion:u.z.string()});h.EnrollResponse=u.z.object({runnerId:u.z.string(),runnerToken:u.z.string(),controlPlaneWsUrl:u.z.string()});function Tp(r){return h.RunnerToServerMsg.parse(r)}function xp(r){return h.ServerToRunnerMsg.parse(r)}h.DEFAULT_PLAN_PROMPT_TEMPLATE=`You are a senior engineer asked to assess a Jira ticket. You have read-only access to the repository \u2014 do not attempt to modify anything.
23
+ `)}),this}_outputHelpIfRequested(e){let t=this._getHelpOption();t&&e.find(s=>t.is(s))&&(this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)"))}};function la(r){return r.map(e=>{if(!e.startsWith("--inspect"))return e;let t,n="127.0.0.1",s="9229",i;return(i=e.match(/^(--inspect(-brk)?)$/))!==null?t=i[1]:(i=e.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null?(t=i[1],/^\d+$/.test(i[3])?s=i[3]:n=i[3]):(i=e.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null&&(t=i[1],n=i[3],s=i[4]),t&&s!=="0"?`${t}=${n}:${parseInt(s)+1}`:e})}da.Command=vi});var ga=Y(Ee=>{var{Argument:fa}=Qn(),{Command:bi}=ha(),{CommanderError:Nd,InvalidArgumentError:pa}=vn(),{Help:Md}=di(),{Option:ma}=mi();Ee.program=new bi;Ee.createCommand=r=>new bi(r);Ee.createOption=(r,e)=>new ma(r,e);Ee.createArgument=(r,e)=>new fa(r,e);Ee.Command=bi;Ee.Option=ma;Ee.Argument=fa;Ee.Help=Md;Ee.CommanderError=Nd;Ee.InvalidArgumentError=pa;Ee.InvalidOptionArgumentError=pa});var xn=Y(te=>{"use strict";Object.defineProperty(te,"__esModule",{value:!0});te.getParsedType=te.ZodParsedType=te.objectUtil=te.util=void 0;var Ei;(function(r){r.assertEqual=s=>{};function e(s){}r.assertIs=e;function t(s){throw new Error}r.assertNever=t,r.arrayToEnum=s=>{let i={};for(let o of s)i[o]=o;return i},r.getValidEnumValues=s=>{let i=r.objectKeys(s).filter(a=>typeof s[s[a]]!="number"),o={};for(let a of i)o[a]=s[a];return r.objectValues(o)},r.objectValues=s=>r.objectKeys(s).map(function(i){return s[i]}),r.objectKeys=typeof Object.keys=="function"?s=>Object.keys(s):s=>{let i=[];for(let o in s)Object.prototype.hasOwnProperty.call(s,o)&&i.push(o);return i},r.find=(s,i)=>{for(let o of s)if(i(o))return o},r.isInteger=typeof Number.isInteger=="function"?s=>Number.isInteger(s):s=>typeof s=="number"&&Number.isFinite(s)&&Math.floor(s)===s;function n(s,i=" | "){return s.map(o=>typeof o=="string"?`'${o}'`:o).join(i)}r.joinValues=n,r.jsonStringifyReplacer=(s,i)=>typeof i=="bigint"?i.toString():i})(Ei||(te.util=Ei={}));var za;(function(r){r.mergeShapes=(e,t)=>({...e,...t})})(za||(te.objectUtil=za={}));te.ZodParsedType=Ei.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]);var ef=r=>{switch(typeof r){case"undefined":return te.ZodParsedType.undefined;case"string":return te.ZodParsedType.string;case"number":return Number.isNaN(r)?te.ZodParsedType.nan:te.ZodParsedType.number;case"boolean":return te.ZodParsedType.boolean;case"function":return te.ZodParsedType.function;case"bigint":return te.ZodParsedType.bigint;case"symbol":return te.ZodParsedType.symbol;case"object":return Array.isArray(r)?te.ZodParsedType.array:r===null?te.ZodParsedType.null:r.then&&typeof r.then=="function"&&r.catch&&typeof r.catch=="function"?te.ZodParsedType.promise:typeof Map<"u"&&r instanceof Map?te.ZodParsedType.map:typeof Set<"u"&&r instanceof Set?te.ZodParsedType.set:typeof Date<"u"&&r instanceof Date?te.ZodParsedType.date:te.ZodParsedType.object;default:return te.ZodParsedType.unknown}};te.getParsedType=ef});var hs=Y(Tt=>{"use strict";Object.defineProperty(Tt,"__esModule",{value:!0});Tt.ZodError=Tt.quotelessJson=Tt.ZodIssueCode=void 0;var Ua=xn();Tt.ZodIssueCode=Ua.util.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]);var tf=r=>JSON.stringify(r,null,2).replace(/"([^"]+)":/g,"$1:");Tt.quotelessJson=tf;var Cn=class r extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=n=>{this.issues=[...this.issues,n]},this.addIssues=(n=[])=>{this.issues=[...this.issues,...n]};let t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name="ZodError",this.issues=e}format(e){let t=e||function(i){return i.message},n={_errors:[]},s=i=>{for(let o of i.issues)if(o.code==="invalid_union")o.unionErrors.map(s);else if(o.code==="invalid_return_type")s(o.returnTypeError);else if(o.code==="invalid_arguments")s(o.argumentsError);else if(o.path.length===0)n._errors.push(t(o));else{let a=n,c=0;for(;c<o.path.length;){let l=o.path[c];c===o.path.length-1?(a[l]=a[l]||{_errors:[]},a[l]._errors.push(t(o))):a[l]=a[l]||{_errors:[]},a=a[l],c++}}};return s(this),n}static assert(e){if(!(e instanceof r))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,Ua.util.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=t=>t.message){let t={},n=[];for(let s of this.issues)if(s.path.length>0){let i=s.path[0];t[i]=t[i]||[],t[i].push(e(s))}else n.push(e(s));return{formErrors:n,fieldErrors:t}}get formErrors(){return this.flatten()}};Tt.ZodError=Cn;Cn.create=r=>new Cn(r)});var Ai=Y(Ii=>{"use strict";Object.defineProperty(Ii,"__esModule",{value:!0});var fe=hs(),Yt=xn(),rf=(r,e)=>{let t;switch(r.code){case fe.ZodIssueCode.invalid_type:r.received===Yt.ZodParsedType.undefined?t="Required":t=`Expected ${r.expected}, received ${r.received}`;break;case fe.ZodIssueCode.invalid_literal:t=`Invalid literal value, expected ${JSON.stringify(r.expected,Yt.util.jsonStringifyReplacer)}`;break;case fe.ZodIssueCode.unrecognized_keys:t=`Unrecognized key(s) in object: ${Yt.util.joinValues(r.keys,", ")}`;break;case fe.ZodIssueCode.invalid_union:t="Invalid input";break;case fe.ZodIssueCode.invalid_union_discriminator:t=`Invalid discriminator value. Expected ${Yt.util.joinValues(r.options)}`;break;case fe.ZodIssueCode.invalid_enum_value:t=`Invalid enum value. Expected ${Yt.util.joinValues(r.options)}, received '${r.received}'`;break;case fe.ZodIssueCode.invalid_arguments:t="Invalid function arguments";break;case fe.ZodIssueCode.invalid_return_type:t="Invalid function return type";break;case fe.ZodIssueCode.invalid_date:t="Invalid date";break;case fe.ZodIssueCode.invalid_string:typeof r.validation=="object"?"includes"in r.validation?(t=`Invalid input: must include "${r.validation.includes}"`,typeof r.validation.position=="number"&&(t=`${t} at one or more positions greater than or equal to ${r.validation.position}`)):"startsWith"in r.validation?t=`Invalid input: must start with "${r.validation.startsWith}"`:"endsWith"in r.validation?t=`Invalid input: must end with "${r.validation.endsWith}"`:Yt.util.assertNever(r.validation):r.validation!=="regex"?t=`Invalid ${r.validation}`:t="Invalid";break;case fe.ZodIssueCode.too_small:r.type==="array"?t=`Array must contain ${r.exact?"exactly":r.inclusive?"at least":"more than"} ${r.minimum} element(s)`:r.type==="string"?t=`String must contain ${r.exact?"exactly":r.inclusive?"at least":"over"} ${r.minimum} character(s)`:r.type==="number"?t=`Number must be ${r.exact?"exactly equal to ":r.inclusive?"greater than or equal to ":"greater than "}${r.minimum}`:r.type==="bigint"?t=`Number must be ${r.exact?"exactly equal to ":r.inclusive?"greater than or equal to ":"greater than "}${r.minimum}`:r.type==="date"?t=`Date must be ${r.exact?"exactly equal to ":r.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(r.minimum))}`:t="Invalid input";break;case fe.ZodIssueCode.too_big:r.type==="array"?t=`Array must contain ${r.exact?"exactly":r.inclusive?"at most":"less than"} ${r.maximum} element(s)`:r.type==="string"?t=`String must contain ${r.exact?"exactly":r.inclusive?"at most":"under"} ${r.maximum} character(s)`:r.type==="number"?t=`Number must be ${r.exact?"exactly":r.inclusive?"less than or equal to":"less than"} ${r.maximum}`:r.type==="bigint"?t=`BigInt must be ${r.exact?"exactly":r.inclusive?"less than or equal to":"less than"} ${r.maximum}`:r.type==="date"?t=`Date must be ${r.exact?"exactly":r.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(r.maximum))}`:t="Invalid input";break;case fe.ZodIssueCode.custom:t="Invalid input";break;case fe.ZodIssueCode.invalid_intersection_types:t="Intersection results could not be merged";break;case fe.ZodIssueCode.not_multiple_of:t=`Number must be a multiple of ${r.multipleOf}`;break;case fe.ZodIssueCode.not_finite:t="Number must be finite";break;default:t=e.defaultError,Yt.util.assertNever(r)}return{message:t}};Ii.default=rf});var fs=Y(xt=>{"use strict";var nf=xt&&xt.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(xt,"__esModule",{value:!0});xt.defaultErrorMap=void 0;xt.setErrorMap=sf;xt.getErrorMap=of;var qa=nf(Ai());xt.defaultErrorMap=qa.default;var Ba=qa.default;function sf(r){Ba=r}function of(){return Ba}});var $i=Y(X=>{"use strict";var af=X&&X.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(X,"__esModule",{value:!0});X.isAsync=X.isValid=X.isDirty=X.isAborted=X.OK=X.DIRTY=X.INVALID=X.ParseStatus=X.EMPTY_PATH=X.makeIssue=void 0;X.addIssueToContext=lf;var uf=fs(),Fa=af(Ai()),cf=r=>{let{data:e,path:t,errorMaps:n,issueData:s}=r,i=[...t,...s.path||[]],o={...s,path:i};if(s.message!==void 0)return{...s,path:i,message:s.message};let a="",c=n.filter(l=>!!l).slice().reverse();for(let l of c)a=l(o,{data:e,defaultError:a}).message;return{...s,path:i,message:a}};X.makeIssue=cf;X.EMPTY_PATH=[];function lf(r,e){let t=(0,uf.getErrorMap)(),n=(0,X.makeIssue)({issueData:e,data:r.data,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,t,t===Fa.default?void 0:Fa.default].filter(s=>!!s)});r.common.issues.push(n)}var Ri=class r{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,t){let n=[];for(let s of t){if(s.status==="aborted")return X.INVALID;s.status==="dirty"&&e.dirty(),n.push(s.value)}return{status:e.value,value:n}}static async mergeObjectAsync(e,t){let n=[];for(let s of t){let i=await s.key,o=await s.value;n.push({key:i,value:o})}return r.mergeObjectSync(e,n)}static mergeObjectSync(e,t){let n={};for(let s of t){let{key:i,value:o}=s;if(i.status==="aborted"||o.status==="aborted")return X.INVALID;i.status==="dirty"&&e.dirty(),o.status==="dirty"&&e.dirty(),i.value!=="__proto__"&&(typeof o.value<"u"||s.alwaysSet)&&(n[i.value]=o.value)}return{status:e.value,value:n}}};X.ParseStatus=Ri;X.INVALID=Object.freeze({status:"aborted"});var df=r=>({status:"dirty",value:r});X.DIRTY=df;var hf=r=>({status:"valid",value:r});X.OK=hf;var ff=r=>r.status==="aborted";X.isAborted=ff;var pf=r=>r.status==="dirty";X.isDirty=pf;var mf=r=>r.status==="valid";X.isValid=mf;var gf=r=>typeof Promise<"u"&&r instanceof Promise;X.isAsync=gf});var Ka=Y(Za=>{"use strict";Object.defineProperty(Za,"__esModule",{value:!0})});var Ha=Y(ps=>{"use strict";Object.defineProperty(ps,"__esModule",{value:!0});ps.errorUtil=void 0;var Va;(function(r){r.errToObj=e=>typeof e=="string"?{message:e}:e||{},r.toString=e=>typeof e=="string"?e:e?.message})(Va||(ps.errorUtil=Va={}))});var iu=Y(y=>{"use strict";Object.defineProperty(y,"__esModule",{value:!0});y.discriminatedUnion=y.date=y.boolean=y.bigint=y.array=y.any=y.coerce=y.ZodFirstPartyTypeKind=y.late=y.ZodSchema=y.Schema=y.ZodReadonly=y.ZodPipeline=y.ZodBranded=y.BRAND=y.ZodNaN=y.ZodCatch=y.ZodDefault=y.ZodNullable=y.ZodOptional=y.ZodTransformer=y.ZodEffects=y.ZodPromise=y.ZodNativeEnum=y.ZodEnum=y.ZodLiteral=y.ZodLazy=y.ZodFunction=y.ZodSet=y.ZodMap=y.ZodRecord=y.ZodTuple=y.ZodIntersection=y.ZodDiscriminatedUnion=y.ZodUnion=y.ZodObject=y.ZodArray=y.ZodVoid=y.ZodNever=y.ZodUnknown=y.ZodAny=y.ZodNull=y.ZodUndefined=y.ZodSymbol=y.ZodDate=y.ZodBoolean=y.ZodBigInt=y.ZodNumber=y.ZodString=y.ZodType=void 0;y.NEVER=y.void=y.unknown=y.union=y.undefined=y.tuple=y.transformer=y.symbol=y.string=y.strictObject=y.set=y.record=y.promise=y.preprocess=y.pipeline=y.ostring=y.optional=y.onumber=y.oboolean=y.object=y.number=y.nullable=y.null=y.never=y.nativeEnum=y.nan=y.map=y.literal=y.lazy=y.intersection=y.instanceof=y.function=y.enum=y.effect=void 0;y.datetimeRegex=Xa;y.custom=eu;var C=hs(),ms=fs(),O=Ha(),_=$i(),E=xn(),Pe=class{constructor(e,t,n,s){this._cachedPath=[],this.parent=e,this.data=t,this._path=n,this._key=s}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},Ga=(r,e)=>{if((0,_.isValid)(e))return{success:!0,data:e.value};if(!r.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let t=new C.ZodError(r.common.issues);return this._error=t,this._error}}};function B(r){if(!r)return{};let{errorMap:e,invalid_type_error:t,required_error:n,description:s}=r;if(e&&(t||n))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:s}:{errorMap:(o,a)=>{let{message:c}=r;return o.code==="invalid_enum_value"?{message:c??a.defaultError}:typeof a.data>"u"?{message:c??n??a.defaultError}:o.code!=="invalid_type"?{message:a.defaultError}:{message:c??t??a.defaultError}},description:s}}var F=class{get description(){return this._def.description}_getType(e){return(0,E.getParsedType)(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:(0,E.getParsedType)(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new _.ParseStatus,ctx:{common:e.parent.common,data:e.data,parsedType:(0,E.getParsedType)(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let t=this._parse(e);if((0,_.isAsync)(t))throw new Error("Synchronous parse encountered promise.");return t}_parseAsync(e){let t=this._parse(e);return Promise.resolve(t)}parse(e,t){let n=this.safeParse(e,t);if(n.success)return n.data;throw n.error}safeParse(e,t){let n={common:{issues:[],async:t?.async??!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:(0,E.getParsedType)(e)},s=this._parseSync({data:e,path:n.path,parent:n});return Ga(n,s)}"~validate"(e){let t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:(0,E.getParsedType)(e)};if(!this["~standard"].async)try{let n=this._parseSync({data:e,path:[],parent:t});return(0,_.isValid)(n)?{value:n.value}:{issues:t.common.issues}}catch(n){n?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then(n=>(0,_.isValid)(n)?{value:n.value}:{issues:t.common.issues})}async parseAsync(e,t){let n=await this.safeParseAsync(e,t);if(n.success)return n.data;throw n.error}async safeParseAsync(e,t){let n={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:(0,E.getParsedType)(e)},s=this._parse({data:e,path:n.path,parent:n}),i=await((0,_.isAsync)(s)?s:Promise.resolve(s));return Ga(n,i)}refine(e,t){let n=s=>typeof t=="string"||typeof t>"u"?{message:t}:typeof t=="function"?t(s):t;return this._refinement((s,i)=>{let o=e(s),a=()=>i.addIssue({code:C.ZodIssueCode.custom,...n(s)});return typeof Promise<"u"&&o instanceof Promise?o.then(c=>c?!0:(a(),!1)):o?!0:(a(),!1)})}refinement(e,t){return this._refinement((n,s)=>e(n)?!0:(s.addIssue(typeof t=="function"?t(n,s):t),!1))}_refinement(e){return new ke({schema:this,typeName:L.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:t=>this["~validate"](t)}}optional(){return $e.create(this,this._def)}nullable(){return He.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return ut.create(this)}promise(){return It.create(this,this._def)}or(e){return sr.create([this,e],this._def)}and(e){return ir.create(this,e,this._def)}transform(e){return new ke({...B(this._def),schema:this,typeName:L.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let t=typeof e=="function"?e:()=>e;return new lr({...B(this._def),innerType:this,defaultValue:t,typeName:L.ZodDefault})}brand(){return new En({typeName:L.ZodBranded,type:this,...B(this._def)})}catch(e){let t=typeof e=="function"?e:()=>e;return new dr({...B(this._def),innerType:this,catchValue:t,typeName:L.ZodCatch})}describe(e){let t=this.constructor;return new t({...this._def,description:e})}pipe(e){return In.create(this,e)}readonly(){return hr.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}};y.ZodType=F;y.Schema=F;y.ZodSchema=F;var yf=/^c[^\s-]{8,}$/i,_f=/^[0-9a-z]+$/,vf=/^[0-9A-HJKMNP-TV-Z]{26}$/i,bf=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,wf=/^[a-z0-9_-]{21}$/i,kf=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Sf=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,Tf=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,xf="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",Pi,Cf=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,Ef=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,If=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,Af=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,Rf=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,$f=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Ja="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",Pf=new RegExp(`^${Ja}$`);function Ya(r){let e="[0-5]\\d";r.precision?e=`${e}\\.\\d{${r.precision}}`:r.precision==null&&(e=`${e}(\\.\\d+)?`);let t=r.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${t}`}function jf(r){return new RegExp(`^${Ya(r)}$`)}function Xa(r){let e=`${Ja}T${Ya(r)}`,t=[];return t.push(r.local?"Z?":"Z"),r.offset&&t.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${t.join("|")})`,new RegExp(`^${e}$`)}function Of(r,e){return!!((e==="v4"||!e)&&Cf.test(r)||(e==="v6"||!e)&&If.test(r))}function Nf(r,e){if(!kf.test(r))return!1;try{let[t]=r.split(".");if(!t)return!1;let n=t.replace(/-/g,"+").replace(/_/g,"/").padEnd(t.length+(4-t.length%4)%4,"="),s=JSON.parse(atob(n));return!(typeof s!="object"||s===null||"typ"in s&&s?.typ!=="JWT"||!s.alg||e&&s.alg!==e)}catch{return!1}}function Mf(r,e){return!!((e==="v4"||!e)&&Ef.test(r)||(e==="v6"||!e)&&Af.test(r))}var Ct=class r extends F{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==E.ZodParsedType.string){let i=this._getOrReturnCtx(e);return(0,_.addIssueToContext)(i,{code:C.ZodIssueCode.invalid_type,expected:E.ZodParsedType.string,received:i.parsedType}),_.INVALID}let n=new _.ParseStatus,s;for(let i of this._def.checks)if(i.kind==="min")e.data.length<i.value&&(s=this._getOrReturnCtx(e,s),(0,_.addIssueToContext)(s,{code:C.ZodIssueCode.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),n.dirty());else if(i.kind==="max")e.data.length>i.value&&(s=this._getOrReturnCtx(e,s),(0,_.addIssueToContext)(s,{code:C.ZodIssueCode.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),n.dirty());else if(i.kind==="length"){let o=e.data.length>i.value,a=e.data.length<i.value;(o||a)&&(s=this._getOrReturnCtx(e,s),o?(0,_.addIssueToContext)(s,{code:C.ZodIssueCode.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}):a&&(0,_.addIssueToContext)(s,{code:C.ZodIssueCode.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}),n.dirty())}else if(i.kind==="email")Tf.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,_.addIssueToContext)(s,{validation:"email",code:C.ZodIssueCode.invalid_string,message:i.message}),n.dirty());else if(i.kind==="emoji")Pi||(Pi=new RegExp(xf,"u")),Pi.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,_.addIssueToContext)(s,{validation:"emoji",code:C.ZodIssueCode.invalid_string,message:i.message}),n.dirty());else if(i.kind==="uuid")bf.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,_.addIssueToContext)(s,{validation:"uuid",code:C.ZodIssueCode.invalid_string,message:i.message}),n.dirty());else if(i.kind==="nanoid")wf.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,_.addIssueToContext)(s,{validation:"nanoid",code:C.ZodIssueCode.invalid_string,message:i.message}),n.dirty());else if(i.kind==="cuid")yf.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,_.addIssueToContext)(s,{validation:"cuid",code:C.ZodIssueCode.invalid_string,message:i.message}),n.dirty());else if(i.kind==="cuid2")_f.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,_.addIssueToContext)(s,{validation:"cuid2",code:C.ZodIssueCode.invalid_string,message:i.message}),n.dirty());else if(i.kind==="ulid")vf.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,_.addIssueToContext)(s,{validation:"ulid",code:C.ZodIssueCode.invalid_string,message:i.message}),n.dirty());else if(i.kind==="url")try{new URL(e.data)}catch{s=this._getOrReturnCtx(e,s),(0,_.addIssueToContext)(s,{validation:"url",code:C.ZodIssueCode.invalid_string,message:i.message}),n.dirty()}else i.kind==="regex"?(i.regex.lastIndex=0,i.regex.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,_.addIssueToContext)(s,{validation:"regex",code:C.ZodIssueCode.invalid_string,message:i.message}),n.dirty())):i.kind==="trim"?e.data=e.data.trim():i.kind==="includes"?e.data.includes(i.value,i.position)||(s=this._getOrReturnCtx(e,s),(0,_.addIssueToContext)(s,{code:C.ZodIssueCode.invalid_string,validation:{includes:i.value,position:i.position},message:i.message}),n.dirty()):i.kind==="toLowerCase"?e.data=e.data.toLowerCase():i.kind==="toUpperCase"?e.data=e.data.toUpperCase():i.kind==="startsWith"?e.data.startsWith(i.value)||(s=this._getOrReturnCtx(e,s),(0,_.addIssueToContext)(s,{code:C.ZodIssueCode.invalid_string,validation:{startsWith:i.value},message:i.message}),n.dirty()):i.kind==="endsWith"?e.data.endsWith(i.value)||(s=this._getOrReturnCtx(e,s),(0,_.addIssueToContext)(s,{code:C.ZodIssueCode.invalid_string,validation:{endsWith:i.value},message:i.message}),n.dirty()):i.kind==="datetime"?Xa(i).test(e.data)||(s=this._getOrReturnCtx(e,s),(0,_.addIssueToContext)(s,{code:C.ZodIssueCode.invalid_string,validation:"datetime",message:i.message}),n.dirty()):i.kind==="date"?Pf.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,_.addIssueToContext)(s,{code:C.ZodIssueCode.invalid_string,validation:"date",message:i.message}),n.dirty()):i.kind==="time"?jf(i).test(e.data)||(s=this._getOrReturnCtx(e,s),(0,_.addIssueToContext)(s,{code:C.ZodIssueCode.invalid_string,validation:"time",message:i.message}),n.dirty()):i.kind==="duration"?Sf.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,_.addIssueToContext)(s,{validation:"duration",code:C.ZodIssueCode.invalid_string,message:i.message}),n.dirty()):i.kind==="ip"?Of(e.data,i.version)||(s=this._getOrReturnCtx(e,s),(0,_.addIssueToContext)(s,{validation:"ip",code:C.ZodIssueCode.invalid_string,message:i.message}),n.dirty()):i.kind==="jwt"?Nf(e.data,i.alg)||(s=this._getOrReturnCtx(e,s),(0,_.addIssueToContext)(s,{validation:"jwt",code:C.ZodIssueCode.invalid_string,message:i.message}),n.dirty()):i.kind==="cidr"?Mf(e.data,i.version)||(s=this._getOrReturnCtx(e,s),(0,_.addIssueToContext)(s,{validation:"cidr",code:C.ZodIssueCode.invalid_string,message:i.message}),n.dirty()):i.kind==="base64"?Rf.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,_.addIssueToContext)(s,{validation:"base64",code:C.ZodIssueCode.invalid_string,message:i.message}),n.dirty()):i.kind==="base64url"?$f.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,_.addIssueToContext)(s,{validation:"base64url",code:C.ZodIssueCode.invalid_string,message:i.message}),n.dirty()):E.util.assertNever(i);return{status:n.value,value:e.data}}_regex(e,t,n){return this.refinement(s=>e.test(s),{validation:t,code:C.ZodIssueCode.invalid_string,...O.errorUtil.errToObj(n)})}_addCheck(e){return new r({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...O.errorUtil.errToObj(e)})}url(e){return this._addCheck({kind:"url",...O.errorUtil.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...O.errorUtil.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...O.errorUtil.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...O.errorUtil.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...O.errorUtil.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...O.errorUtil.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...O.errorUtil.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...O.errorUtil.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...O.errorUtil.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...O.errorUtil.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...O.errorUtil.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...O.errorUtil.errToObj(e)})}datetime(e){return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...O.errorUtil.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof e?.precision>"u"?null:e?.precision,...O.errorUtil.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...O.errorUtil.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...O.errorUtil.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t?.position,...O.errorUtil.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...O.errorUtil.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...O.errorUtil.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...O.errorUtil.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...O.errorUtil.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...O.errorUtil.errToObj(t)})}nonempty(e){return this.min(1,O.errorUtil.errToObj(e))}trim(){return new r({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new r({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new r({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}};y.ZodString=Ct;Ct.create=r=>new Ct({checks:[],typeName:L.ZodString,coerce:r?.coerce??!1,...B(r)});function Df(r,e){let t=(r.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,s=t>n?t:n,i=Number.parseInt(r.toFixed(s).replace(".","")),o=Number.parseInt(e.toFixed(s).replace(".",""));return i%o/10**s}var Xt=class r extends F{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==E.ZodParsedType.number){let i=this._getOrReturnCtx(e);return(0,_.addIssueToContext)(i,{code:C.ZodIssueCode.invalid_type,expected:E.ZodParsedType.number,received:i.parsedType}),_.INVALID}let n,s=new _.ParseStatus;for(let i of this._def.checks)i.kind==="int"?E.util.isInteger(e.data)||(n=this._getOrReturnCtx(e,n),(0,_.addIssueToContext)(n,{code:C.ZodIssueCode.invalid_type,expected:"integer",received:"float",message:i.message}),s.dirty()):i.kind==="min"?(i.inclusive?e.data<i.value:e.data<=i.value)&&(n=this._getOrReturnCtx(e,n),(0,_.addIssueToContext)(n,{code:C.ZodIssueCode.too_small,minimum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),s.dirty()):i.kind==="max"?(i.inclusive?e.data>i.value:e.data>=i.value)&&(n=this._getOrReturnCtx(e,n),(0,_.addIssueToContext)(n,{code:C.ZodIssueCode.too_big,maximum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),s.dirty()):i.kind==="multipleOf"?Df(e.data,i.value)!==0&&(n=this._getOrReturnCtx(e,n),(0,_.addIssueToContext)(n,{code:C.ZodIssueCode.not_multiple_of,multipleOf:i.value,message:i.message}),s.dirty()):i.kind==="finite"?Number.isFinite(e.data)||(n=this._getOrReturnCtx(e,n),(0,_.addIssueToContext)(n,{code:C.ZodIssueCode.not_finite,message:i.message}),s.dirty()):E.util.assertNever(i);return{status:s.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,O.errorUtil.toString(t))}gt(e,t){return this.setLimit("min",e,!1,O.errorUtil.toString(t))}lte(e,t){return this.setLimit("max",e,!0,O.errorUtil.toString(t))}lt(e,t){return this.setLimit("max",e,!1,O.errorUtil.toString(t))}setLimit(e,t,n,s){return new r({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:n,message:O.errorUtil.toString(s)}]})}_addCheck(e){return new r({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:O.errorUtil.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:O.errorUtil.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:O.errorUtil.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:O.errorUtil.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:O.errorUtil.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:O.errorUtil.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:O.errorUtil.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:O.errorUtil.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:O.errorUtil.toString(e)})}get minValue(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&E.util.isInteger(e.value))}get isFinite(){let e=null,t=null;for(let n of this._def.checks){if(n.kind==="finite"||n.kind==="int"||n.kind==="multipleOf")return!0;n.kind==="min"?(t===null||n.value>t)&&(t=n.value):n.kind==="max"&&(e===null||n.value<e)&&(e=n.value)}return Number.isFinite(t)&&Number.isFinite(e)}};y.ZodNumber=Xt;Xt.create=r=>new Xt({checks:[],typeName:L.ZodNumber,coerce:r?.coerce||!1,...B(r)});var Qt=class r extends F{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==E.ZodParsedType.bigint)return this._getInvalidInput(e);let n,s=new _.ParseStatus;for(let i of this._def.checks)i.kind==="min"?(i.inclusive?e.data<i.value:e.data<=i.value)&&(n=this._getOrReturnCtx(e,n),(0,_.addIssueToContext)(n,{code:C.ZodIssueCode.too_small,type:"bigint",minimum:i.value,inclusive:i.inclusive,message:i.message}),s.dirty()):i.kind==="max"?(i.inclusive?e.data>i.value:e.data>=i.value)&&(n=this._getOrReturnCtx(e,n),(0,_.addIssueToContext)(n,{code:C.ZodIssueCode.too_big,type:"bigint",maximum:i.value,inclusive:i.inclusive,message:i.message}),s.dirty()):i.kind==="multipleOf"?e.data%i.value!==BigInt(0)&&(n=this._getOrReturnCtx(e,n),(0,_.addIssueToContext)(n,{code:C.ZodIssueCode.not_multiple_of,multipleOf:i.value,message:i.message}),s.dirty()):E.util.assertNever(i);return{status:s.value,value:e.data}}_getInvalidInput(e){let t=this._getOrReturnCtx(e);return(0,_.addIssueToContext)(t,{code:C.ZodIssueCode.invalid_type,expected:E.ZodParsedType.bigint,received:t.parsedType}),_.INVALID}gte(e,t){return this.setLimit("min",e,!0,O.errorUtil.toString(t))}gt(e,t){return this.setLimit("min",e,!1,O.errorUtil.toString(t))}lte(e,t){return this.setLimit("max",e,!0,O.errorUtil.toString(t))}lt(e,t){return this.setLimit("max",e,!1,O.errorUtil.toString(t))}setLimit(e,t,n,s){return new r({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:n,message:O.errorUtil.toString(s)}]})}_addCheck(e){return new r({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:O.errorUtil.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:O.errorUtil.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:O.errorUtil.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:O.errorUtil.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:O.errorUtil.toString(t)})}get minValue(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}};y.ZodBigInt=Qt;Qt.create=r=>new Qt({checks:[],typeName:L.ZodBigInt,coerce:r?.coerce??!1,...B(r)});var er=class extends F{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==E.ZodParsedType.boolean){let n=this._getOrReturnCtx(e);return(0,_.addIssueToContext)(n,{code:C.ZodIssueCode.invalid_type,expected:E.ZodParsedType.boolean,received:n.parsedType}),_.INVALID}return(0,_.OK)(e.data)}};y.ZodBoolean=er;er.create=r=>new er({typeName:L.ZodBoolean,coerce:r?.coerce||!1,...B(r)});var tr=class r extends F{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==E.ZodParsedType.date){let i=this._getOrReturnCtx(e);return(0,_.addIssueToContext)(i,{code:C.ZodIssueCode.invalid_type,expected:E.ZodParsedType.date,received:i.parsedType}),_.INVALID}if(Number.isNaN(e.data.getTime())){let i=this._getOrReturnCtx(e);return(0,_.addIssueToContext)(i,{code:C.ZodIssueCode.invalid_date}),_.INVALID}let n=new _.ParseStatus,s;for(let i of this._def.checks)i.kind==="min"?e.data.getTime()<i.value&&(s=this._getOrReturnCtx(e,s),(0,_.addIssueToContext)(s,{code:C.ZodIssueCode.too_small,message:i.message,inclusive:!0,exact:!1,minimum:i.value,type:"date"}),n.dirty()):i.kind==="max"?e.data.getTime()>i.value&&(s=this._getOrReturnCtx(e,s),(0,_.addIssueToContext)(s,{code:C.ZodIssueCode.too_big,message:i.message,inclusive:!0,exact:!1,maximum:i.value,type:"date"}),n.dirty()):E.util.assertNever(i);return{status:n.value,value:new Date(e.data.getTime())}}_addCheck(e){return new r({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:O.errorUtil.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:O.errorUtil.toString(t)})}get minDate(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e!=null?new Date(e):null}};y.ZodDate=tr;tr.create=r=>new tr({checks:[],coerce:r?.coerce||!1,typeName:L.ZodDate,...B(r)});var Fr=class extends F{_parse(e){if(this._getType(e)!==E.ZodParsedType.symbol){let n=this._getOrReturnCtx(e);return(0,_.addIssueToContext)(n,{code:C.ZodIssueCode.invalid_type,expected:E.ZodParsedType.symbol,received:n.parsedType}),_.INVALID}return(0,_.OK)(e.data)}};y.ZodSymbol=Fr;Fr.create=r=>new Fr({typeName:L.ZodSymbol,...B(r)});var rr=class extends F{_parse(e){if(this._getType(e)!==E.ZodParsedType.undefined){let n=this._getOrReturnCtx(e);return(0,_.addIssueToContext)(n,{code:C.ZodIssueCode.invalid_type,expected:E.ZodParsedType.undefined,received:n.parsedType}),_.INVALID}return(0,_.OK)(e.data)}};y.ZodUndefined=rr;rr.create=r=>new rr({typeName:L.ZodUndefined,...B(r)});var nr=class extends F{_parse(e){if(this._getType(e)!==E.ZodParsedType.null){let n=this._getOrReturnCtx(e);return(0,_.addIssueToContext)(n,{code:C.ZodIssueCode.invalid_type,expected:E.ZodParsedType.null,received:n.parsedType}),_.INVALID}return(0,_.OK)(e.data)}};y.ZodNull=nr;nr.create=r=>new nr({typeName:L.ZodNull,...B(r)});var Et=class extends F{constructor(){super(...arguments),this._any=!0}_parse(e){return(0,_.OK)(e.data)}};y.ZodAny=Et;Et.create=r=>new Et({typeName:L.ZodAny,...B(r)});var at=class extends F{constructor(){super(...arguments),this._unknown=!0}_parse(e){return(0,_.OK)(e.data)}};y.ZodUnknown=at;at.create=r=>new at({typeName:L.ZodUnknown,...B(r)});var Le=class extends F{_parse(e){let t=this._getOrReturnCtx(e);return(0,_.addIssueToContext)(t,{code:C.ZodIssueCode.invalid_type,expected:E.ZodParsedType.never,received:t.parsedType}),_.INVALID}};y.ZodNever=Le;Le.create=r=>new Le({typeName:L.ZodNever,...B(r)});var Zr=class extends F{_parse(e){if(this._getType(e)!==E.ZodParsedType.undefined){let n=this._getOrReturnCtx(e);return(0,_.addIssueToContext)(n,{code:C.ZodIssueCode.invalid_type,expected:E.ZodParsedType.void,received:n.parsedType}),_.INVALID}return(0,_.OK)(e.data)}};y.ZodVoid=Zr;Zr.create=r=>new Zr({typeName:L.ZodVoid,...B(r)});var ut=class r extends F{_parse(e){let{ctx:t,status:n}=this._processInputParams(e),s=this._def;if(t.parsedType!==E.ZodParsedType.array)return(0,_.addIssueToContext)(t,{code:C.ZodIssueCode.invalid_type,expected:E.ZodParsedType.array,received:t.parsedType}),_.INVALID;if(s.exactLength!==null){let o=t.data.length>s.exactLength.value,a=t.data.length<s.exactLength.value;(o||a)&&((0,_.addIssueToContext)(t,{code:o?C.ZodIssueCode.too_big:C.ZodIssueCode.too_small,minimum:a?s.exactLength.value:void 0,maximum:o?s.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:s.exactLength.message}),n.dirty())}if(s.minLength!==null&&t.data.length<s.minLength.value&&((0,_.addIssueToContext)(t,{code:C.ZodIssueCode.too_small,minimum:s.minLength.value,type:"array",inclusive:!0,exact:!1,message:s.minLength.message}),n.dirty()),s.maxLength!==null&&t.data.length>s.maxLength.value&&((0,_.addIssueToContext)(t,{code:C.ZodIssueCode.too_big,maximum:s.maxLength.value,type:"array",inclusive:!0,exact:!1,message:s.maxLength.message}),n.dirty()),t.common.async)return Promise.all([...t.data].map((o,a)=>s.type._parseAsync(new Pe(t,o,t.path,a)))).then(o=>_.ParseStatus.mergeArray(n,o));let i=[...t.data].map((o,a)=>s.type._parseSync(new Pe(t,o,t.path,a)));return _.ParseStatus.mergeArray(n,i)}get element(){return this._def.type}min(e,t){return new r({...this._def,minLength:{value:e,message:O.errorUtil.toString(t)}})}max(e,t){return new r({...this._def,maxLength:{value:e,message:O.errorUtil.toString(t)}})}length(e,t){return new r({...this._def,exactLength:{value:e,message:O.errorUtil.toString(t)}})}nonempty(e){return this.min(1,e)}};y.ZodArray=ut;ut.create=(r,e)=>new ut({type:r,minLength:null,maxLength:null,exactLength:null,typeName:L.ZodArray,...B(e)});function Br(r){if(r instanceof _e){let e={};for(let t in r.shape){let n=r.shape[t];e[t]=$e.create(Br(n))}return new _e({...r._def,shape:()=>e})}else return r instanceof ut?new ut({...r._def,type:Br(r.element)}):r instanceof $e?$e.create(Br(r.unwrap())):r instanceof He?He.create(Br(r.unwrap())):r instanceof Ve?Ve.create(r.items.map(e=>Br(e))):r}var _e=class r extends F{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape(),t=E.util.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==E.ZodParsedType.object){let l=this._getOrReturnCtx(e);return(0,_.addIssueToContext)(l,{code:C.ZodIssueCode.invalid_type,expected:E.ZodParsedType.object,received:l.parsedType}),_.INVALID}let{status:n,ctx:s}=this._processInputParams(e),{shape:i,keys:o}=this._getCached(),a=[];if(!(this._def.catchall instanceof Le&&this._def.unknownKeys==="strip"))for(let l in s.data)o.includes(l)||a.push(l);let c=[];for(let l of o){let d=i[l],p=s.data[l];c.push({key:{status:"valid",value:l},value:d._parse(new Pe(s,p,s.path,l)),alwaysSet:l in s.data})}if(this._def.catchall instanceof Le){let l=this._def.unknownKeys;if(l==="passthrough")for(let d of a)c.push({key:{status:"valid",value:d},value:{status:"valid",value:s.data[d]}});else if(l==="strict")a.length>0&&((0,_.addIssueToContext)(s,{code:C.ZodIssueCode.unrecognized_keys,keys:a}),n.dirty());else if(l!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let l=this._def.catchall;for(let d of a){let p=s.data[d];c.push({key:{status:"valid",value:d},value:l._parse(new Pe(s,p,s.path,d)),alwaysSet:d in s.data})}}return s.common.async?Promise.resolve().then(async()=>{let l=[];for(let d of c){let p=await d.key,v=await d.value;l.push({key:p,value:v,alwaysSet:d.alwaysSet})}return l}).then(l=>_.ParseStatus.mergeObjectSync(n,l)):_.ParseStatus.mergeObjectSync(n,c)}get shape(){return this._def.shape()}strict(e){return O.errorUtil.errToObj,new r({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(t,n)=>{let s=this._def.errorMap?.(t,n).message??n.defaultError;return t.code==="unrecognized_keys"?{message:O.errorUtil.errToObj(e).message??s}:{message:s}}}:{}})}strip(){return new r({...this._def,unknownKeys:"strip"})}passthrough(){return new r({...this._def,unknownKeys:"passthrough"})}extend(e){return new r({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new r({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:L.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new r({...this._def,catchall:e})}pick(e){let t={};for(let n of E.util.objectKeys(e))e[n]&&this.shape[n]&&(t[n]=this.shape[n]);return new r({...this._def,shape:()=>t})}omit(e){let t={};for(let n of E.util.objectKeys(this.shape))e[n]||(t[n]=this.shape[n]);return new r({...this._def,shape:()=>t})}deepPartial(){return Br(this)}partial(e){let t={};for(let n of E.util.objectKeys(this.shape)){let s=this.shape[n];e&&!e[n]?t[n]=s:t[n]=s.optional()}return new r({...this._def,shape:()=>t})}required(e){let t={};for(let n of E.util.objectKeys(this.shape))if(e&&!e[n])t[n]=this.shape[n];else{let i=this.shape[n];for(;i instanceof $e;)i=i._def.innerType;t[n]=i}return new r({...this._def,shape:()=>t})}keyof(){return Qa(E.util.objectKeys(this.shape))}};y.ZodObject=_e;_e.create=(r,e)=>new _e({shape:()=>r,unknownKeys:"strip",catchall:Le.create(),typeName:L.ZodObject,...B(e)});_e.strictCreate=(r,e)=>new _e({shape:()=>r,unknownKeys:"strict",catchall:Le.create(),typeName:L.ZodObject,...B(e)});_e.lazycreate=(r,e)=>new _e({shape:r,unknownKeys:"strip",catchall:Le.create(),typeName:L.ZodObject,...B(e)});var sr=class extends F{_parse(e){let{ctx:t}=this._processInputParams(e),n=this._def.options;function s(i){for(let a of i)if(a.result.status==="valid")return a.result;for(let a of i)if(a.result.status==="dirty")return t.common.issues.push(...a.ctx.common.issues),a.result;let o=i.map(a=>new C.ZodError(a.ctx.common.issues));return(0,_.addIssueToContext)(t,{code:C.ZodIssueCode.invalid_union,unionErrors:o}),_.INVALID}if(t.common.async)return Promise.all(n.map(async i=>{let o={...t,common:{...t.common,issues:[]},parent:null};return{result:await i._parseAsync({data:t.data,path:t.path,parent:o}),ctx:o}})).then(s);{let i,o=[];for(let c of n){let l={...t,common:{...t.common,issues:[]},parent:null},d=c._parseSync({data:t.data,path:t.path,parent:l});if(d.status==="valid")return d;d.status==="dirty"&&!i&&(i={result:d,ctx:l}),l.common.issues.length&&o.push(l.common.issues)}if(i)return t.common.issues.push(...i.ctx.common.issues),i.result;let a=o.map(c=>new C.ZodError(c));return(0,_.addIssueToContext)(t,{code:C.ZodIssueCode.invalid_union,unionErrors:a}),_.INVALID}}get options(){return this._def.options}};y.ZodUnion=sr;sr.create=(r,e)=>new sr({options:r,typeName:L.ZodUnion,...B(e)});var ot=r=>r instanceof or?ot(r.schema):r instanceof ke?ot(r.innerType()):r instanceof ar?[r.value]:r instanceof ur?r.options:r instanceof cr?E.util.objectValues(r.enum):r instanceof lr?ot(r._def.innerType):r instanceof rr?[void 0]:r instanceof nr?[null]:r instanceof $e?[void 0,...ot(r.unwrap())]:r instanceof He?[null,...ot(r.unwrap())]:r instanceof En||r instanceof hr?ot(r.unwrap()):r instanceof dr?ot(r._def.innerType):[],gs=class r extends F{_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==E.ZodParsedType.object)return(0,_.addIssueToContext)(t,{code:C.ZodIssueCode.invalid_type,expected:E.ZodParsedType.object,received:t.parsedType}),_.INVALID;let n=this.discriminator,s=t.data[n],i=this.optionsMap.get(s);return i?t.common.async?i._parseAsync({data:t.data,path:t.path,parent:t}):i._parseSync({data:t.data,path:t.path,parent:t}):((0,_.addIssueToContext)(t,{code:C.ZodIssueCode.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),_.INVALID)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,t,n){let s=new Map;for(let i of t){let o=ot(i.shape[e]);if(!o.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let a of o){if(s.has(a))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(a)}`);s.set(a,i)}}return new r({typeName:L.ZodDiscriminatedUnion,discriminator:e,options:t,optionsMap:s,...B(n)})}};y.ZodDiscriminatedUnion=gs;function ji(r,e){let t=(0,E.getParsedType)(r),n=(0,E.getParsedType)(e);if(r===e)return{valid:!0,data:r};if(t===E.ZodParsedType.object&&n===E.ZodParsedType.object){let s=E.util.objectKeys(e),i=E.util.objectKeys(r).filter(a=>s.indexOf(a)!==-1),o={...r,...e};for(let a of i){let c=ji(r[a],e[a]);if(!c.valid)return{valid:!1};o[a]=c.data}return{valid:!0,data:o}}else if(t===E.ZodParsedType.array&&n===E.ZodParsedType.array){if(r.length!==e.length)return{valid:!1};let s=[];for(let i=0;i<r.length;i++){let o=r[i],a=e[i],c=ji(o,a);if(!c.valid)return{valid:!1};s.push(c.data)}return{valid:!0,data:s}}else return t===E.ZodParsedType.date&&n===E.ZodParsedType.date&&+r==+e?{valid:!0,data:r}:{valid:!1}}var ir=class extends F{_parse(e){let{status:t,ctx:n}=this._processInputParams(e),s=(i,o)=>{if((0,_.isAborted)(i)||(0,_.isAborted)(o))return _.INVALID;let a=ji(i.value,o.value);return a.valid?(((0,_.isDirty)(i)||(0,_.isDirty)(o))&&t.dirty(),{status:t.value,value:a.data}):((0,_.addIssueToContext)(n,{code:C.ZodIssueCode.invalid_intersection_types}),_.INVALID)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([i,o])=>s(i,o)):s(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}};y.ZodIntersection=ir;ir.create=(r,e,t)=>new ir({left:r,right:e,typeName:L.ZodIntersection,...B(t)});var Ve=class r extends F{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==E.ZodParsedType.array)return(0,_.addIssueToContext)(n,{code:C.ZodIssueCode.invalid_type,expected:E.ZodParsedType.array,received:n.parsedType}),_.INVALID;if(n.data.length<this._def.items.length)return(0,_.addIssueToContext)(n,{code:C.ZodIssueCode.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),_.INVALID;!this._def.rest&&n.data.length>this._def.items.length&&((0,_.addIssueToContext)(n,{code:C.ZodIssueCode.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());let i=[...n.data].map((o,a)=>{let c=this._def.items[a]||this._def.rest;return c?c._parse(new Pe(n,o,n.path,a)):null}).filter(o=>!!o);return n.common.async?Promise.all(i).then(o=>_.ParseStatus.mergeArray(t,o)):_.ParseStatus.mergeArray(t,i)}get items(){return this._def.items}rest(e){return new r({...this._def,rest:e})}};y.ZodTuple=Ve;Ve.create=(r,e)=>{if(!Array.isArray(r))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Ve({items:r,typeName:L.ZodTuple,rest:null,...B(e)})};var ys=class r extends F{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==E.ZodParsedType.object)return(0,_.addIssueToContext)(n,{code:C.ZodIssueCode.invalid_type,expected:E.ZodParsedType.object,received:n.parsedType}),_.INVALID;let s=[],i=this._def.keyType,o=this._def.valueType;for(let a in n.data)s.push({key:i._parse(new Pe(n,a,n.path,a)),value:o._parse(new Pe(n,n.data[a],n.path,a)),alwaysSet:a in n.data});return n.common.async?_.ParseStatus.mergeObjectAsync(t,s):_.ParseStatus.mergeObjectSync(t,s)}get element(){return this._def.valueType}static create(e,t,n){return t instanceof F?new r({keyType:e,valueType:t,typeName:L.ZodRecord,...B(n)}):new r({keyType:Ct.create(),valueType:e,typeName:L.ZodRecord,...B(t)})}};y.ZodRecord=ys;var Kr=class extends F{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==E.ZodParsedType.map)return(0,_.addIssueToContext)(n,{code:C.ZodIssueCode.invalid_type,expected:E.ZodParsedType.map,received:n.parsedType}),_.INVALID;let s=this._def.keyType,i=this._def.valueType,o=[...n.data.entries()].map(([a,c],l)=>({key:s._parse(new Pe(n,a,n.path,[l,"key"])),value:i._parse(new Pe(n,c,n.path,[l,"value"]))}));if(n.common.async){let a=new Map;return Promise.resolve().then(async()=>{for(let c of o){let l=await c.key,d=await c.value;if(l.status==="aborted"||d.status==="aborted")return _.INVALID;(l.status==="dirty"||d.status==="dirty")&&t.dirty(),a.set(l.value,d.value)}return{status:t.value,value:a}})}else{let a=new Map;for(let c of o){let l=c.key,d=c.value;if(l.status==="aborted"||d.status==="aborted")return _.INVALID;(l.status==="dirty"||d.status==="dirty")&&t.dirty(),a.set(l.value,d.value)}return{status:t.value,value:a}}}};y.ZodMap=Kr;Kr.create=(r,e,t)=>new Kr({valueType:e,keyType:r,typeName:L.ZodMap,...B(t)});var Vr=class r extends F{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==E.ZodParsedType.set)return(0,_.addIssueToContext)(n,{code:C.ZodIssueCode.invalid_type,expected:E.ZodParsedType.set,received:n.parsedType}),_.INVALID;let s=this._def;s.minSize!==null&&n.data.size<s.minSize.value&&((0,_.addIssueToContext)(n,{code:C.ZodIssueCode.too_small,minimum:s.minSize.value,type:"set",inclusive:!0,exact:!1,message:s.minSize.message}),t.dirty()),s.maxSize!==null&&n.data.size>s.maxSize.value&&((0,_.addIssueToContext)(n,{code:C.ZodIssueCode.too_big,maximum:s.maxSize.value,type:"set",inclusive:!0,exact:!1,message:s.maxSize.message}),t.dirty());let i=this._def.valueType;function o(c){let l=new Set;for(let d of c){if(d.status==="aborted")return _.INVALID;d.status==="dirty"&&t.dirty(),l.add(d.value)}return{status:t.value,value:l}}let a=[...n.data.values()].map((c,l)=>i._parse(new Pe(n,c,n.path,l)));return n.common.async?Promise.all(a).then(c=>o(c)):o(a)}min(e,t){return new r({...this._def,minSize:{value:e,message:O.errorUtil.toString(t)}})}max(e,t){return new r({...this._def,maxSize:{value:e,message:O.errorUtil.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}};y.ZodSet=Vr;Vr.create=(r,e)=>new Vr({valueType:r,minSize:null,maxSize:null,typeName:L.ZodSet,...B(e)});var _s=class r extends F{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==E.ZodParsedType.function)return(0,_.addIssueToContext)(t,{code:C.ZodIssueCode.invalid_type,expected:E.ZodParsedType.function,received:t.parsedType}),_.INVALID;function n(a,c){return(0,_.makeIssue)({data:a,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,(0,ms.getErrorMap)(),ms.defaultErrorMap].filter(l=>!!l),issueData:{code:C.ZodIssueCode.invalid_arguments,argumentsError:c}})}function s(a,c){return(0,_.makeIssue)({data:a,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,(0,ms.getErrorMap)(),ms.defaultErrorMap].filter(l=>!!l),issueData:{code:C.ZodIssueCode.invalid_return_type,returnTypeError:c}})}let i={errorMap:t.common.contextualErrorMap},o=t.data;if(this._def.returns instanceof It){let a=this;return(0,_.OK)(async function(...c){let l=new C.ZodError([]),d=await a._def.args.parseAsync(c,i).catch(S=>{throw l.addIssue(n(c,S)),l}),p=await Reflect.apply(o,this,d);return await a._def.returns._def.type.parseAsync(p,i).catch(S=>{throw l.addIssue(s(p,S)),l})})}else{let a=this;return(0,_.OK)(function(...c){let l=a._def.args.safeParse(c,i);if(!l.success)throw new C.ZodError([n(c,l.error)]);let d=Reflect.apply(o,this,l.data),p=a._def.returns.safeParse(d,i);if(!p.success)throw new C.ZodError([s(d,p.error)]);return p.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new r({...this._def,args:Ve.create(e).rest(at.create())})}returns(e){return new r({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,t,n){return new r({args:e||Ve.create([]).rest(at.create()),returns:t||at.create(),typeName:L.ZodFunction,...B(n)})}};y.ZodFunction=_s;var or=class extends F{get schema(){return this._def.getter()}_parse(e){let{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}};y.ZodLazy=or;or.create=(r,e)=>new or({getter:r,typeName:L.ZodLazy,...B(e)});var ar=class extends F{_parse(e){if(e.data!==this._def.value){let t=this._getOrReturnCtx(e);return(0,_.addIssueToContext)(t,{received:t.data,code:C.ZodIssueCode.invalid_literal,expected:this._def.value}),_.INVALID}return{status:"valid",value:e.data}}get value(){return this._def.value}};y.ZodLiteral=ar;ar.create=(r,e)=>new ar({value:r,typeName:L.ZodLiteral,...B(e)});function Qa(r,e){return new ur({values:r,typeName:L.ZodEnum,...B(e)})}var ur=class r extends F{_parse(e){if(typeof e.data!="string"){let t=this._getOrReturnCtx(e),n=this._def.values;return(0,_.addIssueToContext)(t,{expected:E.util.joinValues(n),received:t.parsedType,code:C.ZodIssueCode.invalid_type}),_.INVALID}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){let t=this._getOrReturnCtx(e),n=this._def.values;return(0,_.addIssueToContext)(t,{received:t.data,code:C.ZodIssueCode.invalid_enum_value,options:n}),_.INVALID}return(0,_.OK)(e.data)}get options(){return this._def.values}get enum(){let e={};for(let t of this._def.values)e[t]=t;return e}get Values(){let e={};for(let t of this._def.values)e[t]=t;return e}get Enum(){let e={};for(let t of this._def.values)e[t]=t;return e}extract(e,t=this._def){return r.create(e,{...this._def,...t})}exclude(e,t=this._def){return r.create(this.options.filter(n=>!e.includes(n)),{...this._def,...t})}};y.ZodEnum=ur;ur.create=Qa;var cr=class extends F{_parse(e){let t=E.util.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==E.ZodParsedType.string&&n.parsedType!==E.ZodParsedType.number){let s=E.util.objectValues(t);return(0,_.addIssueToContext)(n,{expected:E.util.joinValues(s),received:n.parsedType,code:C.ZodIssueCode.invalid_type}),_.INVALID}if(this._cache||(this._cache=new Set(E.util.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let s=E.util.objectValues(t);return(0,_.addIssueToContext)(n,{received:n.data,code:C.ZodIssueCode.invalid_enum_value,options:s}),_.INVALID}return(0,_.OK)(e.data)}get enum(){return this._def.values}};y.ZodNativeEnum=cr;cr.create=(r,e)=>new cr({values:r,typeName:L.ZodNativeEnum,...B(e)});var It=class extends F{unwrap(){return this._def.type}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==E.ZodParsedType.promise&&t.common.async===!1)return(0,_.addIssueToContext)(t,{code:C.ZodIssueCode.invalid_type,expected:E.ZodParsedType.promise,received:t.parsedType}),_.INVALID;let n=t.parsedType===E.ZodParsedType.promise?t.data:Promise.resolve(t.data);return(0,_.OK)(n.then(s=>this._def.type.parseAsync(s,{path:t.path,errorMap:t.common.contextualErrorMap})))}};y.ZodPromise=It;It.create=(r,e)=>new It({type:r,typeName:L.ZodPromise,...B(e)});var ke=class extends F{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===L.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:t,ctx:n}=this._processInputParams(e),s=this._def.effect||null,i={addIssue:o=>{(0,_.addIssueToContext)(n,o),o.fatal?t.abort():t.dirty()},get path(){return n.path}};if(i.addIssue=i.addIssue.bind(i),s.type==="preprocess"){let o=s.transform(n.data,i);if(n.common.async)return Promise.resolve(o).then(async a=>{if(t.value==="aborted")return _.INVALID;let c=await this._def.schema._parseAsync({data:a,path:n.path,parent:n});return c.status==="aborted"?_.INVALID:c.status==="dirty"||t.value==="dirty"?(0,_.DIRTY)(c.value):c});{if(t.value==="aborted")return _.INVALID;let a=this._def.schema._parseSync({data:o,path:n.path,parent:n});return a.status==="aborted"?_.INVALID:a.status==="dirty"||t.value==="dirty"?(0,_.DIRTY)(a.value):a}}if(s.type==="refinement"){let o=a=>{let c=s.refinement(a,i);if(n.common.async)return Promise.resolve(c);if(c instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return a};if(n.common.async===!1){let a=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return a.status==="aborted"?_.INVALID:(a.status==="dirty"&&t.dirty(),o(a.value),{status:t.value,value:a.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(a=>a.status==="aborted"?_.INVALID:(a.status==="dirty"&&t.dirty(),o(a.value).then(()=>({status:t.value,value:a.value}))))}if(s.type==="transform")if(n.common.async===!1){let o=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!(0,_.isValid)(o))return _.INVALID;let a=s.transform(o.value,i);if(a instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:t.value,value:a}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(o=>(0,_.isValid)(o)?Promise.resolve(s.transform(o.value,i)).then(a=>({status:t.value,value:a})):_.INVALID);E.util.assertNever(s)}};y.ZodEffects=ke;y.ZodTransformer=ke;ke.create=(r,e,t)=>new ke({schema:r,typeName:L.ZodEffects,effect:e,...B(t)});ke.createWithPreprocess=(r,e,t)=>new ke({schema:e,effect:{type:"preprocess",transform:r},typeName:L.ZodEffects,...B(t)});var $e=class extends F{_parse(e){return this._getType(e)===E.ZodParsedType.undefined?(0,_.OK)(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};y.ZodOptional=$e;$e.create=(r,e)=>new $e({innerType:r,typeName:L.ZodOptional,...B(e)});var He=class extends F{_parse(e){return this._getType(e)===E.ZodParsedType.null?(0,_.OK)(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};y.ZodNullable=He;He.create=(r,e)=>new He({innerType:r,typeName:L.ZodNullable,...B(e)});var lr=class extends F{_parse(e){let{ctx:t}=this._processInputParams(e),n=t.data;return t.parsedType===E.ZodParsedType.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:t.path,parent:t})}removeDefault(){return this._def.innerType}};y.ZodDefault=lr;lr.create=(r,e)=>new lr({innerType:r,typeName:L.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...B(e)});var dr=class extends F{_parse(e){let{ctx:t}=this._processInputParams(e),n={...t,common:{...t.common,issues:[]}},s=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return(0,_.isAsync)(s)?s.then(i=>({status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new C.ZodError(n.common.issues)},input:n.data})})):{status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new C.ZodError(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};y.ZodCatch=dr;dr.create=(r,e)=>new dr({innerType:r,typeName:L.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...B(e)});var Hr=class extends F{_parse(e){if(this._getType(e)!==E.ZodParsedType.nan){let n=this._getOrReturnCtx(e);return(0,_.addIssueToContext)(n,{code:C.ZodIssueCode.invalid_type,expected:E.ZodParsedType.nan,received:n.parsedType}),_.INVALID}return{status:"valid",value:e.data}}};y.ZodNaN=Hr;Hr.create=r=>new Hr({typeName:L.ZodNaN,...B(r)});y.BRAND=Symbol("zod_brand");var En=class extends F{_parse(e){let{ctx:t}=this._processInputParams(e),n=t.data;return this._def.type._parse({data:n,path:t.path,parent:t})}unwrap(){return this._def.type}};y.ZodBranded=En;var In=class r extends F{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{let i=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return i.status==="aborted"?_.INVALID:i.status==="dirty"?(t.dirty(),(0,_.DIRTY)(i.value)):this._def.out._parseAsync({data:i.value,path:n.path,parent:n})})();{let s=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return s.status==="aborted"?_.INVALID:s.status==="dirty"?(t.dirty(),{status:"dirty",value:s.value}):this._def.out._parseSync({data:s.value,path:n.path,parent:n})}}static create(e,t){return new r({in:e,out:t,typeName:L.ZodPipeline})}};y.ZodPipeline=In;var hr=class extends F{_parse(e){let t=this._def.innerType._parse(e),n=s=>((0,_.isValid)(s)&&(s.value=Object.freeze(s.value)),s);return(0,_.isAsync)(t)?t.then(s=>n(s)):n(t)}unwrap(){return this._def.innerType}};y.ZodReadonly=hr;hr.create=(r,e)=>new hr({innerType:r,typeName:L.ZodReadonly,...B(e)});function Wa(r,e){let t=typeof r=="function"?r(e):typeof r=="string"?{message:r}:r;return typeof t=="string"?{message:t}:t}function eu(r,e={},t){return r?Et.create().superRefine((n,s)=>{let i=r(n);if(i instanceof Promise)return i.then(o=>{if(!o){let a=Wa(e,n),c=a.fatal??t??!0;s.addIssue({code:"custom",...a,fatal:c})}});if(!i){let o=Wa(e,n),a=o.fatal??t??!0;s.addIssue({code:"custom",...o,fatal:a})}}):Et.create()}y.late={object:_e.lazycreate};var L;(function(r){r.ZodString="ZodString",r.ZodNumber="ZodNumber",r.ZodNaN="ZodNaN",r.ZodBigInt="ZodBigInt",r.ZodBoolean="ZodBoolean",r.ZodDate="ZodDate",r.ZodSymbol="ZodSymbol",r.ZodUndefined="ZodUndefined",r.ZodNull="ZodNull",r.ZodAny="ZodAny",r.ZodUnknown="ZodUnknown",r.ZodNever="ZodNever",r.ZodVoid="ZodVoid",r.ZodArray="ZodArray",r.ZodObject="ZodObject",r.ZodUnion="ZodUnion",r.ZodDiscriminatedUnion="ZodDiscriminatedUnion",r.ZodIntersection="ZodIntersection",r.ZodTuple="ZodTuple",r.ZodRecord="ZodRecord",r.ZodMap="ZodMap",r.ZodSet="ZodSet",r.ZodFunction="ZodFunction",r.ZodLazy="ZodLazy",r.ZodLiteral="ZodLiteral",r.ZodEnum="ZodEnum",r.ZodEffects="ZodEffects",r.ZodNativeEnum="ZodNativeEnum",r.ZodOptional="ZodOptional",r.ZodNullable="ZodNullable",r.ZodDefault="ZodDefault",r.ZodCatch="ZodCatch",r.ZodPromise="ZodPromise",r.ZodBranded="ZodBranded",r.ZodPipeline="ZodPipeline",r.ZodReadonly="ZodReadonly"})(L||(y.ZodFirstPartyTypeKind=L={}));var Lf=(r,e={message:`Input not instance of ${r.name}`})=>eu(t=>t instanceof r,e);y.instanceof=Lf;var tu=Ct.create;y.string=tu;var ru=Xt.create;y.number=ru;var zf=Hr.create;y.nan=zf;var Uf=Qt.create;y.bigint=Uf;var nu=er.create;y.boolean=nu;var qf=tr.create;y.date=qf;var Bf=Fr.create;y.symbol=Bf;var Ff=rr.create;y.undefined=Ff;var Zf=nr.create;y.null=Zf;var Kf=Et.create;y.any=Kf;var Vf=at.create;y.unknown=Vf;var Hf=Le.create;y.never=Hf;var Gf=Zr.create;y.void=Gf;var Wf=ut.create;y.array=Wf;var Jf=_e.create;y.object=Jf;var Yf=_e.strictCreate;y.strictObject=Yf;var Xf=sr.create;y.union=Xf;var Qf=gs.create;y.discriminatedUnion=Qf;var ep=ir.create;y.intersection=ep;var tp=Ve.create;y.tuple=tp;var rp=ys.create;y.record=rp;var np=Kr.create;y.map=np;var sp=Vr.create;y.set=sp;var ip=_s.create;y.function=ip;var op=or.create;y.lazy=op;var ap=ar.create;y.literal=ap;var up=ur.create;y.enum=up;var cp=cr.create;y.nativeEnum=cp;var lp=It.create;y.promise=lp;var su=ke.create;y.effect=su;y.transformer=su;var dp=$e.create;y.optional=dp;var hp=He.create;y.nullable=hp;var fp=ke.createWithPreprocess;y.preprocess=fp;var pp=In.create;y.pipeline=pp;var mp=()=>tu().optional();y.ostring=mp;var gp=()=>ru().optional();y.onumber=gp;var yp=()=>nu().optional();y.oboolean=yp;y.coerce={string:(r=>Ct.create({...r,coerce:!0})),number:(r=>Xt.create({...r,coerce:!0})),boolean:(r=>er.create({...r,coerce:!0})),bigint:(r=>Qt.create({...r,coerce:!0})),date:(r=>tr.create({...r,coerce:!0}))};y.NEVER=_.INVALID});var Oi=Y(je=>{"use strict";var _p=je&&je.__createBinding||(Object.create?(function(r,e,t,n){n===void 0&&(n=t);var s=Object.getOwnPropertyDescriptor(e,t);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(r,n,s)}):(function(r,e,t,n){n===void 0&&(n=t),r[n]=e[t]})),Gr=je&&je.__exportStar||function(r,e){for(var t in r)t!=="default"&&!Object.prototype.hasOwnProperty.call(e,t)&&_p(e,r,t)};Object.defineProperty(je,"__esModule",{value:!0});Gr(fs(),je);Gr($i(),je);Gr(Ka(),je);Gr(xn(),je);Gr(iu(),je);Gr(hs(),je)});var uu=Y(ve=>{"use strict";var ou=ve&&ve.__createBinding||(Object.create?(function(r,e,t,n){n===void 0&&(n=t);var s=Object.getOwnPropertyDescriptor(e,t);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(r,n,s)}):(function(r,e,t,n){n===void 0&&(n=t),r[n]=e[t]})),vp=ve&&ve.__setModuleDefault||(Object.create?(function(r,e){Object.defineProperty(r,"default",{enumerable:!0,value:e})}):function(r,e){r.default=e}),bp=ve&&ve.__importStar||function(r){if(r&&r.__esModule)return r;var e={};if(r!=null)for(var t in r)t!=="default"&&Object.prototype.hasOwnProperty.call(r,t)&&ou(e,r,t);return vp(e,r),e},wp=ve&&ve.__exportStar||function(r,e){for(var t in r)t!=="default"&&!Object.prototype.hasOwnProperty.call(e,t)&&ou(e,r,t)};Object.defineProperty(ve,"__esModule",{value:!0});ve.z=void 0;var au=bp(Oi());ve.z=au;wp(Oi(),ve);ve.default=au});var Se=Y(h=>{"use strict";Object.defineProperty(h,"__esModule",{value:!0});h.EpicListResultMsg=h.EpicChild=h.EpicListMsg=h.BoardTriggerResultMsg=h.BoardTriggerMsg=h.BoardFetchResultMsg=h.BoardFetchMsg=h.ChatLoadResultMsg=h.ChatLoadMsg=h.ChatListResultMsg=h.ChatListMsg=h.ChatStreamMsg=h.JiraUsersResultMsg=h.DeployClaimResultMsg=h.DeployClaimMsg=h.RuleDiagnoseResultMsg=h.ProjectTestResultMsg=h.RunStatusMsg=h.RunLogMsg=h.RunClaimMsg=h.HeartbeatMsg=h.HelloMsg=h.RuleConfig=h.ProjectConfig=h.ActionConfig=h.DeployAction=h.EnvironmentConfig=h.PromotionMode=h.DeployStep=h.RespondAction=h.ImplementAction=h.PlanOnlyAction=h.TriggerConfig=h.StatusChangedTrigger=h.CommentKeywordTrigger=h.LabelAddedTrigger=h.ActionType=h.TriggerType=h.ACTIVE_RUN_STATUSES=h.RunStatus=h.needsInputMarkerIn=h.LEGACY_NEEDS_INPUT_COMMENT_MARKERS=h.NEEDS_INPUT_COMMENT_MARKER=h.NEEDS_INPUT_LABEL=h.NEEDS_INPUT_MARKER=h.BRANCH_DEPLOY_ISSUE_KEY=h.REQUIRED_AGENT_CAPABILITIES=h.DEFAULT_AGENT_ID=h.REGISTERED_AGENTS=h.PROTOCOL_VERSION=void 0;h.DEFAULT_IMPLEMENT_PROMPT_TEMPLATE=h.DEFAULT_PLAN_PROMPT_TEMPLATE=h.EnrollResponse=h.EnrollRequest=h.ServerToRunnerMsg=h.JiraUsersMsg=h.DeploySuggestMsg=h.DeployStartMsg=h.RunRetryPushMsg=h.RunRejectedMsg=h.RunApprovedMsg=h.RunCancelMsg=h.RuleDiagnoseMsg=h.ProjectTestMsg=h.RunClaimResultMsg=h.ConfigMsg=h.HelloAckMsg=h.RunnerToServerMsg=h.SetupStatusResultMsg=h.SetupStatusMsg=h.DeploySuggestResultMsg=h.EnvPreflightResultMsg=h.EnvPreflightMsg=h.ChatCreateTicketResultMsg=h.ChatCreateTicketMsg=h.ChatTurnResultMsg=h.ChatTurnMsg=h.ChatFile=h.TeamCredsResultMsg=h.TeamCredsMsg=h.KnowledgeSaveResultMsg=h.KnowledgeSaveMsg=h.KnowledgeListResultMsg=h.KnowledgeFile=h.KnowledgeListMsg=h.AuditReviewResultMsg=h.AuditReviewMsg=h.AuditGetResultMsg=h.AuditGetMsg=h.AuditListResultMsg=h.AuditListMsg=h.AuditStartResultMsg=h.AuditStartMsg=h.AuditRecord=h.AuditFinding=h.AuditScope=h.AuditSeverity=h.AuditRole=h.EpicSuggestResultMsg=h.EpicSuggestMsg=void 0;h.DEFAULT_DEPLOY_SUGGEST_PROMPT_TEMPLATE=h.DEPLOY_DOC_SUGGEST_PROMPT_TEMPLATE=h.PROMPT_PRESETS=h.DEFAULT_RESPOND_PROMPT_TEMPLATE=h.BUGFIX_IMPLEMENT_PROMPT_TEMPLATE=h.BUG_INVESTIGATION_PROMPT_TEMPLATE=h.TECHNICAL_PLAN_PROMPT_TEMPLATE=h.MEMORY_UPDATE_PROMPT=void 0;h.missingAgentCapabilities=kp;h.parseRunnerMsg=Tp;h.parseServerMsg=xp;var u=uu();h.PROTOCOL_VERSION="1.23";h.REGISTERED_AGENTS=[{id:"claude-code",displayName:"Claude Code",capabilities:{readOnlyJail:!0,editNoShellJail:!0,sessionResume:!0,costReporting:!0,modelSelection:!0,loginProfiles:!0},suggestedModels:["claude-fable-5","claude-opus-5","claude-sonnet-5","claude-haiku-4-5-20251001"],experimental:!1},{id:"codex",displayName:"OpenAI Codex CLI (experimental)",capabilities:{readOnlyJail:!0,editNoShellJail:!1,sessionResume:!1,costReporting:!1,modelSelection:!0,loginProfiles:!1},suggestedModels:[],experimental:!0}];h.DEFAULT_AGENT_ID="claude-code";h.REQUIRED_AGENT_CAPABILITIES={plan_only:["readOnlyJail","sessionResume"],respond:["readOnlyJail"],implement:["editNoShellJail","sessionResume"],deploy:[]};function kp(r,e){let t=h.REGISTERED_AGENTS.find(n=>n.id===r);return t?(h.REQUIRED_AGENT_CAPABILITIES[e]??[]).filter(n=>!t.capabilities[n]):null}h.BRANCH_DEPLOY_ISSUE_KEY="(branch deploy)";h.NEEDS_INPUT_MARKER="NEEDS-INPUT";h.NEEDS_INPUT_LABEL="agent-needs-input";h.NEEDS_INPUT_COMMENT_MARKER="Allwright needs your input";h.LEGACY_NEEDS_INPUT_COMMENT_MARKERS=["TicketPilot needs your input"];var Sp=r=>r.includes(h.NEEDS_INPUT_COMMENT_MARKER)||h.LEGACY_NEEDS_INPUT_COMMENT_MARKERS.some(e=>r.includes(e));h.needsInputMarkerIn=Sp;h.RunStatus=u.z.enum(["queued","running","posting","awaiting_approval","needs_input","succeeded","failed","timed_out"]);h.ACTIVE_RUN_STATUSES=["queued","running","posting","awaiting_approval"];h.TriggerType=u.z.enum(["label_added","comment_keyword","status_changed"]);h.ActionType=u.z.enum(["plan_only","implement","respond","deploy"]);h.LabelAddedTrigger=u.z.object({type:u.z.literal("label_added"),label:u.z.string().min(1),doneLabel:u.z.string().min(1).default("agent-planned"),failedLabel:u.z.string().min(1).default("agent-failed")});h.CommentKeywordTrigger=u.z.object({type:u.z.literal("comment_keyword"),keyword:u.z.string().min(1),doneLabel:u.z.string().min(1).default("agent-implemented"),failedLabel:u.z.string().min(1).default("agent-failed")});h.StatusChangedTrigger=u.z.object({type:u.z.literal("status_changed"),status:u.z.string().min(1),doneLabel:u.z.string().min(1).default("agent-deployed"),failedLabel:u.z.string().min(1).default("agent-failed")});h.TriggerConfig=u.z.discriminatedUnion("type",[h.LabelAddedTrigger,h.CommentKeywordTrigger,h.StatusChangedTrigger]);h.PlanOnlyAction=u.z.object({type:u.z.literal("plan_only"),promptTemplate:u.z.string().min(1),timeoutSeconds:u.z.number().int().positive().max(3600).default(900),agent:u.z.string().default(h.DEFAULT_AGENT_ID),model:u.z.string().default("")});h.ImplementAction=u.z.object({type:u.z.literal("implement"),promptTemplate:u.z.string().min(1),timeoutSeconds:u.z.number().int().positive().max(7200).default(1800),maxTurns:u.z.number().int().positive().max(500).default(120),requireApproval:u.z.boolean().default(!0),branchTemplate:u.z.string().min(1).default("agent/{{issueKey}}").refine(r=>r.includes("{{issueKey}}"),{message:"branchTemplate must contain {{issueKey}}"}),baseBranch:u.z.string().min(1).default("main"),jiraTransition:u.z.string().optional(),jiraTransitionOnStart:u.z.string().optional(),jiraTransitionOnMerge:u.z.string().optional(),agent:u.z.string().default(h.DEFAULT_AGENT_ID),model:u.z.string().default(""),updateMemory:u.z.boolean().default(!1)});h.RespondAction=u.z.object({type:u.z.literal("respond"),promptTemplate:u.z.string().min(1),timeoutSeconds:u.z.number().int().positive().max(3600).default(600),agent:u.z.string().default(h.DEFAULT_AGENT_ID),model:u.z.string().default("")});h.DeployStep=u.z.object({name:u.z.string().min(1).max(120),run:u.z.string().min(1).max(4e3),continueOnError:u.z.boolean().default(!1)});h.PromotionMode=u.z.enum(["deploy_only","merge_and_deploy"]);h.EnvironmentConfig=u.z.object({id:u.z.string(),projectId:u.z.string(),name:u.z.string(),rank:u.z.number().int().nonnegative(),auditBeforeDeploy:u.z.enum(["","security","testing"]).default(""),branch:u.z.string().default(""),publicUrl:u.z.string().default(""),useDedicatedCheckout:u.z.boolean().default(!1),promotionMode:h.PromotionMode.default("deploy_only"),ticketBranchTemplate:u.z.string().default("agent/{{issueKey}}"),steps:u.z.array(h.DeployStep).default([]),workdir:u.z.string().default(""),timeoutSeconds:u.z.number().int().positive().max(21600).default(1800),requiredSecrets:u.z.array(u.z.string()).default([]),requireApproval:u.z.boolean().default(!1),requireSyncCheck:u.z.boolean().default(!1),previousEnvBranch:u.z.string().optional(),deployFromColumn:u.z.string().default(""),deployToColumn:u.z.string().default("")});h.DeployAction=u.z.object({type:u.z.literal("deploy"),envSelection:u.z.enum(["fixed","from_comment"]).default("from_comment"),environmentId:u.z.string().optional(),requireStatus:u.z.string().optional()});h.ActionConfig=u.z.discriminatedUnion("type",[h.PlanOnlyAction,h.ImplementAction,h.RespondAction,h.DeployAction]);h.ProjectConfig=u.z.object({id:u.z.string(),name:u.z.string(),jiraProjectKey:u.z.string(),repoName:u.z.string(),componentRoutes:u.z.array(u.z.object({component:u.z.string().min(1),repoName:u.z.string().min(1)})).default([])});h.RuleConfig=u.z.object({id:u.z.string(),projectId:u.z.string(),name:u.z.string(),enabled:u.z.boolean(),trigger:h.TriggerConfig,action:h.ActionConfig});h.HelloMsg=u.z.object({type:u.z.literal("hello"),protocolVersion:u.z.string(),runnerVersion:u.z.string(),platform:u.z.string(),justBooted:u.z.boolean().optional()});h.HeartbeatMsg=u.z.object({type:u.z.literal("heartbeat"),ts:u.z.string()});h.RunClaimMsg=u.z.object({type:u.z.literal("run.claim"),requestId:u.z.string(),ruleId:u.z.string(),issueKey:u.z.string(),issueSummary:u.z.string().default(""),triggerFingerprint:u.z.string(),dedupKey:u.z.string().optional(),triggeredByAccountId:u.z.string().optional()});h.RunLogMsg=u.z.object({type:u.z.literal("run.log"),runId:u.z.string(),seq:u.z.number().int().nonnegative(),ts:u.z.string(),level:u.z.enum(["info","warn","error","agent"]),message:u.z.string().max(16384)});h.RunStatusMsg=u.z.object({type:u.z.literal("run.status"),runId:u.z.string(),status:h.RunStatus,error:u.z.string().optional(),errorKind:u.z.enum(["guard"]).optional(),costUsd:u.z.number().nonnegative().optional(),inputTokens:u.z.number().int().nonnegative().optional(),outputTokens:u.z.number().int().nonnegative().optional(),resultSummary:u.z.string().max(2e3).optional(),billingMode:u.z.enum(["subscription","api","unknown"]).optional(),model:u.z.string().max(200).optional(),prUrl:u.z.string().optional(),headSha:u.z.string().optional(),deployedRef:u.z.string().optional(),retryAvailable:u.z.boolean().optional()});h.ProjectTestResultMsg=u.z.object({type:u.z.literal("project.test.result"),requestId:u.z.string(),ok:u.z.boolean(),checks:u.z.array(u.z.object({name:u.z.string(),ok:u.z.boolean(),detail:u.z.string()}))});h.RuleDiagnoseResultMsg=u.z.object({type:u.z.literal("rule.diagnose.result"),requestId:u.z.string(),checks:u.z.array(u.z.object({name:u.z.string(),ok:u.z.boolean(),detail:u.z.string()})),matchedCount:u.z.number().int().nonnegative(),excludedCount:u.z.number().int().nonnegative(),excludedSample:u.z.array(u.z.string()).max(5)});h.DeployClaimMsg=u.z.object({type:u.z.literal("deploy.claim"),requestId:u.z.string(),projectId:u.z.string(),ruleId:u.z.string(),issueKey:u.z.string(),issueSummary:u.z.string().default(""),environmentName:u.z.string(),requestedByAccountId:u.z.string().optional(),requestedByDisplayName:u.z.string().default(""),dedupKey:u.z.string(),triggerFingerprint:u.z.string()});h.DeployClaimResultMsg=u.z.object({type:u.z.literal("deploy.claim.result"),requestId:u.z.string(),accepted:u.z.boolean(),runId:u.z.string().optional(),environment:h.EnvironmentConfig.optional(),reason:u.z.string().optional(),code:u.z.enum(["ok","duplicate","unknown_environment","not_permitted","unlinked_jira_account","promotion_order","jira_disabled","rule_disabled","cap"]).optional()});h.JiraUsersResultMsg=u.z.object({type:u.z.literal("jira.users.result"),requestId:u.z.string(),ok:u.z.boolean(),users:u.z.array(u.z.object({accountId:u.z.string(),displayName:u.z.string(),email:u.z.string().default(""),active:u.z.boolean().default(!0)})).default([]),error:u.z.string().optional()});h.ChatStreamMsg=u.z.object({type:u.z.literal("chat.stream"),requestId:u.z.string(),seq:u.z.number().int().nonnegative(),text:u.z.string().max(8e3)});h.ChatListMsg=u.z.object({type:u.z.literal("chat.list"),requestId:u.z.string(),projectId:u.z.string()});h.ChatListResultMsg=u.z.object({type:u.z.literal("chat.list.result"),requestId:u.z.string(),sessions:u.z.array(u.z.object({sessionId:u.z.string(),title:u.z.string().default(""),updatedAt:u.z.string().default(""),messageCount:u.z.number().int().nonnegative().default(0)})).default([])});h.ChatLoadMsg=u.z.object({type:u.z.literal("chat.load"),requestId:u.z.string(),sessionId:u.z.string()});h.ChatLoadResultMsg=u.z.object({type:u.z.literal("chat.load.result"),requestId:u.z.string(),ok:u.z.boolean(),projectId:u.z.string().default(""),messages:u.z.array(u.z.object({role:u.z.enum(["user","agent"]),text:u.z.string()})).default([]),error:u.z.string().optional()});h.BoardFetchMsg=u.z.object({type:u.z.literal("board.fetch"),requestId:u.z.string(),projectId:u.z.string()});h.BoardFetchResultMsg=u.z.object({type:u.z.literal("board.fetch.result"),requestId:u.z.string(),ok:u.z.boolean(),browseBaseUrl:u.z.string().default(""),columns:u.z.array(u.z.object({name:u.z.string(),issues:u.z.array(u.z.object({key:u.z.string(),summary:u.z.string(),labels:u.z.array(u.z.string()).default([])})).default([])})).default([]),error:u.z.string().optional()});h.BoardTriggerMsg=u.z.object({type:u.z.literal("board.trigger"),requestId:u.z.string(),projectId:u.z.string(),issueKey:u.z.string(),comment:u.z.string().max(2e3).default(""),removeLabel:u.z.string().default(""),requestedBy:u.z.string().default(""),requestedByEmail:u.z.string().default(""),reimplement:u.z.boolean().default(!1)});h.BoardTriggerResultMsg=u.z.object({type:u.z.literal("board.trigger.result"),requestId:u.z.string(),ok:u.z.boolean(),error:u.z.string().optional()});h.EpicListMsg=u.z.object({type:u.z.literal("epic.list"),requestId:u.z.string(),projectId:u.z.string(),epicKey:u.z.string().default("")});h.EpicChild=u.z.object({key:u.z.string(),summary:u.z.string(),status:u.z.string(),statusCategory:u.z.string(),labels:u.z.array(u.z.string()).default([])});h.EpicListResultMsg=u.z.object({type:u.z.literal("epic.list.result"),requestId:u.z.string(),ok:u.z.boolean(),error:u.z.string().optional(),epics:u.z.array(u.z.object({key:u.z.string(),summary:u.z.string(),status:u.z.string()})).default([]),children:u.z.array(h.EpicChild).default([])});h.EpicSuggestMsg=u.z.object({type:u.z.literal("epic.suggest"),requestId:u.z.string(),projectId:u.z.string(),epicKey:u.z.string().min(1),model:u.z.string().default("")});h.EpicSuggestResultMsg=u.z.object({type:u.z.literal("epic.suggest.result"),requestId:u.z.string(),ok:u.z.boolean(),error:u.z.string().optional(),issueKey:u.z.string().default(""),reason:u.z.string().default(""),considered:u.z.number().int().default(0)});h.AuditRole=u.z.enum(["security","testing","architecture"]);h.AuditSeverity=u.z.enum(["critical","high","medium","low","info"]);h.AuditScope=u.z.object({kind:u.z.enum(["repo","ticket","branch"]).default("repo"),ref:u.z.string().default("")});h.AuditFinding=u.z.object({id:u.z.string().min(1),title:u.z.string().min(1),ruleId:u.z.string().max(20).default(""),severity:h.AuditSeverity,area:u.z.string().default(""),evidence:u.z.array(u.z.object({file:u.z.string().min(1),line:u.z.number().int().positive().optional(),note:u.z.string().default("")})).min(1),fix:u.z.string().default("")});h.AuditRecord=u.z.object({id:u.z.string(),role:h.AuditRole,createdAt:u.z.string(),model:u.z.string().default(""),summary:u.z.string().default(""),packNames:u.z.array(u.z.string()).default([]),findings:u.z.array(h.AuditFinding).default([]),costUsd:u.z.number().default(0),review:u.z.object({selected:u.z.array(u.z.string()),updatedAt:u.z.string()}).optional(),verdicts:u.z.record(u.z.object({verdict:u.z.enum(["valid","false-positive","wont-fix"]),note:u.z.string().default(""),by:u.z.string().default(""),at:u.z.string().default("")})).default({}),lessonsWritten:u.z.array(u.z.string()).default([]),ticketed:u.z.record(u.z.string()).default({}),scope:h.AuditScope.default({kind:"repo",ref:""}),testRun:u.z.array(u.z.object({command:u.z.string(),exitCode:u.z.number().int(),durationMs:u.z.number().int().default(0),tail:u.z.string().default("")})).optional()});h.AuditStartMsg=u.z.object({type:u.z.literal("audit.start"),requestId:u.z.string(),projectId:u.z.string(),role:h.AuditRole,model:u.z.string().default(""),scope:h.AuditScope.default({kind:"repo",ref:""})});h.AuditStartResultMsg=u.z.object({type:u.z.literal("audit.start.result"),requestId:u.z.string(),ok:u.z.boolean(),error:u.z.string().optional(),audit:h.AuditRecord.optional()});h.AuditListMsg=u.z.object({type:u.z.literal("audit.list"),requestId:u.z.string(),projectId:u.z.string()});h.AuditListResultMsg=u.z.object({type:u.z.literal("audit.list.result"),requestId:u.z.string(),ok:u.z.boolean(),error:u.z.string().optional(),audits:u.z.array(u.z.object({id:u.z.string(),role:h.AuditRole,createdAt:u.z.string(),findingCount:u.z.number().int(),bySeverity:u.z.record(u.z.number().int()).default({})})).default([])});h.AuditGetMsg=u.z.object({type:u.z.literal("audit.get"),requestId:u.z.string(),projectId:u.z.string(),auditId:u.z.string()});h.AuditGetResultMsg=u.z.object({type:u.z.literal("audit.get.result"),requestId:u.z.string(),ok:u.z.boolean(),error:u.z.string().optional(),audit:h.AuditRecord.optional()});h.AuditReviewMsg=u.z.object({type:u.z.literal("audit.review"),requestId:u.z.string(),projectId:u.z.string(),auditId:u.z.string(),selected:u.z.array(u.z.string()).optional(),ticketed:u.z.array(u.z.object({findingId:u.z.string(),issueKey:u.z.string()})).default([]),verdicts:u.z.array(u.z.object({findingId:u.z.string(),verdict:u.z.enum(["valid","false-positive","wont-fix"]),note:u.z.string().max(2e3).default("")})).default([]),verdictBy:u.z.string().default("")});h.AuditReviewResultMsg=u.z.object({type:u.z.literal("audit.review.result"),requestId:u.z.string(),ok:u.z.boolean(),error:u.z.string().optional(),audit:h.AuditRecord.optional()});h.KnowledgeListMsg=u.z.object({type:u.z.literal("knowledge.list"),requestId:u.z.string(),projectId:u.z.string()});h.KnowledgeFile=u.z.object({role:h.AuditRole,level:u.z.enum(["global","org","project"]),source:u.z.enum(["pack","lessons"]),name:u.z.string(),content:u.z.string(),editable:u.z.boolean().default(!1)});h.KnowledgeListResultMsg=u.z.object({type:u.z.literal("knowledge.list.result"),requestId:u.z.string(),ok:u.z.boolean(),error:u.z.string().optional(),files:u.z.array(h.KnowledgeFile).default([])});h.KnowledgeSaveMsg=u.z.object({type:u.z.literal("knowledge.save"),requestId:u.z.string(),projectId:u.z.string(),role:h.AuditRole,level:u.z.enum(["org","project"]),source:u.z.enum(["pack","lessons"]),name:u.z.string().min(1).max(100),content:u.z.string().max(6e4),append:u.z.boolean().default(!1),by:u.z.string().default("")});h.KnowledgeSaveResultMsg=u.z.object({type:u.z.literal("knowledge.save.result"),requestId:u.z.string(),ok:u.z.boolean(),error:u.z.string().optional()});h.TeamCredsMsg=u.z.object({type:u.z.literal("team.creds"),requestId:u.z.string(),emails:u.z.array(u.z.string()).max(200)});h.TeamCredsResultMsg=u.z.object({type:u.z.literal("team.creds.result"),requestId:u.z.string(),ok:u.z.boolean(),error:u.z.string().optional(),githubShared:u.z.boolean().default(!1),sharedGithubLogin:u.z.string().default(""),entries:u.z.array(u.z.object({email:u.z.string(),jira:u.z.enum(["own","runner-account","missing"]),jiraAs:u.z.string().default(""),github:u.z.enum(["own","shared","missing"]),githubAs:u.z.string().default("")})).default([])});h.ChatFile=u.z.object({name:u.z.string().min(1).max(255),contentBase64:u.z.string().min(1).max(6e6)});h.ChatTurnMsg=u.z.object({type:u.z.literal("chat.turn"),requestId:u.z.string(),projectId:u.z.string(),sessionId:u.z.string().optional(),message:u.z.string().min(1).max(2e4),userName:u.z.string().default(""),model:u.z.string().default(""),files:u.z.array(h.ChatFile).max(8).default([])});h.ChatTurnResultMsg=u.z.object({type:u.z.literal("chat.turn.result"),requestId:u.z.string(),ok:u.z.boolean(),sessionId:u.z.string().default(""),reply:u.z.string().default(""),error:u.z.string().optional()});h.ChatCreateTicketMsg=u.z.object({type:u.z.literal("chat.create.ticket"),requestId:u.z.string(),projectId:u.z.string(),summary:u.z.string().min(1).max(250),description:u.z.string().default(""),triggerComment:u.z.string().default(""),requestedBy:u.z.string().default(""),requestedByEmail:u.z.string().default(""),asEpic:u.z.boolean().default(!1),children:u.z.array(u.z.object({summary:u.z.string().min(1),description:u.z.string().default("")})).max(20).default([]),files:u.z.array(h.ChatFile).max(8).default([])});h.ChatCreateTicketResultMsg=u.z.object({type:u.z.literal("chat.create.ticket.result"),requestId:u.z.string(),ok:u.z.boolean(),issueKey:u.z.string().default(""),error:u.z.string().optional(),childKeys:u.z.array(u.z.string()).default([])});h.EnvPreflightMsg=u.z.object({type:u.z.literal("env.preflight"),requestId:u.z.string(),projectId:u.z.string(),environmentName:u.z.string().default(""),steps:u.z.array(h.DeployStep).default([]),requiredSecrets:u.z.array(u.z.string()).default([]),workdir:u.z.string().default(""),branch:u.z.string().default(""),publicUrl:u.z.string().default("")});h.EnvPreflightResultMsg=u.z.object({type:u.z.literal("env.preflight.result"),requestId:u.z.string(),ok:u.z.boolean(),checks:u.z.array(u.z.object({name:u.z.string(),ok:u.z.boolean(),detail:u.z.string().default("")})).default([])});h.DeploySuggestResultMsg=u.z.object({type:u.z.literal("deploy.suggest.result"),requestId:u.z.string(),ok:u.z.boolean(),steps:u.z.array(h.DeployStep).default([]),requiredSecrets:u.z.array(u.z.string()).default([]),notes:u.z.string().default(""),error:u.z.string().optional()});h.SetupStatusMsg=u.z.object({type:u.z.literal("setup.status"),requestId:u.z.string(),repoNames:u.z.array(u.z.string()).max(100).default([])});h.SetupStatusResultMsg=u.z.object({type:u.z.literal("setup.status.result"),requestId:u.z.string(),ok:u.z.boolean(),error:u.z.string().optional(),jiraConfigured:u.z.boolean().default(!1),jiraEmail:u.z.string().default(""),claude:u.z.object({installed:u.z.boolean(),version:u.z.string().default(""),loggedIn:u.z.boolean()}).optional(),githubTokenSet:u.z.boolean().default(!1),githubLogin:u.z.string().default(""),deploysEnabled:u.z.boolean().default(!1),jiraUserCount:u.z.number().int().default(0),repos:u.z.array(u.z.object({repoName:u.z.string(),mapped:u.z.boolean(),pathExists:u.z.boolean().default(!1),isGit:u.z.boolean().default(!1),claudeMd:u.z.boolean().default(!1),deployMd:u.z.boolean().default(!1),testMd:u.z.boolean().default(!1)})).default([])});h.RunnerToServerMsg=u.z.discriminatedUnion("type",[h.HelloMsg,h.HeartbeatMsg,h.RunClaimMsg,h.RunLogMsg,h.RunStatusMsg,h.ProjectTestResultMsg,h.RuleDiagnoseResultMsg,h.DeployClaimMsg,h.DeploySuggestResultMsg,h.EnvPreflightResultMsg,h.ChatTurnResultMsg,h.ChatStreamMsg,h.ChatCreateTicketResultMsg,h.ChatListResultMsg,h.ChatLoadResultMsg,h.BoardFetchResultMsg,h.BoardTriggerResultMsg,h.TeamCredsResultMsg,h.AuditStartResultMsg,h.AuditListResultMsg,h.AuditGetResultMsg,h.AuditReviewResultMsg,h.KnowledgeListResultMsg,h.KnowledgeSaveResultMsg,h.EpicListResultMsg,h.EpicSuggestResultMsg,h.JiraUsersResultMsg,h.SetupStatusResultMsg]);h.HelloAckMsg=u.z.object({type:u.z.literal("hello.ack"),runnerId:u.z.string(),runnerName:u.z.string(),serverTime:u.z.string()});h.ConfigMsg=u.z.object({type:u.z.literal("config"),projects:u.z.array(h.ProjectConfig),rules:u.z.array(h.RuleConfig),environments:u.z.array(h.EnvironmentConfig).default([]),pollingPaused:u.z.boolean().default(!1)});h.RunClaimResultMsg=u.z.object({type:u.z.literal("run.claim.result"),requestId:u.z.string(),accepted:u.z.boolean(),runId:u.z.string().optional(),reason:u.z.string().optional(),claudeProfile:u.z.string().optional(),actorEmail:u.z.string().optional()});h.ProjectTestMsg=u.z.object({type:u.z.literal("project.test"),requestId:u.z.string(),projectId:u.z.string()});h.RuleDiagnoseMsg=u.z.object({type:u.z.literal("rule.diagnose"),requestId:u.z.string(),ruleId:u.z.string()});h.RunCancelMsg=u.z.object({type:u.z.literal("run.cancel"),runId:u.z.string()});h.RunApprovedMsg=u.z.object({type:u.z.literal("run.approved"),runId:u.z.string(),headSha:u.z.string().optional()});h.RunRejectedMsg=u.z.object({type:u.z.literal("run.rejected"),runId:u.z.string()});h.RunRetryPushMsg=u.z.object({type:u.z.literal("run.retryPush"),runId:u.z.string()});h.DeployStartMsg=u.z.object({type:u.z.literal("deploy.start"),runId:u.z.string(),projectId:u.z.string(),issueKey:u.z.string(),issueSummary:u.z.string().default(""),environment:h.EnvironmentConfig,requestedBy:u.z.string().default(""),attempt:u.z.number().int().positive().default(1)});h.DeploySuggestMsg=u.z.object({type:u.z.literal("deploy.suggest"),requestId:u.z.string(),projectId:u.z.string(),environmentName:u.z.string(),notes:u.z.string().default(""),timeoutSeconds:u.z.number().int().positive().max(1800).default(300)});h.JiraUsersMsg=u.z.object({type:u.z.literal("jira.users"),requestId:u.z.string(),query:u.z.string().default("")});h.ServerToRunnerMsg=u.z.discriminatedUnion("type",[h.HelloAckMsg,h.ConfigMsg,h.RunClaimResultMsg,h.ProjectTestMsg,h.RuleDiagnoseMsg,h.RunCancelMsg,h.RunApprovedMsg,h.RunRejectedMsg,h.RunRetryPushMsg,h.DeployClaimResultMsg,h.DeployStartMsg,h.DeploySuggestMsg,h.EnvPreflightMsg,h.ChatTurnMsg,h.ChatCreateTicketMsg,h.ChatListMsg,h.ChatLoadMsg,h.BoardFetchMsg,h.BoardTriggerMsg,h.TeamCredsMsg,h.AuditStartMsg,h.AuditListMsg,h.AuditGetMsg,h.AuditReviewMsg,h.KnowledgeListMsg,h.KnowledgeSaveMsg,h.EpicListMsg,h.EpicSuggestMsg,h.JiraUsersMsg,h.SetupStatusMsg]);h.EnrollRequest=u.z.object({enrollToken:u.z.string().min(10),name:u.z.string().min(1).max(100),platform:u.z.string(),runnerVersion:u.z.string()});h.EnrollResponse=u.z.object({runnerId:u.z.string(),runnerToken:u.z.string(),controlPlaneWsUrl:u.z.string()});function Tp(r){return h.RunnerToServerMsg.parse(r)}function xp(r){return h.ServerToRunnerMsg.parse(r)}h.DEFAULT_PLAN_PROMPT_TEMPLATE=`You are a senior engineer asked to assess a Jira ticket. You have read-only access to the repository \u2014 do not attempt to modify anything.
24
24
 
25
25
  Ticket {{issueKey}}: {{summary}}
26
26
 
@@ -227,13 +227,13 @@ working tree: ${s.length?`
227
227
  ${i}${o}`:"clean"}`}function An(){let r=process.env.ALLWRIGHT_CACHE_DIR??process.env.TICKETPILOT_CACHE_DIR??(le.default.existsSync(re.default.join(fr.default.homedir(),".cache","ticketpilot"))?re.default.join(fr.default.homedir(),".cache","ticketpilot"):re.default.join(fr.default.homedir(),".cache","allwright"));return re.default.join(r,"worktrees")}async function Jr(r,e){try{await Z(r,["fetch","origin",e])}catch(t){throw new Error(`could not fetch base branch "${e}" from origin \u2014 check the rule's base branch and that this machine can reach the remote (${t instanceof Error?t.message:t})`)}}async function Li(r,e){try{let t=await Z(r,["worktree","list","--porcelain"]),n=An(),s=null;for(let i of t.split(`
228
228
  `))i.startsWith("worktree ")&&(s=i.slice(9).trim()),i===`branch refs/heads/${e}`&&s&&s.startsWith(n)&&await Z(r,["worktree","remove","--force",s]);await Z(r,["worktree","prune"])}catch{}try{await Z(r,["branch","-D",e])}catch{}}async function zi(r,e,t,n){le.default.mkdirSync(re.default.dirname(e),{recursive:!0,mode:448}),await Z(r,["worktree","add","-b",t,e,`origin/${n}`])}async function Ss(r,e){if(await Z(r,["add","-A"]),!(await Z(r,["status","--porcelain"])).trim())throw new Error("Claude wrote no changes \u2014 nothing to commit");await Z(r,["-c",`user.name=${mu}`,"-c",`user.email=${gu}`,"commit","-m",e])}async function Ui(r,e){let n=(await Z(r,["diff","--name-only",`origin/${e}...HEAD`])).split(`
229
229
  `).filter(Boolean),s=n.filter(l=>yu.some(d=>d.test(l))),i=await Z(r,["diff","--shortstat",`origin/${e}...HEAD`]),o=Number(/(\d+) insertion/.exec(i)?.[1]??0),a=Number(/(\d+) deletion/.exec(i)?.[1]??0);return{ok:s.length===0&&n.length<=bs&&o+a<=ws,files:n.length,insertions:o,deletions:a,forbidden:s}}async function qi(r,e){await Z(r,["fetch","--prune","origin",`+refs/heads/${e}:refs/remotes/origin/${e}`],{timeoutMs:12e4}).catch(()=>Z(r,["update-ref","-d",`refs/remotes/origin/${e}`]).catch(()=>{})),await Z(r,["push","--force-with-lease","-u","origin",e],{timeoutMs:3e5})}async function Rn(r){return(await Z(r,["rev-parse","HEAD"])).trim()}async function Ts(r,e){try{return(await Z(r,["rev-parse","--verify",`refs/heads/${e}`])).trim()}catch{return null}}async function Yr(r,e){try{await Z(r,["worktree","remove","--force",e])}catch{le.default.rmSync(e,{recursive:!0,force:!0})}}async function Bi(r,e=[]){let t=new Set(e.map(s=>re.default.basename(re.default.resolve(s))).filter(s=>s.length>0)),n=An();if(le.default.existsSync(n))for(let s of le.default.readdirSync(n))t.has(s)||le.default.rmSync(re.default.join(n,s),{recursive:!0,force:!0});for(let s of r)try{await Z(s,["worktree","prune"])}catch{}}async function Fi(r,e){return await Z(r,["fetch","origin","--prune"]).catch(()=>{}),(await Z(r,["branch","-r","--list",`*${e}*`])).split(`
230
- `).map(s=>s.trim()).filter(s=>s&&!s.includes("->"))[0]??null}async function xs(r,e,t=6e4){let s=(await Z(r,["symbolic-ref","refs/remotes/origin/HEAD"]).catch(()=>"")).trim().replace("refs/remotes/","")||"origin/main",i=await Z(r,["diff","--stat",`${s}...${e}`]),o=await Z(r,["diff",`${s}...${e}`]);return{base:s,stat:i.slice(0,4e3),diff:o.slice(0,t)}}function _u(){let r=process.env.ALLWRIGHT_CACHE_DIR??process.env.TICKETPILOT_CACHE_DIR??(le.default.existsSync(re.default.join(fr.default.homedir(),".cache","ticketpilot"))?re.default.join(fr.default.homedir(),".cache","ticketpilot"):re.default.join(fr.default.homedir(),".cache","allwright"));return re.default.join(r,"env-checkouts")}function du(r){return r.replace(/[^\w.-]+/g,"_")}function vu(r,e){return re.default.join(_u(),du(r),du(e))}async function Zi(r){let e=vu(r.repoName,r.envName);return await Z(r.repoPath,["fetch","origin",r.branch],{timeoutMs:3e5}),le.default.existsSync(re.default.join(e,".git"))?await Z(e,["fetch","origin",r.branch],{timeoutMs:3e5}):(le.default.rmSync(e,{recursive:!0,force:!0}),le.default.mkdirSync(re.default.dirname(e),{recursive:!0,mode:448}),await Z(r.repoPath,["worktree","prune"]).catch(()=>{}),await Z(r.repoPath,["worktree","add","--detach",e,`origin/${r.branch}`])),r.attached?await Z(e,["checkout","-B",r.branch,`origin/${r.branch}`]):await Z(e,["checkout","--force","--detach",`origin/${r.branch}`]),e}async function Ki(r,e,t){try{await Z(r,["fetch","origin",e],{timeoutMs:3e5})}catch{return{ok:!1,reason:`branch "${e}" does not exist on origin \u2014 nothing to promote. Check the environment's ticket branch template against the branch your implement rule creates.`}}try{return await Z(r,["merge-base","--is-ancestor",`origin/${e}`,"HEAD"]),{ok:!0,alreadyMerged:!0}}catch{}try{return await Z(r,["-c",`user.name=${mu}`,"-c",`user.email=${gu}`,"merge","--no-ff","-m",t,`origin/${e}`]),{ok:!0}}catch(n){return await Z(r,["merge","--abort"]).catch(()=>{}),{ok:!1,reason:`could not merge "${e}" into the environment branch \u2014 ${n instanceof Error?n.message:n}. Resolve it manually and deploy again.`}}}async function Vi(r,e){try{await Z(r,["push","origin",e],{timeoutMs:3e5})}catch(t){throw new Error(`could not push "${e}" \u2014 ${t instanceof Error?t.message:t}. Someone may have pushed to it since this deploy started; retry.`)}}async function Hi(r,e,t){try{return await pu("git",["-C",r,"diff","--quiet",e,t,"--"],{timeout:12e4,env:{...process.env,GIT_TERMINAL_PROMPT:"0"}}),!1}catch(n){let s=n;if(s.code===1)return!0;throw new Error(`git diff failed comparing ${e}..${t}: ${(s.stderr||s.message||"").trim().slice(0,500)}`)}}async function pr(r){return(await Z(r,["config","--get","remote.origin.url"])).trim()}function mr(r){let e=/^git@github\.com(?:-[\w.-]+)?:([^/]+)\/(.+?)(\.git)?$/.exec(r)??/^https:\/\/github\.com\/([^/]+)\/(.+?)(\.git)?\/?$/.exec(r)??/^ssh:\/\/git@github\.com(?:-[\w.-]+)?\/([^/]+)\/(.+?)(\.git)?$/.exec(r);return e?{owner:e[1],repo:e[2]}:null}var le,fr,re,hu,fu,pu,mu,gu,bs,ws,yu,Wr,gr=ii(()=>{"use strict";le=$(require("node:fs"),1),fr=$(require("node:os"),1),re=$(require("node:path"),1),hu=require("node:child_process"),fu=require("node:util"),pu=(0,fu.promisify)(hu.execFile),mu="Allwright Agent",gu="agent@ticketpilot.local",bs=200,ws=2e4,yu=[/^\.github\/workflows\//,/^\.git\b/,/(^|\/)\.githooks\//];Wr=".ticketpilot-delete"});var tn={};Yn(tn,{GitHubClient:()=>Oe});var Bp,Oe,ct=ii(()=>{"use strict";Bp=process.env.TICKETPILOT_GITHUB_API??"https://api.github.com",Oe=class{constructor(e){this.token=e}token;async request(e,t,n){let s=await fetch(`${Bp}${t}`,{method:e,headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","User-Agent":"allwright",...n!==void 0?{"Content-Type":"application/json"}:{}},body:n===void 0?void 0:JSON.stringify(n)}),i=await s.text(),o=null;try{o=i?JSON.parse(i):null}catch{}if(s.status===401)throw new Error("GitHub rejected the token (401) \u2014 expired or revoked? Run `allwright github set-token`");if(!s.ok&&s.status!==422){let a=o?.message??i.slice(0,300);throw new Error(`GitHub ${e} ${t} -> ${s.status}: ${a}`)}return{status:s.status,data:o}}async whoami(){let{data:e}=await this.request("GET","/user");return e.login}async createPullRequest(e,t,n){let{status:s,data:i}=await this.request("POST",`/repos/${e}/${t}/pulls`,n);if(s===422){let{data:o}=await this.request("GET",`/repos/${e}/${t}/pulls?head=${encodeURIComponent(`${e}:${n.head}`)}&state=open`);if(o?.length){let a=o[0];return{number:a.number,url:a.html_url,state:a.state,merged:a.merged??!1,headSha:a.head.sha,mergeableState:null}}throw new Error(`GitHub refused the PR (422): ${i?.message??"validation failed"}`)}return{number:i.number,url:i.html_url,state:i.state,merged:i.merged??!1,headSha:i.head.sha,mergeableState:null}}async getReviews(e,t,n){let{data:s}=await this.request("GET",`/repos/${e}/${t}/pulls/${n}/reviews?per_page=100`);return(s??[]).map(i=>({state:i.state??"",commitId:i.commit_id??"",user:i.user?.login??"",submittedAt:i.submitted_at??""}))}async getPullRequest(e,t,n){try{let{data:s}=await this.request("GET",`/repos/${e}/${t}/pulls/${n}`);return{number:s.number,url:s.html_url,state:s.state,merged:s.merged,headSha:s.head.sha,mergeableState:s.mergeable_state??null}}catch(s){if(s instanceof Error&&s.message.includes("-> 404"))return null;throw s}}async closePullRequest(e,t,n){await this.request("PATCH",`/repos/${e}/${t}/pulls/${n}`,{state:"closed"})}async deleteBranch(e,t,n){try{await this.request("DELETE",`/repos/${e}/${t}/git/refs/heads/${encodeURIComponent(n)}`)}catch(s){if(s instanceof Error&&s.message.includes("-> 404"))return;throw s}}}});var ht=Y((Dv,rl)=>{"use strict";var el=["nodebuffer","arraybuffer","fragments"],tl=typeof Blob<"u";tl&&el.push("blob");rl.exports={BINARY_TYPES:el,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:tl,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var qn=Y((Lv,Bs)=>{"use strict";var{EMPTY_BUFFER:Im}=ht(),Eo=Buffer[Symbol.species];function Am(r,e){if(r.length===0)return Im;if(r.length===1)return r[0];let t=Buffer.allocUnsafe(e),n=0;for(let s=0;s<r.length;s++){let i=r[s];t.set(i,n),n+=i.length}return n<e?new Eo(t.buffer,t.byteOffset,n):t}function nl(r,e,t,n,s){for(let i=0;i<s;i++)t[n+i]=r[i]^e[i&3]}function sl(r,e){for(let t=0;t<r.length;t++)r[t]^=e[t&3]}function Rm(r){return r.length===r.buffer.byteLength?r.buffer:r.buffer.slice(r.byteOffset,r.byteOffset+r.length)}function Io(r){if(Io.readOnly=!0,Buffer.isBuffer(r))return r;let e;return r instanceof ArrayBuffer?e=new Eo(r):ArrayBuffer.isView(r)?e=new Eo(r.buffer,r.byteOffset,r.byteLength):(e=Buffer.from(r),Io.readOnly=!1),e}Bs.exports={concat:Am,mask:nl,toArrayBuffer:Rm,toBuffer:Io,unmask:sl};if(!process.env.WS_NO_BUFFER_UTIL)try{let r=require("bufferutil");Bs.exports.mask=function(e,t,n,s,i){i<48?nl(e,t,n,s,i):r.mask(e,t,n,s,i)},Bs.exports.unmask=function(e,t){e.length<32?sl(e,t):r.unmask(e,t)}}catch{}});var al=Y((zv,ol)=>{"use strict";var il=Symbol("kDone"),Ao=Symbol("kRun"),Ro=class{constructor(e){this[il]=()=>{this.pending--,this[Ao]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[Ao]()}[Ao](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[il])}}};ol.exports=Ro});var ln=Y((Uv,dl)=>{"use strict";var Bn=require("zlib"),ul=qn(),$m=al(),{kStatusCode:cl}=ht(),Pm=Buffer[Symbol.species],jm=Buffer.from([0,0,255,255]),Zs=Symbol("permessage-deflate"),ft=Symbol("total-length"),un=Symbol("callback"),$t=Symbol("buffers"),cn=Symbol("error"),Fs,$o=class{constructor(e){if(this._options=e||{},this._threshold=this._options.threshold!==void 0?this._options.threshold:1024,this._maxPayload=this._options.maxPayload|0,this._isServer=!!this._options.isServer,this._deflate=null,this._inflate=null,this.params=null,!Fs){let t=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;Fs=new $m(t)}}static get extensionName(){return"permessage-deflate"}offer(){let e={};return this._options.serverNoContextTakeover&&(e.server_no_context_takeover=!0),this._options.clientNoContextTakeover&&(e.client_no_context_takeover=!0),this._options.serverMaxWindowBits&&(e.server_max_window_bits=this._options.serverMaxWindowBits),this._options.clientMaxWindowBits?e.client_max_window_bits=this._options.clientMaxWindowBits:this._options.clientMaxWindowBits==null&&(e.client_max_window_bits=!0),e}accept(e){return e=this.normalizeParams(e),this.params=this._isServer?this.acceptAsServer(e):this.acceptAsClient(e),this.params}cleanup(){if(this._inflate&&(this._inflate.close(),this._inflate=null),this._deflate){let e=this._deflate[un];this._deflate.close(),this._deflate=null,e&&e(new Error("The deflate stream was closed while data was being processed"))}}acceptAsServer(e){let t=this._options,n=e.find(s=>!(t.serverNoContextTakeover===!1&&s.server_no_context_takeover||s.server_max_window_bits&&(t.serverMaxWindowBits===!1||typeof t.serverMaxWindowBits=="number"&&t.serverMaxWindowBits>s.server_max_window_bits)||typeof t.clientMaxWindowBits=="number"&&!s.client_max_window_bits));if(!n)throw new Error("None of the extension offers can be accepted");return t.serverNoContextTakeover&&(n.server_no_context_takeover=!0),t.clientNoContextTakeover&&(n.client_no_context_takeover=!0),typeof t.serverMaxWindowBits=="number"&&(n.server_max_window_bits=t.serverMaxWindowBits),typeof t.clientMaxWindowBits=="number"?n.client_max_window_bits=t.clientMaxWindowBits:(n.client_max_window_bits===!0||t.clientMaxWindowBits===!1)&&delete n.client_max_window_bits,n}acceptAsClient(e){let t=e[0];if(this._options.clientNoContextTakeover===!1&&t.client_no_context_takeover)throw new Error('Unexpected parameter "client_no_context_takeover"');if(!t.client_max_window_bits)typeof this._options.clientMaxWindowBits=="number"&&(t.client_max_window_bits=this._options.clientMaxWindowBits);else if(this._options.clientMaxWindowBits===!1||typeof this._options.clientMaxWindowBits=="number"&&t.client_max_window_bits>this._options.clientMaxWindowBits)throw new Error('Unexpected or invalid parameter "client_max_window_bits"');return t}normalizeParams(e){return e.forEach(t=>{Object.keys(t).forEach(n=>{let s=t[n];if(s.length>1)throw new Error(`Parameter "${n}" must have only a single value`);if(s=s[0],n==="client_max_window_bits"){if(s!==!0){let i=+s;if(!Number.isInteger(i)||i<8||i>15)throw new TypeError(`Invalid value for parameter "${n}": ${s}`);s=i}else if(!this._isServer)throw new TypeError(`Invalid value for parameter "${n}": ${s}`)}else if(n==="server_max_window_bits"){let i=+s;if(!Number.isInteger(i)||i<8||i>15)throw new TypeError(`Invalid value for parameter "${n}": ${s}`);s=i}else if(n==="client_no_context_takeover"||n==="server_no_context_takeover"){if(s!==!0)throw new TypeError(`Invalid value for parameter "${n}": ${s}`)}else throw new Error(`Unknown parameter "${n}"`);t[n]=s})}),e}decompress(e,t,n){Fs.add(s=>{this._decompress(e,t,(i,o)=>{s(),n(i,o)})})}compress(e,t,n){Fs.add(s=>{this._compress(e,t,(i,o)=>{s(),n(i,o)})})}_decompress(e,t,n){let s=this._isServer?"client":"server";if(!this._inflate){let i=`${s}_max_window_bits`,o=typeof this.params[i]!="number"?Bn.Z_DEFAULT_WINDOWBITS:this.params[i];this._inflate=Bn.createInflateRaw({...this._options.zlibInflateOptions,windowBits:o}),this._inflate[Zs]=this,this._inflate[ft]=0,this._inflate[$t]=[],this._inflate.on("error",Nm),this._inflate.on("data",ll)}this._inflate[un]=n,this._inflate.write(e),t&&this._inflate.write(jm),this._inflate.flush(()=>{let i=this._inflate[cn];if(i){this._inflate.close(),this._inflate=null,n(i);return}let o=ul.concat(this._inflate[$t],this._inflate[ft]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[ft]=0,this._inflate[$t]=[],t&&this.params[`${s}_no_context_takeover`]&&this._inflate.reset()),n(null,o)})}_compress(e,t,n){let s=this._isServer?"server":"client";if(!this._deflate){let i=`${s}_max_window_bits`,o=typeof this.params[i]!="number"?Bn.Z_DEFAULT_WINDOWBITS:this.params[i];this._deflate=Bn.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:o}),this._deflate[ft]=0,this._deflate[$t]=[],this._deflate.on("data",Om)}this._deflate[un]=n,this._deflate.write(e),this._deflate.flush(Bn.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let i=ul.concat(this._deflate[$t],this._deflate[ft]);t&&(i=new Pm(i.buffer,i.byteOffset,i.length-4)),this._deflate[un]=null,this._deflate[ft]=0,this._deflate[$t]=[],t&&this.params[`${s}_no_context_takeover`]&&this._deflate.reset(),n(null,i)})}};dl.exports=$o;function Om(r){this[$t].push(r),this[ft]+=r.length}function ll(r){if(this[ft]+=r.length,this[Zs]._maxPayload<1||this[ft]<=this[Zs]._maxPayload){this[$t].push(r);return}this[cn]=new RangeError("Max payload size exceeded"),this[cn].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[cn][cl]=1009,this.removeListener("data",ll),this.reset()}function Nm(r){if(this[Zs]._inflate=null,this[cn]){this[un](this[cn]);return}r[cl]=1007,this[un](r)}});var dn=Y((qv,Ks)=>{"use strict";var{isUtf8:hl}=require("buffer"),{hasBlob:Mm}=ht(),Dm=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,1,0,0,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,0];function Lm(r){return r>=1e3&&r<=1014&&r!==1004&&r!==1005&&r!==1006||r>=3e3&&r<=4999}function Po(r){let e=r.length,t=0;for(;t<e;)if((r[t]&128)===0)t++;else if((r[t]&224)===192){if(t+1===e||(r[t+1]&192)!==128||(r[t]&254)===192)return!1;t+=2}else if((r[t]&240)===224){if(t+2>=e||(r[t+1]&192)!==128||(r[t+2]&192)!==128||r[t]===224&&(r[t+1]&224)===128||r[t]===237&&(r[t+1]&224)===160)return!1;t+=3}else if((r[t]&248)===240){if(t+3>=e||(r[t+1]&192)!==128||(r[t+2]&192)!==128||(r[t+3]&192)!==128||r[t]===240&&(r[t+1]&240)===128||r[t]===244&&r[t+1]>143||r[t]>244)return!1;t+=4}else return!1;return!0}function zm(r){return Mm&&typeof r=="object"&&typeof r.arrayBuffer=="function"&&typeof r.type=="string"&&typeof r.stream=="function"&&(r[Symbol.toStringTag]==="Blob"||r[Symbol.toStringTag]==="File")}Ks.exports={isBlob:zm,isValidStatusCode:Lm,isValidUTF8:Po,tokenChars:Dm};if(hl)Ks.exports.isValidUTF8=function(r){return r.length<24?Po(r):hl(r)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let r=require("utf-8-validate");Ks.exports.isValidUTF8=function(e){return e.length<32?Po(e):r(e)}}catch{}});var Do=Y((Bv,vl)=>{"use strict";var{Writable:Um}=require("stream"),fl=ln(),{BINARY_TYPES:qm,EMPTY_BUFFER:pl,kStatusCode:Bm,kWebSocket:Fm}=ht(),{concat:jo,toArrayBuffer:Zm,unmask:Km}=qn(),{isValidStatusCode:Vm,isValidUTF8:ml}=dn(),Vs=Buffer[Symbol.species],Ne=0,gl=1,yl=2,_l=3,Oo=4,No=5,Hs=6,Mo=class extends Um{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||qm[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxBufferedChunks=e.maxBufferedChunks|0,this._maxFragments=e.maxFragments|0,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[Fm]=void 0,this._bufferedBytes=0,this._buffers=[],this._compressed=!1,this._payloadLength=0,this._mask=void 0,this._fragmented=0,this._masked=!1,this._fin=!1,this._opcode=0,this._totalPayloadLength=0,this._messageLength=0,this._numFragments=0,this._fragments=[],this._errored=!1,this._loop=!1,this._state=Ne}_write(e,t,n){if(this._opcode===8&&this._state==Ne)return n();if(this._maxBufferedChunks>0&&this._buffers.length>=this._maxBufferedChunks){n(this.createError(RangeError,"Too many buffered chunks",!1,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS"));return}this._bufferedBytes+=e.length,this._buffers.push(e),this.startLoop(n)}consume(e){if(this._bufferedBytes-=e,e===this._buffers[0].length)return this._buffers.shift();if(e<this._buffers[0].length){let n=this._buffers[0];return this._buffers[0]=new Vs(n.buffer,n.byteOffset+e,n.length-e),new Vs(n.buffer,n.byteOffset,e)}let t=Buffer.allocUnsafe(e);do{let n=this._buffers[0],s=t.length-e;e>=n.length?t.set(this._buffers.shift(),s):(t.set(new Uint8Array(n.buffer,n.byteOffset,e),s),this._buffers[0]=new Vs(n.buffer,n.byteOffset+e,n.length-e)),e-=n.length}while(e>0);return t}startLoop(e){this._loop=!0;do switch(this._state){case Ne:this.getInfo(e);break;case gl:this.getPayloadLength16(e);break;case yl:this.getPayloadLength64(e);break;case _l:this.getMask();break;case Oo:this.getData(e);break;case No:case Hs:this._loop=!1;return}while(this._loop);this._errored||e()}getInfo(e){if(this._bufferedBytes<2){this._loop=!1;return}let t=this.consume(2);if((t[0]&48)!==0){let s=this.createError(RangeError,"RSV2 and RSV3 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_2_3");e(s);return}let n=(t[0]&64)===64;if(n&&!this._extensions[fl.extensionName]){let s=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(s);return}if(this._fin=(t[0]&128)===128,this._opcode=t[0]&15,this._payloadLength=t[1]&127,this._opcode===0){if(n){let s=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(s);return}if(!this._fragmented){let s=this.createError(RangeError,"invalid opcode 0",!0,1002,"WS_ERR_INVALID_OPCODE");e(s);return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){let s=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(s);return}this._compressed=n}else if(this._opcode>7&&this._opcode<11){if(!this._fin){let s=this.createError(RangeError,"FIN must be set",!0,1002,"WS_ERR_EXPECTED_FIN");e(s);return}if(n){let s=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(s);return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){let s=this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH");e(s);return}}else{let s=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(s);return}if(!this._fin&&!this._fragmented&&(this._fragmented=this._opcode),this._masked=(t[1]&128)===128,this._isServer){if(!this._masked){let s=this.createError(RangeError,"MASK must be set",!0,1002,"WS_ERR_EXPECTED_MASK");e(s);return}}else if(this._masked){let s=this.createError(RangeError,"MASK must be clear",!0,1002,"WS_ERR_UNEXPECTED_MASK");e(s);return}this._payloadLength===126?this._state=gl:this._payloadLength===127?this._state=yl:this.haveLength(e)}getPayloadLength16(e){if(this._bufferedBytes<2){this._loop=!1;return}this._payloadLength=this.consume(2).readUInt16BE(0),this.haveLength(e)}getPayloadLength64(e){if(this._bufferedBytes<8){this._loop=!1;return}let t=this.consume(8),n=t.readUInt32BE(0);if(n>Math.pow(2,21)-1){let s=this.createError(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",!1,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH");e(s);return}this._payloadLength=n*Math.pow(2,32)+t.readUInt32BE(4),this.haveLength(e)}haveLength(e){if(this._payloadLength&&this._opcode<8&&(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0)){let t=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");e(t);return}this._masked?this._state=_l:this._state=Oo}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=Oo}getData(e){let t=pl;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength){this._loop=!1;return}t=this.consume(this._payloadLength),this._masked&&(this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3])!==0&&Km(t,this._mask)}if(this._opcode>7){this.controlMessage(t,e);return}if(this._maxFragments>0&&++this._numFragments>this._maxFragments){let n=this.createError(RangeError,"Too many message fragments",!1,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS");e(n);return}if(this._compressed){this._state=No,this.decompress(t,e);return}t.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(t)),this.dataMessage(e)}decompress(e,t){this._extensions[fl.extensionName].decompress(e,this._fin,(s,i)=>{if(s)return t(s);if(i.length){if(this._messageLength+=i.length,this._messageLength>this._maxPayload&&this._maxPayload>0){let o=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");t(o);return}this._fragments.push(i)}this.dataMessage(t),this._state===Ne&&this.startLoop(t)})}dataMessage(e){if(!this._fin){this._state=Ne;return}let t=this._messageLength,n=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._numFragments=0,this._fragments=[],this._opcode===2){let s;this._binaryType==="nodebuffer"?s=jo(n,t):this._binaryType==="arraybuffer"?s=Zm(jo(n,t)):this._binaryType==="blob"?s=new Blob(n):s=n,this._allowSynchronousEvents?(this.emit("message",s,!0),this._state=Ne):(this._state=Hs,setImmediate(()=>{this.emit("message",s,!0),this._state=Ne,this.startLoop(e)}))}else{let s=jo(n,t);if(!this._skipUTF8Validation&&!ml(s)){let i=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(i);return}this._state===No||this._allowSynchronousEvents?(this.emit("message",s,!1),this._state=Ne):(this._state=Hs,setImmediate(()=>{this.emit("message",s,!1),this._state=Ne,this.startLoop(e)}))}}controlMessage(e,t){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit("conclude",1005,pl),this.end();else{let n=e.readUInt16BE(0);if(!Vm(n)){let i=this.createError(RangeError,`invalid status code ${n}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");t(i);return}let s=new Vs(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!ml(s)){let i=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");t(i);return}this._loop=!1,this.emit("conclude",n,s),this.end()}this._state=Ne;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",e),this._state=Ne):(this._state=Hs,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=Ne,this.startLoop(t)}))}createError(e,t,n,s,i){this._loop=!1,this._errored=!0;let o=new e(n?`Invalid WebSocket frame: ${t}`:t);return Error.captureStackTrace(o,this.createError),o.code=i,o[Bm]=s,o}};vl.exports=Mo});var Uo=Y((Zv,kl)=>{"use strict";var{Duplex:Fv}=require("stream"),{randomFillSync:Hm}=require("crypto"),{types:{isUint8Array:Gm}}=require("util"),bl=ln(),{EMPTY_BUFFER:Wm,kWebSocket:Jm,NOOP:Ym}=ht(),{isBlob:hn,isValidStatusCode:Xm}=dn(),{mask:wl,toBuffer:Tr}=qn(),Me=Symbol("kByteLength"),Qm=Buffer.alloc(4),Gs=8*1024,xr,fn=Gs,Be=0,eg=1,tg=2,Lo=class r{constructor(e,t,n){this._extensions=t||{},n&&(this._generateMask=n,this._maskBuffer=Buffer.alloc(4)),this._socket=e,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=Be,this.onerror=Ym,this[Jm]=void 0}static frame(e,t){let n,s=!1,i=2,o=!1;t.mask&&(n=t.maskBuffer||Qm,t.generateMask?t.generateMask(n):(fn===Gs&&(xr===void 0&&(xr=Buffer.alloc(Gs)),Hm(xr,0,Gs),fn=0),n[0]=xr[fn++],n[1]=xr[fn++],n[2]=xr[fn++],n[3]=xr[fn++]),o=(n[0]|n[1]|n[2]|n[3])===0,i=6);let a;typeof e=="string"?(!t.mask||o)&&t[Me]!==void 0?a=t[Me]:(e=Buffer.from(e),a=e.length):(a=e.length,s=t.mask&&t.readOnly&&!o);let c=a;a>=65536?(i+=8,c=127):a>125&&(i+=2,c=126);let l=Buffer.allocUnsafe(s?a+i:i);return l[0]=t.fin?t.opcode|128:t.opcode,t.rsv1&&(l[0]|=64),l[1]=c,c===126?l.writeUInt16BE(a,2):c===127&&(l[2]=l[3]=0,l.writeUIntBE(a,4,6)),t.mask?(l[1]|=128,l[i-4]=n[0],l[i-3]=n[1],l[i-2]=n[2],l[i-1]=n[3],o?[l,e]:s?(wl(e,n,l,i,a),[l]):(wl(e,n,e,0,a),[l,e])):[l,e]}close(e,t,n,s){let i;if(e===void 0)i=Wm;else{if(typeof e!="number"||!Xm(e))throw new TypeError("First argument must be a valid error code number");if(t===void 0||!t.length)i=Buffer.allocUnsafe(2),i.writeUInt16BE(e,0);else{let a=Buffer.byteLength(t);if(a>123)throw new RangeError("The message must not be greater than 123 bytes");if(i=Buffer.allocUnsafe(2+a),i.writeUInt16BE(e,0),typeof t=="string")i.write(t,2);else if(Gm(t))i.set(t,2);else throw new TypeError("Second argument must be a string or a Uint8Array")}}let o={[Me]:i.length,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==Be?this.enqueue([this.dispatch,i,!1,o,s]):this.sendFrame(r.frame(i,o),s)}ping(e,t,n){let s,i;if(typeof e=="string"?(s=Buffer.byteLength(e),i=!1):hn(e)?(s=e.size,i=!1):(e=Tr(e),s=e.length,i=Tr.readOnly),s>125)throw new RangeError("The data size must not be greater than 125 bytes");let o={[Me]:s,fin:!0,generateMask:this._generateMask,mask:t,maskBuffer:this._maskBuffer,opcode:9,readOnly:i,rsv1:!1};hn(e)?this._state!==Be?this.enqueue([this.getBlobData,e,!1,o,n]):this.getBlobData(e,!1,o,n):this._state!==Be?this.enqueue([this.dispatch,e,!1,o,n]):this.sendFrame(r.frame(e,o),n)}pong(e,t,n){let s,i;if(typeof e=="string"?(s=Buffer.byteLength(e),i=!1):hn(e)?(s=e.size,i=!1):(e=Tr(e),s=e.length,i=Tr.readOnly),s>125)throw new RangeError("The data size must not be greater than 125 bytes");let o={[Me]:s,fin:!0,generateMask:this._generateMask,mask:t,maskBuffer:this._maskBuffer,opcode:10,readOnly:i,rsv1:!1};hn(e)?this._state!==Be?this.enqueue([this.getBlobData,e,!1,o,n]):this.getBlobData(e,!1,o,n):this._state!==Be?this.enqueue([this.dispatch,e,!1,o,n]):this.sendFrame(r.frame(e,o),n)}send(e,t,n){let s=this._extensions[bl.extensionName],i=t.binary?2:1,o=t.compress,a,c;typeof e=="string"?(a=Buffer.byteLength(e),c=!1):hn(e)?(a=e.size,c=!1):(e=Tr(e),a=e.length,c=Tr.readOnly),this._firstFragment?(this._firstFragment=!1,o&&s&&s.params[s._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(o=a>=s._threshold),this._compress=o):(o=!1,i=0),t.fin&&(this._firstFragment=!0);let l={[Me]:a,fin:t.fin,generateMask:this._generateMask,mask:t.mask,maskBuffer:this._maskBuffer,opcode:i,readOnly:c,rsv1:o};hn(e)?this._state!==Be?this.enqueue([this.getBlobData,e,this._compress,l,n]):this.getBlobData(e,this._compress,l,n):this._state!==Be?this.enqueue([this.dispatch,e,this._compress,l,n]):this.dispatch(e,this._compress,l,n)}getBlobData(e,t,n,s){this._bufferedBytes+=n[Me],this._state=tg,e.arrayBuffer().then(i=>{if(this._socket.destroyed){let a=new Error("The socket was closed while the blob was being read");process.nextTick(zo,this,a,s);return}this._bufferedBytes-=n[Me];let o=Tr(i);t?this.dispatch(o,t,n,s):(this._state=Be,this.sendFrame(r.frame(o,n),s),this.dequeue())}).catch(i=>{process.nextTick(rg,this,i,s)})}dispatch(e,t,n,s){if(!t){this.sendFrame(r.frame(e,n),s);return}let i=this._extensions[bl.extensionName];this._bufferedBytes+=n[Me],this._state=eg,i.compress(e,n.fin,(o,a)=>{if(this._socket.destroyed){let c=new Error("The socket was closed while data was being compressed");zo(this,c,s);return}this._bufferedBytes-=n[Me],this._state=Be,n.readOnly=!1,this.sendFrame(r.frame(a,n),s),this.dequeue()})}dequeue(){for(;this._state===Be&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][Me],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][Me],this._queue.push(e)}sendFrame(e,t){e.length===2?(this._socket.cork(),this._socket.write(e[0]),this._socket.write(e[1],t),this._socket.uncork()):this._socket.write(e[0],t)}};kl.exports=Lo;function zo(r,e,t){typeof t=="function"&&t(e);for(let n=0;n<r._queue.length;n++){let s=r._queue[n],i=s[s.length-1];typeof i=="function"&&i(e)}}function rg(r,e,t){zo(r,e,t),r.onerror(e)}});var $l=Y((Kv,Rl)=>{"use strict";var{kForOnEventAttribute:Fn,kListener:qo}=ht(),Sl=Symbol("kCode"),Tl=Symbol("kData"),xl=Symbol("kError"),Cl=Symbol("kMessage"),El=Symbol("kReason"),pn=Symbol("kTarget"),Il=Symbol("kType"),Al=Symbol("kWasClean"),pt=class{constructor(e){this[pn]=null,this[Il]=e}get target(){return this[pn]}get type(){return this[Il]}};Object.defineProperty(pt.prototype,"target",{enumerable:!0});Object.defineProperty(pt.prototype,"type",{enumerable:!0});var Cr=class extends pt{constructor(e,t={}){super(e),this[Sl]=t.code===void 0?0:t.code,this[El]=t.reason===void 0?"":t.reason,this[Al]=t.wasClean===void 0?!1:t.wasClean}get code(){return this[Sl]}get reason(){return this[El]}get wasClean(){return this[Al]}};Object.defineProperty(Cr.prototype,"code",{enumerable:!0});Object.defineProperty(Cr.prototype,"reason",{enumerable:!0});Object.defineProperty(Cr.prototype,"wasClean",{enumerable:!0});var mn=class extends pt{constructor(e,t={}){super(e),this[xl]=t.error===void 0?null:t.error,this[Cl]=t.message===void 0?"":t.message}get error(){return this[xl]}get message(){return this[Cl]}};Object.defineProperty(mn.prototype,"error",{enumerable:!0});Object.defineProperty(mn.prototype,"message",{enumerable:!0});var Zn=class extends pt{constructor(e,t={}){super(e),this[Tl]=t.data===void 0?null:t.data}get data(){return this[Tl]}};Object.defineProperty(Zn.prototype,"data",{enumerable:!0});var ng={addEventListener(r,e,t={}){for(let s of this.listeners(r))if(!t[Fn]&&s[qo]===e&&!s[Fn])return;let n;if(r==="message")n=function(i,o){let a=new Zn("message",{data:o?i:i.toString()});a[pn]=this,Ws(e,this,a)};else if(r==="close")n=function(i,o){let a=new Cr("close",{code:i,reason:o.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});a[pn]=this,Ws(e,this,a)};else if(r==="error")n=function(i){let o=new mn("error",{error:i,message:i.message});o[pn]=this,Ws(e,this,o)};else if(r==="open")n=function(){let i=new pt("open");i[pn]=this,Ws(e,this,i)};else return;n[Fn]=!!t[Fn],n[qo]=e,t.once?this.once(r,n):this.on(r,n)},removeEventListener(r,e){for(let t of this.listeners(r))if(t[qo]===e&&!t[Fn]){this.removeListener(r,t);break}}};Rl.exports={CloseEvent:Cr,ErrorEvent:mn,Event:pt,EventTarget:ng,MessageEvent:Zn};function Ws(r,e,t){typeof r=="object"&&r.handleEvent?r.handleEvent.call(r,t):r.call(e,t)}});var Js=Y((Vv,Pl)=>{"use strict";var{tokenChars:Kn}=dn();function Ye(r,e,t){r[e]===void 0?r[e]=[t]:r[e].push(t)}function sg(r){let e=Object.create(null),t=Object.create(null),n=!1,s=!1,i=!1,o,a,c=-1,l=-1,d=-1,p=0;for(;p<r.length;p++)if(l=r.charCodeAt(p),o===void 0)if(d===-1&&Kn[l]===1)c===-1&&(c=p);else if(p!==0&&(l===32||l===9))d===-1&&c!==-1&&(d=p);else if(l===59||l===44){if(c===-1)throw new SyntaxError(`Unexpected character at index ${p}`);d===-1&&(d=p);let S=r.slice(c,d);l===44?(Ye(e,S,t),t=Object.create(null)):o=S,c=d=-1}else throw new SyntaxError(`Unexpected character at index ${p}`);else if(a===void 0)if(d===-1&&Kn[l]===1)c===-1&&(c=p);else if(l===32||l===9)d===-1&&c!==-1&&(d=p);else if(l===59||l===44){if(c===-1)throw new SyntaxError(`Unexpected character at index ${p}`);d===-1&&(d=p),Ye(t,r.slice(c,d),!0),l===44&&(Ye(e,o,t),t=Object.create(null),o=void 0),c=d=-1}else if(l===61&&c!==-1&&d===-1)a=r.slice(c,p),c=d=-1;else throw new SyntaxError(`Unexpected character at index ${p}`);else if(s){if(Kn[l]!==1)throw new SyntaxError(`Unexpected character at index ${p}`);c===-1?c=p:n||(n=!0),s=!1}else if(i)if(Kn[l]===1)c===-1&&(c=p);else if(l===34&&c!==-1)i=!1,d=p;else if(l===92)s=!0;else throw new SyntaxError(`Unexpected character at index ${p}`);else if(l===34&&r.charCodeAt(p-1)===61)i=!0;else if(d===-1&&Kn[l]===1)c===-1&&(c=p);else if(c!==-1&&(l===32||l===9))d===-1&&(d=p);else if(l===59||l===44){if(c===-1)throw new SyntaxError(`Unexpected character at index ${p}`);d===-1&&(d=p);let S=r.slice(c,d);n&&(S=S.replace(/\\/g,""),n=!1),Ye(t,a,S),l===44&&(Ye(e,o,t),t=Object.create(null),o=void 0),a=void 0,c=d=-1}else throw new SyntaxError(`Unexpected character at index ${p}`);if(c===-1||i||l===32||l===9)throw new SyntaxError("Unexpected end of input");d===-1&&(d=p);let v=r.slice(c,d);return o===void 0?Ye(e,v,t):(a===void 0?Ye(t,v,!0):n?Ye(t,a,v.replace(/\\/g,"")):Ye(t,a,v),Ye(e,o,t)),e}function ig(r){return Object.keys(r).map(e=>{let t=r[e];return Array.isArray(t)||(t=[t]),t.map(n=>[e].concat(Object.keys(n).map(s=>{let i=n[s];return Array.isArray(i)||(i=[i]),i.map(o=>o===!0?s:`${s}=${o}`).join("; ")})).join("; ")).join(", ")}).join(", ")}Pl.exports={format:ig,parse:sg}});var ei=Y((Wv,Zl)=>{"use strict";var og=require("events"),ag=require("https"),ug=require("http"),Nl=require("net"),cg=require("tls"),{randomBytes:lg,createHash:dg}=require("crypto"),{Duplex:Hv,Readable:Gv}=require("stream"),{URL:Bo}=require("url"),Pt=ln(),hg=Do(),fg=Uo(),{isBlob:pg}=dn(),{BINARY_TYPES:jl,CLOSE_TIMEOUT:mg,EMPTY_BUFFER:Ys,GUID:gg,kForOnEventAttribute:Fo,kListener:yg,kStatusCode:_g,kWebSocket:oe,NOOP:Ml}=ht(),{EventTarget:{addEventListener:vg,removeEventListener:bg}}=$l(),{format:wg,parse:kg}=Js(),{toBuffer:Sg}=qn(),Dl=Symbol("kAborted"),Zo=[8,13],mt=["CONNECTING","OPEN","CLOSING","CLOSED"],Tg=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,ne=class r extends og{constructor(e,t,n){super(),this._binaryType=jl[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=Ys,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol="",this._readyState=r.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,e!==null?(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,t===void 0?t=[]:Array.isArray(t)||(typeof t=="object"&&t!==null?(n=t,t=[]):t=[t]),Ll(this,e,t,n)):(this._autoPong=n.autoPong,this._closeTimeout=n.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){jl.includes(e)&&(this._binaryType=e,this._receiver&&(this._receiver._binaryType=e))}get bufferedAmount(){return this._socket?this._socket._writableState.length+this._sender._bufferedBytes:this._bufferedAmount}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(e,t,n){let s=new hg({allowSynchronousEvents:n.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxBufferedChunks:n.maxBufferedChunks,maxFragments:n.maxFragments,maxPayload:n.maxPayload,skipUTF8Validation:n.skipUTF8Validation}),i=new fg(e,this._extensions,n.generateMask);this._receiver=s,this._sender=i,this._socket=e,s[oe]=this,i[oe]=this,e[oe]=this,s.on("conclude",Eg),s.on("drain",Ig),s.on("error",Ag),s.on("message",Rg),s.on("ping",$g),s.on("pong",Pg),i.onerror=jg,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),t.length>0&&e.unshift(t),e.on("close",ql),e.on("data",Qs),e.on("end",Bl),e.on("error",Fl),this._readyState=r.OPEN,this.emit("open")}emitClose(){if(!this._socket){this._readyState=r.CLOSED,this.emit("close",this._closeCode,this._closeMessage);return}this._extensions[Pt.extensionName]&&this._extensions[Pt.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=r.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(e,t){if(this.readyState!==r.CLOSED){if(this.readyState===r.CONNECTING){xe(this,this._req,"WebSocket was closed before the connection was established");return}if(this.readyState===r.CLOSING){this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();return}this._readyState=r.CLOSING,this._sender.close(e,t,!this._isServer,n=>{n||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),Ul(this)}}pause(){this.readyState===r.CONNECTING||this.readyState===r.CLOSED||(this._paused=!0,this._socket.pause())}ping(e,t,n){if(this.readyState===r.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(n=e,e=t=void 0):typeof t=="function"&&(n=t,t=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==r.OPEN){Ko(this,e,n);return}t===void 0&&(t=!this._isServer),this._sender.ping(e||Ys,t,n)}pong(e,t,n){if(this.readyState===r.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(n=e,e=t=void 0):typeof t=="function"&&(n=t,t=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==r.OPEN){Ko(this,e,n);return}t===void 0&&(t=!this._isServer),this._sender.pong(e||Ys,t,n)}resume(){this.readyState===r.CONNECTING||this.readyState===r.CLOSED||(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(e,t,n){if(this.readyState===r.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof t=="function"&&(n=t,t={}),typeof e=="number"&&(e=e.toString()),this.readyState!==r.OPEN){Ko(this,e,n);return}let s={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...t};this._extensions[Pt.extensionName]||(s.compress=!1),this._sender.send(e||Ys,s,n)}terminate(){if(this.readyState!==r.CLOSED){if(this.readyState===r.CONNECTING){xe(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=r.CLOSING,this._socket.destroy())}}};Object.defineProperty(ne,"CONNECTING",{enumerable:!0,value:mt.indexOf("CONNECTING")});Object.defineProperty(ne.prototype,"CONNECTING",{enumerable:!0,value:mt.indexOf("CONNECTING")});Object.defineProperty(ne,"OPEN",{enumerable:!0,value:mt.indexOf("OPEN")});Object.defineProperty(ne.prototype,"OPEN",{enumerable:!0,value:mt.indexOf("OPEN")});Object.defineProperty(ne,"CLOSING",{enumerable:!0,value:mt.indexOf("CLOSING")});Object.defineProperty(ne.prototype,"CLOSING",{enumerable:!0,value:mt.indexOf("CLOSING")});Object.defineProperty(ne,"CLOSED",{enumerable:!0,value:mt.indexOf("CLOSED")});Object.defineProperty(ne.prototype,"CLOSED",{enumerable:!0,value:mt.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(r=>{Object.defineProperty(ne.prototype,r,{enumerable:!0})});["open","error","close","message"].forEach(r=>{Object.defineProperty(ne.prototype,`on${r}`,{enumerable:!0,get(){for(let e of this.listeners(r))if(e[Fo])return e[yg];return null},set(e){for(let t of this.listeners(r))if(t[Fo]){this.removeListener(r,t);break}typeof e=="function"&&this.addEventListener(r,e,{[Fo]:!0})}})});ne.prototype.addEventListener=vg;ne.prototype.removeEventListener=bg;Zl.exports=ne;function Ll(r,e,t,n){let s={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:mg,protocolVersion:Zo[1],maxBufferedChunks:262144,maxFragments:16384,maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...n,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:"GET",host:void 0,path:void 0,port:void 0};if(r._autoPong=s.autoPong,r._closeTimeout=s.closeTimeout,!Zo.includes(s.protocolVersion))throw new RangeError(`Unsupported protocol version: ${s.protocolVersion} (supported versions: ${Zo.join(", ")})`);let i;if(e instanceof Bo)i=e;else try{i=new Bo(e)}catch{throw new SyntaxError(`Invalid URL: ${e}`)}i.protocol==="http:"?i.protocol="ws:":i.protocol==="https:"&&(i.protocol="wss:"),r._url=i.href;let o=i.protocol==="wss:",a=i.protocol==="ws+unix:",c;if(i.protocol!=="ws:"&&!o&&!a?c=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:a&&!i.pathname?c="The URL's pathname is empty":i.hash&&(c="The URL contains a fragment identifier"),c){let w=new SyntaxError(c);if(r._redirects===0)throw w;Xs(r,w);return}let l=o?443:80,d=lg(16).toString("base64"),p=o?ag.request:ug.request,v=new Set,S;if(s.createConnection=s.createConnection||(o?Cg:xg),s.defaultPort=s.defaultPort||l,s.port=i.port||l,s.host=i.hostname.startsWith("[")?i.hostname.slice(1,-1):i.hostname,s.headers={...s.headers,"Sec-WebSocket-Version":s.protocolVersion,"Sec-WebSocket-Key":d,Connection:"Upgrade",Upgrade:"websocket"},s.path=i.pathname+i.search,s.timeout=s.handshakeTimeout,s.perMessageDeflate&&(S=new Pt({...s.perMessageDeflate,isServer:!1,maxPayload:s.maxPayload}),s.headers["Sec-WebSocket-Extensions"]=wg({[Pt.extensionName]:S.offer()})),t.length){for(let w of t){if(typeof w!="string"||!Tg.test(w)||v.has(w))throw new SyntaxError("An invalid or duplicated subprotocol was specified");v.add(w)}s.headers["Sec-WebSocket-Protocol"]=t.join(",")}if(s.origin&&(s.protocolVersion<13?s.headers["Sec-WebSocket-Origin"]=s.origin:s.headers.Origin=s.origin),(i.username||i.password)&&(s.auth=`${i.username}:${i.password}`),a){let w=s.path.split(":");s.socketPath=w[0],s.path=w[1]}let x;if(s.followRedirects){if(r._redirects===0){r._originalIpc=a,r._originalSecure=o,r._originalHostOrSocketPath=a?s.socketPath:i.host;let w=n&&n.headers;if(n={...n,headers:{}},w)for(let[j,U]of Object.entries(w))n.headers[j.toLowerCase()]=U}else if(r.listenerCount("redirect")===0){let w=a?r._originalIpc?s.socketPath===r._originalHostOrSocketPath:!1:r._originalIpc?!1:i.host===r._originalHostOrSocketPath;(!w||r._originalSecure&&!o)&&(delete s.headers.authorization,delete s.headers.cookie,w||delete s.headers.host,s.auth=void 0)}s.auth&&!n.headers.authorization&&(n.headers.authorization="Basic "+Buffer.from(s.auth).toString("base64")),x=r._req=p(s),r._redirects&&r.emit("redirect",r.url,x)}else x=r._req=p(s);s.timeout&&x.on("timeout",()=>{xe(r,x,"Opening handshake has timed out")}),x.on("error",w=>{x===null||x[Dl]||(x=r._req=null,Xs(r,w))}),x.on("response",w=>{let j=w.headers.location,U=w.statusCode;if(j&&s.followRedirects&&U>=300&&U<400){if(++r._redirects>s.maxRedirects){xe(r,x,"Maximum redirects exceeded");return}x.abort();let f;try{f=new Bo(j,e)}catch{let b=new SyntaxError(`Invalid URL: ${j}`);Xs(r,b);return}Ll(r,f,t,n)}else r.emit("unexpected-response",x,w)||xe(r,x,`Unexpected server response: ${w.statusCode}`)}),x.on("upgrade",(w,j,U)=>{if(r.emit("upgrade",w),r.readyState!==ne.CONNECTING)return;x=r._req=null;let f=w.headers.upgrade;if(f===void 0||f.toLowerCase()!=="websocket"){xe(r,j,"Invalid Upgrade header");return}let g=dg("sha1").update(d+gg).digest("base64");if(w.headers["sec-websocket-accept"]!==g){xe(r,j,"Invalid Sec-WebSocket-Accept header");return}let b=w.headers["sec-websocket-protocol"],I;if(b!==void 0?v.size?v.has(b)||(I="Server sent an invalid subprotocol"):I="Server sent a subprotocol but none was requested":v.size&&(I="Server sent no subprotocol"),I){xe(r,j,I);return}b&&(r._protocol=b);let N=w.headers["sec-websocket-extensions"];if(N!==void 0){if(!S){xe(r,j,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let V;try{V=kg(N)}catch{xe(r,j,"Invalid Sec-WebSocket-Extensions header");return}let W=Object.keys(V);if(W.length!==1||W[0]!==Pt.extensionName){xe(r,j,"Server indicated an extension that was not requested");return}try{S.accept(V[Pt.extensionName])}catch{xe(r,j,"Invalid Sec-WebSocket-Extensions header");return}r._extensions[Pt.extensionName]=S}r.setSocket(j,U,{allowSynchronousEvents:s.allowSynchronousEvents,generateMask:s.generateMask,maxBufferedChunks:s.maxBufferedChunks,maxFragments:s.maxFragments,maxPayload:s.maxPayload,skipUTF8Validation:s.skipUTF8Validation})}),s.finishRequest?s.finishRequest(x,r):x.end()}function Xs(r,e){r._readyState=ne.CLOSING,r._errorEmitted=!0,r.emit("error",e),r.emitClose()}function xg(r){return r.path=r.socketPath,Nl.connect(r)}function Cg(r){return r.path=void 0,!r.servername&&r.servername!==""&&(r.servername=Nl.isIP(r.host)?"":r.host),cg.connect(r)}function xe(r,e,t){r._readyState=ne.CLOSING;let n=new Error(t);Error.captureStackTrace(n,xe),e.setHeader?(e[Dl]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(Xs,r,n)):(e.destroy(n),e.once("error",r.emit.bind(r,"error")),e.once("close",r.emitClose.bind(r)))}function Ko(r,e,t){if(e){let n=pg(e)?e.size:Sg(e).length;r._socket?r._sender._bufferedBytes+=n:r._bufferedAmount+=n}if(t){let n=new Error(`WebSocket is not open: readyState ${r.readyState} (${mt[r.readyState]})`);process.nextTick(t,n)}}function Eg(r,e){let t=this[oe];t._closeFrameReceived=!0,t._closeMessage=e,t._closeCode=r,t._socket[oe]!==void 0&&(t._socket.removeListener("data",Qs),process.nextTick(zl,t._socket),r===1005?t.close():t.close(r,e))}function Ig(){let r=this[oe];r.isPaused||r._socket.resume()}function Ag(r){let e=this[oe];e._socket[oe]!==void 0&&(e._socket.removeListener("data",Qs),process.nextTick(zl,e._socket),e.close(r[_g])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",r))}function Ol(){this[oe].emitClose()}function Rg(r,e){this[oe].emit("message",r,e)}function $g(r){let e=this[oe];e._autoPong&&e.pong(r,!this._isServer,Ml),e.emit("ping",r)}function Pg(r){this[oe].emit("pong",r)}function zl(r){r.resume()}function jg(r){let e=this[oe];e.readyState!==ne.CLOSED&&(e.readyState===ne.OPEN&&(e._readyState=ne.CLOSING,Ul(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",r)))}function Ul(r){r._closeTimer=setTimeout(r._socket.destroy.bind(r._socket),r._closeTimeout)}function ql(){let r=this[oe];if(this.removeListener("close",ql),this.removeListener("data",Qs),this.removeListener("end",Bl),r._readyState=ne.CLOSING,!this._readableState.endEmitted&&!r._closeFrameReceived&&!r._receiver._writableState.errorEmitted&&this._readableState.length!==0){let e=this.read(this._readableState.length);r._receiver.write(e)}r._receiver.end(),this[oe]=void 0,clearTimeout(r._closeTimer),r._receiver._writableState.finished||r._receiver._writableState.errorEmitted?r.emitClose():(r._receiver.on("error",Ol),r._receiver.on("finish",Ol))}function Qs(r){this[oe]._receiver.write(r)||this.pause()}function Bl(){let r=this[oe];r._readyState=ne.CLOSING,r._receiver.end(),this.end()}function Fl(){let r=this[oe];this.removeListener("error",Fl),this.on("error",Ml),r&&(r._readyState=ne.CLOSING,this.destroy())}});var Gl=Y((Yv,Hl)=>{"use strict";var Jv=ei(),{Duplex:Og}=require("stream");function Kl(r){r.emit("close")}function Ng(){!this.destroyed&&this._writableState.finished&&this.destroy()}function Vl(r){this.removeListener("error",Vl),this.destroy(),this.listenerCount("error")===0&&this.emit("error",r)}function Mg(r,e){let t=!0,n=new Og({...e,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return r.on("message",function(i,o){let a=!o&&n._readableState.objectMode?i.toString():i;n.push(a)||r.pause()}),r.once("error",function(i){n.destroyed||(t=!1,n.destroy(i))}),r.once("close",function(){n.destroyed||n.push(null)}),n._destroy=function(s,i){if(r.readyState===r.CLOSED){i(s),process.nextTick(Kl,n);return}let o=!1;r.once("error",function(c){o=!0,i(c)}),r.once("close",function(){o||i(s),process.nextTick(Kl,n)}),t&&r.terminate()},n._final=function(s){if(r.readyState===r.CONNECTING){r.once("open",function(){n._final(s)});return}r._socket!==null&&(r._socket._writableState.finished?(s(),n._readableState.endEmitted&&n.destroy()):(r._socket.once("finish",function(){s()}),r.close()))},n._read=function(){r.isPaused&&r.resume()},n._write=function(s,i,o){if(r.readyState===r.CONNECTING){r.once("open",function(){n._write(s,i,o)});return}r.send(s,o)},n.on("end",Ng),n.on("error",Vl),n}Hl.exports=Mg});var Vo=Y((Xv,Wl)=>{"use strict";var{tokenChars:Dg}=dn();function Lg(r){let e=new Set,t=-1,n=-1,s=0;for(s;s<r.length;s++){let o=r.charCodeAt(s);if(n===-1&&Dg[o]===1)t===-1&&(t=s);else if(s!==0&&(o===32||o===9))n===-1&&t!==-1&&(n=s);else if(o===44){if(t===-1)throw new SyntaxError(`Unexpected character at index ${s}`);n===-1&&(n=s);let a=r.slice(t,n);if(e.has(a))throw new SyntaxError(`The "${a}" subprotocol is duplicated`);e.add(a),t=n=-1}else throw new SyntaxError(`Unexpected character at index ${s}`)}if(t===-1||n!==-1)throw new SyntaxError("Unexpected end of input");let i=r.slice(t,s);if(e.has(i))throw new SyntaxError(`The "${i}" subprotocol is duplicated`);return e.add(i),e}Wl.exports={parse:Lg}});var rd=Y((eb,td)=>{"use strict";var zg=require("events"),ti=require("http"),{Duplex:Qv}=require("stream"),{createHash:Ug}=require("crypto"),Jl=Js(),Er=ln(),qg=Vo(),Bg=ei(),{CLOSE_TIMEOUT:Fg,GUID:Zg,kWebSocket:Kg}=ht(),Vg=/^[+/0-9A-Za-z]{22}==$/,Yl=0,Xl=1,ed=2,Ho=class extends zg{constructor(e,t){if(super(),e={allowSynchronousEvents:!0,autoPong:!0,maxBufferedChunks:256*1024,maxFragments:16*1024,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:Fg,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:Bg,...e},e.port==null&&!e.server&&!e.noServer||e.port!=null&&(e.server||e.noServer)||e.server&&e.noServer)throw new TypeError('One and only one of the "port", "server", or "noServer" options must be specified');if(e.port!=null?(this._server=ti.createServer((n,s)=>{let i=ti.STATUS_CODES[426];s.writeHead(426,{"Content-Length":i.length,"Content-Type":"text/plain"}),s.end(i)}),this._server.listen(e.port,e.host,e.backlog,t)):e.server&&(this._server=e.server),this._server){let n=this.emit.bind(this,"connection");this._removeListeners=Hg(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(s,i,o)=>{this.handleUpgrade(s,i,o,n)}})}e.perMessageDeflate===!0&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=Yl}address(){if(this.options.noServer)throw new Error('The server is operating in "noServer" mode');return this._server?this._server.address():null}close(e){if(this._state===ed){e&&this.once("close",()=>{e(new Error("The server is not running"))}),process.nextTick(Vn,this);return}if(e&&this.once("close",e),this._state!==Xl)if(this._state=Xl,this.options.noServer||this.options.server)this._server&&(this._removeListeners(),this._removeListeners=this._server=null),this.clients?this.clients.size?this._shouldEmitClose=!0:process.nextTick(Vn,this):process.nextTick(Vn,this);else{let t=this._server;this._removeListeners(),this._removeListeners=this._server=null,t.close(()=>{Vn(this)})}}shouldHandle(e){if(this.options.path){let t=e.url.indexOf("?");if((t!==-1?e.url.slice(0,t):e.url)!==this.options.path)return!1}return!0}handleUpgrade(e,t,n,s){t.on("error",Ql);let i=e.headers["sec-websocket-key"],o=e.headers.upgrade,a=+e.headers["sec-websocket-version"];if(e.method!=="GET"){Ir(this,e,t,405,"Invalid HTTP method");return}if(o===void 0||o.toLowerCase()!=="websocket"){Ir(this,e,t,400,"Invalid Upgrade header");return}if(i===void 0||!Vg.test(i)){Ir(this,e,t,400,"Missing or invalid Sec-WebSocket-Key header");return}if(a!==13&&a!==8){Ir(this,e,t,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(e)){Hn(t,400);return}let c=e.headers["sec-websocket-protocol"],l=new Set;if(c!==void 0)try{l=qg.parse(c)}catch{Ir(this,e,t,400,"Invalid Sec-WebSocket-Protocol header");return}let d=e.headers["sec-websocket-extensions"],p={};if(this.options.perMessageDeflate&&d!==void 0){let v=new Er({...this.options.perMessageDeflate,isServer:!0,maxPayload:this.options.maxPayload});try{let S=Jl.parse(d);S[Er.extensionName]&&(v.accept(S[Er.extensionName]),p[Er.extensionName]=v)}catch{Ir(this,e,t,400,"Invalid or unacceptable Sec-WebSocket-Extensions header");return}}if(this.options.verifyClient){let v={origin:e.headers[`${a===8?"sec-websocket-origin":"origin"}`],secure:!!(e.socket.authorized||e.socket.encrypted),req:e};if(this.options.verifyClient.length===2){this.options.verifyClient(v,(S,x,w,j)=>{if(!S)return Hn(t,x||401,w,j);this.completeUpgrade(p,i,l,e,t,n,s)});return}if(!this.options.verifyClient(v))return Hn(t,401)}this.completeUpgrade(p,i,l,e,t,n,s)}completeUpgrade(e,t,n,s,i,o,a){if(!i.readable||!i.writable)return i.destroy();if(i[Kg])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>Yl)return Hn(i,503);let l=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${Ug("sha1").update(t+Zg).digest("base64")}`],d=new this.options.WebSocket(null,void 0,this.options);if(n.size){let p=this.options.handleProtocols?this.options.handleProtocols(n,s):n.values().next().value;p&&(l.push(`Sec-WebSocket-Protocol: ${p}`),d._protocol=p)}if(e[Er.extensionName]){let p=e[Er.extensionName].params,v=Jl.format({[Er.extensionName]:[p]});l.push(`Sec-WebSocket-Extensions: ${v}`),d._extensions=e}this.emit("headers",l,s),i.write(l.concat(`\r
230
+ `).map(s=>s.trim()).filter(s=>s&&!s.includes("->"))[0]??null}async function xs(r,e,t=6e4){let s=(await Z(r,["symbolic-ref","refs/remotes/origin/HEAD"]).catch(()=>"")).trim().replace("refs/remotes/","")||"origin/main",i=await Z(r,["diff","--stat",`${s}...${e}`]),o=await Z(r,["diff",`${s}...${e}`]);return{base:s,stat:i.slice(0,4e3),diff:o.slice(0,t)}}function _u(){let r=process.env.ALLWRIGHT_CACHE_DIR??process.env.TICKETPILOT_CACHE_DIR??(le.default.existsSync(re.default.join(fr.default.homedir(),".cache","ticketpilot"))?re.default.join(fr.default.homedir(),".cache","ticketpilot"):re.default.join(fr.default.homedir(),".cache","allwright"));return re.default.join(r,"env-checkouts")}function du(r){return r.replace(/[^\w.-]+/g,"_")}function vu(r,e){return re.default.join(_u(),du(r),du(e))}async function Zi(r){let e=vu(r.repoName,r.envName);return await Z(r.repoPath,["fetch","origin",r.branch],{timeoutMs:3e5}),le.default.existsSync(re.default.join(e,".git"))?await Z(e,["fetch","origin",r.branch],{timeoutMs:3e5}):(le.default.rmSync(e,{recursive:!0,force:!0}),le.default.mkdirSync(re.default.dirname(e),{recursive:!0,mode:448}),await Z(r.repoPath,["worktree","prune"]).catch(()=>{}),await Z(r.repoPath,["worktree","add","--detach",e,`origin/${r.branch}`])),r.attached?await Z(e,["checkout","-B",r.branch,`origin/${r.branch}`]):await Z(e,["checkout","--force","--detach",`origin/${r.branch}`]),e}async function Ki(r,e,t){try{await Z(r,["fetch","origin",e],{timeoutMs:3e5})}catch{return{ok:!1,reason:`branch "${e}" does not exist on origin \u2014 nothing to promote. Check the environment's ticket branch template against the branch your implement rule creates.`}}try{return await Z(r,["merge-base","--is-ancestor",`origin/${e}`,"HEAD"]),{ok:!0,alreadyMerged:!0}}catch{}try{return await Z(r,["-c",`user.name=${mu}`,"-c",`user.email=${gu}`,"merge","--no-ff","-m",t,`origin/${e}`]),{ok:!0}}catch(n){return await Z(r,["merge","--abort"]).catch(()=>{}),{ok:!1,reason:`could not merge "${e}" into the environment branch \u2014 ${n instanceof Error?n.message:n}. Resolve it manually and deploy again.`}}}async function Vi(r,e){try{await Z(r,["push","origin",e],{timeoutMs:3e5})}catch(t){throw new Error(`could not push "${e}" \u2014 ${t instanceof Error?t.message:t}. Someone may have pushed to it since this deploy started; retry.`)}}async function Hi(r,e,t){try{return await pu("git",["-C",r,"diff","--quiet",e,t,"--"],{timeout:12e4,env:{...process.env,GIT_TERMINAL_PROMPT:"0"}}),!1}catch(n){let s=n;if(s.code===1)return!0;throw new Error(`git diff failed comparing ${e}..${t}: ${(s.stderr||s.message||"").trim().slice(0,500)}`)}}async function pr(r){return(await Z(r,["config","--get","remote.origin.url"])).trim()}function mr(r){let e=/^git@github\.com(?:-[\w.-]+)?:([^/]+)\/(.+?)(\.git)?$/.exec(r)??/^https:\/\/github\.com\/([^/]+)\/(.+?)(\.git)?\/?$/.exec(r)??/^ssh:\/\/git@github\.com(?:-[\w.-]+)?\/([^/]+)\/(.+?)(\.git)?$/.exec(r);return e?{owner:e[1],repo:e[2]}:null}var le,fr,re,hu,fu,pu,mu,gu,bs,ws,yu,Wr,gr=ii(()=>{"use strict";le=$(require("node:fs"),1),fr=$(require("node:os"),1),re=$(require("node:path"),1),hu=require("node:child_process"),fu=require("node:util"),pu=(0,fu.promisify)(hu.execFile),mu="Allwright Agent",gu="agent@ticketpilot.local",bs=200,ws=2e4,yu=[/^\.github\/workflows\//,/^\.git\b/,/(^|\/)\.githooks\//];Wr=".ticketpilot-delete"});var tn={};Yn(tn,{GitHubClient:()=>Oe});var Bp,Oe,ct=ii(()=>{"use strict";Bp=process.env.TICKETPILOT_GITHUB_API??"https://api.github.com",Oe=class{constructor(e){this.token=e}token;async request(e,t,n){let s=await fetch(`${Bp}${t}`,{method:e,headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","User-Agent":"allwright",...n!==void 0?{"Content-Type":"application/json"}:{}},body:n===void 0?void 0:JSON.stringify(n)}),i=await s.text(),o=null;try{o=i?JSON.parse(i):null}catch{}if(s.status===401)throw new Error("GitHub rejected the token (401) \u2014 expired or revoked? Run `allwright github set-token`");if(!s.ok&&s.status!==422){let a=o?.message??i.slice(0,300);throw new Error(`GitHub ${e} ${t} -> ${s.status}: ${a}`)}return{status:s.status,data:o}}async whoami(){let{data:e}=await this.request("GET","/user");return e.login}async createPullRequest(e,t,n){let{status:s,data:i}=await this.request("POST",`/repos/${e}/${t}/pulls`,n);if(s===422){let{data:o}=await this.request("GET",`/repos/${e}/${t}/pulls?head=${encodeURIComponent(`${e}:${n.head}`)}&state=open`);if(o?.length){let a=o[0];return{number:a.number,url:a.html_url,state:a.state,merged:a.merged??!1,headSha:a.head.sha,mergeableState:null}}throw new Error(`GitHub refused the PR (422): ${i?.message??"validation failed"}`)}return{number:i.number,url:i.html_url,state:i.state,merged:i.merged??!1,headSha:i.head.sha,mergeableState:null}}async getReviews(e,t,n){let{data:s}=await this.request("GET",`/repos/${e}/${t}/pulls/${n}/reviews?per_page=100`);return(s??[]).map(i=>({state:i.state??"",commitId:i.commit_id??"",user:i.user?.login??"",submittedAt:i.submitted_at??""}))}async getPullRequest(e,t,n){try{let{data:s}=await this.request("GET",`/repos/${e}/${t}/pulls/${n}`);return{number:s.number,url:s.html_url,state:s.state,merged:s.merged,headSha:s.head.sha,mergeableState:s.mergeable_state??null}}catch(s){if(s instanceof Error&&s.message.includes("-> 404"))return null;throw s}}async closePullRequest(e,t,n){await this.request("PATCH",`/repos/${e}/${t}/pulls/${n}`,{state:"closed"})}async deleteBranch(e,t,n){try{await this.request("DELETE",`/repos/${e}/${t}/git/refs/heads/${encodeURIComponent(n)}`)}catch(s){if(s instanceof Error&&s.message.includes("-> 404"))return;throw s}}}});var ht=Y((Lv,rl)=>{"use strict";var el=["nodebuffer","arraybuffer","fragments"],tl=typeof Blob<"u";tl&&el.push("blob");rl.exports={BINARY_TYPES:el,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:tl,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var qn=Y((zv,Bs)=>{"use strict";var{EMPTY_BUFFER:Am}=ht(),Eo=Buffer[Symbol.species];function Rm(r,e){if(r.length===0)return Am;if(r.length===1)return r[0];let t=Buffer.allocUnsafe(e),n=0;for(let s=0;s<r.length;s++){let i=r[s];t.set(i,n),n+=i.length}return n<e?new Eo(t.buffer,t.byteOffset,n):t}function nl(r,e,t,n,s){for(let i=0;i<s;i++)t[n+i]=r[i]^e[i&3]}function sl(r,e){for(let t=0;t<r.length;t++)r[t]^=e[t&3]}function $m(r){return r.length===r.buffer.byteLength?r.buffer:r.buffer.slice(r.byteOffset,r.byteOffset+r.length)}function Io(r){if(Io.readOnly=!0,Buffer.isBuffer(r))return r;let e;return r instanceof ArrayBuffer?e=new Eo(r):ArrayBuffer.isView(r)?e=new Eo(r.buffer,r.byteOffset,r.byteLength):(e=Buffer.from(r),Io.readOnly=!1),e}Bs.exports={concat:Rm,mask:nl,toArrayBuffer:$m,toBuffer:Io,unmask:sl};if(!process.env.WS_NO_BUFFER_UTIL)try{let r=require("bufferutil");Bs.exports.mask=function(e,t,n,s,i){i<48?nl(e,t,n,s,i):r.mask(e,t,n,s,i)},Bs.exports.unmask=function(e,t){e.length<32?sl(e,t):r.unmask(e,t)}}catch{}});var al=Y((Uv,ol)=>{"use strict";var il=Symbol("kDone"),Ao=Symbol("kRun"),Ro=class{constructor(e){this[il]=()=>{this.pending--,this[Ao]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[Ao]()}[Ao](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[il])}}};ol.exports=Ro});var ln=Y((qv,dl)=>{"use strict";var Bn=require("zlib"),ul=qn(),Pm=al(),{kStatusCode:cl}=ht(),jm=Buffer[Symbol.species],Om=Buffer.from([0,0,255,255]),Zs=Symbol("permessage-deflate"),ft=Symbol("total-length"),un=Symbol("callback"),$t=Symbol("buffers"),cn=Symbol("error"),Fs,$o=class{constructor(e){if(this._options=e||{},this._threshold=this._options.threshold!==void 0?this._options.threshold:1024,this._maxPayload=this._options.maxPayload|0,this._isServer=!!this._options.isServer,this._deflate=null,this._inflate=null,this.params=null,!Fs){let t=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;Fs=new Pm(t)}}static get extensionName(){return"permessage-deflate"}offer(){let e={};return this._options.serverNoContextTakeover&&(e.server_no_context_takeover=!0),this._options.clientNoContextTakeover&&(e.client_no_context_takeover=!0),this._options.serverMaxWindowBits&&(e.server_max_window_bits=this._options.serverMaxWindowBits),this._options.clientMaxWindowBits?e.client_max_window_bits=this._options.clientMaxWindowBits:this._options.clientMaxWindowBits==null&&(e.client_max_window_bits=!0),e}accept(e){return e=this.normalizeParams(e),this.params=this._isServer?this.acceptAsServer(e):this.acceptAsClient(e),this.params}cleanup(){if(this._inflate&&(this._inflate.close(),this._inflate=null),this._deflate){let e=this._deflate[un];this._deflate.close(),this._deflate=null,e&&e(new Error("The deflate stream was closed while data was being processed"))}}acceptAsServer(e){let t=this._options,n=e.find(s=>!(t.serverNoContextTakeover===!1&&s.server_no_context_takeover||s.server_max_window_bits&&(t.serverMaxWindowBits===!1||typeof t.serverMaxWindowBits=="number"&&t.serverMaxWindowBits>s.server_max_window_bits)||typeof t.clientMaxWindowBits=="number"&&!s.client_max_window_bits));if(!n)throw new Error("None of the extension offers can be accepted");return t.serverNoContextTakeover&&(n.server_no_context_takeover=!0),t.clientNoContextTakeover&&(n.client_no_context_takeover=!0),typeof t.serverMaxWindowBits=="number"&&(n.server_max_window_bits=t.serverMaxWindowBits),typeof t.clientMaxWindowBits=="number"?n.client_max_window_bits=t.clientMaxWindowBits:(n.client_max_window_bits===!0||t.clientMaxWindowBits===!1)&&delete n.client_max_window_bits,n}acceptAsClient(e){let t=e[0];if(this._options.clientNoContextTakeover===!1&&t.client_no_context_takeover)throw new Error('Unexpected parameter "client_no_context_takeover"');if(!t.client_max_window_bits)typeof this._options.clientMaxWindowBits=="number"&&(t.client_max_window_bits=this._options.clientMaxWindowBits);else if(this._options.clientMaxWindowBits===!1||typeof this._options.clientMaxWindowBits=="number"&&t.client_max_window_bits>this._options.clientMaxWindowBits)throw new Error('Unexpected or invalid parameter "client_max_window_bits"');return t}normalizeParams(e){return e.forEach(t=>{Object.keys(t).forEach(n=>{let s=t[n];if(s.length>1)throw new Error(`Parameter "${n}" must have only a single value`);if(s=s[0],n==="client_max_window_bits"){if(s!==!0){let i=+s;if(!Number.isInteger(i)||i<8||i>15)throw new TypeError(`Invalid value for parameter "${n}": ${s}`);s=i}else if(!this._isServer)throw new TypeError(`Invalid value for parameter "${n}": ${s}`)}else if(n==="server_max_window_bits"){let i=+s;if(!Number.isInteger(i)||i<8||i>15)throw new TypeError(`Invalid value for parameter "${n}": ${s}`);s=i}else if(n==="client_no_context_takeover"||n==="server_no_context_takeover"){if(s!==!0)throw new TypeError(`Invalid value for parameter "${n}": ${s}`)}else throw new Error(`Unknown parameter "${n}"`);t[n]=s})}),e}decompress(e,t,n){Fs.add(s=>{this._decompress(e,t,(i,o)=>{s(),n(i,o)})})}compress(e,t,n){Fs.add(s=>{this._compress(e,t,(i,o)=>{s(),n(i,o)})})}_decompress(e,t,n){let s=this._isServer?"client":"server";if(!this._inflate){let i=`${s}_max_window_bits`,o=typeof this.params[i]!="number"?Bn.Z_DEFAULT_WINDOWBITS:this.params[i];this._inflate=Bn.createInflateRaw({...this._options.zlibInflateOptions,windowBits:o}),this._inflate[Zs]=this,this._inflate[ft]=0,this._inflate[$t]=[],this._inflate.on("error",Mm),this._inflate.on("data",ll)}this._inflate[un]=n,this._inflate.write(e),t&&this._inflate.write(Om),this._inflate.flush(()=>{let i=this._inflate[cn];if(i){this._inflate.close(),this._inflate=null,n(i);return}let o=ul.concat(this._inflate[$t],this._inflate[ft]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[ft]=0,this._inflate[$t]=[],t&&this.params[`${s}_no_context_takeover`]&&this._inflate.reset()),n(null,o)})}_compress(e,t,n){let s=this._isServer?"server":"client";if(!this._deflate){let i=`${s}_max_window_bits`,o=typeof this.params[i]!="number"?Bn.Z_DEFAULT_WINDOWBITS:this.params[i];this._deflate=Bn.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:o}),this._deflate[ft]=0,this._deflate[$t]=[],this._deflate.on("data",Nm)}this._deflate[un]=n,this._deflate.write(e),this._deflate.flush(Bn.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let i=ul.concat(this._deflate[$t],this._deflate[ft]);t&&(i=new jm(i.buffer,i.byteOffset,i.length-4)),this._deflate[un]=null,this._deflate[ft]=0,this._deflate[$t]=[],t&&this.params[`${s}_no_context_takeover`]&&this._deflate.reset(),n(null,i)})}};dl.exports=$o;function Nm(r){this[$t].push(r),this[ft]+=r.length}function ll(r){if(this[ft]+=r.length,this[Zs]._maxPayload<1||this[ft]<=this[Zs]._maxPayload){this[$t].push(r);return}this[cn]=new RangeError("Max payload size exceeded"),this[cn].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[cn][cl]=1009,this.removeListener("data",ll),this.reset()}function Mm(r){if(this[Zs]._inflate=null,this[cn]){this[un](this[cn]);return}r[cl]=1007,this[un](r)}});var dn=Y((Bv,Ks)=>{"use strict";var{isUtf8:hl}=require("buffer"),{hasBlob:Dm}=ht(),Lm=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,1,0,0,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,0];function zm(r){return r>=1e3&&r<=1014&&r!==1004&&r!==1005&&r!==1006||r>=3e3&&r<=4999}function Po(r){let e=r.length,t=0;for(;t<e;)if((r[t]&128)===0)t++;else if((r[t]&224)===192){if(t+1===e||(r[t+1]&192)!==128||(r[t]&254)===192)return!1;t+=2}else if((r[t]&240)===224){if(t+2>=e||(r[t+1]&192)!==128||(r[t+2]&192)!==128||r[t]===224&&(r[t+1]&224)===128||r[t]===237&&(r[t+1]&224)===160)return!1;t+=3}else if((r[t]&248)===240){if(t+3>=e||(r[t+1]&192)!==128||(r[t+2]&192)!==128||(r[t+3]&192)!==128||r[t]===240&&(r[t+1]&240)===128||r[t]===244&&r[t+1]>143||r[t]>244)return!1;t+=4}else return!1;return!0}function Um(r){return Dm&&typeof r=="object"&&typeof r.arrayBuffer=="function"&&typeof r.type=="string"&&typeof r.stream=="function"&&(r[Symbol.toStringTag]==="Blob"||r[Symbol.toStringTag]==="File")}Ks.exports={isBlob:Um,isValidStatusCode:zm,isValidUTF8:Po,tokenChars:Lm};if(hl)Ks.exports.isValidUTF8=function(r){return r.length<24?Po(r):hl(r)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let r=require("utf-8-validate");Ks.exports.isValidUTF8=function(e){return e.length<32?Po(e):r(e)}}catch{}});var Do=Y((Fv,vl)=>{"use strict";var{Writable:qm}=require("stream"),fl=ln(),{BINARY_TYPES:Bm,EMPTY_BUFFER:pl,kStatusCode:Fm,kWebSocket:Zm}=ht(),{concat:jo,toArrayBuffer:Km,unmask:Vm}=qn(),{isValidStatusCode:Hm,isValidUTF8:ml}=dn(),Vs=Buffer[Symbol.species],Ne=0,gl=1,yl=2,_l=3,Oo=4,No=5,Hs=6,Mo=class extends qm{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||Bm[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxBufferedChunks=e.maxBufferedChunks|0,this._maxFragments=e.maxFragments|0,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[Zm]=void 0,this._bufferedBytes=0,this._buffers=[],this._compressed=!1,this._payloadLength=0,this._mask=void 0,this._fragmented=0,this._masked=!1,this._fin=!1,this._opcode=0,this._totalPayloadLength=0,this._messageLength=0,this._numFragments=0,this._fragments=[],this._errored=!1,this._loop=!1,this._state=Ne}_write(e,t,n){if(this._opcode===8&&this._state==Ne)return n();if(this._maxBufferedChunks>0&&this._buffers.length>=this._maxBufferedChunks){n(this.createError(RangeError,"Too many buffered chunks",!1,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS"));return}this._bufferedBytes+=e.length,this._buffers.push(e),this.startLoop(n)}consume(e){if(this._bufferedBytes-=e,e===this._buffers[0].length)return this._buffers.shift();if(e<this._buffers[0].length){let n=this._buffers[0];return this._buffers[0]=new Vs(n.buffer,n.byteOffset+e,n.length-e),new Vs(n.buffer,n.byteOffset,e)}let t=Buffer.allocUnsafe(e);do{let n=this._buffers[0],s=t.length-e;e>=n.length?t.set(this._buffers.shift(),s):(t.set(new Uint8Array(n.buffer,n.byteOffset,e),s),this._buffers[0]=new Vs(n.buffer,n.byteOffset+e,n.length-e)),e-=n.length}while(e>0);return t}startLoop(e){this._loop=!0;do switch(this._state){case Ne:this.getInfo(e);break;case gl:this.getPayloadLength16(e);break;case yl:this.getPayloadLength64(e);break;case _l:this.getMask();break;case Oo:this.getData(e);break;case No:case Hs:this._loop=!1;return}while(this._loop);this._errored||e()}getInfo(e){if(this._bufferedBytes<2){this._loop=!1;return}let t=this.consume(2);if((t[0]&48)!==0){let s=this.createError(RangeError,"RSV2 and RSV3 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_2_3");e(s);return}let n=(t[0]&64)===64;if(n&&!this._extensions[fl.extensionName]){let s=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(s);return}if(this._fin=(t[0]&128)===128,this._opcode=t[0]&15,this._payloadLength=t[1]&127,this._opcode===0){if(n){let s=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(s);return}if(!this._fragmented){let s=this.createError(RangeError,"invalid opcode 0",!0,1002,"WS_ERR_INVALID_OPCODE");e(s);return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){let s=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(s);return}this._compressed=n}else if(this._opcode>7&&this._opcode<11){if(!this._fin){let s=this.createError(RangeError,"FIN must be set",!0,1002,"WS_ERR_EXPECTED_FIN");e(s);return}if(n){let s=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(s);return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){let s=this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH");e(s);return}}else{let s=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(s);return}if(!this._fin&&!this._fragmented&&(this._fragmented=this._opcode),this._masked=(t[1]&128)===128,this._isServer){if(!this._masked){let s=this.createError(RangeError,"MASK must be set",!0,1002,"WS_ERR_EXPECTED_MASK");e(s);return}}else if(this._masked){let s=this.createError(RangeError,"MASK must be clear",!0,1002,"WS_ERR_UNEXPECTED_MASK");e(s);return}this._payloadLength===126?this._state=gl:this._payloadLength===127?this._state=yl:this.haveLength(e)}getPayloadLength16(e){if(this._bufferedBytes<2){this._loop=!1;return}this._payloadLength=this.consume(2).readUInt16BE(0),this.haveLength(e)}getPayloadLength64(e){if(this._bufferedBytes<8){this._loop=!1;return}let t=this.consume(8),n=t.readUInt32BE(0);if(n>Math.pow(2,21)-1){let s=this.createError(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",!1,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH");e(s);return}this._payloadLength=n*Math.pow(2,32)+t.readUInt32BE(4),this.haveLength(e)}haveLength(e){if(this._payloadLength&&this._opcode<8&&(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0)){let t=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");e(t);return}this._masked?this._state=_l:this._state=Oo}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=Oo}getData(e){let t=pl;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength){this._loop=!1;return}t=this.consume(this._payloadLength),this._masked&&(this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3])!==0&&Vm(t,this._mask)}if(this._opcode>7){this.controlMessage(t,e);return}if(this._maxFragments>0&&++this._numFragments>this._maxFragments){let n=this.createError(RangeError,"Too many message fragments",!1,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS");e(n);return}if(this._compressed){this._state=No,this.decompress(t,e);return}t.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(t)),this.dataMessage(e)}decompress(e,t){this._extensions[fl.extensionName].decompress(e,this._fin,(s,i)=>{if(s)return t(s);if(i.length){if(this._messageLength+=i.length,this._messageLength>this._maxPayload&&this._maxPayload>0){let o=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");t(o);return}this._fragments.push(i)}this.dataMessage(t),this._state===Ne&&this.startLoop(t)})}dataMessage(e){if(!this._fin){this._state=Ne;return}let t=this._messageLength,n=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._numFragments=0,this._fragments=[],this._opcode===2){let s;this._binaryType==="nodebuffer"?s=jo(n,t):this._binaryType==="arraybuffer"?s=Km(jo(n,t)):this._binaryType==="blob"?s=new Blob(n):s=n,this._allowSynchronousEvents?(this.emit("message",s,!0),this._state=Ne):(this._state=Hs,setImmediate(()=>{this.emit("message",s,!0),this._state=Ne,this.startLoop(e)}))}else{let s=jo(n,t);if(!this._skipUTF8Validation&&!ml(s)){let i=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(i);return}this._state===No||this._allowSynchronousEvents?(this.emit("message",s,!1),this._state=Ne):(this._state=Hs,setImmediate(()=>{this.emit("message",s,!1),this._state=Ne,this.startLoop(e)}))}}controlMessage(e,t){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit("conclude",1005,pl),this.end();else{let n=e.readUInt16BE(0);if(!Hm(n)){let i=this.createError(RangeError,`invalid status code ${n}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");t(i);return}let s=new Vs(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!ml(s)){let i=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");t(i);return}this._loop=!1,this.emit("conclude",n,s),this.end()}this._state=Ne;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",e),this._state=Ne):(this._state=Hs,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=Ne,this.startLoop(t)}))}createError(e,t,n,s,i){this._loop=!1,this._errored=!0;let o=new e(n?`Invalid WebSocket frame: ${t}`:t);return Error.captureStackTrace(o,this.createError),o.code=i,o[Fm]=s,o}};vl.exports=Mo});var Uo=Y((Kv,kl)=>{"use strict";var{Duplex:Zv}=require("stream"),{randomFillSync:Gm}=require("crypto"),{types:{isUint8Array:Wm}}=require("util"),bl=ln(),{EMPTY_BUFFER:Jm,kWebSocket:Ym,NOOP:Xm}=ht(),{isBlob:hn,isValidStatusCode:Qm}=dn(),{mask:wl,toBuffer:Tr}=qn(),Me=Symbol("kByteLength"),eg=Buffer.alloc(4),Gs=8*1024,xr,fn=Gs,Be=0,tg=1,rg=2,Lo=class r{constructor(e,t,n){this._extensions=t||{},n&&(this._generateMask=n,this._maskBuffer=Buffer.alloc(4)),this._socket=e,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=Be,this.onerror=Xm,this[Ym]=void 0}static frame(e,t){let n,s=!1,i=2,o=!1;t.mask&&(n=t.maskBuffer||eg,t.generateMask?t.generateMask(n):(fn===Gs&&(xr===void 0&&(xr=Buffer.alloc(Gs)),Gm(xr,0,Gs),fn=0),n[0]=xr[fn++],n[1]=xr[fn++],n[2]=xr[fn++],n[3]=xr[fn++]),o=(n[0]|n[1]|n[2]|n[3])===0,i=6);let a;typeof e=="string"?(!t.mask||o)&&t[Me]!==void 0?a=t[Me]:(e=Buffer.from(e),a=e.length):(a=e.length,s=t.mask&&t.readOnly&&!o);let c=a;a>=65536?(i+=8,c=127):a>125&&(i+=2,c=126);let l=Buffer.allocUnsafe(s?a+i:i);return l[0]=t.fin?t.opcode|128:t.opcode,t.rsv1&&(l[0]|=64),l[1]=c,c===126?l.writeUInt16BE(a,2):c===127&&(l[2]=l[3]=0,l.writeUIntBE(a,4,6)),t.mask?(l[1]|=128,l[i-4]=n[0],l[i-3]=n[1],l[i-2]=n[2],l[i-1]=n[3],o?[l,e]:s?(wl(e,n,l,i,a),[l]):(wl(e,n,e,0,a),[l,e])):[l,e]}close(e,t,n,s){let i;if(e===void 0)i=Jm;else{if(typeof e!="number"||!Qm(e))throw new TypeError("First argument must be a valid error code number");if(t===void 0||!t.length)i=Buffer.allocUnsafe(2),i.writeUInt16BE(e,0);else{let a=Buffer.byteLength(t);if(a>123)throw new RangeError("The message must not be greater than 123 bytes");if(i=Buffer.allocUnsafe(2+a),i.writeUInt16BE(e,0),typeof t=="string")i.write(t,2);else if(Wm(t))i.set(t,2);else throw new TypeError("Second argument must be a string or a Uint8Array")}}let o={[Me]:i.length,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==Be?this.enqueue([this.dispatch,i,!1,o,s]):this.sendFrame(r.frame(i,o),s)}ping(e,t,n){let s,i;if(typeof e=="string"?(s=Buffer.byteLength(e),i=!1):hn(e)?(s=e.size,i=!1):(e=Tr(e),s=e.length,i=Tr.readOnly),s>125)throw new RangeError("The data size must not be greater than 125 bytes");let o={[Me]:s,fin:!0,generateMask:this._generateMask,mask:t,maskBuffer:this._maskBuffer,opcode:9,readOnly:i,rsv1:!1};hn(e)?this._state!==Be?this.enqueue([this.getBlobData,e,!1,o,n]):this.getBlobData(e,!1,o,n):this._state!==Be?this.enqueue([this.dispatch,e,!1,o,n]):this.sendFrame(r.frame(e,o),n)}pong(e,t,n){let s,i;if(typeof e=="string"?(s=Buffer.byteLength(e),i=!1):hn(e)?(s=e.size,i=!1):(e=Tr(e),s=e.length,i=Tr.readOnly),s>125)throw new RangeError("The data size must not be greater than 125 bytes");let o={[Me]:s,fin:!0,generateMask:this._generateMask,mask:t,maskBuffer:this._maskBuffer,opcode:10,readOnly:i,rsv1:!1};hn(e)?this._state!==Be?this.enqueue([this.getBlobData,e,!1,o,n]):this.getBlobData(e,!1,o,n):this._state!==Be?this.enqueue([this.dispatch,e,!1,o,n]):this.sendFrame(r.frame(e,o),n)}send(e,t,n){let s=this._extensions[bl.extensionName],i=t.binary?2:1,o=t.compress,a,c;typeof e=="string"?(a=Buffer.byteLength(e),c=!1):hn(e)?(a=e.size,c=!1):(e=Tr(e),a=e.length,c=Tr.readOnly),this._firstFragment?(this._firstFragment=!1,o&&s&&s.params[s._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(o=a>=s._threshold),this._compress=o):(o=!1,i=0),t.fin&&(this._firstFragment=!0);let l={[Me]:a,fin:t.fin,generateMask:this._generateMask,mask:t.mask,maskBuffer:this._maskBuffer,opcode:i,readOnly:c,rsv1:o};hn(e)?this._state!==Be?this.enqueue([this.getBlobData,e,this._compress,l,n]):this.getBlobData(e,this._compress,l,n):this._state!==Be?this.enqueue([this.dispatch,e,this._compress,l,n]):this.dispatch(e,this._compress,l,n)}getBlobData(e,t,n,s){this._bufferedBytes+=n[Me],this._state=rg,e.arrayBuffer().then(i=>{if(this._socket.destroyed){let a=new Error("The socket was closed while the blob was being read");process.nextTick(zo,this,a,s);return}this._bufferedBytes-=n[Me];let o=Tr(i);t?this.dispatch(o,t,n,s):(this._state=Be,this.sendFrame(r.frame(o,n),s),this.dequeue())}).catch(i=>{process.nextTick(ng,this,i,s)})}dispatch(e,t,n,s){if(!t){this.sendFrame(r.frame(e,n),s);return}let i=this._extensions[bl.extensionName];this._bufferedBytes+=n[Me],this._state=tg,i.compress(e,n.fin,(o,a)=>{if(this._socket.destroyed){let c=new Error("The socket was closed while data was being compressed");zo(this,c,s);return}this._bufferedBytes-=n[Me],this._state=Be,n.readOnly=!1,this.sendFrame(r.frame(a,n),s),this.dequeue()})}dequeue(){for(;this._state===Be&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][Me],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][Me],this._queue.push(e)}sendFrame(e,t){e.length===2?(this._socket.cork(),this._socket.write(e[0]),this._socket.write(e[1],t),this._socket.uncork()):this._socket.write(e[0],t)}};kl.exports=Lo;function zo(r,e,t){typeof t=="function"&&t(e);for(let n=0;n<r._queue.length;n++){let s=r._queue[n],i=s[s.length-1];typeof i=="function"&&i(e)}}function ng(r,e,t){zo(r,e,t),r.onerror(e)}});var $l=Y((Vv,Rl)=>{"use strict";var{kForOnEventAttribute:Fn,kListener:qo}=ht(),Sl=Symbol("kCode"),Tl=Symbol("kData"),xl=Symbol("kError"),Cl=Symbol("kMessage"),El=Symbol("kReason"),pn=Symbol("kTarget"),Il=Symbol("kType"),Al=Symbol("kWasClean"),pt=class{constructor(e){this[pn]=null,this[Il]=e}get target(){return this[pn]}get type(){return this[Il]}};Object.defineProperty(pt.prototype,"target",{enumerable:!0});Object.defineProperty(pt.prototype,"type",{enumerable:!0});var Cr=class extends pt{constructor(e,t={}){super(e),this[Sl]=t.code===void 0?0:t.code,this[El]=t.reason===void 0?"":t.reason,this[Al]=t.wasClean===void 0?!1:t.wasClean}get code(){return this[Sl]}get reason(){return this[El]}get wasClean(){return this[Al]}};Object.defineProperty(Cr.prototype,"code",{enumerable:!0});Object.defineProperty(Cr.prototype,"reason",{enumerable:!0});Object.defineProperty(Cr.prototype,"wasClean",{enumerable:!0});var mn=class extends pt{constructor(e,t={}){super(e),this[xl]=t.error===void 0?null:t.error,this[Cl]=t.message===void 0?"":t.message}get error(){return this[xl]}get message(){return this[Cl]}};Object.defineProperty(mn.prototype,"error",{enumerable:!0});Object.defineProperty(mn.prototype,"message",{enumerable:!0});var Zn=class extends pt{constructor(e,t={}){super(e),this[Tl]=t.data===void 0?null:t.data}get data(){return this[Tl]}};Object.defineProperty(Zn.prototype,"data",{enumerable:!0});var sg={addEventListener(r,e,t={}){for(let s of this.listeners(r))if(!t[Fn]&&s[qo]===e&&!s[Fn])return;let n;if(r==="message")n=function(i,o){let a=new Zn("message",{data:o?i:i.toString()});a[pn]=this,Ws(e,this,a)};else if(r==="close")n=function(i,o){let a=new Cr("close",{code:i,reason:o.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});a[pn]=this,Ws(e,this,a)};else if(r==="error")n=function(i){let o=new mn("error",{error:i,message:i.message});o[pn]=this,Ws(e,this,o)};else if(r==="open")n=function(){let i=new pt("open");i[pn]=this,Ws(e,this,i)};else return;n[Fn]=!!t[Fn],n[qo]=e,t.once?this.once(r,n):this.on(r,n)},removeEventListener(r,e){for(let t of this.listeners(r))if(t[qo]===e&&!t[Fn]){this.removeListener(r,t);break}}};Rl.exports={CloseEvent:Cr,ErrorEvent:mn,Event:pt,EventTarget:sg,MessageEvent:Zn};function Ws(r,e,t){typeof r=="object"&&r.handleEvent?r.handleEvent.call(r,t):r.call(e,t)}});var Js=Y((Hv,Pl)=>{"use strict";var{tokenChars:Kn}=dn();function Ye(r,e,t){r[e]===void 0?r[e]=[t]:r[e].push(t)}function ig(r){let e=Object.create(null),t=Object.create(null),n=!1,s=!1,i=!1,o,a,c=-1,l=-1,d=-1,p=0;for(;p<r.length;p++)if(l=r.charCodeAt(p),o===void 0)if(d===-1&&Kn[l]===1)c===-1&&(c=p);else if(p!==0&&(l===32||l===9))d===-1&&c!==-1&&(d=p);else if(l===59||l===44){if(c===-1)throw new SyntaxError(`Unexpected character at index ${p}`);d===-1&&(d=p);let S=r.slice(c,d);l===44?(Ye(e,S,t),t=Object.create(null)):o=S,c=d=-1}else throw new SyntaxError(`Unexpected character at index ${p}`);else if(a===void 0)if(d===-1&&Kn[l]===1)c===-1&&(c=p);else if(l===32||l===9)d===-1&&c!==-1&&(d=p);else if(l===59||l===44){if(c===-1)throw new SyntaxError(`Unexpected character at index ${p}`);d===-1&&(d=p),Ye(t,r.slice(c,d),!0),l===44&&(Ye(e,o,t),t=Object.create(null),o=void 0),c=d=-1}else if(l===61&&c!==-1&&d===-1)a=r.slice(c,p),c=d=-1;else throw new SyntaxError(`Unexpected character at index ${p}`);else if(s){if(Kn[l]!==1)throw new SyntaxError(`Unexpected character at index ${p}`);c===-1?c=p:n||(n=!0),s=!1}else if(i)if(Kn[l]===1)c===-1&&(c=p);else if(l===34&&c!==-1)i=!1,d=p;else if(l===92)s=!0;else throw new SyntaxError(`Unexpected character at index ${p}`);else if(l===34&&r.charCodeAt(p-1)===61)i=!0;else if(d===-1&&Kn[l]===1)c===-1&&(c=p);else if(c!==-1&&(l===32||l===9))d===-1&&(d=p);else if(l===59||l===44){if(c===-1)throw new SyntaxError(`Unexpected character at index ${p}`);d===-1&&(d=p);let S=r.slice(c,d);n&&(S=S.replace(/\\/g,""),n=!1),Ye(t,a,S),l===44&&(Ye(e,o,t),t=Object.create(null),o=void 0),a=void 0,c=d=-1}else throw new SyntaxError(`Unexpected character at index ${p}`);if(c===-1||i||l===32||l===9)throw new SyntaxError("Unexpected end of input");d===-1&&(d=p);let v=r.slice(c,d);return o===void 0?Ye(e,v,t):(a===void 0?Ye(t,v,!0):n?Ye(t,a,v.replace(/\\/g,"")):Ye(t,a,v),Ye(e,o,t)),e}function og(r){return Object.keys(r).map(e=>{let t=r[e];return Array.isArray(t)||(t=[t]),t.map(n=>[e].concat(Object.keys(n).map(s=>{let i=n[s];return Array.isArray(i)||(i=[i]),i.map(o=>o===!0?s:`${s}=${o}`).join("; ")})).join("; ")).join(", ")}).join(", ")}Pl.exports={format:og,parse:ig}});var ei=Y((Jv,Zl)=>{"use strict";var ag=require("events"),ug=require("https"),cg=require("http"),Nl=require("net"),lg=require("tls"),{randomBytes:dg,createHash:hg}=require("crypto"),{Duplex:Gv,Readable:Wv}=require("stream"),{URL:Bo}=require("url"),Pt=ln(),fg=Do(),pg=Uo(),{isBlob:mg}=dn(),{BINARY_TYPES:jl,CLOSE_TIMEOUT:gg,EMPTY_BUFFER:Ys,GUID:yg,kForOnEventAttribute:Fo,kListener:_g,kStatusCode:vg,kWebSocket:oe,NOOP:Ml}=ht(),{EventTarget:{addEventListener:bg,removeEventListener:wg}}=$l(),{format:kg,parse:Sg}=Js(),{toBuffer:Tg}=qn(),Dl=Symbol("kAborted"),Zo=[8,13],mt=["CONNECTING","OPEN","CLOSING","CLOSED"],xg=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,ne=class r extends ag{constructor(e,t,n){super(),this._binaryType=jl[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=Ys,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol="",this._readyState=r.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,e!==null?(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,t===void 0?t=[]:Array.isArray(t)||(typeof t=="object"&&t!==null?(n=t,t=[]):t=[t]),Ll(this,e,t,n)):(this._autoPong=n.autoPong,this._closeTimeout=n.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){jl.includes(e)&&(this._binaryType=e,this._receiver&&(this._receiver._binaryType=e))}get bufferedAmount(){return this._socket?this._socket._writableState.length+this._sender._bufferedBytes:this._bufferedAmount}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(e,t,n){let s=new fg({allowSynchronousEvents:n.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxBufferedChunks:n.maxBufferedChunks,maxFragments:n.maxFragments,maxPayload:n.maxPayload,skipUTF8Validation:n.skipUTF8Validation}),i=new pg(e,this._extensions,n.generateMask);this._receiver=s,this._sender=i,this._socket=e,s[oe]=this,i[oe]=this,e[oe]=this,s.on("conclude",Ig),s.on("drain",Ag),s.on("error",Rg),s.on("message",$g),s.on("ping",Pg),s.on("pong",jg),i.onerror=Og,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),t.length>0&&e.unshift(t),e.on("close",ql),e.on("data",Qs),e.on("end",Bl),e.on("error",Fl),this._readyState=r.OPEN,this.emit("open")}emitClose(){if(!this._socket){this._readyState=r.CLOSED,this.emit("close",this._closeCode,this._closeMessage);return}this._extensions[Pt.extensionName]&&this._extensions[Pt.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=r.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(e,t){if(this.readyState!==r.CLOSED){if(this.readyState===r.CONNECTING){xe(this,this._req,"WebSocket was closed before the connection was established");return}if(this.readyState===r.CLOSING){this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();return}this._readyState=r.CLOSING,this._sender.close(e,t,!this._isServer,n=>{n||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),Ul(this)}}pause(){this.readyState===r.CONNECTING||this.readyState===r.CLOSED||(this._paused=!0,this._socket.pause())}ping(e,t,n){if(this.readyState===r.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(n=e,e=t=void 0):typeof t=="function"&&(n=t,t=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==r.OPEN){Ko(this,e,n);return}t===void 0&&(t=!this._isServer),this._sender.ping(e||Ys,t,n)}pong(e,t,n){if(this.readyState===r.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(n=e,e=t=void 0):typeof t=="function"&&(n=t,t=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==r.OPEN){Ko(this,e,n);return}t===void 0&&(t=!this._isServer),this._sender.pong(e||Ys,t,n)}resume(){this.readyState===r.CONNECTING||this.readyState===r.CLOSED||(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(e,t,n){if(this.readyState===r.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof t=="function"&&(n=t,t={}),typeof e=="number"&&(e=e.toString()),this.readyState!==r.OPEN){Ko(this,e,n);return}let s={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...t};this._extensions[Pt.extensionName]||(s.compress=!1),this._sender.send(e||Ys,s,n)}terminate(){if(this.readyState!==r.CLOSED){if(this.readyState===r.CONNECTING){xe(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=r.CLOSING,this._socket.destroy())}}};Object.defineProperty(ne,"CONNECTING",{enumerable:!0,value:mt.indexOf("CONNECTING")});Object.defineProperty(ne.prototype,"CONNECTING",{enumerable:!0,value:mt.indexOf("CONNECTING")});Object.defineProperty(ne,"OPEN",{enumerable:!0,value:mt.indexOf("OPEN")});Object.defineProperty(ne.prototype,"OPEN",{enumerable:!0,value:mt.indexOf("OPEN")});Object.defineProperty(ne,"CLOSING",{enumerable:!0,value:mt.indexOf("CLOSING")});Object.defineProperty(ne.prototype,"CLOSING",{enumerable:!0,value:mt.indexOf("CLOSING")});Object.defineProperty(ne,"CLOSED",{enumerable:!0,value:mt.indexOf("CLOSED")});Object.defineProperty(ne.prototype,"CLOSED",{enumerable:!0,value:mt.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(r=>{Object.defineProperty(ne.prototype,r,{enumerable:!0})});["open","error","close","message"].forEach(r=>{Object.defineProperty(ne.prototype,`on${r}`,{enumerable:!0,get(){for(let e of this.listeners(r))if(e[Fo])return e[_g];return null},set(e){for(let t of this.listeners(r))if(t[Fo]){this.removeListener(r,t);break}typeof e=="function"&&this.addEventListener(r,e,{[Fo]:!0})}})});ne.prototype.addEventListener=bg;ne.prototype.removeEventListener=wg;Zl.exports=ne;function Ll(r,e,t,n){let s={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:gg,protocolVersion:Zo[1],maxBufferedChunks:262144,maxFragments:16384,maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...n,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:"GET",host:void 0,path:void 0,port:void 0};if(r._autoPong=s.autoPong,r._closeTimeout=s.closeTimeout,!Zo.includes(s.protocolVersion))throw new RangeError(`Unsupported protocol version: ${s.protocolVersion} (supported versions: ${Zo.join(", ")})`);let i;if(e instanceof Bo)i=e;else try{i=new Bo(e)}catch{throw new SyntaxError(`Invalid URL: ${e}`)}i.protocol==="http:"?i.protocol="ws:":i.protocol==="https:"&&(i.protocol="wss:"),r._url=i.href;let o=i.protocol==="wss:",a=i.protocol==="ws+unix:",c;if(i.protocol!=="ws:"&&!o&&!a?c=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:a&&!i.pathname?c="The URL's pathname is empty":i.hash&&(c="The URL contains a fragment identifier"),c){let w=new SyntaxError(c);if(r._redirects===0)throw w;Xs(r,w);return}let l=o?443:80,d=dg(16).toString("base64"),p=o?ug.request:cg.request,v=new Set,S;if(s.createConnection=s.createConnection||(o?Eg:Cg),s.defaultPort=s.defaultPort||l,s.port=i.port||l,s.host=i.hostname.startsWith("[")?i.hostname.slice(1,-1):i.hostname,s.headers={...s.headers,"Sec-WebSocket-Version":s.protocolVersion,"Sec-WebSocket-Key":d,Connection:"Upgrade",Upgrade:"websocket"},s.path=i.pathname+i.search,s.timeout=s.handshakeTimeout,s.perMessageDeflate&&(S=new Pt({...s.perMessageDeflate,isServer:!1,maxPayload:s.maxPayload}),s.headers["Sec-WebSocket-Extensions"]=kg({[Pt.extensionName]:S.offer()})),t.length){for(let w of t){if(typeof w!="string"||!xg.test(w)||v.has(w))throw new SyntaxError("An invalid or duplicated subprotocol was specified");v.add(w)}s.headers["Sec-WebSocket-Protocol"]=t.join(",")}if(s.origin&&(s.protocolVersion<13?s.headers["Sec-WebSocket-Origin"]=s.origin:s.headers.Origin=s.origin),(i.username||i.password)&&(s.auth=`${i.username}:${i.password}`),a){let w=s.path.split(":");s.socketPath=w[0],s.path=w[1]}let x;if(s.followRedirects){if(r._redirects===0){r._originalIpc=a,r._originalSecure=o,r._originalHostOrSocketPath=a?s.socketPath:i.host;let w=n&&n.headers;if(n={...n,headers:{}},w)for(let[j,U]of Object.entries(w))n.headers[j.toLowerCase()]=U}else if(r.listenerCount("redirect")===0){let w=a?r._originalIpc?s.socketPath===r._originalHostOrSocketPath:!1:r._originalIpc?!1:i.host===r._originalHostOrSocketPath;(!w||r._originalSecure&&!o)&&(delete s.headers.authorization,delete s.headers.cookie,w||delete s.headers.host,s.auth=void 0)}s.auth&&!n.headers.authorization&&(n.headers.authorization="Basic "+Buffer.from(s.auth).toString("base64")),x=r._req=p(s),r._redirects&&r.emit("redirect",r.url,x)}else x=r._req=p(s);s.timeout&&x.on("timeout",()=>{xe(r,x,"Opening handshake has timed out")}),x.on("error",w=>{x===null||x[Dl]||(x=r._req=null,Xs(r,w))}),x.on("response",w=>{let j=w.headers.location,U=w.statusCode;if(j&&s.followRedirects&&U>=300&&U<400){if(++r._redirects>s.maxRedirects){xe(r,x,"Maximum redirects exceeded");return}x.abort();let f;try{f=new Bo(j,e)}catch{let b=new SyntaxError(`Invalid URL: ${j}`);Xs(r,b);return}Ll(r,f,t,n)}else r.emit("unexpected-response",x,w)||xe(r,x,`Unexpected server response: ${w.statusCode}`)}),x.on("upgrade",(w,j,U)=>{if(r.emit("upgrade",w),r.readyState!==ne.CONNECTING)return;x=r._req=null;let f=w.headers.upgrade;if(f===void 0||f.toLowerCase()!=="websocket"){xe(r,j,"Invalid Upgrade header");return}let g=hg("sha1").update(d+yg).digest("base64");if(w.headers["sec-websocket-accept"]!==g){xe(r,j,"Invalid Sec-WebSocket-Accept header");return}let b=w.headers["sec-websocket-protocol"],I;if(b!==void 0?v.size?v.has(b)||(I="Server sent an invalid subprotocol"):I="Server sent a subprotocol but none was requested":v.size&&(I="Server sent no subprotocol"),I){xe(r,j,I);return}b&&(r._protocol=b);let N=w.headers["sec-websocket-extensions"];if(N!==void 0){if(!S){xe(r,j,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let V;try{V=Sg(N)}catch{xe(r,j,"Invalid Sec-WebSocket-Extensions header");return}let W=Object.keys(V);if(W.length!==1||W[0]!==Pt.extensionName){xe(r,j,"Server indicated an extension that was not requested");return}try{S.accept(V[Pt.extensionName])}catch{xe(r,j,"Invalid Sec-WebSocket-Extensions header");return}r._extensions[Pt.extensionName]=S}r.setSocket(j,U,{allowSynchronousEvents:s.allowSynchronousEvents,generateMask:s.generateMask,maxBufferedChunks:s.maxBufferedChunks,maxFragments:s.maxFragments,maxPayload:s.maxPayload,skipUTF8Validation:s.skipUTF8Validation})}),s.finishRequest?s.finishRequest(x,r):x.end()}function Xs(r,e){r._readyState=ne.CLOSING,r._errorEmitted=!0,r.emit("error",e),r.emitClose()}function Cg(r){return r.path=r.socketPath,Nl.connect(r)}function Eg(r){return r.path=void 0,!r.servername&&r.servername!==""&&(r.servername=Nl.isIP(r.host)?"":r.host),lg.connect(r)}function xe(r,e,t){r._readyState=ne.CLOSING;let n=new Error(t);Error.captureStackTrace(n,xe),e.setHeader?(e[Dl]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(Xs,r,n)):(e.destroy(n),e.once("error",r.emit.bind(r,"error")),e.once("close",r.emitClose.bind(r)))}function Ko(r,e,t){if(e){let n=mg(e)?e.size:Tg(e).length;r._socket?r._sender._bufferedBytes+=n:r._bufferedAmount+=n}if(t){let n=new Error(`WebSocket is not open: readyState ${r.readyState} (${mt[r.readyState]})`);process.nextTick(t,n)}}function Ig(r,e){let t=this[oe];t._closeFrameReceived=!0,t._closeMessage=e,t._closeCode=r,t._socket[oe]!==void 0&&(t._socket.removeListener("data",Qs),process.nextTick(zl,t._socket),r===1005?t.close():t.close(r,e))}function Ag(){let r=this[oe];r.isPaused||r._socket.resume()}function Rg(r){let e=this[oe];e._socket[oe]!==void 0&&(e._socket.removeListener("data",Qs),process.nextTick(zl,e._socket),e.close(r[vg])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",r))}function Ol(){this[oe].emitClose()}function $g(r,e){this[oe].emit("message",r,e)}function Pg(r){let e=this[oe];e._autoPong&&e.pong(r,!this._isServer,Ml),e.emit("ping",r)}function jg(r){this[oe].emit("pong",r)}function zl(r){r.resume()}function Og(r){let e=this[oe];e.readyState!==ne.CLOSED&&(e.readyState===ne.OPEN&&(e._readyState=ne.CLOSING,Ul(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",r)))}function Ul(r){r._closeTimer=setTimeout(r._socket.destroy.bind(r._socket),r._closeTimeout)}function ql(){let r=this[oe];if(this.removeListener("close",ql),this.removeListener("data",Qs),this.removeListener("end",Bl),r._readyState=ne.CLOSING,!this._readableState.endEmitted&&!r._closeFrameReceived&&!r._receiver._writableState.errorEmitted&&this._readableState.length!==0){let e=this.read(this._readableState.length);r._receiver.write(e)}r._receiver.end(),this[oe]=void 0,clearTimeout(r._closeTimer),r._receiver._writableState.finished||r._receiver._writableState.errorEmitted?r.emitClose():(r._receiver.on("error",Ol),r._receiver.on("finish",Ol))}function Qs(r){this[oe]._receiver.write(r)||this.pause()}function Bl(){let r=this[oe];r._readyState=ne.CLOSING,r._receiver.end(),this.end()}function Fl(){let r=this[oe];this.removeListener("error",Fl),this.on("error",Ml),r&&(r._readyState=ne.CLOSING,this.destroy())}});var Gl=Y((Xv,Hl)=>{"use strict";var Yv=ei(),{Duplex:Ng}=require("stream");function Kl(r){r.emit("close")}function Mg(){!this.destroyed&&this._writableState.finished&&this.destroy()}function Vl(r){this.removeListener("error",Vl),this.destroy(),this.listenerCount("error")===0&&this.emit("error",r)}function Dg(r,e){let t=!0,n=new Ng({...e,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return r.on("message",function(i,o){let a=!o&&n._readableState.objectMode?i.toString():i;n.push(a)||r.pause()}),r.once("error",function(i){n.destroyed||(t=!1,n.destroy(i))}),r.once("close",function(){n.destroyed||n.push(null)}),n._destroy=function(s,i){if(r.readyState===r.CLOSED){i(s),process.nextTick(Kl,n);return}let o=!1;r.once("error",function(c){o=!0,i(c)}),r.once("close",function(){o||i(s),process.nextTick(Kl,n)}),t&&r.terminate()},n._final=function(s){if(r.readyState===r.CONNECTING){r.once("open",function(){n._final(s)});return}r._socket!==null&&(r._socket._writableState.finished?(s(),n._readableState.endEmitted&&n.destroy()):(r._socket.once("finish",function(){s()}),r.close()))},n._read=function(){r.isPaused&&r.resume()},n._write=function(s,i,o){if(r.readyState===r.CONNECTING){r.once("open",function(){n._write(s,i,o)});return}r.send(s,o)},n.on("end",Mg),n.on("error",Vl),n}Hl.exports=Dg});var Vo=Y((Qv,Wl)=>{"use strict";var{tokenChars:Lg}=dn();function zg(r){let e=new Set,t=-1,n=-1,s=0;for(s;s<r.length;s++){let o=r.charCodeAt(s);if(n===-1&&Lg[o]===1)t===-1&&(t=s);else if(s!==0&&(o===32||o===9))n===-1&&t!==-1&&(n=s);else if(o===44){if(t===-1)throw new SyntaxError(`Unexpected character at index ${s}`);n===-1&&(n=s);let a=r.slice(t,n);if(e.has(a))throw new SyntaxError(`The "${a}" subprotocol is duplicated`);e.add(a),t=n=-1}else throw new SyntaxError(`Unexpected character at index ${s}`)}if(t===-1||n!==-1)throw new SyntaxError("Unexpected end of input");let i=r.slice(t,s);if(e.has(i))throw new SyntaxError(`The "${i}" subprotocol is duplicated`);return e.add(i),e}Wl.exports={parse:zg}});var rd=Y((tb,td)=>{"use strict";var Ug=require("events"),ti=require("http"),{Duplex:eb}=require("stream"),{createHash:qg}=require("crypto"),Jl=Js(),Er=ln(),Bg=Vo(),Fg=ei(),{CLOSE_TIMEOUT:Zg,GUID:Kg,kWebSocket:Vg}=ht(),Hg=/^[+/0-9A-Za-z]{22}==$/,Yl=0,Xl=1,ed=2,Ho=class extends Ug{constructor(e,t){if(super(),e={allowSynchronousEvents:!0,autoPong:!0,maxBufferedChunks:256*1024,maxFragments:16*1024,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:Zg,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:Fg,...e},e.port==null&&!e.server&&!e.noServer||e.port!=null&&(e.server||e.noServer)||e.server&&e.noServer)throw new TypeError('One and only one of the "port", "server", or "noServer" options must be specified');if(e.port!=null?(this._server=ti.createServer((n,s)=>{let i=ti.STATUS_CODES[426];s.writeHead(426,{"Content-Length":i.length,"Content-Type":"text/plain"}),s.end(i)}),this._server.listen(e.port,e.host,e.backlog,t)):e.server&&(this._server=e.server),this._server){let n=this.emit.bind(this,"connection");this._removeListeners=Gg(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(s,i,o)=>{this.handleUpgrade(s,i,o,n)}})}e.perMessageDeflate===!0&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=Yl}address(){if(this.options.noServer)throw new Error('The server is operating in "noServer" mode');return this._server?this._server.address():null}close(e){if(this._state===ed){e&&this.once("close",()=>{e(new Error("The server is not running"))}),process.nextTick(Vn,this);return}if(e&&this.once("close",e),this._state!==Xl)if(this._state=Xl,this.options.noServer||this.options.server)this._server&&(this._removeListeners(),this._removeListeners=this._server=null),this.clients?this.clients.size?this._shouldEmitClose=!0:process.nextTick(Vn,this):process.nextTick(Vn,this);else{let t=this._server;this._removeListeners(),this._removeListeners=this._server=null,t.close(()=>{Vn(this)})}}shouldHandle(e){if(this.options.path){let t=e.url.indexOf("?");if((t!==-1?e.url.slice(0,t):e.url)!==this.options.path)return!1}return!0}handleUpgrade(e,t,n,s){t.on("error",Ql);let i=e.headers["sec-websocket-key"],o=e.headers.upgrade,a=+e.headers["sec-websocket-version"];if(e.method!=="GET"){Ir(this,e,t,405,"Invalid HTTP method");return}if(o===void 0||o.toLowerCase()!=="websocket"){Ir(this,e,t,400,"Invalid Upgrade header");return}if(i===void 0||!Hg.test(i)){Ir(this,e,t,400,"Missing or invalid Sec-WebSocket-Key header");return}if(a!==13&&a!==8){Ir(this,e,t,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(e)){Hn(t,400);return}let c=e.headers["sec-websocket-protocol"],l=new Set;if(c!==void 0)try{l=Bg.parse(c)}catch{Ir(this,e,t,400,"Invalid Sec-WebSocket-Protocol header");return}let d=e.headers["sec-websocket-extensions"],p={};if(this.options.perMessageDeflate&&d!==void 0){let v=new Er({...this.options.perMessageDeflate,isServer:!0,maxPayload:this.options.maxPayload});try{let S=Jl.parse(d);S[Er.extensionName]&&(v.accept(S[Er.extensionName]),p[Er.extensionName]=v)}catch{Ir(this,e,t,400,"Invalid or unacceptable Sec-WebSocket-Extensions header");return}}if(this.options.verifyClient){let v={origin:e.headers[`${a===8?"sec-websocket-origin":"origin"}`],secure:!!(e.socket.authorized||e.socket.encrypted),req:e};if(this.options.verifyClient.length===2){this.options.verifyClient(v,(S,x,w,j)=>{if(!S)return Hn(t,x||401,w,j);this.completeUpgrade(p,i,l,e,t,n,s)});return}if(!this.options.verifyClient(v))return Hn(t,401)}this.completeUpgrade(p,i,l,e,t,n,s)}completeUpgrade(e,t,n,s,i,o,a){if(!i.readable||!i.writable)return i.destroy();if(i[Vg])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>Yl)return Hn(i,503);let l=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${qg("sha1").update(t+Kg).digest("base64")}`],d=new this.options.WebSocket(null,void 0,this.options);if(n.size){let p=this.options.handleProtocols?this.options.handleProtocols(n,s):n.values().next().value;p&&(l.push(`Sec-WebSocket-Protocol: ${p}`),d._protocol=p)}if(e[Er.extensionName]){let p=e[Er.extensionName].params,v=Jl.format({[Er.extensionName]:[p]});l.push(`Sec-WebSocket-Extensions: ${v}`),d._extensions=e}this.emit("headers",l,s),i.write(l.concat(`\r
231
231
  `).join(`\r
232
- `)),i.removeListener("error",Ql),d.setSocket(i,o,{allowSynchronousEvents:this.options.allowSynchronousEvents,maxBufferedChunks:this.options.maxBufferedChunks,maxFragments:this.options.maxFragments,maxPayload:this.options.maxPayload,skipUTF8Validation:this.options.skipUTF8Validation}),this.clients&&(this.clients.add(d),d.on("close",()=>{this.clients.delete(d),this._shouldEmitClose&&!this.clients.size&&process.nextTick(Vn,this)})),a(d,s)}};td.exports=Ho;function Hg(r,e){for(let t of Object.keys(e))r.on(t,e[t]);return function(){for(let n of Object.keys(e))r.removeListener(n,e[n])}}function Vn(r){r._state=ed,r.emit("close")}function Ql(){this.destroy()}function Hn(r,e,t,n){t=t||ti.STATUS_CODES[e],n={Connection:"close","Content-Type":"text/html","Content-Length":Buffer.byteLength(t),...n},r.once("finish",r.destroy),r.end(`HTTP/1.1 ${e} ${ti.STATUS_CODES[e]}\r
232
+ `)),i.removeListener("error",Ql),d.setSocket(i,o,{allowSynchronousEvents:this.options.allowSynchronousEvents,maxBufferedChunks:this.options.maxBufferedChunks,maxFragments:this.options.maxFragments,maxPayload:this.options.maxPayload,skipUTF8Validation:this.options.skipUTF8Validation}),this.clients&&(this.clients.add(d),d.on("close",()=>{this.clients.delete(d),this._shouldEmitClose&&!this.clients.size&&process.nextTick(Vn,this)})),a(d,s)}};td.exports=Ho;function Gg(r,e){for(let t of Object.keys(e))r.on(t,e[t]);return function(){for(let n of Object.keys(e))r.removeListener(n,e[n])}}function Vn(r){r._state=ed,r.emit("close")}function Ql(){this.destroy()}function Hn(r,e,t,n){t=t||ti.STATUS_CODES[e],n={Connection:"close","Content-Type":"text/html","Content-Length":Buffer.byteLength(t),...n},r.once("finish",r.destroy),r.end(`HTTP/1.1 ${e} ${ti.STATUS_CODES[e]}\r
233
233
  `+Object.keys(n).map(s=>`${s}: ${n[s]}`).join(`\r
234
234
  `)+`\r
235
235
  \r
236
- `+t)}function Ir(r,e,t,n,s,i){if(r.listenerCount("wsClientError")){let o=new Error(s);Error.captureStackTrace(o,Ir),r.emit("wsClientError",o,t,e)}else Hn(t,n,s,i)}});var dd={};Yn(dd,{buildSetupReport:()=>ay,claudeLoggedIn:()=>ld});function ld(r=ud.default.homedir()){if(jt.default.existsSync(Ar.default.join(r,".claude",".credentials.json")))return!0;try{return!!JSON.parse(jt.default.readFileSync(Ar.default.join(r,".claude.json"),"utf8")).oauthAccount}catch{return!1}}async function ay(r,e){let t=!1,n="";try{let{stdout:o}=await oy(r.claudeBin,["--version"],{timeout:1e4});t=!0,n=o.trim().slice(0,60)}catch{t=!1}let s=e.map(o=>{let a=r.repos[o];if(!a)return{repoName:o,mapped:!1,pathExists:!1,isGit:!1,claudeMd:!1,deployMd:!1,testMd:!1};let c=jt.default.existsSync(a.path);return{repoName:o,mapped:!0,pathExists:c,isGit:c&&jt.default.existsSync(Ar.default.join(a.path,".git")),claudeMd:c&&jt.default.existsSync(Ar.default.join(a.path,"CLAUDE.md")),deployMd:c&&jt.default.existsSync(Ar.default.join(a.path,"DEPLOY.md")),testMd:c&&jt.default.existsSync(Ar.default.join(a.path,"TEST.md"))}}),i=Object.values(r.repos).find(o=>o.github?.token);return{jiraConfigured:!!r.jira,jiraEmail:r.jira?.email??"",claude:{installed:t,version:n,loggedIn:ld()},githubTokenSet:!!(r.github?.token||i),githubLogin:r.github?.login??i?.github?.login??"",deploysEnabled:r.deploy.enabled,jiraUserCount:Object.keys(r.jiraUsers).length,repos:s}}var ad,jt,ud,Ar,cd,oy,hd=ii(()=>{"use strict";ad=require("node:child_process"),jt=$(require("node:fs"),1),ud=$(require("node:os"),1),Ar=$(require("node:path"),1),cd=require("node:util"),oy=(0,cd.promisify)(ad.execFile)});var yn=$(require("node:fs"),1),fd=$(require("node:os"),1),pd=$(require("node:path"),1),Wn=require("node:child_process"),Xo=require("node:crypto"),Rr=$(require("node:readline/promises"),1);var ya=$(ga(),1),{program:yy,createCommand:_y,createArgument:vy,createOption:by,CommanderError:wy,InvalidArgumentError:ky,InvalidOptionArgumentError:Sy,Command:_a,Argument:Ty,Option:xy,Help:Cy}=ya.default;var st=$(require("node:fs"),1),is=$(require("node:os"),1),os=$(require("node:path"),1);var k={};Yn(k,{BRAND:()=>uh,DIRTY:()=>Ot,EMPTY_PATH:()=>Ud,INVALID:()=>M,NEVER:()=>Vh,OK:()=>he,ParseStatus:()=>ue,Schema:()=>K,ZodAny:()=>vt,ZodArray:()=>nt,ZodBigInt:()=>Mt,ZodBoolean:()=>Dt,ZodBranded:()=>wn,ZodCatch:()=>Gt,ZodDate:()=>Lt,ZodDefault:()=>Ht,ZodDiscriminatedUnion:()=>rs,ZodEffects:()=>Re,ZodEnum:()=>Kt,ZodError:()=>ge,ZodFirstPartyTypeKind:()=>D,ZodFunction:()=>ss,ZodIntersection:()=>Bt,ZodIssueCode:()=>T,ZodLazy:()=>Ft,ZodLiteral:()=>Zt,ZodMap:()=>Mr,ZodNaN:()=>Lr,ZodNativeEnum:()=>Vt,ZodNever:()=>De,ZodNull:()=>Ut,ZodNullable:()=>Ke,ZodNumber:()=>Nt,ZodObject:()=>ye,ZodOptional:()=>Ie,ZodParsedType:()=>R,ZodPipeline:()=>kn,ZodPromise:()=>bt,ZodReadonly:()=>Wt,ZodRecord:()=>ns,ZodSchema:()=>K,ZodSet:()=>Dr,ZodString:()=>_t,ZodSymbol:()=>Or,ZodTransformer:()=>Re,ZodTuple:()=>Ze,ZodType:()=>K,ZodUndefined:()=>zt,ZodUnion:()=>qt,ZodUnknown:()=>rt,ZodVoid:()=>Nr,addIssueToContext:()=>A,any:()=>yh,array:()=>wh,bigint:()=>hh,boolean:()=>Aa,coerce:()=>Kh,custom:()=>Ca,date:()=>fh,datetimeRegex:()=>Ta,defaultErrorMap:()=>et,discriminatedUnion:()=>xh,effect:()=>Dh,enum:()=>Oh,function:()=>$h,getErrorMap:()=>$r,getParsedType:()=>Fe,instanceof:()=>lh,intersection:()=>Ch,isAborted:()=>es,isAsync:()=>Pr,isDirty:()=>ts,isValid:()=>yt,late:()=>ch,lazy:()=>Ph,literal:()=>jh,makeIssue:()=>bn,map:()=>Ah,nan:()=>dh,nativeEnum:()=>Nh,never:()=>vh,null:()=>gh,nullable:()=>zh,number:()=>Ia,object:()=>kh,objectUtil:()=>wi,oboolean:()=>Zh,onumber:()=>Fh,optional:()=>Lh,ostring:()=>Bh,pipeline:()=>qh,preprocess:()=>Uh,promise:()=>Mh,quotelessJson:()=>Dd,record:()=>Ih,set:()=>Rh,setErrorMap:()=>zd,strictObject:()=>Sh,string:()=>Ea,symbol:()=>ph,transformer:()=>Dh,tuple:()=>Eh,undefined:()=>mh,union:()=>Th,unknown:()=>_h,util:()=>G,void:()=>bh});var G;(function(r){r.assertEqual=s=>{};function e(s){}r.assertIs=e;function t(s){throw new Error}r.assertNever=t,r.arrayToEnum=s=>{let i={};for(let o of s)i[o]=o;return i},r.getValidEnumValues=s=>{let i=r.objectKeys(s).filter(a=>typeof s[s[a]]!="number"),o={};for(let a of i)o[a]=s[a];return r.objectValues(o)},r.objectValues=s=>r.objectKeys(s).map(function(i){return s[i]}),r.objectKeys=typeof Object.keys=="function"?s=>Object.keys(s):s=>{let i=[];for(let o in s)Object.prototype.hasOwnProperty.call(s,o)&&i.push(o);return i},r.find=(s,i)=>{for(let o of s)if(i(o))return o},r.isInteger=typeof Number.isInteger=="function"?s=>Number.isInteger(s):s=>typeof s=="number"&&Number.isFinite(s)&&Math.floor(s)===s;function n(s,i=" | "){return s.map(o=>typeof o=="string"?`'${o}'`:o).join(i)}r.joinValues=n,r.jsonStringifyReplacer=(s,i)=>typeof i=="bigint"?i.toString():i})(G||(G={}));var wi;(function(r){r.mergeShapes=(e,t)=>({...e,...t})})(wi||(wi={}));var R=G.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Fe=r=>{switch(typeof r){case"undefined":return R.undefined;case"string":return R.string;case"number":return Number.isNaN(r)?R.nan:R.number;case"boolean":return R.boolean;case"function":return R.function;case"bigint":return R.bigint;case"symbol":return R.symbol;case"object":return Array.isArray(r)?R.array:r===null?R.null:r.then&&typeof r.then=="function"&&r.catch&&typeof r.catch=="function"?R.promise:typeof Map<"u"&&r instanceof Map?R.map:typeof Set<"u"&&r instanceof Set?R.set:typeof Date<"u"&&r instanceof Date?R.date:R.object;default:return R.unknown}};var T=G.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),Dd=r=>JSON.stringify(r,null,2).replace(/"([^"]+)":/g,"$1:"),ge=class r extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=n=>{this.issues=[...this.issues,n]},this.addIssues=(n=[])=>{this.issues=[...this.issues,...n]};let t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name="ZodError",this.issues=e}format(e){let t=e||function(i){return i.message},n={_errors:[]},s=i=>{for(let o of i.issues)if(o.code==="invalid_union")o.unionErrors.map(s);else if(o.code==="invalid_return_type")s(o.returnTypeError);else if(o.code==="invalid_arguments")s(o.argumentsError);else if(o.path.length===0)n._errors.push(t(o));else{let a=n,c=0;for(;c<o.path.length;){let l=o.path[c];c===o.path.length-1?(a[l]=a[l]||{_errors:[]},a[l]._errors.push(t(o))):a[l]=a[l]||{_errors:[]},a=a[l],c++}}};return s(this),n}static assert(e){if(!(e instanceof r))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,G.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=t=>t.message){let t={},n=[];for(let s of this.issues)if(s.path.length>0){let i=s.path[0];t[i]=t[i]||[],t[i].push(e(s))}else n.push(e(s));return{formErrors:n,fieldErrors:t}}get formErrors(){return this.flatten()}};ge.create=r=>new ge(r);var Ld=(r,e)=>{let t;switch(r.code){case T.invalid_type:r.received===R.undefined?t="Required":t=`Expected ${r.expected}, received ${r.received}`;break;case T.invalid_literal:t=`Invalid literal value, expected ${JSON.stringify(r.expected,G.jsonStringifyReplacer)}`;break;case T.unrecognized_keys:t=`Unrecognized key(s) in object: ${G.joinValues(r.keys,", ")}`;break;case T.invalid_union:t="Invalid input";break;case T.invalid_union_discriminator:t=`Invalid discriminator value. Expected ${G.joinValues(r.options)}`;break;case T.invalid_enum_value:t=`Invalid enum value. Expected ${G.joinValues(r.options)}, received '${r.received}'`;break;case T.invalid_arguments:t="Invalid function arguments";break;case T.invalid_return_type:t="Invalid function return type";break;case T.invalid_date:t="Invalid date";break;case T.invalid_string:typeof r.validation=="object"?"includes"in r.validation?(t=`Invalid input: must include "${r.validation.includes}"`,typeof r.validation.position=="number"&&(t=`${t} at one or more positions greater than or equal to ${r.validation.position}`)):"startsWith"in r.validation?t=`Invalid input: must start with "${r.validation.startsWith}"`:"endsWith"in r.validation?t=`Invalid input: must end with "${r.validation.endsWith}"`:G.assertNever(r.validation):r.validation!=="regex"?t=`Invalid ${r.validation}`:t="Invalid";break;case T.too_small:r.type==="array"?t=`Array must contain ${r.exact?"exactly":r.inclusive?"at least":"more than"} ${r.minimum} element(s)`:r.type==="string"?t=`String must contain ${r.exact?"exactly":r.inclusive?"at least":"over"} ${r.minimum} character(s)`:r.type==="number"?t=`Number must be ${r.exact?"exactly equal to ":r.inclusive?"greater than or equal to ":"greater than "}${r.minimum}`:r.type==="bigint"?t=`Number must be ${r.exact?"exactly equal to ":r.inclusive?"greater than or equal to ":"greater than "}${r.minimum}`:r.type==="date"?t=`Date must be ${r.exact?"exactly equal to ":r.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(r.minimum))}`:t="Invalid input";break;case T.too_big:r.type==="array"?t=`Array must contain ${r.exact?"exactly":r.inclusive?"at most":"less than"} ${r.maximum} element(s)`:r.type==="string"?t=`String must contain ${r.exact?"exactly":r.inclusive?"at most":"under"} ${r.maximum} character(s)`:r.type==="number"?t=`Number must be ${r.exact?"exactly":r.inclusive?"less than or equal to":"less than"} ${r.maximum}`:r.type==="bigint"?t=`BigInt must be ${r.exact?"exactly":r.inclusive?"less than or equal to":"less than"} ${r.maximum}`:r.type==="date"?t=`Date must be ${r.exact?"exactly":r.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(r.maximum))}`:t="Invalid input";break;case T.custom:t="Invalid input";break;case T.invalid_intersection_types:t="Intersection results could not be merged";break;case T.not_multiple_of:t=`Number must be a multiple of ${r.multipleOf}`;break;case T.not_finite:t="Number must be finite";break;default:t=e.defaultError,G.assertNever(r)}return{message:t}},et=Ld;var va=et;function zd(r){va=r}function $r(){return va}var bn=r=>{let{data:e,path:t,errorMaps:n,issueData:s}=r,i=[...t,...s.path||[]],o={...s,path:i};if(s.message!==void 0)return{...s,path:i,message:s.message};let a="",c=n.filter(l=>!!l).slice().reverse();for(let l of c)a=l(o,{data:e,defaultError:a}).message;return{...s,path:i,message:a}},Ud=[];function A(r,e){let t=$r(),n=bn({issueData:e,data:r.data,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,t,t===et?void 0:et].filter(s=>!!s)});r.common.issues.push(n)}var ue=class r{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,t){let n=[];for(let s of t){if(s.status==="aborted")return M;s.status==="dirty"&&e.dirty(),n.push(s.value)}return{status:e.value,value:n}}static async mergeObjectAsync(e,t){let n=[];for(let s of t){let i=await s.key,o=await s.value;n.push({key:i,value:o})}return r.mergeObjectSync(e,n)}static mergeObjectSync(e,t){let n={};for(let s of t){let{key:i,value:o}=s;if(i.status==="aborted"||o.status==="aborted")return M;i.status==="dirty"&&e.dirty(),o.status==="dirty"&&e.dirty(),i.value!=="__proto__"&&(typeof o.value<"u"||s.alwaysSet)&&(n[i.value]=o.value)}return{status:e.value,value:n}}},M=Object.freeze({status:"aborted"}),Ot=r=>({status:"dirty",value:r}),he=r=>({status:"valid",value:r}),es=r=>r.status==="aborted",ts=r=>r.status==="dirty",yt=r=>r.status==="valid",Pr=r=>typeof Promise<"u"&&r instanceof Promise;var P;(function(r){r.errToObj=e=>typeof e=="string"?{message:e}:e||{},r.toString=e=>typeof e=="string"?e:e?.message})(P||(P={}));var Ae=class{constructor(e,t,n,s){this._cachedPath=[],this.parent=e,this.data=t,this._path=n,this._key=s}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},ba=(r,e)=>{if(yt(e))return{success:!0,data:e.value};if(!r.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let t=new ge(r.common.issues);return this._error=t,this._error}}};function q(r){if(!r)return{};let{errorMap:e,invalid_type_error:t,required_error:n,description:s}=r;if(e&&(t||n))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:s}:{errorMap:(o,a)=>{let{message:c}=r;return o.code==="invalid_enum_value"?{message:c??a.defaultError}:typeof a.data>"u"?{message:c??n??a.defaultError}:o.code!=="invalid_type"?{message:a.defaultError}:{message:c??t??a.defaultError}},description:s}}var K=class{get description(){return this._def.description}_getType(e){return Fe(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:Fe(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new ue,ctx:{common:e.parent.common,data:e.data,parsedType:Fe(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let t=this._parse(e);if(Pr(t))throw new Error("Synchronous parse encountered promise.");return t}_parseAsync(e){let t=this._parse(e);return Promise.resolve(t)}parse(e,t){let n=this.safeParse(e,t);if(n.success)return n.data;throw n.error}safeParse(e,t){let n={common:{issues:[],async:t?.async??!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Fe(e)},s=this._parseSync({data:e,path:n.path,parent:n});return ba(n,s)}"~validate"(e){let t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Fe(e)};if(!this["~standard"].async)try{let n=this._parseSync({data:e,path:[],parent:t});return yt(n)?{value:n.value}:{issues:t.common.issues}}catch(n){n?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then(n=>yt(n)?{value:n.value}:{issues:t.common.issues})}async parseAsync(e,t){let n=await this.safeParseAsync(e,t);if(n.success)return n.data;throw n.error}async safeParseAsync(e,t){let n={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Fe(e)},s=this._parse({data:e,path:n.path,parent:n}),i=await(Pr(s)?s:Promise.resolve(s));return ba(n,i)}refine(e,t){let n=s=>typeof t=="string"||typeof t>"u"?{message:t}:typeof t=="function"?t(s):t;return this._refinement((s,i)=>{let o=e(s),a=()=>i.addIssue({code:T.custom,...n(s)});return typeof Promise<"u"&&o instanceof Promise?o.then(c=>c?!0:(a(),!1)):o?!0:(a(),!1)})}refinement(e,t){return this._refinement((n,s)=>e(n)?!0:(s.addIssue(typeof t=="function"?t(n,s):t),!1))}_refinement(e){return new Re({schema:this,typeName:D.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:t=>this["~validate"](t)}}optional(){return Ie.create(this,this._def)}nullable(){return Ke.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return nt.create(this)}promise(){return bt.create(this,this._def)}or(e){return qt.create([this,e],this._def)}and(e){return Bt.create(this,e,this._def)}transform(e){return new Re({...q(this._def),schema:this,typeName:D.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let t=typeof e=="function"?e:()=>e;return new Ht({...q(this._def),innerType:this,defaultValue:t,typeName:D.ZodDefault})}brand(){return new wn({typeName:D.ZodBranded,type:this,...q(this._def)})}catch(e){let t=typeof e=="function"?e:()=>e;return new Gt({...q(this._def),innerType:this,catchValue:t,typeName:D.ZodCatch})}describe(e){let t=this.constructor;return new t({...this._def,description:e})}pipe(e){return kn.create(this,e)}readonly(){return Wt.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},qd=/^c[^\s-]{8,}$/i,Bd=/^[0-9a-z]+$/,Fd=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Zd=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,Kd=/^[a-z0-9_-]{21}$/i,Vd=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Hd=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,Gd=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,Wd="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",ki,Jd=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,Yd=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,Xd=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,Qd=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,eh=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,th=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,ka="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",rh=new RegExp(`^${ka}$`);function Sa(r){let e="[0-5]\\d";r.precision?e=`${e}\\.\\d{${r.precision}}`:r.precision==null&&(e=`${e}(\\.\\d+)?`);let t=r.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${t}`}function nh(r){return new RegExp(`^${Sa(r)}$`)}function Ta(r){let e=`${ka}T${Sa(r)}`,t=[];return t.push(r.local?"Z?":"Z"),r.offset&&t.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${t.join("|")})`,new RegExp(`^${e}$`)}function sh(r,e){return!!((e==="v4"||!e)&&Jd.test(r)||(e==="v6"||!e)&&Xd.test(r))}function ih(r,e){if(!Vd.test(r))return!1;try{let[t]=r.split(".");if(!t)return!1;let n=t.replace(/-/g,"+").replace(/_/g,"/").padEnd(t.length+(4-t.length%4)%4,"="),s=JSON.parse(atob(n));return!(typeof s!="object"||s===null||"typ"in s&&s?.typ!=="JWT"||!s.alg||e&&s.alg!==e)}catch{return!1}}function oh(r,e){return!!((e==="v4"||!e)&&Yd.test(r)||(e==="v6"||!e)&&Qd.test(r))}var _t=class r extends K{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==R.string){let i=this._getOrReturnCtx(e);return A(i,{code:T.invalid_type,expected:R.string,received:i.parsedType}),M}let n=new ue,s;for(let i of this._def.checks)if(i.kind==="min")e.data.length<i.value&&(s=this._getOrReturnCtx(e,s),A(s,{code:T.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),n.dirty());else if(i.kind==="max")e.data.length>i.value&&(s=this._getOrReturnCtx(e,s),A(s,{code:T.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),n.dirty());else if(i.kind==="length"){let o=e.data.length>i.value,a=e.data.length<i.value;(o||a)&&(s=this._getOrReturnCtx(e,s),o?A(s,{code:T.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}):a&&A(s,{code:T.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}),n.dirty())}else if(i.kind==="email")Gd.test(e.data)||(s=this._getOrReturnCtx(e,s),A(s,{validation:"email",code:T.invalid_string,message:i.message}),n.dirty());else if(i.kind==="emoji")ki||(ki=new RegExp(Wd,"u")),ki.test(e.data)||(s=this._getOrReturnCtx(e,s),A(s,{validation:"emoji",code:T.invalid_string,message:i.message}),n.dirty());else if(i.kind==="uuid")Zd.test(e.data)||(s=this._getOrReturnCtx(e,s),A(s,{validation:"uuid",code:T.invalid_string,message:i.message}),n.dirty());else if(i.kind==="nanoid")Kd.test(e.data)||(s=this._getOrReturnCtx(e,s),A(s,{validation:"nanoid",code:T.invalid_string,message:i.message}),n.dirty());else if(i.kind==="cuid")qd.test(e.data)||(s=this._getOrReturnCtx(e,s),A(s,{validation:"cuid",code:T.invalid_string,message:i.message}),n.dirty());else if(i.kind==="cuid2")Bd.test(e.data)||(s=this._getOrReturnCtx(e,s),A(s,{validation:"cuid2",code:T.invalid_string,message:i.message}),n.dirty());else if(i.kind==="ulid")Fd.test(e.data)||(s=this._getOrReturnCtx(e,s),A(s,{validation:"ulid",code:T.invalid_string,message:i.message}),n.dirty());else if(i.kind==="url")try{new URL(e.data)}catch{s=this._getOrReturnCtx(e,s),A(s,{validation:"url",code:T.invalid_string,message:i.message}),n.dirty()}else i.kind==="regex"?(i.regex.lastIndex=0,i.regex.test(e.data)||(s=this._getOrReturnCtx(e,s),A(s,{validation:"regex",code:T.invalid_string,message:i.message}),n.dirty())):i.kind==="trim"?e.data=e.data.trim():i.kind==="includes"?e.data.includes(i.value,i.position)||(s=this._getOrReturnCtx(e,s),A(s,{code:T.invalid_string,validation:{includes:i.value,position:i.position},message:i.message}),n.dirty()):i.kind==="toLowerCase"?e.data=e.data.toLowerCase():i.kind==="toUpperCase"?e.data=e.data.toUpperCase():i.kind==="startsWith"?e.data.startsWith(i.value)||(s=this._getOrReturnCtx(e,s),A(s,{code:T.invalid_string,validation:{startsWith:i.value},message:i.message}),n.dirty()):i.kind==="endsWith"?e.data.endsWith(i.value)||(s=this._getOrReturnCtx(e,s),A(s,{code:T.invalid_string,validation:{endsWith:i.value},message:i.message}),n.dirty()):i.kind==="datetime"?Ta(i).test(e.data)||(s=this._getOrReturnCtx(e,s),A(s,{code:T.invalid_string,validation:"datetime",message:i.message}),n.dirty()):i.kind==="date"?rh.test(e.data)||(s=this._getOrReturnCtx(e,s),A(s,{code:T.invalid_string,validation:"date",message:i.message}),n.dirty()):i.kind==="time"?nh(i).test(e.data)||(s=this._getOrReturnCtx(e,s),A(s,{code:T.invalid_string,validation:"time",message:i.message}),n.dirty()):i.kind==="duration"?Hd.test(e.data)||(s=this._getOrReturnCtx(e,s),A(s,{validation:"duration",code:T.invalid_string,message:i.message}),n.dirty()):i.kind==="ip"?sh(e.data,i.version)||(s=this._getOrReturnCtx(e,s),A(s,{validation:"ip",code:T.invalid_string,message:i.message}),n.dirty()):i.kind==="jwt"?ih(e.data,i.alg)||(s=this._getOrReturnCtx(e,s),A(s,{validation:"jwt",code:T.invalid_string,message:i.message}),n.dirty()):i.kind==="cidr"?oh(e.data,i.version)||(s=this._getOrReturnCtx(e,s),A(s,{validation:"cidr",code:T.invalid_string,message:i.message}),n.dirty()):i.kind==="base64"?eh.test(e.data)||(s=this._getOrReturnCtx(e,s),A(s,{validation:"base64",code:T.invalid_string,message:i.message}),n.dirty()):i.kind==="base64url"?th.test(e.data)||(s=this._getOrReturnCtx(e,s),A(s,{validation:"base64url",code:T.invalid_string,message:i.message}),n.dirty()):G.assertNever(i);return{status:n.value,value:e.data}}_regex(e,t,n){return this.refinement(s=>e.test(s),{validation:t,code:T.invalid_string,...P.errToObj(n)})}_addCheck(e){return new r({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...P.errToObj(e)})}url(e){return this._addCheck({kind:"url",...P.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...P.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...P.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...P.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...P.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...P.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...P.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...P.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...P.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...P.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...P.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...P.errToObj(e)})}datetime(e){return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...P.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof e?.precision>"u"?null:e?.precision,...P.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...P.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...P.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t?.position,...P.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...P.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...P.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...P.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...P.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...P.errToObj(t)})}nonempty(e){return this.min(1,P.errToObj(e))}trim(){return new r({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new r({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new r({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}};_t.create=r=>new _t({checks:[],typeName:D.ZodString,coerce:r?.coerce??!1,...q(r)});function ah(r,e){let t=(r.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,s=t>n?t:n,i=Number.parseInt(r.toFixed(s).replace(".","")),o=Number.parseInt(e.toFixed(s).replace(".",""));return i%o/10**s}var Nt=class r extends K{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==R.number){let i=this._getOrReturnCtx(e);return A(i,{code:T.invalid_type,expected:R.number,received:i.parsedType}),M}let n,s=new ue;for(let i of this._def.checks)i.kind==="int"?G.isInteger(e.data)||(n=this._getOrReturnCtx(e,n),A(n,{code:T.invalid_type,expected:"integer",received:"float",message:i.message}),s.dirty()):i.kind==="min"?(i.inclusive?e.data<i.value:e.data<=i.value)&&(n=this._getOrReturnCtx(e,n),A(n,{code:T.too_small,minimum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),s.dirty()):i.kind==="max"?(i.inclusive?e.data>i.value:e.data>=i.value)&&(n=this._getOrReturnCtx(e,n),A(n,{code:T.too_big,maximum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),s.dirty()):i.kind==="multipleOf"?ah(e.data,i.value)!==0&&(n=this._getOrReturnCtx(e,n),A(n,{code:T.not_multiple_of,multipleOf:i.value,message:i.message}),s.dirty()):i.kind==="finite"?Number.isFinite(e.data)||(n=this._getOrReturnCtx(e,n),A(n,{code:T.not_finite,message:i.message}),s.dirty()):G.assertNever(i);return{status:s.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,P.toString(t))}gt(e,t){return this.setLimit("min",e,!1,P.toString(t))}lte(e,t){return this.setLimit("max",e,!0,P.toString(t))}lt(e,t){return this.setLimit("max",e,!1,P.toString(t))}setLimit(e,t,n,s){return new r({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:n,message:P.toString(s)}]})}_addCheck(e){return new r({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:P.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:P.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:P.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:P.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:P.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:P.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:P.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:P.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:P.toString(e)})}get minValue(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&G.isInteger(e.value))}get isFinite(){let e=null,t=null;for(let n of this._def.checks){if(n.kind==="finite"||n.kind==="int"||n.kind==="multipleOf")return!0;n.kind==="min"?(t===null||n.value>t)&&(t=n.value):n.kind==="max"&&(e===null||n.value<e)&&(e=n.value)}return Number.isFinite(t)&&Number.isFinite(e)}};Nt.create=r=>new Nt({checks:[],typeName:D.ZodNumber,coerce:r?.coerce||!1,...q(r)});var Mt=class r extends K{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==R.bigint)return this._getInvalidInput(e);let n,s=new ue;for(let i of this._def.checks)i.kind==="min"?(i.inclusive?e.data<i.value:e.data<=i.value)&&(n=this._getOrReturnCtx(e,n),A(n,{code:T.too_small,type:"bigint",minimum:i.value,inclusive:i.inclusive,message:i.message}),s.dirty()):i.kind==="max"?(i.inclusive?e.data>i.value:e.data>=i.value)&&(n=this._getOrReturnCtx(e,n),A(n,{code:T.too_big,type:"bigint",maximum:i.value,inclusive:i.inclusive,message:i.message}),s.dirty()):i.kind==="multipleOf"?e.data%i.value!==BigInt(0)&&(n=this._getOrReturnCtx(e,n),A(n,{code:T.not_multiple_of,multipleOf:i.value,message:i.message}),s.dirty()):G.assertNever(i);return{status:s.value,value:e.data}}_getInvalidInput(e){let t=this._getOrReturnCtx(e);return A(t,{code:T.invalid_type,expected:R.bigint,received:t.parsedType}),M}gte(e,t){return this.setLimit("min",e,!0,P.toString(t))}gt(e,t){return this.setLimit("min",e,!1,P.toString(t))}lte(e,t){return this.setLimit("max",e,!0,P.toString(t))}lt(e,t){return this.setLimit("max",e,!1,P.toString(t))}setLimit(e,t,n,s){return new r({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:n,message:P.toString(s)}]})}_addCheck(e){return new r({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:P.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:P.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:P.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:P.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:P.toString(t)})}get minValue(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}};Mt.create=r=>new Mt({checks:[],typeName:D.ZodBigInt,coerce:r?.coerce??!1,...q(r)});var Dt=class extends K{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==R.boolean){let n=this._getOrReturnCtx(e);return A(n,{code:T.invalid_type,expected:R.boolean,received:n.parsedType}),M}return he(e.data)}};Dt.create=r=>new Dt({typeName:D.ZodBoolean,coerce:r?.coerce||!1,...q(r)});var Lt=class r extends K{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==R.date){let i=this._getOrReturnCtx(e);return A(i,{code:T.invalid_type,expected:R.date,received:i.parsedType}),M}if(Number.isNaN(e.data.getTime())){let i=this._getOrReturnCtx(e);return A(i,{code:T.invalid_date}),M}let n=new ue,s;for(let i of this._def.checks)i.kind==="min"?e.data.getTime()<i.value&&(s=this._getOrReturnCtx(e,s),A(s,{code:T.too_small,message:i.message,inclusive:!0,exact:!1,minimum:i.value,type:"date"}),n.dirty()):i.kind==="max"?e.data.getTime()>i.value&&(s=this._getOrReturnCtx(e,s),A(s,{code:T.too_big,message:i.message,inclusive:!0,exact:!1,maximum:i.value,type:"date"}),n.dirty()):G.assertNever(i);return{status:n.value,value:new Date(e.data.getTime())}}_addCheck(e){return new r({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:P.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:P.toString(t)})}get minDate(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e!=null?new Date(e):null}};Lt.create=r=>new Lt({checks:[],coerce:r?.coerce||!1,typeName:D.ZodDate,...q(r)});var Or=class extends K{_parse(e){if(this._getType(e)!==R.symbol){let n=this._getOrReturnCtx(e);return A(n,{code:T.invalid_type,expected:R.symbol,received:n.parsedType}),M}return he(e.data)}};Or.create=r=>new Or({typeName:D.ZodSymbol,...q(r)});var zt=class extends K{_parse(e){if(this._getType(e)!==R.undefined){let n=this._getOrReturnCtx(e);return A(n,{code:T.invalid_type,expected:R.undefined,received:n.parsedType}),M}return he(e.data)}};zt.create=r=>new zt({typeName:D.ZodUndefined,...q(r)});var Ut=class extends K{_parse(e){if(this._getType(e)!==R.null){let n=this._getOrReturnCtx(e);return A(n,{code:T.invalid_type,expected:R.null,received:n.parsedType}),M}return he(e.data)}};Ut.create=r=>new Ut({typeName:D.ZodNull,...q(r)});var vt=class extends K{constructor(){super(...arguments),this._any=!0}_parse(e){return he(e.data)}};vt.create=r=>new vt({typeName:D.ZodAny,...q(r)});var rt=class extends K{constructor(){super(...arguments),this._unknown=!0}_parse(e){return he(e.data)}};rt.create=r=>new rt({typeName:D.ZodUnknown,...q(r)});var De=class extends K{_parse(e){let t=this._getOrReturnCtx(e);return A(t,{code:T.invalid_type,expected:R.never,received:t.parsedType}),M}};De.create=r=>new De({typeName:D.ZodNever,...q(r)});var Nr=class extends K{_parse(e){if(this._getType(e)!==R.undefined){let n=this._getOrReturnCtx(e);return A(n,{code:T.invalid_type,expected:R.void,received:n.parsedType}),M}return he(e.data)}};Nr.create=r=>new Nr({typeName:D.ZodVoid,...q(r)});var nt=class r extends K{_parse(e){let{ctx:t,status:n}=this._processInputParams(e),s=this._def;if(t.parsedType!==R.array)return A(t,{code:T.invalid_type,expected:R.array,received:t.parsedType}),M;if(s.exactLength!==null){let o=t.data.length>s.exactLength.value,a=t.data.length<s.exactLength.value;(o||a)&&(A(t,{code:o?T.too_big:T.too_small,minimum:a?s.exactLength.value:void 0,maximum:o?s.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:s.exactLength.message}),n.dirty())}if(s.minLength!==null&&t.data.length<s.minLength.value&&(A(t,{code:T.too_small,minimum:s.minLength.value,type:"array",inclusive:!0,exact:!1,message:s.minLength.message}),n.dirty()),s.maxLength!==null&&t.data.length>s.maxLength.value&&(A(t,{code:T.too_big,maximum:s.maxLength.value,type:"array",inclusive:!0,exact:!1,message:s.maxLength.message}),n.dirty()),t.common.async)return Promise.all([...t.data].map((o,a)=>s.type._parseAsync(new Ae(t,o,t.path,a)))).then(o=>ue.mergeArray(n,o));let i=[...t.data].map((o,a)=>s.type._parseSync(new Ae(t,o,t.path,a)));return ue.mergeArray(n,i)}get element(){return this._def.type}min(e,t){return new r({...this._def,minLength:{value:e,message:P.toString(t)}})}max(e,t){return new r({...this._def,maxLength:{value:e,message:P.toString(t)}})}length(e,t){return new r({...this._def,exactLength:{value:e,message:P.toString(t)}})}nonempty(e){return this.min(1,e)}};nt.create=(r,e)=>new nt({type:r,minLength:null,maxLength:null,exactLength:null,typeName:D.ZodArray,...q(e)});function jr(r){if(r instanceof ye){let e={};for(let t in r.shape){let n=r.shape[t];e[t]=Ie.create(jr(n))}return new ye({...r._def,shape:()=>e})}else return r instanceof nt?new nt({...r._def,type:jr(r.element)}):r instanceof Ie?Ie.create(jr(r.unwrap())):r instanceof Ke?Ke.create(jr(r.unwrap())):r instanceof Ze?Ze.create(r.items.map(e=>jr(e))):r}var ye=class r extends K{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape(),t=G.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==R.object){let l=this._getOrReturnCtx(e);return A(l,{code:T.invalid_type,expected:R.object,received:l.parsedType}),M}let{status:n,ctx:s}=this._processInputParams(e),{shape:i,keys:o}=this._getCached(),a=[];if(!(this._def.catchall instanceof De&&this._def.unknownKeys==="strip"))for(let l in s.data)o.includes(l)||a.push(l);let c=[];for(let l of o){let d=i[l],p=s.data[l];c.push({key:{status:"valid",value:l},value:d._parse(new Ae(s,p,s.path,l)),alwaysSet:l in s.data})}if(this._def.catchall instanceof De){let l=this._def.unknownKeys;if(l==="passthrough")for(let d of a)c.push({key:{status:"valid",value:d},value:{status:"valid",value:s.data[d]}});else if(l==="strict")a.length>0&&(A(s,{code:T.unrecognized_keys,keys:a}),n.dirty());else if(l!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let l=this._def.catchall;for(let d of a){let p=s.data[d];c.push({key:{status:"valid",value:d},value:l._parse(new Ae(s,p,s.path,d)),alwaysSet:d in s.data})}}return s.common.async?Promise.resolve().then(async()=>{let l=[];for(let d of c){let p=await d.key,v=await d.value;l.push({key:p,value:v,alwaysSet:d.alwaysSet})}return l}).then(l=>ue.mergeObjectSync(n,l)):ue.mergeObjectSync(n,c)}get shape(){return this._def.shape()}strict(e){return P.errToObj,new r({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(t,n)=>{let s=this._def.errorMap?.(t,n).message??n.defaultError;return t.code==="unrecognized_keys"?{message:P.errToObj(e).message??s}:{message:s}}}:{}})}strip(){return new r({...this._def,unknownKeys:"strip"})}passthrough(){return new r({...this._def,unknownKeys:"passthrough"})}extend(e){return new r({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new r({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:D.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new r({...this._def,catchall:e})}pick(e){let t={};for(let n of G.objectKeys(e))e[n]&&this.shape[n]&&(t[n]=this.shape[n]);return new r({...this._def,shape:()=>t})}omit(e){let t={};for(let n of G.objectKeys(this.shape))e[n]||(t[n]=this.shape[n]);return new r({...this._def,shape:()=>t})}deepPartial(){return jr(this)}partial(e){let t={};for(let n of G.objectKeys(this.shape)){let s=this.shape[n];e&&!e[n]?t[n]=s:t[n]=s.optional()}return new r({...this._def,shape:()=>t})}required(e){let t={};for(let n of G.objectKeys(this.shape))if(e&&!e[n])t[n]=this.shape[n];else{let i=this.shape[n];for(;i instanceof Ie;)i=i._def.innerType;t[n]=i}return new r({...this._def,shape:()=>t})}keyof(){return xa(G.objectKeys(this.shape))}};ye.create=(r,e)=>new ye({shape:()=>r,unknownKeys:"strip",catchall:De.create(),typeName:D.ZodObject,...q(e)});ye.strictCreate=(r,e)=>new ye({shape:()=>r,unknownKeys:"strict",catchall:De.create(),typeName:D.ZodObject,...q(e)});ye.lazycreate=(r,e)=>new ye({shape:r,unknownKeys:"strip",catchall:De.create(),typeName:D.ZodObject,...q(e)});var qt=class extends K{_parse(e){let{ctx:t}=this._processInputParams(e),n=this._def.options;function s(i){for(let a of i)if(a.result.status==="valid")return a.result;for(let a of i)if(a.result.status==="dirty")return t.common.issues.push(...a.ctx.common.issues),a.result;let o=i.map(a=>new ge(a.ctx.common.issues));return A(t,{code:T.invalid_union,unionErrors:o}),M}if(t.common.async)return Promise.all(n.map(async i=>{let o={...t,common:{...t.common,issues:[]},parent:null};return{result:await i._parseAsync({data:t.data,path:t.path,parent:o}),ctx:o}})).then(s);{let i,o=[];for(let c of n){let l={...t,common:{...t.common,issues:[]},parent:null},d=c._parseSync({data:t.data,path:t.path,parent:l});if(d.status==="valid")return d;d.status==="dirty"&&!i&&(i={result:d,ctx:l}),l.common.issues.length&&o.push(l.common.issues)}if(i)return t.common.issues.push(...i.ctx.common.issues),i.result;let a=o.map(c=>new ge(c));return A(t,{code:T.invalid_union,unionErrors:a}),M}}get options(){return this._def.options}};qt.create=(r,e)=>new qt({options:r,typeName:D.ZodUnion,...q(e)});var tt=r=>r instanceof Ft?tt(r.schema):r instanceof Re?tt(r.innerType()):r instanceof Zt?[r.value]:r instanceof Kt?r.options:r instanceof Vt?G.objectValues(r.enum):r instanceof Ht?tt(r._def.innerType):r instanceof zt?[void 0]:r instanceof Ut?[null]:r instanceof Ie?[void 0,...tt(r.unwrap())]:r instanceof Ke?[null,...tt(r.unwrap())]:r instanceof wn||r instanceof Wt?tt(r.unwrap()):r instanceof Gt?tt(r._def.innerType):[],rs=class r extends K{_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==R.object)return A(t,{code:T.invalid_type,expected:R.object,received:t.parsedType}),M;let n=this.discriminator,s=t.data[n],i=this.optionsMap.get(s);return i?t.common.async?i._parseAsync({data:t.data,path:t.path,parent:t}):i._parseSync({data:t.data,path:t.path,parent:t}):(A(t,{code:T.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),M)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,t,n){let s=new Map;for(let i of t){let o=tt(i.shape[e]);if(!o.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let a of o){if(s.has(a))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(a)}`);s.set(a,i)}}return new r({typeName:D.ZodDiscriminatedUnion,discriminator:e,options:t,optionsMap:s,...q(n)})}};function Si(r,e){let t=Fe(r),n=Fe(e);if(r===e)return{valid:!0,data:r};if(t===R.object&&n===R.object){let s=G.objectKeys(e),i=G.objectKeys(r).filter(a=>s.indexOf(a)!==-1),o={...r,...e};for(let a of i){let c=Si(r[a],e[a]);if(!c.valid)return{valid:!1};o[a]=c.data}return{valid:!0,data:o}}else if(t===R.array&&n===R.array){if(r.length!==e.length)return{valid:!1};let s=[];for(let i=0;i<r.length;i++){let o=r[i],a=e[i],c=Si(o,a);if(!c.valid)return{valid:!1};s.push(c.data)}return{valid:!0,data:s}}else return t===R.date&&n===R.date&&+r==+e?{valid:!0,data:r}:{valid:!1}}var Bt=class extends K{_parse(e){let{status:t,ctx:n}=this._processInputParams(e),s=(i,o)=>{if(es(i)||es(o))return M;let a=Si(i.value,o.value);return a.valid?((ts(i)||ts(o))&&t.dirty(),{status:t.value,value:a.data}):(A(n,{code:T.invalid_intersection_types}),M)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([i,o])=>s(i,o)):s(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}};Bt.create=(r,e,t)=>new Bt({left:r,right:e,typeName:D.ZodIntersection,...q(t)});var Ze=class r extends K{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==R.array)return A(n,{code:T.invalid_type,expected:R.array,received:n.parsedType}),M;if(n.data.length<this._def.items.length)return A(n,{code:T.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),M;!this._def.rest&&n.data.length>this._def.items.length&&(A(n,{code:T.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());let i=[...n.data].map((o,a)=>{let c=this._def.items[a]||this._def.rest;return c?c._parse(new Ae(n,o,n.path,a)):null}).filter(o=>!!o);return n.common.async?Promise.all(i).then(o=>ue.mergeArray(t,o)):ue.mergeArray(t,i)}get items(){return this._def.items}rest(e){return new r({...this._def,rest:e})}};Ze.create=(r,e)=>{if(!Array.isArray(r))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Ze({items:r,typeName:D.ZodTuple,rest:null,...q(e)})};var ns=class r extends K{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==R.object)return A(n,{code:T.invalid_type,expected:R.object,received:n.parsedType}),M;let s=[],i=this._def.keyType,o=this._def.valueType;for(let a in n.data)s.push({key:i._parse(new Ae(n,a,n.path,a)),value:o._parse(new Ae(n,n.data[a],n.path,a)),alwaysSet:a in n.data});return n.common.async?ue.mergeObjectAsync(t,s):ue.mergeObjectSync(t,s)}get element(){return this._def.valueType}static create(e,t,n){return t instanceof K?new r({keyType:e,valueType:t,typeName:D.ZodRecord,...q(n)}):new r({keyType:_t.create(),valueType:e,typeName:D.ZodRecord,...q(t)})}},Mr=class extends K{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==R.map)return A(n,{code:T.invalid_type,expected:R.map,received:n.parsedType}),M;let s=this._def.keyType,i=this._def.valueType,o=[...n.data.entries()].map(([a,c],l)=>({key:s._parse(new Ae(n,a,n.path,[l,"key"])),value:i._parse(new Ae(n,c,n.path,[l,"value"]))}));if(n.common.async){let a=new Map;return Promise.resolve().then(async()=>{for(let c of o){let l=await c.key,d=await c.value;if(l.status==="aborted"||d.status==="aborted")return M;(l.status==="dirty"||d.status==="dirty")&&t.dirty(),a.set(l.value,d.value)}return{status:t.value,value:a}})}else{let a=new Map;for(let c of o){let l=c.key,d=c.value;if(l.status==="aborted"||d.status==="aborted")return M;(l.status==="dirty"||d.status==="dirty")&&t.dirty(),a.set(l.value,d.value)}return{status:t.value,value:a}}}};Mr.create=(r,e,t)=>new Mr({valueType:e,keyType:r,typeName:D.ZodMap,...q(t)});var Dr=class r extends K{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==R.set)return A(n,{code:T.invalid_type,expected:R.set,received:n.parsedType}),M;let s=this._def;s.minSize!==null&&n.data.size<s.minSize.value&&(A(n,{code:T.too_small,minimum:s.minSize.value,type:"set",inclusive:!0,exact:!1,message:s.minSize.message}),t.dirty()),s.maxSize!==null&&n.data.size>s.maxSize.value&&(A(n,{code:T.too_big,maximum:s.maxSize.value,type:"set",inclusive:!0,exact:!1,message:s.maxSize.message}),t.dirty());let i=this._def.valueType;function o(c){let l=new Set;for(let d of c){if(d.status==="aborted")return M;d.status==="dirty"&&t.dirty(),l.add(d.value)}return{status:t.value,value:l}}let a=[...n.data.values()].map((c,l)=>i._parse(new Ae(n,c,n.path,l)));return n.common.async?Promise.all(a).then(c=>o(c)):o(a)}min(e,t){return new r({...this._def,minSize:{value:e,message:P.toString(t)}})}max(e,t){return new r({...this._def,maxSize:{value:e,message:P.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}};Dr.create=(r,e)=>new Dr({valueType:r,minSize:null,maxSize:null,typeName:D.ZodSet,...q(e)});var ss=class r extends K{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==R.function)return A(t,{code:T.invalid_type,expected:R.function,received:t.parsedType}),M;function n(a,c){return bn({data:a,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,$r(),et].filter(l=>!!l),issueData:{code:T.invalid_arguments,argumentsError:c}})}function s(a,c){return bn({data:a,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,$r(),et].filter(l=>!!l),issueData:{code:T.invalid_return_type,returnTypeError:c}})}let i={errorMap:t.common.contextualErrorMap},o=t.data;if(this._def.returns instanceof bt){let a=this;return he(async function(...c){let l=new ge([]),d=await a._def.args.parseAsync(c,i).catch(S=>{throw l.addIssue(n(c,S)),l}),p=await Reflect.apply(o,this,d);return await a._def.returns._def.type.parseAsync(p,i).catch(S=>{throw l.addIssue(s(p,S)),l})})}else{let a=this;return he(function(...c){let l=a._def.args.safeParse(c,i);if(!l.success)throw new ge([n(c,l.error)]);let d=Reflect.apply(o,this,l.data),p=a._def.returns.safeParse(d,i);if(!p.success)throw new ge([s(d,p.error)]);return p.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new r({...this._def,args:Ze.create(e).rest(rt.create())})}returns(e){return new r({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,t,n){return new r({args:e||Ze.create([]).rest(rt.create()),returns:t||rt.create(),typeName:D.ZodFunction,...q(n)})}},Ft=class extends K{get schema(){return this._def.getter()}_parse(e){let{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}};Ft.create=(r,e)=>new Ft({getter:r,typeName:D.ZodLazy,...q(e)});var Zt=class extends K{_parse(e){if(e.data!==this._def.value){let t=this._getOrReturnCtx(e);return A(t,{received:t.data,code:T.invalid_literal,expected:this._def.value}),M}return{status:"valid",value:e.data}}get value(){return this._def.value}};Zt.create=(r,e)=>new Zt({value:r,typeName:D.ZodLiteral,...q(e)});function xa(r,e){return new Kt({values:r,typeName:D.ZodEnum,...q(e)})}var Kt=class r extends K{_parse(e){if(typeof e.data!="string"){let t=this._getOrReturnCtx(e),n=this._def.values;return A(t,{expected:G.joinValues(n),received:t.parsedType,code:T.invalid_type}),M}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){let t=this._getOrReturnCtx(e),n=this._def.values;return A(t,{received:t.data,code:T.invalid_enum_value,options:n}),M}return he(e.data)}get options(){return this._def.values}get enum(){let e={};for(let t of this._def.values)e[t]=t;return e}get Values(){let e={};for(let t of this._def.values)e[t]=t;return e}get Enum(){let e={};for(let t of this._def.values)e[t]=t;return e}extract(e,t=this._def){return r.create(e,{...this._def,...t})}exclude(e,t=this._def){return r.create(this.options.filter(n=>!e.includes(n)),{...this._def,...t})}};Kt.create=xa;var Vt=class extends K{_parse(e){let t=G.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==R.string&&n.parsedType!==R.number){let s=G.objectValues(t);return A(n,{expected:G.joinValues(s),received:n.parsedType,code:T.invalid_type}),M}if(this._cache||(this._cache=new Set(G.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let s=G.objectValues(t);return A(n,{received:n.data,code:T.invalid_enum_value,options:s}),M}return he(e.data)}get enum(){return this._def.values}};Vt.create=(r,e)=>new Vt({values:r,typeName:D.ZodNativeEnum,...q(e)});var bt=class extends K{unwrap(){return this._def.type}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==R.promise&&t.common.async===!1)return A(t,{code:T.invalid_type,expected:R.promise,received:t.parsedType}),M;let n=t.parsedType===R.promise?t.data:Promise.resolve(t.data);return he(n.then(s=>this._def.type.parseAsync(s,{path:t.path,errorMap:t.common.contextualErrorMap})))}};bt.create=(r,e)=>new bt({type:r,typeName:D.ZodPromise,...q(e)});var Re=class extends K{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===D.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:t,ctx:n}=this._processInputParams(e),s=this._def.effect||null,i={addIssue:o=>{A(n,o),o.fatal?t.abort():t.dirty()},get path(){return n.path}};if(i.addIssue=i.addIssue.bind(i),s.type==="preprocess"){let o=s.transform(n.data,i);if(n.common.async)return Promise.resolve(o).then(async a=>{if(t.value==="aborted")return M;let c=await this._def.schema._parseAsync({data:a,path:n.path,parent:n});return c.status==="aborted"?M:c.status==="dirty"?Ot(c.value):t.value==="dirty"?Ot(c.value):c});{if(t.value==="aborted")return M;let a=this._def.schema._parseSync({data:o,path:n.path,parent:n});return a.status==="aborted"?M:a.status==="dirty"?Ot(a.value):t.value==="dirty"?Ot(a.value):a}}if(s.type==="refinement"){let o=a=>{let c=s.refinement(a,i);if(n.common.async)return Promise.resolve(c);if(c instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return a};if(n.common.async===!1){let a=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return a.status==="aborted"?M:(a.status==="dirty"&&t.dirty(),o(a.value),{status:t.value,value:a.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(a=>a.status==="aborted"?M:(a.status==="dirty"&&t.dirty(),o(a.value).then(()=>({status:t.value,value:a.value}))))}if(s.type==="transform")if(n.common.async===!1){let o=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!yt(o))return M;let a=s.transform(o.value,i);if(a instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:t.value,value:a}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(o=>yt(o)?Promise.resolve(s.transform(o.value,i)).then(a=>({status:t.value,value:a})):M);G.assertNever(s)}};Re.create=(r,e,t)=>new Re({schema:r,typeName:D.ZodEffects,effect:e,...q(t)});Re.createWithPreprocess=(r,e,t)=>new Re({schema:e,effect:{type:"preprocess",transform:r},typeName:D.ZodEffects,...q(t)});var Ie=class extends K{_parse(e){return this._getType(e)===R.undefined?he(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Ie.create=(r,e)=>new Ie({innerType:r,typeName:D.ZodOptional,...q(e)});var Ke=class extends K{_parse(e){return this._getType(e)===R.null?he(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Ke.create=(r,e)=>new Ke({innerType:r,typeName:D.ZodNullable,...q(e)});var Ht=class extends K{_parse(e){let{ctx:t}=this._processInputParams(e),n=t.data;return t.parsedType===R.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:t.path,parent:t})}removeDefault(){return this._def.innerType}};Ht.create=(r,e)=>new Ht({innerType:r,typeName:D.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...q(e)});var Gt=class extends K{_parse(e){let{ctx:t}=this._processInputParams(e),n={...t,common:{...t.common,issues:[]}},s=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return Pr(s)?s.then(i=>({status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new ge(n.common.issues)},input:n.data})})):{status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new ge(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};Gt.create=(r,e)=>new Gt({innerType:r,typeName:D.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...q(e)});var Lr=class extends K{_parse(e){if(this._getType(e)!==R.nan){let n=this._getOrReturnCtx(e);return A(n,{code:T.invalid_type,expected:R.nan,received:n.parsedType}),M}return{status:"valid",value:e.data}}};Lr.create=r=>new Lr({typeName:D.ZodNaN,...q(r)});var uh=Symbol("zod_brand"),wn=class extends K{_parse(e){let{ctx:t}=this._processInputParams(e),n=t.data;return this._def.type._parse({data:n,path:t.path,parent:t})}unwrap(){return this._def.type}},kn=class r extends K{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{let i=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return i.status==="aborted"?M:i.status==="dirty"?(t.dirty(),Ot(i.value)):this._def.out._parseAsync({data:i.value,path:n.path,parent:n})})();{let s=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return s.status==="aborted"?M:s.status==="dirty"?(t.dirty(),{status:"dirty",value:s.value}):this._def.out._parseSync({data:s.value,path:n.path,parent:n})}}static create(e,t){return new r({in:e,out:t,typeName:D.ZodPipeline})}},Wt=class extends K{_parse(e){let t=this._def.innerType._parse(e),n=s=>(yt(s)&&(s.value=Object.freeze(s.value)),s);return Pr(t)?t.then(s=>n(s)):n(t)}unwrap(){return this._def.innerType}};Wt.create=(r,e)=>new Wt({innerType:r,typeName:D.ZodReadonly,...q(e)});function wa(r,e){let t=typeof r=="function"?r(e):typeof r=="string"?{message:r}:r;return typeof t=="string"?{message:t}:t}function Ca(r,e={},t){return r?vt.create().superRefine((n,s)=>{let i=r(n);if(i instanceof Promise)return i.then(o=>{if(!o){let a=wa(e,n),c=a.fatal??t??!0;s.addIssue({code:"custom",...a,fatal:c})}});if(!i){let o=wa(e,n),a=o.fatal??t??!0;s.addIssue({code:"custom",...o,fatal:a})}}):vt.create()}var ch={object:ye.lazycreate},D;(function(r){r.ZodString="ZodString",r.ZodNumber="ZodNumber",r.ZodNaN="ZodNaN",r.ZodBigInt="ZodBigInt",r.ZodBoolean="ZodBoolean",r.ZodDate="ZodDate",r.ZodSymbol="ZodSymbol",r.ZodUndefined="ZodUndefined",r.ZodNull="ZodNull",r.ZodAny="ZodAny",r.ZodUnknown="ZodUnknown",r.ZodNever="ZodNever",r.ZodVoid="ZodVoid",r.ZodArray="ZodArray",r.ZodObject="ZodObject",r.ZodUnion="ZodUnion",r.ZodDiscriminatedUnion="ZodDiscriminatedUnion",r.ZodIntersection="ZodIntersection",r.ZodTuple="ZodTuple",r.ZodRecord="ZodRecord",r.ZodMap="ZodMap",r.ZodSet="ZodSet",r.ZodFunction="ZodFunction",r.ZodLazy="ZodLazy",r.ZodLiteral="ZodLiteral",r.ZodEnum="ZodEnum",r.ZodEffects="ZodEffects",r.ZodNativeEnum="ZodNativeEnum",r.ZodOptional="ZodOptional",r.ZodNullable="ZodNullable",r.ZodDefault="ZodDefault",r.ZodCatch="ZodCatch",r.ZodPromise="ZodPromise",r.ZodBranded="ZodBranded",r.ZodPipeline="ZodPipeline",r.ZodReadonly="ZodReadonly"})(D||(D={}));var lh=(r,e={message:`Input not instance of ${r.name}`})=>Ca(t=>t instanceof r,e),Ea=_t.create,Ia=Nt.create,dh=Lr.create,hh=Mt.create,Aa=Dt.create,fh=Lt.create,ph=Or.create,mh=zt.create,gh=Ut.create,yh=vt.create,_h=rt.create,vh=De.create,bh=Nr.create,wh=nt.create,kh=ye.create,Sh=ye.strictCreate,Th=qt.create,xh=rs.create,Ch=Bt.create,Eh=Ze.create,Ih=ns.create,Ah=Mr.create,Rh=Dr.create,$h=ss.create,Ph=Ft.create,jh=Zt.create,Oh=Kt.create,Nh=Vt.create,Mh=bt.create,Dh=Re.create,Lh=Ie.create,zh=Ke.create,Uh=Re.createWithPreprocess,qh=kn.create,Bh=()=>Ea().optional(),Fh=()=>Ia().optional(),Zh=()=>Aa().optional(),Kh={string:(r=>_t.create({...r,coerce:!0})),number:(r=>Nt.create({...r,coerce:!0})),boolean:(r=>Dt.create({...r,coerce:!0})),bigint:(r=>Mt.create({...r,coerce:!0})),date:(r=>Lt.create({...r,coerce:!0}))};var Vh=M;var Ra=k.object({baseUrl:k.string().url(),email:k.string().email(),apiToken:k.string().min(1)}),Ti=k.object({controlPlaneUrl:k.string().url(),runnerId:k.string().optional(),runnerToken:k.string().optional(),runnerName:k.string().default(is.default.hostname()),jira:Ra.optional(),repos:k.record(k.object({path:k.string(),jira:Ra.optional(),github:k.object({token:k.string().min(1),login:k.string().optional()}).optional()})).default({}),github:k.object({token:k.string().min(1),login:k.string().optional()}).optional(),githubUsers:k.record(k.object({token:k.string().min(1),login:k.string().optional()})).default({}),deploy:k.object({enabled:k.boolean().default(!1)}).default({enabled:!1}),environments:k.record(k.object({secrets:k.record(k.string()).default({})})).default({}),claudeProfiles:k.record(k.object({configDir:k.string()})).default({}),claudeBin:k.string().default("claude"),agents:k.record(k.object({bin:k.string()})).default({}),jiraUsers:k.record(k.object({email:k.string().email(),apiToken:k.string().min(1)})).default({}),auditSchedules:k.array(k.object({repoName:k.string(),role:k.enum(["security","testing"]),intervalHours:k.number().int().min(6).max(720)})).default([]),pollIntervalSeconds:k.number().int().min(10).max(600).default(30)});function ee(){let r=process.env.ALLWRIGHT_CONFIG_DIR??process.env.TICKETPILOT_CONFIG_DIR;if(r)return r;let e=os.default.join(is.default.homedir(),".config","allwright"),t=os.default.join(is.default.homedir(),".config","ticketpilot");return!st.default.existsSync(e)&&st.default.existsSync(t)?t:e}function wt(){return os.default.join(ee(),"runner.json")}function ce(){let r=wt();if(!st.default.existsSync(r))return null;let e=JSON.parse(st.default.readFileSync(r,"utf8"));return Ti.parse(e)}function ie(r){let e=ee();st.default.mkdirSync(e,{recursive:!0,mode:448});let t=wt(),n=t+".tmp";st.default.writeFileSync(n,JSON.stringify(r,null,2)+`
236
+ `+t)}function Ir(r,e,t,n,s,i){if(r.listenerCount("wsClientError")){let o=new Error(s);Error.captureStackTrace(o,Ir),r.emit("wsClientError",o,t,e)}else Hn(t,n,s,i)}});var dd={};Yn(dd,{buildSetupReport:()=>uy,claudeLoggedIn:()=>ld});function ld(r=ud.default.homedir()){if(jt.default.existsSync(Ar.default.join(r,".claude",".credentials.json")))return!0;try{return!!JSON.parse(jt.default.readFileSync(Ar.default.join(r,".claude.json"),"utf8")).oauthAccount}catch{return!1}}async function uy(r,e){let t=!1,n="";try{let{stdout:o}=await ay(r.claudeBin,["--version"],{timeout:1e4});t=!0,n=o.trim().slice(0,60)}catch{t=!1}let s=e.map(o=>{let a=r.repos[o];if(!a)return{repoName:o,mapped:!1,pathExists:!1,isGit:!1,claudeMd:!1,deployMd:!1,testMd:!1};let c=jt.default.existsSync(a.path);return{repoName:o,mapped:!0,pathExists:c,isGit:c&&jt.default.existsSync(Ar.default.join(a.path,".git")),claudeMd:c&&jt.default.existsSync(Ar.default.join(a.path,"CLAUDE.md")),deployMd:c&&jt.default.existsSync(Ar.default.join(a.path,"DEPLOY.md")),testMd:c&&jt.default.existsSync(Ar.default.join(a.path,"TEST.md"))}}),i=Object.values(r.repos).find(o=>o.github?.token);return{jiraConfigured:!!r.jira,jiraEmail:r.jira?.email??"",claude:{installed:t,version:n,loggedIn:ld()},githubTokenSet:!!(r.github?.token||i),githubLogin:r.github?.login??i?.github?.login??"",deploysEnabled:r.deploy.enabled,jiraUserCount:Object.keys(r.jiraUsers).length,repos:s}}var ad,jt,ud,Ar,cd,ay,hd=ii(()=>{"use strict";ad=require("node:child_process"),jt=$(require("node:fs"),1),ud=$(require("node:os"),1),Ar=$(require("node:path"),1),cd=require("node:util"),ay=(0,cd.promisify)(ad.execFile)});var yn=$(require("node:fs"),1),fd=$(require("node:os"),1),pd=$(require("node:path"),1),Wn=require("node:child_process"),Xo=require("node:crypto"),Rr=$(require("node:readline/promises"),1);var ya=$(ga(),1),{program:_y,createCommand:vy,createArgument:by,createOption:wy,CommanderError:ky,InvalidArgumentError:Sy,InvalidOptionArgumentError:Ty,Command:_a,Argument:xy,Option:Cy,Help:Ey}=ya.default;var st=$(require("node:fs"),1),is=$(require("node:os"),1),os=$(require("node:path"),1);var k={};Yn(k,{BRAND:()=>uh,DIRTY:()=>Ot,EMPTY_PATH:()=>Ud,INVALID:()=>M,NEVER:()=>Vh,OK:()=>he,ParseStatus:()=>ue,Schema:()=>K,ZodAny:()=>vt,ZodArray:()=>nt,ZodBigInt:()=>Mt,ZodBoolean:()=>Dt,ZodBranded:()=>wn,ZodCatch:()=>Gt,ZodDate:()=>Lt,ZodDefault:()=>Ht,ZodDiscriminatedUnion:()=>rs,ZodEffects:()=>Re,ZodEnum:()=>Kt,ZodError:()=>ge,ZodFirstPartyTypeKind:()=>D,ZodFunction:()=>ss,ZodIntersection:()=>Bt,ZodIssueCode:()=>T,ZodLazy:()=>Ft,ZodLiteral:()=>Zt,ZodMap:()=>Mr,ZodNaN:()=>Lr,ZodNativeEnum:()=>Vt,ZodNever:()=>De,ZodNull:()=>Ut,ZodNullable:()=>Ke,ZodNumber:()=>Nt,ZodObject:()=>ye,ZodOptional:()=>Ie,ZodParsedType:()=>R,ZodPipeline:()=>kn,ZodPromise:()=>bt,ZodReadonly:()=>Wt,ZodRecord:()=>ns,ZodSchema:()=>K,ZodSet:()=>Dr,ZodString:()=>_t,ZodSymbol:()=>Or,ZodTransformer:()=>Re,ZodTuple:()=>Ze,ZodType:()=>K,ZodUndefined:()=>zt,ZodUnion:()=>qt,ZodUnknown:()=>rt,ZodVoid:()=>Nr,addIssueToContext:()=>A,any:()=>yh,array:()=>wh,bigint:()=>hh,boolean:()=>Aa,coerce:()=>Kh,custom:()=>Ca,date:()=>fh,datetimeRegex:()=>Ta,defaultErrorMap:()=>et,discriminatedUnion:()=>xh,effect:()=>Dh,enum:()=>Oh,function:()=>$h,getErrorMap:()=>$r,getParsedType:()=>Fe,instanceof:()=>lh,intersection:()=>Ch,isAborted:()=>es,isAsync:()=>Pr,isDirty:()=>ts,isValid:()=>yt,late:()=>ch,lazy:()=>Ph,literal:()=>jh,makeIssue:()=>bn,map:()=>Ah,nan:()=>dh,nativeEnum:()=>Nh,never:()=>vh,null:()=>gh,nullable:()=>zh,number:()=>Ia,object:()=>kh,objectUtil:()=>wi,oboolean:()=>Zh,onumber:()=>Fh,optional:()=>Lh,ostring:()=>Bh,pipeline:()=>qh,preprocess:()=>Uh,promise:()=>Mh,quotelessJson:()=>Dd,record:()=>Ih,set:()=>Rh,setErrorMap:()=>zd,strictObject:()=>Sh,string:()=>Ea,symbol:()=>ph,transformer:()=>Dh,tuple:()=>Eh,undefined:()=>mh,union:()=>Th,unknown:()=>_h,util:()=>G,void:()=>bh});var G;(function(r){r.assertEqual=s=>{};function e(s){}r.assertIs=e;function t(s){throw new Error}r.assertNever=t,r.arrayToEnum=s=>{let i={};for(let o of s)i[o]=o;return i},r.getValidEnumValues=s=>{let i=r.objectKeys(s).filter(a=>typeof s[s[a]]!="number"),o={};for(let a of i)o[a]=s[a];return r.objectValues(o)},r.objectValues=s=>r.objectKeys(s).map(function(i){return s[i]}),r.objectKeys=typeof Object.keys=="function"?s=>Object.keys(s):s=>{let i=[];for(let o in s)Object.prototype.hasOwnProperty.call(s,o)&&i.push(o);return i},r.find=(s,i)=>{for(let o of s)if(i(o))return o},r.isInteger=typeof Number.isInteger=="function"?s=>Number.isInteger(s):s=>typeof s=="number"&&Number.isFinite(s)&&Math.floor(s)===s;function n(s,i=" | "){return s.map(o=>typeof o=="string"?`'${o}'`:o).join(i)}r.joinValues=n,r.jsonStringifyReplacer=(s,i)=>typeof i=="bigint"?i.toString():i})(G||(G={}));var wi;(function(r){r.mergeShapes=(e,t)=>({...e,...t})})(wi||(wi={}));var R=G.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Fe=r=>{switch(typeof r){case"undefined":return R.undefined;case"string":return R.string;case"number":return Number.isNaN(r)?R.nan:R.number;case"boolean":return R.boolean;case"function":return R.function;case"bigint":return R.bigint;case"symbol":return R.symbol;case"object":return Array.isArray(r)?R.array:r===null?R.null:r.then&&typeof r.then=="function"&&r.catch&&typeof r.catch=="function"?R.promise:typeof Map<"u"&&r instanceof Map?R.map:typeof Set<"u"&&r instanceof Set?R.set:typeof Date<"u"&&r instanceof Date?R.date:R.object;default:return R.unknown}};var T=G.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),Dd=r=>JSON.stringify(r,null,2).replace(/"([^"]+)":/g,"$1:"),ge=class r extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=n=>{this.issues=[...this.issues,n]},this.addIssues=(n=[])=>{this.issues=[...this.issues,...n]};let t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name="ZodError",this.issues=e}format(e){let t=e||function(i){return i.message},n={_errors:[]},s=i=>{for(let o of i.issues)if(o.code==="invalid_union")o.unionErrors.map(s);else if(o.code==="invalid_return_type")s(o.returnTypeError);else if(o.code==="invalid_arguments")s(o.argumentsError);else if(o.path.length===0)n._errors.push(t(o));else{let a=n,c=0;for(;c<o.path.length;){let l=o.path[c];c===o.path.length-1?(a[l]=a[l]||{_errors:[]},a[l]._errors.push(t(o))):a[l]=a[l]||{_errors:[]},a=a[l],c++}}};return s(this),n}static assert(e){if(!(e instanceof r))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,G.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=t=>t.message){let t={},n=[];for(let s of this.issues)if(s.path.length>0){let i=s.path[0];t[i]=t[i]||[],t[i].push(e(s))}else n.push(e(s));return{formErrors:n,fieldErrors:t}}get formErrors(){return this.flatten()}};ge.create=r=>new ge(r);var Ld=(r,e)=>{let t;switch(r.code){case T.invalid_type:r.received===R.undefined?t="Required":t=`Expected ${r.expected}, received ${r.received}`;break;case T.invalid_literal:t=`Invalid literal value, expected ${JSON.stringify(r.expected,G.jsonStringifyReplacer)}`;break;case T.unrecognized_keys:t=`Unrecognized key(s) in object: ${G.joinValues(r.keys,", ")}`;break;case T.invalid_union:t="Invalid input";break;case T.invalid_union_discriminator:t=`Invalid discriminator value. Expected ${G.joinValues(r.options)}`;break;case T.invalid_enum_value:t=`Invalid enum value. Expected ${G.joinValues(r.options)}, received '${r.received}'`;break;case T.invalid_arguments:t="Invalid function arguments";break;case T.invalid_return_type:t="Invalid function return type";break;case T.invalid_date:t="Invalid date";break;case T.invalid_string:typeof r.validation=="object"?"includes"in r.validation?(t=`Invalid input: must include "${r.validation.includes}"`,typeof r.validation.position=="number"&&(t=`${t} at one or more positions greater than or equal to ${r.validation.position}`)):"startsWith"in r.validation?t=`Invalid input: must start with "${r.validation.startsWith}"`:"endsWith"in r.validation?t=`Invalid input: must end with "${r.validation.endsWith}"`:G.assertNever(r.validation):r.validation!=="regex"?t=`Invalid ${r.validation}`:t="Invalid";break;case T.too_small:r.type==="array"?t=`Array must contain ${r.exact?"exactly":r.inclusive?"at least":"more than"} ${r.minimum} element(s)`:r.type==="string"?t=`String must contain ${r.exact?"exactly":r.inclusive?"at least":"over"} ${r.minimum} character(s)`:r.type==="number"?t=`Number must be ${r.exact?"exactly equal to ":r.inclusive?"greater than or equal to ":"greater than "}${r.minimum}`:r.type==="bigint"?t=`Number must be ${r.exact?"exactly equal to ":r.inclusive?"greater than or equal to ":"greater than "}${r.minimum}`:r.type==="date"?t=`Date must be ${r.exact?"exactly equal to ":r.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(r.minimum))}`:t="Invalid input";break;case T.too_big:r.type==="array"?t=`Array must contain ${r.exact?"exactly":r.inclusive?"at most":"less than"} ${r.maximum} element(s)`:r.type==="string"?t=`String must contain ${r.exact?"exactly":r.inclusive?"at most":"under"} ${r.maximum} character(s)`:r.type==="number"?t=`Number must be ${r.exact?"exactly":r.inclusive?"less than or equal to":"less than"} ${r.maximum}`:r.type==="bigint"?t=`BigInt must be ${r.exact?"exactly":r.inclusive?"less than or equal to":"less than"} ${r.maximum}`:r.type==="date"?t=`Date must be ${r.exact?"exactly":r.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(r.maximum))}`:t="Invalid input";break;case T.custom:t="Invalid input";break;case T.invalid_intersection_types:t="Intersection results could not be merged";break;case T.not_multiple_of:t=`Number must be a multiple of ${r.multipleOf}`;break;case T.not_finite:t="Number must be finite";break;default:t=e.defaultError,G.assertNever(r)}return{message:t}},et=Ld;var va=et;function zd(r){va=r}function $r(){return va}var bn=r=>{let{data:e,path:t,errorMaps:n,issueData:s}=r,i=[...t,...s.path||[]],o={...s,path:i};if(s.message!==void 0)return{...s,path:i,message:s.message};let a="",c=n.filter(l=>!!l).slice().reverse();for(let l of c)a=l(o,{data:e,defaultError:a}).message;return{...s,path:i,message:a}},Ud=[];function A(r,e){let t=$r(),n=bn({issueData:e,data:r.data,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,t,t===et?void 0:et].filter(s=>!!s)});r.common.issues.push(n)}var ue=class r{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,t){let n=[];for(let s of t){if(s.status==="aborted")return M;s.status==="dirty"&&e.dirty(),n.push(s.value)}return{status:e.value,value:n}}static async mergeObjectAsync(e,t){let n=[];for(let s of t){let i=await s.key,o=await s.value;n.push({key:i,value:o})}return r.mergeObjectSync(e,n)}static mergeObjectSync(e,t){let n={};for(let s of t){let{key:i,value:o}=s;if(i.status==="aborted"||o.status==="aborted")return M;i.status==="dirty"&&e.dirty(),o.status==="dirty"&&e.dirty(),i.value!=="__proto__"&&(typeof o.value<"u"||s.alwaysSet)&&(n[i.value]=o.value)}return{status:e.value,value:n}}},M=Object.freeze({status:"aborted"}),Ot=r=>({status:"dirty",value:r}),he=r=>({status:"valid",value:r}),es=r=>r.status==="aborted",ts=r=>r.status==="dirty",yt=r=>r.status==="valid",Pr=r=>typeof Promise<"u"&&r instanceof Promise;var P;(function(r){r.errToObj=e=>typeof e=="string"?{message:e}:e||{},r.toString=e=>typeof e=="string"?e:e?.message})(P||(P={}));var Ae=class{constructor(e,t,n,s){this._cachedPath=[],this.parent=e,this.data=t,this._path=n,this._key=s}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},ba=(r,e)=>{if(yt(e))return{success:!0,data:e.value};if(!r.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let t=new ge(r.common.issues);return this._error=t,this._error}}};function q(r){if(!r)return{};let{errorMap:e,invalid_type_error:t,required_error:n,description:s}=r;if(e&&(t||n))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:s}:{errorMap:(o,a)=>{let{message:c}=r;return o.code==="invalid_enum_value"?{message:c??a.defaultError}:typeof a.data>"u"?{message:c??n??a.defaultError}:o.code!=="invalid_type"?{message:a.defaultError}:{message:c??t??a.defaultError}},description:s}}var K=class{get description(){return this._def.description}_getType(e){return Fe(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:Fe(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new ue,ctx:{common:e.parent.common,data:e.data,parsedType:Fe(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let t=this._parse(e);if(Pr(t))throw new Error("Synchronous parse encountered promise.");return t}_parseAsync(e){let t=this._parse(e);return Promise.resolve(t)}parse(e,t){let n=this.safeParse(e,t);if(n.success)return n.data;throw n.error}safeParse(e,t){let n={common:{issues:[],async:t?.async??!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Fe(e)},s=this._parseSync({data:e,path:n.path,parent:n});return ba(n,s)}"~validate"(e){let t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Fe(e)};if(!this["~standard"].async)try{let n=this._parseSync({data:e,path:[],parent:t});return yt(n)?{value:n.value}:{issues:t.common.issues}}catch(n){n?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then(n=>yt(n)?{value:n.value}:{issues:t.common.issues})}async parseAsync(e,t){let n=await this.safeParseAsync(e,t);if(n.success)return n.data;throw n.error}async safeParseAsync(e,t){let n={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Fe(e)},s=this._parse({data:e,path:n.path,parent:n}),i=await(Pr(s)?s:Promise.resolve(s));return ba(n,i)}refine(e,t){let n=s=>typeof t=="string"||typeof t>"u"?{message:t}:typeof t=="function"?t(s):t;return this._refinement((s,i)=>{let o=e(s),a=()=>i.addIssue({code:T.custom,...n(s)});return typeof Promise<"u"&&o instanceof Promise?o.then(c=>c?!0:(a(),!1)):o?!0:(a(),!1)})}refinement(e,t){return this._refinement((n,s)=>e(n)?!0:(s.addIssue(typeof t=="function"?t(n,s):t),!1))}_refinement(e){return new Re({schema:this,typeName:D.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:t=>this["~validate"](t)}}optional(){return Ie.create(this,this._def)}nullable(){return Ke.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return nt.create(this)}promise(){return bt.create(this,this._def)}or(e){return qt.create([this,e],this._def)}and(e){return Bt.create(this,e,this._def)}transform(e){return new Re({...q(this._def),schema:this,typeName:D.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let t=typeof e=="function"?e:()=>e;return new Ht({...q(this._def),innerType:this,defaultValue:t,typeName:D.ZodDefault})}brand(){return new wn({typeName:D.ZodBranded,type:this,...q(this._def)})}catch(e){let t=typeof e=="function"?e:()=>e;return new Gt({...q(this._def),innerType:this,catchValue:t,typeName:D.ZodCatch})}describe(e){let t=this.constructor;return new t({...this._def,description:e})}pipe(e){return kn.create(this,e)}readonly(){return Wt.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},qd=/^c[^\s-]{8,}$/i,Bd=/^[0-9a-z]+$/,Fd=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Zd=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,Kd=/^[a-z0-9_-]{21}$/i,Vd=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Hd=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,Gd=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,Wd="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",ki,Jd=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,Yd=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,Xd=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,Qd=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,eh=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,th=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,ka="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",rh=new RegExp(`^${ka}$`);function Sa(r){let e="[0-5]\\d";r.precision?e=`${e}\\.\\d{${r.precision}}`:r.precision==null&&(e=`${e}(\\.\\d+)?`);let t=r.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${t}`}function nh(r){return new RegExp(`^${Sa(r)}$`)}function Ta(r){let e=`${ka}T${Sa(r)}`,t=[];return t.push(r.local?"Z?":"Z"),r.offset&&t.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${t.join("|")})`,new RegExp(`^${e}$`)}function sh(r,e){return!!((e==="v4"||!e)&&Jd.test(r)||(e==="v6"||!e)&&Xd.test(r))}function ih(r,e){if(!Vd.test(r))return!1;try{let[t]=r.split(".");if(!t)return!1;let n=t.replace(/-/g,"+").replace(/_/g,"/").padEnd(t.length+(4-t.length%4)%4,"="),s=JSON.parse(atob(n));return!(typeof s!="object"||s===null||"typ"in s&&s?.typ!=="JWT"||!s.alg||e&&s.alg!==e)}catch{return!1}}function oh(r,e){return!!((e==="v4"||!e)&&Yd.test(r)||(e==="v6"||!e)&&Qd.test(r))}var _t=class r extends K{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==R.string){let i=this._getOrReturnCtx(e);return A(i,{code:T.invalid_type,expected:R.string,received:i.parsedType}),M}let n=new ue,s;for(let i of this._def.checks)if(i.kind==="min")e.data.length<i.value&&(s=this._getOrReturnCtx(e,s),A(s,{code:T.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),n.dirty());else if(i.kind==="max")e.data.length>i.value&&(s=this._getOrReturnCtx(e,s),A(s,{code:T.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),n.dirty());else if(i.kind==="length"){let o=e.data.length>i.value,a=e.data.length<i.value;(o||a)&&(s=this._getOrReturnCtx(e,s),o?A(s,{code:T.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}):a&&A(s,{code:T.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}),n.dirty())}else if(i.kind==="email")Gd.test(e.data)||(s=this._getOrReturnCtx(e,s),A(s,{validation:"email",code:T.invalid_string,message:i.message}),n.dirty());else if(i.kind==="emoji")ki||(ki=new RegExp(Wd,"u")),ki.test(e.data)||(s=this._getOrReturnCtx(e,s),A(s,{validation:"emoji",code:T.invalid_string,message:i.message}),n.dirty());else if(i.kind==="uuid")Zd.test(e.data)||(s=this._getOrReturnCtx(e,s),A(s,{validation:"uuid",code:T.invalid_string,message:i.message}),n.dirty());else if(i.kind==="nanoid")Kd.test(e.data)||(s=this._getOrReturnCtx(e,s),A(s,{validation:"nanoid",code:T.invalid_string,message:i.message}),n.dirty());else if(i.kind==="cuid")qd.test(e.data)||(s=this._getOrReturnCtx(e,s),A(s,{validation:"cuid",code:T.invalid_string,message:i.message}),n.dirty());else if(i.kind==="cuid2")Bd.test(e.data)||(s=this._getOrReturnCtx(e,s),A(s,{validation:"cuid2",code:T.invalid_string,message:i.message}),n.dirty());else if(i.kind==="ulid")Fd.test(e.data)||(s=this._getOrReturnCtx(e,s),A(s,{validation:"ulid",code:T.invalid_string,message:i.message}),n.dirty());else if(i.kind==="url")try{new URL(e.data)}catch{s=this._getOrReturnCtx(e,s),A(s,{validation:"url",code:T.invalid_string,message:i.message}),n.dirty()}else i.kind==="regex"?(i.regex.lastIndex=0,i.regex.test(e.data)||(s=this._getOrReturnCtx(e,s),A(s,{validation:"regex",code:T.invalid_string,message:i.message}),n.dirty())):i.kind==="trim"?e.data=e.data.trim():i.kind==="includes"?e.data.includes(i.value,i.position)||(s=this._getOrReturnCtx(e,s),A(s,{code:T.invalid_string,validation:{includes:i.value,position:i.position},message:i.message}),n.dirty()):i.kind==="toLowerCase"?e.data=e.data.toLowerCase():i.kind==="toUpperCase"?e.data=e.data.toUpperCase():i.kind==="startsWith"?e.data.startsWith(i.value)||(s=this._getOrReturnCtx(e,s),A(s,{code:T.invalid_string,validation:{startsWith:i.value},message:i.message}),n.dirty()):i.kind==="endsWith"?e.data.endsWith(i.value)||(s=this._getOrReturnCtx(e,s),A(s,{code:T.invalid_string,validation:{endsWith:i.value},message:i.message}),n.dirty()):i.kind==="datetime"?Ta(i).test(e.data)||(s=this._getOrReturnCtx(e,s),A(s,{code:T.invalid_string,validation:"datetime",message:i.message}),n.dirty()):i.kind==="date"?rh.test(e.data)||(s=this._getOrReturnCtx(e,s),A(s,{code:T.invalid_string,validation:"date",message:i.message}),n.dirty()):i.kind==="time"?nh(i).test(e.data)||(s=this._getOrReturnCtx(e,s),A(s,{code:T.invalid_string,validation:"time",message:i.message}),n.dirty()):i.kind==="duration"?Hd.test(e.data)||(s=this._getOrReturnCtx(e,s),A(s,{validation:"duration",code:T.invalid_string,message:i.message}),n.dirty()):i.kind==="ip"?sh(e.data,i.version)||(s=this._getOrReturnCtx(e,s),A(s,{validation:"ip",code:T.invalid_string,message:i.message}),n.dirty()):i.kind==="jwt"?ih(e.data,i.alg)||(s=this._getOrReturnCtx(e,s),A(s,{validation:"jwt",code:T.invalid_string,message:i.message}),n.dirty()):i.kind==="cidr"?oh(e.data,i.version)||(s=this._getOrReturnCtx(e,s),A(s,{validation:"cidr",code:T.invalid_string,message:i.message}),n.dirty()):i.kind==="base64"?eh.test(e.data)||(s=this._getOrReturnCtx(e,s),A(s,{validation:"base64",code:T.invalid_string,message:i.message}),n.dirty()):i.kind==="base64url"?th.test(e.data)||(s=this._getOrReturnCtx(e,s),A(s,{validation:"base64url",code:T.invalid_string,message:i.message}),n.dirty()):G.assertNever(i);return{status:n.value,value:e.data}}_regex(e,t,n){return this.refinement(s=>e.test(s),{validation:t,code:T.invalid_string,...P.errToObj(n)})}_addCheck(e){return new r({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...P.errToObj(e)})}url(e){return this._addCheck({kind:"url",...P.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...P.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...P.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...P.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...P.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...P.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...P.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...P.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...P.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...P.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...P.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...P.errToObj(e)})}datetime(e){return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...P.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof e?.precision>"u"?null:e?.precision,...P.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...P.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...P.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t?.position,...P.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...P.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...P.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...P.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...P.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...P.errToObj(t)})}nonempty(e){return this.min(1,P.errToObj(e))}trim(){return new r({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new r({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new r({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}};_t.create=r=>new _t({checks:[],typeName:D.ZodString,coerce:r?.coerce??!1,...q(r)});function ah(r,e){let t=(r.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,s=t>n?t:n,i=Number.parseInt(r.toFixed(s).replace(".","")),o=Number.parseInt(e.toFixed(s).replace(".",""));return i%o/10**s}var Nt=class r extends K{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==R.number){let i=this._getOrReturnCtx(e);return A(i,{code:T.invalid_type,expected:R.number,received:i.parsedType}),M}let n,s=new ue;for(let i of this._def.checks)i.kind==="int"?G.isInteger(e.data)||(n=this._getOrReturnCtx(e,n),A(n,{code:T.invalid_type,expected:"integer",received:"float",message:i.message}),s.dirty()):i.kind==="min"?(i.inclusive?e.data<i.value:e.data<=i.value)&&(n=this._getOrReturnCtx(e,n),A(n,{code:T.too_small,minimum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),s.dirty()):i.kind==="max"?(i.inclusive?e.data>i.value:e.data>=i.value)&&(n=this._getOrReturnCtx(e,n),A(n,{code:T.too_big,maximum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),s.dirty()):i.kind==="multipleOf"?ah(e.data,i.value)!==0&&(n=this._getOrReturnCtx(e,n),A(n,{code:T.not_multiple_of,multipleOf:i.value,message:i.message}),s.dirty()):i.kind==="finite"?Number.isFinite(e.data)||(n=this._getOrReturnCtx(e,n),A(n,{code:T.not_finite,message:i.message}),s.dirty()):G.assertNever(i);return{status:s.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,P.toString(t))}gt(e,t){return this.setLimit("min",e,!1,P.toString(t))}lte(e,t){return this.setLimit("max",e,!0,P.toString(t))}lt(e,t){return this.setLimit("max",e,!1,P.toString(t))}setLimit(e,t,n,s){return new r({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:n,message:P.toString(s)}]})}_addCheck(e){return new r({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:P.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:P.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:P.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:P.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:P.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:P.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:P.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:P.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:P.toString(e)})}get minValue(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&G.isInteger(e.value))}get isFinite(){let e=null,t=null;for(let n of this._def.checks){if(n.kind==="finite"||n.kind==="int"||n.kind==="multipleOf")return!0;n.kind==="min"?(t===null||n.value>t)&&(t=n.value):n.kind==="max"&&(e===null||n.value<e)&&(e=n.value)}return Number.isFinite(t)&&Number.isFinite(e)}};Nt.create=r=>new Nt({checks:[],typeName:D.ZodNumber,coerce:r?.coerce||!1,...q(r)});var Mt=class r extends K{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==R.bigint)return this._getInvalidInput(e);let n,s=new ue;for(let i of this._def.checks)i.kind==="min"?(i.inclusive?e.data<i.value:e.data<=i.value)&&(n=this._getOrReturnCtx(e,n),A(n,{code:T.too_small,type:"bigint",minimum:i.value,inclusive:i.inclusive,message:i.message}),s.dirty()):i.kind==="max"?(i.inclusive?e.data>i.value:e.data>=i.value)&&(n=this._getOrReturnCtx(e,n),A(n,{code:T.too_big,type:"bigint",maximum:i.value,inclusive:i.inclusive,message:i.message}),s.dirty()):i.kind==="multipleOf"?e.data%i.value!==BigInt(0)&&(n=this._getOrReturnCtx(e,n),A(n,{code:T.not_multiple_of,multipleOf:i.value,message:i.message}),s.dirty()):G.assertNever(i);return{status:s.value,value:e.data}}_getInvalidInput(e){let t=this._getOrReturnCtx(e);return A(t,{code:T.invalid_type,expected:R.bigint,received:t.parsedType}),M}gte(e,t){return this.setLimit("min",e,!0,P.toString(t))}gt(e,t){return this.setLimit("min",e,!1,P.toString(t))}lte(e,t){return this.setLimit("max",e,!0,P.toString(t))}lt(e,t){return this.setLimit("max",e,!1,P.toString(t))}setLimit(e,t,n,s){return new r({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:n,message:P.toString(s)}]})}_addCheck(e){return new r({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:P.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:P.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:P.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:P.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:P.toString(t)})}get minValue(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}};Mt.create=r=>new Mt({checks:[],typeName:D.ZodBigInt,coerce:r?.coerce??!1,...q(r)});var Dt=class extends K{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==R.boolean){let n=this._getOrReturnCtx(e);return A(n,{code:T.invalid_type,expected:R.boolean,received:n.parsedType}),M}return he(e.data)}};Dt.create=r=>new Dt({typeName:D.ZodBoolean,coerce:r?.coerce||!1,...q(r)});var Lt=class r extends K{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==R.date){let i=this._getOrReturnCtx(e);return A(i,{code:T.invalid_type,expected:R.date,received:i.parsedType}),M}if(Number.isNaN(e.data.getTime())){let i=this._getOrReturnCtx(e);return A(i,{code:T.invalid_date}),M}let n=new ue,s;for(let i of this._def.checks)i.kind==="min"?e.data.getTime()<i.value&&(s=this._getOrReturnCtx(e,s),A(s,{code:T.too_small,message:i.message,inclusive:!0,exact:!1,minimum:i.value,type:"date"}),n.dirty()):i.kind==="max"?e.data.getTime()>i.value&&(s=this._getOrReturnCtx(e,s),A(s,{code:T.too_big,message:i.message,inclusive:!0,exact:!1,maximum:i.value,type:"date"}),n.dirty()):G.assertNever(i);return{status:n.value,value:new Date(e.data.getTime())}}_addCheck(e){return new r({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:P.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:P.toString(t)})}get minDate(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e!=null?new Date(e):null}};Lt.create=r=>new Lt({checks:[],coerce:r?.coerce||!1,typeName:D.ZodDate,...q(r)});var Or=class extends K{_parse(e){if(this._getType(e)!==R.symbol){let n=this._getOrReturnCtx(e);return A(n,{code:T.invalid_type,expected:R.symbol,received:n.parsedType}),M}return he(e.data)}};Or.create=r=>new Or({typeName:D.ZodSymbol,...q(r)});var zt=class extends K{_parse(e){if(this._getType(e)!==R.undefined){let n=this._getOrReturnCtx(e);return A(n,{code:T.invalid_type,expected:R.undefined,received:n.parsedType}),M}return he(e.data)}};zt.create=r=>new zt({typeName:D.ZodUndefined,...q(r)});var Ut=class extends K{_parse(e){if(this._getType(e)!==R.null){let n=this._getOrReturnCtx(e);return A(n,{code:T.invalid_type,expected:R.null,received:n.parsedType}),M}return he(e.data)}};Ut.create=r=>new Ut({typeName:D.ZodNull,...q(r)});var vt=class extends K{constructor(){super(...arguments),this._any=!0}_parse(e){return he(e.data)}};vt.create=r=>new vt({typeName:D.ZodAny,...q(r)});var rt=class extends K{constructor(){super(...arguments),this._unknown=!0}_parse(e){return he(e.data)}};rt.create=r=>new rt({typeName:D.ZodUnknown,...q(r)});var De=class extends K{_parse(e){let t=this._getOrReturnCtx(e);return A(t,{code:T.invalid_type,expected:R.never,received:t.parsedType}),M}};De.create=r=>new De({typeName:D.ZodNever,...q(r)});var Nr=class extends K{_parse(e){if(this._getType(e)!==R.undefined){let n=this._getOrReturnCtx(e);return A(n,{code:T.invalid_type,expected:R.void,received:n.parsedType}),M}return he(e.data)}};Nr.create=r=>new Nr({typeName:D.ZodVoid,...q(r)});var nt=class r extends K{_parse(e){let{ctx:t,status:n}=this._processInputParams(e),s=this._def;if(t.parsedType!==R.array)return A(t,{code:T.invalid_type,expected:R.array,received:t.parsedType}),M;if(s.exactLength!==null){let o=t.data.length>s.exactLength.value,a=t.data.length<s.exactLength.value;(o||a)&&(A(t,{code:o?T.too_big:T.too_small,minimum:a?s.exactLength.value:void 0,maximum:o?s.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:s.exactLength.message}),n.dirty())}if(s.minLength!==null&&t.data.length<s.minLength.value&&(A(t,{code:T.too_small,minimum:s.minLength.value,type:"array",inclusive:!0,exact:!1,message:s.minLength.message}),n.dirty()),s.maxLength!==null&&t.data.length>s.maxLength.value&&(A(t,{code:T.too_big,maximum:s.maxLength.value,type:"array",inclusive:!0,exact:!1,message:s.maxLength.message}),n.dirty()),t.common.async)return Promise.all([...t.data].map((o,a)=>s.type._parseAsync(new Ae(t,o,t.path,a)))).then(o=>ue.mergeArray(n,o));let i=[...t.data].map((o,a)=>s.type._parseSync(new Ae(t,o,t.path,a)));return ue.mergeArray(n,i)}get element(){return this._def.type}min(e,t){return new r({...this._def,minLength:{value:e,message:P.toString(t)}})}max(e,t){return new r({...this._def,maxLength:{value:e,message:P.toString(t)}})}length(e,t){return new r({...this._def,exactLength:{value:e,message:P.toString(t)}})}nonempty(e){return this.min(1,e)}};nt.create=(r,e)=>new nt({type:r,minLength:null,maxLength:null,exactLength:null,typeName:D.ZodArray,...q(e)});function jr(r){if(r instanceof ye){let e={};for(let t in r.shape){let n=r.shape[t];e[t]=Ie.create(jr(n))}return new ye({...r._def,shape:()=>e})}else return r instanceof nt?new nt({...r._def,type:jr(r.element)}):r instanceof Ie?Ie.create(jr(r.unwrap())):r instanceof Ke?Ke.create(jr(r.unwrap())):r instanceof Ze?Ze.create(r.items.map(e=>jr(e))):r}var ye=class r extends K{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape(),t=G.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==R.object){let l=this._getOrReturnCtx(e);return A(l,{code:T.invalid_type,expected:R.object,received:l.parsedType}),M}let{status:n,ctx:s}=this._processInputParams(e),{shape:i,keys:o}=this._getCached(),a=[];if(!(this._def.catchall instanceof De&&this._def.unknownKeys==="strip"))for(let l in s.data)o.includes(l)||a.push(l);let c=[];for(let l of o){let d=i[l],p=s.data[l];c.push({key:{status:"valid",value:l},value:d._parse(new Ae(s,p,s.path,l)),alwaysSet:l in s.data})}if(this._def.catchall instanceof De){let l=this._def.unknownKeys;if(l==="passthrough")for(let d of a)c.push({key:{status:"valid",value:d},value:{status:"valid",value:s.data[d]}});else if(l==="strict")a.length>0&&(A(s,{code:T.unrecognized_keys,keys:a}),n.dirty());else if(l!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let l=this._def.catchall;for(let d of a){let p=s.data[d];c.push({key:{status:"valid",value:d},value:l._parse(new Ae(s,p,s.path,d)),alwaysSet:d in s.data})}}return s.common.async?Promise.resolve().then(async()=>{let l=[];for(let d of c){let p=await d.key,v=await d.value;l.push({key:p,value:v,alwaysSet:d.alwaysSet})}return l}).then(l=>ue.mergeObjectSync(n,l)):ue.mergeObjectSync(n,c)}get shape(){return this._def.shape()}strict(e){return P.errToObj,new r({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(t,n)=>{let s=this._def.errorMap?.(t,n).message??n.defaultError;return t.code==="unrecognized_keys"?{message:P.errToObj(e).message??s}:{message:s}}}:{}})}strip(){return new r({...this._def,unknownKeys:"strip"})}passthrough(){return new r({...this._def,unknownKeys:"passthrough"})}extend(e){return new r({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new r({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:D.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new r({...this._def,catchall:e})}pick(e){let t={};for(let n of G.objectKeys(e))e[n]&&this.shape[n]&&(t[n]=this.shape[n]);return new r({...this._def,shape:()=>t})}omit(e){let t={};for(let n of G.objectKeys(this.shape))e[n]||(t[n]=this.shape[n]);return new r({...this._def,shape:()=>t})}deepPartial(){return jr(this)}partial(e){let t={};for(let n of G.objectKeys(this.shape)){let s=this.shape[n];e&&!e[n]?t[n]=s:t[n]=s.optional()}return new r({...this._def,shape:()=>t})}required(e){let t={};for(let n of G.objectKeys(this.shape))if(e&&!e[n])t[n]=this.shape[n];else{let i=this.shape[n];for(;i instanceof Ie;)i=i._def.innerType;t[n]=i}return new r({...this._def,shape:()=>t})}keyof(){return xa(G.objectKeys(this.shape))}};ye.create=(r,e)=>new ye({shape:()=>r,unknownKeys:"strip",catchall:De.create(),typeName:D.ZodObject,...q(e)});ye.strictCreate=(r,e)=>new ye({shape:()=>r,unknownKeys:"strict",catchall:De.create(),typeName:D.ZodObject,...q(e)});ye.lazycreate=(r,e)=>new ye({shape:r,unknownKeys:"strip",catchall:De.create(),typeName:D.ZodObject,...q(e)});var qt=class extends K{_parse(e){let{ctx:t}=this._processInputParams(e),n=this._def.options;function s(i){for(let a of i)if(a.result.status==="valid")return a.result;for(let a of i)if(a.result.status==="dirty")return t.common.issues.push(...a.ctx.common.issues),a.result;let o=i.map(a=>new ge(a.ctx.common.issues));return A(t,{code:T.invalid_union,unionErrors:o}),M}if(t.common.async)return Promise.all(n.map(async i=>{let o={...t,common:{...t.common,issues:[]},parent:null};return{result:await i._parseAsync({data:t.data,path:t.path,parent:o}),ctx:o}})).then(s);{let i,o=[];for(let c of n){let l={...t,common:{...t.common,issues:[]},parent:null},d=c._parseSync({data:t.data,path:t.path,parent:l});if(d.status==="valid")return d;d.status==="dirty"&&!i&&(i={result:d,ctx:l}),l.common.issues.length&&o.push(l.common.issues)}if(i)return t.common.issues.push(...i.ctx.common.issues),i.result;let a=o.map(c=>new ge(c));return A(t,{code:T.invalid_union,unionErrors:a}),M}}get options(){return this._def.options}};qt.create=(r,e)=>new qt({options:r,typeName:D.ZodUnion,...q(e)});var tt=r=>r instanceof Ft?tt(r.schema):r instanceof Re?tt(r.innerType()):r instanceof Zt?[r.value]:r instanceof Kt?r.options:r instanceof Vt?G.objectValues(r.enum):r instanceof Ht?tt(r._def.innerType):r instanceof zt?[void 0]:r instanceof Ut?[null]:r instanceof Ie?[void 0,...tt(r.unwrap())]:r instanceof Ke?[null,...tt(r.unwrap())]:r instanceof wn||r instanceof Wt?tt(r.unwrap()):r instanceof Gt?tt(r._def.innerType):[],rs=class r extends K{_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==R.object)return A(t,{code:T.invalid_type,expected:R.object,received:t.parsedType}),M;let n=this.discriminator,s=t.data[n],i=this.optionsMap.get(s);return i?t.common.async?i._parseAsync({data:t.data,path:t.path,parent:t}):i._parseSync({data:t.data,path:t.path,parent:t}):(A(t,{code:T.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),M)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,t,n){let s=new Map;for(let i of t){let o=tt(i.shape[e]);if(!o.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let a of o){if(s.has(a))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(a)}`);s.set(a,i)}}return new r({typeName:D.ZodDiscriminatedUnion,discriminator:e,options:t,optionsMap:s,...q(n)})}};function Si(r,e){let t=Fe(r),n=Fe(e);if(r===e)return{valid:!0,data:r};if(t===R.object&&n===R.object){let s=G.objectKeys(e),i=G.objectKeys(r).filter(a=>s.indexOf(a)!==-1),o={...r,...e};for(let a of i){let c=Si(r[a],e[a]);if(!c.valid)return{valid:!1};o[a]=c.data}return{valid:!0,data:o}}else if(t===R.array&&n===R.array){if(r.length!==e.length)return{valid:!1};let s=[];for(let i=0;i<r.length;i++){let o=r[i],a=e[i],c=Si(o,a);if(!c.valid)return{valid:!1};s.push(c.data)}return{valid:!0,data:s}}else return t===R.date&&n===R.date&&+r==+e?{valid:!0,data:r}:{valid:!1}}var Bt=class extends K{_parse(e){let{status:t,ctx:n}=this._processInputParams(e),s=(i,o)=>{if(es(i)||es(o))return M;let a=Si(i.value,o.value);return a.valid?((ts(i)||ts(o))&&t.dirty(),{status:t.value,value:a.data}):(A(n,{code:T.invalid_intersection_types}),M)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([i,o])=>s(i,o)):s(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}};Bt.create=(r,e,t)=>new Bt({left:r,right:e,typeName:D.ZodIntersection,...q(t)});var Ze=class r extends K{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==R.array)return A(n,{code:T.invalid_type,expected:R.array,received:n.parsedType}),M;if(n.data.length<this._def.items.length)return A(n,{code:T.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),M;!this._def.rest&&n.data.length>this._def.items.length&&(A(n,{code:T.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());let i=[...n.data].map((o,a)=>{let c=this._def.items[a]||this._def.rest;return c?c._parse(new Ae(n,o,n.path,a)):null}).filter(o=>!!o);return n.common.async?Promise.all(i).then(o=>ue.mergeArray(t,o)):ue.mergeArray(t,i)}get items(){return this._def.items}rest(e){return new r({...this._def,rest:e})}};Ze.create=(r,e)=>{if(!Array.isArray(r))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Ze({items:r,typeName:D.ZodTuple,rest:null,...q(e)})};var ns=class r extends K{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==R.object)return A(n,{code:T.invalid_type,expected:R.object,received:n.parsedType}),M;let s=[],i=this._def.keyType,o=this._def.valueType;for(let a in n.data)s.push({key:i._parse(new Ae(n,a,n.path,a)),value:o._parse(new Ae(n,n.data[a],n.path,a)),alwaysSet:a in n.data});return n.common.async?ue.mergeObjectAsync(t,s):ue.mergeObjectSync(t,s)}get element(){return this._def.valueType}static create(e,t,n){return t instanceof K?new r({keyType:e,valueType:t,typeName:D.ZodRecord,...q(n)}):new r({keyType:_t.create(),valueType:e,typeName:D.ZodRecord,...q(t)})}},Mr=class extends K{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==R.map)return A(n,{code:T.invalid_type,expected:R.map,received:n.parsedType}),M;let s=this._def.keyType,i=this._def.valueType,o=[...n.data.entries()].map(([a,c],l)=>({key:s._parse(new Ae(n,a,n.path,[l,"key"])),value:i._parse(new Ae(n,c,n.path,[l,"value"]))}));if(n.common.async){let a=new Map;return Promise.resolve().then(async()=>{for(let c of o){let l=await c.key,d=await c.value;if(l.status==="aborted"||d.status==="aborted")return M;(l.status==="dirty"||d.status==="dirty")&&t.dirty(),a.set(l.value,d.value)}return{status:t.value,value:a}})}else{let a=new Map;for(let c of o){let l=c.key,d=c.value;if(l.status==="aborted"||d.status==="aborted")return M;(l.status==="dirty"||d.status==="dirty")&&t.dirty(),a.set(l.value,d.value)}return{status:t.value,value:a}}}};Mr.create=(r,e,t)=>new Mr({valueType:e,keyType:r,typeName:D.ZodMap,...q(t)});var Dr=class r extends K{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==R.set)return A(n,{code:T.invalid_type,expected:R.set,received:n.parsedType}),M;let s=this._def;s.minSize!==null&&n.data.size<s.minSize.value&&(A(n,{code:T.too_small,minimum:s.minSize.value,type:"set",inclusive:!0,exact:!1,message:s.minSize.message}),t.dirty()),s.maxSize!==null&&n.data.size>s.maxSize.value&&(A(n,{code:T.too_big,maximum:s.maxSize.value,type:"set",inclusive:!0,exact:!1,message:s.maxSize.message}),t.dirty());let i=this._def.valueType;function o(c){let l=new Set;for(let d of c){if(d.status==="aborted")return M;d.status==="dirty"&&t.dirty(),l.add(d.value)}return{status:t.value,value:l}}let a=[...n.data.values()].map((c,l)=>i._parse(new Ae(n,c,n.path,l)));return n.common.async?Promise.all(a).then(c=>o(c)):o(a)}min(e,t){return new r({...this._def,minSize:{value:e,message:P.toString(t)}})}max(e,t){return new r({...this._def,maxSize:{value:e,message:P.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}};Dr.create=(r,e)=>new Dr({valueType:r,minSize:null,maxSize:null,typeName:D.ZodSet,...q(e)});var ss=class r extends K{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==R.function)return A(t,{code:T.invalid_type,expected:R.function,received:t.parsedType}),M;function n(a,c){return bn({data:a,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,$r(),et].filter(l=>!!l),issueData:{code:T.invalid_arguments,argumentsError:c}})}function s(a,c){return bn({data:a,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,$r(),et].filter(l=>!!l),issueData:{code:T.invalid_return_type,returnTypeError:c}})}let i={errorMap:t.common.contextualErrorMap},o=t.data;if(this._def.returns instanceof bt){let a=this;return he(async function(...c){let l=new ge([]),d=await a._def.args.parseAsync(c,i).catch(S=>{throw l.addIssue(n(c,S)),l}),p=await Reflect.apply(o,this,d);return await a._def.returns._def.type.parseAsync(p,i).catch(S=>{throw l.addIssue(s(p,S)),l})})}else{let a=this;return he(function(...c){let l=a._def.args.safeParse(c,i);if(!l.success)throw new ge([n(c,l.error)]);let d=Reflect.apply(o,this,l.data),p=a._def.returns.safeParse(d,i);if(!p.success)throw new ge([s(d,p.error)]);return p.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new r({...this._def,args:Ze.create(e).rest(rt.create())})}returns(e){return new r({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,t,n){return new r({args:e||Ze.create([]).rest(rt.create()),returns:t||rt.create(),typeName:D.ZodFunction,...q(n)})}},Ft=class extends K{get schema(){return this._def.getter()}_parse(e){let{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}};Ft.create=(r,e)=>new Ft({getter:r,typeName:D.ZodLazy,...q(e)});var Zt=class extends K{_parse(e){if(e.data!==this._def.value){let t=this._getOrReturnCtx(e);return A(t,{received:t.data,code:T.invalid_literal,expected:this._def.value}),M}return{status:"valid",value:e.data}}get value(){return this._def.value}};Zt.create=(r,e)=>new Zt({value:r,typeName:D.ZodLiteral,...q(e)});function xa(r,e){return new Kt({values:r,typeName:D.ZodEnum,...q(e)})}var Kt=class r extends K{_parse(e){if(typeof e.data!="string"){let t=this._getOrReturnCtx(e),n=this._def.values;return A(t,{expected:G.joinValues(n),received:t.parsedType,code:T.invalid_type}),M}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){let t=this._getOrReturnCtx(e),n=this._def.values;return A(t,{received:t.data,code:T.invalid_enum_value,options:n}),M}return he(e.data)}get options(){return this._def.values}get enum(){let e={};for(let t of this._def.values)e[t]=t;return e}get Values(){let e={};for(let t of this._def.values)e[t]=t;return e}get Enum(){let e={};for(let t of this._def.values)e[t]=t;return e}extract(e,t=this._def){return r.create(e,{...this._def,...t})}exclude(e,t=this._def){return r.create(this.options.filter(n=>!e.includes(n)),{...this._def,...t})}};Kt.create=xa;var Vt=class extends K{_parse(e){let t=G.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==R.string&&n.parsedType!==R.number){let s=G.objectValues(t);return A(n,{expected:G.joinValues(s),received:n.parsedType,code:T.invalid_type}),M}if(this._cache||(this._cache=new Set(G.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let s=G.objectValues(t);return A(n,{received:n.data,code:T.invalid_enum_value,options:s}),M}return he(e.data)}get enum(){return this._def.values}};Vt.create=(r,e)=>new Vt({values:r,typeName:D.ZodNativeEnum,...q(e)});var bt=class extends K{unwrap(){return this._def.type}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==R.promise&&t.common.async===!1)return A(t,{code:T.invalid_type,expected:R.promise,received:t.parsedType}),M;let n=t.parsedType===R.promise?t.data:Promise.resolve(t.data);return he(n.then(s=>this._def.type.parseAsync(s,{path:t.path,errorMap:t.common.contextualErrorMap})))}};bt.create=(r,e)=>new bt({type:r,typeName:D.ZodPromise,...q(e)});var Re=class extends K{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===D.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:t,ctx:n}=this._processInputParams(e),s=this._def.effect||null,i={addIssue:o=>{A(n,o),o.fatal?t.abort():t.dirty()},get path(){return n.path}};if(i.addIssue=i.addIssue.bind(i),s.type==="preprocess"){let o=s.transform(n.data,i);if(n.common.async)return Promise.resolve(o).then(async a=>{if(t.value==="aborted")return M;let c=await this._def.schema._parseAsync({data:a,path:n.path,parent:n});return c.status==="aborted"?M:c.status==="dirty"?Ot(c.value):t.value==="dirty"?Ot(c.value):c});{if(t.value==="aborted")return M;let a=this._def.schema._parseSync({data:o,path:n.path,parent:n});return a.status==="aborted"?M:a.status==="dirty"?Ot(a.value):t.value==="dirty"?Ot(a.value):a}}if(s.type==="refinement"){let o=a=>{let c=s.refinement(a,i);if(n.common.async)return Promise.resolve(c);if(c instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return a};if(n.common.async===!1){let a=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return a.status==="aborted"?M:(a.status==="dirty"&&t.dirty(),o(a.value),{status:t.value,value:a.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(a=>a.status==="aborted"?M:(a.status==="dirty"&&t.dirty(),o(a.value).then(()=>({status:t.value,value:a.value}))))}if(s.type==="transform")if(n.common.async===!1){let o=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!yt(o))return M;let a=s.transform(o.value,i);if(a instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:t.value,value:a}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(o=>yt(o)?Promise.resolve(s.transform(o.value,i)).then(a=>({status:t.value,value:a})):M);G.assertNever(s)}};Re.create=(r,e,t)=>new Re({schema:r,typeName:D.ZodEffects,effect:e,...q(t)});Re.createWithPreprocess=(r,e,t)=>new Re({schema:e,effect:{type:"preprocess",transform:r},typeName:D.ZodEffects,...q(t)});var Ie=class extends K{_parse(e){return this._getType(e)===R.undefined?he(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Ie.create=(r,e)=>new Ie({innerType:r,typeName:D.ZodOptional,...q(e)});var Ke=class extends K{_parse(e){return this._getType(e)===R.null?he(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Ke.create=(r,e)=>new Ke({innerType:r,typeName:D.ZodNullable,...q(e)});var Ht=class extends K{_parse(e){let{ctx:t}=this._processInputParams(e),n=t.data;return t.parsedType===R.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:t.path,parent:t})}removeDefault(){return this._def.innerType}};Ht.create=(r,e)=>new Ht({innerType:r,typeName:D.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...q(e)});var Gt=class extends K{_parse(e){let{ctx:t}=this._processInputParams(e),n={...t,common:{...t.common,issues:[]}},s=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return Pr(s)?s.then(i=>({status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new ge(n.common.issues)},input:n.data})})):{status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new ge(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};Gt.create=(r,e)=>new Gt({innerType:r,typeName:D.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...q(e)});var Lr=class extends K{_parse(e){if(this._getType(e)!==R.nan){let n=this._getOrReturnCtx(e);return A(n,{code:T.invalid_type,expected:R.nan,received:n.parsedType}),M}return{status:"valid",value:e.data}}};Lr.create=r=>new Lr({typeName:D.ZodNaN,...q(r)});var uh=Symbol("zod_brand"),wn=class extends K{_parse(e){let{ctx:t}=this._processInputParams(e),n=t.data;return this._def.type._parse({data:n,path:t.path,parent:t})}unwrap(){return this._def.type}},kn=class r extends K{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{let i=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return i.status==="aborted"?M:i.status==="dirty"?(t.dirty(),Ot(i.value)):this._def.out._parseAsync({data:i.value,path:n.path,parent:n})})();{let s=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return s.status==="aborted"?M:s.status==="dirty"?(t.dirty(),{status:"dirty",value:s.value}):this._def.out._parseSync({data:s.value,path:n.path,parent:n})}}static create(e,t){return new r({in:e,out:t,typeName:D.ZodPipeline})}},Wt=class extends K{_parse(e){let t=this._def.innerType._parse(e),n=s=>(yt(s)&&(s.value=Object.freeze(s.value)),s);return Pr(t)?t.then(s=>n(s)):n(t)}unwrap(){return this._def.innerType}};Wt.create=(r,e)=>new Wt({innerType:r,typeName:D.ZodReadonly,...q(e)});function wa(r,e){let t=typeof r=="function"?r(e):typeof r=="string"?{message:r}:r;return typeof t=="string"?{message:t}:t}function Ca(r,e={},t){return r?vt.create().superRefine((n,s)=>{let i=r(n);if(i instanceof Promise)return i.then(o=>{if(!o){let a=wa(e,n),c=a.fatal??t??!0;s.addIssue({code:"custom",...a,fatal:c})}});if(!i){let o=wa(e,n),a=o.fatal??t??!0;s.addIssue({code:"custom",...o,fatal:a})}}):vt.create()}var ch={object:ye.lazycreate},D;(function(r){r.ZodString="ZodString",r.ZodNumber="ZodNumber",r.ZodNaN="ZodNaN",r.ZodBigInt="ZodBigInt",r.ZodBoolean="ZodBoolean",r.ZodDate="ZodDate",r.ZodSymbol="ZodSymbol",r.ZodUndefined="ZodUndefined",r.ZodNull="ZodNull",r.ZodAny="ZodAny",r.ZodUnknown="ZodUnknown",r.ZodNever="ZodNever",r.ZodVoid="ZodVoid",r.ZodArray="ZodArray",r.ZodObject="ZodObject",r.ZodUnion="ZodUnion",r.ZodDiscriminatedUnion="ZodDiscriminatedUnion",r.ZodIntersection="ZodIntersection",r.ZodTuple="ZodTuple",r.ZodRecord="ZodRecord",r.ZodMap="ZodMap",r.ZodSet="ZodSet",r.ZodFunction="ZodFunction",r.ZodLazy="ZodLazy",r.ZodLiteral="ZodLiteral",r.ZodEnum="ZodEnum",r.ZodEffects="ZodEffects",r.ZodNativeEnum="ZodNativeEnum",r.ZodOptional="ZodOptional",r.ZodNullable="ZodNullable",r.ZodDefault="ZodDefault",r.ZodCatch="ZodCatch",r.ZodPromise="ZodPromise",r.ZodBranded="ZodBranded",r.ZodPipeline="ZodPipeline",r.ZodReadonly="ZodReadonly"})(D||(D={}));var lh=(r,e={message:`Input not instance of ${r.name}`})=>Ca(t=>t instanceof r,e),Ea=_t.create,Ia=Nt.create,dh=Lr.create,hh=Mt.create,Aa=Dt.create,fh=Lt.create,ph=Or.create,mh=zt.create,gh=Ut.create,yh=vt.create,_h=rt.create,vh=De.create,bh=Nr.create,wh=nt.create,kh=ye.create,Sh=ye.strictCreate,Th=qt.create,xh=rs.create,Ch=Bt.create,Eh=Ze.create,Ih=ns.create,Ah=Mr.create,Rh=Dr.create,$h=ss.create,Ph=Ft.create,jh=Zt.create,Oh=Kt.create,Nh=Vt.create,Mh=bt.create,Dh=Re.create,Lh=Ie.create,zh=Ke.create,Uh=Re.createWithPreprocess,qh=kn.create,Bh=()=>Ea().optional(),Fh=()=>Ia().optional(),Zh=()=>Aa().optional(),Kh={string:(r=>_t.create({...r,coerce:!0})),number:(r=>Nt.create({...r,coerce:!0})),boolean:(r=>Dt.create({...r,coerce:!0})),bigint:(r=>Mt.create({...r,coerce:!0})),date:(r=>Lt.create({...r,coerce:!0}))};var Vh=M;var Ra=k.object({baseUrl:k.string().url(),email:k.string().email(),apiToken:k.string().min(1)}),Ti=k.object({controlPlaneUrl:k.string().url(),runnerId:k.string().optional(),runnerToken:k.string().optional(),runnerName:k.string().default(is.default.hostname()),jira:Ra.optional(),repos:k.record(k.object({path:k.string(),jira:Ra.optional(),github:k.object({token:k.string().min(1),login:k.string().optional()}).optional()})).default({}),github:k.object({token:k.string().min(1),login:k.string().optional()}).optional(),githubUsers:k.record(k.object({token:k.string().min(1),login:k.string().optional()})).default({}),deploy:k.object({enabled:k.boolean().default(!1)}).default({enabled:!1}),environments:k.record(k.object({secrets:k.record(k.string()).default({})})).default({}),claudeProfiles:k.record(k.object({configDir:k.string()})).default({}),claudeBin:k.string().default("claude"),agents:k.record(k.object({bin:k.string()})).default({}),jiraUsers:k.record(k.object({email:k.string().email(),apiToken:k.string().min(1)})).default({}),auditSchedules:k.array(k.object({repoName:k.string(),role:k.enum(["security","testing"]),intervalHours:k.number().int().min(6).max(720)})).default([]),pollIntervalSeconds:k.number().int().min(10).max(600).default(30)});function ee(){let r=process.env.ALLWRIGHT_CONFIG_DIR??process.env.TICKETPILOT_CONFIG_DIR;if(r)return r;let e=os.default.join(is.default.homedir(),".config","allwright"),t=os.default.join(is.default.homedir(),".config","ticketpilot");return!st.default.existsSync(e)&&st.default.existsSync(t)?t:e}function wt(){return os.default.join(ee(),"runner.json")}function ce(){let r=wt();if(!st.default.existsSync(r))return null;let e=JSON.parse(st.default.readFileSync(r,"utf8"));return Ti.parse(e)}function ie(r){let e=ee();st.default.mkdirSync(e,{recursive:!0,mode:448});let t=wt(),n=t+".tmp";st.default.writeFileSync(n,JSON.stringify(r,null,2)+`
237
237
  `,{mode:384}),st.default.renameSync(n,t),st.default.chmodSync(t,384)}function as(r,e){return`${r}:${e}`}function Jt(r,e,t){return r.environments[as(e,t)]?.secrets??{}}function Q(){let r=ce();if(!r)throw new Error(`No runner config found at ${wt()}. Run \`allwright init\` first.`);return r}var us=require("node:child_process"),we=$(require("node:fs"),1),cs=$(require("node:path"),1);var Hh=new Set(["runner.log","runner.pid"]);function Gh(r){return we.default.readdirSync(r).filter(e=>!Hh.has(e)&&!/\.bak-\d+$/.test(e)).sort()}function $a(r){let e=ee();if(!we.default.existsSync(e))throw new Error(`nothing to export \u2014 ${e} does not exist`);let t=Gh(e);if(!t.length)throw new Error(`nothing to export \u2014 ${e} is empty`);let n=new Date().toISOString().slice(0,19).replace(/[:T]/g,"-"),s=cs.default.resolve(r||`ticketpilot-backup-${n}.tgz`);return we.default.writeFileSync(s,"",{mode:384}),(0,us.execFileSync)("tar",["-czf",s,"-C",e,...t]),we.default.chmodSync(s,384),{file:s,entries:t}}function Pa(r){let e=cs.default.resolve(r);if(!we.default.existsSync(e))throw new Error(`backup file not found: ${e}`);let t=(0,us.execFileSync)("tar",["-tzf",e],{encoding:"utf8"}).split(`
238
238
  `).filter(Boolean);for(let i of t)if(i.startsWith("/")||i.split("/").includes(".."))throw new Error(`refusing to import \u2014 unsafe path in archive: ${i}`);let n=ee(),s;we.default.existsSync(n)&&we.default.readdirSync(n).length&&(s=`${n}.bak-${Date.now()}`,we.default.renameSync(n,s)),we.default.mkdirSync(n,{recursive:!0,mode:448}),(0,us.execFileSync)("tar",["-xzf",e,"-C",n]);for(let i of we.default.readdirSync(n)){let o=cs.default.join(n,i);we.default.statSync(o).isFile()&&we.default.chmodSync(o,384)}return{restored:t.map(i=>i.replace(/\/$/,"")).sort(),previousDir:s}}var zr=$(require("node:fs"),1),kt=$(require("node:path"),1),ls=".ticketpilot-attachments",Wh=15*1024*1024,Jh=50*1024*1024,ja=20;function Oa(r,e){let t=kt.default.basename(r).replace(/[^\w.\- ()]/g,"_").replace(/^\.+/,"").slice(-100)||"file",n=t,s=1;for(;e.has(n);)n=`${s++}-${t}`;return e.add(n),n}async function Ur(r,e,t,n){if(!e.length)return"";let s=kt.default.join(t,ls);zr.default.mkdirSync(s,{recursive:!0});let i=new Set,o=[],a=0;for(let c of e){if(o.length>=ja){n("warn",`attachment cap reached (${ja} files) \u2014 skipping the rest`);break}if(c.size>Wh){n("warn",`skipping attachment "${c.filename}" \u2014 ${Qh(c.size)} MB exceeds the 15 MB limit`);continue}if(a+c.size>Jh){n("warn",`attachment size budget reached \u2014 skipping "${c.filename}" and the rest`);break}try{let l=await r.downloadAttachment(c.contentUrl),d=Oa(c.filename,i);zr.default.writeFileSync(kt.default.join(s,d),l),a+=l.length,o.push(`- ${ls}/${d} (${c.mimeType||"unknown type"}, ${xi(l.length)} KB)`),n("info",`Downloaded attachment "${c.filename}" (${xi(l.length)} KB)`)}catch(l){n("warn",`could not download attachment "${c.filename}": ${l instanceof Error?l.message:l}`)}}return o.length?`
239
239
 
@@ -621,15 +621,15 @@ ${c.slice(0,800)}`),s("failed",{error:c})}}async function Fc(r,e){let t=js(e);if
621
621
 
622
622
  No deploy step was executed. (run \`${e}\`)`)}catch(o){m.error(`could not post rejection comment to ${t.issueKey}: ${o}`)}s("failed",{error:"deploy rejected by a reviewer"})}var hm=k.object({steps:k.array(wr.DeployStep).max(50).default([]),requiredSecrets:k.array(k.string()).max(50).default([]),notes:k.string().default("")}),fm=[".ticketpilot/deploy.md","DEPLOY.md","DEPLOYMENT.md","docs/DEPLOY.md","docs/deploy.md","docs/deployment.md"],Dc=24e3;function So(r){for(let e of fm){let t=br.default.join(r,e);try{if(!an.default.existsSync(t))continue;let n=an.default.readFileSync(t,"utf8");if(!n.trim())continue;return{path:e,content:n.length>Dc?n.slice(0,Dc)+`
623
623
 
624
- [\u2026document truncated\u2026]`:n}}catch{continue}}return null}var Lc=["docker","docker-compose","pm2","systemctl","node","pnpm","npm","yarn","make","python3","pip","rsync","ssh","caddy","nginx"];function Zc(r){return Kc("bash",["-lc",`command -v ${JSON.stringify(r)}`]).trim().length>0}function Kc(r,e){try{let t=(0,Ls.spawnSync)(r,e,{encoding:"utf8",timeout:5e3});return t.status===0?t.stdout??"":""}catch{return""}}function pm(r){let e=r.match(/\/(?:var|home|opt|srv)\/[\w./-]+/g)??[],t=[...new Set(e.map(s=>s.replace(/[.,;:)\]'"`]+$/,"")))].slice(0,12);return t.length?`
624
+ [\u2026document truncated\u2026]`:n}}catch{continue}}return null}var Lc=["docker","docker-compose","pm2","systemctl","node","pnpm","npm","yarn","make","python3","pip","rsync","ssh","caddy","nginx"];function Zc(r){return Kc("bash",["-lc",`command -v ${JSON.stringify(r)}`]).trim().length>0}function Kc(r,e){try{let t=(0,Ls.spawnSync)(r,e,{encoding:"utf8",timeout:5e3});return t.status===0?t.stdout??"":""}catch{return""}}async function pm(r,e){let t;try{t=new URL(r)}catch{e.push({name:"public-url",ok:!1,detail:`not a valid URL: ${r}`});return}try{let{lookup:n}=await import("node:dns/promises"),s=await n(t.hostname);e.push({name:"public-url-dns",ok:!0,detail:`${t.hostname} \u2192 ${s.address}`})}catch{e.push({name:"public-url-dns",ok:!1,detail:`${t.hostname} does not resolve \u2014 add an A/CNAME record for it at your DNS provider (changes can take a few minutes to propagate)`});return}if(t.protocol==="https:"){let n=await import("node:tls");await new Promise(s=>{let i=n.connect({host:t.hostname,port:Number(t.port||443),servername:t.hostname,timeout:8e3},()=>{let o=i.getPeerCertificate(),a=o?.valid_to?Math.round((new Date(o.valid_to).getTime()-Date.now())/864e5):NaN;e.push(Number.isFinite(a)&&a>0?{name:"public-url-tls",ok:a>14,detail:`certificate valid, expires in ${a} day(s)${a<=14?" \u2014 renew soon":""}`}:{name:"public-url-tls",ok:!1,detail:"certificate expired or unreadable"}),i.end(),s()});i.on("error",o=>{e.push({name:"public-url-tls",ok:!1,detail:`TLS handshake failed: ${o.message} \u2014 is a certificate installed for this hostname?`}),s()}),i.on("timeout",()=>{e.push({name:"public-url-tls",ok:!1,detail:"TLS handshake timed out"}),i.destroy(),s()})})}try{let n=await fetch(t.toString(),{method:"GET",redirect:"manual",signal:AbortSignal.timeout(1e4)});e.push({name:"public-url-reachable",ok:n.status<500,detail:`HTTP ${n.status}${n.status>=300&&n.status<400?` \u2192 ${n.headers.get("location")??""}`:""}`})}catch(n){e.push({name:"public-url-reachable",ok:!1,detail:`not reachable from the runner: ${n instanceof Error?n.message:String(n)}`})}}function mm(r){let e=r.match(/\/(?:var|home|opt|srv)\/[\w./-]+/g)??[],t=[...new Set(e.map(s=>s.replace(/[.,;:)\]'"`]+$/,"")))].slice(0,12);return t.length?`
625
625
  - absolute paths the document mentions, checked on THIS machine:
626
626
  ${t.map(s=>` - ${s}: ${an.default.existsSync(s)?"EXISTS on this machine":"not found on this machine"}`).join(`
627
- `)}`:""}function mm(r,e,t,n=""){let s=Lc.filter(a=>Zc(a)),i=Lc.filter(a=>!s.includes(a)),o=Object.keys(Jt(r,e,t));return`About the machine these steps will run on (gathered by the runner, trust it):
627
+ `)}`:""}function gm(r,e,t,n=""){let s=Lc.filter(a=>Zc(a)),i=Lc.filter(a=>!s.includes(a)),o=Object.keys(Jt(r,e,t));return`About the machine these steps will run on (gathered by the runner, trust it):
628
628
  - available tools: ${s.join(", ")||"(none of the common ones)"}
629
629
  - NOT installed: ${i.join(", ")||"(none missing)"}
630
- - secrets already stored for this environment (names only): ${o.join(", ")||"(none yet)"}`+pm(n)}async function Vc(r){let e=[];if(e.push(an.default.existsSync(r.repoPath)?{name:"repo-path",ok:!0,detail:r.repoPath}:{name:"repo-path",ok:!1,detail:`checkout missing: ${r.repoPath}`}),e.push({name:"deploys-enabled",ok:r.cfg.deploy.enabled,detail:r.cfg.deploy.enabled?"enabled on this runner":"disabled \u2014 run: allwright deploy enable (then restart the runner)"}),r.workdir){let a=br.default.isAbsolute(r.workdir)?r.workdir:br.default.join(r.repoPath,r.workdir);e.push(an.default.existsSync(a)?{name:"workdir",ok:!0,detail:a}:{name:"workdir",ok:!1,detail:`does not exist: ${a}`})}if(r.branch){let a=Kc("git",["-C",r.repoPath,"ls-remote","--heads","origin",r.branch]);e.push(a.trim()?{name:"branch",ok:!0,detail:`origin/${r.branch} exists`}:{name:"branch",ok:!1,detail:`origin has no branch "${r.branch}" (or the remote is unreachable)`})}let t=Jt(r.cfg,r.repoName,r.environmentName),n=new Set(r.requiredSecrets);for(let a of r.steps)for(let c of a.run.matchAll(/\$\{?([A-Z][A-Z0-9_]{2,})\}?/g))n.add(c[1]);let s=[...n].filter(a=>!t[a]&&!process.env[a]);e.push({name:"secrets",ok:s.length===0,detail:s.length?`missing: ${s.join(", ")} \u2014 set with: allwright env set "${r.repoName}" "${r.environmentName}" ${s[0]}=...`:`${n.size} present`});let i=new Set;for(let a of r.steps)for(let c of a.run.split(/&&|\|\||;|\|/)){let l=c.trim().split(/\s+/),d=l.shift();for(;d&&(/^[A-Za-z_][A-Za-z0-9_]*=/.test(d)||d==="sudo"||d==="env"||d==="nohup");)d=l.shift();!d||d.startsWith("$")||d.startsWith("#")||d.startsWith("(")||i.add(d)}let o=[...i].filter(a=>!Zc(a));return e.push({name:"binaries",ok:o.length===0,detail:o.length?`not found on this machine: ${o.join(", ")}`:`${i.size} found: ${[...i].slice(0,12).join(", ")}`}),{ok:e.every(a=>a.ok),checks:e}}async function Hc(r){let e=So(r.repoPath);if(!e)return{ok:!1,steps:[],requiredSecrets:[],notes:"",error:'this repo has no deploy document. Create DEPLOY.md at the repo root (or .ticketpilot/deploy.md) describing how this project actually deploys \u2014 the same commands you run by hand. "Ask Claude for steps" translates that document; it does not guess.'};let t=mm(r.cfg,r.repoName,r.environmentName,e.content),n=Rt(wr.DEPLOY_DOC_SUGGEST_PROMPT_TEMPLATE,{envName:r.environmentName,docPath:e.path,docContent:e.content,notes:r.notes.trim()||"(nothing specified)",machineContext:t}),s=await Ue.run({repoPath:r.repoPath,prompt:n,timeoutSeconds:r.timeoutSeconds,bin:r.cfg.claudeBin,mode:"read_only",maxTurns:30,sessionId:(0,Uc.randomUUID)(),onLog:()=>{}});if(!s.ok)return{ok:!1,steps:[],requiredSecrets:[],notes:"",error:s.error??"Claude Code produced no output"};let i=gm(s.resultText);return i?{ok:!0,...i}:(m.warn(`deploy step suggestion could not be parsed. Claude's raw answer follows:
631
- `+s.resultText.slice(0,4e3)),{ok:!1,steps:[],requiredSecrets:[],notes:"",error:`Claude answered, but not in the JSON shape we expected, so there is nothing safe to fill in. Try again, or write the steps by hand. Its answer started: "${s.resultText.trim().slice(0,200).replace(/\s+/g," ")}\u2026"`})}function gm(r){for(let e of ym(r)){let t;try{t=JSON.parse(e)}catch{continue}let n=hm.safeParse(_m(t));if(n.success&&n.data.steps.length||n.success&&n.data.notes.trim())return n.data}return null}function ym(r){let e=[];for(let s of r.matchAll(/```[a-zA-Z0-9_-]*[ \t]*\r?\n([\s\S]*?)```/g))s[1].trim()&&e.push(s[1]);let t=r.indexOf("{"),n=r.lastIndexOf("}");return t>=0&&n>t&&e.push(r.slice(t,n+1)),e}function _m(r){if(!r||typeof r!="object")return r;let e=r,n=(Array.isArray(r)?r:Array.isArray(e.steps)?e.steps:Array.isArray(e.deploy_steps)?e.deploy_steps:Array.isArray(e.deploySteps)?e.deploySteps:[]).map((o,a)=>{if(typeof o=="string")return o.trim()?{name:zc(o,a),run:o.trim()}:null;if(!o||typeof o!="object")return null;let c=o,l=vo(c.run,c.command,c.cmd,c.script,c.shell);return l?{name:(vo(c.name,c.title,c.description)??zc(l,a)).slice(0,120),run:l,continueOnError:c.continueOnError===!0||c.continue_on_error===!0}:null}).filter(Boolean),s=e.requiredSecrets??e.required_secrets??e.secrets,i=Array.isArray(s)?s.filter(o=>typeof o=="string"):s&&typeof s=="object"?Object.keys(s):[];return{steps:n.slice(0,50),requiredSecrets:i.slice(0,50),notes:vo(e.notes,e.note,e.explanation)??""}}function vo(...r){for(let e of r)if(typeof e=="string"&&e.trim())return e.trim()}function zc(r,e){return(r.split(`
632
- `)[0].trim()||`Step ${e+1}`).slice(0,120)}gr();ct();function To(r,e){if(!r.componentRoutes.length)return{project:r};let t=e.filter(Boolean);if(!t.length)return{error:`no Jira component set \u2014 project "${r.name}" routes by component (${r.componentRoutes.map(i=>i.component).join(", ")}); set one on the ticket`};let n=r.componentRoutes.filter(i=>t.includes(i.component));if(!n.length)return{error:`component(s) [${t.join(", ")}] not mapped \u2014 known: `+r.componentRoutes.map(i=>`${i.component}\u2192${i.repoName}`).join(", ")};let s=new Set(n.map(i=>i.repoName));return s.size>1?{error:`components map to DIFFERENT repos (${[...s].join(", ")}) \u2014 ambiguous, refusing`}:{project:{...r,repoName:n[0].repoName}}}var Gc=24*3600*1e3,Us=14,vm=Us*24*3600*1e3,bm=new Set(["to","on","this","the","a","an","env","environment","please","now","it"]),qs=class{constructor(e,t,n){this.cfg=e;this.jiraFor=t;this.transport=n}cfg;jiraFor;transport;projects=[];rules=[];environments=[];inFlight=new Set;repoQueues=new Map;envQueues=new Map;timer=null;ticking=!1;paused=!1;jiraOf(e){return this.jiraFor(e.repoName)}routingWarned=new Set;warnRoutingOnce(e,t){this.routingWarned.has(e)||(this.routingWarned.add(e),m.warn(`Component routing refused \u2014 ${t}`))}resolveClaudeProfile(e,t){if(!t)return;let n=this.cfg.claudeProfiles[t]?.configDir;return!n&&e&&(this.transport.send({type:"run.log",runId:e,seq:99e3,ts:new Date().toISOString(),level:"warn",message:`Claude profile "${t}" is not set up on this runner (allwright claude login "${t}") \u2014 using the runner's own login instead.`}),m.warn(`run ${e}: claude profile "${t}" missing locally \u2014 using default login`)),n}setConfig(e,t,n=!1,s=[]){this.projects=e,this.rules=t,this.environments=s;let i=t.filter(o=>o.enabled).length;m.info(`config synced: ${e.length} project(s), ${t.length} rule(s) (${i} enabled), ${s.length} environment(s)`),n!==this.paused&&(m.info(n?"polling paused from the dashboard":"polling resumed from the dashboard"),this.paused=n)}start(){let e=this.cfg.pollIntervalSeconds*1e3;this.timer=setInterval(()=>{this.tick()},e),this.tick(),m.info(`polling Jira every ${this.cfg.pollIntervalSeconds}s`)}stop(){this.timer&&clearInterval(this.timer)}lastScheduleCheck=0;auditInFlight=!1;async runScheduledAudits(){if(!(!this.cfg.auditSchedules.length||this.auditInFlight)&&!(Date.now()-this.lastScheduleCheck<15*6e4)){this.lastScheduleCheck=Date.now();for(let e of this.cfg.auditSchedules){let t=this.projects.find(s=>s.repoName===e.repoName);if(!t)continue;let n=Ku(t.id,e.role);if(!(n&&Date.now()-new Date(n).getTime()<e.intervalHours*36e5)){this.auditInFlight=!0;try{m.info(`Scheduled ${e.role} audit of ${e.repoName} starting (every ${e.intervalHours}h)`);let s=await Qr({projectId:t.id,repoPath:this.cfg.repos[e.repoName]?.path??"",role:e.role,scope:{kind:"repo",ref:""},model:"",claudeBin:this.cfg.claudeBin,jira:this.jiraFor(e.repoName)});if(s.ok){let i=s.audit.findings.length;m.info(`Scheduled audit done: ${i} finding(s) \u2014 drift visible on the Audits page`)}else m.warn(`Scheduled audit failed: ${s.error}`)}catch(s){m.warn(`Scheduled audit crashed: ${s instanceof Error?s.message:String(s)}`)}finally{this.auditInFlight=!1}break}}}}async tick(){if(!(this.ticking||this.paused||!this.transport.connected)){this.ticking=!0;try{await this.runScheduledAudits(),await this.sweepMergedPRs(),await this.sweepGitHubApprovals();let e=new Set;for(let t of this.rules){if(!t.enabled)continue;let n=this.projects.find(i=>i.id===t.projectId);if(!n)continue;let s=this.cfg.repos[n.repoName];if(!s){m.warn(`rule "${t.name}": no local path for repo "${n.repoName}" \u2014 run: allwright repo add "${n.repoName}" /path/to/checkout`);continue}t.action.type==="deploy"?await this.pollDeployRule(t,n,s.path):t.action.type==="respond"?await this.pollRespondRule(t,n,s.path):(e.has(n.id)||(e.add(n.id),await this.sweepNeedsInput(n)),t.trigger.type==="comment_keyword"&&await this.sweepRevisions(t,n),await this.pollRule(t,n,s.path))}}catch(e){m.warn(`poll tick failed: ${e instanceof Error?e.message:e}`)}finally{this.ticking=!1}}}async sweepGitHubApprovals(){let e=Object.values(Mn());if(!e.length)return;let t=ce()??this.cfg,n=new Map,s=i=>{let o=At(t,i);if(!o)return null;let a=n.get(o);return a||n.set(o,a=new Oe(o)),a};for(let i of e.slice(0,10)){let o=s(i.repoName);if(!o)continue;let a=`gh-approve:${i.runId}`;if(this.inFlight.has(a))continue;let c,l;try{[c,l]=await Promise.all([o.getReviews(i.owner,i.repo,i.prNumber),o.getPullRequest(i.owner,i.repo,i.prNumber)])}catch(S){m.warn(`review check failed for ${i.owner}/${i.repo}#${i.prNumber}: ${S instanceof Error?S.message:S}`);continue}if(!l)continue;let d={cfg:this.cfg,jiraFor:this.jiraFor,transport:this.transport};if(l.merged){m.info(`PR #${i.prNumber} for ${i.issueKey} was merged on GitHub \u2014 completing the run`),this.inFlight.add(a);try{await zn(d,i.runId,l.headSha)}finally{this.inFlight.delete(a)}continue}if(l.state==="closed"){m.info(`PR #${i.prNumber} for ${i.issueKey} was closed unmerged on GitHub \u2014 failing the run`);let S=this.jiraFor(i.repoName),x=`PR #${i.prNumber} was closed on GitHub without merging`;await S.addComment(i.issueKey,`**Allwright: the pull request for this ticket was closed on GitHub without merging.**
630
+ - secrets already stored for this environment (names only): ${o.join(", ")||"(none yet)"}`+mm(n)}async function Vc(r){let e=[];if(r.publicUrl?.trim()&&await pm(r.publicUrl.trim(),e),e.push(an.default.existsSync(r.repoPath)?{name:"repo-path",ok:!0,detail:r.repoPath}:{name:"repo-path",ok:!1,detail:`checkout missing: ${r.repoPath}`}),e.push({name:"deploys-enabled",ok:r.cfg.deploy.enabled,detail:r.cfg.deploy.enabled?"enabled on this runner":"disabled \u2014 run: allwright deploy enable (then restart the runner)"}),r.workdir){let a=br.default.isAbsolute(r.workdir)?r.workdir:br.default.join(r.repoPath,r.workdir);e.push(an.default.existsSync(a)?{name:"workdir",ok:!0,detail:a}:{name:"workdir",ok:!1,detail:`does not exist: ${a}`})}if(r.branch){let a=Kc("git",["-C",r.repoPath,"ls-remote","--heads","origin",r.branch]);e.push(a.trim()?{name:"branch",ok:!0,detail:`origin/${r.branch} exists`}:{name:"branch",ok:!1,detail:`origin has no branch "${r.branch}" (or the remote is unreachable)`})}let t=Jt(r.cfg,r.repoName,r.environmentName),n=new Set(r.requiredSecrets);for(let a of r.steps)for(let c of a.run.matchAll(/\$\{?([A-Z][A-Z0-9_]{2,})\}?/g))n.add(c[1]);let s=[...n].filter(a=>!t[a]&&!process.env[a]);e.push({name:"secrets",ok:s.length===0,detail:s.length?`missing: ${s.join(", ")} \u2014 set with: allwright env set "${r.repoName}" "${r.environmentName}" ${s[0]}=...`:`${n.size} present`});let i=new Set;for(let a of r.steps)for(let c of a.run.split(/&&|\|\||;|\|/)){let l=c.trim().split(/\s+/),d=l.shift();for(;d&&(/^[A-Za-z_][A-Za-z0-9_]*=/.test(d)||d==="sudo"||d==="env"||d==="nohup");)d=l.shift();!d||d.startsWith("$")||d.startsWith("#")||d.startsWith("(")||i.add(d)}let o=[...i].filter(a=>!Zc(a));return e.push({name:"binaries",ok:o.length===0,detail:o.length?`not found on this machine: ${o.join(", ")}`:`${i.size} found: ${[...i].slice(0,12).join(", ")}`}),{ok:e.every(a=>a.ok),checks:e}}async function Hc(r){let e=So(r.repoPath);if(!e)return{ok:!1,steps:[],requiredSecrets:[],notes:"",error:'this repo has no deploy document. Create DEPLOY.md at the repo root (or .ticketpilot/deploy.md) describing how this project actually deploys \u2014 the same commands you run by hand. "Ask Claude for steps" translates that document; it does not guess.'};let t=gm(r.cfg,r.repoName,r.environmentName,e.content),n=Rt(wr.DEPLOY_DOC_SUGGEST_PROMPT_TEMPLATE,{envName:r.environmentName,docPath:e.path,docContent:e.content,notes:r.notes.trim()||"(nothing specified)",machineContext:t}),s=await Ue.run({repoPath:r.repoPath,prompt:n,timeoutSeconds:r.timeoutSeconds,bin:r.cfg.claudeBin,mode:"read_only",maxTurns:30,sessionId:(0,Uc.randomUUID)(),onLog:()=>{}});if(!s.ok)return{ok:!1,steps:[],requiredSecrets:[],notes:"",error:s.error??"Claude Code produced no output"};let i=ym(s.resultText);return i?{ok:!0,...i}:(m.warn(`deploy step suggestion could not be parsed. Claude's raw answer follows:
631
+ `+s.resultText.slice(0,4e3)),{ok:!1,steps:[],requiredSecrets:[],notes:"",error:`Claude answered, but not in the JSON shape we expected, so there is nothing safe to fill in. Try again, or write the steps by hand. Its answer started: "${s.resultText.trim().slice(0,200).replace(/\s+/g," ")}\u2026"`})}function ym(r){for(let e of _m(r)){let t;try{t=JSON.parse(e)}catch{continue}let n=hm.safeParse(vm(t));if(n.success&&n.data.steps.length||n.success&&n.data.notes.trim())return n.data}return null}function _m(r){let e=[];for(let s of r.matchAll(/```[a-zA-Z0-9_-]*[ \t]*\r?\n([\s\S]*?)```/g))s[1].trim()&&e.push(s[1]);let t=r.indexOf("{"),n=r.lastIndexOf("}");return t>=0&&n>t&&e.push(r.slice(t,n+1)),e}function vm(r){if(!r||typeof r!="object")return r;let e=r,n=(Array.isArray(r)?r:Array.isArray(e.steps)?e.steps:Array.isArray(e.deploy_steps)?e.deploy_steps:Array.isArray(e.deploySteps)?e.deploySteps:[]).map((o,a)=>{if(typeof o=="string")return o.trim()?{name:zc(o,a),run:o.trim()}:null;if(!o||typeof o!="object")return null;let c=o,l=vo(c.run,c.command,c.cmd,c.script,c.shell);return l?{name:(vo(c.name,c.title,c.description)??zc(l,a)).slice(0,120),run:l,continueOnError:c.continueOnError===!0||c.continue_on_error===!0}:null}).filter(Boolean),s=e.requiredSecrets??e.required_secrets??e.secrets,i=Array.isArray(s)?s.filter(o=>typeof o=="string"):s&&typeof s=="object"?Object.keys(s):[];return{steps:n.slice(0,50),requiredSecrets:i.slice(0,50),notes:vo(e.notes,e.note,e.explanation)??""}}function vo(...r){for(let e of r)if(typeof e=="string"&&e.trim())return e.trim()}function zc(r,e){return(r.split(`
632
+ `)[0].trim()||`Step ${e+1}`).slice(0,120)}gr();ct();function To(r,e){if(!r.componentRoutes.length)return{project:r};let t=e.filter(Boolean);if(!t.length)return{error:`no Jira component set \u2014 project "${r.name}" routes by component (${r.componentRoutes.map(i=>i.component).join(", ")}); set one on the ticket`};let n=r.componentRoutes.filter(i=>t.includes(i.component));if(!n.length)return{error:`component(s) [${t.join(", ")}] not mapped \u2014 known: `+r.componentRoutes.map(i=>`${i.component}\u2192${i.repoName}`).join(", ")};let s=new Set(n.map(i=>i.repoName));return s.size>1?{error:`components map to DIFFERENT repos (${[...s].join(", ")}) \u2014 ambiguous, refusing`}:{project:{...r,repoName:n[0].repoName}}}var Gc=24*3600*1e3,Us=14,bm=Us*24*3600*1e3,wm=new Set(["to","on","this","the","a","an","env","environment","please","now","it"]),qs=class{constructor(e,t,n){this.cfg=e;this.jiraFor=t;this.transport=n}cfg;jiraFor;transport;projects=[];rules=[];environments=[];inFlight=new Set;repoQueues=new Map;envQueues=new Map;timer=null;ticking=!1;paused=!1;jiraOf(e){return this.jiraFor(e.repoName)}routingWarned=new Set;warnRoutingOnce(e,t){this.routingWarned.has(e)||(this.routingWarned.add(e),m.warn(`Component routing refused \u2014 ${t}`))}resolveClaudeProfile(e,t){if(!t)return;let n=this.cfg.claudeProfiles[t]?.configDir;return!n&&e&&(this.transport.send({type:"run.log",runId:e,seq:99e3,ts:new Date().toISOString(),level:"warn",message:`Claude profile "${t}" is not set up on this runner (allwright claude login "${t}") \u2014 using the runner's own login instead.`}),m.warn(`run ${e}: claude profile "${t}" missing locally \u2014 using default login`)),n}setConfig(e,t,n=!1,s=[]){this.projects=e,this.rules=t,this.environments=s;let i=t.filter(o=>o.enabled).length;m.info(`config synced: ${e.length} project(s), ${t.length} rule(s) (${i} enabled), ${s.length} environment(s)`),n!==this.paused&&(m.info(n?"polling paused from the dashboard":"polling resumed from the dashboard"),this.paused=n)}start(){let e=this.cfg.pollIntervalSeconds*1e3;this.timer=setInterval(()=>{this.tick()},e),this.tick(),m.info(`polling Jira every ${this.cfg.pollIntervalSeconds}s`)}stop(){this.timer&&clearInterval(this.timer)}lastScheduleCheck=0;auditInFlight=!1;async runScheduledAudits(){if(!(!this.cfg.auditSchedules.length||this.auditInFlight)&&!(Date.now()-this.lastScheduleCheck<15*6e4)){this.lastScheduleCheck=Date.now();for(let e of this.cfg.auditSchedules){let t=this.projects.find(s=>s.repoName===e.repoName);if(!t)continue;let n=Ku(t.id,e.role);if(!(n&&Date.now()-new Date(n).getTime()<e.intervalHours*36e5)){this.auditInFlight=!0;try{m.info(`Scheduled ${e.role} audit of ${e.repoName} starting (every ${e.intervalHours}h)`);let s=await Qr({projectId:t.id,repoPath:this.cfg.repos[e.repoName]?.path??"",role:e.role,scope:{kind:"repo",ref:""},model:"",claudeBin:this.cfg.claudeBin,jira:this.jiraFor(e.repoName)});if(s.ok){let i=s.audit.findings.length;m.info(`Scheduled audit done: ${i} finding(s) \u2014 drift visible on the Audits page`)}else m.warn(`Scheduled audit failed: ${s.error}`)}catch(s){m.warn(`Scheduled audit crashed: ${s instanceof Error?s.message:String(s)}`)}finally{this.auditInFlight=!1}break}}}}async tick(){if(!(this.ticking||this.paused||!this.transport.connected)){this.ticking=!0;try{await this.runScheduledAudits(),await this.sweepMergedPRs(),await this.sweepGitHubApprovals();let e=new Set;for(let t of this.rules){if(!t.enabled)continue;let n=this.projects.find(i=>i.id===t.projectId);if(!n)continue;let s=this.cfg.repos[n.repoName];if(!s){m.warn(`rule "${t.name}": no local path for repo "${n.repoName}" \u2014 run: allwright repo add "${n.repoName}" /path/to/checkout`);continue}t.action.type==="deploy"?await this.pollDeployRule(t,n,s.path):t.action.type==="respond"?await this.pollRespondRule(t,n,s.path):(e.has(n.id)||(e.add(n.id),await this.sweepNeedsInput(n)),t.trigger.type==="comment_keyword"&&await this.sweepRevisions(t,n),await this.pollRule(t,n,s.path))}}catch(e){m.warn(`poll tick failed: ${e instanceof Error?e.message:e}`)}finally{this.ticking=!1}}}async sweepGitHubApprovals(){let e=Object.values(Mn());if(!e.length)return;let t=ce()??this.cfg,n=new Map,s=i=>{let o=At(t,i);if(!o)return null;let a=n.get(o);return a||n.set(o,a=new Oe(o)),a};for(let i of e.slice(0,10)){let o=s(i.repoName);if(!o)continue;let a=`gh-approve:${i.runId}`;if(this.inFlight.has(a))continue;let c,l;try{[c,l]=await Promise.all([o.getReviews(i.owner,i.repo,i.prNumber),o.getPullRequest(i.owner,i.repo,i.prNumber)])}catch(S){m.warn(`review check failed for ${i.owner}/${i.repo}#${i.prNumber}: ${S instanceof Error?S.message:S}`);continue}if(!l)continue;let d={cfg:this.cfg,jiraFor:this.jiraFor,transport:this.transport};if(l.merged){m.info(`PR #${i.prNumber} for ${i.issueKey} was merged on GitHub \u2014 completing the run`),this.inFlight.add(a);try{await zn(d,i.runId,l.headSha)}finally{this.inFlight.delete(a)}continue}if(l.state==="closed"){m.info(`PR #${i.prNumber} for ${i.issueKey} was closed unmerged on GitHub \u2014 failing the run`);let S=this.jiraFor(i.repoName),x=`PR #${i.prNumber} was closed on GitHub without merging`;await S.addComment(i.issueKey,`**Allwright: the pull request for this ticket was closed on GitHub without merging.**
633
633
 
634
634
  PR: ${i.prUrl}
635
635
 
@@ -651,7 +651,7 @@ Note: the "${a.jiraTransitionOnMerge}" transition failed: ${v instanceof Error?v
651
651
 
652
652
  PR: ${a.prUrl} (merged at \`${l.headSha.slice(0,10)}\`)${p}
653
653
 
654
- (run \`${a.runId}\`)`)}catch(v){m.warn(`could not post merge comment to ${a.issueKey}: ${v instanceof Error?v.message:v}`);continue}m.info(`PR #${a.prNumber} for ${a.issueKey} merged \u2014 ticket updated`),Nn(a.runId)}}async sweepNeedsInput(e){let t;try{t=await this.jiraOf(e).search(`project = "${e.jiraProjectKey}" AND labels = "${kr.NEEDS_INPUT_LABEL}"`,10)}catch(s){m.warn(`needs-input sweep failed for ${e.jiraProjectKey}: ${s instanceof Error?s.message:s}`);return}if(!t.length)return;let n=sn();for(let s of t){let i=Object.values(n).filter(a=>a.issueKey===s.key);if(!i.length){await this.jiraOf(e).editLabels(s.key,{remove:[kr.NEEDS_INPUT_LABEL]}).catch(()=>{}),m.warn(`${s.key}: needs-input label with no local pending record \u2014 removed`);continue}let o=null;for(let a of i){let c=`resume:${a.runId}`;if(this.inFlight.has(c))continue;if(Date.now()-new Date(a.createdAt).getTime()>vm){this.inFlight.add(c),this.abandonStaleInput(a,e).finally(()=>this.inFlight.delete(c));continue}try{o=o??await this.jiraOf(e).getIssue(s.key)}catch(x){m.warn(`needs-input check failed for ${s.key}: ${x instanceof Error?x.message:x}`);continue}let l=new Date(a.questionsPostedAt).getTime(),d=o.comments.filter(x=>!Ge(x.body)&&new Date(x.created).getTime()>l);if(!d.length)continue;let p=Un(d),v=o.attachments;this.inFlight.add(c),m.info(`reply received on ${s.key} \u2014 resuming run ${a.runId}`),await this.jiraOf(e).editLabels(s.key,{remove:[kr.NEEDS_INPUT_LABEL]}).catch(x=>{m.warn(`could not remove needs-input label on ${s.key}: ${x}`)});let S={jiraFor:this.jiraFor,transport:this.transport,cfg:this.cfg};a.kind==="implement"?this.enqueueForRepo(a.baseRepoPath??a.repoPath,async()=>{try{await xc(a,p,v,S)}finally{this.inFlight.delete(c)}}):this.enqueueForRepo(a.repoPath,async()=>{try{await wc(a,p,v,S)}finally{this.inFlight.delete(c)}})}}}async abandonStaleInput(e,t){m.warn(`${e.issueKey}: needs-input unanswered for over ${Us}d \u2014 abandoning run ${e.runId}`);try{await this.jiraOf(t).addComment(e.issueKey,`**Allwright gave up waiting for an answer.**
654
+ (run \`${a.runId}\`)`)}catch(v){m.warn(`could not post merge comment to ${a.issueKey}: ${v instanceof Error?v.message:v}`);continue}m.info(`PR #${a.prNumber} for ${a.issueKey} merged \u2014 ticket updated`),Nn(a.runId)}}async sweepNeedsInput(e){let t;try{t=await this.jiraOf(e).search(`project = "${e.jiraProjectKey}" AND labels = "${kr.NEEDS_INPUT_LABEL}"`,10)}catch(s){m.warn(`needs-input sweep failed for ${e.jiraProjectKey}: ${s instanceof Error?s.message:s}`);return}if(!t.length)return;let n=sn();for(let s of t){let i=Object.values(n).filter(a=>a.issueKey===s.key);if(!i.length){await this.jiraOf(e).editLabels(s.key,{remove:[kr.NEEDS_INPUT_LABEL]}).catch(()=>{}),m.warn(`${s.key}: needs-input label with no local pending record \u2014 removed`);continue}let o=null;for(let a of i){let c=`resume:${a.runId}`;if(this.inFlight.has(c))continue;if(Date.now()-new Date(a.createdAt).getTime()>bm){this.inFlight.add(c),this.abandonStaleInput(a,e).finally(()=>this.inFlight.delete(c));continue}try{o=o??await this.jiraOf(e).getIssue(s.key)}catch(x){m.warn(`needs-input check failed for ${s.key}: ${x instanceof Error?x.message:x}`);continue}let l=new Date(a.questionsPostedAt).getTime(),d=o.comments.filter(x=>!Ge(x.body)&&new Date(x.created).getTime()>l);if(!d.length)continue;let p=Un(d),v=o.attachments;this.inFlight.add(c),m.info(`reply received on ${s.key} \u2014 resuming run ${a.runId}`),await this.jiraOf(e).editLabels(s.key,{remove:[kr.NEEDS_INPUT_LABEL]}).catch(x=>{m.warn(`could not remove needs-input label on ${s.key}: ${x}`)});let S={jiraFor:this.jiraFor,transport:this.transport,cfg:this.cfg};a.kind==="implement"?this.enqueueForRepo(a.baseRepoPath??a.repoPath,async()=>{try{await xc(a,p,v,S)}finally{this.inFlight.delete(c)}}):this.enqueueForRepo(a.repoPath,async()=>{try{await wc(a,p,v,S)}finally{this.inFlight.delete(c)}})}}}async abandonStaleInput(e,t){m.warn(`${e.issueKey}: needs-input unanswered for over ${Us}d \u2014 abandoning run ${e.runId}`);try{await this.jiraOf(t).addComment(e.issueKey,`**Allwright gave up waiting for an answer.**
655
655
 
656
656
  No reply arrived within ${Us} days of the question above. This ticket has been labeled \`${e.failedLabel}\`; remove it and re-trigger to try again. (run \`${e.runId}\`)`),await this.jiraOf(t).editLabels(e.issueKey,{add:[e.failedLabel],remove:[kr.NEEDS_INPUT_LABEL]})}catch(n){m.warn(`could not post staleness notice for ${e.issueKey}: ${n}`)}e.kind==="implement"&&await Yr(e.baseRepoPath??e.repoPath,e.repoPath).catch(()=>{}),Je(e.runId),this.transport.send({type:"run.status",runId:e.runId,status:"failed",error:`no reply within ${Us} days`})}async pollRule(e,t,n){let s=e.trigger.type==="label_added"?await this.matchLabelTrigger(e,t):await this.matchCommentTrigger(e,t);for(let i of s){let o=`${e.id}:${i.issueKey}`;if(this.inFlight.has(o))continue;let a=To(t,i.components??[]);if("error"in a){this.warnRoutingOnce(`${e.id}:${i.issueKey}`,`${i.issueKey}: ${a.error}`);continue}let c=a.project,l=c.repoName===t.repoName?n:this.cfg.repos[c.repoName]?.path;if(!l){this.warnRoutingOnce(`${e.id}:${i.issueKey}:path`,`${i.issueKey}: routed to repo "${c.repoName}" but it has no local checkout \u2014 run: allwright repo add "${c.repoName}" /path/to/checkout`);continue}let d=await this.transport.claimRun({ruleId:e.id,issueKey:i.issueKey,issueSummary:i.summary,triggerFingerprint:i.fingerprint,triggeredByAccountId:i.triggeredByAccountId});if(!d.accepted||!d.runId){d.reason!=="duplicate"&&m.warn(`claim rejected for ${i.issueKey}: ${d.reason??"unknown"}`);continue}this.inFlight.add(o),m.info(`claimed run ${d.runId} for ${i.issueKey}`+(c.repoName!==t.repoName?` (routed \u2192 ${c.repoName})`:"")+(d.claudeProfile?` (claude profile "${d.claudeProfile}")`:""));let p=this.resolveClaudeProfile(d.runId,d.claudeProfile);this.enqueueForRepo(l,async()=>{try{await _o({runId:d.runId,rule:e,project:c,issueKey:i.issueKey,repoPath:l,cfg:this.cfg,jira:this.jiraOf(c),transport:this.transport,claudeConfigDir:p,actorEmail:d.actorEmail})}finally{this.inFlight.delete(o)}})}}async pollRespondRule(e,t,n){let s=e.trigger;if(s.type!=="comment_keyword"||e.action.type!=="respond")return;let i=await this.jiraOf(t).search(`project = "${t.jiraProjectKey}" AND updated >= "-2d" ORDER BY updated DESC`,15),o=s.keyword.toLowerCase(),a=Date.now()-Gc;for(let c of i){let l=await this.jiraOf(t).getIssue(c.key);for(let d of l.comments){if(!d.body.toLowerCase().includes(o)||Ge(d.body)||new Date(d.created).getTime()<a||!d.id)continue;let p=`respond:${d.id}`;if(this.inFlight.has(p))continue;let v=To(t,c.components??[]);if("error"in v){this.warnRoutingOnce(`${e.id}:${c.key}`,`${c.key}: ${v.error}`);continue}let S=v.project,x=S.repoName===t.repoName?n:this.cfg.repos[S.repoName]?.path;if(!x){this.warnRoutingOnce(`${e.id}:${c.key}:path`,`${c.key}: routed to repo "${S.repoName}" but it has no local checkout \u2014 run: allwright repo add "${S.repoName}" /path/to/checkout`);continue}let w=await this.transport.claimRun({ruleId:e.id,issueKey:c.key,issueSummary:c.summary,triggerFingerprint:`question by ${d.author} at ${d.created}`,dedupKey:`respond:comment:${d.id}`,triggeredByAccountId:d.authorAccountId??void 0});if(!w.accepted||!w.runId){w.reason!=="duplicate"&&m.warn(`respond claim rejected for ${c.key}: ${w.reason??"unknown"}`);continue}this.inFlight.add(p),m.info(`claimed respond run ${w.runId}: ${c.key} (comment ${d.id})`+(S.repoName!==t.repoName?` (routed \u2192 ${S.repoName})`:"")+(w.claudeProfile?` (claude profile "${w.claudeProfile}")`:""));let j={author:d.author,body:d.body},U=this.resolveClaudeProfile(w.runId,w.claudeProfile);this.enqueueForRepo(x,async()=>{try{await _o({runId:w.runId,rule:e,project:S,issueKey:c.key,repoPath:x,cfg:this.cfg,jira:this.jiraOf(S),transport:this.transport,question:j,claudeConfigDir:U,actorEmail:w.actorEmail})}finally{this.inFlight.delete(p)}})}}}async sweepRevisions(e,t){let n=e.trigger;if(n.type!=="comment_keyword")return;let s;try{s=await this.jiraOf(t).search(`project = "${t.jiraProjectKey}" AND labels = "${n.doneLabel}" AND updated >= "-2d"`,10)}catch(o){m.warn(`revision sweep failed for ${t.jiraProjectKey}: ${o instanceof Error?o.message:o}`);return}let i=n.keyword.toLowerCase();for(let o of s)try{let a=await this.jiraOf(t).getIssue(o.key),c=null;for(let d of a.comments)Ge(d.body)&&(c=Math.max(c??0,new Date(d.created).getTime()));if(c===null||!a.comments.some(d=>!Ge(d.body)&&d.body.toLowerCase().includes(i)&&new Date(d.created).getTime()>c))continue;await this.jiraOf(t).editLabels(o.key,{remove:[n.doneLabel]}),m.info(`revision requested on ${o.key} (new "${n.keyword}" after completion) \u2014 done label removed, rule will re-fire`)}catch(a){m.warn(`revision check failed for ${o.key}: ${a instanceof Error?a.message:a}`)}}async pollDeployRule(e,t,n){if(e.action.type!=="deploy")return;let s=e.trigger.type==="status_changed"?await this.matchStatusDeploys(e,t):await this.matchCommentDeploys(e,t);for(let i of s){let o=`deploy:${i.dedupKey}`;if(this.inFlight.has(o))continue;let a=await this.transport.claimDeploy({projectId:t.id,ruleId:e.id,issueKey:i.issueKey,issueSummary:i.summary,environmentName:i.environmentName,requestedByAccountId:i.requestedByAccountId,requestedByDisplayName:i.requestedByDisplayName,dedupKey:i.dedupKey,triggerFingerprint:i.fingerprint});if(!a.accepted||!a.runId||!a.environment){if(a.code==="duplicate")continue;a.reason&&a.runId?(await this.jiraOf(t).addComment(i.issueKey,`**Allwright did not deploy this ticket.**
657
657
 
@@ -659,9 +659,9 @@ ${a.reason}`+(i.requestedByAccountId?`
659
659
 
660
660
  Jira account id: \`${i.requestedByAccountId}\``:"")+`
661
661
 
662
- (run \`${a.runId}\`)`).catch(l=>m.warn(`could not post refusal to ${i.issueKey}: ${l}`)),m.warn(`deploy refused for ${i.issueKey}: ${a.reason}`)):a.reason&&m.warn(`deploy claim rejected for ${i.issueKey}: ${a.reason}`);continue}let c=a.environment;this.inFlight.add(o),m.info(`claimed deploy ${a.runId}: ${i.issueKey} \u2192 ${c.name}`),this.enqueue(this.envQueues,c.id,async()=>{try{await zs({runId:a.runId,project:t,environment:c,issueKey:i.issueKey,issueSummary:i.summary,repoPath:n,cfg:this.cfg,jira:this.jiraOf(t),transport:this.transport,requestedBy:i.requestedByDisplayName})}finally{this.inFlight.delete(o)}})}}async matchCommentDeploys(e,t){let n=e.trigger,s=e.action;if(n.type!=="comment_keyword"||s.type!=="deploy")return[];let i=await this.jiraOf(t).search(`project = "${t.jiraProjectKey}" AND updated >= "-2d" ORDER BY updated DESC`,15),o=n.keyword.toLowerCase(),a=Date.now()-Gc,c=this.environments.filter(p=>p.projectId===t.id).map(p=>p.name),l=this.fixedEnvironmentName(s.environmentId),d=[];for(let p of i){let v=await this.jiraOf(t).getIssue(p.key);if(!(s.requireStatus&&v.status.toLowerCase()!==s.requireStatus.toLowerCase()))for(let S of v.comments){if(!S.body.toLowerCase().includes(o)||Ge(S.body)||new Date(S.created).getTime()<a||!S.id)continue;let x=s.envSelection==="fixed"?l:wm(S.body,n.keyword,c);d.push({issueKey:p.key,summary:p.summary,environmentName:x,requestedByAccountId:S.authorAccountId??void 0,requestedByDisplayName:S.author,dedupKey:`deploy:comment:${S.id}`,fingerprint:`comment "${n.keyword}" by ${S.author} at ${S.created}`+(x?` \u2192 ${x}`:"")})}}return d}async matchStatusDeploys(e,t){let n=e.trigger,s=e.action;if(n.type!=="status_changed"||s.type!=="deploy")return[];let i=await this.jiraOf(t).search(`project = "${t.jiraProjectKey}" AND status = "${n.status}" AND updated >= "-2d" ORDER BY updated DESC`,15),o=this.fixedEnvironmentName(s.environmentId),a=[];for(let c of i){let l=await this.jiraOf(t).lastEnteredStatus(c.key,n.status);l&&a.push({issueKey:c.key,summary:c.summary,environmentName:o,requestedByAccountId:l.authorAccountId??void 0,requestedByDisplayName:l.author,dedupKey:`deploy:status:${e.id}:${c.key}:${l.at}`,fingerprint:`moved to "${n.status}" by ${l.author} at ${l.at}`})}return a}fixedEnvironmentName(e){return e?this.environments.find(t=>t.id===e)?.name??"":""}async matchLabelTrigger(e,t){let n=e.trigger;if(n.type!=="label_added")return[];let s=`project = "${t.jiraProjectKey}" AND labels = "${n.label}" AND labels not in ("${n.doneLabel}", "${n.failedLabel}", "${kr.NEEDS_INPUT_LABEL}") ORDER BY updated ASC`;return(await this.jiraOf(t).search(s,10)).map(o=>({issueKey:o.key,summary:o.summary,components:o.components,fingerprint:`label "${n.label}" matched at ${new Date().toISOString()}`}))}async matchCommentTrigger(e,t){let n=e.trigger;if(n.type!=="comment_keyword")return[];let s=`project = "${t.jiraProjectKey}" AND updated >= "-2d" AND (labels IS EMPTY OR labels not in ("${n.doneLabel}", "${n.failedLabel}", "${kr.NEEDS_INPUT_LABEL}")) ORDER BY updated DESC`,i=await this.jiraOf(t).search(s,10),o=n.keyword.toLowerCase(),a=[];for(let c of i){let d=(await this.jiraOf(t).getIssue(c.key)).comments.find(p=>p.body.toLowerCase().includes(o)&&!Ge(p.body));d&&a.push({issueKey:c.key,components:c.components,summary:c.summary,fingerprint:`comment keyword "${n.keyword}" by ${d.author} at ${d.created}`,triggeredByAccountId:d.authorAccountId??void 0})}return a}async diagnoseRule(e,t){let n=e.trigger;if(e.action.type==="deploy"){let c=n.type==="status_changed"?await this.matchStatusDeploys(e,t):await this.matchCommentDeploys(e,t),l=c.filter(d=>d.environmentName);return{matchedCount:l.length,excludedCount:c.length-l.length,excludedSample:c.filter(d=>!d.environmentName).slice(0,5).map(d=>d.issueKey)}}if(n.type==="status_changed")return{matchedCount:(await this.jiraOf(t).search(`project = "${t.jiraProjectKey}" AND status = "${n.status}"`,50)).length,excludedCount:0,excludedSample:[]};if(n.type==="label_added"){let[c,l]=await Promise.all([this.jiraOf(t).search(`project = "${t.jiraProjectKey}" AND labels = "${n.label}" AND labels not in ("${n.doneLabel}", "${n.failedLabel}")`,50),this.jiraOf(t).search(`project = "${t.jiraProjectKey}" AND labels = "${n.label}" AND labels in ("${n.doneLabel}", "${n.failedLabel}")`,50)]);return{matchedCount:c.length,excludedCount:l.length,excludedSample:l.slice(0,5).map(d=>d.key)}}let s=n.keyword.toLowerCase(),[i,o]=await Promise.all([this.matchCommentTrigger(e,t),this.jiraOf(t).search(`project = "${t.jiraProjectKey}" AND updated >= "-2d" AND labels in ("${n.doneLabel}", "${n.failedLabel}")`,50)]),a=[];for(let c of o)(await this.jiraOf(t).getIssue(c.key)).comments.some(d=>d.body.toLowerCase().includes(s))&&a.push(c.key);return{matchedCount:i.length,excludedCount:a.length,excludedSample:a.slice(0,5)}}enqueueForRepo(e,t){this.enqueue(this.repoQueues,e,t)}runOnRepoQueue(e,t){this.enqueue(this.repoQueues,e,t)}runOnEnvironmentQueue(e,t){this.enqueue(this.envQueues,e,t)}enqueue(e,t,n){let i=(e.get(t)??Promise.resolve()).then(n).catch(o=>{m.error(`run crashed: ${o instanceof Error?o.stack:o}`)});e.set(t,i)}};function wm(r,e,t){let n=r.toLowerCase().indexOf(e.toLowerCase());if(n<0)return"";let i=r.slice(n+e.length).split(/[^\w.-]+/).filter(Boolean);for(let o of i){let a=t.find(c=>c.toLowerCase()===o.toLowerCase());if(a)return a}for(let o of i)if(!bm.has(o.toLowerCase()))return o;return""}var Sr=$(require("node:fs"),1),Jc=$(require("node:path"),1);var km=k.object({role:k.enum(["user","agent"]),text:k.string()}),Sm=k.object({sessionId:k.string(),projectId:k.string(),title:k.string().default(""),updatedAt:k.string(),messages:k.array(km).default([])}),Tm=k.record(Sm),xm=10,Cm=200,Wc=2e4;function Yc(){return Jc.default.join(ee(),"chat-sessions.json")}function xo(){let r=Yc();if(!Sr.default.existsSync(r))return{};try{return Tm.parse(JSON.parse(Sr.default.readFileSync(r,"utf8")))}catch{return{}}}function Em(r){Sr.default.mkdirSync(ee(),{recursive:!0,mode:448});let e=Yc(),t=e+".tmp";Sr.default.writeFileSync(t,JSON.stringify(r,null,2)+`
663
- `,{mode:384}),Sr.default.renameSync(t,e),Sr.default.chmodSync(e,384)}function Xc(r,e,t,n){let s=xo(),o=s[e]??{sessionId:e,projectId:r,title:t.slice(0,80),updatedAt:new Date().toISOString(),messages:[]};o.messages.push({role:"user",text:t.slice(0,Wc)},{role:"agent",text:n.slice(0,Wc)}),o.messages=o.messages.slice(-Cm),o.updatedAt=new Date().toISOString(),s[e]=o;let a=Object.values(s).filter(c=>c.projectId===o.projectId).sort((c,l)=>l.updatedAt.localeCompare(c.updatedAt));for(let c of a.slice(xm))delete s[c.sessionId];Em(s)}function Qc(r){return Object.values(xo()).filter(e=>e.projectId===r).sort((e,t)=>t.updatedAt.localeCompare(e.updatedAt)).map(e=>({sessionId:e.sessionId,title:e.title,updatedAt:e.updatedAt,messageCount:e.messages.length}))}function Co(r){return xo()[r]??null}var Gg=$(Gl(),1),Wg=$(Js(),1),Jg=$(ln(),1),Yg=$(Do(),1),Xg=$(Uo(),1),Qg=$(Vo(),1),nd=$(ei(),1),ey=$(rd(),1);var Go=nd.default;var Jo=$(require("node:crypto"),1),Xe=$(Se(),1);function ty(r){let e=r&&typeof r=="object"&&"name"in r?String(r.name):null;return e?`"${e}"`:"(unnamed)"}function Wo(r,e,t,n){r.push(`dropped ${e} ${t} \u2014 this runner is out of date and does not understand it yet (${n}). Update the runner (npm install -g @ticketpilot/runner) to pick it up.`)}function ry(r){if(!r||typeof r!="object"||r.type!=="config")return null;let e=r,t=[],n=[];for(let a of Array.isArray(e.projects)?e.projects:[]){let c=Xe.ProjectConfig.safeParse(a);c.success?n.push(c.data):Wo(t,"project","",c.error.issues[0]?.message??"invalid shape")}let s=[];for(let a of Array.isArray(e.rules)?e.rules:[]){let c=Xe.RuleConfig.safeParse(a);c.success?s.push(c.data):Wo(t,"rule",ty(a),c.error.issues[0]?.message??"invalid shape")}let i=[];for(let a of Array.isArray(e.environments)?e.environments:[]){let c=Xe.EnvironmentConfig.safeParse(a);c.success?i.push(c.data):Wo(t,"environment","",c.error.issues[0]?.message??"invalid shape")}return{msg:{type:"config",projects:n,rules:s,environments:i,pollingPaused:typeof e.pollingPaused=="boolean"?e.pollingPaused:!1},warnings:t}}var ny=2e4,sy=6e4,iy=5e3,ri=class{constructor(e,t,n,s){this.wsUrl=e;this.runnerToken=t;this.meta=n;this.events=s}wsUrl;runnerToken;meta;events;ws=null;queue=[];pending=new Map;backoffMs=1e3;heartbeat=null;closed=!1;bootAnnounced=!1;start(){this.closed=!1,this.connect()}stop(){this.closed=!0,this.heartbeat&&clearInterval(this.heartbeat),this.ws?.close()}get connected(){return this.ws?.readyState===Go.OPEN}connect(){if(this.closed)return;m.info(`connecting to control plane at ${this.wsUrl}`);let e=new Go(this.wsUrl,{headers:{authorization:`Bearer ${this.runnerToken}`}});this.ws=e,e.on("open",()=>{this.backoffMs=1e3,this.sendNow({type:"hello",protocolVersion:Xe.PROTOCOL_VERSION,runnerVersion:this.meta.runnerVersion,platform:`${process.platform}/${process.arch} node${process.versions.node}`,justBooted:!this.bootAnnounced});let t=this.queue.splice(0,this.queue.length);for(let n of t)this.sendNow(n);this.heartbeat&&clearInterval(this.heartbeat),this.heartbeat=setInterval(()=>{this.send({type:"heartbeat",ts:new Date().toISOString()})},ny)}),e.on("message",t=>{let n;try{n=JSON.parse(t.toString())}catch(i){m.warn(`ignoring malformed server message (bad JSON): ${i}`);return}let s;try{s=(0,Xe.parseServerMsg)(n)}catch(i){let o=ry(n);if(!o){m.warn(`ignoring malformed server message: ${i}`);return}for(let a of o.warnings)m.warn(a);m.warn(`config push had ${o.warnings.length} ${o.warnings.length===1?"entry":"entries"} this runner doesn't understand \u2014 applied everything else instead of dropping the whole config`),s=o.msg}this.handle(s)}),e.on("close",t=>{if(this.heartbeat&&clearInterval(this.heartbeat),t===4001)m.error("control plane rejected this runner version (protocol mismatch). Update with: npm install -g @ticketpilot/runner");else if(t===4003){m.error("this runner has been revoked from the control plane UI. Re-enroll with a fresh token if this was not intended."),this.closed=!0;return}if(this.closed)return;let n=Math.random()*.3+.85,s=Math.round(this.backoffMs*n);m.warn(`disconnected (code ${t}); reconnecting in ${Math.round(s/1e3)}s`),setTimeout(()=>this.connect(),s),this.backoffMs=Math.min(this.backoffMs*2,sy)}),e.on("error",t=>{m.warn(`websocket error: ${t.message}`)})}handle(e){if(e.type==="hello.ack"){this.bootAnnounced=!0,m.info(`connected as runner "${e.runnerName}" (${e.runnerId})`);return}if(e.type==="run.claim.result"||e.type==="deploy.claim.result"){let t=this.pending.get(e.requestId);t&&(clearTimeout(t.timer),this.pending.delete(e.requestId),t.resolve(e));return}if(e.type==="config")return this.events.onConfig(e);if(e.type==="project.test")return this.events.onProjectTest(e);if(e.type==="rule.diagnose")return this.events.onRuleDiagnose(e);if(e.type==="run.cancel")return this.events.onCancel(e.runId);if(e.type==="run.approved")return this.events.onApproved(e.runId,e.headSha);if(e.type==="run.rejected")return this.events.onRejected(e.runId);if(e.type==="run.retryPush")return this.events.onRetryPush(e.runId);if(e.type==="deploy.start")return this.events.onDeployStart(e);if(e.type==="deploy.suggest")return this.events.onDeploySuggest(e);if(e.type==="env.preflight")return this.events.onEnvPreflight(e);if(e.type==="chat.turn")return this.events.onChatTurn(e);if(e.type==="chat.create.ticket")return this.events.onChatCreateTicket(e);if(e.type==="chat.list")return this.events.onChatList(e);if(e.type==="chat.load")return this.events.onChatLoad(e);if(e.type==="board.fetch")return this.events.onBoardFetch(e);if(e.type==="board.trigger")return this.events.onBoardTrigger(e);if(e.type==="audit.start")return this.events.onAuditStart(e);if(e.type==="audit.list")return this.events.onAuditList(e);if(e.type==="audit.get")return this.events.onAuditGet(e);if(e.type==="audit.review")return this.events.onAuditReview(e);if(e.type==="knowledge.list")return this.events.onKnowledgeList(e);if(e.type==="knowledge.save")return this.events.onKnowledgeSave(e);if(e.type==="epic.list")return this.events.onEpicList(e);if(e.type==="epic.suggest")return this.events.onEpicSuggest(e);if(e.type==="team.creds")return this.events.onTeamCreds(e);if(e.type==="jira.users")return this.events.onJiraUsers(e);if(e.type==="setup.status")return this.events.onSetupStatus(e)}sendNow(e){this.ws?.send(JSON.stringify(e))}send(e){if(this.connected){this.sendNow(e);return}if(this.queue.length>=iy){let t=this.queue.findIndex(n=>n.type==="run.log");t>=0?this.queue.splice(t,1):this.queue.shift()}this.queue.push(e)}async claimRun(e){if(!this.connected)return{accepted:!1,reason:"control plane offline"};let t=Jo.default.randomUUID(),n=await new Promise(s=>{let i=setTimeout(()=>{this.pending.delete(t),s(null)},15e3);this.pending.set(t,{resolve:s,timer:i}),this.sendNow({type:"run.claim",requestId:t,...e})});return!n||n.type!=="run.claim.result"?{accepted:!1,reason:"claim timed out"}:{accepted:n.accepted,runId:n.runId,reason:n.reason,claudeProfile:n.claudeProfile,actorEmail:n.actorEmail}}async claimDeploy(e){if(!this.connected)return{accepted:!1,reason:"control plane offline"};let t=Jo.default.randomUUID(),n=await new Promise(s=>{let i=setTimeout(()=>{this.pending.delete(t),s(null)},15e3);this.pending.set(t,{resolve:s,timer:i}),this.sendNow({type:"deploy.claim",requestId:t,...e})});return!n||n.type!=="deploy.claim.result"?{accepted:!1,reason:"deploy authorization timed out"}:{accepted:n.accepted,runId:n.runId,environment:n.environment,reason:n.reason,code:n.code}}sendDeploySuggestResult(e,t){this.send({type:"deploy.suggest.result",requestId:e,...t})}sendChatTurnResult(e,t){this.send({type:"chat.turn.result",requestId:e,...t})}sendChatCreateTicketResult(e,t){this.send({type:"chat.create.ticket.result",requestId:e,...t,childKeys:t.childKeys??[]})}sendChatListResult(e,t){this.send({type:"chat.list.result",requestId:e,sessions:t})}sendChatLoadResult(e,t){this.send({type:"chat.load.result",requestId:e,...t})}sendBoardFetchResult(e,t){this.send({type:"board.fetch.result",requestId:e,...t,browseBaseUrl:t.browseBaseUrl??""})}sendAuditStartResult(e,t){this.send({type:"audit.start.result",requestId:e,...t})}sendAuditListResult(e,t){this.send({type:"audit.list.result",requestId:e,ok:t.ok,error:t.error,audits:t.audits??[]})}sendAuditGetResult(e,t){this.send({type:"audit.get.result",requestId:e,...t})}sendAuditReviewResult(e,t){this.send({type:"audit.review.result",requestId:e,...t})}sendKnowledgeListResult(e,t){this.send({type:"knowledge.list.result",requestId:e,ok:t.ok,error:t.error,files:t.files??[]})}sendKnowledgeSaveResult(e,t){this.send({type:"knowledge.save.result",requestId:e,...t})}sendEpicListResult(e,t){this.send({type:"epic.list.result",requestId:e,ok:t.ok,error:t.error,epics:t.epics??[],children:t.children??[]})}sendEpicSuggestResult(e,t){this.send({type:"epic.suggest.result",requestId:e,ok:t.ok,error:t.error,issueKey:t.issueKey??"",reason:t.reason??"",considered:t.considered??0})}sendTeamCredsResult(e,t){this.send({type:"team.creds.result",requestId:e,ok:t.ok,error:t.error,githubShared:t.githubShared??!1,sharedGithubLogin:t.sharedGithubLogin??"",entries:t.entries??[]})}sendBoardTriggerResult(e,t){this.send({type:"board.trigger.result",requestId:e,...t})}sendSetupStatusResult(e,t){this.send({type:"setup.status.result",requestId:e,ok:t.ok,error:t.error,jiraConfigured:t.jiraConfigured??!1,jiraEmail:t.jiraEmail??"",claude:t.claude,githubTokenSet:t.githubTokenSet??!1,githubLogin:t.githubLogin??"",deploysEnabled:t.deploysEnabled??!1,jiraUserCount:t.jiraUserCount??0,repos:t.repos??[]})}sendEnvPreflightResult(e,t){this.send({type:"env.preflight.result",requestId:e,...t})}sendJiraUsersResult(e,t){this.send({type:"jira.users.result",requestId:e,...t})}sendProjectTestResult(e,t,n){this.send({type:"project.test.result",requestId:e,ok:t,checks:n})}sendRuleDiagnoseResult(e,t){this.send({type:"rule.diagnose.result",requestId:e,...t})}};var gn=$(require("node:fs"),1),Yo=$(require("node:path"),1),id=require("node:child_process"),od=require("node:util");var sd=(0,od.promisify)(id.execFile);async function ni(r,e,t=[]){let n=[],s=r.repos[e.repoName]?.jira??r.jira;if(!s)n.push({name:"jira-credentials",ok:!1,detail:"no Jira credentials configured on this runner"});else{let o=new ze(s);try{let a=await o.myself();n.push({name:"jira-auth",ok:!0,detail:`authenticated as ${a.displayName}`});try{await o.search(`project = "${e.jiraProjectKey}" ORDER BY created DESC`,1),n.push({name:"jira-project",ok:!0,detail:`project ${e.jiraProjectKey} is readable`})}catch(c){n.push({name:"jira-project",ok:!1,detail:`cannot read project ${e.jiraProjectKey}: ${Gn(c)}`})}}catch(a){n.push({name:"jira-auth",ok:!1,detail:`Jira auth failed: ${Gn(a)}`})}}let i=r.repos[e.repoName];if(i&&gn.default.existsSync(i.path)){let o=Yo.default.join(i.path,"CLAUDE.md"),a=gn.default.existsSync(o)&&gn.default.readFileSync(o,"utf8").trim().length>0;n.push({name:"memory-file",ok:a,detail:a?"CLAUDE.md present \u2014 the agent has project memory":"MISSING: CLAUDE.md at the repo root. Rules can't be enabled until the project has a memory file \u2014 it is what makes every run smarter than the last."});let c=So(i.path);n.push({name:"deploy-doc",ok:c!==null,detail:c?`${c.path} present \u2014 deploy suggestions will follow it`:"MISSING: DEPLOY.md (or .ticketpilot/deploy.md). Environments can't be created until the repo documents how it deploys."})}if(!i)n.push({name:"repo-path",ok:!1,detail:`no local path mapped for repo "${e.repoName}" \u2014 run: allwright repo add "${e.repoName}" /path/to/checkout`});else if(!gn.default.existsSync(i.path))n.push({name:"repo-path",ok:!1,detail:`path does not exist: ${i.path}`});else{let o=gn.default.existsSync(Yo.default.join(i.path,".git"));n.push({name:"repo-path",ok:!0,detail:`${i.path}${o?" (git checkout)":" (warning: not a git checkout)"}`})}try{let{stdout:o}=await sd(r.claudeBin,["--version"],{timeout:15e3});n.push({name:"claude-code",ok:!0,detail:o.trim().slice(0,100)})}catch(o){n.push({name:"claude-code",ok:!1,detail:`cannot run "${r.claudeBin}": ${Gn(o)}`})}try{let{stdout:o}=await sd("git",["--version"],{timeout:15e3});n.push({name:"git",ok:!0,detail:o.trim().slice(0,100)})}catch(o){n.push({name:"git",ok:!1,detail:`cannot run git: ${Gn(o)}`})}if(r.github?.token)try{let{GitHubClient:o}=await Promise.resolve().then(()=>(ct(),tn)),a=await new o(r.github.token).whoami();n.push({name:"github-token",ok:!0,detail:`authenticated as ${a}`})}catch(o){n.push({name:"github-token",ok:!1,detail:Gn(o)})}else n.push({name:"github-token",ok:!0,detail:"not set \u2014 needed only for implement rules (allwright github set-token)"});if(t.length){r.deploy.enabled?n.push({name:"deploy",ok:!0,detail:"deployments enabled on this runner"}):n.push({name:"deploy",ok:!1,detail:"deployments are disabled on this runner \u2014 run `allwright deploy enable` to allow it to execute your saved deploy steps"});for(let o of t){let a=Jt(r,e.repoName,o.name),c=o.requiredSecrets.filter(l=>!a[l]&&!process.env[l]);n.push({name:`env:${o.name}`,ok:c.length===0,detail:c.length?`missing secret(s): ${c.join(", ")} \u2014 allwright env set "${e.repoName}" "${o.name}" ${c[0]}=...`:`${o.steps.length} step(s), ${o.requiredSecrets.length} secret(s) present`+(o.branch?`, deploys origin/${o.branch}`:"")})}}return n}function Gn(r){return(r instanceof Error?r.message:String(r)).slice(0,300)}var ae=new _a;ae.name("allwright").description("Allwright runner \u2014 runs on YOUR machine, holds YOUR credentials locally, connects outbound-only to the control plane. Your Jira token, Anthropic key and source code never leave this host.").version(vs);ae.command("init").description("Interactive setup: enroll this runner and store credentials locally").option("--cp-url <url>","control plane URL").option("--enroll-token <token>","enrolment token from the Allwright UI").option("--name <name>","runner name",fd.default.hostname()).option("--jira-url <url>","Jira base URL, e.g. https://yourorg.atlassian.net").option("--jira-email <email>","Jira account email").option("--jira-token <token>","Jira API token (stored locally only)").action(async r=>{let e=Rr.default.createInterface({input:process.stdin,output:process.stdout}),t=async(n,s,i=!1)=>{if(s)return s;let o=await e.question(`${n}: `);if(!o.trim())throw new Error(`${n} is required`);return o.trim()};try{let n=await t("Control plane URL",r.cpUrl),s=await t("Enrolment token (from the web UI)",r.enrollToken),i=await t("Jira base URL (https://yourorg.atlassian.net)",r.jiraUrl),o=await t("Jira account email",r.jiraEmail),a=await t("Jira API token (create at id.atlassian.com/manage-profile/security/api-tokens)",r.jiraToken,!0),c=Ti.parse({controlPlaneUrl:n,runnerName:r.name,jira:{baseUrl:i,email:o,apiToken:a}}),l=await new ze(c.jira).myself();m.info(`Jira credential OK \u2014 authenticated as ${l.displayName}`),c=await lu(c,s),m.info(`Enrolled as runner "${c.runnerName}" (${c.runnerId})`),m.info(`Credentials saved to ${wt()} (mode 600, this machine only)`),m.info("Next: map your repo with `allwright repo add <repoName> <localPath>`, then `allwright start`")}finally{e.close()}});var Qo=ae.command("repo").description("Map control-plane repo names to local checkouts");Qo.command("add <repoName> <localPath>").description("Map a repo name (as configured in the web UI) to a local checkout path").action(async(r,e)=>{let t=Q();t.repos[r]={path:e},ie(t),m.info(`mapped repo "${r}" -> ${e}`);try{let{originUrl:n}=await Promise.resolve().then(()=>(gr(),bu));m.info(` origin remote: ${await n(e)} \u2014 make sure this is the repo you meant`)}catch{m.warn(` could not read an origin remote at ${e} \u2014 is it a git checkout?`)}});Qo.command("list").description("Show configured repo mappings").action(()=>{let r=Q(),e=Object.entries(r.repos);if(!e.length)return m.info("no repos mapped yet");for(let[t,n]of e)m.info(`${t} -> ${n.path}`)});var md=ae.command("claude").description("Per-user Claude login profiles \u2014 each teammate's runs bill their OWN Claude account");md.command("login <profileName>").description("Create (or re-login) a named Claude profile. Opens Claude Code interactively with its own config directory \u2014 have the PERSON WHOSE ACCOUNT IT IS complete the /login flow with their credentials, then exit. Assign the profile to their user on the dashboard's Team page.").action(async r=>{if(!/^[a-zA-Z0-9._-]+$/.test(r))throw new Error("profile name: letters, digits, dots, dashes and underscores only");let e=Q(),t=e.claudeProfiles[r]?.configDir??`${wt().replace(/runner\.json$/,"")}claude-profiles/${r}`;yn.default.mkdirSync(t,{recursive:!0,mode:448}),e.claudeProfiles[r]={configDir:t},ie(e),m.info(`profile "${r}" -> ${t}`),m.info("Opening Claude Code with this profile. In it: run /login, complete the browser flow"),m.info("with the account this profile belongs to, then exit Claude (ctrl+c twice or /exit).");let n=(0,Wn.spawn)(e.claudeBin,[],{env:{...process.env,CLAUDE_CONFIG_DIR:t},stdio:"inherit"});await new Promise(s=>n.on("exit",()=>s())),m.info(`Done. Assign it on the dashboard: Team -> the user -> Claude profile = "${r}".`),m.info("Restart the background runner for this to take effect: allwright stop && allwright start")});md.command("list").description("Show configured Claude profiles and whether each looks logged in").action(()=>{let r=Q(),e=Object.entries(r.claudeProfiles);if(m.info("default: this OS user's own Claude login (no profile)"),!e.length)return m.info("no named profiles yet \u2014 allwright claude login <name>");for(let[t,n]of e){let s=yn.default.existsSync(n.configDir)&&yn.default.readdirSync(n.configDir).length>0;m.info(`${t} -> ${n.configDir} ${s?"(logged in)":"(NOT logged in yet)"}`)}});Qo.command("remove <repoName>").description("Unmap a repo from this runner: removes the mapping plus its per-repo Jira/GitHub overrides and env secrets from the config. Does NOT touch the checkout on disk or anything in the control plane \u2014 delete the project on the dashboard separately.").action(r=>{let e=Q();if(!e.repos[r]){let i=Object.keys(e.repos).join(", ")||"(none)";throw new Error(`unknown repo "${r}" \u2014 mapped repos: ${i}`)}let t=e.repos[r].path;delete e.repos[r];let n=Object.keys(e.environments).filter(i=>i.startsWith(`${r}:`));for(let i of n)delete e.environments[i];let s=e.auditSchedules.length;e.auditSchedules=e.auditSchedules.filter(i=>i.repoName!==r),ie(e),m.info(`Removed "${r}" (was ${t})`),n.length&&m.info(`Also removed ${n.length} environment secret set(s): ${n.join(", ")}`),e.auditSchedules.length!==s&&m.info("Also removed its audit schedule(s)"),m.info("The checkout on disk was NOT touched \u2014 remove it yourself if you want it gone."),m.info("Restart the runner to apply. Dashboard project (if any) is deleted separately there.")});var ea=ae.command("service").description("Run the runner as a system service (starts on boot, restarts on crash)");ea.command("install").description("Install + start the systemd service \u2014 detects node, this script, your user and home; no hand-written unit files. Run with sudo. (--print shows the unit without installing.)").option("--print","print the generated unit file and exit").action(r=>{if(r.print){m.info(`
664
- `+Xi(Yi()));return}Eu(m)});ea.command("uninstall").description("Stop and remove the systemd service (config/credentials untouched)").action(()=>Iu(m));ea.command("status").description("systemctl status for the runner service").action(()=>{(0,Wn.spawn)("systemctl",["status","allwright","--no-pager"],{stdio:"inherit"}).on("exit",e=>process.exit(e??0))});ae.command("update").description("Update the runner to the latest published version (npm install -g allwright@latest). Restart the runner afterwards \u2014 and only when no runs are active.").action(async()=>{m.info("Updating: npm install -g allwright@latest");let r=(0,Wn.spawn)("npm",["install","-g","allwright@latest"],{stdio:"inherit"});await new Promise((e,t)=>{r.on("exit",n=>n===0?e():t(new Error(`npm exited with code ${n}`))),r.on("error",t)}),m.info("Updated. Restart the runner service to load the new version (check active runs first).")});var Jn=ae.command("jira").description("Per-repo Jira site overrides \u2014 for projects living on a different Atlassian site");Jn.command("set <repoName>").description("Store Jira credentials for ONE repo's project (e.g. a project on a different *.atlassian.net site than the runner's main credential). Prompts on stdin; stored locally only, like every other credential.").action(async r=>{let e=Q();if(!e.repos[r]){let n=Object.keys(e.repos).join(", ")||"(none)";throw new Error(`unknown repo "${r}" \u2014 mapped repos: ${n}. Run \`allwright repo add\` first.`)}let t=Rr.default.createInterface({input:process.stdin,output:process.stdout});try{let n=(await t.question("Jira base URL for this repo (https://yourorg.atlassian.net): ")).trim(),s=(await t.question("Jira account email: ")).trim(),i=(await t.question("Jira API token (id.atlassian.com/manage-profile/security/api-tokens): ")).trim();if(!n||!s||!i)throw new Error("all three values are required");let o={baseUrl:n,email:s,apiToken:i},a=await new ze(o).myself();m.info(`Jira credential OK \u2014 authenticated as ${a.displayName} on ${n}`),e.repos[r].jira=o,ie(e),m.info(`Saved: repo "${r}" now polls ${n} (other repos keep the runner-wide credential)`),m.info("Restart the background runner for this to take effect: allwright stop && allwright start")}finally{t.close()}});Jn.command("show").description("Show which Jira site each repo uses (never prints tokens)").action(()=>{let r=Q();m.info(`runner-wide: ${r.jira?`${r.jira.baseUrl} (${r.jira.email})`:"(not configured)"}`);for(let[e,t]of Object.entries(r.repos))m.info(`${e} -> ${t.jira?`${t.jira.baseUrl} (${t.jira.email})`:"(runner-wide credential)"}`)});Jn.command("user-add <ticketpilotEmail>").description("Store a PERSON's own Jira credential, so board buttons and Compose tickets they click post to Jira under THEIR Atlassian identity instead of the runner's account. Keyed by their Allwright login email. Prompts on stdin; stored locally only. Picked up on the next click \u2014 no restart needed.").action(async r=>{let e=Q(),t=r.trim().toLowerCase();if(!t.includes("@"))throw new Error(`"${r}" doesn't look like an email`);let n=Rr.default.createInterface({input:process.stdin,output:process.stdout});try{let s=(await n.question(`Their ATLASSIAN account email [${t}]: `)).trim()||t,i=(await n.question("Their Jira API token (they create it at id.atlassian.com/manage-profile/security/api-tokens): ")).trim();if(!i)throw new Error("API token is required");let o=[e.jira,...Object.values(e.repos).map(l=>l.jira)].filter(l=>!!l),a=new Set,c=!1;for(let l of o)if(!a.has(l.baseUrl)){a.add(l.baseUrl);try{let d=await new ze({baseUrl:l.baseUrl,email:s,apiToken:i}).myself();m.info(`${l.baseUrl}: OK \u2014 authenticated as ${d.displayName}`),c=!0}catch{m.warn(`${l.baseUrl}: this credential does NOT work there (fine if they don't use that site)`)}}if(!c)throw new Error("credential failed on every configured Jira site \u2014 nothing saved");e.jiraUsers[t]={email:s,apiToken:i},ie(e),m.info(`Saved. Dashboard actions by ${t} now post to Jira as ${s}. No restart needed.`)}finally{n.close()}});Jn.command("user-list").description("Show which Allwright users have their own Jira credential here (never prints tokens)").action(()=>{let r=Q(),e=Object.entries(r.jiraUsers);if(!e.length)return m.info("none yet \u2014 everyone's dashboard clicks require one: allwright jira user-add <their-ticketpilot-email>");for(let[t,n]of e)m.info(`${t} -> posts to Jira as ${n.email}`)});Jn.command("user-remove <ticketpilotEmail>").description("Delete a person's stored Jira credential").action(r=>{let e=Q(),t=r.trim().toLowerCase();if(!e.jiraUsers[t])throw new Error(`no credential stored for ${t}`);delete e.jiraUsers[t],ie(e),m.info(`Removed. Dashboard actions by ${t} will now be refused until a new credential is added.`)});var _n=ae.command("github").description("GitHub credential for implement-mode rules");_n.command("set-token").description("Store a GitHub token for opening pull requests (implement rules). Stored locally only, like your Jira token. Recommended: a fine-grained PAT scoped to the repo with contents:write + pull_requests:write.").option("--token <token>","GitHub token (omit to be prompted)").action(async r=>{let e=Rr.default.createInterface({input:process.stdin,output:process.stdout});try{let t=r.token??(await e.question("GitHub token (fine-grained PAT recommended): ")).trim();if(!t)throw new Error("token is required");let{GitHubClient:n}=await Promise.resolve().then(()=>(ct(),tn)),s=await new n(t).whoami(),i=Q();i.github={token:t,login:s},ie(i),m.info(`GitHub token OK \u2014 authenticated as ${s}`),m.info(`Saved to ${wt()} (mode 600, this machine only)`)}finally{e.close()}});_n.command("set <repoName>").description("Store a GitHub token for ONE repo only \u2014 overrides the runner-wide token for that repo's PRs and PR-watching. Useful when projects need separately revocable access. Prompts on stdin; stored locally only.").action(async r=>{let e=Q();if(!e.repos[r]){let n=Object.keys(e.repos).join(", ")||"(none)";throw new Error(`unknown repo "${r}" \u2014 mapped repos: ${n}. Run \`allwright repo add\` first.`)}let t=Rr.default.createInterface({input:process.stdin,output:process.stdout});try{let n=(await t.question(`GitHub token for "${r}" (fine-grained PAT scoped to just this repo): `)).trim();if(!n)throw new Error("token is required");let{GitHubClient:s}=await Promise.resolve().then(()=>(ct(),tn)),i=await new s(n).whoami();e.repos[r].github={token:n,login:i},ie(e),m.info(`GitHub token OK \u2014 authenticated as ${i}`),m.info(`Saved: repo "${r}" now uses its own token (other repos keep the runner-wide one)`)}finally{t.close()}});_n.command("user-add <ticketpilotEmail>").description("Store a PERSON's own GitHub token, so PRs from implement runs THEY trigger are authored by their GitHub account. Keyed by their Allwright login email. Optional \u2014 without it their runs fall back to the repo/runner-wide token. Needs contents:write + pull_requests:write on the repos they'll touch.").action(async r=>{let e=Q(),t=r.trim().toLowerCase();if(!t.includes("@"))throw new Error(`"${r}" doesn't look like an email`);let n=Rr.default.createInterface({input:process.stdin,output:process.stdout});try{let s=(await n.question(`GitHub token for ${t}: `)).trim();if(!s)throw new Error("token is required");let{GitHubClient:i}=await Promise.resolve().then(()=>(ct(),tn)),o=await new i(s).whoami();e.githubUsers[t]={token:s,login:o},ie(e),m.info(`GitHub token OK \u2014 authenticated as ${o}`),m.info(`Saved. Implement runs triggered by ${t} now open PRs as ${o}. No restart needed.`)}finally{n.close()}});_n.command("user-list").description("Show which Allwright users have their own GitHub token here (never prints tokens)").action(()=>{let r=Q(),e=Object.entries(r.githubUsers);if(!e.length)return m.info("no per-user GitHub tokens \u2014 everyone's PRs use the repo/runner-wide token");for(let[t]of e)m.info(`${t} -> own GitHub token stored`)});_n.command("user-remove <ticketpilotEmail>").description("Delete a person's stored GitHub token (their runs fall back to the shared token)").action(r=>{let e=Q(),t=r.trim().toLowerCase();if(!e.githubUsers[t])throw new Error(`no GitHub token stored for ${t}`);delete e.githubUsers[t],ie(e),m.info(`Removed. ${t}'s runs use the repo/runner-wide token again.`)});_n.command("show").description("Show which GitHub token each repo and person would use (never prints tokens)").action(()=>{let r=Q();m.info(`runner-wide: ${r.github?.token?"token set":"(not configured)"}`);for(let[t,n]of Object.entries(r.repos))m.info(`${t} -> ${n.github?.token?"own repo token":"runner-wide token"}`);let e=Object.keys(r.githubUsers);m.info(e.length?`per-user tokens: ${e.join(", ")}`:"per-user tokens: (none)")});var ta=ae.command("audit").description("Recurring specialist audits on this runner");ta.command("schedule <repoName> <role> <intervalHours>").description("Audit this repo's project on a cadence (role: security|testing; interval in hours, min 6). Runs on the runner's own clock; reports land in the Audits page history, where the diff-vs-previous view shows drift. Advisory only \u2014 nothing blocks.").action((r,e,t)=>{let n=Q();if(!n.repos[r]){let i=Object.keys(n.repos).join(", ")||"(none)";throw new Error(`unknown repo "${r}" \u2014 mapped repos: ${i}`)}if(e!=="security"&&e!=="testing")throw new Error('role must be "security" or "testing"');let s=parseInt(t,10);if(!Number.isInteger(s)||s<6||s>720)throw new Error("intervalHours must be 6-720");n.auditSchedules=[...n.auditSchedules.filter(i=>!(i.repoName===r&&i.role===e)),{repoName:r,role:e,intervalHours:s}],ie(n),m.info(`Scheduled: ${e} audit of "${r}" every ${s}h. Restart the runner to apply.`)});ta.command("schedules").description("List scheduled audits").action(()=>{let r=Q();if(!r.auditSchedules.length)return m.info("no scheduled audits \u2014 allwright audit schedule <repo> <role> <hours>");for(let e of r.auditSchedules)m.info(`${e.repoName} \xB7 ${e.role} \xB7 every ${e.intervalHours}h`)});ta.command("unschedule <repoName> <role>").description("Remove a scheduled audit").action((r,e)=>{let t=Q(),n=t.auditSchedules.length;if(t.auditSchedules=t.auditSchedules.filter(s=>!(s.repoName===r&&s.role===e)),t.auditSchedules.length===n)throw new Error("no such schedule");ie(t),m.info("Removed. Restart the runner to apply.")});var ra=ae.command("deploy").description("Deployment settings for this machine");ra.command("enable").description("Allow this runner to execute the deploy steps saved in the dashboard. Those steps are shell commands that run here, as this user \u2014 so this switch lives on the machine, not in the web UI, and only someone with shell access can flip it.").action(()=>{let r=Q();r.deploy={enabled:!0},ie(r),m.info("deployments ENABLED on this runner"),m.info("This runner will now execute the deploy steps configured for your environments. Review them in the dashboard before shipping to production."),m.info("Restart the background runner for this to take effect: allwright stop && allwright start")});ra.command("disable").description("Stop this runner from executing any deploy steps").action(()=>{let r=Q();r.deploy={enabled:!1},ie(r),m.info("deployments DISABLED on this runner"),m.info("Restart the background runner for this to take effect: allwright stop && allwright start")});ra.command("status").description("Show whether deployments are enabled here, and which env secrets are stored").action(()=>{let r=Q();m.info(`deployments: ${r.deploy.enabled?"enabled":"disabled"}`);let e=Object.entries(r.environments);if(!e.length)return m.info("no environment secrets stored");for(let[t,n]of e){let s=Object.keys(n.secrets);m.info(`${t}: ${s.length?s.join(", "):"(no secrets)"}`)}});var na=ae.command("env").description("Per-environment deploy secrets. Values stay on this machine, like your Jira token.");na.command("set <repoName> <envName> <assignments...>").description('Store secrets for one environment, e.g. env set acme/api production "SSH_HOST=1.2.3.4" "SSH_USER=deploy". Your deploy steps reference these as $SSH_HOST. The control plane only ever learns the NAMES.').action((r,e,t)=>{let n=Q(),s=as(r,e),i=n.environments[s]??{secrets:{}},o=[];for(let a of t){let c=a.indexOf("=");if(c<=0)throw new Error(`expected KEY=VALUE, got "${a}"`);let l=a.slice(0,c).trim();i.secrets[l]=a.slice(c+1),o.push(l)}n.environments[s]=i,ie(n),m.info(`stored ${o.length} secret(s) for ${s}: ${o.join(", ")}`),m.info(`Saved to ${wt()} (mode 600, this machine only)`),m.info("Restart the background runner to pick these up: allwright stop && allwright start")});na.command("unset <repoName> <envName> <names...>").description("Remove stored secrets for an environment").action((r,e,t)=>{let n=Q(),s=as(r,e),i=n.environments[s];if(!i)return m.info(`nothing stored for ${s}`);for(let o of t)delete i.secrets[o];n.environments[s]=i,ie(n),m.info(`removed ${t.join(", ")} from ${s}`)});na.command("list").description("Show which environments have secrets stored here (names only, never values)").action(()=>{let r=Q(),e=Object.entries(r.environments);if(!e.length)return m.info("no environment secrets stored");for(let[t,n]of e)m.info(`${t}: ${Object.keys(n.secrets).join(", ")||"(none)"}`)});ae.command("export [file]").description("Back up ALL runner state (config+secrets, knowledge, audits, chats) to one tarball").action(r=>{try{let e=$a(r);m.info(`Backup written: ${e.file} (${e.entries.length} entries, mode 600)`),m.warn("This file CONTAINS YOUR SECRETS (Jira/GitHub tokens). Keep it private \u2014 anyone holding it can act as this runner."),m.info(`Restore on any machine with: allwright import ${pd.default.basename(e.file)}`)}catch(e){m.error(e instanceof Error?e.message:String(e)),process.exitCode=1}});ae.command("import <file>").description("Restore runner state from an `export` tarball (existing config is kept as a .bak dir)").action(r=>{let e=qr();if(e&&Tn(e)){m.error("the runner is running \u2014 stop it first (systemctl stop allwright, or `allwright stop` for a pid-file daemon), then import."),process.exitCode=1;return}try{let t=Pa(r);m.info(`Restored ${t.restored.length} entries into ${ee()}`),t.previousDir&&m.info(`Previous config kept at ${t.previousDir}`),m.info("Start the runner and it will reconnect with the restored identity.")}catch(t){m.error(t instanceof Error?t.message:String(t)),process.exitCode=1}});ae.command("test").description("Check local setup: Jira auth, repo mappings, Claude Code binary").action(async()=>{let r=Q(),e=Object.keys(r.repos);if(!r.jira){m.error("no Jira credentials configured \u2014 run `allwright init`"),process.exitCode=1;return}let t=e.length?e.map(s=>({jiraProjectKey:"*",repoName:s})):[{jiraProjectKey:"*",repoName:"(none mapped)"}],n=!0;for(let s of t){let i=await ni(r,s);for(let o of i){if(s.jiraProjectKey==="*"&&o.name==="jira-project")continue;let a=o.ok?"PASS":"FAIL";(o.ok?m.info:m.error)(`[${a}] ${o.name}: ${o.detail}`),n&&=o.ok}}n||(process.exitCode=1)});function uy(r){if(!r.runnerToken)throw new Error("runner not enrolled \u2014 run `allwright init`");if(!r.jira)throw new Error("no Jira credentials \u2014 run `allwright init`");let e=new ze(r.jira),t=new Map,n=f=>{let g=r.repos[f]?.jira;if(!g)return e;let b=t.get(f);return b||(b=new ze(g),t.set(f,b)),b},s=new Map,i=(f,g)=>{let b=Su(ce()??r,f,g);switch(b.kind){case"legacy":return{jira:n(f),authored:!1};case"self":return{jira:n(f),authored:!0};case"missing":return{error:b.error};case"user":{let I=`${b.creds.baseUrl}:${b.creds.email}:${b.creds.apiToken.slice(-6)}`,N=s.get(I);return N||(N=new ze(b.creds),s.set(I,N)),{jira:N,authored:!0}}}},o=new URL("/api/runner/ws",r.controlPlaneUrl);o.protocol=o.protocol==="https:"?"wss:":"ws:";let a=[],c=[],l=[],d,p={cfg:r,jiraFor:n,transport:null},v=new Set,S=f=>{let g=a.find(I=>I.id===f),b=g&&r.repos[g.repoName];return g&&b?{project:g,repoPath:b.path}:null},x={cfg:r,jiraFor:n,get transport(){return p.transport},lookup:(f,g)=>{let b=S(f),I=l.find(N=>N.projectId===f&&N.name===g);return b&&I?{...b,environment:I}:null}},w=new ri(o.toString(),r.runnerToken,{runnerVersion:vs},{onConfig:f=>{a=f.projects,c=f.rules,l=f.environments,d.setConfig(f.projects,f.rules,f.pollingPaused,f.environments)},onProjectTest:async f=>{let g=a.find(I=>I.id===f.projectId);if(!g){w.sendProjectTestResult(f.requestId,!1,[{name:"config",ok:!1,detail:"project not in this runner's synced config yet"}]);return}m.info(`running connection test for project "${g.name}"`);let b=await ni(r,g,l.filter(I=>I.projectId===g.id));w.sendProjectTestResult(f.requestId,b.every(I=>I.ok),b)},onRuleDiagnose:async f=>{let g=c.find(z=>z.id===f.ruleId),b=g&&a.find(z=>z.id===g.projectId);if(!g||!b){w.sendRuleDiagnoseResult(f.requestId,{checks:[{name:"config",ok:!1,detail:"rule not in this runner's synced config yet"}],matchedCount:0,excludedCount:0,excludedSample:[]});return}m.info(`diagnosing rule "${g.name}"`);let I=await ni(r,b,g.action.type==="deploy"?l.filter(z=>z.projectId===b.id):[]),N=g.action.type==="implement"?I:I.filter(z=>z.name!=="github-token"),{matchedCount:V,excludedCount:W,excludedSample:J}=await d.diagnoseRule(g,b);w.sendRuleDiagnoseResult(f.requestId,{checks:N,matchedCount:V,excludedCount:W,excludedSample:J})},onCancel:f=>{m.warn(`cancel requested for run ${f} \u2014 not supported in this version, run will finish or time out`)},onApproved:(f,g)=>{if(ko(f)){Bc(x,f).catch(b=>m.error(`deploy approval crashed for ${f}: ${b instanceof Error?b.stack:b}`));return}zn(p,f,g).catch(b=>m.error(`approval handling crashed for ${f}: ${b instanceof Error?b.stack:b}`))},onRetryPush:f=>{let g=$s(f),b=()=>Rc(p,f).catch(I=>m.error(`retry push crashed for ${f}: ${I instanceof Error?I.stack:I}`));g?d.runOnRepoQueue(g.baseRepoPath,b):b()},onRejected:f=>{if(ko(f)){Fc(x,f).catch(g=>m.error(`deploy rejection crashed for ${f}: ${g instanceof Error?g.stack:g}`));return}Ac(p,f).catch(g=>m.error(`rejection handling crashed for ${f}: ${g instanceof Error?g.stack:g}`))},onDeployStart:f=>{let g=`${f.runId}#${f.attempt}`;if(v.has(g))return;v.add(g);let b=S(f.projectId);if(!b){let I="this runner has no local checkout mapped for that project \u2014 run: allwright repo add <repoName> /path/to/checkout";m.error(`deploy ${f.runId}: ${I}`),w.send({type:"run.status",runId:f.runId,status:"failed",error:I});return}m.info(`deploy ${f.runId} requested from the dashboard: ${f.issueKey} \u2192 ${f.environment.name}`),d.runOnEnvironmentQueue(f.environment.id,()=>zs({runId:f.runId,project:b.project,environment:f.environment,issueKey:f.issueKey,issueSummary:f.issueSummary,repoPath:b.repoPath,cfg:r,jira:n(b.project.repoName),transport:w,requestedBy:f.requestedBy}).catch(I=>m.error(`deploy crashed for ${f.runId}: ${I instanceof Error?I.stack:I}`)))},onDeploySuggest:async f=>{let g=S(f.projectId);if(!g){w.sendDeploySuggestResult(f.requestId,{ok:!1,steps:[],requiredSecrets:[],notes:"",error:"this runner has no local checkout mapped for that project"});return}m.info(`asking Claude Code for "${f.environmentName}" deploy steps in ${g.repoPath}`);let b=await Hc({repoPath:g.repoPath,repoName:g.project.repoName,environmentName:f.environmentName,notes:f.notes,timeoutSeconds:f.timeoutSeconds,cfg:r});w.sendDeploySuggestResult(f.requestId,b)},onEnvPreflight:async f=>{let g=S(f.projectId);if(!g){w.sendEnvPreflightResult(f.requestId,{ok:!1,checks:[{name:"repo",ok:!1,detail:"no local checkout mapped for that project"}]});return}let b=await Vc({repoPath:g.repoPath,repoName:g.project.repoName,environmentName:f.environmentName,steps:f.steps,requiredSecrets:f.requiredSecrets,workdir:f.workdir,branch:f.branch,cfg:r});w.sendEnvPreflightResult(f.requestId,b)},onChatTurn:async f=>{let g=S(f.projectId);if(!g){w.sendChatTurnResult(f.requestId,{ok:!1,sessionId:f.sessionId??"",reply:"",error:"this runner has no local checkout mapped for that project"});return}let b=f.sessionId||(0,Xo.randomUUID)(),I=!f.sessionId;if((I?0:Co(b)?.messages.length??0)>=44){w.sendChatTurnResult(f.requestId,{ok:!1,sessionId:b,reply:"",error:"this chat has hit its length limit \u2014 every turn re-reads the whole conversation, so long chats get slow and expensive. Start a new chat (it keeps the repo knowledge; only the conversation resets)."});return}let V=f.files.length?Na(g.repoPath,f.requestId,f.files):null,W="```",J=I?`You are the project assistant for "${g.project.name}" \u2014 this working directory is its repository, and you have read-only access.
662
+ (run \`${a.runId}\`)`).catch(l=>m.warn(`could not post refusal to ${i.issueKey}: ${l}`)),m.warn(`deploy refused for ${i.issueKey}: ${a.reason}`)):a.reason&&m.warn(`deploy claim rejected for ${i.issueKey}: ${a.reason}`);continue}let c=a.environment;this.inFlight.add(o),m.info(`claimed deploy ${a.runId}: ${i.issueKey} \u2192 ${c.name}`),this.enqueue(this.envQueues,c.id,async()=>{try{await zs({runId:a.runId,project:t,environment:c,issueKey:i.issueKey,issueSummary:i.summary,repoPath:n,cfg:this.cfg,jira:this.jiraOf(t),transport:this.transport,requestedBy:i.requestedByDisplayName})}finally{this.inFlight.delete(o)}})}}async matchCommentDeploys(e,t){let n=e.trigger,s=e.action;if(n.type!=="comment_keyword"||s.type!=="deploy")return[];let i=await this.jiraOf(t).search(`project = "${t.jiraProjectKey}" AND updated >= "-2d" ORDER BY updated DESC`,15),o=n.keyword.toLowerCase(),a=Date.now()-Gc,c=this.environments.filter(p=>p.projectId===t.id).map(p=>p.name),l=this.fixedEnvironmentName(s.environmentId),d=[];for(let p of i){let v=await this.jiraOf(t).getIssue(p.key);if(!(s.requireStatus&&v.status.toLowerCase()!==s.requireStatus.toLowerCase()))for(let S of v.comments){if(!S.body.toLowerCase().includes(o)||Ge(S.body)||new Date(S.created).getTime()<a||!S.id)continue;let x=s.envSelection==="fixed"?l:km(S.body,n.keyword,c);d.push({issueKey:p.key,summary:p.summary,environmentName:x,requestedByAccountId:S.authorAccountId??void 0,requestedByDisplayName:S.author,dedupKey:`deploy:comment:${S.id}`,fingerprint:`comment "${n.keyword}" by ${S.author} at ${S.created}`+(x?` \u2192 ${x}`:"")})}}return d}async matchStatusDeploys(e,t){let n=e.trigger,s=e.action;if(n.type!=="status_changed"||s.type!=="deploy")return[];let i=await this.jiraOf(t).search(`project = "${t.jiraProjectKey}" AND status = "${n.status}" AND updated >= "-2d" ORDER BY updated DESC`,15),o=this.fixedEnvironmentName(s.environmentId),a=[];for(let c of i){let l=await this.jiraOf(t).lastEnteredStatus(c.key,n.status);l&&a.push({issueKey:c.key,summary:c.summary,environmentName:o,requestedByAccountId:l.authorAccountId??void 0,requestedByDisplayName:l.author,dedupKey:`deploy:status:${e.id}:${c.key}:${l.at}`,fingerprint:`moved to "${n.status}" by ${l.author} at ${l.at}`})}return a}fixedEnvironmentName(e){return e?this.environments.find(t=>t.id===e)?.name??"":""}async matchLabelTrigger(e,t){let n=e.trigger;if(n.type!=="label_added")return[];let s=`project = "${t.jiraProjectKey}" AND labels = "${n.label}" AND labels not in ("${n.doneLabel}", "${n.failedLabel}", "${kr.NEEDS_INPUT_LABEL}") ORDER BY updated ASC`;return(await this.jiraOf(t).search(s,10)).map(o=>({issueKey:o.key,summary:o.summary,components:o.components,fingerprint:`label "${n.label}" matched at ${new Date().toISOString()}`}))}async matchCommentTrigger(e,t){let n=e.trigger;if(n.type!=="comment_keyword")return[];let s=`project = "${t.jiraProjectKey}" AND updated >= "-2d" AND (labels IS EMPTY OR labels not in ("${n.doneLabel}", "${n.failedLabel}", "${kr.NEEDS_INPUT_LABEL}")) ORDER BY updated DESC`,i=await this.jiraOf(t).search(s,10),o=n.keyword.toLowerCase(),a=[];for(let c of i){let d=(await this.jiraOf(t).getIssue(c.key)).comments.find(p=>p.body.toLowerCase().includes(o)&&!Ge(p.body));d&&a.push({issueKey:c.key,components:c.components,summary:c.summary,fingerprint:`comment keyword "${n.keyword}" by ${d.author} at ${d.created}`,triggeredByAccountId:d.authorAccountId??void 0})}return a}async diagnoseRule(e,t){let n=e.trigger;if(e.action.type==="deploy"){let c=n.type==="status_changed"?await this.matchStatusDeploys(e,t):await this.matchCommentDeploys(e,t),l=c.filter(d=>d.environmentName);return{matchedCount:l.length,excludedCount:c.length-l.length,excludedSample:c.filter(d=>!d.environmentName).slice(0,5).map(d=>d.issueKey)}}if(n.type==="status_changed")return{matchedCount:(await this.jiraOf(t).search(`project = "${t.jiraProjectKey}" AND status = "${n.status}"`,50)).length,excludedCount:0,excludedSample:[]};if(n.type==="label_added"){let[c,l]=await Promise.all([this.jiraOf(t).search(`project = "${t.jiraProjectKey}" AND labels = "${n.label}" AND labels not in ("${n.doneLabel}", "${n.failedLabel}")`,50),this.jiraOf(t).search(`project = "${t.jiraProjectKey}" AND labels = "${n.label}" AND labels in ("${n.doneLabel}", "${n.failedLabel}")`,50)]);return{matchedCount:c.length,excludedCount:l.length,excludedSample:l.slice(0,5).map(d=>d.key)}}let s=n.keyword.toLowerCase(),[i,o]=await Promise.all([this.matchCommentTrigger(e,t),this.jiraOf(t).search(`project = "${t.jiraProjectKey}" AND updated >= "-2d" AND labels in ("${n.doneLabel}", "${n.failedLabel}")`,50)]),a=[];for(let c of o)(await this.jiraOf(t).getIssue(c.key)).comments.some(d=>d.body.toLowerCase().includes(s))&&a.push(c.key);return{matchedCount:i.length,excludedCount:a.length,excludedSample:a.slice(0,5)}}enqueueForRepo(e,t){this.enqueue(this.repoQueues,e,t)}runOnRepoQueue(e,t){this.enqueue(this.repoQueues,e,t)}runOnEnvironmentQueue(e,t){this.enqueue(this.envQueues,e,t)}enqueue(e,t,n){let i=(e.get(t)??Promise.resolve()).then(n).catch(o=>{m.error(`run crashed: ${o instanceof Error?o.stack:o}`)});e.set(t,i)}};function km(r,e,t){let n=r.toLowerCase().indexOf(e.toLowerCase());if(n<0)return"";let i=r.slice(n+e.length).split(/[^\w.-]+/).filter(Boolean);for(let o of i){let a=t.find(c=>c.toLowerCase()===o.toLowerCase());if(a)return a}for(let o of i)if(!wm.has(o.toLowerCase()))return o;return""}var Sr=$(require("node:fs"),1),Jc=$(require("node:path"),1);var Sm=k.object({role:k.enum(["user","agent"]),text:k.string()}),Tm=k.object({sessionId:k.string(),projectId:k.string(),title:k.string().default(""),updatedAt:k.string(),messages:k.array(Sm).default([])}),xm=k.record(Tm),Cm=10,Em=200,Wc=2e4;function Yc(){return Jc.default.join(ee(),"chat-sessions.json")}function xo(){let r=Yc();if(!Sr.default.existsSync(r))return{};try{return xm.parse(JSON.parse(Sr.default.readFileSync(r,"utf8")))}catch{return{}}}function Im(r){Sr.default.mkdirSync(ee(),{recursive:!0,mode:448});let e=Yc(),t=e+".tmp";Sr.default.writeFileSync(t,JSON.stringify(r,null,2)+`
663
+ `,{mode:384}),Sr.default.renameSync(t,e),Sr.default.chmodSync(e,384)}function Xc(r,e,t,n){let s=xo(),o=s[e]??{sessionId:e,projectId:r,title:t.slice(0,80),updatedAt:new Date().toISOString(),messages:[]};o.messages.push({role:"user",text:t.slice(0,Wc)},{role:"agent",text:n.slice(0,Wc)}),o.messages=o.messages.slice(-Em),o.updatedAt=new Date().toISOString(),s[e]=o;let a=Object.values(s).filter(c=>c.projectId===o.projectId).sort((c,l)=>l.updatedAt.localeCompare(c.updatedAt));for(let c of a.slice(Cm))delete s[c.sessionId];Im(s)}function Qc(r){return Object.values(xo()).filter(e=>e.projectId===r).sort((e,t)=>t.updatedAt.localeCompare(e.updatedAt)).map(e=>({sessionId:e.sessionId,title:e.title,updatedAt:e.updatedAt,messageCount:e.messages.length}))}function Co(r){return xo()[r]??null}var Wg=$(Gl(),1),Jg=$(Js(),1),Yg=$(ln(),1),Xg=$(Do(),1),Qg=$(Uo(),1),ey=$(Vo(),1),nd=$(ei(),1),ty=$(rd(),1);var Go=nd.default;var Jo=$(require("node:crypto"),1),Xe=$(Se(),1);function ry(r){let e=r&&typeof r=="object"&&"name"in r?String(r.name):null;return e?`"${e}"`:"(unnamed)"}function Wo(r,e,t,n){r.push(`dropped ${e} ${t} \u2014 this runner is out of date and does not understand it yet (${n}). Update the runner (npm install -g @ticketpilot/runner) to pick it up.`)}function ny(r){if(!r||typeof r!="object"||r.type!=="config")return null;let e=r,t=[],n=[];for(let a of Array.isArray(e.projects)?e.projects:[]){let c=Xe.ProjectConfig.safeParse(a);c.success?n.push(c.data):Wo(t,"project","",c.error.issues[0]?.message??"invalid shape")}let s=[];for(let a of Array.isArray(e.rules)?e.rules:[]){let c=Xe.RuleConfig.safeParse(a);c.success?s.push(c.data):Wo(t,"rule",ry(a),c.error.issues[0]?.message??"invalid shape")}let i=[];for(let a of Array.isArray(e.environments)?e.environments:[]){let c=Xe.EnvironmentConfig.safeParse(a);c.success?i.push(c.data):Wo(t,"environment","",c.error.issues[0]?.message??"invalid shape")}return{msg:{type:"config",projects:n,rules:s,environments:i,pollingPaused:typeof e.pollingPaused=="boolean"?e.pollingPaused:!1},warnings:t}}var sy=2e4,iy=6e4,oy=5e3,ri=class{constructor(e,t,n,s){this.wsUrl=e;this.runnerToken=t;this.meta=n;this.events=s}wsUrl;runnerToken;meta;events;ws=null;queue=[];pending=new Map;backoffMs=1e3;heartbeat=null;closed=!1;bootAnnounced=!1;start(){this.closed=!1,this.connect()}stop(){this.closed=!0,this.heartbeat&&clearInterval(this.heartbeat),this.ws?.close()}get connected(){return this.ws?.readyState===Go.OPEN}connect(){if(this.closed)return;m.info(`connecting to control plane at ${this.wsUrl}`);let e=new Go(this.wsUrl,{headers:{authorization:`Bearer ${this.runnerToken}`}});this.ws=e,e.on("open",()=>{this.backoffMs=1e3,this.sendNow({type:"hello",protocolVersion:Xe.PROTOCOL_VERSION,runnerVersion:this.meta.runnerVersion,platform:`${process.platform}/${process.arch} node${process.versions.node}`,justBooted:!this.bootAnnounced});let t=this.queue.splice(0,this.queue.length);for(let n of t)this.sendNow(n);this.heartbeat&&clearInterval(this.heartbeat),this.heartbeat=setInterval(()=>{this.send({type:"heartbeat",ts:new Date().toISOString()})},sy)}),e.on("message",t=>{let n;try{n=JSON.parse(t.toString())}catch(i){m.warn(`ignoring malformed server message (bad JSON): ${i}`);return}let s;try{s=(0,Xe.parseServerMsg)(n)}catch(i){let o=ny(n);if(!o){m.warn(`ignoring malformed server message: ${i}`);return}for(let a of o.warnings)m.warn(a);m.warn(`config push had ${o.warnings.length} ${o.warnings.length===1?"entry":"entries"} this runner doesn't understand \u2014 applied everything else instead of dropping the whole config`),s=o.msg}this.handle(s)}),e.on("close",t=>{if(this.heartbeat&&clearInterval(this.heartbeat),t===4001)m.error("control plane rejected this runner version (protocol mismatch). Update with: npm install -g @ticketpilot/runner");else if(t===4003){m.error("this runner has been revoked from the control plane UI. Re-enroll with a fresh token if this was not intended."),this.closed=!0;return}if(this.closed)return;let n=Math.random()*.3+.85,s=Math.round(this.backoffMs*n);m.warn(`disconnected (code ${t}); reconnecting in ${Math.round(s/1e3)}s`),setTimeout(()=>this.connect(),s),this.backoffMs=Math.min(this.backoffMs*2,iy)}),e.on("error",t=>{m.warn(`websocket error: ${t.message}`)})}handle(e){if(e.type==="hello.ack"){this.bootAnnounced=!0,m.info(`connected as runner "${e.runnerName}" (${e.runnerId})`);return}if(e.type==="run.claim.result"||e.type==="deploy.claim.result"){let t=this.pending.get(e.requestId);t&&(clearTimeout(t.timer),this.pending.delete(e.requestId),t.resolve(e));return}if(e.type==="config")return this.events.onConfig(e);if(e.type==="project.test")return this.events.onProjectTest(e);if(e.type==="rule.diagnose")return this.events.onRuleDiagnose(e);if(e.type==="run.cancel")return this.events.onCancel(e.runId);if(e.type==="run.approved")return this.events.onApproved(e.runId,e.headSha);if(e.type==="run.rejected")return this.events.onRejected(e.runId);if(e.type==="run.retryPush")return this.events.onRetryPush(e.runId);if(e.type==="deploy.start")return this.events.onDeployStart(e);if(e.type==="deploy.suggest")return this.events.onDeploySuggest(e);if(e.type==="env.preflight")return this.events.onEnvPreflight(e);if(e.type==="chat.turn")return this.events.onChatTurn(e);if(e.type==="chat.create.ticket")return this.events.onChatCreateTicket(e);if(e.type==="chat.list")return this.events.onChatList(e);if(e.type==="chat.load")return this.events.onChatLoad(e);if(e.type==="board.fetch")return this.events.onBoardFetch(e);if(e.type==="board.trigger")return this.events.onBoardTrigger(e);if(e.type==="audit.start")return this.events.onAuditStart(e);if(e.type==="audit.list")return this.events.onAuditList(e);if(e.type==="audit.get")return this.events.onAuditGet(e);if(e.type==="audit.review")return this.events.onAuditReview(e);if(e.type==="knowledge.list")return this.events.onKnowledgeList(e);if(e.type==="knowledge.save")return this.events.onKnowledgeSave(e);if(e.type==="epic.list")return this.events.onEpicList(e);if(e.type==="epic.suggest")return this.events.onEpicSuggest(e);if(e.type==="team.creds")return this.events.onTeamCreds(e);if(e.type==="jira.users")return this.events.onJiraUsers(e);if(e.type==="setup.status")return this.events.onSetupStatus(e)}sendNow(e){this.ws?.send(JSON.stringify(e))}send(e){if(this.connected){this.sendNow(e);return}if(this.queue.length>=oy){let t=this.queue.findIndex(n=>n.type==="run.log");t>=0?this.queue.splice(t,1):this.queue.shift()}this.queue.push(e)}async claimRun(e){if(!this.connected)return{accepted:!1,reason:"control plane offline"};let t=Jo.default.randomUUID(),n=await new Promise(s=>{let i=setTimeout(()=>{this.pending.delete(t),s(null)},15e3);this.pending.set(t,{resolve:s,timer:i}),this.sendNow({type:"run.claim",requestId:t,...e})});return!n||n.type!=="run.claim.result"?{accepted:!1,reason:"claim timed out"}:{accepted:n.accepted,runId:n.runId,reason:n.reason,claudeProfile:n.claudeProfile,actorEmail:n.actorEmail}}async claimDeploy(e){if(!this.connected)return{accepted:!1,reason:"control plane offline"};let t=Jo.default.randomUUID(),n=await new Promise(s=>{let i=setTimeout(()=>{this.pending.delete(t),s(null)},15e3);this.pending.set(t,{resolve:s,timer:i}),this.sendNow({type:"deploy.claim",requestId:t,...e})});return!n||n.type!=="deploy.claim.result"?{accepted:!1,reason:"deploy authorization timed out"}:{accepted:n.accepted,runId:n.runId,environment:n.environment,reason:n.reason,code:n.code}}sendDeploySuggestResult(e,t){this.send({type:"deploy.suggest.result",requestId:e,...t})}sendChatTurnResult(e,t){this.send({type:"chat.turn.result",requestId:e,...t})}sendChatCreateTicketResult(e,t){this.send({type:"chat.create.ticket.result",requestId:e,...t,childKeys:t.childKeys??[]})}sendChatListResult(e,t){this.send({type:"chat.list.result",requestId:e,sessions:t})}sendChatLoadResult(e,t){this.send({type:"chat.load.result",requestId:e,...t})}sendBoardFetchResult(e,t){this.send({type:"board.fetch.result",requestId:e,...t,browseBaseUrl:t.browseBaseUrl??""})}sendAuditStartResult(e,t){this.send({type:"audit.start.result",requestId:e,...t})}sendAuditListResult(e,t){this.send({type:"audit.list.result",requestId:e,ok:t.ok,error:t.error,audits:t.audits??[]})}sendAuditGetResult(e,t){this.send({type:"audit.get.result",requestId:e,...t})}sendAuditReviewResult(e,t){this.send({type:"audit.review.result",requestId:e,...t})}sendKnowledgeListResult(e,t){this.send({type:"knowledge.list.result",requestId:e,ok:t.ok,error:t.error,files:t.files??[]})}sendKnowledgeSaveResult(e,t){this.send({type:"knowledge.save.result",requestId:e,...t})}sendEpicListResult(e,t){this.send({type:"epic.list.result",requestId:e,ok:t.ok,error:t.error,epics:t.epics??[],children:t.children??[]})}sendEpicSuggestResult(e,t){this.send({type:"epic.suggest.result",requestId:e,ok:t.ok,error:t.error,issueKey:t.issueKey??"",reason:t.reason??"",considered:t.considered??0})}sendTeamCredsResult(e,t){this.send({type:"team.creds.result",requestId:e,ok:t.ok,error:t.error,githubShared:t.githubShared??!1,sharedGithubLogin:t.sharedGithubLogin??"",entries:t.entries??[]})}sendBoardTriggerResult(e,t){this.send({type:"board.trigger.result",requestId:e,...t})}sendSetupStatusResult(e,t){this.send({type:"setup.status.result",requestId:e,ok:t.ok,error:t.error,jiraConfigured:t.jiraConfigured??!1,jiraEmail:t.jiraEmail??"",claude:t.claude,githubTokenSet:t.githubTokenSet??!1,githubLogin:t.githubLogin??"",deploysEnabled:t.deploysEnabled??!1,jiraUserCount:t.jiraUserCount??0,repos:t.repos??[]})}sendEnvPreflightResult(e,t){this.send({type:"env.preflight.result",requestId:e,...t})}sendJiraUsersResult(e,t){this.send({type:"jira.users.result",requestId:e,...t})}sendProjectTestResult(e,t,n){this.send({type:"project.test.result",requestId:e,ok:t,checks:n})}sendRuleDiagnoseResult(e,t){this.send({type:"rule.diagnose.result",requestId:e,...t})}};var gn=$(require("node:fs"),1),Yo=$(require("node:path"),1),id=require("node:child_process"),od=require("node:util");var sd=(0,od.promisify)(id.execFile);async function ni(r,e,t=[]){let n=[],s=r.repos[e.repoName]?.jira??r.jira;if(!s)n.push({name:"jira-credentials",ok:!1,detail:"no Jira credentials configured on this runner"});else{let o=new ze(s);try{let a=await o.myself();n.push({name:"jira-auth",ok:!0,detail:`authenticated as ${a.displayName}`});try{await o.search(`project = "${e.jiraProjectKey}" ORDER BY created DESC`,1),n.push({name:"jira-project",ok:!0,detail:`project ${e.jiraProjectKey} is readable`})}catch(c){n.push({name:"jira-project",ok:!1,detail:`cannot read project ${e.jiraProjectKey}: ${Gn(c)}`})}}catch(a){n.push({name:"jira-auth",ok:!1,detail:`Jira auth failed: ${Gn(a)}`})}}let i=r.repos[e.repoName];if(i&&gn.default.existsSync(i.path)){let o=Yo.default.join(i.path,"CLAUDE.md"),a=gn.default.existsSync(o)&&gn.default.readFileSync(o,"utf8").trim().length>0;n.push({name:"memory-file",ok:a,detail:a?"CLAUDE.md present \u2014 the agent has project memory":"MISSING: CLAUDE.md at the repo root. Rules can't be enabled until the project has a memory file \u2014 it is what makes every run smarter than the last."});let c=So(i.path);n.push({name:"deploy-doc",ok:c!==null,detail:c?`${c.path} present \u2014 deploy suggestions will follow it`:"MISSING: DEPLOY.md (or .ticketpilot/deploy.md). Environments can't be created until the repo documents how it deploys."})}if(!i)n.push({name:"repo-path",ok:!1,detail:`no local path mapped for repo "${e.repoName}" \u2014 run: allwright repo add "${e.repoName}" /path/to/checkout`});else if(!gn.default.existsSync(i.path))n.push({name:"repo-path",ok:!1,detail:`path does not exist: ${i.path}`});else{let o=gn.default.existsSync(Yo.default.join(i.path,".git"));n.push({name:"repo-path",ok:!0,detail:`${i.path}${o?" (git checkout)":" (warning: not a git checkout)"}`})}try{let{stdout:o}=await sd(r.claudeBin,["--version"],{timeout:15e3});n.push({name:"claude-code",ok:!0,detail:o.trim().slice(0,100)})}catch(o){n.push({name:"claude-code",ok:!1,detail:`cannot run "${r.claudeBin}": ${Gn(o)}`})}try{let{stdout:o}=await sd("git",["--version"],{timeout:15e3});n.push({name:"git",ok:!0,detail:o.trim().slice(0,100)})}catch(o){n.push({name:"git",ok:!1,detail:`cannot run git: ${Gn(o)}`})}if(r.github?.token)try{let{GitHubClient:o}=await Promise.resolve().then(()=>(ct(),tn)),a=await new o(r.github.token).whoami();n.push({name:"github-token",ok:!0,detail:`authenticated as ${a}`})}catch(o){n.push({name:"github-token",ok:!1,detail:Gn(o)})}else n.push({name:"github-token",ok:!0,detail:"not set \u2014 needed only for implement rules (allwright github set-token)"});if(t.length){r.deploy.enabled?n.push({name:"deploy",ok:!0,detail:"deployments enabled on this runner"}):n.push({name:"deploy",ok:!1,detail:"deployments are disabled on this runner \u2014 run `allwright deploy enable` to allow it to execute your saved deploy steps"});for(let o of t){let a=Jt(r,e.repoName,o.name),c=o.requiredSecrets.filter(l=>!a[l]&&!process.env[l]);n.push({name:`env:${o.name}`,ok:c.length===0,detail:c.length?`missing secret(s): ${c.join(", ")} \u2014 allwright env set "${e.repoName}" "${o.name}" ${c[0]}=...`:`${o.steps.length} step(s), ${o.requiredSecrets.length} secret(s) present`+(o.branch?`, deploys origin/${o.branch}`:"")})}}return n}function Gn(r){return(r instanceof Error?r.message:String(r)).slice(0,300)}var ae=new _a;ae.name("allwright").description("Allwright runner \u2014 runs on YOUR machine, holds YOUR credentials locally, connects outbound-only to the control plane. Your Jira token, Anthropic key and source code never leave this host.").version(vs);ae.command("init").description("Interactive setup: enroll this runner and store credentials locally").option("--cp-url <url>","control plane URL").option("--enroll-token <token>","enrolment token from the Allwright UI").option("--name <name>","runner name",fd.default.hostname()).option("--jira-url <url>","Jira base URL, e.g. https://yourorg.atlassian.net").option("--jira-email <email>","Jira account email").option("--jira-token <token>","Jira API token (stored locally only)").action(async r=>{let e=Rr.default.createInterface({input:process.stdin,output:process.stdout}),t=async(n,s,i=!1)=>{if(s)return s;let o=await e.question(`${n}: `);if(!o.trim())throw new Error(`${n} is required`);return o.trim()};try{let n=await t("Control plane URL",r.cpUrl),s=await t("Enrolment token (from the web UI)",r.enrollToken),i=await t("Jira base URL (https://yourorg.atlassian.net)",r.jiraUrl),o=await t("Jira account email",r.jiraEmail),a=await t("Jira API token (create at id.atlassian.com/manage-profile/security/api-tokens)",r.jiraToken,!0),c=Ti.parse({controlPlaneUrl:n,runnerName:r.name,jira:{baseUrl:i,email:o,apiToken:a}}),l=await new ze(c.jira).myself();m.info(`Jira credential OK \u2014 authenticated as ${l.displayName}`),c=await lu(c,s),m.info(`Enrolled as runner "${c.runnerName}" (${c.runnerId})`),m.info(`Credentials saved to ${wt()} (mode 600, this machine only)`),m.info("Next: map your repo with `allwright repo add <repoName> <localPath>`, then `allwright start`")}finally{e.close()}});var Qo=ae.command("repo").description("Map control-plane repo names to local checkouts");Qo.command("add <repoName> <localPath>").description("Map a repo name (as configured in the web UI) to a local checkout path").action(async(r,e)=>{let t=Q();t.repos[r]={path:e},ie(t),m.info(`mapped repo "${r}" -> ${e}`);try{let{originUrl:n}=await Promise.resolve().then(()=>(gr(),bu));m.info(` origin remote: ${await n(e)} \u2014 make sure this is the repo you meant`)}catch{m.warn(` could not read an origin remote at ${e} \u2014 is it a git checkout?`)}});Qo.command("list").description("Show configured repo mappings").action(()=>{let r=Q(),e=Object.entries(r.repos);if(!e.length)return m.info("no repos mapped yet");for(let[t,n]of e)m.info(`${t} -> ${n.path}`)});var md=ae.command("claude").description("Per-user Claude login profiles \u2014 each teammate's runs bill their OWN Claude account");md.command("login <profileName>").description("Create (or re-login) a named Claude profile. Opens Claude Code interactively with its own config directory \u2014 have the PERSON WHOSE ACCOUNT IT IS complete the /login flow with their credentials, then exit. Assign the profile to their user on the dashboard's Team page.").action(async r=>{if(!/^[a-zA-Z0-9._-]+$/.test(r))throw new Error("profile name: letters, digits, dots, dashes and underscores only");let e=Q(),t=e.claudeProfiles[r]?.configDir??`${wt().replace(/runner\.json$/,"")}claude-profiles/${r}`;yn.default.mkdirSync(t,{recursive:!0,mode:448}),e.claudeProfiles[r]={configDir:t},ie(e),m.info(`profile "${r}" -> ${t}`),m.info("Opening Claude Code with this profile. In it: run /login, complete the browser flow"),m.info("with the account this profile belongs to, then exit Claude (ctrl+c twice or /exit).");let n=(0,Wn.spawn)(e.claudeBin,[],{env:{...process.env,CLAUDE_CONFIG_DIR:t},stdio:"inherit"});await new Promise(s=>n.on("exit",()=>s())),m.info(`Done. Assign it on the dashboard: Team -> the user -> Claude profile = "${r}".`),m.info("Restart the background runner for this to take effect: allwright stop && allwright start")});md.command("list").description("Show configured Claude profiles and whether each looks logged in").action(()=>{let r=Q(),e=Object.entries(r.claudeProfiles);if(m.info("default: this OS user's own Claude login (no profile)"),!e.length)return m.info("no named profiles yet \u2014 allwright claude login <name>");for(let[t,n]of e){let s=yn.default.existsSync(n.configDir)&&yn.default.readdirSync(n.configDir).length>0;m.info(`${t} -> ${n.configDir} ${s?"(logged in)":"(NOT logged in yet)"}`)}});Qo.command("remove <repoName>").description("Unmap a repo from this runner: removes the mapping plus its per-repo Jira/GitHub overrides and env secrets from the config. Does NOT touch the checkout on disk or anything in the control plane \u2014 delete the project on the dashboard separately.").action(r=>{let e=Q();if(!e.repos[r]){let i=Object.keys(e.repos).join(", ")||"(none)";throw new Error(`unknown repo "${r}" \u2014 mapped repos: ${i}`)}let t=e.repos[r].path;delete e.repos[r];let n=Object.keys(e.environments).filter(i=>i.startsWith(`${r}:`));for(let i of n)delete e.environments[i];let s=e.auditSchedules.length;e.auditSchedules=e.auditSchedules.filter(i=>i.repoName!==r),ie(e),m.info(`Removed "${r}" (was ${t})`),n.length&&m.info(`Also removed ${n.length} environment secret set(s): ${n.join(", ")}`),e.auditSchedules.length!==s&&m.info("Also removed its audit schedule(s)"),m.info("The checkout on disk was NOT touched \u2014 remove it yourself if you want it gone."),m.info("Restart the runner to apply. Dashboard project (if any) is deleted separately there.")});var ea=ae.command("service").description("Run the runner as a system service (starts on boot, restarts on crash)");ea.command("install").description("Install + start the systemd service \u2014 detects node, this script, your user and home; no hand-written unit files. Run with sudo. (--print shows the unit without installing.)").option("--print","print the generated unit file and exit").action(r=>{if(r.print){m.info(`
664
+ `+Xi(Yi()));return}Eu(m)});ea.command("uninstall").description("Stop and remove the systemd service (config/credentials untouched)").action(()=>Iu(m));ea.command("status").description("systemctl status for the runner service").action(()=>{(0,Wn.spawn)("systemctl",["status","allwright","--no-pager"],{stdio:"inherit"}).on("exit",e=>process.exit(e??0))});ae.command("update").description("Update the runner to the latest published version (npm install -g allwright@latest). Restart the runner afterwards \u2014 and only when no runs are active.").action(async()=>{m.info("Updating: npm install -g allwright@latest");let r=(0,Wn.spawn)("npm",["install","-g","allwright@latest"],{stdio:"inherit"});await new Promise((e,t)=>{r.on("exit",n=>n===0?e():t(new Error(`npm exited with code ${n}`))),r.on("error",t)}),m.info("Updated. Restart the runner service to load the new version (check active runs first).")});var Jn=ae.command("jira").description("Per-repo Jira site overrides \u2014 for projects living on a different Atlassian site");Jn.command("set <repoName>").description("Store Jira credentials for ONE repo's project (e.g. a project on a different *.atlassian.net site than the runner's main credential). Prompts on stdin; stored locally only, like every other credential.").action(async r=>{let e=Q();if(!e.repos[r]){let n=Object.keys(e.repos).join(", ")||"(none)";throw new Error(`unknown repo "${r}" \u2014 mapped repos: ${n}. Run \`allwright repo add\` first.`)}let t=Rr.default.createInterface({input:process.stdin,output:process.stdout});try{let n=(await t.question("Jira base URL for this repo (https://yourorg.atlassian.net): ")).trim(),s=(await t.question("Jira account email: ")).trim(),i=(await t.question("Jira API token (id.atlassian.com/manage-profile/security/api-tokens): ")).trim();if(!n||!s||!i)throw new Error("all three values are required");let o={baseUrl:n,email:s,apiToken:i},a=await new ze(o).myself();m.info(`Jira credential OK \u2014 authenticated as ${a.displayName} on ${n}`),e.repos[r].jira=o,ie(e),m.info(`Saved: repo "${r}" now polls ${n} (other repos keep the runner-wide credential)`),m.info("Restart the background runner for this to take effect: allwright stop && allwright start")}finally{t.close()}});Jn.command("show").description("Show which Jira site each repo uses (never prints tokens)").action(()=>{let r=Q();m.info(`runner-wide: ${r.jira?`${r.jira.baseUrl} (${r.jira.email})`:"(not configured)"}`);for(let[e,t]of Object.entries(r.repos))m.info(`${e} -> ${t.jira?`${t.jira.baseUrl} (${t.jira.email})`:"(runner-wide credential)"}`)});Jn.command("user-add <ticketpilotEmail>").description("Store a PERSON's own Jira credential, so board buttons and Compose tickets they click post to Jira under THEIR Atlassian identity instead of the runner's account. Keyed by their Allwright login email. Prompts on stdin; stored locally only. Picked up on the next click \u2014 no restart needed.").action(async r=>{let e=Q(),t=r.trim().toLowerCase();if(!t.includes("@"))throw new Error(`"${r}" doesn't look like an email`);let n=Rr.default.createInterface({input:process.stdin,output:process.stdout});try{let s=(await n.question(`Their ATLASSIAN account email [${t}]: `)).trim()||t,i=(await n.question("Their Jira API token (they create it at id.atlassian.com/manage-profile/security/api-tokens): ")).trim();if(!i)throw new Error("API token is required");let o=[e.jira,...Object.values(e.repos).map(l=>l.jira)].filter(l=>!!l),a=new Set,c=!1;for(let l of o)if(!a.has(l.baseUrl)){a.add(l.baseUrl);try{let d=await new ze({baseUrl:l.baseUrl,email:s,apiToken:i}).myself();m.info(`${l.baseUrl}: OK \u2014 authenticated as ${d.displayName}`),c=!0}catch{m.warn(`${l.baseUrl}: this credential does NOT work there (fine if they don't use that site)`)}}if(!c)throw new Error("credential failed on every configured Jira site \u2014 nothing saved");e.jiraUsers[t]={email:s,apiToken:i},ie(e),m.info(`Saved. Dashboard actions by ${t} now post to Jira as ${s}. No restart needed.`)}finally{n.close()}});Jn.command("user-list").description("Show which Allwright users have their own Jira credential here (never prints tokens)").action(()=>{let r=Q(),e=Object.entries(r.jiraUsers);if(!e.length)return m.info("none yet \u2014 everyone's dashboard clicks require one: allwright jira user-add <their-ticketpilot-email>");for(let[t,n]of e)m.info(`${t} -> posts to Jira as ${n.email}`)});Jn.command("user-remove <ticketpilotEmail>").description("Delete a person's stored Jira credential").action(r=>{let e=Q(),t=r.trim().toLowerCase();if(!e.jiraUsers[t])throw new Error(`no credential stored for ${t}`);delete e.jiraUsers[t],ie(e),m.info(`Removed. Dashboard actions by ${t} will now be refused until a new credential is added.`)});var _n=ae.command("github").description("GitHub credential for implement-mode rules");_n.command("set-token").description("Store a GitHub token for opening pull requests (implement rules). Stored locally only, like your Jira token. Recommended: a fine-grained PAT scoped to the repo with contents:write + pull_requests:write.").option("--token <token>","GitHub token (omit to be prompted)").action(async r=>{let e=Rr.default.createInterface({input:process.stdin,output:process.stdout});try{let t=r.token??(await e.question("GitHub token (fine-grained PAT recommended): ")).trim();if(!t)throw new Error("token is required");let{GitHubClient:n}=await Promise.resolve().then(()=>(ct(),tn)),s=await new n(t).whoami(),i=Q();i.github={token:t,login:s},ie(i),m.info(`GitHub token OK \u2014 authenticated as ${s}`),m.info(`Saved to ${wt()} (mode 600, this machine only)`)}finally{e.close()}});_n.command("set <repoName>").description("Store a GitHub token for ONE repo only \u2014 overrides the runner-wide token for that repo's PRs and PR-watching. Useful when projects need separately revocable access. Prompts on stdin; stored locally only.").action(async r=>{let e=Q();if(!e.repos[r]){let n=Object.keys(e.repos).join(", ")||"(none)";throw new Error(`unknown repo "${r}" \u2014 mapped repos: ${n}. Run \`allwright repo add\` first.`)}let t=Rr.default.createInterface({input:process.stdin,output:process.stdout});try{let n=(await t.question(`GitHub token for "${r}" (fine-grained PAT scoped to just this repo): `)).trim();if(!n)throw new Error("token is required");let{GitHubClient:s}=await Promise.resolve().then(()=>(ct(),tn)),i=await new s(n).whoami();e.repos[r].github={token:n,login:i},ie(e),m.info(`GitHub token OK \u2014 authenticated as ${i}`),m.info(`Saved: repo "${r}" now uses its own token (other repos keep the runner-wide one)`)}finally{t.close()}});_n.command("user-add <ticketpilotEmail>").description("Store a PERSON's own GitHub token, so PRs from implement runs THEY trigger are authored by their GitHub account. Keyed by their Allwright login email. Optional \u2014 without it their runs fall back to the repo/runner-wide token. Needs contents:write + pull_requests:write on the repos they'll touch.").action(async r=>{let e=Q(),t=r.trim().toLowerCase();if(!t.includes("@"))throw new Error(`"${r}" doesn't look like an email`);let n=Rr.default.createInterface({input:process.stdin,output:process.stdout});try{let s=(await n.question(`GitHub token for ${t}: `)).trim();if(!s)throw new Error("token is required");let{GitHubClient:i}=await Promise.resolve().then(()=>(ct(),tn)),o=await new i(s).whoami();e.githubUsers[t]={token:s,login:o},ie(e),m.info(`GitHub token OK \u2014 authenticated as ${o}`),m.info(`Saved. Implement runs triggered by ${t} now open PRs as ${o}. No restart needed.`)}finally{n.close()}});_n.command("user-list").description("Show which Allwright users have their own GitHub token here (never prints tokens)").action(()=>{let r=Q(),e=Object.entries(r.githubUsers);if(!e.length)return m.info("no per-user GitHub tokens \u2014 everyone's PRs use the repo/runner-wide token");for(let[t]of e)m.info(`${t} -> own GitHub token stored`)});_n.command("user-remove <ticketpilotEmail>").description("Delete a person's stored GitHub token (their runs fall back to the shared token)").action(r=>{let e=Q(),t=r.trim().toLowerCase();if(!e.githubUsers[t])throw new Error(`no GitHub token stored for ${t}`);delete e.githubUsers[t],ie(e),m.info(`Removed. ${t}'s runs use the repo/runner-wide token again.`)});_n.command("show").description("Show which GitHub token each repo and person would use (never prints tokens)").action(()=>{let r=Q();m.info(`runner-wide: ${r.github?.token?"token set":"(not configured)"}`);for(let[t,n]of Object.entries(r.repos))m.info(`${t} -> ${n.github?.token?"own repo token":"runner-wide token"}`);let e=Object.keys(r.githubUsers);m.info(e.length?`per-user tokens: ${e.join(", ")}`:"per-user tokens: (none)")});var ta=ae.command("audit").description("Recurring specialist audits on this runner");ta.command("schedule <repoName> <role> <intervalHours>").description("Audit this repo's project on a cadence (role: security|testing; interval in hours, min 6). Runs on the runner's own clock; reports land in the Audits page history, where the diff-vs-previous view shows drift. Advisory only \u2014 nothing blocks.").action((r,e,t)=>{let n=Q();if(!n.repos[r]){let i=Object.keys(n.repos).join(", ")||"(none)";throw new Error(`unknown repo "${r}" \u2014 mapped repos: ${i}`)}if(e!=="security"&&e!=="testing")throw new Error('role must be "security" or "testing"');let s=parseInt(t,10);if(!Number.isInteger(s)||s<6||s>720)throw new Error("intervalHours must be 6-720");n.auditSchedules=[...n.auditSchedules.filter(i=>!(i.repoName===r&&i.role===e)),{repoName:r,role:e,intervalHours:s}],ie(n),m.info(`Scheduled: ${e} audit of "${r}" every ${s}h. Restart the runner to apply.`)});ta.command("schedules").description("List scheduled audits").action(()=>{let r=Q();if(!r.auditSchedules.length)return m.info("no scheduled audits \u2014 allwright audit schedule <repo> <role> <hours>");for(let e of r.auditSchedules)m.info(`${e.repoName} \xB7 ${e.role} \xB7 every ${e.intervalHours}h`)});ta.command("unschedule <repoName> <role>").description("Remove a scheduled audit").action((r,e)=>{let t=Q(),n=t.auditSchedules.length;if(t.auditSchedules=t.auditSchedules.filter(s=>!(s.repoName===r&&s.role===e)),t.auditSchedules.length===n)throw new Error("no such schedule");ie(t),m.info("Removed. Restart the runner to apply.")});var ra=ae.command("deploy").description("Deployment settings for this machine");ra.command("enable").description("Allow this runner to execute the deploy steps saved in the dashboard. Those steps are shell commands that run here, as this user \u2014 so this switch lives on the machine, not in the web UI, and only someone with shell access can flip it.").action(()=>{let r=Q();r.deploy={enabled:!0},ie(r),m.info("deployments ENABLED on this runner"),m.info("This runner will now execute the deploy steps configured for your environments. Review them in the dashboard before shipping to production."),m.info("Restart the background runner for this to take effect: allwright stop && allwright start")});ra.command("disable").description("Stop this runner from executing any deploy steps").action(()=>{let r=Q();r.deploy={enabled:!1},ie(r),m.info("deployments DISABLED on this runner"),m.info("Restart the background runner for this to take effect: allwright stop && allwright start")});ra.command("status").description("Show whether deployments are enabled here, and which env secrets are stored").action(()=>{let r=Q();m.info(`deployments: ${r.deploy.enabled?"enabled":"disabled"}`);let e=Object.entries(r.environments);if(!e.length)return m.info("no environment secrets stored");for(let[t,n]of e){let s=Object.keys(n.secrets);m.info(`${t}: ${s.length?s.join(", "):"(no secrets)"}`)}});var na=ae.command("env").description("Per-environment deploy secrets. Values stay on this machine, like your Jira token.");na.command("set <repoName> <envName> <assignments...>").description('Store secrets for one environment, e.g. env set acme/api production "SSH_HOST=1.2.3.4" "SSH_USER=deploy". Your deploy steps reference these as $SSH_HOST. The control plane only ever learns the NAMES.').action((r,e,t)=>{let n=Q(),s=as(r,e),i=n.environments[s]??{secrets:{}},o=[];for(let a of t){let c=a.indexOf("=");if(c<=0)throw new Error(`expected KEY=VALUE, got "${a}"`);let l=a.slice(0,c).trim();i.secrets[l]=a.slice(c+1),o.push(l)}n.environments[s]=i,ie(n),m.info(`stored ${o.length} secret(s) for ${s}: ${o.join(", ")}`),m.info(`Saved to ${wt()} (mode 600, this machine only)`),m.info("Restart the background runner to pick these up: allwright stop && allwright start")});na.command("unset <repoName> <envName> <names...>").description("Remove stored secrets for an environment").action((r,e,t)=>{let n=Q(),s=as(r,e),i=n.environments[s];if(!i)return m.info(`nothing stored for ${s}`);for(let o of t)delete i.secrets[o];n.environments[s]=i,ie(n),m.info(`removed ${t.join(", ")} from ${s}`)});na.command("list").description("Show which environments have secrets stored here (names only, never values)").action(()=>{let r=Q(),e=Object.entries(r.environments);if(!e.length)return m.info("no environment secrets stored");for(let[t,n]of e)m.info(`${t}: ${Object.keys(n.secrets).join(", ")||"(none)"}`)});ae.command("export [file]").description("Back up ALL runner state (config+secrets, knowledge, audits, chats) to one tarball").action(r=>{try{let e=$a(r);m.info(`Backup written: ${e.file} (${e.entries.length} entries, mode 600)`),m.warn("This file CONTAINS YOUR SECRETS (Jira/GitHub tokens). Keep it private \u2014 anyone holding it can act as this runner."),m.info(`Restore on any machine with: allwright import ${pd.default.basename(e.file)}`)}catch(e){m.error(e instanceof Error?e.message:String(e)),process.exitCode=1}});ae.command("import <file>").description("Restore runner state from an `export` tarball (existing config is kept as a .bak dir)").action(r=>{let e=qr();if(e&&Tn(e)){m.error("the runner is running \u2014 stop it first (systemctl stop allwright, or `allwright stop` for a pid-file daemon), then import."),process.exitCode=1;return}try{let t=Pa(r);m.info(`Restored ${t.restored.length} entries into ${ee()}`),t.previousDir&&m.info(`Previous config kept at ${t.previousDir}`),m.info("Start the runner and it will reconnect with the restored identity.")}catch(t){m.error(t instanceof Error?t.message:String(t)),process.exitCode=1}});ae.command("test").description("Check local setup: Jira auth, repo mappings, Claude Code binary").action(async()=>{let r=Q(),e=Object.keys(r.repos);if(!r.jira){m.error("no Jira credentials configured \u2014 run `allwright init`"),process.exitCode=1;return}let t=e.length?e.map(s=>({jiraProjectKey:"*",repoName:s})):[{jiraProjectKey:"*",repoName:"(none mapped)"}],n=!0;for(let s of t){let i=await ni(r,s);for(let o of i){if(s.jiraProjectKey==="*"&&o.name==="jira-project")continue;let a=o.ok?"PASS":"FAIL";(o.ok?m.info:m.error)(`[${a}] ${o.name}: ${o.detail}`),n&&=o.ok}}n||(process.exitCode=1)});function cy(r){if(!r.runnerToken)throw new Error("runner not enrolled \u2014 run `allwright init`");if(!r.jira)throw new Error("no Jira credentials \u2014 run `allwright init`");let e=new ze(r.jira),t=new Map,n=f=>{let g=r.repos[f]?.jira;if(!g)return e;let b=t.get(f);return b||(b=new ze(g),t.set(f,b)),b},s=new Map,i=(f,g)=>{let b=Su(ce()??r,f,g);switch(b.kind){case"legacy":return{jira:n(f),authored:!1};case"self":return{jira:n(f),authored:!0};case"missing":return{error:b.error};case"user":{let I=`${b.creds.baseUrl}:${b.creds.email}:${b.creds.apiToken.slice(-6)}`,N=s.get(I);return N||(N=new ze(b.creds),s.set(I,N)),{jira:N,authored:!0}}}},o=new URL("/api/runner/ws",r.controlPlaneUrl);o.protocol=o.protocol==="https:"?"wss:":"ws:";let a=[],c=[],l=[],d,p={cfg:r,jiraFor:n,transport:null},v=new Set,S=f=>{let g=a.find(I=>I.id===f),b=g&&r.repos[g.repoName];return g&&b?{project:g,repoPath:b.path}:null},x={cfg:r,jiraFor:n,get transport(){return p.transport},lookup:(f,g)=>{let b=S(f),I=l.find(N=>N.projectId===f&&N.name===g);return b&&I?{...b,environment:I}:null}},w=new ri(o.toString(),r.runnerToken,{runnerVersion:vs},{onConfig:f=>{a=f.projects,c=f.rules,l=f.environments,d.setConfig(f.projects,f.rules,f.pollingPaused,f.environments)},onProjectTest:async f=>{let g=a.find(I=>I.id===f.projectId);if(!g){w.sendProjectTestResult(f.requestId,!1,[{name:"config",ok:!1,detail:"project not in this runner's synced config yet"}]);return}m.info(`running connection test for project "${g.name}"`);let b=await ni(r,g,l.filter(I=>I.projectId===g.id));w.sendProjectTestResult(f.requestId,b.every(I=>I.ok),b)},onRuleDiagnose:async f=>{let g=c.find(z=>z.id===f.ruleId),b=g&&a.find(z=>z.id===g.projectId);if(!g||!b){w.sendRuleDiagnoseResult(f.requestId,{checks:[{name:"config",ok:!1,detail:"rule not in this runner's synced config yet"}],matchedCount:0,excludedCount:0,excludedSample:[]});return}m.info(`diagnosing rule "${g.name}"`);let I=await ni(r,b,g.action.type==="deploy"?l.filter(z=>z.projectId===b.id):[]),N=g.action.type==="implement"?I:I.filter(z=>z.name!=="github-token"),{matchedCount:V,excludedCount:W,excludedSample:J}=await d.diagnoseRule(g,b);w.sendRuleDiagnoseResult(f.requestId,{checks:N,matchedCount:V,excludedCount:W,excludedSample:J})},onCancel:f=>{m.warn(`cancel requested for run ${f} \u2014 not supported in this version, run will finish or time out`)},onApproved:(f,g)=>{if(ko(f)){Bc(x,f).catch(b=>m.error(`deploy approval crashed for ${f}: ${b instanceof Error?b.stack:b}`));return}zn(p,f,g).catch(b=>m.error(`approval handling crashed for ${f}: ${b instanceof Error?b.stack:b}`))},onRetryPush:f=>{let g=$s(f),b=()=>Rc(p,f).catch(I=>m.error(`retry push crashed for ${f}: ${I instanceof Error?I.stack:I}`));g?d.runOnRepoQueue(g.baseRepoPath,b):b()},onRejected:f=>{if(ko(f)){Fc(x,f).catch(g=>m.error(`deploy rejection crashed for ${f}: ${g instanceof Error?g.stack:g}`));return}Ac(p,f).catch(g=>m.error(`rejection handling crashed for ${f}: ${g instanceof Error?g.stack:g}`))},onDeployStart:f=>{let g=`${f.runId}#${f.attempt}`;if(v.has(g))return;v.add(g);let b=S(f.projectId);if(!b){let I="this runner has no local checkout mapped for that project \u2014 run: allwright repo add <repoName> /path/to/checkout";m.error(`deploy ${f.runId}: ${I}`),w.send({type:"run.status",runId:f.runId,status:"failed",error:I});return}m.info(`deploy ${f.runId} requested from the dashboard: ${f.issueKey} \u2192 ${f.environment.name}`),d.runOnEnvironmentQueue(f.environment.id,()=>zs({runId:f.runId,project:b.project,environment:f.environment,issueKey:f.issueKey,issueSummary:f.issueSummary,repoPath:b.repoPath,cfg:r,jira:n(b.project.repoName),transport:w,requestedBy:f.requestedBy}).catch(I=>m.error(`deploy crashed for ${f.runId}: ${I instanceof Error?I.stack:I}`)))},onDeploySuggest:async f=>{let g=S(f.projectId);if(!g){w.sendDeploySuggestResult(f.requestId,{ok:!1,steps:[],requiredSecrets:[],notes:"",error:"this runner has no local checkout mapped for that project"});return}m.info(`asking Claude Code for "${f.environmentName}" deploy steps in ${g.repoPath}`);let b=await Hc({repoPath:g.repoPath,repoName:g.project.repoName,environmentName:f.environmentName,notes:f.notes,timeoutSeconds:f.timeoutSeconds,cfg:r});w.sendDeploySuggestResult(f.requestId,b)},onEnvPreflight:async f=>{let g=S(f.projectId);if(!g){w.sendEnvPreflightResult(f.requestId,{ok:!1,checks:[{name:"repo",ok:!1,detail:"no local checkout mapped for that project"}]});return}let b=await Vc({repoPath:g.repoPath,repoName:g.project.repoName,environmentName:f.environmentName,steps:f.steps,requiredSecrets:f.requiredSecrets,workdir:f.workdir,branch:f.branch,publicUrl:f.publicUrl,cfg:r});w.sendEnvPreflightResult(f.requestId,b)},onChatTurn:async f=>{let g=S(f.projectId);if(!g){w.sendChatTurnResult(f.requestId,{ok:!1,sessionId:f.sessionId??"",reply:"",error:"this runner has no local checkout mapped for that project"});return}let b=f.sessionId||(0,Xo.randomUUID)(),I=!f.sessionId;if((I?0:Co(b)?.messages.length??0)>=44){w.sendChatTurnResult(f.requestId,{ok:!1,sessionId:b,reply:"",error:"this chat has hit its length limit \u2014 every turn re-reads the whole conversation, so long chats get slow and expensive. Start a new chat (it keeps the repo knowledge; only the conversation resets)."});return}let V=f.files.length?Na(g.repoPath,f.requestId,f.files):null,W="```",J=I?`You are the project assistant for "${g.project.name}" \u2014 this working directory is its repository, and you have read-only access.
665
665
 
666
666
  DEFAULT MODE IS DISCUSSION. Answer questions, explain code, weigh approaches, review ideas \u2014 like a teammate who knows this repo. Most conversations never produce a ticket, and that is fine. Do NOT propose a Jira ticket unless the user explicitly asks for one in this conversation ("create a ticket", "make this a ticket", "draft the ticket" or similar). Never end a normal answer with a ticket proposal.
667
667
  Be fast: answer from CLAUDE.md and what you already know first; open files only when the question genuinely needs code-level detail. Keep replies short.
@@ -690,4 +690,4 @@ _(requested by ${f.requestedBy} via Allwright)_`:"")),m.info(`Board action on ${
690
690
  ---
691
691
  _Created via Allwright Compose`+(!b.authored&&f.requestedBy?` by ${f.requestedBy}`:"")+", drafted with the project agent._",{key:N}=await b.jira.createIssue(g.project.jiraProjectKey,f.summary,(f.description||"(no description)")+I,f.asEpic?"Epic":"Task");f.files.length&&await b.jira.addAttachments(N,f.files.map(W=>({name:W.name,content:Buffer.from(W.contentBase64,"base64")}))).then(()=>m.info(`Compose attached ${f.files.length} file(s) to ${N}`)).catch(W=>m.warn(`Compose could not attach files to ${N}: ${W instanceof Error?W.message:W}`));let V=[];if(f.asEpic){for(let W of f.children){let J=await b.jira.createIssue(g.project.jiraProjectKey,W.summary,W.description||"(no description)","Task",N);V.push(J.key)}m.info(`Compose created epic ${N} with ${V.length} child ticket(s)`),w.sendChatCreateTicketResult(f.requestId,{ok:!0,issueKey:N,childKeys:V});return}f.triggerComment.trim()&&await b.jira.addTriggerComment(N,`${f.triggerComment.trim()}`+(!b.authored&&f.requestedBy?`
692
692
 
693
- _(requested by ${f.requestedBy} via Allwright)_`:"")),m.info(`Compose created ${N}`+(f.requestedBy?` for ${f.requestedBy}`:"")+(f.triggerComment?` with trigger "${f.triggerComment.trim()}"`:"")),w.sendChatCreateTicketResult(f.requestId,{ok:!0,issueKey:N})}catch(b){w.sendChatCreateTicketResult(f.requestId,{ok:!1,issueKey:"",error:b instanceof Error?b.message:String(b)})}},onAuditStart:async f=>{let g=S(f.projectId);if(!g){w.sendAuditStartResult(f.requestId,{ok:!1,error:"this runner has no local checkout mapped for that project"});return}try{m.info(`Audit (${f.role}) starting on ${g.project.repoName}`+(f.scope.kind!=="repo"?` scoped to ${f.scope.kind}:${f.scope.ref}`:""));let b=await Qr({projectId:f.projectId,repoPath:g.repoPath,role:f.role,scope:f.scope,model:f.model,claudeBin:r.claudeBin,jira:n(g.project.repoName)});if(!b.ok){w.sendAuditStartResult(f.requestId,{ok:!1,error:b.error});return}w.sendAuditStartResult(f.requestId,{ok:!0,audit:b.audit})}catch(b){w.sendAuditStartResult(f.requestId,{ok:!1,error:b instanceof Error?b.message:String(b)})}},onAuditList:async f=>{try{w.sendAuditListResult(f.requestId,{ok:!0,audits:Zu(f.projectId)})}catch(g){w.sendAuditListResult(f.requestId,{ok:!1,error:g instanceof Error?g.message:String(g)})}},onAuditGet:async f=>{try{let g=Vu(f.projectId,f.auditId);if(!g){w.sendAuditGetResult(f.requestId,{ok:!1,error:"audit not found on this runner"});return}w.sendAuditGetResult(f.requestId,{ok:!0,audit:g})}catch(g){w.sendAuditGetResult(f.requestId,{ok:!1,error:g instanceof Error?g.message:String(g)})}},onAuditReview:async f=>{try{let g=to(f.projectId,f.auditId,{selected:f.selected,ticketed:f.ticketed,verdicts:f.verdicts,verdictBy:f.verdictBy});if(!g){w.sendAuditReviewResult(f.requestId,{ok:!1,error:"audit not found on this runner"});return}let b=S(f.projectId);if(b&&f.verdicts.length){let I=[];for(let N of f.verdicts){if(N.verdict==="valid"||g.lessonsWritten.includes(N.findingId))continue;let V=g.findings.find(W=>W.id===N.findingId);V&&(so(b.repoPath,g.role,Xu(V,N.verdict,N.note,f.verdictBy)),I.push(N.findingId),m.info(`Lesson written (${g.role}): ${N.verdict} \u2014 ${V.title.slice(0,60)}`))}I.length&&(g=to(f.projectId,f.auditId,{markLessonsWritten:I})??g)}w.sendAuditReviewResult(f.requestId,{ok:!0,audit:g})}catch(g){w.sendAuditReviewResult(f.requestId,{ok:!1,error:g instanceof Error?g.message:String(g)})}},onKnowledgeList:async f=>{let g=S(f.projectId);if(!g){w.sendKnowledgeListResult(f.requestId,{ok:!1,error:"this runner has no local checkout mapped for that project"});return}try{w.sendKnowledgeListResult(f.requestId,{ok:!0,files:ec(g.repoPath)})}catch(b){w.sendKnowledgeListResult(f.requestId,{ok:!1,error:b instanceof Error?b.message:String(b)})}},onKnowledgeSave:async f=>{let g=S(f.projectId);if(!g){w.sendKnowledgeSaveResult(f.requestId,{ok:!1,error:"this runner has no local checkout mapped for that project"});return}try{f.append?so(g.repoPath,f.role,Qu(f.content,f.by),f.level):tc(g.repoPath,f.role,f.level,f.source,f.name,f.content),m.info(`Knowledge ${f.append?"taught":"saved"}: ${f.role}/${f.level}/${f.name}`),w.sendKnowledgeSaveResult(f.requestId,{ok:!0})}catch(b){w.sendKnowledgeSaveResult(f.requestId,{ok:!1,error:b instanceof Error?b.message:String(b)})}},onEpicList:async f=>{let g=S(f.projectId);if(!g){w.sendEpicListResult(f.requestId,{ok:!1,error:"this runner has no local checkout mapped for that project"});return}try{let b=n(g.project.repoName);if(f.epicKey){let I=await b.epicChildren(f.epicKey);w.sendEpicListResult(f.requestId,{ok:!0,children:I})}else{let I=await b.searchEpics(g.project.jiraProjectKey);w.sendEpicListResult(f.requestId,{ok:!0,epics:I})}}catch(b){w.sendEpicListResult(f.requestId,{ok:!1,error:b instanceof Error?b.message:String(b)})}},onEpicSuggest:async f=>{let g=S(f.projectId);if(!g){w.sendEpicSuggestResult(f.requestId,{ok:!1,error:"this runner has no local checkout mapped for that project"});return}try{let b=n(g.project.repoName),I=await b.epicChildren(f.epicKey),N=Ru(I);if(!N.length){w.sendEpicSuggestResult(f.requestId,{ok:!1,error:`every child of ${f.epicKey} is already done or in an agent's hands \u2014 nothing to sequence`});return}if(N.length===1){w.sendEpicSuggestResult(f.requestId,{ok:!0,issueKey:N[0].key,reason:"It's the only pending ticket left in this epic.",considered:1});return}let V=await Promise.all(N.slice(0,12).map(async H=>{try{let be=await b.getIssue(H.key);return{...H,description:be.description}}catch{return{...H,description:""}}})),W=(await b.getIssue(f.epicKey).catch(()=>null))?.summary??"";m.info(`Epic suggest: weighing ${V.length} pending children of ${f.epicKey}`);let J=await Ue.run({repoPath:g.repoPath,prompt:$u(f.epicKey,W,V),timeoutSeconds:150,bin:r.claudeBin,mode:"read_only",maxTurns:20,sessionId:(0,Xo.randomUUID)(),model:f.model||"claude-sonnet-5",onLog:()=>{}}),z=Pu(J.resultText,V.map(H=>H.key));if("error"in z){w.sendEpicSuggestResult(f.requestId,{ok:!1,error:z.error});return}m.info(`Epic suggest: ${f.epicKey} -> do ${z.issueKey} first`),w.sendEpicSuggestResult(f.requestId,{ok:!0,issueKey:z.issueKey,reason:z.reason,considered:V.length})}catch(b){w.sendEpicSuggestResult(f.requestId,{ok:!1,error:b instanceof Error?b.message:String(b)})}},onTeamCreds:async f=>{try{let g=ce()??r;if(g.github?.token&&!g.github.login)try{let{GitHubClient:I}=await Promise.resolve().then(()=>(ct(),tn));g.github.login=await new I(g.github.token).whoami(),ie(g)}catch{}let b=Tu(g,f.emails);w.sendTeamCredsResult(f.requestId,{ok:!0,...b})}catch(g){w.sendTeamCredsResult(f.requestId,{ok:!1,error:g instanceof Error?g.message:String(g)})}},onSetupStatus:async f=>{try{let g=ce()??r,{buildSetupReport:b}=await Promise.resolve().then(()=>(hd(),dd)),I=await b(g,f.repoNames);w.sendSetupStatusResult(f.requestId,{ok:!0,...I})}catch(g){w.sendSetupStatusResult(f.requestId,{ok:!1,error:g instanceof Error?g.message:String(g)})}},onJiraUsers:async f=>{try{let g=await e.searchUsers(f.query);w.sendJiraUsersResult(f.requestId,{ok:!0,users:g})}catch(g){w.sendJiraUsersResult(f.requestId,{ok:!1,users:[],error:g instanceof Error?g.message:String(g)})}}});p.transport=w,d=new qs(r,n,w);let j=Object.values(sn()).filter(f=>f.kind==="implement").map(f=>f.repoPath);Bi(Object.values(r.repos).map(f=>f.path),j).catch(()=>{}),w.start(),d.start();let U=()=>{m.info("shutting down"),d.stop(),w.stop(),La(process.pid),process.exit(0)};process.on("SIGINT",U),process.on("SIGTERM",U)}ae.command("start").description("Start watching Jira. Runs in the background by default \u2014 close this terminal and it keeps going until you run `allwright stop`. Use --foreground to keep it attached (e.g. under systemd).").option("--foreground","run in this terminal instead of detaching to the background").action(async r=>{let e=Q();if(r.foreground){uy(e);return}let t=qr();if(t&&Tn(t)){m.info(`already running in the background (pid ${t}). Use \`allwright status\` or \`stop\`.`);return}let n=Ma(),s=(0,Wn.spawn)(process.execPath,[process.argv[1],"start","--foreground"],{detached:!0,stdio:["ignore",n,n]});s.unref(),Da(s.pid),m.info(`Runner started in the background (pid ${s.pid}).`),m.info(`Logs: ${ds()}`),m.info("It will keep polling Jira until you run `allwright stop` \u2014 closing this terminal is fine.")});ae.command("stop").description("Stop the background runner started by `start`").action(()=>{let r=qr();if(!r||!Tn(r)){m.info("no background runner is running"),r&&yn.default.rmSync(Sn(),{force:!0});return}process.kill(r,"SIGTERM"),m.info(`stop signal sent (pid ${r})`)});ae.command("status").description("Check whether the background runner is running").action(()=>{let r=qr();r&&Tn(r)?m.info(`running in the background (pid ${r})`):m.info("not running")});ae.parseAsync().catch(r=>{m.error(r instanceof Error?r.message:String(r)),process.exit(1)});
693
+ _(requested by ${f.requestedBy} via Allwright)_`:"")),m.info(`Compose created ${N}`+(f.requestedBy?` for ${f.requestedBy}`:"")+(f.triggerComment?` with trigger "${f.triggerComment.trim()}"`:"")),w.sendChatCreateTicketResult(f.requestId,{ok:!0,issueKey:N})}catch(b){w.sendChatCreateTicketResult(f.requestId,{ok:!1,issueKey:"",error:b instanceof Error?b.message:String(b)})}},onAuditStart:async f=>{let g=S(f.projectId);if(!g){w.sendAuditStartResult(f.requestId,{ok:!1,error:"this runner has no local checkout mapped for that project"});return}try{m.info(`Audit (${f.role}) starting on ${g.project.repoName}`+(f.scope.kind!=="repo"?` scoped to ${f.scope.kind}:${f.scope.ref}`:""));let b=await Qr({projectId:f.projectId,repoPath:g.repoPath,role:f.role,scope:f.scope,model:f.model,claudeBin:r.claudeBin,jira:n(g.project.repoName)});if(!b.ok){w.sendAuditStartResult(f.requestId,{ok:!1,error:b.error});return}w.sendAuditStartResult(f.requestId,{ok:!0,audit:b.audit})}catch(b){w.sendAuditStartResult(f.requestId,{ok:!1,error:b instanceof Error?b.message:String(b)})}},onAuditList:async f=>{try{w.sendAuditListResult(f.requestId,{ok:!0,audits:Zu(f.projectId)})}catch(g){w.sendAuditListResult(f.requestId,{ok:!1,error:g instanceof Error?g.message:String(g)})}},onAuditGet:async f=>{try{let g=Vu(f.projectId,f.auditId);if(!g){w.sendAuditGetResult(f.requestId,{ok:!1,error:"audit not found on this runner"});return}w.sendAuditGetResult(f.requestId,{ok:!0,audit:g})}catch(g){w.sendAuditGetResult(f.requestId,{ok:!1,error:g instanceof Error?g.message:String(g)})}},onAuditReview:async f=>{try{let g=to(f.projectId,f.auditId,{selected:f.selected,ticketed:f.ticketed,verdicts:f.verdicts,verdictBy:f.verdictBy});if(!g){w.sendAuditReviewResult(f.requestId,{ok:!1,error:"audit not found on this runner"});return}let b=S(f.projectId);if(b&&f.verdicts.length){let I=[];for(let N of f.verdicts){if(N.verdict==="valid"||g.lessonsWritten.includes(N.findingId))continue;let V=g.findings.find(W=>W.id===N.findingId);V&&(so(b.repoPath,g.role,Xu(V,N.verdict,N.note,f.verdictBy)),I.push(N.findingId),m.info(`Lesson written (${g.role}): ${N.verdict} \u2014 ${V.title.slice(0,60)}`))}I.length&&(g=to(f.projectId,f.auditId,{markLessonsWritten:I})??g)}w.sendAuditReviewResult(f.requestId,{ok:!0,audit:g})}catch(g){w.sendAuditReviewResult(f.requestId,{ok:!1,error:g instanceof Error?g.message:String(g)})}},onKnowledgeList:async f=>{let g=S(f.projectId);if(!g){w.sendKnowledgeListResult(f.requestId,{ok:!1,error:"this runner has no local checkout mapped for that project"});return}try{w.sendKnowledgeListResult(f.requestId,{ok:!0,files:ec(g.repoPath)})}catch(b){w.sendKnowledgeListResult(f.requestId,{ok:!1,error:b instanceof Error?b.message:String(b)})}},onKnowledgeSave:async f=>{let g=S(f.projectId);if(!g){w.sendKnowledgeSaveResult(f.requestId,{ok:!1,error:"this runner has no local checkout mapped for that project"});return}try{f.append?so(g.repoPath,f.role,Qu(f.content,f.by),f.level):tc(g.repoPath,f.role,f.level,f.source,f.name,f.content),m.info(`Knowledge ${f.append?"taught":"saved"}: ${f.role}/${f.level}/${f.name}`),w.sendKnowledgeSaveResult(f.requestId,{ok:!0})}catch(b){w.sendKnowledgeSaveResult(f.requestId,{ok:!1,error:b instanceof Error?b.message:String(b)})}},onEpicList:async f=>{let g=S(f.projectId);if(!g){w.sendEpicListResult(f.requestId,{ok:!1,error:"this runner has no local checkout mapped for that project"});return}try{let b=n(g.project.repoName);if(f.epicKey){let I=await b.epicChildren(f.epicKey);w.sendEpicListResult(f.requestId,{ok:!0,children:I})}else{let I=await b.searchEpics(g.project.jiraProjectKey);w.sendEpicListResult(f.requestId,{ok:!0,epics:I})}}catch(b){w.sendEpicListResult(f.requestId,{ok:!1,error:b instanceof Error?b.message:String(b)})}},onEpicSuggest:async f=>{let g=S(f.projectId);if(!g){w.sendEpicSuggestResult(f.requestId,{ok:!1,error:"this runner has no local checkout mapped for that project"});return}try{let b=n(g.project.repoName),I=await b.epicChildren(f.epicKey),N=Ru(I);if(!N.length){w.sendEpicSuggestResult(f.requestId,{ok:!1,error:`every child of ${f.epicKey} is already done or in an agent's hands \u2014 nothing to sequence`});return}if(N.length===1){w.sendEpicSuggestResult(f.requestId,{ok:!0,issueKey:N[0].key,reason:"It's the only pending ticket left in this epic.",considered:1});return}let V=await Promise.all(N.slice(0,12).map(async H=>{try{let be=await b.getIssue(H.key);return{...H,description:be.description}}catch{return{...H,description:""}}})),W=(await b.getIssue(f.epicKey).catch(()=>null))?.summary??"";m.info(`Epic suggest: weighing ${V.length} pending children of ${f.epicKey}`);let J=await Ue.run({repoPath:g.repoPath,prompt:$u(f.epicKey,W,V),timeoutSeconds:150,bin:r.claudeBin,mode:"read_only",maxTurns:20,sessionId:(0,Xo.randomUUID)(),model:f.model||"claude-sonnet-5",onLog:()=>{}}),z=Pu(J.resultText,V.map(H=>H.key));if("error"in z){w.sendEpicSuggestResult(f.requestId,{ok:!1,error:z.error});return}m.info(`Epic suggest: ${f.epicKey} -> do ${z.issueKey} first`),w.sendEpicSuggestResult(f.requestId,{ok:!0,issueKey:z.issueKey,reason:z.reason,considered:V.length})}catch(b){w.sendEpicSuggestResult(f.requestId,{ok:!1,error:b instanceof Error?b.message:String(b)})}},onTeamCreds:async f=>{try{let g=ce()??r;if(g.github?.token&&!g.github.login)try{let{GitHubClient:I}=await Promise.resolve().then(()=>(ct(),tn));g.github.login=await new I(g.github.token).whoami(),ie(g)}catch{}let b=Tu(g,f.emails);w.sendTeamCredsResult(f.requestId,{ok:!0,...b})}catch(g){w.sendTeamCredsResult(f.requestId,{ok:!1,error:g instanceof Error?g.message:String(g)})}},onSetupStatus:async f=>{try{let g=ce()??r,{buildSetupReport:b}=await Promise.resolve().then(()=>(hd(),dd)),I=await b(g,f.repoNames);w.sendSetupStatusResult(f.requestId,{ok:!0,...I})}catch(g){w.sendSetupStatusResult(f.requestId,{ok:!1,error:g instanceof Error?g.message:String(g)})}},onJiraUsers:async f=>{try{let g=await e.searchUsers(f.query);w.sendJiraUsersResult(f.requestId,{ok:!0,users:g})}catch(g){w.sendJiraUsersResult(f.requestId,{ok:!1,users:[],error:g instanceof Error?g.message:String(g)})}}});p.transport=w,d=new qs(r,n,w);let j=Object.values(sn()).filter(f=>f.kind==="implement").map(f=>f.repoPath);Bi(Object.values(r.repos).map(f=>f.path),j).catch(()=>{}),w.start(),d.start();let U=()=>{m.info("shutting down"),d.stop(),w.stop(),La(process.pid),process.exit(0)};process.on("SIGINT",U),process.on("SIGTERM",U)}ae.command("start").description("Start watching Jira. Runs in the background by default \u2014 close this terminal and it keeps going until you run `allwright stop`. Use --foreground to keep it attached (e.g. under systemd).").option("--foreground","run in this terminal instead of detaching to the background").action(async r=>{let e=Q();if(r.foreground){cy(e);return}let t=qr();if(t&&Tn(t)){m.info(`already running in the background (pid ${t}). Use \`allwright status\` or \`stop\`.`);return}let n=Ma(),s=(0,Wn.spawn)(process.execPath,[process.argv[1],"start","--foreground"],{detached:!0,stdio:["ignore",n,n]});s.unref(),Da(s.pid),m.info(`Runner started in the background (pid ${s.pid}).`),m.info(`Logs: ${ds()}`),m.info("It will keep polling Jira until you run `allwright stop` \u2014 closing this terminal is fine.")});ae.command("stop").description("Stop the background runner started by `start`").action(()=>{let r=qr();if(!r||!Tn(r)){m.info("no background runner is running"),r&&yn.default.rmSync(Sn(),{force:!0});return}process.kill(r,"SIGTERM"),m.info(`stop signal sent (pid ${r})`)});ae.command("status").description("Check whether the background runner is running").action(()=>{let r=qr();r&&Tn(r)?m.info(`running in the background (pid ${r})`):m.info("not running")});ae.parseAsync().catch(r=>{m.error(r instanceof Error?r.message:String(r)),process.exit(1)});