@task-handoff/server 0.0.24 → 0.0.25-alpha.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.
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
"use strict";var e=require("node:fs"),t=require("node:path"),n=require("node:child_process"),i=require("node:events"),r=require("node:process"),o=require("fs"),s=require("node:crypto"),a=require("path"),c=require("util"),l=require("node:os");function u(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function d(e){if(Object.prototype.hasOwnProperty.call(e,"__esModule"))return e;var t=e.default;if("function"==typeof t){var n=function e(){var n=!1;try{n=this instanceof e}catch{}return n?Reflect.construct(t,arguments,this.constructor):t.apply(this,arguments)};n.prototype=t.prototype}else n={};return Object.defineProperty(n,"__esModule",{value:!0}),Object.keys(e).forEach(function(t){var i=Object.getOwnPropertyDescriptor(e,t);Object.defineProperty(n,t,i.get?i:{enumerable:!0,get:function(){return e[t]}})}),n}var p,m,h={},f={},g={},y={};function v(){if(p)return y;p=1;class e extends Error{constructor(e,t,n){super(n),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=t,this.exitCode=e,this.nestedError=void 0}}return y.CommanderError=e,y.InvalidArgumentError=class extends e{constructor(e){super(1,"commander.invalidArgument",e),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}},y}function _(){if(m)return g;m=1;const{InvalidArgumentError:e}=v();return g.Argument=class{constructor(e,t){switch(this.description=t||"",this.variadic=!1,this.parseArg=void 0,this.defaultValue=void 0,this.defaultValueDescription=void 0,this.argChoices=void 0,e[0]){case"<":this.required=!0,this._name=e.slice(1,-1);break;case"[":this.required=!1,this._name=e.slice(1,-1);break;default:this.required=!0,this._name=e}this._name.endsWith("...")&&(this.variadic=!0,this._name=this._name.slice(0,-3))}name(){return this._name}_collectValue(e,t){return t!==this.defaultValue&&Array.isArray(t)?(t.push(e),t):[e]}default(e,t){return this.defaultValue=e,this.defaultValueDescription=t,this}argParser(e){return this.parseArg=e,this}choices(t){return this.argChoices=t.slice(),this.parseArg=(t,n)=>{if(!this.argChoices.includes(t))throw new e(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._collectValue(t,n):t},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}},g.humanReadableArgName=function(e){const t=e.name()+(!0===e.variadic?"...":"");return e.required?"<"+t+">":"["+t+"]"},g}var b,A={},I={};function x(){if(b)return I;b=1;const{humanReadableArgName:e}=_();function t(e){return e.replace(/\x1b\[\d*(;\d*)*m/g,"")}return I.Help=class{constructor(){this.helpWidth=void 0,this.minWidthToWrap=40,this.sortSubcommands=!1,this.sortOptions=!1,this.showGlobalOptions=!1}prepareContext(e){this.helpWidth=this.helpWidth??e.helpWidth??80}visibleCommands(e){const t=e.commands.filter(e=>!e._hidden),n=e._getHelpCommand();return n&&!n._hidden&&t.push(n),this.sortSubcommands&&t.sort((e,t)=>e.name().localeCompare(t.name())),t}compareOptions(e,t){const n=e=>e.short?e.short.replace(/^-/,""):e.long.replace(/^--/,"");return n(e).localeCompare(n(t))}visibleOptions(e){const t=e.options.filter(e=>!e.hidden),n=e._getHelpOption();if(n&&!n.hidden){const i=n.short&&e._findOption(n.short),r=n.long&&e._findOption(n.long);i||r?n.long&&!r?t.push(e.createOption(n.long,n.description)):n.short&&!i&&t.push(e.createOption(n.short,n.description)):t.push(n)}return this.sortOptions&&t.sort(this.compareOptions),t}visibleGlobalOptions(e){if(!this.showGlobalOptions)return[];const t=[];for(let n=e.parent;n;n=n.parent){const e=n.options.filter(e=>!e.hidden);t.push(...e)}return this.sortOptions&&t.sort(this.compareOptions),t}visibleArguments(e){return e._argsDescription&&e.registeredArguments.forEach(t=>{t.description=t.description||e._argsDescription[t.name()]||""}),e.registeredArguments.find(e=>e.description)?e.registeredArguments:[]}subcommandTerm(t){const n=t.registeredArguments.map(t=>e(t)).join(" ");return t._name+(t._aliases[0]?"|"+t._aliases[0]:"")+(t.options.length?" [options]":"")+(n?" "+n:"")}optionTerm(e){return e.flags}argumentTerm(e){return e.name()}longestSubcommandTermLength(e,t){return t.visibleCommands(e).reduce((e,n)=>Math.max(e,this.displayWidth(t.styleSubcommandTerm(t.subcommandTerm(n)))),0)}longestOptionTermLength(e,t){return t.visibleOptions(e).reduce((e,n)=>Math.max(e,this.displayWidth(t.styleOptionTerm(t.optionTerm(n)))),0)}longestGlobalOptionTermLength(e,t){return t.visibleGlobalOptions(e).reduce((e,n)=>Math.max(e,this.displayWidth(t.styleOptionTerm(t.optionTerm(n)))),0)}longestArgumentTermLength(e,t){return t.visibleArguments(e).reduce((e,n)=>Math.max(e,this.displayWidth(t.styleArgumentTerm(t.argumentTerm(n)))),0)}commandUsage(e){let t=e._name;e._aliases[0]&&(t=t+"|"+e._aliases[0]);let n="";for(let t=e.parent;t;t=t.parent)n=t.name()+" "+n;return n+t+" "+e.usage()}commandDescription(e){return e.description()}subcommandDescription(e){return e.summary()||e.description()}optionDescription(e){const t=[];if(e.argChoices&&t.push(`choices: ${e.argChoices.map(e=>JSON.stringify(e)).join(", ")}`),void 0!==e.defaultValue&&(e.required||e.optional||e.isBoolean()&&"boolean"==typeof e.defaultValue)&&t.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),void 0!==e.presetArg&&e.optional&&t.push(`preset: ${JSON.stringify(e.presetArg)}`),void 0!==e.envVar&&t.push(`env: ${e.envVar}`),t.length>0){const n=`(${t.join(", ")})`;return e.description?`${e.description} ${n}`:n}return e.description}argumentDescription(e){const t=[];if(e.argChoices&&t.push(`choices: ${e.argChoices.map(e=>JSON.stringify(e)).join(", ")}`),void 0!==e.defaultValue&&t.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),t.length>0){const n=`(${t.join(", ")})`;return e.description?`${e.description} ${n}`:n}return e.description}formatItemList(e,t,n){return 0===t.length?[]:[n.styleTitle(e),...t,""]}groupItems(e,t,n){const i=new Map;return e.forEach(e=>{const t=n(e);i.has(t)||i.set(t,[])}),t.forEach(e=>{const t=n(e);i.has(t)||i.set(t,[]),i.get(t).push(e)}),i}formatHelp(e,t){const n=t.padWidth(e,t),i=t.helpWidth??80;function r(e,i){return t.formatItem(e,n,i,t)}let o=[`${t.styleTitle("Usage:")} ${t.styleUsage(t.commandUsage(e))}`,""];const s=t.commandDescription(e);s.length>0&&(o=o.concat([t.boxWrap(t.styleCommandDescription(s),i),""]));const a=t.visibleArguments(e).map(e=>r(t.styleArgumentTerm(t.argumentTerm(e)),t.styleArgumentDescription(t.argumentDescription(e))));o=o.concat(this.formatItemList("Arguments:",a,t));const c=this.groupItems(e.options,t.visibleOptions(e),e=>e.helpGroupHeading??"Options:");if(c.forEach((e,n)=>{const i=e.map(e=>r(t.styleOptionTerm(t.optionTerm(e)),t.styleOptionDescription(t.optionDescription(e))));o=o.concat(this.formatItemList(n,i,t))}),t.showGlobalOptions){const n=t.visibleGlobalOptions(e).map(e=>r(t.styleOptionTerm(t.optionTerm(e)),t.styleOptionDescription(t.optionDescription(e))));o=o.concat(this.formatItemList("Global Options:",n,t))}return this.groupItems(e.commands,t.visibleCommands(e),e=>e.helpGroup()||"Commands:").forEach((e,n)=>{const i=e.map(e=>r(t.styleSubcommandTerm(t.subcommandTerm(e)),t.styleSubcommandDescription(t.subcommandDescription(e))));o=o.concat(this.formatItemList(n,i,t))}),o.join("\n")}displayWidth(e){return t(e).length}styleTitle(e){return e}styleUsage(e){return e.split(" ").map(e=>"[options]"===e?this.styleOptionText(e):"[command]"===e?this.styleSubcommandText(e):"["===e[0]||"<"===e[0]?this.styleArgumentText(e):this.styleCommandText(e)).join(" ")}styleCommandDescription(e){return this.styleDescriptionText(e)}styleOptionDescription(e){return this.styleDescriptionText(e)}styleSubcommandDescription(e){return this.styleDescriptionText(e)}styleArgumentDescription(e){return this.styleDescriptionText(e)}styleDescriptionText(e){return e}styleOptionTerm(e){return this.styleOptionText(e)}styleSubcommandTerm(e){return e.split(" ").map(e=>"[options]"===e?this.styleOptionText(e):"["===e[0]||"<"===e[0]?this.styleArgumentText(e):this.styleSubcommandText(e)).join(" ")}styleArgumentTerm(e){return this.styleArgumentText(e)}styleOptionText(e){return e}styleArgumentText(e){return e}styleSubcommandText(e){return e}styleCommandText(e){return e}padWidth(e,t){return Math.max(t.longestOptionTermLength(e,t),t.longestGlobalOptionTermLength(e,t),t.longestSubcommandTermLength(e,t),t.longestArgumentTermLength(e,t))}preformatted(e){return/\n[^\S\r\n]/.test(e)}formatItem(e,t,n,i){const r=" ".repeat(2);if(!n)return r+e;const o=e.padEnd(t+e.length-i.displayWidth(e)),s=(this.helpWidth??80)-t-2-2;let a;return a=s<this.minWidthToWrap||i.preformatted(n)?n:i.boxWrap(n,s).replace(/\n/g,"\n"+" ".repeat(t+2)),r+o+" ".repeat(2)+a.replace(/\n/g,`\n${r}`)}boxWrap(e,t){if(t<this.minWidthToWrap)return e;const n=e.split(/\r\n|\n/),i=/[\s]*[^\s]+/g,r=[];return n.forEach(e=>{const n=e.match(i);if(null===n)return void r.push("");let o=[n.shift()],s=this.displayWidth(o[0]);n.forEach(e=>{const n=this.displayWidth(e);if(s+n<=t)return o.push(e),void(s+=n);r.push(o.join(""));const i=e.trimStart();o=[i],s=this.displayWidth(i)}),r.push(o.join(""))}),r.join("\n")}},I.stripColor=t,I}var S,w={};function E(){if(S)return w;S=1;const{InvalidArgumentError:e}=v();function t(e){return e.split("-").reduce((e,t)=>e+t[0].toUpperCase()+t.slice(1))}return w.Option=class{constructor(e,t){this.flags=e,this.description=t||"",this.required=e.includes("<"),this.optional=e.includes("["),this.variadic=/\w\.\.\.[>\]]$/.test(e),this.mandatory=!1;const n=function(e){let t,n;const i=/^-[^-]$/,r=/^--[^-]/,o=e.split(/[ |,]+/).concat("guard");if(i.test(o[0])&&(t=o.shift()),r.test(o[0])&&(n=o.shift()),!t&&i.test(o[0])&&(t=o.shift()),!t&&r.test(o[0])&&(t=n,n=o.shift()),o[0].startsWith("-")){const t=o[0],n=`option creation failed due to '${t}' in option flags '${e}'`;if(/^-[^-][^-]/.test(t))throw new Error(`${n}\n- a short flag is a single dash and a single character\n - either use a single dash and a single character (for a short flag)\n - or use a double dash for a long option (and can have two, like '--ws, --workspace')`);if(i.test(t))throw new Error(`${n}\n- too many short flags`);if(r.test(t))throw new Error(`${n}\n- too many long flags`);throw new Error(`${n}\n- unrecognised flag format`)}if(void 0===t&&void 0===n)throw new Error(`option creation failed due to no flags found in '${e}'.`);return{shortFlag:t,longFlag:n}}(e);this.short=n.shortFlag,this.long=n.longFlag,this.negate=!1,this.long&&(this.negate=this.long.startsWith("--no-")),this.defaultValue=void 0,this.defaultValueDescription=void 0,this.presetArg=void 0,this.envVar=void 0,this.parseArg=void 0,this.hidden=!1,this.argChoices=void 0,this.conflictsWith=[],this.implied=void 0,this.helpGroupHeading=void 0}default(e,t){return this.defaultValue=e,this.defaultValueDescription=t,this}preset(e){return this.presetArg=e,this}conflicts(e){return this.conflictsWith=this.conflictsWith.concat(e),this}implies(e){let t=e;return"string"==typeof e&&(t={[e]:!0}),this.implied=Object.assign(this.implied||{},t),this}env(e){return this.envVar=e,this}argParser(e){return this.parseArg=e,this}makeOptionMandatory(e=!0){return this.mandatory=!!e,this}hideHelp(e=!0){return this.hidden=!!e,this}_collectValue(e,t){return t!==this.defaultValue&&Array.isArray(t)?(t.push(e),t):[e]}choices(t){return this.argChoices=t.slice(),this.parseArg=(t,n)=>{if(!this.argChoices.includes(t))throw new e(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._collectValue(t,n):t},this}name(){return this.long?this.long.replace(/^--/,""):this.short.replace(/^-/,"")}attributeName(){return this.negate?t(this.name().replace(/^no-/,"")):t(this.name())}helpGroup(e){return this.helpGroupHeading=e,this}is(e){return this.short===e||this.long===e}isBoolean(){return!this.required&&!this.optional&&!this.negate}},w.DualOptions=class{constructor(e){this.positiveOptions=new Map,this.negativeOptions=new Map,this.dualOptions=new Set,e.forEach(e=>{e.negate?this.negativeOptions.set(e.attributeName(),e):this.positiveOptions.set(e.attributeName(),e)}),this.negativeOptions.forEach((e,t)=>{this.positiveOptions.has(t)&&this.dualOptions.add(t)})}valueFromOption(e,t){const n=t.attributeName();if(!this.dualOptions.has(n))return!0;const i=this.negativeOptions.get(n).presetArg,r=void 0!==i&&i;return t.negate===(r===e)}},w}var O,k,C,T={};function $(){return O||(O=1,T.suggestSimilar=function(e,t){if(!t||0===t.length)return"";t=Array.from(new Set(t));const n=e.startsWith("--");n&&(e=e.slice(2),t=t.map(e=>e.slice(2)));let i=[],r=3;return t.forEach(t=>{if(t.length<=1)return;const n=function(e,t){if(Math.abs(e.length-t.length)>3)return Math.max(e.length,t.length);const n=[];for(let t=0;t<=e.length;t++)n[t]=[t];for(let e=0;e<=t.length;e++)n[0][e]=e;for(let i=1;i<=t.length;i++)for(let r=1;r<=e.length;r++){let o=1;o=e[r-1]===t[i-1]?0:1,n[r][i]=Math.min(n[r-1][i]+1,n[r][i-1]+1,n[r-1][i-1]+o),r>1&&i>1&&e[r-1]===t[i-2]&&e[r-2]===t[i-1]&&(n[r][i]=Math.min(n[r][i],n[r-2][i-2]+1))}return n[e.length][t.length]}(e,t),o=Math.max(e.length,t.length);(o-n)/o>.4&&(n<r?(r=n,i=[t]):n===r&&i.push(t))}),i.sort((e,t)=>e.localeCompare(t)),n&&(i=i.map(e=>`--${e}`)),i.length>1?`\n(Did you mean one of ${i.join(", ")}?)`:1===i.length?`\n(Did you mean ${i[0]}?)`:""}),T}var N,R,P,z,L,j,D,M,F,V,U,H,G,Z,q,B,W,J,X,Y,K,Q,ee,te,ne,ie,re,oe,se,ae,ce,le,ue,de,pe,me,he,fe,ge,ye,ve,_e,be,Ae,Ie,xe,Se,we,Ee,Oe,ke,Ce,Te,$e,Ne,Re,Pe,ze,Le,je,De,Me,Fe,Ve,Ue,He,Ge,Ze,qe,Be,We,Je,Xe,Ye,Ke,Qe,et,tt,nt,it,rt,ot,st,at,ct,lt,ut,dt,pt,mt,ht,ft={exports:{}};function gt(){if(R)return N;R=1;const e=Number.MAX_SAFE_INTEGER||9007199254740991;return N={MAX_LENGTH:256,MAX_SAFE_COMPONENT_LENGTH:16,MAX_SAFE_BUILD_LENGTH:250,MAX_SAFE_INTEGER:e,RELEASE_TYPES:["major","premajor","minor","preminor","patch","prepatch","prerelease"],SEMVER_SPEC_VERSION:"2.0.0",FLAG_INCLUDE_PRERELEASE:1,FLAG_LOOSE:2}}function yt(){if(z)return P;z=1;const e="object"==typeof process&&process.env&&process.env.NODE_DEBUG&&/\bsemver\b/i.test(process.env.NODE_DEBUG)?(...e)=>console.error("SEMVER",...e):()=>{};return P=e}function vt(){return L||(L=1,function(e,t){const{MAX_SAFE_COMPONENT_LENGTH:n,MAX_SAFE_BUILD_LENGTH:i,MAX_LENGTH:r}=gt(),o=yt(),s=(t=e.exports={}).re=[],a=t.safeRe=[],c=t.src=[],l=t.safeSrc=[],u=t.t={};let d=0;const p="[a-zA-Z0-9-]",m=[["\\s",1],["\\d",r],[p,i]],h=(e,t,n)=>{const i=(e=>{for(const[t,n]of m)e=e.split(`${t}*`).join(`${t}{0,${n}}`).split(`${t}+`).join(`${t}{1,${n}}`);return e})(t),r=d++;o(e,r,t),u[e]=r,c[r]=t,l[r]=i,s[r]=new RegExp(t,n?"g":void 0),a[r]=new RegExp(i,n?"g":void 0)};h("NUMERICIDENTIFIER","0|[1-9]\\d*"),h("NUMERICIDENTIFIERLOOSE","\\d+"),h("NONNUMERICIDENTIFIER",`\\d*[a-zA-Z-]${p}*`),h("MAINVERSION",`(${c[u.NUMERICIDENTIFIER]})\\.(${c[u.NUMERICIDENTIFIER]})\\.(${c[u.NUMERICIDENTIFIER]})`),h("MAINVERSIONLOOSE",`(${c[u.NUMERICIDENTIFIERLOOSE]})\\.(${c[u.NUMERICIDENTIFIERLOOSE]})\\.(${c[u.NUMERICIDENTIFIERLOOSE]})`),h("PRERELEASEIDENTIFIER",`(?:${c[u.NONNUMERICIDENTIFIER]}|${c[u.NUMERICIDENTIFIER]})`),h("PRERELEASEIDENTIFIERLOOSE",`(?:${c[u.NONNUMERICIDENTIFIER]}|${c[u.NUMERICIDENTIFIERLOOSE]})`),h("PRERELEASE",`(?:-(${c[u.PRERELEASEIDENTIFIER]}(?:\\.${c[u.PRERELEASEIDENTIFIER]})*))`),h("PRERELEASELOOSE",`(?:-?(${c[u.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${c[u.PRERELEASEIDENTIFIERLOOSE]})*))`),h("BUILDIDENTIFIER",`${p}+`),h("BUILD",`(?:\\+(${c[u.BUILDIDENTIFIER]}(?:\\.${c[u.BUILDIDENTIFIER]})*))`),h("FULLPLAIN",`v?${c[u.MAINVERSION]}${c[u.PRERELEASE]}?${c[u.BUILD]}?`),h("FULL",`^${c[u.FULLPLAIN]}$`),h("LOOSEPLAIN",`[v=\\s]*${c[u.MAINVERSIONLOOSE]}${c[u.PRERELEASELOOSE]}?${c[u.BUILD]}?`),h("LOOSE",`^${c[u.LOOSEPLAIN]}$`),h("GTLT","((?:<|>)?=?)"),h("XRANGEIDENTIFIERLOOSE",`${c[u.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`),h("XRANGEIDENTIFIER",`${c[u.NUMERICIDENTIFIER]}|x|X|\\*`),h("XRANGEPLAIN",`[v=\\s]*(${c[u.XRANGEIDENTIFIER]})(?:\\.(${c[u.XRANGEIDENTIFIER]})(?:\\.(${c[u.XRANGEIDENTIFIER]})(?:${c[u.PRERELEASE]})?${c[u.BUILD]}?)?)?`),h("XRANGEPLAINLOOSE",`[v=\\s]*(${c[u.XRANGEIDENTIFIERLOOSE]})(?:\\.(${c[u.XRANGEIDENTIFIERLOOSE]})(?:\\.(${c[u.XRANGEIDENTIFIERLOOSE]})(?:${c[u.PRERELEASELOOSE]})?${c[u.BUILD]}?)?)?`),h("XRANGE",`^${c[u.GTLT]}\\s*${c[u.XRANGEPLAIN]}$`),h("XRANGELOOSE",`^${c[u.GTLT]}\\s*${c[u.XRANGEPLAINLOOSE]}$`),h("COERCEPLAIN",`(^|[^\\d])(\\d{1,${n}})(?:\\.(\\d{1,${n}}))?(?:\\.(\\d{1,${n}}))?`),h("COERCE",`${c[u.COERCEPLAIN]}(?:$|[^\\d])`),h("COERCEFULL",c[u.COERCEPLAIN]+`(?:${c[u.PRERELEASE]})?`+`(?:${c[u.BUILD]})?(?:$|[^\\d])`),h("COERCERTL",c[u.COERCE],!0),h("COERCERTLFULL",c[u.COERCEFULL],!0),h("LONETILDE","(?:~>?)"),h("TILDETRIM",`(\\s*)${c[u.LONETILDE]}\\s+`,!0),t.tildeTrimReplace="$1~",h("TILDE",`^${c[u.LONETILDE]}${c[u.XRANGEPLAIN]}$`),h("TILDELOOSE",`^${c[u.LONETILDE]}${c[u.XRANGEPLAINLOOSE]}$`),h("LONECARET","(?:\\^)"),h("CARETTRIM",`(\\s*)${c[u.LONECARET]}\\s+`,!0),t.caretTrimReplace="$1^",h("CARET",`^${c[u.LONECARET]}${c[u.XRANGEPLAIN]}$`),h("CARETLOOSE",`^${c[u.LONECARET]}${c[u.XRANGEPLAINLOOSE]}$`),h("COMPARATORLOOSE",`^${c[u.GTLT]}\\s*(${c[u.LOOSEPLAIN]})$|^$`),h("COMPARATOR",`^${c[u.GTLT]}\\s*(${c[u.FULLPLAIN]})$|^$`),h("COMPARATORTRIM",`(\\s*)${c[u.GTLT]}\\s*(${c[u.LOOSEPLAIN]}|${c[u.XRANGEPLAIN]})`,!0),t.comparatorTrimReplace="$1$2$3",h("HYPHENRANGE",`^\\s*(${c[u.XRANGEPLAIN]})\\s+-\\s+(${c[u.XRANGEPLAIN]})\\s*$`),h("HYPHENRANGELOOSE",`^\\s*(${c[u.XRANGEPLAINLOOSE]})\\s+-\\s+(${c[u.XRANGEPLAINLOOSE]})\\s*$`),h("STAR","(<|>)?=?\\s*\\*"),h("GTE0","^\\s*>=\\s*0\\.0\\.0\\s*$"),h("GTE0PRE","^\\s*>=\\s*0\\.0\\.0-0\\s*$")}(ft,ft.exports)),ft.exports}function _t(){if(D)return j;D=1;const e=Object.freeze({loose:!0}),t=Object.freeze({});return j=n=>n?"object"!=typeof n?e:n:t}function bt(){if(F)return M;F=1;const e=/^[0-9]+$/,t=(t,n)=>{if("number"==typeof t&&"number"==typeof n)return t===n?0:t<n?-1:1;const i=e.test(t),r=e.test(n);return i&&r&&(t=+t,n=+n),t===n?0:i&&!r?-1:r&&!i?1:t<n?-1:1};return M={compareIdentifiers:t,rcompareIdentifiers:(e,n)=>t(n,e)}}function At(){if(U)return V;U=1;const e=yt(),{MAX_LENGTH:t,MAX_SAFE_INTEGER:n}=gt(),{safeRe:i,t:r}=vt(),o=_t(),{compareIdentifiers:s}=bt();class a{constructor(s,c){if(c=o(c),s instanceof a){if(s.loose===!!c.loose&&s.includePrerelease===!!c.includePrerelease)return s;s=s.version}else if("string"!=typeof s)throw new TypeError(`Invalid version. Must be a string. Got type "${typeof s}".`);if(s.length>t)throw new TypeError(`version is longer than ${t} characters`);e("SemVer",s,c),this.options=c,this.loose=!!c.loose,this.includePrerelease=!!c.includePrerelease;const l=s.trim().match(c.loose?i[r.LOOSE]:i[r.FULL]);if(!l)throw new TypeError(`Invalid Version: ${s}`);if(this.raw=s,this.major=+l[1],this.minor=+l[2],this.patch=+l[3],this.major>n||this.major<0)throw new TypeError("Invalid major version");if(this.minor>n||this.minor<0)throw new TypeError("Invalid minor version");if(this.patch>n||this.patch<0)throw new TypeError("Invalid patch version");l[4]?this.prerelease=l[4].split(".").map(e=>{if(/^[0-9]+$/.test(e)){const t=+e;if(t>=0&&t<n)return t}return e}):this.prerelease=[],this.build=l[5]?l[5].split("."):[],this.format()}format(){return this.version=`${this.major}.${this.minor}.${this.patch}`,this.prerelease.length&&(this.version+=`-${this.prerelease.join(".")}`),this.version}toString(){return this.version}compare(t){if(e("SemVer.compare",this.version,this.options,t),!(t instanceof a)){if("string"==typeof t&&t===this.version)return 0;t=new a(t,this.options)}return t.version===this.version?0:this.compareMain(t)||this.comparePre(t)}compareMain(e){return e instanceof a||(e=new a(e,this.options)),this.major<e.major?-1:this.major>e.major?1:this.minor<e.minor?-1:this.minor>e.minor?1:this.patch<e.patch?-1:this.patch>e.patch?1:0}comparePre(t){if(t instanceof a||(t=new a(t,this.options)),this.prerelease.length&&!t.prerelease.length)return-1;if(!this.prerelease.length&&t.prerelease.length)return 1;if(!this.prerelease.length&&!t.prerelease.length)return 0;let n=0;do{const i=this.prerelease[n],r=t.prerelease[n];if(e("prerelease compare",n,i,r),void 0===i&&void 0===r)return 0;if(void 0===r)return 1;if(void 0===i)return-1;if(i!==r)return s(i,r)}while(++n)}compareBuild(t){t instanceof a||(t=new a(t,this.options));let n=0;do{const i=this.build[n],r=t.build[n];if(e("build compare",n,i,r),void 0===i&&void 0===r)return 0;if(void 0===r)return 1;if(void 0===i)return-1;if(i!==r)return s(i,r)}while(++n)}inc(e,t,n){if(e.startsWith("pre")){if(!t&&!1===n)throw new Error("invalid increment argument: identifier is empty");if(t){const e=`-${t}`.match(this.options.loose?i[r.PRERELEASELOOSE]:i[r.PRERELEASE]);if(!e||e[1]!==t)throw new Error(`invalid identifier: ${t}`)}}switch(e){case"premajor":this.prerelease.length=0,this.patch=0,this.minor=0,this.major++,this.inc("pre",t,n);break;case"preminor":this.prerelease.length=0,this.patch=0,this.minor++,this.inc("pre",t,n);break;case"prepatch":this.prerelease.length=0,this.inc("patch",t,n),this.inc("pre",t,n);break;case"prerelease":0===this.prerelease.length&&this.inc("patch",t,n),this.inc("pre",t,n);break;case"release":if(0===this.prerelease.length)throw new Error(`version ${this.raw} is not a prerelease`);this.prerelease.length=0;break;case"major":0===this.minor&&0===this.patch&&0!==this.prerelease.length||this.major++,this.minor=0,this.patch=0,this.prerelease=[];break;case"minor":0===this.patch&&0!==this.prerelease.length||this.minor++,this.patch=0,this.prerelease=[];break;case"patch":0===this.prerelease.length&&this.patch++,this.prerelease=[];break;case"pre":{const e=Number(n)?1:0;if(0===this.prerelease.length)this.prerelease=[e];else{let i=this.prerelease.length;for(;--i>=0;)"number"==typeof this.prerelease[i]&&(this.prerelease[i]++,i=-2);if(-1===i){if(t===this.prerelease.join(".")&&!1===n)throw new Error("invalid increment argument: identifier already exists");this.prerelease.push(e)}}if(t){let i=[t,e];if(!1===n&&(i=[t]),((e,t)=>{const n=t.split(".");if(n.length>e.length)return!1;for(let t=0;t<n.length;t++)if(0!==s(e[t],n[t]))return!1;return!0})(this.prerelease,t)){const e=this.prerelease[t.split(".").length];isNaN(e)&&(this.prerelease=i)}else this.prerelease=i}break}default:throw new Error(`invalid increment argument: ${e}`)}return this.raw=this.format(),this.build.length&&(this.raw+=`+${this.build.join(".")}`),this}}return V=a}function It(){if(G)return H;G=1;const e=At();return H=(t,n,i=!1)=>{if(t instanceof e)return t;try{return new e(t,n)}catch(e){if(!i)return null;throw e}},H}function xt(){if(ce)return ae;ce=1;const e=At();return ae=(t,n,i)=>new e(t,i).compare(new e(n,i))}function St(){if(he)return me;he=1;const e=At();return me=(t,n,i)=>{const r=new e(t,i),o=new e(n,i);return r.compare(o)||r.compareBuild(o)}}function wt(){if(be)return _e;be=1;const e=xt();return _e=(t,n,i)=>e(t,n,i)>0}function Et(){if(Ie)return Ae;Ie=1;const e=xt();return Ae=(t,n,i)=>e(t,n,i)<0}function Ot(){if(Se)return xe;Se=1;const e=xt();return xe=(t,n,i)=>0===e(t,n,i)}function kt(){if(Ee)return we;Ee=1;const e=xt();return we=(t,n,i)=>0!==e(t,n,i)}function Ct(){if(ke)return Oe;ke=1;const e=xt();return Oe=(t,n,i)=>e(t,n,i)>=0}function Tt(){if(Te)return Ce;Te=1;const e=xt();return Ce=(t,n,i)=>e(t,n,i)<=0}function $t(){if(Ne)return $e;Ne=1;const e=Ot(),t=kt(),n=wt(),i=Ct(),r=Et(),o=Tt();return $e=(s,a,c,l)=>{switch(a){case"===":return"object"==typeof s&&(s=s.version),"object"==typeof c&&(c=c.version),s===c;case"!==":return"object"==typeof s&&(s=s.version),"object"==typeof c&&(c=c.version),s!==c;case"":case"=":case"==":return e(s,c,l);case"!=":return t(s,c,l);case">":return n(s,c,l);case">=":return i(s,c,l);case"<":return r(s,c,l);case"<=":return o(s,c,l);default:throw new TypeError(`Invalid operator: ${a}`)}}}function Nt(){if(Fe)return Me;Fe=1;const e=/\s+/g;class t{constructor(n,o){if(o=i(o),n instanceof t)return n.loose===!!o.loose&&n.includePrerelease===!!o.includePrerelease?n:new t(n.raw,o);if(n instanceof r)return this.raw=n.value,this.set=[[n]],this.formatted=void 0,this;if(this.options=o,this.loose=!!o.loose,this.includePrerelease=!!o.includePrerelease,this.raw=n.trim().replace(e," "),this.set=this.raw.split("||").map(e=>this.parseRange(e.trim())).filter(e=>e.length),!this.set.length)throw new TypeError(`Invalid SemVer Range: ${this.raw}`);if(this.set.length>1){const e=this.set[0];if(this.set=this.set.filter(e=>!g(e[0])),0===this.set.length)this.set=[e];else if(this.set.length>1)for(const e of this.set)if(1===e.length&&y(e[0])){this.set=[e];break}}this.formatted=void 0}get range(){if(void 0===this.formatted){this.formatted="";for(let e=0;e<this.set.length;e++){e>0&&(this.formatted+="||");const t=this.set[e];for(let e=0;e<t.length;e++)e>0&&(this.formatted+=" "),this.formatted+=t[e].toString().trim()}}return this.formatted}format(){return this.range}toString(){return this.range}parseRange(e){e=e.replace(f,"");const t=((this.options.includePrerelease&&m)|(this.options.loose&&h))+":"+e,i=n.get(t);if(i)return i;const s=this.options.loose,c=s?a[l.HYPHENRANGELOOSE]:a[l.HYPHENRANGE];e=e.replace(c,C(this.options.includePrerelease)),o("hyphen replace",e),e=e.replace(a[l.COMPARATORTRIM],u),o("comparator trim",e),e=e.replace(a[l.TILDETRIM],d),o("tilde trim",e),e=e.replace(a[l.CARETTRIM],p),o("caret trim",e);let y=e.split(" ").map(e=>_(e,this.options)).join(" ").split(/\s+/).map(e=>k(e,this.options));s&&(y=y.filter(e=>(o("loose invalid filter",e,this.options),!!e.match(a[l.COMPARATORLOOSE])))),o("range list",y);const v=new Map,b=y.map(e=>new r(e,this.options));for(const e of b){if(g(e))return[e];v.set(e.value,e)}v.size>1&&v.has("")&&v.delete("");const A=[...v.values()];return n.set(t,A),A}intersects(e,n){if(!(e instanceof t))throw new TypeError("a Range is required");return this.set.some(t=>v(t,n)&&e.set.some(e=>v(e,n)&&t.every(t=>e.every(e=>t.intersects(e,n)))))}test(e){if(!e)return!1;if("string"==typeof e)try{e=new s(e,this.options)}catch(e){return!1}for(let t=0;t<this.set.length;t++)if(T(this.set[t],e,this.options))return!0;return!1}}Me=t;const n=new(De?je:(De=1,je=class{constructor(){this.max=1e3,this.map=new Map}get(e){const t=this.map.get(e);return void 0===t?void 0:(this.map.delete(e),this.map.set(e,t),t)}delete(e){return this.map.delete(e)}set(e,t){if(!this.delete(e)&&void 0!==t){if(this.map.size>=this.max){const e=this.map.keys().next().value;this.delete(e)}this.map.set(e,t)}return this}})),i=_t(),r=Rt(),o=yt(),s=At(),{safeRe:a,src:c,t:l,comparatorTrimReplace:u,tildeTrimReplace:d,caretTrimReplace:p}=vt(),{FLAG_INCLUDE_PRERELEASE:m,FLAG_LOOSE:h}=gt(),f=new RegExp(c[l.BUILD],"g"),g=e=>"<0.0.0-0"===e.value,y=e=>""===e.value,v=(e,t)=>{let n=!0;const i=e.slice();let r=i.pop();for(;n&&i.length;)n=i.every(e=>r.intersects(e,t)),r=i.pop();return n},_=(e,t)=>(e=e.replace(a[l.BUILD],""),o("comp",e,t),e=x(e,t),o("caret",e),e=A(e,t),o("tildes",e),e=w(e,t),o("xrange",e),e=O(e,t),o("stars",e),e),b=e=>!e||"x"===e.toLowerCase()||"*"===e,A=(e,t)=>e.trim().split(/\s+/).map(e=>I(e,t)).join(" "),I=(e,t)=>{const n=t.loose?a[l.TILDELOOSE]:a[l.TILDE],i=t.includePrerelease?"-0":"";return e.replace(n,(t,n,r,s,a)=>{let c;return o("tilde",e,t,n,r,s,a),b(n)?c="":b(r)?c=`>=${n}.0.0${i} <${+n+1}.0.0-0`:b(s)?c=`>=${n}.${r}.0${i} <${n}.${+r+1}.0-0`:a?(o("replaceTilde pr",a),c=`>=${n}.${r}.${s}-${a} <${n}.${+r+1}.0-0`):c=`>=${n}.${r}.${s} <${n}.${+r+1}.0-0`,o("tilde return",c),c})},x=(e,t)=>e.trim().split(/\s+/).map(e=>S(e,t)).join(" "),S=(e,t)=>{o("caret",e,t);const n=t.loose?a[l.CARETLOOSE]:a[l.CARET],i=t.includePrerelease?"-0":"";return e.replace(n,(t,n,r,s,a)=>{let c;return o("caret",e,t,n,r,s,a),b(n)?c="":b(r)?c=`>=${n}.0.0${i} <${+n+1}.0.0-0`:b(s)?c="0"===n?`>=${n}.${r}.0${i} <${n}.${+r+1}.0-0`:`>=${n}.${r}.0${i} <${+n+1}.0.0-0`:a?(o("replaceCaret pr",a),c="0"===n?"0"===r?`>=${n}.${r}.${s}-${a} <${n}.${r}.${+s+1}-0`:`>=${n}.${r}.${s}-${a} <${n}.${+r+1}.0-0`:`>=${n}.${r}.${s}-${a} <${+n+1}.0.0-0`):(o("no pr"),c="0"===n?"0"===r?`>=${n}.${r}.${s} <${n}.${r}.${+s+1}-0`:`>=${n}.${r}.${s} <${n}.${+r+1}.0-0`:`>=${n}.${r}.${s} <${+n+1}.0.0-0`),o("caret return",c),c})},w=(e,t)=>(o("replaceXRanges",e,t),e.split(/\s+/).map(e=>E(e,t)).join(" ")),E=(e,t)=>{e=e.trim();const n=t.loose?a[l.XRANGELOOSE]:a[l.XRANGE];return e.replace(n,(n,i,r,s,a,c)=>{if(o("xRange",e,n,i,r,s,a,c),((e,t,n)=>b(e)&&!b(t)||b(t)&&n&&!b(n))(r,s,a))return e;const l=b(r),u=l||b(s),d=u||b(a),p=d;return"="===i&&p&&(i=""),c=t.includePrerelease?"-0":"",l?n=">"===i||"<"===i?"<0.0.0-0":"*":i&&p?(u&&(s=0),a=0,">"===i?(i=">=",u?(r=+r+1,s=0,a=0):(s=+s+1,a=0)):"<="===i&&(i="<",u?r=+r+1:s=+s+1),"<"===i&&(c="-0"),n=`${i+r}.${s}.${a}${c}`):u?n=`>=${r}.0.0${c} <${+r+1}.0.0-0`:d&&(n=`>=${r}.${s}.0${c} <${r}.${+s+1}.0-0`),o("xRange return",n),n})},O=(e,t)=>(o("replaceStars",e,t),e.trim().replace(a[l.STAR],"")),k=(e,t)=>(o("replaceGTE0",e,t),e.trim().replace(a[t.includePrerelease?l.GTE0PRE:l.GTE0],"")),C=e=>(t,n,i,r,o,s,a,c,l,u,d,p)=>`${n=b(i)?"":b(r)?`>=${i}.0.0${e?"-0":""}`:b(o)?`>=${i}.${r}.0${e?"-0":""}`:s?`>=${n}`:`>=${n}${e?"-0":""}`} ${c=b(l)?"":b(u)?`<${+l+1}.0.0-0`:b(d)?`<${l}.${+u+1}.0-0`:p?`<=${l}.${u}.${d}-${p}`:e?`<${l}.${u}.${+d+1}-0`:`<=${c}`}`.trim(),T=(e,t,n)=>{for(let n=0;n<e.length;n++)if(!e[n].test(t))return!1;if(t.prerelease.length&&!n.includePrerelease){for(let n=0;n<e.length;n++)if(o(e[n].semver),e[n].semver!==r.ANY&&e[n].semver.prerelease.length>0){const i=e[n].semver;if(i.major===t.major&&i.minor===t.minor&&i.patch===t.patch)return!0}return!1}return!0};return Me}function Rt(){if(Ue)return Ve;Ue=1;const e=Symbol("SemVer ANY");class t{static get ANY(){return e}constructor(i,r){if(r=n(r),i instanceof t){if(i.loose===!!r.loose)return i;i=i.value}i=i.trim().split(/\s+/).join(" "),s("comparator",i,r),this.options=r,this.loose=!!r.loose,this.parse(i),this.semver===e?this.value="":this.value=this.operator+this.semver.version,s("comp",this)}parse(t){const n=this.options.loose?i[r.COMPARATORLOOSE]:i[r.COMPARATOR],o=t.match(n);if(!o)throw new TypeError(`Invalid comparator: ${t}`);this.operator=void 0!==o[1]?o[1]:"","="===this.operator&&(this.operator=""),o[2]?this.semver=new a(o[2],this.options.loose):this.semver=e}toString(){return this.value}test(t){if(s("Comparator.test",t,this.options.loose),this.semver===e||t===e)return!0;if("string"==typeof t)try{t=new a(t,this.options)}catch(e){return!1}return o(t,this.operator,this.semver,this.options)}intersects(e,i){if(!(e instanceof t))throw new TypeError("a Comparator is required");return""===this.operator?""===this.value||new c(e.value,i).test(this.value):""===e.operator?""===e.value||new c(this.value,i).test(e.semver):!((i=n(i)).includePrerelease&&("<0.0.0-0"===this.value||"<0.0.0-0"===e.value)||!i.includePrerelease&&(this.value.startsWith("<0.0.0")||e.value.startsWith("<0.0.0"))||(!this.operator.startsWith(">")||!e.operator.startsWith(">"))&&(!this.operator.startsWith("<")||!e.operator.startsWith("<"))&&(this.semver.version!==e.semver.version||!this.operator.includes("=")||!e.operator.includes("="))&&!(o(this.semver,"<",e.semver,i)&&this.operator.startsWith(">")&&e.operator.startsWith("<"))&&!(o(this.semver,">",e.semver,i)&&this.operator.startsWith("<")&&e.operator.startsWith(">")))}}Ve=t;const n=_t(),{safeRe:i,t:r}=vt(),o=$t(),s=yt(),a=At(),c=Nt();return Ve}function Pt(){if(Ge)return He;Ge=1;const e=Nt();return He=(t,n,i)=>{try{n=new e(n,i)}catch(e){return!1}return n.test(t)},He}function zt(){if(et)return Qe;et=1;const e=Nt();return Qe=(t,n)=>{try{return new e(t,n).range||"*"}catch(e){return null}},Qe}function Lt(){if(nt)return tt;nt=1;const e=At(),t=Rt(),{ANY:n}=t,i=Nt(),r=Pt(),o=wt(),s=Et(),a=Tt(),c=Ct();return tt=(l,u,d,p)=>{let m,h,f,g,y;switch(l=new e(l,p),u=new i(u,p),d){case">":m=o,h=a,f=s,g=">",y=">=";break;case"<":m=s,h=c,f=o,g="<",y="<=";break;default:throw new TypeError('Must provide a hilo val of "<" or ">"')}if(r(l,u,p))return!1;for(let e=0;e<u.set.length;++e){const i=u.set[e];let r=null,o=null;if(i.forEach(e=>{e.semver===n&&(e=new t(">=0.0.0")),r=r||e,o=o||e,m(e.semver,r.semver,p)?r=e:f(e.semver,o.semver,p)&&(o=e)}),r.operator===g||r.operator===y)return!1;if((!o.operator||o.operator===g)&&h(l,o.semver))return!1;if(o.operator===y&&f(l,o.semver))return!1}return!0},tt}function jt(){if(ht)return mt;ht=1;const e=vt(),t=gt(),n=At(),i=bt(),r=It(),o=function(){if(q)return Z;q=1;const e=It();return Z=(t,n)=>{const i=e(t,n);return i?i.version:null},Z}(),s=function(){if(W)return B;W=1;const e=It();return B=(t,n)=>{const i=e(t.trim().replace(/^[=v]+/,""),n);return i?i.version:null},B}(),a=function(){if(X)return J;X=1;const e=At();return J=(t,n,i,r,o)=>{"string"==typeof i&&(o=r,r=i,i=void 0);try{return new e(t instanceof e?t.version:t,i).inc(n,r,o).version}catch(e){return null}},J}(),c=function(){if(K)return Y;K=1;const e=It();return Y=(t,n)=>{const i=e(t,null,!0),r=e(n,null,!0),o=i.compare(r);if(0===o)return null;const s=o>0,a=s?i:r,c=s?r:i,l=!!a.prerelease.length;if(c.prerelease.length&&!l){if(!c.patch&&!c.minor)return"major";if(0===c.compareMain(a))return c.minor&&!c.patch?"minor":"patch"}const u=l?"pre":"";return i.major!==r.major?u+"major":i.minor!==r.minor?u+"minor":i.patch!==r.patch?u+"patch":"prerelease"}}(),l=function(){if(ee)return Q;ee=1;const e=At();return Q=(t,n)=>new e(t,n).major}(),u=function(){if(ne)return te;ne=1;const e=At();return te=(t,n)=>new e(t,n).minor}(),d=function(){if(re)return ie;re=1;const e=At();return ie=(t,n)=>new e(t,n).patch}(),p=function(){if(se)return oe;se=1;const e=It();return oe=(t,n)=>{const i=e(t,n);return i&&i.prerelease.length?i.prerelease:null},oe}(),m=xt(),h=function(){if(ue)return le;ue=1;const e=xt();return le=(t,n,i)=>e(n,t,i)}(),f=function(){if(pe)return de;pe=1;const e=xt();return de=(t,n)=>e(t,n,!0)}(),g=St(),y=function(){if(ge)return fe;ge=1;const e=St();return fe=(t,n)=>t.sort((t,i)=>e(t,i,n))}(),v=function(){if(ve)return ye;ve=1;const e=St();return ye=(t,n)=>t.sort((t,i)=>e(i,t,n))}(),_=wt(),b=Et(),A=Ot(),I=kt(),x=Ct(),S=Tt(),w=$t(),E=function(){if(Pe)return Re;Pe=1;const e=At(),t=It(),{safeRe:n,t:i}=vt();return Re=(r,o)=>{if(r instanceof e)return r;if("number"==typeof r&&(r=String(r)),"string"!=typeof r)return null;let s=null;if((o=o||{}).rtl){const e=o.includePrerelease?n[i.COERCERTLFULL]:n[i.COERCERTL];let t;for(;(t=e.exec(r))&&(!s||s.index+s[0].length!==r.length);)s&&t.index+t[0].length===s.index+s[0].length||(s=t),e.lastIndex=t.index+t[1].length+t[2].length;e.lastIndex=-1}else s=r.match(o.includePrerelease?n[i.COERCEFULL]:n[i.COERCE]);if(null===s)return null;const a=s[2],c=s[3]||"0",l=s[4]||"0",u=o.includePrerelease&&s[5]?`-${s[5]}`:"",d=o.includePrerelease&&s[6]?`+${s[6]}`:"";return t(`${a}.${c}.${l}${u}${d}`,o)},Re}(),O=function(){if(Le)return ze;Le=1;const e=It(),t=gt(),n=At(),i=e=>e.startsWith("pre");return ze=(r,o,s)=>{if(!t.RELEASE_TYPES.includes(o))return null;const a=((t,i)=>{const r=t instanceof n?t.version:t;return e(r,i)})(r,s);return a&&((e,t)=>{if(i(t))return e.version;switch(e.prerelease=[],t){case"major":e.minor=0,e.patch=0;break;case"minor":e.patch=0}return e.format()})(a,o)},ze}(),k=Rt(),C=Nt(),T=Pt(),$=function(){if(qe)return Ze;qe=1;const e=Nt();return Ze=(t,n)=>new e(t,n).set.map(e=>e.map(e=>e.value).join(" ").trim().split(" ")),Ze}(),N=function(){if(We)return Be;We=1;const e=At(),t=Nt();return Be=(n,i,r)=>{let o=null,s=null,a=null;try{a=new t(i,r)}catch(e){return null}return n.forEach(t=>{a.test(t)&&(o&&-1!==s.compare(t)||(o=t,s=new e(o,r)))}),o},Be}(),R=function(){if(Xe)return Je;Xe=1;const e=At(),t=Nt();return Je=(n,i,r)=>{let o=null,s=null,a=null;try{a=new t(i,r)}catch(e){return null}return n.forEach(t=>{a.test(t)&&(o&&1!==s.compare(t)||(o=t,s=new e(o,r)))}),o},Je}(),P=function(){if(Ke)return Ye;Ke=1;const e=At(),t=Nt(),n=wt();return Ye=(i,r)=>{i=new t(i,r);let o=new e("0.0.0");if(i.test(o))return o;if(o=new e("0.0.0-0"),i.test(o))return o;o=null;for(let t=0;t<i.set.length;++t){const r=i.set[t];let s=null;r.forEach(t=>{const i=new e(t.semver.version);switch(t.operator){case">":0===i.prerelease.length?i.patch++:i.prerelease.push(0),i.raw=i.format();case"":case">=":s&&!n(i,s)||(s=i);break;case"<":case"<=":break;default:throw new Error(`Unexpected operation: ${t.operator}`)}}),!s||o&&!n(o,s)||(o=s)}return o&&i.test(o)?o:null},Ye}(),z=zt(),L=Lt(),j=function(){if(rt)return it;rt=1;const e=Lt();return it=(t,n,i)=>e(t,n,">",i),it}(),D=function(){if(st)return ot;st=1;const e=Lt();return ot=(t,n,i)=>e(t,n,"<",i),ot}(),M=function(){if(ct)return at;ct=1;const e=Nt();return at=(t,n,i)=>(t=new e(t,i),n=new e(n,i),t.intersects(n,i))}(),F=function(){if(ut)return lt;ut=1;const e=Pt(),t=xt();return lt=(n,i,r)=>{const o=[];let s=null,a=null;const c=n.sort((e,n)=>t(e,n,r));for(const t of c)e(t,i,r)?(a=t,s||(s=t)):(a&&o.push([s,a]),a=null,s=null);s&&o.push([s,null]);const l=[];for(const[e,t]of o)e===t?l.push(e):t||e!==c[0]?t?e===c[0]?l.push(`<=${t}`):l.push(`${e} - ${t}`):l.push(`>=${e}`):l.push("*");const u=l.join(" || "),d="string"==typeof i.raw?i.raw:String(i);return u.length<d.length?u:i},lt}(),V=function(){if(pt)return dt;pt=1;const e=Nt(),t=Rt(),{ANY:n}=t,i=Pt(),r=xt(),o=[new t(">=0.0.0-0")],s=[new t(">=0.0.0")],a=(e,t,a)=>{if(e===t)return!0;if(1===e.length&&e[0].semver===n){if(1===t.length&&t[0].semver===n)return!0;e=a.includePrerelease?o:s}if(1===t.length&&t[0].semver===n){if(a.includePrerelease)return!0;t=s}const u=new Set;let d,p,m,h,f,g,y;for(const t of e)">"===t.operator||">="===t.operator?d=c(d,t,a):"<"===t.operator||"<="===t.operator?p=l(p,t,a):u.add(t.semver);if(u.size>1)return null;if(d&&p){if(m=r(d.semver,p.semver,a),m>0)return null;if(0===m&&(">="!==d.operator||"<="!==p.operator))return null}for(const e of u){if(d&&!i(e,String(d),a))return null;if(p&&!i(e,String(p),a))return null;for(const n of t)if(!i(e,String(n),a))return!1;return!0}let v=!(!p||a.includePrerelease||!p.semver.prerelease.length)&&p.semver,_=!(!d||a.includePrerelease||!d.semver.prerelease.length)&&d.semver;v&&1===v.prerelease.length&&"<"===p.operator&&0===v.prerelease[0]&&(v=!1);for(const e of t){if(y=y||">"===e.operator||">="===e.operator,g=g||"<"===e.operator||"<="===e.operator,d)if(_&&e.semver.prerelease&&e.semver.prerelease.length&&e.semver.major===_.major&&e.semver.minor===_.minor&&e.semver.patch===_.patch&&(_=!1),">"===e.operator||">="===e.operator){if(h=c(d,e,a),h===e&&h!==d)return!1}else if(">="===d.operator&&!e.test(d.semver))return!1;if(p)if(v&&e.semver.prerelease&&e.semver.prerelease.length&&e.semver.major===v.major&&e.semver.minor===v.minor&&e.semver.patch===v.patch&&(v=!1),"<"===e.operator||"<="===e.operator){if(f=l(p,e,a),f===e&&f!==p)return!1}else if("<="===p.operator&&!e.test(p.semver))return!1;if(!e.operator&&(p||d)&&0!==m)return!1}return!(d&&g&&!p&&0!==m||p&&y&&!d&&0!==m||_||v)},c=(e,t,n)=>{if(!e)return t;const i=r(e.semver,t.semver,n);return i>0?e:i<0||">"===t.operator&&">="===e.operator?t:e},l=(e,t,n)=>{if(!e)return t;const i=r(e.semver,t.semver,n);return i<0?e:i>0||"<"===t.operator&&"<="===e.operator?t:e};return dt=(t,n,i={})=>{if(t===n)return!0;t=new e(t,i),n=new e(n,i);let r=!1;e:for(const e of t.set){for(const t of n.set){const n=a(e,t,i);if(r=r||null!==n,n)continue e}if(r)return!1}return!0}}();return mt={parse:r,valid:o,clean:s,inc:a,diff:c,major:l,minor:u,patch:d,prerelease:p,compare:m,rcompare:h,compareLoose:f,compareBuild:g,sort:y,rsort:v,gt:_,lt:b,eq:A,neq:I,gte:x,lte:S,cmp:w,coerce:E,truncate:O,Comparator:k,Range:C,satisfies:T,toComparators:$,maxSatisfying:N,minSatisfying:R,minVersion:P,validRange:z,outside:L,gtr:j,ltr:D,intersects:M,simplifyRange:F,subset:V,SemVer:n,re:e.re,src:e.src,tokens:e.t,SEMVER_SPEC_VERSION:t.SEMVER_SPEC_VERSION,RELEASE_TYPES:t.RELEASE_TYPES,compareIdentifiers:i.compareIdentifiers,rcompareIdentifiers:i.rcompareIdentifiers}}var Dt,Mt,Ft,Vt,Ut={exports:{}},Ht={},Gt={};function Zt(){return Dt||(Dt=1,e=Gt,Object.defineProperty(e,"__esModule",{value:!0}),e.signals=void 0,e.signals=[],e.signals.push("SIGHUP","SIGINT","SIGTERM"),"win32"!==process.platform&&e.signals.push("SIGALRM","SIGABRT","SIGVTALRM","SIGXCPU","SIGXFSZ","SIGUSR2","SIGTRAP","SIGSYS","SIGQUIT","SIGIOT"),"linux"===process.platform&&e.signals.push("SIGIO","SIGPOLL","SIGPWR","SIGSTKFLT")),Gt;var e}const qt=Object.freeze({status:"aborted"});function Bt(e,t,n){function i(n,i){if(n._zod||Object.defineProperty(n,"_zod",{value:{def:i,constr:s,traits:new Set},enumerable:!1}),n._zod.traits.has(e))return;n._zod.traits.add(e),t(n,i);const r=s.prototype,o=Object.keys(r);for(let e=0;e<o.length;e++){const t=o[e];t in n||(n[t]=r[t].bind(n))}}const r=n?.Parent??Object;class o extends r{}function s(e){var t;const r=n?.Parent?new o:this;i(r,e),(t=r._zod).deferred??(t.deferred=[]);for(const e of r._zod.deferred)e();return r}return Object.defineProperty(o,"name",{value:e}),Object.defineProperty(s,"init",{value:i}),Object.defineProperty(s,Symbol.hasInstance,{value:t=>!!(n?.Parent&&t instanceof n.Parent)||t?._zod?.traits?.has(e)}),Object.defineProperty(s,"name",{value:e}),s}class Wt extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class Jt extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`),this.name="ZodEncodeError"}}(Vt=globalThis).__zod_globalConfig??(Vt.__zod_globalConfig={});const Xt=globalThis.__zod_globalConfig;function Yt(e){return Xt}function Kt(e){const t=Object.values(e).filter(e=>"number"==typeof e);return Object.entries(e).filter(([e,n])=>-1===t.indexOf(+e)).map(([e,t])=>t)}function Qt(e,t){return"bigint"==typeof t?t.toString():t}function en(e){return{get value(){{const t=e();return Object.defineProperty(this,"value",{value:t}),t}}}}function tn(e){return null==e}function nn(e){const t=e.startsWith("^")?1:0,n=e.endsWith("$")?e.length-1:e.length;return e.slice(t,n)}const rn=Symbol("evaluating");function on(e,t,n){let i;Object.defineProperty(e,t,{get(){if(i!==rn)return void 0===i&&(i=rn,i=n()),i},set(n){Object.defineProperty(e,t,{value:n})},configurable:!0})}function sn(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}function an(...e){const t={};for(const n of e){const e=Object.getOwnPropertyDescriptors(n);Object.assign(t,e)}return Object.defineProperties({},t)}function cn(e){return JSON.stringify(e)}const ln="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function un(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}const dn=en(()=>{if(Xt.jitless)return!1;if("undefined"!=typeof navigator&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return new Function(""),!0}catch(e){return!1}});function pn(e){if(!1===un(e))return!1;const t=e.constructor;if(void 0===t)return!0;if("function"!=typeof t)return!0;const n=t.prototype;return!1!==un(n)&&!1!==Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")}function mn(e){return pn(e)?{...e}:Array.isArray(e)?[...e]:e instanceof Map?new Map(e):e instanceof Set?new Set(e):e}const hn=new Set(["string","number","symbol"]);function fn(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function gn(e,t,n){const i=new e._zod.constr(t??e._zod.def);return t&&!n?.parent||(i._zod.parent=e),i}function yn(e){const t=e;if(!t)return{};if("string"==typeof t)return{error:()=>t};if(void 0!==t?.message){if(void 0!==t?.error)throw new Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,"string"==typeof t.error?{...t,error:()=>t.error}:t}const vn={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]};function _n(e,t=0){if(!0===e.aborted)return!0;for(let n=t;n<e.issues.length;n++)if(!0!==e.issues[n]?.continue)return!0;return!1}function bn(e,t=0){if(!0===e.aborted)return!0;for(let n=t;n<e.issues.length;n++)if(!1===e.issues[n]?.continue)return!0;return!1}function An(e,t){return t.map(t=>{var n;return(n=t).path??(n.path=[]),t.path.unshift(e),t})}function In(e){return"string"==typeof e?e:e?.message}function xn(e,t,n){const i=e.message?e.message:In(e.inst?._zod.def?.error?.(e))??In(t?.error?.(e))??In(n.customError?.(e))??In(n.localeError?.(e))??"Invalid input",{inst:r,continue:o,input:s,...a}=e;return a.path??(a.path=[]),a.message=i,t?.reportInput&&(a.input=s),a}function Sn(e){return Array.isArray(e)?"array":"string"==typeof e?"string":"unknown"}function wn(...e){const[t,n,i]=e;return"string"==typeof t?{message:t,code:"custom",input:n,inst:i}:{...t}}const En=(e,t)=>{e.name="$ZodError",Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),e.message=JSON.stringify(t,Qt,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},On=Bt("$ZodError",En),kn=Bt("$ZodError",En,{Parent:Error}),Cn=e=>(t,n,i,r)=>{const o=i?{...i,async:!1}:{async:!1},s=t._zod.run({value:n,issues:[]},o);if(s instanceof Promise)throw new Wt;if(s.issues.length){const t=new(r?.Err??e)(s.issues.map(e=>xn(e,o,Yt())));throw ln(t,r?.callee),t}return s.value},Tn=e=>async(t,n,i,r)=>{const o=i?{...i,async:!0}:{async:!0};let s=t._zod.run({value:n,issues:[]},o);if(s instanceof Promise&&(s=await s),s.issues.length){const t=new(r?.Err??e)(s.issues.map(e=>xn(e,o,Yt())));throw ln(t,r?.callee),t}return s.value},$n=e=>(t,n,i)=>{const r=i?{...i,async:!1}:{async:!1},o=t._zod.run({value:n,issues:[]},r);if(o instanceof Promise)throw new Wt;return o.issues.length?{success:!1,error:new(e??On)(o.issues.map(e=>xn(e,r,Yt())))}:{success:!0,data:o.value}},Nn=$n(kn),Rn=e=>async(t,n,i)=>{const r=i?{...i,async:!0}:{async:!0};let o=t._zod.run({value:n,issues:[]},r);return o instanceof Promise&&(o=await o),o.issues.length?{success:!1,error:new e(o.issues.map(e=>xn(e,r,Yt())))}:{success:!0,data:o.value}},Pn=Rn(kn),zn=e=>(t,n,i)=>{const r=i?{...i,direction:"backward"}:{direction:"backward"};return Cn(e)(t,n,r)},Ln=e=>(t,n,i)=>Cn(e)(t,n,i),jn=e=>async(t,n,i)=>{const r=i?{...i,direction:"backward"}:{direction:"backward"};return Tn(e)(t,n,r)},Dn=e=>async(t,n,i)=>Tn(e)(t,n,i),Mn=e=>(t,n,i)=>{const r=i?{...i,direction:"backward"}:{direction:"backward"};return $n(e)(t,n,r)},Fn=e=>(t,n,i)=>$n(e)(t,n,i),Vn=e=>async(t,n,i)=>{const r=i?{...i,direction:"backward"}:{direction:"backward"};return Rn(e)(t,n,r)},Un=e=>async(t,n,i)=>Rn(e)(t,n,i),Hn=/^[cC][0-9a-z]{6,}$/,Gn=/^[0-9a-z]+$/,Zn=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,qn=/^[0-9a-vA-V]{20}$/,Bn=/^[A-Za-z0-9]{27}$/,Wn=/^[a-zA-Z0-9_-]{21}$/,Jn=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,Xn=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,Yn=e=>e?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/,Kn=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,Qn=/^(?:(?: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])$/,ei=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/,ti=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,ni=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,ii=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,ri=/^[A-Za-z0-9_-]*$/,oi=/^https?$/,si=/^\+[1-9]\d{6,14}$/,ai="(?:(?:\\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])))",ci=new RegExp(`^${ai}$`);function li(e){const t="(?:[01]\\d|2[0-3]):[0-5]\\d";return"number"==typeof e.precision?-1===e.precision?`${t}`:0===e.precision?`${t}:[0-5]\\d`:`${t}:[0-5]\\d\\.\\d{${e.precision}}`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}const ui=/^-?\d+$/,di=/^-?\d+(?:\.\d+)?$/,pi=/^(?:true|false)$/i,mi=/^[^A-Z]*$/,hi=/^[^a-z]*$/,fi=Bt("$ZodCheck",(e,t)=>{var n;e._zod??(e._zod={}),e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),gi={number:"number",bigint:"bigint",object:"date"},yi=Bt("$ZodCheckLessThan",(e,t)=>{fi.init(e,t);const n=gi[typeof t.value];e._zod.onattach.push(e=>{const n=e._zod.bag,i=(t.inclusive?n.maximum:n.exclusiveMaximum)??Number.POSITIVE_INFINITY;t.value<i&&(t.inclusive?n.maximum=t.value:n.exclusiveMaximum=t.value)}),e._zod.check=i=>{(t.inclusive?i.value<=t.value:i.value<t.value)||i.issues.push({origin:n,code:"too_big",maximum:"object"==typeof t.value?t.value.getTime():t.value,input:i.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),vi=Bt("$ZodCheckGreaterThan",(e,t)=>{fi.init(e,t);const n=gi[typeof t.value];e._zod.onattach.push(e=>{const n=e._zod.bag,i=(t.inclusive?n.minimum:n.exclusiveMinimum)??Number.NEGATIVE_INFINITY;t.value>i&&(t.inclusive?n.minimum=t.value:n.exclusiveMinimum=t.value)}),e._zod.check=i=>{(t.inclusive?i.value>=t.value:i.value>t.value)||i.issues.push({origin:n,code:"too_small",minimum:"object"==typeof t.value?t.value.getTime():t.value,input:i.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),_i=Bt("$ZodCheckMultipleOf",(e,t)=>{fi.init(e,t),e._zod.onattach.push(e=>{var n;(n=e._zod.bag).multipleOf??(n.multipleOf=t.value)}),e._zod.check=n=>{if(typeof n.value!=typeof t.value)throw new Error("Cannot mix number and bigint in multiple_of check.");("bigint"==typeof n.value?n.value%t.value===BigInt(0):0===function(e,t){const n=e/t,i=Math.round(n),r=Number.EPSILON*Math.max(Math.abs(n),1);return Math.abs(n-i)<r?0:n-i}(n.value,t.value))||n.issues.push({origin:typeof n.value,code:"not_multiple_of",divisor:t.value,input:n.value,inst:e,continue:!t.abort})}}),bi=Bt("$ZodCheckNumberFormat",(e,t)=>{fi.init(e,t),t.format=t.format||"float64";const n=t.format?.includes("int"),i=n?"int":"number",[r,o]=vn[t.format];e._zod.onattach.push(e=>{const i=e._zod.bag;i.format=t.format,i.minimum=r,i.maximum=o,n&&(i.pattern=ui)}),e._zod.check=s=>{const a=s.value;if(n){if(!Number.isInteger(a))return void s.issues.push({expected:i,format:t.format,code:"invalid_type",continue:!1,input:a,inst:e});if(!Number.isSafeInteger(a))return void(a>0?s.issues.push({input:a,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:i,inclusive:!0,continue:!t.abort}):s.issues.push({input:a,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:i,inclusive:!0,continue:!t.abort}))}a<r&&s.issues.push({origin:"number",input:a,code:"too_small",minimum:r,inclusive:!0,inst:e,continue:!t.abort}),a>o&&s.issues.push({origin:"number",input:a,code:"too_big",maximum:o,inclusive:!0,inst:e,continue:!t.abort})}}),Ai=Bt("$ZodCheckMaxLength",(e,t)=>{var n;fi.init(e,t),(n=e._zod.def).when??(n.when=e=>{const t=e.value;return!tn(t)&&void 0!==t.length}),e._zod.onattach.push(e=>{const n=e._zod.bag.maximum??Number.POSITIVE_INFINITY;t.maximum<n&&(e._zod.bag.maximum=t.maximum)}),e._zod.check=n=>{const i=n.value;if(i.length<=t.maximum)return;const r=Sn(i);n.issues.push({origin:r,code:"too_big",maximum:t.maximum,inclusive:!0,input:i,inst:e,continue:!t.abort})}}),Ii=Bt("$ZodCheckMinLength",(e,t)=>{var n;fi.init(e,t),(n=e._zod.def).when??(n.when=e=>{const t=e.value;return!tn(t)&&void 0!==t.length}),e._zod.onattach.push(e=>{const n=e._zod.bag.minimum??Number.NEGATIVE_INFINITY;t.minimum>n&&(e._zod.bag.minimum=t.minimum)}),e._zod.check=n=>{const i=n.value;if(i.length>=t.minimum)return;const r=Sn(i);n.issues.push({origin:r,code:"too_small",minimum:t.minimum,inclusive:!0,input:i,inst:e,continue:!t.abort})}}),xi=Bt("$ZodCheckLengthEquals",(e,t)=>{var n;fi.init(e,t),(n=e._zod.def).when??(n.when=e=>{const t=e.value;return!tn(t)&&void 0!==t.length}),e._zod.onattach.push(e=>{const n=e._zod.bag;n.minimum=t.length,n.maximum=t.length,n.length=t.length}),e._zod.check=n=>{const i=n.value,r=i.length;if(r===t.length)return;const o=Sn(i),s=r>t.length;n.issues.push({origin:o,...s?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:n.value,inst:e,continue:!t.abort})}}),Si=Bt("$ZodCheckStringFormat",(e,t)=>{var n,i;fi.init(e,t),e._zod.onattach.push(e=>{const n=e._zod.bag;n.format=t.format,t.pattern&&(n.patterns??(n.patterns=new Set),n.patterns.add(t.pattern))}),t.pattern?(n=e._zod).check??(n.check=n=>{t.pattern.lastIndex=0,t.pattern.test(n.value)||n.issues.push({origin:"string",code:"invalid_format",format:t.format,input:n.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(i=e._zod).check??(i.check=()=>{})}),wi=Bt("$ZodCheckRegex",(e,t)=>{Si.init(e,t),e._zod.check=n=>{t.pattern.lastIndex=0,t.pattern.test(n.value)||n.issues.push({origin:"string",code:"invalid_format",format:"regex",input:n.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),Ei=Bt("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=mi),Si.init(e,t)}),Oi=Bt("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=hi),Si.init(e,t)}),ki=Bt("$ZodCheckIncludes",(e,t)=>{fi.init(e,t);const n=fn(t.includes),i=new RegExp("number"==typeof t.position?`^.{${t.position}}${n}`:n);t.pattern=i,e._zod.onattach.push(e=>{const t=e._zod.bag;t.patterns??(t.patterns=new Set),t.patterns.add(i)}),e._zod.check=n=>{n.value.includes(t.includes,t.position)||n.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:n.value,inst:e,continue:!t.abort})}}),Ci=Bt("$ZodCheckStartsWith",(e,t)=>{fi.init(e,t);const n=new RegExp(`^${fn(t.prefix)}.*`);t.pattern??(t.pattern=n),e._zod.onattach.push(e=>{const t=e._zod.bag;t.patterns??(t.patterns=new Set),t.patterns.add(n)}),e._zod.check=n=>{n.value.startsWith(t.prefix)||n.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:t.prefix,input:n.value,inst:e,continue:!t.abort})}}),Ti=Bt("$ZodCheckEndsWith",(e,t)=>{fi.init(e,t);const n=new RegExp(`.*${fn(t.suffix)}$`);t.pattern??(t.pattern=n),e._zod.onattach.push(e=>{const t=e._zod.bag;t.patterns??(t.patterns=new Set),t.patterns.add(n)}),e._zod.check=n=>{n.value.endsWith(t.suffix)||n.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:t.suffix,input:n.value,inst:e,continue:!t.abort})}}),$i=Bt("$ZodCheckOverwrite",(e,t)=>{fi.init(e,t),e._zod.check=e=>{e.value=t.tx(e.value)}});class Ni{constructor(e=[]){this.content=[],this.indent=0,this&&(this.args=e)}indented(e){this.indent+=1,e(this),this.indent-=1}write(e){if("function"==typeof e)return e(this,{execution:"sync"}),void e(this,{execution:"async"});const t=e.split("\n").filter(e=>e),n=Math.min(...t.map(e=>e.length-e.trimStart().length)),i=t.map(e=>e.slice(n)).map(e=>" ".repeat(2*this.indent)+e);for(const e of i)this.content.push(e)}compile(){const e=Function,t=this?.args;return new e(...t,[...(this?.content??[""]).map(e=>` ${e}`)].join("\n"))}}const Ri={major:4,minor:4,patch:3},Pi=Bt("$ZodType",(e,t)=>{var n;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=Ri;const i=[...e._zod.def.checks??[]];e._zod.traits.has("$ZodCheck")&&i.unshift(e);for(const t of i)for(const n of t._zod.onattach)n(e);if(0===i.length)(n=e._zod).deferred??(n.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{const t=(e,t,n)=>{let i,r=_n(e);for(const o of t){if(o._zod.def.when){if(bn(e))continue;if(!o._zod.def.when(e))continue}else if(r)continue;const t=e.issues.length,s=o._zod.check(e);if(s instanceof Promise&&!1===n?.async)throw new Wt;if(i||s instanceof Promise)i=(i??Promise.resolve()).then(async()=>{await s,e.issues.length!==t&&(r||(r=_n(e,t)))});else{if(e.issues.length===t)continue;r||(r=_n(e,t))}}return i?i.then(()=>e):e},n=(n,r,o)=>{if(_n(n))return n.aborted=!0,n;const s=t(r,i,o);if(s instanceof Promise){if(!1===o.async)throw new Wt;return s.then(t=>e._zod.parse(t,o))}return e._zod.parse(s,o)};e._zod.run=(r,o)=>{if(o.skipChecks)return e._zod.parse(r,o);if("backward"===o.direction){const t=e._zod.parse({value:r.value,issues:[]},{...o,skipChecks:!0});return t instanceof Promise?t.then(e=>n(e,r,o)):n(t,r,o)}const s=e._zod.parse(r,o);if(s instanceof Promise){if(!1===o.async)throw new Wt;return s.then(e=>t(e,i,o))}return t(s,i,o)}}on(e,"~standard",()=>({validate:t=>{try{const n=Nn(e,t);return n.success?{value:n.data}:{issues:n.error?.issues}}catch(n){return Pn(e,t).then(e=>e.success?{value:e.data}:{issues:e.error?.issues})}},vendor:"zod",version:1}))}),zi=Bt("$ZodString",(e,t)=>{var n;Pi.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??(n=e._zod.bag,new RegExp(`^${n?`[\\s\\S]{${n?.minimum??0},${n?.maximum??""}}`:"[\\s\\S]*"}$`)),e._zod.parse=(n,i)=>{if(t.coerce)try{n.value=String(n.value)}catch(i){}return"string"==typeof n.value||n.issues.push({expected:"string",code:"invalid_type",input:n.value,inst:e}),n}}),Li=Bt("$ZodStringFormat",(e,t)=>{Si.init(e,t),zi.init(e,t)}),ji=Bt("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=Xn),Li.init(e,t)}),Di=Bt("$ZodUUID",(e,t)=>{if(t.version){const e={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(void 0===e)throw new Error(`Invalid UUID version: "${t.version}"`);t.pattern??(t.pattern=Yn(e))}else t.pattern??(t.pattern=Yn());Li.init(e,t)}),Mi=Bt("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=Kn),Li.init(e,t)}),Fi=Bt("$ZodURL",(e,t)=>{Li.init(e,t),e._zod.check=n=>{try{const i=n.value.trim();if(!t.normalize&&t.protocol?.source===oi.source&&!/^https?:\/\//i.test(i))return void n.issues.push({code:"invalid_format",format:"url",note:"Invalid URL format",input:n.value,inst:e,continue:!t.abort});const r=new URL(i);return t.hostname&&(t.hostname.lastIndex=0,t.hostname.test(r.hostname)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:t.hostname.source,input:n.value,inst:e,continue:!t.abort})),t.protocol&&(t.protocol.lastIndex=0,t.protocol.test(r.protocol.endsWith(":")?r.protocol.slice(0,-1):r.protocol)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:t.protocol.source,input:n.value,inst:e,continue:!t.abort})),void(t.normalize?n.value=r.href:n.value=i)}catch(i){n.issues.push({code:"invalid_format",format:"url",input:n.value,inst:e,continue:!t.abort})}}}),Vi=Bt("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=new RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),Li.init(e,t)}),Ui=Bt("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=Wn),Li.init(e,t)}),Hi=Bt("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=Hn),Li.init(e,t)}),Gi=Bt("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=Gn),Li.init(e,t)}),Zi=Bt("$ZodULID",(e,t)=>{t.pattern??(t.pattern=Zn),Li.init(e,t)}),qi=Bt("$ZodXID",(e,t)=>{t.pattern??(t.pattern=qn),Li.init(e,t)}),Bi=Bt("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=Bn),Li.init(e,t)}),Wi=Bt("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=function(e){const t=li({precision:e.precision}),n=["Z"];e.local&&n.push(""),e.offset&&n.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");const i=`${t}(?:${n.join("|")})`;return new RegExp(`^${ai}T(?:${i})$`)}(t)),Li.init(e,t)}),Ji=Bt("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=ci),Li.init(e,t)}),Xi=Bt("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=new RegExp(`^${li(t)}$`)),Li.init(e,t)}),Yi=Bt("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=Jn),Li.init(e,t)}),Ki=Bt("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=Qn),Li.init(e,t),e._zod.bag.format="ipv4"}),Qi=Bt("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=ei),Li.init(e,t),e._zod.bag.format="ipv6",e._zod.check=n=>{try{new URL(`http://[${n.value}]`)}catch{n.issues.push({code:"invalid_format",format:"ipv6",input:n.value,inst:e,continue:!t.abort})}}}),er=Bt("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=ti),Li.init(e,t)}),tr=Bt("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=ni),Li.init(e,t),e._zod.check=n=>{const i=n.value.split("/");try{if(2!==i.length)throw new Error;const[e,t]=i;if(!t)throw new Error;const n=Number(t);if(`${n}`!==t)throw new Error;if(n<0||n>128)throw new Error;new URL(`http://[${e}]`)}catch{n.issues.push({code:"invalid_format",format:"cidrv6",input:n.value,inst:e,continue:!t.abort})}}});function nr(e){if(""===e)return!0;if(/\s/.test(e))return!1;if(e.length%4!=0)return!1;try{return atob(e),!0}catch{return!1}}const ir=Bt("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=ii),Li.init(e,t),e._zod.bag.contentEncoding="base64",e._zod.check=n=>{nr(n.value)||n.issues.push({code:"invalid_format",format:"base64",input:n.value,inst:e,continue:!t.abort})}}),rr=Bt("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=ri),Li.init(e,t),e._zod.bag.contentEncoding="base64url",e._zod.check=n=>{(function(e){if(!ri.test(e))return!1;const t=e.replace(/[-_]/g,e=>"-"===e?"+":"/");return nr(t.padEnd(4*Math.ceil(t.length/4),"="))})(n.value)||n.issues.push({code:"invalid_format",format:"base64url",input:n.value,inst:e,continue:!t.abort})}}),or=Bt("$ZodE164",(e,t)=>{t.pattern??(t.pattern=si),Li.init(e,t)}),sr=Bt("$ZodJWT",(e,t)=>{Li.init(e,t),e._zod.check=n=>{(function(e,t=null){try{const n=e.split(".");if(3!==n.length)return!1;const[i]=n;if(!i)return!1;const r=JSON.parse(atob(i));return!("typ"in r&&"JWT"!==r?.typ||!r.alg||t&&(!("alg"in r)||r.alg!==t))}catch{return!1}})(n.value,t.alg)||n.issues.push({code:"invalid_format",format:"jwt",input:n.value,inst:e,continue:!t.abort})}}),ar=Bt("$ZodNumber",(e,t)=>{Pi.init(e,t),e._zod.pattern=e._zod.bag.pattern??di,e._zod.parse=(n,i)=>{if(t.coerce)try{n.value=Number(n.value)}catch(e){}const r=n.value;if("number"==typeof r&&!Number.isNaN(r)&&Number.isFinite(r))return n;const o="number"==typeof r?Number.isNaN(r)?"NaN":Number.isFinite(r)?void 0:"Infinity":void 0;return n.issues.push({expected:"number",code:"invalid_type",input:r,inst:e,...o?{received:o}:{}}),n}}),cr=Bt("$ZodNumberFormat",(e,t)=>{bi.init(e,t),ar.init(e,t)}),lr=Bt("$ZodBoolean",(e,t)=>{Pi.init(e,t),e._zod.pattern=pi,e._zod.parse=(n,i)=>{if(t.coerce)try{n.value=Boolean(n.value)}catch(e){}const r=n.value;return"boolean"==typeof r||n.issues.push({expected:"boolean",code:"invalid_type",input:r,inst:e}),n}}),ur=Bt("$ZodUnknown",(e,t)=>{Pi.init(e,t),e._zod.parse=e=>e}),dr=Bt("$ZodNever",(e,t)=>{Pi.init(e,t),e._zod.parse=(t,n)=>(t.issues.push({expected:"never",code:"invalid_type",input:t.value,inst:e}),t)});function pr(e,t,n){e.issues.length&&t.issues.push(...An(n,e.issues)),t.value[n]=e.value}const mr=Bt("$ZodArray",(e,t)=>{Pi.init(e,t),e._zod.parse=(n,i)=>{const r=n.value;if(!Array.isArray(r))return n.issues.push({expected:"array",code:"invalid_type",input:r,inst:e}),n;n.value=Array(r.length);const o=[];for(let e=0;e<r.length;e++){const s=r[e],a=t.element._zod.run({value:s,issues:[]},i);a instanceof Promise?o.push(a.then(t=>pr(t,n,e))):pr(a,n,e)}return o.length?Promise.all(o).then(()=>n):n}});function hr(e,t,n,i,r,o){const s=n in i;if(e.issues.length){if(r&&o&&!s)return;t.issues.push(...An(n,e.issues))}s||r?void 0===e.value?s&&(t.value[n]=void 0):t.value[n]=e.value:e.issues.length||t.issues.push({code:"invalid_type",expected:"nonoptional",input:void 0,path:[n]})}function fr(e){const t=Object.keys(e.shape);for(const n of t)if(!e.shape?.[n]?._zod?.traits?.has("$ZodType"))throw new Error(`Invalid element at key "${n}": expected a Zod schema`);const n=(i=e.shape,Object.keys(i).filter(e=>"optional"===i[e]._zod.optin&&"optional"===i[e]._zod.optout));var i;return{...e,keys:t,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(n)}}function gr(e,t,n,i,r,o){const s=[],a=r.keySet,c=r.catchall._zod,l=c.def.type,u="optional"===c.optin,d="optional"===c.optout;for(const r in t){if("__proto__"===r)continue;if(a.has(r))continue;if("never"===l){s.push(r);continue}const o=c.run({value:t[r],issues:[]},i);o instanceof Promise?e.push(o.then(e=>hr(e,n,r,t,u,d))):hr(o,n,r,t,u,d)}return s.length&&n.issues.push({code:"unrecognized_keys",keys:s,input:t,inst:o}),e.length?Promise.all(e).then(()=>n):n}const yr=Bt("$ZodObject",(e,t)=>{Pi.init(e,t);const n=Object.getOwnPropertyDescriptor(t,"shape");if(!n?.get){const e=t.shape;Object.defineProperty(t,"shape",{get:()=>{const n={...e};return Object.defineProperty(t,"shape",{value:n}),n}})}const i=en(()=>fr(t));on(e._zod,"propValues",()=>{const e=t.shape,n={};for(const t in e){const i=e[t]._zod;if(i.values){n[t]??(n[t]=new Set);for(const e of i.values)n[t].add(e)}}return n});const r=un,o=t.catchall;let s;e._zod.parse=(t,n)=>{s??(s=i.value);const a=t.value;if(!r(a))return t.issues.push({expected:"object",code:"invalid_type",input:a,inst:e}),t;t.value={};const c=[],l=s.shape;for(const e of s.keys){const i=l[e],r="optional"===i._zod.optin,o="optional"===i._zod.optout,s=i._zod.run({value:a[e],issues:[]},n);s instanceof Promise?c.push(s.then(n=>hr(n,t,e,a,r,o))):hr(s,t,e,a,r,o)}return o?gr(c,a,t,n,i.value,e):c.length?Promise.all(c).then(()=>t):t}}),vr=Bt("$ZodObjectJIT",(e,t)=>{yr.init(e,t);const n=e._zod.parse,i=en(()=>fr(t));let r;const o=un,s=!Xt.jitless,a=s&&dn.value,c=t.catchall;let l;e._zod.parse=(u,d)=>{l??(l=i.value);const p=u.value;return o(p)?s&&a&&!1===d?.async&&!0!==d.jitless?(r||(r=(e=>{const t=new Ni(["shape","payload","ctx"]),n=i.value,r=e=>{const t=cn(e);return`shape[${t}]._zod.run({ value: input[${t}], issues: [] }, ctx)`};t.write("const input = payload.value;");const o=Object.create(null);let s=0;for(const e of n.keys)o[e]="key_"+s++;t.write("const newResult = {};");for(const i of n.keys){const n=o[i],s=cn(i),a=e[i],c="optional"===a?._zod?.optin,l="optional"===a?._zod?.optout;t.write(`const ${n} = ${r(i)};`),c&&l?t.write(`\n if (${n}.issues.length) {\n if (${s} in input) {\n payload.issues = payload.issues.concat(${n}.issues.map(iss => ({\n ...iss,\n path: iss.path ? [${s}, ...iss.path] : [${s}]\n })));\n }\n }\n \n if (${n}.value === undefined) {\n if (${s} in input) {\n newResult[${s}] = undefined;\n }\n } else {\n newResult[${s}] = ${n}.value;\n }\n \n `):c?t.write(`\n if (${n}.issues.length) {\n payload.issues = payload.issues.concat(${n}.issues.map(iss => ({\n ...iss,\n path: iss.path ? [${s}, ...iss.path] : [${s}]\n })));\n }\n \n if (${n}.value === undefined) {\n if (${s} in input) {\n newResult[${s}] = undefined;\n }\n } else {\n newResult[${s}] = ${n}.value;\n }\n \n `):t.write(`\n const ${n}_present = ${s} in input;\n if (${n}.issues.length) {\n payload.issues = payload.issues.concat(${n}.issues.map(iss => ({\n ...iss,\n path: iss.path ? [${s}, ...iss.path] : [${s}]\n })));\n }\n if (!${n}_present && !${n}.issues.length) {\n payload.issues.push({\n code: "invalid_type",\n expected: "nonoptional",\n input: undefined,\n path: [${s}]\n });\n }\n\n if (${n}_present) {\n if (${n}.value === undefined) {\n newResult[${s}] = undefined;\n } else {\n newResult[${s}] = ${n}.value;\n }\n }\n\n `)}t.write("payload.value = newResult;"),t.write("return payload;");const a=t.compile();return(t,n)=>a(e,t,n)})(t.shape)),u=r(u,d),c?gr([],p,u,d,l,e):u):n(u,d):(u.issues.push({expected:"object",code:"invalid_type",input:p,inst:e}),u)}});function _r(e,t,n,i){for(const n of e)if(0===n.issues.length)return t.value=n.value,t;const r=e.filter(e=>!_n(e));return 1===r.length?(t.value=r[0].value,r[0]):(t.issues.push({code:"invalid_union",input:t.value,inst:n,errors:e.map(e=>e.issues.map(e=>xn(e,i,Yt())))}),t)}const br=Bt("$ZodUnion",(e,t)=>{Pi.init(e,t),on(e._zod,"optin",()=>t.options.some(e=>"optional"===e._zod.optin)?"optional":void 0),on(e._zod,"optout",()=>t.options.some(e=>"optional"===e._zod.optout)?"optional":void 0),on(e._zod,"values",()=>{if(t.options.every(e=>e._zod.values))return new Set(t.options.flatMap(e=>Array.from(e._zod.values)))}),on(e._zod,"pattern",()=>{if(t.options.every(e=>e._zod.pattern)){const e=t.options.map(e=>e._zod.pattern);return new RegExp(`^(${e.map(e=>nn(e.source)).join("|")})$`)}});const n=1===t.options.length?t.options[0]._zod.run:null;e._zod.parse=(i,r)=>{if(n)return n(i,r);let o=!1;const s=[];for(const e of t.options){const t=e._zod.run({value:i.value,issues:[]},r);if(t instanceof Promise)s.push(t),o=!0;else{if(0===t.issues.length)return t;s.push(t)}}return o?Promise.all(s).then(t=>_r(t,i,e,r)):_r(s,i,e,r)}}),Ar=Bt("$ZodDiscriminatedUnion",(e,t)=>{t.inclusive=!1,br.init(e,t);const n=e._zod.parse;on(e._zod,"propValues",()=>{const e={};for(const n of t.options){const i=n._zod.propValues;if(!i||0===Object.keys(i).length)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(n)}"`);for(const[t,n]of Object.entries(i)){e[t]||(e[t]=new Set);for(const i of n)e[t].add(i)}}return e});const i=en(()=>{const e=t.options,n=new Map;for(const i of e){const e=i._zod.propValues?.[t.discriminator];if(!e||0===e.size)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(i)}"`);for(const t of e){if(n.has(t))throw new Error(`Duplicate discriminator value "${String(t)}"`);n.set(t,i)}}return n});e._zod.parse=(r,o)=>{const s=r.value;if(!un(s))return r.issues.push({code:"invalid_type",expected:"object",input:s,inst:e}),r;const a=i.value.get(s?.[t.discriminator]);return a?a._zod.run(r,o):t.unionFallback||"backward"===o.direction?n(r,o):(r.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:t.discriminator,options:Array.from(i.value.keys()),input:s,path:[t.discriminator],inst:e}),r)}}),Ir=Bt("$ZodIntersection",(e,t)=>{Pi.init(e,t),e._zod.parse=(e,n)=>{const i=e.value,r=t.left._zod.run({value:i,issues:[]},n),o=t.right._zod.run({value:i,issues:[]},n);return r instanceof Promise||o instanceof Promise?Promise.all([r,o]).then(([t,n])=>Sr(e,t,n)):Sr(e,r,o)}});function xr(e,t){if(e===t)return{valid:!0,data:e};if(e instanceof Date&&t instanceof Date&&+e===+t)return{valid:!0,data:e};if(pn(e)&&pn(t)){const n=Object.keys(t),i=Object.keys(e).filter(e=>-1!==n.indexOf(e)),r={...e,...t};for(const n of i){const i=xr(e[n],t[n]);if(!i.valid)return{valid:!1,mergeErrorPath:[n,...i.mergeErrorPath]};r[n]=i.data}return{valid:!0,data:r}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};const n=[];for(let i=0;i<e.length;i++){const r=xr(e[i],t[i]);if(!r.valid)return{valid:!1,mergeErrorPath:[i,...r.mergeErrorPath]};n.push(r.data)}return{valid:!0,data:n}}return{valid:!1,mergeErrorPath:[]}}function Sr(e,t,n){const i=new Map;let r;for(const n of t.issues)if("unrecognized_keys"===n.code){r??(r=n);for(const e of n.keys)i.has(e)||i.set(e,{}),i.get(e).l=!0}else e.issues.push(n);for(const t of n.issues)if("unrecognized_keys"===t.code)for(const e of t.keys)i.has(e)||i.set(e,{}),i.get(e).r=!0;else e.issues.push(t);const o=[...i].filter(([,e])=>e.l&&e.r).map(([e])=>e);if(o.length&&r&&e.issues.push({...r,keys:o}),_n(e))return e;const s=xr(t.value,n.value);if(!s.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(s.mergeErrorPath)}`);return e.value=s.data,e}const wr=Bt("$ZodRecord",(e,t)=>{Pi.init(e,t),e._zod.parse=(n,i)=>{const r=n.value;if(!pn(r))return n.issues.push({expected:"record",code:"invalid_type",input:r,inst:e}),n;const o=[],s=t.keyType._zod.values;if(s){n.value={};const a=new Set;for(const c of s)if("string"==typeof c||"number"==typeof c||"symbol"==typeof c){a.add("number"==typeof c?c.toString():c);const s=t.keyType._zod.run({value:c,issues:[]},i);if(s instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(s.issues.length){n.issues.push({code:"invalid_key",origin:"record",issues:s.issues.map(e=>xn(e,i,Yt())),input:c,path:[c],inst:e});continue}const l=s.value,u=t.valueType._zod.run({value:r[c],issues:[]},i);u instanceof Promise?o.push(u.then(e=>{e.issues.length&&n.issues.push(...An(c,e.issues)),n.value[l]=e.value})):(u.issues.length&&n.issues.push(...An(c,u.issues)),n.value[l]=u.value)}let c;for(const e in r)a.has(e)||(c=c??[],c.push(e));c&&c.length>0&&n.issues.push({code:"unrecognized_keys",input:r,inst:e,keys:c})}else{n.value={};for(const s of Reflect.ownKeys(r)){if("__proto__"===s)continue;if(!Object.prototype.propertyIsEnumerable.call(r,s))continue;let a=t.keyType._zod.run({value:s,issues:[]},i);if(a instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if("string"==typeof s&&di.test(s)&&a.issues.length){const e=t.keyType._zod.run({value:Number(s),issues:[]},i);if(e instanceof Promise)throw new Error("Async schemas not supported in object keys currently");0===e.issues.length&&(a=e)}if(a.issues.length){"loose"===t.mode?n.value[s]=r[s]:n.issues.push({code:"invalid_key",origin:"record",issues:a.issues.map(e=>xn(e,i,Yt())),input:s,path:[s],inst:e});continue}const c=t.valueType._zod.run({value:r[s],issues:[]},i);c instanceof Promise?o.push(c.then(e=>{e.issues.length&&n.issues.push(...An(s,e.issues)),n.value[a.value]=e.value})):(c.issues.length&&n.issues.push(...An(s,c.issues)),n.value[a.value]=c.value)}}return o.length?Promise.all(o).then(()=>n):n}}),Er=Bt("$ZodEnum",(e,t)=>{Pi.init(e,t);const n=Kt(t.entries),i=new Set(n);e._zod.values=i,e._zod.pattern=new RegExp(`^(${n.filter(e=>hn.has(typeof e)).map(e=>"string"==typeof e?fn(e):e.toString()).join("|")})$`),e._zod.parse=(t,r)=>{const o=t.value;return i.has(o)||t.issues.push({code:"invalid_value",values:n,input:o,inst:e}),t}}),Or=Bt("$ZodLiteral",(e,t)=>{if(Pi.init(e,t),0===t.values.length)throw new Error("Cannot create literal schema with no valid values");const n=new Set(t.values);e._zod.values=n,e._zod.pattern=new RegExp(`^(${t.values.map(e=>"string"==typeof e?fn(e):e?fn(e.toString()):String(e)).join("|")})$`),e._zod.parse=(i,r)=>{const o=i.value;return n.has(o)||i.issues.push({code:"invalid_value",values:t.values,input:o,inst:e}),i}}),kr=Bt("$ZodTransform",(e,t)=>{Pi.init(e,t),e._zod.optin="optional",e._zod.parse=(n,i)=>{if("backward"===i.direction)throw new Jt(e.constructor.name);const r=t.transform(n.value,n);if(i.async)return(r instanceof Promise?r:Promise.resolve(r)).then(e=>(n.value=e,n.fallback=!0,n));if(r instanceof Promise)throw new Wt;return n.value=r,n.fallback=!0,n}});function Cr(e,t){return void 0===t&&(e.issues.length||e.fallback)?{issues:[],value:void 0}:e}const Tr=Bt("$ZodOptional",(e,t)=>{Pi.init(e,t),e._zod.optin="optional",e._zod.optout="optional",on(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),on(e._zod,"pattern",()=>{const e=t.innerType._zod.pattern;return e?new RegExp(`^(${nn(e.source)})?$`):void 0}),e._zod.parse=(e,n)=>{if("optional"===t.innerType._zod.optin){const i=e.value,r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(e=>Cr(e,i)):Cr(r,i)}return void 0===e.value?e:t.innerType._zod.run(e,n)}}),$r=Bt("$ZodExactOptional",(e,t)=>{Tr.init(e,t),on(e._zod,"values",()=>t.innerType._zod.values),on(e._zod,"pattern",()=>t.innerType._zod.pattern),e._zod.parse=(e,n)=>t.innerType._zod.run(e,n)}),Nr=Bt("$ZodNullable",(e,t)=>{Pi.init(e,t),on(e._zod,"optin",()=>t.innerType._zod.optin),on(e._zod,"optout",()=>t.innerType._zod.optout),on(e._zod,"pattern",()=>{const e=t.innerType._zod.pattern;return e?new RegExp(`^(${nn(e.source)}|null)$`):void 0}),on(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,null]):void 0),e._zod.parse=(e,n)=>null===e.value?e:t.innerType._zod.run(e,n)}),Rr=Bt("$ZodDefault",(e,t)=>{Pi.init(e,t),e._zod.optin="optional",on(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(e,n)=>{if("backward"===n.direction)return t.innerType._zod.run(e,n);if(void 0===e.value)return e.value=t.defaultValue,e;const i=t.innerType._zod.run(e,n);return i instanceof Promise?i.then(e=>Pr(e,t)):Pr(i,t)}});function Pr(e,t){return void 0===e.value&&(e.value=t.defaultValue),e}const zr=Bt("$ZodPrefault",(e,t)=>{Pi.init(e,t),e._zod.optin="optional",on(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(e,n)=>("backward"===n.direction||void 0===e.value&&(e.value=t.defaultValue),t.innerType._zod.run(e,n))}),Lr=Bt("$ZodNonOptional",(e,t)=>{Pi.init(e,t),on(e._zod,"values",()=>{const e=t.innerType._zod.values;return e?new Set([...e].filter(e=>void 0!==e)):void 0}),e._zod.parse=(n,i)=>{const r=t.innerType._zod.run(n,i);return r instanceof Promise?r.then(t=>jr(t,e)):jr(r,e)}});function jr(e,t){return e.issues.length||void 0!==e.value||e.issues.push({code:"invalid_type",expected:"nonoptional",input:e.value,inst:t}),e}const Dr=Bt("$ZodCatch",(e,t)=>{Pi.init(e,t),e._zod.optin="optional",on(e._zod,"optout",()=>t.innerType._zod.optout),on(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(e,n)=>{if("backward"===n.direction)return t.innerType._zod.run(e,n);const i=t.innerType._zod.run(e,n);return i instanceof Promise?i.then(i=>(e.value=i.value,i.issues.length&&(e.value=t.catchValue({...e,error:{issues:i.issues.map(e=>xn(e,n,Yt()))},input:e.value}),e.issues=[],e.fallback=!0),e)):(e.value=i.value,i.issues.length&&(e.value=t.catchValue({...e,error:{issues:i.issues.map(e=>xn(e,n,Yt()))},input:e.value}),e.issues=[],e.fallback=!0),e)}}),Mr=Bt("$ZodPipe",(e,t)=>{Pi.init(e,t),on(e._zod,"values",()=>t.in._zod.values),on(e._zod,"optin",()=>t.in._zod.optin),on(e._zod,"optout",()=>t.out._zod.optout),on(e._zod,"propValues",()=>t.in._zod.propValues),e._zod.parse=(e,n)=>{if("backward"===n.direction){const i=t.out._zod.run(e,n);return i instanceof Promise?i.then(e=>Fr(e,t.in,n)):Fr(i,t.in,n)}const i=t.in._zod.run(e,n);return i instanceof Promise?i.then(e=>Fr(e,t.out,n)):Fr(i,t.out,n)}});function Fr(e,t,n){return e.issues.length?(e.aborted=!0,e):t._zod.run({value:e.value,issues:e.issues,fallback:e.fallback},n)}const Vr=Bt("$ZodPreprocess",(e,t)=>{Mr.init(e,t)}),Ur=Bt("$ZodReadonly",(e,t)=>{Pi.init(e,t),on(e._zod,"propValues",()=>t.innerType._zod.propValues),on(e._zod,"values",()=>t.innerType._zod.values),on(e._zod,"optin",()=>t.innerType?._zod?.optin),on(e._zod,"optout",()=>t.innerType?._zod?.optout),e._zod.parse=(e,n)=>{if("backward"===n.direction)return t.innerType._zod.run(e,n);const i=t.innerType._zod.run(e,n);return i instanceof Promise?i.then(Hr):Hr(i)}});function Hr(e){return e.value=Object.freeze(e.value),e}const Gr=Bt("$ZodLazy",(e,t)=>{Pi.init(e,t),on(e._zod,"innerType",()=>{const e=t;return e._cachedInner||(e._cachedInner=t.getter()),e._cachedInner}),on(e._zod,"pattern",()=>e._zod.innerType?._zod?.pattern),on(e._zod,"propValues",()=>e._zod.innerType?._zod?.propValues),on(e._zod,"optin",()=>e._zod.innerType?._zod?.optin??void 0),on(e._zod,"optout",()=>e._zod.innerType?._zod?.optout??void 0),e._zod.parse=(t,n)=>e._zod.innerType._zod.run(t,n)}),Zr=Bt("$ZodCustom",(e,t)=>{fi.init(e,t),Pi.init(e,t),e._zod.parse=(e,t)=>e,e._zod.check=n=>{const i=n.value,r=t.fn(i);if(r instanceof Promise)return r.then(t=>qr(t,n,i,e));qr(r,n,i,e)}});function qr(e,t,n,i){if(!e){const e={code:"custom",input:n,inst:i,path:[...i._zod.def.path??[]],continue:!i._zod.def.abort};i._zod.def.params&&(e.params=i._zod.def.params),t.issues.push(wn(e))}}var Br;(Br=globalThis).__zod_globalRegistry??(Br.__zod_globalRegistry=new class{constructor(){this._map=new WeakMap,this._idmap=new Map}add(e,...t){const n=t[0];return this._map.set(e,n),n&&"object"==typeof n&&"id"in n&&this._idmap.set(n.id,e),this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(e){const t=this._map.get(e);return t&&"object"==typeof t&&"id"in t&&this._idmap.delete(t.id),this._map.delete(e),this}get(e){const t=e._zod.parent;if(t){const n={...this.get(t)??{}};delete n.id;const i={...n,...this._map.get(e)};return Object.keys(i).length?i:void 0}return this._map.get(e)}has(e){return this._map.has(e)}});const Wr=globalThis.__zod_globalRegistry;function Jr(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...yn(t)})}function Xr(e,t){return new yi({check:"less_than",...yn(t),value:e,inclusive:!1})}function Yr(e,t){return new yi({check:"less_than",...yn(t),value:e,inclusive:!0})}function Kr(e,t){return new vi({check:"greater_than",...yn(t),value:e,inclusive:!1})}function Qr(e,t){return new vi({check:"greater_than",...yn(t),value:e,inclusive:!0})}function eo(e,t){return new _i({check:"multiple_of",...yn(t),value:e})}function to(e,t){return new Ai({check:"max_length",...yn(t),maximum:e})}function no(e,t){return new Ii({check:"min_length",...yn(t),minimum:e})}function io(e,t){return new xi({check:"length_equals",...yn(t),length:e})}function ro(e){return new $i({check:"overwrite",tx:e})}function oo(e){let t=e?.target??"draft-2020-12";return"draft-4"===t&&(t="draft-04"),"draft-7"===t&&(t="draft-07"),{processors:e.processors??{},metadataRegistry:e?.metadata??Wr,target:t,unrepresentable:e?.unrepresentable??"throw",override:e?.override??(()=>{}),io:e?.io??"output",counter:0,seen:new Map,cycles:e?.cycles??"ref",reused:e?.reused??"inline",external:e?.external??void 0}}function so(e,t,n={path:[],schemaPath:[]}){var i;const r=e._zod.def,o=t.seen.get(e);if(o)return o.count++,n.schemaPath.includes(e)&&(o.cycle=n.path),o.schema;const s={schema:{},count:1,cycle:void 0,path:n.path};t.seen.set(e,s);const a=e._zod.toJSONSchema?.();if(a)s.schema=a;else{const i={...n,schemaPath:[...n.schemaPath,e],path:n.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,s.schema,i);else{const n=s.schema,o=t.processors[r.type];if(!o)throw new Error(`[toJSONSchema]: Non-representable type encountered: ${r.type}`);o(e,t,n,i)}const o=e._zod.parent;o&&(s.ref||(s.ref=o),so(o,t,i),t.seen.get(o).isParent=!0)}const c=t.metadataRegistry.get(e);return c&&Object.assign(s.schema,c),"input"===t.io&&lo(e)&&(delete s.schema.examples,delete s.schema.default),"input"===t.io&&"_prefault"in s.schema&&((i=s.schema).default??(i.default=s.schema._prefault)),delete s.schema._prefault,t.seen.get(e).schema}function ao(e,t){const n=e.seen.get(t);if(!n)throw new Error("Unprocessed schema. This is a bug in Zod.");const i=new Map;for(const t of e.seen.entries()){const n=e.metadataRegistry.get(t[0])?.id;if(n){const e=i.get(n);if(e&&e!==t[0])throw new Error(`Duplicate schema id "${n}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);i.set(n,t[0])}}const r=t=>{if(t[1].schema.$ref)return;const i=t[1],{ref:r,defId:o}=(t=>{const i="draft-2020-12"===e.target?"$defs":"definitions";if(e.external){const n=e.external.registry.get(t[0])?.id,r=e.external.uri??(e=>e);if(n)return{ref:r(n)};const o=t[1].defId??t[1].schema.id??"schema"+e.counter++;return t[1].defId=o,{defId:o,ref:`${r("__shared")}#/${i}/${o}`}}if(t[1]===n)return{ref:"#"};const r=`#/${i}/`,o=t[1].schema.id??"__schema"+e.counter++;return{defId:o,ref:r+o}})(t);i.def={...i.schema},o&&(i.defId=o);const s=i.schema;for(const e in s)delete s[e];s.$ref=r};if("throw"===e.cycles)for(const t of e.seen.entries()){const e=t[1];if(e.cycle)throw new Error(`Cycle detected: #/${e.cycle?.join("/")}/<root>\n\nSet the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(const n of e.seen.entries()){const i=n[1];if(t===n[0]){r(n);continue}if(e.external){const i=e.external.registry.get(n[0])?.id;if(t!==n[0]&&i){r(n);continue}}const o=e.metadataRegistry.get(n[0])?.id;(o||i.cycle||i.count>1&&"ref"===e.reused)&&r(n)}}function co(e,t){const n=e.seen.get(t);if(!n)throw new Error("Unprocessed schema. This is a bug in Zod.");const i=t=>{const n=e.seen.get(t);if(null===n.ref)return;const r=n.def??n.schema,o={...r},s=n.ref;if(n.ref=null,s){i(s);const n=e.seen.get(s),a=n.schema;if(!a.$ref||"draft-07"!==e.target&&"draft-04"!==e.target&&"openapi-3.0"!==e.target?Object.assign(r,a):(r.allOf=r.allOf??[],r.allOf.push(a)),Object.assign(r,o),t._zod.parent===s)for(const e in r)"$ref"!==e&&"allOf"!==e&&(e in o||delete r[e]);if(a.$ref&&n.def)for(const e in r)"$ref"!==e&&"allOf"!==e&&e in n.def&&JSON.stringify(r[e])===JSON.stringify(n.def[e])&&delete r[e]}const a=t._zod.parent;if(a&&a!==s){i(a);const t=e.seen.get(a);if(t?.schema.$ref&&(r.$ref=t.schema.$ref,t.def))for(const e in r)"$ref"!==e&&"allOf"!==e&&e in t.def&&JSON.stringify(r[e])===JSON.stringify(t.def[e])&&delete r[e]}e.override({zodSchema:t,jsonSchema:r,path:n.path??[]})};for(const t of[...e.seen.entries()].reverse())i(t[0]);const r={};if("draft-2020-12"===e.target?r.$schema="https://json-schema.org/draft/2020-12/schema":"draft-07"===e.target?r.$schema="http://json-schema.org/draft-07/schema#":"draft-04"===e.target?r.$schema="http://json-schema.org/draft-04/schema#":e.target,e.external?.uri){const n=e.external.registry.get(t)?.id;if(!n)throw new Error("Schema is missing an `id` property");r.$id=e.external.uri(n)}Object.assign(r,n.def??n.schema);const o=e.metadataRegistry.get(t)?.id;void 0!==o&&r.id===o&&delete r.id;const s=e.external?.defs??{};for(const t of e.seen.entries()){const e=t[1];e.def&&e.defId&&(e.def.id===e.defId&&delete e.def.id,s[e.defId]=e.def)}e.external||Object.keys(s).length>0&&("draft-2020-12"===e.target?r.$defs=s:r.definitions=s);try{const n=JSON.parse(JSON.stringify(r));return Object.defineProperty(n,"~standard",{value:{...t["~standard"],jsonSchema:{input:uo(t,"input",e.processors),output:uo(t,"output",e.processors)}},enumerable:!1,writable:!1}),n}catch(e){throw new Error("Error converting schema to JSON.")}}function lo(e,t){const n=t??{seen:new Set};if(n.seen.has(e))return!1;n.seen.add(e);const i=e._zod.def;if("transform"===i.type)return!0;if("array"===i.type)return lo(i.element,n);if("set"===i.type)return lo(i.valueType,n);if("lazy"===i.type)return lo(i.getter(),n);if("promise"===i.type||"optional"===i.type||"nonoptional"===i.type||"nullable"===i.type||"readonly"===i.type||"default"===i.type||"prefault"===i.type)return lo(i.innerType,n);if("intersection"===i.type)return lo(i.left,n)||lo(i.right,n);if("record"===i.type||"map"===i.type)return lo(i.keyType,n)||lo(i.valueType,n);if("pipe"===i.type)return!!e._zod.traits.has("$ZodCodec")||lo(i.in,n)||lo(i.out,n);if("object"===i.type){for(const e in i.shape)if(lo(i.shape[e],n))return!0;return!1}if("union"===i.type){for(const e of i.options)if(lo(e,n))return!0;return!1}if("tuple"===i.type){for(const e of i.items)if(lo(e,n))return!0;return!(!i.rest||!lo(i.rest,n))}return!1}const uo=(e,t,n={})=>i=>{const{libraryOptions:r,target:o}=i??{},s=oo({...r??{},target:o,io:t,processors:n});return so(e,s),ao(s,e),co(s,e)},po={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},mo=(e,t,n,i)=>{const r=e._zod.def;so(r.innerType,t,i),t.seen.get(e).ref=r.innerType},ho=Bt("ZodISODateTime",(e,t)=>{Wi.init(e,t),Do.init(e,t)});const fo=Bt("ZodISODate",(e,t)=>{Ji.init(e,t),Do.init(e,t)});const go=Bt("ZodISOTime",(e,t)=>{Xi.init(e,t),Do.init(e,t)});const yo=Bt("ZodISODuration",(e,t)=>{Yi.init(e,t),Do.init(e,t)});const vo=(e,t)=>{On.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:t=>function(e,t=e=>e.message){const n={_errors:[]},i=(e,r=[])=>{for(const o of e.issues)if("invalid_union"===o.code&&o.errors.length)o.errors.map(e=>i({issues:e},[...r,...o.path]));else if("invalid_key"===o.code)i({issues:o.issues},[...r,...o.path]);else if("invalid_element"===o.code)i({issues:o.issues},[...r,...o.path]);else{const e=[...r,...o.path];if(0===e.length)n._errors.push(t(o));else{let i=n,r=0;for(;r<e.length;){const n=e[r];r===e.length-1?(i[n]=i[n]||{_errors:[]},i[n]._errors.push(t(o))):i[n]=i[n]||{_errors:[]},i=i[n],r++}}}};return i(e),n}(e,t)},flatten:{value:t=>function(e,t=e=>e.message){const n={},i=[];for(const r of e.issues)r.path.length>0?(n[r.path[0]]=n[r.path[0]]||[],n[r.path[0]].push(t(r))):i.push(t(r));return{formErrors:i,fieldErrors:n}}(e,t)},addIssue:{value:t=>{e.issues.push(t),e.message=JSON.stringify(e.issues,Qt,2)}},addIssues:{value:t=>{e.issues.push(...t),e.message=JSON.stringify(e.issues,Qt,2)}},isEmpty:{get:()=>0===e.issues.length}})},_o=Bt("ZodError",vo,{Parent:Error}),bo=Cn(_o),Ao=Tn(_o),Io=$n(_o),xo=Rn(_o),So=zn(_o),wo=Ln(_o),Eo=jn(_o),Oo=Dn(_o),ko=Mn(_o),Co=Fn(_o),To=Vn(_o),$o=Un(_o),No=new WeakMap;function Ro(e,t,n){const i=Object.getPrototypeOf(e);let r=No.get(i);if(r||(r=new Set,No.set(i,r)),!r.has(t)){r.add(t);for(const e in n){const t=n[e];Object.defineProperty(i,e,{configurable:!0,enumerable:!1,get(){const n=t.bind(this);return Object.defineProperty(this,e,{configurable:!0,writable:!0,enumerable:!0,value:n}),n},set(t){Object.defineProperty(this,e,{configurable:!0,writable:!0,enumerable:!0,value:t})}})}}}const Po=Bt("ZodType",(e,t)=>(Pi.init(e,t),Object.assign(e["~standard"],{jsonSchema:{input:uo(e,"input"),output:uo(e,"output")}}),e.toJSONSchema=((e,t={})=>n=>{const i=oo({...n,processors:t});return so(e,i),ao(i,e),co(i,e)})(e,{}),e.def=t,e.type=t.type,Object.defineProperty(e,"_def",{value:t}),e.parse=(t,n)=>bo(e,t,n,{callee:e.parse}),e.safeParse=(t,n)=>Io(e,t,n),e.parseAsync=async(t,n)=>Ao(e,t,n,{callee:e.parseAsync}),e.safeParseAsync=async(t,n)=>xo(e,t,n),e.spa=e.safeParseAsync,e.encode=(t,n)=>So(e,t,n),e.decode=(t,n)=>wo(e,t,n),e.encodeAsync=async(t,n)=>Eo(e,t,n),e.decodeAsync=async(t,n)=>Oo(e,t,n),e.safeEncode=(t,n)=>ko(e,t,n),e.safeDecode=(t,n)=>Co(e,t,n),e.safeEncodeAsync=async(t,n)=>To(e,t,n),e.safeDecodeAsync=async(t,n)=>$o(e,t,n),Ro(e,"ZodType",{check(...e){const t=this.def;return this.clone(an(t,{checks:[...t.checks??[],...e.map(e=>"function"==typeof e?{_zod:{check:e,def:{check:"custom"},onattach:[]}}:e)]}),{parent:!0})},with(...e){return this.check(...e)},clone(e,t){return gn(this,e,t)},brand(){return this},register(e,t){return e.add(this,t),this},refine(e,t){return this.check(function(e,t={}){return function(e,t,n){return new Gs({type:"custom",check:"custom",fn:t,...yn(n)})}(0,e,t)}(e,t))},superRefine(e,t){return this.check(function(e,t){return function(e,t){const n=function(e,t){const n=new fi({check:"custom",...yn(t)});return n._zod.check=e,n}(t=>(t.addIssue=e=>{if("string"==typeof e)t.issues.push(wn(e,t.value,n._zod.def));else{const i=e;i.fatal&&(i.continue=!1),i.code??(i.code="custom"),i.input??(i.input=t.value),i.inst??(i.inst=n),i.continue??(i.continue=!n._zod.def.abort),t.issues.push(wn(i))}},e(t.value,t)),t);return n}(e,t)}(e,t))},overwrite(e){return this.check(ro(e))},optional(){return $s(this)},exactOptional(){return new Ns({type:"optional",innerType:this})},nullable(){return Ps(this)},nullish(){return $s(Ps(this))},nonoptional(e){return function(e,t){return new js({type:"nonoptional",innerType:e,...yn(t)})}(this,e)},array(){return hs(this)},or(e){return vs([this,e])},and(e){return new As({type:"intersection",left:this,right:e})},transform(e){return Fs(this,Cs(e))},default(e){return t=e,new zs({type:"default",innerType:this,get defaultValue(){return"function"==typeof t?t():mn(t)}});var t},prefault(e){return t=e,new Ls({type:"prefault",innerType:this,get defaultValue(){return"function"==typeof t?t():mn(t)}});var t},catch(e){return new Ds({type:"catch",innerType:this,catchValue:"function"==typeof(t=e)?t:()=>t});var t},pipe(e){return Fs(this,e)},readonly(){return new Us({type:"readonly",innerType:this})},describe(e){const t=this.clone();return Wr.add(t,{description:e}),t},meta(...e){if(0===e.length)return Wr.get(this);const t=this.clone();return Wr.add(t,e[0]),t},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(e){return e(this)}}),Object.defineProperty(e,"description",{get:()=>Wr.get(e)?.description,configurable:!0}),e)),zo=Bt("_ZodString",(e,t)=>{zi.init(e,t),Po.init(e,t),e._zod.processJSONSchema=(t,n,i)=>((e,t,n)=>{const i=n;i.type="string";const{minimum:r,maximum:o,format:s,patterns:a,contentEncoding:c}=e._zod.bag;if("number"==typeof r&&(i.minLength=r),"number"==typeof o&&(i.maxLength=o),s&&(i.format=po[s]??s,""===i.format&&delete i.format,"time"===s&&delete i.format),c&&(i.contentEncoding=c),a&&a.size>0){const e=[...a];1===e.length?i.pattern=e[0].source:e.length>1&&(i.allOf=[...e.map(e=>({..."draft-07"===t.target||"draft-04"===t.target||"openapi-3.0"===t.target?{type:"string"}:{},pattern:e.source}))])}})(e,t,n);const n=e._zod.bag;e.format=n.format??null,e.minLength=n.minimum??null,e.maxLength=n.maximum??null,Ro(e,"_ZodString",{regex(...e){return this.check(function(e,t){return new wi({check:"string_format",format:"regex",...yn(t),pattern:e})}(...e))},includes(...e){return this.check(function(e,t){return new ki({check:"string_format",format:"includes",...yn(t),includes:e})}(...e))},startsWith(...e){return this.check(function(e,t){return new Ci({check:"string_format",format:"starts_with",...yn(t),prefix:e})}(...e))},endsWith(...e){return this.check(function(e,t){return new Ti({check:"string_format",format:"ends_with",...yn(t),suffix:e})}(...e))},min(...e){return this.check(no(...e))},max(...e){return this.check(to(...e))},length(...e){return this.check(io(...e))},nonempty(...e){return this.check(no(1,...e))},lowercase(e){return this.check(function(e){return new Ei({check:"string_format",format:"lowercase",...yn(e)})}(e))},uppercase(e){return this.check(function(e){return new Oi({check:"string_format",format:"uppercase",...yn(e)})}(e))},trim(){return this.check(ro(e=>e.trim()))},normalize(...e){return this.check(function(e){return ro(t=>t.normalize(e))}(...e))},toLowerCase(){return this.check(ro(e=>e.toLowerCase()))},toUpperCase(){return this.check(ro(e=>e.toUpperCase()))},slugify(){return this.check(ro(e=>function(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}(e)))}})}),Lo=Bt("ZodString",(e,t)=>{zi.init(e,t),zo.init(e,t),e.email=t=>e.check(function(e,t){return new Mo({type:"string",format:"email",check:"string_format",abort:!1,...yn(t)})}(0,t)),e.url=t=>e.check(function(e,t){return new Uo({type:"string",format:"url",check:"string_format",abort:!1,...yn(t)})}(0,t)),e.jwt=t=>e.check(function(e,t){return new is({type:"string",format:"jwt",check:"string_format",abort:!1,...yn(t)})}(0,t)),e.emoji=t=>e.check(function(e,t){return new Ho({type:"string",format:"emoji",check:"string_format",abort:!1,...yn(t)})}(0,t)),e.guid=t=>e.check(Jr(Fo,t)),e.uuid=t=>e.check(function(e,t){return new Vo({type:"string",format:"uuid",check:"string_format",abort:!1,...yn(t)})}(0,t)),e.uuidv4=t=>e.check(function(e,t){return new Vo({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...yn(t)})}(0,t)),e.uuidv6=t=>e.check(function(e,t){return new Vo({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...yn(t)})}(0,t)),e.uuidv7=t=>e.check(function(e,t){return new Vo({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...yn(t)})}(0,t)),e.nanoid=t=>e.check(function(e,t){return new Go({type:"string",format:"nanoid",check:"string_format",abort:!1,...yn(t)})}(0,t)),e.guid=t=>e.check(Jr(Fo,t)),e.cuid=t=>e.check(function(e,t){return new Zo({type:"string",format:"cuid",check:"string_format",abort:!1,...yn(t)})}(0,t)),e.cuid2=t=>e.check(function(e,t){return new qo({type:"string",format:"cuid2",check:"string_format",abort:!1,...yn(t)})}(0,t)),e.ulid=t=>e.check(function(e,t){return new Bo({type:"string",format:"ulid",check:"string_format",abort:!1,...yn(t)})}(0,t)),e.base64=t=>e.check(function(e,t){return new es({type:"string",format:"base64",check:"string_format",abort:!1,...yn(t)})}(0,t)),e.base64url=t=>e.check(function(e,t){return new ts({type:"string",format:"base64url",check:"string_format",abort:!1,...yn(t)})}(0,t)),e.xid=t=>e.check(function(e,t){return new Wo({type:"string",format:"xid",check:"string_format",abort:!1,...yn(t)})}(0,t)),e.ksuid=t=>e.check(function(e,t){return new Jo({type:"string",format:"ksuid",check:"string_format",abort:!1,...yn(t)})}(0,t)),e.ipv4=t=>e.check(function(e,t){return new Xo({type:"string",format:"ipv4",check:"string_format",abort:!1,...yn(t)})}(0,t)),e.ipv6=t=>e.check(function(e,t){return new Yo({type:"string",format:"ipv6",check:"string_format",abort:!1,...yn(t)})}(0,t)),e.cidrv4=t=>e.check(function(e,t){return new Ko({type:"string",format:"cidrv4",check:"string_format",abort:!1,...yn(t)})}(0,t)),e.cidrv6=t=>e.check(function(e,t){return new Qo({type:"string",format:"cidrv6",check:"string_format",abort:!1,...yn(t)})}(0,t)),e.e164=t=>e.check(function(e,t){return new ns({type:"string",format:"e164",check:"string_format",abort:!1,...yn(t)})}(0,t)),e.datetime=t=>e.check(function(e){return function(e,t){return new ho({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...yn(t)})}(0,e)}(t)),e.date=t=>e.check(function(e){return function(e,t){return new fo({type:"string",format:"date",check:"string_format",...yn(t)})}(0,e)}(t)),e.time=t=>e.check(function(e){return function(e,t){return new go({type:"string",format:"time",check:"string_format",precision:null,...yn(t)})}(0,e)}(t)),e.duration=t=>e.check(function(e){return function(e,t){return new yo({type:"string",format:"duration",check:"string_format",...yn(t)})}(0,e)}(t))});function jo(e){return function(e,t){return new Lo({type:"string",...yn(t)})}(0,e)}const Do=Bt("ZodStringFormat",(e,t)=>{Li.init(e,t),zo.init(e,t)}),Mo=Bt("ZodEmail",(e,t)=>{Mi.init(e,t),Do.init(e,t)}),Fo=Bt("ZodGUID",(e,t)=>{ji.init(e,t),Do.init(e,t)}),Vo=Bt("ZodUUID",(e,t)=>{Di.init(e,t),Do.init(e,t)}),Uo=Bt("ZodURL",(e,t)=>{Fi.init(e,t),Do.init(e,t)}),Ho=Bt("ZodEmoji",(e,t)=>{Vi.init(e,t),Do.init(e,t)}),Go=Bt("ZodNanoID",(e,t)=>{Ui.init(e,t),Do.init(e,t)}),Zo=Bt("ZodCUID",(e,t)=>{Hi.init(e,t),Do.init(e,t)}),qo=Bt("ZodCUID2",(e,t)=>{Gi.init(e,t),Do.init(e,t)}),Bo=Bt("ZodULID",(e,t)=>{Zi.init(e,t),Do.init(e,t)}),Wo=Bt("ZodXID",(e,t)=>{qi.init(e,t),Do.init(e,t)}),Jo=Bt("ZodKSUID",(e,t)=>{Bi.init(e,t),Do.init(e,t)}),Xo=Bt("ZodIPv4",(e,t)=>{Ki.init(e,t),Do.init(e,t)}),Yo=Bt("ZodIPv6",(e,t)=>{Qi.init(e,t),Do.init(e,t)}),Ko=Bt("ZodCIDRv4",(e,t)=>{er.init(e,t),Do.init(e,t)}),Qo=Bt("ZodCIDRv6",(e,t)=>{tr.init(e,t),Do.init(e,t)}),es=Bt("ZodBase64",(e,t)=>{ir.init(e,t),Do.init(e,t)}),ts=Bt("ZodBase64URL",(e,t)=>{rr.init(e,t),Do.init(e,t)}),ns=Bt("ZodE164",(e,t)=>{or.init(e,t),Do.init(e,t)}),is=Bt("ZodJWT",(e,t)=>{sr.init(e,t),Do.init(e,t)}),rs=Bt("ZodNumber",(e,t)=>{ar.init(e,t),Po.init(e,t),e._zod.processJSONSchema=(t,n,i)=>((e,t,n)=>{const i=n,{minimum:r,maximum:o,format:s,multipleOf:a,exclusiveMaximum:c,exclusiveMinimum:l}=e._zod.bag;"string"==typeof s&&s.includes("int")?i.type="integer":i.type="number";const u="number"==typeof l&&l>=(r??Number.NEGATIVE_INFINITY),d="number"==typeof c&&c<=(o??Number.POSITIVE_INFINITY),p="draft-04"===t.target||"openapi-3.0"===t.target;u?p?(i.minimum=l,i.exclusiveMinimum=!0):i.exclusiveMinimum=l:"number"==typeof r&&(i.minimum=r),d?p?(i.maximum=c,i.exclusiveMaximum=!0):i.exclusiveMaximum=c:"number"==typeof o&&(i.maximum=o),"number"==typeof a&&(i.multipleOf=a)})(e,t,n),Ro(e,"ZodNumber",{gt(e,t){return this.check(Kr(e,t))},gte(e,t){return this.check(Qr(e,t))},min(e,t){return this.check(Qr(e,t))},lt(e,t){return this.check(Xr(e,t))},lte(e,t){return this.check(Yr(e,t))},max(e,t){return this.check(Yr(e,t))},int(e){return this.check(as(e))},safe(e){return this.check(as(e))},positive(e){return this.check(Kr(0,e))},nonnegative(e){return this.check(Qr(0,e))},negative(e){return this.check(Xr(0,e))},nonpositive(e){return this.check(Yr(0,e))},multipleOf(e,t){return this.check(eo(e,t))},step(e,t){return this.check(eo(e,t))},finite(){return this}});const n=e._zod.bag;e.minValue=Math.max(n.minimum??Number.NEGATIVE_INFINITY,n.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,e.maxValue=Math.min(n.maximum??Number.POSITIVE_INFINITY,n.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,e.isInt=(n.format??"").includes("int")||Number.isSafeInteger(n.multipleOf??.5),e.isFinite=!0,e.format=n.format??null});function os(e){return function(e,t){return new rs({type:"number",checks:[],...yn(t)})}(0,e)}const ss=Bt("ZodNumberFormat",(e,t)=>{cr.init(e,t),rs.init(e,t)});function as(e){return function(e,t){return new ss({type:"number",check:"number_format",abort:!1,format:"safeint",...yn(t)})}(0,e)}const cs=Bt("ZodBoolean",(e,t)=>{lr.init(e,t),Po.init(e,t),e._zod.processJSONSchema=(e,t,n)=>((e,t,n)=>{n.type="boolean"})(0,0,t)});function ls(e){return function(e,t){return new cs({type:"boolean",...yn(t)})}(0,e)}const us=Bt("ZodUnknown",(e,t)=>{ur.init(e,t),Po.init(e,t),e._zod.processJSONSchema=(e,t,n)=>{}});function ds(){return new us({type:"unknown"})}const ps=Bt("ZodNever",(e,t)=>{dr.init(e,t),Po.init(e,t),e._zod.processJSONSchema=(e,t,n)=>((e,t,n)=>{n.not={}})(0,0,t)});const ms=Bt("ZodArray",(e,t)=>{mr.init(e,t),Po.init(e,t),e._zod.processJSONSchema=(t,n,i)=>((e,t,n,i)=>{const r=n,o=e._zod.def,{minimum:s,maximum:a}=e._zod.bag;"number"==typeof s&&(r.minItems=s),"number"==typeof a&&(r.maxItems=a),r.type="array",r.items=so(o.element,t,{...i,path:[...i.path,"items"]})})(e,t,n,i),e.element=t.element,Ro(e,"ZodArray",{min(e,t){return this.check(no(e,t))},nonempty(e){return this.check(no(1,e))},max(e,t){return this.check(to(e,t))},length(e,t){return this.check(io(e,t))},unwrap(){return this.element}})});function hs(e,t){return function(e,t,n){return new ms({type:"array",element:t,...yn(n)})}(0,e,t)}const fs=Bt("ZodObject",(e,t)=>{vr.init(e,t),Po.init(e,t),e._zod.processJSONSchema=(t,n,i)=>((e,t,n,i)=>{const r=n,o=e._zod.def;r.type="object",r.properties={};const s=o.shape;for(const e in s)r.properties[e]=so(s[e],t,{...i,path:[...i.path,"properties",e]});const a=new Set(Object.keys(s)),c=new Set([...a].filter(e=>{const n=o.shape[e]._zod;return"input"===t.io?void 0===n.optin:void 0===n.optout}));c.size>0&&(r.required=Array.from(c)),"never"===o.catchall?._zod.def.type?r.additionalProperties=!1:o.catchall?o.catchall&&(r.additionalProperties=so(o.catchall,t,{...i,path:[...i.path,"additionalProperties"]})):"output"===t.io&&(r.additionalProperties=!1)})(e,t,n,i),on(e,"shape",()=>t.shape),Ro(e,"ZodObject",{keyof(){return ws(Object.keys(this._zod.def.shape))},catchall(e){return this.clone({...this._zod.def,catchall:e})},passthrough(){return this.clone({...this._zod.def,catchall:ds()})},loose(){return this.clone({...this._zod.def,catchall:ds()})},strict(){return this.clone({...this._zod.def,catchall:function(e,t){return new ps({type:"never",...yn(t)})}(0,e)});var e},strip(){return this.clone({...this._zod.def,catchall:void 0})},extend(e){return function(e,t){if(!pn(t))throw new Error("Invalid input to extend: expected a plain object");const n=e._zod.def.checks;if(n&&n.length>0){const n=e._zod.def.shape;for(const e in t)if(void 0!==Object.getOwnPropertyDescriptor(n,e))throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}const i=an(e._zod.def,{get shape(){const n={...e._zod.def.shape,...t};return sn(this,"shape",n),n}});return gn(e,i)}(this,e)},safeExtend(e){return function(e,t){if(!pn(t))throw new Error("Invalid input to safeExtend: expected a plain object");const n=an(e._zod.def,{get shape(){const n={...e._zod.def.shape,...t};return sn(this,"shape",n),n}});return gn(e,n)}(this,e)},merge(e){return function(e,t){if(e._zod.def.checks?.length)throw new Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.");const n=an(e._zod.def,{get shape(){const n={...e._zod.def.shape,...t._zod.def.shape};return sn(this,"shape",n),n},get catchall(){return t._zod.def.catchall},checks:t._zod.def.checks??[]});return gn(e,n)}(this,e)},pick(e){return function(e,t){const n=e._zod.def,i=n.checks;if(i&&i.length>0)throw new Error(".pick() cannot be used on object schemas containing refinements");return gn(e,an(e._zod.def,{get shape(){const e={};for(const i in t){if(!(i in n.shape))throw new Error(`Unrecognized key: "${i}"`);t[i]&&(e[i]=n.shape[i])}return sn(this,"shape",e),e},checks:[]}))}(this,e)},omit(e){return function(e,t){const n=e._zod.def,i=n.checks;if(i&&i.length>0)throw new Error(".omit() cannot be used on object schemas containing refinements");const r=an(e._zod.def,{get shape(){const i={...e._zod.def.shape};for(const e in t){if(!(e in n.shape))throw new Error(`Unrecognized key: "${e}"`);t[e]&&delete i[e]}return sn(this,"shape",i),i},checks:[]});return gn(e,r)}(this,e)},partial(...e){return function(e,t,n){const i=t._zod.def.checks;if(i&&i.length>0)throw new Error(".partial() cannot be used on object schemas containing refinements");const r=an(t._zod.def,{get shape(){const i=t._zod.def.shape,r={...i};if(n)for(const t in n){if(!(t in i))throw new Error(`Unrecognized key: "${t}"`);n[t]&&(r[t]=e?new e({type:"optional",innerType:i[t]}):i[t])}else for(const t in i)r[t]=e?new e({type:"optional",innerType:i[t]}):i[t];return sn(this,"shape",r),r},checks:[]});return gn(t,r)}(Ts,this,e[0])},required(...e){return function(e,t,n){const i=an(t._zod.def,{get shape(){const i=t._zod.def.shape,r={...i};if(n)for(const t in n){if(!(t in r))throw new Error(`Unrecognized key: "${t}"`);n[t]&&(r[t]=new e({type:"nonoptional",innerType:i[t]}))}else for(const t in i)r[t]=new e({type:"nonoptional",innerType:i[t]});return sn(this,"shape",r),r}});return gn(t,i)}(js,this,e[0])}})});function gs(e,t){const n={type:"object",shape:e??{},...yn(t)};return new fs(n)}const ys=Bt("ZodUnion",(e,t)=>{br.init(e,t),Po.init(e,t),e._zod.processJSONSchema=(t,n,i)=>((e,t,n,i)=>{const r=e._zod.def,o=!1===r.inclusive,s=r.options.map((e,n)=>so(e,t,{...i,path:[...i.path,o?"oneOf":"anyOf",n]}));o?n.oneOf=s:n.anyOf=s})(e,t,n,i),e.options=t.options});function vs(e,t){return new ys({type:"union",options:e,...yn(t)})}const _s=Bt("ZodDiscriminatedUnion",(e,t)=>{ys.init(e,t),Ar.init(e,t)});function bs(e,t,n){return new _s({type:"union",options:t,discriminator:e,...yn(n)})}const As=Bt("ZodIntersection",(e,t)=>{Ir.init(e,t),Po.init(e,t),e._zod.processJSONSchema=(t,n,i)=>((e,t,n,i)=>{const r=e._zod.def,o=so(r.left,t,{...i,path:[...i.path,"allOf",0]}),s=so(r.right,t,{...i,path:[...i.path,"allOf",1]}),a=e=>"allOf"in e&&1===Object.keys(e).length,c=[...a(o)?o.allOf:[o],...a(s)?s.allOf:[s]];n.allOf=c})(e,t,n,i)}),Is=Bt("ZodRecord",(e,t)=>{wr.init(e,t),Po.init(e,t),e._zod.processJSONSchema=(t,n,i)=>((e,t,n,i)=>{const r=n,o=e._zod.def;r.type="object";const s=o.keyType,a=s._zod.bag,c=a?.patterns;if("loose"===o.mode&&c&&c.size>0){const e=so(o.valueType,t,{...i,path:[...i.path,"patternProperties","*"]});r.patternProperties={};for(const t of c)r.patternProperties[t.source]=e}else"draft-07"!==t.target&&"draft-2020-12"!==t.target||(r.propertyNames=so(o.keyType,t,{...i,path:[...i.path,"propertyNames"]})),r.additionalProperties=so(o.valueType,t,{...i,path:[...i.path,"additionalProperties"]});const l=s._zod.values;if(l){const e=[...l].filter(e=>"string"==typeof e||"number"==typeof e);e.length>0&&(r.required=e)}})(e,t,n,i),e.keyType=t.keyType,e.valueType=t.valueType});function xs(e,t,n){return t&&t._zod?new Is({type:"record",keyType:e,valueType:t,...yn(n)}):new Is({type:"record",keyType:jo(),valueType:e,...yn(t)})}const Ss=Bt("ZodEnum",(e,t)=>{Er.init(e,t),Po.init(e,t),e._zod.processJSONSchema=(t,n,i)=>((e,t,n)=>{const i=Kt(e._zod.def.entries);i.every(e=>"number"==typeof e)&&(n.type="number"),i.every(e=>"string"==typeof e)&&(n.type="string"),n.enum=i})(e,0,n),e.enum=t.entries,e.options=Object.values(t.entries);const n=new Set(Object.keys(t.entries));e.extract=(e,i)=>{const r={};for(const i of e){if(!n.has(i))throw new Error(`Key ${i} not found in enum`);r[i]=t.entries[i]}return new Ss({...t,checks:[],...yn(i),entries:r})},e.exclude=(e,i)=>{const r={...t.entries};for(const t of e){if(!n.has(t))throw new Error(`Key ${t} not found in enum`);delete r[t]}return new Ss({...t,checks:[],...yn(i),entries:r})}});function ws(e,t){const n=Array.isArray(e)?Object.fromEntries(e.map(e=>[e,e])):e;return new Ss({type:"enum",entries:n,...yn(t)})}const Es=Bt("ZodLiteral",(e,t)=>{Or.init(e,t),Po.init(e,t),e._zod.processJSONSchema=(t,n,i)=>((e,t,n)=>{const i=e._zod.def,r=[];for(const e of i.values)if(void 0===e){if("throw"===t.unrepresentable)throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if("bigint"==typeof e){if("throw"===t.unrepresentable)throw new Error("BigInt literals cannot be represented in JSON Schema");r.push(Number(e))}else r.push(e);if(0===r.length);else if(1===r.length){const e=r[0];n.type=null===e?"null":typeof e,"draft-04"===t.target||"openapi-3.0"===t.target?n.enum=[e]:n.const=e}else r.every(e=>"number"==typeof e)&&(n.type="number"),r.every(e=>"string"==typeof e)&&(n.type="string"),r.every(e=>"boolean"==typeof e)&&(n.type="boolean"),r.every(e=>null===e)&&(n.type="null"),n.enum=r})(e,t,n),e.values=new Set(t.values),Object.defineProperty(e,"value",{get(){if(t.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});function Os(e,t){return new Es({type:"literal",values:Array.isArray(e)?e:[e],...yn(t)})}const ks=Bt("ZodTransform",(e,t)=>{kr.init(e,t),Po.init(e,t),e._zod.processJSONSchema=(e,t,n)=>((e,t)=>{if("throw"===t.unrepresentable)throw new Error("Transforms cannot be represented in JSON Schema")})(0,e),e._zod.parse=(n,i)=>{if("backward"===i.direction)throw new Jt(e.constructor.name);n.addIssue=i=>{if("string"==typeof i)n.issues.push(wn(i,n.value,t));else{const t=i;t.fatal&&(t.continue=!1),t.code??(t.code="custom"),t.input??(t.input=n.value),t.inst??(t.inst=e),n.issues.push(wn(t))}};const r=t.transform(n.value,n);return r instanceof Promise?r.then(e=>(n.value=e,n.fallback=!0,n)):(n.value=r,n.fallback=!0,n)}});function Cs(e){return new ks({type:"transform",transform:e})}const Ts=Bt("ZodOptional",(e,t)=>{Tr.init(e,t),Po.init(e,t),e._zod.processJSONSchema=(t,n,i)=>mo(e,t,0,i),e.unwrap=()=>e._zod.def.innerType});function $s(e){return new Ts({type:"optional",innerType:e})}const Ns=Bt("ZodExactOptional",(e,t)=>{$r.init(e,t),Po.init(e,t),e._zod.processJSONSchema=(t,n,i)=>mo(e,t,0,i),e.unwrap=()=>e._zod.def.innerType}),Rs=Bt("ZodNullable",(e,t)=>{Nr.init(e,t),Po.init(e,t),e._zod.processJSONSchema=(t,n,i)=>((e,t,n,i)=>{const r=e._zod.def,o=so(r.innerType,t,i),s=t.seen.get(e);"openapi-3.0"===t.target?(s.ref=r.innerType,n.nullable=!0):n.anyOf=[o,{type:"null"}]})(e,t,n,i),e.unwrap=()=>e._zod.def.innerType});function Ps(e){return new Rs({type:"nullable",innerType:e})}const zs=Bt("ZodDefault",(e,t)=>{Rr.init(e,t),Po.init(e,t),e._zod.processJSONSchema=(t,n,i)=>((e,t,n,i)=>{const r=e._zod.def;so(r.innerType,t,i),t.seen.get(e).ref=r.innerType,n.default=JSON.parse(JSON.stringify(r.defaultValue))})(e,t,n,i),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap}),Ls=Bt("ZodPrefault",(e,t)=>{zr.init(e,t),Po.init(e,t),e._zod.processJSONSchema=(t,n,i)=>((e,t,n,i)=>{const r=e._zod.def;so(r.innerType,t,i),t.seen.get(e).ref=r.innerType,"input"===t.io&&(n._prefault=JSON.parse(JSON.stringify(r.defaultValue)))})(e,t,n,i),e.unwrap=()=>e._zod.def.innerType}),js=Bt("ZodNonOptional",(e,t)=>{Lr.init(e,t),Po.init(e,t),e._zod.processJSONSchema=(t,n,i)=>((e,t,n,i)=>{const r=e._zod.def;so(r.innerType,t,i),t.seen.get(e).ref=r.innerType})(e,t,0,i),e.unwrap=()=>e._zod.def.innerType}),Ds=Bt("ZodCatch",(e,t)=>{Dr.init(e,t),Po.init(e,t),e._zod.processJSONSchema=(t,n,i)=>((e,t,n,i)=>{const r=e._zod.def;let o;so(r.innerType,t,i),t.seen.get(e).ref=r.innerType;try{o=r.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}n.default=o})(e,t,n,i),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap}),Ms=Bt("ZodPipe",(e,t)=>{Mr.init(e,t),Po.init(e,t),e._zod.processJSONSchema=(t,n,i)=>((e,t,n,i)=>{const r=e._zod.def,o=r.in._zod.traits.has("$ZodTransform"),s="input"===t.io?o?r.out:r.in:r.out;so(s,t,i),t.seen.get(e).ref=s})(e,t,0,i),e.in=t.in,e.out=t.out});function Fs(e,t){return new Ms({type:"pipe",in:e,out:t})}const Vs=Bt("ZodPreprocess",(e,t)=>{Ms.init(e,t),Vr.init(e,t)}),Us=Bt("ZodReadonly",(e,t)=>{Ur.init(e,t),Po.init(e,t),e._zod.processJSONSchema=(t,n,i)=>((e,t,n,i)=>{const r=e._zod.def;so(r.innerType,t,i),t.seen.get(e).ref=r.innerType,n.readOnly=!0})(e,t,n,i),e.unwrap=()=>e._zod.def.innerType}),Hs=Bt("ZodLazy",(e,t)=>{Gr.init(e,t),Po.init(e,t),e._zod.processJSONSchema=(t,n,i)=>((e,t,n,i)=>{const r=e._zod.innerType;so(r,t,i),t.seen.get(e).ref=r})(e,t,0,i),e.unwrap=()=>e._zod.def.getter()}),Gs=Bt("ZodCustom",(e,t)=>{Zr.init(e,t),Po.init(e,t),e._zod.processJSONSchema=(e,t,n)=>((e,t)=>{if("throw"===t.unrepresentable)throw new Error("Custom types cannot be represented in JSON Schema")})(0,e)}),Zs="custom";function qs(e){return function(e,t){return new rs({type:"number",coerce:!0,checks:[],...yn(t)})}(0,e)}const Bs=20971520,Ws=512e3,Js=Ws,Xs=Bs,Ys=41943040,Ks=jo().trim().min(1).max(80),Qs=ws(["app-session","ai-session"]),ea=ws(["image","file"]),ta={scopeType:ws(["session","create-request"]),scopeId:jo().trim().min(1).max(160),kind:ea,name:jo().trim().min(1).max(240),mime:jo().trim().min(1).max(120)};gs({...ta,size:qs().int().positive().max(Bs)}).strict();const na=jo().regex(/^cia_[a-f0-9]{24}$/);gs({attachmentId:na,...ta,size:os().int().positive().max(Bs)}).strict(),gs({offset:qs().int().nonnegative()}).strict(),gs({attachmentId:na,offset:os().int().nonnegative()}),gs({id:na,kind:ea,name:jo().trim().min(1).max(240),mime:jo().trim().min(1).max(120),size:os().int().positive().max(Bs),expiresAt:jo().datetime()});const ia=gs({id:jo().trim().min(1).max(120),kind:ea,name:jo().trim().min(1).max(240),mime:jo().trim().min(1).max(120),size:os().int().min(0).max(Number.MAX_SAFE_INTEGER)}),ra=ws(["available","expired","missing"]),oa=ia.extend({contentState:ra.default("available")}).strict(),sa=gs({id:jo().trim().min(1).max(240),text:jo(),attachments:hs(oa).max(6).default([])}).strict(),aa=ws(["running","waiting","idle","failed"]);gs({instanceId:jo().trim().min(1).max(160),sessionId:jo().trim().min(1).max(120),unread:ls(),sessionUpdatedAt:jo().datetime(),updatedAt:jo().datetime()}).strict();const ca=ws(["thinking","tool","editing","approval","responding","unknown"]),la=gs({id:jo().trim().min(1).max(240).optional(),kind:jo().trim().min(1).max(80).optional(),name:jo().trim().min(1).max(120),inputPreview:jo().trim().max(500).optional(),startedAt:jo().datetime().optional()}).strict(),ua=ws(["running","completed","failed","waiting"]),da=gs({id:jo().trim().min(1).max(240),turnId:jo().trim().min(1).max(240)}).strict(),pa=bs("type",[da.extend({type:Os("user-message"),text:jo(),attachments:hs(oa).max(6).optional()}).strict(),da.extend({type:Os("ai-message"),text:jo()}).strict(),da.extend({type:Os("activity"),activityKind:jo().trim().min(1).max(120),title:jo().trim().min(1).max(240),status:ua.optional(),summary:jo().max(4e3).optional(),input:jo().max(1e5).optional(),output:jo().max(1e6).optional(),paths:hs(jo().trim().min(1).max(4096)).max(500).optional(),exitCode:os().int().optional(),durationMs:os().int().nonnegative().optional()}).strict()]);gs({sessionId:jo().trim().min(1).max(120),providerSessionId:jo().trim().min(1).max(240),items:hs(pa),generatedAt:jo().datetime()}).strict(),gs({sessionId:jo().trim().min(1).max(120),turnId:jo().trim().min(1).max(240),items:hs(pa),generatedAt:jo().datetime()}).strict();const ma=ws(["pending-init","running","interrupted","completed","errored","shutdown","not-found"]),ha=ws(["started","interacted","interrupted"]),fa=gs({threadId:jo().trim().min(1).max(240),path:jo().trim().max(4096).optional(),status:ma,activity:ha.optional(),message:jo().trim().max(1e3).optional(),updatedAt:jo().datetime()}).strict(),ga=gs({toolCalls:os().int().min(0).default(0),edits:os().int().min(0).default(0),approvals:os().int().min(0).default(0)}).strict().default({toolCalls:0,edits:0,approvals:0}),ya=gs({send:ls().optional(),interrupt:ls().optional(),approval:ls().optional(),fork:ls().optional(),openApp:ls().optional(),close:ls().optional()}).strict(),va=gs({kind:Os("fork"),parentProviderSessionId:jo().trim().min(1).max(240),throughTurnId:jo().trim().min(1).max(240).optional()}).strict(),_a=vs([ia.extend({source:gs({type:Os("inline"),encoding:Os("base64"),data:jo().min(1).max(31457280)}).strict()}).strict().superRefine((e,t)=>{const n="image"===e.kind?Bs:Ws;(e.size<=0||("file"===e.kind?e.size>=n:e.size>n))&&t.addIssue({code:Zs,path:["size"],message:`Inline ${e.kind} must be between 1 byte and ${n} bytes.`})}),ia.extend({source:gs({type:Os("runtime-path"),path:jo().trim().min(1).max(4096)}).strict()}).strict()]),ba=ia.extend({sourceType:ws(["inline","runtime-path"])}).strict(),Aa=vs([gs({id:jo().trim().min(1).max(120),kind:ea.optional(),source:gs({type:Os("upload-ref")}).strict().default({type:"upload-ref"})}).strict(),gs({id:jo().trim().min(1).max(120),kind:ea,name:jo().trim().min(1).max(240),mime:jo().trim().min(1).max(120),size:os().int().min(0).max(Number.MAX_SAFE_INTEGER),source:gs({type:Os("runtime-path"),path:jo().trim().min(1).max(4096)}).strict()}).strict()]),Ia=ws(["auto","queue","steer","immediate"]),xa=ws(["ask","auto-review","full-access"]),Sa=ws(["review","rename","goal","compact"]);gs({command:Sa,argument:jo().trim().max(4e3).optional()}).strict().superRefine((e,t)=>{"rename"!==e.command||e.argument||t.addIssue({code:"custom",path:["argument"],message:"Rename requires a thread name."}),"review"!==e.command&&"compact"!==e.command||!e.argument||t.addIssue({code:"custom",path:["argument"],message:`${e.command} does not accept an argument.`})}),gs({command:Sa,value:jo().max(4e3).optional(),turnId:jo().trim().min(1).max(240).optional()}).strict(),ws(["skill","app","plugin"]);const wa=gs({name:jo().trim().min(1).max(240),path:jo().trim().min(1).max(4096)}),Ea=hs(bs("kind",[wa.extend({kind:Os("skill"),path:jo().trim().min(1).max(4096).refine(e=>e.startsWith("/"),"Skill paths must be absolute.")}).strict(),wa.extend({kind:Os("app"),path:jo().trim().min(7).max(4096).regex(/^app:\/\/[^\s/]+$/,"App paths must use app://<id>.")}).strict(),wa.extend({kind:Os("plugin"),path:jo().trim().min(10).max(4096).regex(/^plugin:\/\/[^\s/]+$/,"Plugin paths must use plugin://<id>.")}).strict()])).max(20).default([]),Oa=gs({kind:ws(["plugin","skill","file","directory","app"]),name:jo().trim().min(1).max(240),description:jo().trim().max(1e3).optional(),path:jo().trim().min(1).max(4096),icon:jo().trim().max(4096).optional()}).strict().superRefine((e,t)=>{"skill"!==e.kind||e.path.startsWith("/")||t.addIssue({code:"custom",path:["path"],message:"Skill paths must be absolute."}),"app"!==e.kind||/^app:\/\/[^\s/]+$/.test(e.path)||t.addIssue({code:"custom",path:["path"],message:"App paths must use app://<id>."}),"plugin"!==e.kind||/^plugin:\/\/[^\s/]+$/.test(e.path)||t.addIssue({code:"custom",path:["path"],message:"Plugin paths must use plugin://<id>."}),"file"!==e.kind&&"directory"!==e.kind||!e.path.startsWith("/")&&!e.path.split(/[\\/]+/).includes("..")||t.addIssue({code:"custom",path:["path"],message:"File and directory paths must be relative to the session cwd."})}),ka=gs({category:ws(["skills","plugins","apps","files"]),code:jo().trim().min(1).max(160),message:jo().trim().min(1).max(2e3)}).strict();gs({sessionId:jo().trim().min(1).max(120),providerSessionId:jo().trim().min(1).max(240),cwd:jo().trim().min(1).max(4096),candidates:hs(Oa).max(1e3).default([]),diagnostics:hs(ka).max(20).default([])}).strict(),gs({query:jo().trim().max(240).default("")}).strict(),gs({sessionId:jo().trim().min(1).max(120),cwd:jo().trim().min(1).max(4096),query:jo().trim().max(240),requestId:jo().trim().min(1).max(160),candidates:hs(Oa.refine(e=>"file"===e.kind||"directory"===e.kind,"File search only returns files and directories.")).max(200).default([]),complete:ls().default(!1)}).strict();const Ca=gs({message:jo().trim().min(1).max(2e4),mode:Ia.optional(),permissionMode:xa.optional()}),Ta=Ca.extend({attachments:hs(_a).max(6).default([]),references:Ea}).strict().superRefine((e,t)=>{e.attachments.reduce((e,t)=>e+("inline"===t.source.type?t.size:0),0)>Ys&&t.addIssue({code:Zs,path:["attachments"],message:"Inline attachments must be 41943040 bytes or less in total."})}),$a=Ca.extend({attachments:hs(Aa).max(6).default([]),references:Ea}).strict(),Na=gs({type:Os("runtime-path"),path:jo().trim().min(1).max(4096).refine(e=>e.startsWith("/")||/^[A-Za-z]:[\\/]/.test(e),"Runtime paths must be absolute in the target controlled instance.")}).strict();Ta.extend({agent:Ks,cwd:Na,cwdFolderId:jo().trim().min(1).max(120).optional(),clientRequestId:jo().trim().min(1).max(160)}).strict();const Ra=gs({mode:ws(["current-folder","worktree"]),branch:jo().trim().min(1).max(1024)}).strict();$a.extend({agent:Ks,cwdFolderId:jo().trim().min(1).max(120).optional(),gitSelection:Ra.optional(),clientRequestId:jo().trim().min(1).max(160)}).strict(),gs({disposition:ws(["created","already-created"]),aiSessionId:jo().trim().min(1).max(120),providerSessionId:jo().trim().min(1).max(240),creationSource:Os("ai-session")}).strict();const Pa=gs({mode:ws(["current","managed-worktree"]).default("current")}).strict().default({mode:"current"});gs({clientRequestId:jo().trim().min(1).max(160),throughTurnId:jo().trim().min(1).max(240).optional(),workspace:Pa.optional().default({mode:"current"})}).strict(),gs({disposition:ws(["created","already-created"]),aiSessionId:jo().trim().min(1).max(120),providerSessionId:jo().trim().min(1).max(240),creationSource:Os("ai-session")}).strict(),gs({clientRequestId:jo().trim().min(1).max(160)}).strict(),gs({disposition:ws(["opened","already-open"]),aiSessionId:jo().trim().min(1).max(120),providerSessionId:jo().trim().min(1).max(240),appSessionId:jo().trim().min(1).max(120),creationSource:Qs}).strict(),gs({clientRequestId:jo().trim().min(1).max(160)}).strict(),gs({disposition:ws(["closed","already-closed"]),aiSessionId:jo().trim().min(1).max(120),providerSessionId:jo().trim().min(1).max(240),creationSource:Qs}).strict(),gs({code:ws(["invalid-request","not-found","unsupported","provider-unavailable","materialization-failed","open-app-failed","close-failed","conflict"]),message:jo().trim().min(1).max(4e3),retryable:ls().default(!1),aiSessionId:jo().trim().min(1).max(120).optional(),providerSessionId:jo().trim().min(1).max(240).optional()}).strict(),gs({decision:ws(["allow","deny","skip"])}).strict(),gs({expectedRevision:os().int().min(0),queueIds:hs(jo().trim().min(1).max(120)).max(100)}).strict(),gs({expectedRevision:os().int().min(0),message:jo().trim().min(1).max(2e4)}).strict(),gs({code:jo().trim().min(1).max(160),message:jo(),instanceId:jo().trim().min(1).max(160).optional(),nodeId:jo().trim().min(1).max(160).optional(),route:jo().trim().min(1).max(4096).optional()}).strict();const za=gs({id:jo().trim().min(1).max(120),messageId:jo().trim().min(1).max(240).optional(),message:jo().trim().min(1).max(2e4),attachments:hs(ba).max(6).default([]),references:Ea,permissionMode:xa.optional(),status:ws(["queued","sending","failed"]).default("queued"),createdAt:jo().datetime(),updatedAt:jo().datetime(),error:jo().trim().max(4e3).optional()}).strict(),La=gs({revision:os().int().min(0).default(0),pendingCount:os().int().min(0).default(0),items:hs(za).max(100).default([])}).strict().default({revision:0,pendingCount:0,items:[]}),ja=ws(["control","realtime","adapter-snapshot","transcript-tail","transcript-scan","process-scan","app-session"]),Da=gs({id:jo().trim().min(1).max(240),status:ws(["running","completed"]),startedAt:jo().datetime().optional(),completedAt:jo().datetime().optional()}).strict(),Ma=gs({id:jo().trim().min(1).max(240),providerTurnId:jo().trim().max(240).optional(),source:ja.optional(),userPrompt:jo().trim().optional(),userMessages:hs(sa).max(100).optional(),status:ws(["queued","running","waiting","completed","failed"]).default("running"),phase:ca.optional(),summary:jo().trim().max(1e3).optional(),lastMessage:jo().trim().optional(),lastMessageItemId:jo().trim().max(240).optional(),contextCompactions:hs(Da).max(20).optional(),revision:os().int().min(0).default(0),sourcePriority:os().int().min(0).max(100).optional(),snapshotVersion:os().int().min(0).optional(),observedAt:jo().datetime().optional(),startedAt:jo().datetime().optional(),updatedAt:jo().datetime().optional(),completedAt:jo().datetime().optional()}).strict(),Fa=Ma.pick({id:!0,providerTurnId:!0,userPrompt:!0,userMessages:!0,status:!0,phase:!0,summary:!0,lastMessage:!0,contextCompactions:!0,startedAt:!0,updatedAt:!0,completedAt:!0}).strict(),Va=gs({id:jo().trim().min(1).max(120),agent:Ks,creationSource:Qs.default("app-session"),appSessionId:jo().trim().max(120).optional(),appId:jo().trim().max(120).optional(),providerSessionId:jo().trim().max(240).optional(),lineage:va.optional(),providerMeta:xs(jo(),ds()).optional(),appBindingKeys:hs(jo().trim().min(1).max(240)).max(20).optional(),actions:ya.optional(),activeTurnId:jo().trim().max(240).optional(),title:jo().trim().max(240).optional(),cwd:jo().trim().max(4096).optional(),cwdFolderId:jo().trim().min(1).max(120).optional(),userPrompt:jo().trim().optional(),turns:hs(Ma).max(50).optional(),status:aa.default("running"),phase:ca.default("unknown"),summary:jo().trim().max(1e3).optional(),lastMessage:jo().trim().optional(),lastMessageItemId:jo().trim().max(240).optional(),currentTool:la.optional(),toolCallsSinceLastMessage:os().int().min(0).default(0),subAgents:hs(fa).max(50).default([]),transcriptPath:jo().trim().max(4096).optional(),transcriptSize:os().int().min(0).optional(),startedAt:jo().datetime(),updatedAt:jo().datetime(),completedAt:jo().datetime().optional(),error:jo().trim().max(4e3).optional(),counters:ga,queue:La}).strict();Va.pick({id:!0,appBindingKeys:!0,cwd:!0,error:!0,providerMeta:!0,queue:!0,subAgents:!0}).strict();const Ua=Ma.pick({id:!0,providerTurnId:!0,status:!0,phase:!0,revision:!0,startedAt:!0,updatedAt:!0,completedAt:!0}).extend({bodyRevision:jo().trim().min(1).max(64)}).strict();gs({sessionId:jo().trim().min(1).max(120),revision:jo().trim().min(1).max(64),turns:hs(Ua).max(50)}).strict(),gs({sessionId:jo().trim().min(1).max(120),revision:jo().trim().min(1).max(64),turn:Ma}).strict();const Ha=gs({session:Va,provider:jo().trim().min(1).max(80),action:ws(["send","queue","steer","interrupt","approval"]),decision:ws(["allow","deny","skip"]).optional(),turnId:jo().trim().min(1).max(240).optional(),providerTurnId:jo().trim().min(1).max(240).optional(),queueId:jo().trim().min(1).max(120).optional()}).strict(),Ga=Ha.omit({session:!0}).extend({sessionId:jo().trim().min(1).max(120),messageId:jo().trim().min(1).max(240).optional()}).strict();vs([Ga,Ha.transform(function(e){const t=e.session.turns?.at(-1),n=(e.queueId?e.session.queue?.items.find(t=>t.id===e.queueId)?.messageId:void 0)||("send"===e.action||"queue"===e.action||"steer"===e.action?t?.userMessages?.at(-1)?.id:void 0);return Ga.parse({sessionId:e.session.id,provider:e.provider,action:e.action,...e.decision?{decision:e.decision}:{},...e.turnId||e.session.activeTurnId||t?.id?{turnId:e.turnId||e.session.activeTurnId||t?.id}:{},...e.providerTurnId||t?.providerTurnId?{providerTurnId:e.providerTurnId||t?.providerTurnId}:{},...e.queueId?{queueId:e.queueId}:{},...n?{messageId:n}:{}})})]);const Za=gs({id:jo().trim().min(1).max(120),agent:Ks,creationSource:Qs,providerSessionId:jo().trim().min(1).max(240),lineage:va.optional(),title:jo().trim().max(240).optional(),userPrompt:jo().trim().optional(),lastMessage:jo().trim().optional(),cwd:jo().trim().min(1).max(4096),cwdFolderId:jo().trim().min(1).max(120).optional(),lastActiveAt:jo().datetime(),archivedAt:jo().datetime()}).strict();gs({schemaVersion:Os(1).default(1),items:hs(Za).max(500).default([])}).strict(),gs({items:hs(Za).max(500).default([])}).strict(),gs({item:Za,turns:hs(Fa).max(50).default([])}).strict(),gs({disposition:ws(["resumed","already-open"]),aiSessionId:jo().trim().min(1).max(120),providerSessionId:jo().trim().min(1).max(240),appSessionId:jo().trim().min(1).max(120).optional(),creationSource:Qs}).strict();const qa=Ma.omit({userMessages:!0}),Ba=Va.pick({id:!0,agent:!0,creationSource:!0,appSessionId:!0,appId:!0,providerSessionId:!0,lineage:!0,providerMeta:!0,appBindingKeys:!0,actions:!0,activeTurnId:!0,title:!0,cwd:!0,cwdFolderId:!0,userPrompt:!0,turns:!0,status:!0,phase:!0,summary:!0,lastMessage:!0,lastMessageItemId:!0,currentTool:!0,toolCallsSinceLastMessage:!0,subAgents:!0,queue:!0,startedAt:!0,updatedAt:!0,error:!0}).extend({turns:hs(qa).max(50).optional(),detailRevision:jo().trim().min(1).max(64).optional(),turnsRevision:jo().trim().min(1).max(64).optional(),turnCount:os().int().min(0).optional(),subAgentCount:os().int().min(0).optional(),lastUserMessageAt:jo().datetime().optional()}).strict(),Wa=gs({runningCount:os().int().min(0).default(0),waitingCount:os().int().min(0).default(0),staleCount:os().int().min(0).default(0),sessions:hs(Ba).default([]),updatedAt:jo().datetime()}).strict();gs({streamId:jo().trim().min(1).max(240),revision:os().int().min(0),lastEventAt:jo().datetime(),snapshot:Wa}).strict(),Wa.pick({runningCount:!0,waitingCount:!0,staleCount:!0,updatedAt:!0}).extend({idleCount:os().int().min(0).default(0),problemCount:os().int().min(0).default(0),revision:os().int().min(0).optional()});const Ja=ws(["provider-event","app-session-created","app-session-updated","app-session-deleted","discovery-scan","control-action","heartbeat-sync","startup"]),Xa=gs({streamId:jo().trim().min(1).max(240),instanceId:jo().trim().min(1).max(160),nodeId:jo().trim().min(1).max(160).optional(),revision:os().int().min(0),previousRevision:os().int().min(0).optional(),traceId:jo().trim().min(1).max(160),generatedAt:jo().datetime(),reason:Ja}).strict(),Ya=gs({meta:Xa,snapshot:Wa}).strict(),Ka=gs({meta:Xa,upserted:hs(Ba).default([]),removed:hs(jo().trim().min(1).max(120)).default([])}).strict(),Qa=gs({meta:Xa,sessionIds:hs(jo().trim().min(1).max(120)).default([]),expiresAt:jo().datetime()}).strict();gs({instanceId:jo().trim().min(1).max(160),nodeId:jo().trim().min(1).max(160).optional(),sessionId:jo().trim().min(1).max(120),providerSessionId:jo().trim().min(1).max(240).optional(),turnId:jo().trim().min(1).max(240),itemId:jo().trim().min(1).max(240),delta:jo().min(1),generatedAt:jo().datetime()}).strict().omit({instanceId:!0,nodeId:!0,providerSessionId:!0}).strict(),gs({instanceId:jo().trim().min(1).max(160),nodeId:jo().trim().min(1).max(160).optional(),sessionId:jo().trim().min(1).max(120),providerSessionId:jo().trim().min(1).max(240),item:pa,generatedAt:jo().datetime()}).strict(),gs({streamId:jo().trim().min(1).max(240),instanceId:jo().trim().min(1).max(160),sinceRevision:os().int().min(0),latestRevision:os().int().min(0),earliestRetainedRevision:os().int().min(0),syncRequired:ls().default(!1),events:hs(bs("type",[gs({type:Os("ai-session.snapshot"),payload:Ya}).strict(),gs({type:Os("ai-session.patch"),payload:Ka}).strict(),gs({type:Os("ai-session.removed"),payload:Qa}).strict()])).default([])}).strict();const ec=gs({source:ja,sourcePriority:os().int().min(0).max(100).optional(),observedAt:jo().datetime().optional(),snapshotVersion:os().int().min(0).optional()}).strict();bs("type",[ec.extend({type:Os("snapshot"),agent:jo().trim().min(1).max(80),creationSource:Qs.optional(),appSessionId:jo().trim().max(120).optional(),appId:jo().trim().max(120).optional(),providerSessionId:jo().trim().max(240).optional(),lineage:va.optional(),providerMeta:xs(jo(),ds()).optional(),appBindingKeys:hs(jo().trim().min(1).max(240)).max(20).optional(),actions:ya.optional(),title:jo().trim().max(240).optional(),cwd:jo().trim().max(4096).optional(),cwdFolderId:jo().trim().min(1).max(120).optional(),activeTurnId:jo().trim().max(240).optional(),userPrompt:jo().trim().optional(),turns:hs(Ma).max(50).optional(),status:aa.optional(),phase:ca.optional(),summary:jo().trim().max(1e3).optional(),lastMessage:jo().trim().optional(),lastMessageItemId:jo().trim().max(240).optional(),error:jo().trim().max(4e3).optional(),currentTool:la.optional(),toolCallsSinceLastMessage:os().int().min(0).optional(),subAgents:hs(fa).max(50).optional(),transcriptPath:jo().trim().max(4096).optional(),transcriptSize:os().int().min(0).optional(),replaceActivity:ls().optional()}).strict(),ec.extend({type:Os("event"),sessionId:jo().trim().min(1).max(120),kind:ws(["lifecycle","send-ack","turn-started","user-message","assistant-message","approval-requested","turn-completed","session-error","tool-activity","sub-agent-activity","context-compaction"]),activeTurnId:jo().trim().max(240).optional(),providerTurnId:jo().trim().max(240).optional(),userPrompt:jo().trim().optional(),userMessage:sa.optional(),text:jo().optional(),itemId:jo().trim().max(240).optional(),status:aa.optional(),phase:ca.optional(),summary:jo().trim().max(1e3).optional(),error:jo().trim().max(4e3).optional(),currentTool:la.nullable().optional(),toolCallsSinceLastMessage:os().int().min(0).optional(),subAgents:hs(fa).max(50).optional(),contextCompaction:Da.optional(),counters:gs({toolCalls:os().int().min(0).optional(),edits:os().int().min(0).optional(),approvals:os().int().min(0).optional()}).strict().optional()}).strict().superRefine((e,t)=>{if("session-error"!==e.kind||e.error||t.addIssue({code:"custom",path:["error"],message:"session-error events require error"}),"context-compaction"===e.kind?e.contextCompaction||t.addIssue({code:"custom",path:["contextCompaction"],message:"context-compaction events require contextCompaction"}):void 0!==e.contextCompaction&&t.addIssue({code:"custom",path:["contextCompaction"],message:"contextCompaction is only valid for context-compaction events"}),"send-ack"!==e.kind&&"user-message"!==e.kind&&void 0!==e.userMessage&&t.addIssue({code:"custom",path:["userMessage"],message:"userMessage is only valid for send-ack and user-message events"}),"sub-agent-activity"===e.kind?e.subAgents||t.addIssue({code:"custom",path:["subAgents"],message:"sub-agent-activity events require subAgents"}):void 0!==e.subAgents&&t.addIssue({code:"custom",path:["subAgents"],message:"subAgents is only valid for sub-agent-activity events"}),"tool-activity"!==e.kind)return void 0!==e.currentTool&&t.addIssue({code:"custom",path:["currentTool"],message:"currentTool is only valid for tool-activity events"}),void(void 0!==e.toolCallsSinceLastMessage&&t.addIssue({code:"custom",path:["toolCallsSinceLastMessage"],message:"toolCallsSinceLastMessage is only valid for tool-activity events"}));"currentTool"in e||t.addIssue({code:"custom",path:["currentTool"],message:"tool-activity events require currentTool"}),void 0===e.toolCallsSinceLastMessage&&t.addIssue({code:"custom",path:["toolCallsSinceLastMessage"],message:"tool-activity events require toolCallsSinceLastMessage"})})]);const tc=vs([gs({type:Os("schedule"),scheduleKind:Os("interval").default("interval"),intervalMs:os().int().min(1e3)}).strict(),gs({type:Os("schedule"),scheduleKind:Os("daily"),timeOfDay:jo().regex(/^([01]\d|2[0-3]):[0-5]\d$/),timezone:jo().trim().min(1).max(120)}).strict(),gs({type:Os("schedule"),scheduleKind:Os("weekly"),weekdays:hs(os().int().min(0).max(6)).min(1).max(7),timeOfDay:jo().regex(/^([01]\d|2[0-3]):[0-5]\d$/),timezone:jo().trim().min(1).max(120)}).strict()]),nc=vs([tc,gs({type:Os("file-change"),roots:hs(jo().trim().min(1).max(4096)).min(1).max(50),globs:hs(jo().trim().min(1).max(500)).min(1).max(100),ignore:hs(jo().trim().min(1).max(500)).max(100).optional(),debounceMs:os().int().min(100).max(6e4).default(1500)}).strict(),gs({type:Os("ai-session"),agent:jo().trim().min(1).max(80).optional(),statuses:hs(ws(["running","waiting","idle","failed"])).max(20).optional(),phases:hs(ws(["thinking","tool","editing","approval","responding","unknown"])).max(20).optional()}).strict()]),ic=gs({promptTemplate:jo().trim().min(1).max(2e4)}).strict(),rc=gs({cooldownMs:os().int().min(0).max(864e5).optional(),maxConcurrentRuns:os().int().min(1).max(20).default(1),whenBusy:ws(["skip","queue"]).default("skip")}).strict(),oc=gs({configHash:jo().trim().min(8).max(80),name:jo().trim().min(1).max(160),description:jo().trim().max(1e3).optional(),source:nc,action:ic,policy:rc.default({maxConcurrentRuns:1,whenBusy:"skip"}),createdAt:jo().datetime(),updatedAt:jo().datetime()}).strict(),sc=gs({type:Os("ai-session"),aiSessionId:jo().trim().min(1).max(160)}).strict(),ac=gs({configHash:jo().trim().min(8).max(80),deploymentId:jo().trim().min(1).max(240).optional(),instanceId:jo().trim().min(1).max(160),origin:ws(["control-plane","controlled-instance"]).default("controlled-instance"),enabled:ls().default(!0),target:sc,localName:jo().trim().min(1).max(160).optional(),createdAt:jo().datetime(),updatedAt:jo().datetime()}).strict(),cc=gs({configHash:jo().trim().min(8).max(80),deploymentId:jo().trim().min(1).max(240).optional(),instanceId:jo().trim().min(1).max(160),status:ws(["idle","running","disabled","error"]).default("idle"),lastTriggeredAt:jo().datetime().optional(),lastCompletedAt:jo().datetime().optional(),lastSkippedAt:jo().datetime().optional(),lastError:jo().trim().max(4e3).optional(),runCount:os().int().min(0).default(0),skippedCount:os().int().min(0).default(0)}).strict(),lc=gs({id:jo().trim().min(1).max(160),configHash:jo().trim().min(8).max(80),deploymentId:jo().trim().min(1).max(240).optional(),instanceId:jo().trim().min(1).max(160),eventType:ws(["manual","schedule","file-change","ai-session"]),status:ws(["started","completed","failed","skipped"]),target:sc,promptPreview:jo().trim().max(500),eventSummary:jo().trim().max(1e3).optional(),error:jo().trim().max(4e3).optional(),startedAt:jo().datetime(),completedAt:jo().datetime().optional()}).strict();gs({schemaVersion:Os(1).default(1),configs:hs(oc).default([]),deployments:hs(ac).default([]),runtime:hs(cc).default([]),recentRuns:hs(lc).default([])}).strict();const uc=gs({instanceId:jo().trim().min(1).max(160),instanceName:jo().trim().min(1).max(160),deployment:ac,runtime:cc.optional()}).strip(),dc=lc.extend({instanceName:jo().trim().min(1).max(160).optional()}).strip(),pc=gs({configHash:jo().trim().min(8).max(80),config:oc,deploymentCount:os().int().min(0),enabledCount:os().int().min(0),runningCount:os().int().min(0),errorCount:os().int().min(0),ownedByControlPlane:ls(),controlPlaneDeploymentCount:os().int().min(0),deployments:hs(uc),recentRuns:hs(dc)}).strip();gs({updatedAt:jo().datetime(),triggers:hs(pc)}).strip(),gs({name:oc.shape.name,description:oc.shape.description,source:nc,action:ic,policy:rc.partial().optional()}).strict(),gs({scope:ws(["node","instance"]),nodeId:jo().trim().min(1).max(160).optional(),instanceId:jo().trim().min(1).max(160).optional(),code:jo().trim().min(1).max(160),message:jo().trim().min(1).max(4e3)}).strip();const mc=jo().regex(/^\d{4}-\d{2}-\d{2}$/,"Proxy protocol version must use YYYY-MM-DD format."),hc=jo().trim().min(1).max(160).regex(/^[a-zA-Z0-9][a-zA-Z0-9_.:-]*$/),fc=jo().datetime(),gc=jo().trim().min(32).max(4096),yc=jo().trim().max(2048).transform((e,t)=>{try{return function(e){const t=new URL(e.trim());if("https:"!==t.protocol||t.username||t.password||"/"!==t.pathname||t.search||t.hash)throw new Error("Proxy origin must be an HTTPS origin without credentials, path, query, or fragment.");return t.origin}(e)}catch(e){return t.addIssue({code:"custom",message:e instanceof Error?e.message:String(e)}),qt}});jo().trim().min(1).max(4096).transform((e,t)=>{try{return function(e){const t=e.trim();if(!t.startsWith("/")||t.startsWith("//")||t.includes("\\")||/%25/i.test(t))throw new Error("Proxy route must be a single-encoded node-agent relative route.");const n=t.split("?",1)[0];let i,r;try{i=n.split("/").map(e=>decodeURIComponent(e))}catch{throw new Error("Proxy route contains invalid percent encoding.")}if(i.some(e=>".."===e||"."===e))throw new Error("Proxy route cannot traverse outside the node-agent API.");try{r=new URL(t,"https://node-agent.invalid")}catch{throw new Error("Proxy route is invalid.")}if("https://node-agent.invalid"!==r.origin||r.username||r.password)throw new Error("Proxy route cannot select an absolute upstream URL.");return`${r.pathname}${r.search}`}(e)}catch(e){return t.addIssue({code:"custom",message:e instanceof Error?e.message:String(e)}),qt}});const vc=gs({code:ws(Object.values({ProtocolUnsupported:"CONTROL_PLANE_PROXY_PROTOCOL_UNSUPPORTED",InviteInvalid:"CONTROL_PLANE_PROXY_INVITE_INVALID",InviteExpired:"CONTROL_PLANE_PROXY_INVITE_EXPIRED",InviteConsumed:"CONTROL_PLANE_PROXY_INVITE_CONSUMED",InviteRevoked:"CONTROL_PLANE_PROXY_INVITE_REVOKED",TargetUnavailable:"CONTROL_PLANE_PROXY_TARGET_UNAVAILABLE",TargetMismatch:"CONTROL_PLANE_PROXY_TARGET_MISMATCH",BindingUnknown:"CONTROL_PLANE_PROXY_BINDING_UNKNOWN",BindingRevoked:"CONTROL_PLANE_PROXY_BINDING_REVOKED",BindingIdentityConflict:"CONTROL_PLANE_PROXY_BINDING_IDENTITY_CONFLICT",AuthenticationFailed:"CONTROL_PLANE_PROXY_AUTHENTICATION_FAILED",RouteInvalid:"CONTROL_PLANE_PROXY_ROUTE_INVALID",HeaderInvalid:"CONTROL_PLANE_PROXY_HEADER_INVALID",ResourceLimit:"CONTROL_PLANE_PROXY_RESOURCE_LIMIT",SnapshotRequired:"CONTROL_PLANE_PROXY_SNAPSHOT_REQUIRED",Unavailable:"CONTROL_PLANE_PROXY_UNAVAILABLE",TransportFailed:"CONTROL_PLANE_PROXY_TRANSPORT_FAILED"})),message:jo().trim().min(1).max(2048),retryable:ls(),details:xs(jo(),ds()).optional()}).strict(),_c=gs({id:hc,targetNodeId:hc,status:ws(["active","revoked"]),createdBy:hc,expiresAt:fc,revokedAt:fc.optional(),createdAt:fc,updatedAt:fc}).strict();gs({targetNodeId:hc,expiresInSeconds:os().int().min(60).max(3600).default(600)}).strict(),gs({invite:_c,token:jo().trim().min(24).max(512),proxyOrigin:yc,protocolVersion:mc}).strict();const bc=gs({id:hc,claimId:hc,sourceControlPlaneId:hc,targetNodeId:hc,bindingKeyId:hc,status:ws(["active","revoked"]),revision:os().int().positive(),lastError:vc.optional(),revokedAt:fc.optional(),createdAt:fc,updatedAt:fc}).strict();gs({protocolVersion:mc,inviteToken:jo().trim().min(24).max(512).optional(),claimId:hc,sourceControlPlaneId:hc,targetNodeId:hc.optional(),bindingKeyId:hc,credential:gc}).strict(),gs({sourceControlPlaneId:hc,bindingKeyId:hc,credential:gc}).strict();const Ac=gs({id:hc,name:jo().trim().min(1).max(160),status:ws(["unknown","online","offline","degraded"]),health:ws(["unknown","ok","degraded","failed"]),lastSeenAt:fc.optional(),capabilities:xs(jo(),ds()).default({})}).strict(),Ic=gs({protocolVersion:mc,binding:bc,streamId:hc,revision:os().int().nonnegative(),observedAt:fc,target:Ac}).strict();bs("type",[gs({type:Os("control-plane-proxy.event"),protocolVersion:mc,streamId:hc,bindingId:hc,sourceControlPlaneId:hc,targetNodeId:hc,revision:os().int().positive(),source:gs({id:jo().trim().min(1).max(512),seq:os().int().nonnegative()}).strict(),target:Ac,event:gs({type:jo().trim().min(1).max(240),topic:jo().trim().min(1).max(240),createdAt:fc}).strict()}).strict(),gs({type:Os("control-plane-proxy.events.ready"),protocolVersion:mc,streamId:hc,bindingId:hc,sourceControlPlaneId:hc,targetNodeId:hc,latestRevision:os().int().nonnegative(),earliestRetainedRevision:os().int().nonnegative()}).strict(),gs({type:Os("control-plane-proxy.snapshot-required"),protocolVersion:mc,streamId:hc,bindingId:hc,sourceControlPlaneId:hc,targetNodeId:hc,sinceRevision:os().int().nonnegative(),latestRevision:os().int().nonnegative(),earliestRetainedRevision:os().int().nonnegative(),error:vc}).strict()]),gs({protocolVersion:mc,binding:bc,target:Ic.shape.target}).strict(),gs({id:hc,claimId:hc,proxyOrigin:yc,requestedName:jo().trim().min(1).max(160).optional(),sourceControlPlaneId:hc,targetNodeId:hc.optional(),bindingKeyId:hc,credential:gc,status:ws(["pending","compensation-required"]),createdAt:fc,updatedAt:fc,expiresAt:fc}).strict().omit({credential:!0}),gs({id:hc,nodeId:hc,proxyOrigin:yc,proxyBindingId:hc,targetNodeId:hc,sourceControlPlaneId:hc,bindingKeyId:hc,credential:gc,createdAt:fc,updatedAt:fc}).strict();const xc=gs({agent:jo().trim().min(1).max(120),actions:gs({create:ls().default(!1),send:ls().default(!1),queue:ls().default(!1),steer:ls().default(!1),interrupt:ls().default(!1),archive:ls().default(!1),delete:ls().default(!1),fork:ls().default(!1),approvalDecisions:hs(ws(["allow","deny","skip"])).max(3).default([])}).passthrough(),timeline:gs({sessionRead:ls().default(!1),turnRead:ls().default(!1),liveItems:ls().default(!1)}).passthrough()}).passthrough(),Sc=hs(xc).max(100).default([]),wc="2026-08-23",Ec=new Set(["2026-08-01","2026-08-16","2026-08-17","2026-08-20",wc]),Oc=jo().regex(/^\d{4}-\d{2}-\d{2}$/,"Protocol version must use YYYY-MM-DD format."),kc=jo().trim().min(1).max(120);function Cc(){return{features:{appRuntime:!1,tty:!1,gui:!1,browser:!1,screenshots:!1,logs:!1,aiSessionWorkspaceSelection:!1,aiSessionPersistenceSettings:!1,gitCliCredentialBroker:!1,gitCredentialProxy:!1,aiSessionTimeline:{sessionReadAgents:[],turnReadAgents:[],liveItemAgents:[]},aiSessionConversationAttachments:{metadataAgents:[],contentAgents:[],uploadAgents:[],retentionSettings:!1,fileSizeLimitSettings:!1},aiSessionProviders:[]}}}const Tc=gs({sessionReadAgents:hs(kc).max(100).default([]),turnReadAgents:hs(kc).max(100).default([]),liveItemAgents:hs(kc).max(100).default([])}).passthrough(),$c=gs({metadataAgents:hs(kc).max(100).default([]),contentAgents:hs(kc).max(100).default([]),uploadAgents:hs(kc).max(100).default([]),retentionSettings:ls().default(!1),fileSizeLimitSettings:ls().default(!1)}).passthrough(),Nc=gs({appRuntime:ls().default(!1),tty:ls().default(!1),gui:ls().default(!1),browser:ls().default(!1),screenshots:ls().default(!1),logs:ls().default(!1),aiSessionWorkspaceSelection:ls().default(!1),aiSessionPersistenceSettings:ls().default(!1),gitCliCredentialBroker:ls().optional(),gitCredentialProxy:ls().optional(),aiSessionTimeline:Tc.default(function(){return{sessionReadAgents:[],turnReadAgents:[],liveItemAgents:[]}}),aiSessionConversationAttachments:$c.optional(),aiSessionProviders:Sc.optional()}).passthrough(),Rc=gs({features:Nc.default(function(){return{appRuntime:!1,tty:!1,gui:!1,browser:!1,screenshots:!1,logs:!1,aiSessionWorkspaceSelection:!1,aiSessionPersistenceSettings:!1,gitCliCredentialBroker:!1,gitCredentialProxy:!1,aiSessionTimeline:{sessionReadAgents:[],turnReadAgents:[],liveItemAgents:[]},aiSessionConversationAttachments:{metadataAgents:[],contentAgents:[],uploadAgents:[],retentionSettings:!1,fileSizeLimitSettings:!1},aiSessionProviders:[]}})}).passthrough();function Pc(e){const t={features:{appRuntime:!1,tty:!1,gui:!1,browser:!1,screenshots:!1,logs:!1,aiSessionWorkspaceSelection:!1,aiSessionPersistenceSettings:!1,gitCliCredentialBroker:!1,gitCredentialProxy:!1,aiSessionTimeline:{sessionReadAgents:[],turnReadAgents:[],liveItemAgents:[]},aiSessionConversationAttachments:{metadataAgents:[],contentAgents:[],uploadAgents:[],retentionSettings:!1,fileSizeLimitSettings:!1},aiSessionProviders:[]}};if(!e||"object"!=typeof e||Array.isArray(e))return t;const n=e,i=n.features;if(!i||"object"!=typeof i||Array.isArray(i))return t;const r=i,o={appRuntime:!1,tty:!1,gui:!1,browser:!1,screenshots:!1,logs:!1,aiSessionWorkspaceSelection:!1,aiSessionPersistenceSettings:!1,gitCliCredentialBroker:!1,gitCredentialProxy:!1,aiSessionTimeline:{sessionReadAgents:[],turnReadAgents:[],liveItemAgents:[]},aiSessionConversationAttachments:{metadataAgents:[],contentAgents:[],uploadAgents:[],retentionSettings:!1,fileSizeLimitSettings:!1},aiSessionProviders:[]};for(const e of["appRuntime","tty","gui","browser","screenshots","logs","aiSessionWorkspaceSelection","aiSessionPersistenceSettings","gitCliCredentialBroker","gitCredentialProxy"]){const t=ls().safeParse(r[e]);t.success&&(o[e]=t.data)}const s=Tc.safeParse(r.aiSessionTimeline);s.success&&(o.aiSessionTimeline=s.data);const a=$c.safeParse(r.aiSessionConversationAttachments);a.success&&(o.aiSessionConversationAttachments=a.data);const c=Sc.safeParse(r.aiSessionProviders);return c.success&&(o.aiSessionProviders=c.data),Rc.parse({...n,features:{...r,...o}})}function zc(e){return Pc(e).features.aiSessionConversationAttachments}function Lc(e){return Pc(e).features.aiSessionProviders}function jc(e,t){const n=zc(e);return"metadata"===t?n.metadataAgents:"content"===t?n.contentAgents:n.uploadAgents}function Dc(e){return Pc(e).features.aiSessionTimeline}function Mc(e,t){const n=Dc(e);return"session-read"===t?n.sessionReadAgents:"turn-read"===t?n.turnReadAgents:n.liveItemAgents}const Fc=jo().trim().min(1).max(120).regex(/^[a-zA-Z0-9][a-zA-Z0-9_.:-]*$/),Vc=jo().datetime(),Uc=xs(jo(),jo()).default({}),Hc=xs(jo(),jo()).default({}),Gc=gs({encoding:ws(["utf8","base64"]),data:jo()}).strict().superRefine((e,t)=>{"base64"===e.encoding&&Buffer.from(e.data,"base64").toString("base64")!==e.data&&t.addIssue({code:"custom",path:["data"],message:"Node tunnel binary body must use canonical base64 encoding."})}),Zc=/^[A-Za-z0-9_][A-Za-z0-9_.-]{0,127}$/,qc=/^sha256:([a-fA-F0-9]{64})$/,Bc=/^(?:localhost|[a-z0-9](?:[a-z0-9.-]*[a-z0-9])?)(?::[1-9][0-9]{0,4})?$/,Wc=/^[a-z0-9]+(?:(?:[._]|__|-+)[a-z0-9]+)*$/;function Jc(e){const t=e.trim();if(!t||t.length>512||t.includes("://")||/\s/.test(t))throw new Error("Docker image reference must not contain a URL scheme or whitespace.");const n=t.indexOf("@");if(-1!==n&&n!==t.lastIndexOf("@"))throw new Error("Docker image reference contains more than one digest separator.");const i=-1===n?void 0:t.slice(n+1),r=-1===n?t:t.slice(0,n),o=i?qc.exec(i):void 0;if(i&&!o)throw new Error("Docker image digest must use sha256 followed by 64 hexadecimal characters.");const s=r.lastIndexOf("/"),a=r.lastIndexOf(":"),c=a>s,l=c?r.slice(a+1):void 0,u=c?r.slice(0,a):r;if(l&&!Zc.test(l))throw new Error("Docker image tag is invalid.");if(!l&&!o)throw new Error("Docker image reference must include an explicit tag or sha256 digest.");const d=u.split("/");if(!d.length||d.some(e=>!e))throw new Error("Docker image repository path is invalid.");const p=d.length>1&&(d[0].includes(".")||d[0].includes(":")||"localhost"===d[0]),m=p?d.slice(1):d;if(p&&!Bc.test(d[0].toLowerCase()))throw new Error("Docker image registry host or port is invalid.");if(!m.length||m.some(e=>!Wc.test(e)))throw new Error("Docker image repository names must be lowercase and use valid separators.");const h=d.map((e,t)=>p&&0===t?e.toLowerCase():e).join("/"),f=o?`sha256:${o[1].toLowerCase()}`:void 0;return`${h}${l?`:${l}`:""}${f?`@${f}`:""}`}function Xc(e){const t=Jc(e),n=t.indexOf("@"),i=-1===n?void 0:t.slice(n+1),r=-1===n?t:t.slice(0,n),o=r.lastIndexOf("/"),s=r.lastIndexOf(":"),a=s>o;return{reference:t,repository:a?r.slice(0,s):r,tag:a?r.slice(s+1):void 0,digest:i}}const Yc=jo().trim().min(1).max(512).transform((e,t)=>{try{return Jc(e)}catch(e){return t.addIssue({code:"custom",message:e instanceof Error?e.message:String(e)}),qt}}),Kc=jo().trim().transform((e,t)=>{const n=qc.exec(e);return n?`sha256:${n[1].toLowerCase()}`:(t.addIssue({code:"custom",message:"Docker image digest must use sha256 followed by 64 hexadecimal characters."}),qt)}),Qc=gs({codexModelHash:Fc.nullable().optional(),claudeModelHash:Fc.nullable().optional(),opencodeModelHash:Fc.nullable().optional()}).strict().default({}),el=gs({imageId:Fc,tag:jo().trim().min(1).max(128).regex(Zc).optional()}).strict(),tl=bs("type",[gs({type:Os("image"),imageSelection:el}).strict(),gs({type:Os("template"),environmentTemplateId:Fc}).strict()]),nl=ws(["creating","ready","failed","deleting"]),il=ws(["linux","darwin","win32","freebsd","openbsd","aix","sunos","unknown"]),rl=ws(["x64","arm64","arm","ia32","ppc64","s390x","riscv64","unknown"]),ol=gs({code:jo().trim().min(1).max(120),message:jo().trim().min(1).max(2048),phase:ws(["validate","commit","inspect","security-check","persist","delete","recovery"]).optional()}).strict(),sl=gs({templateId:Fc,nodeId:Fc,imageId:Kc,name:jo().trim().min(1).max(160),platform:il,architecture:rl}).strict(),al=ws(["data","agent-home","workspace"]),cl=gs({deleteVolumes:ls()}).strict(),ll=gs({role:al,name:jo().trim().min(1).max(255),mountPath:jo().trim().startsWith("/").max(4096),status:ws(["deleted","retained","missing","failed"]),error:gs({code:jo().trim().min(1).max(120),message:jo().trim().min(1).max(2048)}).strict().optional()}).strict(),ul=gs({instanceId:Fc,containerDeleted:ls(),completed:ls(),deletedVolumes:hs(ll),retainedVolumes:hs(ll),volumeResults:hs(ll)}).strict(),dl={img_default:"market_taskhandoff_browser",img_codex:"market_taskhandoff_codex",img_ai:"market_taskhandoff_ai"};function pl(e,t){if(e&&"object"==typeof e&&!Array.isArray(e)){const t=e;return{imageId:"string"==typeof t.imageId&&dl[t.imageId]||t.imageId,..."string"==typeof t.tag?{tag:t.tag}:{}}}if("string"==typeof t)return{imageId:dl[t]||t}}const ml=gs({id:Fc,name:jo().trim().min(1).max(120),kind:ws(["tty","gui","web"]),source:ws(["builtin","custom"]),availability:ws(["available","missing-dependency"]),capabilities:gs({automation:ws(["cdp"]).optional(),supportsCwdSelection:ls().default(!1)}).strict().default({supportsCwdSelection:!1}),diagnosticCode:ws(["APP_EXECUTABLE_NOT_FOUND"]).optional()}).strict(),hl=gs({code:ws(["APP_CATALOG_INVALID"]),message:jo().trim().min(1).max(500)}).strict(),fl=gs({items:hs(ml).max(256),observedAt:Vc,issues:hs(hl).max(32).default([])}).strict(),gl=gs({id:Fc,name:jo().trim().min(1).max(160),sourceInstanceId:Fc,nodeId:Fc,imageId:Kc.optional(),internalTag:jo().trim().min(1).max(512).optional(),platform:il.optional(),architecture:rl.optional(),sizeBytes:os().int().nonnegative().optional(),status:nl,error:ol.optional(),createdAt:Vc,updatedAt:Vc}).strict().superRefine((e,t)=>{if("ready"===e.status)for(const n of["imageId","internalTag","platform","architecture","sizeBytes"])void 0===e[n]&&t.addIssue({code:"custom",path:[n],message:`Ready environment template requires ${n}.`});"failed"!==e.status||e.error||t.addIssue({code:"custom",path:["error"],message:"Failed environment template requires an error diagnostic."})}),yl=ws(["apt","dnf","brew","npm"]),vl=ws(["user","passwordless-sudo","root"]),_l=gs({platform:il,arch:rl,installers:hs(yl).max(8),privilege:vl,installerAccess:gs({npmGlobalWritable:ls().optional()}).strict().optional()}).strict(),bl=ws(["installed","not-installed","broken","unsupported"]),Al=ws(["recipe","bundled","external","none"]),Il=gs({code:ws(["BUNDLED","EXTERNALLY_MANAGED","ALREADY_INSTALLED","NOT_INSTALLED","UNSUPPORTED_PLATFORM","INSTALLER_UNAVAILABLE","INSTALLER_NOT_WRITABLE","INSUFFICIENT_PRIVILEGE","OPERATION_IN_PROGRESS"]),message:jo().trim().min(1).max(500)}).strict(),xl=gs({id:Fc,name:jo().trim().min(1).max(120),kind:ws(["tty","gui","web"]),description:jo().trim().max(500).optional(),state:bl,managementSource:Al,version:jo().trim().max(120).optional(),canInstall:ls(),canUninstall:ls(),installReason:Il.optional(),uninstallReason:Il.optional(),activeJobId:Fc.optional()}).strict(),Sl=ws(["install","uninstall"]),wl=ws(["queued","running","succeeded","failed","cancelled","interrupted"]),El=gs({current:os().finite().nonnegative().optional(),total:os().finite().positive().optional(),unit:jo().trim().min(1).max(40).optional()}).strict().refine(e=>void 0===e.total||void 0===e.current||e.current<=e.total,{message:"Progress current must not exceed total.",path:["current"]}),Ol=gs({executable:jo().trim().min(1).max(4096),args:hs(jo().max(4096)).max(128)}).strict(),kl=gs({code:jo().trim().min(1).max(120).regex(/^[a-z0-9][a-z0-9._-]*$/),message:jo().trim().min(1).max(4096),retryable:ls(),sessionIds:hs(Fc).max(64).optional()}).strict(),Cl=gs({id:Fc,requestId:Fc.optional(),appId:Fc,operation:Sl,state:wl,phase:jo().trim().min(1).max(120).optional(),progress:El.optional(),command:Ol.optional(),logTail:jo().max(32768).optional(),logTruncated:ls().optional(),error:kl.optional(),requestedAt:Vc,startedAt:Vc.optional(),finishedAt:Vc.optional(),updatedAt:Vc}).strict(),Tl=gs({streamId:Fc,sequence:os().int().nonnegative(),capabilities:_l,apps:hs(xl).max(256),activeJobs:hs(Cl).max(256),recentJobs:hs(Cl).max(256),observedAt:Vc}).strict(),$l=gs({requestId:Fc.optional()}).strict(),Nl=gs({job:Cl}).strict(),Rl=gs({type:Os("app-management"),streamId:Fc,sequence:os().int().nonnegative(),observedAt:Vc,job:Cl.optional(),snapshot:Tl.optional()}).strict().refine(e=>void 0!==e.job||void 0!==e.snapshot,{message:"An app management event requires a job or snapshot."}),Pl=gs({component:ws(["control-plane","node-agent","controlled-instance"]),packageName:jo().trim().max(160).optional(),packageVersion:jo().trim().max(80).optional(),protocolVersion:Oc.optional(),buildId:jo().trim().max(160).optional(),builtAt:jo().trim().max(120).optional(),gitCommit:jo().trim().max(120).optional(),imageRef:jo().trim().max(512).optional(),imageDigest:jo().trim().max(240).optional()}).strict(),zl=gs({data:gs({ok:Os(!0),role:Os("control-plane"),protocolVersion:Oc,build:Pl.extend({component:Os("control-plane"),packageVersion:jo().trim().min(1).max(80)}).loose(),serverTime:Vc}).loose()}).loose(),Ll=ws(["stable","beta","alpha"]),jl=gs({packageName:Os("@task-handoff/controlled-instance"),version:jo().trim().min(1).max(80),platform:jo().trim().min(1).max(40),arch:jo().trim().min(1).max(40),formatVersion:os().int().positive(),launcherAbi:os().int().positive(),entrypoint:jo().trim().min(1).max(512),sha256:jo().regex(/^[a-f0-9]{64}$/)}).strict(),Dl=gs({code:ws(["INSTANCE_RUNTIME_VERSION_MISMATCH","INSTANCE_RUNTIME_ARTIFACT_UNAVAILABLE","INSTANCE_RUNTIME_ARTIFACT_INVALID","INSTANCE_RUNTIME_INSTALL_FAILED","INSTANCE_RUNTIME_RESTART_FAILED","INSTANCE_RUNTIME_VERIFICATION_FAILED","INSTANCE_BASE_RUNTIME_INCOMPATIBLE","NODE_UPDATE_PREFLIGHT_FAILED","NODE_UPDATE_FAILED","LEGACY_INSTANCE_UPDATE_RETIRED"]),message:jo().trim().min(1).max(4096),expectedVersion:jo().trim().min(1).max(80).optional(),actualVersion:jo().trim().min(1).max(80).optional(),retryable:ls().default(!1)}).strict(),Ml=gs({desiredVersion:jo().trim().min(1).max(80),actualVersion:jo().trim().min(1).max(80).optional(),phase:ws(["pending","draining","installing","restarting","verifying","matched","failed"]),attempt:os().int().nonnegative().default(0),lastAttemptAt:Vc.optional(),matchedAt:Vc.optional(),error:Dl.optional()}).strict(),Fl=gs({runningInstanceCount:os().int().nonnegative(),stoppedInstanceCount:os().int().nonnegative(),activeInstanceCount:os().int().nonnegative(),restartInstanceCount:os().int().nonnegative(),runningInstanceIds:hs(Fc).max(1024).default([]),stoppedInstanceIds:hs(Fc).max(1024).default([]),activeInstanceIds:hs(Fc).max(1024).default([])}).strict(),Vl=gs({phase:ws(["queued","updating-node","restarting-node","converging-instances","succeeded","degraded","failed"]),desiredVersion:jo().trim().min(1).max(80),nodeVersion:jo().trim().min(1).max(80).optional(),expectedInstanceIds:hs(Fc).max(1024).default([]),expectedInstanceCount:os().int().nonnegative(),matchedInstanceCount:os().int().nonnegative(),pendingInstanceCount:os().int().nonnegative(),failedInstanceCount:os().int().nonnegative(),deferredInstanceCount:os().int().nonnegative().default(0)}).strict(),Ul=gs({channel:Ll.default("stable")}).strict(),Hl=gs({source:Os("npm"),channel:Ll,currentVersion:jo().trim().max(240).optional(),availableVersion:jo().trim().min(1).max(240),artifactRef:jo().trim().min(1).max(512).optional(),runtimeArtifacts:hs(jl).default([]),impact:Fl,updateAvailable:ls(),supported:ls().default(!0),reason:jo().trim().max(2048).optional(),checkedAt:Vc,preflightToken:jo().trim().min(16).max(240).optional()}).strict(),Gl=gs({id:Fc,nodeId:Fc,source:Os("npm"),channel:Ll,fromVersion:jo().trim().max(240).optional(),toVersion:jo().trim().min(1).max(240),artifactRef:jo().trim().min(1).max(512).optional(),runtimeArtifacts:hs(jl).default([]),impact:Fl,rollout:Vl,status:ws(["queued","updating-node","restarting-node","converging-instances","succeeded","degraded","failed"]),error:Dl.optional(),startedAt:Vc.optional(),completedAt:Vc.optional(),createdAt:Vc,updatedAt:Vc}).strict(),Zl=gs({channel:Ll,targetVersion:jo().trim().min(1).max(240),preflightToken:jo().trim().min(16).max(240)}).strict(),ql=bs("type",[gs({type:ws(["branch","tag"]),name:jo().trim().min(1).max(240)}).strict(),gs({type:Os("commit"),commit:jo().trim().regex(/^[0-9a-fA-F]{4,64}$/,"commit must be a hexadecimal Git object id")}).strict()]),Bl=gs({type:ws(["none","ssh-key","https-token"]).default("none"),secretId:jo().trim().min(1).max(120).optional()}).strict(),Wl=gs({depth:os().int().positive().max(1e5).optional(),submodules:ls().default(!1),lfs:ls().default(!1),subdirectory:jo().trim().max(240).refine(e=>!e.startsWith("/")&&!e.split("/").some(e=>".."===e),"subdirectory must be a relative path within the repository").transform(e=>e.split("/").filter(e=>e&&"."!==e).join("/")).default("")}).strict(),Jl=gs({id:Fc,name:jo().trim().min(1).max(160),url:jo().trim().min(1).max(2048),provider:jo().trim().max(80).optional(),ref:ql.default({type:"branch",name:"main"}),auth:Bl.default({type:"none"}),clone:Wl.default({submodules:!1,lfs:!1,subdirectory:""}),defaultImageSelection:el.optional(),labels:Uc,createdAt:Vc,updatedAt:Vc}).strict(),Xl=gs({id:Fc,nodeId:Fc,name:jo().trim().min(1).max(160),path:jo().trim().min(1).max(4096),defaultImageSelection:el.optional(),labels:Uc,createdAt:Vc,updatedAt:Vc}).strict(),Yl=bs("type",[gs({type:Os("git-repository"),repositoryId:Fc.optional(),url:jo().trim().min(1).max(2048),provider:jo().trim().max(80).optional(),ref:ql.default({type:"branch",name:"main"}),auth:Bl.default({type:"none"}),clone:Wl.default({submodules:!1,lfs:!1,subdirectory:""})}).strict(),gs({type:Os("git-template"),url:jo().trim().min(1).max(2048),templateId:jo().trim().min(1).max(120).optional(),ref:ql.default({type:"branch",name:"main"}),auth:Bl.default({type:"none"}),clone:Wl.default({submodules:!1,lfs:!1,subdirectory:""})}).strict(),gs({type:Os("local-folder"),localFolderId:Fc.optional(),path:jo().trim().min(1).max(4096),ownerNodeId:Fc.optional()}).strict()]);function Kl(e){const t=Yl.parse(e);return"local-folder"===t.type?t:Yl.parse({...t,auth:{type:"none"}})}const Ql=Kl,eu=gs({mode:ws(["local-bind","git-clone","empty-volume","persistent-volume"]),path:jo().trim().min(1).max(4096).default("/workspace"),volumeName:jo().trim().max(240).optional(),readOnly:ls().default(!1)}).strict(),tu=ws(["codex","claude","opencode"]),nu=gs({id:Fc,name:jo().trim().min(1).max(160),source:Yl,defaultImageSelection:el.optional(),defaultNodeId:Fc.optional(),workspacePolicy:eu,labels:Uc,createdAt:Vc,updatedAt:Vc}).strict(),iu=gs({id:Fc,name:jo().trim().min(1).max(160),endpoint:jo().trim().min(1).max(2048),key:jo().trim().min(1).max(4096),model:jo().trim().min(1).max(240),app:tu,enabled:ls().default(!0),order:os().int().min(0).max(1e6).default(0),labels:Uc,createdAt:Vc,updatedAt:Vc}).strict(),ru=iu,ou=iu.omit({key:!0}).extend({keyPreview:jo().trim().min(1).max(160),keySet:ls()}).strict(),su=ou.extend({referenceCount:os().int().min(0)}).strict(),au=gs({instanceId:Fc,codexModelHash:Fc.optional(),claudeModelHash:Fc.optional(),opencodeModelHash:Fc.optional(),updatedAt:Vc}).strict(),cu=bs("type",[gs({type:Os("control-plane"),name:iu.shape.name,enabled:iu.shape.enabled,order:iu.shape.order}).strict(),gs({type:Os("node"),nodeId:Fc,name:iu.shape.name,enabled:iu.shape.enabled,order:iu.shape.order,referenceCount:os().int().min(0)}).strict()]),lu=gs({id:Fc,model:ou,locations:hs(cu).min(1),referenceCount:os().int().min(0).default(0)}).strict(),uu=gs({nodeId:Fc,code:jo().trim().min(1).max(120),message:jo().trim().min(1).max(2e3)}).strict(),du=gs({models:hs(lu),nodeDiagnostics:hs(uu).default([]),updatedAt:Vc}).strict(),pu=iu.omit({id:!0,createdAt:!0,updatedAt:!0}).strict(),mu=pu.partial().strict(),hu=iu,fu=gs({modelSelection:Qc,codexModelHash:Fc.optional(),claudeModelHash:Fc.optional(),opencodeModelHash:Fc.optional()}).strict(),gu=ws(["market","custom"]),yu=ws(["active","deprecated","yanked"]),vu=bs("kind",[gs({kind:Os("builtin"),key:jo().trim().min(1).max(120)}).strict(),gs({kind:Os("remote"),url:jo().trim().url().max(2048),mediaType:ws(["image/png","image/jpeg","image/webp"]).optional(),digest:Kc.optional()}).strict()]),_u=hs(jo().trim().min(1).max(80)).default([]),bu=hs(jo().trim().min(1).max(120)).default([]),Au=xs(jo().trim().min(2).max(35),jo().trim().min(1).max(4096)),Iu=gs({os:jo().trim().min(1).max(40),architecture:jo().trim().min(1).max(40),digest:Kc.optional(),downloadSizeBytes:os().int().positive().optional(),unpackedSizeBytes:os().int().positive().optional()}).strict(),xu=gs({name:jo().trim().min(1).max(128).regex(Zc),version:jo().trim().min(1).max(160).optional(),reference:Yc,manifestDigest:Kc.optional(),publishedAt:Vc.optional(),platforms:hs(Iu).default([]),status:yu.default("active")}).strict(),Su=gs({id:Fc,publisher:jo().trim().min(1).max(160),slug:jo().trim().min(1).max(160),name:jo().trim().min(1).max(160),description:jo().trim().min(1).max(4096),localizedDescriptions:Au.optional(),cover:vu.optional(),repository:jo().trim().min(1).max(512),defaultTag:jo().trim().min(1).max(128).regex(Zc),tags:hs(xu).min(1),capabilities:_u,optionalApps:bu,defaultEnv:Hc,labels:Uc,status:yu.default("active")}).strict().superRefine((e,t)=>{e.tags.some(t=>t.name===e.defaultTag)||t.addIssue({code:"custom",path:["defaultTag"],message:"Market defaultTag must identify one of the image tags."})}),wu=gs({protocolVersion:Oc,catalogId:Fc,revision:jo().trim().min(1).max(240),source:ws(["embedded","remote","cache"]),generatedAt:Vc,expiresAt:Vc.optional(),items:hs(Su)}).strict(),Eu=gs({source:ws(["embedded","remote","cache"]),state:ws(["ready","refreshing","stale","failed"]),revision:jo().trim().min(1).max(240),updatedAt:Vc,error:jo().trim().max(4096).optional()}).strict(),Ou=gs({id:Fc,origin:Os("custom"),name:jo().trim().min(1).max(160),description:jo().trim().max(4096).optional(),localizedDescriptions:Au.optional(),cover:vu.optional(),reference:Yc,repository:jo().trim().min(1).max(512),tag:jo().trim().min(1).max(128).regex(Zc).optional(),pullPolicy:Os("if-not-present").default("if-not-present"),capabilities:_u,optionalApps:bu,defaultEnv:Hc,labels:Uc,createdAt:Vc,updatedAt:Vc}).strict(),ku=Ou,Cu=gs({name:jo().trim().min(1).max(128).regex(Zc),version:jo().trim().min(1).max(160).optional(),reference:Yc,manifestDigest:Kc.optional(),status:yu}).strict(),Tu=gs({id:Fc,origin:gu,name:jo().trim().min(1).max(160),description:jo().trim().max(4096).optional(),localizedDescriptions:Au.optional(),cover:vu,repository:jo().trim().min(1).max(512),tag:jo().trim().min(1).max(128).regex(Zc).optional(),availableTags:hs(Cu),reference:Yc,digest:Kc.optional(),downloadSizeBytes:os().int().positive().optional(),unpackedSizeBytes:os().int().positive().optional(),capabilities:_u,optionalApps:bu,defaultEnv:Hc,labels:Uc,readOnly:ls(),lifecycleStatus:yu.optional(),market:gs({catalogId:Fc,catalogRevision:jo().trim().min(1).max(240),publisher:jo().trim().min(1).max(160),version:jo().trim().min(1).max(160).optional()}).strict().optional()}).strict(),$u=gs({id:Fc,origin:gu,name:jo().trim().min(1).max(160),description:jo().trim().max(4096).optional(),localizedDescriptions:Au.optional(),cover:vu.optional(),repository:jo().trim().min(1).max(512),tag:jo().trim().min(1).max(128).regex(Zc).optional(),requestedReference:Yc,resolvedDigest:Kc.optional(),resolvedReference:Yc.optional(),downloadSizeBytes:os().int().positive().optional(),pullPolicy:Os("if-not-present").default("if-not-present"),capabilities:_u,optionalApps:bu,defaultEnv:Hc,labels:Uc,market:gs({catalogId:Fc,catalogRevision:jo().trim().min(1).max(240),publisher:jo().trim().min(1).max(160),version:jo().trim().min(1).max(160).optional()}).strict().optional(),createdAt:Vc,updatedAt:Vc}).strict(),Nu=gs({phase:ws(["checking-image","pulling-image","resolving-image","ready","failed"]),requestedReference:Yc,generation:os().int().nonnegative().default(0),error:jo().trim().max(4096).optional(),startedAt:Vc,updatedAt:Vc}).strict(),Ru=gs({instanceId:Fc,generation:os().int().nonnegative(),requestedReference:Yc,sequence:os().int().nonnegative(),observedAt:Vc}).strict(),Pu=Ru.extend({data:jo().min(1).max(65536),replay:ls().optional()}).strict(),zu=Ru.extend({outcome:ws(["succeeded","failed"])}).strict(),Lu=Ru.extend({status:ws(["connecting","pulling","extracting","complete","failed"]),layers:gs({total:os().int().nonnegative(),completed:os().int().nonnegative(),downloaded:os().int().nonnegative(),downloading:os().int().nonnegative(),extracting:os().int().nonnegative()}).strict(),bytes:gs({current:os().finite().nonnegative(),total:os().finite().positive()}).strict().optional(),percent:os().finite().min(0).max(100).optional(),message:jo().trim().min(1).max(500),terminalTail:jo().max(262144).optional(),terminalTruncated:ls().optional()}).strict();function ju(e,t){if(!e||"object"!=typeof e||Array.isArray(e))return e;const n=e,i=new Set(["id","origin","name","description","localizedDescriptions","cover","reference","repository","tag","image","registry","pullPolicy","capabilities","optionalApps","defaultEnv","labels","createdAt","updatedAt"]);for(const e of Object.keys(n))i.has(e)||t?.({imageId:"string"==typeof n.id?n.id:void 0,field:e});const r="string"==typeof n.id?n.id:void 0,o="string"==typeof n.image?n.image:void 0;void 0!==o&&t?.({imageId:r,field:"image"}),Object.prototype.hasOwnProperty.call(n,"registry")&&t?.({imageId:r,field:"registry"});let s,a="string"==typeof n.reference?n.reference:o;if(a)try{a=Jc(a)}catch{if(!a.includes("@")&&a.lastIndexOf(":")<=a.lastIndexOf("/"))try{a=Jc(`${a}:latest`),t?.({imageId:r,field:"reference:implicit-latest"})}catch{}}try{s=a?Xc(a):void 0}catch{}return{id:n.id,origin:"custom",name:n.name,description:n.description,localizedDescriptions:n.localizedDescriptions,cover:wd(n.cover,["kind","key","url","mediaType","digest"]),reference:s?.reference??a,repository:s?.repository??n.repository,tag:s?.tag??n.tag,pullPolicy:n.pullPolicy??"if-not-present",capabilities:n.capabilities,optionalApps:n.optionalApps,defaultEnv:n.defaultEnv,labels:n.labels,createdAt:n.createdAt,updatedAt:n.updatedAt}}const Du=bs("kind",[gs({kind:Os("direct")}).strict(),gs({kind:Os("control-plane-proxy"),proxyId:Fc,proxyBindingId:Fc,targetNodeId:Fc}).strict()]),Mu=gs({pingRttMs:os().nonnegative().optional(),pingRttP95Ms:os().nonnegative().optional(),consecutiveReconnects:os().int().nonnegative(),nextRetryAt:Vc.optional()}).strict(),Fu=gs({nodeId:Fc,inviteId:Fc.optional()}).strict(),Vu=bs("status",[gs({id:Fc,status:Os("pending")}).strict(),gs({id:Fc,status:Os("completed"),nodeId:Fc}).strict()]),Uu=gs({reachability:ws(["unknown","reachable","unreachable"]),bindingStatus:ws(["unknown","active","revoked"]),bindingRevision:os().int().positive().optional(),streamId:jo().trim().min(1).max(160).optional(),revision:os().int().nonnegative().optional(),observedAt:Vc.optional(),target:Ac.optional(),lastError:vc.optional(),updatedAt:Vc}).strict(),Hu=gs({id:Fc,name:jo().trim().min(1).max(160),connectionMode:ws(["local-ipc","local-loopback","direct-http","reverse-wss","control-plane-proxy"]).default("direct-http"),connectionPath:Du.default({kind:"direct"}),connectionEnabled:ls().default(!0),auth:gs({mode:ws(["local-static-key","paired-hmac","proxy-binding"]).default("local-static-key"),keyId:Fc.optional(),secret:jo().trim().max(4096).optional(),pairedAt:Vc.optional(),pairing:gs({status:ws(["pending","paired","expired"]).default("pending"),joinToken:jo().trim().max(4096).optional(),expiresAt:Vc.optional()}).strict().optional()}).strict().default({mode:"local-static-key"}),endpoint:jo().trim().max(2048).optional(),controlEndpoint:jo().trim().max(2048).optional(),containerEndpoint:jo().trim().max(2048).optional(),publicWebBase:jo().trim().max(2048).optional(),status:ws(["unknown","online","offline","degraded"]).default("unknown"),health:ws(["unknown","ok","degraded","failed"]).default("unknown"),capabilities:xs(jo(),ds()).default({}),proxyState:Uu.optional(),appInventory:fl.optional(),labels:Uc,lastSeenAt:Vc.optional(),createdAt:Vc,updatedAt:Vc}).strict().superRefine((e,t)=>{"control-plane-proxy"===e.connectionPath.kind&&"control-plane-proxy"!==e.connectionMode&&t.addIssue({code:"custom",path:["connectionPath"],message:"Control-plane proxy paths require control-plane-proxy connection mode."}),"control-plane-proxy"===e.connectionMode&&"control-plane-proxy"!==e.connectionPath.kind&&t.addIssue({code:"custom",path:["connectionPath"],message:"Control-plane proxy nodes require a control-plane-proxy connection path."})}),Gu=gs({nodeId:Fc,status:ws(["unknown","online","offline","degraded"]),health:ws(["unknown","ok","degraded","failed"]),lastSeenAt:Vc.nullable(),connectionPhase:ws(["connecting","handshaking","healthy","reconnecting","suspect","offline"]).nullable(),connectionDiagnostics:Mu.nullable(),proxyState:Uu.nullable()}).strict(),Zu=gs({id:Fc,nodeId:Fc,name:jo().trim().min(1).max(160),type:ws(["docker","kubernetes","local"]),status:ws(["unknown","online","offline","degraded"]).default("unknown"),accessStrategy:ws(["node-proxy","direct-port","kubernetes-ingress","kubernetes-port-forward"]).default("node-proxy"),capabilities:xs(jo(),ds()).default({}),labels:Uc,createdAt:Vc,updatedAt:Vc}).strict(),qu=gs({instanceId:Fc,runtimeKind:Os("docker"),state:ws(["pending","available","stopped","unavailable"]),sampledAt:Vc,cpu:gs({usagePercent:os().nonnegative()}).strict().optional(),memory:gs({usageBytes:os().nonnegative(),limitBytes:os().nonnegative().optional(),usagePercent:os().nonnegative().optional()}).strict().optional(),network:gs({rxBytes:os().nonnegative(),txBytes:os().nonnegative()}).strict().optional(),blockIo:gs({readBytes:os().nonnegative(),writeBytes:os().nonnegative()}).strict().optional(),pids:os().int().nonnegative().optional(),error:jo().trim().max(2048).optional()}).strict(),Bu=gs({registry:ls().default(!1),runtimeBroker:ls().default(!1),workspaceProvisioning:gs({docker:ls().default(!1),kubernetes:ls().default(!1),local:ls().default(!1)}).strip().default({docker:!1,kubernetes:!1,local:!1})}).strip(),Wu=gs({modelEndpointProbe:ls().optional(),aiSessionHistoryLimit:ls().optional(),aiSessionAttachmentRetention:ls().optional(),aiSessionFileAttachmentLimit:ls().optional(),folderPlaces:ls().optional(),localFolderNameUpdate:ls().optional(),managedGitCredentials:Bu.optional()}).strip();function Ju(e){const t=Wu.safeParse(e),n=t.success?t.data:{};return{...n,managedGitCredentials:Bu.parse(n.managedGitCredentials||{})}}const Xu=gs({status:ws(["healthy","congested","recovering"]),activeOutputs:os().int().nonnegative(),bufferedBytes:os().int().nonnegative(),peakBufferedBytes:os().int().nonnegative(),coalescedEvents:os().int().nonnegative(),oversizedEvents:os().int().nonnegative().optional(),peakEventBytes:os().int().nonnegative().optional(),congestedSince:Vc.optional(),lastCongestedAt:Vc.optional()}).strip(),Yu=gs({ok:ls().optional(),role:jo().optional(),nodeId:Fc.optional(),platform:il.optional(),arch:rl.optional(),protocolVersion:Oc.optional(),capabilities:Wu.optional(),build:Pl.strip().optional(),process:gs({pid:os().int().positive(),startIdentity:jo().trim().min(1).optional()}).strip().optional(),listener:gs({host:jo().trim().min(1),port:os().int().min(1).max(65535)}).strip().optional(),instanceProxy:gs({requests:os().int().nonnegative(),active:os().int().nonnegative(),completed:os().int().nonnegative(),aborted:os().int().nonnegative(),limitRejected:os().int().nonnegative(),responseBytes:os().nonnegative(),totalDurationMs:os().nonnegative(),maxResponseBytes:os().int().nonnegative()}).partial().strip().optional(),eventTransport:Xu.optional(),serverTime:Vc.optional()}).strip(),Ku=gs({bindScope:ws(["loopback","all-ipv4"]),port:os().int().min(1).max(65535)}).strict(),Qu=Ku.extend({host:ws(["127.0.0.1","0.0.0.0"]),status:ws(["listening","error"]),source:ws(["bootstrap","persisted"]),error:jo().trim().max(2048).optional()}).strict(),ed=Ku,td=gs({nodeId:Fc,joinToken:jo().trim().min(1),expiresAt:Vc}).passthrough(),nd=gs({nodeId:Fc,keyId:Fc,secret:jo().regex(/^[A-Za-z0-9_-]{32,128}$/),pairedAt:Vc}).strict(),id=gs({id:Fc,keyId:Fc,name:jo().trim().min(1).max(160).optional(),pairedAt:Vc,updatedAt:Vc,current:ls()}).passthrough(),rd=gs({keyId:Fc,revoked:Os(!0),revokedAt:Vc}).strict(),od=gs({id:Fc,pairingKeyId:Fc,url:jo().trim().min(1).max(2048),name:jo().trim().min(1).max(160).optional(),enabled:ls(),createdAt:Vc,updatedAt:Vc,status:ws(["disabled","connecting","connected","reconnecting","failed"]),pingRttMs:os().nonnegative().optional(),pingRttP95Ms:os().nonnegative().optional(),consecutiveReconnects:os().int().nonnegative().optional(),nextRetryAt:Vc.optional(),lastConnectedAt:Vc.optional(),lastDisconnectedAt:Vc.optional(),error:jo().optional()}).passthrough(),sd=gs({pairing:id,connection:gs({id:Fc,pairingKeyId:Fc,url:jo().trim().min(1).max(2048),name:jo().trim().min(1).max(160).optional(),enabled:ls(),createdAt:Vc,updatedAt:Vc}).passthrough(),tunnel:gs({status:ws(["disabled","saved","connecting","connected","failed"]),error:jo().trim().max(2048).optional()}).passthrough()}).passthrough(),ad=gs({deleted:ls().optional()}).passthrough(),cd=gs({repository:jo().trim().optional(),tag:jo().trim().optional(),id:jo().trim(),createdSince:jo().trim().optional(),size:jo().trim().optional(),sizeBytes:os().int().nonnegative().optional(),reference:jo().trim().min(1),repoDigests:hs(jo().trim().min(1).max(512)).default([])}).passthrough(),ld=gs({image:Tu,status:ws(["available","pull-required","unknown"]),localImage:cd.optional(),localSizeBytes:os().int().nonnegative().optional(),downloadSizeBytes:os().int().positive().optional(),unpackedSizeBytes:os().int().positive().optional(),error:jo().trim().max(2048).optional()}).strict(),ud=new Hs({type:"lazy",getter:()=>gs({name:jo().trim().min(1),path:jo().trim().min(1).max(4096),children:hs(ud)}).passthrough()}),dd=gs({kind:ws(["home","root"]),name:jo().trim().min(1),path:jo().trim().min(1).max(4096)}).passthrough(),pd=gs({status:os().int().min(100).max(599).optional(),headers:xs(jo(),jo()).optional(),bodyBase64:jo().optional()}).passthrough(),md=gs({strategy:ws(["node-proxy","direct-port","kubernetes-ingress","kubernetes-port-forward"]).default("node-proxy"),web:jo().trim().max(2048).optional(),api:jo().trim().max(2048).optional(),vnc:jo().trim().max(2048).optional(),tty:jo().trim().max(2048).optional(),logs:jo().trim().max(2048).optional(),status:ws(["unknown","reachable","endpoint-unreachable"]).default("unknown")}).strict(),hd=gs({...md.shape}).strict(),fd=gs({strategy:ws(["control-plane-proxy","direct-port","node-proxy","kubernetes-ingress","kubernetes-port-forward"]).default("control-plane-proxy"),web:jo().trim().max(2048).optional(),api:jo().trim().max(2048).optional(),ws:jo().trim().max(2048).optional(),status:ws(["unknown","reachable","endpoint-unreachable"]).default("unknown")}).strict().default({strategy:"control-plane-proxy",status:"unknown"}),gd=gs({mode:ws(["local-bind","git-clone","empty-volume","persistent-volume"]).optional(),status:ws(["unknown","pending","ready","failed"]).default("unknown"),path:jo().trim().max(4096).optional(),resolvedCommit:jo().trim().max(120).optional(),error:jo().trim().max(2048).optional()}).passthrough(),yd=gs({id:Fc,name:jo().trim().min(1).max(160),projectId:Fc.optional(),source:Yl,sourceSnapshot:xs(jo(),ds()).default({}),modelSelection:Qc,nodeId:Fc,runtimeId:Fc,imageSelection:el.optional(),environmentSource:tl.optional(),environmentTemplateOrigin:sl.optional(),imageSnapshot:$u.optional(),imageProvisioning:Nu.optional(),stateRevision:os().int().min(0).default(0),processIncarnationId:jo().trim().min(1).max(120).optional(),status:ws(["created","provisioning","starting","registering","registered","running","stopping","stopped","deleting","failed","unhealthy"]).default("created"),health:ws(["unknown","ok","degraded","failed"]).default("unknown"),connectionStatus:ws(["unknown","online","offline","endpoint-unreachable"]).default("unknown"),agentStatus:ws(["unknown","online","offline"]).default("unknown"),targetStatus:ws(["unknown","reachable","endpoint-unreachable"]).default("unknown"),uiAccessStatus:ws(["unknown","reachable","endpoint-unreachable"]).default("unknown"),controlMode:ws(["standalone","controlled"]).default("controlled"),protocolVersion:Oc.optional(),instanceVersion:jo().trim().max(80).optional(),build:Pl.optional(),runtimeVersion:Ml.optional(),ready:ls().default(!1),capabilities:Rc.default(Cc),appInventory:fl.optional(),config:gs({autoImportAgentConfigs:ls().default(!0),defaultCodexPermissionMode:xa.default("ask"),aiSessionHistoryLimit:os().int().min(1).max(500).default(50),aiSessionAttachmentRetentionDays:os().int().min(0).max(365).default(30),aiSessionMaxFileAttachmentBytes:os().int().positive().max(Xs).default(Js)}).strict().default({autoImportAgentConfigs:!0,defaultCodexPermissionMode:"ask",aiSessionHistoryLimit:50,aiSessionAttachmentRetentionDays:30,aiSessionMaxFileAttachmentBytes:Js}),workspace:gd.default({status:"unknown"}),target:md.default({strategy:"direct-port",status:"unknown"}),access:fd,apps:gs({runningCount:os().int().min(0).default(0),problemCount:os().int().min(0).default(0),updatedAt:Vc.optional(),revision:os().int().min(0).optional()}).strict().default({runningCount:0,problemCount:0}),aiSessions:Wa.default(()=>({runningCount:0,waitingCount:0,staleCount:0,sessions:[],updatedAt:(new Date).toISOString()})),triggers:gs({enabledCount:os().int().min(0).default(0),runningCount:os().int().min(0).default(0),errorCount:os().int().min(0).default(0),configs:hs(gs({configHash:jo().trim().min(1),config:oc,deployments:hs(ac).default([]),runtime:hs(cc).default([])}).strict()).default([]),recentRuns:hs(lc).default([])}).strict().optional(),runtime:gs({kind:jo().trim().max(80).optional(),containerName:jo().trim().max(240).optional(),containerId:jo().trim().max(240).optional(),workspacePath:jo().trim().max(4096).optional(),pid:os().int().positive().optional(),port:os().int().positive().max(65535).optional(),labels:xs(jo(),jo()).default({})}).strict().default({labels:{}}),registrationToken:jo().trim().min(1).max(240).optional(),lastHeartbeatAt:Vc.optional(),createdAt:Vc,updatedAt:Vc}).strict(),vd=(_d=vs([yd.transform(e=>({instance:e,gitWorkspaceProvisioningOperationId:void 0})),gs({instance:yd,gitWorkspaceProvisioningOperationId:Fc.optional()}).strict()]),new Vs({type:"pipe",in:Cs(e=>{if(!e||"object"!=typeof e||Array.isArray(e))return e;const t=e;return t.instance&&"object"==typeof t.instance&&!Array.isArray(t.instance)?{instance:Ad(t.instance),..."string"==typeof t.gitWorkspaceProvisioningOperationId?{gitWorkspaceProvisioningOperationId:t.gitWorkspaceProvisioningOperationId}:{}}:Ad(t)}),out:_d}));var _d;const bd=gs({instanceId:yd.shape.id,revision:os().int().min(0),updatedAt:Vc,status:yd.shape.status.unwrap(),health:yd.shape.health.unwrap(),connectionStatus:yd.shape.connectionStatus.unwrap(),accessStatus:ws(["reachable","endpoint-unreachable"]),imageProvisioning:Nu.optional(),workspace:gd,runtime:yd.shape.runtime.unwrap(),runtimeVersion:Ml.optional(),ready:ls(),lastHeartbeatAt:Vc.optional()}).strict();function Ad(e,t){if(!e||"object"!=typeof e||Array.isArray(e))return e;const n=e,i=new Set(Object.keys(yd.shape)),r={};for(const[e,o]of Object.entries(n))i.has(e)?r[e]=o:t?.({instanceId:"string"==typeof n.id?n.id:void 0,field:e});if(n.capabilities&&"object"==typeof n.capabilities&&!Array.isArray(n.capabilities)){const e={...n.capabilities};Object.prototype.hasOwnProperty.call(e,"apps")&&(t?.({instanceId:"string"==typeof n.id?n.id:void 0,field:"capabilities.apps"}),delete e.apps),r.capabilities=Pc(e)}else r.capabilities=Pc(void 0);r.appInventory=function(e,t,n){if(!e||"object"!=typeof e||Array.isArray(e))return;const i=e;Object.keys(i).some(e=>!["observedAt","items","issues"].includes(e))&&t?.({instanceId:n,field:"appInventory"});const r={observedAt:i.observedAt,items:Array.isArray(i.items)?i.items.map(e=>{e&&"object"==typeof e&&!Array.isArray(e)&&Object.keys(e).some(e=>!["id","name","kind","source","availability","capabilities","diagnosticCode"].includes(e))&&t?.({instanceId:n,field:"appInventory.items"});const i=wd(e,["id","name","kind","source","availability","diagnosticCode"]);return!i||"object"!=typeof i||Array.isArray(i)?i:{...i,capabilities:wd(e.capabilities,["automation","supportsCwdSelection"])}}):i.items,issues:Array.isArray(i.issues)?i.issues.map(e=>wd(e,["code","message"])):i.issues},o=fl.safeParse(r);return o.success?o.data:void 0}(n.appInventory,t,"string"==typeof n.id?n.id:void 0),r.source=Sd(n.source,t,"string"==typeof n.id?n.id:void 0),r.sourceSnapshot=n.sourceSnapshot&&"object"==typeof n.sourceSnapshot&&!Array.isArray(n.sourceSnapshot)?n.sourceSnapshot:{},r.build=Id(Pl,n.build,"build",t,"string"==typeof n.id?n.id:void 0),r.aiSessions=function(e,t,n){if(!e||"object"!=typeof e||Array.isArray(e))return;const i=e,r=Array.isArray(i.sessions)?i.sessions.flatMap((e,i)=>{const r=Id(Ba,e,`aiSessions.sessions.${i}`,t,n);return r?[r]:[]}):[],o={runningCount:"number"==typeof i.runningCount&&Number.isInteger(i.runningCount)&&i.runningCount>=0?i.runningCount:0,waitingCount:"number"==typeof i.waitingCount&&Number.isInteger(i.waitingCount)&&i.waitingCount>=0?i.waitingCount:0,staleCount:"number"==typeof i.staleCount&&Number.isInteger(i.staleCount)&&i.staleCount>=0?i.staleCount:0,sessions:r,updatedAt:Vc.safeParse(i.updatedAt).success?i.updatedAt:(new Date).toISOString()};return Object.keys(i).some(e=>!["runningCount","waitingCount","staleCount","sessions","updatedAt"].includes(e))&&t?.({instanceId:n,field:"aiSessions"}),Wa.parse(o)}(n.aiSessions,t,"string"==typeof n.id?n.id:void 0),r.triggers=function(e,t,n){if(!e||"object"!=typeof e||Array.isArray(e))return;const i=e;Object.keys(i).some(e=>!["enabledCount","runningCount","errorCount","configs","recentRuns"].includes(e))&&t?.({instanceId:n,field:"triggers"});const r=(e,i,r)=>Array.isArray(e)?e.flatMap((e,o)=>{const s=Id(i,e,`${r}.${o}`,t,n);return s?[s]:[]}):[],o=Array.isArray(i.configs)?i.configs.flatMap((e,i)=>{if(!e||"object"!=typeof e||Array.isArray(e))return[];const o=e;Object.keys(o).some(e=>!["configHash","config","deployments","runtime"].includes(e))&&t?.({instanceId:n,field:`triggers.configs.${i}`});const s=function(e,t,n,i){if(!e||"object"!=typeof e||Array.isArray(e))return;const r=e,o=wd(r,["configHash","name","description","createdAt","updatedAt"]);if(r.source&&"object"==typeof r.source&&!Array.isArray(r.source)){const e=r.source,t="schedule"===e.type?"interval"===e.scheduleKind?["type","scheduleKind","intervalMs"]:"daily"===e.scheduleKind?["type","scheduleKind","timeOfDay","timezone"]:["type","scheduleKind","weekdays","timeOfDay","timezone"]:"file-change"===e.type?["type","roots","globs","ignore","debounceMs"]:["type","agent","statuses","phases"];o.source=wd(e,t)}return o.action=wd(r.action,["promptTemplate"]),o.policy=wd(r.policy,["cooldownMs","maxConcurrentRuns","whenBusy"]),Id(oc,o,t,n,i)}(o.config,`triggers.configs.${i}.config`,t,n);return"string"==typeof o.configHash&&s?[{configHash:o.configHash,config:s,deployments:r(o.deployments,ac,`triggers.configs.${i}.deployments`),runtime:r(o.runtime,cc,`triggers.configs.${i}.runtime`)}]:[]}):[];return{enabledCount:"number"==typeof i.enabledCount&&Number.isInteger(i.enabledCount)&&i.enabledCount>=0?i.enabledCount:0,runningCount:"number"==typeof i.runningCount&&Number.isInteger(i.runningCount)&&i.runningCount>=0?i.runningCount:0,errorCount:"number"==typeof i.errorCount&&Number.isInteger(i.errorCount)&&i.errorCount>=0?i.errorCount:0,configs:o,recentRuns:r(i.recentRuns,lc,"triggers.recentRuns")}}(n.triggers,t,"string"==typeof n.id?n.id:void 0),r.apps=Id(yd.shape.apps.unwrap(),wd(n.apps,["runningCount","problemCount","updatedAt","revision"]),"apps",t,"string"==typeof n.id?n.id:void 0)||{runningCount:0,problemCount:0},r.config=Id(yd.shape.config.unwrap(),wd(n.config,["autoImportAgentConfigs","defaultCodexPermissionMode","aiSessionHistoryLimit","aiSessionAttachmentRetentionDays","aiSessionMaxFileAttachmentBytes"]),"config",t,"string"==typeof n.id?n.id:void 0)||{autoImportAgentConfigs:!0,defaultCodexPermissionMode:"ask",aiSessionHistoryLimit:50,aiSessionAttachmentRetentionDays:30,aiSessionMaxFileAttachmentBytes:Js},r.modelSelection=Id(Qc.unwrap(),wd(n.modelSelection,["codexModelHash","claudeModelHash","opencodeModelHash"]),"modelSelection",t,"string"==typeof n.id?n.id:void 0)||{},r.imageSnapshot=function(e,t,n,i){if(!e||"object"!=typeof e||Array.isArray(e))return e;const r=e,o=ju(r),{reference:s,...a}=o,c=r.requestedReference??s;let l;try{l="string"==typeof c?Xc(c):void 0}catch{}const u={img_default:"market_taskhandoff_browser",img_codex:"market_taskhandoff_codex",img_ai:"market_taskhandoff_ai"},d="string"==typeof r.id?r.id:"string"==typeof t?t:void 0,p="market"===r.origin||d&&u[d]?"market":"custom";return void 0===r.image&&void 0===r.reference||n?.({instanceId:i,field:"imageSnapshot.reference"}),{...a,id:d&&u[d]?u[d]:d,origin:p,repository:l?.repository??r.repository,tag:l?.tag??r.tag,requestedReference:l?.reference??c,resolvedDigest:r.resolvedDigest,resolvedReference:r.resolvedReference,downloadSizeBytes:r.downloadSizeBytes,market:"market"===p?wd(r.market,["catalogId","catalogRevision","publisher","version"])??{catalogId:"task_handoff_embedded",catalogRevision:"legacy",publisher:"task-handoff"}:void 0}}(n.imageSnapshot,n.imageId,t,"string"==typeof n.id?n.id:void 0);const o="string"==typeof n.imageId?{img_default:"market_taskhandoff_browser",img_codex:"market_taskhandoff_codex",img_ai:"market_taskhandoff_ai"}[n.imageId]||n.imageId:void 0,s=wd(n.imageSelection,["imageId","tag"]);r.imageSelection=s||(o?{imageId:o,tag:r.imageSnapshot?.tag}:void 0),r.imageProvisioning=Id(Nu,wd(n.imageProvisioning,["phase","requestedReference","generation","error","startedAt","updatedAt"]),"imageProvisioning",t,"string"==typeof n.id?n.id:void 0),r.runtimeVersion=function(e,t,n){if(!e||"object"!=typeof e||Array.isArray(e))return;const i=e,r=e=>{if("string"!=typeof e)return;const t=e.trim();return t&&t.length<=80?t:void 0},o=r(i.desiredVersion);if(!o)return void t?.({instanceId:n,field:"runtimeVersion.desiredVersion"});const s=new Set(Ml.shape.phase.options),a="string"==typeof i.phase?i.phase:"pending",c=s.has(a)?a:{idle:"pending",queued:"pending",checking:"pending",downloading:"installing",updating:"installing",completed:"matched",succeeded:"matched",ready:"matched",error:"failed"}[a]||"pending";let l;if(c!==a&&t?.({instanceId:n,field:"runtimeVersion.phase"}),i.error&&"object"==typeof i.error&&!Array.isArray(i.error)){const e=i.error,o="string"==typeof e.message?e.message.trim().slice(0,4096):"";if(o){const i=new Set(Dl.shape.code.options),s="string"==typeof e.code&&i.has(e.code)?e.code:"INSTANCE_RUNTIME_INSTALL_FAILED";s!==e.code&&t?.({instanceId:n,field:"runtimeVersion.error.code"});const a=r(e.expectedVersion),c=r(e.actualVersion);l={code:s,message:o,...a?{expectedVersion:a}:{},...c?{actualVersion:c}:{},retryable:!0===e.retryable}}else t?.({instanceId:n,field:"runtimeVersion.error"})}"string"==typeof i.error&&i.error.trim()&&(l={code:"INSTANCE_RUNTIME_INSTALL_FAILED",message:i.error.trim().slice(0,4096),expectedVersion:o,...r(i.actualVersion)?{actualVersion:r(i.actualVersion)}:{},retryable:!1});const u=r(i.actualVersion),d=Vc.safeParse(i.lastAttemptAt),p=Vc.safeParse(i.matchedAt);return void 0===i.lastAttemptAt||d.success||t?.({instanceId:n,field:"runtimeVersion.lastAttemptAt"}),void 0===i.matchedAt||p.success||t?.({instanceId:n,field:"runtimeVersion.matchedAt"}),{desiredVersion:o,...u?{actualVersion:u}:{},phase:c,attempt:"number"==typeof i.attempt&&Number.isInteger(i.attempt)&&i.attempt>=0?i.attempt:0,...d.success?{lastAttemptAt:d.data}:{},...p.success?{matchedAt:p.data}:{},...l?{error:l}:{}}}(n.runtimeVersion,t,"string"==typeof n.id?n.id:void 0),r.workspace=Id(gd,n.workspace,"workspace",t,"string"==typeof n.id?n.id:void 0)||{status:"unknown"},r.environmentSource=Id(tl,n.environmentSource,"environmentSource",t,"string"==typeof n.id?n.id:void 0),r.environmentTemplateOrigin=Id(sl,n.environmentTemplateOrigin,"environmentTemplateOrigin",t,"string"==typeof n.id?n.id:void 0),r.runtime=Id(yd.shape.runtime.unwrap(),n.runtime,"runtime",t,"string"==typeof n.id?n.id:void 0)||{labels:{}},r.target=Id(md,wd(n.target??n.endpoints,["strategy","web","api","vnc","tty","logs","status"]),"target",t,"string"==typeof n.id?n.id:void 0)||{strategy:"direct-port",status:"unknown"},r.access=Id(fd,wd(n.access,["strategy","web","api","ws","status"]),"access",t,"string"==typeof n.id?n.id:void 0)||{strategy:"control-plane-proxy",status:"unknown"};for(const[e,i]of Object.entries(yd.shape))Object.prototype.hasOwnProperty.call(r,e)&&!i.safeParse(r[e]).success&&i.safeParse(void 0).success&&(delete r[e],t?.({instanceId:"string"==typeof n.id?n.id:void 0,field:e}));return r}function Id(e,t,n,i,r){if(!t||"object"!=typeof t||Array.isArray(t))return;let o=structuredClone(t),s=!1;for(let t=0;t<20;t+=1){const t=e.safeParse(o);if(t.success)return s&&i?.({instanceId:r,field:n}),t.data;let a=!1;for(const e of t.error.issues){if("unrecognized_keys"!==e.code)continue;const t=xd(o,e.path);if(t&&"object"==typeof t&&!Array.isArray(t))for(const n of e.keys)Object.prototype.hasOwnProperty.call(t,n)&&(delete t[n],a=!0,s=!0)}if(!a){const s=structuredClone(o);let a=!1;for(const e of t.error.issues){if(!e.path.length||"string"!=typeof e.path.at(-1))continue;const t=xd(s,e.path.slice(0,-1)),n=e.path.at(-1);t&&"object"==typeof t&&!Array.isArray(t)&&Object.prototype.hasOwnProperty.call(t,n)&&(delete t[n],a=!0)}if(a){const t=e.safeParse(s);if(t.success)return i?.({instanceId:r,field:n}),t.data}break}}i?.({instanceId:r,field:n})}function xd(e,t){let n=e;for(const e of t){if(!n||"object"!=typeof n)return;n=n[e]}return n}function Sd(e,t,n){if(!e||"object"!=typeof e||Array.isArray(e))return e;const i=e,r=i.type,o=Yl.options.find(e=>e.shape.type.value===r);if(!o)return e;const s="local-folder"===r?["type","localFolderId","path","ownerNodeId"]:"git-template"===r?["type","url","templateId","ref","auth","clone"]:["type","repositoryId","url","provider","ref","auth","clone"],a=wd(i,s);if("local-folder"!==r){const e=function(e,t,n){const i=e&&"object"==typeof e&&!Array.isArray(e)?e:void 0,r=ql.safeParse(wd(i,["type","name","commit"]));if(r.success)return r.data;const o="string"==typeof i?.commit?i.commit.trim():"",s="string"==typeof i?.name?i.name.trim():"",a=o?ql.safeParse({type:"commit",commit:o}):s?ql.safeParse({type:"tag"===i?.type?"tag":"branch",name:s}):ql.safeParse({type:"branch",name:"main"});return a.success?(t?.({instanceId:n,field:"source.ref"}),a.data):void 0}(i.ref,t,n),r=Id(Bl,wd(i.auth,["type","secretId"]),"source.auth",t,n),o=Id(Wl,wd(i.clone,["depth","submodules","lfs","subdirectory"]),"source.clone",t,n);e?a.ref=e:delete a.ref,r?a.auth=r:delete a.auth,o?a.clone=o:delete a.clone}const c=Id(o,a,"source",t,n);return c?(Object.keys(i).some(e=>!s.includes(e))&&t?.({instanceId:n,field:"source"}),c):a}function wd(e,t){if(!e||"object"!=typeof e||Array.isArray(e))return e;const n=e;return Object.fromEntries(t.filter(e=>Object.prototype.hasOwnProperty.call(n,e)).map(e=>[e,n[e]]))}const Ed=gs({instanceId:Fc.optional(),projectId:Fc.optional(),source:Yl.optional(),nodeId:Fc.optional(),runtimeId:Fc.optional(),imageSelection:el.optional(),instanceVersion:jo().trim().max(80).optional(),protocolVersion:Oc,build:Pl.optional(),controlMode:ws(["standalone","controlled"]).default("controlled"),capabilities:Rc.default(Cc),appInventory:fl.optional(),target:hd.optional(),workspace:gd.default({status:"unknown"}),registrationToken:jo().trim().max(240).optional(),processIncarnationId:jo().trim().min(1).max(120).optional()}).strict().superRefine((e,t)=>{Ec.has(e.protocolVersion)&&!e.appInventory&&t.addIssue({code:"custom",path:["appInventory"],message:"Current protocol register payload requires appInventory."})}),Od=gs({status:yd.shape.status.optional(),health:yd.shape.health.optional(),protocolVersion:Oc,build:Pl.optional(),capabilities:yd.shape.capabilities.optional(),appInventory:fl.optional(),apps:yd.shape.apps.optional(),aiSessions:yd.shape.aiSessions.optional(),triggers:yd.shape.triggers.optional(),workspace:gd.optional(),target:hd.optional(),processIncarnationId:jo().trim().min(1).max(120).optional()}).strict().superRefine((e,t)=>{Ec.has(e.protocolVersion)&&!e.appInventory&&t.addIssue({code:"custom",path:["appInventory"],message:"Current protocol heartbeat payload requires appInventory."})}),kd=ws(["web","telegram","wechat","dingding","lark"]),Cd=gs({id:Fc,channel:kd,name:jo().trim().min(1).max(160),enabled:ls().default(!1),token:jo().trim().max(4096).optional(),defaultChatId:jo().trim().max(240).optional(),allowedUserIds:hs(jo().trim().min(1).max(240)).default([]),pollIntervalMs:os().int().positive().max(6e4).default(3e3),settings:xs(jo(),ds()).default({}),createdAt:Vc,updatedAt:Vc}).strict(),Td=gs({id:Fc,channel:kd,bridgeId:Fc.optional(),chatSessionId:jo().trim().min(1).max(240),userId:jo().trim().max(240).optional(),activeProjectId:Fc.optional(),activeInstanceId:Fc.optional(),activeAiSessionId:jo().trim().min(1).max(120).optional(),lastUsedAt:Vc,createdAt:Vc,updatedAt:Vc}).strict(),$d=gs({source:gs({type:Os("chat-gateway").default("chat-gateway"),channel:kd,bridgeId:Fc.optional(),chatSessionId:jo().trim().min(1).max(240),userId:jo().trim().max(240).optional()}).strict(),message:gs({text:jo().trim().max(2e4).default(""),attachments:hs(_a).max(6).default([])}).strict().superRefine((e,t)=>{e.attachments.reduce((e,t)=>e+("inline"===t.source.type?t.size:0),0)>Ys&&t.addIssue({code:Zs,path:["attachments"],message:"Inline attachments must be 41943040 bytes or less in total."})}),target:gs({instanceId:Fc,aiSessionId:jo().trim().min(1).max(120)}).strict().optional()}).strict(),Nd=gs({id:Fc,instanceId:Fc,projectId:Fc.optional(),aiSessionId:jo().trim().min(1).max(120),providerSessionId:jo().trim().max(240).optional(),result:jo().default(""),timeoutMs:os().positive().optional(),source:jo().trim().max(120).optional(),kind:ws(["task","approval"]).default("task"),status:ws(["pending","unreachable"]).default("pending"),error:jo().trim().max(2048).optional(),lastSeenAt:Vc}).strict();var Rd,Pd,zd=Object.freeze({__proto__:null,AiSessionConversationAttachmentCapabilitiesSchema:$c,AiSessionProviderCapabilitiesSchema:Sc,AiSessionProviderCapabilitySchema:xc,AiSessionTimelineCapabilitiesSchema:Tc,AppInstallPrivilegeSchema:vl,AppInstallerSchema:yl,AppManagementCommandSchema:Ol,AppManagementErrorSchema:kl,AppManagementEventSchema:Rl,AppManagementJobResponseSchema:Nl,AppManagementJobSchema:Cl,AppManagementJobStateSchema:wl,AppManagementOperationRequestSchema:$l,AppManagementOperationSchema:Sl,AppManagementProgressSchema:El,AppManagementSnapshotSchema:Tl,ApplyUpdateRequestSchema:Zl,BuildInfoSchema:Pl,CONTROL_PLANE_PROTOCOL_VERSION:wc,ChatBridgeConfigSchema:Cd,ChatChannelSchema:kd,ChatGatewayMessageSchema:$d,ChatSessionBindingSchema:Td,ControlPlaneHealthResponseSchema:zl,ControlledInstanceCapabilitiesSchema:Rc,ControlledInstanceFeatureCapabilitiesSchema:Nc,ControlledInstanceHeartbeatSchema:Od,ControlledInstanceRegisterSchema:Ed,ControlledInstanceSchema:yd,CreateNodeModelSchema:pu,CustomImageProfileSchema:Ou,DEFAULT_IMAGE_COVER:{kind:"builtin",key:"default-image-cover"},DeployNodeModelSchema:hu,DockerImageDigestSchema:Kc,DockerImageReferenceSchema:Yc,EnvironmentSourceSchema:tl,EnvironmentTemplateErrorSchema:ol,EnvironmentTemplateOriginSchema:sl,EnvironmentTemplateSchema:gl,EnvironmentTemplateStatusSchema:nl,FederatedModelGroupSchema:lu,FederatedModelRegistrySchema:du,FinalComputerArchSchema:rl,FinalComputerCapabilitiesSchema:_l,FinalComputerPlatformSchema:il,GitAuthSchema:Bl,GitCloneOptionsSchema:Wl,GitRefSchema:ql,GitRepositorySchema:Jl,ImageCoverSchema:vu,ImageOriginSchema:gu,ImageProfileSchema:ku,ImageProvisioningSchema:Nu,ImagePullProgressSchema:Lu,ImagePullTerminalEventType:{Output:"image.pull.terminal.output",Finished:"image.pull.terminal.finished",Progress:"image.pull.progress",Snapshot:"image.pull.snapshot"},ImagePullTerminalFinishedSchema:zu,ImagePullTerminalOutputSchema:Pu,ImageSelectionSchema:el,InstanceAccessSchema:fd,InstanceAppInventoryIssueSchema:hl,InstanceAppInventoryItemSchema:ml,InstanceAppInventorySchema:fl,InstanceDeleteInputSchema:cl,InstanceDeleteResultSchema:ul,InstanceImageSnapshotSchema:$u,InstanceLifecycleEventType:{Snapshot:"instance.lifecycle.snapshot"},InstanceLifecycleSnapshotSchema:bd,InstanceResourceMetricsEventType:{Snapshot:"instance.metrics.snapshot"},InstanceResourceMetricsSchema:qu,InstanceTargetSchema:md,InstanceVolumeDispositionSchema:ll,InstanceVolumeRoleSchema:al,LEGACY_MARKET_IMAGE_IDS:dl,LocalDockerImageSchema:cd,MARKET_CATALOG_PROTOCOL_VERSION:"2026-07-29",ManagedAppActionReasonSchema:Il,ManagedAppManagementSourceSchema:Al,ManagedAppProjectionSchema:xl,ManagedAppStateSchema:bl,MarketCatalogSnapshotSchema:wu,MarketCatalogStatusSchema:Eu,MarketImagePlatformArtifactSchema:Iu,MarketImageSchema:Su,MarketImageTagSchema:xu,MarketLifecycleStatusSchema:yu,ModelAppSchema:tu,ModelConfigSchema:iu,ModelLocationSchema:cu,ModelRegistryNodeDiagnosticSchema:uu,ModelSelectionSchema:Qc,NODE_TUNNEL_PROTOCOL_VERSION:"2026-08-01",NodeAgentCapabilitiesSchema:Wu,NodeAgentControlPlaneConnectionCreateResultSchema:sd,NodeAgentControlPlaneConnectionSchema:od,NodeAgentControlPlanePairingSchema:id,NodeAgentDeleteResponseSchema:ad,NodeAgentEventTransportHealthSchema:Xu,NodeAgentExternalListenerConfigSchema:Ku,NodeAgentExternalListenerSchema:Qu,NodeAgentHealthSchema:Yu,NodeAgentInstanceLifecycleResultSchema:vd,NodeAgentInstanceProxyRawResponseSchema:pd,NodeAgentManagedGitCapabilitiesSchema:Bu,NodeAgentPairingCompleteResultSchema:nd,NodeAgentPairingInviteResponseSchema:td,NodeAgentPairingSelfRevokeResultSchema:rd,NodeConnectionDiagnosticsSchema:Mu,NodeConnectionPathSchema:Du,NodeControlPlaneProxyStateSchema:Uu,NodeFolderPlaceSchema:dd,NodeFolderTreeEntrySchema:ud,NodeImageAvailabilitySchema:ld,NodeJoinInviteStatusSchema:Vu,NodeJoinedEventSchema:Fu,NodeLocalFolderSchema:Xl,NodeModelAssignmentSchema:au,NodeModelConfigSchema:ru,NodeModelPublicRecordSchema:su,NodeRolloutSummarySchema:Vl,NodeRuntimeSchema:Zu,NodeSchema:Hu,NodeStateProjectionEventSchema:Gu,NodeTunnelRequestBodySchema:Gc,NodeUpdateImpactSchema:Fl,PendingRouteSchema:Nd,ProjectSchema:nu,ProjectSourceSchema:Yl,ProtocolVersionSchema:Oc,PublicModelConfigSchema:ou,RuntimeArtifactIdentitySchema:jl,RuntimeConvergenceErrorSchema:Dl,RuntimeVersionStateSchema:Ml,SelectableImageSchema:Tu,SelectableImageTagSchema:Cu,UpdateChannelSchema:Ll,UpdateCheckRequestSchema:Ul,UpdateCheckResultSchema:Hl,UpdateJobSchema:Gl,UpdateNodeAgentExternalListenerSchema:ed,UpdateNodeModelAssignmentSchema:fu,UpdateNodeModelSchema:mu,WorkspacePolicySchema:eu,WorkspaceStatusSchema:gd,aiSessionConversationAttachmentCapabilities:zc,aiSessionConversationAttachmentCapabilityAgents:jc,aiSessionProviderCapabilities:Lc,aiSessionProviderCapability:function(e,t){return Lc(e).find(e=>e.agent===t)},aiSessionTimelineCapabilities:Dc,aiSessionTimelineCapabilityAgents:Mc,controlledInstanceAcceptsTraffic:function(e){return!1!==e.ready&&(!e.runtimeVersion||["matched","failed"].includes(e.runtimeVersion.phase))},decodeNodeTunnelRequestBody:function(e){if(null==e)return;const t=Gc.parse(e);return"utf8"===t.encoding?t.data:Buffer.from(t.data,"base64")},encodeNodeTunnelRequestBody:function(e){if(null!=e){if("string"==typeof e)return{encoding:"utf8",data:e};if(Buffer.isBuffer(e))return{encoding:"base64",data:e.toString("base64")};if(e instanceof ArrayBuffer)return{encoding:"base64",data:Buffer.from(e).toString("base64")};if(ArrayBuffer.isView(e))return{encoding:"base64",data:Buffer.from(e.buffer,e.byteOffset,e.byteLength).toString("base64")};throw new TypeError("Node tunnel request body must be a string or binary buffer.")}},migrateLegacyImageSelection:pl,modelConfigHash:function(e){const t={app:tu.parse(e.app),endpoint:iu.shape.endpoint.parse(e.endpoint),key:iu.shape.key.parse(e.key),model:iu.shape.model.parse(e.model)};return`mdl_${s.createHash("sha256").update(JSON.stringify(t)).digest("hex")}`},normalizeControlledInstanceCapabilities:Pc,normalizeDockerImageReference:Jc,normalizeNodeAgentCapabilities:Ju,parseDockerImageReference:Xc,parseStoredControlledInstance:function(e,t){return yd.parse(Ad(e,t))},projectSourceWithoutGitCredential:Kl,projectSourceWithoutLegacyGitSecretId:Ql,safeParseStoredControlledInstance:function(e,t){return yd.safeParse(Ad(e,t))},sanitizeCrossVersionControlledInstanceHeartbeat:function(e,t){if(!e||"object"!=typeof e||Array.isArray(e))return e;const n=["status","health","protocolVersion","build","capabilities","appInventory","apps","aiSessions","triggers","workspace","target","processIncarnationId"],i=new Set(n);for(const n of Object.keys(e))i.has(n)||t?.({field:n,action:"ignored"});return wd(e,n)},sanitizeCrossVersionControlledInstanceRegister:function(e,t){if(!e||"object"!=typeof e||Array.isArray(e))return e;const n=e,i=["instanceId","projectId","source","nodeId","runtimeId","imageSelection","instanceVersion","protocolVersion","build","controlMode","capabilities","appInventory","target","workspace","registrationToken","processIncarnationId"],r=new Set([...i,"imageId"]);for(const e of Object.keys(n))r.has(e)||t?.({field:e,action:"ignored"});return Object.prototype.hasOwnProperty.call(n,"imageId")&&t?.({field:"imageId",action:"migrated"}),{...wd(n,i),imageSelection:pl(n.imageSelection,n.imageId)}},sanitizeStoredControlledInstance:Ad,sanitizeStoredEnvironmentTemplate:function(e,t){if(!e||"object"!=typeof e||Array.isArray(e))return e;const n=e,i=new Set(["id","name","sourceInstanceId","nodeId","imageId","internalTag","platform","architecture","sizeBytes","status","error","createdAt","updatedAt"]),r="string"==typeof n.id?n.id:void 0;for(const e of Object.keys(n))i.has(e)||t?.({templateId:r,field:e});const o=wd(n,[...i]);if(n.error&&"object"==typeof n.error&&!Array.isArray(n.error)){const e=n.error;for(const n of Object.keys(e))["code","message","phase"].includes(n)||t?.({templateId:r,field:`error.${n}`});o.error=wd(e,["code","message","phase"])}return o},sanitizeStoredImageProfile:ju,sanitizeStoredMarketCatalogSnapshot:function(e,t){if(!e||"object"!=typeof e||Array.isArray(e))return e;const n=e,i=["protocolVersion","catalogId","revision","source","generatedAt","expiresAt","items"];for(const e of Object.keys(n))i.includes(e)||t?.({field:e});const r=Array.isArray(n.items)?n.items.flatMap(e=>{if(!e||"object"!=typeof e||Array.isArray(e))return t?.({field:"items"}),[];const n=e,i=["id","publisher","slug","name","description","localizedDescriptions","cover","repository","defaultTag","tags","capabilities","optionalApps","defaultEnv","labels","status"];for(const e of Object.keys(n))i.includes(e)||t?.({itemId:"string"==typeof n.id?n.id:void 0,field:e});const r=Su.safeParse(wd(n,i));return r.success?[r.data]:(t?.({itemId:"string"==typeof n.id?n.id:void 0,field:"invalid-record"}),[])}):n.items;return{...wd(n,i),items:r}},sanitizeStoredNode:function(e,t){if(!e||"object"!=typeof e||Array.isArray(e))return e;const n=e,i=new Set(["id","name","connectionMode","connectionPath","connectionEnabled","auth","endpoint","controlEndpoint","containerEndpoint","publicWebBase","status","health","capabilities","proxyState","appInventory","labels","lastSeenAt","createdAt","updatedAt"]);for(const e of Object.keys(n))i.has(e)||t?.({field:e});const r=n.auth&&"object"==typeof n.auth&&!Array.isArray(n.auth)?wd(n.auth,["mode","keyId","secret","pairedAt","pairing"]):n.auth;r&&"object"==typeof r&&"pairing"in r&&(r.pairing=wd(r.pairing,["status","joinToken","expiresAt"]));const o=n.connectionPath&&"object"==typeof n.connectionPath&&!Array.isArray(n.connectionPath)?"control-plane-proxy"===n.connectionPath.kind?wd(n.connectionPath,["kind","proxyId","proxyBindingId","targetNodeId"]):wd(n.connectionPath,["kind"]):{kind:"direct"},s=n.proxyState&&"object"==typeof n.proxyState&&!Array.isArray(n.proxyState)?wd(n.proxyState,["reachability","bindingStatus","bindingRevision","streamId","revision","observedAt","target","lastError","updatedAt"]):n.proxyState;if(s&&"object"==typeof s){const e=s;e.target=wd(e.target,["id","name","status","health","lastSeenAt","capabilities"]),e.lastError=wd(e.lastError,["code","message","retryable","details"])}return{...Object.fromEntries(Object.entries(n).filter(([e])=>i.has(e))),auth:r,connectionPath:o,proxyState:s}},sanitizeStoredNodeLocalFolder:function(e){if(!e||"object"!=typeof e||Array.isArray(e))return e;const t=e,{defaultImageId:n,...i}=t;return{...i,defaultImageSelection:pl(t.defaultImageSelection,n)}},sanitizeStoredProject:function(e){if(!e||"object"!=typeof e||Array.isArray(e))return e;const t=e,{defaultImageId:n,defaultRuntimeId:i,...r}=t;return{...r,source:Sd(t.source),defaultImageSelection:pl(t.defaultImageSelection,n)}},supportsAiSessionAttachmentRetentionSettings:function(e){return zc(e).retentionSettings},supportsAiSessionConversationAttachmentCapability:function(e,t,n){return jc(e,n).includes(t)},supportsAiSessionFileSizeLimitSettings:function(e){return!0===zc(e).fileSizeLimitSettings},supportsAiSessionPersistenceSettings:function(e){return Pc(e).features.aiSessionPersistenceSettings},supportsAiSessionTimelineCapability:function(e,t,n){return Mc(e,n).includes(t)},supportsAiSessionWorkspaceSelection:function(e){return Pc(e).features.aiSessionWorkspaceSelection},supportsGitCliCredentialBroker:function(e){const t=Pc(e).features;return t.gitCredentialProxy||t.gitCliCredentialBroker},supportsGitCredentialProxy:function(e){return Pc(e).features.gitCredentialProxy},supportsNodeAiSessionFileAttachmentLimit:function(e){return!0===Wu.safeParse(e).data?.aiSessionFileAttachmentLimit},supportsNodeFolderPlaces:function(e){return!0===Wu.safeParse(e).data?.folderPlaces},supportsNodeGitCredentialRuntimeBroker:function(e){return Ju(e).managedGitCredentials.runtimeBroker},supportsNodeGitWorkspaceProvisioning:function(e,t){return Ju(e).managedGitCredentials.workspaceProvisioning[t]},supportsNodeLocalFolderNameUpdate:function(e){return!0===Wu.safeParse(e).data?.localFolderNameUpdate},supportsNodeManagedGitCredentialRegistry:function(e){return Ju(e).managedGitCredentials.registry}}),Ld=d(zd),jd=function(){if(Pd)return Rd;Pd=1;const t=e,{spawnSync:i}=n;return Rd={processStartIdentity:function(e,n=process.platform){if(Number.isInteger(e)&&!(e<=0)){if("linux"===n)try{const n=t.readFileSync(`/proc/${e}/stat`,"utf8"),i=n.lastIndexOf(")");if(i<0)return;const r=n.slice(i+2).trim().split(/\s+/)[19];return r?`linux:${r}`:void 0}catch{return}if(["darwin","freebsd","openbsd","aix","sunos"].includes(n)){const t=i("ps",["-o","lstart=","-p",String(e)],{encoding:"utf8",timeout:1e3}),r=0===t.status?t.stdout.trim().replace(/\s+/g," "):"";return r?`${n}:${r}`:void 0}if("win32"===n){const t=i("powershell.exe",["-NoProfile","-NonInteractive","-Command",`(Get-Process -Id ${e} -ErrorAction Stop).StartTime.ToUniversalTime().Ticks`],{encoding:"utf8",timeout:2e3}),n=0===t.status?t.stdout.trim():"";return/^\d+$/.test(n)?`win32:${n}`:void 0}}}}}();class Dd extends Error{code;lockPath;owner;constructor(e,t,n={}){const i=t?.pid?` pid ${t.pid}`:"";super(`${n.label||"Process"} is already running${i}. Lock: ${e}`),this.name="ProcessSingletonError",this.code=n.code||"PROCESS_ALREADY_RUNNING",this.lockPath=e,this.owner=t}}function Md(e){return t.join(e,"owner.json")}function Fd(e){return t.join(e,"initializing.json")}function Vd(e){return t.join(e,"recovering.json")}function Ud(e){return Number.isInteger(e)&&Number(e)>0}const Hd=function(t){try{const n=JSON.parse(e.readFileSync(Md(t),"utf8"));if(Ud(n.pid)&&"string"==typeof n.startTime){const e=n;return{pid:e.pid,hostname:"string"==typeof e.hostname&&e.hostname?e.hostname:l.hostname(),component:e.component||"server-update",command:"string"==typeof e.command?e.command:"",acquiredAt:"string"==typeof e.createdAt&&Number.isFinite(Date.parse(e.createdAt))?e.createdAt:new Date(0).toISOString(),token:"string"==typeof e.token&&e.token?e.token:`legacy:${e.pid}:${e.startTime}`,startIdentity:e.startTime.startsWith("linux:")?e.startTime:`linux:${e.startTime}`}}if(!(Ud(n.pid)&&"string"==typeof n.hostname&&n.hostname&&"string"==typeof n.command&&"string"==typeof n.acquiredAt&&Number.isFinite(Date.parse(n.acquiredAt))&&"string"==typeof n.token&&n.token))return;return n}catch{return}};function Gd(e){if(!Ud(e))return!1;try{return process.kill(Number(e),0),!0}catch(e){return"EPERM"===e.code}}function Zd(e){if(!e||!Gd(e.pid))return!1;if(!e.startIdentity)return!0;const t=jd.processStartIdentity(e.pid);return void 0===t||t===e.startIdentity}function qd(n,i){const r=t.join(n,`.owner-${i.token}.tmp`);e.writeFileSync(r,`${JSON.stringify(i,null,2)}\n`,{encoding:"utf8",mode:384,flag:"wx"});const o=Wd(n);if(o?.token!==i.token)throw Xd(r),new Error(`Process lock initialization was superseded: ${n}`);e.renameSync(r,Md(n)),Xd(Fd(n))}function Bd(n,i,r){const o=Hd(n);if(o?.token!==i.token)return!1;const a={...i};for(const[e,t]of Object.entries(r))void 0===t?delete a[e]:Object.assign(a,{[e]:t});const c=t.join(n,`.owner-update-${i.token}-${s.randomUUID()}.tmp`);try{if(e.writeFileSync(c,`${JSON.stringify(a,null,2)}\n`,{encoding:"utf8",mode:384,flag:"wx"}),Hd(n)?.token!==i.token)return!1;e.renameSync(c,Md(n));for(const e of Object.keys(i))delete i[e];return Object.assign(i,a),!0}catch(e){if("ENOENT"===e.code)return!1;throw e}finally{Xd(c)}}function Wd(t){try{return JSON.parse(e.readFileSync(Fd(t),"utf8"))}catch{return}}function Jd(e){const t=Wd(e);return Ud(t?.pid)&&Zd({pid:t.pid,startIdentity:t.startIdentity})}function Xd(t){try{e.unlinkSync(t)}catch(e){if("ENOENT"!==e.code)throw e}}function Yd(){Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,20)}function Kd(t){try{const n=Wd(t),i=Date.parse(n?.startedAt||"");return Number.isFinite(i)?Math.max(0,Date.now()-i):Math.max(0,Date.now()-e.statSync(t).mtimeMs)}catch{return 0}}function Qd(n,i){try{return e.writeFileSync(Vd(n),`${JSON.stringify({token:i,pid:process.pid,startedAt:(new Date).toISOString()})}\n`,{encoding:"utf8",mode:384,flag:"wx"}),!0}catch(r){if("EEXIST"===r.code)return!!function(n){const i=Vd(n),r=ep(i),o=Date.parse(r?.startedAt||"");if(Gd(r?.pid)||Number.isFinite(o)&&Date.now()-o<2e3)return!1;const a=t.join(n,`.recovering-${s.randomUUID()}.stale`);try{e.renameSync(i,a)}catch(e){if(["ENOENT","EEXIST"].includes(e.code||""))return!1;throw e}const c=ep(a);if(c?.token===r?.token)return Xd(a),!0;try{e.linkSync(a,i)}catch(e){if("EEXIST"!==e.code)throw e}finally{Xd(a)}return!1}(n)&&Qd(n,i);if("ENOENT"===r.code)return!1;throw r}}function ep(t){try{return JSON.parse(e.readFileSync(t,"utf8"))}catch{return}}function tp(e,t){return ep(Vd(e))?.token===t}const np="/run/task-handoff-server-update.lock";function ip(t){const n={};if(!e.existsSync(t))return n;for(const i of e.readFileSync(t,"utf8").split(/\r?\n/)){if(!i||i.startsWith("#"))continue;const e=i.indexOf("=");e>0&&(n[i.slice(0,e)]=i.slice(e+1))}return n}var rp,op=Object.freeze({__proto__:null,SERVER_UPDATE_LOCK_PATH:np,acquireServerUpdateLock:function(n=np,i={}){const r=function(n,i={}){e.mkdirSync(t.dirname(n),{recursive:!0});const r=jd.processStartIdentity(process.pid),o={pid:process.pid,hostname:l.hostname(),command:process.argv.join(" "),acquiredAt:(new Date).toISOString(),token:s.randomUUID(),...void 0!==i.component?{component:i.component}:{},...r?{startIdentity:r}:{},...void 0!==i.dataDir?{dataDir:i.dataDir}:{},...void 0!==i.host?{host:i.host}:{},...void 0!==i.port?{port:i.port}:{},...void 0!==i.instanceId?{instanceId:i.instanceId}:{}};for(let t=0;t<5;t+=1)try{return e.mkdirSync(n),e.writeFileSync(Fd(n),`${JSON.stringify({token:o.token,pid:o.pid,startIdentity:o.startIdentity,startedAt:(new Date).toISOString()})}\n`,{encoding:"utf8",mode:384,flag:"wx"}),qd(n,o),{lockPath:n,owner:o,updateDetails:e=>Bd(n,o,e),release(){const t=Hd(n);t?.token===o.token&&e.rmSync(n,{recursive:!0,force:!0})}}}catch(r){if("EEXIST"!==r.code)throw r;const o=Hd(n);if(Zd(o))throw new Dd(n,o,i.error);if(!o&&(Jd(n)||Kd(n)<(i.incompleteLockStaleMs??2e3))){if(t+1<5){Yd();continue}throw new Dd(n,void 0,i.error)}const a=s.randomUUID();if(!Qd(n,a)){if(t+1<5){Yd();continue}throw new Dd(n,Hd(n),i.error)}const c=Hd(n);if(Zd(c))throw Xd(Vd(n)),new Dd(n,c,i.error);if(o?.token&&c?.token!==o.token){Xd(Vd(n));continue}if(!tp(n,a))continue;e.rmSync(n,{recursive:!0,force:!0})}const a=Hd(n);throw new Dd(n,a,i.error)}(n,{component:"server-update",incompleteLockStaleMs:i.legacyGraceMs??3e4,error:{label:"TaskHandoff server update",code:"SERVER_UPDATE_ALREADY_RUNNING"}});return r.release},cleanUpServerUpdateLockOnSignals:function(e){const t=new Map;for(const n of["SIGINT","SIGTERM","SIGHUP"]){const i=()=>{e(),process.removeListener(n,i),process.kill(process.pid,n)};t.set(n,i),process.on(n,i)}return()=>{for(const[e,n]of t)process.removeListener(e,n)}},currentServerInstallArgs:function(t={}){const n=ip(t.controlPlaneEnvFile||"/etc/task-handoff/control-plane.env"),i=ip(t.nodeAgentEnvFile||"/etc/task-handoff/node-agent.env");return["--service-user",(r=t.nodeAgentUnitFile||"/etc/systemd/system/task-handoff-node-agent.service",e.existsSync(r)&&e.readFileSync(r,"utf8").match(/^User=(.+)$/m)?.[1]||"root"),"--control-plane-data-dir",n.TASK_HANDOFF_CONTROL_PLANE_DATA_DIR||"/var/lib/task-handoff/control-plane","--node-agent-data-dir",i.TASK_HANDOFF_NODE_AGENT_DATA_DIR||"/var/lib/task-handoff/node-agent","--control-plane-host",n.TASK_HANDOFF_CONTROL_PLANE_HOST||"0.0.0.0","--control-plane-port",n.TASK_HANDOFF_CONTROL_PLANE_PORT||"8081","--node-agent-host",i.TASK_HANDOFF_NODE_AGENT_HOST||"127.0.0.1","--node-agent-port",i.TASK_HANDOFF_NODE_AGENT_PORT||"8091","--node-agent-ipc-path",i.TASK_HANDOFF_NODE_AGENT_IPC_PATH||"/run/task-handoff/node-agent.sock","--auth-mode",n.TASK_HANDOFF_CONTROL_PLANE_AUTH_MODE||"password",...n.TASK_HANDOFF_CONTROL_PLANE_STATIC_DIR?["--static-dir",n.TASK_HANDOFF_CONTROL_PLANE_STATIC_DIR]:[]];var r},globalPrefixFromModulePath:function(e){let n=t.resolve(e);for(;n!==t.dirname(n);){if("node_modules"===t.basename(n)&&"lib"===t.basename(t.dirname(n)))return t.dirname(t.dirname(n));n=t.dirname(n)}}}),sp=d(op),ap=function(){if(rp)return h;rp=1,Object.defineProperty(h,"__esModule",{value:!0});const l=e,u=t,{spawnSync:d}=n,{Command:p,InvalidArgumentError:m}=function(){if(C)return f;C=1;const{Argument:o}=_(),{Command:s}=function(){if(k)return A;k=1;const o=i.EventEmitter,s=n,a=t,c=e,l=r,{Argument:u,humanReadableArgName:d}=_(),{CommanderError:p}=v(),{Help:m,stripColor:h}=x(),{Option:f,DualOptions:g}=E(),{suggestSimilar:y}=$();class b extends o{constructor(e){super(),this.commands=[],this.options=[],this.parent=null,this._allowUnknownOption=!1,this._allowExcessArguments=!1,this.registeredArguments=[],this._args=this.registeredArguments,this.args=[],this.rawArgs=[],this.processedArgs=[],this._scriptPath=null,this._name=e||"",this._optionValues={},this._optionValueSources={},this._storeOptionsAsProperties=!1,this._actionHandler=null,this._executableHandler=!1,this._executableFile=null,this._executableDir=null,this._defaultCommandName=null,this._exitCallback=null,this._aliases=[],this._combineFlagAndOptionalValue=!0,this._description="",this._summary="",this._argsDescription=void 0,this._enablePositionalOptions=!1,this._passThroughOptions=!1,this._lifeCycleHooks={},this._showHelpAfterError=!1,this._showSuggestionAfterError=!0,this._savedState=null,this._outputConfiguration={writeOut:e=>l.stdout.write(e),writeErr:e=>l.stderr.write(e),outputError:(e,t)=>t(e),getOutHelpWidth:()=>l.stdout.isTTY?l.stdout.columns:void 0,getErrHelpWidth:()=>l.stderr.isTTY?l.stderr.columns:void 0,getOutHasColors:()=>S()??(l.stdout.isTTY&&l.stdout.hasColors?.()),getErrHasColors:()=>S()??(l.stderr.isTTY&&l.stderr.hasColors?.()),stripColor:e=>h(e)},this._hidden=!1,this._helpOption=void 0,this._addImplicitHelpCommand=void 0,this._helpCommand=void 0,this._helpConfiguration={},this._helpGroupHeading=void 0,this._defaultCommandGroup=void 0,this._defaultOptionGroup=void 0}copyInheritedSettings(e){return this._outputConfiguration=e._outputConfiguration,this._helpOption=e._helpOption,this._helpCommand=e._helpCommand,this._helpConfiguration=e._helpConfiguration,this._exitCallback=e._exitCallback,this._storeOptionsAsProperties=e._storeOptionsAsProperties,this._combineFlagAndOptionalValue=e._combineFlagAndOptionalValue,this._allowExcessArguments=e._allowExcessArguments,this._enablePositionalOptions=e._enablePositionalOptions,this._showHelpAfterError=e._showHelpAfterError,this._showSuggestionAfterError=e._showSuggestionAfterError,this}_getCommandAndAncestors(){const e=[];for(let t=this;t;t=t.parent)e.push(t);return e}command(e,t,n){let i=t,r=n;"object"==typeof i&&null!==i&&(r=i,i=null),r=r||{};const[,o,s]=e.match(/([^ ]+) *(.*)/),a=this.createCommand(o);return i&&(a.description(i),a._executableHandler=!0),r.isDefault&&(this._defaultCommandName=a._name),a._hidden=!(!r.noHelp&&!r.hidden),a._executableFile=r.executableFile||null,s&&a.arguments(s),this._registerCommand(a),a.parent=this,a.copyInheritedSettings(this),i?this:a}createCommand(e){return new b(e)}createHelp(){return Object.assign(new m,this.configureHelp())}configureHelp(e){return void 0===e?this._helpConfiguration:(this._helpConfiguration=e,this)}configureOutput(e){return void 0===e?this._outputConfiguration:(this._outputConfiguration={...this._outputConfiguration,...e},this)}showHelpAfterError(e=!0){return"string"!=typeof e&&(e=!!e),this._showHelpAfterError=e,this}showSuggestionAfterError(e=!0){return this._showSuggestionAfterError=!!e,this}addCommand(e,t){if(!e._name)throw new Error("Command passed to .addCommand() must have a name\n- specify the name in Command constructor or using .name()");return(t=t||{}).isDefault&&(this._defaultCommandName=e._name),(t.noHelp||t.hidden)&&(e._hidden=!0),this._registerCommand(e),e.parent=this,e._checkForBrokenPassThrough(),this}createArgument(e,t){return new u(e,t)}argument(e,t,n,i){const r=this.createArgument(e,t);return"function"==typeof n?r.default(i).argParser(n):r.default(n),this.addArgument(r),this}arguments(e){return e.trim().split(/ +/).forEach(e=>{this.argument(e)}),this}addArgument(e){const t=this.registeredArguments.slice(-1)[0];if(t?.variadic)throw new Error(`only the last argument can be variadic '${t.name()}'`);if(e.required&&void 0!==e.defaultValue&&void 0===e.parseArg)throw new Error(`a default value for a required argument is never used: '${e.name()}'`);return this.registeredArguments.push(e),this}helpCommand(e,t){if("boolean"==typeof e)return this._addImplicitHelpCommand=e,e&&this._defaultCommandGroup&&this._initCommandGroup(this._getHelpCommand()),this;const n=e??"help [command]",[,i,r]=n.match(/([^ ]+) *(.*)/),o=t??"display help for command",s=this.createCommand(i);return s.helpOption(!1),r&&s.arguments(r),o&&s.description(o),this._addImplicitHelpCommand=!0,this._helpCommand=s,(e||t)&&this._initCommandGroup(s),this}addHelpCommand(e,t){return"object"!=typeof e?(this.helpCommand(e,t),this):(this._addImplicitHelpCommand=!0,this._helpCommand=e,this._initCommandGroup(e),this)}_getHelpCommand(){return this._addImplicitHelpCommand??(this.commands.length&&!this._actionHandler&&!this._findCommand("help"))?(void 0===this._helpCommand&&this.helpCommand(void 0,void 0),this._helpCommand):null}hook(e,t){const n=["preSubcommand","preAction","postAction"];if(!n.includes(e))throw new Error(`Unexpected value for event passed to hook : '${e}'.\nExpecting one of '${n.join("', '")}'`);return this._lifeCycleHooks[e]?this._lifeCycleHooks[e].push(t):this._lifeCycleHooks[e]=[t],this}exitOverride(e){return this._exitCallback=e||(e=>{if("commander.executeSubCommandAsync"!==e.code)throw e}),this}_exit(e,t,n){this._exitCallback&&this._exitCallback(new p(e,t,n)),l.exit(e)}action(e){return this._actionHandler=t=>{const n=this.registeredArguments.length,i=t.slice(0,n);return this._storeOptionsAsProperties?i[n]=this:i[n]=this.opts(),i.push(this),e.apply(this,i)},this}createOption(e,t){return new f(e,t)}_callParseArg(e,t,n,i){try{return e.parseArg(t,n)}catch(e){if("commander.invalidArgument"===e.code){const t=`${i} ${e.message}`;this.error(t,{exitCode:e.exitCode,code:e.code})}throw e}}_registerOption(e){const t=e.short&&this._findOption(e.short)||e.long&&this._findOption(e.long);if(t){const n=e.long&&this._findOption(e.long)?e.long:e.short;throw new Error(`Cannot add option '${e.flags}'${this._name&&` to command '${this._name}'`} due to conflicting flag '${n}'\n- already used by option '${t.flags}'`)}this._initOptionGroup(e),this.options.push(e)}_registerCommand(e){const t=e=>[e.name()].concat(e.aliases()),n=t(e).find(e=>this._findCommand(e));if(n){const i=t(this._findCommand(n)).join("|"),r=t(e).join("|");throw new Error(`cannot add command '${r}' as already have command '${i}'`)}this._initCommandGroup(e),this.commands.push(e)}addOption(e){this._registerOption(e);const t=e.name(),n=e.attributeName();if(e.negate){const t=e.long.replace(/^--no-/,"--");this._findOption(t)||this.setOptionValueWithSource(n,void 0===e.defaultValue||e.defaultValue,"default")}else void 0!==e.defaultValue&&this.setOptionValueWithSource(n,e.defaultValue,"default");const i=(t,i,r)=>{null==t&&void 0!==e.presetArg&&(t=e.presetArg);const o=this.getOptionValue(n);null!==t&&e.parseArg?t=this._callParseArg(e,t,o,i):null!==t&&e.variadic&&(t=e._collectValue(t,o)),null==t&&(t=!e.negate&&(!(!e.isBoolean()&&!e.optional)||"")),this.setOptionValueWithSource(n,t,r)};return this.on("option:"+t,t=>{const n=`error: option '${e.flags}' argument '${t}' is invalid.`;i(t,n,"cli")}),e.envVar&&this.on("optionEnv:"+t,t=>{const n=`error: option '${e.flags}' value '${t}' from env '${e.envVar}' is invalid.`;i(t,n,"env")}),this}_optionEx(e,t,n,i,r){if("object"==typeof t&&t instanceof f)throw new Error("To add an Option object use addOption() instead of option() or requiredOption()");const o=this.createOption(t,n);if(o.makeOptionMandatory(!!e.mandatory),"function"==typeof i)o.default(r).argParser(i);else if(i instanceof RegExp){const e=i;i=(t,n)=>{const i=e.exec(t);return i?i[0]:n},o.default(r).argParser(i)}else o.default(i);return this.addOption(o)}option(e,t,n,i){return this._optionEx({},e,t,n,i)}requiredOption(e,t,n,i){return this._optionEx({mandatory:!0},e,t,n,i)}combineFlagAndOptionalValue(e=!0){return this._combineFlagAndOptionalValue=!!e,this}allowUnknownOption(e=!0){return this._allowUnknownOption=!!e,this}allowExcessArguments(e=!0){return this._allowExcessArguments=!!e,this}enablePositionalOptions(e=!0){return this._enablePositionalOptions=!!e,this}passThroughOptions(e=!0){return this._passThroughOptions=!!e,this._checkForBrokenPassThrough(),this}_checkForBrokenPassThrough(){if(this.parent&&this._passThroughOptions&&!this.parent._enablePositionalOptions)throw new Error(`passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`)}storeOptionsAsProperties(e=!0){if(this.options.length)throw new Error("call .storeOptionsAsProperties() before adding options");if(Object.keys(this._optionValues).length)throw new Error("call .storeOptionsAsProperties() before setting option values");return this._storeOptionsAsProperties=!!e,this}getOptionValue(e){return this._storeOptionsAsProperties?this[e]:this._optionValues[e]}setOptionValue(e,t){return this.setOptionValueWithSource(e,t,void 0)}setOptionValueWithSource(e,t,n){return this._storeOptionsAsProperties?this[e]=t:this._optionValues[e]=t,this._optionValueSources[e]=n,this}getOptionValueSource(e){return this._optionValueSources[e]}getOptionValueSourceWithGlobals(e){let t;return this._getCommandAndAncestors().forEach(n=>{void 0!==n.getOptionValueSource(e)&&(t=n.getOptionValueSource(e))}),t}_prepareUserArgs(e,t){if(void 0!==e&&!Array.isArray(e))throw new Error("first parameter to parse must be array or undefined");if(t=t||{},void 0===e&&void 0===t.from){l.versions?.electron&&(t.from="electron");const e=l.execArgv??[];(e.includes("-e")||e.includes("--eval")||e.includes("-p")||e.includes("--print"))&&(t.from="eval")}let n;switch(void 0===e&&(e=l.argv),this.rawArgs=e.slice(),t.from){case void 0:case"node":this._scriptPath=e[1],n=e.slice(2);break;case"electron":l.defaultApp?(this._scriptPath=e[1],n=e.slice(2)):n=e.slice(1);break;case"user":n=e.slice(0);break;case"eval":n=e.slice(1);break;default:throw new Error(`unexpected parse option { from: '${t.from}' }`)}return!this._name&&this._scriptPath&&this.nameFromFilename(this._scriptPath),this._name=this._name||"program",n}parse(e,t){this._prepareForParse();const n=this._prepareUserArgs(e,t);return this._parseCommand([],n),this}async parseAsync(e,t){this._prepareForParse();const n=this._prepareUserArgs(e,t);return await this._parseCommand([],n),this}_prepareForParse(){null===this._savedState?this.saveStateBeforeParse():this.restoreStateBeforeParse()}saveStateBeforeParse(){this._savedState={_name:this._name,_optionValues:{...this._optionValues},_optionValueSources:{...this._optionValueSources}}}restoreStateBeforeParse(){if(this._storeOptionsAsProperties)throw new Error("Can not call parse again when storeOptionsAsProperties is true.\n- either make a new Command for each call to parse, or stop storing options as properties");this._name=this._savedState._name,this._scriptPath=null,this.rawArgs=[],this._optionValues={...this._savedState._optionValues},this._optionValueSources={...this._savedState._optionValueSources},this.args=[],this.processedArgs=[]}_checkForMissingExecutable(e,t,n){if(!c.existsSync(e))throw new Error(`'${e}' does not exist\n - if '${n}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead\n - if the default executable name is not suitable, use the executableFile option to supply a custom name or path\n - ${t?`searched for local subcommand relative to directory '${t}'`:"no directory for search for local subcommand, use .executableDir() to supply a custom directory"}`)}_executeSubCommand(e,t){t=t.slice();let n=!1;const i=[".js",".ts",".tsx",".mjs",".cjs"];function r(e,t){const n=a.resolve(e,t);if(c.existsSync(n))return n;if(i.includes(a.extname(t)))return;const r=i.find(e=>c.existsSync(`${n}${e}`));return r?`${n}${r}`:void 0}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let o,u=e._executableFile||`${this._name}-${e._name}`,d=this._executableDir||"";if(this._scriptPath){let e;try{e=c.realpathSync(this._scriptPath)}catch{e=this._scriptPath}d=a.resolve(a.dirname(e),d)}if(d){let t=r(d,u);if(!t&&!e._executableFile&&this._scriptPath){const n=a.basename(this._scriptPath,a.extname(this._scriptPath));n!==this._name&&(t=r(d,`${n}-${e._name}`))}u=t||u}n=i.includes(a.extname(u)),"win32"!==l.platform?n?(t.unshift(u),t=I(l.execArgv).concat(t),o=s.spawn(l.argv[0],t,{stdio:"inherit"})):o=s.spawn(u,t,{stdio:"inherit"}):(this._checkForMissingExecutable(u,d,e._name),t.unshift(u),t=I(l.execArgv).concat(t),o=s.spawn(l.execPath,t,{stdio:"inherit"})),o.killed||["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach(e=>{l.on(e,()=>{!1===o.killed&&null===o.exitCode&&o.kill(e)})});const m=this._exitCallback;o.on("close",e=>{e=e??1,m?m(new p(e,"commander.executeSubCommandAsync","(close)")):l.exit(e)}),o.on("error",t=>{if("ENOENT"===t.code)this._checkForMissingExecutable(u,d,e._name);else if("EACCES"===t.code)throw new Error(`'${u}' not executable`);if(m){const e=new p(1,"commander.executeSubCommandAsync","(error)");e.nestedError=t,m(e)}else l.exit(1)}),this.runningCommand=o}_dispatchSubcommand(e,t,n){const i=this._findCommand(e);let r;return i||this.help({error:!0}),i._prepareForParse(),r=this._chainOrCallSubCommandHook(r,i,"preSubcommand"),r=this._chainOrCall(r,()=>{if(!i._executableHandler)return i._parseCommand(t,n);this._executeSubCommand(i,t.concat(n))}),r}_dispatchHelpCommand(e){e||this.help();const t=this._findCommand(e);return t&&!t._executableHandler&&t.help(),this._dispatchSubcommand(e,[],[this._getHelpOption()?.long??this._getHelpOption()?.short??"--help"])}_checkNumberOfArguments(){this.registeredArguments.forEach((e,t)=>{e.required&&null==this.args[t]&&this.missingArgument(e.name())}),this.registeredArguments.length>0&&this.registeredArguments[this.registeredArguments.length-1].variadic||this.args.length>this.registeredArguments.length&&this._excessArguments(this.args)}_processArguments(){const e=(e,t,n)=>{let i=t;if(null!==t&&e.parseArg){const r=`error: command-argument value '${t}' is invalid for argument '${e.name()}'.`;i=this._callParseArg(e,t,n,r)}return i};this._checkNumberOfArguments();const t=[];this.registeredArguments.forEach((n,i)=>{let r=n.defaultValue;n.variadic?i<this.args.length?(r=this.args.slice(i),n.parseArg&&(r=r.reduce((t,i)=>e(n,i,t),n.defaultValue))):void 0===r&&(r=[]):i<this.args.length&&(r=this.args[i],n.parseArg&&(r=e(n,r,n.defaultValue))),t[i]=r}),this.processedArgs=t}_chainOrCall(e,t){return e?.then&&"function"==typeof e.then?e.then(()=>t()):t()}_chainOrCallHooks(e,t){let n=e;const i=[];return this._getCommandAndAncestors().reverse().filter(e=>void 0!==e._lifeCycleHooks[t]).forEach(e=>{e._lifeCycleHooks[t].forEach(t=>{i.push({hookedCommand:e,callback:t})})}),"postAction"===t&&i.reverse(),i.forEach(e=>{n=this._chainOrCall(n,()=>e.callback(e.hookedCommand,this))}),n}_chainOrCallSubCommandHook(e,t,n){let i=e;return void 0!==this._lifeCycleHooks[n]&&this._lifeCycleHooks[n].forEach(e=>{i=this._chainOrCall(i,()=>e(this,t))}),i}_parseCommand(e,t){const n=this.parseOptions(t);if(this._parseOptionsEnv(),this._parseOptionsImplied(),e=e.concat(n.operands),t=n.unknown,this.args=e.concat(t),e&&this._findCommand(e[0]))return this._dispatchSubcommand(e[0],e.slice(1),t);if(this._getHelpCommand()&&e[0]===this._getHelpCommand().name())return this._dispatchHelpCommand(e[1]);if(this._defaultCommandName)return this._outputHelpIfRequested(t),this._dispatchSubcommand(this._defaultCommandName,e,t);!this.commands.length||0!==this.args.length||this._actionHandler||this._defaultCommandName||this.help({error:!0}),this._outputHelpIfRequested(n.unknown),this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();const i=()=>{n.unknown.length>0&&this.unknownOption(n.unknown[0])},r=`command:${this.name()}`;if(this._actionHandler){let n;return i(),this._processArguments(),n=this._chainOrCallHooks(n,"preAction"),n=this._chainOrCall(n,()=>this._actionHandler(this.processedArgs)),this.parent&&(n=this._chainOrCall(n,()=>{this.parent.emit(r,e,t)})),n=this._chainOrCallHooks(n,"postAction"),n}if(this.parent?.listenerCount(r))i(),this._processArguments(),this.parent.emit(r,e,t);else if(e.length){if(this._findCommand("*"))return this._dispatchSubcommand("*",e,t);this.listenerCount("command:*")?this.emit("command:*",e,t):this.commands.length?this.unknownCommand():(i(),this._processArguments())}else this.commands.length?(i(),this.help({error:!0})):(i(),this._processArguments())}_findCommand(e){if(e)return this.commands.find(t=>t._name===e||t._aliases.includes(e))}_findOption(e){return this.options.find(t=>t.is(e))}_checkForMissingMandatoryOptions(){this._getCommandAndAncestors().forEach(e=>{e.options.forEach(t=>{t.mandatory&&void 0===e.getOptionValue(t.attributeName())&&e.missingMandatoryOptionValue(t)})})}_checkForConflictingLocalOptions(){const e=this.options.filter(e=>{const t=e.attributeName();return void 0!==this.getOptionValue(t)&&"default"!==this.getOptionValueSource(t)}),t=e.filter(e=>e.conflictsWith.length>0);t.forEach(t=>{const n=e.find(e=>t.conflictsWith.includes(e.attributeName()));n&&this._conflictingOption(t,n)})}_checkForConflictingOptions(){this._getCommandAndAncestors().forEach(e=>{e._checkForConflictingLocalOptions()})}parseOptions(e){const t=[],n=[];let i=t;function r(e){return e.length>1&&"-"===e[0]}const o=e=>!!/^-(\d+|\d*\.\d+)(e[+-]?\d+)?$/.test(e)&&!this._getCommandAndAncestors().some(e=>e.options.map(e=>e.short).some(e=>/^-\d$/.test(e)));let s=null,a=null,c=0;for(;c<e.length||a;){const l=a??e[c++];if(a=null,"--"===l){i===n&&i.push(l),i.push(...e.slice(c));break}if(!s||r(l)&&!o(l)){if(s=null,r(l)){const t=this._findOption(l);if(t){if(t.required){const n=e[c++];void 0===n&&this.optionMissingArgument(t),this.emit(`option:${t.name()}`,n)}else if(t.optional){let n=null;c<e.length&&(!r(e[c])||o(e[c]))&&(n=e[c++]),this.emit(`option:${t.name()}`,n)}else this.emit(`option:${t.name()}`);s=t.variadic?t:null;continue}}if(l.length>2&&"-"===l[0]&&"-"!==l[1]){const e=this._findOption(`-${l[1]}`);if(e){e.required||e.optional&&this._combineFlagAndOptionalValue?this.emit(`option:${e.name()}`,l.slice(2)):(this.emit(`option:${e.name()}`),a=`-${l.slice(2)}`);continue}}if(/^--[^=]+=/.test(l)){const e=l.indexOf("="),t=this._findOption(l.slice(0,e));if(t&&(t.required||t.optional)){this.emit(`option:${t.name()}`,l.slice(e+1));continue}}if(i!==t||!r(l)||0===this.commands.length&&o(l)||(i=n),(this._enablePositionalOptions||this._passThroughOptions)&&0===t.length&&0===n.length){if(this._findCommand(l)){t.push(l),n.push(...e.slice(c));break}if(this._getHelpCommand()&&l===this._getHelpCommand().name()){t.push(l,...e.slice(c));break}if(this._defaultCommandName){n.push(l,...e.slice(c));break}}if(this._passThroughOptions){i.push(l,...e.slice(c));break}i.push(l)}else this.emit(`option:${s.name()}`,l)}return{operands:t,unknown:n}}opts(){if(this._storeOptionsAsProperties){const e={},t=this.options.length;for(let n=0;n<t;n++){const t=this.options[n].attributeName();e[t]=t===this._versionOptionName?this._version:this[t]}return e}return this._optionValues}optsWithGlobals(){return this._getCommandAndAncestors().reduce((e,t)=>Object.assign(e,t.opts()),{})}error(e,t){this._outputConfiguration.outputError(`${e}\n`,this._outputConfiguration.writeErr),"string"==typeof this._showHelpAfterError?this._outputConfiguration.writeErr(`${this._showHelpAfterError}\n`):this._showHelpAfterError&&(this._outputConfiguration.writeErr("\n"),this.outputHelp({error:!0}));const n=t||{},i=n.exitCode||1,r=n.code||"commander.error";this._exit(i,r,e)}_parseOptionsEnv(){this.options.forEach(e=>{if(e.envVar&&e.envVar in l.env){const t=e.attributeName();(void 0===this.getOptionValue(t)||["default","config","env"].includes(this.getOptionValueSource(t)))&&(e.required||e.optional?this.emit(`optionEnv:${e.name()}`,l.env[e.envVar]):this.emit(`optionEnv:${e.name()}`))}})}_parseOptionsImplied(){const e=new g(this.options),t=e=>void 0!==this.getOptionValue(e)&&!["default","implied"].includes(this.getOptionValueSource(e));this.options.filter(n=>void 0!==n.implied&&t(n.attributeName())&&e.valueFromOption(this.getOptionValue(n.attributeName()),n)).forEach(e=>{Object.keys(e.implied).filter(e=>!t(e)).forEach(t=>{this.setOptionValueWithSource(t,e.implied[t],"implied")})})}missingArgument(e){const t=`error: missing required argument '${e}'`;this.error(t,{code:"commander.missingArgument"})}optionMissingArgument(e){const t=`error: option '${e.flags}' argument missing`;this.error(t,{code:"commander.optionMissingArgument"})}missingMandatoryOptionValue(e){const t=`error: required option '${e.flags}' not specified`;this.error(t,{code:"commander.missingMandatoryOptionValue"})}_conflictingOption(e,t){const n=e=>{const t=e.attributeName(),n=this.getOptionValue(t),i=this.options.find(e=>e.negate&&t===e.attributeName()),r=this.options.find(e=>!e.negate&&t===e.attributeName());return i&&(void 0===i.presetArg&&!1===n||void 0!==i.presetArg&&n===i.presetArg)?i:r||e},i=e=>{const t=n(e),i=t.attributeName();return"env"===this.getOptionValueSource(i)?`environment variable '${t.envVar}'`:`option '${t.flags}'`},r=`error: ${i(e)} cannot be used with ${i(t)}`;this.error(r,{code:"commander.conflictingOption"})}unknownOption(e){if(this._allowUnknownOption)return;let t="";if(e.startsWith("--")&&this._showSuggestionAfterError){let n=[],i=this;do{const e=i.createHelp().visibleOptions(i).filter(e=>e.long).map(e=>e.long);n=n.concat(e),i=i.parent}while(i&&!i._enablePositionalOptions);t=y(e,n)}const n=`error: unknown option '${e}'${t}`;this.error(n,{code:"commander.unknownOption"})}_excessArguments(e){if(this._allowExcessArguments)return;const t=this.registeredArguments.length,n=1===t?"":"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(){const e=this.args[0];let t="";if(this._showSuggestionAfterError){const n=[];this.createHelp().visibleCommands(this).forEach(e=>{n.push(e.name()),e.alias()&&n.push(e.alias())}),t=y(e,n)}const n=`error: unknown command '${e}'${t}`;this.error(n,{code:"commander.unknownCommand"})}version(e,t,n){if(void 0===e)return this._version;this._version=e,t=t||"-V, --version",n=n||"output the version number";const i=this.createOption(t,n);return this._versionOptionName=i.attributeName(),this._registerOption(i),this.on("option:"+i.name(),()=>{this._outputConfiguration.writeOut(`${e}\n`),this._exit(0,"commander.version",e)}),this}description(e,t){return void 0===e&&void 0===t?this._description:(this._description=e,t&&(this._argsDescription=t),this)}summary(e){return void 0===e?this._summary:(this._summary=e,this)}alias(e){if(void 0===e)return this._aliases[0];let t=this;if(0!==this.commands.length&&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");const n=this.parent?._findCommand(e);if(n){const t=[n.name()].concat(n.aliases()).join("|");throw new Error(`cannot add alias '${e}' to command '${this.name()}' as already have command '${t}'`)}return t._aliases.push(e),this}aliases(e){return void 0===e?this._aliases:(e.forEach(e=>this.alias(e)),this)}usage(e){if(void 0===e){if(this._usage)return this._usage;const e=this.registeredArguments.map(e=>d(e));return[].concat(this.options.length||null!==this._helpOption?"[options]":[],this.commands.length?"[command]":[],this.registeredArguments.length?e:[]).join(" ")}return this._usage=e,this}name(e){return void 0===e?this._name:(this._name=e,this)}helpGroup(e){return void 0===e?this._helpGroupHeading??"":(this._helpGroupHeading=e,this)}commandsGroup(e){return void 0===e?this._defaultCommandGroup??"":(this._defaultCommandGroup=e,this)}optionsGroup(e){return void 0===e?this._defaultOptionGroup??"":(this._defaultOptionGroup=e,this)}_initOptionGroup(e){this._defaultOptionGroup&&!e.helpGroupHeading&&e.helpGroup(this._defaultOptionGroup)}_initCommandGroup(e){this._defaultCommandGroup&&!e.helpGroup()&&e.helpGroup(this._defaultCommandGroup)}nameFromFilename(e){return this._name=a.basename(e,a.extname(e)),this}executableDir(e){return void 0===e?this._executableDir:(this._executableDir=e,this)}helpInformation(e){const t=this.createHelp(),n=this._getOutputContext(e);t.prepareContext({error:n.error,helpWidth:n.helpWidth,outputHasColors:n.hasColors});const i=t.formatHelp(this,t);return n.hasColors?i:this._outputConfiguration.stripColor(i)}_getOutputContext(e){const t=!!(e=e||{}).error;let n,i,r;return t?(n=e=>this._outputConfiguration.writeErr(e),i=this._outputConfiguration.getErrHasColors(),r=this._outputConfiguration.getErrHelpWidth()):(n=e=>this._outputConfiguration.writeOut(e),i=this._outputConfiguration.getOutHasColors(),r=this._outputConfiguration.getOutHelpWidth()),{error:t,write:e=>(i||(e=this._outputConfiguration.stripColor(e)),n(e)),hasColors:i,helpWidth:r}}outputHelp(e){let t;"function"==typeof e&&(t=e,e=void 0);const n=this._getOutputContext(e),i={error:n.error,write:n.write,command:this};this._getCommandAndAncestors().reverse().forEach(e=>e.emit("beforeAllHelp",i)),this.emit("beforeHelp",i);let r=this.helpInformation({error:n.error});if(t&&(r=t(r),"string"!=typeof r&&!Buffer.isBuffer(r)))throw new Error("outputHelp callback must return a string or a Buffer");n.write(r),this._getHelpOption()?.long&&this.emit(this._getHelpOption().long),this.emit("afterHelp",i),this._getCommandAndAncestors().forEach(e=>e.emit("afterAllHelp",i))}helpOption(e,t){return"boolean"==typeof e?(e?(null===this._helpOption&&(this._helpOption=void 0),this._defaultOptionGroup&&this._initOptionGroup(this._getHelpOption())):this._helpOption=null,this):(this._helpOption=this.createOption(e??"-h, --help",t??"display help for command"),(e||t)&&this._initOptionGroup(this._helpOption),this)}_getHelpOption(){return void 0===this._helpOption&&this.helpOption(void 0,void 0),this._helpOption}addHelpOption(e){return this._helpOption=e,this._initOptionGroup(e),this}help(e){this.outputHelp(e);let t=Number(l.exitCode??0);0===t&&e&&"function"!=typeof e&&e.error&&(t=1),this._exit(t,"commander.help","(outputHelp)")}addHelpText(e,t){const n=["beforeAll","before","after","afterAll"];if(!n.includes(e))throw new Error(`Unexpected value for position to addHelpText.\nExpecting one of '${n.join("', '")}'`);const i=`${e}Help`;return this.on(i,e=>{let n;n="function"==typeof t?t({error:e.error,command:e.command}):t,n&&e.write(`${n}\n`)}),this}_outputHelpIfRequested(e){const t=this._getHelpOption();t&&e.find(e=>t.is(e))&&(this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)"))}}function I(e){return e.map(e=>{if(!e.startsWith("--inspect"))return e;let t,n,i="127.0.0.1",r="9229";return null!==(n=e.match(/^(--inspect(-brk)?)$/))?t=n[1]:null!==(n=e.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))?(t=n[1],/^\d+$/.test(n[3])?r=n[3]:i=n[3]):null!==(n=e.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))&&(t=n[1],i=n[3],r=n[4]),t&&"0"!==r?`${t}=${i}:${parseInt(r)+1}`:e})}function S(){return!l.env.NO_COLOR&&"0"!==l.env.FORCE_COLOR&&"false"!==l.env.FORCE_COLOR&&(!(!l.env.FORCE_COLOR&&void 0===l.env.CLICOLOR_FORCE)||void 0)}return A.Command=b,A.useColor=S,A}(),{CommanderError:a,InvalidArgumentError:c}=v(),{Help:l}=x(),{Option:u}=E();return f.program=new s,f.createCommand=e=>new s(e),f.createOption=(e,t)=>new u(e,t),f.createArgument=(e,t)=>new o(e,t),f.Command=s,f.Option=u,f.Argument=o,f.Help=l,f.CommanderError=a,f.InvalidArgumentError=c,f.InvalidOptionArgumentError=c,f}(),g=jt(),y=function(){if(Ft)return Ut.exports;Ft=1,Ut.exports=async function(t,o,s,a){s instanceof Function&&(a=s,s={});const c=async function(t,o,s={}){let a,c;"string"==typeof s&&(s={encoding:s});const u=n(m(()=>c)),d=i.resolve(t);try{await function(e){return new Promise(t=>{l[e]||(l[e]=[]),l[e].push(t),1===l[e].length&&t()})}(d);const n=await r(e.realpath)(t).catch(()=>t);if(c=p(n),!s.mode||!s.chown){const t=await r(e.stat)(n).catch(()=>{});t&&(null==s.mode&&(s.mode=t.mode),null==s.chown&&process.getuid&&(s.chown={uid:t.uid,gid:t.gid}))}a=await r(e.open)(c,"w",s.mode),s.tmpfileCreated&&await s.tmpfileCreated(c),ArrayBuffer.isView(o)?await r(e.write)(a,o,0,o.length,0):null!=o&&await r(e.write)(a,String(o),0,String(s.encoding||"utf8")),!1!==s.fsync&&await r(e.fsync)(a),await r(e.close)(a),a=null,s.chown&&await r(e.chown)(c,s.chown.uid,s.chown.gid).catch(e=>{if(!h(e))throw e}),s.mode&&await r(e.chmod)(c,s.mode).catch(e=>{if(!h(e))throw e}),await r(e.rename)(c,n)}finally{a&&await r(e.close)(a).catch(()=>{}),u(),await r(e.unlink)(c).catch(()=>{}),l[d].shift(),l[d].length>0?l[d][0]():delete l[d]}}(t,o,s);if(a)try{return a(await c)}catch(e){return a(e)}return c},Ut.exports.sync=function(t,i,r){"string"==typeof r?r={encoding:r}:r||(r={});try{t=e.realpathSync(t)}catch(e){}const o=p(t);if(!r.mode||!r.chown)try{const n=e.statSync(t);(r=Object.assign({},r)).mode||(r.mode=n.mode),!r.chown&&process.getuid&&(r.chown={uid:n.uid,gid:n.gid})}catch(e){}let s;const a=m(o),c=n(a);let l=!0;try{if(s=e.openSync(o,"w",r.mode||438),r.tmpfileCreated&&r.tmpfileCreated(o),ArrayBuffer.isView(i)?e.writeSync(s,i,0,i.length,0):null!=i&&e.writeSync(s,String(i),0,String(r.encoding||"utf8")),!1!==r.fsync&&e.fsyncSync(s),e.closeSync(s),s=null,r.chown)try{e.chownSync(o,r.chown.uid,r.chown.gid)}catch(e){if(!h(e))throw e}if(r.mode)try{e.chmodSync(o,r.mode)}catch(e){if(!h(e))throw e}e.renameSync(o,t),l=!1}finally{if(s)try{e.closeSync(s)}catch(e){}c(),l&&a()}},Ut.exports._getTmpname=p,Ut.exports._cleanupOnExit=m;const e=o,t=s,{onExit:n}=(Mt||(Mt=1,function(e){var t;Object.defineProperty(e,"__esModule",{value:!0}),e.unload=e.load=e.onExit=e.signals=void 0;const n=Zt();Object.defineProperty(e,"signals",{enumerable:!0,get:function(){return n.signals}});const i=e=>!!e&&"object"==typeof e&&"function"==typeof e.removeListener&&"function"==typeof e.emit&&"function"==typeof e.reallyExit&&"function"==typeof e.listeners&&"function"==typeof e.kill&&"number"==typeof e.pid&&"function"==typeof e.on,r=Symbol.for("signal-exit emitter"),o=globalThis,s=Object.defineProperty.bind(Object);class a{emitted={afterExit:!1,exit:!1};listeners={afterExit:[],exit:[]};count=0;id=Math.random();constructor(){if(o[r])return o[r];s(o,r,{value:this,writable:!1,enumerable:!1,configurable:!1})}on(e,t){this.listeners[e].push(t)}removeListener(e,t){const n=this.listeners[e],i=n.indexOf(t);-1!==i&&(0===i&&1===n.length?n.length=0:n.splice(i,1))}emit(e,t,n){if(this.emitted[e])return!1;this.emitted[e]=!0;let i=!1;for(const r of this.listeners[e])i=!0===r(t,n)||i;return"exit"===e&&(i=this.emit("afterExit",t,n)||i),i}}class c{}const l=globalThis.process;var u;u=i(l)?new class extends c{#e="win32"===l.platform?"SIGINT":"SIGHUP";#t=new a;#n;#i;#r;#o={};#s=!1;constructor(e){super(),this.#n=e,this.#o={};for(const t of n.signals)this.#o[t]=()=>{const n=this.#n.listeners(t);let{count:i}=this.#t;const r=e;if("object"==typeof r.__signal_exit_emitter__&&"number"==typeof r.__signal_exit_emitter__.count&&(i+=r.__signal_exit_emitter__.count),n.length===i){this.unload();const n=this.#t.emit("exit",null,t),i="SIGHUP"===t?this.#e:t;n||e.kill(e.pid,i)}};this.#r=e.reallyExit,this.#i=e.emit}onExit(e,t){if(!i(this.#n))return()=>{};!1===this.#s&&this.load();const n=t?.alwaysLast?"afterExit":"exit";return this.#t.on(n,e),()=>{this.#t.removeListener(n,e),0===this.#t.listeners.exit.length&&0===this.#t.listeners.afterExit.length&&this.unload()}}load(){if(!this.#s){this.#s=!0,this.#t.count+=1;for(const e of n.signals)try{const t=this.#o[e];t&&this.#n.on(e,t)}catch(e){}this.#n.emit=(e,...t)=>this.#a(e,...t),this.#n.reallyExit=e=>this.#c(e)}}unload(){this.#s&&(this.#s=!1,n.signals.forEach(e=>{const t=this.#o[e];if(!t)throw new Error("Listener not defined for signal: "+e);try{this.#n.removeListener(e,t)}catch(e){}}),this.#n.emit=this.#i,this.#n.reallyExit=this.#r,this.#t.count-=1)}#c(e){return i(this.#n)?(this.#n.exitCode=e||0,this.#t.emit("exit",this.#n.exitCode,null),this.#r.call(this.#n,this.#n.exitCode)):0}#a(e,...t){const n=this.#i;if("exit"===e&&i(this.#n)){"number"==typeof t[0]&&(this.#n.exitCode=t[0]);const i=n.call(this.#n,e,...t);return this.#t.emit("exit",this.#n.exitCode,null),i}return n.call(this.#n,e,...t)}}(l):new class extends c{onExit(){return()=>{}}load(){}unload(){}},t={onExit:(e,t)=>u.onExit(e,t),load:()=>u.load(),unload:()=>u.unload()},e.onExit=t.onExit,e.load=t.load,e.unload=t.unload}(Ht)),Ht),i=a,{promisify:r}=c,l={},u=function(){try{return require("worker_threads").threadId}catch(e){return 0}}();let d=0;function p(e){return e+"."+t.createHash("sha1").update(__filename).update(String(process.pid)).update(String(u)).update(String(++d)).digest().readUInt32BE(0)}function m(t){return()=>{try{e.unlinkSync("function"==typeof t?t():t)}catch{}}}function h(e){return"ENOSYS"===e.code||!(process.getuid&&0===process.getuid()||"EINVAL"!==e.code&&"EPERM"!==e.code)}return Ut.exports}(),{ControlPlaneHealthResponseSchema:b}=Ld,{acquireServerUpdateLock:I,cleanUpServerUpdateLockOnSignals:S,globalPrefixFromModulePath:w}=sp;function O(e){const t=b.safeParse(e);return t.success?t.data.data.build.packageVersion:void 0}function T(e){if(!u.isAbsolute(e))throw new m("must be an absolute path");return u.resolve(e)}const N=(new p).name("task-handoff-node-update-worker").description("Apply a detached TaskHandoff node update.").requiredOption("--job-file <path>","persisted update job file").requiredOption("--target-version <version>","exact semantic version",function(e){if(e.trim()!==e||/^[v=]/.test(e)||null===g.valid(e))throw new m("must be an exact semantic version");return e}).option("--service <name>","systemd service to restart","task-handoff-node-agent.service").option("--npm-command <path>","npm executable",process.env.TASK_HANDOFF_NPM_COMMAND||"npm").option("--control-plane-health-url <url>","local control-plane health endpoint",function(e){let t;try{t=new URL(e)}catch{throw new m("must be a valid loopback HTTP URL")}if(!["http:","https:"].includes(t.protocol)||!["127.0.0.1","localhost","::1"].includes(t.hostname))throw new m("must be a valid loopback HTTP URL");return t.toString()}).option("--install-prefix <path>","authoritative npm global prefix",T).option("--node-agent-ipc-path <path>","node-agent readiness socket",T).option("--registry <url>","npm registry URL").option("--standalone","complete the temporary job after service verification").parse(process.argv).opts(),R=N.jobFile,P=N.targetVersion,z=N.service,L=N.npmCommand,j=N.controlPlaneHealthUrl,D=N.installPrefix,M=N.nodeAgentIpcPath,F=N.registry,V=new Set(["succeeded","degraded","failed"]),U=new Set(["@task-handoff/node-agent","@task-handoff/server"]),H=["/etc/task-handoff/control-plane.env","/etc/task-handoff/node-agent.env","/etc/systemd/system/task-handoff-control-plane.service","/etc/systemd/system/task-handoff-node-agent.service"];function G(e,t){const n=JSON.parse(l.readFileSync(R,"utf8"));process.env.TASK_HANDOFF_UPDATE_WORKER_TEST_CAS_HOOK&&function(e){throw new Error('Could not dynamically require "'+e+'". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.')}(u.resolve(process.env.TASK_HANDOFF_UPDATE_WORKER_TEST_CAS_HOOK))({jobFile:R,observed:n});const i=`${R}.worker-lock`;l.mkdirSync(i);try{const n=JSON.parse(l.readFileSync(R,"utf8"));if(V.has(n.status)||!e.includes(n.status))return!1;const i="function"==typeof t?t(n):t,r={...n,...i,updatedAt:(new Date).toISOString()};return y.sync(R,`${JSON.stringify(r,null,2)}\n`,{encoding:"utf8"}),!0}finally{l.rmdirSync(i)}}function Z(e,t){const n=d(e,t,{stdio:"inherit"});if(0!==n.status)throw new Error(`${e} exited with status ${n.status??"unknown"}`)}function q(e,t,n){const i=n?u.join(t,...n.split("/"),"node_modules",...e.split("/"),"package.json"):u.join(t,...e.split("/"),"package.json");try{return JSON.parse(l.readFileSync(i,"utf8")).version}catch(e){if("ENOENT"===e?.code)return;throw e}}function B(e,t){const n=q(e,t);if(n!==P)throw new Error(`Updated ${e} verification failed: expected ${P}, found ${n||"unknown"}.`)}function W(e){const t=["view",`${e}@${P}`,"dist.integrity","--json"];F&&t.push("--registry",F);const n=d(L,t,{encoding:"utf8"});if(0!==n.status)throw new Error(`Could not verify the ${e} npm artifact integrity.`);let i;try{i=JSON.parse(n.stdout)}catch{throw new Error(`npm returned invalid ${e} artifact integrity metadata.`)}if("string"!=typeof i||!/^sha(?:256|384|512)-[A-Za-z0-9+/=]+$/.test(i))throw new Error(`npm returned invalid ${e} artifact integrity metadata.`);return i}async function J(e,t=P,n=6e4){const i=Date.now()+n;let r="not reachable";for(;Date.now()<i;){try{if(process.env.TASK_HANDOFF_UPDATE_WORKER_TEST_HEALTH_FILE){const e=O(JSON.parse(l.readFileSync(process.env.TASK_HANDOFF_UPDATE_WORKER_TEST_HEALTH_FILE,"utf8")));if(e===t)return;r=`reported version ${String(e||"unknown")}`,await new Promise(e=>setTimeout(e,10));continue}const n=await fetch(e,{headers:{"cache-control":"no-cache"},signal:AbortSignal.timeout(2e3)}),i=O(await n.json().catch(()=>({})));if(n.ok&&i===t)return;r=n.ok?`reported version ${String(i||"unknown")}`:`returned HTTP ${n.status}`}catch(e){r=e instanceof Error?e.message:String(e)}await new Promise(e=>setTimeout(e,500))}throw new Error(`Control plane did not become healthy at ${e} with version ${t}: ${r}.`)}function X(e,t=3e4){const n=Date.now()+t;for(;Date.now()<n;){try{if(l.statSync(e).isSocket())return}catch{}Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,250)}throw new Error(`Node agent socket was not ready after ${t}ms: ${e}`)}function Y(e,t,n){const i=["install","--global","--prefix",e,`${t}@${n}`];F&&i.push("--registry",F),Z(L,i)}return async function(){let e,t,n;try{if(!G(["queued"],e=>({status:"updating-node",rollout:{...e.rollout,phase:"updating-node"},startedAt:(new Date).toISOString(),error:void 0})))return;e=I(process.env.TASK_HANDOFF_SERVER_UPDATE_LOCK_PATH||void 0),t=S(e);const i=function(){const e=JSON.parse(l.readFileSync(R,"utf8")),t=`@${P}#`;if("string"!=typeof e.artifactRef||!e.artifactRef.startsWith("npm:")||!e.artifactRef.includes(t))throw new Error(`Update job does not pin npm integrity for version ${P}.`);const n=e.artifactRef.indexOf(t),i=e.artifactRef.slice(4,n),r=e.artifactRef.slice(n+t.length);if(!U.has(i)||!r)throw new Error("Update job does not identify a supported immutable npm artifact.");const o=W(i);if(o!==r)throw new Error(`${i} npm artifact integrity mismatch: expected ${r}, found ${String(o||"unknown")}.`);return{packageName:i,integrity:o}}(),r=i.packageName,o=w(process.argv[1]);if(D&&o&&D!==o)throw Object.assign(new Error(`Update prefix ${D} does not match the running package prefix ${o}.`),{code:"UPDATE_INSTALL_PREFIX_MISMATCH"});const s=o?void 0:d(L,["prefix","--global"],{encoding:"utf8"});if(s&&0!==s.status)throw new Error("Could not determine the npm global prefix.");const a=D||o||s?.stdout.trim();if(!a)throw new Error("Could not determine the npm global prefix.");const c=d(L,["root","--global","--prefix",a],{encoding:"utf8"});if(0!==c.status)throw new Error("Could not determine the npm global module root.");const p=c.stdout.trim(),m=[r];"@task-handoff/server"===r&&void 0!==q("@task-handoff/node-agent",p)&&m.push("@task-handoff/node-agent");const h=new Map(m.map(e=>[e,q(e,p)])),f="@task-handoff/server"===r?function(){const e=process.env.TASK_HANDOFF_UPDATE_WORKER_TEST_CONFIGURATION_ROOT;return e?H.map(t=>u.join(e,t.slice(1))):H}().map(e=>{try{const t=l.statSync(e);return{file:e,contents:l.readFileSync(e),mode:t.mode}}catch(t){if("ENOENT"===t?.code)return{file:e};throw t}}):[];let g=!1;n=async()=>{for(const e of[...m].reverse()){const t=h.get(e);t&&Y(a,e,t)}if("@task-handoff/server"===r){g&&(function(e){for(const t of e)t.contents?(l.mkdirSync(u.dirname(t.file),{recursive:!0}),y.sync(t.file,t.contents,{mode:t.mode})):l.rmSync(t.file,{force:!0})}(f),Z("systemctl",["daemon-reload"])),Z("systemctl",["restart","task-handoff-control-plane.service"]);const e=h.get("@task-handoff/server");j&&e&&await J(j,e)}Z("systemctl",["restart",z]),M&&X(M)};const v=new Map([[r,i.integrity]]);for(const e of m.slice(1))v.set(e,W(e));for(const e of m){if(Y(a,e,P),W(e)!==v.get(e))throw new Error(`${e} npm artifact integrity changed during installation.`);B(e,p)}if("@task-handoff/server"===r){if(function(e){for(const t of["@task-handoff/control-plane","@task-handoff/node-agent","@task-handoff/controlled-instance"]){const n=q(t,e,"@task-handoff/server")||q(t,e);if(n!==P)throw new Error(`Updated @task-handoff/server does not provide ${t} ${P}; found ${n||"unknown"}.`)}}(p),!j)throw new Error("A control-plane health URL is required for a complete server update.");g=!0,function(e){Z(u.join(e,"bin","task-handoff"),["install","--preserve-current","--materialize-only"])}(a),Z("systemctl",["restart","task-handoff-control-plane.service"]),await J(j)}if(!G(["updating-node"],e=>({status:"restarting-node",rollout:{...e.rollout,phase:"restarting-node"}})))return;Z("systemctl",["restart",z]),M&&X(M),N.standalone&&G(["restarting-node"],e=>({status:"succeeded",rollout:{...e.rollout,phase:"succeeded",nodeVersion:P},completedAt:(new Date).toISOString()}))}catch(e){let t;if(n)try{await n()}catch(e){t=e}const i=[e instanceof Error?e.message:String(e),t?`Rollback failed: ${t instanceof Error?t.message:String(t)}`:void 0].filter(Boolean).join(" ");G(["queued","updating-node","restarting-node"],t=>({status:"failed",rollout:{...t.rollout,phase:"failed"},error:{code:e&&"object"==typeof e&&"code"in e&&"string"==typeof e.code?e.code:"NODE_UPDATE_FAILED",message:i,retryable:e&&"object"==typeof e&&"code"in e&&"SERVER_UPDATE_ALREADY_RUNNING"===e.code},completedAt:(new Date).toISOString()})),console.error(e),process.exitCode=1}finally{t?.(),e?.()}}(),h}(),cp=u(ap);module.exports=cp;
|