@linzumi/cli 1.0.275 → 1.0.276

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/README.md +10 -9
  2. package/dist/{impl-ts/cloud-supervisor.mjs → cloud-supervisor.mjs} +78 -78
  3. package/dist/hosted-coding-account-worker.js +25 -0
  4. package/dist/index.js +1609 -3
  5. package/dist/mcp-server.mjs +174 -168
  6. package/dist/{impl-res/native → native}/darwin/manifest.json +5 -2
  7. package/dist/remote-codex-harness-worker.js +757 -0
  8. package/dist/tcp-tunnel-cli.mjs +25 -69
  9. package/dist/topics-cli.mjs +137 -13
  10. package/package.json +9 -16
  11. package/scripts/build.mjs +33 -356
  12. package/scripts/bump-cli-version.mjs +35 -9
  13. package/scripts/check-package-size-budget.mjs +13 -61
  14. package/dist/impl-res/cloud-supervisor.mjs +0 -281
  15. package/dist/impl-res/index.js +0 -1546
  16. package/dist/impl-res/mcp-server.mjs +0 -461
  17. package/dist/impl-ts/assets/linzumi-logo.svg +0 -1
  18. package/dist/impl-ts/crossHarnessFailover.mjs +0 -14
  19. package/dist/impl-ts/index.js +0 -2617
  20. package/dist/impl-ts/mcp-server.mjs +0 -455
  21. package/dist/impl-ts/native/darwin/manifest.json +0 -21
  22. package/dist/impl-ts/native/darwin/preview-process-identity +0 -0
  23. package/dist/impl-ts/tcp-tunnel-cli.mjs +0 -93
  24. package/scripts/build-differential-entry-impl-res.mjs +0 -64
  25. package/scripts/build-differential-entry.mjs +0 -180
  26. package/scripts/build-onboarding-demo-evidence.mjs +0 -186
  27. package/scripts/build-tui-demo-evidence.mjs +0 -107
  28. package/scripts/diagnose-claude-probe.ts +0 -198
  29. package/scripts/differentialMutations.mjs +0 -114
  30. package/scripts/f5_live_cross_harness_failover_e2e.mjs +0 -239
  31. package/scripts/golden-chaos-harness.mjs +0 -1420
  32. package/scripts/normalize-agent-replay-fixture.ts +0 -281
  33. package/scripts/promote-gstack-claude-smoke-fixture.ts +0 -891
  34. package/scripts/record-agent-replay-fixtures.ts +0 -610
  35. package/scripts/replay-agent-backend-browser.ts +0 -198
  36. package/scripts/replay-agent-backend.ts +0 -1961
  37. package/scripts/replay-agent-fixture.ts +0 -326
  38. package/scripts/typecheck.mjs +0 -42
  39. /package/dist/{impl-res/assets → assets}/linzumi-logo.svg +0 -0
  40. /package/dist/{impl-res/crossHarnessFailover.mjs → crossHarnessFailover.mjs} +0 -0
  41. /package/dist/{impl-res/native → native}/darwin/preview-process-identity +0 -0
@@ -1,455 +0,0 @@
1
- import { createRequire as __linzumiBundleCreateRequire } from 'node:module';
2
- const require = __linzumiBundleCreateRequire(import.meta.url);
3
- var Yb=Object.create;var Vs=Object.defineProperty;var Xb=Object.getOwnPropertyDescriptor;var ev=Object.getOwnPropertyNames;var tv=Object.getPrototypeOf,rv=Object.prototype.hasOwnProperty;var T=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),Ws=(e,t)=>{for(var r in t)Vs(e,r,{get:t[r],enumerable:!0})},nv=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of ev(t))!rv.call(e,o)&&o!==r&&Vs(e,o,{get:()=>t[o],enumerable:!(n=Xb(t,o))||n.enumerable});return e};var sp=(e,t,r)=>(r=e!=null?Yb(tv(e)):{},nv(t||!e||!e.__esModule?Vs(r,"default",{value:e,enumerable:!0}):r,e));var ao=T(X=>{"use strict";Object.defineProperty(X,"__esModule",{value:!0});X.regexpCode=X.getEsmExportName=X.getProperty=X.safeStringify=X.stringify=X.strConcat=X.addCodeArg=X.str=X._=X.nil=X._Code=X.Name=X.IDENTIFIER=X._CodeOrName=void 0;var io=class{};X._CodeOrName=io;X.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var Rr=class extends io{constructor(t){if(super(),!X.IDENTIFIER.test(t))throw new Error("CodeGen: name must be a valid identifier");this.str=t}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}};X.Name=Rr;var nt=class extends io{constructor(t){super(),this._items=typeof t=="string"?[t]:t}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;let t=this._items[0];return t===""||t==='""'}get str(){var t;return(t=this._str)!==null&&t!==void 0?t:this._str=this._items.reduce((r,n)=>`${r}${n}`,"")}get names(){var t;return(t=this._names)!==null&&t!==void 0?t:this._names=this._items.reduce((r,n)=>(n instanceof Rr&&(r[n.str]=(r[n.str]||0)+1),r),{})}};X._Code=nt;X.nil=new nt("");function nh(e,...t){let r=[e[0]],n=0;for(;n<t.length;)Pd(r,t[n]),r.push(e[++n]);return new nt(r)}X._=nh;var Td=new nt("+");function oh(e,...t){let r=[so(e[0])],n=0;for(;n<t.length;)r.push(Td),Pd(r,t[n]),r.push(Td,so(e[++n]));return tS(r),new nt(r)}X.str=oh;function Pd(e,t){t instanceof nt?e.push(...t._items):t instanceof Rr?e.push(t):e.push(oS(t))}X.addCodeArg=Pd;function tS(e){let t=1;for(;t<e.length-1;){if(e[t]===Td){let r=rS(e[t-1],e[t+1]);if(r!==void 0){e.splice(t-1,3,r);continue}e[t++]="+"}t++}}function rS(e,t){if(t==='""')return e;if(e==='""')return t;if(typeof e=="string")return t instanceof Rr||e[e.length-1]!=='"'?void 0:typeof t!="string"?`${e.slice(0,-1)}${t}"`:t[0]==='"'?e.slice(0,-1)+t.slice(1):void 0;if(typeof t=="string"&&t[0]==='"'&&!(e instanceof Rr))return`"${e}${t.slice(1)}`}function nS(e,t){return t.emptyStr()?e:e.emptyStr()?t:oh`${e}${t}`}X.strConcat=nS;function oS(e){return typeof e=="number"||typeof e=="boolean"||e===null?e:so(Array.isArray(e)?e.join(","):e)}function iS(e){return new nt(so(e))}X.stringify=iS;function so(e){return JSON.stringify(e).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}X.safeStringify=so;function sS(e){return typeof e=="string"&&X.IDENTIFIER.test(e)?new nt(`.${e}`):nh`[${e}]`}X.getProperty=sS;function aS(e){if(typeof e=="string"&&X.IDENTIFIER.test(e))return new nt(`${e}`);throw new Error(`CodeGen: invalid export name: ${e}, use explicit $id name mapping`)}X.getEsmExportName=aS;function cS(e){return new nt(e.toString())}X.regexpCode=cS});var Ed=T(Je=>{"use strict";Object.defineProperty(Je,"__esModule",{value:!0});Je.ValueScope=Je.ValueScopeName=Je.Scope=Je.varKinds=Je.UsedValueState=void 0;var Ze=ao(),Rd=class extends Error{constructor(t){super(`CodeGen: "code" for ${t} not defined`),this.value=t.value}},Vi;(function(e){e[e.Started=0]="Started",e[e.Completed=1]="Completed"})(Vi||(Je.UsedValueState=Vi={}));Je.varKinds={const:new Ze.Name("const"),let:new Ze.Name("let"),var:new Ze.Name("var")};var Wi=class{constructor({prefixes:t,parent:r}={}){this._names={},this._prefixes=t,this._parent=r}toName(t){return t instanceof Ze.Name?t:this.name(t)}name(t){return new Ze.Name(this._newName(t))}_newName(t){let r=this._names[t]||this._nameGroup(t);return`${t}${r.index++}`}_nameGroup(t){var r,n;if(!((n=(r=this._parent)===null||r===void 0?void 0:r._prefixes)===null||n===void 0)&&n.has(t)||this._prefixes&&!this._prefixes.has(t))throw new Error(`CodeGen: prefix "${t}" is not allowed in this scope`);return this._names[t]={prefix:t,index:0}}};Je.Scope=Wi;var Bi=class extends Ze.Name{constructor(t,r){super(r),this.prefix=t}setValue(t,{property:r,itemIndex:n}){this.value=t,this.scopePath=(0,Ze._)`.${new Ze.Name(r)}[${n}]`}};Je.ValueScopeName=Bi;var dS=(0,Ze._)`\n`,Od=class extends Wi{constructor(t){super(t),this._values={},this._scope=t.scope,this.opts={...t,_n:t.lines?dS:Ze.nil}}get(){return this._scope}name(t){return new Bi(t,this._newName(t))}value(t,r){var n;if(r.ref===void 0)throw new Error("CodeGen: ref must be passed in value");let o=this.toName(t),{prefix:i}=o,s=(n=r.key)!==null&&n!==void 0?n:r.ref,a=this._values[i];if(a){let u=a.get(s);if(u)return u}else a=this._values[i]=new Map;a.set(s,o);let c=this._scope[i]||(this._scope[i]=[]),d=c.length;return c[d]=r.ref,o.setValue(r,{property:i,itemIndex:d}),o}getValue(t,r){let n=this._values[t];if(n)return n.get(r)}scopeRefs(t,r=this._values){return this._reduceValues(r,n=>{if(n.scopePath===void 0)throw new Error(`CodeGen: name "${n}" has no value`);return(0,Ze._)`${t}${n.scopePath}`})}scopeCode(t=this._values,r,n){return this._reduceValues(t,o=>{if(o.value===void 0)throw new Error(`CodeGen: name "${o}" has no value`);return o.value.code},r,n)}_reduceValues(t,r,n={},o){let i=Ze.nil;for(let s in t){let a=t[s];if(!a)continue;let c=n[s]=n[s]||new Map;a.forEach(d=>{if(c.has(d))return;c.set(d,Vi.Started);let u=r(d);if(u){let p=this.opts.es5?Je.varKinds.var:Je.varKinds.const;i=(0,Ze._)`${i}${p} ${d} = ${u};${this.opts._n}`}else if(u=o?.(d))i=(0,Ze._)`${i}${u}${this.opts._n}`;else throw new Rd(d);c.set(d,Vi.Completed)})}return i}};Je.ValueScope=Od});var F=T(V=>{"use strict";Object.defineProperty(V,"__esModule",{value:!0});V.or=V.and=V.not=V.CodeGen=V.operators=V.varKinds=V.ValueScopeName=V.ValueScope=V.Scope=V.Name=V.regexpCode=V.stringify=V.getProperty=V.nil=V.strConcat=V.str=V._=void 0;var Q=ao(),lt=Ed(),Qt=ao();Object.defineProperty(V,"_",{enumerable:!0,get:function(){return Qt._}});Object.defineProperty(V,"str",{enumerable:!0,get:function(){return Qt.str}});Object.defineProperty(V,"strConcat",{enumerable:!0,get:function(){return Qt.strConcat}});Object.defineProperty(V,"nil",{enumerable:!0,get:function(){return Qt.nil}});Object.defineProperty(V,"getProperty",{enumerable:!0,get:function(){return Qt.getProperty}});Object.defineProperty(V,"stringify",{enumerable:!0,get:function(){return Qt.stringify}});Object.defineProperty(V,"regexpCode",{enumerable:!0,get:function(){return Qt.regexpCode}});Object.defineProperty(V,"Name",{enumerable:!0,get:function(){return Qt.Name}});var Qi=Ed();Object.defineProperty(V,"Scope",{enumerable:!0,get:function(){return Qi.Scope}});Object.defineProperty(V,"ValueScope",{enumerable:!0,get:function(){return Qi.ValueScope}});Object.defineProperty(V,"ValueScopeName",{enumerable:!0,get:function(){return Qi.ValueScopeName}});Object.defineProperty(V,"varKinds",{enumerable:!0,get:function(){return Qi.varKinds}});V.operators={GT:new Q._Code(">"),GTE:new Q._Code(">="),LT:new Q._Code("<"),LTE:new Q._Code("<="),EQ:new Q._Code("==="),NEQ:new Q._Code("!=="),NOT:new Q._Code("!"),OR:new Q._Code("||"),AND:new Q._Code("&&"),ADD:new Q._Code("+")};var It=class{optimizeNodes(){return this}optimizeNames(t,r){return this}},jd=class extends It{constructor(t,r,n){super(),this.varKind=t,this.name=r,this.rhs=n}render({es5:t,_n:r}){let n=t?lt.varKinds.var:this.varKind,o=this.rhs===void 0?"":` = ${this.rhs}`;return`${n} ${this.name}${o};`+r}optimizeNames(t,r){if(t[this.name.str])return this.rhs&&(this.rhs=pn(this.rhs,t,r)),this}get names(){return this.rhs instanceof Q._CodeOrName?this.rhs.names:{}}},Hi=class extends It{constructor(t,r,n){super(),this.lhs=t,this.rhs=r,this.sideEffects=n}render({_n:t}){return`${this.lhs} = ${this.rhs};`+t}optimizeNames(t,r){if(!(this.lhs instanceof Q.Name&&!t[this.lhs.str]&&!this.sideEffects))return this.rhs=pn(this.rhs,t,r),this}get names(){let t=this.lhs instanceof Q.Name?{}:{...this.lhs.names};return Ki(t,this.rhs)}},Id=class extends Hi{constructor(t,r,n,o){super(t,n,o),this.op=r}render({_n:t}){return`${this.lhs} ${this.op}= ${this.rhs};`+t}},Cd=class extends It{constructor(t){super(),this.label=t,this.names={}}render({_n:t}){return`${this.label}:`+t}},Ad=class extends It{constructor(t){super(),this.label=t,this.names={}}render({_n:t}){return`break${this.label?` ${this.label}`:""};`+t}},Md=class extends It{constructor(t){super(),this.error=t}render({_n:t}){return`throw ${this.error};`+t}get names(){return this.error.names}},Nd=class extends It{constructor(t){super(),this.code=t}render({_n:t}){return`${this.code};`+t}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(t,r){return this.code=pn(this.code,t,r),this}get names(){return this.code instanceof Q._CodeOrName?this.code.names:{}}},co=class extends It{constructor(t=[]){super(),this.nodes=t}render(t){return this.nodes.reduce((r,n)=>r+n.render(t),"")}optimizeNodes(){let{nodes:t}=this,r=t.length;for(;r--;){let n=t[r].optimizeNodes();Array.isArray(n)?t.splice(r,1,...n):n?t[r]=n:t.splice(r,1)}return t.length>0?this:void 0}optimizeNames(t,r){let{nodes:n}=this,o=n.length;for(;o--;){let i=n[o];i.optimizeNames(t,r)||(uS(t,i.names),n.splice(o,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((t,r)=>jr(t,r.names),{})}},Ct=class extends co{render(t){return"{"+t._n+super.render(t)+"}"+t._n}},Dd=class extends co{},ln=class extends Ct{};ln.kind="else";var Or=class e extends Ct{constructor(t,r){super(r),this.condition=t}render(t){let r=`if(${this.condition})`+super.render(t);return this.else&&(r+="else "+this.else.render(t)),r}optimizeNodes(){super.optimizeNodes();let t=this.condition;if(t===!0)return this.nodes;let r=this.else;if(r){let n=r.optimizeNodes();r=this.else=Array.isArray(n)?new ln(n):n}if(r)return t===!1?r instanceof e?r:r.nodes:this.nodes.length?this:new e(ih(t),r instanceof e?[r]:r.nodes);if(!(t===!1||!this.nodes.length))return this}optimizeNames(t,r){var n;if(this.else=(n=this.else)===null||n===void 0?void 0:n.optimizeNames(t,r),!!(super.optimizeNames(t,r)||this.else))return this.condition=pn(this.condition,t,r),this}get names(){let t=super.names;return Ki(t,this.condition),this.else&&jr(t,this.else.names),t}};Or.kind="if";var Er=class extends Ct{};Er.kind="for";var Ld=class extends Er{constructor(t){super(),this.iteration=t}render(t){return`for(${this.iteration})`+super.render(t)}optimizeNames(t,r){if(super.optimizeNames(t,r))return this.iteration=pn(this.iteration,t,r),this}get names(){return jr(super.names,this.iteration.names)}},qd=class extends Er{constructor(t,r,n,o){super(),this.varKind=t,this.name=r,this.from=n,this.to=o}render(t){let r=t.es5?lt.varKinds.var:this.varKind,{name:n,from:o,to:i}=this;return`for(${r} ${n}=${o}; ${n}<${i}; ${n}++)`+super.render(t)}get names(){let t=Ki(super.names,this.from);return Ki(t,this.to)}},Gi=class extends Er{constructor(t,r,n,o){super(),this.loop=t,this.varKind=r,this.name=n,this.iterable=o}render(t){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(t)}optimizeNames(t,r){if(super.optimizeNames(t,r))return this.iterable=pn(this.iterable,t,r),this}get names(){return jr(super.names,this.iterable.names)}},uo=class extends Ct{constructor(t,r,n){super(),this.name=t,this.args=r,this.async=n}render(t){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(t)}};uo.kind="func";var lo=class extends co{render(t){return"return "+super.render(t)}};lo.kind="return";var Ud=class extends Ct{render(t){let r="try"+super.render(t);return this.catch&&(r+=this.catch.render(t)),this.finally&&(r+=this.finally.render(t)),r}optimizeNodes(){var t,r;return super.optimizeNodes(),(t=this.catch)===null||t===void 0||t.optimizeNodes(),(r=this.finally)===null||r===void 0||r.optimizeNodes(),this}optimizeNames(t,r){var n,o;return super.optimizeNames(t,r),(n=this.catch)===null||n===void 0||n.optimizeNames(t,r),(o=this.finally)===null||o===void 0||o.optimizeNames(t,r),this}get names(){let t=super.names;return this.catch&&jr(t,this.catch.names),this.finally&&jr(t,this.finally.names),t}},po=class extends Ct{constructor(t){super(),this.error=t}render(t){return`catch(${this.error})`+super.render(t)}};po.kind="catch";var mo=class extends Ct{render(t){return"finally"+super.render(t)}};mo.kind="finally";var Zd=class{constructor(t,r={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...r,_n:r.lines?`
4
- `:""},this._extScope=t,this._scope=new lt.Scope({parent:t}),this._nodes=[new Dd]}toString(){return this._root.render(this.opts)}name(t){return this._scope.name(t)}scopeName(t){return this._extScope.name(t)}scopeValue(t,r){let n=this._extScope.value(t,r);return(this._values[n.prefix]||(this._values[n.prefix]=new Set)).add(n),n}getScopeValue(t,r){return this._extScope.getValue(t,r)}scopeRefs(t){return this._extScope.scopeRefs(t,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(t,r,n,o){let i=this._scope.toName(r);return n!==void 0&&o&&(this._constants[i.str]=n),this._leafNode(new jd(t,i,n)),i}const(t,r,n){return this._def(lt.varKinds.const,t,r,n)}let(t,r,n){return this._def(lt.varKinds.let,t,r,n)}var(t,r,n){return this._def(lt.varKinds.var,t,r,n)}assign(t,r,n){return this._leafNode(new Hi(t,r,n))}add(t,r){return this._leafNode(new Id(t,V.operators.ADD,r))}code(t){return typeof t=="function"?t():t!==Q.nil&&this._leafNode(new Nd(t)),this}object(...t){let r=["{"];for(let[n,o]of t)r.length>1&&r.push(","),r.push(n),(n!==o||this.opts.es5)&&(r.push(":"),(0,Q.addCodeArg)(r,o));return r.push("}"),new Q._Code(r)}if(t,r,n){if(this._blockNode(new Or(t)),r&&n)this.code(r).else().code(n).endIf();else if(r)this.code(r).endIf();else if(n)throw new Error('CodeGen: "else" body without "then" body');return this}elseIf(t){return this._elseNode(new Or(t))}else(){return this._elseNode(new ln)}endIf(){return this._endBlockNode(Or,ln)}_for(t,r){return this._blockNode(t),r&&this.code(r).endFor(),this}for(t,r){return this._for(new Ld(t),r)}forRange(t,r,n,o,i=this.opts.es5?lt.varKinds.var:lt.varKinds.let){let s=this._scope.toName(t);return this._for(new qd(i,s,r,n),()=>o(s))}forOf(t,r,n,o=lt.varKinds.const){let i=this._scope.toName(t);if(this.opts.es5){let s=r instanceof Q.Name?r:this.var("_arr",r);return this.forRange("_i",0,(0,Q._)`${s}.length`,a=>{this.var(i,(0,Q._)`${s}[${a}]`),n(i)})}return this._for(new Gi("of",o,i,r),()=>n(i))}forIn(t,r,n,o=this.opts.es5?lt.varKinds.var:lt.varKinds.const){if(this.opts.ownProperties)return this.forOf(t,(0,Q._)`Object.keys(${r})`,n);let i=this._scope.toName(t);return this._for(new Gi("in",o,i,r),()=>n(i))}endFor(){return this._endBlockNode(Er)}label(t){return this._leafNode(new Cd(t))}break(t){return this._leafNode(new Ad(t))}return(t){let r=new lo;if(this._blockNode(r),this.code(t),r.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(lo)}try(t,r,n){if(!r&&!n)throw new Error('CodeGen: "try" without "catch" and "finally"');let o=new Ud;if(this._blockNode(o),this.code(t),r){let i=this.name("e");this._currNode=o.catch=new po(i),r(i)}return n&&(this._currNode=o.finally=new mo,this.code(n)),this._endBlockNode(po,mo)}throw(t){return this._leafNode(new Md(t))}block(t,r){return this._blockStarts.push(this._nodes.length),t&&this.code(t).endBlock(r),this}endBlock(t){let r=this._blockStarts.pop();if(r===void 0)throw new Error("CodeGen: not in self-balancing block");let n=this._nodes.length-r;if(n<0||t!==void 0&&n!==t)throw new Error(`CodeGen: wrong number of nodes: ${n} vs ${t} expected`);return this._nodes.length=r,this}func(t,r=Q.nil,n,o){return this._blockNode(new uo(t,r,n)),o&&this.code(o).endFunc(),this}endFunc(){return this._endBlockNode(uo)}optimize(t=1){for(;t-- >0;)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(t){return this._currNode.nodes.push(t),this}_blockNode(t){this._currNode.nodes.push(t),this._nodes.push(t)}_endBlockNode(t,r){let n=this._currNode;if(n instanceof t||r&&n instanceof r)return this._nodes.pop(),this;throw new Error(`CodeGen: not in block "${r?`${t.kind}/${r.kind}`:t.kind}"`)}_elseNode(t){let r=this._currNode;if(!(r instanceof Or))throw new Error('CodeGen: "else" without "if"');return this._currNode=r.else=t,this}get _root(){return this._nodes[0]}get _currNode(){let t=this._nodes;return t[t.length-1]}set _currNode(t){let r=this._nodes;r[r.length-1]=t}};V.CodeGen=Zd;function jr(e,t){for(let r in t)e[r]=(e[r]||0)+(t[r]||0);return e}function Ki(e,t){return t instanceof Q._CodeOrName?jr(e,t.names):e}function pn(e,t,r){if(e instanceof Q.Name)return n(e);if(!o(e))return e;return new Q._Code(e._items.reduce((i,s)=>(s instanceof Q.Name&&(s=n(s)),s instanceof Q._Code?i.push(...s._items):i.push(s),i),[]));function n(i){let s=r[i.str];return s===void 0||t[i.str]!==1?i:(delete t[i.str],s)}function o(i){return i instanceof Q._Code&&i._items.some(s=>s instanceof Q.Name&&t[s.str]===1&&r[s.str]!==void 0)}}function uS(e,t){for(let r in t)e[r]=(e[r]||0)-(t[r]||0)}function ih(e){return typeof e=="boolean"||typeof e=="number"||e===null?!e:(0,Q._)`!${Jd(e)}`}V.not=ih;var lS=sh(V.operators.AND);function pS(...e){return e.reduce(lS)}V.and=pS;var mS=sh(V.operators.OR);function fS(...e){return e.reduce(mS)}V.or=fS;function sh(e){return(t,r)=>t===Q.nil?r:r===Q.nil?t:(0,Q._)`${Jd(t)} ${e} ${Jd(r)}`}function Jd(e){return e instanceof Q.Name?e:(0,Q._)`(${e})`}});var ee=T(W=>{"use strict";Object.defineProperty(W,"__esModule",{value:!0});W.checkStrictMode=W.getErrorPath=W.Type=W.useFunc=W.setEvaluated=W.evaluatedPropsToName=W.mergeEvaluated=W.eachItem=W.unescapeJsonPointer=W.escapeJsonPointer=W.escapeFragment=W.unescapeFragment=W.schemaRefOrVal=W.schemaHasRulesButRef=W.schemaHasRules=W.checkUnknownRules=W.alwaysValidSchema=W.toHash=void 0;var ie=F(),hS=ao();function gS(e){let t={};for(let r of e)t[r]=!0;return t}W.toHash=gS;function yS(e,t){return typeof t=="boolean"?t:Object.keys(t).length===0?!0:(dh(e,t),!uh(t,e.self.RULES.all))}W.alwaysValidSchema=yS;function dh(e,t=e.schema){let{opts:r,self:n}=e;if(!r.strictSchema||typeof t=="boolean")return;let o=n.RULES.keywords;for(let i in t)o[i]||mh(e,`unknown keyword: "${i}"`)}W.checkUnknownRules=dh;function uh(e,t){if(typeof e=="boolean")return!e;for(let r in e)if(t[r])return!0;return!1}W.schemaHasRules=uh;function _S(e,t){if(typeof e=="boolean")return!e;for(let r in e)if(r!=="$ref"&&t.all[r])return!0;return!1}W.schemaHasRulesButRef=_S;function bS({topSchemaRef:e,schemaPath:t},r,n,o){if(!o){if(typeof r=="number"||typeof r=="boolean")return r;if(typeof r=="string")return(0,ie._)`${r}`}return(0,ie._)`${e}${t}${(0,ie.getProperty)(n)}`}W.schemaRefOrVal=bS;function vS(e){return lh(decodeURIComponent(e))}W.unescapeFragment=vS;function wS(e){return encodeURIComponent(Vd(e))}W.escapeFragment=wS;function Vd(e){return typeof e=="number"?`${e}`:e.replace(/~/g,"~0").replace(/\//g,"~1")}W.escapeJsonPointer=Vd;function lh(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}W.unescapeJsonPointer=lh;function kS(e,t){if(Array.isArray(e))for(let r of e)t(r);else t(e)}W.eachItem=kS;function ah({mergeNames:e,mergeToName:t,mergeValues:r,resultToName:n}){return(o,i,s,a)=>{let c=s===void 0?i:s instanceof ie.Name?(i instanceof ie.Name?e(o,i,s):t(o,i,s),s):i instanceof ie.Name?(t(o,s,i),i):r(i,s);return a===ie.Name&&!(c instanceof ie.Name)?n(o,c):c}}W.mergeEvaluated={props:ah({mergeNames:(e,t,r)=>e.if((0,ie._)`${r} !== true && ${t} !== undefined`,()=>{e.if((0,ie._)`${t} === true`,()=>e.assign(r,!0),()=>e.assign(r,(0,ie._)`${r} || {}`).code((0,ie._)`Object.assign(${r}, ${t})`))}),mergeToName:(e,t,r)=>e.if((0,ie._)`${r} !== true`,()=>{t===!0?e.assign(r,!0):(e.assign(r,(0,ie._)`${r} || {}`),Wd(e,r,t))}),mergeValues:(e,t)=>e===!0?!0:{...e,...t},resultToName:ph}),items:ah({mergeNames:(e,t,r)=>e.if((0,ie._)`${r} !== true && ${t} !== undefined`,()=>e.assign(r,(0,ie._)`${t} === true ? true : ${r} > ${t} ? ${r} : ${t}`)),mergeToName:(e,t,r)=>e.if((0,ie._)`${r} !== true`,()=>e.assign(r,t===!0?!0:(0,ie._)`${r} > ${t} ? ${r} : ${t}`)),mergeValues:(e,t)=>e===!0?!0:Math.max(e,t),resultToName:(e,t)=>e.var("items",t)})};function ph(e,t){if(t===!0)return e.var("props",!0);let r=e.var("props",(0,ie._)`{}`);return t!==void 0&&Wd(e,r,t),r}W.evaluatedPropsToName=ph;function Wd(e,t,r){Object.keys(r).forEach(n=>e.assign((0,ie._)`${t}${(0,ie.getProperty)(n)}`,!0))}W.setEvaluated=Wd;var ch={};function xS(e,t){return e.scopeValue("func",{ref:t,code:ch[t.code]||(ch[t.code]=new hS._Code(t.code))})}W.useFunc=xS;var Fd;(function(e){e[e.Num=0]="Num",e[e.Str=1]="Str"})(Fd||(W.Type=Fd={}));function SS(e,t,r){if(e instanceof ie.Name){let n=t===Fd.Num;return r?n?(0,ie._)`"[" + ${e} + "]"`:(0,ie._)`"['" + ${e} + "']"`:n?(0,ie._)`"/" + ${e}`:(0,ie._)`"/" + ${e}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return r?(0,ie.getProperty)(e).toString():"/"+Vd(e)}W.getErrorPath=SS;function mh(e,t,r=e.opts.strictSchema){if(r){if(t=`strict mode: ${t}`,r===!0)throw new Error(t);e.self.logger.warn(t)}}W.checkStrictMode=mh});var At=T(Bd=>{"use strict";Object.defineProperty(Bd,"__esModule",{value:!0});var Oe=F(),$S={data:new Oe.Name("data"),valCxt:new Oe.Name("valCxt"),instancePath:new Oe.Name("instancePath"),parentData:new Oe.Name("parentData"),parentDataProperty:new Oe.Name("parentDataProperty"),rootData:new Oe.Name("rootData"),dynamicAnchors:new Oe.Name("dynamicAnchors"),vErrors:new Oe.Name("vErrors"),errors:new Oe.Name("errors"),this:new Oe.Name("this"),self:new Oe.Name("self"),scope:new Oe.Name("scope"),json:new Oe.Name("json"),jsonPos:new Oe.Name("jsonPos"),jsonLen:new Oe.Name("jsonLen"),jsonPart:new Oe.Name("jsonPart")};Bd.default=$S});var fo=T(Ee=>{"use strict";Object.defineProperty(Ee,"__esModule",{value:!0});Ee.extendErrors=Ee.resetErrorsCount=Ee.reportExtraError=Ee.reportError=Ee.keyword$DataError=Ee.keywordError=void 0;var Y=F(),Yi=ee(),Me=At();Ee.keywordError={message:({keyword:e})=>(0,Y.str)`must pass "${e}" keyword validation`};Ee.keyword$DataError={message:({keyword:e,schemaType:t})=>t?(0,Y.str)`"${e}" keyword must be ${t} ($data)`:(0,Y.str)`"${e}" keyword is invalid ($data)`};function zS(e,t=Ee.keywordError,r,n){let{it:o}=e,{gen:i,compositeRule:s,allErrors:a}=o,c=gh(e,t,r);n??(s||a)?fh(i,c):hh(o,(0,Y._)`[${c}]`)}Ee.reportError=zS;function TS(e,t=Ee.keywordError,r){let{it:n}=e,{gen:o,compositeRule:i,allErrors:s}=n,a=gh(e,t,r);fh(o,a),i||s||hh(n,Me.default.vErrors)}Ee.reportExtraError=TS;function PS(e,t){e.assign(Me.default.errors,t),e.if((0,Y._)`${Me.default.vErrors} !== null`,()=>e.if(t,()=>e.assign((0,Y._)`${Me.default.vErrors}.length`,t),()=>e.assign(Me.default.vErrors,null)))}Ee.resetErrorsCount=PS;function RS({gen:e,keyword:t,schemaValue:r,data:n,errsCount:o,it:i}){if(o===void 0)throw new Error("ajv implementation error");let s=e.name("err");e.forRange("i",o,Me.default.errors,a=>{e.const(s,(0,Y._)`${Me.default.vErrors}[${a}]`),e.if((0,Y._)`${s}.instancePath === undefined`,()=>e.assign((0,Y._)`${s}.instancePath`,(0,Y.strConcat)(Me.default.instancePath,i.errorPath))),e.assign((0,Y._)`${s}.schemaPath`,(0,Y.str)`${i.errSchemaPath}/${t}`),i.opts.verbose&&(e.assign((0,Y._)`${s}.schema`,r),e.assign((0,Y._)`${s}.data`,n))})}Ee.extendErrors=RS;function fh(e,t){let r=e.const("err",t);e.if((0,Y._)`${Me.default.vErrors} === null`,()=>e.assign(Me.default.vErrors,(0,Y._)`[${r}]`),(0,Y._)`${Me.default.vErrors}.push(${r})`),e.code((0,Y._)`${Me.default.errors}++`)}function hh(e,t){let{gen:r,validateName:n,schemaEnv:o}=e;o.$async?r.throw((0,Y._)`new ${e.ValidationError}(${t})`):(r.assign((0,Y._)`${n}.errors`,t),r.return(!1))}var Ir={keyword:new Y.Name("keyword"),schemaPath:new Y.Name("schemaPath"),params:new Y.Name("params"),propertyName:new Y.Name("propertyName"),message:new Y.Name("message"),schema:new Y.Name("schema"),parentSchema:new Y.Name("parentSchema")};function gh(e,t,r){let{createErrors:n}=e.it;return n===!1?(0,Y._)`{}`:OS(e,t,r)}function OS(e,t,r={}){let{gen:n,it:o}=e,i=[ES(o,r),jS(e,r)];return IS(e,t,i),n.object(...i)}function ES({errorPath:e},{instancePath:t}){let r=t?(0,Y.str)`${e}${(0,Yi.getErrorPath)(t,Yi.Type.Str)}`:e;return[Me.default.instancePath,(0,Y.strConcat)(Me.default.instancePath,r)]}function jS({keyword:e,it:{errSchemaPath:t}},{schemaPath:r,parentSchema:n}){let o=n?t:(0,Y.str)`${t}/${e}`;return r&&(o=(0,Y.str)`${o}${(0,Yi.getErrorPath)(r,Yi.Type.Str)}`),[Ir.schemaPath,o]}function IS(e,{params:t,message:r},n){let{keyword:o,data:i,schemaValue:s,it:a}=e,{opts:c,propertyName:d,topSchemaRef:u,schemaPath:p}=a;n.push([Ir.keyword,o],[Ir.params,typeof t=="function"?t(e):t||(0,Y._)`{}`]),c.messages&&n.push([Ir.message,typeof r=="function"?r(e):r]),c.verbose&&n.push([Ir.schema,s],[Ir.parentSchema,(0,Y._)`${u}${p}`],[Me.default.data,i]),d&&n.push([Ir.propertyName,d])}});var _h=T(mn=>{"use strict";Object.defineProperty(mn,"__esModule",{value:!0});mn.boolOrEmptySchema=mn.topBoolOrEmptySchema=void 0;var CS=fo(),AS=F(),MS=At(),NS={message:"boolean schema is false"};function DS(e){let{gen:t,schema:r,validateName:n}=e;r===!1?yh(e,!1):typeof r=="object"&&r.$async===!0?t.return(MS.default.data):(t.assign((0,AS._)`${n}.errors`,null),t.return(!0))}mn.topBoolOrEmptySchema=DS;function LS(e,t){let{gen:r,schema:n}=e;n===!1?(r.var(t,!1),yh(e)):r.var(t,!0)}mn.boolOrEmptySchema=LS;function yh(e,t){let{gen:r,data:n}=e,o={gen:r,keyword:"false schema",data:n,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:e};(0,CS.reportError)(o,NS,void 0,t)}});var Hd=T(fn=>{"use strict";Object.defineProperty(fn,"__esModule",{value:!0});fn.getRules=fn.isJSONType=void 0;var qS=["string","number","integer","boolean","null","object","array"],US=new Set(qS);function ZS(e){return typeof e=="string"&&US.has(e)}fn.isJSONType=ZS;function JS(){let e={number:{type:"number",rules:[]},string:{type:"string",rules:[]},array:{type:"array",rules:[]},object:{type:"object",rules:[]}};return{types:{...e,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},e.number,e.string,e.array,e.object],post:{rules:[]},all:{},keywords:{}}}fn.getRules=JS});var Gd=T(Yt=>{"use strict";Object.defineProperty(Yt,"__esModule",{value:!0});Yt.shouldUseRule=Yt.shouldUseGroup=Yt.schemaHasRulesForType=void 0;function FS({schema:e,self:t},r){let n=t.RULES.types[r];return n&&n!==!0&&bh(e,n)}Yt.schemaHasRulesForType=FS;function bh(e,t){return t.rules.some(r=>vh(e,r))}Yt.shouldUseGroup=bh;function vh(e,t){var r;return e[t.keyword]!==void 0||((r=t.definition.implements)===null||r===void 0?void 0:r.some(n=>e[n]!==void 0))}Yt.shouldUseRule=vh});var ho=T(je=>{"use strict";Object.defineProperty(je,"__esModule",{value:!0});je.reportTypeError=je.checkDataTypes=je.checkDataType=je.coerceAndCheckDataType=je.getJSONTypes=je.getSchemaTypes=je.DataType=void 0;var VS=Hd(),WS=Gd(),BS=fo(),Z=F(),wh=ee(),hn;(function(e){e[e.Correct=0]="Correct",e[e.Wrong=1]="Wrong"})(hn||(je.DataType=hn={}));function HS(e){let t=kh(e.type);if(t.includes("null")){if(e.nullable===!1)throw new Error("type: null contradicts nullable: false")}else{if(!t.length&&e.nullable!==void 0)throw new Error('"nullable" cannot be used without "type"');e.nullable===!0&&t.push("null")}return t}je.getSchemaTypes=HS;function kh(e){let t=Array.isArray(e)?e:e?[e]:[];if(t.every(VS.isJSONType))return t;throw new Error("type must be JSONType or JSONType[]: "+t.join(","))}je.getJSONTypes=kh;function GS(e,t){let{gen:r,data:n,opts:o}=e,i=KS(t,o.coerceTypes),s=t.length>0&&!(i.length===0&&t.length===1&&(0,WS.schemaHasRulesForType)(e,t[0]));if(s){let a=Qd(t,n,o.strictNumbers,hn.Wrong);r.if(a,()=>{i.length?QS(e,t,i):Yd(e)})}return s}je.coerceAndCheckDataType=GS;var xh=new Set(["string","number","integer","boolean","null"]);function KS(e,t){return t?e.filter(r=>xh.has(r)||t==="array"&&r==="array"):[]}function QS(e,t,r){let{gen:n,data:o,opts:i}=e,s=n.let("dataType",(0,Z._)`typeof ${o}`),a=n.let("coerced",(0,Z._)`undefined`);i.coerceTypes==="array"&&n.if((0,Z._)`${s} == 'object' && Array.isArray(${o}) && ${o}.length == 1`,()=>n.assign(o,(0,Z._)`${o}[0]`).assign(s,(0,Z._)`typeof ${o}`).if(Qd(t,o,i.strictNumbers),()=>n.assign(a,o))),n.if((0,Z._)`${a} !== undefined`);for(let d of r)(xh.has(d)||d==="array"&&i.coerceTypes==="array")&&c(d);n.else(),Yd(e),n.endIf(),n.if((0,Z._)`${a} !== undefined`,()=>{n.assign(o,a),YS(e,a)});function c(d){switch(d){case"string":n.elseIf((0,Z._)`${s} == "number" || ${s} == "boolean"`).assign(a,(0,Z._)`"" + ${o}`).elseIf((0,Z._)`${o} === null`).assign(a,(0,Z._)`""`);return;case"number":n.elseIf((0,Z._)`${s} == "boolean" || ${o} === null
5
- || (${s} == "string" && ${o} && ${o} == +${o})`).assign(a,(0,Z._)`+${o}`);return;case"integer":n.elseIf((0,Z._)`${s} === "boolean" || ${o} === null
6
- || (${s} === "string" && ${o} && ${o} == +${o} && !(${o} % 1))`).assign(a,(0,Z._)`+${o}`);return;case"boolean":n.elseIf((0,Z._)`${o} === "false" || ${o} === 0 || ${o} === null`).assign(a,!1).elseIf((0,Z._)`${o} === "true" || ${o} === 1`).assign(a,!0);return;case"null":n.elseIf((0,Z._)`${o} === "" || ${o} === 0 || ${o} === false`),n.assign(a,null);return;case"array":n.elseIf((0,Z._)`${s} === "string" || ${s} === "number"
7
- || ${s} === "boolean" || ${o} === null`).assign(a,(0,Z._)`[${o}]`)}}}function YS({gen:e,parentData:t,parentDataProperty:r},n){e.if((0,Z._)`${t} !== undefined`,()=>e.assign((0,Z._)`${t}[${r}]`,n))}function Kd(e,t,r,n=hn.Correct){let o=n===hn.Correct?Z.operators.EQ:Z.operators.NEQ,i;switch(e){case"null":return(0,Z._)`${t} ${o} null`;case"array":i=(0,Z._)`Array.isArray(${t})`;break;case"object":i=(0,Z._)`${t} && typeof ${t} == "object" && !Array.isArray(${t})`;break;case"integer":i=s((0,Z._)`!(${t} % 1) && !isNaN(${t})`);break;case"number":i=s();break;default:return(0,Z._)`typeof ${t} ${o} ${e}`}return n===hn.Correct?i:(0,Z.not)(i);function s(a=Z.nil){return(0,Z.and)((0,Z._)`typeof ${t} == "number"`,a,r?(0,Z._)`isFinite(${t})`:Z.nil)}}je.checkDataType=Kd;function Qd(e,t,r,n){if(e.length===1)return Kd(e[0],t,r,n);let o,i=(0,wh.toHash)(e);if(i.array&&i.object){let s=(0,Z._)`typeof ${t} != "object"`;o=i.null?s:(0,Z._)`!${t} || ${s}`,delete i.null,delete i.array,delete i.object}else o=Z.nil;i.number&&delete i.integer;for(let s in i)o=(0,Z.and)(o,Kd(s,t,r,n));return o}je.checkDataTypes=Qd;var XS={message:({schema:e})=>`must be ${e}`,params:({schema:e,schemaValue:t})=>typeof e=="string"?(0,Z._)`{type: ${e}}`:(0,Z._)`{type: ${t}}`};function Yd(e){let t=e$(e);(0,BS.reportError)(t,XS)}je.reportTypeError=Yd;function e$(e){let{gen:t,data:r,schema:n}=e,o=(0,wh.schemaRefOrVal)(e,n,"type");return{gen:t,keyword:"type",data:r,schema:n.type,schemaCode:o,schemaValue:o,parentSchema:n,params:{},it:e}}});var $h=T(Xi=>{"use strict";Object.defineProperty(Xi,"__esModule",{value:!0});Xi.assignDefaults=void 0;var gn=F(),t$=ee();function r$(e,t){let{properties:r,items:n}=e.schema;if(t==="object"&&r)for(let o in r)Sh(e,o,r[o].default);else t==="array"&&Array.isArray(n)&&n.forEach((o,i)=>Sh(e,i,o.default))}Xi.assignDefaults=r$;function Sh(e,t,r){let{gen:n,compositeRule:o,data:i,opts:s}=e;if(r===void 0)return;let a=(0,gn._)`${i}${(0,gn.getProperty)(t)}`;if(o){(0,t$.checkStrictMode)(e,`default is ignored for: ${a}`);return}let c=(0,gn._)`${a} === undefined`;s.useDefaults==="empty"&&(c=(0,gn._)`${c} || ${a} === null || ${a} === ""`),n.if(c,(0,gn._)`${a} = ${(0,gn.stringify)(r)}`)}});var ot=T(oe=>{"use strict";Object.defineProperty(oe,"__esModule",{value:!0});oe.validateUnion=oe.validateArray=oe.usePattern=oe.callValidateCode=oe.schemaProperties=oe.allSchemaProperties=oe.noPropertyInData=oe.propertyInData=oe.isOwnProperty=oe.hasPropFunc=oe.reportMissingProp=oe.checkMissingProp=oe.checkReportMissingProp=void 0;var ue=F(),Xd=ee(),Xt=At(),n$=ee();function o$(e,t){let{gen:r,data:n,it:o}=e;r.if(tu(r,n,t,o.opts.ownProperties),()=>{e.setParams({missingProperty:(0,ue._)`${t}`},!0),e.error()})}oe.checkReportMissingProp=o$;function i$({gen:e,data:t,it:{opts:r}},n,o){return(0,ue.or)(...n.map(i=>(0,ue.and)(tu(e,t,i,r.ownProperties),(0,ue._)`${o} = ${i}`)))}oe.checkMissingProp=i$;function s$(e,t){e.setParams({missingProperty:t},!0),e.error()}oe.reportMissingProp=s$;function zh(e){return e.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,ue._)`Object.prototype.hasOwnProperty`})}oe.hasPropFunc=zh;function eu(e,t,r){return(0,ue._)`${zh(e)}.call(${t}, ${r})`}oe.isOwnProperty=eu;function a$(e,t,r,n){let o=(0,ue._)`${t}${(0,ue.getProperty)(r)} !== undefined`;return n?(0,ue._)`${o} && ${eu(e,t,r)}`:o}oe.propertyInData=a$;function tu(e,t,r,n){let o=(0,ue._)`${t}${(0,ue.getProperty)(r)} === undefined`;return n?(0,ue.or)(o,(0,ue.not)(eu(e,t,r))):o}oe.noPropertyInData=tu;function Th(e){return e?Object.keys(e).filter(t=>t!=="__proto__"):[]}oe.allSchemaProperties=Th;function c$(e,t){return Th(t).filter(r=>!(0,Xd.alwaysValidSchema)(e,t[r]))}oe.schemaProperties=c$;function d$({schemaCode:e,data:t,it:{gen:r,topSchemaRef:n,schemaPath:o,errorPath:i},it:s},a,c,d){let u=d?(0,ue._)`${e}, ${t}, ${n}${o}`:t,p=[[Xt.default.instancePath,(0,ue.strConcat)(Xt.default.instancePath,i)],[Xt.default.parentData,s.parentData],[Xt.default.parentDataProperty,s.parentDataProperty],[Xt.default.rootData,Xt.default.rootData]];s.opts.dynamicRef&&p.push([Xt.default.dynamicAnchors,Xt.default.dynamicAnchors]);let m=(0,ue._)`${u}, ${r.object(...p)}`;return c!==ue.nil?(0,ue._)`${a}.call(${c}, ${m})`:(0,ue._)`${a}(${m})`}oe.callValidateCode=d$;var u$=(0,ue._)`new RegExp`;function l$({gen:e,it:{opts:t}},r){let n=t.unicodeRegExp?"u":"",{regExp:o}=t.code,i=o(r,n);return e.scopeValue("pattern",{key:i.toString(),ref:i,code:(0,ue._)`${o.code==="new RegExp"?u$:(0,n$.useFunc)(e,o)}(${r}, ${n})`})}oe.usePattern=l$;function p$(e){let{gen:t,data:r,keyword:n,it:o}=e,i=t.name("valid");if(o.allErrors){let a=t.let("valid",!0);return s(()=>t.assign(a,!1)),a}return t.var(i,!0),s(()=>t.break()),i;function s(a){let c=t.const("len",(0,ue._)`${r}.length`);t.forRange("i",0,c,d=>{e.subschema({keyword:n,dataProp:d,dataPropType:Xd.Type.Num},i),t.if((0,ue.not)(i),a)})}}oe.validateArray=p$;function m$(e){let{gen:t,schema:r,keyword:n,it:o}=e;if(!Array.isArray(r))throw new Error("ajv implementation error");if(r.some(c=>(0,Xd.alwaysValidSchema)(o,c))&&!o.opts.unevaluated)return;let s=t.let("valid",!1),a=t.name("_valid");t.block(()=>r.forEach((c,d)=>{let u=e.subschema({keyword:n,schemaProp:d,compositeRule:!0},a);t.assign(s,(0,ue._)`${s} || ${a}`),e.mergeValidEvaluated(u,a)||t.if((0,ue.not)(s))})),e.result(s,()=>e.reset(),()=>e.error(!0))}oe.validateUnion=m$});var Oh=T(wt=>{"use strict";Object.defineProperty(wt,"__esModule",{value:!0});wt.validateKeywordUsage=wt.validSchemaType=wt.funcKeywordCode=wt.macroKeywordCode=void 0;var Ne=F(),Cr=At(),f$=ot(),h$=fo();function g$(e,t){let{gen:r,keyword:n,schema:o,parentSchema:i,it:s}=e,a=t.macro.call(s.self,o,i,s),c=Rh(r,n,a);s.opts.validateSchema!==!1&&s.self.validateSchema(a,!0);let d=r.name("valid");e.subschema({schema:a,schemaPath:Ne.nil,errSchemaPath:`${s.errSchemaPath}/${n}`,topSchemaRef:c,compositeRule:!0},d),e.pass(d,()=>e.error(!0))}wt.macroKeywordCode=g$;function y$(e,t){var r;let{gen:n,keyword:o,schema:i,parentSchema:s,$data:a,it:c}=e;b$(c,t);let d=!a&&t.compile?t.compile.call(c.self,i,s,c):t.validate,u=Rh(n,o,d),p=n.let("valid");e.block$data(p,m),e.ok((r=t.valid)!==null&&r!==void 0?r:p);function m(){if(t.errors===!1)g(),t.modifying&&Ph(e),y(()=>e.error());else{let v=t.async?f():h();t.modifying&&Ph(e),y(()=>_$(e,v))}}function f(){let v=n.let("ruleErrs",null);return n.try(()=>g((0,Ne._)`await `),w=>n.assign(p,!1).if((0,Ne._)`${w} instanceof ${c.ValidationError}`,()=>n.assign(v,(0,Ne._)`${w}.errors`),()=>n.throw(w))),v}function h(){let v=(0,Ne._)`${u}.errors`;return n.assign(v,null),g(Ne.nil),v}function g(v=t.async?(0,Ne._)`await `:Ne.nil){let w=c.opts.passContext?Cr.default.this:Cr.default.self,k=!("compile"in t&&!a||t.schema===!1);n.assign(p,(0,Ne._)`${v}${(0,f$.callValidateCode)(e,u,w,k)}`,t.modifying)}function y(v){var w;n.if((0,Ne.not)((w=t.valid)!==null&&w!==void 0?w:p),v)}}wt.funcKeywordCode=y$;function Ph(e){let{gen:t,data:r,it:n}=e;t.if(n.parentData,()=>t.assign(r,(0,Ne._)`${n.parentData}[${n.parentDataProperty}]`))}function _$(e,t){let{gen:r}=e;r.if((0,Ne._)`Array.isArray(${t})`,()=>{r.assign(Cr.default.vErrors,(0,Ne._)`${Cr.default.vErrors} === null ? ${t} : ${Cr.default.vErrors}.concat(${t})`).assign(Cr.default.errors,(0,Ne._)`${Cr.default.vErrors}.length`),(0,h$.extendErrors)(e)},()=>e.error())}function b$({schemaEnv:e},t){if(t.async&&!e.$async)throw new Error("async keyword in sync schema")}function Rh(e,t,r){if(r===void 0)throw new Error(`keyword "${t}" failed to compile`);return e.scopeValue("keyword",typeof r=="function"?{ref:r}:{ref:r,code:(0,Ne.stringify)(r)})}function v$(e,t,r=!1){return!t.length||t.some(n=>n==="array"?Array.isArray(e):n==="object"?e&&typeof e=="object"&&!Array.isArray(e):typeof e==n||r&&typeof e>"u")}wt.validSchemaType=v$;function w$({schema:e,opts:t,self:r,errSchemaPath:n},o,i){if(Array.isArray(o.keyword)?!o.keyword.includes(i):o.keyword!==i)throw new Error("ajv implementation error");let s=o.dependencies;if(s?.some(a=>!Object.prototype.hasOwnProperty.call(e,a)))throw new Error(`parent schema must have dependencies of ${i}: ${s.join(",")}`);if(o.validateSchema&&!o.validateSchema(e[i])){let c=`keyword "${i}" value is invalid at path "${n}": `+r.errorsText(o.validateSchema.errors);if(t.validateSchema==="log")r.logger.error(c);else throw new Error(c)}}wt.validateKeywordUsage=w$});var jh=T(er=>{"use strict";Object.defineProperty(er,"__esModule",{value:!0});er.extendSubschemaMode=er.extendSubschemaData=er.getSubschema=void 0;var kt=F(),Eh=ee();function k$(e,{keyword:t,schemaProp:r,schema:n,schemaPath:o,errSchemaPath:i,topSchemaRef:s}){if(t!==void 0&&n!==void 0)throw new Error('both "keyword" and "schema" passed, only one allowed');if(t!==void 0){let a=e.schema[t];return r===void 0?{schema:a,schemaPath:(0,kt._)`${e.schemaPath}${(0,kt.getProperty)(t)}`,errSchemaPath:`${e.errSchemaPath}/${t}`}:{schema:a[r],schemaPath:(0,kt._)`${e.schemaPath}${(0,kt.getProperty)(t)}${(0,kt.getProperty)(r)}`,errSchemaPath:`${e.errSchemaPath}/${t}/${(0,Eh.escapeFragment)(r)}`}}if(n!==void 0){if(o===void 0||i===void 0||s===void 0)throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:n,schemaPath:o,topSchemaRef:s,errSchemaPath:i}}throw new Error('either "keyword" or "schema" must be passed')}er.getSubschema=k$;function x$(e,t,{dataProp:r,dataPropType:n,data:o,dataTypes:i,propertyName:s}){if(o!==void 0&&r!==void 0)throw new Error('both "data" and "dataProp" passed, only one allowed');let{gen:a}=t;if(r!==void 0){let{errorPath:d,dataPathArr:u,opts:p}=t,m=a.let("data",(0,kt._)`${t.data}${(0,kt.getProperty)(r)}`,!0);c(m),e.errorPath=(0,kt.str)`${d}${(0,Eh.getErrorPath)(r,n,p.jsPropertySyntax)}`,e.parentDataProperty=(0,kt._)`${r}`,e.dataPathArr=[...u,e.parentDataProperty]}if(o!==void 0){let d=o instanceof kt.Name?o:a.let("data",o,!0);c(d),s!==void 0&&(e.propertyName=s)}i&&(e.dataTypes=i);function c(d){e.data=d,e.dataLevel=t.dataLevel+1,e.dataTypes=[],t.definedProperties=new Set,e.parentData=t.data,e.dataNames=[...t.dataNames,d]}}er.extendSubschemaData=x$;function S$(e,{jtdDiscriminator:t,jtdMetadata:r,compositeRule:n,createErrors:o,allErrors:i}){n!==void 0&&(e.compositeRule=n),o!==void 0&&(e.createErrors=o),i!==void 0&&(e.allErrors=i),e.jtdDiscriminator=t,e.jtdMetadata=r}er.extendSubschemaMode=S$});var ru=T((F2,Ih)=>{"use strict";Ih.exports=function e(t,r){if(t===r)return!0;if(t&&r&&typeof t=="object"&&typeof r=="object"){if(t.constructor!==r.constructor)return!1;var n,o,i;if(Array.isArray(t)){if(n=t.length,n!=r.length)return!1;for(o=n;o--!==0;)if(!e(t[o],r[o]))return!1;return!0}if(t.constructor===RegExp)return t.source===r.source&&t.flags===r.flags;if(t.valueOf!==Object.prototype.valueOf)return t.valueOf()===r.valueOf();if(t.toString!==Object.prototype.toString)return t.toString()===r.toString();if(i=Object.keys(t),n=i.length,n!==Object.keys(r).length)return!1;for(o=n;o--!==0;)if(!Object.prototype.hasOwnProperty.call(r,i[o]))return!1;for(o=n;o--!==0;){var s=i[o];if(!e(t[s],r[s]))return!1}return!0}return t!==t&&r!==r}});var Ah=T((V2,Ch)=>{"use strict";var tr=Ch.exports=function(e,t,r){typeof t=="function"&&(r=t,t={}),r=t.cb||r;var n=typeof r=="function"?r:r.pre||function(){},o=r.post||function(){};es(t,n,o,e,"",e)};tr.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};tr.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};tr.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};tr.skipKeywords={default:!0,enum:!0,const:!0,required:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0};function es(e,t,r,n,o,i,s,a,c,d){if(n&&typeof n=="object"&&!Array.isArray(n)){t(n,o,i,s,a,c,d);for(var u in n){var p=n[u];if(Array.isArray(p)){if(u in tr.arrayKeywords)for(var m=0;m<p.length;m++)es(e,t,r,p[m],o+"/"+u+"/"+m,i,o,u,n,m)}else if(u in tr.propsKeywords){if(p&&typeof p=="object")for(var f in p)es(e,t,r,p[f],o+"/"+u+"/"+$$(f),i,o,u,n,f)}else(u in tr.keywords||e.allKeys&&!(u in tr.skipKeywords))&&es(e,t,r,p,o+"/"+u,i,o,u,n)}r(n,o,i,s,a,c,d)}}function $$(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}});var go=T(Fe=>{"use strict";Object.defineProperty(Fe,"__esModule",{value:!0});Fe.getSchemaRefs=Fe.resolveUrl=Fe.normalizeId=Fe._getFullPath=Fe.getFullPath=Fe.inlineRef=void 0;var z$=ee(),T$=ru(),P$=Ah(),R$=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function O$(e,t=!0){return typeof e=="boolean"?!0:t===!0?!nu(e):t?Mh(e)<=t:!1}Fe.inlineRef=O$;var E$=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function nu(e){for(let t in e){if(E$.has(t))return!0;let r=e[t];if(Array.isArray(r)&&r.some(nu)||typeof r=="object"&&nu(r))return!0}return!1}function Mh(e){let t=0;for(let r in e){if(r==="$ref")return 1/0;if(t++,!R$.has(r)&&(typeof e[r]=="object"&&(0,z$.eachItem)(e[r],n=>t+=Mh(n)),t===1/0))return 1/0}return t}function Nh(e,t="",r){r!==!1&&(t=yn(t));let n=e.parse(t);return Dh(e,n)}Fe.getFullPath=Nh;function Dh(e,t){return e.serialize(t).split("#")[0]+"#"}Fe._getFullPath=Dh;var j$=/#\/?$/;function yn(e){return e?e.replace(j$,""):""}Fe.normalizeId=yn;function I$(e,t,r){return r=yn(r),e.resolve(t,r)}Fe.resolveUrl=I$;var C$=/^[a-z_][-a-z0-9._]*$/i;function A$(e,t){if(typeof e=="boolean")return{};let{schemaId:r,uriResolver:n}=this.opts,o=yn(e[r]||t),i={"":o},s=Nh(n,o,!1),a={},c=new Set;return P$(e,{allKeys:!0},(p,m,f,h)=>{if(h===void 0)return;let g=s+m,y=i[h];typeof p[r]=="string"&&(y=v.call(this,p[r])),w.call(this,p.$anchor),w.call(this,p.$dynamicAnchor),i[m]=y;function v(k){let O=this.opts.uriResolver.resolve;if(k=yn(y?O(y,k):k),c.has(k))throw u(k);c.add(k);let M=this.refs[k];return typeof M=="string"&&(M=this.refs[M]),typeof M=="object"?d(p,M.schema,k):k!==yn(g)&&(k[0]==="#"?(d(p,a[k],k),a[k]=p):this.refs[k]=g),k}function w(k){if(typeof k=="string"){if(!C$.test(k))throw new Error(`invalid anchor "${k}"`);v.call(this,`#${k}`)}}}),a;function d(p,m,f){if(m!==void 0&&!T$(p,m))throw u(f)}function u(p){return new Error(`reference "${p}" resolves to more than one schema`)}}Fe.getSchemaRefs=A$});var bo=T(rr=>{"use strict";Object.defineProperty(rr,"__esModule",{value:!0});rr.getData=rr.KeywordCxt=rr.validateFunctionCode=void 0;var Jh=_h(),Lh=ho(),iu=Gd(),ts=ho(),M$=$h(),_o=Oh(),ou=jh(),C=F(),q=At(),N$=go(),Mt=ee(),yo=fo();function D$(e){if(Wh(e)&&(Bh(e),Vh(e))){U$(e);return}Fh(e,()=>(0,Jh.topBoolOrEmptySchema)(e))}rr.validateFunctionCode=D$;function Fh({gen:e,validateName:t,schema:r,schemaEnv:n,opts:o},i){o.code.es5?e.func(t,(0,C._)`${q.default.data}, ${q.default.valCxt}`,n.$async,()=>{e.code((0,C._)`"use strict"; ${qh(r,o)}`),q$(e,o),e.code(i)}):e.func(t,(0,C._)`${q.default.data}, ${L$(o)}`,n.$async,()=>e.code(qh(r,o)).code(i))}function L$(e){return(0,C._)`{${q.default.instancePath}="", ${q.default.parentData}, ${q.default.parentDataProperty}, ${q.default.rootData}=${q.default.data}${e.dynamicRef?(0,C._)`, ${q.default.dynamicAnchors}={}`:C.nil}}={}`}function q$(e,t){e.if(q.default.valCxt,()=>{e.var(q.default.instancePath,(0,C._)`${q.default.valCxt}.${q.default.instancePath}`),e.var(q.default.parentData,(0,C._)`${q.default.valCxt}.${q.default.parentData}`),e.var(q.default.parentDataProperty,(0,C._)`${q.default.valCxt}.${q.default.parentDataProperty}`),e.var(q.default.rootData,(0,C._)`${q.default.valCxt}.${q.default.rootData}`),t.dynamicRef&&e.var(q.default.dynamicAnchors,(0,C._)`${q.default.valCxt}.${q.default.dynamicAnchors}`)},()=>{e.var(q.default.instancePath,(0,C._)`""`),e.var(q.default.parentData,(0,C._)`undefined`),e.var(q.default.parentDataProperty,(0,C._)`undefined`),e.var(q.default.rootData,q.default.data),t.dynamicRef&&e.var(q.default.dynamicAnchors,(0,C._)`{}`)})}function U$(e){let{schema:t,opts:r,gen:n}=e;Fh(e,()=>{r.$comment&&t.$comment&&Gh(e),W$(e),n.let(q.default.vErrors,null),n.let(q.default.errors,0),r.unevaluated&&Z$(e),Hh(e),G$(e)})}function Z$(e){let{gen:t,validateName:r}=e;e.evaluated=t.const("evaluated",(0,C._)`${r}.evaluated`),t.if((0,C._)`${e.evaluated}.dynamicProps`,()=>t.assign((0,C._)`${e.evaluated}.props`,(0,C._)`undefined`)),t.if((0,C._)`${e.evaluated}.dynamicItems`,()=>t.assign((0,C._)`${e.evaluated}.items`,(0,C._)`undefined`))}function qh(e,t){let r=typeof e=="object"&&e[t.schemaId];return r&&(t.code.source||t.code.process)?(0,C._)`/*# sourceURL=${r} */`:C.nil}function J$(e,t){if(Wh(e)&&(Bh(e),Vh(e))){F$(e,t);return}(0,Jh.boolOrEmptySchema)(e,t)}function Vh({schema:e,self:t}){if(typeof e=="boolean")return!e;for(let r in e)if(t.RULES.all[r])return!0;return!1}function Wh(e){return typeof e.schema!="boolean"}function F$(e,t){let{schema:r,gen:n,opts:o}=e;o.$comment&&r.$comment&&Gh(e),B$(e),H$(e);let i=n.const("_errs",q.default.errors);Hh(e,i),n.var(t,(0,C._)`${i} === ${q.default.errors}`)}function Bh(e){(0,Mt.checkUnknownRules)(e),V$(e)}function Hh(e,t){if(e.opts.jtd)return Uh(e,[],!1,t);let r=(0,Lh.getSchemaTypes)(e.schema),n=(0,Lh.coerceAndCheckDataType)(e,r);Uh(e,r,!n,t)}function V$(e){let{schema:t,errSchemaPath:r,opts:n,self:o}=e;t.$ref&&n.ignoreKeywordsWithRef&&(0,Mt.schemaHasRulesButRef)(t,o.RULES)&&o.logger.warn(`$ref: keywords ignored in schema at path "${r}"`)}function W$(e){let{schema:t,opts:r}=e;t.default!==void 0&&r.useDefaults&&r.strictSchema&&(0,Mt.checkStrictMode)(e,"default is ignored in the schema root")}function B$(e){let t=e.schema[e.opts.schemaId];t&&(e.baseId=(0,N$.resolveUrl)(e.opts.uriResolver,e.baseId,t))}function H$(e){if(e.schema.$async&&!e.schemaEnv.$async)throw new Error("async schema in sync schema")}function Gh({gen:e,schemaEnv:t,schema:r,errSchemaPath:n,opts:o}){let i=r.$comment;if(o.$comment===!0)e.code((0,C._)`${q.default.self}.logger.log(${i})`);else if(typeof o.$comment=="function"){let s=(0,C.str)`${n}/$comment`,a=e.scopeValue("root",{ref:t.root});e.code((0,C._)`${q.default.self}.opts.$comment(${i}, ${s}, ${a}.schema)`)}}function G$(e){let{gen:t,schemaEnv:r,validateName:n,ValidationError:o,opts:i}=e;r.$async?t.if((0,C._)`${q.default.errors} === 0`,()=>t.return(q.default.data),()=>t.throw((0,C._)`new ${o}(${q.default.vErrors})`)):(t.assign((0,C._)`${n}.errors`,q.default.vErrors),i.unevaluated&&K$(e),t.return((0,C._)`${q.default.errors} === 0`))}function K$({gen:e,evaluated:t,props:r,items:n}){r instanceof C.Name&&e.assign((0,C._)`${t}.props`,r),n instanceof C.Name&&e.assign((0,C._)`${t}.items`,n)}function Uh(e,t,r,n){let{gen:o,schema:i,data:s,allErrors:a,opts:c,self:d}=e,{RULES:u}=d;if(i.$ref&&(c.ignoreKeywordsWithRef||!(0,Mt.schemaHasRulesButRef)(i,u))){o.block(()=>Qh(e,"$ref",u.all.$ref.definition));return}c.jtd||Q$(e,t),o.block(()=>{for(let m of u.rules)p(m);p(u.post)});function p(m){(0,iu.shouldUseGroup)(i,m)&&(m.type?(o.if((0,ts.checkDataType)(m.type,s,c.strictNumbers)),Zh(e,m),t.length===1&&t[0]===m.type&&r&&(o.else(),(0,ts.reportTypeError)(e)),o.endIf()):Zh(e,m),a||o.if((0,C._)`${q.default.errors} === ${n||0}`))}}function Zh(e,t){let{gen:r,schema:n,opts:{useDefaults:o}}=e;o&&(0,M$.assignDefaults)(e,t.type),r.block(()=>{for(let i of t.rules)(0,iu.shouldUseRule)(n,i)&&Qh(e,i.keyword,i.definition,t.type)})}function Q$(e,t){e.schemaEnv.meta||!e.opts.strictTypes||(Y$(e,t),e.opts.allowUnionTypes||X$(e,t),ez(e,e.dataTypes))}function Y$(e,t){if(t.length){if(!e.dataTypes.length){e.dataTypes=t;return}t.forEach(r=>{Kh(e.dataTypes,r)||su(e,`type "${r}" not allowed by context "${e.dataTypes.join(",")}"`)}),rz(e,t)}}function X$(e,t){t.length>1&&!(t.length===2&&t.includes("null"))&&su(e,"use allowUnionTypes to allow union type keyword")}function ez(e,t){let r=e.self.RULES.all;for(let n in r){let o=r[n];if(typeof o=="object"&&(0,iu.shouldUseRule)(e.schema,o)){let{type:i}=o.definition;i.length&&!i.some(s=>tz(t,s))&&su(e,`missing type "${i.join(",")}" for keyword "${n}"`)}}}function tz(e,t){return e.includes(t)||t==="number"&&e.includes("integer")}function Kh(e,t){return e.includes(t)||t==="integer"&&e.includes("number")}function rz(e,t){let r=[];for(let n of e.dataTypes)Kh(t,n)?r.push(n):t.includes("integer")&&n==="number"&&r.push("integer");e.dataTypes=r}function su(e,t){let r=e.schemaEnv.baseId+e.errSchemaPath;t+=` at "${r}" (strictTypes)`,(0,Mt.checkStrictMode)(e,t,e.opts.strictTypes)}var rs=class{constructor(t,r,n){if((0,_o.validateKeywordUsage)(t,r,n),this.gen=t.gen,this.allErrors=t.allErrors,this.keyword=n,this.data=t.data,this.schema=t.schema[n],this.$data=r.$data&&t.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,Mt.schemaRefOrVal)(t,this.schema,n,this.$data),this.schemaType=r.schemaType,this.parentSchema=t.schema,this.params={},this.it=t,this.def=r,this.$data)this.schemaCode=t.gen.const("vSchema",Yh(this.$data,t));else if(this.schemaCode=this.schemaValue,!(0,_o.validSchemaType)(this.schema,r.schemaType,r.allowUndefined))throw new Error(`${n} value must be ${JSON.stringify(r.schemaType)}`);("code"in r?r.trackErrors:r.errors!==!1)&&(this.errsCount=t.gen.const("_errs",q.default.errors))}result(t,r,n){this.failResult((0,C.not)(t),r,n)}failResult(t,r,n){this.gen.if(t),n?n():this.error(),r?(this.gen.else(),r(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(t,r){this.failResult((0,C.not)(t),void 0,r)}fail(t){if(t===void 0){this.error(),this.allErrors||this.gen.if(!1);return}this.gen.if(t),this.error(),this.allErrors?this.gen.endIf():this.gen.else()}fail$data(t){if(!this.$data)return this.fail(t);let{schemaCode:r}=this;this.fail((0,C._)`${r} !== undefined && (${(0,C.or)(this.invalid$data(),t)})`)}error(t,r,n){if(r){this.setParams(r),this._error(t,n),this.setParams({});return}this._error(t,n)}_error(t,r){(t?yo.reportExtraError:yo.reportError)(this,this.def.error,r)}$dataError(){(0,yo.reportError)(this,this.def.$dataError||yo.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,yo.resetErrorsCount)(this.gen,this.errsCount)}ok(t){this.allErrors||this.gen.if(t)}setParams(t,r){r?Object.assign(this.params,t):this.params=t}block$data(t,r,n=C.nil){this.gen.block(()=>{this.check$data(t,n),r()})}check$data(t=C.nil,r=C.nil){if(!this.$data)return;let{gen:n,schemaCode:o,schemaType:i,def:s}=this;n.if((0,C.or)((0,C._)`${o} === undefined`,r)),t!==C.nil&&n.assign(t,!0),(i.length||s.validateSchema)&&(n.elseIf(this.invalid$data()),this.$dataError(),t!==C.nil&&n.assign(t,!1)),n.else()}invalid$data(){let{gen:t,schemaCode:r,schemaType:n,def:o,it:i}=this;return(0,C.or)(s(),a());function s(){if(n.length){if(!(r instanceof C.Name))throw new Error("ajv implementation error");let c=Array.isArray(n)?n:[n];return(0,C._)`${(0,ts.checkDataTypes)(c,r,i.opts.strictNumbers,ts.DataType.Wrong)}`}return C.nil}function a(){if(o.validateSchema){let c=t.scopeValue("validate$data",{ref:o.validateSchema});return(0,C._)`!${c}(${r})`}return C.nil}}subschema(t,r){let n=(0,ou.getSubschema)(this.it,t);(0,ou.extendSubschemaData)(n,this.it,t),(0,ou.extendSubschemaMode)(n,t);let o={...this.it,...n,items:void 0,props:void 0};return J$(o,r),o}mergeEvaluated(t,r){let{it:n,gen:o}=this;n.opts.unevaluated&&(n.props!==!0&&t.props!==void 0&&(n.props=Mt.mergeEvaluated.props(o,t.props,n.props,r)),n.items!==!0&&t.items!==void 0&&(n.items=Mt.mergeEvaluated.items(o,t.items,n.items,r)))}mergeValidEvaluated(t,r){let{it:n,gen:o}=this;if(n.opts.unevaluated&&(n.props!==!0||n.items!==!0))return o.if(r,()=>this.mergeEvaluated(t,C.Name)),!0}};rr.KeywordCxt=rs;function Qh(e,t,r,n){let o=new rs(e,r,t);"code"in r?r.code(o,n):o.$data&&r.validate?(0,_o.funcKeywordCode)(o,r):"macro"in r?(0,_o.macroKeywordCode)(o,r):(r.compile||r.validate)&&(0,_o.funcKeywordCode)(o,r)}var nz=/^\/(?:[^~]|~0|~1)*$/,oz=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function Yh(e,{dataLevel:t,dataNames:r,dataPathArr:n}){let o,i;if(e==="")return q.default.rootData;if(e[0]==="/"){if(!nz.test(e))throw new Error(`Invalid JSON-pointer: ${e}`);o=e,i=q.default.rootData}else{let d=oz.exec(e);if(!d)throw new Error(`Invalid JSON-pointer: ${e}`);let u=+d[1];if(o=d[2],o==="#"){if(u>=t)throw new Error(c("property/index",u));return n[t-u]}if(u>t)throw new Error(c("data",u));if(i=r[t-u],!o)return i}let s=i,a=o.split("/");for(let d of a)d&&(i=(0,C._)`${i}${(0,C.getProperty)((0,Mt.unescapeJsonPointer)(d))}`,s=(0,C._)`${s} && ${i}`);return s;function c(d,u){return`Cannot access ${d} ${u} levels up, current level is ${t}`}}rr.getData=Yh});var ns=T(cu=>{"use strict";Object.defineProperty(cu,"__esModule",{value:!0});var au=class extends Error{constructor(t){super("validation failed"),this.errors=t,this.ajv=this.validation=!0}};cu.default=au});var vo=T(lu=>{"use strict";Object.defineProperty(lu,"__esModule",{value:!0});var du=go(),uu=class extends Error{constructor(t,r,n,o){super(o||`can't resolve reference ${n} from id ${r}`),this.missingRef=(0,du.resolveUrl)(t,r,n),this.missingSchema=(0,du.normalizeId)((0,du.getFullPath)(t,this.missingRef))}};lu.default=uu});var is=T(it=>{"use strict";Object.defineProperty(it,"__esModule",{value:!0});it.resolveSchema=it.getCompilingSchema=it.resolveRef=it.compileSchema=it.SchemaEnv=void 0;var pt=F(),iz=ns(),Ar=At(),mt=go(),Xh=ee(),sz=bo(),_n=class{constructor(t){var r;this.refs={},this.dynamicAnchors={};let n;typeof t.schema=="object"&&(n=t.schema),this.schema=t.schema,this.schemaId=t.schemaId,this.root=t.root||this,this.baseId=(r=t.baseId)!==null&&r!==void 0?r:(0,mt.normalizeId)(n?.[t.schemaId||"$id"]),this.schemaPath=t.schemaPath,this.localRefs=t.localRefs,this.meta=t.meta,this.$async=n?.$async,this.refs={}}};it.SchemaEnv=_n;function mu(e){let t=eg.call(this,e);if(t)return t;let r=(0,mt.getFullPath)(this.opts.uriResolver,e.root.baseId),{es5:n,lines:o}=this.opts.code,{ownProperties:i}=this.opts,s=new pt.CodeGen(this.scope,{es5:n,lines:o,ownProperties:i}),a;e.$async&&(a=s.scopeValue("Error",{ref:iz.default,code:(0,pt._)`require("ajv/dist/runtime/validation_error").default`}));let c=s.scopeName("validate");e.validateName=c;let d={gen:s,allErrors:this.opts.allErrors,data:Ar.default.data,parentData:Ar.default.parentData,parentDataProperty:Ar.default.parentDataProperty,dataNames:[Ar.default.data],dataPathArr:[pt.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:s.scopeValue("schema",this.opts.code.source===!0?{ref:e.schema,code:(0,pt.stringify)(e.schema)}:{ref:e.schema}),validateName:c,ValidationError:a,schema:e.schema,schemaEnv:e,rootId:r,baseId:e.baseId||r,schemaPath:pt.nil,errSchemaPath:e.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,pt._)`""`,opts:this.opts,self:this},u;try{this._compilations.add(e),(0,sz.validateFunctionCode)(d),s.optimize(this.opts.code.optimize);let p=s.toString();u=`${s.scopeRefs(Ar.default.scope)}return ${p}`,this.opts.code.process&&(u=this.opts.code.process(u,e));let f=new Function(`${Ar.default.self}`,`${Ar.default.scope}`,u)(this,this.scope.get());if(this.scope.value(c,{ref:f}),f.errors=null,f.schema=e.schema,f.schemaEnv=e,e.$async&&(f.$async=!0),this.opts.code.source===!0&&(f.source={validateName:c,validateCode:p,scopeValues:s._values}),this.opts.unevaluated){let{props:h,items:g}=d;f.evaluated={props:h instanceof pt.Name?void 0:h,items:g instanceof pt.Name?void 0:g,dynamicProps:h instanceof pt.Name,dynamicItems:g instanceof pt.Name},f.source&&(f.source.evaluated=(0,pt.stringify)(f.evaluated))}return e.validate=f,e}catch(p){throw delete e.validate,delete e.validateName,u&&this.logger.error("Error compiling schema, function code:",u),p}finally{this._compilations.delete(e)}}it.compileSchema=mu;function az(e,t,r){var n;r=(0,mt.resolveUrl)(this.opts.uriResolver,t,r);let o=e.refs[r];if(o)return o;let i=uz.call(this,e,r);if(i===void 0){let s=(n=e.localRefs)===null||n===void 0?void 0:n[r],{schemaId:a}=this.opts;s&&(i=new _n({schema:s,schemaId:a,root:e,baseId:t}))}if(i!==void 0)return e.refs[r]=cz.call(this,i)}it.resolveRef=az;function cz(e){return(0,mt.inlineRef)(e.schema,this.opts.inlineRefs)?e.schema:e.validate?e:mu.call(this,e)}function eg(e){for(let t of this._compilations)if(dz(t,e))return t}it.getCompilingSchema=eg;function dz(e,t){return e.schema===t.schema&&e.root===t.root&&e.baseId===t.baseId}function uz(e,t){let r;for(;typeof(r=this.refs[t])=="string";)t=r;return r||this.schemas[t]||os.call(this,e,t)}function os(e,t){let r=this.opts.uriResolver.parse(t),n=(0,mt._getFullPath)(this.opts.uriResolver,r),o=(0,mt.getFullPath)(this.opts.uriResolver,e.baseId,void 0);if(Object.keys(e.schema).length>0&&n===o)return pu.call(this,r,e);let i=(0,mt.normalizeId)(n),s=this.refs[i]||this.schemas[i];if(typeof s=="string"){let a=os.call(this,e,s);return typeof a?.schema!="object"?void 0:pu.call(this,r,a)}if(typeof s?.schema=="object"){if(s.validate||mu.call(this,s),i===(0,mt.normalizeId)(t)){let{schema:a}=s,{schemaId:c}=this.opts,d=a[c];return d&&(o=(0,mt.resolveUrl)(this.opts.uriResolver,o,d)),new _n({schema:a,schemaId:c,root:e,baseId:o})}return pu.call(this,r,s)}}it.resolveSchema=os;var lz=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function pu(e,{baseId:t,schema:r,root:n}){var o;if(((o=e.fragment)===null||o===void 0?void 0:o[0])!=="/")return;for(let a of e.fragment.slice(1).split("/")){if(typeof r=="boolean")return;let c=r[(0,Xh.unescapeFragment)(a)];if(c===void 0)return;r=c;let d=typeof r=="object"&&r[this.opts.schemaId];!lz.has(a)&&d&&(t=(0,mt.resolveUrl)(this.opts.uriResolver,t,d))}let i;if(typeof r!="boolean"&&r.$ref&&!(0,Xh.schemaHasRulesButRef)(r,this.RULES)){let a=(0,mt.resolveUrl)(this.opts.uriResolver,t,r.$ref);i=os.call(this,n,a)}let{schemaId:s}=this.opts;if(i=i||new _n({schema:r,schemaId:s,root:n,baseId:t}),i.schema!==i.root.schema)return i}});var tg=T((Q2,pz)=>{pz.exports={$id:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#",description:"Meta-schema for $data reference (JSON AnySchema extension proposal)",type:"object",required:["$data"],properties:{$data:{type:"string",anyOf:[{format:"relative-json-pointer"},{format:"json-pointer"}]}},additionalProperties:!1}});var hu=T((Y2,ig)=>{"use strict";var mz=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),ng=RegExp.prototype.test.bind(/^(?:(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)$/u);function fu(e){let t="",r=0,n=0;for(n=0;n<e.length;n++)if(r=e[n].charCodeAt(0),r!==48){if(!(r>=48&&r<=57||r>=65&&r<=70||r>=97&&r<=102))return"";t+=e[n];break}for(n+=1;n<e.length;n++){if(r=e[n].charCodeAt(0),!(r>=48&&r<=57||r>=65&&r<=70||r>=97&&r<=102))return"";t+=e[n]}return t}var fz=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function rg(e){return e.length=0,!0}function hz(e,t,r){if(e.length){let n=fu(e);if(n!=="")t.push(n);else return r.error=!0,!1;e.length=0}return!0}function gz(e){let t=0,r={error:!1,address:"",zone:""},n=[],o=[],i=!1,s=!1,a=hz;for(let c=0;c<e.length;c++){let d=e[c];if(!(d==="["||d==="]"))if(d===":"){if(i===!0&&(s=!0),!a(o,n,r))break;if(++t>7){r.error=!0;break}c>0&&e[c-1]===":"&&(i=!0),n.push(":");continue}else if(d==="%"){if(!a(o,n,r))break;a=rg}else{o.push(d);continue}}return o.length&&(a===rg?r.zone=o.join(""):s?n.push(o.join("")):n.push(fu(o))),r.address=n.join(""),r}function og(e){if(yz(e,":")<2)return{host:e,isIPV6:!1};let t=gz(e);if(t.error)return{host:e,isIPV6:!1};{let r=t.address,n=t.address;return t.zone&&(r+="%"+t.zone,n+="%25"+t.zone),{host:r,isIPV6:!0,escapedHost:n}}}function yz(e,t){let r=0;for(let n=0;n<e.length;n++)e[n]===t&&r++;return r}function _z(e){let t=e,r=[],n=-1,o=0;for(;o=t.length;){if(o===1){if(t===".")break;if(t==="/"){r.push("/");break}else{r.push(t);break}}else if(o===2){if(t[0]==="."){if(t[1]===".")break;if(t[1]==="/"){t=t.slice(2);continue}}else if(t[0]==="/"&&(t[1]==="."||t[1]==="/")){r.push("/");break}}else if(o===3&&t==="/.."){r.length!==0&&r.pop(),r.push("/");break}if(t[0]==="."){if(t[1]==="."){if(t[2]==="/"){t=t.slice(3);continue}}else if(t[1]==="/"){t=t.slice(2);continue}}else if(t[0]==="/"&&t[1]==="."){if(t[2]==="/"){t=t.slice(2);continue}else if(t[2]==="."&&t[3]==="/"){t=t.slice(3),r.length!==0&&r.pop();continue}}if((n=t.indexOf("/",1))===-1){r.push(t);break}else r.push(t.slice(0,n)),t=t.slice(n)}return r.join("")}function bz(e,t){let r=t!==!0?escape:unescape;return e.scheme!==void 0&&(e.scheme=r(e.scheme)),e.userinfo!==void 0&&(e.userinfo=r(e.userinfo)),e.host!==void 0&&(e.host=r(e.host)),e.path!==void 0&&(e.path=r(e.path)),e.query!==void 0&&(e.query=r(e.query)),e.fragment!==void 0&&(e.fragment=r(e.fragment)),e}function vz(e){let t=[];if(e.userinfo!==void 0&&(t.push(e.userinfo),t.push("@")),e.host!==void 0){let r=unescape(e.host);if(!ng(r)){let n=og(r);n.isIPV6===!0?r=`[${n.escapedHost}]`:r=e.host}t.push(r)}return(typeof e.port=="number"||typeof e.port=="string")&&(t.push(":"),t.push(String(e.port))),t.length?t.join(""):void 0}ig.exports={nonSimpleDomain:fz,recomposeAuthority:vz,normalizeComponentEncoding:bz,removeDotSegments:_z,isIPv4:ng,isUUID:mz,normalizeIPv6:og,stringArrayToHexStripped:fu}});var ug=T((X2,dg)=>{"use strict";var{isUUID:wz}=hu(),kz=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,xz=["http","https","ws","wss","urn","urn:uuid"];function Sz(e){return xz.indexOf(e)!==-1}function gu(e){return e.secure===!0?!0:e.secure===!1?!1:e.scheme?e.scheme.length===3&&(e.scheme[0]==="w"||e.scheme[0]==="W")&&(e.scheme[1]==="s"||e.scheme[1]==="S")&&(e.scheme[2]==="s"||e.scheme[2]==="S"):!1}function sg(e){return e.host||(e.error=e.error||"HTTP URIs must have a host."),e}function ag(e){let t=String(e.scheme).toLowerCase()==="https";return(e.port===(t?443:80)||e.port==="")&&(e.port=void 0),e.path||(e.path="/"),e}function $z(e){return e.secure=gu(e),e.resourceName=(e.path||"/")+(e.query?"?"+e.query:""),e.path=void 0,e.query=void 0,e}function zz(e){if((e.port===(gu(e)?443:80)||e.port==="")&&(e.port=void 0),typeof e.secure=="boolean"&&(e.scheme=e.secure?"wss":"ws",e.secure=void 0),e.resourceName){let[t,r]=e.resourceName.split("?");e.path=t&&t!=="/"?t:void 0,e.query=r,e.resourceName=void 0}return e.fragment=void 0,e}function Tz(e,t){if(!e.path)return e.error="URN can not be parsed",e;let r=e.path.match(kz);if(r){let n=t.scheme||e.scheme||"urn";e.nid=r[1].toLowerCase(),e.nss=r[2];let o=`${n}:${t.nid||e.nid}`,i=yu(o);e.path=void 0,i&&(e=i.parse(e,t))}else e.error=e.error||"URN can not be parsed.";return e}function Pz(e,t){if(e.nid===void 0)throw new Error("URN without nid cannot be serialized");let r=t.scheme||e.scheme||"urn",n=e.nid.toLowerCase(),o=`${r}:${t.nid||n}`,i=yu(o);i&&(e=i.serialize(e,t));let s=e,a=e.nss;return s.path=`${n||t.nid}:${a}`,t.skipEscape=!0,s}function Rz(e,t){let r=e;return r.uuid=r.nss,r.nss=void 0,!t.tolerant&&(!r.uuid||!wz(r.uuid))&&(r.error=r.error||"UUID is not valid."),r}function Oz(e){let t=e;return t.nss=(e.uuid||"").toLowerCase(),t}var cg={scheme:"http",domainHost:!0,parse:sg,serialize:ag},Ez={scheme:"https",domainHost:cg.domainHost,parse:sg,serialize:ag},ss={scheme:"ws",domainHost:!0,parse:$z,serialize:zz},jz={scheme:"wss",domainHost:ss.domainHost,parse:ss.parse,serialize:ss.serialize},Iz={scheme:"urn",parse:Tz,serialize:Pz,skipNormalize:!0},Cz={scheme:"urn:uuid",parse:Rz,serialize:Oz,skipNormalize:!0},as={http:cg,https:Ez,ws:ss,wss:jz,urn:Iz,"urn:uuid":Cz};Object.setPrototypeOf(as,null);function yu(e){return e&&(as[e]||as[e.toLowerCase()])||void 0}dg.exports={wsIsSecure:gu,SCHEMES:as,isValidSchemeName:Sz,getSchemeHandler:yu}});var mg=T((eM,ds)=>{"use strict";var{normalizeIPv6:Az,removeDotSegments:wo,recomposeAuthority:Mz,normalizeComponentEncoding:cs,isIPv4:Nz,nonSimpleDomain:Dz}=hu(),{SCHEMES:Lz,getSchemeHandler:lg}=ug();function qz(e,t){return typeof e=="string"?e=xt(Nt(e,t),t):typeof e=="object"&&(e=Nt(xt(e,t),t)),e}function Uz(e,t,r){let n=r?Object.assign({scheme:"null"},r):{scheme:"null"},o=pg(Nt(e,n),Nt(t,n),n,!0);return n.skipEscape=!0,xt(o,n)}function pg(e,t,r,n){let o={};return n||(e=Nt(xt(e,r),r),t=Nt(xt(t,r),r)),r=r||{},!r.tolerant&&t.scheme?(o.scheme=t.scheme,o.userinfo=t.userinfo,o.host=t.host,o.port=t.port,o.path=wo(t.path||""),o.query=t.query):(t.userinfo!==void 0||t.host!==void 0||t.port!==void 0?(o.userinfo=t.userinfo,o.host=t.host,o.port=t.port,o.path=wo(t.path||""),o.query=t.query):(t.path?(t.path[0]==="/"?o.path=wo(t.path):((e.userinfo!==void 0||e.host!==void 0||e.port!==void 0)&&!e.path?o.path="/"+t.path:e.path?o.path=e.path.slice(0,e.path.lastIndexOf("/")+1)+t.path:o.path=t.path,o.path=wo(o.path)),o.query=t.query):(o.path=e.path,t.query!==void 0?o.query=t.query:o.query=e.query),o.userinfo=e.userinfo,o.host=e.host,o.port=e.port),o.scheme=e.scheme),o.fragment=t.fragment,o}function Zz(e,t,r){return typeof e=="string"?(e=unescape(e),e=xt(cs(Nt(e,r),!0),{...r,skipEscape:!0})):typeof e=="object"&&(e=xt(cs(e,!0),{...r,skipEscape:!0})),typeof t=="string"?(t=unescape(t),t=xt(cs(Nt(t,r),!0),{...r,skipEscape:!0})):typeof t=="object"&&(t=xt(cs(t,!0),{...r,skipEscape:!0})),e.toLowerCase()===t.toLowerCase()}function xt(e,t){let r={host:e.host,scheme:e.scheme,userinfo:e.userinfo,port:e.port,path:e.path,query:e.query,nid:e.nid,nss:e.nss,uuid:e.uuid,fragment:e.fragment,reference:e.reference,resourceName:e.resourceName,secure:e.secure,error:""},n=Object.assign({},t),o=[],i=lg(n.scheme||r.scheme);i&&i.serialize&&i.serialize(r,n),r.path!==void 0&&(n.skipEscape?r.path=unescape(r.path):(r.path=escape(r.path),r.scheme!==void 0&&(r.path=r.path.split("%3A").join(":")))),n.reference!=="suffix"&&r.scheme&&o.push(r.scheme,":");let s=Mz(r);if(s!==void 0&&(n.reference!=="suffix"&&o.push("//"),o.push(s),r.path&&r.path[0]!=="/"&&o.push("/")),r.path!==void 0){let a=r.path;!n.absolutePath&&(!i||!i.absolutePath)&&(a=wo(a)),s===void 0&&a[0]==="/"&&a[1]==="/"&&(a="/%2F"+a.slice(2)),o.push(a)}return r.query!==void 0&&o.push("?",r.query),r.fragment!==void 0&&o.push("#",r.fragment),o.join("")}var Jz=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function Nt(e,t){let r=Object.assign({},t),n={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0},o=!1;r.reference==="suffix"&&(r.scheme?e=r.scheme+":"+e:e="//"+e);let i=e.match(Jz);if(i){if(n.scheme=i[1],n.userinfo=i[3],n.host=i[4],n.port=parseInt(i[5],10),n.path=i[6]||"",n.query=i[7],n.fragment=i[8],isNaN(n.port)&&(n.port=i[5]),n.host)if(Nz(n.host)===!1){let c=Az(n.host);n.host=c.host.toLowerCase(),o=c.isIPV6}else o=!0;n.scheme===void 0&&n.userinfo===void 0&&n.host===void 0&&n.port===void 0&&n.query===void 0&&!n.path?n.reference="same-document":n.scheme===void 0?n.reference="relative":n.fragment===void 0?n.reference="absolute":n.reference="uri",r.reference&&r.reference!=="suffix"&&r.reference!==n.reference&&(n.error=n.error||"URI is not a "+r.reference+" reference.");let s=lg(r.scheme||n.scheme);if(!r.unicodeSupport&&(!s||!s.unicodeSupport)&&n.host&&(r.domainHost||s&&s.domainHost)&&o===!1&&Dz(n.host))try{n.host=URL.domainToASCII(n.host.toLowerCase())}catch(a){n.error=n.error||"Host's domain name can not be converted to ASCII: "+a}(!s||s&&!s.skipNormalize)&&(e.indexOf("%")!==-1&&(n.scheme!==void 0&&(n.scheme=unescape(n.scheme)),n.host!==void 0&&(n.host=unescape(n.host))),n.path&&(n.path=escape(unescape(n.path))),n.fragment&&(n.fragment=encodeURI(decodeURIComponent(n.fragment)))),s&&s.parse&&s.parse(n,r)}else n.error=n.error||"URI can not be parsed.";return n}var _u={SCHEMES:Lz,normalize:qz,resolve:Uz,resolveComponent:pg,equal:Zz,serialize:xt,parse:Nt};ds.exports=_u;ds.exports.default=_u;ds.exports.fastUri=_u});var hg=T(bu=>{"use strict";Object.defineProperty(bu,"__esModule",{value:!0});var fg=mg();fg.code='require("ajv/dist/runtime/uri").default';bu.default=fg});var xg=T(Te=>{"use strict";Object.defineProperty(Te,"__esModule",{value:!0});Te.CodeGen=Te.Name=Te.nil=Te.stringify=Te.str=Te._=Te.KeywordCxt=void 0;var Fz=bo();Object.defineProperty(Te,"KeywordCxt",{enumerable:!0,get:function(){return Fz.KeywordCxt}});var bn=F();Object.defineProperty(Te,"_",{enumerable:!0,get:function(){return bn._}});Object.defineProperty(Te,"str",{enumerable:!0,get:function(){return bn.str}});Object.defineProperty(Te,"stringify",{enumerable:!0,get:function(){return bn.stringify}});Object.defineProperty(Te,"nil",{enumerable:!0,get:function(){return bn.nil}});Object.defineProperty(Te,"Name",{enumerable:!0,get:function(){return bn.Name}});Object.defineProperty(Te,"CodeGen",{enumerable:!0,get:function(){return bn.CodeGen}});var Vz=ns(),vg=vo(),Wz=Hd(),ko=is(),Bz=F(),xo=go(),us=ho(),wu=ee(),gg=tg(),Hz=hg(),wg=(e,t)=>new RegExp(e,t);wg.code="new RegExp";var Gz=["removeAdditional","useDefaults","coerceTypes"],Kz=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),Qz={errorDataPath:"",format:"`validateFormats: false` can be used instead.",nullable:'"nullable" keyword is supported by default.',jsonPointers:"Deprecated jsPropertySyntax can be used instead.",extendRefs:"Deprecated ignoreKeywordsWithRef can be used instead.",missingRefs:"Pass empty schema with $id that should be ignored to ajv.addSchema.",processCode:"Use option `code: {process: (code, schemaEnv: object) => string}`",sourceCode:"Use option `code: {source: true}`",strictDefaults:"It is default now, see option `strict`.",strictKeywords:"It is default now, see option `strict`.",uniqueItems:'"uniqueItems" keyword is always validated.',unknownFormats:"Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).",cache:"Map is used as cache, schema object as key.",serialize:"Map is used as cache, schema object as key.",ajvErrors:"It is default now."},Yz={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},yg=200;function Xz(e){var t,r,n,o,i,s,a,c,d,u,p,m,f,h,g,y,v,w,k,O,M,Ie,Qe,Fr,Js;let On=e.strict,Fs=(t=e.code)===null||t===void 0?void 0:t.optimize,op=Fs===!0||Fs===void 0?1:Fs||0,ip=(n=(r=e.code)===null||r===void 0?void 0:r.regExp)!==null&&n!==void 0?n:wg,Qb=(o=e.uriResolver)!==null&&o!==void 0?o:Hz.default;return{strictSchema:(s=(i=e.strictSchema)!==null&&i!==void 0?i:On)!==null&&s!==void 0?s:!0,strictNumbers:(c=(a=e.strictNumbers)!==null&&a!==void 0?a:On)!==null&&c!==void 0?c:!0,strictTypes:(u=(d=e.strictTypes)!==null&&d!==void 0?d:On)!==null&&u!==void 0?u:"log",strictTuples:(m=(p=e.strictTuples)!==null&&p!==void 0?p:On)!==null&&m!==void 0?m:"log",strictRequired:(h=(f=e.strictRequired)!==null&&f!==void 0?f:On)!==null&&h!==void 0?h:!1,code:e.code?{...e.code,optimize:op,regExp:ip}:{optimize:op,regExp:ip},loopRequired:(g=e.loopRequired)!==null&&g!==void 0?g:yg,loopEnum:(y=e.loopEnum)!==null&&y!==void 0?y:yg,meta:(v=e.meta)!==null&&v!==void 0?v:!0,messages:(w=e.messages)!==null&&w!==void 0?w:!0,inlineRefs:(k=e.inlineRefs)!==null&&k!==void 0?k:!0,schemaId:(O=e.schemaId)!==null&&O!==void 0?O:"$id",addUsedSchema:(M=e.addUsedSchema)!==null&&M!==void 0?M:!0,validateSchema:(Ie=e.validateSchema)!==null&&Ie!==void 0?Ie:!0,validateFormats:(Qe=e.validateFormats)!==null&&Qe!==void 0?Qe:!0,unicodeRegExp:(Fr=e.unicodeRegExp)!==null&&Fr!==void 0?Fr:!0,int32range:(Js=e.int32range)!==null&&Js!==void 0?Js:!0,uriResolver:Qb}}var So=class{constructor(t={}){this.schemas={},this.refs={},this.formats={},this._compilations=new Set,this._loading={},this._cache=new Map,t=this.opts={...t,...Xz(t)};let{es5:r,lines:n}=this.opts.code;this.scope=new Bz.ValueScope({scope:{},prefixes:Kz,es5:r,lines:n}),this.logger=iT(t.logger);let o=t.validateFormats;t.validateFormats=!1,this.RULES=(0,Wz.getRules)(),_g.call(this,Qz,t,"NOT SUPPORTED"),_g.call(this,Yz,t,"DEPRECATED","warn"),this._metaOpts=nT.call(this),t.formats&&tT.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),t.keywords&&rT.call(this,t.keywords),typeof t.meta=="object"&&this.addMetaSchema(t.meta),eT.call(this),t.validateFormats=o}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:t,meta:r,schemaId:n}=this.opts,o=gg;n==="id"&&(o={...gg},o.id=o.$id,delete o.$id),r&&t&&this.addMetaSchema(o,o[n],!1)}defaultMeta(){let{meta:t,schemaId:r}=this.opts;return this.opts.defaultMeta=typeof t=="object"?t[r]||t:void 0}validate(t,r){let n;if(typeof t=="string"){if(n=this.getSchema(t),!n)throw new Error(`no schema with key or ref "${t}"`)}else n=this.compile(t);let o=n(r);return"$async"in n||(this.errors=n.errors),o}compile(t,r){let n=this._addSchema(t,r);return n.validate||this._compileSchemaEnv(n)}compileAsync(t,r){if(typeof this.opts.loadSchema!="function")throw new Error("options.loadSchema should be a function");let{loadSchema:n}=this.opts;return o.call(this,t,r);async function o(u,p){await i.call(this,u.$schema);let m=this._addSchema(u,p);return m.validate||s.call(this,m)}async function i(u){u&&!this.getSchema(u)&&await o.call(this,{$ref:u},!0)}async function s(u){try{return this._compileSchemaEnv(u)}catch(p){if(!(p instanceof vg.default))throw p;return a.call(this,p),await c.call(this,p.missingSchema),s.call(this,u)}}function a({missingSchema:u,missingRef:p}){if(this.refs[u])throw new Error(`AnySchema ${u} is loaded but ${p} cannot be resolved`)}async function c(u){let p=await d.call(this,u);this.refs[u]||await i.call(this,p.$schema),this.refs[u]||this.addSchema(p,u,r)}async function d(u){let p=this._loading[u];if(p)return p;try{return await(this._loading[u]=n(u))}finally{delete this._loading[u]}}}addSchema(t,r,n,o=this.opts.validateSchema){if(Array.isArray(t)){for(let s of t)this.addSchema(s,void 0,n,o);return this}let i;if(typeof t=="object"){let{schemaId:s}=this.opts;if(i=t[s],i!==void 0&&typeof i!="string")throw new Error(`schema ${s} must be string`)}return r=(0,xo.normalizeId)(r||i),this._checkUnique(r),this.schemas[r]=this._addSchema(t,n,r,o,!0),this}addMetaSchema(t,r,n=this.opts.validateSchema){return this.addSchema(t,r,!0,n),this}validateSchema(t,r){if(typeof t=="boolean")return!0;let n;if(n=t.$schema,n!==void 0&&typeof n!="string")throw new Error("$schema must be a string");if(n=n||this.opts.defaultMeta||this.defaultMeta(),!n)return this.logger.warn("meta-schema not available"),this.errors=null,!0;let o=this.validate(n,t);if(!o&&r){let i="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(i);else throw new Error(i)}return o}getSchema(t){let r;for(;typeof(r=bg.call(this,t))=="string";)t=r;if(r===void 0){let{schemaId:n}=this.opts,o=new ko.SchemaEnv({schema:{},schemaId:n});if(r=ko.resolveSchema.call(this,o,t),!r)return;this.refs[t]=r}return r.validate||this._compileSchemaEnv(r)}removeSchema(t){if(t instanceof RegExp)return this._removeAllSchemas(this.schemas,t),this._removeAllSchemas(this.refs,t),this;switch(typeof t){case"undefined":return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case"string":{let r=bg.call(this,t);return typeof r=="object"&&this._cache.delete(r.schema),delete this.schemas[t],delete this.refs[t],this}case"object":{let r=t;this._cache.delete(r);let n=t[this.opts.schemaId];return n&&(n=(0,xo.normalizeId)(n),delete this.schemas[n],delete this.refs[n]),this}default:throw new Error("ajv.removeSchema: invalid parameter")}}addVocabulary(t){for(let r of t)this.addKeyword(r);return this}addKeyword(t,r){let n;if(typeof t=="string")n=t,typeof r=="object"&&(this.logger.warn("these parameters are deprecated, see docs for addKeyword"),r.keyword=n);else if(typeof t=="object"&&r===void 0){if(r=t,n=r.keyword,Array.isArray(n)&&!n.length)throw new Error("addKeywords: keyword must be string or non-empty array")}else throw new Error("invalid addKeywords parameters");if(aT.call(this,n,r),!r)return(0,wu.eachItem)(n,i=>vu.call(this,i)),this;dT.call(this,r);let o={...r,type:(0,us.getJSONTypes)(r.type),schemaType:(0,us.getJSONTypes)(r.schemaType)};return(0,wu.eachItem)(n,o.type.length===0?i=>vu.call(this,i,o):i=>o.type.forEach(s=>vu.call(this,i,o,s))),this}getKeyword(t){let r=this.RULES.all[t];return typeof r=="object"?r.definition:!!r}removeKeyword(t){let{RULES:r}=this;delete r.keywords[t],delete r.all[t];for(let n of r.rules){let o=n.rules.findIndex(i=>i.keyword===t);o>=0&&n.rules.splice(o,1)}return this}addFormat(t,r){return typeof r=="string"&&(r=new RegExp(r)),this.formats[t]=r,this}errorsText(t=this.errors,{separator:r=", ",dataVar:n="data"}={}){return!t||t.length===0?"No errors":t.map(o=>`${n}${o.instancePath} ${o.message}`).reduce((o,i)=>o+r+i)}$dataMetaSchema(t,r){let n=this.RULES.all;t=JSON.parse(JSON.stringify(t));for(let o of r){let i=o.split("/").slice(1),s=t;for(let a of i)s=s[a];for(let a in n){let c=n[a];if(typeof c!="object")continue;let{$data:d}=c.definition,u=s[a];d&&u&&(s[a]=kg(u))}}return t}_removeAllSchemas(t,r){for(let n in t){let o=t[n];(!r||r.test(n))&&(typeof o=="string"?delete t[n]:o&&!o.meta&&(this._cache.delete(o.schema),delete t[n]))}}_addSchema(t,r,n,o=this.opts.validateSchema,i=this.opts.addUsedSchema){let s,{schemaId:a}=this.opts;if(typeof t=="object")s=t[a];else{if(this.opts.jtd)throw new Error("schema must be object");if(typeof t!="boolean")throw new Error("schema must be object or boolean")}let c=this._cache.get(t);if(c!==void 0)return c;n=(0,xo.normalizeId)(s||n);let d=xo.getSchemaRefs.call(this,t,n);return c=new ko.SchemaEnv({schema:t,schemaId:a,meta:r,baseId:n,localRefs:d}),this._cache.set(c.schema,c),i&&!n.startsWith("#")&&(n&&this._checkUnique(n),this.refs[n]=c),o&&this.validateSchema(t,!0),c}_checkUnique(t){if(this.schemas[t]||this.refs[t])throw new Error(`schema with key or id "${t}" already exists`)}_compileSchemaEnv(t){if(t.meta?this._compileMetaSchema(t):ko.compileSchema.call(this,t),!t.validate)throw new Error("ajv implementation error");return t.validate}_compileMetaSchema(t){let r=this.opts;this.opts=this._metaOpts;try{ko.compileSchema.call(this,t)}finally{this.opts=r}}};So.ValidationError=Vz.default;So.MissingRefError=vg.default;Te.default=So;function _g(e,t,r,n="error"){for(let o in e){let i=o;i in t&&this.logger[n](`${r}: option ${o}. ${e[i]}`)}}function bg(e){return e=(0,xo.normalizeId)(e),this.schemas[e]||this.refs[e]}function eT(){let e=this.opts.schemas;if(e)if(Array.isArray(e))this.addSchema(e);else for(let t in e)this.addSchema(e[t],t)}function tT(){for(let e in this.opts.formats){let t=this.opts.formats[e];t&&this.addFormat(e,t)}}function rT(e){if(Array.isArray(e)){this.addVocabulary(e);return}this.logger.warn("keywords option as map is deprecated, pass array");for(let t in e){let r=e[t];r.keyword||(r.keyword=t),this.addKeyword(r)}}function nT(){let e={...this.opts};for(let t of Gz)delete e[t];return e}var oT={log(){},warn(){},error(){}};function iT(e){if(e===!1)return oT;if(e===void 0)return console;if(e.log&&e.warn&&e.error)return e;throw new Error("logger must implement log, warn and error methods")}var sT=/^[a-z_$][a-z0-9_$:-]*$/i;function aT(e,t){let{RULES:r}=this;if((0,wu.eachItem)(e,n=>{if(r.keywords[n])throw new Error(`Keyword ${n} is already defined`);if(!sT.test(n))throw new Error(`Keyword ${n} has invalid name`)}),!!t&&t.$data&&!("code"in t||"validate"in t))throw new Error('$data keyword must have "code" or "validate" function')}function vu(e,t,r){var n;let o=t?.post;if(r&&o)throw new Error('keyword with "post" flag cannot have "type"');let{RULES:i}=this,s=o?i.post:i.rules.find(({type:c})=>c===r);if(s||(s={type:r,rules:[]},i.rules.push(s)),i.keywords[e]=!0,!t)return;let a={keyword:e,definition:{...t,type:(0,us.getJSONTypes)(t.type),schemaType:(0,us.getJSONTypes)(t.schemaType)}};t.before?cT.call(this,s,a,t.before):s.rules.push(a),i.all[e]=a,(n=t.implements)===null||n===void 0||n.forEach(c=>this.addKeyword(c))}function cT(e,t,r){let n=e.rules.findIndex(o=>o.keyword===r);n>=0?e.rules.splice(n,0,t):(e.rules.push(t),this.logger.warn(`rule ${r} is not defined`))}function dT(e){let{metaSchema:t}=e;t!==void 0&&(e.$data&&this.opts.$data&&(t=kg(t)),e.validateSchema=this.compile(t,!0))}var uT={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function kg(e){return{anyOf:[e,uT]}}});var Sg=T(ku=>{"use strict";Object.defineProperty(ku,"__esModule",{value:!0});var lT={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};ku.default=lT});var Pg=T(Mr=>{"use strict";Object.defineProperty(Mr,"__esModule",{value:!0});Mr.callRef=Mr.getValidate=void 0;var pT=vo(),$g=ot(),Ve=F(),vn=At(),zg=is(),ls=ee(),mT={keyword:"$ref",schemaType:"string",code(e){let{gen:t,schema:r,it:n}=e,{baseId:o,schemaEnv:i,validateName:s,opts:a,self:c}=n,{root:d}=i;if((r==="#"||r==="#/")&&o===d.baseId)return p();let u=zg.resolveRef.call(c,d,o,r);if(u===void 0)throw new pT.default(n.opts.uriResolver,o,r);if(u instanceof zg.SchemaEnv)return m(u);return f(u);function p(){if(i===d)return ps(e,s,i,i.$async);let h=t.scopeValue("root",{ref:d});return ps(e,(0,Ve._)`${h}.validate`,d,d.$async)}function m(h){let g=Tg(e,h);ps(e,g,h,h.$async)}function f(h){let g=t.scopeValue("schema",a.code.source===!0?{ref:h,code:(0,Ve.stringify)(h)}:{ref:h}),y=t.name("valid"),v=e.subschema({schema:h,dataTypes:[],schemaPath:Ve.nil,topSchemaRef:g,errSchemaPath:r},y);e.mergeEvaluated(v),e.ok(y)}}};function Tg(e,t){let{gen:r}=e;return t.validate?r.scopeValue("validate",{ref:t.validate}):(0,Ve._)`${r.scopeValue("wrapper",{ref:t})}.validate`}Mr.getValidate=Tg;function ps(e,t,r,n){let{gen:o,it:i}=e,{allErrors:s,schemaEnv:a,opts:c}=i,d=c.passContext?vn.default.this:Ve.nil;n?u():p();function u(){if(!a.$async)throw new Error("async schema referenced by sync schema");let h=o.let("valid");o.try(()=>{o.code((0,Ve._)`await ${(0,$g.callValidateCode)(e,t,d)}`),f(t),s||o.assign(h,!0)},g=>{o.if((0,Ve._)`!(${g} instanceof ${i.ValidationError})`,()=>o.throw(g)),m(g),s||o.assign(h,!1)}),e.ok(h)}function p(){e.result((0,$g.callValidateCode)(e,t,d),()=>f(t),()=>m(t))}function m(h){let g=(0,Ve._)`${h}.errors`;o.assign(vn.default.vErrors,(0,Ve._)`${vn.default.vErrors} === null ? ${g} : ${vn.default.vErrors}.concat(${g})`),o.assign(vn.default.errors,(0,Ve._)`${vn.default.vErrors}.length`)}function f(h){var g;if(!i.opts.unevaluated)return;let y=(g=r?.validate)===null||g===void 0?void 0:g.evaluated;if(i.props!==!0)if(y&&!y.dynamicProps)y.props!==void 0&&(i.props=ls.mergeEvaluated.props(o,y.props,i.props));else{let v=o.var("props",(0,Ve._)`${h}.evaluated.props`);i.props=ls.mergeEvaluated.props(o,v,i.props,Ve.Name)}if(i.items!==!0)if(y&&!y.dynamicItems)y.items!==void 0&&(i.items=ls.mergeEvaluated.items(o,y.items,i.items));else{let v=o.var("items",(0,Ve._)`${h}.evaluated.items`);i.items=ls.mergeEvaluated.items(o,v,i.items,Ve.Name)}}}Mr.callRef=ps;Mr.default=mT});var Rg=T(xu=>{"use strict";Object.defineProperty(xu,"__esModule",{value:!0});var fT=Sg(),hT=Pg(),gT=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",fT.default,hT.default];xu.default=gT});var Og=T(Su=>{"use strict";Object.defineProperty(Su,"__esModule",{value:!0});var ms=F(),nr=ms.operators,fs={maximum:{okStr:"<=",ok:nr.LTE,fail:nr.GT},minimum:{okStr:">=",ok:nr.GTE,fail:nr.LT},exclusiveMaximum:{okStr:"<",ok:nr.LT,fail:nr.GTE},exclusiveMinimum:{okStr:">",ok:nr.GT,fail:nr.LTE}},yT={message:({keyword:e,schemaCode:t})=>(0,ms.str)`must be ${fs[e].okStr} ${t}`,params:({keyword:e,schemaCode:t})=>(0,ms._)`{comparison: ${fs[e].okStr}, limit: ${t}}`},_T={keyword:Object.keys(fs),type:"number",schemaType:"number",$data:!0,error:yT,code(e){let{keyword:t,data:r,schemaCode:n}=e;e.fail$data((0,ms._)`${r} ${fs[t].fail} ${n} || isNaN(${r})`)}};Su.default=_T});var Eg=T($u=>{"use strict";Object.defineProperty($u,"__esModule",{value:!0});var $o=F(),bT={message:({schemaCode:e})=>(0,$o.str)`must be multiple of ${e}`,params:({schemaCode:e})=>(0,$o._)`{multipleOf: ${e}}`},vT={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:bT,code(e){let{gen:t,data:r,schemaCode:n,it:o}=e,i=o.opts.multipleOfPrecision,s=t.let("res"),a=i?(0,$o._)`Math.abs(Math.round(${s}) - ${s}) > 1e-${i}`:(0,$o._)`${s} !== parseInt(${s})`;e.fail$data((0,$o._)`(${n} === 0 || (${s} = ${r}/${n}, ${a}))`)}};$u.default=vT});var Ig=T(zu=>{"use strict";Object.defineProperty(zu,"__esModule",{value:!0});function jg(e){let t=e.length,r=0,n=0,o;for(;n<t;)r++,o=e.charCodeAt(n++),o>=55296&&o<=56319&&n<t&&(o=e.charCodeAt(n),(o&64512)===56320&&n++);return r}zu.default=jg;jg.code='require("ajv/dist/runtime/ucs2length").default'});var Cg=T(Tu=>{"use strict";Object.defineProperty(Tu,"__esModule",{value:!0});var Nr=F(),wT=ee(),kT=Ig(),xT={message({keyword:e,schemaCode:t}){let r=e==="maxLength"?"more":"fewer";return(0,Nr.str)`must NOT have ${r} than ${t} characters`},params:({schemaCode:e})=>(0,Nr._)`{limit: ${e}}`},ST={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:xT,code(e){let{keyword:t,data:r,schemaCode:n,it:o}=e,i=t==="maxLength"?Nr.operators.GT:Nr.operators.LT,s=o.opts.unicode===!1?(0,Nr._)`${r}.length`:(0,Nr._)`${(0,wT.useFunc)(e.gen,kT.default)}(${r})`;e.fail$data((0,Nr._)`${s} ${i} ${n}`)}};Tu.default=ST});var Ag=T(Pu=>{"use strict";Object.defineProperty(Pu,"__esModule",{value:!0});var $T=ot(),hs=F(),zT={message:({schemaCode:e})=>(0,hs.str)`must match pattern "${e}"`,params:({schemaCode:e})=>(0,hs._)`{pattern: ${e}}`},TT={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:zT,code(e){let{data:t,$data:r,schema:n,schemaCode:o,it:i}=e,s=i.opts.unicodeRegExp?"u":"",a=r?(0,hs._)`(new RegExp(${o}, ${s}))`:(0,$T.usePattern)(e,n);e.fail$data((0,hs._)`!${a}.test(${t})`)}};Pu.default=TT});var Mg=T(Ru=>{"use strict";Object.defineProperty(Ru,"__esModule",{value:!0});var zo=F(),PT={message({keyword:e,schemaCode:t}){let r=e==="maxProperties"?"more":"fewer";return(0,zo.str)`must NOT have ${r} than ${t} properties`},params:({schemaCode:e})=>(0,zo._)`{limit: ${e}}`},RT={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:PT,code(e){let{keyword:t,data:r,schemaCode:n}=e,o=t==="maxProperties"?zo.operators.GT:zo.operators.LT;e.fail$data((0,zo._)`Object.keys(${r}).length ${o} ${n}`)}};Ru.default=RT});var Ng=T(Ou=>{"use strict";Object.defineProperty(Ou,"__esModule",{value:!0});var To=ot(),Po=F(),OT=ee(),ET={message:({params:{missingProperty:e}})=>(0,Po.str)`must have required property '${e}'`,params:({params:{missingProperty:e}})=>(0,Po._)`{missingProperty: ${e}}`},jT={keyword:"required",type:"object",schemaType:"array",$data:!0,error:ET,code(e){let{gen:t,schema:r,schemaCode:n,data:o,$data:i,it:s}=e,{opts:a}=s;if(!i&&r.length===0)return;let c=r.length>=a.loopRequired;if(s.allErrors?d():u(),a.strictRequired){let f=e.parentSchema.properties,{definedProperties:h}=e.it;for(let g of r)if(f?.[g]===void 0&&!h.has(g)){let y=s.schemaEnv.baseId+s.errSchemaPath,v=`required property "${g}" is not defined at "${y}" (strictRequired)`;(0,OT.checkStrictMode)(s,v,s.opts.strictRequired)}}function d(){if(c||i)e.block$data(Po.nil,p);else for(let f of r)(0,To.checkReportMissingProp)(e,f)}function u(){let f=t.let("missing");if(c||i){let h=t.let("valid",!0);e.block$data(h,()=>m(f,h)),e.ok(h)}else t.if((0,To.checkMissingProp)(e,r,f)),(0,To.reportMissingProp)(e,f),t.else()}function p(){t.forOf("prop",n,f=>{e.setParams({missingProperty:f}),t.if((0,To.noPropertyInData)(t,o,f,a.ownProperties),()=>e.error())})}function m(f,h){e.setParams({missingProperty:f}),t.forOf(f,n,()=>{t.assign(h,(0,To.propertyInData)(t,o,f,a.ownProperties)),t.if((0,Po.not)(h),()=>{e.error(),t.break()})},Po.nil)}}};Ou.default=jT});var Dg=T(Eu=>{"use strict";Object.defineProperty(Eu,"__esModule",{value:!0});var Ro=F(),IT={message({keyword:e,schemaCode:t}){let r=e==="maxItems"?"more":"fewer";return(0,Ro.str)`must NOT have ${r} than ${t} items`},params:({schemaCode:e})=>(0,Ro._)`{limit: ${e}}`},CT={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:IT,code(e){let{keyword:t,data:r,schemaCode:n}=e,o=t==="maxItems"?Ro.operators.GT:Ro.operators.LT;e.fail$data((0,Ro._)`${r}.length ${o} ${n}`)}};Eu.default=CT});var gs=T(ju=>{"use strict";Object.defineProperty(ju,"__esModule",{value:!0});var Lg=ru();Lg.code='require("ajv/dist/runtime/equal").default';ju.default=Lg});var qg=T(Cu=>{"use strict";Object.defineProperty(Cu,"__esModule",{value:!0});var Iu=ho(),Pe=F(),AT=ee(),MT=gs(),NT={message:({params:{i:e,j:t}})=>(0,Pe.str)`must NOT have duplicate items (items ## ${t} and ${e} are identical)`,params:({params:{i:e,j:t}})=>(0,Pe._)`{i: ${e}, j: ${t}}`},DT={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:NT,code(e){let{gen:t,data:r,$data:n,schema:o,parentSchema:i,schemaCode:s,it:a}=e;if(!n&&!o)return;let c=t.let("valid"),d=i.items?(0,Iu.getSchemaTypes)(i.items):[];e.block$data(c,u,(0,Pe._)`${s} === false`),e.ok(c);function u(){let h=t.let("i",(0,Pe._)`${r}.length`),g=t.let("j");e.setParams({i:h,j:g}),t.assign(c,!0),t.if((0,Pe._)`${h} > 1`,()=>(p()?m:f)(h,g))}function p(){return d.length>0&&!d.some(h=>h==="object"||h==="array")}function m(h,g){let y=t.name("item"),v=(0,Iu.checkDataTypes)(d,y,a.opts.strictNumbers,Iu.DataType.Wrong),w=t.const("indices",(0,Pe._)`{}`);t.for((0,Pe._)`;${h}--;`,()=>{t.let(y,(0,Pe._)`${r}[${h}]`),t.if(v,(0,Pe._)`continue`),d.length>1&&t.if((0,Pe._)`typeof ${y} == "string"`,(0,Pe._)`${y} += "_"`),t.if((0,Pe._)`typeof ${w}[${y}] == "number"`,()=>{t.assign(g,(0,Pe._)`${w}[${y}]`),e.error(),t.assign(c,!1).break()}).code((0,Pe._)`${w}[${y}] = ${h}`)})}function f(h,g){let y=(0,AT.useFunc)(t,MT.default),v=t.name("outer");t.label(v).for((0,Pe._)`;${h}--;`,()=>t.for((0,Pe._)`${g} = ${h}; ${g}--;`,()=>t.if((0,Pe._)`${y}(${r}[${h}], ${r}[${g}])`,()=>{e.error(),t.assign(c,!1).break(v)})))}}};Cu.default=DT});var Ug=T(Mu=>{"use strict";Object.defineProperty(Mu,"__esModule",{value:!0});var Au=F(),LT=ee(),qT=gs(),UT={message:"must be equal to constant",params:({schemaCode:e})=>(0,Au._)`{allowedValue: ${e}}`},ZT={keyword:"const",$data:!0,error:UT,code(e){let{gen:t,data:r,$data:n,schemaCode:o,schema:i}=e;n||i&&typeof i=="object"?e.fail$data((0,Au._)`!${(0,LT.useFunc)(t,qT.default)}(${r}, ${o})`):e.fail((0,Au._)`${i} !== ${r}`)}};Mu.default=ZT});var Zg=T(Nu=>{"use strict";Object.defineProperty(Nu,"__esModule",{value:!0});var Oo=F(),JT=ee(),FT=gs(),VT={message:"must be equal to one of the allowed values",params:({schemaCode:e})=>(0,Oo._)`{allowedValues: ${e}}`},WT={keyword:"enum",schemaType:"array",$data:!0,error:VT,code(e){let{gen:t,data:r,$data:n,schema:o,schemaCode:i,it:s}=e;if(!n&&o.length===0)throw new Error("enum must have non-empty array");let a=o.length>=s.opts.loopEnum,c,d=()=>c??(c=(0,JT.useFunc)(t,FT.default)),u;if(a||n)u=t.let("valid"),e.block$data(u,p);else{if(!Array.isArray(o))throw new Error("ajv implementation error");let f=t.const("vSchema",i);u=(0,Oo.or)(...o.map((h,g)=>m(f,g)))}e.pass(u);function p(){t.assign(u,!1),t.forOf("v",i,f=>t.if((0,Oo._)`${d()}(${r}, ${f})`,()=>t.assign(u,!0).break()))}function m(f,h){let g=o[h];return typeof g=="object"&&g!==null?(0,Oo._)`${d()}(${r}, ${f}[${h}])`:(0,Oo._)`${r} === ${g}`}}};Nu.default=WT});var Jg=T(Du=>{"use strict";Object.defineProperty(Du,"__esModule",{value:!0});var BT=Og(),HT=Eg(),GT=Cg(),KT=Ag(),QT=Mg(),YT=Ng(),XT=Dg(),e1=qg(),t1=Ug(),r1=Zg(),n1=[BT.default,HT.default,GT.default,KT.default,QT.default,YT.default,XT.default,e1.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},t1.default,r1.default];Du.default=n1});var qu=T(Eo=>{"use strict";Object.defineProperty(Eo,"__esModule",{value:!0});Eo.validateAdditionalItems=void 0;var Dr=F(),Lu=ee(),o1={message:({params:{len:e}})=>(0,Dr.str)`must NOT have more than ${e} items`,params:({params:{len:e}})=>(0,Dr._)`{limit: ${e}}`},i1={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:o1,code(e){let{parentSchema:t,it:r}=e,{items:n}=t;if(!Array.isArray(n)){(0,Lu.checkStrictMode)(r,'"additionalItems" is ignored when "items" is not an array of schemas');return}Fg(e,n)}};function Fg(e,t){let{gen:r,schema:n,data:o,keyword:i,it:s}=e;s.items=!0;let a=r.const("len",(0,Dr._)`${o}.length`);if(n===!1)e.setParams({len:t.length}),e.pass((0,Dr._)`${a} <= ${t.length}`);else if(typeof n=="object"&&!(0,Lu.alwaysValidSchema)(s,n)){let d=r.var("valid",(0,Dr._)`${a} <= ${t.length}`);r.if((0,Dr.not)(d),()=>c(d)),e.ok(d)}function c(d){r.forRange("i",t.length,a,u=>{e.subschema({keyword:i,dataProp:u,dataPropType:Lu.Type.Num},d),s.allErrors||r.if((0,Dr.not)(d),()=>r.break())})}}Eo.validateAdditionalItems=Fg;Eo.default=i1});var Uu=T(jo=>{"use strict";Object.defineProperty(jo,"__esModule",{value:!0});jo.validateTuple=void 0;var Vg=F(),ys=ee(),s1=ot(),a1={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(e){let{schema:t,it:r}=e;if(Array.isArray(t))return Wg(e,"additionalItems",t);r.items=!0,!(0,ys.alwaysValidSchema)(r,t)&&e.ok((0,s1.validateArray)(e))}};function Wg(e,t,r=e.schema){let{gen:n,parentSchema:o,data:i,keyword:s,it:a}=e;u(o),a.opts.unevaluated&&r.length&&a.items!==!0&&(a.items=ys.mergeEvaluated.items(n,r.length,a.items));let c=n.name("valid"),d=n.const("len",(0,Vg._)`${i}.length`);r.forEach((p,m)=>{(0,ys.alwaysValidSchema)(a,p)||(n.if((0,Vg._)`${d} > ${m}`,()=>e.subschema({keyword:s,schemaProp:m,dataProp:m},c)),e.ok(c))});function u(p){let{opts:m,errSchemaPath:f}=a,h=r.length,g=h===p.minItems&&(h===p.maxItems||p[t]===!1);if(m.strictTuples&&!g){let y=`"${s}" is ${h}-tuple, but minItems or maxItems/${t} are not specified or different at path "${f}"`;(0,ys.checkStrictMode)(a,y,m.strictTuples)}}}jo.validateTuple=Wg;jo.default=a1});var Bg=T(Zu=>{"use strict";Object.defineProperty(Zu,"__esModule",{value:!0});var c1=Uu(),d1={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:e=>(0,c1.validateTuple)(e,"items")};Zu.default=d1});var Gg=T(Ju=>{"use strict";Object.defineProperty(Ju,"__esModule",{value:!0});var Hg=F(),u1=ee(),l1=ot(),p1=qu(),m1={message:({params:{len:e}})=>(0,Hg.str)`must NOT have more than ${e} items`,params:({params:{len:e}})=>(0,Hg._)`{limit: ${e}}`},f1={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:m1,code(e){let{schema:t,parentSchema:r,it:n}=e,{prefixItems:o}=r;n.items=!0,!(0,u1.alwaysValidSchema)(n,t)&&(o?(0,p1.validateAdditionalItems)(e,o):e.ok((0,l1.validateArray)(e)))}};Ju.default=f1});var Kg=T(Fu=>{"use strict";Object.defineProperty(Fu,"__esModule",{value:!0});var st=F(),_s=ee(),h1={message:({params:{min:e,max:t}})=>t===void 0?(0,st.str)`must contain at least ${e} valid item(s)`:(0,st.str)`must contain at least ${e} and no more than ${t} valid item(s)`,params:({params:{min:e,max:t}})=>t===void 0?(0,st._)`{minContains: ${e}}`:(0,st._)`{minContains: ${e}, maxContains: ${t}}`},g1={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:h1,code(e){let{gen:t,schema:r,parentSchema:n,data:o,it:i}=e,s,a,{minContains:c,maxContains:d}=n;i.opts.next?(s=c===void 0?1:c,a=d):s=1;let u=t.const("len",(0,st._)`${o}.length`);if(e.setParams({min:s,max:a}),a===void 0&&s===0){(0,_s.checkStrictMode)(i,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(a!==void 0&&s>a){(0,_s.checkStrictMode)(i,'"minContains" > "maxContains" is always invalid'),e.fail();return}if((0,_s.alwaysValidSchema)(i,r)){let g=(0,st._)`${u} >= ${s}`;a!==void 0&&(g=(0,st._)`${g} && ${u} <= ${a}`),e.pass(g);return}i.items=!0;let p=t.name("valid");a===void 0&&s===1?f(p,()=>t.if(p,()=>t.break())):s===0?(t.let(p,!0),a!==void 0&&t.if((0,st._)`${o}.length > 0`,m)):(t.let(p,!1),m()),e.result(p,()=>e.reset());function m(){let g=t.name("_valid"),y=t.let("count",0);f(g,()=>t.if(g,()=>h(y)))}function f(g,y){t.forRange("i",0,u,v=>{e.subschema({keyword:"contains",dataProp:v,dataPropType:_s.Type.Num,compositeRule:!0},g),y()})}function h(g){t.code((0,st._)`${g}++`),a===void 0?t.if((0,st._)`${g} >= ${s}`,()=>t.assign(p,!0).break()):(t.if((0,st._)`${g} > ${a}`,()=>t.assign(p,!1).break()),s===1?t.assign(p,!0):t.if((0,st._)`${g} >= ${s}`,()=>t.assign(p,!0)))}}};Fu.default=g1});var Xg=T(St=>{"use strict";Object.defineProperty(St,"__esModule",{value:!0});St.validateSchemaDeps=St.validatePropertyDeps=St.error=void 0;var Vu=F(),y1=ee(),Io=ot();St.error={message:({params:{property:e,depsCount:t,deps:r}})=>{let n=t===1?"property":"properties";return(0,Vu.str)`must have ${n} ${r} when property ${e} is present`},params:({params:{property:e,depsCount:t,deps:r,missingProperty:n}})=>(0,Vu._)`{property: ${e},
8
- missingProperty: ${n},
9
- depsCount: ${t},
10
- deps: ${r}}`};var _1={keyword:"dependencies",type:"object",schemaType:"object",error:St.error,code(e){let[t,r]=b1(e);Qg(e,t),Yg(e,r)}};function b1({schema:e}){let t={},r={};for(let n in e){if(n==="__proto__")continue;let o=Array.isArray(e[n])?t:r;o[n]=e[n]}return[t,r]}function Qg(e,t=e.schema){let{gen:r,data:n,it:o}=e;if(Object.keys(t).length===0)return;let i=r.let("missing");for(let s in t){let a=t[s];if(a.length===0)continue;let c=(0,Io.propertyInData)(r,n,s,o.opts.ownProperties);e.setParams({property:s,depsCount:a.length,deps:a.join(", ")}),o.allErrors?r.if(c,()=>{for(let d of a)(0,Io.checkReportMissingProp)(e,d)}):(r.if((0,Vu._)`${c} && (${(0,Io.checkMissingProp)(e,a,i)})`),(0,Io.reportMissingProp)(e,i),r.else())}}St.validatePropertyDeps=Qg;function Yg(e,t=e.schema){let{gen:r,data:n,keyword:o,it:i}=e,s=r.name("valid");for(let a in t)(0,y1.alwaysValidSchema)(i,t[a])||(r.if((0,Io.propertyInData)(r,n,a,i.opts.ownProperties),()=>{let c=e.subschema({keyword:o,schemaProp:a},s);e.mergeValidEvaluated(c,s)},()=>r.var(s,!0)),e.ok(s))}St.validateSchemaDeps=Yg;St.default=_1});var ty=T(Wu=>{"use strict";Object.defineProperty(Wu,"__esModule",{value:!0});var ey=F(),v1=ee(),w1={message:"property name must be valid",params:({params:e})=>(0,ey._)`{propertyName: ${e.propertyName}}`},k1={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:w1,code(e){let{gen:t,schema:r,data:n,it:o}=e;if((0,v1.alwaysValidSchema)(o,r))return;let i=t.name("valid");t.forIn("key",n,s=>{e.setParams({propertyName:s}),e.subschema({keyword:"propertyNames",data:s,dataTypes:["string"],propertyName:s,compositeRule:!0},i),t.if((0,ey.not)(i),()=>{e.error(!0),o.allErrors||t.break()})}),e.ok(i)}};Wu.default=k1});var Hu=T(Bu=>{"use strict";Object.defineProperty(Bu,"__esModule",{value:!0});var bs=ot(),ft=F(),x1=At(),vs=ee(),S1={message:"must NOT have additional properties",params:({params:e})=>(0,ft._)`{additionalProperty: ${e.additionalProperty}}`},$1={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:S1,code(e){let{gen:t,schema:r,parentSchema:n,data:o,errsCount:i,it:s}=e;if(!i)throw new Error("ajv implementation error");let{allErrors:a,opts:c}=s;if(s.props=!0,c.removeAdditional!=="all"&&(0,vs.alwaysValidSchema)(s,r))return;let d=(0,bs.allSchemaProperties)(n.properties),u=(0,bs.allSchemaProperties)(n.patternProperties);p(),e.ok((0,ft._)`${i} === ${x1.default.errors}`);function p(){t.forIn("key",o,y=>{!d.length&&!u.length?h(y):t.if(m(y),()=>h(y))})}function m(y){let v;if(d.length>8){let w=(0,vs.schemaRefOrVal)(s,n.properties,"properties");v=(0,bs.isOwnProperty)(t,w,y)}else d.length?v=(0,ft.or)(...d.map(w=>(0,ft._)`${y} === ${w}`)):v=ft.nil;return u.length&&(v=(0,ft.or)(v,...u.map(w=>(0,ft._)`${(0,bs.usePattern)(e,w)}.test(${y})`))),(0,ft.not)(v)}function f(y){t.code((0,ft._)`delete ${o}[${y}]`)}function h(y){if(c.removeAdditional==="all"||c.removeAdditional&&r===!1){f(y);return}if(r===!1){e.setParams({additionalProperty:y}),e.error(),a||t.break();return}if(typeof r=="object"&&!(0,vs.alwaysValidSchema)(s,r)){let v=t.name("valid");c.removeAdditional==="failing"?(g(y,v,!1),t.if((0,ft.not)(v),()=>{e.reset(),f(y)})):(g(y,v),a||t.if((0,ft.not)(v),()=>t.break()))}}function g(y,v,w){let k={keyword:"additionalProperties",dataProp:y,dataPropType:vs.Type.Str};w===!1&&Object.assign(k,{compositeRule:!0,createErrors:!1,allErrors:!1}),e.subschema(k,v)}}};Bu.default=$1});var oy=T(Ku=>{"use strict";Object.defineProperty(Ku,"__esModule",{value:!0});var z1=bo(),ry=ot(),Gu=ee(),ny=Hu(),T1={keyword:"properties",type:"object",schemaType:"object",code(e){let{gen:t,schema:r,parentSchema:n,data:o,it:i}=e;i.opts.removeAdditional==="all"&&n.additionalProperties===void 0&&ny.default.code(new z1.KeywordCxt(i,ny.default,"additionalProperties"));let s=(0,ry.allSchemaProperties)(r);for(let p of s)i.definedProperties.add(p);i.opts.unevaluated&&s.length&&i.props!==!0&&(i.props=Gu.mergeEvaluated.props(t,(0,Gu.toHash)(s),i.props));let a=s.filter(p=>!(0,Gu.alwaysValidSchema)(i,r[p]));if(a.length===0)return;let c=t.name("valid");for(let p of a)d(p)?u(p):(t.if((0,ry.propertyInData)(t,o,p,i.opts.ownProperties)),u(p),i.allErrors||t.else().var(c,!0),t.endIf()),e.it.definedProperties.add(p),e.ok(c);function d(p){return i.opts.useDefaults&&!i.compositeRule&&r[p].default!==void 0}function u(p){e.subschema({keyword:"properties",schemaProp:p,dataProp:p},c)}}};Ku.default=T1});var cy=T(Qu=>{"use strict";Object.defineProperty(Qu,"__esModule",{value:!0});var iy=ot(),ws=F(),sy=ee(),ay=ee(),P1={keyword:"patternProperties",type:"object",schemaType:"object",code(e){let{gen:t,schema:r,data:n,parentSchema:o,it:i}=e,{opts:s}=i,a=(0,iy.allSchemaProperties)(r),c=a.filter(g=>(0,sy.alwaysValidSchema)(i,r[g]));if(a.length===0||c.length===a.length&&(!i.opts.unevaluated||i.props===!0))return;let d=s.strictSchema&&!s.allowMatchingProperties&&o.properties,u=t.name("valid");i.props!==!0&&!(i.props instanceof ws.Name)&&(i.props=(0,ay.evaluatedPropsToName)(t,i.props));let{props:p}=i;m();function m(){for(let g of a)d&&f(g),i.allErrors?h(g):(t.var(u,!0),h(g),t.if(u))}function f(g){for(let y in d)new RegExp(g).test(y)&&(0,sy.checkStrictMode)(i,`property ${y} matches pattern ${g} (use allowMatchingProperties)`)}function h(g){t.forIn("key",n,y=>{t.if((0,ws._)`${(0,iy.usePattern)(e,g)}.test(${y})`,()=>{let v=c.includes(g);v||e.subschema({keyword:"patternProperties",schemaProp:g,dataProp:y,dataPropType:ay.Type.Str},u),i.opts.unevaluated&&p!==!0?t.assign((0,ws._)`${p}[${y}]`,!0):!v&&!i.allErrors&&t.if((0,ws.not)(u),()=>t.break())})})}}};Qu.default=P1});var dy=T(Yu=>{"use strict";Object.defineProperty(Yu,"__esModule",{value:!0});var R1=ee(),O1={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(e){let{gen:t,schema:r,it:n}=e;if((0,R1.alwaysValidSchema)(n,r)){e.fail();return}let o=t.name("valid");e.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},o),e.failResult(o,()=>e.reset(),()=>e.error())},error:{message:"must NOT be valid"}};Yu.default=O1});var uy=T(Xu=>{"use strict";Object.defineProperty(Xu,"__esModule",{value:!0});var E1=ot(),j1={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:E1.validateUnion,error:{message:"must match a schema in anyOf"}};Xu.default=j1});var ly=T(el=>{"use strict";Object.defineProperty(el,"__esModule",{value:!0});var ks=F(),I1=ee(),C1={message:"must match exactly one schema in oneOf",params:({params:e})=>(0,ks._)`{passingSchemas: ${e.passing}}`},A1={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:C1,code(e){let{gen:t,schema:r,parentSchema:n,it:o}=e;if(!Array.isArray(r))throw new Error("ajv implementation error");if(o.opts.discriminator&&n.discriminator)return;let i=r,s=t.let("valid",!1),a=t.let("passing",null),c=t.name("_valid");e.setParams({passing:a}),t.block(d),e.result(s,()=>e.reset(),()=>e.error(!0));function d(){i.forEach((u,p)=>{let m;(0,I1.alwaysValidSchema)(o,u)?t.var(c,!0):m=e.subschema({keyword:"oneOf",schemaProp:p,compositeRule:!0},c),p>0&&t.if((0,ks._)`${c} && ${s}`).assign(s,!1).assign(a,(0,ks._)`[${a}, ${p}]`).else(),t.if(c,()=>{t.assign(s,!0),t.assign(a,p),m&&e.mergeEvaluated(m,ks.Name)})})}}};el.default=A1});var py=T(tl=>{"use strict";Object.defineProperty(tl,"__esModule",{value:!0});var M1=ee(),N1={keyword:"allOf",schemaType:"array",code(e){let{gen:t,schema:r,it:n}=e;if(!Array.isArray(r))throw new Error("ajv implementation error");let o=t.name("valid");r.forEach((i,s)=>{if((0,M1.alwaysValidSchema)(n,i))return;let a=e.subschema({keyword:"allOf",schemaProp:s},o);e.ok(o),e.mergeEvaluated(a)})}};tl.default=N1});var hy=T(rl=>{"use strict";Object.defineProperty(rl,"__esModule",{value:!0});var xs=F(),fy=ee(),D1={message:({params:e})=>(0,xs.str)`must match "${e.ifClause}" schema`,params:({params:e})=>(0,xs._)`{failingKeyword: ${e.ifClause}}`},L1={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:D1,code(e){let{gen:t,parentSchema:r,it:n}=e;r.then===void 0&&r.else===void 0&&(0,fy.checkStrictMode)(n,'"if" without "then" and "else" is ignored');let o=my(n,"then"),i=my(n,"else");if(!o&&!i)return;let s=t.let("valid",!0),a=t.name("_valid");if(c(),e.reset(),o&&i){let u=t.let("ifClause");e.setParams({ifClause:u}),t.if(a,d("then",u),d("else",u))}else o?t.if(a,d("then")):t.if((0,xs.not)(a),d("else"));e.pass(s,()=>e.error(!0));function c(){let u=e.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},a);e.mergeEvaluated(u)}function d(u,p){return()=>{let m=e.subschema({keyword:u},a);t.assign(s,a),e.mergeValidEvaluated(m,s),p?t.assign(p,(0,xs._)`${u}`):e.setParams({ifClause:u})}}}};function my(e,t){let r=e.schema[t];return r!==void 0&&!(0,fy.alwaysValidSchema)(e,r)}rl.default=L1});var gy=T(nl=>{"use strict";Object.defineProperty(nl,"__esModule",{value:!0});var q1=ee(),U1={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:e,parentSchema:t,it:r}){t.if===void 0&&(0,q1.checkStrictMode)(r,`"${e}" without "if" is ignored`)}};nl.default=U1});var yy=T(ol=>{"use strict";Object.defineProperty(ol,"__esModule",{value:!0});var Z1=qu(),J1=Bg(),F1=Uu(),V1=Gg(),W1=Kg(),B1=Xg(),H1=ty(),G1=Hu(),K1=oy(),Q1=cy(),Y1=dy(),X1=uy(),eP=ly(),tP=py(),rP=hy(),nP=gy();function oP(e=!1){let t=[Y1.default,X1.default,eP.default,tP.default,rP.default,nP.default,H1.default,G1.default,B1.default,K1.default,Q1.default];return e?t.push(J1.default,V1.default):t.push(Z1.default,F1.default),t.push(W1.default),t}ol.default=oP});var _y=T(il=>{"use strict";Object.defineProperty(il,"__esModule",{value:!0});var _e=F(),iP={message:({schemaCode:e})=>(0,_e.str)`must match format "${e}"`,params:({schemaCode:e})=>(0,_e._)`{format: ${e}}`},sP={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:iP,code(e,t){let{gen:r,data:n,$data:o,schema:i,schemaCode:s,it:a}=e,{opts:c,errSchemaPath:d,schemaEnv:u,self:p}=a;if(!c.validateFormats)return;o?m():f();function m(){let h=r.scopeValue("formats",{ref:p.formats,code:c.code.formats}),g=r.const("fDef",(0,_e._)`${h}[${s}]`),y=r.let("fType"),v=r.let("format");r.if((0,_e._)`typeof ${g} == "object" && !(${g} instanceof RegExp)`,()=>r.assign(y,(0,_e._)`${g}.type || "string"`).assign(v,(0,_e._)`${g}.validate`),()=>r.assign(y,(0,_e._)`"string"`).assign(v,g)),e.fail$data((0,_e.or)(w(),k()));function w(){return c.strictSchema===!1?_e.nil:(0,_e._)`${s} && !${v}`}function k(){let O=u.$async?(0,_e._)`(${g}.async ? await ${v}(${n}) : ${v}(${n}))`:(0,_e._)`${v}(${n})`,M=(0,_e._)`(typeof ${v} == "function" ? ${O} : ${v}.test(${n}))`;return(0,_e._)`${v} && ${v} !== true && ${y} === ${t} && !${M}`}}function f(){let h=p.formats[i];if(!h){w();return}if(h===!0)return;let[g,y,v]=k(h);g===t&&e.pass(O());function w(){if(c.strictSchema===!1){p.logger.warn(M());return}throw new Error(M());function M(){return`unknown format "${i}" ignored in schema at path "${d}"`}}function k(M){let Ie=M instanceof RegExp?(0,_e.regexpCode)(M):c.code.formats?(0,_e._)`${c.code.formats}${(0,_e.getProperty)(i)}`:void 0,Qe=r.scopeValue("formats",{key:i,ref:M,code:Ie});return typeof M=="object"&&!(M instanceof RegExp)?[M.type||"string",M.validate,(0,_e._)`${Qe}.validate`]:["string",M,Qe]}function O(){if(typeof h=="object"&&!(h instanceof RegExp)&&h.async){if(!u.$async)throw new Error("async format in sync schema");return(0,_e._)`await ${v}(${n})`}return typeof y=="function"?(0,_e._)`${v}(${n})`:(0,_e._)`${v}.test(${n})`}}}};il.default=sP});var by=T(sl=>{"use strict";Object.defineProperty(sl,"__esModule",{value:!0});var aP=_y(),cP=[aP.default];sl.default=cP});var vy=T(wn=>{"use strict";Object.defineProperty(wn,"__esModule",{value:!0});wn.contentVocabulary=wn.metadataVocabulary=void 0;wn.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];wn.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var ky=T(al=>{"use strict";Object.defineProperty(al,"__esModule",{value:!0});var dP=Rg(),uP=Jg(),lP=yy(),pP=by(),wy=vy(),mP=[dP.default,uP.default,(0,lP.default)(),pP.default,wy.metadataVocabulary,wy.contentVocabulary];al.default=mP});var Sy=T(Ss=>{"use strict";Object.defineProperty(Ss,"__esModule",{value:!0});Ss.DiscrError=void 0;var xy;(function(e){e.Tag="tag",e.Mapping="mapping"})(xy||(Ss.DiscrError=xy={}))});var zy=T(dl=>{"use strict";Object.defineProperty(dl,"__esModule",{value:!0});var kn=F(),cl=Sy(),$y=is(),fP=vo(),hP=ee(),gP={message:({params:{discrError:e,tagName:t}})=>e===cl.DiscrError.Tag?`tag "${t}" must be string`:`value of tag "${t}" must be in oneOf`,params:({params:{discrError:e,tag:t,tagName:r}})=>(0,kn._)`{error: ${e}, tag: ${r}, tagValue: ${t}}`},yP={keyword:"discriminator",type:"object",schemaType:"object",error:gP,code(e){let{gen:t,data:r,schema:n,parentSchema:o,it:i}=e,{oneOf:s}=o;if(!i.opts.discriminator)throw new Error("discriminator: requires discriminator option");let a=n.propertyName;if(typeof a!="string")throw new Error("discriminator: requires propertyName");if(n.mapping)throw new Error("discriminator: mapping is not supported");if(!s)throw new Error("discriminator: requires oneOf keyword");let c=t.let("valid",!1),d=t.const("tag",(0,kn._)`${r}${(0,kn.getProperty)(a)}`);t.if((0,kn._)`typeof ${d} == "string"`,()=>u(),()=>e.error(!1,{discrError:cl.DiscrError.Tag,tag:d,tagName:a})),e.ok(c);function u(){let f=m();t.if(!1);for(let h in f)t.elseIf((0,kn._)`${d} === ${h}`),t.assign(c,p(f[h]));t.else(),e.error(!1,{discrError:cl.DiscrError.Mapping,tag:d,tagName:a}),t.endIf()}function p(f){let h=t.name("valid"),g=e.subschema({keyword:"oneOf",schemaProp:f},h);return e.mergeEvaluated(g,kn.Name),h}function m(){var f;let h={},g=v(o),y=!0;for(let O=0;O<s.length;O++){let M=s[O];if(M?.$ref&&!(0,hP.schemaHasRulesButRef)(M,i.self.RULES)){let Qe=M.$ref;if(M=$y.resolveRef.call(i.self,i.schemaEnv.root,i.baseId,Qe),M instanceof $y.SchemaEnv&&(M=M.schema),M===void 0)throw new fP.default(i.opts.uriResolver,i.baseId,Qe)}let Ie=(f=M?.properties)===null||f===void 0?void 0:f[a];if(typeof Ie!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${a}"`);y=y&&(g||v(M)),w(Ie,O)}if(!y)throw new Error(`discriminator: "${a}" must be required`);return h;function v({required:O}){return Array.isArray(O)&&O.includes(a)}function w(O,M){if(O.const)k(O.const,M);else if(O.enum)for(let Ie of O.enum)k(Ie,M);else throw new Error(`discriminator: "properties/${a}" must have "const" or "enum"`)}function k(O,M){if(typeof O!="string"||O in h)throw new Error(`discriminator: "${a}" values must be unique strings`);h[O]=M}}}};dl.default=yP});var Ty=T((ZM,_P)=>{_P.exports={$schema:"http://json-schema.org/draft-07/schema#",$id:"http://json-schema.org/draft-07/schema#",title:"Core schema meta-schema",definitions:{schemaArray:{type:"array",minItems:1,items:{$ref:"#"}},nonNegativeInteger:{type:"integer",minimum:0},nonNegativeIntegerDefault0:{allOf:[{$ref:"#/definitions/nonNegativeInteger"},{default:0}]},simpleTypes:{enum:["array","boolean","integer","null","number","object","string"]},stringArray:{type:"array",items:{type:"string"},uniqueItems:!0,default:[]}},type:["object","boolean"],properties:{$id:{type:"string",format:"uri-reference"},$schema:{type:"string",format:"uri"},$ref:{type:"string",format:"uri-reference"},$comment:{type:"string"},title:{type:"string"},description:{type:"string"},default:!0,readOnly:{type:"boolean",default:!1},examples:{type:"array",items:!0},multipleOf:{type:"number",exclusiveMinimum:0},maximum:{type:"number"},exclusiveMaximum:{type:"number"},minimum:{type:"number"},exclusiveMinimum:{type:"number"},maxLength:{$ref:"#/definitions/nonNegativeInteger"},minLength:{$ref:"#/definitions/nonNegativeIntegerDefault0"},pattern:{type:"string",format:"regex"},additionalItems:{$ref:"#"},items:{anyOf:[{$ref:"#"},{$ref:"#/definitions/schemaArray"}],default:!0},maxItems:{$ref:"#/definitions/nonNegativeInteger"},minItems:{$ref:"#/definitions/nonNegativeIntegerDefault0"},uniqueItems:{type:"boolean",default:!1},contains:{$ref:"#"},maxProperties:{$ref:"#/definitions/nonNegativeInteger"},minProperties:{$ref:"#/definitions/nonNegativeIntegerDefault0"},required:{$ref:"#/definitions/stringArray"},additionalProperties:{$ref:"#"},definitions:{type:"object",additionalProperties:{$ref:"#"},default:{}},properties:{type:"object",additionalProperties:{$ref:"#"},default:{}},patternProperties:{type:"object",additionalProperties:{$ref:"#"},propertyNames:{format:"regex"},default:{}},dependencies:{type:"object",additionalProperties:{anyOf:[{$ref:"#"},{$ref:"#/definitions/stringArray"}]}},propertyNames:{$ref:"#"},const:!0,enum:{type:"array",items:!0,minItems:1,uniqueItems:!0},type:{anyOf:[{$ref:"#/definitions/simpleTypes"},{type:"array",items:{$ref:"#/definitions/simpleTypes"},minItems:1,uniqueItems:!0}]},format:{type:"string"},contentMediaType:{type:"string"},contentEncoding:{type:"string"},if:{$ref:"#"},then:{$ref:"#"},else:{$ref:"#"},allOf:{$ref:"#/definitions/schemaArray"},anyOf:{$ref:"#/definitions/schemaArray"},oneOf:{$ref:"#/definitions/schemaArray"},not:{$ref:"#"}},default:!0}});var ll=T((le,ul)=>{"use strict";Object.defineProperty(le,"__esModule",{value:!0});le.MissingRefError=le.ValidationError=le.CodeGen=le.Name=le.nil=le.stringify=le.str=le._=le.KeywordCxt=le.Ajv=void 0;var bP=xg(),vP=ky(),wP=zy(),Py=Ty(),kP=["/properties"],$s="http://json-schema.org/draft-07/schema",xn=class extends bP.default{_addVocabularies(){super._addVocabularies(),vP.default.forEach(t=>this.addVocabulary(t)),this.opts.discriminator&&this.addKeyword(wP.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let t=this.opts.$data?this.$dataMetaSchema(Py,kP):Py;this.addMetaSchema(t,$s,!1),this.refs["http://json-schema.org/schema"]=$s}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema($s)?$s:void 0)}};le.Ajv=xn;ul.exports=le=xn;ul.exports.Ajv=xn;Object.defineProperty(le,"__esModule",{value:!0});le.default=xn;var xP=bo();Object.defineProperty(le,"KeywordCxt",{enumerable:!0,get:function(){return xP.KeywordCxt}});var Sn=F();Object.defineProperty(le,"_",{enumerable:!0,get:function(){return Sn._}});Object.defineProperty(le,"str",{enumerable:!0,get:function(){return Sn.str}});Object.defineProperty(le,"stringify",{enumerable:!0,get:function(){return Sn.stringify}});Object.defineProperty(le,"nil",{enumerable:!0,get:function(){return Sn.nil}});Object.defineProperty(le,"Name",{enumerable:!0,get:function(){return Sn.Name}});Object.defineProperty(le,"CodeGen",{enumerable:!0,get:function(){return Sn.CodeGen}});var SP=ns();Object.defineProperty(le,"ValidationError",{enumerable:!0,get:function(){return SP.default}});var $P=vo();Object.defineProperty(le,"MissingRefError",{enumerable:!0,get:function(){return $P.default}})});var My=T(zt=>{"use strict";Object.defineProperty(zt,"__esModule",{value:!0});zt.formatNames=zt.fastFormats=zt.fullFormats=void 0;function $t(e,t){return{validate:e,compare:t}}zt.fullFormats={date:$t(jy,hl),time:$t(ml(!0),gl),"date-time":$t(Ry(!0),Cy),"iso-time":$t(ml(),Iy),"iso-date-time":$t(Ry(),Ay),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:EP,"uri-reference":/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,"uri-template":/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,url:/^(?:https?|ftp):\/\/(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)(?:\.(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu,email:/^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i,hostname:/^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i,ipv4:/^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/,ipv6:/^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i,regex:DP,uuid:/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,"json-pointer":/^(?:\/(?:[^~/]|~0|~1)*)*$/,"json-pointer-uri-fragment":/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,"relative-json-pointer":/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,byte:jP,int32:{type:"number",validate:AP},int64:{type:"number",validate:MP},float:{type:"number",validate:Ey},double:{type:"number",validate:Ey},password:!0,binary:!0};zt.fastFormats={...zt.fullFormats,date:$t(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,hl),time:$t(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,gl),"date-time":$t(/^\d\d\d\d-[0-1]\d-[0-3]\dt(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,Cy),"iso-time":$t(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,Iy),"iso-date-time":$t(/^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,Ay),uri:/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i,"uri-reference":/^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i,email:/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i};zt.formatNames=Object.keys(zt.fullFormats);function zP(e){return e%4===0&&(e%100!==0||e%400===0)}var TP=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,PP=[0,31,28,31,30,31,30,31,31,30,31,30,31];function jy(e){let t=TP.exec(e);if(!t)return!1;let r=+t[1],n=+t[2],o=+t[3];return n>=1&&n<=12&&o>=1&&o<=(n===2&&zP(r)?29:PP[n])}function hl(e,t){if(e&&t)return e>t?1:e<t?-1:0}var pl=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function ml(e){return function(r){let n=pl.exec(r);if(!n)return!1;let o=+n[1],i=+n[2],s=+n[3],a=n[4],c=n[5]==="-"?-1:1,d=+(n[6]||0),u=+(n[7]||0);if(d>23||u>59||e&&!a)return!1;if(o<=23&&i<=59&&s<60)return!0;let p=i-u*c,m=o-d*c-(p<0?1:0);return(m===23||m===-1)&&(p===59||p===-1)&&s<61}}function gl(e,t){if(!(e&&t))return;let r=new Date("2020-01-01T"+e).valueOf(),n=new Date("2020-01-01T"+t).valueOf();if(r&&n)return r-n}function Iy(e,t){if(!(e&&t))return;let r=pl.exec(e),n=pl.exec(t);if(r&&n)return e=r[1]+r[2]+r[3],t=n[1]+n[2]+n[3],e>t?1:e<t?-1:0}var fl=/t|\s/i;function Ry(e){let t=ml(e);return function(n){let o=n.split(fl);return o.length===2&&jy(o[0])&&t(o[1])}}function Cy(e,t){if(!(e&&t))return;let r=new Date(e).valueOf(),n=new Date(t).valueOf();if(r&&n)return r-n}function Ay(e,t){if(!(e&&t))return;let[r,n]=e.split(fl),[o,i]=t.split(fl),s=hl(r,o);if(s!==void 0)return s||gl(n,i)}var RP=/\/|:/,OP=/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;function EP(e){return RP.test(e)&&OP.test(e)}var Oy=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function jP(e){return Oy.lastIndex=0,Oy.test(e)}var IP=-(2**31),CP=2**31-1;function AP(e){return Number.isInteger(e)&&e<=CP&&e>=IP}function MP(e){return Number.isInteger(e)}function Ey(){return!0}var NP=/[^\\]\\Z/;function DP(e){if(NP.test(e))return!1;try{return new RegExp(e),!0}catch{return!1}}});var Ny=T($n=>{"use strict";Object.defineProperty($n,"__esModule",{value:!0});$n.formatLimitDefinition=void 0;var LP=ll(),ht=F(),or=ht.operators,zs={formatMaximum:{okStr:"<=",ok:or.LTE,fail:or.GT},formatMinimum:{okStr:">=",ok:or.GTE,fail:or.LT},formatExclusiveMaximum:{okStr:"<",ok:or.LT,fail:or.GTE},formatExclusiveMinimum:{okStr:">",ok:or.GT,fail:or.LTE}},qP={message:({keyword:e,schemaCode:t})=>(0,ht.str)`should be ${zs[e].okStr} ${t}`,params:({keyword:e,schemaCode:t})=>(0,ht._)`{comparison: ${zs[e].okStr}, limit: ${t}}`};$n.formatLimitDefinition={keyword:Object.keys(zs),type:"string",schemaType:"string",$data:!0,error:qP,code(e){let{gen:t,data:r,schemaCode:n,keyword:o,it:i}=e,{opts:s,self:a}=i;if(!s.validateFormats)return;let c=new LP.KeywordCxt(i,a.RULES.all.format.definition,"format");c.$data?d():u();function d(){let m=t.scopeValue("formats",{ref:a.formats,code:s.code.formats}),f=t.const("fmt",(0,ht._)`${m}[${c.schemaCode}]`);e.fail$data((0,ht.or)((0,ht._)`typeof ${f} != "object"`,(0,ht._)`${f} instanceof RegExp`,(0,ht._)`typeof ${f}.compare != "function"`,p(f)))}function u(){let m=c.schema,f=a.formats[m];if(!f||f===!0)return;if(typeof f!="object"||f instanceof RegExp||typeof f.compare!="function")throw new Error(`"${o}": format "${m}" does not define "compare" function`);let h=t.scopeValue("formats",{key:m,ref:f,code:s.code.formats?(0,ht._)`${s.code.formats}${(0,ht.getProperty)(m)}`:void 0});e.fail$data(p(h))}function p(m){return(0,ht._)`${m}.compare(${r}, ${n}) ${zs[o].fail} 0`}},dependencies:["format"]};var UP=e=>(e.addKeyword($n.formatLimitDefinition),e);$n.default=UP});var Uy=T((Co,qy)=>{"use strict";Object.defineProperty(Co,"__esModule",{value:!0});var zn=My(),ZP=Ny(),yl=F(),Dy=new yl.Name("fullFormats"),JP=new yl.Name("fastFormats"),_l=(e,t={keywords:!0})=>{if(Array.isArray(t))return Ly(e,t,zn.fullFormats,Dy),e;let[r,n]=t.mode==="fast"?[zn.fastFormats,JP]:[zn.fullFormats,Dy],o=t.formats||zn.formatNames;return Ly(e,o,r,n),t.keywords&&(0,ZP.default)(e),e};_l.get=(e,t="full")=>{let n=(t==="fast"?zn.fastFormats:zn.fullFormats)[e];if(!n)throw new Error(`Unknown format "${e}"`);return n};function Ly(e,t,r,n){var o,i;(o=(i=e.opts.code).formats)!==null&&o!==void 0||(i.formats=(0,yl._)`require("ajv-formats/dist/formats").${n}`);for(let s of t)e.addFormat(s,r[s])}qy.exports=Co=_l;Object.defineProperty(Co,"__esModule",{value:!0});Co.default=_l});import{pathToFileURL as kE}from"node:url";var l={};Ws(l,{BRAND:()=>Rv,DIRTY:()=>sr,EMPTY_PATH:()=>av,INVALID:()=>N,NEVER:()=>pw,OK:()=>Re,ParseStatus:()=>xe,Schema:()=>J,ZodAny:()=>Jt,ZodArray:()=>Et,ZodBigInt:()=>cr,ZodBoolean:()=>dr,ZodBranded:()=>jn,ZodCatch:()=>vr,ZodDate:()=>ur,ZodDefault:()=>br,ZodDiscriminatedUnion:()=>Go,ZodEffects:()=>Xe,ZodEnum:()=>yr,ZodError:()=>De,ZodFirstPartyTypeKind:()=>S,ZodFunction:()=>Qo,ZodIntersection:()=>fr,ZodIssueCode:()=>x,ZodLazy:()=>hr,ZodLiteral:()=>gr,ZodMap:()=>Kr,ZodNaN:()=>Yr,ZodNativeEnum:()=>_r,ZodNever:()=>at,ZodNull:()=>pr,ZodNullable:()=>bt,ZodNumber:()=>ar,ZodObject:()=>qe,ZodOptional:()=>Le,ZodParsedType:()=>P,ZodPipeline:()=>In,ZodPromise:()=>Ft,ZodReadonly:()=>wr,ZodRecord:()=>Ko,ZodSchema:()=>J,ZodSet:()=>Qr,ZodString:()=>Zt,ZodSymbol:()=>Hr,ZodTransformer:()=>Xe,ZodTuple:()=>_t,ZodType:()=>J,ZodUndefined:()=>lr,ZodUnion:()=>mr,ZodUnknown:()=>Ot,ZodVoid:()=>Gr,addIssueToContext:()=>$,any:()=>Dv,array:()=>Zv,bigint:()=>Iv,boolean:()=>yp,coerce:()=>lw,custom:()=>fp,date:()=>Cv,datetimeRegex:()=>pp,defaultErrorMap:()=>Pt,discriminatedUnion:()=>Vv,effect:()=>nw,enum:()=>ew,function:()=>Qv,getErrorMap:()=>Vr,getParsedType:()=>yt,instanceof:()=>Ev,intersection:()=>Wv,isAborted:()=>Bo,isAsync:()=>Wr,isDirty:()=>Ho,isValid:()=>Ut,late:()=>Ov,lazy:()=>Yv,literal:()=>Xv,makeIssue:()=>En,map:()=>Gv,nan:()=>jv,nativeEnum:()=>tw,never:()=>qv,null:()=>Nv,nullable:()=>iw,number:()=>gp,object:()=>Ks,objectUtil:()=>Bs,oboolean:()=>uw,onumber:()=>dw,optional:()=>ow,ostring:()=>cw,pipeline:()=>aw,preprocess:()=>sw,promise:()=>rw,quotelessJson:()=>ov,record:()=>Hv,set:()=>Kv,setErrorMap:()=>sv,strictObject:()=>Jv,string:()=>hp,symbol:()=>Av,transformer:()=>nw,tuple:()=>Bv,undefined:()=>Mv,union:()=>Fv,unknown:()=>Lv,util:()=>B,void:()=>Uv});var B;(function(e){e.assertEqual=o=>{};function t(o){}e.assertIs=t;function r(o){throw new Error}e.assertNever=r,e.arrayToEnum=o=>{let i={};for(let s of o)i[s]=s;return i},e.getValidEnumValues=o=>{let i=e.objectKeys(o).filter(a=>typeof o[o[a]]!="number"),s={};for(let a of i)s[a]=o[a];return e.objectValues(s)},e.objectValues=o=>e.objectKeys(o).map(function(i){return o[i]}),e.objectKeys=typeof Object.keys=="function"?o=>Object.keys(o):o=>{let i=[];for(let s in o)Object.prototype.hasOwnProperty.call(o,s)&&i.push(s);return i},e.find=(o,i)=>{for(let s of o)if(i(s))return s},e.isInteger=typeof Number.isInteger=="function"?o=>Number.isInteger(o):o=>typeof o=="number"&&Number.isFinite(o)&&Math.floor(o)===o;function n(o,i=" | "){return o.map(s=>typeof s=="string"?`'${s}'`:s).join(i)}e.joinValues=n,e.jsonStringifyReplacer=(o,i)=>typeof i=="bigint"?i.toString():i})(B||(B={}));var Bs;(function(e){e.mergeShapes=(t,r)=>({...t,...r})})(Bs||(Bs={}));var P=B.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),yt=e=>{switch(typeof e){case"undefined":return P.undefined;case"string":return P.string;case"number":return Number.isNaN(e)?P.nan:P.number;case"boolean":return P.boolean;case"function":return P.function;case"bigint":return P.bigint;case"symbol":return P.symbol;case"object":return Array.isArray(e)?P.array:e===null?P.null:e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?P.promise:typeof Map<"u"&&e instanceof Map?P.map:typeof Set<"u"&&e instanceof Set?P.set:typeof Date<"u"&&e instanceof Date?P.date:P.object;default:return P.unknown}};var x=B.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),ov=e=>JSON.stringify(e,null,2).replace(/"([^"]+)":/g,"$1:"),De=class e extends Error{get errors(){return this.issues}constructor(t){super(),this.issues=[],this.addIssue=n=>{this.issues=[...this.issues,n]},this.addIssues=(n=[])=>{this.issues=[...this.issues,...n]};let r=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,r):this.__proto__=r,this.name="ZodError",this.issues=t}format(t){let r=t||function(i){return i.message},n={_errors:[]},o=i=>{for(let s of i.issues)if(s.code==="invalid_union")s.unionErrors.map(o);else if(s.code==="invalid_return_type")o(s.returnTypeError);else if(s.code==="invalid_arguments")o(s.argumentsError);else if(s.path.length===0)n._errors.push(r(s));else{let a=n,c=0;for(;c<s.path.length;){let d=s.path[c];c===s.path.length-1?(a[d]=a[d]||{_errors:[]},a[d]._errors.push(r(s))):a[d]=a[d]||{_errors:[]},a=a[d],c++}}};return o(this),n}static assert(t){if(!(t instanceof e))throw new Error(`Not a ZodError: ${t}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,B.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(t=r=>r.message){let r={},n=[];for(let o of this.issues)if(o.path.length>0){let i=o.path[0];r[i]=r[i]||[],r[i].push(t(o))}else n.push(t(o));return{formErrors:n,fieldErrors:r}}get formErrors(){return this.flatten()}};De.create=e=>new De(e);var iv=(e,t)=>{let r;switch(e.code){case x.invalid_type:e.received===P.undefined?r="Required":r=`Expected ${e.expected}, received ${e.received}`;break;case x.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(e.expected,B.jsonStringifyReplacer)}`;break;case x.unrecognized_keys:r=`Unrecognized key(s) in object: ${B.joinValues(e.keys,", ")}`;break;case x.invalid_union:r="Invalid input";break;case x.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${B.joinValues(e.options)}`;break;case x.invalid_enum_value:r=`Invalid enum value. Expected ${B.joinValues(e.options)}, received '${e.received}'`;break;case x.invalid_arguments:r="Invalid function arguments";break;case x.invalid_return_type:r="Invalid function return type";break;case x.invalid_date:r="Invalid date";break;case x.invalid_string:typeof e.validation=="object"?"includes"in e.validation?(r=`Invalid input: must include "${e.validation.includes}"`,typeof e.validation.position=="number"&&(r=`${r} at one or more positions greater than or equal to ${e.validation.position}`)):"startsWith"in e.validation?r=`Invalid input: must start with "${e.validation.startsWith}"`:"endsWith"in e.validation?r=`Invalid input: must end with "${e.validation.endsWith}"`:B.assertNever(e.validation):e.validation!=="regex"?r=`Invalid ${e.validation}`:r="Invalid";break;case x.too_small:e.type==="array"?r=`Array must contain ${e.exact?"exactly":e.inclusive?"at least":"more than"} ${e.minimum} element(s)`:e.type==="string"?r=`String must contain ${e.exact?"exactly":e.inclusive?"at least":"over"} ${e.minimum} character(s)`:e.type==="number"?r=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:e.type==="bigint"?r=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:e.type==="date"?r=`Date must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(e.minimum))}`:r="Invalid input";break;case x.too_big:e.type==="array"?r=`Array must contain ${e.exact?"exactly":e.inclusive?"at most":"less than"} ${e.maximum} element(s)`:e.type==="string"?r=`String must contain ${e.exact?"exactly":e.inclusive?"at most":"under"} ${e.maximum} character(s)`:e.type==="number"?r=`Number must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:e.type==="bigint"?r=`BigInt must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:e.type==="date"?r=`Date must be ${e.exact?"exactly":e.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(e.maximum))}`:r="Invalid input";break;case x.custom:r="Invalid input";break;case x.invalid_intersection_types:r="Intersection results could not be merged";break;case x.not_multiple_of:r=`Number must be a multiple of ${e.multipleOf}`;break;case x.not_finite:r="Number must be finite";break;default:r=t.defaultError,B.assertNever(e)}return{message:r}},Pt=iv;var ap=Pt;function sv(e){ap=e}function Vr(){return ap}var En=e=>{let{data:t,path:r,errorMaps:n,issueData:o}=e,i=[...r,...o.path||[]],s={...o,path:i};if(o.message!==void 0)return{...o,path:i,message:o.message};let a="",c=n.filter(d=>!!d).slice().reverse();for(let d of c)a=d(s,{data:t,defaultError:a}).message;return{...o,path:i,message:a}},av=[];function $(e,t){let r=Vr(),n=En({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,r,r===Pt?void 0:Pt].filter(o=>!!o)});e.common.issues.push(n)}var xe=class e{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(t,r){let n=[];for(let o of r){if(o.status==="aborted")return N;o.status==="dirty"&&t.dirty(),n.push(o.value)}return{status:t.value,value:n}}static async mergeObjectAsync(t,r){let n=[];for(let o of r){let i=await o.key,s=await o.value;n.push({key:i,value:s})}return e.mergeObjectSync(t,n)}static mergeObjectSync(t,r){let n={};for(let o of r){let{key:i,value:s}=o;if(i.status==="aborted"||s.status==="aborted")return N;i.status==="dirty"&&t.dirty(),s.status==="dirty"&&t.dirty(),i.value!=="__proto__"&&(typeof s.value<"u"||o.alwaysSet)&&(n[i.value]=s.value)}return{status:t.value,value:n}}},N=Object.freeze({status:"aborted"}),sr=e=>({status:"dirty",value:e}),Re=e=>({status:"valid",value:e}),Bo=e=>e.status==="aborted",Ho=e=>e.status==="dirty",Ut=e=>e.status==="valid",Wr=e=>typeof Promise<"u"&&e instanceof Promise;var E;(function(e){e.errToObj=t=>typeof t=="string"?{message:t}:t||{},e.toString=t=>typeof t=="string"?t:t?.message})(E||(E={}));var Ye=class{constructor(t,r,n,o){this._cachedPath=[],this.parent=t,this.data=r,this._path=n,this._key=o}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},cp=(e,t)=>{if(Ut(t))return{success:!0,data:t.value};if(!e.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let r=new De(e.common.issues);return this._error=r,this._error}}};function U(e){if(!e)return{};let{errorMap:t,invalid_type_error:r,required_error:n,description:o}=e;if(t&&(r||n))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return t?{errorMap:t,description:o}:{errorMap:(s,a)=>{let{message:c}=e;return s.code==="invalid_enum_value"?{message:c??a.defaultError}:typeof a.data>"u"?{message:c??n??a.defaultError}:s.code!=="invalid_type"?{message:a.defaultError}:{message:c??r??a.defaultError}},description:o}}var J=class{get description(){return this._def.description}_getType(t){return yt(t.data)}_getOrReturnCtx(t,r){return r||{common:t.parent.common,data:t.data,parsedType:yt(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}_processInputParams(t){return{status:new xe,ctx:{common:t.parent.common,data:t.data,parsedType:yt(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}}_parseSync(t){let r=this._parse(t);if(Wr(r))throw new Error("Synchronous parse encountered promise.");return r}_parseAsync(t){let r=this._parse(t);return Promise.resolve(r)}parse(t,r){let n=this.safeParse(t,r);if(n.success)return n.data;throw n.error}safeParse(t,r){let n={common:{issues:[],async:r?.async??!1,contextualErrorMap:r?.errorMap},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:yt(t)},o=this._parseSync({data:t,path:n.path,parent:n});return cp(n,o)}"~validate"(t){let r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:yt(t)};if(!this["~standard"].async)try{let n=this._parseSync({data:t,path:[],parent:r});return Ut(n)?{value:n.value}:{issues:r.common.issues}}catch(n){n?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),r.common={issues:[],async:!0}}return this._parseAsync({data:t,path:[],parent:r}).then(n=>Ut(n)?{value:n.value}:{issues:r.common.issues})}async parseAsync(t,r){let n=await this.safeParseAsync(t,r);if(n.success)return n.data;throw n.error}async safeParseAsync(t,r){let n={common:{issues:[],contextualErrorMap:r?.errorMap,async:!0},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:yt(t)},o=this._parse({data:t,path:n.path,parent:n}),i=await(Wr(o)?o:Promise.resolve(o));return cp(n,i)}refine(t,r){let n=o=>typeof r=="string"||typeof r>"u"?{message:r}:typeof r=="function"?r(o):r;return this._refinement((o,i)=>{let s=t(o),a=()=>i.addIssue({code:x.custom,...n(o)});return typeof Promise<"u"&&s instanceof Promise?s.then(c=>c?!0:(a(),!1)):s?!0:(a(),!1)})}refinement(t,r){return this._refinement((n,o)=>t(n)?!0:(o.addIssue(typeof r=="function"?r(n,o):r),!1))}_refinement(t){return new Xe({schema:this,typeName:S.ZodEffects,effect:{type:"refinement",refinement:t}})}superRefine(t){return this._refinement(t)}constructor(t){this.spa=this.safeParseAsync,this._def=t,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:r=>this["~validate"](r)}}optional(){return Le.create(this,this._def)}nullable(){return bt.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Et.create(this)}promise(){return Ft.create(this,this._def)}or(t){return mr.create([this,t],this._def)}and(t){return fr.create(this,t,this._def)}transform(t){return new Xe({...U(this._def),schema:this,typeName:S.ZodEffects,effect:{type:"transform",transform:t}})}default(t){let r=typeof t=="function"?t:()=>t;return new br({...U(this._def),innerType:this,defaultValue:r,typeName:S.ZodDefault})}brand(){return new jn({typeName:S.ZodBranded,type:this,...U(this._def)})}catch(t){let r=typeof t=="function"?t:()=>t;return new vr({...U(this._def),innerType:this,catchValue:r,typeName:S.ZodCatch})}describe(t){let r=this.constructor;return new r({...this._def,description:t})}pipe(t){return In.create(this,t)}readonly(){return wr.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},cv=/^c[^\s-]{8,}$/i,dv=/^[0-9a-z]+$/,uv=/^[0-9A-HJKMNP-TV-Z]{26}$/i,lv=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,pv=/^[a-z0-9_-]{21}$/i,mv=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,fv=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,hv=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,gv="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",Hs,yv=/^(?:(?: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])$/,_v=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,bv=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,vv=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,wv=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,kv=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,up="((\\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])))",xv=new RegExp(`^${up}$`);function lp(e){let t="[0-5]\\d";e.precision?t=`${t}\\.\\d{${e.precision}}`:e.precision==null&&(t=`${t}(\\.\\d+)?`);let r=e.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${t})${r}`}function Sv(e){return new RegExp(`^${lp(e)}$`)}function pp(e){let t=`${up}T${lp(e)}`,r=[];return r.push(e.local?"Z?":"Z"),e.offset&&r.push("([+-]\\d{2}:?\\d{2})"),t=`${t}(${r.join("|")})`,new RegExp(`^${t}$`)}function $v(e,t){return!!((t==="v4"||!t)&&yv.test(e)||(t==="v6"||!t)&&bv.test(e))}function zv(e,t){if(!mv.test(e))return!1;try{let[r]=e.split(".");if(!r)return!1;let n=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.length%4)%4,"="),o=JSON.parse(atob(n));return!(typeof o!="object"||o===null||"typ"in o&&o?.typ!=="JWT"||!o.alg||t&&o.alg!==t)}catch{return!1}}function Tv(e,t){return!!((t==="v4"||!t)&&_v.test(e)||(t==="v6"||!t)&&vv.test(e))}var Zt=class e extends J{_parse(t){if(this._def.coerce&&(t.data=String(t.data)),this._getType(t)!==P.string){let i=this._getOrReturnCtx(t);return $(i,{code:x.invalid_type,expected:P.string,received:i.parsedType}),N}let n=new xe,o;for(let i of this._def.checks)if(i.kind==="min")t.data.length<i.value&&(o=this._getOrReturnCtx(t,o),$(o,{code:x.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),n.dirty());else if(i.kind==="max")t.data.length>i.value&&(o=this._getOrReturnCtx(t,o),$(o,{code:x.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),n.dirty());else if(i.kind==="length"){let s=t.data.length>i.value,a=t.data.length<i.value;(s||a)&&(o=this._getOrReturnCtx(t,o),s?$(o,{code:x.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}):a&&$(o,{code:x.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}),n.dirty())}else if(i.kind==="email")hv.test(t.data)||(o=this._getOrReturnCtx(t,o),$(o,{validation:"email",code:x.invalid_string,message:i.message}),n.dirty());else if(i.kind==="emoji")Hs||(Hs=new RegExp(gv,"u")),Hs.test(t.data)||(o=this._getOrReturnCtx(t,o),$(o,{validation:"emoji",code:x.invalid_string,message:i.message}),n.dirty());else if(i.kind==="uuid")lv.test(t.data)||(o=this._getOrReturnCtx(t,o),$(o,{validation:"uuid",code:x.invalid_string,message:i.message}),n.dirty());else if(i.kind==="nanoid")pv.test(t.data)||(o=this._getOrReturnCtx(t,o),$(o,{validation:"nanoid",code:x.invalid_string,message:i.message}),n.dirty());else if(i.kind==="cuid")cv.test(t.data)||(o=this._getOrReturnCtx(t,o),$(o,{validation:"cuid",code:x.invalid_string,message:i.message}),n.dirty());else if(i.kind==="cuid2")dv.test(t.data)||(o=this._getOrReturnCtx(t,o),$(o,{validation:"cuid2",code:x.invalid_string,message:i.message}),n.dirty());else if(i.kind==="ulid")uv.test(t.data)||(o=this._getOrReturnCtx(t,o),$(o,{validation:"ulid",code:x.invalid_string,message:i.message}),n.dirty());else if(i.kind==="url")try{new URL(t.data)}catch{o=this._getOrReturnCtx(t,o),$(o,{validation:"url",code:x.invalid_string,message:i.message}),n.dirty()}else i.kind==="regex"?(i.regex.lastIndex=0,i.regex.test(t.data)||(o=this._getOrReturnCtx(t,o),$(o,{validation:"regex",code:x.invalid_string,message:i.message}),n.dirty())):i.kind==="trim"?t.data=t.data.trim():i.kind==="includes"?t.data.includes(i.value,i.position)||(o=this._getOrReturnCtx(t,o),$(o,{code:x.invalid_string,validation:{includes:i.value,position:i.position},message:i.message}),n.dirty()):i.kind==="toLowerCase"?t.data=t.data.toLowerCase():i.kind==="toUpperCase"?t.data=t.data.toUpperCase():i.kind==="startsWith"?t.data.startsWith(i.value)||(o=this._getOrReturnCtx(t,o),$(o,{code:x.invalid_string,validation:{startsWith:i.value},message:i.message}),n.dirty()):i.kind==="endsWith"?t.data.endsWith(i.value)||(o=this._getOrReturnCtx(t,o),$(o,{code:x.invalid_string,validation:{endsWith:i.value},message:i.message}),n.dirty()):i.kind==="datetime"?pp(i).test(t.data)||(o=this._getOrReturnCtx(t,o),$(o,{code:x.invalid_string,validation:"datetime",message:i.message}),n.dirty()):i.kind==="date"?xv.test(t.data)||(o=this._getOrReturnCtx(t,o),$(o,{code:x.invalid_string,validation:"date",message:i.message}),n.dirty()):i.kind==="time"?Sv(i).test(t.data)||(o=this._getOrReturnCtx(t,o),$(o,{code:x.invalid_string,validation:"time",message:i.message}),n.dirty()):i.kind==="duration"?fv.test(t.data)||(o=this._getOrReturnCtx(t,o),$(o,{validation:"duration",code:x.invalid_string,message:i.message}),n.dirty()):i.kind==="ip"?$v(t.data,i.version)||(o=this._getOrReturnCtx(t,o),$(o,{validation:"ip",code:x.invalid_string,message:i.message}),n.dirty()):i.kind==="jwt"?zv(t.data,i.alg)||(o=this._getOrReturnCtx(t,o),$(o,{validation:"jwt",code:x.invalid_string,message:i.message}),n.dirty()):i.kind==="cidr"?Tv(t.data,i.version)||(o=this._getOrReturnCtx(t,o),$(o,{validation:"cidr",code:x.invalid_string,message:i.message}),n.dirty()):i.kind==="base64"?wv.test(t.data)||(o=this._getOrReturnCtx(t,o),$(o,{validation:"base64",code:x.invalid_string,message:i.message}),n.dirty()):i.kind==="base64url"?kv.test(t.data)||(o=this._getOrReturnCtx(t,o),$(o,{validation:"base64url",code:x.invalid_string,message:i.message}),n.dirty()):B.assertNever(i);return{status:n.value,value:t.data}}_regex(t,r,n){return this.refinement(o=>t.test(o),{validation:r,code:x.invalid_string,...E.errToObj(n)})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}email(t){return this._addCheck({kind:"email",...E.errToObj(t)})}url(t){return this._addCheck({kind:"url",...E.errToObj(t)})}emoji(t){return this._addCheck({kind:"emoji",...E.errToObj(t)})}uuid(t){return this._addCheck({kind:"uuid",...E.errToObj(t)})}nanoid(t){return this._addCheck({kind:"nanoid",...E.errToObj(t)})}cuid(t){return this._addCheck({kind:"cuid",...E.errToObj(t)})}cuid2(t){return this._addCheck({kind:"cuid2",...E.errToObj(t)})}ulid(t){return this._addCheck({kind:"ulid",...E.errToObj(t)})}base64(t){return this._addCheck({kind:"base64",...E.errToObj(t)})}base64url(t){return this._addCheck({kind:"base64url",...E.errToObj(t)})}jwt(t){return this._addCheck({kind:"jwt",...E.errToObj(t)})}ip(t){return this._addCheck({kind:"ip",...E.errToObj(t)})}cidr(t){return this._addCheck({kind:"cidr",...E.errToObj(t)})}datetime(t){return typeof t=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:t}):this._addCheck({kind:"datetime",precision:typeof t?.precision>"u"?null:t?.precision,offset:t?.offset??!1,local:t?.local??!1,...E.errToObj(t?.message)})}date(t){return this._addCheck({kind:"date",message:t})}time(t){return typeof t=="string"?this._addCheck({kind:"time",precision:null,message:t}):this._addCheck({kind:"time",precision:typeof t?.precision>"u"?null:t?.precision,...E.errToObj(t?.message)})}duration(t){return this._addCheck({kind:"duration",...E.errToObj(t)})}regex(t,r){return this._addCheck({kind:"regex",regex:t,...E.errToObj(r)})}includes(t,r){return this._addCheck({kind:"includes",value:t,position:r?.position,...E.errToObj(r?.message)})}startsWith(t,r){return this._addCheck({kind:"startsWith",value:t,...E.errToObj(r)})}endsWith(t,r){return this._addCheck({kind:"endsWith",value:t,...E.errToObj(r)})}min(t,r){return this._addCheck({kind:"min",value:t,...E.errToObj(r)})}max(t,r){return this._addCheck({kind:"max",value:t,...E.errToObj(r)})}length(t,r){return this._addCheck({kind:"length",value:t,...E.errToObj(r)})}nonempty(t){return this.min(1,E.errToObj(t))}trim(){return new e({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new e({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new e({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(t=>t.kind==="datetime")}get isDate(){return!!this._def.checks.find(t=>t.kind==="date")}get isTime(){return!!this._def.checks.find(t=>t.kind==="time")}get isDuration(){return!!this._def.checks.find(t=>t.kind==="duration")}get isEmail(){return!!this._def.checks.find(t=>t.kind==="email")}get isURL(){return!!this._def.checks.find(t=>t.kind==="url")}get isEmoji(){return!!this._def.checks.find(t=>t.kind==="emoji")}get isUUID(){return!!this._def.checks.find(t=>t.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(t=>t.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(t=>t.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(t=>t.kind==="cuid2")}get isULID(){return!!this._def.checks.find(t=>t.kind==="ulid")}get isIP(){return!!this._def.checks.find(t=>t.kind==="ip")}get isCIDR(){return!!this._def.checks.find(t=>t.kind==="cidr")}get isBase64(){return!!this._def.checks.find(t=>t.kind==="base64")}get isBase64url(){return!!this._def.checks.find(t=>t.kind==="base64url")}get minLength(){let t=null;for(let r of this._def.checks)r.kind==="min"&&(t===null||r.value>t)&&(t=r.value);return t}get maxLength(){let t=null;for(let r of this._def.checks)r.kind==="max"&&(t===null||r.value<t)&&(t=r.value);return t}};Zt.create=e=>new Zt({checks:[],typeName:S.ZodString,coerce:e?.coerce??!1,...U(e)});function Pv(e,t){let r=(e.toString().split(".")[1]||"").length,n=(t.toString().split(".")[1]||"").length,o=r>n?r:n,i=Number.parseInt(e.toFixed(o).replace(".","")),s=Number.parseInt(t.toFixed(o).replace(".",""));return i%s/10**o}var ar=class e extends J{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(t){if(this._def.coerce&&(t.data=Number(t.data)),this._getType(t)!==P.number){let i=this._getOrReturnCtx(t);return $(i,{code:x.invalid_type,expected:P.number,received:i.parsedType}),N}let n,o=new xe;for(let i of this._def.checks)i.kind==="int"?B.isInteger(t.data)||(n=this._getOrReturnCtx(t,n),$(n,{code:x.invalid_type,expected:"integer",received:"float",message:i.message}),o.dirty()):i.kind==="min"?(i.inclusive?t.data<i.value:t.data<=i.value)&&(n=this._getOrReturnCtx(t,n),$(n,{code:x.too_small,minimum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),o.dirty()):i.kind==="max"?(i.inclusive?t.data>i.value:t.data>=i.value)&&(n=this._getOrReturnCtx(t,n),$(n,{code:x.too_big,maximum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),o.dirty()):i.kind==="multipleOf"?Pv(t.data,i.value)!==0&&(n=this._getOrReturnCtx(t,n),$(n,{code:x.not_multiple_of,multipleOf:i.value,message:i.message}),o.dirty()):i.kind==="finite"?Number.isFinite(t.data)||(n=this._getOrReturnCtx(t,n),$(n,{code:x.not_finite,message:i.message}),o.dirty()):B.assertNever(i);return{status:o.value,value:t.data}}gte(t,r){return this.setLimit("min",t,!0,E.toString(r))}gt(t,r){return this.setLimit("min",t,!1,E.toString(r))}lte(t,r){return this.setLimit("max",t,!0,E.toString(r))}lt(t,r){return this.setLimit("max",t,!1,E.toString(r))}setLimit(t,r,n,o){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:r,inclusive:n,message:E.toString(o)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}int(t){return this._addCheck({kind:"int",message:E.toString(t)})}positive(t){return this._addCheck({kind:"min",value:0,inclusive:!1,message:E.toString(t)})}negative(t){return this._addCheck({kind:"max",value:0,inclusive:!1,message:E.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:0,inclusive:!0,message:E.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:0,inclusive:!0,message:E.toString(t)})}multipleOf(t,r){return this._addCheck({kind:"multipleOf",value:t,message:E.toString(r)})}finite(t){return this._addCheck({kind:"finite",message:E.toString(t)})}safe(t){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:E.toString(t)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:E.toString(t)})}get minValue(){let t=null;for(let r of this._def.checks)r.kind==="min"&&(t===null||r.value>t)&&(t=r.value);return t}get maxValue(){let t=null;for(let r of this._def.checks)r.kind==="max"&&(t===null||r.value<t)&&(t=r.value);return t}get isInt(){return!!this._def.checks.find(t=>t.kind==="int"||t.kind==="multipleOf"&&B.isInteger(t.value))}get isFinite(){let t=null,r=null;for(let n of this._def.checks){if(n.kind==="finite"||n.kind==="int"||n.kind==="multipleOf")return!0;n.kind==="min"?(r===null||n.value>r)&&(r=n.value):n.kind==="max"&&(t===null||n.value<t)&&(t=n.value)}return Number.isFinite(r)&&Number.isFinite(t)}};ar.create=e=>new ar({checks:[],typeName:S.ZodNumber,coerce:e?.coerce||!1,...U(e)});var cr=class e extends J{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(t){if(this._def.coerce)try{t.data=BigInt(t.data)}catch{return this._getInvalidInput(t)}if(this._getType(t)!==P.bigint)return this._getInvalidInput(t);let n,o=new xe;for(let i of this._def.checks)i.kind==="min"?(i.inclusive?t.data<i.value:t.data<=i.value)&&(n=this._getOrReturnCtx(t,n),$(n,{code:x.too_small,type:"bigint",minimum:i.value,inclusive:i.inclusive,message:i.message}),o.dirty()):i.kind==="max"?(i.inclusive?t.data>i.value:t.data>=i.value)&&(n=this._getOrReturnCtx(t,n),$(n,{code:x.too_big,type:"bigint",maximum:i.value,inclusive:i.inclusive,message:i.message}),o.dirty()):i.kind==="multipleOf"?t.data%i.value!==BigInt(0)&&(n=this._getOrReturnCtx(t,n),$(n,{code:x.not_multiple_of,multipleOf:i.value,message:i.message}),o.dirty()):B.assertNever(i);return{status:o.value,value:t.data}}_getInvalidInput(t){let r=this._getOrReturnCtx(t);return $(r,{code:x.invalid_type,expected:P.bigint,received:r.parsedType}),N}gte(t,r){return this.setLimit("min",t,!0,E.toString(r))}gt(t,r){return this.setLimit("min",t,!1,E.toString(r))}lte(t,r){return this.setLimit("max",t,!0,E.toString(r))}lt(t,r){return this.setLimit("max",t,!1,E.toString(r))}setLimit(t,r,n,o){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:r,inclusive:n,message:E.toString(o)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}positive(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:E.toString(t)})}negative(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:E.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:E.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:E.toString(t)})}multipleOf(t,r){return this._addCheck({kind:"multipleOf",value:t,message:E.toString(r)})}get minValue(){let t=null;for(let r of this._def.checks)r.kind==="min"&&(t===null||r.value>t)&&(t=r.value);return t}get maxValue(){let t=null;for(let r of this._def.checks)r.kind==="max"&&(t===null||r.value<t)&&(t=r.value);return t}};cr.create=e=>new cr({checks:[],typeName:S.ZodBigInt,coerce:e?.coerce??!1,...U(e)});var dr=class extends J{_parse(t){if(this._def.coerce&&(t.data=!!t.data),this._getType(t)!==P.boolean){let n=this._getOrReturnCtx(t);return $(n,{code:x.invalid_type,expected:P.boolean,received:n.parsedType}),N}return Re(t.data)}};dr.create=e=>new dr({typeName:S.ZodBoolean,coerce:e?.coerce||!1,...U(e)});var ur=class e extends J{_parse(t){if(this._def.coerce&&(t.data=new Date(t.data)),this._getType(t)!==P.date){let i=this._getOrReturnCtx(t);return $(i,{code:x.invalid_type,expected:P.date,received:i.parsedType}),N}if(Number.isNaN(t.data.getTime())){let i=this._getOrReturnCtx(t);return $(i,{code:x.invalid_date}),N}let n=new xe,o;for(let i of this._def.checks)i.kind==="min"?t.data.getTime()<i.value&&(o=this._getOrReturnCtx(t,o),$(o,{code:x.too_small,message:i.message,inclusive:!0,exact:!1,minimum:i.value,type:"date"}),n.dirty()):i.kind==="max"?t.data.getTime()>i.value&&(o=this._getOrReturnCtx(t,o),$(o,{code:x.too_big,message:i.message,inclusive:!0,exact:!1,maximum:i.value,type:"date"}),n.dirty()):B.assertNever(i);return{status:n.value,value:new Date(t.data.getTime())}}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}min(t,r){return this._addCheck({kind:"min",value:t.getTime(),message:E.toString(r)})}max(t,r){return this._addCheck({kind:"max",value:t.getTime(),message:E.toString(r)})}get minDate(){let t=null;for(let r of this._def.checks)r.kind==="min"&&(t===null||r.value>t)&&(t=r.value);return t!=null?new Date(t):null}get maxDate(){let t=null;for(let r of this._def.checks)r.kind==="max"&&(t===null||r.value<t)&&(t=r.value);return t!=null?new Date(t):null}};ur.create=e=>new ur({checks:[],coerce:e?.coerce||!1,typeName:S.ZodDate,...U(e)});var Hr=class extends J{_parse(t){if(this._getType(t)!==P.symbol){let n=this._getOrReturnCtx(t);return $(n,{code:x.invalid_type,expected:P.symbol,received:n.parsedType}),N}return Re(t.data)}};Hr.create=e=>new Hr({typeName:S.ZodSymbol,...U(e)});var lr=class extends J{_parse(t){if(this._getType(t)!==P.undefined){let n=this._getOrReturnCtx(t);return $(n,{code:x.invalid_type,expected:P.undefined,received:n.parsedType}),N}return Re(t.data)}};lr.create=e=>new lr({typeName:S.ZodUndefined,...U(e)});var pr=class extends J{_parse(t){if(this._getType(t)!==P.null){let n=this._getOrReturnCtx(t);return $(n,{code:x.invalid_type,expected:P.null,received:n.parsedType}),N}return Re(t.data)}};pr.create=e=>new pr({typeName:S.ZodNull,...U(e)});var Jt=class extends J{constructor(){super(...arguments),this._any=!0}_parse(t){return Re(t.data)}};Jt.create=e=>new Jt({typeName:S.ZodAny,...U(e)});var Ot=class extends J{constructor(){super(...arguments),this._unknown=!0}_parse(t){return Re(t.data)}};Ot.create=e=>new Ot({typeName:S.ZodUnknown,...U(e)});var at=class extends J{_parse(t){let r=this._getOrReturnCtx(t);return $(r,{code:x.invalid_type,expected:P.never,received:r.parsedType}),N}};at.create=e=>new at({typeName:S.ZodNever,...U(e)});var Gr=class extends J{_parse(t){if(this._getType(t)!==P.undefined){let n=this._getOrReturnCtx(t);return $(n,{code:x.invalid_type,expected:P.void,received:n.parsedType}),N}return Re(t.data)}};Gr.create=e=>new Gr({typeName:S.ZodVoid,...U(e)});var Et=class e extends J{_parse(t){let{ctx:r,status:n}=this._processInputParams(t),o=this._def;if(r.parsedType!==P.array)return $(r,{code:x.invalid_type,expected:P.array,received:r.parsedType}),N;if(o.exactLength!==null){let s=r.data.length>o.exactLength.value,a=r.data.length<o.exactLength.value;(s||a)&&($(r,{code:s?x.too_big:x.too_small,minimum:a?o.exactLength.value:void 0,maximum:s?o.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:o.exactLength.message}),n.dirty())}if(o.minLength!==null&&r.data.length<o.minLength.value&&($(r,{code:x.too_small,minimum:o.minLength.value,type:"array",inclusive:!0,exact:!1,message:o.minLength.message}),n.dirty()),o.maxLength!==null&&r.data.length>o.maxLength.value&&($(r,{code:x.too_big,maximum:o.maxLength.value,type:"array",inclusive:!0,exact:!1,message:o.maxLength.message}),n.dirty()),r.common.async)return Promise.all([...r.data].map((s,a)=>o.type._parseAsync(new Ye(r,s,r.path,a)))).then(s=>xe.mergeArray(n,s));let i=[...r.data].map((s,a)=>o.type._parseSync(new Ye(r,s,r.path,a)));return xe.mergeArray(n,i)}get element(){return this._def.type}min(t,r){return new e({...this._def,minLength:{value:t,message:E.toString(r)}})}max(t,r){return new e({...this._def,maxLength:{value:t,message:E.toString(r)}})}length(t,r){return new e({...this._def,exactLength:{value:t,message:E.toString(r)}})}nonempty(t){return this.min(1,t)}};Et.create=(e,t)=>new Et({type:e,minLength:null,maxLength:null,exactLength:null,typeName:S.ZodArray,...U(t)});function Br(e){if(e instanceof qe){let t={};for(let r in e.shape){let n=e.shape[r];t[r]=Le.create(Br(n))}return new qe({...e._def,shape:()=>t})}else return e instanceof Et?new Et({...e._def,type:Br(e.element)}):e instanceof Le?Le.create(Br(e.unwrap())):e instanceof bt?bt.create(Br(e.unwrap())):e instanceof _t?_t.create(e.items.map(t=>Br(t))):e}var qe=class e extends J{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let t=this._def.shape(),r=B.objectKeys(t);return this._cached={shape:t,keys:r},this._cached}_parse(t){if(this._getType(t)!==P.object){let d=this._getOrReturnCtx(t);return $(d,{code:x.invalid_type,expected:P.object,received:d.parsedType}),N}let{status:n,ctx:o}=this._processInputParams(t),{shape:i,keys:s}=this._getCached(),a=[];if(!(this._def.catchall instanceof at&&this._def.unknownKeys==="strip"))for(let d in o.data)s.includes(d)||a.push(d);let c=[];for(let d of s){let u=i[d],p=o.data[d];c.push({key:{status:"valid",value:d},value:u._parse(new Ye(o,p,o.path,d)),alwaysSet:d in o.data})}if(this._def.catchall instanceof at){let d=this._def.unknownKeys;if(d==="passthrough")for(let u of a)c.push({key:{status:"valid",value:u},value:{status:"valid",value:o.data[u]}});else if(d==="strict")a.length>0&&($(o,{code:x.unrecognized_keys,keys:a}),n.dirty());else if(d!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let d=this._def.catchall;for(let u of a){let p=o.data[u];c.push({key:{status:"valid",value:u},value:d._parse(new Ye(o,p,o.path,u)),alwaysSet:u in o.data})}}return o.common.async?Promise.resolve().then(async()=>{let d=[];for(let u of c){let p=await u.key,m=await u.value;d.push({key:p,value:m,alwaysSet:u.alwaysSet})}return d}).then(d=>xe.mergeObjectSync(n,d)):xe.mergeObjectSync(n,c)}get shape(){return this._def.shape()}strict(t){return E.errToObj,new e({...this._def,unknownKeys:"strict",...t!==void 0?{errorMap:(r,n)=>{let o=this._def.errorMap?.(r,n).message??n.defaultError;return r.code==="unrecognized_keys"?{message:E.errToObj(t).message??o}:{message:o}}}:{}})}strip(){return new e({...this._def,unknownKeys:"strip"})}passthrough(){return new e({...this._def,unknownKeys:"passthrough"})}extend(t){return new e({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new e({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:S.ZodObject})}setKey(t,r){return this.augment({[t]:r})}catchall(t){return new e({...this._def,catchall:t})}pick(t){let r={};for(let n of B.objectKeys(t))t[n]&&this.shape[n]&&(r[n]=this.shape[n]);return new e({...this._def,shape:()=>r})}omit(t){let r={};for(let n of B.objectKeys(this.shape))t[n]||(r[n]=this.shape[n]);return new e({...this._def,shape:()=>r})}deepPartial(){return Br(this)}partial(t){let r={};for(let n of B.objectKeys(this.shape)){let o=this.shape[n];t&&!t[n]?r[n]=o:r[n]=o.optional()}return new e({...this._def,shape:()=>r})}required(t){let r={};for(let n of B.objectKeys(this.shape))if(t&&!t[n])r[n]=this.shape[n];else{let i=this.shape[n];for(;i instanceof Le;)i=i._def.innerType;r[n]=i}return new e({...this._def,shape:()=>r})}keyof(){return mp(B.objectKeys(this.shape))}};qe.create=(e,t)=>new qe({shape:()=>e,unknownKeys:"strip",catchall:at.create(),typeName:S.ZodObject,...U(t)});qe.strictCreate=(e,t)=>new qe({shape:()=>e,unknownKeys:"strict",catchall:at.create(),typeName:S.ZodObject,...U(t)});qe.lazycreate=(e,t)=>new qe({shape:e,unknownKeys:"strip",catchall:at.create(),typeName:S.ZodObject,...U(t)});var mr=class extends J{_parse(t){let{ctx:r}=this._processInputParams(t),n=this._def.options;function o(i){for(let a of i)if(a.result.status==="valid")return a.result;for(let a of i)if(a.result.status==="dirty")return r.common.issues.push(...a.ctx.common.issues),a.result;let s=i.map(a=>new De(a.ctx.common.issues));return $(r,{code:x.invalid_union,unionErrors:s}),N}if(r.common.async)return Promise.all(n.map(async i=>{let s={...r,common:{...r.common,issues:[]},parent:null};return{result:await i._parseAsync({data:r.data,path:r.path,parent:s}),ctx:s}})).then(o);{let i,s=[];for(let c of n){let d={...r,common:{...r.common,issues:[]},parent:null},u=c._parseSync({data:r.data,path:r.path,parent:d});if(u.status==="valid")return u;u.status==="dirty"&&!i&&(i={result:u,ctx:d}),d.common.issues.length&&s.push(d.common.issues)}if(i)return r.common.issues.push(...i.ctx.common.issues),i.result;let a=s.map(c=>new De(c));return $(r,{code:x.invalid_union,unionErrors:a}),N}}get options(){return this._def.options}};mr.create=(e,t)=>new mr({options:e,typeName:S.ZodUnion,...U(t)});var Rt=e=>e instanceof hr?Rt(e.schema):e instanceof Xe?Rt(e.innerType()):e instanceof gr?[e.value]:e instanceof yr?e.options:e instanceof _r?B.objectValues(e.enum):e instanceof br?Rt(e._def.innerType):e instanceof lr?[void 0]:e instanceof pr?[null]:e instanceof Le?[void 0,...Rt(e.unwrap())]:e instanceof bt?[null,...Rt(e.unwrap())]:e instanceof jn||e instanceof wr?Rt(e.unwrap()):e instanceof vr?Rt(e._def.innerType):[],Go=class e extends J{_parse(t){let{ctx:r}=this._processInputParams(t);if(r.parsedType!==P.object)return $(r,{code:x.invalid_type,expected:P.object,received:r.parsedType}),N;let n=this.discriminator,o=r.data[n],i=this.optionsMap.get(o);return i?r.common.async?i._parseAsync({data:r.data,path:r.path,parent:r}):i._parseSync({data:r.data,path:r.path,parent:r}):($(r,{code:x.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),N)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(t,r,n){let o=new Map;for(let i of r){let s=Rt(i.shape[t]);if(!s.length)throw new Error(`A discriminator value for key \`${t}\` could not be extracted from all schema options`);for(let a of s){if(o.has(a))throw new Error(`Discriminator property ${String(t)} has duplicate value ${String(a)}`);o.set(a,i)}}return new e({typeName:S.ZodDiscriminatedUnion,discriminator:t,options:r,optionsMap:o,...U(n)})}};function Gs(e,t){let r=yt(e),n=yt(t);if(e===t)return{valid:!0,data:e};if(r===P.object&&n===P.object){let o=B.objectKeys(t),i=B.objectKeys(e).filter(a=>o.indexOf(a)!==-1),s={...e,...t};for(let a of i){let c=Gs(e[a],t[a]);if(!c.valid)return{valid:!1};s[a]=c.data}return{valid:!0,data:s}}else if(r===P.array&&n===P.array){if(e.length!==t.length)return{valid:!1};let o=[];for(let i=0;i<e.length;i++){let s=e[i],a=t[i],c=Gs(s,a);if(!c.valid)return{valid:!1};o.push(c.data)}return{valid:!0,data:o}}else return r===P.date&&n===P.date&&+e==+t?{valid:!0,data:e}:{valid:!1}}var fr=class extends J{_parse(t){let{status:r,ctx:n}=this._processInputParams(t),o=(i,s)=>{if(Bo(i)||Bo(s))return N;let a=Gs(i.value,s.value);return a.valid?((Ho(i)||Ho(s))&&r.dirty(),{status:r.value,value:a.data}):($(n,{code:x.invalid_intersection_types}),N)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([i,s])=>o(i,s)):o(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}};fr.create=(e,t,r)=>new fr({left:e,right:t,typeName:S.ZodIntersection,...U(r)});var _t=class e extends J{_parse(t){let{status:r,ctx:n}=this._processInputParams(t);if(n.parsedType!==P.array)return $(n,{code:x.invalid_type,expected:P.array,received:n.parsedType}),N;if(n.data.length<this._def.items.length)return $(n,{code:x.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),N;!this._def.rest&&n.data.length>this._def.items.length&&($(n,{code:x.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),r.dirty());let i=[...n.data].map((s,a)=>{let c=this._def.items[a]||this._def.rest;return c?c._parse(new Ye(n,s,n.path,a)):null}).filter(s=>!!s);return n.common.async?Promise.all(i).then(s=>xe.mergeArray(r,s)):xe.mergeArray(r,i)}get items(){return this._def.items}rest(t){return new e({...this._def,rest:t})}};_t.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new _t({items:e,typeName:S.ZodTuple,rest:null,...U(t)})};var Ko=class e extends J{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){let{status:r,ctx:n}=this._processInputParams(t);if(n.parsedType!==P.object)return $(n,{code:x.invalid_type,expected:P.object,received:n.parsedType}),N;let o=[],i=this._def.keyType,s=this._def.valueType;for(let a in n.data)o.push({key:i._parse(new Ye(n,a,n.path,a)),value:s._parse(new Ye(n,n.data[a],n.path,a)),alwaysSet:a in n.data});return n.common.async?xe.mergeObjectAsync(r,o):xe.mergeObjectSync(r,o)}get element(){return this._def.valueType}static create(t,r,n){return r instanceof J?new e({keyType:t,valueType:r,typeName:S.ZodRecord,...U(n)}):new e({keyType:Zt.create(),valueType:t,typeName:S.ZodRecord,...U(r)})}},Kr=class extends J{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){let{status:r,ctx:n}=this._processInputParams(t);if(n.parsedType!==P.map)return $(n,{code:x.invalid_type,expected:P.map,received:n.parsedType}),N;let o=this._def.keyType,i=this._def.valueType,s=[...n.data.entries()].map(([a,c],d)=>({key:o._parse(new Ye(n,a,n.path,[d,"key"])),value:i._parse(new Ye(n,c,n.path,[d,"value"]))}));if(n.common.async){let a=new Map;return Promise.resolve().then(async()=>{for(let c of s){let d=await c.key,u=await c.value;if(d.status==="aborted"||u.status==="aborted")return N;(d.status==="dirty"||u.status==="dirty")&&r.dirty(),a.set(d.value,u.value)}return{status:r.value,value:a}})}else{let a=new Map;for(let c of s){let d=c.key,u=c.value;if(d.status==="aborted"||u.status==="aborted")return N;(d.status==="dirty"||u.status==="dirty")&&r.dirty(),a.set(d.value,u.value)}return{status:r.value,value:a}}}};Kr.create=(e,t,r)=>new Kr({valueType:t,keyType:e,typeName:S.ZodMap,...U(r)});var Qr=class e extends J{_parse(t){let{status:r,ctx:n}=this._processInputParams(t);if(n.parsedType!==P.set)return $(n,{code:x.invalid_type,expected:P.set,received:n.parsedType}),N;let o=this._def;o.minSize!==null&&n.data.size<o.minSize.value&&($(n,{code:x.too_small,minimum:o.minSize.value,type:"set",inclusive:!0,exact:!1,message:o.minSize.message}),r.dirty()),o.maxSize!==null&&n.data.size>o.maxSize.value&&($(n,{code:x.too_big,maximum:o.maxSize.value,type:"set",inclusive:!0,exact:!1,message:o.maxSize.message}),r.dirty());let i=this._def.valueType;function s(c){let d=new Set;for(let u of c){if(u.status==="aborted")return N;u.status==="dirty"&&r.dirty(),d.add(u.value)}return{status:r.value,value:d}}let a=[...n.data.values()].map((c,d)=>i._parse(new Ye(n,c,n.path,d)));return n.common.async?Promise.all(a).then(c=>s(c)):s(a)}min(t,r){return new e({...this._def,minSize:{value:t,message:E.toString(r)}})}max(t,r){return new e({...this._def,maxSize:{value:t,message:E.toString(r)}})}size(t,r){return this.min(t,r).max(t,r)}nonempty(t){return this.min(1,t)}};Qr.create=(e,t)=>new Qr({valueType:e,minSize:null,maxSize:null,typeName:S.ZodSet,...U(t)});var Qo=class e extends J{constructor(){super(...arguments),this.validate=this.implement}_parse(t){let{ctx:r}=this._processInputParams(t);if(r.parsedType!==P.function)return $(r,{code:x.invalid_type,expected:P.function,received:r.parsedType}),N;function n(a,c){return En({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,Vr(),Pt].filter(d=>!!d),issueData:{code:x.invalid_arguments,argumentsError:c}})}function o(a,c){return En({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,Vr(),Pt].filter(d=>!!d),issueData:{code:x.invalid_return_type,returnTypeError:c}})}let i={errorMap:r.common.contextualErrorMap},s=r.data;if(this._def.returns instanceof Ft){let a=this;return Re(async function(...c){let d=new De([]),u=await a._def.args.parseAsync(c,i).catch(f=>{throw d.addIssue(n(c,f)),d}),p=await Reflect.apply(s,this,u);return await a._def.returns._def.type.parseAsync(p,i).catch(f=>{throw d.addIssue(o(p,f)),d})})}else{let a=this;return Re(function(...c){let d=a._def.args.safeParse(c,i);if(!d.success)throw new De([n(c,d.error)]);let u=Reflect.apply(s,this,d.data),p=a._def.returns.safeParse(u,i);if(!p.success)throw new De([o(u,p.error)]);return p.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...t){return new e({...this._def,args:_t.create(t).rest(Ot.create())})}returns(t){return new e({...this._def,returns:t})}implement(t){return this.parse(t)}strictImplement(t){return this.parse(t)}static create(t,r,n){return new e({args:t||_t.create([]).rest(Ot.create()),returns:r||Ot.create(),typeName:S.ZodFunction,...U(n)})}},hr=class extends J{get schema(){return this._def.getter()}_parse(t){let{ctx:r}=this._processInputParams(t);return this._def.getter()._parse({data:r.data,path:r.path,parent:r})}};hr.create=(e,t)=>new hr({getter:e,typeName:S.ZodLazy,...U(t)});var gr=class extends J{_parse(t){if(t.data!==this._def.value){let r=this._getOrReturnCtx(t);return $(r,{received:r.data,code:x.invalid_literal,expected:this._def.value}),N}return{status:"valid",value:t.data}}get value(){return this._def.value}};gr.create=(e,t)=>new gr({value:e,typeName:S.ZodLiteral,...U(t)});function mp(e,t){return new yr({values:e,typeName:S.ZodEnum,...U(t)})}var yr=class e extends J{_parse(t){if(typeof t.data!="string"){let r=this._getOrReturnCtx(t),n=this._def.values;return $(r,{expected:B.joinValues(n),received:r.parsedType,code:x.invalid_type}),N}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(t.data)){let r=this._getOrReturnCtx(t),n=this._def.values;return $(r,{received:r.data,code:x.invalid_enum_value,options:n}),N}return Re(t.data)}get options(){return this._def.values}get enum(){let t={};for(let r of this._def.values)t[r]=r;return t}get Values(){let t={};for(let r of this._def.values)t[r]=r;return t}get Enum(){let t={};for(let r of this._def.values)t[r]=r;return t}extract(t,r=this._def){return e.create(t,{...this._def,...r})}exclude(t,r=this._def){return e.create(this.options.filter(n=>!t.includes(n)),{...this._def,...r})}};yr.create=mp;var _r=class extends J{_parse(t){let r=B.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(t);if(n.parsedType!==P.string&&n.parsedType!==P.number){let o=B.objectValues(r);return $(n,{expected:B.joinValues(o),received:n.parsedType,code:x.invalid_type}),N}if(this._cache||(this._cache=new Set(B.getValidEnumValues(this._def.values))),!this._cache.has(t.data)){let o=B.objectValues(r);return $(n,{received:n.data,code:x.invalid_enum_value,options:o}),N}return Re(t.data)}get enum(){return this._def.values}};_r.create=(e,t)=>new _r({values:e,typeName:S.ZodNativeEnum,...U(t)});var Ft=class extends J{unwrap(){return this._def.type}_parse(t){let{ctx:r}=this._processInputParams(t);if(r.parsedType!==P.promise&&r.common.async===!1)return $(r,{code:x.invalid_type,expected:P.promise,received:r.parsedType}),N;let n=r.parsedType===P.promise?r.data:Promise.resolve(r.data);return Re(n.then(o=>this._def.type.parseAsync(o,{path:r.path,errorMap:r.common.contextualErrorMap})))}};Ft.create=(e,t)=>new Ft({type:e,typeName:S.ZodPromise,...U(t)});var Xe=class extends J{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===S.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(t){let{status:r,ctx:n}=this._processInputParams(t),o=this._def.effect||null,i={addIssue:s=>{$(n,s),s.fatal?r.abort():r.dirty()},get path(){return n.path}};if(i.addIssue=i.addIssue.bind(i),o.type==="preprocess"){let s=o.transform(n.data,i);if(n.common.async)return Promise.resolve(s).then(async a=>{if(r.value==="aborted")return N;let c=await this._def.schema._parseAsync({data:a,path:n.path,parent:n});return c.status==="aborted"?N:c.status==="dirty"?sr(c.value):r.value==="dirty"?sr(c.value):c});{if(r.value==="aborted")return N;let a=this._def.schema._parseSync({data:s,path:n.path,parent:n});return a.status==="aborted"?N:a.status==="dirty"?sr(a.value):r.value==="dirty"?sr(a.value):a}}if(o.type==="refinement"){let s=a=>{let c=o.refinement(a,i);if(n.common.async)return Promise.resolve(c);if(c instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return a};if(n.common.async===!1){let a=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return a.status==="aborted"?N:(a.status==="dirty"&&r.dirty(),s(a.value),{status:r.value,value:a.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(a=>a.status==="aborted"?N:(a.status==="dirty"&&r.dirty(),s(a.value).then(()=>({status:r.value,value:a.value}))))}if(o.type==="transform")if(n.common.async===!1){let s=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!Ut(s))return N;let a=o.transform(s.value,i);if(a instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:r.value,value:a}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(s=>Ut(s)?Promise.resolve(o.transform(s.value,i)).then(a=>({status:r.value,value:a})):N);B.assertNever(o)}};Xe.create=(e,t,r)=>new Xe({schema:e,typeName:S.ZodEffects,effect:t,...U(r)});Xe.createWithPreprocess=(e,t,r)=>new Xe({schema:t,effect:{type:"preprocess",transform:e},typeName:S.ZodEffects,...U(r)});var Le=class extends J{_parse(t){return this._getType(t)===P.undefined?Re(void 0):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};Le.create=(e,t)=>new Le({innerType:e,typeName:S.ZodOptional,...U(t)});var bt=class extends J{_parse(t){return this._getType(t)===P.null?Re(null):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};bt.create=(e,t)=>new bt({innerType:e,typeName:S.ZodNullable,...U(t)});var br=class extends J{_parse(t){let{ctx:r}=this._processInputParams(t),n=r.data;return r.parsedType===P.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:r.path,parent:r})}removeDefault(){return this._def.innerType}};br.create=(e,t)=>new br({innerType:e,typeName:S.ZodDefault,defaultValue:typeof t.default=="function"?t.default:()=>t.default,...U(t)});var vr=class extends J{_parse(t){let{ctx:r}=this._processInputParams(t),n={...r,common:{...r.common,issues:[]}},o=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return Wr(o)?o.then(i=>({status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new De(n.common.issues)},input:n.data})})):{status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new De(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};vr.create=(e,t)=>new vr({innerType:e,typeName:S.ZodCatch,catchValue:typeof t.catch=="function"?t.catch:()=>t.catch,...U(t)});var Yr=class extends J{_parse(t){if(this._getType(t)!==P.nan){let n=this._getOrReturnCtx(t);return $(n,{code:x.invalid_type,expected:P.nan,received:n.parsedType}),N}return{status:"valid",value:t.data}}};Yr.create=e=>new Yr({typeName:S.ZodNaN,...U(e)});var Rv=Symbol("zod_brand"),jn=class extends J{_parse(t){let{ctx:r}=this._processInputParams(t),n=r.data;return this._def.type._parse({data:n,path:r.path,parent:r})}unwrap(){return this._def.type}},In=class e extends J{_parse(t){let{status:r,ctx:n}=this._processInputParams(t);if(n.common.async)return(async()=>{let i=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return i.status==="aborted"?N:i.status==="dirty"?(r.dirty(),sr(i.value)):this._def.out._parseAsync({data:i.value,path:n.path,parent:n})})();{let o=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return o.status==="aborted"?N:o.status==="dirty"?(r.dirty(),{status:"dirty",value:o.value}):this._def.out._parseSync({data:o.value,path:n.path,parent:n})}}static create(t,r){return new e({in:t,out:r,typeName:S.ZodPipeline})}},wr=class extends J{_parse(t){let r=this._def.innerType._parse(t),n=o=>(Ut(o)&&(o.value=Object.freeze(o.value)),o);return Wr(r)?r.then(o=>n(o)):n(r)}unwrap(){return this._def.innerType}};wr.create=(e,t)=>new wr({innerType:e,typeName:S.ZodReadonly,...U(t)});function dp(e,t){let r=typeof e=="function"?e(t):typeof e=="string"?{message:e}:e;return typeof r=="string"?{message:r}:r}function fp(e,t={},r){return e?Jt.create().superRefine((n,o)=>{let i=e(n);if(i instanceof Promise)return i.then(s=>{if(!s){let a=dp(t,n),c=a.fatal??r??!0;o.addIssue({code:"custom",...a,fatal:c})}});if(!i){let s=dp(t,n),a=s.fatal??r??!0;o.addIssue({code:"custom",...s,fatal:a})}}):Jt.create()}var Ov={object:qe.lazycreate},S;(function(e){e.ZodString="ZodString",e.ZodNumber="ZodNumber",e.ZodNaN="ZodNaN",e.ZodBigInt="ZodBigInt",e.ZodBoolean="ZodBoolean",e.ZodDate="ZodDate",e.ZodSymbol="ZodSymbol",e.ZodUndefined="ZodUndefined",e.ZodNull="ZodNull",e.ZodAny="ZodAny",e.ZodUnknown="ZodUnknown",e.ZodNever="ZodNever",e.ZodVoid="ZodVoid",e.ZodArray="ZodArray",e.ZodObject="ZodObject",e.ZodUnion="ZodUnion",e.ZodDiscriminatedUnion="ZodDiscriminatedUnion",e.ZodIntersection="ZodIntersection",e.ZodTuple="ZodTuple",e.ZodRecord="ZodRecord",e.ZodMap="ZodMap",e.ZodSet="ZodSet",e.ZodFunction="ZodFunction",e.ZodLazy="ZodLazy",e.ZodLiteral="ZodLiteral",e.ZodEnum="ZodEnum",e.ZodEffects="ZodEffects",e.ZodNativeEnum="ZodNativeEnum",e.ZodOptional="ZodOptional",e.ZodNullable="ZodNullable",e.ZodDefault="ZodDefault",e.ZodCatch="ZodCatch",e.ZodPromise="ZodPromise",e.ZodBranded="ZodBranded",e.ZodPipeline="ZodPipeline",e.ZodReadonly="ZodReadonly"})(S||(S={}));var Ev=(e,t={message:`Input not instance of ${e.name}`})=>fp(r=>r instanceof e,t),hp=Zt.create,gp=ar.create,jv=Yr.create,Iv=cr.create,yp=dr.create,Cv=ur.create,Av=Hr.create,Mv=lr.create,Nv=pr.create,Dv=Jt.create,Lv=Ot.create,qv=at.create,Uv=Gr.create,Zv=Et.create,Ks=qe.create,Jv=qe.strictCreate,Fv=mr.create,Vv=Go.create,Wv=fr.create,Bv=_t.create,Hv=Ko.create,Gv=Kr.create,Kv=Qr.create,Qv=Qo.create,Yv=hr.create,Xv=gr.create,ew=yr.create,tw=_r.create,rw=Ft.create,nw=Xe.create,ow=Le.create,iw=bt.create,sw=Xe.createWithPreprocess,aw=In.create,cw=()=>hp().optional(),dw=()=>gp().optional(),uw=()=>yp().optional(),lw={string:(e=>Zt.create({...e,coerce:!0})),number:(e=>ar.create({...e,coerce:!0})),boolean:(e=>dr.create({...e,coerce:!0})),bigint:(e=>cr.create({...e,coerce:!0})),date:(e=>ur.create({...e,coerce:!0}))};var pw=N;var fw=Object.freeze({status:"aborted"});function b(e,t,r){function n(a,c){var d;Object.defineProperty(a,"_zod",{value:a._zod??{},enumerable:!1}),(d=a._zod).traits??(d.traits=new Set),a._zod.traits.add(e),t(a,c);for(let u in s.prototype)u in a||Object.defineProperty(a,u,{value:s.prototype[u].bind(a)});a._zod.constr=s,a._zod.def=c}let o=r?.Parent??Object;class i extends o{}Object.defineProperty(i,"name",{value:e});function s(a){var c;let d=r?.Parent?new i:this;n(d,a),(c=d._zod).deferred??(c.deferred=[]);for(let u of d._zod.deferred)u();return d}return Object.defineProperty(s,"init",{value:n}),Object.defineProperty(s,Symbol.hasInstance,{value:a=>r?.Parent&&a instanceof r.Parent?!0:a?._zod?.traits?.has(e)}),Object.defineProperty(s,"name",{value:e}),s}var jt=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},Yo={};function He(e){return e&&Object.assign(Yo,e),Yo}var H={};Ws(H,{BIGINT_FORMAT_RANGES:()=>bp,Class:()=>Ys,NUMBER_FORMAT_RANGES:()=>ia,aborted:()=>xr,allowsEval:()=>ra,assert:()=>bw,assertEqual:()=>hw,assertIs:()=>yw,assertNever:()=>_w,assertNotEqual:()=>gw,assignProp:()=>ta,cached:()=>Mn,captureStackTrace:()=>ei,cleanEnum:()=>jw,cleanRegex:()=>Dn,clone:()=>Ge,createTransparentProxy:()=>$w,defineLazy:()=>se,esc:()=>kr,escapeRegex:()=>Vt,extend:()=>Pw,finalizeIssue:()=>ct,floatSafeRemainder:()=>ea,getElementAtPath:()=>vw,getEnumValues:()=>An,getLengthableOrigin:()=>Ln,getParsedType:()=>Sw,getSizableOrigin:()=>vp,isObject:()=>Xr,isPlainObject:()=>en,issue:()=>sa,joinValues:()=>Xo,jsonStringifyReplacer:()=>Xs,merge:()=>Rw,normalizeParams:()=>D,nullish:()=>Nn,numKeys:()=>xw,omit:()=>Tw,optionalKeys:()=>oa,partial:()=>Ow,pick:()=>zw,prefixIssues:()=>vt,primitiveTypes:()=>_p,promiseAllObject:()=>ww,propertyKeyTypes:()=>na,randomString:()=>kw,required:()=>Ew,stringifyPrimitive:()=>ti,unwrapMessage:()=>Cn});function hw(e){return e}function gw(e){return e}function yw(e){}function _w(e){throw new Error}function bw(e){}function An(e){let t=Object.values(e).filter(n=>typeof n=="number");return Object.entries(e).filter(([n,o])=>t.indexOf(+n)===-1).map(([n,o])=>o)}function Xo(e,t="|"){return e.map(r=>ti(r)).join(t)}function Xs(e,t){return typeof t=="bigint"?t.toString():t}function Mn(e){return{get value(){{let r=e();return Object.defineProperty(this,"value",{value:r}),r}throw new Error("cached value already set")}}}function Nn(e){return e==null}function Dn(e){let t=e.startsWith("^")?1:0,r=e.endsWith("$")?e.length-1:e.length;return e.slice(t,r)}function ea(e,t){let r=(e.toString().split(".")[1]||"").length,n=(t.toString().split(".")[1]||"").length,o=r>n?r:n,i=Number.parseInt(e.toFixed(o).replace(".","")),s=Number.parseInt(t.toFixed(o).replace(".",""));return i%s/10**o}function se(e,t,r){Object.defineProperty(e,t,{get(){{let o=r();return e[t]=o,o}throw new Error("cached value already set")},set(o){Object.defineProperty(e,t,{value:o})},configurable:!0})}function ta(e,t,r){Object.defineProperty(e,t,{value:r,writable:!0,enumerable:!0,configurable:!0})}function vw(e,t){return t?t.reduce((r,n)=>r?.[n],e):e}function ww(e){let t=Object.keys(e),r=t.map(n=>e[n]);return Promise.all(r).then(n=>{let o={};for(let i=0;i<t.length;i++)o[t[i]]=n[i];return o})}function kw(e=10){let t="abcdefghijklmnopqrstuvwxyz",r="";for(let n=0;n<e;n++)r+=t[Math.floor(Math.random()*t.length)];return r}function kr(e){return JSON.stringify(e)}var ei=Error.captureStackTrace?Error.captureStackTrace:(...e)=>{};function Xr(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var ra=Mn(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let e=Function;return new e(""),!0}catch{return!1}});function en(e){if(Xr(e)===!1)return!1;let t=e.constructor;if(t===void 0)return!0;let r=t.prototype;return!(Xr(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}function xw(e){let t=0;for(let r in e)Object.prototype.hasOwnProperty.call(e,r)&&t++;return t}var Sw=e=>{let t=typeof e;switch(t){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(e)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":return Array.isArray(e)?"array":e===null?"null":e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?"promise":typeof Map<"u"&&e instanceof Map?"map":typeof Set<"u"&&e instanceof Set?"set":typeof Date<"u"&&e instanceof Date?"date":typeof File<"u"&&e instanceof File?"file":"object";default:throw new Error(`Unknown data type: ${t}`)}},na=new Set(["string","number","symbol"]),_p=new Set(["string","number","bigint","boolean","symbol","undefined"]);function Vt(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Ge(e,t,r){let n=new e._zod.constr(t??e._zod.def);return(!t||r?.parent)&&(n._zod.parent=e),n}function D(e){let t=e;if(!t)return{};if(typeof t=="string")return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,typeof t.error=="string"?{...t,error:()=>t.error}:t}function $w(e){let t;return new Proxy({},{get(r,n,o){return t??(t=e()),Reflect.get(t,n,o)},set(r,n,o,i){return t??(t=e()),Reflect.set(t,n,o,i)},has(r,n){return t??(t=e()),Reflect.has(t,n)},deleteProperty(r,n){return t??(t=e()),Reflect.deleteProperty(t,n)},ownKeys(r){return t??(t=e()),Reflect.ownKeys(t)},getOwnPropertyDescriptor(r,n){return t??(t=e()),Reflect.getOwnPropertyDescriptor(t,n)},defineProperty(r,n,o){return t??(t=e()),Reflect.defineProperty(t,n,o)}})}function ti(e){return typeof e=="bigint"?e.toString()+"n":typeof e=="string"?`"${e}"`:`${e}`}function oa(e){return Object.keys(e).filter(t=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}var ia={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]},bp={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function zw(e,t){let r={},n=e._zod.def;for(let o in t){if(!(o in n.shape))throw new Error(`Unrecognized key: "${o}"`);t[o]&&(r[o]=n.shape[o])}return Ge(e,{...e._zod.def,shape:r,checks:[]})}function Tw(e,t){let r={...e._zod.def.shape},n=e._zod.def;for(let o in t){if(!(o in n.shape))throw new Error(`Unrecognized key: "${o}"`);t[o]&&delete r[o]}return Ge(e,{...e._zod.def,shape:r,checks:[]})}function Pw(e,t){if(!en(t))throw new Error("Invalid input to extend: expected a plain object");let r={...e._zod.def,get shape(){let n={...e._zod.def.shape,...t};return ta(this,"shape",n),n},checks:[]};return Ge(e,r)}function Rw(e,t){return Ge(e,{...e._zod.def,get shape(){let r={...e._zod.def.shape,...t._zod.def.shape};return ta(this,"shape",r),r},catchall:t._zod.def.catchall,checks:[]})}function Ow(e,t,r){let n=t._zod.def.shape,o={...n};if(r)for(let i in r){if(!(i in n))throw new Error(`Unrecognized key: "${i}"`);r[i]&&(o[i]=e?new e({type:"optional",innerType:n[i]}):n[i])}else for(let i in n)o[i]=e?new e({type:"optional",innerType:n[i]}):n[i];return Ge(t,{...t._zod.def,shape:o,checks:[]})}function Ew(e,t,r){let n=t._zod.def.shape,o={...n};if(r)for(let i in r){if(!(i in o))throw new Error(`Unrecognized key: "${i}"`);r[i]&&(o[i]=new e({type:"nonoptional",innerType:n[i]}))}else for(let i in n)o[i]=new e({type:"nonoptional",innerType:n[i]});return Ge(t,{...t._zod.def,shape:o,checks:[]})}function xr(e,t=0){for(let r=t;r<e.issues.length;r++)if(e.issues[r]?.continue!==!0)return!0;return!1}function vt(e,t){return t.map(r=>{var n;return(n=r).path??(n.path=[]),r.path.unshift(e),r})}function Cn(e){return typeof e=="string"?e:e?.message}function ct(e,t,r){let n={...e,path:e.path??[]};if(!e.message){let o=Cn(e.inst?._zod.def?.error?.(e))??Cn(t?.error?.(e))??Cn(r.customError?.(e))??Cn(r.localeError?.(e))??"Invalid input";n.message=o}return delete n.inst,delete n.continue,t?.reportInput||delete n.input,n}function vp(e){return e instanceof Set?"set":e instanceof Map?"map":e instanceof File?"file":"unknown"}function Ln(e){return Array.isArray(e)?"array":typeof e=="string"?"string":"unknown"}function sa(...e){let[t,r,n]=e;return typeof t=="string"?{message:t,code:"custom",input:r,inst:n}:{...t}}function jw(e){return Object.entries(e).filter(([t,r])=>Number.isNaN(Number.parseInt(t,10))).map(t=>t[1])}var Ys=class{constructor(...t){}};var wp=(e,t)=>{e.name="$ZodError",Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),Object.defineProperty(e,"message",{get(){return JSON.stringify(t,Xs,2)},enumerable:!0}),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},ri=b("$ZodError",wp),qn=b("$ZodError",wp,{Parent:Error});function aa(e,t=r=>r.message){let r={},n=[];for(let o of e.issues)o.path.length>0?(r[o.path[0]]=r[o.path[0]]||[],r[o.path[0]].push(t(o))):n.push(t(o));return{formErrors:n,fieldErrors:r}}function ca(e,t){let r=t||function(i){return i.message},n={_errors:[]},o=i=>{for(let s of i.issues)if(s.code==="invalid_union"&&s.errors.length)s.errors.map(a=>o({issues:a}));else if(s.code==="invalid_key")o({issues:s.issues});else if(s.code==="invalid_element")o({issues:s.issues});else if(s.path.length===0)n._errors.push(r(s));else{let a=n,c=0;for(;c<s.path.length;){let d=s.path[c];c===s.path.length-1?(a[d]=a[d]||{_errors:[]},a[d]._errors.push(r(s))):a[d]=a[d]||{_errors:[]},a=a[d],c++}}};return o(e),n}var da=e=>(t,r,n,o)=>{let i=n?Object.assign(n,{async:!1}):{async:!1},s=t._zod.run({value:r,issues:[]},i);if(s instanceof Promise)throw new jt;if(s.issues.length){let a=new(o?.Err??e)(s.issues.map(c=>ct(c,i,He())));throw ei(a,o?.callee),a}return s.value},ua=da(qn),la=e=>async(t,r,n,o)=>{let i=n?Object.assign(n,{async:!0}):{async:!0},s=t._zod.run({value:r,issues:[]},i);if(s instanceof Promise&&(s=await s),s.issues.length){let a=new(o?.Err??e)(s.issues.map(c=>ct(c,i,He())));throw ei(a,o?.callee),a}return s.value},pa=la(qn),ma=e=>(t,r,n)=>{let o=n?{...n,async:!1}:{async:!1},i=t._zod.run({value:r,issues:[]},o);if(i instanceof Promise)throw new jt;return i.issues.length?{success:!1,error:new(e??ri)(i.issues.map(s=>ct(s,o,He())))}:{success:!0,data:i.value}},Sr=ma(qn),fa=e=>async(t,r,n)=>{let o=n?Object.assign(n,{async:!0}):{async:!0},i=t._zod.run({value:r,issues:[]},o);return i instanceof Promise&&(i=await i),i.issues.length?{success:!1,error:new e(i.issues.map(s=>ct(s,o,He())))}:{success:!0,data:i.value}},$r=fa(qn);var kp=/^[cC][^\s-]{8,}$/,xp=/^[0-9a-z]+$/,Sp=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,$p=/^[0-9a-vA-V]{20}$/,zp=/^[A-Za-z0-9]{27}$/,Tp=/^[a-zA-Z0-9_-]{21}$/,Pp=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;var Rp=/^([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})$/,ha=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)$/;var Op=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;var Cw="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function Ep(){return new RegExp(Cw,"u")}var jp=/^(?:(?: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])$/,Ip=/^(([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})$/,Cp=/^((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])$/,Ap=/^(([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])$/,Mp=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,ga=/^[A-Za-z0-9_-]*$/,Np=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/;var Dp=/^\+(?:[0-9]){6,14}[0-9]$/,Lp="(?:(?:\\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])))",qp=new RegExp(`^${Lp}$`);function Up(e){let t="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof e.precision=="number"?e.precision===-1?`${t}`:e.precision===0?`${t}:[0-5]\\d`:`${t}:[0-5]\\d\\.\\d{${e.precision}}`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}function Zp(e){return new RegExp(`^${Up(e)}$`)}function Jp(e){let t=Up({precision:e.precision}),r=["Z"];e.local&&r.push(""),e.offset&&r.push("([+-]\\d{2}:\\d{2})");let n=`${t}(?:${r.join("|")})`;return new RegExp(`^${Lp}T(?:${n})$`)}var Fp=e=>{let t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)};var Vp=/^\d+$/,Wp=/^-?\d+(?:\.\d+)?/i,Bp=/true|false/i,Hp=/null/i;var Gp=/^[^A-Z]*$/,Kp=/^[^a-z]*$/;var Se=b("$ZodCheck",(e,t)=>{var r;e._zod??(e._zod={}),e._zod.def=t,(r=e._zod).onattach??(r.onattach=[])}),Qp={number:"number",bigint:"bigint",object:"date"},ya=b("$ZodCheckLessThan",(e,t)=>{Se.init(e,t);let r=Qp[typeof t.value];e._zod.onattach.push(n=>{let o=n._zod.bag,i=(t.inclusive?o.maximum:o.exclusiveMaximum)??Number.POSITIVE_INFINITY;t.value<i&&(t.inclusive?o.maximum=t.value:o.exclusiveMaximum=t.value)}),e._zod.check=n=>{(t.inclusive?n.value<=t.value:n.value<t.value)||n.issues.push({origin:r,code:"too_big",maximum:t.value,input:n.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),_a=b("$ZodCheckGreaterThan",(e,t)=>{Se.init(e,t);let r=Qp[typeof t.value];e._zod.onattach.push(n=>{let o=n._zod.bag,i=(t.inclusive?o.minimum:o.exclusiveMinimum)??Number.NEGATIVE_INFINITY;t.value>i&&(t.inclusive?o.minimum=t.value:o.exclusiveMinimum=t.value)}),e._zod.check=n=>{(t.inclusive?n.value>=t.value:n.value>t.value)||n.issues.push({origin:r,code:"too_small",minimum:t.value,input:n.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),Yp=b("$ZodCheckMultipleOf",(e,t)=>{Se.init(e,t),e._zod.onattach.push(r=>{var n;(n=r._zod.bag).multipleOf??(n.multipleOf=t.value)}),e._zod.check=r=>{if(typeof r.value!=typeof t.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof r.value=="bigint"?r.value%t.value===BigInt(0):ea(r.value,t.value)===0)||r.issues.push({origin:typeof r.value,code:"not_multiple_of",divisor:t.value,input:r.value,inst:e,continue:!t.abort})}}),Xp=b("$ZodCheckNumberFormat",(e,t)=>{Se.init(e,t),t.format=t.format||"float64";let r=t.format?.includes("int"),n=r?"int":"number",[o,i]=ia[t.format];e._zod.onattach.push(s=>{let a=s._zod.bag;a.format=t.format,a.minimum=o,a.maximum=i,r&&(a.pattern=Vp)}),e._zod.check=s=>{let a=s.value;if(r){if(!Number.isInteger(a)){s.issues.push({expected:n,format:t.format,code:"invalid_type",input:a,inst:e});return}if(!Number.isSafeInteger(a)){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:n,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:n,continue:!t.abort});return}}a<o&&s.issues.push({origin:"number",input:a,code:"too_small",minimum:o,inclusive:!0,inst:e,continue:!t.abort}),a>i&&s.issues.push({origin:"number",input:a,code:"too_big",maximum:i,inst:e})}});var em=b("$ZodCheckMaxLength",(e,t)=>{var r;Se.init(e,t),(r=e._zod.def).when??(r.when=n=>{let o=n.value;return!Nn(o)&&o.length!==void 0}),e._zod.onattach.push(n=>{let o=n._zod.bag.maximum??Number.POSITIVE_INFINITY;t.maximum<o&&(n._zod.bag.maximum=t.maximum)}),e._zod.check=n=>{let o=n.value;if(o.length<=t.maximum)return;let s=Ln(o);n.issues.push({origin:s,code:"too_big",maximum:t.maximum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),tm=b("$ZodCheckMinLength",(e,t)=>{var r;Se.init(e,t),(r=e._zod.def).when??(r.when=n=>{let o=n.value;return!Nn(o)&&o.length!==void 0}),e._zod.onattach.push(n=>{let o=n._zod.bag.minimum??Number.NEGATIVE_INFINITY;t.minimum>o&&(n._zod.bag.minimum=t.minimum)}),e._zod.check=n=>{let o=n.value;if(o.length>=t.minimum)return;let s=Ln(o);n.issues.push({origin:s,code:"too_small",minimum:t.minimum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),rm=b("$ZodCheckLengthEquals",(e,t)=>{var r;Se.init(e,t),(r=e._zod.def).when??(r.when=n=>{let o=n.value;return!Nn(o)&&o.length!==void 0}),e._zod.onattach.push(n=>{let o=n._zod.bag;o.minimum=t.length,o.maximum=t.length,o.length=t.length}),e._zod.check=n=>{let o=n.value,i=o.length;if(i===t.length)return;let s=Ln(o),a=i>t.length;n.issues.push({origin:s,...a?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:n.value,inst:e,continue:!t.abort})}}),Un=b("$ZodCheckStringFormat",(e,t)=>{var r,n;Se.init(e,t),e._zod.onattach.push(o=>{let i=o._zod.bag;i.format=t.format,t.pattern&&(i.patterns??(i.patterns=new Set),i.patterns.add(t.pattern))}),t.pattern?(r=e._zod).check??(r.check=o=>{t.pattern.lastIndex=0,!t.pattern.test(o.value)&&o.issues.push({origin:"string",code:"invalid_format",format:t.format,input:o.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(n=e._zod).check??(n.check=()=>{})}),nm=b("$ZodCheckRegex",(e,t)=>{Un.init(e,t),e._zod.check=r=>{t.pattern.lastIndex=0,!t.pattern.test(r.value)&&r.issues.push({origin:"string",code:"invalid_format",format:"regex",input:r.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),om=b("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=Gp),Un.init(e,t)}),im=b("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=Kp),Un.init(e,t)}),sm=b("$ZodCheckIncludes",(e,t)=>{Se.init(e,t);let r=Vt(t.includes),n=new RegExp(typeof t.position=="number"?`^.{${t.position}}${r}`:r);t.pattern=n,e._zod.onattach.push(o=>{let i=o._zod.bag;i.patterns??(i.patterns=new Set),i.patterns.add(n)}),e._zod.check=o=>{o.value.includes(t.includes,t.position)||o.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:o.value,inst:e,continue:!t.abort})}}),am=b("$ZodCheckStartsWith",(e,t)=>{Se.init(e,t);let r=new RegExp(`^${Vt(t.prefix)}.*`);t.pattern??(t.pattern=r),e._zod.onattach.push(n=>{let o=n._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(r)}),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})}}),cm=b("$ZodCheckEndsWith",(e,t)=>{Se.init(e,t);let r=new RegExp(`.*${Vt(t.suffix)}$`);t.pattern??(t.pattern=r),e._zod.onattach.push(n=>{let o=n._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(r)}),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})}});var dm=b("$ZodCheckOverwrite",(e,t)=>{Se.init(e,t),e._zod.check=r=>{r.value=t.tx(r.value)}});var oi=class{constructor(t=[]){this.content=[],this.indent=0,this&&(this.args=t)}indented(t){this.indent+=1,t(this),this.indent-=1}write(t){if(typeof t=="function"){t(this,{execution:"sync"}),t(this,{execution:"async"});return}let n=t.split(`
11
- `).filter(s=>s),o=Math.min(...n.map(s=>s.length-s.trimStart().length)),i=n.map(s=>s.slice(o)).map(s=>" ".repeat(this.indent*2)+s);for(let s of i)this.content.push(s)}compile(){let t=Function,r=this?.args,o=[...(this?.content??[""]).map(i=>` ${i}`)];return new t(...r,o.join(`
12
- `))}};var lm={major:4,minor:0,patch:0};var ne=b("$ZodType",(e,t)=>{var r;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=lm;let n=[...e._zod.def.checks??[]];e._zod.traits.has("$ZodCheck")&&n.unshift(e);for(let o of n)for(let i of o._zod.onattach)i(e);if(n.length===0)(r=e._zod).deferred??(r.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{let o=(i,s,a)=>{let c=xr(i),d;for(let u of s){if(u._zod.def.when){if(!u._zod.def.when(i))continue}else if(c)continue;let p=i.issues.length,m=u._zod.check(i);if(m instanceof Promise&&a?.async===!1)throw new jt;if(d||m instanceof Promise)d=(d??Promise.resolve()).then(async()=>{await m,i.issues.length!==p&&(c||(c=xr(i,p)))});else{if(i.issues.length===p)continue;c||(c=xr(i,p))}}return d?d.then(()=>i):i};e._zod.run=(i,s)=>{let a=e._zod.parse(i,s);if(a instanceof Promise){if(s.async===!1)throw new jt;return a.then(c=>o(c,n,s))}return o(a,n,s)}}e["~standard"]={validate:o=>{try{let i=Sr(e,o);return i.success?{value:i.data}:{issues:i.error?.issues}}catch{return $r(e,o).then(s=>s.success?{value:s.data}:{issues:s.error?.issues})}},vendor:"zod",version:1}}),Zn=b("$ZodString",(e,t)=>{ne.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??Fp(e._zod.bag),e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=String(r.value)}catch{}return typeof r.value=="string"||r.issues.push({expected:"string",code:"invalid_type",input:r.value,inst:e}),r}}),ae=b("$ZodStringFormat",(e,t)=>{Un.init(e,t),Zn.init(e,t)}),va=b("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=Rp),ae.init(e,t)}),wa=b("$ZodUUID",(e,t)=>{if(t.version){let n={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(n===void 0)throw new Error(`Invalid UUID version: "${t.version}"`);t.pattern??(t.pattern=ha(n))}else t.pattern??(t.pattern=ha());ae.init(e,t)}),ka=b("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=Op),ae.init(e,t)}),xa=b("$ZodURL",(e,t)=>{ae.init(e,t),e._zod.check=r=>{try{let n=r.value,o=new URL(n),i=o.href;t.hostname&&(t.hostname.lastIndex=0,t.hostname.test(o.hostname)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:Np.source,input:r.value,inst:e,continue:!t.abort})),t.protocol&&(t.protocol.lastIndex=0,t.protocol.test(o.protocol.endsWith(":")?o.protocol.slice(0,-1):o.protocol)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:t.protocol.source,input:r.value,inst:e,continue:!t.abort})),!n.endsWith("/")&&i.endsWith("/")?r.value=i.slice(0,-1):r.value=i;return}catch{r.issues.push({code:"invalid_format",format:"url",input:r.value,inst:e,continue:!t.abort})}}}),Sa=b("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=Ep()),ae.init(e,t)}),$a=b("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=Tp),ae.init(e,t)}),za=b("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=kp),ae.init(e,t)}),Ta=b("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=xp),ae.init(e,t)}),Pa=b("$ZodULID",(e,t)=>{t.pattern??(t.pattern=Sp),ae.init(e,t)}),Ra=b("$ZodXID",(e,t)=>{t.pattern??(t.pattern=$p),ae.init(e,t)}),Oa=b("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=zp),ae.init(e,t)}),wm=b("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=Jp(t)),ae.init(e,t)}),km=b("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=qp),ae.init(e,t)}),xm=b("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=Zp(t)),ae.init(e,t)}),Sm=b("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=Pp),ae.init(e,t)}),Ea=b("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=jp),ae.init(e,t),e._zod.onattach.push(r=>{let n=r._zod.bag;n.format="ipv4"})}),ja=b("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=Ip),ae.init(e,t),e._zod.onattach.push(r=>{let n=r._zod.bag;n.format="ipv6"}),e._zod.check=r=>{try{new URL(`http://[${r.value}]`)}catch{r.issues.push({code:"invalid_format",format:"ipv6",input:r.value,inst:e,continue:!t.abort})}}}),Ia=b("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=Cp),ae.init(e,t)}),Ca=b("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=Ap),ae.init(e,t),e._zod.check=r=>{let[n,o]=r.value.split("/");try{if(!o)throw new Error;let i=Number(o);if(`${i}`!==o)throw new Error;if(i<0||i>128)throw new Error;new URL(`http://[${n}]`)}catch{r.issues.push({code:"invalid_format",format:"cidrv6",input:r.value,inst:e,continue:!t.abort})}}});function $m(e){if(e==="")return!0;if(e.length%4!==0)return!1;try{return atob(e),!0}catch{return!1}}var Aa=b("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=Mp),ae.init(e,t),e._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64"}),e._zod.check=r=>{$m(r.value)||r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:e,continue:!t.abort})}});function Aw(e){if(!ga.test(e))return!1;let t=e.replace(/[-_]/g,n=>n==="-"?"+":"/"),r=t.padEnd(Math.ceil(t.length/4)*4,"=");return $m(r)}var Ma=b("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=ga),ae.init(e,t),e._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64url"}),e._zod.check=r=>{Aw(r.value)||r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:e,continue:!t.abort})}}),Na=b("$ZodE164",(e,t)=>{t.pattern??(t.pattern=Dp),ae.init(e,t)});function Mw(e,t=null){try{let r=e.split(".");if(r.length!==3)return!1;let[n]=r;if(!n)return!1;let o=JSON.parse(atob(n));return!("typ"in o&&o?.typ!=="JWT"||!o.alg||t&&(!("alg"in o)||o.alg!==t))}catch{return!1}}var Da=b("$ZodJWT",(e,t)=>{ae.init(e,t),e._zod.check=r=>{Mw(r.value,t.alg)||r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:e,continue:!t.abort})}});var si=b("$ZodNumber",(e,t)=>{ne.init(e,t),e._zod.pattern=e._zod.bag.pattern??Wp,e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=Number(r.value)}catch{}let o=r.value;if(typeof o=="number"&&!Number.isNaN(o)&&Number.isFinite(o))return r;let i=typeof o=="number"?Number.isNaN(o)?"NaN":Number.isFinite(o)?void 0:"Infinity":void 0;return r.issues.push({expected:"number",code:"invalid_type",input:o,inst:e,...i?{received:i}:{}}),r}}),La=b("$ZodNumber",(e,t)=>{Xp.init(e,t),si.init(e,t)}),qa=b("$ZodBoolean",(e,t)=>{ne.init(e,t),e._zod.pattern=Bp,e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=!!r.value}catch{}let o=r.value;return typeof o=="boolean"||r.issues.push({expected:"boolean",code:"invalid_type",input:o,inst:e}),r}});var Ua=b("$ZodNull",(e,t)=>{ne.init(e,t),e._zod.pattern=Hp,e._zod.values=new Set([null]),e._zod.parse=(r,n)=>{let o=r.value;return o===null||r.issues.push({expected:"null",code:"invalid_type",input:o,inst:e}),r}});var Za=b("$ZodUnknown",(e,t)=>{ne.init(e,t),e._zod.parse=r=>r}),Ja=b("$ZodNever",(e,t)=>{ne.init(e,t),e._zod.parse=(r,n)=>(r.issues.push({expected:"never",code:"invalid_type",input:r.value,inst:e}),r)});function pm(e,t,r){e.issues.length&&t.issues.push(...vt(r,e.issues)),t.value[r]=e.value}var Fa=b("$ZodArray",(e,t)=>{ne.init(e,t),e._zod.parse=(r,n)=>{let o=r.value;if(!Array.isArray(o))return r.issues.push({expected:"array",code:"invalid_type",input:o,inst:e}),r;r.value=Array(o.length);let i=[];for(let s=0;s<o.length;s++){let a=o[s],c=t.element._zod.run({value:a,issues:[]},n);c instanceof Promise?i.push(c.then(d=>pm(d,r,s))):pm(c,r,s)}return i.length?Promise.all(i).then(()=>r):r}});function ii(e,t,r){e.issues.length&&t.issues.push(...vt(r,e.issues)),t.value[r]=e.value}function mm(e,t,r,n){e.issues.length?n[r]===void 0?r in n?t.value[r]=void 0:t.value[r]=e.value:t.issues.push(...vt(r,e.issues)):e.value===void 0?r in n&&(t.value[r]=void 0):t.value[r]=e.value}var ai=b("$ZodObject",(e,t)=>{ne.init(e,t);let r=Mn(()=>{let p=Object.keys(t.shape);for(let f of p)if(!(t.shape[f]instanceof ne))throw new Error(`Invalid element at key "${f}": expected a Zod schema`);let m=oa(t.shape);return{shape:t.shape,keys:p,keySet:new Set(p),numKeys:p.length,optionalKeys:new Set(m)}});se(e._zod,"propValues",()=>{let p=t.shape,m={};for(let f in p){let h=p[f]._zod;if(h.values){m[f]??(m[f]=new Set);for(let g of h.values)m[f].add(g)}}return m});let n=p=>{let m=new oi(["shape","payload","ctx"]),f=r.value,h=w=>{let k=kr(w);return`shape[${k}]._zod.run({ value: input[${k}], issues: [] }, ctx)`};m.write("const input = payload.value;");let g=Object.create(null),y=0;for(let w of f.keys)g[w]=`key_${y++}`;m.write("const newResult = {}");for(let w of f.keys)if(f.optionalKeys.has(w)){let k=g[w];m.write(`const ${k} = ${h(w)};`);let O=kr(w);m.write(`
13
- if (${k}.issues.length) {
14
- if (input[${O}] === undefined) {
15
- if (${O} in input) {
16
- newResult[${O}] = undefined;
17
- }
18
- } else {
19
- payload.issues = payload.issues.concat(
20
- ${k}.issues.map((iss) => ({
21
- ...iss,
22
- path: iss.path ? [${O}, ...iss.path] : [${O}],
23
- }))
24
- );
25
- }
26
- } else if (${k}.value === undefined) {
27
- if (${O} in input) newResult[${O}] = undefined;
28
- } else {
29
- newResult[${O}] = ${k}.value;
30
- }
31
- `)}else{let k=g[w];m.write(`const ${k} = ${h(w)};`),m.write(`
32
- if (${k}.issues.length) payload.issues = payload.issues.concat(${k}.issues.map(iss => ({
33
- ...iss,
34
- path: iss.path ? [${kr(w)}, ...iss.path] : [${kr(w)}]
35
- })));`),m.write(`newResult[${kr(w)}] = ${k}.value`)}m.write("payload.value = newResult;"),m.write("return payload;");let v=m.compile();return(w,k)=>v(p,w,k)},o,i=Xr,s=!Yo.jitless,c=s&&ra.value,d=t.catchall,u;e._zod.parse=(p,m)=>{u??(u=r.value);let f=p.value;if(!i(f))return p.issues.push({expected:"object",code:"invalid_type",input:f,inst:e}),p;let h=[];if(s&&c&&m?.async===!1&&m.jitless!==!0)o||(o=n(t.shape)),p=o(p,m);else{p.value={};let k=u.shape;for(let O of u.keys){let M=k[O],Ie=M._zod.run({value:f[O],issues:[]},m),Qe=M._zod.optin==="optional"&&M._zod.optout==="optional";Ie instanceof Promise?h.push(Ie.then(Fr=>Qe?mm(Fr,p,O,f):ii(Fr,p,O))):Qe?mm(Ie,p,O,f):ii(Ie,p,O)}}if(!d)return h.length?Promise.all(h).then(()=>p):p;let g=[],y=u.keySet,v=d._zod,w=v.def.type;for(let k of Object.keys(f)){if(y.has(k))continue;if(w==="never"){g.push(k);continue}let O=v.run({value:f[k],issues:[]},m);O instanceof Promise?h.push(O.then(M=>ii(M,p,k))):ii(O,p,k)}return g.length&&p.issues.push({code:"unrecognized_keys",keys:g,input:f,inst:e}),h.length?Promise.all(h).then(()=>p):p}});function fm(e,t,r,n){for(let o of e)if(o.issues.length===0)return t.value=o.value,t;return t.issues.push({code:"invalid_union",input:t.value,inst:r,errors:e.map(o=>o.issues.map(i=>ct(i,n,He())))}),t}var ci=b("$ZodUnion",(e,t)=>{ne.init(e,t),se(e._zod,"optin",()=>t.options.some(r=>r._zod.optin==="optional")?"optional":void 0),se(e._zod,"optout",()=>t.options.some(r=>r._zod.optout==="optional")?"optional":void 0),se(e._zod,"values",()=>{if(t.options.every(r=>r._zod.values))return new Set(t.options.flatMap(r=>Array.from(r._zod.values)))}),se(e._zod,"pattern",()=>{if(t.options.every(r=>r._zod.pattern)){let r=t.options.map(n=>n._zod.pattern);return new RegExp(`^(${r.map(n=>Dn(n.source)).join("|")})$`)}}),e._zod.parse=(r,n)=>{let o=!1,i=[];for(let s of t.options){let a=s._zod.run({value:r.value,issues:[]},n);if(a instanceof Promise)i.push(a),o=!0;else{if(a.issues.length===0)return a;i.push(a)}}return o?Promise.all(i).then(s=>fm(s,r,e,n)):fm(i,r,e,n)}}),Va=b("$ZodDiscriminatedUnion",(e,t)=>{ci.init(e,t);let r=e._zod.parse;se(e._zod,"propValues",()=>{let o={};for(let i of t.options){let s=i._zod.propValues;if(!s||Object.keys(s).length===0)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(i)}"`);for(let[a,c]of Object.entries(s)){o[a]||(o[a]=new Set);for(let d of c)o[a].add(d)}}return o});let n=Mn(()=>{let o=t.options,i=new Map;for(let s of o){let a=s._zod.propValues[t.discriminator];if(!a||a.size===0)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(s)}"`);for(let c of a){if(i.has(c))throw new Error(`Duplicate discriminator value "${String(c)}"`);i.set(c,s)}}return i});e._zod.parse=(o,i)=>{let s=o.value;if(!Xr(s))return o.issues.push({code:"invalid_type",expected:"object",input:s,inst:e}),o;let a=n.value.get(s?.[t.discriminator]);return a?a._zod.run(o,i):t.unionFallback?r(o,i):(o.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",input:s,path:[t.discriminator],inst:e}),o)}}),Wa=b("$ZodIntersection",(e,t)=>{ne.init(e,t),e._zod.parse=(r,n)=>{let o=r.value,i=t.left._zod.run({value:o,issues:[]},n),s=t.right._zod.run({value:o,issues:[]},n);return i instanceof Promise||s instanceof Promise?Promise.all([i,s]).then(([c,d])=>hm(r,c,d)):hm(r,i,s)}});function ba(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(en(e)&&en(t)){let r=Object.keys(t),n=Object.keys(e).filter(i=>r.indexOf(i)!==-1),o={...e,...t};for(let i of n){let s=ba(e[i],t[i]);if(!s.valid)return{valid:!1,mergeErrorPath:[i,...s.mergeErrorPath]};o[i]=s.data}return{valid:!0,data:o}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};let r=[];for(let n=0;n<e.length;n++){let o=e[n],i=t[n],s=ba(o,i);if(!s.valid)return{valid:!1,mergeErrorPath:[n,...s.mergeErrorPath]};r.push(s.data)}return{valid:!0,data:r}}return{valid:!1,mergeErrorPath:[]}}function hm(e,t,r){if(t.issues.length&&e.issues.push(...t.issues),r.issues.length&&e.issues.push(...r.issues),xr(e))return e;let n=ba(t.value,r.value);if(!n.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(n.mergeErrorPath)}`);return e.value=n.data,e}var Ba=b("$ZodRecord",(e,t)=>{ne.init(e,t),e._zod.parse=(r,n)=>{let o=r.value;if(!en(o))return r.issues.push({expected:"record",code:"invalid_type",input:o,inst:e}),r;let i=[];if(t.keyType._zod.values){let s=t.keyType._zod.values;r.value={};for(let c of s)if(typeof c=="string"||typeof c=="number"||typeof c=="symbol"){let d=t.valueType._zod.run({value:o[c],issues:[]},n);d instanceof Promise?i.push(d.then(u=>{u.issues.length&&r.issues.push(...vt(c,u.issues)),r.value[c]=u.value})):(d.issues.length&&r.issues.push(...vt(c,d.issues)),r.value[c]=d.value)}let a;for(let c in o)s.has(c)||(a=a??[],a.push(c));a&&a.length>0&&r.issues.push({code:"unrecognized_keys",input:o,inst:e,keys:a})}else{r.value={};for(let s of Reflect.ownKeys(o)){if(s==="__proto__")continue;let a=t.keyType._zod.run({value:s,issues:[]},n);if(a instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(a.issues.length){r.issues.push({origin:"record",code:"invalid_key",issues:a.issues.map(d=>ct(d,n,He())),input:s,path:[s],inst:e}),r.value[a.value]=a.value;continue}let c=t.valueType._zod.run({value:o[s],issues:[]},n);c instanceof Promise?i.push(c.then(d=>{d.issues.length&&r.issues.push(...vt(s,d.issues)),r.value[a.value]=d.value})):(c.issues.length&&r.issues.push(...vt(s,c.issues)),r.value[a.value]=c.value)}}return i.length?Promise.all(i).then(()=>r):r}});var Ha=b("$ZodEnum",(e,t)=>{ne.init(e,t);let r=An(t.entries);e._zod.values=new Set(r),e._zod.pattern=new RegExp(`^(${r.filter(n=>na.has(typeof n)).map(n=>typeof n=="string"?Vt(n):n.toString()).join("|")})$`),e._zod.parse=(n,o)=>{let i=n.value;return e._zod.values.has(i)||n.issues.push({code:"invalid_value",values:r,input:i,inst:e}),n}}),Ga=b("$ZodLiteral",(e,t)=>{ne.init(e,t),e._zod.values=new Set(t.values),e._zod.pattern=new RegExp(`^(${t.values.map(r=>typeof r=="string"?Vt(r):r?r.toString():String(r)).join("|")})$`),e._zod.parse=(r,n)=>{let o=r.value;return e._zod.values.has(o)||r.issues.push({code:"invalid_value",values:t.values,input:o,inst:e}),r}});var Ka=b("$ZodTransform",(e,t)=>{ne.init(e,t),e._zod.parse=(r,n)=>{let o=t.transform(r.value,r);if(n.async)return(o instanceof Promise?o:Promise.resolve(o)).then(s=>(r.value=s,r));if(o instanceof Promise)throw new jt;return r.value=o,r}}),Qa=b("$ZodOptional",(e,t)=>{ne.init(e,t),e._zod.optin="optional",e._zod.optout="optional",se(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),se(e._zod,"pattern",()=>{let r=t.innerType._zod.pattern;return r?new RegExp(`^(${Dn(r.source)})?$`):void 0}),e._zod.parse=(r,n)=>t.innerType._zod.optin==="optional"?t.innerType._zod.run(r,n):r.value===void 0?r:t.innerType._zod.run(r,n)}),Ya=b("$ZodNullable",(e,t)=>{ne.init(e,t),se(e._zod,"optin",()=>t.innerType._zod.optin),se(e._zod,"optout",()=>t.innerType._zod.optout),se(e._zod,"pattern",()=>{let r=t.innerType._zod.pattern;return r?new RegExp(`^(${Dn(r.source)}|null)$`):void 0}),se(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,null]):void 0),e._zod.parse=(r,n)=>r.value===null?r:t.innerType._zod.run(r,n)}),Xa=b("$ZodDefault",(e,t)=>{ne.init(e,t),e._zod.optin="optional",se(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(r,n)=>{if(r.value===void 0)return r.value=t.defaultValue,r;let o=t.innerType._zod.run(r,n);return o instanceof Promise?o.then(i=>gm(i,t)):gm(o,t)}});function gm(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}var ec=b("$ZodPrefault",(e,t)=>{ne.init(e,t),e._zod.optin="optional",se(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(r,n)=>(r.value===void 0&&(r.value=t.defaultValue),t.innerType._zod.run(r,n))}),tc=b("$ZodNonOptional",(e,t)=>{ne.init(e,t),se(e._zod,"values",()=>{let r=t.innerType._zod.values;return r?new Set([...r].filter(n=>n!==void 0)):void 0}),e._zod.parse=(r,n)=>{let o=t.innerType._zod.run(r,n);return o instanceof Promise?o.then(i=>ym(i,e)):ym(o,e)}});function ym(e,t){return!e.issues.length&&e.value===void 0&&e.issues.push({code:"invalid_type",expected:"nonoptional",input:e.value,inst:t}),e}var rc=b("$ZodCatch",(e,t)=>{ne.init(e,t),e._zod.optin="optional",se(e._zod,"optout",()=>t.innerType._zod.optout),se(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(r,n)=>{let o=t.innerType._zod.run(r,n);return o instanceof Promise?o.then(i=>(r.value=i.value,i.issues.length&&(r.value=t.catchValue({...r,error:{issues:i.issues.map(s=>ct(s,n,He()))},input:r.value}),r.issues=[]),r)):(r.value=o.value,o.issues.length&&(r.value=t.catchValue({...r,error:{issues:o.issues.map(i=>ct(i,n,He()))},input:r.value}),r.issues=[]),r)}});var nc=b("$ZodPipe",(e,t)=>{ne.init(e,t),se(e._zod,"values",()=>t.in._zod.values),se(e._zod,"optin",()=>t.in._zod.optin),se(e._zod,"optout",()=>t.out._zod.optout),e._zod.parse=(r,n)=>{let o=t.in._zod.run(r,n);return o instanceof Promise?o.then(i=>_m(i,t,n)):_m(o,t,n)}});function _m(e,t,r){return xr(e)?e:t.out._zod.run({value:e.value,issues:e.issues},r)}var oc=b("$ZodReadonly",(e,t)=>{ne.init(e,t),se(e._zod,"propValues",()=>t.innerType._zod.propValues),se(e._zod,"values",()=>t.innerType._zod.values),se(e._zod,"optin",()=>t.innerType._zod.optin),se(e._zod,"optout",()=>t.innerType._zod.optout),e._zod.parse=(r,n)=>{let o=t.innerType._zod.run(r,n);return o instanceof Promise?o.then(bm):bm(o)}});function bm(e){return e.value=Object.freeze(e.value),e}var ic=b("$ZodCustom",(e,t)=>{Se.init(e,t),ne.init(e,t),e._zod.parse=(r,n)=>r,e._zod.check=r=>{let n=r.value,o=t.fn(n);if(o instanceof Promise)return o.then(i=>vm(i,r,n,e));vm(o,r,n,e)}});function vm(e,t,r,n){if(!e){let o={code:"custom",input:r,inst:n,path:[...n._zod.def.path??[]],continue:!n._zod.def.abort};n._zod.def.params&&(o.params=n._zod.def.params),t.issues.push(sa(o))}}var Nw=e=>{let t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"number";case"object":{if(Array.isArray(e))return"array";if(e===null)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}}return t},Dw=()=>{let e={string:{unit:"characters",verb:"to have"},file:{unit:"bytes",verb:"to have"},array:{unit:"items",verb:"to have"},set:{unit:"items",verb:"to have"}};function t(n){return e[n]??null}let r={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",jwt:"JWT",template_literal:"input"};return n=>{switch(n.code){case"invalid_type":return`Invalid input: expected ${n.expected}, received ${Nw(n.input)}`;case"invalid_value":return n.values.length===1?`Invalid input: expected ${ti(n.values[0])}`:`Invalid option: expected one of ${Xo(n.values,"|")}`;case"too_big":{let o=n.inclusive?"<=":"<",i=t(n.origin);return i?`Too big: expected ${n.origin??"value"} to have ${o}${n.maximum.toString()} ${i.unit??"elements"}`:`Too big: expected ${n.origin??"value"} to be ${o}${n.maximum.toString()}`}case"too_small":{let o=n.inclusive?">=":">",i=t(n.origin);return i?`Too small: expected ${n.origin} to have ${o}${n.minimum.toString()} ${i.unit}`:`Too small: expected ${n.origin} to be ${o}${n.minimum.toString()}`}case"invalid_format":{let o=n;return o.format==="starts_with"?`Invalid string: must start with "${o.prefix}"`:o.format==="ends_with"?`Invalid string: must end with "${o.suffix}"`:o.format==="includes"?`Invalid string: must include "${o.includes}"`:o.format==="regex"?`Invalid string: must match pattern ${o.pattern}`:`Invalid ${r[o.format]??n.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${n.divisor}`;case"unrecognized_keys":return`Unrecognized key${n.keys.length>1?"s":""}: ${Xo(n.keys,", ")}`;case"invalid_key":return`Invalid key in ${n.origin}`;case"invalid_union":return"Invalid input";case"invalid_element":return`Invalid value in ${n.origin}`;default:return"Invalid input"}}};function zm(){return{localeError:Dw()}}var Jn=class{constructor(){this._map=new Map,this._idmap=new Map}add(t,...r){let n=r[0];if(this._map.set(t,n),n&&typeof n=="object"&&"id"in n){if(this._idmap.has(n.id))throw new Error(`ID ${n.id} already exists in the registry`);this._idmap.set(n.id,t)}return this}clear(){return this._map=new Map,this._idmap=new Map,this}remove(t){let r=this._map.get(t);return r&&typeof r=="object"&&"id"in r&&this._idmap.delete(r.id),this._map.delete(t),this}get(t){let r=t._zod.parent;if(r){let n={...this.get(r)??{}};return delete n.id,{...n,...this._map.get(t)}}return this._map.get(t)}has(t){return this._map.has(t)}};function Tm(){return new Jn}var Wt=Tm();function sc(e,t){return new e({type:"string",...D(t)})}function ac(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...D(t)})}function di(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...D(t)})}function cc(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...D(t)})}function dc(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...D(t)})}function uc(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...D(t)})}function lc(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...D(t)})}function pc(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...D(t)})}function mc(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...D(t)})}function fc(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...D(t)})}function hc(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...D(t)})}function gc(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...D(t)})}function yc(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...D(t)})}function _c(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...D(t)})}function bc(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...D(t)})}function vc(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...D(t)})}function wc(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...D(t)})}function kc(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...D(t)})}function xc(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...D(t)})}function Sc(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...D(t)})}function $c(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...D(t)})}function zc(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...D(t)})}function Tc(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...D(t)})}function Pm(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...D(t)})}function Rm(e,t){return new e({type:"string",format:"date",check:"string_format",...D(t)})}function Om(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...D(t)})}function Em(e,t){return new e({type:"string",format:"duration",check:"string_format",...D(t)})}function Pc(e,t){return new e({type:"number",checks:[],...D(t)})}function Rc(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...D(t)})}function Oc(e,t){return new e({type:"boolean",...D(t)})}function Ec(e,t){return new e({type:"null",...D(t)})}function jc(e){return new e({type:"unknown"})}function Ic(e,t){return new e({type:"never",...D(t)})}function ui(e,t){return new ya({check:"less_than",...D(t),value:e,inclusive:!1})}function Fn(e,t){return new ya({check:"less_than",...D(t),value:e,inclusive:!0})}function li(e,t){return new _a({check:"greater_than",...D(t),value:e,inclusive:!1})}function Vn(e,t){return new _a({check:"greater_than",...D(t),value:e,inclusive:!0})}function pi(e,t){return new Yp({check:"multiple_of",...D(t),value:e})}function mi(e,t){return new em({check:"max_length",...D(t),maximum:e})}function tn(e,t){return new tm({check:"min_length",...D(t),minimum:e})}function fi(e,t){return new rm({check:"length_equals",...D(t),length:e})}function Cc(e,t){return new nm({check:"string_format",format:"regex",...D(t),pattern:e})}function Ac(e){return new om({check:"string_format",format:"lowercase",...D(e)})}function Mc(e){return new im({check:"string_format",format:"uppercase",...D(e)})}function Nc(e,t){return new sm({check:"string_format",format:"includes",...D(t),includes:e})}function Dc(e,t){return new am({check:"string_format",format:"starts_with",...D(t),prefix:e})}function Lc(e,t){return new cm({check:"string_format",format:"ends_with",...D(t),suffix:e})}function zr(e){return new dm({check:"overwrite",tx:e})}function qc(e){return zr(t=>t.normalize(e))}function Uc(){return zr(e=>e.trim())}function Zc(){return zr(e=>e.toLowerCase())}function Jc(){return zr(e=>e.toUpperCase())}function jm(e,t,r){return new e({type:"array",element:t,...D(r)})}function Fc(e,t,r){let n=D(r);return n.abort??(n.abort=!0),new e({type:"custom",check:"custom",fn:t,...n})}function Vc(e,t,r){return new e({type:"custom",check:"custom",fn:t,...D(r)})}var hi=class{constructor(t){this.counter=0,this.metadataRegistry=t?.metadata??Wt,this.target=t?.target??"draft-2020-12",this.unrepresentable=t?.unrepresentable??"throw",this.override=t?.override??(()=>{}),this.io=t?.io??"output",this.seen=new Map}process(t,r={path:[],schemaPath:[]}){var n;let o=t._zod.def,i={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},s=this.seen.get(t);if(s)return s.count++,r.schemaPath.includes(t)&&(s.cycle=r.path),s.schema;let a={schema:{},count:1,cycle:void 0,path:r.path};this.seen.set(t,a);let c=t._zod.toJSONSchema?.();if(c)a.schema=c;else{let p={...r,schemaPath:[...r.schemaPath,t],path:r.path},m=t._zod.parent;if(m)a.ref=m,this.process(m,p),this.seen.get(m).isParent=!0;else{let f=a.schema;switch(o.type){case"string":{let h=f;h.type="string";let{minimum:g,maximum:y,format:v,patterns:w,contentEncoding:k}=t._zod.bag;if(typeof g=="number"&&(h.minLength=g),typeof y=="number"&&(h.maxLength=y),v&&(h.format=i[v]??v,h.format===""&&delete h.format),k&&(h.contentEncoding=k),w&&w.size>0){let O=[...w];O.length===1?h.pattern=O[0].source:O.length>1&&(a.schema.allOf=[...O.map(M=>({...this.target==="draft-7"?{type:"string"}:{},pattern:M.source}))])}break}case"number":{let h=f,{minimum:g,maximum:y,format:v,multipleOf:w,exclusiveMaximum:k,exclusiveMinimum:O}=t._zod.bag;typeof v=="string"&&v.includes("int")?h.type="integer":h.type="number",typeof O=="number"&&(h.exclusiveMinimum=O),typeof g=="number"&&(h.minimum=g,typeof O=="number"&&(O>=g?delete h.minimum:delete h.exclusiveMinimum)),typeof k=="number"&&(h.exclusiveMaximum=k),typeof y=="number"&&(h.maximum=y,typeof k=="number"&&(k<=y?delete h.maximum:delete h.exclusiveMaximum)),typeof w=="number"&&(h.multipleOf=w);break}case"boolean":{let h=f;h.type="boolean";break}case"bigint":{if(this.unrepresentable==="throw")throw new Error("BigInt cannot be represented in JSON Schema");break}case"symbol":{if(this.unrepresentable==="throw")throw new Error("Symbols cannot be represented in JSON Schema");break}case"null":{f.type="null";break}case"any":break;case"unknown":break;case"undefined":{if(this.unrepresentable==="throw")throw new Error("Undefined cannot be represented in JSON Schema");break}case"void":{if(this.unrepresentable==="throw")throw new Error("Void cannot be represented in JSON Schema");break}case"never":{f.not={};break}case"date":{if(this.unrepresentable==="throw")throw new Error("Date cannot be represented in JSON Schema");break}case"array":{let h=f,{minimum:g,maximum:y}=t._zod.bag;typeof g=="number"&&(h.minItems=g),typeof y=="number"&&(h.maxItems=y),h.type="array",h.items=this.process(o.element,{...p,path:[...p.path,"items"]});break}case"object":{let h=f;h.type="object",h.properties={};let g=o.shape;for(let w in g)h.properties[w]=this.process(g[w],{...p,path:[...p.path,"properties",w]});let y=new Set(Object.keys(g)),v=new Set([...y].filter(w=>{let k=o.shape[w]._zod;return this.io==="input"?k.optin===void 0:k.optout===void 0}));v.size>0&&(h.required=Array.from(v)),o.catchall?._zod.def.type==="never"?h.additionalProperties=!1:o.catchall?o.catchall&&(h.additionalProperties=this.process(o.catchall,{...p,path:[...p.path,"additionalProperties"]})):this.io==="output"&&(h.additionalProperties=!1);break}case"union":{let h=f;h.anyOf=o.options.map((g,y)=>this.process(g,{...p,path:[...p.path,"anyOf",y]}));break}case"intersection":{let h=f,g=this.process(o.left,{...p,path:[...p.path,"allOf",0]}),y=this.process(o.right,{...p,path:[...p.path,"allOf",1]}),v=k=>"allOf"in k&&Object.keys(k).length===1,w=[...v(g)?g.allOf:[g],...v(y)?y.allOf:[y]];h.allOf=w;break}case"tuple":{let h=f;h.type="array";let g=o.items.map((w,k)=>this.process(w,{...p,path:[...p.path,"prefixItems",k]}));if(this.target==="draft-2020-12"?h.prefixItems=g:h.items=g,o.rest){let w=this.process(o.rest,{...p,path:[...p.path,"items"]});this.target==="draft-2020-12"?h.items=w:h.additionalItems=w}o.rest&&(h.items=this.process(o.rest,{...p,path:[...p.path,"items"]}));let{minimum:y,maximum:v}=t._zod.bag;typeof y=="number"&&(h.minItems=y),typeof v=="number"&&(h.maxItems=v);break}case"record":{let h=f;h.type="object",h.propertyNames=this.process(o.keyType,{...p,path:[...p.path,"propertyNames"]}),h.additionalProperties=this.process(o.valueType,{...p,path:[...p.path,"additionalProperties"]});break}case"map":{if(this.unrepresentable==="throw")throw new Error("Map cannot be represented in JSON Schema");break}case"set":{if(this.unrepresentable==="throw")throw new Error("Set cannot be represented in JSON Schema");break}case"enum":{let h=f,g=An(o.entries);g.every(y=>typeof y=="number")&&(h.type="number"),g.every(y=>typeof y=="string")&&(h.type="string"),h.enum=g;break}case"literal":{let h=f,g=[];for(let y of o.values)if(y===void 0){if(this.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof y=="bigint"){if(this.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");g.push(Number(y))}else g.push(y);if(g.length!==0)if(g.length===1){let y=g[0];h.type=y===null?"null":typeof y,h.const=y}else g.every(y=>typeof y=="number")&&(h.type="number"),g.every(y=>typeof y=="string")&&(h.type="string"),g.every(y=>typeof y=="boolean")&&(h.type="string"),g.every(y=>y===null)&&(h.type="null"),h.enum=g;break}case"file":{let h=f,g={type:"string",format:"binary",contentEncoding:"binary"},{minimum:y,maximum:v,mime:w}=t._zod.bag;y!==void 0&&(g.minLength=y),v!==void 0&&(g.maxLength=v),w?w.length===1?(g.contentMediaType=w[0],Object.assign(h,g)):h.anyOf=w.map(k=>({...g,contentMediaType:k})):Object.assign(h,g);break}case"transform":{if(this.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema");break}case"nullable":{let h=this.process(o.innerType,p);f.anyOf=[h,{type:"null"}];break}case"nonoptional":{this.process(o.innerType,p),a.ref=o.innerType;break}case"success":{let h=f;h.type="boolean";break}case"default":{this.process(o.innerType,p),a.ref=o.innerType,f.default=JSON.parse(JSON.stringify(o.defaultValue));break}case"prefault":{this.process(o.innerType,p),a.ref=o.innerType,this.io==="input"&&(f._prefault=JSON.parse(JSON.stringify(o.defaultValue)));break}case"catch":{this.process(o.innerType,p),a.ref=o.innerType;let h;try{h=o.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}f.default=h;break}case"nan":{if(this.unrepresentable==="throw")throw new Error("NaN cannot be represented in JSON Schema");break}case"template_literal":{let h=f,g=t._zod.pattern;if(!g)throw new Error("Pattern not found in template literal");h.type="string",h.pattern=g.source;break}case"pipe":{let h=this.io==="input"?o.in._zod.def.type==="transform"?o.out:o.in:o.out;this.process(h,p),a.ref=h;break}case"readonly":{this.process(o.innerType,p),a.ref=o.innerType,f.readOnly=!0;break}case"promise":{this.process(o.innerType,p),a.ref=o.innerType;break}case"optional":{this.process(o.innerType,p),a.ref=o.innerType;break}case"lazy":{let h=t._zod.innerType;this.process(h,p),a.ref=h;break}case"custom":{if(this.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema");break}default:}}}let d=this.metadataRegistry.get(t);return d&&Object.assign(a.schema,d),this.io==="input"&&be(t)&&(delete a.schema.examples,delete a.schema.default),this.io==="input"&&a.schema._prefault&&((n=a.schema).default??(n.default=a.schema._prefault)),delete a.schema._prefault,this.seen.get(t).schema}emit(t,r){let n={cycles:r?.cycles??"ref",reused:r?.reused??"inline",external:r?.external??void 0},o=this.seen.get(t);if(!o)throw new Error("Unprocessed schema. This is a bug in Zod.");let i=u=>{let p=this.target==="draft-2020-12"?"$defs":"definitions";if(n.external){let g=n.external.registry.get(u[0])?.id,y=n.external.uri??(w=>w);if(g)return{ref:y(g)};let v=u[1].defId??u[1].schema.id??`schema${this.counter++}`;return u[1].defId=v,{defId:v,ref:`${y("__shared")}#/${p}/${v}`}}if(u[1]===o)return{ref:"#"};let f=`#/${p}/`,h=u[1].schema.id??`__schema${this.counter++}`;return{defId:h,ref:f+h}},s=u=>{if(u[1].schema.$ref)return;let p=u[1],{ref:m,defId:f}=i(u);p.def={...p.schema},f&&(p.defId=f);let h=p.schema;for(let g in h)delete h[g];h.$ref=m};if(n.cycles==="throw")for(let u of this.seen.entries()){let p=u[1];if(p.cycle)throw new Error(`Cycle detected: #/${p.cycle?.join("/")}/<root>
36
-
37
- Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let u of this.seen.entries()){let p=u[1];if(t===u[0]){s(u);continue}if(n.external){let f=n.external.registry.get(u[0])?.id;if(t!==u[0]&&f){s(u);continue}}if(this.metadataRegistry.get(u[0])?.id){s(u);continue}if(p.cycle){s(u);continue}if(p.count>1&&n.reused==="ref"){s(u);continue}}let a=(u,p)=>{let m=this.seen.get(u),f=m.def??m.schema,h={...f};if(m.ref===null)return;let g=m.ref;if(m.ref=null,g){a(g,p);let y=this.seen.get(g).schema;y.$ref&&p.target==="draft-7"?(f.allOf=f.allOf??[],f.allOf.push(y)):(Object.assign(f,y),Object.assign(f,h))}m.isParent||this.override({zodSchema:u,jsonSchema:f,path:m.path??[]})};for(let u of[...this.seen.entries()].reverse())a(u[0],{target:this.target});let c={};if(this.target==="draft-2020-12"?c.$schema="https://json-schema.org/draft/2020-12/schema":this.target==="draft-7"?c.$schema="http://json-schema.org/draft-07/schema#":console.warn(`Invalid target: ${this.target}`),n.external?.uri){let u=n.external.registry.get(t)?.id;if(!u)throw new Error("Schema is missing an `id` property");c.$id=n.external.uri(u)}Object.assign(c,o.def);let d=n.external?.defs??{};for(let u of this.seen.entries()){let p=u[1];p.def&&p.defId&&(d[p.defId]=p.def)}n.external||Object.keys(d).length>0&&(this.target==="draft-2020-12"?c.$defs=d:c.definitions=d);try{return JSON.parse(JSON.stringify(c))}catch{throw new Error("Error converting schema to JSON.")}}};function Wc(e,t){if(e instanceof Jn){let n=new hi(t),o={};for(let a of e._idmap.entries()){let[c,d]=a;n.process(d)}let i={},s={registry:e,uri:t?.uri,defs:o};for(let a of e._idmap.entries()){let[c,d]=a;i[c]=n.emit(d,{...t,external:s})}if(Object.keys(o).length>0){let a=n.target==="draft-2020-12"?"$defs":"definitions";i.__shared={[a]:o}}return{schemas:i}}let r=new hi(t);return r.process(e),r.emit(e,t)}function be(e,t){let r=t??{seen:new Set};if(r.seen.has(e))return!1;r.seen.add(e);let o=e._zod.def;switch(o.type){case"string":case"number":case"bigint":case"boolean":case"date":case"symbol":case"undefined":case"null":case"any":case"unknown":case"never":case"void":case"literal":case"enum":case"nan":case"file":case"template_literal":return!1;case"array":return be(o.element,r);case"object":{for(let i in o.shape)if(be(o.shape[i],r))return!0;return!1}case"union":{for(let i of o.options)if(be(i,r))return!0;return!1}case"intersection":return be(o.left,r)||be(o.right,r);case"tuple":{for(let i of o.items)if(be(i,r))return!0;return!!(o.rest&&be(o.rest,r))}case"record":return be(o.keyType,r)||be(o.valueType,r);case"map":return be(o.keyType,r)||be(o.valueType,r);case"set":return be(o.valueType,r);case"promise":case"optional":case"nonoptional":case"nullable":case"readonly":return be(o.innerType,r);case"lazy":return be(o.getter(),r);case"default":return be(o.innerType,r);case"prefault":return be(o.innerType,r);case"custom":return!1;case"transform":return!0;case"pipe":return be(o.in,r)||be(o.out,r);case"success":return!1;case"catch":return!1;default:}throw new Error(`Unknown schema type: ${o.type}`)}var bk=b("ZodMiniType",(e,t)=>{if(!e._zod)throw new Error("Uninitialized schema in ZodMiniType.");ne.init(e,t),e.def=t,e.parse=(r,n)=>ua(e,r,n,{callee:e.parse}),e.safeParse=(r,n)=>Sr(e,r,n),e.parseAsync=async(r,n)=>pa(e,r,n,{callee:e.parseAsync}),e.safeParseAsync=async(r,n)=>$r(e,r,n),e.check=(...r)=>e.clone({...t,checks:[...t.checks??[],...r.map(n=>typeof n=="function"?{_zod:{check:n,def:{check:"custom"},onattach:[]}}:n)]}),e.clone=(r,n)=>Ge(e,r,n),e.brand=()=>e,e.register=((r,n)=>(r.add(e,n),e))});var vk=b("ZodMiniObject",(e,t)=>{ai.init(e,t),bk.init(e,t),H.defineLazy(e,"shape",()=>t.shape)});function Bc(e,t){let r={type:"object",get shape(){return H.assignProp(this,"shape",{...e}),this.shape},...H.normalizeParams(t)};return new vk(r)}function et(e){return!!e._zod}function Pr(e){let t=Object.values(e);if(t.length===0)return Bc({});let r=t.every(et),n=t.every(o=>!et(o));if(r)return Bc(e);if(n)return Ks(e);throw new Error("Mixed Zod versions detected in object shape.")}function Bt(e,t){return et(e)?Sr(e,t):e.safeParse(t)}async function gi(e,t){return et(e)?await $r(e,t):await e.safeParseAsync(t)}function Ht(e){if(!e)return;let t;if(et(e)?t=e._zod?.def?.shape:t=e.shape,!!t){if(typeof t=="function")try{return t()}catch{return}return t}}function rn(e){if(e){if(typeof e=="object"){let t=e,r=e;if(!t._def&&!r._zod){let n=Object.values(e);if(n.length>0&&n.every(o=>typeof o=="object"&&o!==null&&(o._def!==void 0||o._zod!==void 0||typeof o.parse=="function")))return Pr(e)}}if(et(e)){let r=e._zod?.def;if(r&&(r.type==="object"||r.shape!==void 0))return e}else if(e.shape!==void 0)return e}}function yi(e){if(e&&typeof e=="object"){if("message"in e&&typeof e.message=="string")return e.message;if("issues"in e&&Array.isArray(e.issues)&&e.issues.length>0){let t=e.issues[0];if(t&&typeof t=="object"&&"message"in t)return String(t.message)}try{return JSON.stringify(e)}catch{return String(e)}}return String(e)}function Cm(e){return e.description}function Am(e){if(et(e))return e._zod?.def?.type==="optional";let t=e;return typeof e.isOptional=="function"?e.isOptional():t._def?.typeName==="ZodOptional"}function _i(e){if(et(e)){let i=e._zod?.def;if(i){if(i.value!==void 0)return i.value;if(Array.isArray(i.values)&&i.values.length>0)return i.values[0]}}let r=e._def;if(r){if(r.value!==void 0)return r.value;if(Array.isArray(r.values)&&r.values.length>0)return r.values[0]}let n=e.value;if(n!==void 0)return n}var Wn={};Ws(Wn,{ZodISODate:()=>Nm,ZodISODateTime:()=>Mm,ZodISODuration:()=>Lm,ZodISOTime:()=>Dm,date:()=>Gc,datetime:()=>Hc,duration:()=>Qc,time:()=>Kc});var Mm=b("ZodISODateTime",(e,t)=>{wm.init(e,t),pe.init(e,t)});function Hc(e){return Pm(Mm,e)}var Nm=b("ZodISODate",(e,t)=>{km.init(e,t),pe.init(e,t)});function Gc(e){return Rm(Nm,e)}var Dm=b("ZodISOTime",(e,t)=>{xm.init(e,t),pe.init(e,t)});function Kc(e){return Om(Dm,e)}var Lm=b("ZodISODuration",(e,t)=>{Sm.init(e,t),pe.init(e,t)});function Qc(e){return Em(Lm,e)}var qm=(e,t)=>{ri.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:r=>ca(e,r)},flatten:{value:r=>aa(e,r)},addIssue:{value:r=>e.issues.push(r)},addIssues:{value:r=>e.issues.push(...r)},isEmpty:{get(){return e.issues.length===0}}})},oI=b("ZodError",qm),Bn=b("ZodError",qm,{Parent:Error});var Um=da(Bn),Zm=la(Bn),Jm=ma(Bn),Fm=fa(Bn);var ge=b("ZodType",(e,t)=>(ne.init(e,t),e.def=t,Object.defineProperty(e,"_def",{value:t}),e.check=(...r)=>e.clone({...t,checks:[...t.checks??[],...r.map(n=>typeof n=="function"?{_zod:{check:n,def:{check:"custom"},onattach:[]}}:n)]}),e.clone=(r,n)=>Ge(e,r,n),e.brand=()=>e,e.register=((r,n)=>(r.add(e,n),e)),e.parse=(r,n)=>Um(e,r,n,{callee:e.parse}),e.safeParse=(r,n)=>Jm(e,r,n),e.parseAsync=async(r,n)=>Zm(e,r,n,{callee:e.parseAsync}),e.safeParseAsync=async(r,n)=>Fm(e,r,n),e.spa=e.safeParseAsync,e.refine=(r,n)=>e.check(yx(r,n)),e.superRefine=r=>e.check(_x(r)),e.overwrite=r=>e.check(zr(r)),e.optional=()=>fe(e),e.nullable=()=>Bm(e),e.nullish=()=>fe(Bm(e)),e.nonoptional=r=>ux(e,r),e.array=()=>G(e),e.or=r=>de([e,r]),e.and=r=>vi(e,r),e.transform=r=>Xc(e,Xm(r)),e.default=r=>ax(e,r),e.prefault=r=>dx(e,r),e.catch=r=>px(e,r),e.pipe=r=>Xc(e,r),e.readonly=()=>hx(e),e.describe=r=>{let n=e.clone();return Wt.add(n,{description:r}),n},Object.defineProperty(e,"description",{get(){return Wt.get(e)?.description},configurable:!0}),e.meta=(...r)=>{if(r.length===0)return Wt.get(e);let n=e.clone();return Wt.add(n,r[0]),n},e.isOptional=()=>e.safeParse(void 0).success,e.isNullable=()=>e.safeParse(null).success,e)),Hm=b("_ZodString",(e,t)=>{Zn.init(e,t),ge.init(e,t);let r=e._zod.bag;e.format=r.format??null,e.minLength=r.minimum??null,e.maxLength=r.maximum??null,e.regex=(...n)=>e.check(Cc(...n)),e.includes=(...n)=>e.check(Nc(...n)),e.startsWith=(...n)=>e.check(Dc(...n)),e.endsWith=(...n)=>e.check(Lc(...n)),e.min=(...n)=>e.check(tn(...n)),e.max=(...n)=>e.check(mi(...n)),e.length=(...n)=>e.check(fi(...n)),e.nonempty=(...n)=>e.check(tn(1,...n)),e.lowercase=n=>e.check(Ac(n)),e.uppercase=n=>e.check(Mc(n)),e.trim=()=>e.check(Uc()),e.normalize=(...n)=>e.check(qc(...n)),e.toLowerCase=()=>e.check(Zc()),e.toUpperCase=()=>e.check(Jc())}),Rk=b("ZodString",(e,t)=>{Zn.init(e,t),Hm.init(e,t),e.email=r=>e.check(ac(Ok,r)),e.url=r=>e.check(pc(Ek,r)),e.jwt=r=>e.check(Tc(Wk,r)),e.emoji=r=>e.check(mc(jk,r)),e.guid=r=>e.check(di(Vm,r)),e.uuid=r=>e.check(cc(bi,r)),e.uuidv4=r=>e.check(dc(bi,r)),e.uuidv6=r=>e.check(uc(bi,r)),e.uuidv7=r=>e.check(lc(bi,r)),e.nanoid=r=>e.check(fc(Ik,r)),e.guid=r=>e.check(di(Vm,r)),e.cuid=r=>e.check(hc(Ck,r)),e.cuid2=r=>e.check(gc(Ak,r)),e.ulid=r=>e.check(yc(Mk,r)),e.base64=r=>e.check(Sc(Jk,r)),e.base64url=r=>e.check($c(Fk,r)),e.xid=r=>e.check(_c(Nk,r)),e.ksuid=r=>e.check(bc(Dk,r)),e.ipv4=r=>e.check(vc(Lk,r)),e.ipv6=r=>e.check(wc(qk,r)),e.cidrv4=r=>e.check(kc(Uk,r)),e.cidrv6=r=>e.check(xc(Zk,r)),e.e164=r=>e.check(zc(Vk,r)),e.datetime=r=>e.check(Hc(r)),e.date=r=>e.check(Gc(r)),e.time=r=>e.check(Kc(r)),e.duration=r=>e.check(Qc(r))});function _(e){return sc(Rk,e)}var pe=b("ZodStringFormat",(e,t)=>{ae.init(e,t),Hm.init(e,t)}),Ok=b("ZodEmail",(e,t)=>{ka.init(e,t),pe.init(e,t)});var Vm=b("ZodGUID",(e,t)=>{va.init(e,t),pe.init(e,t)});var bi=b("ZodUUID",(e,t)=>{wa.init(e,t),pe.init(e,t)});var Ek=b("ZodURL",(e,t)=>{xa.init(e,t),pe.init(e,t)});var jk=b("ZodEmoji",(e,t)=>{Sa.init(e,t),pe.init(e,t)});var Ik=b("ZodNanoID",(e,t)=>{$a.init(e,t),pe.init(e,t)});var Ck=b("ZodCUID",(e,t)=>{za.init(e,t),pe.init(e,t)});var Ak=b("ZodCUID2",(e,t)=>{Ta.init(e,t),pe.init(e,t)});var Mk=b("ZodULID",(e,t)=>{Pa.init(e,t),pe.init(e,t)});var Nk=b("ZodXID",(e,t)=>{Ra.init(e,t),pe.init(e,t)});var Dk=b("ZodKSUID",(e,t)=>{Oa.init(e,t),pe.init(e,t)});var Lk=b("ZodIPv4",(e,t)=>{Ea.init(e,t),pe.init(e,t)});var qk=b("ZodIPv6",(e,t)=>{ja.init(e,t),pe.init(e,t)});var Uk=b("ZodCIDRv4",(e,t)=>{Ia.init(e,t),pe.init(e,t)});var Zk=b("ZodCIDRv6",(e,t)=>{Ca.init(e,t),pe.init(e,t)});var Jk=b("ZodBase64",(e,t)=>{Aa.init(e,t),pe.init(e,t)});var Fk=b("ZodBase64URL",(e,t)=>{Ma.init(e,t),pe.init(e,t)});var Vk=b("ZodE164",(e,t)=>{Na.init(e,t),pe.init(e,t)});var Wk=b("ZodJWT",(e,t)=>{Da.init(e,t),pe.init(e,t)});var Gm=b("ZodNumber",(e,t)=>{si.init(e,t),ge.init(e,t),e.gt=(n,o)=>e.check(li(n,o)),e.gte=(n,o)=>e.check(Vn(n,o)),e.min=(n,o)=>e.check(Vn(n,o)),e.lt=(n,o)=>e.check(ui(n,o)),e.lte=(n,o)=>e.check(Fn(n,o)),e.max=(n,o)=>e.check(Fn(n,o)),e.int=n=>e.check(Wm(n)),e.safe=n=>e.check(Wm(n)),e.positive=n=>e.check(li(0,n)),e.nonnegative=n=>e.check(Vn(0,n)),e.negative=n=>e.check(ui(0,n)),e.nonpositive=n=>e.check(Fn(0,n)),e.multipleOf=(n,o)=>e.check(pi(n,o)),e.step=(n,o)=>e.check(pi(n,o)),e.finite=()=>e;let r=e._zod.bag;e.minValue=Math.max(r.minimum??Number.NEGATIVE_INFINITY,r.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,e.maxValue=Math.min(r.maximum??Number.POSITIVE_INFINITY,r.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,e.isInt=(r.format??"").includes("int")||Number.isSafeInteger(r.multipleOf??.5),e.isFinite=!0,e.format=r.format??null});function re(e){return Pc(Gm,e)}var Bk=b("ZodNumberFormat",(e,t)=>{La.init(e,t),Gm.init(e,t)});function Wm(e){return Rc(Bk,e)}var Hk=b("ZodBoolean",(e,t)=>{qa.init(e,t),ge.init(e,t)});function ke(e){return Oc(Hk,e)}var Gk=b("ZodNull",(e,t)=>{Ua.init(e,t),ge.init(e,t)});function Km(e){return Ec(Gk,e)}var Kk=b("ZodUnknown",(e,t)=>{Za.init(e,t),ge.init(e,t)});function me(){return jc(Kk)}var Qk=b("ZodNever",(e,t)=>{Ja.init(e,t),ge.init(e,t)});function Yk(e){return Ic(Qk,e)}var Xk=b("ZodArray",(e,t)=>{Fa.init(e,t),ge.init(e,t),e.element=t.element,e.min=(r,n)=>e.check(tn(r,n)),e.nonempty=r=>e.check(tn(1,r)),e.max=(r,n)=>e.check(mi(r,n)),e.length=(r,n)=>e.check(fi(r,n)),e.unwrap=()=>e.element});function G(e,t){return jm(Xk,e,t)}var Qm=b("ZodObject",(e,t)=>{ai.init(e,t),ge.init(e,t),H.defineLazy(e,"shape",()=>t.shape),e.keyof=()=>Ue(Object.keys(e._zod.def.shape)),e.catchall=r=>e.clone({...e._zod.def,catchall:r}),e.passthrough=()=>e.clone({...e._zod.def,catchall:me()}),e.loose=()=>e.clone({...e._zod.def,catchall:me()}),e.strict=()=>e.clone({...e._zod.def,catchall:Yk()}),e.strip=()=>e.clone({...e._zod.def,catchall:void 0}),e.extend=r=>H.extend(e,r),e.merge=r=>H.merge(e,r),e.pick=r=>H.pick(e,r),e.omit=r=>H.omit(e,r),e.partial=(...r)=>H.partial(ef,e,r[0]),e.required=(...r)=>H.required(tf,e,r[0])});function R(e,t){let r={type:"object",get shape(){return H.assignProp(this,"shape",{...e}),this.shape},...H.normalizeParams(t)};return new Qm(r)}function Ce(e,t){return new Qm({type:"object",get shape(){return H.assignProp(this,"shape",{...e}),this.shape},catchall:me(),...H.normalizeParams(t)})}var Ym=b("ZodUnion",(e,t)=>{ci.init(e,t),ge.init(e,t),e.options=t.options});function de(e,t){return new Ym({type:"union",options:e,...H.normalizeParams(t)})}var ex=b("ZodDiscriminatedUnion",(e,t)=>{Ym.init(e,t),Va.init(e,t)});function ed(e,t,r){return new ex({type:"union",options:t,discriminator:e,...H.normalizeParams(r)})}var tx=b("ZodIntersection",(e,t)=>{Wa.init(e,t),ge.init(e,t)});function vi(e,t){return new tx({type:"intersection",left:e,right:t})}var rx=b("ZodRecord",(e,t)=>{Ba.init(e,t),ge.init(e,t),e.keyType=t.keyType,e.valueType=t.valueType});function ce(e,t,r){return new rx({type:"record",keyType:e,valueType:t,...H.normalizeParams(r)})}var Yc=b("ZodEnum",(e,t)=>{Ha.init(e,t),ge.init(e,t),e.enum=t.entries,e.options=Object.values(t.entries);let r=new Set(Object.keys(t.entries));e.extract=(n,o)=>{let i={};for(let s of n)if(r.has(s))i[s]=t.entries[s];else throw new Error(`Key ${s} not found in enum`);return new Yc({...t,checks:[],...H.normalizeParams(o),entries:i})},e.exclude=(n,o)=>{let i={...t.entries};for(let s of n)if(r.has(s))delete i[s];else throw new Error(`Key ${s} not found in enum`);return new Yc({...t,checks:[],...H.normalizeParams(o),entries:i})}});function Ue(e,t){let r=Array.isArray(e)?Object.fromEntries(e.map(n=>[n,n])):e;return new Yc({type:"enum",entries:r,...H.normalizeParams(t)})}var nx=b("ZodLiteral",(e,t)=>{Ga.init(e,t),ge.init(e,t),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 I(e,t){return new nx({type:"literal",values:Array.isArray(e)?e:[e],...H.normalizeParams(t)})}var ox=b("ZodTransform",(e,t)=>{Ka.init(e,t),ge.init(e,t),e._zod.parse=(r,n)=>{r.addIssue=i=>{if(typeof i=="string")r.issues.push(H.issue(i,r.value,t));else{let s=i;s.fatal&&(s.continue=!1),s.code??(s.code="custom"),s.input??(s.input=r.value),s.inst??(s.inst=e),s.continue??(s.continue=!0),r.issues.push(H.issue(s))}};let o=t.transform(r.value,r);return o instanceof Promise?o.then(i=>(r.value=i,r)):(r.value=o,r)}});function Xm(e){return new ox({type:"transform",transform:e})}var ef=b("ZodOptional",(e,t)=>{Qa.init(e,t),ge.init(e,t),e.unwrap=()=>e._zod.def.innerType});function fe(e){return new ef({type:"optional",innerType:e})}var ix=b("ZodNullable",(e,t)=>{Ya.init(e,t),ge.init(e,t),e.unwrap=()=>e._zod.def.innerType});function Bm(e){return new ix({type:"nullable",innerType:e})}var sx=b("ZodDefault",(e,t)=>{Xa.init(e,t),ge.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function ax(e,t){return new sx({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():t}})}var cx=b("ZodPrefault",(e,t)=>{ec.init(e,t),ge.init(e,t),e.unwrap=()=>e._zod.def.innerType});function dx(e,t){return new cx({type:"prefault",innerType:e,get defaultValue(){return typeof t=="function"?t():t}})}var tf=b("ZodNonOptional",(e,t)=>{tc.init(e,t),ge.init(e,t),e.unwrap=()=>e._zod.def.innerType});function ux(e,t){return new tf({type:"nonoptional",innerType:e,...H.normalizeParams(t)})}var lx=b("ZodCatch",(e,t)=>{rc.init(e,t),ge.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function px(e,t){return new lx({type:"catch",innerType:e,catchValue:typeof t=="function"?t:()=>t})}var mx=b("ZodPipe",(e,t)=>{nc.init(e,t),ge.init(e,t),e.in=t.in,e.out=t.out});function Xc(e,t){return new mx({type:"pipe",in:e,out:t})}var fx=b("ZodReadonly",(e,t)=>{oc.init(e,t),ge.init(e,t)});function hx(e){return new fx({type:"readonly",innerType:e})}var rf=b("ZodCustom",(e,t)=>{ic.init(e,t),ge.init(e,t)});function gx(e){let t=new Se({check:"custom"});return t._zod.check=e,t}function nf(e,t){return Fc(rf,e??(()=>!0),t)}function yx(e,t={}){return Vc(rf,e,t)}function _x(e){let t=gx(r=>(r.addIssue=n=>{if(typeof n=="string")r.issues.push(H.issue(n,r.value,t._zod.def));else{let o=n;o.fatal&&(o.continue=!1),o.code??(o.code="custom"),o.input??(o.input=r.value),o.inst??(o.inst=t),o.continue??(o.continue=!t._zod.def.abort),r.issues.push(H.issue(o))}},e(r.value,r)));return t}function td(e,t){return Xc(Xm(e),t)}He(zm());var nd="2025-11-25";var of=[nd,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],Gt="io.modelcontextprotocol/related-task",ki="2.0",ve=nf(e=>e!==null&&(typeof e=="object"||typeof e=="function")),sf=de([_(),re().int()]),af=_(),_I=Ce({ttl:re().optional(),pollInterval:re().optional()}),bx=R({ttl:re().optional()}),vx=R({taskId:_()}),od=Ce({progressToken:sf.optional(),[Gt]:vx.optional()}),Ke=R({_meta:od.optional()}),Hn=Ke.extend({task:bx.optional()}),cf=e=>Hn.safeParse(e).success,$e=R({method:_(),params:Ke.loose().optional()}),tt=R({_meta:od.optional()}),rt=R({method:_(),params:tt.loose().optional()}),ze=Ce({_meta:od.optional()}),xi=de([_(),re().int()]),df=R({jsonrpc:I(ki),id:xi,...$e.shape}).strict(),id=e=>df.safeParse(e).success,uf=R({jsonrpc:I(ki),...rt.shape}).strict(),lf=e=>uf.safeParse(e).success,sd=R({jsonrpc:I(ki),id:xi,result:ze}).strict(),Gn=e=>sd.safeParse(e).success;var A;(function(e){e[e.ConnectionClosed=-32e3]="ConnectionClosed",e[e.RequestTimeout=-32001]="RequestTimeout",e[e.ParseError=-32700]="ParseError",e[e.InvalidRequest=-32600]="InvalidRequest",e[e.MethodNotFound=-32601]="MethodNotFound",e[e.InvalidParams=-32602]="InvalidParams",e[e.InternalError=-32603]="InternalError",e[e.UrlElicitationRequired=-32042]="UrlElicitationRequired"})(A||(A={}));var ad=R({jsonrpc:I(ki),id:xi.optional(),error:R({code:re().int(),message:_(),data:me().optional()})}).strict();var pf=e=>ad.safeParse(e).success;var mf=de([df,uf,sd,ad]),bI=de([sd,ad]),Si=ze.strict(),wx=tt.extend({requestId:xi.optional(),reason:_().optional()}),$i=rt.extend({method:I("notifications/cancelled"),params:wx}),kx=R({src:_(),mimeType:_().optional(),sizes:G(_()).optional(),theme:Ue(["light","dark"]).optional()}),Kn=R({icons:G(kx).optional()}),nn=R({name:_(),title:_().optional()}),ff=nn.extend({...nn.shape,...Kn.shape,version:_(),websiteUrl:_().optional(),description:_().optional()}),xx=vi(R({applyDefaults:ke().optional()}),ce(_(),me())),Sx=td(e=>e&&typeof e=="object"&&!Array.isArray(e)&&Object.keys(e).length===0?{form:{}}:e,vi(R({form:xx.optional(),url:ve.optional()}),ce(_(),me()).optional())),$x=Ce({list:ve.optional(),cancel:ve.optional(),requests:Ce({sampling:Ce({createMessage:ve.optional()}).optional(),elicitation:Ce({create:ve.optional()}).optional()}).optional()}),zx=Ce({list:ve.optional(),cancel:ve.optional(),requests:Ce({tools:Ce({call:ve.optional()}).optional()}).optional()}),Tx=R({experimental:ce(_(),ve).optional(),sampling:R({context:ve.optional(),tools:ve.optional()}).optional(),elicitation:Sx.optional(),roots:R({listChanged:ke().optional()}).optional(),tasks:$x.optional(),extensions:ce(_(),ve).optional()}),Px=Ke.extend({protocolVersion:_(),capabilities:Tx,clientInfo:ff}),cd=$e.extend({method:I("initialize"),params:Px});var Rx=R({experimental:ce(_(),ve).optional(),logging:ve.optional(),completions:ve.optional(),prompts:R({listChanged:ke().optional()}).optional(),resources:R({subscribe:ke().optional(),listChanged:ke().optional()}).optional(),tools:R({listChanged:ke().optional()}).optional(),tasks:zx.optional(),extensions:ce(_(),ve).optional()}),Ox=ze.extend({protocolVersion:_(),capabilities:Rx,serverInfo:ff,instructions:_().optional()}),dd=rt.extend({method:I("notifications/initialized"),params:tt.optional()});var zi=$e.extend({method:I("ping"),params:Ke.optional()}),Ex=R({progress:re(),total:fe(re()),message:fe(_())}),jx=R({...tt.shape,...Ex.shape,progressToken:sf}),Ti=rt.extend({method:I("notifications/progress"),params:jx}),Ix=Ke.extend({cursor:af.optional()}),Qn=$e.extend({params:Ix.optional()}),Yn=ze.extend({nextCursor:af.optional()}),Cx=Ue(["working","input_required","completed","failed","cancelled"]),Xn=R({taskId:_(),status:Cx,ttl:de([re(),Km()]),createdAt:_(),lastUpdatedAt:_(),pollInterval:fe(re()),statusMessage:fe(_())}),on=ze.extend({task:Xn}),Ax=tt.merge(Xn),eo=rt.extend({method:I("notifications/tasks/status"),params:Ax}),Pi=$e.extend({method:I("tasks/get"),params:Ke.extend({taskId:_()})}),Ri=ze.merge(Xn),Oi=$e.extend({method:I("tasks/result"),params:Ke.extend({taskId:_()})}),vI=ze.loose(),Ei=Qn.extend({method:I("tasks/list")}),ji=Yn.extend({tasks:G(Xn)}),Ii=$e.extend({method:I("tasks/cancel"),params:Ke.extend({taskId:_()})}),hf=ze.merge(Xn),gf=R({uri:_(),mimeType:fe(_()),_meta:ce(_(),me()).optional()}),yf=gf.extend({text:_()}),ud=_().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:"Invalid Base64 string"}),_f=gf.extend({blob:ud}),to=Ue(["user","assistant"]),sn=R({audience:G(to).optional(),priority:re().min(0).max(1).optional(),lastModified:Wn.datetime({offset:!0}).optional()}),bf=R({...nn.shape,...Kn.shape,uri:_(),description:fe(_()),mimeType:fe(_()),size:fe(re()),annotations:sn.optional(),_meta:fe(Ce({}))}),Mx=R({...nn.shape,...Kn.shape,uriTemplate:_(),description:fe(_()),mimeType:fe(_()),annotations:sn.optional(),_meta:fe(Ce({}))}),an=Qn.extend({method:I("resources/list")}),Nx=Yn.extend({resources:G(bf)}),cn=Qn.extend({method:I("resources/templates/list")}),Dx=Yn.extend({resourceTemplates:G(Mx)}),ld=Ke.extend({uri:_()}),Lx=ld,Ci=$e.extend({method:I("resources/read"),params:Lx}),qx=ze.extend({contents:G(de([yf,_f]))}),Ux=rt.extend({method:I("notifications/resources/list_changed"),params:tt.optional()}),Zx=ld,Jx=$e.extend({method:I("resources/subscribe"),params:Zx}),Fx=ld,Vx=$e.extend({method:I("resources/unsubscribe"),params:Fx}),Wx=tt.extend({uri:_()}),Bx=rt.extend({method:I("notifications/resources/updated"),params:Wx}),Hx=R({name:_(),description:fe(_()),required:fe(ke())}),Gx=R({...nn.shape,...Kn.shape,description:fe(_()),arguments:fe(G(Hx)),_meta:fe(Ce({}))}),Ai=Qn.extend({method:I("prompts/list")}),Kx=Yn.extend({prompts:G(Gx)}),Qx=Ke.extend({name:_(),arguments:ce(_(),_()).optional()}),Mi=$e.extend({method:I("prompts/get"),params:Qx}),pd=R({type:I("text"),text:_(),annotations:sn.optional(),_meta:ce(_(),me()).optional()}),md=R({type:I("image"),data:ud,mimeType:_(),annotations:sn.optional(),_meta:ce(_(),me()).optional()}),fd=R({type:I("audio"),data:ud,mimeType:_(),annotations:sn.optional(),_meta:ce(_(),me()).optional()}),Yx=R({type:I("tool_use"),name:_(),id:_(),input:ce(_(),me()),_meta:ce(_(),me()).optional()}),Xx=R({type:I("resource"),resource:de([yf,_f]),annotations:sn.optional(),_meta:ce(_(),me()).optional()}),e0=bf.extend({type:I("resource_link")}),hd=de([pd,md,fd,e0,Xx]),t0=R({role:to,content:hd}),r0=ze.extend({description:_().optional(),messages:G(t0)}),n0=rt.extend({method:I("notifications/prompts/list_changed"),params:tt.optional()}),o0=R({title:_().optional(),readOnlyHint:ke().optional(),destructiveHint:ke().optional(),idempotentHint:ke().optional(),openWorldHint:ke().optional()}),i0=R({taskSupport:Ue(["required","optional","forbidden"]).optional()}),vf=R({...nn.shape,...Kn.shape,description:_().optional(),inputSchema:R({type:I("object"),properties:ce(_(),ve).optional(),required:G(_()).optional()}).catchall(me()),outputSchema:R({type:I("object"),properties:ce(_(),ve).optional(),required:G(_()).optional()}).catchall(me()).optional(),annotations:o0.optional(),execution:i0.optional(),_meta:ce(_(),me()).optional()}),Ni=Qn.extend({method:I("tools/list")}),s0=Yn.extend({tools:G(vf)}),Di=ze.extend({content:G(hd).default([]),structuredContent:ce(_(),me()).optional(),isError:ke().optional()}),wI=Di.or(ze.extend({toolResult:me()})),a0=Hn.extend({name:_(),arguments:ce(_(),me()).optional()}),dn=$e.extend({method:I("tools/call"),params:a0}),c0=rt.extend({method:I("notifications/tools/list_changed"),params:tt.optional()}),kI=R({autoRefresh:ke().default(!0),debounceMs:re().int().nonnegative().default(300)}),ro=Ue(["debug","info","notice","warning","error","critical","alert","emergency"]),d0=Ke.extend({level:ro}),gd=$e.extend({method:I("logging/setLevel"),params:d0}),u0=tt.extend({level:ro,logger:_().optional(),data:me()}),l0=rt.extend({method:I("notifications/message"),params:u0}),p0=R({name:_().optional()}),m0=R({hints:G(p0).optional(),costPriority:re().min(0).max(1).optional(),speedPriority:re().min(0).max(1).optional(),intelligencePriority:re().min(0).max(1).optional()}),f0=R({mode:Ue(["auto","required","none"]).optional()}),h0=R({type:I("tool_result"),toolUseId:_().describe("The unique identifier for the corresponding tool call."),content:G(hd).default([]),structuredContent:R({}).loose().optional(),isError:ke().optional(),_meta:ce(_(),me()).optional()}),g0=ed("type",[pd,md,fd]),wi=ed("type",[pd,md,fd,Yx,h0]),y0=R({role:to,content:de([wi,G(wi)]),_meta:ce(_(),me()).optional()}),_0=Hn.extend({messages:G(y0),modelPreferences:m0.optional(),systemPrompt:_().optional(),includeContext:Ue(["none","thisServer","allServers"]).optional(),temperature:re().optional(),maxTokens:re().int(),stopSequences:G(_()).optional(),metadata:ve.optional(),tools:G(vf).optional(),toolChoice:f0.optional()}),b0=$e.extend({method:I("sampling/createMessage"),params:_0}),no=ze.extend({model:_(),stopReason:fe(Ue(["endTurn","stopSequence","maxTokens"]).or(_())),role:to,content:g0}),yd=ze.extend({model:_(),stopReason:fe(Ue(["endTurn","stopSequence","maxTokens","toolUse"]).or(_())),role:to,content:de([wi,G(wi)])}),v0=R({type:I("boolean"),title:_().optional(),description:_().optional(),default:ke().optional()}),w0=R({type:I("string"),title:_().optional(),description:_().optional(),minLength:re().optional(),maxLength:re().optional(),format:Ue(["email","uri","date","date-time"]).optional(),default:_().optional()}),k0=R({type:Ue(["number","integer"]),title:_().optional(),description:_().optional(),minimum:re().optional(),maximum:re().optional(),default:re().optional()}),x0=R({type:I("string"),title:_().optional(),description:_().optional(),enum:G(_()),default:_().optional()}),S0=R({type:I("string"),title:_().optional(),description:_().optional(),oneOf:G(R({const:_(),title:_()})),default:_().optional()}),$0=R({type:I("string"),title:_().optional(),description:_().optional(),enum:G(_()),enumNames:G(_()).optional(),default:_().optional()}),z0=de([x0,S0]),T0=R({type:I("array"),title:_().optional(),description:_().optional(),minItems:re().optional(),maxItems:re().optional(),items:R({type:I("string"),enum:G(_())}),default:G(_()).optional()}),P0=R({type:I("array"),title:_().optional(),description:_().optional(),minItems:re().optional(),maxItems:re().optional(),items:R({anyOf:G(R({const:_(),title:_()}))}),default:G(_()).optional()}),R0=de([T0,P0]),O0=de([$0,z0,R0]),E0=de([O0,v0,w0,k0]),j0=Hn.extend({mode:I("form").optional(),message:_(),requestedSchema:R({type:I("object"),properties:ce(_(),E0),required:G(_()).optional()})}),I0=Hn.extend({mode:I("url"),message:_(),elicitationId:_(),url:_().url()}),C0=de([j0,I0]),A0=$e.extend({method:I("elicitation/create"),params:C0}),M0=tt.extend({elicitationId:_()}),N0=rt.extend({method:I("notifications/elicitation/complete"),params:M0}),un=ze.extend({action:Ue(["accept","decline","cancel"]),content:td(e=>e===null?void 0:e,ce(_(),de([_(),re(),ke(),G(_())])).optional())}),D0=R({type:I("ref/resource"),uri:_()});var L0=R({type:I("ref/prompt"),name:_()}),q0=Ke.extend({ref:de([L0,D0]),argument:R({name:_(),value:_()}),context:R({arguments:ce(_(),_()).optional()}).optional()}),Li=$e.extend({method:I("completion/complete"),params:q0});function wf(e){if(e.params.ref.type!=="ref/prompt")throw new TypeError(`Expected CompleteRequestPrompt, but got ${e.params.ref.type}`)}function kf(e){if(e.params.ref.type!=="ref/resource")throw new TypeError(`Expected CompleteRequestResourceTemplate, but got ${e.params.ref.type}`)}var U0=ze.extend({completion:Ce({values:G(_()).max(100),total:fe(re().int()),hasMore:fe(ke())})}),Z0=R({uri:_().startsWith("file://"),name:_().optional(),_meta:ce(_(),me()).optional()}),J0=$e.extend({method:I("roots/list"),params:Ke.optional()}),_d=ze.extend({roots:G(Z0)}),F0=rt.extend({method:I("notifications/roots/list_changed"),params:tt.optional()}),xI=de([zi,cd,Li,gd,Mi,Ai,an,cn,Ci,Jx,Vx,dn,Ni,Pi,Oi,Ei,Ii]),SI=de([$i,Ti,dd,F0,eo]),$I=de([Si,no,yd,un,_d,Ri,ji,on]),zI=de([zi,b0,A0,J0,Pi,Oi,Ei,Ii]),TI=de([$i,Ti,l0,Bx,Ux,c0,n0,eo,N0]),PI=de([Si,Ox,U0,r0,Kx,Nx,Dx,qx,Di,s0,Ri,ji,on]),j=class e extends Error{constructor(t,r,n){super(`MCP error ${t}: ${r}`),this.code=t,this.data=n,this.name="McpError"}static fromError(t,r,n){if(t===A.UrlElicitationRequired&&n){let o=n;if(o.elicitations)return new rd(o.elicitations,r)}return new e(t,r,n)}},rd=class extends j{constructor(t,r=`URL elicitation${t.length>1?"s":""} required`){super(A.UrlElicitationRequired,r,{elicitations:t})}get elicitations(){return this.data?.elicitations??[]}};function Kt(e){return e==="completed"||e==="failed"||e==="cancelled"}var Sf=Symbol("Let zodToJsonSchema decide on which parser to use");var xf={name:void 0,$refStrategy:"root",basePath:["#"],effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",removeAdditionalStrategy:"passthrough",allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:"definitions",target:"jsonSchema7",strictUnions:!1,definitions:{},errorMessages:!1,markdownDescription:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref",openAiAnyTypeName:"OpenAiAnyType"},$f=e=>typeof e=="string"?{...xf,name:e}:{...xf,...e};var zf=e=>{let t=$f(e),r=t.name!==void 0?[...t.basePath,t.definitionPath,t.name]:t.basePath;return{...t,flags:{hasReferencedOpenAiAnyType:!1},currentPath:r,propertyPath:void 0,seen:new Map(Object.entries(t.definitions).map(([n,o])=>[o._def,{def:o._def,path:[...t.basePath,t.definitionPath,n],jsonSchema:void 0}]))}};function bd(e,t,r,n){n?.errorMessages&&r&&(e.errorMessage={...e.errorMessage,[t]:r})}function K(e,t,r,n,o){e[t]=r,bd(e,t,n,o)}var qi=(e,t)=>{let r=0;for(;r<e.length&&r<t.length&&e[r]===t[r];r++);return[(e.length-r).toString(),...t.slice(r)].join("/")};function he(e){if(e.target!=="openAi")return{};let t=[...e.basePath,e.definitionPath,e.openAiAnyTypeName];return e.flags.hasReferencedOpenAiAnyType=!0,{$ref:e.$refStrategy==="relative"?qi(t,e.currentPath):t.join("/")}}function Tf(e,t){let r={type:"array"};return e.type?._def&&e.type?._def?.typeName!==S.ZodAny&&(r.items=L(e.type._def,{...t,currentPath:[...t.currentPath,"items"]})),e.minLength&&K(r,"minItems",e.minLength.value,e.minLength.message,t),e.maxLength&&K(r,"maxItems",e.maxLength.value,e.maxLength.message,t),e.exactLength&&(K(r,"minItems",e.exactLength.value,e.exactLength.message,t),K(r,"maxItems",e.exactLength.value,e.exactLength.message,t)),r}function Pf(e,t){let r={type:"integer",format:"int64"};if(!e.checks)return r;for(let n of e.checks)switch(n.kind){case"min":t.target==="jsonSchema7"?n.inclusive?K(r,"minimum",n.value,n.message,t):K(r,"exclusiveMinimum",n.value,n.message,t):(n.inclusive||(r.exclusiveMinimum=!0),K(r,"minimum",n.value,n.message,t));break;case"max":t.target==="jsonSchema7"?n.inclusive?K(r,"maximum",n.value,n.message,t):K(r,"exclusiveMaximum",n.value,n.message,t):(n.inclusive||(r.exclusiveMaximum=!0),K(r,"maximum",n.value,n.message,t));break;case"multipleOf":K(r,"multipleOf",n.value,n.message,t);break}return r}function Rf(){return{type:"boolean"}}function Ui(e,t){return L(e.type._def,t)}var Of=(e,t)=>L(e.innerType._def,t);function vd(e,t,r){let n=r??t.dateStrategy;if(Array.isArray(n))return{anyOf:n.map((o,i)=>vd(e,t,o))};switch(n){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return V0(e,t)}}var V0=(e,t)=>{let r={type:"integer",format:"unix-time"};if(t.target==="openApi3")return r;for(let n of e.checks)switch(n.kind){case"min":K(r,"minimum",n.value,n.message,t);break;case"max":K(r,"maximum",n.value,n.message,t);break}return r};function Ef(e,t){return{...L(e.innerType._def,t),default:e.defaultValue()}}function jf(e,t){return t.effectStrategy==="input"?L(e.schema._def,t):he(t)}function If(e){return{type:"string",enum:Array.from(e.values)}}var W0=e=>"type"in e&&e.type==="string"?!1:"allOf"in e;function Cf(e,t){let r=[L(e.left._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),L(e.right._def,{...t,currentPath:[...t.currentPath,"allOf","1"]})].filter(i=>!!i),n=t.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0,o=[];return r.forEach(i=>{if(W0(i))o.push(...i.allOf),i.unevaluatedProperties===void 0&&(n=void 0);else{let s=i;if("additionalProperties"in i&&i.additionalProperties===!1){let{additionalProperties:a,...c}=i;s=c}else n=void 0;o.push(s)}}),o.length?{allOf:o,...n}:void 0}function Af(e,t){let r=typeof e.value;return r!=="bigint"&&r!=="number"&&r!=="boolean"&&r!=="string"?{type:Array.isArray(e.value)?"array":"object"}:t.target==="openApi3"?{type:r==="bigint"?"integer":r,enum:[e.value]}:{type:r==="bigint"?"integer":r,const:e.value}}var wd,dt={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:()=>(wd===void 0&&(wd=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),wd),uuid:/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,ipv4:/^(?:(?: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])$/,ipv4Cidr:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,ipv6Cidr:/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64url:/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,jwt:/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/};function Zi(e,t){let r={type:"string"};if(e.checks)for(let n of e.checks)switch(n.kind){case"min":K(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,t);break;case"max":K(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value,n.message,t);break;case"email":switch(t.emailStrategy){case"format:email":ut(r,"email",n.message,t);break;case"format:idn-email":ut(r,"idn-email",n.message,t);break;case"pattern:zod":Ae(r,dt.email,n.message,t);break}break;case"url":ut(r,"uri",n.message,t);break;case"uuid":ut(r,"uuid",n.message,t);break;case"regex":Ae(r,n.regex,n.message,t);break;case"cuid":Ae(r,dt.cuid,n.message,t);break;case"cuid2":Ae(r,dt.cuid2,n.message,t);break;case"startsWith":Ae(r,RegExp(`^${kd(n.value,t)}`),n.message,t);break;case"endsWith":Ae(r,RegExp(`${kd(n.value,t)}$`),n.message,t);break;case"datetime":ut(r,"date-time",n.message,t);break;case"date":ut(r,"date",n.message,t);break;case"time":ut(r,"time",n.message,t);break;case"duration":ut(r,"duration",n.message,t);break;case"length":K(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,t),K(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value,n.message,t);break;case"includes":{Ae(r,RegExp(kd(n.value,t)),n.message,t);break}case"ip":{n.version!=="v6"&&ut(r,"ipv4",n.message,t),n.version!=="v4"&&ut(r,"ipv6",n.message,t);break}case"base64url":Ae(r,dt.base64url,n.message,t);break;case"jwt":Ae(r,dt.jwt,n.message,t);break;case"cidr":{n.version!=="v6"&&Ae(r,dt.ipv4Cidr,n.message,t),n.version!=="v4"&&Ae(r,dt.ipv6Cidr,n.message,t);break}case"emoji":Ae(r,dt.emoji(),n.message,t);break;case"ulid":{Ae(r,dt.ulid,n.message,t);break}case"base64":{switch(t.base64Strategy){case"format:binary":{ut(r,"binary",n.message,t);break}case"contentEncoding:base64":{K(r,"contentEncoding","base64",n.message,t);break}case"pattern:zod":{Ae(r,dt.base64,n.message,t);break}}break}case"nanoid":Ae(r,dt.nanoid,n.message,t);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return r}function kd(e,t){return t.patternStrategy==="escape"?H0(e):e}var B0=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function H0(e){let t="";for(let r=0;r<e.length;r++)B0.has(e[r])||(t+="\\"),t+=e[r];return t}function ut(e,t,r,n){e.format||e.anyOf?.some(o=>o.format)?(e.anyOf||(e.anyOf=[]),e.format&&(e.anyOf.push({format:e.format,...e.errorMessage&&n.errorMessages&&{errorMessage:{format:e.errorMessage.format}}}),delete e.format,e.errorMessage&&(delete e.errorMessage.format,Object.keys(e.errorMessage).length===0&&delete e.errorMessage)),e.anyOf.push({format:t,...r&&n.errorMessages&&{errorMessage:{format:r}}})):K(e,"format",t,r,n)}function Ae(e,t,r,n){e.pattern||e.allOf?.some(o=>o.pattern)?(e.allOf||(e.allOf=[]),e.pattern&&(e.allOf.push({pattern:e.pattern,...e.errorMessage&&n.errorMessages&&{errorMessage:{pattern:e.errorMessage.pattern}}}),delete e.pattern,e.errorMessage&&(delete e.errorMessage.pattern,Object.keys(e.errorMessage).length===0&&delete e.errorMessage)),e.allOf.push({pattern:Mf(t,n),...r&&n.errorMessages&&{errorMessage:{pattern:r}}})):K(e,"pattern",Mf(t,n),r,n)}function Mf(e,t){if(!t.applyRegexFlags||!e.flags)return e.source;let r={i:e.flags.includes("i"),m:e.flags.includes("m"),s:e.flags.includes("s")},n=r.i?e.source.toLowerCase():e.source,o="",i=!1,s=!1,a=!1;for(let c=0;c<n.length;c++){if(i){o+=n[c],i=!1;continue}if(r.i){if(s){if(n[c].match(/[a-z]/)){a?(o+=n[c],o+=`${n[c-2]}-${n[c]}`.toUpperCase(),a=!1):n[c+1]==="-"&&n[c+2]?.match(/[a-z]/)?(o+=n[c],a=!0):o+=`${n[c]}${n[c].toUpperCase()}`;continue}}else if(n[c].match(/[a-z]/)){o+=`[${n[c]}${n[c].toUpperCase()}]`;continue}}if(r.m){if(n[c]==="^"){o+=`(^|(?<=[\r
38
- ]))`;continue}else if(n[c]==="$"){o+=`($|(?=[\r
39
- ]))`;continue}}if(r.s&&n[c]==="."){o+=s?`${n[c]}\r
40
- `:`[${n[c]}\r
41
- ]`;continue}o+=n[c],n[c]==="\\"?i=!0:s&&n[c]==="]"?s=!1:!s&&n[c]==="["&&(s=!0)}try{new RegExp(o)}catch{return console.warn(`Could not convert regex pattern at ${t.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),e.source}return o}function Ji(e,t){if(t.target==="openAi"&&console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead."),t.target==="openApi3"&&e.keyType?._def.typeName===S.ZodEnum)return{type:"object",required:e.keyType._def.values,properties:e.keyType._def.values.reduce((n,o)=>({...n,[o]:L(e.valueType._def,{...t,currentPath:[...t.currentPath,"properties",o]})??he(t)}),{}),additionalProperties:t.rejectedAdditionalProperties};let r={type:"object",additionalProperties:L(e.valueType._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]})??t.allowedAdditionalProperties};if(t.target==="openApi3")return r;if(e.keyType?._def.typeName===S.ZodString&&e.keyType._def.checks?.length){let{type:n,...o}=Zi(e.keyType._def,t);return{...r,propertyNames:o}}else{if(e.keyType?._def.typeName===S.ZodEnum)return{...r,propertyNames:{enum:e.keyType._def.values}};if(e.keyType?._def.typeName===S.ZodBranded&&e.keyType._def.type._def.typeName===S.ZodString&&e.keyType._def.type._def.checks?.length){let{type:n,...o}=Ui(e.keyType._def,t);return{...r,propertyNames:o}}}return r}function Nf(e,t){if(t.mapStrategy==="record")return Ji(e,t);let r=L(e.keyType._def,{...t,currentPath:[...t.currentPath,"items","items","0"]})||he(t),n=L(e.valueType._def,{...t,currentPath:[...t.currentPath,"items","items","1"]})||he(t);return{type:"array",maxItems:125,items:{type:"array",items:[r,n],minItems:2,maxItems:2}}}function Df(e){let t=e.values,n=Object.keys(e.values).filter(i=>typeof t[t[i]]!="number").map(i=>t[i]),o=Array.from(new Set(n.map(i=>typeof i)));return{type:o.length===1?o[0]==="string"?"string":"number":["string","number"],enum:n}}function Lf(e){return e.target==="openAi"?void 0:{not:he({...e,currentPath:[...e.currentPath,"not"]})}}function qf(e){return e.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var oo={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function Zf(e,t){if(t.target==="openApi3")return Uf(e,t);let r=e.options instanceof Map?Array.from(e.options.values()):e.options;if(r.every(n=>n._def.typeName in oo&&(!n._def.checks||!n._def.checks.length))){let n=r.reduce((o,i)=>{let s=oo[i._def.typeName];return s&&!o.includes(s)?[...o,s]:o},[]);return{type:n.length>1?n:n[0]}}else if(r.every(n=>n._def.typeName==="ZodLiteral"&&!n.description)){let n=r.reduce((o,i)=>{let s=typeof i._def.value;switch(s){case"string":case"number":case"boolean":return[...o,s];case"bigint":return[...o,"integer"];case"object":if(i._def.value===null)return[...o,"null"];default:return o}},[]);if(n.length===r.length){let o=n.filter((i,s,a)=>a.indexOf(i)===s);return{type:o.length>1?o:o[0],enum:r.reduce((i,s)=>i.includes(s._def.value)?i:[...i,s._def.value],[])}}}else if(r.every(n=>n._def.typeName==="ZodEnum"))return{type:"string",enum:r.reduce((n,o)=>[...n,...o._def.values.filter(i=>!n.includes(i))],[])};return Uf(e,t)}var Uf=(e,t)=>{let r=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((n,o)=>L(n._def,{...t,currentPath:[...t.currentPath,"anyOf",`${o}`]})).filter(n=>!!n&&(!t.strictUnions||typeof n=="object"&&Object.keys(n).length>0));return r.length?{anyOf:r}:void 0};function Jf(e,t){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(e.innerType._def.typeName)&&(!e.innerType._def.checks||!e.innerType._def.checks.length))return t.target==="openApi3"?{type:oo[e.innerType._def.typeName],nullable:!0}:{type:[oo[e.innerType._def.typeName],"null"]};if(t.target==="openApi3"){let n=L(e.innerType._def,{...t,currentPath:[...t.currentPath]});return n&&"$ref"in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}let r=L(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}function Ff(e,t){let r={type:"number"};if(!e.checks)return r;for(let n of e.checks)switch(n.kind){case"int":r.type="integer",bd(r,"type",n.message,t);break;case"min":t.target==="jsonSchema7"?n.inclusive?K(r,"minimum",n.value,n.message,t):K(r,"exclusiveMinimum",n.value,n.message,t):(n.inclusive||(r.exclusiveMinimum=!0),K(r,"minimum",n.value,n.message,t));break;case"max":t.target==="jsonSchema7"?n.inclusive?K(r,"maximum",n.value,n.message,t):K(r,"exclusiveMaximum",n.value,n.message,t):(n.inclusive||(r.exclusiveMaximum=!0),K(r,"maximum",n.value,n.message,t));break;case"multipleOf":K(r,"multipleOf",n.value,n.message,t);break}return r}function Vf(e,t){let r=t.target==="openAi",n={type:"object",properties:{}},o=[],i=e.shape();for(let a in i){let c=i[a];if(c===void 0||c._def===void 0)continue;let d=K0(c);d&&r&&(c._def.typeName==="ZodOptional"&&(c=c._def.innerType),c.isNullable()||(c=c.nullable()),d=!1);let u=L(c._def,{...t,currentPath:[...t.currentPath,"properties",a],propertyPath:[...t.currentPath,"properties",a]});u!==void 0&&(n.properties[a]=u,d||o.push(a))}o.length&&(n.required=o);let s=G0(e,t);return s!==void 0&&(n.additionalProperties=s),n}function G0(e,t){if(e.catchall._def.typeName!=="ZodNever")return L(e.catchall._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]});switch(e.unknownKeys){case"passthrough":return t.allowedAdditionalProperties;case"strict":return t.rejectedAdditionalProperties;case"strip":return t.removeAdditionalStrategy==="strict"?t.allowedAdditionalProperties:t.rejectedAdditionalProperties}}function K0(e){try{return e.isOptional()}catch{return!0}}var Wf=(e,t)=>{if(t.currentPath.toString()===t.propertyPath?.toString())return L(e.innerType._def,t);let r=L(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","1"]});return r?{anyOf:[{not:he(t)},r]}:he(t)};var Bf=(e,t)=>{if(t.pipeStrategy==="input")return L(e.in._def,t);if(t.pipeStrategy==="output")return L(e.out._def,t);let r=L(e.in._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),n=L(e.out._def,{...t,currentPath:[...t.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,n].filter(o=>o!==void 0)}};function Hf(e,t){return L(e.type._def,t)}function Gf(e,t){let n={type:"array",uniqueItems:!0,items:L(e.valueType._def,{...t,currentPath:[...t.currentPath,"items"]})};return e.minSize&&K(n,"minItems",e.minSize.value,e.minSize.message,t),e.maxSize&&K(n,"maxItems",e.maxSize.value,e.maxSize.message,t),n}function Kf(e,t){return e.rest?{type:"array",minItems:e.items.length,items:e.items.map((r,n)=>L(r._def,{...t,currentPath:[...t.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[]),additionalItems:L(e.rest._def,{...t,currentPath:[...t.currentPath,"additionalItems"]})}:{type:"array",minItems:e.items.length,maxItems:e.items.length,items:e.items.map((r,n)=>L(r._def,{...t,currentPath:[...t.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[])}}function Qf(e){return{not:he(e)}}function Yf(e){return he(e)}var Xf=(e,t)=>L(e.innerType._def,t);var eh=(e,t,r)=>{switch(t){case S.ZodString:return Zi(e,r);case S.ZodNumber:return Ff(e,r);case S.ZodObject:return Vf(e,r);case S.ZodBigInt:return Pf(e,r);case S.ZodBoolean:return Rf();case S.ZodDate:return vd(e,r);case S.ZodUndefined:return Qf(r);case S.ZodNull:return qf(r);case S.ZodArray:return Tf(e,r);case S.ZodUnion:case S.ZodDiscriminatedUnion:return Zf(e,r);case S.ZodIntersection:return Cf(e,r);case S.ZodTuple:return Kf(e,r);case S.ZodRecord:return Ji(e,r);case S.ZodLiteral:return Af(e,r);case S.ZodEnum:return If(e);case S.ZodNativeEnum:return Df(e);case S.ZodNullable:return Jf(e,r);case S.ZodOptional:return Wf(e,r);case S.ZodMap:return Nf(e,r);case S.ZodSet:return Gf(e,r);case S.ZodLazy:return()=>e.getter()._def;case S.ZodPromise:return Hf(e,r);case S.ZodNaN:case S.ZodNever:return Lf(r);case S.ZodEffects:return jf(e,r);case S.ZodAny:return he(r);case S.ZodUnknown:return Yf(r);case S.ZodDefault:return Ef(e,r);case S.ZodBranded:return Ui(e,r);case S.ZodReadonly:return Xf(e,r);case S.ZodCatch:return Of(e,r);case S.ZodPipeline:return Bf(e,r);case S.ZodFunction:case S.ZodVoid:case S.ZodSymbol:return;default:return(n=>{})(t)}};function L(e,t,r=!1){let n=t.seen.get(e);if(t.override){let a=t.override?.(e,t,n,r);if(a!==Sf)return a}if(n&&!r){let a=Q0(n,t);if(a!==void 0)return a}let o={def:e,path:t.currentPath,jsonSchema:void 0};t.seen.set(e,o);let i=eh(e,e.typeName,t),s=typeof i=="function"?L(i(),t):i;if(s&&Y0(e,t,s),t.postProcess){let a=t.postProcess(s,e,t);return o.jsonSchema=s,a}return o.jsonSchema=s,s}var Q0=(e,t)=>{switch(t.$refStrategy){case"root":return{$ref:e.path.join("/")};case"relative":return{$ref:qi(t.currentPath,e.path)};case"none":case"seen":return e.path.length<t.currentPath.length&&e.path.every((r,n)=>t.currentPath[n]===r)?(console.warn(`Recursive reference detected at ${t.currentPath.join("/")}! Defaulting to any`),he(t)):t.$refStrategy==="seen"?he(t):void 0}},Y0=(e,t,r)=>(e.description&&(r.description=e.description,t.markdownDescription&&(r.markdownDescription=e.description)),r);var xd=(e,t)=>{let r=zf(t),n=typeof t=="object"&&t.definitions?Object.entries(t.definitions).reduce((c,[d,u])=>({...c,[d]:L(u._def,{...r,currentPath:[...r.basePath,r.definitionPath,d]},!0)??he(r)}),{}):void 0,o=typeof t=="string"?t:t?.nameStrategy==="title"?void 0:t?.name,i=L(e._def,o===void 0?r:{...r,currentPath:[...r.basePath,r.definitionPath,o]},!1)??he(r),s=typeof t=="object"&&t.name!==void 0&&t.nameStrategy==="title"?t.name:void 0;s!==void 0&&(i.title=s),r.flags.hasReferencedOpenAiAnyType&&(n||(n={}),n[r.openAiAnyTypeName]||(n[r.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:r.$refStrategy==="relative"?"1":[...r.basePath,r.definitionPath,r.openAiAnyTypeName].join("/")}}));let a=o===void 0?n?{...i,[r.definitionPath]:n}:i:{$ref:[...r.$refStrategy==="relative"?[]:r.basePath,r.definitionPath,o].join("/"),[r.definitionPath]:{...n,[o]:i}};return r.target==="jsonSchema7"?a.$schema="http://json-schema.org/draft-07/schema#":(r.target==="jsonSchema2019-09"||r.target==="openAi")&&(a.$schema="https://json-schema.org/draft/2019-09/schema#"),r.target==="openAi"&&("anyOf"in a||"oneOf"in a||"allOf"in a||"type"in a&&Array.isArray(a.type))&&console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property."),a};function X0(e){return!e||e==="jsonSchema7"||e==="draft-7"?"draft-7":e==="jsonSchema2019-09"||e==="draft-2020-12"?"draft-2020-12":"draft-7"}function Sd(e,t){return et(e)?Wc(e,{target:X0(t?.target),io:t?.pipeStrategy??"input"}):xd(e,{strictUnions:t?.strictUnions??!0,pipeStrategy:t?.pipeStrategy??"input"})}function $d(e){let r=Ht(e)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=_i(r);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}function zd(e,t){let r=Bt(e,t);if(!r.success)throw r.error;return r.data}var eS=6e4,Fi=class{constructor(t){this._options=t,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this._pendingDebouncedNotifications=new Set,this._taskProgressTokens=new Map,this._requestResolvers=new Map,this.setNotificationHandler($i,r=>{this._oncancel(r)}),this.setNotificationHandler(Ti,r=>{this._onprogress(r)}),this.setRequestHandler(zi,r=>({})),this._taskStore=t?.taskStore,this._taskMessageQueue=t?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(Pi,async(r,n)=>{let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new j(A.InvalidParams,"Failed to retrieve task: Task not found");return{...o}}),this.setRequestHandler(Oi,async(r,n)=>{let o=async()=>{let i=r.params.taskId;if(this._taskMessageQueue){let a;for(;a=await this._taskMessageQueue.dequeue(i,n.sessionId);){if(a.type==="response"||a.type==="error"){let c=a.message,d=c.id,u=this._requestResolvers.get(d);if(u)if(this._requestResolvers.delete(d),a.type==="response")u(c);else{let p=c,m=new j(p.error.code,p.error.message,p.error.data);u(m)}else{let p=a.type==="response"?"Response":"Error";this._onerror(new Error(`${p} handler missing for request ${d}`))}continue}await this._transport?.send(a.message,{relatedRequestId:n.requestId})}}let s=await this._taskStore.getTask(i,n.sessionId);if(!s)throw new j(A.InvalidParams,`Task not found: ${i}`);if(!Kt(s.status))return await this._waitForTaskUpdate(i,n.signal),await o();if(Kt(s.status)){let a=await this._taskStore.getTaskResult(i,n.sessionId);return this._clearTaskQueue(i),{...a,_meta:{...a._meta,[Gt]:{taskId:i}}}}return await o()};return await o()}),this.setRequestHandler(Ei,async(r,n)=>{try{let{tasks:o,nextCursor:i}=await this._taskStore.listTasks(r.params?.cursor,n.sessionId);return{tasks:o,nextCursor:i,_meta:{}}}catch(o){throw new j(A.InvalidParams,`Failed to list tasks: ${o instanceof Error?o.message:String(o)}`)}}),this.setRequestHandler(Ii,async(r,n)=>{try{let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new j(A.InvalidParams,`Task not found: ${r.params.taskId}`);if(Kt(o.status))throw new j(A.InvalidParams,`Cannot cancel task in terminal status: ${o.status}`);await this._taskStore.updateTaskStatus(r.params.taskId,"cancelled","Client cancelled task execution.",n.sessionId),this._clearTaskQueue(r.params.taskId);let i=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!i)throw new j(A.InvalidParams,`Task not found after cancellation: ${r.params.taskId}`);return{_meta:{},...i}}catch(o){throw o instanceof j?o:new j(A.InvalidRequest,`Failed to cancel task: ${o instanceof Error?o.message:String(o)}`)}}))}async _oncancel(t){if(!t.params.requestId)return;this._requestHandlerAbortControllers.get(t.params.requestId)?.abort(t.params.reason)}_setupTimeout(t,r,n,o,i=!1){this._timeoutInfo.set(t,{timeoutId:setTimeout(o,r),startTime:Date.now(),timeout:r,maxTotalTimeout:n,resetTimeoutOnProgress:i,onTimeout:o})}_resetTimeout(t){let r=this._timeoutInfo.get(t);if(!r)return!1;let n=Date.now()-r.startTime;if(r.maxTotalTimeout&&n>=r.maxTotalTimeout)throw this._timeoutInfo.delete(t),j.fromError(A.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:r.maxTotalTimeout,totalElapsed:n});return clearTimeout(r.timeoutId),r.timeoutId=setTimeout(r.onTimeout,r.timeout),!0}_cleanupTimeout(t){let r=this._timeoutInfo.get(t);r&&(clearTimeout(r.timeoutId),this._timeoutInfo.delete(t))}async connect(t){if(this._transport)throw new Error("Already connected to a transport. Call close() before connecting to a new transport, or use a separate Protocol instance per connection.");this._transport=t;let r=this.transport?.onclose;this._transport.onclose=()=>{r?.(),this._onclose()};let n=this.transport?.onerror;this._transport.onerror=i=>{n?.(i),this._onerror(i)};let o=this._transport?.onmessage;this._transport.onmessage=(i,s)=>{o?.(i,s),Gn(i)||pf(i)?this._onresponse(i):id(i)?this._onrequest(i,s):lf(i)?this._onnotification(i):this._onerror(new Error(`Unknown message type: ${JSON.stringify(i)}`))},await this._transport.start()}_onclose(){let t=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();for(let n of this._timeoutInfo.values())clearTimeout(n.timeoutId);this._timeoutInfo.clear();for(let n of this._requestHandlerAbortControllers.values())n.abort();this._requestHandlerAbortControllers.clear();let r=j.fromError(A.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(let n of t.values())n(r)}_onerror(t){this.onerror?.(t)}_onnotification(t){let r=this._notificationHandlers.get(t.method)??this.fallbackNotificationHandler;r!==void 0&&Promise.resolve().then(()=>r(t)).catch(n=>this._onerror(new Error(`Uncaught error in notification handler: ${n}`)))}_onrequest(t,r){let n=this._requestHandlers.get(t.method)??this.fallbackRequestHandler,o=this._transport,i=t.params?._meta?.[Gt]?.taskId;if(n===void 0){let u={jsonrpc:"2.0",id:t.id,error:{code:A.MethodNotFound,message:"Method not found"}};i&&this._taskMessageQueue?this._enqueueTaskMessage(i,{type:"error",message:u,timestamp:Date.now()},o?.sessionId).catch(p=>this._onerror(new Error(`Failed to enqueue error response: ${p}`))):o?.send(u).catch(p=>this._onerror(new Error(`Failed to send an error response: ${p}`)));return}let s=new AbortController;this._requestHandlerAbortControllers.set(t.id,s);let a=cf(t.params)?t.params.task:void 0,c=this._taskStore?this.requestTaskStore(t,o?.sessionId):void 0,d={signal:s.signal,sessionId:o?.sessionId,_meta:t.params?._meta,sendNotification:async u=>{if(s.signal.aborted)return;let p={relatedRequestId:t.id};i&&(p.relatedTask={taskId:i}),await this.notification(u,p)},sendRequest:async(u,p,m)=>{if(s.signal.aborted)throw new j(A.ConnectionClosed,"Request was cancelled");let f={...m,relatedRequestId:t.id};i&&!f.relatedTask&&(f.relatedTask={taskId:i});let h=f.relatedTask?.taskId??i;return h&&c&&await c.updateTaskStatus(h,"input_required"),await this.request(u,p,f)},authInfo:r?.authInfo,requestId:t.id,requestInfo:r?.requestInfo,taskId:i,taskStore:c,taskRequestedTtl:a?.ttl,closeSSEStream:r?.closeSSEStream,closeStandaloneSSEStream:r?.closeStandaloneSSEStream};Promise.resolve().then(()=>{a&&this.assertTaskHandlerCapability(t.method)}).then(()=>n(t,d)).then(async u=>{if(s.signal.aborted)return;let p={result:u,jsonrpc:"2.0",id:t.id};i&&this._taskMessageQueue?await this._enqueueTaskMessage(i,{type:"response",message:p,timestamp:Date.now()},o?.sessionId):await o?.send(p)},async u=>{if(s.signal.aborted)return;let p={jsonrpc:"2.0",id:t.id,error:{code:Number.isSafeInteger(u.code)?u.code:A.InternalError,message:u.message??"Internal error",...u.data!==void 0&&{data:u.data}}};i&&this._taskMessageQueue?await this._enqueueTaskMessage(i,{type:"error",message:p,timestamp:Date.now()},o?.sessionId):await o?.send(p)}).catch(u=>this._onerror(new Error(`Failed to send response: ${u}`))).finally(()=>{this._requestHandlerAbortControllers.get(t.id)===s&&this._requestHandlerAbortControllers.delete(t.id)})}_onprogress(t){let{progressToken:r,...n}=t.params,o=Number(r),i=this._progressHandlers.get(o);if(!i){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(t)}`));return}let s=this._responseHandlers.get(o),a=this._timeoutInfo.get(o);if(a&&s&&a.resetTimeoutOnProgress)try{this._resetTimeout(o)}catch(c){this._responseHandlers.delete(o),this._progressHandlers.delete(o),this._cleanupTimeout(o),s(c);return}i(n)}_onresponse(t){let r=Number(t.id),n=this._requestResolvers.get(r);if(n){if(this._requestResolvers.delete(r),Gn(t))n(t);else{let s=new j(t.error.code,t.error.message,t.error.data);n(s)}return}let o=this._responseHandlers.get(r);if(o===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(t)}`));return}this._responseHandlers.delete(r),this._cleanupTimeout(r);let i=!1;if(Gn(t)&&t.result&&typeof t.result=="object"){let s=t.result;if(s.task&&typeof s.task=="object"){let a=s.task;typeof a.taskId=="string"&&(i=!0,this._taskProgressTokens.set(a.taskId,r))}}if(i||this._progressHandlers.delete(r),Gn(t))o(t);else{let s=j.fromError(t.error.code,t.error.message,t.error.data);o(s)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(t,r,n){let{task:o}=n??{};if(!o){try{yield{type:"result",result:await this.request(t,r,n)}}catch(s){yield{type:"error",error:s instanceof j?s:new j(A.InternalError,String(s))}}return}let i;try{let s=await this.request(t,on,n);if(s.task)i=s.task.taskId,yield{type:"taskCreated",task:s.task};else throw new j(A.InternalError,"Task creation did not return a task");for(;;){let a=await this.getTask({taskId:i},n);if(yield{type:"taskStatus",task:a},Kt(a.status)){a.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:i},r,n)}:a.status==="failed"?yield{type:"error",error:new j(A.InternalError,`Task ${i} failed`)}:a.status==="cancelled"&&(yield{type:"error",error:new j(A.InternalError,`Task ${i} was cancelled`)});return}if(a.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:i},r,n)};return}let c=a.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(d=>setTimeout(d,c)),n?.signal?.throwIfAborted()}}catch(s){yield{type:"error",error:s instanceof j?s:new j(A.InternalError,String(s))}}}request(t,r,n){let{relatedRequestId:o,resumptionToken:i,onresumptiontoken:s,task:a,relatedTask:c}=n??{};return new Promise((d,u)=>{let p=w=>{u(w)};if(!this._transport){p(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(t.method),a&&this.assertTaskCapability(t.method)}catch(w){p(w);return}n?.signal?.throwIfAborted();let m=this._requestMessageId++,f={...t,jsonrpc:"2.0",id:m};n?.onprogress&&(this._progressHandlers.set(m,n.onprogress),f.params={...t.params,_meta:{...t.params?._meta||{},progressToken:m}}),a&&(f.params={...f.params,task:a}),c&&(f.params={...f.params,_meta:{...f.params?._meta||{},[Gt]:c}});let h=w=>{this._responseHandlers.delete(m),this._progressHandlers.delete(m),this._cleanupTimeout(m),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:m,reason:String(w)}},{relatedRequestId:o,resumptionToken:i,onresumptiontoken:s}).catch(O=>this._onerror(new Error(`Failed to send cancellation: ${O}`)));let k=w instanceof j?w:new j(A.RequestTimeout,String(w));u(k)};this._responseHandlers.set(m,w=>{if(!n?.signal?.aborted){if(w instanceof Error)return u(w);try{let k=Bt(r,w.result);k.success?d(k.data):u(k.error)}catch(k){u(k)}}}),n?.signal?.addEventListener("abort",()=>{h(n?.signal?.reason)});let g=n?.timeout??eS,y=()=>h(j.fromError(A.RequestTimeout,"Request timed out",{timeout:g}));this._setupTimeout(m,g,n?.maxTotalTimeout,y,n?.resetTimeoutOnProgress??!1);let v=c?.taskId;if(v){let w=k=>{let O=this._responseHandlers.get(m);O?O(k):this._onerror(new Error(`Response handler missing for side-channeled request ${m}`))};this._requestResolvers.set(m,w),this._enqueueTaskMessage(v,{type:"request",message:f,timestamp:Date.now()}).catch(k=>{this._cleanupTimeout(m),u(k)})}else this._transport.send(f,{relatedRequestId:o,resumptionToken:i,onresumptiontoken:s}).catch(w=>{this._cleanupTimeout(m),u(w)})})}async getTask(t,r){return this.request({method:"tasks/get",params:t},Ri,r)}async getTaskResult(t,r,n){return this.request({method:"tasks/result",params:t},r,n)}async listTasks(t,r){return this.request({method:"tasks/list",params:t},ji,r)}async cancelTask(t,r){return this.request({method:"tasks/cancel",params:t},hf,r)}async notification(t,r){if(!this._transport)throw new Error("Not connected");this.assertNotificationCapability(t.method);let n=r?.relatedTask?.taskId;if(n){let a={...t,jsonrpc:"2.0",params:{...t.params,_meta:{...t.params?._meta||{},[Gt]:r.relatedTask}}};await this._enqueueTaskMessage(n,{type:"notification",message:a,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(t.method)&&!t.params&&!r?.relatedRequestId&&!r?.relatedTask){if(this._pendingDebouncedNotifications.has(t.method))return;this._pendingDebouncedNotifications.add(t.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(t.method),!this._transport)return;let a={...t,jsonrpc:"2.0"};r?.relatedTask&&(a={...a,params:{...a.params,_meta:{...a.params?._meta||{},[Gt]:r.relatedTask}}}),this._transport?.send(a,r).catch(c=>this._onerror(c))});return}let s={...t,jsonrpc:"2.0"};r?.relatedTask&&(s={...s,params:{...s.params,_meta:{...s.params?._meta||{},[Gt]:r.relatedTask}}}),await this._transport.send(s,r)}setRequestHandler(t,r){let n=$d(t);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(o,i)=>{let s=zd(t,o);return Promise.resolve(r(s,i))})}removeRequestHandler(t){this._requestHandlers.delete(t)}assertCanSetRequestHandler(t){if(this._requestHandlers.has(t))throw new Error(`A request handler for ${t} already exists, which would be overridden`)}setNotificationHandler(t,r){let n=$d(t);this._notificationHandlers.set(n,o=>{let i=zd(t,o);return Promise.resolve(r(i))})}removeNotificationHandler(t){this._notificationHandlers.delete(t)}_cleanupTaskProgressHandler(t){let r=this._taskProgressTokens.get(t);r!==void 0&&(this._progressHandlers.delete(r),this._taskProgressTokens.delete(t))}async _enqueueTaskMessage(t,r,n){if(!this._taskStore||!this._taskMessageQueue)throw new Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");let o=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(t,r,n,o)}async _clearTaskQueue(t,r){if(this._taskMessageQueue){let n=await this._taskMessageQueue.dequeueAll(t,r);for(let o of n)if(o.type==="request"&&id(o.message)){let i=o.message.id,s=this._requestResolvers.get(i);s?(s(new j(A.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(i)):this._onerror(new Error(`Resolver missing for request ${i} during task ${t} cleanup`))}}}async _waitForTaskUpdate(t,r){let n=this._options?.defaultTaskPollInterval??1e3;try{let o=await this._taskStore?.getTask(t);o?.pollInterval&&(n=o.pollInterval)}catch{}return new Promise((o,i)=>{if(r.aborted){i(new j(A.InvalidRequest,"Request cancelled"));return}let s=setTimeout(o,n);r.addEventListener("abort",()=>{clearTimeout(s),i(new j(A.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(t,r){let n=this._taskStore;if(!n)throw new Error("No task store configured");return{createTask:async o=>{if(!t)throw new Error("No request provided");return await n.createTask(o,t.id,{method:t.method,params:t.params},r)},getTask:async o=>{let i=await n.getTask(o,r);if(!i)throw new j(A.InvalidParams,"Failed to retrieve task: Task not found");return i},storeTaskResult:async(o,i,s)=>{await n.storeTaskResult(o,i,s,r);let a=await n.getTask(o,r);if(a){let c=eo.parse({method:"notifications/tasks/status",params:a});await this.notification(c),Kt(a.status)&&this._cleanupTaskProgressHandler(o)}},getTaskResult:o=>n.getTaskResult(o,r),updateTaskStatus:async(o,i,s)=>{let a=await n.getTask(o,r);if(!a)throw new j(A.InvalidParams,`Task "${o}" not found - it may have been cleaned up`);if(Kt(a.status))throw new j(A.InvalidParams,`Cannot update task "${o}" from terminal status "${a.status}" to "${i}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await n.updateTaskStatus(o,i,s,r);let c=await n.getTask(o,r);if(c){let d=eo.parse({method:"notifications/tasks/status",params:c});await this.notification(d),Kt(c.status)&&this._cleanupTaskProgressHandler(o)}},listTasks:o=>n.listTasks(o,r)}}};function th(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function rh(e,t){let r={...e};for(let n in t){let o=n,i=t[o];if(i===void 0)continue;let s=r[o];th(s)&&th(i)?r[o]={...s,...i}:r[o]=i}return r}var Zy=sp(ll(),1),Jy=sp(Uy(),1);function FP(){let e=new Zy.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,Jy.default)(e),e}var Ts=class{constructor(t){this._ajv=t??FP()}getValidator(t){let r="$id"in t&&typeof t.$id=="string"?this._ajv.getSchema(t.$id)??this._ajv.compile(t):this._ajv.compile(t);return n=>r(n)?{valid:!0,data:n,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(r.errors)}}};var Ps=class{constructor(t){this._server=t}requestStream(t,r,n){return this._server.requestStream(t,r,n)}createMessageStream(t,r){let n=this._server.getClientCapabilities();if((t.tools||t.toolChoice)&&!n?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(t.messages.length>0){let o=t.messages[t.messages.length-1],i=Array.isArray(o.content)?o.content:[o.content],s=i.some(u=>u.type==="tool_result"),a=t.messages.length>1?t.messages[t.messages.length-2]:void 0,c=a?Array.isArray(a.content)?a.content:[a.content]:[],d=c.some(u=>u.type==="tool_use");if(s){if(i.some(u=>u.type!=="tool_result"))throw new Error("The last message must contain only tool_result content if any is present");if(!d)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(d){let u=new Set(c.filter(m=>m.type==="tool_use").map(m=>m.id)),p=new Set(i.filter(m=>m.type==="tool_result").map(m=>m.toolUseId));if(u.size!==p.size||![...u].every(m=>p.has(m)))throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return this.requestStream({method:"sampling/createMessage",params:t},no,r)}elicitInputStream(t,r){let n=this._server.getClientCapabilities(),o=t.mode??"form";switch(o){case"url":{if(!n?.elicitation?.url)throw new Error("Client does not support url elicitation.");break}case"form":{if(!n?.elicitation?.form)throw new Error("Client does not support form elicitation.");break}}let i=o==="form"&&t.mode===void 0?{...t,mode:"form"}:t;return this.requestStream({method:"elicitation/create",params:i},un,r)}async getTask(t,r){return this._server.getTask({taskId:t},r)}async getTaskResult(t,r,n){return this._server.getTaskResult({taskId:t},r,n)}async listTasks(t,r){return this._server.listTasks(t?{cursor:t}:void 0,r)}async cancelTask(t,r){return this._server.cancelTask({taskId:t},r)}};function Fy(e,t,r){if(!e)throw new Error(`${r} does not support task creation (required for ${t})`);switch(t){case"tools/call":if(!e.tools?.call)throw new Error(`${r} does not support task creation for tools/call (required for ${t})`);break;default:break}}function Vy(e,t,r){if(!e)throw new Error(`${r} does not support task creation (required for ${t})`);switch(t){case"sampling/createMessage":if(!e.sampling?.createMessage)throw new Error(`${r} does not support task creation for sampling/createMessage (required for ${t})`);break;case"elicitation/create":if(!e.elicitation?.create)throw new Error(`${r} does not support task creation for elicitation/create (required for ${t})`);break;default:break}}var Rs=class extends Fi{constructor(t,r){super(r),this._serverInfo=t,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(ro.options.map((n,o)=>[n,o])),this.isMessageIgnored=(n,o)=>{let i=this._loggingLevels.get(o);return i?this.LOG_LEVEL_SEVERITY.get(n)<this.LOG_LEVEL_SEVERITY.get(i):!1},this._capabilities=r?.capabilities??{},this._instructions=r?.instructions,this._jsonSchemaValidator=r?.jsonSchemaValidator??new Ts,this.setRequestHandler(cd,n=>this._oninitialize(n)),this.setNotificationHandler(dd,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(gd,async(n,o)=>{let i=o.sessionId||o.requestInfo?.headers["mcp-session-id"]||void 0,{level:s}=n.params,a=ro.safeParse(s);return a.success&&this._loggingLevels.set(i,a.data),{}})}get experimental(){return this._experimental||(this._experimental={tasks:new Ps(this)}),this._experimental}registerCapabilities(t){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=rh(this._capabilities,t)}setRequestHandler(t,r){let o=Ht(t)?.method;if(!o)throw new Error("Schema is missing a method literal");let i;if(et(o)){let a=o;i=a._zod?.def?.value??a.value}else{let a=o;i=a._def?.value??a.value}if(typeof i!="string")throw new Error("Schema method literal must be a string");if(i==="tools/call"){let a=async(c,d)=>{let u=Bt(dn,c);if(!u.success){let h=u.error instanceof Error?u.error.message:String(u.error);throw new j(A.InvalidParams,`Invalid tools/call request: ${h}`)}let{params:p}=u.data,m=await Promise.resolve(r(c,d));if(p.task){let h=Bt(on,m);if(!h.success){let g=h.error instanceof Error?h.error.message:String(h.error);throw new j(A.InvalidParams,`Invalid task creation result: ${g}`)}return h.data}let f=Bt(Di,m);if(!f.success){let h=f.error instanceof Error?f.error.message:String(f.error);throw new j(A.InvalidParams,`Invalid tools/call result: ${h}`)}return f.data};return super.setRequestHandler(t,a)}return super.setRequestHandler(t,r)}assertCapabilityForMethod(t){switch(t){case"sampling/createMessage":if(!this._clientCapabilities?.sampling)throw new Error(`Client does not support sampling (required for ${t})`);break;case"elicitation/create":if(!this._clientCapabilities?.elicitation)throw new Error(`Client does not support elicitation (required for ${t})`);break;case"roots/list":if(!this._clientCapabilities?.roots)throw new Error(`Client does not support listing roots (required for ${t})`);break;case"ping":break}}assertNotificationCapability(t){switch(t){case"notifications/message":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${t})`);break;case"notifications/resources/updated":case"notifications/resources/list_changed":if(!this._capabilities.resources)throw new Error(`Server does not support notifying about resources (required for ${t})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw new Error(`Server does not support notifying of tool list changes (required for ${t})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw new Error(`Server does not support notifying of prompt list changes (required for ${t})`);break;case"notifications/elicitation/complete":if(!this._clientCapabilities?.elicitation?.url)throw new Error(`Client does not support URL elicitation (required for ${t})`);break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(t){if(this._capabilities)switch(t){case"completion/complete":if(!this._capabilities.completions)throw new Error(`Server does not support completions (required for ${t})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${t})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw new Error(`Server does not support prompts (required for ${t})`);break;case"resources/list":case"resources/templates/list":case"resources/read":if(!this._capabilities.resources)throw new Error(`Server does not support resources (required for ${t})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw new Error(`Server does not support tools (required for ${t})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw new Error(`Server does not support tasks capability (required for ${t})`);break;case"ping":case"initialize":break}}assertTaskCapability(t){Vy(this._clientCapabilities?.tasks?.requests,t,"Client")}assertTaskHandlerCapability(t){this._capabilities&&Fy(this._capabilities.tasks?.requests,t,"Server")}async _oninitialize(t){let r=t.params.protocolVersion;return this._clientCapabilities=t.params.capabilities,this._clientVersion=t.params.clientInfo,{protocolVersion:of.includes(r)?r:nd,capabilities:this.getCapabilities(),serverInfo:this._serverInfo,...this._instructions&&{instructions:this._instructions}}}getClientCapabilities(){return this._clientCapabilities}getClientVersion(){return this._clientVersion}getCapabilities(){return this._capabilities}async ping(){return this.request({method:"ping"},Si)}async createMessage(t,r){if((t.tools||t.toolChoice)&&!this._clientCapabilities?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(t.messages.length>0){let n=t.messages[t.messages.length-1],o=Array.isArray(n.content)?n.content:[n.content],i=o.some(d=>d.type==="tool_result"),s=t.messages.length>1?t.messages[t.messages.length-2]:void 0,a=s?Array.isArray(s.content)?s.content:[s.content]:[],c=a.some(d=>d.type==="tool_use");if(i){if(o.some(d=>d.type!=="tool_result"))throw new Error("The last message must contain only tool_result content if any is present");if(!c)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(c){let d=new Set(a.filter(p=>p.type==="tool_use").map(p=>p.id)),u=new Set(o.filter(p=>p.type==="tool_result").map(p=>p.toolUseId));if(d.size!==u.size||![...d].every(p=>u.has(p)))throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return t.tools?this.request({method:"sampling/createMessage",params:t},yd,r):this.request({method:"sampling/createMessage",params:t},no,r)}async elicitInput(t,r){switch(t.mode??"form"){case"url":{if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support url elicitation.");let o=t;return this.request({method:"elicitation/create",params:o},un,r)}case"form":{if(!this._clientCapabilities?.elicitation?.form)throw new Error("Client does not support form elicitation.");let o=t.mode==="form"?t:{...t,mode:"form"},i=await this.request({method:"elicitation/create",params:o},un,r);if(i.action==="accept"&&i.content&&o.requestedSchema)try{let a=this._jsonSchemaValidator.getValidator(o.requestedSchema)(i.content);if(!a.valid)throw new j(A.InvalidParams,`Elicitation response content does not match requested schema: ${a.errorMessage}`)}catch(s){throw s instanceof j?s:new j(A.InternalError,`Error validating elicitation response: ${s instanceof Error?s.message:String(s)}`)}return i}}}createElicitationCompletionNotifier(t,r){if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support URL elicitation (required for notifications/elicitation/complete)");return()=>this.notification({method:"notifications/elicitation/complete",params:{elicitationId:t}},r)}async listRoots(t,r){return this.request({method:"roots/list",params:t},_d,r)}async sendLoggingMessage(t,r){if(this._capabilities.logging&&!this.isMessageIgnored(t.level,r))return this.notification({method:"notifications/message",params:t})}async sendResourceUpdated(t){return this.notification({method:"notifications/resources/updated",params:t})}async sendResourceListChanged(){return this.notification({method:"notifications/resources/list_changed"})}async sendToolListChanged(){return this.notification({method:"notifications/tools/list_changed"})}async sendPromptListChanged(){return this.notification({method:"notifications/prompts/list_changed"})}};var By=Symbol.for("mcp.completable");function bl(e){return!!e&&typeof e=="object"&&By in e}function Hy(e){return e[By]?.complete}var Wy;(function(e){e.Completable="McpCompletable"})(Wy||(Wy={}));var VP=/^[A-Za-z0-9._-]{1,128}$/;function WP(e){let t=[];if(e.length===0)return{isValid:!1,warnings:["Tool name cannot be empty"]};if(e.length>128)return{isValid:!1,warnings:[`Tool name exceeds maximum length of 128 characters (current: ${e.length})`]};if(e.includes(" ")&&t.push("Tool name contains spaces, which may cause parsing issues"),e.includes(",")&&t.push("Tool name contains commas, which may cause parsing issues"),(e.startsWith("-")||e.endsWith("-"))&&t.push("Tool name starts or ends with a dash, which may cause parsing issues in some contexts"),(e.startsWith(".")||e.endsWith("."))&&t.push("Tool name starts or ends with a dot, which may cause parsing issues in some contexts"),!VP.test(e)){let r=e.split("").filter(n=>!/[A-Za-z0-9._-]/.test(n)).filter((n,o,i)=>i.indexOf(n)===o);return t.push(`Tool name contains invalid characters: ${r.map(n=>`"${n}"`).join(", ")}`,"Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)"),{isValid:!1,warnings:t}}return{isValid:!0,warnings:t}}function BP(e,t){if(t.length>0){console.warn(`Tool name validation warning for "${e}":`);for(let r of t)console.warn(` - ${r}`);console.warn("Tool registration will proceed, but this may cause compatibility issues."),console.warn("Consider updating the tool name to conform to the MCP tool naming standard."),console.warn("See SEP: Specify Format for Tool Names (https://github.com/modelcontextprotocol/modelcontextprotocol/issues/986) for more details.")}}function vl(e){let t=WP(e);return BP(e,t.warnings),t.isValid}var Os=class{constructor(t){this._mcpServer=t}registerToolTask(t,r,n){let o={taskSupport:"required",...r.execution};if(o.taskSupport==="forbidden")throw new Error(`Cannot register task-based tool '${t}' with taskSupport 'forbidden'. Use registerTool() instead.`);return this._mcpServer._createRegisteredTool(t,r.title,r.description,r.inputSchema,r.outputSchema,r.annotations,o,r._meta,n)}};var Es=class{constructor(t,r){this._registeredResources={},this._registeredResourceTemplates={},this._registeredTools={},this._registeredPrompts={},this._toolHandlersInitialized=!1,this._completionHandlerInitialized=!1,this._resourceHandlersInitialized=!1,this._promptHandlersInitialized=!1,this.server=new Rs(t,r)}get experimental(){return this._experimental||(this._experimental={tasks:new Os(this)}),this._experimental}async connect(t){return await this.server.connect(t)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||(this.server.assertCanSetRequestHandler(ir(Ni)),this.server.assertCanSetRequestHandler(ir(dn)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(Ni,()=>({tools:Object.entries(this._registeredTools).filter(([,t])=>t.enabled).map(([t,r])=>{let n={name:t,title:r.title,description:r.description,inputSchema:(()=>{let o=rn(r.inputSchema);return o?Sd(o,{strictUnions:!0,pipeStrategy:"input"}):HP})(),annotations:r.annotations,execution:r.execution,_meta:r._meta};if(r.outputSchema){let o=rn(r.outputSchema);o&&(n.outputSchema=Sd(o,{strictUnions:!0,pipeStrategy:"output"}))}return n})})),this.server.setRequestHandler(dn,async(t,r)=>{try{let n=this._registeredTools[t.params.name];if(!n)throw new j(A.InvalidParams,`Tool ${t.params.name} not found`);if(!n.enabled)throw new j(A.InvalidParams,`Tool ${t.params.name} disabled`);let o=!!t.params.task,i=n.execution?.taskSupport,s="createTask"in n.handler;if((i==="required"||i==="optional")&&!s)throw new j(A.InternalError,`Tool ${t.params.name} has taskSupport '${i}' but was not registered with registerToolTask`);if(i==="required"&&!o)throw new j(A.MethodNotFound,`Tool ${t.params.name} requires task augmentation (taskSupport: 'required')`);if(i==="optional"&&!o&&s)return await this.handleAutomaticTaskPolling(n,t,r);let a=await this.validateToolInput(n,t.params.arguments,t.params.name),c=await this.executeToolHandler(n,a,r);return o||await this.validateToolOutput(n,c,t.params.name),c}catch(n){if(n instanceof j&&n.code===A.UrlElicitationRequired)throw n;return this.createToolError(n instanceof Error?n.message:String(n))}}),this._toolHandlersInitialized=!0)}createToolError(t){return{content:[{type:"text",text:t}],isError:!0}}async validateToolInput(t,r,n){if(!t.inputSchema)return;let i=rn(t.inputSchema)??t.inputSchema,s=await gi(i,r);if(!s.success){let a="error"in s?s.error:"Unknown error",c=yi(a);throw new j(A.InvalidParams,`Input validation error: Invalid arguments for tool ${n}: ${c}`)}return s.data}async validateToolOutput(t,r,n){if(!t.outputSchema||!("content"in r)||r.isError)return;if(!r.structuredContent)throw new j(A.InvalidParams,`Output validation error: Tool ${n} has an output schema but no structured content was provided`);let o=rn(t.outputSchema),i=await gi(o,r.structuredContent);if(!i.success){let s="error"in i?i.error:"Unknown error",a=yi(s);throw new j(A.InvalidParams,`Output validation error: Invalid structured content for tool ${n}: ${a}`)}}async executeToolHandler(t,r,n){let o=t.handler;if("createTask"in o){if(!n.taskStore)throw new Error("No task store provided.");let s={...n,taskStore:n.taskStore};if(t.inputSchema){let a=o;return await Promise.resolve(a.createTask(r,s))}else{let a=o;return await Promise.resolve(a.createTask(s))}}if(t.inputSchema){let s=o;return await Promise.resolve(s(r,n))}else{let s=o;return await Promise.resolve(s(n))}}async handleAutomaticTaskPolling(t,r,n){if(!n.taskStore)throw new Error("No task store provided for task-capable tool.");let o=await this.validateToolInput(t,r.params.arguments,r.params.name),i=t.handler,s={...n,taskStore:n.taskStore},a=o?await Promise.resolve(i.createTask(o,s)):await Promise.resolve(i.createTask(s)),c=a.task.taskId,d=a.task,u=d.pollInterval??5e3;for(;d.status!=="completed"&&d.status!=="failed"&&d.status!=="cancelled";){await new Promise(m=>setTimeout(m,u));let p=await n.taskStore.getTask(c);if(!p)throw new j(A.InternalError,`Task ${c} not found during polling`);d=p}return await n.taskStore.getTaskResult(c)}setCompletionRequestHandler(){this._completionHandlerInitialized||(this.server.assertCanSetRequestHandler(ir(Li)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(Li,async t=>{switch(t.params.ref.type){case"ref/prompt":return wf(t),this.handlePromptCompletion(t,t.params.ref);case"ref/resource":return kf(t),this.handleResourceCompletion(t,t.params.ref);default:throw new j(A.InvalidParams,`Invalid completion reference: ${t.params.ref}`)}}),this._completionHandlerInitialized=!0)}async handlePromptCompletion(t,r){let n=this._registeredPrompts[r.name];if(!n)throw new j(A.InvalidParams,`Prompt ${r.name} not found`);if(!n.enabled)throw new j(A.InvalidParams,`Prompt ${r.name} disabled`);if(!n.argsSchema)return Ao;let i=Ht(n.argsSchema)?.[t.params.argument.name];if(!bl(i))return Ao;let s=Hy(i);if(!s)return Ao;let a=await s(t.params.argument.value,t.params.context);return Ky(a)}async handleResourceCompletion(t,r){let n=Object.values(this._registeredResourceTemplates).find(s=>s.resourceTemplate.uriTemplate.toString()===r.uri);if(!n){if(this._registeredResources[r.uri])return Ao;throw new j(A.InvalidParams,`Resource template ${t.params.ref.uri} not found`)}let o=n.resourceTemplate.completeCallback(t.params.argument.name);if(!o)return Ao;let i=await o(t.params.argument.value,t.params.context);return Ky(i)}setResourceRequestHandlers(){this._resourceHandlersInitialized||(this.server.assertCanSetRequestHandler(ir(an)),this.server.assertCanSetRequestHandler(ir(cn)),this.server.assertCanSetRequestHandler(ir(Ci)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(an,async(t,r)=>{let n=Object.entries(this._registeredResources).filter(([i,s])=>s.enabled).map(([i,s])=>({uri:i,name:s.name,...s.metadata})),o=[];for(let i of Object.values(this._registeredResourceTemplates)){if(!i.resourceTemplate.listCallback)continue;let s=await i.resourceTemplate.listCallback(r);for(let a of s.resources)o.push({...i.metadata,...a})}return{resources:[...n,...o]}}),this.server.setRequestHandler(cn,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([r,n])=>({name:r,uriTemplate:n.resourceTemplate.uriTemplate.toString(),...n.metadata}))})),this.server.setRequestHandler(Ci,async(t,r)=>{let n=new URL(t.params.uri),o=this._registeredResources[n.toString()];if(o){if(!o.enabled)throw new j(A.InvalidParams,`Resource ${n} disabled`);return o.readCallback(n,r)}for(let i of Object.values(this._registeredResourceTemplates)){let s=i.resourceTemplate.uriTemplate.match(n.toString());if(s)return i.readCallback(n,s,r)}throw new j(A.InvalidParams,`Resource ${n} not found`)}),this._resourceHandlersInitialized=!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||(this.server.assertCanSetRequestHandler(ir(Ai)),this.server.assertCanSetRequestHandler(ir(Mi)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(Ai,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,t])=>t.enabled).map(([t,r])=>({name:t,title:r.title,description:r.description,arguments:r.argsSchema?GP(r.argsSchema):void 0}))})),this.server.setRequestHandler(Mi,async(t,r)=>{let n=this._registeredPrompts[t.params.name];if(!n)throw new j(A.InvalidParams,`Prompt ${t.params.name} not found`);if(!n.enabled)throw new j(A.InvalidParams,`Prompt ${t.params.name} disabled`);if(n.argsSchema){let o=rn(n.argsSchema),i=await gi(o,t.params.arguments);if(!i.success){let c="error"in i?i.error:"Unknown error",d=yi(c);throw new j(A.InvalidParams,`Invalid arguments for prompt ${t.params.name}: ${d}`)}let s=i.data,a=n.callback;return await Promise.resolve(a(s,r))}else{let o=n.callback;return await Promise.resolve(o(r))}}),this._promptHandlersInitialized=!0)}resource(t,r,...n){let o;typeof n[0]=="object"&&(o=n.shift());let i=n[0];if(typeof r=="string"){if(this._registeredResources[r])throw new Error(`Resource ${r} is already registered`);let s=this._createRegisteredResource(t,void 0,r,o,i);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),s}else{if(this._registeredResourceTemplates[t])throw new Error(`Resource template ${t} is already registered`);let s=this._createRegisteredResourceTemplate(t,void 0,r,o,i);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),s}}registerResource(t,r,n,o){if(typeof r=="string"){if(this._registeredResources[r])throw new Error(`Resource ${r} is already registered`);let i=this._createRegisteredResource(t,n.title,r,n,o);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}else{if(this._registeredResourceTemplates[t])throw new Error(`Resource template ${t} is already registered`);let i=this._createRegisteredResourceTemplate(t,n.title,r,n,o);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}}_createRegisteredResource(t,r,n,o,i){let s={name:t,title:r,metadata:o,readCallback:i,enabled:!0,disable:()=>s.update({enabled:!1}),enable:()=>s.update({enabled:!0}),remove:()=>s.update({uri:null}),update:a=>{typeof a.uri<"u"&&a.uri!==n&&(delete this._registeredResources[n],a.uri&&(this._registeredResources[a.uri]=s)),typeof a.name<"u"&&(s.name=a.name),typeof a.title<"u"&&(s.title=a.title),typeof a.metadata<"u"&&(s.metadata=a.metadata),typeof a.callback<"u"&&(s.readCallback=a.callback),typeof a.enabled<"u"&&(s.enabled=a.enabled),this.sendResourceListChanged()}};return this._registeredResources[n]=s,s}_createRegisteredResourceTemplate(t,r,n,o,i){let s={resourceTemplate:n,title:r,metadata:o,readCallback:i,enabled:!0,disable:()=>s.update({enabled:!1}),enable:()=>s.update({enabled:!0}),remove:()=>s.update({name:null}),update:d=>{typeof d.name<"u"&&d.name!==t&&(delete this._registeredResourceTemplates[t],d.name&&(this._registeredResourceTemplates[d.name]=s)),typeof d.title<"u"&&(s.title=d.title),typeof d.template<"u"&&(s.resourceTemplate=d.template),typeof d.metadata<"u"&&(s.metadata=d.metadata),typeof d.callback<"u"&&(s.readCallback=d.callback),typeof d.enabled<"u"&&(s.enabled=d.enabled),this.sendResourceListChanged()}};this._registeredResourceTemplates[t]=s;let a=n.uriTemplate.variableNames;return Array.isArray(a)&&a.some(d=>!!n.completeCallback(d))&&this.setCompletionRequestHandler(),s}_createRegisteredPrompt(t,r,n,o,i){let s={title:r,description:n,argsSchema:o===void 0?void 0:Pr(o),callback:i,enabled:!0,disable:()=>s.update({enabled:!1}),enable:()=>s.update({enabled:!0}),remove:()=>s.update({name:null}),update:a=>{typeof a.name<"u"&&a.name!==t&&(delete this._registeredPrompts[t],a.name&&(this._registeredPrompts[a.name]=s)),typeof a.title<"u"&&(s.title=a.title),typeof a.description<"u"&&(s.description=a.description),typeof a.argsSchema<"u"&&(s.argsSchema=Pr(a.argsSchema)),typeof a.callback<"u"&&(s.callback=a.callback),typeof a.enabled<"u"&&(s.enabled=a.enabled),this.sendPromptListChanged()}};return this._registeredPrompts[t]=s,o&&Object.values(o).some(c=>{let d=c instanceof Le?c._def?.innerType:c;return bl(d)})&&this.setCompletionRequestHandler(),s}_createRegisteredTool(t,r,n,o,i,s,a,c,d){vl(t);let u={title:r,description:n,inputSchema:Gy(o),outputSchema:Gy(i),annotations:s,execution:a,_meta:c,handler:d,enabled:!0,disable:()=>u.update({enabled:!1}),enable:()=>u.update({enabled:!0}),remove:()=>u.update({name:null}),update:p=>{typeof p.name<"u"&&p.name!==t&&(typeof p.name=="string"&&vl(p.name),delete this._registeredTools[t],p.name&&(this._registeredTools[p.name]=u)),typeof p.title<"u"&&(u.title=p.title),typeof p.description<"u"&&(u.description=p.description),typeof p.paramsSchema<"u"&&(u.inputSchema=Pr(p.paramsSchema)),typeof p.outputSchema<"u"&&(u.outputSchema=Pr(p.outputSchema)),typeof p.callback<"u"&&(u.handler=p.callback),typeof p.annotations<"u"&&(u.annotations=p.annotations),typeof p._meta<"u"&&(u._meta=p._meta),typeof p.enabled<"u"&&(u.enabled=p.enabled),this.sendToolListChanged()}};return this._registeredTools[t]=u,this.setToolRequestHandlers(),this.sendToolListChanged(),u}tool(t,...r){if(this._registeredTools[t])throw new Error(`Tool ${t} is already registered`);let n,o,i,s;if(typeof r[0]=="string"&&(n=r.shift()),r.length>1){let c=r[0];if(wl(c))o=r.shift(),r.length>1&&typeof r[0]=="object"&&r[0]!==null&&!wl(r[0])&&(s=r.shift());else if(typeof c=="object"&&c!==null){if(Object.values(c).some(d=>typeof d=="object"&&d!==null))throw new Error(`Tool ${t} expected a Zod schema or ToolAnnotations, but received an unrecognized object`);s=r.shift()}}let a=r[0];return this._createRegisteredTool(t,void 0,n,o,i,s,{taskSupport:"forbidden"},void 0,a)}registerTool(t,r,n){if(this._registeredTools[t])throw new Error(`Tool ${t} is already registered`);let{title:o,description:i,inputSchema:s,outputSchema:a,annotations:c,_meta:d}=r;return this._createRegisteredTool(t,o,i,s,a,c,{taskSupport:"forbidden"},d,n)}prompt(t,...r){if(this._registeredPrompts[t])throw new Error(`Prompt ${t} is already registered`);let n;typeof r[0]=="string"&&(n=r.shift());let o;r.length>1&&(o=r.shift());let i=r[0],s=this._createRegisteredPrompt(t,void 0,n,o,i);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),s}registerPrompt(t,r,n){if(this._registeredPrompts[t])throw new Error(`Prompt ${t} is already registered`);let{title:o,description:i,argsSchema:s}=r,a=this._createRegisteredPrompt(t,o,i,s,n);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),a}isConnected(){return this.server.transport!==void 0}async sendLoggingMessage(t,r){return this.server.sendLoggingMessage(t,r)}sendResourceListChanged(){this.isConnected()&&this.server.sendResourceListChanged()}sendToolListChanged(){this.isConnected()&&this.server.sendToolListChanged()}sendPromptListChanged(){this.isConnected()&&this.server.sendPromptListChanged()}};var HP={type:"object",properties:{}};function Qy(e){return e!==null&&typeof e=="object"&&"parse"in e&&typeof e.parse=="function"&&"safeParse"in e&&typeof e.safeParse=="function"}function Yy(e){return"_def"in e||"_zod"in e||Qy(e)}function wl(e){return typeof e!="object"||e===null||Yy(e)?!1:Object.keys(e).length===0?!0:Object.values(e).some(Qy)}function Gy(e){if(e){if(wl(e))return Pr(e);if(!Yy(e))throw new Error("inputSchema must be a Zod schema or raw shape, received an unrecognized object");return e}}function GP(e){let t=Ht(e);return t?Object.entries(t).map(([r,n])=>{let o=Cm(n),i=Am(n);return{name:r,description:o,required:!i}}):[]}function ir(e){let r=Ht(e)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=_i(r);if(typeof n=="string")return n;throw new Error("Schema method literal must be a string")}function Ky(e){return{completion:{values:e.slice(0,100),total:e.length,hasMore:e.length>100}}}var Ao={completion:{values:[],hasMore:!1}};import e_ from"node:process";var js=class{append(t){this._buffer=this._buffer?Buffer.concat([this._buffer,t]):t}readMessage(){if(!this._buffer)return null;let t=this._buffer.indexOf(`
42
- `);if(t===-1)return null;let r=this._buffer.toString("utf8",0,t).replace(/\r$/,"");return this._buffer=this._buffer.subarray(t+1),KP(r)}clear(){this._buffer=void 0}};function KP(e){return mf.parse(JSON.parse(e))}function Xy(e){return JSON.stringify(e)+`
43
- `}var Is=class{constructor(t=e_.stdin,r=e_.stdout){this._stdin=t,this._stdout=r,this._readBuffer=new js,this._started=!1,this._ondata=n=>{this._readBuffer.append(n),this.processReadBuffer()},this._onerror=n=>{this.onerror?.(n)}}async start(){if(this._started)throw new Error("StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.");this._started=!0,this._stdin.on("data",this._ondata),this._stdin.on("error",this._onerror)}processReadBuffer(){for(;;)try{let t=this._readBuffer.readMessage();if(t===null)break;this.onmessage?.(t)}catch(t){this.onerror?.(t)}}async close(){this._stdin.off("data",this._ondata),this._stdin.off("error",this._onerror),this._stdin.listenerCount("data")===0&&this._stdin.pause(),this._readBuffer.clear(),this.onclose?.()}send(t){return new Promise(r=>{let n=Xy(t);this._stdout.write(n)?r():this._stdout.once("drain",r)})}};function kl(e){return e.trim()!==""?Buffer.byteLength(e,"utf8")<=2e3:!1}function xl(e){if(typeof e!="object"||e===null||Array.isArray(e))return{TAG:"Error",_0:"topic_quiet_auth_file_invalid"};let t=e.topicWakeTurnCapability;if(t===void 0)return{TAG:"Ok",_0:"none"};if(t===null||Array.isArray(t))return{TAG:"Error",_0:"topic_quiet_capability_invalid"};switch(typeof t){case"string":return t.trim()!==""&&Buffer.byteLength(t,"utf8")<=4096?{TAG:"Ok",_0:"available"}:{TAG:"Error",_0:"topic_quiet_capability_invalid"};case"object":let r=t.custody,n=0;if(typeof r=="string"){if(r==="claimed")return{TAG:"Ok",_0:"claimed"};n=1}else n=1;if(n===1){let o=t.custody,i=0;if(typeof o=="string"){if(o==="attempt_pending")return{TAG:"Ok",_0:"attempt_pending"};i=2}else i=2;if(i===2){let s=t.custody,a=0;if(typeof s=="string"){if(s==="attempt_acknowledged")return{TAG:"Ok",_0:"attempt_acknowledged"};a=3}else a=3;if(a===3){let c=t.custody,d=0;if(typeof c=="string"){if(c==="attempt_failed")return{TAG:"Ok",_0:"attempt_failed"};d=4}else d=4;if(d===4)return t.custody==="quiet_acknowledged"?{TAG:"Ok",_0:"quiet_acknowledged"}:{TAG:"Error",_0:"topic_quiet_capability_invalid"}}}}break;default:return{TAG:"Error",_0:"topic_quiet_capability_invalid"}}}function t_(e,t){return e==="claimed"?t==="attempt_pending"||t==="quiet_acknowledged"||t==="attempt_failed"?{TAG:"Ok",_0:t}:{TAG:"Error",_0:"topic_quiet_custody_transition_refused"}:e==="available"?t==="claimed"?{TAG:"Ok",_0:t}:{TAG:"Error",_0:"topic_quiet_custody_transition_refused"}:e==="quiet_acknowledged"?t==="quiet_acknowledged"?{TAG:"Ok",_0:t}:{TAG:"Error",_0:"topic_quiet_custody_transition_refused"}:e==="attempt_acknowledged"?t==="attempt_pending"?{TAG:"Ok",_0:t}:{TAG:"Error",_0:"topic_quiet_custody_transition_refused"}:e==="attempt_pending"&&(t==="attempt_acknowledged"||t==="attempt_failed")?{TAG:"Ok",_0:t}:{TAG:"Error",_0:"topic_quiet_custody_transition_refused"}}function r_(e,t,r){try{let n=xl(e());if(n.TAG!=="Ok")return{TAG:"Error",_0:n._0};let o=t_(n._0,r);return o.TAG!=="Ok"?{TAG:"Error",_0:o._0}:(t(o._0),{TAG:"Ok",_0:void 0})}catch{return{TAG:"Error",_0:"topic_quiet_custody_write_failed"}}}function n_(e,t,r){try{let n=e(),o=xl(n);if(o.TAG!=="Ok")return{TAG:"Error",_0:o._0};let i=o._0;if(i==="none")return{TAG:"Ok",_0:void 0};if(i!=="available")return{TAG:"Error",_0:"topic_quiet_consumed_capability_launch_refused"};if(typeof n!="object"||n===null||Array.isArray(n))return{TAG:"Error",_0:"topic_quiet_consumed_capability_launch_refused"};let s=n.topicWakeTurnCapability;return typeof s!="string"?{TAG:"Error",_0:"topic_quiet_consumed_capability_launch_refused"}:(t(),r("claimed"),{TAG:"Ok",_0:s})}catch{return{TAG:"Error",_0:"topic_quiet_single_launch_claim_refused"}}}function o_(e){if(typeof e!="object"||e===null||Array.isArray(e))return!1;let t=e.name;if(typeof t!="string"||t!=="linzumi_complete_topic_wake_no_action")return!1;let r=e.arguments;if(typeof r!="object"||r===null||Array.isArray(r))return!1;let n=r.reason;return typeof n=="string"?kl(n):!1}function i_(e){if(typeof e!="object"||e===null||Array.isArray(e))return!1;let t=e.ok;return typeof t!="boolean"||!t?!1:e.completed_without_action===!0}function s_(e,t,r){return t?"closed_after_failure":e?r?"closed_after_quiet":"closed_after_failure":"accepting"}var a_=kl;var c_=r_,d_=n_,u_=o_,Sl=i_,l_=s_;import{hostname as lO}from"node:os";import{randomBytes as P_}from"node:crypto";import{existsSync as Rl,closeSync as As,fsyncSync as Ms,lstatSync as R_,mkdirSync as jR,openSync as Ns,readFileSync as Tn,renameSync as O_,rmSync as E_,writeFileSync as j_}from"node:fs";import{homedir as IR}from"node:os";import{dirname as Ol,join as CR}from"node:path";import{spawn as yR}from"node:child_process";import{randomBytes as _R}from"node:crypto";import{createServer as bR}from"node:http";import{appendFileSync as nR,openSync as I4}from"node:fs";import{homedir as y_}from"node:os";import{dirname as oR,join as __,resolve as iR,sep as sR}from"node:path";import{mkdirSync as aR}from"node:fs";var Tt={_generated:"GENERATED by scripts/naming_dual_emit_codegen.mjs from scripts/naming_canonical_key_map.json (N2.2 dual-emit, D46) - DO NOT EDIT; run: node scripts/naming_dual_emit_codegen.mjs --write",events:[["codex.agent_turn_narration_only_no_reply","harness.agent_turn_narration_only_no_reply"],["codex.cost_cap_402_seen","harness.cost_cap_402_seen"],["codex.edge_blocked_captured","harness.edge_blocked_captured"],["codex.empty_turn_auto_retry_suppressed_cost_cap","harness.empty_turn_auto_retry_suppressed_cost_cap"],["codex.empty_turn_loop_guard_tripped","harness.empty_turn_loop_guard_tripped"],["codex.error_without_http_status_captured","harness.error_without_http_status_captured"],["codex.mid_stream_stall_auto_resume_flagged","harness.mid_stream_stall_auto_resume_flagged"],["codex.mid_stream_stall_fresh_session_resume","harness.mid_stream_stall_fresh_session_resume"],["codex.mid_stream_stall_fresh_session_resume_failed","harness.mid_stream_stall_fresh_session_resume_failed"],["codex.mid_stream_stall_fresh_session_resume_flagged","harness.mid_stream_stall_fresh_session_resume_flagged"],["codex.mid_stream_stall_resume_suppressed_rate_limit","harness.mid_stream_stall_resume_suppressed_rate_limit"],["codex.mid_stream_stall_second_stall_after_resume","harness.mid_stream_stall_second_stall_after_resume"],["codex.pre_first_byte_stall_auto_retry_flagged","harness.pre_first_byte_stall_auto_retry_flagged"],["codex.pre_first_byte_stall_retry_suppressed_cost_cap","harness.pre_first_byte_stall_retry_suppressed_cost_cap"],["codex.provider_outage_flagged_captured","harness.provider_outage_flagged_captured"],["codex.reasoning_loop_breaker_tripped","harness.reasoning_loop_breaker_tripped"],["codex.tool_fatal_captured","harness.tool_fatal_captured"],["codex.turn_completed","job.turn_completed"],["codex.turn_completed_with_protocol_failure","job.turn_completed_with_protocol_failure"],["codex.turn_completed_with_unsupported_tool_call_ignored","job.turn_completed_with_unsupported_tool_call_ignored"],["codex.turn_completed_without_assistant_output","job.turn_completed_without_assistant_output"],["codex.turn_demoted_late_upstream_error","job.turn_demoted_late_upstream_error"],["codex.turn_forward_failed","job.turn_forward_failed"],["codex.upstream_error_captured","harness.upstream_error_captured"],["codex.upstream_rejection_captured","harness.upstream_rejection_captured"],["codex.upstream_turn_error_captured","harness.upstream_turn_error_captured"],["kandan.chat_event","linzumi.chat_event"],["kandan.chat_event_abandoned","linzumi.chat_event_abandoned"],["kandan.chat_event_failed","linzumi.chat_event_failed"],["kandan.chat_event_failure_cleared","linzumi.chat_event_failure_cleared"],["kandan.child_thread_event_failed","linzumi.child_thread_event_failed"],["kandan.child_thread_event_skipped_missing_thread_binding","linzumi.child_thread_event_skipped_missing_thread_binding"],["kandan.child_thread_upsert_failed","linzumi.child_thread_upsert_failed"],["kandan.child_thread_upsert_skipped_missing_thread_binding","linzumi.child_thread_upsert_skipped_missing_thread_binding"],["kandan.claude_code_interrupt_state_push_failed","linzumi.claude_code_interrupt_state_push_failed"],["kandan.claude_code_stop_state_push_failed","linzumi.claude_code_stop_state_push_failed"],["kandan.claude_code_typing_heartbeat_failed","linzumi.claude_code_typing_heartbeat_failed"],["kandan.claude_code_typing_start_wait_timeout","linzumi.claude_code_typing_start_wait_timeout"],["kandan.claude_code_typing_stop_failed","linzumi.claude_code_typing_stop_failed"],["kandan.claude_code_user_input_abort_publish_failed","linzumi.claude_code_user_input_abort_publish_failed"],["kandan.claude_code_user_question_completed_publish_failed","linzumi.claude_code_user_question_completed_publish_failed"],["kandan.codex_command_output_forwarded","linzumi.codex_command_output_forwarded"],["kandan.codex_delta_forwarded","linzumi.codex_delta_forwarded"],["kandan.codex_file_change_forwarded","linzumi.codex_file_change_forwarded"],["kandan.codex_notification_push_failed","linzumi.codex_notification_push_failed"],["kandan.codex_output_forwarded","linzumi.codex_output_forwarded"],["kandan.codex_reasoning_delta_forwarded","linzumi.codex_reasoning_delta_forwarded"],["kandan.codex_web_search_progress_forwarded","linzumi.codex_web_search_progress_forwarded"],["kandan.connection_force_reconnect","linzumi.connection_force_reconnect"],["kandan.connection_force_reconnect_dispatched","linzumi.connection_force_reconnect_dispatched"],["kandan.connection_hard_reset","linzumi.connection_hard_reset"],["kandan.connection_hard_reset_exhausted","linzumi.connection_hard_reset_exhausted"],["kandan.connection_recovered","linzumi.connection_recovered"],["kandan.connection_stale","linzumi.connection_stale"],["kandan.connection_unrecoverable","linzumi.connection_unrecoverable"],["kandan.control","linzumi.control"],["kandan.control_ack_withheld_on_failure","linzumi.control_ack_withheld_on_failure"],["kandan.control_epoch_changed","linzumi.control_epoch_changed"],["kandan.control_handler_threw","linzumi.control_handler_threw"],["kandan.control_ignored","linzumi.control_ignored"],["kandan.control_response_push_failed","linzumi.control_response_push_failed"],["kandan.failed_seq_overflow","linzumi.failed_seq_overflow"],["kandan.forward_port_revoked_push_failed","linzumi.forward_port_revoked_push_failed"],["kandan.forward_response","linzumi.forward_response"],["kandan.forward_response_push_failed","linzumi.forward_response_push_failed"],["kandan.forward_tunnel_error","linzumi.forward_tunnel_error"],["kandan.forward_tunnel_open_failed","linzumi.forward_tunnel_open_failed"],["kandan.heartbeat_push_failed","linzumi.heartbeat_push_failed"],["kandan.local_editor_initial_status_failed","linzumi.local_editor_initial_status_failed"],["kandan.local_editor_status_push_failed","linzumi.local_editor_status_push_failed"],["kandan.message_duplicate_ignored","linzumi.message_duplicate_ignored"],["kandan.message_ignored","linzumi.message_ignored"],["kandan.message_queued","linzumi.message_queued"],["kandan.message_spawn_on_miss","linzumi.message_spawn_on_miss"],["kandan.message_spawn_on_miss_failed","linzumi.message_spawn_on_miss_failed"],["kandan.message_state_refresh_failed","linzumi.message_state_refresh_failed"],["kandan.optional_push_failed","linzumi.optional_push_failed"],["kandan.post_stop_queue_drain_failed","linzumi.post_stop_queue_drain_failed"],["kandan.queue_drain_blocked","linzumi.queue_drain_blocked"],["kandan.queue_drain_dead_worker_fail_publish_failed","linzumi.queue_drain_dead_worker_fail_publish_failed"],["kandan.queue_drain_dead_worker_rebuild","linzumi.queue_drain_dead_worker_rebuild"],["kandan.queue_drain_dead_worker_rebuild_exhausted","linzumi.queue_drain_dead_worker_rebuild_exhausted"],["kandan.queue_drain_dead_worker_rebuild_failed","linzumi.queue_drain_dead_worker_rebuild_failed"],["kandan.reconnect_handling_failed","linzumi.reconnect_handling_failed"],["kandan.reconnect_thread_context_fetch_failed","linzumi.reconnect_thread_context_fetch_failed"],["kandan.reconnect_thread_cwd_failed_state_push_failed","linzumi.reconnect_thread_cwd_failed_state_push_failed"],["kandan.reconnect_thread_failed","linzumi.reconnect_thread_failed"],["kandan.reconnect_thread_processing_state_push_failed","linzumi.reconnect_thread_processing_state_push_failed"],["kandan.reconnect_thread_queue_closed_state_push_failed","linzumi.reconnect_thread_queue_closed_state_push_failed"],["kandan.reconnect_thread_queue_failed_state_push_failed","linzumi.reconnect_thread_queue_failed_state_push_failed"],["kandan.reconnect_thread_queue_state_push_failed","linzumi.reconnect_thread_queue_state_push_failed"],["kandan.reconnect_thread_rehydrate_forced","linzumi.reconnect_thread_rehydrate_forced"],["kandan.reconnect_thread_rehydrated","linzumi.reconnect_thread_rehydrated"],["kandan.reconnect_thread_rehydrated_state_push_failed","linzumi.reconnect_thread_rehydrated_state_push_failed"],["kandan.reconnect_thread_rehydration_failed","linzumi.reconnect_thread_rehydration_failed"],["kandan.reconnect_thread_rehydration_ir_emitted","linzumi.reconnect_thread_rehydration_ir_emitted"],["kandan.reconnect_thread_rehydration_items_failed","linzumi.reconnect_thread_rehydration_items_failed"],["kandan.reconnect_thread_resume_failed","linzumi.reconnect_thread_resume_failed"],["kandan.reconnect_thread_seq_already_applied","linzumi.reconnect_thread_seq_already_applied"],["kandan.reconnect_thread_transcript_fetch_failed","linzumi.reconnect_thread_transcript_fetch_failed"],["kandan.reconnect_thread_unarchive_failed","linzumi.reconnect_thread_unarchive_failed"],["kandan.reconnect_thread_unarchive_resumed","linzumi.reconnect_thread_unarchive_resumed"],["kandan.reconnect_thread_unarchive_started","linzumi.reconnect_thread_unarchive_started"],["kandan.reconnect_thread_unavailable_state_push_failed","linzumi.reconnect_thread_unavailable_state_push_failed"],["kandan.reconnected","linzumi.reconnected"],["kandan.roster_seeded","linzumi.roster_seeded"],["kandan.session_app_server_lost_push_failed","linzumi.session_app_server_lost_push_failed"],["kandan.session_settings_publish_failed","linzumi.session_settings_publish_failed"],["kandan.start_instance_claude_code_attachment_failed_state_push_failed","linzumi.start_instance_claude_code_attachment_failed_state_push_failed"],["kandan.start_instance_codex_app_server_unavailable","linzumi.start_instance_codex_app_server_unavailable"],["kandan.start_instance_cwd_failed_state_push_failed","linzumi.start_instance_cwd_failed_state_push_failed"],["kandan.start_instance_cwd_rejected","linzumi.start_instance_cwd_rejected"],["kandan.start_instance_failed","linzumi.start_instance_failed"],["kandan.start_instance_processing_state_push_failed","linzumi.start_instance_processing_state_push_failed"],["kandan.start_instance_skipped_known_session","linzumi.start_instance_skipped_known_session"],["kandan.start_instance_stale_skipped","linzumi.start_instance_stale_skipped"],["kandan.start_instance_unavailable_state_push_failed","linzumi.start_instance_unavailable_state_push_failed"],["kandan.start_instance_wafer_state_push_failed","linzumi.start_instance_wafer_state_push_failed"],["kandan.start_turn_replay_skipped","linzumi.start_turn_replay_skipped"],["kandan.steer_duplicate_ignored","linzumi.steer_duplicate_ignored"],["kandan.steer_parked_as_own_turn","linzumi.steer_parked_as_own_turn"],["kandan.thread_bind_from_historical_reply_failed","linzumi.thread_bind_from_historical_reply_failed"],["kandan.thread_bound_from_historical_reply","linzumi.thread_bound_from_historical_reply"],["kandan.thread_sessions_reannounce_failed","linzumi.thread_sessions_reannounce_failed"],["kandan.thread_sessions_reannounced","linzumi.thread_sessions_reannounced"],["kandan.tui_input_mirrored","linzumi.tui_input_mirrored"],["kandan.typing_heartbeat_failed","linzumi.typing_heartbeat_failed"],["kandan.typing_stop_after_completion_failed","linzumi.typing_stop_after_completion_failed"]],keys:[["codexThreadId","harness_session_id"],["codex_thread_id","harness_session_id"],["kandanThreadId","thread_id"],["kandan_preview_ticket","linzumi_preview_ticket"],["kandan_thread_id","thread_id"],["linzumiThreadId","thread_id"],["linzumi_thread_id","thread_id"],["local_codex_runner","commander"],["runnerId","commander_id"],["runner_config","commander_config"],["runner_id","commander_id"]],keyPrimaryLegacy:[["commander","local_codex_runner"],["commander_config","runner_config"],["commander_id","runner_id"],["harness_session_id","codex_thread_id"],["linzumi_preview_ticket","kandan_preview_ticket"],["thread_id","kandan_thread_id"]],values:[["engine_boot_reconnect","harness_boot_reconnect"],["engine_for_runner_event_type","harness_for_commander_event_type"],["engine_rejected_steer","harness_rejected_steer"],["engine_unavailable","harness_unavailable"],["join_engine","join_harness"],["kandan-local-codex-runner","linzumi-commander"],["local_codex_runner","commander"],["original_engine","original_harness"],["resume_engine","resume_harness"]],topic:{legacyPrefix:"local_codex_runner:",canonicalPrefix:"commander:"},originator:{legacy:"kandan-local-codex-runner",canonical:"linzumi-commander"}};var XP=new Map(Tt.events),eR=new Map(Tt.events.map(([e,t])=>[t,e])),f_=new Map(Tt.keys),h_=new Map(Tt.keyPrimaryLegacy),tR=new Map(Tt.values),rR=new Map(Tt.values.map(([e,t])=>[t,e])),P4={eventCanonicalByLegacy:XP,eventLegacyByCanonical:eR,keyCanonicalByLegacy:f_,keyPrimaryLegacyByCanonical:h_,valueCanonicalByLegacy:tR,valueLegacyByCanonical:rR,originator:Tt.originator,topic:Tt.topic};function g_(e){let t=new Set(e);for(let r of e){let n=f_.get(r);n!==void 0&&t.add(n);let o=h_.get(r);o!==void 0&&t.add(o)}return t}var m_=new Map;for(let[e,t]of Tt.keys){let r=m_.get(t)??[];r.push(e),m_.set(t,r)}var Lr="<SENSITIVE_DATA>",b_=g_(new Set(["access_token","authorization","code","cookie","kandan_preview_ticket","refresh_token","token"])),cR=new Set(["--access-token","--api-key","--authorization","--cookie","--oauth-code","--password","--refresh-token","--secret","--token"]);function dR(e){if(process.env.VITEST===void 0)return;let t=__(y_(),".linzumi"),r=iR(e);if(r===t||r.startsWith(`${t}${sR}`))throw new Error(`test-mode log isolation violated: refusing to open ${e} inside the real ~/.linzumi (point the logger at a temp path; the harness defaults LINZUMI_RUNNER_LOG_FILE / LINZUMI_CLI_AUDIT_LOG for exactly this - see plans/2026-07-10-cli-test-hygiene-spec.md item 2)`)}function $l(e,t,r={}){let n=r.logFile??uR();dR(n);try{aR(oR(n),{recursive:!0}),nR(n,`${JSON.stringify({ts:new Date().toISOString(),event:e,...r.sessionId===void 0?{}:{sessionId:r.sessionId},...lR(t)})}
44
- `,"utf8")}catch(o){console.warn("cli.audit_write_failed",{event:e,code:o instanceof Error&&"code"in o&&typeof o.code=="string"?o.code:"audit_write_error"});return}}function uR(){let e=process.env.LINZUMI_CLI_AUDIT_LOG?.trim();return e===void 0||e===""?__(y_(),".linzumi","logs","command-events.jsonl"):e}function lR(e){return v_(e)}function zl(e,t){return fR(t)?Lr:typeof e=="string"?w_(e):Array.isArray(e)?t==="args"?pR(e):e.map(r=>zl(r,void 0)):e!==null&&typeof e=="object"?v_(e):e}function v_(e){let t=typeof e.name=="string"?e.name.toLowerCase():void 0,r=t==="authorization"||t==="cookie"||t==="x-linzumi-agent-turn"||t==="set-cookie";return Object.fromEntries(Object.entries(e).filter(([n])=>n!=="runner_console").map(([n,o])=>[n,r&&n==="value"?Lr:zl(o,n)]))}function pR(e){let t=!1;return e.map(r=>{if(typeof r!="string")return t=!1,zl(r,void 0);if(t)return t=!1,Lr;let[n,o]=mR(r);return cR.has(n)?o===void 0?(t=!0,r):`${n}=${Lr}`:w_(r)})}function mR(e){let t=e.indexOf("=");return t===-1?[e,void 0]:[e.slice(0,t),e.slice(t+1)]}function fR(e){return e===void 0?!1:/^(authorization|cookie|set-cookie|password|login[_-]?url|turnCapability|topicWakeTurnCapability|topic_wake_turn_capability|x-linzumi-agent-turn|mcpAuthFileContents|LINZUMI_CLOUD_MCP_AUTH_JSON)$/i.test(e)||/(^|[_-])(access[_-]?token|api[_-]?key|auth[_-]?token|oauth[_-]?code|refresh[_-]?token|secret|token)$/i.test(e)}function w_(e){return hR(e).replace(/\beyJ[A-Za-z0-9_-]*\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\b/g,Lr)}function hR(e){let t;try{t=new URL(e)}catch{return gR(e)}for(let r of[...t.searchParams.keys()])b_.has(r.toLowerCase())&&t.searchParams.set(r,Lr);return t.toString()}function gR(e){let t=e.indexOf("?"),r=e.indexOf("#");if(t===-1||r!==-1&&r<t)return e;let n=e.slice(0,t),o=r===-1?e.slice(t+1):e.slice(t+1,r),i=r===-1?"":e.slice(r),s=new URLSearchParams(o),a=!1;for(let c of[...s.keys()])b_.has(c.toLowerCase())&&(s.set(c,Lr),a=!0);switch(a){case!0:return`${n}?${s.toString()}${i}`;case!1:return e}}var vR=300*1e3,wR=1e4;function k_(e,t=process.env){if(typeof e=="number"&&Number.isFinite(e)&&e>0)return e;let r=t.LINZUMI_OAUTH_CALLBACK_TIMEOUT_MS?.trim();if(r!==void 0&&r!==""){let n=Number.parseInt(r,10);if(Number.isFinite(n)&&n>0)return n}return vR}async function x_(e){let t=We(e.kandanUrl),r=_R(18).toString("base64url"),n=await zR({host:kR(e.kandanUrl,e.callbackHost),exchange:async i=>{if(i.state!==r)throw new Error("local runner OAuth state mismatch");return await $R({httpBaseUrl:t,code:i.code,redirectUri:i.redirectUri})}}),o=SR({httpBaseUrl:t,redirectUri:n.redirectUri,state:r,workspaceSlug:e.workspaceSlug,channelSlug:e.channelSlug,onboarding:e.onboarding,purpose:e.purpose});process.stderr.write(`Authorize the local Codex runner:
45
- ${o}
46
- `);try{return await(e.openAuthorizationUrl??ER)(o),await n.waitForToken(k_(e.waitForTokenTimeoutMs))}finally{n.close()}}async function S_(e){return await No(e)==="usable"}async function No(e){let t=new URL("/api/v2/local-codex-runner/oauth/validate",We(e.kandanUrl));e.workspaceSlug!==void 0&&t.searchParams.set("workspace",e.workspaceSlug),e.channelSlug!==void 0&&t.searchParams.set("channel",e.channelSlug);for(let n of e.requiredScopes??[])t.searchParams.append("required_scope",n);let r=await fetch(t,{method:"GET",headers:{authorization:`Bearer ${e.accessToken}`}});switch(r.status){case 200:{let n=await r.json();return typeof n=="object"&&n!==null&&"ok"in n&&n.ok===!0?"usable":"rejected"}case 401:case 403:return"rejected";case 404:return"not_found";default:throw new Error(`local runner auth validation failed with HTTP ${r.status}`)}}function We(e){let t=new URL(e);switch(t.protocol){case"ws:":t.protocol="http:";break;case"wss:":t.protocol="https:";break;case"http:":case"https:":break;default:throw new Error("--api-url must be ws://, wss://, http://, or https://")}return t.pathname="",t.search="",t.hash="",t.toString().replace(/\/$/,"")}function kR(e,t){let r=t?.trim();if(r!==void 0&&r!=="")return r;let n=new URL(e).hostname.trim();return xR(n)&&n!=="localhost"?n:"127.0.0.1"}function xR(e){let t=e.split(".").map(o=>Number.parseInt(o,10));if(t.length!==4||t.some(o=>!Number.isInteger(o)||o<0||o>255))return e==="localhost";let[r,n]=t;return r===void 0||n===void 0?!1:r===10||r===127||r===172&&n>=16&&n<=31||r===192&&n===168||r===169&&n===254||r===100&&n>=64&&n<=127}function SR(e){let t=new URL("/api/v2/local-codex-runner/oauth/authorize",e.httpBaseUrl);return t.searchParams.set("redirect_uri",e.redirectUri),t.searchParams.set("state",e.state),e.workspaceSlug!==void 0&&t.searchParams.set("workspace",e.workspaceSlug),e.channelSlug!==void 0&&t.searchParams.set("channel",e.channelSlug),e.onboarding!==void 0&&t.searchParams.set("onboarding",e.onboarding),e.purpose!==void 0&&t.searchParams.set("purpose",e.purpose),t.toString()}async function $R(e){let t=await fetch(new URL("/api/v2/local-codex-runner/oauth/token",e.httpBaseUrl),{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({code:e.code,redirect_uri:e.redirectUri})}),r=await t.json();if(!t.ok||typeof r!="object"||r===null){let i=typeof r=="object"&&r!==null&&"error"in r&&typeof r.error=="string"?r.error:void 0;throw i==="admin_role_required"?new Error("This token requires a Linzumi admin account. Approve the request while signed in as an admin."):new Error(i!==void 0?`local runner OAuth token exchange failed: ${i}`:"local runner OAuth token exchange failed")}let n="access_token"in r?r.access_token:void 0;if(typeof n!="string"||n.trim()==="")throw new Error("local runner OAuth token response did not include access_token");let o="expires_in"in r?r.expires_in:void 0;return{accessToken:n,expiresInSeconds:typeof o=="number"?o:void 0,workspaceSlug:Cs(r,"workspace"),channelSlug:Cs(r,"channel")}}async function $_(e){let t=await fetch(new URL("/api/v2/local-codex-runner/device/start",e.httpBaseUrl),{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({workspace:e.workspaceSlug,channel:e.channelSlug,onboarding:e.onboarding,runner_id:e.identity?.runnerId,machine_fingerprint:e.identity?.machineFingerprint,hostname:e.identity?.hostname})}),r=await t.json();if(!t.ok||typeof r!="object"||r===null){let a=Pl(r);throw new Error(a===void 0?`local runner device authorization failed to start (HTTP ${t.status})`:`local runner device authorization failed to start (server said: ${a})`)}let n="device_code"in r?r.device_code:void 0,o="user_code"in r?r.user_code:void 0,i="verification_uri"in r?r.verification_uri:void 0,s="expires_in"in r?r.expires_in:void 0;if(typeof n!="string"||n.trim()===""||typeof o!="string"||o.trim()===""||typeof i!="string"||i.trim()==="")throw new Error("local runner device authorization response was incomplete");return{deviceCode:n,userCode:o,verificationUri:i,expiresInSeconds:typeof s=="number"?s:void 0}}async function z_(e){let t=e.now??Date.now,r=typeof e.expiresInSeconds=="number"&&e.expiresInSeconds>=0?e.expiresInSeconds:600,n=t()+r*1e3;for(;t()<n;){let o=Math.max(0,Math.min(3e4,n-t())),i=new AbortController,s=setTimeout(()=>i.abort(),o+wR),a,c;try{a=await fetch(new URL("/api/v2/local-codex-runner/device/token",e.httpBaseUrl),{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({device_code:e.deviceCode,wait_ms:o}),signal:i.signal})}catch(p){if(clearTimeout(s),i.signal.aborted)continue;return{kind:"transient",reason:p instanceof Error?p.message:String(p)}}try{c=await a.json()}catch(p){if(i.signal.aborted)continue;return{kind:"transient",reason:`non-JSON device/token response (${p instanceof Error?p.message:String(p)})`,httpStatus:a.status}}finally{clearTimeout(s)}if(a.status===202&&Pl(c)==="authorization_pending")continue;if(!a.ok||typeof c!="object"||c===null){let p=Pl(c);switch(p){case"access_denied":return{kind:"denied"};case"device_session_expired":return{kind:"code_expired"};case"device_session_consumed":return{kind:"consumed"};default:return a.status>=500||a.status===429?{kind:"transient",reason:p??`HTTP ${a.status}`,httpStatus:a.status}:{kind:"rejected",reason:p,httpStatus:a.status}}}let d="access_token"in c?c.access_token:void 0;if(typeof d!="string"||d.trim()==="")return{kind:"rejected",reason:"device token response did not include access_token",httpStatus:a.status};let u="expires_in"in c?c.expires_in:void 0;return{kind:"token",token:{accessToken:d,expiresInSeconds:typeof u=="number"?u:void 0,workspaceSlug:Cs(c,"workspace"),channelSlug:Cs(c,"channel")}}}return{kind:"code_expired"}}function Pl(e){if(!(typeof e!="object"||e===null||!("error"in e)))return typeof e.error=="string"?e.error:void 0}function T_(e,t){switch(e){case"access_denied":return"local runner device authorization was denied";case"device_session_expired":return"local runner device authorization expired";case"device_session_consumed":return"local runner device authorization was already used";case"invalid_device_code":return"local runner device authorization code was rejected";case"device_session_not_pending":return"local runner device authorization was already decided (approved or denied) on the server";case"invalid_user_code":return"local runner device authorization code was not recognized by the server";case"approving_user_not_found":return"local runner device authorization failed: the approving Linzumi account could not be found";case"rate_limited":return"local runner device authorization was rate limited by the server; wait a minute and retry";case void 0:return t===void 0?"local runner device authorization failed (no reason returned by the server)":`local runner device authorization failed (HTTP ${t}, no reason returned by the server)`;default:return`local runner device authorization failed (server said: ${e})`}}function Cs(e,t){let r=e[t];return typeof r=="string"&&r.trim()!==""?r:void 0}function zR(e){return new Promise((t,r)=>{let n,o,i=!1,s=new Promise((u,p)=>{n=u,o=p});s.catch(()=>{});let a=u=>i?!1:(i=!0,u(),!0),c=`http://${e.host}/callback`,d=bR((u,p)=>{(async()=>{try{let m=new URL(u.url??"/",`http://${e.host}`),f=m.searchParams.get("code"),h=m.searchParams.get("state"),g=m.searchParams.get("error");if(g!==null&&g.trim()!==""){a(()=>o?.(new Error(`local runner OAuth failed: ${g}`))),Mo(p,{title:"Not authorized",body:"You denied the request. Close this tab and rerun the bootstrap command when you're ready.",status:403});return}if(f===null||h===null||f.trim()===""||h.trim()===""){Mo(p,{title:"Authorization callback was incomplete",body:"We didn't receive the authorization code. Return to your terminal and try again.",status:400});return}let y;try{y=await e.exchange({code:f,state:h,redirectUri:c})}catch(w){a(()=>o?.(w)),Mo(p,{title:"Authorization could not be completed",body:"We received the authorization but could not finish setup. Return to your terminal for details and rerun the bootstrap command.",status:400});return}let v=a(()=>n?.(y));Mo(p,{title:v?"Computer authorized":"Already authorized",body:"This computer has been authorized for agentic use in Linzumi. Feel free to close this tab and let the terminal finish setup.",status:200})}catch(m){a(()=>o?.(m)),Mo(p,{title:"Authorization callback failed",body:"Return to your terminal and rerun the bootstrap command.",status:500})}})()});d.once("error",r),d.listen(0,e.host,()=>{let u=d.address();if(!TR(u)){r(new Error("local runner OAuth callback server did not bind to a TCP port"));return}c=`http://${e.host}:${u.port}/callback`,t({redirectUri:c,waitForToken:p=>{let m=k_(p),f=setTimeout(()=>{a(()=>o?.(new Error("Authorization timed out before the browser callback completed. Rerun the connect command and finish authorizing in the browser."))),d.close()},m);return f.unref?.(),s.finally(()=>{clearTimeout(f)}).catch(()=>{}),s},close:()=>{d.close()}})})})}function TR(e){return typeof e=="object"&&e!==null&&typeof e.port=="number"}function Mo(e,t){e.writeHead(t.status,{"content-type":"text/html; charset=utf-8"}),e.end(RR(t))}var PR='<svg viewBox="0 0 512 512" xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false"><path fill="currentColor" d="M206.7,82.37l2.55-6.45,2.01-3.63c.67-1.21,1.07-1.88,2.55-3.63,1.34-1.61,3.36-4.43,5.64-6.58,2.42-2.24,5.06-4.3,7.93-6.18,3.92-2.53,8.17-4.52,12.63-5.91,1.79-.63,4.03-1.16,6.72-1.61,6.1-.88,12.29-.92,18.4-.13,2.69.45,5.06,1.03,7.12,1.75,2.15.67,3.49,1.07,5.64,2.15,4.55,2.16,8.87,4.77,12.9,7.79,1.61,1.34,2.42,2.15,4.16,4.16l5.91,7.66c1.34,2.01,1.34,2.28,2.15,4.03l2.55,6.58c.67,1.34-.13,1.34,1.07.94,1.21-.27,4.3-2.01,6.45-2.82,4.7-1.83,9.62-3,14.64-3.49,2.42-.27,3.76-.54,7.12-.27s9.27,1.21,12.76,2.15c3.63.94,6.58,2.55,8.73,3.49,2.15,1.07,2.55,1.48,4.16,2.55,3.49,2.51,6.77,5.29,9.81,8.33,1.52,1.7,3.04,3.58,4.57,5.64,2.74,4.49,4.86,9.32,6.31,14.37.67,2.28,1.07,3.49,1.34,6.72.27,3.22,0,10.48.4,12.76.27,2.28.27.67,1.61.94,1.48.27,4.3,0,6.72.4,2.42.27,4.97.85,7.66,1.75,6.76,2.32,13.01,5.92,18.4,10.61,2.28,1.75,2.96,2.69,4.3,4.3,3.51,3.93,6.32,8.43,8.33,13.3,1.07,2.15,1.21,2.28,1.88,5.1.54,2.96,1.61,8.19,1.61,12.36s-.81,9.67-1.34,12.76c-.67,3.22-1.07,4.03-2.15,6.18-2.16,4.54-4.81,8.82-7.93,12.76-1.25,1.61-2.6,3-4.03,4.16-1.48,1.34-2.69,2.42-4.7,3.76-3.79,2.34-7.74,4.4-11.82,6.18l-6.58,2.15c-2.06.45-4.12.72-6.18.81l-7.25.13c-2.28,0-2.82.27-6.58-.4-3.76-.81-11.69-2.82-15.99-4.3-4.16-1.34-6.31-2.69-9.67-4.43-3.49-1.75-10.48-6.18-12.9-7.39-8.26-4.54-16.78-8.58-25.52-12.09-4.3-1.75-9.27-3.22-11.82-4.03-2.55-.81-5.24-1.61-7.66-2.15-8.39-2.25-16.99-3.6-25.66-4.03-3.9-.27-4.84-.27-8.19-.13-3.67-.09-7.79.04-12.36.4-7.9.79-15.75,2.04-23.51,3.76-8.37,2.26-16.62,4.95-24.72,8.06-3.22,1.34-2.82.81-9.13,4.16-6.31,3.36-22.03,12.22-28.75,15.58-6.72,3.36-8.73,3.49-11.82,4.43-3.09,1.07-4.3,1.21-6.58,1.61-7.3,1.09-14.71,1.18-22.03.27-2.55-.54-5.78-1.61-7.79-2.28-2.01-.54-2.15-.67-4.03-1.75-2.02-1.07-5.64-3.22-7.79-4.7-3.24-2.15-6.14-4.77-8.6-7.79-1.34-1.52-2.69-3.36-4.03-5.51-1.52-2.51-2.96-5.24-4.3-8.19-2.03-5.46-3.03-11.24-2.96-17.06,0-2.96.13-6.72.67-9.67.54-2.87,1.34-5.6,2.42-8.19,4.24-10.52,12.04-19.22,22.03-24.58,5.19-2.98,10.88-4.98,16.79-5.91,2.55-.4,5.37-.13,6.72-.4,1.34-.27,1.34,1.34,1.61-.94.4-2.28,0-9.4.4-12.76.27-3.36.81-4.97,1.48-7.25,1.87-6.19,4.88-11.97,8.87-17.06,3.47-3.98,7.39-7.54,11.69-10.61,4.43-2.61,9.11-4.77,13.97-6.45,2.55-.67,6.99-1.34,9.13-1.75,2.15-.27,1.88-.13,3.63-.13,1.79-.09,4.03,0,6.72.27,2.69.18,5.73.72,9.13,1.61,3.49,1.07,9.27,4.03,11.28,4.7s.4.27,1.07-.94ZM512.27,255.7c0,141.39-114.62,256-256,256S.27,397.09.27,255.7,114.89-.3,256.27-.3s256,114.62,256,256ZM449.33,352.66c14.67-29.16,22.94-62.09,22.94-96.95,0-119.29-96.71-216-216-216S40.27,136.41,40.27,255.7c0,41.89,11.94,80.98,32.57,114.09,1.7,1.79,2.94.65,3.05-.57.27-1.61,2.75-20.85,4.43-27.27,1.87-7.6,4.52-14.98,7.93-22.03,1.75-3.49,3.76-7.93,6.18-11.82,8.77-13.95,19.75-26.38,32.51-36.81,7.24-5.32,14.87-10.08,22.84-14.24,9.74-4.78,20.09-8.22,30.76-10.21,4.03-.99,7.61-1.66,10.75-2.02,3.36-.54,5.78-.54,9.27-.94,3.49-.54,9.32-1.16,11.82-2.01,6.65-2.27,5.64-6.72,3.09-7.52-2.55-.81-9.67-1.88-13.84-2.96-4.16-1.21-8.73-2.82-11.28-3.76-2.55-.94-2.28-.94-3.9-2.02l-5.91-4.03c-.94-.94-1.34-.94.54-2.02l10.21-5.51c2.01-1.07,1.75-.67,3.09-.13,1.34.67,4.3,2.42,6.72,3.36,7.2,2.69,14.96,3.52,22.57,2.42,1.34-.27,1.34-.54,1.61-1.21.27-.67.81-.94-.13-2.69-.94-1.88-4.43-6.58-5.64-8.46l-1.21-2.28c-.27-.45-1.07-1.07,1.21-1.75,2.42-.54,10.48-2.58,12.9-2.82.86-.09.67,0,1.75,1.07,1.07,1.07,3.09,3.63,4.84,5.24,1.88,1.61,4.43,3.22,6.18,4.3,2.8,1.71,5.99,2.68,9.27,2.82,1.88,0,4.97-.13,7.12-.67,2.15-.4,3.63-.94,5.64-2.02,2.01-1.07,4.7-2.69,6.72-4.43,2.01-1.75,3.49-5.1,5.64-6.04,2.15-.81,4.97.54,7.12.94,2.28.4,4.97,1.21,6.18,1.61,1.21.4,2.01.4.67,2.28l-8.06,10.34c-1.34,1.88.13,5.51,1.21,5.64l5.64.27c2.28-.13,4.43.13,7.66-.67,3.36-.81,9.27-2.96,11.82-3.9,2.69-.94,3.22-1.34,4.16-2.01.81-.54,1.39-1.03,1.75-1.48.45-.27.67-1.07,2.82,0s9.4,4.97,11.28,6.18c2.01,1.21,1.07.94,0,1.75l-5.51,3.9c-1.48.94-1.07.94-3.22,1.88-2.15,1.07-6.58,2.96-9.67,4.03s-4.03,1.75-8.73,2.69c-4.7.81-14.51,1.75-19.48,2.55-4.97.81-7.93,1.34-10.34,2.01-2.28.67-2.15.94-3.49,1.88-1.48,1.07-2.69,1.61-4.97,3.9-2.28,2.28-5.91,6.85-8.73,9.81-2.82,2.96-6.45,6.04-8.33,7.79-2.02,1.61-1.61,1.34-3.36,2.42l-6.99,4.03-4.03,2.02-6.72,2.15c-2.42.67-3.9,1.21-7.66,2.01l-14.91,2.82c-3.63.81-4.3,1.07-7.12,2.01-2.96,1.07-6.22,2.46-9.81,4.16-3.22,1.43-6.81,3.45-10.75,6.04-13.6,9.14-24.61,21.63-31.97,36.27-2.01,3.76-2.96,6.58-3.9,9.27-1.07,2.69-1.61,4.03-2.28,6.58-.67,2.69-1.48,5.24-2.15,9.27-.54,4.16-1.48,11.15-1.75,15.45-.27,4.16-.27,6.04,0,10.21l1.88,14.91c.67,3.76,1.48,5.91,2.15,8.19l1.88,5.64c.99,2.6,2.42,5.78,4.3,9.54,2.15,3.76,5.37,9.13,8.06,13.03,10.08,14.51,23.81,26.36,40.17,33.05,22.55,9.22,43.32,10.46,61.89,10.46,3.25,0,6.49-.09,9.71-.23,3.07-.42,2.74-6.09,10.48-9.42,5.26-2.26,13.7-2.42,14.91-2.55,1.07-.13-5.24-4.57-7.79-6.45-2.55-1.88-4.97-4.3-6.72-5.91-1.75-1.75-2.42-2.28-3.9-4.16-1.61-1.88-3.9-5.51-5.24-7.12-1.34-1.61-1.48-2.28-2.55-2.55-.98-.27-2.37-.09-4.16.54-1.88.4-5.37,1.21-7.12,1.88-1.75.67-2.02.81-3.09,2.01-1.07,1.07-2.69,3.76-3.63,4.7-.81.94-.67.67-1.48.94-.81.27-2.42.67-3.63.54-1.34-.18-2.55-.58-3.63-1.21-.81-.81-1.48-2.42-1.88-3.22-.4-.94-.54-1.21-.54-2.15l.4-3.49c.18-1.52.72-3.27,1.61-5.24.94-1.75,1.88-3.49,4.16-5.64,2.15-2.02,7.52-5.51,9.13-6.85,1.61-1.34,1.21-2.15.54-3.63-2.69-5.16-6.33-9.77-10.75-13.57-2.42-1.88-5.51-3.22-7.79-4.3-2.15-1.21-2.01-1.21-5.78-2.42-3.76-1.07-13.16-3.63-16.79-4.84-3.63-1.07-2.82-.94-5.1-2.01l-8.19-4.3c-1.75-.94-1.34-.54-2.69-1.61l-5.51-4.57c-2.18-1.93-3.77-4.45-4.57-7.25-.45-1.52-.45-2.87,0-4.03.4-1.34,0-1.21,2.01-3.63,2.15-2.42,7.25-7.93,10.21-10.75,3.09-2.82,4.97-4.03,7.79-6.04,5.43-3.82,11.09-7.32,16.93-10.48,2.42-1.21,5.37-2.02,7.12-2.69,1.61-.81,2.64-1.43,3.09-1.88.54-.4.67.54.4-.94-.4-1.48-1.88-4.97-2.28-7.66-.4-2.82-.4-6.18,0-8.73.36-2.42,1.03-4.66,2.01-6.72,1.16-2.24,2.46-4.3,3.9-6.18,1.34-1.7,2.91-3.04,4.7-4.03,1.75-1.07,4.3-2.01,6.18-2.42,1.61-.45,3.13-.58,4.57-.4l4.57.27c1.34.18,2.55.49,3.63.94,1.07.54,2.55,1.48,3.09,2.01.4.67.67.13-.27,1.61-1.07,1.48-4.16,4.57-5.78,7.12-1.61,2.69-2.96,5.6-4.03,8.73-.94,3.22-1.88,8.73-2.01,10.75-.27,2.15,4.7,1.75,5.1.54.54-1.07.27-2.55,1.07-5.1.81-2.42,2.42-7.25,3.9-9.81,1.34-2.55,2.82-3.76,4.57-5.51,1.79-1.88,3.67-3.45,5.64-4.7,1.88-1.21,3.22-1.75,5.64-2.28,2.42-.4,6.18-.67,8.73-.67,2.42,0,3.9.13,6.18.94,2.15.81,5.24,2.69,7.12,4.03,1.79,1.52,3.22,3.09,4.3,4.7,1.21,1.61,1.88,2.96,2.55,5.1.67,2.15,1.34,5.1,1.34,7.66,0,2.69-.54,6.04-1.21,8.19-.63,2.24-1.43,4.03-2.42,5.37-.67,1.34-.94,1.61-2.15,2.82-1.21,1.34-3.22,3.22-4.97,4.57-1.75,1.21-4.43,2.28-5.51,3.22-.94.81-.4,2.51.4,2.42.94.13,1.75.4,4.57-.13,2.82-.4,8.33-2.15,12.22-2.82,11.99-2.63,24.41-2.63,36.4,0,3.22.54,4.16,1.07,6.31,1.75l6.04,2.28c2.42,1.07,5.51,2.42,8.19,4.16,8.15,5.36,15.14,12.3,20.55,20.42,1.61,2.42,2.87,4.66,3.76,6.72,1.85,4.51,3.42,9.13,4.7,13.84.67,2.82,1.21,4.43,1.61,8.19.4,3.76.4,11.82.54,14.37.27,2.55-.13,2.28,1.75,1.34,1.75-.94,20.09-7.74,30.63-31.57,9.16-20.71,1.9-47.26-2.28-55.34-1.75-3.22-4.16-6.99-6.31-9.81-4.44-5.14-9.6-9.62-15.31-13.3-2.96-1.7-5.55-3.09-7.79-4.16-4.33-1.6-8.77-2.86-13.3-3.76l-6.18-.4h-14.37c-2.69-.27-3.1-3.18-.54-4.3,3.64-1.58,9.88-2.63,18.54-2.42,8.78.21,14.91,1.88,17.33,2.55,13.98,3.94,30.19,16.65,38.55,30.76,6.61,11.16,9.81,29.96,9.81,29.96.37,1.75,2.18,1.66,3.08.35ZM232.78,345.3c-3.91,0-7.08,3.17-7.08,7.08s3.17,7.08,7.08,7.08,7.08-3.17,7.08-7.08-3.17-7.08-7.08-7.08Z"/></svg>';function RR(e){let t=e.status>=200&&e.status<300,r=t?"badge badge--success":"badge badge--notice",n=t?'<svg viewBox="0 0 24 24" aria-hidden="true" focusable="false" class="mark"><path fill="none" stroke="currentColor" stroke-width="2.4" stroke-linecap="round" stroke-linejoin="round" d="M5 12.5l4.2 4.2L19 7"/></svg>':'<svg viewBox="0 0 24 24" aria-hidden="true" focusable="false" class="mark"><path fill="none" stroke="currentColor" stroke-width="2.4" stroke-linecap="round" stroke-linejoin="round" d="M12 7v6M12 17h.01"/></svg>';return`<!doctype html>
47
- <html lang="en">
48
- <head>
49
- <meta charset="utf-8" />
50
- <meta name="viewport" content="width=device-width, initial-scale=1" />
51
- <title>${Tl(e.title)}</title>
52
- <style>
53
- :root {
54
- color-scheme: light dark;
55
- /* Linzumi brand tokens (light) \u2014 kandan/server_v2/web/src/ui/theme/tokens.css */
56
- --page-bg: #f5f2ee;
57
- --surface: #fcfaf7;
58
- --foreground: #1e1b18;
59
- --muted: #5c5550;
60
- --divider: rgba(138, 148, 144, 0.16);
61
- --accent: #c4897a;
62
- --success: #5a9a6a;
63
- --success-soft: rgba(90, 154, 106, 0.1);
64
- --notice-soft: rgba(196, 137, 122, 0.1);
65
- --shadow: 0 12px 40px rgba(106, 138, 122, 0.12), 0 4px 12px rgba(106, 138, 122, 0.06);
66
- }
67
- @media (prefers-color-scheme: dark) {
68
- :root {
69
- /* Linzumi brand tokens (dark) */
70
- --page-bg: #171b19;
71
- --surface: #202522;
72
- --foreground: rgba(245, 241, 232, 0.95);
73
- --muted: rgba(245, 241, 232, 0.68);
74
- --divider: rgba(245, 241, 232, 0.1);
75
- --accent: #c8a0b0;
76
- --success: #72c488;
77
- --success-soft: rgba(114, 196, 136, 0.14);
78
- --notice-soft: rgba(200, 160, 176, 0.14);
79
- --shadow: 0 18px 50px rgba(0, 0, 0, 0.5), 0 4px 12px rgba(0, 0, 0, 0.35);
80
- }
81
- }
82
- * { box-sizing: border-box; }
83
- body {
84
- margin: 0;
85
- min-height: 100vh;
86
- display: grid;
87
- place-items: center;
88
- padding: 24px;
89
- background:
90
- radial-gradient(1200px 600px at 50% -10%, var(${t?"--success-soft":"--notice-soft"}), transparent 60%),
91
- var(--page-bg);
92
- color: var(--foreground);
93
- font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
94
- -webkit-font-smoothing: antialiased;
95
- }
96
- main {
97
- width: min(520px, 100%);
98
- border: 1px solid var(--divider);
99
- border-radius: 16px;
100
- background: var(--surface);
101
- padding: 40px 36px;
102
- box-shadow: var(--shadow);
103
- text-align: center;
104
- }
105
- .logo {
106
- width: 44px;
107
- height: 44px;
108
- margin: 28px auto 0;
109
- color: var(--accent);
110
- }
111
- .logo svg { display: block; width: 100%; height: 100%; }
112
- .badge {
113
- width: 64px;
114
- height: 64px;
115
- margin: 0 auto 22px;
116
- display: grid;
117
- place-items: center;
118
- border-radius: 999px;
119
- }
120
- .badge--success { background: var(--success-soft); color: var(--success); }
121
- .badge--notice { background: var(--notice-soft); color: var(--accent); }
122
- .mark { width: 32px; height: 32px; }
123
- h1 {
124
- margin: 0 0 12px;
125
- font-size: 23px;
126
- font-weight: 600;
127
- line-height: 1.3;
128
- letter-spacing: -0.01em;
129
- color: var(--foreground);
130
- }
131
- p {
132
- margin: 0;
133
- color: var(--muted);
134
- font-size: 15px;
135
- line-height: 1.6;
136
- }
137
- </style>
138
- </head>
139
- <body>
140
- <main>
141
- <div class="${r}">${n}</div>
142
- <h1>${Tl(e.title)}</h1>
143
- <p>${Tl(e.body)}</p>
144
- <div class="logo">${PR}</div>
145
- </main>
146
- </body>
147
- </html>`}function Tl(e){return e.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;")}function OR(e){return e.replace(/[&^|<>()%"]/g,t=>`^${t}`)}function ER(e){let t=process.platform==="darwin"?"open":process.platform==="win32"?"cmd":"xdg-open",r=process.platform==="win32"?["/c","start","",OR(e)]:[e];return new Promise(n=>{$l("process.spawn",{command:t,args:r,purpose:"oauth.open_browser"});let o=yR(t,r,{stdio:"ignore",detached:!0});$l("process.spawned",{command:t,args:r,pid:o.pid,purpose:"oauth.open_browser"}),o.on("error",()=>n()),o.on("spawn",()=>{o.unref(),n()})})}function I_(e){if(e===void 0)return;let t=d_(()=>JSON.parse(Tn(e,"utf8")),()=>{let r=R_(e);if(!r.isFile()||r.isSymbolicLink()||(r.mode&63)!==0)throw new Error("topic_quiet_private_auth_required");let n=Ns(`${e}.quiet-launch`,"wx",384);try{Ms(n)}finally{As(n)}let o=Ns(Ol(e),"r");try{Ms(o)}finally{As(o)}},r=>C_(e,r));switch(t.TAG){case"Ok":return t._0;case"Error":throw console.warn(t._0),new Error(t._0)}}function Do(e,t){let r=c_(()=>JSON.parse(Tn(e,"utf8")),n=>C_(e,n),t);switch(r.TAG){case"Ok":return;case"Error":throw new Error(r._0)}}function C_(e,t){let r=R_(e);if(!r.isFile()||r.isSymbolicLink()||(r.mode&63)!==0)throw new Error("topic_quiet_private_auth_required");let n=JSON.parse(Tn(e,"utf8")),o=`${e}.quiet.${process.pid}.${P_(8).toString("hex")}`;try{let i=Ns(o,"wx",384);try{j_(i,JSON.stringify({...n,topicWakeTurnCapability:{custody:t}})),Ms(i)}finally{As(i)}O_(o,e);let s=Ns(Ol(e),"r");try{Ms(s)}finally{As(s)}}catch(i){console.warn("topic_quiet_custody_write_failed");try{E_(o,{force:!0})}catch{console.warn("topic_quiet_custody_temporary_cleanup_failed")}throw i}}function A_(){return CR(IR(),".linzumi","auth.json")}function Ds(e,t=A_()){if(!Rl(t))return;let r=El(Tn(t,"utf8")),n=We(e),o=r.local_codex_runner?.[n];if(!(o===void 0||o.access_token.trim()==="")&&!(o.expires_at!==void 0&&Date.parse(o.expires_at)<=Date.now()))return{accessToken:o.access_token,kandanBaseUrl:n,issuedAt:o.issued_at,expiresAt:o.expires_at}}function M_(e){if(!Rl(e))throw new Error(`missing personal-agent delegation auth file: ${e}`);let r=El(Tn(e,"utf8")).personal_agent_delegation;if(r===void 0||r.access_token.trim()==="")throw new Error("personal-agent delegation auth file is missing access_token");if(r.expires_at!==void 0&&Date.parse(r.expires_at)<=Date.now())throw new Error("personal-agent delegation auth file token is expired");return{accessToken:r.access_token,issuedAt:r.issued_at,expiresAt:r.expires_at}}function N_(e){let t=e.authFilePath??A_(),r=Rl(t)?El(Tn(t,"utf8")):{version:1},n=We(e.kandanUrl),o=new Date,i=e.expiresInSeconds===void 0?void 0:new Date(o.getTime()+e.expiresInSeconds*1e3).toISOString(),s={...r,version:1,local_codex_runner:{...r.local_codex_runner??{},[n]:{access_token:e.accessToken,issued_at:o.toISOString(),expires_at:i}}};jR(Ol(t),{recursive:!0});let a=`${t}.tmp.${process.pid}.${P_(6).toString("hex")}`;try{j_(a,`${JSON.stringify(s,null,2)}
148
- `,{encoding:"utf8",mode:384}),O_(a,t)}catch(c){try{E_(a,{force:!0})}catch{}throw c}return{accessToken:e.accessToken,kandanBaseUrl:n,issuedAt:o.toISOString(),expiresAt:i}}function El(e){let t=JSON.parse(e);if(typeof t!="object"||t===null||Array.isArray(t))throw new Error("Kandan auth cache must contain a JSON object");let r=t,n=r.local_codex_runner,o=r.personal_agent_delegation;if(n!==void 0&&(typeof n!="object"||n===null||Array.isArray(n)))throw new Error("Kandan auth cache local_codex_runner must be an object");if(o!==void 0&&(typeof o!="object"||o===null||Array.isArray(o)))throw new Error("Kandan auth cache personal_agent_delegation must be an object");return{version:1,local_codex_runner:MR(n),personal_agent_delegation:AR(o)}}function AR(e){if(typeof e!="object"||e===null||Array.isArray(e))return;let t=e.access_token,r=e.issued_at,n=e.expires_at;if(!(typeof t!="string"||typeof r!="string"))return{access_token:t,issued_at:r,expires_at:typeof n=="string"?n:void 0}}function MR(e){if(!(typeof e!="object"||e===null||Array.isArray(e)))return Object.fromEntries(Object.entries(e).flatMap(([t,r])=>{if(typeof r!="object"||r===null||Array.isArray(r))return[];let n=r.access_token,o=r.issued_at,i=r.expires_at;return typeof n!="string"||typeof o!="string"?[]:[[t,{access_token:n,issued_at:o,expires_at:typeof i=="string"?i:void 0}]]}))}var NR=3,DR=3600*1e3,LR=5e3,qR=5e3,UR=6e4;function ZR(e){return e.cycle<=NR?"prompt":e.lastLoudPromptAtMs===void 0||e.nowMs-e.lastLoudPromptAtMs>=DR?"summary":e.isInteractive?"refresh_line":"silent"}function JR(e){switch(e.kind){case"prompt":return`${e.cycle===1?"":`The previous code expired; here is a fresh one (no restart needed - this prompt stays alive).
149
- `}Authorize this computer:
150
- Code: ${e.userCode}
151
- Open: ${e.verificationUri}
152
- `;case"summary":return`Still waiting for authorization after ${D_(e.waitedMs)} (${e.cycle} codes issued so far).
153
- Authorize this computer:
154
- Code: ${e.userCode}
155
- Open: ${e.verificationUri}
156
- `;case"refresh_line":return`\r\x1B[2KCode: ${e.userCode} (waiting ${D_(e.waitedMs)}) - open ${e.verificationUri}`;case"transient":return`Device authorization poll hit a transient failure (${e.reason}); retrying with the same code.
157
- `;case"start_failed":return`Could not mint a device authorization code (${e.reason}); retrying in ${Math.round(e.retryInMs/1e3)}s.
158
- `}}function D_(e){let t=Math.floor(e/6e4),r=Math.floor(t/60),n=t%60;return r>0?`${r}h ${n}m`:`${n}m`}async function L_(e){let t=e.deps??{},r=t.startDeviceAuthorization??$_,n=t.pollDeviceCodeForToken??z_,o=t.now??Date.now,i=t.sleep??(g=>new Promise(y=>setTimeout(y,g))),s=e.writeStderr??(g=>process.stderr.write(g)),a=e.isInteractive??process.stderr.isTTY===!0,c=t.report??(g=>s(JR(g))),d=t.log??(()=>{}),u=We(e.kandanUrl),p=o(),m=0,f,h=0;for(;;){let g;try{g=await r({httpBaseUrl:u,workspaceSlug:e.workspaceSlug,channelSlug:e.channelSlug,onboarding:e.onboarding,identity:e.identity})}catch(w){h+=1;let k=Math.min(UR,qR*2**(h-1)),O=w instanceof Error?w.message:String(w);c({kind:"start_failed",reason:O,retryInMs:k}),d("device_wait.start_failed",{reason:O,retryInMs:k,attempt:h}),await i(k);continue}h=0,m+=1;let y=ZR({cycle:m,nowMs:o(),lastLoudPromptAtMs:f,isInteractive:a});y==="prompt"||y==="summary"?(f=o(),c({kind:y,cycle:m,userCode:g.userCode,verificationUri:g.verificationUri,waitedMs:o()-p})):y==="refresh_line"&&c({kind:"refresh_line",cycle:m,userCode:g.userCode,verificationUri:g.verificationUri,waitedMs:o()-p}),d("device_wait.code_issued",{cycle:m,verificationUri:g.verificationUri});let v;for(;v=await n({httpBaseUrl:u,deviceCode:g.deviceCode,expiresInSeconds:g.expiresInSeconds}),v.kind==="transient";)c({kind:"transient",reason:v.reason,waitedMs:o()-p}),d("device_wait.transient_poll_failure",{cycle:m,reason:v.reason,httpStatus:v.httpStatus??null}),await i(LR);switch(v.kind){case"token":return d("device_wait.authorized",{cycle:m,waitedMs:o()-p}),v.token;case"denied":throw new Error("local runner device authorization was denied - a signed-in user rejected this computer");case"code_expired":case"consumed":d("device_wait.code_retired",{cycle:m,outcome:v.kind});continue;case"rejected":c({kind:"transient",reason:T_(v.reason,v.httpStatus),waitedMs:o()-p}),d("device_wait.code_rejected",{cycle:m,reason:v.reason??null,httpStatus:v.httpStatus});continue}}}import{randomUUID as G_}from"node:crypto";import{chmodSync as F_,existsSync as Ml,linkSync as WR,mkdirSync as K_,readFileSync as Q_,realpathSync as yN,unlinkSync as BR,writeFileSync as Y_}from"node:fs";import{homedir as HR}from"node:os";import{basename as Il,dirname as Lo,join as Cl,resolve as V_}from"node:path";var q_="wss://serve.linzumi.com";import{homedir as FR}from"node:os";import{isAbsolute as lN,relative as pN,resolve as VR}from"node:path";import{delimiter as tN,isAbsolute as rN,join as U_,parse as nN,resolve as oN,sep as iN}from"node:path";var sN=[".volta",".nvm",".npm",".asdf",".fnm",".bun",U_(".cargo","bin"),U_(".local","bin")];function J_(e){return e==="~"?Z_():e.startsWith("~/")?VR(Z_(),e.slice(2)):e}function Z_(){let e=process.env.HOME;return e===void 0||e.trim()===""?FR():e}var jl=384,Dt="prod";function Pn(e=process.env){let t=e.LINZUMI_CONFIG_FILE;return t!==void 0&&t.trim()!==""?V_(J_(t)):V_(HR(),".linzumi","config.json")}function qo(e){let t=We(e),r=We(q_);return t===r?Dt:t}function GR(e){let t=qo(e);return t===Dt?Dt:Buffer.from(t).toString("base64url")}function W_(e=Pn()){return eb(e)}function B_(e,t=Pn()){return eb(t,e)}function X_(e,t=Pn(),r=ib){if(qo(e)===Dt)return KR(t,r);let n=B_(e,t);if(n.runnerId!==void 0)return n.runnerId;let o=ob(t,r,e),i=B_(e,t),s=i.runnerId;return s!==void 0?s:(tb({...i,runnerId:o},t,e),o)}function KR(e=Pn(),t=ib){let r=W_(e);if(r.runnerId!==void 0)return r.runnerId;let n=ob(e,t),o=W_(e),i=o.runnerId;return i!==void 0?i:(YR({...o,runnerId:n},e),n)}function QR(e=Pn(),t){return t!==void 0&&qo(t)!==Dt?Cl(Lo(e),`${Il(e)}.${GR(t)}.runner-id`):Cl(Lo(e),`${Il(e)}.runner-id`)}function YR(e,t=Pn()){tb(e,t)}function XR(e,t){Ml(e)&&F_(e,jl),Y_(e,`${JSON.stringify(t,null,2)}
159
- `,{encoding:"utf8",mode:jl}),F_(e,jl)}function Al(e){if(!Ml(e))return{version:1,allowedCwds:[]};let t=JSON.parse(Q_(e,"utf8"));if(!rb(t))throw new Error(`invalid Linzumi config: ${e}`);return t}function eb(e,t){let r=Al(e),n=t===void 0?Dt:qo(t),o=n===Dt?r:r[n]??tO();if(!nb(o))throw new Error(`invalid Linzumi config section ${n}: ${e}`);let i=sb(o.allowedCwds);return{version:1,...o.machineId===void 0?{}:{machineId:o.machineId},...o.runnerId===void 0?{}:{runnerId:o.runnerId},allowedCwds:i}}function tb(e,t,r){let n=r===void 0?Dt:qo(r),o=eO(e),i=n===Dt?{...Al(t),...o,version:1}:{...Al(t),version:1,[n]:o};K_(Lo(t),{recursive:!0}),XR(t,i)}function rb(e){return typeof e=="object"&&e!==null&&e.version===1&&nb(e)}function nb(e){return typeof e=="object"&&e!==null&&Array.isArray(e.allowedCwds)&&rO(e.machineId)&&Nl(e.runnerId)&&e.allowedCwds.every(t=>typeof t=="string"&&t.trim()!=="")}function eO(e){if(!rb(e))throw new Error("invalid Linzumi config");let t=sb(e.allowedCwds);return{...e.machineId===void 0?{}:{machineId:e.machineId},...e.runnerId===void 0?{}:{runnerId:e.runnerId},allowedCwds:t}}function tO(){return{allowedCwds:[]}}function rO(e){return e===void 0||typeof e=="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(e)}function Nl(e){return e===void 0||typeof e=="string"&&/^[a-zA-Z0-9_.-]+$/.test(e)}function ob(e,t,r){let n=QR(e,r);if(Ml(n))return H_(n);let o=t();if(!Nl(o))throw new Error(`invalid generated Linzumi runner id: ${o}`);K_(Lo(n),{recursive:!0});let i=Cl(Lo(n),`.${Il(n)}.${process.pid}.${G_()}.tmp`);Y_(i,`${o}
160
- `,{encoding:"utf8",flag:"wx"});try{return WR(i,n),o}catch(s){if(nO(s,"EEXIST"))return H_(n);throw s}finally{BR(i)}}function H_(e){let t=Q_(e,"utf8").trim();if(!Nl(t))throw new Error(`invalid Linzumi runner id seed: ${e}`);return t}function ib(){return`runner-${G_()}`}function sb(e){return[...new Set(e.map(t=>t.trim()).filter(t=>t!==""))]}function nO(e,t){return typeof e=="object"&&e!==null&&"code"in e&&e.code===t}import{execFileSync as oO}from"node:child_process";import{createHash as iO}from"node:crypto";import{readFileSync as sO}from"node:fs";var aO="linzumi-machine-fingerprint:v1:";function cO(e,t){return oO(e,[...t],{encoding:"utf8",timeout:5e3,maxBuffer:1024*1024})}function dO(e){return sO(e,"utf8")}function uO(e={}){let t=e.platform??process.platform,r=e.execFile??cO,n=e.readFile??dO;try{if(t==="darwin"){let s=r("ioreg",["-rd1","-c","IOPlatformExpertDevice"]).match(/"IOPlatformUUID"\s*=\s*"([0-9A-Fa-f-]{36})"/)?.[1];return s===void 0?void 0:s.toLowerCase()}if(t==="linux"){for(let o of["/etc/machine-id","/var/lib/dbus/machine-id"])try{let i=n(o).trim().toLowerCase();if(/^[0-9a-f]{32}$/.test(i))return i}catch{}return}return}catch{return}}function ab(e={}){let t=uO(e);return t===void 0?void 0:`mfp-${iO("sha256").update(`${aO}${t}`).digest("hex").slice(0,32)}`}async function cb(e,t={readCachedToken:Ds,validateToken:No,acquireAndCacheToken:fO}){if(e.explicitToken!==void 0)return e.explicitToken;let r=t.readCachedToken(e.kandanUrl,e.authFilePath);if(r!==void 0){let o=await t.validateToken({kandanUrl:e.kandanUrl,accessToken:r.accessToken,workspaceSlug:e.workspaceSlug,channelSlug:e.channelSlug,requiredScopes:e.requiredScopes});if(o==="usable")return r.accessToken;e.reportRejectedCachedToken?.(o)}let n=await t.acquireAndCacheToken(e);return e.workspaceSlug!==void 0&&await pO(e,t,n),n}async function pO(e,t,r){let n;try{n=await t.validateToken({kandanUrl:e.kandanUrl,accessToken:r,workspaceSlug:e.workspaceSlug,channelSlug:e.channelSlug,requiredScopes:e.requiredScopes})}catch{return}if(n==="not_found")throw new Error(mO(e))}function mO(e){let t=new URL(We(e.kandanUrl)).host;return`Workspace '${e.workspaceSlug}' was not found on ${t}. Sign in to the web app to create it, then re-run connect.`}async function fO(e){let t=e.authMode??{kind:"browser",callbackHost:e.callbackHost},r=t.kind==="device"?await L_({kandanUrl:e.kandanUrl,workspaceSlug:e.workspaceSlug,channelSlug:e.channelSlug,onboarding:e.onboarding,identity:{runnerId:X_(e.kandanUrl),machineFingerprint:ab(),hostname:lO()}}):await x_({kandanUrl:e.kandanUrl,workspaceSlug:e.workspaceSlug,channelSlug:e.channelSlug,onboarding:e.onboarding,callbackHost:t.callbackHost??e.callbackHost});return N_({kandanUrl:e.kandanUrl,accessToken:r.accessToken,expiresInSeconds:r.expiresInSeconds,authFilePath:e.authFilePath}),r.accessToken}import{realpath as Ul,writeFile as LN,mkdir as qN,open as hO,rm as UN}from"node:fs/promises";import{constants as ub}from"node:fs";import{homedir as gO}from"node:os";import{basename as yO,extname as _O,isAbsolute as lb,join as VN,relative as pb,resolve as ql}from"node:path";function Be(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Dl(e){let t=e.split(".")[1];if(t===void 0||t.length===0)return!1;try{let r=JSON.parse(Buffer.from(t,"base64url").toString("utf8"));if(!Be(r)||r.document_surfaces!==!0)return!1;let n=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,o=typeof r.linzumi_agent_session=="string"&&n.test(r.linzumi_agent_session),i=typeof r.coding_job_id=="string"&&n.test(r.coding_job_id)&&typeof r.coding_job_thread_id=="string"&&n.test(r.coding_job_thread_id);return o||i}catch{return!1}}function we(e){return e!==void 0&&Be(e)?e:void 0}function qr(e){return Array.isArray(e)?e:void 0}function ye(e){return typeof e=="string"&&e.trim()!==""?e.trim():void 0}function db(e){return typeof e=="number"&&Number.isInteger(e)?e:void 0}var bO=new Set([".csv",".diff",".gif",".htm",".html",".jpeg",".jpg",".json",".jsonl",".log",".md",".mp4",".patch",".pdf",".png",".svg",".txt",".webm",".webp",".xml",".zip"]);async function Zl(e,t){let r=await Ul(e),n=await kO(r),o=await vO(r,t),i=await wO(n,o);return{fileName:yO(o),contentType:$O(o,i.classification),sizeBytes:i.bytes.byteLength,bytes:i.bytes}}async function vO(e,t){if(t==="")throw new Error("Kandan attachment path must not be empty");let r=lb(t)?ql(t):ql(e,t);return await Ul(r)}var Ll=8192;async function wO(e,t){let r=e.find(s=>xO(s.path,t));if(r===void 0){let s=e.map(a=>a.label).join(", ");throw new Error(`Kandan attachment path must resolve inside an allowed upload root (${s}): ${t}`)}if(pb(r.path,t).split(/[\\/]+/).find(s=>s.startsWith("."))!==void 0)throw new Error(`Kandan attachment upload path must not include hidden path segments: ${t}`);let i=await hO(t,ub.O_RDONLY|ub.O_NONBLOCK);try{if(!(await i.stat()).isFile())throw new Error(`Kandan attachment path is not a file: ${t}`);let a=_O(t).toLowerCase();if(bO.has(a))return{classification:"known-type",bytes:await i.readFile()};let c=Buffer.alloc(Ll),{bytesRead:d}=await i.read(c,0,Ll,0);if(c.subarray(0,d).includes(0))throw new Error(`Kandan attachment upload requires a known media/document type or text content (binary content is not allowed): ${t}`);let u=await i.readFile();if(u.subarray(0,Ll).includes(0))throw new Error(`Kandan attachment upload requires a known media/document type or text content (binary content is not allowed): ${t}`);return{classification:"text-content",bytes:u}}finally{await i.close()}}async function kO(e){let t=[{path:e,label:"runner cwd"}],r=process.env.HOME?.trim(),n=ql(r===void 0||r===""?gO():r,"Downloads");try{let o=await Ul(n);t.some(i=>i.path===o)||t.push({path:o,label:"~/Downloads"})}catch{return t}return t}function xO(e,t){let r=pb(e,t);return r===""||!r.startsWith("..")&&!lb(r)}function SO(e){let t=e.toLowerCase();return t.endsWith(".png")?"image/png":t.endsWith(".jpg")||t.endsWith(".jpeg")?"image/jpeg":t.endsWith(".gif")?"image/gif":t.endsWith(".webp")?"image/webp":t.endsWith(".csv")?"text/csv":t.endsWith(".json")?"application/json":t.endsWith(".md")||t.endsWith(".txt")||t.endsWith(".log")?"text/plain":"application/octet-stream"}function $O(e,t){if(e.toLowerCase().endsWith(".py"))return"text/x-python";let n=SO(e);return t==="text-content"&&n==="application/octet-stream"?"text/plain":n}function Jl(e){let t=e.fetchImpl??fetch,r=We(e.kandanUrl),n=e.authMode==="personal-agent-delegation"?"/api/v2/personal-agent-mcp":"/api/v2/local-runner-mcp",o=e.operatingMode??"text",i=async(s,a,c,d={})=>{let u=new URL(a,r),p={...c,operating_mode:o},m={method:s,headers:{authorization:`Bearer ${e.accessToken}`,...e.topicWakeTurnCapability===void 0?{}:{"x-linzumi-agent-turn":e.topicWakeTurnCapability}},...d.signal===void 0?{}:{signal:d.signal}};if(s==="GET")for(let[w,k]of Object.entries(p))k!=null&&u.searchParams.set(w,String(k));else m.headers={...m.headers,"content-type":"application/json"},m.body=JSON.stringify(p);let f=await t(u,m),h=await f.json(),g=Be(h)?h:void 0;if(g===void 0)throw new Error(`Linzumi MCP API returned non-object JSON from ${a}`);if(f.ok&&g.ok===!0)return g;let y=typeof g.error=="string"?g.error:`HTTP ${f.status}`,v=typeof g.detail=="string"?g.detail:void 0;throw new Error(`Linzumi MCP API ${a} failed: ${y}${v===void 0?"":` detail=${v}`}`)};return{validateAuth:()=>i("GET",`${n}/validate`,{}),issueOnboardingDiscoveryToken:s=>i("POST",`${n}/onboarding-discovery-token`,s),getMessage:s=>i("GET",`${n}/message`,s),getThread:s=>i("GET",`${n}/thread`,s),getThreadTranscript:s=>i("GET",`${n}/thread-transcript`,s),getChannel:s=>i("GET",`${n}/channel`,s),searchWorkspace:s=>i("GET",`${n}/search`,s),askWorkspace:s=>i("POST",`${n}/ask`,s),aboutMe:s=>i("GET",`${n}/about-me`,s),webSearch:s=>i("GET",`${n}/web-search`,s),fetchUrl:s=>i("GET",`${n}/fetch-url`,s),listUiTargets:s=>i("GET",`${n}/ui-targets`,s),openUi:s=>i("POST",`${n}/open-ui`,s),getCodingJobMetadata:s=>i("GET",`${n}/coding-job-metadata`,s),listProjects:s=>i("GET",`${n}/projects`,s),getProjectTasks:s=>i("GET",`${n}/project-tasks`,s),createProjectTask:s=>i("POST",`${n}/project-tasks/create`,s),updateProjectTask:s=>i("POST",`${n}/project-tasks/update`,s),deleteProjectTask:s=>i("POST",`${n}/project-tasks/delete`,s),addProjectTaskDependency:s=>i("POST",`${n}/project-tasks/add-dependency`,s),removeProjectTaskDependency:s=>i("POST",`${n}/project-tasks/remove-dependency`,s),getCallTranscript:s=>i("GET",`${n}/call-transcript`,s),renameCodingJob:s=>i("POST",`${n}/coding-job-title`,s),upsertCodingJobPlan:(s,a)=>i("POST",`${n}/coding-job-plan`,s,a),replaceCodingJobPlanSteps:s=>i("POST",`${n}/coding-job-plan/steps`,s),updateCodingJobPlanStep:s=>i("POST",`${n}/coding-job-plan/step`,s),linkCodingJobPullRequest:s=>i("POST",`${n}/coding-job-primary-pr`,s),listVaultSecrets:s=>i("GET",`${n}/vault-secrets`,s),noteProjectDirectory:s=>i("POST",`${n}/discovered-project`,s),noteAgentConversation:s=>i("POST",`${n}/discovered-conversation`,s),noteOnboardingDiscoveryStatus:s=>i("POST",`${n}/discovery-status`,s),sendChannelMessage:s=>i("POST",`${n}/channel-message`,s),editMessage:s=>i("POST",`${n}/message/edit`,s),agentReply:s=>i("POST",`${n}/agent-reply`,s),scheduleWake:s=>i("POST",`${n}/scheduled-wakes`,s),cancelWake:s=>i("POST",`${n}/scheduled-wakes/cancel`,s),declineDocumentAction:s=>i("POST",`${n}/agent/decline-document-action`,s),completeTopicWakeNoAction:s=>i("POST",`${n}/agent/complete-topic-wake-no-action`,s),recordTopicWakeToolAttempt:()=>i("POST",`${n}/agent/topic-wake-tool-attempt`,{}),agentTurnProgress:s=>i("POST",`${n}/agent-turn-progress`,s),agentDocumentTool:s=>i("POST",`${n}/agent/document-tool`,s),agentTopicTool:s=>i("POST",`${n}/agent/topic-tool`,s),agentListCodingJobs:s=>i("GET",`${n}/agent/coding-jobs`,s),agentStartCodingJob:s=>i("POST",`${n}/agent/start-coding-job`,s),agentSpawnChildJob:s=>i("POST",`${n}/agent/spawn-child-job`,s),agentArchiveChildJob:s=>i("POST",`${n}/agent/archive-child-job`,s),agentUnarchiveChildJob:s=>i("POST",`${n}/agent/unarchive-child-job`,s),agentInterruptCodingJob:s=>i("POST",`${n}/agent/interrupt-coding-job`,s),agentSendCodingJobMessage:s=>i("POST",`${n}/agent/send-coding-job-message`,s),agentDiscoverCodingJobs:s=>i("GET",`${n}/agent/discover-coding-jobs`,s),agentReadCodingJobThread:s=>i("GET",`${n}/agent/coding-job-thread`,s),agentResolveJobApproval:s=>i("POST",`${n}/agent/resolve-job-approval`,s),agentArchiveCodingJob:s=>i("POST",`${n}/agent/archive-coding-job`,s),agentUnarchiveCodingJob:s=>i("POST",`${n}/agent/unarchive-coding-job`,s),agentSetThreadStatus:s=>i("POST",`${n}/agent/set-thread-status`,s),agentCreateChannel:s=>i("POST",`${n}/agent/create-channel`,s),agentRenameChannel:s=>i("POST",`${n}/agent/rename-channel`,s),agentArchiveChannel:s=>i("POST",`${n}/agent/archive-channel`,s),agentUnarchiveChannel:s=>i("POST",`${n}/agent/unarchive-channel`,s),agentAddReaction:s=>i("POST",`${n}/agent/add-reaction`,s),agentRemoveReaction:s=>i("POST",`${n}/agent/remove-reaction`,s),agentPinMessage:s=>i("POST",`${n}/agent/pin-message`,s),agentUnpinMessage:s=>i("POST",`${n}/agent/unpin-message`,s),prepareMessageUploads:s=>i("POST",`${n}/message-uploads/prepare`,s),attachMessageFiles:s=>i("POST",`${n}/message-files/attach`,s),prepareCustomEmoji:s=>i("POST",`${n}/custom-emoji/prepare`,s),renameCustomEmoji:s=>i("POST",`${n}/custom-emoji/rename`,s),sendThreadReply:s=>i("POST",`${n}/thread-reply`,s),sendDm:s=>i("POST",`${n}/dm`,s),dmOwner:s=>i("POST",`${n}/dm-owner`,s),getVaultValues:s=>i("POST",`${n}/vault-values`,s)}}import{closeSync as Ls,fstatSync as zO,mkdirSync as Uo,openSync as mb,readdirSync as TO,readFileSync as fb,readSync as PO,renameSync as RO,rmSync as qs,statSync as hb,writeFileSync as gb}from"node:fs";import{spawn as OO,execFile as tD}from"node:child_process";import{createHash as EO}from"node:crypto";import{createRequire as jO}from"node:module";import{createConnection as IO}from"node:net";import{homedir as CO}from"node:os";import{dirname as Us,join as Zr}from"node:path";var AO=(()=>{let e;return()=>{if(e!==void 0)return e;let{lockSync:t}=jO(import.meta.url)("proper-lockfile");return e=t,t}})(),Bl=()=>{},yb=1,MO=1;function NO(){let e=process.env.LINZUMI_DEV_SERVICES_DIR?.trim();return e!==void 0&&e!==""?e:Zr(CO(),".linzumi","dev-services")}function _b(e){let t=e.replace(/[^A-Za-z0-9._-]+/g,"-").replace(/^[-.]+|[-.]+$/g,"").slice(0,80),r=EO("sha256").update(e).digest("hex").slice(0,8),n=t===""?"runner":t;return Zr(NO(),`${n}.${r}`)}function Zs(e){let t=e.trim().toLowerCase();return/^[a-z0-9][a-z0-9._-]{0,63}$/.test(t)&&!t.includes("..")?t:void 0}function Rn(e,t){return Zr(e,"services",`${t}.json`)}function Hl(e,t){return Zr(e,"exits",`${t}.json`)}function bb(e,t){return Zr(e,"logs",`${t}.log`)}function Ur(e){return typeof e=="string"&&e!==""?e:void 0}function Lt(e){return typeof e=="number"&&Number.isFinite(e)?e:void 0}function DO(e){return Array.isArray(e)?e.filter(t=>typeof t=="number"&&Number.isInteger(t)&&t>0&&t<=65535):[]}function LO(e){if(!Be(e)||e.version!==yb)return;let t=Ur(e.name),r=t===void 0?void 0:Zs(t),n=Ur(e.command),o=Ur(e.cwd),i=e.desiredState==="running"||e.desiredState==="stopped"?e.desiredState:void 0,s=Lt(e.updatedAtMs),a=Ur(e.logPath);if(r===void 0||r!==t||n===void 0||o===void 0||i===void 0||s===void 0||a===void 0)return;let c=e.failure,d;if(c!=null){let u=Be(c)?Ur(c.reason):void 0,p=Be(c)?Lt(c.atMs):void 0,m=[...u===void 0?["reason"]:[],...p===void 0?["atMs"]:[]];if(m.length===0&&u!==void 0&&p!==void 0)d={reason:u,atMs:p};else{let f=`dev-service "${r}" has a malformed persisted failure record: invalid ${m.join(", ")}`;console.warn(`[dev_services.failure_record_malformed] name=${r} invalid_fields=${m.join(",")}`),d={reason:f,atMs:s}}}return{watchdogVersion:Lt(e.watchdogVersion),name:r,command:n,cwd:o,ports:DO(e.ports),restartOnBranchChange:e.restartOnBranchChange===!0,desiredState:i,pid:Lt(e.pid),ownerPid:Lt(e.ownerPid),startedAtMs:Lt(e.startedAtMs),updatedAtMs:s,lastBranch:Ur(e.lastBranch),logPath:a,automaticRestartAttempts:Lt(e.automaticRestartAttempts)??0,automaticRestartWindowStartedAtMs:Lt(e.automaticRestartWindowStartedAtMs),automaticRestartCause:Ur(e.automaticRestartCause),failure:d}}function qO(e){return{version:yb,watchdogVersion:e.watchdogVersion??null,name:e.name,command:e.command,cwd:e.cwd,ports:[...e.ports],restartOnBranchChange:e.restartOnBranchChange,desiredState:e.desiredState,pid:e.pid??null,ownerPid:e.ownerPid??null,startedAtMs:e.startedAtMs??null,updatedAtMs:e.updatedAtMs,lastBranch:e.lastBranch??null,logPath:e.logPath,automaticRestartAttempts:e.automaticRestartAttempts,automaticRestartWindowStartedAtMs:e.automaticRestartWindowStartedAtMs??null,automaticRestartCause:e.automaticRestartCause??null,failure:e.failure===void 0?null:{reason:e.failure.reason,atMs:e.failure.atMs}}}function UO(e){return`${JSON.stringify(qO(e))}
161
- `}var Fl=5e3;function ZO(e,t,r){let n=`${Rn(e,t)}.lock`;try{Uo(Us(n),{recursive:!0});let o=(()=>{try{let s=hb(n),a=Date.now()-s.mtimeMs;if(s.isFile()&&a>=Fl){qs(n),r("dev_services.legacy_record_lock_recovered",{name:t,path:n,age_ms:a});return}return s.isDirectory()&&a>=Fl?a:void 0}catch(s){if((s!==null&&typeof s=="object"&&"code"in s?s.code:void 0)!=="ENOENT")throw s;return}})(),i=AO()(Rn(e,t),{lockfilePath:n,realpath:!1,retries:0,stale:Fl,update:1e3,onCompromised:s=>{throw r("dev_services.record_lock_compromised",{name:t,path:n,message:s.message}),s}});return o!==void 0&&r("dev_services.record_lease_recovered",{name:t,path:n,age_ms:o}),{ok:!0,release:i,path:n}}catch(o){let i=o instanceof Error?o.message:String(o);return r("dev_services.record_lock_failed",{name:t,path:n,message:i}),{ok:!1,error:`could not lock dev-service state at ${n}: ${i}`}}}function JO(e,t,r){try{return e.release(),{ok:!0}}catch(n){let o=n instanceof Error?n.message:String(n);return r("dev_services.record_unlock_failed",{name:t,path:e.path,message:o}),{ok:!1,error:`could not unlock dev-service state at ${e.path}: ${o}`}}}function FO(e,t,r){let n=Rn(e,t.name);try{Uo(Us(n),{recursive:!0});let o=`${n}.tmp`;return gb(o,UO(t),"utf8"),RO(o,n),{ok:!0}}catch(o){let i=o instanceof Error?o.message:String(o);return r("dev_services.record_write_failed",{path:n,message:i}),{ok:!1,error:`could not persist dev-service state at ${n}: ${i}`}}}function Vl(e,t,r,n){let o=ZO(e,t.name,r);if(!o.ok)return{ok:!1,error:o.error,persisted:!1};n?.(o.path);let i=FO(e,t,r),s=JO(o,t.name,r);return i.ok?s.ok?{ok:!0}:{ok:!1,error:s.error,persisted:!0}:{ok:!1,error:i.error,persisted:!1}}function Gl(e,t){let r=Zs(t);if(r===void 0)return;let n;try{n=fb(Rn(e,r),"utf8")}catch{return}try{return LO(JSON.parse(n))}catch{return}}function VO(e){let t;try{t=TO(Zr(e,"services"))}catch{return[]}let r=[];for(let n of t){if(!n.endsWith(".json"))continue;let o=Gl(e,n.slice(0,-5));o!==void 0&&r.push(o)}return r.sort((n,o)=>n.name.localeCompare(o.name))}function vb(e,t){let r;try{r=fb(Hl(e,t),"utf8")}catch{return}try{let n=JSON.parse(r);if(!Be(n))return;let o=Lt(n.atMs);return o===void 0?void 0:{code:typeof n.code=="number"?n.code:null,signal:typeof n.signal=="string"?n.signal:null,atMs:o}}catch{return}}function WO(e){return JSON.stringify(e)}function BO(){return`
162
- const { spawn } = require('node:child_process');
163
- const fs = require('node:fs');
164
- const config = JSON.parse(process.argv[process.argv.length - 1]);
165
- const child = spawn(config.command, config.args, { cwd: config.cwd, stdio: 'inherit' });
166
- let done = false;
167
- function cleanupFailed(branch, error) {
168
- const message = error && error.message ? error.message : String(error);
169
- process.stderr.write('dev-service watchdog cleanup failed: branch=' + branch + ' reason=' + message + '\\n');
170
- }
171
- function shutdown(signal) {
172
- if (done) return;
173
- done = true;
174
- try { process.kill(-process.pid, signal); }
175
- catch (groupError) {
176
- cleanupFailed('shutdown_group', groupError);
177
- try { child.kill(signal); } catch (childError) { cleanupFailed('shutdown_child', childError); }
178
- }
179
- }
180
- process.on('SIGINT', () => shutdown('SIGINT'));
181
- process.on('SIGTERM', () => shutdown('SIGTERM'));
182
- process.on('SIGHUP', () => shutdown('SIGTERM'));
183
- child.on('exit', (code, signal) => {
184
- clearInterval(watchdog);
185
- // Record the exit before following the child down, so a crash is
186
- // explainable from dev_service_status/logs after the fact. Best-effort:
187
- // never let bookkeeping block teardown.
188
- try {
189
- fs.writeFileSync(config.exitStatusPath, JSON.stringify({ code: code, signal: signal, atMs: Date.now() }) + '\\n', 'utf8');
190
- } catch (error) { cleanupFailed('record_child_exit', error); }
191
- process.removeAllListeners('SIGINT');
192
- process.removeAllListeners('SIGTERM');
193
- process.removeAllListeners('SIGHUP');
194
- // Sweep any grandchildren left in the group (a dev server that forked
195
- // workers must not leak them past its own death), then follow the child.
196
- try { process.kill(-process.pid, 'SIGKILL'); } catch (error) { cleanupFailed('sweep_child_group', error); }
197
- if (signal) {
198
- try { process.kill(process.pid, signal); }
199
- catch (error) { cleanupFailed('mirror_child_signal', error); }
200
- }
201
- process.exit(signal ? 1 : code == null ? 0 : code);
202
- });
203
- child.on('error', (err) => {
204
- try {
205
- fs.writeFileSync(config.exitStatusPath, JSON.stringify({ code: 127, signal: null, atMs: Date.now() }) + '\\n', 'utf8');
206
- } catch (error) { cleanupFailed('record_spawn_failure', error); }
207
- process.stderr.write('dev-service spawn failed: ' + (err && err.message) + '\\n');
208
- process.exit(1);
209
- });
210
- function currentOwnerPid() {
211
- try {
212
- const record = JSON.parse(fs.readFileSync(config.recordPath, 'utf8'));
213
- if (typeof record.ownerPid !== 'number') {
214
- throw new Error('dev-service owner record has no numeric ownerPid');
215
- }
216
- return record.ownerPid;
217
- } catch (error) {
218
- const message = error && error.message ? error.message : String(error);
219
- process.stderr.write('dev-service owner record failed: ' + message + '\\n');
220
- try {
221
- fs.writeFileSync(config.exitStatusPath, JSON.stringify({ code: 126, signal: null, atMs: Date.now() }) + '\\n', 'utf8');
222
- } catch (recordError) { cleanupFailed('record_owner_failure', recordError); }
223
- try { child.kill('SIGKILL'); } catch (childError) { cleanupFailed('owner_failure_child', childError); }
224
- try { process.kill(-process.pid, 'SIGKILL'); } catch (groupError) { cleanupFailed('owner_failure_group', groupError); }
225
- process.exit(126);
226
- }
227
- }
228
- const watchdog = setInterval(() => {
229
- // Inlined devServiceOwnerAlive (keep in sync): the CURRENT owning runner's
230
- // death takes the whole service group down. The durable record is reread so
231
- // a replacement runner can transfer the live group before its predecessor
232
- // exits.
233
- // EPERM = alive-but-unsignalable; anything else thrown by kill(pid, 0)
234
- // means the runner is gone.
235
- const ownerPid = currentOwnerPid();
236
- if (ownerPid > 0) {
237
- let alive = true;
238
- try { process.kill(ownerPid, 0); }
239
- catch (e) { alive = e && e.code === 'EPERM'; }
240
- if (!alive) {
241
- try { child.kill('SIGKILL'); } catch (childError) { cleanupFailed('owner_dead_child', childError); }
242
- try { process.kill(-process.pid, 'SIGKILL'); } catch (groupError) { cleanupFailed('owner_dead_group', groupError); }
243
- process.exit(0);
244
- }
245
- }
246
- }, config.pollIntervalMs);
247
- `.trim()}function HO(e,t){return{command:e,args:["-e",BO(),WO(t)]}}function wb(e,t=r=>process.kill(r,0)){if(e===void 0||e<=1)return!1;try{return t(-e),!0}catch(r){return r?.code==="EPERM"}}function Kl(e,t){if(t.pid===void 0||t.pid<=1)return!1;let r=vb(e,t.name);return r!==void 0&&t.startedAtMs!==void 0&&r.atMs>=t.startedAtMs?!1:wb(t.pid)}async function Ql(e,t=750,r="127.0.0.1"){return await new Promise(n=>{let o=IO({port:e,host:r}),i=s=>{o.removeAllListeners(),o.destroy(),n(s)};o.setTimeout(t),o.once("connect",()=>i(!0)),o.once("timeout",()=>i(!1)),o.once("error",()=>i(!1))})}async function GO(e,t){let r=Kl(e,t),n=[];for(let i of t.ports)n.push({port:i,listening:r?await Ql(i):!1});let o=t.desiredState==="stopped"?"stopped":!r&&t.failure!==void 0?"failed":r?n.every(i=>i.listening)?"running":"unhealthy":"exited";return{record:t,liveness:o,portProbes:n,lastExit:vb(e,t.name),failure:t.failure}}async function Yl(e){let t=[];for(let r of VO(e))t.push(await GO(e,r));return t}function KO(e=process.env){let t=e.SHELL?.trim();return t!==void 0&&t!==""?t:"/bin/sh"}async function kb(e){let t=e.log??Bl,r=Zs(e.definition.name);if(r===void 0)return{ok:!1,error:"invalid service name: use 1-64 lowercase letters, digits, ., _ or -"};let n=e.definition.command.trim();if(n==="")return{ok:!1,error:"service command must not be empty"};try{if(!hb(e.definition.cwd).isDirectory())return{ok:!1,error:`cwd is not a directory: ${e.definition.cwd}`}}catch{return{ok:!1,error:`cwd does not exist: ${e.definition.cwd}`}}let o=Gl(e.scopeDir,r);o!==void 0&&Kl(e.scopeDir,o)&&await Wl(o.pid,t,r);let i=e.nowMs??Date.now(),s=bb(e.scopeDir,r),a=Hl(e.scopeDir,r),c;try{Uo(Us(s),{recursive:!0}),Uo(Zr(e.scopeDir,"services"),{recursive:!0}),Uo(Us(a),{recursive:!0}),c=mb(s,"a")}catch(y){return{ok:!1,error:`cannot open service log: ${y instanceof Error?y.message:String(y)}`}}try{qs(a,{force:!0})}catch{}let d=e.shellPath??KO(),u=HO(e.nodeExecPath??process.execPath,{command:d,args:["-lc",n],cwd:e.definition.cwd,pollIntervalMs:e.watchdogPollIntervalMs??500,recordPath:Rn(e.scopeDir,r),exitStatusPath:a});try{gb(c,`
248
- --- linzumi dev-service "${r}" starting at ${new Date(i).toISOString()} (owner pid ${e.ownerPid}) ---
249
- $ ${n}
250
- `)}catch{t("dev_services.start_banner_write_failed",{name:r,log_path:s})}let p={watchdogVersion:MO,name:r,command:n,cwd:e.definition.cwd,ports:[...new Set(e.definition.ports)].sort((y,v)=>y-v),restartOnBranchChange:e.definition.restartOnBranchChange===!0,desiredState:"stopped",pid:void 0,ownerPid:e.ownerPid,startedAtMs:i,updatedAtMs:i,lastBranch:void 0,logPath:s,automaticRestartAttempts:e.automaticRestartState?.attempts??0,automaticRestartWindowStartedAtMs:e.automaticRestartState?.windowStartedAtMs,automaticRestartCause:e.automaticRestartState?.cause,failure:{reason:`dev service "${r}" start did not complete`,atMs:i}},m=Vl(e.scopeDir,p,t);if(!m.ok){try{Ls(c)}catch(y){t("dev_services.log_close_failed",{name:r,message:y instanceof Error?y.message:String(y)})}return m}try{await e.beforeWatchdogSpawnForTest?.()}catch(y){try{Ls(c)}catch(v){t("dev_services.log_close_failed",{name:r,message:v instanceof Error?v.message:String(v)})}return{ok:!1,error:y instanceof Error?y.message:`start interrupted before watchdog spawn: ${String(y)}`}}let f;try{let y=OO(u.command,[...u.args],{cwd:e.definition.cwd,detached:!0,stdio:["ignore",c,c],env:{...process.env,ELECTRON_RUN_AS_NODE:"1"}});y.unref(),f=y.pid}catch(y){return{ok:!1,error:`spawn failed: ${y instanceof Error?y.message:String(y)}`}}finally{try{Ls(c)}catch(y){t("dev_services.log_close_failed",{name:r,message:y instanceof Error?y.message:String(y)})}}if(f===void 0)return{ok:!1,error:"spawn failed: no pid"};let h={...p,desiredState:"running",pid:f,failure:void 0},g=Vl(e.scopeDir,h,t,e.afterFinalRecordLockedForTest);return g.ok?(t("dev_services.started",{name:r,pid:f,owner_pid:e.ownerPid,cwd:e.definition.cwd,ports:[...h.ports]}),{ok:!0,record:h}):(g.persisted||await Wl(f,t,r,0),g)}async function Wl(e,t,r,n=3e3){if(e===void 0||e<=1)return;try{process.kill(-e,"SIGTERM")}catch{return}let o=Date.now()+n;for(;Date.now()<o;){if(!wb(e))return;await new Promise(i=>setTimeout(i,100))}try{process.kill(-e,"SIGKILL"),t("dev_services.stop_escalated",{name:r,pgid:e})}catch{}}async function Xl(e){let t=e.log??Bl,r=Gl(e.scopeDir,e.name);if(r===void 0)return{ok:!1,error:`unknown service: ${e.name}`};Kl(e.scopeDir,r)&&await Wl(r.pid,t,r.name);let n={...r,desiredState:"stopped",pid:void 0,ownerPid:void 0,updatedAtMs:e.nowMs??Date.now(),failure:void 0},o=Vl(e.scopeDir,n,t);return o.ok?(t("dev_services.stopped",{name:r.name}),{ok:!0,record:n}):o}async function xb(e){let t=e.log??Bl,r=await Xl(e);if(!r.ok)return r;try{qs(Rn(e.scopeDir,r.record.name),{force:!0}),qs(Hl(e.scopeDir,r.record.name),{force:!0})}catch(n){let o=n instanceof Error?n.message:String(n);return t("dev_services.remove_failed",{name:r.record.name,message:o}),{ok:!1,error:`could not remove dev service "${r.record.name}": ${o}`}}return r}function Sb(e,t,r=16384){let n=Zs(t);if(n===void 0)return;let o=bb(e,n),i;try{i=mb(o,"r");let s=zO(i).size,a=Math.min(s,r),c=Buffer.alloc(a);return PO(i,c,0,a,s-a),c.toString("utf8")}catch{return}finally{if(i!==void 0)try{Ls(i)}catch{}}}var cD=10*6e4;function $b(e){return{name:"linzumi",command:e.command??"linzumi",args:[...e.argsPrefix??[],"mcp","server","--api-url",e.kandanUrl,...e.authFilePath===void 0?[]:["--auth-file",e.authFilePath],...e.delegationAuthFilePath===void 0?[]:["--delegation-auth-file",e.delegationAuthFilePath],...e.ownerUsername===void 0?[]:["--owner-username",e.ownerUsername],...e.cwd===void 0?[]:["--cwd",e.cwd],...e.threadId===void 0?[]:["--thread-id",e.threadId],"--mode",e.operatingMode??"text",...e.toolScope===void 0||e.toolScope==="all"?[]:["--tool-scope",e.toolScope],...e.agentSession===!0?["--agent-session"]:[],...e.askUserQuestionTool===!0?["--ask-user-question-tool"]:[],...e.multiAgentJobs===!0?["--multi-agent-jobs"]:[]],env:{...e.accessToken===void 0?{}:{LINZUMI_MCP_ACCESS_TOKEN:e.accessToken},...e.devServices===void 0?{}:{LINZUMI_DEV_SERVICES_SCOPE:e.devServices.scope,LINZUMI_DEV_SERVICES_OWNER_PID:String(e.devServices.ownerPid)},ELECTRON_RUN_AS_NODE:"1"}}}function zb(e){return`${JSON.stringify({mcpServers:{[e.name]:{command:e.command,args:e.args,env:e.env}}},null,2)}
251
- `}function Tb(e){return`[mcp_servers.${e.name}]
252
- command = ${JSON.stringify(e.command)}
253
- args = ${QO(e.args)}
254
- ${Object.keys(e.env).length===0?"":`env = ${YO(e.env)}
255
- `}`}function QO(e){return`[${e.map(t=>JSON.stringify(t)).join(", ")}]`}function YO(e){return`{ ${Object.entries(e).map(([r,n])=>`${r} = ${JSON.stringify(n)}`).join(", ")} }`}var Pb="linzumi_ask_user_question",Zo=4,Jo=12,Fo=2,Vo=4,Rb="Other";var Ob=2147483647,XO=2147483,lD=XO*1e3-5*6e4,Eb="linzumi_ask_user_question",jb="plan_mode_native_interview_tool",Ib="no_active_turn";function eE(e){let t=e.trim().toLowerCase();switch(t){case"other":case"something else":case"something else...":return!0;default:return t.includes("other")||t.includes("something else")}}function Cb(e){let t=we(e),r=qr(t?.questions);if(r===void 0)return{type:"invalid",message:"questions: expected an array"};if(r.length===0)return{type:"invalid",message:"questions: min 1, got 0"};if(r.length>Zo)return{type:"invalid",message:`questions: max ${Zo}, got ${r.length}`};let n=[],o=new Set;for(let[i,s]of r.entries()){let a=we(s);if(a===void 0)return{type:"invalid",message:`questions[${i}]: expected an object`};let c=ye(a.question);if(c===void 0)return{type:"invalid",message:`questions[${i}].question: must be a non-empty string`};if(o.has(c))return{type:"invalid",message:`questions: duplicate question text ${JSON.stringify(c)}`};let d=ye(a.header);if(d===void 0)return{type:"invalid",message:`questions[${i}].header: must be a non-empty string`};if(d.length>Jo)return{type:"invalid",message:`questions[${i}].header: max ${Jo} chars, got ${d.length}`};if(a.multiSelect!==void 0&&typeof a.multiSelect!="boolean")return{type:"invalid",message:`questions[${i}].multiSelect: must be a boolean`};let u=qr(a.options);if(u===void 0)return{type:"invalid",message:`questions[${i}].options: expected an array`};if(u.length<Fo)return{type:"invalid",message:`questions[${i}].options: min ${Fo}, got ${u.length}`};if(u.length>Vo)return{type:"invalid",message:`questions[${i}].options: max ${Vo}, got ${u.length}`};let p=[],m=new Set;for(let[f,h]of u.entries()){let g=we(h),y=ye(g?.label);if(g===void 0||y===void 0)return{type:"invalid",message:`questions[${i}].options[${f}].label: must be a non-empty string`};if(g.description!==void 0&&typeof g.description!="string")return{type:"invalid",message:`questions[${i}].options[${f}].description: must be a string`};if(eE(y))return{type:"invalid",message:`questions[${i}].options[${f}].label: ${JSON.stringify(y)} is reserved for the built-in Other option`};if(m.has(y))return{type:"invalid",message:`questions[${i}].options: duplicate label ${JSON.stringify(y)}`};m.add(y),p.push({label:y,description:typeof g.description=="string"?g.description:""})}o.add(c),n.push({question:c,header:d,options:p,multiSelect:a.multiSelect===!0})}return{type:"ok",request:{questions:n}}}function Ab(e){return{message:"Linzumi interview: the user is being asked in the Linzumi thread.",requestedSchema:{type:"object",properties:Object.fromEntries(e.questions.map(t=>[t.question,{type:"string",description:t.header}])),required:e.questions.map(t=>t.question)},_meta:{[Eb]:{version:1,questions:e.questions.map(t=>({question:t.question,header:t.header,multiSelect:t.multiSelect,options:t.options.map(r=>({label:r.label,description:r.description}))}))}}}}function Mb(e,t){let r=we(t??void 0);if(r===void 0)return{type:"invalid",message:"the runner accepted the interview but returned no answers; it may predate linzumi_ask_user_question support"};let n={};for(let o of e.questions){let i=r[o.question];if(typeof i!="string")return{type:"invalid",message:`the runner returned no answer for question ${JSON.stringify(o.question)}`};try{n[o.question]=JSON.parse(i)}catch{return{type:"invalid",message:`the runner returned an undecodable answer for question ${JSON.stringify(o.question)}`}}}return{type:"ok",answers:n}}function Nb(e){return ye(we(we(e)?.[Eb])?.reason)}var Db=`<linzumi_markdown_media_guidance>
256
- Some Linzumi users have opted into rich Markdown media rendering. When you are
257
- writing a visible Linzumi message, channel message, or thread reply, you may use
258
- these Markdown-compatible media directives:
259
-
260
- - Audio: ::audio[Label]{src="https://serve.linzumi.com/api/v2/workspaces/<workspace>/channels/<channel>/files/<file>/download?share_token=<token>" caption="Short caption" meta="MP3, 12s" source="Original source"}
261
- - Video: ::video[Label]{src="https://serve.linzumi.com/api/v2/workspaces/<workspace>/channels/<channel>/files/<file>/download?share_token=<token>" caption="Short caption" meta="MP4, 1080p" poster="https://serve.linzumi.com/api/v2/workspaces/<workspace>/channels/<channel>/files/<poster-file>/download?share_token=<token>" source="Original source"}
262
- - Image: ::image[Label]{src="https://serve.linzumi.com/api/v2/workspaces/<workspace>/channels/<channel>/files/<file>/download?share_token=<token>" caption="Short caption" meta="PNG, 1200x800" source="Original source"}
263
- - Markdown image: ![Label](https://serve.linzumi.com/api/v2/workspaces/<workspace>/channels/<channel>/files/<file>/download?share_token=<token> "Short caption")
264
-
265
- <media_rules>
266
- - Use this syntax only for user-visible media that helps the user inspect or
267
- play the artifact directly in the message.
268
- - "src" is required. Every other field is optional.
269
- - "src" must be a full Linzumi attachment download URL on
270
- "https://serve.linzumi.com/api/v2/workspaces/.../channels/.../files/.../download".
271
- Do not use arbitrary external URLs for auto-rendered media.
272
- - "poster" is optional, video-only, and must use the same full Linzumi
273
- attachment download URL shape. If poster is omitted, the video still renders
274
- with the browser's native unloaded video surface.
275
- - "caption", "meta", and "source" are optional text fields. Keep them short.
276
- - Use at most 10 media embeds in one message. If there are more artifacts,
277
- attach them and summarize the rest with ordinary links or text.
278
- - Do not use root-relative URLs such as "/files/a.mp3", local filesystem paths
279
- such as "/tmp/a.mp3", "file://" URLs, object-store upload URLs, third-party
280
- CDN URLs, or guessed attachment URLs.
281
- - If you created local files that should be attached, upload/attach the files
282
- first. Then use the returned "message.attachments[].url" absolute URL in
283
- "src" or "poster". For a single final message that both attaches files and
284
- embeds them, use a two-step flow: create or target the message with the
285
- attachments, then edit the same message body with directives that reference
286
- the returned absolute URLs. When upload/attach returns "target_seq", use that
287
- value as target.message_seq in linzumi_edit_message for the follow-up
288
- body-only edit; the returned "message" is the edit event that carries the new
289
- attachment URLs, and "target_message" is the original target.
290
- - If you do not yet have a returned absolute attachment URL, mention the file as
291
- an attachment instead of writing a media directive.
292
- </media_rules>
293
-
294
- <media_examples>
295
- Audio examples:
296
-
297
- GOOD:
298
- ::audio[Temple bell]{src="https://serve.linzumi.com/api/v2/workspaces/linzumi/channels/general/files/file-123/download?share_token=token" caption="Completion cue used in the demo." meta="MP3, 12s" source="Generated by the agent"}
299
- Why good: It uses the audio directive, includes the required Linzumi attachment download URL in "src", and keeps optional descriptive fields short.
300
-
301
- GOOD:
302
- | Sound | Use | Player |
303
- | --- | --- | --- |
304
- | Alert chime | Error state cue | ::audio[Alert chime]{src="https://serve.linzumi.com/api/v2/workspaces/linzumi/channels/general/files/file-124/download?share_token=token" caption="Short, dry chime." meta="WAV, 3s"} |
305
- Why good: It shows that audio embeds compose inside Markdown tables while still using a trusted Linzumi attachment URL.
306
-
307
- BAD:
308
- ::audio[Temple bell]{src="/files/temple-bell.mp3" caption="Root-relative URLs are not allowed."}
309
- Why bad: A root-relative path is not a full returned attachment URL and will not be auto-rendered.
310
-
311
- BAD:
312
- ::audio[Alert chime]{src="https://cdn.example.com/audio/alert-chime.wav" caption="External CDN media should not auto-render."}
313
- Why bad: Third-party media URLs can create unwanted automatic fetches for many viewers; link to external sources with ordinary Markdown instead.
314
-
315
- Video examples:
316
-
317
- GOOD:
318
- ::video[Flow recording]{src="https://serve.linzumi.com/api/v2/workspaces/linzumi/channels/general/files/file-456/download?share_token=token" caption="Composer flow with media playback." meta="WebM, 44s" poster="https://serve.linzumi.com/api/v2/workspaces/linzumi/channels/general/files/file-789/download?share_token=token"}
319
- Why good: Both "src" and the optional "poster" point to returned Linzumi attachment download URLs.
320
-
321
- GOOD:
322
- | Clip | Notes | Player |
323
- | --- | --- | --- |
324
- | Routing demo | Shows the happy path | ::video[Routing demo]{src="https://serve.linzumi.com/api/v2/workspaces/linzumi/channels/general/files/file-457/download?share_token=token" caption="Screen recording of routing." meta="MP4, 1080p"} |
325
- Why good: It omits "poster", which is allowed, and keeps the video playable inside a table using the required Linzumi URL shape.
326
-
327
- BAD:
328
- ::video[Flow recording]{src="file:///tmp/flow.webm" caption="file:// URLs are not accessible in Linzumi."}
329
- Why bad: "file://" URLs point at the agent's machine, not the user's Linzumi attachment, so the renderer will leave the syntax inert.
330
-
331
- BAD:
332
- ::video[Flow recording]{src="https://uploads.example.com/presigned-put-url" caption="Do not use temporary upload URLs; use the returned Linzumi download URL."}
333
- Why bad: Upload or object-store URLs are not stable returned Linzumi download URLs and can expire or expose the wrong transport seam.
334
-
335
- Image examples:
336
-
337
- GOOD:
338
- ::image[Final UI]{src="https://serve.linzumi.com/api/v2/workspaces/linzumi/channels/general/files/file-abc/download?share_token=token" caption="Final media comparison table." meta="PNG, desktop viewport" source="Playwright screenshot"}
339
- Why good: It uses the image directive with the required "src" and useful optional caption, meta, and source fields.
340
-
341
- GOOD:
342
- ![Waveform preview](https://serve.linzumi.com/api/v2/workspaces/linzumi/channels/general/files/file-def/download?share_token=token "Caption shown under the image")
343
- Why good: Markdown image syntax is supported when the URL is the returned Linzumi attachment download URL.
344
-
345
- BAD:
346
- ::image[Final UI]{src="./artifacts/final.png" caption="Relative paths are not accessible to the user."}
347
- Why bad: Relative paths describe local workspace files, not uploaded attachments that Linzumi can render for the viewer.
348
-
349
- BAD:
350
- ![Waveform preview](https://images.example.com/waveform-preview.png "External image URLs are not rich media embeds.")
351
- Why bad: External image hosts are intentionally not auto-rendered; attach the image first, then use the returned Linzumi URL.
352
- </media_examples>
353
-
354
- <media_reminder>
355
- Use media directives only after upload/attach returns a Linzumi download URL.
356
- Keep "src" required, all other fields optional, and never exceed 10 embeds in one message.
357
- </media_reminder>
358
- </linzumi_markdown_media_guidance>`;var tE=l.discriminatedUnion("type",[l.object({type:l.literal("text"),text:l.string(),style:l.array(l.enum(["bold","italic","code"])).optional()}).strict(),l.object({type:l.literal("actor"),user_id:l.number().int().positive(),fallback:l.string().min(1)}).strict()]),Jr=l.array(l.object({kind:l.literal("prose"),tokens:l.array(tE).min(1)}).strict()).min(1).describe("Canonical BlockSequence. Actor mentions must be actor tokens; literal @ text stays a text token."),Lb=64;function rE(e){switch(e){case"all":return!0;case"coding":case"onboarding-discovery":return!1}}function nE(e){switch(e){case"voice":return!0;case"text":return!1}}function oE(e){return e.trim().replace(/^:+/,"").replace(/:+$/,"").toLowerCase()}var qb=l.string().min(1).refine(e=>oE(e).length<=Lb,{message:`Custom emoji shortcode name must be at most ${Lb} characters after trimming surrounding colons.`}),iE=new Map([["api-url",{kind:"value"}],["token",{kind:"value"}],["auth-file",{kind:"value"}],["delegation-auth-file",{kind:"value"}],["workspace",{kind:"value"}],["channel",{kind:"value"}],["owner-username",{kind:"value"}],["mode",{kind:"value"}],["cwd",{kind:"value"}],["thread-id",{kind:"value"}],["format",{kind:"value"}],["command",{kind:"value"}],["tool-scope",{kind:"value"}],["agent-session",{kind:"boolean"}],["ask-user-question-tool",{kind:"boolean"}],["multi-agent-jobs",{kind:"boolean"}],["include-token",{kind:"boolean"}],["help",{kind:"boolean"}]]);async function Hb(e){let[t,...r]=e;switch(t){case void 0:case"--help":case"-h":process.stdout.write(Gb());return;case"server":await sE(r);return;case"config":await _E(r);return;case"doctor":await bE(r);return;default:throw new Error(`unknown linzumi mcp command: ${t}`)}}function Gb(){return`Linzumi MCP
359
-
360
- Usage:
361
- linzumi mcp server --api-url <url> [--mode voice|text] [--workspace <slug> --channel <slug>]
362
- linzumi mcp server --api-url <url> --delegation-auth-file <path> [--mode voice|text]
363
- linzumi mcp config --api-url <url> --format codex|claude-code [--include-token]
364
- linzumi mcp doctor --api-url <url> [--workspace <slug> --channel <slug>]
365
-
366
- Tools:
367
- linzumi_get_message Read one message by scoped seq or Linzumi message URL.
368
- linzumi_get_thread Read one bounded thread by ID.
369
- linzumi_get_thread_transcript
370
- Read a thread's FULL transcript (tool calls, commands,
371
- diffs) as canonical IR nodes, cursor-paginated.
372
- linzumi_get_channel Read bounded recent messages and channel metadata.
373
- linzumi_web_search Search the public web (news, docs, live info).
374
- linzumi_fetch_url Fetch a public http(s) URL as readable text.
375
- linzumi_list_ui_targets
376
- List UI surfaces the user can be asked to open.
377
- linzumi_open_ui Ask the user (consent toast) to open one UI surface
378
- in their own Linzumi window.
379
- linzumi_get_coding_job_metadata
380
- Read the current coding job goal, plan, and workflow metadata.
381
- linzumi_rename_coding_job
382
- Update the coding job thread and workflow-facing title.
383
- linzumi_upsert_coding_job_plan
384
- Set or update the coding job goal.
385
- linzumi_replace_coding_job_plan_steps
386
- Replace the ordered coding job plan steps.
387
- linzumi_update_coding_job_plan_step
388
- Update one coding job plan step status or note.
389
- linzumi_link_coding_job_pull_request
390
- Link the coding job to its primary GitHub pull request.
391
- linzumi_list_vault_secrets
392
- List vault secret names, descriptions, and owner scope.
393
- linzumi_list_projects
394
- List workspace projects with their project ids.
395
- linzumi_get_project_tasks
396
- Read a project's task graph: groups, issues, statuses,
397
- derived readiness, and dependency edges.
398
- linzumi_create_project_task
399
- Create a task group or issue in a project.
400
- linzumi_update_project_task
401
- Update, transition, reassign, or reorganize a task.
402
- linzumi_delete_project_task
403
- Permanently delete a task group or issue.
404
- linzumi_add_project_task_dependency
405
- Add a blocked-by edge between two issues (acyclic).
406
- linzumi_remove_project_task_dependency
407
- Remove a blocked-by edge between two issues.
408
- linzumi_get_call_transcript
409
- Read a completed notetaker call's full transcript.
410
- linzumi_start_coding_job
411
- Start a coding job (a project-bound job starts ready
412
- task items with project_task_id). Honor existing explicit launch authorization
413
- within its scope; otherwise offer and wait for acceptance.
414
- Readiness alone is not authorization; do not duplicate active work.
415
- linzumi_note_project_directory
416
- Record one discovered local Git project directory.
417
- linzumi_note_agent_conversation
418
- Record one discovered Codex or Claude Code conversation.
419
- linzumi_note_onboarding_discovery_status
420
- Record onboarding discovery progress or failure.
421
- linzumi_send_channel_message
422
- Post a NEW standalone message to the scoped channel
423
- (not how you reply to the current request).
424
- linzumi_send_thread_reply
425
- Post a reply into some OTHER existing thread
426
- (not how you reply to the current request).
427
- linzumi_send_dm Send a plain-text DM to a visible user.
428
- linzumi_dm_owner Send a plain-text DM to the configured owner username.
429
- linzumi_get_vault_values
430
- Request approved named vault values for a thread.
431
- linzumi_upload_files
432
- Attach generated files and return absolute file URLs
433
- suitable for Markdown media src/poster attributes.
434
- linzumi_upload_custom_emoji
435
- Upload a local image as a workspace custom emoji.
436
- linzumi_rename_custom_emoji
437
- Rename an existing workspace custom emoji.
438
- linzumi_dev_service_start
439
- Start (or declaratively restart) a named managed dev
440
- service owned by the runner's dev-service registry.
441
- linzumi_dev_service_stop
442
- Stop a managed dev service.
443
- linzumi_dev_service_status
444
- List managed dev services with liveness + port health.
445
- linzumi_dev_service_logs
446
- Read the tail of a managed dev service's log.
447
- linzumi_dev_service_remove
448
- Stop a managed dev service and delete its registration.
449
-
450
- Auth:
451
- Uses --token, LINZUMI_MCP_ACCESS_TOKEN, or cached local runner OAuth from linzumi auth.
452
- Hosted personal agents use --delegation-auth-file with a signed delegation grant.
453
- `}async function sE(e){let t=tp(e);if(t.get("help")===!0){process.stdout.write(Gb());return}let r=np(t,"api-url"),n=await ep({kandanUrl:r,explicitToken:te(t,"token")??process.env.LINZUMI_MCP_ACCESS_TOKEN,authFilePath:te(t,"auth-file"),delegationAuthFilePath:te(t,"delegation-auth-file"),workspaceSlug:te(t,"workspace"),channelSlug:te(t,"channel")}),o=te(t,"owner-username")??process.env.LINZUMI_MCP_OWNER_USERNAME,i=rp(te(t,"mode")),s=Kb(te(t,"tool-scope")),a=te(t,"cwd")??process.cwd(),c=te(t,"thread-id")??process.env.LINZUMI_THREAD_RUNNER_KANDAN_THREAD_ID,d=t.get("agent-session")===!0?I_(te(t,"auth-file")):void 0,u=Jl({kandanUrl:r,accessToken:n.accessToken,authMode:n.mode,operatingMode:i,topicWakeTurnCapability:d}),p=new Es({name:"linzumi",version:"0.1.0"});yE(p),uE(p,{client:u,toolScope:s,operatingMode:i,cwd:a,kandanUrl:r,defaultThreadId:c,ownerUsername:o,agentSession:t.get("agent-session")===!0,topicQuietAuthFilePath:d===void 0?void 0:te(t,"auth-file"),documentSurfaces:Dl(n.accessToken),askUserQuestionTool:t.get("ask-user-question-tool")===!0,devServices:cE(process.env),multiAgentJobs:t.get("multi-agent-jobs")===!0});let m=new Is;await p.connect(d===void 0?m:dE(m,()=>u.recordTopicWakeToolAttempt(),te(t,"auth-file")))}var Ub="One or two sentences a teammate skimming the board would want: what changed, and what happens next. Standup register, present tense, name agents and lanes plainly. No thread ids or UUIDs unless needed for lookup; proofs and evidence belong in the thread, not here. Good: 'Retired the silent watchdog and spawned Thorne to replace it \u2014 running lean at three children.' Bad: 'Broken 67f1d639 archived abandoned; board claim preceded spawn; children verified at exactly 3.'",aE=new Intl.Segmenter("en",{granularity:"grapheme"}),Zb=l.string().min(1).refine(e=>Array.from(aE.segment(e)).length<=240,{message:"status_note over 240 chars \u2014 trim to what a reader needs; put evidence in the thread."});function cE(e){let t=e.LINZUMI_DEV_SERVICES_SCOPE?.trim(),r=Number.parseInt(e.LINZUMI_DEV_SERVICES_OWNER_PID??"",10);if(!(t===void 0||t===""||!Number.isInteger(r)||r<=0))return{scopeDir:_b(t),ownerPid:r}}function dE(e,t,r){let n=Promise.resolve(),o="accepting",i=new Map,s=()=>{if(o="closed_after_failure",console.warn("topic_quiet_tool_admission_refused"),r!==void 0)try{Do(r,"attempt_failed")}catch{console.warn("topic_quiet_fault_custody_unresolved")}},a={start:async()=>{e.onclose=()=>a.onclose?.(),e.onerror=c=>a.onerror?.(c),e.onmessage=(c,d)=>{if(o!=="accepting"){console.warn("topic_quiet_transport_closed_request_refused");return}if(!("method"in c)||c.method!=="tools/call"||!("id"in c)){a.onmessage?.(c,d);return}let u=u_(c.params??null);n=n.then(async()=>{if(o!=="accepting"){console.warn("topic_quiet_transport_queued_request_refused");return}try{if(u||(r!==void 0&&Do(r,"attempt_pending"),await t(),r!==void 0&&Do(r,"attempt_acknowledged")),a.onmessage===void 0)throw new Error("topic_quiet_transport_unbound");let p=new Promise((m,f)=>{i.set(c.id,{quietRequest:u,resolve:m,reject:f})});a.onmessage(c,d),await p}catch{i.delete(c.id),s();try{await e.send({jsonrpc:"2.0",id:c.id,result:{isError:!0,content:[{type:"text",text:"topic_quiet_tool_admission_refused"}]}})}finally{await e.close()}}}).catch(()=>{console.warn("topic_quiet_transport_response_failed"),a.onerror?.(new Error("topic_quiet_transport_response_failed"))})},await e.start()},send:async(c,d)=>{let u="id"in c&&c.id!==void 0&&("result"in c||"error"in c)?i.get(c.id):void 0,p=u!==void 0&&("error"in c||"result"in c&&we(c.result)?.isError===!0);u!==void 0&&(o=l_(u.quietRequest,p,Sl("result"in c?we(c.result)?.structuredContent??null:null)),o==="closed_after_failure"&&s());try{await e.send(c,d),u?.resolve(),o!=="accepting"&&await e.close()}catch(m){throw u?.reject(m),m}finally{u!==void 0&&"id"in c&&c.id!==void 0&&i.delete(c.id)}},close:()=>e.close(),setProtocolVersion:c=>e.setProtocolVersion?.(c)};return a}function uE(e,t){let{client:r,toolScope:n,operatingMode:o,cwd:i,kandanUrl:s,defaultThreadId:a,ownerUsername:c,agentSession:d,devServices:u}=t;d&&e.tool("linzumi_complete_topic_wake_no_action","Complete an authenticated conditional topic wake when its condition requires no action. Supply a clear reason. This posts no message, proposes no edit, and cannot conceal failed tools or attempted effects. Ordinary mentions and component batches are not eligible.",{reason:l.string().refine(a_,{message:"A nonblank reason of at most 2000 UTF-8 bytes is required."})},async m=>{let f=await r.completeTopicWakeNoAction({reason:m.reason});if(!Sl(f))throw new Error("topic_quiet_server_receipt_invalid");return t.topicQuietAuthFilePath!==void 0&&Do(t.topicQuietAuthFilePath,"quiet_acknowledged"),z(f)});let p=n==="all"||n==="coding";if(t.askUserQuestionTool===!0&&e.tool(Pb,`Ask the user up to ${Zo} structured multiple-choice questions and BLOCK until they answer in the Linzumi thread. Use this whenever you need a decision or clarification mid-task. Each question needs a short header (max ${Jo} chars) and ${Fo}-${Vo} options {label, description}; a built-in "${Rb}" free-text choice is always shown in addition to your options, so never add one yourself. Set multiSelect true to allow choosing several options. Returns {answers} keyed by question text: a single label string, an array of labels for multiSelect, and {"other": "<typed text>"} for a free-text reply.`,{questions:l.array(l.object({question:l.string().describe("The question to ask the user."),header:l.string().describe(`Short category header shown above the question (max ${Jo} chars, e.g. "Auth", "Scope").`),options:l.array(l.object({label:l.string().describe("Option label the user taps."),description:l.string().optional().describe("One-line explanation of the option.")})).describe(`${Fo}-${Vo} options for this question.`),multiSelect:l.boolean().optional().describe("True lets the user select several options; the answer becomes an array.")})).describe(`1-${Zo} questions to ask atomically.`)},async m=>wE((f,h)=>e.server.elicitInput(f,h),m)),t.documentSurfaces===!0){let m=l.number().int().positive().optional().describe("Immutable admitted entry_id from the component wake batch. Required when the batch has multiple authorized contexts; never selects newer authority."),f=async(h,g)=>z(await r.agentDocumentTool({...g,tool:h}));e.tool("linzumi_lookup_documents","Search document titles and content within the controlling human's visibility ceiling. Returns authorized results in canonical search order; zero, one, and multiple matches carry the rule-03 ambiguity meaning.",{query:l.string().min(1).describe("Document title or content search query."),component_entry_id:m},async h=>f("lookup_documents",h)),e.tool("linzumi_read_document","Read one in-scope document as full AST and metadata, including pending proposals and required-agent-context comments. Both controlling-human visibility and agent delegation are required.",{document_id:l.string().uuid().describe("Document UUID."),component_entry_id:m},async h=>f("read_document",h)),d?(e.tool("linzumi_invoke_command","Invoke a registered command authorized by the current component wake context. Use the embedding document UUID, exact command name and typed inputs from that context, a stable idempotency key, and its admitted component_entry_id. Current permissions and the frozen per-entry authority are rechecked by the server; this tool grants no new authority.",{document_id:l.string().uuid().describe("Embedding document UUID."),command_name:l.string().min(1).describe("Exact registered command name authorized by this component context."),inputs:l.record(l.unknown()).describe("Typed inputs for the registered command."),idempotency_key:l.string().min(1).describe("Stable key for this logical command invocation; preserve it on replay."),component_entry_id:m},async h=>f("invoke_command",h)),e.tool("linzumi_append_document_section","Use this tool for append-shaped document requests: add or append a new section, or add or update a tracker row as new section content, including parent-delegated work. After resolving exactly one patch target document and reading it, call this tool in the same turn; do not merely reply with suggested prose. Other authorized context documents do not make the patch target ambiguous. Supply only the heading and body Markdown: the server composes the closed structural operations. Every change is proposal-always.",{document_id:l.string().uuid().describe("Document UUID."),heading:l.string().trim().min(1).describe("Section heading."),body_markdown:l.string().trim().min(1).describe("Section body as Markdown authored by the model."),component_entry_id:m},async h=>f("append_document_section",h)),e.tool("linzumi_replace_section","Use this tool for targeted section rewrites, fixes, and tightening. After resolving exactly one patch target document and reading it, identify the section by exact heading text or its heading block UUID and supply the replacement body Markdown. The server rejects missing and ambiguous headings with actionable typed errors and composes the closed structural operations. Every change is proposal-always.",{document_id:l.string().uuid().describe("Document UUID."),heading_or_section_ref:l.string().trim().min(1).describe("Exact heading text or heading block UUID from read_document."),body_markdown:l.string().trim().min(1).describe("Replacement section body as Markdown."),component_entry_id:m},async h=>f("replace_section",h)),e.tool("linzumi_annotate_document_section","Use this tool to add a durable note to one existing heading-delimited document section without rewriting its content. After resolving exactly one patch target document and reading it, identify the section by exact heading text or its heading block UUID and supply only the note Markdown. The server rejects missing and ambiguous headings, composes the anchored comment, and persists a proposal before any authorized auto-apply.",{document_id:l.string().uuid().describe("Document UUID."),heading_or_section_ref:l.string().trim().min(1).describe("Exact heading text or heading block UUID from read_document."),note_markdown:l.string().trim().min(1).describe("Durable section note as Markdown."),component_entry_id:m},async h=>f("annotate_document_section",h)),e.tool("linzumi_decline_document_action","Decline the current document action when no advertised document intent can express it. Give a clear reason; the server relays it verbatim with an honest decline prefix and satisfies the action binding.",{reason:l.string().refine(h=>h.trim().length>0,{message:"Reason must contain non-whitespace text."}).describe("Clear reason the available document intents cannot express the request.")},async h=>z(await r.declineDocumentAction({reason:h.reason})))):e.tool("linzumi_propose_document_patch","Submit a raw revisioned structural document patch. This power/API surface requires the caller to compose the closed operation vocabulary. Create a native data-bound table with the atomic create_bound_table operation containing bindingId, block, and binding; rows remain source data and must not be copied into the block. Every change is proposal-always.",{document_id:l.string().uuid().describe("Document UUID."),patch:l.object({baseRevision:l.number().int().nonnegative(),operations:l.array(l.record(l.unknown())),title:l.string().min(1).optional()}).describe("Revisioned structural document patch."),rationale:l.string().min(1).describe("Why this change is proposed."),component_entry_id:m},async h=>f("propose_document_patch",h)),d||e.tool("linzumi_create_document","Create an agent-attributed document through an atomic bootstrap proposal and apply transaction in the named folder or workspace default folder.",{title:l.string().min(1).describe("Document title."),initial_patch:l.record(l.unknown()).describe("Bootstrap structural patch."),folder_id:l.string().uuid().optional().describe("Destination folder UUID."),component_entry_id:m},async h=>f("create_document",h))}if(d){e.tool("linzumi_agent_reply","Post your single @linzumi reply for the current turn into the surface where you were mentioned. Call EXACTLY ONCE per turn with your final answer; the reply links to this working session automatically. Fails with already_replied on a second call and no_active_asker_binding when no turn is active.",{body:l.string().min(1).describe("Plain-text reply body to post."),tokens:Jr.optional()},async f=>z(await r.agentReply({body:f.body,...f.tokens===void 0?{}:{tokens:f.tokens}})));let m=async(f,h)=>z(await r.agentTopicTool({...h,tool:f}));e.tool("linzumi_create_topic_wake_subscription","Create or update a standing subscription that wakes @linzumi when new entries land on an existing workspace topic. Use this when the user asks you to watch a topic and perform an ongoing job. The server stores the instruction, derives the creator from the current asker, and targets this conversation; do not claim success without calling this tool.",{topic_slug:l.string().min(1).describe("Existing workspace topic slug to watch."),instruction:l.string().min(1).max(4e3).describe("Standing job to execute whenever a matching topic entry wakes the agent.")},async f=>m("create_topic_wake_subscription",f)),e.tool("linzumi_disable_topic_wake_subscription","Disable the current asker's standing @linzumi wake subscription for a topic. The durable row and cursor are retained so reactivation can drain the disabled-period backlog.",{topic_slug:l.string().min(1).describe("Workspace topic slug whose standing wake should stop.")},async f=>m("disable_topic_wake_subscription",f)),e.tool("linzumi_list_coding_jobs","List the coding jobs the current asker can see in this workspace: runner connections (online and recent) with their bound job threads. Live state - never answered from search.",{},async()=>z(await r.agentListCodingJobs({}))),e.tool("linzumi_start_coding_job","Start a coding job exactly as if the asking user clicked start: same runner/channel authorization, same pipeline. Returns status 'unavailable' with a reason when the runner cannot take the job (relay that honestly).",{channel:l.string().describe("Channel slug to host the job thread."),runner_key:l.string().describe("Runner (computer) to run the job on."),cwd:l.string().describe("Working directory on the runner."),work_description:l.string().min(1).describe("What the job should do - the initial instruction."),model:l.string().optional().describe("Model override (optional)."),model_provider:l.string().optional().describe("Model provider override, e.g. 'wafer' (optional)."),execution_mode:l.enum(["raw","local_vm"]).optional().describe("Execution placement override (optional)."),project_task_id:l.string().optional().describe("Project task item to bind the job to (task_id from linzumi_get_project_tasks). The task flips todo -> active and links to the new job."),visibility:l.enum(["project","private"]).optional().describe("Job visibility. Defaults to 'project'; private jobs are limited to directly authorized participants.")},async f=>z(await r.agentStartCodingJob(f))),e.tool("linzumi_interrupt_coding_job","Interrupt a coding job: mode 'steer' (default) discards its queued follow-ups so your next message lands first; mode 'stop' terminates the current turn.",{channel:l.string().describe("Channel slug hosting the job thread."),thread_id:l.string().uuid().describe("The job thread UUID."),mode:l.enum(["steer","stop"]).optional().describe("Interrupt mode; defaults to 'steer'.")},async f=>z(await r.agentInterruptCodingJob(f))),e.tool("linzumi_send_coding_job_message","Message a coding job or a person. Queue is the encouraged default: it lands in the colleague's inbox for their own cadence. Steer only for urgent, potentially-clashing work because it interrupts the running turn. Would this be worthless or harmful after their turn finishes? If no, queue. Delivery urgency is not access control. To message a person, pass to_user and omit channel and thread_id: delivery lands in their personal inbox.",{channel:l.string().optional().describe("Channel slug hosting the job thread. Required unless to_user is set."),thread_id:l.string().uuid().optional().describe("The job thread UUID. Required unless to_user is set."),to_user:l.string().min(1).optional().describe("Username of a workspace member to message instead of a job. Delivery lands in their personal inbox."),body:l.string().min(1).describe("Message body to send."),tokens:Jr.optional(),delivery:l.enum(["queue","steer"]).optional().describe("Delivery urgency. Defaults to 'queue'.")},async f=>z(await r.agentSendCodingJobMessage(f))),e.tool("linzumi_read_coding_job_thread","Read a coding job's thread (asker-visible history) plus its workflow status metadata.",{channel:l.string().describe("Channel slug hosting the job thread."),thread_id:l.string().uuid().describe("The job thread UUID."),limit:l.number().int().min(1).max(100).optional().describe("Maximum replies to return."),before_seq:l.number().int().positive().optional().describe("Return replies before this channel seq.")},async f=>z(await r.agentReadCodingJobThread(f))),e.tool("linzumi_resolve_job_approval","Resolve a coding job's pending approval request with the asking user's decision ('approve' or 'deny'). Only relays the asker's authority - never approve without their explicit instruction.",{channel:l.string().describe("Channel slug hosting the job thread."),thread_id:l.string().uuid().describe("The job thread UUID."),source_seq:l.number().int().positive().describe("Channel seq of the message the approval request rides on."),request_id:l.string().describe("The approval request id."),decision:l.enum(["approve","deny"]).describe("The asker's decision.")},async f=>z(await r.agentResolveJobApproval(f))),e.tool("linzumi_archive_coding_job","Archive a coding job's thread (or any thread the asking user owns) so it leaves the active list; history is preserved. Do this when the asker says to archive a job or thread - never just promise it.",{channel:l.string().describe("Channel slug hosting the thread."),thread_id:l.string().uuid().describe("The thread UUID to archive.")},async f=>z(await r.agentArchiveCodingJob(f))),e.tool("linzumi_unarchive_coding_job","Unarchive a previously archived coding job thread the asking user owns, returning it to the active list.",{channel:l.string().describe("Channel slug hosting the thread."),thread_id:l.string().uuid().describe("The thread UUID to unarchive.")},async f=>z(await r.agentUnarchiveCodingJob(f))),e.tool("linzumi_set_thread_status","Set a thread's lifecycle status as the asking user: 'closed' marks it done, 'open' reopens it. Works on threads the asker owns.",{channel:l.string().describe("Channel slug hosting the thread."),thread_id:l.string().uuid().describe("The thread UUID."),status:l.enum(["open","closed"]).describe("Replacement lifecycle status ('closed' = done).")},async f=>z(await r.agentSetThreadStatus(f))),e.tool("linzumi_create_channel","Create a new public channel in this workspace as the asking user. The slug is derived from the name.",{name:l.string().min(1).describe("Channel name to create.")},async f=>z(await r.agentCreateChannel(f))),e.tool("linzumi_rename_channel","Rename a channel's display name as the asking user. The channel's URL slug stays stable.",{channel:l.string().describe("Current channel slug to rename."),name:l.string().min(1).describe("New display name.")},async f=>z(await r.agentRenameChannel(f))),e.tool("linzumi_archive_channel","Archive a channel in this workspace as the asking user. History is preserved; the channel leaves the active sidebar.",{channel:l.string().describe("Channel slug to archive.")},async f=>z(await r.agentArchiveChannel(f))),e.tool("linzumi_unarchive_channel","Unarchive a previously archived channel as the asking user.",{channel:l.string().describe("Channel slug to unarchive.")},async f=>z(await r.agentUnarchiveChannel(f))),e.tool("linzumi_add_reaction","Add an emoji reaction to a channel message as the asking user. Accepts unicode emoji or a workspace :shortcode:.",{channel:l.string().describe("Channel slug containing the message."),message_seq:l.number().int().positive().describe("Channel seq of the message to react to."),emoji:l.string().min(1).describe("Emoji to add (unicode or :shortcode:).")},async f=>z(await r.agentAddReaction(f))),e.tool("linzumi_remove_reaction","Remove the asking user's emoji reaction from a channel message.",{channel:l.string().describe("Channel slug containing the message."),message_seq:l.number().int().positive().describe("Channel seq of the reacted message."),emoji:l.string().min(1).describe("Emoji to remove (unicode or :shortcode:).")},async f=>z(await r.agentRemoveReaction(f))),e.tool("linzumi_pin_message","Pin a channel message as the asking user. Thread replies re-point to their root message.",{channel:l.string().describe("Channel slug containing the message."),message_seq:l.number().int().positive().describe("Channel seq of the message to pin.")},async f=>z(await r.agentPinMessage(f))),e.tool("linzumi_unpin_message","Remove a pin from a channel message as the asking user.",{channel:l.string().describe("Channel slug containing the message."),message_seq:l.number().int().positive().describe("Channel seq of the pinned message.")},async f=>z(await r.agentUnpinMessage(f)))}n==="all"&&(e.tool("linzumi_get_message","Read one Linzumi message by scoped message_seq/message_id or a Linzumi message URL, with optional bounded before/after context.",{workspace:l.string().optional().describe("Workspace slug. Omit to use the message URL target, or the authenticated token scope without a URL."),channel:l.string().optional().describe("Channel slug. Omit to use the message URL target, or the authenticated token scope without a URL."),message_id:l.union([l.string(),l.number()]).optional().describe("Message seq inside the scoped channel."),message_seq:l.union([l.string(),l.number()]).optional().describe("Alias for message_id."),message_url:l.string().optional().describe("Full Linzumi message URL with ?message=<seq>; legacy #message-<seq> links are also supported."),before:l.number().int().min(0).max(100).optional().describe("Number of visible messages before the target."),after:l.number().int().min(0).max(100).optional().describe("Number of visible messages after the target.")},async m=>z(await r.getMessage(m))),e.tool("linzumi_get_thread","Read one Linzumi thread by thread_id in the scoped channel, including the parent message and bounded replies.",{workspace:l.string().optional().describe("Workspace slug. Omit to use the authenticated token scope."),channel:l.string().optional().describe("Channel slug. Omit to use the authenticated token scope."),thread_id:l.string().uuid().describe("Linzumi thread UUID."),limit:l.number().int().min(1).max(100).optional().describe("Maximum replies to return."),before_seq:l.number().int().positive().optional().describe("Return replies before this channel seq.")},async m=>z(await r.getThread(m))),e.tool("linzumi_get_thread_transcript","Read a Linzumi thread's full transcript as canonical IR nodes (user/assistant messages, command executions, file changes, tool calls, statuses), cursor-paginated over the complete history. Use the returned cursor with has_more to walk older pages.",{workspace:l.string().optional().describe("Workspace slug. Omit to use the authenticated token scope."),channel:l.string().optional().describe("Channel slug. Omit to use the authenticated token scope."),thread_id:l.string().uuid().describe("Linzumi thread UUID."),limit:l.number().int().min(1).max(500).optional().describe("Maximum transcript nodes per page (default 200)."),cursor:l.number().int().positive().optional().describe("Return nodes below this seq (the previous page reply cursor).")},async m=>z(await r.getThreadTranscript(m))),e.tool("linzumi_get_channel","Read scoped Linzumi channel metadata and bounded recent channel messages.",{workspace:l.string().optional().describe("Workspace slug. Omit to use the authenticated token scope."),channel:l.string().optional().describe("Channel slug. Omit to use the authenticated token scope."),limit:l.number().int().min(1).max(100).optional().describe("Maximum messages to return."),before_seq:l.number().int().positive().optional().describe("Return messages before this channel seq.")},async m=>z(await r.getChannel(m))),e.tool("linzumi_search_workspace","Search the Linzumi workspace with hybrid lexical+semantic retrieval, scoped to what the authorizing user can access. Returns scored content chunks with provenance (channel, thread, authored time) and a permalink to cite.",{workspace:l.string().optional().describe("Workspace slug. Omit to use the authenticated token scope."),query:l.string().min(1).describe("Natural-language or keyword query to retrieve against."),limit:l.number().int().min(1).max(25).optional().describe("Maximum results to return (default 10, server-capped)."),source_types:l.array(l.enum(["message","coding_job","github_pr","github_pr_review","github_check_run","github_workflow_run","github_diff","dictation","file"])).optional().describe("Restrict results to these corpora; omit for all."),authored_after:l.string().optional().describe("ISO8601 instant; only content authored at or after this time."),authored_before:l.string().optional().describe("ISO8601 instant; only content authored at or before this time."),repo:l.string().optional().describe("Restrict GitHub-sourced results to one repository by full name (owner/name)."),check_status:l.enum(["pending","success","failed"]).optional().describe("Restrict check and workflow results to one conclusion bucket.")},async m=>z(await r.searchWorkspace(m))),e.tool("linzumi_ask_workspace",'Ask the Linzumi workspace a natural-language question and get a synthesized, citation-backed answer over what the authorizing user can access. Costs an LLM call on cache misses, so prefer linzumi_search_workspace for simple lookups. A "refused" status means there was not enough accessible evidence - treat it as "the workspace does not know", never retry verbatim.',{workspace:l.string().optional().describe("Workspace slug. Omit to use the authenticated token scope."),question:l.string().min(1).max(2e3).describe("Natural-language question to answer with citations."),channel:l.string().optional().describe("Optional channel slug providing conversational context; never widens access."),allow_cached:l.boolean().optional().describe("Allow serving a cached synthesis when the evidence set is unchanged (default true). Set false to force fresh synthesis.")},async m=>z(await r.askWorkspace(m))),e.tool("linzumi_about_me","Read what the authorizing user has told Linzumi about themselves: their profile facts (homes, unit preferences, and other self-maintained attributes) plus their derived current timezone. Use it to personalize answers (e.g. pick the right city for weather, use their preferred units). Predicates may have multiple active values; prefer the one consistent with the derived timezone.",{},async m=>z(await r.aboutMe(m)))),p&&(e.tool("linzumi_web_search","Search the public web for live or external information: news, current events, weather, prices, third-party API docs, research. Returns result titles, URLs, and snippets. Use this whenever the answer lives outside the Linzumi workspace; follow up with linzumi_fetch_url to read a result page.",{query:l.string().min(1).describe("Web search query (natural language or keywords)."),limit:l.number().int().min(1).max(10).optional().describe("Maximum results to return (default 8, server-capped).")},async m=>z(await r.webSearch(m))),e.tool("linzumi_fetch_url","Fetch one public http(s) URL and return its readable text content (HTML is reduced to plain text; large pages are truncated). Use it to read pages found via linzumi_web_search or any public docs/API reference. Only public addresses are reachable - private/internal hosts are rejected with url_not_allowed.",{url:l.string().min(1).describe("Absolute public http(s) URL to fetch.")},async m=>z(await r.fetchUrl(m)))),n==="all"&&(e.tool("linzumi_list_ui_targets","List every UI surface you can ask the user to open in their own Linzumi window (channels, DMs, threads, projects, coding jobs, computers, catch-up, activity, settings tabs, pane layouts) with the structured args each kind takes. Use UI control only when the user asks for help or asks to be shown something.",{},async()=>await Bb(r.listUiTargets({}))),e.tool("linzumi_open_ui","Ask the user to open one whitelisted UI surface in their own already-open Linzumi window. A consent toast appears in THEIR session; navigation happens only if they tap Open. The call blocks until they decide and returns status opened/dismissed/expired - or error no_active_ui_session when they have no Linzumi window open (tell them to open Linzumi), or invalid_target with a detail. Use it only when the user asks for help or asks to be shown something; kinds and per-kind args come from linzumi_list_ui_targets.",{kind:l.string().min(1).describe("Target kind from linzumi_list_ui_targets (e.g. settings_workspace, channel, pane_layout)."),args:l.record(l.unknown()).optional().describe("Structured per-kind args from linzumi_list_ui_targets (never a URL - the server computes every path)."),workspace:l.string().optional().describe("Workspace slug. Omit to use the authenticated token scope.")},async m=>await Bb(r.openUi(gt(m,a))))),p&&(e.registerTool("linzumi_schedule_wake",{description:'Schedule this coding job to wake itself once and start an ordinary visible turn with the supplied prompt. Provide exactly one of fire_at or delay_minutes. Good: delay_minutes=20, prompt="Check CI, address any failures, then update the plan." Bad: prompt="wake up" (it gives the future turn no actionable context).',inputSchema:l.object({fire_at:l.string().datetime({offset:!0}).optional().describe("Future ISO8601 timestamp with timezone."),delay_minutes:l.number().int().min(1).max(525600).optional().describe("Minutes from now before the one-time wake fires."),prompt:l.string().min(1).max(4e3).describe("Actionable human-register description of exactly what to do when this job wakes.")}).refine(m=>m.fire_at===void 0!=(m.delay_minutes===void 0),{message:"provide exactly one of fire_at or delay_minutes"})},async m=>z(await r.scheduleWake(m))),e.tool("linzumi_cancel_wake","Cancel one still-scheduled wake owned by this coding job. Fired, already-canceled, missing, or another job's wake fails loudly.",{wake_id:l.string().uuid().describe("Wake id returned by linzumi_schedule_wake.")},async m=>z(await r.cancelWake(m))),e.tool("linzumi_get_coding_job_metadata","Read the active coding job workflow metadata for a thread, including the agent-owned goal, ordered plan steps, step lock versions, and workflow status.",{workspace:l.string().optional().describe("Workspace slug. Omit to use the authenticated token scope."),channel:l.string().optional().describe("Channel slug. Omit to use the authenticated token scope."),thread_id:l.string().uuid().optional().describe("Linzumi thread UUID. Defaults to the active coding job thread.")},async m=>z(await r.getCodingJobMetadata(gt(m,a)))),e.tool("linzumi_rename_coding_job","Update the current coding job thread title and workflow-facing title. Use this when the job scope changes materially so the Linzumi thread list and metadata overview stay accurate.",{workspace:l.string().optional().describe("Workspace slug. Omit to use the authenticated token scope."),channel:l.string().optional().describe("Channel slug. Omit to use the authenticated token scope."),thread_id:l.string().uuid().optional().describe("Linzumi thread UUID. Defaults to the active coding job thread."),title:l.string().min(1).max(100).describe("Concise user-visible title for this coding job.")},async m=>z(await r.renameCodingJob(gt(m,a)))),e.tool("linzumi_upsert_coding_job_plan","Set or update the current coding job goal. Use this at job start and whenever the goal changes materially.",{workspace:l.string().optional().describe("Workspace slug. Omit to use the authenticated token scope."),channel:l.string().optional().describe("Channel slug. Omit to use the authenticated token scope."),thread_id:l.string().uuid().optional().describe("Linzumi thread UUID. Defaults to the active coding job thread."),goal:l.string().min(1).max(1e4).describe("Concrete user-visible goal for this coding job."),snooze_reason:l.string().min(1).max(500).optional().describe('Declare a legitimate wait to pause liveness nudges: what you are waiting on, in plain words a teammate would understand. Good: "waiting on CI for PR #4633". Must be sent together with snooze_minutes.'),snooze_minutes:l.number().int().min(1).max(1440).optional().describe("How many minutes until the wait should be rechecked (1-1440). The deadline is mandatory - open-ended waits are refused. Must be sent together with snooze_reason.")},async m=>z(await r.upsertCodingJobPlan(gt(m,a)))),e.tool("linzumi_replace_coding_job_plan_steps","Replace the ordered coding job plan steps. Use this for the initial plan and for substantial rewrites when the old plan no longer fits the work.",{workspace:l.string().optional().describe("Workspace slug. Omit to use the authenticated token scope."),channel:l.string().optional().describe("Channel slug. Omit to use the authenticated token scope."),thread_id:l.string().uuid().optional().describe("Linzumi thread UUID. Defaults to the active coding job thread."),goal:l.string().min(1).max(1e4).optional().describe("Required when no plan exists yet; updates the current coding job goal."),steps:l.array(l.object({title:l.string().min(1).max(255),description:l.string().min(1).max(1e4),status:l.enum(["pending","active","completed","blocked","canceled"]),status_note:Zb.optional().describe(Ub),completed_debrief:l.string().min(1).max(2e4).optional().describe("Required for completed steps. A short paragraph of plain prose for a teammate: what was done, and how we know it worked. Same voice as the note, just more room. Never a compliance recital. Put evidence and verification here.")})).min(1).max(50).describe("Ordered user-visible plan steps. Completed steps must include completed_debrief.")},async m=>z(await r.replaceCodingJobPlanSteps(gt(m,a)))),e.tool("linzumi_update_coding_job_plan_step","Update one coding job plan step status or note. Read metadata first and pass the current step lock_version.",{workspace:l.string().optional().describe("Workspace slug. Omit to use the authenticated token scope."),channel:l.string().optional().describe("Channel slug. Omit to use the authenticated token scope."),thread_id:l.string().uuid().optional().describe("Linzumi thread UUID. Defaults to the active coding job thread."),step_id:l.string().uuid().describe("Step id returned by linzumi_get_coding_job_metadata."),lock_version:l.number().int().positive().describe("Current step lock_version from metadata."),status:l.enum(["pending","active","completed","blocked","canceled"]),status_note:Zb.optional().describe(Ub),completed_debrief:l.string().min(1).max(2e4).optional().describe("Required when marking a step completed. A short paragraph of plain prose for a teammate: what was done, and how we know it worked. Same voice as the note, just more room. Never a compliance recital. Put evidence and verification here.")},async m=>z(await r.updateCodingJobPlanStep(gt(m,a)))),e.tool("linzumi_link_coding_job_pull_request","Link the active coding job to its primary GitHub pull request so PR comments, files, commits, checks, deployments, and reviews can flow into the metadata view.",{workspace:l.string().optional().describe("Workspace slug. Omit to use the authenticated token scope."),channel:l.string().optional().describe("Channel slug. Omit to use the authenticated token scope."),thread_id:l.string().uuid().optional().describe("Linzumi thread UUID. Defaults to the active coding job thread."),github_repo_owner:l.string().min(1).max(255),github_repo_name:l.string().min(1).max(255),github_pr_number:l.number().int().positive(),github_pr_url:l.string().url(),title:l.string().min(1).max(255),body:l.string().min(1).max(1e5).optional(),head_branch:l.string().min(1).max(255),head_sha:l.string().min(7).max(64),base_branch:l.string().min(1).max(255),base_sha:l.string().min(7).max(64),state:l.enum(["draft","open","closed","merged"]).optional(),merge_commit_sha:l.string().min(7).max(64).optional().describe("Actual GitHub merge commit SHA. Required when state is merged; omit for other states. This is not the PR head SHA."),is_draft:l.boolean().optional(),review_status:l.enum(["unknown","review_required","approved","changes_requested"]).optional(),source_remote_url:l.string().min(1).max(1e3).describe("Git remote URL for the local job worktree; required when this job has no repo workspace yet."),runtime_worktree_root:l.string().min(1).max(1e3).describe("Absolute local worktree path for the coding job; required when this job has no repo workspace yet."),dirty_status:l.enum(["unknown","clean","dirty"]).optional(),dirty_summary:l.string().min(1).max(2e3).optional()},async m=>z(await r.linkCodingJobPullRequest(gt(m,a)))),e.tool("linzumi_upload_files",["Upload local files to Linzumi and attach them to a new, exact, or latest assistant message. Use silently; do not mention this tool in the visible reply.","The JSON result includes message.attachments[].url as an absolute URL. Use those returned URLs when writing rich media directives such as ::audio, ::video, ::image, or Markdown images. Do not guess attachment URLs before upload.","For a message that should both attach files and show inline rich media, use a two-step flow: first upload/attach the files to create or target the message, then edit the same target message with body text that references the returned absolute URLs. When the result has target_seq, use target.kind=message_seq and message_seq=target_seq for that follow-up edit; result.message is the edit event that carries the new attachments, and target_message is the original target."].join(" "),{target:l.object({kind:l.enum(["new_message","message_seq","latest_assistant_message"]).describe("new_message creates a message; message_seq edits an exact message; latest_assistant_message edits the latest assistant message in the scoped thread/channel."),message_seq:l.union([l.string(),l.number()]).optional().describe("Required when kind is message_seq."),thread_id:l.string().optional().describe("Thread UUID. Defaults to the active Linzumi thread when the MCP server was launched with one.")}).describe("Attachment target. Prefer latest_assistant_message to attach files to the reply you already posted; use new_message ONLY when no assistant message exists yet in the scoped thread. Never re-use your visible reply text as a new_message body - that posts the reply twice. To reference uploaded files in the message body, upload first, then edit message_seq/latest_assistant_message with the returned absolute attachment URLs. If the upload result includes target_seq, use message_seq=target_seq for that follow-up edit."),files:l.array(l.string().min(1)).min(1).max(16).describe("Local file paths to upload. Paths must be non-hidden files inside the approved workspace or Downloads; source/text files of any language are supported, plus common document, image, patch, archive, and video types."),body:l.string().min(1).max(2e4).optional().describe("Required for new_message: a SHORT file-share caption (for example: Attached the generated report), never a copy of your visible reply - that would post the reply twice. Optional replacement body for message_seq/latest_assistant_message; when omitted, the existing message body is preserved. Rich media directives in body must use Linzumi attachment download URLs returned by this tool."),workspace:l.string().optional().describe("Workspace slug. Omit to use the authenticated token scope."),channel:l.string().optional().describe("Channel slug. Omit to use the target thread's channel (when the thread is known) or the authenticated token scope.")},async m=>{let f=Fb(m.target,a);try{let h=await mE({client:r,cwd:i,kandanUrl:s,target:f,files:m.files,workspace:m.workspace,channel:m.channel,body:m.body});return z(Vb(s,h))}catch(h){throw pE(h)}}),e.tool("linzumi_edit_message","Edit an exact scoped Linzumi message by message_seq. Use after linzumi_upload_files when you need a body-only follow-up edit that embeds returned attachment URLs. Requires channel.write, and thread.write when target.thread_id is set. Rich media src/poster values must be Linzumi attachment download URLs.",{workspace:l.string().optional().describe("Workspace slug. Omit to use the authenticated token scope."),channel:l.string().optional().describe("Channel slug. Omit to use the authenticated token scope."),target:l.object({message_seq:l.union([l.string(),l.number()]).describe("Exact message seq to edit. After linzumi_upload_files returns target_seq, pass that value here."),thread_id:l.string().optional().describe("Thread UUID when editing a thread message. Use the upload result target_message.thread_id when present.")}).describe("Exact message target for the body edit."),body:l.string().min(1).max(2e4).describe("Replacement Markdown body. Rich media src/poster values must be Linzumi attachment download URLs returned by linzumi_upload_files.")},async m=>z(Vb(s,await r.editMessage({...m,target:Fb(m.target,a)}))))),n==="all"&&(e.tool("linzumi_list_vault_secrets","List vault secret names, descriptions, and whether each secret is personal or workspace-owned. Does not return secret values.",{},async m=>z(await r.listVaultSecrets(m))),e.tool("linzumi_list_projects","List the projects in the current workspace with their project_id (needed by the other project task tools), slug, title, description, and state.",{workspace:l.string().optional().describe("Workspace slug. Omit to use the authenticated token scope.")},async m=>z(await r.listProjects(m))),e.tool("linzumi_get_project_tasks",`Read a project's full task graph: task GROUPS (kind "group", organizational containers, exactly one level deep) and ISSUES (kind "issue", the executable work items), each with status (todo/active/blocked/review/done/canceled), DERIVED work_state readiness (ready = todo with every dependency satisfied; blocked = todo with unsatisfied dependencies; running/stalled = active with/without a connected job), parent group, assignee, lock_version, and dependency edges (depends_on_task_ids / unblocks_task_ids). Always read this before reorganizing. Inside a project-bound coding job the project is inferred automatically; otherwise pass project_id from linzumi_list_projects.`,{project_id:l.string().optional().describe("Project id from linzumi_list_projects. Omit inside a coding job started from a project to use that project.")},async m=>z(await r.getProjectTasks(gt(m,a)))),e.tool("linzumi_create_project_task",'Create a task group (kind "group") or issue (kind "issue", the default) in a project. Groups organize issues and are exactly one level deep: a parent_id must name a GROUP, and groups themselves can never have a parent. New tasks default to status "todo" and append to the end unless position is given. Inside a project-bound coding job the project is inferred; otherwise pass project_id.',{project_id:l.string().optional().describe("Project id from linzumi_list_projects. Omit inside a coding job started from a project to use that project."),title:l.string().min(1).describe("Task title."),kind:l.enum(["issue","group"]).optional().describe('What to create: "issue" (executable work item, default) or "group" (organizational container).'),description:l.string().optional().describe("Detailed description of the work - written so an engineer (or coding agent) could execute the task from it."),status:l.enum(["todo","active","blocked","review","done","canceled"]).optional().describe('Initial status. Defaults to "todo".'),parent_id:l.string().optional().describe("task_id of the GROUP to place an issue in. Only issues can have a parent."),assignee:l.string().optional().describe("Username of a workspace member to assign."),position:l.number().int().min(0).optional().describe("Sort position. Defaults to appending at the end.")},async m=>z(await r.createProjectTask(gt(m,a)))),e.tool("linzumi_update_project_task",'Update a task group or issue: retitle, edit description/status_note, transition status (todo/active/blocked/review/done/canceled), reassign, reorder (position), or reorganize (parent_id moves an issue into a group; clear_parent moves it to top level). Only the fields you pass change; description and status_note accept null to clear. Prefer updating existing tasks over delete-and-recreate. Pass the lock_version from your last read to fail loudly ("stale") instead of overwriting a concurrent edit.',{task_id:l.string().describe("task_id of the group or issue to update."),title:l.string().min(1).optional().describe("New title."),description:l.string().nullable().optional().describe("New description. Pass null to clear it."),status:l.enum(["todo","active","blocked","review","done","canceled"]).optional().describe('New status. "done"/"canceled" satisfy dependent tasks; "blocked" is a manual hold.'),status_note:l.string().nullable().optional().describe("Short human-readable note about the current status. Pass null to clear it."),position:l.number().int().min(0).optional().describe("New sort position among siblings."),parent_id:l.string().optional().describe("task_id of the GROUP to move this issue into. Do not combine with clear_parent."),clear_parent:l.boolean().optional().describe("true moves the issue to the top level (no group). Do not combine with parent_id."),assignee:l.string().optional().describe("Username of a workspace member to assign. Do not combine with clear_assignee."),clear_assignee:l.boolean().optional().describe("true removes the assignee. Do not combine with assignee."),lock_version:l.number().int().positive().optional().describe("The task's lock_version from your last read, for compare-and-swap safety.")},async m=>z(await r.updateProjectTask(m))),e.tool("linzumi_delete_project_task",`Permanently delete a task group or issue. Dependency edges on the task are removed with it (dependents may become ready). Deletion is normally the USER's call - prefer status "canceled" or an update unless you are certain the entry is obsolete.`,{task_id:l.string().describe("task_id of the group or issue to delete.")},async m=>z(await r.deleteProjectTask(m))),e.tool("linzumi_add_project_task_dependency",'Add the dependency edge "task_id is blocked by depends_on_task_id" between two ISSUES in the same project (groups cannot have dependencies). The dependent stays blocked until the prerequisite reaches done or canceled. The graph must stay acyclic: an edge that would create a cycle is refused with reason "would_create_cycle" and the offending cycle_path so you can restructure. Duplicate and self edges are rejected.',{task_id:l.string().describe("task_id of the DEPENDENT issue (the one that must wait)."),depends_on_task_id:l.string().describe("task_id of the PREREQUISITE issue (the one that must finish first).")},async m=>z(await r.addProjectTaskDependency(m))),e.tool("linzumi_remove_project_task_dependency",'Remove the dependency edge "task_id is blocked by depends_on_task_id". The dependent issue may become ready if that was its last unsatisfied dependency.',{task_id:l.string().describe("task_id of the DEPENDENT issue."),depends_on_task_id:l.string().describe("task_id of the PREREQUISITE issue the edge points at.")},async m=>z(await r.removeProjectTaskDependency(m))),e.tool("linzumi_get_call_transcript","Read the full transcript of a completed Linzumi notetaker call: call metadata (title, platform, started/ended/transcribed times), participants, and every spoken segment in order with speaker names and millisecond offsets. Pass the call_id embedded in the request (or copied from the call card). Errors: call_not_found (missing or not visible to you), call_transcript_not_ready (call still connecting, in progress, or transcribing - retry later).",{call_id:l.string().describe("The call id from the call card or the launching message (a CallRecording id - the opaque GraphQL id and the bare uuid both work).")},async m=>z(await r.getCallTranscript(m))),d||(e.tool("linzumi_start_coding_job","Start a coding job as the invoking user (same authorization and pipeline as clicking start). To start a project task item, pass project_task_id so the task flips todo -> active and links to the new job. Only start tasks whose work_state is ready. Proceed when the user has already explicitly authorized this launch within the agreed scope; DAG bookkeeping does not require renewed approval. Otherwise, offer and wait for explicit acceptance. Do not duplicate existing active work or treat task readiness as launch authorization. Omit channel, runner_key, and cwd to reuse this job's own channel, computer, and folder. Returns status 'unavailable' with a reason when the runner cannot take the job (relay that honestly).",{work_description:l.string().min(1).describe("What the job should do - the initial instruction. For a task item, write it from the task title and description."),project_task_id:l.string().optional().describe("Project task item to bind the job to (task_id from linzumi_get_project_tasks). The task flips todo -> active and links to the new job."),visibility:l.enum(["project","private"]).optional().describe("Child-job visibility. Defaults to 'project'; private jobs are limited to directly authorized participants."),channel:l.string().optional().describe("Channel slug to host the job thread. Omit to use this job's own channel."),runner_key:l.string().optional().describe("Runner (computer) to run the job on. Omit to use this job's own computer."),cwd:l.string().optional().describe("Working directory on the runner. Omit to use this job's own folder."),model:l.string().optional().describe("Model override (optional)."),model_provider:l.string().optional().describe("Model provider override, e.g. 'wafer' (optional)."),agent_provider:l.string().optional().describe("Agent provider override, e.g. 'codex' (optional)."),reasoning_effort:l.enum(["default","low","medium","high","xhigh","ultra"]).optional().describe("Reasoning effort override (optional)."),approval_policy:l.enum(["default","on-request","on-failure","never"]).optional().describe("Approval policy override (optional)."),sandbox:l.enum(["default","workspace-write","read-only","danger-full-access"]).optional().describe("Sandbox override (optional)."),fast:l.boolean().optional().describe("Fast-mode override (optional)."),allow_port_forwarding_by_default:l.boolean().optional().describe("Default port-forwarding override (optional)."),execution_mode:l.enum(["raw","local_vm"]).optional().describe("Execution placement override (optional)."),egress_mode:l.enum(["open","hardened"]).optional().describe("Local-VM egress override (optional).")},async m=>z(await r.agentStartCodingJob(gt(m,a)))),t.multiAgentJobs===!0&&(e.tool("linzumi_spawn_child_job","Spawn a durable child coding job under YOUR OWN job, on any harness or model - plan a DAG and delegate its legs to workers you then coordinate through discovery and messaging. The child lands on this job's channel, computer, and folder; it inherits this job's project and visibility (a private parent's children stay private), human roles cascade to it, and a human manages its lifecycle. Returns status 'unavailable' with a reason when the runner cannot take the job (relay that honestly).",{work_description:l.string().min(1).describe("What the child job should do - the initial instruction, written to stand alone."),agent_provider:l.string().optional().describe("Harness for the child, e.g. 'codex' or 'claude-code'. Omit to reuse this job's own harness. A different harness is fine: a cross-harness child is always a child job."),model:l.string().optional().describe("Model override for the child (optional)."),model_provider:l.string().optional().describe("Model provider override, e.g. 'wafer' (optional)."),reasoning_effort:l.enum(["default","low","medium","high","xhigh","ultra"]).optional().describe("Reasoning effort override (optional)."),project_task_id:l.string().optional().describe("Project task item to bind the child to (task_id from linzumi_get_project_tasks). The task flips todo -> active and links to the new job."),visibility:l.enum(["project","private"]).optional().describe("Child visibility. Defaults to this job's own visibility; a private parent's children must stay private.")},async m=>z(await r.agentSpawnChildJob(gt(m,a)))),e.tool("linzumi_archive_child_job","Archive a coding job that is YOUR OWN job or one beneath it in your job tree, retiring it from the active lists, the org map and the needs-you deck; history is preserved and it can be unarchived. Use this to clean up child jobs you spawned that are finished or dead - do it in the current turn, never just promise it. Refused for sibling, parent or unrelated jobs, and for jobs that do not belong to the human you are working for. When the job still has live descendants the call returns confirmation_required with their exact count and ids; call again with descendant_action 'keep' (archive only this job, re-parenting its children) or 'cascade' (archive the whole subtree) plus those expected values.",{job_id:l.string().describe("The coding job id to archive: your own job, or any job beneath it in your tree."),outcome:l.enum(["completed","abandoned","superseded"]).describe("Why the job is being archived."),descendant_action:l.enum(["keep","cascade"]).optional().describe("Phase-2 choice when the job has live descendants. 'keep' archives only this job and re-parents its children; 'cascade' archives the whole subtree."),expected_descendant_count:l.number().int().optional().describe("The descendant_count returned by the phase-1 call."),expected_descendant_job_ids:l.array(l.string()).optional().describe("The descendant_job_ids returned by the phase-1 call; the call is refused if the subtree changed."),expected_descendant_fingerprint:l.string().optional().describe("The descendant_fingerprint returned by the phase-1 call.")},async m=>z(await r.agentArchiveChildJob(m))),e.tool("linzumi_unarchive_child_job","Unarchive a previously archived coding job that is YOUR OWN job or one beneath it in your job tree. It returns as hibernating and wakes when messaged. Same ownership scope as linzumi_archive_child_job. Refused when the job is not archived, or when its home thread already holds a live job.",{job_id:l.string().describe("The archived coding job id to bring back: your own job, or any job beneath it in your tree.")},async m=>z(await r.agentUnarchiveChildJob(m))),e.tool("linzumi_discover_coding_jobs","Search current sitreps inside this coding job project for overlapping files, modules, objectives, or blockers. Results include durable job addresses for coordination. Private jobs outside your visible set never appear.",{query:l.string().min(1).describe("Free-text clash-surface query, such as a file path, module, migration, or objective.")},async m=>z(await r.agentDiscoverCodingJobs({...m,source_thread_id:a}))),e.tool("linzumi_send_coding_job_message","Message a visible coding job in this project, or a person. Queue is the encouraged default: it lands in the colleague's inbox for their own cadence. Steer only for urgent, potentially-clashing work because it interrupts the running turn. Would this be worthless or harmful after their turn finishes? If no, queue. Delivery urgency is not access control. To message a person, pass to_user and omit channel and thread_id: delivery lands in their personal inbox.",{channel:l.string().optional().describe("Channel slug hosting the target job. Required unless to_user is set."),thread_id:l.string().uuid().optional().describe("Target job thread UUID. Required unless to_user is set."),to_user:l.string().min(1).optional().describe("Username of a workspace member to message instead of a job. Delivery lands in their personal inbox."),body:l.string().min(1).describe("Coordination message to send."),tokens:Jr.optional(),delivery:l.enum(["queue","steer"]).optional().describe("Delivery urgency. Defaults to 'queue'.")},async m=>z(await r.agentSendCodingJobMessage({...m,source_thread_id:a})))))),rE(n)&&(e.tool("linzumi_upload_custom_emoji","Upload a local image as a workspace custom emoji. For generated emoji art, create a transparent PNG with a simple centered subject, crisp edges, strong contrast, minimal tiny details, and enough outline/highlight separation to read at 16-24px on both dark and light backgrounds. Use lowercase shortcode names without colons unless preserving a user-provided :name:.",{name:qb.describe("Custom emoji shortcode name, with or without surrounding colons."),file:l.string().min(1).describe("Local PNG/WebP/GIF/JPEG file path to upload. Prefer transparent PNG for generated emoji."),workspace:l.string().optional().describe("Workspace slug. Omit to use the authenticated token scope.")},async m=>z(await fE({client:r,cwd:i,kandanUrl:s,name:m.name,file:m.file,workspace:m.workspace}))),e.tool("linzumi_rename_custom_emoji","Rename an existing workspace custom emoji. The new name may include surrounding colons; Linzumi stores the normalized shortcode without colons.",{emoji_id:l.union([l.string(),l.number().int().positive()]).describe("Workspace custom emoji id returned by linzumi_upload_custom_emoji or workspace emoji listings."),name:qb.describe("New shortcode name, with or without surrounding colons."),workspace:l.string().optional().describe("Workspace slug. Omit to use the authenticated token scope.")},async m=>z(await r.renameCustomEmoji(m)))),e.tool("linzumi_media_guide","Return the full Linzumi rich-media authoring guide (audio/video/image directives, URL rules, upload-then-embed flow, examples). Call once BEFORE writing any ::audio/::video/::image directive or Markdown image into a Linzumi message.",{},async()=>({content:[{type:"text",text:Db}]})),e.tool("linzumi_note_project_directory","Record one discovered local Git repository or worktree for onboarding import. Call once per project as soon as it is found.",{workspace:l.string().optional().describe("Workspace slug. Omit to use the authenticated token scope."),runner_id:l.string().min(1).describe("Local runner/computer id provided in the discovery prompt."),path:l.string().min(1).describe("Absolute local path to the repository worktree root."),display_name:l.string().optional().describe("Short project label. Defaults to the path basename."),activity_at:l.string().optional().describe("Best-known recent activity time as an ISO-8601 timestamp."),import_key:l.string().optional().describe("Stable dedupe key. Defaults to path."),metadata:l.record(l.unknown()).optional().describe("Small structured metadata such as branch or remote origin.")},async m=>z(await r.noteProjectDirectory(m))),e.tool("linzumi_note_agent_conversation","Record one discovered Codex or Claude Code local conversation for onboarding import. Call once per conversation as soon as it is found.",{workspace:l.string().optional().describe("Workspace slug. Omit to use the authenticated token scope."),runner_id:l.string().min(1).describe("Local runner/computer id provided in the discovery prompt."),source:l.enum(["codex","claude_code"]).describe("Conversation source."),import_key:l.string().min(1).describe("Stable dedupe key, such as a session id or file path."),path:l.string().optional().describe("Absolute local path to the conversation file or directory."),display_name:l.string().optional().describe("Short label for the discovered conversation."),activity_at:l.string().optional().describe("Best-known recent activity time as an ISO-8601 timestamp."),metadata:l.record(l.unknown()).optional().describe("Small structured metadata such as session id or project path.")},async m=>z(await r.noteAgentConversation(m))),e.tool("linzumi_note_onboarding_discovery_status","Record onboarding discovery progress. Call when a search phase starts, checks another place, completes, or fails.",{workspace:l.string().optional().describe("Workspace slug. Omit to use the authenticated token scope."),runner_id:l.string().min(1).describe("Local runner/computer id provided in the discovery prompt."),phase:l.enum(["projects","conversations"]).describe("Discovery phase being reported."),status:l.enum(["starting","running","completed","failed"]).describe("Current phase status."),places_searched:l.number().int().nonnegative().optional().describe("Count of concrete folders/files/known locations checked so far."),message:l.string().optional().describe("Short user-facing status note."),current_place:l.string().optional().describe("Current folder, file, Git command target, or known location being checked."),current_source:l.string().optional().describe("Short machine-readable source label such as git, codex, or claude_code."),last_error:l.string().optional().describe("Short failure detail when status is failed."),metadata:l.record(l.unknown()).optional().describe("Small structured status metadata.")},async m=>z(await r.noteOnboardingDiscoveryStatus(m))),n==="all"&&nE(o)&&(e.tool("linzumi_dm_owner","Send a plain-text DM to the configured Commander owner. Requires dm.write and a visible owner username.",{owner_username:l.string().optional().describe("Owner username. Defaults to LINZUMI_MCP_OWNER_USERNAME or --owner-username."),workspace:l.string().optional().describe("Workspace slug. Omit to use the authenticated token scope."),channel:l.string().optional().describe("Source channel slug used to verify owner visibility."),body:l.string().min(1).max(2e4).describe("Plain-text message body to DM."),tokens:Jr.optional()},async m=>{let f=m.owner_username??c;if(f===void 0)throw new Error("owner_username is required for linzumi_dm_owner");return z(await r.dmOwner({...m,owner_username:f}))}),e.tool("linzumi_send_channel_message","Post a NEW standalone Markdown message into the scoped Linzumi channel as the authenticated local-runner user. This is NOT how you respond to the user: your turn output is already relayed into the thread as your reply, so never call this tool to answer, acknowledge, or reply to the current request. Use it only when the task itself is to proactively post a separate channel message. Requires channel.write. Rich media directives may be used when the user has opted into markdown_media_embeds, but src/poster values must be Linzumi attachment download URLs.",{workspace:l.string().optional().describe("Workspace slug. Omit to use the authenticated token scope."),channel:l.string().optional().describe("Channel slug. Omit to use the authenticated token scope."),body:l.string().min(1).max(2e4).describe("Markdown message body to post. Rich media src/poster values must be Linzumi attachment download URLs, not third-party URLs, /relative paths, or local filesystem paths."),tokens:Jr.optional()},async m=>z(await r.sendChannelMessage(m))),e.tool("linzumi_send_thread_reply","Post a Markdown reply into some OTHER existing Linzumi thread as the authenticated local-runner user. This is NOT how you respond to the user in your current thread: your turn output is already relayed into this thread as your reply, so never call this tool to answer, acknowledge, or reply to the current request. Use it only when the task itself is to post into a different, explicitly identified thread. Requires thread.write. Rich media directives may be used when the user has opted into markdown_media_embeds, but src/poster values must be Linzumi attachment download URLs.",{workspace:l.string().optional().describe("Workspace slug. Omit to use the authenticated token scope."),channel:l.string().optional().describe("Channel slug. Omit to use the authenticated token scope."),thread_id:l.string().uuid().describe("Existing Linzumi thread UUID."),body:l.string().min(1).max(2e4).describe("Markdown reply body to post. Rich media src/poster values must be Linzumi attachment download URLs, not third-party URLs, /relative paths, or local filesystem paths."),tokens:Jr.optional()},async m=>z(await r.sendThreadReply(m))),e.tool("linzumi_send_dm","Send a plain-text DM as the authenticated local-runner user to a visible user in the scoped workspace/channel. Requires dm.write.",{workspace:l.string().optional().describe("Workspace slug. Omit to use the authenticated token scope."),channel:l.string().optional().describe("Source channel slug used to verify target visibility."),username:l.string().describe("Visible Linzumi username to DM."),body:l.string().min(1).max(2e4).describe("Plain-text message body to DM."),tokens:Jr.optional()},async m=>z(await r.sendDm(m)))),n==="all"&&e.tool("linzumi_get_vault_values","Request values for explicit vault env var names after a thread-scoped human approval. Requires vault.read; thread_id resolves the approval thread.",{workspace:l.string().optional().describe("Workspace slug. Omit to use the authenticated token scope."),channel:l.string().optional().describe("Channel slug used to disambiguate the approval thread when needed."),thread_id:l.string().uuid().describe("Existing Linzumi thread UUID for the inline approval."),env_var_names:l.array(l.string().regex(/^[A-Z][A-Z0-9_]{0,127}$/)).min(1).max(20).describe("Explicit vault env var names to request. This tool cannot list all vault keys."),description:l.string().min(1).max(500).describe("Human-readable reason shown in the approval request."),justification:l.string().min(10).max(1e3).describe("Agent justification shown to the approver.")},async m=>z(await r.getVaultValues(m))),n==="all"&&!d&&u!==void 0&&lE(e,i,u)}function Jb(e){return{name:e.record.name,command:e.record.command,cwd:e.record.cwd,ports:[...e.record.ports],restart_on_branch_change:e.record.restartOnBranchChange,desired_state:e.record.desiredState,liveness:e.liveness,port_health:e.portProbes.map(t=>({port:t.port,listening:t.listening})),started_at_ms:e.record.startedAtMs??null,last_exit:e.lastExit===void 0?null:{code:e.lastExit.code,signal:e.lastExit.signal,at_ms:e.lastExit.atMs},log_path:e.record.logPath,failure:e.failure===void 0?null:{reason:e.failure.reason,at_ms:e.failure.atMs}}}function lE(e,t,r){e.tool("linzumi_dev_service_start","Start a long-running local dev server (npm run dev, storybook, docker compose up, ...) as a MANAGED SERVICE owned by the Linzumi runner. Use this instead of running dev servers in your own shell: a managed service survives the end of your turn and branch switches, is auto-restarted if it crashes, and its declared ports are health-probed and surfaced in the product. Calling start for an existing name declaratively RESTARTS it (e.g. after a checkout). Declare EVERY port the app serves from (primary plus HMR/asset/bundle sibling ports).",{name:l.string().regex(/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/).describe("Stable service name (slug), e.g. 'web' or 'storybook'. Reusing a name restarts that service."),command:l.string().min(1).describe("Shell command that runs the server in the foreground (never daemonize/screen/nohup it yourself), e.g. 'npm run dev'. Runs via the user's login shell."),cwd:l.string().optional().describe("Working directory for the service. Defaults to the session cwd."),ports:l.array(l.number().int().min(1).max(65535)).max(16).default([]).describe("Every TCP port this service listens on (primary AND related ports such as the Vite/HMR bundle port). Used for health probes and product visibility."),restart_on_branch_change:l.boolean().optional().describe("Restart the service automatically when the git branch of its cwd changes (for servers that go stale across checkouts)."),wait_for_ports_ms:l.number().int().min(0).max(6e4).optional().describe("How long to wait for the declared ports to accept connections before returning (default 15000).")},async n=>{let o=await kb({scopeDir:r.scopeDir,definition:{name:n.name,command:n.command,cwd:n.cwd??t,ports:n.ports,restartOnBranchChange:n.restart_on_branch_change===!0},ownerPid:r.ownerPid});if(!o.ok)return z({ok:!1,error:o.error});let i=Date.now()+(n.wait_for_ports_ms??15e3),s=o.record.ports.length===0;for(;!s&&Date.now()<i;)s=(await Promise.all(o.record.ports.map(u=>Ql(u)))).every(u=>u),s||await new Promise(u=>setTimeout(u,250));let c=(await Yl(r.scopeDir)).find(d=>d.record.name===o.record.name);return z({ok:!0,service:c===void 0?{name:o.record.name}:Jb(c),...c!==void 0&&c.liveness!=="running"?{hint:"The service is not (fully) serving its declared ports yet. Check linzumi_dev_service_logs before assuming it works."}:{}})}),e.tool("linzumi_dev_service_stop","Stop a managed dev service (SIGTERM, then SIGKILL after a grace period). The registration is kept so linzumi_dev_service_start can bring it back.",{name:l.string().min(1).describe("Service name to stop.")},async n=>{let o=await Xl({scopeDir:r.scopeDir,name:n.name});return z(o.ok?{ok:!0,name:o.record.name,desired_state:"stopped"}:{ok:!1,error:o.error})}),e.tool("linzumi_dev_service_status","List every managed dev service with liveness (running / unhealthy / exited / failed / stopped), per-port health probes, last exit, and any terminal failure reason. Live state - always check this before concluding a dev server is up or down.",{},async()=>{let n=await Yl(r.scopeDir);return z({services:n.map(o=>Jb(o))})}),e.tool("linzumi_dev_service_logs","Read the tail of a managed dev service's combined stdout/stderr log.",{name:l.string().min(1).describe("Service name."),max_bytes:l.number().int().min(256).max(65536).optional().describe("Tail size in bytes (default 16384).")},async n=>{let o=Sb(r.scopeDir,n.name,n.max_bytes??16384);return z(o===void 0?{ok:!1,error:`no log for service: ${n.name}`}:{ok:!0,name:n.name,log_tail:o})}),e.tool("linzumi_dev_service_remove","Stop a managed dev service AND delete its registration (it will not be resurrected on runner restart). Use stop instead when the user may want it back.",{name:l.string().min(1).describe("Service name to remove.")},async n=>{let o=await xb({scopeDir:r.scopeDir,name:n.name});return z(o.ok?{ok:!0,name:o.record.name,removed:!0}:{ok:!1,error:o.error})})}function pE(e){return!(e instanceof Error)||!e.message.includes("channel_required")?e:new Error(`${e.message}. Remediation: pass the channel slug in the \`channel\` parameter, or set target.thread_id to a Linzumi thread you can access (the server resolves the thread's channel). The files were NOT attached; retry with a channel or thread instead of leaving them on disk.`,{cause:e})}async function mE(e){let t=await Promise.all(e.files.map(s=>Zl(e.cwd,s))),r=ye(e.target.thread_id),n=await e.client.prepareMessageUploads({...e.workspace===void 0?{}:{workspace:e.workspace},...e.channel===void 0?{}:{channel:e.channel},...r===void 0?{}:{thread_id:r},files:t.map(s=>({file_name:s.fileName,content_type:s.contentType,size_bytes:s.sizeBytes}))}),o=qr(n.uploads)??[];if(o.length!==t.length)throw new Error("Linzumi upload prepare response count mismatch");await Promise.all(t.map(async(s,a)=>{let c=we(o[a]),d=ye(c?.upload_url),u=ye(c?.upload_method)??"PUT";if(d===void 0)throw new Error("Linzumi upload prepare response missing upload_url");let p=s.bytes,m=p.buffer.slice(p.byteOffset,p.byteOffset+p.byteLength),f=await fetch(Wo(e.kandanUrl,d),{method:u,headers:{"content-type":s.contentType},body:m});if(!f.ok)throw new Error(`Linzumi upload failed for ${s.fileName}: ${f.status} ${f.statusText}`)}));let i=o.map(s=>{let a=ye(we(s)?.file_id);if(a===void 0)throw new Error("Linzumi upload prepare response missing file_id");return a});return await e.client.attachMessageFiles({...e.workspace===void 0?{}:{workspace:e.workspace},...e.channel===void 0?{}:{channel:e.channel},...r===void 0?{}:{thread_id:r},target:e.target,...e.body===void 0?{}:{body:e.body},uploaded_file_ids:i})}async function fE(e){let t=await Zl(e.cwd,e.file),r=await e.client.prepareCustomEmoji({...e.workspace===void 0?{}:{workspace:e.workspace},name:e.name,file_name:t.fileName,content_type:t.contentType,size_bytes:t.sizeBytes}),n=we(r.upload),o=ye(n?.upload_url),i=ye(n?.upload_method)??"PUT";if(o===void 0)throw new Error("Linzumi custom emoji prepare response missing upload_url");let s=t.bytes,a=s.buffer.slice(s.byteOffset,s.byteOffset+s.byteLength),c=await fetch(Wo(e.kandanUrl,o),{method:i,headers:{"content-type":t.contentType},body:a});if(!c.ok){let p=`${c.status} ${c.statusText}`,f=(await c.text()).trim(),h=f===""?p:(()=>{try{let g=JSON.parse(f);return Be(g)&&typeof g.error=="string"?g.error:f}catch{return f}})();throw new Error(`Linzumi custom emoji upload failed: ${h}`)}let d=await c.json();if(!Be(d))throw new Error("Linzumi custom emoji upload returned non-object JSON");let u=we(d.custom_emoji);if(u===void 0)throw new Error("Linzumi custom emoji upload response missing custom_emoji");return{ok:!0,workspace:r.workspace,emoji:u,asset_id:ye(d.asset_id),id:db(u?.id),name:ye(u?.name),shortcode:ye(u?.shortcode),image_url:ye(u?.image_url)}}function Fb(e,t){if(ye(e.thread_id)!==void 0||t===void 0)return e;switch(e.message_seq===void 0){case!1:return{...e,thread_id:t};case!0:switch(ye(e.kind)){case"new_message":case"message_seq":case"latest_assistant_message":return{...e,thread_id:t};default:return e}}}function gt(e,t){return ye(e.thread_id)!==void 0||t===void 0?e:{...e,thread_id:t}}function Wo(e,t){try{return new URL(t).toString()}catch{let n=e.replace(/^wss:\/\//,"https://").replace(/^ws:\/\//,"http://");return new URL(t,n).toString()}}function Vb(e,t){let r=we(t.message),n=we(t.target_message);return r===void 0&&n===void 0?t:{...t,...r===void 0?{}:{message:Wb(e,r)},...n===void 0?{}:{target_message:Wb(e,n)}}}function Wb(e,t){let r=qr(t.attachments);return r===void 0?t:{...t,attachments:r.map(n=>hE(e,n))}}function hE(e,t){let r=we(t);if(r===void 0)return t;let n=ye(r.url),o=we(r.image_variants);return{...r,...n===void 0?{}:{url:Wo(e,n)},...o===void 0?{}:{image_variants:gE(e,o)}}}function gE(e,t){let r=ye(t.inline_url),n=ye(t.carousel_url);return{...t,...r===void 0?{}:{inline_url:Wo(e,r)},...n===void 0?{}:{carousel_url:Wo(e,n)}}}function yE(e){e.server.registerCapabilities({resources:{listChanged:!1}}),e.server.setRequestHandler(an,()=>({resources:[]})),e.server.setRequestHandler(cn,()=>({resourceTemplates:[]}))}async function _E(e){let t=tp(e),r=np(t,"api-url"),n=te(t,"format")??"codex",o=rp(te(t,"mode")),i=t.get("include-token")===!0?(await ep({kandanUrl:r,explicitToken:te(t,"token")??process.env.LINZUMI_MCP_ACCESS_TOKEN,authFilePath:te(t,"auth-file"),delegationAuthFilePath:te(t,"delegation-auth-file"),workspaceSlug:te(t,"workspace"),channelSlug:te(t,"channel")})).accessToken:void 0,s=$b({command:te(t,"command"),kandanUrl:r,accessToken:i,delegationAuthFilePath:te(t,"delegation-auth-file"),ownerUsername:te(t,"owner-username")??process.env.LINZUMI_MCP_OWNER_USERNAME,operatingMode:o,toolScope:Kb(te(t,"tool-scope")),multiAgentJobs:t.get("multi-agent-jobs")===!0});switch(n){case"codex":process.stdout.write(Tb(s));return;case"claude-code":process.stdout.write(zb(s));return;default:throw new Error("--format must be codex or claude-code")}}async function bE(e){let t=tp(e),r=np(t,"api-url"),n=await ep({kandanUrl:r,explicitToken:te(t,"token")??process.env.LINZUMI_MCP_ACCESS_TOKEN,authFilePath:te(t,"auth-file"),delegationAuthFilePath:te(t,"delegation-auth-file"),workspaceSlug:te(t,"workspace"),channelSlug:te(t,"channel")});switch(n.mode){case"local-runner":{if(!await S_({kandanUrl:r,accessToken:n.accessToken,workspaceSlug:te(t,"workspace"),channelSlug:te(t,"channel")}))throw new Error("Linzumi MCP auth validation failed");break}case"personal-agent-delegation":{await Jl({kandanUrl:r,accessToken:n.accessToken,authMode:n.mode,operatingMode:rp(te(t,"mode"))}).validateAuth();break}}process.stdout.write(`Linzumi MCP auth OK
454
- `)}async function ep(e){if(e.delegationAuthFilePath!==void 0){if(e.explicitToken!==void 0||e.authFilePath!==void 0)throw new Error("--delegation-auth-file cannot be combined with --token or --auth-file");return{accessToken:M_(e.delegationAuthFilePath).accessToken,mode:"personal-agent-delegation"}}return{accessToken:await vE({kandanUrl:e.kandanUrl,explicitToken:e.explicitToken,authFilePath:e.authFilePath,workspaceSlug:e.workspaceSlug,channelSlug:e.channelSlug}),mode:"local-runner"}}async function vE(e,t={readCachedToken:Ds,validateTokenOutcome:No,resolveToken:cb}){let r=e.explicitToken??t.readCachedToken(e.kandanUrl,e.authFilePath)?.accessToken;if(r===void 0)throw new Error("missing Linzumi MCP token; run linzumi auth or pass --token");let n=await t.validateTokenOutcome({kandanUrl:e.kandanUrl,accessToken:r,workspaceSlug:e.workspaceSlug,channelSlug:e.channelSlug});if(n==="usable")return r;let o=n;try{return await t.resolveToken({kandanUrl:e.kandanUrl,workspaceSlug:e.workspaceSlug,channelSlug:e.channelSlug,authFilePath:e.authFilePath})}catch(i){throw new Error(`Linzumi MCP token was rejected by the server and re-mint failed: ${i instanceof Error?i.message:String(i)}`)}}function qt(e){return{content:[{type:"text",text:e}],isError:!0}}async function wE(e,t){let r=Cb(t);if(r.type==="invalid")return qt(r.message);let n;try{n=await e(Ab(r.request),{timeout:Ob})}catch(o){return qt(`the interview could not be delivered to the user: ${o instanceof Error?o.message:String(o)}`)}switch(n.action){case"accept":{let o=Mb(r.request,n.content??void 0);switch(o.type){case"ok":return z({answers:o.answers});case"invalid":return qt(o.message)}break}case"decline":{let o=Nb(n._meta);switch(o){case jb:return qt("linzumi_ask_user_question is unavailable during a Plan-mode turn: use the native request_user_input interview tool instead");case Ib:return qt("the interview was declined: no active turn is bound to this session");default:let i="publish_failed: ";return o?.startsWith(i)?qt(`the interview could not be published to the user: ${o.slice(i.length)}`):qt("the interview request was declined by the runner")}}case"cancel":return qt("the user dismissed the question without answering");default:return qt(`the interview returned an unknown action: ${String(n.action)}`)}}function z(e){return{content:[{type:"text",text:JSON.stringify(e,null,2)}],structuredContent:e}}async function Bb(e){try{return z(await e)}catch(t){let r=t instanceof Error?t.message:String(t),n=r.match(/failed: ([a-z0-9_]+)(?: detail=(.+))?$/);if(n===null)return z({error:r});let[,o,i]=n;return z(i===void 0?{error:o??r}:{error:o??r,detail:i})}}function tp(e){let t=new Map;for(let r=0;r<e.length;r+=1){let n=e[r];if(n===void 0)continue;if(!n.startsWith("--"))throw new Error(`unexpected argument ${n}`);let o=n.slice(2),i=iE.get(o);if(i===void 0)throw new Error(`unsupported option --${o}`);if(i.kind==="boolean"){t.set(o,!0);continue}let s=e[r+1];if(s===void 0||s.startsWith("--"))throw new Error(`--${o} requires a value`);t.set(o,s),r+=1}return t}function te(e,t){let r=e.get(t);return typeof r=="string"&&r.trim()!==""?r:void 0}function rp(e){switch(e){case void 0:return"text";case"voice":case"text":return e;default:throw new Error("--mode must be voice or text")}}function Kb(e){switch(e){case void 0:return"all";case"all":case"coding":case"onboarding-discovery":return e;default:throw new Error("--tool-scope must be all, coding, or onboarding-discovery")}}function np(e,t){let r=te(e,t);if(r===void 0)throw new Error(`--${t} is required`);return r}function xE(e){return e[0]==="mcp"?e.slice(1):e}async function SE(e){try{await Hb(xE(e))}catch(t){process.stderr.write(`linzumi mcp server failed: ${t instanceof Error?t.message:String(t)}
455
- `),process.exitCode=1}}var $E=process.argv[1]!==void 0&&import.meta.url===kE(process.argv[1]).href;$E&&SE(process.argv.slice(2));export{xE as mcpServerEntryArgs,SE as runMcpServerEntry};