@kya-os/mcp-i 1.5.6-canary.1 → 1.5.6-canary.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/runtime/adapter-express.js +1 -1
- package/dist/runtime/adapter-nextjs.js +1 -1
- package/dist/runtime/http.js +1 -1
- package/dist/runtime/proof.d.ts +4 -0
- package/dist/runtime/proof.js +36 -5
- package/dist/runtime/stdio.js +1 -1
- package/dist/runtime/verifier-middleware.d.ts +25 -2
- package/dist/runtime/verifier-middleware.js +82 -6
- package/package.json +3 -3
package/dist/runtime/stdio.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
/*! For license information please see stdio.js.LICENSE.txt */
|
|
2
|
-
(()=>{var e={6069:(e,t,r)=>{"use strict";var a=r(72916).MissingRef;e.exports=function e(t,r,s){var i=this;if("function"!=typeof this._opts.loadSchema)throw new Error("options.loadSchema should be a function");"function"==typeof r&&(s=r,r=void 0);var n=o(t).then(function(){var e=i._addSchema(t,void 0,r);return e.validate||d(e)});return s&&n.then(function(e){s(null,e)},s),n;function o(t){var r=t.$schema;return r&&!i.getSchema(r)?e.call(i,{$ref:r},!0):Promise.resolve()}function d(e){try{return i._compile(e)}catch(t){if(t instanceof a)return function(t){var a=t.missingSchema;if(c(a))throw new Error("Schema "+a+" is loaded but "+t.missingRef+" cannot be resolved");var s=i._loadingSchemas[a];return s||(s=i._loadingSchemas[a]=i._opts.loadSchema(a)).then(n,n),s.then(function(e){if(!c(a))return o(e).then(function(){c(a)||i.addSchema(e,a,void 0,r)})}).then(function(){return d(e)});function n(){delete i._loadingSchemas[a]}function c(e){return i._refs[e]||i._schemas[e]}}(t);throw t}}}},9717:(e,t,r)=>{"use strict";function a(e,t,r,a){var s=a?" !== ":" === ",i=a?" || ":" && ",n=a?"!":"",o=a?"":"!";switch(e){case"null":return t+s+"null";case"array":return n+"Array.isArray("+t+")";case"object":return"("+n+t+i+"typeof "+t+s+'"object"'+i+o+"Array.isArray("+t+"))";case"integer":return"(typeof "+t+s+'"number"'+i+o+"("+t+" % 1)"+i+t+s+t+(r?i+n+"isFinite("+t+")":"")+")";case"number":return"(typeof "+t+s+'"'+e+'"'+(r?i+n+"isFinite("+t+")":"")+")";default:return"typeof "+t+s+'"'+e+'"'}}e.exports={copy:function(e,t){for(var r in t=t||{},e)t[r]=e[r];return t},checkDataType:a,checkDataTypes:function(e,t,r){if(1===e.length)return a(e[0],t,r,!0);var s="",n=i(e);for(var o in n.array&&n.object&&(s=n.null?"(":"(!"+t+" || ",s+="typeof "+t+' !== "object")',delete n.null,delete n.array,delete n.object),n.number&&delete n.integer,n)s+=(s?" && ":"")+a(o,t,r,!0);return s},coerceToTypes:function(e,t){if(Array.isArray(t)){for(var r=[],a=0;a<t.length;a++){var i=t[a];(s[i]||"array"===e&&"array"===i)&&(r[r.length]=i)}if(r.length)return r}else{if(s[t])return[t];if("array"===e&&"array"===t)return["array"]}},toHash:i,getProperty:d,escapeQuotes:c,equal:r(67371),ucs2length:r(61812),varOccurences:function(e,t){t+="[^0-9]";var r=e.match(new RegExp(t,"g"));return r?r.length:0},varReplace:function(e,t,r){return t+="([^0-9])",r=r.replace(/\$/g,"$$$$"),e.replace(new RegExp(t,"g"),r+"$1")},schemaHasRules:function(e,t){if("boolean"==typeof e)return!e;for(var r in e)if(t[r])return!0},schemaHasRulesExcept:function(e,t,r){if("boolean"==typeof e)return!e&&"not"!=r;for(var a in e)if(a!=r&&t[a])return!0},schemaUnknownRules:function(e,t){if("boolean"!=typeof e)for(var r in e)if(!t[r])return r},toQuotedString:u,getPathExpr:function(e,t,r,a){return p(e,r?"'/' + "+t+(a?"":".replace(/~/g, '~0').replace(/\\//g, '~1')"):a?"'[' + "+t+" + ']'":"'[\\'' + "+t+" + '\\']'")},getPath:function(e,t,r){return p(e,u(r?"/"+f(t):d(t)))},getData:function(e,t,r){var a,s,i,n;if(""===e)return"rootData";if("/"==e[0]){if(!l.test(e))throw new Error("Invalid JSON-pointer: "+e);s=e,i="rootData"}else{if(!(n=e.match(h)))throw new Error("Invalid JSON-pointer: "+e);if(a=+n[1],"#"==(s=n[2])){if(a>=t)throw new Error("Cannot access property/index "+a+" levels up, current level is "+t);return r[t-a]}if(a>t)throw new Error("Cannot access data "+a+" levels up, current level is "+t);if(i="data"+(t-a||""),!s)return i}for(var o=i,c=s.split("/"),u=0;u<c.length;u++){var p=c[u];p&&(o+=" && "+(i+=d(m(p))))}return o},unescapeFragment:function(e){return m(decodeURIComponent(e))},unescapeJsonPointer:m,escapeFragment:function(e){return encodeURIComponent(f(e))},escapeJsonPointer:f};var s=i(["string","number","integer","boolean","null"]);function i(e){for(var t={},r=0;r<e.length;r++)t[e[r]]=!0;return t}var n=/^[a-z$_][a-z$_0-9]*$/i,o=/'|\\/g;function d(e){return"number"==typeof e?"["+e+"]":n.test(e)?"."+e:"['"+c(e)+"']"}function c(e){return e.replace(o,"\\$&").replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\f/g,"\\f").replace(/\t/g,"\\t")}function u(e){return"'"+c(e)+"'"}var l=/^\/(?:[^~]|~0|~1)*$/,h=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function p(e,t){return'""'==e?t:(e+" + "+t).replace(/([^\\])' \+ '/g,"$1")}function f(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}function m(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}},9931:e=>{"use strict";e.exports=function(e,t,r){var a=" ",s=e.level,i=e.dataLevel,n=e.schema[t],o=e.schemaPath+e.util.getProperty(t),d=e.errSchemaPath+"/"+t,c=!e.opts.allErrors,u="data"+(i||""),l="errs__"+s,h=e.util.copy(e);h.level++;var p="valid"+h.level;if(a+="var "+l+" = errors;",e.opts.strictKeywords?"object"==typeof n&&Object.keys(n).length>0||!1===n:e.util.schemaHasRules(n,e.RULES.all)){h.schema=n,h.schemaPath=o,h.errSchemaPath=d;var f="key"+s,m="idx"+s,v="i"+s,y="' + "+f+" + '",g="data"+(h.dataLevel=e.dataLevel+1),_="dataProperties"+s,b=e.opts.ownProperties,w=e.baseId;b&&(a+=" var "+_+" = undefined; "),a+=b?" "+_+" = "+_+" || Object.keys("+u+"); for (var "+m+"=0; "+m+"<"+_+".length; "+m+"++) { var "+f+" = "+_+"["+m+"]; ":" for (var "+f+" in "+u+") { ",a+=" var startErrs"+s+" = errors; ";var P=f,E=e.compositeRule;e.compositeRule=h.compositeRule=!0;var x=e.validate(h);h.baseId=w,e.util.varOccurences(x,g)<2?a+=" "+e.util.varReplace(x,g,P)+" ":a+=" var "+g+" = "+P+"; "+x+" ",e.compositeRule=h.compositeRule=E,a+=" if (!"+p+") { for (var "+v+"=startErrs"+s+"; "+v+"<errors; "+v+"++) { vErrors["+v+"].propertyName = "+f+"; } var err = ",!1!==e.createErrors?(a+=" { keyword: 'propertyNames' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(d)+" , params: { propertyName: '"+y+"' } ",!1!==e.opts.messages&&(a+=" , message: 'property name \\'"+y+"\\' is invalid' "),e.opts.verbose&&(a+=" , schema: validate.schema"+o+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+u+" "),a+=" } "):a+=" {} ",a+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",!e.compositeRule&&c&&(e.async?a+=" throw new ValidationError(vErrors); ":a+=" validate.errors = vErrors; return false; "),c&&(a+=" break; "),a+=" } }"}return c&&(a+=" if ("+l+" == errors) {"),a}},12269:e=>{"use strict";e.exports=JSON.parse('{"$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":true,"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":true,"readOnly":{"type":"boolean","default":false},"examples":{"type":"array","items":true},"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":true},"maxItems":{"$ref":"#/definitions/nonNegativeInteger"},"minItems":{"$ref":"#/definitions/nonNegativeIntegerDefault0"},"uniqueItems":{"type":"boolean","default":false},"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":true,"enum":{"type":"array","items":true,"minItems":1,"uniqueItems":true},"type":{"anyOf":[{"$ref":"#/definitions/simpleTypes"},{"type":"array","items":{"$ref":"#/definitions/simpleTypes"},"minItems":1,"uniqueItems":true}]},"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":true}')},12857:e=>{"use strict";e.exports=function(e,t,r){var a,s,i=" ",n=e.level,o=e.dataLevel,d=e.schema[t],c=e.errSchemaPath+"/"+t,u=!e.opts.allErrors,l="data"+(o||""),h="valid"+n;if("#"==d||"#/"==d)e.isRoot?(a=e.async,s="validate"):(a=!0===e.root.schema.$async,s="root.refVal[0]");else{var p=e.resolveRef(e.baseId,d,e.isRoot);if(void 0===p){var f=e.MissingRefError.message(e.baseId,d);if("fail"==e.opts.missingRefs){e.logger.error(f),(g=g||[]).push(i),i="",!1!==e.createErrors?(i+=" { keyword: '$ref' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { ref: '"+e.util.escapeQuotes(d)+"' } ",!1!==e.opts.messages&&(i+=" , message: 'can\\'t resolve reference "+e.util.escapeQuotes(d)+"' "),e.opts.verbose&&(i+=" , schema: "+e.util.toQuotedString(d)+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+l+" "),i+=" } "):i+=" {} ";var m=i;i=g.pop(),!e.compositeRule&&u?e.async?i+=" throw new ValidationError(["+m+"]); ":i+=" validate.errors = ["+m+"]; return false; ":i+=" var err = "+m+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",u&&(i+=" if (false) { ")}else{if("ignore"!=e.opts.missingRefs)throw new e.MissingRefError(e.baseId,d,f);e.logger.warn(f),u&&(i+=" if (true) { ")}}else if(p.inline){var v=e.util.copy(e);v.level++;var y="valid"+v.level;v.schema=p.schema,v.schemaPath="",v.errSchemaPath=d,i+=" "+e.validate(v).replace(/validate\.schema/g,p.code)+" ",u&&(i+=" if ("+y+") { ")}else a=!0===p.$async||e.async&&!1!==p.$async,s=p.code}if(s){var g;(g=g||[]).push(i),i="",e.opts.passContext?i+=" "+s+".call(this, ":i+=" "+s+"( ",i+=" "+l+", (dataPath || '')",'""'!=e.errorPath&&(i+=" + "+e.errorPath);var _=i+=" , "+(o?"data"+(o-1||""):"parentData")+" , "+(o?e.dataPathArr[o]:"parentDataProperty")+", rootData) ";if(i=g.pop(),a){if(!e.async)throw new Error("async schema referenced by sync schema");u&&(i+=" var "+h+"; "),i+=" try { await "+_+"; ",u&&(i+=" "+h+" = true; "),i+=" } catch (e) { if (!(e instanceof ValidationError)) throw e; if (vErrors === null) vErrors = e.errors; else vErrors = vErrors.concat(e.errors); errors = vErrors.length; ",u&&(i+=" "+h+" = false; "),i+=" } ",u&&(i+=" if ("+h+") { ")}else i+=" if (!"+_+") { if (vErrors === null) vErrors = "+s+".errors; else vErrors = vErrors.concat("+s+".errors); errors = vErrors.length; } ",u&&(i+=" else { ")}return i}},13215:e=>{"use strict";e.exports=JSON.parse('{"$schema":"http://json-schema.org/draft-07/schema#","$id":"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#","description":"Meta-schema for $data reference (JSON Schema extension proposal)","type":"object","required":["$data"],"properties":{"$data":{"type":"string","anyOf":[{"format":"relative-json-pointer"},{"format":"json-pointer"}]}},"additionalProperties":false}')},13441:e=>{"use strict";e.exports=function(e,t,r){var a=" ",s=e.level,i=e.dataLevel,n=e.schema[t],o=e.schemaPath+e.util.getProperty(t),d=e.errSchemaPath+"/"+t,c=!e.opts.allErrors,u="data"+(i||""),l="errs__"+s,h=e.util.copy(e);h.level++;var p="valid"+h.level;if(e.opts.strictKeywords?"object"==typeof n&&Object.keys(n).length>0||!1===n:e.util.schemaHasRules(n,e.RULES.all)){h.schema=n,h.schemaPath=o,h.errSchemaPath=d,a+=" var "+l+" = errors; ";var f,m=e.compositeRule;e.compositeRule=h.compositeRule=!0,h.createErrors=!1,h.opts.allErrors&&(f=h.opts.allErrors,h.opts.allErrors=!1),a+=" "+e.validate(h)+" ",h.createErrors=!0,f&&(h.opts.allErrors=f),e.compositeRule=h.compositeRule=m,a+=" if ("+p+") { ";var v=v||[];v.push(a),a="",!1!==e.createErrors?(a+=" { keyword: 'not' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(d)+" , params: {} ",!1!==e.opts.messages&&(a+=" , message: 'should NOT be valid' "),e.opts.verbose&&(a+=" , schema: validate.schema"+o+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+u+" "),a+=" } "):a+=" {} ";var y=a;a=v.pop(),!e.compositeRule&&c?e.async?a+=" throw new ValidationError(["+y+"]); ":a+=" validate.errors = ["+y+"]; return false; ":a+=" var err = "+y+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",a+=" } else { errors = "+l+"; if (vErrors !== null) { if ("+l+") vErrors.length = "+l+"; else vErrors = null; } ",e.opts.allErrors&&(a+=" } ")}else a+=" var err = ",!1!==e.createErrors?(a+=" { keyword: 'not' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(d)+" , params: {} ",!1!==e.opts.messages&&(a+=" , message: 'should NOT be valid' "),e.opts.verbose&&(a+=" , schema: validate.schema"+o+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+u+" "),a+=" } "):a+=" {} ",a+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",c&&(a+=" if (false) { ");return a}},13749:function(e,t){!function(e){"use strict";function t(){for(var e=arguments.length,t=Array(e),r=0;r<e;r++)t[r]=arguments[r];if(t.length>1){t[0]=t[0].slice(0,-1);for(var a=t.length-1,s=1;s<a;++s)t[s]=t[s].slice(1,-1);return t[a]=t[a].slice(1),t.join("")}return t[0]}function r(e){return"(?:"+e+")"}function a(e){return void 0===e?"undefined":null===e?"null":Object.prototype.toString.call(e).split(" ").pop().split("]").shift().toLowerCase()}function s(e){return e.toUpperCase()}function i(e){var a="[A-Za-z]",s="[0-9]",i=t(s,"[A-Fa-f]"),n=r(r("%[EFef]"+i+"%"+i+i+"%"+i+i)+"|"+r("%[89A-Fa-f]"+i+"%"+i+i)+"|"+r("%"+i+i)),o="[\\!\\$\\&\\'\\(\\)\\*\\+\\,\\;\\=]",d=t("[\\:\\/\\?\\#\\[\\]\\@]",o),c=e?"[\\uE000-\\uF8FF]":"[]",u=t(a,s,"[\\-\\.\\_\\~]",e?"[\\xA0-\\u200D\\u2010-\\u2029\\u202F-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF]":"[]"),l=r(a+t(a,s,"[\\+\\-\\.]")+"*"),h=r(r(n+"|"+t(u,o,"[\\:]"))+"*"),p=(r(r("25[0-5]")+"|"+r("2[0-4]"+s)+"|"+r("1"+s+s)+"|"+r("[1-9]"+s)+"|"+s),r(r("25[0-5]")+"|"+r("2[0-4]"+s)+"|"+r("1"+s+s)+"|"+r("0?[1-9]"+s)+"|0?0?"+s)),f=r(p+"\\."+p+"\\."+p+"\\."+p),m=r(i+"{1,4}"),v=r(r(m+"\\:"+m)+"|"+f),y=r(r(m+"\\:")+"{6}"+v),g=r("\\:\\:"+r(m+"\\:")+"{5}"+v),_=r(r(m)+"?\\:\\:"+r(m+"\\:")+"{4}"+v),b=r(r(r(m+"\\:")+"{0,1}"+m)+"?\\:\\:"+r(m+"\\:")+"{3}"+v),w=r(r(r(m+"\\:")+"{0,2}"+m)+"?\\:\\:"+r(m+"\\:")+"{2}"+v),P=r(r(r(m+"\\:")+"{0,3}"+m)+"?\\:\\:"+m+"\\:"+v),E=r(r(r(m+"\\:")+"{0,4}"+m)+"?\\:\\:"+v),x=r(r(r(m+"\\:")+"{0,5}"+m)+"?\\:\\:"+m),S=r(r(r(m+"\\:")+"{0,6}"+m)+"?\\:\\:"),I=r([y,g,_,b,w,P,E,x,S].join("|")),k=r(r(u+"|"+n)+"+"),T=(r(I+"\\%25"+k),r(I+r("\\%25|\\%(?!"+i+"{2})")+k)),C=r("[vV]"+i+"+\\."+t(u,o,"[\\:]")+"+"),A=r("\\["+r(T+"|"+I+"|"+C)+"\\]"),O=r(r(n+"|"+t(u,o))+"*"),R=r(A+"|"+f+"(?!"+O+")|"+O),D=r(s+"*"),N=r(r(h+"@")+"?"+R+r("\\:"+D)+"?"),Z=r(n+"|"+t(u,o,"[\\:\\@]")),$=r(Z+"*"),j=r(Z+"+"),F=r(r(n+"|"+t(u,o,"[\\@]"))+"+"),M=r(r("\\/"+$)+"*"),L=r("\\/"+r(j+M)+"?"),z=r(F+M),V=r(j+M),q="(?!"+Z+")",U=(r(M+"|"+L+"|"+z+"|"+V+"|"+q),r(r(Z+"|"+t("[\\/\\?]",c))+"*")),K=r(r(Z+"|[\\/\\?]")+"*"),H=r(r("\\/\\/"+N+M)+"|"+L+"|"+V+"|"+q),B=r(l+"\\:"+H+r("\\?"+U)+"?"+r("\\#"+K)+"?"),Q=r(r("\\/\\/"+N+M)+"|"+L+"|"+z+"|"+q),J=r(Q+r("\\?"+U)+"?"+r("\\#"+K)+"?");return r(B+"|"+J),r(l+"\\:"+H+r("\\?"+U)+"?"),r(r("\\/\\/("+r("("+h+")@")+"?("+R+")"+r("\\:("+D+")")+"?)")+"?("+M+"|"+L+"|"+V+"|"+q+")"),r("\\?("+U+")"),r("\\#("+K+")"),r(r("\\/\\/("+r("("+h+")@")+"?("+R+")"+r("\\:("+D+")")+"?)")+"?("+M+"|"+L+"|"+z+"|"+q+")"),r("\\?("+U+")"),r("\\#("+K+")"),r(r("\\/\\/("+r("("+h+")@")+"?("+R+")"+r("\\:("+D+")")+"?)")+"?("+M+"|"+L+"|"+V+"|"+q+")"),r("\\?("+U+")"),r("\\#("+K+")"),r("("+h+")@"),r("\\:("+D+")"),{NOT_SCHEME:new RegExp(t("[^]",a,s,"[\\+\\-\\.]"),"g"),NOT_USERINFO:new RegExp(t("[^\\%\\:]",u,o),"g"),NOT_HOST:new RegExp(t("[^\\%\\[\\]\\:]",u,o),"g"),NOT_PATH:new RegExp(t("[^\\%\\/\\:\\@]",u,o),"g"),NOT_PATH_NOSCHEME:new RegExp(t("[^\\%\\/\\@]",u,o),"g"),NOT_QUERY:new RegExp(t("[^\\%]",u,o,"[\\:\\@\\/\\?]",c),"g"),NOT_FRAGMENT:new RegExp(t("[^\\%]",u,o,"[\\:\\@\\/\\?]"),"g"),ESCAPE:new RegExp(t("[^]",u,o),"g"),UNRESERVED:new RegExp(u,"g"),OTHER_CHARS:new RegExp(t("[^\\%]",u,d),"g"),PCT_ENCODED:new RegExp(n,"g"),IPV4ADDRESS:new RegExp("^("+f+")$"),IPV6ADDRESS:new RegExp("^\\[?("+I+")"+r(r("\\%25|\\%(?!"+i+"{2})")+"("+k+")")+"?\\]?$")}}var n=i(!1),o=i(!0),d=function(e,t){if(Array.isArray(e))return e;if(Symbol.iterator in Object(e))return function(e,t){var r=[],a=!0,s=!1,i=void 0;try{for(var n,o=e[Symbol.iterator]();!(a=(n=o.next()).done)&&(r.push(n.value),!t||r.length!==t);a=!0);}catch(e){s=!0,i=e}finally{try{!a&&o.return&&o.return()}finally{if(s)throw i}}return r}(e,t);throw new TypeError("Invalid attempt to destructure non-iterable instance")},c=2147483647,u=36,l=/^xn--/,h=/[^\0-\x7E]/,p=/[\x2E\u3002\uFF0E\uFF61]/g,f={overflow:"Overflow: input needs wider integers to process","not-basic":"Illegal input >= 0x80 (not a basic code point)","invalid-input":"Invalid input"},m=Math.floor,v=String.fromCharCode;function y(e){throw new RangeError(f[e])}function g(e,t){var r=e.split("@"),a="";return r.length>1&&(a=r[0]+"@",e=r[1]),a+function(e,t){for(var r=[],a=e.length;a--;)r[a]=t(e[a]);return r}((e=e.replace(p,".")).split("."),t).join(".")}function _(e){for(var t=[],r=0,a=e.length;r<a;){var s=e.charCodeAt(r++);if(s>=55296&&s<=56319&&r<a){var i=e.charCodeAt(r++);56320==(64512&i)?t.push(((1023&s)<<10)+(1023&i)+65536):(t.push(s),r--)}else t.push(s)}return t}var b=function(e){return e-48<10?e-22:e-65<26?e-65:e-97<26?e-97:u},w=function(e,t){return e+22+75*(e<26)-((0!=t)<<5)},P=function(e,t,r){var a=0;for(e=r?m(e/700):e>>1,e+=m(e/t);e>455;a+=u)e=m(e/35);return m(a+36*e/(e+38))},E=function(e){var t=[],r=e.length,a=0,s=128,i=72,n=e.lastIndexOf("-");n<0&&(n=0);for(var o=0;o<n;++o)e.charCodeAt(o)>=128&&y("not-basic"),t.push(e.charCodeAt(o));for(var d=n>0?n+1:0;d<r;){for(var l=a,h=1,p=u;;p+=u){d>=r&&y("invalid-input");var f=b(e.charCodeAt(d++));(f>=u||f>m((c-a)/h))&&y("overflow"),a+=f*h;var v=p<=i?1:p>=i+26?26:p-i;if(f<v)break;var g=u-v;h>m(c/g)&&y("overflow"),h*=g}var _=t.length+1;i=P(a-l,_,0==l),m(a/_)>c-s&&y("overflow"),s+=m(a/_),a%=_,t.splice(a++,0,s)}return String.fromCodePoint.apply(String,t)},x=function(e){var t=[],r=(e=_(e)).length,a=128,s=0,i=72,n=!0,o=!1,d=void 0;try{for(var l,h=e[Symbol.iterator]();!(n=(l=h.next()).done);n=!0){var p=l.value;p<128&&t.push(v(p))}}catch(e){o=!0,d=e}finally{try{!n&&h.return&&h.return()}finally{if(o)throw d}}var f=t.length,g=f;for(f&&t.push("-");g<r;){var b=c,E=!0,x=!1,S=void 0;try{for(var I,k=e[Symbol.iterator]();!(E=(I=k.next()).done);E=!0){var T=I.value;T>=a&&T<b&&(b=T)}}catch(e){x=!0,S=e}finally{try{!E&&k.return&&k.return()}finally{if(x)throw S}}var C=g+1;b-a>m((c-s)/C)&&y("overflow"),s+=(b-a)*C,a=b;var A=!0,O=!1,R=void 0;try{for(var D,N=e[Symbol.iterator]();!(A=(D=N.next()).done);A=!0){var Z=D.value;if(Z<a&&++s>c&&y("overflow"),Z==a){for(var $=s,j=u;;j+=u){var F=j<=i?1:j>=i+26?26:j-i;if($<F)break;var M=$-F,L=u-F;t.push(v(w(F+M%L,0))),$=m(M/L)}t.push(v(w($,0))),i=P(s,C,g==f),s=0,++g}}}catch(e){O=!0,R=e}finally{try{!A&&N.return&&N.return()}finally{if(O)throw R}}++s,++a}return t.join("")},S=function(e){return g(e,function(e){return h.test(e)?"xn--"+x(e):e})},I=function(e){return g(e,function(e){return l.test(e)?E(e.slice(4).toLowerCase()):e})},k={};function T(e){var t=e.charCodeAt(0);return t<16?"%0"+t.toString(16).toUpperCase():t<128?"%"+t.toString(16).toUpperCase():t<2048?"%"+(t>>6|192).toString(16).toUpperCase()+"%"+(63&t|128).toString(16).toUpperCase():"%"+(t>>12|224).toString(16).toUpperCase()+"%"+(t>>6&63|128).toString(16).toUpperCase()+"%"+(63&t|128).toString(16).toUpperCase()}function C(e){for(var t="",r=0,a=e.length;r<a;){var s=parseInt(e.substr(r+1,2),16);if(s<128)t+=String.fromCharCode(s),r+=3;else if(s>=194&&s<224){if(a-r>=6){var i=parseInt(e.substr(r+4,2),16);t+=String.fromCharCode((31&s)<<6|63&i)}else t+=e.substr(r,6);r+=6}else if(s>=224){if(a-r>=9){var n=parseInt(e.substr(r+4,2),16),o=parseInt(e.substr(r+7,2),16);t+=String.fromCharCode((15&s)<<12|(63&n)<<6|63&o)}else t+=e.substr(r,9);r+=9}else t+=e.substr(r,3),r+=3}return t}function A(e,t){function r(e){var r=C(e);return r.match(t.UNRESERVED)?r:e}return e.scheme&&(e.scheme=String(e.scheme).replace(t.PCT_ENCODED,r).toLowerCase().replace(t.NOT_SCHEME,"")),void 0!==e.userinfo&&(e.userinfo=String(e.userinfo).replace(t.PCT_ENCODED,r).replace(t.NOT_USERINFO,T).replace(t.PCT_ENCODED,s)),void 0!==e.host&&(e.host=String(e.host).replace(t.PCT_ENCODED,r).toLowerCase().replace(t.NOT_HOST,T).replace(t.PCT_ENCODED,s)),void 0!==e.path&&(e.path=String(e.path).replace(t.PCT_ENCODED,r).replace(e.scheme?t.NOT_PATH:t.NOT_PATH_NOSCHEME,T).replace(t.PCT_ENCODED,s)),void 0!==e.query&&(e.query=String(e.query).replace(t.PCT_ENCODED,r).replace(t.NOT_QUERY,T).replace(t.PCT_ENCODED,s)),void 0!==e.fragment&&(e.fragment=String(e.fragment).replace(t.PCT_ENCODED,r).replace(t.NOT_FRAGMENT,T).replace(t.PCT_ENCODED,s)),e}function O(e){return e.replace(/^0*(.*)/,"$1")||"0"}function R(e,t){var r=e.match(t.IPV4ADDRESS)||[],a=d(r,2)[1];return a?a.split(".").map(O).join("."):e}function D(e,t){var r=e.match(t.IPV6ADDRESS)||[],a=d(r,3),s=a[1],i=a[2];if(s){for(var n=s.toLowerCase().split("::").reverse(),o=d(n,2),c=o[0],u=o[1],l=u?u.split(":").map(O):[],h=c.split(":").map(O),p=t.IPV4ADDRESS.test(h[h.length-1]),f=p?7:8,m=h.length-f,v=Array(f),y=0;y<f;++y)v[y]=l[y]||h[m+y]||"";p&&(v[f-1]=R(v[f-1],t));var g=v.reduce(function(e,t,r){if(!t||"0"===t){var a=e[e.length-1];a&&a.index+a.length===r?a.length++:e.push({index:r,length:1})}return e},[]).sort(function(e,t){return t.length-e.length})[0],_=void 0;if(g&&g.length>1){var b=v.slice(0,g.index),w=v.slice(g.index+g.length);_=b.join(":")+"::"+w.join(":")}else _=v.join(":");return i&&(_+="%"+i),_}return e}var N=/^(?:([^:\/?#]+):)?(?:\/\/((?:([^\/?#@]*)@)?(\[[^\/?#\]]+\]|[^\/?#:]*)(?:\:(\d*))?))?([^?#]*)(?:\?([^#]*))?(?:#((?:.|\n|\r)*))?/i,Z=void 0==="".match(/(){0}/)[1];function $(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r={},a=!1!==t.iri?o:n;"suffix"===t.reference&&(e=(t.scheme?t.scheme+":":"")+"//"+e);var s=e.match(N);if(s){Z?(r.scheme=s[1],r.userinfo=s[3],r.host=s[4],r.port=parseInt(s[5],10),r.path=s[6]||"",r.query=s[7],r.fragment=s[8],isNaN(r.port)&&(r.port=s[5])):(r.scheme=s[1]||void 0,r.userinfo=-1!==e.indexOf("@")?s[3]:void 0,r.host=-1!==e.indexOf("//")?s[4]:void 0,r.port=parseInt(s[5],10),r.path=s[6]||"",r.query=-1!==e.indexOf("?")?s[7]:void 0,r.fragment=-1!==e.indexOf("#")?s[8]:void 0,isNaN(r.port)&&(r.port=e.match(/\/\/(?:.|\n)*\:(?:\/|\?|\#|$)/)?s[4]:void 0)),r.host&&(r.host=D(R(r.host,a),a)),void 0!==r.scheme||void 0!==r.userinfo||void 0!==r.host||void 0!==r.port||r.path||void 0!==r.query?void 0===r.scheme?r.reference="relative":void 0===r.fragment?r.reference="absolute":r.reference="uri":r.reference="same-document",t.reference&&"suffix"!==t.reference&&t.reference!==r.reference&&(r.error=r.error||"URI is not a "+t.reference+" reference.");var i=k[(t.scheme||r.scheme||"").toLowerCase()];if(t.unicodeSupport||i&&i.unicodeSupport)A(r,a);else{if(r.host&&(t.domainHost||i&&i.domainHost))try{r.host=S(r.host.replace(a.PCT_ENCODED,C).toLowerCase())}catch(e){r.error=r.error||"Host's domain name can not be converted to ASCII via punycode: "+e}A(r,n)}i&&i.parse&&i.parse(r,t)}else r.error=r.error||"URI can not be parsed.";return r}var j=/^\.\.?\//,F=/^\/\.(\/|$)/,M=/^\/\.\.(\/|$)/,L=/^\/?(?:.|\n)*?(?=\/|$)/;function z(e){for(var t=[];e.length;)if(e.match(j))e=e.replace(j,"");else if(e.match(F))e=e.replace(F,"/");else if(e.match(M))e=e.replace(M,"/"),t.pop();else if("."===e||".."===e)e="";else{var r=e.match(L);if(!r)throw new Error("Unexpected dot segment condition");var a=r[0];e=e.slice(a.length),t.push(a)}return t.join("")}function V(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=t.iri?o:n,a=[],s=k[(t.scheme||e.scheme||"").toLowerCase()];if(s&&s.serialize&&s.serialize(e,t),e.host)if(r.IPV6ADDRESS.test(e.host));else if(t.domainHost||s&&s.domainHost)try{e.host=t.iri?I(e.host):S(e.host.replace(r.PCT_ENCODED,C).toLowerCase())}catch(r){e.error=e.error||"Host's domain name can not be converted to "+(t.iri?"Unicode":"ASCII")+" via punycode: "+r}A(e,r),"suffix"!==t.reference&&e.scheme&&(a.push(e.scheme),a.push(":"));var i=function(e,t){var r=!1!==t.iri?o:n,a=[];return void 0!==e.userinfo&&(a.push(e.userinfo),a.push("@")),void 0!==e.host&&a.push(D(R(String(e.host),r),r).replace(r.IPV6ADDRESS,function(e,t,r){return"["+t+(r?"%25"+r:"")+"]"})),"number"!=typeof e.port&&"string"!=typeof e.port||(a.push(":"),a.push(String(e.port))),a.length?a.join(""):void 0}(e,t);if(void 0!==i&&("suffix"!==t.reference&&a.push("//"),a.push(i),e.path&&"/"!==e.path.charAt(0)&&a.push("/")),void 0!==e.path){var d=e.path;t.absolutePath||s&&s.absolutePath||(d=z(d)),void 0===i&&(d=d.replace(/^\/\//,"/%2F")),a.push(d)}return void 0!==e.query&&(a.push("?"),a.push(e.query)),void 0!==e.fragment&&(a.push("#"),a.push(e.fragment)),a.join("")}function q(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},a={};return arguments[3]||(e=$(V(e,r),r),t=$(V(t,r),r)),!(r=r||{}).tolerant&&t.scheme?(a.scheme=t.scheme,a.userinfo=t.userinfo,a.host=t.host,a.port=t.port,a.path=z(t.path||""),a.query=t.query):(void 0!==t.userinfo||void 0!==t.host||void 0!==t.port?(a.userinfo=t.userinfo,a.host=t.host,a.port=t.port,a.path=z(t.path||""),a.query=t.query):(t.path?("/"===t.path.charAt(0)?a.path=z(t.path):(void 0===e.userinfo&&void 0===e.host&&void 0===e.port||e.path?e.path?a.path=e.path.slice(0,e.path.lastIndexOf("/")+1)+t.path:a.path=t.path:a.path="/"+t.path,a.path=z(a.path)),a.query=t.query):(a.path=e.path,void 0!==t.query?a.query=t.query:a.query=e.query),a.userinfo=e.userinfo,a.host=e.host,a.port=e.port),a.scheme=e.scheme),a.fragment=t.fragment,a}function U(e,t){return e&&e.toString().replace(t&&t.iri?o.PCT_ENCODED:n.PCT_ENCODED,C)}var K={scheme:"http",domainHost:!0,parse:function(e,t){return e.host||(e.error=e.error||"HTTP URIs must have a host."),e},serialize:function(e,t){var r="https"===String(e.scheme).toLowerCase();return e.port!==(r?443:80)&&""!==e.port||(e.port=void 0),e.path||(e.path="/"),e}},H={scheme:"https",domainHost:K.domainHost,parse:K.parse,serialize:K.serialize};function B(e){return"boolean"==typeof e.secure?e.secure:"wss"===String(e.scheme).toLowerCase()}var Q={scheme:"ws",domainHost:!0,parse:function(e,t){var r=e;return r.secure=B(r),r.resourceName=(r.path||"/")+(r.query?"?"+r.query:""),r.path=void 0,r.query=void 0,r},serialize:function(e,t){if(e.port!==(B(e)?443:80)&&""!==e.port||(e.port=void 0),"boolean"==typeof e.secure&&(e.scheme=e.secure?"wss":"ws",e.secure=void 0),e.resourceName){var r=e.resourceName.split("?"),a=d(r,2),s=a[0],i=a[1];e.path=s&&"/"!==s?s:void 0,e.query=i,e.resourceName=void 0}return e.fragment=void 0,e}},J={scheme:"wss",domainHost:Q.domainHost,parse:Q.parse,serialize:Q.serialize},W={},G="[A-Za-z0-9\\-\\.\\_\\~\\xA0-\\u200D\\u2010-\\u2029\\u202F-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF]",Y="[0-9A-Fa-f]",X=r(r("%[EFef]"+Y+"%"+Y+Y+"%"+Y+Y)+"|"+r("%[89A-Fa-f]"+Y+"%"+Y+Y)+"|"+r("%"+Y+Y)),ee=t("[\\!\\$\\%\\'\\(\\)\\*\\+\\,\\-\\.0-9\\<\\>A-Z\\x5E-\\x7E]",'[\\"\\\\]'),te=new RegExp(G,"g"),re=new RegExp(X,"g"),ae=new RegExp(t("[^]","[A-Za-z0-9\\!\\$\\%\\'\\*\\+\\-\\^\\_\\`\\{\\|\\}\\~]","[\\.]",'[\\"]',ee),"g"),se=new RegExp(t("[^]",G,"[\\!\\$\\'\\(\\)\\*\\+\\,\\;\\:\\@]"),"g"),ie=se;function ne(e){var t=C(e);return t.match(te)?t:e}var oe={scheme:"mailto",parse:function(e,t){var r=e,a=r.to=r.path?r.path.split(","):[];if(r.path=void 0,r.query){for(var s=!1,i={},n=r.query.split("&"),o=0,d=n.length;o<d;++o){var c=n[o].split("=");switch(c[0]){case"to":for(var u=c[1].split(","),l=0,h=u.length;l<h;++l)a.push(u[l]);break;case"subject":r.subject=U(c[1],t);break;case"body":r.body=U(c[1],t);break;default:s=!0,i[U(c[0],t)]=U(c[1],t)}}s&&(r.headers=i)}r.query=void 0;for(var p=0,f=a.length;p<f;++p){var m=a[p].split("@");if(m[0]=U(m[0]),t.unicodeSupport)m[1]=U(m[1],t).toLowerCase();else try{m[1]=S(U(m[1],t).toLowerCase())}catch(e){r.error=r.error||"Email address's domain name can not be converted to ASCII via punycode: "+e}a[p]=m.join("@")}return r},serialize:function(e,t){var r,a=e,i=null!=(r=e.to)?r instanceof Array?r:"number"!=typeof r.length||r.split||r.setInterval||r.call?[r]:Array.prototype.slice.call(r):[];if(i){for(var n=0,o=i.length;n<o;++n){var d=String(i[n]),c=d.lastIndexOf("@"),u=d.slice(0,c).replace(re,ne).replace(re,s).replace(ae,T),l=d.slice(c+1);try{l=t.iri?I(l):S(U(l,t).toLowerCase())}catch(e){a.error=a.error||"Email address's domain name can not be converted to "+(t.iri?"Unicode":"ASCII")+" via punycode: "+e}i[n]=u+"@"+l}a.path=i.join(",")}var h=e.headers=e.headers||{};e.subject&&(h.subject=e.subject),e.body&&(h.body=e.body);var p=[];for(var f in h)h[f]!==W[f]&&p.push(f.replace(re,ne).replace(re,s).replace(se,T)+"="+h[f].replace(re,ne).replace(re,s).replace(ie,T));return p.length&&(a.query=p.join("&")),a}},de=/^([^\:]+)\:(.*)/,ce={scheme:"urn",parse:function(e,t){var r=e.path&&e.path.match(de),a=e;if(r){var s=t.scheme||a.scheme||"urn",i=r[1].toLowerCase(),n=r[2],o=s+":"+(t.nid||i),d=k[o];a.nid=i,a.nss=n,a.path=void 0,d&&(a=d.parse(a,t))}else a.error=a.error||"URN can not be parsed.";return a},serialize:function(e,t){var r=t.scheme||e.scheme||"urn",a=e.nid,s=r+":"+(t.nid||a),i=k[s];i&&(e=i.serialize(e,t));var n=e,o=e.nss;return n.path=(a||t.nid)+":"+o,n}},ue=/^[0-9A-Fa-f]{8}(?:\-[0-9A-Fa-f]{4}){3}\-[0-9A-Fa-f]{12}$/,le={scheme:"urn:uuid",parse:function(e,t){var r=e;return r.uuid=r.nss,r.nss=void 0,t.tolerant||r.uuid&&r.uuid.match(ue)||(r.error=r.error||"UUID is not valid."),r},serialize:function(e,t){var r=e;return r.nss=(e.uuid||"").toLowerCase(),r}};k[K.scheme]=K,k[H.scheme]=H,k[Q.scheme]=Q,k[J.scheme]=J,k[oe.scheme]=oe,k[ce.scheme]=ce,k[le.scheme]=le,e.SCHEMES=k,e.pctEncChar=T,e.pctDecChars=C,e.parse=$,e.removeDotSegments=z,e.serialize=V,e.resolveComponents=q,e.resolve=function(e,t,r){var a=function(e,t){var r=e;if(t)for(var a in t)r[a]=t[a];return r}({scheme:"null"},r);return V(q($(e,a),$(t,a),a,!0),a)},e.normalize=function(e,t){return"string"==typeof e?e=V($(e,t),t):"object"===a(e)&&(e=$(V(e,t),t)),e},e.equal=function(e,t,r){return"string"==typeof e?e=V($(e,r),r):"object"===a(e)&&(e=V(e,r)),"string"==typeof t?t=V($(t,r),r):"object"===a(t)&&(t=V(t,r)),e===t},e.escapeComponent=function(e,t){return e&&e.toString().replace(t&&t.iri?o.ESCAPE:n.ESCAPE,T)},e.unescapeComponent=U,Object.defineProperty(e,"__esModule",{value:!0})}(t)},14547:e=>{"use strict";e.exports=function(e,t,r){var a=" ",s=e.level,i=e.dataLevel,n=e.schema[t],o=e.schemaPath+e.util.getProperty(t),d=e.errSchemaPath+"/"+t,c=!e.opts.allErrors,u="data"+(i||""),l="valid"+s,h="errs__"+s,p=e.util.copy(e),f="";p.level++;var m="valid"+p.level,v=n.every(function(t){return e.opts.strictKeywords?"object"==typeof t&&Object.keys(t).length>0||!1===t:e.util.schemaHasRules(t,e.RULES.all)});if(v){var y=p.baseId;a+=" var "+h+" = errors; var "+l+" = false; ";var g=e.compositeRule;e.compositeRule=p.compositeRule=!0;var _=n;if(_)for(var b,w=-1,P=_.length-1;w<P;)b=_[w+=1],p.schema=b,p.schemaPath=o+"["+w+"]",p.errSchemaPath=d+"/"+w,a+=" "+e.validate(p)+" ",p.baseId=y,a+=" "+l+" = "+l+" || "+m+"; if (!"+l+") { ",f+="}";e.compositeRule=p.compositeRule=g,a+=" "+f+" if (!"+l+") { var err = ",!1!==e.createErrors?(a+=" { keyword: 'anyOf' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(d)+" , params: {} ",!1!==e.opts.messages&&(a+=" , message: 'should match some schema in anyOf' "),e.opts.verbose&&(a+=" , schema: validate.schema"+o+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+u+" "),a+=" } "):a+=" {} ",a+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",!e.compositeRule&&c&&(e.async?a+=" throw new ValidationError(vErrors); ":a+=" validate.errors = vErrors; return false; "),a+=" } else { errors = "+h+"; if (vErrors !== null) { if ("+h+") vErrors.length = "+h+"; else vErrors = null; } ",e.opts.allErrors&&(a+=" } ")}else c&&(a+=" if (true) { ");return a}},16928:e=>{"use strict";e.exports=require("path")},20698:(e,t,r)=>{"use strict";var a=r(52004),s=r(9717).toHash;e.exports=function(){var e=[{type:"number",rules:[{maximum:["exclusiveMaximum"]},{minimum:["exclusiveMinimum"]},"multipleOf","format"]},{type:"string",rules:["maxLength","minLength","pattern","format"]},{type:"array",rules:["maxItems","minItems","items","contains","uniqueItems"]},{type:"object",rules:["maxProperties","minProperties","required","dependencies","propertyNames",{properties:["additionalProperties","patternProperties"]}]},{rules:["$ref","const","enum","not","anyOf","oneOf","allOf","if"]}],t=["type","$comment"];return e.all=s(t),e.types=s(["number","integer","string","array","object","boolean","null"]),e.forEach(function(r){r.rules=r.rules.map(function(r){var s;if("object"==typeof r){var i=Object.keys(r)[0];s=r[i],r=i,s.forEach(function(r){t.push(r),e.all[r]=!0})}return t.push(r),e.all[r]={keyword:r,code:a[r],implements:s}}),e.all.$comment={keyword:"$comment",code:a.$comment},r.type&&(e.types[r.type]=r)}),e.keywords=s(t.concat(["$schema","$id","id","$data","$async","title","description","default","definitions","examples","readOnly","writeOnly","contentMediaType","contentEncoding","additionalItems","then","else"])),e.custom={},e}},20812:(e,t,r)=>{"use strict";var a=r(9717);e.exports=function(e){a.copy(e,this)}},22853:(e,t,r)=>{"use strict";var a=r(40985),s=r(9717),i=r(72916),n=r(56039),o=r(25572),d=s.ucs2length,c=r(67371),u=i.Validation;function l(e,t,r){var a=p.call(this,e,t,r);return a>=0?{index:a,compiling:!0}:(a=this._compilations.length,this._compilations[a]={schema:e,root:t,baseId:r},{index:a,compiling:!1})}function h(e,t,r){var a=p.call(this,e,t,r);a>=0&&this._compilations.splice(a,1)}function p(e,t,r){for(var a=0;a<this._compilations.length;a++){var s=this._compilations[a];if(s.schema==e&&s.root==t&&s.baseId==r)return a}return-1}function f(e,t){return"var pattern"+e+" = new RegExp("+s.toQuotedString(t[e])+");"}function m(e){return"var default"+e+" = defaults["+e+"];"}function v(e,t){return void 0===t[e]?"":"var refVal"+e+" = refVal["+e+"];"}function y(e){return"var customRule"+e+" = customRules["+e+"];"}function g(e,t){if(!e.length)return"";for(var r="",a=0;a<e.length;a++)r+=t(a,e);return r}e.exports=function e(t,r,p,_){var b=this,w=this._opts,P=[void 0],E={},x=[],S={},I=[],k={},T=[];r=r||{schema:t,refVal:P,refs:E};var C=l.call(this,t,r,_),A=this._compilations[C.index];if(C.compiling)return A.callValidate=function e(){var t=A.validate,r=t.apply(this,arguments);return e.errors=t.errors,r};var O=this._formats,R=this.RULES;try{var D=Z(t,r,p,_);A.validate=D;var N=A.callValidate;return N&&(N.schema=D.schema,N.errors=null,N.refs=D.refs,N.refVal=D.refVal,N.root=D.root,N.$async=D.$async,w.sourceCode&&(N.source=D.source)),D}finally{h.call(this,t,r,_)}function Z(t,n,l,h){var p=!n||n&&n.schema==t;if(n.schema!=r.schema)return e.call(b,t,n,l,h);var _,S=!0===t.$async,k=o({isTop:!0,schema:t,isRoot:p,baseId:h,root:n,schemaPath:"",errSchemaPath:"#",errorPath:'""',MissingRefError:i.MissingRef,RULES:R,validate:o,util:s,resolve:a,resolveRef:$,usePattern:M,useDefault:L,useCustomRule:z,opts:w,formats:O,logger:b.logger,self:b});k=g(P,v)+g(x,f)+g(I,m)+g(T,y)+k,w.processCode&&(k=w.processCode(k,t));try{_=new Function("self","RULES","formats","root","refVal","defaults","customRules","equal","ucs2length","ValidationError",k)(b,R,O,r,P,I,T,c,d,u),P[0]=_}catch(e){throw b.logger.error("Error compiling schema, function code:",k),e}return _.schema=t,_.errors=null,_.refs=E,_.refVal=P,_.root=p?_:n,S&&(_.$async=!0),!0===w.sourceCode&&(_.source={code:k,patterns:x,defaults:I}),_}function $(t,s,i){s=a.url(t,s);var n,o,d=E[s];if(void 0!==d)return F(n=P[d],o="refVal["+d+"]");if(!i&&r.refs){var c=r.refs[s];if(void 0!==c)return F(n=r.refVal[c],o=j(s,n))}o=j(s);var u=a.call(b,Z,r,s);if(void 0===u){var l=p&&p[s];l&&(u=a.inlineRef(l,w.inlineRefs)?l:e.call(b,l,r,p,t))}if(void 0!==u)return function(e,t){var r=E[e];P[r]=t}(s,u),F(u,o);!function(e){delete E[e]}(s)}function j(e,t){var r=P.length;return P[r]=t,E[e]=r,"refVal"+r}function F(e,t){return"object"==typeof e||"boolean"==typeof e?{code:t,schema:e,inline:!0}:{code:t,$async:e&&!!e.$async}}function M(e){var t=S[e];return void 0===t&&(t=S[e]=x.length,x[t]=e),"pattern"+t}function L(e){switch(typeof e){case"boolean":case"number":return""+e;case"string":return s.toQuotedString(e);case"object":if(null===e)return"null";var t=n(e),r=k[t];return void 0===r&&(r=k[t]=I.length,I[r]=e),"default"+r}}function z(e,t,r,a){if(!1!==b._opts.validateSchema){var s=e.definition.dependencies;if(s&&!s.every(function(e){return Object.prototype.hasOwnProperty.call(r,e)}))throw new Error("parent schema must have all required keywords: "+s.join(","));var i=e.definition.validateSchema;if(i&&!i(t)){var n="keyword schema is invalid: "+b.errorsText(i.errors);if("log"!=b._opts.validateSchema)throw new Error(n);b.logger.error(n)}}var o,d=e.definition.compile,c=e.definition.inline,u=e.definition.macro;if(d)o=d.call(b,t,r,a);else if(u)o=u.call(b,t,r,a),!1!==w.validateSchema&&b.validateSchema(o,!0);else if(c)o=c.call(b,a,e.keyword,t,r);else if(!(o=e.definition.validate))return;if(void 0===o)throw new Error('custom keyword "'+e.keyword+'"failed to compile');var l=T.length;return T[l]=o,{code:"customRule"+l,validate:o}}}},24235:e=>{"use strict";e.exports=function(e,t,r){var a=" ",s=e.level,i=e.dataLevel,n=e.schema[t],o=e.schemaPath+e.util.getProperty(t),d=e.errSchemaPath+"/"+t,c=!e.opts.allErrors,u="data"+(i||""),l="valid"+s,h="errs__"+s,p=e.util.copy(e);p.level++;var f="valid"+p.level,m="i"+s,v=p.dataLevel=e.dataLevel+1,y="data"+v,g=e.baseId,_=e.opts.strictKeywords?"object"==typeof n&&Object.keys(n).length>0||!1===n:e.util.schemaHasRules(n,e.RULES.all);if(a+="var "+h+" = errors;var "+l+";",_){var b=e.compositeRule;e.compositeRule=p.compositeRule=!0,p.schema=n,p.schemaPath=o,p.errSchemaPath=d,a+=" var "+f+" = false; for (var "+m+" = 0; "+m+" < "+u+".length; "+m+"++) { ",p.errorPath=e.util.getPathExpr(e.errorPath,m,e.opts.jsonPointers,!0);var w=u+"["+m+"]";p.dataPathArr[v]=m;var P=e.validate(p);p.baseId=g,e.util.varOccurences(P,y)<2?a+=" "+e.util.varReplace(P,y,w)+" ":a+=" var "+y+" = "+w+"; "+P+" ",a+=" if ("+f+") break; } ",e.compositeRule=p.compositeRule=b,a+=" if (!"+f+") {"}else a+=" if ("+u+".length == 0) {";var E=E||[];E.push(a),a="",!1!==e.createErrors?(a+=" { keyword: 'contains' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(d)+" , params: {} ",!1!==e.opts.messages&&(a+=" , message: 'should contain a valid item' "),e.opts.verbose&&(a+=" , schema: validate.schema"+o+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+u+" "),a+=" } "):a+=" {} ";var x=a;return a=E.pop(),!e.compositeRule&&c?e.async?a+=" throw new ValidationError(["+x+"]); ":a+=" validate.errors = ["+x+"]; return false; ":a+=" var err = "+x+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",a+=" } else { ",_&&(a+=" errors = "+h+"; if (vErrors !== null) { if ("+h+") vErrors.length = "+h+"; else vErrors = null; } "),e.opts.allErrors&&(a+=" } "),a}},25572:e=>{"use strict";e.exports=function(e,t,r){var a="",s=!0===e.schema.$async,i=e.util.schemaHasRulesExcept(e.schema,e.RULES.all,"$ref"),n=e.self._getId(e.schema);if(e.opts.strictKeywords){var o=e.util.schemaUnknownRules(e.schema,e.RULES.keywords);if(o){var d="unknown keyword: "+o;if("log"!==e.opts.strictKeywords)throw new Error(d);e.logger.warn(d)}}if(e.isTop&&(a+=" var validate = ",s&&(e.async=!0,a+="async "),a+="function(data, dataPath, parentData, parentDataProperty, rootData) { 'use strict'; ",n&&(e.opts.sourceCode||e.opts.processCode)&&(a+=" /*# sourceURL="+n+" */ ")),"boolean"==typeof e.schema||!i&&!e.schema.$ref){t="false schema";var c=e.level,u=e.dataLevel,l=e.schema[t],h=e.schemaPath+e.util.getProperty(t),p=e.errSchemaPath+"/"+t,f=!e.opts.allErrors,m="data"+(u||""),v="valid"+c;if(!1===e.schema){e.isTop?f=!0:a+=" var "+v+" = false; ",(K=K||[]).push(a),a="",!1!==e.createErrors?(a+=" { keyword: 'false schema' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(p)+" , params: {} ",!1!==e.opts.messages&&(a+=" , message: 'boolean schema is false' "),e.opts.verbose&&(a+=" , schema: false , parentSchema: validate.schema"+e.schemaPath+" , data: "+m+" "),a+=" } "):a+=" {} ";var y=a;a=K.pop(),!e.compositeRule&&f?e.async?a+=" throw new ValidationError(["+y+"]); ":a+=" validate.errors = ["+y+"]; return false; ":a+=" var err = "+y+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; "}else e.isTop?a+=s?" return data; ":" validate.errors = null; return true; ":a+=" var "+v+" = true; ";return e.isTop&&(a+=" }; return validate; "),a}if(e.isTop){var g=e.isTop;if(c=e.level=0,u=e.dataLevel=0,m="data",e.rootId=e.resolve.fullPath(e.self._getId(e.root.schema)),e.baseId=e.baseId||e.rootId,delete e.isTop,e.dataPathArr=[""],void 0!==e.schema.default&&e.opts.useDefaults&&e.opts.strictDefaults){var _="default is ignored in the schema root";if("log"!==e.opts.strictDefaults)throw new Error(_);e.logger.warn(_)}a+=" var vErrors = null; ",a+=" var errors = 0; ",a+=" if (rootData === undefined) rootData = data; "}else{if(c=e.level,m="data"+((u=e.dataLevel)||""),n&&(e.baseId=e.resolve.url(e.baseId,n)),s&&!e.async)throw new Error("async schema in sync schema");a+=" var errs_"+c+" = errors;"}v="valid"+c,f=!e.opts.allErrors;var b="",w="",P=e.schema.type,E=Array.isArray(P);if(P&&e.opts.nullable&&!0===e.schema.nullable&&(E?-1==P.indexOf("null")&&(P=P.concat("null")):"null"!=P&&(P=[P,"null"],E=!0)),E&&1==P.length&&(P=P[0],E=!1),e.schema.$ref&&i){if("fail"==e.opts.extendRefs)throw new Error('$ref: validation keywords used in schema at path "'+e.errSchemaPath+'" (see option extendRefs)');!0!==e.opts.extendRefs&&(i=!1,e.logger.warn('$ref: keywords ignored in schema at path "'+e.errSchemaPath+'"'))}if(e.schema.$comment&&e.opts.$comment&&(a+=" "+e.RULES.all.$comment.code(e,"$comment")),P){if(e.opts.coerceTypes)var x=e.util.coerceToTypes(e.opts.coerceTypes,P);var S=e.RULES.types[P];if(x||E||!0===S||S&&!G(S)){h=e.schemaPath+".type",p=e.errSchemaPath+"/type",h=e.schemaPath+".type",p=e.errSchemaPath+"/type";var I=E?"checkDataTypes":"checkDataType";if(a+=" if ("+e.util[I](P,m,e.opts.strictNumbers,!0)+") { ",x){var k="dataType"+c,T="coerced"+c;a+=" var "+k+" = typeof "+m+"; var "+T+" = undefined; ","array"==e.opts.coerceTypes&&(a+=" if ("+k+" == 'object' && Array.isArray("+m+") && "+m+".length == 1) { "+m+" = "+m+"[0]; "+k+" = typeof "+m+"; if ("+e.util.checkDataType(e.schema.type,m,e.opts.strictNumbers)+") "+T+" = "+m+"; } "),a+=" if ("+T+" !== undefined) ; ";var C=x;if(C)for(var A,O=-1,R=C.length-1;O<R;)"string"==(A=C[O+=1])?a+=" else if ("+k+" == 'number' || "+k+" == 'boolean') "+T+" = '' + "+m+"; else if ("+m+" === null) "+T+" = ''; ":"number"==A||"integer"==A?(a+=" else if ("+k+" == 'boolean' || "+m+" === null || ("+k+" == 'string' && "+m+" && "+m+" == +"+m+" ","integer"==A&&(a+=" && !("+m+" % 1)"),a+=")) "+T+" = +"+m+"; "):"boolean"==A?a+=" else if ("+m+" === 'false' || "+m+" === 0 || "+m+" === null) "+T+" = false; else if ("+m+" === 'true' || "+m+" === 1) "+T+" = true; ":"null"==A?a+=" else if ("+m+" === '' || "+m+" === 0 || "+m+" === false) "+T+" = null; ":"array"==e.opts.coerceTypes&&"array"==A&&(a+=" else if ("+k+" == 'string' || "+k+" == 'number' || "+k+" == 'boolean' || "+m+" == null) "+T+" = ["+m+"]; ");a+=" else { ",(K=K||[]).push(a),a="",!1!==e.createErrors?(a+=" { keyword: 'type' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(p)+" , params: { type: '",a+=E?""+P.join(","):""+P,a+="' } ",!1!==e.opts.messages&&(a+=" , message: 'should be ",a+=E?""+P.join(","):""+P,a+="' "),e.opts.verbose&&(a+=" , schema: validate.schema"+h+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+m+" "),a+=" } "):a+=" {} ",y=a,a=K.pop(),!e.compositeRule&&f?e.async?a+=" throw new ValidationError(["+y+"]); ":a+=" validate.errors = ["+y+"]; return false; ":a+=" var err = "+y+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",a+=" } if ("+T+" !== undefined) { ";var D=u?"data"+(u-1||""):"parentData";a+=" "+m+" = "+T+"; ",u||(a+="if ("+D+" !== undefined)"),a+=" "+D+"["+(u?e.dataPathArr[u]:"parentDataProperty")+"] = "+T+"; } "}else(K=K||[]).push(a),a="",!1!==e.createErrors?(a+=" { keyword: 'type' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(p)+" , params: { type: '",a+=E?""+P.join(","):""+P,a+="' } ",!1!==e.opts.messages&&(a+=" , message: 'should be ",a+=E?""+P.join(","):""+P,a+="' "),e.opts.verbose&&(a+=" , schema: validate.schema"+h+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+m+" "),a+=" } "):a+=" {} ",y=a,a=K.pop(),!e.compositeRule&&f?e.async?a+=" throw new ValidationError(["+y+"]); ":a+=" validate.errors = ["+y+"]; return false; ":a+=" var err = "+y+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ";a+=" } "}}if(e.schema.$ref&&!i)a+=" "+e.RULES.all.$ref.code(e,"$ref")+" ",f&&(a+=" } if (errors === ",a+=g?"0":"errs_"+c,a+=") { ",w+="}");else{var N=e.RULES;if(N)for(var Z=-1,$=N.length-1;Z<$;)if(G(S=N[Z+=1])){if(S.type&&(a+=" if ("+e.util.checkDataType(S.type,m,e.opts.strictNumbers)+") { "),e.opts.useDefaults)if("object"==S.type&&e.schema.properties){l=e.schema.properties;var j=Object.keys(l);if(j)for(var F,M=-1,L=j.length-1;M<L;)if(void 0!==(q=l[F=j[M+=1]]).default){var z=m+e.util.getProperty(F);if(e.compositeRule){if(e.opts.strictDefaults){if(_="default is ignored for: "+z,"log"!==e.opts.strictDefaults)throw new Error(_);e.logger.warn(_)}}else a+=" if ("+z+" === undefined ","empty"==e.opts.useDefaults&&(a+=" || "+z+" === null || "+z+" === '' "),a+=" ) "+z+" = ","shared"==e.opts.useDefaults?a+=" "+e.useDefault(q.default)+" ":a+=" "+JSON.stringify(q.default)+" ",a+="; "}}else if("array"==S.type&&Array.isArray(e.schema.items)){var V=e.schema.items;if(V){O=-1;for(var q,U=V.length-1;O<U;)if(void 0!==(q=V[O+=1]).default)if(z=m+"["+O+"]",e.compositeRule){if(e.opts.strictDefaults){if(_="default is ignored for: "+z,"log"!==e.opts.strictDefaults)throw new Error(_);e.logger.warn(_)}}else a+=" if ("+z+" === undefined ","empty"==e.opts.useDefaults&&(a+=" || "+z+" === null || "+z+" === '' "),a+=" ) "+z+" = ","shared"==e.opts.useDefaults?a+=" "+e.useDefault(q.default)+" ":a+=" "+JSON.stringify(q.default)+" ",a+="; "}}var K,H=S.rules;if(H)for(var B,Q=-1,J=H.length-1;Q<J;)if(Y(B=H[Q+=1])){var W=B.code(e,B.keyword,S.type);W&&(a+=" "+W+" ",f&&(b+="}"))}if(f&&(a+=" "+b+" ",b=""),S.type&&(a+=" } ",P&&P===S.type&&!x))a+=" else { ",h=e.schemaPath+".type",p=e.errSchemaPath+"/type",(K=K||[]).push(a),a="",!1!==e.createErrors?(a+=" { keyword: 'type' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(p)+" , params: { type: '",a+=E?""+P.join(","):""+P,a+="' } ",!1!==e.opts.messages&&(a+=" , message: 'should be ",a+=E?""+P.join(","):""+P,a+="' "),e.opts.verbose&&(a+=" , schema: validate.schema"+h+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+m+" "),a+=" } "):a+=" {} ",y=a,a=K.pop(),!e.compositeRule&&f?e.async?a+=" throw new ValidationError(["+y+"]); ":a+=" validate.errors = ["+y+"]; return false; ":a+=" var err = "+y+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",a+=" } ";f&&(a+=" if (errors === ",a+=g?"0":"errs_"+c,a+=") { ",w+="}")}}function G(e){for(var t=e.rules,r=0;r<t.length;r++)if(Y(t[r]))return!0}function Y(t){return void 0!==e.schema[t.keyword]||t.implements&&function(t){for(var r=t.implements,a=0;a<r.length;a++)if(void 0!==e.schema[r[a]])return!0}(t)}return f&&(a+=" "+w+" "),g?(s?(a+=" if (errors === 0) return data; ",a+=" else throw new ValidationError(vErrors); "):(a+=" validate.errors = vErrors; ",a+=" return errors === 0; "),a+=" }; return validate;"):a+=" var "+v+" = errors === errs_"+c+";",a}},27165:(e,t)=>{"use strict";var r,a;Object.defineProperty(t,"__esModule",{value:!0}),t.getParsedType=t.ZodParsedType=t.objectUtil=t.util=void 0,function(e){e.assertEqual=e=>{},e.assertIs=function(e){},e.assertNever=function(e){throw new Error},e.arrayToEnum=e=>{const t={};for(const r of e)t[r]=r;return t},e.getValidEnumValues=t=>{const r=e.objectKeys(t).filter(e=>"number"!=typeof t[t[e]]),a={};for(const e of r)a[e]=t[e];return e.objectValues(a)},e.objectValues=t=>e.objectKeys(t).map(function(e){return t[e]}),e.objectKeys="function"==typeof Object.keys?e=>Object.keys(e):e=>{const t=[];for(const r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.push(r);return t},e.find=(e,t)=>{for(const r of e)if(t(r))return r},e.isInteger="function"==typeof Number.isInteger?e=>Number.isInteger(e):e=>"number"==typeof e&&Number.isFinite(e)&&Math.floor(e)===e,e.joinValues=function(e,t=" | "){return e.map(e=>"string"==typeof e?`'${e}'`:e).join(t)},e.jsonStringifyReplacer=(e,t)=>"bigint"==typeof t?t.toString():t}(r||(t.util=r={})),function(e){e.mergeShapes=(e,t)=>({...e,...t})}(a||(t.objectUtil=a={})),t.ZodParsedType=r.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),t.getParsedType=e=>{switch(typeof e){case"undefined":return t.ZodParsedType.undefined;case"string":return t.ZodParsedType.string;case"number":return Number.isNaN(e)?t.ZodParsedType.nan:t.ZodParsedType.number;case"boolean":return t.ZodParsedType.boolean;case"function":return t.ZodParsedType.function;case"bigint":return t.ZodParsedType.bigint;case"symbol":return t.ZodParsedType.symbol;case"object":return Array.isArray(e)?t.ZodParsedType.array:null===e?t.ZodParsedType.null:e.then&&"function"==typeof e.then&&e.catch&&"function"==typeof e.catch?t.ZodParsedType.promise:"undefined"!=typeof Map&&e instanceof Map?t.ZodParsedType.map:"undefined"!=typeof Set&&e instanceof Set?t.ZodParsedType.set:"undefined"!=typeof Date&&e instanceof Date?t.ZodParsedType.date:t.ZodParsedType.object;default:return t.ZodParsedType.unknown}}},27713:e=>{"use strict";var t=e.exports=function(e,t,a){"function"==typeof t&&(a=t,t={}),r(t,"function"==typeof(a=t.cb||a)?a:a.pre||function(){},a.post||function(){},e,"",e)};function r(e,s,i,n,o,d,c,u,l,h){if(n&&"object"==typeof n&&!Array.isArray(n)){for(var p in s(n,o,d,c,u,l,h),n){var f=n[p];if(Array.isArray(f)){if(p in t.arrayKeywords)for(var m=0;m<f.length;m++)r(e,s,i,f[m],o+"/"+p+"/"+m,d,o,p,n,m)}else if(p in t.propsKeywords){if(f&&"object"==typeof f)for(var v in f)r(e,s,i,f[v],o+"/"+p+"/"+a(v),d,o,p,n,v)}else(p in t.keywords||e.allKeys&&!(p in t.skipKeywords))&&r(e,s,i,f,o+"/"+p,d,o,p,n)}i(n,o,d,c,u,l,h)}}function a(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}t.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0},t.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0},t.propsKeywords={definitions:!0,properties:!0,patternProperties:!0,dependencies:!0},t.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}},28565:e=>{"use strict";var t=e.exports=function(){this._cache={}};t.prototype.put=function(e,t){this._cache[e]=t},t.prototype.get=function(e){return this._cache[e]},t.prototype.del=function(e){delete this._cache[e]},t.prototype.clear=function(){this._cache={}}},33728:e=>{"use strict";e.exports=function(e,t,r){var a=" ",s=e.level,i=e.dataLevel,n=e.schema[t],o=e.schemaPath+e.util.getProperty(t),d=e.errSchemaPath+"/"+t,c=!e.opts.allErrors,u="data"+(i||""),l="valid"+s,h="errs__"+s,p=e.util.copy(e),f="";p.level++;var m="valid"+p.level,v="i"+s,y=p.dataLevel=e.dataLevel+1,g="data"+y,_=e.baseId;if(a+="var "+h+" = errors;var "+l+";",Array.isArray(n)){var b=e.schema.additionalItems;if(!1===b){a+=" "+l+" = "+u+".length <= "+n.length+"; ";var w=d;d=e.errSchemaPath+"/additionalItems",a+=" if (!"+l+") { ";var P=P||[];P.push(a),a="",!1!==e.createErrors?(a+=" { keyword: 'additionalItems' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(d)+" , params: { limit: "+n.length+" } ",!1!==e.opts.messages&&(a+=" , message: 'should NOT have more than "+n.length+" items' "),e.opts.verbose&&(a+=" , schema: false , parentSchema: validate.schema"+e.schemaPath+" , data: "+u+" "),a+=" } "):a+=" {} ";var E=a;a=P.pop(),!e.compositeRule&&c?e.async?a+=" throw new ValidationError(["+E+"]); ":a+=" validate.errors = ["+E+"]; return false; ":a+=" var err = "+E+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",a+=" } ",d=w,c&&(f+="}",a+=" else { ")}var x=n;if(x)for(var S,I=-1,k=x.length-1;I<k;)if(S=x[I+=1],e.opts.strictKeywords?"object"==typeof S&&Object.keys(S).length>0||!1===S:e.util.schemaHasRules(S,e.RULES.all)){a+=" "+m+" = true; if ("+u+".length > "+I+") { ";var T=u+"["+I+"]";p.schema=S,p.schemaPath=o+"["+I+"]",p.errSchemaPath=d+"/"+I,p.errorPath=e.util.getPathExpr(e.errorPath,I,e.opts.jsonPointers,!0),p.dataPathArr[y]=I;var C=e.validate(p);p.baseId=_,e.util.varOccurences(C,g)<2?a+=" "+e.util.varReplace(C,g,T)+" ":a+=" var "+g+" = "+T+"; "+C+" ",a+=" } ",c&&(a+=" if ("+m+") { ",f+="}")}"object"==typeof b&&(e.opts.strictKeywords?"object"==typeof b&&Object.keys(b).length>0||!1===b:e.util.schemaHasRules(b,e.RULES.all))&&(p.schema=b,p.schemaPath=e.schemaPath+".additionalItems",p.errSchemaPath=e.errSchemaPath+"/additionalItems",a+=" "+m+" = true; if ("+u+".length > "+n.length+") { for (var "+v+" = "+n.length+"; "+v+" < "+u+".length; "+v+"++) { ",p.errorPath=e.util.getPathExpr(e.errorPath,v,e.opts.jsonPointers,!0),T=u+"["+v+"]",p.dataPathArr[y]=v,C=e.validate(p),p.baseId=_,e.util.varOccurences(C,g)<2?a+=" "+e.util.varReplace(C,g,T)+" ":a+=" var "+g+" = "+T+"; "+C+" ",c&&(a+=" if (!"+m+") break; "),a+=" } } ",c&&(a+=" if ("+m+") { ",f+="}"))}else(e.opts.strictKeywords?"object"==typeof n&&Object.keys(n).length>0||!1===n:e.util.schemaHasRules(n,e.RULES.all))&&(p.schema=n,p.schemaPath=o,p.errSchemaPath=d,a+=" for (var "+v+" = 0; "+v+" < "+u+".length; "+v+"++) { ",p.errorPath=e.util.getPathExpr(e.errorPath,v,e.opts.jsonPointers,!0),T=u+"["+v+"]",p.dataPathArr[y]=v,C=e.validate(p),p.baseId=_,e.util.varOccurences(C,g)<2?a+=" "+e.util.varReplace(C,g,T)+" ":a+=" var "+g+" = "+T+"; "+C+" ",c&&(a+=" if (!"+m+") break; "),a+=" }");return c&&(a+=" "+f+" if ("+h+" == errors) {"),a}},36885:(e,t,r)=>{"use strict";var a=r(9717),s=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,i=[0,31,28,31,30,31,30,31,31,30,31,30,31],n=/^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d(?::?\d\d)?)?$/i,o=/^(?=.{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,d=/^(?:[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,c=/^(?:(?:[^\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,u=/^(?:(?:http[s\u017F]?|ftp):\/\/)(?:(?:[\0-\x08\x0E-\x1F!-\x9F\xA1-\u167F\u1681-\u1FFF\u200B-\u2027\u202A-\u202E\u2030-\u205E\u2060-\u2FFF\u3001-\uD7FF\uE000-\uFEFE\uFF00-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+(?::(?:[\0-\x08\x0E-\x1F!-\x9F\xA1-\u167F\u1681-\u1FFF\u200B-\u2027\u202A-\u202E\u2030-\u205E\u2060-\u2FFF\u3001-\uD7FF\uE000-\uFEFE\uFF00-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])*)?@)?(?:(?!10(?:\.[0-9]{1,3}){3})(?!127(?:\.[0-9]{1,3}){3})(?!169\.254(?:\.[0-9]{1,3}){2})(?!192\.168(?:\.[0-9]{1,3}){2})(?!172\.(?:1[6-9]|2[0-9]|3[01])(?:\.[0-9]{1,3}){2})(?:[1-9][0-9]?|1[0-9][0-9]|2[01][0-9]|22[0-3])(?:\.(?:1?[0-9]{1,2}|2[0-4][0-9]|25[0-5])){2}(?:\.(?:[1-9][0-9]?|1[0-9][0-9]|2[0-4][0-9]|25[0-4]))|(?:(?:(?:[0-9a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+-)*(?:[0-9a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+)(?:\.(?:(?:[0-9a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+-)*(?:[0-9a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+)*(?:\.(?:(?:[a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]){2,})))(?::[0-9]{2,5})?(?:\/(?:[\0-\x08\x0E-\x1F!-\x9F\xA1-\u167F\u1681-\u1FFF\u200B-\u2027\u202A-\u202E\u2030-\u205E\u2060-\u2FFF\u3001-\uD7FF\uE000-\uFEFE\uFF00-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])*)?$/i,l=/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,h=/^(?:\/(?:[^~/]|~0|~1)*)*$/,p=/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,f=/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/;function m(e){return e="full"==e?"full":"fast",a.copy(m[e])}function v(e){var t=e.match(s);if(!t)return!1;var r=+t[1],a=+t[2],n=+t[3];return a>=1&&a<=12&&n>=1&&n<=(2==a&&function(e){return e%4==0&&(e%100!=0||e%400==0)}(r)?29:i[a])}function y(e,t){var r=e.match(n);if(!r)return!1;var a=r[1],s=r[2],i=r[3],o=r[5];return(a<=23&&s<=59&&i<=59||23==a&&59==s&&60==i)&&(!t||o)}e.exports=m,m.fast={date:/^\d\d\d\d-[0-1]\d-[0-3]\d$/,time:/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,"date-time":/^\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,uri:/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i,"uri-reference":/^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i,"uri-template":c,url:u,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,hostname:o,ipv4:/^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,ipv6:/^\s*(?:(?:(?:[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}))|:)))(?:%.+)?\s*$/i,regex:w,uuid:l,"json-pointer":h,"json-pointer-uri-fragment":p,"relative-json-pointer":f},m.full={date:v,time:y,"date-time":function(e){var t=e.split(g);return 2==t.length&&v(t[0])&&y(t[1],!0)},uri:function(e){return _.test(e)&&d.test(e)},"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":c,url:u,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:o,ipv4:/^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,ipv6:/^\s*(?:(?:(?:[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}))|:)))(?:%.+)?\s*$/i,regex:w,uuid:l,"json-pointer":h,"json-pointer-uri-fragment":p,"relative-json-pointer":f};var g=/t|\s/i,_=/\/|:/,b=/[^\\]\\Z/;function w(e){if(b.test(e))return!1;try{return new RegExp(e),!0}catch(e){return!1}}},36886:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const a=r(68820),s=r(27165);t.default=(e,t)=>{let r;switch(e.code){case a.ZodIssueCode.invalid_type:r=e.received===s.ZodParsedType.undefined?"Required":`Expected ${e.expected}, received ${e.received}`;break;case a.ZodIssueCode.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(e.expected,s.util.jsonStringifyReplacer)}`;break;case a.ZodIssueCode.unrecognized_keys:r=`Unrecognized key(s) in object: ${s.util.joinValues(e.keys,", ")}`;break;case a.ZodIssueCode.invalid_union:r="Invalid input";break;case a.ZodIssueCode.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${s.util.joinValues(e.options)}`;break;case a.ZodIssueCode.invalid_enum_value:r=`Invalid enum value. Expected ${s.util.joinValues(e.options)}, received '${e.received}'`;break;case a.ZodIssueCode.invalid_arguments:r="Invalid function arguments";break;case a.ZodIssueCode.invalid_return_type:r="Invalid function return type";break;case a.ZodIssueCode.invalid_date:r="Invalid date";break;case a.ZodIssueCode.invalid_string:"object"==typeof e.validation?"includes"in e.validation?(r=`Invalid input: must include "${e.validation.includes}"`,"number"==typeof e.validation.position&&(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}"`:s.util.assertNever(e.validation):r="regex"!==e.validation?`Invalid ${e.validation}`:"Invalid";break;case a.ZodIssueCode.too_small:r="array"===e.type?`Array must contain ${e.exact?"exactly":e.inclusive?"at least":"more than"} ${e.minimum} element(s)`:"string"===e.type?`String must contain ${e.exact?"exactly":e.inclusive?"at least":"over"} ${e.minimum} character(s)`:"number"===e.type||"bigint"===e.type?`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:"date"===e.type?`Date must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(e.minimum))}`:"Invalid input";break;case a.ZodIssueCode.too_big:r="array"===e.type?`Array must contain ${e.exact?"exactly":e.inclusive?"at most":"less than"} ${e.maximum} element(s)`:"string"===e.type?`String must contain ${e.exact?"exactly":e.inclusive?"at most":"under"} ${e.maximum} character(s)`:"number"===e.type?`Number must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:"bigint"===e.type?`BigInt must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:"date"===e.type?`Date must be ${e.exact?"exactly":e.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(e.maximum))}`:"Invalid input";break;case a.ZodIssueCode.custom:r="Invalid input";break;case a.ZodIssueCode.invalid_intersection_types:r="Intersection results could not be merged";break;case a.ZodIssueCode.not_multiple_of:r=`Number must be a multiple of ${e.multipleOf}`;break;case a.ZodIssueCode.not_finite:r="Number must be finite";break;default:r=t.defaultError,s.util.assertNever(e)}return{message:r}}},40985:(e,t,r)=>{"use strict";var a=r(13749),s=r(67371),i=r(9717),n=r(20812),o=r(27713);function d(e,t,r){var a=this._refs[r];if("string"==typeof a){if(!this._refs[a])return d.call(this,e,t,a);a=this._refs[a]}if((a=a||this._schemas[r])instanceof n)return f(a.schema,this._opts.inlineRefs)?a.schema:a.validate||this._compile(a);var s,i,o,u=c.call(this,t,r);return u&&(s=u.schema,t=u.root,o=u.baseId),s instanceof n?i=s.validate||e.call(this,s.schema,t,void 0,o):void 0!==s&&(i=f(s,this._opts.inlineRefs)?s:e.call(this,s,t,void 0,o)),i}function c(e,t){var r=a.parse(t),s=g(r),i=y(this._getId(e.schema));if(0===Object.keys(e.schema).length||s!==i){var o=b(s),d=this._refs[o];if("string"==typeof d)return u.call(this,e,d,r);if(d instanceof n)d.validate||this._compile(d),e=d;else{if(!((d=this._schemas[o])instanceof n))return;if(d.validate||this._compile(d),o==b(t))return{schema:d,root:e,baseId:i};e=d}if(!e.schema)return;i=y(this._getId(e.schema))}return h.call(this,r,i,e.schema,e)}function u(e,t,r){var a=c.call(this,e,t);if(a){var s=a.schema,i=a.baseId;e=a.root;var n=this._getId(s);return n&&(i=w(i,n)),h.call(this,r,i,s,e)}}e.exports=d,d.normalizeId=b,d.fullPath=y,d.url=w,d.ids=function(e){var t=b(this._getId(e)),r={"":t},n={"":y(t,!1)},d={},c=this;return o(e,{allKeys:!0},function(e,t,o,u,l,h,p){if(""!==t){var f=c._getId(e),m=r[u],v=n[u]+"/"+l;if(void 0!==p&&(v+="/"+("number"==typeof p?p:i.escapeFragment(p))),"string"==typeof f){f=m=b(m?a.resolve(m,f):f);var y=c._refs[f];if("string"==typeof y&&(y=c._refs[y]),y&&y.schema){if(!s(e,y.schema))throw new Error('id "'+f+'" resolves to more than one schema')}else if(f!=b(v))if("#"==f[0]){if(d[f]&&!s(e,d[f]))throw new Error('id "'+f+'" resolves to more than one schema');d[f]=e}else c._refs[f]=v}r[t]=m,n[t]=v}}),d},d.inlineRef=f,d.schema=c;var l=i.toHash(["properties","patternProperties","enum","dependencies","definitions"]);function h(e,t,r,a){if(e.fragment=e.fragment||"","/"==e.fragment.slice(0,1)){for(var s=e.fragment.split("/"),n=1;n<s.length;n++){var o=s[n];if(o){if(void 0===(r=r[o=i.unescapeFragment(o)]))break;var d;if(!l[o]&&((d=this._getId(r))&&(t=w(t,d)),r.$ref)){var u=w(t,r.$ref),h=c.call(this,a,u);h&&(r=h.schema,a=h.root,t=h.baseId)}}}return void 0!==r&&r!==a.schema?{schema:r,root:a,baseId:t}:void 0}}var p=i.toHash(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum"]);function f(e,t){return!1!==t&&(void 0===t||!0===t?m(e):t?v(e)<=t:void 0)}function m(e){var t;if(Array.isArray(e)){for(var r=0;r<e.length;r++)if("object"==typeof(t=e[r])&&!m(t))return!1}else for(var a in e){if("$ref"==a)return!1;if("object"==typeof(t=e[a])&&!m(t))return!1}return!0}function v(e){var t,r=0;if(Array.isArray(e)){for(var a=0;a<e.length;a++)if("object"==typeof(t=e[a])&&(r+=v(t)),r==1/0)return 1/0}else for(var s in e){if("$ref"==s)return 1/0;if(p[s])r++;else if("object"==typeof(t=e[s])&&(r+=v(t)+1),r==1/0)return 1/0}return r}function y(e,t){return!1!==t&&(e=b(e)),g(a.parse(e))}function g(e){return a.serialize(e).split("#")[0]+"#"}var _=/#\/?$/;function b(e){return e?e.replace(_,""):""}function w(e,t){return t=b(t),a.resolve(e,t)}},41021:e=>{"use strict";e.exports=function(e,t,r){var a,s,i=" ",n=e.level,o=e.dataLevel,d=e.schema[t],c=e.schemaPath+e.util.getProperty(t),u=e.errSchemaPath+"/"+t,l=!e.opts.allErrors,h="data"+(o||""),p="valid"+n,f="errs__"+n,m=e.opts.$data&&d&&d.$data;m?(i+=" var schema"+n+" = "+e.util.getData(d.$data,o,e.dataPathArr)+"; ",s="schema"+n):s=d;var v,y,g,_,b,w=this,P="definition"+n,E=w.definition,x="";if(m&&E.$data){b="keywordValidate"+n;var S=E.validateSchema;i+=" var "+P+" = RULES.custom['"+t+"'].definition; var "+b+" = "+P+".validate;"}else{if(!(_=e.useCustomRule(w,d,e.schema,e)))return;s="validate.schema"+c,b=_.code,v=E.compile,y=E.inline,g=E.macro}var I=b+".errors",k="i"+n,T="ruleErr"+n,C=E.async;if(C&&!e.async)throw new Error("async keyword in sync schema");if(y||g||(i+=I+" = null;"),i+="var "+f+" = errors;var "+p+";",m&&E.$data&&(x+="}",i+=" if ("+s+" === undefined) { "+p+" = true; } else { ",S&&(x+="}",i+=" "+p+" = "+P+".validateSchema("+s+"); if ("+p+") { ")),y)E.statements?i+=" "+_.validate+" ":i+=" "+p+" = "+_.validate+"; ";else if(g){var A=e.util.copy(e);x="",A.level++;var O="valid"+A.level;A.schema=_.validate,A.schemaPath="";var R=e.compositeRule;e.compositeRule=A.compositeRule=!0;var D=e.validate(A).replace(/validate\.schema/g,b);e.compositeRule=A.compositeRule=R,i+=" "+D}else{(j=j||[]).push(i),i="",i+=" "+b+".call( ",e.opts.passContext?i+="this":i+="self",v||!1===E.schema?i+=" , "+h+" ":i+=" , "+s+" , "+h+" , validate.schema"+e.schemaPath+" ",i+=" , (dataPath || '')",'""'!=e.errorPath&&(i+=" + "+e.errorPath);var N=o?"data"+(o-1||""):"parentData",Z=o?e.dataPathArr[o]:"parentDataProperty",$=i+=" , "+N+" , "+Z+" , rootData ) ";i=j.pop(),!1===E.errors?(i+=" "+p+" = ",C&&(i+="await "),i+=$+"; "):i+=C?" var "+(I="customErrors"+n)+" = null; try { "+p+" = await "+$+"; } catch (e) { "+p+" = false; if (e instanceof ValidationError) "+I+" = e.errors; else throw e; } ":" "+I+" = null; "+p+" = "+$+"; "}if(E.modifying&&(i+=" if ("+N+") "+h+" = "+N+"["+Z+"];"),i+=""+x,E.valid)l&&(i+=" if (true) { ");else{var j;i+=" if ( ",void 0===E.valid?(i+=" !",i+=g?""+O:""+p):i+=" "+!E.valid+" ",i+=") { ",a=w.keyword,(j=j||[]).push(i),i="",(j=j||[]).push(i),i="",!1!==e.createErrors?(i+=" { keyword: '"+(a||"custom")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: { keyword: '"+w.keyword+"' } ",!1!==e.opts.messages&&(i+=" , message: 'should pass \""+w.keyword+"\" keyword validation' "),e.opts.verbose&&(i+=" , schema: validate.schema"+c+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+h+" "),i+=" } "):i+=" {} ";var F=i;i=j.pop(),!e.compositeRule&&l?e.async?i+=" throw new ValidationError(["+F+"]); ":i+=" validate.errors = ["+F+"]; return false; ":i+=" var err = "+F+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ";var M=i;i=j.pop(),y?E.errors?"full"!=E.errors&&(i+=" for (var "+k+"="+f+"; "+k+"<errors; "+k+"++) { var "+T+" = vErrors["+k+"]; if ("+T+".dataPath === undefined) "+T+".dataPath = (dataPath || '') + "+e.errorPath+"; if ("+T+".schemaPath === undefined) { "+T+'.schemaPath = "'+u+'"; } ',e.opts.verbose&&(i+=" "+T+".schema = "+s+"; "+T+".data = "+h+"; "),i+=" } "):!1===E.errors?i+=" "+M+" ":(i+=" if ("+f+" == errors) { "+M+" } else { for (var "+k+"="+f+"; "+k+"<errors; "+k+"++) { var "+T+" = vErrors["+k+"]; if ("+T+".dataPath === undefined) "+T+".dataPath = (dataPath || '') + "+e.errorPath+"; if ("+T+".schemaPath === undefined) { "+T+'.schemaPath = "'+u+'"; } ',e.opts.verbose&&(i+=" "+T+".schema = "+s+"; "+T+".data = "+h+"; "),i+=" } } "):g?(i+=" var err = ",!1!==e.createErrors?(i+=" { keyword: '"+(a||"custom")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: { keyword: '"+w.keyword+"' } ",!1!==e.opts.messages&&(i+=" , message: 'should pass \""+w.keyword+"\" keyword validation' "),e.opts.verbose&&(i+=" , schema: validate.schema"+c+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+h+" "),i+=" } "):i+=" {} ",i+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",!e.compositeRule&&l&&(e.async?i+=" throw new ValidationError(vErrors); ":i+=" validate.errors = vErrors; return false; ")):!1===E.errors?i+=" "+M+" ":(i+=" if (Array.isArray("+I+")) { if (vErrors === null) vErrors = "+I+"; else vErrors = vErrors.concat("+I+"); errors = vErrors.length; for (var "+k+"="+f+"; "+k+"<errors; "+k+"++) { var "+T+" = vErrors["+k+"]; if ("+T+".dataPath === undefined) "+T+".dataPath = (dataPath || '') + "+e.errorPath+"; "+T+'.schemaPath = "'+u+'"; ',e.opts.verbose&&(i+=" "+T+".schema = "+s+"; "+T+".data = "+h+"; "),i+=" } } else { "+M+" } "),i+=" } ",l&&(i+=" else { ")}return i}},43528:(e,t,r)=>{"use strict";var a=/^[a-z_$][a-z0-9_$-]*$/i,s=r(41021),i=r(96150);e.exports={add:function(e,t){var r=this.RULES;if(r.keywords[e])throw new Error("Keyword "+e+" is already defined");if(!a.test(e))throw new Error("Keyword "+e+" is not a valid identifier");if(t){this.validateKeyword(t,!0);var i=t.type;if(Array.isArray(i))for(var n=0;n<i.length;n++)d(e,i[n],t);else d(e,i,t);var o=t.metaSchema;o&&(t.$data&&this._opts.$data&&(o={anyOf:[o,{$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"}]}),t.validateSchema=this.compile(o,!0))}function d(e,t,a){for(var i,n=0;n<r.length;n++){var o=r[n];if(o.type==t){i=o;break}}i||(i={type:t,rules:[]},r.push(i));var d={keyword:e,definition:a,custom:!0,code:s,implements:a.implements};i.rules.push(d),r.custom[e]=d}return r.keywords[e]=r.all[e]=!0,this},get:function(e){var t=this.RULES.custom[e];return t?t.definition:this.RULES.keywords[e]||!1},remove:function(e){var t=this.RULES;delete t.keywords[e],delete t.all[e],delete t.custom[e];for(var r=0;r<t.length;r++)for(var a=t[r].rules,s=0;s<a.length;s++)if(a[s].keyword==e){a.splice(s,1);break}return this},validate:function e(t,r){e.errors=null;var a=this._validateKeyword=this._validateKeyword||this.compile(i,!0);if(a(t))return!0;if(e.errors=a.errors,r)throw new Error("custom keyword definition is invalid: "+this.errorsText(a.errors));return!1}}},44242:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.discriminatedUnion=t.date=t.boolean=t.bigint=t.array=t.any=t.coerce=t.ZodFirstPartyTypeKind=t.late=t.ZodSchema=t.Schema=t.ZodReadonly=t.ZodPipeline=t.ZodBranded=t.BRAND=t.ZodNaN=t.ZodCatch=t.ZodDefault=t.ZodNullable=t.ZodOptional=t.ZodTransformer=t.ZodEffects=t.ZodPromise=t.ZodNativeEnum=t.ZodEnum=t.ZodLiteral=t.ZodLazy=t.ZodFunction=t.ZodSet=t.ZodMap=t.ZodRecord=t.ZodTuple=t.ZodIntersection=t.ZodDiscriminatedUnion=t.ZodUnion=t.ZodObject=t.ZodArray=t.ZodVoid=t.ZodNever=t.ZodUnknown=t.ZodAny=t.ZodNull=t.ZodUndefined=t.ZodSymbol=t.ZodDate=t.ZodBoolean=t.ZodBigInt=t.ZodNumber=t.ZodString=t.ZodType=void 0,t.NEVER=t.void=t.unknown=t.union=t.undefined=t.tuple=t.transformer=t.symbol=t.string=t.strictObject=t.set=t.record=t.promise=t.preprocess=t.pipeline=t.ostring=t.optional=t.onumber=t.oboolean=t.object=t.number=t.nullable=t.null=t.never=t.nativeEnum=t.nan=t.map=t.literal=t.lazy=t.intersection=t.instanceof=t.function=t.enum=t.effect=void 0,t.datetimeRegex=O,t.custom=Ee;const a=r(68820),s=r(80630),i=r(55957),n=r(70926),o=r(27165);class d{constructor(e,t,r,a){this._cachedPath=[],this.parent=e,this.data=t,this._path=r,this._key=a}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}}const c=(e,t)=>{if((0,n.isValid)(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;const t=new a.ZodError(e.common.issues);return this._error=t,this._error}}};function u(e){if(!e)return{};const{errorMap:t,invalid_type_error:r,required_error:a,description:s}=e;if(t&&(r||a))throw new Error('Can\'t use "invalid_type_error" or "required_error" in conjunction with custom error map.');return t?{errorMap:t,description:s}:{errorMap:(t,s)=>{const{message:i}=e;return"invalid_enum_value"===t.code?{message:i??s.defaultError}:void 0===s.data?{message:i??a??s.defaultError}:"invalid_type"!==t.code?{message:s.defaultError}:{message:i??r??s.defaultError}},description:s}}class l{get description(){return this._def.description}_getType(e){return(0,o.getParsedType)(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:(0,o.getParsedType)(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new n.ParseStatus,ctx:{common:e.parent.common,data:e.data,parsedType:(0,o.getParsedType)(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const t=this._parse(e);if((0,n.isAsync)(t))throw new Error("Synchronous parse encountered promise.");return t}_parseAsync(e){const t=this._parse(e);return Promise.resolve(t)}parse(e,t){const r=this.safeParse(e,t);if(r.success)return r.data;throw r.error}safeParse(e,t){const r={common:{issues:[],async:t?.async??!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:(0,o.getParsedType)(e)},a=this._parseSync({data:e,path:r.path,parent:r});return c(r,a)}"~validate"(e){const t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:(0,o.getParsedType)(e)};if(!this["~standard"].async)try{const r=this._parseSync({data:e,path:[],parent:t});return(0,n.isValid)(r)?{value:r.value}:{issues:t.common.issues}}catch(e){e?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then(e=>(0,n.isValid)(e)?{value:e.value}:{issues:t.common.issues})}async parseAsync(e,t){const r=await this.safeParseAsync(e,t);if(r.success)return r.data;throw r.error}async safeParseAsync(e,t){const r={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:(0,o.getParsedType)(e)},a=this._parse({data:e,path:r.path,parent:r}),s=await((0,n.isAsync)(a)?a:Promise.resolve(a));return c(r,s)}refine(e,t){const r=e=>"string"==typeof t||void 0===t?{message:t}:"function"==typeof t?t(e):t;return this._refinement((t,s)=>{const i=e(t),n=()=>s.addIssue({code:a.ZodIssueCode.custom,...r(t)});return"undefined"!=typeof Promise&&i instanceof Promise?i.then(e=>!!e||(n(),!1)):!!i||(n(),!1)})}refinement(e,t){return this._refinement((r,a)=>!!e(r)||(a.addIssue("function"==typeof t?t(r,a):t),!1))}_refinement(e){return new pe({schema:this,typeName:xe.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:e=>this["~validate"](e)}}optional(){return fe.create(this,this._def)}nullable(){return me.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Q.create(this)}promise(){return he.create(this,this._def)}or(e){return G.create([this,e],this._def)}and(e){return te.create(this,e,this._def)}transform(e){return new pe({...u(this._def),schema:this,typeName:xe.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const t="function"==typeof e?e:()=>e;return new ve({...u(this._def),innerType:this,defaultValue:t,typeName:xe.ZodDefault})}brand(){return new _e({typeName:xe.ZodBranded,type:this,...u(this._def)})}catch(e){const t="function"==typeof e?e:()=>e;return new ye({...u(this._def),innerType:this,catchValue:t,typeName:xe.ZodCatch})}describe(e){return new(0,this.constructor)({...this._def,description:e})}pipe(e){return be.create(this,e)}readonly(){return we.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}t.ZodType=l,t.Schema=l,t.ZodSchema=l;const h=/^c[^\s-]{8,}$/i,p=/^[0-9a-z]+$/,f=/^[0-9A-HJKMNP-TV-Z]{26}$/i,m=/^[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,v=/^[a-z0-9_-]{21}$/i,y=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,g=/^[-+]?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)?)??$/,_=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;let b;const w=/^(?:(?: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])$/,P=/^(?:(?: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])$/,E=/^(([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]))$/,x=/^(([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])$/,S=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,I=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,k="((\\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])))",T=new RegExp(`^${k}$`);function C(e){let t="[0-5]\\d";return e.precision?t=`${t}\\.\\d{${e.precision}}`:null==e.precision&&(t=`${t}(\\.\\d+)?`),`([01]\\d|2[0-3]):[0-5]\\d(:${t})${e.precision?"+":"?"}`}function A(e){return new RegExp(`^${C(e)}$`)}function O(e){let t=`${k}T${C(e)}`;const r=[];return r.push(e.local?"Z?":"Z"),e.offset&&r.push("([+-]\\d{2}:?\\d{2})"),t=`${t}(${r.join("|")})`,new RegExp(`^${t}$`)}function R(e,t){return!("v4"!==t&&t||!w.test(e))||!("v6"!==t&&t||!E.test(e))}function D(e,t){if(!y.test(e))return!1;try{const[r]=e.split(".");if(!r)return!1;const a=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.length%4)%4,"="),s=JSON.parse(atob(a));return!("object"!=typeof s||null===s||"typ"in s&&"JWT"!==s?.typ||!s.alg||t&&s.alg!==t)}catch{return!1}}function N(e,t){return!("v4"!==t&&t||!P.test(e))||!("v6"!==t&&t||!x.test(e))}class Z extends l{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==o.ZodParsedType.string){const t=this._getOrReturnCtx(e);return(0,n.addIssueToContext)(t,{code:a.ZodIssueCode.invalid_type,expected:o.ZodParsedType.string,received:t.parsedType}),n.INVALID}const t=new n.ParseStatus;let r;for(const s of this._def.checks)if("min"===s.kind)e.data.length<s.value&&(r=this._getOrReturnCtx(e,r),(0,n.addIssueToContext)(r,{code:a.ZodIssueCode.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),t.dirty());else if("max"===s.kind)e.data.length>s.value&&(r=this._getOrReturnCtx(e,r),(0,n.addIssueToContext)(r,{code:a.ZodIssueCode.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),t.dirty());else if("length"===s.kind){const i=e.data.length>s.value,o=e.data.length<s.value;(i||o)&&(r=this._getOrReturnCtx(e,r),i?(0,n.addIssueToContext)(r,{code:a.ZodIssueCode.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}):o&&(0,n.addIssueToContext)(r,{code:a.ZodIssueCode.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}),t.dirty())}else if("email"===s.kind)_.test(e.data)||(r=this._getOrReturnCtx(e,r),(0,n.addIssueToContext)(r,{validation:"email",code:a.ZodIssueCode.invalid_string,message:s.message}),t.dirty());else if("emoji"===s.kind)b||(b=new RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),b.test(e.data)||(r=this._getOrReturnCtx(e,r),(0,n.addIssueToContext)(r,{validation:"emoji",code:a.ZodIssueCode.invalid_string,message:s.message}),t.dirty());else if("uuid"===s.kind)m.test(e.data)||(r=this._getOrReturnCtx(e,r),(0,n.addIssueToContext)(r,{validation:"uuid",code:a.ZodIssueCode.invalid_string,message:s.message}),t.dirty());else if("nanoid"===s.kind)v.test(e.data)||(r=this._getOrReturnCtx(e,r),(0,n.addIssueToContext)(r,{validation:"nanoid",code:a.ZodIssueCode.invalid_string,message:s.message}),t.dirty());else if("cuid"===s.kind)h.test(e.data)||(r=this._getOrReturnCtx(e,r),(0,n.addIssueToContext)(r,{validation:"cuid",code:a.ZodIssueCode.invalid_string,message:s.message}),t.dirty());else if("cuid2"===s.kind)p.test(e.data)||(r=this._getOrReturnCtx(e,r),(0,n.addIssueToContext)(r,{validation:"cuid2",code:a.ZodIssueCode.invalid_string,message:s.message}),t.dirty());else if("ulid"===s.kind)f.test(e.data)||(r=this._getOrReturnCtx(e,r),(0,n.addIssueToContext)(r,{validation:"ulid",code:a.ZodIssueCode.invalid_string,message:s.message}),t.dirty());else if("url"===s.kind)try{new URL(e.data)}catch{r=this._getOrReturnCtx(e,r),(0,n.addIssueToContext)(r,{validation:"url",code:a.ZodIssueCode.invalid_string,message:s.message}),t.dirty()}else"regex"===s.kind?(s.regex.lastIndex=0,s.regex.test(e.data)||(r=this._getOrReturnCtx(e,r),(0,n.addIssueToContext)(r,{validation:"regex",code:a.ZodIssueCode.invalid_string,message:s.message}),t.dirty())):"trim"===s.kind?e.data=e.data.trim():"includes"===s.kind?e.data.includes(s.value,s.position)||(r=this._getOrReturnCtx(e,r),(0,n.addIssueToContext)(r,{code:a.ZodIssueCode.invalid_string,validation:{includes:s.value,position:s.position},message:s.message}),t.dirty()):"toLowerCase"===s.kind?e.data=e.data.toLowerCase():"toUpperCase"===s.kind?e.data=e.data.toUpperCase():"startsWith"===s.kind?e.data.startsWith(s.value)||(r=this._getOrReturnCtx(e,r),(0,n.addIssueToContext)(r,{code:a.ZodIssueCode.invalid_string,validation:{startsWith:s.value},message:s.message}),t.dirty()):"endsWith"===s.kind?e.data.endsWith(s.value)||(r=this._getOrReturnCtx(e,r),(0,n.addIssueToContext)(r,{code:a.ZodIssueCode.invalid_string,validation:{endsWith:s.value},message:s.message}),t.dirty()):"datetime"===s.kind?O(s).test(e.data)||(r=this._getOrReturnCtx(e,r),(0,n.addIssueToContext)(r,{code:a.ZodIssueCode.invalid_string,validation:"datetime",message:s.message}),t.dirty()):"date"===s.kind?T.test(e.data)||(r=this._getOrReturnCtx(e,r),(0,n.addIssueToContext)(r,{code:a.ZodIssueCode.invalid_string,validation:"date",message:s.message}),t.dirty()):"time"===s.kind?A(s).test(e.data)||(r=this._getOrReturnCtx(e,r),(0,n.addIssueToContext)(r,{code:a.ZodIssueCode.invalid_string,validation:"time",message:s.message}),t.dirty()):"duration"===s.kind?g.test(e.data)||(r=this._getOrReturnCtx(e,r),(0,n.addIssueToContext)(r,{validation:"duration",code:a.ZodIssueCode.invalid_string,message:s.message}),t.dirty()):"ip"===s.kind?R(e.data,s.version)||(r=this._getOrReturnCtx(e,r),(0,n.addIssueToContext)(r,{validation:"ip",code:a.ZodIssueCode.invalid_string,message:s.message}),t.dirty()):"jwt"===s.kind?D(e.data,s.alg)||(r=this._getOrReturnCtx(e,r),(0,n.addIssueToContext)(r,{validation:"jwt",code:a.ZodIssueCode.invalid_string,message:s.message}),t.dirty()):"cidr"===s.kind?N(e.data,s.version)||(r=this._getOrReturnCtx(e,r),(0,n.addIssueToContext)(r,{validation:"cidr",code:a.ZodIssueCode.invalid_string,message:s.message}),t.dirty()):"base64"===s.kind?S.test(e.data)||(r=this._getOrReturnCtx(e,r),(0,n.addIssueToContext)(r,{validation:"base64",code:a.ZodIssueCode.invalid_string,message:s.message}),t.dirty()):"base64url"===s.kind?I.test(e.data)||(r=this._getOrReturnCtx(e,r),(0,n.addIssueToContext)(r,{validation:"base64url",code:a.ZodIssueCode.invalid_string,message:s.message}),t.dirty()):o.util.assertNever(s);return{status:t.value,value:e.data}}_regex(e,t,r){return this.refinement(t=>e.test(t),{validation:t,code:a.ZodIssueCode.invalid_string,...i.errorUtil.errToObj(r)})}_addCheck(e){return new Z({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...i.errorUtil.errToObj(e)})}url(e){return this._addCheck({kind:"url",...i.errorUtil.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...i.errorUtil.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...i.errorUtil.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...i.errorUtil.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...i.errorUtil.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...i.errorUtil.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...i.errorUtil.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...i.errorUtil.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...i.errorUtil.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...i.errorUtil.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...i.errorUtil.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...i.errorUtil.errToObj(e)})}datetime(e){return"string"==typeof e?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:void 0===e?.precision?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...i.errorUtil.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return"string"==typeof e?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:void 0===e?.precision?null:e?.precision,...i.errorUtil.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...i.errorUtil.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...i.errorUtil.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t?.position,...i.errorUtil.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...i.errorUtil.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...i.errorUtil.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...i.errorUtil.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...i.errorUtil.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...i.errorUtil.errToObj(t)})}nonempty(e){return this.min(1,i.errorUtil.errToObj(e))}trim(){return new Z({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new Z({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new Z({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>"datetime"===e.kind)}get isDate(){return!!this._def.checks.find(e=>"date"===e.kind)}get isTime(){return!!this._def.checks.find(e=>"time"===e.kind)}get isDuration(){return!!this._def.checks.find(e=>"duration"===e.kind)}get isEmail(){return!!this._def.checks.find(e=>"email"===e.kind)}get isURL(){return!!this._def.checks.find(e=>"url"===e.kind)}get isEmoji(){return!!this._def.checks.find(e=>"emoji"===e.kind)}get isUUID(){return!!this._def.checks.find(e=>"uuid"===e.kind)}get isNANOID(){return!!this._def.checks.find(e=>"nanoid"===e.kind)}get isCUID(){return!!this._def.checks.find(e=>"cuid"===e.kind)}get isCUID2(){return!!this._def.checks.find(e=>"cuid2"===e.kind)}get isULID(){return!!this._def.checks.find(e=>"ulid"===e.kind)}get isIP(){return!!this._def.checks.find(e=>"ip"===e.kind)}get isCIDR(){return!!this._def.checks.find(e=>"cidr"===e.kind)}get isBase64(){return!!this._def.checks.find(e=>"base64"===e.kind)}get isBase64url(){return!!this._def.checks.find(e=>"base64url"===e.kind)}get minLength(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}}function $(e,t){const r=(e.toString().split(".")[1]||"").length,a=(t.toString().split(".")[1]||"").length,s=r>a?r:a;return Number.parseInt(e.toFixed(s).replace(".",""))%Number.parseInt(t.toFixed(s).replace(".",""))/10**s}t.ZodString=Z,Z.create=e=>new Z({checks:[],typeName:xe.ZodString,coerce:e?.coerce??!1,...u(e)});class j extends l{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==o.ZodParsedType.number){const t=this._getOrReturnCtx(e);return(0,n.addIssueToContext)(t,{code:a.ZodIssueCode.invalid_type,expected:o.ZodParsedType.number,received:t.parsedType}),n.INVALID}let t;const r=new n.ParseStatus;for(const s of this._def.checks)"int"===s.kind?o.util.isInteger(e.data)||(t=this._getOrReturnCtx(e,t),(0,n.addIssueToContext)(t,{code:a.ZodIssueCode.invalid_type,expected:"integer",received:"float",message:s.message}),r.dirty()):"min"===s.kind?(s.inclusive?e.data<s.value:e.data<=s.value)&&(t=this._getOrReturnCtx(e,t),(0,n.addIssueToContext)(t,{code:a.ZodIssueCode.too_small,minimum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),r.dirty()):"max"===s.kind?(s.inclusive?e.data>s.value:e.data>=s.value)&&(t=this._getOrReturnCtx(e,t),(0,n.addIssueToContext)(t,{code:a.ZodIssueCode.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),r.dirty()):"multipleOf"===s.kind?0!==$(e.data,s.value)&&(t=this._getOrReturnCtx(e,t),(0,n.addIssueToContext)(t,{code:a.ZodIssueCode.not_multiple_of,multipleOf:s.value,message:s.message}),r.dirty()):"finite"===s.kind?Number.isFinite(e.data)||(t=this._getOrReturnCtx(e,t),(0,n.addIssueToContext)(t,{code:a.ZodIssueCode.not_finite,message:s.message}),r.dirty()):o.util.assertNever(s);return{status:r.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,i.errorUtil.toString(t))}gt(e,t){return this.setLimit("min",e,!1,i.errorUtil.toString(t))}lte(e,t){return this.setLimit("max",e,!0,i.errorUtil.toString(t))}lt(e,t){return this.setLimit("max",e,!1,i.errorUtil.toString(t))}setLimit(e,t,r,a){return new j({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:i.errorUtil.toString(a)}]})}_addCheck(e){return new j({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:i.errorUtil.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:i.errorUtil.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:i.errorUtil.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:i.errorUtil.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:i.errorUtil.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:i.errorUtil.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:i.errorUtil.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:i.errorUtil.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:i.errorUtil.toString(e)})}get minValue(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find(e=>"int"===e.kind||"multipleOf"===e.kind&&o.util.isInteger(e.value))}get isFinite(){let e=null,t=null;for(const r of this._def.checks){if("finite"===r.kind||"int"===r.kind||"multipleOf"===r.kind)return!0;"min"===r.kind?(null===t||r.value>t)&&(t=r.value):"max"===r.kind&&(null===e||r.value<e)&&(e=r.value)}return Number.isFinite(t)&&Number.isFinite(e)}}t.ZodNumber=j,j.create=e=>new j({checks:[],typeName:xe.ZodNumber,coerce:e?.coerce||!1,...u(e)});class F extends l{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==o.ZodParsedType.bigint)return this._getInvalidInput(e);let t;const r=new n.ParseStatus;for(const s of this._def.checks)"min"===s.kind?(s.inclusive?e.data<s.value:e.data<=s.value)&&(t=this._getOrReturnCtx(e,t),(0,n.addIssueToContext)(t,{code:a.ZodIssueCode.too_small,type:"bigint",minimum:s.value,inclusive:s.inclusive,message:s.message}),r.dirty()):"max"===s.kind?(s.inclusive?e.data>s.value:e.data>=s.value)&&(t=this._getOrReturnCtx(e,t),(0,n.addIssueToContext)(t,{code:a.ZodIssueCode.too_big,type:"bigint",maximum:s.value,inclusive:s.inclusive,message:s.message}),r.dirty()):"multipleOf"===s.kind?e.data%s.value!==BigInt(0)&&(t=this._getOrReturnCtx(e,t),(0,n.addIssueToContext)(t,{code:a.ZodIssueCode.not_multiple_of,multipleOf:s.value,message:s.message}),r.dirty()):o.util.assertNever(s);return{status:r.value,value:e.data}}_getInvalidInput(e){const t=this._getOrReturnCtx(e);return(0,n.addIssueToContext)(t,{code:a.ZodIssueCode.invalid_type,expected:o.ZodParsedType.bigint,received:t.parsedType}),n.INVALID}gte(e,t){return this.setLimit("min",e,!0,i.errorUtil.toString(t))}gt(e,t){return this.setLimit("min",e,!1,i.errorUtil.toString(t))}lte(e,t){return this.setLimit("max",e,!0,i.errorUtil.toString(t))}lt(e,t){return this.setLimit("max",e,!1,i.errorUtil.toString(t))}setLimit(e,t,r,a){return new F({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:i.errorUtil.toString(a)}]})}_addCheck(e){return new F({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:i.errorUtil.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:i.errorUtil.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:i.errorUtil.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:i.errorUtil.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:i.errorUtil.toString(t)})}get minValue(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}}t.ZodBigInt=F,F.create=e=>new F({checks:[],typeName:xe.ZodBigInt,coerce:e?.coerce??!1,...u(e)});class M extends l{_parse(e){if(this._def.coerce&&(e.data=Boolean(e.data)),this._getType(e)!==o.ZodParsedType.boolean){const t=this._getOrReturnCtx(e);return(0,n.addIssueToContext)(t,{code:a.ZodIssueCode.invalid_type,expected:o.ZodParsedType.boolean,received:t.parsedType}),n.INVALID}return(0,n.OK)(e.data)}}t.ZodBoolean=M,M.create=e=>new M({typeName:xe.ZodBoolean,coerce:e?.coerce||!1,...u(e)});class L extends l{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==o.ZodParsedType.date){const t=this._getOrReturnCtx(e);return(0,n.addIssueToContext)(t,{code:a.ZodIssueCode.invalid_type,expected:o.ZodParsedType.date,received:t.parsedType}),n.INVALID}if(Number.isNaN(e.data.getTime())){const t=this._getOrReturnCtx(e);return(0,n.addIssueToContext)(t,{code:a.ZodIssueCode.invalid_date}),n.INVALID}const t=new n.ParseStatus;let r;for(const s of this._def.checks)"min"===s.kind?e.data.getTime()<s.value&&(r=this._getOrReturnCtx(e,r),(0,n.addIssueToContext)(r,{code:a.ZodIssueCode.too_small,message:s.message,inclusive:!0,exact:!1,minimum:s.value,type:"date"}),t.dirty()):"max"===s.kind?e.data.getTime()>s.value&&(r=this._getOrReturnCtx(e,r),(0,n.addIssueToContext)(r,{code:a.ZodIssueCode.too_big,message:s.message,inclusive:!0,exact:!1,maximum:s.value,type:"date"}),t.dirty()):o.util.assertNever(s);return{status:t.value,value:new Date(e.data.getTime())}}_addCheck(e){return new L({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:i.errorUtil.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:i.errorUtil.toString(t)})}get minDate(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return null!=e?new Date(e):null}get maxDate(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return null!=e?new Date(e):null}}t.ZodDate=L,L.create=e=>new L({checks:[],coerce:e?.coerce||!1,typeName:xe.ZodDate,...u(e)});class z extends l{_parse(e){if(this._getType(e)!==o.ZodParsedType.symbol){const t=this._getOrReturnCtx(e);return(0,n.addIssueToContext)(t,{code:a.ZodIssueCode.invalid_type,expected:o.ZodParsedType.symbol,received:t.parsedType}),n.INVALID}return(0,n.OK)(e.data)}}t.ZodSymbol=z,z.create=e=>new z({typeName:xe.ZodSymbol,...u(e)});class V extends l{_parse(e){if(this._getType(e)!==o.ZodParsedType.undefined){const t=this._getOrReturnCtx(e);return(0,n.addIssueToContext)(t,{code:a.ZodIssueCode.invalid_type,expected:o.ZodParsedType.undefined,received:t.parsedType}),n.INVALID}return(0,n.OK)(e.data)}}t.ZodUndefined=V,V.create=e=>new V({typeName:xe.ZodUndefined,...u(e)});class q extends l{_parse(e){if(this._getType(e)!==o.ZodParsedType.null){const t=this._getOrReturnCtx(e);return(0,n.addIssueToContext)(t,{code:a.ZodIssueCode.invalid_type,expected:o.ZodParsedType.null,received:t.parsedType}),n.INVALID}return(0,n.OK)(e.data)}}t.ZodNull=q,q.create=e=>new q({typeName:xe.ZodNull,...u(e)});class U extends l{constructor(){super(...arguments),this._any=!0}_parse(e){return(0,n.OK)(e.data)}}t.ZodAny=U,U.create=e=>new U({typeName:xe.ZodAny,...u(e)});class K extends l{constructor(){super(...arguments),this._unknown=!0}_parse(e){return(0,n.OK)(e.data)}}t.ZodUnknown=K,K.create=e=>new K({typeName:xe.ZodUnknown,...u(e)});class H extends l{_parse(e){const t=this._getOrReturnCtx(e);return(0,n.addIssueToContext)(t,{code:a.ZodIssueCode.invalid_type,expected:o.ZodParsedType.never,received:t.parsedType}),n.INVALID}}t.ZodNever=H,H.create=e=>new H({typeName:xe.ZodNever,...u(e)});class B extends l{_parse(e){if(this._getType(e)!==o.ZodParsedType.undefined){const t=this._getOrReturnCtx(e);return(0,n.addIssueToContext)(t,{code:a.ZodIssueCode.invalid_type,expected:o.ZodParsedType.void,received:t.parsedType}),n.INVALID}return(0,n.OK)(e.data)}}t.ZodVoid=B,B.create=e=>new B({typeName:xe.ZodVoid,...u(e)});class Q extends l{_parse(e){const{ctx:t,status:r}=this._processInputParams(e),s=this._def;if(t.parsedType!==o.ZodParsedType.array)return(0,n.addIssueToContext)(t,{code:a.ZodIssueCode.invalid_type,expected:o.ZodParsedType.array,received:t.parsedType}),n.INVALID;if(null!==s.exactLength){const e=t.data.length>s.exactLength.value,i=t.data.length<s.exactLength.value;(e||i)&&((0,n.addIssueToContext)(t,{code:e?a.ZodIssueCode.too_big:a.ZodIssueCode.too_small,minimum:i?s.exactLength.value:void 0,maximum:e?s.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:s.exactLength.message}),r.dirty())}if(null!==s.minLength&&t.data.length<s.minLength.value&&((0,n.addIssueToContext)(t,{code:a.ZodIssueCode.too_small,minimum:s.minLength.value,type:"array",inclusive:!0,exact:!1,message:s.minLength.message}),r.dirty()),null!==s.maxLength&&t.data.length>s.maxLength.value&&((0,n.addIssueToContext)(t,{code:a.ZodIssueCode.too_big,maximum:s.maxLength.value,type:"array",inclusive:!0,exact:!1,message:s.maxLength.message}),r.dirty()),t.common.async)return Promise.all([...t.data].map((e,r)=>s.type._parseAsync(new d(t,e,t.path,r)))).then(e=>n.ParseStatus.mergeArray(r,e));const i=[...t.data].map((e,r)=>s.type._parseSync(new d(t,e,t.path,r)));return n.ParseStatus.mergeArray(r,i)}get element(){return this._def.type}min(e,t){return new Q({...this._def,minLength:{value:e,message:i.errorUtil.toString(t)}})}max(e,t){return new Q({...this._def,maxLength:{value:e,message:i.errorUtil.toString(t)}})}length(e,t){return new Q({...this._def,exactLength:{value:e,message:i.errorUtil.toString(t)}})}nonempty(e){return this.min(1,e)}}function J(e){if(e instanceof W){const t={};for(const r in e.shape){const a=e.shape[r];t[r]=fe.create(J(a))}return new W({...e._def,shape:()=>t})}return e instanceof Q?new Q({...e._def,type:J(e.element)}):e instanceof fe?fe.create(J(e.unwrap())):e instanceof me?me.create(J(e.unwrap())):e instanceof re?re.create(e.items.map(e=>J(e))):e}t.ZodArray=Q,Q.create=(e,t)=>new Q({type:e,minLength:null,maxLength:null,exactLength:null,typeName:xe.ZodArray,...u(t)});class W extends l{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(null!==this._cached)return this._cached;const e=this._def.shape(),t=o.util.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==o.ZodParsedType.object){const t=this._getOrReturnCtx(e);return(0,n.addIssueToContext)(t,{code:a.ZodIssueCode.invalid_type,expected:o.ZodParsedType.object,received:t.parsedType}),n.INVALID}const{status:t,ctx:r}=this._processInputParams(e),{shape:s,keys:i}=this._getCached(),c=[];if(!(this._def.catchall instanceof H&&"strip"===this._def.unknownKeys))for(const e in r.data)i.includes(e)||c.push(e);const u=[];for(const e of i){const t=s[e],a=r.data[e];u.push({key:{status:"valid",value:e},value:t._parse(new d(r,a,r.path,e)),alwaysSet:e in r.data})}if(this._def.catchall instanceof H){const e=this._def.unknownKeys;if("passthrough"===e)for(const e of c)u.push({key:{status:"valid",value:e},value:{status:"valid",value:r.data[e]}});else if("strict"===e)c.length>0&&((0,n.addIssueToContext)(r,{code:a.ZodIssueCode.unrecognized_keys,keys:c}),t.dirty());else if("strip"!==e)throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const e=this._def.catchall;for(const t of c){const a=r.data[t];u.push({key:{status:"valid",value:t},value:e._parse(new d(r,a,r.path,t)),alwaysSet:t in r.data})}}return r.common.async?Promise.resolve().then(async()=>{const e=[];for(const t of u){const r=await t.key,a=await t.value;e.push({key:r,value:a,alwaysSet:t.alwaysSet})}return e}).then(e=>n.ParseStatus.mergeObjectSync(t,e)):n.ParseStatus.mergeObjectSync(t,u)}get shape(){return this._def.shape()}strict(e){return i.errorUtil.errToObj,new W({...this._def,unknownKeys:"strict",...void 0!==e?{errorMap:(t,r)=>{const a=this._def.errorMap?.(t,r).message??r.defaultError;return"unrecognized_keys"===t.code?{message:i.errorUtil.errToObj(e).message??a}:{message:a}}}:{}})}strip(){return new W({...this._def,unknownKeys:"strip"})}passthrough(){return new W({...this._def,unknownKeys:"passthrough"})}extend(e){return new W({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new W({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:xe.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new W({...this._def,catchall:e})}pick(e){const t={};for(const r of o.util.objectKeys(e))e[r]&&this.shape[r]&&(t[r]=this.shape[r]);return new W({...this._def,shape:()=>t})}omit(e){const t={};for(const r of o.util.objectKeys(this.shape))e[r]||(t[r]=this.shape[r]);return new W({...this._def,shape:()=>t})}deepPartial(){return J(this)}partial(e){const t={};for(const r of o.util.objectKeys(this.shape)){const a=this.shape[r];e&&!e[r]?t[r]=a:t[r]=a.optional()}return new W({...this._def,shape:()=>t})}required(e){const t={};for(const r of o.util.objectKeys(this.shape))if(e&&!e[r])t[r]=this.shape[r];else{let e=this.shape[r];for(;e instanceof fe;)e=e._def.innerType;t[r]=e}return new W({...this._def,shape:()=>t})}keyof(){return ce(o.util.objectKeys(this.shape))}}t.ZodObject=W,W.create=(e,t)=>new W({shape:()=>e,unknownKeys:"strip",catchall:H.create(),typeName:xe.ZodObject,...u(t)}),W.strictCreate=(e,t)=>new W({shape:()=>e,unknownKeys:"strict",catchall:H.create(),typeName:xe.ZodObject,...u(t)}),W.lazycreate=(e,t)=>new W({shape:e,unknownKeys:"strip",catchall:H.create(),typeName:xe.ZodObject,...u(t)});class G extends l{_parse(e){const{ctx:t}=this._processInputParams(e),r=this._def.options;if(t.common.async)return Promise.all(r.map(async e=>{const r={...t,common:{...t.common,issues:[]},parent:null};return{result:await e._parseAsync({data:t.data,path:t.path,parent:r}),ctx:r}})).then(function(e){for(const t of e)if("valid"===t.result.status)return t.result;for(const r of e)if("dirty"===r.result.status)return t.common.issues.push(...r.ctx.common.issues),r.result;const r=e.map(e=>new a.ZodError(e.ctx.common.issues));return(0,n.addIssueToContext)(t,{code:a.ZodIssueCode.invalid_union,unionErrors:r}),n.INVALID});{let e;const s=[];for(const a of r){const r={...t,common:{...t.common,issues:[]},parent:null},i=a._parseSync({data:t.data,path:t.path,parent:r});if("valid"===i.status)return i;"dirty"!==i.status||e||(e={result:i,ctx:r}),r.common.issues.length&&s.push(r.common.issues)}if(e)return t.common.issues.push(...e.ctx.common.issues),e.result;const i=s.map(e=>new a.ZodError(e));return(0,n.addIssueToContext)(t,{code:a.ZodIssueCode.invalid_union,unionErrors:i}),n.INVALID}}get options(){return this._def.options}}t.ZodUnion=G,G.create=(e,t)=>new G({options:e,typeName:xe.ZodUnion,...u(t)});const Y=e=>e instanceof oe?Y(e.schema):e instanceof pe?Y(e.innerType()):e instanceof de?[e.value]:e instanceof ue?e.options:e instanceof le?o.util.objectValues(e.enum):e instanceof ve?Y(e._def.innerType):e instanceof V?[void 0]:e instanceof q?[null]:e instanceof fe?[void 0,...Y(e.unwrap())]:e instanceof me?[null,...Y(e.unwrap())]:e instanceof _e||e instanceof we?Y(e.unwrap()):e instanceof ye?Y(e._def.innerType):[];class X extends l{_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==o.ZodParsedType.object)return(0,n.addIssueToContext)(t,{code:a.ZodIssueCode.invalid_type,expected:o.ZodParsedType.object,received:t.parsedType}),n.INVALID;const r=this.discriminator,s=t.data[r],i=this.optionsMap.get(s);return i?t.common.async?i._parseAsync({data:t.data,path:t.path,parent:t}):i._parseSync({data:t.data,path:t.path,parent:t}):((0,n.addIssueToContext)(t,{code:a.ZodIssueCode.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),n.INVALID)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,t,r){const a=new Map;for(const r of t){const t=Y(r.shape[e]);if(!t.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(const s of t){if(a.has(s))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(s)}`);a.set(s,r)}}return new X({typeName:xe.ZodDiscriminatedUnion,discriminator:e,options:t,optionsMap:a,...u(r)})}}function ee(e,t){const r=(0,o.getParsedType)(e),a=(0,o.getParsedType)(t);if(e===t)return{valid:!0,data:e};if(r===o.ZodParsedType.object&&a===o.ZodParsedType.object){const r=o.util.objectKeys(t),a=o.util.objectKeys(e).filter(e=>-1!==r.indexOf(e)),s={...e,...t};for(const r of a){const a=ee(e[r],t[r]);if(!a.valid)return{valid:!1};s[r]=a.data}return{valid:!0,data:s}}if(r===o.ZodParsedType.array&&a===o.ZodParsedType.array){if(e.length!==t.length)return{valid:!1};const r=[];for(let a=0;a<e.length;a++){const s=ee(e[a],t[a]);if(!s.valid)return{valid:!1};r.push(s.data)}return{valid:!0,data:r}}return r===o.ZodParsedType.date&&a===o.ZodParsedType.date&&+e===+t?{valid:!0,data:e}:{valid:!1}}t.ZodDiscriminatedUnion=X;class te extends l{_parse(e){const{status:t,ctx:r}=this._processInputParams(e),s=(e,s)=>{if((0,n.isAborted)(e)||(0,n.isAborted)(s))return n.INVALID;const i=ee(e.value,s.value);return i.valid?(((0,n.isDirty)(e)||(0,n.isDirty)(s))&&t.dirty(),{status:t.value,value:i.data}):((0,n.addIssueToContext)(r,{code:a.ZodIssueCode.invalid_intersection_types}),n.INVALID)};return r.common.async?Promise.all([this._def.left._parseAsync({data:r.data,path:r.path,parent:r}),this._def.right._parseAsync({data:r.data,path:r.path,parent:r})]).then(([e,t])=>s(e,t)):s(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}}t.ZodIntersection=te,te.create=(e,t,r)=>new te({left:e,right:t,typeName:xe.ZodIntersection,...u(r)});class re extends l{_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==o.ZodParsedType.array)return(0,n.addIssueToContext)(r,{code:a.ZodIssueCode.invalid_type,expected:o.ZodParsedType.array,received:r.parsedType}),n.INVALID;if(r.data.length<this._def.items.length)return(0,n.addIssueToContext)(r,{code:a.ZodIssueCode.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),n.INVALID;!this._def.rest&&r.data.length>this._def.items.length&&((0,n.addIssueToContext)(r,{code:a.ZodIssueCode.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());const s=[...r.data].map((e,t)=>{const a=this._def.items[t]||this._def.rest;return a?a._parse(new d(r,e,r.path,t)):null}).filter(e=>!!e);return r.common.async?Promise.all(s).then(e=>n.ParseStatus.mergeArray(t,e)):n.ParseStatus.mergeArray(t,s)}get items(){return this._def.items}rest(e){return new re({...this._def,rest:e})}}t.ZodTuple=re,re.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new re({items:e,typeName:xe.ZodTuple,rest:null,...u(t)})};class ae extends l{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==o.ZodParsedType.object)return(0,n.addIssueToContext)(r,{code:a.ZodIssueCode.invalid_type,expected:o.ZodParsedType.object,received:r.parsedType}),n.INVALID;const s=[],i=this._def.keyType,c=this._def.valueType;for(const e in r.data)s.push({key:i._parse(new d(r,e,r.path,e)),value:c._parse(new d(r,r.data[e],r.path,e)),alwaysSet:e in r.data});return r.common.async?n.ParseStatus.mergeObjectAsync(t,s):n.ParseStatus.mergeObjectSync(t,s)}get element(){return this._def.valueType}static create(e,t,r){return new ae(t instanceof l?{keyType:e,valueType:t,typeName:xe.ZodRecord,...u(r)}:{keyType:Z.create(),valueType:e,typeName:xe.ZodRecord,...u(t)})}}t.ZodRecord=ae;class se extends l{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==o.ZodParsedType.map)return(0,n.addIssueToContext)(r,{code:a.ZodIssueCode.invalid_type,expected:o.ZodParsedType.map,received:r.parsedType}),n.INVALID;const s=this._def.keyType,i=this._def.valueType,c=[...r.data.entries()].map(([e,t],a)=>({key:s._parse(new d(r,e,r.path,[a,"key"])),value:i._parse(new d(r,t,r.path,[a,"value"]))}));if(r.common.async){const e=new Map;return Promise.resolve().then(async()=>{for(const r of c){const a=await r.key,s=await r.value;if("aborted"===a.status||"aborted"===s.status)return n.INVALID;"dirty"!==a.status&&"dirty"!==s.status||t.dirty(),e.set(a.value,s.value)}return{status:t.value,value:e}})}{const e=new Map;for(const r of c){const a=r.key,s=r.value;if("aborted"===a.status||"aborted"===s.status)return n.INVALID;"dirty"!==a.status&&"dirty"!==s.status||t.dirty(),e.set(a.value,s.value)}return{status:t.value,value:e}}}}t.ZodMap=se,se.create=(e,t,r)=>new se({valueType:t,keyType:e,typeName:xe.ZodMap,...u(r)});class ie extends l{_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==o.ZodParsedType.set)return(0,n.addIssueToContext)(r,{code:a.ZodIssueCode.invalid_type,expected:o.ZodParsedType.set,received:r.parsedType}),n.INVALID;const s=this._def;null!==s.minSize&&r.data.size<s.minSize.value&&((0,n.addIssueToContext)(r,{code:a.ZodIssueCode.too_small,minimum:s.minSize.value,type:"set",inclusive:!0,exact:!1,message:s.minSize.message}),t.dirty()),null!==s.maxSize&&r.data.size>s.maxSize.value&&((0,n.addIssueToContext)(r,{code:a.ZodIssueCode.too_big,maximum:s.maxSize.value,type:"set",inclusive:!0,exact:!1,message:s.maxSize.message}),t.dirty());const i=this._def.valueType;function c(e){const r=new Set;for(const a of e){if("aborted"===a.status)return n.INVALID;"dirty"===a.status&&t.dirty(),r.add(a.value)}return{status:t.value,value:r}}const u=[...r.data.values()].map((e,t)=>i._parse(new d(r,e,r.path,t)));return r.common.async?Promise.all(u).then(e=>c(e)):c(u)}min(e,t){return new ie({...this._def,minSize:{value:e,message:i.errorUtil.toString(t)}})}max(e,t){return new ie({...this._def,maxSize:{value:e,message:i.errorUtil.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}}t.ZodSet=ie,ie.create=(e,t)=>new ie({valueType:e,minSize:null,maxSize:null,typeName:xe.ZodSet,...u(t)});class ne extends l{constructor(){super(...arguments),this.validate=this.implement}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==o.ZodParsedType.function)return(0,n.addIssueToContext)(t,{code:a.ZodIssueCode.invalid_type,expected:o.ZodParsedType.function,received:t.parsedType}),n.INVALID;function r(e,r){return(0,n.makeIssue)({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,(0,s.getErrorMap)(),s.defaultErrorMap].filter(e=>!!e),issueData:{code:a.ZodIssueCode.invalid_arguments,argumentsError:r}})}function i(e,r){return(0,n.makeIssue)({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,(0,s.getErrorMap)(),s.defaultErrorMap].filter(e=>!!e),issueData:{code:a.ZodIssueCode.invalid_return_type,returnTypeError:r}})}const d={errorMap:t.common.contextualErrorMap},c=t.data;if(this._def.returns instanceof he){const e=this;return(0,n.OK)(async function(...t){const s=new a.ZodError([]),n=await e._def.args.parseAsync(t,d).catch(e=>{throw s.addIssue(r(t,e)),s}),o=await Reflect.apply(c,this,n);return await e._def.returns._def.type.parseAsync(o,d).catch(e=>{throw s.addIssue(i(o,e)),s})})}{const e=this;return(0,n.OK)(function(...t){const s=e._def.args.safeParse(t,d);if(!s.success)throw new a.ZodError([r(t,s.error)]);const n=Reflect.apply(c,this,s.data),o=e._def.returns.safeParse(n,d);if(!o.success)throw new a.ZodError([i(n,o.error)]);return o.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new ne({...this._def,args:re.create(e).rest(K.create())})}returns(e){return new ne({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,t,r){return new ne({args:e||re.create([]).rest(K.create()),returns:t||K.create(),typeName:xe.ZodFunction,...u(r)})}}t.ZodFunction=ne;class oe extends l{get schema(){return this._def.getter()}_parse(e){const{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}}t.ZodLazy=oe,oe.create=(e,t)=>new oe({getter:e,typeName:xe.ZodLazy,...u(t)});class de extends l{_parse(e){if(e.data!==this._def.value){const t=this._getOrReturnCtx(e);return(0,n.addIssueToContext)(t,{received:t.data,code:a.ZodIssueCode.invalid_literal,expected:this._def.value}),n.INVALID}return{status:"valid",value:e.data}}get value(){return this._def.value}}function ce(e,t){return new ue({values:e,typeName:xe.ZodEnum,...u(t)})}t.ZodLiteral=de,de.create=(e,t)=>new de({value:e,typeName:xe.ZodLiteral,...u(t)});class ue extends l{_parse(e){if("string"!=typeof e.data){const t=this._getOrReturnCtx(e),r=this._def.values;return(0,n.addIssueToContext)(t,{expected:o.util.joinValues(r),received:t.parsedType,code:a.ZodIssueCode.invalid_type}),n.INVALID}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){const t=this._getOrReturnCtx(e),r=this._def.values;return(0,n.addIssueToContext)(t,{received:t.data,code:a.ZodIssueCode.invalid_enum_value,options:r}),n.INVALID}return(0,n.OK)(e.data)}get options(){return this._def.values}get enum(){const e={};for(const t of this._def.values)e[t]=t;return e}get Values(){const e={};for(const t of this._def.values)e[t]=t;return e}get Enum(){const e={};for(const t of this._def.values)e[t]=t;return e}extract(e,t=this._def){return ue.create(e,{...this._def,...t})}exclude(e,t=this._def){return ue.create(this.options.filter(t=>!e.includes(t)),{...this._def,...t})}}t.ZodEnum=ue,ue.create=ce;class le extends l{_parse(e){const t=o.util.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(e);if(r.parsedType!==o.ZodParsedType.string&&r.parsedType!==o.ZodParsedType.number){const e=o.util.objectValues(t);return(0,n.addIssueToContext)(r,{expected:o.util.joinValues(e),received:r.parsedType,code:a.ZodIssueCode.invalid_type}),n.INVALID}if(this._cache||(this._cache=new Set(o.util.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){const e=o.util.objectValues(t);return(0,n.addIssueToContext)(r,{received:r.data,code:a.ZodIssueCode.invalid_enum_value,options:e}),n.INVALID}return(0,n.OK)(e.data)}get enum(){return this._def.values}}t.ZodNativeEnum=le,le.create=(e,t)=>new le({values:e,typeName:xe.ZodNativeEnum,...u(t)});class he extends l{unwrap(){return this._def.type}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==o.ZodParsedType.promise&&!1===t.common.async)return(0,n.addIssueToContext)(t,{code:a.ZodIssueCode.invalid_type,expected:o.ZodParsedType.promise,received:t.parsedType}),n.INVALID;const r=t.parsedType===o.ZodParsedType.promise?t.data:Promise.resolve(t.data);return(0,n.OK)(r.then(e=>this._def.type.parseAsync(e,{path:t.path,errorMap:t.common.contextualErrorMap})))}}t.ZodPromise=he,he.create=(e,t)=>new he({type:e,typeName:xe.ZodPromise,...u(t)});class pe extends l{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===xe.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){const{status:t,ctx:r}=this._processInputParams(e),a=this._def.effect||null,s={addIssue:e=>{(0,n.addIssueToContext)(r,e),e.fatal?t.abort():t.dirty()},get path(){return r.path}};if(s.addIssue=s.addIssue.bind(s),"preprocess"===a.type){const e=a.transform(r.data,s);if(r.common.async)return Promise.resolve(e).then(async e=>{if("aborted"===t.value)return n.INVALID;const a=await this._def.schema._parseAsync({data:e,path:r.path,parent:r});return"aborted"===a.status?n.INVALID:"dirty"===a.status||"dirty"===t.value?(0,n.DIRTY)(a.value):a});{if("aborted"===t.value)return n.INVALID;const a=this._def.schema._parseSync({data:e,path:r.path,parent:r});return"aborted"===a.status?n.INVALID:"dirty"===a.status||"dirty"===t.value?(0,n.DIRTY)(a.value):a}}if("refinement"===a.type){const e=e=>{const t=a.refinement(e,s);if(r.common.async)return Promise.resolve(t);if(t instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return e};if(!1===r.common.async){const a=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return"aborted"===a.status?n.INVALID:("dirty"===a.status&&t.dirty(),e(a.value),{status:t.value,value:a.value})}return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(r=>"aborted"===r.status?n.INVALID:("dirty"===r.status&&t.dirty(),e(r.value).then(()=>({status:t.value,value:r.value}))))}if("transform"===a.type){if(!1===r.common.async){const e=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!(0,n.isValid)(e))return n.INVALID;const i=a.transform(e.value,s);if(i instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:t.value,value:i}}return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(e=>(0,n.isValid)(e)?Promise.resolve(a.transform(e.value,s)).then(e=>({status:t.value,value:e})):n.INVALID)}o.util.assertNever(a)}}t.ZodEffects=pe,t.ZodTransformer=pe,pe.create=(e,t,r)=>new pe({schema:e,typeName:xe.ZodEffects,effect:t,...u(r)}),pe.createWithPreprocess=(e,t,r)=>new pe({schema:t,effect:{type:"preprocess",transform:e},typeName:xe.ZodEffects,...u(r)});class fe extends l{_parse(e){return this._getType(e)===o.ZodParsedType.undefined?(0,n.OK)(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}t.ZodOptional=fe,fe.create=(e,t)=>new fe({innerType:e,typeName:xe.ZodOptional,...u(t)});class me extends l{_parse(e){return this._getType(e)===o.ZodParsedType.null?(0,n.OK)(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}t.ZodNullable=me,me.create=(e,t)=>new me({innerType:e,typeName:xe.ZodNullable,...u(t)});class ve extends l{_parse(e){const{ctx:t}=this._processInputParams(e);let r=t.data;return t.parsedType===o.ZodParsedType.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:t.path,parent:t})}removeDefault(){return this._def.innerType}}t.ZodDefault=ve,ve.create=(e,t)=>new ve({innerType:e,typeName:xe.ZodDefault,defaultValue:"function"==typeof t.default?t.default:()=>t.default,...u(t)});class ye extends l{_parse(e){const{ctx:t}=this._processInputParams(e),r={...t,common:{...t.common,issues:[]}},s=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return(0,n.isAsync)(s)?s.then(e=>({status:"valid",value:"valid"===e.status?e.value:this._def.catchValue({get error(){return new a.ZodError(r.common.issues)},input:r.data})})):{status:"valid",value:"valid"===s.status?s.value:this._def.catchValue({get error(){return new a.ZodError(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}}t.ZodCatch=ye,ye.create=(e,t)=>new ye({innerType:e,typeName:xe.ZodCatch,catchValue:"function"==typeof t.catch?t.catch:()=>t.catch,...u(t)});class ge extends l{_parse(e){if(this._getType(e)!==o.ZodParsedType.nan){const t=this._getOrReturnCtx(e);return(0,n.addIssueToContext)(t,{code:a.ZodIssueCode.invalid_type,expected:o.ZodParsedType.nan,received:t.parsedType}),n.INVALID}return{status:"valid",value:e.data}}}t.ZodNaN=ge,ge.create=e=>new ge({typeName:xe.ZodNaN,...u(e)}),t.BRAND=Symbol("zod_brand");class _e extends l{_parse(e){const{ctx:t}=this._processInputParams(e),r=t.data;return this._def.type._parse({data:r,path:t.path,parent:t})}unwrap(){return this._def.type}}t.ZodBranded=_e;class be extends l{_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.common.async)return(async()=>{const e=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return"aborted"===e.status?n.INVALID:"dirty"===e.status?(t.dirty(),(0,n.DIRTY)(e.value)):this._def.out._parseAsync({data:e.value,path:r.path,parent:r})})();{const e=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return"aborted"===e.status?n.INVALID:"dirty"===e.status?(t.dirty(),{status:"dirty",value:e.value}):this._def.out._parseSync({data:e.value,path:r.path,parent:r})}}static create(e,t){return new be({in:e,out:t,typeName:xe.ZodPipeline})}}t.ZodPipeline=be;class we extends l{_parse(e){const t=this._def.innerType._parse(e),r=e=>((0,n.isValid)(e)&&(e.value=Object.freeze(e.value)),e);return(0,n.isAsync)(t)?t.then(e=>r(e)):r(t)}unwrap(){return this._def.innerType}}function Pe(e,t){const r="function"==typeof e?e(t):"string"==typeof e?{message:e}:e;return"string"==typeof r?{message:r}:r}function Ee(e,t={},r){return e?U.create().superRefine((a,s)=>{const i=e(a);if(i instanceof Promise)return i.then(e=>{if(!e){const e=Pe(t,a),i=e.fatal??r??!0;s.addIssue({code:"custom",...e,fatal:i})}});if(!i){const e=Pe(t,a),i=e.fatal??r??!0;s.addIssue({code:"custom",...e,fatal:i})}}):U.create()}var xe;t.ZodReadonly=we,we.create=(e,t)=>new we({innerType:e,typeName:xe.ZodReadonly,...u(t)}),t.late={object:W.lazycreate},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"}(xe||(t.ZodFirstPartyTypeKind=xe={})),t.instanceof=(e,t={message:`Input not instance of ${e.name}`})=>Ee(t=>t instanceof e,t);const Se=Z.create;t.string=Se;const Ie=j.create;t.number=Ie;const ke=ge.create;t.nan=ke;const Te=F.create;t.bigint=Te;const Ce=M.create;t.boolean=Ce;const Ae=L.create;t.date=Ae;const Oe=z.create;t.symbol=Oe;const Re=V.create;t.undefined=Re;const De=q.create;t.null=De;const Ne=U.create;t.any=Ne;const Ze=K.create;t.unknown=Ze;const $e=H.create;t.never=$e;const je=B.create;t.void=je;const Fe=Q.create;t.array=Fe;const Me=W.create;t.object=Me;const Le=W.strictCreate;t.strictObject=Le;const ze=G.create;t.union=ze;const Ve=X.create;t.discriminatedUnion=Ve;const qe=te.create;t.intersection=qe;const Ue=re.create;t.tuple=Ue;const Ke=ae.create;t.record=Ke;const He=se.create;t.map=He;const Be=ie.create;t.set=Be;const Qe=ne.create;t.function=Qe;const Je=oe.create;t.lazy=Je;const We=de.create;t.literal=We;const Ge=ue.create;t.enum=Ge;const Ye=le.create;t.nativeEnum=Ye;const Xe=he.create;t.promise=Xe;const et=pe.create;t.effect=et,t.transformer=et;const tt=fe.create;t.optional=tt;const rt=me.create;t.nullable=rt;const at=pe.createWithPreprocess;t.preprocess=at;const st=be.create;t.pipeline=st,t.ostring=()=>Se().optional(),t.onumber=()=>Ie().optional(),t.oboolean=()=>Ce().optional(),t.coerce={string:e=>Z.create({...e,coerce:!0}),number:e=>j.create({...e,coerce:!0}),boolean:e=>M.create({...e,coerce:!0}),bigint:e=>F.create({...e,coerce:!0}),date:e=>L.create({...e,coerce:!0})},t.NEVER=n.INVALID},44413:e=>{"use strict";e.exports=function(e,t,r){var a=" ",s=e.schema[t],i=e.errSchemaPath+"/"+t,n=(e.opts.allErrors,e.util.toQuotedString(s));return!0===e.opts.$comment?a+=" console.log("+n+");":"function"==typeof e.opts.$comment&&(a+=" self._opts.$comment("+n+", "+e.util.toQuotedString(i)+", validate.root.schema);"),a}},46079:e=>{"use strict";var t=["multipleOf","maximum","exclusiveMaximum","minimum","exclusiveMinimum","maxLength","minLength","pattern","additionalItems","maxItems","minItems","uniqueItems","maxProperties","minProperties","required","additionalProperties","enum","format","const"];e.exports=function(e,r){for(var a=0;a<r.length;a++){e=JSON.parse(JSON.stringify(e));var s,i=r[a].split("/"),n=e;for(s=1;s<i.length;s++)n=n[i[s]];for(s=0;s<t.length;s++){var o=t[s],d=n[o];d&&(n[o]={anyOf:[d,{$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"}]})}}return e}},46137:e=>{"use strict";e.exports=function(e,t,r){var a=" ",s=e.level,i=e.dataLevel,n=e.schema[t],o=e.schemaPath+e.util.getProperty(t),d=e.errSchemaPath+"/"+t,c=!e.opts.allErrors,u="data"+(i||""),l="valid"+s,h="errs__"+s,p=e.util.copy(e),f="";p.level++;var m="valid"+p.level,v=p.baseId,y="prevValid"+s,g="passingSchemas"+s;a+="var "+h+" = errors , "+y+" = false , "+l+" = false , "+g+" = null; ";var _=e.compositeRule;e.compositeRule=p.compositeRule=!0;var b=n;if(b)for(var w,P=-1,E=b.length-1;P<E;)w=b[P+=1],(e.opts.strictKeywords?"object"==typeof w&&Object.keys(w).length>0||!1===w:e.util.schemaHasRules(w,e.RULES.all))?(p.schema=w,p.schemaPath=o+"["+P+"]",p.errSchemaPath=d+"/"+P,a+=" "+e.validate(p)+" ",p.baseId=v):a+=" var "+m+" = true; ",P&&(a+=" if ("+m+" && "+y+") { "+l+" = false; "+g+" = ["+g+", "+P+"]; } else { ",f+="}"),a+=" if ("+m+") { "+l+" = "+y+" = true; "+g+" = "+P+"; }";return e.compositeRule=p.compositeRule=_,a+=f+"if (!"+l+") { var err = ",!1!==e.createErrors?(a+=" { keyword: 'oneOf' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(d)+" , params: { passingSchemas: "+g+" } ",!1!==e.opts.messages&&(a+=" , message: 'should match exactly one schema in oneOf' "),e.opts.verbose&&(a+=" , schema: validate.schema"+o+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+u+" "),a+=" } "):a+=" {} ",a+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",!e.compositeRule&&c&&(e.async?a+=" throw new ValidationError(vErrors); ":a+=" validate.errors = vErrors; return false; "),a+="} else { errors = "+h+"; if (vErrors !== null) { if ("+h+") vErrors.length = "+h+"; else vErrors = null; }",e.opts.allErrors&&(a+=" } "),a}},49436:e=>{function t(e){return Promise.resolve().then(()=>{var t=new Error("Cannot find module '"+e+"'");throw t.code="MODULE_NOT_FOUND",t})}t.keys=()=>[],t.resolve=t,t.id=49436,e.exports=t},52004:(e,t,r)=>{"use strict";e.exports={$ref:r(12857),allOf:r(67578),anyOf:r(14547),$comment:r(44413),const:r(59087),contains:r(24235),dependencies:r(90083),enum:r(68307),format:r(95545),if:r(82917),items:r(33728),maximum:r(71346),minimum:r(71346),maxItems:r(80536),minItems:r(80536),maxLength:r(83010),minLength:r(83010),maxProperties:r(96111),minProperties:r(96111),multipleOf:r(58047),not:r(13441),oneOf:r(46137),pattern:r(96774),properties:r(86343),propertyNames:r(9931),required:r(91939),uniqueItems:r(57817),validate:r(25572)}},53084:(e,t,r)=>{"use strict";var a=r(22853),s=r(40985),i=r(28565),n=r(20812),o=r(56039),d=r(36885),c=r(20698),u=r(46079),l=r(9717);e.exports=y,y.prototype.validate=function(e,t){var r;if("string"==typeof e){if(!(r=this.getSchema(e)))throw new Error('no schema with key or ref "'+e+'"')}else{var a=this._addSchema(e);r=a.validate||this._compile(a)}var s=r(t);return!0!==r.$async&&(this.errors=r.errors),s},y.prototype.compile=function(e,t){var r=this._addSchema(e,void 0,t);return r.validate||this._compile(r)},y.prototype.addSchema=function(e,t,r,a){if(Array.isArray(e)){for(var i=0;i<e.length;i++)this.addSchema(e[i],void 0,r,a);return this}var n=this._getId(e);if(void 0!==n&&"string"!=typeof n)throw new Error("schema id must be string");return E(this,t=s.normalizeId(t||n)),this._schemas[t]=this._addSchema(e,r,a,!0),this},y.prototype.addMetaSchema=function(e,t,r){return this.addSchema(e,t,r,!0),this},y.prototype.validateSchema=function(e,t){var r,a,s=e.$schema;if(void 0!==s&&"string"!=typeof s)throw new Error("$schema must be a string");if(!(s=s||this._opts.defaultMeta||(r=this,a=r._opts.meta,r._opts.defaultMeta="object"==typeof a?r._getId(a)||a:r.getSchema(f)?f:void 0,r._opts.defaultMeta)))return this.logger.warn("meta-schema not available"),this.errors=null,!0;var i=this.validate(s,e);if(!i&&t){var n="schema is invalid: "+this.errorsText();if("log"!=this._opts.validateSchema)throw new Error(n);this.logger.error(n)}return i},y.prototype.getSchema=function(e){var t=g(this,e);switch(typeof t){case"object":return t.validate||this._compile(t);case"string":return this.getSchema(t);case"undefined":return function(e,t){var r=s.schema.call(e,{schema:{}},t);if(r){var i=r.schema,o=r.root,d=r.baseId,c=a.call(e,i,o,void 0,d);return e._fragments[t]=new n({ref:t,fragment:!0,schema:i,root:o,baseId:d,validate:c}),c}}(this,e)}},y.prototype.removeSchema=function(e){if(e instanceof RegExp)return _(this,this._schemas,e),_(this,this._refs,e),this;switch(typeof e){case"undefined":return _(this,this._schemas),_(this,this._refs),this._cache.clear(),this;case"string":var t=g(this,e);return t&&this._cache.del(t.cacheKey),delete this._schemas[e],delete this._refs[e],this;case"object":var r=this._opts.serialize,a=r?r(e):e;this._cache.del(a);var i=this._getId(e);i&&(i=s.normalizeId(i),delete this._schemas[i],delete this._refs[i])}return this},y.prototype.addFormat=function(e,t){return"string"==typeof t&&(t=new RegExp(t)),this._formats[e]=t,this},y.prototype.errorsText=function(e,t){if(!(e=e||this.errors))return"No errors";for(var r=void 0===(t=t||{}).separator?", ":t.separator,a=void 0===t.dataVar?"data":t.dataVar,s="",i=0;i<e.length;i++){var n=e[i];n&&(s+=a+n.dataPath+" "+n.message+r)}return s.slice(0,-r.length)},y.prototype._addSchema=function(e,t,r,a){if("object"!=typeof e&&"boolean"!=typeof e)throw new Error("schema should be object or boolean");var i=this._opts.serialize,o=i?i(e):e,d=this._cache.get(o);if(d)return d;a=a||!1!==this._opts.addUsedSchema;var c=s.normalizeId(this._getId(e));c&&a&&E(this,c);var u,l=!1!==this._opts.validateSchema&&!t;l&&!(u=c&&c==s.normalizeId(e.$schema))&&this.validateSchema(e,!0);var h=s.ids.call(this,e),p=new n({id:c,schema:e,localRefs:h,cacheKey:o,meta:r});return"#"!=c[0]&&a&&(this._refs[c]=p),this._cache.put(o,p),l&&u&&this.validateSchema(e,!0),p},y.prototype._compile=function(e,t){if(e.compiling)return e.validate=i,i.schema=e.schema,i.errors=null,i.root=t||i,!0===e.schema.$async&&(i.$async=!0),i;var r,s;e.compiling=!0,e.meta&&(r=this._opts,this._opts=this._metaOpts);try{s=a.call(this,e.schema,t,e.localRefs)}catch(t){throw delete e.validate,t}finally{e.compiling=!1,e.meta&&(this._opts=r)}return e.validate=s,e.refs=s.refs,e.refVal=s.refVal,e.root=s.root,s;function i(){var t=e.validate,r=t.apply(this,arguments);return i.errors=t.errors,r}},y.prototype.compileAsync=r(6069);var h=r(43528);y.prototype.addKeyword=h.add,y.prototype.getKeyword=h.get,y.prototype.removeKeyword=h.remove,y.prototype.validateKeyword=h.validate;var p=r(72916);y.ValidationError=p.Validation,y.MissingRefError=p.MissingRef,y.$dataMetaSchema=u;var f="http://json-schema.org/draft-07/schema",m=["removeAdditional","useDefaults","coerceTypes","strictDefaults"],v=["/properties"];function y(e){if(!(this instanceof y))return new y(e);e=this._opts=l.copy(e)||{},function(e){var t=e._opts.logger;if(!1===t)e.logger={log:x,warn:x,error:x};else{if(void 0===t&&(t=console),!("object"==typeof t&&t.log&&t.warn&&t.error))throw new Error("logger must implement log, warn and error methods");e.logger=t}}(this),this._schemas={},this._refs={},this._fragments={},this._formats=d(e.format),this._cache=e.cache||new i,this._loadingSchemas={},this._compilations=[],this.RULES=c(),this._getId=function(e){switch(e.schemaId){case"auto":return P;case"id":return b;default:return w}}(e),e.loopRequired=e.loopRequired||1/0,"property"==e.errorDataPath&&(e._errorDataPathProperty=!0),void 0===e.serialize&&(e.serialize=o),this._metaOpts=function(e){for(var t=l.copy(e._opts),r=0;r<m.length;r++)delete t[m[r]];return t}(this),e.formats&&function(e){for(var t in e._opts.formats){var r=e._opts.formats[t];e.addFormat(t,r)}}(this),e.keywords&&function(e){for(var t in e._opts.keywords){var r=e._opts.keywords[t];e.addKeyword(t,r)}}(this),function(e){var t;if(e._opts.$data&&(t=r(13215),e.addMetaSchema(t,t.$id,!0)),!1!==e._opts.meta){var a=r(12269);e._opts.$data&&(a=u(a,v)),e.addMetaSchema(a,f,!0),e._refs["http://json-schema.org/schema"]=f}}(this),"object"==typeof e.meta&&this.addMetaSchema(e.meta),e.nullable&&this.addKeyword("nullable",{metaSchema:{type:"boolean"}}),function(e){var t=e._opts.schemas;if(t)if(Array.isArray(t))e.addSchema(t);else for(var r in t)e.addSchema(t[r],r)}(this)}function g(e,t){return t=s.normalizeId(t),e._schemas[t]||e._refs[t]||e._fragments[t]}function _(e,t,r){for(var a in t){var s=t[a];s.meta||r&&!r.test(a)||(e._cache.del(s.cacheKey),delete t[a])}}function b(e){return e.$id&&this.logger.warn("schema $id ignored",e.$id),e.id}function w(e){return e.id&&this.logger.warn("schema id ignored",e.id),e.$id}function P(e){if(e.$id&&e.id&&e.$id!=e.id)throw new Error("schema $id is different from id");return e.$id||e.id}function E(e,t){if(e._schemas[t]||e._refs[t])throw new Error('schema with key or id "'+t+'" already exists')}function x(){}},55957:(e,t)=>{"use strict";var r;Object.defineProperty(t,"__esModule",{value:!0}),t.errorUtil=void 0,function(e){e.errToObj=e=>"string"==typeof e?{message:e}:e||{},e.toString=e=>"string"==typeof e?e:e?.message}(r||(t.errorUtil=r={}))},56039:e=>{"use strict";e.exports=function(e,t){t||(t={}),"function"==typeof t&&(t={cmp:t});var r,a="boolean"==typeof t.cycles&&t.cycles,s=t.cmp&&(r=t.cmp,function(e){return function(t,a){var s={key:t,value:e[t]},i={key:a,value:e[a]};return r(s,i)}}),i=[];return function e(t){if(t&&t.toJSON&&"function"==typeof t.toJSON&&(t=t.toJSON()),void 0!==t){if("number"==typeof t)return isFinite(t)?""+t:"null";if("object"!=typeof t)return JSON.stringify(t);var r,n;if(Array.isArray(t)){for(n="[",r=0;r<t.length;r++)r&&(n+=","),n+=e(t[r])||"null";return n+"]"}if(null===t)return"null";if(-1!==i.indexOf(t)){if(a)return JSON.stringify("__cycle__");throw new TypeError("Converting circular structure to JSON")}var o=i.push(t)-1,d=Object.keys(t).sort(s&&s(t));for(n="",r=0;r<d.length;r++){var c=d[r],u=e(t[c]);u&&(n&&(n+=","),n+=JSON.stringify(c)+":"+u)}return i.splice(o,1),"{"+n+"}"}}(e)}},57817:e=>{"use strict";e.exports=function(e,t,r){var a,s=" ",i=e.level,n=e.dataLevel,o=e.schema[t],d=e.schemaPath+e.util.getProperty(t),c=e.errSchemaPath+"/"+t,u=!e.opts.allErrors,l="data"+(n||""),h="valid"+i,p=e.opts.$data&&o&&o.$data;if(p?(s+=" var schema"+i+" = "+e.util.getData(o.$data,n,e.dataPathArr)+"; ",a="schema"+i):a=o,(o||p)&&!1!==e.opts.uniqueItems){p&&(s+=" var "+h+"; if ("+a+" === false || "+a+" === undefined) "+h+" = true; else if (typeof "+a+" != 'boolean') "+h+" = false; else { "),s+=" var i = "+l+".length , "+h+" = true , j; if (i > 1) { ";var f=e.schema.items&&e.schema.items.type,m=Array.isArray(f);if(!f||"object"==f||"array"==f||m&&(f.indexOf("object")>=0||f.indexOf("array")>=0))s+=" outer: for (;i--;) { for (j = i; j--;) { if (equal("+l+"[i], "+l+"[j])) { "+h+" = false; break outer; } } } ";else{s+=" var itemIndices = {}, item; for (;i--;) { var item = "+l+"[i]; ";var v="checkDataType"+(m?"s":"");s+=" if ("+e.util[v](f,"item",e.opts.strictNumbers,!0)+") continue; ",m&&(s+=" if (typeof item == 'string') item = '\"' + item; "),s+=" if (typeof itemIndices[item] == 'number') { "+h+" = false; j = itemIndices[item]; break; } itemIndices[item] = i; } "}s+=" } ",p&&(s+=" } "),s+=" if (!"+h+") { ";var y=y||[];y.push(s),s="",!1!==e.createErrors?(s+=" { keyword: 'uniqueItems' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { i: i, j: j } ",!1!==e.opts.messages&&(s+=" , message: 'should NOT have duplicate items (items ## ' + j + ' and ' + i + ' are identical)' "),e.opts.verbose&&(s+=" , schema: ",s+=p?"validate.schema"+d:""+o,s+=" , parentSchema: validate.schema"+e.schemaPath+" , data: "+l+" "),s+=" } "):s+=" {} ";var g=s;s=y.pop(),!e.compositeRule&&u?e.async?s+=" throw new ValidationError(["+g+"]); ":s+=" validate.errors = ["+g+"]; return false; ":s+=" var err = "+g+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",s+=" } ",u&&(s+=" else { ")}else u&&(s+=" if (true) { ");return s}},58047:e=>{"use strict";e.exports=function(e,t,r){var a,s=" ",i=e.level,n=e.dataLevel,o=e.schema[t],d=e.schemaPath+e.util.getProperty(t),c=e.errSchemaPath+"/"+t,u=!e.opts.allErrors,l="data"+(n||""),h=e.opts.$data&&o&&o.$data;if(h?(s+=" var schema"+i+" = "+e.util.getData(o.$data,n,e.dataPathArr)+"; ",a="schema"+i):a=o,!h&&"number"!=typeof o)throw new Error(t+" must be number");s+="var division"+i+";if (",h&&(s+=" "+a+" !== undefined && ( typeof "+a+" != 'number' || "),s+=" (division"+i+" = "+l+" / "+a+", ",e.opts.multipleOfPrecision?s+=" Math.abs(Math.round(division"+i+") - division"+i+") > 1e-"+e.opts.multipleOfPrecision+" ":s+=" division"+i+" !== parseInt(division"+i+") ",s+=" ) ",h&&(s+=" ) "),s+=" ) { ";var p=p||[];p.push(s),s="",!1!==e.createErrors?(s+=" { keyword: 'multipleOf' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { multipleOf: "+a+" } ",!1!==e.opts.messages&&(s+=" , message: 'should be multiple of ",s+=h?"' + "+a:a+"'"),e.opts.verbose&&(s+=" , schema: ",s+=h?"validate.schema"+d:""+o,s+=" , parentSchema: validate.schema"+e.schemaPath+" , data: "+l+" "),s+=" } "):s+=" {} ";var f=s;return s=p.pop(),!e.compositeRule&&u?e.async?s+=" throw new ValidationError(["+f+"]); ":s+=" validate.errors = ["+f+"]; return false; ":s+=" var err = "+f+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",s+="} ",u&&(s+=" else { "),s}},59087:e=>{"use strict";e.exports=function(e,t,r){var a=" ",s=e.level,i=e.dataLevel,n=e.schema[t],o=e.schemaPath+e.util.getProperty(t),d=e.errSchemaPath+"/"+t,c=!e.opts.allErrors,u="data"+(i||""),l="valid"+s,h=e.opts.$data&&n&&n.$data;h&&(a+=" var schema"+s+" = "+e.util.getData(n.$data,i,e.dataPathArr)+"; "),h||(a+=" var schema"+s+" = validate.schema"+o+";"),a+="var "+l+" = equal("+u+", schema"+s+"); if (!"+l+") { ";var p=p||[];p.push(a),a="",!1!==e.createErrors?(a+=" { keyword: 'const' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(d)+" , params: { allowedValue: schema"+s+" } ",!1!==e.opts.messages&&(a+=" , message: 'should be equal to constant' "),e.opts.verbose&&(a+=" , schema: validate.schema"+o+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+u+" "),a+=" } "):a+=" {} ";var f=a;return a=p.pop(),!e.compositeRule&&c?e.async?a+=" throw new ValidationError(["+f+"]); ":a+=" validate.errors = ["+f+"]; return false; ":a+=" var err = "+f+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",a+=" }",c&&(a+=" else { "),a}},61763:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0})},61812:e=>{"use strict";e.exports=function(e){for(var t,r=0,a=e.length,s=0;s<a;)r++,(t=e.charCodeAt(s++))>=55296&&t<=56319&&s<a&&56320==(64512&(t=e.charCodeAt(s)))&&s++;return r}},67371:e=>{"use strict";e.exports=function e(t,r){if(t===r)return!0;if(t&&r&&"object"==typeof t&&"object"==typeof r){if(t.constructor!==r.constructor)return!1;var a,s,i;if(Array.isArray(t)){if((a=t.length)!=r.length)return!1;for(s=a;0!==s--;)if(!e(t[s],r[s]))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((a=(i=Object.keys(t)).length)!==Object.keys(r).length)return!1;for(s=a;0!==s--;)if(!Object.prototype.hasOwnProperty.call(r,i[s]))return!1;for(s=a;0!==s--;){var n=i[s];if(!e(t[n],r[n]))return!1}return!0}return t!=t&&r!=r}},67578:e=>{"use strict";e.exports=function(e,t,r){var a=" ",s=e.schema[t],i=e.schemaPath+e.util.getProperty(t),n=e.errSchemaPath+"/"+t,o=!e.opts.allErrors,d=e.util.copy(e),c="";d.level++;var u="valid"+d.level,l=d.baseId,h=!0,p=s;if(p)for(var f,m=-1,v=p.length-1;m<v;)f=p[m+=1],(e.opts.strictKeywords?"object"==typeof f&&Object.keys(f).length>0||!1===f:e.util.schemaHasRules(f,e.RULES.all))&&(h=!1,d.schema=f,d.schemaPath=i+"["+m+"]",d.errSchemaPath=n+"/"+m,a+=" "+e.validate(d)+" ",d.baseId=l,o&&(a+=" if ("+u+") { ",c+="}"));return o&&(a+=h?" if (true) { ":" "+c.slice(0,-1)+" "),a}},68307:e=>{"use strict";e.exports=function(e,t,r){var a=" ",s=e.level,i=e.dataLevel,n=e.schema[t],o=e.schemaPath+e.util.getProperty(t),d=e.errSchemaPath+"/"+t,c=!e.opts.allErrors,u="data"+(i||""),l="valid"+s,h=e.opts.$data&&n&&n.$data;h&&(a+=" var schema"+s+" = "+e.util.getData(n.$data,i,e.dataPathArr)+"; ");var p="i"+s,f="schema"+s;h||(a+=" var "+f+" = validate.schema"+o+";"),a+="var "+l+";",h&&(a+=" if (schema"+s+" === undefined) "+l+" = true; else if (!Array.isArray(schema"+s+")) "+l+" = false; else {"),a+=l+" = false;for (var "+p+"=0; "+p+"<"+f+".length; "+p+"++) if (equal("+u+", "+f+"["+p+"])) { "+l+" = true; break; }",h&&(a+=" } "),a+=" if (!"+l+") { ";var m=m||[];m.push(a),a="",!1!==e.createErrors?(a+=" { keyword: 'enum' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(d)+" , params: { allowedValues: schema"+s+" } ",!1!==e.opts.messages&&(a+=" , message: 'should be equal to one of the allowed values' "),e.opts.verbose&&(a+=" , schema: validate.schema"+o+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+u+" "),a+=" } "):a+=" {} ";var v=a;return a=m.pop(),!e.compositeRule&&c?e.async?a+=" throw new ValidationError(["+v+"]); ":a+=" validate.errors = ["+v+"]; return false; ":a+=" var err = "+v+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",a+=" }",c&&(a+=" else { "),a}},68820:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ZodError=t.quotelessJson=t.ZodIssueCode=void 0;const a=r(27165);t.ZodIssueCode=a.util.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),t.quotelessJson=e=>JSON.stringify(e,null,2).replace(/"([^"]+)":/g,"$1:");class s extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=e=>{this.issues=[...this.issues,e]},this.addIssues=(e=[])=>{this.issues=[...this.issues,...e]};const t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name="ZodError",this.issues=e}format(e){const t=e||function(e){return e.message},r={_errors:[]},a=e=>{for(const s of e.issues)if("invalid_union"===s.code)s.unionErrors.map(a);else if("invalid_return_type"===s.code)a(s.returnTypeError);else if("invalid_arguments"===s.code)a(s.argumentsError);else if(0===s.path.length)r._errors.push(t(s));else{let e=r,a=0;for(;a<s.path.length;){const r=s.path[a];a===s.path.length-1?(e[r]=e[r]||{_errors:[]},e[r]._errors.push(t(s))):e[r]=e[r]||{_errors:[]},e=e[r],a++}}};return a(this),r}static assert(e){if(!(e instanceof s))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,a.util.jsonStringifyReplacer,2)}get isEmpty(){return 0===this.issues.length}flatten(e=e=>e.message){const t={},r=[];for(const a of this.issues)if(a.path.length>0){const r=a.path[0];t[r]=t[r]||[],t[r].push(e(a))}else r.push(e(a));return{formErrors:r,fieldErrors:t}}get formErrors(){return this.flatten()}}t.ZodError=s,s.create=e=>new s(e)},70926:function(e,t,r){"use strict";var a=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.isAsync=t.isValid=t.isDirty=t.isAborted=t.OK=t.DIRTY=t.INVALID=t.ParseStatus=t.EMPTY_PATH=t.makeIssue=void 0,t.addIssueToContext=function(e,r){const a=(0,s.getErrorMap)(),n=(0,t.makeIssue)({issueData:r,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,a,a===i.default?void 0:i.default].filter(e=>!!e)});e.common.issues.push(n)};const s=r(80630),i=a(r(36886));t.makeIssue=e=>{const{data:t,path:r,errorMaps:a,issueData:s}=e,i=[...r,...s.path||[]],n={...s,path:i};if(void 0!==s.message)return{...s,path:i,message:s.message};let o="";const d=a.filter(e=>!!e).slice().reverse();for(const e of d)o=e(n,{data:t,defaultError:o}).message;return{...s,path:i,message:o}},t.EMPTY_PATH=[];class n{constructor(){this.value="valid"}dirty(){"valid"===this.value&&(this.value="dirty")}abort(){"aborted"!==this.value&&(this.value="aborted")}static mergeArray(e,r){const a=[];for(const s of r){if("aborted"===s.status)return t.INVALID;"dirty"===s.status&&e.dirty(),a.push(s.value)}return{status:e.value,value:a}}static async mergeObjectAsync(e,t){const r=[];for(const e of t){const t=await e.key,a=await e.value;r.push({key:t,value:a})}return n.mergeObjectSync(e,r)}static mergeObjectSync(e,r){const a={};for(const s of r){const{key:r,value:i}=s;if("aborted"===r.status)return t.INVALID;if("aborted"===i.status)return t.INVALID;"dirty"===r.status&&e.dirty(),"dirty"===i.status&&e.dirty(),"__proto__"===r.value||void 0===i.value&&!s.alwaysSet||(a[r.value]=i.value)}return{status:e.value,value:a}}}t.ParseStatus=n,t.INVALID=Object.freeze({status:"aborted"}),t.DIRTY=e=>({status:"dirty",value:e}),t.OK=e=>({status:"valid",value:e}),t.isAborted=e=>"aborted"===e.status,t.isDirty=e=>"dirty"===e.status,t.isValid=e=>"valid"===e.status,t.isAsync=e=>"undefined"!=typeof Promise&&e instanceof Promise},71346:e=>{"use strict";e.exports=function(e,t,r){var a,s=" ",i=e.level,n=e.dataLevel,o=e.schema[t],d=e.schemaPath+e.util.getProperty(t),c=e.errSchemaPath+"/"+t,u=!e.opts.allErrors,l="data"+(n||""),h=e.opts.$data&&o&&o.$data;h?(s+=" var schema"+i+" = "+e.util.getData(o.$data,n,e.dataPathArr)+"; ",a="schema"+i):a=o;var p="maximum"==t,f=p?"exclusiveMaximum":"exclusiveMinimum",m=e.schema[f],v=e.opts.$data&&m&&m.$data,y=p?"<":">",g=p?">":"<",_=void 0;if(!h&&"number"!=typeof o&&void 0!==o)throw new Error(t+" must be number");if(!v&&void 0!==m&&"number"!=typeof m&&"boolean"!=typeof m)throw new Error(f+" must be number or boolean");if(v){var b,w=e.util.getData(m.$data,n,e.dataPathArr),P="exclusive"+i,E="exclType"+i,x="exclIsNumber"+i,S="' + "+(k="op"+i)+" + '";s+=" var schemaExcl"+i+" = "+w+"; ",s+=" var "+P+"; var "+E+" = typeof "+(w="schemaExcl"+i)+"; if ("+E+" != 'boolean' && "+E+" != 'undefined' && "+E+" != 'number') { ",_=f,(b=b||[]).push(s),s="",!1!==e.createErrors?(s+=" { keyword: '"+(_||"_exclusiveLimit")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: {} ",!1!==e.opts.messages&&(s+=" , message: '"+f+" should be boolean' "),e.opts.verbose&&(s+=" , schema: validate.schema"+d+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+l+" "),s+=" } "):s+=" {} ";var I=s;s=b.pop(),!e.compositeRule&&u?e.async?s+=" throw new ValidationError(["+I+"]); ":s+=" validate.errors = ["+I+"]; return false; ":s+=" var err = "+I+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",s+=" } else if ( ",h&&(s+=" ("+a+" !== undefined && typeof "+a+" != 'number') || "),s+=" "+E+" == 'number' ? ( ("+P+" = "+a+" === undefined || "+w+" "+y+"= "+a+") ? "+l+" "+g+"= "+w+" : "+l+" "+g+" "+a+" ) : ( ("+P+" = "+w+" === true) ? "+l+" "+g+"= "+a+" : "+l+" "+g+" "+a+" ) || "+l+" !== "+l+") { var op"+i+" = "+P+" ? '"+y+"' : '"+y+"='; ",void 0===o&&(_=f,c=e.errSchemaPath+"/"+f,a=w,h=v)}else if(S=y,(x="number"==typeof m)&&h){var k="'"+S+"'";s+=" if ( ",h&&(s+=" ("+a+" !== undefined && typeof "+a+" != 'number') || "),s+=" ( "+a+" === undefined || "+m+" "+y+"= "+a+" ? "+l+" "+g+"= "+m+" : "+l+" "+g+" "+a+" ) || "+l+" !== "+l+") { "}else x&&void 0===o?(P=!0,_=f,c=e.errSchemaPath+"/"+f,a=m,g+="="):(x&&(a=Math[p?"min":"max"](m,o)),m===(!x||a)?(P=!0,_=f,c=e.errSchemaPath+"/"+f,g+="="):(P=!1,S+="=")),k="'"+S+"'",s+=" if ( ",h&&(s+=" ("+a+" !== undefined && typeof "+a+" != 'number') || "),s+=" "+l+" "+g+" "+a+" || "+l+" !== "+l+") { ";return _=_||t,(b=b||[]).push(s),s="",!1!==e.createErrors?(s+=" { keyword: '"+(_||"_limit")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { comparison: "+k+", limit: "+a+", exclusive: "+P+" } ",!1!==e.opts.messages&&(s+=" , message: 'should be "+S+" ",s+=h?"' + "+a:a+"'"),e.opts.verbose&&(s+=" , schema: ",s+=h?"validate.schema"+d:""+o,s+=" , parentSchema: validate.schema"+e.schemaPath+" , data: "+l+" "),s+=" } "):s+=" {} ",I=s,s=b.pop(),!e.compositeRule&&u?e.async?s+=" throw new ValidationError(["+I+"]); ":s+=" validate.errors = ["+I+"]; return false; ":s+=" var err = "+I+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",s+=" } ",u&&(s+=" else { "),s}},72916:(e,t,r)=>{"use strict";var a=r(40985);function s(e,t,r){this.message=r||s.message(e,t),this.missingRef=a.url(e,t),this.missingSchema=a.normalizeId(a.fullPath(this.missingRef))}function i(e){return e.prototype=Object.create(Error.prototype),e.prototype.constructor=e,e}e.exports={Validation:i(function(e){this.message="validation failed",this.errors=e,this.ajv=this.validation=!0}),MissingRef:i(s)},s.message=function(e,t){return"can't resolve reference "+t+" from id "+e}},74488:function(e,t,r){"use strict";var a=this&&this.__createBinding||(Object.create?function(e,t,r,a){void 0===a&&(a=r);var s=Object.getOwnPropertyDescriptor(t,r);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,a,s)}:function(e,t,r,a){void 0===a&&(a=r),e[a]=t[r]}),s=this&&this.__exportStar||function(e,t){for(var r in e)"default"===r||Object.prototype.hasOwnProperty.call(t,r)||a(t,e,r)};Object.defineProperty(t,"__esModule",{value:!0}),s(r(97145),t),s(r(78362),t)},78362:(e,t)=>{"use strict";function r(e){return JSON.stringify(e)}Object.defineProperty(t,"__esModule",{value:!0}),t.DOWNSTREAM_HEADER_NAMES=void 0,t.serializeCrispSpend=r,t.parseCrispSpend=function(e){try{const t=JSON.parse(e);return t&&"string"==typeof t.unit?t:null}catch{return null}},t.createDownstreamHeaders=function(e){const t={"X-Agent-DID":e.agentDid,"X-MCPI-Proof-Id":e.proofId};return e.delegationId&&(t["X-Delegation-Id"]=e.delegationId),e.delegationChain&&(t["X-Delegation-Chain"]=e.delegationChain),e.crispSpend&&(t["X-CRISP-Spend"]=r(e.crispSpend)),e.sessionId&&(t["X-Session-Id"]=e.sessionId),e.scopes&&e.scopes.length>0&&(t["X-Scopes"]=e.scopes.join(",")),t},t.DOWNSTREAM_HEADER_NAMES=Object.freeze({AGENT_DID:"X-Agent-DID",DELEGATION_ID:"X-Delegation-Id",DELEGATION_CHAIN:"X-Delegation-Chain",PROOF_ID:"X-MCPI-Proof-Id",CRISP_SPEND:"X-CRISP-Spend",SESSION_ID:"X-Session-Id",SCOPES:"X-Scopes"})},80536:e=>{"use strict";e.exports=function(e,t,r){var a,s=" ",i=e.level,n=e.dataLevel,o=e.schema[t],d=e.schemaPath+e.util.getProperty(t),c=e.errSchemaPath+"/"+t,u=!e.opts.allErrors,l="data"+(n||""),h=e.opts.$data&&o&&o.$data;if(h?(s+=" var schema"+i+" = "+e.util.getData(o.$data,n,e.dataPathArr)+"; ",a="schema"+i):a=o,!h&&"number"!=typeof o)throw new Error(t+" must be number");s+="if ( ",h&&(s+=" ("+a+" !== undefined && typeof "+a+" != 'number') || "),s+=" "+l+".length "+("maxItems"==t?">":"<")+" "+a+") { ";var p=t,f=f||[];f.push(s),s="",!1!==e.createErrors?(s+=" { keyword: '"+(p||"_limitItems")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { limit: "+a+" } ",!1!==e.opts.messages&&(s+=" , message: 'should NOT have ",s+="maxItems"==t?"more":"fewer",s+=" than ",s+=h?"' + "+a+" + '":""+o,s+=" items' "),e.opts.verbose&&(s+=" , schema: ",s+=h?"validate.schema"+d:""+o,s+=" , parentSchema: validate.schema"+e.schemaPath+" , data: "+l+" "),s+=" } "):s+=" {} ";var m=s;return s=f.pop(),!e.compositeRule&&u?e.async?s+=" throw new ValidationError(["+m+"]); ":s+=" validate.errors = ["+m+"]; return false; ":s+=" var err = "+m+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",s+="} ",u&&(s+=" else { "),s}},80630:function(e,t,r){"use strict";var a=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.defaultErrorMap=void 0,t.setErrorMap=function(e){i=e},t.getErrorMap=function(){return i};const s=a(r(36886));t.defaultErrorMap=s.default;let i=s.default},82917:e=>{"use strict";e.exports=function(e,t,r){var a=" ",s=e.level,i=e.dataLevel,n=e.schema[t],o=e.schemaPath+e.util.getProperty(t),d=e.errSchemaPath+"/"+t,c=!e.opts.allErrors,u="data"+(i||""),l="valid"+s,h="errs__"+s,p=e.util.copy(e);p.level++;var f="valid"+p.level,m=e.schema.then,v=e.schema.else,y=void 0!==m&&(e.opts.strictKeywords?"object"==typeof m&&Object.keys(m).length>0||!1===m:e.util.schemaHasRules(m,e.RULES.all)),g=void 0!==v&&(e.opts.strictKeywords?"object"==typeof v&&Object.keys(v).length>0||!1===v:e.util.schemaHasRules(v,e.RULES.all)),_=p.baseId;if(y||g){var b;p.createErrors=!1,p.schema=n,p.schemaPath=o,p.errSchemaPath=d,a+=" var "+h+" = errors; var "+l+" = true; ";var w=e.compositeRule;e.compositeRule=p.compositeRule=!0,a+=" "+e.validate(p)+" ",p.baseId=_,p.createErrors=!0,a+=" errors = "+h+"; if (vErrors !== null) { if ("+h+") vErrors.length = "+h+"; else vErrors = null; } ",e.compositeRule=p.compositeRule=w,y?(a+=" if ("+f+") { ",p.schema=e.schema.then,p.schemaPath=e.schemaPath+".then",p.errSchemaPath=e.errSchemaPath+"/then",a+=" "+e.validate(p)+" ",p.baseId=_,a+=" "+l+" = "+f+"; ",y&&g?a+=" var "+(b="ifClause"+s)+" = 'then'; ":b="'then'",a+=" } ",g&&(a+=" else { ")):a+=" if (!"+f+") { ",g&&(p.schema=e.schema.else,p.schemaPath=e.schemaPath+".else",p.errSchemaPath=e.errSchemaPath+"/else",a+=" "+e.validate(p)+" ",p.baseId=_,a+=" "+l+" = "+f+"; ",y&&g?a+=" var "+(b="ifClause"+s)+" = 'else'; ":b="'else'",a+=" } "),a+=" if (!"+l+") { var err = ",!1!==e.createErrors?(a+=" { keyword: 'if' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(d)+" , params: { failingKeyword: "+b+" } ",!1!==e.opts.messages&&(a+=" , message: 'should match \"' + "+b+" + '\" schema' "),e.opts.verbose&&(a+=" , schema: validate.schema"+o+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+u+" "),a+=" } "):a+=" {} ",a+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",!e.compositeRule&&c&&(e.async?a+=" throw new ValidationError(vErrors); ":a+=" validate.errors = vErrors; return false; "),a+=" } ",c&&(a+=" else { ")}else c&&(a+=" if (true) { ");return a}},83010:e=>{"use strict";e.exports=function(e,t,r){var a,s=" ",i=e.level,n=e.dataLevel,o=e.schema[t],d=e.schemaPath+e.util.getProperty(t),c=e.errSchemaPath+"/"+t,u=!e.opts.allErrors,l="data"+(n||""),h=e.opts.$data&&o&&o.$data;if(h?(s+=" var schema"+i+" = "+e.util.getData(o.$data,n,e.dataPathArr)+"; ",a="schema"+i):a=o,!h&&"number"!=typeof o)throw new Error(t+" must be number");var p="maxLength"==t?">":"<";s+="if ( ",h&&(s+=" ("+a+" !== undefined && typeof "+a+" != 'number') || "),!1===e.opts.unicode?s+=" "+l+".length ":s+=" ucs2length("+l+") ",s+=" "+p+" "+a+") { ";var f=t,m=m||[];m.push(s),s="",!1!==e.createErrors?(s+=" { keyword: '"+(f||"_limitLength")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { limit: "+a+" } ",!1!==e.opts.messages&&(s+=" , message: 'should NOT be ",s+="maxLength"==t?"longer":"shorter",s+=" than ",s+=h?"' + "+a+" + '":""+o,s+=" characters' "),e.opts.verbose&&(s+=" , schema: ",s+=h?"validate.schema"+d:""+o,s+=" , parentSchema: validate.schema"+e.schemaPath+" , data: "+l+" "),s+=" } "):s+=" {} ";var v=s;return s=m.pop(),!e.compositeRule&&u?e.async?s+=" throw new ValidationError(["+v+"]); ":s+=" validate.errors = ["+v+"]; return false; ":s+=" var err = "+v+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",s+="} ",u&&(s+=" else { "),s}},86343:e=>{"use strict";e.exports=function(e,t,r){var a=" ",s=e.level,i=e.dataLevel,n=e.schema[t],o=e.schemaPath+e.util.getProperty(t),d=e.errSchemaPath+"/"+t,c=!e.opts.allErrors,u="data"+(i||""),l="errs__"+s,h=e.util.copy(e),p="";h.level++;var f="valid"+h.level,m="key"+s,v="idx"+s,y=h.dataLevel=e.dataLevel+1,g="data"+y,_="dataProperties"+s,b=Object.keys(n||{}).filter(D),w=e.schema.patternProperties||{},P=Object.keys(w).filter(D),E=e.schema.additionalProperties,x=b.length||P.length,S=!1===E,I="object"==typeof E&&Object.keys(E).length,k=e.opts.removeAdditional,T=S||I||k,C=e.opts.ownProperties,A=e.baseId,O=e.schema.required;if(O&&(!e.opts.$data||!O.$data)&&O.length<e.opts.loopRequired)var R=e.util.toHash(O);function D(e){return"__proto__"!==e}if(a+="var "+l+" = errors;var "+f+" = true;",C&&(a+=" var "+_+" = undefined;"),T){if(a+=C?" "+_+" = "+_+" || Object.keys("+u+"); for (var "+v+"=0; "+v+"<"+_+".length; "+v+"++) { var "+m+" = "+_+"["+v+"]; ":" for (var "+m+" in "+u+") { ",x){if(a+=" var isAdditional"+s+" = !(false ",b.length)if(b.length>8)a+=" || validate.schema"+o+".hasOwnProperty("+m+") ";else{var N=b;if(N)for(var Z=-1,$=N.length-1;Z<$;)J=N[Z+=1],a+=" || "+m+" == "+e.util.toQuotedString(J)+" "}if(P.length){var j=P;if(j)for(var F=-1,M=j.length-1;F<M;)ie=j[F+=1],a+=" || "+e.usePattern(ie)+".test("+m+") "}a+=" ); if (isAdditional"+s+") { "}if("all"==k)a+=" delete "+u+"["+m+"]; ";else{var L=e.errorPath,z="' + "+m+" + '";if(e.opts._errorDataPathProperty&&(e.errorPath=e.util.getPathExpr(e.errorPath,m,e.opts.jsonPointers)),S)if(k)a+=" delete "+u+"["+m+"]; ";else{a+=" "+f+" = false; ";var V=d;d=e.errSchemaPath+"/additionalProperties",(re=re||[]).push(a),a="",!1!==e.createErrors?(a+=" { keyword: 'additionalProperties' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(d)+" , params: { additionalProperty: '"+z+"' } ",!1!==e.opts.messages&&(a+=" , message: '",e.opts._errorDataPathProperty?a+="is an invalid additional property":a+="should NOT have additional properties",a+="' "),e.opts.verbose&&(a+=" , schema: false , parentSchema: validate.schema"+e.schemaPath+" , data: "+u+" "),a+=" } "):a+=" {} ";var q=a;a=re.pop(),!e.compositeRule&&c?e.async?a+=" throw new ValidationError(["+q+"]); ":a+=" validate.errors = ["+q+"]; return false; ":a+=" var err = "+q+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",d=V,c&&(a+=" break; ")}else if(I)if("failing"==k){a+=" var "+l+" = errors; ";var U=e.compositeRule;e.compositeRule=h.compositeRule=!0,h.schema=E,h.schemaPath=e.schemaPath+".additionalProperties",h.errSchemaPath=e.errSchemaPath+"/additionalProperties",h.errorPath=e.opts._errorDataPathProperty?e.errorPath:e.util.getPathExpr(e.errorPath,m,e.opts.jsonPointers);var K=u+"["+m+"]";h.dataPathArr[y]=m;var H=e.validate(h);h.baseId=A,e.util.varOccurences(H,g)<2?a+=" "+e.util.varReplace(H,g,K)+" ":a+=" var "+g+" = "+K+"; "+H+" ",a+=" if (!"+f+") { errors = "+l+"; if (validate.errors !== null) { if (errors) validate.errors.length = errors; else validate.errors = null; } delete "+u+"["+m+"]; } ",e.compositeRule=h.compositeRule=U}else h.schema=E,h.schemaPath=e.schemaPath+".additionalProperties",h.errSchemaPath=e.errSchemaPath+"/additionalProperties",h.errorPath=e.opts._errorDataPathProperty?e.errorPath:e.util.getPathExpr(e.errorPath,m,e.opts.jsonPointers),K=u+"["+m+"]",h.dataPathArr[y]=m,H=e.validate(h),h.baseId=A,e.util.varOccurences(H,g)<2?a+=" "+e.util.varReplace(H,g,K)+" ":a+=" var "+g+" = "+K+"; "+H+" ",c&&(a+=" if (!"+f+") break; ");e.errorPath=L}x&&(a+=" } "),a+=" } ",c&&(a+=" if ("+f+") { ",p+="}")}var B=e.opts.useDefaults&&!e.compositeRule;if(b.length){var Q=b;if(Q)for(var J,W=-1,G=Q.length-1;W<G;){var Y=n[J=Q[W+=1]];if(e.opts.strictKeywords?"object"==typeof Y&&Object.keys(Y).length>0||!1===Y:e.util.schemaHasRules(Y,e.RULES.all)){var X=e.util.getProperty(J),ee=(K=u+X,B&&void 0!==Y.default);if(h.schema=Y,h.schemaPath=o+X,h.errSchemaPath=d+"/"+e.util.escapeFragment(J),h.errorPath=e.util.getPath(e.errorPath,J,e.opts.jsonPointers),h.dataPathArr[y]=e.util.toQuotedString(J),H=e.validate(h),h.baseId=A,e.util.varOccurences(H,g)<2){H=e.util.varReplace(H,g,K);var te=K}else te=g,a+=" var "+g+" = "+K+"; ";if(ee)a+=" "+H+" ";else{if(R&&R[J]){a+=" if ( "+te+" === undefined ",C&&(a+=" || ! Object.prototype.hasOwnProperty.call("+u+", '"+e.util.escapeQuotes(J)+"') "),a+=") { "+f+" = false; ",L=e.errorPath,V=d;var re,ae=e.util.escapeQuotes(J);e.opts._errorDataPathProperty&&(e.errorPath=e.util.getPath(L,J,e.opts.jsonPointers)),d=e.errSchemaPath+"/required",(re=re||[]).push(a),a="",!1!==e.createErrors?(a+=" { keyword: 'required' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(d)+" , params: { missingProperty: '"+ae+"' } ",!1!==e.opts.messages&&(a+=" , message: '",e.opts._errorDataPathProperty?a+="is a required property":a+="should have required property \\'"+ae+"\\'",a+="' "),e.opts.verbose&&(a+=" , schema: validate.schema"+o+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+u+" "),a+=" } "):a+=" {} ",q=a,a=re.pop(),!e.compositeRule&&c?e.async?a+=" throw new ValidationError(["+q+"]); ":a+=" validate.errors = ["+q+"]; return false; ":a+=" var err = "+q+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",d=V,e.errorPath=L,a+=" } else { "}else c?(a+=" if ( "+te+" === undefined ",C&&(a+=" || ! Object.prototype.hasOwnProperty.call("+u+", '"+e.util.escapeQuotes(J)+"') "),a+=") { "+f+" = true; } else { "):(a+=" if ("+te+" !== undefined ",C&&(a+=" && Object.prototype.hasOwnProperty.call("+u+", '"+e.util.escapeQuotes(J)+"') "),a+=" ) { ");a+=" "+H+" } "}}c&&(a+=" if ("+f+") { ",p+="}")}}if(P.length){var se=P;if(se)for(var ie,ne=-1,oe=se.length-1;ne<oe;)Y=w[ie=se[ne+=1]],(e.opts.strictKeywords?"object"==typeof Y&&Object.keys(Y).length>0||!1===Y:e.util.schemaHasRules(Y,e.RULES.all))&&(h.schema=Y,h.schemaPath=e.schemaPath+".patternProperties"+e.util.getProperty(ie),h.errSchemaPath=e.errSchemaPath+"/patternProperties/"+e.util.escapeFragment(ie),a+=C?" "+_+" = "+_+" || Object.keys("+u+"); for (var "+v+"=0; "+v+"<"+_+".length; "+v+"++) { var "+m+" = "+_+"["+v+"]; ":" for (var "+m+" in "+u+") { ",a+=" if ("+e.usePattern(ie)+".test("+m+")) { ",h.errorPath=e.util.getPathExpr(e.errorPath,m,e.opts.jsonPointers),K=u+"["+m+"]",h.dataPathArr[y]=m,H=e.validate(h),h.baseId=A,e.util.varOccurences(H,g)<2?a+=" "+e.util.varReplace(H,g,K)+" ":a+=" var "+g+" = "+K+"; "+H+" ",c&&(a+=" if (!"+f+") break; "),a+=" } ",c&&(a+=" else "+f+" = true; "),a+=" } ",c&&(a+=" if ("+f+") { ",p+="}"))}return c&&(a+=" "+p+" if ("+l+" == errors) {"),a}},90083:e=>{"use strict";e.exports=function(e,t,r){var a=" ",s=e.level,i=e.dataLevel,n=e.schema[t],o=e.schemaPath+e.util.getProperty(t),d=e.errSchemaPath+"/"+t,c=!e.opts.allErrors,u="data"+(i||""),l="errs__"+s,h=e.util.copy(e),p="";h.level++;var f="valid"+h.level,m={},v={},y=e.opts.ownProperties;for(w in n)if("__proto__"!=w){var g=n[w],_=Array.isArray(g)?v:m;_[w]=g}a+="var "+l+" = errors;";var b=e.errorPath;for(var w in a+="var missing"+s+";",v)if((_=v[w]).length){if(a+=" if ( "+u+e.util.getProperty(w)+" !== undefined ",y&&(a+=" && Object.prototype.hasOwnProperty.call("+u+", '"+e.util.escapeQuotes(w)+"') "),c){a+=" && ( ";var P=_;if(P)for(var E=-1,x=P.length-1;E<x;)A=P[E+=1],E&&(a+=" || "),a+=" ( ( "+(N=u+(D=e.util.getProperty(A)))+" === undefined ",y&&(a+=" || ! Object.prototype.hasOwnProperty.call("+u+", '"+e.util.escapeQuotes(A)+"') "),a+=") && (missing"+s+" = "+e.util.toQuotedString(e.opts.jsonPointers?A:D)+") ) ";a+=")) { ";var S="missing"+s,I="' + "+S+" + '";e.opts._errorDataPathProperty&&(e.errorPath=e.opts.jsonPointers?e.util.getPathExpr(b,S,!0):b+" + "+S);var k=k||[];k.push(a),a="",!1!==e.createErrors?(a+=" { keyword: 'dependencies' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(d)+" , params: { property: '"+e.util.escapeQuotes(w)+"', missingProperty: '"+I+"', depsCount: "+_.length+", deps: '"+e.util.escapeQuotes(1==_.length?_[0]:_.join(", "))+"' } ",!1!==e.opts.messages&&(a+=" , message: 'should have ",1==_.length?a+="property "+e.util.escapeQuotes(_[0]):a+="properties "+e.util.escapeQuotes(_.join(", ")),a+=" when property "+e.util.escapeQuotes(w)+" is present' "),e.opts.verbose&&(a+=" , schema: validate.schema"+o+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+u+" "),a+=" } "):a+=" {} ";var T=a;a=k.pop(),!e.compositeRule&&c?e.async?a+=" throw new ValidationError(["+T+"]); ":a+=" validate.errors = ["+T+"]; return false; ":a+=" var err = "+T+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; "}else{a+=" ) { ";var C=_;if(C)for(var A,O=-1,R=C.length-1;O<R;){A=C[O+=1];var D=e.util.getProperty(A),N=(I=e.util.escapeQuotes(A),u+D);e.opts._errorDataPathProperty&&(e.errorPath=e.util.getPath(b,A,e.opts.jsonPointers)),a+=" if ( "+N+" === undefined ",y&&(a+=" || ! Object.prototype.hasOwnProperty.call("+u+", '"+e.util.escapeQuotes(A)+"') "),a+=") { var err = ",!1!==e.createErrors?(a+=" { keyword: 'dependencies' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(d)+" , params: { property: '"+e.util.escapeQuotes(w)+"', missingProperty: '"+I+"', depsCount: "+_.length+", deps: '"+e.util.escapeQuotes(1==_.length?_[0]:_.join(", "))+"' } ",!1!==e.opts.messages&&(a+=" , message: 'should have ",1==_.length?a+="property "+e.util.escapeQuotes(_[0]):a+="properties "+e.util.escapeQuotes(_.join(", ")),a+=" when property "+e.util.escapeQuotes(w)+" is present' "),e.opts.verbose&&(a+=" , schema: validate.schema"+o+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+u+" "),a+=" } "):a+=" {} ",a+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } "}}a+=" } ",c&&(p+="}",a+=" else { ")}e.errorPath=b;var Z=h.baseId;for(var w in m)g=m[w],(e.opts.strictKeywords?"object"==typeof g&&Object.keys(g).length>0||!1===g:e.util.schemaHasRules(g,e.RULES.all))&&(a+=" "+f+" = true; if ( "+u+e.util.getProperty(w)+" !== undefined ",y&&(a+=" && Object.prototype.hasOwnProperty.call("+u+", '"+e.util.escapeQuotes(w)+"') "),a+=") { ",h.schema=g,h.schemaPath=o+e.util.getProperty(w),h.errSchemaPath=d+"/"+e.util.escapeFragment(w),a+=" "+e.validate(h)+" ",h.baseId=Z,a+=" } ",c&&(a+=" if ("+f+") { ",p+="}"));return c&&(a+=" "+p+" if ("+l+" == errors) {"),a}},90315:function(e,t,r){"use strict";var a=this&&this.__createBinding||(Object.create?function(e,t,r,a){void 0===a&&(a=r);var s=Object.getOwnPropertyDescriptor(t,r);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,a,s)}:function(e,t,r,a){void 0===a&&(a=r),e[a]=t[r]}),s=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),i=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)"default"!==r&&Object.prototype.hasOwnProperty.call(e,r)&&a(t,e,r);return s(t,e),t},n=this&&this.__exportStar||function(e,t){for(var r in e)"default"===r||Object.prototype.hasOwnProperty.call(t,r)||a(t,e,r)};Object.defineProperty(t,"__esModule",{value:!0}),t.z=void 0;const o=i(r(99394));t.z=o,n(r(99394),t),t.default=o},91939:e=>{"use strict";e.exports=function(e,t,r){var a=" ",s=e.level,i=e.dataLevel,n=e.schema[t],o=e.schemaPath+e.util.getProperty(t),d=e.errSchemaPath+"/"+t,c=!e.opts.allErrors,u="data"+(i||""),l="valid"+s,h=e.opts.$data&&n&&n.$data;h&&(a+=" var schema"+s+" = "+e.util.getData(n.$data,i,e.dataPathArr)+"; ");var p="schema"+s;if(!h)if(n.length<e.opts.loopRequired&&e.schema.properties&&Object.keys(e.schema.properties).length){var f=[],m=n;if(m)for(var v,y=-1,g=m.length-1;y<g;){v=m[y+=1];var _=e.schema.properties[v];_&&(e.opts.strictKeywords?"object"==typeof _&&Object.keys(_).length>0||!1===_:e.util.schemaHasRules(_,e.RULES.all))||(f[f.length]=v)}}else f=n;if(h||f.length){var b=e.errorPath,w=h||f.length>=e.opts.loopRequired,P=e.opts.ownProperties;if(c)if(a+=" var missing"+s+"; ",w){h||(a+=" var "+p+" = validate.schema"+o+"; ");var E="' + "+(C="schema"+s+"["+(k="i"+s)+"]")+" + '";e.opts._errorDataPathProperty&&(e.errorPath=e.util.getPathExpr(b,C,e.opts.jsonPointers)),a+=" var "+l+" = true; ",h&&(a+=" if (schema"+s+" === undefined) "+l+" = true; else if (!Array.isArray(schema"+s+")) "+l+" = false; else {"),a+=" for (var "+k+" = 0; "+k+" < "+p+".length; "+k+"++) { "+l+" = "+u+"["+p+"["+k+"]] !== undefined ",P&&(a+=" && Object.prototype.hasOwnProperty.call("+u+", "+p+"["+k+"]) "),a+="; if (!"+l+") break; } ",h&&(a+=" } "),a+=" if (!"+l+") { ",(S=S||[]).push(a),a="",!1!==e.createErrors?(a+=" { keyword: 'required' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(d)+" , params: { missingProperty: '"+E+"' } ",!1!==e.opts.messages&&(a+=" , message: '",e.opts._errorDataPathProperty?a+="is a required property":a+="should have required property \\'"+E+"\\'",a+="' "),e.opts.verbose&&(a+=" , schema: validate.schema"+o+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+u+" "),a+=" } "):a+=" {} ";var x=a;a=S.pop(),!e.compositeRule&&c?e.async?a+=" throw new ValidationError(["+x+"]); ":a+=" validate.errors = ["+x+"]; return false; ":a+=" var err = "+x+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",a+=" } else { "}else{a+=" if ( ";var S,I=f;if(I)for(var k=-1,T=I.length-1;k<T;)O=I[k+=1],k&&(a+=" || "),a+=" ( ( "+(Z=u+(N=e.util.getProperty(O)))+" === undefined ",P&&(a+=" || ! Object.prototype.hasOwnProperty.call("+u+", '"+e.util.escapeQuotes(O)+"') "),a+=") && (missing"+s+" = "+e.util.toQuotedString(e.opts.jsonPointers?O:N)+") ) ";a+=") { ",E="' + "+(C="missing"+s)+" + '",e.opts._errorDataPathProperty&&(e.errorPath=e.opts.jsonPointers?e.util.getPathExpr(b,C,!0):b+" + "+C),(S=S||[]).push(a),a="",!1!==e.createErrors?(a+=" { keyword: 'required' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(d)+" , params: { missingProperty: '"+E+"' } ",!1!==e.opts.messages&&(a+=" , message: '",e.opts._errorDataPathProperty?a+="is a required property":a+="should have required property \\'"+E+"\\'",a+="' "),e.opts.verbose&&(a+=" , schema: validate.schema"+o+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+u+" "),a+=" } "):a+=" {} ",x=a,a=S.pop(),!e.compositeRule&&c?e.async?a+=" throw new ValidationError(["+x+"]); ":a+=" validate.errors = ["+x+"]; return false; ":a+=" var err = "+x+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",a+=" } else { "}else if(w){var C;h||(a+=" var "+p+" = validate.schema"+o+"; "),E="' + "+(C="schema"+s+"["+(k="i"+s)+"]")+" + '",e.opts._errorDataPathProperty&&(e.errorPath=e.util.getPathExpr(b,C,e.opts.jsonPointers)),h&&(a+=" if ("+p+" && !Array.isArray("+p+")) { var err = ",!1!==e.createErrors?(a+=" { keyword: 'required' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(d)+" , params: { missingProperty: '"+E+"' } ",!1!==e.opts.messages&&(a+=" , message: '",e.opts._errorDataPathProperty?a+="is a required property":a+="should have required property \\'"+E+"\\'",a+="' "),e.opts.verbose&&(a+=" , schema: validate.schema"+o+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+u+" "),a+=" } "):a+=" {} ",a+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } else if ("+p+" !== undefined) { "),a+=" for (var "+k+" = 0; "+k+" < "+p+".length; "+k+"++) { if ("+u+"["+p+"["+k+"]] === undefined ",P&&(a+=" || ! Object.prototype.hasOwnProperty.call("+u+", "+p+"["+k+"]) "),a+=") { var err = ",!1!==e.createErrors?(a+=" { keyword: 'required' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(d)+" , params: { missingProperty: '"+E+"' } ",!1!==e.opts.messages&&(a+=" , message: '",e.opts._errorDataPathProperty?a+="is a required property":a+="should have required property \\'"+E+"\\'",a+="' "),e.opts.verbose&&(a+=" , schema: validate.schema"+o+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+u+" "),a+=" } "):a+=" {} ",a+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } } ",h&&(a+=" } ")}else{var A=f;if(A)for(var O,R=-1,D=A.length-1;R<D;){O=A[R+=1];var N=e.util.getProperty(O),Z=(E=e.util.escapeQuotes(O),u+N);e.opts._errorDataPathProperty&&(e.errorPath=e.util.getPath(b,O,e.opts.jsonPointers)),a+=" if ( "+Z+" === undefined ",P&&(a+=" || ! Object.prototype.hasOwnProperty.call("+u+", '"+e.util.escapeQuotes(O)+"') "),a+=") { var err = ",!1!==e.createErrors?(a+=" { keyword: 'required' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(d)+" , params: { missingProperty: '"+E+"' } ",!1!==e.opts.messages&&(a+=" , message: '",e.opts._errorDataPathProperty?a+="is a required property":a+="should have required property \\'"+E+"\\'",a+="' "),e.opts.verbose&&(a+=" , schema: validate.schema"+o+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+u+" "),a+=" } "):a+=" {} ",a+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } "}}e.errorPath=b}else c&&(a+=" if (true) {");return a}},95545:e=>{"use strict";e.exports=function(e,t,r){var a=" ",s=e.level,i=e.dataLevel,n=e.schema[t],o=e.schemaPath+e.util.getProperty(t),d=e.errSchemaPath+"/"+t,c=!e.opts.allErrors,u="data"+(i||"");if(!1===e.opts.format)return c&&(a+=" if (true) { "),a;var l,h=e.opts.$data&&n&&n.$data;h?(a+=" var schema"+s+" = "+e.util.getData(n.$data,i,e.dataPathArr)+"; ",l="schema"+s):l=n;var p=e.opts.unknownFormats,f=Array.isArray(p);if(h)a+=" var "+(m="format"+s)+" = formats["+l+"]; var "+(v="isObject"+s)+" = typeof "+m+" == 'object' && !("+m+" instanceof RegExp) && "+m+".validate; var "+(y="formatType"+s)+" = "+v+" && "+m+".type || 'string'; if ("+v+") { ",e.async&&(a+=" var async"+s+" = "+m+".async; "),a+=" "+m+" = "+m+".validate; } if ( ",h&&(a+=" ("+l+" !== undefined && typeof "+l+" != 'string') || "),a+=" (","ignore"!=p&&(a+=" ("+l+" && !"+m+" ",f&&(a+=" && self._opts.unknownFormats.indexOf("+l+") == -1 "),a+=") || "),a+=" ("+m+" && "+y+" == '"+r+"' && !(typeof "+m+" == 'function' ? ",e.async?a+=" (async"+s+" ? await "+m+"("+u+") : "+m+"("+u+")) ":a+=" "+m+"("+u+") ",a+=" : "+m+".test("+u+"))))) {";else{var m;if(!(m=e.formats[n])){if("ignore"==p)return e.logger.warn('unknown format "'+n+'" ignored in schema at path "'+e.errSchemaPath+'"'),c&&(a+=" if (true) { "),a;if(f&&p.indexOf(n)>=0)return c&&(a+=" if (true) { "),a;throw new Error('unknown format "'+n+'" is used in schema at path "'+e.errSchemaPath+'"')}var v,y=(v="object"==typeof m&&!(m instanceof RegExp)&&m.validate)&&m.type||"string";if(v){var g=!0===m.async;m=m.validate}if(y!=r)return c&&(a+=" if (true) { "),a;if(g){if(!e.async)throw new Error("async format in sync schema");a+=" if (!(await "+(_="formats"+e.util.getProperty(n)+".validate")+"("+u+"))) { "}else{a+=" if (! ";var _="formats"+e.util.getProperty(n);v&&(_+=".validate"),a+="function"==typeof m?" "+_+"("+u+") ":" "+_+".test("+u+") ",a+=") { "}}var b=b||[];b.push(a),a="",!1!==e.createErrors?(a+=" { keyword: 'format' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(d)+" , params: { format: ",a+=h?""+l:""+e.util.toQuotedString(n),a+=" } ",!1!==e.opts.messages&&(a+=" , message: 'should match format \"",a+=h?"' + "+l+" + '":""+e.util.escapeQuotes(n),a+="\"' "),e.opts.verbose&&(a+=" , schema: ",a+=h?"validate.schema"+o:""+e.util.toQuotedString(n),a+=" , parentSchema: validate.schema"+e.schemaPath+" , data: "+u+" "),a+=" } "):a+=" {} ";var w=a;return a=b.pop(),!e.compositeRule&&c?e.async?a+=" throw new ValidationError(["+w+"]); ":a+=" validate.errors = ["+w+"]; return false; ":a+=" var err = "+w+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",a+=" } ",c&&(a+=" else { "),a}},96111:e=>{"use strict";e.exports=function(e,t,r){var a,s=" ",i=e.level,n=e.dataLevel,o=e.schema[t],d=e.schemaPath+e.util.getProperty(t),c=e.errSchemaPath+"/"+t,u=!e.opts.allErrors,l="data"+(n||""),h=e.opts.$data&&o&&o.$data;if(h?(s+=" var schema"+i+" = "+e.util.getData(o.$data,n,e.dataPathArr)+"; ",a="schema"+i):a=o,!h&&"number"!=typeof o)throw new Error(t+" must be number");s+="if ( ",h&&(s+=" ("+a+" !== undefined && typeof "+a+" != 'number') || "),s+=" Object.keys("+l+").length "+("maxProperties"==t?">":"<")+" "+a+") { ";var p=t,f=f||[];f.push(s),s="",!1!==e.createErrors?(s+=" { keyword: '"+(p||"_limitProperties")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { limit: "+a+" } ",!1!==e.opts.messages&&(s+=" , message: 'should NOT have ",s+="maxProperties"==t?"more":"fewer",s+=" than ",s+=h?"' + "+a+" + '":""+o,s+=" properties' "),e.opts.verbose&&(s+=" , schema: ",s+=h?"validate.schema"+d:""+o,s+=" , parentSchema: validate.schema"+e.schemaPath+" , data: "+l+" "),s+=" } "):s+=" {} ";var m=s;return s=f.pop(),!e.compositeRule&&u?e.async?s+=" throw new ValidationError(["+m+"]); ":s+=" validate.errors = ["+m+"]; return false; ":s+=" var err = "+m+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",s+="} ",u&&(s+=" else { "),s}},96150:(e,t,r)=>{"use strict";var a=r(12269);e.exports={$id:"https://github.com/ajv-validator/ajv/blob/master/lib/definition_schema.js",definitions:{simpleTypes:a.definitions.simpleTypes},type:"object",dependencies:{schema:["validate"],$data:["validate"],statements:["inline"],valid:{not:{required:["macro"]}}},properties:{type:a.properties.type,schema:{type:"boolean"},statements:{type:"boolean"},dependencies:{type:"array",items:{type:"string"}},metaSchema:{type:"object"},modifying:{type:"boolean"},valid:{type:"boolean"},$data:{type:"boolean"},async:{type:"boolean"},errors:{anyOf:[{type:"boolean"},{const:"full"}]}}}},96774:e=>{"use strict";e.exports=function(e,t,r){var a,s=" ",i=e.level,n=e.dataLevel,o=e.schema[t],d=e.schemaPath+e.util.getProperty(t),c=e.errSchemaPath+"/"+t,u=!e.opts.allErrors,l="data"+(n||""),h=e.opts.$data&&o&&o.$data;h?(s+=" var schema"+i+" = "+e.util.getData(o.$data,n,e.dataPathArr)+"; ",a="schema"+i):a=o,s+="if ( ",h&&(s+=" ("+a+" !== undefined && typeof "+a+" != 'string') || "),s+=" !"+(h?"(new RegExp("+a+"))":e.usePattern(o))+".test("+l+") ) { ";var p=p||[];p.push(s),s="",!1!==e.createErrors?(s+=" { keyword: 'pattern' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { pattern: ",s+=h?""+a:""+e.util.toQuotedString(o),s+=" } ",!1!==e.opts.messages&&(s+=" , message: 'should match pattern \"",s+=h?"' + "+a+" + '":""+e.util.escapeQuotes(o),s+="\"' "),e.opts.verbose&&(s+=" , schema: ",s+=h?"validate.schema"+d:""+e.util.toQuotedString(o),s+=" , parentSchema: validate.schema"+e.schemaPath+" , data: "+l+" "),s+=" } "):s+=" {} ";var f=s;return s=p.pop(),!e.compositeRule&&u?e.async?s+=" throw new ValidationError(["+f+"]); ":s+=" validate.errors = ["+f+"]; return false; ":s+=" var err = "+f+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",s+="} ",u&&(s+=" else { "),s}},97145:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ERROR_CODES=t.RuntimeErrorSchema=t.NeedsAuthorizationErrorSchema=t.AuthorizationDisplaySchema=t.DisplayHintSchema=void 0,t.validateNeedsAuthorizationError=function(e){return t.NeedsAuthorizationErrorSchema.safeParse(e)},t.isNeedsAuthorizationError=function(e){return e&&"needs_authorization"===e.error},t.createNeedsAuthorizationError=function(e){return{error:"needs_authorization",...e}};const a=r(90315);t.DisplayHintSchema=a.z.enum(["link","qr","code"]),t.AuthorizationDisplaySchema=a.z.object({title:a.z.string().optional(),hint:a.z.array(t.DisplayHintSchema).optional(),authorizationCode:a.z.string().optional(),qrUrl:a.z.string().url().optional()}).passthrough(),t.NeedsAuthorizationErrorSchema=a.z.object({error:a.z.literal("needs_authorization"),message:a.z.string().min(1),authorizationUrl:a.z.string().url(),resumeToken:a.z.string().min(1),expiresAt:a.z.number().int().positive(),scopes:a.z.array(a.z.string()),display:t.AuthorizationDisplaySchema.optional(),context:a.z.record(a.z.any()).optional()}).passthrough(),t.RuntimeErrorSchema=a.z.object({error:a.z.string().min(1),message:a.z.string().min(1),details:a.z.record(a.z.any()).optional(),httpStatus:a.z.number().int().min(400).max(599).optional()}),t.ERROR_CODES=Object.freeze({NEEDS_AUTHORIZATION:"needs_authorization",INVALID_TOKEN:"invalid_token",TOKEN_EXPIRED:"token_expired",INSUFFICIENT_SCOPE:"insufficient_scope",INVALID_SIGNATURE:"invalid_signature",DELEGATION_REVOKED:"delegation_revoked",CREDENTIAL_REVOKED:"credential_revoked"})},99394:function(e,t,r){"use strict";var a=this&&this.__createBinding||(Object.create?function(e,t,r,a){void 0===a&&(a=r);var s=Object.getOwnPropertyDescriptor(t,r);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,a,s)}:function(e,t,r,a){void 0===a&&(a=r),e[a]=t[r]}),s=this&&this.__exportStar||function(e,t){for(var r in e)"default"===r||Object.prototype.hasOwnProperty.call(t,r)||a(t,e,r)};Object.defineProperty(t,"__esModule",{value:!0}),s(r(80630),t),s(r(70926),t),s(r(61763),t),s(r(27165),t),s(r(44242),t),s(r(68820),t)}},t={};function r(a){var s=t[a];if(void 0!==s)return s.exports;var i=t[a]={exports:{}};return e[a].call(i.exports,i,i.exports,r),i.exports}r.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),(()=>{"use strict";const e=require("node:process");var t,a;!function(e){e.assertEqual=e=>{},e.assertIs=function(e){},e.assertNever=function(e){throw new Error},e.arrayToEnum=e=>{const t={};for(const r of e)t[r]=r;return t},e.getValidEnumValues=t=>{const r=e.objectKeys(t).filter(e=>"number"!=typeof t[t[e]]),a={};for(const e of r)a[e]=t[e];return e.objectValues(a)},e.objectValues=t=>e.objectKeys(t).map(function(e){return t[e]}),e.objectKeys="function"==typeof Object.keys?e=>Object.keys(e):e=>{const t=[];for(const r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.push(r);return t},e.find=(e,t)=>{for(const r of e)if(t(r))return r},e.isInteger="function"==typeof Number.isInteger?e=>Number.isInteger(e):e=>"number"==typeof e&&Number.isFinite(e)&&Math.floor(e)===e,e.joinValues=function(e,t=" | "){return e.map(e=>"string"==typeof e?`'${e}'`:e).join(t)},e.jsonStringifyReplacer=(e,t)=>"bigint"==typeof t?t.toString():t}(t||(t={})),function(e){e.mergeShapes=(e,t)=>({...e,...t})}(a||(a={}));const s=t.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),i=e=>{switch(typeof e){case"undefined":return s.undefined;case"string":return s.string;case"number":return Number.isNaN(e)?s.nan:s.number;case"boolean":return s.boolean;case"function":return s.function;case"bigint":return s.bigint;case"symbol":return s.symbol;case"object":return Array.isArray(e)?s.array:null===e?s.null:e.then&&"function"==typeof e.then&&e.catch&&"function"==typeof e.catch?s.promise:"undefined"!=typeof Map&&e instanceof Map?s.map:"undefined"!=typeof Set&&e instanceof Set?s.set:"undefined"!=typeof Date&&e instanceof Date?s.date:s.object;default:return s.unknown}},n=t.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"]);class o extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=e=>{this.issues=[...this.issues,e]},this.addIssues=(e=[])=>{this.issues=[...this.issues,...e]};const t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name="ZodError",this.issues=e}format(e){const t=e||function(e){return e.message},r={_errors:[]},a=e=>{for(const s of e.issues)if("invalid_union"===s.code)s.unionErrors.map(a);else if("invalid_return_type"===s.code)a(s.returnTypeError);else if("invalid_arguments"===s.code)a(s.argumentsError);else if(0===s.path.length)r._errors.push(t(s));else{let e=r,a=0;for(;a<s.path.length;){const r=s.path[a];a===s.path.length-1?(e[r]=e[r]||{_errors:[]},e[r]._errors.push(t(s))):e[r]=e[r]||{_errors:[]},e=e[r],a++}}};return a(this),r}static assert(e){if(!(e instanceof o))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,t.jsonStringifyReplacer,2)}get isEmpty(){return 0===this.issues.length}flatten(e=e=>e.message){const t={},r=[];for(const a of this.issues)if(a.path.length>0){const r=a.path[0];t[r]=t[r]||[],t[r].push(e(a))}else r.push(e(a));return{formErrors:r,fieldErrors:t}}get formErrors(){return this.flatten()}}o.create=e=>new o(e);const d=(e,r)=>{let a;switch(e.code){case n.invalid_type:a=e.received===s.undefined?"Required":`Expected ${e.expected}, received ${e.received}`;break;case n.invalid_literal:a=`Invalid literal value, expected ${JSON.stringify(e.expected,t.jsonStringifyReplacer)}`;break;case n.unrecognized_keys:a=`Unrecognized key(s) in object: ${t.joinValues(e.keys,", ")}`;break;case n.invalid_union:a="Invalid input";break;case n.invalid_union_discriminator:a=`Invalid discriminator value. Expected ${t.joinValues(e.options)}`;break;case n.invalid_enum_value:a=`Invalid enum value. Expected ${t.joinValues(e.options)}, received '${e.received}'`;break;case n.invalid_arguments:a="Invalid function arguments";break;case n.invalid_return_type:a="Invalid function return type";break;case n.invalid_date:a="Invalid date";break;case n.invalid_string:"object"==typeof e.validation?"includes"in e.validation?(a=`Invalid input: must include "${e.validation.includes}"`,"number"==typeof e.validation.position&&(a=`${a} at one or more positions greater than or equal to ${e.validation.position}`)):"startsWith"in e.validation?a=`Invalid input: must start with "${e.validation.startsWith}"`:"endsWith"in e.validation?a=`Invalid input: must end with "${e.validation.endsWith}"`:t.assertNever(e.validation):a="regex"!==e.validation?`Invalid ${e.validation}`:"Invalid";break;case n.too_small:a="array"===e.type?`Array must contain ${e.exact?"exactly":e.inclusive?"at least":"more than"} ${e.minimum} element(s)`:"string"===e.type?`String must contain ${e.exact?"exactly":e.inclusive?"at least":"over"} ${e.minimum} character(s)`:"number"===e.type||"bigint"===e.type?`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:"date"===e.type?`Date must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(e.minimum))}`:"Invalid input";break;case n.too_big:a="array"===e.type?`Array must contain ${e.exact?"exactly":e.inclusive?"at most":"less than"} ${e.maximum} element(s)`:"string"===e.type?`String must contain ${e.exact?"exactly":e.inclusive?"at most":"under"} ${e.maximum} character(s)`:"number"===e.type?`Number must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:"bigint"===e.type?`BigInt must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:"date"===e.type?`Date must be ${e.exact?"exactly":e.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(e.maximum))}`:"Invalid input";break;case n.custom:a="Invalid input";break;case n.invalid_intersection_types:a="Intersection results could not be merged";break;case n.not_multiple_of:a=`Number must be a multiple of ${e.multipleOf}`;break;case n.not_finite:a="Number must be finite";break;default:a=r.defaultError,t.assertNever(e)}return{message:a}};let c=d;var u;!function(e){e.errToObj=e=>"string"==typeof e?{message:e}:e||{},e.toString=e=>"string"==typeof e?e:e?.message}(u||(u={}));function l(e,t){const r=c,a=(e=>{const{data:t,path:r,errorMaps:a,issueData:s}=e,i=[...r,...s.path||[]],n={...s,path:i};if(void 0!==s.message)return{...s,path:i,message:s.message};let o="";const d=a.filter(e=>!!e).slice().reverse();for(const e of d)o=e(n,{data:t,defaultError:o}).message;return{...s,path:i,message:o}})({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,r,r===d?void 0:d].filter(e=>!!e)});e.common.issues.push(a)}class h{constructor(){this.value="valid"}dirty(){"valid"===this.value&&(this.value="dirty")}abort(){"aborted"!==this.value&&(this.value="aborted")}static mergeArray(e,t){const r=[];for(const a of t){if("aborted"===a.status)return p;"dirty"===a.status&&e.dirty(),r.push(a.value)}return{status:e.value,value:r}}static async mergeObjectAsync(e,t){const r=[];for(const e of t){const t=await e.key,a=await e.value;r.push({key:t,value:a})}return h.mergeObjectSync(e,r)}static mergeObjectSync(e,t){const r={};for(const a of t){const{key:t,value:s}=a;if("aborted"===t.status)return p;if("aborted"===s.status)return p;"dirty"===t.status&&e.dirty(),"dirty"===s.status&&e.dirty(),"__proto__"===t.value||void 0===s.value&&!a.alwaysSet||(r[t.value]=s.value)}return{status:e.value,value:r}}}const p=Object.freeze({status:"aborted"}),f=e=>({status:"dirty",value:e}),m=e=>({status:"valid",value:e}),v=e=>"aborted"===e.status,y=e=>"dirty"===e.status,g=e=>"valid"===e.status,_=e=>"undefined"!=typeof Promise&&e instanceof Promise;class b{constructor(e,t,r,a){this._cachedPath=[],this.parent=e,this.data=t,this._path=r,this._key=a}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}}const w=(e,t)=>{if(g(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;const t=new o(e.common.issues);return this._error=t,this._error}}};function P(e){if(!e)return{};const{errorMap:t,invalid_type_error:r,required_error:a,description:s}=e;if(t&&(r||a))throw new Error('Can\'t use "invalid_type_error" or "required_error" in conjunction with custom error map.');return t?{errorMap:t,description:s}:{errorMap:(t,s)=>{const{message:i}=e;return"invalid_enum_value"===t.code?{message:i??s.defaultError}:void 0===s.data?{message:i??a??s.defaultError}:"invalid_type"!==t.code?{message:s.defaultError}:{message:i??r??s.defaultError}},description:s}}class E{get description(){return this._def.description}_getType(e){return i(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:i(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new h,ctx:{common:e.parent.common,data:e.data,parsedType:i(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const t=this._parse(e);if(_(t))throw new Error("Synchronous parse encountered promise.");return t}_parseAsync(e){const t=this._parse(e);return Promise.resolve(t)}parse(e,t){const r=this.safeParse(e,t);if(r.success)return r.data;throw r.error}safeParse(e,t){const r={common:{issues:[],async:t?.async??!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:i(e)},a=this._parseSync({data:e,path:r.path,parent:r});return w(r,a)}"~validate"(e){const t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:i(e)};if(!this["~standard"].async)try{const r=this._parseSync({data:e,path:[],parent:t});return g(r)?{value:r.value}:{issues:t.common.issues}}catch(e){e?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then(e=>g(e)?{value:e.value}:{issues:t.common.issues})}async parseAsync(e,t){const r=await this.safeParseAsync(e,t);if(r.success)return r.data;throw r.error}async safeParseAsync(e,t){const r={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:i(e)},a=this._parse({data:e,path:r.path,parent:r}),s=await(_(a)?a:Promise.resolve(a));return w(r,s)}refine(e,t){const r=e=>"string"==typeof t||void 0===t?{message:t}:"function"==typeof t?t(e):t;return this._refinement((t,a)=>{const s=e(t),i=()=>a.addIssue({code:n.custom,...r(t)});return"undefined"!=typeof Promise&&s instanceof Promise?s.then(e=>!!e||(i(),!1)):!!s||(i(),!1)})}refinement(e,t){return this._refinement((r,a)=>!!e(r)||(a.addIssue("function"==typeof t?t(r,a):t),!1))}_refinement(e){return new xe({schema:this,typeName:De.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:e=>this["~validate"](e)}}optional(){return Se.create(this,this._def)}nullable(){return Ie.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return ne.create(this)}promise(){return Ee.create(this,this._def)}or(e){return ce.create([this,e],this._def)}and(e){return pe.create(this,e,this._def)}transform(e){return new xe({...P(this._def),schema:this,typeName:De.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const t="function"==typeof e?e:()=>e;return new ke({...P(this._def),innerType:this,defaultValue:t,typeName:De.ZodDefault})}brand(){return new Ae({typeName:De.ZodBranded,type:this,...P(this._def)})}catch(e){const t="function"==typeof e?e:()=>e;return new Te({...P(this._def),innerType:this,catchValue:t,typeName:De.ZodCatch})}describe(e){return new(0,this.constructor)({...this._def,description:e})}pipe(e){return Oe.create(this,e)}readonly(){return Re.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const x=/^c[^\s-]{8,}$/i,S=/^[0-9a-z]+$/,I=/^[0-9A-HJKMNP-TV-Z]{26}$/i,k=/^[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,T=/^[a-z0-9_-]{21}$/i,C=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,A=/^[-+]?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)?)??$/,O=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;let R;const D=/^(?:(?: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])$/,N=/^(?:(?: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])$/,Z=/^(([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]))$/,$=/^(([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])$/,j=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,F=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,M="((\\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])))",L=new RegExp(`^${M}$`);function z(e){let t="[0-5]\\d";return e.precision?t=`${t}\\.\\d{${e.precision}}`:null==e.precision&&(t=`${t}(\\.\\d+)?`),`([01]\\d|2[0-3]):[0-5]\\d(:${t})${e.precision?"+":"?"}`}function V(e){return new RegExp(`^${z(e)}$`)}function q(e){let t=`${M}T${z(e)}`;const r=[];return r.push(e.local?"Z?":"Z"),e.offset&&r.push("([+-]\\d{2}:?\\d{2})"),t=`${t}(${r.join("|")})`,new RegExp(`^${t}$`)}function U(e,t){return!("v4"!==t&&t||!D.test(e))||!("v6"!==t&&t||!Z.test(e))}function K(e,t){if(!C.test(e))return!1;try{const[r]=e.split(".");if(!r)return!1;const a=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.length%4)%4,"="),s=JSON.parse(atob(a));return!("object"!=typeof s||null===s||"typ"in s&&"JWT"!==s?.typ||!s.alg||t&&s.alg!==t)}catch{return!1}}function H(e,t){return!("v4"!==t&&t||!N.test(e))||!("v6"!==t&&t||!$.test(e))}class B extends E{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==s.string){const t=this._getOrReturnCtx(e);return l(t,{code:n.invalid_type,expected:s.string,received:t.parsedType}),p}const r=new h;let a;for(const s of this._def.checks)if("min"===s.kind)e.data.length<s.value&&(a=this._getOrReturnCtx(e,a),l(a,{code:n.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),r.dirty());else if("max"===s.kind)e.data.length>s.value&&(a=this._getOrReturnCtx(e,a),l(a,{code:n.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),r.dirty());else if("length"===s.kind){const t=e.data.length>s.value,i=e.data.length<s.value;(t||i)&&(a=this._getOrReturnCtx(e,a),t?l(a,{code:n.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}):i&&l(a,{code:n.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}),r.dirty())}else if("email"===s.kind)O.test(e.data)||(a=this._getOrReturnCtx(e,a),l(a,{validation:"email",code:n.invalid_string,message:s.message}),r.dirty());else if("emoji"===s.kind)R||(R=new RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),R.test(e.data)||(a=this._getOrReturnCtx(e,a),l(a,{validation:"emoji",code:n.invalid_string,message:s.message}),r.dirty());else if("uuid"===s.kind)k.test(e.data)||(a=this._getOrReturnCtx(e,a),l(a,{validation:"uuid",code:n.invalid_string,message:s.message}),r.dirty());else if("nanoid"===s.kind)T.test(e.data)||(a=this._getOrReturnCtx(e,a),l(a,{validation:"nanoid",code:n.invalid_string,message:s.message}),r.dirty());else if("cuid"===s.kind)x.test(e.data)||(a=this._getOrReturnCtx(e,a),l(a,{validation:"cuid",code:n.invalid_string,message:s.message}),r.dirty());else if("cuid2"===s.kind)S.test(e.data)||(a=this._getOrReturnCtx(e,a),l(a,{validation:"cuid2",code:n.invalid_string,message:s.message}),r.dirty());else if("ulid"===s.kind)I.test(e.data)||(a=this._getOrReturnCtx(e,a),l(a,{validation:"ulid",code:n.invalid_string,message:s.message}),r.dirty());else if("url"===s.kind)try{new URL(e.data)}catch{a=this._getOrReturnCtx(e,a),l(a,{validation:"url",code:n.invalid_string,message:s.message}),r.dirty()}else"regex"===s.kind?(s.regex.lastIndex=0,s.regex.test(e.data)||(a=this._getOrReturnCtx(e,a),l(a,{validation:"regex",code:n.invalid_string,message:s.message}),r.dirty())):"trim"===s.kind?e.data=e.data.trim():"includes"===s.kind?e.data.includes(s.value,s.position)||(a=this._getOrReturnCtx(e,a),l(a,{code:n.invalid_string,validation:{includes:s.value,position:s.position},message:s.message}),r.dirty()):"toLowerCase"===s.kind?e.data=e.data.toLowerCase():"toUpperCase"===s.kind?e.data=e.data.toUpperCase():"startsWith"===s.kind?e.data.startsWith(s.value)||(a=this._getOrReturnCtx(e,a),l(a,{code:n.invalid_string,validation:{startsWith:s.value},message:s.message}),r.dirty()):"endsWith"===s.kind?e.data.endsWith(s.value)||(a=this._getOrReturnCtx(e,a),l(a,{code:n.invalid_string,validation:{endsWith:s.value},message:s.message}),r.dirty()):"datetime"===s.kind?q(s).test(e.data)||(a=this._getOrReturnCtx(e,a),l(a,{code:n.invalid_string,validation:"datetime",message:s.message}),r.dirty()):"date"===s.kind?L.test(e.data)||(a=this._getOrReturnCtx(e,a),l(a,{code:n.invalid_string,validation:"date",message:s.message}),r.dirty()):"time"===s.kind?V(s).test(e.data)||(a=this._getOrReturnCtx(e,a),l(a,{code:n.invalid_string,validation:"time",message:s.message}),r.dirty()):"duration"===s.kind?A.test(e.data)||(a=this._getOrReturnCtx(e,a),l(a,{validation:"duration",code:n.invalid_string,message:s.message}),r.dirty()):"ip"===s.kind?U(e.data,s.version)||(a=this._getOrReturnCtx(e,a),l(a,{validation:"ip",code:n.invalid_string,message:s.message}),r.dirty()):"jwt"===s.kind?K(e.data,s.alg)||(a=this._getOrReturnCtx(e,a),l(a,{validation:"jwt",code:n.invalid_string,message:s.message}),r.dirty()):"cidr"===s.kind?H(e.data,s.version)||(a=this._getOrReturnCtx(e,a),l(a,{validation:"cidr",code:n.invalid_string,message:s.message}),r.dirty()):"base64"===s.kind?j.test(e.data)||(a=this._getOrReturnCtx(e,a),l(a,{validation:"base64",code:n.invalid_string,message:s.message}),r.dirty()):"base64url"===s.kind?F.test(e.data)||(a=this._getOrReturnCtx(e,a),l(a,{validation:"base64url",code:n.invalid_string,message:s.message}),r.dirty()):t.assertNever(s);return{status:r.value,value:e.data}}_regex(e,t,r){return this.refinement(t=>e.test(t),{validation:t,code:n.invalid_string,...u.errToObj(r)})}_addCheck(e){return new B({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...u.errToObj(e)})}url(e){return this._addCheck({kind:"url",...u.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...u.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...u.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...u.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...u.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...u.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...u.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...u.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...u.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...u.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...u.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...u.errToObj(e)})}datetime(e){return"string"==typeof e?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:void 0===e?.precision?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...u.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return"string"==typeof e?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:void 0===e?.precision?null:e?.precision,...u.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...u.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...u.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t?.position,...u.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...u.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...u.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...u.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...u.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...u.errToObj(t)})}nonempty(e){return this.min(1,u.errToObj(e))}trim(){return new B({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new B({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new B({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>"datetime"===e.kind)}get isDate(){return!!this._def.checks.find(e=>"date"===e.kind)}get isTime(){return!!this._def.checks.find(e=>"time"===e.kind)}get isDuration(){return!!this._def.checks.find(e=>"duration"===e.kind)}get isEmail(){return!!this._def.checks.find(e=>"email"===e.kind)}get isURL(){return!!this._def.checks.find(e=>"url"===e.kind)}get isEmoji(){return!!this._def.checks.find(e=>"emoji"===e.kind)}get isUUID(){return!!this._def.checks.find(e=>"uuid"===e.kind)}get isNANOID(){return!!this._def.checks.find(e=>"nanoid"===e.kind)}get isCUID(){return!!this._def.checks.find(e=>"cuid"===e.kind)}get isCUID2(){return!!this._def.checks.find(e=>"cuid2"===e.kind)}get isULID(){return!!this._def.checks.find(e=>"ulid"===e.kind)}get isIP(){return!!this._def.checks.find(e=>"ip"===e.kind)}get isCIDR(){return!!this._def.checks.find(e=>"cidr"===e.kind)}get isBase64(){return!!this._def.checks.find(e=>"base64"===e.kind)}get isBase64url(){return!!this._def.checks.find(e=>"base64url"===e.kind)}get minLength(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}}function Q(e,t){const r=(e.toString().split(".")[1]||"").length,a=(t.toString().split(".")[1]||"").length,s=r>a?r:a;return Number.parseInt(e.toFixed(s).replace(".",""))%Number.parseInt(t.toFixed(s).replace(".",""))/10**s}B.create=e=>new B({checks:[],typeName:De.ZodString,coerce:e?.coerce??!1,...P(e)});class J extends E{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==s.number){const t=this._getOrReturnCtx(e);return l(t,{code:n.invalid_type,expected:s.number,received:t.parsedType}),p}let r;const a=new h;for(const s of this._def.checks)"int"===s.kind?t.isInteger(e.data)||(r=this._getOrReturnCtx(e,r),l(r,{code:n.invalid_type,expected:"integer",received:"float",message:s.message}),a.dirty()):"min"===s.kind?(s.inclusive?e.data<s.value:e.data<=s.value)&&(r=this._getOrReturnCtx(e,r),l(r,{code:n.too_small,minimum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),a.dirty()):"max"===s.kind?(s.inclusive?e.data>s.value:e.data>=s.value)&&(r=this._getOrReturnCtx(e,r),l(r,{code:n.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),a.dirty()):"multipleOf"===s.kind?0!==Q(e.data,s.value)&&(r=this._getOrReturnCtx(e,r),l(r,{code:n.not_multiple_of,multipleOf:s.value,message:s.message}),a.dirty()):"finite"===s.kind?Number.isFinite(e.data)||(r=this._getOrReturnCtx(e,r),l(r,{code:n.not_finite,message:s.message}),a.dirty()):t.assertNever(s);return{status:a.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,u.toString(t))}gt(e,t){return this.setLimit("min",e,!1,u.toString(t))}lte(e,t){return this.setLimit("max",e,!0,u.toString(t))}lt(e,t){return this.setLimit("max",e,!1,u.toString(t))}setLimit(e,t,r,a){return new J({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:u.toString(a)}]})}_addCheck(e){return new J({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:u.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:u.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:u.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:u.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:u.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:u.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:u.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:u.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:u.toString(e)})}get minValue(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find(e=>"int"===e.kind||"multipleOf"===e.kind&&t.isInteger(e.value))}get isFinite(){let e=null,t=null;for(const r of this._def.checks){if("finite"===r.kind||"int"===r.kind||"multipleOf"===r.kind)return!0;"min"===r.kind?(null===t||r.value>t)&&(t=r.value):"max"===r.kind&&(null===e||r.value<e)&&(e=r.value)}return Number.isFinite(t)&&Number.isFinite(e)}}J.create=e=>new J({checks:[],typeName:De.ZodNumber,coerce:e?.coerce||!1,...P(e)});class W extends E{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==s.bigint)return this._getInvalidInput(e);let r;const a=new h;for(const s of this._def.checks)"min"===s.kind?(s.inclusive?e.data<s.value:e.data<=s.value)&&(r=this._getOrReturnCtx(e,r),l(r,{code:n.too_small,type:"bigint",minimum:s.value,inclusive:s.inclusive,message:s.message}),a.dirty()):"max"===s.kind?(s.inclusive?e.data>s.value:e.data>=s.value)&&(r=this._getOrReturnCtx(e,r),l(r,{code:n.too_big,type:"bigint",maximum:s.value,inclusive:s.inclusive,message:s.message}),a.dirty()):"multipleOf"===s.kind?e.data%s.value!==BigInt(0)&&(r=this._getOrReturnCtx(e,r),l(r,{code:n.not_multiple_of,multipleOf:s.value,message:s.message}),a.dirty()):t.assertNever(s);return{status:a.value,value:e.data}}_getInvalidInput(e){const t=this._getOrReturnCtx(e);return l(t,{code:n.invalid_type,expected:s.bigint,received:t.parsedType}),p}gte(e,t){return this.setLimit("min",e,!0,u.toString(t))}gt(e,t){return this.setLimit("min",e,!1,u.toString(t))}lte(e,t){return this.setLimit("max",e,!0,u.toString(t))}lt(e,t){return this.setLimit("max",e,!1,u.toString(t))}setLimit(e,t,r,a){return new W({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:u.toString(a)}]})}_addCheck(e){return new W({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:u.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:u.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:u.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:u.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:u.toString(t)})}get minValue(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}}W.create=e=>new W({checks:[],typeName:De.ZodBigInt,coerce:e?.coerce??!1,...P(e)});class G extends E{_parse(e){if(this._def.coerce&&(e.data=Boolean(e.data)),this._getType(e)!==s.boolean){const t=this._getOrReturnCtx(e);return l(t,{code:n.invalid_type,expected:s.boolean,received:t.parsedType}),p}return m(e.data)}}G.create=e=>new G({typeName:De.ZodBoolean,coerce:e?.coerce||!1,...P(e)});class Y extends E{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==s.date){const t=this._getOrReturnCtx(e);return l(t,{code:n.invalid_type,expected:s.date,received:t.parsedType}),p}if(Number.isNaN(e.data.getTime()))return l(this._getOrReturnCtx(e),{code:n.invalid_date}),p;const r=new h;let a;for(const s of this._def.checks)"min"===s.kind?e.data.getTime()<s.value&&(a=this._getOrReturnCtx(e,a),l(a,{code:n.too_small,message:s.message,inclusive:!0,exact:!1,minimum:s.value,type:"date"}),r.dirty()):"max"===s.kind?e.data.getTime()>s.value&&(a=this._getOrReturnCtx(e,a),l(a,{code:n.too_big,message:s.message,inclusive:!0,exact:!1,maximum:s.value,type:"date"}),r.dirty()):t.assertNever(s);return{status:r.value,value:new Date(e.data.getTime())}}_addCheck(e){return new Y({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:u.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:u.toString(t)})}get minDate(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return null!=e?new Date(e):null}get maxDate(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return null!=e?new Date(e):null}}Y.create=e=>new Y({checks:[],coerce:e?.coerce||!1,typeName:De.ZodDate,...P(e)});class X extends E{_parse(e){if(this._getType(e)!==s.symbol){const t=this._getOrReturnCtx(e);return l(t,{code:n.invalid_type,expected:s.symbol,received:t.parsedType}),p}return m(e.data)}}X.create=e=>new X({typeName:De.ZodSymbol,...P(e)});class ee extends E{_parse(e){if(this._getType(e)!==s.undefined){const t=this._getOrReturnCtx(e);return l(t,{code:n.invalid_type,expected:s.undefined,received:t.parsedType}),p}return m(e.data)}}ee.create=e=>new ee({typeName:De.ZodUndefined,...P(e)});class te extends E{_parse(e){if(this._getType(e)!==s.null){const t=this._getOrReturnCtx(e);return l(t,{code:n.invalid_type,expected:s.null,received:t.parsedType}),p}return m(e.data)}}te.create=e=>new te({typeName:De.ZodNull,...P(e)});class re extends E{constructor(){super(...arguments),this._any=!0}_parse(e){return m(e.data)}}re.create=e=>new re({typeName:De.ZodAny,...P(e)});class ae extends E{constructor(){super(...arguments),this._unknown=!0}_parse(e){return m(e.data)}}ae.create=e=>new ae({typeName:De.ZodUnknown,...P(e)});class se extends E{_parse(e){const t=this._getOrReturnCtx(e);return l(t,{code:n.invalid_type,expected:s.never,received:t.parsedType}),p}}se.create=e=>new se({typeName:De.ZodNever,...P(e)});class ie extends E{_parse(e){if(this._getType(e)!==s.undefined){const t=this._getOrReturnCtx(e);return l(t,{code:n.invalid_type,expected:s.void,received:t.parsedType}),p}return m(e.data)}}ie.create=e=>new ie({typeName:De.ZodVoid,...P(e)});class ne extends E{_parse(e){const{ctx:t,status:r}=this._processInputParams(e),a=this._def;if(t.parsedType!==s.array)return l(t,{code:n.invalid_type,expected:s.array,received:t.parsedType}),p;if(null!==a.exactLength){const e=t.data.length>a.exactLength.value,s=t.data.length<a.exactLength.value;(e||s)&&(l(t,{code:e?n.too_big:n.too_small,minimum:s?a.exactLength.value:void 0,maximum:e?a.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:a.exactLength.message}),r.dirty())}if(null!==a.minLength&&t.data.length<a.minLength.value&&(l(t,{code:n.too_small,minimum:a.minLength.value,type:"array",inclusive:!0,exact:!1,message:a.minLength.message}),r.dirty()),null!==a.maxLength&&t.data.length>a.maxLength.value&&(l(t,{code:n.too_big,maximum:a.maxLength.value,type:"array",inclusive:!0,exact:!1,message:a.maxLength.message}),r.dirty()),t.common.async)return Promise.all([...t.data].map((e,r)=>a.type._parseAsync(new b(t,e,t.path,r)))).then(e=>h.mergeArray(r,e));const i=[...t.data].map((e,r)=>a.type._parseSync(new b(t,e,t.path,r)));return h.mergeArray(r,i)}get element(){return this._def.type}min(e,t){return new ne({...this._def,minLength:{value:e,message:u.toString(t)}})}max(e,t){return new ne({...this._def,maxLength:{value:e,message:u.toString(t)}})}length(e,t){return new ne({...this._def,exactLength:{value:e,message:u.toString(t)}})}nonempty(e){return this.min(1,e)}}function oe(e){if(e instanceof de){const t={};for(const r in e.shape){const a=e.shape[r];t[r]=Se.create(oe(a))}return new de({...e._def,shape:()=>t})}return e instanceof ne?new ne({...e._def,type:oe(e.element)}):e instanceof Se?Se.create(oe(e.unwrap())):e instanceof Ie?Ie.create(oe(e.unwrap())):e instanceof fe?fe.create(e.items.map(e=>oe(e))):e}ne.create=(e,t)=>new ne({type:e,minLength:null,maxLength:null,exactLength:null,typeName:De.ZodArray,...P(t)});class de extends E{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(null!==this._cached)return this._cached;const e=this._def.shape(),r=t.objectKeys(e);return this._cached={shape:e,keys:r},this._cached}_parse(e){if(this._getType(e)!==s.object){const t=this._getOrReturnCtx(e);return l(t,{code:n.invalid_type,expected:s.object,received:t.parsedType}),p}const{status:t,ctx:r}=this._processInputParams(e),{shape:a,keys:i}=this._getCached(),o=[];if(!(this._def.catchall instanceof se&&"strip"===this._def.unknownKeys))for(const e in r.data)i.includes(e)||o.push(e);const d=[];for(const e of i){const t=a[e],s=r.data[e];d.push({key:{status:"valid",value:e},value:t._parse(new b(r,s,r.path,e)),alwaysSet:e in r.data})}if(this._def.catchall instanceof se){const e=this._def.unknownKeys;if("passthrough"===e)for(const e of o)d.push({key:{status:"valid",value:e},value:{status:"valid",value:r.data[e]}});else if("strict"===e)o.length>0&&(l(r,{code:n.unrecognized_keys,keys:o}),t.dirty());else if("strip"!==e)throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const e=this._def.catchall;for(const t of o){const a=r.data[t];d.push({key:{status:"valid",value:t},value:e._parse(new b(r,a,r.path,t)),alwaysSet:t in r.data})}}return r.common.async?Promise.resolve().then(async()=>{const e=[];for(const t of d){const r=await t.key,a=await t.value;e.push({key:r,value:a,alwaysSet:t.alwaysSet})}return e}).then(e=>h.mergeObjectSync(t,e)):h.mergeObjectSync(t,d)}get shape(){return this._def.shape()}strict(e){return u.errToObj,new de({...this._def,unknownKeys:"strict",...void 0!==e?{errorMap:(t,r)=>{const a=this._def.errorMap?.(t,r).message??r.defaultError;return"unrecognized_keys"===t.code?{message:u.errToObj(e).message??a}:{message:a}}}:{}})}strip(){return new de({...this._def,unknownKeys:"strip"})}passthrough(){return new de({...this._def,unknownKeys:"passthrough"})}extend(e){return new de({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new de({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:De.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new de({...this._def,catchall:e})}pick(e){const r={};for(const a of t.objectKeys(e))e[a]&&this.shape[a]&&(r[a]=this.shape[a]);return new de({...this._def,shape:()=>r})}omit(e){const r={};for(const a of t.objectKeys(this.shape))e[a]||(r[a]=this.shape[a]);return new de({...this._def,shape:()=>r})}deepPartial(){return oe(this)}partial(e){const r={};for(const a of t.objectKeys(this.shape)){const t=this.shape[a];e&&!e[a]?r[a]=t:r[a]=t.optional()}return new de({...this._def,shape:()=>r})}required(e){const r={};for(const a of t.objectKeys(this.shape))if(e&&!e[a])r[a]=this.shape[a];else{let e=this.shape[a];for(;e instanceof Se;)e=e._def.innerType;r[a]=e}return new de({...this._def,shape:()=>r})}keyof(){return be(t.objectKeys(this.shape))}}de.create=(e,t)=>new de({shape:()=>e,unknownKeys:"strip",catchall:se.create(),typeName:De.ZodObject,...P(t)}),de.strictCreate=(e,t)=>new de({shape:()=>e,unknownKeys:"strict",catchall:se.create(),typeName:De.ZodObject,...P(t)}),de.lazycreate=(e,t)=>new de({shape:e,unknownKeys:"strip",catchall:se.create(),typeName:De.ZodObject,...P(t)});class ce extends E{_parse(e){const{ctx:t}=this._processInputParams(e),r=this._def.options;if(t.common.async)return Promise.all(r.map(async e=>{const r={...t,common:{...t.common,issues:[]},parent:null};return{result:await e._parseAsync({data:t.data,path:t.path,parent:r}),ctx:r}})).then(function(e){for(const t of e)if("valid"===t.result.status)return t.result;for(const r of e)if("dirty"===r.result.status)return t.common.issues.push(...r.ctx.common.issues),r.result;const r=e.map(e=>new o(e.ctx.common.issues));return l(t,{code:n.invalid_union,unionErrors:r}),p});{let e;const a=[];for(const s of r){const r={...t,common:{...t.common,issues:[]},parent:null},i=s._parseSync({data:t.data,path:t.path,parent:r});if("valid"===i.status)return i;"dirty"!==i.status||e||(e={result:i,ctx:r}),r.common.issues.length&&a.push(r.common.issues)}if(e)return t.common.issues.push(...e.ctx.common.issues),e.result;const s=a.map(e=>new o(e));return l(t,{code:n.invalid_union,unionErrors:s}),p}}get options(){return this._def.options}}ce.create=(e,t)=>new ce({options:e,typeName:De.ZodUnion,...P(t)});const ue=e=>e instanceof ge?ue(e.schema):e instanceof xe?ue(e.innerType()):e instanceof _e?[e.value]:e instanceof we?e.options:e instanceof Pe?t.objectValues(e.enum):e instanceof ke?ue(e._def.innerType):e instanceof ee?[void 0]:e instanceof te?[null]:e instanceof Se?[void 0,...ue(e.unwrap())]:e instanceof Ie?[null,...ue(e.unwrap())]:e instanceof Ae||e instanceof Re?ue(e.unwrap()):e instanceof Te?ue(e._def.innerType):[];class le extends E{_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==s.object)return l(t,{code:n.invalid_type,expected:s.object,received:t.parsedType}),p;const r=this.discriminator,a=t.data[r],i=this.optionsMap.get(a);return i?t.common.async?i._parseAsync({data:t.data,path:t.path,parent:t}):i._parseSync({data:t.data,path:t.path,parent:t}):(l(t,{code:n.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),p)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,t,r){const a=new Map;for(const r of t){const t=ue(r.shape[e]);if(!t.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(const s of t){if(a.has(s))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(s)}`);a.set(s,r)}}return new le({typeName:De.ZodDiscriminatedUnion,discriminator:e,options:t,optionsMap:a,...P(r)})}}function he(e,r){const a=i(e),n=i(r);if(e===r)return{valid:!0,data:e};if(a===s.object&&n===s.object){const a=t.objectKeys(r),s=t.objectKeys(e).filter(e=>-1!==a.indexOf(e)),i={...e,...r};for(const t of s){const a=he(e[t],r[t]);if(!a.valid)return{valid:!1};i[t]=a.data}return{valid:!0,data:i}}if(a===s.array&&n===s.array){if(e.length!==r.length)return{valid:!1};const t=[];for(let a=0;a<e.length;a++){const s=he(e[a],r[a]);if(!s.valid)return{valid:!1};t.push(s.data)}return{valid:!0,data:t}}return a===s.date&&n===s.date&&+e===+r?{valid:!0,data:e}:{valid:!1}}class pe extends E{_parse(e){const{status:t,ctx:r}=this._processInputParams(e),a=(e,a)=>{if(v(e)||v(a))return p;const s=he(e.value,a.value);return s.valid?((y(e)||y(a))&&t.dirty(),{status:t.value,value:s.data}):(l(r,{code:n.invalid_intersection_types}),p)};return r.common.async?Promise.all([this._def.left._parseAsync({data:r.data,path:r.path,parent:r}),this._def.right._parseAsync({data:r.data,path:r.path,parent:r})]).then(([e,t])=>a(e,t)):a(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}}pe.create=(e,t,r)=>new pe({left:e,right:t,typeName:De.ZodIntersection,...P(r)});class fe extends E{_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==s.array)return l(r,{code:n.invalid_type,expected:s.array,received:r.parsedType}),p;if(r.data.length<this._def.items.length)return l(r,{code:n.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),p;!this._def.rest&&r.data.length>this._def.items.length&&(l(r,{code:n.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());const a=[...r.data].map((e,t)=>{const a=this._def.items[t]||this._def.rest;return a?a._parse(new b(r,e,r.path,t)):null}).filter(e=>!!e);return r.common.async?Promise.all(a).then(e=>h.mergeArray(t,e)):h.mergeArray(t,a)}get items(){return this._def.items}rest(e){return new fe({...this._def,rest:e})}}fe.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new fe({items:e,typeName:De.ZodTuple,rest:null,...P(t)})};class me extends E{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==s.object)return l(r,{code:n.invalid_type,expected:s.object,received:r.parsedType}),p;const a=[],i=this._def.keyType,o=this._def.valueType;for(const e in r.data)a.push({key:i._parse(new b(r,e,r.path,e)),value:o._parse(new b(r,r.data[e],r.path,e)),alwaysSet:e in r.data});return r.common.async?h.mergeObjectAsync(t,a):h.mergeObjectSync(t,a)}get element(){return this._def.valueType}static create(e,t,r){return new me(t instanceof E?{keyType:e,valueType:t,typeName:De.ZodRecord,...P(r)}:{keyType:B.create(),valueType:e,typeName:De.ZodRecord,...P(t)})}}class ve extends E{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==s.map)return l(r,{code:n.invalid_type,expected:s.map,received:r.parsedType}),p;const a=this._def.keyType,i=this._def.valueType,o=[...r.data.entries()].map(([e,t],s)=>({key:a._parse(new b(r,e,r.path,[s,"key"])),value:i._parse(new b(r,t,r.path,[s,"value"]))}));if(r.common.async){const e=new Map;return Promise.resolve().then(async()=>{for(const r of o){const a=await r.key,s=await r.value;if("aborted"===a.status||"aborted"===s.status)return p;"dirty"!==a.status&&"dirty"!==s.status||t.dirty(),e.set(a.value,s.value)}return{status:t.value,value:e}})}{const e=new Map;for(const r of o){const a=r.key,s=r.value;if("aborted"===a.status||"aborted"===s.status)return p;"dirty"!==a.status&&"dirty"!==s.status||t.dirty(),e.set(a.value,s.value)}return{status:t.value,value:e}}}}ve.create=(e,t,r)=>new ve({valueType:t,keyType:e,typeName:De.ZodMap,...P(r)});class ye extends E{_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==s.set)return l(r,{code:n.invalid_type,expected:s.set,received:r.parsedType}),p;const a=this._def;null!==a.minSize&&r.data.size<a.minSize.value&&(l(r,{code:n.too_small,minimum:a.minSize.value,type:"set",inclusive:!0,exact:!1,message:a.minSize.message}),t.dirty()),null!==a.maxSize&&r.data.size>a.maxSize.value&&(l(r,{code:n.too_big,maximum:a.maxSize.value,type:"set",inclusive:!0,exact:!1,message:a.maxSize.message}),t.dirty());const i=this._def.valueType;function o(e){const r=new Set;for(const a of e){if("aborted"===a.status)return p;"dirty"===a.status&&t.dirty(),r.add(a.value)}return{status:t.value,value:r}}const d=[...r.data.values()].map((e,t)=>i._parse(new b(r,e,r.path,t)));return r.common.async?Promise.all(d).then(e=>o(e)):o(d)}min(e,t){return new ye({...this._def,minSize:{value:e,message:u.toString(t)}})}max(e,t){return new ye({...this._def,maxSize:{value:e,message:u.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}}ye.create=(e,t)=>new ye({valueType:e,minSize:null,maxSize:null,typeName:De.ZodSet,...P(t)});class ge extends E{get schema(){return this._def.getter()}_parse(e){const{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}}ge.create=(e,t)=>new ge({getter:e,typeName:De.ZodLazy,...P(t)});class _e extends E{_parse(e){if(e.data!==this._def.value){const t=this._getOrReturnCtx(e);return l(t,{received:t.data,code:n.invalid_literal,expected:this._def.value}),p}return{status:"valid",value:e.data}}get value(){return this._def.value}}function be(e,t){return new we({values:e,typeName:De.ZodEnum,...P(t)})}_e.create=(e,t)=>new _e({value:e,typeName:De.ZodLiteral,...P(t)});class we extends E{_parse(e){if("string"!=typeof e.data){const r=this._getOrReturnCtx(e),a=this._def.values;return l(r,{expected:t.joinValues(a),received:r.parsedType,code:n.invalid_type}),p}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){const t=this._getOrReturnCtx(e),r=this._def.values;return l(t,{received:t.data,code:n.invalid_enum_value,options:r}),p}return m(e.data)}get options(){return this._def.values}get enum(){const e={};for(const t of this._def.values)e[t]=t;return e}get Values(){const e={};for(const t of this._def.values)e[t]=t;return e}get Enum(){const e={};for(const t of this._def.values)e[t]=t;return e}extract(e,t=this._def){return we.create(e,{...this._def,...t})}exclude(e,t=this._def){return we.create(this.options.filter(t=>!e.includes(t)),{...this._def,...t})}}we.create=be;class Pe extends E{_parse(e){const r=t.getValidEnumValues(this._def.values),a=this._getOrReturnCtx(e);if(a.parsedType!==s.string&&a.parsedType!==s.number){const e=t.objectValues(r);return l(a,{expected:t.joinValues(e),received:a.parsedType,code:n.invalid_type}),p}if(this._cache||(this._cache=new Set(t.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){const e=t.objectValues(r);return l(a,{received:a.data,code:n.invalid_enum_value,options:e}),p}return m(e.data)}get enum(){return this._def.values}}Pe.create=(e,t)=>new Pe({values:e,typeName:De.ZodNativeEnum,...P(t)});class Ee extends E{unwrap(){return this._def.type}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==s.promise&&!1===t.common.async)return l(t,{code:n.invalid_type,expected:s.promise,received:t.parsedType}),p;const r=t.parsedType===s.promise?t.data:Promise.resolve(t.data);return m(r.then(e=>this._def.type.parseAsync(e,{path:t.path,errorMap:t.common.contextualErrorMap})))}}Ee.create=(e,t)=>new Ee({type:e,typeName:De.ZodPromise,...P(t)});class xe extends E{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===De.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){const{status:r,ctx:a}=this._processInputParams(e),s=this._def.effect||null,i={addIssue:e=>{l(a,e),e.fatal?r.abort():r.dirty()},get path(){return a.path}};if(i.addIssue=i.addIssue.bind(i),"preprocess"===s.type){const e=s.transform(a.data,i);if(a.common.async)return Promise.resolve(e).then(async e=>{if("aborted"===r.value)return p;const t=await this._def.schema._parseAsync({data:e,path:a.path,parent:a});return"aborted"===t.status?p:"dirty"===t.status||"dirty"===r.value?f(t.value):t});{if("aborted"===r.value)return p;const t=this._def.schema._parseSync({data:e,path:a.path,parent:a});return"aborted"===t.status?p:"dirty"===t.status||"dirty"===r.value?f(t.value):t}}if("refinement"===s.type){const e=e=>{const t=s.refinement(e,i);if(a.common.async)return Promise.resolve(t);if(t instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return e};if(!1===a.common.async){const t=this._def.schema._parseSync({data:a.data,path:a.path,parent:a});return"aborted"===t.status?p:("dirty"===t.status&&r.dirty(),e(t.value),{status:r.value,value:t.value})}return this._def.schema._parseAsync({data:a.data,path:a.path,parent:a}).then(t=>"aborted"===t.status?p:("dirty"===t.status&&r.dirty(),e(t.value).then(()=>({status:r.value,value:t.value}))))}if("transform"===s.type){if(!1===a.common.async){const e=this._def.schema._parseSync({data:a.data,path:a.path,parent:a});if(!g(e))return p;const t=s.transform(e.value,i);if(t instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:r.value,value:t}}return this._def.schema._parseAsync({data:a.data,path:a.path,parent:a}).then(e=>g(e)?Promise.resolve(s.transform(e.value,i)).then(e=>({status:r.value,value:e})):p)}t.assertNever(s)}}xe.create=(e,t,r)=>new xe({schema:e,typeName:De.ZodEffects,effect:t,...P(r)}),xe.createWithPreprocess=(e,t,r)=>new xe({schema:t,effect:{type:"preprocess",transform:e},typeName:De.ZodEffects,...P(r)});class Se extends E{_parse(e){return this._getType(e)===s.undefined?m(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}Se.create=(e,t)=>new Se({innerType:e,typeName:De.ZodOptional,...P(t)});class Ie extends E{_parse(e){return this._getType(e)===s.null?m(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}Ie.create=(e,t)=>new Ie({innerType:e,typeName:De.ZodNullable,...P(t)});class ke extends E{_parse(e){const{ctx:t}=this._processInputParams(e);let r=t.data;return t.parsedType===s.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:t.path,parent:t})}removeDefault(){return this._def.innerType}}ke.create=(e,t)=>new ke({innerType:e,typeName:De.ZodDefault,defaultValue:"function"==typeof t.default?t.default:()=>t.default,...P(t)});class Te extends E{_parse(e){const{ctx:t}=this._processInputParams(e),r={...t,common:{...t.common,issues:[]}},a=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return _(a)?a.then(e=>({status:"valid",value:"valid"===e.status?e.value:this._def.catchValue({get error(){return new o(r.common.issues)},input:r.data})})):{status:"valid",value:"valid"===a.status?a.value:this._def.catchValue({get error(){return new o(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}}Te.create=(e,t)=>new Te({innerType:e,typeName:De.ZodCatch,catchValue:"function"==typeof t.catch?t.catch:()=>t.catch,...P(t)});class Ce extends E{_parse(e){if(this._getType(e)!==s.nan){const t=this._getOrReturnCtx(e);return l(t,{code:n.invalid_type,expected:s.nan,received:t.parsedType}),p}return{status:"valid",value:e.data}}}Ce.create=e=>new Ce({typeName:De.ZodNaN,...P(e)}),Symbol("zod_brand");class Ae extends E{_parse(e){const{ctx:t}=this._processInputParams(e),r=t.data;return this._def.type._parse({data:r,path:t.path,parent:t})}unwrap(){return this._def.type}}class Oe extends E{_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.common.async)return(async()=>{const e=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return"aborted"===e.status?p:"dirty"===e.status?(t.dirty(),f(e.value)):this._def.out._parseAsync({data:e.value,path:r.path,parent:r})})();{const e=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return"aborted"===e.status?p:"dirty"===e.status?(t.dirty(),{status:"dirty",value:e.value}):this._def.out._parseSync({data:e.value,path:r.path,parent:r})}}static create(e,t){return new Oe({in:e,out:t,typeName:De.ZodPipeline})}}class Re extends E{_parse(e){const t=this._def.innerType._parse(e),r=e=>(g(e)&&(e.value=Object.freeze(e.value)),e);return _(t)?t.then(e=>r(e)):r(t)}unwrap(){return this._def.innerType}}var De;Re.create=(e,t)=>new Re({innerType:e,typeName:De.ZodReadonly,...P(t)}),de.lazycreate,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"}(De||(De={}));const Ne=B.create,Ze=J.create,$e=(Ce.create,W.create,G.create),je=(Y.create,X.create,ee.create,te.create,re.create,ae.create),Fe=(se.create,ie.create,ne.create),Me=de.create,Le=(de.strictCreate,ce.create),ze=le.create,Ve=(pe.create,fe.create,me.create),qe=(ve.create,ye.create,ge.create,_e.create),Ue=we.create,Ke=(Pe.create,Ee.create,xe.create,Se.create),He=(Ie.create,xe.createWithPreprocess,Oe.create,"2025-06-18"),Be=[He,"2025-03-26","2024-11-05","2024-10-07"],Qe="2.0",Je=Le([Ne(),Ze().int()]),We=Ne(),Ge=Me({progressToken:Ke(Je)}).passthrough(),Ye=Me({_meta:Ke(Ge)}).passthrough(),Xe=Me({method:Ne(),params:Ke(Ye)}),et=Me({_meta:Ke(Me({}).passthrough())}).passthrough(),tt=Me({method:Ne(),params:Ke(et)}),rt=Me({_meta:Ke(Me({}).passthrough())}).passthrough(),at=Le([Ne(),Ze().int()]),st=Me({jsonrpc:qe(Qe),id:at}).merge(Xe).strict(),it=Me({jsonrpc:qe(Qe)}).merge(tt).strict(),nt=Me({jsonrpc:qe(Qe),id:at,result:rt}).strict(),ot=e=>nt.safeParse(e).success;var dt;!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"}(dt||(dt={}));const ct=Me({jsonrpc:qe(Qe),id:at,error:Me({code:Ze().int(),message:Ne(),data:Ke(je())})}).strict(),ut=Le([st,it,nt,ct]),lt=rt.strict(),ht=tt.extend({method:qe("notifications/cancelled"),params:et.extend({requestId:at,reason:Ne().optional()})}),pt=Me({src:Ne(),mimeType:Ke(Ne()),sizes:Ke(Ne())}).passthrough(),ft=Me({name:Ne(),title:Ke(Ne())}).passthrough(),mt=ft.extend({version:Ne(),websiteUrl:Ke(Ne()),icons:Ke(Fe(pt))}),vt=Me({experimental:Ke(Me({}).passthrough()),sampling:Ke(Me({}).passthrough()),elicitation:Ke(Me({}).passthrough()),roots:Ke(Me({listChanged:Ke($e())}).passthrough())}).passthrough(),yt=Xe.extend({method:qe("initialize"),params:Ye.extend({protocolVersion:Ne(),capabilities:vt,clientInfo:mt})}),gt=Me({experimental:Ke(Me({}).passthrough()),logging:Ke(Me({}).passthrough()),completions:Ke(Me({}).passthrough()),prompts:Ke(Me({listChanged:Ke($e())}).passthrough()),resources:Ke(Me({subscribe:Ke($e()),listChanged:Ke($e())}).passthrough()),tools:Ke(Me({listChanged:Ke($e())}).passthrough())}).passthrough(),_t=rt.extend({protocolVersion:Ne(),capabilities:gt,serverInfo:mt,instructions:Ke(Ne())}),bt=tt.extend({method:qe("notifications/initialized")}),wt=Xe.extend({method:qe("ping")}),Pt=Me({progress:Ze(),total:Ke(Ze()),message:Ke(Ne())}).passthrough(),Et=tt.extend({method:qe("notifications/progress"),params:et.merge(Pt).extend({progressToken:Je})}),xt=Xe.extend({params:Ye.extend({cursor:Ke(We)}).optional()}),St=rt.extend({nextCursor:Ke(We)}),It=Me({uri:Ne(),mimeType:Ke(Ne()),_meta:Ke(Me({}).passthrough())}).passthrough(),kt=It.extend({text:Ne()}),Tt=Ne().refine(e=>{try{return atob(e),!0}catch(e){return!1}},{message:"Invalid Base64 string"}),Ct=It.extend({blob:Tt}),At=ft.extend({uri:Ne(),description:Ke(Ne()),mimeType:Ke(Ne()),icons:Ke(Fe(pt)),_meta:Ke(Me({}).passthrough())}),Ot=ft.extend({uriTemplate:Ne(),description:Ke(Ne()),mimeType:Ke(Ne()),_meta:Ke(Me({}).passthrough())}),Rt=xt.extend({method:qe("resources/list")}),Dt=St.extend({resources:Fe(At)}),Nt=xt.extend({method:qe("resources/templates/list")}),Zt=St.extend({resourceTemplates:Fe(Ot)}),$t=Xe.extend({method:qe("resources/read"),params:Ye.extend({uri:Ne()})}),jt=rt.extend({contents:Fe(Le([kt,Ct]))}),Ft=tt.extend({method:qe("notifications/resources/list_changed")}),Mt=Xe.extend({method:qe("resources/subscribe"),params:Ye.extend({uri:Ne()})}),Lt=Xe.extend({method:qe("resources/unsubscribe"),params:Ye.extend({uri:Ne()})}),zt=tt.extend({method:qe("notifications/resources/updated"),params:et.extend({uri:Ne()})}),Vt=Me({name:Ne(),description:Ke(Ne()),required:Ke($e())}).passthrough(),qt=ft.extend({description:Ke(Ne()),arguments:Ke(Fe(Vt)),icons:Ke(Fe(pt)),_meta:Ke(Me({}).passthrough())}),Ut=xt.extend({method:qe("prompts/list")}),Kt=St.extend({prompts:Fe(qt)}),Ht=Xe.extend({method:qe("prompts/get"),params:Ye.extend({name:Ne(),arguments:Ke(Ve(Ne()))})}),Bt=Me({type:qe("text"),text:Ne(),_meta:Ke(Me({}).passthrough())}).passthrough(),Qt=Me({type:qe("image"),data:Tt,mimeType:Ne(),_meta:Ke(Me({}).passthrough())}).passthrough(),Jt=Me({type:qe("audio"),data:Tt,mimeType:Ne(),_meta:Ke(Me({}).passthrough())}).passthrough(),Wt=Me({type:qe("resource"),resource:Le([kt,Ct]),_meta:Ke(Me({}).passthrough())}).passthrough(),Gt=Le([Bt,Qt,Jt,At.extend({type:qe("resource_link")}),Wt]),Yt=Me({role:Ue(["user","assistant"]),content:Gt}).passthrough(),Xt=rt.extend({description:Ke(Ne()),messages:Fe(Yt)}),er=tt.extend({method:qe("notifications/prompts/list_changed")}),tr=Me({title:Ke(Ne()),readOnlyHint:Ke($e()),destructiveHint:Ke($e()),idempotentHint:Ke($e()),openWorldHint:Ke($e())}).passthrough(),rr=ft.extend({description:Ke(Ne()),inputSchema:Me({type:qe("object"),properties:Ke(Me({}).passthrough()),required:Ke(Fe(Ne()))}).passthrough(),outputSchema:Ke(Me({type:qe("object"),properties:Ke(Me({}).passthrough()),required:Ke(Fe(Ne()))}).passthrough()),annotations:Ke(tr),icons:Ke(Fe(pt)),_meta:Ke(Me({}).passthrough())}),ar=xt.extend({method:qe("tools/list")}),sr=St.extend({tools:Fe(rr)}),ir=rt.extend({content:Fe(Gt).default([]),structuredContent:Me({}).passthrough().optional(),isError:Ke($e())}),nr=(ir.or(rt.extend({toolResult:je()})),Xe.extend({method:qe("tools/call"),params:Ye.extend({name:Ne(),arguments:Ke(Ve(je()))})})),or=tt.extend({method:qe("notifications/tools/list_changed")}),dr=Ue(["debug","info","notice","warning","error","critical","alert","emergency"]),cr=Xe.extend({method:qe("logging/setLevel"),params:Ye.extend({level:dr})}),ur=tt.extend({method:qe("notifications/message"),params:et.extend({level:dr,logger:Ke(Ne()),data:je()})}),lr=Me({name:Ne().optional()}).passthrough(),hr=Me({hints:Ke(Fe(lr)),costPriority:Ke(Ze().min(0).max(1)),speedPriority:Ke(Ze().min(0).max(1)),intelligencePriority:Ke(Ze().min(0).max(1))}).passthrough(),pr=Me({role:Ue(["user","assistant"]),content:Le([Bt,Qt,Jt])}).passthrough(),fr=Xe.extend({method:qe("sampling/createMessage"),params:Ye.extend({messages:Fe(pr),systemPrompt:Ke(Ne()),includeContext:Ke(Ue(["none","thisServer","allServers"])),temperature:Ke(Ze()),maxTokens:Ze().int(),stopSequences:Ke(Fe(Ne())),metadata:Ke(Me({}).passthrough()),modelPreferences:Ke(hr)})}),mr=rt.extend({model:Ne(),stopReason:Ke(Ue(["endTurn","stopSequence","maxTokens"]).or(Ne())),role:Ue(["user","assistant"]),content:ze("type",[Bt,Qt,Jt])}),vr=Le([Me({type:qe("boolean"),title:Ke(Ne()),description:Ke(Ne()),default:Ke($e())}).passthrough(),Me({type:qe("string"),title:Ke(Ne()),description:Ke(Ne()),minLength:Ke(Ze()),maxLength:Ke(Ze()),format:Ke(Ue(["email","uri","date","date-time"]))}).passthrough(),Me({type:Ue(["number","integer"]),title:Ke(Ne()),description:Ke(Ne()),minimum:Ke(Ze()),maximum:Ke(Ze())}).passthrough(),Me({type:qe("string"),title:Ke(Ne()),description:Ke(Ne()),enum:Fe(Ne()),enumNames:Ke(Fe(Ne()))}).passthrough()]),yr=Xe.extend({method:qe("elicitation/create"),params:Ye.extend({message:Ne(),requestedSchema:Me({type:qe("object"),properties:Ve(Ne(),vr),required:Ke(Fe(Ne()))}).passthrough()})}),gr=rt.extend({action:Ue(["accept","decline","cancel"]),content:Ke(Ve(Ne(),je()))}),_r=Me({type:qe("ref/resource"),uri:Ne()}).passthrough(),br=Me({type:qe("ref/prompt"),name:Ne()}).passthrough(),wr=Xe.extend({method:qe("completion/complete"),params:Ye.extend({ref:Le([br,_r]),argument:Me({name:Ne(),value:Ne()}).passthrough(),context:Ke(Me({arguments:Ke(Ve(Ne(),Ne()))}))})}),Pr=rt.extend({completion:Me({values:Fe(Ne()).max(100),total:Ke(Ze().int()),hasMore:Ke($e())}).passthrough()}),Er=Me({uri:Ne().startsWith("file://"),name:Ke(Ne()),_meta:Ke(Me({}).passthrough())}).passthrough(),xr=Xe.extend({method:qe("roots/list")}),Sr=rt.extend({roots:Fe(Er)}),Ir=tt.extend({method:qe("notifications/roots/list_changed")});Le([wt,yt,wr,cr,Ht,Ut,Rt,Nt,$t,Mt,Lt,nr,ar]),Le([ht,Et,bt,Ir]),Le([lt,mr,gr,Sr]),Le([wt,fr,yr,xr]),Le([ht,Et,ur,zt,Ft,or,er]),Le([lt,_t,Pr,Xt,Kt,Dt,Zt,jt,ir,sr]);class kr extends Error{constructor(e,t,r){super(`MCP error ${e}: ${t}`),this.code=e,this.data=r,this.name="McpError"}}class Tr{append(e){this._buffer=this._buffer?Buffer.concat([this._buffer,e]):e}readMessage(){if(!this._buffer)return null;const e=this._buffer.indexOf("\n");if(-1===e)return null;const t=this._buffer.toString("utf8",0,e).replace(/\r$/,"");return this._buffer=this._buffer.subarray(e+1),function(e){return ut.parse(JSON.parse(e))}(t)}clear(){this._buffer=void 0}}class Cr{constructor(t=e.stdin,r=e.stdout){this._stdin=t,this._stdout=r,this._readBuffer=new Tr,this._started=!1,this._ondata=e=>{this._readBuffer.append(e),this.processReadBuffer()},this._onerror=e=>{var t;null===(t=this.onerror)||void 0===t||t.call(this,e)}}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(var e,t;;)try{const t=this._readBuffer.readMessage();if(null===t)break;null===(e=this.onmessage)||void 0===e||e.call(this,t)}catch(e){null===(t=this.onerror)||void 0===t||t.call(this,e)}}async close(){var e;this._stdin.off("data",this._ondata),this._stdin.off("error",this._onerror),0===this._stdin.listenerCount("data")&&this._stdin.pause(),this._readBuffer.clear(),null===(e=this.onclose)||void 0===e||e.call(this)}send(e){return new Promise(t=>{const r=function(e){return JSON.stringify(e)+"\n"}(e);this._stdout.write(r)?t():this._stdout.once("drain",t)})}}class Ar{constructor(e){this._options=e,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.setNotificationHandler(ht,e=>{const t=this._requestHandlerAbortControllers.get(e.params.requestId);null==t||t.abort(e.params.reason)}),this.setNotificationHandler(Et,e=>{this._onprogress(e)}),this.setRequestHandler(wt,e=>({}))}_setupTimeout(e,t,r,a,s=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(a,t),startTime:Date.now(),timeout:t,maxTotalTimeout:r,resetTimeoutOnProgress:s,onTimeout:a})}_resetTimeout(e){const t=this._timeoutInfo.get(e);if(!t)return!1;const r=Date.now()-t.startTime;if(t.maxTotalTimeout&&r>=t.maxTotalTimeout)throw this._timeoutInfo.delete(e),new kr(dt.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:t.maxTotalTimeout,totalElapsed:r});return clearTimeout(t.timeoutId),t.timeoutId=setTimeout(t.onTimeout,t.timeout),!0}_cleanupTimeout(e){const t=this._timeoutInfo.get(e);t&&(clearTimeout(t.timeoutId),this._timeoutInfo.delete(e))}async connect(e){var t,r,a;this._transport=e;const s=null===(t=this.transport)||void 0===t?void 0:t.onclose;this._transport.onclose=()=>{null==s||s(),this._onclose()};const i=null===(r=this.transport)||void 0===r?void 0:r.onerror;this._transport.onerror=e=>{null==i||i(e),this._onerror(e)};const n=null===(a=this._transport)||void 0===a?void 0:a.onmessage;this._transport.onmessage=(e,t)=>{var r;null==n||n(e,t),ot(e)||(r=e,ct.safeParse(r).success)?this._onresponse(e):(e=>st.safeParse(e).success)(e)?this._onrequest(e,t):(e=>it.safeParse(e).success)(e)?this._onnotification(e):this._onerror(new Error(`Unknown message type: ${JSON.stringify(e)}`))},await this._transport.start()}_onclose(){var e;const t=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._pendingDebouncedNotifications.clear(),this._transport=void 0,null===(e=this.onclose)||void 0===e||e.call(this);const r=new kr(dt.ConnectionClosed,"Connection closed");for(const e of t.values())e(r)}_onerror(e){var t;null===(t=this.onerror)||void 0===t||t.call(this,e)}_onnotification(e){var t;const r=null!==(t=this._notificationHandlers.get(e.method))&&void 0!==t?t:this.fallbackNotificationHandler;void 0!==r&&Promise.resolve().then(()=>r(e)).catch(e=>this._onerror(new Error(`Uncaught error in notification handler: ${e}`)))}_onrequest(e,t){var r,a;const s=null!==(r=this._requestHandlers.get(e.method))&&void 0!==r?r:this.fallbackRequestHandler,i=this._transport;if(void 0===s)return void(null==i||i.send({jsonrpc:"2.0",id:e.id,error:{code:dt.MethodNotFound,message:"Method not found"}}).catch(e=>this._onerror(new Error(`Failed to send an error response: ${e}`))));const n=new AbortController;this._requestHandlerAbortControllers.set(e.id,n);const o={signal:n.signal,sessionId:null==i?void 0:i.sessionId,_meta:null===(a=e.params)||void 0===a?void 0:a._meta,sendNotification:t=>this.notification(t,{relatedRequestId:e.id}),sendRequest:(t,r,a)=>this.request(t,r,{...a,relatedRequestId:e.id}),authInfo:null==t?void 0:t.authInfo,requestId:e.id,requestInfo:null==t?void 0:t.requestInfo};Promise.resolve().then(()=>s(e,o)).then(t=>{if(!n.signal.aborted)return null==i?void 0:i.send({result:t,jsonrpc:"2.0",id:e.id})},t=>{var r;if(!n.signal.aborted)return null==i?void 0:i.send({jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(t.code)?t.code:dt.InternalError,message:null!==(r=t.message)&&void 0!==r?r:"Internal error"}})}).catch(e=>this._onerror(new Error(`Failed to send response: ${e}`))).finally(()=>{this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){const{progressToken:t,...r}=e.params,a=Number(t),s=this._progressHandlers.get(a);if(!s)return void this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));const i=this._responseHandlers.get(a),n=this._timeoutInfo.get(a);if(n&&i&&n.resetTimeoutOnProgress)try{this._resetTimeout(a)}catch(e){return void i(e)}s(r)}_onresponse(e){const t=Number(e.id),r=this._responseHandlers.get(t);void 0!==r?(this._responseHandlers.delete(t),this._progressHandlers.delete(t),this._cleanupTimeout(t),ot(e)?r(e):r(new kr(e.error.code,e.error.message,e.error.data))):this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`))}get transport(){return this._transport}async close(){var e;await(null===(e=this._transport)||void 0===e?void 0:e.close())}request(e,t,r){const{relatedRequestId:a,resumptionToken:s,onresumptiontoken:i}=null!=r?r:{};return new Promise((n,o)=>{var d,c,u,l,h,p;if(!this._transport)return void o(new Error("Not connected"));!0===(null===(d=this._options)||void 0===d?void 0:d.enforceStrictCapabilities)&&this.assertCapabilityForMethod(e.method),null===(c=null==r?void 0:r.signal)||void 0===c||c.throwIfAborted();const f=this._requestMessageId++,m={...e,jsonrpc:"2.0",id:f};(null==r?void 0:r.onprogress)&&(this._progressHandlers.set(f,r.onprogress),m.params={...e.params,_meta:{...(null===(u=e.params)||void 0===u?void 0:u._meta)||{},progressToken:f}});const v=e=>{var t;this._responseHandlers.delete(f),this._progressHandlers.delete(f),this._cleanupTimeout(f),null===(t=this._transport)||void 0===t||t.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:f,reason:String(e)}},{relatedRequestId:a,resumptionToken:s,onresumptiontoken:i}).catch(e=>this._onerror(new Error(`Failed to send cancellation: ${e}`))),o(e)};this._responseHandlers.set(f,e=>{var a;if(!(null===(a=null==r?void 0:r.signal)||void 0===a?void 0:a.aborted)){if(e instanceof Error)return o(e);try{const r=t.parse(e.result);n(r)}catch(e){o(e)}}}),null===(l=null==r?void 0:r.signal)||void 0===l||l.addEventListener("abort",()=>{var e;v(null===(e=null==r?void 0:r.signal)||void 0===e?void 0:e.reason)});const y=null!==(h=null==r?void 0:r.timeout)&&void 0!==h?h:6e4;this._setupTimeout(f,y,null==r?void 0:r.maxTotalTimeout,()=>v(new kr(dt.RequestTimeout,"Request timed out",{timeout:y})),null!==(p=null==r?void 0:r.resetTimeoutOnProgress)&&void 0!==p&&p),this._transport.send(m,{relatedRequestId:a,resumptionToken:s,onresumptiontoken:i}).catch(e=>{this._cleanupTimeout(f),o(e)})})}async notification(e,t){var r,a;if(!this._transport)throw new Error("Not connected");if(this.assertNotificationCapability(e.method),(null!==(a=null===(r=this._options)||void 0===r?void 0:r.debouncedNotificationMethods)&&void 0!==a?a:[]).includes(e.method)&&!e.params&&!(null==t?void 0:t.relatedRequestId)){if(this._pendingDebouncedNotifications.has(e.method))return;return this._pendingDebouncedNotifications.add(e.method),void Promise.resolve().then(()=>{var r;if(this._pendingDebouncedNotifications.delete(e.method),!this._transport)return;const a={...e,jsonrpc:"2.0"};null===(r=this._transport)||void 0===r||r.send(a,t).catch(e=>this._onerror(e))})}const s={...e,jsonrpc:"2.0"};await this._transport.send(s,t)}setRequestHandler(e,t){const r=e.shape.method.value;this.assertRequestHandlerCapability(r),this._requestHandlers.set(r,(r,a)=>Promise.resolve(t(e.parse(r),a)))}removeRequestHandler(e){this._requestHandlers.delete(e)}assertCanSetRequestHandler(e){if(this._requestHandlers.has(e))throw new Error(`A request handler for ${e} already exists, which would be overridden`)}setNotificationHandler(e,t){this._notificationHandlers.set(e.shape.method.value,r=>Promise.resolve(t(e.parse(r))))}removeNotificationHandler(e){this._notificationHandlers.delete(e)}}var Or=r(53084);class Rr extends Ar{constructor(e,t){var r;super(t),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(dr.options.map((e,t)=>[e,t])),this.isMessageIgnored=(e,t)=>{const r=this._loggingLevels.get(t);return!!r&&this.LOG_LEVEL_SEVERITY.get(e)<this.LOG_LEVEL_SEVERITY.get(r)},this._capabilities=null!==(r=null==t?void 0:t.capabilities)&&void 0!==r?r:{},this._instructions=null==t?void 0:t.instructions,this.setRequestHandler(yt,e=>this._oninitialize(e)),this.setNotificationHandler(bt,()=>{var e;return null===(e=this.oninitialized)||void 0===e?void 0:e.call(this)}),this._capabilities.logging&&this.setRequestHandler(cr,async(e,t)=>{var r;const a=t.sessionId||(null===(r=t.requestInfo)||void 0===r?void 0:r.headers["mcp-session-id"])||void 0,{level:s}=e.params,i=dr.safeParse(s);return i.success&&this._loggingLevels.set(a,i.data),{}})}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");var t,r;this._capabilities=(t=this._capabilities,r=e,Object.entries(r).reduce((e,[t,r])=>(e[t]=r&&"object"==typeof r&&e[t]?{...e[t],...r}:r,e),{...t}))}assertCapabilityForMethod(e){var t,r,a;switch(e){case"sampling/createMessage":if(!(null===(t=this._clientCapabilities)||void 0===t?void 0:t.sampling))throw new Error(`Client does not support sampling (required for ${e})`);break;case"elicitation/create":if(!(null===(r=this._clientCapabilities)||void 0===r?void 0:r.elicitation))throw new Error(`Client does not support elicitation (required for ${e})`);break;case"roots/list":if(!(null===(a=this._clientCapabilities)||void 0===a?void 0:a.roots))throw new Error(`Client does not support listing roots (required for ${e})`)}}assertNotificationCapability(e){switch(e){case"notifications/message":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${e})`);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 ${e})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw new Error(`Server does not support notifying of tool list changes (required for ${e})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw new Error(`Server does not support notifying of prompt list changes (required for ${e})`)}}assertRequestHandlerCapability(e){switch(e){case"sampling/createMessage":if(!this._capabilities.sampling)throw new Error(`Server does not support sampling (required for ${e})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw new Error(`Server does not support prompts (required for ${e})`);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 ${e})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw new Error(`Server does not support tools (required for ${e})`)}}async _oninitialize(e){const t=e.params.protocolVersion;return this._clientCapabilities=e.params.capabilities,this._clientVersion=e.params.clientInfo,{protocolVersion:Be.includes(t)?t:He,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"},lt)}async createMessage(e,t){return this.request({method:"sampling/createMessage",params:e},mr,t)}async elicitInput(e,t){const r=await this.request({method:"elicitation/create",params:e},gr,t);if("accept"===r.action&&r.content)try{const t=new Or,a=t.compile(e.requestedSchema);if(!a(r.content))throw new kr(dt.InvalidParams,`Elicitation response content does not match requested schema: ${t.errorsText(a.errors)}`)}catch(e){if(e instanceof kr)throw e;throw new kr(dt.InternalError,`Error validating elicitation response: ${e}`)}return r}async listRoots(e,t){return this.request({method:"roots/list",params:e},Sr,t)}async sendLoggingMessage(e,t){if(this._capabilities.logging&&!this.isMessageIgnored(e.level,t))return this.notification({method:"notifications/message",params:e})}async sendResourceUpdated(e){return this.notification({method:"notifications/resources/updated",params:e})}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"})}}const Dr=require("crypto"),Nr=require("node:crypto"),Zr=require("node:buffer");const $r=e=>Zr.Buffer.from(e).toString("base64url"),jr=require("node:util");class Fr extends Error{static code="ERR_JOSE_GENERIC";code="ERR_JOSE_GENERIC";constructor(e,t){super(e,t),this.name=this.constructor.name,Error.captureStackTrace?.(this,this.constructor)}}class Mr extends Fr{static code="ERR_JOSE_NOT_SUPPORTED";code="ERR_JOSE_NOT_SUPPORTED"}class Lr extends Fr{static code="ERR_JWS_INVALID";code="ERR_JWS_INVALID"}class zr extends Fr{static code="ERR_JWT_INVALID";code="ERR_JWT_INVALID"}Symbol.asyncIterator;const Vr=Nr.webcrypto,qr=e=>jr.types.isCryptoKey(e),Ur=e=>jr.types.isKeyObject(e);function Kr(e,t,...r){if((r=r.filter(Boolean)).length>2){const t=r.pop();e+=`one of type ${r.join(", ")}, or ${t}.`}else 2===r.length?e+=`one of type ${r[0]} or ${r[1]}.`:e+=`of type ${r[0]}.`;return null==t?e+=` Received ${t}`:"function"==typeof t&&t.name?e+=` Received function ${t.name}`:"object"==typeof t&&null!=t&&t.constructor?.name&&(e+=` Received an instance of ${t.constructor.name}`),e}const Hr=(e,...t)=>Kr("Key must be ",e,...t);function Br(e,t,...r){return Kr(`Key for the ${e} algorithm must be `,t,...r)}const Qr=e=>Ur(e)||qr(e),Jr=["KeyObject"];function Wr(e){if("object"!=typeof(t=e)||null===t||"[object Object]"!==Object.prototype.toString.call(e))return!1;var t;if(null===Object.getPrototypeOf(e))return!0;let r=e;for(;null!==Object.getPrototypeOf(r);)r=Object.getPrototypeOf(r);return Object.getPrototypeOf(e)===r}function Gr(e){return Wr(e)&&"string"==typeof e.kty}(globalThis.CryptoKey||Vr?.CryptoKey)&&Jr.push("CryptoKey"),new WeakMap;const Yr=(e,t)=>{let r;if(qr(e))r=Nr.KeyObject.from(e);else{if(!Ur(e)){if(Gr(e))return e.crv;throw new TypeError(Hr(e,...Jr))}r=e}if("secret"===r.type)throw new TypeError('only "private" or "public" type keys can be used for this operation');switch(r.asymmetricKeyType){case"ed25519":case"ed448":return`Ed${r.asymmetricKeyType.slice(2)}`;case"x25519":case"x448":return`X${r.asymmetricKeyType.slice(1)}`;case"ec":{const e=r.asymmetricKeyDetails.namedCurve;return t?e:(e=>{switch(e){case"prime256v1":return"P-256";case"secp384r1":return"P-384";case"secp521r1":return"P-521";case"secp256k1":return"secp256k1";default:throw new Mr("Unsupported key curve for this operation")}})(e)}default:throw new TypeError("Invalid asymmetric key type for this operation")}},Xr=(e,t)=>{let r;try{r=e instanceof Nr.KeyObject?e.asymmetricKeyDetails?.modulusLength:Buffer.from(e.n,"base64url").byteLength<<3}catch{}if("number"!=typeof r||r<2048)throw new TypeError(`${t} requires key modulusLength to be 2048 bits or larger`)},ea=new Map([["ES256","P-256"],["ES256K","secp256k1"],["ES384","P-384"],["ES512","P-521"]]);function ta(e,t="algorithm.name"){return new TypeError(`CryptoKey does not support this operation, its ${t} must be ${e}`)}function ra(e,t){return e.name===t}function aa(e){return parseInt(e.name.slice(4),10)}function sa(e,t,...r){switch(t){case"HS256":case"HS384":case"HS512":{if(!ra(e.algorithm,"HMAC"))throw ta("HMAC");const r=parseInt(t.slice(2),10);if(aa(e.algorithm.hash)!==r)throw ta(`SHA-${r}`,"algorithm.hash");break}case"RS256":case"RS384":case"RS512":{if(!ra(e.algorithm,"RSASSA-PKCS1-v1_5"))throw ta("RSASSA-PKCS1-v1_5");const r=parseInt(t.slice(2),10);if(aa(e.algorithm.hash)!==r)throw ta(`SHA-${r}`,"algorithm.hash");break}case"PS256":case"PS384":case"PS512":{if(!ra(e.algorithm,"RSA-PSS"))throw ta("RSA-PSS");const r=parseInt(t.slice(2),10);if(aa(e.algorithm.hash)!==r)throw ta(`SHA-${r}`,"algorithm.hash");break}case"EdDSA":if("Ed25519"!==e.algorithm.name&&"Ed448"!==e.algorithm.name)throw ta("Ed25519 or Ed448");break;case"Ed25519":if(!ra(e.algorithm,"Ed25519"))throw ta("Ed25519");break;case"ES256":case"ES384":case"ES512":{if(!ra(e.algorithm,"ECDSA"))throw ta("ECDSA");const r=function(e){switch(e){case"ES256":return"P-256";case"ES384":return"P-384";case"ES512":return"P-521";default:throw new Error("unreachable")}}(t);if(e.algorithm.namedCurve!==r)throw ta(r,"algorithm.namedCurve");break}default:throw new TypeError("CryptoKey does not support this operation")}!function(e,t){if(t.length&&!t.some(t=>e.usages.includes(t))){let e="CryptoKey does not support this operation, its usages must include ";if(t.length>2){const r=t.pop();e+=`one of ${t.join(", ")}, or ${r}.`}else 2===t.length?e+=`one of ${t[0]} or ${t[1]}.`:e+=`${t[0]}.`;throw new TypeError(e)}}(e,r)}const ia=(0,jr.promisify)(Nr.sign),na=new TextEncoder,oa=new TextDecoder;const da=e=>e?.[Symbol.toStringTag],ca=(e,t,r)=>{if(void 0!==t.use&&"sig"!==t.use)throw new TypeError("Invalid key for this operation, when present its use must be sig");if(void 0!==t.key_ops&&!0!==t.key_ops.includes?.(r))throw new TypeError(`Invalid key for this operation, when present its key_ops must include ${r}`);if(void 0!==t.alg&&t.alg!==e)throw new TypeError(`Invalid key for this operation, when present its alg must be ${e}`);return!0};function ua(e,t,r,a){t.startsWith("HS")||"dir"===t||t.startsWith("PBES2")||/^A\d{3}(?:GCM)?KW$/.test(t)?((e,t,r,a)=>{if(!(t instanceof Uint8Array)){if(a&&Gr(t)){if(function(e){return Gr(e)&&"oct"===e.kty&&"string"==typeof e.k}(t)&&ca(e,t,r))return;throw new TypeError('JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present')}if(!Qr(t))throw new TypeError(Br(e,t,...Jr,"Uint8Array",a?"JSON Web Key":null));if("secret"!==t.type)throw new TypeError(`${da(t)} instances for symmetric algorithms must be of type "secret"`)}})(t,r,a,e):((e,t,r,a)=>{if(a&&Gr(t))switch(r){case"sign":if(function(e){return"oct"!==e.kty&&"string"==typeof e.d}(t)&&ca(e,t,r))return;throw new TypeError("JSON Web Key for this operation be a private JWK");case"verify":if(function(e){return"oct"!==e.kty&&void 0===e.d}(t)&&ca(e,t,r))return;throw new TypeError("JSON Web Key for this operation be a public JWK")}if(!Qr(t))throw new TypeError(Br(e,t,...Jr,a?"JSON Web Key":null));if("secret"===t.type)throw new TypeError(`${da(t)} instances for asymmetric algorithms must not be of type "secret"`);if("sign"===r&&"public"===t.type)throw new TypeError(`${da(t)} instances for asymmetric algorithm signing must be of type "private"`);if("decrypt"===r&&"public"===t.type)throw new TypeError(`${da(t)} instances for asymmetric algorithm decryption must be of type "private"`);if(t.algorithm&&"verify"===r&&"private"===t.type)throw new TypeError(`${da(t)} instances for asymmetric algorithm verifying must be of type "public"`);if(t.algorithm&&"encrypt"===r&&"private"===t.type)throw new TypeError(`${da(t)} instances for asymmetric algorithm encryption must be of type "public"`)})(t,r,a,e)}ua.bind(void 0,!1);const la=ua.bind(void 0,!0);class ha{_payload;_protectedHeader;_unprotectedHeader;constructor(e){if(!(e instanceof Uint8Array))throw new TypeError("payload must be an instance of Uint8Array");this._payload=e}setProtectedHeader(e){if(this._protectedHeader)throw new TypeError("setProtectedHeader can only be called once");return this._protectedHeader=e,this}setUnprotectedHeader(e){if(this._unprotectedHeader)throw new TypeError("setUnprotectedHeader can only be called once");return this._unprotectedHeader=e,this}async sign(e,t){if(!this._protectedHeader&&!this._unprotectedHeader)throw new Lr("either setProtectedHeader or setUnprotectedHeader must be called before #sign()");if(!((...e)=>{const t=e.filter(Boolean);if(0===t.length||1===t.length)return!0;let r;for(const e of t){const t=Object.keys(e);if(r&&0!==r.size)for(const e of t){if(r.has(e))return!1;r.add(e)}else r=new Set(t)}return!0})(this._protectedHeader,this._unprotectedHeader))throw new Lr("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");const r={...this._protectedHeader,...this._unprotectedHeader};let a=!0;if(function(e,t,r,a,s){if(void 0!==s.crit&&void 0===a?.crit)throw new e('"crit" (Critical) Header Parameter MUST be integrity protected');if(!a||void 0===a.crit)return new Set;if(!Array.isArray(a.crit)||0===a.crit.length||a.crit.some(e=>"string"!=typeof e||0===e.length))throw new e('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');let i;i=void 0!==r?new Map([...Object.entries(r),...t.entries()]):t;for(const t of a.crit){if(!i.has(t))throw new Mr(`Extension Header Parameter "${t}" is not recognized`);if(void 0===s[t])throw new e(`Extension Header Parameter "${t}" is missing`);if(i.get(t)&&void 0===a[t])throw new e(`Extension Header Parameter "${t}" MUST be integrity protected`)}return new Set(a.crit)}(Lr,new Map([["b64",!0]]),t?.crit,this._protectedHeader,r).has("b64")&&(a=this._protectedHeader.b64,"boolean"!=typeof a))throw new Lr('The "b64" (base64url-encode payload) Header Parameter must be a boolean');const{alg:s}=r;if("string"!=typeof s||!s)throw new Lr('JWS "alg" (Algorithm) Header Parameter missing or invalid');la(s,e,"sign");let i,n=this._payload;a&&(n=na.encode($r(n))),i=this._protectedHeader?na.encode($r(JSON.stringify(this._protectedHeader))):na.encode("");const o=function(...e){const t=e.reduce((e,{length:t})=>e+t,0),r=new Uint8Array(t);let a=0;for(const t of e)r.set(t,a),a+=t.length;return r}(i,na.encode("."),n),d=await(async(e,t,r)=>{const a=function(e,t){if(t instanceof Uint8Array){if(!e.startsWith("HS"))throw new TypeError(Hr(t,...Jr));return(0,Nr.createSecretKey)(t)}if(t instanceof Nr.KeyObject)return t;if(qr(t))return sa(t,e,"sign"),Nr.KeyObject.from(t);if(Gr(t))return e.startsWith("HS")?(0,Nr.createSecretKey)(Buffer.from(t.k,"base64url")):t;throw new TypeError(Hr(t,...Jr,"Uint8Array","JSON Web Key"))}(e,t);if(e.startsWith("HS")){const t=Nr.createHmac(function(e){switch(e){case"HS256":return"sha256";case"HS384":return"sha384";case"HS512":return"sha512";default:throw new Mr(`alg ${e} is not supported either by JOSE or your javascript runtime`)}}(e),a);return t.update(r),t.digest()}return ia(function(e){switch(e){case"PS256":case"RS256":case"ES256":case"ES256K":return"sha256";case"PS384":case"RS384":case"ES384":return"sha384";case"PS512":case"RS512":case"ES512":return"sha512";case"Ed25519":case"EdDSA":return;default:throw new Mr(`alg ${e} is not supported either by JOSE or your javascript runtime`)}}(e),r,function(e,t){let r,a,s,i;if(t instanceof Nr.KeyObject)r=t.asymmetricKeyType,a=t.asymmetricKeyDetails;else switch(s=!0,t.kty){case"RSA":r="rsa";break;case"EC":r="ec";break;case"OKP":if("Ed25519"===t.crv){r="ed25519";break}if("Ed448"===t.crv){r="ed448";break}throw new TypeError("Invalid key for this operation, its crv must be Ed25519 or Ed448");default:throw new TypeError("Invalid key for this operation, its kty must be RSA, OKP, or EC")}switch(e){case"Ed25519":if("ed25519"!==r)throw new TypeError("Invalid key for this operation, its asymmetricKeyType must be ed25519");break;case"EdDSA":if(!["ed25519","ed448"].includes(r))throw new TypeError("Invalid key for this operation, its asymmetricKeyType must be ed25519 or ed448");break;case"RS256":case"RS384":case"RS512":if("rsa"!==r)throw new TypeError("Invalid key for this operation, its asymmetricKeyType must be rsa");Xr(t,e);break;case"PS256":case"PS384":case"PS512":if("rsa-pss"===r){const{hashAlgorithm:t,mgf1HashAlgorithm:r,saltLength:s}=a,i=parseInt(e.slice(-3),10);if(void 0!==t&&(t!==`sha${i}`||r!==t))throw new TypeError(`Invalid key for this operation, its RSA-PSS parameters do not meet the requirements of "alg" ${e}`);if(void 0!==s&&s>i>>3)throw new TypeError(`Invalid key for this operation, its RSA-PSS parameter saltLength does not meet the requirements of "alg" ${e}`)}else if("rsa"!==r)throw new TypeError("Invalid key for this operation, its asymmetricKeyType must be rsa or rsa-pss");Xr(t,e),i={padding:Nr.constants.RSA_PKCS1_PSS_PADDING,saltLength:Nr.constants.RSA_PSS_SALTLEN_DIGEST};break;case"ES256":case"ES256K":case"ES384":case"ES512":{if("ec"!==r)throw new TypeError("Invalid key for this operation, its asymmetricKeyType must be ec");const a=Yr(t),s=ea.get(e);if(a!==s)throw new TypeError(`Invalid key curve for the algorithm, its curve must be ${s}, got ${a}`);i={dsaEncoding:"ieee-p1363"};break}default:throw new Mr(`alg ${e} is not supported either by JOSE or your javascript runtime`)}return s?{format:"jwk",key:t,...i}:i?{...i,key:t}:t}(e,a))})(s,e,o),c={signature:$r(d),payload:""};return a&&(c.payload=oa.decode(n)),this._unprotectedHeader&&(c.header=this._unprotectedHeader),this._protectedHeader&&(c.protected=oa.decode(i)),c}}class pa{_flattened;constructor(e){this._flattened=new ha(e)}setProtectedHeader(e){return this._flattened.setProtectedHeader(e),this}async sign(e,t){const r=await this._flattened.sign(e,t);if(void 0===r.payload)throw new TypeError("use the flattened module for creating JWS with b64: false");return`${r.protected}.${r.payload}.${r.signature}`}}const fa=e=>Math.floor(e.getTime()/1e3),ma=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i,va=e=>{const t=ma.exec(e);if(!t||t[4]&&t[1])throw new TypeError("Invalid time period format");const r=parseFloat(t[2]);let a;switch(t[3].toLowerCase()){case"sec":case"secs":case"second":case"seconds":case"s":a=Math.round(r);break;case"minute":case"minutes":case"min":case"mins":case"m":a=Math.round(60*r);break;case"hour":case"hours":case"hr":case"hrs":case"h":a=Math.round(3600*r);break;case"day":case"days":case"d":a=Math.round(86400*r);break;case"week":case"weeks":case"w":a=Math.round(604800*r);break;default:a=Math.round(31557600*r)}return"-"===t[1]||"ago"===t[4]?-a:a};function ya(e,t){if(!Number.isFinite(t))throw new TypeError(`Invalid ${e} input`);return t}class ga{_payload;constructor(e={}){if(!Wr(e))throw new TypeError("JWT Claims Set MUST be an object");this._payload=e}setIssuer(e){return this._payload={...this._payload,iss:e},this}setSubject(e){return this._payload={...this._payload,sub:e},this}setAudience(e){return this._payload={...this._payload,aud:e},this}setJti(e){return this._payload={...this._payload,jti:e},this}setNotBefore(e){return"number"==typeof e?this._payload={...this._payload,nbf:ya("setNotBefore",e)}:e instanceof Date?this._payload={...this._payload,nbf:ya("setNotBefore",fa(e))}:this._payload={...this._payload,nbf:fa(new Date)+va(e)},this}setExpirationTime(e){return"number"==typeof e?this._payload={...this._payload,exp:ya("setExpirationTime",e)}:e instanceof Date?this._payload={...this._payload,exp:ya("setExpirationTime",fa(e))}:this._payload={...this._payload,exp:fa(new Date)+va(e)},this}setIssuedAt(e){return void 0===e?this._payload={...this._payload,iat:fa(new Date)}:e instanceof Date?this._payload={...this._payload,iat:ya("setIssuedAt",fa(e))}:this._payload="string"==typeof e?{...this._payload,iat:ya("setIssuedAt",fa(new Date)+va(e))}:{...this._payload,iat:ya("setIssuedAt",e)},this}}class _a extends ga{_protectedHeader;setProtectedHeader(e){return this._protectedHeader=e,this}async sign(e,t){const r=new pa(na.encode(JSON.stringify(this._payload)));if(r.setProtectedHeader(this._protectedHeader),Array.isArray(this._protectedHeader?.crit)&&this._protectedHeader.crit.includes("b64")&&!1===this._protectedHeader.b64)throw new zr("JWTs MUST NOT use unencoded payload");return r.sign(e,t)}}class ba{async generateProof(e,t,r,a={}){const s=this.generateCanonicalHashes(e,t),i={did:this.identity.did,kid:this.identity.kid,ts:Math.floor(Date.now()/1e3),nonce:r.nonce,audience:r.audience,sessionId:r.sessionId,requestHash:s.requestHash,responseHash:s.responseHash,...a};return{jws:await this.generateJWS(i),meta:i}}generateCanonicalHashes(e,t){const r={method:e.method,...e.params&&{params:e.params}},a=t.data;return{requestHash:this.generateSHA256Hash(r),responseHash:this.generateSHA256Hash(a)}}generateSHA256Hash(e){const t=this.canonicalizeJSON(e);return`sha256:${(0,Dr.createHash)("sha256").update(t,"utf8").digest("hex")}`}canonicalizeJSON(e){return function(e,t){return function(e,t){var r="",a=t&&t.include,s=t&&t.exclude;s&&"string"==typeof s&&(s=[s]),a&&a.sort();var i=new WeakMap,n=t&&t.allowCircular,o=t&&t.filterUndefined,d=t&&t.undefinedInArrayToNull;return function e(t,c){if(null===t||"object"!=typeof t||null!=t.toJSON)r+=JSON.stringify(t);else if(Array.isArray(t)){if(void 0!==(l=i.get(t))&&c.startsWith(l)){if(!n)throw new Error("Circular reference detected");return void(r+='"[Circular:'+l+']"')}i.set(t,c),r+="[";var u=!1;t.forEach(function(t,a){u&&(r+=","),u=!0,d&&void 0===t&&(t=null),e(t,c+"["+a+"]")}),r+="]"}else{var l;if(void 0!==(l=i.get(t))&&c.startsWith(l)){if(!n)throw new Error("Circular reference detected");return void(r+='"[Circular:'+l+']"')}i.set(t,c),r+="{";var h=!1,p=function(a){s&&s.includes(a)||(h&&(r+=","),h=!0,r+=JSON.stringify(a),r+=":",e(t[a],c+"."+a))};if("$"===c&&a)a.forEach(function(e){t.hasOwnProperty(e)&&p(e)});else{var f=Object.keys(t);o&&(f=f.filter(function(e){return void 0!==t[e]})),f.sort(),f.forEach(function(e){p(e)})}r+="}"}}(e,"$"),r}(e,{allowCircular:t,filterUndefined:!0,undefinedInArrayToNull:!0})}(e)}async generateJWS(e){try{const t=this.formatPrivateKeyAsPEM(this.identity.privateKey),r=await async function(e){if("string"!=typeof e||0!==e.indexOf("-----BEGIN PRIVATE KEY-----"))throw new TypeError('"pkcs8" must be PKCS#8 formatted string');return t=e,(0,Nr.createPrivateKey)({key:Zr.Buffer.from(t.replace(/(?:-----(?:BEGIN|END) PRIVATE KEY-----|\s)/g,""),"base64"),type:"pkcs8",format:"der"});var t}(t),a={aud:e.audience,sub:e.did,iss:e.did,requestHash:e.requestHash,responseHash:e.responseHash,ts:e.ts,nonce:e.nonce,sessionId:e.sessionId,...e.scopeId&&{scopeId:e.scopeId},...e.delegationRef&&{delegationRef:e.delegationRef},...e.clientDid&&{clientDid:e.clientDid}};return await new _a(a).setProtectedHeader({alg:"EdDSA",kid:this.identity.kid}).sign(r)}catch(e){throw new Error(`Failed to generate JWS: ${e instanceof Error?e.message:"Unknown error"}`)}}formatPrivateKeyAsPEM(e){const t=Buffer.from(e,"base64"),r=Buffer.from([48,46,2,1,0,48,5,6,3,43,101,112,4,34,4,32]),a=Buffer.concat([r,t.subarray(0,32)]).toString("base64");return"-----BEGIN PRIVATE KEY-----\n"+(a.match(/.{1,64}/g)?.join("\n")||a)+"\n-----END PRIVATE KEY-----"}async verifyProof(e,t,r){try{const a=this.generateCanonicalHashes(t,r);if(e.meta.requestHash!==a.requestHash||e.meta.responseHash!==a.responseHash)return!1;const s=e.jws.split(".");return 3===s.length&&""!==s[0]&&""!==s[1]&&""!==s[2]}catch{return!1}}constructor(e){var t,r;r=void 0,(t="identity")in this?Object.defineProperty(this,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):this[t]=r,this.identity=e}}const wa=require("fs/promises"),Pa=require("fs");var Ea=r(16928);const xa=(0,jr.promisify)(Nr.generateKeyPair);function Sa(e,t,r){return t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}class Ia{async ensureIdentity(){return this.cachedIdentity||("development"===this.config.environment?this.cachedIdentity=await this.loadOrGenerateDevIdentity():this.cachedIdentity=await this.loadProdIdentity()),this.cachedIdentity}async loadOrGenerateDevIdentity(){const e=this.config.devIdentityPath;try{if((0,Pa.existsSync)(e)){const t=await(0,wa.readFile)(e,"utf-8"),r=JSON.parse(t);let a=r.kid||r.keyId;if(r.keyId&&!r.kid&&a.startsWith("key-")){a=this.generateMultibaseKid(r.publicKey);const e={did:r.did,kid:a,privateKey:r.privateKey,publicKey:r.publicKey,createdAt:r.createdAt,lastRotated:r.lastRotated};return await this.saveDevIdentity(e),console.error(`✅ Migrated identity to new multibase kid format: ${a}`),e}return{did:r.did,kid:a,privateKey:r.privateKey,publicKey:r.publicKey,createdAt:r.createdAt,lastRotated:r.lastRotated}}}catch(t){console.warn(`Warning: Could not load identity from ${e}, generating new one`,t instanceof Error?t.message:t)}return await this.generateDevIdentity()}async generateDevIdentity(){const e=await async function(e,t){return async function(e,t){switch(e){case"RS256":case"RS384":case"RS512":case"PS256":case"PS384":case"PS512":case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":case"RSA1_5":{const e=t?.modulusLength??2048;if("number"!=typeof e||e<2048)throw new Mr("Invalid or unsupported modulusLength option provided, 2048 bits or larger keys must be used");return await xa("rsa",{modulusLength:e,publicExponent:65537})}case"ES256":return xa("ec",{namedCurve:"P-256"});case"ES256K":return xa("ec",{namedCurve:"secp256k1"});case"ES384":return xa("ec",{namedCurve:"P-384"});case"ES512":return xa("ec",{namedCurve:"P-521"});case"Ed25519":return xa("ed25519");case"EdDSA":switch(t?.crv){case void 0:case"Ed25519":return xa("ed25519");case"Ed448":return xa("ed448");default:throw new Mr("Invalid or unsupported crv option provided, supported values are Ed25519 and Ed448")}case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":{const e=t?.crv??"P-256";switch(e){case void 0:case"P-256":case"P-384":case"P-521":return xa("ec",{namedCurve:e});case"X25519":return xa("x25519");case"X448":return xa("x448");default:throw new Mr("Invalid or unsupported crv option provided, supported values are P-256, P-384, P-521, X25519, and X448")}}default:throw new Mr('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}}(e,t)}("EdDSA",{crv:"Ed25519"}),t=await async function(e){return(e=>{let t;if(qr(e)){if(!e.extractable)throw new TypeError("CryptoKey is not extractable");t=Nr.KeyObject.from(e)}else{if(!Ur(e)){if(e instanceof Uint8Array)return{kty:"oct",k:$r(e)};throw new TypeError(Hr(e,...Jr,"Uint8Array"))}t=e}if("secret"!==t.type&&!["rsa","ec","ed25519","x25519","ed448","x448"].includes(t.asymmetricKeyType))throw new Mr("Unsupported key asymmetricKeyType");return t.export({format:"jwk"})})(e)}(e.privateKey);if(!t.x||!t.d)throw new Error("Failed to generate Ed25519 keypair");const r=Buffer.from(t.d,"base64url").toString("base64"),a=Buffer.from(t.x,"base64url").toString("base64"),s=this.generateMultibaseKid(a),i={did:`did:web:localhost:3000:agents:${(0,Dr.createHash)("sha256").update(a).digest("hex").substring(0,8)}`,kid:s,privateKey:r,publicKey:a,createdAt:(new Date).toISOString()};return await this.saveDevIdentity(i),i}generateMultibaseKid(e){const t=Buffer.from(e,"base64"),r=Buffer.concat([Buffer.from([237,1]),t]);return`z${this.encodeBase58(r)}`}encodeBase58(e){let t=BigInt("0x"+e.toString("hex")),r="";for(;t>0n;)r="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"[Number(t%58n)]+r,t/=58n;for(let t=0;t<e.length&&0===e[t];t++)r="1"+r;return r}async saveDevIdentity(e){const t=this.config.devIdentityPath;await(0,wa.mkdir)((0,Ea.dirname)(t),{recursive:!0});const r={version:"1.0",did:e.did,kid:e.kid,privateKey:e.privateKey,publicKey:e.publicKey,createdAt:e.createdAt,lastRotated:e.lastRotated};await(0,wa.writeFile)(t,JSON.stringify(r,null,2),{mode:384}),console.error(`✅ Identity saved to ${t}`),console.error(` DID: ${e.did}`),console.error(` Key ID: ${e.kid}`)}async loadProdIdentity(){const e=["AGENT_PRIVATE_KEY","AGENT_KEY_ID","AGENT_DID","KYA_VOUCHED_API_KEY"],t=[],r={};for(const a of e){const e=process.env[a];e?r[a]=e:t.push(a)}if(t.length>0){const e=new Error(`Missing required environment variables for production identity: ${t.join(", ")}\nRequired variables:\n AGENT_PRIVATE_KEY - Base64-encoded Ed25519 private key\n AGENT_KEY_ID - Key identifier\n AGENT_DID - Agent DID\n KYA_VOUCHED_API_KEY - Know-That-AI API key`);throw e.code="XMCP_I_ENOIDENTITY",e}const a=Buffer.from(r.AGENT_PRIVATE_KEY,"base64"),s=(0,Dr.createHash)("sha256").update(a).digest("base64");return{did:r.AGENT_DID,kid:r.AGENT_KEY_ID,privateKey:r.AGENT_PRIVATE_KEY,publicKey:s,createdAt:(new Date).toISOString()}}async validateIdentity(e){try{return!!(e.did&&e.kid&&e.privateKey&&e.publicKey)&&!!e.did.startsWith("did:")&&(Buffer.from(e.privateKey,"base64"),Buffer.from(e.publicKey,"base64"),!0)}catch{return!1}}clearCache(){this.cachedIdentity=void 0}getConfig(){return{...this.config}}constructor(e={environment:"development"}){Sa(this,"config",void 0),Sa(this,"cachedIdentity",void 0);const t=r(16928);let a=e.devIdentityPath||".mcpi/identity.json";t.isAbsolute(a)||(a=t.resolve(process.cwd(),a)),this.config={privacyMode:!1,...e,devIdentityPath:a},this.config.debug&&console.error("[IdentityManager] Constructed with config:",{environment:this.config.environment,devIdentityPath:this.config.devIdentityPath})}}function ka(e,t,r){return t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}new Ia;const Ta=new class{register(e,t){this.config.set(e,t),this.debug&&console.error(`[ToolProtectionRegistry] Registered protection for tool: ${e}`,t)}registerAll(e){for(const[t,r]of Object.entries(e))this.register(t,r)}get(e){return this.config.get(e)||null}requiresDelegation(e){const t=this.get(e);return t?.requiresDelegation||!1}getRequiredScopes(e){const t=this.get(e);return t?.requiredScopes||[]}setDelegationVerifier(e){this.delegationVerifier=e}setAuthConfig(e){this.authConfig=e}getDelegationVerifier(){return this.delegationVerifier}getAuthConfig(){return this.authConfig}setDebug(e){this.debug=e}setCurrentSession(e){this.currentSession=e}getCurrentSession(){return this.currentSession}getCurrentAgentDid(){return this.currentSession?.agentDid||null}clear(){this.config.clear(),this.delegationVerifier=null,this.authConfig=null,this.currentSession=null}getProtectedTools(){return Array.from(this.config.keys())}constructor(){ka(this,"config",new Map),ka(this,"delegationVerifier",null),ka(this,"authConfig",null),ka(this,"debug",!1),ka(this,"currentSession",null)}};var Ca=r(74488);async function Aa(e,t,r,a){const s=await r.resumeTokenStore.create(e,t,{requestedAt:Date.now()}),i=Date.now()+(r.bouncer.resumeTokenTtl||6e5),n=new URL(r.bouncer.authorizationUrl);n.searchParams.set("agent_did",e),n.searchParams.set("scopes",t.join(",")),n.searchParams.set("resume_token",s);const o={title:"Authorization Required",hint:["link","qr"],authorizationCode:s.substring(0,8).toUpperCase(),qrUrl:`https://chart.googleapis.com/chart?cht=qr&chs=300x300&chl=${encodeURIComponent(n.toString())}`};return(0,Ca.createNeedsAuthorizationError)({message:a,authorizationUrl:n.toString(),resumeToken:s,expiresAt:i,scopes:t,display:o})}function Oa(e,t,r){return t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}class Ra{async has(e){const t=this.cache.get(e);return!(!t||Date.now()>t.expiresAt&&(this.cache.delete(e),1))}async add(e,t){const r=this.cache.get(e);if(r&&Date.now()<=r.expiresAt)throw new Error(`Nonce ${e} already exists - potential replay attack`);const a=t<=0?Date.now()-1:Date.now()+1e3*t,s={sessionId:`mem_${Date.now()}_${Math.random().toString(36).substring(2)}`,expiresAt:a};this.cache.set(e,s)}async cleanup(){const e=Date.now(),t=[];for(const[r,a]of this.cache.entries())e>a.expiresAt&&t.push(r);for(const e of t)this.cache.delete(e)}getStats(){const e=Date.now();let t=0;for(const r of this.cache.values())e>r.expiresAt&&t++;return{size:this.cache.size,expired:t}}clear(){this.cache.clear()}destroy(){this.cleanupInterval&&(clearInterval(this.cleanupInterval),this.cleanupInterval=void 0),this.cache.clear()}constructor(e=6e4){Oa(this,"cache",new Map),Oa(this,"cleanupInterval",void 0),console.warn("⚠️ MemoryNonceCache is not suitable for multi-instance deployments. For production use with multiple instances, configure Redis, DynamoDB, or Cloudflare KV."),this.cleanupInterval=setInterval(()=>{this.cleanup().catch(console.error)},e)}}function Da(e,t,r){return t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}class Na{setServerDid(e){this.config.serverDid=e}async validateHandshake(e){try{const t=Math.floor(Date.now()/1e3),r=Math.abs(t-e.timestamp);if(r>this.config.timestampSkewSeconds)return{success:!1,error:{code:"XMCP_I_EHANDSHAKE",message:`Timestamp outside acceptable range (±${this.config.timestampSkewSeconds}s)`,remediation:`Check NTP sync on client and server. Current server time: ${t}, received: ${e.timestamp}, diff: ${r}s. Adjust XMCP_I_TS_SKEW_SEC if needed.`}};if(await this.config.nonceCache.has(e.nonce))return{success:!1,error:{code:"XMCP_I_EHANDSHAKE",message:"Nonce already used (replay attack prevention)",remediation:"Generate a new unique nonce for each request"}};const a=60*this.config.sessionTtlMinutes+60;await this.config.nonceCache.add(e.nonce,a);const s=this.generateSessionId(),i={sessionId:s,audience:e.audience,nonce:e.nonce,timestamp:e.timestamp,createdAt:t,lastActivity:t,ttlMinutes:this.config.sessionTtlMinutes,agentDid:e.agentDid,...this.config.serverDid&&{serverDid:this.config.serverDid}};return this.sessions.set(s,i),{success:!0,session:i}}catch(e){return{success:!1,error:{code:"XMCP_I_EHANDSHAKE",message:`Handshake validation failed: ${e instanceof Error?e.message:"Unknown error"}`}}}}async getSession(e){const t=this.sessions.get(e);if(!t)return null;const r=Math.floor(Date.now()/1e3);return r-t.lastActivity>60*t.ttlMinutes||this.config.absoluteSessionLifetime&&r-t.createdAt>60*this.config.absoluteSessionLifetime?(this.sessions.delete(e),null):(t.lastActivity=r,this.sessions.set(e,t),t)}generateSessionId(){return`sess_${Date.now().toString(36)}_${(0,Dr.randomBytes)(8).toString("hex")}`}static generateNonce(){return(0,Dr.randomBytes)(16).toString("base64url")}async cleanup(){const e=Math.floor(Date.now()/1e3);for(const[t,r]of this.sessions.entries()){let a=e-r.lastActivity>60*r.ttlMinutes;!a&&this.config.absoluteSessionLifetime&&(a=e-r.createdAt>60*this.config.absoluteSessionLifetime),a&&this.sessions.delete(t)}await this.config.nonceCache.cleanup()}getStats(){return{activeSessions:this.sessions.size,config:{timestampSkewSeconds:this.config.timestampSkewSeconds,sessionTtlMinutes:this.config.sessionTtlMinutes,absoluteSessionLifetime:this.config.absoluteSessionLifetime,cacheType:this.config.nonceCache.constructor.name}}}clearSessions(){this.sessions.clear()}constructor(e={}){Da(this,"config",void 0),Da(this,"sessions",new Map),this.config={timestampSkewSeconds:parseInt(process.env.XMCP_I_TS_SKEW_SEC||"120"),sessionTtlMinutes:parseInt(process.env.XMCP_I_SESSION_TTL_MIN||"30"),nonceCache:new Ra,...e},this.config.nonceCache instanceof Ra&&console.warn("Warning: Using MemoryNonceCache - not suitable for multi-instance deployments. Consider using Redis, DynamoDB, or Cloudflare KV for production.")}}new Na;const Za=new(require("async_hooks").AsyncLocalStorage);function $a(){return(Za.getStore()?.session)?.agentDid}function ja(e,t,r){return t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}class Fa{async submit(e){if(0===e.length)return;const t={delegation_id:null,session_id:e[0]?.meta?.sessionId||"unknown",proofs:e},r=await fetch(`${this.apiUrl}/api/v1/bouncer/proofs`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify(t)});if(!r.ok){const e=await r.text().catch(()=>"Unable to read error body");throw new Error(`AgentShield proof submission failed: ${r.status} ${r.statusText}\n${e}`)}}constructor(e,t){ja(this,"name","AgentShield"),ja(this,"apiUrl",void 0),ja(this,"apiKey",void 0),this.apiUrl=e.replace(/\/$/,""),this.apiKey=t}}class Ma{enqueue(e){this.closed?console.warn("[ProofBatchQueue] Queue is closed, dropping proof"):(this.queue.push(e),this.stats.queued++,this.config.debug&&console.log(`[ProofBatchQueue] Enqueued proof (queue size: ${this.queue.length})`),this.queue.length>=this.config.maxBatchSize&&this.flush())}async flush(){if(0===this.queue.length)return;const e=this.queue.splice(0,this.config.maxBatchSize);this.config.debug&&console.log(`[ProofBatchQueue] Flushing ${e.length} proofs to ${this.config.destinations.length} destinations`);for(const t of this.config.destinations){const r={proofs:e,destination:t,retryCount:0};this.submitBatch(r)}}async submitBatch(e){try{await e.destination.submit(e.proofs),this.stats.submitted+=e.proofs.length,this.stats.batchesSubmitted++,this.config.debug&&console.log(`[ProofBatchQueue] Successfully submitted ${e.proofs.length} proofs to ${e.destination.name}`)}catch(t){if(console.error(`[ProofBatchQueue] Failed to submit to ${e.destination.name}:`,t),e.retryCount<this.config.maxRetries){e.retryCount++;const t=Math.min(1e3*Math.pow(2,e.retryCount-1),16e3);e.nextRetryAt=Date.now()+t,this.pendingBatches.push(e),this.config.debug&&console.log(`[ProofBatchQueue] Scheduling retry ${e.retryCount}/${this.config.maxRetries} in ${t}ms`)}else this.stats.failed+=e.proofs.length,console.error(`[ProofBatchQueue] Max retries exceeded for ${e.destination.name}, dropping ${e.proofs.length} proofs`)}}startFlushTimer(){this.flushTimer=setInterval(()=>{this.queue.length>0&&this.flush()},this.config.flushIntervalMs),"function"==typeof this.flushTimer.unref&&this.flushTimer.unref()}startRetryTimer(){this.retryTimer=setInterval(()=>{const e=Date.now(),t=this.pendingBatches.filter(t=>t.nextRetryAt&&t.nextRetryAt<=e);if(t.length>0){this.pendingBatches=this.pendingBatches.filter(e=>!t.includes(e));for(const e of t)this.submitBatch(e)}},1e3),"function"==typeof this.retryTimer.unref&&this.retryTimer.unref()}async close(){this.closed=!0,this.flushTimer&&clearInterval(this.flushTimer),this.retryTimer&&clearInterval(this.retryTimer),await this.flush();const e=Date.now();for(;this.pendingBatches.length>0&&Date.now()-e<3e4;)await new Promise(e=>setTimeout(e,100));this.pendingBatches.length>0&&console.warn(`[ProofBatchQueue] Closing with ${this.pendingBatches.length} pending batches (timed out)`)}getStats(){return{...this.stats,queueSize:this.queue.length,pendingBatches:this.pendingBatches.length}}constructor(e){ja(this,"queue",[]),ja(this,"pendingBatches",[]),ja(this,"config",void 0),ja(this,"flushTimer",void 0),ja(this,"retryTimer",void 0),ja(this,"closed",!1),ja(this,"stats",{queued:0,submitted:0,failed:0,batchesSubmitted:0}),this.config={destinations:e.destinations,maxBatchSize:e.maxBatchSize||10,flushIntervalMs:e.flushIntervalMs||5e3,maxRetries:e.maxRetries||5,debug:e.debug||!1},this.startFlushTimer(),this.startRetryTimer()}}const La="undefined"!=typeof RUNTIME_CONFIG_PATH?RUNTIME_CONFIG_PATH:void 0,za=La?"string"==typeof La?JSON.parse(La):La:null;let Va=null;async function qa(e,t,a){if("undefined"!=typeof global){if(global.__MCPI_HANDLERS_REGISTERED__)return a?.debug&&console.error("[MCPI] Handlers already registered, skipping duplicate registration"),e;global.__MCPI_HANDLERS_REGISTERED__=!0}a?.debug&&console.error("[MCPI] Registering handlers for the first time");const s=new Na;let i=null;if(a?.enabled)try{i=new Ia({environment:a.environment||"development",devIdentityPath:a.devIdentityPath,debug:a.debug});const e=await i.ensureIdentity();a.debug&&(console.error(`[MCPI] Identity enabled - DID: ${e.did}`),console.error(`[MCPI] Identity path: ${a.devIdentityPath||".mcpi/identity.json"}`))}catch(e){a?.debug&&console.error("[MCPI] Failed to initialize identity:",e)}await async function(e){if(Va)return Va;if(!za)return e&&console.error("[MCPI] No runtime config found - proof submission disabled"),null;try{e&&console.error("[MCPI] Loading runtime config from:",za);const t=await r(49436)(za),a="function"==typeof t.getRuntimeConfig?t.getRuntimeConfig():t.default;if(!a?.proofing?.enabled)return e&&console.error("[MCPI] Proofing is disabled in runtime config"),null;const s=a.proofing;if(!s.batchQueue?.destinations||0===s.batchQueue.destinations.length)return e&&console.error("[MCPI] No proof destinations configured"),null;const i=[];for(const t of s.batchQueue.destinations)"agentshield"===t.type&&(i.push(new Fa(t.apiUrl,t.apiKey)),e&&console.error(`[MCPI] Added AgentShield destination: ${t.apiUrl}`));return 0===i.length?(e&&console.error("[MCPI] No valid proof destinations configured"),null):(Va=new Ma({destinations:i,maxBatchSize:s.batchQueue.maxBatchSize||10,flushIntervalMs:s.batchQueue.flushIntervalMs||5e3,maxRetries:s.batchQueue.maxRetries||3,debug:s.batchQueue.debug||e}),e&&console.error(`[MCPI] ProofBatchQueue initialized (batch: ${s.batchQueue.maxBatchSize}, flush: ${s.batchQueue.flushIntervalMs}ms, destinations: ${i.length})`),Va)}catch(t){return e&&console.error("[MCPI] Failed to initialize ProofBatchQueue:",t),null}}(a?.debug);const n=[],o=new Map;return t.forEach((e,t)=>{const r=function(e){return(e.split("/").pop()||e).replace(/\.[^/.]+$/,"")}(t),a={name:r,description:"No description provided"};let s={};const{default:i,metadata:d,schema:c}=e;"object"==typeof d&&null!==d&&Object.assign(a,d),function(e){if("object"!=typeof e||null===e)return!1;const t=e;return Object.entries(t).every(([e,t])=>"string"==typeof e&&"object"==typeof t&&null!==t&&"parse"in t&&"function"==typeof t.parse)}(c)?Object.assign(s,c):null!=c&&console.warn(`Invalid schema for tool "${a.name}" at ${t}. Expected Record<string, z.ZodType>`),void 0===a.annotations&&(a.annotations={}),void 0===a.annotations.title&&(a.annotations.title=a.name);const u={name:a.name,description:a.description,inputSchema:{type:"object",properties:Object.fromEntries(Object.entries(s).map(([e,t])=>[e,{type:"string"}]))}};n.push(u),o.set(a.name,i)}),a?.debug&&console.error("[MCPI] About to register handlers (tools/list, tools/call)"),e.setRequestHandler(ar,async e=>({tools:n})),e.setRequestHandler(nr,async e=>{const t=e._meta?.sessionId;let r=null;return t&&(r=await s.getSession(t),!r&&a?.debug&&console.error(`[MCPI] Session not found or expired: ${t}`)),n={session:r||void 0,requestId:e._meta?.requestId,startTime:Date.now()},d=async()=>{const{name:t,arguments:r}=e.params,s=o.get(t);if(!s)return{content:[{type:"text",text:`Tool "${t}" not found`}],isError:!0};const n=Ta.get(t);if(n?.requiresDelegation){const e=Ta.getAuthConfig();if(!Ta.getDelegationVerifier()||!e)return a?.debug&&console.error(`[MCPI] Tool "${t}" requires delegation but verifier not configured`),{content:[{type:"text",text:`❌ Tool "${t}" requires delegation verification, but the delegation system is not configured.\n\nTo fix this:\n1. Configure a delegation verifier:\n - MemoryDelegationVerifier (development/testing)\n - KVDelegationVerifier (production with KV store)\n - AgentShieldVerifier (production with AgentShield service)\n\n2. Enable delegation in your runtime config:\n const runtime = new MCPIRuntime({\n delegation: { enabled: true },\n // ... other config\n });\n\n3. Ensure the verifier is initialized before tool execution.\n\n📚 Documentation: https://docs.mcp-i.dev/delegation/setup`}],isError:!0};const r=$a();if(!r)return a?.debug&&console.error(`[MCPI] Tool "${t}" requires delegation but no agent DID in session`),{content:[{type:"text",text:`❌ Tool "${t}" requires delegation, but no agent identity was found in the current session.\n\nThis usually means one of the following:\n\n1. **No handshake was performed**: The MCP client must send a handshake request before calling protected tools.\n Example handshake:\n {\n "agentDid": "did:key:z6Mk...",\n "nonce": "unique-value",\n "audience": "server-did",\n "timestamp": ${Date.now()}\n }\n\n2. **Handshake missing agentDid**: Ensure the handshake request includes the 'agentDid' field.\n\n3. **Session expired**: The session may have expired. Try performing a new handshake.\n\n4. **Request missing sessionId**: Ensure tool call requests include _meta.sessionId from the handshake response.\n\n📚 Learn more: https://docs.mcp-i.dev/delegation/handshake`}],isError:!0};a?.debug&&console.error(`[MCPI] Tool "${t}" requires delegation - verifying scopes: ${n.requiredScopes?.join(", ")}`);const s=await async function(e,t,r){const a=Date.now();let s,i;if(r.debug&&console.log(`[AuthHandshake] Verifying ${e} for scopes: ${t.join(", ")}`),r.kta&&void 0!==r.bouncer.minReputationScore)try{if(s=await async function(e,t){const r=t.apiUrl.replace(/\/$/,""),a={"Content-Type":"application/json"};t.apiKey&&(a["X-API-Key"]=t.apiKey);const s=await fetch(`${r}/api/v1/reputation/${encodeURIComponent(e)}`,{method:"GET",headers:a});if(!s.ok){if(404===s.status)return{agentDid:e,score:50,totalInteractions:0,successRate:0,riskLevel:"unknown",updatedAt:Date.now()};throw new Error(`KTA API error: ${s.status} ${s.statusText}`)}const i=await s.json();return{agentDid:i.agentDid||e,score:i.score||50,totalInteractions:i.totalInteractions||0,successRate:i.successRate||0,riskLevel:i.riskLevel||"unknown",updatedAt:i.updatedAt||Date.now()}}(e,r.kta),r.debug&&console.log(`[AuthHandshake] Reputation score: ${s.score}`),s.score<r.bouncer.minReputationScore)return r.debug&&console.log(`[AuthHandshake] Reputation ${s.score} < ${r.bouncer.minReputationScore}, requiring authorization`),{authorized:!1,authError:await Aa(e,t,r,"Agent reputation score below threshold"),reputation:s,reason:"Low reputation score"}}catch(e){console.warn("[AuthHandshake] Failed to check reputation:",e)}try{i=await r.delegationVerifier.verify(e,t)}catch(a){console.error("[AuthHandshake] Delegation verification failed:",a);const s=`Delegation verification error: ${a instanceof Error?a.message:"Unknown error"}`;return{authorized:!1,authError:await Aa(e,t,r,s),reason:s}}return i.valid&&i.delegation?(r.debug&&console.log(`[AuthHandshake] Delegation valid, authorized (${Date.now()-a}ms)`),{authorized:!0,delegation:i.delegation,reputation:s,reason:"Valid delegation found"}):(r.debug&&console.log(`[AuthHandshake] No delegation found, returning needs_authorization (${Date.now()-a}ms)`),{authorized:!1,authError:await Aa(e,t,r,i.reason||"No valid delegation found"),reputation:s,reason:i.reason||"No delegation"})}(r,n.requiredScopes||[],e);if(!s.authorized)return a?.debug&&console.error(`[MCPI] Tool "${t}" blocked - authorization required`),{content:[{type:"text",text:JSON.stringify({error:"needs_authorization",message:`Tool "${t}" requires user authorization`,authorizationUrl:s.authError?.authorizationUrl,resumeToken:s.authError?.resumeToken,scopes:s.authError?.scopes,display:s.authError?.display})}],isError:!0};a?.debug&&console.error(`[MCPI] Tool "${t}" authorized - executing handler`)}try{const e=await s(r||{}),n={content:[{type:"text",text:"string"==typeof e?e:JSON.stringify(e)}]};if(i)try{const s=await i.ensureIdentity(),o={method:t,params:r||{}},d={data:e},c=Math.floor(Date.now()/1e3),u={sessionId:`tool-${Date.now()}`,nonce:`${Date.now()}`,audience:"client",createdAt:c,timestamp:c,lastActivity:c,ttlMinutes:30};let l;const h=Ta.get(t);l=h?.requiredScopes&&h.requiredScopes.length>0?h.requiredScopes[0]:`${t}:execute`,a?.debug&&console.error(`[MCPI] Proof scopeId for tool "${t}": ${l}`);const p=new ba(s),f=await p.generateProof(o,d,u,{scopeId:l,clientDid:u?.clientDid});if(a?.debug&&console.error(`[MCPI] Generated proof for tool "${t}" - DID: ${f.meta.did}`),Va)try{Va.enqueue(f),a?.debug&&console.error("[MCPI] Proof enqueued for submission to AgentShield")}catch(e){a?.debug&&console.error("[MCPI] Failed to enqueue proof:",e)}return{...n,_meta:{proof:f}}}catch(e){return a?.debug&&console.error(`[MCPI] Failed to generate proof for tool "${t}":`,e),n}return n}catch(e){return{content:[{type:"text",text:`Error executing tool "${t}": ${e instanceof Error?e.message:String(e)}`}],isError:!0}}},Za.run(n,d);var n,d}),a?.debug&&console.error("[MCPI] Handlers registered successfully"),e}"undefined"!=typeof global&&(global.__MCPI_HANDLERS_REGISTERED__=global.__MCPI_HANDLERS_REGISTERED__||!1);const Ua=INJECTED_TOOLS,Ka="undefined"!=typeof IDENTITY_CONFIG?IDENTITY_CONFIG:void 0,Ha=Ka?JSON.parse(Ka):void 0,Ba={name:"MCP Server",version:"0.0.1"},Qa={capabilities:{tools:{}}};function Ja(e,t,r){return t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}"undefined"!=typeof global&&(global.__MCPI_SERVER_CREATED__=global.__MCPI_SERVER_CREATED__||!1);class Wa{start(){try{this.mcpServer.connect(this.transport),this.debug&&console.error("[STDIO] MCP Server running with STDIO transport"),this.setupShutdownHandlers()}catch(e){this.debug&&console.error("[STDIO] Error starting STDIO transport:",e),process.exit(1)}}setupShutdownHandlers(){const e=()=>{this.debug&&console.error("[STDIO] Shutting down STDIO transport"),process.exit(0)};process.on("SIGINT",e),process.on("SIGTERM",e)}shutdown(){this.debug&&console.error("[STDIO] Shutting down STDIO transport"),process.exit(0)}constructor(e,t=!1){Ja(this,"mcpServer",void 0),Ja(this,"transport",void 0),Ja(this,"debug",void 0),this.mcpServer=e,this.transport=new Cr,this.debug=t}}const Ga=STDIO_CONFIG.debug||!1;(async function(){if(Ha?.debug&&console.error("[createServer] Starting server creation"),"undefined"!=typeof global&&global.__MCPI_SERVER_CREATED__&&(Ha?.debug&&console.error("[createServer] Server already exists, returning cached instance"),global.__MCPI_SERVER_INSTANCE__))return global.__MCPI_SERVER_INSTANCE__;Ha?.debug&&(console.error("[createServer] Creating new McpServer"),console.error("[createServer] SERVER_INFO constant:",JSON.stringify(Ba)),console.error("[createServer] SERVER_CAPABILITIES constant:",JSON.stringify(Qa)),console.error("[createServer] Calling: new McpServer(SERVER_INFO, SERVER_CAPABILITIES)"));const e=new Rr(Ba,Qa);if(Ha?.debug){console.error("[createServer] Server created successfully");const t=e;console.error("[createServer] Actual server._serverInfo:",JSON.stringify(t._serverInfo||"undefined")),console.error("[createServer] Actual server._capabilities:",JSON.stringify(t._capabilities||"undefined")),console.error("[createServer] Loading tools...")}const[t,r]=function(){const e=new Map,t=Object.keys(Ua);return Ha?.debug&&console.error("[loadTools] Injected tool paths:",t),[t.map(t=>Ua[t]().then(r=>{Ha?.debug&&console.error("[loadTools] Loaded tool from path:",t),e.set(t,r)})),e]}();await Promise.all(t),Ha?.debug&&console.error("[createServer] Tools loaded, configuring server");const a=await async function(e,t){return await qa(e,t,Ha),e}(e,r);return Ha?.debug&&console.error("[createServer] Server configured successfully"),"undefined"!=typeof global&&(global.__MCPI_SERVER_CREATED__=!0,global.__MCPI_SERVER_INSTANCE__=a),a})().then(e=>{new Wa(e,Ga).start()})})()})();
|
|
2
|
+
(()=>{var e={1258:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DelegationCredentialSchema=t.DelegationCredentialSubjectSchema=t.DELEGATION_CREDENTIAL_CONTEXT=t.DELEGATION_STATUSES=t.DEFAULT_DELEGATION_STATUS=t.MAX_DELEGATION_CHAIN_DEPTH=t.DelegationVerificationResultSchema=t.DelegationCreationRequestSchema=t.DelegationChainSchema=t.DelegationChainEntrySchema=t.DelegationRecordSchema=t.DelegationStatusSchema=void 0,t.validateDelegationRecord=function(e){return t.DelegationRecordSchema.safeParse(e)},t.validateDelegationChain=function(e){return t.DelegationChainSchema.safeParse(e)},t.isDelegationExpired=n,t.isDelegationNotYetValid=o,t.isDelegationCurrentlyValid=function(e){return"active"===e.status&&(!n(e)&&!o(e))},t.validateDelegationCredential=function(e){return t.DelegationCredentialSchema.safeParse(e)},t.extractDelegationFromVC=function(e){const t=e.credentialSubject.delegation;let r="";if(e.proof){const t=e.proof;r=t.proofValue||t.jws||t.signatureValue||""}return{id:t.id,issuerDid:t.issuerDid,subjectDid:t.subjectDid,controller:t.controller,vcId:e.id||`vc:${t.id}`,parentId:t.parentId,constraints:t.constraints,signature:r,status:t.status,createdAt:t.createdAt,revokedAt:void 0,revokedReason:void 0,metadata:t.metadata}},t.wrapDelegationAsVC=function(e,r){const a=(new Date).toISOString(),s=e.constraints.notAfter?new Date(1e3*e.constraints.notAfter).toISOString():r?.expirationDate;let i=r?.issuanceDate||a;return!r?.issuanceDate&&e.createdAt&&(i=new Date(e.createdAt).toISOString()),{"@context":["https://www.w3.org/2018/credentials/v1",t.DELEGATION_CREDENTIAL_CONTEXT],id:r?.id||e.vcId||`urn:uuid:${e.id}`,type:["VerifiableCredential","DelegationCredential"],issuer:e.issuerDid,issuanceDate:i,expirationDate:s,credentialSubject:{id:e.subjectDid,delegation:{id:e.id,issuerDid:e.issuerDid,subjectDid:e.subjectDid,controller:e.controller,parentId:e.parentId,constraints:e.constraints,status:e.status,createdAt:e.createdAt,metadata:e.metadata}},credentialStatus:r?.credentialStatus}},t.isDelegationCredentialExpired=function(e){if(e.expirationDate&&new Date(e.expirationDate)<new Date)return!0;const t=e.credentialSubject.delegation;return!!(t.constraints.notAfter&&Math.floor(Date.now()/1e3)>t.constraints.notAfter)},t.isDelegationCredentialNotYetValid=function(e){const t=e.credentialSubject.delegation;return!!(t.constraints.notBefore&&Math.floor(Date.now()/1e3)<t.constraints.notBefore)};const a=r(90315),s=r(4774),i=r(46511);function n(e){return!!e.constraints.notAfter&&Math.floor(Date.now()/1e3)>e.constraints.notAfter}function o(e){return!!e.constraints.notBefore&&Math.floor(Date.now()/1e3)<e.constraints.notBefore}t.DelegationStatusSchema=a.z.enum(["active","revoked","expired"]),t.DelegationRecordSchema=a.z.object({id:a.z.string().min(1),issuerDid:a.z.string().min(1),subjectDid:a.z.string().min(1),controller:a.z.string().optional(),vcId:a.z.string().min(1),parentId:a.z.string().optional(),constraints:s.DelegationConstraintsSchema,signature:a.z.string().min(1),status:t.DelegationStatusSchema,createdAt:a.z.number().int().positive().optional(),revokedAt:a.z.number().int().positive().optional(),revokedReason:a.z.string().optional(),metadata:a.z.record(a.z.any()).optional()}).passthrough(),t.DelegationChainEntrySchema=a.z.object({delegationId:a.z.string().min(1),issuerDid:a.z.string().min(1),subjectDid:a.z.string().min(1),vcId:a.z.string().min(1),depth:a.z.number().int().nonnegative(),constraints:s.DelegationConstraintsSchema,status:t.DelegationStatusSchema}),t.DelegationChainSchema=a.z.object({rootIssuer:a.z.string().min(1),leafSubject:a.z.string().min(1),chain:a.z.array(t.DelegationChainEntrySchema).min(1),depth:a.z.number().int().nonnegative(),valid:a.z.boolean(),errors:a.z.array(a.z.string()).optional()}),t.DelegationCreationRequestSchema=a.z.object({issuerDid:a.z.string().min(1),subjectDid:a.z.string().min(1),controller:a.z.string().optional(),constraints:s.DelegationConstraintsSchema,parentId:a.z.string().optional(),vcId:a.z.string().optional()}),t.DelegationVerificationResultSchema=a.z.object({valid:a.z.boolean(),delegationId:a.z.string().min(1),status:t.DelegationStatusSchema,reason:a.z.string().optional(),credentialValid:a.z.boolean().optional(),chainValid:a.z.boolean().optional(),verifiedAt:a.z.number().int().positive(),details:a.z.record(a.z.any()).optional()}),t.MAX_DELEGATION_CHAIN_DEPTH=10,t.DEFAULT_DELEGATION_STATUS="active",t.DELEGATION_STATUSES=["active","revoked","expired"],t.DELEGATION_CREDENTIAL_CONTEXT="https://schemas.kya-os.ai/xmcp-i/credentials/delegation.v1.0.0.json",t.DelegationCredentialSubjectSchema=a.z.object({id:a.z.string().min(1),delegation:a.z.object({id:a.z.string().min(1),issuerDid:a.z.string().min(1),subjectDid:a.z.string().min(1),controller:a.z.string().optional(),parentId:a.z.string().optional(),constraints:s.DelegationConstraintsSchema,status:t.DelegationStatusSchema.default("active"),createdAt:a.z.number().int().positive().optional(),metadata:a.z.record(a.z.any()).optional()})}),t.DelegationCredentialSchema=i.VerifiableCredentialSchema.extend({"@context":a.z.array(a.z.union([a.z.string().url(),a.z.record(a.z.any())])).refine(e=>{const t=e[0];return"string"==typeof t&&"https://www.w3.org/2018/credentials/v1"===t},{message:"First @context must be W3C VC context"}),type:a.z.array(a.z.string()).refine(e=>e.includes("VerifiableCredential")&&e.includes("DelegationCredential"),{message:'type must include both "VerifiableCredential" and "DelegationCredential"'}),issuer:i.IssuerSchema,issuanceDate:a.z.string().datetime(),expirationDate:a.z.string().datetime().optional(),credentialSubject:t.DelegationCredentialSubjectSchema,credentialStatus:i.CredentialStatusSchema.optional(),proof:i.ProofSchema.optional()})},2603:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.StatusList2021Manager=void 0,t.createStatusListManager=function(e,t,r,a,s,n){return new i(e,t,r,a,s,n)};const a=r(33021),s=r(98770);class i{storage;identity;signingFunction;compressor;decompressor;statusListBaseUrl;defaultListSize;constructor(e,t,r,a,s,i){this.storage=e,this.identity=t,this.signingFunction=r,this.compressor=a,this.decompressor=s,this.statusListBaseUrl=i?.statusListBaseUrl||"https://status.example.com",this.defaultListSize=i?.defaultListSize||131072}async allocateStatusEntry(e){const t=`${this.statusListBaseUrl}/${e}/v1`,r=await this.storage.allocateIndex(t);return await this.ensureStatusListExists(t,e),{id:`${t}#${r}`,type:"StatusList2021Entry",statusPurpose:e,statusListIndex:r.toString(),statusListCredential:t}}async updateStatus(e,t){const{statusListCredential:r,statusListIndex:i}=e,n=await this.storage.getStatusList(r);if(!n)throw new Error(`Status list not found: ${r}`);const o=await a.BitstringManager.decode(n.credentialSubject.encodedList,this.compressor,this.decompressor),c=parseInt(i,10);o.setBit(c,t);const d=await o.encode(),u={...n,credentialSubject:{...n.credentialSubject,encodedList:d}},l={...u};delete l.proof;const h=(0,s.canonicalizeJSON)(l),p=await this.signingFunction(h,this.identity.getDid(),this.identity.getKeyId()),f={...u,proof:p};await this.storage.setStatusList(r,f)}async checkStatus(e){const{statusListCredential:t,statusListIndex:r}=e,s=await this.storage.getStatusList(t);if(!s)return!1;const i=await a.BitstringManager.decode(s.credentialSubject.encodedList,this.compressor,this.decompressor),n=parseInt(r,10);return i.getBit(n)}async getRevokedIndices(e){const t=await this.storage.getStatusList(e);return t?(await a.BitstringManager.decode(t.credentialSubject.encodedList,this.compressor,this.decompressor)).getSetBits():[]}async ensureStatusListExists(e,t){if(await this.storage.getStatusList(e))return;const r=new a.BitstringManager(this.defaultListSize,this.compressor,this.decompressor),i=await r.encode(),n={"@context":["https://www.w3.org/2018/credentials/v1","https://w3id.org/vc/status-list/2021/v1"],id:e,type:["VerifiableCredential","StatusList2021Credential"],issuer:this.identity.getDid(),issuanceDate:(new Date).toISOString(),credentialSubject:{id:`${e}#list`,type:"StatusList2021",statusPurpose:t,encodedList:i}},o=(0,s.canonicalizeJSON)(n),c=await this.signingFunction(o,this.identity.getDid(),this.identity.getKeyId()),d={...n,proof:c};await this.storage.setStatusList(e,d)}getStatusListBaseUrl(){return this.statusListBaseUrl}getDefaultListSize(){return this.defaultListSize}}t.StatusList2021Manager=i},4774:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.MAX_WINDOW_DURATION_SEC=t.MAX_BUDGET_CAP=t.SUPPORTED_MATCHERS=t.SUPPORTED_CURRENCIES=t.DelegationConstraintsSchema=t.CrispScopeSchema=t.ScopeMatcherSchema=t.CrispBudgetSchema=t.BudgetWindowSchema=t.WindowKindSchema=t.CurrencySchema=void 0,t.validateDelegationConstraints=function(e){return t.DelegationConstraintsSchema.safeParse(e)},t.hasValidTimeRange=function(e){return void 0===e.notBefore&&void 0===e.notAfter||(void 0===e.notBefore||void 0===e.notAfter||e.notBefore<e.notAfter)},t.areChildConstraintsValid=function(e,t){return!(void 0!==e.notBefore&&void 0!==t.notBefore&&t.notBefore<e.notBefore)&&(!(void 0!==e.notAfter&&void 0!==t.notAfter&&t.notAfter>e.notAfter)&&(!(e.crisp?.budget&&t.crisp?.budget&&e.crisp.budget.unit===t.crisp.budget.unit&&t.crisp.budget.cap>e.crisp.budget.cap)&&(!e.crisp||!t.crisp||(new Set(e.crisp.scopes.map(e=>e.resource)),t.crisp.scopes.every(t=>e.crisp.scopes.some(e=>"exact"===e.matcher?e.resource===t.resource:"prefix"!==e.matcher||t.resource.startsWith(e.resource)))))))},t.doesResourceMatchScope=function(e,t){switch(t.matcher){case"exact":return e===t.resource;case"prefix":return e.startsWith(t.resource);case"regex":try{return new RegExp(t.resource).test(e)}catch{return!1}default:return!1}};const a=r(90315);t.CurrencySchema=a.z.enum(["USD","ops","points"]),t.WindowKindSchema=a.z.enum(["rolling","fixed"]),t.BudgetWindowSchema=a.z.object({kind:t.WindowKindSchema,durationSec:a.z.number().int().positive()}),t.CrispBudgetSchema=a.z.object({unit:t.CurrencySchema,cap:a.z.number().nonnegative(),window:t.BudgetWindowSchema.optional()}),t.ScopeMatcherSchema=a.z.enum(["exact","prefix","regex"]),t.CrispScopeSchema=a.z.object({resource:a.z.string().min(1),matcher:t.ScopeMatcherSchema,constraints:a.z.record(a.z.any()).optional()}),t.DelegationConstraintsSchema=a.z.object({notBefore:a.z.number().int().optional(),notAfter:a.z.number().int().optional(),scopes:a.z.array(a.z.string()).optional(),audience:a.z.union([a.z.string().startsWith("did:"),a.z.array(a.z.string().startsWith("did:"))]).optional(),crisp:a.z.object({budget:t.CrispBudgetSchema.optional(),scopes:a.z.array(t.CrispScopeSchema).min(1)}).passthrough().optional()}).passthrough(),t.SUPPORTED_CURRENCIES=["USD","ops","points"],t.SUPPORTED_MATCHERS=["exact","prefix","regex"],t.MAX_BUDGET_CAP=Number.MAX_SAFE_INTEGER,t.MAX_WINDOW_DURATION_SEC=31536e4},6069:(e,t,r)=>{"use strict";var a=r(72916).MissingRef;e.exports=function e(t,r,s){var i=this;if("function"!=typeof this._opts.loadSchema)throw new Error("options.loadSchema should be a function");"function"==typeof r&&(s=r,r=void 0);var n=o(t).then(function(){var e=i._addSchema(t,void 0,r);return e.validate||c(e)});return s&&n.then(function(e){s(null,e)},s),n;function o(t){var r=t.$schema;return r&&!i.getSchema(r)?e.call(i,{$ref:r},!0):Promise.resolve()}function c(e){try{return i._compile(e)}catch(t){if(t instanceof a)return function(t){var a=t.missingSchema;if(d(a))throw new Error("Schema "+a+" is loaded but "+t.missingRef+" cannot be resolved");var s=i._loadingSchemas[a];return s||(s=i._loadingSchemas[a]=i._opts.loadSchema(a)).then(n,n),s.then(function(e){if(!d(a))return o(e).then(function(){d(a)||i.addSchema(e,a,void 0,r)})}).then(function(){return c(e)});function n(){delete i._loadingSchemas[a]}function d(e){return i._refs[e]||i._schemas[e]}}(t);throw t}}}},9717:(e,t,r)=>{"use strict";function a(e,t,r,a){var s=a?" !== ":" === ",i=a?" || ":" && ",n=a?"!":"",o=a?"":"!";switch(e){case"null":return t+s+"null";case"array":return n+"Array.isArray("+t+")";case"object":return"("+n+t+i+"typeof "+t+s+'"object"'+i+o+"Array.isArray("+t+"))";case"integer":return"(typeof "+t+s+'"number"'+i+o+"("+t+" % 1)"+i+t+s+t+(r?i+n+"isFinite("+t+")":"")+")";case"number":return"(typeof "+t+s+'"'+e+'"'+(r?i+n+"isFinite("+t+")":"")+")";default:return"typeof "+t+s+'"'+e+'"'}}e.exports={copy:function(e,t){for(var r in t=t||{},e)t[r]=e[r];return t},checkDataType:a,checkDataTypes:function(e,t,r){if(1===e.length)return a(e[0],t,r,!0);var s="",n=i(e);for(var o in n.array&&n.object&&(s=n.null?"(":"(!"+t+" || ",s+="typeof "+t+' !== "object")',delete n.null,delete n.array,delete n.object),n.number&&delete n.integer,n)s+=(s?" && ":"")+a(o,t,r,!0);return s},coerceToTypes:function(e,t){if(Array.isArray(t)){for(var r=[],a=0;a<t.length;a++){var i=t[a];(s[i]||"array"===e&&"array"===i)&&(r[r.length]=i)}if(r.length)return r}else{if(s[t])return[t];if("array"===e&&"array"===t)return["array"]}},toHash:i,getProperty:c,escapeQuotes:d,equal:r(67371),ucs2length:r(61812),varOccurences:function(e,t){t+="[^0-9]";var r=e.match(new RegExp(t,"g"));return r?r.length:0},varReplace:function(e,t,r){return t+="([^0-9])",r=r.replace(/\$/g,"$$$$"),e.replace(new RegExp(t,"g"),r+"$1")},schemaHasRules:function(e,t){if("boolean"==typeof e)return!e;for(var r in e)if(t[r])return!0},schemaHasRulesExcept:function(e,t,r){if("boolean"==typeof e)return!e&&"not"!=r;for(var a in e)if(a!=r&&t[a])return!0},schemaUnknownRules:function(e,t){if("boolean"!=typeof e)for(var r in e)if(!t[r])return r},toQuotedString:u,getPathExpr:function(e,t,r,a){return p(e,r?"'/' + "+t+(a?"":".replace(/~/g, '~0').replace(/\\//g, '~1')"):a?"'[' + "+t+" + ']'":"'[\\'' + "+t+" + '\\']'")},getPath:function(e,t,r){return p(e,u(r?"/"+f(t):c(t)))},getData:function(e,t,r){var a,s,i,n;if(""===e)return"rootData";if("/"==e[0]){if(!l.test(e))throw new Error("Invalid JSON-pointer: "+e);s=e,i="rootData"}else{if(!(n=e.match(h)))throw new Error("Invalid JSON-pointer: "+e);if(a=+n[1],"#"==(s=n[2])){if(a>=t)throw new Error("Cannot access property/index "+a+" levels up, current level is "+t);return r[t-a]}if(a>t)throw new Error("Cannot access data "+a+" levels up, current level is "+t);if(i="data"+(t-a||""),!s)return i}for(var o=i,d=s.split("/"),u=0;u<d.length;u++){var p=d[u];p&&(o+=" && "+(i+=c(m(p))))}return o},unescapeFragment:function(e){return m(decodeURIComponent(e))},unescapeJsonPointer:m,escapeFragment:function(e){return encodeURIComponent(f(e))},escapeJsonPointer:f};var s=i(["string","number","integer","boolean","null"]);function i(e){for(var t={},r=0;r<e.length;r++)t[e[r]]=!0;return t}var n=/^[a-z$_][a-z$_0-9]*$/i,o=/'|\\/g;function c(e){return"number"==typeof e?"["+e+"]":n.test(e)?"."+e:"['"+d(e)+"']"}function d(e){return e.replace(o,"\\$&").replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\f/g,"\\f").replace(/\t/g,"\\t")}function u(e){return"'"+d(e)+"'"}var l=/^\/(?:[^~]|~0|~1)*$/,h=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function p(e,t){return'""'==e?t:(e+" + "+t).replace(/([^\\])' \+ '/g,"$1")}function f(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}function m(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}},9931:e=>{"use strict";e.exports=function(e,t,r){var a=" ",s=e.level,i=e.dataLevel,n=e.schema[t],o=e.schemaPath+e.util.getProperty(t),c=e.errSchemaPath+"/"+t,d=!e.opts.allErrors,u="data"+(i||""),l="errs__"+s,h=e.util.copy(e);h.level++;var p="valid"+h.level;if(a+="var "+l+" = errors;",e.opts.strictKeywords?"object"==typeof n&&Object.keys(n).length>0||!1===n:e.util.schemaHasRules(n,e.RULES.all)){h.schema=n,h.schemaPath=o,h.errSchemaPath=c;var f="key"+s,m="idx"+s,g="i"+s,y="' + "+f+" + '",v="data"+(h.dataLevel=e.dataLevel+1),_="dataProperties"+s,S=e.opts.ownProperties,b=e.baseId;S&&(a+=" var "+_+" = undefined; "),a+=S?" "+_+" = "+_+" || Object.keys("+u+"); for (var "+m+"=0; "+m+"<"+_+".length; "+m+"++) { var "+f+" = "+_+"["+m+"]; ":" for (var "+f+" in "+u+") { ",a+=" var startErrs"+s+" = errors; ";var E=f,P=e.compositeRule;e.compositeRule=h.compositeRule=!0;var I=e.validate(h);h.baseId=b,e.util.varOccurences(I,v)<2?a+=" "+e.util.varReplace(I,v,E)+" ":a+=" var "+v+" = "+E+"; "+I+" ",e.compositeRule=h.compositeRule=P,a+=" if (!"+p+") { for (var "+g+"=startErrs"+s+"; "+g+"<errors; "+g+"++) { vErrors["+g+"].propertyName = "+f+"; } var err = ",!1!==e.createErrors?(a+=" { keyword: 'propertyNames' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { propertyName: '"+y+"' } ",!1!==e.opts.messages&&(a+=" , message: 'property name \\'"+y+"\\' is invalid' "),e.opts.verbose&&(a+=" , schema: validate.schema"+o+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+u+" "),a+=" } "):a+=" {} ",a+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",!e.compositeRule&&d&&(e.async?a+=" throw new ValidationError(vErrors); ":a+=" validate.errors = vErrors; return false; "),d&&(a+=" break; "),a+=" } }"}return d&&(a+=" if ("+l+" == errors) {"),a}},10568:(e,t)=>{"use strict";function r(e){return`agent:${e}:delegation`}function a(e,t,r){return r?`delegation:user:${e}:agent:${t}:project:${r}`:`delegation:user:${e}:agent:${t}`}function s(e){return`session:${e}`}function i(e,t){return`userDid:oauth:${e}:${t}`}function n(e,t){return`oauth:${e}:${t}`}function o(e){return`verified:${e}`}function c(e){return`nonce:${e}`}Object.defineProperty(t,"__esModule",{value:!0}),t.STORAGE_KEYS=void 0,t.legacyDelegationKey=r,t.compositeDelegationKey=a,t.sessionKey=s,t.userDidKey=i,t.oauthIdentityKey=n,t.verificationCacheKey=o,t.nonceKey=c,t.migrateDelegationKeys=async function(e,t={}){const r={migrated:0,failed:0,migrations:[],errors:[]};try{const s=(await e.list("agent:")).filter(e=>e.match(/^agent:[^:]+:delegation$/));console.log(`Found ${s.length} legacy delegation keys to migrate`);for(const i of s)try{const s=i.match(/^agent:([^:]+):delegation$/);if(!s){r.errors.push({key:i,error:"Invalid legacy key format"}),r.failed++;continue}const n=s[1],o=await e.get(i);if(!o)continue;let c,d=null;const u=await e.list("session:");for(const t of u){const r=await e.get(t);if(r)try{const e=JSON.parse(r);if(e.userDid&&e.agentDid===n){d=e.userDid;const r=t.match(/^session:(.+)$/);r&&(c=r[1]);break}}catch{}}if(t.resolveUserDid){const e=await t.resolveUserDid(n,c);e&&(d=e)}if(!d){r.errors.push({key:i,error:"Cannot resolve userDid - skipping migration"}),r.failed++;continue}const l=a(d,n);t.dryRun?(r.migrations.push({oldKey:i,newKey:l}),r.migrated++):(await e.set(l,o),r.migrations.push({oldKey:i,newKey:l}),r.migrated++,t.deleteOldKeys&&await e.delete(i))}catch(e){r.errors.push({key:i,error:e instanceof Error?e.message:String(e)}),r.failed++}}catch(e){r.errors.push({key:"migration",error:e instanceof Error?e.message:String(e)})}return r},t.STORAGE_KEYS={userDid:i,oauthIdentity:n,delegation:a,session:s,legacyDelegation:r,verificationCache:o,nonce:c}},10985:(e,t,r)=>{"use strict";r.d(t,{S:()=>s});var a="$";function s(e,t){var r="",s=t&&t.include,i=t&&t.exclude;i&&"string"==typeof i&&(i=[i]),s&&s.sort();var n=new WeakMap,o=t&&t.allowCircular,c=t&&t.filterUndefined,d=t&&t.undefinedInArrayToNull;return function e(t,u){if(null===t||"object"!=typeof t||null!=t.toJSON)r+=JSON.stringify(t);else if(Array.isArray(t)){if(void 0!==(h=n.get(t))&&u.startsWith(h)){if(!o)throw new Error("Circular reference detected");return void(r+='"[Circular:'+h+']"')}n.set(t,u),r+="[";var l=!1;t.forEach(function(t,a){l&&(r+=","),l=!0,d&&void 0===t&&(t=null),e(t,u+"["+a+"]")}),r+="]"}else{var h;if(void 0!==(h=n.get(t))&&u.startsWith(h)){if(!o)throw new Error("Circular reference detected");return void(r+='"[Circular:'+h+']"')}n.set(t,u),r+="{";var p=!1,f=function(a){i&&i.includes(a)||(p&&(r+=","),p=!0,r+=JSON.stringify(a),r+=":",e(t[a],u+"."+a))};if(u===a&&s)s.forEach(function(e){t.hasOwnProperty(e)&&f(e)});else{var m=Object.keys(t);c&&(m=m.filter(function(e){return void 0!==t[e]})),m.sort(),m.forEach(function(e){f(e)})}r+="}"}}(e,a),r}},12269:e=>{"use strict";e.exports=JSON.parse('{"$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":true,"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":true,"readOnly":{"type":"boolean","default":false},"examples":{"type":"array","items":true},"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":true},"maxItems":{"$ref":"#/definitions/nonNegativeInteger"},"minItems":{"$ref":"#/definitions/nonNegativeIntegerDefault0"},"uniqueItems":{"type":"boolean","default":false},"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":true,"enum":{"type":"array","items":true,"minItems":1,"uniqueItems":true},"type":{"anyOf":[{"$ref":"#/definitions/simpleTypes"},{"type":"array","items":{"$ref":"#/definitions/simpleTypes"},"minItems":1,"uniqueItems":true}]},"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":true}')},12308:function(e,t,r){"use strict";var a=this&&this.__createBinding||(Object.create?function(e,t,r,a){void 0===a&&(a=r);var s=Object.getOwnPropertyDescriptor(t,r);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,a,s)}:function(e,t,r,a){void 0===a&&(a=r),e[a]=t[r]}),s=this&&this.__exportStar||function(e,t){for(var r in e)"default"===r||Object.prototype.hasOwnProperty.call(t,r)||a(t,e,r)};Object.defineProperty(t,"__esModule",{value:!0}),t.canonicalizeJSON=t.getSchemaStats=t.getCriticalSchemas=t.getSchemaById=t.getSchemasByCategory=t.getAllSchemas=t.SCHEMA_REGISTRY=t.createSchemaVerifier=t.SchemaVerifier=t.MemoryDelegationGraphStorage=t.MemoryStatusListStorage=t.createCascadingRevocationManager=t.CascadingRevocationManager=t.createDelegationGraph=t.DelegationGraphManager=t.isIndexSet=t.BitstringManager=t.createStatusListManager=t.StatusList2021Manager=t.createDelegationVerifier=t.DelegationCredentialVerifier=t.createDelegationIssuer=t.DelegationCredentialIssuer=t.DelegationRequiredError=t.NoOpToolProtectionCache=t.InMemoryToolProtectionCache=t.createProofVerificationError=t.PROOF_VERIFICATION_ERROR_CODES=t.ProofVerificationError=t.AccessControlApiService=t.ProofVerifier=t.CryptoService=t.ToolProtectionService=t.MCPIRuntimeBase=t.MemoryIdentityProvider=t.MemoryNonceCacheProvider=t.MemoryStorageProvider=t.IdentityProvider=t.NonceCacheProvider=t.StorageProvider=t.FetchProvider=t.ClockProvider=t.CryptoProvider=void 0;var i=r(96308);Object.defineProperty(t,"CryptoProvider",{enumerable:!0,get:function(){return i.CryptoProvider}}),Object.defineProperty(t,"ClockProvider",{enumerable:!0,get:function(){return i.ClockProvider}}),Object.defineProperty(t,"FetchProvider",{enumerable:!0,get:function(){return i.FetchProvider}}),Object.defineProperty(t,"StorageProvider",{enumerable:!0,get:function(){return i.StorageProvider}}),Object.defineProperty(t,"NonceCacheProvider",{enumerable:!0,get:function(){return i.NonceCacheProvider}}),Object.defineProperty(t,"IdentityProvider",{enumerable:!0,get:function(){return i.IdentityProvider}});var n=r(96654);Object.defineProperty(t,"MemoryStorageProvider",{enumerable:!0,get:function(){return n.MemoryStorageProvider}}),Object.defineProperty(t,"MemoryNonceCacheProvider",{enumerable:!0,get:function(){return n.MemoryNonceCacheProvider}}),Object.defineProperty(t,"MemoryIdentityProvider",{enumerable:!0,get:function(){return n.MemoryIdentityProvider}});var o=r(77990);Object.defineProperty(t,"MCPIRuntimeBase",{enumerable:!0,get:function(){return o.MCPIRuntimeBase}}),s(r(20774),t);var c=r(95630);Object.defineProperty(t,"ToolProtectionService",{enumerable:!0,get:function(){return c.ToolProtectionService}});var d=r(22169);Object.defineProperty(t,"CryptoService",{enumerable:!0,get:function(){return d.CryptoService}});var u=r(73706);Object.defineProperty(t,"ProofVerifier",{enumerable:!0,get:function(){return u.ProofVerifier}});var l=r(42318);Object.defineProperty(t,"AccessControlApiService",{enumerable:!0,get:function(){return l.AccessControlApiService}});var h=r(62846);Object.defineProperty(t,"ProofVerificationError",{enumerable:!0,get:function(){return h.ProofVerificationError}}),Object.defineProperty(t,"PROOF_VERIFICATION_ERROR_CODES",{enumerable:!0,get:function(){return h.PROOF_VERIFICATION_ERROR_CODES}}),Object.defineProperty(t,"createProofVerificationError",{enumerable:!0,get:function(){return h.createProofVerificationError}});var p=r(59236);Object.defineProperty(t,"InMemoryToolProtectionCache",{enumerable:!0,get:function(){return p.InMemoryToolProtectionCache}}),Object.defineProperty(t,"NoOpToolProtectionCache",{enumerable:!0,get:function(){return p.NoOpToolProtectionCache}});var f=r(63288);Object.defineProperty(t,"DelegationRequiredError",{enumerable:!0,get:function(){return f.DelegationRequiredError}});var m=r(18702);Object.defineProperty(t,"DelegationCredentialIssuer",{enumerable:!0,get:function(){return m.DelegationCredentialIssuer}}),Object.defineProperty(t,"createDelegationIssuer",{enumerable:!0,get:function(){return m.createDelegationIssuer}});var g=r(28339);Object.defineProperty(t,"DelegationCredentialVerifier",{enumerable:!0,get:function(){return g.DelegationCredentialVerifier}}),Object.defineProperty(t,"createDelegationVerifier",{enumerable:!0,get:function(){return g.createDelegationVerifier}});var y=r(2603);Object.defineProperty(t,"StatusList2021Manager",{enumerable:!0,get:function(){return y.StatusList2021Manager}}),Object.defineProperty(t,"createStatusListManager",{enumerable:!0,get:function(){return y.createStatusListManager}});var v=r(33021);Object.defineProperty(t,"BitstringManager",{enumerable:!0,get:function(){return v.BitstringManager}}),Object.defineProperty(t,"isIndexSet",{enumerable:!0,get:function(){return v.isIndexSet}});var _=r(65652);Object.defineProperty(t,"DelegationGraphManager",{enumerable:!0,get:function(){return _.DelegationGraphManager}}),Object.defineProperty(t,"createDelegationGraph",{enumerable:!0,get:function(){return _.createDelegationGraph}});var S=r(94423);Object.defineProperty(t,"CascadingRevocationManager",{enumerable:!0,get:function(){return S.CascadingRevocationManager}}),Object.defineProperty(t,"createCascadingRevocationManager",{enumerable:!0,get:function(){return S.createCascadingRevocationManager}});var b=r(16257);Object.defineProperty(t,"MemoryStatusListStorage",{enumerable:!0,get:function(){return b.MemoryStatusListStorage}});var E=r(71283);Object.defineProperty(t,"MemoryDelegationGraphStorage",{enumerable:!0,get:function(){return E.MemoryDelegationGraphStorage}});var P=r(27170);Object.defineProperty(t,"SchemaVerifier",{enumerable:!0,get:function(){return P.SchemaVerifier}}),Object.defineProperty(t,"createSchemaVerifier",{enumerable:!0,get:function(){return P.createSchemaVerifier}});var I=r(69411);Object.defineProperty(t,"SCHEMA_REGISTRY",{enumerable:!0,get:function(){return I.SCHEMA_REGISTRY}}),Object.defineProperty(t,"getAllSchemas",{enumerable:!0,get:function(){return I.getAllSchemas}}),Object.defineProperty(t,"getSchemasByCategory",{enumerable:!0,get:function(){return I.getSchemasByCategory}}),Object.defineProperty(t,"getSchemaById",{enumerable:!0,get:function(){return I.getSchemaById}}),Object.defineProperty(t,"getCriticalSchemas",{enumerable:!0,get:function(){return I.getCriticalSchemas}}),Object.defineProperty(t,"getSchemaStats",{enumerable:!0,get:function(){return I.getSchemaStats}});var w=r(98770);Object.defineProperty(t,"canonicalizeJSON",{enumerable:!0,get:function(){return w.canonicalizeJSON}}),s(r(56392),t)},12857:e=>{"use strict";e.exports=function(e,t,r){var a,s,i=" ",n=e.level,o=e.dataLevel,c=e.schema[t],d=e.errSchemaPath+"/"+t,u=!e.opts.allErrors,l="data"+(o||""),h="valid"+n;if("#"==c||"#/"==c)e.isRoot?(a=e.async,s="validate"):(a=!0===e.root.schema.$async,s="root.refVal[0]");else{var p=e.resolveRef(e.baseId,c,e.isRoot);if(void 0===p){var f=e.MissingRefError.message(e.baseId,c);if("fail"==e.opts.missingRefs){e.logger.error(f),(v=v||[]).push(i),i="",!1!==e.createErrors?(i+=" { keyword: '$ref' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(d)+" , params: { ref: '"+e.util.escapeQuotes(c)+"' } ",!1!==e.opts.messages&&(i+=" , message: 'can\\'t resolve reference "+e.util.escapeQuotes(c)+"' "),e.opts.verbose&&(i+=" , schema: "+e.util.toQuotedString(c)+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+l+" "),i+=" } "):i+=" {} ";var m=i;i=v.pop(),!e.compositeRule&&u?e.async?i+=" throw new ValidationError(["+m+"]); ":i+=" validate.errors = ["+m+"]; return false; ":i+=" var err = "+m+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",u&&(i+=" if (false) { ")}else{if("ignore"!=e.opts.missingRefs)throw new e.MissingRefError(e.baseId,c,f);e.logger.warn(f),u&&(i+=" if (true) { ")}}else if(p.inline){var g=e.util.copy(e);g.level++;var y="valid"+g.level;g.schema=p.schema,g.schemaPath="",g.errSchemaPath=c,i+=" "+e.validate(g).replace(/validate\.schema/g,p.code)+" ",u&&(i+=" if ("+y+") { ")}else a=!0===p.$async||e.async&&!1!==p.$async,s=p.code}if(s){var v;(v=v||[]).push(i),i="",e.opts.passContext?i+=" "+s+".call(this, ":i+=" "+s+"( ",i+=" "+l+", (dataPath || '')",'""'!=e.errorPath&&(i+=" + "+e.errorPath);var _=i+=" , "+(o?"data"+(o-1||""):"parentData")+" , "+(o?e.dataPathArr[o]:"parentDataProperty")+", rootData) ";if(i=v.pop(),a){if(!e.async)throw new Error("async schema referenced by sync schema");u&&(i+=" var "+h+"; "),i+=" try { await "+_+"; ",u&&(i+=" "+h+" = true; "),i+=" } catch (e) { if (!(e instanceof ValidationError)) throw e; if (vErrors === null) vErrors = e.errors; else vErrors = vErrors.concat(e.errors); errors = vErrors.length; ",u&&(i+=" "+h+" = false; "),i+=" } ",u&&(i+=" if ("+h+") { ")}else i+=" if (!"+_+") { if (vErrors === null) vErrors = "+s+".errors; else vErrors = vErrors.concat("+s+".errors); errors = vErrors.length; } ",u&&(i+=" else { ")}return i}},13215:e=>{"use strict";e.exports=JSON.parse('{"$schema":"http://json-schema.org/draft-07/schema#","$id":"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#","description":"Meta-schema for $data reference (JSON Schema extension proposal)","type":"object","required":["$data"],"properties":{"$data":{"type":"string","anyOf":[{"format":"relative-json-pointer"},{"format":"json-pointer"}]}},"additionalProperties":false}')},13441:e=>{"use strict";e.exports=function(e,t,r){var a=" ",s=e.level,i=e.dataLevel,n=e.schema[t],o=e.schemaPath+e.util.getProperty(t),c=e.errSchemaPath+"/"+t,d=!e.opts.allErrors,u="data"+(i||""),l="errs__"+s,h=e.util.copy(e);h.level++;var p="valid"+h.level;if(e.opts.strictKeywords?"object"==typeof n&&Object.keys(n).length>0||!1===n:e.util.schemaHasRules(n,e.RULES.all)){h.schema=n,h.schemaPath=o,h.errSchemaPath=c,a+=" var "+l+" = errors; ";var f,m=e.compositeRule;e.compositeRule=h.compositeRule=!0,h.createErrors=!1,h.opts.allErrors&&(f=h.opts.allErrors,h.opts.allErrors=!1),a+=" "+e.validate(h)+" ",h.createErrors=!0,f&&(h.opts.allErrors=f),e.compositeRule=h.compositeRule=m,a+=" if ("+p+") { ";var g=g||[];g.push(a),a="",!1!==e.createErrors?(a+=" { keyword: 'not' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: {} ",!1!==e.opts.messages&&(a+=" , message: 'should NOT be valid' "),e.opts.verbose&&(a+=" , schema: validate.schema"+o+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+u+" "),a+=" } "):a+=" {} ";var y=a;a=g.pop(),!e.compositeRule&&d?e.async?a+=" throw new ValidationError(["+y+"]); ":a+=" validate.errors = ["+y+"]; return false; ":a+=" var err = "+y+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",a+=" } else { errors = "+l+"; if (vErrors !== null) { if ("+l+") vErrors.length = "+l+"; else vErrors = null; } ",e.opts.allErrors&&(a+=" } ")}else a+=" var err = ",!1!==e.createErrors?(a+=" { keyword: 'not' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: {} ",!1!==e.opts.messages&&(a+=" , message: 'should NOT be valid' "),e.opts.verbose&&(a+=" , schema: validate.schema"+o+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+u+" "),a+=" } "):a+=" {} ",a+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",d&&(a+=" if (false) { ");return a}},13749:function(e,t){!function(e){"use strict";function t(){for(var e=arguments.length,t=Array(e),r=0;r<e;r++)t[r]=arguments[r];if(t.length>1){t[0]=t[0].slice(0,-1);for(var a=t.length-1,s=1;s<a;++s)t[s]=t[s].slice(1,-1);return t[a]=t[a].slice(1),t.join("")}return t[0]}function r(e){return"(?:"+e+")"}function a(e){return void 0===e?"undefined":null===e?"null":Object.prototype.toString.call(e).split(" ").pop().split("]").shift().toLowerCase()}function s(e){return e.toUpperCase()}function i(e){var a="[A-Za-z]",s="[0-9]",i=t(s,"[A-Fa-f]"),n=r(r("%[EFef]"+i+"%"+i+i+"%"+i+i)+"|"+r("%[89A-Fa-f]"+i+"%"+i+i)+"|"+r("%"+i+i)),o="[\\!\\$\\&\\'\\(\\)\\*\\+\\,\\;\\=]",c=t("[\\:\\/\\?\\#\\[\\]\\@]",o),d=e?"[\\uE000-\\uF8FF]":"[]",u=t(a,s,"[\\-\\.\\_\\~]",e?"[\\xA0-\\u200D\\u2010-\\u2029\\u202F-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF]":"[]"),l=r(a+t(a,s,"[\\+\\-\\.]")+"*"),h=r(r(n+"|"+t(u,o,"[\\:]"))+"*"),p=(r(r("25[0-5]")+"|"+r("2[0-4]"+s)+"|"+r("1"+s+s)+"|"+r("[1-9]"+s)+"|"+s),r(r("25[0-5]")+"|"+r("2[0-4]"+s)+"|"+r("1"+s+s)+"|"+r("0?[1-9]"+s)+"|0?0?"+s)),f=r(p+"\\."+p+"\\."+p+"\\."+p),m=r(i+"{1,4}"),g=r(r(m+"\\:"+m)+"|"+f),y=r(r(m+"\\:")+"{6}"+g),v=r("\\:\\:"+r(m+"\\:")+"{5}"+g),_=r(r(m)+"?\\:\\:"+r(m+"\\:")+"{4}"+g),S=r(r(r(m+"\\:")+"{0,1}"+m)+"?\\:\\:"+r(m+"\\:")+"{3}"+g),b=r(r(r(m+"\\:")+"{0,2}"+m)+"?\\:\\:"+r(m+"\\:")+"{2}"+g),E=r(r(r(m+"\\:")+"{0,3}"+m)+"?\\:\\:"+m+"\\:"+g),P=r(r(r(m+"\\:")+"{0,4}"+m)+"?\\:\\:"+g),I=r(r(r(m+"\\:")+"{0,5}"+m)+"?\\:\\:"+m),w=r(r(r(m+"\\:")+"{0,6}"+m)+"?\\:\\:"),C=r([y,v,_,S,b,E,P,I,w].join("|")),T=r(r(u+"|"+n)+"+"),D=(r(C+"\\%25"+T),r(C+r("\\%25|\\%(?!"+i+"{2})")+T)),x=r("[vV]"+i+"+\\."+t(u,o,"[\\:]")+"+"),O=r("\\["+r(D+"|"+C+"|"+x)+"\\]"),A=r(r(n+"|"+t(u,o))+"*"),k=r(O+"|"+f+"(?!"+A+")|"+A),R=r(s+"*"),N=r(r(h+"@")+"?"+k+r("\\:"+R)+"?"),j=r(n+"|"+t(u,o,"[\\:\\@]")),z=r(j+"*"),$=r(j+"+"),M=r(r(n+"|"+t(u,o,"[\\@]"))+"+"),L=r(r("\\/"+z)+"*"),F=r("\\/"+r($+L)+"?"),Z=r(M+L),V=r($+L),K="(?!"+j+")",U=(r(L+"|"+F+"|"+Z+"|"+V+"|"+K),r(r(j+"|"+t("[\\/\\?]",d))+"*")),H=r(r(j+"|[\\/\\?]")+"*"),q=r(r("\\/\\/"+N+L)+"|"+F+"|"+V+"|"+K),B=r(l+"\\:"+q+r("\\?"+U)+"?"+r("\\#"+H)+"?"),W=r(r("\\/\\/"+N+L)+"|"+F+"|"+Z+"|"+K),G=r(W+r("\\?"+U)+"?"+r("\\#"+H)+"?");return r(B+"|"+G),r(l+"\\:"+q+r("\\?"+U)+"?"),r(r("\\/\\/("+r("("+h+")@")+"?("+k+")"+r("\\:("+R+")")+"?)")+"?("+L+"|"+F+"|"+V+"|"+K+")"),r("\\?("+U+")"),r("\\#("+H+")"),r(r("\\/\\/("+r("("+h+")@")+"?("+k+")"+r("\\:("+R+")")+"?)")+"?("+L+"|"+F+"|"+Z+"|"+K+")"),r("\\?("+U+")"),r("\\#("+H+")"),r(r("\\/\\/("+r("("+h+")@")+"?("+k+")"+r("\\:("+R+")")+"?)")+"?("+L+"|"+F+"|"+V+"|"+K+")"),r("\\?("+U+")"),r("\\#("+H+")"),r("("+h+")@"),r("\\:("+R+")"),{NOT_SCHEME:new RegExp(t("[^]",a,s,"[\\+\\-\\.]"),"g"),NOT_USERINFO:new RegExp(t("[^\\%\\:]",u,o),"g"),NOT_HOST:new RegExp(t("[^\\%\\[\\]\\:]",u,o),"g"),NOT_PATH:new RegExp(t("[^\\%\\/\\:\\@]",u,o),"g"),NOT_PATH_NOSCHEME:new RegExp(t("[^\\%\\/\\@]",u,o),"g"),NOT_QUERY:new RegExp(t("[^\\%]",u,o,"[\\:\\@\\/\\?]",d),"g"),NOT_FRAGMENT:new RegExp(t("[^\\%]",u,o,"[\\:\\@\\/\\?]"),"g"),ESCAPE:new RegExp(t("[^]",u,o),"g"),UNRESERVED:new RegExp(u,"g"),OTHER_CHARS:new RegExp(t("[^\\%]",u,c),"g"),PCT_ENCODED:new RegExp(n,"g"),IPV4ADDRESS:new RegExp("^("+f+")$"),IPV6ADDRESS:new RegExp("^\\[?("+C+")"+r(r("\\%25|\\%(?!"+i+"{2})")+"("+T+")")+"?\\]?$")}}var n=i(!1),o=i(!0),c=function(e,t){if(Array.isArray(e))return e;if(Symbol.iterator in Object(e))return function(e,t){var r=[],a=!0,s=!1,i=void 0;try{for(var n,o=e[Symbol.iterator]();!(a=(n=o.next()).done)&&(r.push(n.value),!t||r.length!==t);a=!0);}catch(e){s=!0,i=e}finally{try{!a&&o.return&&o.return()}finally{if(s)throw i}}return r}(e,t);throw new TypeError("Invalid attempt to destructure non-iterable instance")},d=2147483647,u=36,l=/^xn--/,h=/[^\0-\x7E]/,p=/[\x2E\u3002\uFF0E\uFF61]/g,f={overflow:"Overflow: input needs wider integers to process","not-basic":"Illegal input >= 0x80 (not a basic code point)","invalid-input":"Invalid input"},m=Math.floor,g=String.fromCharCode;function y(e){throw new RangeError(f[e])}function v(e,t){var r=e.split("@"),a="";return r.length>1&&(a=r[0]+"@",e=r[1]),a+function(e,t){for(var r=[],a=e.length;a--;)r[a]=t(e[a]);return r}((e=e.replace(p,".")).split("."),t).join(".")}function _(e){for(var t=[],r=0,a=e.length;r<a;){var s=e.charCodeAt(r++);if(s>=55296&&s<=56319&&r<a){var i=e.charCodeAt(r++);56320==(64512&i)?t.push(((1023&s)<<10)+(1023&i)+65536):(t.push(s),r--)}else t.push(s)}return t}var S=function(e){return e-48<10?e-22:e-65<26?e-65:e-97<26?e-97:u},b=function(e,t){return e+22+75*(e<26)-((0!=t)<<5)},E=function(e,t,r){var a=0;for(e=r?m(e/700):e>>1,e+=m(e/t);e>455;a+=u)e=m(e/35);return m(a+36*e/(e+38))},P=function(e){var t=[],r=e.length,a=0,s=128,i=72,n=e.lastIndexOf("-");n<0&&(n=0);for(var o=0;o<n;++o)e.charCodeAt(o)>=128&&y("not-basic"),t.push(e.charCodeAt(o));for(var c=n>0?n+1:0;c<r;){for(var l=a,h=1,p=u;;p+=u){c>=r&&y("invalid-input");var f=S(e.charCodeAt(c++));(f>=u||f>m((d-a)/h))&&y("overflow"),a+=f*h;var g=p<=i?1:p>=i+26?26:p-i;if(f<g)break;var v=u-g;h>m(d/v)&&y("overflow"),h*=v}var _=t.length+1;i=E(a-l,_,0==l),m(a/_)>d-s&&y("overflow"),s+=m(a/_),a%=_,t.splice(a++,0,s)}return String.fromCodePoint.apply(String,t)},I=function(e){var t=[],r=(e=_(e)).length,a=128,s=0,i=72,n=!0,o=!1,c=void 0;try{for(var l,h=e[Symbol.iterator]();!(n=(l=h.next()).done);n=!0){var p=l.value;p<128&&t.push(g(p))}}catch(e){o=!0,c=e}finally{try{!n&&h.return&&h.return()}finally{if(o)throw c}}var f=t.length,v=f;for(f&&t.push("-");v<r;){var S=d,P=!0,I=!1,w=void 0;try{for(var C,T=e[Symbol.iterator]();!(P=(C=T.next()).done);P=!0){var D=C.value;D>=a&&D<S&&(S=D)}}catch(e){I=!0,w=e}finally{try{!P&&T.return&&T.return()}finally{if(I)throw w}}var x=v+1;S-a>m((d-s)/x)&&y("overflow"),s+=(S-a)*x,a=S;var O=!0,A=!1,k=void 0;try{for(var R,N=e[Symbol.iterator]();!(O=(R=N.next()).done);O=!0){var j=R.value;if(j<a&&++s>d&&y("overflow"),j==a){for(var z=s,$=u;;$+=u){var M=$<=i?1:$>=i+26?26:$-i;if(z<M)break;var L=z-M,F=u-M;t.push(g(b(M+L%F,0))),z=m(L/F)}t.push(g(b(z,0))),i=E(s,x,v==f),s=0,++v}}}catch(e){A=!0,k=e}finally{try{!O&&N.return&&N.return()}finally{if(A)throw k}}++s,++a}return t.join("")},w=function(e){return v(e,function(e){return h.test(e)?"xn--"+I(e):e})},C=function(e){return v(e,function(e){return l.test(e)?P(e.slice(4).toLowerCase()):e})},T={};function D(e){var t=e.charCodeAt(0);return t<16?"%0"+t.toString(16).toUpperCase():t<128?"%"+t.toString(16).toUpperCase():t<2048?"%"+(t>>6|192).toString(16).toUpperCase()+"%"+(63&t|128).toString(16).toUpperCase():"%"+(t>>12|224).toString(16).toUpperCase()+"%"+(t>>6&63|128).toString(16).toUpperCase()+"%"+(63&t|128).toString(16).toUpperCase()}function x(e){for(var t="",r=0,a=e.length;r<a;){var s=parseInt(e.substr(r+1,2),16);if(s<128)t+=String.fromCharCode(s),r+=3;else if(s>=194&&s<224){if(a-r>=6){var i=parseInt(e.substr(r+4,2),16);t+=String.fromCharCode((31&s)<<6|63&i)}else t+=e.substr(r,6);r+=6}else if(s>=224){if(a-r>=9){var n=parseInt(e.substr(r+4,2),16),o=parseInt(e.substr(r+7,2),16);t+=String.fromCharCode((15&s)<<12|(63&n)<<6|63&o)}else t+=e.substr(r,9);r+=9}else t+=e.substr(r,3),r+=3}return t}function O(e,t){function r(e){var r=x(e);return r.match(t.UNRESERVED)?r:e}return e.scheme&&(e.scheme=String(e.scheme).replace(t.PCT_ENCODED,r).toLowerCase().replace(t.NOT_SCHEME,"")),void 0!==e.userinfo&&(e.userinfo=String(e.userinfo).replace(t.PCT_ENCODED,r).replace(t.NOT_USERINFO,D).replace(t.PCT_ENCODED,s)),void 0!==e.host&&(e.host=String(e.host).replace(t.PCT_ENCODED,r).toLowerCase().replace(t.NOT_HOST,D).replace(t.PCT_ENCODED,s)),void 0!==e.path&&(e.path=String(e.path).replace(t.PCT_ENCODED,r).replace(e.scheme?t.NOT_PATH:t.NOT_PATH_NOSCHEME,D).replace(t.PCT_ENCODED,s)),void 0!==e.query&&(e.query=String(e.query).replace(t.PCT_ENCODED,r).replace(t.NOT_QUERY,D).replace(t.PCT_ENCODED,s)),void 0!==e.fragment&&(e.fragment=String(e.fragment).replace(t.PCT_ENCODED,r).replace(t.NOT_FRAGMENT,D).replace(t.PCT_ENCODED,s)),e}function A(e){return e.replace(/^0*(.*)/,"$1")||"0"}function k(e,t){var r=e.match(t.IPV4ADDRESS)||[],a=c(r,2)[1];return a?a.split(".").map(A).join("."):e}function R(e,t){var r=e.match(t.IPV6ADDRESS)||[],a=c(r,3),s=a[1],i=a[2];if(s){for(var n=s.toLowerCase().split("::").reverse(),o=c(n,2),d=o[0],u=o[1],l=u?u.split(":").map(A):[],h=d.split(":").map(A),p=t.IPV4ADDRESS.test(h[h.length-1]),f=p?7:8,m=h.length-f,g=Array(f),y=0;y<f;++y)g[y]=l[y]||h[m+y]||"";p&&(g[f-1]=k(g[f-1],t));var v=g.reduce(function(e,t,r){if(!t||"0"===t){var a=e[e.length-1];a&&a.index+a.length===r?a.length++:e.push({index:r,length:1})}return e},[]).sort(function(e,t){return t.length-e.length})[0],_=void 0;if(v&&v.length>1){var S=g.slice(0,v.index),b=g.slice(v.index+v.length);_=S.join(":")+"::"+b.join(":")}else _=g.join(":");return i&&(_+="%"+i),_}return e}var N=/^(?:([^:\/?#]+):)?(?:\/\/((?:([^\/?#@]*)@)?(\[[^\/?#\]]+\]|[^\/?#:]*)(?:\:(\d*))?))?([^?#]*)(?:\?([^#]*))?(?:#((?:.|\n|\r)*))?/i,j=void 0==="".match(/(){0}/)[1];function z(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r={},a=!1!==t.iri?o:n;"suffix"===t.reference&&(e=(t.scheme?t.scheme+":":"")+"//"+e);var s=e.match(N);if(s){j?(r.scheme=s[1],r.userinfo=s[3],r.host=s[4],r.port=parseInt(s[5],10),r.path=s[6]||"",r.query=s[7],r.fragment=s[8],isNaN(r.port)&&(r.port=s[5])):(r.scheme=s[1]||void 0,r.userinfo=-1!==e.indexOf("@")?s[3]:void 0,r.host=-1!==e.indexOf("//")?s[4]:void 0,r.port=parseInt(s[5],10),r.path=s[6]||"",r.query=-1!==e.indexOf("?")?s[7]:void 0,r.fragment=-1!==e.indexOf("#")?s[8]:void 0,isNaN(r.port)&&(r.port=e.match(/\/\/(?:.|\n)*\:(?:\/|\?|\#|$)/)?s[4]:void 0)),r.host&&(r.host=R(k(r.host,a),a)),void 0!==r.scheme||void 0!==r.userinfo||void 0!==r.host||void 0!==r.port||r.path||void 0!==r.query?void 0===r.scheme?r.reference="relative":void 0===r.fragment?r.reference="absolute":r.reference="uri":r.reference="same-document",t.reference&&"suffix"!==t.reference&&t.reference!==r.reference&&(r.error=r.error||"URI is not a "+t.reference+" reference.");var i=T[(t.scheme||r.scheme||"").toLowerCase()];if(t.unicodeSupport||i&&i.unicodeSupport)O(r,a);else{if(r.host&&(t.domainHost||i&&i.domainHost))try{r.host=w(r.host.replace(a.PCT_ENCODED,x).toLowerCase())}catch(e){r.error=r.error||"Host's domain name can not be converted to ASCII via punycode: "+e}O(r,n)}i&&i.parse&&i.parse(r,t)}else r.error=r.error||"URI can not be parsed.";return r}var $=/^\.\.?\//,M=/^\/\.(\/|$)/,L=/^\/\.\.(\/|$)/,F=/^\/?(?:.|\n)*?(?=\/|$)/;function Z(e){for(var t=[];e.length;)if(e.match($))e=e.replace($,"");else if(e.match(M))e=e.replace(M,"/");else if(e.match(L))e=e.replace(L,"/"),t.pop();else if("."===e||".."===e)e="";else{var r=e.match(F);if(!r)throw new Error("Unexpected dot segment condition");var a=r[0];e=e.slice(a.length),t.push(a)}return t.join("")}function V(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=t.iri?o:n,a=[],s=T[(t.scheme||e.scheme||"").toLowerCase()];if(s&&s.serialize&&s.serialize(e,t),e.host)if(r.IPV6ADDRESS.test(e.host));else if(t.domainHost||s&&s.domainHost)try{e.host=t.iri?C(e.host):w(e.host.replace(r.PCT_ENCODED,x).toLowerCase())}catch(r){e.error=e.error||"Host's domain name can not be converted to "+(t.iri?"Unicode":"ASCII")+" via punycode: "+r}O(e,r),"suffix"!==t.reference&&e.scheme&&(a.push(e.scheme),a.push(":"));var i=function(e,t){var r=!1!==t.iri?o:n,a=[];return void 0!==e.userinfo&&(a.push(e.userinfo),a.push("@")),void 0!==e.host&&a.push(R(k(String(e.host),r),r).replace(r.IPV6ADDRESS,function(e,t,r){return"["+t+(r?"%25"+r:"")+"]"})),"number"!=typeof e.port&&"string"!=typeof e.port||(a.push(":"),a.push(String(e.port))),a.length?a.join(""):void 0}(e,t);if(void 0!==i&&("suffix"!==t.reference&&a.push("//"),a.push(i),e.path&&"/"!==e.path.charAt(0)&&a.push("/")),void 0!==e.path){var c=e.path;t.absolutePath||s&&s.absolutePath||(c=Z(c)),void 0===i&&(c=c.replace(/^\/\//,"/%2F")),a.push(c)}return void 0!==e.query&&(a.push("?"),a.push(e.query)),void 0!==e.fragment&&(a.push("#"),a.push(e.fragment)),a.join("")}function K(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},a={};return arguments[3]||(e=z(V(e,r),r),t=z(V(t,r),r)),!(r=r||{}).tolerant&&t.scheme?(a.scheme=t.scheme,a.userinfo=t.userinfo,a.host=t.host,a.port=t.port,a.path=Z(t.path||""),a.query=t.query):(void 0!==t.userinfo||void 0!==t.host||void 0!==t.port?(a.userinfo=t.userinfo,a.host=t.host,a.port=t.port,a.path=Z(t.path||""),a.query=t.query):(t.path?("/"===t.path.charAt(0)?a.path=Z(t.path):(void 0===e.userinfo&&void 0===e.host&&void 0===e.port||e.path?e.path?a.path=e.path.slice(0,e.path.lastIndexOf("/")+1)+t.path:a.path=t.path:a.path="/"+t.path,a.path=Z(a.path)),a.query=t.query):(a.path=e.path,void 0!==t.query?a.query=t.query:a.query=e.query),a.userinfo=e.userinfo,a.host=e.host,a.port=e.port),a.scheme=e.scheme),a.fragment=t.fragment,a}function U(e,t){return e&&e.toString().replace(t&&t.iri?o.PCT_ENCODED:n.PCT_ENCODED,x)}var H={scheme:"http",domainHost:!0,parse:function(e,t){return e.host||(e.error=e.error||"HTTP URIs must have a host."),e},serialize:function(e,t){var r="https"===String(e.scheme).toLowerCase();return e.port!==(r?443:80)&&""!==e.port||(e.port=void 0),e.path||(e.path="/"),e}},q={scheme:"https",domainHost:H.domainHost,parse:H.parse,serialize:H.serialize};function B(e){return"boolean"==typeof e.secure?e.secure:"wss"===String(e.scheme).toLowerCase()}var W={scheme:"ws",domainHost:!0,parse:function(e,t){var r=e;return r.secure=B(r),r.resourceName=(r.path||"/")+(r.query?"?"+r.query:""),r.path=void 0,r.query=void 0,r},serialize:function(e,t){if(e.port!==(B(e)?443:80)&&""!==e.port||(e.port=void 0),"boolean"==typeof e.secure&&(e.scheme=e.secure?"wss":"ws",e.secure=void 0),e.resourceName){var r=e.resourceName.split("?"),a=c(r,2),s=a[0],i=a[1];e.path=s&&"/"!==s?s:void 0,e.query=i,e.resourceName=void 0}return e.fragment=void 0,e}},G={scheme:"wss",domainHost:W.domainHost,parse:W.parse,serialize:W.serialize},J={},X="[A-Za-z0-9\\-\\.\\_\\~\\xA0-\\u200D\\u2010-\\u2029\\u202F-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF]",Q="[0-9A-Fa-f]",Y=r(r("%[EFef]"+Q+"%"+Q+Q+"%"+Q+Q)+"|"+r("%[89A-Fa-f]"+Q+"%"+Q+Q)+"|"+r("%"+Q+Q)),ee=t("[\\!\\$\\%\\'\\(\\)\\*\\+\\,\\-\\.0-9\\<\\>A-Z\\x5E-\\x7E]",'[\\"\\\\]'),te=new RegExp(X,"g"),re=new RegExp(Y,"g"),ae=new RegExp(t("[^]","[A-Za-z0-9\\!\\$\\%\\'\\*\\+\\-\\^\\_\\`\\{\\|\\}\\~]","[\\.]",'[\\"]',ee),"g"),se=new RegExp(t("[^]",X,"[\\!\\$\\'\\(\\)\\*\\+\\,\\;\\:\\@]"),"g"),ie=se;function ne(e){var t=x(e);return t.match(te)?t:e}var oe={scheme:"mailto",parse:function(e,t){var r=e,a=r.to=r.path?r.path.split(","):[];if(r.path=void 0,r.query){for(var s=!1,i={},n=r.query.split("&"),o=0,c=n.length;o<c;++o){var d=n[o].split("=");switch(d[0]){case"to":for(var u=d[1].split(","),l=0,h=u.length;l<h;++l)a.push(u[l]);break;case"subject":r.subject=U(d[1],t);break;case"body":r.body=U(d[1],t);break;default:s=!0,i[U(d[0],t)]=U(d[1],t)}}s&&(r.headers=i)}r.query=void 0;for(var p=0,f=a.length;p<f;++p){var m=a[p].split("@");if(m[0]=U(m[0]),t.unicodeSupport)m[1]=U(m[1],t).toLowerCase();else try{m[1]=w(U(m[1],t).toLowerCase())}catch(e){r.error=r.error||"Email address's domain name can not be converted to ASCII via punycode: "+e}a[p]=m.join("@")}return r},serialize:function(e,t){var r,a=e,i=null!=(r=e.to)?r instanceof Array?r:"number"!=typeof r.length||r.split||r.setInterval||r.call?[r]:Array.prototype.slice.call(r):[];if(i){for(var n=0,o=i.length;n<o;++n){var c=String(i[n]),d=c.lastIndexOf("@"),u=c.slice(0,d).replace(re,ne).replace(re,s).replace(ae,D),l=c.slice(d+1);try{l=t.iri?C(l):w(U(l,t).toLowerCase())}catch(e){a.error=a.error||"Email address's domain name can not be converted to "+(t.iri?"Unicode":"ASCII")+" via punycode: "+e}i[n]=u+"@"+l}a.path=i.join(",")}var h=e.headers=e.headers||{};e.subject&&(h.subject=e.subject),e.body&&(h.body=e.body);var p=[];for(var f in h)h[f]!==J[f]&&p.push(f.replace(re,ne).replace(re,s).replace(se,D)+"="+h[f].replace(re,ne).replace(re,s).replace(ie,D));return p.length&&(a.query=p.join("&")),a}},ce=/^([^\:]+)\:(.*)/,de={scheme:"urn",parse:function(e,t){var r=e.path&&e.path.match(ce),a=e;if(r){var s=t.scheme||a.scheme||"urn",i=r[1].toLowerCase(),n=r[2],o=s+":"+(t.nid||i),c=T[o];a.nid=i,a.nss=n,a.path=void 0,c&&(a=c.parse(a,t))}else a.error=a.error||"URN can not be parsed.";return a},serialize:function(e,t){var r=t.scheme||e.scheme||"urn",a=e.nid,s=r+":"+(t.nid||a),i=T[s];i&&(e=i.serialize(e,t));var n=e,o=e.nss;return n.path=(a||t.nid)+":"+o,n}},ue=/^[0-9A-Fa-f]{8}(?:\-[0-9A-Fa-f]{4}){3}\-[0-9A-Fa-f]{12}$/,le={scheme:"urn:uuid",parse:function(e,t){var r=e;return r.uuid=r.nss,r.nss=void 0,t.tolerant||r.uuid&&r.uuid.match(ue)||(r.error=r.error||"UUID is not valid."),r},serialize:function(e,t){var r=e;return r.nss=(e.uuid||"").toLowerCase(),r}};T[H.scheme]=H,T[q.scheme]=q,T[W.scheme]=W,T[G.scheme]=G,T[oe.scheme]=oe,T[de.scheme]=de,T[le.scheme]=le,e.SCHEMES=T,e.pctEncChar=D,e.pctDecChars=x,e.parse=z,e.removeDotSegments=Z,e.serialize=V,e.resolveComponents=K,e.resolve=function(e,t,r){var a=function(e,t){var r=e;if(t)for(var a in t)r[a]=t[a];return r}({scheme:"null"},r);return V(K(z(e,a),z(t,a),a,!0),a)},e.normalize=function(e,t){return"string"==typeof e?e=V(z(e,t),t):"object"===a(e)&&(e=z(V(e,t),t)),e},e.equal=function(e,t,r){return"string"==typeof e?e=V(z(e,r),r):"object"===a(e)&&(e=V(e,r)),"string"==typeof t?t=V(z(t,r),r):"object"===a(t)&&(t=V(t,r)),e===t},e.escapeComponent=function(e,t){return e&&e.toString().replace(t&&t.iri?o.ESCAPE:n.ESCAPE,D)},e.unescapeComponent=U,Object.defineProperty(e,"__esModule",{value:!0})}(t)},14547:e=>{"use strict";e.exports=function(e,t,r){var a=" ",s=e.level,i=e.dataLevel,n=e.schema[t],o=e.schemaPath+e.util.getProperty(t),c=e.errSchemaPath+"/"+t,d=!e.opts.allErrors,u="data"+(i||""),l="valid"+s,h="errs__"+s,p=e.util.copy(e),f="";p.level++;var m="valid"+p.level,g=n.every(function(t){return e.opts.strictKeywords?"object"==typeof t&&Object.keys(t).length>0||!1===t:e.util.schemaHasRules(t,e.RULES.all)});if(g){var y=p.baseId;a+=" var "+h+" = errors; var "+l+" = false; ";var v=e.compositeRule;e.compositeRule=p.compositeRule=!0;var _=n;if(_)for(var S,b=-1,E=_.length-1;b<E;)S=_[b+=1],p.schema=S,p.schemaPath=o+"["+b+"]",p.errSchemaPath=c+"/"+b,a+=" "+e.validate(p)+" ",p.baseId=y,a+=" "+l+" = "+l+" || "+m+"; if (!"+l+") { ",f+="}";e.compositeRule=p.compositeRule=v,a+=" "+f+" if (!"+l+") { var err = ",!1!==e.createErrors?(a+=" { keyword: 'anyOf' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: {} ",!1!==e.opts.messages&&(a+=" , message: 'should match some schema in anyOf' "),e.opts.verbose&&(a+=" , schema: validate.schema"+o+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+u+" "),a+=" } "):a+=" {} ",a+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",!e.compositeRule&&d&&(e.async?a+=" throw new ValidationError(vErrors); ":a+=" validate.errors = vErrors; return false; "),a+=" } else { errors = "+h+"; if (vErrors !== null) { if ("+h+") vErrors.length = "+h+"; else vErrors = null; } ",e.opts.allErrors&&(a+=" } ")}else d&&(a+=" if (true) { ");return a}},16257:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.MemoryStatusListStorage=void 0,t.MemoryStatusListStorage=class{statusLists=new Map;indexCounters=new Map;async getStatusList(e){return this.statusLists.get(e)||null}async setStatusList(e,t){this.statusLists.set(e,t)}async allocateIndex(e){const t=this.indexCounters.get(e)||0,r=t;return this.indexCounters.set(e,t+1),r}getIndexCount(e){return this.indexCounters.get(e)||0}clear(){this.statusLists.clear(),this.indexCounters.clear()}getAllStatusListIds(){return Array.from(this.statusLists.keys())}}},16928:e=>{"use strict";e.exports=require("path")},18702:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DelegationCredentialIssuer=void 0,t.createDelegationIssuer=function(e,t){return new i(e,t)};const a=r(49351),s=r(98770);class i{identity;signingFunction;constructor(e,t){this.identity=e,this.signingFunction=t}async issueDelegationCredential(e,t={}){let r=(0,a.wrapDelegationAsVC)(e,{id:t.id,issuanceDate:t.issuanceDate,expirationDate:t.expirationDate,credentialStatus:t.credentialStatus});if(t.additionalContexts&&t.additionalContexts.length>0){const e=r["@context"];r={...r,"@context":[...e,...t.additionalContexts]}}const s=this.canonicalizeVC(r),i=await this.signingFunction(s,this.identity.getDid(),this.identity.getKeyId());return{...r,proof:i}}async createAndIssueDelegation(e,t={}){const r=Date.now(),a={id:e.id,issuerDid:e.issuerDid,subjectDid:e.subjectDid,controller:e.controller,vcId:t.id||`urn:uuid:${e.id}`,parentId:e.parentId,constraints:e.constraints,signature:"",status:e.status||"active",createdAt:r,metadata:e.metadata};return this.issueDelegationCredential(a,t)}canonicalizeVC(e){return(0,s.canonicalizeJSON)(e)}getIssuerDid(){return this.identity.getDid()}getIssuerKeyId(){return this.identity.getKeyId()}}t.DelegationCredentialIssuer=i},19613:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ProofSubmissionRequestSchema=t.ProofSubmissionContextSchema=t.ToolCallContextSchema=t.AUDIT_VERSION=t.HASH_ALGORITHM=t.JWS_ALGORITHM=t.AuditRecordSchema=t.CanonicalHashesSchema=t.DetachedProofSchema=t.ProofMetaSchema=void 0;const a=r(90315);t.ProofMetaSchema=a.z.object({did:a.z.string().min(1),kid:a.z.string().min(1),ts:a.z.number().int().positive(),nonce:a.z.string().min(1),audience:a.z.string().min(1),sessionId:a.z.string().min(1),requestHash:a.z.string().regex(/^sha256:[a-f0-9]{64}$/),responseHash:a.z.string().regex(/^sha256:[a-f0-9]{64}$/),scopeId:a.z.string().optional(),delegationRef:a.z.string().optional(),clientDid:a.z.string().optional()}),t.DetachedProofSchema=a.z.object({jws:a.z.string().min(1),meta:t.ProofMetaSchema}),t.CanonicalHashesSchema=a.z.object({requestHash:a.z.string().regex(/^sha256:[a-f0-9]{64}$/),responseHash:a.z.string().regex(/^sha256:[a-f0-9]{64}$/)}),t.AuditRecordSchema=a.z.object({version:a.z.literal("audit.v1"),ts:a.z.number().int().positive(),session:a.z.string().min(1),audience:a.z.string().min(1),did:a.z.string().min(1),kid:a.z.string().min(1),reqHash:a.z.string().regex(/^sha256:[a-f0-9]{64}$/),resHash:a.z.string().regex(/^sha256:[a-f0-9]{64}$/),verified:a.z.enum(["yes","no"]),scope:a.z.string().min(1)}),t.JWS_ALGORITHM="EdDSA",t.HASH_ALGORITHM="sha256",t.AUDIT_VERSION="audit.v1",t.ToolCallContextSchema=a.z.object({tool:a.z.string().min(1),args:a.z.record(a.z.unknown()),result:a.z.unknown().optional(),scopeId:a.z.string(),userId:a.z.string().optional()}),t.ProofSubmissionContextSchema=a.z.object({toolCalls:a.z.array(t.ToolCallContextSchema),mcpServerUrl:a.z.string().url().optional()}),t.ProofSubmissionRequestSchema=a.z.object({session_id:a.z.string().min(1),delegation_id:a.z.string().nullable().optional(),proofs:a.z.array(a.z.object({jws:a.z.string().min(1),meta:t.ProofMetaSchema})),context:t.ProofSubmissionContextSchema.optional()})},20698:(e,t,r)=>{"use strict";var a=r(52004),s=r(9717).toHash;e.exports=function(){var e=[{type:"number",rules:[{maximum:["exclusiveMaximum"]},{minimum:["exclusiveMinimum"]},"multipleOf","format"]},{type:"string",rules:["maxLength","minLength","pattern","format"]},{type:"array",rules:["maxItems","minItems","items","contains","uniqueItems"]},{type:"object",rules:["maxProperties","minProperties","required","dependencies","propertyNames",{properties:["additionalProperties","patternProperties"]}]},{rules:["$ref","const","enum","not","anyOf","oneOf","allOf","if"]}],t=["type","$comment"];return e.all=s(t),e.types=s(["number","integer","string","array","object","boolean","null"]),e.forEach(function(r){r.rules=r.rules.map(function(r){var s;if("object"==typeof r){var i=Object.keys(r)[0];s=r[i],r=i,s.forEach(function(r){t.push(r),e.all[r]=!0})}return t.push(r),e.all[r]={keyword:r,code:a[r],implements:s}}),e.all.$comment={keyword:"$comment",code:a.$comment},r.type&&(e.types[r.type]=r)}),e.keywords=s(t.concat(["$schema","$id","id","$data","$async","title","description","default","definitions","examples","readOnly","writeOnly","contentMediaType","contentEncoding","additionalItems","then","else"])),e.custom={},e}},20774:function(e,t,r){"use strict";var a=this&&this.__createBinding||(Object.create?function(e,t,r,a){void 0===a&&(a=r);var s=Object.getOwnPropertyDescriptor(t,r);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,a,s)}:function(e,t,r,a){void 0===a&&(a=r),e[a]=t[r]}),s=this&&this.__exportStar||function(e,t){for(var r in e)"default"===r||Object.prototype.hasOwnProperty.call(t,r)||a(t,e,r)};Object.defineProperty(t,"__esModule",{value:!0}),s(r(92881),t),s(r(33327),t),s(r(10568),t)},20812:(e,t,r)=>{"use strict";var a=r(9717);e.exports=function(e){a.copy(e,this)}},22169:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.CryptoService=void 0;const a=r(33327);t.CryptoService=class{cryptoProvider;constructor(e){this.cryptoProvider=e}async verifyEd25519(e,t,r){try{return!0===await this.cryptoProvider.verify(e,t,r)}catch(e){return console.error("[CryptoService] Ed25519 verification error:",e),!1}}parseJWS(e){const t=e.split(".");if(3!==t.length)throw new Error("Invalid JWS format: expected header.payload.signature");const[r,s,i]=t;let n,o,c;try{n=JSON.parse((0,a.base64urlDecodeToString)(r))}catch(e){throw new Error(`Invalid header base64: ${e instanceof Error?e.message:String(e)}`)}if(s)try{o=JSON.parse((0,a.base64urlDecodeToString)(s))}catch(e){throw new Error(`Invalid payload base64: ${e instanceof Error?e.message:String(e)}`)}try{c=(0,a.base64urlDecodeToBytes)(i)}catch(e){throw new Error(`Invalid signature base64: ${e instanceof Error?e.message:String(e)}`)}return{header:n,payload:o,signatureBytes:c,signingInput:`${r}.${s}`}}async verifyJWS(e,t,r){try{if(!this.isValidEd25519JWK(t))return console.error("[CryptoService] Invalid Ed25519 JWK format"),!1;if(r?.expectedKid&&t.kid!==r.expectedKid)return console.error("[CryptoService] Key ID mismatch"),!1;let s;try{s=this.parseJWS(e)}catch(t){if(void 0===r?.detachedPayload)return console.error("[CryptoService] Invalid JWS format:",t),!1;{const r=e.split(".");if(3!==r.length||""!==r[1])return console.error("[CryptoService] Invalid JWS format:",t),!1;try{const e=r[0],t=r[2];s={header:JSON.parse((0,a.base64urlDecodeToString)(e)),payload:void 0,signatureBytes:(0,a.base64urlDecodeToBytes)(t),signingInput:""}}catch{return console.error("[CryptoService] Invalid detached JWS format"),!1}}}const i=r?.alg||"EdDSA";if(s.header.alg!==i)return console.error(`[CryptoService] Unsupported algorithm: ${s.header.alg}, expected ${i}`),!1;let n,o,c;if(void 0!==r?.detachedPayload){const t=e.split(".")[0];let s;s=r.detachedPayload instanceof Uint8Array?(0,a.base64urlEncodeFromBytes)(r.detachedPayload):(0,a.base64urlEncodeFromBytes)((new TextEncoder).encode(r.detachedPayload)),n=`${t}.${s}`,o=(new TextEncoder).encode(n)}else{if(!s.signingInput)return console.error("[CryptoService] Missing signing input for compact JWS"),!1;n=s.signingInput,o=(new TextEncoder).encode(n)}try{c=this.jwkToBase64PublicKey(t)}catch(e){return console.error("[CryptoService] Failed to extract public key:",e),!1}return await this.verifyEd25519(o,s.signatureBytes,c)}catch(e){return console.error("[CryptoService] JWS verification error:",e),!1}}isValidEd25519JWK(e){return"object"==typeof e&&null!==e&&"kty"in e&&"OKP"===e.kty&&"crv"in e&&"Ed25519"===e.crv&&"x"in e&&"string"==typeof e.x&&e.x.length>0}jwkToBase64PublicKey(e){const t=(0,a.base64urlDecodeToBytes)(e.x);if(32!==t.length)throw new Error(`Invalid Ed25519 public key length: ${t.length}`);return(0,a.bytesToBase64)(t)}}},22853:(e,t,r)=>{"use strict";var a=r(40985),s=r(9717),i=r(72916),n=r(56039),o=r(25572),c=s.ucs2length,d=r(67371),u=i.Validation;function l(e,t,r){var a=p.call(this,e,t,r);return a>=0?{index:a,compiling:!0}:(a=this._compilations.length,this._compilations[a]={schema:e,root:t,baseId:r},{index:a,compiling:!1})}function h(e,t,r){var a=p.call(this,e,t,r);a>=0&&this._compilations.splice(a,1)}function p(e,t,r){for(var a=0;a<this._compilations.length;a++){var s=this._compilations[a];if(s.schema==e&&s.root==t&&s.baseId==r)return a}return-1}function f(e,t){return"var pattern"+e+" = new RegExp("+s.toQuotedString(t[e])+");"}function m(e){return"var default"+e+" = defaults["+e+"];"}function g(e,t){return void 0===t[e]?"":"var refVal"+e+" = refVal["+e+"];"}function y(e){return"var customRule"+e+" = customRules["+e+"];"}function v(e,t){if(!e.length)return"";for(var r="",a=0;a<e.length;a++)r+=t(a,e);return r}e.exports=function e(t,r,p,_){var S=this,b=this._opts,E=[void 0],P={},I=[],w={},C=[],T={},D=[];r=r||{schema:t,refVal:E,refs:P};var x=l.call(this,t,r,_),O=this._compilations[x.index];if(x.compiling)return O.callValidate=function e(){var t=O.validate,r=t.apply(this,arguments);return e.errors=t.errors,r};var A=this._formats,k=this.RULES;try{var R=j(t,r,p,_);O.validate=R;var N=O.callValidate;return N&&(N.schema=R.schema,N.errors=null,N.refs=R.refs,N.refVal=R.refVal,N.root=R.root,N.$async=R.$async,b.sourceCode&&(N.source=R.source)),R}finally{h.call(this,t,r,_)}function j(t,n,l,h){var p=!n||n&&n.schema==t;if(n.schema!=r.schema)return e.call(S,t,n,l,h);var _,w=!0===t.$async,T=o({isTop:!0,schema:t,isRoot:p,baseId:h,root:n,schemaPath:"",errSchemaPath:"#",errorPath:'""',MissingRefError:i.MissingRef,RULES:k,validate:o,util:s,resolve:a,resolveRef:z,usePattern:L,useDefault:F,useCustomRule:Z,opts:b,formats:A,logger:S.logger,self:S});T=v(E,g)+v(I,f)+v(C,m)+v(D,y)+T,b.processCode&&(T=b.processCode(T,t));try{_=new Function("self","RULES","formats","root","refVal","defaults","customRules","equal","ucs2length","ValidationError",T)(S,k,A,r,E,C,D,d,c,u),E[0]=_}catch(e){throw S.logger.error("Error compiling schema, function code:",T),e}return _.schema=t,_.errors=null,_.refs=P,_.refVal=E,_.root=p?_:n,w&&(_.$async=!0),!0===b.sourceCode&&(_.source={code:T,patterns:I,defaults:C}),_}function z(t,s,i){s=a.url(t,s);var n,o,c=P[s];if(void 0!==c)return M(n=E[c],o="refVal["+c+"]");if(!i&&r.refs){var d=r.refs[s];if(void 0!==d)return M(n=r.refVal[d],o=$(s,n))}o=$(s);var u=a.call(S,j,r,s);if(void 0===u){var l=p&&p[s];l&&(u=a.inlineRef(l,b.inlineRefs)?l:e.call(S,l,r,p,t))}if(void 0!==u)return function(e,t){var r=P[e];E[r]=t}(s,u),M(u,o);!function(e){delete P[e]}(s)}function $(e,t){var r=E.length;return E[r]=t,P[e]=r,"refVal"+r}function M(e,t){return"object"==typeof e||"boolean"==typeof e?{code:t,schema:e,inline:!0}:{code:t,$async:e&&!!e.$async}}function L(e){var t=w[e];return void 0===t&&(t=w[e]=I.length,I[t]=e),"pattern"+t}function F(e){switch(typeof e){case"boolean":case"number":return""+e;case"string":return s.toQuotedString(e);case"object":if(null===e)return"null";var t=n(e),r=T[t];return void 0===r&&(r=T[t]=C.length,C[r]=e),"default"+r}}function Z(e,t,r,a){if(!1!==S._opts.validateSchema){var s=e.definition.dependencies;if(s&&!s.every(function(e){return Object.prototype.hasOwnProperty.call(r,e)}))throw new Error("parent schema must have all required keywords: "+s.join(","));var i=e.definition.validateSchema;if(i&&!i(t)){var n="keyword schema is invalid: "+S.errorsText(i.errors);if("log"!=S._opts.validateSchema)throw new Error(n);S.logger.error(n)}}var o,c=e.definition.compile,d=e.definition.inline,u=e.definition.macro;if(c)o=c.call(S,t,r,a);else if(u)o=u.call(S,t,r,a),!1!==b.validateSchema&&S.validateSchema(o,!0);else if(d)o=d.call(S,a,e.keyword,t,r);else if(!(o=e.definition.validate))return;if(void 0===o)throw new Error('custom keyword "'+e.keyword+'"failed to compile');var l=D.length;return D[l]=o,{code:"customRule"+l,validate:o}}}},24235:e=>{"use strict";e.exports=function(e,t,r){var a=" ",s=e.level,i=e.dataLevel,n=e.schema[t],o=e.schemaPath+e.util.getProperty(t),c=e.errSchemaPath+"/"+t,d=!e.opts.allErrors,u="data"+(i||""),l="valid"+s,h="errs__"+s,p=e.util.copy(e);p.level++;var f="valid"+p.level,m="i"+s,g=p.dataLevel=e.dataLevel+1,y="data"+g,v=e.baseId,_=e.opts.strictKeywords?"object"==typeof n&&Object.keys(n).length>0||!1===n:e.util.schemaHasRules(n,e.RULES.all);if(a+="var "+h+" = errors;var "+l+";",_){var S=e.compositeRule;e.compositeRule=p.compositeRule=!0,p.schema=n,p.schemaPath=o,p.errSchemaPath=c,a+=" var "+f+" = false; for (var "+m+" = 0; "+m+" < "+u+".length; "+m+"++) { ",p.errorPath=e.util.getPathExpr(e.errorPath,m,e.opts.jsonPointers,!0);var b=u+"["+m+"]";p.dataPathArr[g]=m;var E=e.validate(p);p.baseId=v,e.util.varOccurences(E,y)<2?a+=" "+e.util.varReplace(E,y,b)+" ":a+=" var "+y+" = "+b+"; "+E+" ",a+=" if ("+f+") break; } ",e.compositeRule=p.compositeRule=S,a+=" if (!"+f+") {"}else a+=" if ("+u+".length == 0) {";var P=P||[];P.push(a),a="",!1!==e.createErrors?(a+=" { keyword: 'contains' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: {} ",!1!==e.opts.messages&&(a+=" , message: 'should contain a valid item' "),e.opts.verbose&&(a+=" , schema: validate.schema"+o+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+u+" "),a+=" } "):a+=" {} ";var I=a;return a=P.pop(),!e.compositeRule&&d?e.async?a+=" throw new ValidationError(["+I+"]); ":a+=" validate.errors = ["+I+"]; return false; ":a+=" var err = "+I+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",a+=" } else { ",_&&(a+=" errors = "+h+"; if (vErrors !== null) { if ("+h+") vErrors.length = "+h+"; else vErrors = null; } "),e.opts.allErrors&&(a+=" } "),a}},25572:e=>{"use strict";e.exports=function(e,t,r){var a="",s=!0===e.schema.$async,i=e.util.schemaHasRulesExcept(e.schema,e.RULES.all,"$ref"),n=e.self._getId(e.schema);if(e.opts.strictKeywords){var o=e.util.schemaUnknownRules(e.schema,e.RULES.keywords);if(o){var c="unknown keyword: "+o;if("log"!==e.opts.strictKeywords)throw new Error(c);e.logger.warn(c)}}if(e.isTop&&(a+=" var validate = ",s&&(e.async=!0,a+="async "),a+="function(data, dataPath, parentData, parentDataProperty, rootData) { 'use strict'; ",n&&(e.opts.sourceCode||e.opts.processCode)&&(a+=" /*# sourceURL="+n+" */ ")),"boolean"==typeof e.schema||!i&&!e.schema.$ref){t="false schema";var d=e.level,u=e.dataLevel,l=e.schema[t],h=e.schemaPath+e.util.getProperty(t),p=e.errSchemaPath+"/"+t,f=!e.opts.allErrors,m="data"+(u||""),g="valid"+d;if(!1===e.schema){e.isTop?f=!0:a+=" var "+g+" = false; ",(H=H||[]).push(a),a="",!1!==e.createErrors?(a+=" { keyword: 'false schema' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(p)+" , params: {} ",!1!==e.opts.messages&&(a+=" , message: 'boolean schema is false' "),e.opts.verbose&&(a+=" , schema: false , parentSchema: validate.schema"+e.schemaPath+" , data: "+m+" "),a+=" } "):a+=" {} ";var y=a;a=H.pop(),!e.compositeRule&&f?e.async?a+=" throw new ValidationError(["+y+"]); ":a+=" validate.errors = ["+y+"]; return false; ":a+=" var err = "+y+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; "}else e.isTop?a+=s?" return data; ":" validate.errors = null; return true; ":a+=" var "+g+" = true; ";return e.isTop&&(a+=" }; return validate; "),a}if(e.isTop){var v=e.isTop;if(d=e.level=0,u=e.dataLevel=0,m="data",e.rootId=e.resolve.fullPath(e.self._getId(e.root.schema)),e.baseId=e.baseId||e.rootId,delete e.isTop,e.dataPathArr=[""],void 0!==e.schema.default&&e.opts.useDefaults&&e.opts.strictDefaults){var _="default is ignored in the schema root";if("log"!==e.opts.strictDefaults)throw new Error(_);e.logger.warn(_)}a+=" var vErrors = null; ",a+=" var errors = 0; ",a+=" if (rootData === undefined) rootData = data; "}else{if(d=e.level,m="data"+((u=e.dataLevel)||""),n&&(e.baseId=e.resolve.url(e.baseId,n)),s&&!e.async)throw new Error("async schema in sync schema");a+=" var errs_"+d+" = errors;"}g="valid"+d,f=!e.opts.allErrors;var S="",b="",E=e.schema.type,P=Array.isArray(E);if(E&&e.opts.nullable&&!0===e.schema.nullable&&(P?-1==E.indexOf("null")&&(E=E.concat("null")):"null"!=E&&(E=[E,"null"],P=!0)),P&&1==E.length&&(E=E[0],P=!1),e.schema.$ref&&i){if("fail"==e.opts.extendRefs)throw new Error('$ref: validation keywords used in schema at path "'+e.errSchemaPath+'" (see option extendRefs)');!0!==e.opts.extendRefs&&(i=!1,e.logger.warn('$ref: keywords ignored in schema at path "'+e.errSchemaPath+'"'))}if(e.schema.$comment&&e.opts.$comment&&(a+=" "+e.RULES.all.$comment.code(e,"$comment")),E){if(e.opts.coerceTypes)var I=e.util.coerceToTypes(e.opts.coerceTypes,E);var w=e.RULES.types[E];if(I||P||!0===w||w&&!X(w)){h=e.schemaPath+".type",p=e.errSchemaPath+"/type",h=e.schemaPath+".type",p=e.errSchemaPath+"/type";var C=P?"checkDataTypes":"checkDataType";if(a+=" if ("+e.util[C](E,m,e.opts.strictNumbers,!0)+") { ",I){var T="dataType"+d,D="coerced"+d;a+=" var "+T+" = typeof "+m+"; var "+D+" = undefined; ","array"==e.opts.coerceTypes&&(a+=" if ("+T+" == 'object' && Array.isArray("+m+") && "+m+".length == 1) { "+m+" = "+m+"[0]; "+T+" = typeof "+m+"; if ("+e.util.checkDataType(e.schema.type,m,e.opts.strictNumbers)+") "+D+" = "+m+"; } "),a+=" if ("+D+" !== undefined) ; ";var x=I;if(x)for(var O,A=-1,k=x.length-1;A<k;)"string"==(O=x[A+=1])?a+=" else if ("+T+" == 'number' || "+T+" == 'boolean') "+D+" = '' + "+m+"; else if ("+m+" === null) "+D+" = ''; ":"number"==O||"integer"==O?(a+=" else if ("+T+" == 'boolean' || "+m+" === null || ("+T+" == 'string' && "+m+" && "+m+" == +"+m+" ","integer"==O&&(a+=" && !("+m+" % 1)"),a+=")) "+D+" = +"+m+"; "):"boolean"==O?a+=" else if ("+m+" === 'false' || "+m+" === 0 || "+m+" === null) "+D+" = false; else if ("+m+" === 'true' || "+m+" === 1) "+D+" = true; ":"null"==O?a+=" else if ("+m+" === '' || "+m+" === 0 || "+m+" === false) "+D+" = null; ":"array"==e.opts.coerceTypes&&"array"==O&&(a+=" else if ("+T+" == 'string' || "+T+" == 'number' || "+T+" == 'boolean' || "+m+" == null) "+D+" = ["+m+"]; ");a+=" else { ",(H=H||[]).push(a),a="",!1!==e.createErrors?(a+=" { keyword: 'type' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(p)+" , params: { type: '",a+=P?""+E.join(","):""+E,a+="' } ",!1!==e.opts.messages&&(a+=" , message: 'should be ",a+=P?""+E.join(","):""+E,a+="' "),e.opts.verbose&&(a+=" , schema: validate.schema"+h+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+m+" "),a+=" } "):a+=" {} ",y=a,a=H.pop(),!e.compositeRule&&f?e.async?a+=" throw new ValidationError(["+y+"]); ":a+=" validate.errors = ["+y+"]; return false; ":a+=" var err = "+y+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",a+=" } if ("+D+" !== undefined) { ";var R=u?"data"+(u-1||""):"parentData";a+=" "+m+" = "+D+"; ",u||(a+="if ("+R+" !== undefined)"),a+=" "+R+"["+(u?e.dataPathArr[u]:"parentDataProperty")+"] = "+D+"; } "}else(H=H||[]).push(a),a="",!1!==e.createErrors?(a+=" { keyword: 'type' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(p)+" , params: { type: '",a+=P?""+E.join(","):""+E,a+="' } ",!1!==e.opts.messages&&(a+=" , message: 'should be ",a+=P?""+E.join(","):""+E,a+="' "),e.opts.verbose&&(a+=" , schema: validate.schema"+h+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+m+" "),a+=" } "):a+=" {} ",y=a,a=H.pop(),!e.compositeRule&&f?e.async?a+=" throw new ValidationError(["+y+"]); ":a+=" validate.errors = ["+y+"]; return false; ":a+=" var err = "+y+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ";a+=" } "}}if(e.schema.$ref&&!i)a+=" "+e.RULES.all.$ref.code(e,"$ref")+" ",f&&(a+=" } if (errors === ",a+=v?"0":"errs_"+d,a+=") { ",b+="}");else{var N=e.RULES;if(N)for(var j=-1,z=N.length-1;j<z;)if(X(w=N[j+=1])){if(w.type&&(a+=" if ("+e.util.checkDataType(w.type,m,e.opts.strictNumbers)+") { "),e.opts.useDefaults)if("object"==w.type&&e.schema.properties){l=e.schema.properties;var $=Object.keys(l);if($)for(var M,L=-1,F=$.length-1;L<F;)if(void 0!==(K=l[M=$[L+=1]]).default){var Z=m+e.util.getProperty(M);if(e.compositeRule){if(e.opts.strictDefaults){if(_="default is ignored for: "+Z,"log"!==e.opts.strictDefaults)throw new Error(_);e.logger.warn(_)}}else a+=" if ("+Z+" === undefined ","empty"==e.opts.useDefaults&&(a+=" || "+Z+" === null || "+Z+" === '' "),a+=" ) "+Z+" = ","shared"==e.opts.useDefaults?a+=" "+e.useDefault(K.default)+" ":a+=" "+JSON.stringify(K.default)+" ",a+="; "}}else if("array"==w.type&&Array.isArray(e.schema.items)){var V=e.schema.items;if(V){A=-1;for(var K,U=V.length-1;A<U;)if(void 0!==(K=V[A+=1]).default)if(Z=m+"["+A+"]",e.compositeRule){if(e.opts.strictDefaults){if(_="default is ignored for: "+Z,"log"!==e.opts.strictDefaults)throw new Error(_);e.logger.warn(_)}}else a+=" if ("+Z+" === undefined ","empty"==e.opts.useDefaults&&(a+=" || "+Z+" === null || "+Z+" === '' "),a+=" ) "+Z+" = ","shared"==e.opts.useDefaults?a+=" "+e.useDefault(K.default)+" ":a+=" "+JSON.stringify(K.default)+" ",a+="; "}}var H,q=w.rules;if(q)for(var B,W=-1,G=q.length-1;W<G;)if(Q(B=q[W+=1])){var J=B.code(e,B.keyword,w.type);J&&(a+=" "+J+" ",f&&(S+="}"))}if(f&&(a+=" "+S+" ",S=""),w.type&&(a+=" } ",E&&E===w.type&&!I))a+=" else { ",h=e.schemaPath+".type",p=e.errSchemaPath+"/type",(H=H||[]).push(a),a="",!1!==e.createErrors?(a+=" { keyword: 'type' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(p)+" , params: { type: '",a+=P?""+E.join(","):""+E,a+="' } ",!1!==e.opts.messages&&(a+=" , message: 'should be ",a+=P?""+E.join(","):""+E,a+="' "),e.opts.verbose&&(a+=" , schema: validate.schema"+h+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+m+" "),a+=" } "):a+=" {} ",y=a,a=H.pop(),!e.compositeRule&&f?e.async?a+=" throw new ValidationError(["+y+"]); ":a+=" validate.errors = ["+y+"]; return false; ":a+=" var err = "+y+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",a+=" } ";f&&(a+=" if (errors === ",a+=v?"0":"errs_"+d,a+=") { ",b+="}")}}function X(e){for(var t=e.rules,r=0;r<t.length;r++)if(Q(t[r]))return!0}function Q(t){return void 0!==e.schema[t.keyword]||t.implements&&function(t){for(var r=t.implements,a=0;a<r.length;a++)if(void 0!==e.schema[r[a]])return!0}(t)}return f&&(a+=" "+b+" "),v?(s?(a+=" if (errors === 0) return data; ",a+=" else throw new ValidationError(vErrors); "):(a+=" validate.errors = vErrors; ",a+=" return errors === 0; "),a+=" }; return validate;"):a+=" var "+g+" = errors === errs_"+d+";",a}},27165:(e,t)=>{"use strict";var r,a;Object.defineProperty(t,"__esModule",{value:!0}),t.getParsedType=t.ZodParsedType=t.objectUtil=t.util=void 0,function(e){e.assertEqual=e=>{},e.assertIs=function(e){},e.assertNever=function(e){throw new Error},e.arrayToEnum=e=>{const t={};for(const r of e)t[r]=r;return t},e.getValidEnumValues=t=>{const r=e.objectKeys(t).filter(e=>"number"!=typeof t[t[e]]),a={};for(const e of r)a[e]=t[e];return e.objectValues(a)},e.objectValues=t=>e.objectKeys(t).map(function(e){return t[e]}),e.objectKeys="function"==typeof Object.keys?e=>Object.keys(e):e=>{const t=[];for(const r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.push(r);return t},e.find=(e,t)=>{for(const r of e)if(t(r))return r},e.isInteger="function"==typeof Number.isInteger?e=>Number.isInteger(e):e=>"number"==typeof e&&Number.isFinite(e)&&Math.floor(e)===e,e.joinValues=function(e,t=" | "){return e.map(e=>"string"==typeof e?`'${e}'`:e).join(t)},e.jsonStringifyReplacer=(e,t)=>"bigint"==typeof t?t.toString():t}(r||(t.util=r={})),function(e){e.mergeShapes=(e,t)=>({...e,...t})}(a||(t.objectUtil=a={})),t.ZodParsedType=r.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),t.getParsedType=e=>{switch(typeof e){case"undefined":return t.ZodParsedType.undefined;case"string":return t.ZodParsedType.string;case"number":return Number.isNaN(e)?t.ZodParsedType.nan:t.ZodParsedType.number;case"boolean":return t.ZodParsedType.boolean;case"function":return t.ZodParsedType.function;case"bigint":return t.ZodParsedType.bigint;case"symbol":return t.ZodParsedType.symbol;case"object":return Array.isArray(e)?t.ZodParsedType.array:null===e?t.ZodParsedType.null:e.then&&"function"==typeof e.then&&e.catch&&"function"==typeof e.catch?t.ZodParsedType.promise:"undefined"!=typeof Map&&e instanceof Map?t.ZodParsedType.map:"undefined"!=typeof Set&&e instanceof Set?t.ZodParsedType.set:"undefined"!=typeof Date&&e instanceof Date?t.ZodParsedType.date:t.ZodParsedType.object;default:return t.ZodParsedType.unknown}}},27170:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SchemaVerifier=void 0,t.createSchemaVerifier=function(e){return new r(e)};class r{schemasBaseUrl="https://schemas.kya-os.ai";schemaCache=new Map;constructor(e){e?.schemasBaseUrl&&(this.schemasBaseUrl=e.schemasBaseUrl)}async verifySchema(e,t){const r=[],a=[],s=[];let i;try{i=await this.fetchSchema(e.url)}catch(t){return{schema:e,compliant:!1,compliancePercentage:0,fields:[],issues:[`Failed to fetch schema: ${t instanceof Error?t.message:"Unknown error"}`],warnings:[],timestamp:Date.now()}}const n=this.resolveRef(i,i),o=this.validateAgainstSchema(t,n,i,"");r.push(...o.fields);for(const e of r)"fail"===e.status?a.push(`${e.fieldPath}: ${e.reason}`):"warning"===e.status&&s.push(`${e.fieldPath}: ${e.reason}`);const c=r.filter(e=>e.required),d=c.filter(e=>"pass"===e.status).length,u=c.length>0?d/c.length*100:100;return{schema:e,compliant:0===a.length&&u>=95,compliancePercentage:u,fields:r,issues:a,warnings:s,timestamp:Date.now()}}async verifyAll(e,t){const r=[],a=[];for(const s of e){const e=t.get(s.id);if(!e){a.push(`No implementation found for schema: ${s.id}`);continue}const i=await this.verifySchema(s,e);r.push(i),i.compliant||a.push(`${s.id}: ${i.issues.join(", ")}`)}const s=r.filter(e=>e.compliant).length,i=e.length>0?s/e.length*100:0;return{totalSchemas:e.length,compliantSchemas:s,overallCompliance:i,schemaReports:r,criticalIssues:a,timestamp:Date.now()}}validateAgainstSchema(e,t,r,a){const s=[];if((t=this.resolveRef(t,r)).oneOf||t.anyOf||t.allOf)return this.validateUnion(e,t,r,a);if("object"===t.type&&t.properties){const i=t.required||[];for(const[n,o]of Object.entries(t.properties)){const t=a?`${a}.${n}`:n,c=e?.[n],d=i.includes(n),u=this.checkField(t,c,o,r,d);if(s.push(u),void 0!==c&&"object"===o.type){const e=this.validateAgainstSchema(c,o,r,t);s.push(...e.fields)}}}if("array"===t.type&&e&&Array.isArray(e)){const i=this.validateArray(e,t,r,a);s.push(...i.fields)}return{fields:s}}validateUnion(e,t,r,a){const s=[];if(t.anyOf||t.oneOf){const i=t.anyOf||t.oneOf;let n=!1;for(const t of i){const i=this.resolveRef(t,r);try{if(this.matchesSchema(e,i,r)){const t=this.validateAgainstSchema(e,i,r,a);s.push(...t.fields),n=!0;break}}catch(e){continue}}!n&&a&&s.push({fieldPath:a,present:void 0!==e,expectedType:"oneOf/anyOf options",actualType:typeof e,typeMatches:!1,required:!0,status:"fail",reason:"Value does not match any of the schema options"})}if(t.allOf)for(const i of t.allOf){const t=this.resolveRef(i,r),n=this.validateAgainstSchema(e,t,r,a);s.push(...n.fields)}return{fields:s}}matchesSchema(e,t,r){if((t=this.resolveRef(t,r)).type){const r=Array.isArray(e)?"array":typeof e;if("integer"===t.type&&"number"===r){if(!Number.isInteger(e))return!1}else if(t.type!==r)return!1}if(void 0!==t.const&&e!==t.const)return!1;if(t.enum&&!t.enum.includes(e))return!1;if(t.pattern&&"string"==typeof e&&!new RegExp(t.pattern).test(e))return!1;if("object"===t.type&&t.required)for(const r of t.required)if(!(r in e))return!1;return!0}validateArray(e,t,r,a){const s=[];if(void 0!==t.minItems&&e.length<t.minItems&&s.push({fieldPath:`${a}.length`,present:!0,expectedType:`array with minItems: ${t.minItems}`,actualType:`array with length: ${e.length}`,typeMatches:!1,required:!0,status:"fail",reason:`Array length ${e.length} is less than minItems ${t.minItems}`}),Array.isArray(t.items)){for(let i=0;i<t.items.length;i++){const n=t.items[i],o=e[i],c=`${a}[${i}]`;if(void 0!==o){const e=this.resolveRef(n,r),t=this.validateAgainstSchema(o,e,r,c);s.push(...t.fields)}}if(void 0!==t.additionalItems&&e.length>t.items.length)for(let i=t.items.length;i<e.length;i++){const n=e[i],o=`${a}[${i}]`,c=this.validateAgainstSchema(n,t.additionalItems,r,o);s.push(...c.fields)}}else if(t.items)for(let i=0;i<e.length;i++){const n=e[i],o=`${a}[${i}]`,c=this.resolveRef(t.items,r),d=this.validateAgainstSchema(n,c,r,o);s.push(...d.fields)}if(t.contains){const i=this.resolveRef(t.contains,r);e.some(e=>this.matchesSchema(e,i,r))||s.push({fieldPath:`${a}.contains`,present:!0,expectedType:"array containing matching item",actualType:"array without matching item",typeMatches:!1,required:!0,status:"fail",reason:'Array does not contain any item matching the "contains" schema'})}return{fields:s}}checkField(e,t,r,a,s){r=this.resolveRef(r,a);const i=void 0!==t,n=this.getActualType(t);let o="unknown";return r.type?o=r.type:r.anyOf?o="anyOf":r.oneOf?o="oneOf":r.allOf&&(o="allOf"),s&&!i?{fieldPath:e,present:i,expectedType:o,actualType:n,typeMatches:!1,required:s,status:"fail",reason:"Required field missing"}:s||i?this.matchesSchema(t,r,a)?{fieldPath:e,present:i,expectedType:o,actualType:n,typeMatches:!0,required:s,status:"pass"}:{fieldPath:e,present:i,expectedType:o,actualType:n,typeMatches:!1,required:s,status:"fail",reason:"Type/value mismatch"}:{fieldPath:e,present:i,expectedType:o,actualType:n,typeMatches:!0,required:s,status:"pass"}}getActualType(e){return null===e?"null":Array.isArray(e)?"array":"number"==typeof e&&Number.isInteger(e)?"integer":typeof e}resolveRef(e,t){if(!e.$ref)return e;const r=e.$ref;if(r.startsWith("#/definitions/")){const e=r.substring(14);if(t.definitions&&t.definitions[e])return t.definitions[e]}if(r.startsWith("#/$defs/")){const e=r.substring(8);if(t.$defs&&t.$defs[e])return t.$defs[e]}return"#"===r?t:e}async fetchSchema(e){if(this.schemaCache.has(e))return this.schemaCache.get(e);try{const t=await fetch(e);if(!t.ok)throw new Error(`HTTP ${t.status}: ${t.statusText}`);const r=await t.json();return this.schemaCache.set(e,r),r}catch(t){if(t instanceof Error)throw new Error(`Failed to fetch schema from ${e}: ${t.message}`);throw new Error(`Failed to fetch schema from ${e}: Unknown error`)}}generateReport(e){const t=[];t.push(`\n${"=".repeat(80)}`),t.push(`SCHEMA COMPLIANCE REPORT: ${e.schema.id}`),t.push(`${"=".repeat(80)}\n`),t.push(`Schema: ${e.schema.type} v${e.schema.version}`),t.push(`URL: ${e.schema.url}`),t.push("Status: "+(e.compliant?"✅ COMPLIANT":"❌ NON-COMPLIANT")),t.push(`Compliance: ${e.compliancePercentage.toFixed(1)}%\n`),e.issues.length>0&&(t.push(`\n🚨 ISSUES (${e.issues.length}):`),e.issues.forEach((e,r)=>{t.push(` ${r+1}. ${e}`)})),e.warnings.length>0&&(t.push(`\n⚠️ WARNINGS (${e.warnings.length}):`),e.warnings.forEach((e,r)=>{t.push(` ${r+1}. ${e}`)})),t.push("\n📊 FIELD DETAILS:\n");const r=e.fields.filter(e=>e.required),a=r.filter(e=>"pass"===e.status).length,s=r.filter(e=>"fail"===e.status).length,i=e.fields.filter(e=>"warning"===e.status).length;return t.push(` ✅ Pass: ${a}/${r.length} required fields`),t.push(` ❌ Fail: ${s}/${r.length} required fields`),t.push(` ⚠️ Warn: ${i} optional fields`),t.push(` 📝 Total: ${e.fields.length} fields checked\n`),t.push(`${"=".repeat(80)}\n`),t.join("\n")}generateFullReport(e){const t=[];return t.push(`\n${"=".repeat(80)}`),t.push("FULL SCHEMA COMPLIANCE REPORT"),t.push(`${"=".repeat(80)}\n`),t.push(`Total Schemas: ${e.totalSchemas}`),t.push(`Compliant: ${e.compliantSchemas}`),t.push("Non-Compliant: "+(e.totalSchemas-e.compliantSchemas)),t.push(`Overall Compliance: ${e.overallCompliance.toFixed(1)}%\n`),e.criticalIssues.length>0&&(t.push(`\n🚨 CRITICAL ISSUES (${e.criticalIssues.length}):`),e.criticalIssues.slice(0,10).forEach((e,r)=>{t.push(` ${r+1}. ${e}`)}),e.criticalIssues.length>10&&t.push(` ... and ${e.criticalIssues.length-10} more issues`)),t.push("\n📊 SCHEMA BREAKDOWN:\n"),e.schemaReports.forEach(e=>{const r=e.compliant?"✅":"❌",a=e.compliancePercentage.toFixed(1);t.push(` ${r} ${e.schema.id}: ${a}%`)}),t.push(`\n${"=".repeat(80)}\n`),t.join("\n")}}t.SchemaVerifier=r},27713:e=>{"use strict";var t=e.exports=function(e,t,a){"function"==typeof t&&(a=t,t={}),r(t,"function"==typeof(a=t.cb||a)?a:a.pre||function(){},a.post||function(){},e,"",e)};function r(e,s,i,n,o,c,d,u,l,h){if(n&&"object"==typeof n&&!Array.isArray(n)){for(var p in s(n,o,c,d,u,l,h),n){var f=n[p];if(Array.isArray(f)){if(p in t.arrayKeywords)for(var m=0;m<f.length;m++)r(e,s,i,f[m],o+"/"+p+"/"+m,c,o,p,n,m)}else if(p in t.propsKeywords){if(f&&"object"==typeof f)for(var g in f)r(e,s,i,f[g],o+"/"+p+"/"+a(g),c,o,p,n,g)}else(p in t.keywords||e.allKeys&&!(p in t.skipKeywords))&&r(e,s,i,f,o+"/"+p,c,o,p,n)}i(n,o,c,d,u,l,h)}}function a(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}t.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0},t.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0},t.propsKeywords={definitions:!0,properties:!0,patternProperties:!0,dependencies:!0},t.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}},28339:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DelegationCredentialVerifier=void 0,t.createDelegationVerifier=function(e){return new s(e)};const a=r(49351);class s{didResolver;statusListResolver;signatureVerifier;cache=new Map;cacheTtl;constructor(e){this.didResolver=e?.didResolver,this.statusListResolver=e?.statusListResolver,this.signatureVerifier=e?.signatureVerifier,this.cacheTtl=e?.cacheTtl||6e4}async verifyDelegationCredential(e,t={}){const r=Date.now();if(!t.skipCache){const t=this.getFromCache(e.id||"");if(t)return{...t,cached:!0}}const a=Date.now(),s=this.validateBasicProperties(e),i=Date.now()-a;if(!s.valid)return{valid:!1,reason:s.reason,stage:"basic",metrics:{basicCheckMs:i,totalMs:Date.now()-r},checks:{basicValid:!1}};const n=t.skipSignature?Promise.resolve({valid:!0,durationMs:0}):this.verifySignature(e,t.didResolver||this.didResolver),o=!t.skipStatus&&e.credentialStatus?this.checkCredentialStatus(e.credentialStatus,t.statusListResolver||this.statusListResolver):Promise.resolve({valid:!0,durationMs:0}),[c,d]=await Promise.all([n,o]),u=c.durationMs||0,l=d.durationMs||0,h=s.valid&&c.valid&&d.valid,p={valid:h,reason:h?void 0:c.reason||d.reason||"Unknown failure",stage:"complete",metrics:{basicCheckMs:i,signatureCheckMs:u,statusCheckMs:l,totalMs:Date.now()-r},checks:{basicValid:s.valid,signatureValid:c.valid,statusValid:d.valid}};return p.valid&&e.id&&this.setInCache(e.id,p),p}validateBasicProperties(e){const t=(0,a.validateDelegationCredential)(e);if(!t.success)return{valid:!1,reason:`Schema validation failed: ${t.error.message}`};if((0,a.isDelegationCredentialExpired)(e))return{valid:!1,reason:"Delegation credential expired"};if((0,a.isDelegationCredentialNotYetValid)(e))return{valid:!1,reason:"Delegation credential not yet valid"};const r=e.credentialSubject.delegation;return"revoked"===r.status?{valid:!1,reason:"Delegation status is revoked"}:"expired"===r.status?{valid:!1,reason:"Delegation status is expired"}:r.issuerDid&&r.subjectDid?e.proof?{valid:!0}:{valid:!1,reason:"Missing proof"}:{valid:!1,reason:"Missing issuer or subject DID"}}async verifySignature(e,t){const r=Date.now();try{const a="string"==typeof e.issuer?e.issuer:e.issuer.id;if(!t||!this.signatureVerifier)return{valid:!0,reason:"No DID resolver or signature verifier available, skipping signature verification",durationMs:Date.now()-r};const s=await t.resolve(a);if(!s)return{valid:!1,reason:`Could not resolve issuer DID: ${a}`,durationMs:Date.now()-r};if(!e.proof)return{valid:!1,reason:"Proof is missing",durationMs:Date.now()-r};const i=e.proof.verificationMethod;if(!i)return{valid:!1,reason:"Proof missing verificationMethod",durationMs:Date.now()-r};const n=this.findVerificationMethod(s,i);if(!n)return{valid:!1,reason:`Verification method ${i} not found`,durationMs:Date.now()-r};const o=n.publicKeyJwk;if(!o)return{valid:!1,reason:"Verification method missing publicKeyJwk",durationMs:Date.now()-r};const c=await this.signatureVerifier(e,o);return{valid:c.valid,reason:c.reason,durationMs:Date.now()-r}}catch(e){return{valid:!1,reason:`Signature verification error: ${e instanceof Error?e.message:"Unknown error"}`,durationMs:Date.now()-r}}}async checkCredentialStatus(e,t){const r=Date.now();try{return t?await t.checkStatus(e)?{valid:!1,reason:`Credential revoked via StatusList2021 (${e.statusPurpose})`,durationMs:Date.now()-r}:{valid:!0,durationMs:Date.now()-r}:{valid:!0,reason:"No status list resolver available, skipping status check",durationMs:Date.now()-r}}catch(e){return{valid:!1,reason:`Status check error: ${e instanceof Error?e.message:"Unknown error"}`,durationMs:Date.now()-r}}}findVerificationMethod(e,t){return e.verificationMethod?.find(e=>e.id===t)}getFromCache(e){const t=this.cache.get(e);return t?Date.now()>t.expiresAt?(this.cache.delete(e),null):t.result:null}setInCache(e,t){this.cache.set(e,{result:t,expiresAt:Date.now()+this.cacheTtl})}clearCache(){this.cache.clear()}clearCacheEntry(e){this.cache.delete(e)}}t.DelegationCredentialVerifier=s},28565:e=>{"use strict";var t=e.exports=function(){this._cache={}};t.prototype.put=function(e,t){this._cache[e]=t},t.prototype.get=function(e){return this._cache[e]},t.prototype.del=function(e){delete this._cache[e]},t.prototype.clear=function(){this._cache={}}},31302:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.UserDidManager=void 0,t.UserDidManager=class{config;sessionDidCache=new Map;constructor(e){this.config=e}async getOrCreateUserDid(e){if(this.sessionDidCache.has(e))return this.sessionDidCache.get(e);if(this.config.storage)try{const t=await this.config.storage.get(e);if(t)return this.sessionDidCache.set(e,t),t}catch(e){console.warn("[UserDidManager] Storage.get failed, generating new DID:",e)}const t=await this.generateUserDid();if(this.sessionDidCache.set(e,t),this.config.storage)try{await this.config.storage.set(e,t,1800)}catch(e){console.warn("[UserDidManager] Storage.set failed, continuing with cached DID:",e)}return t}async generateUserDid(){this.config.useDidWeb&&this.config.didWebBaseUrl&&console.warn("[UserDidManager] did:web not yet implemented, using did:key");const e=await this.config.crypto.generateKeyPair(),t=this.base64ToBytes(e.publicKey);return this.generateDidKeyFromPublicKey(t)}generateDidKeyFromPublicKey(e){const t=new Uint8Array([237,1]),r=new Uint8Array(t.length+e.length);return r.set(t),r.set(e,t.length),`did:key:z${this.base58Encode(r)}`}base58Encode(e){let t=BigInt(0);for(let r=0;r<e.length;r++)t=t*BigInt(256)+BigInt(e[r]);let r="";for(;t>0;)r="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"[Number(t%BigInt(58))]+r,t/=BigInt(58);for(let t=0;t<e.length&&0===e[t];t++)r="1"+r;return r}base64ToBytes(e){if("undefined"!=typeof Buffer)return new Uint8Array(Buffer.from(e,"base64"));{const t=atob(e),r=new Uint8Array(t.length);for(let e=0;e<t.length;e++)r[e]=t.charCodeAt(e);return r}}async getUserDid(e){if(this.sessionDidCache.has(e))return this.sessionDidCache.get(e);if(this.config.storage){const t=await this.config.storage.get(e);if(t)return this.sessionDidCache.set(e,t),t}return null}async clearUserDid(e){if(this.sessionDidCache.delete(e),this.config.storage)try{await this.config.storage.delete(e)}catch(e){console.warn("[UserDidManager] Storage.delete failed, continuing:",e)}}clearCache(){this.sessionDidCache.clear()}}},33021:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.BitstringManager=void 0,t.isIndexSet=async function(e,t,a){const s=r.base64urlDecode(e),i=await a.decompress(s),n=Math.floor(t/8),o=t%8;return!(n>=i.length)&&!!(i[n]&1<<o)};class r{compressor;decompressor;bits;size;constructor(e,t,r){this.compressor=t,this.decompressor=r,this.size=e;const a=Math.ceil(e/8);this.bits=new Uint8Array(a)}setBit(e,t){if(e<0||e>=this.size)throw new Error(`Bit index ${e} out of range (0-${this.size-1})`);const r=Math.floor(e/8),a=e%8;t?this.bits[r]|=1<<a:this.bits[r]&=~(1<<a)}getBit(e){if(e<0||e>=this.size)throw new Error(`Bit index ${e} out of range (0-${this.size-1})`);const t=Math.floor(e/8),r=e%8;return!!(this.bits[t]&1<<r)}getSetBits(){const e=[];for(let t=0;t<this.size;t++)this.getBit(t)&&e.push(t);return e}async encode(){const e=await this.compressor.compress(this.bits);return this.base64urlEncode(e)}static async decode(e,t,a){const s=r.base64urlDecode(e),i=await a.decompress(s),n=8*i.length,o=new r(n,t,a);return o.bits=i,o}getRawBits(){return this.bits}getSize(){return this.size}base64urlEncode(e){return this.bytesToBase64(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}static base64urlDecode(e){let t=e.replace(/-/g,"+").replace(/_/g,"/");for(;t.length%4!=0;)t+="=";return r.base64ToBytes(t)}bytesToBase64(e){const t=Array.from(e).map(e=>String.fromCharCode(e)).join("");return btoa(t)}static base64ToBytes(e){const t=atob(e),r=new Uint8Array(t.length);for(let e=0;e<t.length;e++)r[e]=t.charCodeAt(e);return r}static fromSetBits(e,t,a,s){const i=new r(e,a,s);for(const e of t)i.setBit(e,!0);return i}}t.BitstringManager=r},33327:(e,t)=>{"use strict";function r(e){const t=e.length%4;return 0===t?e:e+"=".repeat((4-t)%4)}Object.defineProperty(t,"__esModule",{value:!0}),t.base64urlDecodeToString=function(e){const t=r(e).replace(/-/g,"+").replace(/_/g,"/");if("undefined"!=typeof atob)try{return atob(t)}catch(e){throw new Error(`Invalid base64url string: ${e instanceof Error?e.message:String(e)}`)}if(!/^[A-Za-z0-9+/]*={0,2}$/.test(t))throw new Error("Invalid base64url string: contains invalid characters");try{return Buffer.from(t,"base64").toString("utf-8")}catch(e){throw new Error(`Invalid base64url string: ${e instanceof Error?e.message:String(e)}`)}},t.base64urlDecodeToBytes=function(e){const t=r(e).replace(/-/g,"+").replace(/_/g,"/");if("undefined"!=typeof atob)try{const e=atob(t),r=new Uint8Array(e.length);for(let t=0;t<e.length;t++)r[t]=e.charCodeAt(t);return r}catch(e){throw new Error(`Invalid base64url string: ${e instanceof Error?e.message:String(e)}`)}return new Uint8Array(Buffer.from(t,"base64"))},t.base64urlEncodeFromString=function(e){return"undefined"!=typeof btoa?btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,""):Buffer.from(e,"utf-8").toString("base64").replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")},t.base64urlEncodeFromBytes=function(e){if("undefined"!=typeof btoa){const t=Array.from(e).map(e=>String.fromCharCode(e)).join("");return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}return Buffer.from(e).toString("base64").replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")},t.bytesToBase64=function(e){if("undefined"!=typeof btoa){const t=Array.from(e).map(e=>String.fromCharCode(e)).join("");return btoa(t)}return Buffer.from(e).toString("base64")},t.base64ToBytes=function(e){if("undefined"!=typeof atob){const t=atob(e),r=new Uint8Array(t.length);for(let e=0;e<t.length;e++)r[e]=t.charCodeAt(e);return r}return new Uint8Array(Buffer.from(e,"base64"))}},33728:e=>{"use strict";e.exports=function(e,t,r){var a=" ",s=e.level,i=e.dataLevel,n=e.schema[t],o=e.schemaPath+e.util.getProperty(t),c=e.errSchemaPath+"/"+t,d=!e.opts.allErrors,u="data"+(i||""),l="valid"+s,h="errs__"+s,p=e.util.copy(e),f="";p.level++;var m="valid"+p.level,g="i"+s,y=p.dataLevel=e.dataLevel+1,v="data"+y,_=e.baseId;if(a+="var "+h+" = errors;var "+l+";",Array.isArray(n)){var S=e.schema.additionalItems;if(!1===S){a+=" "+l+" = "+u+".length <= "+n.length+"; ";var b=c;c=e.errSchemaPath+"/additionalItems",a+=" if (!"+l+") { ";var E=E||[];E.push(a),a="",!1!==e.createErrors?(a+=" { keyword: 'additionalItems' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { limit: "+n.length+" } ",!1!==e.opts.messages&&(a+=" , message: 'should NOT have more than "+n.length+" items' "),e.opts.verbose&&(a+=" , schema: false , parentSchema: validate.schema"+e.schemaPath+" , data: "+u+" "),a+=" } "):a+=" {} ";var P=a;a=E.pop(),!e.compositeRule&&d?e.async?a+=" throw new ValidationError(["+P+"]); ":a+=" validate.errors = ["+P+"]; return false; ":a+=" var err = "+P+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",a+=" } ",c=b,d&&(f+="}",a+=" else { ")}var I=n;if(I)for(var w,C=-1,T=I.length-1;C<T;)if(w=I[C+=1],e.opts.strictKeywords?"object"==typeof w&&Object.keys(w).length>0||!1===w:e.util.schemaHasRules(w,e.RULES.all)){a+=" "+m+" = true; if ("+u+".length > "+C+") { ";var D=u+"["+C+"]";p.schema=w,p.schemaPath=o+"["+C+"]",p.errSchemaPath=c+"/"+C,p.errorPath=e.util.getPathExpr(e.errorPath,C,e.opts.jsonPointers,!0),p.dataPathArr[y]=C;var x=e.validate(p);p.baseId=_,e.util.varOccurences(x,v)<2?a+=" "+e.util.varReplace(x,v,D)+" ":a+=" var "+v+" = "+D+"; "+x+" ",a+=" } ",d&&(a+=" if ("+m+") { ",f+="}")}"object"==typeof S&&(e.opts.strictKeywords?"object"==typeof S&&Object.keys(S).length>0||!1===S:e.util.schemaHasRules(S,e.RULES.all))&&(p.schema=S,p.schemaPath=e.schemaPath+".additionalItems",p.errSchemaPath=e.errSchemaPath+"/additionalItems",a+=" "+m+" = true; if ("+u+".length > "+n.length+") { for (var "+g+" = "+n.length+"; "+g+" < "+u+".length; "+g+"++) { ",p.errorPath=e.util.getPathExpr(e.errorPath,g,e.opts.jsonPointers,!0),D=u+"["+g+"]",p.dataPathArr[y]=g,x=e.validate(p),p.baseId=_,e.util.varOccurences(x,v)<2?a+=" "+e.util.varReplace(x,v,D)+" ":a+=" var "+v+" = "+D+"; "+x+" ",d&&(a+=" if (!"+m+") break; "),a+=" } } ",d&&(a+=" if ("+m+") { ",f+="}"))}else(e.opts.strictKeywords?"object"==typeof n&&Object.keys(n).length>0||!1===n:e.util.schemaHasRules(n,e.RULES.all))&&(p.schema=n,p.schemaPath=o,p.errSchemaPath=c,a+=" for (var "+g+" = 0; "+g+" < "+u+".length; "+g+"++) { ",p.errorPath=e.util.getPathExpr(e.errorPath,g,e.opts.jsonPointers,!0),D=u+"["+g+"]",p.dataPathArr[y]=g,x=e.validate(p),p.baseId=_,e.util.varOccurences(x,v)<2?a+=" "+e.util.varReplace(x,v,D)+" ":a+=" var "+v+" = "+D+"; "+x+" ",d&&(a+=" if (!"+m+") break; "),a+=" }");return d&&(a+=" "+f+" if ("+h+" == errors) {"),a}},36885:(e,t,r)=>{"use strict";var a=r(9717),s=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,i=[0,31,28,31,30,31,30,31,31,30,31,30,31],n=/^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d(?::?\d\d)?)?$/i,o=/^(?=.{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,c=/^(?:[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,d=/^(?:(?:[^\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,u=/^(?:(?:http[s\u017F]?|ftp):\/\/)(?:(?:[\0-\x08\x0E-\x1F!-\x9F\xA1-\u167F\u1681-\u1FFF\u200B-\u2027\u202A-\u202E\u2030-\u205E\u2060-\u2FFF\u3001-\uD7FF\uE000-\uFEFE\uFF00-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+(?::(?:[\0-\x08\x0E-\x1F!-\x9F\xA1-\u167F\u1681-\u1FFF\u200B-\u2027\u202A-\u202E\u2030-\u205E\u2060-\u2FFF\u3001-\uD7FF\uE000-\uFEFE\uFF00-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])*)?@)?(?:(?!10(?:\.[0-9]{1,3}){3})(?!127(?:\.[0-9]{1,3}){3})(?!169\.254(?:\.[0-9]{1,3}){2})(?!192\.168(?:\.[0-9]{1,3}){2})(?!172\.(?:1[6-9]|2[0-9]|3[01])(?:\.[0-9]{1,3}){2})(?:[1-9][0-9]?|1[0-9][0-9]|2[01][0-9]|22[0-3])(?:\.(?:1?[0-9]{1,2}|2[0-4][0-9]|25[0-5])){2}(?:\.(?:[1-9][0-9]?|1[0-9][0-9]|2[0-4][0-9]|25[0-4]))|(?:(?:(?:[0-9a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+-)*(?:[0-9a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+)(?:\.(?:(?:[0-9a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+-)*(?:[0-9a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+)*(?:\.(?:(?:[a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]){2,})))(?::[0-9]{2,5})?(?:\/(?:[\0-\x08\x0E-\x1F!-\x9F\xA1-\u167F\u1681-\u1FFF\u200B-\u2027\u202A-\u202E\u2030-\u205E\u2060-\u2FFF\u3001-\uD7FF\uE000-\uFEFE\uFF00-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])*)?$/i,l=/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,h=/^(?:\/(?:[^~/]|~0|~1)*)*$/,p=/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,f=/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/;function m(e){return e="full"==e?"full":"fast",a.copy(m[e])}function g(e){var t=e.match(s);if(!t)return!1;var r=+t[1],a=+t[2],n=+t[3];return a>=1&&a<=12&&n>=1&&n<=(2==a&&function(e){return e%4==0&&(e%100!=0||e%400==0)}(r)?29:i[a])}function y(e,t){var r=e.match(n);if(!r)return!1;var a=r[1],s=r[2],i=r[3],o=r[5];return(a<=23&&s<=59&&i<=59||23==a&&59==s&&60==i)&&(!t||o)}e.exports=m,m.fast={date:/^\d\d\d\d-[0-1]\d-[0-3]\d$/,time:/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,"date-time":/^\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,uri:/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i,"uri-reference":/^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i,"uri-template":d,url:u,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,hostname:o,ipv4:/^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,ipv6:/^\s*(?:(?:(?:[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}))|:)))(?:%.+)?\s*$/i,regex:b,uuid:l,"json-pointer":h,"json-pointer-uri-fragment":p,"relative-json-pointer":f},m.full={date:g,time:y,"date-time":function(e){var t=e.split(v);return 2==t.length&&g(t[0])&&y(t[1],!0)},uri:function(e){return _.test(e)&&c.test(e)},"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":d,url:u,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:o,ipv4:/^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,ipv6:/^\s*(?:(?:(?:[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}))|:)))(?:%.+)?\s*$/i,regex:b,uuid:l,"json-pointer":h,"json-pointer-uri-fragment":p,"relative-json-pointer":f};var v=/t|\s/i,_=/\/|:/,S=/[^\\]\\Z/;function b(e){if(S.test(e))return!1;try{return new RegExp(e),!0}catch(e){return!1}}},36886:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const a=r(68820),s=r(27165);t.default=(e,t)=>{let r;switch(e.code){case a.ZodIssueCode.invalid_type:r=e.received===s.ZodParsedType.undefined?"Required":`Expected ${e.expected}, received ${e.received}`;break;case a.ZodIssueCode.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(e.expected,s.util.jsonStringifyReplacer)}`;break;case a.ZodIssueCode.unrecognized_keys:r=`Unrecognized key(s) in object: ${s.util.joinValues(e.keys,", ")}`;break;case a.ZodIssueCode.invalid_union:r="Invalid input";break;case a.ZodIssueCode.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${s.util.joinValues(e.options)}`;break;case a.ZodIssueCode.invalid_enum_value:r=`Invalid enum value. Expected ${s.util.joinValues(e.options)}, received '${e.received}'`;break;case a.ZodIssueCode.invalid_arguments:r="Invalid function arguments";break;case a.ZodIssueCode.invalid_return_type:r="Invalid function return type";break;case a.ZodIssueCode.invalid_date:r="Invalid date";break;case a.ZodIssueCode.invalid_string:"object"==typeof e.validation?"includes"in e.validation?(r=`Invalid input: must include "${e.validation.includes}"`,"number"==typeof e.validation.position&&(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}"`:s.util.assertNever(e.validation):r="regex"!==e.validation?`Invalid ${e.validation}`:"Invalid";break;case a.ZodIssueCode.too_small:r="array"===e.type?`Array must contain ${e.exact?"exactly":e.inclusive?"at least":"more than"} ${e.minimum} element(s)`:"string"===e.type?`String must contain ${e.exact?"exactly":e.inclusive?"at least":"over"} ${e.minimum} character(s)`:"number"===e.type||"bigint"===e.type?`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:"date"===e.type?`Date must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(e.minimum))}`:"Invalid input";break;case a.ZodIssueCode.too_big:r="array"===e.type?`Array must contain ${e.exact?"exactly":e.inclusive?"at most":"less than"} ${e.maximum} element(s)`:"string"===e.type?`String must contain ${e.exact?"exactly":e.inclusive?"at most":"under"} ${e.maximum} character(s)`:"number"===e.type?`Number must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:"bigint"===e.type?`BigInt must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:"date"===e.type?`Date must be ${e.exact?"exactly":e.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(e.maximum))}`:"Invalid input";break;case a.ZodIssueCode.custom:r="Invalid input";break;case a.ZodIssueCode.invalid_intersection_types:r="Intersection results could not be merged";break;case a.ZodIssueCode.not_multiple_of:r=`Number must be a multiple of ${e.multipleOf}`;break;case a.ZodIssueCode.not_finite:r="Number must be finite";break;default:r=t.defaultError,s.util.assertNever(e)}return{message:r}}},39308:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AgentShieldAPIError=void 0;class r extends Error{constructor(e,t,r){super(t),this.code=e,this.details=r,this.name="AgentShieldAPIError"}}t.AgentShieldAPIError=r},40985:(e,t,r)=>{"use strict";var a=r(13749),s=r(67371),i=r(9717),n=r(20812),o=r(27713);function c(e,t,r){var a=this._refs[r];if("string"==typeof a){if(!this._refs[a])return c.call(this,e,t,a);a=this._refs[a]}if((a=a||this._schemas[r])instanceof n)return f(a.schema,this._opts.inlineRefs)?a.schema:a.validate||this._compile(a);var s,i,o,u=d.call(this,t,r);return u&&(s=u.schema,t=u.root,o=u.baseId),s instanceof n?i=s.validate||e.call(this,s.schema,t,void 0,o):void 0!==s&&(i=f(s,this._opts.inlineRefs)?s:e.call(this,s,t,void 0,o)),i}function d(e,t){var r=a.parse(t),s=v(r),i=y(this._getId(e.schema));if(0===Object.keys(e.schema).length||s!==i){var o=S(s),c=this._refs[o];if("string"==typeof c)return u.call(this,e,c,r);if(c instanceof n)c.validate||this._compile(c),e=c;else{if(!((c=this._schemas[o])instanceof n))return;if(c.validate||this._compile(c),o==S(t))return{schema:c,root:e,baseId:i};e=c}if(!e.schema)return;i=y(this._getId(e.schema))}return h.call(this,r,i,e.schema,e)}function u(e,t,r){var a=d.call(this,e,t);if(a){var s=a.schema,i=a.baseId;e=a.root;var n=this._getId(s);return n&&(i=b(i,n)),h.call(this,r,i,s,e)}}e.exports=c,c.normalizeId=S,c.fullPath=y,c.url=b,c.ids=function(e){var t=S(this._getId(e)),r={"":t},n={"":y(t,!1)},c={},d=this;return o(e,{allKeys:!0},function(e,t,o,u,l,h,p){if(""!==t){var f=d._getId(e),m=r[u],g=n[u]+"/"+l;if(void 0!==p&&(g+="/"+("number"==typeof p?p:i.escapeFragment(p))),"string"==typeof f){f=m=S(m?a.resolve(m,f):f);var y=d._refs[f];if("string"==typeof y&&(y=d._refs[y]),y&&y.schema){if(!s(e,y.schema))throw new Error('id "'+f+'" resolves to more than one schema')}else if(f!=S(g))if("#"==f[0]){if(c[f]&&!s(e,c[f]))throw new Error('id "'+f+'" resolves to more than one schema');c[f]=e}else d._refs[f]=g}r[t]=m,n[t]=g}}),c},c.inlineRef=f,c.schema=d;var l=i.toHash(["properties","patternProperties","enum","dependencies","definitions"]);function h(e,t,r,a){if(e.fragment=e.fragment||"","/"==e.fragment.slice(0,1)){for(var s=e.fragment.split("/"),n=1;n<s.length;n++){var o=s[n];if(o){if(void 0===(r=r[o=i.unescapeFragment(o)]))break;var c;if(!l[o]&&((c=this._getId(r))&&(t=b(t,c)),r.$ref)){var u=b(t,r.$ref),h=d.call(this,a,u);h&&(r=h.schema,a=h.root,t=h.baseId)}}}return void 0!==r&&r!==a.schema?{schema:r,root:a,baseId:t}:void 0}}var p=i.toHash(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum"]);function f(e,t){return!1!==t&&(void 0===t||!0===t?m(e):t?g(e)<=t:void 0)}function m(e){var t;if(Array.isArray(e)){for(var r=0;r<e.length;r++)if("object"==typeof(t=e[r])&&!m(t))return!1}else for(var a in e){if("$ref"==a)return!1;if("object"==typeof(t=e[a])&&!m(t))return!1}return!0}function g(e){var t,r=0;if(Array.isArray(e)){for(var a=0;a<e.length;a++)if("object"==typeof(t=e[a])&&(r+=g(t)),r==1/0)return 1/0}else for(var s in e){if("$ref"==s)return 1/0;if(p[s])r++;else if("object"==typeof(t=e[s])&&(r+=g(t)+1),r==1/0)return 1/0}return r}function y(e,t){return!1!==t&&(e=S(e)),v(a.parse(e))}function v(e){return a.serialize(e).split("#")[0]+"#"}var _=/#\/?$/;function S(e){return e?e.replace(_,""):""}function b(e,t){return t=S(t),a.resolve(e,t)}},41021:e=>{"use strict";e.exports=function(e,t,r){var a,s,i=" ",n=e.level,o=e.dataLevel,c=e.schema[t],d=e.schemaPath+e.util.getProperty(t),u=e.errSchemaPath+"/"+t,l=!e.opts.allErrors,h="data"+(o||""),p="valid"+n,f="errs__"+n,m=e.opts.$data&&c&&c.$data;m?(i+=" var schema"+n+" = "+e.util.getData(c.$data,o,e.dataPathArr)+"; ",s="schema"+n):s=c;var g,y,v,_,S,b=this,E="definition"+n,P=b.definition,I="";if(m&&P.$data){S="keywordValidate"+n;var w=P.validateSchema;i+=" var "+E+" = RULES.custom['"+t+"'].definition; var "+S+" = "+E+".validate;"}else{if(!(_=e.useCustomRule(b,c,e.schema,e)))return;s="validate.schema"+d,S=_.code,g=P.compile,y=P.inline,v=P.macro}var C=S+".errors",T="i"+n,D="ruleErr"+n,x=P.async;if(x&&!e.async)throw new Error("async keyword in sync schema");if(y||v||(i+=C+" = null;"),i+="var "+f+" = errors;var "+p+";",m&&P.$data&&(I+="}",i+=" if ("+s+" === undefined) { "+p+" = true; } else { ",w&&(I+="}",i+=" "+p+" = "+E+".validateSchema("+s+"); if ("+p+") { ")),y)P.statements?i+=" "+_.validate+" ":i+=" "+p+" = "+_.validate+"; ";else if(v){var O=e.util.copy(e);I="",O.level++;var A="valid"+O.level;O.schema=_.validate,O.schemaPath="";var k=e.compositeRule;e.compositeRule=O.compositeRule=!0;var R=e.validate(O).replace(/validate\.schema/g,S);e.compositeRule=O.compositeRule=k,i+=" "+R}else{($=$||[]).push(i),i="",i+=" "+S+".call( ",e.opts.passContext?i+="this":i+="self",g||!1===P.schema?i+=" , "+h+" ":i+=" , "+s+" , "+h+" , validate.schema"+e.schemaPath+" ",i+=" , (dataPath || '')",'""'!=e.errorPath&&(i+=" + "+e.errorPath);var N=o?"data"+(o-1||""):"parentData",j=o?e.dataPathArr[o]:"parentDataProperty",z=i+=" , "+N+" , "+j+" , rootData ) ";i=$.pop(),!1===P.errors?(i+=" "+p+" = ",x&&(i+="await "),i+=z+"; "):i+=x?" var "+(C="customErrors"+n)+" = null; try { "+p+" = await "+z+"; } catch (e) { "+p+" = false; if (e instanceof ValidationError) "+C+" = e.errors; else throw e; } ":" "+C+" = null; "+p+" = "+z+"; "}if(P.modifying&&(i+=" if ("+N+") "+h+" = "+N+"["+j+"];"),i+=""+I,P.valid)l&&(i+=" if (true) { ");else{var $;i+=" if ( ",void 0===P.valid?(i+=" !",i+=v?""+A:""+p):i+=" "+!P.valid+" ",i+=") { ",a=b.keyword,($=$||[]).push(i),i="",($=$||[]).push(i),i="",!1!==e.createErrors?(i+=" { keyword: '"+(a||"custom")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: { keyword: '"+b.keyword+"' } ",!1!==e.opts.messages&&(i+=" , message: 'should pass \""+b.keyword+"\" keyword validation' "),e.opts.verbose&&(i+=" , schema: validate.schema"+d+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+h+" "),i+=" } "):i+=" {} ";var M=i;i=$.pop(),!e.compositeRule&&l?e.async?i+=" throw new ValidationError(["+M+"]); ":i+=" validate.errors = ["+M+"]; return false; ":i+=" var err = "+M+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ";var L=i;i=$.pop(),y?P.errors?"full"!=P.errors&&(i+=" for (var "+T+"="+f+"; "+T+"<errors; "+T+"++) { var "+D+" = vErrors["+T+"]; if ("+D+".dataPath === undefined) "+D+".dataPath = (dataPath || '') + "+e.errorPath+"; if ("+D+".schemaPath === undefined) { "+D+'.schemaPath = "'+u+'"; } ',e.opts.verbose&&(i+=" "+D+".schema = "+s+"; "+D+".data = "+h+"; "),i+=" } "):!1===P.errors?i+=" "+L+" ":(i+=" if ("+f+" == errors) { "+L+" } else { for (var "+T+"="+f+"; "+T+"<errors; "+T+"++) { var "+D+" = vErrors["+T+"]; if ("+D+".dataPath === undefined) "+D+".dataPath = (dataPath || '') + "+e.errorPath+"; if ("+D+".schemaPath === undefined) { "+D+'.schemaPath = "'+u+'"; } ',e.opts.verbose&&(i+=" "+D+".schema = "+s+"; "+D+".data = "+h+"; "),i+=" } } "):v?(i+=" var err = ",!1!==e.createErrors?(i+=" { keyword: '"+(a||"custom")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: { keyword: '"+b.keyword+"' } ",!1!==e.opts.messages&&(i+=" , message: 'should pass \""+b.keyword+"\" keyword validation' "),e.opts.verbose&&(i+=" , schema: validate.schema"+d+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+h+" "),i+=" } "):i+=" {} ",i+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",!e.compositeRule&&l&&(e.async?i+=" throw new ValidationError(vErrors); ":i+=" validate.errors = vErrors; return false; ")):!1===P.errors?i+=" "+L+" ":(i+=" if (Array.isArray("+C+")) { if (vErrors === null) vErrors = "+C+"; else vErrors = vErrors.concat("+C+"); errors = vErrors.length; for (var "+T+"="+f+"; "+T+"<errors; "+T+"++) { var "+D+" = vErrors["+T+"]; if ("+D+".dataPath === undefined) "+D+".dataPath = (dataPath || '') + "+e.errorPath+"; "+D+'.schemaPath = "'+u+'"; ',e.opts.verbose&&(i+=" "+D+".schema = "+s+"; "+D+".data = "+h+"; "),i+=" } } else { "+L+" } "),i+=" } ",l&&(i+=" else { ")}return i}},41094:function(e,t,r){"use strict";var a=this&&this.__createBinding||(Object.create?function(e,t,r,a){void 0===a&&(a=r);var s=Object.getOwnPropertyDescriptor(t,r);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,a,s)}:function(e,t,r,a){void 0===a&&(a=r),e[a]=t[r]}),s=this&&this.__exportStar||function(e,t){for(var r in e)"default"===r||Object.prototype.hasOwnProperty.call(t,r)||a(t,e,r)};Object.defineProperty(t,"__esModule",{value:!0}),s(r(1258),t),s(r(4774),t)},42318:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AccessControlApiService=void 0,t.AccessControlApiService=class{config;metrics;constructor(e){const t=e.retryConfig||{};this.config={retryConfig:{maxRetries:t.maxRetries??3,initialDelayMs:t.initialDelayMs??100,maxDelayMs:t.maxDelayMs??5e3},logger:e.logger||(()=>{}),baseUrl:e.baseUrl,apiKey:e.apiKey,fetchProvider:e.fetchProvider},this.metrics={successCount:0,errorCount:0,retryCount:0}}async fetchConfig(e){throw new Error("Not implemented: fetchConfig")}async verifyDelegation(e,t){throw new Error("Not implemented: verifyDelegation")}async submitProofs(e){throw new Error("Not implemented: submitProofs")}getMetrics(){return{...this.metrics}}resetMetrics(){this.metrics={successCount:0,errorCount:0,retryCount:0}}async retryWithBackoff(e,t=0){try{const t=await e();return this.metrics.successCount++,t}catch(r){const a=this.isRetryableError(r),{maxRetries:s,initialDelayMs:i,maxDelayMs:n}=this.config.retryConfig;if(a&&t<s){const r=Math.min(i*Math.pow(2,t),n);return this.metrics.retryCount++,this.config.logger(`Retrying after ${r}ms (attempt ${t+1}/${s})`),await this.sleep(r),this.retryWithBackoff(e,t+1)}throw this.metrics.errorCount++,r}}isRetryableError(e){return!1}sleep(e){return new Promise(t=>setTimeout(t,e))}}},43528:(e,t,r)=>{"use strict";var a=/^[a-z_$][a-z0-9_$-]*$/i,s=r(41021),i=r(96150);e.exports={add:function(e,t){var r=this.RULES;if(r.keywords[e])throw new Error("Keyword "+e+" is already defined");if(!a.test(e))throw new Error("Keyword "+e+" is not a valid identifier");if(t){this.validateKeyword(t,!0);var i=t.type;if(Array.isArray(i))for(var n=0;n<i.length;n++)c(e,i[n],t);else c(e,i,t);var o=t.metaSchema;o&&(t.$data&&this._opts.$data&&(o={anyOf:[o,{$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"}]}),t.validateSchema=this.compile(o,!0))}function c(e,t,a){for(var i,n=0;n<r.length;n++){var o=r[n];if(o.type==t){i=o;break}}i||(i={type:t,rules:[]},r.push(i));var c={keyword:e,definition:a,custom:!0,code:s,implements:a.implements};i.rules.push(c),r.custom[e]=c}return r.keywords[e]=r.all[e]=!0,this},get:function(e){var t=this.RULES.custom[e];return t?t.definition:this.RULES.keywords[e]||!1},remove:function(e){var t=this.RULES;delete t.keywords[e],delete t.all[e],delete t.custom[e];for(var r=0;r<t.length;r++)for(var a=t[r].rules,s=0;s<a.length;s++)if(a[s].keyword==e){a.splice(s,1);break}return this},validate:function e(t,r){e.errors=null;var a=this._validateKeyword=this._validateKeyword||this.compile(i,!0);if(a(t))return!0;if(e.errors=a.errors,r)throw new Error("custom keyword definition is invalid: "+this.errorsText(a.errors));return!1}}},44242:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.discriminatedUnion=t.date=t.boolean=t.bigint=t.array=t.any=t.coerce=t.ZodFirstPartyTypeKind=t.late=t.ZodSchema=t.Schema=t.ZodReadonly=t.ZodPipeline=t.ZodBranded=t.BRAND=t.ZodNaN=t.ZodCatch=t.ZodDefault=t.ZodNullable=t.ZodOptional=t.ZodTransformer=t.ZodEffects=t.ZodPromise=t.ZodNativeEnum=t.ZodEnum=t.ZodLiteral=t.ZodLazy=t.ZodFunction=t.ZodSet=t.ZodMap=t.ZodRecord=t.ZodTuple=t.ZodIntersection=t.ZodDiscriminatedUnion=t.ZodUnion=t.ZodObject=t.ZodArray=t.ZodVoid=t.ZodNever=t.ZodUnknown=t.ZodAny=t.ZodNull=t.ZodUndefined=t.ZodSymbol=t.ZodDate=t.ZodBoolean=t.ZodBigInt=t.ZodNumber=t.ZodString=t.ZodType=void 0,t.NEVER=t.void=t.unknown=t.union=t.undefined=t.tuple=t.transformer=t.symbol=t.string=t.strictObject=t.set=t.record=t.promise=t.preprocess=t.pipeline=t.ostring=t.optional=t.onumber=t.oboolean=t.object=t.number=t.nullable=t.null=t.never=t.nativeEnum=t.nan=t.map=t.literal=t.lazy=t.intersection=t.instanceof=t.function=t.enum=t.effect=void 0,t.datetimeRegex=A,t.custom=Pe;const a=r(68820),s=r(80630),i=r(55957),n=r(70926),o=r(27165);class c{constructor(e,t,r,a){this._cachedPath=[],this.parent=e,this.data=t,this._path=r,this._key=a}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}}const d=(e,t)=>{if((0,n.isValid)(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;const t=new a.ZodError(e.common.issues);return this._error=t,this._error}}};function u(e){if(!e)return{};const{errorMap:t,invalid_type_error:r,required_error:a,description:s}=e;if(t&&(r||a))throw new Error('Can\'t use "invalid_type_error" or "required_error" in conjunction with custom error map.');return t?{errorMap:t,description:s}:{errorMap:(t,s)=>{const{message:i}=e;return"invalid_enum_value"===t.code?{message:i??s.defaultError}:void 0===s.data?{message:i??a??s.defaultError}:"invalid_type"!==t.code?{message:s.defaultError}:{message:i??r??s.defaultError}},description:s}}class l{get description(){return this._def.description}_getType(e){return(0,o.getParsedType)(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:(0,o.getParsedType)(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new n.ParseStatus,ctx:{common:e.parent.common,data:e.data,parsedType:(0,o.getParsedType)(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const t=this._parse(e);if((0,n.isAsync)(t))throw new Error("Synchronous parse encountered promise.");return t}_parseAsync(e){const t=this._parse(e);return Promise.resolve(t)}parse(e,t){const r=this.safeParse(e,t);if(r.success)return r.data;throw r.error}safeParse(e,t){const r={common:{issues:[],async:t?.async??!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:(0,o.getParsedType)(e)},a=this._parseSync({data:e,path:r.path,parent:r});return d(r,a)}"~validate"(e){const t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:(0,o.getParsedType)(e)};if(!this["~standard"].async)try{const r=this._parseSync({data:e,path:[],parent:t});return(0,n.isValid)(r)?{value:r.value}:{issues:t.common.issues}}catch(e){e?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then(e=>(0,n.isValid)(e)?{value:e.value}:{issues:t.common.issues})}async parseAsync(e,t){const r=await this.safeParseAsync(e,t);if(r.success)return r.data;throw r.error}async safeParseAsync(e,t){const r={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:(0,o.getParsedType)(e)},a=this._parse({data:e,path:r.path,parent:r}),s=await((0,n.isAsync)(a)?a:Promise.resolve(a));return d(r,s)}refine(e,t){const r=e=>"string"==typeof t||void 0===t?{message:t}:"function"==typeof t?t(e):t;return this._refinement((t,s)=>{const i=e(t),n=()=>s.addIssue({code:a.ZodIssueCode.custom,...r(t)});return"undefined"!=typeof Promise&&i instanceof Promise?i.then(e=>!!e||(n(),!1)):!!i||(n(),!1)})}refinement(e,t){return this._refinement((r,a)=>!!e(r)||(a.addIssue("function"==typeof t?t(r,a):t),!1))}_refinement(e){return new pe({schema:this,typeName:Ie.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:e=>this["~validate"](e)}}optional(){return fe.create(this,this._def)}nullable(){return me.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return W.create(this)}promise(){return he.create(this,this._def)}or(e){return X.create([this,e],this._def)}and(e){return te.create(this,e,this._def)}transform(e){return new pe({...u(this._def),schema:this,typeName:Ie.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const t="function"==typeof e?e:()=>e;return new ge({...u(this._def),innerType:this,defaultValue:t,typeName:Ie.ZodDefault})}brand(){return new _e({typeName:Ie.ZodBranded,type:this,...u(this._def)})}catch(e){const t="function"==typeof e?e:()=>e;return new ye({...u(this._def),innerType:this,catchValue:t,typeName:Ie.ZodCatch})}describe(e){return new(0,this.constructor)({...this._def,description:e})}pipe(e){return Se.create(this,e)}readonly(){return be.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}t.ZodType=l,t.Schema=l,t.ZodSchema=l;const h=/^c[^\s-]{8,}$/i,p=/^[0-9a-z]+$/,f=/^[0-9A-HJKMNP-TV-Z]{26}$/i,m=/^[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,g=/^[a-z0-9_-]{21}$/i,y=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,v=/^[-+]?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)?)??$/,_=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;let S;const b=/^(?:(?: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])$/,E=/^(?:(?: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])$/,P=/^(([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]))$/,I=/^(([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])$/,w=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,C=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,T="((\\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])))",D=new RegExp(`^${T}$`);function x(e){let t="[0-5]\\d";return e.precision?t=`${t}\\.\\d{${e.precision}}`:null==e.precision&&(t=`${t}(\\.\\d+)?`),`([01]\\d|2[0-3]):[0-5]\\d(:${t})${e.precision?"+":"?"}`}function O(e){return new RegExp(`^${x(e)}$`)}function A(e){let t=`${T}T${x(e)}`;const r=[];return r.push(e.local?"Z?":"Z"),e.offset&&r.push("([+-]\\d{2}:?\\d{2})"),t=`${t}(${r.join("|")})`,new RegExp(`^${t}$`)}function k(e,t){return!("v4"!==t&&t||!b.test(e))||!("v6"!==t&&t||!P.test(e))}function R(e,t){if(!y.test(e))return!1;try{const[r]=e.split(".");if(!r)return!1;const a=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.length%4)%4,"="),s=JSON.parse(atob(a));return!("object"!=typeof s||null===s||"typ"in s&&"JWT"!==s?.typ||!s.alg||t&&s.alg!==t)}catch{return!1}}function N(e,t){return!("v4"!==t&&t||!E.test(e))||!("v6"!==t&&t||!I.test(e))}class j extends l{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==o.ZodParsedType.string){const t=this._getOrReturnCtx(e);return(0,n.addIssueToContext)(t,{code:a.ZodIssueCode.invalid_type,expected:o.ZodParsedType.string,received:t.parsedType}),n.INVALID}const t=new n.ParseStatus;let r;for(const s of this._def.checks)if("min"===s.kind)e.data.length<s.value&&(r=this._getOrReturnCtx(e,r),(0,n.addIssueToContext)(r,{code:a.ZodIssueCode.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),t.dirty());else if("max"===s.kind)e.data.length>s.value&&(r=this._getOrReturnCtx(e,r),(0,n.addIssueToContext)(r,{code:a.ZodIssueCode.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),t.dirty());else if("length"===s.kind){const i=e.data.length>s.value,o=e.data.length<s.value;(i||o)&&(r=this._getOrReturnCtx(e,r),i?(0,n.addIssueToContext)(r,{code:a.ZodIssueCode.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}):o&&(0,n.addIssueToContext)(r,{code:a.ZodIssueCode.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}),t.dirty())}else if("email"===s.kind)_.test(e.data)||(r=this._getOrReturnCtx(e,r),(0,n.addIssueToContext)(r,{validation:"email",code:a.ZodIssueCode.invalid_string,message:s.message}),t.dirty());else if("emoji"===s.kind)S||(S=new RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),S.test(e.data)||(r=this._getOrReturnCtx(e,r),(0,n.addIssueToContext)(r,{validation:"emoji",code:a.ZodIssueCode.invalid_string,message:s.message}),t.dirty());else if("uuid"===s.kind)m.test(e.data)||(r=this._getOrReturnCtx(e,r),(0,n.addIssueToContext)(r,{validation:"uuid",code:a.ZodIssueCode.invalid_string,message:s.message}),t.dirty());else if("nanoid"===s.kind)g.test(e.data)||(r=this._getOrReturnCtx(e,r),(0,n.addIssueToContext)(r,{validation:"nanoid",code:a.ZodIssueCode.invalid_string,message:s.message}),t.dirty());else if("cuid"===s.kind)h.test(e.data)||(r=this._getOrReturnCtx(e,r),(0,n.addIssueToContext)(r,{validation:"cuid",code:a.ZodIssueCode.invalid_string,message:s.message}),t.dirty());else if("cuid2"===s.kind)p.test(e.data)||(r=this._getOrReturnCtx(e,r),(0,n.addIssueToContext)(r,{validation:"cuid2",code:a.ZodIssueCode.invalid_string,message:s.message}),t.dirty());else if("ulid"===s.kind)f.test(e.data)||(r=this._getOrReturnCtx(e,r),(0,n.addIssueToContext)(r,{validation:"ulid",code:a.ZodIssueCode.invalid_string,message:s.message}),t.dirty());else if("url"===s.kind)try{new URL(e.data)}catch{r=this._getOrReturnCtx(e,r),(0,n.addIssueToContext)(r,{validation:"url",code:a.ZodIssueCode.invalid_string,message:s.message}),t.dirty()}else"regex"===s.kind?(s.regex.lastIndex=0,s.regex.test(e.data)||(r=this._getOrReturnCtx(e,r),(0,n.addIssueToContext)(r,{validation:"regex",code:a.ZodIssueCode.invalid_string,message:s.message}),t.dirty())):"trim"===s.kind?e.data=e.data.trim():"includes"===s.kind?e.data.includes(s.value,s.position)||(r=this._getOrReturnCtx(e,r),(0,n.addIssueToContext)(r,{code:a.ZodIssueCode.invalid_string,validation:{includes:s.value,position:s.position},message:s.message}),t.dirty()):"toLowerCase"===s.kind?e.data=e.data.toLowerCase():"toUpperCase"===s.kind?e.data=e.data.toUpperCase():"startsWith"===s.kind?e.data.startsWith(s.value)||(r=this._getOrReturnCtx(e,r),(0,n.addIssueToContext)(r,{code:a.ZodIssueCode.invalid_string,validation:{startsWith:s.value},message:s.message}),t.dirty()):"endsWith"===s.kind?e.data.endsWith(s.value)||(r=this._getOrReturnCtx(e,r),(0,n.addIssueToContext)(r,{code:a.ZodIssueCode.invalid_string,validation:{endsWith:s.value},message:s.message}),t.dirty()):"datetime"===s.kind?A(s).test(e.data)||(r=this._getOrReturnCtx(e,r),(0,n.addIssueToContext)(r,{code:a.ZodIssueCode.invalid_string,validation:"datetime",message:s.message}),t.dirty()):"date"===s.kind?D.test(e.data)||(r=this._getOrReturnCtx(e,r),(0,n.addIssueToContext)(r,{code:a.ZodIssueCode.invalid_string,validation:"date",message:s.message}),t.dirty()):"time"===s.kind?O(s).test(e.data)||(r=this._getOrReturnCtx(e,r),(0,n.addIssueToContext)(r,{code:a.ZodIssueCode.invalid_string,validation:"time",message:s.message}),t.dirty()):"duration"===s.kind?v.test(e.data)||(r=this._getOrReturnCtx(e,r),(0,n.addIssueToContext)(r,{validation:"duration",code:a.ZodIssueCode.invalid_string,message:s.message}),t.dirty()):"ip"===s.kind?k(e.data,s.version)||(r=this._getOrReturnCtx(e,r),(0,n.addIssueToContext)(r,{validation:"ip",code:a.ZodIssueCode.invalid_string,message:s.message}),t.dirty()):"jwt"===s.kind?R(e.data,s.alg)||(r=this._getOrReturnCtx(e,r),(0,n.addIssueToContext)(r,{validation:"jwt",code:a.ZodIssueCode.invalid_string,message:s.message}),t.dirty()):"cidr"===s.kind?N(e.data,s.version)||(r=this._getOrReturnCtx(e,r),(0,n.addIssueToContext)(r,{validation:"cidr",code:a.ZodIssueCode.invalid_string,message:s.message}),t.dirty()):"base64"===s.kind?w.test(e.data)||(r=this._getOrReturnCtx(e,r),(0,n.addIssueToContext)(r,{validation:"base64",code:a.ZodIssueCode.invalid_string,message:s.message}),t.dirty()):"base64url"===s.kind?C.test(e.data)||(r=this._getOrReturnCtx(e,r),(0,n.addIssueToContext)(r,{validation:"base64url",code:a.ZodIssueCode.invalid_string,message:s.message}),t.dirty()):o.util.assertNever(s);return{status:t.value,value:e.data}}_regex(e,t,r){return this.refinement(t=>e.test(t),{validation:t,code:a.ZodIssueCode.invalid_string,...i.errorUtil.errToObj(r)})}_addCheck(e){return new j({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...i.errorUtil.errToObj(e)})}url(e){return this._addCheck({kind:"url",...i.errorUtil.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...i.errorUtil.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...i.errorUtil.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...i.errorUtil.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...i.errorUtil.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...i.errorUtil.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...i.errorUtil.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...i.errorUtil.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...i.errorUtil.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...i.errorUtil.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...i.errorUtil.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...i.errorUtil.errToObj(e)})}datetime(e){return"string"==typeof e?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:void 0===e?.precision?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...i.errorUtil.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return"string"==typeof e?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:void 0===e?.precision?null:e?.precision,...i.errorUtil.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...i.errorUtil.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...i.errorUtil.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t?.position,...i.errorUtil.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...i.errorUtil.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...i.errorUtil.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...i.errorUtil.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...i.errorUtil.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...i.errorUtil.errToObj(t)})}nonempty(e){return this.min(1,i.errorUtil.errToObj(e))}trim(){return new j({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new j({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new j({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>"datetime"===e.kind)}get isDate(){return!!this._def.checks.find(e=>"date"===e.kind)}get isTime(){return!!this._def.checks.find(e=>"time"===e.kind)}get isDuration(){return!!this._def.checks.find(e=>"duration"===e.kind)}get isEmail(){return!!this._def.checks.find(e=>"email"===e.kind)}get isURL(){return!!this._def.checks.find(e=>"url"===e.kind)}get isEmoji(){return!!this._def.checks.find(e=>"emoji"===e.kind)}get isUUID(){return!!this._def.checks.find(e=>"uuid"===e.kind)}get isNANOID(){return!!this._def.checks.find(e=>"nanoid"===e.kind)}get isCUID(){return!!this._def.checks.find(e=>"cuid"===e.kind)}get isCUID2(){return!!this._def.checks.find(e=>"cuid2"===e.kind)}get isULID(){return!!this._def.checks.find(e=>"ulid"===e.kind)}get isIP(){return!!this._def.checks.find(e=>"ip"===e.kind)}get isCIDR(){return!!this._def.checks.find(e=>"cidr"===e.kind)}get isBase64(){return!!this._def.checks.find(e=>"base64"===e.kind)}get isBase64url(){return!!this._def.checks.find(e=>"base64url"===e.kind)}get minLength(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}}function z(e,t){const r=(e.toString().split(".")[1]||"").length,a=(t.toString().split(".")[1]||"").length,s=r>a?r:a;return Number.parseInt(e.toFixed(s).replace(".",""))%Number.parseInt(t.toFixed(s).replace(".",""))/10**s}t.ZodString=j,j.create=e=>new j({checks:[],typeName:Ie.ZodString,coerce:e?.coerce??!1,...u(e)});class $ extends l{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==o.ZodParsedType.number){const t=this._getOrReturnCtx(e);return(0,n.addIssueToContext)(t,{code:a.ZodIssueCode.invalid_type,expected:o.ZodParsedType.number,received:t.parsedType}),n.INVALID}let t;const r=new n.ParseStatus;for(const s of this._def.checks)"int"===s.kind?o.util.isInteger(e.data)||(t=this._getOrReturnCtx(e,t),(0,n.addIssueToContext)(t,{code:a.ZodIssueCode.invalid_type,expected:"integer",received:"float",message:s.message}),r.dirty()):"min"===s.kind?(s.inclusive?e.data<s.value:e.data<=s.value)&&(t=this._getOrReturnCtx(e,t),(0,n.addIssueToContext)(t,{code:a.ZodIssueCode.too_small,minimum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),r.dirty()):"max"===s.kind?(s.inclusive?e.data>s.value:e.data>=s.value)&&(t=this._getOrReturnCtx(e,t),(0,n.addIssueToContext)(t,{code:a.ZodIssueCode.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),r.dirty()):"multipleOf"===s.kind?0!==z(e.data,s.value)&&(t=this._getOrReturnCtx(e,t),(0,n.addIssueToContext)(t,{code:a.ZodIssueCode.not_multiple_of,multipleOf:s.value,message:s.message}),r.dirty()):"finite"===s.kind?Number.isFinite(e.data)||(t=this._getOrReturnCtx(e,t),(0,n.addIssueToContext)(t,{code:a.ZodIssueCode.not_finite,message:s.message}),r.dirty()):o.util.assertNever(s);return{status:r.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,i.errorUtil.toString(t))}gt(e,t){return this.setLimit("min",e,!1,i.errorUtil.toString(t))}lte(e,t){return this.setLimit("max",e,!0,i.errorUtil.toString(t))}lt(e,t){return this.setLimit("max",e,!1,i.errorUtil.toString(t))}setLimit(e,t,r,a){return new $({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:i.errorUtil.toString(a)}]})}_addCheck(e){return new $({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:i.errorUtil.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:i.errorUtil.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:i.errorUtil.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:i.errorUtil.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:i.errorUtil.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:i.errorUtil.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:i.errorUtil.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:i.errorUtil.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:i.errorUtil.toString(e)})}get minValue(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find(e=>"int"===e.kind||"multipleOf"===e.kind&&o.util.isInteger(e.value))}get isFinite(){let e=null,t=null;for(const r of this._def.checks){if("finite"===r.kind||"int"===r.kind||"multipleOf"===r.kind)return!0;"min"===r.kind?(null===t||r.value>t)&&(t=r.value):"max"===r.kind&&(null===e||r.value<e)&&(e=r.value)}return Number.isFinite(t)&&Number.isFinite(e)}}t.ZodNumber=$,$.create=e=>new $({checks:[],typeName:Ie.ZodNumber,coerce:e?.coerce||!1,...u(e)});class M extends l{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==o.ZodParsedType.bigint)return this._getInvalidInput(e);let t;const r=new n.ParseStatus;for(const s of this._def.checks)"min"===s.kind?(s.inclusive?e.data<s.value:e.data<=s.value)&&(t=this._getOrReturnCtx(e,t),(0,n.addIssueToContext)(t,{code:a.ZodIssueCode.too_small,type:"bigint",minimum:s.value,inclusive:s.inclusive,message:s.message}),r.dirty()):"max"===s.kind?(s.inclusive?e.data>s.value:e.data>=s.value)&&(t=this._getOrReturnCtx(e,t),(0,n.addIssueToContext)(t,{code:a.ZodIssueCode.too_big,type:"bigint",maximum:s.value,inclusive:s.inclusive,message:s.message}),r.dirty()):"multipleOf"===s.kind?e.data%s.value!==BigInt(0)&&(t=this._getOrReturnCtx(e,t),(0,n.addIssueToContext)(t,{code:a.ZodIssueCode.not_multiple_of,multipleOf:s.value,message:s.message}),r.dirty()):o.util.assertNever(s);return{status:r.value,value:e.data}}_getInvalidInput(e){const t=this._getOrReturnCtx(e);return(0,n.addIssueToContext)(t,{code:a.ZodIssueCode.invalid_type,expected:o.ZodParsedType.bigint,received:t.parsedType}),n.INVALID}gte(e,t){return this.setLimit("min",e,!0,i.errorUtil.toString(t))}gt(e,t){return this.setLimit("min",e,!1,i.errorUtil.toString(t))}lte(e,t){return this.setLimit("max",e,!0,i.errorUtil.toString(t))}lt(e,t){return this.setLimit("max",e,!1,i.errorUtil.toString(t))}setLimit(e,t,r,a){return new M({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:i.errorUtil.toString(a)}]})}_addCheck(e){return new M({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:i.errorUtil.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:i.errorUtil.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:i.errorUtil.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:i.errorUtil.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:i.errorUtil.toString(t)})}get minValue(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}}t.ZodBigInt=M,M.create=e=>new M({checks:[],typeName:Ie.ZodBigInt,coerce:e?.coerce??!1,...u(e)});class L extends l{_parse(e){if(this._def.coerce&&(e.data=Boolean(e.data)),this._getType(e)!==o.ZodParsedType.boolean){const t=this._getOrReturnCtx(e);return(0,n.addIssueToContext)(t,{code:a.ZodIssueCode.invalid_type,expected:o.ZodParsedType.boolean,received:t.parsedType}),n.INVALID}return(0,n.OK)(e.data)}}t.ZodBoolean=L,L.create=e=>new L({typeName:Ie.ZodBoolean,coerce:e?.coerce||!1,...u(e)});class F extends l{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==o.ZodParsedType.date){const t=this._getOrReturnCtx(e);return(0,n.addIssueToContext)(t,{code:a.ZodIssueCode.invalid_type,expected:o.ZodParsedType.date,received:t.parsedType}),n.INVALID}if(Number.isNaN(e.data.getTime())){const t=this._getOrReturnCtx(e);return(0,n.addIssueToContext)(t,{code:a.ZodIssueCode.invalid_date}),n.INVALID}const t=new n.ParseStatus;let r;for(const s of this._def.checks)"min"===s.kind?e.data.getTime()<s.value&&(r=this._getOrReturnCtx(e,r),(0,n.addIssueToContext)(r,{code:a.ZodIssueCode.too_small,message:s.message,inclusive:!0,exact:!1,minimum:s.value,type:"date"}),t.dirty()):"max"===s.kind?e.data.getTime()>s.value&&(r=this._getOrReturnCtx(e,r),(0,n.addIssueToContext)(r,{code:a.ZodIssueCode.too_big,message:s.message,inclusive:!0,exact:!1,maximum:s.value,type:"date"}),t.dirty()):o.util.assertNever(s);return{status:t.value,value:new Date(e.data.getTime())}}_addCheck(e){return new F({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:i.errorUtil.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:i.errorUtil.toString(t)})}get minDate(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return null!=e?new Date(e):null}get maxDate(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return null!=e?new Date(e):null}}t.ZodDate=F,F.create=e=>new F({checks:[],coerce:e?.coerce||!1,typeName:Ie.ZodDate,...u(e)});class Z extends l{_parse(e){if(this._getType(e)!==o.ZodParsedType.symbol){const t=this._getOrReturnCtx(e);return(0,n.addIssueToContext)(t,{code:a.ZodIssueCode.invalid_type,expected:o.ZodParsedType.symbol,received:t.parsedType}),n.INVALID}return(0,n.OK)(e.data)}}t.ZodSymbol=Z,Z.create=e=>new Z({typeName:Ie.ZodSymbol,...u(e)});class V extends l{_parse(e){if(this._getType(e)!==o.ZodParsedType.undefined){const t=this._getOrReturnCtx(e);return(0,n.addIssueToContext)(t,{code:a.ZodIssueCode.invalid_type,expected:o.ZodParsedType.undefined,received:t.parsedType}),n.INVALID}return(0,n.OK)(e.data)}}t.ZodUndefined=V,V.create=e=>new V({typeName:Ie.ZodUndefined,...u(e)});class K extends l{_parse(e){if(this._getType(e)!==o.ZodParsedType.null){const t=this._getOrReturnCtx(e);return(0,n.addIssueToContext)(t,{code:a.ZodIssueCode.invalid_type,expected:o.ZodParsedType.null,received:t.parsedType}),n.INVALID}return(0,n.OK)(e.data)}}t.ZodNull=K,K.create=e=>new K({typeName:Ie.ZodNull,...u(e)});class U extends l{constructor(){super(...arguments),this._any=!0}_parse(e){return(0,n.OK)(e.data)}}t.ZodAny=U,U.create=e=>new U({typeName:Ie.ZodAny,...u(e)});class H extends l{constructor(){super(...arguments),this._unknown=!0}_parse(e){return(0,n.OK)(e.data)}}t.ZodUnknown=H,H.create=e=>new H({typeName:Ie.ZodUnknown,...u(e)});class q extends l{_parse(e){const t=this._getOrReturnCtx(e);return(0,n.addIssueToContext)(t,{code:a.ZodIssueCode.invalid_type,expected:o.ZodParsedType.never,received:t.parsedType}),n.INVALID}}t.ZodNever=q,q.create=e=>new q({typeName:Ie.ZodNever,...u(e)});class B extends l{_parse(e){if(this._getType(e)!==o.ZodParsedType.undefined){const t=this._getOrReturnCtx(e);return(0,n.addIssueToContext)(t,{code:a.ZodIssueCode.invalid_type,expected:o.ZodParsedType.void,received:t.parsedType}),n.INVALID}return(0,n.OK)(e.data)}}t.ZodVoid=B,B.create=e=>new B({typeName:Ie.ZodVoid,...u(e)});class W extends l{_parse(e){const{ctx:t,status:r}=this._processInputParams(e),s=this._def;if(t.parsedType!==o.ZodParsedType.array)return(0,n.addIssueToContext)(t,{code:a.ZodIssueCode.invalid_type,expected:o.ZodParsedType.array,received:t.parsedType}),n.INVALID;if(null!==s.exactLength){const e=t.data.length>s.exactLength.value,i=t.data.length<s.exactLength.value;(e||i)&&((0,n.addIssueToContext)(t,{code:e?a.ZodIssueCode.too_big:a.ZodIssueCode.too_small,minimum:i?s.exactLength.value:void 0,maximum:e?s.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:s.exactLength.message}),r.dirty())}if(null!==s.minLength&&t.data.length<s.minLength.value&&((0,n.addIssueToContext)(t,{code:a.ZodIssueCode.too_small,minimum:s.minLength.value,type:"array",inclusive:!0,exact:!1,message:s.minLength.message}),r.dirty()),null!==s.maxLength&&t.data.length>s.maxLength.value&&((0,n.addIssueToContext)(t,{code:a.ZodIssueCode.too_big,maximum:s.maxLength.value,type:"array",inclusive:!0,exact:!1,message:s.maxLength.message}),r.dirty()),t.common.async)return Promise.all([...t.data].map((e,r)=>s.type._parseAsync(new c(t,e,t.path,r)))).then(e=>n.ParseStatus.mergeArray(r,e));const i=[...t.data].map((e,r)=>s.type._parseSync(new c(t,e,t.path,r)));return n.ParseStatus.mergeArray(r,i)}get element(){return this._def.type}min(e,t){return new W({...this._def,minLength:{value:e,message:i.errorUtil.toString(t)}})}max(e,t){return new W({...this._def,maxLength:{value:e,message:i.errorUtil.toString(t)}})}length(e,t){return new W({...this._def,exactLength:{value:e,message:i.errorUtil.toString(t)}})}nonempty(e){return this.min(1,e)}}function G(e){if(e instanceof J){const t={};for(const r in e.shape){const a=e.shape[r];t[r]=fe.create(G(a))}return new J({...e._def,shape:()=>t})}return e instanceof W?new W({...e._def,type:G(e.element)}):e instanceof fe?fe.create(G(e.unwrap())):e instanceof me?me.create(G(e.unwrap())):e instanceof re?re.create(e.items.map(e=>G(e))):e}t.ZodArray=W,W.create=(e,t)=>new W({type:e,minLength:null,maxLength:null,exactLength:null,typeName:Ie.ZodArray,...u(t)});class J extends l{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(null!==this._cached)return this._cached;const e=this._def.shape(),t=o.util.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==o.ZodParsedType.object){const t=this._getOrReturnCtx(e);return(0,n.addIssueToContext)(t,{code:a.ZodIssueCode.invalid_type,expected:o.ZodParsedType.object,received:t.parsedType}),n.INVALID}const{status:t,ctx:r}=this._processInputParams(e),{shape:s,keys:i}=this._getCached(),d=[];if(!(this._def.catchall instanceof q&&"strip"===this._def.unknownKeys))for(const e in r.data)i.includes(e)||d.push(e);const u=[];for(const e of i){const t=s[e],a=r.data[e];u.push({key:{status:"valid",value:e},value:t._parse(new c(r,a,r.path,e)),alwaysSet:e in r.data})}if(this._def.catchall instanceof q){const e=this._def.unknownKeys;if("passthrough"===e)for(const e of d)u.push({key:{status:"valid",value:e},value:{status:"valid",value:r.data[e]}});else if("strict"===e)d.length>0&&((0,n.addIssueToContext)(r,{code:a.ZodIssueCode.unrecognized_keys,keys:d}),t.dirty());else if("strip"!==e)throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const e=this._def.catchall;for(const t of d){const a=r.data[t];u.push({key:{status:"valid",value:t},value:e._parse(new c(r,a,r.path,t)),alwaysSet:t in r.data})}}return r.common.async?Promise.resolve().then(async()=>{const e=[];for(const t of u){const r=await t.key,a=await t.value;e.push({key:r,value:a,alwaysSet:t.alwaysSet})}return e}).then(e=>n.ParseStatus.mergeObjectSync(t,e)):n.ParseStatus.mergeObjectSync(t,u)}get shape(){return this._def.shape()}strict(e){return i.errorUtil.errToObj,new J({...this._def,unknownKeys:"strict",...void 0!==e?{errorMap:(t,r)=>{const a=this._def.errorMap?.(t,r).message??r.defaultError;return"unrecognized_keys"===t.code?{message:i.errorUtil.errToObj(e).message??a}:{message:a}}}:{}})}strip(){return new J({...this._def,unknownKeys:"strip"})}passthrough(){return new J({...this._def,unknownKeys:"passthrough"})}extend(e){return new J({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new J({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:Ie.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new J({...this._def,catchall:e})}pick(e){const t={};for(const r of o.util.objectKeys(e))e[r]&&this.shape[r]&&(t[r]=this.shape[r]);return new J({...this._def,shape:()=>t})}omit(e){const t={};for(const r of o.util.objectKeys(this.shape))e[r]||(t[r]=this.shape[r]);return new J({...this._def,shape:()=>t})}deepPartial(){return G(this)}partial(e){const t={};for(const r of o.util.objectKeys(this.shape)){const a=this.shape[r];e&&!e[r]?t[r]=a:t[r]=a.optional()}return new J({...this._def,shape:()=>t})}required(e){const t={};for(const r of o.util.objectKeys(this.shape))if(e&&!e[r])t[r]=this.shape[r];else{let e=this.shape[r];for(;e instanceof fe;)e=e._def.innerType;t[r]=e}return new J({...this._def,shape:()=>t})}keyof(){return de(o.util.objectKeys(this.shape))}}t.ZodObject=J,J.create=(e,t)=>new J({shape:()=>e,unknownKeys:"strip",catchall:q.create(),typeName:Ie.ZodObject,...u(t)}),J.strictCreate=(e,t)=>new J({shape:()=>e,unknownKeys:"strict",catchall:q.create(),typeName:Ie.ZodObject,...u(t)}),J.lazycreate=(e,t)=>new J({shape:e,unknownKeys:"strip",catchall:q.create(),typeName:Ie.ZodObject,...u(t)});class X extends l{_parse(e){const{ctx:t}=this._processInputParams(e),r=this._def.options;if(t.common.async)return Promise.all(r.map(async e=>{const r={...t,common:{...t.common,issues:[]},parent:null};return{result:await e._parseAsync({data:t.data,path:t.path,parent:r}),ctx:r}})).then(function(e){for(const t of e)if("valid"===t.result.status)return t.result;for(const r of e)if("dirty"===r.result.status)return t.common.issues.push(...r.ctx.common.issues),r.result;const r=e.map(e=>new a.ZodError(e.ctx.common.issues));return(0,n.addIssueToContext)(t,{code:a.ZodIssueCode.invalid_union,unionErrors:r}),n.INVALID});{let e;const s=[];for(const a of r){const r={...t,common:{...t.common,issues:[]},parent:null},i=a._parseSync({data:t.data,path:t.path,parent:r});if("valid"===i.status)return i;"dirty"!==i.status||e||(e={result:i,ctx:r}),r.common.issues.length&&s.push(r.common.issues)}if(e)return t.common.issues.push(...e.ctx.common.issues),e.result;const i=s.map(e=>new a.ZodError(e));return(0,n.addIssueToContext)(t,{code:a.ZodIssueCode.invalid_union,unionErrors:i}),n.INVALID}}get options(){return this._def.options}}t.ZodUnion=X,X.create=(e,t)=>new X({options:e,typeName:Ie.ZodUnion,...u(t)});const Q=e=>e instanceof oe?Q(e.schema):e instanceof pe?Q(e.innerType()):e instanceof ce?[e.value]:e instanceof ue?e.options:e instanceof le?o.util.objectValues(e.enum):e instanceof ge?Q(e._def.innerType):e instanceof V?[void 0]:e instanceof K?[null]:e instanceof fe?[void 0,...Q(e.unwrap())]:e instanceof me?[null,...Q(e.unwrap())]:e instanceof _e||e instanceof be?Q(e.unwrap()):e instanceof ye?Q(e._def.innerType):[];class Y extends l{_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==o.ZodParsedType.object)return(0,n.addIssueToContext)(t,{code:a.ZodIssueCode.invalid_type,expected:o.ZodParsedType.object,received:t.parsedType}),n.INVALID;const r=this.discriminator,s=t.data[r],i=this.optionsMap.get(s);return i?t.common.async?i._parseAsync({data:t.data,path:t.path,parent:t}):i._parseSync({data:t.data,path:t.path,parent:t}):((0,n.addIssueToContext)(t,{code:a.ZodIssueCode.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),n.INVALID)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,t,r){const a=new Map;for(const r of t){const t=Q(r.shape[e]);if(!t.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(const s of t){if(a.has(s))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(s)}`);a.set(s,r)}}return new Y({typeName:Ie.ZodDiscriminatedUnion,discriminator:e,options:t,optionsMap:a,...u(r)})}}function ee(e,t){const r=(0,o.getParsedType)(e),a=(0,o.getParsedType)(t);if(e===t)return{valid:!0,data:e};if(r===o.ZodParsedType.object&&a===o.ZodParsedType.object){const r=o.util.objectKeys(t),a=o.util.objectKeys(e).filter(e=>-1!==r.indexOf(e)),s={...e,...t};for(const r of a){const a=ee(e[r],t[r]);if(!a.valid)return{valid:!1};s[r]=a.data}return{valid:!0,data:s}}if(r===o.ZodParsedType.array&&a===o.ZodParsedType.array){if(e.length!==t.length)return{valid:!1};const r=[];for(let a=0;a<e.length;a++){const s=ee(e[a],t[a]);if(!s.valid)return{valid:!1};r.push(s.data)}return{valid:!0,data:r}}return r===o.ZodParsedType.date&&a===o.ZodParsedType.date&&+e===+t?{valid:!0,data:e}:{valid:!1}}t.ZodDiscriminatedUnion=Y;class te extends l{_parse(e){const{status:t,ctx:r}=this._processInputParams(e),s=(e,s)=>{if((0,n.isAborted)(e)||(0,n.isAborted)(s))return n.INVALID;const i=ee(e.value,s.value);return i.valid?(((0,n.isDirty)(e)||(0,n.isDirty)(s))&&t.dirty(),{status:t.value,value:i.data}):((0,n.addIssueToContext)(r,{code:a.ZodIssueCode.invalid_intersection_types}),n.INVALID)};return r.common.async?Promise.all([this._def.left._parseAsync({data:r.data,path:r.path,parent:r}),this._def.right._parseAsync({data:r.data,path:r.path,parent:r})]).then(([e,t])=>s(e,t)):s(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}}t.ZodIntersection=te,te.create=(e,t,r)=>new te({left:e,right:t,typeName:Ie.ZodIntersection,...u(r)});class re extends l{_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==o.ZodParsedType.array)return(0,n.addIssueToContext)(r,{code:a.ZodIssueCode.invalid_type,expected:o.ZodParsedType.array,received:r.parsedType}),n.INVALID;if(r.data.length<this._def.items.length)return(0,n.addIssueToContext)(r,{code:a.ZodIssueCode.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),n.INVALID;!this._def.rest&&r.data.length>this._def.items.length&&((0,n.addIssueToContext)(r,{code:a.ZodIssueCode.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());const s=[...r.data].map((e,t)=>{const a=this._def.items[t]||this._def.rest;return a?a._parse(new c(r,e,r.path,t)):null}).filter(e=>!!e);return r.common.async?Promise.all(s).then(e=>n.ParseStatus.mergeArray(t,e)):n.ParseStatus.mergeArray(t,s)}get items(){return this._def.items}rest(e){return new re({...this._def,rest:e})}}t.ZodTuple=re,re.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new re({items:e,typeName:Ie.ZodTuple,rest:null,...u(t)})};class ae extends l{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==o.ZodParsedType.object)return(0,n.addIssueToContext)(r,{code:a.ZodIssueCode.invalid_type,expected:o.ZodParsedType.object,received:r.parsedType}),n.INVALID;const s=[],i=this._def.keyType,d=this._def.valueType;for(const e in r.data)s.push({key:i._parse(new c(r,e,r.path,e)),value:d._parse(new c(r,r.data[e],r.path,e)),alwaysSet:e in r.data});return r.common.async?n.ParseStatus.mergeObjectAsync(t,s):n.ParseStatus.mergeObjectSync(t,s)}get element(){return this._def.valueType}static create(e,t,r){return new ae(t instanceof l?{keyType:e,valueType:t,typeName:Ie.ZodRecord,...u(r)}:{keyType:j.create(),valueType:e,typeName:Ie.ZodRecord,...u(t)})}}t.ZodRecord=ae;class se extends l{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==o.ZodParsedType.map)return(0,n.addIssueToContext)(r,{code:a.ZodIssueCode.invalid_type,expected:o.ZodParsedType.map,received:r.parsedType}),n.INVALID;const s=this._def.keyType,i=this._def.valueType,d=[...r.data.entries()].map(([e,t],a)=>({key:s._parse(new c(r,e,r.path,[a,"key"])),value:i._parse(new c(r,t,r.path,[a,"value"]))}));if(r.common.async){const e=new Map;return Promise.resolve().then(async()=>{for(const r of d){const a=await r.key,s=await r.value;if("aborted"===a.status||"aborted"===s.status)return n.INVALID;"dirty"!==a.status&&"dirty"!==s.status||t.dirty(),e.set(a.value,s.value)}return{status:t.value,value:e}})}{const e=new Map;for(const r of d){const a=r.key,s=r.value;if("aborted"===a.status||"aborted"===s.status)return n.INVALID;"dirty"!==a.status&&"dirty"!==s.status||t.dirty(),e.set(a.value,s.value)}return{status:t.value,value:e}}}}t.ZodMap=se,se.create=(e,t,r)=>new se({valueType:t,keyType:e,typeName:Ie.ZodMap,...u(r)});class ie extends l{_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==o.ZodParsedType.set)return(0,n.addIssueToContext)(r,{code:a.ZodIssueCode.invalid_type,expected:o.ZodParsedType.set,received:r.parsedType}),n.INVALID;const s=this._def;null!==s.minSize&&r.data.size<s.minSize.value&&((0,n.addIssueToContext)(r,{code:a.ZodIssueCode.too_small,minimum:s.minSize.value,type:"set",inclusive:!0,exact:!1,message:s.minSize.message}),t.dirty()),null!==s.maxSize&&r.data.size>s.maxSize.value&&((0,n.addIssueToContext)(r,{code:a.ZodIssueCode.too_big,maximum:s.maxSize.value,type:"set",inclusive:!0,exact:!1,message:s.maxSize.message}),t.dirty());const i=this._def.valueType;function d(e){const r=new Set;for(const a of e){if("aborted"===a.status)return n.INVALID;"dirty"===a.status&&t.dirty(),r.add(a.value)}return{status:t.value,value:r}}const u=[...r.data.values()].map((e,t)=>i._parse(new c(r,e,r.path,t)));return r.common.async?Promise.all(u).then(e=>d(e)):d(u)}min(e,t){return new ie({...this._def,minSize:{value:e,message:i.errorUtil.toString(t)}})}max(e,t){return new ie({...this._def,maxSize:{value:e,message:i.errorUtil.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}}t.ZodSet=ie,ie.create=(e,t)=>new ie({valueType:e,minSize:null,maxSize:null,typeName:Ie.ZodSet,...u(t)});class ne extends l{constructor(){super(...arguments),this.validate=this.implement}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==o.ZodParsedType.function)return(0,n.addIssueToContext)(t,{code:a.ZodIssueCode.invalid_type,expected:o.ZodParsedType.function,received:t.parsedType}),n.INVALID;function r(e,r){return(0,n.makeIssue)({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,(0,s.getErrorMap)(),s.defaultErrorMap].filter(e=>!!e),issueData:{code:a.ZodIssueCode.invalid_arguments,argumentsError:r}})}function i(e,r){return(0,n.makeIssue)({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,(0,s.getErrorMap)(),s.defaultErrorMap].filter(e=>!!e),issueData:{code:a.ZodIssueCode.invalid_return_type,returnTypeError:r}})}const c={errorMap:t.common.contextualErrorMap},d=t.data;if(this._def.returns instanceof he){const e=this;return(0,n.OK)(async function(...t){const s=new a.ZodError([]),n=await e._def.args.parseAsync(t,c).catch(e=>{throw s.addIssue(r(t,e)),s}),o=await Reflect.apply(d,this,n);return await e._def.returns._def.type.parseAsync(o,c).catch(e=>{throw s.addIssue(i(o,e)),s})})}{const e=this;return(0,n.OK)(function(...t){const s=e._def.args.safeParse(t,c);if(!s.success)throw new a.ZodError([r(t,s.error)]);const n=Reflect.apply(d,this,s.data),o=e._def.returns.safeParse(n,c);if(!o.success)throw new a.ZodError([i(n,o.error)]);return o.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new ne({...this._def,args:re.create(e).rest(H.create())})}returns(e){return new ne({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,t,r){return new ne({args:e||re.create([]).rest(H.create()),returns:t||H.create(),typeName:Ie.ZodFunction,...u(r)})}}t.ZodFunction=ne;class oe extends l{get schema(){return this._def.getter()}_parse(e){const{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}}t.ZodLazy=oe,oe.create=(e,t)=>new oe({getter:e,typeName:Ie.ZodLazy,...u(t)});class ce extends l{_parse(e){if(e.data!==this._def.value){const t=this._getOrReturnCtx(e);return(0,n.addIssueToContext)(t,{received:t.data,code:a.ZodIssueCode.invalid_literal,expected:this._def.value}),n.INVALID}return{status:"valid",value:e.data}}get value(){return this._def.value}}function de(e,t){return new ue({values:e,typeName:Ie.ZodEnum,...u(t)})}t.ZodLiteral=ce,ce.create=(e,t)=>new ce({value:e,typeName:Ie.ZodLiteral,...u(t)});class ue extends l{_parse(e){if("string"!=typeof e.data){const t=this._getOrReturnCtx(e),r=this._def.values;return(0,n.addIssueToContext)(t,{expected:o.util.joinValues(r),received:t.parsedType,code:a.ZodIssueCode.invalid_type}),n.INVALID}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){const t=this._getOrReturnCtx(e),r=this._def.values;return(0,n.addIssueToContext)(t,{received:t.data,code:a.ZodIssueCode.invalid_enum_value,options:r}),n.INVALID}return(0,n.OK)(e.data)}get options(){return this._def.values}get enum(){const e={};for(const t of this._def.values)e[t]=t;return e}get Values(){const e={};for(const t of this._def.values)e[t]=t;return e}get Enum(){const e={};for(const t of this._def.values)e[t]=t;return e}extract(e,t=this._def){return ue.create(e,{...this._def,...t})}exclude(e,t=this._def){return ue.create(this.options.filter(t=>!e.includes(t)),{...this._def,...t})}}t.ZodEnum=ue,ue.create=de;class le extends l{_parse(e){const t=o.util.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(e);if(r.parsedType!==o.ZodParsedType.string&&r.parsedType!==o.ZodParsedType.number){const e=o.util.objectValues(t);return(0,n.addIssueToContext)(r,{expected:o.util.joinValues(e),received:r.parsedType,code:a.ZodIssueCode.invalid_type}),n.INVALID}if(this._cache||(this._cache=new Set(o.util.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){const e=o.util.objectValues(t);return(0,n.addIssueToContext)(r,{received:r.data,code:a.ZodIssueCode.invalid_enum_value,options:e}),n.INVALID}return(0,n.OK)(e.data)}get enum(){return this._def.values}}t.ZodNativeEnum=le,le.create=(e,t)=>new le({values:e,typeName:Ie.ZodNativeEnum,...u(t)});class he extends l{unwrap(){return this._def.type}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==o.ZodParsedType.promise&&!1===t.common.async)return(0,n.addIssueToContext)(t,{code:a.ZodIssueCode.invalid_type,expected:o.ZodParsedType.promise,received:t.parsedType}),n.INVALID;const r=t.parsedType===o.ZodParsedType.promise?t.data:Promise.resolve(t.data);return(0,n.OK)(r.then(e=>this._def.type.parseAsync(e,{path:t.path,errorMap:t.common.contextualErrorMap})))}}t.ZodPromise=he,he.create=(e,t)=>new he({type:e,typeName:Ie.ZodPromise,...u(t)});class pe extends l{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===Ie.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){const{status:t,ctx:r}=this._processInputParams(e),a=this._def.effect||null,s={addIssue:e=>{(0,n.addIssueToContext)(r,e),e.fatal?t.abort():t.dirty()},get path(){return r.path}};if(s.addIssue=s.addIssue.bind(s),"preprocess"===a.type){const e=a.transform(r.data,s);if(r.common.async)return Promise.resolve(e).then(async e=>{if("aborted"===t.value)return n.INVALID;const a=await this._def.schema._parseAsync({data:e,path:r.path,parent:r});return"aborted"===a.status?n.INVALID:"dirty"===a.status||"dirty"===t.value?(0,n.DIRTY)(a.value):a});{if("aborted"===t.value)return n.INVALID;const a=this._def.schema._parseSync({data:e,path:r.path,parent:r});return"aborted"===a.status?n.INVALID:"dirty"===a.status||"dirty"===t.value?(0,n.DIRTY)(a.value):a}}if("refinement"===a.type){const e=e=>{const t=a.refinement(e,s);if(r.common.async)return Promise.resolve(t);if(t instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return e};if(!1===r.common.async){const a=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return"aborted"===a.status?n.INVALID:("dirty"===a.status&&t.dirty(),e(a.value),{status:t.value,value:a.value})}return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(r=>"aborted"===r.status?n.INVALID:("dirty"===r.status&&t.dirty(),e(r.value).then(()=>({status:t.value,value:r.value}))))}if("transform"===a.type){if(!1===r.common.async){const e=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!(0,n.isValid)(e))return n.INVALID;const i=a.transform(e.value,s);if(i instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:t.value,value:i}}return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(e=>(0,n.isValid)(e)?Promise.resolve(a.transform(e.value,s)).then(e=>({status:t.value,value:e})):n.INVALID)}o.util.assertNever(a)}}t.ZodEffects=pe,t.ZodTransformer=pe,pe.create=(e,t,r)=>new pe({schema:e,typeName:Ie.ZodEffects,effect:t,...u(r)}),pe.createWithPreprocess=(e,t,r)=>new pe({schema:t,effect:{type:"preprocess",transform:e},typeName:Ie.ZodEffects,...u(r)});class fe extends l{_parse(e){return this._getType(e)===o.ZodParsedType.undefined?(0,n.OK)(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}t.ZodOptional=fe,fe.create=(e,t)=>new fe({innerType:e,typeName:Ie.ZodOptional,...u(t)});class me extends l{_parse(e){return this._getType(e)===o.ZodParsedType.null?(0,n.OK)(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}t.ZodNullable=me,me.create=(e,t)=>new me({innerType:e,typeName:Ie.ZodNullable,...u(t)});class ge extends l{_parse(e){const{ctx:t}=this._processInputParams(e);let r=t.data;return t.parsedType===o.ZodParsedType.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:t.path,parent:t})}removeDefault(){return this._def.innerType}}t.ZodDefault=ge,ge.create=(e,t)=>new ge({innerType:e,typeName:Ie.ZodDefault,defaultValue:"function"==typeof t.default?t.default:()=>t.default,...u(t)});class ye extends l{_parse(e){const{ctx:t}=this._processInputParams(e),r={...t,common:{...t.common,issues:[]}},s=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return(0,n.isAsync)(s)?s.then(e=>({status:"valid",value:"valid"===e.status?e.value:this._def.catchValue({get error(){return new a.ZodError(r.common.issues)},input:r.data})})):{status:"valid",value:"valid"===s.status?s.value:this._def.catchValue({get error(){return new a.ZodError(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}}t.ZodCatch=ye,ye.create=(e,t)=>new ye({innerType:e,typeName:Ie.ZodCatch,catchValue:"function"==typeof t.catch?t.catch:()=>t.catch,...u(t)});class ve extends l{_parse(e){if(this._getType(e)!==o.ZodParsedType.nan){const t=this._getOrReturnCtx(e);return(0,n.addIssueToContext)(t,{code:a.ZodIssueCode.invalid_type,expected:o.ZodParsedType.nan,received:t.parsedType}),n.INVALID}return{status:"valid",value:e.data}}}t.ZodNaN=ve,ve.create=e=>new ve({typeName:Ie.ZodNaN,...u(e)}),t.BRAND=Symbol("zod_brand");class _e extends l{_parse(e){const{ctx:t}=this._processInputParams(e),r=t.data;return this._def.type._parse({data:r,path:t.path,parent:t})}unwrap(){return this._def.type}}t.ZodBranded=_e;class Se extends l{_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.common.async)return(async()=>{const e=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return"aborted"===e.status?n.INVALID:"dirty"===e.status?(t.dirty(),(0,n.DIRTY)(e.value)):this._def.out._parseAsync({data:e.value,path:r.path,parent:r})})();{const e=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return"aborted"===e.status?n.INVALID:"dirty"===e.status?(t.dirty(),{status:"dirty",value:e.value}):this._def.out._parseSync({data:e.value,path:r.path,parent:r})}}static create(e,t){return new Se({in:e,out:t,typeName:Ie.ZodPipeline})}}t.ZodPipeline=Se;class be extends l{_parse(e){const t=this._def.innerType._parse(e),r=e=>((0,n.isValid)(e)&&(e.value=Object.freeze(e.value)),e);return(0,n.isAsync)(t)?t.then(e=>r(e)):r(t)}unwrap(){return this._def.innerType}}function Ee(e,t){const r="function"==typeof e?e(t):"string"==typeof e?{message:e}:e;return"string"==typeof r?{message:r}:r}function Pe(e,t={},r){return e?U.create().superRefine((a,s)=>{const i=e(a);if(i instanceof Promise)return i.then(e=>{if(!e){const e=Ee(t,a),i=e.fatal??r??!0;s.addIssue({code:"custom",...e,fatal:i})}});if(!i){const e=Ee(t,a),i=e.fatal??r??!0;s.addIssue({code:"custom",...e,fatal:i})}}):U.create()}var Ie;t.ZodReadonly=be,be.create=(e,t)=>new be({innerType:e,typeName:Ie.ZodReadonly,...u(t)}),t.late={object:J.lazycreate},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"}(Ie||(t.ZodFirstPartyTypeKind=Ie={})),t.instanceof=(e,t={message:`Input not instance of ${e.name}`})=>Pe(t=>t instanceof e,t);const we=j.create;t.string=we;const Ce=$.create;t.number=Ce;const Te=ve.create;t.nan=Te;const De=M.create;t.bigint=De;const xe=L.create;t.boolean=xe;const Oe=F.create;t.date=Oe;const Ae=Z.create;t.symbol=Ae;const ke=V.create;t.undefined=ke;const Re=K.create;t.null=Re;const Ne=U.create;t.any=Ne;const je=H.create;t.unknown=je;const ze=q.create;t.never=ze;const $e=B.create;t.void=$e;const Me=W.create;t.array=Me;const Le=J.create;t.object=Le;const Fe=J.strictCreate;t.strictObject=Fe;const Ze=X.create;t.union=Ze;const Ve=Y.create;t.discriminatedUnion=Ve;const Ke=te.create;t.intersection=Ke;const Ue=re.create;t.tuple=Ue;const He=ae.create;t.record=He;const qe=se.create;t.map=qe;const Be=ie.create;t.set=Be;const We=ne.create;t.function=We;const Ge=oe.create;t.lazy=Ge;const Je=ce.create;t.literal=Je;const Xe=ue.create;t.enum=Xe;const Qe=le.create;t.nativeEnum=Qe;const Ye=he.create;t.promise=Ye;const et=pe.create;t.effect=et,t.transformer=et;const tt=fe.create;t.optional=tt;const rt=me.create;t.nullable=rt;const at=pe.createWithPreprocess;t.preprocess=at;const st=Se.create;t.pipeline=st,t.ostring=()=>we().optional(),t.onumber=()=>Ce().optional(),t.oboolean=()=>xe().optional(),t.coerce={string:e=>j.create({...e,coerce:!0}),number:e=>$.create({...e,coerce:!0}),boolean:e=>L.create({...e,coerce:!0}),bigint:e=>M.create({...e,coerce:!0}),date:e=>F.create({...e,coerce:!0})},t.NEVER=n.INVALID},44413:e=>{"use strict";e.exports=function(e,t,r){var a=" ",s=e.schema[t],i=e.errSchemaPath+"/"+t,n=(e.opts.allErrors,e.util.toQuotedString(s));return!0===e.opts.$comment?a+=" console.log("+n+");":"function"==typeof e.opts.$comment&&(a+=" self._opts.$comment("+n+", "+e.util.toQuotedString(i)+", validate.root.schema);"),a}},46079:e=>{"use strict";var t=["multipleOf","maximum","exclusiveMaximum","minimum","exclusiveMinimum","maxLength","minLength","pattern","additionalItems","maxItems","minItems","uniqueItems","maxProperties","minProperties","required","additionalProperties","enum","format","const"];e.exports=function(e,r){for(var a=0;a<r.length;a++){e=JSON.parse(JSON.stringify(e));var s,i=r[a].split("/"),n=e;for(s=1;s<i.length;s++)n=n[i[s]];for(s=0;s<t.length;s++){var o=t[s],c=n[o];c&&(n[o]={anyOf:[c,{$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"}]})}}return e}},46137:e=>{"use strict";e.exports=function(e,t,r){var a=" ",s=e.level,i=e.dataLevel,n=e.schema[t],o=e.schemaPath+e.util.getProperty(t),c=e.errSchemaPath+"/"+t,d=!e.opts.allErrors,u="data"+(i||""),l="valid"+s,h="errs__"+s,p=e.util.copy(e),f="";p.level++;var m="valid"+p.level,g=p.baseId,y="prevValid"+s,v="passingSchemas"+s;a+="var "+h+" = errors , "+y+" = false , "+l+" = false , "+v+" = null; ";var _=e.compositeRule;e.compositeRule=p.compositeRule=!0;var S=n;if(S)for(var b,E=-1,P=S.length-1;E<P;)b=S[E+=1],(e.opts.strictKeywords?"object"==typeof b&&Object.keys(b).length>0||!1===b:e.util.schemaHasRules(b,e.RULES.all))?(p.schema=b,p.schemaPath=o+"["+E+"]",p.errSchemaPath=c+"/"+E,a+=" "+e.validate(p)+" ",p.baseId=g):a+=" var "+m+" = true; ",E&&(a+=" if ("+m+" && "+y+") { "+l+" = false; "+v+" = ["+v+", "+E+"]; } else { ",f+="}"),a+=" if ("+m+") { "+l+" = "+y+" = true; "+v+" = "+E+"; }";return e.compositeRule=p.compositeRule=_,a+=f+"if (!"+l+") { var err = ",!1!==e.createErrors?(a+=" { keyword: 'oneOf' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { passingSchemas: "+v+" } ",!1!==e.opts.messages&&(a+=" , message: 'should match exactly one schema in oneOf' "),e.opts.verbose&&(a+=" , schema: validate.schema"+o+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+u+" "),a+=" } "):a+=" {} ",a+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",!e.compositeRule&&d&&(e.async?a+=" throw new ValidationError(vErrors); ":a+=" validate.errors = vErrors; return false; "),a+="} else { errors = "+h+"; if (vErrors !== null) { if ("+h+") vErrors.length = "+h+"; else vErrors = null; }",e.opts.allErrors&&(a+=" } "),a}},46511:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.VerifiablePresentationSchema=t.VerifiableCredentialSchema=t.ProofSchema=t.CredentialStatusSchema=t.CredentialSubjectSchema=t.IssuerSchema=t.ContextSchema=t.ContextEntrySchema=t.STATUS_LIST_CONTEXT=t.VC_CONTEXT=void 0,t.validateVerifiableCredential=function(e){return t.VerifiableCredentialSchema.safeParse(e)},t.validateVerifiablePresentation=function(e){return t.VerifiablePresentationSchema.safeParse(e)},t.isCredentialExpired=function(e){if(!e.expirationDate)return!1;try{return new Date(e.expirationDate)<new Date}catch{return!1}},t.getIssuerDid=function(e){const t=e.issuer;return"string"==typeof t?t:t.id},t.getSubjectDid=function(e){const t=Array.isArray(e.credentialSubject)?e.credentialSubject[0]:e.credentialSubject;return t?.id||null};const a=r(90315);t.VC_CONTEXT=["https://www.w3.org/2018/credentials/v1"],t.STATUS_LIST_CONTEXT="https://w3id.org/vc/status-list/2021/v1",t.ContextEntrySchema=a.z.union([a.z.string().url(),a.z.record(a.z.any())]),t.ContextSchema=a.z.array(t.ContextEntrySchema).nonempty().refine(e=>{const r=e[0];return"string"==typeof r&&r===t.VC_CONTEXT[0]},{message:'First @context must be "https://www.w3.org/2018/credentials/v1"'}),t.IssuerSchema=a.z.union([a.z.string().min(1),a.z.object({id:a.z.string().min(1)}).passthrough()]),t.CredentialSubjectSchema=a.z.union([a.z.record(a.z.any()),a.z.array(a.z.record(a.z.any()))]),t.CredentialStatusSchema=a.z.object({id:a.z.string().url(),type:a.z.literal("StatusList2021Entry"),statusPurpose:a.z.enum(["revocation","suspension"]),statusListIndex:a.z.string().regex(/^\d+$/,"Must be a numeric string"),statusListCredential:a.z.string().url()}),t.ProofSchema=a.z.object({type:a.z.string().min(1),created:a.z.string().optional(),verificationMethod:a.z.string().optional(),proofPurpose:a.z.string().optional()}).passthrough(),t.VerifiableCredentialSchema=a.z.object({"@context":t.ContextSchema,id:a.z.string().url().optional(),type:a.z.array(a.z.string()).min(1).refine(e=>e.includes("VerifiableCredential"),{message:'type must include "VerifiableCredential"'}),issuer:t.IssuerSchema,issuanceDate:a.z.string().datetime(),expirationDate:a.z.string().datetime().optional(),credentialSubject:t.CredentialSubjectSchema,credentialStatus:t.CredentialStatusSchema.optional(),proof:t.ProofSchema.optional()}).passthrough(),t.VerifiablePresentationSchema=a.z.object({"@context":t.ContextSchema,id:a.z.string().url().optional(),type:a.z.array(a.z.string()).min(1).refine(e=>e.includes("VerifiablePresentation"),{message:'type must include "VerifiablePresentation"'}),holder:a.z.string().min(1).optional(),verifiableCredential:a.z.union([t.VerifiableCredentialSchema,a.z.array(t.VerifiableCredentialSchema)]).optional(),proof:t.ProofSchema.optional()}).passthrough()},49351:function(e,t,r){"use strict";var a=this&&this.__createBinding||(Object.create?function(e,t,r,a){void 0===a&&(a=r);var s=Object.getOwnPropertyDescriptor(t,r);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,a,s)}:function(e,t,r,a){void 0===a&&(a=r),e[a]=t[r]}),s=this&&this.__exportStar||function(e,t){for(var r in e)"default"===r||Object.prototype.hasOwnProperty.call(t,r)||a(t,e,r)};Object.defineProperty(t,"__esModule",{value:!0}),t.SUPPORTED_XMCP_I_VERSION=t.CONTRACTS_VERSION=void 0,s(r(52894),t),s(r(19613),t),s(r(79885),t),s(r(90088),t),s(r(99529),t),s(r(79983),t),s(r(97354),t),s(r(86819),t),s(r(41094),t),t.CONTRACTS_VERSION="1.2.1",t.SUPPORTED_XMCP_I_VERSION="^1.0.0"},49436:e=>{function t(e){return Promise.resolve().then(()=>{var t=new Error("Cannot find module '"+e+"'");throw t.code="MODULE_NOT_FOUND",t})}t.keys=()=>[],t.resolve=t,t.id=49436,e.exports=t},51063:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AGENTSHIELD_METHODS=t.AGENTSHIELD_ENDPOINTS=t.AGENTSHIELD_API_BASE=void 0,t.AGENTSHIELD_API_BASE="/api/v1/bouncer",t.AGENTSHIELD_ENDPOINTS={PROOFS:`${t.AGENTSHIELD_API_BASE}/proofs`,DELEGATIONS_VERIFY:`${t.AGENTSHIELD_API_BASE}/delegations/verify`,DELEGATIONS_GET:e=>`${t.AGENTSHIELD_API_BASE}/delegations/${e}`,DELEGATIONS_CREATE:`${t.AGENTSHIELD_API_BASE}/delegations`,DELEGATIONS_REVOKE:e=>`${t.AGENTSHIELD_API_BASE}/delegations/${e}/revoke`,CONFIG:e=>`${t.AGENTSHIELD_API_BASE}/projects/${e}/config`},t.AGENTSHIELD_METHODS={PROOFS:"POST",DELEGATIONS_VERIFY:"POST",DELEGATIONS_GET:"GET",DELEGATIONS_CREATE:"POST",DELEGATIONS_REVOKE:"POST",CONFIG:"GET"}},51708:(e,t,r)=>{"use strict";r.r(t),r.d(t,{canonicalize:()=>a.d,canonicalizeEx:()=>i});var a=r(77753),s=r(10985);function i(e,t){return(0,s.S)(e,t)}},52004:(e,t,r)=>{"use strict";e.exports={$ref:r(12857),allOf:r(67578),anyOf:r(14547),$comment:r(44413),const:r(59087),contains:r(24235),dependencies:r(90083),enum:r(68307),format:r(95545),if:r(82917),items:r(33728),maximum:r(71346),minimum:r(71346),maxItems:r(80536),minItems:r(80536),maxLength:r(83010),minLength:r(83010),maxProperties:r(96111),minProperties:r(96111),multipleOf:r(58047),not:r(13441),oneOf:r(46137),pattern:r(96774),properties:r(86343),propertyNames:r(9931),required:r(91939),uniqueItems:r(57817),validate:r(25572)}},52894:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.NONCE_LENGTH_BYTES=t.DEFAULT_TIMESTAMP_SKEW_SECONDS=t.DEFAULT_SESSION_TTL_MINUTES=t.NonceCacheConfigSchema=t.NonceCacheEntrySchema=t.SessionContextSchema=t.HandshakeRequestSchema=void 0;const a=r(90315);t.HandshakeRequestSchema=a.z.object({nonce:a.z.string().min(1),audience:a.z.string().min(1),timestamp:a.z.number().int().positive(),agentDid:a.z.string().startsWith("did:").optional()}),t.SessionContextSchema=a.z.object({sessionId:a.z.string().min(1),audience:a.z.string().min(1),nonce:a.z.string().min(1),timestamp:a.z.number().int().positive(),createdAt:a.z.number().int().positive(),lastActivity:a.z.number().int().positive(),ttlMinutes:a.z.number().int().positive().default(30),agentDid:a.z.string().optional(),serverDid:a.z.string().min(1).optional(),clientDid:a.z.string().optional(),userDid:a.z.string().optional()}),t.NonceCacheEntrySchema=a.z.object({sessionId:a.z.string().min(1),expiresAt:a.z.number().int().positive()}),t.NonceCacheConfigSchema=a.z.object({type:a.z.enum(["memory","redis","dynamodb","cloudflare-kv"]).optional(),redis:a.z.object({url:a.z.string().url(),keyPrefix:a.z.string().default("mcpi:nonce:")}).optional(),dynamodb:a.z.object({tableName:a.z.string(),region:a.z.string().optional(),keyAttribute:a.z.string().default("nonce"),ttlAttribute:a.z.string().default("expiresAt")}).optional(),cloudflareKv:a.z.object({namespace:a.z.string(),keyPrefix:a.z.string().default("nonce:")}).optional()}),t.DEFAULT_SESSION_TTL_MINUTES=30,t.DEFAULT_TIMESTAMP_SKEW_SECONDS=120,t.NONCE_LENGTH_BYTES=16},53084:(e,t,r)=>{"use strict";var a=r(22853),s=r(40985),i=r(28565),n=r(20812),o=r(56039),c=r(36885),d=r(20698),u=r(46079),l=r(9717);e.exports=y,y.prototype.validate=function(e,t){var r;if("string"==typeof e){if(!(r=this.getSchema(e)))throw new Error('no schema with key or ref "'+e+'"')}else{var a=this._addSchema(e);r=a.validate||this._compile(a)}var s=r(t);return!0!==r.$async&&(this.errors=r.errors),s},y.prototype.compile=function(e,t){var r=this._addSchema(e,void 0,t);return r.validate||this._compile(r)},y.prototype.addSchema=function(e,t,r,a){if(Array.isArray(e)){for(var i=0;i<e.length;i++)this.addSchema(e[i],void 0,r,a);return this}var n=this._getId(e);if(void 0!==n&&"string"!=typeof n)throw new Error("schema id must be string");return P(this,t=s.normalizeId(t||n)),this._schemas[t]=this._addSchema(e,r,a,!0),this},y.prototype.addMetaSchema=function(e,t,r){return this.addSchema(e,t,r,!0),this},y.prototype.validateSchema=function(e,t){var r,a,s=e.$schema;if(void 0!==s&&"string"!=typeof s)throw new Error("$schema must be a string");if(!(s=s||this._opts.defaultMeta||(r=this,a=r._opts.meta,r._opts.defaultMeta="object"==typeof a?r._getId(a)||a:r.getSchema(f)?f:void 0,r._opts.defaultMeta)))return this.logger.warn("meta-schema not available"),this.errors=null,!0;var i=this.validate(s,e);if(!i&&t){var n="schema is invalid: "+this.errorsText();if("log"!=this._opts.validateSchema)throw new Error(n);this.logger.error(n)}return i},y.prototype.getSchema=function(e){var t=v(this,e);switch(typeof t){case"object":return t.validate||this._compile(t);case"string":return this.getSchema(t);case"undefined":return function(e,t){var r=s.schema.call(e,{schema:{}},t);if(r){var i=r.schema,o=r.root,c=r.baseId,d=a.call(e,i,o,void 0,c);return e._fragments[t]=new n({ref:t,fragment:!0,schema:i,root:o,baseId:c,validate:d}),d}}(this,e)}},y.prototype.removeSchema=function(e){if(e instanceof RegExp)return _(this,this._schemas,e),_(this,this._refs,e),this;switch(typeof e){case"undefined":return _(this,this._schemas),_(this,this._refs),this._cache.clear(),this;case"string":var t=v(this,e);return t&&this._cache.del(t.cacheKey),delete this._schemas[e],delete this._refs[e],this;case"object":var r=this._opts.serialize,a=r?r(e):e;this._cache.del(a);var i=this._getId(e);i&&(i=s.normalizeId(i),delete this._schemas[i],delete this._refs[i])}return this},y.prototype.addFormat=function(e,t){return"string"==typeof t&&(t=new RegExp(t)),this._formats[e]=t,this},y.prototype.errorsText=function(e,t){if(!(e=e||this.errors))return"No errors";for(var r=void 0===(t=t||{}).separator?", ":t.separator,a=void 0===t.dataVar?"data":t.dataVar,s="",i=0;i<e.length;i++){var n=e[i];n&&(s+=a+n.dataPath+" "+n.message+r)}return s.slice(0,-r.length)},y.prototype._addSchema=function(e,t,r,a){if("object"!=typeof e&&"boolean"!=typeof e)throw new Error("schema should be object or boolean");var i=this._opts.serialize,o=i?i(e):e,c=this._cache.get(o);if(c)return c;a=a||!1!==this._opts.addUsedSchema;var d=s.normalizeId(this._getId(e));d&&a&&P(this,d);var u,l=!1!==this._opts.validateSchema&&!t;l&&!(u=d&&d==s.normalizeId(e.$schema))&&this.validateSchema(e,!0);var h=s.ids.call(this,e),p=new n({id:d,schema:e,localRefs:h,cacheKey:o,meta:r});return"#"!=d[0]&&a&&(this._refs[d]=p),this._cache.put(o,p),l&&u&&this.validateSchema(e,!0),p},y.prototype._compile=function(e,t){if(e.compiling)return e.validate=i,i.schema=e.schema,i.errors=null,i.root=t||i,!0===e.schema.$async&&(i.$async=!0),i;var r,s;e.compiling=!0,e.meta&&(r=this._opts,this._opts=this._metaOpts);try{s=a.call(this,e.schema,t,e.localRefs)}catch(t){throw delete e.validate,t}finally{e.compiling=!1,e.meta&&(this._opts=r)}return e.validate=s,e.refs=s.refs,e.refVal=s.refVal,e.root=s.root,s;function i(){var t=e.validate,r=t.apply(this,arguments);return i.errors=t.errors,r}},y.prototype.compileAsync=r(6069);var h=r(43528);y.prototype.addKeyword=h.add,y.prototype.getKeyword=h.get,y.prototype.removeKeyword=h.remove,y.prototype.validateKeyword=h.validate;var p=r(72916);y.ValidationError=p.Validation,y.MissingRefError=p.MissingRef,y.$dataMetaSchema=u;var f="http://json-schema.org/draft-07/schema",m=["removeAdditional","useDefaults","coerceTypes","strictDefaults"],g=["/properties"];function y(e){if(!(this instanceof y))return new y(e);e=this._opts=l.copy(e)||{},function(e){var t=e._opts.logger;if(!1===t)e.logger={log:I,warn:I,error:I};else{if(void 0===t&&(t=console),!("object"==typeof t&&t.log&&t.warn&&t.error))throw new Error("logger must implement log, warn and error methods");e.logger=t}}(this),this._schemas={},this._refs={},this._fragments={},this._formats=c(e.format),this._cache=e.cache||new i,this._loadingSchemas={},this._compilations=[],this.RULES=d(),this._getId=function(e){switch(e.schemaId){case"auto":return E;case"id":return S;default:return b}}(e),e.loopRequired=e.loopRequired||1/0,"property"==e.errorDataPath&&(e._errorDataPathProperty=!0),void 0===e.serialize&&(e.serialize=o),this._metaOpts=function(e){for(var t=l.copy(e._opts),r=0;r<m.length;r++)delete t[m[r]];return t}(this),e.formats&&function(e){for(var t in e._opts.formats){var r=e._opts.formats[t];e.addFormat(t,r)}}(this),e.keywords&&function(e){for(var t in e._opts.keywords){var r=e._opts.keywords[t];e.addKeyword(t,r)}}(this),function(e){var t;if(e._opts.$data&&(t=r(13215),e.addMetaSchema(t,t.$id,!0)),!1!==e._opts.meta){var a=r(12269);e._opts.$data&&(a=u(a,g)),e.addMetaSchema(a,f,!0),e._refs["http://json-schema.org/schema"]=f}}(this),"object"==typeof e.meta&&this.addMetaSchema(e.meta),e.nullable&&this.addKeyword("nullable",{metaSchema:{type:"boolean"}}),function(e){var t=e._opts.schemas;if(t)if(Array.isArray(t))e.addSchema(t);else for(var r in t)e.addSchema(t[r],r)}(this)}function v(e,t){return t=s.normalizeId(t),e._schemas[t]||e._refs[t]||e._fragments[t]}function _(e,t,r){for(var a in t){var s=t[a];s.meta||r&&!r.test(a)||(e._cache.del(s.cacheKey),delete t[a])}}function S(e){return e.$id&&this.logger.warn("schema $id ignored",e.$id),e.id}function b(e){return e.id&&this.logger.warn("schema id ignored",e.id),e.$id}function E(e){if(e.$id&&e.id&&e.$id!=e.id)throw new Error("schema $id is different from id");return e.$id||e.id}function P(e,t){if(e._schemas[t]||e._refs[t])throw new Error('schema with key or id "'+t+'" already exists')}function I(){}},55924:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.fetchRemoteConfig=async function(e,t){const{apiUrl:r,apiKey:s,projectId:i,agentDid:n,cacheTtl:o=3e5,fetchProvider:c}=e,d=i?`config:project:${i}`:n?`config:agent:${n}`:null;if(t&&d)try{const e=await t.get(d);if(e)try{const t=JSON.parse(e);if(t.expiresAt>Date.now())return t.config}catch{}}catch(e){console.warn("[RemoteConfig] Cache read failed:",e)}try{let e;if(i)e=`${r}${a.AGENTSHIELD_ENDPOINTS.CONFIG(i)}`;else{if(!n)return console.warn("[RemoteConfig] Neither projectId nor agentDid provided"),null;e=`${r}/api/v1/bouncer/config?agent_did=${encodeURIComponent(n)}`}const u=await c(e,{headers:{Authorization:`Bearer ${s}`,"Content-Type":"application/json"}});if(!u.ok)return console.warn(`[RemoteConfig] API returned ${u.status}: ${u.statusText}`),null;const l=await u.json(),h=l.config||l.data?.config||(l.success?l.data:null);if(!h)return console.warn("[RemoteConfig] No config found in API response"),null;if(t&&d)try{await t.set(d,JSON.stringify({config:h,expiresAt:Date.now()+o}),o)}catch(e){console.warn("[RemoteConfig] Cache write failed:",e)}return h}catch(e){return console.warn("[RemoteConfig] Failed to fetch config:",e),null}};const a=r(90533)},55957:(e,t)=>{"use strict";var r;Object.defineProperty(t,"__esModule",{value:!0}),t.errorUtil=void 0,function(e){e.errToObj=e=>"string"==typeof e?{message:e}:e||{},e.toString=e=>"string"==typeof e?e:e?.message}(r||(t.errorUtil=r={}))},56039:e=>{"use strict";e.exports=function(e,t){t||(t={}),"function"==typeof t&&(t={cmp:t});var r,a="boolean"==typeof t.cycles&&t.cycles,s=t.cmp&&(r=t.cmp,function(e){return function(t,a){var s={key:t,value:e[t]},i={key:a,value:e[a]};return r(s,i)}}),i=[];return function e(t){if(t&&t.toJSON&&"function"==typeof t.toJSON&&(t=t.toJSON()),void 0!==t){if("number"==typeof t)return isFinite(t)?""+t:"null";if("object"!=typeof t)return JSON.stringify(t);var r,n;if(Array.isArray(t)){for(n="[",r=0;r<t.length;r++)r&&(n+=","),n+=e(t[r])||"null";return n+"]"}if(null===t)return"null";if(-1!==i.indexOf(t)){if(a)return JSON.stringify("__cycle__");throw new TypeError("Converting circular structure to JSON")}var o=i.push(t)-1,c=Object.keys(t).sort(s&&s(t));for(n="",r=0;r<c.length;r++){var d=c[r],u=e(t[d]);u&&(n&&(n+=","),n+=JSON.stringify(d)+":"+u)}return i.splice(o,1),"{"+n+"}"}}(e)}},56392:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.fetchRemoteConfig=t.ProviderRuntimeConfigBuilder=void 0,t.createProviderRuntimeConfig=function(e,t){return(new a).withProviders(e).withEnvironment(t?.environment||"development").withSession(t?.session||{}).withIdentity(t?.identity||{enabled:!1,environment:"development"}).withProofing(t?.proofing||{enabled:!1}).withDelegation(t?.delegation||{enabled:!1,verifier:{type:"memory"}}).withAudit(t?.audit||{enabled:!1}).withWellKnown(t?.wellKnown||{enabled:!0}).build()};class a{config={environment:"development"};withProviders(e){return Object.assign(this.config,e),this}withEnvironment(e){return this.config.environment=e,this}withSession(e){return this.config.session=e,this}withIdentity(e){return this.config.identity=e,this}withProofing(e){return this.config.proofing=e,this}withDelegation(e){return this.config.delegation=e,this}withToolProtectionService(e){return this.config.toolProtectionService=e,this}withToolProtection(e){return this.config.toolProtection=e,this}withAudit(e){return this.config.audit=e,this}withWellKnown(e){return this.config.wellKnown=e,this}build(){const e=["cryptoProvider","clockProvider","fetchProvider","storageProvider","nonceCacheProvider","identityProvider"];for(const t of e)if(!(t in this.config))throw new Error(`Missing required provider: ${t}`);return{environment:"development",session:{timestampSkewSeconds:120,ttlMinutes:30},...this.config}}}t.ProviderRuntimeConfigBuilder=a;var s=r(55924);Object.defineProperty(t,"fetchRemoteConfig",{enumerable:!0,get:function(){return s.fetchRemoteConfig}})},57817:e=>{"use strict";e.exports=function(e,t,r){var a,s=" ",i=e.level,n=e.dataLevel,o=e.schema[t],c=e.schemaPath+e.util.getProperty(t),d=e.errSchemaPath+"/"+t,u=!e.opts.allErrors,l="data"+(n||""),h="valid"+i,p=e.opts.$data&&o&&o.$data;if(p?(s+=" var schema"+i+" = "+e.util.getData(o.$data,n,e.dataPathArr)+"; ",a="schema"+i):a=o,(o||p)&&!1!==e.opts.uniqueItems){p&&(s+=" var "+h+"; if ("+a+" === false || "+a+" === undefined) "+h+" = true; else if (typeof "+a+" != 'boolean') "+h+" = false; else { "),s+=" var i = "+l+".length , "+h+" = true , j; if (i > 1) { ";var f=e.schema.items&&e.schema.items.type,m=Array.isArray(f);if(!f||"object"==f||"array"==f||m&&(f.indexOf("object")>=0||f.indexOf("array")>=0))s+=" outer: for (;i--;) { for (j = i; j--;) { if (equal("+l+"[i], "+l+"[j])) { "+h+" = false; break outer; } } } ";else{s+=" var itemIndices = {}, item; for (;i--;) { var item = "+l+"[i]; ";var g="checkDataType"+(m?"s":"");s+=" if ("+e.util[g](f,"item",e.opts.strictNumbers,!0)+") continue; ",m&&(s+=" if (typeof item == 'string') item = '\"' + item; "),s+=" if (typeof itemIndices[item] == 'number') { "+h+" = false; j = itemIndices[item]; break; } itemIndices[item] = i; } "}s+=" } ",p&&(s+=" } "),s+=" if (!"+h+") { ";var y=y||[];y.push(s),s="",!1!==e.createErrors?(s+=" { keyword: 'uniqueItems' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(d)+" , params: { i: i, j: j } ",!1!==e.opts.messages&&(s+=" , message: 'should NOT have duplicate items (items ## ' + j + ' and ' + i + ' are identical)' "),e.opts.verbose&&(s+=" , schema: ",s+=p?"validate.schema"+c:""+o,s+=" , parentSchema: validate.schema"+e.schemaPath+" , data: "+l+" "),s+=" } "):s+=" {} ";var v=s;s=y.pop(),!e.compositeRule&&u?e.async?s+=" throw new ValidationError(["+v+"]); ":s+=" validate.errors = ["+v+"]; return false; ":s+=" var err = "+v+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",s+=" } ",u&&(s+=" else { ")}else u&&(s+=" if (true) { ");return s}},58047:e=>{"use strict";e.exports=function(e,t,r){var a,s=" ",i=e.level,n=e.dataLevel,o=e.schema[t],c=e.schemaPath+e.util.getProperty(t),d=e.errSchemaPath+"/"+t,u=!e.opts.allErrors,l="data"+(n||""),h=e.opts.$data&&o&&o.$data;if(h?(s+=" var schema"+i+" = "+e.util.getData(o.$data,n,e.dataPathArr)+"; ",a="schema"+i):a=o,!h&&"number"!=typeof o)throw new Error(t+" must be number");s+="var division"+i+";if (",h&&(s+=" "+a+" !== undefined && ( typeof "+a+" != 'number' || "),s+=" (division"+i+" = "+l+" / "+a+", ",e.opts.multipleOfPrecision?s+=" Math.abs(Math.round(division"+i+") - division"+i+") > 1e-"+e.opts.multipleOfPrecision+" ":s+=" division"+i+" !== parseInt(division"+i+") ",s+=" ) ",h&&(s+=" ) "),s+=" ) { ";var p=p||[];p.push(s),s="",!1!==e.createErrors?(s+=" { keyword: 'multipleOf' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(d)+" , params: { multipleOf: "+a+" } ",!1!==e.opts.messages&&(s+=" , message: 'should be multiple of ",s+=h?"' + "+a:a+"'"),e.opts.verbose&&(s+=" , schema: ",s+=h?"validate.schema"+c:""+o,s+=" , parentSchema: validate.schema"+e.schemaPath+" , data: "+l+" "),s+=" } "):s+=" {} ";var f=s;return s=p.pop(),!e.compositeRule&&u?e.async?s+=" throw new ValidationError(["+f+"]); ":s+=" validate.errors = ["+f+"]; return false; ":s+=" var err = "+f+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",s+="} ",u&&(s+=" else { "),s}},59087:e=>{"use strict";e.exports=function(e,t,r){var a=" ",s=e.level,i=e.dataLevel,n=e.schema[t],o=e.schemaPath+e.util.getProperty(t),c=e.errSchemaPath+"/"+t,d=!e.opts.allErrors,u="data"+(i||""),l="valid"+s,h=e.opts.$data&&n&&n.$data;h&&(a+=" var schema"+s+" = "+e.util.getData(n.$data,i,e.dataPathArr)+"; "),h||(a+=" var schema"+s+" = validate.schema"+o+";"),a+="var "+l+" = equal("+u+", schema"+s+"); if (!"+l+") { ";var p=p||[];p.push(a),a="",!1!==e.createErrors?(a+=" { keyword: 'const' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { allowedValue: schema"+s+" } ",!1!==e.opts.messages&&(a+=" , message: 'should be equal to constant' "),e.opts.verbose&&(a+=" , schema: validate.schema"+o+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+u+" "),a+=" } "):a+=" {} ";var f=a;return a=p.pop(),!e.compositeRule&&d?e.async?a+=" throw new ValidationError(["+f+"]); ":a+=" validate.errors = ["+f+"]; return false; ":a+=" var err = "+f+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",a+=" }",d&&(a+=" else { "),a}},59236:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.NoOpToolProtectionCache=t.InMemoryToolProtectionCache=void 0,t.InMemoryToolProtectionCache=class{cache=new Map;async get(e){const t=this.cache.get(e);return t?Date.now()>t.expiresAt?(this.cache.delete(e),null):t.value:null}async set(e,t,r){if(r<=0)return;const a=Date.now()+r;this.cache.set(e,{value:t,expiresAt:a})}async clear(){this.cache.clear()}async delete(e){this.cache.delete(e)}cleanup(){const e=Date.now();for(const[t,r]of this.cache.entries())e>r.expiresAt&&this.cache.delete(t)}getStale(e){const t=this.cache.get(e);return t?t.value:null}getExpiresAt(e){const t=this.cache.get(e);return t?t.expiresAt:null}},t.NoOpToolProtectionCache=class{async get(e){return null}async set(e,t,r){}async clear(){}async delete(e){}}},61763:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0})},61812:e=>{"use strict";e.exports=function(e){for(var t,r=0,a=e.length,s=0;s<a;)r++,(t=e.charCodeAt(s++))>=55296&&t<=56319&&s<a&&56320==(64512&(t=e.charCodeAt(s)))&&s++;return r}},62846:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ProofVerificationError=t.PROOF_VERIFICATION_ERROR_CODES=void 0,t.createProofVerificationError=function(e,t,a){return new r(e,t,a)},t.PROOF_VERIFICATION_ERROR_CODES={INVALID_PROOF_STRUCTURE:"INVALID_PROOF_STRUCTURE",MISSING_REQUIRED_FIELD:"MISSING_REQUIRED_FIELD",NONCE_REPLAY_DETECTED:"NONCE_REPLAY_DETECTED",TIMESTAMP_SKEW_EXCEEDED:"TIMESTAMP_SKEW_EXCEEDED",TIMESTAMP_INVALID:"TIMESTAMP_INVALID",INVALID_JWS_SIGNATURE:"INVALID_JWS_SIGNATURE",INVALID_JWS_FORMAT:"INVALID_JWS_FORMAT",INVALID_JWS_HEADER:"INVALID_JWS_HEADER",INVALID_JWS_PAYLOAD:"INVALID_JWS_PAYLOAD",INVALID_JWS_SIGNATURE_BASE64:"INVALID_JWS_SIGNATURE_BASE64",UNSUPPORTED_ALGORITHM:"UNSUPPORTED_ALGORITHM",INVALID_JWK_FORMAT:"INVALID_JWK_FORMAT",INVALID_JWK_KTY:"INVALID_JWK_KTY",INVALID_JWK_CRV:"INVALID_JWK_CRV",INVALID_JWK_X_FIELD:"INVALID_JWK_X_FIELD",INVALID_JWK_KEY_LENGTH:"INVALID_JWK_KEY_LENGTH",JWK_KID_MISMATCH:"JWK_KID_MISMATCH",DID_RESOLUTION_FAILED:"DID_RESOLUTION_FAILED",DID_DOCUMENT_NOT_FOUND:"DID_DOCUMENT_NOT_FOUND",VERIFICATION_METHOD_NOT_FOUND:"VERIFICATION_METHOD_NOT_FOUND",PUBLIC_KEY_NOT_FOUND:"PUBLIC_KEY_NOT_FOUND",UNSUPPORTED_DID_METHOD:"UNSUPPORTED_DID_METHOD",VERIFICATION_ERROR:"VERIFICATION_ERROR",INTERNAL_ERROR:"INTERNAL_ERROR"};class r extends Error{code;details;constructor(e,t,r){super(t),this.code=e,this.details=r,this.name="ProofVerificationError"}}t.ProofVerificationError=r},63288:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ToolProtectionServiceError=t.DelegationRequiredError=void 0;class r extends Error{toolName;requiredScopes;consentUrl;resumeToken;interceptedCall;constructor(e,t,r,a,s){super(`Delegation required for tool "${e}"`),this.toolName=e,this.requiredScopes=t,this.consentUrl=r,this.name="DelegationRequiredError",this.interceptedCall=a,this.resumeToken=s}}t.DelegationRequiredError=r;class a extends Error{cause;constructor(e,t){super(e),this.cause=t,this.name="ToolProtectionServiceError"}}t.ToolProtectionServiceError=a},65652:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DelegationGraphManager=void 0,t.createDelegationGraph=function(e){return new r(e)};class r{storage;constructor(e){this.storage=e}async registerDelegation(e){const t={id:e.id,parentId:e.parentId,children:[],issuerDid:e.issuerDid,subjectDid:e.subjectDid,credentialStatusId:e.credentialStatusId};return await this.storage.setNode(t),e.parentId&&await this.addChildToParent(e.parentId,e.id),t}async addChildToParent(e,t){const r=await this.storage.getNode(e);if(!r)throw new Error(`Parent delegation not found: ${e}`);r.children.includes(t)||(r.children.push(t),await this.storage.setNode(r))}async getNode(e){return this.storage.getNode(e)}async getChildren(e){return this.storage.getChildren(e)}async getDescendants(e){return this.storage.getDescendants(e)}async getChain(e){return this.storage.getChain(e)}async isAncestor(e,t){return(await this.getChain(t)).some(t=>t.id===e)}async getDepth(e){return(await this.getChain(e)).length-1}async validateChain(e){const t=await this.getChain(e);if(0===t.length)return{valid:!1,reason:"Delegation not found"};for(let e=1;e<t.length;e++){const r=t[e-1],a=t[e];if(a.issuerDid!==r.subjectDid)return{valid:!1,reason:`Invalid chain: ${a.id} issued by ${a.issuerDid} but parent ${r.id} subject is ${r.subjectDid}`};if(a.parentId!==r.id)return{valid:!1,reason:`Invalid chain: ${a.id} parentId=${a.parentId} but actual parent is ${r.id}`}}return{valid:!0}}async removeDelegation(e){const t=await this.storage.getNode(e);if(t){if(t.parentId){const r=await this.storage.getNode(t.parentId);r&&(r.children=r.children.filter(t=>t!==e),await this.storage.setNode(r))}await this.storage.deleteNode(e)}}}t.DelegationGraphManager=r},67371:e=>{"use strict";e.exports=function e(t,r){if(t===r)return!0;if(t&&r&&"object"==typeof t&&"object"==typeof r){if(t.constructor!==r.constructor)return!1;var a,s,i;if(Array.isArray(t)){if((a=t.length)!=r.length)return!1;for(s=a;0!==s--;)if(!e(t[s],r[s]))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((a=(i=Object.keys(t)).length)!==Object.keys(r).length)return!1;for(s=a;0!==s--;)if(!Object.prototype.hasOwnProperty.call(r,i[s]))return!1;for(s=a;0!==s--;){var n=i[s];if(!e(t[n],r[n]))return!1}return!0}return t!=t&&r!=r}},67578:e=>{"use strict";e.exports=function(e,t,r){var a=" ",s=e.schema[t],i=e.schemaPath+e.util.getProperty(t),n=e.errSchemaPath+"/"+t,o=!e.opts.allErrors,c=e.util.copy(e),d="";c.level++;var u="valid"+c.level,l=c.baseId,h=!0,p=s;if(p)for(var f,m=-1,g=p.length-1;m<g;)f=p[m+=1],(e.opts.strictKeywords?"object"==typeof f&&Object.keys(f).length>0||!1===f:e.util.schemaHasRules(f,e.RULES.all))&&(h=!1,c.schema=f,c.schemaPath=i+"["+m+"]",c.errSchemaPath=n+"/"+m,a+=" "+e.validate(c)+" ",c.baseId=l,o&&(a+=" if ("+u+") { ",d+="}"));return o&&(a+=h?" if (true) { ":" "+d.slice(0,-1)+" "),a}},68307:e=>{"use strict";e.exports=function(e,t,r){var a=" ",s=e.level,i=e.dataLevel,n=e.schema[t],o=e.schemaPath+e.util.getProperty(t),c=e.errSchemaPath+"/"+t,d=!e.opts.allErrors,u="data"+(i||""),l="valid"+s,h=e.opts.$data&&n&&n.$data;h&&(a+=" var schema"+s+" = "+e.util.getData(n.$data,i,e.dataPathArr)+"; ");var p="i"+s,f="schema"+s;h||(a+=" var "+f+" = validate.schema"+o+";"),a+="var "+l+";",h&&(a+=" if (schema"+s+" === undefined) "+l+" = true; else if (!Array.isArray(schema"+s+")) "+l+" = false; else {"),a+=l+" = false;for (var "+p+"=0; "+p+"<"+f+".length; "+p+"++) if (equal("+u+", "+f+"["+p+"])) { "+l+" = true; break; }",h&&(a+=" } "),a+=" if (!"+l+") { ";var m=m||[];m.push(a),a="",!1!==e.createErrors?(a+=" { keyword: 'enum' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { allowedValues: schema"+s+" } ",!1!==e.opts.messages&&(a+=" , message: 'should be equal to one of the allowed values' "),e.opts.verbose&&(a+=" , schema: validate.schema"+o+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+u+" "),a+=" } "):a+=" {} ";var g=a;return a=m.pop(),!e.compositeRule&&d?e.async?a+=" throw new ValidationError(["+g+"]); ":a+=" validate.errors = ["+g+"]; return false; ":a+=" var err = "+g+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",a+=" }",d&&(a+=" else { "),a}},68820:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ZodError=t.quotelessJson=t.ZodIssueCode=void 0;const a=r(27165);t.ZodIssueCode=a.util.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),t.quotelessJson=e=>JSON.stringify(e,null,2).replace(/"([^"]+)":/g,"$1:");class s extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=e=>{this.issues=[...this.issues,e]},this.addIssues=(e=[])=>{this.issues=[...this.issues,...e]};const t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name="ZodError",this.issues=e}format(e){const t=e||function(e){return e.message},r={_errors:[]},a=e=>{for(const s of e.issues)if("invalid_union"===s.code)s.unionErrors.map(a);else if("invalid_return_type"===s.code)a(s.returnTypeError);else if("invalid_arguments"===s.code)a(s.argumentsError);else if(0===s.path.length)r._errors.push(t(s));else{let e=r,a=0;for(;a<s.path.length;){const r=s.path[a];a===s.path.length-1?(e[r]=e[r]||{_errors:[]},e[r]._errors.push(t(s))):e[r]=e[r]||{_errors:[]},e=e[r],a++}}};return a(this),r}static assert(e){if(!(e instanceof s))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,a.util.jsonStringifyReplacer,2)}get isEmpty(){return 0===this.issues.length}flatten(e=e=>e.message){const t={},r=[];for(const a of this.issues)if(a.path.length>0){const r=a.path[0];t[r]=t[r]||[],t[r].push(e(a))}else r.push(e(a));return{formErrors:r,fieldErrors:t}}get formErrors(){return this.flatten()}}t.ZodError=s,s.create=e=>new s(e)},69411:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SCHEMA_REGISTRY=void 0,t.getAllSchemas=function(){return t.SCHEMA_REGISTRY},t.getSchemasByCategory=function(e){const r={vc:["verifiable-credential","verifiable-presentation","statuslist2021-credential","statuslist2021-credential-subject"],delegation:["delegation-credential","delegation-record","delegation-constraints","delegation-chain","delegation-creation-request","delegation-verification-result"],handshake:["handshake-request","session-context","nonce-cache-config","nonce-cache-entry"],proof:["detached-proof","proof-meta","proof","proof-w3c","audit-record","canonical-hashes"],registry:["registration-input","registration-result","agent-status","claim-token","delegation-request","delegation-response","registry-delegation","mirror-status","receipt"],runtime:["authorization-display","needs-authorization-error","runtime-error"],cli:["register-output"],tlkrc:["rotation-chain","rotation-event"],verifier:["verify-page"],"well-known":["well-known-agent"]}[e]||[];return t.SCHEMA_REGISTRY.filter(e=>r.includes(e.id))},t.getSchemaById=function(e){return t.SCHEMA_REGISTRY.find(t=>t.id===e)},t.getCriticalSchemas=function(){const e=["verifiable-credential","statuslist2021-credential","delegation-credential","delegation-record","delegation-constraints","detached-proof","proof-meta","handshake-request","session-context","audit-record"];return t.SCHEMA_REGISTRY.filter(t=>e.includes(t.id))},t.getSchemaStats=function(){const e={},a={};for(const s of t.SCHEMA_REGISTRY){const t=s.url.replace(r+"/","").split("/")[0]||"unknown";e[t]=(e[t]||0)+1,a[s.version]=(a[s.version]||0)+1}return{total:t.SCHEMA_REGISTRY.length,byCategory:e,byVersion:a}};const r="https://schemas.kya-os.ai/xmcp-i";t.SCHEMA_REGISTRY=[{id:"verifiable-credential",url:`${r}/vc/verifiable-credential.v1.0.0.json`,version:"1.0.0",type:"VerifiableCredential",description:"W3C Verifiable Credential Data Model"},{id:"verifiable-presentation",url:`${r}/vc/verifiable-presentation.v1.0.0.json`,version:"1.0.0",type:"VerifiablePresentation",description:"W3C Verifiable Presentation"},{id:"statuslist2021-credential",url:`${r}/vc/statuslist-2021-credential.v1.0.0.json`,version:"1.0.0",type:"StatusList2021Credential",description:"StatusList2021 Credential for efficient revocation"},{id:"statuslist2021-credential-subject",url:`${r}/vc/statuslist-2021-credential-subject.v1.0.0.json`,version:"1.0.0",type:"StatusList2021CredentialSubject",description:"StatusList2021 Credential Subject"},{id:"delegation-credential",url:`${r}/credentials/delegation/v1.0.0.json`,version:"1.0.0",type:"DelegationCredential",description:"W3C VC-based delegation credential"},{id:"delegation-record",url:`${r}/delegation/delegation-record.v1.0.0.json`,version:"1.0.0",type:"DelegationRecord",description:"Internal delegation record"},{id:"delegation-constraints",url:`${r}/delegation/constraints.v1.0.0.json`,version:"1.0.0",type:"DelegationConstraints",description:"CRISP constraints for delegations"},{id:"delegation-chain",url:`${r}/delegation/delegation-chain.v1.0.0.json`,version:"1.0.0",type:"DelegationChain",description:"Delegation chain for hierarchy tracking"},{id:"delegation-creation-request",url:`${r}/delegation/delegation-creation-request.v1.0.0.json`,version:"1.0.0",type:"DelegationCreationRequest",description:"Request to create a delegation"},{id:"delegation-verification-result",url:`${r}/delegation/delegation-verification-result.v1.0.0.json`,version:"1.0.0",type:"DelegationVerificationResult",description:"Result of delegation verification"},{id:"handshake-request",url:`${r}/handshake/handshake-request.v1.0.0.json`,version:"1.0.0",type:"HandshakeRequest",description:"MCP-I handshake request"},{id:"session-context",url:`${r}/handshake/session-context.v1.0.0.json`,version:"1.0.0",type:"SessionContext",description:"MCP-I session context"},{id:"nonce-cache-config",url:`${r}/handshake/nonce-cache-config.v1.0.0.json`,version:"1.0.0",type:"NonceCacheConfig",description:"Nonce cache configuration"},{id:"nonce-cache-entry",url:`${r}/handshake/nonce-cache-entry.v1.0.0.json`,version:"1.0.0",type:"NonceCacheEntry",description:"Nonce cache entry for replay protection"},{id:"detached-proof",url:`${r}/proof/detached-proof.v1.0.0.json`,version:"1.0.0",type:"DetachedProof",description:"MCP-I detached proof with JWS"},{id:"proof-meta",url:`${r}/proof/proof-meta.v1.0.0.json`,version:"1.0.0",type:"ProofMeta",description:"Metadata for MCP-I proofs"},{id:"proof",url:`${r}/proof/v1.0.0.json`,version:"1.0.0",type:"Proof",description:"Generic proof structure"},{id:"proof-w3c",url:`${r}/proof/w3c/v1.0.0.json`,version:"1.0.0",type:"W3CProof",description:"W3C-compliant proof"},{id:"audit-record",url:`${r}/proof/audit-record.v1.0.0.json`,version:"1.0.0",type:"AuditRecord",description:"Audit trail record"},{id:"canonical-hashes",url:`${r}/proof/canonical-hashes.v1.0.0.json`,version:"1.0.0",type:"CanonicalHashes",description:"Canonical hashes for proof generation"},{id:"registration-input",url:`${r}/registry/registration-input.v1.0.0.json`,version:"1.0.0",type:"RegistrationInput",description:"Agent registration input"},{id:"registration-result",url:`${r}/registry/registration-result.v1.0.0.json`,version:"1.0.0",type:"RegistrationResult",description:"Agent registration result"},{id:"agent-status",url:`${r}/registry/agent-status.v1.0.0.json`,version:"1.0.0",type:"AgentStatus",description:"Agent status information"},{id:"claim-token",url:`${r}/registry/claim-token.v1.0.0.json`,version:"1.0.0",type:"ClaimToken",description:"Token for claiming agent ownership"},{id:"delegation-request",url:`${r}/registry/delegation-request.v1.0.0.json`,version:"1.0.0",type:"DelegationRequest",description:"Registry delegation request"},{id:"delegation-response",url:`${r}/registry/delegation-response.v1.0.0.json`,version:"1.0.0",type:"DelegationResponse",description:"Registry delegation response"},{id:"registry-delegation",url:`${r}/registry/delegation.v1.0.0.json`,version:"1.0.0",type:"RegistryDelegation",description:"Registry delegation object"},{id:"mirror-status",url:`${r}/registry/mirror-status.v1.0.0.json`,version:"1.0.0",type:"MirrorStatus",description:"Registry mirror status"},{id:"receipt",url:`${r}/registry/receipt.v1.0.0.json`,version:"1.0.0",type:"Receipt",description:"Registry receipt"},{id:"authorization-display",url:`${r}/runtime/authorization-display.v1.0.0.json`,version:"1.0.0",type:"AuthorizationDisplay",description:"Authorization display information"},{id:"needs-authorization-error",url:`${r}/runtime/needs-authorization-error.v1.0.0.json`,version:"1.0.0",type:"NeedsAuthorizationError",description:"Error indicating authorization is needed"},{id:"runtime-error",url:`${r}/runtime/runtime-error.v1.0.0.json`,version:"1.0.0",type:"RuntimeError",description:"Generic runtime error"},{id:"register-output",url:`${r}/cli/register-output/v1.0.0.json`,version:"1.0.0",type:"RegisterOutput",description:"CLI registration output"},{id:"rotation-chain",url:`${r}/tlkrc/rotation-chain.v1.0.0.json`,version:"1.0.0",type:"RotationChain",description:"Key rotation chain"},{id:"rotation-event",url:`${r}/tlkrc/rotation-event.v1.0.0.json`,version:"1.0.0",type:"RotationEvent",description:"Key rotation event"},{id:"verify-page",url:`${r}/verifier/verify-page/v1.0.0.json`,version:"1.0.0",type:"VerifyPage",description:"Verifier page response"},{id:"well-known-agent",url:`${r}/well-known/agent/v1.0.0.json`,version:"1.0.0",type:"WellKnownAgent",description:"Agent well-known metadata"}]},70926:function(e,t,r){"use strict";var a=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.isAsync=t.isValid=t.isDirty=t.isAborted=t.OK=t.DIRTY=t.INVALID=t.ParseStatus=t.EMPTY_PATH=t.makeIssue=void 0,t.addIssueToContext=function(e,r){const a=(0,s.getErrorMap)(),n=(0,t.makeIssue)({issueData:r,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,a,a===i.default?void 0:i.default].filter(e=>!!e)});e.common.issues.push(n)};const s=r(80630),i=a(r(36886));t.makeIssue=e=>{const{data:t,path:r,errorMaps:a,issueData:s}=e,i=[...r,...s.path||[]],n={...s,path:i};if(void 0!==s.message)return{...s,path:i,message:s.message};let o="";const c=a.filter(e=>!!e).slice().reverse();for(const e of c)o=e(n,{data:t,defaultError:o}).message;return{...s,path:i,message:o}},t.EMPTY_PATH=[];class n{constructor(){this.value="valid"}dirty(){"valid"===this.value&&(this.value="dirty")}abort(){"aborted"!==this.value&&(this.value="aborted")}static mergeArray(e,r){const a=[];for(const s of r){if("aborted"===s.status)return t.INVALID;"dirty"===s.status&&e.dirty(),a.push(s.value)}return{status:e.value,value:a}}static async mergeObjectAsync(e,t){const r=[];for(const e of t){const t=await e.key,a=await e.value;r.push({key:t,value:a})}return n.mergeObjectSync(e,r)}static mergeObjectSync(e,r){const a={};for(const s of r){const{key:r,value:i}=s;if("aborted"===r.status)return t.INVALID;if("aborted"===i.status)return t.INVALID;"dirty"===r.status&&e.dirty(),"dirty"===i.status&&e.dirty(),"__proto__"===r.value||void 0===i.value&&!s.alwaysSet||(a[r.value]=i.value)}return{status:e.value,value:a}}}t.ParseStatus=n,t.INVALID=Object.freeze({status:"aborted"}),t.DIRTY=e=>({status:"dirty",value:e}),t.OK=e=>({status:"valid",value:e}),t.isAborted=e=>"aborted"===e.status,t.isDirty=e=>"dirty"===e.status,t.isValid=e=>"valid"===e.status,t.isAsync=e=>"undefined"!=typeof Promise&&e instanceof Promise},71089:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.revokeDelegationAPIResponseSchema=t.revokeDelegationResponseSchema=t.revokeDelegationRequestSchema=t.createDelegationAPIResponseSchema=t.createDelegationResponseSchema=t.createDelegationRequestSchema=t.toolProtectionConfigAPIResponseSchema=t.toolProtectionConfigResponseSchema=t.agentShieldToolProtectionSchema=t.verifyDelegationAPIResponseSchema=t.verifyDelegationResponseSchema=t.verifyDelegationRequestSchema=t.delegationCredentialSchema=t.proofSubmissionResponseSchema=t.proofSubmissionRequestSchema=t.agentShieldAPIResponseSchema=t.agentShieldAPIErrorSchema=void 0;const a=r(90315),s=r(19613),i=r(41094);t.agentShieldAPIErrorSchema=a.z.object({code:a.z.string(),message:a.z.string(),details:a.z.record(a.z.unknown()).optional()}),t.agentShieldAPIResponseSchema=e=>a.z.object({success:a.z.boolean(),data:e,metadata:a.z.object({requestId:a.z.string(),timestamp:a.z.string()}).optional()}),t.proofSubmissionRequestSchema=a.z.object({delegation_id:a.z.string().uuid().nullable(),session_id:a.z.string().uuid(),proofs:a.z.array(s.DetachedProofSchema).min(1)}),t.proofSubmissionResponseSchema=a.z.object({success:a.z.boolean(),received:a.z.number().int().min(0),processed:a.z.number().int().min(0),errors:a.z.array(a.z.object({proofId:a.z.string(),error:a.z.string()})).optional()}),t.delegationCredentialSchema=a.z.object({agent_did:a.z.string(),user_id:a.z.string().optional(),user_identifier:a.z.string().optional(),scopes:a.z.array(a.z.string()),constraints:a.z.record(a.z.unknown()).optional(),issued_at:a.z.number().int().positive(),created_at:a.z.number().int().positive()}),t.verifyDelegationRequestSchema=a.z.object({agent_did:a.z.string(),scopes:a.z.array(a.z.string()).min(1),timestamp:a.z.number().int().positive().optional(),client_info:a.z.object({ip_address:a.z.string().ip().optional(),origin:a.z.string().url().optional(),user_agent:a.z.string().optional()}).optional()}),t.verifyDelegationResponseSchema=a.z.object({valid:a.z.boolean(),delegation:i.DelegationRecordSchema.optional(),delegation_id:a.z.string().uuid().optional(),credential:t.delegationCredentialSchema.optional(),error:t.agentShieldAPIErrorSchema.optional(),reason:a.z.string().optional()}),t.verifyDelegationAPIResponseSchema=(0,t.agentShieldAPIResponseSchema)(t.verifyDelegationResponseSchema),t.agentShieldToolProtectionSchema=a.z.object({scopes:a.z.array(a.z.string()),requires_delegation:a.z.boolean().optional(),requiresDelegation:a.z.boolean().optional(),required_scopes:a.z.array(a.z.string()).optional()}).passthrough(),t.toolProtectionConfigResponseSchema=a.z.object({agent_did:a.z.string(),tools:a.z.record(a.z.string(),t.agentShieldToolProtectionSchema),reputation_threshold:a.z.number().min(0).max(1).optional(),denied_agents:a.z.array(a.z.string()).optional()}),t.toolProtectionConfigAPIResponseSchema=(0,t.agentShieldAPIResponseSchema)(t.toolProtectionConfigResponseSchema),t.createDelegationRequestSchema=a.z.object({delegation:i.DelegationRecordSchema}),t.createDelegationResponseSchema=a.z.object({delegation_id:a.z.string().uuid(),delegation:i.DelegationRecordSchema}),t.createDelegationAPIResponseSchema=(0,t.agentShieldAPIResponseSchema)(t.createDelegationResponseSchema),t.revokeDelegationRequestSchema=a.z.object({reason:a.z.string().optional()}),t.revokeDelegationResponseSchema=a.z.object({delegation_id:a.z.string().uuid(),revoked:a.z.boolean(),revoked_at:a.z.number().int().positive()}),t.revokeDelegationAPIResponseSchema=(0,t.agentShieldAPIResponseSchema)(t.revokeDelegationResponseSchema)},71283:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.MemoryDelegationGraphStorage=void 0,t.MemoryDelegationGraphStorage=class{nodes=new Map;async getNode(e){return this.nodes.get(e)||null}async setNode(e){this.nodes.set(e.id,e)}async getChildren(e){const t=this.nodes.get(e);return t?t.children.map(e=>this.nodes.get(e)).filter(e=>void 0!==e):[]}async getChain(e){const t=[];let r=e;for(;r;){const e=this.nodes.get(r);if(!e)break;t.unshift(e),r=e.parentId}return t}async getDescendants(e){const t=[],r=[e],a=new Set;for(;r.length>0;){const e=r.shift();if(a.has(e))continue;a.add(e);const s=this.nodes.get(e);if(s)for(const e of s.children)if(!a.has(e)){r.push(e);const a=this.nodes.get(e);a&&t.push(a)}}return t}async deleteNode(e){this.nodes.delete(e)}clear(){this.nodes.clear()}getAllNodeIds(){return Array.from(this.nodes.keys())}getStats(){const e=Array.from(this.nodes.values()),t=e.filter(e=>null===e.parentId).length,r=e.filter(e=>0===e.children.length).length;let a=0;for(const t of e){const e=this.getChainSync(t.id);a=Math.max(a,e.length-1)}return{totalNodes:e.length,rootNodes:t,leafNodes:r,maxDepth:a}}getChainSync(e){const t=[];let r=e;for(;r;){const e=this.nodes.get(r);if(!e)break;t.unshift(e),r=e.parentId}return t}}},71346:e=>{"use strict";e.exports=function(e,t,r){var a,s=" ",i=e.level,n=e.dataLevel,o=e.schema[t],c=e.schemaPath+e.util.getProperty(t),d=e.errSchemaPath+"/"+t,u=!e.opts.allErrors,l="data"+(n||""),h=e.opts.$data&&o&&o.$data;h?(s+=" var schema"+i+" = "+e.util.getData(o.$data,n,e.dataPathArr)+"; ",a="schema"+i):a=o;var p="maximum"==t,f=p?"exclusiveMaximum":"exclusiveMinimum",m=e.schema[f],g=e.opts.$data&&m&&m.$data,y=p?"<":">",v=p?">":"<",_=void 0;if(!h&&"number"!=typeof o&&void 0!==o)throw new Error(t+" must be number");if(!g&&void 0!==m&&"number"!=typeof m&&"boolean"!=typeof m)throw new Error(f+" must be number or boolean");if(g){var S,b=e.util.getData(m.$data,n,e.dataPathArr),E="exclusive"+i,P="exclType"+i,I="exclIsNumber"+i,w="' + "+(T="op"+i)+" + '";s+=" var schemaExcl"+i+" = "+b+"; ",s+=" var "+E+"; var "+P+" = typeof "+(b="schemaExcl"+i)+"; if ("+P+" != 'boolean' && "+P+" != 'undefined' && "+P+" != 'number') { ",_=f,(S=S||[]).push(s),s="",!1!==e.createErrors?(s+=" { keyword: '"+(_||"_exclusiveLimit")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(d)+" , params: {} ",!1!==e.opts.messages&&(s+=" , message: '"+f+" should be boolean' "),e.opts.verbose&&(s+=" , schema: validate.schema"+c+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+l+" "),s+=" } "):s+=" {} ";var C=s;s=S.pop(),!e.compositeRule&&u?e.async?s+=" throw new ValidationError(["+C+"]); ":s+=" validate.errors = ["+C+"]; return false; ":s+=" var err = "+C+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",s+=" } else if ( ",h&&(s+=" ("+a+" !== undefined && typeof "+a+" != 'number') || "),s+=" "+P+" == 'number' ? ( ("+E+" = "+a+" === undefined || "+b+" "+y+"= "+a+") ? "+l+" "+v+"= "+b+" : "+l+" "+v+" "+a+" ) : ( ("+E+" = "+b+" === true) ? "+l+" "+v+"= "+a+" : "+l+" "+v+" "+a+" ) || "+l+" !== "+l+") { var op"+i+" = "+E+" ? '"+y+"' : '"+y+"='; ",void 0===o&&(_=f,d=e.errSchemaPath+"/"+f,a=b,h=g)}else if(w=y,(I="number"==typeof m)&&h){var T="'"+w+"'";s+=" if ( ",h&&(s+=" ("+a+" !== undefined && typeof "+a+" != 'number') || "),s+=" ( "+a+" === undefined || "+m+" "+y+"= "+a+" ? "+l+" "+v+"= "+m+" : "+l+" "+v+" "+a+" ) || "+l+" !== "+l+") { "}else I&&void 0===o?(E=!0,_=f,d=e.errSchemaPath+"/"+f,a=m,v+="="):(I&&(a=Math[p?"min":"max"](m,o)),m===(!I||a)?(E=!0,_=f,d=e.errSchemaPath+"/"+f,v+="="):(E=!1,w+="=")),T="'"+w+"'",s+=" if ( ",h&&(s+=" ("+a+" !== undefined && typeof "+a+" != 'number') || "),s+=" "+l+" "+v+" "+a+" || "+l+" !== "+l+") { ";return _=_||t,(S=S||[]).push(s),s="",!1!==e.createErrors?(s+=" { keyword: '"+(_||"_limit")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(d)+" , params: { comparison: "+T+", limit: "+a+", exclusive: "+E+" } ",!1!==e.opts.messages&&(s+=" , message: 'should be "+w+" ",s+=h?"' + "+a:a+"'"),e.opts.verbose&&(s+=" , schema: ",s+=h?"validate.schema"+c:""+o,s+=" , parentSchema: validate.schema"+e.schemaPath+" , data: "+l+" "),s+=" } "):s+=" {} ",C=s,s=S.pop(),!e.compositeRule&&u?e.async?s+=" throw new ValidationError(["+C+"]); ":s+=" validate.errors = ["+C+"]; return false; ":s+=" var err = "+C+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",s+=" } ",u&&(s+=" else { "),s}},72916:(e,t,r)=>{"use strict";var a=r(40985);function s(e,t,r){this.message=r||s.message(e,t),this.missingRef=a.url(e,t),this.missingSchema=a.normalizeId(a.fullPath(this.missingRef))}function i(e){return e.prototype=Object.create(Error.prototype),e.prototype.constructor=e,e}e.exports={Validation:i(function(e){this.message="validation failed",this.errors=e,this.ajv=this.validation=!0}),MissingRef:i(s)},s.message=function(e,t){return"can't resolve reference "+t+" from id "+e}},73706:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ProofVerifier=void 0;const a=r(22169),s=r(19613),i=r(51708),n=r(62846);t.ProofVerifier=class{cryptoService;clock;nonceCache;fetch;timestampSkewSeconds;nonceTtlSeconds;constructor(e){this.cryptoService=new a.CryptoService(e.cryptoProvider),this.clock=e.clockProvider,this.nonceCache=e.nonceCacheProvider,this.fetch=e.fetchProvider,this.timestampSkewSeconds=e.timestampSkewSeconds??120,this.nonceTtlSeconds=e.nonceTtlSeconds??300}async verifyProof(e,t){try{const r=await this.validateProofStructure(e);if(!r.valid)return r;const a=r.proof,s=await this.validateNonce(a.meta.nonce);if(!s.valid)return s;const i=await this.validateTimestamp(a.meta.ts);if(!i.valid)return i;const n=this.buildCanonicalPayload(a.meta),o=(new TextEncoder).encode(n),c=await this.verifySignature(a.jws,t,o,a.meta.kid);return c.valid?(await this.addNonceToCache(a.meta.nonce),{valid:!0}):c}catch(e){return{valid:!1,reason:"Proof verification error",errorCode:n.PROOF_VERIFICATION_ERROR_CODES.VERIFICATION_ERROR,error:e instanceof Error?e:new Error(String(e)),details:{errorMessage:e instanceof Error?e.message:String(e)}}}}async verifyProofDetached(e,t,r){try{const a=await this.validateProofStructure(e);if(!a.valid)return a;const s=a.proof,i=await this.validateNonce(s.meta.nonce);if(!i.valid)return i;const n=await this.validateTimestamp(s.meta.ts);if(!n.valid)return n;const o=t instanceof Uint8Array?t:(new TextEncoder).encode(t),c=await this.verifySignature(s.jws,r,o,s.meta.kid);return c.valid?(await this.addNonceToCache(s.meta.nonce),{valid:!0}):c}catch(e){return{valid:!1,reason:"Proof verification error",errorCode:n.PROOF_VERIFICATION_ERROR_CODES.VERIFICATION_ERROR,error:e instanceof Error?e:new Error(String(e)),details:{errorMessage:e instanceof Error?e.message:String(e)}}}}async validateProofStructure(e){const t=s.DetachedProofSchema.safeParse(e);return t.success?{valid:!0,proof:t.data}:{valid:!1,reason:"Invalid proof structure",errorCode:n.PROOF_VERIFICATION_ERROR_CODES.INVALID_PROOF_STRUCTURE,error:new Error(`Proof validation failed: ${t.error.message}`),details:{zodErrors:t.error.errors}}}async validateNonce(e){return await this.nonceCache.has(e)?{valid:!1,reason:"Nonce already used (replay attack detected)",errorCode:n.PROOF_VERIFICATION_ERROR_CODES.NONCE_REPLAY_DETECTED,details:{nonce:e}}:{valid:!0}}async validateTimestamp(e){const t=1e3*e;return this.clock.isWithinSkew(t,this.timestampSkewSeconds)?{valid:!0}:{valid:!1,reason:`Timestamp out of skew window (skew: ${this.timestampSkewSeconds}s)`,errorCode:n.PROOF_VERIFICATION_ERROR_CODES.TIMESTAMP_SKEW_EXCEEDED,details:{timestamp:e,timestampMs:t,skewSeconds:this.timestampSkewSeconds,currentTime:this.clock.now()}}}async verifySignature(e,t,r,a){return await this.cryptoService.verifyJWS(e,t,{detachedPayload:r,expectedKid:a,alg:"EdDSA"})?{valid:!0}:{valid:!1,reason:"Invalid JWS signature",errorCode:n.PROOF_VERIFICATION_ERROR_CODES.INVALID_JWS_SIGNATURE,details:{jwsLength:e.length,expectedKid:a,actualKid:t.kid}}}async addNonceToCache(e){const t=this.clock.calculateExpiry(this.nonceTtlSeconds);await this.nonceCache.add(e,t)}async fetchPublicKeyFromDID(e,t){try{const r=await this.fetch.resolveDID(e);if(!r)throw new n.ProofVerificationError(n.PROOF_VERIFICATION_ERROR_CODES.DID_DOCUMENT_NOT_FOUND,`DID document not found: ${e}`,{did:e});if(!r.verificationMethod||0===r.verificationMethod.length)throw new n.ProofVerificationError(n.PROOF_VERIFICATION_ERROR_CODES.VERIFICATION_METHOD_NOT_FOUND,`No verification methods found in DID document: ${e}`,{did:e});let a;if(t){const s=t.startsWith("#")?t:`#${t}`;if(a=r.verificationMethod.find(t=>t.id===s||t.id===`${e}${s}`),!a)throw new n.ProofVerificationError(n.PROOF_VERIFICATION_ERROR_CODES.VERIFICATION_METHOD_NOT_FOUND,`Verification method not found for kid: ${t}`,{did:e,kid:t,availableKids:r.verificationMethod.map(e=>e.id)})}else a=r.verificationMethod[0];if(!a?.publicKeyJwk)throw new n.ProofVerificationError(n.PROOF_VERIFICATION_ERROR_CODES.PUBLIC_KEY_NOT_FOUND,"Public key JWK not found in verification method",{did:e,kid:t,verificationMethodId:a?.id});const s=a.publicKeyJwk;if("OKP"!==s.kty||"Ed25519"!==s.crv||!s.x)throw new n.ProofVerificationError(n.PROOF_VERIFICATION_ERROR_CODES.INVALID_JWK_FORMAT,`Unsupported key type or curve: kty=${s.kty}, crv=${s.crv}`,{did:e,kid:t,jwk:{kty:s.kty,crv:s.crv}});return s}catch(r){if(r instanceof n.ProofVerificationError)throw r;throw console.error("[ProofVerifier] Failed to fetch public key from DID:",r),new n.ProofVerificationError(n.PROOF_VERIFICATION_ERROR_CODES.DID_RESOLUTION_FAILED,`DID resolution failed: ${r instanceof Error?r.message:String(r)}`,{did:e,kid:t,originalError:r instanceof Error?r.message:String(r)})}}buildCanonicalPayload(e){const t={aud:e.audience,sub:e.did,iss:e.did,requestHash:e.requestHash,responseHash:e.responseHash,ts:e.ts,nonce:e.nonce,sessionId:e.sessionId,...e.scopeId&&{scopeId:e.scopeId},...e.delegationRef&&{delegationRef:e.delegationRef},...e.clientDid&&{clientDid:e.clientDid}};return(0,i.canonicalize)(t)}}},74161:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.STATUSLIST_2021_CONTEXT=t.MAX_STATUSLIST_SIZE=t.DEFAULT_STATUSLIST_CACHE_TTL_SEC=t.StatusList2021CredentialSchema=t.StatusList2021CredentialSubjectSchema=void 0,t.validateStatusList2021Credential=function(e){return t.StatusList2021CredentialSchema.safeParse(e)},t.createStatusListCredentialStructure=function(e){return{"@context":["https://www.w3.org/2018/credentials/v1","https://w3id.org/vc/status-list/2021/v1"],id:e.id,type:["VerifiableCredential","StatusList2021Credential"],issuer:e.issuer,issuanceDate:(new Date).toISOString(),credentialSubject:{type:"StatusList2021",statusPurpose:e.statusPurpose,encodedList:e.encodedList}}};const a=r(90315),s=r(46511);t.StatusList2021CredentialSubjectSchema=a.z.object({id:a.z.string().optional(),type:a.z.literal("StatusList2021"),statusPurpose:a.z.enum(["revocation","suspension"]),encodedList:a.z.string().regex(/^[A-Za-z0-9_-]+$/,{message:"encodedList must be base64url encoded"})}),t.StatusList2021CredentialSchema=a.z.object({"@context":s.ContextSchema.refine(e=>e.length>=2&&"string"==typeof e[0]&&"https://www.w3.org/2018/credentials/v1"===e[0]&&(e.includes("https://w3id.org/vc/status-list/2021/v1")||e.some(e=>"object"==typeof e&&void 0!==e.StatusList2021Credential)),{message:"@context must include VC context and StatusList2021 context"}),id:a.z.string().url(),type:a.z.tuple([a.z.literal("VerifiableCredential"),a.z.literal("StatusList2021Credential")]).or(a.z.array(a.z.string()).refine(e=>e.includes("VerifiableCredential")&&e.includes("StatusList2021Credential"),{message:'type must include "VerifiableCredential" and "StatusList2021Credential"'})),issuer:s.IssuerSchema,issuanceDate:a.z.string().datetime(),credentialSubject:t.StatusList2021CredentialSubjectSchema,proof:s.ProofSchema.optional()}).passthrough(),t.DEFAULT_STATUSLIST_CACHE_TTL_SEC=60,t.MAX_STATUSLIST_SIZE=1e6,t.STATUSLIST_2021_CONTEXT="https://w3id.org/vc/status-list/2021/v1"},74488:function(e,t,r){"use strict";var a=this&&this.__createBinding||(Object.create?function(e,t,r,a){void 0===a&&(a=r);var s=Object.getOwnPropertyDescriptor(t,r);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,a,s)}:function(e,t,r,a){void 0===a&&(a=r),e[a]=t[r]}),s=this&&this.__exportStar||function(e,t){for(var r in e)"default"===r||Object.prototype.hasOwnProperty.call(t,r)||a(t,e,r)};Object.defineProperty(t,"__esModule",{value:!0}),s(r(97145),t),s(r(78362),t)},77753:(e,t,r)=>{"use strict";r.d(t,{d:()=>s});var a=r(10985);function s(e,t){return(0,a.S)(e,{allowCircular:t,filterUndefined:!0,undefinedInArrayToNull:!0})}},77990:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.MCPIRuntimeBase=void 0;const a=r(63288),s=r(22169),i=r(31302);t.MCPIRuntimeBase=class{crypto;clock;fetch;storage;nonceCache;identity;config;cachedIdentity;sessions=new Map;lastProof;userDidManager;interceptedCalls=new Map;cryptoService;constructor(e){this.config=e,this.crypto=e.cryptoProvider,this.clock=e.clockProvider,this.fetch=e.fetchProvider,this.storage=e.storageProvider,this.nonceCache=e.nonceCacheProvider,this.identity=e.identityProvider,this.cryptoService=new s.CryptoService(this.crypto)}async initialize(){this.cachedIdentity=await this.identity.getIdentity(),this.config.identity?.generateUserDids&&(this.userDidManager=new i.UserDidManager({crypto:this.crypto,storage:this.config.identity?.userDidStorage?{get:async e=>await this.storage.get(`userDid:${e}`),set:async(e,t,r)=>{await this.storage.set(`userDid:${e}`,t)},delete:async e=>await this.storage.delete(`userDid:${e}`)}:void 0,useDidWeb:"persistent"===this.config.identity?.userDidStorage})),"initialize"in this.nonceCache&&"function"==typeof this.nonceCache.initialize&&await this.nonceCache.initialize(),this.config.audit?.enabled&&this.logAudit("runtime_initialized",{did:this.cachedIdentity.did,environment:this.config.environment||"development",userDidGeneration:this.config.identity?.generateUserDids?"enabled":"disabled"})}async getIdentity(){return this.cachedIdentity||(this.cachedIdentity=await this.identity.getIdentity()),this.cachedIdentity}async handleHandshake(e){const t=await this.getIdentity(),r=this.clock.now(),a=await this.generateSessionId();let s;if(this.userDidManager)try{s=await this.userDidManager.getOrCreateUserDid(a),this.config.audit?.enabled&&console.log("[MCP-I] Generated user DID for session:",s)}catch(e){console.warn("[MCP-I] Failed to generate user DID:",e)}const i={id:a,clientDid:e.clientDid||s,userDid:s,agentDid:e.agentDid,serverDid:t.did,audience:e.audience,createdAt:r,expiresAt:this.clock.calculateExpiry(60*(this.config.session?.ttlMinutes||30))};this.sessions.set(a,i);const n={sessionId:a,agentDid:t.did,timestamp:r,capabilities:["identity","proof","audit"],...s&&{userDid:s}},o=await this.signData(n);return{...n,signature:o}}async processToolCall(e,t,r,s){if(this.config.toolProtectionService){const r=await this.getIdentity();this.config.audit?.enabled&&console.log("[MCP-I] Checking tool protection:",{tool:e,agentDid:r.did.slice(0,20)+"...",hasDelegation:!(!s?.delegationToken&&!s?.consentProof)});const i=await this.config.toolProtectionService.checkToolProtection(e,r.did);if(i){if(!s?.delegationToken&&!s?.consentProof){const n={toolName:e,args:t,sessionId:s?.id||"unknown",timestamp:this.clock.now(),expiresAt:this.clock.calculateExpiry(1800)},o=this.generateResumeToken(n),c=this.buildConsentUrl(e,i.requiredScopes,s,o),d=new a.DelegationRequiredError(e,i.requiredScopes,c,n,o);throw this.interceptedCalls.set(o,n),this.cleanupExpiredInterceptedCalls(),this.config.audit?.enabled&&console.warn("[MCP-I] BLOCKED: Tool requires delegation but none provided",{tool:e,requiredScopes:i.requiredScopes,agentDid:r.did.slice(0,20)+"...",resumeToken:d.resumeToken,consentUrl:c}),d}this.config.audit?.enabled&&console.log("[MCP-I] Tool protection check passed (delegation provided)",{tool:e,agentDid:r.did.slice(0,20)+"..."})}else this.config.audit?.enabled&&console.log("[MCP-I] Tool protection check passed (no delegation required)",{tool:e,agentDid:r.did.slice(0,20)+"...",reason:"Tool not configured to require delegation"})}const i=await r(t),n=await this.createProof(i,s);return this.lastProof=n,this.config.audit?.enabled&&this.logAudit("tool_executed",{tool:e,sessionId:s?.id,timestamp:this.clock.now()}),i}async resumeToolCall(e,t,r){const a=this.interceptedCalls.get(e);if(!a)throw new Error(`Invalid or expired resume token: ${e}`);if(this.clock.hasExpired(a.expiresAt))throw this.interceptedCalls.delete(e),new Error(`Resume token expired: ${e}`);const s=this.sessions.get(a.sessionId);if(!s)throw new Error(`Session not found for intercepted call: ${a.sessionId}`);const i={...s,delegationToken:r},n=await this.processToolCall(a.toolName,a.args,t,i);return this.interceptedCalls.delete(e),n}generateResumeToken(e){const t=JSON.stringify({tool:e.toolName,args:e.args,sessionId:e.sessionId,timestamp:e.timestamp});let r=0;for(let e=0;e<t.length;e++)r=(r<<5)-r+t.charCodeAt(e),r&=r;return`resume_${Math.abs(r).toString(36)}_${Date.now().toString(36)}`}cleanupExpiredInterceptedCalls(){this.clock.now();for(const[e,t]of this.interceptedCalls.entries())this.clock.hasExpired(t.expiresAt)&&this.interceptedCalls.delete(e)}buildConsentUrl(e,t,r,a,s){const i=new URLSearchParams({tool:e,scopes:t.join(","),session_id:r?.id||"",agent_did:r?.agentDid||""});return s&&i.set("project_id",s),a&&i.set("resume_token",a),`https://kya.vouched.id/bouncer/consent?${i.toString()}`}async issueNonce(e){const t=await this.generateNonce();return await this.nonceCache.add(t,this.clock.calculateExpiry(300)),t}async createProof(e,t){const r=await this.getIdentity(),a=this.clock.now();let s;t?.nonce?s=t.nonce:(s=await this.generateNonce(),await this.nonceCache.add(s,this.clock.calculateExpiry(300)));const i={data:e,timestamp:a,nonce:s,did:r.did,sessionId:t?.id,audience:t?.audience},n=await this.signData(i);return{timestamp:a,nonce:s,did:r.did,signature:n,algorithm:"Ed25519",sessionId:t?.id,audience:t?.audience}}async verifyProof(e,t){try{if(await this.nonceCache.has(t.nonce))return!1;if(!this.clock.isWithinSkew(t.timestamp,this.config.session?.timestampSkewSeconds||120))return!1;const r=await this.fetch.resolveDID(t.did),a=this.extractPublicKey(r),s={data:e,timestamp:t.timestamp,nonce:t.nonce,did:t.did,sessionId:t.sessionId},i=(new TextEncoder).encode(JSON.stringify(s)),n=this.base64ToBytes(t.signature);return await this.crypto.verify(i,n,a)}catch(e){return console.error("Proof verification failed:",e),!1}}async verifyProofJWS(e,t,r){if(!this.cryptoService)return console.error("[MCPIRuntimeBase] CryptoService not initialized"),!1;try{const a=void 0!==r?{detachedPayload:r}:void 0;return await this.cryptoService.verifyJWS(e,t,a)}catch(e){return console.error("[MCPIRuntimeBase] JWS verification failed:",e),!1}}async getCurrentSession(){for(const[e,t]of this.sessions)if(!this.clock.hasExpired(t.expiresAt))return t;return null}getLastProof(){return this.lastProof}createWellKnownHandler(e){return async t=>{const r=await this.getIdentity();if("/.well-known/did.json"===t){const e=this.createDIDDocument(r);return{status:200,headers:{"Content-Type":"application/did+json","Cache-Control":"production"===this.config.environment?"public, max-age=300":"no-store"},body:JSON.stringify(e,null,2)}}if("/.well-known/agent.json"===t){const t={id:r.did,capabilities:{"mcp-i":["handshake","signing","verification"]}};return(e?.serviceName||e?.serviceEndpoint)&&(t.metadata={...e?.serviceName&&{name:e.serviceName},...e?.serviceEndpoint&&{serviceEndpoint:e.serviceEndpoint}}),{status:200,headers:{"Content-Type":"application/json","Cache-Control":"production"===this.config.environment?"public, max-age=300":"no-store"},body:JSON.stringify(t,null,2)}}return"/.well-known/mcp-identity"===t?{did:r.did,publicKey:r.publicKey,serviceName:e?.serviceName||"MCP-I Service",serviceEndpoint:e?.serviceEndpoint||"https://example.com",timestamp:this.clock.now()}:null}}createDebugEndpoint(){return"production"===this.config.environment?null:async()=>{const e=await this.getIdentity(),t=await this.getCurrentSession();return{identity:{did:e.did,publicKey:e.publicKey},session:t,config:{environment:this.config.environment,timestampSkewSeconds:this.config.session?.timestampSkewSeconds,sessionTtlMinutes:this.config.session?.ttlMinutes},timestamp:this.clock.now()}}}getAuditLogger(){return{log:(e,t)=>this.logAudit(e,t)}}async rotateKeys(){const e=this.cachedIdentity?.did,t=await this.identity.rotateKeys();return this.cachedIdentity=t,this.config.audit?.enabled&&this.logAudit("keys_rotated",{oldDid:e,newDid:t.did,timestamp:this.clock.now()}),t}async signData(e){const t=await this.getIdentity(),r=(new TextEncoder).encode(JSON.stringify(e)),a=await this.crypto.sign(r,t.privateKey);return this.bytesToBase64(a)}async generateNonce(){const e=await this.crypto.randomBytes(32);return this.bytesToBase64(e)}async generateSessionId(){const e=await this.crypto.randomBytes(16);return this.bytesToHex(e)}logAudit(e,t){if(!this.config.audit?.enabled)return;const r={event:e,data:this.config.audit.includePayloads?t:void 0,timestamp:this.clock.now(),timestampFormatted:this.clock.format(this.clock.now())},a=JSON.stringify(r);this.config.audit.logFunction?this.config.audit.logFunction(a):console.log("[AUDIT]",a)}createDIDDocument(e){return{"@context":["https://www.w3.org/ns/did/v1"],id:e.did,verificationMethod:[{id:`${e.did}#key-1`,type:"Ed25519VerificationKey2020",controller:e.did,publicKeyBase64:e.publicKey}],authentication:[`${e.did}#key-1`],assertionMethod:[`${e.did}#key-1`]}}extractPublicKey(e){const t=e.verificationMethod?.[0];if(t?.publicKeyBase64)return t.publicKeyBase64;if(t?.publicKeyMultibase)return t.publicKeyMultibase;throw new Error("Public key not found in DID document")}bytesToBase64(e){return Buffer.from(e).toString("base64")}base64ToBytes(e){return new Uint8Array(Buffer.from(e,"base64"))}bytesToHex(e){return Buffer.from(e).toString("hex")}}},78362:(e,t)=>{"use strict";function r(e){return JSON.stringify(e)}Object.defineProperty(t,"__esModule",{value:!0}),t.DOWNSTREAM_HEADER_NAMES=void 0,t.serializeCrispSpend=r,t.parseCrispSpend=function(e){try{const t=JSON.parse(e);return t&&"string"==typeof t.unit?t:null}catch{return null}},t.createDownstreamHeaders=function(e){const t={"X-Agent-DID":e.agentDid,"X-MCPI-Proof-Id":e.proofId};return e.delegationId&&(t["X-Delegation-Id"]=e.delegationId),e.delegationChain&&(t["X-Delegation-Chain"]=e.delegationChain),e.crispSpend&&(t["X-CRISP-Spend"]=r(e.crispSpend)),e.sessionId&&(t["X-Session-Id"]=e.sessionId),e.scopes&&e.scopes.length>0&&(t["X-Scopes"]=e.scopes.join(",")),t},t.DOWNSTREAM_HEADER_NAMES=Object.freeze({AGENT_DID:"X-Agent-DID",DELEGATION_ID:"X-Delegation-Id",DELEGATION_CHAIN:"X-Delegation-Chain",PROOF_ID:"X-MCPI-Proof-Id",CRISP_SPEND:"X-CRISP-Spend",SESSION_ID:"X-Session-Id",SCOPES:"X-Scopes"})},79885:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ERROR_HTTP_STATUS=t.VERIFIER_ERROR_CODES=t.AGENT_HEADERS=t.StructuredErrorSchema=t.VerifierResultSchema=t.AgentContextSchema=void 0;const a=r(90315);t.AgentContextSchema=a.z.object({did:a.z.string().min(1),kid:a.z.string().min(1),subject:a.z.string().optional(),scopes:a.z.array(a.z.string()).default([]),session:a.z.string().min(1),confidence:a.z.literal("verified"),delegationRef:a.z.string().optional(),registry:a.z.string().url(),verifiedAt:a.z.number().int().positive()}),t.VerifierResultSchema=a.z.object({success:a.z.boolean(),headers:a.z.record(a.z.string()).optional(),agentContext:t.AgentContextSchema.optional(),error:a.z.object({code:a.z.string(),message:a.z.string(),details:a.z.any().optional(),httpStatus:a.z.number().int().min(400).max(599)}).optional()}),t.StructuredErrorSchema=a.z.object({code:a.z.string(),message:a.z.string(),httpStatus:a.z.number().int().min(400).max(599),details:a.z.object({reason:a.z.string().optional(),expected:a.z.any().optional(),received:a.z.any().optional(),remediation:a.z.string().optional()}).optional()}),t.AGENT_HEADERS={DID:"X-Agent-DID",KEY_ID:"X-Agent-KeyId",SUBJECT:"X-Agent-Subject",SCOPES:"X-Agent-Scopes",SESSION:"X-Agent-Session",CONFIDENCE:"X-Agent-Confidence",DELEGATION_REF:"X-Agent-Delegation-Ref",REGISTRY:"X-Agent-Registry",VERIFIED_AT:"X-Agent-Verified-At"},t.VERIFIER_ERROR_CODES={PROOF_INVALID_TS:"XMCP_I_PROOF_INVALID_TS",PROOF_FUTURE_TS:"XMCP_I_PROOF_FUTURE_TS",PROOF_TOO_OLD:"XMCP_I_PROOF_TOO_OLD",PROOF_SKEW_EXCEEDED:"XMCP_I_PROOF_SKEW_EXCEEDED",SESSION_IDLE_EXPIRED:"XMCP_I_SESSION_IDLE_EXPIRED",SERVER_TIME_INVALID:"XMCP_I_SERVER_TIME_INVALID"},t.ERROR_HTTP_STATUS={XMCP_I_EBADPROOF:403,XMCP_I_ENOIDENTITY:500,XMCP_I_EMIRRORPENDING:200,XMCP_I_EHANDSHAKE:401,XMCP_I_ESESSION:401,XMCP_I_ECLAIM:400,XMCP_I_ECONFIG:500,XMCP_I_ERUNTIME:500,[t.VERIFIER_ERROR_CODES.PROOF_INVALID_TS]:403,[t.VERIFIER_ERROR_CODES.PROOF_FUTURE_TS]:403,[t.VERIFIER_ERROR_CODES.PROOF_TOO_OLD]:403,[t.VERIFIER_ERROR_CODES.PROOF_SKEW_EXCEEDED]:401,[t.VERIFIER_ERROR_CODES.SESSION_IDLE_EXPIRED]:401,[t.VERIFIER_ERROR_CODES.SERVER_TIME_INVALID]:500}},79983:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.TEST_ERROR_CODES=t.TEST_KEY_IDS=t.TEST_DIDS=t.LocalVerificationResultSchema=t.MockIdentityProviderConfigSchema=t.MockKTAFailureTypeSchema=t.MockDelegationStatusSchema=t.MockIdentitySchema=t.TestEnvironmentSchema=void 0,t.isTestEnvironment=function(){return"test"===process.env.XMCP_ENV},t.getTestSeed=function(e){return process.env.XMCP_TEST_SEED||e||"default-test-seed"};const a=r(90315);t.TestEnvironmentSchema=a.z.object({mode:a.z.literal("test"),seed:a.z.string().optional(),deterministicKeys:a.z.boolean().default(!0),skipKTACalls:a.z.boolean().default(!0)}),t.MockIdentitySchema=a.z.object({did:a.z.string(),kid:a.z.string(),privateKey:a.z.string().regex(/^[A-Za-z0-9+/]{43}=$/,"Must be a valid base64-encoded Ed25519 private key (44 characters)"),publicKey:a.z.string().regex(/^[A-Za-z0-9+/]{43}=$/,"Must be a valid base64-encoded Ed25519 public key (44 characters)"),createdAt:a.z.string(),lastRotated:a.z.string().optional()}),t.MockDelegationStatusSchema=a.z.enum(["active","revoked","pending"]),t.MockKTAFailureTypeSchema=a.z.enum(["network","auth","invalid","timeout"]),t.MockIdentityProviderConfigSchema=a.z.object({identities:a.z.record(a.z.string(),t.MockIdentitySchema),delegations:a.z.record(a.z.string(),t.MockDelegationStatusSchema),ktaFailures:a.z.array(t.MockKTAFailureTypeSchema).default([]),deterministicSeed:a.z.string().optional()}),t.LocalVerificationResultSchema=a.z.object({valid:a.z.boolean(),did:a.z.string().optional(),kid:a.z.string().optional(),signature:a.z.object({valid:a.z.boolean(),algorithm:a.z.string(),error:a.z.string().optional()}),proof:a.z.object({valid:a.z.boolean(),structure:a.z.boolean(),timestamps:a.z.boolean(),hashes:a.z.boolean(),error:a.z.string().optional()}),session:a.z.object({valid:a.z.boolean(),expired:a.z.boolean(),error:a.z.string().optional()}),errors:a.z.array(a.z.string()).default([]),warnings:a.z.array(a.z.string()).default([])}),t.TEST_DIDS={AGENT_1:"did:test:agent-1",AGENT_2:"did:test:agent-2",VERIFIER_1:"did:test:verifier-1"},t.TEST_KEY_IDS={KEY_TEST_1:"key-test-1",KEY_TEST_2:"key-test-2",KEY_VERIFIER_1:"key-verifier-1"},t.TEST_ERROR_CODES={MOCK_KTA_FAILURE:"XMCP_I_TEST_MOCK_KTA_FAILURE",DETERMINISTIC_KEY_GENERATION_FAILED:"XMCP_I_TEST_DETERMINISTIC_KEY_FAILED",LOCAL_VERIFICATION_FAILED:"XMCP_I_TEST_LOCAL_VERIFICATION_FAILED",INVALID_TEST_CONFIGURATION:"XMCP_I_TEST_INVALID_CONFIG"}},80536:e=>{"use strict";e.exports=function(e,t,r){var a,s=" ",i=e.level,n=e.dataLevel,o=e.schema[t],c=e.schemaPath+e.util.getProperty(t),d=e.errSchemaPath+"/"+t,u=!e.opts.allErrors,l="data"+(n||""),h=e.opts.$data&&o&&o.$data;if(h?(s+=" var schema"+i+" = "+e.util.getData(o.$data,n,e.dataPathArr)+"; ",a="schema"+i):a=o,!h&&"number"!=typeof o)throw new Error(t+" must be number");s+="if ( ",h&&(s+=" ("+a+" !== undefined && typeof "+a+" != 'number') || "),s+=" "+l+".length "+("maxItems"==t?">":"<")+" "+a+") { ";var p=t,f=f||[];f.push(s),s="",!1!==e.createErrors?(s+=" { keyword: '"+(p||"_limitItems")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(d)+" , params: { limit: "+a+" } ",!1!==e.opts.messages&&(s+=" , message: 'should NOT have ",s+="maxItems"==t?"more":"fewer",s+=" than ",s+=h?"' + "+a+" + '":""+o,s+=" items' "),e.opts.verbose&&(s+=" , schema: ",s+=h?"validate.schema"+c:""+o,s+=" , parentSchema: validate.schema"+e.schemaPath+" , data: "+l+" "),s+=" } "):s+=" {} ";var m=s;return s=f.pop(),!e.compositeRule&&u?e.async?s+=" throw new ValidationError(["+m+"]); ":s+=" validate.errors = ["+m+"]; return false; ":s+=" var err = "+m+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",s+="} ",u&&(s+=" else { "),s}},80630:function(e,t,r){"use strict";var a=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.defaultErrorMap=void 0,t.setErrorMap=function(e){i=e},t.getErrorMap=function(){return i};const s=a(r(36886));t.defaultErrorMap=s.default;let i=s.default},82917:e=>{"use strict";e.exports=function(e,t,r){var a=" ",s=e.level,i=e.dataLevel,n=e.schema[t],o=e.schemaPath+e.util.getProperty(t),c=e.errSchemaPath+"/"+t,d=!e.opts.allErrors,u="data"+(i||""),l="valid"+s,h="errs__"+s,p=e.util.copy(e);p.level++;var f="valid"+p.level,m=e.schema.then,g=e.schema.else,y=void 0!==m&&(e.opts.strictKeywords?"object"==typeof m&&Object.keys(m).length>0||!1===m:e.util.schemaHasRules(m,e.RULES.all)),v=void 0!==g&&(e.opts.strictKeywords?"object"==typeof g&&Object.keys(g).length>0||!1===g:e.util.schemaHasRules(g,e.RULES.all)),_=p.baseId;if(y||v){var S;p.createErrors=!1,p.schema=n,p.schemaPath=o,p.errSchemaPath=c,a+=" var "+h+" = errors; var "+l+" = true; ";var b=e.compositeRule;e.compositeRule=p.compositeRule=!0,a+=" "+e.validate(p)+" ",p.baseId=_,p.createErrors=!0,a+=" errors = "+h+"; if (vErrors !== null) { if ("+h+") vErrors.length = "+h+"; else vErrors = null; } ",e.compositeRule=p.compositeRule=b,y?(a+=" if ("+f+") { ",p.schema=e.schema.then,p.schemaPath=e.schemaPath+".then",p.errSchemaPath=e.errSchemaPath+"/then",a+=" "+e.validate(p)+" ",p.baseId=_,a+=" "+l+" = "+f+"; ",y&&v?a+=" var "+(S="ifClause"+s)+" = 'then'; ":S="'then'",a+=" } ",v&&(a+=" else { ")):a+=" if (!"+f+") { ",v&&(p.schema=e.schema.else,p.schemaPath=e.schemaPath+".else",p.errSchemaPath=e.errSchemaPath+"/else",a+=" "+e.validate(p)+" ",p.baseId=_,a+=" "+l+" = "+f+"; ",y&&v?a+=" var "+(S="ifClause"+s)+" = 'else'; ":S="'else'",a+=" } "),a+=" if (!"+l+") { var err = ",!1!==e.createErrors?(a+=" { keyword: 'if' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { failingKeyword: "+S+" } ",!1!==e.opts.messages&&(a+=" , message: 'should match \"' + "+S+" + '\" schema' "),e.opts.verbose&&(a+=" , schema: validate.schema"+o+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+u+" "),a+=" } "):a+=" {} ",a+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",!e.compositeRule&&d&&(e.async?a+=" throw new ValidationError(vErrors); ":a+=" validate.errors = vErrors; return false; "),a+=" } ",d&&(a+=" else { ")}else d&&(a+=" if (true) { ");return a}},83010:e=>{"use strict";e.exports=function(e,t,r){var a,s=" ",i=e.level,n=e.dataLevel,o=e.schema[t],c=e.schemaPath+e.util.getProperty(t),d=e.errSchemaPath+"/"+t,u=!e.opts.allErrors,l="data"+(n||""),h=e.opts.$data&&o&&o.$data;if(h?(s+=" var schema"+i+" = "+e.util.getData(o.$data,n,e.dataPathArr)+"; ",a="schema"+i):a=o,!h&&"number"!=typeof o)throw new Error(t+" must be number");var p="maxLength"==t?">":"<";s+="if ( ",h&&(s+=" ("+a+" !== undefined && typeof "+a+" != 'number') || "),!1===e.opts.unicode?s+=" "+l+".length ":s+=" ucs2length("+l+") ",s+=" "+p+" "+a+") { ";var f=t,m=m||[];m.push(s),s="",!1!==e.createErrors?(s+=" { keyword: '"+(f||"_limitLength")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(d)+" , params: { limit: "+a+" } ",!1!==e.opts.messages&&(s+=" , message: 'should NOT be ",s+="maxLength"==t?"longer":"shorter",s+=" than ",s+=h?"' + "+a+" + '":""+o,s+=" characters' "),e.opts.verbose&&(s+=" , schema: ",s+=h?"validate.schema"+c:""+o,s+=" , parentSchema: validate.schema"+e.schemaPath+" , data: "+l+" "),s+=" } "):s+=" {} ";var g=s;return s=m.pop(),!e.compositeRule&&u?e.async?s+=" throw new ValidationError(["+g+"]); ":s+=" validate.errors = ["+g+"]; return false; ":s+=" var err = "+g+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",s+="} ",u&&(s+=" else { "),s}},86343:e=>{"use strict";e.exports=function(e,t,r){var a=" ",s=e.level,i=e.dataLevel,n=e.schema[t],o=e.schemaPath+e.util.getProperty(t),c=e.errSchemaPath+"/"+t,d=!e.opts.allErrors,u="data"+(i||""),l="errs__"+s,h=e.util.copy(e),p="";h.level++;var f="valid"+h.level,m="key"+s,g="idx"+s,y=h.dataLevel=e.dataLevel+1,v="data"+y,_="dataProperties"+s,S=Object.keys(n||{}).filter(R),b=e.schema.patternProperties||{},E=Object.keys(b).filter(R),P=e.schema.additionalProperties,I=S.length||E.length,w=!1===P,C="object"==typeof P&&Object.keys(P).length,T=e.opts.removeAdditional,D=w||C||T,x=e.opts.ownProperties,O=e.baseId,A=e.schema.required;if(A&&(!e.opts.$data||!A.$data)&&A.length<e.opts.loopRequired)var k=e.util.toHash(A);function R(e){return"__proto__"!==e}if(a+="var "+l+" = errors;var "+f+" = true;",x&&(a+=" var "+_+" = undefined;"),D){if(a+=x?" "+_+" = "+_+" || Object.keys("+u+"); for (var "+g+"=0; "+g+"<"+_+".length; "+g+"++) { var "+m+" = "+_+"["+g+"]; ":" for (var "+m+" in "+u+") { ",I){if(a+=" var isAdditional"+s+" = !(false ",S.length)if(S.length>8)a+=" || validate.schema"+o+".hasOwnProperty("+m+") ";else{var N=S;if(N)for(var j=-1,z=N.length-1;j<z;)G=N[j+=1],a+=" || "+m+" == "+e.util.toQuotedString(G)+" "}if(E.length){var $=E;if($)for(var M=-1,L=$.length-1;M<L;)ie=$[M+=1],a+=" || "+e.usePattern(ie)+".test("+m+") "}a+=" ); if (isAdditional"+s+") { "}if("all"==T)a+=" delete "+u+"["+m+"]; ";else{var F=e.errorPath,Z="' + "+m+" + '";if(e.opts._errorDataPathProperty&&(e.errorPath=e.util.getPathExpr(e.errorPath,m,e.opts.jsonPointers)),w)if(T)a+=" delete "+u+"["+m+"]; ";else{a+=" "+f+" = false; ";var V=c;c=e.errSchemaPath+"/additionalProperties",(re=re||[]).push(a),a="",!1!==e.createErrors?(a+=" { keyword: 'additionalProperties' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { additionalProperty: '"+Z+"' } ",!1!==e.opts.messages&&(a+=" , message: '",e.opts._errorDataPathProperty?a+="is an invalid additional property":a+="should NOT have additional properties",a+="' "),e.opts.verbose&&(a+=" , schema: false , parentSchema: validate.schema"+e.schemaPath+" , data: "+u+" "),a+=" } "):a+=" {} ";var K=a;a=re.pop(),!e.compositeRule&&d?e.async?a+=" throw new ValidationError(["+K+"]); ":a+=" validate.errors = ["+K+"]; return false; ":a+=" var err = "+K+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",c=V,d&&(a+=" break; ")}else if(C)if("failing"==T){a+=" var "+l+" = errors; ";var U=e.compositeRule;e.compositeRule=h.compositeRule=!0,h.schema=P,h.schemaPath=e.schemaPath+".additionalProperties",h.errSchemaPath=e.errSchemaPath+"/additionalProperties",h.errorPath=e.opts._errorDataPathProperty?e.errorPath:e.util.getPathExpr(e.errorPath,m,e.opts.jsonPointers);var H=u+"["+m+"]";h.dataPathArr[y]=m;var q=e.validate(h);h.baseId=O,e.util.varOccurences(q,v)<2?a+=" "+e.util.varReplace(q,v,H)+" ":a+=" var "+v+" = "+H+"; "+q+" ",a+=" if (!"+f+") { errors = "+l+"; if (validate.errors !== null) { if (errors) validate.errors.length = errors; else validate.errors = null; } delete "+u+"["+m+"]; } ",e.compositeRule=h.compositeRule=U}else h.schema=P,h.schemaPath=e.schemaPath+".additionalProperties",h.errSchemaPath=e.errSchemaPath+"/additionalProperties",h.errorPath=e.opts._errorDataPathProperty?e.errorPath:e.util.getPathExpr(e.errorPath,m,e.opts.jsonPointers),H=u+"["+m+"]",h.dataPathArr[y]=m,q=e.validate(h),h.baseId=O,e.util.varOccurences(q,v)<2?a+=" "+e.util.varReplace(q,v,H)+" ":a+=" var "+v+" = "+H+"; "+q+" ",d&&(a+=" if (!"+f+") break; ");e.errorPath=F}I&&(a+=" } "),a+=" } ",d&&(a+=" if ("+f+") { ",p+="}")}var B=e.opts.useDefaults&&!e.compositeRule;if(S.length){var W=S;if(W)for(var G,J=-1,X=W.length-1;J<X;){var Q=n[G=W[J+=1]];if(e.opts.strictKeywords?"object"==typeof Q&&Object.keys(Q).length>0||!1===Q:e.util.schemaHasRules(Q,e.RULES.all)){var Y=e.util.getProperty(G),ee=(H=u+Y,B&&void 0!==Q.default);if(h.schema=Q,h.schemaPath=o+Y,h.errSchemaPath=c+"/"+e.util.escapeFragment(G),h.errorPath=e.util.getPath(e.errorPath,G,e.opts.jsonPointers),h.dataPathArr[y]=e.util.toQuotedString(G),q=e.validate(h),h.baseId=O,e.util.varOccurences(q,v)<2){q=e.util.varReplace(q,v,H);var te=H}else te=v,a+=" var "+v+" = "+H+"; ";if(ee)a+=" "+q+" ";else{if(k&&k[G]){a+=" if ( "+te+" === undefined ",x&&(a+=" || ! Object.prototype.hasOwnProperty.call("+u+", '"+e.util.escapeQuotes(G)+"') "),a+=") { "+f+" = false; ",F=e.errorPath,V=c;var re,ae=e.util.escapeQuotes(G);e.opts._errorDataPathProperty&&(e.errorPath=e.util.getPath(F,G,e.opts.jsonPointers)),c=e.errSchemaPath+"/required",(re=re||[]).push(a),a="",!1!==e.createErrors?(a+=" { keyword: 'required' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { missingProperty: '"+ae+"' } ",!1!==e.opts.messages&&(a+=" , message: '",e.opts._errorDataPathProperty?a+="is a required property":a+="should have required property \\'"+ae+"\\'",a+="' "),e.opts.verbose&&(a+=" , schema: validate.schema"+o+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+u+" "),a+=" } "):a+=" {} ",K=a,a=re.pop(),!e.compositeRule&&d?e.async?a+=" throw new ValidationError(["+K+"]); ":a+=" validate.errors = ["+K+"]; return false; ":a+=" var err = "+K+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",c=V,e.errorPath=F,a+=" } else { "}else d?(a+=" if ( "+te+" === undefined ",x&&(a+=" || ! Object.prototype.hasOwnProperty.call("+u+", '"+e.util.escapeQuotes(G)+"') "),a+=") { "+f+" = true; } else { "):(a+=" if ("+te+" !== undefined ",x&&(a+=" && Object.prototype.hasOwnProperty.call("+u+", '"+e.util.escapeQuotes(G)+"') "),a+=" ) { ");a+=" "+q+" } "}}d&&(a+=" if ("+f+") { ",p+="}")}}if(E.length){var se=E;if(se)for(var ie,ne=-1,oe=se.length-1;ne<oe;)Q=b[ie=se[ne+=1]],(e.opts.strictKeywords?"object"==typeof Q&&Object.keys(Q).length>0||!1===Q:e.util.schemaHasRules(Q,e.RULES.all))&&(h.schema=Q,h.schemaPath=e.schemaPath+".patternProperties"+e.util.getProperty(ie),h.errSchemaPath=e.errSchemaPath+"/patternProperties/"+e.util.escapeFragment(ie),a+=x?" "+_+" = "+_+" || Object.keys("+u+"); for (var "+g+"=0; "+g+"<"+_+".length; "+g+"++) { var "+m+" = "+_+"["+g+"]; ":" for (var "+m+" in "+u+") { ",a+=" if ("+e.usePattern(ie)+".test("+m+")) { ",h.errorPath=e.util.getPathExpr(e.errorPath,m,e.opts.jsonPointers),H=u+"["+m+"]",h.dataPathArr[y]=m,q=e.validate(h),h.baseId=O,e.util.varOccurences(q,v)<2?a+=" "+e.util.varReplace(q,v,H)+" ":a+=" var "+v+" = "+H+"; "+q+" ",d&&(a+=" if (!"+f+") break; "),a+=" } ",d&&(a+=" else "+f+" = true; "),a+=" } ",d&&(a+=" if ("+f+") { ",p+="}"))}return d&&(a+=" "+p+" if ("+l+" == errors) {"),a}},86819:function(e,t,r){"use strict";var a=this&&this.__createBinding||(Object.create?function(e,t,r,a){void 0===a&&(a=r);var s=Object.getOwnPropertyDescriptor(t,r);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,a,s)}:function(e,t,r,a){void 0===a&&(a=r),e[a]=t[r]}),s=this&&this.__exportStar||function(e,t){for(var r in e)"default"===r||Object.prototype.hasOwnProperty.call(t,r)||a(t,e,r)};Object.defineProperty(t,"__esModule",{value:!0}),s(r(46511),t),s(r(74161),t)},90083:e=>{"use strict";e.exports=function(e,t,r){var a=" ",s=e.level,i=e.dataLevel,n=e.schema[t],o=e.schemaPath+e.util.getProperty(t),c=e.errSchemaPath+"/"+t,d=!e.opts.allErrors,u="data"+(i||""),l="errs__"+s,h=e.util.copy(e),p="";h.level++;var f="valid"+h.level,m={},g={},y=e.opts.ownProperties;for(b in n)if("__proto__"!=b){var v=n[b],_=Array.isArray(v)?g:m;_[b]=v}a+="var "+l+" = errors;";var S=e.errorPath;for(var b in a+="var missing"+s+";",g)if((_=g[b]).length){if(a+=" if ( "+u+e.util.getProperty(b)+" !== undefined ",y&&(a+=" && Object.prototype.hasOwnProperty.call("+u+", '"+e.util.escapeQuotes(b)+"') "),d){a+=" && ( ";var E=_;if(E)for(var P=-1,I=E.length-1;P<I;)O=E[P+=1],P&&(a+=" || "),a+=" ( ( "+(N=u+(R=e.util.getProperty(O)))+" === undefined ",y&&(a+=" || ! Object.prototype.hasOwnProperty.call("+u+", '"+e.util.escapeQuotes(O)+"') "),a+=") && (missing"+s+" = "+e.util.toQuotedString(e.opts.jsonPointers?O:R)+") ) ";a+=")) { ";var w="missing"+s,C="' + "+w+" + '";e.opts._errorDataPathProperty&&(e.errorPath=e.opts.jsonPointers?e.util.getPathExpr(S,w,!0):S+" + "+w);var T=T||[];T.push(a),a="",!1!==e.createErrors?(a+=" { keyword: 'dependencies' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { property: '"+e.util.escapeQuotes(b)+"', missingProperty: '"+C+"', depsCount: "+_.length+", deps: '"+e.util.escapeQuotes(1==_.length?_[0]:_.join(", "))+"' } ",!1!==e.opts.messages&&(a+=" , message: 'should have ",1==_.length?a+="property "+e.util.escapeQuotes(_[0]):a+="properties "+e.util.escapeQuotes(_.join(", ")),a+=" when property "+e.util.escapeQuotes(b)+" is present' "),e.opts.verbose&&(a+=" , schema: validate.schema"+o+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+u+" "),a+=" } "):a+=" {} ";var D=a;a=T.pop(),!e.compositeRule&&d?e.async?a+=" throw new ValidationError(["+D+"]); ":a+=" validate.errors = ["+D+"]; return false; ":a+=" var err = "+D+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; "}else{a+=" ) { ";var x=_;if(x)for(var O,A=-1,k=x.length-1;A<k;){O=x[A+=1];var R=e.util.getProperty(O),N=(C=e.util.escapeQuotes(O),u+R);e.opts._errorDataPathProperty&&(e.errorPath=e.util.getPath(S,O,e.opts.jsonPointers)),a+=" if ( "+N+" === undefined ",y&&(a+=" || ! Object.prototype.hasOwnProperty.call("+u+", '"+e.util.escapeQuotes(O)+"') "),a+=") { var err = ",!1!==e.createErrors?(a+=" { keyword: 'dependencies' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { property: '"+e.util.escapeQuotes(b)+"', missingProperty: '"+C+"', depsCount: "+_.length+", deps: '"+e.util.escapeQuotes(1==_.length?_[0]:_.join(", "))+"' } ",!1!==e.opts.messages&&(a+=" , message: 'should have ",1==_.length?a+="property "+e.util.escapeQuotes(_[0]):a+="properties "+e.util.escapeQuotes(_.join(", ")),a+=" when property "+e.util.escapeQuotes(b)+" is present' "),e.opts.verbose&&(a+=" , schema: validate.schema"+o+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+u+" "),a+=" } "):a+=" {} ",a+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } "}}a+=" } ",d&&(p+="}",a+=" else { ")}e.errorPath=S;var j=h.baseId;for(var b in m)v=m[b],(e.opts.strictKeywords?"object"==typeof v&&Object.keys(v).length>0||!1===v:e.util.schemaHasRules(v,e.RULES.all))&&(a+=" "+f+" = true; if ( "+u+e.util.getProperty(b)+" !== undefined ",y&&(a+=" && Object.prototype.hasOwnProperty.call("+u+", '"+e.util.escapeQuotes(b)+"') "),a+=") { ",h.schema=v,h.schemaPath=o+e.util.getProperty(b),h.errSchemaPath=c+"/"+e.util.escapeFragment(b),a+=" "+e.validate(h)+" ",h.baseId=j,a+=" } ",d&&(a+=" if ("+f+") { ",p+="}"));return d&&(a+=" "+p+" if ("+l+" == errors) {"),a}},90088:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.CONTENT_HASH_REGEX=t.RECEIPT_SCHEMA_ID=t.STORAGE_MODE_ENV_VAR=t.DEFAULT_STORAGE_MODE=t.KTA_BASE_URL=t.CLAIM_TOKEN_TTL_HOURS=t.MCP_I_CAPABILITIES=t.StorageConfigSchema=t.DelegationResponseSchema=t.ReceiptSchema=t.StorageModeSchema=t.DelegationRequestSchema=t.DelegationSchema=t.AgentStatusSchema=t.MirrorStatusSchema=t.ClaimTokenSchema=t.RegistrationResultSchema=t.RegistrationInputSchema=void 0;const a=r(90315);t.RegistrationInputSchema=a.z.object({agentDID:a.z.string().min(1),agentURL:a.z.string().url(),verificationEndpoint:a.z.string().url(),conformanceCapabilities:a.z.array(a.z.enum(["handshake","signing","verification"])),metadata:a.z.record(a.z.any()).optional()}),t.RegistrationResultSchema=a.z.object({agentDID:a.z.string().min(1),agentURL:a.z.string().url(),agentId:a.z.string().min(1),agentSlug:a.z.string().min(1),claimURL:a.z.string().url().optional(),verificationEndpoint:a.z.string().url(),conformanceCapabilities:a.z.tuple([a.z.literal("handshake"),a.z.literal("signing"),a.z.literal("verification")]),mirrorStatus:a.z.enum(["pending","success","error"]),mirrorLink:a.z.string().url().optional()}),t.ClaimTokenSchema=a.z.object({token:a.z.string().min(1),expiresAt:a.z.number().int().positive(),ttlHours:a.z.number().int().positive().default(24)}),t.MirrorStatusSchema=a.z.object({status:a.z.enum(["pending","success","error"]),lastUpdated:a.z.number().int().positive(),errorMessage:a.z.string().optional(),registryURL:a.z.string().url().optional()}),t.AgentStatusSchema=a.z.object({did:a.z.string().min(1),kid:a.z.string().min(1),ktaURL:a.z.string().url(),mirrorStatus:t.MirrorStatusSchema,lastHandshake:a.z.number().int().positive().optional()}),t.DelegationSchema=a.z.object({issuer:a.z.string().min(1),subject:a.z.string().min(1),scopes:a.z.array(a.z.string()),nbf:a.z.number().int().positive(),exp:a.z.number().int().positive(),aud:a.z.string().optional(),delegationRef:a.z.string().optional()}),t.DelegationRequestSchema=a.z.object({subject:a.z.string().min(1),scopes:a.z.array(a.z.string()),duration:a.z.number().int().positive().optional(),audience:a.z.string().optional()}),t.StorageModeSchema=a.z.enum(["ktaEncrypted","hybridReceiptsOnly","selfHostedAuthoritative"]),t.ReceiptSchema=a.z.object({$schema:a.z.literal("https://schemas.kya-os.ai/mcpi/receipt/v1.0.0.json").optional(),ref:a.z.string().min(1),contentHash:a.z.string().regex(/^sha256:[a-f0-9]{64}$/),action:a.z.enum(["issue","revoke"]),ts:a.z.union([a.z.string().datetime(),a.z.number().int().positive()]),logIndex:a.z.number().int().nonnegative(),logRoot:a.z.string().min(1),inclusionProof:a.z.array(a.z.string())}),t.DelegationResponseSchema=a.z.object({delegation:t.DelegationSchema,receipt:t.ReceiptSchema,encryptedPayload:a.z.string().optional()}),t.StorageConfigSchema=a.z.object({mode:t.StorageModeSchema,encryptionEnabled:a.z.boolean().default(!1),receiptVerificationEnabled:a.z.boolean().default(!0),ktaBaseURL:a.z.string().url().default("https://knowthat.ai")}),t.MCP_I_CAPABILITIES=["handshake","signing","verification"],t.CLAIM_TOKEN_TTL_HOURS=24,t.KTA_BASE_URL="https://knowthat.ai",t.DEFAULT_STORAGE_MODE="ktaEncrypted",t.STORAGE_MODE_ENV_VAR="MCPI_STORAGE_MODE",t.RECEIPT_SCHEMA_ID="https://schemas.kya-os.ai/mcpi/receipt/v1.0.0.json",t.CONTENT_HASH_REGEX=/^sha256:[a-f0-9]{64}$/},90315:function(e,t,r){"use strict";var a=this&&this.__createBinding||(Object.create?function(e,t,r,a){void 0===a&&(a=r);var s=Object.getOwnPropertyDescriptor(t,r);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,a,s)}:function(e,t,r,a){void 0===a&&(a=r),e[a]=t[r]}),s=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),i=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)"default"!==r&&Object.prototype.hasOwnProperty.call(e,r)&&a(t,e,r);return s(t,e),t},n=this&&this.__exportStar||function(e,t){for(var r in e)"default"===r||Object.prototype.hasOwnProperty.call(t,r)||a(t,e,r)};Object.defineProperty(t,"__esModule",{value:!0}),t.z=void 0;const o=i(r(99394));t.z=o,n(r(99394),t),t.default=o},90533:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AGENTSHIELD_METHODS=t.AGENTSHIELD_ENDPOINTS=t.AGENTSHIELD_API_BASE=t.revokeDelegationAPIResponseSchema=t.revokeDelegationResponseSchema=t.revokeDelegationRequestSchema=t.createDelegationAPIResponseSchema=t.createDelegationResponseSchema=t.createDelegationRequestSchema=t.toolProtectionConfigAPIResponseSchema=t.toolProtectionConfigResponseSchema=t.agentShieldToolProtectionSchema=t.verifyDelegationAPIResponseSchema=t.verifyDelegationResponseSchema=t.verifyDelegationRequestSchema=t.delegationCredentialSchema=t.proofSubmissionResponseSchema=t.proofSubmissionRequestSchema=t.agentShieldAPIResponseSchema=t.agentShieldAPIErrorSchema=t.AgentShieldAPIError=void 0;var a=r(39308);Object.defineProperty(t,"AgentShieldAPIError",{enumerable:!0,get:function(){return a.AgentShieldAPIError}});var s=r(71089);Object.defineProperty(t,"agentShieldAPIErrorSchema",{enumerable:!0,get:function(){return s.agentShieldAPIErrorSchema}}),Object.defineProperty(t,"agentShieldAPIResponseSchema",{enumerable:!0,get:function(){return s.agentShieldAPIResponseSchema}}),Object.defineProperty(t,"proofSubmissionRequestSchema",{enumerable:!0,get:function(){return s.proofSubmissionRequestSchema}}),Object.defineProperty(t,"proofSubmissionResponseSchema",{enumerable:!0,get:function(){return s.proofSubmissionResponseSchema}}),Object.defineProperty(t,"delegationCredentialSchema",{enumerable:!0,get:function(){return s.delegationCredentialSchema}}),Object.defineProperty(t,"verifyDelegationRequestSchema",{enumerable:!0,get:function(){return s.verifyDelegationRequestSchema}}),Object.defineProperty(t,"verifyDelegationResponseSchema",{enumerable:!0,get:function(){return s.verifyDelegationResponseSchema}}),Object.defineProperty(t,"verifyDelegationAPIResponseSchema",{enumerable:!0,get:function(){return s.verifyDelegationAPIResponseSchema}}),Object.defineProperty(t,"agentShieldToolProtectionSchema",{enumerable:!0,get:function(){return s.agentShieldToolProtectionSchema}}),Object.defineProperty(t,"toolProtectionConfigResponseSchema",{enumerable:!0,get:function(){return s.toolProtectionConfigResponseSchema}}),Object.defineProperty(t,"toolProtectionConfigAPIResponseSchema",{enumerable:!0,get:function(){return s.toolProtectionConfigAPIResponseSchema}}),Object.defineProperty(t,"createDelegationRequestSchema",{enumerable:!0,get:function(){return s.createDelegationRequestSchema}}),Object.defineProperty(t,"createDelegationResponseSchema",{enumerable:!0,get:function(){return s.createDelegationResponseSchema}}),Object.defineProperty(t,"createDelegationAPIResponseSchema",{enumerable:!0,get:function(){return s.createDelegationAPIResponseSchema}}),Object.defineProperty(t,"revokeDelegationRequestSchema",{enumerable:!0,get:function(){return s.revokeDelegationRequestSchema}}),Object.defineProperty(t,"revokeDelegationResponseSchema",{enumerable:!0,get:function(){return s.revokeDelegationResponseSchema}}),Object.defineProperty(t,"revokeDelegationAPIResponseSchema",{enumerable:!0,get:function(){return s.revokeDelegationAPIResponseSchema}});var i=r(51063);Object.defineProperty(t,"AGENTSHIELD_API_BASE",{enumerable:!0,get:function(){return i.AGENTSHIELD_API_BASE}}),Object.defineProperty(t,"AGENTSHIELD_ENDPOINTS",{enumerable:!0,get:function(){return i.AGENTSHIELD_ENDPOINTS}}),Object.defineProperty(t,"AGENTSHIELD_METHODS",{enumerable:!0,get:function(){return i.AGENTSHIELD_METHODS}})},91939:e=>{"use strict";e.exports=function(e,t,r){var a=" ",s=e.level,i=e.dataLevel,n=e.schema[t],o=e.schemaPath+e.util.getProperty(t),c=e.errSchemaPath+"/"+t,d=!e.opts.allErrors,u="data"+(i||""),l="valid"+s,h=e.opts.$data&&n&&n.$data;h&&(a+=" var schema"+s+" = "+e.util.getData(n.$data,i,e.dataPathArr)+"; ");var p="schema"+s;if(!h)if(n.length<e.opts.loopRequired&&e.schema.properties&&Object.keys(e.schema.properties).length){var f=[],m=n;if(m)for(var g,y=-1,v=m.length-1;y<v;){g=m[y+=1];var _=e.schema.properties[g];_&&(e.opts.strictKeywords?"object"==typeof _&&Object.keys(_).length>0||!1===_:e.util.schemaHasRules(_,e.RULES.all))||(f[f.length]=g)}}else f=n;if(h||f.length){var S=e.errorPath,b=h||f.length>=e.opts.loopRequired,E=e.opts.ownProperties;if(d)if(a+=" var missing"+s+"; ",b){h||(a+=" var "+p+" = validate.schema"+o+"; ");var P="' + "+(x="schema"+s+"["+(T="i"+s)+"]")+" + '";e.opts._errorDataPathProperty&&(e.errorPath=e.util.getPathExpr(S,x,e.opts.jsonPointers)),a+=" var "+l+" = true; ",h&&(a+=" if (schema"+s+" === undefined) "+l+" = true; else if (!Array.isArray(schema"+s+")) "+l+" = false; else {"),a+=" for (var "+T+" = 0; "+T+" < "+p+".length; "+T+"++) { "+l+" = "+u+"["+p+"["+T+"]] !== undefined ",E&&(a+=" && Object.prototype.hasOwnProperty.call("+u+", "+p+"["+T+"]) "),a+="; if (!"+l+") break; } ",h&&(a+=" } "),a+=" if (!"+l+") { ",(w=w||[]).push(a),a="",!1!==e.createErrors?(a+=" { keyword: 'required' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { missingProperty: '"+P+"' } ",!1!==e.opts.messages&&(a+=" , message: '",e.opts._errorDataPathProperty?a+="is a required property":a+="should have required property \\'"+P+"\\'",a+="' "),e.opts.verbose&&(a+=" , schema: validate.schema"+o+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+u+" "),a+=" } "):a+=" {} ";var I=a;a=w.pop(),!e.compositeRule&&d?e.async?a+=" throw new ValidationError(["+I+"]); ":a+=" validate.errors = ["+I+"]; return false; ":a+=" var err = "+I+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",a+=" } else { "}else{a+=" if ( ";var w,C=f;if(C)for(var T=-1,D=C.length-1;T<D;)A=C[T+=1],T&&(a+=" || "),a+=" ( ( "+(j=u+(N=e.util.getProperty(A)))+" === undefined ",E&&(a+=" || ! Object.prototype.hasOwnProperty.call("+u+", '"+e.util.escapeQuotes(A)+"') "),a+=") && (missing"+s+" = "+e.util.toQuotedString(e.opts.jsonPointers?A:N)+") ) ";a+=") { ",P="' + "+(x="missing"+s)+" + '",e.opts._errorDataPathProperty&&(e.errorPath=e.opts.jsonPointers?e.util.getPathExpr(S,x,!0):S+" + "+x),(w=w||[]).push(a),a="",!1!==e.createErrors?(a+=" { keyword: 'required' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { missingProperty: '"+P+"' } ",!1!==e.opts.messages&&(a+=" , message: '",e.opts._errorDataPathProperty?a+="is a required property":a+="should have required property \\'"+P+"\\'",a+="' "),e.opts.verbose&&(a+=" , schema: validate.schema"+o+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+u+" "),a+=" } "):a+=" {} ",I=a,a=w.pop(),!e.compositeRule&&d?e.async?a+=" throw new ValidationError(["+I+"]); ":a+=" validate.errors = ["+I+"]; return false; ":a+=" var err = "+I+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",a+=" } else { "}else if(b){var x;h||(a+=" var "+p+" = validate.schema"+o+"; "),P="' + "+(x="schema"+s+"["+(T="i"+s)+"]")+" + '",e.opts._errorDataPathProperty&&(e.errorPath=e.util.getPathExpr(S,x,e.opts.jsonPointers)),h&&(a+=" if ("+p+" && !Array.isArray("+p+")) { var err = ",!1!==e.createErrors?(a+=" { keyword: 'required' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { missingProperty: '"+P+"' } ",!1!==e.opts.messages&&(a+=" , message: '",e.opts._errorDataPathProperty?a+="is a required property":a+="should have required property \\'"+P+"\\'",a+="' "),e.opts.verbose&&(a+=" , schema: validate.schema"+o+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+u+" "),a+=" } "):a+=" {} ",a+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } else if ("+p+" !== undefined) { "),a+=" for (var "+T+" = 0; "+T+" < "+p+".length; "+T+"++) { if ("+u+"["+p+"["+T+"]] === undefined ",E&&(a+=" || ! Object.prototype.hasOwnProperty.call("+u+", "+p+"["+T+"]) "),a+=") { var err = ",!1!==e.createErrors?(a+=" { keyword: 'required' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { missingProperty: '"+P+"' } ",!1!==e.opts.messages&&(a+=" , message: '",e.opts._errorDataPathProperty?a+="is a required property":a+="should have required property \\'"+P+"\\'",a+="' "),e.opts.verbose&&(a+=" , schema: validate.schema"+o+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+u+" "),a+=" } "):a+=" {} ",a+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } } ",h&&(a+=" } ")}else{var O=f;if(O)for(var A,k=-1,R=O.length-1;k<R;){A=O[k+=1];var N=e.util.getProperty(A),j=(P=e.util.escapeQuotes(A),u+N);e.opts._errorDataPathProperty&&(e.errorPath=e.util.getPath(S,A,e.opts.jsonPointers)),a+=" if ( "+j+" === undefined ",E&&(a+=" || ! Object.prototype.hasOwnProperty.call("+u+", '"+e.util.escapeQuotes(A)+"') "),a+=") { var err = ",!1!==e.createErrors?(a+=" { keyword: 'required' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { missingProperty: '"+P+"' } ",!1!==e.opts.messages&&(a+=" , message: '",e.opts._errorDataPathProperty?a+="is a required property":a+="should have required property \\'"+P+"\\'",a+="' "),e.opts.verbose&&(a+=" , schema: validate.schema"+o+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+u+" "),a+=" } "):a+=" {} ",a+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } "}}e.errorPath=S}else d&&(a+=" if (true) {");return a}},92881:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.OAUTH_CORS_HEADERS=t.PREFLIGHT_CORS_HEADERS=t.MCP_CORS_HEADERS=t.WELL_KNOWN_CORS_HEADERS=void 0,t.mergeCORSHeaders=function(e,r=t.WELL_KNOWN_CORS_HEADERS){return{...e,...r}},t.applyCORSHeaders=function(e,r=t.MCP_CORS_HEADERS){Object.entries(r).forEach(([t,r])=>{void 0!==r&&e.setHeader(t,r)})},t.WELL_KNOWN_CORS_HEADERS={"Access-Control-Allow-Origin":"*",Vary:"Origin"},t.MCP_CORS_HEADERS={"Access-Control-Allow-Origin":"*","Access-Control-Expose-Headers":"mcp-session-id",Vary:"Origin"},t.PREFLIGHT_CORS_HEADERS={"Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":"GET, POST, OPTIONS","Access-Control-Allow-Headers":"Content-Type, Authorization, mcp-session-id, mcp-protocol-version",Vary:"Origin"},t.OAUTH_CORS_HEADERS={"Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":"GET, POST, OPTIONS","Access-Control-Allow-Headers":"Content-Type, Authorization, Accept, mcp-protocol-version","Access-Control-Expose-Headers":"Content-Type",Vary:"Origin"}},94423:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.CascadingRevocationManager=void 0,t.createCascadingRevocationManager=function(e,t){return new r(e,t)};class r{graph;statusList;constructor(e,t){this.graph=e,this.statusList=t}async revokeDelegation(e,t={}){const r=t.maxDepth||100,a=[],s=await this.graph.getNode(e);if(!s)throw new Error(`Delegation not found: ${e}`);const i=await this.graph.getDepth(e);if(i>r)throw new Error(`Delegation depth ${i} exceeds maximum ${r}`);const n=await this.revokeNode(s,!0,t.reason,t.dryRun);a.push(n),t.onRevoke&&await t.onRevoke(n);const o=await this.graph.getDescendants(e);for(const r of o){const s=await this.revokeNode(r,!1,`Cascaded from ${e}`,t.dryRun,e);a.push(s),t.onRevoke&&await t.onRevoke(s)}return a}async revokeNode(e,t,r,a,s){const i={delegationId:e.id,isRoot:t,parentId:s,timestamp:Date.now(),reason:r};if(a)return i;if(e.credentialStatusId){const t=this.parseCredentialStatus(e.credentialStatusId);t&&await this.statusList.updateStatus(t,!0)}return i}async restoreDelegation(e){const t=await this.graph.getNode(e);if(!t)throw new Error(`Delegation not found: ${e}`);const r={delegationId:t.id,isRoot:!0,timestamp:Date.now(),reason:"Restored"};if(t.credentialStatusId){const e=this.parseCredentialStatus(t.credentialStatusId);e&&await this.statusList.updateStatus(e,!1)}return r}async isRevoked(e){const t=await this.graph.getChain(e);for(const r of t.reverse())if(r.credentialStatusId){const t=this.parseCredentialStatus(r.credentialStatusId);if(t&&await this.statusList.checkStatus(t))return{revoked:!0,reason:r.id===e?"Directly revoked":"Ancestor revoked",revokedAncestor:r.id===e?void 0:r.id}}return{revoked:!1}}async getRevokedInSubtree(e){const t=await this.graph.getDescendants(e),r=[];(await this.isRevoked(e)).revoked&&r.push(e);for(const e of t)(await this.isRevoked(e.id)).revoked&&r.push(e.id);return r}parseCredentialStatus(e){const t=e.match(/^(.+)#(\d+)$/);if(!t)return null;const[,r,a]=t;return{id:e,type:"StatusList2021Entry",statusPurpose:"revocation",statusListIndex:parseInt(a,10).toString(),statusListCredential:r}}async validateDelegation(e){const t=await this.isRevoked(e);if(t.revoked)return{valid:!1,reason:t.revokedAncestor?`Ancestor ${t.revokedAncestor} is revoked`:"Delegation is revoked"};const r=await this.graph.validateChain(e);return r.valid?{valid:!0}:r}}t.CascadingRevocationManager=r},95545:e=>{"use strict";e.exports=function(e,t,r){var a=" ",s=e.level,i=e.dataLevel,n=e.schema[t],o=e.schemaPath+e.util.getProperty(t),c=e.errSchemaPath+"/"+t,d=!e.opts.allErrors,u="data"+(i||"");if(!1===e.opts.format)return d&&(a+=" if (true) { "),a;var l,h=e.opts.$data&&n&&n.$data;h?(a+=" var schema"+s+" = "+e.util.getData(n.$data,i,e.dataPathArr)+"; ",l="schema"+s):l=n;var p=e.opts.unknownFormats,f=Array.isArray(p);if(h)a+=" var "+(m="format"+s)+" = formats["+l+"]; var "+(g="isObject"+s)+" = typeof "+m+" == 'object' && !("+m+" instanceof RegExp) && "+m+".validate; var "+(y="formatType"+s)+" = "+g+" && "+m+".type || 'string'; if ("+g+") { ",e.async&&(a+=" var async"+s+" = "+m+".async; "),a+=" "+m+" = "+m+".validate; } if ( ",h&&(a+=" ("+l+" !== undefined && typeof "+l+" != 'string') || "),a+=" (","ignore"!=p&&(a+=" ("+l+" && !"+m+" ",f&&(a+=" && self._opts.unknownFormats.indexOf("+l+") == -1 "),a+=") || "),a+=" ("+m+" && "+y+" == '"+r+"' && !(typeof "+m+" == 'function' ? ",e.async?a+=" (async"+s+" ? await "+m+"("+u+") : "+m+"("+u+")) ":a+=" "+m+"("+u+") ",a+=" : "+m+".test("+u+"))))) {";else{var m;if(!(m=e.formats[n])){if("ignore"==p)return e.logger.warn('unknown format "'+n+'" ignored in schema at path "'+e.errSchemaPath+'"'),d&&(a+=" if (true) { "),a;if(f&&p.indexOf(n)>=0)return d&&(a+=" if (true) { "),a;throw new Error('unknown format "'+n+'" is used in schema at path "'+e.errSchemaPath+'"')}var g,y=(g="object"==typeof m&&!(m instanceof RegExp)&&m.validate)&&m.type||"string";if(g){var v=!0===m.async;m=m.validate}if(y!=r)return d&&(a+=" if (true) { "),a;if(v){if(!e.async)throw new Error("async format in sync schema");a+=" if (!(await "+(_="formats"+e.util.getProperty(n)+".validate")+"("+u+"))) { "}else{a+=" if (! ";var _="formats"+e.util.getProperty(n);g&&(_+=".validate"),a+="function"==typeof m?" "+_+"("+u+") ":" "+_+".test("+u+") ",a+=") { "}}var S=S||[];S.push(a),a="",!1!==e.createErrors?(a+=" { keyword: 'format' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { format: ",a+=h?""+l:""+e.util.toQuotedString(n),a+=" } ",!1!==e.opts.messages&&(a+=" , message: 'should match format \"",a+=h?"' + "+l+" + '":""+e.util.escapeQuotes(n),a+="\"' "),e.opts.verbose&&(a+=" , schema: ",a+=h?"validate.schema"+o:""+e.util.toQuotedString(n),a+=" , parentSchema: validate.schema"+e.schemaPath+" , data: "+u+" "),a+=" } "):a+=" {} ";var b=a;return a=S.pop(),!e.compositeRule&&d?e.async?a+=" throw new ValidationError(["+b+"]); ":a+=" validate.errors = ["+b+"]; return false; ":a+=" var err = "+b+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",a+=" } ",d&&(a+=" else { "),a}},95630:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ToolProtectionService=void 0;const a=r(59236);t.ToolProtectionService=class{config;cache;constructor(e,t){this.config=e,this.cache=t}getProjectId(){return this.config.projectId}async getStaleCache(e){if(!1===this.config.allowStaleCache)return null;if(!(this.cache instanceof a.InMemoryToolProtectionCache))return null;const t=this.cache.getStale(e);if(!t)return null;const r=this.cache.getExpiresAt(e);if(!r)return null;const s=Date.now(),i=this.config.maxStaleCacheAge??864e5;return s>r&&s-r<=i?(this.config.debug&&console.log("[ToolProtectionService] Using stale cache",{cacheKey:e,expiredAt:new Date(r).toISOString(),staleAgeMs:s-r,maxStaleAgeMs:i}),t):null}async getToolProtectionConfig(e){const t=this.config.projectId?`config:tool-protections:${this.config.projectId}`:`agent:${e}`,r=await this.cache.get(t);if(r)return this.config.debug&&console.log("[ToolProtectionService] Cache hit",{cacheKey:t,agentDid:e.slice(0,20)+"...",projectId:this.config.projectId||"none",toolCount:Object.keys(r.toolProtections).length}),r;this.config.debug&&console.log("[ToolProtectionService] Cache miss, fetching from API",{cacheKey:t,agentDid:e.slice(0,20)+"...",projectId:this.config.projectId||"none"});try{const r=await this.fetchFromApi(e),a={};if(r.data.toolProtections)for(const[e,t]of Object.entries(r.data.toolProtections)){const r=t.requiresDelegation??t.requires_delegation??!1,s=t.requiredScopes??t.required_scopes??t.scopes??[];a[e]={requiresDelegation:r,requiredScopes:s}}else if(r.data.tools)if(Array.isArray(r.data.tools))for(const e of r.data.tools){const t=e.name;if(!t){this.config.debug&&console.warn("[ToolProtectionService] Tool missing name in array format",e);continue}const r=e.requiresDelegation??e.requires_delegation??!1,s=e.requiredScopes??e.required_scopes??e.scopes??[];a[t]={requiresDelegation:r,requiredScopes:s}}else for(const[e,t]of Object.entries(r.data.tools)){const r=t.requiresDelegation??t.requires_delegation??!1,s=t.requiredScopes??t.required_scopes??t.scopes??[];a[e]={requiresDelegation:r,requiredScopes:s}}const s={toolProtections:a},i=this.config.cacheTtl??3e5;return await this.cache.set(t,s,i),console.log("[ToolProtectionService] Config loaded",{toolCount:Object.keys(a).length,protectedTools:Object.entries(a).filter(([e,t])=>t.requiresDelegation).map(([e])=>e),agentDid:e.slice(0,20)+"..."}),this.config.debug&&console.log("[ToolProtectionService] API fetch successful, cached",{agentDid:e.slice(0,20)+"...",cacheKey:t,toolCount:Object.keys(a).length,tools:Object.entries(a).map(([e,t])=>({name:e,requiresDelegation:t.requiresDelegation})),ttl:i}),s}catch(r){const a=r instanceof Error?r.message:String(r);if(a.includes("API key is missing or empty"))throw r;if(a.includes("Failed to fetch bouncer config:")&&(429!==r.status||!this.config.fallbackConfig))throw r;if(a.includes("Failed to parse API response:"))throw r;if(a.includes("API returned success: false"))throw r;this.config.debug&&console.error("[ToolProtectionService] API fetch failed",{agentDid:e.slice(0,20)+"...",error:a});const s=await this.getStaleCache(t);if(s)return console.warn("[ToolProtectionService] API fetch failed, using stale cache",{agentDid:e.slice(0,20)+"...",error:a,cacheKey:t}),s;if(this.config.fallbackConfig){console.warn("[ToolProtectionService] API fetch failed, using fallback config",{agentDid:e.slice(0,20)+"...",error:a});const r=this.config.cacheTtl??3e5;return await this.cache.set(t,this.config.fallbackConfig,r),this.config.fallbackConfig}if("deny-all"===(this.config.failSafeBehavior??"deny-all")){console.error("[ToolProtectionService] API fetch failed, no fallback, failing closed (deny-all)",{agentDid:e.slice(0,20)+"...",error:a,cacheKey:t});const r={toolProtections:{"*":{requiresDelegation:!0,requiredScopes:[]}}},s=this.config.cacheTtl??3e5;return await this.cache.set(t,r,s),r}{console.warn("[ToolProtectionService] API fetch failed, no fallback, failing open (allow-all)",{agentDid:e.slice(0,20)+"...",error:a,cacheKey:t});const r={toolProtections:{}},s=this.config.cacheTtl??3e5;return await this.cache.set(t,r,s),r}}}async checkToolProtection(e,t){const r=await this.getToolProtectionConfig(t);let a=r.toolProtections[e];return!a&&r.toolProtections["*"]&&(a=r.toolProtections["*"]),(this.config.debug||!a||a.requiresDelegation)&&console.log("[ToolProtectionService] Protection check",{tool:e,agentDid:t.slice(0,20)+"...",found:!!a,isWildcard:a===r.toolProtections["*"],requiresDelegation:a?.requiresDelegation??!1,availableTools:Object.keys(r.toolProtections)}),a&&a.requiresDelegation?a:null}async fetchFromApi(e){let t,r=!1;this.config.projectId?(t=`${this.config.apiUrl}/api/v1/bouncer/projects/${encodeURIComponent(this.config.projectId)}/tool-protections`,r=!0):t=`${this.config.apiUrl}/api/v1/bouncer/config?agent_did=${encodeURIComponent(e)}`;const a=this.config.apiKey?(()=>{const e=this.config.apiKey.split("_");return e.length>=2?`${e[0]}_${e[1]}...`:`${this.config.apiKey.substring(0,8)}...`})():"(empty)",s=this.config.apiKey?.length||0;if(this.config.debug&&console.log("[ToolProtectionService] Fetching from API:",t,{method:r?"projects/{projectId}/tool-protections (new)":"config?agent_did (old)",projectId:this.config.projectId||"none",apiKeyPresent:!!this.config.apiKey,apiKeyLength:s,apiKeyMasked:a}),!this.config.apiKey||""===this.config.apiKey.trim()){const e="API key is missing or empty";throw this.config.debug&&console.error("[ToolProtectionService]",e,{apiKeyPresent:!!this.config.apiKey,apiKeyLength:s}),new Error(`ToolProtectionService: ${e}. Check AGENTSHIELD_API_KEY in .dev.vars or wrangler.toml [vars]`)}const i={"Content-Type":"application/json"};r?(i["X-API-Key"]=this.config.apiKey,this.config.projectId&&(i["X-Project-Id"]=this.config.projectId)):i.Authorization=`Bearer ${this.config.apiKey}`;const n=await fetch(t,{method:"GET",headers:i});if(!n.ok){const e=await n.text().catch(()=>"Unknown error"),t=new Error(`Failed to fetch bouncer config: ${n.status} ${n.statusText} - ${e}`);throw t.status=n.status,t}let o;try{o=await n.json()}catch(e){throw new Error(`Failed to parse API response: ${e instanceof Error?e.message:String(e)}`)}if(!o.success)throw new Error("API returned success: false");return o}async clearCache(e){const t=this.config.projectId?`config:tool-protections:${this.config.projectId}`:`agent:${e}`;this.config.debug&&console.log("[ToolProtectionService] Clearing cache",{cacheKey:t,projectId:this.config.projectId||"none",agentDid:e.slice(0,20)+"..."}),await this.cache.delete(t)}}},96111:e=>{"use strict";e.exports=function(e,t,r){var a,s=" ",i=e.level,n=e.dataLevel,o=e.schema[t],c=e.schemaPath+e.util.getProperty(t),d=e.errSchemaPath+"/"+t,u=!e.opts.allErrors,l="data"+(n||""),h=e.opts.$data&&o&&o.$data;if(h?(s+=" var schema"+i+" = "+e.util.getData(o.$data,n,e.dataPathArr)+"; ",a="schema"+i):a=o,!h&&"number"!=typeof o)throw new Error(t+" must be number");s+="if ( ",h&&(s+=" ("+a+" !== undefined && typeof "+a+" != 'number') || "),s+=" Object.keys("+l+").length "+("maxProperties"==t?">":"<")+" "+a+") { ";var p=t,f=f||[];f.push(s),s="",!1!==e.createErrors?(s+=" { keyword: '"+(p||"_limitProperties")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(d)+" , params: { limit: "+a+" } ",!1!==e.opts.messages&&(s+=" , message: 'should NOT have ",s+="maxProperties"==t?"more":"fewer",s+=" than ",s+=h?"' + "+a+" + '":""+o,s+=" properties' "),e.opts.verbose&&(s+=" , schema: ",s+=h?"validate.schema"+c:""+o,s+=" , parentSchema: validate.schema"+e.schemaPath+" , data: "+l+" "),s+=" } "):s+=" {} ";var m=s;return s=f.pop(),!e.compositeRule&&u?e.async?s+=" throw new ValidationError(["+m+"]); ":s+=" validate.errors = ["+m+"]; return false; ":s+=" var err = "+m+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",s+="} ",u&&(s+=" else { "),s}},96150:(e,t,r)=>{"use strict";var a=r(12269);e.exports={$id:"https://github.com/ajv-validator/ajv/blob/master/lib/definition_schema.js",definitions:{simpleTypes:a.definitions.simpleTypes},type:"object",dependencies:{schema:["validate"],$data:["validate"],statements:["inline"],valid:{not:{required:["macro"]}}},properties:{type:a.properties.type,schema:{type:"boolean"},statements:{type:"boolean"},dependencies:{type:"array",items:{type:"string"}},metaSchema:{type:"object"},modifying:{type:"boolean"},valid:{type:"boolean"},$data:{type:"boolean"},async:{type:"boolean"},errors:{anyOf:[{type:"boolean"},{const:"full"}]}}}},96308:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.IdentityProvider=t.NonceCacheProvider=t.StorageProvider=t.FetchProvider=t.ClockProvider=t.CryptoProvider=void 0,t.CryptoProvider=class{},t.ClockProvider=class{},t.FetchProvider=class{},t.StorageProvider=class{},t.NonceCacheProvider=class{},t.IdentityProvider=class{}},96654:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.MemoryIdentityProvider=t.MemoryNonceCacheProvider=t.MemoryStorageProvider=void 0;const a=r(96308);class s extends a.StorageProvider{store=new Map;async get(e){return this.store.get(e)??null}async set(e,t){this.store.set(e,t)}async delete(e){this.store.delete(e)}async exists(e){return this.store.has(e)}async list(e){const t=Array.from(this.store.keys());return e?t.filter(t=>t.startsWith(e)):t}}t.MemoryStorageProvider=s;class i extends a.NonceCacheProvider{nonces=new Map;async has(e){const t=this.nonces.get(e);return!(!t||Date.now()>t&&(this.nonces.delete(e),1))}async add(e,t){this.nonces.set(e,t)}async cleanup(){const e=Date.now();for(const[t,r]of this.nonces)e>r&&this.nonces.delete(t)}async destroy(){this.nonces.clear()}}t.MemoryNonceCacheProvider=i;class n extends a.IdentityProvider{identity;cryptoProvider;constructor(e){super(),this.cryptoProvider=e}async getIdentity(){return this.identity||(this.identity=await this.generateIdentity()),this.identity}async saveIdentity(e){this.identity=e}async rotateKeys(){return this.identity=await this.generateIdentity(),this.identity}async deleteIdentity(){this.identity=void 0}async generateIdentity(){if(!this.cryptoProvider)throw new Error("Crypto provider required for identity generation");const e=await this.cryptoProvider.generateKeyPair(),t=this.generateDIDFromPublicKey(e.publicKey);return{did:t,kid:`${t}#key-1`,privateKey:e.privateKey,publicKey:e.publicKey,createdAt:(new Date).toISOString(),type:"development"}}generateDIDFromPublicKey(e){return`did:key:z${Buffer.from(e,"base64").toString("base64url").substring(0,32)}`}}t.MemoryIdentityProvider=n},96774:e=>{"use strict";e.exports=function(e,t,r){var a,s=" ",i=e.level,n=e.dataLevel,o=e.schema[t],c=e.schemaPath+e.util.getProperty(t),d=e.errSchemaPath+"/"+t,u=!e.opts.allErrors,l="data"+(n||""),h=e.opts.$data&&o&&o.$data;h?(s+=" var schema"+i+" = "+e.util.getData(o.$data,n,e.dataPathArr)+"; ",a="schema"+i):a=o,s+="if ( ",h&&(s+=" ("+a+" !== undefined && typeof "+a+" != 'string') || "),s+=" !"+(h?"(new RegExp("+a+"))":e.usePattern(o))+".test("+l+") ) { ";var p=p||[];p.push(s),s="",!1!==e.createErrors?(s+=" { keyword: 'pattern' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(d)+" , params: { pattern: ",s+=h?""+a:""+e.util.toQuotedString(o),s+=" } ",!1!==e.opts.messages&&(s+=" , message: 'should match pattern \"",s+=h?"' + "+a+" + '":""+e.util.escapeQuotes(o),s+="\"' "),e.opts.verbose&&(s+=" , schema: ",s+=h?"validate.schema"+c:""+e.util.toQuotedString(o),s+=" , parentSchema: validate.schema"+e.schemaPath+" , data: "+l+" "),s+=" } "):s+=" {} ";var f=s;return s=p.pop(),!e.compositeRule&&u?e.async?s+=" throw new ValidationError(["+f+"]); ":s+=" validate.errors = ["+f+"]; return false; ":s+=" var err = "+f+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",s+="} ",u&&(s+=" else { "),s}},97145:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ERROR_CODES=t.RuntimeErrorSchema=t.NeedsAuthorizationErrorSchema=t.AuthorizationDisplaySchema=t.DisplayHintSchema=void 0,t.validateNeedsAuthorizationError=function(e){return t.NeedsAuthorizationErrorSchema.safeParse(e)},t.isNeedsAuthorizationError=function(e){return e&&"needs_authorization"===e.error},t.createNeedsAuthorizationError=function(e){return{error:"needs_authorization",...e}};const a=r(90315);t.DisplayHintSchema=a.z.enum(["link","qr","code"]),t.AuthorizationDisplaySchema=a.z.object({title:a.z.string().optional(),hint:a.z.array(t.DisplayHintSchema).optional(),authorizationCode:a.z.string().optional(),qrUrl:a.z.string().url().optional()}).passthrough(),t.NeedsAuthorizationErrorSchema=a.z.object({error:a.z.literal("needs_authorization"),message:a.z.string().min(1),authorizationUrl:a.z.string().url(),resumeToken:a.z.string().min(1),expiresAt:a.z.number().int().positive(),scopes:a.z.array(a.z.string()),display:t.AuthorizationDisplaySchema.optional(),context:a.z.record(a.z.any()).optional()}).passthrough(),t.RuntimeErrorSchema=a.z.object({error:a.z.string().min(1),message:a.z.string().min(1),details:a.z.record(a.z.any()).optional(),httpStatus:a.z.number().int().min(400).max(599).optional()}),t.ERROR_CODES=Object.freeze({NEEDS_AUTHORIZATION:"needs_authorization",INVALID_TOKEN:"invalid_token",TOKEN_EXPIRED:"token_expired",INSUFFICIENT_SCOPE:"insufficient_scope",INVALID_SIGNATURE:"invalid_signature",DELEGATION_REVOKED:"delegation_revoked",CREDENTIAL_REVOKED:"credential_revoked"})},97354:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.StringValidators=void 0,t.validateInput=function(e,t,r){const a=e.safeParse(t);return a.success?{valid:!0,data:a.data,errors:[]}:{valid:!1,errors:a.error.errors.map(e=>{const t=e.path.length>0?` at ${e.path.join(".")}`:"",a=r?` (${r})`:"";return`${e.message}${t}${a}`})}},t.hasRequiredProperties=function(e,t,r){if("object"!=typeof e||null===e)return{valid:!1,errors:["Expected object"+(r?` for ${r}`:"")]};const a=t.filter(t=>!(t in e));return a.length>0?{valid:!1,errors:[`Missing required properties: ${a.join(", ")}${r?` in ${r}`:""}`]}:{valid:!0,errors:[]}},t.StringValidators={did:e=>/^did:[a-z0-9]+:[a-zA-Z0-9._-]+$/.test(e),kid:e=>/^[a-zA-Z0-9._-]+$/.test(e),url:e=>{try{return new URL(e),!0}catch{return!1}},projectName:e=>/^[a-z0-9-]+$/.test(e)&&e.length>=1&&e.length<=214}},98770:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.canonicalizeJSON=function e(t){if(null===t)return"null";if("boolean"==typeof t)return t.toString();if("number"==typeof t){if(!isFinite(t))throw new Error("Cannot canonicalize non-finite number");return JSON.stringify(t)}if("string"==typeof t)return JSON.stringify(t);if(Array.isArray(t))return"["+t.map(t=>e(t)).join(",")+"]";if("object"==typeof t)return"{"+Object.keys(t).sort().map(r=>{const a=e(t[r]);return JSON.stringify(r)+":"+a}).join(",")+"}";throw new Error("Cannot canonicalize type: "+typeof t)}},99394:function(e,t,r){"use strict";var a=this&&this.__createBinding||(Object.create?function(e,t,r,a){void 0===a&&(a=r);var s=Object.getOwnPropertyDescriptor(t,r);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,a,s)}:function(e,t,r,a){void 0===a&&(a=r),e[a]=t[r]}),s=this&&this.__exportStar||function(e,t){for(var r in e)"default"===r||Object.prototype.hasOwnProperty.call(t,r)||a(t,e,r)};Object.defineProperty(t,"__esModule",{value:!0}),s(r(80630),t),s(r(70926),t),s(r(61763),t),s(r(27165),t),s(r(44242),t),s(r(68820),t)},99529:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.CLI_EXIT_CODES=t.ERROR_CODES=t.ScaffolderResultSchema=t.ScaffolderOptionsSchema=t.DoctorResultSchema=t.CacheInfoSchema=t.KTAInfoSchema=t.EnvironmentInfoSchema=t.XMCPUpstreamInfoSchema=t.PackageInfoSchema=t.StatusReportSchema=t.KeyRotationResultSchema=t.CLIIdentityFileSchema=void 0;const a=r(90315);t.CLIIdentityFileSchema=a.z.object({version:a.z.literal("1.0"),did:a.z.string().min(1),kid:a.z.string().min(1).optional(),keyId:a.z.string().min(1).optional(),privateKey:a.z.string().regex(/^[A-Za-z0-9+/]{43}=$/,"Must be a valid base64-encoded Ed25519 private key (44 characters)"),publicKey:a.z.string().regex(/^[A-Za-z0-9+/]{43}=$/,"Must be a valid base64-encoded Ed25519 public key (44 characters)"),createdAt:a.z.string().datetime(),lastRotated:a.z.string().datetime().optional()}).refine(e=>e.kid||e.keyId,{message:"Either kid or keyId must be provided"}).transform(e=>({version:e.version,did:e.did,kid:e.kid||e.keyId,privateKey:e.privateKey,publicKey:e.publicKey,createdAt:e.createdAt,lastRotated:e.lastRotated})),t.KeyRotationResultSchema=a.z.object({success:a.z.boolean(),oldKeyId:a.z.string().min(1),newKeyId:a.z.string().min(1),did:a.z.string().min(1),mode:a.z.enum(["dev","prod"]),delegated:a.z.boolean(),forced:a.z.boolean(),auditLine:a.z.string().min(1)}),t.StatusReportSchema=a.z.object({did:a.z.string().min(1),kid:a.z.string().min(1),ktaURL:a.z.string().url(),mirrorStatus:a.z.enum(["pending","success","error"]),lastHandshake:a.z.number().int().positive().optional(),environment:a.z.enum(["dev","prod"])}),t.PackageInfoSchema=a.z.object({name:a.z.string(),version:a.z.string(),compatible:a.z.boolean(),issues:a.z.array(a.z.string()).optional()}),t.XMCPUpstreamInfoSchema=a.z.object({version:a.z.string(),compatible:a.z.boolean(),issues:a.z.array(a.z.string()).optional()}),t.EnvironmentInfoSchema=a.z.object({valid:a.z.boolean(),missing:a.z.array(a.z.string()),issues:a.z.array(a.z.string()).optional()}),t.KTAInfoSchema=a.z.object({reachable:a.z.boolean(),authenticated:a.z.boolean(),issues:a.z.array(a.z.string()).optional()}),t.CacheInfoSchema=a.z.object({type:a.z.string(),functional:a.z.boolean(),issues:a.z.array(a.z.string()).optional()}),t.DoctorResultSchema=a.z.object({packages:a.z.array(t.PackageInfoSchema),xmcpUpstream:t.XMCPUpstreamInfoSchema,environment:t.EnvironmentInfoSchema,kta:t.KTAInfoSchema,cache:t.CacheInfoSchema}),t.ScaffolderOptionsSchema=a.z.object({projectName:a.z.string().min(1),xmcpVersion:a.z.string().optional(),xmcpChannel:a.z.enum(["latest","next"]).optional(),noIdentity:a.z.boolean().default(!1)}),t.ScaffolderResultSchema=a.z.object({success:a.z.boolean(),projectPath:a.z.string().min(1),xmcpVersion:a.z.string().min(1),identityEnabled:a.z.boolean(),warnings:a.z.array(a.z.string()).optional()}),t.ERROR_CODES={XMCP_I_EBADPROOF:"XMCP_I_EBADPROOF",XMCP_I_ENOIDENTITY:"XMCP_I_ENOIDENTITY",XMCP_I_EMIRRORPENDING:"XMCP_I_EMIRRORPENDING",XMCP_I_EHANDSHAKE:"XMCP_I_EHANDSHAKE",XMCP_I_ESESSION:"XMCP_I_ESESSION",XMCP_I_ECLAIM:"XMCP_I_ECLAIM",XMCP_I_ECONFIG:"XMCP_I_ECONFIG",XMCP_I_ERUNTIME:"XMCP_I_ERUNTIME"},t.CLI_EXIT_CODES={SUCCESS:0,GENERAL_ERROR:1,BADPROOF:20,NOIDENTITY:21,HANDSHAKE:22,SESSION:23,CLAIM:24,CONFIG:25,RUNTIME:26}}},t={};function r(a){var s=t[a];if(void 0!==s)return s.exports;var i=t[a]={exports:{}};return e[a].call(i.exports,i,i.exports,r),i.exports}r.d=(e,t)=>{for(var a in t)r.o(t,a)&&!r.o(e,a)&&Object.defineProperty(e,a,{enumerable:!0,get:t[a]})},r.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),r.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},(()=>{"use strict";const e=require("node:process");var t,a;!function(e){e.assertEqual=e=>{},e.assertIs=function(e){},e.assertNever=function(e){throw new Error},e.arrayToEnum=e=>{const t={};for(const r of e)t[r]=r;return t},e.getValidEnumValues=t=>{const r=e.objectKeys(t).filter(e=>"number"!=typeof t[t[e]]),a={};for(const e of r)a[e]=t[e];return e.objectValues(a)},e.objectValues=t=>e.objectKeys(t).map(function(e){return t[e]}),e.objectKeys="function"==typeof Object.keys?e=>Object.keys(e):e=>{const t=[];for(const r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.push(r);return t},e.find=(e,t)=>{for(const r of e)if(t(r))return r},e.isInteger="function"==typeof Number.isInteger?e=>Number.isInteger(e):e=>"number"==typeof e&&Number.isFinite(e)&&Math.floor(e)===e,e.joinValues=function(e,t=" | "){return e.map(e=>"string"==typeof e?`'${e}'`:e).join(t)},e.jsonStringifyReplacer=(e,t)=>"bigint"==typeof t?t.toString():t}(t||(t={})),function(e){e.mergeShapes=(e,t)=>({...e,...t})}(a||(a={}));const s=t.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),i=e=>{switch(typeof e){case"undefined":return s.undefined;case"string":return s.string;case"number":return Number.isNaN(e)?s.nan:s.number;case"boolean":return s.boolean;case"function":return s.function;case"bigint":return s.bigint;case"symbol":return s.symbol;case"object":return Array.isArray(e)?s.array:null===e?s.null:e.then&&"function"==typeof e.then&&e.catch&&"function"==typeof e.catch?s.promise:"undefined"!=typeof Map&&e instanceof Map?s.map:"undefined"!=typeof Set&&e instanceof Set?s.set:"undefined"!=typeof Date&&e instanceof Date?s.date:s.object;default:return s.unknown}},n=t.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"]);class o extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=e=>{this.issues=[...this.issues,e]},this.addIssues=(e=[])=>{this.issues=[...this.issues,...e]};const t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name="ZodError",this.issues=e}format(e){const t=e||function(e){return e.message},r={_errors:[]},a=e=>{for(const s of e.issues)if("invalid_union"===s.code)s.unionErrors.map(a);else if("invalid_return_type"===s.code)a(s.returnTypeError);else if("invalid_arguments"===s.code)a(s.argumentsError);else if(0===s.path.length)r._errors.push(t(s));else{let e=r,a=0;for(;a<s.path.length;){const r=s.path[a];a===s.path.length-1?(e[r]=e[r]||{_errors:[]},e[r]._errors.push(t(s))):e[r]=e[r]||{_errors:[]},e=e[r],a++}}};return a(this),r}static assert(e){if(!(e instanceof o))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,t.jsonStringifyReplacer,2)}get isEmpty(){return 0===this.issues.length}flatten(e=e=>e.message){const t={},r=[];for(const a of this.issues)if(a.path.length>0){const r=a.path[0];t[r]=t[r]||[],t[r].push(e(a))}else r.push(e(a));return{formErrors:r,fieldErrors:t}}get formErrors(){return this.flatten()}}o.create=e=>new o(e);const c=(e,r)=>{let a;switch(e.code){case n.invalid_type:a=e.received===s.undefined?"Required":`Expected ${e.expected}, received ${e.received}`;break;case n.invalid_literal:a=`Invalid literal value, expected ${JSON.stringify(e.expected,t.jsonStringifyReplacer)}`;break;case n.unrecognized_keys:a=`Unrecognized key(s) in object: ${t.joinValues(e.keys,", ")}`;break;case n.invalid_union:a="Invalid input";break;case n.invalid_union_discriminator:a=`Invalid discriminator value. Expected ${t.joinValues(e.options)}`;break;case n.invalid_enum_value:a=`Invalid enum value. Expected ${t.joinValues(e.options)}, received '${e.received}'`;break;case n.invalid_arguments:a="Invalid function arguments";break;case n.invalid_return_type:a="Invalid function return type";break;case n.invalid_date:a="Invalid date";break;case n.invalid_string:"object"==typeof e.validation?"includes"in e.validation?(a=`Invalid input: must include "${e.validation.includes}"`,"number"==typeof e.validation.position&&(a=`${a} at one or more positions greater than or equal to ${e.validation.position}`)):"startsWith"in e.validation?a=`Invalid input: must start with "${e.validation.startsWith}"`:"endsWith"in e.validation?a=`Invalid input: must end with "${e.validation.endsWith}"`:t.assertNever(e.validation):a="regex"!==e.validation?`Invalid ${e.validation}`:"Invalid";break;case n.too_small:a="array"===e.type?`Array must contain ${e.exact?"exactly":e.inclusive?"at least":"more than"} ${e.minimum} element(s)`:"string"===e.type?`String must contain ${e.exact?"exactly":e.inclusive?"at least":"over"} ${e.minimum} character(s)`:"number"===e.type||"bigint"===e.type?`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:"date"===e.type?`Date must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(e.minimum))}`:"Invalid input";break;case n.too_big:a="array"===e.type?`Array must contain ${e.exact?"exactly":e.inclusive?"at most":"less than"} ${e.maximum} element(s)`:"string"===e.type?`String must contain ${e.exact?"exactly":e.inclusive?"at most":"under"} ${e.maximum} character(s)`:"number"===e.type?`Number must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:"bigint"===e.type?`BigInt must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:"date"===e.type?`Date must be ${e.exact?"exactly":e.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(e.maximum))}`:"Invalid input";break;case n.custom:a="Invalid input";break;case n.invalid_intersection_types:a="Intersection results could not be merged";break;case n.not_multiple_of:a=`Number must be a multiple of ${e.multipleOf}`;break;case n.not_finite:a="Number must be finite";break;default:a=r.defaultError,t.assertNever(e)}return{message:a}};let d=c;var u;!function(e){e.errToObj=e=>"string"==typeof e?{message:e}:e||{},e.toString=e=>"string"==typeof e?e:e?.message}(u||(u={}));function l(e,t){const r=d,a=(e=>{const{data:t,path:r,errorMaps:a,issueData:s}=e,i=[...r,...s.path||[]],n={...s,path:i};if(void 0!==s.message)return{...s,path:i,message:s.message};let o="";const c=a.filter(e=>!!e).slice().reverse();for(const e of c)o=e(n,{data:t,defaultError:o}).message;return{...s,path:i,message:o}})({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,r,r===c?void 0:c].filter(e=>!!e)});e.common.issues.push(a)}class h{constructor(){this.value="valid"}dirty(){"valid"===this.value&&(this.value="dirty")}abort(){"aborted"!==this.value&&(this.value="aborted")}static mergeArray(e,t){const r=[];for(const a of t){if("aborted"===a.status)return p;"dirty"===a.status&&e.dirty(),r.push(a.value)}return{status:e.value,value:r}}static async mergeObjectAsync(e,t){const r=[];for(const e of t){const t=await e.key,a=await e.value;r.push({key:t,value:a})}return h.mergeObjectSync(e,r)}static mergeObjectSync(e,t){const r={};for(const a of t){const{key:t,value:s}=a;if("aborted"===t.status)return p;if("aborted"===s.status)return p;"dirty"===t.status&&e.dirty(),"dirty"===s.status&&e.dirty(),"__proto__"===t.value||void 0===s.value&&!a.alwaysSet||(r[t.value]=s.value)}return{status:e.value,value:r}}}const p=Object.freeze({status:"aborted"}),f=e=>({status:"dirty",value:e}),m=e=>({status:"valid",value:e}),g=e=>"aborted"===e.status,y=e=>"dirty"===e.status,v=e=>"valid"===e.status,_=e=>"undefined"!=typeof Promise&&e instanceof Promise;class S{constructor(e,t,r,a){this._cachedPath=[],this.parent=e,this.data=t,this._path=r,this._key=a}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}}const b=(e,t)=>{if(v(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;const t=new o(e.common.issues);return this._error=t,this._error}}};function E(e){if(!e)return{};const{errorMap:t,invalid_type_error:r,required_error:a,description:s}=e;if(t&&(r||a))throw new Error('Can\'t use "invalid_type_error" or "required_error" in conjunction with custom error map.');return t?{errorMap:t,description:s}:{errorMap:(t,s)=>{const{message:i}=e;return"invalid_enum_value"===t.code?{message:i??s.defaultError}:void 0===s.data?{message:i??a??s.defaultError}:"invalid_type"!==t.code?{message:s.defaultError}:{message:i??r??s.defaultError}},description:s}}class P{get description(){return this._def.description}_getType(e){return i(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:i(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new h,ctx:{common:e.parent.common,data:e.data,parsedType:i(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const t=this._parse(e);if(_(t))throw new Error("Synchronous parse encountered promise.");return t}_parseAsync(e){const t=this._parse(e);return Promise.resolve(t)}parse(e,t){const r=this.safeParse(e,t);if(r.success)return r.data;throw r.error}safeParse(e,t){const r={common:{issues:[],async:t?.async??!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:i(e)},a=this._parseSync({data:e,path:r.path,parent:r});return b(r,a)}"~validate"(e){const t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:i(e)};if(!this["~standard"].async)try{const r=this._parseSync({data:e,path:[],parent:t});return v(r)?{value:r.value}:{issues:t.common.issues}}catch(e){e?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then(e=>v(e)?{value:e.value}:{issues:t.common.issues})}async parseAsync(e,t){const r=await this.safeParseAsync(e,t);if(r.success)return r.data;throw r.error}async safeParseAsync(e,t){const r={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:i(e)},a=this._parse({data:e,path:r.path,parent:r}),s=await(_(a)?a:Promise.resolve(a));return b(r,s)}refine(e,t){const r=e=>"string"==typeof t||void 0===t?{message:t}:"function"==typeof t?t(e):t;return this._refinement((t,a)=>{const s=e(t),i=()=>a.addIssue({code:n.custom,...r(t)});return"undefined"!=typeof Promise&&s instanceof Promise?s.then(e=>!!e||(i(),!1)):!!s||(i(),!1)})}refinement(e,t){return this._refinement((r,a)=>!!e(r)||(a.addIssue("function"==typeof t?t(r,a):t),!1))}_refinement(e){return new Ie({schema:this,typeName:Re.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:e=>this["~validate"](e)}}optional(){return we.create(this,this._def)}nullable(){return Ce.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return ne.create(this)}promise(){return Pe.create(this,this._def)}or(e){return de.create([this,e],this._def)}and(e){return pe.create(this,e,this._def)}transform(e){return new Ie({...E(this._def),schema:this,typeName:Re.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const t="function"==typeof e?e:()=>e;return new Te({...E(this._def),innerType:this,defaultValue:t,typeName:Re.ZodDefault})}brand(){return new Oe({typeName:Re.ZodBranded,type:this,...E(this._def)})}catch(e){const t="function"==typeof e?e:()=>e;return new De({...E(this._def),innerType:this,catchValue:t,typeName:Re.ZodCatch})}describe(e){return new(0,this.constructor)({...this._def,description:e})}pipe(e){return Ae.create(this,e)}readonly(){return ke.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const I=/^c[^\s-]{8,}$/i,w=/^[0-9a-z]+$/,C=/^[0-9A-HJKMNP-TV-Z]{26}$/i,T=/^[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,D=/^[a-z0-9_-]{21}$/i,x=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,O=/^[-+]?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)?)??$/,A=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;let k;const R=/^(?:(?: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])$/,N=/^(?:(?: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])$/,j=/^(([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]))$/,z=/^(([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])$/,$=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,M=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,L="((\\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])))",F=new RegExp(`^${L}$`);function Z(e){let t="[0-5]\\d";return e.precision?t=`${t}\\.\\d{${e.precision}}`:null==e.precision&&(t=`${t}(\\.\\d+)?`),`([01]\\d|2[0-3]):[0-5]\\d(:${t})${e.precision?"+":"?"}`}function V(e){return new RegExp(`^${Z(e)}$`)}function K(e){let t=`${L}T${Z(e)}`;const r=[];return r.push(e.local?"Z?":"Z"),e.offset&&r.push("([+-]\\d{2}:?\\d{2})"),t=`${t}(${r.join("|")})`,new RegExp(`^${t}$`)}function U(e,t){return!("v4"!==t&&t||!R.test(e))||!("v6"!==t&&t||!j.test(e))}function H(e,t){if(!x.test(e))return!1;try{const[r]=e.split(".");if(!r)return!1;const a=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.length%4)%4,"="),s=JSON.parse(atob(a));return!("object"!=typeof s||null===s||"typ"in s&&"JWT"!==s?.typ||!s.alg||t&&s.alg!==t)}catch{return!1}}function q(e,t){return!("v4"!==t&&t||!N.test(e))||!("v6"!==t&&t||!z.test(e))}class B extends P{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==s.string){const t=this._getOrReturnCtx(e);return l(t,{code:n.invalid_type,expected:s.string,received:t.parsedType}),p}const r=new h;let a;for(const s of this._def.checks)if("min"===s.kind)e.data.length<s.value&&(a=this._getOrReturnCtx(e,a),l(a,{code:n.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),r.dirty());else if("max"===s.kind)e.data.length>s.value&&(a=this._getOrReturnCtx(e,a),l(a,{code:n.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),r.dirty());else if("length"===s.kind){const t=e.data.length>s.value,i=e.data.length<s.value;(t||i)&&(a=this._getOrReturnCtx(e,a),t?l(a,{code:n.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}):i&&l(a,{code:n.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}),r.dirty())}else if("email"===s.kind)A.test(e.data)||(a=this._getOrReturnCtx(e,a),l(a,{validation:"email",code:n.invalid_string,message:s.message}),r.dirty());else if("emoji"===s.kind)k||(k=new RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),k.test(e.data)||(a=this._getOrReturnCtx(e,a),l(a,{validation:"emoji",code:n.invalid_string,message:s.message}),r.dirty());else if("uuid"===s.kind)T.test(e.data)||(a=this._getOrReturnCtx(e,a),l(a,{validation:"uuid",code:n.invalid_string,message:s.message}),r.dirty());else if("nanoid"===s.kind)D.test(e.data)||(a=this._getOrReturnCtx(e,a),l(a,{validation:"nanoid",code:n.invalid_string,message:s.message}),r.dirty());else if("cuid"===s.kind)I.test(e.data)||(a=this._getOrReturnCtx(e,a),l(a,{validation:"cuid",code:n.invalid_string,message:s.message}),r.dirty());else if("cuid2"===s.kind)w.test(e.data)||(a=this._getOrReturnCtx(e,a),l(a,{validation:"cuid2",code:n.invalid_string,message:s.message}),r.dirty());else if("ulid"===s.kind)C.test(e.data)||(a=this._getOrReturnCtx(e,a),l(a,{validation:"ulid",code:n.invalid_string,message:s.message}),r.dirty());else if("url"===s.kind)try{new URL(e.data)}catch{a=this._getOrReturnCtx(e,a),l(a,{validation:"url",code:n.invalid_string,message:s.message}),r.dirty()}else"regex"===s.kind?(s.regex.lastIndex=0,s.regex.test(e.data)||(a=this._getOrReturnCtx(e,a),l(a,{validation:"regex",code:n.invalid_string,message:s.message}),r.dirty())):"trim"===s.kind?e.data=e.data.trim():"includes"===s.kind?e.data.includes(s.value,s.position)||(a=this._getOrReturnCtx(e,a),l(a,{code:n.invalid_string,validation:{includes:s.value,position:s.position},message:s.message}),r.dirty()):"toLowerCase"===s.kind?e.data=e.data.toLowerCase():"toUpperCase"===s.kind?e.data=e.data.toUpperCase():"startsWith"===s.kind?e.data.startsWith(s.value)||(a=this._getOrReturnCtx(e,a),l(a,{code:n.invalid_string,validation:{startsWith:s.value},message:s.message}),r.dirty()):"endsWith"===s.kind?e.data.endsWith(s.value)||(a=this._getOrReturnCtx(e,a),l(a,{code:n.invalid_string,validation:{endsWith:s.value},message:s.message}),r.dirty()):"datetime"===s.kind?K(s).test(e.data)||(a=this._getOrReturnCtx(e,a),l(a,{code:n.invalid_string,validation:"datetime",message:s.message}),r.dirty()):"date"===s.kind?F.test(e.data)||(a=this._getOrReturnCtx(e,a),l(a,{code:n.invalid_string,validation:"date",message:s.message}),r.dirty()):"time"===s.kind?V(s).test(e.data)||(a=this._getOrReturnCtx(e,a),l(a,{code:n.invalid_string,validation:"time",message:s.message}),r.dirty()):"duration"===s.kind?O.test(e.data)||(a=this._getOrReturnCtx(e,a),l(a,{validation:"duration",code:n.invalid_string,message:s.message}),r.dirty()):"ip"===s.kind?U(e.data,s.version)||(a=this._getOrReturnCtx(e,a),l(a,{validation:"ip",code:n.invalid_string,message:s.message}),r.dirty()):"jwt"===s.kind?H(e.data,s.alg)||(a=this._getOrReturnCtx(e,a),l(a,{validation:"jwt",code:n.invalid_string,message:s.message}),r.dirty()):"cidr"===s.kind?q(e.data,s.version)||(a=this._getOrReturnCtx(e,a),l(a,{validation:"cidr",code:n.invalid_string,message:s.message}),r.dirty()):"base64"===s.kind?$.test(e.data)||(a=this._getOrReturnCtx(e,a),l(a,{validation:"base64",code:n.invalid_string,message:s.message}),r.dirty()):"base64url"===s.kind?M.test(e.data)||(a=this._getOrReturnCtx(e,a),l(a,{validation:"base64url",code:n.invalid_string,message:s.message}),r.dirty()):t.assertNever(s);return{status:r.value,value:e.data}}_regex(e,t,r){return this.refinement(t=>e.test(t),{validation:t,code:n.invalid_string,...u.errToObj(r)})}_addCheck(e){return new B({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...u.errToObj(e)})}url(e){return this._addCheck({kind:"url",...u.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...u.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...u.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...u.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...u.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...u.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...u.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...u.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...u.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...u.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...u.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...u.errToObj(e)})}datetime(e){return"string"==typeof e?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:void 0===e?.precision?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...u.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return"string"==typeof e?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:void 0===e?.precision?null:e?.precision,...u.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...u.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...u.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t?.position,...u.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...u.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...u.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...u.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...u.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...u.errToObj(t)})}nonempty(e){return this.min(1,u.errToObj(e))}trim(){return new B({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new B({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new B({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>"datetime"===e.kind)}get isDate(){return!!this._def.checks.find(e=>"date"===e.kind)}get isTime(){return!!this._def.checks.find(e=>"time"===e.kind)}get isDuration(){return!!this._def.checks.find(e=>"duration"===e.kind)}get isEmail(){return!!this._def.checks.find(e=>"email"===e.kind)}get isURL(){return!!this._def.checks.find(e=>"url"===e.kind)}get isEmoji(){return!!this._def.checks.find(e=>"emoji"===e.kind)}get isUUID(){return!!this._def.checks.find(e=>"uuid"===e.kind)}get isNANOID(){return!!this._def.checks.find(e=>"nanoid"===e.kind)}get isCUID(){return!!this._def.checks.find(e=>"cuid"===e.kind)}get isCUID2(){return!!this._def.checks.find(e=>"cuid2"===e.kind)}get isULID(){return!!this._def.checks.find(e=>"ulid"===e.kind)}get isIP(){return!!this._def.checks.find(e=>"ip"===e.kind)}get isCIDR(){return!!this._def.checks.find(e=>"cidr"===e.kind)}get isBase64(){return!!this._def.checks.find(e=>"base64"===e.kind)}get isBase64url(){return!!this._def.checks.find(e=>"base64url"===e.kind)}get minLength(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}}function W(e,t){const r=(e.toString().split(".")[1]||"").length,a=(t.toString().split(".")[1]||"").length,s=r>a?r:a;return Number.parseInt(e.toFixed(s).replace(".",""))%Number.parseInt(t.toFixed(s).replace(".",""))/10**s}B.create=e=>new B({checks:[],typeName:Re.ZodString,coerce:e?.coerce??!1,...E(e)});class G extends P{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==s.number){const t=this._getOrReturnCtx(e);return l(t,{code:n.invalid_type,expected:s.number,received:t.parsedType}),p}let r;const a=new h;for(const s of this._def.checks)"int"===s.kind?t.isInteger(e.data)||(r=this._getOrReturnCtx(e,r),l(r,{code:n.invalid_type,expected:"integer",received:"float",message:s.message}),a.dirty()):"min"===s.kind?(s.inclusive?e.data<s.value:e.data<=s.value)&&(r=this._getOrReturnCtx(e,r),l(r,{code:n.too_small,minimum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),a.dirty()):"max"===s.kind?(s.inclusive?e.data>s.value:e.data>=s.value)&&(r=this._getOrReturnCtx(e,r),l(r,{code:n.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),a.dirty()):"multipleOf"===s.kind?0!==W(e.data,s.value)&&(r=this._getOrReturnCtx(e,r),l(r,{code:n.not_multiple_of,multipleOf:s.value,message:s.message}),a.dirty()):"finite"===s.kind?Number.isFinite(e.data)||(r=this._getOrReturnCtx(e,r),l(r,{code:n.not_finite,message:s.message}),a.dirty()):t.assertNever(s);return{status:a.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,u.toString(t))}gt(e,t){return this.setLimit("min",e,!1,u.toString(t))}lte(e,t){return this.setLimit("max",e,!0,u.toString(t))}lt(e,t){return this.setLimit("max",e,!1,u.toString(t))}setLimit(e,t,r,a){return new G({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:u.toString(a)}]})}_addCheck(e){return new G({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:u.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:u.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:u.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:u.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:u.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:u.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:u.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:u.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:u.toString(e)})}get minValue(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find(e=>"int"===e.kind||"multipleOf"===e.kind&&t.isInteger(e.value))}get isFinite(){let e=null,t=null;for(const r of this._def.checks){if("finite"===r.kind||"int"===r.kind||"multipleOf"===r.kind)return!0;"min"===r.kind?(null===t||r.value>t)&&(t=r.value):"max"===r.kind&&(null===e||r.value<e)&&(e=r.value)}return Number.isFinite(t)&&Number.isFinite(e)}}G.create=e=>new G({checks:[],typeName:Re.ZodNumber,coerce:e?.coerce||!1,...E(e)});class J extends P{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==s.bigint)return this._getInvalidInput(e);let r;const a=new h;for(const s of this._def.checks)"min"===s.kind?(s.inclusive?e.data<s.value:e.data<=s.value)&&(r=this._getOrReturnCtx(e,r),l(r,{code:n.too_small,type:"bigint",minimum:s.value,inclusive:s.inclusive,message:s.message}),a.dirty()):"max"===s.kind?(s.inclusive?e.data>s.value:e.data>=s.value)&&(r=this._getOrReturnCtx(e,r),l(r,{code:n.too_big,type:"bigint",maximum:s.value,inclusive:s.inclusive,message:s.message}),a.dirty()):"multipleOf"===s.kind?e.data%s.value!==BigInt(0)&&(r=this._getOrReturnCtx(e,r),l(r,{code:n.not_multiple_of,multipleOf:s.value,message:s.message}),a.dirty()):t.assertNever(s);return{status:a.value,value:e.data}}_getInvalidInput(e){const t=this._getOrReturnCtx(e);return l(t,{code:n.invalid_type,expected:s.bigint,received:t.parsedType}),p}gte(e,t){return this.setLimit("min",e,!0,u.toString(t))}gt(e,t){return this.setLimit("min",e,!1,u.toString(t))}lte(e,t){return this.setLimit("max",e,!0,u.toString(t))}lt(e,t){return this.setLimit("max",e,!1,u.toString(t))}setLimit(e,t,r,a){return new J({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:u.toString(a)}]})}_addCheck(e){return new J({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:u.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:u.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:u.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:u.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:u.toString(t)})}get minValue(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}}J.create=e=>new J({checks:[],typeName:Re.ZodBigInt,coerce:e?.coerce??!1,...E(e)});class X extends P{_parse(e){if(this._def.coerce&&(e.data=Boolean(e.data)),this._getType(e)!==s.boolean){const t=this._getOrReturnCtx(e);return l(t,{code:n.invalid_type,expected:s.boolean,received:t.parsedType}),p}return m(e.data)}}X.create=e=>new X({typeName:Re.ZodBoolean,coerce:e?.coerce||!1,...E(e)});class Q extends P{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==s.date){const t=this._getOrReturnCtx(e);return l(t,{code:n.invalid_type,expected:s.date,received:t.parsedType}),p}if(Number.isNaN(e.data.getTime()))return l(this._getOrReturnCtx(e),{code:n.invalid_date}),p;const r=new h;let a;for(const s of this._def.checks)"min"===s.kind?e.data.getTime()<s.value&&(a=this._getOrReturnCtx(e,a),l(a,{code:n.too_small,message:s.message,inclusive:!0,exact:!1,minimum:s.value,type:"date"}),r.dirty()):"max"===s.kind?e.data.getTime()>s.value&&(a=this._getOrReturnCtx(e,a),l(a,{code:n.too_big,message:s.message,inclusive:!0,exact:!1,maximum:s.value,type:"date"}),r.dirty()):t.assertNever(s);return{status:r.value,value:new Date(e.data.getTime())}}_addCheck(e){return new Q({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:u.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:u.toString(t)})}get minDate(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return null!=e?new Date(e):null}get maxDate(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return null!=e?new Date(e):null}}Q.create=e=>new Q({checks:[],coerce:e?.coerce||!1,typeName:Re.ZodDate,...E(e)});class Y extends P{_parse(e){if(this._getType(e)!==s.symbol){const t=this._getOrReturnCtx(e);return l(t,{code:n.invalid_type,expected:s.symbol,received:t.parsedType}),p}return m(e.data)}}Y.create=e=>new Y({typeName:Re.ZodSymbol,...E(e)});class ee extends P{_parse(e){if(this._getType(e)!==s.undefined){const t=this._getOrReturnCtx(e);return l(t,{code:n.invalid_type,expected:s.undefined,received:t.parsedType}),p}return m(e.data)}}ee.create=e=>new ee({typeName:Re.ZodUndefined,...E(e)});class te extends P{_parse(e){if(this._getType(e)!==s.null){const t=this._getOrReturnCtx(e);return l(t,{code:n.invalid_type,expected:s.null,received:t.parsedType}),p}return m(e.data)}}te.create=e=>new te({typeName:Re.ZodNull,...E(e)});class re extends P{constructor(){super(...arguments),this._any=!0}_parse(e){return m(e.data)}}re.create=e=>new re({typeName:Re.ZodAny,...E(e)});class ae extends P{constructor(){super(...arguments),this._unknown=!0}_parse(e){return m(e.data)}}ae.create=e=>new ae({typeName:Re.ZodUnknown,...E(e)});class se extends P{_parse(e){const t=this._getOrReturnCtx(e);return l(t,{code:n.invalid_type,expected:s.never,received:t.parsedType}),p}}se.create=e=>new se({typeName:Re.ZodNever,...E(e)});class ie extends P{_parse(e){if(this._getType(e)!==s.undefined){const t=this._getOrReturnCtx(e);return l(t,{code:n.invalid_type,expected:s.void,received:t.parsedType}),p}return m(e.data)}}ie.create=e=>new ie({typeName:Re.ZodVoid,...E(e)});class ne extends P{_parse(e){const{ctx:t,status:r}=this._processInputParams(e),a=this._def;if(t.parsedType!==s.array)return l(t,{code:n.invalid_type,expected:s.array,received:t.parsedType}),p;if(null!==a.exactLength){const e=t.data.length>a.exactLength.value,s=t.data.length<a.exactLength.value;(e||s)&&(l(t,{code:e?n.too_big:n.too_small,minimum:s?a.exactLength.value:void 0,maximum:e?a.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:a.exactLength.message}),r.dirty())}if(null!==a.minLength&&t.data.length<a.minLength.value&&(l(t,{code:n.too_small,minimum:a.minLength.value,type:"array",inclusive:!0,exact:!1,message:a.minLength.message}),r.dirty()),null!==a.maxLength&&t.data.length>a.maxLength.value&&(l(t,{code:n.too_big,maximum:a.maxLength.value,type:"array",inclusive:!0,exact:!1,message:a.maxLength.message}),r.dirty()),t.common.async)return Promise.all([...t.data].map((e,r)=>a.type._parseAsync(new S(t,e,t.path,r)))).then(e=>h.mergeArray(r,e));const i=[...t.data].map((e,r)=>a.type._parseSync(new S(t,e,t.path,r)));return h.mergeArray(r,i)}get element(){return this._def.type}min(e,t){return new ne({...this._def,minLength:{value:e,message:u.toString(t)}})}max(e,t){return new ne({...this._def,maxLength:{value:e,message:u.toString(t)}})}length(e,t){return new ne({...this._def,exactLength:{value:e,message:u.toString(t)}})}nonempty(e){return this.min(1,e)}}function oe(e){if(e instanceof ce){const t={};for(const r in e.shape){const a=e.shape[r];t[r]=we.create(oe(a))}return new ce({...e._def,shape:()=>t})}return e instanceof ne?new ne({...e._def,type:oe(e.element)}):e instanceof we?we.create(oe(e.unwrap())):e instanceof Ce?Ce.create(oe(e.unwrap())):e instanceof fe?fe.create(e.items.map(e=>oe(e))):e}ne.create=(e,t)=>new ne({type:e,minLength:null,maxLength:null,exactLength:null,typeName:Re.ZodArray,...E(t)});class ce extends P{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(null!==this._cached)return this._cached;const e=this._def.shape(),r=t.objectKeys(e);return this._cached={shape:e,keys:r},this._cached}_parse(e){if(this._getType(e)!==s.object){const t=this._getOrReturnCtx(e);return l(t,{code:n.invalid_type,expected:s.object,received:t.parsedType}),p}const{status:t,ctx:r}=this._processInputParams(e),{shape:a,keys:i}=this._getCached(),o=[];if(!(this._def.catchall instanceof se&&"strip"===this._def.unknownKeys))for(const e in r.data)i.includes(e)||o.push(e);const c=[];for(const e of i){const t=a[e],s=r.data[e];c.push({key:{status:"valid",value:e},value:t._parse(new S(r,s,r.path,e)),alwaysSet:e in r.data})}if(this._def.catchall instanceof se){const e=this._def.unknownKeys;if("passthrough"===e)for(const e of o)c.push({key:{status:"valid",value:e},value:{status:"valid",value:r.data[e]}});else if("strict"===e)o.length>0&&(l(r,{code:n.unrecognized_keys,keys:o}),t.dirty());else if("strip"!==e)throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const e=this._def.catchall;for(const t of o){const a=r.data[t];c.push({key:{status:"valid",value:t},value:e._parse(new S(r,a,r.path,t)),alwaysSet:t in r.data})}}return r.common.async?Promise.resolve().then(async()=>{const e=[];for(const t of c){const r=await t.key,a=await t.value;e.push({key:r,value:a,alwaysSet:t.alwaysSet})}return e}).then(e=>h.mergeObjectSync(t,e)):h.mergeObjectSync(t,c)}get shape(){return this._def.shape()}strict(e){return u.errToObj,new ce({...this._def,unknownKeys:"strict",...void 0!==e?{errorMap:(t,r)=>{const a=this._def.errorMap?.(t,r).message??r.defaultError;return"unrecognized_keys"===t.code?{message:u.errToObj(e).message??a}:{message:a}}}:{}})}strip(){return new ce({...this._def,unknownKeys:"strip"})}passthrough(){return new ce({...this._def,unknownKeys:"passthrough"})}extend(e){return new ce({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new ce({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:Re.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new ce({...this._def,catchall:e})}pick(e){const r={};for(const a of t.objectKeys(e))e[a]&&this.shape[a]&&(r[a]=this.shape[a]);return new ce({...this._def,shape:()=>r})}omit(e){const r={};for(const a of t.objectKeys(this.shape))e[a]||(r[a]=this.shape[a]);return new ce({...this._def,shape:()=>r})}deepPartial(){return oe(this)}partial(e){const r={};for(const a of t.objectKeys(this.shape)){const t=this.shape[a];e&&!e[a]?r[a]=t:r[a]=t.optional()}return new ce({...this._def,shape:()=>r})}required(e){const r={};for(const a of t.objectKeys(this.shape))if(e&&!e[a])r[a]=this.shape[a];else{let e=this.shape[a];for(;e instanceof we;)e=e._def.innerType;r[a]=e}return new ce({...this._def,shape:()=>r})}keyof(){return Se(t.objectKeys(this.shape))}}ce.create=(e,t)=>new ce({shape:()=>e,unknownKeys:"strip",catchall:se.create(),typeName:Re.ZodObject,...E(t)}),ce.strictCreate=(e,t)=>new ce({shape:()=>e,unknownKeys:"strict",catchall:se.create(),typeName:Re.ZodObject,...E(t)}),ce.lazycreate=(e,t)=>new ce({shape:e,unknownKeys:"strip",catchall:se.create(),typeName:Re.ZodObject,...E(t)});class de extends P{_parse(e){const{ctx:t}=this._processInputParams(e),r=this._def.options;if(t.common.async)return Promise.all(r.map(async e=>{const r={...t,common:{...t.common,issues:[]},parent:null};return{result:await e._parseAsync({data:t.data,path:t.path,parent:r}),ctx:r}})).then(function(e){for(const t of e)if("valid"===t.result.status)return t.result;for(const r of e)if("dirty"===r.result.status)return t.common.issues.push(...r.ctx.common.issues),r.result;const r=e.map(e=>new o(e.ctx.common.issues));return l(t,{code:n.invalid_union,unionErrors:r}),p});{let e;const a=[];for(const s of r){const r={...t,common:{...t.common,issues:[]},parent:null},i=s._parseSync({data:t.data,path:t.path,parent:r});if("valid"===i.status)return i;"dirty"!==i.status||e||(e={result:i,ctx:r}),r.common.issues.length&&a.push(r.common.issues)}if(e)return t.common.issues.push(...e.ctx.common.issues),e.result;const s=a.map(e=>new o(e));return l(t,{code:n.invalid_union,unionErrors:s}),p}}get options(){return this._def.options}}de.create=(e,t)=>new de({options:e,typeName:Re.ZodUnion,...E(t)});const ue=e=>e instanceof ve?ue(e.schema):e instanceof Ie?ue(e.innerType()):e instanceof _e?[e.value]:e instanceof be?e.options:e instanceof Ee?t.objectValues(e.enum):e instanceof Te?ue(e._def.innerType):e instanceof ee?[void 0]:e instanceof te?[null]:e instanceof we?[void 0,...ue(e.unwrap())]:e instanceof Ce?[null,...ue(e.unwrap())]:e instanceof Oe||e instanceof ke?ue(e.unwrap()):e instanceof De?ue(e._def.innerType):[];class le extends P{_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==s.object)return l(t,{code:n.invalid_type,expected:s.object,received:t.parsedType}),p;const r=this.discriminator,a=t.data[r],i=this.optionsMap.get(a);return i?t.common.async?i._parseAsync({data:t.data,path:t.path,parent:t}):i._parseSync({data:t.data,path:t.path,parent:t}):(l(t,{code:n.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),p)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,t,r){const a=new Map;for(const r of t){const t=ue(r.shape[e]);if(!t.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(const s of t){if(a.has(s))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(s)}`);a.set(s,r)}}return new le({typeName:Re.ZodDiscriminatedUnion,discriminator:e,options:t,optionsMap:a,...E(r)})}}function he(e,r){const a=i(e),n=i(r);if(e===r)return{valid:!0,data:e};if(a===s.object&&n===s.object){const a=t.objectKeys(r),s=t.objectKeys(e).filter(e=>-1!==a.indexOf(e)),i={...e,...r};for(const t of s){const a=he(e[t],r[t]);if(!a.valid)return{valid:!1};i[t]=a.data}return{valid:!0,data:i}}if(a===s.array&&n===s.array){if(e.length!==r.length)return{valid:!1};const t=[];for(let a=0;a<e.length;a++){const s=he(e[a],r[a]);if(!s.valid)return{valid:!1};t.push(s.data)}return{valid:!0,data:t}}return a===s.date&&n===s.date&&+e===+r?{valid:!0,data:e}:{valid:!1}}class pe extends P{_parse(e){const{status:t,ctx:r}=this._processInputParams(e),a=(e,a)=>{if(g(e)||g(a))return p;const s=he(e.value,a.value);return s.valid?((y(e)||y(a))&&t.dirty(),{status:t.value,value:s.data}):(l(r,{code:n.invalid_intersection_types}),p)};return r.common.async?Promise.all([this._def.left._parseAsync({data:r.data,path:r.path,parent:r}),this._def.right._parseAsync({data:r.data,path:r.path,parent:r})]).then(([e,t])=>a(e,t)):a(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}}pe.create=(e,t,r)=>new pe({left:e,right:t,typeName:Re.ZodIntersection,...E(r)});class fe extends P{_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==s.array)return l(r,{code:n.invalid_type,expected:s.array,received:r.parsedType}),p;if(r.data.length<this._def.items.length)return l(r,{code:n.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),p;!this._def.rest&&r.data.length>this._def.items.length&&(l(r,{code:n.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());const a=[...r.data].map((e,t)=>{const a=this._def.items[t]||this._def.rest;return a?a._parse(new S(r,e,r.path,t)):null}).filter(e=>!!e);return r.common.async?Promise.all(a).then(e=>h.mergeArray(t,e)):h.mergeArray(t,a)}get items(){return this._def.items}rest(e){return new fe({...this._def,rest:e})}}fe.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new fe({items:e,typeName:Re.ZodTuple,rest:null,...E(t)})};class me extends P{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==s.object)return l(r,{code:n.invalid_type,expected:s.object,received:r.parsedType}),p;const a=[],i=this._def.keyType,o=this._def.valueType;for(const e in r.data)a.push({key:i._parse(new S(r,e,r.path,e)),value:o._parse(new S(r,r.data[e],r.path,e)),alwaysSet:e in r.data});return r.common.async?h.mergeObjectAsync(t,a):h.mergeObjectSync(t,a)}get element(){return this._def.valueType}static create(e,t,r){return new me(t instanceof P?{keyType:e,valueType:t,typeName:Re.ZodRecord,...E(r)}:{keyType:B.create(),valueType:e,typeName:Re.ZodRecord,...E(t)})}}class ge extends P{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==s.map)return l(r,{code:n.invalid_type,expected:s.map,received:r.parsedType}),p;const a=this._def.keyType,i=this._def.valueType,o=[...r.data.entries()].map(([e,t],s)=>({key:a._parse(new S(r,e,r.path,[s,"key"])),value:i._parse(new S(r,t,r.path,[s,"value"]))}));if(r.common.async){const e=new Map;return Promise.resolve().then(async()=>{for(const r of o){const a=await r.key,s=await r.value;if("aborted"===a.status||"aborted"===s.status)return p;"dirty"!==a.status&&"dirty"!==s.status||t.dirty(),e.set(a.value,s.value)}return{status:t.value,value:e}})}{const e=new Map;for(const r of o){const a=r.key,s=r.value;if("aborted"===a.status||"aborted"===s.status)return p;"dirty"!==a.status&&"dirty"!==s.status||t.dirty(),e.set(a.value,s.value)}return{status:t.value,value:e}}}}ge.create=(e,t,r)=>new ge({valueType:t,keyType:e,typeName:Re.ZodMap,...E(r)});class ye extends P{_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==s.set)return l(r,{code:n.invalid_type,expected:s.set,received:r.parsedType}),p;const a=this._def;null!==a.minSize&&r.data.size<a.minSize.value&&(l(r,{code:n.too_small,minimum:a.minSize.value,type:"set",inclusive:!0,exact:!1,message:a.minSize.message}),t.dirty()),null!==a.maxSize&&r.data.size>a.maxSize.value&&(l(r,{code:n.too_big,maximum:a.maxSize.value,type:"set",inclusive:!0,exact:!1,message:a.maxSize.message}),t.dirty());const i=this._def.valueType;function o(e){const r=new Set;for(const a of e){if("aborted"===a.status)return p;"dirty"===a.status&&t.dirty(),r.add(a.value)}return{status:t.value,value:r}}const c=[...r.data.values()].map((e,t)=>i._parse(new S(r,e,r.path,t)));return r.common.async?Promise.all(c).then(e=>o(e)):o(c)}min(e,t){return new ye({...this._def,minSize:{value:e,message:u.toString(t)}})}max(e,t){return new ye({...this._def,maxSize:{value:e,message:u.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}}ye.create=(e,t)=>new ye({valueType:e,minSize:null,maxSize:null,typeName:Re.ZodSet,...E(t)});class ve extends P{get schema(){return this._def.getter()}_parse(e){const{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}}ve.create=(e,t)=>new ve({getter:e,typeName:Re.ZodLazy,...E(t)});class _e extends P{_parse(e){if(e.data!==this._def.value){const t=this._getOrReturnCtx(e);return l(t,{received:t.data,code:n.invalid_literal,expected:this._def.value}),p}return{status:"valid",value:e.data}}get value(){return this._def.value}}function Se(e,t){return new be({values:e,typeName:Re.ZodEnum,...E(t)})}_e.create=(e,t)=>new _e({value:e,typeName:Re.ZodLiteral,...E(t)});class be extends P{_parse(e){if("string"!=typeof e.data){const r=this._getOrReturnCtx(e),a=this._def.values;return l(r,{expected:t.joinValues(a),received:r.parsedType,code:n.invalid_type}),p}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){const t=this._getOrReturnCtx(e),r=this._def.values;return l(t,{received:t.data,code:n.invalid_enum_value,options:r}),p}return m(e.data)}get options(){return this._def.values}get enum(){const e={};for(const t of this._def.values)e[t]=t;return e}get Values(){const e={};for(const t of this._def.values)e[t]=t;return e}get Enum(){const e={};for(const t of this._def.values)e[t]=t;return e}extract(e,t=this._def){return be.create(e,{...this._def,...t})}exclude(e,t=this._def){return be.create(this.options.filter(t=>!e.includes(t)),{...this._def,...t})}}be.create=Se;class Ee extends P{_parse(e){const r=t.getValidEnumValues(this._def.values),a=this._getOrReturnCtx(e);if(a.parsedType!==s.string&&a.parsedType!==s.number){const e=t.objectValues(r);return l(a,{expected:t.joinValues(e),received:a.parsedType,code:n.invalid_type}),p}if(this._cache||(this._cache=new Set(t.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){const e=t.objectValues(r);return l(a,{received:a.data,code:n.invalid_enum_value,options:e}),p}return m(e.data)}get enum(){return this._def.values}}Ee.create=(e,t)=>new Ee({values:e,typeName:Re.ZodNativeEnum,...E(t)});class Pe extends P{unwrap(){return this._def.type}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==s.promise&&!1===t.common.async)return l(t,{code:n.invalid_type,expected:s.promise,received:t.parsedType}),p;const r=t.parsedType===s.promise?t.data:Promise.resolve(t.data);return m(r.then(e=>this._def.type.parseAsync(e,{path:t.path,errorMap:t.common.contextualErrorMap})))}}Pe.create=(e,t)=>new Pe({type:e,typeName:Re.ZodPromise,...E(t)});class Ie extends P{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===Re.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){const{status:r,ctx:a}=this._processInputParams(e),s=this._def.effect||null,i={addIssue:e=>{l(a,e),e.fatal?r.abort():r.dirty()},get path(){return a.path}};if(i.addIssue=i.addIssue.bind(i),"preprocess"===s.type){const e=s.transform(a.data,i);if(a.common.async)return Promise.resolve(e).then(async e=>{if("aborted"===r.value)return p;const t=await this._def.schema._parseAsync({data:e,path:a.path,parent:a});return"aborted"===t.status?p:"dirty"===t.status||"dirty"===r.value?f(t.value):t});{if("aborted"===r.value)return p;const t=this._def.schema._parseSync({data:e,path:a.path,parent:a});return"aborted"===t.status?p:"dirty"===t.status||"dirty"===r.value?f(t.value):t}}if("refinement"===s.type){const e=e=>{const t=s.refinement(e,i);if(a.common.async)return Promise.resolve(t);if(t instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return e};if(!1===a.common.async){const t=this._def.schema._parseSync({data:a.data,path:a.path,parent:a});return"aborted"===t.status?p:("dirty"===t.status&&r.dirty(),e(t.value),{status:r.value,value:t.value})}return this._def.schema._parseAsync({data:a.data,path:a.path,parent:a}).then(t=>"aborted"===t.status?p:("dirty"===t.status&&r.dirty(),e(t.value).then(()=>({status:r.value,value:t.value}))))}if("transform"===s.type){if(!1===a.common.async){const e=this._def.schema._parseSync({data:a.data,path:a.path,parent:a});if(!v(e))return p;const t=s.transform(e.value,i);if(t instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:r.value,value:t}}return this._def.schema._parseAsync({data:a.data,path:a.path,parent:a}).then(e=>v(e)?Promise.resolve(s.transform(e.value,i)).then(e=>({status:r.value,value:e})):p)}t.assertNever(s)}}Ie.create=(e,t,r)=>new Ie({schema:e,typeName:Re.ZodEffects,effect:t,...E(r)}),Ie.createWithPreprocess=(e,t,r)=>new Ie({schema:t,effect:{type:"preprocess",transform:e},typeName:Re.ZodEffects,...E(r)});class we extends P{_parse(e){return this._getType(e)===s.undefined?m(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}we.create=(e,t)=>new we({innerType:e,typeName:Re.ZodOptional,...E(t)});class Ce extends P{_parse(e){return this._getType(e)===s.null?m(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}Ce.create=(e,t)=>new Ce({innerType:e,typeName:Re.ZodNullable,...E(t)});class Te extends P{_parse(e){const{ctx:t}=this._processInputParams(e);let r=t.data;return t.parsedType===s.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:t.path,parent:t})}removeDefault(){return this._def.innerType}}Te.create=(e,t)=>new Te({innerType:e,typeName:Re.ZodDefault,defaultValue:"function"==typeof t.default?t.default:()=>t.default,...E(t)});class De extends P{_parse(e){const{ctx:t}=this._processInputParams(e),r={...t,common:{...t.common,issues:[]}},a=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return _(a)?a.then(e=>({status:"valid",value:"valid"===e.status?e.value:this._def.catchValue({get error(){return new o(r.common.issues)},input:r.data})})):{status:"valid",value:"valid"===a.status?a.value:this._def.catchValue({get error(){return new o(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}}De.create=(e,t)=>new De({innerType:e,typeName:Re.ZodCatch,catchValue:"function"==typeof t.catch?t.catch:()=>t.catch,...E(t)});class xe extends P{_parse(e){if(this._getType(e)!==s.nan){const t=this._getOrReturnCtx(e);return l(t,{code:n.invalid_type,expected:s.nan,received:t.parsedType}),p}return{status:"valid",value:e.data}}}xe.create=e=>new xe({typeName:Re.ZodNaN,...E(e)}),Symbol("zod_brand");class Oe extends P{_parse(e){const{ctx:t}=this._processInputParams(e),r=t.data;return this._def.type._parse({data:r,path:t.path,parent:t})}unwrap(){return this._def.type}}class Ae extends P{_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.common.async)return(async()=>{const e=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return"aborted"===e.status?p:"dirty"===e.status?(t.dirty(),f(e.value)):this._def.out._parseAsync({data:e.value,path:r.path,parent:r})})();{const e=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return"aborted"===e.status?p:"dirty"===e.status?(t.dirty(),{status:"dirty",value:e.value}):this._def.out._parseSync({data:e.value,path:r.path,parent:r})}}static create(e,t){return new Ae({in:e,out:t,typeName:Re.ZodPipeline})}}class ke extends P{_parse(e){const t=this._def.innerType._parse(e),r=e=>(v(e)&&(e.value=Object.freeze(e.value)),e);return _(t)?t.then(e=>r(e)):r(t)}unwrap(){return this._def.innerType}}var Re;ke.create=(e,t)=>new ke({innerType:e,typeName:Re.ZodReadonly,...E(t)}),ce.lazycreate,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"}(Re||(Re={}));const Ne=B.create,je=G.create,ze=(xe.create,J.create,X.create),$e=(Q.create,Y.create,ee.create,te.create,re.create,ae.create),Me=(se.create,ie.create,ne.create),Le=ce.create,Fe=(ce.strictCreate,de.create),Ze=le.create,Ve=(pe.create,fe.create,me.create),Ke=(ge.create,ye.create,ve.create,_e.create),Ue=be.create,He=(Ee.create,Pe.create,Ie.create,we.create),qe=(Ce.create,Ie.createWithPreprocess,Ae.create,"2025-06-18"),Be=[qe,"2025-03-26","2024-11-05","2024-10-07"],We="2.0",Ge=Fe([Ne(),je().int()]),Je=Ne(),Xe=Le({progressToken:He(Ge)}).passthrough(),Qe=Le({_meta:He(Xe)}).passthrough(),Ye=Le({method:Ne(),params:He(Qe)}),et=Le({_meta:He(Le({}).passthrough())}).passthrough(),tt=Le({method:Ne(),params:He(et)}),rt=Le({_meta:He(Le({}).passthrough())}).passthrough(),at=Fe([Ne(),je().int()]),st=Le({jsonrpc:Ke(We),id:at}).merge(Ye).strict(),it=Le({jsonrpc:Ke(We)}).merge(tt).strict(),nt=Le({jsonrpc:Ke(We),id:at,result:rt}).strict(),ot=e=>nt.safeParse(e).success;var ct;!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"}(ct||(ct={}));const dt=Le({jsonrpc:Ke(We),id:at,error:Le({code:je().int(),message:Ne(),data:He($e())})}).strict(),ut=Fe([st,it,nt,dt]),lt=rt.strict(),ht=tt.extend({method:Ke("notifications/cancelled"),params:et.extend({requestId:at,reason:Ne().optional()})}),pt=Le({src:Ne(),mimeType:He(Ne()),sizes:He(Ne())}).passthrough(),ft=Le({name:Ne(),title:He(Ne())}).passthrough(),mt=ft.extend({version:Ne(),websiteUrl:He(Ne()),icons:He(Me(pt))}),gt=Le({experimental:He(Le({}).passthrough()),sampling:He(Le({}).passthrough()),elicitation:He(Le({}).passthrough()),roots:He(Le({listChanged:He(ze())}).passthrough())}).passthrough(),yt=Ye.extend({method:Ke("initialize"),params:Qe.extend({protocolVersion:Ne(),capabilities:gt,clientInfo:mt})}),vt=Le({experimental:He(Le({}).passthrough()),logging:He(Le({}).passthrough()),completions:He(Le({}).passthrough()),prompts:He(Le({listChanged:He(ze())}).passthrough()),resources:He(Le({subscribe:He(ze()),listChanged:He(ze())}).passthrough()),tools:He(Le({listChanged:He(ze())}).passthrough())}).passthrough(),_t=rt.extend({protocolVersion:Ne(),capabilities:vt,serverInfo:mt,instructions:He(Ne())}),St=tt.extend({method:Ke("notifications/initialized")}),bt=Ye.extend({method:Ke("ping")}),Et=Le({progress:je(),total:He(je()),message:He(Ne())}).passthrough(),Pt=tt.extend({method:Ke("notifications/progress"),params:et.merge(Et).extend({progressToken:Ge})}),It=Ye.extend({params:Qe.extend({cursor:He(Je)}).optional()}),wt=rt.extend({nextCursor:He(Je)}),Ct=Le({uri:Ne(),mimeType:He(Ne()),_meta:He(Le({}).passthrough())}).passthrough(),Tt=Ct.extend({text:Ne()}),Dt=Ne().refine(e=>{try{return atob(e),!0}catch(e){return!1}},{message:"Invalid Base64 string"}),xt=Ct.extend({blob:Dt}),Ot=ft.extend({uri:Ne(),description:He(Ne()),mimeType:He(Ne()),icons:He(Me(pt)),_meta:He(Le({}).passthrough())}),At=ft.extend({uriTemplate:Ne(),description:He(Ne()),mimeType:He(Ne()),_meta:He(Le({}).passthrough())}),kt=It.extend({method:Ke("resources/list")}),Rt=wt.extend({resources:Me(Ot)}),Nt=It.extend({method:Ke("resources/templates/list")}),jt=wt.extend({resourceTemplates:Me(At)}),zt=Ye.extend({method:Ke("resources/read"),params:Qe.extend({uri:Ne()})}),$t=rt.extend({contents:Me(Fe([Tt,xt]))}),Mt=tt.extend({method:Ke("notifications/resources/list_changed")}),Lt=Ye.extend({method:Ke("resources/subscribe"),params:Qe.extend({uri:Ne()})}),Ft=Ye.extend({method:Ke("resources/unsubscribe"),params:Qe.extend({uri:Ne()})}),Zt=tt.extend({method:Ke("notifications/resources/updated"),params:et.extend({uri:Ne()})}),Vt=Le({name:Ne(),description:He(Ne()),required:He(ze())}).passthrough(),Kt=ft.extend({description:He(Ne()),arguments:He(Me(Vt)),icons:He(Me(pt)),_meta:He(Le({}).passthrough())}),Ut=It.extend({method:Ke("prompts/list")}),Ht=wt.extend({prompts:Me(Kt)}),qt=Ye.extend({method:Ke("prompts/get"),params:Qe.extend({name:Ne(),arguments:He(Ve(Ne()))})}),Bt=Le({type:Ke("text"),text:Ne(),_meta:He(Le({}).passthrough())}).passthrough(),Wt=Le({type:Ke("image"),data:Dt,mimeType:Ne(),_meta:He(Le({}).passthrough())}).passthrough(),Gt=Le({type:Ke("audio"),data:Dt,mimeType:Ne(),_meta:He(Le({}).passthrough())}).passthrough(),Jt=Le({type:Ke("resource"),resource:Fe([Tt,xt]),_meta:He(Le({}).passthrough())}).passthrough(),Xt=Fe([Bt,Wt,Gt,Ot.extend({type:Ke("resource_link")}),Jt]),Qt=Le({role:Ue(["user","assistant"]),content:Xt}).passthrough(),Yt=rt.extend({description:He(Ne()),messages:Me(Qt)}),er=tt.extend({method:Ke("notifications/prompts/list_changed")}),tr=Le({title:He(Ne()),readOnlyHint:He(ze()),destructiveHint:He(ze()),idempotentHint:He(ze()),openWorldHint:He(ze())}).passthrough(),rr=ft.extend({description:He(Ne()),inputSchema:Le({type:Ke("object"),properties:He(Le({}).passthrough()),required:He(Me(Ne()))}).passthrough(),outputSchema:He(Le({type:Ke("object"),properties:He(Le({}).passthrough()),required:He(Me(Ne()))}).passthrough()),annotations:He(tr),icons:He(Me(pt)),_meta:He(Le({}).passthrough())}),ar=It.extend({method:Ke("tools/list")}),sr=wt.extend({tools:Me(rr)}),ir=rt.extend({content:Me(Xt).default([]),structuredContent:Le({}).passthrough().optional(),isError:He(ze())}),nr=(ir.or(rt.extend({toolResult:$e()})),Ye.extend({method:Ke("tools/call"),params:Qe.extend({name:Ne(),arguments:He(Ve($e()))})})),or=tt.extend({method:Ke("notifications/tools/list_changed")}),cr=Ue(["debug","info","notice","warning","error","critical","alert","emergency"]),dr=Ye.extend({method:Ke("logging/setLevel"),params:Qe.extend({level:cr})}),ur=tt.extend({method:Ke("notifications/message"),params:et.extend({level:cr,logger:He(Ne()),data:$e()})}),lr=Le({name:Ne().optional()}).passthrough(),hr=Le({hints:He(Me(lr)),costPriority:He(je().min(0).max(1)),speedPriority:He(je().min(0).max(1)),intelligencePriority:He(je().min(0).max(1))}).passthrough(),pr=Le({role:Ue(["user","assistant"]),content:Fe([Bt,Wt,Gt])}).passthrough(),fr=Ye.extend({method:Ke("sampling/createMessage"),params:Qe.extend({messages:Me(pr),systemPrompt:He(Ne()),includeContext:He(Ue(["none","thisServer","allServers"])),temperature:He(je()),maxTokens:je().int(),stopSequences:He(Me(Ne())),metadata:He(Le({}).passthrough()),modelPreferences:He(hr)})}),mr=rt.extend({model:Ne(),stopReason:He(Ue(["endTurn","stopSequence","maxTokens"]).or(Ne())),role:Ue(["user","assistant"]),content:Ze("type",[Bt,Wt,Gt])}),gr=Fe([Le({type:Ke("boolean"),title:He(Ne()),description:He(Ne()),default:He(ze())}).passthrough(),Le({type:Ke("string"),title:He(Ne()),description:He(Ne()),minLength:He(je()),maxLength:He(je()),format:He(Ue(["email","uri","date","date-time"]))}).passthrough(),Le({type:Ue(["number","integer"]),title:He(Ne()),description:He(Ne()),minimum:He(je()),maximum:He(je())}).passthrough(),Le({type:Ke("string"),title:He(Ne()),description:He(Ne()),enum:Me(Ne()),enumNames:He(Me(Ne()))}).passthrough()]),yr=Ye.extend({method:Ke("elicitation/create"),params:Qe.extend({message:Ne(),requestedSchema:Le({type:Ke("object"),properties:Ve(Ne(),gr),required:He(Me(Ne()))}).passthrough()})}),vr=rt.extend({action:Ue(["accept","decline","cancel"]),content:He(Ve(Ne(),$e()))}),_r=Le({type:Ke("ref/resource"),uri:Ne()}).passthrough(),Sr=Le({type:Ke("ref/prompt"),name:Ne()}).passthrough(),br=Ye.extend({method:Ke("completion/complete"),params:Qe.extend({ref:Fe([Sr,_r]),argument:Le({name:Ne(),value:Ne()}).passthrough(),context:He(Le({arguments:He(Ve(Ne(),Ne()))}))})}),Er=rt.extend({completion:Le({values:Me(Ne()).max(100),total:He(je().int()),hasMore:He(ze())}).passthrough()}),Pr=Le({uri:Ne().startsWith("file://"),name:He(Ne()),_meta:He(Le({}).passthrough())}).passthrough(),Ir=Ye.extend({method:Ke("roots/list")}),wr=rt.extend({roots:Me(Pr)}),Cr=tt.extend({method:Ke("notifications/roots/list_changed")});Fe([bt,yt,br,dr,qt,Ut,kt,Nt,zt,Lt,Ft,nr,ar]),Fe([ht,Pt,St,Cr]),Fe([lt,mr,vr,wr]),Fe([bt,fr,yr,Ir]),Fe([ht,Pt,ur,Zt,Mt,or,er]),Fe([lt,_t,Er,Yt,Ht,Rt,jt,$t,ir,sr]);class Tr extends Error{constructor(e,t,r){super(`MCP error ${e}: ${t}`),this.code=e,this.data=r,this.name="McpError"}}class Dr{append(e){this._buffer=this._buffer?Buffer.concat([this._buffer,e]):e}readMessage(){if(!this._buffer)return null;const e=this._buffer.indexOf("\n");if(-1===e)return null;const t=this._buffer.toString("utf8",0,e).replace(/\r$/,"");return this._buffer=this._buffer.subarray(e+1),function(e){return ut.parse(JSON.parse(e))}(t)}clear(){this._buffer=void 0}}class xr{constructor(t=e.stdin,r=e.stdout){this._stdin=t,this._stdout=r,this._readBuffer=new Dr,this._started=!1,this._ondata=e=>{this._readBuffer.append(e),this.processReadBuffer()},this._onerror=e=>{var t;null===(t=this.onerror)||void 0===t||t.call(this,e)}}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(var e,t;;)try{const t=this._readBuffer.readMessage();if(null===t)break;null===(e=this.onmessage)||void 0===e||e.call(this,t)}catch(e){null===(t=this.onerror)||void 0===t||t.call(this,e)}}async close(){var e;this._stdin.off("data",this._ondata),this._stdin.off("error",this._onerror),0===this._stdin.listenerCount("data")&&this._stdin.pause(),this._readBuffer.clear(),null===(e=this.onclose)||void 0===e||e.call(this)}send(e){return new Promise(t=>{const r=function(e){return JSON.stringify(e)+"\n"}(e);this._stdout.write(r)?t():this._stdout.once("drain",t)})}}class Or{constructor(e){this._options=e,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.setNotificationHandler(ht,e=>{const t=this._requestHandlerAbortControllers.get(e.params.requestId);null==t||t.abort(e.params.reason)}),this.setNotificationHandler(Pt,e=>{this._onprogress(e)}),this.setRequestHandler(bt,e=>({}))}_setupTimeout(e,t,r,a,s=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(a,t),startTime:Date.now(),timeout:t,maxTotalTimeout:r,resetTimeoutOnProgress:s,onTimeout:a})}_resetTimeout(e){const t=this._timeoutInfo.get(e);if(!t)return!1;const r=Date.now()-t.startTime;if(t.maxTotalTimeout&&r>=t.maxTotalTimeout)throw this._timeoutInfo.delete(e),new Tr(ct.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:t.maxTotalTimeout,totalElapsed:r});return clearTimeout(t.timeoutId),t.timeoutId=setTimeout(t.onTimeout,t.timeout),!0}_cleanupTimeout(e){const t=this._timeoutInfo.get(e);t&&(clearTimeout(t.timeoutId),this._timeoutInfo.delete(e))}async connect(e){var t,r,a;this._transport=e;const s=null===(t=this.transport)||void 0===t?void 0:t.onclose;this._transport.onclose=()=>{null==s||s(),this._onclose()};const i=null===(r=this.transport)||void 0===r?void 0:r.onerror;this._transport.onerror=e=>{null==i||i(e),this._onerror(e)};const n=null===(a=this._transport)||void 0===a?void 0:a.onmessage;this._transport.onmessage=(e,t)=>{var r;null==n||n(e,t),ot(e)||(r=e,dt.safeParse(r).success)?this._onresponse(e):(e=>st.safeParse(e).success)(e)?this._onrequest(e,t):(e=>it.safeParse(e).success)(e)?this._onnotification(e):this._onerror(new Error(`Unknown message type: ${JSON.stringify(e)}`))},await this._transport.start()}_onclose(){var e;const t=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._pendingDebouncedNotifications.clear(),this._transport=void 0,null===(e=this.onclose)||void 0===e||e.call(this);const r=new Tr(ct.ConnectionClosed,"Connection closed");for(const e of t.values())e(r)}_onerror(e){var t;null===(t=this.onerror)||void 0===t||t.call(this,e)}_onnotification(e){var t;const r=null!==(t=this._notificationHandlers.get(e.method))&&void 0!==t?t:this.fallbackNotificationHandler;void 0!==r&&Promise.resolve().then(()=>r(e)).catch(e=>this._onerror(new Error(`Uncaught error in notification handler: ${e}`)))}_onrequest(e,t){var r,a;const s=null!==(r=this._requestHandlers.get(e.method))&&void 0!==r?r:this.fallbackRequestHandler,i=this._transport;if(void 0===s)return void(null==i||i.send({jsonrpc:"2.0",id:e.id,error:{code:ct.MethodNotFound,message:"Method not found"}}).catch(e=>this._onerror(new Error(`Failed to send an error response: ${e}`))));const n=new AbortController;this._requestHandlerAbortControllers.set(e.id,n);const o={signal:n.signal,sessionId:null==i?void 0:i.sessionId,_meta:null===(a=e.params)||void 0===a?void 0:a._meta,sendNotification:t=>this.notification(t,{relatedRequestId:e.id}),sendRequest:(t,r,a)=>this.request(t,r,{...a,relatedRequestId:e.id}),authInfo:null==t?void 0:t.authInfo,requestId:e.id,requestInfo:null==t?void 0:t.requestInfo};Promise.resolve().then(()=>s(e,o)).then(t=>{if(!n.signal.aborted)return null==i?void 0:i.send({result:t,jsonrpc:"2.0",id:e.id})},t=>{var r;if(!n.signal.aborted)return null==i?void 0:i.send({jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(t.code)?t.code:ct.InternalError,message:null!==(r=t.message)&&void 0!==r?r:"Internal error"}})}).catch(e=>this._onerror(new Error(`Failed to send response: ${e}`))).finally(()=>{this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){const{progressToken:t,...r}=e.params,a=Number(t),s=this._progressHandlers.get(a);if(!s)return void this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));const i=this._responseHandlers.get(a),n=this._timeoutInfo.get(a);if(n&&i&&n.resetTimeoutOnProgress)try{this._resetTimeout(a)}catch(e){return void i(e)}s(r)}_onresponse(e){const t=Number(e.id),r=this._responseHandlers.get(t);void 0!==r?(this._responseHandlers.delete(t),this._progressHandlers.delete(t),this._cleanupTimeout(t),ot(e)?r(e):r(new Tr(e.error.code,e.error.message,e.error.data))):this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`))}get transport(){return this._transport}async close(){var e;await(null===(e=this._transport)||void 0===e?void 0:e.close())}request(e,t,r){const{relatedRequestId:a,resumptionToken:s,onresumptiontoken:i}=null!=r?r:{};return new Promise((n,o)=>{var c,d,u,l,h,p;if(!this._transport)return void o(new Error("Not connected"));!0===(null===(c=this._options)||void 0===c?void 0:c.enforceStrictCapabilities)&&this.assertCapabilityForMethod(e.method),null===(d=null==r?void 0:r.signal)||void 0===d||d.throwIfAborted();const f=this._requestMessageId++,m={...e,jsonrpc:"2.0",id:f};(null==r?void 0:r.onprogress)&&(this._progressHandlers.set(f,r.onprogress),m.params={...e.params,_meta:{...(null===(u=e.params)||void 0===u?void 0:u._meta)||{},progressToken:f}});const g=e=>{var t;this._responseHandlers.delete(f),this._progressHandlers.delete(f),this._cleanupTimeout(f),null===(t=this._transport)||void 0===t||t.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:f,reason:String(e)}},{relatedRequestId:a,resumptionToken:s,onresumptiontoken:i}).catch(e=>this._onerror(new Error(`Failed to send cancellation: ${e}`))),o(e)};this._responseHandlers.set(f,e=>{var a;if(!(null===(a=null==r?void 0:r.signal)||void 0===a?void 0:a.aborted)){if(e instanceof Error)return o(e);try{const r=t.parse(e.result);n(r)}catch(e){o(e)}}}),null===(l=null==r?void 0:r.signal)||void 0===l||l.addEventListener("abort",()=>{var e;g(null===(e=null==r?void 0:r.signal)||void 0===e?void 0:e.reason)});const y=null!==(h=null==r?void 0:r.timeout)&&void 0!==h?h:6e4;this._setupTimeout(f,y,null==r?void 0:r.maxTotalTimeout,()=>g(new Tr(ct.RequestTimeout,"Request timed out",{timeout:y})),null!==(p=null==r?void 0:r.resetTimeoutOnProgress)&&void 0!==p&&p),this._transport.send(m,{relatedRequestId:a,resumptionToken:s,onresumptiontoken:i}).catch(e=>{this._cleanupTimeout(f),o(e)})})}async notification(e,t){var r,a;if(!this._transport)throw new Error("Not connected");if(this.assertNotificationCapability(e.method),(null!==(a=null===(r=this._options)||void 0===r?void 0:r.debouncedNotificationMethods)&&void 0!==a?a:[]).includes(e.method)&&!e.params&&!(null==t?void 0:t.relatedRequestId)){if(this._pendingDebouncedNotifications.has(e.method))return;return this._pendingDebouncedNotifications.add(e.method),void Promise.resolve().then(()=>{var r;if(this._pendingDebouncedNotifications.delete(e.method),!this._transport)return;const a={...e,jsonrpc:"2.0"};null===(r=this._transport)||void 0===r||r.send(a,t).catch(e=>this._onerror(e))})}const s={...e,jsonrpc:"2.0"};await this._transport.send(s,t)}setRequestHandler(e,t){const r=e.shape.method.value;this.assertRequestHandlerCapability(r),this._requestHandlers.set(r,(r,a)=>Promise.resolve(t(e.parse(r),a)))}removeRequestHandler(e){this._requestHandlers.delete(e)}assertCanSetRequestHandler(e){if(this._requestHandlers.has(e))throw new Error(`A request handler for ${e} already exists, which would be overridden`)}setNotificationHandler(e,t){this._notificationHandlers.set(e.shape.method.value,r=>Promise.resolve(t(e.parse(r))))}removeNotificationHandler(e){this._notificationHandlers.delete(e)}}var Ar=r(53084);class kr extends Or{constructor(e,t){var r;super(t),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(cr.options.map((e,t)=>[e,t])),this.isMessageIgnored=(e,t)=>{const r=this._loggingLevels.get(t);return!!r&&this.LOG_LEVEL_SEVERITY.get(e)<this.LOG_LEVEL_SEVERITY.get(r)},this._capabilities=null!==(r=null==t?void 0:t.capabilities)&&void 0!==r?r:{},this._instructions=null==t?void 0:t.instructions,this.setRequestHandler(yt,e=>this._oninitialize(e)),this.setNotificationHandler(St,()=>{var e;return null===(e=this.oninitialized)||void 0===e?void 0:e.call(this)}),this._capabilities.logging&&this.setRequestHandler(dr,async(e,t)=>{var r;const a=t.sessionId||(null===(r=t.requestInfo)||void 0===r?void 0:r.headers["mcp-session-id"])||void 0,{level:s}=e.params,i=cr.safeParse(s);return i.success&&this._loggingLevels.set(a,i.data),{}})}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");var t,r;this._capabilities=(t=this._capabilities,r=e,Object.entries(r).reduce((e,[t,r])=>(e[t]=r&&"object"==typeof r&&e[t]?{...e[t],...r}:r,e),{...t}))}assertCapabilityForMethod(e){var t,r,a;switch(e){case"sampling/createMessage":if(!(null===(t=this._clientCapabilities)||void 0===t?void 0:t.sampling))throw new Error(`Client does not support sampling (required for ${e})`);break;case"elicitation/create":if(!(null===(r=this._clientCapabilities)||void 0===r?void 0:r.elicitation))throw new Error(`Client does not support elicitation (required for ${e})`);break;case"roots/list":if(!(null===(a=this._clientCapabilities)||void 0===a?void 0:a.roots))throw new Error(`Client does not support listing roots (required for ${e})`)}}assertNotificationCapability(e){switch(e){case"notifications/message":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${e})`);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 ${e})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw new Error(`Server does not support notifying of tool list changes (required for ${e})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw new Error(`Server does not support notifying of prompt list changes (required for ${e})`)}}assertRequestHandlerCapability(e){switch(e){case"sampling/createMessage":if(!this._capabilities.sampling)throw new Error(`Server does not support sampling (required for ${e})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw new Error(`Server does not support prompts (required for ${e})`);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 ${e})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw new Error(`Server does not support tools (required for ${e})`)}}async _oninitialize(e){const t=e.params.protocolVersion;return this._clientCapabilities=e.params.capabilities,this._clientVersion=e.params.clientInfo,{protocolVersion:Be.includes(t)?t:qe,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"},lt)}async createMessage(e,t){return this.request({method:"sampling/createMessage",params:e},mr,t)}async elicitInput(e,t){const r=await this.request({method:"elicitation/create",params:e},vr,t);if("accept"===r.action&&r.content)try{const t=new Ar,a=t.compile(e.requestedSchema);if(!a(r.content))throw new Tr(ct.InvalidParams,`Elicitation response content does not match requested schema: ${t.errorsText(a.errors)}`)}catch(e){if(e instanceof Tr)throw e;throw new Tr(ct.InternalError,`Error validating elicitation response: ${e}`)}return r}async listRoots(e,t){return this.request({method:"roots/list",params:e},wr,t)}async sendLoggingMessage(e,t){if(this._capabilities.logging&&!this.isMessageIgnored(e.level,t))return this.notification({method:"notifications/message",params:e})}async sendResourceUpdated(e){return this.notification({method:"notifications/resources/updated",params:e})}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"})}}const Rr=require("crypto"),Nr=require("node:crypto"),jr=require("node:buffer");const zr=e=>jr.Buffer.from(e).toString("base64url"),$r=require("node:util");class Mr extends Error{static code="ERR_JOSE_GENERIC";code="ERR_JOSE_GENERIC";constructor(e,t){super(e,t),this.name=this.constructor.name,Error.captureStackTrace?.(this,this.constructor)}}class Lr extends Mr{static code="ERR_JOSE_NOT_SUPPORTED";code="ERR_JOSE_NOT_SUPPORTED"}class Fr extends Mr{static code="ERR_JWS_INVALID";code="ERR_JWS_INVALID"}class Zr extends Mr{static code="ERR_JWT_INVALID";code="ERR_JWT_INVALID"}Symbol.asyncIterator;const Vr=Nr.webcrypto,Kr=e=>$r.types.isCryptoKey(e),Ur=e=>$r.types.isKeyObject(e);function Hr(e,t,...r){if((r=r.filter(Boolean)).length>2){const t=r.pop();e+=`one of type ${r.join(", ")}, or ${t}.`}else 2===r.length?e+=`one of type ${r[0]} or ${r[1]}.`:e+=`of type ${r[0]}.`;return null==t?e+=` Received ${t}`:"function"==typeof t&&t.name?e+=` Received function ${t.name}`:"object"==typeof t&&null!=t&&t.constructor?.name&&(e+=` Received an instance of ${t.constructor.name}`),e}const qr=(e,...t)=>Hr("Key must be ",e,...t);function Br(e,t,...r){return Hr(`Key for the ${e} algorithm must be `,t,...r)}const Wr=e=>Ur(e)||Kr(e),Gr=["KeyObject"];function Jr(e){if("object"!=typeof(t=e)||null===t||"[object Object]"!==Object.prototype.toString.call(e))return!1;var t;if(null===Object.getPrototypeOf(e))return!0;let r=e;for(;null!==Object.getPrototypeOf(r);)r=Object.getPrototypeOf(r);return Object.getPrototypeOf(e)===r}function Xr(e){return Jr(e)&&"string"==typeof e.kty}(globalThis.CryptoKey||Vr?.CryptoKey)&&Gr.push("CryptoKey"),new WeakMap;const Qr=(e,t)=>{let r;if(Kr(e))r=Nr.KeyObject.from(e);else{if(!Ur(e)){if(Xr(e))return e.crv;throw new TypeError(qr(e,...Gr))}r=e}if("secret"===r.type)throw new TypeError('only "private" or "public" type keys can be used for this operation');switch(r.asymmetricKeyType){case"ed25519":case"ed448":return`Ed${r.asymmetricKeyType.slice(2)}`;case"x25519":case"x448":return`X${r.asymmetricKeyType.slice(1)}`;case"ec":{const e=r.asymmetricKeyDetails.namedCurve;return t?e:(e=>{switch(e){case"prime256v1":return"P-256";case"secp384r1":return"P-384";case"secp521r1":return"P-521";case"secp256k1":return"secp256k1";default:throw new Lr("Unsupported key curve for this operation")}})(e)}default:throw new TypeError("Invalid asymmetric key type for this operation")}},Yr=(e,t)=>{let r;try{r=e instanceof Nr.KeyObject?e.asymmetricKeyDetails?.modulusLength:Buffer.from(e.n,"base64url").byteLength<<3}catch{}if("number"!=typeof r||r<2048)throw new TypeError(`${t} requires key modulusLength to be 2048 bits or larger`)},ea=new Map([["ES256","P-256"],["ES256K","secp256k1"],["ES384","P-384"],["ES512","P-521"]]);function ta(e,t="algorithm.name"){return new TypeError(`CryptoKey does not support this operation, its ${t} must be ${e}`)}function ra(e,t){return e.name===t}function aa(e){return parseInt(e.name.slice(4),10)}function sa(e,t,...r){switch(t){case"HS256":case"HS384":case"HS512":{if(!ra(e.algorithm,"HMAC"))throw ta("HMAC");const r=parseInt(t.slice(2),10);if(aa(e.algorithm.hash)!==r)throw ta(`SHA-${r}`,"algorithm.hash");break}case"RS256":case"RS384":case"RS512":{if(!ra(e.algorithm,"RSASSA-PKCS1-v1_5"))throw ta("RSASSA-PKCS1-v1_5");const r=parseInt(t.slice(2),10);if(aa(e.algorithm.hash)!==r)throw ta(`SHA-${r}`,"algorithm.hash");break}case"PS256":case"PS384":case"PS512":{if(!ra(e.algorithm,"RSA-PSS"))throw ta("RSA-PSS");const r=parseInt(t.slice(2),10);if(aa(e.algorithm.hash)!==r)throw ta(`SHA-${r}`,"algorithm.hash");break}case"EdDSA":if("Ed25519"!==e.algorithm.name&&"Ed448"!==e.algorithm.name)throw ta("Ed25519 or Ed448");break;case"Ed25519":if(!ra(e.algorithm,"Ed25519"))throw ta("Ed25519");break;case"ES256":case"ES384":case"ES512":{if(!ra(e.algorithm,"ECDSA"))throw ta("ECDSA");const r=function(e){switch(e){case"ES256":return"P-256";case"ES384":return"P-384";case"ES512":return"P-521";default:throw new Error("unreachable")}}(t);if(e.algorithm.namedCurve!==r)throw ta(r,"algorithm.namedCurve");break}default:throw new TypeError("CryptoKey does not support this operation")}!function(e,t){if(t.length&&!t.some(t=>e.usages.includes(t))){let e="CryptoKey does not support this operation, its usages must include ";if(t.length>2){const r=t.pop();e+=`one of ${t.join(", ")}, or ${r}.`}else 2===t.length?e+=`one of ${t[0]} or ${t[1]}.`:e+=`${t[0]}.`;throw new TypeError(e)}}(e,r)}const ia=(0,$r.promisify)(Nr.sign),na=new TextEncoder,oa=new TextDecoder;const ca=e=>e?.[Symbol.toStringTag],da=(e,t,r)=>{if(void 0!==t.use&&"sig"!==t.use)throw new TypeError("Invalid key for this operation, when present its use must be sig");if(void 0!==t.key_ops&&!0!==t.key_ops.includes?.(r))throw new TypeError(`Invalid key for this operation, when present its key_ops must include ${r}`);if(void 0!==t.alg&&t.alg!==e)throw new TypeError(`Invalid key for this operation, when present its alg must be ${e}`);return!0};function ua(e,t,r,a){t.startsWith("HS")||"dir"===t||t.startsWith("PBES2")||/^A\d{3}(?:GCM)?KW$/.test(t)?((e,t,r,a)=>{if(!(t instanceof Uint8Array)){if(a&&Xr(t)){if(function(e){return Xr(e)&&"oct"===e.kty&&"string"==typeof e.k}(t)&&da(e,t,r))return;throw new TypeError('JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present')}if(!Wr(t))throw new TypeError(Br(e,t,...Gr,"Uint8Array",a?"JSON Web Key":null));if("secret"!==t.type)throw new TypeError(`${ca(t)} instances for symmetric algorithms must be of type "secret"`)}})(t,r,a,e):((e,t,r,a)=>{if(a&&Xr(t))switch(r){case"sign":if(function(e){return"oct"!==e.kty&&"string"==typeof e.d}(t)&&da(e,t,r))return;throw new TypeError("JSON Web Key for this operation be a private JWK");case"verify":if(function(e){return"oct"!==e.kty&&void 0===e.d}(t)&&da(e,t,r))return;throw new TypeError("JSON Web Key for this operation be a public JWK")}if(!Wr(t))throw new TypeError(Br(e,t,...Gr,a?"JSON Web Key":null));if("secret"===t.type)throw new TypeError(`${ca(t)} instances for asymmetric algorithms must not be of type "secret"`);if("sign"===r&&"public"===t.type)throw new TypeError(`${ca(t)} instances for asymmetric algorithm signing must be of type "private"`);if("decrypt"===r&&"public"===t.type)throw new TypeError(`${ca(t)} instances for asymmetric algorithm decryption must be of type "private"`);if(t.algorithm&&"verify"===r&&"private"===t.type)throw new TypeError(`${ca(t)} instances for asymmetric algorithm verifying must be of type "public"`);if(t.algorithm&&"encrypt"===r&&"private"===t.type)throw new TypeError(`${ca(t)} instances for asymmetric algorithm encryption must be of type "public"`)})(t,r,a,e)}ua.bind(void 0,!1);const la=ua.bind(void 0,!0);class ha{_payload;_protectedHeader;_unprotectedHeader;constructor(e){if(!(e instanceof Uint8Array))throw new TypeError("payload must be an instance of Uint8Array");this._payload=e}setProtectedHeader(e){if(this._protectedHeader)throw new TypeError("setProtectedHeader can only be called once");return this._protectedHeader=e,this}setUnprotectedHeader(e){if(this._unprotectedHeader)throw new TypeError("setUnprotectedHeader can only be called once");return this._unprotectedHeader=e,this}async sign(e,t){if(!this._protectedHeader&&!this._unprotectedHeader)throw new Fr("either setProtectedHeader or setUnprotectedHeader must be called before #sign()");if(!((...e)=>{const t=e.filter(Boolean);if(0===t.length||1===t.length)return!0;let r;for(const e of t){const t=Object.keys(e);if(r&&0!==r.size)for(const e of t){if(r.has(e))return!1;r.add(e)}else r=new Set(t)}return!0})(this._protectedHeader,this._unprotectedHeader))throw new Fr("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");const r={...this._protectedHeader,...this._unprotectedHeader};let a=!0;if(function(e,t,r,a,s){if(void 0!==s.crit&&void 0===a?.crit)throw new e('"crit" (Critical) Header Parameter MUST be integrity protected');if(!a||void 0===a.crit)return new Set;if(!Array.isArray(a.crit)||0===a.crit.length||a.crit.some(e=>"string"!=typeof e||0===e.length))throw new e('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');let i;i=void 0!==r?new Map([...Object.entries(r),...t.entries()]):t;for(const t of a.crit){if(!i.has(t))throw new Lr(`Extension Header Parameter "${t}" is not recognized`);if(void 0===s[t])throw new e(`Extension Header Parameter "${t}" is missing`);if(i.get(t)&&void 0===a[t])throw new e(`Extension Header Parameter "${t}" MUST be integrity protected`)}return new Set(a.crit)}(Fr,new Map([["b64",!0]]),t?.crit,this._protectedHeader,r).has("b64")&&(a=this._protectedHeader.b64,"boolean"!=typeof a))throw new Fr('The "b64" (base64url-encode payload) Header Parameter must be a boolean');const{alg:s}=r;if("string"!=typeof s||!s)throw new Fr('JWS "alg" (Algorithm) Header Parameter missing or invalid');la(s,e,"sign");let i,n=this._payload;a&&(n=na.encode(zr(n))),i=this._protectedHeader?na.encode(zr(JSON.stringify(this._protectedHeader))):na.encode("");const o=function(...e){const t=e.reduce((e,{length:t})=>e+t,0),r=new Uint8Array(t);let a=0;for(const t of e)r.set(t,a),a+=t.length;return r}(i,na.encode("."),n),c=await(async(e,t,r)=>{const a=function(e,t){if(t instanceof Uint8Array){if(!e.startsWith("HS"))throw new TypeError(qr(t,...Gr));return(0,Nr.createSecretKey)(t)}if(t instanceof Nr.KeyObject)return t;if(Kr(t))return sa(t,e,"sign"),Nr.KeyObject.from(t);if(Xr(t))return e.startsWith("HS")?(0,Nr.createSecretKey)(Buffer.from(t.k,"base64url")):t;throw new TypeError(qr(t,...Gr,"Uint8Array","JSON Web Key"))}(e,t);if(e.startsWith("HS")){const t=Nr.createHmac(function(e){switch(e){case"HS256":return"sha256";case"HS384":return"sha384";case"HS512":return"sha512";default:throw new Lr(`alg ${e} is not supported either by JOSE or your javascript runtime`)}}(e),a);return t.update(r),t.digest()}return ia(function(e){switch(e){case"PS256":case"RS256":case"ES256":case"ES256K":return"sha256";case"PS384":case"RS384":case"ES384":return"sha384";case"PS512":case"RS512":case"ES512":return"sha512";case"Ed25519":case"EdDSA":return;default:throw new Lr(`alg ${e} is not supported either by JOSE or your javascript runtime`)}}(e),r,function(e,t){let r,a,s,i;if(t instanceof Nr.KeyObject)r=t.asymmetricKeyType,a=t.asymmetricKeyDetails;else switch(s=!0,t.kty){case"RSA":r="rsa";break;case"EC":r="ec";break;case"OKP":if("Ed25519"===t.crv){r="ed25519";break}if("Ed448"===t.crv){r="ed448";break}throw new TypeError("Invalid key for this operation, its crv must be Ed25519 or Ed448");default:throw new TypeError("Invalid key for this operation, its kty must be RSA, OKP, or EC")}switch(e){case"Ed25519":if("ed25519"!==r)throw new TypeError("Invalid key for this operation, its asymmetricKeyType must be ed25519");break;case"EdDSA":if(!["ed25519","ed448"].includes(r))throw new TypeError("Invalid key for this operation, its asymmetricKeyType must be ed25519 or ed448");break;case"RS256":case"RS384":case"RS512":if("rsa"!==r)throw new TypeError("Invalid key for this operation, its asymmetricKeyType must be rsa");Yr(t,e);break;case"PS256":case"PS384":case"PS512":if("rsa-pss"===r){const{hashAlgorithm:t,mgf1HashAlgorithm:r,saltLength:s}=a,i=parseInt(e.slice(-3),10);if(void 0!==t&&(t!==`sha${i}`||r!==t))throw new TypeError(`Invalid key for this operation, its RSA-PSS parameters do not meet the requirements of "alg" ${e}`);if(void 0!==s&&s>i>>3)throw new TypeError(`Invalid key for this operation, its RSA-PSS parameter saltLength does not meet the requirements of "alg" ${e}`)}else if("rsa"!==r)throw new TypeError("Invalid key for this operation, its asymmetricKeyType must be rsa or rsa-pss");Yr(t,e),i={padding:Nr.constants.RSA_PKCS1_PSS_PADDING,saltLength:Nr.constants.RSA_PSS_SALTLEN_DIGEST};break;case"ES256":case"ES256K":case"ES384":case"ES512":{if("ec"!==r)throw new TypeError("Invalid key for this operation, its asymmetricKeyType must be ec");const a=Qr(t),s=ea.get(e);if(a!==s)throw new TypeError(`Invalid key curve for the algorithm, its curve must be ${s}, got ${a}`);i={dsaEncoding:"ieee-p1363"};break}default:throw new Lr(`alg ${e} is not supported either by JOSE or your javascript runtime`)}return s?{format:"jwk",key:t,...i}:i?{...i,key:t}:t}(e,a))})(s,e,o),d={signature:zr(c),payload:""};return a&&(d.payload=oa.decode(n)),this._unprotectedHeader&&(d.header=this._unprotectedHeader),this._protectedHeader&&(d.protected=oa.decode(i)),d}}class pa{_flattened;constructor(e){this._flattened=new ha(e)}setProtectedHeader(e){return this._flattened.setProtectedHeader(e),this}async sign(e,t){const r=await this._flattened.sign(e,t);if(void 0===r.payload)throw new TypeError("use the flattened module for creating JWS with b64: false");return`${r.protected}.${r.payload}.${r.signature}`}}const fa=e=>Math.floor(e.getTime()/1e3),ma=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i,ga=e=>{const t=ma.exec(e);if(!t||t[4]&&t[1])throw new TypeError("Invalid time period format");const r=parseFloat(t[2]);let a;switch(t[3].toLowerCase()){case"sec":case"secs":case"second":case"seconds":case"s":a=Math.round(r);break;case"minute":case"minutes":case"min":case"mins":case"m":a=Math.round(60*r);break;case"hour":case"hours":case"hr":case"hrs":case"h":a=Math.round(3600*r);break;case"day":case"days":case"d":a=Math.round(86400*r);break;case"week":case"weeks":case"w":a=Math.round(604800*r);break;default:a=Math.round(31557600*r)}return"-"===t[1]||"ago"===t[4]?-a:a};function ya(e,t){if(!Number.isFinite(t))throw new TypeError(`Invalid ${e} input`);return t}class va{_payload;constructor(e={}){if(!Jr(e))throw new TypeError("JWT Claims Set MUST be an object");this._payload=e}setIssuer(e){return this._payload={...this._payload,iss:e},this}setSubject(e){return this._payload={...this._payload,sub:e},this}setAudience(e){return this._payload={...this._payload,aud:e},this}setJti(e){return this._payload={...this._payload,jti:e},this}setNotBefore(e){return"number"==typeof e?this._payload={...this._payload,nbf:ya("setNotBefore",e)}:e instanceof Date?this._payload={...this._payload,nbf:ya("setNotBefore",fa(e))}:this._payload={...this._payload,nbf:fa(new Date)+ga(e)},this}setExpirationTime(e){return"number"==typeof e?this._payload={...this._payload,exp:ya("setExpirationTime",e)}:e instanceof Date?this._payload={...this._payload,exp:ya("setExpirationTime",fa(e))}:this._payload={...this._payload,exp:fa(new Date)+ga(e)},this}setIssuedAt(e){return void 0===e?this._payload={...this._payload,iat:fa(new Date)}:e instanceof Date?this._payload={...this._payload,iat:ya("setIssuedAt",fa(e))}:this._payload="string"==typeof e?{...this._payload,iat:ya("setIssuedAt",fa(new Date)+ga(e))}:{...this._payload,iat:ya("setIssuedAt",e)},this}}class _a extends va{_protectedHeader;setProtectedHeader(e){return this._protectedHeader=e,this}async sign(e,t){const r=new pa(na.encode(JSON.stringify(this._payload)));if(r.setProtectedHeader(this._protectedHeader),Array.isArray(this._protectedHeader?.crit)&&this._protectedHeader.crit.includes("b64")&&!1===this._protectedHeader.b64)throw new Zr("JWTs MUST NOT use unencoded payload");return r.sign(e,t)}}var Sa=r(77753),ba=r(12308);const Ea=require("fs");var Pa=r(16928);class Ia extends ba.CryptoProvider{async sign(e,t){const r=Buffer.from(t,"base64"),a=64===r.length?r.subarray(0,32):r,s=Buffer.concat([Buffer.from("302e020100300506032b657004220420","hex"),a]),i=Rr.createPrivateKey({key:s,format:"der",type:"pkcs8"}),n=Rr.sign(null,Buffer.from(e),i);return new Uint8Array(n)}async verify(e,t,r){try{const a=Buffer.from(r,"base64"),s=Buffer.concat([Buffer.from("302a300506032b6570032100","hex"),a]),i=Rr.createPublicKey({key:s,format:"der",type:"spki"});return Rr.verify(null,Buffer.from(e),i,Buffer.from(t))}catch{return!1}}async generateKeyPair(){const{publicKey:e,privateKey:t}=Rr.generateKeyPairSync("ed25519",{publicKeyEncoding:{type:"spki",format:"der"},privateKeyEncoding:{type:"pkcs8",format:"der"}}),r=t.subarray(16,48),a=e.subarray(12,44);return{privateKey:r.toString("base64"),publicKey:a.toString("base64")}}async hash(e){const t=Rr.createHash("sha256").update(Buffer.from(e)).digest();return new Uint8Array(t)}async randomBytes(e){return new Uint8Array(Rr.randomBytes(e))}}ba.StorageProvider,ba.IdentityProvider;class wa{async generateProof(e,t,r,a={}){const s=this.generateCanonicalHashes(e,t),i={did:this.identity.did,kid:this.identity.kid,ts:Math.floor(Date.now()/1e3),nonce:r.nonce,audience:r.audience,sessionId:r.sessionId,requestHash:s.requestHash,responseHash:s.responseHash,...a};return{jws:await this.generateJWS(i),meta:i}}generateCanonicalHashes(e,t){const r={method:e.method,...e.params&&{params:e.params}},a=t.data;return{requestHash:this.generateSHA256Hash(r),responseHash:this.generateSHA256Hash(a)}}generateSHA256Hash(e){const t=this.canonicalizeJSON(e);return`sha256:${(0,Rr.createHash)("sha256").update(t,"utf8").digest("hex")}`}canonicalizeJSON(e){return(0,Sa.d)(e)}async generateJWS(e){try{const t=this.formatPrivateKeyAsPEM(this.identity.privateKey),r=await async function(e){if("string"!=typeof e||0!==e.indexOf("-----BEGIN PRIVATE KEY-----"))throw new TypeError('"pkcs8" must be PKCS#8 formatted string');return t=e,(0,Nr.createPrivateKey)({key:jr.Buffer.from(t.replace(/(?:-----(?:BEGIN|END) PRIVATE KEY-----|\s)/g,""),"base64"),type:"pkcs8",format:"der"});var t}(t),a={aud:e.audience,sub:e.did,iss:e.did,requestHash:e.requestHash,responseHash:e.responseHash,ts:e.ts,nonce:e.nonce,sessionId:e.sessionId,...e.scopeId&&{scopeId:e.scopeId},...e.delegationRef&&{delegationRef:e.delegationRef},...e.clientDid&&{clientDid:e.clientDid}};return await new _a(a).setProtectedHeader({alg:"EdDSA",kid:this.identity.kid}).sign(r)}catch(e){throw new Error(`Failed to generate JWS: ${e instanceof Error?e.message:"Unknown error"}`)}}formatPrivateKeyAsPEM(e){const t=Buffer.from(e,"base64"),r=Buffer.from([48,46,2,1,0,48,5,6,3,43,101,112,4,34,4,32]),a=Buffer.concat([r,t.subarray(0,32)]).toString("base64");return"-----BEGIN PRIVATE KEY-----\n"+(a.match(/.{1,64}/g)?.join("\n")||a)+"\n-----END PRIVATE KEY-----"}async verifyProof(e,t,r){try{const a=this.generateCanonicalHashes(t,r);if(e.meta.requestHash!==a.requestHash||e.meta.responseHash!==a.responseHash)return!1;const s=this.base64PublicKeyToJWK(this.identity.publicKey),i=new Ia,n=new ba.CryptoService(i);return await n.verifyJWS(e.jws,s,{expectedKid:this.identity.kid,alg:"EdDSA"})}catch(e){return console.error("[ProofGenerator] Proof verification error:",e),!1}}base64PublicKeyToJWK(e){const t=Buffer.from(e,"base64");if(32!==t.length)throw new Error(`Invalid Ed25519 public key length: ${t.length}`);return{kty:"OKP",crv:"Ed25519",x:Buffer.from(t).toString("base64").replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,""),kid:this.identity.kid}}constructor(e){var t,r;r=void 0,(t="identity")in this?Object.defineProperty(this,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):this[t]=r,this.identity=e}}const Ca=require("fs/promises"),Ta=(0,$r.promisify)(Nr.generateKeyPair);function Da(e,t,r){return t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}class xa{async ensureIdentity(){return this.cachedIdentity||("development"===this.config.environment?this.cachedIdentity=await this.loadOrGenerateDevIdentity():this.cachedIdentity=await this.loadProdIdentity()),this.cachedIdentity}async loadOrGenerateDevIdentity(){const e=this.config.devIdentityPath;try{if((0,Ea.existsSync)(e)){const t=await(0,Ca.readFile)(e,"utf-8"),r=JSON.parse(t);let a=r.kid||r.keyId;if(r.keyId&&!r.kid&&a.startsWith("key-")){a=this.generateMultibaseKid(r.publicKey);const e={did:r.did,kid:a,privateKey:r.privateKey,publicKey:r.publicKey,createdAt:r.createdAt,lastRotated:r.lastRotated};return await this.saveDevIdentity(e),console.error(`✅ Migrated identity to new multibase kid format: ${a}`),e}return{did:r.did,kid:a,privateKey:r.privateKey,publicKey:r.publicKey,createdAt:r.createdAt,lastRotated:r.lastRotated}}}catch(t){console.warn(`Warning: Could not load identity from ${e}, generating new one`,t instanceof Error?t.message:t)}return await this.generateDevIdentity()}async generateDevIdentity(){const e=await async function(e,t){return async function(e,t){switch(e){case"RS256":case"RS384":case"RS512":case"PS256":case"PS384":case"PS512":case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":case"RSA1_5":{const e=t?.modulusLength??2048;if("number"!=typeof e||e<2048)throw new Lr("Invalid or unsupported modulusLength option provided, 2048 bits or larger keys must be used");return await Ta("rsa",{modulusLength:e,publicExponent:65537})}case"ES256":return Ta("ec",{namedCurve:"P-256"});case"ES256K":return Ta("ec",{namedCurve:"secp256k1"});case"ES384":return Ta("ec",{namedCurve:"P-384"});case"ES512":return Ta("ec",{namedCurve:"P-521"});case"Ed25519":return Ta("ed25519");case"EdDSA":switch(t?.crv){case void 0:case"Ed25519":return Ta("ed25519");case"Ed448":return Ta("ed448");default:throw new Lr("Invalid or unsupported crv option provided, supported values are Ed25519 and Ed448")}case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":{const e=t?.crv??"P-256";switch(e){case void 0:case"P-256":case"P-384":case"P-521":return Ta("ec",{namedCurve:e});case"X25519":return Ta("x25519");case"X448":return Ta("x448");default:throw new Lr("Invalid or unsupported crv option provided, supported values are P-256, P-384, P-521, X25519, and X448")}}default:throw new Lr('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}}(e,t)}("EdDSA",{crv:"Ed25519"}),t=await async function(e){return(e=>{let t;if(Kr(e)){if(!e.extractable)throw new TypeError("CryptoKey is not extractable");t=Nr.KeyObject.from(e)}else{if(!Ur(e)){if(e instanceof Uint8Array)return{kty:"oct",k:zr(e)};throw new TypeError(qr(e,...Gr,"Uint8Array"))}t=e}if("secret"!==t.type&&!["rsa","ec","ed25519","x25519","ed448","x448"].includes(t.asymmetricKeyType))throw new Lr("Unsupported key asymmetricKeyType");return t.export({format:"jwk"})})(e)}(e.privateKey);if(!t.x||!t.d)throw new Error("Failed to generate Ed25519 keypair");const r=Buffer.from(t.d,"base64url").toString("base64"),a=Buffer.from(t.x,"base64url").toString("base64"),s=this.generateMultibaseKid(a),i={did:`did:web:localhost:3000:agents:${(0,Rr.createHash)("sha256").update(a).digest("hex").substring(0,8)}`,kid:s,privateKey:r,publicKey:a,createdAt:(new Date).toISOString()};return await this.saveDevIdentity(i),i}generateMultibaseKid(e){const t=Buffer.from(e,"base64"),r=Buffer.concat([Buffer.from([237,1]),t]);return`z${this.encodeBase58(r)}`}encodeBase58(e){let t=BigInt("0x"+e.toString("hex")),r="";for(;t>0n;)r="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"[Number(t%58n)]+r,t/=58n;for(let t=0;t<e.length&&0===e[t];t++)r="1"+r;return r}async saveDevIdentity(e){const t=this.config.devIdentityPath;await(0,Ca.mkdir)((0,Pa.dirname)(t),{recursive:!0});const r={version:"1.0",did:e.did,kid:e.kid,privateKey:e.privateKey,publicKey:e.publicKey,createdAt:e.createdAt,lastRotated:e.lastRotated};await(0,Ca.writeFile)(t,JSON.stringify(r,null,2),{mode:384}),console.error(`✅ Identity saved to ${t}`),console.error(` DID: ${e.did}`),console.error(` Key ID: ${e.kid}`)}async loadProdIdentity(){const e=["AGENT_PRIVATE_KEY","AGENT_KEY_ID","AGENT_DID","KYA_VOUCHED_API_KEY"],t=[],r={};for(const a of e){const e=process.env[a];e?r[a]=e:t.push(a)}if(t.length>0){const e=new Error(`Missing required environment variables for production identity: ${t.join(", ")}\nRequired variables:\n AGENT_PRIVATE_KEY - Base64-encoded Ed25519 private key\n AGENT_KEY_ID - Key identifier\n AGENT_DID - Agent DID\n KYA_VOUCHED_API_KEY - Know-That-AI API key`);throw e.code="XMCP_I_ENOIDENTITY",e}const a=Buffer.from(r.AGENT_PRIVATE_KEY,"base64"),s=(0,Rr.createHash)("sha256").update(a).digest("base64");return{did:r.AGENT_DID,kid:r.AGENT_KEY_ID,privateKey:r.AGENT_PRIVATE_KEY,publicKey:s,createdAt:(new Date).toISOString()}}async validateIdentity(e){try{return!!(e.did&&e.kid&&e.privateKey&&e.publicKey)&&!!e.did.startsWith("did:")&&(Buffer.from(e.privateKey,"base64"),Buffer.from(e.publicKey,"base64"),!0)}catch{return!1}}clearCache(){this.cachedIdentity=void 0}getConfig(){return{...this.config}}constructor(e={environment:"development"}){Da(this,"config",void 0),Da(this,"cachedIdentity",void 0);const t=r(16928);let a=e.devIdentityPath||".mcpi/identity.json";t.isAbsolute(a)||(a=t.resolve(process.cwd(),a)),this.config={privacyMode:!1,...e,devIdentityPath:a},this.config.debug&&console.error("[IdentityManager] Constructed with config:",{environment:this.config.environment,devIdentityPath:this.config.devIdentityPath})}}function Oa(e,t,r){return t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}new xa;const Aa=new class{register(e,t){this.config.set(e,t),this.debug&&console.error(`[ToolProtectionRegistry] Registered protection for tool: ${e}`,t)}registerAll(e){for(const[t,r]of Object.entries(e))this.register(t,r)}get(e){return this.config.get(e)||null}requiresDelegation(e){const t=this.get(e);return t?.requiresDelegation||!1}getRequiredScopes(e){const t=this.get(e);return t?.requiredScopes||[]}setDelegationVerifier(e){this.delegationVerifier=e}setAuthConfig(e){this.authConfig=e}getDelegationVerifier(){return this.delegationVerifier}getAuthConfig(){return this.authConfig}setDebug(e){this.debug=e}setCurrentSession(e){this.currentSession=e}getCurrentSession(){return this.currentSession}getCurrentAgentDid(){return this.currentSession?.agentDid||null}clear(){this.config.clear(),this.delegationVerifier=null,this.authConfig=null,this.currentSession=null}getProtectedTools(){return Array.from(this.config.keys())}constructor(){Oa(this,"config",new Map),Oa(this,"delegationVerifier",null),Oa(this,"authConfig",null),Oa(this,"debug",!1),Oa(this,"currentSession",null)}};var ka=r(74488);async function Ra(e,t,r,a){const s=await r.resumeTokenStore.create(e,t,{requestedAt:Date.now()}),i=Date.now()+(r.bouncer.resumeTokenTtl||6e5),n=new URL(r.bouncer.authorizationUrl);n.searchParams.set("agent_did",e),n.searchParams.set("scopes",t.join(",")),n.searchParams.set("resume_token",s);const o={title:"Authorization Required",hint:["link","qr"],authorizationCode:s.substring(0,8).toUpperCase(),qrUrl:`https://chart.googleapis.com/chart?cht=qr&chs=300x300&chl=${encodeURIComponent(n.toString())}`};return(0,ka.createNeedsAuthorizationError)({message:a,authorizationUrl:n.toString(),resumeToken:s,expiresAt:i,scopes:t,display:o})}function Na(e,t,r){return t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}class ja{async has(e){const t=this.cache.get(e);return!(!t||Date.now()>t.expiresAt&&(this.cache.delete(e),1))}async add(e,t){const r=this.cache.get(e);if(r&&Date.now()<=r.expiresAt)throw new Error(`Nonce ${e} already exists - potential replay attack`);const a=t<=0?Date.now()-1:Date.now()+1e3*t,s={sessionId:`mem_${Date.now()}_${Math.random().toString(36).substring(2)}`,expiresAt:a};this.cache.set(e,s)}async cleanup(){const e=Date.now(),t=[];for(const[r,a]of this.cache.entries())e>a.expiresAt&&t.push(r);for(const e of t)this.cache.delete(e)}getStats(){const e=Date.now();let t=0;for(const r of this.cache.values())e>r.expiresAt&&t++;return{size:this.cache.size,expired:t}}clear(){this.cache.clear()}destroy(){this.cleanupInterval&&(clearInterval(this.cleanupInterval),this.cleanupInterval=void 0),this.cache.clear()}constructor(e=6e4){Na(this,"cache",new Map),Na(this,"cleanupInterval",void 0),console.warn("⚠️ MemoryNonceCache is not suitable for multi-instance deployments. For production use with multiple instances, configure Redis, DynamoDB, or Cloudflare KV."),this.cleanupInterval=setInterval(()=>{this.cleanup().catch(console.error)},e)}}function za(e,t,r){return t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}class $a{setServerDid(e){this.config.serverDid=e}async validateHandshake(e){try{const t=Math.floor(Date.now()/1e3),r=Math.abs(t-e.timestamp);if(r>this.config.timestampSkewSeconds)return{success:!1,error:{code:"XMCP_I_EHANDSHAKE",message:`Timestamp outside acceptable range (±${this.config.timestampSkewSeconds}s)`,remediation:`Check NTP sync on client and server. Current server time: ${t}, received: ${e.timestamp}, diff: ${r}s. Adjust XMCP_I_TS_SKEW_SEC if needed.`}};if(await this.config.nonceCache.has(e.nonce))return{success:!1,error:{code:"XMCP_I_EHANDSHAKE",message:"Nonce already used (replay attack prevention)",remediation:"Generate a new unique nonce for each request"}};const a=60*this.config.sessionTtlMinutes+60;await this.config.nonceCache.add(e.nonce,a);const s=this.generateSessionId(),i={sessionId:s,audience:e.audience,nonce:e.nonce,timestamp:e.timestamp,createdAt:t,lastActivity:t,ttlMinutes:this.config.sessionTtlMinutes,agentDid:e.agentDid,...this.config.serverDid&&{serverDid:this.config.serverDid}};return this.sessions.set(s,i),{success:!0,session:i}}catch(e){return{success:!1,error:{code:"XMCP_I_EHANDSHAKE",message:`Handshake validation failed: ${e instanceof Error?e.message:"Unknown error"}`}}}}async getSession(e){const t=this.sessions.get(e);if(!t)return null;const r=Math.floor(Date.now()/1e3);return r-t.lastActivity>60*t.ttlMinutes||this.config.absoluteSessionLifetime&&r-t.createdAt>60*this.config.absoluteSessionLifetime?(this.sessions.delete(e),null):(t.lastActivity=r,this.sessions.set(e,t),t)}generateSessionId(){return`sess_${Date.now().toString(36)}_${(0,Rr.randomBytes)(8).toString("hex")}`}static generateNonce(){return(0,Rr.randomBytes)(16).toString("base64url")}async cleanup(){const e=Math.floor(Date.now()/1e3);for(const[t,r]of this.sessions.entries()){let a=e-r.lastActivity>60*r.ttlMinutes;!a&&this.config.absoluteSessionLifetime&&(a=e-r.createdAt>60*this.config.absoluteSessionLifetime),a&&this.sessions.delete(t)}await this.config.nonceCache.cleanup()}getStats(){return{activeSessions:this.sessions.size,config:{timestampSkewSeconds:this.config.timestampSkewSeconds,sessionTtlMinutes:this.config.sessionTtlMinutes,absoluteSessionLifetime:this.config.absoluteSessionLifetime,cacheType:this.config.nonceCache.constructor.name}}}clearSessions(){this.sessions.clear()}constructor(e={}){za(this,"config",void 0),za(this,"sessions",new Map),this.config={timestampSkewSeconds:parseInt(process.env.XMCP_I_TS_SKEW_SEC||"120"),sessionTtlMinutes:parseInt(process.env.XMCP_I_SESSION_TTL_MIN||"30"),nonceCache:new ja,...e},this.config.nonceCache instanceof ja&&console.warn("Warning: Using MemoryNonceCache - not suitable for multi-instance deployments. Consider using Redis, DynamoDB, or Cloudflare KV for production.")}}new $a;const Ma=new(require("async_hooks").AsyncLocalStorage);function La(){return(Ma.getStore()?.session)?.agentDid}function Fa(e,t,r){return t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}class Za{async submit(e){if(0===e.length)return;const t={delegation_id:null,session_id:e[0]?.meta?.sessionId||"unknown",proofs:e},r=await fetch(`${this.apiUrl}/api/v1/bouncer/proofs`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify(t)});if(!r.ok){const e=await r.text().catch(()=>"Unable to read error body");throw new Error(`AgentShield proof submission failed: ${r.status} ${r.statusText}\n${e}`)}}constructor(e,t){Fa(this,"name","AgentShield"),Fa(this,"apiUrl",void 0),Fa(this,"apiKey",void 0),this.apiUrl=e.replace(/\/$/,""),this.apiKey=t}}class Va{enqueue(e){this.closed?console.warn("[ProofBatchQueue] Queue is closed, dropping proof"):(this.queue.push(e),this.stats.queued++,this.config.debug&&console.log(`[ProofBatchQueue] Enqueued proof (queue size: ${this.queue.length})`),this.queue.length>=this.config.maxBatchSize&&this.flush())}async flush(){if(0===this.queue.length)return;const e=this.queue.splice(0,this.config.maxBatchSize);this.config.debug&&console.log(`[ProofBatchQueue] Flushing ${e.length} proofs to ${this.config.destinations.length} destinations`);for(const t of this.config.destinations){const r={proofs:e,destination:t,retryCount:0};this.submitBatch(r)}}async submitBatch(e){try{await e.destination.submit(e.proofs),this.stats.submitted+=e.proofs.length,this.stats.batchesSubmitted++,this.config.debug&&console.log(`[ProofBatchQueue] Successfully submitted ${e.proofs.length} proofs to ${e.destination.name}`)}catch(t){if(console.error(`[ProofBatchQueue] Failed to submit to ${e.destination.name}:`,t),e.retryCount<this.config.maxRetries){e.retryCount++;const t=Math.min(1e3*Math.pow(2,e.retryCount-1),16e3);e.nextRetryAt=Date.now()+t,this.pendingBatches.push(e),this.config.debug&&console.log(`[ProofBatchQueue] Scheduling retry ${e.retryCount}/${this.config.maxRetries} in ${t}ms`)}else this.stats.failed+=e.proofs.length,console.error(`[ProofBatchQueue] Max retries exceeded for ${e.destination.name}, dropping ${e.proofs.length} proofs`)}}startFlushTimer(){this.flushTimer=setInterval(()=>{this.queue.length>0&&this.flush()},this.config.flushIntervalMs),"function"==typeof this.flushTimer.unref&&this.flushTimer.unref()}startRetryTimer(){this.retryTimer=setInterval(()=>{const e=Date.now(),t=this.pendingBatches.filter(t=>t.nextRetryAt&&t.nextRetryAt<=e);if(t.length>0){this.pendingBatches=this.pendingBatches.filter(e=>!t.includes(e));for(const e of t)this.submitBatch(e)}},1e3),"function"==typeof this.retryTimer.unref&&this.retryTimer.unref()}async close(){this.closed=!0,this.flushTimer&&clearInterval(this.flushTimer),this.retryTimer&&clearInterval(this.retryTimer),await this.flush();const e=Date.now();for(;this.pendingBatches.length>0&&Date.now()-e<3e4;)await new Promise(e=>setTimeout(e,100));this.pendingBatches.length>0&&console.warn(`[ProofBatchQueue] Closing with ${this.pendingBatches.length} pending batches (timed out)`)}getStats(){return{...this.stats,queueSize:this.queue.length,pendingBatches:this.pendingBatches.length}}constructor(e){Fa(this,"queue",[]),Fa(this,"pendingBatches",[]),Fa(this,"config",void 0),Fa(this,"flushTimer",void 0),Fa(this,"retryTimer",void 0),Fa(this,"closed",!1),Fa(this,"stats",{queued:0,submitted:0,failed:0,batchesSubmitted:0}),this.config={destinations:e.destinations,maxBatchSize:e.maxBatchSize||10,flushIntervalMs:e.flushIntervalMs||5e3,maxRetries:e.maxRetries||5,debug:e.debug||!1},this.startFlushTimer(),this.startRetryTimer()}}const Ka="undefined"!=typeof RUNTIME_CONFIG_PATH?RUNTIME_CONFIG_PATH:void 0,Ua=Ka?"string"==typeof Ka?JSON.parse(Ka):Ka:null;let Ha=null;async function qa(e,t,a){if("undefined"!=typeof global){if(global.__MCPI_HANDLERS_REGISTERED__)return a?.debug&&console.error("[MCPI] Handlers already registered, skipping duplicate registration"),e;global.__MCPI_HANDLERS_REGISTERED__=!0}a?.debug&&console.error("[MCPI] Registering handlers for the first time");const s=new $a;let i=null;if(a?.enabled)try{i=new xa({environment:a.environment||"development",devIdentityPath:a.devIdentityPath,debug:a.debug});const e=await i.ensureIdentity();a.debug&&(console.error(`[MCPI] Identity enabled - DID: ${e.did}`),console.error(`[MCPI] Identity path: ${a.devIdentityPath||".mcpi/identity.json"}`))}catch(e){a?.debug&&console.error("[MCPI] Failed to initialize identity:",e)}await async function(e){if(Ha)return Ha;if(!Ua)return e&&console.error("[MCPI] No runtime config found - proof submission disabled"),null;try{e&&console.error("[MCPI] Loading runtime config from:",Ua);const t=await r(49436)(Ua),a="function"==typeof t.getRuntimeConfig?t.getRuntimeConfig():t.default;if(!a?.proofing?.enabled)return e&&console.error("[MCPI] Proofing is disabled in runtime config"),null;const s=a.proofing;if(!s.batchQueue?.destinations||0===s.batchQueue.destinations.length)return e&&console.error("[MCPI] No proof destinations configured"),null;const i=[];for(const t of s.batchQueue.destinations)"agentshield"===t.type&&(i.push(new Za(t.apiUrl,t.apiKey)),e&&console.error(`[MCPI] Added AgentShield destination: ${t.apiUrl}`));return 0===i.length?(e&&console.error("[MCPI] No valid proof destinations configured"),null):(Ha=new Va({destinations:i,maxBatchSize:s.batchQueue.maxBatchSize||10,flushIntervalMs:s.batchQueue.flushIntervalMs||5e3,maxRetries:s.batchQueue.maxRetries||3,debug:s.batchQueue.debug||e}),e&&console.error(`[MCPI] ProofBatchQueue initialized (batch: ${s.batchQueue.maxBatchSize}, flush: ${s.batchQueue.flushIntervalMs}ms, destinations: ${i.length})`),Ha)}catch(t){return e&&console.error("[MCPI] Failed to initialize ProofBatchQueue:",t),null}}(a?.debug);const n=[],o=new Map;return t.forEach((e,t)=>{const r=function(e){return(e.split("/").pop()||e).replace(/\.[^/.]+$/,"")}(t),a={name:r,description:"No description provided"};let s={};const{default:i,metadata:c,schema:d}=e;"object"==typeof c&&null!==c&&Object.assign(a,c),function(e){if("object"!=typeof e||null===e)return!1;const t=e;return Object.entries(t).every(([e,t])=>"string"==typeof e&&"object"==typeof t&&null!==t&&"parse"in t&&"function"==typeof t.parse)}(d)?Object.assign(s,d):null!=d&&console.warn(`Invalid schema for tool "${a.name}" at ${t}. Expected Record<string, z.ZodType>`),void 0===a.annotations&&(a.annotations={}),void 0===a.annotations.title&&(a.annotations.title=a.name);const u={name:a.name,description:a.description,inputSchema:{type:"object",properties:Object.fromEntries(Object.entries(s).map(([e,t])=>[e,{type:"string"}]))}};n.push(u),o.set(a.name,i)}),a?.debug&&console.error("[MCPI] About to register handlers (tools/list, tools/call)"),e.setRequestHandler(ar,async e=>({tools:n})),e.setRequestHandler(nr,async e=>{const t=e._meta?.sessionId;let r=null;return t&&(r=await s.getSession(t),!r&&a?.debug&&console.error(`[MCPI] Session not found or expired: ${t}`)),n={session:r||void 0,requestId:e._meta?.requestId,startTime:Date.now()},c=async()=>{const{name:t,arguments:r}=e.params,s=o.get(t);if(!s)return{content:[{type:"text",text:`Tool "${t}" not found`}],isError:!0};const n=Aa.get(t);if(n?.requiresDelegation){const e=Aa.getAuthConfig();if(!Aa.getDelegationVerifier()||!e)return a?.debug&&console.error(`[MCPI] Tool "${t}" requires delegation but verifier not configured`),{content:[{type:"text",text:`❌ Tool "${t}" requires delegation verification, but the delegation system is not configured.\n\nTo fix this:\n1. Configure a delegation verifier:\n - MemoryDelegationVerifier (development/testing)\n - KVDelegationVerifier (production with KV store)\n - AgentShieldVerifier (production with AgentShield service)\n\n2. Enable delegation in your runtime config:\n const runtime = new MCPIRuntime({\n delegation: { enabled: true },\n // ... other config\n });\n\n3. Ensure the verifier is initialized before tool execution.\n\n📚 Documentation: https://docs.mcp-i.dev/delegation/setup`}],isError:!0};const r=La();if(!r)return a?.debug&&console.error(`[MCPI] Tool "${t}" requires delegation but no agent DID in session`),{content:[{type:"text",text:`❌ Tool "${t}" requires delegation, but no agent identity was found in the current session.\n\nThis usually means one of the following:\n\n1. **No handshake was performed**: The MCP client must send a handshake request before calling protected tools.\n Example handshake:\n {\n "agentDid": "did:key:z6Mk...",\n "nonce": "unique-value",\n "audience": "server-did",\n "timestamp": ${Date.now()}\n }\n\n2. **Handshake missing agentDid**: Ensure the handshake request includes the 'agentDid' field.\n\n3. **Session expired**: The session may have expired. Try performing a new handshake.\n\n4. **Request missing sessionId**: Ensure tool call requests include _meta.sessionId from the handshake response.\n\n📚 Learn more: https://docs.mcp-i.dev/delegation/handshake`}],isError:!0};a?.debug&&console.error(`[MCPI] Tool "${t}" requires delegation - verifying scopes: ${n.requiredScopes?.join(", ")}`);const s=await async function(e,t,r){const a=Date.now();let s,i;if(r.debug&&console.log(`[AuthHandshake] Verifying ${e} for scopes: ${t.join(", ")}`),r.kta&&void 0!==r.bouncer.minReputationScore)try{if(s=await async function(e,t){const r=t.apiUrl.replace(/\/$/,""),a={"Content-Type":"application/json"};t.apiKey&&(a["X-API-Key"]=t.apiKey);const s=await fetch(`${r}/api/v1/reputation/${encodeURIComponent(e)}`,{method:"GET",headers:a});if(!s.ok){if(404===s.status)return{agentDid:e,score:50,totalInteractions:0,successRate:0,riskLevel:"unknown",updatedAt:Date.now()};throw new Error(`KTA API error: ${s.status} ${s.statusText}`)}const i=await s.json();return{agentDid:i.agentDid||e,score:i.score||50,totalInteractions:i.totalInteractions||0,successRate:i.successRate||0,riskLevel:i.riskLevel||"unknown",updatedAt:i.updatedAt||Date.now()}}(e,r.kta),r.debug&&console.log(`[AuthHandshake] Reputation score: ${s.score}`),s.score<r.bouncer.minReputationScore)return r.debug&&console.log(`[AuthHandshake] Reputation ${s.score} < ${r.bouncer.minReputationScore}, requiring authorization`),{authorized:!1,authError:await Ra(e,t,r,"Agent reputation score below threshold"),reputation:s,reason:"Low reputation score"}}catch(e){console.warn("[AuthHandshake] Failed to check reputation:",e)}try{i=await r.delegationVerifier.verify(e,t)}catch(a){console.error("[AuthHandshake] Delegation verification failed:",a);const s=`Delegation verification error: ${a instanceof Error?a.message:"Unknown error"}`;return{authorized:!1,authError:await Ra(e,t,r,s),reason:s}}return i.valid&&i.delegation?(r.debug&&console.log(`[AuthHandshake] Delegation valid, authorized (${Date.now()-a}ms)`),{authorized:!0,delegation:i.delegation,reputation:s,reason:"Valid delegation found"}):(r.debug&&console.log(`[AuthHandshake] No delegation found, returning needs_authorization (${Date.now()-a}ms)`),{authorized:!1,authError:await Ra(e,t,r,i.reason||"No valid delegation found"),reputation:s,reason:i.reason||"No delegation"})}(r,n.requiredScopes||[],e);if(!s.authorized)return a?.debug&&console.error(`[MCPI] Tool "${t}" blocked - authorization required`),{content:[{type:"text",text:JSON.stringify({error:"needs_authorization",message:`Tool "${t}" requires user authorization`,authorizationUrl:s.authError?.authorizationUrl,resumeToken:s.authError?.resumeToken,scopes:s.authError?.scopes,display:s.authError?.display})}],isError:!0};a?.debug&&console.error(`[MCPI] Tool "${t}" authorized - executing handler`)}try{const e=await s(r||{}),n={content:[{type:"text",text:"string"==typeof e?e:JSON.stringify(e)}]};if(i)try{const s=await i.ensureIdentity(),o={method:t,params:r||{}},c={data:e},d=Math.floor(Date.now()/1e3),u={sessionId:`tool-${Date.now()}`,nonce:`${Date.now()}`,audience:"client",createdAt:d,timestamp:d,lastActivity:d,ttlMinutes:30};let l;const h=Aa.get(t);l=h?.requiredScopes&&h.requiredScopes.length>0?h.requiredScopes[0]:`${t}:execute`,a?.debug&&console.error(`[MCPI] Proof scopeId for tool "${t}": ${l}`);const p=new wa(s),f=await p.generateProof(o,c,u,{scopeId:l,clientDid:u?.clientDid});if(a?.debug&&console.error(`[MCPI] Generated proof for tool "${t}" - DID: ${f.meta.did}`),Ha)try{Ha.enqueue(f),a?.debug&&console.error("[MCPI] Proof enqueued for submission to AgentShield")}catch(e){a?.debug&&console.error("[MCPI] Failed to enqueue proof:",e)}return{...n,_meta:{proof:f}}}catch(e){return a?.debug&&console.error(`[MCPI] Failed to generate proof for tool "${t}":`,e),n}return n}catch(e){return{content:[{type:"text",text:`Error executing tool "${t}": ${e instanceof Error?e.message:String(e)}`}],isError:!0}}},Ma.run(n,c);var n,c}),a?.debug&&console.error("[MCPI] Handlers registered successfully"),e}"undefined"!=typeof global&&(global.__MCPI_HANDLERS_REGISTERED__=global.__MCPI_HANDLERS_REGISTERED__||!1);const Ba=INJECTED_TOOLS,Wa="undefined"!=typeof IDENTITY_CONFIG?IDENTITY_CONFIG:void 0,Ga=Wa?JSON.parse(Wa):void 0,Ja={name:"MCP Server",version:"0.0.1"},Xa={capabilities:{tools:{}}};function Qa(e,t,r){return t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}"undefined"!=typeof global&&(global.__MCPI_SERVER_CREATED__=global.__MCPI_SERVER_CREATED__||!1);class Ya{start(){try{this.mcpServer.connect(this.transport),this.debug&&console.error("[STDIO] MCP Server running with STDIO transport"),this.setupShutdownHandlers()}catch(e){this.debug&&console.error("[STDIO] Error starting STDIO transport:",e),process.exit(1)}}setupShutdownHandlers(){const e=()=>{this.debug&&console.error("[STDIO] Shutting down STDIO transport"),process.exit(0)};process.on("SIGINT",e),process.on("SIGTERM",e)}shutdown(){this.debug&&console.error("[STDIO] Shutting down STDIO transport"),process.exit(0)}constructor(e,t=!1){Qa(this,"mcpServer",void 0),Qa(this,"transport",void 0),Qa(this,"debug",void 0),this.mcpServer=e,this.transport=new xr,this.debug=t}}const es=STDIO_CONFIG.debug||!1;(async function(){if(Ga?.debug&&console.error("[createServer] Starting server creation"),"undefined"!=typeof global&&global.__MCPI_SERVER_CREATED__&&(Ga?.debug&&console.error("[createServer] Server already exists, returning cached instance"),global.__MCPI_SERVER_INSTANCE__))return global.__MCPI_SERVER_INSTANCE__;Ga?.debug&&(console.error("[createServer] Creating new McpServer"),console.error("[createServer] SERVER_INFO constant:",JSON.stringify(Ja)),console.error("[createServer] SERVER_CAPABILITIES constant:",JSON.stringify(Xa)),console.error("[createServer] Calling: new McpServer(SERVER_INFO, SERVER_CAPABILITIES)"));const e=new kr(Ja,Xa);if(Ga?.debug){console.error("[createServer] Server created successfully");const t=e;console.error("[createServer] Actual server._serverInfo:",JSON.stringify(t._serverInfo||"undefined")),console.error("[createServer] Actual server._capabilities:",JSON.stringify(t._capabilities||"undefined")),console.error("[createServer] Loading tools...")}const[t,r]=function(){const e=new Map,t=Object.keys(Ba);return Ga?.debug&&console.error("[loadTools] Injected tool paths:",t),[t.map(t=>Ba[t]().then(r=>{Ga?.debug&&console.error("[loadTools] Loaded tool from path:",t),e.set(t,r)})),e]}();await Promise.all(t),Ga?.debug&&console.error("[createServer] Tools loaded, configuring server");const a=await async function(e,t){return await qa(e,t,Ga),e}(e,r);return Ga?.debug&&console.error("[createServer] Server configured successfully"),"undefined"!=typeof global&&(global.__MCPI_SERVER_CREATED__=!0,global.__MCPI_SERVER_INSTANCE__=a),a})().then(e=>{new Ya(e,es).start()})})()})();
|