@hookform/resolvers 3.4.2 → 3.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,2 +1,2 @@
1
- import{toNestErrors as r,validateFieldsNatively as e}from"@hookform/resolvers";var o=function(r){for(var e={};r.length;){var o=r[0],a=o.path.join(".");e[a]||(e[a]={message:o.message,type:o.code}),r.shift()}return e},a=function(a,s,t){return void 0===t&&(t={}),function(s,n,i){var u=a(s);return u.problems?{values:{},errors:r(o(u.problems),i)}:(i.shouldUseNativeValidation&&e({},i),{errors:{},values:t.raw?s:u.data})}};export{a as arktypeResolver};
1
+ import{toNestErrors as e,validateFieldsNatively as t}from"@hookform/resolvers";const r=Array,i=(e,t)=>e.includes(t),n=(e,t,r)=>void 0===t?e??[]:void 0===e?void 0===t?[]:Array.isArray(t)?t:[t]:(r?.prepend?Array.isArray(t)?e.unshift(...t):e.unshift(t):Array.isArray(t)?e.push(...t):e.push(t),e),s=(e,t)=>void 0===e?[t]:(e.includes(t)||e.push(t),e);class o extends Error{}const a=e=>l(e,o),l=(e,t=Error)=>{throw new t(e)};class c extends Error{name="ParseError"}const u=e=>l(e,c);function h(e,t){const r=Array.isArray(e),i=Object.entries(e).flatMap((e,i)=>{const n=r?t(i,e[1]):t(...e,i);return Array.isArray(n[0])||0===n.length?n:[n]}),n=Object.fromEntries(i);return"number"==typeof i[0]?.[0]?Object.values(n):n}const d=e=>Object.entries(e),p=e=>Object.fromEntries(e),f=(e,t)=>e in t,m=class{constructor(e){Object.assign(this,e)}};class g extends m{}const y=class{};class b extends y{}const v=(e,t)=>{const r={},i={};let n;for(n in e)n in t?r[n]=e[n]:i[n]=e[n];return[r,i]},$=(e,t)=>v(e,t)[1],x=e=>0===Object.keys(e).length,k=e=>[...Object.entries(e),...Object.getOwnPropertySymbols(e).map(t=>[t,e[t]])],w=Symbol("represents an uninitialized value"),A=(e,t)=>{t.addInitializer(function(){this[t.name]=this[t.name].bind(this)})},O=(e,t)=>function(){const r=e.call(this);return Object.defineProperty(this,t.name,"getter"===t.kind?{value:r}:{value:()=>r,enumerable:!1}),r},j=e=>"function"==typeof e&&0===e.length,q=class extends Function{constructor(...e){const t=e.slice(0,-1),r=e.at(-1);try{super(...t,r)}catch(t){return a(`Encountered an unexpected error while compiling your definition:\n Message: ${t} \n Source: (${e.slice(0,-1)}) => {\n ${e.at(-1)}\n }`)}}};class E extends y{constructor(e,t){return super(),Object.assign(Object.setPrototypeOf(e.bind(t?.bind??this),this.constructor.prototype),t?.attach)}}const K=(e=>{let t=w;return()=>t===w?t=(()=>{try{return new Function("return false")()}catch(e){return!0}})():t})(),S=(e,t)=>R(e)===t,R=e=>{const t=typeof e;return"object"===t?null===e?"null":"object":"function"===t?"object":t},z={bigint:"a bigint",number:"a number",object:"an object",string:"a string",symbol:"a symbol",boolean:"boolean",null:"null",undefined:"undefined"},L={Array:Array,Date:Date,Error:Error,Function:Function,Map:Map,RegExp:RegExp,Set:Set,String:String,Number:Number,Boolean:Boolean,WeakMap:WeakMap,WeakSet:WeakSet,Promise:Promise},C=e=>{let t=Object.getPrototypeOf(e);for(;t?.constructor&&(!f(t.constructor.name,L)||!(e instanceof L[t.constructor.name]));)t=Object.getPrototypeOf(t);const r=t?.constructor?.name;if(void 0!==r&&"Object"!==r)return r},I=e=>"object"==typeof e&&null!==e?C(e)??"object":R(e),B=e=>Array.isArray(e),N={Array:"an array",Function:"a function",Date:"a Date",RegExp:"a RegExp",Error:"an Error",Map:"a Map",Set:"a Set",String:"a String object",Number:"a Number object",Boolean:"a Boolean object",Promise:"a Promise",WeakMap:"a WeakMap",WeakSet:"a WeakSet"},M=e=>{const t=Object(e).name??null;return t&&f(t,L)&&L[t]===e?t:null},P=e=>{const t=[];let r=e;for(;r!==Object.prototype&&null!=r;){for(const e of Object.getOwnPropertyNames(r))"constructor"===e||t.includes(e)||t.push(e);for(const e of Object.getOwnPropertySymbols(r))t.includes(e)||t.push(e);r=Object.getPrototypeOf(r)}return t},F={bigint:P(0n),boolean:P(!1),null:[],number:P(0),object:[],string:P(""),symbol:P(Symbol()),undefined:[]},T=(e,t)=>{let r=e.prototype;for(;null!==r;){if(r===t.prototype)return!0;r=Object.getPrototypeOf(r)}return!1},U=e=>"string"==typeof e?JSON.stringify(e):"bigint"==typeof e?`${e}n`:`${e}`,D={};globalThis.$ark=D;const _=new WeakMap,V={},J=e=>{const t=_.get(e);if(t)return t;let r=G(e);return V[r]?r=`${r}${V[r]++}`:V[r]=1,D[r]=e,_.set(e,r),r},W=e=>`$ark.${J(e)}`,Z=e=>/^[a-zA-Z_$][a-zA-Z_$0-9]*$/.test(e),H=e=>S(e,"object")||"symbol"==typeof e?W(e):U(e),G=e=>{switch(typeof e){case"object":{if(null===e)break;const t=C(e)??"object";return t[0].toLowerCase()+t.slice(1)}case"function":return Z(e.name)?e.name:"fn";case"symbol":return e.description&&Z(e.description)?e.description:"symbol"}return a(`Unexpected attempt to register serializable value of type ${R(e)}`)};class X extends b{argNames;body="";constructor(...e){super(),this.argNames=e;for(const t of e){if(t in this)throw new Error(`Arg name '${t}' would overwrite an existing property on FunctionBody`);this[t]=t}}indentation=0;indent(){return this.indentation+=4,this}dedent(){return this.indentation-=4,this}prop(e,t=!1){return Q(e,t)}index(e,t=!1){return ee(`${e}`,t)}line(e){return this.body+=`${" ".repeat(this.indentation)}${e}\n`,this}const(e,t){return this.line(`const ${e} = ${t}`),this}let(e,t){return this.line(`let ${e} = ${t}`)}set(e,t){return this.line(`${e} = ${t}`)}if(e,t){return this.block(`if (${e})`,t)}elseIf(e,t){return this.block(`else if (${e})`,t)}else(e){return this.block("else",e)}for(e,t,r=0){return this.block(`for (let i = ${r}; ${e}; i++)`,t)}forIn(e,t){return this.block(`for (const k in ${e})`,t)}block(e,t,r=""){return this.line(`${e} {`),this.indent(),t(this),this.dedent(),this.line(`}${r}`)}return(e=""){return this.line(`return ${e}`)}compile(){return new q(...this.argNames,this.body)}}const Q=(e,t=!1)=>"string"==typeof e&&Z(e)?`${t?"?":""}.${e}`:ee(Y(e),t),Y=e=>"symbol"==typeof e?W(e):JSON.stringify(e),ee=(e,t=!1)=>`${t?"?.":""}[${e}]`;var te;!function(e){e.Kind=class{},e.Instantiable=class{},e.reify=e=>e.hkt,e.UnaryKind=class{},e.pipe=(...e)=>t=>e.reduce((e,t)=>t.hkt(e),t)}(te||(te={}));const re=/^(?!^-0$)-?(?:0|[1-9]\d*)(?:\.\d*[1-9])?$/,ie=re.test.bind(re),ne=/^-?\d*\.?\d*$/,se=/^(?:0|(?:-?[1-9]\d*))$/,oe=se.test.bind(se),ae=/^-?\d+$/,le=ae.test.bind(ae),ce={number:"a number",bigint:"a bigint",integer:"an integer"},ue=(e,t)=>`'${e}' was parsed as ${ce[t]} but could not be narrowed to a literal value. Avoid unnecessary leading or trailing zeros and other abnormal notation`,he=(e,t)=>de(e,"number",t),de=(e,t,r)=>{const i=((e,t)=>"number"===t?Number(e):Number.parseInt(e))(e,t);return!Number.isNaN(i)&&((e,t)=>{return"number"===t?0!==(r=e).length&&ne.test(r):le(e);var r})(e,t)?r?.strict?((e,t)=>"number"===t?ie(e):oe(e))(e,t)?i:u(ue(e,t)):i:r?.errorOnFail?u(!0===r?.errorOnFail?`Failed to parse ${ce[t]} from '${e}'`:r?.errorOnFail):void 0},pe=(e,t)=>{switch(R(e)){case"object":return e instanceof Date?e.toDateString():JSON.stringify(me(e,fe,[]),null,t);case"symbol":return fe.onSymbol(e);default:return U(e)}},fe={onCycle:()=>"(cycle)",onSymbol:e=>`Symbol(${J(e)})`,onFunction:e=>`Function(${J(e)})`},me=(e,t,r)=>{switch(R(e)){case"object":{if("function"==typeof e)return fe.onFunction(e);if(r.includes(e))return"(cycle)";const i=[...r,e];if(Array.isArray(e))return e.map(e=>me(e,t,i));if(e instanceof Date)return e.toDateString();const n={};for(const r in e)n[r]=me(e[r],t,i);return n}case"symbol":return fe.onSymbol(e);case"bigint":return`${e}n`;case"undefined":return t.onUndefined??"undefined";default:return e}},ge=e=>h(e,(e,t)=>[e,B(t)?[...t]:t]),ye=Symbol("ArkTypeInternalKind"),be=(e,t)=>e?.[ye]===t,ve=e=>be(e,"root")||be(e,"constraint"),$e=["unit","proto","domain"],xe=["required","optional","index","sequence"],ke=["regex","divisor","exactLength","max","min","maxLength","minLength","before","after"],we=[...ke,...xe,"structure","predicate"],Ae=["alias","union","morph","unit","intersection","proto","domain"],Oe=[...Ae,...we],je=h(we,(e,t)=>[t,1]),qe=h([...xe,"undeclared"],(e,t)=>[t,1]),Ee=h(Oe,(e,t)=>[t,e]),Ke=e=>"string"==typeof e&&e in Ee,Se=e=>Ee[e],Re=e=>Ae.slice(Se(e)+1),ze=e=>"string"==typeof e||"boolean"==typeof e||"number"==typeof e||null===e?e:H(e),Le=e=>{let t="{ ";for(const[r,i]of Object.entries(e))t+=`${r}: ${H(i)}, `;return t+" }"},Ce=e=>{const t=e;return t.hasAssociatedError&&(t.defaults.expected??=e=>"description"in e?e.description:t.defaults.description(e),t.defaults.actual??=e=>pe(e),t.defaults.problem??=e=>`must be ${e.expected}${e.actual?` (was ${e.actual})`:""}`,t.defaults.message??=e=>{if(0===e.path.length)return e.problem;const t=`${e.propString} ${e.problem}`;return"["===t[0]?`value at ${t}`:t}),t},Ie={};class Be extends b{input;[ye]="error";path;data;nodeConfig;constructor(e,t){super(),this.input=e,Object.defineProperties(this,Object.getOwnPropertyDescriptors(e));const r=t.data;"union"===e.code&&(e.errors=e.errors.flatMap(e=>e.hasCode("union")?e.errors:e)),this.nodeConfig=t.config[this.code],this.path=e.path??[...t.path],e.relativePath&&this.path.push(...e.relativePath),this.data="data"in e?e.data:r}hasCode(e){return this.code===e}get propString(){return(e=>{const t=this.path.reduce((e,t)=>"string"==typeof t&&Z(t)?`${e}.${t}`:`${e}[${pe(t)}]`,"");return"."===t[0]?t.slice(1):t})()}get expected(){return this.input.expected??this.nodeConfig.expected?.(this.input)}get actual(){return void 0!==this.input.actual?this.input.actual:this.nodeConfig.actual?.(this.data)}get problem(){return this.input.problem??this.nodeConfig.problem(this)}get message(){return this.input.message??this.nodeConfig.message(this)}toString(){return this.message}throw(){throw this}}class Ne extends r{ctx;constructor(e){super(),this.ctx=e}byPath={};count=0;mutable=this;add(e){const t=this.byPath[e.propString];if(t){const r=new Be({code:"intersection",errors:t.hasCode("intersection")?[...t.errors,e]:[t,e]},this.ctx),i=this.indexOf(t);this.mutable[-1===i?this.length:i]=r,this.byPath[e.propString]=r}else this.byPath[e.propString]=e,this.mutable.push(e);this.count++}get summary(){return this.toString()}get message(){return this.toString()}toString(){return this.join("\n")}throw(){throw this}}class Me{root;config;path=[];queuedMorphs=[];errors=new Ne(this);branches=[];seen={};constructor(e,t){this.root=e,this.config=t}get currentBranch(){return this.branches.at(-1)}queueMorphs(e){const t={path:[...this.path],morphs:e};this.currentBranch?.queuedMorphs.push(t)??this.queuedMorphs.push(t)}finalize(){if(this.hasError())return this.errors;let e=this.root;if(this.queuedMorphs.length)for(let t=0;t<this.queuedMorphs.length;t++){const{path:r,morphs:i}=this.queuedMorphs[t],n=r.at(-1);let s;if(void 0!==n){s=e;for(let e=0;e<r.length-1;e++)s=s[r[e]]}this.path=r;for(const t of i){const r=t(void 0===s?e:s[n],this);if(r instanceof Ne)return r;if(this.hasError())return this.errors;if(r instanceof Be)return this.error(r),this.errors;void 0===s?e=r:s[n]=r}}return e}get currentErrorCount(){return this.currentBranch?this.currentBranch.error?1:0:this.errors.count}hasError(){return 0!==this.currentErrorCount}get failFast(){return 0!==this.branches.length}error(e){const t="object"==typeof e?e.code?e:{...e,code:"predicate"}:{code:"predicate",expected:e},r=new Be(t,this);return this.currentBranch?this.currentBranch.error=r:this.errors.add(r),r}get data(){let e=this.root;for(const t of this.path)e=e?.[t];return e}invalid(e){return this.error(e),!1}pushBranch(){this.branches.push({error:void 0,queuedMorphs:[]})}popBranch(){return this.branches.pop()}}class Pe extends E{attachments;constructor(e){super((e,t)=>{if(!this.includesMorph&&!this.allowsRequiresContext&&this.allows(e))return e;if(t)return this.traverseApply(e,t);const r=new Me(e,this.$.resolvedConfig);return this.traverseApply(e,r),r.finalize()},{attach:e}),this.attachments=e}qualifiedId=`${this.$.id}${this.id}`;includesMorph="morph"===this.kind||this.hasKind("optional")&&this.hasDefault()||this.hasKind("structure")&&"delete"===this.undeclared||this.children.some(e=>e.includesMorph);allowsRequiresContext=this.hasKind("predicate")&&1!==this.inner.predicate.length||"alias"===this.kind||this.children.some(e=>e.allowsRequiresContext);referencesById=this.children.reduce((e,t)=>Object.assign(e,t.referencesById),{[this.id]:this});get references(){return Object.values(this.referencesById)}precedence=Se(this.kind);jit=!1;allows=e=>this.allowsRequiresContext?this.traverseAllows(e,new Me(e,this.$.resolvedConfig)):this.traverseAllows(e);traverse(e){return this(e)}_in;get in(){return this._in??=this.getIo("in"),this._in}_out;get out(){return this._out??=this.getIo("out"),this._out}_description;get description(){return this._description??=this.inner.description??this.$.resolvedConfig[this.kind].description?.(this),this._description}getIo(e){if(!this.includesMorph)return this;const t={};for(const[r,i]of this.entries){const n=this.impl.keys[r];if(!n.meta)if(n.child){const n=i;t[r]=B(n)?n.map(t=>t[e]):n[e]}else t[r]=i}return this.$.node(this.kind,t)}toJSON(){return this.json}toString(){return this.expression}equals(e){return this.typeHash===e.typeHash}hasKind(e){return this.kind===e}isBasis(){return i($e,this.kind)}isConstraint(){return i(we,this.kind)}isRefinement(){return i(ke,this.kind)}isRoot(){return i(Ae,this.kind)}hasUnit(e){return this.hasKind("unit")&&this.allows(e)}hasOpenIntersection(){return this.impl.intersectionIsOpen}get nestableExpression(){return this.expression}bindScope(e){return this.$===e?this:new this.constructor(Object.assign((t=this.attachments,Object.create(Object.getPrototypeOf(t),Object.getOwnPropertyDescriptors(t))),{$:e}));var t}firstReference(e){return this.references.find(t=>t!==this&&e(t))}firstReferenceOrThrow(e){return this.firstReference(e)??l(`${this.id} had no references matching predicate ${e}`)}firstReferenceOfKind(e){return this.firstReference(t=>t.kind===e)}firstReferenceOfKindOrThrow(e){return this.firstReference(t=>t.kind===e)??l(`${this.id} had no ${e} references`)}transform(e,t){return this._transform(e,{seen:{},path:[],shouldTransform:t?.shouldTransform??(()=>!0)})}_transform(e,t){if(t.seen[this.id])return this.$.lazilyResolve(t.seen[this.id]);if(!t.shouldTransform(this,t))return this;let r;t.seen[this.id]=()=>r;const i=h(this.inner,(r,i)=>{if(!this.impl.keys[r].child)return[r,i];const n=i;if(!B(n)){const i=n._transform(e,t);return i?[r,i]:[]}const s=n.flatMap(r=>r._transform(e,t)??[]);return s.length?[r,s]:[]});delete t.seen[this.id];const n=e(this.kind,i,t);return null===n||x(n)?null:"required"!==this.kind&&"optional"!==this.kind&&"index"!==this.kind||"value"in n?("morph"===this.kind&&(n.in??=this.$.keywords.unknown),r=this.$.node(this.kind,n)):null}configureShallowDescendants(e){const t="string"==typeof e?{description:e}:e;return this.transform((e,r)=>({...r,...t}),{shouldTransform:e=>"structure"!==e.kind})}}class Fe{sources;constructor(e){this.sources=e}clone(){return new Fe(this.sources)}static from(e,t,r){return new Fe({"[]":{[e]:{l:t,r:r}}})}static fromEntries(e){return e.length?new Fe({"[]":p(e)}):a("Unexpected attempt to create a disjoint from no entries")}get flat(){return d(this.sources).flatMap(([e,t])=>d(t).map(([t,r])=>({path:e,kind:t,disjoint:r})))}describeReasons(){const e=this.flat;if(1===e.length){const{path:t,disjoint:r}=e[0],i=JSON.parse(t).join(".");return`Intersection${i&&` at ${i}`} of ${Te(r)} results in an unsatisfiable type`}return`The following intersections result in unsatisfiable types:\n• ${e.map(({path:e,disjoint:t})=>`${e}: ${Te(t)}`).join("\n• ")}`}isEmpty(){return 0===this.flat.length}throw(){return u(this.describeReasons())}invert(){const e=d(this.sources).map(([e,t])=>[e,h(t,(e,t)=>[e,{l:t.r,r:t.l}])]);return new Fe(p(e))}add(e){d(e.sources).forEach(([e,t])=>Object.assign(this.sources[e]??{},t))}withPrefixKey(e){const t=d(this.sources).map(([t,r])=>{const i=JSON.parse(t);return i.unshift("symbol"==typeof e?J(e):e),[JSON.stringify(i),r]});return new Fe(p(t))}toString(){return pe(this.sources)}}const Te=e=>`${Ue(e.l)} and ${Ue(e.r)}`,Ue=e=>be(e,"root")?e.expression:B(e)?e.map(Ue).join(" | "):String(e),De={},_e=(e,t,r)=>Ve(e,t,{$:r,invert:!1,pipe:!1}),Ve=(e,t,r)=>{const i=r.pipe?"|>":"&",n=`${e.typeHash}${i}${t.typeHash}`;if(void 0!==De[n])return De[n];if(!r.pipe){const r=`${t.typeHash}${i}${e.typeHash}`;if(void 0!==De[r]){const e=De[r],t=e instanceof Fe?e.invert():e;return De[n]=t,t}}if(e.equals(t))return e;let s;if(r.pipe&&e.hasKind("morph"))s=r.invert?We(t,e,r):Je(e,t,r);else if(r.pipe&&t.hasKind("morph"))s=r.invert?Je(t,e,r):We(e,t,r);else{const i=e.impl.intersections[t.kind]??t.impl.intersections[e.kind];s=void 0===i?null:(e.precedence<t.precedence?e.kind:t.kind)===e.kind?i(e,t,r):i(t,e,{...r,invert:!r.invert})}return ve(s)&&(e.equals(s)?s=e:t.equals(s)&&(s=t)),De[n]=s,s},Je=(e,t,r)=>{const i=[...e.morphs];if(e.validatedOut){const n=Ve(e.validatedOut,t,r);if(n instanceof Fe)return n;i[i.length-1]=n}else i.push(t);return r.$.node("morph",{morphs:i,in:e.in})},We=(e,t,r)=>{const i=Ve(e,t.in,r);return i instanceof Fe?i:r.$.node("morph",{morphs:t.morphs,in:i})};class Ze extends Pe{[ye]="constraint";impliedSiblings;intersect(e){return _e(this,e,this.$)}}class He extends Ze{traverseApply=(e,t)=>{this.traverseAllows(e,t)||t.error(this.errorContext)};compile(e){"Allows"===e.traversalKind?e.return(this.compiledCondition):e.if(this.compiledNegation,()=>e.line(`${e.ctx}.error(${this.compiledErrorContext})`))}get errorContext(){return{code:this.kind,description:this.description,...this.inner}}get compiledErrorContext(){return Le(this.errorContext)}}const Ge=e=>(t,r)=>{if(B(t)){if(0===t.length)return;return t.map(t=>r.$.node(e,t)).sort((e,t)=>e.innerHash<t.innerHash?-1:1)}const i=r.$.node(e,t);return i.hasOpenIntersection()?[i]:i},Xe=e=>{const t=e.r.shift();if(!t){let t=0===e.l.length&&"structure"===e.kind?e.ctx.$.keywords.unknown.raw:e.ctx.$.node(e.kind,Object.assign(e.baseInner,Ye(e.l)),{prereduced:!0});for(const r of e.roots){if(t instanceof Fe)return t;t=Ve(r,t,e.ctx)}return t}let r=!1;for(let i=0;i<e.l.length;i++){const n=Ve(e.l[i],t,e.ctx);if(null!==n){if(n instanceof Fe)return n;if(r){if(!e.l.includes(n))return a(`Unexpectedly encountered multiple distinct intersection results for refinement ${n}`)}else{if(n.isRoot())return e.roots.push(n),e.l.splice(i),Xe(e);e.l[i]=n,r=!0}}}return r||e.l.push(t),"intersection"===e.kind&&t.impliedSiblings?.forEach(t=>s(e.r,t)),Xe(e)},Qe=e=>Object.entries(e).flatMap(([e,t])=>e in je?t:[]).sort((e,t)=>e.precedence<t.precedence?-1:e.precedence>t.precedence?1:e.innerHash<t.innerHash?-1:1),Ye=e=>{const t={};for(const r of e)if(r.hasOpenIntersection())t[r.kind]=n(t[r.kind],r);else{if(t[r.kind])return a(`Unexpected intersection of closed refinements of kind ${r.kind}`);t[r.kind]=r}return t},et=Ce({kind:"predicate",hasAssociatedError:!0,collapsibleKey:"predicate",keys:{predicate:{}},normalize:e=>"function"==typeof e?{predicate:e}:e,defaults:{description:e=>`valid according to ${e.predicate.name||"an anonymous predicate"}`},intersectionIsOpen:!0,intersections:{predicate:()=>null}}),tt=Ce({kind:"divisor",collapsibleKey:"rule",keys:{rule:{}},normalize:e=>"number"==typeof e?{rule:e}:e,hasAssociatedError:!0,defaults:{description:e=>1===e.rule?"an integer":`a multiple of ${e.rule}`},intersections:{divisor:(e,t,r)=>r.$.node("divisor",{rule:Math.abs(e.rule*t.rule/rt(e.rule,t.rule))})}}),rt=(e,t)=>{let r,i=e,n=t;for(;0!==n;)r=n,n=i%n,i=r;return i};class it extends He{boundOperandKind=lt[this.kind];compiledActual="value"===this.boundOperandKind?"data":"length"===this.boundOperandKind?"data.length":"data.valueOf()";comparator=ct(this.kind,this.exclusive);numericLimit=this.rule.valueOf();expression=`${this.comparator}${this.rule}`;compiledCondition=`${this.compiledActual} ${this.comparator} ${this.numericLimit}`;compiledNegation=`${this.compiledActual} ${nt[this.comparator]} ${this.numericLimit}`;stringLimit="date"===this.boundOperandKind?ut(this.numericLimit):`${this.numericLimit}`;limitKind="<"===this.comparator[0]?"upper":"lower";isStricterThan(e){return("upper"===this.limitKind?this.numericLimit<e.numericLimit:this.numericLimit>e.numericLimit)||this.numericLimit===e.numericLimit&&!0===this.exclusive&&!e.exclusive}overlapsRange(e){return!this.isStricterThan(e)&&(this.numericLimit!==e.numericLimit||!this.exclusive&&!e.exclusive)}overlapIsUnit(e){return this.numericLimit===e.numericLimit&&!this.exclusive&&!e.exclusive}}const nt={"<":">=","<=":">",">":"<=",">=":"<"},st={min:"max",minLength:"maxLength",after:"before"},ot={parse:e=>e||void 0},at=e=>"string"==typeof e||"number"==typeof e?new Date(e):e,lt={min:"value",max:"value",minLength:"length",maxLength:"length",after:"date",before:"date"},ct=(e,t)=>`${f(e,st)?">":"<"}${t?"":"="}`,ut=e=>"string"==typeof e?e:new Date(e).toLocaleString(),ht=Ce({kind:"after",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{parse:at,serialize:e=>e.toISOString()},exclusive:ot},normalize:e=>"number"==typeof e||"string"==typeof e||e instanceof Date?{rule:e}:e,defaults:{description:e=>e.exclusive?`after ${e.stringLimit}`:`${e.stringLimit} or later`,actual:e=>e.toLocaleString()},intersections:{after:(e,t)=>e.isStricterThan(t)?e:t}}),dt=Ce({kind:"before",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{parse:at,serialize:e=>e.toISOString()},exclusive:ot},normalize:e=>"number"==typeof e||"string"==typeof e||e instanceof Date?{rule:e}:e,defaults:{description:e=>e.exclusive?`before ${e.stringLimit}`:`${e.stringLimit} or earlier`,actual:e=>e.toLocaleString()},intersections:{before:(e,t)=>e.isStricterThan(t)?e:t,after:(e,t,r)=>e.overlapsRange(t)?e.overlapIsUnit(t)?r.$.node("unit",{unit:e.rule}):null:Fe.from("range",e,t)}}),pt=Ce({kind:"exactLength",collapsibleKey:"rule",keys:{rule:{}},normalize:e=>"number"==typeof e?{rule:e}:e,hasAssociatedError:!0,defaults:{description:e=>`exactly length ${e.rule}`},intersections:{exactLength:(e,t,r)=>new Fe({'["length"]':{unit:{l:r.$.node("unit",{unit:e.rule}),r:r.$.node("unit",{unit:t.rule})}}}),minLength:(e,t)=>(t.exclusive?e.rule>t.rule:e.rule>=t.rule)?e:Fe.from("range",e,t),maxLength:(e,t)=>(t.exclusive?e.rule<t.rule:e.rule<=t.rule)?e:Fe.from("range",e,t)}}),ft=Ce({kind:"max",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{},exclusive:ot},normalize:e=>"number"==typeof e?{rule:e}:e,defaults:{description:e=>`${e.exclusive?"less than":"at most"} ${e.rule}`},intersections:{max:(e,t)=>e.isStricterThan(t)?e:t,min:(e,t,r)=>e.overlapsRange(t)?e.overlapIsUnit(t)?r.$.node("unit",{unit:e.rule}):null:Fe.from("range",e,t)}}),mt=Ce({kind:"maxLength",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{},exclusive:ot},normalize:e=>"number"==typeof e?{rule:e}:e,defaults:{description:e=>e.exclusive?`less than length ${e.rule}`:`at most length ${e.rule}`,actual:e=>`${e.length}`},intersections:{maxLength:(e,t)=>e.isStricterThan(t)?e:t,minLength:(e,t,r)=>e.overlapsRange(t)?e.overlapIsUnit(t)?r.$.node("exactLength",{rule:e.rule}):null:Fe.from("range",e,t)}}),gt={min:Ce({kind:"min",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{},exclusive:ot},normalize:e=>"number"==typeof e?{rule:e}:e,defaults:{description:e=>`${e.exclusive?"more than":"at least"} ${e.rule}`},intersections:{min:(e,t)=>e.isStricterThan(t)?e:t}}),max:ft,minLength:Ce({kind:"minLength",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{},exclusive:ot},normalize:e=>"number"==typeof e?{rule:e}:e,defaults:{description:e=>e.exclusive?0===e.rule?"non-empty":`more than length ${e.rule}`:1===e.rule?"non-empty":`at least length ${e.rule}`,actual:e=>`${e.length}`},intersections:{minLength:(e,t)=>e.isStricterThan(t)?e:t}}),maxLength:mt,exactLength:pt,after:ht,before:dt},yt={min:class extends it{impliedBasis=this.$.keywords.number.raw;traverseAllows=this.exclusive?e=>e>this.rule:e=>e>=this.rule},max:class extends it{impliedBasis=this.$.keywords.number.raw;traverseAllows=this.exclusive?e=>e<this.rule:e=>e<=this.rule},minLength:class extends it{impliedBasis=this.$.keywords.lengthBoundable.raw;traverseAllows=this.exclusive?e=>e.length>this.rule:e=>e.length>=this.rule},maxLength:class extends it{impliedBasis=this.$.keywords.lengthBoundable.raw;traverseAllows=this.exclusive?e=>e.length<this.rule:e=>e.length<=this.rule},exactLength:class extends He{traverseAllows=e=>e.length===this.rule;compiledCondition=`data.length === ${this.rule}`;compiledNegation=`data.length !== ${this.rule}`;impliedBasis=this.$.keywords.lengthBoundable.raw;expression=`{ length: ${this.rule} }`},after:class extends it{impliedBasis=this.$.keywords.Date.raw;traverseAllows=this.exclusive?e=>e>this.rule:e=>e>=this.rule},before:class extends it{traverseAllows=this.exclusive?e=>e<this.rule:e=>e<=this.rule;impliedBasis=this.$.keywords.Date.raw}},bt=Ce({kind:"regex",collapsibleKey:"rule",keys:{rule:{},flags:{}},normalize:e=>"string"==typeof e?{rule:e}:e instanceof RegExp?e.flags?{rule:e.source,flags:e.flags}:{rule:e.source}:e,hasAssociatedError:!0,intersectionIsOpen:!0,defaults:{description:e=>`matched by ${e.rule}`},intersections:{regex:()=>null}});class vt extends Pe{branches=this.hasKind("union")?this.inner.branches:[this];[ye]="root";get raw(){return this}_keyof;keyof(){return this._keyof||(this._keyof=this.rawKeyOf(),0===this._keyof.branches.length&&u(`keyof ${this.expression} results in an unsatisfiable type`)),this._keyof}intersect(e){const t=this.$.parseRoot(e);return _e(this,t,this.$)}and(e){const t=this.intersect(e);return t instanceof Fe?t.throw():t}or(e){const t=this.$.parseRoot(e),r=[...this.branches,...t.branches];return this.$.schema(r)}assert(e){const t=this.traverse(e);return t instanceof Ne?t.throw():t}extract(e){const t=this.$.parseRoot(e);return this.$.schema(this.branches.filter(e=>e.extends(t)))}exclude(e){const t=this.$.parseRoot(e);return this.$.schema(this.branches.filter(e=>!e.extends(t)))}array(){return this.$.schema({proto:Array,sequence:this},{prereduced:!0})}extends(e){const t=this.intersect(e);return!(t instanceof Fe)&&this.equals(t)}subsumes(e){return e.extends(this)}configure(e){return this.configureShallowDescendants(e)}describe(e){return this.configure(e)}create(e){return this.assert(e)}pipe(...e){return e.reduce((e,t)=>e.pipeOnce(t),this)}pipeOnce(e){if(be(e,"root"))return Ve(this,e,{$:this.$,invert:!1,pipe:!0});if(this.hasKind("union")){const t=this.branches.map(t=>t.pipe(e));return this.$.node("union",{...this.inner,branches:t})}return this.hasKind("morph")?this.$.node("morph",{...this.inner,morphs:[...this.morphs,e]}):this.$.node("morph",{in:this,morphs:[e]})}narrow(e){return this.constrain("predicate",e)}constrain(e,t){const r=this.$.node(e,t);return r.impliedBasis&&!this.extends(r.impliedBasis)?((...e)=>u(((e,t,r)=>{return`${i=e,i[0].toUpperCase()+i.slice(1)} operand must be ${t.description} (was ${r.exclude(t).description})`;var i})(...e)))(e,r.impliedBasis,this):this.and(this.$.node("intersection",{[e]:r}))}onUndeclaredKey(e){return this.transform((t,r)=>"structure"===t?"ignore"===e?$(r,{undeclared:1}):{...r,undeclared:e}:r,{shouldTransform:e=>!i(xe,e.kind)})}}const $t=(e,t)=>h(Re(e),(e,r)=>[r,t]);let xt=(()=>{let e,t=vt,r=[];return class extends t{static{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(t[Symbol.metadata]??null):void 0;e=[O],function(e,t,r,i,n,s){function o(e){if(void 0!==e&&"function"!=typeof e)throw new TypeError("Function expected");return e}for(var a,l=i.kind,c="getter"===l?"get":"setter"===l?"set":"value",u=e?i.static?e:e.prototype:null,h=u?Object.getOwnPropertyDescriptor(u,i.name):{},d=!1,p=r.length-1;p>=0;p--){var f={};for(var m in i)f[m]="access"===m?{}:i[m];for(var m in i.access)f.access[m]=i.access[m];f.addInitializer=function(e){if(d)throw new TypeError("Cannot add initializers after decoration has completed");s.push(o(e||null))};var g=(0,r[p])("accessor"===l?{get:h.get,set:h.set}:h[c],f);if("accessor"===l){if(void 0===g)continue;if(null===g||"object"!=typeof g)throw new TypeError("Object expected");(a=o(g.get))&&(h.get=a),(a=o(g.set))&&(h.set=a),(a=o(g.init))&&null.unshift(a)}else(a=o(g))&&("field"===l?null.unshift(a):h[c]=a)}u&&Object.defineProperty(u,i.name,h),d=!0}(this,0,e,{kind:"getter",name:"resolution",static:!1,private:!1,access:{has:e=>"resolution"in e,get:e=>e.resolution},metadata:i},0,r),i&&Object.defineProperty(this,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:i})}expression=(function(e,t,r){for(var i=arguments.length>2,n=0;n<t.length;n++)r=i?t[n].call(e,r):t[n].call(e)}(this,r),this.alias);get resolution(){return this.resolve?.()??this.$.resolveRoot(this.alias)}rawKeyOf(){return this.resolution.keyof()}traverseAllows=(e,t)=>{const r=t.seen[this.id];return!!r?.includes(e)||(t.seen[this.id]=n(r,e),this.resolution.traverseAllows(e,t))};traverseApply=(e,t)=>{const r=t.seen[this.id];r?.includes(e)||(t.seen[this.id]=n(r,e),this.resolution.traverseApply(e,t))};compile(e){e.if(`ctx.seen.${this.id}?.includes(data)`,()=>e.return(!0)),e.line(`ctx.seen.${this.id} ??= []`).line(`ctx.seen.${this.id}.push(data)`),e.return(e.invoke(this.resolution))}}})();const kt=e=>"string"==typeof e?{alias:e.slice(1)}:e,wt=Ce({kind:"alias",hasAssociatedError:!1,collapsibleKey:"alias",keys:{alias:{serialize:e=>`$${e}`},resolve:{}},normalize:kt,defaults:{description:e=>e.alias},intersections:{alias:(e,t,r)=>r.$.lazilyResolve(()=>At(Ve(e.resolution,t.resolution,r),r.$),`${e.alias}${r.pipe?"|>":"&"}${t.alias}`),...$t("alias",(e,t,r)=>r.$.lazilyResolve(()=>At(Ve(e.resolution,t,r),r.$),`${e.alias}${r.pipe?"|>":"&"}${t.alias}`))}}),At=(e,t)=>e instanceof Fe?t.keywords.never.raw:e;class Ot extends vt{rawKeyOf(){return this.$.units(this.literalKeys)}traverseApply=(e,t)=>{this.traverseAllows(e,t)||t.error(this.errorContext)};get errorContext(){return{code:this.kind,description:this.description,...this.inner}}get compiledErrorContext(){return Le(this.errorContext)}compile(e){"Allows"===e.traversalKind?e.return(this.compiledCondition):e.if(this.compiledNegation,()=>e.line(`${e.ctx}.error(${this.compiledErrorContext})`))}}const jt=Ce({kind:"domain",hasAssociatedError:!0,collapsibleKey:"domain",keys:{domain:{}},normalize:e=>"string"==typeof e?{domain:e}:e,defaults:{description:e=>z[e.domain],actual:e=>"boolean"==typeof e?`${e}`:R(e)},intersections:{domain:(e,t)=>Fe.from("domain",e,t)}}),qt={description:1},Et=(e,t,r)=>{if(be(e,"root")&&e.hasKind("intersection"))return Et(e.inner,t,r);if(be(t,"root")&&t.hasKind("intersection"))return Et(e,t.inner,r);const i=x(e)?v(t,qt)[0]:{},n=e.proto??e.domain,s=t.proto??t.domain,o=n?s?Ve(n,s,r):n:s;return o instanceof Fe?o:(o&&(i[o.kind]=o),Xe({kind:"intersection",baseInner:i,l:Qe(e),r:Qe(t),roots:[],ctx:r}))},Kt=Ce({kind:"intersection",hasAssociatedError:!0,normalize:e=>{if(ve(e))return e;const{structure:t,...r}=e,i=!!t,n=t??{},s=h(r,(e,t)=>f(e,qe)?(i&&u(`Flattened structure key ${e} cannot be specified alongside a root 'structure' key.`),n[e]=t,[]):[e,t]);return x(n)||(s.structure=n),s},finalizeJson:({structure:e,...t})=>S(e,"object")?{...e,...t}:t,keys:{domain:{child:!0,parse:(e,t)=>t.$.node("domain",e)},proto:{child:!0,parse:(e,t)=>t.$.node("proto",e)},structure:{child:!0,parse:(e,t)=>t.$.node("structure",e),serialize:e=>{if(!e.sequence?.minLength)return e.collapsibleJson;const{sequence:t,...r}=e.collapsibleJson,{minVariadicLength:i,...n}=t;return{...r,sequence:n.variadic&&1===Object.keys(n).length?n.variadic:n}}},divisor:{child:!0,parse:Ge("divisor")},max:{child:!0,parse:Ge("max")},min:{child:!0,parse:Ge("min")},maxLength:{child:!0,parse:Ge("maxLength")},minLength:{child:!0,parse:Ge("minLength")},exactLength:{child:!0,parse:Ge("exactLength")},before:{child:!0,parse:Ge("before")},after:{child:!0,parse:Ge("after")},regex:{child:!0,parse:Ge("regex")},predicate:{child:!0,parse:Ge("predicate")}},reduce:(e,t)=>Et({},e,{$:t,invert:!1,pipe:!1}),defaults:{description:e=>0===e.children.length?"unknown":e.structure?.description??e.children.map(e=>e.description).join(" and "),expected:e=>` • ${e.errors.map(e=>e.expected).join("\n • ")}`,problem:e=>`must be...\n${e.expected}`},intersections:{intersection:(e,t,r)=>Et(e,t,r),...$t("intersection",(e,t,r)=>{if(0===e.children.length)return t;const i=e.basis?Ve(e.basis,t,r):t;return i instanceof Fe?i:e?.basis?.equals(i)?e:e.$.node("intersection",Object.assign($(e.inner,qt),{[i.kind]:i}),{prereduced:!0})})}}),St=["intersection","unit","domain","proto"],Rt=Ce({kind:"morph",hasAssociatedError:!1,keys:{in:{child:!0,parse:(e,t)=>t.$.node(St,e)},morphs:{parse:e=>Array.isArray(e)?e:[e],serialize:e=>e.map(e=>be(e,"root")?e.json:W(e))}},normalize:e=>e,defaults:{description:e=>`a morph from ${e.in.description} to ${e.out?.description??"unknown"}`},intersections:{morph:(e,t,r)=>{if(e.morphs.some((e,r)=>e!==t.morphs[r]))return u("Invalid intersection of morphs");const i=Ve(e.in,t.in,r);return i instanceof Fe?i:r.$.schema(i.branches.map(t=>r.$.node("morph",{morphs:e.morphs,in:t})))},...$t("morph",(e,t,r)=>{const i=Ve(e.in,t,r);return i instanceof Fe?i:"union"===i.kind?r.$.node("union",i.branches.map(t=>({...e.inner,in:t}))):r.$.node("morph",{...e.inner,in:i})})}}),zt=Ce({kind:"proto",hasAssociatedError:!0,collapsibleKey:"proto",keys:{proto:{serialize:e=>M(e)??ze(e)}},normalize:e=>"string"==typeof e?{proto:L[e]}:"function"==typeof e?{proto:e}:"string"==typeof e.proto?{...e,proto:L[e.proto]}:e,defaults:{description:e=>e.builtinName?N[e.builtinName]:`an instance of ${e.proto.name}`,actual:e=>I(e)},intersections:{proto:(e,t)=>T(e.proto,t.proto)?e:T(t.proto,e.proto)?t:Fe.from("proto",e,t),domain:(e,t,r)=>"object"===t.domain?e:Fe.from("domain",r.$.keywords.object.raw,t)}}),Lt=[...Re("union"),"alias"],Ct=Ce({kind:"union",hasAssociatedError:!0,collapsibleKey:"branches",keys:{ordered:{},branches:{child:!0,parse:(e,t)=>{const r=e.map(e=>t.$.node(Lt,e));return t.schema.ordered||r.sort((e,t)=>e.innerHash<t.innerHash?-1:1),r}}},normalize:e=>B(e)?{branches:e}:e,reduce:(e,t)=>{const r=Pt(e);return 1===r.length?r[0]:r.length!==e.branches.length?t.node("union",{...e,branches:r},{prereduced:!0}):void 0},defaults:{description:e=>Nt(e.branches.map(e=>e.description)),expected:e=>{const t=e.errors.reduce((e,t)=>{const r=t.propString;return e[r]??=[],e[r].push(t),e},{}),r=Object.entries(t).map(([e,t])=>{const r=[];t.forEach(e=>s(r,e.expected));const i=Nt(r),n=t.every(e=>e.actual===t[0].actual)?t[0].actual:pe(t[0].data);return`${e&&`${e} `}must be ${i}${n&&` (was ${n})`}`});return Nt(r)},problem:e=>e.expected,message:e=>e.problem},intersections:{union:(e,t,r)=>{if(e.isNever!==t.isNever)return Fe.from("presence",e,t);let i;if(e.ordered){if(t.ordered)return Fe.from("indiscriminableMorphs",e,t);i=Mt(t.branches,e.branches,r),i instanceof Fe&&i.invert()}else i=Mt(e.branches,t.branches,r);return i instanceof Fe?i:r.$.schema(e.ordered||t.ordered?{branches:i,ordered:!0}:{branches:i})},...$t("union",(e,t,r)=>{const i=Mt(e.branches,[t],r);return i instanceof Fe?i:1===i.length?i[0]:r.$.schema(e.ordered?{branches:i,ordered:!0}:{branches:i})})}});let It=(()=>{let e,t=vt,r=[];return class extends t{static{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(t[Symbol.metadata]??null):void 0;e=[O],function(e,t,r,i,n,s){function o(e){if(void 0!==e&&"function"!=typeof e)throw new TypeError("Function expected");return e}for(var a,l=i.kind,c="getter"===l?"get":"setter"===l?"set":"value",u=e?i.static?e:e.prototype:null,h=u?Object.getOwnPropertyDescriptor(u,i.name):{},d=!1,p=r.length-1;p>=0;p--){var f={};for(var m in i)f[m]="access"===m?{}:i[m];for(var m in i.access)f.access[m]=i.access[m];f.addInitializer=function(e){if(d)throw new TypeError("Cannot add initializers after decoration has completed");s.push(o(e||null))};var g=(0,r[p])("accessor"===l?{get:h.get,set:h.set}:h[c],f);if("accessor"===l){if(void 0===g)continue;if(null===g||"object"!=typeof g)throw new TypeError("Object expected");(a=o(g.get))&&(h.get=a),(a=o(g.set))&&(h.set=a),(a=o(g.init))&&null.unshift(a)}else(a=o(g))&&("field"===l?null.unshift(a):h[c]=a)}u&&Object.defineProperty(u,i.name,h),d=!0}(this,0,e,{kind:"method",name:"discriminate",static:!1,private:!1,access:{has:e=>"discriminate"in e,get:e=>e.discriminate},metadata:i},0,r),i&&Object.defineProperty(this,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:i})}isNever=(function(e,t,r){for(var i=arguments.length>2,n=0;n<t.length;n++)r=i?t[n].call(e,r):t[n].call(e)}(this,r),0===this.branches.length);isBoolean=2===this.branches.length&&this.branches[0].hasUnit(!1)&&this.branches[1].hasUnit(!0);unitBranches=this.branches.filter(e=>e.hasKind("unit"));discriminant=this.discriminate();discriminantJson=this.discriminant?Bt(this.discriminant):null;expression=this.isNever?"never":this.isBoolean?"boolean":this.branches.map(e=>e.nestableExpression).join(" | ");traverseAllows=(e,t)=>this.branches.some(r=>r.traverseAllows(e,t));traverseApply=(e,t)=>{const r=[];for(let i=0;i<this.branches.length;i++){if(t.pushBranch(),this.branches[i].traverseApply(e,t),!t.hasError())return t.queuedMorphs.push(...t.popBranch().queuedMorphs);r.push(t.popBranch().error)}t.error({code:"union",errors:r})};compile(e){if(!this.discriminant||this.unitBranches.length===this.branches.length&&2===this.branches.length)return this.compileIndiscriminable(e);const t=this.discriminant.path.reduce((e,t)=>e+Q(t,!0),"domain"===this.discriminant.kind?"typeof data":"data"),r=this.discriminant.cases,i=Object.keys(r);if(e.block(`switch(${t})`,()=>{for(const t in r){const i=r[t];e.line(`${"default"===t?"default":`case ${t}`}: return ${!0===i?i:e.invoke(i)}`)}return e}),"Allows"===e.traversalKind)return void e.return(!1);const n=Nt("domain"===this.discriminant.kind?i.map(e=>z[e.slice(1,-1)]):i);e.line(`ctx.error({\n\texpected: ${JSON.stringify(n)},\n\tactual: ${t},\n\trelativePath: ${JSON.stringify(this.discriminant.path)}\n})`)}compileIndiscriminable(e){"Apply"===e.traversalKind?(e.const("errors","[]"),this.branches.forEach(t=>e.line("ctx.pushBranch()").line(e.invoke(t)).if("!ctx.hasError()",()=>e.return("ctx.queuedMorphs.push(...ctx.popBranch().queuedMorphs)")).line("errors.push(ctx.popBranch().error)")),e.line('ctx.error({ code: "union", errors })')):(this.branches.forEach(t=>e.if(`${e.invoke(t)}`,()=>e.return(!0))),e.return(!1))}rawKeyOf(){return this.branches.reduce((e,t)=>e.and(t.rawKeyOf()),this.$.keywords.unknown.raw)}get nestableExpression(){return this.isBoolean?"boolean":super.nestableExpression}discriminate(){if(this.branches.length<2)return null;if(this.unitBranches.length===this.branches.length)return{path:[],kind:"unit",cases:h(this.unitBranches,(e,t)=>[`${t.serializedValue}`,!0])};const e={};for(let t=0;t<this.branches.length-1;t++){const r=this.branches[t];for(let i=t+1;i<this.branches.length;i++){const t=this.branches[i],n=_e(r,t,r.$);if(n instanceof Fe)for(const{path:i,kind:s,disjoint:o}of n.flat){if(!f(s,Ft))continue;const n=`${i}${s}`;let l,c;if("domain"===s)l=`"${o.l.domain}"`,c=`"${o.r.domain}"`;else{if("unit"!==s)return a(`Unexpected attempt to discriminate disjoint kind '${s}'`);l=o.l.serializedValue,c=o.r.serializedValue}if(!e[n]){e[n]={[l]:[r],[c]:[t]};continue}const u=e[n];f(l,u)?u[l].includes(r)||u[l].push(r):u[l]=[r],f(c,u)?u[c].includes(t)||u[c].push(t):u[c]=[t]}}}const t=d(e).sort((e,t)=>Object.keys(e[1]).length-Object.keys(t[1]).length).at(-1);if(!t)return null;const[r,i]=t,[n,s]=Tt(r);let o=[...this.branches];const l=h(i,(e,t)=>{const r=[];o=o.filter(e=>!t.includes(e));for(const i of t){const t=Ut(s,n,i);if(null===t)return[e,!0];r.push(t)}const i=1===r.length?r[0]:this.$.node("union",r);return Object.assign(this.referencesById,i.referencesById),[e,i]});return o.length&&(l.default=this.$.node("union",o,{prereduced:!0}),Object.assign(this.referencesById,l.default.referencesById)),{kind:s,path:n,cases:l}}}})();const Bt=e=>({kind:e.kind,path:e.path,cases:h(e.cases,(e,t)=>[e,!0===t?t:t.hasKind("union")&&t.discriminantJson?t.discriminantJson:t.json])}),Nt=e=>{if(0===e.length)return"never";if(1===e.length)return e[0];if(2===e.length&&"false"===e[0]&&"true"===e[1]||"true"===e[0]&&"false"===e[1])return"boolean";let t="";for(let r=0;r<e.length-1;r++)t+=e[r],r<e.length-2&&(t+=", ");return t+=` or ${e[e.length-1]}`,t},Mt=(e,t,r)=>{const i=t.map(()=>[]);for(let n=0;n<e.length;n++){let s={};for(let o=0;o<t.length;o++){if(null===i[o])continue;if(e[n].equals(t[o])){i[o]=null,s={};break}const a=Ve(e[n],t[o],r);if(!(a instanceof Fe)){if(a.equals(e[n])){i[o].push(e[n]),s={};break}a.equals(t[o])?i[o]=null:s[o]=a}}for(const e in s)i[e][n]=s[e]}const n=i.flatMap((e,r)=>e?.flatMap(e=>e.branches)??t[r]);return 0===n.length?Fe.from("union",e,t):n},Pt=({branches:e,ordered:t})=>{if(e.length<2)return e;const r=e.map(()=>!0);for(let i=0;i<e.length;i++)for(let n=i+1;n<e.length&&r[i]&&r[n];n++){if(e[i].equals(e[n])){r[n]=!1;continue}const s=_e(e[i],e[n],e[0].$);s instanceof Fe||(s.equals(e[i])?t||(r[i]=!1):s.equals(e[n])&&(r[n]=!1))}return e.filter((e,t)=>r[t])},Ft={domain:1,unit:1},Tt=e=>{const t=e.lastIndexOf("]");return[JSON.parse(e.slice(0,t+1)),e.slice(t+1)]},Ut=(e,t,r)=>r.transform((r,i,n)=>"domain"===r&&"object"===i.domain&&t.length>n.path.length||(e===r||"domain"===r&&n.path.length===t.length)&&n.path.length===t.length&&n.path.every((e,r)=>e===t[r])?null:i,{shouldTransform:e=>0!==e.children.length||"domain"===e.kind||"unit"===e.kind}),Dt=Ce({kind:"unit",hasAssociatedError:!0,keys:{unit:{preserveUndefined:!0,serialize:e=>e instanceof Date?e.toISOString():ze(e)}},normalize:e=>e,defaults:{description:e=>pe(e.unit),problem:({expected:e,actual:t})=>e===t?`must be reference equal to ${e} (serialized to the same value)`:`must be ${e} (was ${t})`},intersections:{unit:(e,t)=>Fe.from("unit",e,t),...$t("unit",(e,t)=>t.allows(e.unit)?e:Fe.from("assignability",e,t.hasKind("intersection")?t.children.find(t=>!t.allows(e.unit)):t))}}),_t=(e,t,r)=>{if(e instanceof Date){const e=`data instanceof Date && data.toISOString() === ${t}`;return r?`!(${e})`:e}return`data ${r?"!":"="}== ${t}`},Vt=Ce({kind:"index",hasAssociatedError:!1,intersectionIsOpen:!0,keys:{signature:{child:!0,parse:(e,t)=>{const r=t.$.schema(e);if(!r.extends(t.$.keywords.propertyKey))return u(Wt(r.expression));const i=r.branches.filter(e=>e.hasKind("unit"));return i.length?u(Jt(i.map(e=>pe(e.unit)))):r}},value:{child:!0,parse:(e,t)=>t.$.schema(e)}},normalize:e=>e,defaults:{description:e=>`[${e.signature.expression}]: ${e.value.description}`},intersections:{index:(e,t,r)=>{if(e.signature.equals(t.signature)){const i=Ve(e.value,t.value,r);return r.$.node("index",{signature:e.signature,value:i instanceof Fe?r.$.keywords.never.raw:i})}return e.signature.extends(t.signature)&&e.value.subsumes(t.value)?t:t.signature.extends(e.signature)&&t.value.subsumes(e.value)?e:null}}}),Jt=e=>`Index keys ${e.join(", ")} should be specified as named props.`,Wt=e=>`Indexed key definition '${e}' must be a string, number or symbol`,Zt=(e,t,r)=>{if(e.key!==t.key)return null;const i=e.key;let n=Ve(e.value,t.value,r);const s=e.required||t.required?"required":"optional";if(n instanceof Fe){if("optional"!==s)return n.withPrefixKey(e.compiledKey);n=r.$.keywords.never.raw}if("required"===s)return r.$.node("required",{key:i,value:n});const o=e.hasDefault()?t.hasDefault()?e.default===t.default?e.default:u(`Invalid intersection of default values ${pe(e.default)} & ${pe(t.default)}`):e.default:t.hasDefault()?t.default:w;return r.$.node("optional",{key:i,value:n,default:o})};class Ht extends Ze{required="required"===this.kind;impliedBasis=this.$.keywords.object.raw;serializedKey=H(this.key);compiledKey="string"==typeof this.key?this.key:this.serializedKey;_transform(e,t){t.path.push(this.key);const r=super._transform(e,t);return t.path.pop(),r}defaultValueMorphs=[e=>(e[this.key]=this.default,e)];defaultValueMorphsReference=W(this.defaultValueMorphs);hasDefault(){return"default"in this}traverseAllows=(e,t)=>{if(this.key in e){t?.path.push(this.key);const r=this.value.traverseAllows(e[this.key],t);return t?.path.pop(),r}return!this.required};traverseApply=(e,t)=>{this.key in e?(t.path.push(this.key),this.value.traverseApply(e[this.key],t),t.path.pop()):this.hasKind("required")?t.error(this.errorContext):this.hasKind("optional")&&this.hasDefault()&&t.queueMorphs(this.defaultValueMorphs)};compile(e){e.if(`${this.serializedKey} in data`,()=>e.traverseKey(this.serializedKey,`data${e.prop(this.key)}`,this.value)),this.hasKind("required")?e.else(()=>"Apply"===e.traversalKind?e.line(`ctx.error(${this.compiledErrorContext})`):e.return(!1)):"Apply"===e.traversalKind&&"default"in this&&e.else(()=>e.line(`ctx.queueMorphs(${this.defaultValueMorphsReference})`)),"Allows"===e.traversalKind&&e.return(!0)}}const Gt=Ce({kind:"optional",hasAssociatedError:!1,intersectionIsOpen:!0,keys:{key:{},value:{child:!0,parse:(e,t)=>t.$.schema(e)},default:{preserveUndefined:!0}},normalize:e=>e,defaults:{description:e=>`${e.compiledKey}?: ${e.value.description}`},intersections:{optional:Zt}}),Xt=Ce({kind:"required",hasAssociatedError:!0,intersectionIsOpen:!0,keys:{key:{},value:{child:!0,parse:(e,t)=>t.$.schema(e)}},normalize:e=>e,defaults:{description:e=>`${e.compiledKey}: ${e.value.description}`,expected:e=>e.missingValueDescription,actual:()=>"missing"},intersections:{required:Zt,optional:Zt}}),Qt={child:!0,parse:(e,t)=>0===e.length?void 0:e.map(e=>t.$.schema(e))},Yt=Ce({kind:"sequence",hasAssociatedError:!1,collapsibleKey:"variadic",keys:{prefix:Qt,optionals:Qt,variadic:{child:!0,parse:(e,t)=>t.$.schema(e,t)},minVariadicLength:{parse:e=>0===e?void 0:e},postfix:Qt},normalize:e=>{if("string"==typeof e)return{variadic:e};if("variadic"in e||"prefix"in e||"optionals"in e||"postfix"in e||"minVariadicLength"in e){if(e.postfix?.length){if(!e.variadic)return u(rr);if(e.optionals?.length)return u(tr)}return e.minVariadicLength&&!e.variadic?u("minVariadicLength may not be specified without a variadic element"):e}return{variadic:e}},reduce:(e,t)=>{let r=e.minVariadicLength??0;const i=e.prefix?.slice()??[],n=e.optionals?.slice()??[],s=e.postfix?.slice()??[];if(e.variadic){for(;n.at(-1)?.equals(e.variadic);)n.pop();if(0===n.length)for(;i.at(-1)?.equals(e.variadic);)i.pop(),r++;for(;s[0]?.equals(e.variadic);)s.shift(),r++}else 0===n.length&&i.push(...s.splice(0));if(r!==e.minVariadicLength||e.prefix&&e.prefix.length!==i.length)return t.node("sequence",{...e,prefix:i,postfix:s,optionals:n,minVariadicLength:r},{prereduced:!0})},defaults:{description:e=>e.isVariadicOnly?`${e.variadic.nestableExpression}[]`:`[${e.tuple.map(e=>"optionals"===e.kind?`${e.node.nestableExpression}?`:"variadic"===e.kind?`...${e.node.nestableExpression}[]`:e.node.expression).join(", ")}]`},intersections:{sequence:(e,t,r)=>{const i=ir({l:e.tuple,r:t.tuple,disjoint:new Fe({}),result:[],fixedVariants:[],ctx:r}),n=i.disjoint.isEmpty()?[i,...i.fixedVariants]:i.fixedVariants;return 0===n.length?i.disjoint:1===n.length?r.$.node("sequence",er(n[0].result)):r.$.node("union",n.map(e=>({proto:Array,sequence:er(e.result)})))}}}),er=e=>e.reduce((e,t)=>("variadic"===t.kind?e.variadic=t.node:e[t.kind]=n(e[t.kind],t.node),e),{}),tr="A postfix required element cannot follow an optional element",rr="A postfix element requires a variadic element",ir=e=>{const[t,...r]=e.l,[i,...n]=e.r;if(!t||!i)return e;const s="postfix"===r.at(-1)?.kind,o="postfix"===n.at(-1)?.kind,a="prefix"===t.kind||"prefix"===i.kind?"prefix":"optionals"===t.kind||"optionals"===i.kind?s||o?"prefix":"optionals":"postfix"===t.kind||"postfix"===i.kind?"postfix":"variadic";if("prefix"===t.kind&&"variadic"===i.kind&&o){const t=ir({...e,fixedVariants:[],r:n.map(e=>({...e,kind:"prefix"}))});t.disjoint.isEmpty()&&e.fixedVariants.push(t)}else if("prefix"===i.kind&&"variadic"===t.kind&&s){const t=ir({...e,fixedVariants:[],l:r.map(e=>({...e,kind:"prefix"}))});t.disjoint.isEmpty()&&e.fixedVariants.push(t)}const l=Ve(t.node,i.node,e.ctx);if(l instanceof Fe){if("prefix"!==a&&"postfix"!==a)return"optionals"===a?e:ir({...e,fixedVariants:[],l:r.map(e=>({...e,kind:"prefix"})),r:r.map(e=>({...e,kind:"prefix"}))});e.disjoint.add(l.withPrefixKey("prefix"===a?`${e.result.length}`:`-${r.length+1}`)),e.result=[...e.result,{kind:a,node:e.ctx.$.keywords.never.raw}]}else e.result=[...e.result,{kind:a,node:l}];const c=e.l.length,u=e.r.length;return("variadic"!==t.kind||c>=u&&("variadic"===i.kind||1===u))&&(e.l=r),("variadic"!==i.kind||u>=c&&("variadic"===t.kind||1===c))&&(e.r=n),ir(e)},nr=/(?:0|(?:[1-9]\\d*))$/,sr=W(nr);let or=(()=>{let e,t=Ze,r=[];return class extends t{static{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(t[Symbol.metadata]??null):void 0;e=[O],function(e,t,r,i,n,s){function o(e){if(void 0!==e&&"function"!=typeof e)throw new TypeError("Function expected");return e}for(var a,l=i.kind,c="getter"===l?"get":"setter"===l?"set":"value",u=e?i.static?e:e.prototype:null,h=u?Object.getOwnPropertyDescriptor(u,i.name):{},d=!1,p=r.length-1;p>=0;p--){var f={};for(var m in i)f[m]="access"===m?{}:i[m];for(var m in i.access)f.access[m]=i.access[m];f.addInitializer=function(e){if(d)throw new TypeError("Cannot add initializers after decoration has completed");s.push(o(e||null))};var g=(0,r[p])("accessor"===l?{get:h.get,set:h.set}:h[c],f);if("accessor"===l){if(void 0===g)continue;if(null===g||"object"!=typeof g)throw new TypeError("Object expected");(a=o(g.get))&&(h.get=a),(a=o(g.set))&&(h.set=a),(a=o(g.init))&&null.unshift(a)}else(a=o(g))&&("field"===l?null.unshift(a):h[c]=a)}u&&Object.defineProperty(u,i.name,h),d=!0}(this,0,e,{kind:"method",name:"keyof",static:!1,private:!1,access:{has:e=>"keyof"in e,get:e=>e.keyof},metadata:i},0,r),i&&Object.defineProperty(this,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:i})}impliedBasis=(function(e,t,r){for(var i=arguments.length>2,n=0;n<t.length;n++)r=i?t[n].call(e,r):t[n].call(e)}(this,r),this.$.keywords.object.raw);impliedSiblings=this.children.flatMap(e=>e.impliedSiblings??[]);props=this.required?this.optional?[...this.required,...this.optional]:this.required:this.optional??[];propsByKey=h(this.props,(e,t)=>[t.key,t]);propsByKeyReference=W(this.propsByKey);expression=ur(this);requiredLiteralKeys=this.required?.map(e=>e.key)??[];optionalLiteralKeys=this.optional?.map(e=>e.key)??[];literalKeys=[...this.requiredLiteralKeys,...this.optionalLiteralKeys];keyof(){let e=this.$.units(this.literalKeys).branches;return this.index?.forEach(({signature:t})=>{e=e.concat(t.branches)}),this.$.node("union",e)}exhaustive=void 0!==this.undeclared||void 0!==this.index;omit(...e){return this.$.node("structure",ar(this.inner,e))}merge(e){const t=ge(ar(this.inner,[e.keyof()]));return e.required&&(t.required=n(t.required,e.required)),e.optional&&(t.optional=n(t.optional,e.optional)),e.index&&(t.index=n(t.index,e.index)),e.sequence&&(t.sequence=e.sequence),e.undeclared?t.undeclared=e.undeclared:delete t.undeclared,this.$.node("structure",t)}traverseAllows=(e,t)=>this._traverse("Allows",e,t);traverseApply=(e,t)=>this._traverse("Apply",e,t);_traverse=(e,t,r)=>{const i=r?.currentErrorCount??0;for(let n=0;n<this.props.length;n++)if("Allows"===e){if(!this.props[n].traverseAllows(t,r))return!1}else if(this.props[n].traverseApply(t,r),r.failFast&&r.currentErrorCount>i)return!1;if(this.sequence)if("Allows"===e){if(!this.sequence.traverseAllows(t,r))return!1}else if(this.sequence.traverseApply(t,r),r.failFast&&r.currentErrorCount>i)return!1;if(!this.exhaustive)return!0;const n=Object.keys(t);n.push(...Object.getOwnPropertySymbols(t));for(let s=0;s<n.length;s++){const o=n[s];let a=!1;if(this.index)for(const n of this.index)if(n.signature.traverseAllows(o,r)){if("Allows"===e){r?.path.push(o);const e=n.value.traverseAllows(t[o],r);if(r?.path.pop(),!e)return!1}else if(r.path.push(o),n.value.traverseApply(t[o],r),r.path.pop(),r.failFast&&r.currentErrorCount>i)return!1;a=!0}if(this.undeclared&&(a||=o in this.propsByKey,a||=void 0!==this.sequence&&"string"==typeof o&&nr.test(o),!a)){if("Allows"===e)return!1;if("reject"===this.undeclared?r.error({expected:"removed",actual:null,relativePath:[o]}):r.queueMorphs([e=>(delete e[o],e)]),r.failFast)return!1}r?.path.pop()}return!0};compile(e){"Apply"===e.traversalKind&&e.initializeErrorCount(),this.props.forEach(t=>{e.check(t),"Apply"===e.traversalKind&&e.returnIfFailFast()}),this.sequence&&(e.check(this.sequence),"Apply"===e.traversalKind&&e.returnIfFailFast()),this.exhaustive&&(e.const("keys","Object.keys(data)"),e.line("keys.push(...Object.getOwnPropertySymbols(data))"),e.for("i < keys.length",()=>this.compileExhaustiveEntry(e))),"Allows"===e.traversalKind&&e.return(!0)}compileExhaustiveEntry(e){return e.const("k","keys[i]"),this.undeclared&&e.let("matched",!1),this.index?.forEach(t=>{e.if(`${e.invoke(t.signature,{arg:"k",kind:"Allows"})}`,()=>(e.traverseKey("k","data[k]",t.value),this.undeclared&&e.set("matched",!0),e))}),this.undeclared&&(0!==this.props?.length&&e.line(`matched ||= k in ${this.propsByKeyReference}`),this.sequence&&e.line(`matched ||= typeof k === "string" && ${sr}.test(k)`),e.if("!matched",()=>"Allows"===e.traversalKind?e.return(!1):"reject"===this.undeclared?e.line('ctx.error({ expected: "removed", actual: null, relativePath: [k] })').if("ctx.failFast",()=>e.return()):e.line("ctx.queueMorphs([data => { delete data[k]; return data }])"))),e}}})();const ar=(e,t)=>{const r={...e};return t.forEach(e=>{r.required&&(r.required=r.required.filter(t=>"function"==typeof e?!e.allows(t.key):e!==t.key)),r.optional&&(r.optional=r.optional.filter(t=>"function"==typeof e?!e.allows(t.key):e!==t.key)),r.index&&"function"==typeof e&&(r.index=r.index.filter(t=>!t.signature.extends(e)))}),r},lr=e=>t=>{if(t.props.length||t.index){const r=t.index?.map(String)??[];t.props.forEach(t=>r.push(t[e])),t.undeclared&&r.push(`+ (undeclared): ${t.undeclared}`);const i=`{ ${r.join(", ")} }`;return t.sequence?`${i} & ${t.sequence.description}`:i}return t.sequence?.description??"{}"},cr=lr("description"),ur=lr("expression"),hr=Ce({kind:"structure",hasAssociatedError:!1,normalize:e=>e,keys:{required:{child:!0,parse:Ge("required")},optional:{child:!0,parse:Ge("optional")},index:{child:!0,parse:Ge("index")},sequence:{child:!0,parse:Ge("sequence")},undeclared:{parse:e=>"ignore"===e?void 0:e}},defaults:{description:cr},intersections:{structure:(e,t,r)=>{const i={...e.inner},n={...t.inner};if(e.undeclared){const i=e.keyof(),s=t.requiredLiteralKeys.filter(e=>!i.allows(e));if(s.length)return Fe.from("presence",r.$.keywords.never.raw,t.propsByKey[s[0]].value).withPrefixKey(s[0]);n.optional&&(n.optional=n.optional.filter(e=>i.allows(e.key))),n.index&&(n.index=n.index.flatMap(e=>{if(e.signature.extends(i))return e;const t=_e(i,e.signature,r.$);if(t instanceof Fe)return[];const s=dr(t,e.value,r.$);return s.required&&(n.required=n.required?[...n.required,...s.required]:s.required),s.index??[]}))}if(t.undeclared){const n=t.keyof(),s=e.requiredLiteralKeys.filter(e=>!n.allows(e));if(s.length)return Fe.from("presence",e.propsByKey[s[0]].value,r.$.keywords.never.raw).withPrefixKey(s[0]);i.optional&&(i.optional=i.optional.filter(e=>n.allows(e.key))),i.index&&(i.index=i.index.flatMap(e=>{if(e.signature.extends(n))return e;const t=_e(n,e.signature,r.$);if(t instanceof Fe)return[];const s=dr(t,e.value,r.$);return s.required&&(i.required=i.required?[...i.required,...s.required]:s.required),s.index??[]}))}const s={};return(e.undeclared||t.undeclared)&&(s.undeclared="reject"===e.undeclared||"reject"===t.undeclared?"reject":"delete"),Xe({kind:"structure",baseInner:s,l:Qe(i),r:Qe(n),roots:[],ctx:r})}}}),dr=(e,t,r)=>{const[i,n]=((e,t)=>{const r=[[],[]];for(const t of e)t.hasKind("unit")?r[0].push(t):r[1].push(t);return r})(e.branches);if(!i.length)return{index:r.node("index",{signature:e,value:t})};const s={};return s.required=i.map(e=>r.node("required",{key:e.unit,value:t})),n.length&&(s.index=r.node("index",{signature:n,value:t})),s},pr={...gt,alias:wt,domain:jt,unit:Dt,proto:zt,union:Ct,morph:Rt,intersection:Kt,divisor:tt,regex:bt,predicate:et,required:Xt,optional:Gt,index:Vt,sequence:Yt,structure:hr},fr={...yt,alias:xt,domain:class extends Ot{traverseAllows=e=>R(e)===this.domain;compiledCondition="object"===this.domain?'((typeof data === "object" && data !== null) || typeof data === "function")':`typeof data === "${this.domain}"`;compiledNegation="object"===this.domain?'((typeof data !== "object" || data === null) && typeof data !== "function")':`typeof data !== "${this.domain}"`;expression=this.domain;literalKeys=(e=>[...F[this.domain]])()},unit:class extends Ot{compiledValue=this.json.unit;serializedValue="string"==typeof this.unit||this.unit instanceof Date?JSON.stringify(this.compiledValue):this.compiledValue;literalKeys=P(this.unit);compiledCondition=_t(this.unit,this.serializedValue);compiledNegation=_t(this.unit,this.serializedValue,"negated");expression=pe(this.unit);domain=R(this.unit);traverseAllows=this.unit instanceof Date?e=>e instanceof Date&&e.toISOString()===this.compiledValue:e=>e===this.unit},proto:class extends Ot{builtinName=M(this.proto);serializedConstructor=this.json.proto;compiledCondition=`data instanceof ${this.serializedConstructor}`;compiledNegation=`!(${this.compiledCondition})`;literalKeys=P(this.proto.prototype);traverseAllows=e=>e instanceof this.proto;expression=this.proto.name;domain="object"},union:It,morph:class extends vt{serializedMorphs=this.morphs.map(W);compiledMorphs=`[${this.serializedMorphs}]`;traverseAllows=(e,t)=>this.in.traverseAllows(e,t);traverseApply=(e,t)=>{t.queueMorphs(this.morphs),this.in.traverseApply(e,t)};expression=`(In: ${this.in.expression}) => Out<${this.out?.expression??"unknown"}>`;compile(e){"Allows"!==e.traversalKind?(e.line(`ctx.queueMorphs(${this.compiledMorphs})`),e.line(e.invoke(this.in))):e.return(e.invoke(this.in))}get in(){return this.inner.in}get validatedOut(){const e=this.inner.morphs.at(-1);return be(e,"root")?e?.out:void 0}get out(){return this.validatedOut??this.$.keywords.unknown.raw}rawKeyOf(){return this.in.rawKeyOf()}},intersection:class extends vt{basis=this.domain??this.proto??null;refinements=this.children.filter(e=>e.isRefinement());expression=this.structure?.expression||this.children.map(e=>e.nestableExpression).join(" & ")||"unknown";traverseAllows=(e,t)=>this.children.every(r=>r.traverseAllows(e,t));traverseApply=(e,t)=>{const r=t.currentErrorCount;if(!(this.basis&&(this.basis.traverseApply(e,t),t.currentErrorCount>r))){if(this.refinements.length){for(let i=0;i<this.refinements.length-1;i++)if(this.refinements[i].traverseApply(e,t),t.failFast&&t.currentErrorCount>r)return;if(this.refinements.at(-1).traverseApply(e,t),t.currentErrorCount>r)return}if(!(this.structure&&(this.structure.traverseApply(e,t),t.currentErrorCount>r))&&this.predicate){for(let i=0;i<this.predicate.length-1;i++)if(this.predicate[i].traverseApply(e,t),t.failFast&&t.currentErrorCount>r)return;this.predicate.at(-1).traverseApply(e,t)}}};compile(e){if("Allows"===e.traversalKind)return this.children.forEach(t=>e.check(t)),void e.return(!0);if(e.initializeErrorCount(),this.basis&&(e.check(this.basis),this.children.length>1&&e.returnIfFail()),this.refinements.length){for(let t=0;t<this.refinements.length-1;t++)e.check(this.refinements[t]),e.returnIfFailFast();e.check(this.refinements.at(-1)),(this.structure||this.predicate)&&e.returnIfFail()}if(this.structure&&(e.check(this.structure),this.predicate&&e.returnIfFail()),this.predicate){for(let t=0;t<this.predicate.length-1;t++)e.check(this.predicate[t]),e.returnIfFail();e.check(this.predicate.at(-1))}}rawKeyOf(){return this.basis?this.structure?this.basis.rawKeyOf().or(this.structure.keyof()):this.basis.rawKeyOf():this.structure?.keyof()??this.$.keywords.never.raw}},divisor:class extends He{traverseAllows=e=>e%this.rule==0;compiledCondition=`data % ${this.rule} === 0`;compiledNegation=`data % ${this.rule} !== 0`;impliedBasis=this.$.keywords.number.raw;expression=`% ${this.rule}`},regex:class extends He{instance=new RegExp(this.rule,this.flags);expression=`${this.instance}`;traverseAllows=this.instance.test.bind(this.instance);compiledCondition=`${this.expression}.test(data)`;compiledNegation=`!${this.compiledCondition}`;impliedBasis=this.$.keywords.string.raw},predicate:class extends Ze{serializedPredicate=W(this.predicate);compiledCondition=`${this.serializedPredicate}(data, ctx)`;compiledNegation=`!${this.compiledCondition}`;impliedBasis=null;expression=this.serializedPredicate;traverseAllows=this.predicate;errorContext={code:"predicate",description:this.description};compiledErrorContext=`{ code: "predicate", description: "${this.description}" }`;traverseApply=(e,t)=>{this.predicate(e,t)||t.hasError()||t.error(this.errorContext)};compile(e){"Allows"!==e.traversalKind?e.if(`${this.compiledNegation} && !ctx.hasError()`,()=>e.line(`ctx.error(${this.compiledErrorContext})`)):e.return(this.compiledCondition)}},required:class extends Ht{expression=`${this.compiledKey}: ${this.value.expression}`;errorContext=Object.freeze({code:"required",missingValueDescription:this.value.description,relativePath:[this.key]});compiledErrorContext=Le(this.errorContext)},optional:class extends Ht{expression=`${this.compiledKey}?: ${this.value.expression}`},index:class extends Ze{impliedBasis=this.$.keywords.object.raw;expression=`[${this.signature.expression}]: ${this.value.expression}`;traverseAllows=(e,t)=>k(e).every(e=>{if(this.signature.traverseAllows(e[0],t)){t?.path.push(e[0]);const r=this.value.traverseAllows(e[1],t);return t?.path.pop(),r}return!0});traverseApply=(e,t)=>k(e).forEach(e=>{this.signature.traverseAllows(e[0],t)&&(t.path.push(e[0]),this.value.traverseApply(e[1],t),t.path.pop())});_transform(e,t){t.path.push(this.signature);const r=super._transform(e,t);return t.path.pop(),r}compile(){}},sequence:class extends Ze{impliedBasis=this.$.keywords.Array.raw;prefix=this.inner.prefix??[];optionals=this.inner.optionals??[];prevariadic=[...this.prefix,...this.optionals];postfix=this.inner.postfix??[];isVariadicOnly=this.prevariadic.length+this.postfix.length===0;minVariadicLength=this.inner.minVariadicLength??0;minLength=this.prefix.length+this.minVariadicLength+this.postfix.length;minLengthNode=0===this.minLength?null:this.$.node("minLength",this.minLength);maxLength=this.variadic?null:this.minLength+this.optionals.length;maxLengthNode=null===this.maxLength?null:this.$.node("maxLength",this.maxLength);impliedSiblings=this.minLengthNode?this.maxLengthNode?[this.minLengthNode,this.maxLengthNode]:[this.minLengthNode]:this.maxLengthNode?[this.maxLengthNode]:[];childAtIndex(e,t){if(t<this.prevariadic.length)return this.prevariadic[t];const r=e.length-this.postfix.length;return t>=r?this.postfix[t-r]:this.variadic??a(`Unexpected attempt to access index ${t} on ${this}`)}traverseAllows=(e,t)=>{for(let r=0;r<e.length;r++)if(!this.childAtIndex(e,r).traverseAllows(e[r],t))return!1;return!0};traverseApply=(e,t)=>{for(let r=0;r<e.length;r++)t.path.push(r),this.childAtIndex(e,r).traverseApply(e[r],t),t.path.pop()};compile(e){this.prefix.forEach((t,r)=>e.traverseKey(`${r}`,`data[${r}]`,t)),this.optionals.forEach((t,r)=>{const i=`${r+this.prefix.length}`;e.if(`${i} >= ${e.data}.length`,()=>"Allows"===e.traversalKind?e.return(!0):e.return()),e.traverseKey(i,`data[${i}]`,t)}),this.variadic&&(this.postfix.length&&e.const("firstPostfixIndex",`${e.data}.length${this.postfix.length?`- ${this.postfix.length}`:""}`),e.for("i < "+(this.postfix.length?"firstPostfixIndex":"data.length"),()=>e.traverseKey("i","data[i]",this.variadic),this.prevariadic.length),this.postfix.forEach((t,r)=>{const i=`firstPostfixIndex + ${r}`;e.traverseKey(i,`data[${i}]`,t)})),"Allows"===e.traversalKind&&e.return(!0)}_transform(e,t){t.path.push(this.$.keywords.nonNegativeIntegerString.raw);const r=super._transform(e,t);return t.path.pop(),r}tuple=(e=>{const t=[];return e.prefix?.forEach(e=>t.push({kind:"prefix",node:e})),e.optionals?.forEach(e=>t.push({kind:"optionals",node:e})),e.variadic&&t.push({kind:"variadic",node:e.variadic}),e.postfix?.forEach(e=>t.push({kind:"postfix",node:e})),t})(this.inner);expression=this.description},structure:or};class mr extends g{get[ye](){return"module"}}const gr={description:{meta:!0}},yr=(e,t)=>{const r=br(e);return t&&!t.includes(r)?u(`Root of kind ${r} should be one of ${t}`):r},br=e=>{switch(typeof e){case"string":return"$"===e[0]?"alias":"domain";case"function":return be(e,"root")?e.kind:"proto";case"object":{if(null===e)break;if("morphs"in e)return"morph";if("branches"in e||B(e))return"union";if("unit"in e)return"unit";if("alias"in e)return"alias";const t=Object.keys(e);if(0===t.length||t.some(e=>e in je))return"intersection";if("proto"in e)return"proto";if("domain"in e)return"domain"}}return u(`${pe(e)} is not a valid type schema`)},vr={},$r=e=>B(e)?e.map(e=>e.collapsibleJson):e.collapsibleJson;class xr extends X{traversalKind;path=[];discriminants=[];constructor(e){super("data","ctx"),this.traversalKind=e}invoke(e,t){const r=t?.arg??this.data;return this.requiresContextFor(e)?`${this.reference(e,t)}(${r}, ${this.ctx})`:`${this.reference(e,t)}(${r})`}reference(e,t){const r=`this.${e.id}${t?.kind??this.traversalKind}`;return t?.bind?`${r}.bind(${t?.bind})`:r}requiresContextFor(e){return"Apply"===this.traversalKind||e.allowsRequiresContext}initializeErrorCount(){return this.const("errorCount","ctx.currentErrorCount")}returnIfFail(){return this.if("ctx.currentErrorCount > errorCount",()=>this.return())}returnIfFailFast(){return this.if("ctx.failFast && ctx.currentErrorCount > errorCount",()=>this.return())}traverseKey(e,t,r){const i=this.requiresContextFor(r);return i&&this.line(`${this.ctx}.path.push(${e})`),this.check(r,{arg:t}),i&&this.line(`${this.ctx}.path.pop()`),this}check(e,t){return"Allows"===this.traversalKind?this.if(`!${this.invoke(e,t)}`,()=>this.return(!1)):this.line(this.invoke(e,t))}writeMethod(e){return`${e}(${this.argNames.join(", ")}){\n${this.body} }\n`}}var kr=function(e,t,r,i,n,s){function o(e){if(void 0!==e&&"function"!=typeof e)throw new TypeError("Function expected");return e}for(var a,l=i.kind,c="getter"===l?"get":"setter"===l?"set":"value",u=!t&&e?i.static?e:e.prototype:null,h=t||(u?Object.getOwnPropertyDescriptor(u,i.name):{}),d=!1,p=r.length-1;p>=0;p--){var f={};for(var m in i)f[m]="access"===m?{}:i[m];for(var m in i.access)f.access[m]=i.access[m];f.addInitializer=function(e){if(d)throw new TypeError("Cannot add initializers after decoration has completed");s.push(o(e||null))};var g=(0,r[p])("accessor"===l?{get:h.get,set:h.set}:h[c],f);if("accessor"===l){if(void 0===g)continue;if(null===g||"object"!=typeof g)throw new TypeError("Object expected");(a=o(g.get))&&(h.get=a),(a=o(g.set))&&(h.set=a),(a=o(g.init))&&n.unshift(a)}else(a=o(g))&&("field"===l?n.unshift(a):h[c]=a)}u&&Object.defineProperty(u,i.name,h),d=!0};const wr=Object.assign(h(pr,(e,t)=>[e,t.defaults]),{jitless:K(),registerKeywords:!1,prereducedAliases:!1}),Ar=["registerKeywords","prereducedAliases"],Or=(e,t)=>{if(!t)return e;const r=((e,t)=>{const r={...e};let i;for(i in t)r[i]=Ke(i)?{...e[i],...t[i]}:t[i];return r})(e,t);return Ar.forEach(e=>{e in t||delete r[e]}),r},jr=e=>`#${e} duplicates public alias ${e}`,qr={};let Er=0,Kr=(()=>{let e,t,r,i=[];return class n{static{const n="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;e=[A],t=[A],r=[A],kr(this,null,e,{kind:"method",name:"schema",static:!1,private:!1,access:{has:e=>"schema"in e,get:e=>e.schema},metadata:n},null,i),kr(this,null,t,{kind:"method",name:"defineRoot",static:!1,private:!1,access:{has:e=>"defineRoot"in e,get:e=>e.defineRoot},metadata:n},null,i),kr(this,null,r,{kind:"method",name:"units",static:!1,private:!1,access:{has:e=>"units"in e,get:e=>e.units},metadata:n},null,i),n&&Object.defineProperty(this,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:n})}config=function(e,t,r){for(var i=arguments.length>2,n=0;n<t.length;n++)r=i?t[n].call(e,r):t[n].call(e);return i?r:void 0}(this,i);resolvedConfig;id="$"+ ++Er;[ye]="scope";referencesById={};references=[];resolutions={};json={};exportedNames;aliases={};resolved=!1;static keywords={};get keywords(){return n.keywords}static ambient;get ambient(){return this.constructor.ambient}constructor(e,t){this.config=t??{},this.resolvedConfig=(e=>Or(Or(wr,Ie),e))(t),this.exportedNames=Object.keys(e).filter(t=>{if("#"===t[0]){const r=t.slice(1);return r in this.aliases&&u(jr(r)),this.aliases[r]=e[t],!1}return t in this.aliases&&u(jr(t)),this.aliases[t]=e[t],!0}),this.ambient&&(this.ambient.export(),this.resolutions=h(this.ambient.resolutions,(e,t)=>[e,be(t,"root")?t.bindScope(this):t]))}get raw(){return this}schema(e,t){return this.node(yr(e),e,t)}defineRoot(e){return e}units(e,t){const r=[];for(const t of e)r.includes(t)||r.push(t);const i=r.map(e=>this.node("unit",{unit:e},t));return this.node("union",i,{...t,prereduced:!0})}lazyResolutions=[];lazilyResolve(e,t){t||(qr.synthetic??=0,t="synthetic"+ ++qr.synthetic);const r=this.node("alias",{alias:t,resolve:e},{prereduced:!0});return this.lazyResolutions.push(r),r}node=((e,t,r)=>{let i="string"==typeof e?e:yr(t,e),n=t;if(ve(n)&&n.kind===i)return n.bindScope(this);if("alias"!==i||r?.prereduced){if("union"===i&&S(n,"object")){const e=(e=>B(e)?e:"branches"in e&&B(e.branches)?e.branches:void 0)(n);1===e?.length&&(n=e[0],i=yr(n))}}else{const e=this.resolveRoot(kt(n).alias);n=e,i=e.kind}const s=pr[i],o=s.normalize?.(n)??n;if(ve(o))return o.kind===i?o.bindScope(this):u(`Node of kind ${o.kind} is not valid as a ${i} definition`);const a=r?.alias??i;qr[a]??=0;const l=`${a}${++qr[a]}`,c=((e,t)=>{const r=pr[e],i={},n=d(t.schema).sort(([e],[t])=>Ke(e)?Ke(t)?Se(e)-Se(t):1:Ke(t)||e<t?-1:1),s=[];for(const s of n){const n=s[0],o=r.keys[n]??gr[n];if(!o)return u(`Key ${n} is not valid on ${e} schema`);const a=o.parse?o.parse(s[1],t):s[1];a===w||void 0===a&&!o.preserveUndefined||(i[n]=a)}const o=d(i);let a={},l={};o.forEach(([e,t])=>{const i=t,n=r.keys[e]??gr[e];a[e]=(n.serialize??(n.child?$r:ze))(i),n.child&&(B(i)?s.push(...i):s.push(i)),n.meta||(l[e]=a[e])}),r.finalizeJson&&(a=r.finalizeJson(a),l=r.finalizeJson(l));let c=a;const h=Object.keys(c);1===h.length&&h[0]===r.collapsibleKey&&(c=c[r.collapsibleKey],S(c,"object")&&1===Object.keys(a).length&&(a=c,l=c));const p=JSON.stringify({kind:e,...a});if(t.reduceTo)return vr[p]=t.reduceTo,t.reduceTo;const f=JSON.stringify({kind:e,...l});if(r.reduce&&!t.prereduced){const e=r.reduce(i,t.$);if(e)return e instanceof Fe?e.throw():(t.alias&&(e.alias??=t.alias),e)}if(vr[p])return vr[p];const m={id:t.id,kind:e,impl:r,inner:i,entries:o,json:a,typeJson:l,collapsibleJson:c,children:s,innerHash:p,typeHash:f,$:t.$};t.alias&&(m.alias=t.alias);for(const e in i)"description"!==e&&"in"!==e&&"out"!==e&&(m[e]=i[e]);const g=new fr[e](m);return vr[p]=g,g})(i,{...r,id:l,$:this,schema:o}).bindScope(this);return this.resolved?this.resolvedConfig.jitless||Mr(c.references):Object.assign(this.referencesById,c.referencesById),c}).bind(this);parseRoot(e,t){return this.schema(e,t)}resolveRoot(e){return this.maybeResolveRoot(e)??u(Ir(e))}maybeResolveRoot(e){const t=this.maybeResolveGenericOrRoot(e);if(!be(t,"generic"))return t}maybeResolveGenericOrRoot(e){const t=this.maybeResolve(e);return be(t,"module")?u(Nr(e)):t}preparseRoot(e){return e}maybeResolve(e){const t=this.maybeShallowResolve(e);return"string"==typeof t?this.node("alias",{alias:t},{prereduced:!0}):t}maybeShallowResolve(e){const t=this.resolutions[e];if(t)return t;let r=this.aliases[e];return r?(r=this.preparseRoot(r),be(r,"generic")?this.resolutions[e]=((i=r).$.schema(i.def,{}),i):be(r,"module")?this.resolutions[e]=r:(this.resolutions[e]=e,this.resolutions[e]=this.parseRoot(r))):this.maybeResolveSubalias(e);var i}maybeResolveSubalias(e){return Sr(this.aliases,e)}import(...e){return new mr(h(this.export(...e),(e,t)=>[`#${e}`,t]))}_exportedResolutions;_exports;export(...e){if(!this._exports){this._exports={};for(const e of this.exportedNames)this._exports[e]=this.maybeResolve(e);this.lazyResolutions.forEach(e=>e.resolution),this._exportedResolutions=Cr(this,this._exports),Object.assign(this.json,h(this._exportedResolutions,(e,t)=>be(t,"root")?[e,t.json]:[])),Object.assign(this.resolutions,this._exportedResolutions),this.config.registerKeywords&&Object.assign(n.keywords,this._exportedResolutions),this.references=Object.values(this.referencesById),this.resolvedConfig.jitless||Mr(this.references),this.resolved=!0}return new mr(h(e.length?e:this.exportedNames,(e,t)=>[t,this._exports[t]]))}resolve(e){return this.export()[e]}}})();const Sr=(e,t)=>{const r=t.indexOf(".");if(-1===r)return;const i=t.slice(0,r),n=e[i];if(void 0===n)return;if(!be(n,"module"))return u(Br(i));const s=t.slice(r+1),o=n[s];return void 0===o?be(o,"module")?Sr(o,s):u(Ir(t)):be(o,"root")||be(o,"generic")?o:void a(`Unexpected resolution for alias '${t}': ${pe(o)}`)},Rr=(e,t)=>new zr(e,t),zr=Kr,Lr=new zr({}),Cr=(e,t)=>{const r={};for(const i in t){const n=t[i];if(be(n,"module")){const t=h(Cr(e,n),(e,t)=>[`${i}.${e}`,t]);Object.assign(r,t)}else be(n,"generic")||be(n,"root")?r[i]=n:a(`Unexpected scope resolution ${pe(n)}`)}return r},Ir=e=>`'${e}' is unresolvable`,Br=e=>`'${e}' must reference a module to be accessed using dot syntax`,Nr=e=>`Reference to submodule '${e}' must specify an alias`,Mr=e=>{const t=Pr(e);for(const r of e)r.jit||(r.jit=!0,r.traverseAllows=t[`${r.id}Allows`].bind(t),r.isRoot()&&!r.allowsRequiresContext&&(r.allows=r.traverseAllows),r.traverseApply=t[`${r.id}Apply`].bind(t))},Pr=e=>(new X).block("return",t=>(e.forEach(e=>{const r=new xr("Allows").indent();e.compile(r);const i=new xr("Apply").indent();e.compile(i),t.line(`${r.writeMethod(`${e.id}Allows`)},`).line(`${i.writeMethod(`${e.id}Apply`)},`)}),t)).compile()(),Fr=Rr({any:{},bigint:"bigint",boolean:[{unit:!1},{unit:!0}],false:{unit:!1},never:[],null:{unit:null},number:"number",object:"object",string:"string",symbol:"symbol",true:{unit:!0},unknown:{},void:{unit:void 0},undefined:{unit:void 0}},{prereducedAliases:!0,registerKeywords:!0}).export(),Tr=Rr({lengthBoundable:["string",Array],propertyKey:["string","symbol"],nonNegativeIntegerString:{domain:"string",regex:nr}},{prereducedAliases:!0,registerKeywords:!0}).export();Lr.node("union",{branches:["string","number","object","bigint","symbol",{unit:!0},{unit:!1},{unit:null},{unit:void 0}]},{reduceTo:Lr.node("intersection",{},{prereduced:!0})});const Ur=Rr({Array:Array,Function:Function,Date:Date,Error:Error,Map:Map,RegExp:RegExp,Set:Set,WeakMap:WeakMap,WeakSet:WeakSet,Promise:Promise},{prereducedAliases:!0,registerKeywords:!0}).export(),Dr=(e,t)=>Lr.defineRoot({domain:"string",regex:{rule:e.source,flags:e.flags,description:t}}),_r=Lr.defineRoot({in:Dr(re,"a well-formed numeric string"),morphs:e=>Number.parseFloat(e)}),Vr=Lr.defineRoot({in:Dr(se,"a well-formed integer string"),morphs:(e,t)=>{if(!oe(e))return t.error("a well-formed integer string");const r=Number.parseInt(e);return Number.isSafeInteger(r)?r:t.error("an integer in the range Number.MIN_SAFE_INTEGER to Number.MAX_SAFE_INTEGER")}}),Jr=Lr.defineRoot({in:"string",morphs:(e,t)=>{try{return new URL(e)}catch{return t.error("a valid URL")}}}),Wr=Lr.defineRoot({in:"string",morphs:(e,t)=>{try{return JSON.parse(e)}catch{return t.error("a valid JSON string")}}}),Zr=Rr({url:Jr,number:_r,integer:Vr,date:Lr.defineRoot({in:"string",morphs:(e,t)=>{const r=((e,t)=>{{const t=new Date(e);return Number.isNaN(+t)?"a valid date":t}})(e);return"string"==typeof r?t.error(r):r}}),json:Wr}).export(),Hr="(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])",Gr=`(${Hr}[.]){3}${Hr}`,Xr=Dr(new RegExp(`^${Gr}$`),"a valid IPv4 address"),Qr="(?:[0-9a-fA-F]{1,4})",Yr=Dr(new RegExp(`^((?:${Qr}:){7}(?:${Qr}|:)|(?:${Qr}:){6}(?:${Gr}|:${Qr}|:)|(?:${Qr}:){5}(?::${Gr}|(:${Qr}){1,2}|:)|(?:${Qr}:){4}(?:(:${Qr}){0,1}:${Gr}|(:${Qr}){1,3}|:)|(?:${Qr}:){3}(?:(:${Qr}){0,2}:${Gr}|(:${Qr}){1,4}|:)|(?:${Qr}:){2}(?:(:${Qr}){0,3}:${Gr}|(:${Qr}){1,5}|:)|(?:${Qr}:){1}(?:(:${Qr}){0,4}:${Gr}|(:${Qr}){1,6}|:)|(?::((?::${Qr}){0,5}:${Gr}|(?::${Qr}){1,7}|:)))(%[0-9a-zA-Z-.:]{1,})?$`),"a valid IPv6 address"),ei=Lr.defineRoot([Xr,Yr]),ti=Lr.defineRoot({domain:"string",predicate:{predicate:e=>{try{new URL(e)}catch{return!1}return!0},description:"a valid URL"}}),ri=Dr(/^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$/,"a valid email"),ii=Dr(/^[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}$/,"a valid UUID"),ni=Dr(/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+([0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?$/,"a valid semantic version (see https://semver.org/)"),si=Lr.defineRoot({domain:"string",regex:{rule:/^(?:4[0-9]{12}(?:[0-9]{3,6})?|5[1-5][0-9]{14}|(222[1-9]|22[3-9][0-9]|2[3-6][0-9]{2}|27[01][0-9]|2720)[0-9]{12}|6(?:011|5[0-9][0-9])[0-9]{12,15}|3[47][0-9]{13}|3(?:0[0-5]|[68][0-9])[0-9]{11}|(?:2131|1800|35\d{3})\d{11}|6[27][0-9]{14}|^(81[0-9]{14,17}))$/.source,description:"a valid credit card number"},predicate:{predicate:e=>{const t=e.replace(/[- ]+/g,"");let r,i,n=0,s=!1;for(let e=t.length-1;e>=0;e--)r=t.substring(e,e+1),i=Number.parseInt(r,10),s?(i*=2,n+=i>=10?i%10+1:i):n+=i,s=!s;return!(n%10!=0||!t)},description:"a valid credit card number"}}),oi=Rr({alpha:Dr(/^[A-Za-z]*$/,"only letters"),alphanumeric:Dr(/^[A-Za-z\d]*$/,"only letters and digits"),lowercase:Dr(/^[a-z]*$/,"only lowercase letters"),uppercase:Dr(/^[A-Z]*$/,"only uppercase letters"),creditCard:si,email:ri,uuid:ii,url:ti,semver:ni,ip:ei,integer:{domain:"number",divisor:1}},{prereducedAliases:!0}).export(),ai=Rr({...Fr,...Ur,...oi,parse:Zr});Kr.ambient=ai.raw;const li=ai.export();class ci extends E{params;def;$;[ye]="generic";constructor(e,t,r){super((...e)=>r.parseRoot(t)),this.params=e,this.def=t,this.$=r}}class ui{chars;i;constructor(e){this.chars=[...e],this.i=0}shift(){return this.chars[this.i++]??""}get lookahead(){return this.chars[this.i]??""}get nextLookahead(){return this.chars[this.i+1]??""}get length(){return this.chars.length}shiftUntil(e){let t="";for(;this.lookahead;){if(e(this,t)){if(t[t.length-1]!==ui.escapeToken)break;t=t.slice(0,-1)}t+=this.shift()}return t}shiftUntilNextTerminator(){return this.shiftUntilNonWhitespace(),this.shiftUntil(ui.lookaheadIsTerminator)}shiftUntilNonWhitespace(){return this.shiftUntil(ui.lookaheadIsNotWhitespace)}jumpToIndex(e){this.i=e<0?this.length+e:e}get location(){return this.i}get unscanned(){return this.chars.slice(this.i,this.length).join("")}get scanned(){return this.chars.slice(0,this.i).join("")}sliceChars(e,t){return this.chars.slice(e,t).join("")}lookaheadIs(e){return this.lookahead===e}lookaheadIsIn(e){return this.lookahead in e}}!function(e){e.lookaheadIsTerminator=t=>t.lookahead in e.terminatingChars,e.lookaheadIsNotWhitespace=t=>!(t.lookahead in e.whiteSpaceTokens),e.terminatingChars={"<":!0,">":!0,"=":!0,"|":!0,"&":!0,")":!0,"[":!0,"%":!0," ":!0,",":!0},e.finalizingLookaheads={">":!0,",":!0,"":!0},e.escapeToken="\\",e.whiteSpaceTokens={" ":!0,"\n":!0,"\t":!0},e.lookaheadIsFinalizing=(t,r)=>">"===t?"="===r[0]?"="===r[1]:""===r.trimStart()||f(r.trimStart()[0],e.terminatingChars):","===t}(ui||(ui={}));const hi=([e,t])=>{const r=pi(e);return B(t)&&"="===t[1]?("required"!==r.kind&&u(di),{kind:"optional",key:r.key,value:t[0],default:t[2]}):{kind:r.kind,key:r.key,value:t,default:w}},di="Only required keys may specify default values, e.g. { ark: ['string', '=', '⛵'] }",pi=e=>"symbol"==typeof e?{kind:"required",key:e}:"?"===e.at(-1)?e.at(-2)===ui.escapeToken?{kind:"required",key:`${e.slice(0,-2)}?`}:{kind:"optional",key:e.slice(0,-1)}:"["===e[0]&&"]"===e.at(-1)?{kind:"index",key:e.slice(1,-1)}:e[0]===ui.escapeToken&&"["===e[1]&&"]"===e.at(-1)?{kind:"required",key:e.slice(1)}:"..."===e||"+"===e?{kind:e,key:e}:{kind:"required",key:"\\..."===e?"...":"\\+"===e?"+":e},fi={">":!0,">=":!0},mi={"<":!0,"<=":!0},gi={"<":">",">":"<","<=":">=",">=":"<=","==":"=="},yi=e=>`Missing ${e}`,bi=e=>`Left-bounded expressions must specify their limits using < or <= (was ${e})`,vi=(e,t,r,i,n)=>{const s=r.parseUntilFinalizer();return i.push(s.scanner.scanned.slice(0,-1)),n.push(s.root),">"===s.finalizer?n.length===t.length?{result:n,unscanned:s.scanner.unscanned}:s.error($i(e,t,i)):","===s.finalizer?vi(e,t,r,i,n):s.error(yi(">"))},$i=(e,t,r)=>`${e}<${t.join(", ")}> requires exactly ${t.length} args (got ${r.length}${0===r.length?"":`: ${r.join(", ")}`})`,xi=e=>{const t=e.previousOperator();return t?ki(t,e.scanner.unscanned):wi(e.scanner.unscanned)},ki=(e,t="")=>`Token '${e}' requires a right operand${t?` before '${t}'`:""}`,wi=e=>"Expected an expression"+(e?` before '${e}'`:""),Ai=(e,t,r)=>{switch(t){case"required":return e.optionals?u(qi):(e.variadic?e.postfix=n(e.postfix,r):e.prefix=n(e.prefix,r),e);case"optional":return e.variadic?u(Ei):(e.optionals=n(e.optionals,r),e);case"variadic":return e.postfix&&u(ji),e.variadic?e.variadic.equals(r)||u(ji):e.variadic=r.raw,e}},Oi=(e,t)=>{const r=t.firstReferenceOfKind("sequence");return r?(r.prefix.forEach(t=>Ai(e,"required",t)),r.optionals.forEach(t=>Ai(e,"optional",t)),r.variadic&&Ai(e,"variadic",r.variadic),r.postfix.forEach(t=>Ai(e,"required",t)),e):Ai(e,"variadic",Fr.unknown)},ji="A tuple may have at most one variadic element",qi="A required element may not follow an optional element",Ei="An optional element may not follow a variadic element",Ki=(e,t)=>{if(void 0===e[2])return u(ki(e[1],""));const r=t.$.parse(e[0],t),i=t.$.parse(e[2],t);return"&"===e[1]?r.and(i):r.or(i)},Si=(e,t)=>`${":"===e?"Narrow":"Morph"} expression requires a function following '${e}' (was ${typeof t})`,Ri={"|":Ki,"&":Ki,"[]":(e,t)=>t.$.parse(e[0],t).array(),":":(e,t)=>"function"!=typeof e[2]?u(Si(":",e[2])):t.$.parse(e[0],t).constrain("predicate",e[2]),"=>":(e,t)=>"function"!=typeof e[2]?u(Si("=>",e[2])):t.$.parse(e[0],t).pipe(e[2]),"@":(e,t)=>t.$.parse(e[0],t).configureShallowDescendants(e[2])},zi={keyof:(e,t)=>t.$.parse(e[1],t).keyof(),instanceof:(e,t)=>{if("function"!=typeof e[1])return u(Li(I(e[1])));const r=e.slice(1).map(e=>"function"==typeof e?t.$.node("proto",{proto:e}):u(Li(I(e))));return 1===r.length?r[0]:t.$.node("union",{branches:r})},"===":(e,t)=>t.$.units(e.slice(1))},Li=e=>`Expected a constructor following 'instanceof' operator (was ${e})`,Ci=e=>`Type definitions must be strings or objects (was ${e})`,Ii=e=>"Invalid Date"!==e.toString(),Bi=e=>`'${e}' could not be parsed by the Date constructor`,Ni={"<":!0,">":!0},Mi={"<":1,">":1,"=":1},Pi=(e,t,r,i)=>r.extends(Fr.number)?"number"!=typeof t?u(Fi(e,t,i)):"=="===e?["min","max"]:">"===e[0]?["min"]:["max"]:r.extends(Tr.lengthBoundable)?"number"!=typeof t?u(Fi(e,t,i)):"=="===e?["minLength","maxLength"]:">"===e[0]?["minLength"]:["maxLength"]:r.extends(Ur.Date)?"=="===e?["after","before"]:">"===e[0]?["after"]:["before"]:u((e=>`Bounded expression ${e} must be a number, string, Array, or Date`)(r.expression)),Fi=(e,t,r)=>`Comparator ${"left"===r?gi[e]:e} must be ${"left"===r?"preceded":"followed"} by a corresponding literal (was ${t})`,Ti=e=>`% operator must be followed by a non-zero integer literal (was ${e})`,Ui=e=>{const t=e.scanner.shift();return""===t?e.finalize(""):"["===t?"]"===e.scanner.shift()?e.setRoot(e.root.array()):e.error(_i):"|"===t||"&"===t?e.pushRootToBranch(t):")"===t?e.finalizeGroup():ui.lookaheadIsFinalizing(t,e.scanner.unscanned)?e.finalize(t):f(t,Mi)?((e,t)=>{const r=((e,t)=>e.scanner.lookaheadIs("=")?`${t}${e.scanner.shift()}`:f(t,Ni)?t:e.error("= is not a valid comparator. Use == to check for equality"))(e,t);if(e.root.hasKind("unit")){if("number"==typeof e.root.unit)return e.reduceLeftBound(e.root.unit,r),void e.unsetRoot();if(e.root.unit instanceof Date){const t=`d'${e.root.description??e.root.unit.toISOString()}'`;return e.unsetRoot(),void e.reduceLeftBound(t,r)}}return((e,t)=>{const r=e.unsetRoot(),i=e.scanner.location;e.parseOperand();const n=e.unsetRoot(),s=e.scanner.sliceChars(i,e.scanner.location);if(e.root=r,!n.hasKind("unit")||"number"!=typeof n.unit&&!(n.unit instanceof Date))return e.error(Fi(t,s,"right"));const o=n.unit,a=1===t.length;for(const i of Pi(t,"number"==typeof o?o:s,r,"right"))e.constrainRoot(i,{rule:o,exclusive:a});if(!e.branches.leftBound)return;if(!f(t,mi))return e.error(bi(t));const l=Pi(e.branches.leftBound.comparator,e.branches.leftBound.limit,r,"left");var c,u,h;e.constrainRoot(l[0],{rule:(h=(c=e.branches.leftBound).limit,"string"!=typeof h||"d"!==h[0]||"'"!==h[1]&&'"'!==h[1]||h.at(-1)!==h[1]?c.limit:(u=c.limit,u.slice(2,-1))),exclusive:1===c.comparator.length}),e.branches.leftBound=null})(e,r)})(e,t):"%"===t?(e=>{const t=e.scanner.shiftUntilNextTerminator(),r=(i=t,n={errorOnFail:Ti(t)},de(i,"integer",n));var i,n;0===r&&e.error(Ti(0)),e.root=e.root.constrain("divisor",r)})(e):" "===t?Ui(e):e.error(Di(t))},Di=(e,t="")=>`'${e}' is not allowed here${t&&` (should be ${t})`}`,_i="Missing expected ']'",Vi=e=>Ji(new ui(e)),Ji=e=>{const t=e.shiftUntilNextTerminator();""===t&&u("An empty string is not a valid generic parameter name"),e.shiftUntilNonWhitespace();const r=e.shift();return""===r?[t]:","===r?[t,...Ji(e)]:u(Di(r,","))},Wi=(e,t)=>{const r=e.scanner.shiftUntil(Xi[Gi[t]]);if(""===e.scanner.lookahead)return e.error(Yi(r,t));if(e.scanner.shift(),"/"===t)e.root=e.ctx.$.node("intersection",{domain:"string",regex:r},{prereduced:!0});else if(f(t,Zi))e.root=e.ctx.$.node("unit",{unit:r});else{const t=((e,t)=>{const r=new Date(e);if(Ii(r))return r;const i=he(e);if(void 0!==i){const e=new Date(i);if(Ii(e))return e}return t?u(!0===t?Bi(e):t):void 0})(r,Bi(r));e.root=e.ctx.$.node("unit",{unit:t,description:r})}},Zi={"'":1,'"':1},Hi={"/":1,"'":1,'"':1},Gi={"d'":"'",'d"':'"',"'":"'",'"':'"',"/":"/"},Xi={"'":e=>"'"===e.lookahead,'"':e=>'"'===e.lookahead,"/":e=>"/"===e.lookahead},Qi={'"':"double-quote","'":"single-quote","/":"forward slash"},Yi=(e,t)=>`${t}${e} requires a closing ${Qi[Gi[t]]}`,en=e=>""===e.scanner.lookahead?e.error(xi(e)):"("===e.scanner.lookahead?e.shiftedByOne().reduceGroupOpen():e.scanner.lookaheadIsIn(Hi)?Wi(e,e.scanner.shift()):e.scanner.lookaheadIsIn(ui.whiteSpaceTokens)?en(e.shiftedByOne()):"d"===e.scanner.lookahead&&e.scanner.nextLookahead in Zi?Wi(e,`${e.scanner.shift()}${e.scanner.shift()}`):(e=>{const t=e.scanner.shiftUntilNextTerminator();"keyof"===t?e.addPrefix("keyof"):e.root=((e,t)=>((e,t)=>{if(e.ctx.args?.[t])return e.ctx.args[t].raw;const r=e.ctx.$.maybeResolve(t);return r instanceof vt?r:void 0!==r?be(r,"generic")?((e,t,r)=>{if(r.scanner.shiftUntilNonWhitespace(),"<"!==r.scanner.shift())return r.error($i(e,t.params,[]));const i=((e,t,r)=>vi(e,t,r,[],[]))(e,t.params,r),n=i.unscanned.length;return r.scanner.jumpToIndex(0===n?r.scanner.length:-n),t(...i.result)})(t,r,e):u(`Unexpected resolution ${pe(r)}`):void 0})(e,t)??((e,t)=>{const r=he(t,{strict:!0});if(void 0!==r)return e.ctx.$.node("unit",{unit:r});const i=(e=>{if("n"!==e[e.length-1])return;const t=e.slice(0,-1);let r;try{r=BigInt(t)}catch{return}return se.test(t)?r:ae.test(t)?u(ue(e,"bigint")):void 0})(t);return void 0!==i?e.ctx.$.node("unit",{unit:i}):void 0})(e,t)??e.error(""===t?xi(e):"#"===t[0]?`Private type references should not include '#'. Use '${t.slice(1)}' instead.`:Ir(t)))(e,t)})(e),tn=e=>{for(;void 0===e.finalizer;)rn(e);return e},rn=e=>e.hasRoot()?e.parseOperator():e.parseOperand();class nn{ctx;scanner;root;branches={prefixes:[],leftBound:null,intersection:null,union:null};finalizer;groups=[];constructor(e,t){this.ctx=t,this.scanner=new ui(e)}error(e){return u(e)}hasRoot(){return void 0!==this.root}setRoot(e){this.root=e}unsetRoot(){const e=this.root;return this.root=void 0,e}constrainRoot(...e){this.root=this.root.constrain(e[0],e[1])}finalize(e){if(this.groups.length)return this.error(yi(")"));this.finalizeBranches(),this.finalizer=e}reduceLeftBound(e,t){const r=gi[t];return f(r,fi)?this.branches.leftBound?this.error(((e,t,r,i)=>`An expression may have at most one left bound (parsed ${this.branches.leftBound.limit}${gi[this.branches.leftBound.comparator]}, ${r}${gi[i]})`)(0,0,e,r)):void(this.branches.leftBound={comparator:r,limit:e}):this.error(bi(t))}finalizeBranches(){this.assertRangeUnset(),this.branches.union?(this.pushRootToBranch("|"),this.root=this.branches.union):this.branches.intersection?(this.pushRootToBranch("&"),this.root=this.branches.intersection):this.applyPrefixes()}finalizeGroup(){this.finalizeBranches();const e=this.groups.pop();if(!e)return this.error("Unmatched )"+(""===(t=this.scanner.unscanned)?"":` before ${t}`));var t;this.branches=e}addPrefix(e){this.branches.prefixes.push(e)}applyPrefixes(){for(;this.branches.prefixes.length;){const e=this.branches.prefixes.pop();this.root="keyof"===e?this.root.keyof():a(`Unexpected prefix '${e}'`)}}pushRootToBranch(e){this.assertRangeUnset(),this.applyPrefixes();const t=this.root;this.branches.intersection=this.branches.intersection?.and(t)??t,"|"===e&&(this.branches.union=this.branches.union?.or(this.branches.intersection)??this.branches.intersection,this.branches.intersection=null),this.root=void 0}parseUntilFinalizer(){return tn(new nn(this.scanner.unscanned,this.ctx))}parseOperator(){return Ui(this)}parseOperand(){return en(this)}assertRangeUnset(){if(this.branches.leftBound)return this.error(`Left bounds are only valid when paired with right bounds (try ...${this.branches.leftBound.comparator}${this.branches.leftBound.limit})`)}reduceGroupOpen(){this.groups.push(this.branches),this.branches={prefixes:[],leftBound:null,union:null,intersection:null}}previousOperator(){return this.branches.leftBound?.comparator??this.branches.prefixes.at(-1)??(this.branches.intersection?"&":this.branches.union?"|":void 0)}shiftedByOne(){return this.scanner.shift(),this}}const sn=Object.freeze({errors:Ne});class on extends E{constructor(e){super((...t)=>{if(1===t.length)return e.parseRoot(t[0]);if(2===t.length&&"string"==typeof t[0]&&"<"===t[0][0]&&">"===t[0].at(-1)){const r=Vi(t[0].slice(1,-1));return new ci(r,t[1],e)}return e.parseRoot(t)},{bind:e,attach:sn})}}class an extends Kr{parseCache={};constructor(e,t){const r={};for(const t in e){const i=ln(t);r[i.name]=i.params.length?new ci(i.params,e[t],{}):e[t]}super(r,t)}type=new on(this);match=(e=>(()=>{}).bind(this))();declare=(()=>({type:this.type})).bind(this);define=(e=>e).bind(this);preparseRoot(e){return j(e)&&!be(e,"generic")?e():e}parseRoot(e){return this.parse(e,{$:this,args:{}}).bindScope(this)}parse(e,t){return"string"==typeof e?t.args&&Object.keys(t.args).every(t=>!e.includes(t))?this.parseString(e,t):(this.parseCache[e]||(this.parseCache[e]=this.parseString(e,t)),this.parseCache[e]):S(e,"object")?((e,t)=>{const r=C(e);switch(r){case void 0:return be(e,"root")?e:((e,t)=>{let r;const i={},s=k(e).map(hi);if("..."===s[0]?.kind){const e=s.shift(),i=t.$.parse(e.value,t);if(!i.hasKind("intersection")||!i.structure)return u((e=>`Spread operand must resolve to an object literal type (was ${e})`)("string"==typeof e.value?e.value:pe(e.value)));r=i.structure}for(const e of s){if("..."===e.kind)return u("Spread operator may only be used as the first key in an object");if("+"!==e.kind)if("index"===e.kind){const r=t.$.parse(e.key,t),s=t.$.parse(e.value,t),o=dr(r,s,t.$);o.required&&(i.required=n(i.required,o.required)),o.index&&(i.index=n(i.index,o.index))}else{const r=t.$.parse(e.value,t),s={key:e.key,value:r};if(e.default!==w){const t=r(e.default);t instanceof Ne&&u(`Default value at ${pe(e.key)} ${t}`),r.assert(e.default),s.default=e.default}i[e.kind]=n(i[e.kind],s)}else"reject"!==e.value&&"delete"!==e.value&&"ignore"!==e.value&&u(`Value of '+' key must be 'reject', 'delete', or 'ignore' (was ${pe(e.value)})`),i.undeclared=e.value}const o=t.$.node("structure",i);return t.$.schema({domain:"object",structure:r?.merge(o)??o})})(e,t);case"Array":return((e,t)=>((e,t)=>(e=>void 0!==zi[e[0]])(e)?zi[e[0]](e,t):(e=>void 0!==Ri[e[1]])(e)?Ri[e[1]](e,t):void 0)(e,t)??((e,t)=>{let r=[{}],i=0;for(;i<e.length;){let n=!1,s=!1;"..."===e[i]&&i<e.length-1&&(n=!0,i++);const o=t.$.parse(e[i],t);if(i++,"?"===e[i]){if(n)return u("A spread element cannot be optional");s=!0,i++}if(n){if(!o.extends(Ur.Array))return u(`Spread element must be an array (was ${o.expression})`);r=r.flatMap(e=>o.branches.map(t=>Oi(ge(e),t)))}else r=r.map(e=>Ai(e,s?"optional":"required",o))}return t.$.raw.schema(r.map(e=>({proto:Array,sequence:e})))})(e,t))(e,t);case"RegExp":return t.$.node("intersection",{domain:"string",regex:e},{prereduced:!0});case"Function":{const t=j(e)?e():e;return be(t,"root")?t:u(Ci("Function"))}default:return u(Ci(r??pe(e)))}})(e,t):u(Ci(R(e)))}parseString(e,t){return this.maybeResolveRoot(e)??(e.endsWith("[]")&&this.maybeResolveRoot(e.slice(0,-2))?.array()||(e=>{e.parseOperand();const t=tn(e).root;return t?(e.scanner.shiftUntilNonWhitespace(),e.scanner.lookahead&&u(Di(e.scanner.lookahead)),t):a(`Root was unexpectedly unset after parsing string '${e.scanner.scanned}'`)})(new nn(e,t)))}}const ln=e=>{const t=e.indexOf("<");return-1===t?{name:e,params:[]}:(">"!==e.at(-1)&&u("'>' must be the last character of a generic declaration in a scope"),{name:e.slice(0,t),params:Vi(e.slice(t+1,-1))})},cn=((e,t={})=>new an(li,t))();an.ambient=cn.raw,cn.export();var un=function(r,i,n){return void 0===n&&(n={}),function(i,s,o){var a,l=r(i);return l instanceof Ne?{values:{},errors:e((a=l,a.forEach(function(e){return Object.assign(e,{type:e.code})}),a.byPath),o)}:(o.shouldUseNativeValidation&&t({},o),{errors:{},values:n.raw?i:l})}};export{un as arktypeResolver};
2
2
  //# sourceMappingURL=arktype.module.js.map