← Back
Editing: angie-integration.min.js
(()=>{"use strict";var e={4018(e,t){function r(e,t){return{validate:e,compare:t}}t.formatNames=t.fastFormats=t.fullFormats=void 0,t.fullFormats={date:r(i,a),time:r(c(!0),d),"date-time":r(h(!0),p),"iso-time":r(c(),l),"iso-date-time":r(h(),m),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:function(e){return f.test(e)&&g.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":/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,url:/^(?:https?|ftp):\/\/(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)(?:\.(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu,email:/^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i,hostname:/^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i,ipv4:/^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/,ipv6:/^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i,regex:function(e){if(w.test(e))return!1;try{return new RegExp(e),!0}catch(e){return!1}},uuid:/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,"json-pointer":/^(?:\/(?:[^~/]|~0|~1)*)*$/,"json-pointer-uri-fragment":/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,"relative-json-pointer":/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,byte:function(e){return _.lastIndex=0,_.test(e)},int32:{type:"number",validate:function(e){return Number.isInteger(e)&&e<=2147483647&&e>=-2147483648}},int64:{type:"number",validate:function(e){return Number.isInteger(e)}},float:{type:"number",validate:y},double:{type:"number",validate:y},password:!0,binary:!0},t.fastFormats={...t.fullFormats,date:r(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,a),time:r(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,d),"date-time":r(/^\d\d\d\d-[0-1]\d-[0-3]\dt(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,p),"iso-time":r(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,l),"iso-date-time":r(/^\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,m),uri:/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i,"uri-reference":/^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i,email:/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i},t.formatNames=Object.keys(t.fullFormats);const n=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,s=[0,31,28,31,30,31,30,31,31,30,31,30,31];function i(e){const t=n.exec(e);if(!t)return!1;const r=+t[1],i=+t[2],a=+t[3];return i>=1&&i<=12&&a>=1&&a<=(2===i&&function(e){return e%4==0&&(e%100!=0||e%400==0)}(r)?29:s[i])}function a(e,t){if(e&&t)return e>t?1:e<t?-1:0}const o=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function c(e){return function(t){const r=o.exec(t);if(!r)return!1;const n=+r[1],s=+r[2],i=+r[3],a=r[4],c="-"===r[5]?-1:1,d=+(r[6]||0),l=+(r[7]||0);if(d>23||l>59||e&&!a)return!1;if(n<=23&&s<=59&&i<60)return!0;const u=s-l*c,h=n-d*c-(u<0?1:0);return(23===h||-1===h)&&(59===u||-1===u)&&i<61}}function d(e,t){if(!e||!t)return;const r=new Date("2020-01-01T"+e).valueOf(),n=new Date("2020-01-01T"+t).valueOf();return r&&n?r-n:void 0}function l(e,t){if(!e||!t)return;const r=o.exec(e),n=o.exec(t);return r&&n?(e=r[1]+r[2]+r[3])>(t=n[1]+n[2]+n[3])?1:e<t?-1:0:void 0}const u=/t|\s/i;function h(e){const t=c(e);return function(e){const r=e.split(u);return 2===r.length&&i(r[0])&&t(r[1])}}function p(e,t){if(!e||!t)return;const r=new Date(e).valueOf(),n=new Date(t).valueOf();return r&&n?r-n:void 0}function m(e,t){if(!e||!t)return;const[r,n]=e.split(u),[s,i]=t.split(u),o=a(r,s);return void 0!==o?o||d(n,i):void 0}const f=/\/|:/,g=/^(?:[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,_=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function y(){return!0}const w=/[^\\]\\Z/},8182(e,t,r){Object.defineProperty(t,"__esModule",{value:!0});const n=r(4018),s=r(6461),i=r(9029),a=new i.Name("fullFormats"),o=new i.Name("fastFormats"),c=(e,t={keywords:!0})=>{if(Array.isArray(t))return d(e,t,n.fullFormats,a),e;const[r,i]="fast"===t.mode?[n.fastFormats,o]:[n.fullFormats,a];return d(e,t.formats||n.formatNames,r,i),t.keywords&&(0,s.default)(e),e};function d(e,t,r,n){var s,a;null!==(s=(a=e.opts.code).formats)&&void 0!==s||(a.formats=i._`require("ajv-formats/dist/formats").${n}`);for(const n of t)e.addFormat(n,r[n])}c.get=(e,t="full")=>{const r=("fast"===t?n.fastFormats:n.fullFormats)[e];if(!r)throw new Error(`Unknown format "${e}"`);return r},e.exports=t=c,Object.defineProperty(t,"__esModule",{value:!0}),t.default=c},6461(e,t,r){t.A=void 0;const n=r(3282),s=r(9029),i=s.operators,a={formatMaximum:{okStr:"<=",ok:i.LTE,fail:i.GT},formatMinimum:{okStr:">=",ok:i.GTE,fail:i.LT},formatExclusiveMaximum:{okStr:"<",ok:i.LT,fail:i.GTE},formatExclusiveMinimum:{okStr:">",ok:i.GT,fail:i.LTE}},o={message:({keyword:e,schemaCode:t})=>s.str`should be ${a[e].okStr} ${t}`,params:({keyword:e,schemaCode:t})=>s._`{comparison: ${a[e].okStr}, limit: ${t}}`};t.A={keyword:Object.keys(a),type:"string",schemaType:"string",$data:!0,error:o,code(e){const{gen:t,data:r,schemaCode:i,keyword:o,it:c}=e,{opts:d,self:l}=c;if(!d.validateFormats)return;const u=new n.KeywordCxt(c,l.RULES.all.format.definition,"format");function h(e){return s._`${e}.compare(${r}, ${i}) ${a[o].fail} 0`}u.$data?function(){const r=t.scopeValue("formats",{ref:l.formats,code:d.code.formats}),n=t.const("fmt",s._`${r}[${u.schemaCode}]`);e.fail$data((0,s.or)(s._`typeof ${n} != "object"`,s._`${n} instanceof RegExp`,s._`typeof ${n}.compare != "function"`,h(n)))}():function(){const r=u.schema,n=l.formats[r];if(!n||!0===n)return;if("object"!=typeof n||n instanceof RegExp||"function"!=typeof n.compare)throw new Error(`"${o}": format "${r}" does not define "compare" function`);const i=t.scopeValue("formats",{key:r,ref:n,code:d.code.formats?s._`${d.code.formats}${(0,s.getProperty)(r)}`:void 0});e.fail$data(h(i))}()},dependencies:["format"]},t.default=e=>(e.addKeyword(t.A),e)},3282(e,t,r){Object.defineProperty(t,"__esModule",{value:!0}),t.MissingRefError=t.ValidationError=t.CodeGen=t.Name=t.nil=t.stringify=t.str=t._=t.KeywordCxt=t.Ajv=void 0;const n=r(4042),s=r(6144),i=r(6653),a=r(2079),o=["/properties"],c="http://json-schema.org/draft-07/schema";class d extends n.default{_addVocabularies(){super._addVocabularies(),s.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(i.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;const e=this.opts.$data?this.$dataMetaSchema(a,o):a;this.addMetaSchema(e,c,!1),this.refs["http://json-schema.org/schema"]=c}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(c)?c:void 0)}}t.Ajv=d,e.exports=t=d,e.exports.Ajv=d,Object.defineProperty(t,"__esModule",{value:!0}),t.default=d;var l=r(2586);Object.defineProperty(t,"KeywordCxt",{enumerable:!0,get:function(){return l.KeywordCxt}});var u=r(9029);Object.defineProperty(t,"_",{enumerable:!0,get:function(){return u._}}),Object.defineProperty(t,"str",{enumerable:!0,get:function(){return u.str}}),Object.defineProperty(t,"stringify",{enumerable:!0,get:function(){return u.stringify}}),Object.defineProperty(t,"nil",{enumerable:!0,get:function(){return u.nil}}),Object.defineProperty(t,"Name",{enumerable:!0,get:function(){return u.Name}}),Object.defineProperty(t,"CodeGen",{enumerable:!0,get:function(){return u.CodeGen}});var h=r(3558);Object.defineProperty(t,"ValidationError",{enumerable:!0,get:function(){return h.default}});var p=r(4551);Object.defineProperty(t,"MissingRefError",{enumerable:!0,get:function(){return p.default}})},1520(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.regexpCode=t.getEsmExportName=t.getProperty=t.safeStringify=t.stringify=t.strConcat=t.addCodeArg=t.str=t._=t.nil=t._Code=t.Name=t.IDENTIFIER=t._CodeOrName=void 0;class r{}t._CodeOrName=r,t.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;class n extends r{constructor(e){if(super(),!t.IDENTIFIER.test(e))throw new Error("CodeGen: name must be a valid identifier");this.str=e}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}}t.Name=n;class s extends r{constructor(e){super(),this._items="string"==typeof e?[e]:e}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;const e=this._items[0];return""===e||'""'===e}get str(){var e;return null!==(e=this._str)&&void 0!==e?e:this._str=this._items.reduce((e,t)=>`${e}${t}`,"")}get names(){var e;return null!==(e=this._names)&&void 0!==e?e:this._names=this._items.reduce((e,t)=>(t instanceof n&&(e[t.str]=(e[t.str]||0)+1),e),{})}}function i(e,...t){const r=[e[0]];let n=0;for(;n<t.length;)c(r,t[n]),r.push(e[++n]);return new s(r)}t._Code=s,t.nil=new s(""),t._=i;const a=new s("+");function o(e,...t){const r=[l(e[0])];let n=0;for(;n<t.length;)r.push(a),c(r,t[n]),r.push(a,l(e[++n]));return function(e){let t=1;for(;t<e.length-1;){if(e[t]===a){const r=d(e[t-1],e[t+1]);if(void 0!==r){e.splice(t-1,3,r);continue}e[t++]="+"}t++}}(r),new s(r)}function c(e,t){t instanceof s?e.push(...t._items):t instanceof n?e.push(t):e.push(function(e){return"number"==typeof e||"boolean"==typeof e||null===e?e:l(Array.isArray(e)?e.join(","):e)}(t))}function d(e,t){if('""'===t)return e;if('""'===e)return t;if("string"==typeof e){if(t instanceof n||'"'!==e[e.length-1])return;return"string"!=typeof t?`${e.slice(0,-1)}${t}"`:'"'===t[0]?e.slice(0,-1)+t.slice(1):void 0}return"string"!=typeof t||'"'!==t[0]||e instanceof n?void 0:`"${e}${t.slice(1)}`}function l(e){return JSON.stringify(e).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}t.str=o,t.addCodeArg=c,t.strConcat=function(e,t){return t.emptyStr()?e:e.emptyStr()?t:o`${e}${t}`},t.stringify=function(e){return new s(l(e))},t.safeStringify=l,t.getProperty=function(e){return"string"==typeof e&&t.IDENTIFIER.test(e)?new s(`.${e}`):i`[${e}]`},t.getEsmExportName=function(e){if("string"==typeof e&&t.IDENTIFIER.test(e))return new s(`${e}`);throw new Error(`CodeGen: invalid export name: ${e}, use explicit $id name mapping`)},t.regexpCode=function(e){return new s(e.toString())}},9029(e,t,r){Object.defineProperty(t,"__esModule",{value:!0}),t.or=t.and=t.not=t.CodeGen=t.operators=t.varKinds=t.ValueScopeName=t.ValueScope=t.Scope=t.Name=t.regexpCode=t.stringify=t.getProperty=t.nil=t.strConcat=t.str=t._=void 0;const n=r(1520),s=r(7845);var i=r(1520);Object.defineProperty(t,"_",{enumerable:!0,get:function(){return i._}}),Object.defineProperty(t,"str",{enumerable:!0,get:function(){return i.str}}),Object.defineProperty(t,"strConcat",{enumerable:!0,get:function(){return i.strConcat}}),Object.defineProperty(t,"nil",{enumerable:!0,get:function(){return i.nil}}),Object.defineProperty(t,"getProperty",{enumerable:!0,get:function(){return i.getProperty}}),Object.defineProperty(t,"stringify",{enumerable:!0,get:function(){return i.stringify}}),Object.defineProperty(t,"regexpCode",{enumerable:!0,get:function(){return i.regexpCode}}),Object.defineProperty(t,"Name",{enumerable:!0,get:function(){return i.Name}});var a=r(7845);Object.defineProperty(t,"Scope",{enumerable:!0,get:function(){return a.Scope}}),Object.defineProperty(t,"ValueScope",{enumerable:!0,get:function(){return a.ValueScope}}),Object.defineProperty(t,"ValueScopeName",{enumerable:!0,get:function(){return a.ValueScopeName}}),Object.defineProperty(t,"varKinds",{enumerable:!0,get:function(){return a.varKinds}}),t.operators={GT:new n._Code(">"),GTE:new n._Code(">="),LT:new n._Code("<"),LTE:new n._Code("<="),EQ:new n._Code("==="),NEQ:new n._Code("!=="),NOT:new n._Code("!"),OR:new n._Code("||"),AND:new n._Code("&&"),ADD:new n._Code("+")};class o{optimizeNodes(){return this}optimizeNames(e,t){return this}}class c extends o{constructor(e,t,r){super(),this.varKind=e,this.name=t,this.rhs=r}render({es5:e,_n:t}){const r=e?s.varKinds.var:this.varKind,n=void 0===this.rhs?"":` = ${this.rhs}`;return`${r} ${this.name}${n};`+t}optimizeNames(e,t){if(e[this.name.str])return this.rhs&&(this.rhs=R(this.rhs,e,t)),this}get names(){return this.rhs instanceof n._CodeOrName?this.rhs.names:{}}}class d extends o{constructor(e,t,r){super(),this.lhs=e,this.rhs=t,this.sideEffects=r}render({_n:e}){return`${this.lhs} = ${this.rhs};`+e}optimizeNames(e,t){if(!(this.lhs instanceof n.Name)||e[this.lhs.str]||this.sideEffects)return this.rhs=R(this.rhs,e,t),this}get names(){return C(this.lhs instanceof n.Name?{}:{...this.lhs.names},this.rhs)}}class l extends d{constructor(e,t,r,n){super(e,r,n),this.op=t}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}}class u extends o{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}}class h extends o{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:""};`+e}}class p extends o{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}}class m extends o{constructor(e){super(),this.code=e}render({_n:e}){return`${this.code};`+e}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(e,t){return this.code=R(this.code,e,t),this}get names(){return this.code instanceof n._CodeOrName?this.code.names:{}}}class f extends o{constructor(e=[]){super(),this.nodes=e}render(e){return this.nodes.reduce((t,r)=>t+r.render(e),"")}optimizeNodes(){const{nodes:e}=this;let t=e.length;for(;t--;){const r=e[t].optimizeNodes();Array.isArray(r)?e.splice(t,1,...r):r?e[t]=r:e.splice(t,1)}return e.length>0?this:void 0}optimizeNames(e,t){const{nodes:r}=this;let n=r.length;for(;n--;){const s=r[n];s.optimizeNames(e,t)||(A(e,s.names),r.splice(n,1))}return r.length>0?this:void 0}get names(){return this.nodes.reduce((e,t)=>P(e,t.names),{})}}class g extends f{render(e){return"{"+e._n+super.render(e)+"}"+e._n}}class _ extends f{}class y extends g{}y.kind="else";class w extends g{constructor(e,t){super(t),this.condition=e}render(e){let t=`if(${this.condition})`+super.render(e);return this.else&&(t+="else "+this.else.render(e)),t}optimizeNodes(){super.optimizeNodes();const e=this.condition;if(!0===e)return this.nodes;let t=this.else;if(t){const e=t.optimizeNodes();t=this.else=Array.isArray(e)?new y(e):e}return t?!1===e?t instanceof w?t:t.nodes:this.nodes.length?this:new w(O(e),t instanceof w?[t]:t.nodes):!1!==e&&this.nodes.length?this:void 0}optimizeNames(e,t){var r;if(this.else=null===(r=this.else)||void 0===r?void 0:r.optimizeNames(e,t),super.optimizeNames(e,t)||this.else)return this.condition=R(this.condition,e,t),this}get names(){const e=super.names;return C(e,this.condition),this.else&&P(e,this.else.names),e}}w.kind="if";class v extends g{}v.kind="for";class b extends v{constructor(e){super(),this.iteration=e}render(e){return`for(${this.iteration})`+super.render(e)}optimizeNames(e,t){if(super.optimizeNames(e,t))return this.iteration=R(this.iteration,e,t),this}get names(){return P(super.names,this.iteration.names)}}class k extends v{constructor(e,t,r,n){super(),this.varKind=e,this.name=t,this.from=r,this.to=n}render(e){const t=e.es5?s.varKinds.var:this.varKind,{name:r,from:n,to:i}=this;return`for(${t} ${r}=${n}; ${r}<${i}; ${r}++)`+super.render(e)}get names(){const e=C(super.names,this.from);return C(e,this.to)}}class S extends v{constructor(e,t,r,n){super(),this.loop=e,this.varKind=t,this.name=r,this.iterable=n}render(e){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(e)}optimizeNames(e,t){if(super.optimizeNames(e,t))return this.iterable=R(this.iterable,e,t),this}get names(){return P(super.names,this.iterable.names)}}class $ extends g{constructor(e,t,r){super(),this.name=e,this.args=t,this.async=r}render(e){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(e)}}$.kind="func";class E extends f{render(e){return"return "+super.render(e)}}E.kind="return";class T extends g{render(e){let t="try"+super.render(e);return this.catch&&(t+=this.catch.render(e)),this.finally&&(t+=this.finally.render(e)),t}optimizeNodes(){var e,t;return super.optimizeNodes(),null===(e=this.catch)||void 0===e||e.optimizeNodes(),null===(t=this.finally)||void 0===t||t.optimizeNodes(),this}optimizeNames(e,t){var r,n;return super.optimizeNames(e,t),null===(r=this.catch)||void 0===r||r.optimizeNames(e,t),null===(n=this.finally)||void 0===n||n.optimizeNames(e,t),this}get names(){const e=super.names;return this.catch&&P(e,this.catch.names),this.finally&&P(e,this.finally.names),e}}class I extends g{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}}I.kind="catch";class x extends g{render(e){return"finally"+super.render(e)}}function P(e,t){for(const r in t)e[r]=(e[r]||0)+(t[r]||0);return e}function C(e,t){return t instanceof n._CodeOrName?P(e,t.names):e}function R(e,t,r){return e instanceof n.Name?i(e):(s=e)instanceof n._Code&&s._items.some(e=>e instanceof n.Name&&1===t[e.str]&&void 0!==r[e.str])?new n._Code(e._items.reduce((e,t)=>(t instanceof n.Name&&(t=i(t)),t instanceof n._Code?e.push(...t._items):e.push(t),e),[])):e;var s;function i(e){const n=r[e.str];return void 0===n||1!==t[e.str]?e:(delete t[e.str],n)}}function A(e,t){for(const r in t)e[r]=(e[r]||0)-(t[r]||0)}function O(e){return"boolean"==typeof e||"number"==typeof e||null===e?!e:n._`!${U(e)}`}x.kind="finally",t.CodeGen=class{constructor(e,t={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...t,_n:t.lines?"\n":""},this._extScope=e,this._scope=new s.Scope({parent:e}),this._nodes=[new _]}toString(){return this._root.render(this.opts)}name(e){return this._scope.name(e)}scopeName(e){return this._extScope.name(e)}scopeValue(e,t){const r=this._extScope.value(e,t);return(this._values[r.prefix]||(this._values[r.prefix]=new Set)).add(r),r}getScopeValue(e,t){return this._extScope.getValue(e,t)}scopeRefs(e){return this._extScope.scopeRefs(e,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(e,t,r,n){const s=this._scope.toName(t);return void 0!==r&&n&&(this._constants[s.str]=r),this._leafNode(new c(e,s,r)),s}const(e,t,r){return this._def(s.varKinds.const,e,t,r)}let(e,t,r){return this._def(s.varKinds.let,e,t,r)}var(e,t,r){return this._def(s.varKinds.var,e,t,r)}assign(e,t,r){return this._leafNode(new d(e,t,r))}add(e,r){return this._leafNode(new l(e,t.operators.ADD,r))}code(e){return"function"==typeof e?e():e!==n.nil&&this._leafNode(new m(e)),this}object(...e){const t=["{"];for(const[r,s]of e)t.length>1&&t.push(","),t.push(r),(r!==s||this.opts.es5)&&(t.push(":"),(0,n.addCodeArg)(t,s));return t.push("}"),new n._Code(t)}if(e,t,r){if(this._blockNode(new w(e)),t&&r)this.code(t).else().code(r).endIf();else if(t)this.code(t).endIf();else if(r)throw new Error('CodeGen: "else" body without "then" body');return this}elseIf(e){return this._elseNode(new w(e))}else(){return this._elseNode(new y)}endIf(){return this._endBlockNode(w,y)}_for(e,t){return this._blockNode(e),t&&this.code(t).endFor(),this}for(e,t){return this._for(new b(e),t)}forRange(e,t,r,n,i=(this.opts.es5?s.varKinds.var:s.varKinds.let)){const a=this._scope.toName(e);return this._for(new k(i,a,t,r),()=>n(a))}forOf(e,t,r,i=s.varKinds.const){const a=this._scope.toName(e);if(this.opts.es5){const e=t instanceof n.Name?t:this.var("_arr",t);return this.forRange("_i",0,n._`${e}.length`,t=>{this.var(a,n._`${e}[${t}]`),r(a)})}return this._for(new S("of",i,a,t),()=>r(a))}forIn(e,t,r,i=(this.opts.es5?s.varKinds.var:s.varKinds.const)){if(this.opts.ownProperties)return this.forOf(e,n._`Object.keys(${t})`,r);const a=this._scope.toName(e);return this._for(new S("in",i,a,t),()=>r(a))}endFor(){return this._endBlockNode(v)}label(e){return this._leafNode(new u(e))}break(e){return this._leafNode(new h(e))}return(e){const t=new E;if(this._blockNode(t),this.code(e),1!==t.nodes.length)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(E)}try(e,t,r){if(!t&&!r)throw new Error('CodeGen: "try" without "catch" and "finally"');const n=new T;if(this._blockNode(n),this.code(e),t){const e=this.name("e");this._currNode=n.catch=new I(e),t(e)}return r&&(this._currNode=n.finally=new x,this.code(r)),this._endBlockNode(I,x)}throw(e){return this._leafNode(new p(e))}block(e,t){return this._blockStarts.push(this._nodes.length),e&&this.code(e).endBlock(t),this}endBlock(e){const t=this._blockStarts.pop();if(void 0===t)throw new Error("CodeGen: not in self-balancing block");const r=this._nodes.length-t;if(r<0||void 0!==e&&r!==e)throw new Error(`CodeGen: wrong number of nodes: ${r} vs ${e} expected`);return this._nodes.length=t,this}func(e,t=n.nil,r,s){return this._blockNode(new $(e,t,r)),s&&this.code(s).endFunc(),this}endFunc(){return this._endBlockNode($)}optimize(e=1){for(;e-- >0;)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(e){return this._currNode.nodes.push(e),this}_blockNode(e){this._currNode.nodes.push(e),this._nodes.push(e)}_endBlockNode(e,t){const r=this._currNode;if(r instanceof e||t&&r instanceof t)return this._nodes.pop(),this;throw new Error(`CodeGen: not in block "${t?`${e.kind}/${t.kind}`:e.kind}"`)}_elseNode(e){const t=this._currNode;if(!(t instanceof w))throw new Error('CodeGen: "else" without "if"');return this._currNode=t.else=e,this}get _root(){return this._nodes[0]}get _currNode(){const e=this._nodes;return e[e.length-1]}set _currNode(e){const t=this._nodes;t[t.length-1]=e}},t.not=O;const N=j(t.operators.AND);t.and=function(...e){return e.reduce(N)};const z=j(t.operators.OR);function j(e){return(t,r)=>t===n.nil?r:r===n.nil?t:n._`${U(t)} ${e} ${U(r)}`}function U(e){return e instanceof n.Name?e:n._`(${e})`}t.or=function(...e){return e.reduce(z)}},7845(e,t,r){Object.defineProperty(t,"__esModule",{value:!0}),t.ValueScope=t.ValueScopeName=t.Scope=t.varKinds=t.UsedValueState=void 0;const n=r(1520);class s extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}}var i;!function(e){e[e.Started=0]="Started",e[e.Completed=1]="Completed"}(i||(t.UsedValueState=i={})),t.varKinds={const:new n.Name("const"),let:new n.Name("let"),var:new n.Name("var")};class a{constructor({prefixes:e,parent:t}={}){this._names={},this._prefixes=e,this._parent=t}toName(e){return e instanceof n.Name?e:this.name(e)}name(e){return new n.Name(this._newName(e))}_newName(e){return`${e}${(this._names[e]||this._nameGroup(e)).index++}`}_nameGroup(e){var t,r;if((null===(r=null===(t=this._parent)||void 0===t?void 0:t._prefixes)||void 0===r?void 0:r.has(e))||this._prefixes&&!this._prefixes.has(e))throw new Error(`CodeGen: prefix "${e}" is not allowed in this scope`);return this._names[e]={prefix:e,index:0}}}t.Scope=a;class o extends n.Name{constructor(e,t){super(t),this.prefix=e}setValue(e,{property:t,itemIndex:r}){this.value=e,this.scopePath=n._`.${new n.Name(t)}[${r}]`}}t.ValueScopeName=o;const c=n._`\n`;t.ValueScope=class extends a{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?c:n.nil}}get(){return this._scope}name(e){return new o(e,this._newName(e))}value(e,t){var r;if(void 0===t.ref)throw new Error("CodeGen: ref must be passed in value");const n=this.toName(e),{prefix:s}=n,i=null!==(r=t.key)&&void 0!==r?r:t.ref;let a=this._values[s];if(a){const e=a.get(i);if(e)return e}else a=this._values[s]=new Map;a.set(i,n);const o=this._scope[s]||(this._scope[s]=[]),c=o.length;return o[c]=t.ref,n.setValue(t,{property:s,itemIndex:c}),n}getValue(e,t){const r=this._values[e];if(r)return r.get(t)}scopeRefs(e,t=this._values){return this._reduceValues(t,t=>{if(void 0===t.scopePath)throw new Error(`CodeGen: name "${t}" has no value`);return n._`${e}${t.scopePath}`})}scopeCode(e=this._values,t,r){return this._reduceValues(e,e=>{if(void 0===e.value)throw new Error(`CodeGen: name "${e}" has no value`);return e.value.code},t,r)}_reduceValues(e,r,a={},o){let c=n.nil;for(const d in e){const l=e[d];if(!l)continue;const u=a[d]=a[d]||new Map;l.forEach(e=>{if(u.has(e))return;u.set(e,i.Started);let a=r(e);if(a){const r=this.opts.es5?t.varKinds.var:t.varKinds.const;c=n._`${c}${r} ${e} = ${a};${this.opts._n}`}else{if(!(a=null==o?void 0:o(e)))throw new s(e);c=n._`${c}${a}${this.opts._n}`}u.set(e,i.Completed)})}return c}}},8708(e,t,r){t.extendErrors=t.resetErrorsCount=t.reportExtraError=t.reportError=t.keyword$DataError=t.y=void 0;const n=r(9029),s=r(4227),i=r(2023);function a(e,t){const r=e.const("err",t);e.if(n._`${i.default.vErrors} === null`,()=>e.assign(i.default.vErrors,n._`[${r}]`),n._`${i.default.vErrors}.push(${r})`),e.code(n._`${i.default.errors}++`)}function o(e,t){const{gen:r,validateName:s,schemaEnv:i}=e;i.$async?r.throw(n._`new ${e.ValidationError}(${t})`):(r.assign(n._`${s}.errors`,t),r.return(!1))}t.y={message:({keyword:e})=>n.str`must pass "${e}" keyword validation`},t.keyword$DataError={message:({keyword:e,schemaType:t})=>t?n.str`"${e}" keyword must be ${t} ($data)`:n.str`"${e}" keyword is invalid ($data)`},t.reportError=function(e,r=t.y,s,i){const{it:c}=e,{gen:l,compositeRule:u,allErrors:h}=c,p=d(e,r,s);(null!=i?i:u||h)?a(l,p):o(c,n._`[${p}]`)},t.reportExtraError=function(e,r=t.y,n){const{it:s}=e,{gen:c,compositeRule:l,allErrors:u}=s;a(c,d(e,r,n)),l||u||o(s,i.default.vErrors)},t.resetErrorsCount=function(e,t){e.assign(i.default.errors,t),e.if(n._`${i.default.vErrors} !== null`,()=>e.if(t,()=>e.assign(n._`${i.default.vErrors}.length`,t),()=>e.assign(i.default.vErrors,null)))},t.extendErrors=function({gen:e,keyword:t,schemaValue:r,data:s,errsCount:a,it:o}){if(void 0===a)throw new Error("ajv implementation error");const c=e.name("err");e.forRange("i",a,i.default.errors,a=>{e.const(c,n._`${i.default.vErrors}[${a}]`),e.if(n._`${c}.instancePath === undefined`,()=>e.assign(n._`${c}.instancePath`,(0,n.strConcat)(i.default.instancePath,o.errorPath))),e.assign(n._`${c}.schemaPath`,n.str`${o.errSchemaPath}/${t}`),o.opts.verbose&&(e.assign(n._`${c}.schema`,r),e.assign(n._`${c}.data`,s))})};const c={keyword:new n.Name("keyword"),schemaPath:new n.Name("schemaPath"),params:new n.Name("params"),propertyName:new n.Name("propertyName"),message:new n.Name("message"),schema:new n.Name("schema"),parentSchema:new n.Name("parentSchema")};function d(e,t,r){const{createErrors:s}=e.it;return!1===s?n._`{}`:function(e,t,r={}){const{gen:s,it:a}=e,o=[l(a,r),u(e,r)];return function(e,{params:t,message:r},s){const{keyword:a,data:o,schemaValue:d,it:l}=e,{opts:u,propertyName:h,topSchemaRef:p,schemaPath:m}=l;s.push([c.keyword,a],[c.params,"function"==typeof t?t(e):t||n._`{}`]),u.messages&&s.push([c.message,"function"==typeof r?r(e):r]),u.verbose&&s.push([c.schema,d],[c.parentSchema,n._`${p}${m}`],[i.default.data,o]),h&&s.push([c.propertyName,h])}(e,t,o),s.object(...o)}(e,t,r)}function l({errorPath:e},{instancePath:t}){const r=t?n.str`${e}${(0,s.getErrorPath)(t,s.Type.Str)}`:e;return[i.default.instancePath,(0,n.strConcat)(i.default.instancePath,r)]}function u({keyword:e,it:{errSchemaPath:t}},{schemaPath:r,parentSchema:i}){let a=i?t:n.str`${t}/${e}`;return r&&(a=n.str`${a}${(0,s.getErrorPath)(r,s.Type.Str)}`),[c.schemaPath,a]}},3835(e,t,r){t.resolveSchema=t.resolveRef=t.compileSchema=t.SchemaEnv=void 0;const n=r(9029),s=r(3558),i=r(2023),a=r(6939),o=r(4227),c=r(2586);class d{constructor(e){var t;let r;this.refs={},this.dynamicAnchors={},"object"==typeof e.schema&&(r=e.schema),this.schema=e.schema,this.schemaId=e.schemaId,this.root=e.root||this,this.baseId=null!==(t=e.baseId)&&void 0!==t?t:(0,a.normalizeId)(null==r?void 0:r[e.schemaId||"$id"]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=null==r?void 0:r.$async,this.refs={}}}function l(e){const t=h.call(this,e);if(t)return t;const r=(0,a.getFullPath)(this.opts.uriResolver,e.root.baseId),{es5:o,lines:d}=this.opts.code,{ownProperties:l}=this.opts,u=new n.CodeGen(this.scope,{es5:o,lines:d,ownProperties:l});let p;e.$async&&(p=u.scopeValue("Error",{ref:s.default,code:n._`require("ajv/dist/runtime/validation_error").default`}));const m=u.scopeName("validate");e.validateName=m;const f={gen:u,allErrors:this.opts.allErrors,data:i.default.data,parentData:i.default.parentData,parentDataProperty:i.default.parentDataProperty,dataNames:[i.default.data],dataPathArr:[n.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:u.scopeValue("schema",!0===this.opts.code.source?{ref:e.schema,code:(0,n.stringify)(e.schema)}:{ref:e.schema}),validateName:m,ValidationError:p,schema:e.schema,schemaEnv:e,rootId:r,baseId:e.baseId||r,schemaPath:n.nil,errSchemaPath:e.schemaPath||(this.opts.jtd?"":"#"),errorPath:n._`""`,opts:this.opts,self:this};let g;try{this._compilations.add(e),(0,c.validateFunctionCode)(f),u.optimize(this.opts.code.optimize);const t=u.toString();g=`${u.scopeRefs(i.default.scope)}return ${t}`,this.opts.code.process&&(g=this.opts.code.process(g,e));const r=new Function(`${i.default.self}`,`${i.default.scope}`,g)(this,this.scope.get());if(this.scope.value(m,{ref:r}),r.errors=null,r.schema=e.schema,r.schemaEnv=e,e.$async&&(r.$async=!0),!0===this.opts.code.source&&(r.source={validateName:m,validateCode:t,scopeValues:u._values}),this.opts.unevaluated){const{props:e,items:t}=f;r.evaluated={props:e instanceof n.Name?void 0:e,items:t instanceof n.Name?void 0:t,dynamicProps:e instanceof n.Name,dynamicItems:t instanceof n.Name},r.source&&(r.source.evaluated=(0,n.stringify)(r.evaluated))}return e.validate=r,e}catch(t){throw delete e.validate,delete e.validateName,g&&this.logger.error("Error compiling schema, function code:",g),t}finally{this._compilations.delete(e)}}function u(e){return(0,a.inlineRef)(e.schema,this.opts.inlineRefs)?e.schema:e.validate?e:l.call(this,e)}function h(e){for(const t of this._compilations)if(p(t,e))return t}function p(e,t){return e.schema===t.schema&&e.root===t.root&&e.baseId===t.baseId}function m(e,t){let r;for(;"string"==typeof(r=this.refs[t]);)t=r;return r||this.schemas[t]||f.call(this,e,t)}function f(e,t){const r=this.opts.uriResolver.parse(t),n=(0,a._getFullPath)(this.opts.uriResolver,r);let s=(0,a.getFullPath)(this.opts.uriResolver,e.baseId,void 0);if(Object.keys(e.schema).length>0&&n===s)return _.call(this,r,e);const i=(0,a.normalizeId)(n),o=this.refs[i]||this.schemas[i];if("string"==typeof o){const t=f.call(this,e,o);if("object"!=typeof(null==t?void 0:t.schema))return;return _.call(this,r,t)}if("object"==typeof(null==o?void 0:o.schema)){if(o.validate||l.call(this,o),i===(0,a.normalizeId)(t)){const{schema:t}=o,{schemaId:r}=this.opts,n=t[r];return n&&(s=(0,a.resolveUrl)(this.opts.uriResolver,s,n)),new d({schema:t,schemaId:r,root:e,baseId:s})}return _.call(this,r,o)}}t.SchemaEnv=d,t.compileSchema=l,t.resolveRef=function(e,t,r){var n;r=(0,a.resolveUrl)(this.opts.uriResolver,t,r);const s=e.refs[r];if(s)return s;let i=m.call(this,e,r);if(void 0===i){const s=null===(n=e.localRefs)||void 0===n?void 0:n[r],{schemaId:a}=this.opts;s&&(i=new d({schema:s,schemaId:a,root:e,baseId:t}))}return void 0!==i?e.refs[r]=u.call(this,i):void 0},t.resolveSchema=f;const g=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function _(e,{baseId:t,schema:r,root:n}){var s;if("/"!==(null===(s=e.fragment)||void 0===s?void 0:s[0]))return;for(const n of e.fragment.slice(1).split("/")){if("boolean"==typeof r)return;const e=r[(0,o.unescapeFragment)(n)];if(void 0===e)return;const s="object"==typeof(r=e)&&r[this.opts.schemaId];!g.has(n)&&s&&(t=(0,a.resolveUrl)(this.opts.uriResolver,t,s))}let i;if("boolean"!=typeof r&&r.$ref&&!(0,o.schemaHasRulesButRef)(r,this.RULES)){const e=(0,a.resolveUrl)(this.opts.uriResolver,t,r.$ref);i=f.call(this,n,e)}const{schemaId:c}=this.opts;return i=i||new d({schema:r,schemaId:c,root:n,baseId:t}),i.schema!==i.root.schema?i:void 0}},2023(e,t,r){const n=r(9029),s={data:new n.Name("data"),valCxt:new n.Name("valCxt"),instancePath:new n.Name("instancePath"),parentData:new n.Name("parentData"),parentDataProperty:new n.Name("parentDataProperty"),rootData:new n.Name("rootData"),dynamicAnchors:new n.Name("dynamicAnchors"),vErrors:new n.Name("vErrors"),errors:new n.Name("errors"),this:new n.Name("this"),self:new n.Name("self"),scope:new n.Name("scope"),json:new n.Name("json"),jsonPos:new n.Name("jsonPos"),jsonLen:new n.Name("jsonLen"),jsonPart:new n.Name("jsonPart")};t.default=s},4551(e,t,r){Object.defineProperty(t,"__esModule",{value:!0});const n=r(6939);class s extends Error{constructor(e,t,r,s){super(s||`can't resolve reference ${r} from id ${t}`),this.missingRef=(0,n.resolveUrl)(e,t,r),this.missingSchema=(0,n.normalizeId)((0,n.getFullPath)(e,this.missingRef))}}t.default=s},6939(e,t,r){t.getSchemaRefs=t.resolveUrl=t.normalizeId=t._getFullPath=t.getFullPath=t.inlineRef=void 0;const n=r(4227),s=r(2017),i=r(7106),a=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);t.inlineRef=function(e,t=!0){return"boolean"==typeof e||(!0===t?!c(e):!!t&&d(e)<=t)};const o=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function c(e){for(const t in e){if(o.has(t))return!0;const r=e[t];if(Array.isArray(r)&&r.some(c))return!0;if("object"==typeof r&&c(r))return!0}return!1}function d(e){let t=0;for(const r in e){if("$ref"===r)return 1/0;if(t++,!a.has(r)&&("object"==typeof e[r]&&(0,n.eachItem)(e[r],e=>t+=d(e)),t===1/0))return 1/0}return t}function l(e,t="",r){!1!==r&&(t=p(t));const n=e.parse(t);return u(e,n)}function u(e,t){return e.serialize(t).split("#")[0]+"#"}t.getFullPath=l,t._getFullPath=u;const h=/#\/?$/;function p(e){return e?e.replace(h,""):""}t.normalizeId=p,t.resolveUrl=function(e,t,r){return r=p(r),e.resolve(t,r)};const m=/^[a-z_][-a-z0-9._]*$/i;t.getSchemaRefs=function(e,t){if("boolean"==typeof e)return{};const{schemaId:r,uriResolver:n}=this.opts,a=p(e[r]||t),o={"":a},c=l(n,a,!1),d={},u=new Set;return i(e,{allKeys:!0},(e,t,n,s)=>{if(void 0===s)return;const i=c+t;let a=o[s];function l(t){const r=this.opts.uriResolver.resolve;if(t=p(a?r(a,t):t),u.has(t))throw f(t);u.add(t);let n=this.refs[t];return"string"==typeof n&&(n=this.refs[n]),"object"==typeof n?h(e,n.schema,t):t!==p(i)&&("#"===t[0]?(h(e,d[t],t),d[t]=e):this.refs[t]=i),t}function g(e){if("string"==typeof e){if(!m.test(e))throw new Error(`invalid anchor "${e}"`);l.call(this,`#${e}`)}}"string"==typeof e[r]&&(a=l.call(this,e[r])),g.call(this,e.$anchor),g.call(this,e.$dynamicAnchor),o[t]=a}),d;function h(e,t,r){if(void 0!==t&&!s(e,t))throw f(r)}function f(e){return new Error(`reference "${e}" resolves to more than one schema`)}}},396(e,t){t.getRules=t.isJSONType=void 0;const r=new Set(["string","number","integer","boolean","null","object","array"]);t.isJSONType=function(e){return"string"==typeof e&&r.has(e)},t.getRules=function(){const e={number:{type:"number",rules:[]},string:{type:"string",rules:[]},array:{type:"array",rules:[]},object:{type:"object",rules:[]}};return{types:{...e,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},e.number,e.string,e.array,e.object],post:{rules:[]},all:{},keywords:{}}}},4227(e,t,r){t.checkStrictMode=t.getErrorPath=t.Type=t.useFunc=t.evaluatedPropsToName=t.mergeEvaluated=t.eachItem=t.unescapeJsonPointer=t.escapeFragment=t.unescapeFragment=t.schemaRefOrVal=t.schemaHasRulesButRef=t.checkUnknownRules=t.alwaysValidSchema=t.toHash=void 0;const n=r(9029),s=r(1520);function i(e,t=e.schema){const{opts:r,self:n}=e;if(!r.strictSchema)return;if("boolean"==typeof t)return;const s=n.RULES.keywords;for(const r in t)s[r]||p(e,`unknown keyword: "${r}"`)}function a(e){return"number"==typeof e?`${e}`:e.replace(/~/g,"~0").replace(/\//g,"~1")}function o(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}function c({mergeNames:e,mergeToName:t,mergeValues:r,resultToName:s}){return(i,a,o,c)=>{const d=void 0===o?a:o instanceof n.Name?(a instanceof n.Name?e(i,a,o):t(i,a,o),o):a instanceof n.Name?(t(i,o,a),a):r(a,o);return c!==n.Name||d instanceof n.Name?d:s(i,d)}}function d(e,t){if(!0===t)return e.var("props",!0);const r=e.var("props",n._`{}`);return void 0!==t&&l(e,r,t),r}function l(e,t,r){Object.keys(r).forEach(r=>e.assign(n._`${t}${(0,n.getProperty)(r)}`,!0))}t.toHash=function(e){const t={};for(const r of e)t[r]=!0;return t},t.alwaysValidSchema=function(e,t){return"boolean"==typeof t?t:0===Object.keys(t).length||(i(e,t),!function(e,t){if("boolean"==typeof e)return!e;for(const r in e)if(t[r])return!0;return!1}(t,e.self.RULES.all))},t.checkUnknownRules=i,t.schemaHasRulesButRef=function(e,t){if("boolean"==typeof e)return!e;for(const r in e)if("$ref"!==r&&t.all[r])return!0;return!1},t.schemaRefOrVal=function({topSchemaRef:e,schemaPath:t},r,s,i){if(!i){if("number"==typeof r||"boolean"==typeof r)return r;if("string"==typeof r)return n._`${r}`}return n._`${e}${t}${(0,n.getProperty)(s)}`},t.unescapeFragment=function(e){return o(decodeURIComponent(e))},t.escapeFragment=function(e){return encodeURIComponent(a(e))},t.unescapeJsonPointer=o,t.eachItem=function(e,t){if(Array.isArray(e))for(const r of e)t(r);else t(e)},t.mergeEvaluated={props:c({mergeNames:(e,t,r)=>e.if(n._`${r} !== true && ${t} !== undefined`,()=>{e.if(n._`${t} === true`,()=>e.assign(r,!0),()=>e.assign(r,n._`${r} || {}`).code(n._`Object.assign(${r}, ${t})`))}),mergeToName:(e,t,r)=>e.if(n._`${r} !== true`,()=>{!0===t?e.assign(r,!0):(e.assign(r,n._`${r} || {}`),l(e,r,t))}),mergeValues:(e,t)=>!0===e||{...e,...t},resultToName:d}),items:c({mergeNames:(e,t,r)=>e.if(n._`${r} !== true && ${t} !== undefined`,()=>e.assign(r,n._`${t} === true ? true : ${r} > ${t} ? ${r} : ${t}`)),mergeToName:(e,t,r)=>e.if(n._`${r} !== true`,()=>e.assign(r,!0===t||n._`${r} > ${t} ? ${r} : ${t}`)),mergeValues:(e,t)=>!0===e||Math.max(e,t),resultToName:(e,t)=>e.var("items",t)})},t.evaluatedPropsToName=d;const u={};var h;function p(e,t,r=e.opts.strictSchema){if(r){if(t=`strict mode: ${t}`,!0===r)throw new Error(t);e.self.logger.warn(t)}}t.useFunc=function(e,t){return e.scopeValue("func",{ref:t,code:u[t.code]||(u[t.code]=new s._Code(t.code))})},function(e){e[e.Num=0]="Num",e[e.Str=1]="Str"}(h||(t.Type=h={})),t.getErrorPath=function(e,t,r){if(e instanceof n.Name){const s=t===h.Num;return r?s?n._`"[" + ${e} + "]"`:n._`"['" + ${e} + "']"`:s?n._`"/" + ${e}`:n._`"/" + ${e}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return r?(0,n.getProperty)(e).toString():"/"+a(e)},t.checkStrictMode=p},7887(e,t){function r(e,t){return t.rules.some(t=>n(e,t))}function n(e,t){var r;return void 0!==e[t.keyword]||(null===(r=t.definition.implements)||void 0===r?void 0:r.some(t=>void 0!==e[t]))}t.shouldUseRule=t.shouldUseGroup=t.schemaHasRulesForType=void 0,t.schemaHasRulesForType=function({schema:e,self:t},n){const s=t.RULES.types[n];return s&&!0!==s&&r(e,s)},t.shouldUseGroup=r,t.shouldUseRule=n},8727(e,t,r){t.boolOrEmptySchema=t.topBoolOrEmptySchema=void 0;const n=r(8708),s=r(9029),i=r(2023),a={message:"boolean schema is false"};function o(e,t){const{gen:r,data:s}=e,i={gen:r,keyword:"false schema",data:s,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:e};(0,n.reportError)(i,a,void 0,t)}t.topBoolOrEmptySchema=function(e){const{gen:t,schema:r,validateName:n}=e;!1===r?o(e,!1):"object"==typeof r&&!0===r.$async?t.return(i.default.data):(t.assign(s._`${n}.errors`,null),t.return(!0))},t.boolOrEmptySchema=function(e,t){const{gen:r,schema:n}=e;!1===n?(r.var(t,!1),o(e)):r.var(t,!0)}},208(e,t,r){t.reportTypeError=t.checkDataTypes=t.checkDataType=t.coerceAndCheckDataType=t.getJSONTypes=t.getSchemaTypes=t.DataType=void 0;const n=r(396),s=r(7887),i=r(8708),a=r(9029),o=r(4227);var c;function d(e){const t=Array.isArray(e)?e:e?[e]:[];if(t.every(n.isJSONType))return t;throw new Error("type must be JSONType or JSONType[]: "+t.join(","))}!function(e){e[e.Correct=0]="Correct",e[e.Wrong=1]="Wrong"}(c||(t.DataType=c={})),t.getSchemaTypes=function(e){const t=d(e.type);if(t.includes("null")){if(!1===e.nullable)throw new Error("type: null contradicts nullable: false")}else{if(!t.length&&void 0!==e.nullable)throw new Error('"nullable" cannot be used without "type"');!0===e.nullable&&t.push("null")}return t},t.getJSONTypes=d,t.coerceAndCheckDataType=function(e,t){const{gen:r,data:n,opts:i}=e,o=function(e,t){return t?e.filter(e=>l.has(e)||"array"===t&&"array"===e):[]}(t,i.coerceTypes),d=t.length>0&&!(0===o.length&&1===t.length&&(0,s.schemaHasRulesForType)(e,t[0]));if(d){const s=h(t,n,i.strictNumbers,c.Wrong);r.if(s,()=>{o.length?function(e,t,r){const{gen:n,data:s,opts:i}=e,o=n.let("dataType",a._`typeof ${s}`),c=n.let("coerced",a._`undefined`);"array"===i.coerceTypes&&n.if(a._`${o} == 'object' && Array.isArray(${s}) && ${s}.length == 1`,()=>n.assign(s,a._`${s}[0]`).assign(o,a._`typeof ${s}`).if(h(t,s,i.strictNumbers),()=>n.assign(c,s))),n.if(a._`${c} !== undefined`);for(const e of r)(l.has(e)||"array"===e&&"array"===i.coerceTypes)&&d(e);function d(e){switch(e){case"string":return void n.elseIf(a._`${o} == "number" || ${o} == "boolean"`).assign(c,a._`"" + ${s}`).elseIf(a._`${s} === null`).assign(c,a._`""`);case"number":return void n.elseIf(a._`${o} == "boolean" || ${s} === null || (${o} == "string" && ${s} && ${s} == +${s})`).assign(c,a._`+${s}`);case"integer":return void n.elseIf(a._`${o} === "boolean" || ${s} === null || (${o} === "string" && ${s} && ${s} == +${s} && !(${s} % 1))`).assign(c,a._`+${s}`);case"boolean":return void n.elseIf(a._`${s} === "false" || ${s} === 0 || ${s} === null`).assign(c,!1).elseIf(a._`${s} === "true" || ${s} === 1`).assign(c,!0);case"null":return n.elseIf(a._`${s} === "" || ${s} === 0 || ${s} === false`),void n.assign(c,null);case"array":n.elseIf(a._`${o} === "string" || ${o} === "number" || ${o} === "boolean" || ${s} === null`).assign(c,a._`[${s}]`)}}n.else(),m(e),n.endIf(),n.if(a._`${c} !== undefined`,()=>{n.assign(s,c),function({gen:e,parentData:t,parentDataProperty:r},n){e.if(a._`${t} !== undefined`,()=>e.assign(a._`${t}[${r}]`,n))}(e,c)})}(e,t,o):m(e)})}return d};const l=new Set(["string","number","integer","boolean","null"]);function u(e,t,r,n=c.Correct){const s=n===c.Correct?a.operators.EQ:a.operators.NEQ;let i;switch(e){case"null":return a._`${t} ${s} null`;case"array":i=a._`Array.isArray(${t})`;break;case"object":i=a._`${t} && typeof ${t} == "object" && !Array.isArray(${t})`;break;case"integer":i=o(a._`!(${t} % 1) && !isNaN(${t})`);break;case"number":i=o();break;default:return a._`typeof ${t} ${s} ${e}`}return n===c.Correct?i:(0,a.not)(i);function o(e=a.nil){return(0,a.and)(a._`typeof ${t} == "number"`,e,r?a._`isFinite(${t})`:a.nil)}}function h(e,t,r,n){if(1===e.length)return u(e[0],t,r,n);let s;const i=(0,o.toHash)(e);if(i.array&&i.object){const e=a._`typeof ${t} != "object"`;s=i.null?e:a._`!${t} || ${e}`,delete i.null,delete i.array,delete i.object}else s=a.nil;i.number&&delete i.integer;for(const e in i)s=(0,a.and)(s,u(e,t,r,n));return s}t.checkDataType=u,t.checkDataTypes=h;const p={message:({schema:e})=>`must be ${e}`,params:({schema:e,schemaValue:t})=>"string"==typeof e?a._`{type: ${e}}`:a._`{type: ${t}}`};function m(e){const t=function(e){const{gen:t,data:r,schema:n}=e,s=(0,o.schemaRefOrVal)(e,n,"type");return{gen:t,keyword:"type",data:r,schema:n.type,schemaCode:s,schemaValue:s,parentSchema:n,params:{},it:e}}(e);(0,i.reportError)(t,p)}t.reportTypeError=m},7870(e,t,r){t.assignDefaults=void 0;const n=r(9029),s=r(4227);function i(e,t,r){const{gen:i,compositeRule:a,data:o,opts:c}=e;if(void 0===r)return;const d=n._`${o}${(0,n.getProperty)(t)}`;if(a)return void(0,s.checkStrictMode)(e,`default is ignored for: ${d}`);let l=n._`${d} === undefined`;"empty"===c.useDefaults&&(l=n._`${l} || ${d} === null || ${d} === ""`),i.if(l,n._`${d} = ${(0,n.stringify)(r)}`)}t.assignDefaults=function(e,t){const{properties:r,items:n}=e.schema;if("object"===t&&r)for(const t in r)i(e,t,r[t].default);else"array"===t&&Array.isArray(n)&&n.forEach((t,r)=>i(e,r,t.default))}},2586(e,t,r){Object.defineProperty(t,"__esModule",{value:!0}),t.getData=t.KeywordCxt=t.validateFunctionCode=void 0;const n=r(8727),s=r(208),i=r(7887),a=r(208),o=r(7870),c=r(3673),d=r(4495),l=r(9029),u=r(2023),h=r(6939),p=r(4227),m=r(8708);function f({gen:e,validateName:t,schema:r,schemaEnv:n,opts:s},i){s.code.es5?e.func(t,l._`${u.default.data}, ${u.default.valCxt}`,n.$async,()=>{e.code(l._`"use strict"; ${g(r,s)}`),function(e,t){e.if(u.default.valCxt,()=>{e.var(u.default.instancePath,l._`${u.default.valCxt}.${u.default.instancePath}`),e.var(u.default.parentData,l._`${u.default.valCxt}.${u.default.parentData}`),e.var(u.default.parentDataProperty,l._`${u.default.valCxt}.${u.default.parentDataProperty}`),e.var(u.default.rootData,l._`${u.default.valCxt}.${u.default.rootData}`),t.dynamicRef&&e.var(u.default.dynamicAnchors,l._`${u.default.valCxt}.${u.default.dynamicAnchors}`)},()=>{e.var(u.default.instancePath,l._`""`),e.var(u.default.parentData,l._`undefined`),e.var(u.default.parentDataProperty,l._`undefined`),e.var(u.default.rootData,u.default.data),t.dynamicRef&&e.var(u.default.dynamicAnchors,l._`{}`)})}(e,s),e.code(i)}):e.func(t,l._`${u.default.data}, ${function(e){return l._`{${u.default.instancePath}="", ${u.default.parentData}, ${u.default.parentDataProperty}, ${u.default.rootData}=${u.default.data}${e.dynamicRef?l._`, ${u.default.dynamicAnchors}={}`:l.nil}}={}`}(s)}`,n.$async,()=>e.code(g(r,s)).code(i))}function g(e,t){const r="object"==typeof e&&e[t.schemaId];return r&&(t.code.source||t.code.process)?l._`/*# sourceURL=${r} */`:l.nil}function _({schema:e,self:t}){if("boolean"==typeof e)return!e;for(const r in e)if(t.RULES.all[r])return!0;return!1}function y(e){return"boolean"!=typeof e.schema}function w(e){(0,p.checkUnknownRules)(e),function(e){const{schema:t,errSchemaPath:r,opts:n,self:s}=e;t.$ref&&n.ignoreKeywordsWithRef&&(0,p.schemaHasRulesButRef)(t,s.RULES)&&s.logger.warn(`$ref: keywords ignored in schema at path "${r}"`)}(e)}function v(e,t){if(e.opts.jtd)return k(e,[],!1,t);const r=(0,s.getSchemaTypes)(e.schema);k(e,r,!(0,s.coerceAndCheckDataType)(e,r),t)}function b({gen:e,schemaEnv:t,schema:r,errSchemaPath:n,opts:s}){const i=r.$comment;if(!0===s.$comment)e.code(l._`${u.default.self}.logger.log(${i})`);else if("function"==typeof s.$comment){const r=l.str`${n}/$comment`,s=e.scopeValue("root",{ref:t.root});e.code(l._`${u.default.self}.opts.$comment(${i}, ${r}, ${s}.schema)`)}}function k(e,t,r,n){const{gen:s,schema:o,data:c,allErrors:d,opts:h,self:m}=e,{RULES:f}=m;function g(p){(0,i.shouldUseGroup)(o,p)&&(p.type?(s.if((0,a.checkDataType)(p.type,c,h.strictNumbers)),S(e,p),1===t.length&&t[0]===p.type&&r&&(s.else(),(0,a.reportTypeError)(e)),s.endIf()):S(e,p),d||s.if(l._`${u.default.errors} === ${n||0}`))}!o.$ref||!h.ignoreKeywordsWithRef&&(0,p.schemaHasRulesButRef)(o,f)?(h.jtd||function(e,t){!e.schemaEnv.meta&&e.opts.strictTypes&&(function(e,t){t.length&&(e.dataTypes.length?(t.forEach(t=>{$(e.dataTypes,t)||E(e,`type "${t}" not allowed by context "${e.dataTypes.join(",")}"`)}),function(e,t){const r=[];for(const n of e.dataTypes)$(t,n)?r.push(n):t.includes("integer")&&"number"===n&&r.push("integer");e.dataTypes=r}(e,t)):e.dataTypes=t)}(e,t),e.opts.allowUnionTypes||function(e,t){t.length>1&&(2!==t.length||!t.includes("null"))&&E(e,"use allowUnionTypes to allow union type keyword")}(e,t),function(e,t){const r=e.self.RULES.all;for(const n in r){const s=r[n];if("object"==typeof s&&(0,i.shouldUseRule)(e.schema,s)){const{type:r}=s.definition;r.length&&!r.some(e=>{return n=e,(r=t).includes(n)||"number"===n&&r.includes("integer");var r,n})&&E(e,`missing type "${r.join(",")}" for keyword "${n}"`)}}}(e,e.dataTypes))}(e,t),s.block(()=>{for(const e of f.rules)g(e);g(f.post)})):s.block(()=>I(e,"$ref",f.all.$ref.definition))}function S(e,t){const{gen:r,schema:n,opts:{useDefaults:s}}=e;s&&(0,o.assignDefaults)(e,t.type),r.block(()=>{for(const r of t.rules)(0,i.shouldUseRule)(n,r)&&I(e,r.keyword,r.definition,t.type)})}function $(e,t){return e.includes(t)||"integer"===t&&e.includes("number")}function E(e,t){t+=` at "${e.schemaEnv.baseId+e.errSchemaPath}" (strictTypes)`,(0,p.checkStrictMode)(e,t,e.opts.strictTypes)}t.validateFunctionCode=function(e){y(e)&&(w(e),_(e))?function(e){const{schema:t,opts:r,gen:n}=e;f(e,()=>{r.$comment&&t.$comment&&b(e),function(e){const{schema:t,opts:r}=e;void 0!==t.default&&r.useDefaults&&r.strictSchema&&(0,p.checkStrictMode)(e,"default is ignored in the schema root")}(e),n.let(u.default.vErrors,null),n.let(u.default.errors,0),r.unevaluated&&function(e){const{gen:t,validateName:r}=e;e.evaluated=t.const("evaluated",l._`${r}.evaluated`),t.if(l._`${e.evaluated}.dynamicProps`,()=>t.assign(l._`${e.evaluated}.props`,l._`undefined`)),t.if(l._`${e.evaluated}.dynamicItems`,()=>t.assign(l._`${e.evaluated}.items`,l._`undefined`))}(e),v(e),function(e){const{gen:t,schemaEnv:r,validateName:n,ValidationError:s,opts:i}=e;r.$async?t.if(l._`${u.default.errors} === 0`,()=>t.return(u.default.data),()=>t.throw(l._`new ${s}(${u.default.vErrors})`)):(t.assign(l._`${n}.errors`,u.default.vErrors),i.unevaluated&&function({gen:e,evaluated:t,props:r,items:n}){r instanceof l.Name&&e.assign(l._`${t}.props`,r),n instanceof l.Name&&e.assign(l._`${t}.items`,n)}(e),t.return(l._`${u.default.errors} === 0`))}(e)})}(e):f(e,()=>(0,n.topBoolOrEmptySchema)(e))};class T{constructor(e,t,r){if((0,c.validateKeywordUsage)(e,t,r),this.gen=e.gen,this.allErrors=e.allErrors,this.keyword=r,this.data=e.data,this.schema=e.schema[r],this.$data=t.$data&&e.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,p.schemaRefOrVal)(e,this.schema,r,this.$data),this.schemaType=t.schemaType,this.parentSchema=e.schema,this.params={},this.it=e,this.def=t,this.$data)this.schemaCode=e.gen.const("vSchema",C(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,c.validSchemaType)(this.schema,t.schemaType,t.allowUndefined))throw new Error(`${r} value must be ${JSON.stringify(t.schemaType)}`);("code"in t?t.trackErrors:!1!==t.errors)&&(this.errsCount=e.gen.const("_errs",u.default.errors))}result(e,t,r){this.failResult((0,l.not)(e),t,r)}failResult(e,t,r){this.gen.if(e),r?r():this.error(),t?(this.gen.else(),t(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(e,t){this.failResult((0,l.not)(e),void 0,t)}fail(e){if(void 0===e)return this.error(),void(this.allErrors||this.gen.if(!1));this.gen.if(e),this.error(),this.allErrors?this.gen.endIf():this.gen.else()}fail$data(e){if(!this.$data)return this.fail(e);const{schemaCode:t}=this;this.fail(l._`${t} !== undefined && (${(0,l.or)(this.invalid$data(),e)})`)}error(e,t,r){if(t)return this.setParams(t),this._error(e,r),void this.setParams({});this._error(e,r)}_error(e,t){(e?m.reportExtraError:m.reportError)(this,this.def.error,t)}$dataError(){(0,m.reportError)(this,this.def.$dataError||m.keyword$DataError)}reset(){if(void 0===this.errsCount)throw new Error('add "trackErrors" to keyword definition');(0,m.resetErrorsCount)(this.gen,this.errsCount)}ok(e){this.allErrors||this.gen.if(e)}setParams(e,t){t?Object.assign(this.params,e):this.params=e}block$data(e,t,r=l.nil){this.gen.block(()=>{this.check$data(e,r),t()})}check$data(e=l.nil,t=l.nil){if(!this.$data)return;const{gen:r,schemaCode:n,schemaType:s,def:i}=this;r.if((0,l.or)(l._`${n} === undefined`,t)),e!==l.nil&&r.assign(e,!0),(s.length||i.validateSchema)&&(r.elseIf(this.invalid$data()),this.$dataError(),e!==l.nil&&r.assign(e,!1)),r.else()}invalid$data(){const{gen:e,schemaCode:t,schemaType:r,def:n,it:s}=this;return(0,l.or)(function(){if(r.length){if(!(t instanceof l.Name))throw new Error("ajv implementation error");const e=Array.isArray(r)?r:[r];return l._`${(0,a.checkDataTypes)(e,t,s.opts.strictNumbers,a.DataType.Wrong)}`}return l.nil}(),function(){if(n.validateSchema){const r=e.scopeValue("validate$data",{ref:n.validateSchema});return l._`!${r}(${t})`}return l.nil}())}subschema(e,t){const r=(0,d.getSubschema)(this.it,e);(0,d.extendSubschemaData)(r,this.it,e),(0,d.extendSubschemaMode)(r,e);const s={...this.it,...r,items:void 0,props:void 0};return function(e,t){y(e)&&(w(e),_(e))?function(e,t){const{schema:r,gen:n,opts:s}=e;s.$comment&&r.$comment&&b(e),function(e){const t=e.schema[e.opts.schemaId];t&&(e.baseId=(0,h.resolveUrl)(e.opts.uriResolver,e.baseId,t))}(e),function(e){if(e.schema.$async&&!e.schemaEnv.$async)throw new Error("async schema in sync schema")}(e);const i=n.const("_errs",u.default.errors);v(e,i),n.var(t,l._`${i} === ${u.default.errors}`)}(e,t):(0,n.boolOrEmptySchema)(e,t)}(s,t),s}mergeEvaluated(e,t){const{it:r,gen:n}=this;r.opts.unevaluated&&(!0!==r.props&&void 0!==e.props&&(r.props=p.mergeEvaluated.props(n,e.props,r.props,t)),!0!==r.items&&void 0!==e.items&&(r.items=p.mergeEvaluated.items(n,e.items,r.items,t)))}mergeValidEvaluated(e,t){const{it:r,gen:n}=this;if(r.opts.unevaluated&&(!0!==r.props||!0!==r.items))return n.if(t,()=>this.mergeEvaluated(e,l.Name)),!0}}function I(e,t,r,n){const s=new T(e,r,t);"code"in r?r.code(s,n):s.$data&&r.validate?(0,c.funcKeywordCode)(s,r):"macro"in r?(0,c.macroKeywordCode)(s,r):(r.compile||r.validate)&&(0,c.funcKeywordCode)(s,r)}t.KeywordCxt=T;const x=/^\/(?:[^~]|~0|~1)*$/,P=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function C(e,{dataLevel:t,dataNames:r,dataPathArr:n}){let s,i;if(""===e)return u.default.rootData;if("/"===e[0]){if(!x.test(e))throw new Error(`Invalid JSON-pointer: ${e}`);s=e,i=u.default.rootData}else{const a=P.exec(e);if(!a)throw new Error(`Invalid JSON-pointer: ${e}`);const o=+a[1];if(s=a[2],"#"===s){if(o>=t)throw new Error(c("property/index",o));return n[t-o]}if(o>t)throw new Error(c("data",o));if(i=r[t-o],!s)return i}let a=i;const o=s.split("/");for(const e of o)e&&(i=l._`${i}${(0,l.getProperty)((0,p.unescapeJsonPointer)(e))}`,a=l._`${a} && ${i}`);return a;function c(e,r){return`Cannot access ${e} ${r} levels up, current level is ${t}`}}t.getData=C},3673(e,t,r){t.validateKeywordUsage=t.validSchemaType=t.funcKeywordCode=t.macroKeywordCode=void 0;const n=r(9029),s=r(2023),i=r(5765),a=r(8708);function o(e){const{gen:t,data:r,it:s}=e;t.if(s.parentData,()=>t.assign(r,n._`${s.parentData}[${s.parentDataProperty}]`))}function c(e,t,r){if(void 0===r)throw new Error(`keyword "${t}" failed to compile`);return e.scopeValue("keyword","function"==typeof r?{ref:r}:{ref:r,code:(0,n.stringify)(r)})}t.macroKeywordCode=function(e,t){const{gen:r,keyword:s,schema:i,parentSchema:a,it:o}=e,d=t.macro.call(o.self,i,a,o),l=c(r,s,d);!1!==o.opts.validateSchema&&o.self.validateSchema(d,!0);const u=r.name("valid");e.subschema({schema:d,schemaPath:n.nil,errSchemaPath:`${o.errSchemaPath}/${s}`,topSchemaRef:l,compositeRule:!0},u),e.pass(u,()=>e.error(!0))},t.funcKeywordCode=function(e,t){var r;const{gen:d,keyword:l,schema:u,parentSchema:h,$data:p,it:m}=e;!function({schemaEnv:e},t){if(t.async&&!e.$async)throw new Error("async keyword in sync schema")}(m,t);const f=!p&&t.compile?t.compile.call(m.self,u,h,m):t.validate,g=c(d,l,f),_=d.let("valid");function y(r=(t.async?n._`await `:n.nil)){const a=m.opts.passContext?s.default.this:s.default.self,o=!("compile"in t&&!p||!1===t.schema);d.assign(_,n._`${r}${(0,i.callValidateCode)(e,g,a,o)}`,t.modifying)}function w(e){var r;d.if((0,n.not)(null!==(r=t.valid)&&void 0!==r?r:_),e)}e.block$data(_,function(){if(!1===t.errors)y(),t.modifying&&o(e),w(()=>e.error());else{const r=t.async?function(){const e=d.let("ruleErrs",null);return d.try(()=>y(n._`await `),t=>d.assign(_,!1).if(n._`${t} instanceof ${m.ValidationError}`,()=>d.assign(e,n._`${t}.errors`),()=>d.throw(t))),e}():function(){const e=n._`${g}.errors`;return d.assign(e,null),y(n.nil),e}();t.modifying&&o(e),w(()=>function(e,t){const{gen:r}=e;r.if(n._`Array.isArray(${t})`,()=>{r.assign(s.default.vErrors,n._`${s.default.vErrors} === null ? ${t} : ${s.default.vErrors}.concat(${t})`).assign(s.default.errors,n._`${s.default.vErrors}.length`),(0,a.extendErrors)(e)},()=>e.error())}(e,r))}}),e.ok(null!==(r=t.valid)&&void 0!==r?r:_)},t.validSchemaType=function(e,t,r=!1){return!t.length||t.some(t=>"array"===t?Array.isArray(e):"object"===t?e&&"object"==typeof e&&!Array.isArray(e):typeof e==t||r&&void 0===e)},t.validateKeywordUsage=function({schema:e,opts:t,self:r,errSchemaPath:n},s,i){if(Array.isArray(s.keyword)?!s.keyword.includes(i):s.keyword!==i)throw new Error("ajv implementation error");const a=s.dependencies;if(null==a?void 0:a.some(t=>!Object.prototype.hasOwnProperty.call(e,t)))throw new Error(`parent schema must have dependencies of ${i}: ${a.join(",")}`);if(s.validateSchema&&!s.validateSchema(e[i])){const e=`keyword "${i}" value is invalid at path "${n}": `+r.errorsText(s.validateSchema.errors);if("log"!==t.validateSchema)throw new Error(e);r.logger.error(e)}}},4495(e,t,r){t.extendSubschemaMode=t.extendSubschemaData=t.getSubschema=void 0;const n=r(9029),s=r(4227);t.getSubschema=function(e,{keyword:t,schemaProp:r,schema:i,schemaPath:a,errSchemaPath:o,topSchemaRef:c}){if(void 0!==t&&void 0!==i)throw new Error('both "keyword" and "schema" passed, only one allowed');if(void 0!==t){const i=e.schema[t];return void 0===r?{schema:i,schemaPath:n._`${e.schemaPath}${(0,n.getProperty)(t)}`,errSchemaPath:`${e.errSchemaPath}/${t}`}:{schema:i[r],schemaPath:n._`${e.schemaPath}${(0,n.getProperty)(t)}${(0,n.getProperty)(r)}`,errSchemaPath:`${e.errSchemaPath}/${t}/${(0,s.escapeFragment)(r)}`}}if(void 0!==i){if(void 0===a||void 0===o||void 0===c)throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:i,schemaPath:a,topSchemaRef:c,errSchemaPath:o}}throw new Error('either "keyword" or "schema" must be passed')},t.extendSubschemaData=function(e,t,{dataProp:r,dataPropType:i,data:a,dataTypes:o,propertyName:c}){if(void 0!==a&&void 0!==r)throw new Error('both "data" and "dataProp" passed, only one allowed');const{gen:d}=t;if(void 0!==r){const{errorPath:a,dataPathArr:o,opts:c}=t;l(d.let("data",n._`${t.data}${(0,n.getProperty)(r)}`,!0)),e.errorPath=n.str`${a}${(0,s.getErrorPath)(r,i,c.jsPropertySyntax)}`,e.parentDataProperty=n._`${r}`,e.dataPathArr=[...o,e.parentDataProperty]}function l(r){e.data=r,e.dataLevel=t.dataLevel+1,e.dataTypes=[],t.definedProperties=new Set,e.parentData=t.data,e.dataNames=[...t.dataNames,r]}void 0!==a&&(l(a instanceof n.Name?a:d.let("data",a,!0)),void 0!==c&&(e.propertyName=c)),o&&(e.dataTypes=o)},t.extendSubschemaMode=function(e,{jtdDiscriminator:t,jtdMetadata:r,compositeRule:n,createErrors:s,allErrors:i}){void 0!==n&&(e.compositeRule=n),void 0!==s&&(e.createErrors=s),void 0!==i&&(e.allErrors=i),e.jtdDiscriminator=t,e.jtdMetadata=r}},4042(e,t,r){r(2586),r(9029);const n=r(3558),s=r(4551),i=r(396),a=r(3835),o=r(9029),c=r(6939),d=r(208),l=r(4227),u=r(3837),h=r(5944),p=(e,t)=>new RegExp(e,t);p.code="new RegExp";const m=["removeAdditional","useDefaults","coerceTypes"],f=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),g={errorDataPath:"",format:"`validateFormats: false` can be used instead.",nullable:'"nullable" keyword is supported by default.',jsonPointers:"Deprecated jsPropertySyntax can be used instead.",extendRefs:"Deprecated ignoreKeywordsWithRef can be used instead.",missingRefs:"Pass empty schema with $id that should be ignored to ajv.addSchema.",processCode:"Use option `code: {process: (code, schemaEnv: object) => string}`",sourceCode:"Use option `code: {source: true}`",strictDefaults:"It is default now, see option `strict`.",strictKeywords:"It is default now, see option `strict`.",uniqueItems:'"uniqueItems" keyword is always validated.',unknownFormats:"Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).",cache:"Map is used as cache, schema object as key.",serialize:"Map is used as cache, schema object as key.",ajvErrors:"It is default now."},_={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'};function y(e){var t,r,n,s,i,a,o,c,d,l,u,m,f,g,_,y,w,v,b,k,S,$,E,T,I;const x=e.strict,P=null===(t=e.code)||void 0===t?void 0:t.optimize,C=!0===P||void 0===P?1:P||0,R=null!==(n=null===(r=e.code)||void 0===r?void 0:r.regExp)&&void 0!==n?n:p,A=null!==(s=e.uriResolver)&&void 0!==s?s:h.default;return{strictSchema:null===(a=null!==(i=e.strictSchema)&&void 0!==i?i:x)||void 0===a||a,strictNumbers:null===(c=null!==(o=e.strictNumbers)&&void 0!==o?o:x)||void 0===c||c,strictTypes:null!==(l=null!==(d=e.strictTypes)&&void 0!==d?d:x)&&void 0!==l?l:"log",strictTuples:null!==(m=null!==(u=e.strictTuples)&&void 0!==u?u:x)&&void 0!==m?m:"log",strictRequired:null!==(g=null!==(f=e.strictRequired)&&void 0!==f?f:x)&&void 0!==g&&g,code:e.code?{...e.code,optimize:C,regExp:R}:{optimize:C,regExp:R},loopRequired:null!==(_=e.loopRequired)&&void 0!==_?_:200,loopEnum:null!==(y=e.loopEnum)&&void 0!==y?y:200,meta:null===(w=e.meta)||void 0===w||w,messages:null===(v=e.messages)||void 0===v||v,inlineRefs:null===(b=e.inlineRefs)||void 0===b||b,schemaId:null!==(k=e.schemaId)&&void 0!==k?k:"$id",addUsedSchema:null===(S=e.addUsedSchema)||void 0===S||S,validateSchema:null===($=e.validateSchema)||void 0===$||$,validateFormats:null===(E=e.validateFormats)||void 0===E||E,unicodeRegExp:null===(T=e.unicodeRegExp)||void 0===T||T,int32range:null===(I=e.int32range)||void 0===I||I,uriResolver:A}}class w{constructor(e={}){this.schemas={},this.refs={},this.formats=Object.create(null),this._compilations=new Set,this._loading={},this._cache=new Map,e=this.opts={...e,...y(e)};const{es5:t,lines:r}=this.opts.code;this.scope=new o.ValueScope({scope:{},prefixes:f,es5:t,lines:r}),this.logger=function(e){if(!1===e)return T;if(void 0===e)return console;if(e.log&&e.warn&&e.error)return e;throw new Error("logger must implement log, warn and error methods")}(e.logger);const n=e.validateFormats;e.validateFormats=!1,this.RULES=(0,i.getRules)(),v.call(this,g,e,"NOT SUPPORTED"),v.call(this,_,e,"DEPRECATED","warn"),this._metaOpts=E.call(this),e.formats&&S.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&$.call(this,e.keywords),"object"==typeof e.meta&&this.addMetaSchema(e.meta),k.call(this),e.validateFormats=n}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){const{$data:e,meta:t,schemaId:r}=this.opts;let n=u;"id"===r&&(n={...u},n.id=n.$id,delete n.$id),t&&e&&this.addMetaSchema(n,n[r],!1)}defaultMeta(){const{meta:e,schemaId:t}=this.opts;return this.opts.defaultMeta="object"==typeof e?e[t]||e:void 0}validate(e,t){let r;if("string"==typeof e){if(r=this.getSchema(e),!r)throw new Error(`no schema with key or ref "${e}"`)}else r=this.compile(e);const n=r(t);return"$async"in r||(this.errors=r.errors),n}compile(e,t){const r=this._addSchema(e,t);return r.validate||this._compileSchemaEnv(r)}compileAsync(e,t){if("function"!=typeof this.opts.loadSchema)throw new Error("options.loadSchema should be a function");const{loadSchema:r}=this.opts;return n.call(this,e,t);async function n(e,t){await i.call(this,e.$schema);const r=this._addSchema(e,t);return r.validate||a.call(this,r)}async function i(e){e&&!this.getSchema(e)&&await n.call(this,{$ref:e},!0)}async function a(e){try{return this._compileSchemaEnv(e)}catch(t){if(!(t instanceof s.default))throw t;return o.call(this,t),await c.call(this,t.missingSchema),a.call(this,e)}}function o({missingSchema:e,missingRef:t}){if(this.refs[e])throw new Error(`AnySchema ${e} is loaded but ${t} cannot be resolved`)}async function c(e){const r=await d.call(this,e);this.refs[e]||await i.call(this,r.$schema),this.refs[e]||this.addSchema(r,e,t)}async function d(e){const t=this._loading[e];if(t)return t;try{return await(this._loading[e]=r(e))}finally{delete this._loading[e]}}}addSchema(e,t,r,n=this.opts.validateSchema){if(Array.isArray(e)){for(const t of e)this.addSchema(t,void 0,r,n);return this}let s;if("object"==typeof e){const{schemaId:t}=this.opts;if(s=e[t],void 0!==s&&"string"!=typeof s)throw new Error(`schema ${t} must be string`)}return t=(0,c.normalizeId)(t||s),this._checkUnique(t),this.schemas[t]=this._addSchema(e,r,t,n,!0),this}addMetaSchema(e,t,r=this.opts.validateSchema){return this.addSchema(e,t,!0,r),this}validateSchema(e,t){if("boolean"==typeof e)return!0;let r;if(r=e.$schema,void 0!==r&&"string"!=typeof r)throw new Error("$schema must be a string");if(r=r||this.opts.defaultMeta||this.defaultMeta(),!r)return this.logger.warn("meta-schema not available"),this.errors=null,!0;const n=this.validate(r,e);if(!n&&t){const e="schema is invalid: "+this.errorsText();if("log"!==this.opts.validateSchema)throw new Error(e);this.logger.error(e)}return n}getSchema(e){let t;for(;"string"==typeof(t=b.call(this,e));)e=t;if(void 0===t){const{schemaId:r}=this.opts,n=new a.SchemaEnv({schema:{},schemaId:r});if(t=a.resolveSchema.call(this,n,e),!t)return;this.refs[e]=t}return t.validate||this._compileSchemaEnv(t)}removeSchema(e){if(e instanceof RegExp)return this._removeAllSchemas(this.schemas,e),this._removeAllSchemas(this.refs,e),this;switch(typeof e){case"undefined":return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case"string":{const t=b.call(this,e);return"object"==typeof t&&this._cache.delete(t.schema),delete this.schemas[e],delete this.refs[e],this}case"object":{const t=e;this._cache.delete(t);let r=e[this.opts.schemaId];return r&&(r=(0,c.normalizeId)(r),delete this.schemas[r],delete this.refs[r]),this}default:throw new Error("ajv.removeSchema: invalid parameter")}}addVocabulary(e){for(const t of e)this.addKeyword(t);return this}addKeyword(e,t){let r;if("string"==typeof e)r=e,"object"==typeof t&&(this.logger.warn("these parameters are deprecated, see docs for addKeyword"),t.keyword=r);else{if("object"!=typeof e||void 0!==t)throw new Error("invalid addKeywords parameters");if(r=(t=e).keyword,Array.isArray(r)&&!r.length)throw new Error("addKeywords: keyword must be string or non-empty array")}if(x.call(this,r,t),!t)return(0,l.eachItem)(r,e=>P.call(this,e)),this;R.call(this,t);const n={...t,type:(0,d.getJSONTypes)(t.type),schemaType:(0,d.getJSONTypes)(t.schemaType)};return(0,l.eachItem)(r,0===n.type.length?e=>P.call(this,e,n):e=>n.type.forEach(t=>P.call(this,e,n,t))),this}getKeyword(e){const t=this.RULES.all[e];return"object"==typeof t?t.definition:!!t}removeKeyword(e){const{RULES:t}=this;delete t.keywords[e],delete t.all[e];for(const r of t.rules){const t=r.rules.findIndex(t=>t.keyword===e);t>=0&&r.rules.splice(t,1)}return this}addFormat(e,t){return"string"==typeof t&&(t=new RegExp(t)),this.formats[e]=t,this}errorsText(e=this.errors,{separator:t=", ",dataVar:r="data"}={}){return e&&0!==e.length?e.map(e=>`${r}${e.instancePath} ${e.message}`).reduce((e,r)=>e+t+r):"No errors"}$dataMetaSchema(e,t){const r=this.RULES.all;e=JSON.parse(JSON.stringify(e));for(const n of t){const t=n.split("/").slice(1);let s=e;for(const e of t)s=s[e];for(const e in r){const t=r[e];if("object"!=typeof t)continue;const{$data:n}=t.definition,i=s[e];n&&i&&(s[e]=O(i))}}return e}_removeAllSchemas(e,t){for(const r in e){const n=e[r];t&&!t.test(r)||("string"==typeof n?delete e[r]:n&&!n.meta&&(this._cache.delete(n.schema),delete e[r]))}}_addSchema(e,t,r,n=this.opts.validateSchema,s=this.opts.addUsedSchema){let i;const{schemaId:o}=this.opts;if("object"==typeof e)i=e[o];else{if(this.opts.jtd)throw new Error("schema must be object");if("boolean"!=typeof e)throw new Error("schema must be object or boolean")}let d=this._cache.get(e);if(void 0!==d)return d;r=(0,c.normalizeId)(i||r);const l=c.getSchemaRefs.call(this,e,r);return d=new a.SchemaEnv({schema:e,schemaId:o,meta:t,baseId:r,localRefs:l}),this._cache.set(d.schema,d),s&&!r.startsWith("#")&&(r&&this._checkUnique(r),this.refs[r]=d),n&&this.validateSchema(e,!0),d}_checkUnique(e){if(this.schemas[e]||this.refs[e])throw new Error(`schema with key or id "${e}" already exists`)}_compileSchemaEnv(e){if(e.meta?this._compileMetaSchema(e):a.compileSchema.call(this,e),!e.validate)throw new Error("ajv implementation error");return e.validate}_compileMetaSchema(e){const t=this.opts;this.opts=this._metaOpts;try{a.compileSchema.call(this,e)}finally{this.opts=t}}}function v(e,t,r,n="error"){for(const s in e){const i=s;i in t&&this.logger[n](`${r}: option ${s}. ${e[i]}`)}}function b(e){return e=(0,c.normalizeId)(e),this.schemas[e]||this.refs[e]}function k(){const e=this.opts.schemas;if(e)if(Array.isArray(e))this.addSchema(e);else for(const t in e)this.addSchema(e[t],t)}function S(){for(const e in this.opts.formats){const t=this.opts.formats[e];t&&this.addFormat(e,t)}}function $(e){if(Array.isArray(e))this.addVocabulary(e);else{this.logger.warn("keywords option as map is deprecated, pass array");for(const t in e){const r=e[t];r.keyword||(r.keyword=t),this.addKeyword(r)}}}function E(){const e={...this.opts};for(const t of m)delete e[t];return e}w.ValidationError=n.default,w.MissingRefError=s.default,t.default=w;const T={log(){},warn(){},error(){}},I=/^[a-z_$][a-z0-9_$:-]*$/i;function x(e,t){const{RULES:r}=this;if((0,l.eachItem)(e,e=>{if(r.keywords[e])throw new Error(`Keyword ${e} is already defined`);if(!I.test(e))throw new Error(`Keyword ${e} has invalid name`)}),t&&t.$data&&!("code"in t)&&!("validate"in t))throw new Error('$data keyword must have "code" or "validate" function')}function P(e,t,r){var n;const s=null==t?void 0:t.post;if(r&&s)throw new Error('keyword with "post" flag cannot have "type"');const{RULES:i}=this;let a=s?i.post:i.rules.find(({type:e})=>e===r);if(a||(a={type:r,rules:[]},i.rules.push(a)),i.keywords[e]=!0,!t)return;const o={keyword:e,definition:{...t,type:(0,d.getJSONTypes)(t.type),schemaType:(0,d.getJSONTypes)(t.schemaType)}};t.before?C.call(this,a,o,t.before):a.rules.push(o),i.all[e]=o,null===(n=t.implements)||void 0===n||n.forEach(e=>this.addKeyword(e))}function C(e,t,r){const n=e.rules.findIndex(e=>e.keyword===r);n>=0?e.rules.splice(n,0,t):(e.rules.push(t),this.logger.warn(`rule ${r} is not defined`))}function R(e){let{metaSchema:t}=e;void 0!==t&&(e.$data&&this.opts.$data&&(t=O(t)),e.validateSchema=this.compile(t,!0))}const A={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function O(e){return{anyOf:[e,A]}}},6250(e,t,r){const n=r(2017);n.code='require("ajv/dist/runtime/equal").default',t.default=n},3853(e,t){function r(e){const t=e.length;let r,n=0,s=0;for(;s<t;)n++,r=e.charCodeAt(s++),r>=55296&&r<=56319&&s<t&&(r=e.charCodeAt(s),56320==(64512&r)&&s++);return n}t.default=r,r.code='require("ajv/dist/runtime/ucs2length").default'},5944(e,t,r){const n=r(8343);n.code='require("ajv/dist/runtime/uri").default',t.default=n},3558(e,t){Object.defineProperty(t,"__esModule",{value:!0});class r extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=!0}}t.default=r},5457(e,t,r){t.validateAdditionalItems=void 0;const n=r(9029),s=r(4227),i={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:{message:({params:{len:e}})=>n.str`must NOT have more than ${e} items`,params:({params:{len:e}})=>n._`{limit: ${e}}`},code(e){const{parentSchema:t,it:r}=e,{items:n}=t;Array.isArray(n)?a(e,n):(0,s.checkStrictMode)(r,'"additionalItems" is ignored when "items" is not an array of schemas')}};function a(e,t){const{gen:r,schema:i,data:a,keyword:o,it:c}=e;c.items=!0;const d=r.const("len",n._`${a}.length`);if(!1===i)e.setParams({len:t.length}),e.pass(n._`${d} <= ${t.length}`);else if("object"==typeof i&&!(0,s.alwaysValidSchema)(c,i)){const i=r.var("valid",n._`${d} <= ${t.length}`);r.if((0,n.not)(i),()=>function(i){r.forRange("i",t.length,d,t=>{e.subschema({keyword:o,dataProp:t,dataPropType:s.Type.Num},i),c.allErrors||r.if((0,n.not)(i),()=>r.break())})}(i)),e.ok(i)}}t.validateAdditionalItems=a,t.default=i},8660(e,t,r){const n=r(5765),s=r(9029),i=r(2023),a=r(4227),o={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:{message:"must NOT have additional properties",params:({params:e})=>s._`{additionalProperty: ${e.additionalProperty}}`},code(e){const{gen:t,schema:r,parentSchema:o,data:c,errsCount:d,it:l}=e;if(!d)throw new Error("ajv implementation error");const{allErrors:u,opts:h}=l;if(l.props=!0,"all"!==h.removeAdditional&&(0,a.alwaysValidSchema)(l,r))return;const p=(0,n.allSchemaProperties)(o.properties),m=(0,n.allSchemaProperties)(o.patternProperties);function f(e){t.code(s._`delete ${c}[${e}]`)}function g(n){if("all"===h.removeAdditional||h.removeAdditional&&!1===r)f(n);else{if(!1===r)return e.setParams({additionalProperty:n}),e.error(),void(u||t.break());if("object"==typeof r&&!(0,a.alwaysValidSchema)(l,r)){const r=t.name("valid");"failing"===h.removeAdditional?(_(n,r,!1),t.if((0,s.not)(r),()=>{e.reset(),f(n)})):(_(n,r),u||t.if((0,s.not)(r),()=>t.break()))}}}function _(t,r,n){const s={keyword:"additionalProperties",dataProp:t,dataPropType:a.Type.Str};!1===n&&Object.assign(s,{compositeRule:!0,createErrors:!1,allErrors:!1}),e.subschema(s,r)}t.forIn("key",c,r=>{p.length||m.length?t.if(function(r){let i;if(p.length>8){const e=(0,a.schemaRefOrVal)(l,o.properties,"properties");i=(0,n.isOwnProperty)(t,e,r)}else i=p.length?(0,s.or)(...p.map(e=>s._`${r} === ${e}`)):s.nil;return m.length&&(i=(0,s.or)(i,...m.map(t=>s._`${(0,n.usePattern)(e,t)}.test(${r})`))),(0,s.not)(i)}(r),()=>g(r)):g(r)}),e.ok(s._`${d} === ${i.default.errors}`)}};t.default=o},5844(e,t,r){const n=r(4227),s={keyword:"allOf",schemaType:"array",code(e){const{gen:t,schema:r,it:s}=e;if(!Array.isArray(r))throw new Error("ajv implementation error");const i=t.name("valid");r.forEach((t,r)=>{if((0,n.alwaysValidSchema)(s,t))return;const a=e.subschema({keyword:"allOf",schemaProp:r},i);e.ok(i),e.mergeEvaluated(a)})}};t.default=s},6505(e,t,r){const n={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:r(5765).validateUnion,error:{message:"must match a schema in anyOf"}};t.default=n},2661(e,t,r){const n=r(9029),s=r(4227),i={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:{message:({params:{min:e,max:t}})=>void 0===t?n.str`must contain at least ${e} valid item(s)`:n.str`must contain at least ${e} and no more than ${t} valid item(s)`,params:({params:{min:e,max:t}})=>void 0===t?n._`{minContains: ${e}}`:n._`{minContains: ${e}, maxContains: ${t}}`},code(e){const{gen:t,schema:r,parentSchema:i,data:a,it:o}=e;let c,d;const{minContains:l,maxContains:u}=i;o.opts.next?(c=void 0===l?1:l,d=u):c=1;const h=t.const("len",n._`${a}.length`);if(e.setParams({min:c,max:d}),void 0===d&&0===c)return void(0,s.checkStrictMode)(o,'"minContains" == 0 without "maxContains": "contains" keyword ignored');if(void 0!==d&&c>d)return(0,s.checkStrictMode)(o,'"minContains" > "maxContains" is always invalid'),void e.fail();if((0,s.alwaysValidSchema)(o,r)){let t=n._`${h} >= ${c}`;return void 0!==d&&(t=n._`${t} && ${h} <= ${d}`),void e.pass(t)}o.items=!0;const p=t.name("valid");function m(){const e=t.name("_valid"),r=t.let("count",0);f(e,()=>t.if(e,()=>function(e){t.code(n._`${e}++`),void 0===d?t.if(n._`${e} >= ${c}`,()=>t.assign(p,!0).break()):(t.if(n._`${e} > ${d}`,()=>t.assign(p,!1).break()),1===c?t.assign(p,!0):t.if(n._`${e} >= ${c}`,()=>t.assign(p,!0)))}(r)))}function f(r,n){t.forRange("i",0,h,t=>{e.subschema({keyword:"contains",dataProp:t,dataPropType:s.Type.Num,compositeRule:!0},r),n()})}void 0===d&&1===c?f(p,()=>t.if(p,()=>t.break())):0===c?(t.let(p,!0),void 0!==d&&t.if(n._`${a}.length > 0`,m)):(t.let(p,!1),m()),e.result(p,()=>e.reset())}};t.default=i},3025(e,t,r){t.z3=void 0;const n=r(9029),s=r(4227),i=r(5765);t.z3={message:({params:{property:e,depsCount:t,deps:r}})=>{const s=1===t?"property":"properties";return n.str`must have ${s} ${r} when property ${e} is present`},params:({params:{property:e,depsCount:t,deps:r,missingProperty:s}})=>n._`{property: ${e}, missingProperty: ${s}, depsCount: ${t}, deps: ${r}}`};const a={keyword:"dependencies",type:"object",schemaType:"object",error:t.z3,code(e){const[t,r]=function({schema:e}){const t={},r={};for(const n in e)"__proto__"!==n&&((Array.isArray(e[n])?t:r)[n]=e[n]);return[t,r]}(e);(function(e,t=e.schema){const{gen:r,data:s,it:a}=e;if(0===Object.keys(t).length)return;const o=r.let("missing");for(const c in t){const d=t[c];if(0===d.length)continue;const l=(0,i.propertyInData)(r,s,c,a.opts.ownProperties);e.setParams({property:c,depsCount:d.length,deps:d.join(", ")}),a.allErrors?r.if(l,()=>{for(const t of d)(0,i.checkReportMissingProp)(e,t)}):(r.if(n._`${l} && (${(0,i.checkMissingProp)(e,d,o)})`),(0,i.reportMissingProp)(e,o),r.else())}})(e,t),function(e,t=e.schema){const{gen:r,data:n,keyword:a,it:o}=e,c=r.name("valid");for(const d in t)(0,s.alwaysValidSchema)(o,t[d])||(r.if((0,i.propertyInData)(r,n,d,o.opts.ownProperties),()=>{const t=e.subschema({keyword:a,schemaProp:d},c);e.mergeValidEvaluated(t,c)},()=>r.var(c,!0)),e.ok(c))}(e,r)}};t.default=a},1239(e,t,r){const n=r(9029),s=r(4227),i={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:{message:({params:e})=>n.str`must match "${e.ifClause}" schema`,params:({params:e})=>n._`{failingKeyword: ${e.ifClause}}`},code(e){const{gen:t,parentSchema:r,it:i}=e;void 0===r.then&&void 0===r.else&&(0,s.checkStrictMode)(i,'"if" without "then" and "else" is ignored');const o=a(i,"then"),c=a(i,"else");if(!o&&!c)return;const d=t.let("valid",!0),l=t.name("_valid");if(function(){const t=e.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},l);e.mergeEvaluated(t)}(),e.reset(),o&&c){const r=t.let("ifClause");e.setParams({ifClause:r}),t.if(l,u("then",r),u("else",r))}else o?t.if(l,u("then")):t.if((0,n.not)(l),u("else"));function u(r,s){return()=>{const i=e.subschema({keyword:r},l);t.assign(d,l),e.mergeValidEvaluated(i,d),s?t.assign(s,n._`${r}`):e.setParams({ifClause:r})}}e.pass(d,()=>e.error(!0))}};function a(e,t){const r=e.schema[t];return void 0!==r&&!(0,s.alwaysValidSchema)(e,r)}t.default=i},6378(e,t,r){const n=r(5457),s=r(5354),i=r(494),a=r(3966),o=r(2661),c=r(3025),d=r(9713),l=r(8660),u=r(117),h=r(5333),p=r(7923),m=r(6505),f=r(6163),g=r(5844),_=r(1239),y=r(4426);t.default=function(e=!1){const t=[p.default,m.default,f.default,g.default,_.default,y.default,d.default,l.default,c.default,u.default,h.default];return e?t.push(s.default,a.default):t.push(n.default,i.default),t.push(o.default),t}},494(e,t,r){t.validateTuple=void 0;const n=r(9029),s=r(4227),i=r(5765),a={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(e){const{schema:t,it:r}=e;if(Array.isArray(t))return o(e,"additionalItems",t);r.items=!0,(0,s.alwaysValidSchema)(r,t)||e.ok((0,i.validateArray)(e))}};function o(e,t,r=e.schema){const{gen:i,parentSchema:a,data:o,keyword:c,it:d}=e;!function(e){const{opts:n,errSchemaPath:i}=d,a=r.length,o=a===e.minItems&&(a===e.maxItems||!1===e[t]);if(n.strictTuples&&!o){const e=`"${c}" is ${a}-tuple, but minItems or maxItems/${t} are not specified or different at path "${i}"`;(0,s.checkStrictMode)(d,e,n.strictTuples)}}(a),d.opts.unevaluated&&r.length&&!0!==d.items&&(d.items=s.mergeEvaluated.items(i,r.length,d.items));const l=i.name("valid"),u=i.const("len",n._`${o}.length`);r.forEach((t,r)=>{(0,s.alwaysValidSchema)(d,t)||(i.if(n._`${u} > ${r}`,()=>e.subschema({keyword:c,schemaProp:r,dataProp:r},l)),e.ok(l))})}t.validateTuple=o,t.default=a},3966(e,t,r){const n=r(9029),s=r(4227),i=r(5765),a=r(5457),o={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:{message:({params:{len:e}})=>n.str`must NOT have more than ${e} items`,params:({params:{len:e}})=>n._`{limit: ${e}}`},code(e){const{schema:t,parentSchema:r,it:n}=e,{prefixItems:o}=r;n.items=!0,(0,s.alwaysValidSchema)(n,t)||(o?(0,a.validateAdditionalItems)(e,o):e.ok((0,i.validateArray)(e)))}};t.default=o},7923(e,t,r){const n=r(4227),s={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(e){const{gen:t,schema:r,it:s}=e;if((0,n.alwaysValidSchema)(s,r))return void e.fail();const i=t.name("valid");e.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},i),e.failResult(i,()=>e.reset(),()=>e.error())},error:{message:"must NOT be valid"}};t.default=s},6163(e,t,r){const n=r(9029),s=r(4227),i={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:{message:"must match exactly one schema in oneOf",params:({params:e})=>n._`{passingSchemas: ${e.passing}}`},code(e){const{gen:t,schema:r,parentSchema:i,it:a}=e;if(!Array.isArray(r))throw new Error("ajv implementation error");if(a.opts.discriminator&&i.discriminator)return;const o=r,c=t.let("valid",!1),d=t.let("passing",null),l=t.name("_valid");e.setParams({passing:d}),t.block(function(){o.forEach((r,i)=>{let o;(0,s.alwaysValidSchema)(a,r)?t.var(l,!0):o=e.subschema({keyword:"oneOf",schemaProp:i,compositeRule:!0},l),i>0&&t.if(n._`${l} && ${c}`).assign(c,!1).assign(d,n._`[${d}, ${i}]`).else(),t.if(l,()=>{t.assign(c,!0),t.assign(d,i),o&&e.mergeEvaluated(o,n.Name)})})}),e.result(c,()=>e.reset(),()=>e.error(!0))}};t.default=i},5333(e,t,r){const n=r(5765),s=r(9029),i=r(4227),a=r(4227),o={keyword:"patternProperties",type:"object",schemaType:"object",code(e){const{gen:t,schema:r,data:o,parentSchema:c,it:d}=e,{opts:l}=d,u=(0,n.allSchemaProperties)(r),h=u.filter(e=>(0,i.alwaysValidSchema)(d,r[e]));if(0===u.length||h.length===u.length&&(!d.opts.unevaluated||!0===d.props))return;const p=l.strictSchema&&!l.allowMatchingProperties&&c.properties,m=t.name("valid");!0===d.props||d.props instanceof s.Name||(d.props=(0,a.evaluatedPropsToName)(t,d.props));const{props:f}=d;function g(e){for(const t in p)new RegExp(e).test(t)&&(0,i.checkStrictMode)(d,`property ${t} matches pattern ${e} (use allowMatchingProperties)`)}function _(r){t.forIn("key",o,i=>{t.if(s._`${(0,n.usePattern)(e,r)}.test(${i})`,()=>{const n=h.includes(r);n||e.subschema({keyword:"patternProperties",schemaProp:r,dataProp:i,dataPropType:a.Type.Str},m),d.opts.unevaluated&&!0!==f?t.assign(s._`${f}[${i}]`,!0):n||d.allErrors||t.if((0,s.not)(m),()=>t.break())})})}!function(){for(const e of u)p&&g(e),d.allErrors?_(e):(t.var(m,!0),_(e),t.if(m))}()}};t.default=o},5354(e,t,r){const n=r(494),s={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:e=>(0,n.validateTuple)(e,"items")};t.default=s},117(e,t,r){const n=r(2586),s=r(5765),i=r(4227),a=r(8660),o={keyword:"properties",type:"object",schemaType:"object",code(e){const{gen:t,schema:r,parentSchema:o,data:c,it:d}=e;"all"===d.opts.removeAdditional&&void 0===o.additionalProperties&&a.default.code(new n.KeywordCxt(d,a.default,"additionalProperties"));const l=(0,s.allSchemaProperties)(r);for(const e of l)d.definedProperties.add(e);d.opts.unevaluated&&l.length&&!0!==d.props&&(d.props=i.mergeEvaluated.props(t,(0,i.toHash)(l),d.props));const u=l.filter(e=>!(0,i.alwaysValidSchema)(d,r[e]));if(0===u.length)return;const h=t.name("valid");for(const r of u)p(r)?m(r):(t.if((0,s.propertyInData)(t,c,r,d.opts.ownProperties)),m(r),d.allErrors||t.else().var(h,!0),t.endIf()),e.it.definedProperties.add(r),e.ok(h);function p(e){return d.opts.useDefaults&&!d.compositeRule&&void 0!==r[e].default}function m(t){e.subschema({keyword:"properties",schemaProp:t,dataProp:t},h)}}};t.default=o},9713(e,t,r){const n=r(9029),s=r(4227),i={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:{message:"property name must be valid",params:({params:e})=>n._`{propertyName: ${e.propertyName}}`},code(e){const{gen:t,schema:r,data:i,it:a}=e;if((0,s.alwaysValidSchema)(a,r))return;const o=t.name("valid");t.forIn("key",i,r=>{e.setParams({propertyName:r}),e.subschema({keyword:"propertyNames",data:r,dataTypes:["string"],propertyName:r,compositeRule:!0},o),t.if((0,n.not)(o),()=>{e.error(!0),a.allErrors||t.break()})}),e.ok(o)}};t.default=i},4426(e,t,r){const n=r(4227),s={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:e,parentSchema:t,it:r}){void 0===t.if&&(0,n.checkStrictMode)(r,`"${e}" without "if" is ignored`)}};t.default=s},5765(e,t,r){t.validateUnion=t.validateArray=t.usePattern=t.callValidateCode=t.allSchemaProperties=t.noPropertyInData=t.propertyInData=t.isOwnProperty=t.reportMissingProp=t.checkMissingProp=t.checkReportMissingProp=void 0;const n=r(9029),s=r(4227),i=r(2023),a=r(4227);function o(e,t,r){return n._`${function(e){return e.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:n._`Object.prototype.hasOwnProperty`})}(e)}.call(${t}, ${r})`}function c(e,t,r,s){const i=n._`${t}${(0,n.getProperty)(r)} === undefined`;return s?(0,n.or)(i,(0,n.not)(o(e,t,r))):i}t.checkReportMissingProp=function(e,t){const{gen:r,data:s,it:i}=e;r.if(c(r,s,t,i.opts.ownProperties),()=>{e.setParams({missingProperty:n._`${t}`},!0),e.error()})},t.checkMissingProp=function({gen:e,data:t,it:{opts:r}},s,i){return(0,n.or)(...s.map(s=>(0,n.and)(c(e,t,s,r.ownProperties),n._`${i} = ${s}`)))},t.reportMissingProp=function(e,t){e.setParams({missingProperty:t},!0),e.error()},t.isOwnProperty=o,t.propertyInData=function(e,t,r,s){const i=n._`${t}${(0,n.getProperty)(r)} !== undefined`;return s?n._`${i} && ${o(e,t,r)}`:i},t.noPropertyInData=c,t.allSchemaProperties=function(e){return e?Object.keys(e).filter(e=>"__proto__"!==e):[]},t.callValidateCode=function({schemaCode:e,data:t,it:{gen:r,topSchemaRef:s,schemaPath:a,errorPath:o},it:c},d,l,u){const h=u?n._`${e}, ${t}, ${s}${a}`:t,p=[[i.default.instancePath,(0,n.strConcat)(i.default.instancePath,o)],[i.default.parentData,c.parentData],[i.default.parentDataProperty,c.parentDataProperty],[i.default.rootData,i.default.rootData]];c.opts.dynamicRef&&p.push([i.default.dynamicAnchors,i.default.dynamicAnchors]);const m=n._`${h}, ${r.object(...p)}`;return l!==n.nil?n._`${d}.call(${l}, ${m})`:n._`${d}(${m})`};const d=n._`new RegExp`;t.usePattern=function({gen:e,it:{opts:t}},r){const s=t.unicodeRegExp?"u":"",{regExp:i}=t.code,o=i(r,s);return e.scopeValue("pattern",{key:o.toString(),ref:o,code:n._`${"new RegExp"===i.code?d:(0,a.useFunc)(e,i)}(${r}, ${s})`})},t.validateArray=function(e){const{gen:t,data:r,keyword:i,it:a}=e,o=t.name("valid");if(a.allErrors){const e=t.let("valid",!0);return c(()=>t.assign(e,!1)),e}return t.var(o,!0),c(()=>t.break()),o;function c(a){const c=t.const("len",n._`${r}.length`);t.forRange("i",0,c,r=>{e.subschema({keyword:i,dataProp:r,dataPropType:s.Type.Num},o),t.if((0,n.not)(o),a)})}},t.validateUnion=function(e){const{gen:t,schema:r,keyword:i,it:a}=e;if(!Array.isArray(r))throw new Error("ajv implementation error");if(r.some(e=>(0,s.alwaysValidSchema)(a,e))&&!a.opts.unevaluated)return;const o=t.let("valid",!1),c=t.name("_valid");t.block(()=>r.forEach((r,s)=>{const a=e.subschema({keyword:i,schemaProp:s,compositeRule:!0},c);t.assign(o,n._`${o} || ${c}`),e.mergeValidEvaluated(a,c)||t.if((0,n.not)(o))})),e.result(o,()=>e.reset(),()=>e.error(!0))}},3463(e,t){const r={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};t.default=r},2128(e,t,r){const n=r(3463),s=r(3693),i=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",n.default,s.default];t.default=i},3693(e,t,r){const n=r(4551),s=r(5765),i=r(9029),a=r(2023),o=r(3835),c=r(4227),d={keyword:"$ref",schemaType:"string",code(e){const{gen:t,schema:r,it:s}=e,{baseId:a,schemaEnv:c,validateName:d,opts:u,self:h}=s,{root:p}=c;if(("#"===r||"#/"===r)&&a===p.baseId)return function(){if(c===p)return l(e,d,c,c.$async);const r=t.scopeValue("root",{ref:p});return l(e,i._`${r}.validate`,p,p.$async)}();const m=o.resolveRef.call(h,p,a,r);if(void 0===m)throw new n.default(s.opts.uriResolver,a,r);return m instanceof o.SchemaEnv?function(t){const r=function(e,t){const{gen:r}=e;return t.validate?r.scopeValue("validate",{ref:t.validate}):i._`${r.scopeValue("wrapper",{ref:t})}.validate`}(e,t);l(e,r,t,t.$async)}(m):function(n){const s=t.scopeValue("schema",!0===u.code.source?{ref:n,code:(0,i.stringify)(n)}:{ref:n}),a=t.name("valid"),o=e.subschema({schema:n,dataTypes:[],schemaPath:i.nil,topSchemaRef:s,errSchemaPath:r},a);e.mergeEvaluated(o),e.ok(a)}(m)}};function l(e,t,r,n){const{gen:o,it:d}=e,{allErrors:l,schemaEnv:u,opts:h}=d,p=h.passContext?a.default.this:i.nil;function m(e){const t=i._`${e}.errors`;o.assign(a.default.vErrors,i._`${a.default.vErrors} === null ? ${t} : ${a.default.vErrors}.concat(${t})`),o.assign(a.default.errors,i._`${a.default.vErrors}.length`)}function f(e){var t;if(!d.opts.unevaluated)return;const n=null===(t=null==r?void 0:r.validate)||void 0===t?void 0:t.evaluated;if(!0!==d.props)if(n&&!n.dynamicProps)void 0!==n.props&&(d.props=c.mergeEvaluated.props(o,n.props,d.props));else{const t=o.var("props",i._`${e}.evaluated.props`);d.props=c.mergeEvaluated.props(o,t,d.props,i.Name)}if(!0!==d.items)if(n&&!n.dynamicItems)void 0!==n.items&&(d.items=c.mergeEvaluated.items(o,n.items,d.items));else{const t=o.var("items",i._`${e}.evaluated.items`);d.items=c.mergeEvaluated.items(o,t,d.items,i.Name)}}n?function(){if(!u.$async)throw new Error("async schema referenced by sync schema");const r=o.let("valid");o.try(()=>{o.code(i._`await ${(0,s.callValidateCode)(e,t,p)}`),f(t),l||o.assign(r,!0)},e=>{o.if(i._`!(${e} instanceof ${d.ValidationError})`,()=>o.throw(e)),m(e),l||o.assign(r,!1)}),e.ok(r)}():e.result((0,s.callValidateCode)(e,t,p),()=>f(t),()=>m(t))}t.default=d},6653(e,t,r){const n=r(9029),s=r(7652),i=r(3835),a=r(4551),o=r(4227),c={keyword:"discriminator",type:"object",schemaType:"object",error:{message:({params:{discrError:e,tagName:t}})=>e===s.DiscrError.Tag?`tag "${t}" must be string`:`value of tag "${t}" must be in oneOf`,params:({params:{discrError:e,tag:t,tagName:r}})=>n._`{error: ${e}, tag: ${r}, tagValue: ${t}}`},code(e){const{gen:t,data:r,schema:c,parentSchema:d,it:l}=e,{oneOf:u}=d;if(!l.opts.discriminator)throw new Error("discriminator: requires discriminator option");const h=c.propertyName;if("string"!=typeof h)throw new Error("discriminator: requires propertyName");if(c.mapping)throw new Error("discriminator: mapping is not supported");if(!u)throw new Error("discriminator: requires oneOf keyword");const p=t.let("valid",!1),m=t.const("tag",n._`${r}${(0,n.getProperty)(h)}`);function f(r){const s=t.name("valid"),i=e.subschema({keyword:"oneOf",schemaProp:r},s);return e.mergeEvaluated(i,n.Name),s}t.if(n._`typeof ${m} == "string"`,()=>function(){const r=function(){var e;const t={},r=s(d);let n=!0;for(let t=0;t<u.length;t++){let d=u[t];if((null==d?void 0:d.$ref)&&!(0,o.schemaHasRulesButRef)(d,l.self.RULES)){const e=d.$ref;if(d=i.resolveRef.call(l.self,l.schemaEnv.root,l.baseId,e),d instanceof i.SchemaEnv&&(d=d.schema),void 0===d)throw new a.default(l.opts.uriResolver,l.baseId,e)}const p=null===(e=null==d?void 0:d.properties)||void 0===e?void 0:e[h];if("object"!=typeof p)throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${h}"`);n=n&&(r||s(d)),c(p,t)}if(!n)throw new Error(`discriminator: "${h}" must be required`);return t;function s({required:e}){return Array.isArray(e)&&e.includes(h)}function c(e,t){if(e.const)p(e.const,t);else{if(!e.enum)throw new Error(`discriminator: "properties/${h}" must have "const" or "enum"`);for(const r of e.enum)p(r,t)}}function p(e,r){if("string"!=typeof e||e in t)throw new Error(`discriminator: "${h}" values must be unique strings`);t[e]=r}}();t.if(!1);for(const e in r)t.elseIf(n._`${m} === ${e}`),t.assign(p,f(r[e]));t.else(),e.error(!1,{discrError:s.DiscrError.Mapping,tag:m,tagName:h}),t.endIf()}(),()=>e.error(!1,{discrError:s.DiscrError.Tag,tag:m,tagName:h})),e.ok(p)}};t.default=c},7652(e,t){var r;t.DiscrError=void 0,function(e){e.Tag="tag",e.Mapping="mapping"}(r||(t.DiscrError=r={}))},6144(e,t,r){const n=r(2128),s=r(7060),i=r(6378),a=r(7532),o=r(9857),c=[n.default,s.default,(0,i.default)(),a.default,o.metadataVocabulary,o.contentVocabulary];t.default=c},4737(e,t,r){const n=r(9029),s={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:{message:({schemaCode:e})=>n.str`must match format "${e}"`,params:({schemaCode:e})=>n._`{format: ${e}}`},code(e,t){const{gen:r,data:s,$data:i,schema:a,schemaCode:o,it:c}=e,{opts:d,errSchemaPath:l,schemaEnv:u,self:h}=c;d.validateFormats&&(i?function(){const i=r.scopeValue("formats",{ref:h.formats,code:d.code.formats}),a=r.const("fDef",n._`${i}[${o}]`),c=r.let("fType"),l=r.let("format");r.if(n._`typeof ${a} == "object" && !(${a} instanceof RegExp)`,()=>r.assign(c,n._`${a}.type || "string"`).assign(l,n._`${a}.validate`),()=>r.assign(c,n._`"string"`).assign(l,a)),e.fail$data((0,n.or)(!1===d.strictSchema?n.nil:n._`${o} && !${l}`,function(){const e=u.$async?n._`(${a}.async ? await ${l}(${s}) : ${l}(${s}))`:n._`${l}(${s})`,r=n._`(typeof ${l} == "function" ? ${e} : ${l}.test(${s}))`;return n._`${l} && ${l} !== true && ${c} === ${t} && !${r}`}()))}():function(){const i=h.formats[a];if(!i)return void function(){if(!1!==d.strictSchema)throw new Error(e());function e(){return`unknown format "${a}" ignored in schema at path "${l}"`}h.logger.warn(e())}();if(!0===i)return;const[o,c,p]=function(e){const t=e instanceof RegExp?(0,n.regexpCode)(e):d.code.formats?n._`${d.code.formats}${(0,n.getProperty)(a)}`:void 0,s=r.scopeValue("formats",{key:a,ref:e,code:t});return"object"!=typeof e||e instanceof RegExp?["string",e,s]:[e.type||"string",e.validate,n._`${s}.validate`]}(i);o===t&&e.pass(function(){if("object"==typeof i&&!(i instanceof RegExp)&&i.async){if(!u.$async)throw new Error("async format in sync schema");return n._`await ${p}(${s})`}return"function"==typeof c?n._`${p}(${s})`:n._`${p}.test(${s})`}())}())}};t.default=s},7532(e,t,r){const n=[r(4737).default];t.default=n},9857(e,t){t.contentVocabulary=t.metadataVocabulary=void 0,t.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"],t.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]},7935(e,t,r){const n=r(9029),s=r(4227),i=r(6250),a={keyword:"const",$data:!0,error:{message:"must be equal to constant",params:({schemaCode:e})=>n._`{allowedValue: ${e}}`},code(e){const{gen:t,data:r,$data:a,schemaCode:o,schema:c}=e;a||c&&"object"==typeof c?e.fail$data(n._`!${(0,s.useFunc)(t,i.default)}(${r}, ${o})`):e.fail(n._`${c} !== ${r}`)}};t.default=a},8643(e,t,r){const n=r(9029),s=r(4227),i=r(6250),a={keyword:"enum",schemaType:"array",$data:!0,error:{message:"must be equal to one of the allowed values",params:({schemaCode:e})=>n._`{allowedValues: ${e}}`},code(e){const{gen:t,data:r,$data:a,schema:o,schemaCode:c,it:d}=e;if(!a&&0===o.length)throw new Error("enum must have non-empty array");const l=o.length>=d.opts.loopEnum;let u;const h=()=>null!=u?u:u=(0,s.useFunc)(t,i.default);let p;if(l||a)p=t.let("valid"),e.block$data(p,function(){t.assign(p,!1),t.forOf("v",c,e=>t.if(n._`${h()}(${r}, ${e})`,()=>t.assign(p,!0).break()))});else{if(!Array.isArray(o))throw new Error("ajv implementation error");const e=t.const("vSchema",c);p=(0,n.or)(...o.map((t,s)=>function(e,t){const s=o[t];return"object"==typeof s&&null!==s?n._`${h()}(${r}, ${e}[${t}])`:n._`${r} === ${s}`}(e,s)))}e.pass(p)}};t.default=a},7060(e,t,r){const n=r(5882),s=r(3439),i=r(7307),a=r(422),o=r(4486),c=r(4003),d=r(1163),l=r(617),u=r(7935),h=r(8643),p=[n.default,s.default,i.default,a.default,o.default,c.default,d.default,l.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},u.default,h.default];t.default=p},1163(e,t,r){const n=r(9029),s={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:{message({keyword:e,schemaCode:t}){const r="maxItems"===e?"more":"fewer";return n.str`must NOT have ${r} than ${t} items`},params:({schemaCode:e})=>n._`{limit: ${e}}`},code(e){const{keyword:t,data:r,schemaCode:s}=e,i="maxItems"===t?n.operators.GT:n.operators.LT;e.fail$data(n._`${r}.length ${i} ${s}`)}};t.default=s},7307(e,t,r){const n=r(9029),s=r(4227),i=r(3853),a={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:{message({keyword:e,schemaCode:t}){const r="maxLength"===e?"more":"fewer";return n.str`must NOT have ${r} than ${t} characters`},params:({schemaCode:e})=>n._`{limit: ${e}}`},code(e){const{keyword:t,data:r,schemaCode:a,it:o}=e,c="maxLength"===t?n.operators.GT:n.operators.LT,d=!1===o.opts.unicode?n._`${r}.length`:n._`${(0,s.useFunc)(e.gen,i.default)}(${r})`;e.fail$data(n._`${d} ${c} ${a}`)}};t.default=a},5882(e,t,r){const n=r(9029),s=n.operators,i={maximum:{okStr:"<=",ok:s.LTE,fail:s.GT},minimum:{okStr:">=",ok:s.GTE,fail:s.LT},exclusiveMaximum:{okStr:"<",ok:s.LT,fail:s.GTE},exclusiveMinimum:{okStr:">",ok:s.GT,fail:s.LTE}},a={message:({keyword:e,schemaCode:t})=>n.str`must be ${i[e].okStr} ${t}`,params:({keyword:e,schemaCode:t})=>n._`{comparison: ${i[e].okStr}, limit: ${t}}`},o={keyword:Object.keys(i),type:"number",schemaType:"number",$data:!0,error:a,code(e){const{keyword:t,data:r,schemaCode:s}=e;e.fail$data(n._`${r} ${i[t].fail} ${s} || isNaN(${r})`)}};t.default=o},4486(e,t,r){const n=r(9029),s={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:{message({keyword:e,schemaCode:t}){const r="maxProperties"===e?"more":"fewer";return n.str`must NOT have ${r} than ${t} properties`},params:({schemaCode:e})=>n._`{limit: ${e}}`},code(e){const{keyword:t,data:r,schemaCode:s}=e,i="maxProperties"===t?n.operators.GT:n.operators.LT;e.fail$data(n._`Object.keys(${r}).length ${i} ${s}`)}};t.default=s},3439(e,t,r){const n=r(9029),s={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:{message:({schemaCode:e})=>n.str`must be multiple of ${e}`,params:({schemaCode:e})=>n._`{multipleOf: ${e}}`},code(e){const{gen:t,data:r,schemaCode:s,it:i}=e,a=i.opts.multipleOfPrecision,o=t.let("res"),c=a?n._`Math.abs(Math.round(${o}) - ${o}) > 1e-${a}`:n._`${o} !== parseInt(${o})`;e.fail$data(n._`(${s} === 0 || (${o} = ${r}/${s}, ${c}))`)}};t.default=s},422(e,t,r){const n=r(5765),s=r(4227),i=r(9029),a={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:{message:({schemaCode:e})=>i.str`must match pattern "${e}"`,params:({schemaCode:e})=>i._`{pattern: ${e}}`},code(e){const{gen:t,data:r,$data:a,schema:o,schemaCode:c,it:d}=e,l=d.opts.unicodeRegExp?"u":"";if(a){const{regExp:n}=d.opts.code,a="new RegExp"===n.code?i._`new RegExp`:(0,s.useFunc)(t,n),o=t.let("valid");t.try(()=>t.assign(o,i._`${a}(${c}, ${l}).test(${r})`),()=>t.assign(o,!1)),e.fail$data(i._`!${o}`)}else{const t=(0,n.usePattern)(e,o);e.fail$data(i._`!${t}.test(${r})`)}}};t.default=a},4003(e,t,r){const n=r(5765),s=r(9029),i=r(4227),a={keyword:"required",type:"object",schemaType:"array",$data:!0,error:{message:({params:{missingProperty:e}})=>s.str`must have required property '${e}'`,params:({params:{missingProperty:e}})=>s._`{missingProperty: ${e}}`},code(e){const{gen:t,schema:r,schemaCode:a,data:o,$data:c,it:d}=e,{opts:l}=d;if(!c&&0===r.length)return;const u=r.length>=l.loopRequired;if(d.allErrors?function(){if(u||c)e.block$data(s.nil,h);else for(const t of r)(0,n.checkReportMissingProp)(e,t)}():function(){const i=t.let("missing");if(u||c){const r=t.let("valid",!0);e.block$data(r,()=>function(r,i){e.setParams({missingProperty:r}),t.forOf(r,a,()=>{t.assign(i,(0,n.propertyInData)(t,o,r,l.ownProperties)),t.if((0,s.not)(i),()=>{e.error(),t.break()})},s.nil)}(i,r)),e.ok(r)}else t.if((0,n.checkMissingProp)(e,r,i)),(0,n.reportMissingProp)(e,i),t.else()}(),l.strictRequired){const t=e.parentSchema.properties,{definedProperties:n}=e.it;for(const e of r)if(void 0===(null==t?void 0:t[e])&&!n.has(e)){const t=`required property "${e}" is not defined at "${d.schemaEnv.baseId+d.errSchemaPath}" (strictRequired)`;(0,i.checkStrictMode)(d,t,d.opts.strictRequired)}}function h(){t.forOf("prop",a,r=>{e.setParams({missingProperty:r}),t.if((0,n.noPropertyInData)(t,o,r,l.ownProperties),()=>e.error())})}}};t.default=a},617(e,t,r){const n=r(208),s=r(9029),i=r(4227),a=r(6250),o={message:({params:{i:e,j:t}})=>s.str`must NOT have duplicate items (items ## ${t} and ${e} are identical)`,params:({params:{i:e,j:t}})=>s._`{i: ${e}, j: ${t}}`},c={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:o,code(e){const{gen:t,data:r,$data:o,schema:c,parentSchema:d,schemaCode:l,it:u}=e;if(!o&&!c)return;const h=t.let("valid"),p=d.items?(0,n.getSchemaTypes)(d.items):[];function m(i,a){const o=t.name("item"),c=(0,n.checkDataTypes)(p,o,u.opts.strictNumbers,n.DataType.Wrong),d=t.const("indices",s._`{}`);t.for(s._`;${i}--;`,()=>{t.let(o,s._`${r}[${i}]`),t.if(c,s._`continue`),p.length>1&&t.if(s._`typeof ${o} == "string"`,s._`${o} += "_"`),t.if(s._`typeof ${d}[${o}] == "number"`,()=>{t.assign(a,s._`${d}[${o}]`),e.error(),t.assign(h,!1).break()}).code(s._`${d}[${o}] = ${i}`)})}function f(n,o){const c=(0,i.useFunc)(t,a.default),d=t.name("outer");t.label(d).for(s._`;${n}--;`,()=>t.for(s._`${o} = ${n}; ${o}--;`,()=>t.if(s._`${c}(${r}[${n}], ${r}[${o}])`,()=>{e.error(),t.assign(h,!1).break(d)})))}e.block$data(h,function(){const n=t.let("i",s._`${r}.length`),i=t.let("j");e.setParams({i:n,j:i}),t.assign(h,!0),t.if(s._`${n} > 1`,()=>(p.length>0&&!p.some(e=>"object"===e||"array"===e)?m:f)(n,i))},s._`${l} === false`),e.ok(h)}};t.default=c},2017(e){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 n,s,i;if(Array.isArray(t)){if((n=t.length)!=r.length)return!1;for(s=n;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((n=(i=Object.keys(t)).length)!==Object.keys(r).length)return!1;for(s=n;0!==s--;)if(!Object.prototype.hasOwnProperty.call(r,i[s]))return!1;for(s=n;0!==s--;){var a=i[s];if(!e(t[a],r[a]))return!1}return!0}return t!=t&&r!=r}},7106(e){var t=e.exports=function(e,t,n){"function"==typeof t&&(n=t,t={}),r(t,"function"==typeof(n=t.cb||n)?n:n.pre||function(){},n.post||function(){},e,"",e)};function r(e,s,i,a,o,c,d,l,u,h){if(a&&"object"==typeof a&&!Array.isArray(a)){for(var p in s(a,o,c,d,l,u,h),a){var m=a[p];if(Array.isArray(m)){if(p in t.arrayKeywords)for(var f=0;f<m.length;f++)r(e,s,i,m[f],o+"/"+p+"/"+f,c,o,p,a,f)}else if(p in t.propsKeywords){if(m&&"object"==typeof m)for(var g in m)r(e,s,i,m[g],o+"/"+p+"/"+n(g),c,o,p,a,g)}else(p in t.keywords||e.allKeys&&!(p in t.skipKeywords))&&r(e,s,i,m,o+"/"+p,c,o,p,a)}i(a,o,c,d,l,u,h)}}function n(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}t.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0},t.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0},t.propsKeywords={$defs:!0,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}},8343(e,t,r){const{normalizeIPv6:n,removeDotSegments:s,removeDotSegmentsRelative:i,recomposeAuthority:a,normalizePercentEncoding:o,normalizePathEncoding:c,serializePathEncoding:d,normalizeQueryFragmentEncoding:l,encodeQuery:u,encodeFragment:h,reescapeHostDelimiters:p,isIPv4:m,nonSimpleDomain:f}=r(4834),{SCHEMES:g,getSchemeHandler:_}=r(343),y=/^[A-Za-z][A-Za-z0-9+.-]*$/u,w="URI scheme is malformed.",v="URI host is malformed.",b=/[\0-\x20"#/:<>?@[\\\]^`{|}\x7F]/u;function k(e){const t=String(e);if(!y.test(t))throw new TypeError(w);return t}function S(e,t,r,n){const a={};if(n||(e=O($(e,r),r),t=O($(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=s(t.path||""),a.query=t.query;else{if(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=s(t.path||""),a.query=t.query;else{if(t.path){if("/"===t.path[0])a.path=s(t.path);else{const r=void 0!==e.userinfo||void 0!==e.host||void 0!==e.port;r&&!e.path?a.path="/"+t.path:e.path?a.path=e.path.slice(0,e.path.lastIndexOf("/")+1)+t.path:a.path=t.path,a.path=void 0!==e.scheme||r||"/"===a.path[0]?s(a.path):i(a.path)}a.query=t.query}else 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}return a.fragment=t.fragment,a}function $(e,t){const r={host:e.host,scheme:e.scheme,userinfo:e.userinfo,port:e.port,path:e.path,query:e.query,nid:e.nid,nss:e.nss,uuid:e.uuid,fragment:e.fragment,reference:e.reference,resourceName:e.resourceName,secure:e.secure,error:""},n=Object.assign({},t),c=[];r.scheme&&(r.scheme=k(r.scheme));const l=_(n.scheme||r.scheme);l&&l.serialize&&l.serialize(r,n);const p=void 0!==r.userinfo||void 0!==r.host||void 0!==r.port,m=(void 0===r.scheme||"suffix"===n.reference)&&!p,f=!n.skipEscape&&m;void 0!==r.path&&(n.skipEscape?r.path=o(r.path):r.path=d(r.path,f)),"suffix"!==n.reference&&r.scheme&&(r.scheme=k(r.scheme),c.push(r.scheme,":"));const g=a(r);if(void 0!==g&&("suffix"!==n.reference&&c.push("//"),c.push(g),r.path&&"/"!==r.path[0]&&c.push("/")),void 0!==r.path){let e=r.path;n.absolutePath||l&&l.absolutePath||(e=m&&"/"!==e[0]?i(e):s(e)),m&&(e=d(e,!0)),void 0===g&&"/"===e[0]&&"/"===e[1]&&(e="/%2F"+e.slice(2)),c.push(e)}return void 0!==r.query&&c.push("?",u(r.query)),void 0!==r.fragment&&c.push("#",h(r.fragment)),c.join("")}const E=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u,T=/^(?:[^#/:?]+:)?\/\/([^/?#]*)/,I=/^(?:[^#/:?]+:)?([/\\\t\n\r]*)/;function x(e){if(void 0===e)return!1;let t=e.indexOf("%");for(;-1!==t;){if(t+2>=e.length||!/^[\da-f]{2}$/iu.test(e.slice(t+1,t+3)))return!0;t=e.indexOf("%",t+3)}return!1}function P(e){return"["===e[0]&&"]"===e[e.length-1]}function C(e,t,r,n){if(R(e,t,r,n))return e.error=e.error||v,!0;if(!t.unicodeSupport&&(!r||!r.unicodeSupport)&&e.host&&!P(e.host)&&(t.domainHost||r&&r.domainHost)&&!1===n&&f(e.host)){let t;try{t=new URL("http://"+e.host)}catch(t){return e.error=e.error||"Host's domain name can not be converted to ASCII: "+t,!0}if(!function(e){return""===e.username&&""===e.password&&""===e.port&&"/"===e.pathname&&""===e.search&&""===e.hash&&""!==e.hostname}(t))return e.error=e.error||v,!0;e.host=t.hostname}return!1}function R(e,t,r,n){return Boolean(e.host&&!1===n&&!P(e.host)&&(t.domainHost||r&&r.domainHost)&&b.test(e.host))}function A(e,t){const r=Object.assign({},t),s={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0};let i=!1,a=!1,d=!1,u=!1,h=!1,f=!1,b=!1;"suffix"===r.reference&&(e=r.scheme?r.scheme+":"+e:"//"+e);const k=e.match(T);null!==k&&-1!==k[1].indexOf("\\")&&(s.error="URI authority must not contain a literal backslash.",i=!0);const S=e.match(I);if(null!==S){const e=S[1],t=e.replace(/[\t\n\r]/g,"");t.length>=2&&("//"!==t.slice(0,2)?(s.error=s.error||"URI authority must not contain a literal backslash.",i=!0):e.length!==t.length&&(s.error=s.error||"URI authority introducer must not contain whitespace.",i=!0))}const $=e.match(E);if($){s.scheme=$[1],s.userinfo=$[3],s.host=$[4],s.port=parseInt($[5],10),s.path=$[6]||"",s.query=$[7],s.fragment=$[8],void 0!==s.scheme&&(y.test(s.scheme)?s.scheme=s.scheme.toLowerCase():(s.error=s.error||w,f=!0)),a=function(e){const t=e[4];return x(e[3])||void 0!==t&&!P(t)&&x(t)||x(e[6])||x(e[7])||x(e[8])}($),a&&(s.error=s.error||"URI contains malformed percent-encoding."),isNaN(s.port)&&(s.port=$[5]);const t=function(e,t){return void 0!==t[2]&&e.path&&"/"!==e.path[0]?'URI path must start with "/" when authority is present.':"number"==typeof e.port&&(e.port<0||e.port>65535)?"URI port is malformed.":void 0}(s,$);if(void 0!==t&&(s.error=s.error||t,i=!0),s.host)if(!1===m(s.host)){const e=P(s.host),t=-1!==s.host.indexOf("[")||-1!==s.host.indexOf("]"),r=n(s.host);b=r.isIPV6||!0===r.isIPVFuture,h=t&&(!e||!0===r.error),s.host=b?r.host:r.host.toLowerCase(),h&&(s.error=s.error||v,i=!0)}else b=!0;void 0!==s.scheme||void 0!==s.userinfo||void 0!==s.host||void 0!==s.port||void 0!==s.query||s.path?void 0===s.scheme?s.reference="relative":void 0===s.fragment?s.reference="absolute":s.reference="uri":s.reference="same-document",r.reference&&"suffix"!==r.reference&&r.reference!==s.reference&&(s.error=s.error||"URI is not a "+r.reference+" reference.");const k=_(r.scheme||s.scheme);if(h||(u=C(s,r,k,b)),-1!==e.indexOf("%")&&void 0!==s.host&&!h){let e=b?s.host:o(s.host,!0);b||(e=o(e.toLowerCase())),s.host=b||"null"!==r.scheme?p(e,b):e}(!k||k&&!k.skipNormalize)&&(s.path&&(s.path=c(s.path)),s.query&&(s.query=l(s.query)),s.fragment&&(s.fragment=l(s.fragment))),k&&k.parse&&(k.parse(s,r),k===g.urn&&void 0===s.nid&&(d=!0))}else s.error=s.error||"URI can not be parsed.";return{parsed:s,malformedAuthorityOrPort:i,malformedPercentEncoding:a,malformedSchemeSpecific:d,malformedHost:u,malformedScheme:f}}function O(e,t){return A(e,t).parsed}function N(e,t){const{parsed:r,malformedAuthorityOrPort:n,malformedPercentEncoding:s,malformedSchemeSpecific:i,malformedHost:a,malformedScheme:o}=A(e,t);return{normalized:n||s||i||a||o?e:$(r,t),malformedAuthorityOrPort:n,malformedPercentEncoding:s,malformedSchemeSpecific:i,malformedHost:a,malformedScheme:o}}function z(e,t){if("string"!=typeof e&&"object"!=typeof e)return;let r;try{r="string"==typeof e?e:$(e,t)}catch{return}const{normalized:n,malformedAuthorityOrPort:s,malformedPercentEncoding:i,malformedSchemeSpecific:a,malformedHost:o,malformedScheme:c}=N(r,t);return s||i||a||o||c?void 0:n}const j={SCHEMES:g,normalize:function(e,t){return"string"==typeof e?e=function(e,t){return N(e,t).normalized}(e,t):"object"==typeof e&&(e=O($(e,t),t)),e},resolve:function(e,t,r){const s=r?Object.assign({scheme:"null"},r):{scheme:"null"},{parsed:i,malformedAuthorityOrPort:a,malformedPercentEncoding:o,malformedSchemeSpecific:c,malformedHost:d,malformedScheme:l}=A(e,s),{parsed:u,malformedAuthorityOrPort:h,malformedPercentEncoding:p,malformedSchemeSpecific:f,malformedHost:g,malformedScheme:y}=A(t,s);if(a||h||o||p||c||f||d||g||l||y)throw new Error(i.error||u.error||"URI is malformed.");const w=S(i,u,s,!0),b=_(r&&r.scheme||w.scheme),k=w.host,E=void 0!==k&&""!==k&&(m(k)||n(k).isIPV6);if(R(w,r||{},b,E))throw new Error(v);C(w,r||{},b,E);const T=k&&-1!==k.indexOf("%")&&!/\P{ASCII}/u.test(k);if(w.error&&!T)throw new Error(w.error);return s.skipEscape=!0,$(w,s)},resolveComponent:S,equal:function(e,t,r){const n=z(e,r),s=z(t,r);return void 0!==n&&void 0!==s&&n===s},serialize:$,parse:O};e.exports=j,e.exports.default=j,e.exports.fastUri=j},343(e,t,r){const{isUUID:n}=r(4834),s=/^([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-./:;=@]|%[\da-f]{2})+)$/iu,i=["http","https","ws","wss","urn","urn:uuid"];function a(e){return!0===e.secure||!1!==e.secure&&!!e.scheme&&!(3!==e.scheme.length||"w"!==e.scheme[0]&&"W"!==e.scheme[0]||"s"!==e.scheme[1]&&"S"!==e.scheme[1]||"s"!==e.scheme[2]&&"S"!==e.scheme[2])}function o(e){return e.host||(e.error=e.error||"HTTP URIs must have a host."),e}function c(e){const t="https"===String(e.scheme).toLowerCase();return e.port!==(t?443:80)&&""!==e.port||(e.port=void 0),e.path||(e.path="/"),e}const d={scheme:"http",domainHost:!0,parse:o,serialize:c},l={scheme:"ws",domainHost:!0,parse:function(e){return e.secure=a(e),e.resourceName=(e.path||"/")+(e.query?"?"+e.query:""),e.path=void 0,e.query=void 0,e},serialize:function(e){if(e.port!==(a(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){const t=e.resourceName.indexOf("?"),r=-1===t?e.resourceName:e.resourceName.slice(0,t);e.path=r&&"/"!==r?r:void 0,e.query=-1===t?void 0:e.resourceName.slice(t+1),e.resourceName=void 0}return e.fragment=void 0,e}},u={http:d,https:{scheme:"https",domainHost:d.domainHost,parse:o,serialize:c},ws:l,wss:{scheme:"wss",domainHost:l.domainHost,parse:l.parse,serialize:l.serialize},urn:{scheme:"urn",parse:function(e,t){if(!e.path)return e.error="URN can not be parsed",e;const r=e.path.match(s);if(r&&r[0]===e.path){const n=t.scheme||e.scheme||"urn";e.nid=r[1].toLowerCase(),e.nss=r[2];const s=h(`${n}:${t.nid||e.nid}`);e.path=void 0,s&&(e=s.parse(e,t))}else e.error=e.error||"URN can not be parsed.";return e},serialize:function(e,t){if(void 0===e.nid)throw new Error("URN without nid cannot be serialized");const r=t.scheme||e.scheme||"urn",n=e.nid.toLowerCase(),s=h(`${r}:${t.nid||n}`);s&&(e=s.serialize(e,t));const i=e,a=e.nss;return i.path=`${n||t.nid}:${a}`,t.skipEscape=!0,i},skipNormalize:!0},"urn:uuid":{scheme:"urn:uuid",parse:function(e,t){const r=e;return r.uuid=r.nss,r.nss=void 0,t.tolerant||r.uuid&&n(r.uuid)||(r.error=r.error||"UUID is not valid."),r},serialize:function(e){const t=e;return t.nss=(e.uuid||"").toLowerCase(),t},skipNormalize:!0}};function h(e){return e&&(u[e]||u[e.toLowerCase()])||void 0}Object.setPrototypeOf(u,null),e.exports={wsIsSecure:a,SCHEMES:u,isValidSchemeName:function(e){return-1!==i.indexOf(e)},getSchemeHandler:h}},4834(e){const t=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),r=RegExp.prototype.test.bind(/^(?:(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)$/u),n=RegExp.prototype.test.bind(/^\d*$/u),s=RegExp.prototype.test.bind(/^[\da-f]{2}$/iu),i=RegExp.prototype.test.bind(/^[\da-z\-._~]$/iu),a=RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:@/]$/u),o=RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:@/?]$/u),c=RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:]$/u),d=new Array(256);{const e="0123456789ABCDEF";for(let t=0;t<256;t++)d[t]="%"+e[t>>4]+e[15&t]}function l(e){return e<2048?d[192|e>>6]+d[128|63&e]:e<65536?d[224|e>>12]+d[128|e>>6&63]+d[128|63&e]:d[240|e>>18]+d[128|e>>12&63]+d[128|e>>6&63]+d[128|63&e]}const u=RegExp.prototype.test.bind(/^[\dA-Fa-f]{1,4}$/),h=RegExp.prototype.test.bind(/^[vV][\dA-Fa-f]+\.[A-Za-z\d\-._~!$&'()*+,;=:]+$/),p=RegExp.prototype.test.bind(/^[A-Za-z\d\-._~]$/),m=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function f(e){let t=-1,r=0,n=-1,s=0;for(let i=0;i<e.length;i++)"0"===e[i]?(-1===n&&(n=i),s++,s>r&&(r=s,t=n)):(n=-1,s=0);return r<2?e.join(":"):e.slice(0,t).join(":")+"::"+e.slice(t+r).join(":")}function g(e){const t="["===e[0]&&"]"===e[e.length-1];if(("["===e[0]||"]"===e[e.length-1])&&!t)return{host:e,isIPV6:!1,error:!0};let n=t?e.slice(1,-1):e;if(t&&h(n))return n=n.toLowerCase(),{host:`[${n}]`,escapedHost:n,isIPV6:!1,isIPVFuture:!0};if(function(e){let t=0;for(let r=0;r<e.length;r++)":"===e[r]&&t++;return t}(n)<2)return{host:e,isIPV6:!1,error:t};let i="";const a=n.indexOf("%");if(-1!==a){const t="%25"===n.slice(a,a+3).toLowerCase()?3:1;if(i=n.slice(a+t),!function(e){if(0===e.length)return!1;for(let t=0;t<e.length;t++)if(!p(e[t])){if(!("%"===e[t]&&t+2<e.length&&s(e.slice(t+1,t+3))))return!1;t+=2}return!0}(i))return{host:e,isIPV6:!1,error:!0};n=n.slice(0,a)}const o=function(e){const t=e.indexOf("::");if(-1!==t&&-1!==e.indexOf("::",t+1))return;const n=-1===t?e.split(":"):e.slice(0,t).split(":"),s=-1===t?[]:e.slice(t+2).split(":");-1!==t&&(1===n.length&&""===n[0]&&(n.length=0),1===s.length&&""===s[0]&&(s.length=0));const i=n.concat(s);let a=0;for(let e=0;e<i.length;e++){const n=i[e];if(""===n)return;if(-1===n.indexOf(".")){if(!u(n))return;i[e]=parseInt(n,16).toString(16),a++}else{if(e!==i.length-1||-1!==t&&0===s.length||!r(n))return;a+=2}}if(-1===t){if(8!==a)return;return f(i)}if(a>=8)return;const o=i.slice(0,n.length);for(let e=a;e<8;e++)o.push("0");for(let e=n.length;e<i.length;e++)o.push(i[e]);return f(o)}(n);return void 0===o?{host:e,isIPV6:!1,error:!0}:{host:o+(i?"%"+i:""),escapedHost:o+(i?"%25"+i:""),isIPV6:!0}}function _(e){let t=e;const r=[];let n=-1,s=0;for(;s=t.length;){if(1===s){if("."===t)break;if("/"===t){r.push("/");break}r.push(t);break}if(2===s){if("."===t[0]){if("."===t[1])break;if("/"===t[1]){t=t.slice(2);continue}}else if("/"===t[0]&&("."===t[1]||"/"===t[1])){r.push("/");break}}else if(3===s&&"/.."===t){0!==r.length&&r.pop(),r.push("/");break}if("."===t[0]){if("."===t[1]){if("/"===t[2]){t=t.slice(3);continue}}else if("/"===t[1]){t=t.slice(2);continue}}else if("/"===t[0]&&"."===t[1]){if("/"===t[2]){t=t.slice(2);continue}if("."===t[2]&&"/"===t[3]){t=t.slice(3),0!==r.length&&r.pop();continue}}if(-1===(n=t.indexOf("/",1))){r.push(t);break}r.push(t.slice(0,n)),t=t.slice(n)}return r.join("")}const y={"@":"%40","/":"%2F","?":"%3F","#":"%23",":":"%3A"},w=/[@/?#:]/g,v=/[@/?#]/g;function b(e,t){const r=t?v:w;return r.lastIndex=0,e.replace(r,e=>y[e])}function k(e,t=!1){if(-1===e.indexOf("%"))return e;let r="";for(let n=0;n<e.length;n++){if("%"===e[n]&&n+2<e.length){const a=e.slice(n+1,n+3);if(s(a)){const e=a.toUpperCase(),s=String.fromCharCode(parseInt(e,16));t&&i(s)?r+=s:r+="%"+e,n+=2;continue}}r+=e[n]}return r}function S(e,t){let r="";for(let n=0;n<e.length;n++){const i=e[n];if("%"===i&&n+2<e.length){const t=e.slice(n+1,n+3);if(s(t)){r+="%"+t.toUpperCase(),n+=2;continue}}if(t(i))r+=i;else{const t=e.charCodeAt(n);if(t<128)r+=d[t];else if(t<55296||t>57343)r+=l(t);else if(t<=56319&&n+1<e.length){const s=e.charCodeAt(n+1);s>=56320&&s<=57343?(r+=l(65536+(t-55296<<10)+(s-56320)),n++):r+=l(65533)}else r+=l(65533)}}return r}function $(e){return S(e,c)}function E(e){return e>=48&&e<=57||e>=65&&e<=90||e>=97&&e<=122||42===e||43===e||45===e||46===e||47===e||64===e||95===e}e.exports={nonSimpleDomain:m,recomposeAuthority:function(e){const t=[];if(void 0!==e.userinfo&&(t.push($(e.userinfo)),t.push("@")),void 0!==e.host){let n=e.host;if(!r(n)){let e=g(n);!0!==e.isIPV6&&!0!==e.isIPVFuture&&(n=k(n,!0),e=g(n)),n=!0===e.isIPV6||!0===e.isIPVFuture?`[${e.escapedHost}]`:b(n,!1)}t.push(n)}if("number"==typeof e.port||"string"==typeof e.port){const r=String(e.port);if(!n(r))throw new TypeError("URI port is malformed.");t.push(":"),t.push(r)}return t.length?t.join(""):void 0},reescapeHostDelimiters:b,normalizePercentEncoding:k,normalizePathEncoding:function(e){let t="";for(let r=0;r<e.length;r++){const n=e[r];if("%"===n&&r+2<e.length){const n=e.slice(r+1,r+3);if(s(n)){const e=n.toUpperCase(),s=String.fromCharCode(parseInt(e,16));"."!==s&&i(s)?t+=s:t+="%"+e,r+=2;continue}}if(a(n))t+=n;else{const s=e.charCodeAt(r);if(s<128)t+=E(s)?n:d[s];else if(s<55296||s>57343)t+=l(s);else if(s<=56319&&r+1<e.length){const n=e.charCodeAt(r+1);n>=56320&&n<=57343?(t+=l(65536+(s-55296<<10)+(n-56320)),r++):t+=l(65533)}else t+=l(65533)}}return t},serializePathEncoding:function(e,t=!1){let r="",n=t&&"/"!==e[0];for(let t=0;t<e.length;t++){const i=e[t];if("%"===i&&t+2<e.length){const n=e.slice(t+1,t+3);if(s(n)){r+="%"+n.toUpperCase(),t+=2;continue}}if("/"===i&&(n=!1),!a(i)||":"===i&&n){const n=e.charCodeAt(t);if(n<128)r+=d[n];else if(n<55296||n>57343)r+=l(n);else if(n<=56319&&t+1<e.length){const s=e.charCodeAt(t+1);s>=56320&&s<=57343?(r+=l(65536+(n-55296<<10)+(s-56320)),t++):r+=l(65533)}else r+=l(65533)}else r+=i}return r},normalizeQueryFragmentEncoding:function(e){let t="";for(let r=0;r<e.length;r++){const n=e[r];if("%"===n&&r+2<e.length){const n=e.slice(r+1,r+3);if(s(n)){const e=n.toUpperCase(),s=String.fromCharCode(parseInt(e,16));i(s)?t+=s:t+="%"+e,r+=2;continue}}if(o(n))t+=n;else{const s=e.charCodeAt(r);if(s<128)t+=E(s)?n:d[s];else if(s<55296||s>57343)t+=l(s);else if(s<=56319&&r+1<e.length){const n=e.charCodeAt(r+1);n>=56320&&n<=57343?(t+=l(65536+(s-55296<<10)+(n-56320)),r++):t+=l(65533)}else t+=l(65533)}}return t},encodeUserinfo:$,encodeQuery:function(e){return S(e,o)},encodeFragment:function(e){return S(e,o)},escapePreservingEscapes:function(e){let t="";for(let r=0;r<e.length;r++){if("%"===e[r]&&r+2<e.length){const n=e.slice(r+1,r+3);if(s(n)){t+="%"+n.toUpperCase(),r+=2;continue}}t+=escape(e[r])}return t},removeDotSegments:_,removeDotSegmentsRelative:function(e){if(""===e||"/"===e[0])return _(e);const t=e.split("/"),r=t.length-1,n=[];let s=!1;for(let e=0;e<=r;e++){const i=t[e];"."===i||".."===i?(".."===i&&(0!==n.length&&".."!==n[n.length-1]?n.pop():n.push("..")),s=e===r):n.push(i)}return s&&".."!==n[n.length-1]&&n.push(""),(0===n.length||""===n[0]||n[0].includes(":"))&&n.unshift("."),n.join("/")},isIPv4:r,isUUID:t,normalizeIPv6:g,stringArrayToHexStripped:function(e){let t="",r=0,n=0;for(n=0;n<e.length;n++)if(r=e[n].charCodeAt(0),48!==r){if(!(r>=48&&r<=57||r>=65&&r<=70||r>=97&&r<=102))return"";t+=e[n];break}for(n+=1;n<e.length;n++){if(r=e[n].charCodeAt(0),!(r>=48&&r<=57||r>=65&&r<=70||r>=97&&r<=102))return"";t+=e[n]}return t}}},3837(e){e.exports=JSON.parse('{"$id":"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#","description":"Meta-schema for $data reference (JSON AnySchema extension proposal)","type":"object","required":["$data"],"properties":{"$data":{"type":"string","anyOf":[{"format":"relative-json-pointer"},{"format":"json-pointer"}]}},"additionalProperties":false}')},2079(e){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}')}};const t={};function r(n){const s=t[n];if(void 0!==s)return s.exports;const i=t[n]={exports:{}};return e[n](i,i.exports,r),i.exports}function n(e,t,r){function n(r,n){var s;Object.defineProperty(r,"_zod",{value:r._zod??{},enumerable:!1}),(s=r._zod).traits??(s.traits=new Set),r._zod.traits.add(e),t(r,n);for(const e in a.prototype)e in r||Object.defineProperty(r,e,{value:a.prototype[e].bind(r)});r._zod.constr=a,r._zod.def=n}const s=r?.Parent??Object;class i extends s{}function a(e){var t;const s=r?.Parent?new i:this;n(s,e),(t=s._zod).deferred??(t.deferred=[]);for(const e of s._zod.deferred)e();return s}return Object.defineProperty(i,"name",{value:e}),Object.defineProperty(a,"init",{value:n}),Object.defineProperty(a,Symbol.hasInstance,{value:t=>!!(r?.Parent&&t instanceof r.Parent)||t?._zod?.traits?.has(e)}),Object.defineProperty(a,"name",{value:e}),a}Object.freeze({status:"aborted"}),Symbol("zod_brand");class s extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}const i={};function a(e){return e&&Object.assign(i,e),i}const o=/^[cC][^\s-]{8,}$/,c=/^[0-9a-z]+$/,d=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,l=/^[0-9a-vA-V]{20}$/,u=/^[A-Za-z0-9]{27}$/,h=/^[a-zA-Z0-9_-]{21}$/,p=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,m=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,f=e=>e?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000)$/,g=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,_=/^(?:(?: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])$/,y=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})$/,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])\/([0-9]|[1-2][0-9]|3[0-2])$/,v=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,b=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,k=/^[A-Za-z0-9_-]*$/,S=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/,$=/^\+(?:[0-9]){6,14}[0-9]$/,E="(?:(?:\\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(`^${E}$`);function I(e){const t="(?:[01]\\d|2[0-3]):[0-5]\\d";return"number"==typeof e.precision?-1===e.precision?`${t}`:0===e.precision?`${t}:[0-5]\\d`:`${t}:[0-5]\\d\\.\\d{${e.precision}}`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}const x=/^\d+$/,P=/^-?\d+(?:\.\d+)?/i,C=/true|false/i,R=/null/i,A=/^[^A-Z]*$/,O=/^[^a-z]*$/;function N(e){const t=Object.values(e).filter(e=>"number"==typeof e),r=Object.entries(e).filter(([e,r])=>-1===t.indexOf(+e)).map(([e,t])=>t);return r}function z(e,t){return"bigint"==typeof t?t.toString():t}function j(e){return{get value(){{const t=e();return Object.defineProperty(this,"value",{value:t}),t}}}}function U(e){return null==e}function q(e){const t=e.startsWith("^")?1:0,r=e.endsWith("$")?e.length-1:e.length;return e.slice(t,r)}function D(e,t,r){Object.defineProperty(e,t,{get(){{const n=r();return e[t]=n,n}},set(r){Object.defineProperty(e,t,{value:r})},configurable:!0})}function M(e,t,r){Object.defineProperty(e,t,{value:r,writable:!0,enumerable:!0,configurable:!0})}function L(e){return JSON.stringify(e)}const Z=Error.captureStackTrace?Error.captureStackTrace:(...e)=>{};function F(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}const H=j(()=>{if("undefined"!=typeof navigator&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return new Function(""),!0}catch(e){return!1}});function V(e){if(!1===F(e))return!1;const t=e.constructor;if(void 0===t)return!0;const r=t.prototype;return!1!==F(r)&&!1!==Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")}const K=new Set(["string","number","symbol"]);function G(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function W(e,t,r){const n=new e._zod.constr(t??e._zod.def);return t&&!r?.parent||(n._zod.parent=e),n}function B(e){const t=e;if(!t)return{};if("string"==typeof t)return{error:()=>t};if(void 0!==t?.message){if(void 0!==t?.error)throw new Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,"string"==typeof t.error?{...t,error:()=>t.error}:t}new Set(["string","number","bigint","boolean","symbol","undefined"]);const J={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]};function Q(e,t=0){for(let r=t;r<e.issues.length;r++)if(!0!==e.issues[r]?.continue)return!0;return!1}function Y(e,t){return t.map(t=>{var r;return(r=t).path??(r.path=[]),t.path.unshift(e),t})}function X(e){return"string"==typeof e?e:e?.message}function ee(e,t,r){const n={...e,path:e.path??[]};if(!e.message){const s=X(e.inst?._zod.def?.error?.(e))??X(t?.error?.(e))??X(r.customError?.(e))??X(r.localeError?.(e))??"Invalid input";n.message=s}return delete n.inst,delete n.continue,t?.reportInput||delete n.input,n}function te(e){return Array.isArray(e)?"array":"string"==typeof e?"string":"unknown"}function re(...e){const[t,r,n]=e;return"string"==typeof t?{message:t,code:"custom",input:r,inst:n}:{...t}}const ne=n("$ZodCheck",(e,t)=>{var r;e._zod??(e._zod={}),e._zod.def=t,(r=e._zod).onattach??(r.onattach=[])}),se={number:"number",bigint:"bigint",object:"date"},ie=n("$ZodCheckLessThan",(e,t)=>{ne.init(e,t);const r=se[typeof t.value];e._zod.onattach.push(e=>{const r=e._zod.bag,n=(t.inclusive?r.maximum:r.exclusiveMaximum)??Number.POSITIVE_INFINITY;t.value<n&&(t.inclusive?r.maximum=t.value:r.exclusiveMaximum=t.value)}),e._zod.check=n=>{(t.inclusive?n.value<=t.value:n.value<t.value)||n.issues.push({origin:r,code:"too_big",maximum:t.value,input:n.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),ae=n("$ZodCheckGreaterThan",(e,t)=>{ne.init(e,t);const r=se[typeof t.value];e._zod.onattach.push(e=>{const r=e._zod.bag,n=(t.inclusive?r.minimum:r.exclusiveMinimum)??Number.NEGATIVE_INFINITY;t.value>n&&(t.inclusive?r.minimum=t.value:r.exclusiveMinimum=t.value)}),e._zod.check=n=>{(t.inclusive?n.value>=t.value:n.value>t.value)||n.issues.push({origin:r,code:"too_small",minimum:t.value,input:n.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),oe=n("$ZodCheckMultipleOf",(e,t)=>{ne.init(e,t),e._zod.onattach.push(e=>{var r;(r=e._zod.bag).multipleOf??(r.multipleOf=t.value)}),e._zod.check=r=>{if(typeof r.value!=typeof t.value)throw new Error("Cannot mix number and bigint in multiple_of check.");("bigint"==typeof r.value?r.value%t.value===BigInt(0):0===function(e,t){const r=(e.toString().split(".")[1]||"").length,n=(t.toString().split(".")[1]||"").length,s=r>n?r:n;return Number.parseInt(e.toFixed(s).replace(".",""))%Number.parseInt(t.toFixed(s).replace(".",""))/10**s}(r.value,t.value))||r.issues.push({origin:typeof r.value,code:"not_multiple_of",divisor:t.value,input:r.value,inst:e,continue:!t.abort})}}),ce=n("$ZodCheckNumberFormat",(e,t)=>{ne.init(e,t),t.format=t.format||"float64";const r=t.format?.includes("int"),n=r?"int":"number",[s,i]=J[t.format];e._zod.onattach.push(e=>{const n=e._zod.bag;n.format=t.format,n.minimum=s,n.maximum=i,r&&(n.pattern=x)}),e._zod.check=a=>{const o=a.value;if(r){if(!Number.isInteger(o))return void a.issues.push({expected:n,format:t.format,code:"invalid_type",input:o,inst:e});if(!Number.isSafeInteger(o))return void(o>0?a.issues.push({input:o,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:n,continue:!t.abort}):a.issues.push({input:o,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:n,continue:!t.abort}))}o<s&&a.issues.push({origin:"number",input:o,code:"too_small",minimum:s,inclusive:!0,inst:e,continue:!t.abort}),o>i&&a.issues.push({origin:"number",input:o,code:"too_big",maximum:i,inst:e})}}),de=n("$ZodCheckMaxLength",(e,t)=>{var r;ne.init(e,t),(r=e._zod.def).when??(r.when=e=>{const t=e.value;return!U(t)&&void 0!==t.length}),e._zod.onattach.push(e=>{const r=e._zod.bag.maximum??Number.POSITIVE_INFINITY;t.maximum<r&&(e._zod.bag.maximum=t.maximum)}),e._zod.check=r=>{const n=r.value;if(n.length<=t.maximum)return;const s=te(n);r.issues.push({origin:s,code:"too_big",maximum:t.maximum,inclusive:!0,input:n,inst:e,continue:!t.abort})}}),le=n("$ZodCheckMinLength",(e,t)=>{var r;ne.init(e,t),(r=e._zod.def).when??(r.when=e=>{const t=e.value;return!U(t)&&void 0!==t.length}),e._zod.onattach.push(e=>{const r=e._zod.bag.minimum??Number.NEGATIVE_INFINITY;t.minimum>r&&(e._zod.bag.minimum=t.minimum)}),e._zod.check=r=>{const n=r.value;if(n.length>=t.minimum)return;const s=te(n);r.issues.push({origin:s,code:"too_small",minimum:t.minimum,inclusive:!0,input:n,inst:e,continue:!t.abort})}}),ue=n("$ZodCheckLengthEquals",(e,t)=>{var r;ne.init(e,t),(r=e._zod.def).when??(r.when=e=>{const t=e.value;return!U(t)&&void 0!==t.length}),e._zod.onattach.push(e=>{const r=e._zod.bag;r.minimum=t.length,r.maximum=t.length,r.length=t.length}),e._zod.check=r=>{const n=r.value,s=n.length;if(s===t.length)return;const i=te(n),a=s>t.length;r.issues.push({origin:i,...a?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:r.value,inst:e,continue:!t.abort})}}),he=n("$ZodCheckStringFormat",(e,t)=>{var r,n;ne.init(e,t),e._zod.onattach.push(e=>{const r=e._zod.bag;r.format=t.format,t.pattern&&(r.patterns??(r.patterns=new Set),r.patterns.add(t.pattern))}),t.pattern?(r=e._zod).check??(r.check=r=>{t.pattern.lastIndex=0,t.pattern.test(r.value)||r.issues.push({origin:"string",code:"invalid_format",format:t.format,input:r.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(n=e._zod).check??(n.check=()=>{})}),pe=n("$ZodCheckRegex",(e,t)=>{he.init(e,t),e._zod.check=r=>{t.pattern.lastIndex=0,t.pattern.test(r.value)||r.issues.push({origin:"string",code:"invalid_format",format:"regex",input:r.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),me=n("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=A),he.init(e,t)}),fe=n("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=O),he.init(e,t)}),ge=n("$ZodCheckIncludes",(e,t)=>{ne.init(e,t);const r=G(t.includes),n=new RegExp("number"==typeof t.position?`^.{${t.position}}${r}`:r);t.pattern=n,e._zod.onattach.push(e=>{const t=e._zod.bag;t.patterns??(t.patterns=new Set),t.patterns.add(n)}),e._zod.check=r=>{r.value.includes(t.includes,t.position)||r.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:r.value,inst:e,continue:!t.abort})}}),_e=n("$ZodCheckStartsWith",(e,t)=>{ne.init(e,t);const r=new RegExp(`^${G(t.prefix)}.*`);t.pattern??(t.pattern=r),e._zod.onattach.push(e=>{const t=e._zod.bag;t.patterns??(t.patterns=new Set),t.patterns.add(r)}),e._zod.check=r=>{r.value.startsWith(t.prefix)||r.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:t.prefix,input:r.value,inst:e,continue:!t.abort})}}),ye=n("$ZodCheckEndsWith",(e,t)=>{ne.init(e,t);const r=new RegExp(`.*${G(t.suffix)}$`);t.pattern??(t.pattern=r),e._zod.onattach.push(e=>{const t=e._zod.bag;t.patterns??(t.patterns=new Set),t.patterns.add(r)}),e._zod.check=r=>{r.value.endsWith(t.suffix)||r.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:t.suffix,input:r.value,inst:e,continue:!t.abort})}}),we=n("$ZodCheckOverwrite",(e,t)=>{ne.init(e,t),e._zod.check=e=>{e.value=t.tx(e.value)}});class ve{constructor(e=[]){this.content=[],this.indent=0,this&&(this.args=e)}indented(e){this.indent+=1,e(this),this.indent-=1}write(e){if("function"==typeof e)return e(this,{execution:"sync"}),void e(this,{execution:"async"});const t=e.split("\n").filter(e=>e),r=Math.min(...t.map(e=>e.length-e.trimStart().length)),n=t.map(e=>e.slice(r)).map(e=>" ".repeat(2*this.indent)+e);for(const e of n)this.content.push(e)}compile(){const e=Function,t=this?.args,r=[...(this?.content??[""]).map(e=>` ${e}`)];return new e(...t,r.join("\n"))}}const be=(e,t)=>{e.name="$ZodError",Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),Object.defineProperty(e,"message",{get:()=>JSON.stringify(t,z,2),enumerable:!0}),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},ke=n("$ZodError",be),Se=n("$ZodError",be,{Parent:Error}),Ee=e=>(t,r,n,i)=>{const o=n?Object.assign(n,{async:!1}):{async:!1},c=t._zod.run({value:r,issues:[]},o);if(c instanceof Promise)throw new s;if(c.issues.length){const t=new(i?.Err??e)(c.issues.map(e=>ee(e,o,a())));throw Z(t,i?.callee),t}return c.value},Te=Ee(Se),Ie=e=>async(t,r,n,s)=>{const i=n?Object.assign(n,{async:!0}):{async:!0};let o=t._zod.run({value:r,issues:[]},i);if(o instanceof Promise&&(o=await o),o.issues.length){const t=new(s?.Err??e)(o.issues.map(e=>ee(e,i,a())));throw Z(t,s?.callee),t}return o.value},xe=Ie(Se),Pe=e=>(t,r,n)=>{const i=n?{...n,async:!1}:{async:!1},o=t._zod.run({value:r,issues:[]},i);if(o instanceof Promise)throw new s;return o.issues.length?{success:!1,error:new(e??ke)(o.issues.map(e=>ee(e,i,a())))}:{success:!0,data:o.value}},Ce=Pe(Se),Re=e=>async(t,r,n)=>{const s=n?Object.assign(n,{async:!0}):{async:!0};let i=t._zod.run({value:r,issues:[]},s);return i instanceof Promise&&(i=await i),i.issues.length?{success:!1,error:new e(i.issues.map(e=>ee(e,s,a())))}:{success:!0,data:i.value}},Ae=Re(Se),Oe={major:4,minor:0,patch:0},Ne=n("$ZodType",(e,t)=>{var r;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=Oe;const n=[...e._zod.def.checks??[]];e._zod.traits.has("$ZodCheck")&&n.unshift(e);for(const t of n)for(const r of t._zod.onattach)r(e);if(0===n.length)(r=e._zod).deferred??(r.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{const t=(e,t,r)=>{let n,i=Q(e);for(const a of t){if(a._zod.def.when){if(!a._zod.def.when(e))continue}else if(i)continue;const t=e.issues.length,o=a._zod.check(e);if(o instanceof Promise&&!1===r?.async)throw new s;if(n||o instanceof Promise)n=(n??Promise.resolve()).then(async()=>{await o,e.issues.length!==t&&(i||(i=Q(e,t)))});else{if(e.issues.length===t)continue;i||(i=Q(e,t))}}return n?n.then(()=>e):e};e._zod.run=(r,i)=>{const a=e._zod.parse(r,i);if(a instanceof Promise){if(!1===i.async)throw new s;return a.then(e=>t(e,n,i))}return t(a,n,i)}}e["~standard"]={validate:t=>{try{const r=Ce(e,t);return r.success?{value:r.data}:{issues:r.error?.issues}}catch(r){return Ae(e,t).then(e=>e.success?{value:e.data}:{issues:e.error?.issues})}},vendor:"zod",version:1}}),ze=n("$ZodString",(e,t)=>{var r;Ne.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??(r=e._zod.bag,new RegExp(`^${r?`[\\s\\S]{${r?.minimum??0},${r?.maximum??""}}`:"[\\s\\S]*"}$`)),e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=String(r.value)}catch(n){}return"string"==typeof r.value||r.issues.push({expected:"string",code:"invalid_type",input:r.value,inst:e}),r}}),je=n("$ZodStringFormat",(e,t)=>{he.init(e,t),ze.init(e,t)}),Ue=n("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=m),je.init(e,t)}),qe=n("$ZodUUID",(e,t)=>{if(t.version){const e={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(void 0===e)throw new Error(`Invalid UUID version: "${t.version}"`);t.pattern??(t.pattern=f(e))}else t.pattern??(t.pattern=f());je.init(e,t)}),De=n("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=g),je.init(e,t)}),Me=n("$ZodURL",(e,t)=>{je.init(e,t),e._zod.check=r=>{try{const n=r.value,s=new URL(n),i=s.href;return t.hostname&&(t.hostname.lastIndex=0,t.hostname.test(s.hostname)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:S.source,input:r.value,inst:e,continue:!t.abort})),t.protocol&&(t.protocol.lastIndex=0,t.protocol.test(s.protocol.endsWith(":")?s.protocol.slice(0,-1):s.protocol)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:t.protocol.source,input:r.value,inst:e,continue:!t.abort})),void(!n.endsWith("/")&&i.endsWith("/")?r.value=i.slice(0,-1):r.value=i)}catch(n){r.issues.push({code:"invalid_format",format:"url",input:r.value,inst:e,continue:!t.abort})}}}),Le=n("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=new RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),je.init(e,t)}),Ze=n("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=h),je.init(e,t)}),Fe=n("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=o),je.init(e,t)}),He=n("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=c),je.init(e,t)}),Ve=n("$ZodULID",(e,t)=>{t.pattern??(t.pattern=d),je.init(e,t)}),Ke=n("$ZodXID",(e,t)=>{t.pattern??(t.pattern=l),je.init(e,t)}),Ge=n("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=u),je.init(e,t)}),We=n("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=function(e){const t=I({precision:e.precision}),r=["Z"];e.local&&r.push(""),e.offset&&r.push("([+-]\\d{2}:\\d{2})");const n=`${t}(?:${r.join("|")})`;return new RegExp(`^${E}T(?:${n})$`)}(t)),je.init(e,t)}),Be=n("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=T),je.init(e,t)}),Je=n("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=new RegExp(`^${I(t)}$`)),je.init(e,t)}),Qe=n("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=p),je.init(e,t)}),Ye=n("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=_),je.init(e,t),e._zod.onattach.push(e=>{e._zod.bag.format="ipv4"})}),Xe=n("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=y),je.init(e,t),e._zod.onattach.push(e=>{e._zod.bag.format="ipv6"}),e._zod.check=r=>{try{new URL(`http://[${r.value}]`)}catch{r.issues.push({code:"invalid_format",format:"ipv6",input:r.value,inst:e,continue:!t.abort})}}}),et=n("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=w),je.init(e,t)}),tt=n("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=v),je.init(e,t),e._zod.check=r=>{const[n,s]=r.value.split("/");try{if(!s)throw new Error;const e=Number(s);if(`${e}`!==s)throw new Error;if(e<0||e>128)throw new Error;new URL(`http://[${n}]`)}catch{r.issues.push({code:"invalid_format",format:"cidrv6",input:r.value,inst:e,continue:!t.abort})}}});function rt(e){if(""===e)return!0;if(e.length%4!=0)return!1;try{return atob(e),!0}catch{return!1}}const nt=n("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=b),je.init(e,t),e._zod.onattach.push(e=>{e._zod.bag.contentEncoding="base64"}),e._zod.check=r=>{rt(r.value)||r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:e,continue:!t.abort})}}),st=n("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=k),je.init(e,t),e._zod.onattach.push(e=>{e._zod.bag.contentEncoding="base64url"}),e._zod.check=r=>{(function(e){if(!k.test(e))return!1;const t=e.replace(/[-_]/g,e=>"-"===e?"+":"/");return rt(t.padEnd(4*Math.ceil(t.length/4),"="))})(r.value)||r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:e,continue:!t.abort})}}),it=n("$ZodE164",(e,t)=>{t.pattern??(t.pattern=$),je.init(e,t)}),at=n("$ZodJWT",(e,t)=>{je.init(e,t),e._zod.check=r=>{(function(e,t=null){try{const r=e.split(".");if(3!==r.length)return!1;const[n]=r;if(!n)return!1;const s=JSON.parse(atob(n));return!("typ"in s&&"JWT"!==s?.typ||!s.alg||t&&(!("alg"in s)||s.alg!==t))}catch{return!1}})(r.value,t.alg)||r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:e,continue:!t.abort})}}),ot=n("$ZodNumber",(e,t)=>{Ne.init(e,t),e._zod.pattern=e._zod.bag.pattern??P,e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=Number(r.value)}catch(e){}const s=r.value;if("number"==typeof s&&!Number.isNaN(s)&&Number.isFinite(s))return r;const i="number"==typeof s?Number.isNaN(s)?"NaN":Number.isFinite(s)?void 0:"Infinity":void 0;return r.issues.push({expected:"number",code:"invalid_type",input:s,inst:e,...i?{received:i}:{}}),r}}),ct=n("$ZodNumber",(e,t)=>{ce.init(e,t),ot.init(e,t)}),dt=n("$ZodBoolean",(e,t)=>{Ne.init(e,t),e._zod.pattern=C,e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=Boolean(r.value)}catch(e){}const s=r.value;return"boolean"==typeof s||r.issues.push({expected:"boolean",code:"invalid_type",input:s,inst:e}),r}}),lt=n("$ZodNull",(e,t)=>{Ne.init(e,t),e._zod.pattern=R,e._zod.values=new Set([null]),e._zod.parse=(t,r)=>{const n=t.value;return null===n||t.issues.push({expected:"null",code:"invalid_type",input:n,inst:e}),t}}),ut=n("$ZodUnknown",(e,t)=>{Ne.init(e,t),e._zod.parse=e=>e}),ht=n("$ZodNever",(e,t)=>{Ne.init(e,t),e._zod.parse=(t,r)=>(t.issues.push({expected:"never",code:"invalid_type",input:t.value,inst:e}),t)});function pt(e,t,r){e.issues.length&&t.issues.push(...Y(r,e.issues)),t.value[r]=e.value}const mt=n("$ZodArray",(e,t)=>{Ne.init(e,t),e._zod.parse=(r,n)=>{const s=r.value;if(!Array.isArray(s))return r.issues.push({expected:"array",code:"invalid_type",input:s,inst:e}),r;r.value=Array(s.length);const i=[];for(let e=0;e<s.length;e++){const a=s[e],o=t.element._zod.run({value:a,issues:[]},n);o instanceof Promise?i.push(o.then(t=>pt(t,r,e))):pt(o,r,e)}return i.length?Promise.all(i).then(()=>r):r}});function ft(e,t,r){e.issues.length&&t.issues.push(...Y(r,e.issues)),t.value[r]=e.value}function gt(e,t,r,n){e.issues.length?void 0===n[r]?t.value[r]=r in n?void 0:e.value:t.issues.push(...Y(r,e.issues)):void 0===e.value?r in n&&(t.value[r]=void 0):t.value[r]=e.value}const _t=n("$ZodObject",(e,t)=>{Ne.init(e,t);const r=j(()=>{const e=Object.keys(t.shape);for(const r of e)if(!(t.shape[r]instanceof Ne))throw new Error(`Invalid element at key "${r}": expected a Zod schema`);const r=(n=t.shape,Object.keys(n).filter(e=>"optional"===n[e]._zod.optin&&"optional"===n[e]._zod.optout));var n;return{shape:t.shape,keys:e,keySet:new Set(e),numKeys:e.length,optionalKeys:new Set(r)}});let n;D(e._zod,"propValues",()=>{const e=t.shape,r={};for(const t in e){const n=e[t]._zod;if(n.values){r[t]??(r[t]=new Set);for(const e of n.values)r[t].add(e)}}return r});const s=F,a=!i.jitless,o=a&&H.value,c=t.catchall;let d;e._zod.parse=(i,l)=>{d??(d=r.value);const u=i.value;if(!s(u))return i.issues.push({expected:"object",code:"invalid_type",input:u,inst:e}),i;const h=[];if(a&&o&&!1===l?.async&&!0!==l.jitless)n||(n=(e=>{const t=new ve(["shape","payload","ctx"]),n=r.value,s=e=>{const t=L(e);return`shape[${t}]._zod.run({ value: input[${t}], issues: [] }, ctx)`};t.write("const input = payload.value;");const i=Object.create(null);let a=0;for(const e of n.keys)i[e]="key_"+a++;t.write("const newResult = {}");for(const e of n.keys)if(n.optionalKeys.has(e)){const r=i[e];t.write(`const ${r} = ${s(e)};`);const n=L(e);t.write(`\n if (${r}.issues.length) {\n if (input[${n}] === undefined) {\n if (${n} in input) {\n newResult[${n}] = undefined;\n }\n } else {\n payload.issues = payload.issues.concat(\n ${r}.issues.map((iss) => ({\n ...iss,\n path: iss.path ? [${n}, ...iss.path] : [${n}],\n }))\n );\n }\n } else if (${r}.value === undefined) {\n if (${n} in input) newResult[${n}] = undefined;\n } else {\n newResult[${n}] = ${r}.value;\n }\n `)}else{const r=i[e];t.write(`const ${r} = ${s(e)};`),t.write(`\n if (${r}.issues.length) payload.issues = payload.issues.concat(${r}.issues.map(iss => ({\n ...iss,\n path: iss.path ? [${L(e)}, ...iss.path] : [${L(e)}]\n })));`),t.write(`newResult[${L(e)}] = ${r}.value`)}t.write("payload.value = newResult;"),t.write("return payload;");const o=t.compile();return(t,r)=>o(e,t,r)})(t.shape)),i=n(i,l);else{i.value={};const e=d.shape;for(const t of d.keys){const r=e[t],n=r._zod.run({value:u[t],issues:[]},l),s="optional"===r._zod.optin&&"optional"===r._zod.optout;n instanceof Promise?h.push(n.then(e=>s?gt(e,i,t,u):ft(e,i,t))):s?gt(n,i,t,u):ft(n,i,t)}}if(!c)return h.length?Promise.all(h).then(()=>i):i;const p=[],m=d.keySet,f=c._zod,g=f.def.type;for(const e of Object.keys(u)){if(m.has(e))continue;if("never"===g){p.push(e);continue}const t=f.run({value:u[e],issues:[]},l);t instanceof Promise?h.push(t.then(t=>ft(t,i,e))):ft(t,i,e)}return p.length&&i.issues.push({code:"unrecognized_keys",keys:p,input:u,inst:e}),h.length?Promise.all(h).then(()=>i):i}});function yt(e,t,r,n){for(const r of e)if(0===r.issues.length)return t.value=r.value,t;return t.issues.push({code:"invalid_union",input:t.value,inst:r,errors:e.map(e=>e.issues.map(e=>ee(e,n,a())))}),t}const wt=n("$ZodUnion",(e,t)=>{Ne.init(e,t),D(e._zod,"optin",()=>t.options.some(e=>"optional"===e._zod.optin)?"optional":void 0),D(e._zod,"optout",()=>t.options.some(e=>"optional"===e._zod.optout)?"optional":void 0),D(e._zod,"values",()=>{if(t.options.every(e=>e._zod.values))return new Set(t.options.flatMap(e=>Array.from(e._zod.values)))}),D(e._zod,"pattern",()=>{if(t.options.every(e=>e._zod.pattern)){const e=t.options.map(e=>e._zod.pattern);return new RegExp(`^(${e.map(e=>q(e.source)).join("|")})$`)}}),e._zod.parse=(r,n)=>{let s=!1;const i=[];for(const e of t.options){const t=e._zod.run({value:r.value,issues:[]},n);if(t instanceof Promise)i.push(t),s=!0;else{if(0===t.issues.length)return t;i.push(t)}}return s?Promise.all(i).then(t=>yt(t,r,e,n)):yt(i,r,e,n)}}),vt=n("$ZodDiscriminatedUnion",(e,t)=>{wt.init(e,t);const r=e._zod.parse;D(e._zod,"propValues",()=>{const e={};for(const r of t.options){const n=r._zod.propValues;if(!n||0===Object.keys(n).length)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(r)}"`);for(const[t,r]of Object.entries(n)){e[t]||(e[t]=new Set);for(const n of r)e[t].add(n)}}return e});const n=j(()=>{const e=t.options,r=new Map;for(const n of e){const e=n._zod.propValues[t.discriminator];if(!e||0===e.size)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(n)}"`);for(const t of e){if(r.has(t))throw new Error(`Duplicate discriminator value "${String(t)}"`);r.set(t,n)}}return r});e._zod.parse=(s,i)=>{const a=s.value;if(!F(a))return s.issues.push({code:"invalid_type",expected:"object",input:a,inst:e}),s;const o=n.value.get(a?.[t.discriminator]);return o?o._zod.run(s,i):t.unionFallback?r(s,i):(s.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",input:a,path:[t.discriminator],inst:e}),s)}}),bt=n("$ZodIntersection",(e,t)=>{Ne.init(e,t),e._zod.parse=(e,r)=>{const n=e.value,s=t.left._zod.run({value:n,issues:[]},r),i=t.right._zod.run({value:n,issues:[]},r);return s instanceof Promise||i instanceof Promise?Promise.all([s,i]).then(([t,r])=>St(e,t,r)):St(e,s,i)}});function kt(e,t){if(e===t)return{valid:!0,data:e};if(e instanceof Date&&t instanceof Date&&+e===+t)return{valid:!0,data:e};if(V(e)&&V(t)){const r=Object.keys(t),n=Object.keys(e).filter(e=>-1!==r.indexOf(e)),s={...e,...t};for(const r of n){const n=kt(e[r],t[r]);if(!n.valid)return{valid:!1,mergeErrorPath:[r,...n.mergeErrorPath]};s[r]=n.data}return{valid:!0,data:s}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};const r=[];for(let n=0;n<e.length;n++){const s=kt(e[n],t[n]);if(!s.valid)return{valid:!1,mergeErrorPath:[n,...s.mergeErrorPath]};r.push(s.data)}return{valid:!0,data:r}}return{valid:!1,mergeErrorPath:[]}}function St(e,t,r){if(t.issues.length&&e.issues.push(...t.issues),r.issues.length&&e.issues.push(...r.issues),Q(e))return e;const n=kt(t.value,r.value);if(!n.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(n.mergeErrorPath)}`);return e.value=n.data,e}const $t=n("$ZodRecord",(e,t)=>{Ne.init(e,t),e._zod.parse=(r,n)=>{const s=r.value;if(!V(s))return r.issues.push({expected:"record",code:"invalid_type",input:s,inst:e}),r;const i=[];if(t.keyType._zod.values){const a=t.keyType._zod.values;r.value={};for(const e of a)if("string"==typeof e||"number"==typeof e||"symbol"==typeof e){const a=t.valueType._zod.run({value:s[e],issues:[]},n);a instanceof Promise?i.push(a.then(t=>{t.issues.length&&r.issues.push(...Y(e,t.issues)),r.value[e]=t.value})):(a.issues.length&&r.issues.push(...Y(e,a.issues)),r.value[e]=a.value)}let o;for(const e in s)a.has(e)||(o=o??[],o.push(e));o&&o.length>0&&r.issues.push({code:"unrecognized_keys",input:s,inst:e,keys:o})}else{r.value={};for(const o of Reflect.ownKeys(s)){if("__proto__"===o)continue;const c=t.keyType._zod.run({value:o,issues:[]},n);if(c instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(c.issues.length){r.issues.push({origin:"record",code:"invalid_key",issues:c.issues.map(e=>ee(e,n,a())),input:o,path:[o],inst:e}),r.value[c.value]=c.value;continue}const d=t.valueType._zod.run({value:s[o],issues:[]},n);d instanceof Promise?i.push(d.then(e=>{e.issues.length&&r.issues.push(...Y(o,e.issues)),r.value[c.value]=e.value})):(d.issues.length&&r.issues.push(...Y(o,d.issues)),r.value[c.value]=d.value)}}return i.length?Promise.all(i).then(()=>r):r}}),Et=n("$ZodEnum",(e,t)=>{Ne.init(e,t);const r=N(t.entries);e._zod.values=new Set(r),e._zod.pattern=new RegExp(`^(${r.filter(e=>K.has(typeof e)).map(e=>"string"==typeof e?G(e):e.toString()).join("|")})$`),e._zod.parse=(t,n)=>{const s=t.value;return e._zod.values.has(s)||t.issues.push({code:"invalid_value",values:r,input:s,inst:e}),t}}),Tt=n("$ZodLiteral",(e,t)=>{Ne.init(e,t),e._zod.values=new Set(t.values),e._zod.pattern=new RegExp(`^(${t.values.map(e=>"string"==typeof e?G(e):e?e.toString():String(e)).join("|")})$`),e._zod.parse=(r,n)=>{const s=r.value;return e._zod.values.has(s)||r.issues.push({code:"invalid_value",values:t.values,input:s,inst:e}),r}}),It=n("$ZodTransform",(e,t)=>{Ne.init(e,t),e._zod.parse=(e,r)=>{const n=t.transform(e.value,e);if(r.async)return(n instanceof Promise?n:Promise.resolve(n)).then(t=>(e.value=t,e));if(n instanceof Promise)throw new s;return e.value=n,e}}),xt=n("$ZodOptional",(e,t)=>{Ne.init(e,t),e._zod.optin="optional",e._zod.optout="optional",D(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),D(e._zod,"pattern",()=>{const e=t.innerType._zod.pattern;return e?new RegExp(`^(${q(e.source)})?$`):void 0}),e._zod.parse=(e,r)=>"optional"===t.innerType._zod.optin?t.innerType._zod.run(e,r):void 0===e.value?e:t.innerType._zod.run(e,r)}),Pt=n("$ZodNullable",(e,t)=>{Ne.init(e,t),D(e._zod,"optin",()=>t.innerType._zod.optin),D(e._zod,"optout",()=>t.innerType._zod.optout),D(e._zod,"pattern",()=>{const e=t.innerType._zod.pattern;return e?new RegExp(`^(${q(e.source)}|null)$`):void 0}),D(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,null]):void 0),e._zod.parse=(e,r)=>null===e.value?e:t.innerType._zod.run(e,r)}),Ct=n("$ZodDefault",(e,t)=>{Ne.init(e,t),e._zod.optin="optional",D(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(e,r)=>{if(void 0===e.value)return e.value=t.defaultValue,e;const n=t.innerType._zod.run(e,r);return n instanceof Promise?n.then(e=>Rt(e,t)):Rt(n,t)}});function Rt(e,t){return void 0===e.value&&(e.value=t.defaultValue),e}const At=n("$ZodPrefault",(e,t)=>{Ne.init(e,t),e._zod.optin="optional",D(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(e,r)=>(void 0===e.value&&(e.value=t.defaultValue),t.innerType._zod.run(e,r))}),Ot=n("$ZodNonOptional",(e,t)=>{Ne.init(e,t),D(e._zod,"values",()=>{const e=t.innerType._zod.values;return e?new Set([...e].filter(e=>void 0!==e)):void 0}),e._zod.parse=(r,n)=>{const s=t.innerType._zod.run(r,n);return s instanceof Promise?s.then(t=>Nt(t,e)):Nt(s,e)}});function Nt(e,t){return e.issues.length||void 0!==e.value||e.issues.push({code:"invalid_type",expected:"nonoptional",input:e.value,inst:t}),e}const zt=n("$ZodCatch",(e,t)=>{Ne.init(e,t),e._zod.optin="optional",D(e._zod,"optout",()=>t.innerType._zod.optout),D(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(e,r)=>{const n=t.innerType._zod.run(e,r);return n instanceof Promise?n.then(n=>(e.value=n.value,n.issues.length&&(e.value=t.catchValue({...e,error:{issues:n.issues.map(e=>ee(e,r,a()))},input:e.value}),e.issues=[]),e)):(e.value=n.value,n.issues.length&&(e.value=t.catchValue({...e,error:{issues:n.issues.map(e=>ee(e,r,a()))},input:e.value}),e.issues=[]),e)}}),jt=n("$ZodPipe",(e,t)=>{Ne.init(e,t),D(e._zod,"values",()=>t.in._zod.values),D(e._zod,"optin",()=>t.in._zod.optin),D(e._zod,"optout",()=>t.out._zod.optout),e._zod.parse=(e,r)=>{const n=t.in._zod.run(e,r);return n instanceof Promise?n.then(e=>Ut(e,t,r)):Ut(n,t,r)}});function Ut(e,t,r){return Q(e)?e:t.out._zod.run({value:e.value,issues:e.issues},r)}const qt=n("$ZodReadonly",(e,t)=>{Ne.init(e,t),D(e._zod,"propValues",()=>t.innerType._zod.propValues),D(e._zod,"values",()=>t.innerType._zod.values),D(e._zod,"optin",()=>t.innerType._zod.optin),D(e._zod,"optout",()=>t.innerType._zod.optout),e._zod.parse=(e,r)=>{const n=t.innerType._zod.run(e,r);return n instanceof Promise?n.then(Dt):Dt(n)}});function Dt(e){return e.value=Object.freeze(e.value),e}const Mt=n("$ZodCustom",(e,t)=>{ne.init(e,t),Ne.init(e,t),e._zod.parse=(e,t)=>e,e._zod.check=r=>{const n=r.value,s=t.fn(n);if(s instanceof Promise)return s.then(t=>Lt(t,r,n,e));Lt(s,r,n,e)}});function Lt(e,t,r,n){if(!e){const e={code:"custom",input:r,inst:n,path:[...n._zod.def.path??[]],continue:!n._zod.def.abort};n._zod.def.params&&(e.params=n._zod.def.params),t.issues.push(re(e))}}Symbol("ZodOutput"),Symbol("ZodInput");class Zt{constructor(){this._map=new Map,this._idmap=new Map}add(e,...t){const r=t[0];if(this._map.set(e,r),r&&"object"==typeof r&&"id"in r){if(this._idmap.has(r.id))throw new Error(`ID ${r.id} already exists in the registry`);this._idmap.set(r.id,e)}return this}clear(){return this._map=new Map,this._idmap=new Map,this}remove(e){const t=this._map.get(e);return t&&"object"==typeof t&&"id"in t&&this._idmap.delete(t.id),this._map.delete(e),this}get(e){const t=e._zod.parent;if(t){const r={...this.get(t)??{}};return delete r.id,{...r,...this._map.get(e)}}return this._map.get(e)}has(e){return this._map.has(e)}}function Ft(){return new Zt}const Ht=Ft();function Vt(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...B(t)})}function Kt(e,t){return new ie({check:"less_than",...B(t),value:e,inclusive:!1})}function Gt(e,t){return new ie({check:"less_than",...B(t),value:e,inclusive:!0})}function Wt(e,t){return new ae({check:"greater_than",...B(t),value:e,inclusive:!1})}function Bt(e,t){return new ae({check:"greater_than",...B(t),value:e,inclusive:!0})}function Jt(e,t){return new oe({check:"multiple_of",...B(t),value:e})}function Qt(e,t){return new de({check:"max_length",...B(t),maximum:e})}function Yt(e,t){return new le({check:"min_length",...B(t),minimum:e})}function Xt(e,t){return new ue({check:"length_equals",...B(t),length:e})}function er(e){return new we({check:"overwrite",tx:e})}const tr=n("ZodISODateTime",(e,t)=>{We.init(e,t),fr.init(e,t)});function rr(e){return function(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...B(t)})}(tr,e)}const nr=n("ZodISODate",(e,t)=>{Be.init(e,t),fr.init(e,t)});const sr=n("ZodISOTime",(e,t)=>{Je.init(e,t),fr.init(e,t)});const ir=n("ZodISODuration",(e,t)=>{Qe.init(e,t),fr.init(e,t)});const ar=n("ZodError",(e,t)=>{ke.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:t=>function(e,t){const r=t||function(e){return e.message},n={_errors:[]},s=e=>{for(const t of e.issues)if("invalid_union"===t.code&&t.errors.length)t.errors.map(e=>s({issues:e}));else if("invalid_key"===t.code)s({issues:t.issues});else if("invalid_element"===t.code)s({issues:t.issues});else if(0===t.path.length)n._errors.push(r(t));else{let e=n,s=0;for(;s<t.path.length;){const n=t.path[s];s===t.path.length-1?(e[n]=e[n]||{_errors:[]},e[n]._errors.push(r(t))):e[n]=e[n]||{_errors:[]},e=e[n],s++}}};return s(e),n}(e,t)},flatten:{value:t=>function(e,t=e=>e.message){const r={},n=[];for(const s of e.issues)s.path.length>0?(r[s.path[0]]=r[s.path[0]]||[],r[s.path[0]].push(t(s))):n.push(t(s));return{formErrors:n,fieldErrors:r}}(e,t)},addIssue:{value:t=>e.issues.push(t)},addIssues:{value:t=>e.issues.push(...t)},isEmpty:{get:()=>0===e.issues.length}})},{Parent:Error}),or=Ee(ar),cr=Ie(ar),dr=Pe(ar),lr=Re(ar),ur=n("ZodType",(e,t)=>(Ne.init(e,t),e.def=t,Object.defineProperty(e,"_def",{value:t}),e.check=(...r)=>e.clone({...t,checks:[...t.checks??[],...r.map(e=>"function"==typeof e?{_zod:{check:e,def:{check:"custom"},onattach:[]}}:e)]}),e.clone=(t,r)=>W(e,t,r),e.brand=()=>e,e.register=(t,r)=>(t.add(e,r),e),e.parse=(t,r)=>or(e,t,r,{callee:e.parse}),e.safeParse=(t,r)=>dr(e,t,r),e.parseAsync=async(t,r)=>cr(e,t,r,{callee:e.parseAsync}),e.safeParseAsync=async(t,r)=>lr(e,t,r),e.spa=e.safeParseAsync,e.refine=(t,r)=>e.check(function(e,t={}){return function(e,t,r){return new e({type:"custom",check:"custom",fn:t,...B(r)})}(kn,e,t)}(t,r)),e.superRefine=t=>e.check(function(e){const t=function(e){const t=new ne({check:"custom"});return t._zod.check=e,t}(r=>(r.addIssue=e=>{if("string"==typeof e)r.issues.push(re(e,r.value,t._zod.def));else{const n=e;n.fatal&&(n.continue=!1),n.code??(n.code="custom"),n.input??(n.input=r.value),n.inst??(n.inst=t),n.continue??(n.continue=!t._zod.def.abort),r.issues.push(re(n))}},e(r.value,r)));return t}(t)),e.overwrite=t=>e.check(er(t)),e.optional=()=>hn(e),e.nullable=()=>mn(e),e.nullish=()=>hn(mn(e)),e.nonoptional=t=>function(e,t){return new _n({type:"nonoptional",innerType:e,...B(t)})}(e,t),e.array=()=>Kr(e),e.or=t=>Qr([e,t]),e.and=t=>tn(e,t),e.transform=t=>vn(e,ln(t)),e.default=t=>{return r=t,new fn({type:"default",innerType:e,get defaultValue(){return"function"==typeof r?r():r}});var r},e.prefault=t=>{return r=t,new gn({type:"prefault",innerType:e,get defaultValue(){return"function"==typeof r?r():r}});var r},e.catch=t=>{return new yn({type:"catch",innerType:e,catchValue:"function"==typeof(r=t)?r:()=>r});var r},e.pipe=t=>vn(e,t),e.readonly=()=>new bn({type:"readonly",innerType:e}),e.describe=t=>{const r=e.clone();return Ht.add(r,{description:t}),r},Object.defineProperty(e,"description",{get:()=>Ht.get(e)?.description,configurable:!0}),e.meta=(...t)=>{if(0===t.length)return Ht.get(e);const r=e.clone();return Ht.add(r,t[0]),r},e.isOptional=()=>e.safeParse(void 0).success,e.isNullable=()=>e.safeParse(null).success,e)),hr=n("_ZodString",(e,t)=>{ze.init(e,t),ur.init(e,t);const r=e._zod.bag;e.format=r.format??null,e.minLength=r.minimum??null,e.maxLength=r.maximum??null,e.regex=(...t)=>e.check(function(e,t){return new pe({check:"string_format",format:"regex",...B(t),pattern:e})}(...t)),e.includes=(...t)=>e.check(function(e,t){return new ge({check:"string_format",format:"includes",...B(t),includes:e})}(...t)),e.startsWith=(...t)=>e.check(function(e,t){return new _e({check:"string_format",format:"starts_with",...B(t),prefix:e})}(...t)),e.endsWith=(...t)=>e.check(function(e,t){return new ye({check:"string_format",format:"ends_with",...B(t),suffix:e})}(...t)),e.min=(...t)=>e.check(Yt(...t)),e.max=(...t)=>e.check(Qt(...t)),e.length=(...t)=>e.check(Xt(...t)),e.nonempty=(...t)=>e.check(Yt(1,...t)),e.lowercase=t=>e.check(function(e){return new me({check:"string_format",format:"lowercase",...B(e)})}(t)),e.uppercase=t=>e.check(function(e){return new fe({check:"string_format",format:"uppercase",...B(e)})}(t)),e.trim=()=>e.check(er(e=>e.trim())),e.normalize=(...t)=>e.check(function(e){return er(t=>t.normalize(e))}(...t)),e.toLowerCase=()=>e.check(er(e=>e.toLowerCase())),e.toUpperCase=()=>e.check(er(e=>e.toUpperCase()))}),pr=n("ZodString",(e,t)=>{ze.init(e,t),hr.init(e,t),e.email=t=>e.check(function(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...B(t)})}(gr,t)),e.url=t=>e.check(function(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...B(t)})}(wr,t)),e.jwt=t=>e.check(function(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...B(t)})}(Nr,t)),e.emoji=t=>e.check(function(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...B(t)})}(vr,t)),e.guid=t=>e.check(Vt(_r,t)),e.uuid=t=>e.check(function(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...B(t)})}(yr,t)),e.uuidv4=t=>e.check(function(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...B(t)})}(yr,t)),e.uuidv6=t=>e.check(function(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...B(t)})}(yr,t)),e.uuidv7=t=>e.check(function(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...B(t)})}(yr,t)),e.nanoid=t=>e.check(function(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...B(t)})}(br,t)),e.guid=t=>e.check(Vt(_r,t)),e.cuid=t=>e.check(function(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...B(t)})}(kr,t)),e.cuid2=t=>e.check(function(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...B(t)})}(Sr,t)),e.ulid=t=>e.check(function(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...B(t)})}($r,t)),e.base64=t=>e.check(function(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...B(t)})}(Rr,t)),e.base64url=t=>e.check(function(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...B(t)})}(Ar,t)),e.xid=t=>e.check(function(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...B(t)})}(Er,t)),e.ksuid=t=>e.check(function(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...B(t)})}(Tr,t)),e.ipv4=t=>e.check(function(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...B(t)})}(Ir,t)),e.ipv6=t=>e.check(function(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...B(t)})}(xr,t)),e.cidrv4=t=>e.check(function(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...B(t)})}(Pr,t)),e.cidrv6=t=>e.check(function(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...B(t)})}(Cr,t)),e.e164=t=>e.check(function(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...B(t)})}(Or,t)),e.datetime=t=>e.check(rr(t)),e.date=t=>e.check(function(e){return function(e,t){return new e({type:"string",format:"date",check:"string_format",...B(t)})}(nr,e)}(t)),e.time=t=>e.check(function(e){return function(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...B(t)})}(sr,e)}(t)),e.duration=t=>e.check(function(e){return function(e,t){return new e({type:"string",format:"duration",check:"string_format",...B(t)})}(ir,e)}(t))});function mr(e){return function(e,t){return new e({type:"string",...B(t)})}(pr,e)}const fr=n("ZodStringFormat",(e,t)=>{je.init(e,t),hr.init(e,t)}),gr=n("ZodEmail",(e,t)=>{De.init(e,t),fr.init(e,t)}),_r=n("ZodGUID",(e,t)=>{Ue.init(e,t),fr.init(e,t)}),yr=n("ZodUUID",(e,t)=>{qe.init(e,t),fr.init(e,t)}),wr=n("ZodURL",(e,t)=>{Me.init(e,t),fr.init(e,t)}),vr=n("ZodEmoji",(e,t)=>{Le.init(e,t),fr.init(e,t)}),br=n("ZodNanoID",(e,t)=>{Ze.init(e,t),fr.init(e,t)}),kr=n("ZodCUID",(e,t)=>{Fe.init(e,t),fr.init(e,t)}),Sr=n("ZodCUID2",(e,t)=>{He.init(e,t),fr.init(e,t)}),$r=n("ZodULID",(e,t)=>{Ve.init(e,t),fr.init(e,t)}),Er=n("ZodXID",(e,t)=>{Ke.init(e,t),fr.init(e,t)}),Tr=n("ZodKSUID",(e,t)=>{Ge.init(e,t),fr.init(e,t)}),Ir=n("ZodIPv4",(e,t)=>{Ye.init(e,t),fr.init(e,t)}),xr=n("ZodIPv6",(e,t)=>{Xe.init(e,t),fr.init(e,t)}),Pr=n("ZodCIDRv4",(e,t)=>{et.init(e,t),fr.init(e,t)}),Cr=n("ZodCIDRv6",(e,t)=>{tt.init(e,t),fr.init(e,t)}),Rr=n("ZodBase64",(e,t)=>{nt.init(e,t),fr.init(e,t)}),Ar=n("ZodBase64URL",(e,t)=>{st.init(e,t),fr.init(e,t)}),Or=n("ZodE164",(e,t)=>{it.init(e,t),fr.init(e,t)}),Nr=n("ZodJWT",(e,t)=>{at.init(e,t),fr.init(e,t)}),zr=n("ZodNumber",(e,t)=>{ot.init(e,t),ur.init(e,t),e.gt=(t,r)=>e.check(Wt(t,r)),e.gte=(t,r)=>e.check(Bt(t,r)),e.min=(t,r)=>e.check(Bt(t,r)),e.lt=(t,r)=>e.check(Kt(t,r)),e.lte=(t,r)=>e.check(Gt(t,r)),e.max=(t,r)=>e.check(Gt(t,r)),e.int=t=>e.check(qr(t)),e.safe=t=>e.check(qr(t)),e.positive=t=>e.check(Wt(0,t)),e.nonnegative=t=>e.check(Bt(0,t)),e.negative=t=>e.check(Kt(0,t)),e.nonpositive=t=>e.check(Gt(0,t)),e.multipleOf=(t,r)=>e.check(Jt(t,r)),e.step=(t,r)=>e.check(Jt(t,r)),e.finite=()=>e;const r=e._zod.bag;e.minValue=Math.max(r.minimum??Number.NEGATIVE_INFINITY,r.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,e.maxValue=Math.min(r.maximum??Number.POSITIVE_INFINITY,r.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,e.isInt=(r.format??"").includes("int")||Number.isSafeInteger(r.multipleOf??.5),e.isFinite=!0,e.format=r.format??null});function jr(e){return function(e,t){return new e({type:"number",checks:[],...B(t)})}(zr,e)}const Ur=n("ZodNumberFormat",(e,t)=>{ct.init(e,t),zr.init(e,t)});function qr(e){return function(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...B(t)})}(Ur,e)}const Dr=n("ZodBoolean",(e,t)=>{dt.init(e,t),ur.init(e,t)});function Mr(e){return function(e,t){return new e({type:"boolean",...B(t)})}(Dr,e)}const Lr=n("ZodNull",(e,t)=>{lt.init(e,t),ur.init(e,t)});const Zr=n("ZodUnknown",(e,t)=>{ut.init(e,t),ur.init(e,t)});function Fr(){return new Zr({type:"unknown"})}const Hr=n("ZodNever",(e,t)=>{ht.init(e,t),ur.init(e,t)});const Vr=n("ZodArray",(e,t)=>{mt.init(e,t),ur.init(e,t),e.element=t.element,e.min=(t,r)=>e.check(Yt(t,r)),e.nonempty=t=>e.check(Yt(1,t)),e.max=(t,r)=>e.check(Qt(t,r)),e.length=(t,r)=>e.check(Xt(t,r)),e.unwrap=()=>e.element});function Kr(e,t){return function(e,t,r){return new e({type:"array",element:t,...B(r)})}(Vr,e,t)}const Gr=n("ZodObject",(e,t)=>{_t.init(e,t),ur.init(e,t),D(e,"shape",()=>t.shape),e.keyof=()=>an(Object.keys(e._zod.def.shape)),e.catchall=t=>e.clone({...e._zod.def,catchall:t}),e.passthrough=()=>e.clone({...e._zod.def,catchall:Fr()}),e.loose=()=>e.clone({...e._zod.def,catchall:Fr()}),e.strict=()=>{return e.clone({...e._zod.def,catchall:function(e,t){return new e({type:"never",...B(t)})}(Hr,t)});var t},e.strip=()=>e.clone({...e._zod.def,catchall:void 0}),e.extend=t=>function(e,t){if(!V(t))throw new Error("Invalid input to extend: expected a plain object");const r={...e._zod.def,get shape(){const r={...e._zod.def.shape,...t};return M(this,"shape",r),r},checks:[]};return W(e,r)}(e,t),e.merge=t=>function(e,t){return W(e,{...e._zod.def,get shape(){const r={...e._zod.def.shape,...t._zod.def.shape};return M(this,"shape",r),r},catchall:t._zod.def.catchall,checks:[]})}(e,t),e.pick=t=>function(e,t){const r={},n=e._zod.def;for(const e in t){if(!(e in n.shape))throw new Error(`Unrecognized key: "${e}"`);t[e]&&(r[e]=n.shape[e])}return W(e,{...e._zod.def,shape:r,checks:[]})}(e,t),e.omit=t=>function(e,t){const r={...e._zod.def.shape},n=e._zod.def;for(const e in t){if(!(e in n.shape))throw new Error(`Unrecognized key: "${e}"`);t[e]&&delete r[e]}return W(e,{...e._zod.def,shape:r,checks:[]})}(e,t),e.partial=(...t)=>function(e,t,r){const n=t._zod.def.shape,s={...n};if(r)for(const t in r){if(!(t in n))throw new Error(`Unrecognized key: "${t}"`);r[t]&&(s[t]=e?new e({type:"optional",innerType:n[t]}):n[t])}else for(const t in n)s[t]=e?new e({type:"optional",innerType:n[t]}):n[t];return W(t,{...t._zod.def,shape:s,checks:[]})}(un,e,t[0]),e.required=(...t)=>function(e,t,r){const n=t._zod.def.shape,s={...n};if(r)for(const t in r){if(!(t in s))throw new Error(`Unrecognized key: "${t}"`);r[t]&&(s[t]=new e({type:"nonoptional",innerType:n[t]}))}else for(const t in n)s[t]=new e({type:"nonoptional",innerType:n[t]});return W(t,{...t._zod.def,shape:s,checks:[]})}(_n,e,t[0])});function Wr(e,t){const r={type:"object",get shape(){return M(this,"shape",{...e}),this.shape},...B(t)};return new Gr(r)}function Br(e,t){return new Gr({type:"object",get shape(){return M(this,"shape",{...e}),this.shape},catchall:Fr(),...B(t)})}const Jr=n("ZodUnion",(e,t)=>{wt.init(e,t),ur.init(e,t),e.options=t.options});function Qr(e,t){return new Jr({type:"union",options:e,...B(t)})}const Yr=n("ZodDiscriminatedUnion",(e,t)=>{Jr.init(e,t),vt.init(e,t)});function Xr(e,t,r){return new Yr({type:"union",options:t,discriminator:e,...B(r)})}const en=n("ZodIntersection",(e,t)=>{bt.init(e,t),ur.init(e,t)});function tn(e,t){return new en({type:"intersection",left:e,right:t})}const rn=n("ZodRecord",(e,t)=>{$t.init(e,t),ur.init(e,t),e.keyType=t.keyType,e.valueType=t.valueType});function nn(e,t,r){return new rn({type:"record",keyType:e,valueType:t,...B(r)})}const sn=n("ZodEnum",(e,t)=>{Et.init(e,t),ur.init(e,t),e.enum=t.entries,e.options=Object.values(t.entries);const r=new Set(Object.keys(t.entries));e.extract=(e,n)=>{const s={};for(const n of e){if(!r.has(n))throw new Error(`Key ${n} not found in enum`);s[n]=t.entries[n]}return new sn({...t,checks:[],...B(n),entries:s})},e.exclude=(e,n)=>{const s={...t.entries};for(const t of e){if(!r.has(t))throw new Error(`Key ${t} not found in enum`);delete s[t]}return new sn({...t,checks:[],...B(n),entries:s})}});function an(e,t){const r=Array.isArray(e)?Object.fromEntries(e.map(e=>[e,e])):e;return new sn({type:"enum",entries:r,...B(t)})}const on=n("ZodLiteral",(e,t)=>{Tt.init(e,t),ur.init(e,t),e.values=new Set(t.values),Object.defineProperty(e,"value",{get(){if(t.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});function cn(e,t){return new on({type:"literal",values:Array.isArray(e)?e:[e],...B(t)})}const dn=n("ZodTransform",(e,t)=>{It.init(e,t),ur.init(e,t),e._zod.parse=(r,n)=>{r.addIssue=n=>{if("string"==typeof n)r.issues.push(re(n,r.value,t));else{const t=n;t.fatal&&(t.continue=!1),t.code??(t.code="custom"),t.input??(t.input=r.value),t.inst??(t.inst=e),t.continue??(t.continue=!0),r.issues.push(re(t))}};const s=t.transform(r.value,r);return s instanceof Promise?s.then(e=>(r.value=e,r)):(r.value=s,r)}});function ln(e){return new dn({type:"transform",transform:e})}const un=n("ZodOptional",(e,t)=>{xt.init(e,t),ur.init(e,t),e.unwrap=()=>e._zod.def.innerType});function hn(e){return new un({type:"optional",innerType:e})}const pn=n("ZodNullable",(e,t)=>{Pt.init(e,t),ur.init(e,t),e.unwrap=()=>e._zod.def.innerType});function mn(e){return new pn({type:"nullable",innerType:e})}const fn=n("ZodDefault",(e,t)=>{Ct.init(e,t),ur.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap}),gn=n("ZodPrefault",(e,t)=>{At.init(e,t),ur.init(e,t),e.unwrap=()=>e._zod.def.innerType}),_n=n("ZodNonOptional",(e,t)=>{Ot.init(e,t),ur.init(e,t),e.unwrap=()=>e._zod.def.innerType}),yn=n("ZodCatch",(e,t)=>{zt.init(e,t),ur.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap}),wn=n("ZodPipe",(e,t)=>{jt.init(e,t),ur.init(e,t),e.in=t.in,e.out=t.out});function vn(e,t){return new wn({type:"pipe",in:e,out:t})}const bn=n("ZodReadonly",(e,t)=>{qt.init(e,t),ur.init(e,t)}),kn=n("ZodCustom",(e,t)=>{Mt.init(e,t),ur.init(e,t)});function Sn(e,t){return vn(ln(e),t)}const $n="2025-11-25",En=[$n,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],Tn="io.modelcontextprotocol/related-task",In="2.0",xn=function(e,t){const r=B(void 0);return r.abort??(r.abort=!0),new e({type:"custom",check:"custom",fn:t,...r})}(kn,(e=>null!==e&&("object"==typeof e||"function"==typeof e))??(()=>!0),void 0),Pn=Qr([mr(),jr().int()]),Cn=mr(),Rn=(Br({ttl:jr().optional(),pollInterval:jr().optional()}),Wr({ttl:jr().optional()})),An=Wr({taskId:mr()}),On=Br({progressToken:Pn.optional(),[Tn]:An.optional()}),Nn=Wr({_meta:On.optional()}),zn=Nn.extend({task:Rn.optional()}),jn=Wr({method:mr(),params:Nn.loose().optional()}),Un=Wr({_meta:On.optional()}),qn=Wr({method:mr(),params:Un.loose().optional()}),Dn=Br({_meta:On.optional()}),Mn=Qr([mr(),jr().int()]),Ln=Wr({jsonrpc:cn(In),id:Mn,...jn.shape}).strict(),Zn=e=>Ln.safeParse(e).success,Fn=Wr({jsonrpc:cn(In),...qn.shape}).strict(),Hn=Wr({jsonrpc:cn(In),id:Mn,result:Dn}).strict(),Vn=e=>Hn.safeParse(e).success;var Kn;!function(e){e[e.ConnectionClosed=-32e3]="ConnectionClosed",e[e.RequestTimeout=-32001]="RequestTimeout",e[e.ParseError=-32700]="ParseError",e[e.InvalidRequest=-32600]="InvalidRequest",e[e.MethodNotFound=-32601]="MethodNotFound",e[e.InvalidParams=-32602]="InvalidParams",e[e.InternalError=-32603]="InternalError",e[e.UrlElicitationRequired=-32042]="UrlElicitationRequired"}(Kn||(Kn={}));const Gn=Wr({jsonrpc:cn(In),id:Mn.optional(),error:Wr({code:jr().int(),message:mr(),data:Fr().optional()})}).strict(),Wn=Qr([Ln,Fn,Hn,Gn]),Bn=(Qr([Hn,Gn]),Dn.strict()),Jn=Un.extend({requestId:Mn.optional(),reason:mr().optional()}),Qn=qn.extend({method:cn("notifications/cancelled"),params:Jn}),Yn=Wr({src:mr(),mimeType:mr().optional(),sizes:Kr(mr()).optional(),theme:an(["light","dark"]).optional()}),Xn=Wr({icons:Kr(Yn).optional()}),es=Wr({name:mr(),title:mr().optional()}),ts=es.extend({...es.shape,...Xn.shape,version:mr(),websiteUrl:mr().optional(),description:mr().optional()}),rs=tn(Wr({applyDefaults:Mr().optional()}),nn(mr(),Fr())),ns=Sn(e=>e&&"object"==typeof e&&!Array.isArray(e)&&0===Object.keys(e).length?{form:{}}:e,tn(Wr({form:rs.optional(),url:xn.optional()}),nn(mr(),Fr()).optional())),ss=Br({list:xn.optional(),cancel:xn.optional(),requests:Br({sampling:Br({createMessage:xn.optional()}).optional(),elicitation:Br({create:xn.optional()}).optional()}).optional()}),is=Br({list:xn.optional(),cancel:xn.optional(),requests:Br({tools:Br({call:xn.optional()}).optional()}).optional()}),as=Wr({experimental:nn(mr(),xn).optional(),sampling:Wr({context:xn.optional(),tools:xn.optional()}).optional(),elicitation:ns.optional(),roots:Wr({listChanged:Mr().optional()}).optional(),tasks:ss.optional(),extensions:nn(mr(),xn).optional()}),os=Nn.extend({protocolVersion:mr(),capabilities:as,clientInfo:ts}),cs=jn.extend({method:cn("initialize"),params:os}),ds=Wr({experimental:nn(mr(),xn).optional(),logging:xn.optional(),completions:xn.optional(),prompts:Wr({listChanged:Mr().optional()}).optional(),resources:Wr({subscribe:Mr().optional(),listChanged:Mr().optional()}).optional(),tools:Wr({listChanged:Mr().optional()}).optional(),tasks:is.optional(),extensions:nn(mr(),xn).optional()}),ls=Dn.extend({protocolVersion:mr(),capabilities:ds,serverInfo:ts,instructions:mr().optional()}),us=qn.extend({method:cn("notifications/initialized"),params:Un.optional()}),hs=jn.extend({method:cn("ping"),params:Nn.optional()}),ps=Wr({progress:jr(),total:hn(jr()),message:hn(mr())}),ms=Wr({...Un.shape,...ps.shape,progressToken:Pn}),fs=qn.extend({method:cn("notifications/progress"),params:ms}),gs=Nn.extend({cursor:Cn.optional()}),_s=jn.extend({params:gs.optional()}),ys=Dn.extend({nextCursor:Cn.optional()}),ws=an(["working","input_required","completed","failed","cancelled"]),vs=Wr({taskId:mr(),status:ws,ttl:Qr([jr(),function(e,t){return new e({type:"null",...B(t)})}(Lr,ia)]),createdAt:mr(),lastUpdatedAt:mr(),pollInterval:hn(jr()),statusMessage:hn(mr())}),bs=Dn.extend({task:vs}),ks=Un.merge(vs),Ss=qn.extend({method:cn("notifications/tasks/status"),params:ks}),$s=jn.extend({method:cn("tasks/get"),params:Nn.extend({taskId:mr()})}),Es=Dn.merge(vs),Ts=jn.extend({method:cn("tasks/result"),params:Nn.extend({taskId:mr()})}),Is=(Dn.loose(),_s.extend({method:cn("tasks/list")})),xs=ys.extend({tasks:Kr(vs)}),Ps=jn.extend({method:cn("tasks/cancel"),params:Nn.extend({taskId:mr()})}),Cs=Dn.merge(vs),Rs=Wr({uri:mr(),mimeType:hn(mr()),_meta:nn(mr(),Fr()).optional()}),As=Rs.extend({text:mr()}),Os=mr().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:"Invalid Base64 string"}),Ns=Rs.extend({blob:Os}),zs=an(["user","assistant"]),js=Wr({audience:Kr(zs).optional(),priority:jr().min(0).max(1).optional(),lastModified:rr({offset:!0}).optional()}),Us=Wr({...es.shape,...Xn.shape,uri:mr(),description:hn(mr()),mimeType:hn(mr()),size:hn(jr()),annotations:js.optional(),_meta:hn(Br({}))}),qs=Wr({...es.shape,...Xn.shape,uriTemplate:mr(),description:hn(mr()),mimeType:hn(mr()),annotations:js.optional(),_meta:hn(Br({}))}),Ds=_s.extend({method:cn("resources/list")}),Ms=ys.extend({resources:Kr(Us)}),Ls=_s.extend({method:cn("resources/templates/list")}),Zs=ys.extend({resourceTemplates:Kr(qs)}),Fs=Nn.extend({uri:mr()}),Hs=Fs,Vs=jn.extend({method:cn("resources/read"),params:Hs}),Ks=Dn.extend({contents:Kr(Qr([As,Ns]))}),Gs=qn.extend({method:cn("notifications/resources/list_changed"),params:Un.optional()}),Ws=Fs,Bs=jn.extend({method:cn("resources/subscribe"),params:Ws}),Js=Fs,Qs=jn.extend({method:cn("resources/unsubscribe"),params:Js}),Ys=Un.extend({uri:mr()}),Xs=qn.extend({method:cn("notifications/resources/updated"),params:Ys}),ei=Wr({name:mr(),description:hn(mr()),required:hn(Mr())}),ti=Wr({...es.shape,...Xn.shape,description:hn(mr()),arguments:hn(Kr(ei)),_meta:hn(Br({}))}),ri=_s.extend({method:cn("prompts/list")}),ni=ys.extend({prompts:Kr(ti)}),si=Nn.extend({name:mr(),arguments:nn(mr(),mr()).optional()}),ii=jn.extend({method:cn("prompts/get"),params:si}),ai=Wr({type:cn("text"),text:mr(),annotations:js.optional(),_meta:nn(mr(),Fr()).optional()}),oi=Wr({type:cn("image"),data:Os,mimeType:mr(),annotations:js.optional(),_meta:nn(mr(),Fr()).optional()}),ci=Wr({type:cn("audio"),data:Os,mimeType:mr(),annotations:js.optional(),_meta:nn(mr(),Fr()).optional()}),di=Wr({type:cn("tool_use"),name:mr(),id:mr(),input:nn(mr(),Fr()),_meta:nn(mr(),Fr()).optional()}),li=Wr({type:cn("resource"),resource:Qr([As,Ns]),annotations:js.optional(),_meta:nn(mr(),Fr()).optional()}),ui=Qr([ai,oi,ci,Us.extend({type:cn("resource_link")}),li]),hi=Wr({role:zs,content:ui}),pi=Dn.extend({description:mr().optional(),messages:Kr(hi)}),mi=qn.extend({method:cn("notifications/prompts/list_changed"),params:Un.optional()}),fi=Wr({title:mr().optional(),readOnlyHint:Mr().optional(),destructiveHint:Mr().optional(),idempotentHint:Mr().optional(),openWorldHint:Mr().optional()}),gi=Wr({taskSupport:an(["required","optional","forbidden"]).optional()}),_i=Wr({...es.shape,...Xn.shape,description:mr().optional(),inputSchema:Wr({type:cn("object"),properties:nn(mr(),xn).optional(),required:Kr(mr()).optional()}).catchall(Fr()),outputSchema:Wr({type:cn("object"),properties:nn(mr(),xn).optional(),required:Kr(mr()).optional()}).catchall(Fr()).optional(),annotations:fi.optional(),execution:gi.optional(),_meta:nn(mr(),Fr()).optional()}),yi=_s.extend({method:cn("tools/list")}),wi=ys.extend({tools:Kr(_i)}),vi=Dn.extend({content:Kr(ui).default([]),structuredContent:nn(mr(),Fr()).optional(),isError:Mr().optional()}),bi=(vi.or(Dn.extend({toolResult:Fr()})),zn.extend({name:mr(),arguments:nn(mr(),Fr()).optional()})),ki=jn.extend({method:cn("tools/call"),params:bi}),Si=qn.extend({method:cn("notifications/tools/list_changed"),params:Un.optional()}),$i=(Wr({autoRefresh:Mr().default(!0),debounceMs:jr().int().nonnegative().default(300)}),an(["debug","info","notice","warning","error","critical","alert","emergency"])),Ei=Nn.extend({level:$i}),Ti=jn.extend({method:cn("logging/setLevel"),params:Ei}),Ii=Un.extend({level:$i,logger:mr().optional(),data:Fr()}),xi=qn.extend({method:cn("notifications/message"),params:Ii}),Pi=Wr({name:mr().optional()}),Ci=Wr({hints:Kr(Pi).optional(),costPriority:jr().min(0).max(1).optional(),speedPriority:jr().min(0).max(1).optional(),intelligencePriority:jr().min(0).max(1).optional()}),Ri=Wr({mode:an(["auto","required","none"]).optional()}),Ai=Wr({type:cn("tool_result"),toolUseId:mr().describe("The unique identifier for the corresponding tool call."),content:Kr(ui).default([]),structuredContent:Wr({}).loose().optional(),isError:Mr().optional(),_meta:nn(mr(),Fr()).optional()}),Oi=Xr("type",[ai,oi,ci]),Ni=Xr("type",[ai,oi,ci,di,Ai]),zi=Wr({role:zs,content:Qr([Ni,Kr(Ni)]),_meta:nn(mr(),Fr()).optional()}),ji=zn.extend({messages:Kr(zi),modelPreferences:Ci.optional(),systemPrompt:mr().optional(),includeContext:an(["none","thisServer","allServers"]).optional(),temperature:jr().optional(),maxTokens:jr().int(),stopSequences:Kr(mr()).optional(),metadata:xn.optional(),tools:Kr(_i).optional(),toolChoice:Ri.optional()}),Ui=jn.extend({method:cn("sampling/createMessage"),params:ji}),qi=Dn.extend({model:mr(),stopReason:hn(an(["endTurn","stopSequence","maxTokens"]).or(mr())),role:zs,content:Oi}),Di=Dn.extend({model:mr(),stopReason:hn(an(["endTurn","stopSequence","maxTokens","toolUse"]).or(mr())),role:zs,content:Qr([Ni,Kr(Ni)])}),Mi=Wr({type:cn("boolean"),title:mr().optional(),description:mr().optional(),default:Mr().optional()}),Li=Wr({type:cn("string"),title:mr().optional(),description:mr().optional(),minLength:jr().optional(),maxLength:jr().optional(),format:an(["email","uri","date","date-time"]).optional(),default:mr().optional()}),Zi=Wr({type:an(["number","integer"]),title:mr().optional(),description:mr().optional(),minimum:jr().optional(),maximum:jr().optional(),default:jr().optional()}),Fi=Wr({type:cn("string"),title:mr().optional(),description:mr().optional(),enum:Kr(mr()),default:mr().optional()}),Hi=Wr({type:cn("string"),title:mr().optional(),description:mr().optional(),oneOf:Kr(Wr({const:mr(),title:mr()})),default:mr().optional()}),Vi=Wr({type:cn("string"),title:mr().optional(),description:mr().optional(),enum:Kr(mr()),enumNames:Kr(mr()).optional(),default:mr().optional()}),Ki=Qr([Fi,Hi]),Gi=Qr([Wr({type:cn("array"),title:mr().optional(),description:mr().optional(),minItems:jr().optional(),maxItems:jr().optional(),items:Wr({type:cn("string"),enum:Kr(mr())}),default:Kr(mr()).optional()}),Wr({type:cn("array"),title:mr().optional(),description:mr().optional(),minItems:jr().optional(),maxItems:jr().optional(),items:Wr({anyOf:Kr(Wr({const:mr(),title:mr()}))}),default:Kr(mr()).optional()})]),Wi=Qr([Vi,Ki,Gi]),Bi=Qr([Wi,Mi,Li,Zi]),Ji=Qr([zn.extend({mode:cn("form").optional(),message:mr(),requestedSchema:Wr({type:cn("object"),properties:nn(mr(),Bi),required:Kr(mr()).optional()})}),zn.extend({mode:cn("url"),message:mr(),elicitationId:mr(),url:mr().url()})]),Qi=jn.extend({method:cn("elicitation/create"),params:Ji}),Yi=Un.extend({elicitationId:mr()}),Xi=qn.extend({method:cn("notifications/elicitation/complete"),params:Yi}),ea=Dn.extend({action:an(["accept","decline","cancel"]),content:Sn(e=>null===e?void 0:e,nn(mr(),Qr([mr(),jr(),Mr(),Kr(mr())])).optional())}),ta=Wr({type:cn("ref/resource"),uri:mr()}),ra=Wr({type:cn("ref/prompt"),name:mr()}),na=Nn.extend({ref:Qr([ra,ta]),argument:Wr({name:mr(),value:mr()}),context:Wr({arguments:nn(mr(),mr()).optional()}).optional()}),sa=jn.extend({method:cn("completion/complete"),params:na});var ia;const aa=Dn.extend({completion:Br({values:Kr(mr()).max(100),total:hn(jr().int()),hasMore:hn(Mr())})}),oa=Wr({uri:mr().startsWith("file://"),name:mr().optional(),_meta:nn(mr(),Fr()).optional()}),ca=jn.extend({method:cn("roots/list"),params:Nn.optional()}),da=Dn.extend({roots:Kr(oa)}),la=qn.extend({method:cn("notifications/roots/list_changed"),params:Un.optional()});Qr([hs,cs,sa,Ti,ii,ri,Ds,Ls,Vs,Bs,Qs,ki,yi,$s,Ts,Is,Ps]),Qr([Qn,fs,us,la,Ss]),Qr([Bn,qi,Di,ea,da,Es,xs,bs]),Qr([hs,Ui,Qi,ca,$s,Ts,Is,Ps]),Qr([Qn,fs,xi,Xs,Gs,Si,mi,Ss,Xi]),Qr([Bn,ls,aa,pi,ni,Ms,Zs,Ks,vi,wi,Es,xs,bs]);class ua extends Error{constructor(e,t,r){super(`MCP error ${e}: ${t}`),this.code=e,this.data=r,this.name="McpError"}static fromError(e,t,r){if(e===Kn.UrlElicitationRequired&&r){const e=r;if(e.elicitations)return new ha(e.elicitations,t)}return new ua(e,t,r)}}class ha extends ua{constructor(e,t=`URL elicitation${e.length>1?"s":""} required`){super(Kn.UrlElicitationRequired,t,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}}const pa={none:0,error:1,warn:2,info:3,debug:4},ma={error:"error",warn:"warn",info:"info",log:"info",debug:"debug"},fa=(e,t)=>pa[e]<=pa[t],ga=e=>"string"==typeof e?e:JSON.stringify(e),_a=(e,t)=>{let r=`[${ga(e)}]`;return typeof window<"u"?{text:`%c${r}`,style:`color: ${t.color||"#00bcd4"}; font-weight: bold;`}:{text:r}},ya=(e,t,r,n)=>(...s)=>{if(!fa(ma[e],n()))return;if(!t)return void console[e](...s);let{text:i,style:a}=_a(t,r);a?console[e](i,a,...s):console[e](i,...s)},wa=(e,t)=>{let r=t.logLevel??"debug",n=()=>r;return{log:ya("log",e,t,n),info:ya("info",e,t,n),warn:ya("warn",e,t,n),error:ya("error",e,t,n),debug:ya("debug",e,t,n),setLogLevel:e=>{r=e},extend:n=>wa(e?((e,t)=>`${ga(e)} > ${ga(t)}`)(e,n):n,{...t,logLevel:r})}},va=(e,t)=>wa(e,{color:"#00bcd4",logLevel:"debug",...t}),ba=va("angie-sdk",{color:"#00BCD4",logLevel:"error"}),ka=e=>ba.extend(e);var Sa,$a,Ea,Ta,Ia,xa,Pa,Ca;(Sa||(Sa={})).POST_MESSAGE="postMessage",($a||($a={})).POST_MESSAGE="postMessage",function(e){e.STREAMABLE_HTTP="streamableHttp",e.SSE="sse"}(Ea||(Ea={})),function(e){e.LOCAL="local",e.REMOTE="remote"}(Ta||(Ta={})),function(e){e.AGENT="agent",e.PLAN="plan",e.ASK="ask",e.SUPER_ADMIN="super-admin"}(Ia||(Ia={})),function(e){e.SDK_ANGIE_READY_PING="sdk-angie-ready-ping",e.SDK_ANGIE_REFRESH_PING="sdk-angie-refresh-ping",e.SDK_ANGIE_ALL_SERVERS_REGISTERED="sdk-angie-all-servers-registered",e.SDK_REQUEST_CLIENT_CREATION="sdk-request-client-creation",e.SDK_REQUEST_INIT_SERVER="sdk-request-init-server",e.SDK_TRIGGER_ANGIE="sdk-trigger-angie",e.SDK_TRIGGER_ANGIE_RESPONSE="sdk-trigger-angie-response",e.ANGIE_SIDEBAR_RESIZED="angie-sidebar-resized",e.ANGIE_SIDEBAR_TOGGLED="angie-sidebar-toggled",e.ANGIE_CHAT_TOGGLE="angie-chat-toggle",e.ANGIE_STUDIO_TOGGLE="angie-studio-toggle",e.ANGIE_NAVIGATE_TO_URL="angie/navigate-to-url",e.ANGIE_PAGE_RELOAD="angie/page-reload",e.ANGIE_DISABLE_NAVIGATION_PREVENTION="angie/disable-navigation-prevention",e.ANGIE_NAVIGATE_AFTER_RESPONSE="angie/navigate-after-response",e.ANGIE_SET_INTERACTION_MODE="angie/set-interaction-mode"}(xa||(xa={})),function(e){e.SET="ANGIE_SET_LOCALSTORAGE",e.GET="ANGIE_GET_LOCALSTORAGE"}(Pa||(Pa={})),function(e){e.RESET_HASH="reset-hash",e.HOST_READY="host/ready",e.ANGIE_LOADED="angie/loaded",e.ANGIE_READY="angie/ready"}(Ca||(Ca={}));const Ra=ka("angie-detector");class Aa{isAngieReady=!1;readyPromise;readyResolve;getInstanceId;constructor(e){if(this.getInstanceId=e,this.readyPromise=new Promise(e=>{this.readyResolve=e}),"undefined"==typeof window)return;let t=0;const r=()=>{if(this.isAngieReady||t>=500)return void(!this.isAngieReady&&t>=500&&this.handleDetectionTimeout());const e=new MessageChannel;e.port1.onmessage=t=>{this.handleAngieReady(t.data),e.port1.close(),e.port2.close()};const n={type:xa.SDK_ANGIE_READY_PING,payload:{instanceId:this.getInstanceId?.()},timestamp:Date.now()};window.postMessage(n,window.location.origin,[e.port2]),t++,setTimeout(r,500)};r()}handleAngieReady(e){this.isAngieReady=!0;const t={isReady:!0,version:e.version,capabilities:e.capabilities};this.readyResolve&&this.readyResolve(t)}handleDetectionTimeout(){this.readyResolve&&this.readyResolve({isReady:!1}),Ra.warn("Detection timeout - Angie may not be available")}isReady(){return this.isAngieReady}async waitForReady(){return this.readyPromise}async waitUntilReady(e){return this.isAngieReady?this.readyPromise:Promise.race([this.readyPromise,new Promise(t=>{setTimeout(()=>t({isReady:!1}),e)})])}}class Oa{sessionId;onmessage;onerror;onclose;_port;_started=!1;_closed=!1;constructor(e){if(!e)throw new Error("MessagePort is required");this._port=e,this._port.onmessage=e=>{try{const t=Wn.parse(e.data);this.onmessage?.(t)}catch(e){const t=new Error(`Failed to parse message: ${e}`);this.onerror?.(t)}},this._port.onmessageerror=e=>{const t=new Error(`MessagePort error: ${JSON.stringify(e)}`);this.onerror?.(t)}}async start(){if(this._started)throw new Error("BrowserContextTransport already started! If using Client or Server class, note that connect() calls start() automatically.");if(this._closed)throw new Error("Cannot start a closed BrowserContextTransport");this._started=!0,this._port.start()}async send(e){if(this._closed)throw new Error("Cannot send on a closed BrowserContextTransport");return new Promise((t,r)=>{try{this._port.postMessage(e),t()}catch(e){const t=e instanceof Error?e:new Error(String(e));this.onerror?.(t),r(t)}})}async close(){this._closed||(this._closed=!0,this._port.close(),this.onclose?.())}}class Na{async requestClientCreation(e){const{config:t}=e,r={serverId:e.id,serverName:t.name,serverTitle:t.title,serverVersion:t.version,description:t.description,transport:t.transport||$a.POST_MESSAGE,capabilities:t.capabilities,instanceId:e.instanceId};return"type"in t&&"remote"===t.type&&(r.remote={url:t.url}),new Promise((e,t)=>{const n=new MessageChannel,s=setTimeout(()=>{t(new Error("Client creation request timed out after 15000ms"))},15e3);n.port1.onmessage=t=>{clearTimeout(s),e(t.data)};const i={type:xa.SDK_REQUEST_CLIENT_CREATION,payload:r,timestamp:Date.now()};window.postMessage(i,window.location.origin,[n.port2])})}}const za="angie-sidebar-container",ja="angie-iframe",Ua=()=>({open:!1,iframe:null,iframeUrlObject:null,containerId:za,instanceId:"",appId:void 0,layout:"",iframeElementId:ja}),qa=Ua();class Da extends Error{}Da.prototype.name="InvalidTokenError";var Ma,La,Za,Fa={debug:()=>{},info:()=>{},warn:()=>{},error:()=>{}},Ha=(e=>(e[e.NONE=0]="NONE",e[e.ERROR=1]="ERROR",e[e.WARN=2]="WARN",e[e.INFO=3]="INFO",e[e.DEBUG=4]="DEBUG",e))(Ha||{});(Za=Ha||(Ha={})).reset=function(){Ma=3,La=Fa},Za.setLevel=function(e){if(!(0<=e&&e<=4))throw new Error("Invalid log level");Ma=e},Za.setLogger=function(e){La=e};var Va=class e{constructor(e){this._name=e}debug(...t){Ma>=4&&La.debug(e._format(this._name,this._method),...t)}info(...t){Ma>=3&&La.info(e._format(this._name,this._method),...t)}warn(...t){Ma>=2&&La.warn(e._format(this._name,this._method),...t)}error(...t){Ma>=1&&La.error(e._format(this._name,this._method),...t)}throw(e){throw this.error(e),e}create(e){const t=Object.create(this);return t._method=e,t.debug("begin"),t}static createStatic(t,r){const n=new e(`${t}.${r}`);return n.debug("begin"),n}static _format(e,t){const r=`[${e}]`;return t?`${r} ${t}:`:r}static debug(t,...r){Ma>=4&&La.debug(e._format(t),...r)}static info(t,...r){Ma>=3&&La.info(e._format(t),...r)}static warn(t,...r){Ma>=2&&La.warn(e._format(t),...r)}static error(t,...r){Ma>=1&&La.error(e._format(t),...r)}};Ha.reset();var Ka=class{static decode(e){try{return function(e,t){if("string"!=typeof e)throw new Da("Invalid token specified: must be a string");t||(t={});const r=!0===t.header?0:1,n=e.split(".")[r];if("string"!=typeof n)throw new Da(`Invalid token specified: missing part #${r+1}`);let s;try{s=function(e){let t=e.replace(/-/g,"+").replace(/_/g,"/");switch(t.length%4){case 0:break;case 2:t+="==";break;case 3:t+="=";break;default:throw new Error("base64 string is not of the correct length")}try{return function(e){return decodeURIComponent(atob(e).replace(/(.)/g,(e,t)=>{let r=t.charCodeAt(0).toString(16).toUpperCase();return r.length<2&&(r="0"+r),"%"+r}))}(t)}catch(e){return atob(t)}}(n)}catch(e){throw new Da(`Invalid token specified: invalid base64 for part #${r+1} (${e.message})`)}try{return JSON.parse(s)}catch(e){throw new Da(`Invalid token specified: invalid json for part #${r+1} (${e.message})`)}}(e)}catch(e){throw Va.error("JwtUtils.decode",e),e}}static async generateSignedJwt(e,t,r){const n=`${Ba.encodeBase64Url((new TextEncoder).encode(JSON.stringify(e)))}.${Ba.encodeBase64Url((new TextEncoder).encode(JSON.stringify(t)))}`,s=await window.crypto.subtle.sign({name:"ECDSA",hash:{name:"SHA-256"}},r,(new TextEncoder).encode(n));return`${n}.${Ba.encodeBase64Url(new Uint8Array(s))}`}static async generateSignedJwtWithHmac(e,t,r){const n=`${Ba.encodeBase64Url((new TextEncoder).encode(JSON.stringify(e)))}.${Ba.encodeBase64Url((new TextEncoder).encode(JSON.stringify(t)))}`,s=await window.crypto.subtle.sign("HMAC",r,(new TextEncoder).encode(n));return`${n}.${Ba.encodeBase64Url(new Uint8Array(s))}`}},Ga=e=>btoa([...new Uint8Array(e)].map(e=>String.fromCharCode(e)).join("")),Wa=class e{static _randomWord(){const e=new Uint32Array(1);return crypto.getRandomValues(e),e[0]}static generateUUIDv4(){return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,t=>(+t^e._randomWord()&15>>+t/4).toString(16)).replace(/-/g,"")}static generateCodeVerifier(){return e.generateUUIDv4()+e.generateUUIDv4()+e.generateUUIDv4()}static async generateCodeChallenge(e){if(!crypto.subtle)throw new Error("Crypto.subtle is available only in secure contexts (HTTPS).");try{const t=(new TextEncoder).encode(e),r=await crypto.subtle.digest("SHA-256",t);return Ga(r).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}catch(e){throw Va.error("CryptoUtils.generateCodeChallenge",e),e}}static generateBasicAuth(e,t){const r=(new TextEncoder).encode([e,t].join(":"));return Ga(r)}static async hash(e,t){const r=(new TextEncoder).encode(t),n=await crypto.subtle.digest(e,r);return new Uint8Array(n)}static async customCalculateJwkThumbprint(t){let r;switch(t.kty){case"RSA":r={e:t.e,kty:t.kty,n:t.n};break;case"EC":r={crv:t.crv,kty:t.kty,x:t.x,y:t.y};break;case"OKP":r={crv:t.crv,kty:t.kty,x:t.x};break;case"oct":r={crv:t.k,kty:t.kty};break;default:throw new Error("Unknown jwk type")}const n=await e.hash("SHA-256",JSON.stringify(r));return e.encodeBase64Url(n)}static async generateDPoPProof({url:t,accessToken:r,httpMethod:n,keyPair:s,nonce:i}){let a,o;const c={jti:window.crypto.randomUUID(),htm:null!=n?n:"GET",htu:t,iat:Math.floor(Date.now()/1e3)};r&&(a=await e.hash("SHA-256",r),o=e.encodeBase64Url(a),c.ath=o),i&&(c.nonce=i);try{const e=await crypto.subtle.exportKey("jwk",s.publicKey),t={alg:"ES256",typ:"dpop+jwt",jwk:{crv:e.crv,kty:e.kty,x:e.x,y:e.y}};return await Ka.generateSignedJwt(t,c,s.privateKey)}catch(e){throw e instanceof TypeError?new Error(`Error exporting dpop public key: ${e.message}`):e}}static async generateDPoPJkt(t){try{const r=await crypto.subtle.exportKey("jwk",t.publicKey);return await e.customCalculateJwkThumbprint(r)}catch(e){throw e instanceof TypeError?new Error(`Could not retrieve dpop keys from storage: ${e.message}`):e}}static async generateDPoPKeys(){return await window.crypto.subtle.generateKey({name:"ECDSA",namedCurve:"P-256"},!1,["sign","verify"])}static async generateClientAssertionJwt(t,r,n,s="HS256"){const i=Math.floor(Date.now()/1e3),a={alg:s,typ:"JWT"},o={iss:t,sub:t,aud:n,jti:e.generateUUIDv4(),exp:i+300,iat:i},c={HS256:"SHA-256",HS384:"SHA-384",HS512:"SHA-512"}[s];if(!c)throw new Error(`Unsupported algorithm: ${s}. Supported algorithms are: HS256, HS384, HS512`);const d=new TextEncoder,l=await crypto.subtle.importKey("raw",d.encode(r),{name:"HMAC",hash:c},!1,["sign"]);return await Ka.generateSignedJwtWithHmac(a,o,l)}};Wa.encodeBase64Url=e=>Ga(e).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_");var Ba=Wa,Ja=class{constructor(e){this._name=e,this._callbacks=[],this._logger=new Va(`Event('${this._name}')`)}addHandler(e){return this._callbacks.push(e),()=>this.removeHandler(e)}removeHandler(e){const t=this._callbacks.lastIndexOf(e);t>=0&&this._callbacks.splice(t,1)}async raise(...e){this._logger.debug("raise:",...e);for(const t of this._callbacks)await t(...e)}},Qa=class{static center({...e}){var t;return null==e.width&&(e.width=null!=(t=[800,720,600,480].find(e=>e<=window.outerWidth/1.618))?t:360),null!=e.left||(e.left=Math.max(0,Math.round(window.screenX+(window.outerWidth-e.width)/2))),null!=e.height&&(null!=e.top||(e.top=Math.max(0,Math.round(window.screenY+(window.outerHeight-e.height)/2)))),e}static serialize(e){return Object.entries(e).filter(([,e])=>null!=e).map(([e,t])=>`${e}=${"boolean"!=typeof t?t:t?"yes":"no"}`).join(",")}},Ya=class e extends Ja{constructor(){super(...arguments),this._logger=new Va(`Timer('${this._name}')`),this._timerHandle=null,this._expiration=0,this._callback=()=>{const t=this._expiration-e.getEpochTime();this._logger.debug("timer completes in",t),this._expiration<=e.getEpochTime()&&(this.cancel(),super.raise())}}static getEpochTime(){return Math.floor(Date.now()/1e3)}init(t){const r=this._logger.create("init");t=Math.max(Math.floor(t),1);const n=e.getEpochTime()+t;if(this.expiration===n&&this._timerHandle)return void r.debug("skipping since already initialized for expiration at",this.expiration);this.cancel(),r.debug("using duration",t),this._expiration=n;const s=Math.min(t,5);this._timerHandle=setInterval(this._callback,1e3*s)}get expiration(){return this._expiration}cancel(){this._logger.create("cancel"),this._timerHandle&&(clearInterval(this._timerHandle),this._timerHandle=null)}},Xa=class{static readParams(e,t="query"){if(!e)throw new TypeError("Invalid URL");const r=new URL(e,"http://127.0.0.1")["fragment"===t?"hash":"search"];return new URLSearchParams(r.slice(1))}},eo=";",to=class extends Error{constructor(e,t){var r,n,s;if(super(e.error_description||e.error||""),this.form=t,this.name="ErrorResponse",!e.error)throw Va.error("ErrorResponse","No error passed"),new Error("No error passed");this.error=e.error,this.error_description=null!=(r=e.error_description)?r:null,this.error_uri=null!=(n=e.error_uri)?n:null,this.state=e.userState,this.session_state=null!=(s=e.session_state)?s:null,this.url_state=e.url_state}},ro=class extends Error{constructor(e){super(e),this.name="ErrorTimeout"}},no=class{constructor(e){this._logger=new Va("AccessTokenEvents"),this._expiringTimer=new Ya("Access token expiring"),this._expiredTimer=new Ya("Access token expired"),this._expiringNotificationTimeInSeconds=e.expiringNotificationTimeInSeconds}async load(e){const t=this._logger.create("load");if(e.access_token&&void 0!==e.expires_in){const r=e.expires_in;if(t.debug("access token present, remaining duration:",r),r>0){let e=r-this._expiringNotificationTimeInSeconds;e<=0&&(e=1),t.debug("registering expiring timer, raising in",e,"seconds"),this._expiringTimer.init(e)}else t.debug("canceling existing expiring timer because we're past expiration."),this._expiringTimer.cancel();const n=r+1;t.debug("registering expired timer, raising in",n,"seconds"),this._expiredTimer.init(n)}else this._expiringTimer.cancel(),this._expiredTimer.cancel()}async unload(){this._logger.debug("unload: canceling existing access token timers"),this._expiringTimer.cancel(),this._expiredTimer.cancel()}addAccessTokenExpiring(e){return this._expiringTimer.addHandler(e)}removeAccessTokenExpiring(e){this._expiringTimer.removeHandler(e)}addAccessTokenExpired(e){return this._expiredTimer.addHandler(e)}removeAccessTokenExpired(e){this._expiredTimer.removeHandler(e)}},so=class{constructor(e,t,r,n,s){this._callback=e,this._client_id=t,this._intervalInSeconds=n,this._stopOnError=s,this._logger=new Va("CheckSessionIFrame"),this._timer=null,this._session_state=null,this._message=e=>{e.origin===this._frame_origin&&e.source===this._frame.contentWindow&&("error"===e.data?(this._logger.error("error message from check session op iframe"),this._stopOnError&&this.stop()):"changed"===e.data?(this._logger.debug("changed message from check session op iframe"),this.stop(),this._callback()):this._logger.debug(e.data+" message from check session op iframe"))};const i=new URL(r);this._frame_origin=i.origin,this._frame=window.document.createElement("iframe"),this._frame.style.visibility="hidden",this._frame.style.position="fixed",this._frame.style.left="-1000px",this._frame.style.top="0",this._frame.width="0",this._frame.height="0",this._frame.src=i.href}load(){return new Promise(e=>{this._frame.onload=()=>{e()},window.document.body.appendChild(this._frame),window.addEventListener("message",this._message,!1)})}start(e){if(this._session_state===e)return;this._logger.create("start"),this.stop(),this._session_state=e;const t=()=>{this._frame.contentWindow&&this._session_state&&this._frame.contentWindow.postMessage(this._client_id+" "+this._session_state,this._frame_origin)};t(),this._timer=setInterval(t,1e3*this._intervalInSeconds)}stop(){this._logger.create("stop"),this._session_state=null,this._timer&&(clearInterval(this._timer),this._timer=null)}},io=class{constructor(){this._logger=new Va("InMemoryWebStorage"),this._data={}}clear(){this._logger.create("clear"),this._data={}}getItem(e){return this._logger.create(`getItem('${e}')`),this._data[e]}setItem(e,t){this._logger.create(`setItem('${e}')`),this._data[e]=t}removeItem(e){this._logger.create(`removeItem('${e}')`),delete this._data[e]}get length(){return Object.getOwnPropertyNames(this._data).length}key(e){return Object.getOwnPropertyNames(this._data)[e]}},ao=class extends Error{constructor(e,t){super(t),this.name="ErrorDPoPNonce",this.nonce=e}},oo=class{constructor(e=[],t=null,r={}){this._jwtHandler=t,this._extraHeaders=r,this._logger=new Va("JsonService"),this._contentTypes=[],this._contentTypes.push(...e,"application/json"),t&&this._contentTypes.push("application/jwt")}async fetchWithTimeout(e,t={}){const{timeoutInSeconds:r,...n}=t;if(!r)return await fetch(e,n);const s=new AbortController,i=setTimeout(()=>s.abort(),1e3*r);try{return await fetch(e,{...t,signal:s.signal})}catch(e){if(e instanceof DOMException&&"AbortError"===e.name)throw new ro("Network timed out");throw e}finally{clearTimeout(i)}}async getJson(e,{token:t,credentials:r,timeoutInSeconds:n}={}){const s=this._logger.create("getJson"),i={Accept:this._contentTypes.join(", ")};let a;t&&(s.debug("token passed, setting Authorization header"),i.Authorization="Bearer "+t),this._appendExtraHeaders(i);try{s.debug("url:",e),a=await this.fetchWithTimeout(e,{method:"GET",headers:i,timeoutInSeconds:n,credentials:r})}catch(e){throw s.error("Network Error"),e}s.debug("HTTP response received, status",a.status);const o=a.headers.get("Content-Type");if(o&&!this._contentTypes.find(e=>o.startsWith(e))&&s.throw(new Error(`Invalid response Content-Type: ${null!=o?o:"undefined"}, from URL: ${e}`)),a.ok&&this._jwtHandler&&(null==o?void 0:o.startsWith("application/jwt")))return await this._jwtHandler(await a.text());let c;try{c=await a.json()}catch(e){if(s.error("Error parsing JSON response",e),a.ok)throw e;throw new Error(`${a.statusText} (${a.status})`)}if(!a.ok){if(s.error("Error from server:",c),c.error)throw new to(c);throw new Error(`${a.statusText} (${a.status}): ${JSON.stringify(c)}`)}return c}async postForm(e,{body:t,basicAuth:r,timeoutInSeconds:n,initCredentials:s,extraHeaders:i}){const a=this._logger.create("postForm"),o={Accept:this._contentTypes.join(", "),"Content-Type":"application/x-www-form-urlencoded",...i};let c;void 0!==r&&(o.Authorization="Basic "+r),this._appendExtraHeaders(o);try{a.debug("url:",e),c=await this.fetchWithTimeout(e,{method:"POST",headers:o,body:t,timeoutInSeconds:n,credentials:s})}catch(e){throw a.error("Network error"),e}a.debug("HTTP response received, status",c.status);const d=c.headers.get("Content-Type");if(d&&!this._contentTypes.find(e=>d.startsWith(e)))throw new Error(`Invalid response Content-Type: ${null!=d?d:"undefined"}, from URL: ${e}`);const l=await c.text();let u={};if(l)try{u=JSON.parse(l)}catch(e){if(a.error("Error parsing JSON response",e),c.ok)throw e;throw new Error(`${c.statusText} (${c.status})`)}if(!c.ok){if(a.error("Error from server:",u),c.headers.has("dpop-nonce")){const e=c.headers.get("dpop-nonce");throw new ao(e,`${JSON.stringify(u)}`)}if(u.error)throw new to(u,t);throw new Error(`${c.statusText} (${c.status}): ${JSON.stringify(u)}`)}return u}_appendExtraHeaders(e){const t=this._logger.create("appendExtraHeaders"),r=Object.keys(this._extraHeaders),n=["accept","content-type"],s=["authorization"];0!==r.length&&r.forEach(r=>{if(n.includes(r.toLocaleLowerCase()))return void t.warn("Protected header could not be set",r,n);if(s.includes(r.toLocaleLowerCase())&&Object.keys(e).includes(r))return void t.warn("Header could not be overridden",r,s);const i="function"==typeof this._extraHeaders[r]?this._extraHeaders[r]():this._extraHeaders[r];i&&""!==i&&(e[r]=i)})}},co=class{constructor(e){this._settings=e,this._logger=new Va("MetadataService"),this._signingKeys=null,this._metadata=null,this._metadataUrl=this._settings.metadataUrl,this._jsonService=new oo(["application/jwk-set+json"],null,this._settings.extraHeaders),this._settings.signingKeys&&(this._logger.debug("using signingKeys from settings"),this._signingKeys=this._settings.signingKeys),this._settings.metadata&&(this._logger.debug("using metadata from settings"),this._metadata=this._settings.metadata),this._settings.fetchRequestCredentials&&(this._logger.debug("using fetchRequestCredentials from settings"),this._fetchRequestCredentials=this._settings.fetchRequestCredentials)}resetSigningKeys(){this._signingKeys=null}async getMetadata(){const e=this._logger.create("getMetadata");if(this._metadata)return e.debug("using cached values"),this._metadata;if(!this._metadataUrl)throw e.throw(new Error("No authority or metadataUrl configured on settings")),null;e.debug("getting metadata from",this._metadataUrl);const t=await this._jsonService.getJson(this._metadataUrl,{credentials:this._fetchRequestCredentials,timeoutInSeconds:this._settings.requestTimeoutInSeconds});return e.debug("merging remote JSON with seed metadata"),this._metadata=Object.assign({},t,this._settings.metadataSeed),this._metadata}getIssuer(){return this._getMetadataProperty("issuer")}getAuthorizationEndpoint(){return this._getMetadataProperty("authorization_endpoint")}getUserInfoEndpoint(){return this._getMetadataProperty("userinfo_endpoint")}getTokenEndpoint(e=!0){return this._getMetadataProperty("token_endpoint",e)}getCheckSessionIframe(){return this._getMetadataProperty("check_session_iframe",!0)}getEndSessionEndpoint(){return this._getMetadataProperty("end_session_endpoint",!0)}getRevocationEndpoint(e=!0){return this._getMetadataProperty("revocation_endpoint",e)}getKeysEndpoint(e=!0){return this._getMetadataProperty("jwks_uri",e)}async _getMetadataProperty(e,t=!1){const r=this._logger.create(`_getMetadataProperty('${e}')`),n=await this.getMetadata();if(r.debug("resolved"),void 0===n[e]){if(!0===t)return void r.warn("Metadata does not contain optional property");r.throw(new Error("Metadata does not contain property "+e))}return n[e]}async getSigningKeys(){const e=this._logger.create("getSigningKeys");if(this._signingKeys)return e.debug("returning signingKeys from cache"),this._signingKeys;const t=await this.getKeysEndpoint(!1);e.debug("got jwks_uri",t);const r=await this._jsonService.getJson(t,{timeoutInSeconds:this._settings.requestTimeoutInSeconds});if(e.debug("got key set",r),!Array.isArray(r.keys))throw e.throw(new Error("Missing keys on keyset")),null;return this._signingKeys=r.keys,this._signingKeys}},lo=class{constructor({prefix:e="oidc.",store:t=localStorage}={}){this._logger=new Va("WebStorageStateStore"),this._store=t,this._prefix=e}async set(e,t){this._logger.create(`set('${e}')`),e=this._prefix+e,await this._store.setItem(e,t)}async get(e){return this._logger.create(`get('${e}')`),e=this._prefix+e,await this._store.getItem(e)}async remove(e){this._logger.create(`remove('${e}')`),e=this._prefix+e;const t=await this._store.getItem(e);return await this._store.removeItem(e),t}async getAllKeys(){this._logger.create("getAllKeys");const e=await this._store.length,t=[];for(let r=0;r<e;r++){const e=await this._store.key(r);e&&0===e.indexOf(this._prefix)&&t.push(e.substr(this._prefix.length))}return t}},uo=class{constructor({authority:e,metadataUrl:t,metadata:r,signingKeys:n,metadataSeed:s,client_id:i,client_secret:a,response_type:o="code",scope:c="openid",redirect_uri:d,post_logout_redirect_uri:l,client_authentication:u="client_secret_post",token_endpoint_auth_signing_alg:h="HS256",prompt:p,display:m,max_age:f,ui_locales:g,acr_values:_,resource:y,response_mode:w,filterProtocolClaims:v=!0,loadUserInfo:b=!1,requestTimeoutInSeconds:k,staleStateAgeInSeconds:S=900,mergeClaimsStrategy:$={array:"replace"},disablePKCE:E=!1,stateStore:T,revokeTokenAdditionalContentTypes:I,fetchRequestCredentials:x,refreshTokenAllowedScope:P,extraQueryParams:C={},extraTokenParams:R={},extraHeaders:A={},dpop:O,omitScopeWhenRequesting:N=!1}){var z;if(this.authority=e,t?this.metadataUrl=t:(this.metadataUrl=e,e&&(this.metadataUrl.endsWith("/")||(this.metadataUrl+="/"),this.metadataUrl+=".well-known/openid-configuration")),this.metadata=r,this.metadataSeed=s,this.signingKeys=n,this.client_id=i,this.client_secret=a,this.response_type=o,this.scope=c,this.redirect_uri=d,this.post_logout_redirect_uri=l,this.client_authentication=u,this.token_endpoint_auth_signing_alg=h,this.prompt=p,this.display=m,this.max_age=f,this.ui_locales=g,this.acr_values=_,this.resource=y,this.response_mode=w,this.filterProtocolClaims=null==v||v,this.loadUserInfo=!!b,this.staleStateAgeInSeconds=S,this.mergeClaimsStrategy=$,this.omitScopeWhenRequesting=N,this.disablePKCE=!!E,this.revokeTokenAdditionalContentTypes=I,this.fetchRequestCredentials=x||"same-origin",this.requestTimeoutInSeconds=k,T)this.stateStore=T;else{const e="undefined"!=typeof window?window.localStorage:new io;this.stateStore=new lo({store:e})}if(this.refreshTokenAllowedScope=P,this.extraQueryParams=C,this.extraTokenParams=R,this.extraHeaders=A,this.dpop=O,this.dpop&&!(null==(z=this.dpop)?void 0:z.store))throw new Error("A DPoPStore is required when dpop is enabled")}},ho=class{constructor(e,t){this._settings=e,this._metadataService=t,this._logger=new Va("UserInfoService"),this._getClaimsFromJwt=async e=>{const t=this._logger.create("_getClaimsFromJwt");try{const r=Ka.decode(e);return t.debug("JWT decoding successful"),r}catch(e){throw t.error("Error parsing JWT response"),e}},this._jsonService=new oo(void 0,this._getClaimsFromJwt,this._settings.extraHeaders)}async getClaims(e){const t=this._logger.create("getClaims");e||this._logger.throw(new Error("No token passed"));const r=await this._metadataService.getUserInfoEndpoint();t.debug("got userinfo url",r);const n=await this._jsonService.getJson(r,{token:e,credentials:this._settings.fetchRequestCredentials,timeoutInSeconds:this._settings.requestTimeoutInSeconds});return t.debug("got claims",n),n}},po=class{constructor(e,t){this._settings=e,this._metadataService=t,this._logger=new Va("TokenClient"),this._jsonService=new oo(this._settings.revokeTokenAdditionalContentTypes,null,this._settings.extraHeaders)}async exchangeCode({grant_type:e="authorization_code",redirect_uri:t=this._settings.redirect_uri,client_id:r=this._settings.client_id,client_secret:n=this._settings.client_secret,extraHeaders:s,...i}){const a=this._logger.create("exchangeCode");r||a.throw(new Error("A client_id is required")),t||a.throw(new Error("A redirect_uri is required")),i.code||a.throw(new Error("A code is required"));const o=new URLSearchParams({grant_type:e,redirect_uri:t});for(const[e,t]of Object.entries(i))null!=t&&o.set(e,t);if(("client_secret_basic"===this._settings.client_authentication||"client_secret_jwt"===this._settings.client_authentication)&&null==n)throw a.throw(new Error("A client_secret is required")),null;let c;const d=await this._metadataService.getTokenEndpoint(!1);switch(this._settings.client_authentication){case"client_secret_basic":c=Ba.generateBasicAuth(r,n);break;case"client_secret_post":o.append("client_id",r),n&&o.append("client_secret",n);break;case"client_secret_jwt":{const e=await Ba.generateClientAssertionJwt(r,n,d,this._settings.token_endpoint_auth_signing_alg);o.append("client_id",r),o.append("client_assertion_type","urn:ietf:params:oauth:client-assertion-type:jwt-bearer"),o.append("client_assertion",e);break}}a.debug("got token endpoint");const l=await this._jsonService.postForm(d,{body:o,basicAuth:c,timeoutInSeconds:this._settings.requestTimeoutInSeconds,initCredentials:this._settings.fetchRequestCredentials,extraHeaders:s});return a.debug("got response"),l}async exchangeCredentials({grant_type:e="password",client_id:t=this._settings.client_id,client_secret:r=this._settings.client_secret,scope:n=this._settings.scope,...s}){const i=this._logger.create("exchangeCredentials");t||i.throw(new Error("A client_id is required"));const a=new URLSearchParams({grant_type:e});this._settings.omitScopeWhenRequesting||a.set("scope",n);for(const[e,t]of Object.entries(s))null!=t&&a.set(e,t);if(("client_secret_basic"===this._settings.client_authentication||"client_secret_jwt"===this._settings.client_authentication)&&null==r)throw i.throw(new Error("A client_secret is required")),null;let o;const c=await this._metadataService.getTokenEndpoint(!1);switch(this._settings.client_authentication){case"client_secret_basic":o=Ba.generateBasicAuth(t,r);break;case"client_secret_post":a.append("client_id",t),r&&a.append("client_secret",r);break;case"client_secret_jwt":{const e=await Ba.generateClientAssertionJwt(t,r,c,this._settings.token_endpoint_auth_signing_alg);a.append("client_id",t),a.append("client_assertion_type","urn:ietf:params:oauth:client-assertion-type:jwt-bearer"),a.append("client_assertion",e);break}}i.debug("got token endpoint");const d=await this._jsonService.postForm(c,{body:a,basicAuth:o,timeoutInSeconds:this._settings.requestTimeoutInSeconds,initCredentials:this._settings.fetchRequestCredentials});return i.debug("got response"),d}async exchangeRefreshToken({grant_type:e="refresh_token",client_id:t=this._settings.client_id,client_secret:r=this._settings.client_secret,timeoutInSeconds:n,extraHeaders:s,...i}){const a=this._logger.create("exchangeRefreshToken");t||a.throw(new Error("A client_id is required")),i.refresh_token||a.throw(new Error("A refresh_token is required"));const o=new URLSearchParams({grant_type:e});for(const[e,t]of Object.entries(i))Array.isArray(t)?t.forEach(t=>o.append(e,t)):null!=t&&o.set(e,t);if(("client_secret_basic"===this._settings.client_authentication||"client_secret_jwt"===this._settings.client_authentication)&&null==r)throw a.throw(new Error("A client_secret is required")),null;let c;const d=await this._metadataService.getTokenEndpoint(!1);switch(this._settings.client_authentication){case"client_secret_basic":c=Ba.generateBasicAuth(t,r);break;case"client_secret_post":o.append("client_id",t),r&&o.append("client_secret",r);break;case"client_secret_jwt":{const e=await Ba.generateClientAssertionJwt(t,r,d,this._settings.token_endpoint_auth_signing_alg);o.append("client_id",t),o.append("client_assertion_type","urn:ietf:params:oauth:client-assertion-type:jwt-bearer"),o.append("client_assertion",e);break}}a.debug("got token endpoint");const l=await this._jsonService.postForm(d,{body:o,basicAuth:c,timeoutInSeconds:n,initCredentials:this._settings.fetchRequestCredentials,extraHeaders:s});return a.debug("got response"),l}async revoke(e){var t;const r=this._logger.create("revoke");e.token||r.throw(new Error("A token is required"));const n=await this._metadataService.getRevocationEndpoint(!1);r.debug(`got revocation endpoint, revoking ${null!=(t=e.token_type_hint)?t:"default token type"}`);const s=new URLSearchParams;for(const[t,r]of Object.entries(e))null!=r&&s.set(t,r);s.set("client_id",this._settings.client_id),this._settings.client_secret&&s.set("client_secret",this._settings.client_secret),await this._jsonService.postForm(n,{body:s,timeoutInSeconds:this._settings.requestTimeoutInSeconds}),r.debug("got response")}},mo=class{constructor(e,t,r){this._settings=e,this._metadataService=t,this._claimsService=r,this._logger=new Va("ResponseValidator"),this._userInfoService=new ho(this._settings,this._metadataService),this._tokenClient=new po(this._settings,this._metadataService)}async validateSigninResponse(e,t,r){const n=this._logger.create("validateSigninResponse");this._processSigninState(e,t),n.debug("state processed"),await this._processCode(e,t,r),n.debug("code processed"),e.isOpenId&&this._validateIdTokenAttributes(e),n.debug("tokens validated"),await this._processClaims(e,null==t?void 0:t.skipUserInfo,e.isOpenId),n.debug("claims processed")}async validateCredentialsResponse(e,t){const r=this._logger.create("validateCredentialsResponse"),n=e.isOpenId&&!!e.id_token;n&&this._validateIdTokenAttributes(e),r.debug("tokens validated"),await this._processClaims(e,t,n),r.debug("claims processed")}async validateRefreshResponse(e,t){const r=this._logger.create("validateRefreshResponse");e.userState=t.data,null!=e.session_state||(e.session_state=t.session_state),null!=e.scope||(e.scope=t.scope),e.isOpenId&&e.id_token&&(this._validateIdTokenAttributes(e,t.id_token),r.debug("ID Token validated")),e.id_token||(e.id_token=t.id_token,e.profile=t.profile);const n=e.isOpenId&&!!e.id_token;await this._processClaims(e,!1,n),r.debug("claims processed")}validateSignoutResponse(e,t){const r=this._logger.create("validateSignoutResponse");if(t.id!==e.state&&r.throw(new Error("State does not match")),r.debug("state validated"),e.userState=t.data,e.error)throw r.warn("Response was error",e.error),new to(e)}_processSigninState(e,t){const r=this._logger.create("_processSigninState");if(t.id!==e.state&&r.throw(new Error("State does not match")),t.client_id||r.throw(new Error("No client_id on state")),t.authority||r.throw(new Error("No authority on state")),this._settings.authority!==t.authority&&r.throw(new Error("authority mismatch on settings vs. signin state")),this._settings.client_id&&this._settings.client_id!==t.client_id&&r.throw(new Error("client_id mismatch on settings vs. signin state")),r.debug("state validated"),e.userState=t.data,e.url_state=t.url_state,null!=e.scope||(e.scope=t.scope),e.error)throw r.warn("Response was error",e.error),new to(e);t.code_verifier&&!e.code&&r.throw(new Error("Expected code in response"))}async _processClaims(e,t=!1,r=!0){const n=this._logger.create("_processClaims");if(e.profile=this._claimsService.filterProtocolClaims(e.profile),t||!this._settings.loadUserInfo||!e.access_token)return void n.debug("not loading user info");n.debug("loading user info");const s=await this._userInfoService.getClaims(e.access_token);n.debug("user info claims received from user info endpoint"),r&&s.sub!==e.profile.sub&&n.throw(new Error("subject from UserInfo response does not match subject in ID Token")),e.profile=this._claimsService.mergeClaims(e.profile,this._claimsService.filterProtocolClaims(s)),n.debug("user info claims received, updated profile:",e.profile)}async _processCode(e,t,r){const n=this._logger.create("_processCode");if(e.code){n.debug("Validating code");const s=await this._tokenClient.exchangeCode({client_id:t.client_id,client_secret:t.client_secret,code:e.code,redirect_uri:t.redirect_uri,code_verifier:t.code_verifier,extraHeaders:r,...t.extraTokenParams});Object.assign(e,s)}else n.debug("No code to process")}_validateIdTokenAttributes(e,t){var r;const n=this._logger.create("_validateIdTokenAttributes");n.debug("decoding ID Token JWT");const s=Ka.decode(null!=(r=e.id_token)?r:"");if(s.sub||n.throw(new Error("ID Token is missing a subject claim")),t){const e=Ka.decode(t);s.sub!==e.sub&&n.throw(new Error("sub in id_token does not match current sub")),s.auth_time&&s.auth_time!==e.auth_time&&n.throw(new Error("auth_time in id_token does not match original auth_time")),s.azp&&s.azp!==e.azp&&n.throw(new Error("azp in id_token does not match original azp")),!s.azp&&e.azp&&n.throw(new Error("azp not in id_token, but present in original id_token"))}e.profile=s}},fo=class e{constructor(e){this.id=e.id||Ba.generateUUIDv4(),this.data=e.data,e.created&&e.created>0?this.created=e.created:this.created=Ya.getEpochTime(),this.request_type=e.request_type,this.url_state=e.url_state}toStorageString(){return new Va("State").create("toStorageString"),JSON.stringify({id:this.id,data:this.data,created:this.created,request_type:this.request_type,url_state:this.url_state})}static fromStorageString(t){return Va.createStatic("State","fromStorageString"),Promise.resolve(new e(JSON.parse(t)))}static async clearStaleState(t,r){const n=Va.createStatic("State","clearStaleState"),s=Ya.getEpochTime()-r,i=await t.getAllKeys();n.debug("got keys",i);for(let r=0;r<i.length;r++){const a=i[r],o=await t.get(a);let c=!1;if(o)try{const t=await e.fromStorageString(o);n.debug("got item from key:",a,t.created),t.created<=s&&(c=!0)}catch(e){n.error("Error parsing state for key:",a,e),c=!0}else n.debug("no item in storage for key:",a),c=!0;c&&(n.debug("removed item for key:",a),t.remove(a))}}},go=class e extends fo{constructor(e){super(e),this.code_verifier=e.code_verifier,this.code_challenge=e.code_challenge,this.authority=e.authority,this.client_id=e.client_id,this.redirect_uri=e.redirect_uri,this.scope=e.scope,this.client_secret=e.client_secret,this.extraTokenParams=e.extraTokenParams,this.response_mode=e.response_mode,this.skipUserInfo=e.skipUserInfo}static async create(t){const r=!0===t.code_verifier?Ba.generateCodeVerifier():t.code_verifier||void 0,n=r?await Ba.generateCodeChallenge(r):void 0;return new e({...t,code_verifier:r,code_challenge:n})}toStorageString(){return new Va("SigninState").create("toStorageString"),JSON.stringify({id:this.id,data:this.data,created:this.created,request_type:this.request_type,url_state:this.url_state,code_verifier:this.code_verifier,authority:this.authority,client_id:this.client_id,redirect_uri:this.redirect_uri,scope:this.scope,client_secret:this.client_secret,extraTokenParams:this.extraTokenParams,response_mode:this.response_mode,skipUserInfo:this.skipUserInfo})}static fromStorageString(t){Va.createStatic("SigninState","fromStorageString");const r=JSON.parse(t);return e.create(r)}},_o=class e{constructor(e){this.url=e.url,this.state=e.state}static async create({url:t,authority:r,client_id:n,redirect_uri:s,response_type:i,scope:a,state_data:o,response_mode:c,request_type:d,client_secret:l,nonce:u,url_state:h,resource:p,skipUserInfo:m,extraQueryParams:f,extraTokenParams:g,disablePKCE:_,dpopJkt:y,omitScopeWhenRequesting:w,...v}){if(!t)throw this._logger.error("create: No url passed"),new Error("url");if(!n)throw this._logger.error("create: No client_id passed"),new Error("client_id");if(!s)throw this._logger.error("create: No redirect_uri passed"),new Error("redirect_uri");if(!i)throw this._logger.error("create: No response_type passed"),new Error("response_type");if(!a)throw this._logger.error("create: No scope passed"),new Error("scope");if(!r)throw this._logger.error("create: No authority passed"),new Error("authority");const b=await go.create({data:o,request_type:d,url_state:h,code_verifier:!_,client_id:n,authority:r,redirect_uri:s,response_mode:c,client_secret:l,scope:a,extraTokenParams:g,skipUserInfo:m}),k=new URL(t);k.searchParams.append("client_id",n),k.searchParams.append("redirect_uri",s),k.searchParams.append("response_type",i),w||k.searchParams.append("scope",a),u&&k.searchParams.append("nonce",u),y&&k.searchParams.append("dpop_jkt",y);let S=b.id;h&&(S=`${S}${eo}${h}`),k.searchParams.append("state",S),b.code_challenge&&(k.searchParams.append("code_challenge",b.code_challenge),k.searchParams.append("code_challenge_method","S256")),p&&(Array.isArray(p)?p:[p]).forEach(e=>k.searchParams.append("resource",e));for(const[e,t]of Object.entries({response_mode:c,...v,...f}))null!=t&&k.searchParams.append(e,t.toString());return new e({url:k.href,state:b})}};_o._logger=new Va("SigninRequest");var yo=_o,wo=class{constructor(e){if(this.access_token="",this.token_type="",this.profile={},this.state=e.get("state"),this.session_state=e.get("session_state"),this.state){const e=decodeURIComponent(this.state).split(eo);this.state=e[0],e.length>1&&(this.url_state=e.slice(1).join(eo))}this.error=e.get("error"),this.error_description=e.get("error_description"),this.error_uri=e.get("error_uri"),this.code=e.get("code")}get expires_in(){if(void 0!==this.expires_at)return this.expires_at-Ya.getEpochTime()}set expires_in(e){"string"==typeof e&&(e=Number(e)),void 0!==e&&e>=0&&(this.expires_at=Math.floor(e)+Ya.getEpochTime())}get isOpenId(){var e;return(null==(e=this.scope)?void 0:e.split(" ").includes("openid"))||!!this.id_token}},vo=class{constructor({url:e,state_data:t,id_token_hint:r,post_logout_redirect_uri:n,extraQueryParams:s,request_type:i,client_id:a,url_state:o}){if(this._logger=new Va("SignoutRequest"),!e)throw this._logger.error("ctor: No url passed"),new Error("url");const c=new URL(e);if(r&&c.searchParams.append("id_token_hint",r),a&&c.searchParams.append("client_id",a),n&&(c.searchParams.append("post_logout_redirect_uri",n),t||o)){this.state=new fo({data:t,request_type:i,url_state:o});let e=this.state.id;o&&(e=`${e}${eo}${o}`),c.searchParams.append("state",e)}for(const[e,t]of Object.entries({...s}))null!=t&&c.searchParams.append(e,t.toString());this.url=c.href}},bo=class{constructor(e){if(this.state=e.get("state"),this.state){const e=decodeURIComponent(this.state).split(eo);this.state=e[0],e.length>1&&(this.url_state=e.slice(1).join(eo))}this.error=e.get("error"),this.error_description=e.get("error_description"),this.error_uri=e.get("error_uri")}},ko=["nbf","jti","auth_time","nonce","acr","amr","azp","at_hash"],So=["sub","iss","aud","exp","iat"],$o=class{constructor(e){this._settings=e,this._logger=new Va("ClaimsService")}filterProtocolClaims(e){const t={...e};if(this._settings.filterProtocolClaims){let e;e=Array.isArray(this._settings.filterProtocolClaims)?this._settings.filterProtocolClaims:ko;for(const r of e)So.includes(r)||delete t[r]}return t}mergeClaims(e,t){const r={...e};for(const[e,n]of Object.entries(t))if(r[e]!==n)if(Array.isArray(r[e])||Array.isArray(n))if("replace"==this._settings.mergeClaimsStrategy.array)r[e]=n;else{const t=Array.isArray(r[e])?r[e]:[r[e]];for(const e of Array.isArray(n)?n:[n])t.includes(e)||t.push(e);r[e]=t}else"object"==typeof r[e]&&"object"==typeof n?r[e]=this.mergeClaims(r[e],n):r[e]=n;return r}},Eo=class{constructor(e,t){this.keys=e,this.nonce=t}},To=class{constructor(e,t){this._logger=new Va("OidcClient"),this.settings=e instanceof uo?e:new uo(e),this.metadataService=null!=t?t:new co(this.settings),this._claimsService=new $o(this.settings),this._validator=new mo(this.settings,this.metadataService,this._claimsService),this._tokenClient=new po(this.settings,this.metadataService)}async createSigninRequest({state:e,request:t,request_uri:r,request_type:n,id_token_hint:s,login_hint:i,skipUserInfo:a,nonce:o,url_state:c,response_type:d=this.settings.response_type,scope:l=this.settings.scope,redirect_uri:u=this.settings.redirect_uri,prompt:h=this.settings.prompt,display:p=this.settings.display,max_age:m=this.settings.max_age,ui_locales:f=this.settings.ui_locales,acr_values:g=this.settings.acr_values,resource:_=this.settings.resource,response_mode:y=this.settings.response_mode,extraQueryParams:w=this.settings.extraQueryParams,extraTokenParams:v=this.settings.extraTokenParams,dpopJkt:b,omitScopeWhenRequesting:k=this.settings.omitScopeWhenRequesting}){const S=this._logger.create("createSigninRequest");if("code"!==d)throw new Error("Only the Authorization Code flow (with PKCE) is supported");const $=await this.metadataService.getAuthorizationEndpoint();S.debug("Received authorization endpoint",$);const E=await yo.create({url:$,authority:this.settings.authority,client_id:this.settings.client_id,redirect_uri:u,response_type:d,scope:l,state_data:e,url_state:c,prompt:h,display:p,max_age:m,ui_locales:f,id_token_hint:s,login_hint:i,acr_values:g,dpopJkt:b,resource:_,request:t,request_uri:r,extraQueryParams:w,extraTokenParams:v,request_type:n,response_mode:y,client_secret:this.settings.client_secret,skipUserInfo:a,nonce:o,disablePKCE:this.settings.disablePKCE,omitScopeWhenRequesting:k});await this.clearStaleState();const T=E.state;return await this.settings.stateStore.set(T.id,T.toStorageString()),E}async readSigninResponseState(e,t=!1){const r=this._logger.create("readSigninResponseState"),n=new wo(Xa.readParams(e,this.settings.response_mode));if(!n.state)throw r.throw(new Error("No state in response")),null;const s=await this.settings.stateStore[t?"remove":"get"](n.state);if(!s)throw r.throw(new Error("No matching state found in storage")),null;return{state:await go.fromStorageString(s),response:n}}async processSigninResponse(e,t,r=!0){const n=this._logger.create("processSigninResponse"),{state:s,response:i}=await this.readSigninResponseState(e,r);if(n.debug("received state from storage; validating response"),this.settings.dpop&&this.settings.dpop.store){const e=await this.getDpopProof(this.settings.dpop.store);t={...t,DPoP:e}}try{await this._validator.validateSigninResponse(i,s,t)}catch(e){if(!(e instanceof ao&&this.settings.dpop))throw e;{const r=await this.getDpopProof(this.settings.dpop.store,e.nonce);t.DPoP=r,await this._validator.validateSigninResponse(i,s,t)}}return i}async getDpopProof(e,t){let r,n;return(await e.getAllKeys()).includes(this.settings.client_id)?(n=await e.get(this.settings.client_id),n.nonce!==t&&t&&(n.nonce=t,await e.set(this.settings.client_id,n))):(r=await Ba.generateDPoPKeys(),n=new Eo(r,t),await e.set(this.settings.client_id,n)),await Ba.generateDPoPProof({url:await this.metadataService.getTokenEndpoint(!1),httpMethod:"POST",keyPair:n.keys,nonce:n.nonce})}async processResourceOwnerPasswordCredentials({username:e,password:t,skipUserInfo:r=!1,extraTokenParams:n={}}){const s=await this._tokenClient.exchangeCredentials({username:e,password:t,...n}),i=new wo(new URLSearchParams);return Object.assign(i,s),await this._validator.validateCredentialsResponse(i,r),i}async useRefreshToken({state:e,redirect_uri:t,resource:r,timeoutInSeconds:n,extraHeaders:s,extraTokenParams:i}){var a;const o=this._logger.create("useRefreshToken");let c,d;if(void 0===this.settings.refreshTokenAllowedScope)c=e.scope;else{const t=this.settings.refreshTokenAllowedScope.split(" ");c=((null==(a=e.scope)?void 0:a.split(" "))||[]).filter(e=>t.includes(e)).join(" ")}if(this.settings.dpop&&this.settings.dpop.store){const e=await this.getDpopProof(this.settings.dpop.store);s={...s,DPoP:e}}try{d=await this._tokenClient.exchangeRefreshToken({refresh_token:e.refresh_token,scope:c,redirect_uri:t,resource:r,timeoutInSeconds:n,extraHeaders:s,...i})}catch(a){if(!(a instanceof ao&&this.settings.dpop))throw a;s.DPoP=await this.getDpopProof(this.settings.dpop.store,a.nonce),d=await this._tokenClient.exchangeRefreshToken({refresh_token:e.refresh_token,scope:c,redirect_uri:t,resource:r,timeoutInSeconds:n,extraHeaders:s,...i})}const l=new wo(new URLSearchParams);return Object.assign(l,d),o.debug("validating response",l),await this._validator.validateRefreshResponse(l,{...e,scope:c}),l}async createSignoutRequest({state:e,id_token_hint:t,client_id:r,request_type:n,url_state:s,post_logout_redirect_uri:i=this.settings.post_logout_redirect_uri,extraQueryParams:a=this.settings.extraQueryParams}={}){const o=this._logger.create("createSignoutRequest"),c=await this.metadataService.getEndSessionEndpoint();if(!c)throw o.throw(new Error("No end session endpoint")),null;o.debug("Received end session endpoint",c),r||!i||t||(r=this.settings.client_id);const d=new vo({url:c,id_token_hint:t,client_id:r,post_logout_redirect_uri:i,state_data:e,extraQueryParams:a,request_type:n,url_state:s});await this.clearStaleState();const l=d.state;return l&&(o.debug("Signout request has state to persist"),await this.settings.stateStore.set(l.id,l.toStorageString())),d}async readSignoutResponseState(e,t=!1){const r=this._logger.create("readSignoutResponseState"),n=new bo(Xa.readParams(e,this.settings.response_mode));if(!n.state){if(r.debug("No state in response"),n.error)throw r.warn("Response was error:",n.error),new to(n);return{state:void 0,response:n}}const s=await this.settings.stateStore[t?"remove":"get"](n.state);if(!s)throw r.throw(new Error("No matching state found in storage")),null;return{state:await fo.fromStorageString(s),response:n}}async processSignoutResponse(e){const t=this._logger.create("processSignoutResponse"),{state:r,response:n}=await this.readSignoutResponseState(e,!0);return r?(t.debug("Received state from storage; validating response"),this._validator.validateSignoutResponse(n,r)):t.debug("No state from storage; skipping response validation"),n}clearStaleState(){return this._logger.create("clearStaleState"),fo.clearStaleState(this.settings.stateStore,this.settings.staleStateAgeInSeconds)}async revokeToken(e,t){return this._logger.create("revokeToken"),await this._tokenClient.revoke({token:e,token_type_hint:t})}},Io=class{constructor(e){this._userManager=e,this._logger=new Va("SessionMonitor"),this._start=async e=>{const t=e.session_state;if(!t)return;const r=this._logger.create("_start");if(e.profile?(this._sub=e.profile.sub,r.debug("session_state",t,", sub",this._sub)):(this._sub=void 0,r.debug("session_state",t,", anonymous user")),this._checkSessionIFrame)this._checkSessionIFrame.start(t);else try{const e=await this._userManager.metadataService.getCheckSessionIframe();if(e){r.debug("initializing check session iframe");const n=this._userManager.settings.client_id,s=this._userManager.settings.checkSessionIntervalInSeconds,i=this._userManager.settings.stopCheckSessionOnError,a=new so(this._callback,n,e,s,i);await a.load(),this._checkSessionIFrame=a,a.start(t)}else r.warn("no check session iframe found in the metadata")}catch(e){r.error("Error from getCheckSessionIframe:",e instanceof Error?e.message:e)}},this._stop=()=>{const e=this._logger.create("_stop");if(this._sub=void 0,this._checkSessionIFrame&&this._checkSessionIFrame.stop(),this._userManager.settings.monitorAnonymousSession){const t=setInterval(async()=>{clearInterval(t);try{const e=await this._userManager.querySessionStatus();if(e){const t={session_state:e.session_state,profile:e.sub?{sub:e.sub}:null};this._start(t)}}catch(t){e.error("error from querySessionStatus",t instanceof Error?t.message:t)}},1e3)}},this._callback=async()=>{const e=this._logger.create("_callback");try{const t=await this._userManager.querySessionStatus();let r=!0;t&&this._checkSessionIFrame?t.sub===this._sub?(r=!1,this._checkSessionIFrame.start(t.session_state),e.debug("same sub still logged in at OP, session state has changed, restarting check session iframe; session_state",t.session_state),await this._userManager.events._raiseUserSessionChanged()):e.debug("different subject signed into OP",t.sub):e.debug("subject no longer signed into OP"),r?this._sub?await this._userManager.events._raiseUserSignedOut():await this._userManager.events._raiseUserSignedIn():e.debug("no change in session detected, no event to raise")}catch(t){this._sub&&(e.debug("Error calling queryCurrentSigninSession; raising signed out event",t),await this._userManager.events._raiseUserSignedOut())}},e||this._logger.throw(new Error("No user manager passed")),this._userManager.events.addUserLoaded(this._start),this._userManager.events.addUserUnloaded(this._stop),this._init().catch(e=>{this._logger.error(e)})}async _init(){this._logger.create("_init");const e=await this._userManager.getUser();if(e)this._start(e);else if(this._userManager.settings.monitorAnonymousSession){const e=await this._userManager.querySessionStatus();if(e){const t={session_state:e.session_state,profile:e.sub?{sub:e.sub}:null};this._start(t)}}}},xo=class e{constructor(e){var t;this.id_token=e.id_token,this.session_state=null!=(t=e.session_state)?t:null,this.access_token=e.access_token,this.refresh_token=e.refresh_token,this.token_type=e.token_type,this.scope=e.scope,this.profile=e.profile,this.expires_at=e.expires_at,this.state=e.userState,this.url_state=e.url_state}get expires_in(){if(void 0!==this.expires_at)return this.expires_at-Ya.getEpochTime()}set expires_in(e){void 0!==e&&(this.expires_at=Math.floor(e)+Ya.getEpochTime())}get expired(){const e=this.expires_in;if(void 0!==e)return e<=0}get scopes(){var e,t;return null!=(t=null==(e=this.scope)?void 0:e.split(" "))?t:[]}toStorageString(){return new Va("User").create("toStorageString"),JSON.stringify({id_token:this.id_token,session_state:this.session_state,access_token:this.access_token,refresh_token:this.refresh_token,token_type:this.token_type,scope:this.scope,profile:this.profile,expires_at:this.expires_at})}static fromStorageString(t){return Va.createStatic("User","fromStorageString"),new e(JSON.parse(t))}},Po="oidc-client",Co=class{constructor(){this._abort=new Ja("Window navigation aborted"),this._disposeHandlers=new Set,this._window=null}async navigate(e){const t=this._logger.create("navigate");if(!this._window)throw new Error("Attempted to navigate on a disposed window");t.debug("setting URL in window"),this._window.location.replace(e.url);const{url:r,keepOpen:n}=await new Promise((r,n)=>{const s=s=>{var i;const a=s.data,o=null!=(i=e.scriptOrigin)?i:window.location.origin;if(s.origin===o&&(null==a?void 0:a.source)===Po){try{const r=Xa.readParams(a.url,e.response_mode).get("state");if(r||t.warn("no state found in response url"),s.source!==this._window&&r!==e.state)return}catch{this._dispose(),n(new Error("Invalid response from window"))}r(a)}};window.addEventListener("message",s,!1),this._disposeHandlers.add(()=>window.removeEventListener("message",s,!1));const i=new BroadcastChannel(`oidc-client-popup-${e.state}`);i.addEventListener("message",s,!1),this._disposeHandlers.add(()=>i.close()),this._disposeHandlers.add(this._abort.addHandler(e=>{this._dispose(),n(e)}))});return t.debug("got response from window"),this._dispose(),n||this.close(),{url:r}}_dispose(){this._logger.create("_dispose");for(const e of this._disposeHandlers)e();this._disposeHandlers.clear()}static _notifyParent(e,t,r=!1,n=window.location.origin){const s={source:Po,url:t,keepOpen:r},i=new Va("_notifyParent");if(e)i.debug("With parent. Using parent.postMessage."),e.postMessage(s,n);else{i.debug("No parent. Using BroadcastChannel.");const e=new URL(t).searchParams.get("state");if(!e)throw new Error("No parent and no state in URL. Can't complete notification.");const r=new BroadcastChannel(`oidc-client-popup-${e}`);r.postMessage(s),r.close()}}},Ro={location:!1,toolbar:!1,height:640,closePopupWindowAfterInSeconds:-1},Ao="_blank",Oo=60,No=2,zo=class extends uo{constructor(e){const{popup_redirect_uri:t=e.redirect_uri,popup_post_logout_redirect_uri:r=e.post_logout_redirect_uri,popupWindowFeatures:n=Ro,popupWindowTarget:s=Ao,redirectMethod:i="assign",redirectTarget:a="self",iframeNotifyParentOrigin:o=e.iframeNotifyParentOrigin,iframeScriptOrigin:c=e.iframeScriptOrigin,requestTimeoutInSeconds:d,silent_redirect_uri:l=e.redirect_uri,silentRequestTimeoutInSeconds:u,automaticSilentRenew:h=!0,validateSubOnSilentRenew:p=!0,includeIdTokenInSilentRenew:m=!1,monitorSession:f=!1,monitorAnonymousSession:g=!1,checkSessionIntervalInSeconds:_=No,query_status_response_type:y="code",stopCheckSessionOnError:w=!0,revokeTokenTypes:v=["access_token","refresh_token"],revokeTokensOnSignout:b=!1,includeIdTokenInSilentSignout:k=!1,accessTokenExpiringNotificationTimeInSeconds:S=Oo,userStore:$}=e;if(super(e),this.popup_redirect_uri=t,this.popup_post_logout_redirect_uri=r,this.popupWindowFeatures=n,this.popupWindowTarget=s,this.redirectMethod=i,this.redirectTarget=a,this.iframeNotifyParentOrigin=o,this.iframeScriptOrigin=c,this.silent_redirect_uri=l,this.silentRequestTimeoutInSeconds=u||d||10,this.automaticSilentRenew=h,this.validateSubOnSilentRenew=p,this.includeIdTokenInSilentRenew=m,this.monitorSession=f,this.monitorAnonymousSession=g,this.checkSessionIntervalInSeconds=_,this.stopCheckSessionOnError=w,this.query_status_response_type=y,this.revokeTokenTypes=v,this.revokeTokensOnSignout=b,this.includeIdTokenInSilentSignout=k,this.accessTokenExpiringNotificationTimeInSeconds=S,$)this.userStore=$;else{const e="undefined"!=typeof window?window.sessionStorage:new io;this.userStore=new lo({store:e})}}},jo=class e extends Co{constructor({silentRequestTimeoutInSeconds:t=10}){super(),this._logger=new Va("IFrameWindow"),this._timeoutInSeconds=t,this._frame=e.createHiddenIframe(),this._window=this._frame.contentWindow}static createHiddenIframe(){const e=window.document.createElement("iframe");return e.style.visibility="hidden",e.style.position="fixed",e.style.left="-1000px",e.style.top="0",e.width="0",e.height="0",window.document.body.appendChild(e),e}async navigate(e){this._logger.debug("navigate: Using timeout of:",this._timeoutInSeconds);const t=setTimeout(()=>{this._abort.raise(new ro("IFrame timed out without a response"))},1e3*this._timeoutInSeconds);return this._disposeHandlers.add(()=>clearTimeout(t)),await super.navigate(e)}close(){var e;this._frame&&(this._frame.parentNode&&(this._frame.addEventListener("load",e=>{var t;const r=e.target;null==(t=r.parentNode)||t.removeChild(r),this._abort.raise(new Error("IFrame removed from DOM"))},!0),null==(e=this._frame.contentWindow)||e.location.replace("about:blank")),this._frame=null),this._window=null}static notifyParent(e,t){return super._notifyParent(window.parent,e,!1,t)}},Uo=class{constructor(e){this._settings=e,this._logger=new Va("IFrameNavigator")}async prepare({silentRequestTimeoutInSeconds:e=this._settings.silentRequestTimeoutInSeconds}){return new jo({silentRequestTimeoutInSeconds:e})}async callback(e){this._logger.create("callback"),jo.notifyParent(e,this._settings.iframeNotifyParentOrigin)}},qo=class extends Co{constructor({popupWindowTarget:e=Ao,popupWindowFeatures:t={},popupSignal:r,popupAbortOnClose:n}){super(),this._logger=new Va("PopupWindow");const s=Qa.center({...Ro,...t});this._window=window.open(void 0,e,Qa.serialize(s)),this.abortOnClose=Boolean(n),r&&r.addEventListener("abort",()=>{var e;this._abort.raise(new Error(null!=(e=r.reason)?e:"Popup aborted"))}),t.closePopupWindowAfterInSeconds&&t.closePopupWindowAfterInSeconds>0&&setTimeout(()=>{this._window&&"boolean"==typeof this._window.closed&&!this._window.closed?this.close():this._abort.raise(new Error("Popup blocked by user"))},1e3*t.closePopupWindowAfterInSeconds)}async navigate(e){var t;null==(t=this._window)||t.focus();const r=setInterval(()=>{this._window&&!this._window.closed||(this._logger.debug("Popup closed by user or isolated by redirect"),n(),this._disposeHandlers.delete(n),this.abortOnClose&&this._abort.raise(new Error("Popup closed by user")))},500),n=()=>clearInterval(r);return this._disposeHandlers.add(n),await super.navigate(e)}close(){this._window&&(this._window.closed||(this._window.close(),this._abort.raise(new Error("Popup closed")))),this._window=null}static notifyOpener(e,t){super._notifyParent(window.opener,e,t),t||window.opener||window.close()}},Do=class{constructor(e){this._settings=e,this._logger=new Va("PopupNavigator")}async prepare({popupWindowFeatures:e=this._settings.popupWindowFeatures,popupWindowTarget:t=this._settings.popupWindowTarget,popupSignal:r,popupAbortOnClose:n}){return new qo({popupWindowFeatures:e,popupWindowTarget:t,popupSignal:r,popupAbortOnClose:n})}async callback(e,{keepOpen:t=!1}){this._logger.create("callback"),qo.notifyOpener(e,t)}},Mo=class{constructor(e){this._settings=e,this._logger=new Va("RedirectNavigator")}async prepare({redirectMethod:e=this._settings.redirectMethod,redirectTarget:t=this._settings.redirectTarget}){var r;this._logger.create("prepare");let n=window.self;"top"===t&&(n=null!=(r=window.top)?r:window.self);const s=n.location[e].bind(n.location);let i;return{navigate:async e=>{this._logger.create("navigate");const t=new Promise((t,r)=>{i=r,window.addEventListener("pageshow",()=>t(window.location.href)),s(e.url)});return await t},close:()=>{this._logger.create("close"),null==i||i(new Error("Redirect aborted")),n.stop()}}}async callback(){}},Lo=class extends no{constructor(e){super({expiringNotificationTimeInSeconds:e.accessTokenExpiringNotificationTimeInSeconds}),this._logger=new Va("UserManagerEvents"),this._userLoaded=new Ja("User loaded"),this._userUnloaded=new Ja("User unloaded"),this._silentRenewError=new Ja("Silent renew error"),this._userSignedIn=new Ja("User signed in"),this._userSignedOut=new Ja("User signed out"),this._userSessionChanged=new Ja("User session changed")}async load(e,t=!0){await super.load(e),t&&await this._userLoaded.raise(e)}async unload(){await super.unload(),await this._userUnloaded.raise()}addUserLoaded(e){return this._userLoaded.addHandler(e)}removeUserLoaded(e){return this._userLoaded.removeHandler(e)}addUserUnloaded(e){return this._userUnloaded.addHandler(e)}removeUserUnloaded(e){return this._userUnloaded.removeHandler(e)}addSilentRenewError(e){return this._silentRenewError.addHandler(e)}removeSilentRenewError(e){return this._silentRenewError.removeHandler(e)}async _raiseSilentRenewError(e){await this._silentRenewError.raise(e)}addUserSignedIn(e){return this._userSignedIn.addHandler(e)}removeUserSignedIn(e){this._userSignedIn.removeHandler(e)}async _raiseUserSignedIn(){await this._userSignedIn.raise()}addUserSignedOut(e){return this._userSignedOut.addHandler(e)}removeUserSignedOut(e){this._userSignedOut.removeHandler(e)}async _raiseUserSignedOut(){await this._userSignedOut.raise()}addUserSessionChanged(e){return this._userSessionChanged.addHandler(e)}removeUserSessionChanged(e){this._userSessionChanged.removeHandler(e)}async _raiseUserSessionChanged(){await this._userSessionChanged.raise()}},Zo=class{constructor(e){this._userManager=e,this._logger=new Va("SilentRenewService"),this._isStarted=!1,this._retryTimer=new Ya("Retry Silent Renew"),this._tokenExpiring=async()=>{const e=this._logger.create("_tokenExpiring");try{await this._userManager.signinSilent(),e.debug("silent token renewal successful")}catch(t){if(t instanceof ro)return e.warn("ErrorTimeout from signinSilent:",t,"retry in 5s"),void this._retryTimer.init(5);e.error("Error from signinSilent:",t),await this._userManager.events._raiseSilentRenewError(t)}}}async start(){const e=this._logger.create("start");if(!this._isStarted){this._isStarted=!0,this._userManager.events.addAccessTokenExpiring(this._tokenExpiring),this._retryTimer.addHandler(this._tokenExpiring);try{await this._userManager.getUser()}catch(t){e.error("getUser error",t)}}}stop(){this._isStarted&&(this._retryTimer.cancel(),this._retryTimer.removeHandler(this._tokenExpiring),this._userManager.events.removeAccessTokenExpiring(this._tokenExpiring),this._isStarted=!1)}},Fo=class{constructor(e){this.refresh_token=e.refresh_token,this.id_token=e.id_token,this.session_state=e.session_state,this.scope=e.scope,this.profile=e.profile,this.data=e.state}},Ho=class{constructor(e,t,r,n){this._logger=new Va("UserManager"),this.settings=new zo(e),this._client=new To(e),this._redirectNavigator=null!=t?t:new Mo(this.settings),this._popupNavigator=null!=r?r:new Do(this.settings),this._iframeNavigator=null!=n?n:new Uo(this.settings),this._events=new Lo(this.settings),this._silentRenewService=new Zo(this),this.settings.automaticSilentRenew&&this.startSilentRenew(),this._sessionMonitor=null,this.settings.monitorSession&&(this._sessionMonitor=new Io(this))}get events(){return this._events}get metadataService(){return this._client.metadataService}async getUser(e=!1){const t=this._logger.create("getUser"),r=await this._loadUser();return r?(t.info("user loaded"),await this._events.load(r,e),r):(t.info("user not found in storage"),null)}async removeUser(){const e=this._logger.create("removeUser");await this.storeUser(null),e.info("user removed from storage"),await this._events.unload()}async signinRedirect(e={}){var t;this._logger.create("signinRedirect");const{redirectMethod:r,...n}=e;let s;(null==(t=this.settings.dpop)?void 0:t.bind_authorization_code)&&(s=await this.generateDPoPJkt(this.settings.dpop));const i=await this._redirectNavigator.prepare({redirectMethod:r});await this._signinStart({request_type:"si:r",dpopJkt:s,...n},i)}async signinRedirectCallback(e=window.location.href){const t=this._logger.create("signinRedirectCallback"),r=await this._signinEnd(e);return r.profile&&r.profile.sub?t.info("success, signed in subject",r.profile.sub):t.info("no subject"),r}async signinResourceOwnerCredentials({username:e,password:t,skipUserInfo:r=!1}){const n=this._logger.create("signinResourceOwnerCredential"),s=await this._client.processResourceOwnerPasswordCredentials({username:e,password:t,skipUserInfo:r,extraTokenParams:this.settings.extraTokenParams});n.debug("got signin response");const i=await this._buildUser(s);return i.profile&&i.profile.sub?n.info("success, signed in subject",i.profile.sub):n.info("no subject"),i}async signinPopup(e={}){var t;const r=this._logger.create("signinPopup");let n;(null==(t=this.settings.dpop)?void 0:t.bind_authorization_code)&&(n=await this.generateDPoPJkt(this.settings.dpop));const{popupWindowFeatures:s,popupWindowTarget:i,popupSignal:a,popupAbortOnClose:o,...c}=e,d=this.settings.popup_redirect_uri;d||r.throw(new Error("No popup_redirect_uri configured"));const l=await this._popupNavigator.prepare({popupWindowFeatures:s,popupWindowTarget:i,popupSignal:a,popupAbortOnClose:o}),u=await this._signin({request_type:"si:p",redirect_uri:d,display:"popup",dpopJkt:n,...c},l);return u&&(u.profile&&u.profile.sub?r.info("success, signed in subject",u.profile.sub):r.info("no subject")),u}async signinPopupCallback(e=window.location.href,t=!1){const r=this._logger.create("signinPopupCallback");await this._popupNavigator.callback(e,{keepOpen:t}),r.info("success")}async signinSilent(e={}){var t,r;const n=this._logger.create("signinSilent"),{silentRequestTimeoutInSeconds:s,...i}=e;let a,o=await this._loadUser();if(!e.forceIframeAuth&&(null==o?void 0:o.refresh_token)){n.debug("using refresh token");const e=new Fo(o);return await this._useRefreshToken({state:e,redirect_uri:i.redirect_uri,resource:i.resource,extraTokenParams:i.extraTokenParams,timeoutInSeconds:s})}(null==(t=this.settings.dpop)?void 0:t.bind_authorization_code)&&(a=await this.generateDPoPJkt(this.settings.dpop));const c=this.settings.silent_redirect_uri;let d;c||n.throw(new Error("No silent_redirect_uri configured")),o&&this.settings.validateSubOnSilentRenew&&(n.debug("subject prior to silent renew:",o.profile.sub),d=o.profile.sub);const l=await this._iframeNavigator.prepare({silentRequestTimeoutInSeconds:s});return o=await this._signin({request_type:"si:s",redirect_uri:c,prompt:"none",id_token_hint:this.settings.includeIdTokenInSilentRenew?null==o?void 0:o.id_token:void 0,dpopJkt:a,...i},l,d),o&&((null==(r=o.profile)?void 0:r.sub)?n.info("success, signed in subject",o.profile.sub):n.info("no subject")),o}async _useRefreshToken(e){const t=await this._client.useRefreshToken({timeoutInSeconds:this.settings.silentRequestTimeoutInSeconds,...e}),r=new xo({...e.state,...t});return await this.storeUser(r),await this._events.load(r),r}async signinSilentCallback(e=window.location.href){const t=this._logger.create("signinSilentCallback");await this._iframeNavigator.callback(e),t.info("success")}async signinCallback(e=window.location.href){const{state:t}=await this._client.readSigninResponseState(e);switch(t.request_type){case"si:r":return await this.signinRedirectCallback(e);case"si:p":await this.signinPopupCallback(e);break;case"si:s":await this.signinSilentCallback(e);break;default:throw new Error("invalid response_type in state")}}async signoutCallback(e=window.location.href,t=!1){const{state:r}=await this._client.readSignoutResponseState(e);if(r)switch(r.request_type){case"so:r":return await this.signoutRedirectCallback(e);case"so:p":await this.signoutPopupCallback(e,t);break;case"so:s":await this.signoutSilentCallback(e);break;default:throw new Error("invalid response_type in state")}}async querySessionStatus(e={}){const t=this._logger.create("querySessionStatus"),{silentRequestTimeoutInSeconds:r,...n}=e,s=this.settings.silent_redirect_uri;s||t.throw(new Error("No silent_redirect_uri configured"));const i=await this._loadUser(),a=await this._iframeNavigator.prepare({silentRequestTimeoutInSeconds:r}),o=await this._signinStart({request_type:"si:s",redirect_uri:s,prompt:"none",id_token_hint:this.settings.includeIdTokenInSilentRenew?null==i?void 0:i.id_token:void 0,response_type:this.settings.query_status_response_type,scope:"openid",skipUserInfo:!0,...n},a);try{const e={},r=await this._client.processSigninResponse(o.url,e);return t.debug("got signin response"),r.session_state&&r.profile.sub?(t.info("success for subject",r.profile.sub),{session_state:r.session_state,sub:r.profile.sub}):(t.info("success, user not authenticated"),null)}catch(e){if(this.settings.monitorAnonymousSession&&e instanceof to)switch(e.error){case"login_required":case"consent_required":case"interaction_required":case"account_selection_required":return t.info("success for anonymous user"),{session_state:e.session_state}}throw e}}async _signin(e,t,r){const n=await this._signinStart(e,t);return await this._signinEnd(n.url,r)}async _signinStart(e,t){const r=this._logger.create("_signinStart");try{const n=await this._client.createSigninRequest(e);return r.debug("got signin request"),await t.navigate({url:n.url,state:n.state.id,response_mode:n.state.response_mode,scriptOrigin:this.settings.iframeScriptOrigin})}catch(e){throw r.debug("error after preparing navigator, closing navigator window"),t.close(),e}}async _signinEnd(e,t){const r=this._logger.create("_signinEnd"),n=await this._client.processSigninResponse(e,{});return r.debug("got signin response"),await this._buildUser(n,t)}async _buildUser(e,t){const r=this._logger.create("_buildUser"),n=new xo(e);if(t){if(t!==n.profile.sub)throw r.debug("current user does not match user returned from signin. sub from signin:",n.profile.sub),new to({...e,error:"login_required"});r.debug("current user matches user returned from signin")}return await this.storeUser(n),r.debug("user stored"),await this._events.load(n),n}async signoutRedirect(e={}){const t=this._logger.create("signoutRedirect"),{redirectMethod:r,...n}=e,s=await this._redirectNavigator.prepare({redirectMethod:r});await this._signoutStart({request_type:"so:r",post_logout_redirect_uri:this.settings.post_logout_redirect_uri,...n},s),t.info("success")}async signoutRedirectCallback(e=window.location.href){const t=this._logger.create("signoutRedirectCallback"),r=await this._signoutEnd(e);return t.info("success"),r}async signoutPopup(e={}){const t=this._logger.create("signoutPopup"),{popupWindowFeatures:r,popupWindowTarget:n,popupSignal:s,...i}=e,a=this.settings.popup_post_logout_redirect_uri,o=await this._popupNavigator.prepare({popupWindowFeatures:r,popupWindowTarget:n,popupSignal:s});await this._signout({request_type:"so:p",post_logout_redirect_uri:a,state:null==a?void 0:{},...i},o),t.info("success")}async signoutPopupCallback(e=window.location.href,t=!1){const r=this._logger.create("signoutPopupCallback");await this._popupNavigator.callback(e,{keepOpen:t}),r.info("success")}async _signout(e,t){const r=await this._signoutStart(e,t);return await this._signoutEnd(r.url)}async _signoutStart(e={},t){var r;const n=this._logger.create("_signoutStart");try{const s=await this._loadUser();n.debug("loaded current user from storage"),this.settings.revokeTokensOnSignout&&await this._revokeInternal(s);const i=e.id_token_hint||s&&s.id_token;i&&(n.debug("setting id_token_hint in signout request"),e.id_token_hint=i),await this.removeUser(),n.debug("user removed, creating signout request");const a=await this._client.createSignoutRequest(e);return n.debug("got signout request"),await t.navigate({url:a.url,state:null==(r=a.state)?void 0:r.id,scriptOrigin:this.settings.iframeScriptOrigin})}catch(e){throw n.debug("error after preparing navigator, closing navigator window"),t.close(),e}}async _signoutEnd(e){const t=this._logger.create("_signoutEnd"),r=await this._client.processSignoutResponse(e);return t.debug("got signout response"),r}async signoutSilent(e={}){var t;const r=this._logger.create("signoutSilent"),{silentRequestTimeoutInSeconds:n,...s}=e,i=this.settings.includeIdTokenInSilentSignout?null==(t=await this._loadUser())?void 0:t.id_token:void 0,a=this.settings.popup_post_logout_redirect_uri,o=await this._iframeNavigator.prepare({silentRequestTimeoutInSeconds:n});await this._signout({request_type:"so:s",post_logout_redirect_uri:a,id_token_hint:i,...s},o),r.info("success")}async signoutSilentCallback(e=window.location.href){const t=this._logger.create("signoutSilentCallback");await this._iframeNavigator.callback(e),t.info("success")}async revokeTokens(e){const t=await this._loadUser();await this._revokeInternal(t,e)}async _revokeInternal(e,t=this.settings.revokeTokenTypes){const r=this._logger.create("_revokeInternal");if(!e)return;const n=t.filter(t=>"string"==typeof e[t]);if(n.length){for(const t of n)await this._client.revokeToken(e[t],t),r.info(`${t} revoked successfully`),"access_token"!==t&&(e[t]=null);await this.storeUser(e),r.debug("user stored"),await this._events.load(e)}else r.debug("no need to revoke due to no token(s)")}startSilentRenew(){this._logger.create("startSilentRenew"),this._silentRenewService.start()}stopSilentRenew(){this._silentRenewService.stop()}get _userStoreKey(){return`user:${this.settings.authority}:${this.settings.client_id}`}async _loadUser(){const e=this._logger.create("_loadUser"),t=await this.settings.userStore.get(this._userStoreKey);return t?(e.debug("user storageString loaded"),xo.fromStorageString(t)):(e.debug("no user storageString"),null)}async storeUser(e){const t=this._logger.create("storeUser");if(e){t.debug("storing user");const r=e.toStorageString();await this.settings.userStore.set(this._userStoreKey,r)}else this._logger.debug("removing user"),await this.settings.userStore.remove(this._userStoreKey),this.settings.dpop&&await this.settings.dpop.store.remove(this.settings.client_id)}async clearStaleState(){await this._client.clearStaleState()}async dpopProof(e,t,r,n){var s,i;const a=await(null==(i=null==(s=this.settings.dpop)?void 0:s.store)?void 0:i.get(this.settings.client_id));if(a)return await Ba.generateDPoPProof({url:e,accessToken:null==t?void 0:t.access_token,httpMethod:r,keyPair:a.keys,nonce:n})}async generateDPoPJkt(e){let t=await e.store.get(this.settings.client_id);if(!t){const r=await Ba.generateDPoPKeys();t=new Eo(r),await e.store.set(this.settings.client_id,t)}return await Ba.generateDPoPJkt(t.keys)}};const Vo="OAUTH2_LOGIN_FLOW_COMPLETE_EVENT",Ko="OAUTH_GET_TOP_URL",Go="OAUTH_REDIRECT_TOP_WINDOW",Wo="OAUTH_UPDATE_URL",Bo="OAUTH2_CHECK_PENDING",Jo="oauth2_top_origin",Qo="oauth2_login_success",Yo="oauth2_state",Xo=60,ec=Math.max(Xo-15,20),tc=va("oidc-auth",{color:"green"}),rc=e=>tc.extend(e);va("oidc-auth-utils");const nc=()=>"undefined"==typeof window?"":new URLSearchParams(window.location.search).get("origin")||"";class sc{static instance=null;settings=null;constructor(){}static getInstance(){return sc.instance||(sc.instance=new sc),sc.instance}configure(e){this.settings=e}isConfigured(){return null!==this.settings}getSettings(){if(!this.settings)throw new Error("OidcAuthConfig not configured. Call configure() or pass settings to OidcAuthClient.initialize().");return this.settings}getAuthOrigin(){const{authOrigin:e,authEndpoint:t}=this.getSettings();return e||new URL(t).origin}isAccessTokenProactiveRefreshEnabled(){return this.settings?.accessTokenProactiveRefreshEnabled??!0}getOidcSettings(){const e="undefined"==typeof window?"":window.location.origin,{clientId:t,authEndpoint:r}=this.getSettings(),n=this.getAuthOrigin(),s="undefined"!=typeof window?new lo({store:window.localStorage}):void 0,{accessTokenExpiringNotificationTimeInSeconds:i=Xo}=this.getSettings();return{client_id:t,authority:n,redirect_uri:`${e}/login/oauth-callback`,post_logout_redirect_uri:e,response_type:"code",scope:"openid offline_access",automaticSilentRenew:!1,accessTokenExpiringNotificationTimeInSeconds:i,stateStore:s,userStore:s,metadata:{issuer:n,authorization_endpoint:r,token_endpoint:`${n}/connect/api/v1/oauth2/token`,end_session_endpoint:`${n}/logout/`}}}getAccessTokenExpiringNotificationTimeInSeconds(){return this.getSettings().accessTokenExpiringNotificationTimeInSeconds??Xo}getAccessTokenFreshnessThresholdInSeconds(){return this.getSettings().accessTokenFreshnessThresholdInSeconds??ec}getAllowedParentOrigins(){return this.settings?.allowedParentOrigins}}const ic=sc.getInstance(),ac=rc("oidc-auth:host-api"),oc=async e=>new Promise((t,r)=>{const n=new MessageChannel;let s=!1;const i=()=>{s=!0,n.port1.close()},a=setTimeout(()=>{s||(i(),r(new Error(`Host message timeout: ${e.type}`)))},1e4);n.port1.onmessage=e=>{clearTimeout(a),i(),"success"!==e.data.status?r(e.data.payload):t(e.data.payload)};const o=new URLSearchParams(window.location.search).get("origin")||"";if(!function(e){if(!e.startsWith("http://")&&!e.startsWith("https://"))return!1;const t=ic.getAllowedParentOrigins();return!t||0===t.length||t.includes(e)}(o))return clearTimeout(a),i(),void r(new Error("Origin not allowed"));ac.log("posting message to host",e),window.top.postMessage({type:e.type,payload:e.payload,...e.data||{}},o,[n.port2])}),cc=rc("oidc-auth:OidcAuthTimer");class dc{timerHandle=null;expiration=null;initialized=!1;callback=()=>{};constructor(){this.timerHandle=null}init(e,t,r){const n=e-this.getEpochTime(),s=Math.max(n-t,10);this.cancel(),this.expiration=s,this.callback=r,cc.debug("OIDC: timer - using expiration",s,n,t,e,n-t),this.timerHandle=setTimeout(this.callback,1e3*s),this.initialized=!0}cancel(){this.timerHandle&&(clearTimeout(this.timerHandle),this.timerHandle=null),this.expiration=null}getEpochTime(){return Math.floor(Date.now()/1e3)}isInitialized(){return this.initialized}}const lc=rc("oidc-auth:OidcAuthClient");class uc{static instance=null;userManager=null;initialized=!1;accessTokenExpiringTimer=null;retryTimers=new Set;constructor(){}static getInstance(){return uc.instance||(uc.instance=new uc),uc.instance}isInitialized(){return this.initialized}ensureInitialized(){if(!this.userManager)throw new Error("OidcAuthClient not initialized. Call initialize() first.");return this.userManager}initialize(e){if(e&&(this.initialized=!1,ic.configure(e)),this.initialized)lc.info("OIDC: initialize() - already initialized, skipping");else if("undefined"!=typeof window)if(ic.isConfigured())try{lc.info("OIDC: initialize() - starting initialization");const e=ic.getOidcSettings();this.userManager=new Ho(e),Ha.setLogger(lc),Ha.setLevel(Ha.ERROR),this.initAccessTokenExpiringTimer(),this.initialized=!0}catch(e){throw lc.error("OIDC: initialize() - FAILED:",e),e}else lc.warn("OIDC: initialize() - skipped, config not set");else lc.warn("OidcAuthClient cannot initialize on server side")}async initAccessTokenExpiringTimer(){ic.isAccessTokenProactiveRefreshEnabled()?this.getUser().then(e=>{const t=e?.expires_at;t&&(this.accessTokenExpiringTimer||(this.accessTokenExpiringTimer=new dc),this.accessTokenExpiringTimer.init(t,ic.getAccessTokenExpiringNotificationTimeInSeconds(),async()=>{lc.info("OIDC: timer proactive refresh access token expiring timer fired",t),this.proactiveRefreshWithRetry()}))}).catch(e=>{lc.error("OIDC: initAccessTokenExpiringTimer - FAILED:",e)}):lc.warn("OIDC: timer - not starting, access token proactive refresh is disabled")}async getUser(){if(!this.userManager)return null;try{return await this.userManager.getUser()}catch(e){return lc.error("OIDC: getUser - FAILED:",e),null}}async storeUser(e){const t=this.ensureInitialized();await t.storeUser(e)}async getAccessToken(){const e=await this.getUser();if(!e)return lc.info("OIDC: getAccessToken - no user found"),null;if(e.expired)try{const e=await this.signinSilent();return e?.access_token||null}catch(e){return lc.error("OIDC: getAccessToken - silent renew failed:",e),null}return this.isTokenFresh(e)||this.signinSilent().catch(e=>{lc.error("OIDC: getAccessToken - background refresh failed:",e)}),e.access_token}getUserData(){if("undefined"==typeof window)return null;try{const e=ic.getOidcSettings(),t=`oidc.user:${e.authority}:${e.client_id}`,r=localStorage.getItem(t);if(!r)return null;const n=JSON.parse(r),s=n?.profile;return s?.sub?(lc.info("OIDC: USER:",{profile:s}),{id:s.sub,email:s.email||"",first_name:s.given_name,last_name:s.family_name}):null}catch(e){return lc.error("OIDC: getUserData - FAILED:",e),null}}async isAuthenticated(){const e=await this.getUser();return null!==e&&!e.expired}async signinRedirect(e){const t=this.ensureInitialized();await t.signinRedirect({state:e?{data:e}:void 0,prompt:"login"})}async signinCallback(){const e=this.ensureInitialized(),t=await e.signinCallback();if(!t)throw lc.error("OIDC: signinCallback - FAILED: no user returned"),new Error("Signin callback failed: no user returned");return t}async signinSilent(e){return this.ensureInitialized(),"undefined"!=typeof navigator&&navigator.locks?navigator.locks.request("oidc-token-refresh",async()=>{const t=await this.getUser();return t&&this.isTokenFresh(t,e)?t:this.doSigninSilent()}):(lc.warn("OIDC: signinSilent - navigator.locks not available, proceeding without lock"),this.doSigninSilent())}isTokenFresh(e,t){if(!e.expires_at)return!1;const r=t??ic.getAccessTokenFreshnessThresholdInSeconds(),n=Math.floor(Date.now()/1e3);return e.expires_at-n>r}async doSigninSilent(){const e=this.ensureInitialized();try{return await e.signinSilent()}catch(e){throw lc.error("OIDC: doSigninSilent - FAILED:",e),e}}proactiveRefreshWithRetry(e=1){if("undefined"!=typeof document&&"hidden"===document.visibilityState){lc.info("OIDC: tab is hidden, deferring proactive refresh until visible");const t=()=>{"visible"===document.visibilityState&&(document.removeEventListener("visibilitychange",t),this.proactiveRefreshWithRetry(e))};return void document.addEventListener("visibilitychange",t)}this.signinSilent(ic.getAccessTokenExpiringNotificationTimeInSeconds()).then(()=>{this.initAccessTokenExpiringTimer()}).catch(t=>{if(lc.error(`OIDC: proactive refresh failed (attempt ${e}/2):`,t),e<2){const t=setTimeout(()=>{this.retryTimers.delete(t),this.proactiveRefreshWithRetry(e+1)},3e3);this.retryTimers.add(t)}else lc.error("OIDC: proactive refresh exhausted all retries")})}async removeUser(){const e=this.ensureInitialized();this.accessTokenExpiringTimer?.cancel(),this.retryTimers.forEach(clearTimeout),this.retryTimers.clear(),await e.removeUser()}onUserLoaded(e){this.ensureInitialized().events.addUserLoaded(e)}offUserLoaded(e){this.ensureInitialized().events.removeUserLoaded(e)}onUserUnloaded(e){this.ensureInitialized().events.addUserUnloaded(e)}offUserUnloaded(e){this.ensureInitialized().events.removeUserUnloaded(e)}onSilentRenewError(e){this.ensureInitialized().events.addSilentRenewError(e)}offSilentRenewError(e){this.ensureInitialized().events.removeSilentRenewError(e)}onAccessTokenExpiring(e){this.ensureInitialized().events.addAccessTokenExpiring(e)}offAccessTokenExpiring(e){this.ensureInitialized().events.removeAccessTokenExpiring(e)}onAccessTokenExpired(e){this.ensureInitialized().events.addAccessTokenExpired(e)}offAccessTokenExpired(e){this.ensureInitialized().events.removeAccessTokenExpired(e)}getLogoutUrl(e,t){const r=new URL(function(e){return`${ic.getAuthOrigin()}${e.logoutPath}`}(e));return t&&r.searchParams.set("redirect_to",t),r.toString()}getWindowOriginParam(){const e=new URL(window.location.href).searchParams.get("origin");if(!e)throw new Error("iframe origin param is required");return e}async getTopUrl(){return(await oc({type:Ko})).topUrl}async isOAuthFlowPending(){try{return(await oc({type:Bo})).isPending}catch(e){return lc.warn("OIDC: isOAuthFlowPending() - failed to check, assuming not pending:",e),!1}}async triggerLoginFlowViaParent({loginPath:e,windowPath:t}){lc.info("OIDC: triggerLoginFlowViaParent() - starting");const r=await this.getTopUrl(),n=new URL(r).origin,s=`${n}${t}`,i=new URL(`${window.location.origin}${e}`);i.searchParams.set(Jo,n),i.searchParams.set("oauth2_top_wp_url",s),lc.info("OIDC: triggerLoginFlowViaParent() - redirecting parent to:",i.toString()),await oc({type:Go,payload:{url:i.toString()}})}async handleLoginFlowComplete(e,t){if(!t)throw new Error("oauthUserState is required");const r=this.getWindowOriginParam(),n=t.state,s=n?.data?.[Jo];if(r!==s)throw lc.error("OIDC: handleLoginFlowComplete - origin mismatch:",r,"!==",s),new Error("Invalid origin in OAuth state");try{const e=new xo(t);await this.storeUser(e),this.initAccessTokenExpiringTimer(),window.dispatchEvent(new CustomEvent("oidc-auth-completed"))}catch(t){lc.error("OIDC: handleLoginFlowComplete - FAILED to store user:",t),await this.triggerLoginFlowViaParent(e)}}async triggerLogoutViaParent(e,t=!0){const r=await this.getTopUrl(),n=new URL(r).origin,s=t?`${n}${e.windowPath}`:n;await this.removeUser();const i=this.getLogoutUrl(e,s);await oc({type:Go,payload:{url:i}})}async cleanOAuthParamsFromUrl(){try{const e=await this.getTopUrl(),t=new URL(e);t.searchParams.delete("oauth_code"),t.searchParams.delete("oauth_state"),t.searchParams.delete("start-oauth"),t.searchParams.delete(Qo),t.searchParams.delete(Yo),await oc({type:Wo,payload:{url:t.toString()}})}catch(e){lc.warn("Failed to clean OAuth params from URL:",e)}}setupLoginFlowMessageListener(e){let t=!1;const r=r=>{if(r.data?.type!==Vo)return;if(r.origin!==nc())return void lc.error("OIDC: origin mismatch - expected:",nc(),"received:",r.origin);if(t)return void lc.debug("OIDC: LOGIN_FLOW_COMPLETE already processed, ignoring duplicate");const n=r.data.payload;n?.oauthState?(t=!0,this.handleLoginFlowComplete(e,n.oauthState).catch(e=>{lc.error("OIDC: Failed to handle login flow complete:",e),t=!1})):lc.warn("OIDC: LOGIN_FLOW_COMPLETE but no oauthState in payload")};return window.addEventListener("message",r),()=>{window.removeEventListener("message",r)}}async getTokenExpirationInfo(){const e=await this.getUser();if(!e||!e.expires_at)return{expiresAt:null,expiresInSeconds:null,isExpired:!0};const t=new Date(1e3*e.expires_at),r=Date.now(),n=Math.floor((1e3*e.expires_at-r)/1e3);return{expiresAt:t,expiresInSeconds:n,isExpired:n<=0}}async forceTokenRefresh(){return lc.info("OIDC: forceTokenRefresh() - manually triggering token refresh"),this.signinSilent()}}const hc=uc.getInstance();"undefined"!=typeof window&&(window.oidcAuthClient=hc);const pc=rc("oidc-auth:oidc-auth-redirect");function mc(e,t){e.postMessage({status:"success",payload:t})}function fc(e,t){e.postMessage({status:"error",payload:t})}function gc({targets:e,onSuccess:t,attempt:r=1}){const n=new URLSearchParams(window.location.search);if(!n.get(Qo))return void pc.warn("OIDC: No login_success param found, skipping");const s=n.get(Yo);if(s){if(!e.window?.contentWindow||!e.windowURL)return pc.warn("Cannot forward OIDC state: iframe not available"),void(r<5?setTimeout(()=>{gc({targets:e,onSuccess:t,attempt:r+1})},500):pc.error("OIDC: Failed to forward login flow after",5,"attempts - iframe never became available"));try{const r=JSON.parse(s),n=r.state?.data?.[Jo];if(n&&n!==window.location.origin)return void pc.error("Origin mismatch in OIDC state:",n,"vs",window.location.origin);!function(e,t){const r=t.window?.contentWindow,n=t.windowURL?.origin;r&&n?r.postMessage({type:Vo,payload:e},n):pc.warn("Cannot send OIDC state: window or origin not available")}({oauthState:r},e);const i=new URL(window.location.href);i.searchParams.delete(Qo),i.searchParams.delete(Yo),history.replaceState({},"",i.toString()),t?.()}catch(e){pc.error("Failed to parse or forward OIDC state:",e)}}else pc.warn("OIDC login complete but no state found in URL")}const _c=ka("iframe-utils"),yc=e=>(e=>!!e&&document.contains(e))(e.iframe)?e.iframe:null,wc=(e,t)=>((e,t,r)=>!!e?.contentWindow&&(t?(e.contentWindow.postMessage(r,t),!0):(_c.error("Could not determine target origin for Angie iframe"),!1)))(yc(e),(e=>{if(e.iframeUrlObject)return e.iframeUrlObject.origin;const t=yc(e);return t?(e=>{try{return new URL(e.src).origin}catch(e){return _c.error("Error parsing iframe URL:",e),null}})(t):null})(e),t),vc=(e,t,r)=>{const n=document.getElementById(r??qa.containerId);n&&n.setAttribute("aria-hidden",t?"false":"true"),t?e.removeAttribute("tabindex"):e.setAttribute("tabindex","-1")},bc=(e,t)=>{const r=t?.contentWindow;return!r||!e.source||e.source===r},kc=(e,t,r)=>e.origin===t&&bc(e,r),Sc=()=>Math.random().toString(36).substring(2,8),$c=(e,t)=>{e.postMessage({status:"success",payload:t})},Ec=(e,t)=>{e.postMessage({status:"error",payload:t})},Tc=ka("sidebar");let Ic=!1;const xc="open",Pc="closed",Cc="angie_sidebar_state",Rc="angie_sidebar_width";function Ac(){if("undefined"==typeof window)return 370;try{const e=window.localStorage.getItem(Rc);if(e){const t=parseInt(e,10);if(t>=350&&t<=590)return t}}catch(e){Tc.warn("localStorage not available")}return 370}function Oc(){return"undefined"==typeof window?null:localStorage.getItem(Cc)}function Nc(e){document.documentElement.style.setProperty("--angie-sidebar-width",`${e}px`)}function zc(e){"undefined"!=typeof window&&window.toggleAngieSidebar&&window.toggleAngieSidebar(e===xc,!0)}let jc=!1;function Uc(e){e?.skipDefaultCss||function(){if("undefined"==typeof document||Ic)return;const e="angie-sidebar-styles";if(document.getElementById(e))return void(Ic=!0);const t=document.createElement("style");t.id=e,t.textContent="/* Angie Sidebar - CSS Variables */\n:root {\n --angie-sidebar-z-index: 1200; /* below MUI popups, elementor popups and media library modal */\n --angie-sidebar-width: 330px;\n --angie-sidebar-transition: margin 0.3s ease-in-out, transform 0.3s ease-in-out;\n /* Direction-aware transform values for sidebar positioning */\n --angie-sidebar-hide-transform: translateX(-100%); /* LTR: hide to the left */\n --angie-sidebar-show-transform: translateX(0);\n}\n\n/* RTL-specific transform values */\n[dir=\"rtl\"] {\n --angie-sidebar-hide-transform: translateX(100%); /* RTL: hide to the right */\n}\n\n/* Respect user's motion preferences */\n@media (prefers-reduced-motion: reduce) {\n :root {\n --angie-sidebar-transition: none;\n }\n}\n\n/* Apply transitions only when user is actively toggling */\nbody.angie-sidebar-transitioning {\n transition: var(--angie-sidebar-transition) !important;\n}\n\nbody.angie-sidebar-transitioning #angie-sidebar-container {\n transition: var(--angie-sidebar-transition) !important;\n}\n\n/* Layout (default) - Push content */\n@media (min-width: 768px) {\n body.angie-sidebar-active {\n padding-inline-start: var(--angie-sidebar-width) !important;\n }\n\n #angie-sidebar-container {\n position: fixed;\n top: 0;\n inset-inline-start: 0;\n width: var(--angie-sidebar-width);\n height: 100vh;\n z-index: var(--angie-sidebar-z-index) !important; /* below elementor popups and media library modal */\n background: #FCFCFC;\n transform: var(--angie-sidebar-hide-transform);\n outline: none;\n overflow: hidden;\n /* No default transition - only when transitioning */\n }\n\n /* Resize handle */\n #angie-sidebar-container::after {\n content: '';\n position: absolute;\n top: 0;\n inset-inline-end: 0;\n width: 4px;\n height: 100%;\n cursor: ew-resize;\n background: transparent;\n z-index: 1000001;\n }\n\n /* Pink border during resize */\n #angie-sidebar-container.angie-resizing {\n border-inline-end-color: #ff69b4 !important;\n border-inline-end-width: 2px !important;\n }\n\n /* Disable iframe pointer events during resize */\n #angie-sidebar-container.angie-resizing iframe#angie-iframe {\n pointer-events: none !important;\n }\n}\n\n/* Active states */\nbody.angie-sidebar-active #angie-sidebar-container {\n transform: var(--angie-sidebar-show-transform);\n}\n\n/* Studio mode - sidebar takes full width */\n@media (min-width: 768px) {\n html.angie-studio-active body.angie-sidebar-active #angie-sidebar-container {\n width: 100%;\n }\n}\n\n/* High contrast mode support */\n@media (prefers-contrast: high) {\n #angie-sidebar-container {\n border-color: #000;\n box-shadow: none;\n }\n}\n\n/* Screen reader only class */\n.angie-sr-only {\n position: absolute;\n width: 1px;\n height: 1px;\n padding: 0;\n margin: -1px;\n overflow: hidden;\n clip: rect(0, 0, 0, 0);\n white-space: nowrap;\n border: 0;\n}\n\n/* Plugin conflict resolution */\nbody.angie-sidebar-active {\n /* Reset common conflicting styles */\n box-sizing: border-box !important;\n position: relative !important;\n}\n\n#angie-sidebar-toggle {\n z-index: 99999 !important;\n}\n";const r=document.head||document.getElementsByTagName("head")[0];r.insertBefore(t,r.firstChild),Ic=!0}();const t=e?.instance??qa;"undefined"!=typeof window&&(window.toggleAngieSidebar=function(e,t=qa){return function(r,n){const s=document.body,i=document.getElementById(t.containerId);if(!i)return void Tc.warn("Required elements not found!");const a=s.classList.contains("angie-sidebar-active"),o=void 0!==r?r:!a;n||(s.classList.add("angie-sidebar-transitioning"),setTimeout(function(){s.classList.remove("angie-sidebar-transitioning")},300)),o?s.classList.add("angie-sidebar-active"):s.classList.remove("angie-sidebar-active"),t.iframe&&vc(t.iframe,o,t.containerId),function(e,t,r=qa){e&&setTimeout(function(){wc(r,{type:"focusInput"})},t)}(o,n?0:300,t),e&&e(o,i,n),function(e){try{localStorage.setItem(Cc,e)}catch(e){Tc.warn("localStorage not available")}}(o?xc:Pc);const c=new CustomEvent("angieSidebarToggle",{detail:{isOpen:o,sidebar:i,skipTransition:n}});document.dispatchEvent(c),wc(t,{type:xa.ANGIE_SIDEBAR_TOGGLED,payload:{state:o?"opened":"closed"}})}}(e?.onToggle,t),function(e=qa){jc||(jc=!0,window.addEventListener("message",function(t){if("toggleAngieSidebar"!==t.data?.type)return;const r=e.iframeUrlObject?.origin;if(!(r?kc(t,r,e.iframe):bc(t,e.iframe)))return;const{force:n,skipTransition:s}=t.data.payload||{};window.toggleAngieSidebar&&window.toggleAngieSidebar(n,s);const i=t.ports?.[0];i&&$c(i)}))}(t))}const qc="angie_return_url",Dc=ka("referrer-redirect");function Mc(){try{const e=localStorage.getItem(qc);if(!e)return null;let t;try{t=JSON.parse(e)}catch{return Dc.warn("Stored redirect data is not valid JSON, returning null"),null}return t.url&&"string"==typeof t.url?function(e){try{return new URL(e,window.location.origin).origin===window.location.origin}catch{return!1}}(t.url)?t:(Dc.warn("Stored redirect URL is invalid, returning null:",t.url),null):(Dc.warn("Stored redirect data missing url field, returning null"),null)}catch(e){return Dc.warn("localStorage not available"),null}}function Lc(){try{localStorage.removeItem(qc)}catch(e){Dc.warn("localStorage not available")}}function Zc(e,t){return t?`${e}#angie-prompt=${encodeURIComponent(t)}`:e}const Fc=ka("oauth"),Hc=[];let Vc=!1,Kc=!1;const Gc=()=>{(()=>{try{const e=new URL(window.location.href,window.location.origin).searchParams;return e.has("start-oauth")&&"angie-app"===e.get("page")}catch{return!1}})()&&(Fc.log("Post-consent flow detected, checking for referrer redirect"),function(){const e=Mc();e&&(Lc(),window.location.href=Zc(e.url,e.prompt))}())};function Wc(){const e=Mc();if(e)return Lc(),void(window.location.href=Zc(e.url,e.prompt));try{localStorage.setItem(Cc,"open")}catch(e){Fc.warn("localStorage not available")}setTimeout(()=>{window.toggleAngieSidebar(!0)},500)}const Bc=e=>{Hc.includes(e)||Hc.push(e)},Jc=()=>{for(const e of Hc.flatMap(e=>e.iframe&&e.iframeUrlObject?[{window:e.iframe,windowURL:e.iframeUrlObject}]:[]))gc({targets:e,onSuccess:Wc})},Qc="sidebar",Yc="floatingChat",Xc=[],ed=()=>Xc.length,td=e=>Xc.find(t=>t.instanceId===e)??null,rd=()=>Xc.some(e=>e.layout===Qc),nd=ka("sdk");var sd;(sd||(sd={})).POST_MESSAGE="postMessage";const id=new Map,ad=[];let od=null;const cd=()=>{0===ad.length||od||(od=e=>{const t=(e=>{if(e.origin===window.location.origin)return ad.find(t=>((e,t)=>!((!t||t!==e.instanceId)&&(t&&td(t)||t&&null===td(t)&&ed()>=1||(Xc.find(e=>null!==e.iframe)||(0===Xc.length&&qa.iframe?qa:null))!==e)))(t,e?.data?.payload?.instanceId))??null;const t=ad.find(t=>t.iframe?.contentWindow===e.source);return t&&kc(e,t.iframeUrlObject?.origin,t.iframe)?t:null})(e);if(t)switch(e?.data?.type){case xa.SDK_ANGIE_ALL_SERVERS_REGISTERED:break;case xa.SDK_ANGIE_READY_PING:{const t=e.ports[0];nd.log("Angie is ready",e),$c(t,{message:"Angie is ready"});break}case xa.SDK_REQUEST_CLIENT_CREATION:{const r=e.data.payload,n=e.ports[0];((e,t)=>{if(e.iframe)return void t();let r=id.get(e);r||(r=[],id.set(e,r)),r.push(t)})(t,()=>{try{const s=new MessageChannel;s.port1.onmessage=e=>{n.postMessage({success:!0,data:e.data})};const i={type:xa.SDK_REQUEST_CLIENT_CREATION,payload:{success:!0,...r,clientId:`dynamic-client-${r.serverName}-${r.serverVersion}`,requestId:e.data.payload.requestId},timestamp:Date.now()};t.iframe?.contentWindow?.postMessage(i,t.iframeUrlObject?.origin||"",[s.port2])}catch(e){nd.error(`Failed to create client for SDK server "${r.serverName}":`,e)}});break}case xa.SDK_TRIGGER_ANGIE:nd.log("SDK Trigger Angie received",e.data);try{const{requestId:r,prompt:n,context:s,contextAttachment:i,suggestions:a,options:o}=e.data.payload;if(!t.iframe)throw new Error("Iframe not found");t.iframe.contentWindow?.postMessage({type:xa.SDK_TRIGGER_ANGIE,payload:{requestId:r,prompt:n,context:s,contextAttachment:i,suggestions:a,options:o}},t.iframeUrlObject?.origin||""),window.postMessage({type:xa.SDK_TRIGGER_ANGIE_RESPONSE,payload:{success:!0,requestId:r,response:"Angie triggered successfully"}},window.location.origin)}catch(t){nd.error("Failed to trigger Angie:",t),window.postMessage({type:xa.SDK_TRIGGER_ANGIE_RESPONSE,payload:{success:!1,requestId:e.data.payload?.requestId,error:t instanceof Error?t.message:"Unknown error"}},window.location.origin)}}},window.addEventListener("message",od))},dd=e=>{ad.includes(e)||ad.push(e)},ld=ka("iframe"),ud=[];let hd=null;const pd=e=>{if(e.includes("://")||e.startsWith("//"))return!1;try{const t="https://test.com";return new URL(e,t).origin===t}catch{return!1}},md=async(e=qa)=>{if(e.iframe?.contentWindow&&e.iframeUrlObject)try{ld.log("Disabling navigation prevention in Angie iframe"),e.iframe.contentWindow.postMessage({type:xa.ANGIE_DISABLE_NAVIGATION_PREVENTION},e.iframeUrlObject.origin),await new Promise(e=>setTimeout(e,100))}catch(e){throw ld.error("Failed to disable navigation prevention:",e),e}else ld.warn("Cannot disable navigation prevention: iframe or origin not available")},fd=async(e,t=qa)=>{if(window.screen.availWidth<=768)return void ld.log("Mobile detected, skipping iframe injection");const r=t.containerId;let n=document.getElementById(r);if(!n){const e=performance.now();if(ld.log("⏱️ Waiting for sidebar container..."),await new Promise(e=>{let t=0;const s=setInterval(()=>{n=document.getElementById(r),t++,(n||t>20)&&(clearInterval(s),n&&e())},100);setTimeout(()=>{if(clearInterval(s),n)return void e();const t=new MutationObserver(()=>{n=document.getElementById(r),n&&(t.disconnect(),e())});t.observe(document.body,{childList:!0,subtree:!0}),setTimeout(()=>{t.disconnect(),e()},8e3)},2e3)}),ld.log(`⏱️ Sidebar container detection took: ${(performance.now()-e).toFixed(2)}ms`),!n)return void ld.error("Sidebar container not found")}const{iframe:s,iframeUrlObject:i}=await(async e=>{const t=e.origin,r=new URL(e.path,t),n=e.instanceId||Sc(),s=r.pathname.slice(1).replace(/\//,"--")+"-"+n;return new Promise(n=>{const i=new URL(t);i.pathname=r.pathname;const a=window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light";if(i.searchParams.append("colorScheme",e.uiTheme||a||"light"),i.searchParams.append("sdkVersion",e.sdkVersion),i.searchParams.append("instanceId",s),i.searchParams.append("origin",window.location.origin),e.isRTL&&i.searchParams.append("isRTL",e.isRTL?"true":"false"),e.appId&&i.searchParams.append("appId",e.appId),"localhost"===window.location.hostname&&window.location.search.includes("debug_error")){const e=new URLSearchParams(window.location.search).get("debug_error");e&&i.searchParams.append("debug_error",e)}r.searchParams.forEach((e,t)=>{i.searchParams.set(t,e)}),i.searchParams.set("ver",(new Date).getTime().toString());const o=e.parent||document,c=o.createElement("iframe"),d={"background-color":"transparent","color-scheme":"normal",...e.css};window.addEventListener("message",async t=>{if(kc(t,i.origin,c))switch(t.data.type){case Ca.ANGIE_READY:n({iframe:c,iframeUrlObject:i});break;case Ca.ANGIE_LOADED:c.contentWindow?.postMessage({type:Ca.HOST_READY,instanceId:s,...e.embeddedConfig?{embedded:e.embeddedConfig}:{}},i.origin)}}),c.setAttribute("src",i.href),c.id=e.iframeElementId||"angie-iframe",c.setAttribute("frameborder","0"),c.setAttribute("scrolling","no"),c.setAttribute("style",Object.entries(d).map(([e,t])=>`${e}: ${t}`).join("; ")),c.setAttribute("allow","clipboard-write; clipboard-read"),e.insertCallback?e.insertCallback(c):o.body.appendChild(c)})})({origin:e.origin||"https://angie.elementor.com",path:e.path&&pd(e.path)?e.path:"angie/wp-admin",insertCallback:e=>{ld.log("Injecting Angie iframe into sidebar container"),e.setAttribute("title","Angie AI Assistant"),e.setAttribute("role","application"),e.setAttribute("aria-label","Angie AI Assistant Interface");const t=document.getElementById("angie-sidebar-loading");t&&(t.textContent=""),n?.appendChild(e)},embeddedConfig:e.embeddedConfig,css:{width:"100%",height:"100%",border:"none",outline:"none"},uiTheme:e.uiTheme,isRTL:e.isRTL,sdkVersion:"1.7.7",iframeElementId:t.iframeElementId,instanceId:t.instanceId,appId:t.appId});return t.iframe=s,t.iframeUrlObject=i,(e=>{cd();const t=id.get(e);t?.length&&(id.delete(e),t.forEach(e=>e()))})(t),dd(t),cd(),((e=qa)=>{Bc(e),Vc||(Vc=!0,function({trustedOrigin:e,onOAuthParamsCleared:t}){window.addEventListener("message",r=>{if(r.origin!==e)return;const n=r.ports?.[0];switch(r.data.type){case Ko:if(!n)return;mc(n,{topUrl:window.location.href});break;case Go:window.location.href=r.data.payload.url;break;case Wo:{if(!n)return;const e=r.data.payload.url;if(!history?.replaceState)return void fc(n,{message:"URL update not supported in this browser"});try{const r=window.location.href;history.replaceState({},"",e),function(e,t){const r=new URL(e).searchParams,n=new URL(t).searchParams,s=[Qo,Yo,Jo];return s.some(e=>r.has(e))&&!s.some(e=>n.has(e))}(r,e)&&t?.(),mc(n,{message:"URL updated successfully"})}catch(e){fc(n,{message:"URL update failed: "+(e instanceof Error?e.message:"Unknown error")})}break}case Bo:if(!n)return;mc(n,{isPending:"true"===new URLSearchParams(window.location.search).get(Qo)})}})}({trustedOrigin:e.iframeUrlObject?.origin??"",onOAuthParamsCleared:Wc}))})(t),((e=qa)=>{Bc(e),Jc(),Kc||(Kc=!0,window.addEventListener("load",()=>{Fc.log("OIDC: Window load event fired, forwarding OIDC state if present"),Jc()}))})(t),(e=>{ud.push(e),hd||(hd=e=>{const t=ud.find(t=>bc(e,t.instance.iframe));t&&t.trustedOrigins.includes(e.origin)&&(async(e,t)=>{if(e?.data?.type===xa.ANGIE_CHAT_TOGGLE)t.open=e.data.open,t.iframe&&vc(t.iframe,t.open,t.containerId);else if(e?.data?.type===xa.ANGIE_STUDIO_TOGGLE){const r=e.data.isStudioOpen;if(!t.iframe)return;if(r)document.documentElement.classList.add("angie-studio-active");else{const e=Ac();document.documentElement.style.setProperty("--angie-sidebar-width",`${e}px`),document.documentElement.classList.remove("angie-studio-active")}}else if(e?.data?.type===xa.ANGIE_NAVIGATE_TO_URL){const{url:r="",confirmed:n=!1}=e.data.payload||{};if(!n)return void ld.log("Navigation requires user confirmation");((e,t=[])=>{const r=0===t.length&&"undefined"!=typeof window?[window.location.origin]:t;if(!e.startsWith("http"))return!1;try{const t=new URL(e);return r.includes(t.origin)}catch{return!1}})(r)?(await md(t),window.location.assign(r)):ld.error("Navigation blocked: Invalid or unsafe URL",{url:r})}else if(e?.data?.type===xa.ANGIE_PAGE_RELOAD){const{confirmed:r=!1}=e.data.payload||{};if(!r)return void ld.log("Page reload requires user confirmation");ld.log("Page reload confirmed - disabling navigation prevention and reloading"),await md(t),setTimeout(()=>{window.location.reload()},50)}else e?.data?.type===Ca.RESET_HASH&&(window.location.hash="",$c(e.ports[0],{message:"Hash reset successfully"}))})(e,t.instance)},window.addEventListener("message",hd))})({instance:t,trustedOrigins:[window.location.origin,e.origin||"https://angie.elementor.com"]}),{iframe:s,iframeOrigin:i.origin}},gd=ka("registration-queue");class _d{queue=[];isProcessing=!1;add(e){const t={id:this.generateId(e),config:e,timestamp:Date.now(),status:"pending"};return this.queue.push(t),gd.log(`Added server "${e.name}" to queue`),t}getAll(){return[...this.queue]}getPending(){return this.queue.filter(e=>"pending"===e.status)}updateStatus(e,t,r){const n=this.queue.find(t=>t.id===e);n&&(n.status=t,r?n.error=r:"pending"!==t&&"registered"!==t||delete n.error,gd.log(`Updated server ${e} status to ${t}`))}async processQueue(e){if(this.isProcessing)return void gd.log("Already processing queue");this.isProcessing=!0;const t=this.getPending();gd.log(`Processing ${t.length} pending registrations`);try{for(const r of t)try{await e(r),this.updateStatus(r.id,"registered")}catch(e){const t=e instanceof Error?e.message:String(e);this.updateStatus(r.id,"failed",t),gd.error(`Failed to process registration ${r.id}:`,t)}}finally{this.isProcessing=!1}}clear(){this.queue=[],gd.log("Cleared all registrations")}resetAllToPending(){if(this.isProcessing)return gd.log("Cannot reset to pending - processing in progress"),!1;const e=this.queue.filter(e=>"registered"===e.status).length,t=this.queue.filter(e=>"failed"===e.status).length;return this.queue.forEach(e=>{"pending"!==e.status&&(e.status="pending",delete e.error)}),gd.log(`Reset ${e+t} registrations to pending`),!0}remove(e){const t=this.queue.findIndex(t=>t.id===e);return-1!==t&&(this.queue.splice(t,1),gd.log(`Removed registration ${e}`),!0)}generateId(e){return`reg_${e.name}_${e.version}_${Date.now()}`}}const yd={layout:Qc,styleTheme:"",create:!0,skipDefaultCss:!1,persistOpenState:!0,resizable:!0,chatToggleButtonEnabled:!1},wd="#angie-widget-toggle",vd={boot:{allowInIframe:!1},container:{layout:yd.layout,styleTheme:yd.styleTheme,create:yd.create,skipDefaultCss:yd.skipDefaultCss,persistOpenState:yd.persistOpenState,resizable:yd.resizable,chatToggleButtonSelector:wd},iframe:{origin:"https://angie.elementor.com",path:"angie/embedded",uiTheme:"light"}},bd=new Map;let kd=!1;const Sd=async(e,t,r)=>{if(t)try{$c(e,{payload:await t()})}catch(t){Ec(e,{message:t instanceof Error?t.message:String(t)})}else $c(e,r())},$d=(e,t)=>e&&t?`${e}::__angie::${t}`:e,Ed=(e,t)=>{const r=$d(e,t);try{const t=window.localStorage.getItem(r);return null!==t?t:r===e?null:window.localStorage.getItem(e)}catch{return null}},Td="data-angie-toggle-wired",Id=(e,t)=>{const r=document.querySelector(e);r&&(r.setAttribute("aria-expanded",t?"true":"false"),r.setAttribute("aria-label",t?"Close Angie":"Open Angie"))},xd=e=>{const t=document.querySelector(e.toggleButtonSelector);t&&"true"!==t.getAttribute(Td)&&(t.setAttribute(Td,"true"),t.addEventListener("click",e.onClick))},Pd=new Set;let Cd=!1;const Rd=e=>{for(const t of Pd)t(e)},Ad="angie-widget-toggle",Od="angie-widget-hidden",Nd="angie-widget-fullscreen",zd="angie-widget-container",jd="angie-chat-widget-styles",Ud=/^#([^\s#.[:]+)$/,qd=/^\[([^\]=]+)(?:="([^"]*)")?\]$/,Dd=e=>document.querySelector(e),Md=new Map,Ld=e=>{const t=document.getElementById(e.containerId);t&&(e.isOpen?t.classList.remove(Od):t.classList.add(Od),e.instance.iframe&&vc(e.instance.iframe,e.isOpen,e.containerId),Id(e.toggleButtonSelector,e.isOpen))},Zd=(e,t)=>{Ld({containerId:e.containerId,toggleButtonSelector:e.toggleButtonSelector,isOpen:t,instance:e.instance})},Fd=(e,t)=>{const r=t?.force;if(void 0!==r)return Zd(e,r),void(r||e.onClose?.());const n=(e=>{const t=document.getElementById(e);return!!t&&!t.classList.contains(Od)})(e.containerId);Zd(e,!n),n&&e.onClose?.()},Hd=e=>{const t=document.getElementById(e);t&&(t.classList.add(zd,Od),t.setAttribute("role","complementary"),t.setAttribute("aria-label","Angie"),t.setAttribute("aria-hidden","true"),t.setAttribute("tabindex","-1"))};let Vd=!1;const Kd={initShell:({config:e,instance:t})=>{((e,t,r=qa)=>{const n=e.chatToggleButton.enabled?e.chatToggleButton.selector:void 0;Uc({instance:r,skipDefaultCss:e.skipDefaultCss,onToggle:e=>{n&&Id(n,e),t.onToggle?.(e),!e&&t.onClose&&t.onClose()}}),(e=>{if("wordpress"!==e||"undefined"==typeof document)return;const t="angie-sidebar-wordpress-styles";if(document.getElementById(t)||(Vd=!1),Vd)return;const r=document.createElement("style");r.id=t,r.textContent="body.admin-bar {\n --angie-sidebar-z-index: 99999;\n}\n\n#angie-body-top-padding {\n height: 0;\n transition: height 0.3s ease-in-out;\n}\n\nbody.angie-sidebar-transitioning #wpadminbar {\n transition: var(--angie-sidebar-transition) !important;\n}\n\n@media (min-width: 768px) {\n body.angie-sidebar-active #angie-body-top-padding {\n width: 100%;\n height: 0;\n }\n\n body.angie-sidebar-active #wpadminbar {\n inset-inline-start: var(--angie-sidebar-width) !important;\n inset-inline-end: 0 !important;\n width: calc(100% - var(--angie-sidebar-width)) !important;\n margin-top: 0;\n }\n}\n\n@media (max-width: 768px) {\n body.angie-sidebar-active #wpadminbar {\n inset-inline-start: 0 !important;\n inset-inline-end: 0 !important;\n width: 100% !important;\n }\n}\n\nbody:not(.wp-admin) #angie-sidebar-container {\n margin-top: 3px;\n}\n",(document.head||document.getElementsByTagName("head")[0]).appendChild(r),Vd=!0})(e.styleTheme),n&&xd({toggleButtonSelector:n,onClick:e=>{e.preventDefault(),window.toggleAngieSidebar?.()}})})(e.container,e.callbacks,t)},beforeOpenIframe:({config:e})=>{var t;(t=e.container).chatToggleButton.enabled&&(t.persistOpenState&&Oc()===xc||zc(Pc))},afterOpenIframe:({config:e,instance:t})=>{((e,t=qa)=>{e.persistOpenState&&function(e=xc){!function(){if("undefined"==typeof window)return!1;const e=new URLSearchParams(window.location.search);return e.has(Qo)||e.has(Yo)||e.has(Jo)}()?zc(Oc()||e):function(){zc(Pc);try{localStorage.setItem(Cc,Pc)}catch(e){Tc.warn("localStorage not available")}}()}(e.chatToggleButton.enabled?Pc:xc),e.resizable&&function(e=qa){const t=document.getElementById(e.containerId);if(!t)return;let r=!1,n=0,s=0;t.addEventListener("mousedown",e=>{const i=t.getBoundingClientRect();("rtl"===document.documentElement.dir?e.clientX<=i.left+4:e.clientX>=i.right-4)&&(r=!0,n=e.clientX,s=i.width,t.classList.add("angie-resizing"),document.body.style.cursor="ew-resize",document.body.style.userSelect="none",e.preventDefault(),e.stopPropagation())}),document.addEventListener("mousemove",e=>{if(!r)return;let t;t="rtl"===document.documentElement.dir?n-e.clientX:e.clientX-n,Nc(Math.max(350,Math.min(590,s+t))),e.preventDefault(),e.stopPropagation()}),document.addEventListener("mouseup",n=>{if(r){r=!1,t.classList.remove("angie-resizing"),document.body.style.cursor="",document.body.style.userSelect="";const i=parseInt(getComputedStyle(document.documentElement).getPropertyValue("--angie-sidebar-width"),10);(function(e){try{localStorage.setItem(Rc,e.toString())}catch(e){Tc.warn("localStorage not available")}})(i),wc(e,{type:xa.ANGIE_SIDEBAR_RESIZED,payload:{initialWidth:s,width:i}}),n.preventDefault(),n.stopPropagation()}}),Nc(Ac())}(t)})(e.container,t)}},Gd={initShell:({config:e,instance:t})=>{const{chatToggleButton:r}=e.container;var n;(e=>{const t=(e=>e===za?jd:`${jd}-${e}`)(e);if(document.getElementById(t))return;const r=document.createElement("style");r.id=t,r.textContent=(e=>`\n#${e}.${zd} {\n\t--angie-widget-width: 400px;\n\t--angie-widget-height: 600px;\n\t--angie-widget-z-index: 99999;\n\n\tposition: fixed !important;\n\ttop: auto !important;\n\tbottom: 20px !important;\n\tinset-inline-start: auto !important;\n\tinset-inline-end: 20px !important;\n\twidth: var(--angie-widget-width) !important;\n\theight: var(--angie-widget-height) !important;\n\tmax-height: calc(100vh - 40px) !important;\n\tmax-width: calc(100vw - 40px) !important;\n\tz-index: var(--angie-widget-z-index) !important;\n\ttransform: none !important;\n\tborder-radius: 12px !important;\n\toverflow: hidden !important;\n\tbox-shadow: 0 4px 24px rgba(0, 0, 0, 0.15) !important;\n\ttransition: opacity 0.2s ease, transform 0.2s ease !important;\n}\n\n#${e}.${zd}.${Od} {\n\tdisplay: none !important;\n}\n\n#${e}.${zd} iframe {\n\twidth: 100% !important;\n\theight: 100% !important;\n\tborder: none !important;\n\tborder-radius: 12px !important;\n}\n\n\n.${Ad} {\n\t--angie-toggle-size: 56px;\n\t--angie-widget-z-index: 99999;\n\n\tposition: fixed;\n\tbottom: 20px;\n\tinset-inline-end: 20px;\n\twidth: var(--angie-toggle-size);\n\theight: var(--angie-toggle-size);\n\tborder-radius: 50%;\n\tborder: none;\n\tbackground: #EB8EFB;\n\tcolor: white;\n\tcursor: pointer;\n\tz-index: var(--angie-widget-z-index);\n\tdisplay: flex;\n\talign-items: center;\n\tjustify-content: center;\n\tbox-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);\n\ttransition: background 0.2s ease, transform 0.15s ease;\n\tpadding: 0;\n}\n\n.${Ad}:hover {\n\tbackground: #E070F5;\n\ttransform: scale(1.05);\n}\n\n.${Ad}:active {\n\ttransform: scale(0.95);\n}\n\n.${Ad}[aria-expanded="true"] {\n\tdisplay: none;\n}\n\n\n#${e}.${zd}.${Nd} {\n\tbottom: 0 !important;\n\tinset-inline-end: 0 !important;\n\twidth: 100vw !important;\n\theight: 100vh !important;\n\tmax-height: 100vh !important;\n\tmax-width: 100vw !important;\n\tborder-radius: 0 !important;\n}\n\n#${e}.${zd}.${Nd} iframe {\n\tborder-radius: 0 !important;\n}\n\n@media (max-width: 480px) {\n\t#${e}.${zd} {\n\t\tbottom: 0 !important;\n\t\tinset-inline-end: 0 !important;\n\t\twidth: 100vw !important;\n\t\theight: 100vh !important;\n\t\tmax-height: 100vh !important;\n\t\tmax-width: 100vw !important;\n\t\tborder-radius: 0 !important;\n\t}\n\n\t#${e}.${zd} iframe {\n\t\tborder-radius: 0 !important;\n\t}\n}\n`)(e),document.head.appendChild(r)})((n={containerId:e.container.id,iframeOrigin:e.iframe.origin,onClose:e.callbacks.onClose,toggleButtonSelector:r.selector,injectToggleButton:r.enabled,instance:t}).containerId),Hd(n.containerId),n.injectToggleButton&&(e=>{if(Dd(e))return;const t=document.createElement("button");((e,t)=>{const r=t.match(Ud);if(r)return void(e.id=r[1]);const n=t.match(qd);n&&e.setAttribute(n[1],n[2]??"")})(t,e),t.className=Ad,t.setAttribute("aria-label","Open Angie"),t.setAttribute("aria-expanded","false"),t.type="button",t.innerHTML='<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 16 16" fill="none">\n\t<path d="M15.0998 8.00414L14.622 8.18282C13.4991 8.60516 12.8142 9.50669 12.4001 10.6519L12.2249 11.1392L12.0497 10.6519C11.6356 9.50669 10.9109 8.60516 9.78801 8.18282L9.31018 8.00414L9.78801 7.82546C10.9109 7.40312 11.6356 6.50159 12.0497 5.3564L12.2249 4.86909L12.4001 5.3564C12.8142 6.50159 13.4991 7.40312 14.622 7.82546L15.0998 8.00414Z" fill="white"/>\n\t<path d="M2 8.42721C5.5608 8.42721 8.44479 11.3685 8.44479 15" stroke="white" stroke-width="2.05092" stroke-miterlimit="10"/>\n\t<path d="M2 7.57275C5.5608 7.57275 8.44479 4.6315 8.44479 0.999991" stroke="white" stroke-width="2.05092" stroke-miterlimit="10"/>\n</svg>',document.body.appendChild(t)})(n.toggleButtonSelector),(e=>{(e=>{xd({toggleButtonSelector:e.toggleButtonSelector,onClick:()=>{const t=Dd(e.toggleButtonSelector),r="true"===t?.getAttribute("aria-expanded");Zd(e,!r),r&&e.onClose?.()}})})(e),(e=>{const{instance:t}=e;var r;Md.get(t)?.(),Md.set(t,(r=r=>{if(!kc(r,e.iframeOrigin,t.iframe))return;const n=r.ports?.[0],{type:s,payload:i}=r.data||{};switch(s){case xa.ANGIE_SIDEBAR_TOGGLED:case"toggleAngieSidebar":Fd(e,i),n&&$c(n);break;case xa.ANGIE_STUDIO_TOGGLE:{const t=!!r.data.isStudioOpen;((e,t)=>{const r=document.getElementById(e);r&&(t?r.classList.add(Nd):r.classList.remove(Nd))})(e.containerId,t),t&&Zd(e,!0),n&&$c(n);break}}},Pd.add(r),Cd||(Cd=!0,window.addEventListener("message",Rd)),()=>{Pd.delete(r)}))})(e),rd()||(window.toggleAngieSidebar=t=>{Fd(e,{force:t})})})({containerId:n.containerId,iframeOrigin:n.iframeOrigin,onClose:n.onClose,toggleButtonSelector:n.toggleButtonSelector,instance:n.instance})},afterOpenIframe:({config:e})=>{Hd(e.container.id)}},Wd={[Qc]:Kd,[Yc]:Gd},Bd={layout:Yc,styleTheme:"",create:!0,skipDefaultCss:!1,persistOpenState:!1,resizable:!1,chatToggleButtonEnabled:!0},Jd={closeButton:"collapse"},Qd=(e,t)=>e===Yc?{closeButton:"close",...t}:t?{...Jd,...t}:Jd,Yd="angie-prompt",Xd=[],el={origin:"https://angie.elementor.com",uiTheme:"light",isRTL:!1,containerId:za,skipDefaultCss:!1,path:"angie/wp-admin"};var tl,rl,nl,sl;ka("navigation"),ka("interaction-mode"),function(e){e.Inline="inline",e.EndOfTurn="end-of-turn"}(tl||(tl={})),(sl=rl||(rl={})).assertEqual=e=>{},sl.assertIs=function(e){},sl.assertNever=function(e){throw new Error},sl.arrayToEnum=e=>{const t={};for(const r of e)t[r]=r;return t},sl.getValidEnumValues=e=>{const t=sl.objectKeys(e).filter(t=>"number"!=typeof e[e[t]]),r={};for(const n of t)r[n]=e[n];return sl.objectValues(r)},sl.objectValues=e=>sl.objectKeys(e).map(function(t){return e[t]}),sl.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},sl.find=(e,t)=>{for(const r of e)if(t(r))return r},sl.isInteger="function"==typeof Number.isInteger?e=>Number.isInteger(e):e=>"number"==typeof e&&Number.isFinite(e)&&Math.floor(e)===e,sl.joinValues=function(e,t=" | "){return e.map(e=>"string"==typeof e?`'${e}'`:e).join(t)},sl.jsonStringifyReplacer=(e,t)=>"bigint"==typeof t?t.toString():t,function(e){e.mergeShapes=(e,t)=>({...e,...t})}(nl||(nl={}));const il=rl.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),al=e=>{switch(typeof e){case"undefined":return il.undefined;case"string":return il.string;case"number":return Number.isNaN(e)?il.nan:il.number;case"boolean":return il.boolean;case"function":return il.function;case"bigint":return il.bigint;case"symbol":return il.symbol;case"object":return Array.isArray(e)?il.array:null===e?il.null:e.then&&"function"==typeof e.then&&e.catch&&"function"==typeof e.catch?il.promise:"undefined"!=typeof Map&&e instanceof Map?il.map:"undefined"!=typeof Set&&e instanceof Set?il.set:"undefined"!=typeof Date&&e instanceof Date?il.date:il.object;default:return il.unknown}},ol=rl.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 cl 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:[]},n=e=>{for(const s of e.issues)if("invalid_union"===s.code)s.unionErrors.map(n);else if("invalid_return_type"===s.code)n(s.returnTypeError);else if("invalid_arguments"===s.code)n(s.argumentsError);else if(0===s.path.length)r._errors.push(t(s));else{let e=r,n=0;for(;n<s.path.length;){const r=s.path[n];n===s.path.length-1?(e[r]=e[r]||{_errors:[]},e[r]._errors.push(t(s))):e[r]=e[r]||{_errors:[]},e=e[r],n++}}};return n(this),r}static assert(e){if(!(e instanceof cl))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,rl.jsonStringifyReplacer,2)}get isEmpty(){return 0===this.issues.length}flatten(e=e=>e.message){const t={},r=[];for(const n of this.issues)if(n.path.length>0){const r=n.path[0];t[r]=t[r]||[],t[r].push(e(n))}else r.push(e(n));return{formErrors:r,fieldErrors:t}}get formErrors(){return this.flatten()}}cl.create=e=>new cl(e);const dl=(e,t)=>{let r;switch(e.code){case ol.invalid_type:r=e.received===il.undefined?"Required":`Expected ${e.expected}, received ${e.received}`;break;case ol.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(e.expected,rl.jsonStringifyReplacer)}`;break;case ol.unrecognized_keys:r=`Unrecognized key(s) in object: ${rl.joinValues(e.keys,", ")}`;break;case ol.invalid_union:r="Invalid input";break;case ol.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${rl.joinValues(e.options)}`;break;case ol.invalid_enum_value:r=`Invalid enum value. Expected ${rl.joinValues(e.options)}, received '${e.received}'`;break;case ol.invalid_arguments:r="Invalid function arguments";break;case ol.invalid_return_type:r="Invalid function return type";break;case ol.invalid_date:r="Invalid date";break;case ol.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}"`:rl.assertNever(e.validation):r="regex"!==e.validation?`Invalid ${e.validation}`:"Invalid";break;case ol.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 ol.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 ol.custom:r="Invalid input";break;case ol.invalid_intersection_types:r="Intersection results could not be merged";break;case ol.not_multiple_of:r=`Number must be a multiple of ${e.multipleOf}`;break;case ol.not_finite:r="Number must be finite";break;default:r=t.defaultError,rl.assertNever(e)}return{message:r}};let ll=dl;var ul;!function(e){e.errToObj=e=>"string"==typeof e?{message:e}:e||{},e.toString=e=>"string"==typeof e?e:e?.message}(ul||(ul={}));function hl(e,t){const r=ll,n=(e=>{const{data:t,path:r,errorMaps:n,issueData:s}=e,i=[...r,...s.path||[]],a={...s,path:i};if(void 0!==s.message)return{...s,path:i,message:s.message};let o="";const c=n.filter(e=>!!e).slice().reverse();for(const e of c)o=e(a,{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===dl?void 0:dl].filter(e=>!!e)});e.common.issues.push(n)}class pl{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 n of t){if("aborted"===n.status)return ml;"dirty"===n.status&&e.dirty(),r.push(n.value)}return{status:e.value,value:r}}static async mergeObjectAsync(e,t){const r=[];for(const e of t){const t=await e.key,n=await e.value;r.push({key:t,value:n})}return pl.mergeObjectSync(e,r)}static mergeObjectSync(e,t){const r={};for(const n of t){const{key:t,value:s}=n;if("aborted"===t.status)return ml;if("aborted"===s.status)return ml;"dirty"===t.status&&e.dirty(),"dirty"===s.status&&e.dirty(),"__proto__"===t.value||void 0===s.value&&!n.alwaysSet||(r[t.value]=s.value)}return{status:e.value,value:r}}}const ml=Object.freeze({status:"aborted"}),fl=e=>({status:"dirty",value:e}),gl=e=>({status:"valid",value:e}),_l=e=>"aborted"===e.status,yl=e=>"dirty"===e.status,wl=e=>"valid"===e.status,vl=e=>"undefined"!=typeof Promise&&e instanceof Promise;class bl{constructor(e,t,r,n){this._cachedPath=[],this.parent=e,this.data=t,this._path=r,this._key=n}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 kl=(e,t)=>{if(wl(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 cl(e.common.issues);return this._error=t,this._error}}};function Sl(e){if(!e)return{};const{errorMap:t,invalid_type_error:r,required_error:n,description:s}=e;if(t&&(r||n))throw new Error('Can\'t use "invalid_type_error" or "required_error" in conjunction with custom error map.');return t?{errorMap:t,description:s}:{errorMap:(t,s)=>{const{message:i}=e;return"invalid_enum_value"===t.code?{message:i??s.defaultError}:void 0===s.data?{message:i??n??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 al(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:al(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new pl,ctx:{common:e.parent.common,data:e.data,parsedType:al(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const t=this._parse(e);if(vl(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:al(e)},n=this._parseSync({data:e,path:r.path,parent:r});return kl(r,n)}"~validate"(e){const t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:al(e)};if(!this["~standard"].async)try{const r=this._parseSync({data:e,path:[],parent:t});return wl(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=>wl(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:al(e)},n=this._parse({data:e,path:r.path,parent:r}),s=await(vl(n)?n:Promise.resolve(n));return kl(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,n)=>{const s=e(t),i=()=>n.addIssue({code:ol.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,n)=>!!e(r)||(n.addIssue("function"==typeof t?t(r,n):t),!1))}_refinement(e){return new Su({schema:this,typeName:Au.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 $u.create(this,this._def)}nullable(){return Eu.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return ou.create(this)}promise(){return ku.create(this,this._def)}or(e){return lu.create([this,e],this._def)}and(e){return hu.create(this,e,this._def)}transform(e){return new Su({...Sl(this._def),schema:this,typeName:Au.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const t="function"==typeof e?e:()=>e;return new Tu({...Sl(this._def),innerType:this,defaultValue:t,typeName:Au.ZodDefault})}brand(){return new Pu({typeName:Au.ZodBranded,type:this,...Sl(this._def)})}catch(e){const t="function"==typeof e?e:()=>e;return new Iu({...Sl(this._def),innerType:this,catchValue:t,typeName:Au.ZodCatch})}describe(e){return new(0,this.constructor)({...this._def,description:e})}pipe(e){return Cu.create(this,e)}readonly(){return Ru.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const El=/^c[^\s-]{8,}$/i,Tl=/^[0-9a-z]+$/,Il=/^[0-9A-HJKMNP-TV-Z]{26}$/i,xl=/^[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,Pl=/^[a-z0-9_-]{21}$/i,Cl=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Rl=/^[-+]?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)?)??$/,Al=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;let Ol;const Nl=/^(?:(?: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])$/,zl=/^(?:(?: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])$/,jl=/^(([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]))$/,Ul=/^(([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])$/,ql=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Dl=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Ml="((\\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])))",Ll=new RegExp(`^${Ml}$`);function Zl(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 Fl(e){return new RegExp(`^${Zl(e)}$`)}function Hl(e){let t=`${Ml}T${Zl(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 Vl(e,t){return!("v4"!==t&&t||!Nl.test(e))||!("v6"!==t&&t||!jl.test(e))}function Kl(e,t){if(!Cl.test(e))return!1;try{const[r]=e.split(".");if(!r)return!1;const n=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.length%4)%4,"="),s=JSON.parse(atob(n));return!("object"!=typeof s||null===s||"typ"in s&&"JWT"!==s?.typ||!s.alg||t&&s.alg!==t)}catch{return!1}}function Gl(e,t){return!("v4"!==t&&t||!zl.test(e))||!("v6"!==t&&t||!Ul.test(e))}class Wl extends $l{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==il.string){const t=this._getOrReturnCtx(e);return hl(t,{code:ol.invalid_type,expected:il.string,received:t.parsedType}),ml}const t=new pl;let r;for(const n of this._def.checks)if("min"===n.kind)e.data.length<n.value&&(r=this._getOrReturnCtx(e,r),hl(r,{code:ol.too_small,minimum:n.value,type:"string",inclusive:!0,exact:!1,message:n.message}),t.dirty());else if("max"===n.kind)e.data.length>n.value&&(r=this._getOrReturnCtx(e,r),hl(r,{code:ol.too_big,maximum:n.value,type:"string",inclusive:!0,exact:!1,message:n.message}),t.dirty());else if("length"===n.kind){const s=e.data.length>n.value,i=e.data.length<n.value;(s||i)&&(r=this._getOrReturnCtx(e,r),s?hl(r,{code:ol.too_big,maximum:n.value,type:"string",inclusive:!0,exact:!0,message:n.message}):i&&hl(r,{code:ol.too_small,minimum:n.value,type:"string",inclusive:!0,exact:!0,message:n.message}),t.dirty())}else if("email"===n.kind)Al.test(e.data)||(r=this._getOrReturnCtx(e,r),hl(r,{validation:"email",code:ol.invalid_string,message:n.message}),t.dirty());else if("emoji"===n.kind)Ol||(Ol=new RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),Ol.test(e.data)||(r=this._getOrReturnCtx(e,r),hl(r,{validation:"emoji",code:ol.invalid_string,message:n.message}),t.dirty());else if("uuid"===n.kind)xl.test(e.data)||(r=this._getOrReturnCtx(e,r),hl(r,{validation:"uuid",code:ol.invalid_string,message:n.message}),t.dirty());else if("nanoid"===n.kind)Pl.test(e.data)||(r=this._getOrReturnCtx(e,r),hl(r,{validation:"nanoid",code:ol.invalid_string,message:n.message}),t.dirty());else if("cuid"===n.kind)El.test(e.data)||(r=this._getOrReturnCtx(e,r),hl(r,{validation:"cuid",code:ol.invalid_string,message:n.message}),t.dirty());else if("cuid2"===n.kind)Tl.test(e.data)||(r=this._getOrReturnCtx(e,r),hl(r,{validation:"cuid2",code:ol.invalid_string,message:n.message}),t.dirty());else if("ulid"===n.kind)Il.test(e.data)||(r=this._getOrReturnCtx(e,r),hl(r,{validation:"ulid",code:ol.invalid_string,message:n.message}),t.dirty());else if("url"===n.kind)try{new URL(e.data)}catch{r=this._getOrReturnCtx(e,r),hl(r,{validation:"url",code:ol.invalid_string,message:n.message}),t.dirty()}else"regex"===n.kind?(n.regex.lastIndex=0,n.regex.test(e.data)||(r=this._getOrReturnCtx(e,r),hl(r,{validation:"regex",code:ol.invalid_string,message:n.message}),t.dirty())):"trim"===n.kind?e.data=e.data.trim():"includes"===n.kind?e.data.includes(n.value,n.position)||(r=this._getOrReturnCtx(e,r),hl(r,{code:ol.invalid_string,validation:{includes:n.value,position:n.position},message:n.message}),t.dirty()):"toLowerCase"===n.kind?e.data=e.data.toLowerCase():"toUpperCase"===n.kind?e.data=e.data.toUpperCase():"startsWith"===n.kind?e.data.startsWith(n.value)||(r=this._getOrReturnCtx(e,r),hl(r,{code:ol.invalid_string,validation:{startsWith:n.value},message:n.message}),t.dirty()):"endsWith"===n.kind?e.data.endsWith(n.value)||(r=this._getOrReturnCtx(e,r),hl(r,{code:ol.invalid_string,validation:{endsWith:n.value},message:n.message}),t.dirty()):"datetime"===n.kind?Hl(n).test(e.data)||(r=this._getOrReturnCtx(e,r),hl(r,{code:ol.invalid_string,validation:"datetime",message:n.message}),t.dirty()):"date"===n.kind?Ll.test(e.data)||(r=this._getOrReturnCtx(e,r),hl(r,{code:ol.invalid_string,validation:"date",message:n.message}),t.dirty()):"time"===n.kind?Fl(n).test(e.data)||(r=this._getOrReturnCtx(e,r),hl(r,{code:ol.invalid_string,validation:"time",message:n.message}),t.dirty()):"duration"===n.kind?Rl.test(e.data)||(r=this._getOrReturnCtx(e,r),hl(r,{validation:"duration",code:ol.invalid_string,message:n.message}),t.dirty()):"ip"===n.kind?Vl(e.data,n.version)||(r=this._getOrReturnCtx(e,r),hl(r,{validation:"ip",code:ol.invalid_string,message:n.message}),t.dirty()):"jwt"===n.kind?Kl(e.data,n.alg)||(r=this._getOrReturnCtx(e,r),hl(r,{validation:"jwt",code:ol.invalid_string,message:n.message}),t.dirty()):"cidr"===n.kind?Gl(e.data,n.version)||(r=this._getOrReturnCtx(e,r),hl(r,{validation:"cidr",code:ol.invalid_string,message:n.message}),t.dirty()):"base64"===n.kind?ql.test(e.data)||(r=this._getOrReturnCtx(e,r),hl(r,{validation:"base64",code:ol.invalid_string,message:n.message}),t.dirty()):"base64url"===n.kind?Dl.test(e.data)||(r=this._getOrReturnCtx(e,r),hl(r,{validation:"base64url",code:ol.invalid_string,message:n.message}),t.dirty()):rl.assertNever(n);return{status:t.value,value:e.data}}_regex(e,t,r){return this.refinement(t=>e.test(t),{validation:t,code:ol.invalid_string,...ul.errToObj(r)})}_addCheck(e){return new Wl({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...ul.errToObj(e)})}url(e){return this._addCheck({kind:"url",...ul.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...ul.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...ul.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...ul.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...ul.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...ul.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...ul.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...ul.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...ul.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...ul.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...ul.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...ul.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,...ul.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,...ul.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...ul.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...ul.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t?.position,...ul.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...ul.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...ul.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...ul.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...ul.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...ul.errToObj(t)})}nonempty(e){return this.min(1,ul.errToObj(e))}trim(){return new Wl({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new Wl({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new Wl({...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 Bl(e,t){const r=(e.toString().split(".")[1]||"").length,n=(t.toString().split(".")[1]||"").length,s=r>n?r:n;return Number.parseInt(e.toFixed(s).replace(".",""))%Number.parseInt(t.toFixed(s).replace(".",""))/10**s}Wl.create=e=>new Wl({checks:[],typeName:Au.ZodString,coerce:e?.coerce??!1,...Sl(e)});class Jl 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)!==il.number){const t=this._getOrReturnCtx(e);return hl(t,{code:ol.invalid_type,expected:il.number,received:t.parsedType}),ml}let t;const r=new pl;for(const n of this._def.checks)"int"===n.kind?rl.isInteger(e.data)||(t=this._getOrReturnCtx(e,t),hl(t,{code:ol.invalid_type,expected:"integer",received:"float",message:n.message}),r.dirty()):"min"===n.kind?(n.inclusive?e.data<n.value:e.data<=n.value)&&(t=this._getOrReturnCtx(e,t),hl(t,{code:ol.too_small,minimum:n.value,type:"number",inclusive:n.inclusive,exact:!1,message:n.message}),r.dirty()):"max"===n.kind?(n.inclusive?e.data>n.value:e.data>=n.value)&&(t=this._getOrReturnCtx(e,t),hl(t,{code:ol.too_big,maximum:n.value,type:"number",inclusive:n.inclusive,exact:!1,message:n.message}),r.dirty()):"multipleOf"===n.kind?0!==Bl(e.data,n.value)&&(t=this._getOrReturnCtx(e,t),hl(t,{code:ol.not_multiple_of,multipleOf:n.value,message:n.message}),r.dirty()):"finite"===n.kind?Number.isFinite(e.data)||(t=this._getOrReturnCtx(e,t),hl(t,{code:ol.not_finite,message:n.message}),r.dirty()):rl.assertNever(n);return{status:r.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,ul.toString(t))}gt(e,t){return this.setLimit("min",e,!1,ul.toString(t))}lte(e,t){return this.setLimit("max",e,!0,ul.toString(t))}lt(e,t){return this.setLimit("max",e,!1,ul.toString(t))}setLimit(e,t,r,n){return new Jl({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:ul.toString(n)}]})}_addCheck(e){return new Jl({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:ul.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:ul.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:ul.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:ul.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:ul.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:ul.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:ul.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:ul.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:ul.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&&rl.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)}}Jl.create=e=>new Jl({checks:[],typeName:Au.ZodNumber,coerce:e?.coerce||!1,...Sl(e)});class Ql 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)!==il.bigint)return this._getInvalidInput(e);let t;const r=new pl;for(const n of this._def.checks)"min"===n.kind?(n.inclusive?e.data<n.value:e.data<=n.value)&&(t=this._getOrReturnCtx(e,t),hl(t,{code:ol.too_small,type:"bigint",minimum:n.value,inclusive:n.inclusive,message:n.message}),r.dirty()):"max"===n.kind?(n.inclusive?e.data>n.value:e.data>=n.value)&&(t=this._getOrReturnCtx(e,t),hl(t,{code:ol.too_big,type:"bigint",maximum:n.value,inclusive:n.inclusive,message:n.message}),r.dirty()):"multipleOf"===n.kind?e.data%n.value!==BigInt(0)&&(t=this._getOrReturnCtx(e,t),hl(t,{code:ol.not_multiple_of,multipleOf:n.value,message:n.message}),r.dirty()):rl.assertNever(n);return{status:r.value,value:e.data}}_getInvalidInput(e){const t=this._getOrReturnCtx(e);return hl(t,{code:ol.invalid_type,expected:il.bigint,received:t.parsedType}),ml}gte(e,t){return this.setLimit("min",e,!0,ul.toString(t))}gt(e,t){return this.setLimit("min",e,!1,ul.toString(t))}lte(e,t){return this.setLimit("max",e,!0,ul.toString(t))}lt(e,t){return this.setLimit("max",e,!1,ul.toString(t))}setLimit(e,t,r,n){return new Ql({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:ul.toString(n)}]})}_addCheck(e){return new Ql({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:ul.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:ul.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:ul.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:ul.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:ul.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}}Ql.create=e=>new Ql({checks:[],typeName:Au.ZodBigInt,coerce:e?.coerce??!1,...Sl(e)});class Yl extends $l{_parse(e){if(this._def.coerce&&(e.data=Boolean(e.data)),this._getType(e)!==il.boolean){const t=this._getOrReturnCtx(e);return hl(t,{code:ol.invalid_type,expected:il.boolean,received:t.parsedType}),ml}return gl(e.data)}}Yl.create=e=>new Yl({typeName:Au.ZodBoolean,coerce:e?.coerce||!1,...Sl(e)});class Xl extends $l{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==il.date){const t=this._getOrReturnCtx(e);return hl(t,{code:ol.invalid_type,expected:il.date,received:t.parsedType}),ml}if(Number.isNaN(e.data.getTime()))return hl(this._getOrReturnCtx(e),{code:ol.invalid_date}),ml;const t=new pl;let r;for(const n of this._def.checks)"min"===n.kind?e.data.getTime()<n.value&&(r=this._getOrReturnCtx(e,r),hl(r,{code:ol.too_small,message:n.message,inclusive:!0,exact:!1,minimum:n.value,type:"date"}),t.dirty()):"max"===n.kind?e.data.getTime()>n.value&&(r=this._getOrReturnCtx(e,r),hl(r,{code:ol.too_big,message:n.message,inclusive:!0,exact:!1,maximum:n.value,type:"date"}),t.dirty()):rl.assertNever(n);return{status:t.value,value:new Date(e.data.getTime())}}_addCheck(e){return new Xl({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:ul.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:ul.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}}Xl.create=e=>new Xl({checks:[],coerce:e?.coerce||!1,typeName:Au.ZodDate,...Sl(e)});class eu extends $l{_parse(e){if(this._getType(e)!==il.symbol){const t=this._getOrReturnCtx(e);return hl(t,{code:ol.invalid_type,expected:il.symbol,received:t.parsedType}),ml}return gl(e.data)}}eu.create=e=>new eu({typeName:Au.ZodSymbol,...Sl(e)});class tu extends $l{_parse(e){if(this._getType(e)!==il.undefined){const t=this._getOrReturnCtx(e);return hl(t,{code:ol.invalid_type,expected:il.undefined,received:t.parsedType}),ml}return gl(e.data)}}tu.create=e=>new tu({typeName:Au.ZodUndefined,...Sl(e)});class ru extends $l{_parse(e){if(this._getType(e)!==il.null){const t=this._getOrReturnCtx(e);return hl(t,{code:ol.invalid_type,expected:il.null,received:t.parsedType}),ml}return gl(e.data)}}ru.create=e=>new ru({typeName:Au.ZodNull,...Sl(e)});class nu extends $l{constructor(){super(...arguments),this._any=!0}_parse(e){return gl(e.data)}}nu.create=e=>new nu({typeName:Au.ZodAny,...Sl(e)});class su extends $l{constructor(){super(...arguments),this._unknown=!0}_parse(e){return gl(e.data)}}su.create=e=>new su({typeName:Au.ZodUnknown,...Sl(e)});class iu extends $l{_parse(e){const t=this._getOrReturnCtx(e);return hl(t,{code:ol.invalid_type,expected:il.never,received:t.parsedType}),ml}}iu.create=e=>new iu({typeName:Au.ZodNever,...Sl(e)});class au extends $l{_parse(e){if(this._getType(e)!==il.undefined){const t=this._getOrReturnCtx(e);return hl(t,{code:ol.invalid_type,expected:il.void,received:t.parsedType}),ml}return gl(e.data)}}au.create=e=>new au({typeName:Au.ZodVoid,...Sl(e)});class ou extends $l{_parse(e){const{ctx:t,status:r}=this._processInputParams(e),n=this._def;if(t.parsedType!==il.array)return hl(t,{code:ol.invalid_type,expected:il.array,received:t.parsedType}),ml;if(null!==n.exactLength){const e=t.data.length>n.exactLength.value,s=t.data.length<n.exactLength.value;(e||s)&&(hl(t,{code:e?ol.too_big:ol.too_small,minimum:s?n.exactLength.value:void 0,maximum:e?n.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:n.exactLength.message}),r.dirty())}if(null!==n.minLength&&t.data.length<n.minLength.value&&(hl(t,{code:ol.too_small,minimum:n.minLength.value,type:"array",inclusive:!0,exact:!1,message:n.minLength.message}),r.dirty()),null!==n.maxLength&&t.data.length>n.maxLength.value&&(hl(t,{code:ol.too_big,maximum:n.maxLength.value,type:"array",inclusive:!0,exact:!1,message:n.maxLength.message}),r.dirty()),t.common.async)return Promise.all([...t.data].map((e,r)=>n.type._parseAsync(new bl(t,e,t.path,r)))).then(e=>pl.mergeArray(r,e));const s=[...t.data].map((e,r)=>n.type._parseSync(new bl(t,e,t.path,r)));return pl.mergeArray(r,s)}get element(){return this._def.type}min(e,t){return new ou({...this._def,minLength:{value:e,message:ul.toString(t)}})}max(e,t){return new ou({...this._def,maxLength:{value:e,message:ul.toString(t)}})}length(e,t){return new ou({...this._def,exactLength:{value:e,message:ul.toString(t)}})}nonempty(e){return this.min(1,e)}}function cu(e){if(e instanceof du){const t={};for(const r in e.shape){const n=e.shape[r];t[r]=$u.create(cu(n))}return new du({...e._def,shape:()=>t})}return e instanceof ou?new ou({...e._def,type:cu(e.element)}):e instanceof $u?$u.create(cu(e.unwrap())):e instanceof Eu?Eu.create(cu(e.unwrap())):e instanceof pu?pu.create(e.items.map(e=>cu(e))):e}ou.create=(e,t)=>new ou({type:e,minLength:null,maxLength:null,exactLength:null,typeName:Au.ZodArray,...Sl(t)});class du 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=rl.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==il.object){const t=this._getOrReturnCtx(e);return hl(t,{code:ol.invalid_type,expected:il.object,received:t.parsedType}),ml}const{status:t,ctx:r}=this._processInputParams(e),{shape:n,keys:s}=this._getCached(),i=[];if(!(this._def.catchall instanceof iu&&"strip"===this._def.unknownKeys))for(const e in r.data)s.includes(e)||i.push(e);const a=[];for(const e of s){const t=n[e],s=r.data[e];a.push({key:{status:"valid",value:e},value:t._parse(new bl(r,s,r.path,e)),alwaysSet:e in r.data})}if(this._def.catchall instanceof iu){const e=this._def.unknownKeys;if("passthrough"===e)for(const e of i)a.push({key:{status:"valid",value:e},value:{status:"valid",value:r.data[e]}});else if("strict"===e)i.length>0&&(hl(r,{code:ol.unrecognized_keys,keys:i}),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 i){const n=r.data[t];a.push({key:{status:"valid",value:t},value:e._parse(new bl(r,n,r.path,t)),alwaysSet:t in r.data})}}return r.common.async?Promise.resolve().then(async()=>{const e=[];for(const t of a){const r=await t.key,n=await t.value;e.push({key:r,value:n,alwaysSet:t.alwaysSet})}return e}).then(e=>pl.mergeObjectSync(t,e)):pl.mergeObjectSync(t,a)}get shape(){return this._def.shape()}strict(e){return ul.errToObj,new du({...this._def,unknownKeys:"strict",...void 0!==e?{errorMap:(t,r)=>{const n=this._def.errorMap?.(t,r).message??r.defaultError;return"unrecognized_keys"===t.code?{message:ul.errToObj(e).message??n}:{message:n}}}:{}})}strip(){return new du({...this._def,unknownKeys:"strip"})}passthrough(){return new du({...this._def,unknownKeys:"passthrough"})}extend(e){return new du({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new du({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:Au.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new du({...this._def,catchall:e})}pick(e){const t={};for(const r of rl.objectKeys(e))e[r]&&this.shape[r]&&(t[r]=this.shape[r]);return new du({...this._def,shape:()=>t})}omit(e){const t={};for(const r of rl.objectKeys(this.shape))e[r]||(t[r]=this.shape[r]);return new du({...this._def,shape:()=>t})}deepPartial(){return cu(this)}partial(e){const t={};for(const r of rl.objectKeys(this.shape)){const n=this.shape[r];e&&!e[r]?t[r]=n:t[r]=n.optional()}return new du({...this._def,shape:()=>t})}required(e){const t={};for(const r of rl.objectKeys(this.shape))if(e&&!e[r])t[r]=this.shape[r];else{let e=this.shape[r];for(;e instanceof $u;)e=e._def.innerType;t[r]=e}return new du({...this._def,shape:()=>t})}keyof(){return wu(rl.objectKeys(this.shape))}}du.create=(e,t)=>new du({shape:()=>e,unknownKeys:"strip",catchall:iu.create(),typeName:Au.ZodObject,...Sl(t)}),du.strictCreate=(e,t)=>new du({shape:()=>e,unknownKeys:"strict",catchall:iu.create(),typeName:Au.ZodObject,...Sl(t)}),du.lazycreate=(e,t)=>new du({shape:e,unknownKeys:"strip",catchall:iu.create(),typeName:Au.ZodObject,...Sl(t)});class lu 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 cl(e.ctx.common.issues));return hl(t,{code:ol.invalid_union,unionErrors:r}),ml});{let e;const n=[];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&&n.push(r.common.issues)}if(e)return t.common.issues.push(...e.ctx.common.issues),e.result;const s=n.map(e=>new cl(e));return hl(t,{code:ol.invalid_union,unionErrors:s}),ml}}get options(){return this._def.options}}function uu(e,t){const r=al(e),n=al(t);if(e===t)return{valid:!0,data:e};if(r===il.object&&n===il.object){const r=rl.objectKeys(t),n=rl.objectKeys(e).filter(e=>-1!==r.indexOf(e)),s={...e,...t};for(const r of n){const n=uu(e[r],t[r]);if(!n.valid)return{valid:!1};s[r]=n.data}return{valid:!0,data:s}}if(r===il.array&&n===il.array){if(e.length!==t.length)return{valid:!1};const r=[];for(let n=0;n<e.length;n++){const s=uu(e[n],t[n]);if(!s.valid)return{valid:!1};r.push(s.data)}return{valid:!0,data:r}}return r===il.date&&n===il.date&&+e===+t?{valid:!0,data:e}:{valid:!1}}lu.create=(e,t)=>new lu({options:e,typeName:Au.ZodUnion,...Sl(t)});class hu extends $l{_parse(e){const{status:t,ctx:r}=this._processInputParams(e),n=(e,n)=>{if(_l(e)||_l(n))return ml;const s=uu(e.value,n.value);return s.valid?((yl(e)||yl(n))&&t.dirty(),{status:t.value,value:s.data}):(hl(r,{code:ol.invalid_intersection_types}),ml)};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])=>n(e,t)):n(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}}hu.create=(e,t,r)=>new hu({left:e,right:t,typeName:Au.ZodIntersection,...Sl(r)});class pu extends $l{_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==il.array)return hl(r,{code:ol.invalid_type,expected:il.array,received:r.parsedType}),ml;if(r.data.length<this._def.items.length)return hl(r,{code:ol.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),ml;!this._def.rest&&r.data.length>this._def.items.length&&(hl(r,{code:ol.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());const n=[...r.data].map((e,t)=>{const n=this._def.items[t]||this._def.rest;return n?n._parse(new bl(r,e,r.path,t)):null}).filter(e=>!!e);return r.common.async?Promise.all(n).then(e=>pl.mergeArray(t,e)):pl.mergeArray(t,n)}get items(){return this._def.items}rest(e){return new pu({...this._def,rest:e})}}pu.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new pu({items:e,typeName:Au.ZodTuple,rest:null,...Sl(t)})};class mu 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!==il.object)return hl(r,{code:ol.invalid_type,expected:il.object,received:r.parsedType}),ml;const n=[],s=this._def.keyType,i=this._def.valueType;for(const e in r.data)n.push({key:s._parse(new bl(r,e,r.path,e)),value:i._parse(new bl(r,r.data[e],r.path,e)),alwaysSet:e in r.data});return r.common.async?pl.mergeObjectAsync(t,n):pl.mergeObjectSync(t,n)}get element(){return this._def.valueType}static create(e,t,r){return new mu(t instanceof $l?{keyType:e,valueType:t,typeName:Au.ZodRecord,...Sl(r)}:{keyType:Wl.create(),valueType:e,typeName:Au.ZodRecord,...Sl(t)})}}class fu 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!==il.map)return hl(r,{code:ol.invalid_type,expected:il.map,received:r.parsedType}),ml;const n=this._def.keyType,s=this._def.valueType,i=[...r.data.entries()].map(([e,t],i)=>({key:n._parse(new bl(r,e,r.path,[i,"key"])),value:s._parse(new bl(r,t,r.path,[i,"value"]))}));if(r.common.async){const e=new Map;return Promise.resolve().then(async()=>{for(const r of i){const n=await r.key,s=await r.value;if("aborted"===n.status||"aborted"===s.status)return ml;"dirty"!==n.status&&"dirty"!==s.status||t.dirty(),e.set(n.value,s.value)}return{status:t.value,value:e}})}{const e=new Map;for(const r of i){const n=r.key,s=r.value;if("aborted"===n.status||"aborted"===s.status)return ml;"dirty"!==n.status&&"dirty"!==s.status||t.dirty(),e.set(n.value,s.value)}return{status:t.value,value:e}}}}fu.create=(e,t,r)=>new fu({valueType:t,keyType:e,typeName:Au.ZodMap,...Sl(r)});class gu extends $l{_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==il.set)return hl(r,{code:ol.invalid_type,expected:il.set,received:r.parsedType}),ml;const n=this._def;null!==n.minSize&&r.data.size<n.minSize.value&&(hl(r,{code:ol.too_small,minimum:n.minSize.value,type:"set",inclusive:!0,exact:!1,message:n.minSize.message}),t.dirty()),null!==n.maxSize&&r.data.size>n.maxSize.value&&(hl(r,{code:ol.too_big,maximum:n.maxSize.value,type:"set",inclusive:!0,exact:!1,message:n.maxSize.message}),t.dirty());const s=this._def.valueType;function i(e){const r=new Set;for(const n of e){if("aborted"===n.status)return ml;"dirty"===n.status&&t.dirty(),r.add(n.value)}return{status:t.value,value:r}}const a=[...r.data.values()].map((e,t)=>s._parse(new bl(r,e,r.path,t)));return r.common.async?Promise.all(a).then(e=>i(e)):i(a)}min(e,t){return new gu({...this._def,minSize:{value:e,message:ul.toString(t)}})}max(e,t){return new gu({...this._def,maxSize:{value:e,message:ul.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}}gu.create=(e,t)=>new gu({valueType:e,minSize:null,maxSize:null,typeName:Au.ZodSet,...Sl(t)});class _u 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})}}_u.create=(e,t)=>new _u({getter:e,typeName:Au.ZodLazy,...Sl(t)});class yu extends $l{_parse(e){if(e.data!==this._def.value){const t=this._getOrReturnCtx(e);return hl(t,{received:t.data,code:ol.invalid_literal,expected:this._def.value}),ml}return{status:"valid",value:e.data}}get value(){return this._def.value}}function wu(e,t){return new vu({values:e,typeName:Au.ZodEnum,...Sl(t)})}yu.create=(e,t)=>new yu({value:e,typeName:Au.ZodLiteral,...Sl(t)});class vu extends $l{_parse(e){if("string"!=typeof e.data){const t=this._getOrReturnCtx(e),r=this._def.values;return hl(t,{expected:rl.joinValues(r),received:t.parsedType,code:ol.invalid_type}),ml}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 hl(t,{received:t.data,code:ol.invalid_enum_value,options:r}),ml}return gl(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 vu.create(e,{...this._def,...t})}exclude(e,t=this._def){return vu.create(this.options.filter(t=>!e.includes(t)),{...this._def,...t})}}vu.create=wu;class bu extends $l{_parse(e){const t=rl.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(e);if(r.parsedType!==il.string&&r.parsedType!==il.number){const e=rl.objectValues(t);return hl(r,{expected:rl.joinValues(e),received:r.parsedType,code:ol.invalid_type}),ml}if(this._cache||(this._cache=new Set(rl.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){const e=rl.objectValues(t);return hl(r,{received:r.data,code:ol.invalid_enum_value,options:e}),ml}return gl(e.data)}get enum(){return this._def.values}}bu.create=(e,t)=>new bu({values:e,typeName:Au.ZodNativeEnum,...Sl(t)});class ku extends $l{unwrap(){return this._def.type}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==il.promise&&!1===t.common.async)return hl(t,{code:ol.invalid_type,expected:il.promise,received:t.parsedType}),ml;const r=t.parsedType===il.promise?t.data:Promise.resolve(t.data);return gl(r.then(e=>this._def.type.parseAsync(e,{path:t.path,errorMap:t.common.contextualErrorMap})))}}ku.create=(e,t)=>new ku({type:e,typeName:Au.ZodPromise,...Sl(t)});class Su extends $l{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===Au.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){const{status:t,ctx:r}=this._processInputParams(e),n=this._def.effect||null,s={addIssue:e=>{hl(r,e),e.fatal?t.abort():t.dirty()},get path(){return r.path}};if(s.addIssue=s.addIssue.bind(s),"preprocess"===n.type){const e=n.transform(r.data,s);if(r.common.async)return Promise.resolve(e).then(async e=>{if("aborted"===t.value)return ml;const n=await this._def.schema._parseAsync({data:e,path:r.path,parent:r});return"aborted"===n.status?ml:"dirty"===n.status||"dirty"===t.value?fl(n.value):n});{if("aborted"===t.value)return ml;const n=this._def.schema._parseSync({data:e,path:r.path,parent:r});return"aborted"===n.status?ml:"dirty"===n.status||"dirty"===t.value?fl(n.value):n}}if("refinement"===n.type){const e=e=>{const t=n.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 n=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return"aborted"===n.status?ml:("dirty"===n.status&&t.dirty(),e(n.value),{status:t.value,value:n.value})}return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(r=>"aborted"===r.status?ml:("dirty"===r.status&&t.dirty(),e(r.value).then(()=>({status:t.value,value:r.value}))))}if("transform"===n.type){if(!1===r.common.async){const e=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!wl(e))return ml;const i=n.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=>wl(e)?Promise.resolve(n.transform(e.value,s)).then(e=>({status:t.value,value:e})):ml)}rl.assertNever(n)}}Su.create=(e,t,r)=>new Su({schema:e,typeName:Au.ZodEffects,effect:t,...Sl(r)}),Su.createWithPreprocess=(e,t,r)=>new Su({schema:t,effect:{type:"preprocess",transform:e},typeName:Au.ZodEffects,...Sl(r)});class $u extends $l{_parse(e){return this._getType(e)===il.undefined?gl(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}$u.create=(e,t)=>new $u({innerType:e,typeName:Au.ZodOptional,...Sl(t)});class Eu extends $l{_parse(e){return this._getType(e)===il.null?gl(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}Eu.create=(e,t)=>new Eu({innerType:e,typeName:Au.ZodNullable,...Sl(t)});class Tu extends $l{_parse(e){const{ctx:t}=this._processInputParams(e);let r=t.data;return t.parsedType===il.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:t.path,parent:t})}removeDefault(){return this._def.innerType}}Tu.create=(e,t)=>new Tu({innerType:e,typeName:Au.ZodDefault,defaultValue:"function"==typeof t.default?t.default:()=>t.default,...Sl(t)});class Iu extends $l{_parse(e){const{ctx:t}=this._processInputParams(e),r={...t,common:{...t.common,issues:[]}},n=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return vl(n)?n.then(e=>({status:"valid",value:"valid"===e.status?e.value:this._def.catchValue({get error(){return new cl(r.common.issues)},input:r.data})})):{status:"valid",value:"valid"===n.status?n.value:this._def.catchValue({get error(){return new cl(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}}Iu.create=(e,t)=>new Iu({innerType:e,typeName:Au.ZodCatch,catchValue:"function"==typeof t.catch?t.catch:()=>t.catch,...Sl(t)});class xu extends $l{_parse(e){if(this._getType(e)!==il.nan){const t=this._getOrReturnCtx(e);return hl(t,{code:ol.invalid_type,expected:il.nan,received:t.parsedType}),ml}return{status:"valid",value:e.data}}}xu.create=e=>new xu({typeName:Au.ZodNaN,...Sl(e)}),Symbol("zod_brand");class Pu 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}}class Cu 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?ml:"dirty"===e.status?(t.dirty(),fl(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?ml:"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 Cu({in:e,out:t,typeName:Au.ZodPipeline})}}class Ru extends $l{_parse(e){const t=this._def.innerType._parse(e),r=e=>(wl(e)&&(e.value=Object.freeze(e.value)),e);return vl(t)?t.then(e=>r(e)):r(t)}unwrap(){return this._def.innerType}}var Au;Ru.create=(e,t)=>new Ru({innerType:e,typeName:Au.ZodReadonly,...Sl(t)}),du.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"}(Au||(Au={}));const Ou=Wl.create,Nu=Jl.create,zu=(xu.create,Ql.create,Yl.create,Xl.create,eu.create,tu.create,ru.create,nu.create),ju=(su.create,iu.create,au.create,ou.create),Uu=du.create,qu=(du.strictCreate,lu.create,hu.create,pu.create,mu.create),Du=(fu.create,gu.create,_u.create,yu.create,vu.create);bu.create,ku.create,Su.create,$u.create,Eu.create,Su.createWithPreprocess,Cu.create;const Mu=n("ZodMiniType",(e,t)=>{if(!e._zod)throw new Error("Uninitialized schema in ZodMiniType.");Ne.init(e,t),e.def=t,e.parse=(t,r)=>Te(e,t,r,{callee:e.parse}),e.safeParse=(t,r)=>Ce(e,t,r),e.parseAsync=async(t,r)=>xe(e,t,r,{callee:e.parseAsync}),e.safeParseAsync=async(t,r)=>Ae(e,t,r),e.check=(...r)=>e.clone({...t,checks:[...t.checks??[],...r.map(e=>"function"==typeof e?{_zod:{check:e,def:{check:"custom"},onattach:[]}}:e)]}),e.clone=(t,r)=>W(e,t,r),e.brand=()=>e,e.register=(t,r)=>(t.add(e,r),e)}),Lu=n("ZodMiniObject",(e,t)=>{_t.init(e,t),Mu.init(e,t),D(e,"shape",()=>t.shape)});function Zu(e,t){const r={type:"object",get shape(){return M(this,"shape",{...e}),this.shape},...B(t)};return new Lu(r)}function Fu(e){return!!e._zod}function Hu(e){const t=Object.values(e);if(0===t.length)return Zu({});const r=t.every(Fu),n=t.every(e=>!Fu(e));if(r)return Zu(e);if(n)return Uu(e);throw new Error("Mixed Zod versions detected in object shape.")}function Vu(e,t){return Fu(e)?Ce(e,t):e.safeParse(t)}async function Ku(e,t){if(Fu(e))return await Ae(e,t);const r=e;return await r.safeParseAsync(t)}function Gu(e){if(!e)return;let t;if(Fu(e)){const r=e;t=r._zod?.def?.shape}else t=e.shape;if(t){if("function"==typeof t)try{return t()}catch{return}return t}}function Wu(e){if(e){if("object"==typeof e){const t=e;if(!e._def&&!t._zod){const t=Object.values(e);if(t.length>0&&t.every(e=>"object"==typeof e&&null!==e&&(void 0!==e._def||void 0!==e._zod||"function"==typeof e.parse)))return Hu(e)}}if(Fu(e)){const t=e,r=t._zod?.def;if(r&&("object"===r.type||void 0!==r.shape))return e}else if(void 0!==e.shape)return e}}function Bu(e){if(e&&"object"==typeof e){if("issues"in e&&Array.isArray(e.issues)&&e.issues.length>0)return e.issues.map(e=>{return e.path?.length?`${e.message} at ${t=e.path,0===t.length?"object root":t.reduce((e,t,r)=>0===r?String(t):"number"==typeof t?`${e}[${t}]`:`${e}.${t}`,"")}`:e.message;var t}).join("\n");if("message"in e&&"string"==typeof e.message)return e.message;try{return JSON.stringify(e)}catch{return String(e)}}return String(e)}function Ju(e){if(Fu(e)){const t=e,r=t._zod?.def;if(r){if(void 0!==r.value)return r.value;if(Array.isArray(r.values)&&r.values.length>0)return r.values[0]}}const t=e._def;if(t){if(void 0!==t.value)return t.value;if(Array.isArray(t.values)&&t.values.length>0)return t.values[0]}const r=e.value;if(void 0!==r)return r}function Qu(e){return"completed"===e||"failed"===e||"cancelled"===e}class Yu{constructor(e){this.counter=0,this.metadataRegistry=e?.metadata??Ht,this.target=e?.target??"draft-2020-12",this.unrepresentable=e?.unrepresentable??"throw",this.override=e?.override??(()=>{}),this.io=e?.io??"output",this.seen=new Map}process(e,t={path:[],schemaPath:[]}){var r;const n=e._zod.def,s={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},i=this.seen.get(e);if(i)return i.count++,t.schemaPath.includes(e)&&(i.cycle=t.path),i.schema;const a={schema:{},count:1,cycle:void 0,path:t.path};this.seen.set(e,a);const o=e._zod.toJSONSchema?.();if(o)a.schema=o;else{const r={...t,schemaPath:[...t.schemaPath,e],path:t.path},i=e._zod.parent;if(i)a.ref=i,this.process(i,r),this.seen.get(i).isParent=!0;else{const t=a.schema;switch(n.type){case"string":{const r=t;r.type="string";const{minimum:n,maximum:i,format:o,patterns:c,contentEncoding:d}=e._zod.bag;if("number"==typeof n&&(r.minLength=n),"number"==typeof i&&(r.maxLength=i),o&&(r.format=s[o]??o,""===r.format&&delete r.format),d&&(r.contentEncoding=d),c&&c.size>0){const e=[...c];1===e.length?r.pattern=e[0].source:e.length>1&&(a.schema.allOf=[...e.map(e=>({..."draft-7"===this.target?{type:"string"}:{},pattern:e.source}))])}break}case"number":{const r=t,{minimum:n,maximum:s,format:i,multipleOf:a,exclusiveMaximum:o,exclusiveMinimum:c}=e._zod.bag;"string"==typeof i&&i.includes("int")?r.type="integer":r.type="number","number"==typeof c&&(r.exclusiveMinimum=c),"number"==typeof n&&(r.minimum=n,"number"==typeof c&&(c>=n?delete r.minimum:delete r.exclusiveMinimum)),"number"==typeof o&&(r.exclusiveMaximum=o),"number"==typeof s&&(r.maximum=s,"number"==typeof o&&(o<=s?delete r.maximum:delete r.exclusiveMaximum)),"number"==typeof a&&(r.multipleOf=a);break}case"boolean":case"success":t.type="boolean";break;case"bigint":if("throw"===this.unrepresentable)throw new Error("BigInt cannot be represented in JSON Schema");break;case"symbol":if("throw"===this.unrepresentable)throw new Error("Symbols cannot be represented in JSON Schema");break;case"null":t.type="null";break;case"any":case"unknown":break;case"undefined":if("throw"===this.unrepresentable)throw new Error("Undefined cannot be represented in JSON Schema");break;case"void":if("throw"===this.unrepresentable)throw new Error("Void cannot be represented in JSON Schema");break;case"never":t.not={};break;case"date":if("throw"===this.unrepresentable)throw new Error("Date cannot be represented in JSON Schema");break;case"array":{const s=t,{minimum:i,maximum:a}=e._zod.bag;"number"==typeof i&&(s.minItems=i),"number"==typeof a&&(s.maxItems=a),s.type="array",s.items=this.process(n.element,{...r,path:[...r.path,"items"]});break}case"object":{const e=t;e.type="object",e.properties={};const s=n.shape;for(const t in s)e.properties[t]=this.process(s[t],{...r,path:[...r.path,"properties",t]});const i=new Set(Object.keys(s)),a=new Set([...i].filter(e=>{const t=n.shape[e]._zod;return"input"===this.io?void 0===t.optin:void 0===t.optout}));a.size>0&&(e.required=Array.from(a)),"never"===n.catchall?._zod.def.type?e.additionalProperties=!1:n.catchall?n.catchall&&(e.additionalProperties=this.process(n.catchall,{...r,path:[...r.path,"additionalProperties"]})):"output"===this.io&&(e.additionalProperties=!1);break}case"union":t.anyOf=n.options.map((e,t)=>this.process(e,{...r,path:[...r.path,"anyOf",t]}));break;case"intersection":{const e=t,s=this.process(n.left,{...r,path:[...r.path,"allOf",0]}),i=this.process(n.right,{...r,path:[...r.path,"allOf",1]}),a=e=>"allOf"in e&&1===Object.keys(e).length,o=[...a(s)?s.allOf:[s],...a(i)?i.allOf:[i]];e.allOf=o;break}case"tuple":{const s=t;s.type="array";const i=n.items.map((e,t)=>this.process(e,{...r,path:[...r.path,"prefixItems",t]}));if("draft-2020-12"===this.target?s.prefixItems=i:s.items=i,n.rest){const e=this.process(n.rest,{...r,path:[...r.path,"items"]});"draft-2020-12"===this.target?s.items=e:s.additionalItems=e}n.rest&&(s.items=this.process(n.rest,{...r,path:[...r.path,"items"]}));const{minimum:a,maximum:o}=e._zod.bag;"number"==typeof a&&(s.minItems=a),"number"==typeof o&&(s.maxItems=o);break}case"record":{const e=t;e.type="object",e.propertyNames=this.process(n.keyType,{...r,path:[...r.path,"propertyNames"]}),e.additionalProperties=this.process(n.valueType,{...r,path:[...r.path,"additionalProperties"]});break}case"map":if("throw"===this.unrepresentable)throw new Error("Map cannot be represented in JSON Schema");break;case"set":if("throw"===this.unrepresentable)throw new Error("Set cannot be represented in JSON Schema");break;case"enum":{const e=t,r=N(n.entries);r.every(e=>"number"==typeof e)&&(e.type="number"),r.every(e=>"string"==typeof e)&&(e.type="string"),e.enum=r;break}case"literal":{const e=t,r=[];for(const e of n.values)if(void 0===e){if("throw"===this.unrepresentable)throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if("bigint"==typeof e){if("throw"===this.unrepresentable)throw new Error("BigInt literals cannot be represented in JSON Schema");r.push(Number(e))}else r.push(e);if(0===r.length);else if(1===r.length){const t=r[0];e.type=null===t?"null":typeof t,e.const=t}else r.every(e=>"number"==typeof e)&&(e.type="number"),r.every(e=>"string"==typeof e)&&(e.type="string"),r.every(e=>"boolean"==typeof e)&&(e.type="string"),r.every(e=>null===e)&&(e.type="null"),e.enum=r;break}case"file":{const r=t,n={type:"string",format:"binary",contentEncoding:"binary"},{minimum:s,maximum:i,mime:a}=e._zod.bag;void 0!==s&&(n.minLength=s),void 0!==i&&(n.maxLength=i),a?1===a.length?(n.contentMediaType=a[0],Object.assign(r,n)):r.anyOf=a.map(e=>({...n,contentMediaType:e})):Object.assign(r,n);break}case"transform":if("throw"===this.unrepresentable)throw new Error("Transforms cannot be represented in JSON Schema");break;case"nullable":{const e=this.process(n.innerType,r);t.anyOf=[e,{type:"null"}];break}case"nonoptional":case"promise":case"optional":this.process(n.innerType,r),a.ref=n.innerType;break;case"default":this.process(n.innerType,r),a.ref=n.innerType,t.default=JSON.parse(JSON.stringify(n.defaultValue));break;case"prefault":this.process(n.innerType,r),a.ref=n.innerType,"input"===this.io&&(t._prefault=JSON.parse(JSON.stringify(n.defaultValue)));break;case"catch":{let e;this.process(n.innerType,r),a.ref=n.innerType;try{e=n.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}t.default=e;break}case"nan":if("throw"===this.unrepresentable)throw new Error("NaN cannot be represented in JSON Schema");break;case"template_literal":{const r=t,n=e._zod.pattern;if(!n)throw new Error("Pattern not found in template literal");r.type="string",r.pattern=n.source;break}case"pipe":{const e="input"===this.io?"transform"===n.in._zod.def.type?n.out:n.in:n.out;this.process(e,r),a.ref=e;break}case"readonly":this.process(n.innerType,r),a.ref=n.innerType,t.readOnly=!0;break;case"lazy":{const t=e._zod.innerType;this.process(t,r),a.ref=t;break}case"custom":if("throw"===this.unrepresentable)throw new Error("Custom types cannot be represented in JSON Schema")}}}const c=this.metadataRegistry.get(e);return c&&Object.assign(a.schema,c),"input"===this.io&&Xu(e)&&(delete a.schema.examples,delete a.schema.default),"input"===this.io&&a.schema._prefault&&((r=a.schema).default??(r.default=a.schema._prefault)),delete a.schema._prefault,this.seen.get(e).schema}emit(e,t){const r={cycles:t?.cycles??"ref",reused:t?.reused??"inline",external:t?.external??void 0},n=this.seen.get(e);if(!n)throw new Error("Unprocessed schema. This is a bug in Zod.");const s=e=>{const t="draft-2020-12"===this.target?"$defs":"definitions";if(r.external){const n=r.external.registry.get(e[0])?.id,s=r.external.uri??(e=>e);if(n)return{ref:s(n)};const i=e[1].defId??e[1].schema.id??"schema"+this.counter++;return e[1].defId=i,{defId:i,ref:`${s("__shared")}#/${t}/${i}`}}if(e[1]===n)return{ref:"#"};const s=`#/${t}/`,i=e[1].schema.id??"__schema"+this.counter++;return{defId:i,ref:s+i}},i=e=>{if(e[1].schema.$ref)return;const t=e[1],{ref:r,defId:n}=s(e);t.def={...t.schema},n&&(t.defId=n);const i=t.schema;for(const e in i)delete i[e];i.$ref=r};if("throw"===r.cycles)for(const e of this.seen.entries()){const t=e[1];if(t.cycle)throw new Error(`Cycle detected: #/${t.cycle?.join("/")}/<root>\n\nSet the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(const t of this.seen.entries()){const n=t[1];if(e===t[0]){i(t);continue}if(r.external){const n=r.external.registry.get(t[0])?.id;if(e!==t[0]&&n){i(t);continue}}const s=this.metadataRegistry.get(t[0])?.id;(s||n.cycle||n.count>1&&"ref"===r.reused)&&i(t)}const a=(e,t)=>{const r=this.seen.get(e),n=r.def??r.schema,s={...n};if(null===r.ref)return;const i=r.ref;if(r.ref=null,i){a(i,t);const e=this.seen.get(i).schema;e.$ref&&"draft-7"===t.target?(n.allOf=n.allOf??[],n.allOf.push(e)):(Object.assign(n,e),Object.assign(n,s))}r.isParent||this.override({zodSchema:e,jsonSchema:n,path:r.path??[]})};for(const e of[...this.seen.entries()].reverse())a(e[0],{target:this.target});const o={};if("draft-2020-12"===this.target?o.$schema="https://json-schema.org/draft/2020-12/schema":"draft-7"===this.target?o.$schema="http://json-schema.org/draft-07/schema#":console.warn(`Invalid target: ${this.target}`),r.external?.uri){const t=r.external.registry.get(e)?.id;if(!t)throw new Error("Schema is missing an `id` property");o.$id=r.external.uri(t)}Object.assign(o,n.def);const c=r.external?.defs??{};for(const e of this.seen.entries()){const t=e[1];t.def&&t.defId&&(c[t.defId]=t.def)}r.external||Object.keys(c).length>0&&("draft-2020-12"===this.target?o.$defs=c:o.definitions=c);try{return JSON.parse(JSON.stringify(o))}catch(e){throw new Error("Error converting schema to JSON.")}}}function Xu(e,t){const r=t??{seen:new Set};if(r.seen.has(e))return!1;r.seen.add(e);const n=e._zod.def;switch(n.type){case"string":case"number":case"bigint":case"boolean":case"date":case"symbol":case"undefined":case"null":case"any":case"unknown":case"never":case"void":case"literal":case"enum":case"nan":case"file":case"template_literal":case"custom":case"success":case"catch":return!1;case"array":return Xu(n.element,r);case"object":for(const e in n.shape)if(Xu(n.shape[e],r))return!0;return!1;case"union":for(const e of n.options)if(Xu(e,r))return!0;return!1;case"intersection":return Xu(n.left,r)||Xu(n.right,r);case"tuple":for(const e of n.items)if(Xu(e,r))return!0;return!(!n.rest||!Xu(n.rest,r));case"record":case"map":return Xu(n.keyType,r)||Xu(n.valueType,r);case"set":return Xu(n.valueType,r);case"promise":case"optional":case"nonoptional":case"nullable":case"readonly":case"default":case"prefault":return Xu(n.innerType,r);case"lazy":return Xu(n.getter(),r);case"transform":return!0;case"pipe":return Xu(n.in,r)||Xu(n.out,r)}throw new Error(`Unknown schema type: ${n.type}`)}const eh=Symbol("Let zodToJsonSchema decide on which parser to use"),th={name:void 0,$refStrategy:"root",basePath:["#"],effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",removeAdditionalStrategy:"passthrough",allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:"definitions",target:"jsonSchema7",strictUnions:!1,definitions:{},errorMessages:!1,markdownDescription:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref",openAiAnyTypeName:"OpenAiAnyType"},rh=(e,t)=>{let r=0;for(;r<e.length&&r<t.length&&e[r]===t[r];r++);return[(e.length-r).toString(),...t.slice(r)].join("/")};function nh(e){if("openAi"!==e.target)return{};const t=[...e.basePath,e.definitionPath,e.openAiAnyTypeName];return e.flags.hasReferencedOpenAiAnyType=!0,{$ref:"relative"===e.$refStrategy?rh(t,e.currentPath):t.join("/")}}function sh(e,t,r,n){n?.errorMessages&&r&&(e.errorMessage={...e.errorMessage,[t]:r})}function ih(e,t,r,n,s){e[t]=r,sh(e,t,n,s)}function ah(e,t){return Ah(e.type._def,t)}function oh(e,t,r){const n=r??t.dateStrategy;if(Array.isArray(n))return{anyOf:n.map((r,n)=>oh(e,t,r))};switch(n){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return ch(e,t)}}const ch=(e,t)=>{const r={type:"integer",format:"unix-time"};if("openApi3"===t.target)return r;for(const n of e.checks)switch(n.kind){case"min":ih(r,"minimum",n.value,n.message,t);break;case"max":ih(r,"maximum",n.value,n.message,t)}return r};let dh;const lh=/^[cC][^\s-]{8,}$/,uh=/^[0-9a-z]+$/,hh=/^[0-9A-HJKMNP-TV-Z]{26}$/,ph=/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,mh=()=>(void 0===dh&&(dh=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),dh),fh=/^(?:(?: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])$/,gh=/^(([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])$/,_h=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,yh=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,wh=/^[a-zA-Z0-9_-]{21}$/,vh=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/;function bh(e,t){const r={type:"string"};if(e.checks)for(const n of e.checks)switch(n.kind){case"min":ih(r,"minLength","number"==typeof r.minLength?Math.max(r.minLength,n.value):n.value,n.message,t);break;case"max":ih(r,"maxLength","number"==typeof r.maxLength?Math.min(r.maxLength,n.value):n.value,n.message,t);break;case"email":switch(t.emailStrategy){case"format:email":$h(r,"email",n.message,t);break;case"format:idn-email":$h(r,"idn-email",n.message,t);break;case"pattern:zod":Eh(r,ph,n.message,t)}break;case"url":$h(r,"uri",n.message,t);break;case"uuid":$h(r,"uuid",n.message,t);break;case"regex":Eh(r,n.regex,n.message,t);break;case"cuid":Eh(r,lh,n.message,t);break;case"cuid2":Eh(r,uh,n.message,t);break;case"startsWith":Eh(r,RegExp(`^${kh(n.value,t)}`),n.message,t);break;case"endsWith":Eh(r,RegExp(`${kh(n.value,t)}$`),n.message,t);break;case"datetime":$h(r,"date-time",n.message,t);break;case"date":$h(r,"date",n.message,t);break;case"time":$h(r,"time",n.message,t);break;case"duration":$h(r,"duration",n.message,t);break;case"length":ih(r,"minLength","number"==typeof r.minLength?Math.max(r.minLength,n.value):n.value,n.message,t),ih(r,"maxLength","number"==typeof r.maxLength?Math.min(r.maxLength,n.value):n.value,n.message,t);break;case"includes":Eh(r,RegExp(kh(n.value,t)),n.message,t);break;case"ip":"v6"!==n.version&&$h(r,"ipv4",n.message,t),"v4"!==n.version&&$h(r,"ipv6",n.message,t);break;case"base64url":Eh(r,yh,n.message,t);break;case"jwt":Eh(r,vh,n.message,t);break;case"cidr":"v6"!==n.version&&Eh(r,fh,n.message,t),"v4"!==n.version&&Eh(r,gh,n.message,t);break;case"emoji":Eh(r,mh(),n.message,t);break;case"ulid":Eh(r,hh,n.message,t);break;case"base64":switch(t.base64Strategy){case"format:binary":$h(r,"binary",n.message,t);break;case"contentEncoding:base64":ih(r,"contentEncoding","base64",n.message,t);break;case"pattern:zod":Eh(r,_h,n.message,t)}break;case"nanoid":Eh(r,wh,n.message,t);case"toLowerCase":case"toUpperCase":case"trim":break;default:(()=>{})()}return r}function kh(e,t){return"escape"===t.patternStrategy?function(e){let t="";for(let r=0;r<e.length;r++)Sh.has(e[r])||(t+="\\"),t+=e[r];return t}(e):e}const Sh=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function $h(e,t,r,n){e.format||e.anyOf?.some(e=>e.format)?(e.anyOf||(e.anyOf=[]),e.format&&(e.anyOf.push({format:e.format,...e.errorMessage&&n.errorMessages&&{errorMessage:{format:e.errorMessage.format}}}),delete e.format,e.errorMessage&&(delete e.errorMessage.format,0===Object.keys(e.errorMessage).length&&delete e.errorMessage)),e.anyOf.push({format:t,...r&&n.errorMessages&&{errorMessage:{format:r}}})):ih(e,"format",t,r,n)}function Eh(e,t,r,n){e.pattern||e.allOf?.some(e=>e.pattern)?(e.allOf||(e.allOf=[]),e.pattern&&(e.allOf.push({pattern:e.pattern,...e.errorMessage&&n.errorMessages&&{errorMessage:{pattern:e.errorMessage.pattern}}}),delete e.pattern,e.errorMessage&&(delete e.errorMessage.pattern,0===Object.keys(e.errorMessage).length&&delete e.errorMessage)),e.allOf.push({pattern:Th(t,n),...r&&n.errorMessages&&{errorMessage:{pattern:r}}})):ih(e,"pattern",Th(t,n),r,n)}function Th(e,t){if(!t.applyRegexFlags||!e.flags)return e.source;const r=e.flags.includes("i"),n=e.flags.includes("m"),s=e.flags.includes("s"),i=r?e.source.toLowerCase():e.source;let a="",o=!1,c=!1,d=!1;for(let e=0;e<i.length;e++)if(o)a+=i[e],o=!1;else{if(r)if(c){if(i[e].match(/[a-z]/)){d?(a+=i[e],a+=`${i[e-2]}-${i[e]}`.toUpperCase(),d=!1):"-"===i[e+1]&&i[e+2]?.match(/[a-z]/)?(a+=i[e],d=!0):a+=`${i[e]}${i[e].toUpperCase()}`;continue}}else if(i[e].match(/[a-z]/)){a+=`[${i[e]}${i[e].toUpperCase()}]`;continue}if(n){if("^"===i[e]){a+="(^|(?<=[\r\n]))";continue}if("$"===i[e]){a+="($|(?=[\r\n]))";continue}}s&&"."===i[e]?a+=c?`${i[e]}\r\n`:`[${i[e]}\r\n]`:(a+=i[e],"\\"===i[e]?o=!0:c&&"]"===i[e]?c=!1:c||"["!==i[e]||(c=!0))}try{new RegExp(a)}catch{return console.warn(`Could not convert regex pattern at ${t.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),e.source}return a}function Ih(e,t){if("openAi"===t.target&&console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead."),"openApi3"===t.target&&e.keyType?._def.typeName===Au.ZodEnum)return{type:"object",required:e.keyType._def.values,properties:e.keyType._def.values.reduce((r,n)=>({...r,[n]:Ah(e.valueType._def,{...t,currentPath:[...t.currentPath,"properties",n]})??nh(t)}),{}),additionalProperties:t.rejectedAdditionalProperties};const r={type:"object",additionalProperties:Ah(e.valueType._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]})??t.allowedAdditionalProperties};if("openApi3"===t.target)return r;if(e.keyType?._def.typeName===Au.ZodString&&e.keyType._def.checks?.length){const{type:n,...s}=bh(e.keyType._def,t);return{...r,propertyNames:s}}if(e.keyType?._def.typeName===Au.ZodEnum)return{...r,propertyNames:{enum:e.keyType._def.values}};if(e.keyType?._def.typeName===Au.ZodBranded&&e.keyType._def.type._def.typeName===Au.ZodString&&e.keyType._def.type._def.checks?.length){const{type:n,...s}=ah(e.keyType._def,t);return{...r,propertyNames:s}}return r}const xh={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"},Ph=(e,t)=>{const r=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((e,r)=>Ah(e._def,{...t,currentPath:[...t.currentPath,"anyOf",`${r}`]})).filter(e=>!!e&&(!t.strictUnions||"object"==typeof e&&Object.keys(e).length>0));return r.length?{anyOf:r}:void 0};function Ch(e){try{return e.isOptional()}catch{return!0}}const Rh=(e,t,r)=>{switch(t){case Au.ZodString:return bh(e,r);case Au.ZodNumber:return function(e,t){const r={type:"number"};if(!e.checks)return r;for(const n of e.checks)switch(n.kind){case"int":r.type="integer",sh(r,"type",n.message,t);break;case"min":"jsonSchema7"===t.target?n.inclusive?ih(r,"minimum",n.value,n.message,t):ih(r,"exclusiveMinimum",n.value,n.message,t):(n.inclusive||(r.exclusiveMinimum=!0),ih(r,"minimum",n.value,n.message,t));break;case"max":"jsonSchema7"===t.target?n.inclusive?ih(r,"maximum",n.value,n.message,t):ih(r,"exclusiveMaximum",n.value,n.message,t):(n.inclusive||(r.exclusiveMaximum=!0),ih(r,"maximum",n.value,n.message,t));break;case"multipleOf":ih(r,"multipleOf",n.value,n.message,t)}return r}(e,r);case Au.ZodObject:return function(e,t){const r="openAi"===t.target,n={type:"object",properties:{}},s=[],i=e.shape();for(const e in i){let a=i[e];if(void 0===a||void 0===a._def)continue;let o=Ch(a);o&&r&&("ZodOptional"===a._def.typeName&&(a=a._def.innerType),a.isNullable()||(a=a.nullable()),o=!1);const c=Ah(a._def,{...t,currentPath:[...t.currentPath,"properties",e],propertyPath:[...t.currentPath,"properties",e]});void 0!==c&&(n.properties[e]=c,o||s.push(e))}s.length&&(n.required=s);const a=function(e,t){if("ZodNever"!==e.catchall._def.typeName)return Ah(e.catchall._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]});switch(e.unknownKeys){case"passthrough":return t.allowedAdditionalProperties;case"strict":return t.rejectedAdditionalProperties;case"strip":return"strict"===t.removeAdditionalStrategy?t.allowedAdditionalProperties:t.rejectedAdditionalProperties}}(e,t);return void 0!==a&&(n.additionalProperties=a),n}(e,r);case Au.ZodBigInt:return function(e,t){const r={type:"integer",format:"int64"};if(!e.checks)return r;for(const n of e.checks)switch(n.kind){case"min":"jsonSchema7"===t.target?n.inclusive?ih(r,"minimum",n.value,n.message,t):ih(r,"exclusiveMinimum",n.value,n.message,t):(n.inclusive||(r.exclusiveMinimum=!0),ih(r,"minimum",n.value,n.message,t));break;case"max":"jsonSchema7"===t.target?n.inclusive?ih(r,"maximum",n.value,n.message,t):ih(r,"exclusiveMaximum",n.value,n.message,t):(n.inclusive||(r.exclusiveMaximum=!0),ih(r,"maximum",n.value,n.message,t));break;case"multipleOf":ih(r,"multipleOf",n.value,n.message,t)}return r}(e,r);case Au.ZodBoolean:return{type:"boolean"};case Au.ZodDate:return oh(e,r);case Au.ZodUndefined:return function(e){return{not:nh(e)}}(r);case Au.ZodNull:return function(e){return"openApi3"===e.target?{enum:["null"],nullable:!0}:{type:"null"}}(r);case Au.ZodArray:return function(e,t){const r={type:"array"};return e.type?._def&&e.type?._def?.typeName!==Au.ZodAny&&(r.items=Ah(e.type._def,{...t,currentPath:[...t.currentPath,"items"]})),e.minLength&&ih(r,"minItems",e.minLength.value,e.minLength.message,t),e.maxLength&&ih(r,"maxItems",e.maxLength.value,e.maxLength.message,t),e.exactLength&&(ih(r,"minItems",e.exactLength.value,e.exactLength.message,t),ih(r,"maxItems",e.exactLength.value,e.exactLength.message,t)),r}(e,r);case Au.ZodUnion:case Au.ZodDiscriminatedUnion:return function(e,t){if("openApi3"===t.target)return Ph(e,t);const r=e.options instanceof Map?Array.from(e.options.values()):e.options;if(r.every(e=>e._def.typeName in xh&&(!e._def.checks||!e._def.checks.length))){const e=r.reduce((e,t)=>{const r=xh[t._def.typeName];return r&&!e.includes(r)?[...e,r]:e},[]);return{type:e.length>1?e:e[0]}}if(r.every(e=>"ZodLiteral"===e._def.typeName&&!e.description)){const e=r.reduce((e,t)=>{const r=typeof t._def.value;switch(r){case"string":case"number":case"boolean":return[...e,r];case"bigint":return[...e,"integer"];case"object":if(null===t._def.value)return[...e,"null"];default:return e}},[]);if(e.length===r.length){const t=e.filter((e,t,r)=>r.indexOf(e)===t);return{type:t.length>1?t:t[0],enum:r.reduce((e,t)=>e.includes(t._def.value)?e:[...e,t._def.value],[])}}}else if(r.every(e=>"ZodEnum"===e._def.typeName))return{type:"string",enum:r.reduce((e,t)=>[...e,...t._def.values.filter(t=>!e.includes(t))],[])};return Ph(e,t)}(e,r);case Au.ZodIntersection:return function(e,t){const r=[Ah(e.left._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),Ah(e.right._def,{...t,currentPath:[...t.currentPath,"allOf","1"]})].filter(e=>!!e);let n="jsonSchema2019-09"===t.target?{unevaluatedProperties:!1}:void 0;const s=[];return r.forEach(e=>{if("type"in(t=e)&&"string"===t.type||!("allOf"in t)){let t=e;if("additionalProperties"in e&&!1===e.additionalProperties){const{additionalProperties:r,...n}=e;t=n}else n=void 0;s.push(t)}else s.push(...e.allOf),void 0===e.unevaluatedProperties&&(n=void 0);var t}),s.length?{allOf:s,...n}:void 0}(e,r);case Au.ZodTuple:return function(e,t){return e.rest?{type:"array",minItems:e.items.length,items:e.items.map((e,r)=>Ah(e._def,{...t,currentPath:[...t.currentPath,"items",`${r}`]})).reduce((e,t)=>void 0===t?e:[...e,t],[]),additionalItems:Ah(e.rest._def,{...t,currentPath:[...t.currentPath,"additionalItems"]})}:{type:"array",minItems:e.items.length,maxItems:e.items.length,items:e.items.map((e,r)=>Ah(e._def,{...t,currentPath:[...t.currentPath,"items",`${r}`]})).reduce((e,t)=>void 0===t?e:[...e,t],[])}}(e,r);case Au.ZodRecord:return Ih(e,r);case Au.ZodLiteral:return function(e,t){const r=typeof e.value;return"bigint"!==r&&"number"!==r&&"boolean"!==r&&"string"!==r?{type:Array.isArray(e.value)?"array":"object"}:"openApi3"===t.target?{type:"bigint"===r?"integer":r,enum:[e.value]}:{type:"bigint"===r?"integer":r,const:e.value}}(e,r);case Au.ZodEnum:return function(e){return{type:"string",enum:Array.from(e.values)}}(e);case Au.ZodNativeEnum:return function(e){const t=e.values,r=Object.keys(e.values).filter(e=>"number"!=typeof t[t[e]]).map(e=>t[e]),n=Array.from(new Set(r.map(e=>typeof e)));return{type:1===n.length?"string"===n[0]?"string":"number":["string","number"],enum:r}}(e);case Au.ZodNullable:return function(e,t){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(e.innerType._def.typeName)&&(!e.innerType._def.checks||!e.innerType._def.checks.length))return"openApi3"===t.target?{type:xh[e.innerType._def.typeName],nullable:!0}:{type:[xh[e.innerType._def.typeName],"null"]};if("openApi3"===t.target){const r=Ah(e.innerType._def,{...t,currentPath:[...t.currentPath]});return r&&"$ref"in r?{allOf:[r],nullable:!0}:r&&{...r,nullable:!0}}const r=Ah(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}(e,r);case Au.ZodOptional:return((e,t)=>{if(t.currentPath.toString()===t.propertyPath?.toString())return Ah(e.innerType._def,t);const r=Ah(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","1"]});return r?{anyOf:[{not:nh(t)},r]}:nh(t)})(e,r);case Au.ZodMap:return function(e,t){return"record"===t.mapStrategy?Ih(e,t):{type:"array",maxItems:125,items:{type:"array",items:[Ah(e.keyType._def,{...t,currentPath:[...t.currentPath,"items","items","0"]})||nh(t),Ah(e.valueType._def,{...t,currentPath:[...t.currentPath,"items","items","1"]})||nh(t)],minItems:2,maxItems:2}}}(e,r);case Au.ZodSet:return function(e,t){const r={type:"array",uniqueItems:!0,items:Ah(e.valueType._def,{...t,currentPath:[...t.currentPath,"items"]})};return e.minSize&&ih(r,"minItems",e.minSize.value,e.minSize.message,t),e.maxSize&&ih(r,"maxItems",e.maxSize.value,e.maxSize.message,t),r}(e,r);case Au.ZodLazy:return()=>e.getter()._def;case Au.ZodPromise:return function(e,t){return Ah(e.type._def,t)}(e,r);case Au.ZodNaN:case Au.ZodNever:return function(e){return"openAi"===e.target?void 0:{not:nh({...e,currentPath:[...e.currentPath,"not"]})}}(r);case Au.ZodEffects:return function(e,t){return"input"===t.effectStrategy?Ah(e.schema._def,t):nh(t)}(e,r);case Au.ZodAny:return nh(r);case Au.ZodUnknown:return function(e){return nh(e)}(r);case Au.ZodDefault:return function(e,t){return{...Ah(e.innerType._def,t),default:e.defaultValue()}}(e,r);case Au.ZodBranded:return ah(e,r);case Au.ZodReadonly:case Au.ZodCatch:return((e,t)=>Ah(e.innerType._def,t))(e,r);case Au.ZodPipeline:return((e,t)=>{if("input"===t.pipeStrategy)return Ah(e.in._def,t);if("output"===t.pipeStrategy)return Ah(e.out._def,t);const r=Ah(e.in._def,{...t,currentPath:[...t.currentPath,"allOf","0"]});return{allOf:[r,Ah(e.out._def,{...t,currentPath:[...t.currentPath,"allOf",r?"1":"0"]})].filter(e=>void 0!==e)}})(e,r);case Au.ZodFunction:case Au.ZodVoid:case Au.ZodSymbol:default:return}};function Ah(e,t,r=!1){const n=t.seen.get(e);if(t.override){const s=t.override?.(e,t,n,r);if(s!==eh)return s}if(n&&!r){const e=Oh(n,t);if(void 0!==e)return e}const s={def:e,path:t.currentPath,jsonSchema:void 0};t.seen.set(e,s);const i=Rh(e,e.typeName,t),a="function"==typeof i?Ah(i(),t):i;if(a&&Nh(e,t,a),t.postProcess){const r=t.postProcess(a,e,t);return s.jsonSchema=a,r}return s.jsonSchema=a,a}const Oh=(e,t)=>{switch(t.$refStrategy){case"root":return{$ref:e.path.join("/")};case"relative":return{$ref:rh(t.currentPath,e.path)};case"none":case"seen":return e.path.length<t.currentPath.length&&e.path.every((e,r)=>t.currentPath[r]===e)?(console.warn(`Recursive reference detected at ${t.currentPath.join("/")}! Defaulting to any`),nh(t)):"seen"===t.$refStrategy?nh(t):void 0}},Nh=(e,t,r)=>(e.description&&(r.description=e.description,t.markdownDescription&&(r.markdownDescription=e.description)),r);function zh(e){return e?"jsonSchema7"===e||"draft-7"===e?"draft-7":"jsonSchema2019-09"===e||"draft-2020-12"===e?"draft-2020-12":"draft-7":"draft-7"}function jh(e,t){return Fu(e)?function(e,t){if(e instanceof Zt){const r=new Yu(t),n={};for(const t of e._idmap.entries()){const[e,n]=t;r.process(n)}const s={},i={registry:e,uri:t?.uri,defs:n};for(const n of e._idmap.entries()){const[e,a]=n;s[e]=r.emit(a,{...t,external:i})}if(Object.keys(n).length>0){const e="draft-2020-12"===r.target?"$defs":"definitions";s.__shared={[e]:n}}return{schemas:s}}const r=new Yu(t);return r.process(e),r.emit(e,t)}(e,{target:zh(t?.target),io:t?.pipeStrategy??"input"}):((e,t)=>{const r=(e=>{const t=(e=>"string"==typeof e?{...th,name:e}:{...th,...e})(e),r=void 0!==t.name?[...t.basePath,t.definitionPath,t.name]:t.basePath;return{...t,flags:{hasReferencedOpenAiAnyType:!1},currentPath:r,propertyPath:void 0,seen:new Map(Object.entries(t.definitions).map(([e,r])=>[r._def,{def:r._def,path:[...t.basePath,t.definitionPath,e],jsonSchema:void 0}]))}})(t);let n=t.definitions?Object.entries(t.definitions).reduce((e,[t,n])=>({...e,[t]:Ah(n._def,{...r,currentPath:[...r.basePath,r.definitionPath,t]},!0)??nh(r)}),{}):void 0;const s="title"===t?.nameStrategy?void 0:t?.name,i=Ah(e._def,void 0===s?r:{...r,currentPath:[...r.basePath,r.definitionPath,s]},!1)??nh(r),a=void 0!==t.name&&"title"===t.nameStrategy?t.name:void 0;void 0!==a&&(i.title=a),r.flags.hasReferencedOpenAiAnyType&&(n||(n={}),n[r.openAiAnyTypeName]||(n[r.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:"relative"===r.$refStrategy?"1":[...r.basePath,r.definitionPath,r.openAiAnyTypeName].join("/")}}));const o=void 0===s?n?{...i,[r.definitionPath]:n}:i:{$ref:[..."relative"===r.$refStrategy?[]:r.basePath,r.definitionPath,s].join("/"),[r.definitionPath]:{...n,[s]:i}};return"jsonSchema7"===r.target?o.$schema="http://json-schema.org/draft-07/schema#":"jsonSchema2019-09"!==r.target&&"openAi"!==r.target||(o.$schema="https://json-schema.org/draft/2019-09/schema#"),"openAi"===r.target&&("anyOf"in o||"oneOf"in o||"allOf"in o||"type"in o&&Array.isArray(o.type))&&console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property."),o})(e,{strictUnions:t?.strictUnions??!0,pipeStrategy:t?.pipeStrategy??"input"})}function Uh(e){const t=Gu(e),r=t?.method;if(!r)throw new Error("Schema is missing a method literal");const n=Ju(r);if("string"!=typeof n)throw new Error("Schema method literal must be a string");return n}function qh(e,t){const r=Vu(e,t);if(!r.success)throw r.error;return r.data}class Dh{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._taskProgressTokens=new Map,this._requestResolvers=new Map,this.setNotificationHandler(Qn,e=>{this._oncancel(e)}),this.setNotificationHandler(fs,e=>{this._onprogress(e)}),this.setRequestHandler(hs,e=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler($s,async(e,t)=>{const r=await this._taskStore.getTask(e.params.taskId,t.sessionId);if(!r)throw new ua(Kn.InvalidParams,"Failed to retrieve task: Task not found");return{...r}}),this.setRequestHandler(Ts,async(e,t)=>{const r=async()=>{const n=e.params.taskId;if(!await this._taskStore.getTask(n,t.sessionId))throw new ua(Kn.InvalidParams,`Task not found: ${n}`);if(this._taskMessageQueue){let e;for(;e=await this._taskMessageQueue.dequeue(n,t.sessionId);){if("response"===e.type||"error"===e.type){const t=e.message,r=t.id,n=this._requestResolvers.get(r);if(n)if(this._requestResolvers.delete(r),"response"===e.type)n(t);else{const e=t;n(new ua(e.error.code,e.error.message,e.error.data))}else{const t="response"===e.type?"Response":"Error";this._onerror(new Error(`${t} handler missing for request ${r}`))}continue}await(this._transport?.send(e.message,{relatedRequestId:t.requestId}))}}const s=await this._taskStore.getTask(n,t.sessionId);if(!s)throw new ua(Kn.InvalidParams,`Task not found: ${n}`);if(!Qu(s.status))return await this._waitForTaskUpdate(n,t.signal,t.sessionId),await r();if(Qu(s.status)){const e=await this._taskStore.getTaskResult(n,t.sessionId);return this._clearTaskQueue(n,t.sessionId),{...e,_meta:{...e._meta,[Tn]:{taskId:n}}}}return await r()};return await r()}),this.setRequestHandler(Is,async(e,t)=>{try{const{tasks:r,nextCursor:n}=await this._taskStore.listTasks(e.params?.cursor,t.sessionId);return{tasks:r,nextCursor:n,_meta:{}}}catch(e){throw new ua(Kn.InvalidParams,`Failed to list tasks: ${e instanceof Error?e.message:String(e)}`)}}),this.setRequestHandler(Ps,async(e,t)=>{try{const r=await this._taskStore.getTask(e.params.taskId,t.sessionId);if(!r)throw new ua(Kn.InvalidParams,`Task not found: ${e.params.taskId}`);if(Qu(r.status))throw new ua(Kn.InvalidParams,`Cannot cancel task in terminal status: ${r.status}`);await this._taskStore.updateTaskStatus(e.params.taskId,"cancelled","Client cancelled task execution.",t.sessionId),this._clearTaskQueue(e.params.taskId,t.sessionId);const n=await this._taskStore.getTask(e.params.taskId,t.sessionId);if(!n)throw new ua(Kn.InvalidParams,`Task not found after cancellation: ${e.params.taskId}`);return{_meta:{},...n}}catch(e){if(e instanceof ua)throw e;throw new ua(Kn.InvalidRequest,`Failed to cancel task: ${e instanceof Error?e.message:String(e)}`)}}))}async _oncancel(e){if(!e.params.requestId)return;const t=this._requestHandlerAbortControllers.get(e.params.requestId);t?.abort(e.params.reason)}_setupTimeout(e,t,r,n,s=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(n,t),startTime:Date.now(),timeout:t,maxTotalTimeout:r,resetTimeoutOnProgress:s,onTimeout:n})}_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),ua.fromError(Kn.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){if(this._transport)throw new Error("Already connected to a transport. Call close() before connecting to a new transport, or use a separate Protocol instance per connection.");this._transport=e;const t=this.transport?.onclose;this._transport.onclose=()=>{t?.(),this._onclose()};const r=this.transport?.onerror;this._transport.onerror=e=>{r?.(e),this._onerror(e)};const n=this._transport?.onmessage;this._transport.onmessage=(e,t)=>{var r;n?.(e,t),Vn(e)||(e=>Gn.safeParse(e).success)(e)?this._onresponse(e):Zn(e)?this._onrequest(e,t):(r=e,Fn.safeParse(r).success?this._onnotification(e):this._onerror(new Error(`Unknown message type: ${JSON.stringify(e)}`)))},await this._transport.start()}_onclose(){const e=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();for(const e of this._timeoutInfo.values())clearTimeout(e.timeoutId);this._timeoutInfo.clear();for(const e of this._requestHandlerAbortControllers.values())e.abort();this._requestHandlerAbortControllers.clear();const t=ua.fromError(Kn.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(const r of e.values())r(t)}_onerror(e){this.onerror?.(e)}_onnotification(e){const t=this._notificationHandlers.get(e.method)??this.fallbackNotificationHandler;void 0!==t&&Promise.resolve().then(()=>t(e)).catch(e=>this._onerror(new Error(`Uncaught error in notification handler: ${e}`)))}_onrequest(e,t){const r=this._requestHandlers.get(e.method)??this.fallbackRequestHandler,n=this._transport,s=e.params?._meta?.[Tn]?.taskId,i=n?.sessionId,a=this._taskStore;let o,c=!0;if(s&&a&&this._taskMessageQueue&&void 0!==i&&(c=!1,o=(async()=>{if(!await a.getTask(s,i))throw new ua(Kn.InvalidParams,`Task not found: ${s}`);c=!0})()),void 0===r){const t={jsonrpc:"2.0",id:e.id,error:{code:Kn.MethodNotFound,message:"Method not found"}};if(s&&o){const e={type:"error",message:t,timestamp:Date.now()};o.then(()=>this._enqueueTaskMessage(s,e,i),()=>n?.send(t)).catch(e=>this._onerror(new Error(`Failed to send an error response: ${e}`)))}else s&&this._taskMessageQueue?this._enqueueTaskMessage(s,{type:"error",message:t,timestamp:Date.now()},n?.sessionId).catch(e=>this._onerror(new Error(`Failed to enqueue error response: ${e}`))):n?.send(t).catch(e=>this._onerror(new Error(`Failed to send an error response: ${e}`)));return}const d=new AbortController;this._requestHandlerAbortControllers.set(e.id,d);const l=(u=e.params,zn.safeParse(u).success?e.params.task:void 0);var u;const h=this._taskStore?this.requestTaskStore(e,n?.sessionId):void 0,p={signal:d.signal,sessionId:n?.sessionId,_meta:e.params?._meta,sendNotification:async t=>{if(d.signal.aborted)return;const r={relatedRequestId:e.id};s&&(r.relatedTask={taskId:s}),await this.notification(t,r)},sendRequest:async(t,r,n)=>{if(d.signal.aborted)throw new ua(Kn.ConnectionClosed,"Request was cancelled");const i={...n,relatedRequestId:e.id};s&&!i.relatedTask&&(i.relatedTask={taskId:s});const a=i.relatedTask?.taskId??s;return a&&h&&await h.updateTaskStatus(a,"input_required"),await this.request(t,r,i)},authInfo:t?.authInfo,requestId:e.id,requestInfo:t?.requestInfo,taskId:s,taskStore:h,taskRequestedTtl:l?.ttl,closeSSEStream:t?.closeSSEStream,closeStandaloneSSEStream:t?.closeStandaloneSSEStream};(o??Promise.resolve()).then(()=>{if(o&&d.signal.aborted)throw new ua(Kn.ConnectionClosed,"Request was cancelled");l&&this.assertTaskHandlerCapability(e.method)}).then(()=>r(e,p)).then(async t=>{if(d.signal.aborted)return;const r={result:t,jsonrpc:"2.0",id:e.id};s&&this._taskMessageQueue?await this._enqueueTaskMessage(s,{type:"response",message:r,timestamp:Date.now()},n?.sessionId):await(n?.send(r))},async t=>{if(d.signal.aborted)return;const r={jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(t.code)?t.code:Kn.InternalError,message:t.message??"Internal error",...void 0!==t.data&&{data:t.data}}};s&&this._taskMessageQueue&&c?await this._enqueueTaskMessage(s,{type:"error",message:r,timestamp:Date.now()},n?.sessionId):await(n?.send(r))}).catch(e=>this._onerror(new Error(`Failed to send response: ${e}`))).finally(()=>{this._requestHandlerAbortControllers.get(e.id)===d&&this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){const{progressToken:t,...r}=e.params,n=Number(t),s=this._progressHandlers.get(n);if(!s)return void this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));const i=this._responseHandlers.get(n),a=this._timeoutInfo.get(n);if(a&&i&&a.resetTimeoutOnProgress)try{this._resetTimeout(n)}catch(e){return this._responseHandlers.delete(n),this._progressHandlers.delete(n),this._cleanupTimeout(n),void i(e)}s(r)}_onresponse(e){const t=Number(e.id),r=this._requestResolvers.get(t);if(r)return this._requestResolvers.delete(t),void(Vn(e)?r(e):r(new ua(e.error.code,e.error.message,e.error.data)));const n=this._responseHandlers.get(t);if(void 0===n)return void this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));this._responseHandlers.delete(t),this._cleanupTimeout(t);let s=!1;if(Vn(e)&&e.result&&"object"==typeof e.result){const r=e.result;if(r.task&&"object"==typeof r.task){const e=r.task;"string"==typeof e.taskId&&(s=!0,this._taskProgressTokens.set(e.taskId,t))}}s||this._progressHandlers.delete(t),Vn(e)?n(e):n(ua.fromError(e.error.code,e.error.message,e.error.data))}get transport(){return this._transport}async close(){await(this._transport?.close())}async*requestStream(e,t,r){const{task:n}=r??{};if(!n){try{const n=await this.request(e,t,r);yield{type:"result",result:n}}catch(e){yield{type:"error",error:e instanceof ua?e:new ua(Kn.InternalError,String(e))}}return}let s;try{const n=await this.request(e,bs,r);if(!n.task)throw new ua(Kn.InternalError,"Task creation did not return a task");for(s=n.task.taskId,yield{type:"taskCreated",task:n.task};;){const e=await this.getTask({taskId:s},r);if(yield{type:"taskStatus",task:e},Qu(e.status)){if("completed"===e.status){const e=await this.getTaskResult({taskId:s},t,r);yield{type:"result",result:e}}else"failed"===e.status?yield{type:"error",error:new ua(Kn.InternalError,`Task ${s} failed`)}:"cancelled"===e.status&&(yield{type:"error",error:new ua(Kn.InternalError,`Task ${s} was cancelled`)});return}if("input_required"===e.status){const e=await this.getTaskResult({taskId:s},t,r);return void(yield{type:"result",result:e})}const n=e.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(e=>setTimeout(e,n)),r?.signal?.throwIfAborted()}}catch(e){yield{type:"error",error:e instanceof ua?e:new ua(Kn.InternalError,String(e))}}}request(e,t,r){const{relatedRequestId:n,resumptionToken:s,onresumptiontoken:i,task:a,relatedTask:o}=r??{};return new Promise((c,d)=>{const l=e=>{d(e)};if(!this._transport)return void l(new Error("Not connected"));if(!0===this._options?.enforceStrictCapabilities)try{this.assertCapabilityForMethod(e.method),a&&this.assertTaskCapability(e.method)}catch(e){return void l(e)}r?.signal?.throwIfAborted();const u=this._requestMessageId++,h={...e,jsonrpc:"2.0",id:u};r?.onprogress&&(this._progressHandlers.set(u,r.onprogress),h.params={...e.params,_meta:{...e.params?._meta||{},progressToken:u}}),a&&(h.params={...h.params,task:a}),o&&(h.params={...h.params,_meta:{...h.params?._meta||{},[Tn]:o}});const p=e=>{this._responseHandlers.delete(u),this._progressHandlers.delete(u),this._cleanupTimeout(u),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:u,reason:String(e)}},{relatedRequestId:n,resumptionToken:s,onresumptiontoken:i}).catch(e=>this._onerror(new Error(`Failed to send cancellation: ${e}`)));const t=e instanceof ua?e:new ua(Kn.RequestTimeout,String(e));d(t)};this._responseHandlers.set(u,e=>{if(!r?.signal?.aborted){if(e instanceof Error)return d(e);try{const r=Vu(t,e.result);r.success?c(r.data):d(r.error)}catch(e){d(e)}}}),r?.signal?.addEventListener("abort",()=>{p(r?.signal?.reason)});const m=r?.timeout??6e4;this._setupTimeout(u,m,r?.maxTotalTimeout,()=>p(ua.fromError(Kn.RequestTimeout,"Request timed out",{timeout:m})),r?.resetTimeoutOnProgress??!1);const f=o?.taskId;if(f){const e=e=>{const t=this._responseHandlers.get(u);t?t(e):this._onerror(new Error(`Response handler missing for side-channeled request ${u}`))};this._requestResolvers.set(u,e),this._enqueueTaskMessage(f,{type:"request",message:h,timestamp:Date.now()}).catch(e=>{this._cleanupTimeout(u),d(e)})}else this._transport.send(h,{relatedRequestId:n,resumptionToken:s,onresumptiontoken:i}).catch(e=>{this._cleanupTimeout(u),d(e)})})}async getTask(e,t){return this.request({method:"tasks/get",params:e},Es,t)}async getTaskResult(e,t,r){return this.request({method:"tasks/result",params:e},t,r)}async listTasks(e,t){return this.request({method:"tasks/list",params:e},xs,t)}async cancelTask(e,t){return this.request({method:"tasks/cancel",params:e},Cs,t)}async notification(e,t){if(!this._transport)throw new Error("Not connected");this.assertNotificationCapability(e.method);const r=t?.relatedTask?.taskId;if(r){const n={...e,jsonrpc:"2.0",params:{...e.params,_meta:{...e.params?._meta||{},[Tn]:t.relatedTask}}};return void await this._enqueueTaskMessage(r,{type:"notification",message:n,timestamp:Date.now()})}if((this._options?.debouncedNotificationMethods??[]).includes(e.method)&&!e.params&&!t?.relatedRequestId&&!t?.relatedTask){if(this._pendingDebouncedNotifications.has(e.method))return;return this._pendingDebouncedNotifications.add(e.method),void Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(e.method),!this._transport)return;let r={...e,jsonrpc:"2.0"};t?.relatedTask&&(r={...r,params:{...r.params,_meta:{...r.params?._meta||{},[Tn]:t.relatedTask}}}),this._transport?.send(r,t).catch(e=>this._onerror(e))})}let n={...e,jsonrpc:"2.0"};t?.relatedTask&&(n={...n,params:{...n.params,_meta:{...n.params?._meta||{},[Tn]:t.relatedTask}}}),await this._transport.send(n,t)}setRequestHandler(e,t){const r=Uh(e);this.assertRequestHandlerCapability(r),this._requestHandlers.set(r,(r,n)=>{const s=qh(e,r);return Promise.resolve(t(s,n))})}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){const r=Uh(e);this._notificationHandlers.set(r,r=>{const n=qh(e,r);return Promise.resolve(t(n))})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}_cleanupTaskProgressHandler(e){const t=this._taskProgressTokens.get(e);void 0!==t&&(this._progressHandlers.delete(t),this._taskProgressTokens.delete(e))}async _enqueueTaskMessage(e,t,r){if(!this._taskStore||!this._taskMessageQueue)throw new Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");const n=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(e,t,r??this._transport?.sessionId,n)}async _clearTaskQueue(e,t){if(this._taskMessageQueue){const r=await this._taskMessageQueue.dequeueAll(e,t);for(const t of r)if("request"===t.type&&Zn(t.message)){const r=t.message.id,n=this._requestResolvers.get(r);n?(n(new ua(Kn.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(r)):this._onerror(new Error(`Resolver missing for request ${r} during task ${e} cleanup`))}}}async _waitForTaskUpdate(e,t,r){let n=this._options?.defaultTaskPollInterval??1e3;try{const t=await(this._taskStore?.getTask(e,r));t?.pollInterval&&(n=t.pollInterval)}catch{}return new Promise((e,r)=>{if(t.aborted)return void r(new ua(Kn.InvalidRequest,"Request cancelled"));const s=setTimeout(e,n);t.addEventListener("abort",()=>{clearTimeout(s),r(new ua(Kn.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(e,t){const r=this._taskStore;if(!r)throw new Error("No task store configured");return{createTask:async n=>{if(!e)throw new Error("No request provided");return await r.createTask(n,e.id,{method:e.method,params:e.params},t)},getTask:async e=>{const n=await r.getTask(e,t);if(!n)throw new ua(Kn.InvalidParams,"Failed to retrieve task: Task not found");return n},storeTaskResult:async(e,n,s)=>{await r.storeTaskResult(e,n,s,t);const i=await r.getTask(e,t);if(i){const t=Ss.parse({method:"notifications/tasks/status",params:i});await this.notification(t),Qu(i.status)&&this._cleanupTaskProgressHandler(e)}},getTaskResult:e=>r.getTaskResult(e,t),updateTaskStatus:async(e,n,s)=>{const i=await r.getTask(e,t);if(!i)throw new ua(Kn.InvalidParams,`Task "${e}" not found - it may have been cleaned up`);if(Qu(i.status))throw new ua(Kn.InvalidParams,`Cannot update task "${e}" from terminal status "${i.status}" to "${n}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await r.updateTaskStatus(e,n,s,t);const a=await r.getTask(e,t);if(a){const t=Ss.parse({method:"notifications/tasks/status",params:a});await this.notification(t),Qu(a.status)&&this._cleanupTaskProgressHandler(e)}},listTasks:e=>r.listTasks(e,t)}}}function Mh(e){return null!==e&&"object"==typeof e&&!Array.isArray(e)}var Lh=r(3282),Zh=r(8182);class Fh{constructor(e){this._ajv=e??function(){const e=new Lh({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return Zh(e),e}()}getValidator(e){const t="$id"in e&&"string"==typeof e.$id?this._ajv.getSchema(e.$id)??this._ajv.compile(e):this._ajv.compile(e);return e=>t(e)?{valid:!0,data:e,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(t.errors)}}}class Hh{constructor(e){this._server=e}requestStream(e,t,r){return this._server.requestStream(e,t,r)}createMessageStream(e,t){const r=this._server.getClientCapabilities();if((e.tools||e.toolChoice)&&!r?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(e.messages.length>0){const t=e.messages[e.messages.length-1],r=Array.isArray(t.content)?t.content:[t.content],n=r.some(e=>"tool_result"===e.type),s=e.messages.length>1?e.messages[e.messages.length-2]:void 0,i=s?Array.isArray(s.content)?s.content:[s.content]:[],a=i.some(e=>"tool_use"===e.type);if(n){if(r.some(e=>"tool_result"!==e.type))throw new Error("The last message must contain only tool_result content if any is present");if(!a)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(a){const e=new Set(i.filter(e=>"tool_use"===e.type).map(e=>e.id)),t=new Set(r.filter(e=>"tool_result"===e.type).map(e=>e.toolUseId));if(e.size!==t.size||![...e].every(e=>t.has(e)))throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return this.requestStream({method:"sampling/createMessage",params:e},qi,t)}elicitInputStream(e,t){const r=this._server.getClientCapabilities(),n=e.mode??"form";switch(n){case"url":if(!r?.elicitation?.url)throw new Error("Client does not support url elicitation.");break;case"form":if(!r?.elicitation?.form)throw new Error("Client does not support form elicitation.")}const s="form"===n&&void 0===e.mode?{...e,mode:"form"}:e;return this.requestStream({method:"elicitation/create",params:s},ea,t)}async getTask(e,t){return this._server.getTask({taskId:e},t)}async getTaskResult(e,t,r){return this._server.getTaskResult({taskId:e},t,r)}async listTasks(e,t){return this._server.listTasks(e?{cursor:e}:void 0,t)}async cancelTask(e,t){return this._server.cancelTask({taskId:e},t)}}class Vh extends Dh{constructor(e,t){super(t),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map($i.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=t?.capabilities??{},this._instructions=t?.instructions,this._jsonSchemaValidator=t?.jsonSchemaValidator??new Fh,this.setRequestHandler(cs,e=>this._oninitialize(e)),this.setNotificationHandler(us,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(Ti,async(e,t)=>{const r=t.sessionId||t.requestInfo?.headers["mcp-session-id"]||void 0,{level:n}=e.params,s=$i.safeParse(n);return s.success&&this._loggingLevels.set(r,s.data),{}})}get experimental(){return this._experimental||(this._experimental={tasks:new Hh(this)}),this._experimental}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=function(e,t){const r={...e};for(const e in t){const n=e,s=t[n];if(void 0===s)continue;const i=r[n];Mh(i)&&Mh(s)?r[n]={...i,...s}:r[n]=s}return r}(this._capabilities,e)}setRequestHandler(e,t){const r=Gu(e),n=r?.method;if(!n)throw new Error("Schema is missing a method literal");const s=Ju(n);if("string"!=typeof s)throw new Error("Schema method literal must be a string");if("tools/call"===s){const r=async(e,r)=>{const n=Vu(ki,e);if(!n.success){const e=n.error instanceof Error?n.error.message:String(n.error);throw new ua(Kn.InvalidParams,`Invalid tools/call request: ${e}`)}const{params:s}=n.data,i=await Promise.resolve(t(e,r));if(s.task){const e=Vu(bs,i);if(!e.success){const t=e.error instanceof Error?e.error.message:String(e.error);throw new ua(Kn.InvalidParams,`Invalid task creation result: ${t}`)}return e.data}const a=Vu(vi,i);if(!a.success){const e=a.error instanceof Error?a.error.message:String(a.error);throw new ua(Kn.InvalidParams,`Invalid tools/call result: ${e}`)}return a.data};return super.setRequestHandler(e,r)}return super.setRequestHandler(e,t)}assertCapabilityForMethod(e){switch(e){case"sampling/createMessage":if(!this._clientCapabilities?.sampling)throw new Error(`Client does not support sampling (required for ${e})`);break;case"elicitation/create":if(!this._clientCapabilities?.elicitation)throw new Error(`Client does not support elicitation (required for ${e})`);break;case"roots/list":if(!this._clientCapabilities?.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})`);break;case"notifications/elicitation/complete":if(!this._clientCapabilities?.elicitation?.url)throw new Error(`Client does not support URL elicitation (required for ${e})`)}}assertRequestHandlerCapability(e){if(this._capabilities)switch(e){case"completion/complete":if(!this._capabilities.completions)throw new Error(`Server does not support completions (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})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw new Error(`Server does not support tasks capability (required for ${e})`)}}assertTaskCapability(e){!function(e,t,r){if(!e)throw new Error(`${r} does not support task creation (required for ${t})`);switch(t){case"sampling/createMessage":if(!e.sampling?.createMessage)throw new Error(`${r} does not support task creation for sampling/createMessage (required for ${t})`);break;case"elicitation/create":if(!e.elicitation?.create)throw new Error(`${r} does not support task creation for elicitation/create (required for ${t})`)}}(this._clientCapabilities?.tasks?.requests,e,"Client")}assertTaskHandlerCapability(e){this._capabilities&&function(e,t,r){if(!e)throw new Error(`${r} does not support task creation (required for ${t})`);if("tools/call"===t&&!e.tools?.call)throw new Error(`${r} does not support task creation for tools/call (required for ${t})`)}(this._capabilities.tasks?.requests,e,"Server")}async _oninitialize(e){const t=e.params.protocolVersion;return this._clientCapabilities=e.params.capabilities,this._clientVersion=e.params.clientInfo,{protocolVersion:En.includes(t)?t:$n,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"},Bn)}async createMessage(e,t){if((e.tools||e.toolChoice)&&!this._clientCapabilities?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(e.messages.length>0){const t=e.messages[e.messages.length-1],r=Array.isArray(t.content)?t.content:[t.content],n=r.some(e=>"tool_result"===e.type),s=e.messages.length>1?e.messages[e.messages.length-2]:void 0,i=s?Array.isArray(s.content)?s.content:[s.content]:[],a=i.some(e=>"tool_use"===e.type);if(n){if(r.some(e=>"tool_result"!==e.type))throw new Error("The last message must contain only tool_result content if any is present");if(!a)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(a){const e=new Set(i.filter(e=>"tool_use"===e.type).map(e=>e.id)),t=new Set(r.filter(e=>"tool_result"===e.type).map(e=>e.toolUseId));if(e.size!==t.size||![...e].every(e=>t.has(e)))throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return e.tools?this.request({method:"sampling/createMessage",params:e},Di,t):this.request({method:"sampling/createMessage",params:e},qi,t)}async elicitInput(e,t){switch(e.mode??"form"){case"url":{if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support url elicitation.");const r=e;return this.request({method:"elicitation/create",params:r},ea,t)}case"form":{if(!this._clientCapabilities?.elicitation?.form)throw new Error("Client does not support form elicitation.");const r="form"===e.mode?e:{...e,mode:"form"},n=await this.request({method:"elicitation/create",params:r},ea,t);if("accept"===n.action&&n.content&&r.requestedSchema)try{const e=this._jsonSchemaValidator.getValidator(r.requestedSchema)(n.content);if(!e.valid)throw new ua(Kn.InvalidParams,`Elicitation response content does not match requested schema: ${e.errorMessage}`)}catch(e){if(e instanceof ua)throw e;throw new ua(Kn.InternalError,`Error validating elicitation response: ${e instanceof Error?e.message:String(e)}`)}return n}}}createElicitationCompletionNotifier(e,t){if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support URL elicitation (required for notifications/elicitation/complete)");return()=>this.notification({method:"notifications/elicitation/complete",params:{elicitationId:e}},t)}async listRoots(e,t){return this.request({method:"roots/list",params:e},da,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 Kh=Symbol.for("mcp.completable");function Gh(e){return!!e&&"object"==typeof e&&Kh in e}var Wh;!function(e){e.Completable="McpCompletable"}(Wh||(Wh={}));const Bh=/^[A-Za-z0-9._-]{1,128}$/;function Jh(e){const t=function(e){const t=[];if(0===e.length)return{isValid:!1,warnings:["Tool name cannot be empty"]};if(e.length>128)return{isValid:!1,warnings:[`Tool name exceeds maximum length of 128 characters (current: ${e.length})`]};if(e.includes(" ")&&t.push("Tool name contains spaces, which may cause parsing issues"),e.includes(",")&&t.push("Tool name contains commas, which may cause parsing issues"),(e.startsWith("-")||e.endsWith("-"))&&t.push("Tool name starts or ends with a dash, which may cause parsing issues in some contexts"),(e.startsWith(".")||e.endsWith("."))&&t.push("Tool name starts or ends with a dot, which may cause parsing issues in some contexts"),!Bh.test(e)){const r=e.split("").filter(e=>!/[A-Za-z0-9._-]/.test(e)).filter((e,t,r)=>r.indexOf(e)===t);return t.push(`Tool name contains invalid characters: ${r.map(e=>`"${e}"`).join(", ")}`,"Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)"),{isValid:!1,warnings:t}}return{isValid:!0,warnings:t}}(e);return function(e,t){if(t.length>0){console.warn(`Tool name validation warning for "${e}":`);for(const e of t)console.warn(` - ${e}`);console.warn("Tool registration will proceed, but this may cause compatibility issues."),console.warn("Consider updating the tool name to conform to the MCP tool naming standard."),console.warn("See SEP: Specify Format for Tool Names (https://github.com/modelcontextprotocol/modelcontextprotocol/issues/986) for more details.")}}(e,t.warnings),t.isValid}class Qh{constructor(e){this._mcpServer=e}registerToolTask(e,t,r){const n={taskSupport:"required",...t.execution};if("forbidden"===n.taskSupport)throw new Error(`Cannot register task-based tool '${e}' with taskSupport 'forbidden'. Use registerTool() instead.`);return this._mcpServer._createRegisteredTool(e,t.title,t.description,t.inputSchema,t.outputSchema,t.annotations,n,t._meta,r)}}class Yh{constructor(e,t){this._registeredResources={},this._registeredResourceTemplates={},this._registeredTools={},this._registeredPrompts={},this._toolHandlersInitialized=!1,this._completionHandlerInitialized=!1,this._resourceHandlersInitialized=!1,this._promptHandlersInitialized=!1,this.server=new Vh(e,t),this._maxToolInputElements=function(e){if(void 0!==e&&e!==1/0){if("number"!=typeof e||Number.isNaN(e)||e<1)throw new RangeError(`maxToolInputElements must be a number of at least 1, or Infinity, got ${String(e)}`);return e}}(t?.maxToolInputElements)}get experimental(){return this._experimental||(this._experimental={tasks:new Qh(this)}),this._experimental}async connect(e){return await this.server.connect(e)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||(this.server.assertCanSetRequestHandler(ip(yi)),this.server.assertCanSetRequestHandler(ip(ki)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(yi,()=>({tools:Object.entries(this._registeredTools).filter(([,e])=>e.enabled).map(([e,t])=>{const r={name:e,title:t.title,description:t.description,inputSchema:(()=>{const e=Wu(t.inputSchema);return e?jh(e,{strictUnions:!0,pipeStrategy:"input"}):Xh})(),annotations:t.annotations,execution:t.execution,_meta:t._meta};if(t.outputSchema){const e=Wu(t.outputSchema);e&&(r.outputSchema=jh(e,{strictUnions:!0,pipeStrategy:"output"}))}return r})})),this.server.setRequestHandler(ki,async(e,t)=>{try{const r=this._registeredTools[e.params.name];if(!r)throw new ua(Kn.InvalidParams,`Tool ${e.params.name} not found`);if(!r.enabled)throw new ua(Kn.InvalidParams,`Tool ${e.params.name} disabled`);const n=!!e.params.task,s=r.execution?.taskSupport,i="createTask"in r.handler;if(("required"===s||"optional"===s)&&!i)throw new ua(Kn.InternalError,`Tool ${e.params.name} has taskSupport '${s}' but was not registered with registerToolTask`);if("required"===s&&!n)throw new ua(Kn.MethodNotFound,`Tool ${e.params.name} requires task augmentation (taskSupport: 'required')`);if("optional"===s&&!n&&i)return await this.handleAutomaticTaskPolling(r,e,t);const a=await this.validateToolInput(r,e.params.arguments,e.params.name),o=await this.executeToolHandler(r,a,t);return n||await this.validateToolOutput(r,o,e.params.name),o}catch(e){if(e instanceof ua&&e.code===Kn.UrlElicitationRequired)throw e;return this.createToolError(e instanceof Error?e.message:String(e))}}),this._toolHandlersInitialized=!0)}createToolError(e){return{content:[{type:"text",text:e}],isError:!0}}async validateToolInput(e,t,r){if(void 0!==this._maxToolInputElements&&function(e,t){let r=0;const n=[e];for(;n.length>0;){const e=n.pop();if(null!==e&&"object"==typeof e)if(Array.isArray(e))for(const s of e){if(++r>t)return r;null!==s&&"object"==typeof s&&n.push(s)}else for(const s in e){if(!Object.prototype.hasOwnProperty.call(e,s))continue;if(++r>t)return r;const i=e[s];null!==i&&"object"==typeof i&&n.push(i)}}return r}(t,this._maxToolInputElements)>this._maxToolInputElements)throw new ua(Kn.InvalidParams,`Invalid arguments for tool ${r}: arguments contain more than the maximum of ${this._maxToolInputElements} elements`);if(!e.inputSchema)return;const n=Wu(e.inputSchema)??e.inputSchema,s=await Ku(n,t??{});if(!s.success){const e=Bu("error"in s?s.error:"Unknown error");throw new ua(Kn.InvalidParams,`Input validation error: Invalid arguments for tool ${r}: ${e}`)}return s.data}async validateToolOutput(e,t,r){if(!e.outputSchema)return;if(!("content"in t))return;if(t.isError)return;if(!t.structuredContent)throw new ua(Kn.InvalidParams,`Output validation error: Tool ${r} has an output schema but no structured content was provided`);const n=Wu(e.outputSchema),s=await Ku(n,t.structuredContent);if(!s.success){const e=Bu("error"in s?s.error:"Unknown error");throw new ua(Kn.InvalidParams,`Output validation error: Invalid structured content for tool ${r}: ${e}`)}}async executeToolHandler(e,t,r){const n=e.handler;if("createTask"in n){if(!r.taskStore)throw new Error("No task store provided.");const s={...r,taskStore:r.taskStore};if(e.inputSchema){const e=n;return await Promise.resolve(e.createTask(t,s))}{const e=n;return await Promise.resolve(e.createTask(s))}}if(e.inputSchema){const e=n;return await Promise.resolve(e(t,r))}{const e=n;return await Promise.resolve(e(r))}}async handleAutomaticTaskPolling(e,t,r){if(!r.taskStore)throw new Error("No task store provided for task-capable tool.");const n=await this.validateToolInput(e,t.params.arguments,t.params.name),s=e.handler,i={...r,taskStore:r.taskStore},a=n?await Promise.resolve(s.createTask(n,i)):await Promise.resolve(s.createTask(i)),o=a.task.taskId;let c=a.task;const d=c.pollInterval??5e3;for(;"completed"!==c.status&&"failed"!==c.status&&"cancelled"!==c.status;){await new Promise(e=>setTimeout(e,d));const e=await r.taskStore.getTask(o);if(!e)throw new ua(Kn.InternalError,`Task ${o} not found during polling`);c=e}return await r.taskStore.getTaskResult(o)}setCompletionRequestHandler(){this._completionHandlerInitialized||(this.server.assertCanSetRequestHandler(ip(sa)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(sa,async e=>{switch(e.params.ref.type){case"ref/prompt":return function(e){if("ref/prompt"!==e.params.ref.type)throw new TypeError(`Expected CompleteRequestPrompt, but got ${e.params.ref.type}`)}(e),this.handlePromptCompletion(e,e.params.ref);case"ref/resource":return function(e){if("ref/resource"!==e.params.ref.type)throw new TypeError(`Expected CompleteRequestResourceTemplate, but got ${e.params.ref.type}`)}(e),this.handleResourceCompletion(e,e.params.ref);default:throw new ua(Kn.InvalidParams,`Invalid completion reference: ${e.params.ref}`)}}),this._completionHandlerInitialized=!0)}async handlePromptCompletion(e,t){const r=this._registeredPrompts[t.name];if(!r)throw new ua(Kn.InvalidParams,`Prompt ${t.name} not found`);if(!r.enabled)throw new ua(Kn.InvalidParams,`Prompt ${t.name} disabled`);if(!r.argsSchema)return op;const n=Gu(r.argsSchema),s=n?.[e.params.argument.name];if(!Gh(s))return op;const i=function(e){const t=e[Kh];return t?.complete}(s);return i?ap(await i(e.params.argument.value,e.params.context)):op}async handleResourceCompletion(e,t){const r=Object.values(this._registeredResourceTemplates).find(e=>e.resourceTemplate.uriTemplate.toString()===t.uri);if(!r){if(this._registeredResources[t.uri])return op;throw new ua(Kn.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}const n=r.resourceTemplate.completeCallback(e.params.argument.name);return n?ap(await n(e.params.argument.value,e.params.context)):op}setResourceRequestHandlers(){this._resourceHandlersInitialized||(this.server.assertCanSetRequestHandler(ip(Ds)),this.server.assertCanSetRequestHandler(ip(Ls)),this.server.assertCanSetRequestHandler(ip(Vs)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(Ds,async(e,t)=>{const r=Object.entries(this._registeredResources).filter(([e,t])=>t.enabled).map(([e,t])=>({uri:e,name:t.name,...t.metadata})),n=[];for(const e of Object.values(this._registeredResourceTemplates)){if(!e.resourceTemplate.listCallback)continue;const r=await e.resourceTemplate.listCallback(t);for(const t of r.resources)n.push({...e.metadata,...t})}return{resources:[...r,...n]}}),this.server.setRequestHandler(Ls,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([e,t])=>({name:e,uriTemplate:t.resourceTemplate.uriTemplate.toString(),...t.metadata}))})),this.server.setRequestHandler(Vs,async(e,t)=>{const r=new URL(e.params.uri),n=this._registeredResources[r.toString()];if(n){if(!n.enabled)throw new ua(Kn.InvalidParams,`Resource ${r} disabled`);return n.readCallback(r,t)}for(const e of Object.values(this._registeredResourceTemplates)){const n=e.resourceTemplate.uriTemplate.match(r.toString());if(n)return e.readCallback(r,n,t)}throw new ua(Kn.InvalidParams,`Resource ${r} not found`)}),this._resourceHandlersInitialized=!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||(this.server.assertCanSetRequestHandler(ip(ri)),this.server.assertCanSetRequestHandler(ip(ii)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(ri,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,e])=>e.enabled).map(([e,t])=>({name:e,title:t.title,description:t.description,arguments:t.argsSchema?sp(t.argsSchema):void 0}))})),this.server.setRequestHandler(ii,async(e,t)=>{const r=this._registeredPrompts[e.params.name];if(!r)throw new ua(Kn.InvalidParams,`Prompt ${e.params.name} not found`);if(!r.enabled)throw new ua(Kn.InvalidParams,`Prompt ${e.params.name} disabled`);if(r.argsSchema){const n=Wu(r.argsSchema),s=await Ku(n,e.params.arguments??{});if(!s.success){const t=Bu("error"in s?s.error:"Unknown error");throw new ua(Kn.InvalidParams,`Invalid arguments for prompt ${e.params.name}: ${t}`)}const i=s.data,a=r.callback;return await Promise.resolve(a(i,t))}{const e=r.callback;return await Promise.resolve(e(t))}}),this._promptHandlersInitialized=!0)}resource(e,t,...r){let n;"object"==typeof r[0]&&(n=r.shift());const s=r[0];if("string"==typeof t){if(this._registeredResources[t])throw new Error(`Resource ${t} is already registered`);const r=this._createRegisteredResource(e,void 0,t,n,s);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),r}{if(this._registeredResourceTemplates[e])throw new Error(`Resource template ${e} is already registered`);const r=this._createRegisteredResourceTemplate(e,void 0,t,n,s);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),r}}registerResource(e,t,r,n){if("string"==typeof t){if(this._registeredResources[t])throw new Error(`Resource ${t} is already registered`);const s=this._createRegisteredResource(e,r.title,t,r,n);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),s}{if(this._registeredResourceTemplates[e])throw new Error(`Resource template ${e} is already registered`);const s=this._createRegisteredResourceTemplate(e,r.title,t,r,n);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),s}}_createRegisteredResource(e,t,r,n,s){const i={name:e,title:t,metadata:n,readCallback:s,enabled:!0,disable:()=>i.update({enabled:!1}),enable:()=>i.update({enabled:!0}),remove:()=>i.update({uri:null}),update:e=>{void 0!==e.uri&&e.uri!==r&&(delete this._registeredResources[r],e.uri&&(this._registeredResources[e.uri]=i)),void 0!==e.name&&(i.name=e.name),void 0!==e.title&&(i.title=e.title),void 0!==e.metadata&&(i.metadata=e.metadata),void 0!==e.callback&&(i.readCallback=e.callback),void 0!==e.enabled&&(i.enabled=e.enabled),this.sendResourceListChanged()}};return this._registeredResources[r]=i,i}_createRegisteredResourceTemplate(e,t,r,n,s){const i={resourceTemplate:r,title:t,metadata:n,readCallback:s,enabled:!0,disable:()=>i.update({enabled:!1}),enable:()=>i.update({enabled:!0}),remove:()=>i.update({name:null}),update:t=>{void 0!==t.name&&t.name!==e&&(delete this._registeredResourceTemplates[e],t.name&&(this._registeredResourceTemplates[t.name]=i)),void 0!==t.title&&(i.title=t.title),void 0!==t.template&&(i.resourceTemplate=t.template),void 0!==t.metadata&&(i.metadata=t.metadata),void 0!==t.callback&&(i.readCallback=t.callback),void 0!==t.enabled&&(i.enabled=t.enabled),this.sendResourceListChanged()}};this._registeredResourceTemplates[e]=i;const a=r.uriTemplate.variableNames,o=Array.isArray(a)&&a.some(e=>!!r.completeCallback(e));return o&&this.setCompletionRequestHandler(),i}_createRegisteredPrompt(e,t,r,n,s){const i={title:t,description:r,argsSchema:void 0===n?void 0:Hu(n),callback:s,enabled:!0,disable:()=>i.update({enabled:!1}),enable:()=>i.update({enabled:!0}),remove:()=>i.update({name:null}),update:t=>{void 0!==t.name&&t.name!==e&&(delete this._registeredPrompts[e],t.name&&(this._registeredPrompts[t.name]=i)),void 0!==t.title&&(i.title=t.title),void 0!==t.description&&(i.description=t.description),void 0!==t.argsSchema&&(i.argsSchema=Hu(t.argsSchema)),void 0!==t.callback&&(i.callback=t.callback),void 0!==t.enabled&&(i.enabled=t.enabled),this.sendPromptListChanged()}};return this._registeredPrompts[e]=i,n&&Object.values(n).some(e=>Gh(e instanceof $u?e._def?.innerType:e))&&this.setCompletionRequestHandler(),i}_createRegisteredTool(e,t,r,n,s,i,a,o,c){Jh(e);const d={title:t,description:r,inputSchema:np(n),outputSchema:np(s),annotations:i,execution:a,_meta:o,handler:c,enabled:!0,disable:()=>d.update({enabled:!1}),enable:()=>d.update({enabled:!0}),remove:()=>d.update({name:null}),update:t=>{void 0!==t.name&&t.name!==e&&("string"==typeof t.name&&Jh(t.name),delete this._registeredTools[e],t.name&&(this._registeredTools[t.name]=d)),void 0!==t.title&&(d.title=t.title),void 0!==t.description&&(d.description=t.description),void 0!==t.paramsSchema&&(d.inputSchema=Hu(t.paramsSchema)),void 0!==t.outputSchema&&(d.outputSchema=Hu(t.outputSchema)),void 0!==t.callback&&(d.handler=t.callback),void 0!==t.annotations&&(d.annotations=t.annotations),void 0!==t._meta&&(d._meta=t._meta),void 0!==t.enabled&&(d.enabled=t.enabled),this.sendToolListChanged()}};return this._registeredTools[e]=d,this.setToolRequestHandlers(),this.sendToolListChanged(),d}tool(e,...t){if(this._registeredTools[e])throw new Error(`Tool ${e} is already registered`);let r,n,s;if("string"==typeof t[0]&&(r=t.shift()),t.length>1){const r=t[0];if(rp(r))n=t.shift(),t.length>1&&"object"==typeof t[0]&&null!==t[0]&&!rp(t[0])&&(s=t.shift());else if("object"==typeof r&&null!==r){if(Object.values(r).some(e=>"object"==typeof e&&null!==e))throw new Error(`Tool ${e} expected a Zod schema or ToolAnnotations, but received an unrecognized object`);s=t.shift()}}const i=t[0];return this._createRegisteredTool(e,void 0,r,n,void 0,s,{taskSupport:"forbidden"},void 0,i)}registerTool(e,t,r){if(this._registeredTools[e])throw new Error(`Tool ${e} is already registered`);const{title:n,description:s,inputSchema:i,outputSchema:a,annotations:o,_meta:c}=t;return this._createRegisteredTool(e,n,s,i,a,o,{taskSupport:"forbidden"},c,r)}prompt(e,...t){if(this._registeredPrompts[e])throw new Error(`Prompt ${e} is already registered`);let r,n;"string"==typeof t[0]&&(r=t.shift()),t.length>1&&(n=t.shift());const s=t[0],i=this._createRegisteredPrompt(e,void 0,r,n,s);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),i}registerPrompt(e,t,r){if(this._registeredPrompts[e])throw new Error(`Prompt ${e} is already registered`);const{title:n,description:s,argsSchema:i}=t,a=this._createRegisteredPrompt(e,n,s,i,r);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),a}isConnected(){return void 0!==this.server.transport}async sendLoggingMessage(e,t){return this.server.sendLoggingMessage(e,t)}sendResourceListChanged(){this.isConnected()&&this.server.sendResourceListChanged()}sendToolListChanged(){this.isConnected()&&this.server.sendToolListChanged()}sendPromptListChanged(){this.isConnected()&&this.server.sendPromptListChanged()}}const Xh={type:"object",properties:{}};function ep(e){return null!==e&&"object"==typeof e&&"parse"in e&&"function"==typeof e.parse&&"safeParse"in e&&"function"==typeof e.safeParse}function tp(e){return"_def"in e||"_zod"in e||ep(e)}function rp(e){return"object"==typeof e&&null!==e&&!tp(e)&&(0===Object.keys(e).length||Object.values(e).some(ep))}function np(e){if(e){if(rp(e))return Hu(e);if(!tp(e))throw new Error("inputSchema must be a Zod schema or raw shape, received an unrecognized object");return e}}function sp(e){const t=Gu(e);return t?Object.entries(t).map(([e,t])=>{const r=function(e){return e.description}(t),n=function(e){if(Fu(e)){const t=e;return"optional"===t._zod?.def?.type}const t=e;return"function"==typeof e.isOptional?e.isOptional():"ZodOptional"===t._def?.typeName}(t);return{name:e,description:r,required:!n}}):[]}function ip(e){const t=Gu(e),r=t?.method;if(!r)throw new Error("Schema is missing a method literal");const n=Ju(r);if("string"==typeof n)return n;throw new Error("Schema method literal must be a string")}function ap(e){return{completion:{values:e.slice(0,100),total:e.length,hasMore:e.length>100}}}const op={completion:{values:[],hasMore:!1}},cp=window.aeproAngie,dp="Changes are live in the editor but NOT saved. Ask the user to review and click Update (or Save Draft), or save with dynific-editor-save-document when the user asks.",lp=Ou().regex(/^[a-z0-9]+$/i).max(20),up=qu(zu()).optional().describe("Setting keys from dynific/get-widget-schema; omit to keep defaults"),hp=async(e,t={})=>{const r=new FormData;r.append("action",e),r.append("nonce",cp.nonce),r.append("post_id",String(mp().id)),Object.keys(t).forEach(e=>r.append(e,t[e]));const n=await fetch(cp.ajaxUrl,{method:"POST",credentials:"same-origin",body:r}),s=await n.json().catch(()=>null);if(!s||!s.success){const e=s&&s.data&&s.data.message?s.data.message:`Request failed (${n.status})`;throw new Error(e)}return s.data},pp=async e=>{try{return{content:[{type:"text",text:JSON.stringify(await e())}]}}catch(e){return{content:[{type:"text",text:e.message}],isError:!0}}},mp=()=>{const e=window.elementor&&window.elementor.documents&&window.elementor.documents.getCurrent();if(!e||!e.container)throw new Error("No Elementor document is open.");return e},fp=e=>{const t=window.elementor.getContainer(e);if(!t||!t.model||t.document&&t.document!==mp())throw new Error(`Element "${e}" was not found in the open document. Call dynific-editor-get-open-document.`);return t},gp=e=>e&&!Array.isArray(e)?e:{},_p=["e-flexbox","e-div-block","e-grid"],yp=e=>(e||[]).map(e=>{const t={id:e.id,elType:e.elType};return e.widgetType&&(t.widgetType=e.widgetType,t.settings=gp(e.settings)),e.elements&&e.elements.length&&(t.elements=yp(e.elements)),t}),wp=e=>{const t=fp(e),r=t.model.get("elType");if("section"===r){const r=t.model.get("elements").first();if(!r)throw new Error(`Section "${e}" has no column.`);return fp(r.id)}if("container"!==r&&"column"!==r&&!_p.includes(r))throw new Error(`"${e}" is a ${r}. parent_id must be a box: container, section, column, or an Elementor 4 Flexbox / Div block / Grid.`);return t},vp=()=>{const e=mp(),t=e.config||{};let r=[];try{r=window.elementor.selection.getElements().map(e=>e.id)}catch(e){r=[]}return{document_id:e.id,type:t.type,selected_ids:r,elements:yp(window.elementor.elements.toJSON({remove:["default","editSettings","defaultEditSettings"]})),note:"Dynific widgets: dynific-editor-add-widgets / update-widget / move-element / remove-element. Structure: Elementor's own tools. "+dp}},bp=async({widgets:e,parent_id:t,position:r})=>{const n=await hp("aepro_ai_validate_widgets",{widgets:JSON.stringify(e)});return(()=>{let e=null;try{e=$e.internal("document/history/start-log",{type:"add",title:"Dynific AI: add widgets"})}catch(t){e=null}try{return(()=>{const e=t?wp(t):(()=>{const e=mp().container;if(cp.useContainer)return $e.run("document/elements/create",{container:e,model:{elType:"container",settings:{flex_direction:"column"}}});const t=$e.run("document/elements/create",{container:e,model:{elType:"section"},columns:1});return wp(t.id)})(),s=[];return n.elements.forEach((t,n)=>{const i={};Number.isInteger(r)&&(i.at=r+n);const a=$e.run("document/elements/create",{container:e,model:{elType:"widget",widgetType:t.widgetType,settings:gp(t.settings)},options:i});s.push({id:a.id,widgetType:t.widgetType})}),{parent_id:e.id,created:s,note:dp}})()}finally{e&&$e.internal("document/history/end-log",{id:e})}})()},kp=(e,t=!1)=>(e||[]).reduce((e,r)=>e+(t&&"widget"!==r.elType?0:1)+kp(r.elements,t),0);cp&&cp.ajaxUrl&&cp.nonce&&window.$e&&(new class{appId;angieDetector;clientManager;logger;registrationQueue;isInitialized=!1;instanceId;sidebarV2BootPromise=null;promptHashListenerAttached=!1;constructor(e){this.appId=e?.appId?.trim()||void 0,this.instanceId=Sc(),this.logger=ka({instanceId:this.instanceId}),this.logger.log("Constructor called - initializing SDK"),this.angieDetector=new Aa(()=>this.instanceId),this.registrationQueue=new _d,this.clientManager=new Na,this.logger.log("Setting up event handlers"),this.setupAngieReadyHandler(),this.setupServerInitHandler(),this.setupReRegistrationHandler(),this.logger.log("SDK initialization complete")}async loadSidebar(e){Gc();const{widgetConfig:t,...r}=e||{},n={...el,...r};qa.containerId=n.containerId,qa.instanceId=this.instanceId,qa.appId=this.appId,Uc({skipDefaultCss:n.skipDefaultCss});const s=await fd(n);s&&window.addEventListener("message",e=>{if(e.origin===qa.iframeUrlObject?.origin)switch(e.data.type){case Pa.SET:window.localStorage.setItem(e.data.key,e.data.value);break;case Pa.GET:{const t=e.ports[0],r=window.localStorage.getItem(e.data.key);t.postMessage({value:r});break}}}),s&&t&&s.iframe.contentWindow?.postMessage({type:"sdk-widget-config",payload:t},s.iframeOrigin),this.setupPromptHashDetection()}loadSidebarV2(e){return e.host.instanceId&&(this.instanceId=e.host.instanceId),this.sidebarV2BootPromise=(async e=>{Gc();const t={browserUiTheme:"undefined"!=typeof window&&"function"==typeof window.matchMedia?window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light":vd.iframe.uiTheme,isInIframe:"undefined"!=typeof window&&window!==window.top,isRTL:"undefined"!=typeof document&&"rtl"===document.documentElement.dir},r=((e,t)=>{const r=e.boot??{},n=e.container??{},s=e.iframe??{},i=e.callbacks??{},a=n.layout??vd.container.layout,o=(e=>e===Yc?Bd:yd)(a),c=n.chatToggleButton?.enabled??o.chatToggleButtonEnabled;return{host:{appId:e.host.appId,instanceId:e.host.instanceId,aiContext:e.host.aiContext,website:e.host.website,analytics:e.host.analytics},boot:{allowInIframe:r.allowInIframe??vd.boot.allowInIframe},container:{id:n.id?.trim()||za,layout:a,styleTheme:n.styleTheme??o.styleTheme,create:n.create??o.create,skipDefaultCss:n.skipDefaultCss??o.skipDefaultCss,persistOpenState:n.persistOpenState??o.persistOpenState,resizable:n.resizable??o.resizable,chatToggleButton:{enabled:c,selector:n.chatToggleButton?.selector?.trim()||vd.container.chatToggleButtonSelector}},iframe:{origin:s.origin?.trim()||vd.iframe.origin,path:s.path?.trim()||vd.iframe.path,uiTheme:s.uiTheme??t.browserUiTheme,isRTL:s.isRTL??t.isRTL},callbacks:{onClose:i.onClose,onToggle:i.onToggle,getExternalHeaders:i.getExternalHeaders,getWebsiteContext:i.getWebsiteContext,getAnalyticsContext:i.getAnalyticsContext},widgetConfig:Qd(a,e.widgetConfig)}})(e,t);if(!((e,t)=>!(!e.boot.allowInIframe&&t.isInIframe))(r,t))return;if(r.container.layout===Qc&&rd())throw new Error('Angie SDK: only one sidebar layout instance is supported on a page. Use container.layout "floatingChat" for the extra instance.');if(n=r.container.id,Xc.find(e=>e.containerId===n))throw new Error(`Angie SDK: container id "${r.container.id}" is already used by another Angie instance. Give this instance its own container.id.`);var n;const s=r.host.instanceId||e.sdkInstanceId||Sc();if(td(s))throw new Error(`Angie SDK: instance id "${s}" is already used by another Angie instance. Give this instance its own host.instanceId.`);Xc[0]&&r.container.chatToggleButton.selector===wd&&(r.container.chatToggleButton.selector=`${wd}-${s}`);const i=(e=>{const t=0===Xc.length,r={...Ua(),...e,iframeElementId:t?ja:`${ja}-${e.instanceId}`},n=t?Object.assign(qa,r):r;return Xc.push(n),n})({containerId:r.container.id,instanceId:s,appId:e.appId,layout:r.container.layout});var a;dd(i),cd(),a={iframeOrigin:r.iframe.origin,host:r.host,getExternalHeaders:r.callbacks.getExternalHeaders,getWebsiteContext:r.callbacks.getWebsiteContext,getAnalyticsContext:r.callbacks.getAnalyticsContext,instance:i},bd.set(a.instance,a),kd||(kd=!0,window.addEventListener("message",e=>{(async e=>{const t=(e=>{const t=[...bd.values()].filter(t=>t.iframeOrigin===e.origin);return t.length<=1?t[0]??null:t.find(t=>t.instance.iframe?.contentWindow===e.source)??null})(e);if(!t)return;const r=e.data?.type,n=e.ports?.[0];switch(r){case"GET_EXTERNAL_HEADERS":if(!n)return;await(async(e,t)=>{try{const r=t?await t():{};$c(e,(e=>Object.fromEntries(Object.entries(e).filter(([,e])=>void 0!==e)))(r))}catch(t){Ec(e,{message:t instanceof Error?t.message:String(t)})}})(n,t.getExternalHeaders);break;case"angie/context/get-website-context":if(!n)return;await Sd(n,t.getWebsiteContext,()=>{return e=t.host,{payload:{name:document.title,tagline:"",homeUrl:window.location.origin,siteLang:document.documentElement.lang,docTitle:document.title,platform:"frontend",timezone:Intl.DateTimeFormat().resolvedOptions().timeZone,today:(new Date).toISOString().split("T")[0],...e?.website}};var e});break;case"angie/context/get-analytics-context":if(!n)return;await Sd(n,t.getAnalyticsContext,()=>{return e=t.host,{payload:{screenPath:window.location.pathname,...e?.analytics}};var e});break;case Pa.GET:if(!n)return;n.postMessage({value:Ed(e.data.key,t.host?.instanceId)});break;case Pa.SET:((e,t,r)=>{try{window.localStorage.setItem($d(e,r),t)}catch{}})(e.data.key,e.data.value,t.host?.instanceId)}})(e)})),r.container.create&&((e,t)=>{if(document.getElementById(e))return;const r=document.createElement("div");r.id=e,r.dir=t?"rtl":"ltr";const n=document.createElement("div");n.id="angie-sidebar-loading",n.setAttribute("aria-live","polite"),n.className="angie-sr-only",r.appendChild(n),document.body.appendChild(r)})(r.container.id,t.isRTL);const o=Wd[r.container.layout],c={config:r,env:t,instance:i};o.initShell(c),o.beforeOpenIframe?.(c);const d={aiContext:(l=r.host).aiContext,appId:l.appId,configVersion:2,telemetry:{screenPath:window.location.pathname},website:{docTitle:document.title,homeUrl:window.location.origin,name:document.title,platform:"frontend",siteLang:document.documentElement.lang,tagline:"",...l.website}};var l;const u=await(async e=>{const t=e.instance??qa;return!!await fd({isRTL:e.iframe.isRTL,origin:e.iframe.origin,path:e.iframe.path,uiTheme:e.iframe.uiTheme,embeddedConfig:e.embeddedConfig},t)&&(e.container.layout===Yc&&e.container.chatToggleButton.enabled?(Ld({containerId:e.container.id,toggleButtonSelector:e.container.chatToggleButton.selector,isOpen:!1,instance:t}),!0):(t.iframe&&vc(t.iframe,!1,t.containerId),e.container.chatToggleButton.enabled&&Id(e.container.chatToggleButton.selector,!1),!0))})({container:r.container,iframe:r.iframe,embeddedConfig:d,instance:i});o.afterOpenIframe?.(c),u&&(((e,t=qa)=>{wc(t,{payload:e,type:"sdk-embedded-config"})})(d,i),r.widgetConfig&&((e,t=qa)=>{wc(t,{payload:e,type:"sdk-widget-config"})})(r.widgetConfig,i))})({...e,sdkInstanceId:this.instanceId,appId:this.appId}),this.setupPromptHashDetection(),this.sidebarV2BootPromise}isRefreshPingForThisInstance(e,t){const r=e.data?.payload?.instanceId;if(r)return r===this.instanceId;const n=t?.iframe?.contentWindow;return n&&e.source?e.source===n:ed()<2}setupReRegistrationHandler(){window.addEventListener("message",e=>{if(e.data?.type===xa.SDK_ANGIE_REFRESH_PING){const t=td(this.instanceId),r=t?.iframeUrlObject?.origin;if(r&&e.origin!==r)return void this.logger.log(`Ignoring refresh ping from unexpected origin. Event origin: ${e.origin}, iframe origin: ${r}`);if(!this.isRefreshPingForThisInstance(e,t))return;if(this.logger.log("Angie refresh ping received"),this.registrationQueue.resetAllToPending()){const e=this.registrationQueue.getPending().length;this.logger.log(`Successfully reset ${e} registrations, processing queue`),this.handleAngieReady()}else this.logger.log("Skipping queue reset - processing already in progress")}})}setupAngieReadyHandler(){this.angieDetector.waitForReady().then(e=>{e.isReady?this.handleAngieReady():this.logger.warn("Angie not detected - servers will remain queued")}).catch(e=>{this.logger.error("Error waiting for Angie:",e)})}async handleAngieReady(){this.logger.log("Angie is ready, processing queued registrations");try{await this.registrationQueue.processQueue(async e=>{this.logger.log(`processQueue callback called for "${e.config.name}"`),await this.processRegistration(e)}),this.isInitialized=!0,this.logger.log("Initialization complete")}catch(e){this.logger.error("Error processing registration queue:",e)}}async processRegistration(e){this.logger.log(`Processing registration for server "${e.config.name}" (ID: ${e.id})`);try{this.logger.log(`Calling clientManager.requestClientCreation for "${e.config.name}"`);const t={...e,instanceId:this.instanceId};await this.clientManager.requestClientCreation(t),this.logger.log(`Successfully registered server "${e.config.name}"`)}catch(t){throw this.logger.error(`Failed to register server "${e.config.name}":`,t),t}}registerLocalServer(e){return e.type=Ta.LOCAL,e.transport=$a.POST_MESSAGE,this.registerServer(e)}registerRemoteServer(e){return e.type=Ta.REMOTE,this.registerServer(e)}isLocalServerConfig(e){return e.type===Ta.LOCAL||!e.type&&"server"in e}isRemoteServerConfig(e){return e.type===Ta.REMOTE&&"url"in e}async registerServer(e){if(!e.type)return this.logger.warn("For a local server, please use registerLocalServer instead of registerServer"),void this.registerLocalServer(e);if(this.logger.log(`registerServer called for "${e.name}"`),!e.name)throw new Error("Server name is required");if(!e.description)throw new Error("Server description is required");if(this.isLocalServerConfig(e)&&!e.server)throw new Error("Server instance is required for local servers");this.logger.log(`Registering server "${e.name}"`);const t=this.registrationQueue.add(e);if(this.logger.log(`Added registration to queue: ${t.id}`),this.angieDetector.isReady())try{await this.processRegistration(t),this.registrationQueue.updateStatus(t.id,"registered"),this.logger.log(`Server "${e.name}" registered successfully`)}catch(e){const r=e instanceof Error?e.message:String(e);throw this.registrationQueue.updateStatus(t.id,"failed",r),e}else this.logger.log(`Server "${e.name}" queued until Angie is ready`)}getRegistrations(){return this.registrationQueue.getAll()}getPendingRegistrations(){return this.registrationQueue.getPending()}isAngieReady(){return this.angieDetector.isReady()}isReady(){return this.isInitialized}async waitForReady(){if(this.sidebarV2BootPromise)await this.sidebarV2BootPromise;else for(;!qa.iframe;)await new Promise(e=>setTimeout(e,100));if(!(await this.angieDetector.waitForReady()).isReady)throw new Error("Angie is not available");for(;!this.isInitialized;)await new Promise(e=>setTimeout(e,100))}async triggerAngie(e){if(!this.isAngieReady())throw new Error("Angie is not ready. Please wait for Angie to be available before triggering.");const t=this.generateRequestId(),r=e.options?.timeout||3e4;return new Promise((n,s)=>{const i=setTimeout(()=>{s(new Error("Angie trigger request timed out"))},r),a=e=>{e.data?.type===xa.SDK_TRIGGER_ANGIE_RESPONSE&&e.data?.payload?.requestId===t&&(clearTimeout(i),window.removeEventListener("message",a),n(e.data.payload))};window.addEventListener("message",a);const o={type:xa.SDK_TRIGGER_ANGIE,payload:{requestId:t,instanceId:this.instanceId,prompt:e.prompt,options:e.options,contextAttachment:e.contextAttachment,suggestions:e.suggestions,context:{pageUrl:window.location.href,pageTitle:document.title,...e.context}},timestamp:Date.now()};this.logger.log(`Triggering Angie with prompt (Request ID: ${t})`),window.postMessage(o,window.location.origin)})}destroy(){this.registrationQueue.clear(),this.logger.log("SDK destroyed")}setupServerInitHandler(){window.addEventListener("message",e=>{e.data?.type===xa.SDK_REQUEST_INIT_SERVER&&(this.logger.log("Server init request received"),this.handleServerInitRequest(e))})}handleServerInitRequest(e){const{clientId:t,serverId:r,instanceId:n}=e.data.payload||{};if(t&&r)if(this.logger.log(`Server init request received - Request instanceId: ${n}, This instanceId: ${this.instanceId}`),n&&n!==this.instanceId)this.logger.log(`Ignoring server init request for different instance. Request instanceId: ${n}, this instanceId: ${this.instanceId}`);else{this.logger.log(`Handling server init request for clientId: ${t}, serverId: ${r}`);try{const t=this.registrationQueue.getAll().find(e=>e.id===r);if(!t)return void this.logger.log(`No registration found for serverId: ${r} (likely belongs to another instance)`);if("type"in t.config&&"remote"===t.config.type)return void this.logger.log("Remote server registration detected; skipping local connect");const n=e.ports[0];if(!n)return void this.logger.error("No port provided in server init request");const s=t.config.server;this.migrateInstructionsCompat(s);const i=new Oa(n);s.connect(i),this.logger.log(`Server "${t.config.name}" initialized successfully`)}catch(e){this.logger.error(`Error initializing server for clientId ${t}:`,e)}}else this.logger.error("Invalid server init request - missing clientId or serverId")}migrateInstructionsCompat(e){try{const t="server"in e&&e.server?e.server:e,r=t._serverInfo,n=t._instructions;r?.instructions&&!n&&(t._instructions=r.instructions,this.logger.log("Migrated instructions from serverInfo to serverOptions (backward compat)"))}catch{}}generateRequestId(){return`${this.instanceId}-${Date.now()}-${Math.random().toString(36).substring(2,8)}`}parseHashParams(e){const t=e.startsWith("#")?e.substring(1):e;return new URLSearchParams(t)}shouldHandlePromptHash(e){const t=e.get("angie-instance");return t?t===this.instanceId:0===Xd.length||Xd[0]===this}async handlePromptHash(){const e=window.location.hash;if(e.includes(`${Yd}=`))try{const t=this.parseHashParams(e);if(!this.shouldHandlePromptHash(t))return;const r=t.get(Yd)||"";if(!r)return void this.logger.warn("Empty prompt detected in hash");const n="true"===t.get("angie-new-chat");this.logger.log("Detected prompt in hash:",{prompt:r,newChat:n}),await this.waitForReady();const s=await this.triggerAngie({prompt:r,context:{source:"hash-parameter",pageUrl:window.location.href,timestamp:(new Date).toISOString()},options:{newChat:n}});this.logger.log("Triggered successfully from hash:",s),window.location.hash=""}catch(e){this.logger.error("Failed to trigger from hash:",e)}}setupPromptHashDetection(){this.promptHashListenerAttached||(this.promptHashListenerAttached=!0,Xd.push(this),window.addEventListener("hashchange",()=>this.handlePromptHash())),this.handlePromptHash()}}).registerLocalServer({name:"dynific-editor",version:cp.version,description:"Dynific Addons: change the template or page open in the Elementor editor live (add, update, move, remove Dynific widgets).",server:(()=>{const e=new Yh({name:"dynific-editor",title:"Dynific Addons editor tools",version:cp.version},{instructions:cp.instructions});return e.registerTool("dynific-editor-get-open-document",{title:"Dynific: get open document",description:'Call FIRST before changing the template or page open in the Elementor editor. Returns its element tree (ids, widget types, changed settings) and the ids the user has selected ("this widget").',annotations:{readOnlyHint:!0}},()=>pp(vp)),e.registerTool("dynific-editor-add-widgets",{title:"Dynific: add widgets to open document",description:'Inserts Dynific widgets into the page, post or template open in the Elementor editor, live – into an existing box (parent_id) or, without parent_id, into a new box at the end. Structure (columns, rows) is built with Elementor\'s own tools. Listings work too, e.g. ae-post-blocks with settings {template: "<published block layout id>", ae_post_type: "<post type>"}. Widgets, setting keys, ACF fields and layout IDs are validated first; nothing is added if any is invalid.',inputSchema:{widgets:ju(Uu({widget:Ou().regex(/^[a-z0-9_-]+$/i).max(100).describe("Widget name from dynific/list-widgets, e.g. ae-post-title"),settings:up})).min(1).max(30),parent_id:lp.optional().describe("Box id from get-open-document: container, section, column, or an Elementor 4 Flexbox / Div block / Grid"),position:Nu().int().min(0).optional().describe("Index inside the parent; omit to append")}},e=>pp(()=>bp(e))),e.registerTool("dynific-editor-update-widget",{title:"Dynific: update widget settings",description:"Changes settings of one Dynific widget in the open editor, live. Send only the keys to change. Keys and select values are validated against dynific/get-widget-schema. Boxes are changed with Elementor's own tools.",inputSchema:{element_id:lp.describe("Widget id from get-open-document"),settings:qu(zu())}},e=>pp(()=>(async({element_id:e,settings:t})=>{const r=fp(e),n=r.model.get("widgetType");if("widget"!==r.model.get("elType")||!n)throw new Error(`"${e}" is a box, not a widget. Boxes (structure, sizes, styles) are changed with Elementor's own tools, e.g. elementor/manage-elements.`);const s=await hp("aepro_ai_validate_settings",{widget:n,settings:JSON.stringify(t)});return $e.run("document/elements/settings",{container:r,settings:gp(s.settings),options:{external:!0}}),{id:e,widgetType:n,updated:Object.keys(gp(s.settings)),note:dp}})(e))),e.registerTool("dynific-editor-move-element",{title:"Dynific: move element",description:"Moves a widget or box to another box and/or position in the open editor – e.g. put the title above the image (same parent, new position) or move the rating into the left column (parent_id = that column's id from get-open-document).",inputSchema:{element_id:lp,parent_id:lp.describe("Target box id (container, section, column, or Elementor 4 Flexbox / Div block / Grid)"),position:Nu().int().min(0).optional()}},e=>pp(()=>(({element_id:e,parent_id:t,position:r})=>{const n=fp(e),s=wp(t),i=Number.isInteger(r)?{at:r}:{};return $e.run("document/elements/move",{container:n,target:s,options:i}),{id:e,parent_id:s.id,note:dp}})(e))),e.registerTool("dynific-editor-remove-element",{title:"Dynific: remove element",description:"Removes a widget or container from the open editor. The user can undo it; confirm with the user before removing more than they asked for.",inputSchema:{element_id:lp},annotations:{destructiveHint:!0}},e=>pp(()=>(({element_id:e})=>($e.run("document/elements/delete",{container:fp(e)}),{removed:e,note:"Removed (undo with Ctrl/Cmd+Z). "+dp}))(e))),e.registerTool("dynific-editor-save-document",{title:"Dynific: save or publish open document",description:"USE THIS whenever the user is in the Elementor editor and says publish, save or update – never dynific/update-template for that. Clicks the editor's Publish/Update (status=publish) or Save Draft (status=draft), so every live change made in the editor is saved, then verifies the saved content matches the editor. status=publish makes it live – only when the user asked. To change where a Dynific template applies (post type, apply_global, specific posts) use dynific/update-template and dynific/assign-template-to-post (settings only).",inputSchema:{status:Du(["publish","draft"]).describe("publish = Publish/Update; draft = Save Draft")}},e=>pp(()=>(async({status:e})=>{const t=mp(),r="publish"===e?"document/save/publish":"document/save/draft",n=window.elementor.elements.toJSON({remove:["default","editSettings","defaultEditSettings"]});await $e.run(r,{document:t});const s=await hp("aepro_ai_document_state"),i=kp(n),a=kp(n,!0);if((e=>!(!e.editor||!e.editor.isChanged))(t))throw new Error("The editor still has unsaved changes after saving. Ask the user to click Publish/Update and check for an error message in the editor.");if("publish"===e){if("publish"!==s.status)throw new Error(`The document was saved but its status is "${s.status}", not publish. The user may not be allowed to publish; ask them to click Publish.`);if(s.elements!==i||s.widgets!==a)throw new Error(`Saved content does not match the editor (saved ${s.widgets} widgets, editor has ${a}). Ask the user to click Update and reload the page to check.`)}return{document_id:t.id,status:s.status,saved_widgets:s.widgets,note:"publish"===e?`Published with all editor changes (${s.widgets} widgets saved and verified). If this is a Dynific template, check where it applies with dynific/get-template.`:"Saved as draft. For a page that is already published, Elementor keeps the live version unchanged."}})(e))),e})()}).then(()=>window.console.debug("[Dynific] Angie editor MCP server registered")).catch(e=>window.console.debug("[Dynific] Angie editor MCP server registration failed",e))})();
Save File
Cancel