schemas/libraries/arktype/download_compiled/minified.js
const e=e=>Array.isArray(e)?e:[e],t=(e,t)=>{let n=[[],[]];for(let r of e)t(r)?n[0].push(r):n[1].push(r);return n},n=Array,r=(e,t)=>e.includes(t),i=(e,t=0)=>[...Array(e)].map((e,n)=>n+t),a=(e,t,n)=>e===void 0?t===void 0?[]:Array.isArray(t)?t:[t]:(n?.prepend?Array.isArray(t)?e.unshift(...t):e.unshift(t):Array.isArray(t)?e.push(...t):e.push(t),e),o=(t,n)=>n==null?t??[]:t==null?e(n):t.concat(n),s=(...e)=>e.reduce(o,[]),c=(t,n,r)=>{if(t===void 0)return Array.isArray(n)?n:[n];let i=r?.isEqual??((e,t)=>e===t);for(let r of e(n))t.some(e=>i(e,r))||t.push(r);return t},l=(e,t)=>e.reduce((e,n)=>{let r=n[t];return e[r]=a(e[r],n),e},{}),u=(e,t,n)=>e.length===t.length&&e.every(n?.isEqual?(e,r)=>n.isEqual(e,t[r]):(e,n)=>e===t[n]),d=(e,t)=>f(e)===t,f=e=>{let t=typeof e;return t===`object`?e===null?`null`:`object`:t===`function`?`object`:t},p={boolean:`boolean`,null:`null`,undefined:`undefined`,bigint:`a bigint`,number:`a number`,object:`an object`,string:`a string`,symbol:`a symbol`},ee={...p,function:`a function`};var te=class extends Error{};const m=e=>ne(e,te),ne=(e,t=Error)=>{throw new t(e)};var re=class extends Error{name=`ParseError`};const h=e=>ne(e,re),ie=e=>` ${e}`,g=(e,t)=>{let n={},r=Array.isArray(e),i=!1;for(let[o,s]of Object.entries(e).entries()){let e=r?t(o,s[1]):t(...s,o);i||=typeof e[0]==`number`;let c=Array.isArray(e[0])||e.length===0?e:[e];for(let[e,t]of c)typeof e==`object`?n[e.group]=a(n[e.group],t):n[e]=t}return i?Object.values(n):n},ae=Object.entries,_=(e,t)=>e in t,oe=(e,t)=>t in e;var se=class{constructor(e){Object.assign(this,e)}};const ce=class{};var le=class extends ce{};const ue=(e,t)=>{let n={},r={},i;for(i in e)i in t?n[i]=e[i]:r[i]=e[i];return[n,r]},de=(e,t)=>ue(e,t)[1],fe=e=>Object.keys(e).length===0,pe=e=>[...Object.entries(e),...Object.getOwnPropertySymbols(e).map(t=>[t,e[t]])],me=(e,t)=>Object.defineProperties(e,Object.getOwnPropertyDescriptors(t)),he=e=>{let t=Object.keys(e).sort(),n={};for(let r=0;r<t.length;r++)n[t[r]]=e[t[r]];return n},v=ie(`unset​`),ge=e=>Object.values(e).filter(t=>typeof t==`number`?!0:typeof e[t]!=`number`),_e={Array,Boolean,Date,Error,Function,Map,Number,Promise,RegExp,Set,String,WeakMap,WeakSet},ve=globalThis.File??Blob,ye={ArrayBuffer,Blob,File:ve,FormData,Headers,Request,Response,URL},be={Int8Array,Uint8Array,Uint8ClampedArray,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array},xe={..._e,...ye,...be,String,Number,Boolean},Se=e=>{let t=Object.getPrototypeOf(e);for(;t?.constructor&&(!_(t.constructor.name,xe)||!(e instanceof xe[t.constructor.name]));)t=Object.getPrototypeOf(t);let n=t?.constructor?.name;if(!(n===void 0||n===`Object`))return n},Ce=e=>typeof e==`object`&&e?Se(e)??`object`:f(e),y=Array.isArray,we={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`},Te={ArrayBuffer:`an ArrayBuffer instance`,Blob:`a Blob instance`,File:`a File instance`,FormData:`a FormData instance`,Headers:`a Headers instance`,Request:`a Request instance`,Response:`a Response instance`,URL:`a URL instance`},Ee={Int8Array:`an Int8Array`,Uint8Array:`a Uint8Array`,Uint8ClampedArray:`a Uint8ClampedArray`,Int16Array:`an Int16Array`,Uint16Array:`a Uint16Array`,Int32Array:`an Int32Array`,Uint32Array:`a Uint32Array`,Float32Array:`a Float32Array`,Float64Array:`a Float64Array`,BigInt64Array:`a BigInt64Array`,BigUint64Array:`a BigUint64Array`},De={...we,...Te,...Ee},Oe=e=>{let t=Object(e).name??null;return t&&_(t,xe)&&xe[t]===e?t:null},ke=(e,t)=>{let n=e.prototype;for(;n!==null;){if(n===t.prototype)return!0;n=Object.getPrototypeOf(n)}return!1},Ae=e=>je(e,new Map),je=(e,t)=>{if(typeof e!=`object`||!e)return e;if(t?.has(e))return t.get(e);let n=Oe(e.constructor);if(n===`Date`)return new Date(e.getTime());if(n&&n!==`Array`)return e;let r=Array.isArray(e)?e.slice():Object.create(Object.getPrototypeOf(e)),i=Object.getOwnPropertyDescriptors(e);if(t){t.set(e,r);for(let e in i){let n=i[e];`get`in n||`set`in n||(n.value=je(n.value,t))}}return Object.defineProperties(r,i),r},Me=e=>{let t=v;return()=>t===v?t=e():t},Ne=e=>typeof e==`function`&&e.length===0,Pe=class extends Function{constructor(...e){let t=e.slice(0,-1),n=e[e.length-1];try{super(...t,n)}catch(t){return m(`Encountered an unexpected error while compiling your definition: Message: ${t} Source: (${e.slice(0,-1)}) => { ${e[e.length-1]} }`)}}};var b=class{constructor(e,...[t]){return Object.assign(Object.setPrototypeOf(e.bind(t?.bind??this),this.constructor.prototype),t?.attach)}};const Fe=Me(()=>{try{return Function(`return false`)()}catch{return!0}});ie(`brand`),ie(`arkInferred`),ie(`args`);var x=class{constructor(){}};const Ie={fileName:()=>{try{return((Error().stack?.split(` `)[2]?.trim()||``).match(/\(?(.+?)(?::\d+:\d+)?\)?$/)?.[1]||`unknown`).replace(/^file:\/\//,``)}catch{return`unknown`}},env:globalThis.process?.env??{}},Le=e=>e[0].toUpperCase()+e.slice(1),Re=e=>e[0].toLowerCase()+e.slice(1),ze=e=>new RegExp(Be(e),typeof e==`string`?``:e.flags),Be=e=>`^(?:${typeof e==`string`?e:e.source})$`,S={negativeLookahead:e=>`(?!${e})`,nonCapturingGroup:e=>`(?:${e})`},Ve={" ":1,"\n":1," ":1},He=`[1-9]\\d*`,Ue=e=>ze(S.negativeLookahead(`^-0\\.?0*$`)+S.nonCapturingGroup(`-?`+S.nonCapturingGroup(S.nonCapturingGroup(`0|`+He)+S.nonCapturingGroup(e.decimalPattern)+`?`)+(e.allowDecimalOnly?`|`+e.decimalPattern:``)+`?`)),We=Ue({decimalPattern:`\\.\\d*[1-9]`,allowDecimalOnly:!1}),Ge=We.test.bind(We),Ke=Ue({decimalPattern:`\\.\\d+`,allowDecimalOnly:!0});Ke.test.bind(Ke);const qe=/^-?\d*\.?\d*$/,Je=e=>e.length!==0&&qe.test(e),Ye=ze(S.negativeLookahead(`^-0$`)+`-?`+S.nonCapturingGroup(S.nonCapturingGroup(`0|`+He))),Xe=Ye.test.bind(Ye),Ze=/^-?\d+$/,Qe=Ze.test.bind(Ze),$e={number:`a number`,bigint:`a bigint`,integer:`an integer`},et=(e,t)=>`'${e}' was parsed as ${$e[t]} but could not be narrowed to a literal value. Avoid unnecessary leading or trailing zeros and other abnormal notation`,tt=(e,t)=>t===`number`?Ge(e):Xe(e),nt=(e,t)=>t===`number`?Number(e):Number.parseInt(e),rt=(e,t)=>t===`number`?Je(e):Qe(e),it=(e,t)=>st(e,`number`,t),at=(e,t)=>st(e,`number`,{...t,strict:!0}),ot=(e,t)=>st(e,`integer`,t),st=(e,t,n)=>{let r=nt(e,t);return!Number.isNaN(r)&&rt(e,t)?n?.strict?tt(e,t)?r:h(et(e,t)):r:n?.errorOnFail?h(n?.errorOnFail===!0?`Failed to parse ${$e[t]} from '${e}'`:n?.errorOnFail):void 0},ct=e=>{if(e[e.length-1]!==`n`)return;let t=e.slice(0,-1),n;try{n=BigInt(t)}catch{return}if(Ye.test(t))return n;if(Ze.test(t))return h(et(e,`bigint`))},lt={version:`0.56.0`,filename:Ie.fileName(),FileConstructor:ve},ut=new Map,dt=Object.create(null),ft=e=>{let t=ut.get(e);if(t)return t;let n=mt(e);return dt[n]?n=`${n}${dt[n]++}`:dt[n]=1,lt[n]=e,ut.set(e,n),n},pt=e=>/^[$A-Z_a-z][\w$]*$/.test(e),mt=e=>{switch(typeof e){case`object`:{if(e===null)break;let t=Se(e)??`object`;return t[0].toLowerCase()+t.slice(1)}case`function`:return pt(e.name)?e.name:`fn`;case`symbol`:return e.description&&pt(e.description)?e.description:`symbol`}return m(`Unexpected attempt to register serializable value of type ${f(e)}`)},ht=e=>typeof e==`string`?JSON.stringify(e):typeof e==`bigint`?`${e}n`:`${e}`,gt=(e,t={})=>yt(e,{onUndefined:`$ark.undefined`,onBigInt:e=>`$ark.bigint-${e}`,...t},[]),C=(e,t)=>{switch(f(e)){case`object`:let n=e,r=n.constructor?.name??`Object`;return r===`Object`||r===`Array`?t?.quoteKeys===!1?_t(n,t?.indent??0,``):JSON.stringify(yt(n,vt,[]),null,t?.indent):_t(n,t?.indent??0,``);case`symbol`:return vt.onSymbol(e);default:return ht(e)}},_t=(e,t,n)=>{if(typeof e==`function`)return vt.onFunction(e);if(typeof e!=`object`||!e)return ht(e);let r=n+` `.repeat(t);if(Array.isArray(e)){if(e.length===0)return`[]`;let i=e.map(e=>_t(e,t,r)).join(`, `+r);return t?`[\n${r}${i}\n${n}]`:`[${i}]`}let i=e.constructor?.name??`Object`;if(i===`Object`){let i=pe(e).map(([e,n])=>`${r}${typeof e==`symbol`?vt.onSymbol(e):pt(e)?e:JSON.stringify(e)}: ${_t(n,t,r)}`);return i.length===0?`{}`:t?`{\n${i.join(`, `)}\n${n}}`:`{${i.join(`, `)}}`}return e instanceof Date?bt(e):`expression`in e&&typeof e.expression==`string`?e.expression:i},vt={onCycle:()=>`(cycle)`,onSymbol:e=>`Symbol(${ft(e)})`,onFunction:e=>`Function(${ft(e)})`},yt=(e,t,n)=>{switch(f(e)){case`object`:{let r=e;if(`toJSON`in r&&typeof r.toJSON==`function`)return r.toJSON();if(typeof r==`function`)return vt.onFunction(r);if(n.includes(r))return`(cycle)`;let i=[...n,r];if(Array.isArray(r))return r.map(e=>yt(e,t,i));if(r instanceof Date)return r.toDateString();let a={};for(let e in r)a[e]=yt(r[e],t,i);for(let e of Object.getOwnPropertySymbols(r))a[t.onSymbol?.(e)??e.toString()]=yt(r[e],t,i);return a}case`symbol`:return vt.onSymbol(e);case`bigint`:return t.onBigInt?.(e)??`${e}n`;case`undefined`:return t.onUndefined??`undefined`;case`string`:return e.replace(/\\/g,`\\\\`);default:return e}},bt=e=>{let t=e.getFullYear(),n=e.getMonth(),r=e.getDate(),i=e.getHours(),a=e.getMinutes(),o=e.getSeconds(),s=e.getMilliseconds();if(n===0&&r===1&&i===0&&a===0&&o===0&&s===0)return`${t}`;let c=`${xt[n]} ${r}, ${t}`;if(i===0&&a===0&&o===0&&s===0)return c;let l=e.toLocaleTimeString(),u=l.endsWith(` AM`)||l.endsWith(` PM`)?l.slice(-3):``;return u&&(l=l.slice(0,-u.length)),s?l+=`.${Ct(s,3)}`:St.test(l)&&(l=l.slice(0,-3)),`${l+u}, ${c}`},xt=[`January`,`February`,`March`,`April`,`May`,`June`,`July`,`August`,`September`,`October`,`November`,`December`],St=/:\d\d:00$/,Ct=(e,t)=>String(e).padStart(t,`0`),wt=(e,t,...[n])=>{let r=n?.stringifySymbol??C,i=e;switch(typeof t){case`string`:i=pt(t)?e===``?t:`${e}.${t}`:`${e}[${JSON.stringify(t)}]`;break;case`number`:i=`${e}[${t}]`;break;case`symbol`:i=`${e}[${r(t)}]`;break;default:n?.stringifyNonKey?i=`${e}[${n.stringifyNonKey(t)}]`:h(`${C(t)} must be a PropertyKey or stringifyNonKey must be passed to options`)}return i},Tt=(e,...t)=>e.reduce((e,n)=>wt(e,n,...t),``);var Et=class extends n{cache={};constructor(...e){super(),this.push(...e)}toJSON(){if(this.cache.json)return this.cache.json;this.cache.json=[];for(let e=0;e<this.length;e++)this.cache.json.push(typeof this[e]==`symbol`?C(this[e]):this[e]);return this.cache.json}stringify(){return this.cache.stringify?this.cache.stringify:this.cache.stringify=Tt(this)}stringifyAncestors(){if(this.cache.stringifyAncestors)return this.cache.stringifyAncestors;let e=``,t=[e];for(let n of this)e=wt(e,n),t.push(e);return this.cache.stringifyAncestors=t}},Dt=class{chars;i;def;constructor(e){this.def=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&&!e(this,t);)t+=this.shift();return t}shiftUntilEscapable(e){let t=``;for(;this.lookahead;)if(this.lookahead===`\\`)this.shift(),e(this,t)||this.lookahead===`\\`?t+=this.shift():t+=`\\${this.shift()}`;else if(e(this,t))break;else t+=this.shift();return t}shiftUntilLookahead(e){return typeof e==`string`?this.shiftUntil(t=>t.lookahead===e):this.shiftUntil(t=>t.lookahead in e)}shiftUntilNonWhitespace(){return this.shiftUntil(()=>!(this.lookahead in Ve))}jumpToIndex(e){this.i=e<0?this.length+e:e}jumpForward(e){this.i+=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}};const Ot=(e,t)=>`Unmatched ${e}${t===``?``:` before ${t}`}`,kt=e=>`Missing ${e}`;ie(`implementedTraits`),Symbol.hasInstance;let At=`$ark`,jt=2;for(;At in globalThis;)At=`$ark${jt++}`;const Mt=At;globalThis[Mt]=lt;const w=lt,Nt=e=>`${Mt}.${e}`,T=e=>Nt(ft(e));var Pt=class extends le{argNames;body=``;constructor(...e){super(),this.argNames=e;for(let t of e){if(t in this)throw 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 Ft(e,t)}index(e,t=!1){return Lt(`${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,n=0){return this.block(`for (let i = ${n}; ${e}; i++)`,t)}forIn(e,t){return this.block(`for (const k in ${e})`,t)}block(e,t,n=``){return this.line(`${e} {`),this.indent(),t(this),this.dedent(),this.line(`}${n}`)}return(e=``){return this.line(`return ${e}`)}write(e=`anonymous`,t=0){return`${e}(${this.argNames.join(`, `)}) { ${t?this.body.split(` `).map(e=>` `.repeat(t)+`${e}`).join(` `):this.body} }`}compile(){return new Pe(...this.argNames,this.body)}};const E=e=>d(e,`object`)||typeof e==`symbol`?T(e):ht(e),Ft=(e,t=!1)=>typeof e==`string`&&pt(e)?`${t?`?`:``}.${e}`:Lt(It(e),t),It=e=>typeof e==`symbol`?T(e):JSON.stringify(e),Lt=(e,t=!1)=>`${t?`?.`:``}[${e}]`;var Rt=class extends Pt{traversalKind;optimistic;constructor(e){super(`data`,`ctx`),this.traversalKind=e.kind,this.optimistic=e.optimistic===!0}invoke(e,t){let n=t?.arg??this.data,r=typeof e==`string`?!0:this.requiresContextFor(e),i=typeof e==`string`?e:e.id;return r?`${this.referenceToId(i,t)}(${n}, ${this.ctx})`:`${this.referenceToId(i,t)}(${n})`}referenceToId(e,t){let n=`this.${e}${t?.kind??this.traversalKind}`;return t?.bind?`${n}.bind(${t?.bind})`:n}requiresContextFor(e){return this.traversalKind===`Apply`||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,n){let r=this.requiresContextFor(n);return r&&this.line(`${this.ctx}.path.push(${e})`),this.check(n,{arg:t}),r&&this.line(`${this.ctx}.path.pop()`),this}check(e,t){return this.traversalKind===`Allows`?this.if(`!${this.invoke(e,t)}`,()=>this.return(!1)):this.line(this.invoke(e,t))}};const zt=e=>g(e,(e,t)=>[e,y(t)?[...t]:t]),D=ie(`arkKind`),O=(e,t)=>e?.[D]===t,k=e=>O(e,`root`)||O(e,`constraint`),Bt=[`unit`,`proto`,`domain`],Vt=[`required`,`optional`,`index`,`sequence`],Ht=[`pattern`,`divisor`,`exactLength`,`max`,`min`,`maxLength`,`minLength`,`before`,`after`],Ut=[...Ht,`structure`,`predicate`],Wt=[...Ut,...Vt],Gt=[`alias`,`union`,`morph`,`unit`,`intersection`,`proto`,`domain`],Kt=[...Gt,...Wt],qt=g(Wt,(e,t)=>[t,1]),Jt=g([...Vt,`undeclared`],(e,t)=>[t,1]),Yt=g(Kt,(e,t)=>[t,e]),Xt=e=>typeof e==`string`&&e in Yt,Zt=e=>Yt[e],Qt=e=>Gt.slice(Zt(e)+1);[...Qt(`union`)],[...Qt(`morph`)];const A=e=>typeof e==`string`||typeof e==`boolean`||e===null?e:typeof e==`number`?Number.isNaN(e)?`NaN`:e===1/0?`Infinity`:e===-1/0?`-Infinity`:e:E(e),$t=e=>{let t=`{ `;for(let[n,r]of Object.entries(e))t+=`${n}: ${E(r)}, `;return t+` }`},j=e=>{let t=e;return t.hasAssociatedError&&(t.defaults.expected??=e=>`description`in e?e.description:t.defaults.description(e),t.defaults.actual??=e=>C(e),t.defaults.problem??=e=>`must be ${e.expected}${e.actual?` (was ${e.actual})`:``}`,t.defaults.message??=e=>{if(e.path.length===0)return e.problem;let t=`${e.propString} ${e.problem}`;return t[0]===`[`?`value at ${t}`:t}),t},M={Error:class extends Error{name=`ToJsonSchemaError`;code;context;constructor(e,t){super(C(t,{quoteKeys:!1,indent:4})),this.code=e,this.context=t}hasCode(e){return this.code===e}},throw:(...e)=>{throw new M.Error(...e)},throwInternalOperandError:(e,t)=>m(`Unexpected JSON Schema input for ${e}: ${C(t)}`),defaultConfig:{target:`draft-2020-12`,dialect:`https://json-schema.org/draft/2020-12/schema`,useRefs:!1,fallback:{arrayObject:e=>M.throw(`arrayObject`,e),arrayPostfix:e=>M.throw(`arrayPostfix`,e),defaultValue:e=>M.throw(`defaultValue`,e),domain:e=>M.throw(`domain`,e),morph:e=>M.throw(`morph`,e),patternIntersection:e=>M.throw(`patternIntersection`,e),predicate:e=>M.throw(`predicate`,e),proto:e=>M.throw(`proto`,e),symbolKey:e=>M.throw(`symbolKey`,e),unit:e=>M.throw(`unit`,e),date:e=>M.throw(`date`,e)}}};w.config??={};const en=(e,t)=>{if(!t)return e;let n={...e},r;for(r in t){let i={...e.keywords};if(r===`keywords`){for(let e in t[r]){let n=t.keywords[e];n!==void 0&&(i[e]=typeof n==`string`?{description:n}:n)}n.keywords=i}else r===`toJsonSchema`?n[r]=nn(e.toJsonSchema,t.toJsonSchema):Xt(r)?n[r]={...e[r],...t[r]}:n[r]=t[r]}return n},tn={"draft-2020-12":`https://json-schema.org/draft/2020-12/schema`,"draft-07":`http://json-schema.org/draft-07/schema#`},nn=((e,t)=>{if(!e)return rn(t??{},void 0);if(!t)return e;let n={...e},r;for(r in t)r===`fallback`?n.fallback=an(e.fallback,t.fallback):n[r]=t[r];return rn(n,t)}),rn=(e,t)=>t?.dialect===void 0?t?.target===void 0?e:{...e,dialect:tn[t.target]}:e,an=(e,t)=>{e=on(e),t=on(t);let n={},r;for(r in M.defaultConfig.fallback)n[r]=t[r]??t.default??e[r]??e.default??M.defaultConfig.fallback[r];return n},on=e=>typeof e==`function`?{default:e}:e??{};var sn=class e extends le{[D]=`error`;path;data;nodeConfig;input;ctx;constructor({prefixPath:e,relativePath:t,...n},r){super(),this.input=n,this.ctx=r,me(this,n);let i=r.data;n.code===`union`&&(n.errors=n.errors.flatMap(n=>{let r=n.hasCode(`union`)?n.errors:[n];return!e&&!t?r:r.map(n=>n.transform(n=>({...n,path:s(e,n.path,t)})))})),this.nodeConfig=r.config[this.code];let a=[...n.path??r.path];t&&a.push(...t),e&&a.unshift(...e),this.path=new Et(...a),this.data=`data`in n?n.data:i}transform(t){return new e(t({data:this.data,path:this.path,...this.input}),this.ctx)}hasCode(e){return this.code===e}get propString(){return Tt(this.path)}get expected(){if(this.input.expected)return this.input.expected;let e=this.meta?.expected??this.nodeConfig.expected;return typeof e==`function`?e(this.input):e}get actual(){if(this.input.actual)return this.input.actual;let e=this.meta?.actual??this.nodeConfig.actual;return typeof e==`function`?e(this.data):e}get problem(){if(this.input.problem)return this.input.problem;let e=this.meta?.problem??this.nodeConfig.problem;return typeof e==`function`?e(this):e}get message(){if(this.input.message)return this.input.message;let e=this.meta?.message??this.nodeConfig.message;return typeof e==`function`?e(this):e}get flat(){return this.hasCode(`intersection`)?[...this.errors]:[this]}toJSON(){return{data:this.data,path:this.path,...this.input,expected:this.expected,actual:this.actual,problem:this.problem,message:this.message}}toString(){return this.message}throw(){throw this}},N=class e extends n{[D]=`errors`;ctx;constructor(e){super(),this.ctx=e}byPath=Object.create(null);get flatByPath(){return g(this.byPath,(e,t)=>[e,t.flat])}get flatProblemsByPath(){return g(this.byPath,(e,t)=>[e,t.flat.map(e=>e.problem)])}byAncestorPath=Object.create(null);count=0;mutable=this;throw(){throw this.toTraversalError()}toTraversalError(){return new cn(this)}add(e){let t=this.byPath[e.propString];if(t){if(e===t||t.hasCode(`union`)&&t.errors.length===0)return;let n=e.hasCode(`union`)&&e.errors.length===0?e:new sn({code:`intersection`,errors:t.hasCode(`intersection`)?[...t.errors,e]:[t,e]},this.ctx),r=this.indexOf(t);this.mutable[r===-1?this.length:r]=n,this.byPath[e.propString]=n,this.addAncestorPaths(e)}else this.byPath[e.propString]=e,this.addAncestorPaths(e),this.mutable.push(e);this.count++}transform(t){let n=new e(this.ctx);for(let e of this)n.add(t(e));return n}merge(e){for(let t of e)this.add(new sn({...t,path:[...this.ctx.path,...t.path]},this.ctx))}affectsPath(e){return this.length===0?!1:e.stringifyAncestors().some(e=>e in this.byPath)||e.stringify()in this.byAncestorPath}get summary(){return this.toString()}get issues(){return this}toJSON(){return[...this.map(e=>e.toJSON())]}toString(){return this.join(` `)}addAncestorPaths(e){for(let t of e.path.stringifyAncestors())this.byAncestorPath[t]=a(this.byAncestorPath[t],e)}},cn=class extends Error{name=`TraversalError`;constructor(e){e.length===1?super(e.summary):super(` `+e.map(e=>` • ${ln(e)}`).join(` `)),Object.defineProperty(this,`arkErrors`,{value:e,enumerable:!1})}};const ln=e=>e.toString().split(` `).join(` `);var P=class{path=[];errors=new N(this);root;config;queuedMorphs=[];branches=[];seen={};constructor(e,t){this.root=e,this.config=t}get data(){let e=this.root;for(let t of this.path)e=e?.[t];return e}get propString(){return Tt(this.path)}reject(e){return this.error(e),!1}mustBe(e){return this.error(e),!1}error(e){let t=typeof e==`object`?e.code?e:{...e,code:`predicate`}:{code:`predicate`,expected:e};return this.errorFromContext(t)}hasError(){return this.currentErrorCount!==0}get currentBranch(){return this.branches[this.branches.length-1]}queueMorphs(e){let t={path:new Et(...this.path),morphs:e};this.currentBranch?this.currentBranch.queuedMorphs.push(t):this.queuedMorphs.push(t)}finalize(e){return this.queuedMorphs.length&&(typeof this.root==`object`&&this.root!==null&&this.config.clone&&(this.root=this.config.clone(this.root)),this.applyQueuedMorphs()),this.hasError()?e?e(this.errors):this.errors:this.root}get currentErrorCount(){return this.currentBranch?this.currentBranch.error?1:0:this.errors.count}get failFast(){return this.branches.length!==0}pushBranch(){this.branches.push({error:void 0,queuedMorphs:[]})}popBranch(){return this.branches.pop()}get external(){return this}errorFromNodeContext(e){return this.errorFromContext(e)}errorFromContext(e){let t=new sn(e,this);return this.currentBranch?this.currentBranch.error=t:this.errors.add(t),t}applyQueuedMorphs(){for(;this.queuedMorphs.length;){let e=this.queuedMorphs;this.queuedMorphs=[];for(let{path:t,morphs:n}of e)this.errors.affectsPath(t)||this.applyMorphsAtPath(t,n)}}applyMorphsAtPath(e,t){let n=e[e.length-1],r;if(n!==void 0){r=this.root;for(let t=0;t<e.length-1;t++)r=r[e[t]]}for(let i of t){this.path=[...e];let t=k(i),a=i(r===void 0?this.root:r[n],this);if(a instanceof sn){this.errors.includes(a)||this.errors.add(a);break}if(a instanceof N){t||this.errors.merge(a),this.queuedMorphs=[];break}r===void 0?this.root=a:r[n]=a,this.applyQueuedMorphs()}}};const F=(e,t,n)=>{if(!n)return t();n.path.push(e);let r=t();return n.path.pop(),r};var un=class extends b{attachments;$;onFail;includesTransform;includesContextualPredicate;isCyclic;allowsRequiresContext;rootApplyStrategy;contextFreeMorph;rootApply;referencesById;shallowReferences;flatRefs;flatMorphs;allows;get shallowMorphs(){return[]}constructor(e,t){super((e,t,n=this.onFail)=>t?(this.traverseApply(e,t),t.hasError()?t.errors:t.data):this.rootApply(e,n),{attach:e}),this.attachments=e,this.$=t,this.onFail=this.meta.onFail??this.$.resolvedConfig.onFail,this.includesTransform=this.hasKind(`morph`)||this.hasKind(`structure`)&&this.structuralMorph!==void 0||this.hasKind(`sequence`)&&this.inner.defaultables!==void 0,this.includesContextualPredicate=this.hasKind(`predicate`)&&this.inner.predicate.length!==1,this.isCyclic=this.kind===`alias`,this.referencesById={[this.id]:this},this.shallowReferences=this.hasKind(`structure`)?[this,...this.children]:this.children.reduce((e,t)=>vn(e,t.shallowReferences),[this]);let n=this.isStructural();this.flatRefs=[],this.flatMorphs=[];for(let e=0;e<this.children.length;e++){if(this.includesTransform||=this.children[e].includesTransform,this.includesContextualPredicate||=this.children[e].includesContextualPredicate,this.isCyclic||=this.children[e].isCyclic,!n){let t=this.children[e].flatRefs;for(let e=0;e<t.length;e++){let n=t[e];if(!this.flatRefs.some(e=>gn(e,n))){this.flatRefs.push(n);for(let e of n.node.branches)(e.hasKind(`morph`)||e.hasKind(`intersection`)&&e.structure?.structuralMorph!==void 0)&&this.flatMorphs.push({path:n.path,propString:n.propString,node:e})}}}Object.assign(this.referencesById,this.children[e].referencesById)}this.flatRefs.sort((e,t)=>e.path.length>t.path.length?1:e.path.length<t.path.length?-1:e.propString>t.propString?1:e.propString<t.propString||e.node.expression<t.node.expression?-1:1),this.allowsRequiresContext=this.includesContextualPredicate||this.isCyclic,this.rootApplyStrategy=!this.allowsRequiresContext&&this.flatMorphs.length===0?this.shallowMorphs.length===0?`allows`:this.shallowMorphs.every(e=>e.length===1||e.name===`$arkStructuralMorph`)?this.hasKind(`union`)?this.branches.some(e=>e.shallowMorphs.length>1)?`contextual`:`branchedOptimistic`:this.shallowMorphs.length>1?`contextual`:`optimistic`:`contextual`:`contextual`,this.rootApply=this.createRootApply(),this.allows=this.allowsRequiresContext?e=>this.traverseAllows(e,new P(e,this.$.resolvedConfig)):e=>this.traverseAllows(e)}createRootApply(){switch(this.rootApplyStrategy){case`allows`:return(e,t)=>{if(this.allows(e))return e;let n=new P(e,this.$.resolvedConfig);return this.traverseApply(e,n),n.finalize(t)};case`contextual`:return(e,t)=>{let n=new P(e,this.$.resolvedConfig);return this.traverseApply(e,n),n.finalize(t)};case`optimistic`:this.contextFreeMorph=this.shallowMorphs[0];let e=this.$.resolvedConfig.clone;return(t,n)=>{if(this.allows(t))return this.contextFreeMorph(e&&(typeof t==`object`&&t||typeof t==`function`)?e(t):t);let r=new P(t,this.$.resolvedConfig);return this.traverseApply(t,r),r.finalize(n)};case`branchedOptimistic`:return this.createBranchedOptimisticRootApply();default:return this.rootApplyStrategy,m(`Unexpected rootApplyStrategy ${this.rootApplyStrategy}`)}}compiledMeta=hn(this.metaJson);cacheGetter(e,t){return Object.defineProperty(this,e,{value:t}),t}get description(){return this.cacheGetter(`description`,this.meta?.description??this.$.resolvedConfig[this.kind].description(this))}get references(){return Object.values(this.referencesById)}precedence=Zt(this.kind);precompilation;assert=(e,t)=>this(e,t,e=>e.throw());traverse(e,t){return this(e,t,null)}get in(){return this.cacheGetter(`in`,this.rawIn.isRoot()?this.$.finalize(this.rawIn):this.rawIn)}get rawIn(){return this.cacheGetter(`rawIn`,this.getIo(`in`))}get out(){return this.cacheGetter(`out`,this.rawOut.isRoot()?this.$.finalize(this.rawOut):this.rawOut)}get rawOut(){return this.cacheGetter(`rawOut`,this.getIo(`out`))}getIo(e){if(!this.includesTransform)return this;let t={};for(let[n,r]of this.innerEntries){let i=this.impl.keys[n];if(i.reduceIo)i.reduceIo(e,t,r);else if(i.child){let i=r;t[n]=y(i)?i.map(t=>e===`in`?t.rawIn:t.rawOut):e===`in`?i.rawIn:i.rawOut}else t[n]=r}return this.$.node(this.kind,t)}toJSON(){return this.json}toString(){return`Type<${this.expression}>`}equals(e){let t=k(e)?e:this.$.parseDefinition(e);return this.innerHash===t.innerHash}ifEquals(e){return this.equals(e)?this:void 0}hasKind(e){return this.kind===e}assertHasKind(e){return this.kind!==e&&ne(`${this.kind} node was not of asserted kind ${e}`),this}hasKindIn(...e){return e.includes(this.kind)}assertHasKindIn(...e){return r(e,this.kind)||ne(`${this.kind} node was not one of asserted kinds ${e}`),this}isBasis(){return r(Bt,this.kind)}isConstraint(){return r(Wt,this.kind)}isStructural(){return r(Vt,this.kind)}isRefinement(){return r(Ut,this.kind)}isRoot(){return r(Gt,this.kind)}isUnknown(){return this.hasKind(`intersection`)&&this.children.length===0}isNever(){return this.hasKind(`union`)&&this.children.length===0}hasUnit(e){return this.hasKind(`unit`)&&this.allows(e)}hasOpenIntersection(){return this.impl.intersectionIsOpen}get nestableExpression(){return this.expression}select(e){let t=dn.normalize(e);return this._select(t)}_select(e){let t=dn.applyBoundary[e.boundary??`references`](this);return e.kind&&(t=t.filter(t=>t.kind===e.kind)),e.where&&(t=t.filter(e.where)),dn.applyMethod[e.method??`filter`](t,this,e)}transform(e,t){return this._transform(e,this._createTransformContext(t))}_createTransformContext(e){return{root:this,selected:void 0,seen:{},path:[],parseOptions:{prereduced:e?.prereduced??!1},undeclaredKeyHandling:void 0,...e}}_transform(e,t){let n=t.bindScope??this.$;if(t.seen[this.id])return this.$.lazilyResolve(t.seen[this.id]);if(t.shouldTransform?.(this,t)===!1)return this;let r;t.seen[this.id]=()=>r,this.hasKind(`structure`)&&this.undeclared!==t.undeclaredKeyHandling&&(t={...t,undeclaredKeyHandling:this.undeclared});let i=g(this.inner,(n,r)=>{if(!this.impl.keys[n].child)return[n,r];let i=r;if(!y(i)){let r=i._transform(e,t);return r?[n,r]:[]}if(i.length===0)return[n,r];let a=i.flatMap(n=>n._transform(e,t)??[]);return a.length?[n,a]:[]});delete t.seen[this.id];let a=Object.assign(i,{meta:this.meta}),o=t.selected&&!t.selected.includes(this)?a:e(this.kind,a,t);if(o===null)return null;if(k(o))return r=o;let s=Object.keys(o);return(s.length===0||s.length===1&&s[0]===`meta`)&&!fe(this.inner)?null:(this.kind===`required`||this.kind===`optional`||this.kind===`index`)&&!(`value`in o)?t.undeclaredKeyHandling?{...o,value:w.intrinsic.unknown}:null:(this.kind===`morph`&&(o.in??=w.intrinsic.unknown),r=n.node(this.kind,o,t.parseOptions))}configureReferences(t,n=`references`){let r=dn.normalize(n),i=typeof t==`string`?(e,n)=>({...n,meta:{...n.meta,description:t}}):typeof t==`function`?(e,n)=>({...n,meta:t(n.meta)}):(e,n)=>({...n,meta:{...n.meta,...t}});if(r.boundary===`self`)return this.$.node(this.kind,i(this.kind,{...this.inner,meta:this.meta}));let a=this._select(r),o=a&&e(a),s=r.boundary===`child`?(e,t)=>t.root.children.includes(e):r.boundary===`shallow`?e=>e.kind!==`structure`:()=>!0;return this.$.finalize(this.transform(i,{shouldTransform:s,selected:o}))}};const dn={applyBoundary:{self:e=>[e],child:e=>[...e.children],shallow:e=>[...e.shallowReferences],references:e=>[...e.references]},applyMethod:{filter:e=>e,assertFilter:(e,t,n)=>(e.length===0&&ne(fn(t,n)),e),find:e=>e[0],assertFind:(e,t,n)=>(e.length===0&&ne(fn(t,n)),e[0])},normalize:e=>typeof e==`function`?{boundary:`references`,method:`filter`,where:e}:typeof e==`string`?_(e,dn.applyBoundary)?{method:`filter`,boundary:e}:{boundary:`references`,method:`filter`,kind:e}:{boundary:`references`,method:`filter`,...e}},fn=(e,t)=>`${e} had no references matching ${C(t)}.`,pn=e=>Tt(e,{stringifyNonKey:e=>e.expression}),mn=/"(\$ark\.[^"]+)"/g,hn=e=>JSON.stringify(e).replace(mn,`$1`),I=(e,t)=>({path:e,node:t,propString:pn(e)}),gn=(e,t)=>e.propString===t.propString&&e.node.equals(t.node),_n=(e,t)=>c(e,t,{isEqual:gn}),vn=(e,t)=>c(e,t,{isEqual:(e,t)=>e.equals(t)});var L=class e extends Array{static init(t,n,r,i){return new e({kind:t,l:n,r,path:i?.path??[],optional:i?.optional??!1})}add(e,t,n,r){return this.push({kind:e,l:t,r:n,path:r?.path??[],optional:r?.optional??!1}),this}get summary(){return this.describeReasons()}describeReasons(){if(this.length===1){let{path:e,l:t,r:n}=this[0],r=Tt(e);return xn(`Intersection${r&&` at ${r}`} of ${yn(t,n)}`)}return`The following intersections result in unsatisfiable types:\n• ${this.map(({path:e,l:t,r:n})=>`${e}: ${yn(t,n)}`).join(` • `)}`}throw(){return h(this.describeReasons())}invert(){let t=this.map(e=>({...e,l:e.r,r:e.l}));return t instanceof e?t:new e(...t)}withPrefixKey(e,t){return this.map(n=>({...n,path:[e,...n.path],optional:n.optional||t===`optional`}))}toNeverIfDisjoint(){return w.intrinsic.never}};const yn=(e,t)=>`${bn(e)} and ${bn(t)}`,bn=e=>k(e)?e.expression:y(e)?e.map(bn).join(` | `)||`never`:String(e),xn=e=>`${e} results in an unsatisfiable type`,R={},z=(e,t,n)=>B(e,t,{$:n,invert:!1,pipe:!1}),Sn=(e,t,n)=>B(e,t,{$:n,invert:!1,pipe:!0}),B=((e,t,n)=>{let r=n.pipe?`|>`:`&`,i=`${e.hash}${r}${t.hash}`;if(R[i]!==void 0)return R[i];if(!n.pipe){let n=`${t.hash}${r}${e.hash}`;if(R[n]!==void 0){let e=R[n],t=e instanceof L?e.invert():e;return R[i]=t,t}}let a=!n.pipe||!e.includesTransform&&!t.includesTransform;if(a&&e.equals(t))return e;let o=a?Cn(e,t,n):e.hasKindIn(...Gt)?wn(e,t,n):Cn(e,t,n);return k(o)&&(e.equals(o)?o=e:t.equals(o)&&(o=t)),R[i]=o,o}),Cn=(e,t,n)=>{let r=e.precedence<t.precedence?e.kind:t.kind,i=e.impl.intersections[t.kind]??t.impl.intersections[e.kind];if(i===void 0)return null;if(r===e.kind)return i(e,t,n);{let r=i(t,e,{...n,invert:!n.invert});return r instanceof L&&(r=r.invert()),r}},wn=(e,t,n)=>e.includesTransform||t.includesTransform?n.invert?Tn(t,e,n):Tn(e,t,n):Cn(e,t,n),Tn=(e,t,n)=>e.distribute(e=>En(e,t,n),r=>{let i=r.filter(k);if(i.length===0)return L.init(`union`,e.branches,t.branches);if(i.length<e.branches.length||!e.branches.every((e,t)=>e.rawIn.equals(i[t].rawIn)))return n.$.parseSchema(i);if(i.length===1)return i[0];let a={branches:i};return n.$.parseSchema(a)}),En=(e,t,n)=>{if(e.hasKind(`morph`)){let r=[...e.morphs];if(e.lastMorphIfNode){let i=B(e.lastMorphIfNode,t,n);if(i instanceof L)return i;r[r.length-1]=i}else r.push(t);return n.$.node(`morph`,{morphs:r,in:e.inner.in})}if(t.hasKind(`morph`)){let r=B(e,t.rawIn,n);return r instanceof L?r:n.$.node(`morph`,{morphs:[t],in:r})}return n.$.node(`morph`,{morphs:[t],in:e})};var V=class extends un{constructor(e,t){super(e,t),Object.defineProperty(this,D,{value:`constraint`,enumerable:!1})}impliedSiblings;intersect(e){return z(this,e,this.$)}},Dn=class extends V{traverseApply=(e,t)=>{this.traverseAllows(e,t)||t.errorFromNodeContext(this.errorContext)};compile(e){e.traversalKind===`Allows`?e.return(this.compiledCondition):e.if(this.compiledNegation,()=>e.line(`ctx.errorFromNodeContext(${this.compiledErrorContext})`))}get errorContext(){return{code:this.kind,description:this.description,meta:this.meta,...this.inner}}get compiledErrorContext(){return $t(this.errorContext)}};const H=e=>(t,n)=>{if(y(t)){if(t.length===0)return;let r=t.map(t=>n.$.node(e,t));return e===`predicate`?r:r.sort((e,t)=>e.hash<t.hash?-1:1)}let r=n.$.node(e,t);return r.hasOpenIntersection()?[r]:r},On=e=>{let t=e.r.shift();if(!t){let t=e.l.length===0&&e.kind===`structure`?w.intrinsic.unknown.internal:e.ctx.$.node(e.kind,Object.assign(e.baseInner,An(e.l)),{prereduced:!0});for(let n of e.roots){if(t instanceof L)return t;t=B(n,t,e.ctx)}return t}let n=!1;for(let r=0;r<e.l.length;r++){let i=B(e.l[r],t,e.ctx);if(i!==null){if(i instanceof L)return i;if(i.isRoot())return e.roots.push(i),e.l.splice(r),On(e);if(!n)e.l[r]=i,n=!0;else if(!e.l.includes(i))return m(`Unexpectedly encountered multiple distinct intersection results for refinement ${t}`)}}if(n||e.l.push(t),e.kind===`intersection`&&t.impliedSiblings)for(let n of t.impliedSiblings)c(e.r,n);return On(e)},kn=e=>Object.entries(e).flatMap(([e,t])=>e in qt?t:[]).sort((e,t)=>e.precedence<t.precedence?-1:e.precedence>t.precedence?1:e.kind===`predicate`&&t.kind===`predicate`?0:e.hash<t.hash?-1:1),An=e=>{let t={};for(let n of e)if(n.hasOpenIntersection())t[n.kind]=a(t[n.kind],n);else{if(t[n.kind])return m(`Unexpected intersection of closed refinements of kind ${n.kind}`);t[n.kind]=n}return t},jn=(...e)=>h(Mn(...e)),Mn=(e,t,n)=>{let r=n.hasKind(`morph`)?`a morph`:n.isUnknown()?`unknown`:n.exclude(t).defaultShortDescription;return`${Le(e)} operand must be ${t.description} (was ${r})`},Nn=(e,t,n)=>new Fn(e,t,n,n,null);var Pn=class extends b{},Fn=class extends b{[D]=`generic`;paramDefs;bodyDef;$;arg$;baseInstantiation;hkt;description;constructor(e,t,n,r,i){super((...e)=>{let n=g(this.names,(t,n)=>{let r=this.arg$.parse(e[t]);return r.extends(this.constraints[t])||h(In(n,this.constraints[t].expression,r.expression)),[n,r]});if(this.defIsLazy()){let e=this.bodyDef(n);return this.$.parse(e)}return this.$.parse(t,{args:n})}),this.paramDefs=e,this.bodyDef=t,this.$=n,this.arg$=r,this.hkt=i,this.description=i?new i().description??`a generic type for ${i.constructor.name}`:`a generic type`,this.baseInstantiation=this(...this.constraints)}defIsLazy(){return this.bodyDef instanceof Pn}cacheGetter(e,t){return Object.defineProperty(this,e,{value:t}),t}get json(){return this.cacheGetter(`json`,{params:this.params.map(e=>e[1].isUnknown()?e[0]:[e[0],e[1].json]),body:gt(this.bodyDef)})}get params(){return this.cacheGetter(`params`,this.paramDefs.map(e=>typeof e==`string`?[e,w.intrinsic.unknown]:[e[0],this.$.parse(e[1])]))}get names(){return this.cacheGetter(`names`,this.params.map(e=>e[0]))}get constraints(){return this.cacheGetter(`constraints`,this.params.map(e=>e[1]))}get internal(){return this}get referencesById(){return this.baseInstantiation.internal.referencesById}get references(){return this.baseInstantiation.internal.references}};const In=(e,t,n)=>`${e} must be assignable to ${t} (was ${n})`,Ln={implementation:j({kind:`predicate`,hasAssociatedError:!0,collapsibleKey:`predicate`,keys:{predicate:{}},normalize:e=>typeof e==`function`?{predicate:e}:e,defaults:{description:e=>`valid according to ${e.predicate.name||`an anonymous predicate`}`},intersectionIsOpen:!0,intersections:{predicate:()=>null}}),Node:class extends V{serializedPredicate=T(this.predicate);compiledCondition=`${this.serializedPredicate}(data, ctx)`;compiledNegation=`!${this.compiledCondition}`;impliedBasis=null;expression=this.serializedPredicate;traverseAllows=this.predicate;errorContext={code:`predicate`,description:this.description,meta:this.meta};compiledErrorContext=$t(this.errorContext);traverseApply=(e,t)=>{let n=t.currentErrorCount;!this.predicate(e,t.external)&&t.currentErrorCount===n&&t.errorFromNodeContext(this.errorContext)};compile(e){if(e.traversalKind===`Allows`){e.return(this.compiledCondition);return}e.initializeErrorCount(),e.if(`${this.compiledNegation} && ctx.currentErrorCount === errorCount`,()=>e.line(`ctx.errorFromNodeContext(${this.compiledErrorContext})`))}reduceJsonSchema(e,t){return t.fallback.predicate({code:`predicate`,base:e,predicate:this.predicate})}}},Rn={implementation:j({kind:`divisor`,collapsibleKey:`rule`,keys:{rule:{parse:e=>Number.isInteger(e)?e:h(zn(e))}},normalize:e=>typeof e==`number`?{rule:e}:e,hasAssociatedError:!0,defaults:{description:e=>e.rule===1?`an integer`:e.rule===2?`even`:`a multiple of ${e.rule}`},intersections:{divisor:(e,t,n)=>n.$.node(`divisor`,{rule:Math.abs(e.rule*t.rule/Bn(e.rule,t.rule))})},obviatesBasisDescription:!0}),Node:class extends Dn{traverseAllows=e=>e%this.rule===0;compiledCondition=`data % ${this.rule} === 0`;compiledNegation=`data % ${this.rule} !== 0`;impliedBasis=w.intrinsic.number.internal;expression=`% ${this.rule}`;reduceJsonSchema(e){return e.type=`integer`,this.rule===1||(e.multipleOf=this.rule),e}}},zn=e=>`divisor must be an integer (was ${e})`,Bn=(e,t)=>{let n,r=e,i=t;for(;i!==0;)n=i,i=r%i,r=n;return r};var U=class extends Dn{boundOperandKind=Yn[this.kind];compiledActual=this.boundOperandKind===`value`?`data`:this.boundOperandKind===`length`?`data.length`:`data.valueOf()`;comparator=Xn(this.kind,this.exclusive);numericLimit=this.rule.valueOf();expression=`${this.comparator} ${this.rule}`;compiledCondition=`${this.compiledActual} ${this.comparator} ${this.numericLimit}`;compiledNegation=`${this.compiledActual} ${Vn[this.comparator]} ${this.numericLimit}`;stringLimit=this.boundOperandKind===`date`?Zn(this.numericLimit):`${this.numericLimit}`;limitKind=this.comparator[0]===`<`?`upper`:`lower`;isStricterThan(e){return(this.limitKind===`upper`?this.numericLimit<e.numericLimit:this.numericLimit>e.numericLimit)||this.numericLimit===e.numericLimit&&this.exclusive===!0&&!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 Vn={"<":`>=`,"<=":`>`,">":`<=`,">=":`<`},Hn={min:`max`,minLength:`maxLength`,after:`before`},Un={parse:e=>e||void 0},Wn=e=>t=>{if(typeof t==`number`)return{rule:t};let{exclusive:n,...r}=t;return n?{...r,rule:e===`minLength`?r.rule+1:r.rule-1}:r},Gn=e=>t=>{if(typeof t==`number`||typeof t==`string`||t instanceof Date)return{rule:t};let{exclusive:n,...r}=t;if(!n)return r;let i=typeof r.rule==`number`?r.rule:typeof r.rule==`string`?new Date(r.rule).valueOf():r.rule.valueOf();return n?{...r,rule:e===`after`?i+1:i-1}:r},Kn=e=>typeof e==`string`||typeof e==`number`?new Date(e):e,qn=(e,t)=>`${e} bound must be a positive integer (was ${t})`,Jn=e=>t=>((!Number.isInteger(t)||t<0)&&h(qn(e,t)),t),Yn={min:`value`,max:`value`,minLength:`length`,maxLength:`length`,after:`date`,before:`date`},Xn=(e,t)=>`${_(e,Hn)?`>`:`<`}${t?``:`=`}`,Zn=e=>typeof e==`string`?e:new Date(e).toLocaleString(),Qn=e=>`Bounded expression ${e} must be exactly one of number, string, Array, or Date`,$n={implementation:j({kind:`after`,collapsibleKey:`rule`,hasAssociatedError:!0,keys:{rule:{parse:Kn,serialize:e=>e.toISOString()}},normalize:Gn(`after`),defaults:{description:e=>`${e.collapsibleLimitString} or later`,actual:bt},intersections:{after:(e,t)=>e.isStricterThan(t)?e:t}}),Node:class extends U{impliedBasis=w.intrinsic.Date.internal;collapsibleLimitString=bt(this.rule);traverseAllows=e=>e>=this.rule;reduceJsonSchema(e,t){return t.fallback.date({code:`date`,base:e,after:this.rule})}}},er={implementation:j({kind:`before`,collapsibleKey:`rule`,hasAssociatedError:!0,keys:{rule:{parse:Kn,serialize:e=>e.toISOString()}},normalize:Gn(`before`),defaults:{description:e=>`${e.collapsibleLimitString} or earlier`,actual:bt},intersections:{before:(e,t)=>e.isStricterThan(t)?e:t,after:(e,t,n)=>e.overlapsRange(t)?e.overlapIsUnit(t)?n.$.node(`unit`,{unit:e.rule}):null:L.init(`range`,e,t)}}),Node:class extends U{collapsibleLimitString=bt(this.rule);traverseAllows=e=>e<=this.rule;impliedBasis=w.intrinsic.Date.internal;reduceJsonSchema(e,t){return t.fallback.date({code:`date`,base:e,before:this.rule})}}},tr={implementation:j({kind:`exactLength`,collapsibleKey:`rule`,keys:{rule:{parse:Jn(`exactLength`)}},normalize:e=>typeof e==`number`?{rule:e}:e,hasAssociatedError:!0,defaults:{description:e=>`exactly length ${e.rule}`,actual:e=>`${e.length}`},intersections:{exactLength:(e,t,n)=>L.init(`unit`,n.$.node(`unit`,{unit:e.rule}),n.$.node(`unit`,{unit:t.rule}),{path:[`length`]}),minLength:(e,t)=>e.rule>=t.rule?e:L.init(`range`,e,t),maxLength:(e,t)=>e.rule<=t.rule?e:L.init(`range`,e,t)}}),Node:class extends Dn{traverseAllows=e=>e.length===this.rule;compiledCondition=`data.length === ${this.rule}`;compiledNegation=`data.length !== ${this.rule}`;impliedBasis=w.intrinsic.lengthBoundable.internal;expression=`== ${this.rule}`;reduceJsonSchema(e){switch(e.type){case`string`:return e.minLength=this.rule,e.maxLength=this.rule,e;case`array`:return e.minItems=this.rule,e.maxItems=this.rule,e;default:return M.throwInternalOperandError(`exactLength`,e)}}}},nr={implementation:j({kind:`max`,collapsibleKey:`rule`,hasAssociatedError:!0,keys:{rule:{},exclusive:Un},normalize:e=>typeof e==`number`?{rule:e}:e,defaults:{description:e=>e.rule===0?e.exclusive?`negative`:`non-positive`:`${e.exclusive?`less than`:`at most`} ${e.rule}`},intersections:{max:(e,t)=>e.isStricterThan(t)?e:t,min:(e,t,n)=>e.overlapsRange(t)?e.overlapIsUnit(t)?n.$.node(`unit`,{unit:e.rule}):null:L.init(`range`,e,t)},obviatesBasisDescription:!0}),Node:class extends U{impliedBasis=w.intrinsic.number.internal;traverseAllows=this.exclusive?e=>e<this.rule:e=>e<=this.rule;reduceJsonSchema(e){return this.exclusive?e.exclusiveMaximum=this.rule:e.maximum=this.rule,e}}},rr={implementation:j({kind:`maxLength`,collapsibleKey:`rule`,hasAssociatedError:!0,keys:{rule:{parse:Jn(`maxLength`)}},reduce:(e,t)=>e.rule===0?t.node(`exactLength`,e):void 0,normalize:Wn(`maxLength`),defaults:{description:e=>`at most length ${e.rule}`,actual:e=>`${e.length}`},intersections:{maxLength:(e,t)=>e.isStricterThan(t)?e:t,minLength:(e,t,n)=>e.overlapsRange(t)?e.overlapIsUnit(t)?n.$.node(`exactLength`,{rule:e.rule}):null:L.init(`range`,e,t)}}),Node:class extends U{impliedBasis=w.intrinsic.lengthBoundable.internal;traverseAllows=e=>e.length<=this.rule;reduceJsonSchema(e){switch(e.type){case`string`:return e.maxLength=this.rule,e;case`array`:return e.maxItems=this.rule,e;default:return M.throwInternalOperandError(`maxLength`,e)}}}},ir={implementation:j({kind:`min`,collapsibleKey:`rule`,hasAssociatedError:!0,keys:{rule:{},exclusive:Un},normalize:e=>typeof e==`number`?{rule:e}:e,defaults:{description:e=>e.rule===0?e.exclusive?`positive`:`non-negative`:`${e.exclusive?`more than`:`at least`} ${e.rule}`},intersections:{min:(e,t)=>e.isStricterThan(t)?e:t},obviatesBasisDescription:!0}),Node:class extends U{impliedBasis=w.intrinsic.number.internal;traverseAllows=this.exclusive?e=>e>this.rule:e=>e>=this.rule;reduceJsonSchema(e){return this.exclusive?e.exclusiveMinimum=this.rule:e.minimum=this.rule,e}}},ar={implementation:j({kind:`minLength`,collapsibleKey:`rule`,hasAssociatedError:!0,keys:{rule:{parse:Jn(`minLength`)}},reduce:e=>e.rule===0?w.intrinsic.unknown:void 0,normalize:Wn(`minLength`),defaults:{description:e=>e.rule===1?`non-empty`:`at least length ${e.rule}`,actual:e=>e.length===0?``:`${e.length}`},intersections:{minLength:(e,t)=>e.isStricterThan(t)?e:t}}),Node:class extends U{impliedBasis=w.intrinsic.lengthBoundable.internal;traverseAllows=e=>e.length>=this.rule;reduceJsonSchema(e){switch(e.type){case`string`:return e.minLength=this.rule,e;case`array`:return e.minItems=this.rule,e;default:return M.throwInternalOperandError(`minLength`,e)}}}},or={min:ir.implementation,max:nr.implementation,minLength:ar.implementation,maxLength:rr.implementation,exactLength:tr.implementation,after:$n.implementation,before:er.implementation},sr={min:ir.Node,max:nr.Node,minLength:ar.Node,maxLength:rr.Node,exactLength:tr.Node,after:$n.Node,before:er.Node},cr={implementation:j({kind:`pattern`,collapsibleKey:`rule`,keys:{rule:{},flags:{}},normalize:e=>typeof e==`string`?{rule:e}:e instanceof RegExp?e.flags?{rule:e.source,flags:e.flags}:{rule:e.source}:e,obviatesBasisDescription:!0,obviatesBasisExpression:!0,hasAssociatedError:!0,intersectionIsOpen:!0,defaults:{description:e=>`matched by ${e.rule}`},intersections:{pattern:()=>null}}),Node:class extends Dn{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=w.intrinsic.string.internal;reduceJsonSchema(e,t){return e.pattern?t.fallback.patternIntersection({code:`patternIntersection`,base:e,pattern:this.rule}):(e.pattern=this.rule,e)}}},lr=(e,t)=>{let n=ur(e);return t&&!t.includes(n)?h(`Root of kind ${n} should be one of ${t}`):n},ur=e=>{if(O(e,`root`))return e.kind;if(typeof e==`string`)return e[0]===`$`?`alias`:e in p?`domain`:`proto`;if(typeof e==`function`)return`proto`;if(typeof e!=`object`||!e)return h(dr(e));if(`morphs`in e)return`morph`;if(`branches`in e||y(e))return`union`;if(`unit`in e)return`unit`;if(`reference`in e)return`alias`;let t=Object.keys(e);return t.length===0||t.some(e=>e in qt)?`intersection`:`proto`in e?`proto`:`domain`in e?`domain`:h(dr(e))},dr=e=>`${C(e)} is not a valid type schema`,fr={},pr=e=>y(e)?e.map(e=>e.collapsibleJson):e.collapsibleJson,W={};w.nodesByRegisteredId=W;const mr=e=>(fr[e]??=0,`${e}${++fr[e]}`),hr=e=>{let t=ea[e.kind],n=t.applyConfig?.(e.def,e.$.resolvedConfig)??e.def,r={},{meta:i,...a}=n,o=i===void 0?{}:typeof i==`string`?{description:i}:i,s=ae(a).sort(([e],[t])=>Xt(e)?Xt(t)?Zt(e)-Zt(t):1:Xt(t)||e<t?-1:1).filter(([e,t])=>{if(e.startsWith(`meta.`)){let n=e.slice(5);return o[n]=t,!1}return!0});for(let n of s){let i=n[0],a=t.keys[i];if(!a)return h(`Key ${i} is not valid on ${e.kind} schema`);let o=a.parse?a.parse(n[1],e):n[1];o!==v&&(o!==void 0||a.preserveUndefined)&&(r[i]=o)}if(t.reduce&&!e.prereduced){let n=t.reduce(r,e.$);if(n)return n instanceof L?n.throw():vr(n,o)}return gr({id:e.id,kind:e.kind,inner:r,meta:o,$:e.$})},gr=({id:e,kind:t,inner:n,meta:r,$:i,ignoreCache:a})=>{let o=ea[t],s=ae(n),c=[],l={};for(let[e,t]of s){let n=o.keys[e],r=n.serialize??(n.child?pr:A);if(l[e]=r(t),n.child===!0){let e=t;y(e)?c.push(...e):c.push(e)}else typeof n.child==`function`&&c.push(...n.child(t))}o.finalizeInnerJson&&(l=o.finalizeInnerJson(l));let u={...l},d={};fe(r)||(d=g(r,(e,t)=>[e,e===`examples`?t:A(t)]),u.meta=yr(d,`description`,!0)),l=yr(l,o.collapsibleKey,!1);let f=JSON.stringify({kind:t,...l});u=yr(u,o.collapsibleKey,!1);let p=yr(u,o.collapsibleKey,!0),ee=JSON.stringify({kind:t,...u});if(i.nodesByHash[ee]&&!a)return i.nodesByHash[ee];let te={id:e,kind:t,impl:o,inner:n,innerEntries:s,innerJson:l,innerHash:f,meta:r,metaJson:d,json:u,hash:ee,collapsibleJson:p,children:c};if(t!==`intersection`)for(let e in n)e!==`in`&&e!==`out`&&(te[e]=n[e]);let m=new ta[t](te,i);return i.nodesByHash[ee]=m},_r=(e,t)=>e.id===t?e:(k(W[t])&&m(`Unexpected attempt to overwrite node id ${t}`),gr({id:t,kind:e.kind,inner:e.inner,meta:e.meta,$:e.$,ignoreCache:!0})),vr=(e,t,n)=>(n&&k(W[n])&&m(`Unexpected attempt to overwrite node id ${n}`),gr({id:n??mr(t.alias??e.kind),kind:e.kind,inner:e.inner,meta:t,$:e.$})),yr=(e,t,n)=>{let r=Object.keys(e);if(r.length===1&&r[0]===t){let r=e[t];if(n||d(r,`object`)&&(Object.keys(r).length===1||Array.isArray(r)))return r}return e},br=(e,t,n)=>{if(e.key!==t.key)return null;let r=e.key,i=B(e.value,t.value,n),a=e.required||t.required?`required`:`optional`;if(i instanceof L)if(a===`optional`)i=w.intrinsic.never.internal;else return i.withPrefixKey(e.key,e.required&&t.required?`required`:`optional`);if(a===`required`)return n.$.node(`required`,{key:r,value:i});let o=e.hasDefault()?t.hasDefault()?e.default===t.default?e.default:h(Sr(e.default,t.default)):e.default:t.hasDefault()?t.default:v;return n.$.node(`optional`,{key:r,value:i,default:o})};var xr=class extends V{required=this.kind===`required`;optional=this.kind===`optional`;impliedBasis=w.intrinsic.object.internal;serializedKey=E(this.key);compiledKey=typeof this.key==`string`?this.key:this.serializedKey;flatRefs=a(this.value.flatRefs.map(e=>I([this.key,...e.path],e.node)),I([this.key],this.value));_transform(e,t){t.path.push(this.key);let n=super._transform(e,t);return t.path.pop(),n}hasDefault(){return`default`in this.inner}traverseAllows=(e,t)=>this.key in e?F(this.key,()=>this.value.traverseAllows(e[this.key],t),t):this.optional;traverseApply=(e,t)=>{this.key in e?F(this.key,()=>this.value.traverseApply(e[this.key],t),t):this.hasKind(`required`)&&t.errorFromNodeContext(this.errorContext)};compile(e){e.if(`${this.serializedKey} in data`,()=>e.traverseKey(this.serializedKey,`data${e.prop(this.key)}`,this.value)),this.hasKind(`required`)&&e.else(()=>e.traversalKind===`Apply`?e.line(`ctx.errorFromNodeContext(${this.compiledErrorContext})`):e.return(!1)),e.traversalKind===`Allows`&&e.return(!0)}};const Sr=(e,t)=>`Invalid intersection of default values ${C(e)} & ${C(t)}`,Cr={implementation:j({kind:`optional`,hasAssociatedError:!1,intersectionIsOpen:!0,keys:{key:{},value:{child:!0,parse:(e,t)=>t.$.parseSchema(e)},default:{preserveUndefined:!0}},normalize:e=>e,reduce:(e,t)=>{if(t.resolvedConfig.exactOptionalPropertyTypes===!1&&!e.value.allows(void 0))return t.node(`optional`,{...e,value:e.value.or(q.undefined)},{prereduced:!0})},defaults:{description:e=>`${e.compiledKey}?: ${e.value.description}`},intersections:{optional:br}}),Node:class extends xr{constructor(...e){super(...e),`default`in this.inner&&Dr(this.value,this.inner.default,this.key)}get rawIn(){let e=super.rawIn;return this.hasDefault()?this.$.node(`optional`,de(e.inner,{default:!0}),{prereduced:!0}):e}get outProp(){if(!this.hasDefault())return this;let{default:e,...t}=this.inner;return this.cacheGetter(`outProp`,this.$.node(`required`,t,{prereduced:!0}))}expression=this.hasDefault()?`${this.compiledKey}: ${this.value.expression} = ${C(this.inner.default)}`:`${this.compiledKey}?: ${this.value.expression}`;defaultValueMorph=Tr(this);defaultValueMorphRef=this.defaultValueMorph&&T(this.defaultValueMorph)}},wr={},Tr=e=>{if(!e.hasDefault())return;let t=`{${e.compiledKey}: ${e.value.id} = ${A(e.default)}}`;return wr[t]??=Er(e.key,e.value,e.default)},Er=(e,t,n)=>{if(typeof n==`function`)return t.includesTransform?(r,i)=>(F(e,()=>t(r[e]=n(),i),i),r):t=>(t[e]=n(),t);let r=t.includesTransform?t.assert(n):n;return d(r,`object`)?(r,i)=>(F(e,()=>t(r[e]=n,i),i),r):t=>(t[e]=r,t)},Dr=(e,t,n)=>{let r=Ne(t);d(t,`object`)&&!r&&h(Or(n));let i=e.in(r?t():t);return i instanceof N&&(n===null&&h(`Default ${i.summary}`),h(`Default for ${i.transform(e=>e.transform(e=>({...e,prefixPath:[n]}))).summary}`)),t},Or=e=>`Non-primitive default ${e===null?``:typeof e==`number`?`for value at [${e}] `:`for ${E(e)} `}must be specified as a function like () => ({my: 'object'})`;var kr=class extends un{constructor(e,t){super(e,t),Object.defineProperty(this,D,{value:`root`,enumerable:!1})}get rawIn(){return super.rawIn}get rawOut(){return super.rawOut}get internal(){return this}get"~standard"(){return{vendor:`arktype`,version:1,validate:e=>{let t=this(e);return t instanceof N?t:{value:t}},jsonSchema:{input:e=>this.rawIn.toJsonSchema({target:Nr(e.target),...e.libraryOptions}),output:e=>this.rawOut.toJsonSchema({target:Nr(e.target),...e.libraryOptions})}}}as(){return this}brand(e){return e===``?h(Ar):this}readonly(){return this}branches=this.hasKind(`union`)?this.inner.branches:[this];distribute(e,t){let n=this.branches.map(e);return t?.(n)??n}get shortDescription(){return this.meta.description??this.defaultShortDescription}toJsonSchema(e={}){let t=nn(this.$.resolvedConfig.toJsonSchema,e);t.useRefs||=this.isCyclic;let n=typeof t.dialect==`string`?{$schema:t.dialect}:{};if(Object.assign(n,this.toJsonSchemaRecurse(t)),t.useRefs){let e=g(this.references,(e,n)=>n.isRoot()&&!n.alwaysExpandJsonSchema?[n.id,n.toResolvedJsonSchema(t)]:[]);t.target===`draft-07`?Object.assign(n,{definitions:e}):n.$defs=e}return n}toJsonSchemaRecurse(e){return e.useRefs&&!this.alwaysExpandJsonSchema?{$ref:`#/${e.target===`draft-07`?`definitions`:`$defs`}/${this.id}`}:this.toResolvedJsonSchema(e)}get alwaysExpandJsonSchema(){return this.isBasis()||this.kind===`alias`||this.hasKind(`union`)&&this.isBoolean}toResolvedJsonSchema(e){let t=this.innerToJsonSchema(e);return Object.assign(t,this.metaJson)}intersect(e){let t=this.$.parseDefinition(e),n=this.rawIntersect(t);return n instanceof L?n:this.$.finalize(n)}rawIntersect(e){return z(this,e,this.$)}toNeverIfDisjoint(){return this}and(e){let t=this.intersect(e);return t instanceof L?t.throw():t}rawAnd(e){let t=this.rawIntersect(e);return t instanceof L?t.throw():t}or(e){let t=this.$.parseDefinition(e);return this.$.finalize(this.rawOr(t))}rawOr(e){let t=[...this.branches,...e.branches];return this.$.node(`union`,t)}map(e){return this.$.schema(this.applyStructuralOperation(`map`,[e]))}pick(...e){return this.$.schema(this.applyStructuralOperation(`pick`,e))}omit(...e){return this.$.schema(this.applyStructuralOperation(`omit`,e))}required(){return this.$.schema(this.applyStructuralOperation(`required`,[]))}partial(){return this.$.schema(this.applyStructuralOperation(`partial`,[]))}_keyof;keyof(){if(this._keyof)return this._keyof;let e=this.applyStructuralOperation(`keyof`,[]).reduce((e,t)=>e.intersect(t).toNeverIfDisjoint(),w.intrinsic.unknown.internal);return e.branches.length===0&&h(xn(`keyof ${this.expression}`)),this._keyof=this.$.finalize(e)}get props(){return this.branches.length===1?[...this.applyStructuralOperation(`props`,[])[0]]:h(Lr(this.expression))}merge(e){let t=this.$.parseDefinition(e);return this.$.schema(t.distribute(e=>this.applyStructuralOperation(`merge`,[Ir(e)??h(Rr(`merge`,e.expression))])))}applyStructuralOperation(e,t){return this.distribute(n=>{if(n.equals(w.intrinsic.object)&&e!==`merge`)return n;let r=Ir(n);if(r||h(Rr(e,n.expression)),e===`keyof`)return r.keyof();if(e===`get`)return r.get(...t);if(e===`props`)return r.props;let i=e===`required`?`require`:e===`partial`?`optionalize`:e;return this.$.node(`intersection`,{domain:`object`,structure:r[i](...t)})})}get(...e){return e[0]===void 0?this:this.$.schema(this.applyStructuralOperation(`get`,e))}extract(e){let t=this.$.parseDefinition(e);return this.$.schema(this.branches.filter(e=>e.extends(t)))}exclude(e){let t=this.$.parseDefinition(e);return this.$.schema(this.branches.filter(e=>!e.extends(t)))}array(){return this.$.schema(this.isUnknown()?{proto:Array}:{proto:Array,sequence:this},{prereduced:!0})}overlaps(e){return!(this.intersect(e)instanceof L)}extends(e){if(this.isNever())return!0;let t=this.intersect(e);return!(t instanceof L)&&this.equals(t)}ifExtends(e){return this.extends(e)?this:void 0}subsumes(e){return this.$.parseDefinition(e).extends(this)}configure(e,t=`shallow`){return this.configureReferences(e,t)}describe(e,t=`shallow`){return this.configure({description:e},t)}optional(){return[this,`?`]}default(e){return Dr(this,e,null),[this,`=`,e]}from(e){return this.assert(e)}_pipe(...e){let t=e.reduce((e,t)=>e.rawPipeOnce(t),this);return this.$.finalize(t)}tryPipe(...e){let t=e.reduce((e,t)=>e.rawPipeOnce(O(t,`root`)?t:((e,n)=>{try{return t(e,n)}catch(e){return n.error({code:`predicate`,predicate:t,actual:`aborted due to error:\n ${e}\n`})}})),this);return this.$.finalize(t)}pipe=Object.assign(this._pipe.bind(this),{try:this.tryPipe.bind(this)});to(e){return this.$.finalize(this.toNode(this.$.parseDefinition(e)))}toNode(e){let t=Sn(this,e,this.$);return t instanceof L?t.throw():t}rawPipeOnce(e){return O(e,`root`)?this.toNode(e):this.distribute(t=>t.hasKind(`morph`)?this.$.node(`morph`,{in:t.inner.in,morphs:[...t.morphs,e]}):this.$.node(`morph`,{in:t,morphs:[e]}),this.$.parseSchema)}narrow(e){return this.constrainOut(`predicate`,e)}constrain(e,t){return this._constrain(`root`,e,t)}constrainIn(e,t){return this._constrain(`in`,e,t)}constrainOut(e,t){return this._constrain(`out`,e,t)}_constrain(e,t,n){let r=this.$.node(t,n);if(r.isRoot())return r.isUnknown()?this:m(`Unexpected constraint node ${r}`);let i=e===`root`?this:e===`in`?this.rawIn:this.rawOut;if(i.hasKind(`morph`)||r.impliedBasis&&!i.extends(r.impliedBasis))return jn(t,r.impliedBasis,this);let a=this.$.node(`intersection`,{[r.kind]:r}),o=e===`out`?Sn(this,a,this.$):z(this,a,this.$);return o instanceof L&&o.throw(),this.$.finalize(o)}onUndeclaredKey(e){let t=typeof e==`string`?e:e.rule,n=typeof e==`string`?!1:e.deep;return this.$.finalize(this.transform((e,n)=>e===`structure`?t===`ignore`?de(n,{undeclared:1}):{...n,undeclared:t}:n,n?void 0:{shouldTransform:e=>!r(Vt,e.kind)}))}hasEqualMorphs(e){return!this.includesTransform&&!e.includesTransform?!0:!(!u(this.shallowMorphs,e.shallowMorphs)||!u(this.flatMorphs,e.flatMorphs,{isEqual:(e,t)=>e.propString===t.propString&&(e.node.hasKind(`morph`)&&t.node.hasKind(`morph`)?e.node.hasEqualMorphs(t.node):e.node.hasKind(`intersection`)&&t.node.hasKind(`intersection`)?e.node.structure?.structuralMorphRef===t.node.structure?.structuralMorphRef:!1)}))}onDeepUndeclaredKey(e){return this.onUndeclaredKey({rule:e,deep:!0})}filter(e){return this.constrainIn(`predicate`,e)}divisibleBy(e){return this.constrain(`divisor`,e)}matching(e){return this.constrain(`pattern`,e)}atLeast(e){return this.constrain(`min`,e)}atMost(e){return this.constrain(`max`,e)}moreThan(e){return this.constrain(`min`,Pr(e))}lessThan(e){return this.constrain(`max`,Pr(e))}atLeastLength(e){return this.constrain(`minLength`,e)}atMostLength(e){return this.constrain(`maxLength`,e)}moreThanLength(e){return this.constrain(`minLength`,Pr(e))}lessThanLength(e){return this.constrain(`maxLength`,Pr(e))}exactlyLength(e){return this.constrain(`exactLength`,e)}atOrAfter(e){return this.constrain(`after`,e)}atOrBefore(e){return this.constrain(`before`,e)}laterThan(e){return this.constrain(`after`,Pr(e))}earlierThan(e){return this.constrain(`before`,Pr(e))}};const Ar=`Expected a non-empty brand name after #`,jr=[`draft-2020-12`,`draft-07`],Mr=e=>`JSONSchema target '${e}' is not supported (must be ${jr.map(e=>`"${e}"`).join(` or `)})`,Nr=e=>(r(jr,e)||h(Mr(e)),e),Pr=e=>typeof e==`object`&&!(e instanceof Date)?{...e,exclusive:!0}:{rule:e,exclusive:!0},Fr=(e,t)=>O(t,`root`)?O(e,`root`)?e.extends(t):t.allows(e):O(e,`root`)?e.hasUnit(t):t===e,Ir=e=>e.hasKind(`morph`)?null:e.hasKind(`intersection`)?e.inner.structure??(e.basis?.domain===`object`?e.$.bindReference(w.intrinsic.emptyStructure):null):e.isBasis()&&e.domain===`object`?e.$.bindReference(w.intrinsic.emptyStructure):null,Lr=e=>`Props cannot be extracted from a union. Use .distribute to extract props from each branch instead. Received: ${e}`,Rr=(e,t)=>`${e} operand must be an object (was ${t})`,zr=(e,t)=>g(Qt(e),(e,n)=>[n,t]),Br=e=>typeof e==`string`?{reference:e}:e,Vr=e=>e instanceof L?w.intrinsic.never.internal:e,Hr=j({kind:`alias`,hasAssociatedError:!1,collapsibleKey:`reference`,keys:{reference:{serialize:e=>e.startsWith(`$`)?e:`$ark.${e}`},resolve:{}},normalize:Br,defaults:{description:e=>e.reference},intersections:{alias:(e,t,n)=>n.$.lazilyResolve(()=>Vr(B(e.resolution,t.resolution,n)),`${e.reference}${n.pipe?`=>`:`&`}${t.reference}`),...zr(`alias`,(e,t,n)=>t.isUnknown()?e:t.isNever()?t:t.isBasis()&&!t.overlaps(w.intrinsic.object)?L.init(`assignability`,w.intrinsic.object,t):n.$.lazilyResolve(()=>Vr(B(e.resolution,t,n)),`${e.reference}${n.pipe?`=>`:`&`}${t.id}`))}});var Ur=class extends kr{expression=this.reference;structure=void 0;get resolution(){let e=this._resolve();return W[this.id]=e}_resolve(){if(this.resolve)return this.resolve();if(this.reference[0]===`$`)return this.$.resolveRoot(this.reference.slice(1));let e=W[this.reference],t=[];for(;O(e,`context`);){if(t.includes(e.id))return h(Wr(e.id,t));t.push(e.id),e=W[e.id]}return O(e,`root`)?e:m(`Unexpected resolution for reference ${this.reference} Seen: [${t.join(`->`)}] Resolution: ${C(e)}`)}get resolutionId(){if(this.reference.includes(`&`)||this.reference.includes(`=>`))return this.resolution.id;if(this.reference[0]!==`$`)return this.reference;let e=this.reference.slice(1),t=this.$.resolutions[e];return typeof t==`string`?t:O(t,`root`)?t.id:m(`Unexpected resolution for reference ${this.reference}: ${C(t)}`)}get defaultShortDescription(){return p.object}innerToJsonSchema(e){return this.resolution.toJsonSchemaRecurse(e)}traverseAllows=(e,t)=>{let n=t.seen[this.reference];return n?.includes(e)?!0:(t.seen[this.reference]=a(n,e),this.resolution.traverseAllows(e,t))};traverseApply=(e,t)=>{let n=t.seen[this.reference];n?.includes(e)||(t.seen[this.reference]=a(n,e),this.resolution.traverseApply(e,t))};compile(e){let t=this.resolutionId;e.if(`ctx.seen.${t} && ctx.seen.${t}.includes(data)`,()=>e.return(!0)),e.if(`!ctx.seen.${t}`,()=>e.line(`ctx.seen.${t} = []`)),e.line(`ctx.seen.${t}.push(data)`),e.return(e.invoke(t))}};const Wr=(e,t)=>`Alias '${e}' has a shallow resolution cycle: ${[...t,e].join(`->`)}`,Gr={implementation:Hr,Node:Ur};var Kr=class extends kr{traverseApply=(e,t)=>{this.traverseAllows(e,t)||t.errorFromNodeContext(this.errorContext)};get errorContext(){return{code:this.kind,description:this.description,meta:this.meta,...this.inner}}get compiledErrorContext(){return $t(this.errorContext)}compile(e){e.traversalKind===`Allows`?e.return(this.compiledCondition):e.if(this.compiledNegation,()=>e.line(`ctx.errorFromNodeContext(${this.compiledErrorContext})`))}};const qr={implementation:j({kind:`domain`,hasAssociatedError:!0,collapsibleKey:`domain`,keys:{domain:{},numberAllowsNaN:{}},normalize:e=>typeof e==`string`?{domain:e}:oe(e,`numberAllowsNaN`)&&e.domain!==`number`?h(qr.writeBadAllowNanMessage(e.domain)):e,applyConfig:(e,t)=>e.numberAllowsNaN===void 0&&e.domain===`number`&&t.numberAllowsNaN?{...e,numberAllowsNaN:!0}:e,defaults:{description:e=>p[e.domain],actual:e=>Number.isNaN(e)?`NaN`:p[f(e)]},intersections:{domain:(e,t)=>e.domain===`number`&&t.domain===`number`?e.numberAllowsNaN?t:e:L.init(`domain`,e,t)}}),Node:class extends Kr{requiresNaNCheck=this.domain===`number`&&!this.numberAllowsNaN;traverseAllows=this.requiresNaNCheck?e=>typeof e==`number`&&!Number.isNaN(e):e=>f(e)===this.domain;compiledCondition=this.domain===`object`?`((typeof data === "object" && data !== null) || typeof data === "function")`:`typeof data === "${this.domain}"${this.requiresNaNCheck?` && !Number.isNaN(data)`:``}`;compiledNegation=this.domain===`object`?`((typeof data !== "object" || data === null) && typeof data !== "function")`:`typeof data !== "${this.domain}"${this.requiresNaNCheck?` || Number.isNaN(data)`:``}`;expression=this.numberAllowsNaN?`number | NaN`:this.domain;get nestableExpression(){return this.numberAllowsNaN?`(${this.expression})`:this.expression}get defaultShortDescription(){return p[this.domain]}innerToJsonSchema(e){return this.domain===`bigint`||this.domain===`symbol`?e.fallback.domain({code:`domain`,base:{},domain:this.domain}):{type:this.domain}}},writeBadAllowNanMessage:e=>`numberAllowsNaN may only be specified with domain "number" (was ${e})`},Jr={implementation:j({kind:`intersection`,hasAssociatedError:!0,normalize:e=>{if(k(e))return e;let{structure:t,...n}=e,r=!!t,i=t??{},a=g(n,(e,t)=>_(e,Jt)?(r&&h(`Flattened structure key ${e} cannot be specified alongside a root 'structure' key.`),i[e]=t,[]):[e,t]);return(O(i,`constraint`)||!fe(i))&&(a.structure=i),a},finalizeInnerJson:({structure:e,...t})=>d(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;let{sequence:t,...n}=e.collapsibleJson,{minVariadicLength:r,...i}=t,a=i.variadic&&Object.keys(i).length===1?i.variadic:i;return{...n,sequence:a}}},divisor:{child:!0,parse:H(`divisor`)},max:{child:!0,parse:H(`max`)},min:{child:!0,parse:H(`min`)},maxLength:{child:!0,parse:H(`maxLength`)},minLength:{child:!0,parse:H(`minLength`)},exactLength:{child:!0,parse:H(`exactLength`)},before:{child:!0,parse:H(`before`)},after:{child:!0,parse:H(`after`)},pattern:{child:!0,parse:H(`pattern`)},predicate:{child:!0,parse:H(`predicate`)}},reduce:(e,t)=>Xr({},e,{$:t,invert:!1,pipe:!1}),defaults:{description:e=>{if(e.children.length===0)return`unknown`;if(e.structure)return e.structure.description;let t=[];if(e.basis&&!e.prestructurals.some(e=>e.impl.obviatesBasisDescription)&&t.push(e.basis.description),e.prestructurals.length){let n=e.prestructurals.slice().sort((e,t)=>e.kind===`min`&&t.kind===`max`?-1:0).map(e=>e.description);t.push(...n)}return e.inner.predicate&&t.push(...e.inner.predicate.map(e=>e.description)),t.join(` and `)},expected:e=>` ◦ ${e.errors.map(e=>e.expected).join(` ◦ `)}`,problem:e=>`(${e.actual}) must be...\n${e.expected}`},intersections:{intersection:(e,t,n)=>Xr(e.inner,t.inner,n),...zr(`intersection`,(e,t,n)=>{if(e.children.length===0)return t;let{domain:r,proto:i,...a}=e.inner,o=i??r,s=o?B(o,t,n):t;return s instanceof L?s:e?.basis?.equals(s)?e:e.$.node(`intersection`,{...a,[s.kind]:s},{prereduced:!0})})}}),Node:class extends kr{basis=this.inner.domain??this.inner.proto??null;prestructurals=[];refinements=this.children.filter(e=>e.isRefinement()?(r(Ht,e.kind)&&this.prestructurals.push(e),!0):!1);structure=this.inner.structure;expression=Yr(this);get shallowMorphs(){return this.inner.structure?.structuralMorph?[this.inner.structure.structuralMorph]:[]}get defaultShortDescription(){return this.basis?.defaultShortDescription??`present`}innerToJsonSchema(e){return this.children.reduce((t,n)=>n.isBasis()?n.toJsonSchemaRecurse(e):n.reduceJsonSchema(t,e),{})}traverseAllows=(e,t)=>this.children.every(n=>n.traverseAllows(e,t));traverseApply=(e,t)=>{let n=t.currentErrorCount;if(!(this.basis&&(this.basis.traverseApply(e,t),t.currentErrorCount>n))){if(this.prestructurals.length){for(let r=0;r<this.prestructurals.length-1;r++)if(this.prestructurals[r].traverseApply(e,t),t.failFast&&t.currentErrorCount>n)return;if(this.prestructurals[this.prestructurals.length-1].traverseApply(e,t),t.currentErrorCount>n)return}if(!(this.structure&&(this.structure.traverseApply(e,t),t.currentErrorCount>n))&&this.inner.predicate){for(let r=0;r<this.inner.predicate.length-1;r++)if(this.inner.predicate[r].traverseApply(e,t),t.failFast&&t.currentErrorCount>n)return;this.inner.predicate[this.inner.predicate.length-1].traverseApply(e,t)}}};compile(e){if(e.traversalKind===`Allows`){for(let t of this.children)e.check(t);e.return(!0);return}if(e.initializeErrorCount(),this.basis&&(e.check(this.basis),this.children.length>1&&e.returnIfFail()),this.prestructurals.length){for(let t=0;t<this.prestructurals.length-1;t++)e.check(this.prestructurals[t]),e.returnIfFailFast();e.check(this.prestructurals[this.prestructurals.length-1]),(this.structure||this.inner.predicate)&&e.returnIfFail()}if(this.structure&&(e.check(this.structure),this.inner.predicate&&e.returnIfFail()),this.inner.predicate){for(let t=0;t<this.inner.predicate.length-1;t++)e.check(this.inner.predicate[t]),e.returnIfFail();e.check(this.inner.predicate[this.inner.predicate.length-1])}}}},Yr=e=>{if(e.structure?.expression)return e.structure.expression;let t=e.basis&&!e.prestructurals.some(e=>e.impl.obviatesBasisExpression)?e.basis.nestableExpression:``,n=e.prestructurals.map(e=>e.expression).join(` & `),r=`${t}${t?` `:``}${n}`;return r===`Array == 0`?`[]`:r||`unknown`},Xr=(e,t,n)=>{let r={},i=e.proto??e.domain,a=t.proto??t.domain,o=i?a?B(i,a,n):i:a;return o instanceof L?o:(o&&(r[o.kind]=o),On({kind:`intersection`,baseInner:r,l:kn(e),r:kn(t),roots:[],ctx:n}))},Zr={implementation:j({kind:`morph`,hasAssociatedError:!1,keys:{in:{child:!0,parse:(e,t)=>t.$.parseSchema(e)},morphs:{parse:e,serialize:e=>e.map(e=>O(e,`root`)?e.json:T(e))},declaredIn:{child:!1,serialize:e=>e.json},declaredOut:{child:!1,serialize:e=>e.json}},normalize:e=>e,defaults:{description:e=>`a morph from ${e.rawIn.description} to ${e.rawOut?.description??`unknown`}`},intersections:{morph:(e,t,n)=>{if(!e.hasEqualMorphs(t))return h(Qr(e.expression,t.expression));let r=B(e.rawIn,t.rawIn,n);if(r instanceof L)return r;let i={morphs:e.morphs};if(e.declaredIn||t.declaredIn){let r=B(e.rawIn,t.rawIn,n);if(r instanceof L)return r.throw();i.declaredIn=r}if(e.declaredOut||t.declaredOut){let r=B(e.rawOut,t.rawOut,n);if(r instanceof L)return r.throw();i.declaredOut=r}return r.distribute(e=>n.$.node(`morph`,{...i,in:e}),n.$.parseSchema)},...zr(`morph`,(e,t,n)=>{let r=e.inner.in?B(e.inner.in,t,n):t;return r instanceof L?r:r.equals(e.inner.in)?e:n.$.node(`morph`,{...e.inner,in:r})})}}),Node:class extends kr{serializedMorphs=this.morphs.map(T);compiledMorphs=`[${this.serializedMorphs}]`;lastMorph=this.inner.morphs[this.inner.morphs.length-1];lastMorphIfNode=O(this.lastMorph,`root`)?this.lastMorph:void 0;introspectableIn=this.inner.in;introspectableOut=this.lastMorphIfNode?Object.assign(this.referencesById,this.lastMorphIfNode.referencesById)&&this.lastMorphIfNode.rawOut:void 0;get shallowMorphs(){return Array.isArray(this.inner.in?.shallowMorphs)?[...this.inner.in.shallowMorphs,...this.morphs]:this.morphs}get rawIn(){return this.declaredIn??this.inner.in?.rawIn??w.intrinsic.unknown.internal}get rawOut(){return this.declaredOut??this.introspectableOut??w.intrinsic.unknown.internal}declareIn(e){return this.$.node(`morph`,{...this.inner,declaredIn:e})}declareOut(e){return this.$.node(`morph`,{...this.inner,declaredOut:e})}expression=`(In: ${this.rawIn.expression}) => ${this.lastMorphIfNode?`To`:`Out`}<${this.rawOut.expression}>`;get defaultShortDescription(){return this.rawIn.meta.description??this.rawIn.defaultShortDescription}innerToJsonSchema(e){return e.fallback.morph({code:`morph`,base:this.rawIn.toJsonSchemaRecurse(e),out:this.introspectableOut?.toJsonSchemaRecurse(e)??null})}compile(e){if(e.traversalKind===`Allows`){if(!this.introspectableIn)return;e.return(e.invoke(this.introspectableIn));return}this.introspectableIn&&e.line(e.invoke(this.introspectableIn)),e.line(`ctx.queueMorphs(${this.compiledMorphs})`)}traverseAllows=(e,t)=>!this.introspectableIn||this.introspectableIn.traverseAllows(e,t);traverseApply=(e,t)=>{this.introspectableIn&&this.introspectableIn.traverseApply(e,t),t.queueMorphs(this.morphs)};hasEqualMorphs(e){return u(this.morphs,e.morphs,{isEqual:(e,t)=>e===t||O(e,`root`)&&O(t,`root`)&&e.equals(t)})}}},Qr=(e,t)=>`The intersection of distinct morphs at a single path is indeterminate: Left: ${e} Right: ${t}`,$r={implementation:j({kind:`proto`,hasAssociatedError:!0,collapsibleKey:`proto`,keys:{proto:{serialize:e=>Oe(e)??A(e)},dateAllowsInvalid:{}},normalize:e=>{let t=typeof e==`string`?{proto:xe[e]}:typeof e==`function`?k(e)?e:{proto:e}:typeof e.proto==`string`?{...e,proto:xe[e.proto]}:e;return typeof t.proto!=`function`&&h($r.writeInvalidSchemaMessage(t.proto)),oe(t,`dateAllowsInvalid`)&&t.proto!==Date&&h($r.writeBadInvalidDateMessage(t.proto)),t},applyConfig:(e,t)=>e.dateAllowsInvalid===void 0&&e.proto===Date&&t.dateAllowsInvalid?{...e,dateAllowsInvalid:!0}:e,defaults:{description:e=>e.builtinName?De[e.builtinName]:`an instance of ${e.proto.name}`,actual:e=>e instanceof Date&&e.toString()===`Invalid Date`?`an invalid Date`:Ce(e)},intersections:{proto:(e,t)=>e.proto===Date&&t.proto===Date?e.dateAllowsInvalid?t:e:ke(e.proto,t.proto)?e:ke(t.proto,e.proto)?t:L.init(`proto`,e,t),domain:(e,t)=>t.domain===`object`?e:L.init(`domain`,w.intrinsic.object.internal,t)}}),Node:class extends Kr{builtinName=Oe(this.proto);serializedConstructor=this.json.proto;requiresInvalidDateCheck=this.proto===Date&&!this.dateAllowsInvalid;traverseAllows=this.requiresInvalidDateCheck?e=>e instanceof Date&&e.toString()!==`Invalid Date`:e=>e instanceof this.proto;compiledCondition=`data instanceof ${this.serializedConstructor}${this.requiresInvalidDateCheck?` && data.toString() !== "Invalid Date"`:``}`;compiledNegation=`!(${this.compiledCondition})`;innerToJsonSchema(e){switch(this.builtinName){case`Array`:return{type:`array`};case`Date`:return e.fallback.date?.({code:`date`,base:{}})??e.fallback.proto({code:`proto`,base:{},proto:this.proto});default:return e.fallback.proto({code:`proto`,base:{},proto:this.proto})}}expression=this.dateAllowsInvalid?`Date | InvalidDate`:this.proto.name;get nestableExpression(){return this.dateAllowsInvalid?`(${this.expression})`:this.expression}domain=`object`;get defaultShortDescription(){return this.description}},writeBadInvalidDateMessage:e=>`dateAllowsInvalid may only be specified with constructor Date (was ${e.name})`,writeInvalidSchemaMessage:e=>`instanceOf operand must be a function (was ${f(e)})`},ei=j({kind:`union`,hasAssociatedError:!0,collapsibleKey:`branches`,keys:{ordered:{},branches:{child:!0,parse:(e,t)=>{let n=[];for(let r of e){let e=O(r,`root`)?r.branches:t.$.parseSchema(r).branches;for(let r of e)if(r.hasKind(`morph`)){let e=n.findIndex(e=>e.hasKind(`morph`)&&e.hasEqualMorphs(r));if(e===-1)n.push(r);else{let i=n[e];n[e]=t.$.node(`morph`,{...i.inner,in:i.rawIn.rawOr(r.rawIn)})}}else n.push(r)}return t.def.ordered||n.sort((e,t)=>e.hash<t.hash?-1:1),n}}},normalize:e=>y(e)?{branches:e}:e,reduce:(e,t)=>{let n=hi(e);if(n.length===1)return n[0];if(n.length!==e.branches.length)return t.node(`union`,{...e,branches:n},{prereduced:!0})},defaults:{description:e=>e.distribute(e=>e.description,pi),expected:e=>{let t=l(e.errors,`propString`);return pi(Object.entries(t).map(([e,t])=>{let n=[];for(let e of t)c(n,e.expected);let r=pi(n),i=t.every(e=>e.actual===t[0].actual)?t[0].actual:C(t[0].data);return`${e&&`${e} `}must be ${r}${i&&` (was ${i})`}`}))},problem:e=>e.expected,message:e=>e.problem[0]===`[`?`value at ${e.problem}`:e.problem},intersections:{union:(e,t,n)=>{if(e.isNever!==t.isNever)return L.init(`presence`,e,t);let r;return e.ordered?(t.ordered&&h(yi(e.expression,t.expression)),r=mi(t.branches,e.branches,n),r instanceof L&&r.invert()):r=mi(e.branches,t.branches,n),r instanceof L?r:n.$.parseSchema(e.ordered||t.ordered?{branches:r,ordered:!0}:{branches:r})},...zr(`union`,(e,t,n)=>{let r=mi(e.branches,[t],n);return r instanceof L?r:r.length===1?r[0]:n.$.parseSchema(e.ordered?{branches:r,ordered:!0}:{branches:r})})}});var ti=class extends kr{isBoolean=this.branches.length===2&&this.branches[0].hasUnit(!1)&&this.branches[1].hasUnit(!0);get branchGroups(){let e=[],t=-1;for(let n of this.branches){if(n.hasKind(`unit`)&&n.domain===`boolean`){t===-1?(t=e.length,e.push(n)):e[t]=w.intrinsic.boolean;continue}e.push(n)}return e}unitBranches=this.branches.filter(e=>e.rawIn.hasKind(`unit`));discriminant=this.discriminate();discriminantJson=this.discriminant?ui(this.discriminant):null;expression=this.distribute(e=>e.nestableExpression,fi);createBranchedOptimisticRootApply(){return(e,t)=>{let n=this.traverseOptimistic(e);if(n!==v)return n;let r=new P(e,this.$.resolvedConfig);return this.traverseApply(e,r),r.finalize(t)}}get shallowMorphs(){return this.branches.reduce((e,t)=>c(e,t.shallowMorphs),[])}get defaultShortDescription(){return this.distribute(e=>e.defaultShortDescription,pi)}innerToJsonSchema(e){if(this.branchGroups.length===1&&this.branchGroups[0].equals(w.intrinsic.boolean))return{type:`boolean`};let t=this.branchGroups.map(t=>t.toJsonSchemaRecurse(e));return t.every(e=>Object.keys(e).length===1&&oe(e,`const`))?{enum:t.map(e=>e.const)}:{anyOf:t}}traverseAllows=(e,t)=>this.branches.some(n=>n.traverseAllows(e,t));traverseApply=(e,t)=>{let n=[];for(let r=0;r<this.branches.length;r++){if(t.pushBranch(),this.branches[r].traverseApply(e,t),!t.hasError())return this.branches[r].includesTransform?t.queuedMorphs.push(...t.popBranch().queuedMorphs):t.popBranch();n.push(t.popBranch().error)}t.errorFromNodeContext({code:`union`,errors:n,meta:this.meta})};traverseOptimistic=e=>{for(let t=0;t<this.branches.length;t++){let n=this.branches[t];if(n.traverseAllows(e))return n.contextFreeMorph?n.contextFreeMorph(e):e}return v};compile(e){if(!this.discriminant||this.unitBranches.length===this.branches.length&&this.branches.length===2)return this.compileIndiscriminable(e);let t=this.discriminant.optionallyChainedPropString;this.discriminant.kind===`domain`&&(t=`typeof ${t} === "object" ? ${t} === null ? "null" : "object" : typeof ${t} === "function" ? "object" : typeof ${t}`);let n=this.discriminant.cases,r=Object.keys(n),{optimistic:i}=e;if(e.optimistic=!1,e.block(`switch(${t})`,()=>{for(let t in n){let r=n[t],a=t===`default`?t:`case ${t}`,o;o=r===!0?i?`data`:`true`:i?r.rootApplyStrategy===`branchedOptimistic`?e.invoke(r,{kind:`Optimistic`}):r.contextFreeMorph?`${e.invoke(r)} ? ${T(r.contextFreeMorph)}(data) : "${v}"`:`${e.invoke(r)} ? data : "${v}"`:e.invoke(r),e.line(`${a}: return ${o}`)}return e}),e.traversalKind===`Allows`){e.return(i?`"${v}"`:!1);return}let a=pi(this.discriminant.kind===`domain`?r.map(e=>{let t=e.slice(1,-1);return t===`function`?p.object:p[t]}):r),o=this.discriminant.path.map(e=>typeof e==`symbol`?T(e):JSON.stringify(e)),s=JSON.stringify(a),c=this.discriminant.kind===`domain`?`${si}[${t}]`:`${ci}(${t})`;e.line(`ctx.errorFromNodeContext({ code: "predicate", expected: ${s}, actual: ${c}, relativePath: [${o}], meta: ${this.compiledMeta} })`)}compileIndiscriminable(e){if(e.traversalKind===`Apply`){e.const(`errors`,`[]`);for(let t of this.branches)e.line(`ctx.pushBranch()`).line(e.invoke(t)).if(`!ctx.hasError()`,()=>e.return(t.includesTransform?`ctx.queuedMorphs.push(...ctx.popBranch().queuedMorphs)`:`ctx.popBranch()`)).line(`errors.push(ctx.popBranch().error)`);e.line(`ctx.errorFromNodeContext({ code: "union", errors, meta: ${this.compiledMeta} })`)}else{let{optimistic:t}=e;e.optimistic=!1;for(let n of this.branches)e.if(`${e.invoke(n)}`,()=>e.return(t?n.contextFreeMorph?`${T(n.contextFreeMorph)}(data)`:`data`:!0));e.return(t?`"${v}"`:!1)}}get nestableExpression(){return this.isBoolean?`boolean`:`(${this.expression})`}discriminate(){if(this.branches.length<2||this.isCyclic)return null;if(this.unitBranches.length===this.branches.length)return{kind:`unit`,path:[],optionallyChainedPropString:`data`,cases:g(this.unitBranches,(e,t)=>[`${t.rawIn.serializedValue}`,t.hasKind(`morph`)?t:!0])};let e=[];for(let t=0;t<this.branches.length-1;t++){let n=this.branches[t];for(let r=t+1;r<this.branches.length;r++){let i=this.branches[r],a=z(n.rawIn,i.rawIn,n.$);if(a instanceof L)for(let n of a){if(!n.kind||n.optional)continue;let i,a;if(n.kind===`domain`){let e=n.l,t=n.r;i=`"${typeof e==`string`?e:e.domain}"`,a=`"${typeof t==`string`?t:t.domain}"`}else if(n.kind===`unit`)i=n.l.serializedValue,a=n.r.serializedValue;else continue;let o=e.find(e=>u(e.path,n.path)&&e.kind===n.kind);o?(o.cases[i]?o.cases[i].branchIndices=c(o.cases[i].branchIndices,t):o.cases[i]??={branchIndices:[t],condition:n.l},o.cases[a]?o.cases[a].branchIndices=c(o.cases[a].branchIndices,r):o.cases[a]??={branchIndices:[r],condition:n.r}):e.push({kind:n.kind,cases:{[i]:{branchIndices:[t],condition:n.l},[a]:{branchIndices:[r],condition:n.r}},path:n.path})}}}let t=this.ordered?ii(e,this.branches):e;if(!t.length)return null;let n=ni(t,this),r={};for(let e in n.best.cases){let t=ri(n,e);if(t===null){r[e]=!0;continue}if(t.length===this.branches.length)return null;this.ordered&&t.sort((e,t)=>e.originalIndex-t.originalIndex);let i=t.map(e=>e.branch),a=i.length===1?i[0]:this.$.node(`union`,this.ordered?{branches:i,ordered:!0}:i);Object.assign(this.referencesById,a.referencesById),r[e]=a}if(n.defaultEntries.length){let e=n.defaultEntries.map(e=>e.branch);r.default=this.$.node(`union`,this.ordered?{branches:e,ordered:!0}:e,{prereduced:!0}),Object.assign(this.referencesById,r.default.referencesById)}return Object.assign(n.location,{cases:r})}};const ni=(e,t)=>{let n=e.sort((e,t)=>e.path.length===t.path.length?Object.keys(t.cases).length-Object.keys(e.cases).length:e.path.length-t.path.length)[0];return{best:n,location:{kind:n.kind,path:n.path,optionallyChainedPropString:oi(n.path)},defaultEntries:t.branches.map((e,t)=>({originalIndex:t,branch:e})),node:t}},ri=(e,t)=>{let n=e.best.cases[t],r=ai(n.condition,e.location.path,e.node.$),i=[],a=[];for(let t=0;t<e.defaultEntries.length;t++){let o=e.defaultEntries[t];if(n.branchIndices.includes(o.originalIndex)){let t=_i(e.node.branches[o.originalIndex],e.location);t===null?i=null:i?.push({originalIndex:o.originalIndex,branch:t})}else if(o.branch.hasKind(`alias`)&&r.hasKind(`domain`)&&r.domain===`object`)i?.push(o);else{if(o.branch.rawIn.overlaps(r)){let t=_i(o.branch,e.location);i?.push({originalIndex:o.originalIndex,branch:t})}a.push(o)}}return e.defaultEntries=a,i},ii=(e,t)=>e.filter(e=>{let n=Object.values(e.cases).map(e=>e.branchIndices);for(let e=0;e<n.length-1;e++){let r=n[e];for(let i=e+1;i<n.length;i++){let e=n[i];for(let n of r)for(let r of e)if(n>r&&t[n].overlaps(t[r]))return!1}}return!0}),ai=(e,t,n)=>{let r=e===`undefined`?n.node(`unit`,{unit:void 0}):e===`null`?n.node(`unit`,{unit:null}):e===`boolean`?n.units([!0,!1]):e;for(let e=t.length-1;e>=0;e--){let a=t[e];r=n.node(`intersection`,typeof a==`number`?{proto:`Array`,sequence:[...i(a).map(e=>({})),r]}:{domain:`object`,required:[{key:a,value:r}]})}return r},oi=e=>e.reduce((e,t)=>e+Ft(t,!0),`data`),si=T(ee),ci=T(C),li={implementation:ei,Node:ti},ui=e=>({kind:e.kind,path:e.path.map(e=>typeof e==`string`?e:E(e)),cases:g(e.cases,(e,t)=>[e,t===!0?t:t.hasKind(`union`)&&t.discriminantJson?t.discriminantJson:t.json])}),di={delimiter:` | `,finalDelimiter:` | `},fi=e=>pi(e,di),pi=(e,t)=>{let n=t?.delimiter??`, `,r=t?.finalDelimiter??` or `;if(e.length===0)return`never`;if(e.length===1)return e[0];if(e.length===2&&e[0]===`false`&&e[1]===`true`||e[0]===`true`&&e[1]===`false`)return`boolean`;let i={},a=e.filter(e=>i[e]?!1:i[e]=!0),o=a.pop();return`${a.join(n)}${a.length?r:``}${o}`},mi=(e,t,n)=>{let r=t.map(()=>[]);for(let i=0;i<e.length;i++){let a={};for(let o=0;o<t.length;o++){if(r[o]===null)continue;if(e[i].equals(t[o])){r[o]=null,a={};break}let s=B(e[i],t[o],n);if(!(s instanceof L)){if(s.equals(e[i])){r[o].push(e[i]),a={};break}s.equals(t[o])?r[o]=null:a[o]=s}}for(let e in a)r[e][i]=a[e]}let i=r.flatMap((e,n)=>e?.flatMap(e=>e.branches)??t[n]);return i.length===0?L.init(`union`,e,t):i},hi=({branches:e,ordered:t})=>{if(e.length<2)return e;let n=e.map(()=>!0);for(let r=0;r<e.length;r++)for(let i=r+1;i<e.length&&n[r]&&n[i];i++){if(e[r].equals(e[i])){n[i]=!1;continue}let a=z(e[r].rawIn,e[i].rawIn,e[0].$);a instanceof L||(t||gi(e[r],e[i]),a.equals(e[r].rawIn)?n[r]=!!t:a.equals(e[i].rawIn)&&(n[i]=!1))}return e.filter((e,t)=>n[t])},gi=(e,t)=>{!e.includesTransform&&!t.includesTransform||(u(e.shallowMorphs,t.shallowMorphs)||h(vi(e.expression,t.expression)),u(e.flatMorphs,t.flatMorphs,{isEqual:(e,t)=>e.propString===t.propString&&(e.node.hasKind(`morph`)&&t.node.hasKind(`morph`)?e.node.hasEqualMorphs(t.node):e.node.hasKind(`intersection`)&&t.node.hasKind(`intersection`)?e.node.structure?.structuralMorphRef===t.node.structure?.structuralMorphRef:!1)})||h(vi(e.expression,t.expression)))},_i=(e,t)=>e.transform((e,t)=>e===`domain`||e===`unit`?null:t,{shouldTransform:(e,n)=>{let r=oi(n.path);return t.optionallyChainedPropString.startsWith(r)?e.hasKind(`domain`)&&e.domain===`object`||(e.hasKind(`domain`)||t.kind===`unit`)&&r===t.optionallyChainedPropString?!0:e.children.length!==0&&e.kind!==`index`:!1}}),vi=(e,t)=>`An unordered union of a type including a morph and a type with overlapping input is indeterminate: Left: ${e} Right: ${t}`,yi=(e,t)=>`The intersection of two ordered unions is indeterminate: Left: ${e} Right: ${t}`,bi={implementation:j({kind:`unit`,hasAssociatedError:!0,keys:{unit:{preserveUndefined:!0,serialize:e=>e instanceof Date?e.toISOString():A(e)}},normalize:e=>e,defaults:{description:e=>C(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)=>L.init(`unit`,e,t),...zr(`unit`,(e,t)=>{if(t.allows(e.unit))return e;let n=t.hasKind(`intersection`)?t.basis:t;if(n){let t=n.hasKind(`domain`)?n:w.intrinsic.object;if(e.domain!==t.domain){let n=e.domain===`undefined`||e.domain===`null`||e.domain===`boolean`?e.domain:w.intrinsic[e.domain];return L.init(`domain`,n,t)}}return L.init(`assignability`,e,t.hasKind(`intersection`)?t.children.find(t=>!t.allows(e.unit)):t)})}}),Node:class extends Kr{compiledValue=this.json.unit;serializedValue=typeof this.unit==`string`||this.unit instanceof Date?JSON.stringify(this.compiledValue):`${this.compiledValue}`;compiledCondition=xi(this.unit,this.serializedValue);compiledNegation=xi(this.unit,this.serializedValue,`negated`);expression=C(this.unit);domain=f(this.unit);get defaultShortDescription(){return this.domain===`object`?p.object:this.description}innerToJsonSchema(e){return this.unit===null?{type:`null`}:w.intrinsic.jsonPrimitive.allows(this.unit)?{const:this.unit}:e.fallback.unit({code:`unit`,base:{},unit:this.unit})}traverseAllows=this.unit instanceof Date?e=>e instanceof Date&&e.toISOString()===this.compiledValue:Number.isNaN(this.unit)?e=>Number.isNaN(e):e=>e===this.unit}},xi=(e,t,n)=>{if(e instanceof Date){let e=`data instanceof Date && data.toISOString() === ${t}`;return n?`!(${e})`:e}return Number.isNaN(e)?`${n?`!`:``}Number.isNaN(data)`:`data ${n?`!`:`=`}== ${t}`},Si={implementation:j({kind:`index`,hasAssociatedError:!1,intersectionIsOpen:!0,keys:{signature:{child:!0,parse:(e,t)=>{let n=t.$.parseSchema(e);if(!n.extends(w.intrinsic.key))return h(wi(n.expression));let r=n.branches.filter(e=>e.hasKind(`unit`));return r.length?h(Ci(r.map(e=>C(e.unit)))):n}},value:{child:!0,parse:(e,t)=>t.$.parseSchema(e)}},normalize:e=>e,defaults:{description:e=>`[${e.signature.expression}]: ${e.value.description}`},intersections:{index:(e,t,n)=>{if(e.signature.equals(t.signature)){let r=B(e.value,t.value,n),i=r instanceof L?w.intrinsic.never.internal:r;return n.$.node(`index`,{signature:e.signature,value: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}}}),Node:class extends V{impliedBasis=w.intrinsic.object.internal;expression=`[${this.signature.expression}]: ${this.value.expression}`;flatRefs=a(this.value.flatRefs.map(e=>I([this.signature,...e.path],e.node)),I([this.signature],this.value));traverseAllows=(e,t)=>pe(e).every(e=>this.signature.traverseAllows(e[0],t)?F(e[0],()=>this.value.traverseAllows(e[1],t),t):!0);traverseApply=(e,t)=>{for(let n of pe(e))this.signature.traverseAllows(n[0],t)&&F(n[0],()=>this.value.traverseApply(n[1],t),t)};_transform(e,t){t.path.push(this.signature);let n=super._transform(e,t);return t.path.pop(),n}compile(){}}},Ci=e=>`Index keys ${e.join(`, `)} should be specified as named props.`,wi=e=>`Indexed key definition '${e}' must be a string or symbol`,Ti={implementation:j({kind:`required`,hasAssociatedError:!0,intersectionIsOpen:!0,keys:{key:{},value:{child:!0,parse:(e,t)=>t.$.parseSchema(e)}},normalize:e=>e,defaults:{description:e=>`${e.compiledKey}: ${e.value.description}`,expected:e=>e.missingValueDescription,actual:()=>`missing`},intersections:{required:br,optional:br}}),Node:class extends xr{expression=`${this.compiledKey}: ${this.value.expression}`;errorContext=Object.freeze({code:`required`,missingValueDescription:this.value.defaultShortDescription,relativePath:[this.key],meta:this.meta});compiledErrorContext=$t(this.errorContext)}},Ei=j({kind:`sequence`,hasAssociatedError:!1,collapsibleKey:`variadic`,keys:{prefix:{child:!0,parse:(e,t)=>{if(e.length!==0)return e.map(e=>t.$.parseSchema(e))}},optionals:{child:!0,parse:(e,t)=>{if(e.length!==0)return e.map(e=>t.$.parseSchema(e))}},defaultables:{child:e=>e.map(e=>e[0]),parse:(e,t)=>{if(e.length!==0)return e.map(e=>{let n=t.$.parseSchema(e[0]);return Dr(n,e[1],null),[n,e[1]]})},serialize:e=>e.map(e=>[e[0].collapsibleJson,A(e[1])]),reduceIo:(e,t,n)=>{if(e===`in`){t.optionals=n.map(e=>e[0].rawIn);return}t.prefix=n.map(e=>e[0].rawOut)}},variadic:{child:!0,parse:(e,t)=>t.$.parseSchema(e,t)},minVariadicLength:{parse:e=>e===0?void 0:e},postfix:{child:!0,parse:(e,t)=>{if(e.length!==0)return e.map(e=>t.$.parseSchema(e))}}},normalize:e=>{if(typeof e==`string`)return{variadic:e};if(`variadic`in e||`prefix`in e||`defaultables`in e||`optionals`in e||`postfix`in e||`minVariadicLength`in e){if(e.postfix?.length){if(!e.variadic)return h(Pi);if(e.optionals?.length||e.defaultables?.length)return h(Ni)}return e.minVariadicLength&&!e.variadic?h(`minVariadicLength may not be specified without a variadic element`):e}return{variadic:e}},reduce:(e,t)=>{let n=e.minVariadicLength??0,r=e.prefix?.slice()??[],i=e.defaultables?.slice()??[],a=e.optionals?.slice()??[],o=e.postfix?.slice()??[];if(e.variadic){for(;a[a.length-1]?.equals(e.variadic);)a.pop();if(a.length===0&&i.length===0)for(;r[r.length-1]?.equals(e.variadic);)r.pop(),n++;for(;o[0]?.equals(e.variadic);)o.shift(),n++}else a.length===0&&i.length===0&&r.push(...o.splice(0));if(n!==e.minVariadicLength||e.prefix&&e.prefix.length!==r.length)return t.node(`sequence`,{...e,prefix:r,defaultables:i,optionals:a,postfix:o,minVariadicLength:n},{prereduced:!0})},defaults:{description:e=>e.isVariadicOnly?`${e.variadic.nestableExpression}[]`:`[${e.tuple.map(e=>e.kind===`defaultables`?`${e.node.nestableExpression} = ${C(e.default)}`:e.kind===`optionals`?`${e.node.nestableExpression}?`:e.kind===`variadic`?`...${e.node.nestableExpression}[]`:e.node.expression).join(`, `)}]`},intersections:{sequence:(e,t,n)=>{let r=Fi({l:e.tuple,r:t.tuple,disjoint:new L,result:[],fixedVariants:[],ctx:n}),i=r.disjoint.length===0?[r,...r.fixedVariants]:r.fixedVariants;return i.length===0?r.disjoint:i.length===1?n.$.node(`sequence`,Mi(i[0].result)):n.$.node(`union`,i.map(e=>({proto:Array,sequence:Mi(e.result)})))}}});var Di=class extends V{impliedBasis=w.intrinsic.Array.internal;tuple=ji(this.inner);prefixLength=this.prefix?.length??0;defaultablesLength=this.defaultables?.length??0;optionalsLength=this.optionals?.length??0;postfixLength=this.postfix?.length??0;defaultablesAndOptionals=[];prevariadic=this.tuple.filter(e=>e.kind===`defaultables`||e.kind===`optionals`?(this.defaultablesAndOptionals.push(e.node),!0):e.kind===`prefix`);variadicOrPostfix=o(this.variadic&&[this.variadic],this.postfix);flatRefs=this.addFlatRefs();addFlatRefs(){return _n(this.flatRefs,this.prevariadic.flatMap((e,t)=>a(e.node.flatRefs.map(e=>I([`${t}`,...e.path],e.node)),I([`${t}`],e.node)))),_n(this.flatRefs,this.variadicOrPostfix.flatMap(e=>a(e.flatRefs.map(e=>I([w.intrinsic.nonNegativeIntegerString.internal,...e.path],e.node)),I([w.intrinsic.nonNegativeIntegerString.internal],e)))),this.flatRefs}isVariadicOnly=this.prevariadic.length+this.postfixLength===0;minVariadicLength=this.inner.minVariadicLength??0;minLength=this.prefixLength+this.minVariadicLength+this.postfixLength;minLengthNode=this.minLength===0?null:this.$.node(`minLength`,this.minLength);maxLength=this.variadic?null:this.tuple.length;maxLengthNode=this.maxLength===null?null:this.$.node(`maxLength`,this.maxLength);impliedSiblings=this.minLengthNode?this.maxLengthNode?[this.minLengthNode,this.maxLengthNode]:[this.minLengthNode]:this.maxLengthNode?[this.maxLengthNode]:[];defaultValueMorphs=ki(this);defaultValueMorphsReference=this.defaultValueMorphs.length?T(this.defaultValueMorphs):void 0;elementAtIndex(e,t){if(t<this.prevariadic.length)return this.tuple[t];let n=e.length-this.postfixLength;return t>=n?{kind:`postfix`,node:this.postfix[t-n]}:{kind:`variadic`,node:this.variadic??m(`Unexpected attempt to access index ${t} on ${this}`)}}traverseAllows=(e,t)=>{for(let n=0;n<e.length;n++)if(!this.elementAtIndex(e,n).node.traverseAllows(e[n],t))return!1;return!0};traverseApply=(e,t)=>{let n=0;for(;n<e.length;n++)F(n,()=>this.elementAtIndex(e,n).node.traverseApply(e[n],t),t)};get element(){return this.cacheGetter(`element`,this.$.node(`union`,this.children))}compile(e){if(this.prefix)for(let[t,n]of this.prefix.entries())e.traverseKey(`${t}`,`data[${t}]`,n);for(let[t,n]of this.defaultablesAndOptionals.entries()){let r=`${t+this.prefixLength}`;e.if(`${r} >= data.length`,()=>e.traversalKind===`Allows`?e.return(!0):e.return()),e.traverseKey(r,`data[${r}]`,n)}if(this.variadic&&(this.postfix&&e.const(`firstPostfixIndex`,`data.length${this.postfix?`- ${this.postfix.length}`:``}`),e.for(`i < ${this.postfix?`firstPostfixIndex`:`data.length`}`,()=>e.traverseKey(`i`,`data[i]`,this.variadic),this.prevariadic.length),this.postfix))for(let[t,n]of this.postfix.entries()){let r=`firstPostfixIndex + ${t}`;e.traverseKey(r,`data[${r}]`,n)}e.traversalKind===`Allows`&&e.return(!0)}_transform(e,t){t.path.push(w.intrinsic.nonNegativeIntegerString.internal);let n=super._transform(e,t);return t.path.pop(),n}expression=this.description;reduceJsonSchema(e,t){let n=t.target===`draft-07`;if(this.prevariadic.length){let r=this.prevariadic.map(e=>{let n=e.node.toJsonSchemaRecurse(t);if(e.kind===`defaultables`){let r=typeof e.default==`function`?e.default():e.default;n.default=w.intrinsic.jsonData.allows(r)?r:t.fallback.defaultValue({code:`defaultValue`,base:n,value:r})}return n});n?e.items=r:e.prefixItems=r}if(this.minLength&&(e.minItems=this.minLength),this.variadic){let r=this.variadic.toJsonSchemaRecurse(t);if(n&&this.prevariadic.length?e.additionalItems=r:e.items=r,this.maxLength&&(e.maxItems=this.maxLength),this.postfix){let n=this.postfix.map(e=>e.toJsonSchemaRecurse(t));e=t.fallback.arrayPostfix({code:`arrayPostfix`,base:e,elements:n})}}else n?e.additionalItems=!1:e.items=!1,delete e.maxItems;return e}};const Oi={},ki=e=>{if(!e.defaultables)return[];let t=[],n=`[`,r=e.prefixLength+e.defaultablesLength-1;for(let i=e.prefixLength;i<=r;i++){let[r,a]=e.defaultables[i-e.prefixLength];t.push(Er(i,r,a)),n+=`${i}: ${r.id} = ${A(a)}, `}return n+=`]`,Oi[n]??=t},Ai={implementation:Ei,Node:Di},ji=e=>{let t=[];if(e.prefix)for(let n of e.prefix)t.push({kind:`prefix`,node:n});if(e.defaultables)for(let[n,r]of e.defaultables)t.push({kind:`defaultables`,node:n,default:r});if(e.optionals)for(let n of e.optionals)t.push({kind:`optionals`,node:n});if(e.variadic&&t.push({kind:`variadic`,node:e.variadic}),e.postfix)for(let n of e.postfix)t.push({kind:`postfix`,node:n});return t},Mi=e=>e.reduce((e,t)=>(t.kind===`variadic`?e.variadic=t.node:t.kind===`defaultables`?e.defaultables=a(e.defaultables,[[t.node,t.default]]):e[t.kind]=a(e[t.kind],t.node),e),{}),Ni=`A postfix required element cannot follow an optional or defaultable element`,Pi=`A postfix element requires a variadic element`,Fi=e=>{let[t,...n]=e.l,[r,...i]=e.r;if(!t||!r)return e;let a=n[n.length-1]?.kind===`postfix`,o=i[i.length-1]?.kind===`postfix`,s=t.kind===`prefix`||r.kind===`prefix`?`prefix`:t.kind===`postfix`||r.kind===`postfix`?`postfix`:t.kind===`variadic`&&r.kind===`variadic`?`variadic`:a||o?`prefix`:t.kind===`defaultables`||r.kind===`defaultables`?`defaultables`:`optionals`;if(t.kind===`prefix`&&r.kind===`variadic`&&o){let t=Fi({...e,fixedVariants:[],r:i.map(e=>({...e,kind:`prefix`}))});t.disjoint.length===0&&e.fixedVariants.push(t)}else if(r.kind===`prefix`&&t.kind===`variadic`&&a){let t=Fi({...e,fixedVariants:[],l:n.map(e=>({...e,kind:`prefix`}))});t.disjoint.length===0&&e.fixedVariants.push(t)}let c=B(t.node,r.node,e.ctx);if(c instanceof L)if(s===`prefix`||s===`postfix`)e.disjoint.push(...c.withPrefixKey(s===`prefix`?e.result.length:`-${n.length+1}`,Ii(t)&&Ii(r)?`required`:`optional`)),e.result=[...e.result,{kind:s,node:w.intrinsic.never.internal}];else if(s===`optionals`||s===`defaultables`)return e;else return Fi({...e,fixedVariants:[],l:n.map(e=>({...e,kind:`prefix`})),r:n.map(e=>({...e,kind:`prefix`}))});else s===`defaultables`?(t.kind===`defaultables`&&r.kind===`defaultables`&&t.default!==r.default&&h(Sr(t.default,r.default)),e.result=[...e.result,{kind:s,node:c,default:t.kind===`defaultables`?t.default:r.kind===`defaultables`?r.default:m(`Unexpected defaultable intersection from ${t.kind} and ${r.kind} elements.`)}]):e.result=[...e.result,{kind:s,node:c}];let l=e.l.length,u=e.r.length;return(t.kind!==`variadic`||l>=u&&(r.kind===`variadic`||u===1))&&(e.l=n),(r.kind!==`variadic`||u>=l&&(t.kind===`variadic`||l===1))&&(e.r=i),Fi(e)},Ii=e=>e.kind===`prefix`||e.kind===`postfix`,Li=e=>t=>{if(t.props.length||t.index){let n=t.index?.map(t=>t[e])??[];for(let r of t.props)n.push(r[e]);t.undeclared&&n.push(`+ (undeclared): ${t.undeclared}`);let r=`{ ${n.join(`, `)} }`;return t.sequence?`${r} & ${t.sequence.description}`:r}return t.sequence?.description??`{}`},Ri=Li(`description`),zi=Li(`expression`),Bi=(e,t,n)=>{let r=e.required?`required`:`optional`;if(!t.signature.allows(e.key))return null;let i=z(e.value,t.value,n);return i instanceof L?r===`optional`?n.node(`optional`,{key:e.key,value:w.intrinsic.never.internal}):i.withPrefixKey(e.key,e.kind):null},Vi=j({kind:`structure`,hasAssociatedError:!1,normalize:e=>e,applyConfig:(e,t)=>!e.undeclared&&t.onUndeclaredKey!==`ignore`?{...e,undeclared:t.onUndeclaredKey}:e,keys:{required:{child:!0,parse:H(`required`),reduceIo:(e,t,n)=>{t.required=a(t.required,n.map(t=>e===`in`?t.rawIn:t.rawOut))}},optional:{child:!0,parse:H(`optional`),reduceIo:(e,t,n)=>{if(e===`in`){t.optional=n.map(e=>e.rawIn);return}for(let e of n)t[e.outProp.kind]=a(t[e.outProp.kind],e.outProp.rawOut)}},index:{child:!0,parse:H(`index`)},sequence:{child:!0,parse:H(`sequence`)},undeclared:{parse:e=>e===`ignore`?void 0:e,reduceIo:(e,t,n)=>{if(n===`reject`){t.undeclared=`reject`;return}e===`in`?delete t.undeclared:t.undeclared=`reject`}}},defaults:{description:Ri},intersections:{structure:(e,t,n)=>{let r={...e.inner},i={...t.inner},a=new L;if(e.undeclared){let r=e.keyof();for(let e of t.requiredKeys)r.allows(e)||a.add(`presence`,w.intrinsic.never.internal,t.propsByKey[e].value,{path:[e]});i.optional&&=i.optional.filter(e=>r.allows(e.key)),i.index&&=i.index.flatMap(e=>{if(e.signature.extends(r))return e;let t=z(r,e.signature,n.$);if(t instanceof L)return[];let a=Xi(t,e.value,n.$);return a.required&&(i.required=o(i.required,a.required)),a.optional&&(i.optional=o(i.optional,a.optional)),a.index??[]})}if(t.undeclared){let i=t.keyof();for(let t of e.requiredKeys)i.allows(t)||a.add(`presence`,e.propsByKey[t].value,w.intrinsic.never.internal,{path:[t]});r.optional&&=r.optional.filter(e=>i.allows(e.key)),r.index&&=r.index.flatMap(e=>{if(e.signature.extends(i))return e;let t=z(i,e.signature,n.$);if(t instanceof L)return[];let a=Xi(t,e.value,n.$);return a.required&&(r.required=o(r.required,a.required)),a.optional&&(r.optional=o(r.optional,a.optional)),a.index??[]})}let s={};(e.undeclared||t.undeclared)&&(s.undeclared=e.undeclared===`reject`||t.undeclared===`reject`?`reject`:`delete`);let c=On({kind:`structure`,baseInner:s,l:kn(r),r:kn(i),roots:[],ctx:n});return c instanceof L&&a.push(...c),a.length?a:c}},reduce:(e,t)=>{if(!e.required&&!e.optional)return;let n={},r=!1,i=e.optional?[...e.optional]:[];if(e.required)for(let r=0;r<e.required.length;r++){let i=e.required[r];if(i.key in n&&h($i(i.key)),n[i.key]=!0,e.index)for(let n of e.index){let e=Bi(i,n,t);if(e instanceof L)return e}}if(e.optional)for(let a=0;a<e.optional.length;a++){let o=e.optional[a];if(o.key in n&&h($i(o.key)),n[o.key]=!0,e.index)for(let n of e.index){let e=Bi(o,n,t);if(e instanceof L)return e;e!==null&&(i[a]=e,r=!0)}}if(r)return t.node(`structure`,{...e,optional:i},{prereduced:!0})}});var Hi=class extends V{impliedBasis=w.intrinsic.object.internal;impliedSiblings=this.children.flatMap(e=>e.impliedSiblings??[]);props=o(this.required,this.optional);propsByKey=g(this.props,(e,t)=>[t.key,t]);propsByKeyReference=T(this.propsByKey);expression=zi(this);requiredKeys=this.required?.map(e=>e.key)??[];optionalKeys=this.optional?.map(e=>e.key)??[];literalKeys=[...this.requiredKeys,...this.optionalKeys];_keyof;keyof(){if(this._keyof)return this._keyof;let e=this.$.units(this.literalKeys).branches;if(this.index)for(let{signature:t}of this.index)e=e.concat(t.branches);return this._keyof=this.$.node(`union`,e)}map(e){return this.$.node(`structure`,this.props.flatMap(e).reduce((e,t)=>{let n=this.propsByKey[t.key];if(k(t))return t.kind!==`required`&&t.kind!==`optional`?h(`Map result must have kind "required" or "optional" (was ${t.kind})`):(e[t.kind]=a(e[t.kind],t),e);let r=t.kind??n?.kind??`required`,i=g(t,(e,t)=>e in Cr.implementation.keys?[e,t]:[]);return e[r]=a(e[r],this.$.node(r,i)),e},{}))}assertHasKeys(e){let t=e.filter(e=>!Fr(e,this.keyof()));if(t.length)return h(Qi(this.expression,t))}get(e,...t){let n,r=!1,i=Ji(e);if((typeof i==`string`||typeof i==`symbol`)&&this.propsByKey[i]&&(n=this.propsByKey[i].value,r=this.propsByKey[i].required),this.index)for(let e of this.index)Fr(i,e.signature)&&(n=n?.and(e.value)??e.value);if(this.sequence&&Fr(i,w.intrinsic.nonNegativeIntegerString))if(O(i,`root`))this.sequence.variadic&&(n=n?.and(this.sequence.element)??this.sequence.element);else{let e=Number.parseInt(i);if(e<this.sequence.prevariadic.length){let t=this.sequence.prevariadic[e].node;n=n?.and(t)??t,r||=e<this.sequence.prefixLength}else if(this.sequence.variadic){let e=this.$.node(`union`,this.sequence.variadicOrPostfix);n=n?.and(e)??e}}if(!n)return this.sequence?.variadic&&O(i,`root`)&&i.extends(w.intrinsic.number)?h(Yi(i.expression,this.sequence.expression)):h(Qi(this.expression,[i]));let a=n.get(...t);return r?a:a.or(w.intrinsic.undefined)}pick(...e){return this.assertHasKeys(e),this.$.node(`structure`,this.filterKeys(`pick`,e))}omit(...e){return this.assertHasKeys(e),this.$.node(`structure`,this.filterKeys(`omit`,e))}optionalize(){let{required:e,...t}=this.inner;return this.$.node(`structure`,{...t,optional:this.props.map(e=>e.hasKind(`required`)?this.$.node(`optional`,e.inner):e)})}require(){let{optional:e,...t}=this.inner;return this.$.node(`structure`,{...t,required:this.props.map(e=>e.hasKind(`optional`)?{key:e.key,value:e.value}:e)})}merge(e){let t=this.filterKeys(`omit`,[e.keyof()]);return e.required&&(t.required=a(t.required,e.required)),e.optional&&(t.optional=a(t.optional,e.optional)),e.index&&(t.index=a(t.index,e.index)),e.sequence&&(t.sequence=e.sequence),e.undeclared?t.undeclared=e.undeclared:delete t.undeclared,this.$.node(`structure`,t)}filterKeys(e,t){let n=zt(this.inner),r=n=>{let r=t.some(e=>Fr(n,e));return e===`pick`?r:!r};return n.required&&=n.required.filter(e=>r(e.key)),n.optional&&=n.optional.filter(e=>r(e.key)),n.index&&=n.index.filter(e=>r(e.signature)),n}traverseAllows=(e,t)=>this._traverse(`Allows`,e,t);traverseApply=(e,t)=>this._traverse(`Apply`,e,t);_traverse=(e,t,n)=>{let r=n?.currentErrorCount??0;for(let i=0;i<this.props.length;i++)if(e===`Allows`){if(!this.props[i].traverseAllows(t,n))return!1}else if(this.props[i].traverseApply(t,n),n.failFast&&n.currentErrorCount>r)return!1;if(this.sequence){if(e===`Allows`){if(!this.sequence.traverseAllows(t,n))return!1}else if(this.sequence.traverseApply(t,n),n.failFast&&n.currentErrorCount>r)return!1}if(this.index||this.undeclared===`reject`){let i=Object.keys(t);i.push(...Object.getOwnPropertySymbols(t));for(let a=0;a<i.length;a++){let o=i[a];if(this.index){for(let i of this.index)if(i.signature.traverseAllows(o,n)){if(e===`Allows`){if(!F(o,()=>i.value.traverseAllows(t[o],n),n))return!1}else if(F(o,()=>i.value.traverseApply(t[o],n),n),n.failFast&&n.currentErrorCount>r)return!1}}if(this.undeclared===`reject`&&!this.declaresKey(o)&&(e===`Allows`||(n.errorFromNodeContext({code:`predicate`,expected:`removed`,actual:``,relativePath:[o],meta:this.meta}),n.failFast)))return!1}}return this.structuralMorph&&n&&!n.hasError()&&n.queueMorphs([this.structuralMorph]),!0};get defaultable(){return this.cacheGetter(`defaultable`,this.optional?.filter(e=>e.hasDefault())??[])}declaresKey=e=>e in this.propsByKey||this.index?.some(t=>t.signature.allows(e))||this.sequence!==void 0&&w.intrinsic.nonNegativeIntegerString.allows(e);_compileDeclaresKey(e){let t=[];if(this.props.length&&t.push(`k in ${this.propsByKeyReference}`),this.index)for(let n of this.index)t.push(e.invoke(n.signature,{kind:`Allows`,arg:`k`}));return this.sequence&&t.push(`$ark.intrinsic.nonNegativeIntegerString.allows(k)`),t.join(` || `)||`false`}get structuralMorph(){return this.cacheGetter(`structuralMorph`,Gi(this))}structuralMorphRef=this.structuralMorph&&T(this.structuralMorph);compile(e){e.traversalKind===`Apply`&&e.initializeErrorCount();for(let t of this.props)e.check(t),e.traversalKind===`Apply`&&e.returnIfFailFast();if(this.sequence&&(e.check(this.sequence),e.traversalKind===`Apply`&&e.returnIfFailFast()),(this.index||this.undeclared===`reject`)&&(e.const(`keys`,`Object.keys(data)`),e.line(`keys.push(...Object.getOwnPropertySymbols(data))`),e.for(`i < keys.length`,()=>this.compileExhaustiveEntry(e))),e.traversalKind===`Allows`)return e.return(!0);this.structuralMorphRef&&e.if(`ctx && !ctx.hasError()`,()=>(e.line(`ctx.queueMorphs([`),Ki(e,this),e.line(`])`)))}compileExhaustiveEntry(e){if(e.const(`k`,`keys[i]`),this.index)for(let t of this.index)e.if(`${e.invoke(t.signature,{arg:`k`,kind:`Allows`})}`,()=>e.traverseKey(`k`,`data[k]`,t.value));return this.undeclared===`reject`&&e.if(`!(${this._compileDeclaresKey(e)})`,()=>e.traversalKind===`Allows`?e.return(!1):e.line(`ctx.errorFromNodeContext({ code: "predicate", expected: "removed", actual: "", relativePath: [k], meta: ${this.compiledMeta} })`).if(`ctx.failFast`,()=>e.return())),e}reduceJsonSchema(e,t){switch(e.type){case`object`:return this.reduceObjectJsonSchema(e,t);case`array`:let n=this.sequence?.reduceJsonSchema(e,t)??e;return this.props.length||this.index?t.fallback.arrayObject({code:`arrayObject`,base:n,object:this.reduceObjectJsonSchema({type:`object`},t)}):n;default:return M.throwInternalOperandError(`structure`,e)}}reduceObjectJsonSchema(e,t){if(this.props.length){e.properties={};for(let n of this.props){let r=n.value.toJsonSchemaRecurse(t);if(typeof n.key==`symbol`){t.fallback.symbolKey({code:`symbolKey`,base:e,key:n.key,value:r,optional:n.optional});continue}if(n.hasDefault()){let e=typeof n.default==`function`?n.default():n.default;r.default=w.intrinsic.jsonData.allows(e)?e:t.fallback.defaultValue({code:`defaultValue`,base:r,value:e})}e.properties[n.key]=r}this.requiredKeys.length&&e.properties&&(e.required=this.requiredKeys.filter(t=>typeof t==`string`&&t in e.properties))}if(this.index)for(let n of this.index){let r=n.value.toJsonSchemaRecurse(t);if(n.signature.equals(w.intrinsic.string)){e.additionalProperties=r;continue}for(let i of n.signature.branches){if(!i.extends(w.intrinsic.string)){e=t.fallback.symbolKey({code:`symbolKey`,base:e,key:null,value:r,optional:!1});continue}let n={type:`string`};if(i.hasKind(`morph`)&&(n=t.fallback.morph({code:`morph`,base:i.rawIn.toJsonSchemaRecurse(t),out:i.rawOut.toJsonSchemaRecurse(t)})),!i.hasKind(`intersection`))return m(`Unexpected index branch kind ${i.kind}.`);let{pattern:a}=i.inner;if(a){let i=Object.assign(n,{pattern:a[0].rule});for(let e=1;e<a.length;e++)n=t.fallback.patternIntersection({code:`patternIntersection`,base:i,pattern:a[e].rule});e.patternProperties??={},e.patternProperties[i.pattern]=r}}}return this.undeclared&&!e.additionalProperties&&(e.additionalProperties=!1),e}};const Ui={},Wi=e=>{let t=``;for(let n=0;n<e.defaultable.length;n++)t+=e.defaultable[n].defaultValueMorphRef;if(e.sequence?.defaultValueMorphsReference&&(t+=e.sequence?.defaultValueMorphsReference),e.undeclared===`delete`){if(t+=`delete !(`,e.required)for(let n of e.required)t+=n.compiledKey+` | `;if(e.optional)for(let n of e.optional)t+=n.compiledKey+` | `;if(e.index)for(let n of e.index)t+=n.signature.id+` | `;if(e.sequence)if(e.sequence.maxLength===null)t+=q.nonNegativeIntegerString.id;else for(let n=0;n<e.sequence.tuple.length;n++)t+=n+` | `;t+=`)`}return t},Gi=e=>{let t=Wi(e);return t?Ui[t]?Ui[t]:Ui[t]=(t,n)=>{for(let r=0;r<e.defaultable.length;r++)e.defaultable[r].key in t||e.defaultable[r].defaultValueMorph(t,n);if(e.sequence?.defaultables)for(let r=t.length-e.sequence.prefixLength;r<e.sequence.defaultables.length;r++)e.sequence.defaultValueMorphs[r](t,n);if(e.undeclared===`delete`)for(let n in t)e.declaresKey(n)||delete t[n];return t}:void 0},Ki=(e,t)=>{let n=`(data${t.defaultable.some(e=>e.defaultValueMorph.length===2)||t.sequence?.defaultValueMorphs.some(e=>e.length===2)?`, ctx`:``})`;return e.block(`${n} => `,e=>{for(let r=0;r<t.defaultable.length;r++){let{serializedKey:i,defaultValueMorphRef:a}=t.defaultable[r];e.if(`!(${i} in data)`,e=>e.line(`${a}${n}`))}return t.sequence?.defaultables&&e.for(`i < ${t.sequence.defaultables.length}`,e=>e.set(`data[i]`,5),`data.length - ${t.sequence.prefixLength}`),t.undeclared===`delete`&&e.forIn(`data`,e=>e.if(`!(${t._compileDeclaresKey(e)})`,e=>e.line(`delete data[k]`))),e.return(`data`)})},qi={implementation:Vi,Node:Hi},Ji=e=>(O(e,`root`)&&e.hasKind(`unit`)&&(e=e.unit),typeof e==`number`&&(e=`${e}`),e),Yi=(e,t)=>`${e} is not allowed as an array index on ${t}. Use the 'nonNegativeIntegerString' keyword instead.`,Xi=(e,n,r)=>{let[i,o]=t(e.branches,e=>e.hasKind(`unit`));if(!i.length)return{index:r.node(`index`,{signature:e,value:n})};let s={};for(let e of i){let t=r.node(`required`,{key:e.unit,value:n});s[t.kind]=a(s[t.kind],t)}return o.length&&(s.index=r.node(`index`,{signature:o,value:n})),s},Zi=e=>O(e,`root`)?e.expression:C(e),Qi=(e,t)=>`Key${t.length===1?``:`s`} ${t.map(Zi).join(`, `)} ${t.length===1?`does`:`do`} not exist on ${e}`,$i=e=>`Duplicate key ${E(e)}`,ea={...or,alias:Gr.implementation,domain:qr.implementation,unit:bi.implementation,proto:$r.implementation,union:li.implementation,morph:Zr.implementation,intersection:Jr.implementation,divisor:Rn.implementation,pattern:cr.implementation,predicate:Ln.implementation,required:Ti.implementation,optional:Cr.implementation,index:Si.implementation,sequence:Ai.implementation,structure:qi.implementation};w.defaultConfig=he(Object.assign(g(ea,(e,t)=>[e,t.defaults]),{jitless:Fe(),clone:Ae,onUndeclaredKey:`ignore`,exactOptionalPropertyTypes:!0,numberAllowsNaN:!1,dateAllowsInvalid:!1,onFail:null,keywords:{},toJsonSchema:M.defaultConfig})),w.resolvedConfig=en(w.defaultConfig,w.config);const ta={...sr,alias:Gr.Node,domain:qr.Node,unit:bi.Node,proto:$r.Node,union:li.Node,morph:Zr.Node,intersection:Jr.Node,divisor:Rn.Node,pattern:cr.Node,predicate:Ln.Node,required:Ti.Node,optional:Cr.Node,index:Si.Node,sequence:Ai.Node,structure:qi.Node};var na=class extends se{get[D](){return`module`}};const ra=(e,t)=>new na(g(e,(e,n)=>[e,O(n,`module`)?ra(n,t):t.bindReference(n)])),ia=e=>y(e)?e:`branches`in e&&y(e.branches)?e.branches:void 0,aa=(e,t)=>h(`Node of kind ${t} is not valid as a ${e} definition`),oa=e=>`#${e} duplicates public alias ${e}`,sa={};w.ambient??={};let ca;const la=`function $`,ua=e=>da(e,fa(e)),da=(e,t)=>{let n=t.write(la,4),r=t.compile()();for(let t of e)t.precompilation||=(t.traverseAllows=r[`${t.id}Allows`].bind(r),t.isRoot()&&!t.allowsRequiresContext&&(t.allows=t.traverseAllows),t.traverseApply=r[`${t.id}Apply`].bind(r),r[`${t.id}Optimistic`]&&(t.traverseOptimistic=r[`${t.id}Optimistic`].bind(r)),n)},fa=e=>new Pt().return(e.reduce((e,t)=>{let n=new Rt({kind:`Allows`}).indent();t.compile(n);let r=n.write(`${t.id}Allows`),i=new Rt({kind:`Apply`}).indent();t.compile(i);let a=`${e}${r},\n${i.write(`${t.id}Apply`)},\n`;if(!t.hasKind(`union`))return a;let o=new Rt({kind:`Allows`,optimistic:!0}).indent();return t.compile(o),`${a}${o.write(`${t.id}Optimistic`)},\n`},`{ `)+`}`);var pa=class{config;resolvedConfig;name;get[D](){return`scope`}referencesById={};references=[];resolutions={};exportedNames=[];aliases={};resolved=!1;nodesByHash={};intrinsic;constructor(e,t){this.config=en(w.config,t),this.resolvedConfig=en(w.resolvedConfig,t),this.name=this.resolvedConfig.name??`anonymousScope${Object.keys(sa).length}`,this.name in sa&&h(`A Scope already named ${this.name} already exists`),sa[this.name]=this;let n=Object.entries(e).map(e=>this.preparseOwnAliasEntry(...e));for(let[e,t]of n){let n=e;if(e[0]===`#`?(n=e.slice(1),n in this.aliases&&h(oa(n)),this.aliases[n]=t):(n in this.aliases&&h(oa(e)),this.aliases[n]=t,this.exportedNames.push(n)),!O(t,`module`)&&!O(t,`generic`)&&!Ne(t)){let e=this.preparseOwnDefinitionFormat(t,{alias:n});this.resolutions[n]=O(e,`root`)?this.bindReference(e):this.createParseContext(e).id}}ca??=this.node(`union`,{branches:[`string`,`number`,`object`,`bigint`,`symbol`,{unit:!0},{unit:!1},{unit:void 0},{unit:null}]},{prereduced:!0}),this.nodesByHash[ca.hash]=this.node(`intersection`,{},{prereduced:!0}),this.intrinsic=w.intrinsic?g(w.intrinsic,(e,t)=>e.startsWith(`json`)?[]:[e,this.bindReference(t)]):{}}cacheGetter(e,t){return Object.defineProperty(this,e,{value:t}),t}get internal(){return this}_json;get json(){return this._json||this.export(),this._json}defineSchema(e){return e}generic=(...e)=>{let t=this;return(n,r)=>new Fn(e,r?new Pn(n):n,t,t,r??null)};units=(e,t)=>{let n=[];for(let t of e)n.includes(t)||n.push(t);let r=n.map(e=>this.node(`unit`,{unit:e},t));return this.node(`union`,r,{...t,prereduced:!0})};lazyResolutions=[];lazilyResolve(e,t){let n=this.node(`alias`,{reference:t??`synthetic`,resolve:e},{prereduced:!0});return this.resolved||this.lazyResolutions.push(n),n}schema=(e,t)=>this.finalize(this.parseSchema(e,t));parseSchema=(e,t)=>this.node(lr(e),e,t);preparseNode(e,t,n){let r=typeof e==`string`?e:lr(t,e);if(k(t)&&t.kind===r)return t;if(r===`alias`&&!n?.prereduced){let{reference:e}=Gr.implementation.normalize(t,this);if(e.startsWith(`$`)){let n=this.resolveRoot(e.slice(1));t=n,r=n.kind}}else if(r===`union`&&d(t,`object`)){let e=ia(t);e?.length===1&&(t=e[0],r=lr(t))}if(k(t)&&t.kind===r)return t;let i=ea[r].normalize?.(t,this)??t;return k(i)?i.kind===r?i:aa(r,i.kind):{...n,$:this,kind:r,def:i,prefix:n.alias??r}}bindReference(e){let t;return t=k(e)?e.$===this?e:new e.constructor(e.attachments,this):e.$===this?e:new Fn(e.params,e.bodyDef,e.$,this,e.hkt),this.resolved||Object.assign(this.referencesById,t.referencesById),t}resolveRoot(e){return this.maybeResolveRoot(e)??h(xa(e))}maybeResolveRoot(e){let t=this.maybeResolve(e);if(!O(t,`generic`))return t}maybeResolveSubalias(e){return _a(this.aliases,e)??_a(this.ambient,e)}get ambient(){return w.ambient}maybeResolve(e){let t=this.resolutions[e];if(t){if(typeof t!=`string`)return this.bindReference(t);let n=W[t];if(O(n,`root`))return this.resolutions[e]=n;if(O(n,`context`)){if(n.phase===`resolving`)return this.node(`alias`,{reference:`$${e}`},{prereduced:!0});if(n.phase===`resolved`)return m(`Unexpected resolved context for was uncached by its scope: ${C(n)}`);n.phase=`resolving`;let t=this.bindReference(this.parseOwnDefinitionFormat(n.def,n));return n.phase=`resolved`,W[t.id]=t,W[n.id]=t,this.resolutions[e]=t}return m(`Unexpected nodesById entry for ${t}: ${C(n)}`)}let n=this.aliases[e]??this.ambient?.[e];return n?(n=this.normalizeRootScopeValue(n),O(n,`generic`)?this.resolutions[e]=this.bindReference(n):O(n,`module`)?(n.root||h(Ca(e)),this.resolutions[e]=this.bindReference(n.root)):this.resolutions[e]=this.parse(n,{alias:e})):this.maybeResolveSubalias(e)}createParseContext(e){let t=e.id??mr(e.prefix);return W[t]=Object.assign(e,{[D]:`context`,$:this,id:t,phase:`unresolved`})}traversal(e){return new P(e,this.resolvedConfig)}import(...e){return new na(g(this.export(...e),(e,t)=>[`#${e}`,t]))}precompilation;_exportedResolutions;_exports;export(...e){if(!this._exports){this._exports={};for(let e of this.exportedNames){let t=this.aliases[e];this._exports[e]=O(t,`module`)?ra(t,this):ha(this.maybeResolve(e))}for(let e of this.lazyResolutions)e.resolution;if(this._exportedResolutions=ba(this,this._exports),this._json=ga(this._exportedResolutions),Object.assign(this.resolutions,this._exportedResolutions),this.references=Object.values(this.referencesById),!this.resolvedConfig.jitless){let e=fa(this.references);this.precompilation=e.write(la,4),da(this.references,e)}this.resolved=!0}return new na(g(e.length?e:this.exportedNames,(e,t)=>[t,this._exports[t]]))}resolve(e){return this.export()[e]}node=(e,t,n={})=>{let r=this.preparseNode(e,t,n);if(k(r))return this.bindReference(r);let i=this.createParseContext(r),a=hr(i),o=this.bindReference(a);return W[i.id]=o};parse=(e,t={})=>this.finalize(this.parseDefinition(e,t));parseDefinition(e,t={}){if(O(e,`root`))return this.bindReference(e);let n=this.preparseOwnDefinitionFormat(e,t);if(O(n,`root`))return this.bindReference(n);let r=this.createParseContext(n);W[r.id]=r;let i=this.bindReference(this.parseOwnDefinitionFormat(e,r));return i.isCyclic&&(i=_r(i,r.id)),W[r.id]=i,i}finalize(e){return ha(e),!e.precompilation&&!this.resolvedConfig.jitless&&ua(e.references),e}},ma=class extends pa{parseOwnDefinitionFormat(e,t){return hr(t)}preparseOwnDefinitionFormat(e,t){return this.preparseNode(lr(e),e,t)}preparseOwnAliasEntry(e,t){return[e,t]}normalizeRootScopeValue(e){return e}};const ha=e=>{let t=e.references.filter(e=>e.hasKind(`alias`));for(let n of t){Object.assign(n.referencesById,n.resolution.referencesById);for(let t of e.references)n.id in t.referencesById&&Object.assign(t.referencesById,n.referencesById)}return e},ga=e=>g(e,(e,t)=>[e,O(t,`root`)||O(t,`generic`)?t.json:O(t,`module`)?ga(t):m(`Unexpected resolution ${C(t)}`)]),_a=(e,t)=>{let n=t.indexOf(`.`);if(n===-1)return;let r=t.slice(0,n),i=e[r];if(i===void 0)return;if(!O(i,`module`))return h(Sa(r));let a=t.slice(n+1),o=i[a];if(o===void 0)return _a(i,a);if(O(o,`root`)||O(o,`generic`))return o;if(O(o,`module`))return o.root??h(Ca(t));m(`Unexpected resolution for alias '${t}': ${C(o)}`)},va=(e,t)=>new ma(e,t),ya=new ma({}),ba=(e,t)=>{let n={};for(let r in t){let i=t[r];if(O(i,`module`)){let t=g(ba(e,i),(e,t)=>[`${r}.${e}`,t]);Object.assign(n,t)}else O(i,`root`)||O(i,`generic`)?n[r]=i:m(`Unexpected scope resolution ${C(i)}`)}return n},xa=e=>`'${e}' is unresolvable`,Sa=e=>`'${e}' must reference a module to be accessed using dot syntax`,Ca=e=>`Reference to submodule '${e}' must specify an alias`;ya.export();const G=ya.schema,wa=ya.node;ya.defineSchema;const K=ya.generic,Ta=`^(?:0|[1-9]\\d*)$`;T(new RegExp(Ta));const Ea=va({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:{},undefined:{unit:void 0},Array,Date},{prereducedAliases:!0}).export();w.intrinsic={...Ea};const Da=va({integer:{domain:`number`,divisor:1},lengthBoundable:[`string`,Array],key:[`string`,`symbol`],nonNegativeIntegerString:{domain:`string`,pattern:Ta}},{prereducedAliases:!0}).export();Object.assign(w.intrinsic,Da);const Oa=va({jsonPrimitive:[`string`,`number`,{unit:!0},{unit:!1},{unit:null}],jsonObject:{domain:`object`,index:{signature:`string`,value:`$jsonData`}},jsonData:[`$jsonPrimitive`,`$jsonObject`]},{prereducedAliases:!0}).export(),q={...Ea,...Da,...Oa,emptyStructure:wa(`structure`,{},{prereduced:!0})};w.intrinsic={...q};const ka=((e,t)=>new RegExp(e,t));Object.assign(ka,{as:ka});const Aa=e=>typeof e==`string`&&e[0]===`d`&&(e[1]===`'`||e[1]===`"`)&&e[e.length-1]===e[1],ja=e=>e.toString()!==`Invalid Date`,Ma=e=>e.slice(2,-1),Na=e=>`'${e}' could not be parsed by the Date constructor`,Pa=(e,t)=>Fa(e,t),Fa=(e,t)=>{let n=new Date(e);if(ja(n))return n;let r=it(e);if(r!==void 0){let e=new Date(r);if(ja(e))return e}return t?h(t===!0?Na(e):t):void 0},Ia=G({proto:`Array`,sequence:`string`,required:{key:`groups`,value:[`object`,{unit:void 0}]}}),La=(e,t)=>{let n=e.scanner.shiftUntilEscapable(Ua[Ha[t]]);if(e.scanner.lookahead===``)return e.error(Ga(n,t));if(e.scanner.shift(),t in Va){let r;try{r=new RegExp(n)}catch(e){h(String(e))}e.root=e.ctx.$.node(`intersection`,{domain:`string`,pattern:n},{prereduced:!0}),t===`x/`&&(e.root=e.ctx.$.node(`morph`,{in:e.root,morphs:e=>r.exec(e),declaredOut:Ia}))}else if(_(t,Ra))e.root=e.ctx.$.node(`unit`,{unit:n});else{let t=Pa(n,Na(n));e.root=e.ctx.$.node(`unit`,{meta:n,unit:t})}},Ra={"'":1,'"':1},za={"/":1,"'":1,'"':1},Ba={"d'":`'`,'d"':`"`,"'":`'`,'"':`"`},Va={"/":`/`,"x/":`/`},Ha={...Ba,...Va},Ua={"'":e=>e.lookahead===`'`,'"':e=>e.lookahead===`"`,"/":e=>e.lookahead===`/`},Wa={'"':`double-quote`,"'":`single-quote`,"/":`forward slash`},Ga=(e,t)=>`${t}${e} requires a closing ${Wa[Ha[t]]}`,Ka=e=>`Private type references should not include '#'. Use '${e}' instead.`,qa=`Optional definitions like 'string?' are only valid as properties in an object or tuple`,Ja=`Defaultable definitions like 'number = 0' are only valid as properties in an object or tuple`,Ya={"<":1,">":1,"=":1,"|":1,"&":1,")":1,"[":1,"%":1,",":1,":":1,"?":1,"#":1,...Ve},Xa=(e,t)=>e===`>`?t[0]===`=`?t[1]===`=`:t.trimStart()===``||_(t.trimStart()[0],Ya):e===`=`?t[0]!==`=`:e===`,`||e===`?`,Za=(e,t,n)=>Qa(e,t,n,[]),Qa=(e,t,n,r)=>{let i=n.parseUntilFinalizer();return r.push(i.root),i.finalizer===`>`?r.length===t.params.length?r:n.error($a(e,t.names,r.map(e=>e.expression))):i.finalizer===`,`?Qa(e,t,n,r):i.error(kt(`>`))},$a=(e,t,n)=>`${e}<${t.join(`, `)}> requires exactly ${t.length} args (got ${n.length}${n.length===0?``:`: ${n.join(`, `)}`})`,eo=e=>{let t=e.scanner.shiftUntilLookahead(Ya);t===`keyof`?e.addPrefix(`keyof`):e.root=no(e,t)},to=(e,t,n)=>(n.scanner.shiftUntilNonWhitespace(),n.scanner.shift()===`<`?t(...Za(e,t,n)):n.error($a(e,t.names,[]))),no=(e,t)=>ro(e,t)??io(e,t)??e.error(t===``?e.scanner.lookahead===`#`?Ka(e.shiftedBy(1).scanner.shiftUntilLookahead(Ya)):ao(e):xa(t)),ro=(e,t)=>{if(e.ctx.args?.[t]){let n=e.ctx.args[t];return typeof n==`string`?e.ctx.$.node(`alias`,{reference:n},{prereduced:!0}):n}let n=e.ctx.$.maybeResolve(t);if(O(n,`root`))return n;if(n!==void 0)return O(n,`generic`)?to(t,n,e):h(`Unexpected resolution ${C(n)}`)},io=(e,t)=>{let n=at(t);if(n!==void 0)return e.ctx.$.node(`unit`,{unit:n});let r=ct(t);if(r!==void 0)return e.ctx.$.node(`unit`,{unit:r})},ao=e=>{let t=e.previousOperator();return t?oo(t,e.scanner.unscanned):so(e.scanner.unscanned)},oo=(e,t=``)=>`Token '${e}' requires a right operand${t?` before '${t}'`:``}`,so=e=>`Expected an expression${e?` before '${e}'`:``}`,co=e=>e.scanner.lookahead===``?e.error(ao(e)):e.scanner.lookahead===`(`?e.shiftedBy(1).reduceGroupOpen():e.scanner.lookaheadIsIn(za)?La(e,e.scanner.shift()):e.scanner.lookaheadIsIn(Ve)?co(e.shiftedBy(1)):e.scanner.lookahead===`d`?e.scanner.nextLookahead in Ra?La(e,`${e.scanner.shift()}${e.scanner.shift()}`):eo(e):e.scanner.lookahead===`x`&&e.scanner.nextLookahead===`/`?e.shiftedBy(2)&&La(e,`x/`):eo(e),lo={">":!0,">=":!0},uo={"<":!0,"<=":!0},fo={"<":`>`,">":`<`,"<=":`>=`,">=":`<=`,"==":`==`},po=(e,t)=>`Left bounds are only valid when paired with right bounds (try ...${t}${e})`,mo=e=>`Left-bounded expressions must specify their limits using < or <= (was ${e})`,ho=(e,t,n,r)=>`An expression may have at most one left bound (parsed ${e}${fo[t]}, ${n}${fo[r]})`,go=(e,t)=>{let n=vo(e,t);if(e.root.hasKind(`unit`)){if(typeof e.root.unit==`number`){e.reduceLeftBound(e.root.unit,n),e.unsetRoot();return}if(e.root.unit instanceof Date){let t=`d'${e.root.description??e.root.unit.toISOString()}'`;e.unsetRoot(),e.reduceLeftBound(t,n);return}}return xo(e,n)},_o={"<":1,">":1,"=":1},vo=(e,t)=>e.scanner.lookaheadIs(`=`)?`${t}${e.scanner.shift()}`:t,yo=(e,t,n,r)=>n.extends(w.intrinsic.number)?typeof t==`number`?e===`==`?[`min`,`max`]:e[0]===`>`?[`min`]:[`max`]:h(So(e,t,r)):n.extends(w.intrinsic.lengthBoundable)?typeof t==`number`?e===`==`?[`exactLength`]:e[0]===`>`?[`minLength`]:[`maxLength`]:h(So(e,t,r)):n.extends(w.intrinsic.Date)?e===`==`?[`after`,`before`]:e[0]===`>`?[`after`]:[`before`]:h(Qn(n.expression)),bo=e=>({rule:Aa(e.limit)?Ma(e.limit):e.limit,exclusive:e.comparator.length===1}),xo=(e,t)=>{let n=e.unsetRoot(),r=e.scanner.location;e.parseOperand();let i=e.unsetRoot(),a=e.scanner.sliceChars(r,e.scanner.location);if(e.root=n,!i.hasKind(`unit`)||typeof i.unit!=`number`&&!(i.unit instanceof Date))return e.error(So(t,a,`right`));let o=i.unit,s=t.length===1,c=yo(t,typeof o==`number`?o:a,n,`right`);for(let n of c)e.constrainRoot(n,t===`==`?{rule:o}:{rule:o,exclusive:s});if(!e.branches.leftBound)return;if(!_(t,uo))return e.error(mo(t));let l=yo(e.branches.leftBound.comparator,e.branches.leftBound.limit,n,`left`);e.constrainRoot(l[0],bo(e.branches.leftBound)),e.branches.leftBound=null},So=(e,t,n)=>`Comparator ${n===`left`?fo[e]:e} must be ${n===`left`?`preceded`:`followed`} by a corresponding literal (was ${t})`,Co=e=>{e.scanner.shiftUntilNonWhitespace();let t=e.scanner.shiftUntilLookahead(Ya);e.root=e.root.brand(t)},wo=e=>{e.scanner.shiftUntilNonWhitespace();let t=e.scanner.shiftUntilLookahead(Ya),n=ot(t,{errorOnFail:To(t)});n===0&&e.error(To(0)),e.root=e.root.constrain(`divisor`,n)},To=e=>`% operator must be followed by a non-zero integer literal (was ${e})`,Eo=e=>{let t=e.scanner.shift();return t===``?e.finalize(``):t===`[`?e.scanner.shift()===`]`?e.setRoot(e.root.array()):e.error(Oo):t===`|`?e.scanner.lookahead===`>`?e.shiftedBy(1).pushRootToBranch(`|>`):e.pushRootToBranch(t):t===`&`?e.pushRootToBranch(t):t===`)`?e.finalizeGroup():Xa(t,e.scanner.unscanned)?e.finalize(t):_(t,_o)?go(e,t):t===`%`?wo(e):t===`#`?Co(e):t in Ve?Eo(e):e.error(Do(t))},Do=(e,t=``)=>`'${e}' is not allowed here${t&&` (should be ${t})`}`,Oo=`Missing expected ']'`,ko=e=>{let t=e.unsetRoot();e.parseOperand();let n=e.unsetRoot();return n.hasKind(`unit`)?[t,`=`,n.unit instanceof Date?()=>new Date(n.unit):n.unit]:e.error(Ao(n.expression))},Ao=e=>`Default value '${e}' must be a literal value`,jo=(e,t)=>{let n=t.$.maybeResolveRoot(e);if(n)return n;if(e.endsWith(`[]`)){let n=t.$.maybeResolveRoot(e.slice(0,-2));if(n)return n.array()}let r=new Fo(new Dt(e),t),i=Mo(r);return r.finalizer===`>`&&h(Do(`>`)),i},Mo=e=>{e.parseOperand();let t=No(e).root;return t?(e.finalizer===`=`?t=ko(e):e.finalizer===`?`&&(t=[t,`?`]),e.scanner.shiftUntilNonWhitespace(),e.scanner.lookahead&&h(Do(e.scanner.lookahead)),t):m(`Root was unexpectedly unset after parsing string '${e.scanner.scanned}'`)},No=e=>{for(;e.finalizer===void 0;)Po(e);return e},Po=e=>e.hasRoot()?e.parseOperator():e.parseOperand();var Fo=class e{root;branches={prefixes:[],leftBound:null,intersection:null,union:null,pipe:null};finalizer;groups=[];scanner;ctx;constructor(e,t){this.scanner=e,this.ctx=t}error(e){return h(e)}hasRoot(){return this.root!==void 0}setRoot(e){this.root=e}unsetRoot(){let 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(kt(`)`));this.finalizeBranches(),this.finalizer=e}reduceLeftBound(e,t){let n=fo[t];if(!_(n,lo))return this.error(mo(t));if(this.branches.leftBound)return this.error(ho(this.branches.leftBound.limit,this.branches.leftBound.comparator,e,n));this.branches.leftBound={comparator:n,limit:e}}finalizeBranches(){if(this.assertRangeUnset(),this.branches.pipe){this.pushRootToBranch(`|>`),this.root=this.branches.pipe;return}if(this.branches.union){this.pushRootToBranch(`|`),this.root=this.branches.union;return}if(this.branches.intersection){this.pushRootToBranch(`&`),this.root=this.branches.intersection;return}this.applyPrefixes()}finalizeGroup(){this.finalizeBranches();let e=this.groups.pop();if(!e)return this.error(Ot(`)`,this.scanner.unscanned));this.branches=e}addPrefix(e){this.branches.prefixes.push(e)}applyPrefixes(){for(;this.branches.prefixes.length;){let e=this.branches.prefixes.pop();this.root=e===`keyof`?this.root.keyof():m(`Unexpected prefix '${e}'`)}}pushRootToBranch(e){this.assertRangeUnset(),this.applyPrefixes();let t=this.root;this.root=void 0,this.branches.intersection=this.branches.intersection?.rawAnd(t)??t,e!==`&`&&(this.branches.union=this.branches.union?.rawOr(this.branches.intersection)??this.branches.intersection,this.branches.intersection=null,e!==`|`&&(this.branches.pipe=this.branches.pipe?.rawPipeOnce(this.branches.union)??this.branches.union,this.branches.union=null))}parseUntilFinalizer(){return No(new e(this.scanner,this.ctx))}parseOperator(){return Eo(this)}parseOperand(){return co(this)}assertRangeUnset(){if(this.branches.leftBound)return this.error(po(this.branches.leftBound.limit,this.branches.leftBound.comparator))}reduceGroupOpen(){this.groups.push(this.branches),this.branches={prefixes:[],leftBound:null,union:null,intersection:null,pipe:null}}previousOperator(){return this.branches.leftBound?.comparator??this.branches.prefixes[this.branches.prefixes.length-1]??(this.branches.intersection?`&`:this.branches.union?`|`:this.branches.pipe?`|>`:void 0)}shiftedBy(e){return this.scanner.jumpForward(e),this}};const Io=(e,t,n)=>{e.shiftUntilNonWhitespace();let r=e.shiftUntilLookahead(Ya);return r===``?e.lookahead===``&&t.length?t:h(`An empty string is not a valid generic parameter name`):(e.shiftUntilNonWhitespace(),Lo(e,r,t,n))},Lo=(e,t,n,r)=>{if(e.shiftUntilNonWhitespace(),e.unscanned.startsWith(`extends `))e.jumpForward(8);else return e.lookahead===`,`&&e.shift(),n.push(t),Io(e,n,r);let i=No(new Fo(e,r));return n.push([t,i.root]),Io(e,n,r)};var Ro=class extends b{constructor(e){let t={$:e,raw:e.fn};super((...t)=>{let n=t.indexOf(`:`),r=n===-1?t.length-1:n-1,i=t.slice(0,r+1),a=e.parse(i).assertHasKind(`intersection`),o=e.intrinsic.unknown;if(n!==-1){if(n!==t.length-2)return h(Bo);o=e.parse(t[n+1])}return e=>new zo(e,a,o)},{attach:t})}},zo=class extends b{raw;params;returns;expression;constructor(e,t,n){let r=`typed ${e.name}`,i={[r]:(...r)=>{let i=e(...t.assert(r));return n.assert(i)}}[r];super(i),this.raw=e,this.params=t,this.returns=n;let a=t.expression;a[0]===`[`&&a[a.length-1]===`]`?a=a.slice(1,-1):a.endsWith(`[]`)&&(a=`...${a}`),this.expression=`(${a}) => ${n?.expression??`unknown`}`}};const Bo=`":" must be followed by exactly one return type e.g: fn("string", ":", "number")(s => s.length)`;var Vo=class extends b{$;constructor(e){super((...t)=>new Ho(e)(...t),{bind:e}),this.$=e}in(e){return new Ho(this.$,e===void 0?void 0:this.$.parse(e))}at(e,t){return new Ho(this.$).at(e,t)}case(e,t){return new Ho(this.$).case(e,t)}},Ho=class extends b{$;in;key;branches=[];constructor(e,t){super(e=>this.caseEntries(Object.entries(e).map(([e,t])=>e===`default`?[e,t]:[this.$.parse(e),t]))),this.$=e,this.in=t}at(e,t){return this.key&&h(Go),this.branches.length&&h(Wo),this.key=e,t?this.match(t):this}case(e,t){return this.caseEntry(this.$.parse(e),t)}caseEntry(e,t){let n=(this.key?this.$.parse({[this.key]:e}):e).pipe(t);return this.branches.push(n),this}match(e){return this(e)}strings(e){return this.caseEntries(Object.entries(e).map(([e,t])=>e===`default`?[e,t]:[this.$.node(`unit`,{unit:e}),t]))}caseEntries(e){for(let t=0;t<e.length;t++){let[n,r]=e[t];if(n===`default`)return t!==e.length-1&&h(`default may only be specified as the last key of a switch definition`),this.default(r);if(typeof r!=`function`)return h(`Value for case "${n}" must be a function (was ${f(r)})`);this.caseEntry(n,r)}return this}default(e){typeof e==`function`&&this.case(q.unknown,e);let t={branches:this.branches,ordered:!0};(e===`never`||e===`assert`)&&(t.meta={onFail:Uo});let n=this.$.node(`union`,t);if(!this.in)return this.$.finalize(n);let r=this.in.pipe(n);return(e===`never`||e===`assert`)&&(r=r.configureReferences({onFail:Uo},`self`)),this.$.finalize(r)}};const Uo=e=>e.throw(),Wo=`A key matcher must be specified before the first case i.e. match.at('foo') or match.in<object>().at('bar')`,Go=`At most one key matcher may be specified per expression`,Ko=(e,t)=>{if(y(e)){if(e[1]===`=`)return[t.$.parseOwnDefinitionFormat(e[0],t),`=`,e[2]];if(e[1]===`?`)return[t.$.parseOwnDefinitionFormat(e[0],t),`?`]}return Ds(e,t)},qo=(e,t)=>{let n,r={},i=pe(e);for(let[e,o]of i){let i=Zo(e);if(i.kind===`spread`){if(!fe(r))return h(Xo);let e=t.$.parseOwnDefinitionFormat(o,t);if(e.equals(q.object))continue;if(!e.hasKind(`intersection`)||!e.basis?.equals(q.object))return h(Qo(e.expression));n=e.structure;continue}if(i.kind===`undeclared`){o!==`reject`&&o!==`delete`&&o!==`ignore`&&h(Yo(o)),r.undeclared=o;continue}let s=Ko(o,t),c=i;if(i.kind===`required`){y(s)?Jo(r,`optional`,s[1]===`=`?{key:i.normalized,value:s[0],default:s[2]}:{key:i.normalized,value:s[0]},t):Jo(r,`required`,{key:i.normalized,value:s},t);continue}if(y(s)&&(s[1]===`?`&&h(`Only required keys may make their values optional, e.g. { [mySymbol]: ['number', '?'] }`),s[1]===`=`&&h(`Only required keys may specify default values, e.g. { value: 'number = 0' }`)),i.kind===`optional`){Jo(r,`optional`,{key:i.normalized,value:s},t);continue}let l=Xi(t.$.parseOwnDefinitionFormat(c.normalized,t),s,t.$);l.index&&(r.index=a(r.index,l.index)),l.required&&(r.required=a(r.required,l.required))}let o=t.$.node(`structure`,r);return t.$.parseSchema({domain:`object`,structure:n?.merge(o)??o})},Jo=(e,t,n,r)=>{e[t]=a(e[t],r.$.node(t,n))},Yo=e=>`Value of '+' key must be 'reject', 'delete', or 'ignore' (was ${C(e)})`,Xo=`Spread operator may only be used as the first key in an object`,Zo=e=>typeof e==`symbol`?{kind:`required`,normalized:e}:e[e.length-1]===`?`?e[e.length-2]===`\\`?{kind:`required`,normalized:`${e.slice(0,-2)}?`}:{kind:`optional`,normalized:e.slice(0,-1)}:e[0]===`[`&&e[e.length-1]===`]`?{kind:`index`,normalized:e.slice(1,-1)}:e[0]===`\\`&&e[1]===`[`&&e[e.length-1]===`]`?{kind:`required`,normalized:e.slice(1)}:e===`...`?{kind:`spread`}:e===`+`?{kind:`undeclared`}:{kind:`required`,normalized:e===`\\...`?`...`:e===`\\+`?`+`:e},Qo=e=>`Spread operand must resolve to an object literal type (was ${e})`,$o=(e,t)=>ps(e)?fs[e[0]](e,t):ds(e)?us[e[1]](e,t):null,es=(e,t)=>t.$.parseOwnDefinitionFormat(e[1],t).keyof(),ts=(e,t)=>{if(e[2]===void 0)return h(oo(e[1],``));let n=t.$.parseOwnDefinitionFormat(e[0],t),r=t.$.parseOwnDefinitionFormat(e[2],t);if(e[1]===`|`)return t.$.node(`union`,{branches:[n,r]});let i=e[1]===`&`?z(n,r,t.$):Sn(n,r,t.$);return i instanceof L?i.throw():i},ns=(e,t)=>t.$.parseOwnDefinitionFormat(e[0],t).array(),rs=(e,t)=>typeof e[2]==`function`?t.$.parseOwnDefinitionFormat(e[0],t).pipe(e[2]):h(is(`=>`,e[2])),is=(e,t)=>`${e===`:`?`Narrow`:`Morph`} expression requires a function following '${e}' (was ${typeof t})`,as=(e,t)=>typeof e[2]==`function`?t.$.parseOwnDefinitionFormat(e[0],t).constrain(`predicate`,e[2]):h(is(`:`,e[2])),os=(e,t)=>t.$.parseOwnDefinitionFormat(e[0],t).configure(e[2],e[3]),ss=e=>e,cs=ss({"[]":ns,"?":()=>h(qa)}),ls=ss({"|":ts,"&":ts,":":as,"=>":rs,"|>":ts,"@":os,"=":()=>h(Ja)}),us={...cs,...ls},ds=e=>us[e[1]]!==void 0,fs=(e=>e)({keyof:es,instanceof:(e,t)=>{if(typeof e[1]!=`function`)return h(ms(Ce(e[1])));let n=e.slice(1).map(e=>typeof e==`function`?t.$.node(`proto`,{proto:e}):h(ms(Ce(e))));return n.length===1?n[0]:t.$.node(`union`,{branches:n})},"===":(e,t)=>t.$.units(e.slice(1))}),ps=e=>fs[e[0]]!==void 0,ms=e=>`Expected a constructor following 'instanceof' operator (was ${e})`,hs=(e,t)=>{let n=[{}],r=0;for(;r<e.length;){let i=!1;e[r]===`...`&&r<e.length-1&&(i=!0,r++);let a=Ko(e[r],t),[o,s,c]=y(a)?a:[a];if(r++,i){if(!o.extends(w.intrinsic.Array))return h(xs(o.expression));n=n.flatMap(e=>o.distribute(t=>bs(zt(e),t)))}else n=n.map(e=>s===`?`?_s(e,o):s===`=`?vs(e,o,c):gs(e,o))}return t.$.parseSchema(n.map(e=>fe(e)?{proto:Array,exactLength:0}:{proto:Array,sequence:e}))},gs=(e,t)=>e.defaultables||e.optionals?h(e.variadic?Ni:Cs):(e.variadic?e.postfix=a(e.postfix,t):e.prefix=a(e.prefix,t),e),_s=(e,t)=>e.variadic?h(ws):(e.optionals=a(e.optionals,t),e),vs=(e,t,n)=>e.variadic?h(ws):e.optionals?h(Ts):(e.defaultables=a(e.defaultables,[[t,n]]),e),ys=(e,t)=>(e.postfix&&h(Ss),e.variadic?e.variadic.equals(t)||h(Ss):e.variadic=t.internal,e),bs=(e,t)=>{let n=t.select({method:`find`,kind:`sequence`});if(!n)return ys(e,w.intrinsic.unknown);if(n.prefix)for(let t of n.prefix)gs(e,t);if(n.optionals)for(let t of n.optionals)_s(e,t);if(n.variadic&&ys(e,n.variadic),n.postfix)for(let t of n.postfix)gs(e,t);return e},xs=e=>`Spread element must be an array (was ${e})`,Ss=`A tuple may have at most one variadic element`,Cs=`A required element may not follow an optional element`,ws=`An optional element may not follow a variadic element`,Ts=`A defaultable element may not follow an optional element without a default`,Es={},Ds=(e,t)=>{if(typeof e==`string`){if(t.args&&Object.keys(t.args).some(t=>e.includes(t)))return jo(e,t);let n=Es[t.$.name]??={};return n[e]??=jo(e,t)}return d(e,`object`)?Os(e,t):h(js(f(e)))},Os=(e,t)=>{let n=Se(e);switch(n){case void 0:return O(e,`root`)?e:`~standard`in e?ks(e,t):qo(e,t);case`Array`:return As(e,t);case`RegExp`:return t.$.node(`intersection`,{domain:`string`,pattern:e},{prereduced:!0});case`Function`:{let t=Ne(e)?e():e;return O(t,`root`)?t:h(js(`Function`))}default:return h(js(n??C(e)))}},ks=(e,t)=>t.$.intrinsic.unknown.pipe((t,n)=>{let r=e[`~standard`].validate(t);if(!r.issues)return r.value;for(let{message:e,path:t}of r.issues)t&&t.length?n.error({problem:Re(e),relativePath:t.map(e=>typeof e==`object`?e.key:e)}):n.error({message:e})}),As=(e,t)=>$o(e,t)??hs(e,t),js=e=>`Type definitions must be strings or objects (was ${e})`;var Ms=class extends b{constructor(e){let t=Object.assign({errors:N,hkt:x,$:e,raw:e.parse,module:e.constructor.module,scope:e.constructor.scope,declare:e.declare,define:e.define,match:e.match,generic:e.generic,schema:e.schema,keywords:e.ambient,unit:e.unit,enumerated:e.enumerated,instanceOf:e.instanceOf,valueOf:e.valueOf,or:e.or,and:e.and,merge:e.merge,pipe:e.pipe,fn:e.fn},e.ambientAttachments);super((...t)=>{if(t.length===1)return e.parse(t[0]);if(t.length===2&&typeof t[0]==`string`&&t[0][0]===`<`&&t[0][t[0].length-1]===`>`){let n=t[0].slice(1,-1);return new Fn(e.parseGenericParams(n,{}),t[1],e,e,null)}return e.parse(t)},{attach:t})}};const Ns=w;var Ps=class e extends pa{get ambientAttachments(){if(Ns.typeAttachments)return this.cacheGetter(`ambientAttachments`,g(Ns.typeAttachments,(e,t)=>[e,this.bindReference(t)]))}preparseOwnAliasEntry(e,t){let n=e.indexOf(`<`);if(n===-1){if(O(t,`module`)||O(t,`generic`))return[e,t];let n=this.name===`ark`?e:e===`root`?this.name:`${this.name}.${e}`,r=this.resolvedConfig.keywords?.[n];return r&&(t=[t,`@`,r]),[e,t]}e[e.length-1]!==`>`&&h(`'>' must be the last character of a generic declaration in a scope`);let r=e.slice(0,n),i=e.slice(n+1,-1);return[r,()=>Nn(this.parseGenericParams(i,{alias:r}),t,this)]}parseGenericParams(e,t){return Io(new Dt(e),[],this.createParseContext({...t,def:e,prefix:`generic`}))}normalizeRootScopeValue(e){return Ne(e)&&!O(e,`generic`)?e():e}preparseOwnDefinitionFormat(e,t){return{...t,def:e,prefix:t.alias??`type`}}parseOwnDefinitionFormat(e,t){!(t.alias&&t.alias in this.aliases)&&!t.args&&(t.args={this:t.id});let n=Ds(e,t);if(y(n)){if(n[1]===`=`)return h(Ja);if(n[1]===`?`)return h(qa)}return n}unit=e=>this.units([e]);valueOf=e=>this.units(ge(e));enumerated=(...e)=>this.units(e);instanceOf=e=>this.node(`proto`,{proto:e},{prereduced:!0});or=(...e)=>this.schema(e.map(e=>this.parse(e)));and=(...e)=>e.reduce((e,t)=>e.and(this.parse(t)),this.intrinsic.unknown);merge=(...e)=>e.reduce((e,t)=>e.merge(this.parse(t)),this.intrinsic.object);pipe=(...e)=>this.intrinsic.unknown.pipe(...e);fn=new Ro(this);match=new Vo(this);declare=()=>({type:this.type});define(e){return e}type=new Ms(this);static scope=((t,n={})=>new e(t,n));static module=((e,t={})=>this.scope(e,t).export())};const Fs=Object.assign(Ps.scope,{define:e=>e}),J=Ps;var Is=class extends x{description='merge an object\'s properties onto another like `Merge(User, { isAdmin: "true" })`'};const Ls=K([`base`,q.object],[`props`,q.object])(e=>e.base.merge(e.props),Is),Rs=J.module({Key:q.key,Merge:Ls});var zs=class extends x{};const Bs=K(`element`)(t=>{let n=t.element.exclude(q.Array),r=n.array();return n.rawOr(r).pipe(e).distribute(e=>e.assertHasKind(`morph`).declareOut(r),G)},zs),Vs=J.module({root:q.Array,readonly:`root`,index:q.nonNegativeIntegerString,liftFrom:Bs},{name:`Array`}),Hs=G([`string`,lt.FileConstructor]),Us=G({meta:`an object representing parsed form data`,domain:`object`,index:{signature:`string`,value:Hs.rawOr(Hs.array())}}),Ws=J.module({root:[`instanceof`,FormData],value:Hs,parsed:Us,parse:G({in:FormData,morphs:e=>{let t={};for(let[n,r]of e)if(n in t){let e=t[n];typeof e==`string`||e instanceof lt.FileConstructor?t[n]=[e,r]:e.push(r)}else t[n]=r;return t},declaredOut:Us})},{name:`FormData`}),Gs=J.module({Int8:[`instanceof`,Int8Array],Uint8:[`instanceof`,Uint8Array],Uint8Clamped:[`instanceof`,Uint8ClampedArray],Int16:[`instanceof`,Int16Array],Uint16:[`instanceof`,Uint16Array],Int32:[`instanceof`,Int32Array],Uint32:[`instanceof`,Uint32Array],Float32:[`instanceof`,Float32Array],Float64:[`instanceof`,Float64Array],BigInt64:[`instanceof`,BigInt64Array],BigUint64:[`instanceof`,BigUint64Array]},{name:`TypedArray`}),Ks={Boolean:1,Number:1,String:1},qs=J.module({...g({..._e,...ye},(e,t)=>e in Ks?[]:[e,[`instanceof`,t]]),Array:Vs,TypedArray:Gs,FormData:Ws}),Js=G({domain:{domain:`number`,meta:`a number representing a Unix timestamp`},divisor:{rule:1,meta:`an integer representing a Unix timestamp`},min:{rule:-864e13,meta:`a Unix timestamp after -8640000000000000`},max:{rule:864e13,meta:`a Unix timestamp before 8640000000000000`},meta:`an integer representing a safe Unix timestamp`}),Ys=G({domain:`number`,divisor:1}),Xs=J.module({root:q.number,integer:Ys,epoch:Js,safe:G({domain:{domain:`number`,numberAllowsNaN:!1},min:-(2**53-1),max:2**53-1}),NaN:[`===`,NaN],Infinity:[`===`,1/0],NegativeInfinity:[`===`,-1/0]},{name:`number`}),Y=(e,t,n)=>{let r={domain:`string`,pattern:{rule:e.source,flags:e.flags,meta:t}};return n&&(r.meta={format:n}),wa(`intersection`,r)},Zs=Y(Ye,`a well-formed integer string`),Qs=J.module({root:Zs,parse:G({in:Zs,morphs:(e,t)=>{let n=Number.parseInt(e);return Number.isSafeInteger(n)?n:t.error(`an integer in the range Number.MIN_SAFE_INTEGER to Number.MAX_SAFE_INTEGER`)},declaredOut:q.integer})},{name:`string.integer`}),$s=Y(/^[\dA-Fa-f]+$/,`hex characters only`),ec=J.module({root:Y(/^(?:[\d+/A-Za-z]{4})*(?:[\d+/A-Za-z]{2}==|[\d+/A-Za-z]{3}=)?$/,`base64-encoded`),url:Y(/^(?:[\w-]{4})*(?:[\w-]{2}(?:==|%3D%3D)?|[\w-]{3}(?:=|%3D)?)?$/,`base64url-encoded`)},{name:`string.base64`}),tc=Y(/^[A-Z].*$/,`capitalized`),nc=J.module({root:G({in:`string`,morphs:e=>e.charAt(0).toUpperCase()+e.slice(1),declaredOut:tc}),preformatted:tc},{name:`string.capitalize`}),rc=G({domain:`string`,pattern:{meta:`a credit card number`,rule:`^(?:4\\d{12}(?:\\d{3,6})?|5[1-5]\\d{14}|(222[1-9]|22[3-9]\\d|2[3-6]\\d{2}|27[01]\\d|2720)\\d{12}|6(?:011|5\\d\\d)\\d{12,15}|3[47]\\d{13}|3(?:0[0-5]|[68]\\d)\\d{11}|(?:2131|1800|35\\d{3})\\d{11}|6[27]\\d{14}|^(81\\d{14,17}))$`},predicate:{meta:`a credit card number`,predicate:e=>{let t=e.replace(/[ -]+/g,``),n=0,r,i,a=!1;for(let e=t.length-1;e>=0;e--)r=t.substring(e,e+1),i=Number.parseInt(r,10),a?(i*=2,n+=i>=10?i%10+1:i):n+=i,a=!a;return!!(n%10==0&&t)}}}),ic=/^([+-]?\d{4}(?!\d{2}\b))((-?)((0[1-9]|1[0-2])(\3([12]\d|0[1-9]|3[01]))?|W([0-4]\d|5[0-3])(-?[1-7])?|(00[1-9]|0[1-9]\d|[12]\d{2}|3([0-5]\d|6[1-6])))(T((([01]\d|2[0-3])((:?)[0-5]\d)?|24:?00)([,.]\d+(?!:))?)?(\17[0-5]\d([,.]\d+)?)?([Zz]|([+-])([01]\d|2[0-3]):?([0-5]\d)?)?)?)?$/,ac=G({domain:`string`,predicate:{meta:`a parsable date`,predicate:e=>!Number.isNaN(new Date(e).valueOf())}}).assertHasKind(`intersection`),oc=Qs.root.internal.narrow((e,t)=>{let n=Number.parseInt(e),r=Xs.epoch(n);return r instanceof N?(t.errors.merge(r),!1):!0}).configure({description:`an integer string representing a safe Unix timestamp`},`self`).assertHasKind(`intersection`),sc=J.module({root:oc,parse:G({in:oc,morphs:e=>new Date(e),declaredOut:q.Date})},{name:`string.date.epoch`}),cc=Y(ic,`an ISO 8601 (YYYY-MM-DDTHH:mm:ss.sssZ) date`).internal.assertHasKind(`intersection`),lc=J.module({root:cc,parse:G({in:cc,morphs:e=>new Date(e),declaredOut:q.Date})},{name:`string.date.iso`}),uc=J.module({root:ac,parse:G({declaredIn:ac,in:`string`,morphs:(e,t)=>{let n=new Date(e);return Number.isNaN(n.valueOf())?t.error(`a parsable date`):n},declaredOut:q.Date}),iso:lc,epoch:sc},{name:`string.date`}),dc=Y(/^[\w%+.-]+@[\d.A-Za-z-]+\.[A-Za-z]{2,}$/,`an email address`,`email`),fc=`(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])`,X=`(${fc}[.]){3}${fc}`,pc=RegExp(`^${X}$`),Z=`(?:[0-9a-fA-F]{1,4})`,mc=RegExp(`^((?:${Z}:){7}(?:${Z}|:)|(?:${Z}:){6}(?:${X}|:${Z}|:)|(?:${Z}:){5}(?::${X}|(:${Z}){1,2}|:)|(?:${Z}:){4}(?:(:${Z}){0,1}:${X}|(:${Z}){1,3}|:)|(?:${Z}:){3}(?:(:${Z}){0,2}:${X}|(:${Z}){1,4}|:)|(?:${Z}:){2}(?:(:${Z}){0,3}:${X}|(:${Z}){1,5}|:)|(?:${Z}:){1}(?:(:${Z}){0,4}:${X}|(:${Z}){1,6}|:)|(?::((?::${Z}){0,5}:${X}|(?::${Z}){1,7}|:)))(%[0-9a-zA-Z.]{1,})?\$`),hc=J.module({root:[`v4 | v6`,`@`,`an IP address`],v4:Y(pc,`an IPv4 address`,`ipv4`),v6:Y(mc,`an IPv6 address`,`ipv6`)},{name:`string.ip`}),gc=`a JSON string`,_c=e=>{if(!(e instanceof SyntaxError))throw e;return`must be ${gc} (${e})`},vc=G({meta:gc,domain:`string`,predicate:{meta:gc,predicate:(e,t)=>{try{return JSON.parse(e),!0}catch(e){return t.reject({code:`predicate`,expected:gc,problem:_c(e)})}}}}),yc=J.module({root:vc,parse:G({meta:`safe JSON string parser`,in:`string`,morphs:(e,t)=>{if(e.length===0)return t.error({code:`predicate`,expected:gc,actual:`empty`});try{return JSON.parse(e)}catch(e){return t.error({code:`predicate`,expected:gc,problem:_c(e)})}},declaredOut:q.jsonObject})},{name:`string.json`}),bc=Y(/^[a-z]*$/,`only lowercase letters`),xc=J.module({root:G({in:`string`,morphs:e=>e.toLowerCase(),declaredOut:bc}),preformatted:bc},{name:`string.lower`}),Sc=[`NFC`,`NFD`,`NFKC`,`NFKD`],Cc=g(Sc,(e,t)=>[t,G({domain:`string`,predicate:e=>e.normalize(t)===e,meta:`${t}-normalized unicode`})]),wc=g(Sc,(e,t)=>[t,G({in:`string`,morphs:e=>e.normalize(t),declaredOut:Cc[t]})]),Tc=J.module({root:wc.NFC,preformatted:Cc.NFC},{name:`string.normalize.NFC`}),Ec=J.module({root:wc.NFD,preformatted:Cc.NFD},{name:`string.normalize.NFD`}),Dc=J.module({root:wc.NFKC,preformatted:Cc.NFKC},{name:`string.normalize.NFKC`}),Oc=J.module({root:wc.NFKD,preformatted:Cc.NFKD},{name:`string.normalize.NFKD`}),kc=J.module({root:`NFC`,NFC:Tc,NFD:Ec,NFKC:Dc,NFKD:Oc},{name:`string.normalize`}),Ac=Y(Ke,`a well-formed numeric string`),jc=J.module({root:Ac,parse:G({in:Ac,morphs:e=>Number.parseFloat(e),declaredOut:q.number})},{name:`string.numeric`}),Mc=`a regex pattern`,Nc=G({domain:`string`,predicate:{meta:Mc,predicate:(e,t)=>{try{return new RegExp(e),!0}catch(e){return t.reject({code:`predicate`,expected:Mc,problem:String(e)})}}},meta:{format:`regex`}}),Pc=Y(/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[A-Za-z-][\dA-Za-z-]*)(?:\.(?:0|[1-9]\d*|\d*[A-Za-z-][\dA-Za-z-]*))*))?(?:\+([\dA-Za-z-]+(?:\.[\dA-Za-z-]+)*))?$/,`a semantic version (see https://semver.org/)`),Fc=Y(/^\S.*\S$|^\S?$/,`trimmed`),Ic=J.module({root:G({in:`string`,morphs:e=>e.trim(),declaredOut:Fc}),preformatted:Fc},{name:`string.trim`}),Lc=Y(/^[A-Z]*$/,`only uppercase letters`),Rc=J.module({root:G({in:`string`,morphs:e=>e.toUpperCase(),declaredOut:Lc}),preformatted:Lc},{name:`string.upper`}),zc=G({domain:`string`,predicate:{meta:`a URL string`,predicate:e=>URL.canParse(e)},meta:{format:`uri`}}),Bc=J.module({root:zc,parse:G({declaredIn:zc,in:`string`,morphs:(e,t)=>{try{return new URL(e)}catch{return t.error(`a URL string`)}},declaredOut:G(URL)})},{name:`string.url`}),Vc=J.module({root:[`versioned | nil | max`,`@`,{description:`a UUID`,format:`uuid`}],"#nil":`'00000000-0000-0000-0000-000000000000'`,"#max":`'ffffffff-ffff-ffff-ffff-ffffffffffff'`,"#versioned":/[\da-f]{8}-[\da-f]{4}-[1-8][\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}/i,v1:Y(/^[\da-f]{8}-[\da-f]{4}-1[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,`a UUIDv1`),v2:Y(/^[\da-f]{8}-[\da-f]{4}-2[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,`a UUIDv2`),v3:Y(/^[\da-f]{8}-[\da-f]{4}-3[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,`a UUIDv3`),v4:Y(/^[\da-f]{8}-[\da-f]{4}-4[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,`a UUIDv4`),v5:Y(/^[\da-f]{8}-[\da-f]{4}-5[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,`a UUIDv5`),v6:Y(/^[\da-f]{8}-[\da-f]{4}-6[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,`a UUIDv6`),v7:Y(/^[\da-f]{8}-[\da-f]{4}-7[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,`a UUIDv7`),v8:Y(/^[\da-f]{8}-[\da-f]{4}-8[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,`a UUIDv8`)},{name:`string.uuid`}),Hc=J.module({root:q.string,alpha:Y(/^[A-Za-z]*$/,`only letters`),alphanumeric:Y(/^[\dA-Za-z]*$/,`only letters and digits 0-9`),hex:$s,base64:ec,capitalize:nc,creditCard:rc,date:uc,digits:Y(/^\d*$/,`only digits 0-9`),email:dc,integer:Qs,ip:hc,json:yc,lower:xc,normalize:kc,numeric:jc,regex:Nc,semver:Pc,trim:Ic,upper:Rc,url:Bc,uuid:Vc},{name:`string`}),Uc=J.module({bigint:q.bigint,boolean:q.boolean,false:q.false,never:q.never,null:q.null,number:q.number,object:q.object,string:q.string,symbol:q.symbol,true:q.true,unknown:q.unknown,undefined:q.undefined}),Wc=J.module({root:q.unknown,any:q.unknown},{name:`unknown`}),Gc=J.module({root:q.jsonObject,stringify:wa(`morph`,{in:q.jsonObject,morphs:e=>JSON.stringify(e),declaredOut:q.string})},{name:`object.json`}),Kc=J.module({root:q.object,json:Gc},{name:`object`});var qc=class extends x{description='instantiate an object from an index signature and corresponding value type like `Record("string", "number")`'};const Jc=K([`K`,q.key],`V`)(e=>({domain:`object`,index:{signature:e.K,value:e.V}}),qc);var Yc=class extends x{description='pick a set of properties from an object like `Pick(User, "name | age")`'};const Xc=K([`T`,q.object],[`K`,q.key])(e=>e.T.pick(e.K),Yc);var Zc=class extends x{description='omit a set of properties from an object like `Omit(User, "age")`'};const Qc=K([`T`,q.object],[`K`,q.key])(e=>e.T.omit(e.K),Zc);var $c=class extends x{description="make all named properties of an object optional like `Partial(User)`"};const el=K([`T`,q.object])(e=>e.T.partial(),$c);var tl=class extends x{description="make all named properties of an object required like `Required(User)`"};const nl=K([`T`,q.object])(e=>e.T.required(),tl);var rl=class extends x{description='exclude branches of a union like `Exclude("boolean", "true")`'};const il=K(`T`,`U`)(e=>e.T.exclude(e.U),rl);var al=class extends x{description='extract branches of a union like `Extract("0 | false | 1", "number")`'};const ol=K(`T`,`U`)(e=>e.T.extract(e.U),al),sl=J.module({Exclude:il,Extract:ol,Omit:Qc,Partial:el,Pick:Xc,Record:Jc,Required:nl}),Q=Fs({...Uc,...sl,...qs,...Rs,string:Hc,number:Xs,object:Kc,unknown:Wc},{prereducedAliases:!0,name:`ark`}),$=Q.export();Object.assign(Ns.ambient,$),Ns.typeAttachments={string:$.string.root,number:$.number.root,bigint:$.bigint,boolean:$.boolean,symbol:$.symbol,undefined:$.undefined,null:$.null,object:$.object.root,unknown:$.unknown.root,false:$.false,true:$.true,never:$.never,arrayIndex:$.Array.index,Key:$.Key,Record:$.Record,Array:$.Array.root,Date:$.Date};const cl=Object.assign(Q.type,Ns.typeAttachments);Q.match,Q.fn,Q.generic,Q.schema,Q.define,Q.declare;const ll=cl({id:`number`,created:`Date`,title:`1<=string<=100`,type:`'jpg'|'png'`,size:`number`,url:`string.url`}),ul=cl({id:`number`,stars:`1<=number<=5`,title:`1<=string<=100`,text:`1<=string<=1000`,images:ll.array()});cl({id:`number`,created:`Date`,title:`1<=string<=100`,brand:`1<=string<=30`,description:`1<=string<=500`,price:`1<=number<=10000`,discount:`1<=number<=100|null`,quantity:`1<=number<=10`,tags:`(1<=string<=30)[]`,images:ll.array(),ratings:ul.array()})({});