@hookform/resolvers
Version:
React Hook Form validation resolvers: Yup, Joi, Superstruct, Zod, Vest, Class Validator, io-ts, Nope, computed-types, TypeBox, arktype, Typanion and Effect-TS
1 lines • 92.5 kB
JavaScript
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,Date,Error,Function,Map,RegExp,Set,String,Number,Boolean,WeakMap,WeakSet,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}}})}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("structur