@paroicms/content-loading-plugin 0.27.3 → 0.27.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
|
@@ -1 +1 @@
|
|
|
1
|
-
|
|
1
|
+
.PaSearchApp-form{display:flex;justify-content:center;margin-bottom:20px}.PaSearchOpenerButton{cursor:pointer}.PaSearchOpenerButton-svg{fill:var(--paInteractiveColor, #000)}.PaSearchOpener{box-sizing:border-box;display:flex;gap:20px;justify-content:center;flex-direction:column;align-items:center;max-width:500px;padding:30px 5px;width:85vw}.PaSearchOpener-input{border:1px solid transparent;font-size:1.2rem;padding:10px;width:100%}.PaSearchOpener-button{cursor:pointer;padding:20px 25px}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{delegateEvents as fn,template as V,insert as J,setAttribute as kt,isServer as Ue,getRequestEvent as Jt,createComponent as E,memo as Vt,effect as pt,render as jr,setStyleProperty as oo}from"https://esm.sh/solid-js@1.9.9/web";import{createMemo as Z,getOwner as Fr,runWithOwner as Ur,useContext as zr,createContext as Tr,createSignal as Y,createRenderEffect as ao,on as We,startTransition as co,resetErrorBoundaries as lo,batch as uo,untrack as _r,createComponent as ho,children as Jr,mergeProps as po,Show as Se,createRoot as fo,onCleanup as Vr,sharedConfig as Kt,createEffect as Gr}from"https://esm.sh/solid-js@1.9.9";import mo from"https://esm.sh/@paroicms/tiny-modal@0.7.0";function go(t){let e=t;const n=e.indexOf("?");n!==-1&&(e=e.substring(0,n));const r=e.indexOf("#");r!==-1&&(e=e.substring(0,r));const i=e.lastIndexOf("/");return i===-1?void 0:e.slice(0,i)}function X(t){return t!=null&&t!==""}const jn=(t,e)=>new RegExp(t,e);Object.assign(jn,{cast:jn});const He=t=>Array.isArray(t)?t:[t],yo=(t,e)=>{const n=[[],[]];for(const r of t)e(r)?n[0].push(r):n[1].push(r);return n},Wr=Array,le=(t,e)=>t.includes(e),bo=(t,e=0)=>[...new Array(t)].map((n,r)=>r+e),N=(t,e,n)=>t===void 0?e===void 0?[]:Array.isArray(e)?e:[e]:(Array.isArray(e)?t.push(...e):t.push(e),t),ge=(t,e)=>e==null?t??[]:t==null?He(e):t.concat(e),$o=(...t)=>t.reduce(ge,[]),ye=(t,e,n)=>{if(t===void 0)return Array.isArray(e)?e:[e];const r=n?.isEqual??((i,s)=>i===s);for(const i of He(e))t.some(s=>r(s,i))||t.push(i);return t},wo=(t,e)=>t.reduce((n,r)=>{const i=r[e];return n[i]=N(n[i],r),n},{}),Ce=(t,e,n)=>t.length===e.length&&t.every(n?.isEqual?(r,i)=>n.isEqual(r,e[i]):(r,i)=>r===e[i]),$e=(t,e)=>Q(t)===e,Q=t=>{const e=typeof t;return e==="object"?t===null?"null":"object":e==="function"?"object":e},re={boolean:"boolean",null:"null",undefined:"undefined",bigint:"a bigint",number:"a number",object:"an object",string:"a string",symbol:"a symbol"},vo={...re,function:"a function"};class xo extends Error{}const D=t=>Me(t,xo),Me=(t,e=Error)=>{throw new e(t)};class ko extends Error{name="ParseError"}const d=t=>Me(t,ko),Hr=t=>` ${t}`,Ao="",O=(t,e)=>{const n={},r=Array.isArray(t);let i=!1;for(const[s,o]of Object.entries(t).entries()){const a=r?e(s,o[1]):e(...o,s);i||=typeof a[0]=="number";const l=Array.isArray(a[0])||a.length===0?a:[a];for(const[c,u]of l)typeof c=="object"?n[c.group]=N(n[c.group],u):n[c]=u}return i?Object.values(n):n},Zr=Object.entries,te=(t,e)=>t in e,mn=(t,e)=>e in t;class Io{constructor(e){Object.assign(this,e)}}const So=class{};class Yr extends So{}const No=(t,e)=>{const n={},r={};let i;for(i in t)i in e?n[i]=t[i]:r[i]=t[i];return[n,r]},Qr=(t,e)=>No(t,e)[1],Ze=t=>Object.keys(t).length===0,ft=t=>[...Object.entries(t),...Object.getOwnPropertySymbols(t).map(e=>[e,t[e]])],Oo=(t,e)=>Object.defineProperties(t,Object.getOwnPropertyDescriptors(e)),Ro=t=>{const e=Object.keys(t).sort(),n={};for(let r=0;r<e.length;r++)n[e[r]]=t[e[r]];return n},ee=Hr(`unset${Ao}`),Co=t=>Object.values(t).filter(e=>typeof e=="number"?!0:typeof t[e]!="number"),Xr={Array:Array,Boolean:Boolean,Date:Date,Error:Error,Function:Function,Map:Map,Number:Number,Promise:Promise,RegExp:RegExp,Set:Set,String:String,WeakMap:WeakMap,WeakSet:WeakSet},ei=globalThis.File??Blob,ti={ArrayBuffer:ArrayBuffer,Blob:Blob,File:ei,FormData:FormData,Headers:Headers,Request:Request,Response:Response,URL:URL},Mo={Int8Array:Int8Array,Uint8Array:Uint8Array,Uint8ClampedArray:Uint8ClampedArray,Int16Array:Int16Array,Uint16Array:Uint16Array,Int32Array:Int32Array,Uint32Array:Uint32Array,Float32Array:Float32Array,Float64Array:Float64Array,BigInt64Array:BigInt64Array,BigUint64Array:BigUint64Array},Pe={...Xr,...ti,...Mo,String:String,Number:Number,Boolean:Boolean},gn=t=>{let e=Object.getPrototypeOf(t);for(;e?.constructor&&(!te(e.constructor.name,Pe)||!(t instanceof Pe[e.constructor.name]));)e=Object.getPrototypeOf(e);const n=e?.constructor?.name;if(!(n===void 0||n==="Object"))return n},Gt=t=>typeof t=="object"&&t!==null?gn(t)??"object":Q(t),F=Array.isArray,Po={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"},qo={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"},Eo={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"},Ko={...Po,...qo,...Eo},yn=t=>{const e=Object(t).name??null;return e&&te(e,Pe)&&Pe[e]===t?e:null},Fn=(t,e)=>{let n=t.prototype;for(;n!==null;){if(n===e.prototype)return!0;n=Object.getPrototypeOf(n)}return!1},Do=t=>ni(t,new Map),ni=(t,e)=>{if(typeof t!="object"||t===null)return t;if(e?.has(t))return e.get(t);const n=yn(t.constructor);if(n==="Date")return new Date(t.getTime());if(n&&n!=="Array")return t;const r=Array.isArray(t)?t.slice():Object.create(Object.getPrototypeOf(t)),i=Object.getOwnPropertyDescriptors(t);if(e){e.set(t,r);for(const s in i){const o=i[s];"get"in o||"set"in o||(o.value=ni(o.value,e))}}return Object.defineProperties(r,i),r},Lo=t=>{let e=ee;return()=>e===ee?e=t():e},At=t=>typeof t=="function"&&t.length===0,Bo=class extends Function{constructor(...t){const e=t.slice(0,-1),n=t.at(-1);try{super(...e,n)}catch(r){return D(`Encountered an unexpected error while compiling your definition:\n Message: ${r} \n Source: (${t.slice(0,-1)}) => {\n ${t.at(-1)}\n }`)}}};class pe{constructor(e,...[n]){return Object.assign(Object.setPrototypeOf(e.bind(n?.bind??this),this.constructor.prototype),n?.attach)}}const jo=Lo(()=>{try{return new Function("return false")()}catch{return!0}});class ne{constructor(){}}const Fo=()=>{try{return(((new Error).stack?.split(`\n`)[2]?.trim()||"").match(/\(?(.+?)(?::\d+:\d+)?\)?$/)?.[1]||"unknown").replace(/^file:\/\//,"")}catch{return"unknown"}},Uo=globalThis.process?.env??{},zo={fileName:Fo,env:Uo},To=t=>t[0].toUpperCase()+t.slice(1),ri=t=>new RegExp(_o(t),typeof t=="string"?"":t.flags),_o=t=>`^(?:${typeof t=="string"?t:t.source})$`,ue={negativeLookahead:t=>`(?!${t})`,nonCapturingGroup:t=>`(?:${t})`},ze="\\",It={" ":1,"\n":1,"\t":1},Jo=/^-0\.?0*$/.source,ii=/[1-9]\d*/.source,Vo=/\.\d+/.source,Go=/\.\d*[1-9]/.source,si=t=>ri(ue.negativeLookahead(Jo)+ue.nonCapturingGroup("-?"+ue.nonCapturingGroup(ue.nonCapturingGroup("0|"+ii)+ue.nonCapturingGroup(t.decimalPattern)+"?")+(t.allowDecimalOnly?"|"+t.decimalPattern:"")+"?")),Un=si({decimalPattern:Go,allowDecimalOnly:!1}),Wo=Un.test.bind(Un),Wt=si({decimalPattern:Vo,allowDecimalOnly:!0});Wt.test.bind(Wt);const Ho=/^-?\d*\.?\d*$/,Zo=t=>t.length!==0&&Ho.test(t),mt=ri(ue.negativeLookahead("^-0$")+"-?"+ue.nonCapturingGroup(ue.nonCapturingGroup("0|"+ii))),Yo=mt.test.bind(mt),Ht=/^-?\d+$/,Qo=Ht.test.bind(Ht),oi={number:"a number",bigint:"a bigint",integer:"an integer"},ai=(t,e)=>`'${t}' was parsed as ${oi[e]} but could not be narrowed to a literal value. Avoid unnecessary leading or trailing zeros and other abnormal notation`,Xo=(t,e)=>e==="number"?Wo(t):Yo(t),ea=(t,e)=>e==="number"?Number(t):Number.parseInt(t),ta=(t,e)=>e==="number"?Zo(t):Qo(t),na=(t,e)=>bn(t,"number",e),ra=(t,e)=>bn(t,"number",{...e,strict:!0}),ia=(t,e)=>bn(t,"integer",e),bn=(t,e,n)=>{const r=ea(t,e);return!Number.isNaN(r)&&ta(t,e)?n?.strict?Xo(t,e)?r:d(ai(t,e)):r:n?.errorOnFail?d(n?.errorOnFail===!0?`Failed to parse ${oi[e]} from '${t}'`:n?.errorOnFail):void 0},sa=t=>{if(t[t.length-1]!=="n")return;const e=t.slice(0,-1);let n;try{n=BigInt(e)}catch{return}if(mt.test(e))return n;if(Ht.test(e))return d(ai(t,"bigint"))},oa="0.50.0",aa={version:oa,filename:zo.fileName(),FileConstructor:ei},Ye=aa,zn=new Map,Dt=Object.create(null),Zt=t=>{const e=zn.get(t);if(e)return e;let n=ca(t);return Dt[n]?n=`${n}${Dt[n]++}`:Dt[n]=1,Ye[n]=t,zn.set(t,n),n},Ve=t=>/^[$A-Z_a-z][\w$]*$/.test(t),ca=t=>{switch(typeof t){case"object":{if(t===null)break;const e=gn(t)??"object";return e[0].toLowerCase()+e.slice(1)}case"function":return Ve(t.name)?t.name:"fn";case"symbol":return t.description&&Ve(t.description)?t.description:"symbol"}return D(`Unexpected attempt to register serializable value of type ${Q(t)}`)},$n=t=>typeof t=="string"?JSON.stringify(t):typeof t=="bigint"?`${t}n`:`${t}`,la=(t,e={})=>Te(t,{onUndefined:"$ark.undefined",onBigInt:n=>`$ark.bigint-${n}`,...e},[]),S=(t,e)=>{switch(Q(t)){case"object":const n=t,r=n.constructor.name;return r==="Object"||r==="Array"?e?.quoteKeys===!1?gt(n,e?.indent??0,""):JSON.stringify(Te(n,qe,[]),null,e?.indent):gt(n,e?.indent??0,"");case"symbol":return qe.onSymbol(t);default:return $n(t)}},gt=(t,e,n)=>{if(typeof t=="function")return qe.onFunction(t);if(typeof t!="object"||t===null)return $n(t);const r=n+" ".repeat(e);if(Array.isArray(t)){if(t.length===0)return"[]";const s=t.map(o=>gt(o,e,r)).join(`,\n`+r);return e?`[\n${r}${s}\n${n}]`:`[${s}]`}const i=t.constructor.name;if(i==="Object"){const s=ft(t).map(([o,a])=>{const l=typeof o=="symbol"?qe.onSymbol(o):Ve(o)?o:JSON.stringify(o),c=gt(a,e,r);return`${r}${l}: ${c}`});return s.length===0?"{}":e?`{\n${s.join(`,\n`)}\n${n}}`:`{${s.join(", ")}}`}return t instanceof Date?Qe(t):"expression"in t&&typeof t.expression=="string"?t.expression:i},qe={onCycle:()=>"(cycle)",onSymbol:t=>`Symbol(${Zt(t)})`,onFunction:t=>`Function(${Zt(t)})`},Te=(t,e,n)=>{switch(Q(t)){case"object":{const r=t;if("toJSON"in r&&typeof r.toJSON=="function")return r.toJSON();if(typeof r=="function")return qe.onFunction(r);if(n.includes(r))return"(cycle)";const i=[...n,r];if(Array.isArray(r))return r.map(o=>Te(o,e,i));if(r instanceof Date)return r.toDateString();const s={};for(const o in r)s[o]=Te(r[o],e,i);for(const o of Object.getOwnPropertySymbols(r))s[e.onSymbol?.(o)??o.toString()]=Te(r[o],e,i);return s}case"symbol":return qe.onSymbol(t);case"bigint":return e.onBigInt?.(t)??`${t}n`;case"undefined":return e.onUndefined??"undefined";case"string":return t.replaceAll("\\","\\\\");default:return t}},Qe=t=>{const e=t.getFullYear(),n=t.getMonth(),r=t.getDate(),i=t.getHours(),s=t.getMinutes(),o=t.getSeconds(),a=t.getMilliseconds();if(n===0&&r===1&&i===0&&s===0&&o===0&&a===0)return`${e}`;const l=`${ua[n]} ${r}, ${e}`;if(i===0&&s===0&&o===0&&a===0)return l;let c=t.toLocaleTimeString();const u=c.endsWith(" AM")||c.endsWith(" PM")?c.slice(-3):"";return u&&(c=c.slice(0,-u.length)),a?c+=`.${ha(a,3)}`:da.test(c)&&(c=c.slice(0,-3)),`${c+u}, ${l}`},ua=["January","February","March","April","May","June","July","August","September","October","November","December"],da=/:\d\d:00$/,ha=(t,e)=>String(t).padStart(e,"0"),ci=(t,e,...[n])=>{const r=n?.stringifySymbol??S;let i=t;switch(typeof e){case"string":i=Ve(e)?t===""?e:`${t}.${e}`:`${t}[${JSON.stringify(e)}]`;break;case"number":i=`${t}[${e}]`;break;case"symbol":i=`${t}[${r(e)}]`;break;default:n?.stringifyNonKey?i=`${t}[${n.stringifyNonKey(e)}]`:d(`${S(e)} must be a PropertyKey or stringifyNonKey must be passed to options`)}return i},Xe=(t,...e)=>t.reduce((n,r)=>ci(n,r,...e),"");class li extends Wr{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"?S(this[e]):this[e]);return this.cache.json}stringify(){return this.cache.stringify?this.cache.stringify:this.cache.stringify=Xe(this)}stringifyAncestors(){if(this.cache.stringifyAncestors)return this.cache.stringifyAncestors;let e="";const n=[e];for(const r of this)e=ci(e,r),n.push(e);return this.cache.stringifyAncestors=n}}class ui{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 n="";for(;this.lookahead&&!e(this,n);)n+=this.shift();return n}shiftUntilEscapable(e){let n="";for(;this.lookahead;)if(this.lookahead===ze)this.shift(),e(this,n)?n+=this.shift():this.lookahead===ze?n+=this.shift():n+=`${ze}${this.shift()}`;else{if(e(this,n))break;n+=this.shift()}return n}shiftUntilLookahead(e){return typeof e=="string"?this.shiftUntil(n=>n.lookahead===e):this.shiftUntil(n=>n.lookahead in e)}shiftUntilNonWhitespace(){return this.shiftUntil(()=>!(this.lookahead in It))}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,n){return this.chars.slice(e,n).join("")}lookaheadIs(e){return this.lookahead===e}lookaheadIsIn(e){return this.lookahead in e}}const pa=(t,e)=>`Unmatched ${t}${e===""?"":` before ${e}`}`,di=t=>`Missing ${t}`;let Yt="$ark",fa=2;for(;Yt in globalThis;)Yt=`$ark${fa++}`;const hi=Yt;globalThis[hi]=Ye;const p=Ye,ma=t=>`${hi}.${t}`,z=t=>ma(Zt(t));class pi extends Yr{argNames;body="";constructor(...e){super(),this.argNames=e;for(const n of e){if(n in this)throw new Error(`Arg name '${n}' would overwrite an existing property on FunctionBody`);this[n]=n}}indentation=0;indent(){return this.indentation+=4,this}dedent(){return this.indentation-=4,this}prop(e,n=!1){return fi(e,n)}index(e,n=!1){return mi(`${e}`,n)}line(e){return this.body+=`${" ".repeat(this.indentation)}${e}\n`,this}const(e,n){return this.line(`const ${e} = ${n}`),this}let(e,n){return this.line(`let ${e} = ${n}`)}set(e,n){return this.line(`${e} = ${n}`)}if(e,n){return this.block(`if (${e})`,n)}elseIf(e,n){return this.block(`else if (${e})`,n)}else(e){return this.block("else",e)}for(e,n,r=0){return this.block(`for (let i = ${r}; ${e}; i++)`,n)}forIn(e,n){return this.block(`for (const k in ${e})`,n)}block(e,n,r=""){return this.line(`${e} {`),this.indent(),n(this),this.dedent(),this.line(`}${r}`)}return(e=""){return this.line(`return ${e}`)}write(e="anonymous",n=0){return`${e}(${this.argNames.join(", ")}) { ${n?this.body.split(`\n`).map(r=>" ".repeat(n)+`${r}`).join(`\n`):this.body} }`}compile(){return new Bo(...this.argNames,this.body)}}const et=t=>$e(t,"object")||typeof t=="symbol"?z(t):$n(t),fi=(t,e=!1)=>typeof t=="string"&&Ve(t)?`${e?"?":""}.${t}`:mi(ga(t),e),ga=t=>typeof t=="symbol"?z(t):JSON.stringify(t),mi=(t,e=!1)=>`${e?"?.":""}[${t}]`;class Lt extends pi{traversalKind;optimistic;constructor(e){super("data","ctx"),this.traversalKind=e.kind,this.optimistic=e.optimistic===!0}invoke(e,n){const r=n?.arg??this.data,i=typeof e=="string"?!0:this.requiresContextFor(e),s=typeof e=="string"?e:e.id;return i?`${this.referenceToId(s,n)}(${r}, ${this.ctx})`:`${this.referenceToId(s,n)}(${r})`}referenceToId(e,n){const r=n?.kind??this.traversalKind,i=`this.${e}${r}`;return n?.bind?`${i}.bind(${n?.bind})`:i}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,n,r){const i=this.requiresContextFor(r);return i&&this.line(`${this.ctx}.path.push(${e})`),this.check(r,{arg:n}),i&&this.line(`${this.ctx}.path.pop()`),this}check(e,n){return this.traversalKind==="Allows"?this.if(`!${this.invoke(e,n)}`,()=>this.return(!1)):this.line(this.invoke(e,n))}}const gi=t=>O(t,(e,n)=>[e,F(n)?[...n]:n]),ie=Hr("arkKind"),b=(t,e)=>t?.[ie]===e,U=t=>b(t,"root")||b(t,"constraint"),ya=["unit","proto","domain"],St=["required","optional","index","sequence"],yi=["pattern","divisor","exactLength","max","min","maxLength","minLength","before","after"],bi=[...yi,"structure","predicate"],wn=[...bi,...St],Nt=["alias","union","morph","unit","intersection","proto","domain"],ba=[...Nt,...wn],$i=O(wn,(t,e)=>[e,1]),$a=O([...St,"undeclared"],(t,e)=>[e,1]),wi=O(ba,(t,e)=>[e,t]),ut=t=>typeof t=="string"&&t in wi,yt=t=>wi[t],vn=t=>Nt.slice(yt(t)+1);[...vn("union")];[...vn("morph")];const be=t=>typeof t=="string"||typeof t=="boolean"||t===null?t:typeof t=="number"?Number.isNaN(t)?"NaN":t===Number.POSITIVE_INFINITY?"Infinity":t===Number.NEGATIVE_INFINITY?"-Infinity":t:et(t),Ot=t=>{let e="{ ";for(const[n,r]of Object.entries(t))e+=`${n}: ${et(r)}, `;return e+" }"},q=t=>{const e=t;return e.hasAssociatedError&&(e.defaults.expected??=n=>"description"in n?n.description:e.defaults.description(n),e.defaults.actual??=n=>S(n),e.defaults.problem??=n=>`must be ${n.expected}${n.actual?` (was ${n.actual})`:""}`,e.defaults.message??=n=>{if(n.path.length===0)return n.problem;const r=`${n.propString} ${n.problem}`;return r[0]==="["?`value at ${r}`:r}),e};class wa extends Error{name="ToJsonSchemaError";code;context;constructor(e,n){super(S(n,{quoteKeys:!1,indent:4})),this.code=e,this.context=n}hasCode(e){return this.code===e}}const va={dialect:"https://json-schema.org/draft/2020-12/schema",useRefs:!1,fallback:{arrayObject:t=>L.throw("arrayObject",t),arrayPostfix:t=>L.throw("arrayPostfix",t),defaultValue:t=>L.throw("defaultValue",t),domain:t=>L.throw("domain",t),morph:t=>L.throw("morph",t),patternIntersection:t=>L.throw("patternIntersection",t),predicate:t=>L.throw("predicate",t),proto:t=>L.throw("proto",t),symbolKey:t=>L.throw("symbolKey",t),unit:t=>L.throw("unit",t),date:t=>L.throw("date",t)}},L={Error:wa,throw:(...t)=>{throw new L.Error(...t)},throwInternalOperandError:(t,e)=>D(`Unexpected JSON Schema input for ${t}: ${S(e)}`),defaultConfig:va};p.config??={};const Qt=(t,e)=>{if(!e)return t;const n={...t};let r;for(r in e){const i={...t.keywords};if(r==="keywords"){for(const s in e[r]){const o=e.keywords[s];o!==void 0&&(i[s]=typeof o=="string"?{description:o}:o)}n.keywords=i}else r==="toJsonSchema"?n[r]=vi(t.toJsonSchema,e.toJsonSchema):ut(r)?n[r]={...t[r],...e[r]}:n[r]=e[r]}return n},vi=(t,e)=>{if(!t)return e??{};if(!e)return t;const n={...t};let r;for(r in e)r==="fallback"?n.fallback=xa(t.fallback,e.fallback):n[r]=e[r];return n},xa=(t,e)=>{t=Tn(t),e=Tn(e);const n={};let r;for(r in L.defaultConfig.fallback)n[r]=e[r]??e.default??t[r]??t.default??L.defaultConfig.fallback[r];return n},Tn=t=>typeof t=="function"?{default:t}:t??{};class Ee extends Yr{[ie]="error";path;data;nodeConfig;input;ctx;constructor({prefixPath:e,relativePath:n,...r},i){super(),this.input=r,this.ctx=i,Oo(this,r);const s=i.data;r.code==="union"&&(r.errors=r.errors.flatMap(a=>{const l=a.hasCode("union")?a.errors:[a];return!e&&!n?l:l.map(c=>c.transform(u=>({...u,path:$o(e,u.path,n)})))})),this.nodeConfig=i.config[this.code];const o=[...r.path??i.path];n&&o.push(...n),e&&o.unshift(...e),this.path=new li(...o),this.data="data"in r?r.data:s}transform(e){return new Ee(e({data:this.data,path:this.path,...this.input}),this.ctx)}hasCode(e){return this.code===e}get propString(){return Xe(this.path)}get expected(){if(this.input.expected)return this.input.expected;const 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;const 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;const e=this.meta?.problem??this.nodeConfig.problem;return typeof e=="function"?e(this):e}get message(){if(this.input.message)return this.input.message;const 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}}class he extends Wr{[ie]="errors";ctx;constructor(e){super(),this.ctx=e}byPath=Object.create(null);get flatByPath(){return O(this.byPath,(e,n)=>[e,n.flat])}get flatProblemsByPath(){return O(this.byPath,(e,n)=>[e,n.flat.map(r=>r.problem)])}byAncestorPath=Object.create(null);count=0;mutable=this;throw(){throw this.toTraversalError()}toTraversalError(){return new ka(this)}add(e){const n=this.byPath[e.propString];if(n){if(e===n||n.hasCode("union")&&n.errors.length===0)return;const r=e.hasCode("union")&&e.errors.length===0?e:new Ee({code:"intersection",errors:n.hasCode("intersection")?[...n.errors,e]:[n,e]},this.ctx),i=this.indexOf(n);this.mutable[i===-1?this.length:i]=r,this.byPath[e.propString]=r,this.addAncestorPaths(e)}else this.byPath[e.propString]=e,this.addAncestorPaths(e),this.mutable.push(e);this.count++}transform(e){const n=new he(this.ctx);for(const r of this)n.add(e(r));return n}merge(e){for(const n of e)this.add(new Ee({...n,path:[...this.ctx.path,...n.path]},this.ctx))}affectsPath(e){return this.length===0?!1:e.stringifyAncestors().some(n=>n 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(`\n`)}addAncestorPaths(e){for(const n of e.path.stringifyAncestors())this.byAncestorPath[n]=N(this.byAncestorPath[n],e)}}class ka extends Error{name="TraversalError";constructor(e){e.length===1?super(e.summary):super(`\n`+e.map(n=>` • ${Aa(n)}`).join(`\n`)),Object.defineProperty(this,"arkErrors",{value:e,enumerable:!1})}}const Aa=t=>t.toString().split(`\n`).join(`\n `);class Ne{path=[];errors=new he(this);root;config;queuedMorphs=[];branches=[];seen={};constructor(e,n){this.root=e,this.config=n}get data(){let e=this.root;for(const n of this.path)e=e?.[n];return e}get propString(){return Xe(this.path)}reject(e){return this.error(e),!1}mustBe(e){return this.error(e),!1}error(e){const n=typeof e=="object"?e.code?e:{...e,code:"predicate"}:{code:"predicate",expected:e};return this.errorFromContext(n)}hasError(){return this.currentErrorCount!==0}get currentBranch(){return this.branches.at(-1)}queueMorphs(e){const n={path:new li(...this.path),morphs:e};this.currentBranch?this.currentBranch.queuedMorphs.push(n):this.queuedMorphs.push(n)}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){const n=new Ee(e,this);return this.currentBranch?this.currentBranch.error=n:this.errors.add(n),n}applyQueuedMorphs(){for(;this.queuedMorphs.length;){const e=this.queuedMorphs;this.queuedMorphs=[];for(const{path:n,morphs:r}of e)this.errors.affectsPath(n)||this.applyMorphsAtPath(n,r)}}applyMorphsAtPath(e,n){const r=e.at(-1);let i;if(r!==void 0){i=this.root;for(let s=0;s<e.length-1;s++)i=i[e[s]]}for(const s of n){this.path=[...e];const o=U(s),a=s(i===void 0?this.root:i[r],this);if(a instanceof Ee){this.errors.add(a);break}if(a instanceof he){o||this.errors.merge(a),this.queuedMorphs=[];break}i===void 0?this.root=a:i[r]=a,this.applyQueuedMorphs()}}}const se=(t,e,n)=>{if(!n)return e();n.path.push(t);const r=e();return n.path.pop(),r};class xi extends pe{attachments;$;onFail;includesTransform;includesContextualPredicate;isCyclic;allowsRequiresContext;rootApplyStrategy;contextFreeMorph;rootApply;referencesById;shallowReferences;flatRefs;flatMorphs;allows;get shallowMorphs(){return[]}constructor(e,n){super((i,s,o=this.onFail)=>s?(this.traverseApply(i,s),s.hasError()?s.errors:s.data):this.rootApply(i,o),{attach:e}),this.attachments=e,this.$=n,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((i,s)=>Oa(i,s.shallowReferences),[this]);const r=this.isStructural();this.flatRefs=[],this.flatMorphs=[];for(let i=0;i<this.children.length;i++){if(this.includesTransform||=this.children[i].includesTransform,this.includesContextualPredicate||=this.children[i].includesContextualPredicate,this.isCyclic||=this.children[i].isCyclic,!r){const s=this.children[i].flatRefs;for(let o=0;o<s.length;o++){const a=s[o];if(!this.flatRefs.some(l=>ki(l,a))){this.flatRefs.push(a);for(const l of a.node.branches)(l.hasKind("morph")||l.hasKind("intersection")&&l.structure?.structuralMorph!==void 0)&&this.flatMorphs.push({path:a.path,propString:a.propString,node:l})}}}Object.assign(this.referencesById,this.children[i].referencesById)}this.flatRefs.sort((i,s)=>i.path.length>s.path.length?1:i.path.length<s.path.length?-1:i.propString>s.propString?1:i.propString<s.propString||i.node.expression<s.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(i=>i.length===1||i.name==="$arkStructuralMorph")?this.hasKind("union")?this.branches.some(i=>i.shallowMorphs.length>1)?"contextual":"branchedOptimistic":this.shallowMorphs.length>1?"contextual":"optimistic":"contextual":"contextual",this.rootApply=this.createRootApply(),this.allows=this.allowsRequiresContext?i=>this.traverseAllows(i,new Ne(i,this.$.resolvedConfig)):i=>this.traverseAllows(i)}createRootApply(){switch(this.rootApplyStrategy){case"allows":return(n,r)=>{if(this.allows(n))return n;const i=new Ne(n,this.$.resolvedConfig);return this.traverseApply(n,i),i.finalize(r)};case"contextual":return(n,r)=>{const i=new Ne(n,this.$.resolvedConfig);return this.traverseApply(n,i),i.finalize(r)};case"optimistic":this.contextFreeMorph=this.shallowMorphs[0];const e=this.$.resolvedConfig.clone;return(n,r)=>{if(this.allows(n))return this.contextFreeMorph(e&&(typeof n=="object"&&n!==null||typeof n=="function")?e(n):n);const i=new Ne(n,this.$.resolvedConfig);return this.traverseApply(n,i),i.finalize(r)};case"branchedOptimistic":return this.createBranchedOptimisticRootApply();default:return this.rootApplyStrategy,D(`Unexpected rootApplyStrategy ${this.rootApplyStrategy}`)}}compiledMeta=Na(this.metaJson);cacheGetter(e,n){return Object.defineProperty(this,e,{value:n}),n}get description(){return this.cacheGetter("description",this.meta?.description??this.$.resolvedConfig[this.kind].description(this))}get references(){return Object.values(this.referencesById)}precedence=yt(this.kind);precompilation;assert=(e,n)=>this(e,n,r=>r.throw());traverse(e,n){return this(e,n,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;const n={};for(const[r,i]of this.innerEntries){const s=this.impl.keys[r];if(s.reduceIo)s.reduceIo(e,n,i);else if(s.child){const o=i;n[r]=F(o)?o.map(a=>e==="in"?a.rawIn:a.rawOut):e==="in"?o.rawIn:o.rawOut}else n[r]=i}return this.$.node(this.kind,n)}toJSON(){return this.json}toString(){return`Type<${this.expression}>`}equals(e){const n=U(e)?e:this.$.parseDefinition(e);return this.innerHash===n.innerHash}ifEquals(e){return this.equals(e)?this:void 0}hasKind(e){return this.kind===e}assertHasKind(e){return this.kind!==e&&Me(`${this.kind} node was not of asserted kind ${e}`),this}hasKindIn(...e){return e.includes(this.kind)}assertHasKindIn(...e){return le(e,this.kind)||Me(`${this.kind} node was not one of asserted kinds ${e}`),this}isBasis(){return le(ya,this.kind)}isConstraint(){return le(wn,this.kind)}isStructural(){return le(St,this.kind)}isRefinement(){return le(bi,this.kind)}isRoot(){return le(Nt,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){const n=je.normalize(e);return this._select(n)}_select(e){let n=je.applyBoundary[e.boundary??"references"](this);return e.kind&&(n=n.filter(r=>r.kind===e.kind)),e.where&&(n=n.filter(e.where)),je.applyMethod[e.method??"filter"](n,this,e)}transform(e,n){return this._transform(e,this._createTransformContext(n))}_createTransformContext(e){return{root:this,selected:void 0,seen:{},path:[],parseOptions:{prereduced:e?.prereduced??!1},undeclaredKeyHandling:void 0,...e}}_transform(e,n){const r=n.bindScope??this.$;if(n.seen[this.id])return this.$.lazilyResolve(n.seen[this.id]);if(n.shouldTransform?.(this,n)===!1)return this;let i;n.seen[this.id]=()=>i,this.hasKind("structure")&&this.undeclared!==n.undeclaredKeyHandling&&(n={...n,undeclaredKeyHandling:this.undeclared});const s=O(this.inner,(u,h)=>{if(!this.impl.keys[u].child)return[u,h];const m=h;if(!F(m)){const x=m._transform(e,n);return x?[u,x]:[]}if(m.length===0)return[u,h];const y=m.flatMap(x=>x._transform(e,n)??[]);return y.length?[u,y]:[]});delete n.seen[this.id];const o=Object.assign(s,{meta:this.meta}),a=n.selected&&!n.selected.includes(this)?o:e(this.kind,o,n);if(a===null)return null;if(U(a))return i=a;const l=Object.keys(a);return(l.length===0||l.length===1&&l[0]==="meta")&&!Ze(this.inner)?null:(this.kind==="required"||this.kind==="optional"||this.kind==="index")&&!("value"in a)?n.undeclaredKeyHandling?{...a,value:p.intrinsic.unknown}:null:(this.kind==="morph"&&(a.in??=p.intrinsic.unknown),i=r.node(this.kind,a,n.parseOptions))}configureReferences(e,n="references"){const r=je.normalize(n),i=typeof e=="string"?(l,c)=>({...c,meta:{...c.meta,description:e}}):typeof e=="function"?(l,c)=>({...c,meta:e(c.meta)}):(l,c)=>({...c,meta:{...c.meta,...e}});if(r.boundary==="self")return this.$.node(this.kind,i(this.kind,{...this.inner,meta:this.meta}));const s=this._select(r),o=s&&He(s),a=r.boundary==="child"?(l,c)=>c.root.children.includes(l):r.boundary==="shallow"?l=>l.kind!=="structure":()=>!0;return this.$.finalize(this.transform(i,{shouldTransform:a,selected:o}))}}const je={applyBoundary:{self:t=>[t],child:t=>[...t.children],shallow:t=>[...t.shallowReferences],references:t=>[...t.references]},applyMethod:{filter:t=>t,assertFilter:(t,e,n)=>(t.length===0&&Me(_n(e,n)),t),find:t=>t[0],assertFind:(t,e,n)=>(t.length===0&&Me(_n(e,n)),t[0])},normalize:t=>typeof t=="function"?{boundary:"references",method:"filter",where:t}:typeof t=="string"?te(t,je.applyBoundary)?{method:"filter",boundary:t}:{boundary:"references",method:"filter",kind:t}:{boundary:"references",method:"filter",...t}},_n=(t,e)=>`${t} had no references matching ${S(e)}.`,Ia=t=>Xe(t,{stringifyNonKey:e=>e.expression}),Sa=/"(\$ark\.[^"]+)"/g,Na=t=>JSON.stringify(t).replaceAll(Sa,"$1"),de=(t,e)=>({path:t,node:e,propString:Ia(t)}),ki=(t,e)=>t.propString===e.propString&&t.node.equals(e.node),Jn=(t,e)=>ye(t,e,{isEqual:ki}),Oa=(t,e)=>ye(t,e,{isEqual:(n,r)=>n.equals(r)});class g extends Array{static init(e,n,r,i){return new g({kind:e,l:n,r:r,path:i?.path??[],optional:i?.optional??!1})}add(e,n,r,i){return this.push({kind:e,l:n,r:r,path:i?.path??[],optional:i?.optional??!1}),this}get summary(){return this.describeReasons()}describeReasons(){if(this.length===1){const{path:e,l:n,r:r}=this[0],i=Xe(e);return Ai(`Intersection${i&&` at ${i}`} of ${Vn(n,r)}`)}return`The following intersections result in unsatisfiable types:\n• ${this.map(({path:e,l:n,r:r})=>`${e}: ${Vn(n,r)}`).join(`\n• `)}`}throw(){return d(this.describeReasons())}invert(){const e=this.map(n=>({...n,l:n.r,r:n.l}));return e instanceof g?e:new g(...e)}withPrefixKey(e,n){return this.map(r=>({...r,path:[e,...r.path],optional:r.optional||n==="optional"}))}toNeverIfDisjoint(){return p.intrinsic.never}}const Vn=(t,e)=>`${Xt(t)} and ${Xt(e)}`,Xt=t=>U(t)?t.expression:F(t)?t.map(Xt).join(" | ")||"never":String(t),Ai=t=>`${t} results in an unsatisfiable type`,Ae={},oe=(t,e,n)=>j(t,e,{$:n,invert:!1,pipe:!1}),en=(t,e,n)=>j(t,e,{$:n,invert:!1,pipe:!0}),j=(t,e,n)=>{const r=n.pipe?"|>":"&",i=`${t.hash}${r}${e.hash}`;if(Ae[i]!==void 0)return Ae[i];if(!n.pipe){const a=`${e.hash}${r}${t.hash}`;if(Ae[a]!==void 0){const l=Ae[a],c=l instanceof g?l.invert():l;return Ae[i]=c,c}}const s=!n.pipe||!t.includesTransform&&!e.includesTransform;if(s&&t.equals(e))return t;let o=s?tn(t,e,n):t.hasKindIn(...Nt)?Ra(t,e,n):tn(t,e,n);return U(o)&&(t.equals(o)?o=t:e.equals(o)&&(o=e)),Ae[i]=o,o},tn=(t,e,n)=>{const r=t.precedence<e.precedence?t.kind:e.kind,i=t.impl.intersections[e.kind]??e.impl.intersections[t.kind];if(i===void 0)return null;if(r===t.kind)return i(t,e,n);{let s=i(e,t,{...n,invert:!n.invert});return s instanceof g&&(s=s.invert()),s}},Ra=(t,e,n)=>t.includesTransform||e.includesTransform?n.invert?Gn(e,t,n):Gn(t,e,n):tn(t,e,n),Gn=(t,e,n)=>t.distribute(r=>Ca(r,e,n),r=>{const i=r.filter(U);if(i.length===0)return g.init("union",t.branches,e.branches);if(i.length<t.branches.length||!t.branches.every((o,a)=>o.rawIn.equals(i[a].rawIn)))return n.$.parseSchema(i);if(i.length===1)return i[0];const s={branches:i};return n.$.parseSchema(s)}),Ca=(t,e,n)=>{if(t.hasKind("morph")){const i=[...t.morphs];if(t.lastMorphIfNode){const s=j(t.lastMorphIfNode,e,n);if(s instanceof g)return s;i[i.length-1]=s}else i.push(e);return n.$.node("morph",{morphs:i,in:t.inner.in})}if(e.hasKind("morph")){const i=j(t,e.rawIn,n);return i instanceof g?i:n.$.node("morph",{morphs:[e],in:i})}return n.$.node("morph",{morphs:[e],in:t})};class Ke extends xi{constructor(e,n){super(e,n),Object.defineProperty(this,ie,{value:"constraint",enumerable:!1})}impliedSiblings;intersect(e){return oe(this,e,this.$)}}class Rt extends Ke{traverseApply=(e,n)=>{this.traverseAllows(e,n)||n.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 Ot(this.errorContext)}}const T=t=>(e,n)=>{if(F(e)){if(e.length===0)return;const i=e.map(s=>n.$.node(t,s));return t==="predicate"?i:i.sort((s,o)=>s.hash<o.hash?-1:1)}const r=n.$.node(t,e);return r.hasOpenIntersection()?[r]:r},bt=t=>{const e=t.r.shift();if(!e){let r=t.l.length===0&&t.kind==="structure"?p.intrinsic.unknown.internal:t.ctx.$.node(t.kind,Object.assign(t.baseInner,Ma(t.l)),{prereduced:!0});for(const i of t.roots){if(r instanceof g)return r;r=j(i,r,t.ctx)}return r}let n=!1;for(let r=0;r<t.l.length;r++){const i=j(t.l[r],e,t.ctx);if(i!==null){if(i instanceof g)return i;if(i.isRoot())return t.roots.push(i),t.l.splice(r),bt(t);if(!n)t.l[r]=i,n=!0;else if(!t.l.includes(i))return D(`Unexpectedly encountered multiple distinct intersection results for refinement ${e}`)}}if(n||t.l.push(e),t.kind==="intersection"&&e.impliedSiblings)for(const r of e.impliedSiblings)ye(t.r,r);return bt(t)},$t=t=>Object.entries(t).flatMap(([n,r])=>n in $i?r:[]).sort((n,r)=>n.precedence<r.precedence?-1:n.precedence>r.precedence?1:n.kind==="predicate"&&r.kind==="predicate"?0:n.hash<r.hash?-1:1),Ma=t=>{const e={};for(const n of t)if(n.hasOpenIntersection())e[n.kind]=N(e[n.kind],n);else{if(e[n.kind])return D(`Unexpected intersection of closed refinements of kind ${n.kind}`);e[n.kind]=n}return e},Pa=(...t)=>d(qa(...t)),qa=(t,e,n)=>{const r=n.hasKind("morph")?"a morph":n.isUnknown()?"unknown":n.exclude(e).defaultShortDescription;return`${To(t)} operand must be ${e.description} (was ${r})`},Ea=(t,e,n)=>new wt(t,e,n,n,null);class Ii extends pe{}class wt extends pe{[ie]="generic";paramDefs;bodyDef;$;arg$;baseInstantiation;hkt;description;constructor(e,n,r,i,s){super((...o)=>{const a=O(this.names,(l,c)=>{const u=this.arg$.parse(o[l]);return u.extends(this.constraints[l])||d(Ka(c,this.constraints[l].expression,u.expression)),[c,u]});if(this.defIsLazy()){const l=this.bodyDef(a);return this.$.parse(l)}return this.$.parse(n,{args:a})}),this.paramDefs=e,this.bodyDef=n,this.$=r,this.arg$=i,this.hkt=s,this.description=s?(new s).description??`a generic type for ${s.constructor.name}`:"a generic type",this.baseInstantiation=this(...this.constraints)}defIsLazy(){return this.bodyDef instanceof Ii}cacheGetter(e,n){return Object.defineProperty(this,e,{value:n}),n}get json(){return this.cacheGetter("json",{params:this.params.map(e=>e[1].isUnknown()?e[0]:[e[0],e[1].json]),body:la(this.bodyDef)})}get params(){return this.cacheGetter("params",this.paramDefs.map(e=>typeof e=="string"?[e,p.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 Ka=(t,e,n)=>`${t} must be assignable to ${e} (was ${n})`,Da=q({kind:"predicate",hasAssociatedError:!0,collapsibleKey:"predicate",keys:{predicate:{}},normalize:t=>typeof t=="function"?{predicate:t}:t,defaults:{description:t=>`valid according to ${t.predicate.name||"an anonymous predicate"}`},intersectionIsOpen:!0,intersections:{predicate:()=>null}});class La extends Ke{serializedPredicate=z(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=Ot(this.errorContext);traverseApply=(e,n)=>{!this.predicate(e,n.external)&&!n.hasError()&&n.errorFromNodeContext(this.errorContext)};compile(e){if(e.traversalKind==="Allows"){e.return(this.compiledCondition);return}e.if(`${this.compiledNegation} && !ctx.hasError()`,()=>e.line(`ctx.errorFromNodeContext(${this.compiledErrorContext})`))}reduceJsonSchema(e,n){return n.fallback.predicate({code:"predicate",base:e,predicate:this.predicate})}}const Si={implementation:Da,Node:La},Ba=q({kind:"divisor",collapsibleKey:"rule",keys:{rule:{parse:t=>Number.isInteger(t)?t:d(Fa(t))}},normalize:t=>typeof t=="number"?{rule:t}:t,hasAssociatedError:!0,defaults:{description:t=>t.rule===1?"an integer":t.rule===2?"even":`a multiple of ${t.rule}`},intersections:{divisor:(t,e,n)=>n.$.node("divisor",{rule:Math.abs(t.rule*e.rule/Ua(t.rule,e.rule))})},obviatesBasisDescription:!0});class ja extends Rt{traverseAllows=e=>e%this.rule===0;compiledCondition=`data % ${this.rule} === 0`;compiledNegation=`data % ${this.rule} !== 0`;impliedBasis=p.intrinsic.number.internal;expression=`% ${this.rule}`;reduceJsonSchema(e){return e.type="integer",this.rule===1||(e.multipleOf=this.rule),e}}const Ni={implementation:Ba,Node:ja},Fa=t=>`divisor must be an integer (was ${t})`,Ua=(t,e)=>{let n,r=t,i=e;for(;i!==0;)n=i,i=r%i,r=n;return r};class De extends Rt{boundOperandKind=Ja[this.kind];compiledActual=this.boundOperandKind==="value"?"data":this.boundOperandKind==="length"?"data.length":"data.valueOf()";comparator=Va(this.kind,this.exclusive);numericLimit=this.rule.valueOf();expression=`${this.comparator} ${this.rule}`;compiledCondition=`${this.compiledActual} ${this.comparator} ${this.numericLimit}`;compiledNegation=`${this.compiledActual} ${za[this.comparator]} ${this.numericLimit}`;stringLimit=this.boundOperandKind==="date"?Ga(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 za={"<":">=","<=":">",">":"<=",">=":"<"},Ta={min:"max",minLength:"maxLength",after:"before"},Oi={parse:t=>t||void 0},Ri=t=>e=>{if(typeof e=="number")return{rule:e};const{exclusive:n,...r}=e;return n?{...r,rule:t==="minLength"?r.rule+1:r.rule-1}:r},Ci=t=>e=>{if(typeof e=="number"||typeof e=="string"||e instanceof Date)return{rule:e};const{exclusive:n,...r}=e;if(!n)return r;const i=typeof r.rule=="number"?r.rule:typeof r.rule=="string"?new Date(r.rule).valueOf():r.rule.valueOf();return n?{...r,rule:t==="after"?i+1:i-1}:r},Mi=t=>typeof t=="string"||typeof t=="number"?new Date(t):t,_a=(t,e)=>`${t} bound must be a positive integer (was ${e})`,xn=t=>e=>((!Number.isInteger(e)||e<0)&&d(_a(t,e)),e),Ja={min:"value",max:"value",minLength:"length",maxLength:"length",after:"date",before:"date"},Va=(t,e)=>`${te(t,Ta)?">":"<"}${e?"":"="}`,Ga=t=>typeof t=="string"?t:new Date(t).toLocaleString(),Wa=t=>`Bounded expression ${t} must be exactly one of number, string, Array, or Date`,Ha=q({kind:"after",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{parse:Mi,serialize:t=>t.toISOString()}},normalize:Ci("after"),defaults:{description:t=>`${t.collapsibleLimitString} or later`,actual:Qe},intersections:{after:(t,e)=>t.isStricterThan(e)?t:e}});class Za extends De{impliedBasis=p.intrinsic.Date.internal;collapsibleLimitString=Qe(this.rule);traverseAllows=e=>e>=this.rule;reduceJsonSchema(e,n){return n.fallback.date({code:"date",base:e,after:this.rule})}}const Pi={implementation:Ha,Node:Za},Ya=q({kind:"before",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{parse:Mi,serialize:t=>t.toISOString()}},normalize:Ci("before"),defaults:{description:t=>`${t.collapsibleLimitString} or earlier`,actual:Qe},intersections:{before:(t,e)=>t.isStricterThan(e)?t:e,after:(t,e,n)=>t.overlapsRange(e)?t.overlapIsUnit(e)?n.$.node("unit",{unit:t.rule}):null:g.init("range",t,e)}});class Qa extends De{collapsibleLimitString=Qe(this.rule);traverseAllows=e=>e<=this.rule;impliedBasis=p.intrinsic.Date.internal;reduceJsonSchema(e,n){return n.fallback.date({code:"date",base:e,before:this.rule})}}const qi={implementation:Ya,Node:Qa},Xa=q({kind:"exactLength",collapsibleKey:"rule",keys:{rule:{parse:xn("exactLength")}},normalize:t=>typeof t=="number"?{rule:t}:t,hasAssociatedError:!0,defaults:{description:t=>`exactly length ${t.rule}`,actual:t=>`${t.length}`},intersections:{exactLength:(t,e,n)=>g.init("unit",n.$.node("unit",{unit:t.rule}),n.$.node("unit",{unit:e.rule}),{path:["length"]}),minLength:(t,e)=>t.rule>=e.rule?t:g.init("range",t,e),maxLength:(t,e)=>t.rule<=e.rule?t:g.init("range",t,e)}});class ec extends Rt{traverseAllows=e=>e.length===this.rule;compiledCondition=`data.length === ${this.rule}`;compiledNegation=`data.length !== ${this.rule}`;impliedBasis=p.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 L.throwInternalOperandError("exactLength",e)}}}const Ei={implementation:Xa,Node:ec},tc=q({kind:"max",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{},exclusive:Oi},normalize:t=>typeof t=="number"?{rule:t}:t,defaults:{description:t=>t.rule===0?t.exclusive?"negative":"non-positive":`${t.exclusive?"less than":"at most"} ${t.rule}`},intersections:{max:(t,e)=>t.isStricterThan(e)?t:e,min:(t,e,n)=>t.overlapsRange(e)?t.overlapIsUnit(e)?n.$.node("unit",{unit:t.rule}):null:g.init("range",t,e)},obviatesBasisDescription:!0});class nc extends De{impliedBasis=p.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}}const Ki={implementation:tc,Node:nc},rc=q({kind:"maxLength",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{parse:xn("maxLength")}},reduce:(t,e)=>t.rule===0?e.node("exactLength",t):void 0,normalize:Ri("maxLength"),defaults:{description:t=>`at most length ${t.rule}`,actual:t=>`${t.length}`},intersections:{maxLength:(t,e)=>t.isStricterThan(e)?t:e,minLength:(t,e,n)=>t.overlapsRange(e)?t.overlapIsUnit(e)?n.$.node("exactLength",{rule:t.rule}):null:g.init("range",t,e)}});class ic extends De{impliedBasis=p.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 L.throwInternalOperandError("maxLength",e)}}}const Di={implementation:rc,Node:ic},sc=q({kind:"min",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{},exclusive:Oi},normalize:t=>typeof t=="number"?{rule:t}:t,defaults:{description:t=>t.rule===0?t.exclusive?"positive":"non-negative":`${t.exclusive?"more than":"at least"} ${t.rule}`},intersections:{min:(t,e)=>t.isStricterThan(e)?t:e},obviatesBasisDescription:!0});class oc extends De{impliedBasis=p.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}}const Li={implementation:sc,Node:oc},ac=q({kind:"minLength",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{parse:xn("minLength")}},reduce:t=>t.rule===0?p.intrinsic.unknown:void 0,normalize:Ri("minLength"),defaults:{description:t=>t.rule===1?"non-empty":`at least length ${t.rule}`,actual:t=>t.length===0?"":`${t.length}`},intersections:{minLength:(t,e)=>t.isStricterThan(e)?t:e}});class cc extends De{impliedBasis=p.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 L.throwInternalOperandError("minLength",e)}}}const Bi={implementation:ac,Node:cc},lc={min:Li.implementation,max:Ki.implementation,minLength:Bi.implementation,maxLength:Di.implementation,exactLength:Ei.implementation,after:Pi.implementation,before:qi.implementation},uc={min:Li.Node,max:Ki.Node,minLength:Bi.Node,maxLength:Di.Node,exactLength:Ei.Node,after:Pi.Node,before:qi.Node},dc=q({kind:"pattern",collapsibleKey:"rule",keys:{rule:{},flags:{}},normalize:t=>typeof t=="string"?{rule:t}:t instanceof RegExp?t.flags?{rule:t.source,flags:t.flags}:{rule:t.source}:t,obviatesBasisDescription:!0,obviatesBasisExpression:!0,hasAssociatedError:!0,intersectionIsOpen:!0,defaults:{description:t=>`matched by ${t.rule}`},intersections:{pattern:()=>null}});class hc extends Rt{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=p.intrinsic.string.internal;reduceJsonSchema(e,n){return e.pattern?n.fallback.patternIntersection({code:"patternIntersection",base:e,pattern:this.rule}):(e.pattern=this.rule,e)}}const ji={implementation:dc,Node:hc},dt=(t,e)=>{const n=pc(t);return e&&!e.includes(n)?d(`Root of kind ${n} should be one of ${e}`):n},pc=t=>{if(b(t,"root"))return t.kind;if(typeof t=="string")return t[0]==="$"?"alias":t in re?"domain":"proto";if(typeof t=="function")return"proto";if(typeof t!="object"||t===null)return d(Wn(t));if("morphs"in t)return"morph";if("branches"in t||F(t))return"union";if("unit"in t)return"unit";if("reference"in t)return"alias";const e=Object.keys(t);return e.length===0||e.some(n=>n in $i)?"intersection":"proto"in t?"proto":"domain"in t?"domain":d(Wn(t))},Wn=t=>`${S(t)} is not a valid type schema`,Hn={},fc=t=>F(t)?t.map(e=>e.collapsibleJson):t.collapsibleJson,W={};p.nodesByRegisteredId=W;const Fi=t=>(Hn[t]??=0,`${t}${++Hn[t]}`),Ui=t=>{const e=Ct[t.kind],n=e.applyConfig?.(t.def,t.$.resolvedConfig)??t.def,r={},{meta:i,...s}=n,o=i===void 0?{}:typeof i=="string"?{description:i}:i,a=Zr(s).sort(([c],[u])=>ut(c)?ut(u)?yt(c)-yt(u):1:ut(u)||c<u?-1:1).filter(([c,u])=>{if(c.startsWith("meta.")){const h=c.slice(5);return o[h]=u,!1}return!0});for(const c of a){const u=c[0],h=e.keys[u];if(!h)return d(`Key ${u} is not valid on ${t.kind} schema`);const m=h.parse?h.parse(c[1],t):c[1];m!==ee&&(m!==void 0||h.preserveUndefined)&&(r[u]=m)}if(e.reduce&&!t.prereduced){const c=e.reduce(r,t.$);if(c)return c instanceof g?c.throw():gc(c,o)}return kn({id:t.id,kind:t.kind,inner:r,meta:o,$:t.$})},kn=({id:t,kind:e,inner:n,meta:r,$:i,ignoreCache:s})=>{const o=Ct[e],a=Zr(n),l=[];let c={};for(const[v,A]of a){const P=o.keys[v],G=P.serialize??(P.child?fc:be);if(c[v]=G(A),P.child===!0){const H=A;F(H)?l.push(...H):l.push(H)}else typeof P.child=="function"&&l.push(...P.child(A))}o.finalizeInnerJson&&(c=o.finalizeInnerJson(c));let u={...c},h={};Ze(r)||(h=O(r,(v,A)=>[v,v==="examples"?A:be(A)]),u.meta=at(h,"description",!0)),c=at(c,o.collapsibleKey,!1);const m=JSON.stringify({kind:e,...c});u=at(u,o.collapsibleKey,!1);const y=at(u,o.collapsibleKey,!0),x=JSON.stringify({kind:e,...u});if(i.nodesByHash[x]&&!s)return i.nodesByHash[x];const f={id:t,kind:e,impl:o,inner:n,innerEntries:a,innerJson:c,innerHash:m,meta:r,metaJson:h,json:u,hash:x,collapsibleJson:y,children:l};if(e!=="intersection")for(const v in n)v!=="in"&&v!=="out"&&(f[v]=n[v]);const w=new xl[e](f,i);return i.nodesByHash[x]=w},mc=(t,e)=>t.id===e?t:(U(W[e])&&D(`Unexpected attempt to overwrite node id ${e}`),kn({id:e,kind:t.kind,inner:t.inner,meta:t.meta,$:t.$,ignoreCache:!0})),gc=(t,e,n)=>kn({id:Fi(e.alias??t.kind),kind:t.kind,inner:t.inner,meta:e,$:t.$}),at=(t,e,n)=>{const r=Object.keys(t);if(r.length===1&&r[0]===e){const i=t[e];if(n||$e(i,"object")&&(Object.keys(i).length===1||Array.isArray(i)))return i}return t},nn=(t,e,n)=>{if(t.key!==e.key)return null;const r=t.key;let i=j(t.value,e.value,n);const s=t.required||e.required?"required":"optional";if(i instanceof g)if(s==="optional")i=p.intrinsic.never.internal;else return i.withPrefixKey(t.key,t.required&&e.required?"required":"optional");if(s==="required")return n.$.node("required",{key:r,value:i});const o=t.hasDefault()?e.hasDefault()?t.default===e.default?t.default:d(Ti(t.default,e.default)):t.default:e.hasDefault()?e.default:ee;return n.$.node("optional",{key:r,value:i,default:o})};class zi extends Ke{required=this.kind==="required";optional=this.kind==="optional";impliedBasis=p.intrinsic.object.internal;serializedKey=et(this.key);compiledKey=typeof this.key=="string"?this.key:this.serializedKey;flatRefs=N(this.value.flatRefs.map(e=>de([this.key,...e.path],e.node)),de([this.key],this.value));_transform(e,n){n.path.push(this.key);const r=super._transform(e,n);return n.path.pop(),r}hasDefault(){return"default"in this.inner}traverseAllows=(e,n)=>this.key in e?se(this.key,()=>this.value.traverseAllows(e[this.key],n),n):this.optional;traverseApply=(e,n)=>{this.key in e?se(this.key,()=>this.value.traverseApply(e[this.key],n),n):this.hasKind("required")&&n.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 Ti=(t,e)=>`Invalid intersection of default values ${S(t)} & ${S(e)}`,yc=q({kind:"optional",hasAssociatedError:!1,intersectionIsOpen:!0,keys:{key:{},value:{child:!0,parse:(t,e)=>e.$.parseSchema(t)},default:{preserveUndefined:!0}},normalize:t=>t,reduce:(t,e)=>{if(e.resolvedConfig.exactOptionalPropertyTypes===!1&&!t.value.allows(void 0))return e.node("optional",{...t,value:t.value.or($.undefined)},{prereduced:!0})},defaults:{description:t=>`${t.compiledKey}?: ${t.value.description}`},intersections:{optional:nn}});class bc extends zi{constructor(...e){super(...e),"default"in this.inner&&In(this.value,this.inner.default,this.key)}get rawIn(){const e=super.rawIn;return this.hasDefault()?this.$.node("optional",Qr(e.inner,{default:!0}),{prereduced:!0}):e}get outProp(){if(!this.hasDefault())return this;const{default:e,...n}=this.inner;return this.cacheGetter("outProp",this.$.node("required",n,{prereduced:!0}))}expression=this.hasDefault()?`${this.compiledKey}: ${this.value.expression} = ${S(this.inner.default)}`:`${this.compiledKey}?: ${this.value.expression}`;defaultValueMorph=wc(this);defaultValueMorphRef=this.defaultValueMorph&&z(this.defaultValueMorph)}const An={implementation:yc,Node:bc},$c={},wc=t=>{if(!t.hasDefault())return;const e=`{${t.compiledKey}: ${t.value.id} = ${be(t.default)}}`;return $c[e]??=_i(t.key,t.value,t.default)},_i=(t,e,n)=>{if(typeof n=="function")return e.includesTransform?(i,s)=>(se(t,()=>e(i[t]=n(),s),s),i):i=>(i[t]=n(),i);const r=e.includesTransform?e.assert(n):n;return $e(r,"object")?(i,s)=>(se(t,()=>e(i[t]=n,s),s),i):i=>(i[t]=r,i)},In=(t,e,n)=>{const r=At(e);$e(e,"object")&&!r&&d(vc(n));const i=t.in(r?e():e);if(i instanceof he){n===null&&d(`Default ${i.summary}`);const s=i.transform(o=>o.transform(a=>({...a,prefixPath:[n]})));d(`Default for ${s.summary}`)}return e},vc=t=>`Non-primitive default ${t===null?"":typeof t=="number"?`for value at [${t}] `:`for ${et(t)} `}must be specified as a function like () => ({my: 'object'})`;class tt extends xi{constructor(e,n){super(e,n),Object.defineProperty(this,ie,{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=>{const n=this(e);return n instanceof he?n:{value:n}},toJSONSchema:e=>e.target&&e.target!=="draft-2020-12"?d(`JSONSchema target '${e.target}' is not supported (must be "draft-2020-12")`):e.io==="input"?this.rawIn.toJsonSchema():this.rawOut.toJsonSchema()}}as(){return this}brand(e){return e===""?d(xc):this}readonly(){return this}branches=this.hasKind("union")?this.inner.branches:[this];distribute(e,n){const r=this.branches.map(e);return n?.(r)??r}get shortDescription(){return this.meta.description??this.defaultShortDescription}toJsonSchema(e={}){const n=vi(this.$.resolvedConfig.toJsonSchema,e);n.useRefs||=this.isCyclic;const r=typeof n.dialect=="string"?{$schema:n.dialect}:{};return Object.assign(r,this.toJsonSchemaRecurse(n)),n.useRefs&&(r.$defs=O(this.references,(i,s)=>s.isRoot()&&!s.alwaysExpandJsonSchema?[s.id,s.toResolvedJsonSchema(n)]:[])),r}toJsonSchemaRecurse(e){return e.useRefs&&!this.alwaysExpandJsonSchema?{$ref:`#/$defs/${this.id}`}:this.toResolvedJsonSchema(e)}get alwaysExpandJsonSchema(){return this.isBasis()||this.kind==="alias"||this.hasKind("union")&&this.isBoolean}toResolvedJsonSchema(e){const n=this.innerToJsonSchema(e);return Object.assign(n,this.metaJson)}intersect(e){const n=this.$.parseDefinition(e),r=this.rawIntersect(n);return r instanceof g?r:this.$.finalize(r)}rawIntersect(e){return oe(this,e,this.$)}toNeverIfDisjoint(){return this}and(e){const n=this.intersect(e);return n instanceof g?n.throw():n}rawAnd(e){const n=this.rawIntersect(e);return n instanceof g?n.throw():n}or(e){const n=this.$.parseDefinition(e);return this.$.finalize(this.rawOr(n))}rawOr(e){const n=[...this.branches,...e.branches];return this.$.node("union",n)}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;const e=this.applyStructuralOperation("keyof",[]).reduce((n,r)=>n.intersect(r).toNeverIfDisjoint(),p.intrinsic.unknown.internal);return e.branches.length===0&&d(Ai(`keyof ${this.expression}`)),this._keyof=this.$.finalize(e)}get props(){return this.branches.length!==1?d(kc(this.expression)):[...this.applyStructuralOperation("props",[])[0]]}merge(e){const n=this.$.parseDefinition(e);return this.$.schema(n.distribute(r=>this.applyStructuralOperation("merge",[Zn(r)??d(Yn("merge",r.expression))])))}applyStructuralOperation(e,n){return this.distribute(r=>{if(r.equals(p.intrinsic.object)&&e!=="merge")return r;const i=Zn(r);if(i||d(Yn(e,r.expression)),e==="keyof")return i.keyof();if(e==="get")return i.get(...n);if(e==="props")return i.props;const s=e==="required"?"require":e==="partial"?"optionalize":e;return this.$.node("intersection",{domain:"object",structure:i[s](...n)})})}get(...e){return e[0]===void 0?this:this.$.schema(this.applyStructuralOperation("get",e))}extract(e){const n=this.$.parseDefinition(e);return this.$.schema(this.branches.filter(r=>r.extends(n)))}exclude(e){const n=this.$.parseDefinition(e);return this.$.schema(this.branches.filter(r=>!r.extends(n)))}array(){return this.$.schema(this.isUnknown()?{proto:Array}:{proto:Array,sequence:this},{prereduced:!0})}overlaps(e){return!(this.intersect(e)instanceof g)}extends(e){const n=this.intersect(e);return!(n instanceof g)&&this.equals(n)}ifExtends(e){return this.extends(e)?this:void 0}subsumes(e){return this.$.parseDefinition(e).extends(this)}configure(e,n="shallow"){return this.configureReferences(e,n)}describe(e,n="shallow"){return this.configure({description:e},n)}optional(){return[this,"?"]}default(e){return In(this,e,null),[this,"=",e]}from(e){return this.assert(e)}_pipe(...e){const n=e.reduce((r,i)=>r.rawPipeOnce(i),this);return this.$.finalize(n)}tryPipe(...e){const n=e.reduce((r,i)=>r.rawPipeOnce(b(i,"root")?i:(s,o)=>{try{return i(s,o)}catch(a){return o.error({code:"predicate",predicate:i,actual:`aborted due to error:\n ${a}\n`})}}),this);return this.$.finalize(n)}pipe=Object.assign(this._pipe.bind(this),{try:this.tryPipe.bind(this)});to(e){return this.$.finalize(this.toNode(this.$.parseDefinition(e)))}toNode(e){const n=en(this,e,this.$);return n instanceof g?n.throw():n}rawPipeOnce(e){return b(e,"root")?this.toNode(e):this.distribute(n=>n.hasKind("morph")?this.$.node("morph",{in:n.inner.in,morphs:[...n.morphs,e]}):this.$.node("morph",{in:n,morphs:[e]}),this.$.parseSchema)}narrow(e){return this.constrainOut("predicate",e)}constrain(e,n){return this._constrain("root",e,n)}constrainIn(e,n){return this._constrain("in",e,n)}constrainOut(e,n){return this._constrain("out",e,n)}_constrain(e,n,r){const i=this.$.node(n,r);if(i.isRoot())return i.isUnknown()?this:D(`Unexpected constraint node ${i}`);const s=e==="root"?this:e==="in"?this.rawIn:this.rawOut;if(s.hasKind("morph")||i.impliedBasis&&!s.extends(i.impliedBasis))return Pa(n,i.impliedBasis,this);const o=this.$.node("intersection",{[i.kind]:i}),a=e==="out"?en(this,o,this.$):oe(this,o,this.$);return a instanceof g&&a.throw(),this.$.finalize(a)}onUndeclaredKey(e){const n=typeof e=="string"?e:e.rule,r=typeof e=="string"?!1:e.deep;return this.$.finalize(this.transform((i,s)=>i==="structure"?n==="ignore"?Qr(s,{undeclared:1}):{...s,undeclared:n}:s,r?void 0:{shouldTransform:i=>!le(St,i.kind)}))}hasEqualMorphs(e){return!this.includesTransform&&!e.includesTransform?!0:!(!Ce(this.shallowMorphs,e.shallowMorphs)||!Ce(this.flatMorphs,e.flatMorphs,{isEqual:(n,r)=>n.propString===r.propString&&(n.node.hasKind("morph")&&r.node.hasKind("morph")?n.node.hasEqualMorphs(r.node):n.node.hasKind("intersection")&&r.node.hasKind("intersection")?n.node.structure?.structuralMorphRef===r.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",Ie(e))}lessThan(e){return this.constrain("max",Ie(e))}atLeastLength(e){return this.constrain("minLength",e)}atMostLength(e){return this.constrain("maxLength",e)}moreThanLength(e){return this.constrain("minLength",Ie(e))}lessThanLength(e){return this.constrain("maxLength",Ie(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",Ie(e))}earlierThan(e){return this.constrain("before",Ie(e))}}const xc="Expected a non-empty brand name after #",Ie=t=>typeof t=="object"&&!(t instanceof Date)?{...t,exclusive:!0}:{rule:t,exclusive:!0},ct=(t,e)=>b(e,"root")?b(t,"root")?t.extends(e):e.allows(t):b(t,"root")?t.hasUnit(e):e===t,Zn=t=>t.hasKind("morph")?null:t.hasKind("intersection")?t.inner.structure??(t.basis?.domain==="object"?t.$.bindReference(p.intrinsic.emptyStructure):null):t.isBasis()&&t.domain==="object"?t.$.bindReference(p.intrinsic.emptyStructure):null,kc=t=>`Props cannot be extracted from a union. Use .distribute to extract props from each branch instead. Received:\n${t}`,Yn=(t,e)=>`${t} operand must be an object (was ${e})`,nt=(t,e)=>O(vn(t),(n,r)=>[r,e]),Ac=t=>typeof t=="string"?{reference:t}:t,Qn=t=>t instanceof g?p.intrinsic.never.internal:t,Ic=q({kind:"alias",hasAssociatedError:!1,collapsibleKey:"reference",keys:{reference:{serialize:t=>t.startsWith("$")?t:`$ark.${t}`},resolve:{}},normalize:Ac,defaults:{description:t=>t.reference},intersections:{alias:(t,e,n)=>n.$.lazilyResolve(()=>Qn(j(t.resolution,e.resolution,n)),`${t.reference}${n.pipe?"=>":"&"}${e.reference}`),...nt("alias",(t,e,n)=>e.isUnknown()?t:e.isNever()?e:e.isBasis()&&!e.overlaps(p.intrinsic.object)?g.init("assignability",p.intrinsic.object,e):n.$.lazilyResolve(()=>Qn(j(t.resolution,e,n)),`${t.reference}${n.pipe?"=>":"&"}${e.id}`))}});class Sc extends tt{expression=this.reference;structure=void 0;get resolution(){const 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));const e=this.reference;let n=W[e];const r=[];for(;b(n,"context");){if(r.includes(n.id))return d(Nc(n.id,r));r.push(n.id),n=W[n.id]}return b(n,"root")?n:D(`Unexpected resolution for reference ${this.reference}\nSeen: [${r.join("->")}] \nResolution: ${S(n)}`)}get resolutionId(){if(this.reference.includes("&")||this.reference.includes("=>"))return this.resolution.id;if(this.reference[0]!=="$")return this.reference;const e=this.reference.slice(1),n=this.$.resolutions[e];return typeof n=="string"?n:b(n,"root")?n.id:D(`Unexpected resolution for reference ${this.reference}: ${S(n)}`)}get defaultShortDescription(){return re.object}innerToJsonSchema(e){return this.resolution.toJsonSchemaRecurse(e)}traverseAllows=(e,n)=>{const r=n.seen[this.reference];return r?.includes(e)?!0:(n.seen[this.reference]=N(r,e),this.resolution.traverseAllows(e,n))};traverseApply=(e,n)=>{const r=n.seen[this.reference];r?.includes(e)||(n.seen[this.reference]=N(r,e),this.resolution.traverseApply(e,n))};compile(e){const n=this.resolutionId;e.if(`ctx.seen.${n} && ctx.seen.${n}.includes(data)`,()=>e.return(!0)),e.if(`!ctx.seen.${n}`,()=>e.line(`ctx.seen.${n} = []`)),e.line(`ctx.seen.${n}.push(data)`),e.return(e.invoke(n))}}const Nc=(t,e)=>`Alias '${t}' has a shallow resolution cycle: ${[...e,t].join("->")}`,Sn={implementation:Ic,Node:Sc};class Nn extends tt{traverseApply=(e,n)=>{this.traverseAllows(e,n)||n.errorFromNodeContext(this.errorContext)};get errorContext(){return{code:this.kind,description:this.description,meta:this.meta,...this.inner}}get compiledErrorContext(){return Ot(this.errorContext)}compile(e){e.traversalKind==="Allows"?e.return(this.compiledCondition):e.if(this.compiledNegation,()=>e.line(`ctx.errorFromNodeContext(${this.compiledErrorContext})`))}}const Oc=q({kind:"domain",hasAssociatedError:!0,collapsibleKey:"domain",keys:{domain:{},numberAllowsNaN:{}},normalize:t=>typeof t=="string"?{domain:t}:mn(t,"numberAllowsNaN")&&t.domain!=="number"?d(On.writeBadAllowNanMessage(t.domain)):t,applyConfig:(t,e)=>t.numberAllowsNaN===void 0&&t.domain==="number"&&e.numberAllowsNaN?{...t,numberAllowsNaN:!0}:t,defaults:{description:t=>re[t.domain],actual:t=>Number.isNaN(t)?"NaN":re[Q(t)]},intersections:{domain:(t,e)=>t.domain==="number"&&e.domain==="number"?t.numberAllowsNaN?e:t:g.init("domain",t,e)}});class Rc extends Nn{requiresNaNCheck=this.domain==="number"&&!this.numberAllowsNaN;traverseAllows=this.requiresNaNCheck?e=>typeof e=="number"&&!Number.isNaN(e):e=>Q(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 re[this.domain]}innerToJsonSchema(e){return this.domain==="bigint"||this.domain==="symbol"?e.fallback.domain({code:"domain",base:{},domain:this.domain}):{type:this.domain}}}const On={implementation:Oc,Node:Rc,writeBadAllowNanMessage:t=>`numberAllowsNaN may only be specified with domain "number" (was ${t})`},Cc=q({kind:"intersection",hasAssociatedError:!0,normalize:t=>{if(U(t))return t;const{structure:e,...n}=t,r=!!e,i=e??{},s=O(n,(o,a)=>te(o,$a)?(r&&d(`Flattened structure key ${o} cannot be specified alongside a root 'structure' key.`),i[o]=a,[]):[o,a]);return(b(i,"constraint")||!Ze(i))&&(s.structure=i),s},finalizeInnerJson:({structure:t,...e})=>$e(t,"object")?{...t,...e}:e,keys:{domain:{child:!0,parse:(t,e)=>e.$.node("domain",t)},proto:{child:!0,parse:(t,e)=>e.$.node("proto",t)},structure:{child:!0,parse:(t,e)=>e.$.node("structure",t),serialize:t=>{if(!t.sequence?.minLength)return t.collapsibleJson;const{sequence:e,...n}=t.collapsibleJson,{minVariadicLength:r,...i}=e,s=i.variadic&&Object.keys(i).length===1?i.variadic:i;return{...n,sequence:s}}},divisor:{child:!0,parse:T("divisor")},max:{child:!0,parse:T("max")},min:{child:!0,parse:T("min")},maxLength:{child:!0,parse:T("maxLength")},minLength:{child:!0,parse:T("minLength")},exactLength:{child:!0,parse:T("exactLength")},before:{child:!0,parse:T("before")},after:{child:!0,parse:T("after")},pattern:{child:!0,parse:T("pattern")},predicate:{child:!0,parse:T("predicate")}},reduce:(t,e)=>Xn({},t,{$:e,invert:!1,pipe:!1}),defaults:{description:t=>{if(t.children.length===0)return"unknown";if(t.structure)return t.structure.description;const e=[];if(t.basis&&!t.prestructurals.some(n=>n.impl.obviatesBasisDescription)&&e.push(t.basis.description),t.prestructurals.length){const n=t.prestructurals.toSorted((r,i)=>r.kind==="min"&&i.kind==="max"?-1:0).map(r=>r.description);e.push(...n)}return t.inner.predicate&&e.push(...t.inner.predicate.map(n=>n.description)),e.join(" and ")},expected:t=>` ◦ ${t.errors.map(e=>e.expected).join(`\n ◦ `)}`,problem:t=>`(${t.actual}) must be...\n${t.expected}`},intersections:{intersection:(t,e,n)=>Xn(t.inner,e.inner,n),...nt("intersection",(t,e,n)=>{if(t.children.length===0)return e;const{domain:r,proto:i,...s}=t.inner,o=i??r,a=o?j(o,e,n):e;return a instanceof g?a:t?.basis?.equals(a)?t:t.$.node("intersection",{...s,[a.kind]:a},{prereduced:!0})})}});class Mc extends tt{basis=this.inner.domain??this.inner.proto??null;prestructurals=[];refinements=this.children.filter(e=>e.isRefinement()?(le(yi,e.kind)&&this.prestructurals.push(e),!0):!1);structure=this.inner.structure;expression=Pc(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((n,r)=>r.isBasis()?r.toJsonSchemaRecurse(e):r.reduceJsonSchema(n,e),{})}traverseAllows=(e,n)=>this.children.every(r=>r.traverseAllows(e,n));traverseApply=(e,n)=>{const r=n.currentErrorCount;if(!(this.basis&&(this.basis.traverseApply(e,n),n.currentErrorCount>r))){if(this.prestructurals.length){for(let i=0;i<this.prestructurals.length-1;i++)if(this.prestructurals[i].traverseApply(e,n),n.failFast&&n.currentErrorCount>r)return;if(this.prestructurals.at(-1).traverseApply(e,n),n.currentErrorCount>r)return}if(!(this.structure&&(this.structure.traverseApply(e,n),n.currentErrorCount>r))&&this.inner.predicate){for(let i=0;i<this.inner.predicate.length-1;i++)if(this.inner.predicate[i].traverseApply(e,n),n.failFast&&n.currentErrorCount>r)return;this.inner.predicate.at(-1).traverseApply(e,n)}}};compile(e){if(e.traversalKind==="Allows"){for(const n of this.children)e.check(n);e.return(!0);return}if(e.initializeErrorCount(),this.basis&&(e.check(this.basis),this.children.length>1&&e.returnIfFail()),this.prestructurals.length){for(let n=0;n<this.prestructurals.length-1;n++)e.check(this.prestructurals[n]),e.returnIfFailFast();e.check(this.prestructurals.at(-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 n=0;n<this.inner.predicate.length-1;n++)e.check(this.inner.predicate[n]),e.returnIfFail();e.check(this.inner.predicate.at(-1))}}}const Ji={implementation:Cc,Node:Mc},Pc=t=>{if(t.structure?.expression)return t.structure.expression;const e=t.basis&&!t.prestructurals.some(i=>i.impl.obviatesBasisExpression)?t.basis.nestableExpression:"",n=t.prestructurals.map(i=>i.expression).join(" & "),r=`${e}${e?" ":""}${n}`;return r==="Array == 0"?"[]":r||"unknown"},Xn=(t,e,n)=>{const r={},i=t.proto??t.domain,s=e.proto??e.domain,o=i?s?j(i,s,n):i:s;return o instanceof g?o:(o&&(r[o.kind]=o),bt({kind:"intersection",baseInner:r,l:$t(t),r:$t(e),roots:[],ctx:n}))},qc=q({kind:"morph",hasAssociatedError:!1,keys:{in:{child:!0,parse:(t,e)=>e.$.parseSchema(t)},morphs:{parse:He,serialize:t=>t.map(e=>b(e,"root")?e.json:z(e))},declaredIn:{child:!1,serialize:t=>t.json},declaredOut:{child:!1,serialize:t=>t.json}},normalize:t=>t,defaults:{description:t=>`a morph from ${t.rawIn.description} to ${t.rawOut?.description??"unknown"}`},intersections:{morph:(t,e,n)=>{if(!t.hasEqualMorphs(e))return d(Kc(t.expression,e.expression));const r=j(t.rawIn,e.rawIn,n);if(r instanceof g)return r;const i={morphs:t.morphs};if(t.declaredIn||e.declaredIn){const s=j(t.rawIn,e.rawIn,n);if(s instanceof g)return s.throw();i.declaredIn=s}if(t.declaredOut||e.declaredOut){const s=j(t.rawOut,e.rawOut,n);if(s instanceof g)return s.throw();i.declaredOut=s}return r.distribute(s=>n.$.node("morph",{...i,in:s}),n.$.parseSchema)},...nt("morph",(t,e,n)=>{const r=t.inner.in?j(t.inner.in,e,n):e;return r instanceof g?r:r.equals(t.inner.in)?t:n.$.node("morph",{...t.inner,in:r})})}});class Ec extends tt{serializedMorphs=this.morphs.map(z);compiledMorphs=`[${this.serializedMorphs}]`;lastMorph=this.inner.morphs.at(-1);lastMorphIfNode=b(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??p.intrinsic.unknown.internal}get rawOut(){return this.declaredOut??this.introspectableOut??p.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,n)=>!this.introspectableIn||this.introspectableIn.traverseAllows(e,n);traverseApply=(e,n)=>{this.introspectableIn&&this.introspectableIn.traverseApply(e,n),n.queueMorphs(this.morphs)};hasEqualMorphs(e){return Ce(this.morphs,e.morphs,{isEqual:(n,r)=>n===r||b(n,"root")&&b(r,"root")&&n.equals(r)})}}const Vi={implementation:qc,Node:Ec},Kc=(t,e)=>`The intersection of distinct morphs at a single path is indeterminate:\nLeft: ${t}\nRight: ${e}`,Dc=q({kind:"proto",hasAssociatedError:!0,collapsibleKey:"proto",keys:{proto:{serialize:t=>yn(t)??be(t)},dateAllowsInvalid:{}},normalize:t=>{const e=typeof t=="string"?{proto:Pe[t]}:typeof t=="function"?U(t)?t:{proto:t}:typeof t.proto=="string"?{...t,proto:Pe[t.proto]}:t;return typeof e.proto!="function"&&d(vt.writeInvalidSchemaMessage(e.proto)),mn(e,"dateAllowsInvalid")&&e.proto!==Date&&d(vt.writeBadInvalidDateMessage(e.proto)),e},applyConfig:(t,e)=>t.dateAllowsInvalid===void 0&&t.proto===Date&&e.dateAllowsInvalid?{...t,dateAllowsInvalid:!0}:t,defaults:{description:t=>t.builtinName?Ko[t.builtinName]:`an instance of ${t.proto.name}`,actual:t=>t instanceof Date&&t.toString()==="Invalid Date"?"an invalid Date":Gt(t)},intersections:{proto:(t,e)=>t.proto===Date&&e.proto===Date?t.dateAllowsInvalid?e:t:Fn(t.proto,e.proto)?t:Fn(e.proto,t.proto)?e:g.init("proto",t,e),domain:(t,e)=>e.domain==="object"?t:g.init("domain",p.intrinsic.object.internal,e)}});class Lc extends Nn{builtinName=yn(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}}const vt={implementation:Dc,Node:Lc,writeBadInvalidDateMessage:t=>`dateAllowsInvalid may only be specified with constructor Date (was ${t.name})`,writeInvalidSchemaMessage:t=>`instanceOf operand must be a function (was ${Q(t)})`},Bc=q({kind:"union",hasAssociatedError:!0,collapsibleKey:"branches",keys:{ordered:{},branches:{child:!0,parse:(t,e)=>{const n=[];for(const r of t){const i=b(r,"root")?r.branches:e.$.parseSchema(r).branches;for(const s of i)if(s.hasKind("morph")){const o=n.findIndex(a=>a.hasKind("morph")&&a.hasEqualMorphs(s));if(o===-1)n.push(s);else{const a=n[o];n[o]=e.$.node("morph",{...a.inner,in:a.rawIn.rawOr(s.rawIn)})}}else n.push(s)}return e.def.ordered||n.sort((r,i)=>r.hash<i.hash?-1:1),n}}},normalize:t=>F(t)?{branches:t}:t,reduce:(t,e)=>{const n=Hc(t);if(n.length===1)return n[0];if(n.length!==t.branches.length)return e.node("union",{...t,branches:n},{prereduced:!0})},defaults:{description:t=>t.distribute(e=>e.description,Oe),expected:t=>{const e=wo(t.errors,"propString"),n=Object.entries(e).map(([r,i])=>{const s=[];for(const l of i)ye(s,l.expected);const o=Oe(s),a=i.every(l=>l.actual===i[0].actual)?i[0].actual:S(i[0].data);return`${r&&`${r} `}must be ${o}${a&&` (was ${a})`}`});return Oe(n)},problem:t=>t.expected,message:t=>t.problem[0]==="["?`value at ${t.problem}`:t.problem},intersections:{union:(t,e,n)=>{if(t.isNever!==e.isNever)return g.init("presence",t,e);let r;return t.ordered?(e.ordered&&d(Yc(t.expression,e.expression)),r=Bt(e.branches,t.branches,n),r instanceof g&&r.invert()):r=Bt(t.branches,e.branches,n),r instanceof g?r:n.$.parseSchema(t.ordered||e.ordered?{branches:r,ordered:!0}:{branches:r})},...nt("union",(t,e,n)=>{const r=Bt(t.branches,[e],n);return r instanceof g?r:r.length===1?r[0]:n.$.parseSchema(t.ordered?{branches:r,ordered:!0}:{branches:r})})}});class jc extends tt{isBoolean=this.branches.length===2&&this.branches[0].hasUnit(!1)&&this.branches[1].hasUnit(!0);get branchGroups(){const e=[];let n=-1;for(const r of this.branches){if(r.hasKind("unit")&&r.domain==="boolean"){n===-1?(n=e.length,e.push(r)):e[n]=p.intrinsic.boolean;continue}e.push(r)}return e}unitBranches=this.branches.filter(e=>e.rawIn.hasKind("unit"));discriminant=this.discriminate();discriminantJson=this.discriminant?Vc(this.discriminant):null;expression=this.distribute(e=>e.nestableExpression,Wc);createBranchedOptimisticRootApply(){return(e,n)=>{const r=this.traverseOptimistic(e);if(r!==ee)return r;const i=new Ne(e,this.$.resolvedConfig);return this.traverseApply(e,i),i.finalize(n)}}get shallowMorphs(){return this.branches.reduce((e,n)=>ye(e,n.shallowMorphs),[])}get defaultShortDescription(){return this.distribute(e=>e.defaultShortDescription,Oe)}innerToJsonSchema(e){if(this.branchGroups.length===1&&this.branchGroups[0].equals(p.intrinsic.boolean))return{type:"boolean"};const n=this.branchGroups.map(r=>r.toJsonSchemaRecurse(e));return n.every(r=>Object.keys(r).length===1&&mn(r,"const"))?{enum:n.map(r=>r.const)}:{anyOf:n}}traverseAllows=(e,n)=>this.branches.some(r=>r.traverseAllows(e,n));traverseApply=(e,n)=>{const r=[];for(let i=0;i<this.branches.length;i++){if(n.pushBranch(),this.branches[i].traverseApply(e,n),!n.hasError())return this.branches[i].includesTransform?n.queuedMorphs.push(...n.popBranch().queuedMorphs):n.popBranch();r.push(n.popBranch().error)}n.errorFromNodeContext({code:"union",errors:r,meta:this.meta})};traverseOptimistic=e=>{for(let n=0;n<this.branches.length;n++){const r=this.branches[n];if(r.traverseAllows(e))return r.contextFreeMorph?r.contextFreeMorph(e):e}return ee};compile(e){if(!this.discriminant||this.unitBranches.length===this.branches.length&&this.branches.length===2)return this.compileIndiscriminable(e);let n=this.discriminant.optionallyChainedPropString;this.discriminant.kind==="domain"&&(n=`typeof ${n} === "object" ? ${n} === null ? "null" : "object" : typeof ${n} === "function" ? "object" : typeof ${n}`);const r=this.discriminant.cases,i=Object.keys(r),{optimistic:s}=e;if(e.optimistic=!1,e.block(`switch(${n})`,()=>{for(const u in r){const h=r[u],m=u==="default"?u:`case ${u}`;let y;h===!0?y=s?"data":"true":s?h.rootApplyStrategy==="branchedOptimistic"?y=e.invoke(h,{kind:"Optimistic"}):h.contextFreeMorph?y=`${e.invoke(h)} ? ${z(h.contextFreeMorph)}(data) : "${ee}"`:y=`${e.invoke(h)} ? data : "${ee}"`:y=e.invoke(h),e.line(`${m}: return ${y}`)}return e}),e.traversalKind==="Allows"){e.return(s?`"${ee}"`:!1);return}const o=Oe(this.discriminant.kind==="domain"?i.map(u=>{const h=u.slice(1,-1);return h==="function"?re.object:re[h]}):i),a=this.discriminant.path.map(u=>typeof u=="symbol"?z(u):JSON.stringify(u)),l=JSON.stringify(o),c=this.discriminant.kind==="domain"?`${_c}[${n}]`:`${Jc}(${n})`;e.line(`ctx.errorFromNodeContext({\n\tcode: "predicate",\n\texpected: ${l},\n\tactual: ${c},\n\trelativePath: [${a}],\n\tmeta: ${this.compiledMeta}\n})`)}compileIndiscriminable(e){if(e.traversalKind==="Apply"){e.const("errors","[]");for(const n of this.branches)e.line("ctx.pushBranch()").line(e.invoke(n)).if("!ctx.hasError()",()=>e.return(n.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{const{optimistic:n}=e;e.optimistic=!1;for(const r of this.branches)e.if(`${e.invoke(r)}`,()=>e.return(n?r.contextFreeMorph?`${z(r.contextFreeMorph)}(data)`:"data":!0));e.return(n?`"${ee}"`:!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){const s=O(this.unitBranches,(o,a)=>[`${a.rawIn.serializedValue}`,a.hasKind("morph")?a:!0]);return{kind:"unit",path:[],optionallyChainedPropString:"data",cases:s}}const e=[];for(let s=0;s<this.branches.length-1;s++){const o=this.branches[s];for(let a=s+1;a<this.branches.length;a++){const l=this.branches[a],c=oe(o.rawIn,l.rawIn,o.$);if(c instanceof g)for(const u of c){if(!u.kind||u.optional)continue;let h,m;if(u.kind==="domain"){const x=u.l,f=u.r;h=`"${typeof x=="string"?x:x.domain}"`,m=`"${typeof f=="string"?f:f.domain}"`}else if(u.kind==="unit")h=u.l.serializedValue,m=u.r.serializedValue;else continue;const y=e.find(x=>Ce(x.path,u.path)&&x.kind===u.kind);y?(y.cases[h]?y.cases[h].branchIndices=ye(y.cases[h].branchIndices,s):y.cases[h]??={branchIndices:[s],condition:u.l},y.cases[m]?y.cases[m].branchIndices=ye(y.cases[m].branchIndices,a):y.cases[m]??={branchIndices:[a],condition:u.r}):e.push({kind:u.kind,cases:{[h]:{branchIndices:[s],condition:u.l},[m]:{branchIndices:[a],condition:u.r}},path:u.path})}}}const n=this.ordered?zc(e,this.branches):e;if(!n.length)return null;const r=Fc(n,this),i={};for(const s in r.best.cases){const o=Uc(r,s);if(o===null){i[s]=!0;continue}if(o.length===this.branches.length)return null;this.ordered&&o.sort((c,u)=>c.originalIndex-u.originalIndex);const a=o.map(c=>c.branch),l=a.length===1?a[0]:this.$.node("union",this.ordered?{branches:a,ordered:!0}:a);Object.assign(this.referencesById,l.referencesById),i[s]=l}if(r.defaultEntries.length){const s=r.defaultEntries.map(o=>o.branch);i.default=this.$.node("union",this.ordered?{branches:s,ordered:!0}:s,{prereduced:!0}),Object.assign(this.referencesById,i.default.referencesById)}return Object.assign(r.location,{cases:i})}}const Fc=(t,e)=>{const r=t.sort((o,a)=>o.path.length===a.path.length?Object.keys(a.cases).length-Object.keys(o.cases).length:o.path.length-a.path.length)[0],i={kind:r.kind,path:r.path,optionallyChainedPropString:Gi(r.path)},s=e.branches.map((o,a)=>({originalIndex:a,branch:o}));return{best:r,location:i,defaultEntries:s,node:e}},Uc=(t,e)=>{const n=t.best.cases[e],r=Tc(n.condition,t.location.path,t.node.$);let i=[];const s=[];for(let o=0;o<t.defaultEntries.length;o++){const a=t.defaultEntries[o];if(n.branchIndices.includes(a.originalIndex)){const l=er(t.node.branches[a.originalIndex],t.location);l===null?i=null:i?.push({originalIndex:a.originalIndex,branch:l})}else if(a.branch.hasKind("alias")&&r.hasKind("domain")&&r.domain==="object")i?.push(a);else{if(a.branch.rawIn.overlaps(r)){const l=er(a.branch,t.location);i?.push({originalIndex:a.originalIndex,branch:l})}s.push(a)}}return t.defaultEntries=s,i},zc=(t,e)=>t.filter(r=>{const i=Object.values(r.cases).map(s=>s.branchIndices);for(let s=0;s<i.length-1;s++){const o=i[s];for(let a=s+1;a<i.length;a++){const l=i[a];for(const c of o)for(const u of l)if(c>u&&e[c].overlaps(e[u]))return!1}}return!0}),Tc=(t,e,n)=>{let r=t==="undefined"?n.node("unit",{unit:void 0}):t==="null"?n.node("unit",{unit:null}):t==="boolean"?n.units([!0,!1]):t;for(let i=e.length-1;i>=0;i--){const s=e[i];r=n.node("intersection",typeof s=="number"?{proto:"Array",sequence:[...bo(s).map(o=>({})),r]}:{domain:"object",required:[{key:s,value:r}]})}return r},Gi=t=>t.reduce((e,n)=>e+fi(n,!0),"data"),_c=z(vo),Jc=z(S),Wi={implementation:Bc,Node:jc},Vc=t=>({kind:t.kind,path:t.path.map(e=>typeof e=="string"?e:et(e)),cases:O(t.cases,(e,n)=>[e,n===!0?n:n.hasKind("union")&&n.discriminantJson?n.discriminantJson:n.json])}),Gc={delimiter:" | ",finalDelimiter:" | "},Wc=t=>Oe(t,Gc),Oe=(t,e)=>{const n=e?.delimiter??", ",r=e?.finalDelimiter??" or ";if(t.length===0)return"never";if(t.length===1)return t[0];if(t.length===2&&t[0]==="false"&&t[1]==="true"||t[0]==="true"&&t[1]==="false")return"boolean";const i={},s=t.filter(a=>i[a]?!1:i[a]=!0),o=s.pop();return`${s.join(n)}${s.length?r:""}${o}`},Bt=(t,e,n)=>{const r=e.map(()=>[]);for(let s=0;s<t.length;s++){let o={};for(let a=0;a<e.length;a++){if(r[a]===null)continue;if(t[s].equals(e[a])){r[a]=null,o={};break}const l=j(t[s],e[a],n);if(!(l instanceof g)){if(l.equals(t[s])){r[a].push(t[s]),o={};break}l.equals(e[a])?r[a]=null:o[a]=l}}for(const a in o)r[a][s]=o[a]}const i=r.flatMap((s,o)=>s?.flatMap(a=>a.branches)??e[o]);return i.length===0?g.init("union",t,e):i},Hc=({branches:t,ordered:e})=>{if(t.length<2)return t;const n=t.map(()=>!0);for(let r=0;r<t.length;r++)for(let i=r+1;i<t.length&&n[r]&&n[i];i++){if(t[r].equals(t[i])){n[i]=!1;continue}const s=oe(t[r].rawIn,t[i].rawIn,t[0].$);s instanceof g||(e||Zc(t[r],t[i]),s.equals(t[r].rawIn)?n[r]=!!e:s.equals(t[i].rawIn)&&(n[i]=!1))}return t.filter((r,i)=>n[i])},Zc=(t,e)=>{!t.includesTransform&&!e.includesTransform||(Ce(t.shallowMorphs,e.shallowMorphs)||d(tr(t.expression,e.expression)),Ce(t.flatMorphs,e.flatMorphs,{isEqual:(n,r)=>n.propString===r.propString&&(n.node.hasKind("morph")&&r.node.hasKind("morph")?n.node.hasEqualMorphs(r.node):n.node.hasKind("intersection")&&r.node.hasKind("intersection")?n.node.structure?.structuralMorphRef===r.node.structure?.structuralMorphRef:!1)})||d(tr(t.expression,e.expression)))},er=(t,e)=>t.transform((n,r)=>n==="domain"||n==="unit"?null:r,{shouldTransform:(n,r)=>{const i=Gi(r.path);return e.optionallyChainedPropString.startsWith(i)?n.hasKind("domain")&&n.domain==="object"||(n.hasKind("domain")||e.kind==="unit")&&i===e.optionallyChainedPropString?!0:n.children.length!==0&&n.kind!=="index":!1}}),tr=(t,e)=>`An unordered union of a type including a morph and a type with overlapping input is indeterminate:\nLeft: ${t}\nRight: ${e}`,Yc=(t,e)=>`The intersection of two ordered unions is indeterminate:\nLeft: ${t}\nRight: ${e}`,Qc=q({kind:"unit",hasAssociatedError:!0,keys:{unit:{preserveUndefined:!0,serialize:t=>t instanceof Date?t.toISOString():be(t)}},normalize:t=>t,defaults:{description:t=>S(t.unit),problem:({expected:t,actual:e})=>`${t===e?`must be reference equal to ${t} (serialized to the same value)`:`must be ${t} (was ${e})`}`},intersections:{unit:(t,e)=>g.init("unit",t,e),...nt("unit",(t,e)=>{if(e.allows(t.unit))return t;const n=e.hasKind("intersection")?e.basis:e;if(n){const r=n.hasKind("domain")?n:p.intrinsic.object;if(t.domain!==r.domain){const i=t.domain==="undefined"||t.domain==="null"||t.domain==="boolean"?t.domain:p.intrinsic[t.domain];return g.init("domain",i,r)}}return g.init("assignability",t,e.hasKind("intersection")?e.children.find(r=>!r.allows(t.unit)):e)})}});class Xc extends Nn{compiledValue=this.json.unit;serializedValue=typeof this.unit=="string"||this.unit instanceof Date?JSON.stringify(this.compiledValue):`${this.compiledValue}`;compiledCondition=nr(this.unit,this.serializedValue);compiledNegation=nr(this.unit,this.serializedValue,"negated");expression=S(this.unit);domain=Q(this.unit);get defaultShortDescription(){return this.domain==="object"?re.object:this.description}innerToJsonSchema(e){return this.unit===null?{type:"null"}:p.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}const Hi={implementation:Qc,Node:Xc},nr=(t,e,n)=>{if(t instanceof Date){const r=`data instanceof Date && data.toISOString() === ${e}`;return n?`!(${r})`:r}return Number.isNaN(t)?`${n?"!":""}Number.isNaN(data)`:`data ${n?"!":"="}== ${e}`},el=q({kind:"index",hasAssociatedError:!1,intersectionIsOpen:!0,keys:{signature:{child:!0,parse:(t,e)=>{const n=e.$.parseSchema(t);if(!n.extends(p.intrinsic.key))return d(rl(n.expression));const r=n.branches.filter(i=>i.hasKind("unit"));return r.length?d(nl(r.map(i=>S(i.unit)))):n}},value:{child:!0,parse:(t,e)=>e.$.parseSchema(t)}},normalize:t=>t,defaults:{description:t=>`[${t.signature.expression}]: ${t.value.description}`},intersections:{index:(t,e,n)=>{if(t.signature.equals(e.signature)){const r=j(t.value,e.value,n),i=r instanceof g?p.intrinsic.never.internal:r;return n.$.node("index",{signature:t.signature,value:i})}return t.signature.extends(e.signature)&&t.value.subsumes(e.value)?e:e.signature.extends(t.signature)&&e.value.subsumes(t.value)?t:null}}});class tl extends Ke{impliedBasis=p.intrinsic.object.internal;expression=`[${this.signature.expression}]: ${this.value.expression}`;flatRefs=N(this.value.flatRefs.map(e=>de([this.signature,...e.path],e.node)),de([this.signature],this.value));traverseAllows=(e,n)=>ft(e).every(r=>this.signature.traverseAllows(r[0],n)?se(r[0],()=>this.value.traverseAllows(r[1],n),n):!0);traverseApply=(e,n)=>{for(const r of ft(e))this.signature.traverseAllows(r[0],n)&&se(r[0],()=>this.value.traverseApply(r[1],n),n)};_transform(e,n){n.path.push(this.signature);const r=super._transform(e,n);return n.path.pop(),r}compile(){}}const Zi={implementation:el,Node:tl},nl=t=>`Index keys ${t.join(", ")} should be specified as named props.`,rl=t=>`Indexed key definition '${t}' must be a string or symbol`,il=q({kind:"required",hasAssociatedError:!0,intersectionIsOpen:!0,keys:{key:{},value:{child:!0,parse:(t,e)=>e.$.parseSchema(t)}},normalize:t=>t,defaults:{description:t=>`${t.compiledKey}: ${t.value.description}`,expected:t=>t.missingValueDescription,actual:()=>"missing"},intersections:{required:nn,optional:nn}});class sl extends zi{expression=`${this.compiledKey}: ${this.value.expression}`;errorContext=Object.freeze({code:"required",missingValueDescription:this.value.defaultShortDescription,relativePath:[this.key],meta:this.meta});compiledErrorContext=Ot(this.errorContext)}const Yi={implementation:il,Node:sl},ol=q({kind:"sequence",hasAssociatedError:!1,collapsibleKey:"variadic",keys:{prefix:{child:!0,parse:(t,e)=>{if(t.length!==0)return t.map(n=>e.$.parseSchema(n))}},optionals:{child:!0,parse:(t,e)=>{if(t.length!==0)return t.map(n=>e.$.parseSchema(n))}},defaultables:{child:t=>t.map(e=>e[0]),parse:(t,e)=>{if(t.length!==0)return t.map(n=>{const r=e.$.parseSchema(n[0]);return In(r,n[1],null),[r,n[1]]})},serialize:t=>t.map(e=>[e[0].collapsibleJson,be(e[1])]),reduceIo:(t,e,n)=>{if(t==="in"){e.optionals=n.map(r=>r[0].rawIn);return}e.prefix=n.map(r=>r[0].rawOut)}},variadic:{child:!0,parse:(t,e)=>e.$.parseSchema(t,e)},minVariadicLength:{parse:t=>t===0?void 0:t},postfix:{child:!0,parse:(t,e)=>{if(t.length!==0)return t.map(n=>e.$.parseSchema(n))}}},normalize:t=>{if(typeof t=="string")return{variadic:t};if("variadic"in t||"prefix"in t||"defaultables"in t||"optionals"in t||"postfix"in t||"minVariadicLength"in t){if(t.postfix?.length){if(!t.variadic)return d(dl);if(t.optionals?.length||t.defaultables?.length)return d(Xi)}return t.minVariadicLength&&!t.variadic?d("minVariadicLength may not be specified without a variadic element"):t}return{variadic:t}},reduce:(t,e)=>{let n=t.minVariadicLength??0;const r=t.prefix?.slice()??[],i=t.defaultables?.slice()??[],s=t.optionals?.slice()??[],o=t.postfix?.slice()??[];if(t.variadic){for(;s.at(-1)?.equals(t.variadic);)s.pop();if(s.length===0&&i.length===0)for(;r.at(-1)?.equals(t.variadic);)r.pop(),n++;for(;o[0]?.equals(t.variadic);)o.shift(),n++}else s.length===0&&i.length===0&&r.push(...o.splice(0));if(n!==t.minVariadicLength||t.prefix&&t.prefix.length!==r.length)return e.node("sequence",{...t,prefix:r,defaultables:i,optionals:s,postfix:o,minVariadicLength:n},{prereduced:!0})},defaults:{description:t=>t.isVariadicOnly?`${t.variadic.nestableExpression}[]`:`[${t.tuple.map(n=>n.kind==="defaultables"?`${n.node.nestableExpression} = ${S(n.default)}`:n.kind==="optionals"?`${n.node.nestableExpression}?`:n.kind==="variadic"?`...${n.node.nestableExpression}[]`:n.node.expression).join(", ")}]`},intersections:{sequence:(t,e,n)=>{const r=Fe({l:t.tuple,r:e.tuple,disjoint:new g,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",rr(i[0].result)):n.$.node("union",i.map(s=>({proto:Array,sequence:rr(s.result)})))}}});class al extends Ke{impliedBasis=p.intrinsic.Array.internal;tuple=ul(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=ge(this.variadic&&[this.variadic],this.postfix);flatRefs=this.addFlatRefs();addFlatRefs(){return Jn(this.flatRefs,this.prevariadic.flatMap((e,n)=>N(e.node.flatRefs.map(r=>de([`${n}`,...r.path],r.node)),de([`${n}`],e.node)))),Jn(this.flatRefs,this.variadicOrPostfix.flatMap(e=>N(e.flatRefs.map(n=>de([p.intrinsic.nonNegativeIntegerString.internal,...n.path],n.node)),de([p.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=ll(this);defaultValueMorphsReference=this.defaultValueMorphs.length?z(this.defaultValueMorphs):void 0;elementAtIndex(e,n){if(n<this.prevariadic.length)return this.tuple[n];const r=e.length-this.postfixLength;return n>=r?{kind:"postfix",node:this.postfix[n-r]}:{kind:"variadic",node:this.variadic??D(`Unexpected attempt to access index ${n} on ${this}`)}}traverseAllows=(e,n)=>{for(let r=0;r<e.length;r++)if(!this.elementAtIndex(e,r).node.traverseAllows(e[r],n))return!1;return!0};traverseApply=(e,n)=>{let r=0;for(;r<e.length;r++)se(r,()=>this.elementAtIndex(e,r).node.traverseApply(e[r],n),n)};get element(){return this.cacheGetter("element",this.$.node("union",this.children))}compile(e){if(this.prefix)for(const[n,r]of this.prefix.entries())e.traverseKey(`${n}`,`data[${n}]`,r);for(const[n,r]of this.defaultablesAndOptionals.entries()){const i=`${n+this.prefixLength}`;e.if(`${i} >= data.length`,()=>e.traversalKind==="Allows"?e.return(!0):e.return()),e.traverseKey(i,`data[${i}]`,r)}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(const[n,r]of this.postfix.entries()){const i=`firstPostfixIndex + ${n}`;e.traverseKey(i,`data[${i}]`,r)}e.traversalKind==="Allows"&&e.return(!0)}_transform(e,n){n.path.push(p.intrinsic.nonNegativeIntegerString.internal);const r=super._transform(e,n);return n.path.pop(),r}expression=this.description;reduceJsonSchema(e,n){if(this.prevariadic.length&&(e.prefixItems=this.prevariadic.map(r=>{const i=r.node.toJsonSchemaRecurse(n);if(r.kind==="defaultables"){const s=typeof r.default=="function"?r.default():r.default;i.default=p.intrinsic.jsonData.allows(s)?s:n.fallback.defaultValue({code:"defaultValue",base:i,value:s})}return i})),this.minLength&&(e.minItems=this.minLength),this.variadic){const r=Object.assign(e,{items:this.variadic.toJsonSchemaRecurse(n)});if(this.maxLength&&(r.maxItems=this.maxLength),this.postfix){const i=this.postfix.map(s=>s.toJsonSchemaRecurse(n));e=n.fallback.arrayPostfix({code:"arrayPostfix",base:r,elements:i})}}else e.items=!1,delete e.maxItems;return e}}const cl={},ll=t=>{if(!t.defaultables)return[];const e=[];let n="[";const r=t.prefixLength+t.defaultablesLength-1;for(let i=t.prefixLength;i<=r;i++){const[s,o]=t.defaultables[i-t.prefixLength];e.push(_i(i,s,o)),n+=`${i}: ${s.id} = ${be(o)}, `}return n+="]",cl[n]??=e},Qi={implementation:ol,Node:al},ul=t=>{const e=[];if(t.prefix)for(const n of t.prefix)e.push({kind:"prefix",node:n});if(t.defaultables)for(const[n,r]of t.defaultables)e.push({kind:"defaultables",node:n,default:r});if(t.optionals)for(const n of t.optionals)e.push({kind:"optionals",node:n});if(t.variadic&&e.push({kind:"variadic",node:t.variadic}),t.postfix)for(const n of t.postfix)e.push({kind:"postfix",node:n});return e},rr=t=>t.reduce((e,n)=>(n.kind==="variadic"?e.variadic=n.node:n.kind==="defaultables"?e.defaultables=N(e.defaultables,[[n.node,n.default]]):e[n.kind]=N(e[n.kind],n.node),e),{}),Xi="A postfix required element cannot follow an optional or defaultable element",dl="A postfix element requires a variadic element",Fe=t=>{const[e,...n]=t.l,[r,...i]=t.r;if(!e||!r)return t;const s=n.at(-1)?.kind==="postfix",o=i.at(-1)?.kind==="postfix",a=e.kind==="prefix"||r.kind==="prefix"?"prefix":e.kind==="postfix"||r.kind==="postfix"?"postfix":e.kind==="variadic"&&r.kind==="variadic"?"variadic":s||o?"prefix":e.kind==="defaultables"||r.kind==="defaultables"?"defaultables":"optionals";if(e.kind==="prefix"&&r.kind==="variadic"&&o){const h=Fe({...t,fixedVariants:[],r:i.map(m=>({...m,kind:"prefix"}))});h.disjoint.length===0&&t.fixedVariants.push(h)}else if(r.kind==="prefix"&&e.kind==="variadic"&&s){const h=Fe({...t,fixedVariants:[],l:n.map(m=>({...m,kind:"prefix"}))});h.disjoint.length===0&&t.fixedVariants.push(h)}const l=j(e.node,r.node,t.ctx);if(l instanceof g)if(a==="prefix"||a==="postfix")t.disjoint.push(...l.withPrefixKey(a==="prefix"?t.result.length:`-${n.length+1}`,ir(e)&&ir(r)?"required":"optional")),t.result=[...t.result,{kind:a,node:p.intrinsic.never.internal}];else return a==="optionals"||a==="defaultables"?t:Fe({...t,fixedVariants:[],l:n.map(h=>({...h,kind:"prefix"})),r:n.map(h=>({...h,kind:"prefix"}))});else a==="defaultables"?(e.kind==="defaultables"&&r.kind==="defaultables"&&e.default!==r.default&&d(Ti(e.default,r.default)),t.result=[...t.result,{kind:a,node:l,default:e.kind==="defaultables"?e.default:r.kind==="defaultables"?r.default:D(`Unexpected defaultable intersection from ${e.kind} and ${r.kind} elements.`)}]):t.result=[...t.result,{kind:a,node:l}];const c=t.l.length,u=t.r.length;return(e.kind!=="variadic"||c>=u&&(r.kind==="variadic"||u===1))&&(t.l=n),(r.kind!=="variadic"||u>=c&&(e.kind==="variadic"||c===1))&&(t.r=i),Fe(t)},ir=t=>t.kind==="prefix"||t.kind==="postfix",es=t=>e=>{if(e.props.length||e.index){const n=e.index?.map(i=>i[t])??[];for(const i of e.props)n.push(i[t]);e.undeclared&&n.push(`+ (undeclared): ${e.undeclared}`);const r=`{ ${n.join(", ")} }`;return e.sequence?`${r} & ${e.sequence.description}`:r}return e.sequence?.description??"{}"},hl=es("description"),pl=es("expression"),sr=(t,e,n)=>{const r=t.required?"required":"optional";if(!e.signature.allows(t.key))return null;const i=oe(t.value,e.value,n);return i instanceof g?r==="optional"?n.node("optional",{key:t.key,value:p.intrinsic.never.internal}):i.withPrefixKey(t.key,t.kind):null},fl=q({kind:"structure",hasAssociatedError:!1,normalize:t=>t,applyConfig:(t,e)=>!t.undeclared&&e.onUndeclaredKey!=="ignore"?{...t,undeclared:e.onUndeclaredKey}:t,keys:{required:{child:!0,parse:T("required"),reduceIo:(t,e,n)=>{e.required=N(e.required,n.map(r=>t==="in"?r.rawIn:r.rawOut))}},optional:{child:!0,parse:T("optional"),reduceIo:(t,e,n)=>{if(t==="in"){e.optional=n.map(r=>r.rawIn);return}for(const r of n)e[r.outProp.kind]=N(e[r.outProp.kind],r.outProp.rawOut)}},index:{child:!0,parse:T("index")},sequence:{child:!0,parse:T("sequence")},undeclared:{parse:t=>t==="ignore"?void 0:t,reduceIo:(t,e,n)=>{if(n==="reject"){e.undeclared="reject";return}t==="in"?delete e.undeclared:e.undeclared="reject"}}},defaults:{description:hl},intersections:{structure:(t,e,n)=>{const r={...t.inner},i={...e.inner},s=new g;if(t.undeclared){const l=t.keyof();for(const c of e.requiredKeys)l.allows(c)||s.add("presence",p.intrinsic.never.internal,e.propsByKey[c].value,{path:[c]});i.optional&&(i.optional=i.optional.filter(c=>l.allows(c.key))),i.index&&(i.index=i.index.flatMap(c=>{if(c.signature.extends(l))return c;const u=oe(l,c.signature,n.$);if(u instanceof g)return[];const h=rn(u,c.value,n.$);return h.required&&(i.required=ge(i.required,h.required)),h.optional&&(i.optional=ge(i.optional,h.optional)),h.index??[]}))}if(e.undeclared){const l=e.keyof();for(const c of t.requiredKeys)l.allows(c)||s.add("presence",t.propsByKey[c].value,p.intrinsic.never.internal,{path:[c]});r.optional&&(r.optional=r.optional.filter(c=>l.allows(c.key))),r.index&&(r.index=r.index.flatMap(c=>{if(c.signature.extends(l))return c;const u=oe(l,c.signature,n.$);if(u instanceof g)return[];const h=rn(u,c.value,n.$);return h.required&&(r.required=ge(r.required,h.required)),h.optional&&(r.optional=ge(r.optional,h.optional)),h.index??[]}))}const o={};(t.undeclared||e.undeclared)&&(o.undeclared=t.undeclared==="reject"||e.undeclared==="reject"?"reject":"delete");const a=bt({kind:"structure",baseInner:o,l:$t(r),r:$t(i),roots:[],ctx:n});return a instanceof g&&s.push(...a),s.length?s:a}},reduce:(t,e)=>{if(t.index){if(!(t.required||t.optional))return;let n=!1;const r=t.required??[],i=t.optional??[],s=[...i];for(const o of t.index){for(const a of r){const l=sr(a,o,e);if(l instanceof g)return l}for(const[a,l]of i.entries()){const c=sr(l,o,e);if(c instanceof g)return c;c!==null&&(s[a]=c,n=!0)}}if(n)return e.node("structure",{...t,optional:s},{prereduced:!0})}}});class ml extends Ke{impliedBasis=p.intrinsic.object.internal;impliedSiblings=this.children.flatMap(e=>e.impliedSiblings??[]);props=ge(this.required,this.optional);propsByKey=O(this.props,(e,n)=>[n.key,n]);propsByKeyReference=z(this.propsByKey);expression=pl(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(const{signature:n}of this.index)e=e.concat(n.branches);return this._keyof=this.$.node("union",e)}map(e){return this.$.node("structure",this.props.flatMap(e).reduce((n,r)=>{const i=this.propsByKey[r.key];if(U(r))return r.kind!=="required"&&r.kind!=="optional"?d(`Map result must have kind "required" or "optional" (was ${r.kind})`):(n[r.kind]=N(n[r.kind],r),n);const s=r.kind??i?.kind??"required",o=O(r,(a,l)=>a in An.implementation.keys?[a,l]:[]);return n[s]=N(n[s],this.$.node(s,o)),n},{}))}assertHasKeys(e){const n=e.filter(r=>!ct(r,this.keyof()));if(n.length)return d(or(this.expression,n))}get(e,...n){let r,i=!1;const s=$l(e);if((typeof s=="string"||typeof s=="symbol")&&this.propsByKey[s]&&(r=this.propsByKey[s].value,i=this.propsByKey[s].required),this.index)for(const a of this.index)ct(s,a.signature)&&(r=r?.and(a.value)??a.value);if(this.sequence&&ct(s,p.intrinsic.nonNegativeIntegerString))if(b(s,"root"))this.sequence.variadic&&(r=r?.and(this.sequence.element)??this.sequence.element);else{const a=Number.parseInt(s);if(a<this.sequence.prevariadic.length){const l=this.sequence.prevariadic[a].node;r=r?.and(l)??l,i||=a<this.sequence.prefixLength}else if(this.sequence.variadic){const l=this.$.node("union",this.sequence.variadicOrPostfix);r=r?.and(l)??l}}if(!r)return this.sequence?.variadic&&b(s,"root")&&s.extends(p.intrinsic.number)?d(wl(s.expression,this.sequence.expression)):d(or(this.expression,[s]));const o=r.get(...n);return i?o:o.or(p.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(){const{required:e,...n}=this.inner;return this.$.node("structure",{...n,optional:this.props.map(r=>r.hasKind("required")?this.$.node("optional",r.inner):r)})}require(){const{optional:e,...n}=this.inner;return this.$.node("structure",{...n,required:this.props.map(r=>r.hasKind("optional")?{key:r.key,value:r.value}:r)})}merge(e){const n=this.filterKeys("omit",[e.keyof()]);return e.required&&(n.required=N(n.required,e.required)),e.optional&&(n.optional=N(n.optional,e.optional)),e.index&&(n.index=N(n.index,e.index)),e.sequence&&(n.sequence=e.sequence),e.undeclared?n.undeclared=e.undeclared:delete n.undeclared,this.$.node("structure",n)}filterKeys(e,n){const r=gi(this.inner),i=s=>{const o=n.some(a=>ct(s,a));return e==="pick"?o:!o};return r.required&&(r.required=r.required.filter(s=>i(s.key))),r.optional&&(r.optional=r.optional.filter(s=>i(s.key))),r.index&&(r.index=r.index.filter(s=>i(s.signature))),r}traverseAllows=(e,n)=>this._traverse("Allows",e,n);traverseApply=(e,n)=>this._traverse("Apply",e,n);_traverse=(e,n,r)=>{const i=r?.currentErrorCount??0;for(let s=0;s<this.props.length;s++)if(e==="Allows"){if(!this.props[s].traverseAllows(n,r))return!1}else if(this.props[s].traverseApply(n,r),r.failFast&&r.currentErrorCount>i)return!1;if(this.sequence){if(e==="Allows"){if(!this.sequence.traverseAllows(n,r))return!1}else if(this.sequence.traverseApply(n,r),r.failFast&&r.currentErrorCount>i)return!1}if(this.index||this.undeclared==="reject"){const s=Object.keys(n);s.push(...Object.getOwnPropertySymbols(n));for(let o=0;o<s.length;o++){const a=s[o];if(this.index){for(const l of this.index)if(l.signature.traverseAllows(a,r)){if(e==="Allows"){if(!se(a,()=>l.value.traverseAllows(n[a],r),r))return!1}else if(se(a,()=>l.value.traverseApply(n[a],r),r),r.failFast&&r.currentErrorCount>i)return!1}}if(this.undeclared==="reject"&&!this.declaresKey(a)&&(e==="Allows"||(r.errorFromNodeContext({code:"predicate",expected:"removed",actual:"",relativePath:[a],meta:this.meta}),r.failFast)))return!1}}return this.structuralMorph&&r&&!r.hasError()&&r.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(n=>n.signature.allows(e))||this.sequence!==void 0&&p.intrinsic.nonNegativeIntegerString.allows(e);_compileDeclaresKey(e){const n=[];if(this.props.length&&n.push(`k in ${this.propsByKeyReference}`),this.index)for(const r of this.index)n.push(e.invoke(r.signature,{kind:"Allows",arg:"k"}));return this.sequence&&n.push("$ark.intrinsic.nonNegativeIntegerString.allows(k)"),n.join(" || ")||"false"}get structuralMorph(){return this.cacheGetter("structuralMorph",yl(this))}structuralMorphRef=this.structuralMorph&&z(this.structuralMorph);compile(e){e.traversalKind==="Apply"&&e.initializeErrorCount();for(const n of this.props)e.check(n),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(["),bl(e,this),e.line("])")))}compileExhaustiveEntry(e){if(e.const("k","keys[i]"),this.index)for(const n of this.index)e.if(`${e.invoke(n.signature,{arg:"k",kind:"Allows"})}`,()=>e.traverseKey("k","data[k]",n.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,n){switch(e.type){case"object":return this.reduceObjectJsonSchema(e,n);case"array":const r=this.sequence?.reduceJsonSchema(e,n)??e;return this.props.length||this.index?n.fallback.arrayObject({code:"arrayObject",base:r,object:this.reduceObjectJsonSchema({type:"object"},n)}):r;default:return L.throwInternalOperandError("structure",e)}}reduceObjectJsonSchema(e,n){if(this.props.length){e.properties={};for(const r of this.props){const i=r.value.toJsonSchemaRecurse(n);if(typeof r.key=="symbol"){n.fallback.symbolKey({code:"symbolKey",base:e,key:r.key,value:i,optional:r.optional});continue}if(r.hasDefault()){const s=typeof r.default=="function"?r.default():r.default;i.default=p.intrinsic.jsonData.allows(s)?s:n.fallback.defaultValue({code:"defaultValue",base:i,value:s})}e.properties[r.key]=i}this.requiredKeys.length&&e.properties&&(e.required=this.requiredKeys.filter(r=>typeof r=="string"&&r in e.properties))}if(this.index)for(const r of this.index){const i=r.value.toJsonSchemaRecurse(n);if(r.signature.equals(p.intrinsic.string)){e.additionalProperties=i;continue}for(const s of r.signature.branches){if(!s.extends(p.intrinsic.string)){e=n.fallback.symbolKey({code:"symbolKey",base:e,key:null,value:i,optional:!1});continue}let o={type:"string"};if(s.hasKind("morph")&&(o=n.fallback.morph({code:"morph",base:s.rawIn.toJsonSchemaRecurse(n),out:s.rawOut.toJsonSchemaRecurse(n)})),!s.hasKind("intersection"))return D(`Unexpected index branch kind ${s.kind}.`);const{pattern:a}=s.inner;if(a){const l=Object.assign(o,{pattern:a[0].rule});for(let c=1;c<a.length;c++)o=n.fallback.patternIntersection({code:"patternIntersection",base:l,pattern:a[c].rule});e.patternProperties??={},e.patternProperties[l.pattern]=i}}}return this.undeclared&&!e.additionalProperties&&(e.additionalProperties=!1),e}}const jt={},gl=t=>{let e="";for(let n=0;n<t.defaultable.length;n++)e+=t.defaultable[n].defaultValueMorphRef;if(t.sequence?.defaultValueMorphsReference&&(e+=t.sequence?.defaultValueMorphsReference),t.undeclared==="delete"){if(e+="delete !(",t.required)for(const n of t.required)e+=n.compiledKey+" | ";if(t.optional)for(const n of t.optional)e+=n.compiledKey+" | ";if(t.index)for(const n of t.index)e+=n.signature.id+" | ";if(t.sequence)if(t.sequence.maxLength===null)e+=$.nonNegativeIntegerString.id;else for(let n=0;n<t.sequence.tuple.length;n++)e+=n+" | ";e+=")"}return e},yl=t=>{const e=gl(t);if(!e)return;if(jt[e])return jt[e];const n=(r,i)=>{for(let s=0;s<t.defaultable.length;s++)t.defaultable[s].key in r||t.defaultable[s].defaultValueMorph(r,i);if(t.sequence?.defaultables)for(let s=r.length-t.sequence.prefixLength;s<t.sequence.defaultables.length;s++)t.sequence.defaultValueMorphs[s](r,i);if(t.undeclared==="delete")for(const s in r)t.declaresKey(s)||delete r[s];return r};return jt[e]=n},bl=(t,e)=>{const r=`(data${e.defaultable.some(i=>i.defaultValueMorph.length===2)||e.sequence?.defaultValueMorphs.some(i=>i.length===2)?", ctx":""})`;return t.block(`${r} => `,i=>{for(let s=0;s<e.defaultable.length;s++){const{serializedKey:o,defaultValueMorphRef:a}=e.defaultable[s];i.if(`!(${o} in data)`,l=>l.line(`${a}${r}`))}return e.sequence?.defaultables&&i.for(`i < ${e.sequence.defaultables.length}`,s=>s.set("data[i]",5),`data.length - ${e.sequence.prefixLength}`),e.undeclared==="delete"&&i.forIn("data",s=>s.if(`!(${e._compileDeclaresKey(s)})`,o=>o.line("delete data[k]"))),i.return("data")})},ts={implementation:fl,Node:ml},$l=t=>(b(t,"root")&&t.hasKind("unit")&&(t=t.unit),typeof t=="number"&&(t=`${t}`),t),wl=(t,e)=>`${t} is not allowed as an array index on ${e}. Use the 'nonNegativeIntegerString' keyword instead.`,rn=(t,e,n)=>{const[r,i]=yo(t.branches,o=>o.hasKind("unit"));if(!r.length)return{index:n.node("index",{signature:t,value:e})};const s={};for(const o of r){const a=n.node("required",{key:o.unit,value:e});s[a.kind]=N(s[a.kind],a)}return i.length&&(s.index=n.node("index",{signature:i,value:e})),s},vl=t=>b(t,"root")?t.expression:S(t),or=(t,e)=>`Key${e.length===1?"":"s"} ${e.map(vl).join(", ")} ${e.length===1?"does":"do"} not exist on ${t}`,Ct={...lc,alias:Sn.implementation,domain:On.implementation,unit:Hi.implementation,proto:vt.implementation,union:Wi.implementation,morph:Vi.implementation,intersection:Ji.implementation,divisor:Ni.implementation,pattern:ji.implementation,predicate:Si.implementation,required:Yi.implementation,optional:An.implementation,index:Zi.implementation,sequence:Qi.implementation,structure:ts.implementation};p.defaultConfig=Ro(Object.assign(O(Ct,(t,e)=>[t,e.defaults]),{jitless:jo(),clone:Do,onUndeclaredKey:"ignore",exactOptionalPropertyTypes:!0,numberAllowsNaN:!1,dateAllowsInvalid:!1,onFail:null,keywords:{},toJsonSchema:L.defaultConfig}));p.resolvedConfig=Qt(p.defaultConfig,p.config);const xl={...uc,alias:Sn.Node,domain:On.Node,unit:Hi.Node,proto:vt.Node,union:Wi.Node,morph:Vi.Node,intersection:Ji.Node,divisor:Ni.Node,pattern:ji.Node,predicate:Si.Node,required:Yi.Node,optional:An.Node,index:Zi.Node,sequence:Qi.Node,structure:ts.Node};class sn extends Io{get[ie](){return"module"}}const ns=(t,e)=>new sn(O(t,(n,r)=>[n,b(r,"module")?ns(r,e):e.bindReference(r)])),kl=t=>F(t)?t:"branches"in t&&F(t.branches)?t.branches:void 0,Al=(t,e)=>d(`Node of kind ${e} is not valid as a ${t} definition`),ar=t=>`#${t} duplicates public alias ${t}`,Ft={};p.ambient??={};let cr;const rs="function $",Il=t=>is(t,ss(t)),is=(t,e)=>{const n=e.write(rs,4),r=e.compile()();for(const i of t)i.precompilation||(i.traverseAllows=r[`${i.id}Allows`].bind(r),i.isRoot()&&!i.allowsRequiresContext&&(i.allows=i.traverseAllows),i.traverseApply=r[`${i.id}Apply`].bind(r),r[`${i.id}Optimistic`]&&(i.traverseOptimistic=r[`${i.id}Optimistic`].bind(r)),i.precompilation=n)},ss=t=>(new pi).return(t.reduce((e,n)=>{const r=new Lt({kind:"Allows"}).indent();n.compile(r);const i=r.write(`${n.id}Allows`),s=new Lt({kind:"Apply"}).indent();n.compile(s);const o=s.write(`${n.id}Apply`),a=`${e}${i},\n${o},\n`;if(!n.hasKind("union"))return a;const l=new Lt({kind:"Allows",optimistic:!0}).indent();n.compile(l);const c=l.write(`${n.id}Optimistic`);return`${a}${c},\n`},`{\n`)+"}");class os{config;resolvedConfig;name;get[ie](){return"scope"}referencesById={};references=[];resolutions={};exportedNames=[];aliases={};resolved=!1;nodesByHash={};intrinsic;constructor(e,n){this.config=Qt(p.config,n),this.resolvedConfig=Qt(p.resolvedConfig,n),this.name=this.resolvedConfig.name??`anonymousScope${Object.keys(Ft).length}`,this.name in Ft&&d(`A Scope already named ${this.name} already exists`),Ft[this.name]=this;const r=Object.entries(e).map(i=>this.preparseOwnAliasEntry(...i));for(const[i,s]of r){let o=i;if(i[0]==="#"?(o=i.slice(1),o in this.aliases&&d(ar(o)),this.aliases[o]=s):(o in this.aliases&&d(ar(i)),this.aliases[o]=s,this.exportedNames.push(o)),!b(s,"module")&&!b(s,"generic")&&!At(s)){const a=this.preparseOwnDefinitionFormat(s,{alias:o});this.resolutions[o]=b(a,"root")?this.bindReference(a):this.createParseContext(a).id}}cr??=this.node("union",{branches:["string","number","object","bigint","symbol",{unit:!0},{unit:!1},{unit:void 0},{unit:null}]},{prereduced:!0}),this.nodesByHash[cr.hash]=this.node("intersection",{},{prereduced:!0}),this.intrinsic=p.intrinsic?O(p.intrinsic,(i,s)=>i.startsWith("json")?[]:[i,this.bindReference(s)]):{}}cacheGetter(e,n){return Object.defineProperty(this,e,{value:n}),n}get internal(){return this}_json;get json(){return this._json||this.export(),this._json}defineSchema(e){return e}generic=(...e)=>{const n=this;return(r,i)=>new wt(e,i?new Ii(r):r,n,n,i??null)};units=(e,n)=>{const r=[];for(const s of e)r.includes(s)||r.push(s);const i=r.map(s=>this.node("unit",{unit:s},n));return this.node("union",i,{...n,prereduced:!0})};lazyResolutions=[];lazilyResolve(e,n){const r=this.node("alias",{reference:n??"synthetic",resolve:e},{prereduced:!0});return this.resolved||this.lazyResolutions.push(r),r}schema=(e,n)=>this.finalize(this.parseSchema(e,n));parseSchema=(e,n)=>this.node(dt(e),e,n);preparseNode(e,n,r){let i=typeof e=="string"?e:dt(n,e);if(U(n)&&n.kind===i)return n;if(i==="alias"&&!r?.prereduced){const{reference:a}=Sn.implementation.normalize(n,this);if(a.startsWith("$")){const l=this.resolveRoot(a.slice(1));n=l,i=l.kind}}else if(i==="union"&&$e(n,"object")){const a=kl(n);a?.length===1&&(n=a[0],i=dt(n))}if(U(n)&&n.kind===i)return n;const o=Ct[i].normalize?.(n,this)??n;return U(o)?o.kind===i?o:Al(i,o.kind):{...r,$:this,kind:i,def:o,prefix:r.alias??i}}bindReference(e){let n;return U(e)?n=e.$===this?e:new e.constructor(e.attachments,this):n=e.$===this?e:new wt(e.params,e.bodyDef,e.$,this,e.hkt),this.resolved||Object.assign(this.referencesById,n.referencesById),n}resolveRoot(e){return this.maybeResolveRoot(e)??d(us(e))}maybeResolveRoot(e){const n=this.maybeResolve(e);if(!b(n,"generic"))return n}maybeResolveSubalias(e){return on(this.aliases,e)??on(this.ambient,e)}get ambient(){return p.ambient}maybeResolve(e){const n=this.resolutions[e];if(n){if(typeof n!="string")return this.bindReference(n);const i=W[n];if(b(i,"root"))return this.resolutions[e]=i;if(b(i,"context")){if(i.phase==="resolving")return this.node("alias",{reference:`$${e}`},{prereduced:!0});if(i.phase==="resolved")return D(`Unexpected resolved context for was uncached by its scope: ${S(i)}`);i.phase="resolving";const s=this.bindReference(this.parseOwnDefinitionFormat(i.def,i));return i.phase="resolved",W[s.id]=s,W[i.id]=s,this.resolutions[e]=s}return D(`Unexpected nodesById entry for ${n}: ${S(i)}`)}let r=this.aliases[e]??this.ambient?.[e];return r?(r=this.normalizeRootScopeValue(r),b(r,"generic")?this.resolutions[e]=this.bindReference(r):b(r,"module")?(r.root||d(ds(e)),this.resolutions[e]=this.bindReference(r.root)):this.resolutions[e]=this.parse(r,{alias:e})):this.maybeResolveSubalias(e)}createParseContext(e){const n=e.id??Fi(e.prefix);return W[n]=Object.assign(e,{[ie]:"context",$:this,id:n,phase:"unresolved"})}traversal(e){return new Ne(e,this.resolvedConfig)}import(...e){return new sn(O(this.export(...e),(n,r)=>[`#${n}`,r]))}precompilation;_exportedResolutions;_exports;export(...e){if(!this._exports){this._exports={};for(const r of this.exportedNames){const i=this.aliases[r];this._exports[r]=b(i,"module")?ns(i,this):lr(this.maybeResolve(r))}for(const r of this.lazyResolutions)r.resolution;if(this._exportedResolutions=ls(this,this._exports),this._json=cs(this._exportedResolutions),Object.assign(this.resolutions,this._exportedResolutions),this.references=Object.values(this.referencesById),!this.resolvedConfig.jitless){const r=ss(this.references);this.precompilation=r.write(rs,4),is(this.references,r)}this.resolved=!0}const n=e.length?e:this.exportedNames;return new sn(O(n,(r,i)=>[i,this._exports[i]]))}resolve(e){return this.export()[e]}node=(e,n,r={})=>{const i=this.preparseNode(e,n,r);if(U(i))return this.bindReference(i);const s=this.createParseContext(i),o=Ui(s),a=this.bindReference(o);return W[s.id]=a};parse=(e,n={})=>this.finalize(this.parseDefinition(e,n));parseDefinition(e,n={}){if(b(e,"root"))return this.bindReference(e);const r=this.preparseOwnDefinitionFormat(e,n);if(b(r,"root"))return this.bindReference(r);const i=this.createParseContext(r);W[i.id]=i;let s=this.bindReference(this.parseOwnDefinitionFormat(e,i));return s.isCyclic&&(s=mc(s,i.id)),W[i.id]=s,s}finalize(e){return lr(e),!e.precompilation&&!this.resolvedConfig.jitless&&Il(e.references),e}}class as extends os{parseOwnDefinitionFormat(e,n){return Ui(n)}preparseOwnDefinitionFormat(e,n){return this.preparseNode(dt(e),e,n)}preparseOwnAliasEntry(e,n){return[e,n]}normalizeRootScopeValue(e){return e}}const lr=t=>{const e=t.references.filter(n=>n.hasKind("alias"));for(const n of e){Object.assign(n.referencesById,n.resolution.referencesById);for(const r of t.references)n.id in r.referencesById&&Object.assign(r.referencesById,n.referencesById)}return t},cs=t=>O(t,(e,n)=>[e,b(n,"root")||b(n,"generic")?n.json:b(n,"module")?cs(n):D(`Unexpected resolution ${S(n)}`)]),on=(t,e)=>{const n=e.indexOf(".");if(n===-1)return;const r=e.slice(0,n),i=t[r];if(i===void 0)return;if(!b(i,"module"))return d(Sl(r));const s=e.slice(n+1),o=i[s];if(o===void 0)return on(i,s);if(b(o,"root")||b(o,"generic"))return o;if(b(o,"module"))return o.root??d(ds(e));D(`Unexpected resolution for alias '${e}': ${S(o)}`)},Rn=(t,e)=>new as(t,e),rt=new as({}),ls=(t,e)=>{const n={};for(const r in e){const i=e[r];if(b(i,"module")){const s=ls(t,i),o=O(s,(a,l)=>[`${r}.${a}`,l]);Object.assign(n,o)}else b(i,"root")||b(i,"generic")?n[r]=i:D(`Unexpected scope resolution ${S(i)}`)}return n},us=t=>`'${t}' is unresolvable`,Sl=t=>`'${t}' must reference a module to be accessed using dot syntax`,ds=t=>`Reference to submodule '${t}' must specify an alias`;rt.export();const R=rt.schema,Cn=rt.node;rt.defineSchema;const ae=rt.generic,hs="^(?:0|[1-9]\\d*)$",Nl=new RegExp(hs);z(Nl);const ps=Rn({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:Array,Date:Date},{prereducedAliases:!0}).export();p.intrinsic={...ps};const fs=Rn({integer:{domain:"number",divisor:1},lengthBoundable:["string",Array],key:["string","symbol"],nonNegativeIntegerString:{domain:"string",pattern:hs}},{prereducedAliases:!0}).export();Object.assign(p.intrinsic,fs);const Ol=Rn({jsonPrimitive:["string","number",{unit:!0},{unit:!1},{unit:null}],jsonObject:{domain:"object",index:{signature:"string",value:"$jsonData"}},jsonData:["$jsonPrimitive","$jsonObject"]},{prereducedAliases:!0}).export(),$={...ps,...fs,...Ol,emptyStructure:Cn("structure",{},{prereduced:!0})};p.intrinsic={...$};const Rl=t=>typeof t=="string"&&t[0]==="d"&&(t[1]==="'"||t[1]==='"')&&t.at(-1)===t[1],ur=t=>t.toString()!=="Invalid Date",Cl=t=>t.slice(2,-1),ms=t=>`'${t}' could not be parsed by the Date constructor`,Ml=(t,e)=>Pl(t,e),Pl=(t,e)=>{const n=new Date(t);if(ur(n))return n;const r=na(t);if(r!==void 0){const i=new Date(r);if(ur(i))return i}return e?d(e===!0?ms(t):e):void 0},dr=(t,e)=>{const n=t.scanner.shiftUntilEscapable(Kl[ys[e]]);if(t.scanner.lookahead==="")return t.error(Ll(n,e));if(t.scanner.shift(),e==="/"){try{new RegExp(n)}catch(r){d(String(r))}t.root=t.ctx.$.node("intersection",{domain:"string",pattern:n},{prereduced:!0})}else if(te(e,gs))t.root=t.ctx.$.node("unit",{unit:n});else{const r=Ml(n,ms(n));t.root=t.ctx.$.node("unit",{meta:n,unit:r})}},gs={"'":1,'"':1},ql={"/":1,"'":1,'"':1},El={"d'":"'",'d"':'"',"'":"'",'"':'"'},ys={...El,"/":"/"},Kl={"'":t=>t.lookahead==="'",'"':t=>t.lookahead==='"',"/":t=>t.lookahead==="/"},Dl={'"':"double-quote","'":"single-quote","/":"forward slash"},Ll=(t,e)=>`${e}${t} requires a closing ${Dl[ys[e]]}`,Bl=t=>`Private type references should not include '#'. Use '${t}' instead.`,bs="Optional definitions like 'string?' are only valid as properties in an object or tuple",$s="Defaultable definitions like 'number = 0' are only valid as properties in an object or tuple",Le={"<":1,">":1,"=":1,"|":1,"&":1,")":1,"[":1,"%":1,",":1,":":1,"?":1,"#":1,...It},jl=(t,e)=>t===">"?e[0]==="="?e[1]==="=":e.trimStart()===""||te(e.trimStart()[0],Le):t==="="?e[0]!=="=":t===","||t==="?",Fl=(t,e,n)=>ws(t,e,n,[]),ws=(t,e,n,r)=>{const i=n.parseUntilFinalizer();return r.push(i.root),i.finalizer===">"?r.length!==e.params.length?n.error(vs(t,e.names,r.map(s=>s.expression))):r:i.finalizer===","?ws(t,e,n,r):i.error(di(">"))},vs=(t,e,n)=>`${t}<${e.join(", ")}> requires exactly ${e.length} args (got ${n.length}${n.length===0?"":`: ${n.join(", ")}`})`,hr=t=>{const e=t.scanner.shiftUntilLookahead(Le);e==="keyof"?t.addPrefix("keyof"):t.root=zl(t,e)},Ul=(t,e,n)=>{if(n.scanner.shiftUntilNonWhitespace(),n.scanner.shift()!=="<")return n.error(vs(t,e.names,[]));const i=Fl(t,e,n);return e(...i)},zl=(t,e)=>Tl(t,e)??_l(t,e)??t.error(e===""?t.scanner.lookahead==="#"?Bl(t.shiftedByOne().scanner.shiftUntilLookahead(Le)):xs(t):us(e)),Tl=(t,e)=>{if(t.ctx.args?.[e]){const r=t.ctx.args[e];return typeof r!="string"?r:t.ctx.$.node("alias",{reference:r},{prereduced:!0})}const n=t.ctx.$.maybeResolve(e);if(b(n,"root"))return n;if(n!==void 0)return b(n,"generic")?Ul(e,n,t):d(`Unexpected resolution ${S(n)}`)},_l=(t,e)=>{const n=ra(e);if(n!==void 0)return t.ctx.$.node("unit",{unit:n});const r=sa(e);if(r!==void 0)return t.ctx.$.node("unit",{unit:r})},xs=t=>{const e=t.previousOperator();return e?ks(e,t.scanner.unscanned):Jl(t.scanner.unscanned)},ks=(t,e="")=>`Token '${t}' requires a right operand${e?` before '${e}'`:""}`,Jl=t=>`Expected an expression${t?` before '${t}'`:""}`,As=t=>t.scanner.lookahead===""?t.error(xs(t)):t.scanner.lookahead==="("?t.shiftedByOne().reduceGroupOpen():t.scanner.lookaheadIsIn(ql)?dr(t,t.scanner.shift()):t.scanner.lookaheadIsIn(It)?As(t.shiftedByOne()):t.scanner.lookahead==="d"&&t.scanner.nextLookahead in gs?dr(t,`${t.scanner.shift()}${t.scanner.shift()}`):hr(t),Vl={">":!0,">=":!0},Gl={"<":!0,"<=":!0},xt={"<":">",">":"<","<=":">=",">=":"<=","==":"=="},Wl=(t,e)=>`Left bounds are only valid when paired with right bounds (try ...${e}${t})`,Is=t=>`Left-bounded expressions must specify their limits using < or <= (was ${t})`,Hl=(t,e,n,r)=>`An expression may have at most one left bound (parsed ${t}${xt[e]}, ${n}${xt[r]})`,Zl=(t,e)=>{const n=Ql(t,e);if(t.root.hasKind("unit")){if(typeof t.root.unit=="number"){t.reduceLeftBound(t.root.unit,n),t.unsetRoot();return}if(t.root.unit instanceof Date){const r=`d'${t.root.description??t.root.unit.toISOString()}'`;t.unsetRoot(),t.reduceLeftBound(r,n);return}}return eu(t,n)},Yl={"<":1,">":1,"=":1},Ql=(t,e)=>t.scanner.lookaheadIs("=")?`${e}${t.scanner.shift()}`:e,pr=(t,e,n,r)=>n.extends(p.intrinsic.number)?typeof e!="number"?d(an(t,e,r)):t==="=="?["min","max"]:t[0]===">"?["min"]:["max"]:n.extends(p.intrinsic.lengthBoundable)?typeof e!="number"?d(an(t,e,r)):t==="=="?["exactLength"]:t[0]===">"?["minLength"]:["maxLength"]:n.extends(p.intrinsic.Date)?t==="=="?["after","before"]:t[0]===">"?["after"]:["before"]:d(Wa(n.expression)),Xl=t=>({rule:Rl(t.limit)?Cl(t.limit):t.limit,exclusive:t.comparator.length===1}),eu=(t,e)=>{const n=t.unsetRoot(),r=t.scanner.location;t.parseOperand();const i=t.unsetRoot(),s=t.scanner.sliceChars(r,t.scanner.location);if(t.root=n,!i.hasKind("unit")||typeof i.unit!="number"&&!(i.unit instanceof Date))return t.error(an(e,s,"right"));const o=i.unit,a=e.length===1,l=pr(e,typeof o=="number"?o:s,n,"right");for(const u of l)t.constrainRoot(u,e==="=="?{rule:o}:{rule:o,exclusive:a});if(!t.branches.leftBound)return;if(!te(e,Gl))return t.error(Is(e));const c=pr(t.branches.leftBound.comparator,t.branches.leftBound.limit,n,"left");t.constrainRoot(c[0],Xl(t.branches.leftBound)),t.branches.leftBound=null},an=(t,e,n)=>`Comparator ${n==="left"?xt[t]:t} must be ${n==="left"?"preceded":"followed"} by a corresponding literal (was ${e})`,tu=t=>{t.scanner.shiftUntilNonWhitespace();const e=t.scanner.shiftUntilLookahead(Le);t.root=t.root.brand(e)},nu=t=>{t.scanner.shiftUntilNonWhitespace();const e=t.scanner.shiftUntilLookahead(Le),n=ia(e,{errorOnFail:fr(e)});n===0&&t.error(fr(0)),t.root=t.root.constrain("divisor",n)},fr=t=>`% operator must be followed by a non-zero integer literal (was ${t})`,Ss=t=>{const e=t.scanner.shift();return e===""?t.finalize(""):e==="["?t.scanner.shift()==="]"?t.setRoot(t.root.array()):t.error(ru):e==="|"?t.scanner.lookahead===">"?t.shiftedByOne().pushRootToBranch("|>"):t.pushRootToBranch(e):e==="&"?t.pushRootToBranch(e):e===")"?t.finalizeGroup():jl(e,t.scanner.unscanned)?t.finalize(e):te(e,Yl)?Zl(t,e):e==="%"?nu(t):e==="#"?tu(t):e in It?Ss(t):t.error(Mn(e))},Mn=(t,e="")=>`'${t}' is not allowed here${e&&` (should be ${e})`}`,ru="Missing expected ']'",iu=t=>{const e=t.unsetRoot();t.parseOperand();const n=t.unsetRoot();if(!n.hasKind("unit"))return t.error(su(n.expression));const r=n.unit instanceof Date?()=>new Date(n.unit):n.unit;return[e,"=",r]},su=t=>`Default value '${t}' must be a literal value`,mr=(t,e)=>{const n=e.$.maybeResolveRoot(t);if(n)return n;if(t.endsWith("[]")){const s=e.$.maybeResolveRoot(t.slice(0,-2));if(s)return s.array()}const r=new Mt(new ui(t),e),i=ou(r);return r.finalizer===">"&&d(Mn(">")),i},ou=t=>{t.parseOperand();let e=Pn(t).root;return e?(t.finalizer==="="?e=iu(t):t.finalizer==="?"&&(e=[e,"?"]),t.scanner.shiftUntilNonWhitespace(),t.scanner.lookahead&&d(Mn(t.scanner.lookahead)),e):D(`Root was unexpectedly unset after parsing string '${t.scanner.scanned}'`)},Pn=t=>{for(;t.finalizer===void 0;)au(t);return t},au=t=>t.hasRoot()?t.parseOperator():t.parseOperand();class Mt{root;branches={prefixes:[],leftBound:null,intersection:null,union:null,pipe:null};finalizer;groups=[];scanner;ctx;constructor(e,n){this.scanner=e,this.ctx=n}error(e){return d(e)}hasRoot(){return this.root!==void 0}setRoot(e){this.root=e}unsetRoot(){const e=this.root;return this.root=void 0,e}constrainRoot(...e){this.root=this.root.constrain(e[0],e[1])}finalize(e){if(this.groups.length)return this.error(di(")"));this.finalizeBranches(),this.finalizer=e}reduceLeftBound(e,n){const r=xt[n];if(!te(r,Vl))return this.error(Is(n));if(this.branches.leftBound)return this.error(Hl(this.branches.leftBound.limit,this.branches.leftBound.comparator,e,r));this.branches.leftBound={comparator:r,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();const e=this.groups.pop();if(!e)return this.error(pa(")",this.scanner.unscanned));this.branches=e}addPrefix(e){this.branches.prefixes.push(e)}applyPrefixes(){for(;this.branches.prefixes.length;){const e=this.branches.prefixes.pop();this.root=e==="keyof"?this.root.keyof():D(`Unexpected prefix '${e}'`)}}pushRootToBranch(e){this.assertRangeUnset(),this.applyPrefixes();const n=this.root;this.root=void 0,this.branches.intersection=this.branches.intersection?.rawAnd(n)??n,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 Pn(new Mt(this.scanner,this.ctx))}parseOperator(){return Ss(this)}parseOperand(){return As(this)}assertRangeUnset(){if(this.branches.leftBound)return this.error(Wl(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.at(-1)??(this.branches.intersection?"&":this.branches.union?"|":this.branches.pipe?"|>":void 0)}shiftedByOne(){return this.scanner.shift(),this}}const cu="An empty string is not a valid generic parameter name",cn=(t,e,n)=>{t.shiftUntilNonWhitespace();const r=t.shiftUntilLookahead(Le);return r===""?t.lookahead===""&&e.length?e:d(cu):(t.shiftUntilNonWhitespace(),lu(t,r,e,n))},gr="extends ",lu=(t,e,n,r)=>{if(t.shiftUntilNonWhitespace(),t.unscanned.startsWith(gr))t.jumpForward(gr.length);else return t.lookahead===","&&t.shift(),n.push(e),cn(t,n,r);const i=Pn(new Mt(t,r));return n.push([e,i.root]),cn(t,n,r)};class uu extends pe{constructor(e){const n={$:e,raw:e.fn};super((...r)=>{const i=r.indexOf(":"),s=i===-1?r.length-1:i-1,o=r.slice(0,s+1),a=e.parse(o).assertHasKind("intersection");let l=e.intrinsic.unknown;if(i!==-1){if(i!==r.length-2)return d(hu);l=e.parse(r[i+1])}return c=>new du(c,a,l)},{attach:n})}}class du extends pe{raw;params;returns;expression;constructor(e,n,r){const i=`typed ${e.name}`,s={[i]:(...a)=>{const l=n.assert(a),c=e(...l);return r.assert(c)}}[i];super(s),this.raw=e,this.params=n,this.returns=r;let o=n.expression;o[0]==="["&&o.at(-1)==="]"?o=o.slice(1,-1):o.endsWith("[]")&&(o=`...${o}`),this.expression=`(${o}) => ${r?.expression??"unknown"}`}}const hu=`":" must be followed by exactly one return type e.g:\nfn("string", ":", "number")(s => s.length)`;class pu extends pe{$;constructor(e){super((...n)=>new lt(e)(...n),{bind:e}),this.$=e}in(e){return new lt(this.$,e===void 0?void 0:this.$.parse(e))}at(e,n){return new lt(this.$).at(e,n)}case(e,n){return new lt(this.$).case(e,n)}}class lt extends pe{$;in;key;branches=[];constructor(e,n){super(r=>this.caseEntries(Object.entries(r).map(([i,s])=>i==="default"?[i,s]:[this.$.parse(i),s]))),this.$=e,this.in=n}at(e,n){return this.key&&d(mu),this.branches.length&&d(fu),this.key=e,n?this.match(n):this}case(e,n){return this.caseEntry(this.$.parse(e),n)}caseEntry(e,n){const i=(this.key?this.$.parse({[this.key]:e}):e).pipe(n);return this.branches.push(i),this}match(e){return this(e)}strings(e){return this.caseEntries(Object.entries(e).map(([n,r])=>n==="default"?[n,r]:[this.$.node("unit",{unit:n}),r]))}caseEntries(e){for(let n=0;n<e.length;n++){const[r,i]=e[n];if(r==="default")return n!==e.length-1&&d("default may only be specified as the last key of a switch definition"),this.default(i);if(typeof i!="function")return d(`Value for case "${r}" must be a function (was ${Q(i)})`);this.caseEntry(r,i)}return this}default(e){typeof e=="function"&&this.case($.unknown,e);const n={branches:this.branches,ordered:!0};(e==="never"||e==="assert")&&(n.meta={onFail:yr});const r=this.$.node("union",n);if(!this.in)return this.$.finalize(r);let i=this.in.pipe(r);return(e==="never"||e==="assert")&&(i=i.configureReferences({onFail:yr},"self")),this.$.finalize(i)}}const yr=t=>t.throw(),fu="A key matcher must be specified before the first case i.e. match.at('foo') or match.in<object>().at('bar')",mu="At most one key matcher may be specified per expression",Ns=(t,e)=>{if(F(t)){if(t[1]==="=")return[e.$.parseOwnDefinitionFormat(t[0],e),"=",t[2]];if(t[1]==="?")return[e.$.parseOwnDefinitionFormat(t[0],e),"?"]}return Es(t,e)},gu="Only required keys may make their values optional, e.g. { [mySymbol]: ['number', '?'] }",yu="Only required keys may specify default values, e.g. { value: 'number = 0' }",bu=(t,e)=>{let n;const r={},i=ft(t);for(const[o,a]of i){const l=vu(o);if(l.kind==="spread"){if(!Ze(r))return d(wu);const y=e.$.parseOwnDefinitionFormat(a,e);if(y.equals($.object))continue;if(!y.hasKind("intersection")||!y.basis?.equals($.object))return d(xu(y.expression));n=y.structure;continue}if(l.kind==="undeclared"){a!=="reject"&&a!=="delete"&&a!=="ignore"&&d($u(a)),r.undeclared=a;continue}const c=Ns(a,e),u=l;if(l.kind==="required"){F(c)?Ut(r,"optional",c[1]==="="?{key:l.normalized,value:c[0],default:c[2]}:{key:l.normalized,value:c[0]},e):Ut(r,"required",{key:l.normalized,value:c},e);continue}if(F(c)&&(c[1]==="?"&&d(gu),c[1]==="="&&d(yu)),l.kind==="optional"){Ut(r,"optional",{key:l.normalized,value:c},e);continue}const h=e.$.parseOwnDefinitionFormat(u.normalized,e),m=rn(h,c,e.$);m.index&&(r.index=N(r.index,m.index)),m.required&&(r.required=N(r.required,m.required))}const s=e.$.node("structure",r);return e.$.parseSchema({domain:"object",structure:n?.merge(s)??s})},Ut=(t,e,n,r)=>{t[e]=N(t[e],r.$.node(e,n))},$u=t=>`Value of '+' key must be 'reject', 'delete', or 'ignore' (was ${S(t)})`,wu="Spread operator may only be used as the first key in an object",vu=t=>typeof t=="symbol"?{kind:"required",normalized:t}:t.at(-1)==="?"?t.at(-2)===ze?{kind:"required",normalized:`${t.slice(0,-2)}?`}:{kind:"optional",normalized:t.slice(0,-1)}:t[0]==="["&&t.at(-1)==="]"?{kind:"index",normalized:t.slice(1,-1)}:t[0]===ze&&t[1]==="["&&t.at(-1)==="]"?{kind:"required",normalized:t.slice(1)}:t==="..."?{kind:"spread"}:t==="+"?{kind:"undeclared"}:{kind:"required",normalized:t==="\\..."?"...":t==="\\+"?"+":t},xu=t=>`Spread operand must resolve to an object literal type (was ${t})`,ku=(t,e)=>qu(t)?Ms[t[0]](t,e):Mu(t)?Cs[t[1]](t,e):null,Au=(t,e)=>e.$.parseOwnDefinitionFormat(t[1],e).keyof(),zt=(t,e)=>{if(t[2]===void 0)return d(ks(t[1],""));const n=e.$.parseOwnDefinitionFormat(t[0],e),r=e.$.parseOwnDefinitionFormat(t[2],e);if(t[1]==="|")return e.$.node("union",{branches:[n,r]});const i=t[1]==="&"?oe(n,r,e.$):en(n,r,e.$);return i instanceof g?i.throw():i},Iu=(t,e)=>e.$.parseOwnDefinitionFormat(t[0],e).array(),Su=(t,e)=>typeof t[2]!="function"?d(Os("=>",t[2])):e.$.parseOwnDefinitionFormat(t[0],e).pipe(t[2]),Os=(t,e)=>`${t===":"?"Narrow":"Morph"} expression requires a function following '${t}' (was ${typeof e})`,Nu=(t,e)=>typeof t[2]!="function"?d(Os(":",t[2])):e.$.parseOwnDefinitionFormat(t[0],e).constrain("predicate",t[2]),Ou=(t,e)=>e.$.parseOwnDefinitionFormat(t[0],e).configure(t[2],t[3]),Rs=t=>t,Ru=Rs({"[]":Iu,"?":()=>d(bs)}),Cu=Rs({"|":zt,"&":zt,":":Nu,"=>":Su,"|>":zt,"@":Ou,"=":()=>d($s)}),Cs={...Ru,...Cu},Mu=t=>Cs[t[1]]!==void 0,Pu=t=>t,Ms=Pu({keyof:Au,instanceof:(t,e)=>{if(typeof t[1]!="function")return d(br(Gt(t[1])));const n=t.slice(1).map(r=>typeof r=="function"?e.$.node("proto",{proto:r}):d(br(Gt(r))));return n.length===1?n[0]:e.$.node("union",{branches:n})},"===":(t,e)=>e.$.units(t.slice(1))}),qu=t=>Ms[t[0]]!==void 0,br=t=>`Expected a constructor following 'instanceof' operator (was ${t})`,Eu=(t,e)=>{let n=[{}],r=0;for(;r<t.length;){let i=!1;t[r]==="..."&&r<t.length-1&&(i=!0,r++);const s=Ns(t[r],e),[o,a,l]=F(s)?s:[s];if(r++,i){if(!o.extends(p.intrinsic.Array))return d(Lu(o.expression));n=n.flatMap(c=>o.distribute(u=>Du(gi(c),u)))}else n=n.map(c=>a==="?"?Ps(c,o):a==="="?Ku(c,o,l):ln(c,o))}return e.$.parseSchema(n.map(i=>Ze(i)?{proto:Array,exactLength:0}:{proto:Array,sequence:i}))},ln=(t,e)=>t.defaultables||t.optionals?d(t.variadic?Xi:Bu):(t.variadic?t.postfix=N(t.postfix,e):t.prefix=N(t.prefix,e),t),Ps=(t,e)=>t.variadic?d(qs):(t.optionals=N(t.optionals,e),t),Ku=(t,e,n)=>t.variadic?d(qs):t.optionals?d(ju):(t.defaultables=N(t.defaultables,[[e,n]]),t),$r=(t,e)=>(t.postfix&&d(wr),t.variadic?t.variadic.equals(e)||d(wr):t.variadic=e.internal,t),Du=(t,e)=>{const n=e.select({method:"find",kind:"sequence"});if(!n)return $r(t,p.intrinsic.unknown);if(n.prefix)for(const r of n.prefix)ln(t,r);if(n.optionals)for(const r of n.optionals)Ps(t,r);if(n.variadic&&$r(t,n.variadic),n.postfix)for(const r of n.postfix)ln(t,r);return t},Lu=t=>`Spread element must be an array (was ${t})`,wr="A tuple may have at most one variadic element",Bu="A required element may not follow an optional element",qs="An optional element may not follow a variadic element",ju="A defaultable element may not follow an optional element without a default",Fu={},Es=(t,e)=>{if(typeof t=="string"){if(e.args&&Object.keys(e.args).some(r=>t.includes(r)))return mr(t,e);const n=Fu[e.$.name]??={};return n[t]??=mr(t,e)}return $e(t,"object")?Uu(t,e):d(un(Q(t)))},Uu=(t,e)=>{const n=gn(t);switch(n){case void 0:return b(t,"root")?t:bu(t,e);case"Array":return zu(t,e);case"RegExp":return e.$.node("intersection",{domain:"string",pattern:t},{prereduced:!0});case"Function":{const r=At(t)?t():t;return b(r,"root")?r:d(un("Function"))}default:return d(un(n??S(t)))}},zu=(t,e)=>ku(t,e)??Eu(t,e),un=t=>`Type definitions must be strings or objects (was ${t})`;class Tu extends pe{constructor(e){const n=Object.assign({errors:he,hkt:ne,$: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((...r)=>{if(r.length===1)return e.parse(r[0]);if(r.length===2&&typeof r[0]=="string"&&r[0][0]==="<"&&r[0].at(-1)===">"){const i=r[0].slice(1,-1),s=e.parseGenericParams(i,{});return new wt(s,r[1],e,e,null)}return e.parse(r)},{attach:n})}}const Ge=p;class Pt extends os{get ambientAttachments(){if(Ge.typeAttachments)return this.cacheGetter("ambientAttachments",O(Ge.typeAttachments,(e,n)=>[e,this.bindReference(n)]))}preparseOwnAliasEntry(e,n){const r=e.indexOf("<");if(r===-1){if(b(n,"module")||b(n,"generic"))return[e,n];const o=this.name==="ark"?e:e==="root"?this.name:`${this.name}.${e}`,a=this.resolvedConfig.keywords?.[o];return a&&(n=[n,"@",a]),[e,n]}e.at(-1)!==">"&&d("'>' must be the last character of a generic declaration in a scope");const i=e.slice(0,r),s=e.slice(r+1,-1);return[i,()=>{const o=this.parseGenericParams(s,{alias:i});return Ea(o,n,this)}]}parseGenericParams(e,n){return cn(new ui(e),[],this.createParseContext({...n,def:e,prefix:"generic"}))}normalizeRootScopeValue(e){return At(e)&&!b(e,"generic")?e():e}preparseOwnDefinitionFormat(e,n){return{...n,def:e,prefix:n.alias??"type"}}parseOwnDefinitionFormat(e,n){!(n.alias&&n.alias in this.aliases)&&!n.args&&(n.args={this:n.id});const i=Es(e,n);if(F(i)){if(i[1]==="=")return d($s);if(i[1]==="?")return d(bs)}return i}unit=e=>this.units([e]);valueOf=e=>this.units(Co(e));enumerated=(...e)=>this.units(e);instanceOf=e=>this.node("proto",{proto:e},{prereduced:!0});or=(...e)=>this.schema(e.map(n=>this.parse(n)));and=(...e)=>e.reduce((n,r)=>n.and(this.parse(r)),this.intrinsic.unknown);merge=(...e)=>e.reduce((n,r)=>n.merge(this.parse(r)),this.intrinsic.object);pipe=(...e)=>this.intrinsic.unknown.pipe(...e);fn=new uu(this);match=new pu(this);declare=()=>({type:this.type});define(e){return e}type=new Tu(this);static scope=(e,n={})=>new Pt(e,n);static module=(e,n={})=>this.scope(e,n).export()}const _u=Object.assign(Pt.scope,{define:t=>t}),I=Pt;class Ju extends ne{description='merge an object\'s properties onto another like `Merge(User, { isAdmin: "true" })`'}const Vu=ae(["base",$.object],["props",$.object])(t=>t.base.merge(t.props),Ju),Gu=I.module({Key:$.key,Merge:Vu});class Wu extends ne{}const Hu=ae("element")(t=>{const e=t.element.exclude($.Array),n=e.array();return e.rawOr(n).pipe(He).distribute(r=>r.assertHasKind("morph").declareOut(n),R)},Wu),Zu=I.module({root:$.Array,readonly:"root",index:$.nonNegativeIntegerString,liftFrom:Hu},{name:"Array"}),dn=R(["string",Ye.FileConstructor]),Yu=dn.rawOr(dn.array()),vr=R({meta:"an object representing parsed form data",domain:"object",index:{signature:"string",value:Yu}}),Qu=I.module({root:["instanceof",FormData],value:dn,parsed:vr,parse:R({in:FormData,morphs:t=>{const e={};for(const[n,r]of t)if(n in e){const i=e[n];typeof i=="string"||i instanceof Ye.FileConstructor?e[n]=[i,r]:i.push(r)}else e[n]=r;return e},declaredOut:vr})},{name:"FormData"}),Xu=I.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"}),ed={Boolean:1,Number:1,String:1},td=I.module({...O({...Xr,...ti},(t,e)=>t in ed?[]:[t,["instanceof",e]]),Array:Zu,TypedArray:Xu,FormData:Qu}),nd=R({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"}),rd=R({domain:"number",divisor:1}),Ks=I.module({root:$.number,integer:rd,epoch:nd,safe:R({domain:{domain:"number",numberAllowsNaN:!1},min:Number.MIN_SAFE_INTEGER,max:Number.MAX_SAFE_INTEGER}),NaN:["===",Number.NaN],Infinity:["===",Number.POSITIVE_INFINITY],NegativeInfinity:["===",Number.NEGATIVE_INFINITY]},{name:"number"}),M=(t,e,n)=>{const r={domain:"string",pattern:{rule:t.source,flags:t.flags,meta:e}};return n&&(r.meta={format:n}),Cn("intersection",r)},xr=M(mt,"a well-formed integer string"),Ds=I.module({root:xr,parse:R({in:xr,morphs:(t,e)=>{const n=Number.parseInt(t);return Number.isSafeInteger(n)?n:e.error("an integer in the range Number.MIN_SAFE_INTEGER to Number.MAX_SAFE_INTEGER")},declaredOut:$.integer})},{name:"string.integer"}),id=M(/^[\dA-Fa-f]+$/,"hex characters only"),sd=I.module({root:M(/^(?:[\d+/A-Za-z]{4})*(?:[\d+/A-Za-z]{2}==|[\d+/A-Za-z]{3}=)?$/,"base64-encoded"),url:M(/^(?:[\w-]{4})*(?:[\w-]{2}(?:==|%3D%3D)?|[\w-]{3}(?:=|%3D)?)?$/,"base64url-encoded")},{name:"string.base64"}),kr=M(/^[A-Z].*$/,"capitalized"),od=I.module({root:R({in:"string",morphs:t=>t.charAt(0).toUpperCase()+t.slice(1),declaredOut:kr}),preformatted:kr},{name:"string.capitalize"}),ad=t=>{const e=t.replaceAll(/[ -]+/g,"");let n=0,r,i,s=!1;for(let o=e.length-1;o>=0;o--)r=e.substring(o,o+1),i=Number.parseInt(r,10),s?(i*=2,n+=i>=10?i%10+1:i):n+=i,s=!s;return!!(n%10===0&&e)},cd=/^(?: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}))$/,ld=R({domain:"string",pattern:{meta:"a credit card number",rule:cd.source},predicate:{meta:"a credit card number",predicate:ad}}),ud=/^([+-]?\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)?)?)?)?$/,dd=t=>!Number.isNaN(new Date(t).valueOf()),Ar=R({domain:"string",predicate:{meta:"a parsable date",predicate:dd}}).assertHasKind("intersection"),Ir=Ds.root.internal.narrow((t,e)=>{const n=Number.parseInt(t),r=Ks.epoch(n);return r instanceof he?(e.errors.merge(r),!1):!0}).configure({description:"an integer string representing a safe Unix timestamp"},"self").assertHasKind("intersection"),hd=I.module({root:Ir,parse:R({in:Ir,morphs:t=>new Date(t),declaredOut:$.Date})},{name:"string.date.epoch"}),Sr=M(ud,"an ISO 8601 (YYYY-MM-DDTHH:mm:ss.sssZ) date").internal.assertHasKind("intersection"),pd=I.module({root:Sr,parse:R({in:Sr,morphs:t=>new Date(t),declaredOut:$.Date})},{name:"string.date.iso"}),fd=I.module({root:Ar,parse:R({declaredIn:Ar,in:"string",morphs:(t,e)=>{const n=new Date(t);return Number.isNaN(n.valueOf())?e.error("a parsable date"):n},declaredOut:$.Date}),iso:pd,epoch:hd},{name:"string.date"}),md=M(/^[\w%+.-]+@[\d.A-Za-z-]+\.[A-Za-z]{2,}$/,"an email address","email"),Nr="(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])",ce=`(${Nr}[.]){3}${Nr}`,gd=new RegExp(`^${ce}$`),K="(?:[0-9a-fA-F]{1,4})",yd=new RegExp(`^((?:${K}:){7}(?:${K}|:)|(?:${K}:){6}(?:${ce}|:${K}|:)|(?:${K}:){5}(?::${ce}|(:${K}){1,2}|:)|(?:${K}:){4}(?:(:${K}){0,1}:${ce}|(:${K}){1,3}|:)|(?:${K}:){3}(?:(:${K}){0,2}:${ce}|(:${K}){1,4}|:)|(?:${K}:){2}(?:(:${K}){0,3}:${ce}|(:${K}){1,5}|:)|(?:${K}:){1}(?:(:${K}){0,4}:${ce}|(:${K}){1,6}|:)|(?::((?::${K}){0,5}:${ce}|(?::${K}){1,7}|:)))(%[0-9a-zA-Z.]{1,})?$`),bd=I.module({root:["v4 | v6","@","an IP address"],v4:M(gd,"an IPv4 address","ipv4"),v6:M(yd,"an IPv6 address","ipv6")},{name:"string.ip"}),Re="a JSON string",Ls=t=>{if(!(t instanceof SyntaxError))throw t;return`must be ${Re} (${t})`},$d=R({meta:Re,domain:"string",predicate:{meta:Re,predicate:(t,e)=>{try{return JSON.parse(t),!0}catch(n){return e.reject({code:"predicate",expected:Re,problem:Ls(n)})}}}}),wd=(t,e)=>{if(t.length===0)return e.error({code:"predicate",expected:Re,actual:"empty"});try{return JSON.parse(t)}catch(n){return e.error({code:"predicate",expected:Re,problem:Ls(n)})}},vd=I.module({root:$d,parse:R({meta:"safe JSON string parser",in:"string",morphs:wd,declaredOut:$.jsonObject})},{name:"string.json"}),Or=M(/^[a-z]*$/,"only lowercase letters"),xd=I.module({root:R({in:"string",morphs:t=>t.toLowerCase(),declaredOut:Or}),preformatted:Or},{name:"string.lower"}),Bs=["NFC","NFD","NFKC","NFKD"],it=O(Bs,(t,e)=>[e,R({domain:"string",predicate:n=>n.normalize(e)===n,meta:`${e}-normalized unicode`})]),qt=O(Bs,(t,e)=>[e,R({in:"string",morphs:n=>n.normalize(e),declaredOut:it[e]})]),kd=I.module({root:qt.NFC,preformatted:it.NFC},{name:"string.normalize.NFC"}),Ad=I.module({root:qt.NFD,preformatted:it.NFD},{name:"string.normalize.NFD"}),Id=I.module({root:qt.NFKC,preformatted:it.NFKC},{name:"string.normalize.NFKC"}),Sd=I.module({root:qt.NFKD,preformatted:it.NFKD},{name:"string.normalize.NFKD"}),Nd=I.module({root:"NFC",NFC:kd,NFD:Ad,NFKC:Id,NFKD:Sd},{name:"string.normalize"}),Rr=M(Wt,"a well-formed numeric string"),Od=I.module({root:Rr,parse:R({in:Rr,morphs:t=>Number.parseFloat(t),declaredOut:$.number})},{name:"string.numeric"}),Cr="a regex pattern",Rd=R({domain:"string",predicate:{meta:Cr,predicate:(t,e)=>{try{return new RegExp(t),!0}catch(n){return e.reject({code:"predicate",expected:Cr,problem:String(n)})}}},meta:{format:"regex"}}),Cd=/^(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-]+)*))?$/,Md=M(Cd,"a semantic version (see https://semver.org/)"),Mr=M(/^\S.*\S$|^\S?$/,"trimmed"),Pd=I.module({root:R({in:"string",morphs:t=>t.trim(),declaredOut:Mr}),preformatted:Mr},{name:"string.trim"}),Pr=M(/^[A-Z]*$/,"only uppercase letters"),qd=I.module({root:R({in:"string",morphs:t=>t.toUpperCase(),declaredOut:Pr}),preformatted:Pr},{name:"string.upper"}),Ed=t=>URL.canParse(t),qr=R({domain:"string",predicate:{meta:"a URL string",predicate:Ed},meta:{format:"uri"}}),Kd=I.module({root:qr,parse:R({declaredIn:qr,in:"string",morphs:(t,e)=>{try{return new URL(t)}catch{return e.error("a URL string")}},declaredOut:R(URL)})},{name:"string.url"}),Dd=I.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:M(/^[\da-f]{8}-[\da-f]{4}-1[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv1"),v2:M(/^[\da-f]{8}-[\da-f]{4}-2[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv2"),v3:M(/^[\da-f]{8}-[\da-f]{4}-3[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv3"),v4:M(/^[\da-f]{8}-[\da-f]{4}-4[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv4"),v5:M(/^[\da-f]{8}-[\da-f]{4}-5[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv5"),v6:M(/^[\da-f]{8}-[\da-f]{4}-6[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv6"),v7:M(/^[\da-f]{8}-[\da-f]{4}-7[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv7"),v8:M(/^[\da-f]{8}-[\da-f]{4}-8[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv8")},{name:"string.uuid"}),Ld=I.module({root:$.string,alpha:M(/^[A-Za-z]*$/,"only letters"),alphanumeric:M(/^[\dA-Za-z]*$/,"only letters and digits 0-9"),hex:id,base64:sd,capitalize:od,creditCard:ld,date:fd,digits:M(/^\d*$/,"only digits 0-9"),email:md,integer:Ds,ip:bd,json:vd,lower:xd,normalize:Nd,numeric:Od,regex:Rd,semver:Md,trim:Pd,upper:qd,url:Kd,uuid:Dd},{name:"string"}),Bd=I.module({bigint:$.bigint,boolean:$.boolean,false:$.false,never:$.never,null:$.null,number:$.number,object:$.object,string:$.string,symbol:$.symbol,true:$.true,unknown:$.unknown,undefined:$.undefined}),jd=I.module({root:$.unknown,any:$.unknown},{name:"unknown"}),Fd=I.module({root:$.jsonObject,stringify:Cn("morph",{in:$.jsonObject,morphs:t=>JSON.stringify(t),declaredOut:$.string})},{name:"object.json"}),Ud=I.module({root:$.object,json:Fd},{name:"object"});class zd extends ne{description='instantiate an object from an index signature and corresponding value type like `Record("string", "number")`'}const Td=ae(["K",$.key],"V")(t=>({domain:"object",index:{signature:t.K,value:t.V}}),zd);class _d extends ne{description='pick a set of properties from an object like `Pick(User, "name | age")`'}const Jd=ae(["T",$.object],["K",$.key])(t=>t.T.pick(t.K),_d);class Vd extends ne{description='omit a set of properties from an object like `Omit(User, "age")`'}const Gd=ae(["T",$.object],["K",$.key])(t=>t.T.omit(t.K),Vd);class Wd extends ne{description="make all named properties of an object optional like `Partial(User)`"}const Hd=ae(["T",$.object])(t=>t.T.partial(),Wd);class Zd extends ne{description="make all named properties of an object required like `Required(User)`"}const Yd=ae(["T",$.object])(t=>t.T.required(),Zd);class Qd extends ne{description='exclude branches of a union like `Exclude("boolean", "true")`'}const Xd=ae("T","U")(t=>t.T.exclude(t.U),Qd);class eh extends ne{description='extract branches of a union like `Extract("0 | false | 1", "number")`'}const th=ae("T","U")(t=>t.T.extract(t.U),eh),nh=I.module({Exclude:Xd,Extract:th,Omit:Gd,Partial:Hd,Pick:Jd,Record:Td,Required:Yd}),fe=_u({...Bd,...nh,...td,...Gu,string:Ld,number:Ks,object:Ud,unknown:jd},{prereducedAliases:!0,name:"ark"}),B=fe.export();Object.assign(Ge.ambient,B);Ge.typeAttachments={string:B.string.root,number:B.number.root,bigint:B.bigint,boolean:B.boolean,symbol:B.symbol,undefined:B.undefined,null:B.null,object:B.object.root,unknown:B.unknown.root,false:B.false,true:B.true,never:B.never,arrayIndex:B.Array.index,Key:B.Key,Record:B.Record,Array:B.Array.root,Date:B.Date};const js=Object.assign(fe.type,Ge.typeAttachments);fe.match;fe.fn;fe.generic;fe.schema;fe.define;fe.declare;const rh="/api/plugin/content-loading-plugin",Fs=rh,Us=go(import.meta.url);async function ih(t){const e=`${Fs}${t}`,n=await fetch(e);if(n.status!==200)throw new Error(`api error ${n.status}`);return await n.text()}function hn(t){const e=document.createElement("div");return e.innerHTML=t,[...e.children]}const zs=t=>t!=null&&(t=Object.getPrototypeOf(t),t===Array.prototype||t===Object.prototype);function Ts(t,e,n){for(const[r,i]of Object.entries(e)){const s=`${n}.${r}`;t[s]=i,zs(i)&&Ts(t,i,s)}}function sh(t){const e={...t};for(const[n,r]of Object.entries(t))zs(r)&&Ts(e,r,n);return e}const oh=(t,e)=>{if(e)for(const[n,r]of Object.entries(e))t=t.replace(new RegExp(`{{\\s*${n}\\s*}}`,"g"),r);return t},ah=t=>t;function ch(t,e=ah){return(n,...r)=>{n[0]==="."&&(n=n.slice(1));const i=t()?.[n];switch(typeof i){case"function":return i(...r);case"string":return e(i,r[0]);default:return i}}}const lh={nothingMessage:"Keine Ergebnisse gefunden für",search:"Suchen"},uh={loadMore:"Mehr laden"},dh={searchApp:lh,infiniteLoading:uh},hh={nothingMessage:"No results found for",search:"Search"},ph={loadMore:"Load more"},fh={searchApp:hh,infiniteLoading:ph},mh={nothingMessage:"No se encontraron resultados para",search:"Buscar"},gh={loadMore:"Cargar más"},yh={searchApp:mh,infiniteLoading:gh},bh={nothingMessage:"Aucun résultat trouvé pour",search:"Rechercher"},$h={loadMore:"Charger la suite"},wh={searchApp:bh,infiniteLoading:$h},vh={nothingMessage:"Nessun risultato trovato per",search:"Cerca"},xh={loadMore:"Carica altro"},kh={searchApp:vh,infiniteLoading:xh},Ah={nothingMessage:"Nenhum resultado encontrado para",search:"Pesquisar"},Ih={loadMore:"Carregar mais"},Sh={searchApp:Ah,infiniteLoading:Ih},Er={en:fh,fr:wh,es:yh,de:dh,it:kh,pt:Sh};function Et(t){const e=Z(()=>{const r=t in Er?t:"en";return sh(Er[r])});return{t:ch(e,oh)}}var Nh=V('<button class="PaInfiniteLoading-loadButton PaButton"type=button>'),Oh=V("<div class=PaInfiniteLoading-loadMore>"),Rh=V('<img class="PaInfiniteLoading-loading PaLoading"width=50 height=50 alt=…>');const Ch=js({"offset?":"string|undefined","total?":"string|undefined","limit?":"string|undefined","parentDocumentId?":"string|undefined","template?":"string|undefined","labeledWith?":"string|undefined","termNodeId?":"string|undefined","sorting?":"string|undefined","+":"ignore"}).pipe(t=>({offset:X(t.offset)?Number(t.offset):void 0,total:X(t.total)?Number(t.total):void 0,limit:X(t.limit)?Number(t.limit):void 0,parentDocumentId:X(t.parentDocumentId)?t.parentDocumentId:void 0,templateName:X(t.template)?t.template:void 0,termNodeId:X(t.termNodeId)?t.termNodeId:void 0,labeledWith:X(t.labeledWith)?t.labeledWith:void 0,sorting:X(t.sorting)?t.sorting:void 0}));function Mh(t,{language:e}){const{templateName:n,offset:r,total:i,limit:s,parentDocumentId:o,sorting:a,termNodeId:l,labeledWith:c}=Ch.assert(t.dataset);if(!(r===void 0||i===void 0||o===void 0||s===void 0||n===void 0)){if(!e)throw new Error("Missing language");Ph({language:e,limit:s,parentDocumentId:o,root:t,offset:r,total:i,sorting:a,labeledWith:l!==void 0&&c?{termNodeId:l,fieldName:c}:void 0,templateName:n})}}function Ph({language:t,limit:e,root:n,offset:r,total:i,parentDocumentId:s,sorting:o,templateName:a,labeledWith:l}){const{t:c}=Et(t);let u=r;if(u>=i)return;const h=(()=>{var f=Nh();return f.$$click=x,J(f,()=>c("infiniteLoading.loadMore")),f})(),m=(()=>{var f=Oh();return J(f,h),f})(),y=(()=>{var f=Rh();return kt(f,"src",`${Us}/spinner.svg`),f})();n.appendChild(m);async function x(){n.appendChild(y);const f=await qh({limit:e,newOffset:u,parentDocumentId:s,sorting:o,labeledWith:l,templateName:a});for(const w of f)n.insertBefore(w,m);u+=e,u>=i&&m.remove(),y.remove()}}async function qh({limit:t,newOffset:e,parentDocumentId:n,labeledWith:r,sorting:i,templateName:s}){const o=[["template",s],["children-of",n],["offset",e],["limit",t]];i&&o.push(["sorting",i]),r&&(o.push(["labeled-t",r.termNodeId]),o.push(["labeled-f",r.fieldName]));const a=`/partials?${o.map(([c,u])=>`${c}=${encodeURIComponent(u)}`).join("&")}`,l=await ih(a);return hn(l)}fn(["click"]);function _s(){let t=new Set;function e(i){return t.add(i),()=>t.delete(i)}let n=!1;function r(i,s){if(n)return!(n=!1);const o={to:i,options:s,defaultPrevented:!1,preventDefault:()=>o.defaultPrevented=!0};for(const a of t)a.listener({...o,from:a.location,retry:l=>{l&&(n=!0),a.navigate(i,{...s,resolve:!1})}});return!o.defaultPrevented}return{subscribe:e,confirm:r}}let pn;function qn(){(!window.history.state||window.history.state._depth==null)&&window.history.replaceState({...window.history.state,_depth:window.history.length-1},""),pn=window.history.state._depth}Ue||qn();function Eh(t){return{...t,_depth:window.history.state&&window.history.state._depth}}function Kh(t,e){let n=!1;return()=>{const r=pn;qn();const i=r==null?null:pn-r;if(n){n=!1;return}i&&e(i)?(n=!0,window.history.go(-i)):t()}}const Dh=/^(?:[a-z0-9]+:)?\/\//i,Lh=/^\/+|(\/)\/+$/g,Js="http://sr";function _e(t,e=!1){const n=t.replace(Lh,"$1");return n?e||/^[?#]/.test(n)?n:"/"+n:""}function ht(t,e,n){if(Dh.test(e))return;const r=_e(t),i=n&&_e(n);let s="";return!i||e.startsWith("/")?s=r:i.toLowerCase().indexOf(r.toLowerCase())!==0?s=r+i:s=i,(s||"/")+_e(e,!s)}function Bh(t,e){if(t==null)throw new Error(e);return t}function jh(t,e){return _e(t).replace(/\/*(\*.*)?$/g,"")+_e(e)}function Vs(t){const e={};return t.searchParams.forEach((n,r)=>{r in e?Array.isArray(e[r])?e[r].push(n):e[r]=[e[r],n]:e[r]=n}),e}function Fh(t,e,n){const[r,i]=t.split("/*",2),s=r.split("/").filter(Boolean),o=s.length;return a=>{const l=a.split("/").filter(Boolean),c=l.length-o;if(c<0||c>0&&i===void 0&&!e)return null;const u={path:o?"":"/",params:{}},h=m=>n===void 0?void 0:n[m];for(let m=0;m<o;m++){const y=s[m],x=y[0]===":",f=x?l[m]:l[m].toLowerCase(),w=x?y.slice(1):y.toLowerCase();if(x&&Tt(f,h(w)))u.params[w]=f;else if(x||!Tt(f,w))return null;u.path+=`/${f}`}if(i){const m=c?l.slice(-c).join("/"):"";if(Tt(m,h(i)))u.params[i]=m;else return null}return u}}function Tt(t,e){const n=r=>r===t;return e===void 0?!0:typeof e=="string"?n(e):typeof e=="function"?e(t):Array.isArray(e)?e.some(n):e instanceof RegExp?e.test(t):!1}function Uh(t){const[e,n]=t.pattern.split("/*",2),r=e.split("/").filter(Boolean);return r.reduce((i,s)=>i+(s.startsWith(":")?2:3),r.length-(n===void 0?0:1))}function Gs(t){const e=new Map,n=Fr();return new Proxy({},{get(r,i){return e.has(i)||Ur(n,()=>e.set(i,Z(()=>t()[i]))),e.get(i)()},getOwnPropertyDescriptor(){return{enumerable:!0,configurable:!0}},ownKeys(){return Reflect.ownKeys(t())}})}function Ws(t){let e=/(\/?\:[^\/]+)\?/.exec(t);if(!e)return[t];let n=t.slice(0,e.index),r=t.slice(e.index+e[0].length);const i=[n,n+=e[1]];for(;e=/^(\/\:[^\/]+)\?/.exec(r);)i.push(n+=e[1]),r=r.slice(e[0].length);return Ws(r).reduce((s,o)=>[...s,...i.map(a=>a+o)],[])}const zh=100,Hs=Tr(),Zs=Tr(),En=()=>Bh(zr(Hs),"<A> and 'use' router primitives can be only used inside a Route."),Ys=()=>En().navigatorFactory(),Th=()=>En().location,_h=()=>En().params;function Jh(t,e=""){const{component:n,preload:r,load:i,children:s,info:o}=t,a=!s||Array.isArray(s)&&!s.length,l={key:t,component:n,preload:r||i,info:o};return Qs(t.path).reduce((c,u)=>{for(const h of Ws(u)){const m=jh(e,h);let y=a?m:m.split("/*",1)[0];y=y.split("/").map(x=>x.startsWith(":")||x.startsWith("*")?x:encodeURIComponent(x)).join("/"),c.push({...l,originalPath:u,pattern:y,matcher:Fh(y,!a,t.matchFilters)})}return c},[])}function Vh(t,e=0){return{routes:t,score:Uh(t[t.length-1])*1e4-e,matcher(n){const r=[];for(let i=t.length-1;i>=0;i--){const s=t[i],o=s.matcher(n);if(!o)return null;r.unshift({...o,route:s})}return r}}}function Qs(t){return Array.isArray(t)?t:[t]}function Xs(t,e="",n=[],r=[]){const i=Qs(t);for(let s=0,o=i.length;s<o;s++){const a=i[s];if(a&&typeof a=="object"){a.hasOwnProperty("path")||(a.path="");const l=Jh(a,e);for(const c of l){n.push(c);const u=Array.isArray(a.children)&&a.children.length===0;if(a.children&&!u)Xs(a.children,c.pattern,n,r);else{const h=Vh([...n],r.length);r.push(h)}n.pop()}}}return n.length?r:r.sort((s,o)=>o.score-s.score)}function Je(t,e){for(let n=0,r=t.length;n<r;n++){const i=t[n].matcher(e);if(i)return i}return[]}function Gh(t,e,n){const r=new URL(Js),i=Z(u=>{const h=t();try{return new URL(h,r)}catch{return console.error(`Invalid path ${h}`),u}},r,{equals:(u,h)=>u.href===h.href}),s=Z(()=>i().pathname),o=Z(()=>i().search,!0),a=Z(()=>i().hash),l=()=>"",c=We(o,()=>Vs(i()));return{get pathname(){return s()},get search(){return o()},get hash(){return a()},get state(){return e()},get key(){return l()},query:n?n(c):Gs(c)}}let me;function Wh(){return me}function Hh(t,e,n,r={}){const{signal:[i,s],utils:o={}}=t,a=o.parsePath||(k=>k),l=o.renderPath||(k=>k),c=o.beforeLeave||_s(),u=ht("",r.base||"");if(u===void 0)throw new Error(`${u} is not a valid base path`);u&&!i().value&&s({value:u,replace:!0,scroll:!1});const[h,m]=Y(!1);let y;const x=(k,C)=>{C.value===f()&&C.state===v()||(y===void 0&&m(!0),me=k,y=C,co(()=>{y===C&&(w(y.value),A(y.state),lo(),Ue||H[1](_=>_.filter(we=>we.pending)))}).finally(()=>{y===C&&uo(()=>{me=void 0,k==="navigate"&&ro(y),m(!1),y=void 0})}))},[f,w]=Y(i().value),[v,A]=Y(i().state),P=Gh(f,v,o.queryWrapper),G=[],H=Y(Ue?so():[]),Be=Z(()=>typeof r.transformUrl=="function"?Je(e(),r.transformUrl(P.pathname)):Je(e(),P.pathname)),Kn=()=>{const k=Be(),C={};for(let _=0;_<k.length;_++)Object.assign(C,k[_].params);return C},eo=o.paramsWrapper?o.paramsWrapper(Kn,e):Gs(Kn),Dn={pattern:u,path:()=>u,outlet:()=>null,resolvePath(k){return ht(u,k)}};return ao(We(i,k=>x("native",k),{defer:!0})),{base:Dn,location:P,params:eo,isRouting:h,renderPath:l,parsePath:a,navigatorFactory:no,matches:Be,beforeLeave:c,preloadRoute:io,singleFlight:r.singleFlight===void 0?!0:r.singleFlight,submissions:H};function to(k,C,_){_r(()=>{if(typeof C=="number"){C&&(o.go?o.go(C):console.warn("Router integration does not support relative routing"));return}const we=!C||C[0]==="?",{replace:st,resolve:ve,scroll:ot,state:xe}={replace:!1,resolve:!we,scroll:!0,..._},ke=ve?k.resolvePath(C):ht(we&&P.pathname||"",C);if(ke===void 0)throw new Error(`Path '${C}' is not a routable path`);if(G.length>=zh)throw new Error("Too many redirects");const Ln=f();if(ke!==Ln||xe!==v())if(Ue){const Bn=Jt();Bn&&(Bn.response={status:302,headers:new Headers({Location:ke})}),s({value:ke,replace:st,scroll:ot,state:xe})}else c.confirm(ke,_)&&(G.push({value:Ln,replace:st,scroll:ot,state:v()}),x("navigate",{value:ke,state:xe}))})}function no(k){return k=k||zr(Zs)||Dn,(C,_)=>to(k,C,_)}function ro(k){const C=G[0];C&&(s({...k,replace:C.replace,scroll:C.scroll}),G.length=0)}function io(k,C){const _=Je(e(),k.pathname),we=me;me="preload";for(let st in _){const{route:ve,params:ot}=_[st];ve.component&&ve.component.preload&&ve.component.preload();const{preload:xe}=ve;C&&xe&&Ur(n(),()=>xe({params:ot,location:{pathname:k.pathname,search:k.search,hash:k.hash,query:Vs(k),state:null,key:""},intent:"preload"}))}me=we}function so(){const k=Jt();return k&&k.router&&k.router.submission?[k.router.submission]:[]}}function Zh(t,e,n,r){const{base:i,location:s,params:o}=t,{pattern:a,component:l,preload:c}=r().route,u=Z(()=>r().path);l&&l.preload&&l.preload();const h=c?c({params:o,location:s,intent:me||"initial"}):void 0;return{parent:e,pattern:a,path:u,outlet:()=>l?ho(l,{params:o,location:s,data:h,get children(){return n()}}):n(),resolvePath(y){return ht(i.path(),y,u())}}}const Yh=t=>e=>{const{base:n}=e,r=Jr(()=>e.children),i=Z(()=>Xs(r(),e.base||""));let s;const o=Hh(t,i,()=>s,{base:n,singleFlight:e.singleFlight,transformUrl:e.transformUrl});return t.create&&t.create(o),E(Hs.Provider,{value:o,get children(){return E(Qh,{routerState:o,get root(){return e.root},get preload(){return e.rootPreload||e.rootLoad},get children(){return[Vt(()=>(s=Fr())&&null),E(Xh,{routerState:o,get branches(){return i()}})]}})}})};function Qh(t){const e=t.routerState.location,n=t.routerState.params,r=Z(()=>t.preload&&_r(()=>{t.preload({params:n,location:e,intent:Wh()||"initial"})}));return E(Se,{get when(){return t.root},keyed:!0,get fallback(){return t.children},children:i=>E(i,{params:n,location:e,get data(){return r()},get children(){return t.children}})})}function Xh(t){if(Ue){const i=Jt();if(i&&i.router&&i.router.dataOnly){ep(i,t.routerState,t.branches);return}i&&((i.router||(i.router={})).matches||(i.router.matches=t.routerState.matches().map(({route:s,path:o,params:a})=>({path:s.originalPath,pattern:s.pattern,match:o,params:a,info:s.info}))))}const e=[];let n;const r=Z(We(t.routerState.matches,(i,s,o)=>{let a=s&&i.length===s.length;const l=[];for(let c=0,u=i.length;c<u;c++){const h=s&&s[c],m=i[c];o&&h&&m.route.key===h.route.key?l[c]=o[c]:(a=!1,e[c]&&e[c](),fo(y=>{e[c]=y,l[c]=Zh(t.routerState,l[c-1]||t.routerState.base,Kr(()=>r()[c+1]),()=>t.routerState.matches()[c])}))}return e.splice(i.length).forEach(c=>c()),o&&a?o:(n=l[0],l)}));return Kr(()=>r()&&n)()}const Kr=t=>()=>E(Se,{get when(){return t()},keyed:!0,children:e=>E(Zs.Provider,{value:e,get children(){return e.outlet()}})}),_t=t=>{const e=Jr(()=>t.children);return po(t,{get children(){return e()}})};function ep(t,e,n){const r=new URL(t.request.url),i=Je(n,new URL(t.router.previousUrl||t.request.url).pathname),s=Je(n,r.pathname);for(let o=0;o<s.length;o++){(!i[o]||s[o].route!==i[o].route)&&(t.router.dataOnly=!0);const{route:a,params:l}=s[o];a.preload&&a.preload({params:l,location:e.location,intent:"preload"})}}function tp([t,e],n,r){return[t,r?i=>e(r(i)):e]}function np(t){let e=!1;const n=i=>typeof i=="string"?{value:i}:i,r=tp(Y(n(t.get()),{equals:(i,s)=>i.value===s.value&&i.state===s.state}),void 0,i=>(!e&&t.set(i),Kt.registry&&!Kt.done&&(Kt.done=!0),i));return t.init&&Vr(t.init((i=t.get())=>{e=!0,r[1](n(i)),e=!1})),Yh({signal:r,create:t.create,utils:t.utils})}function rp(t,e,n){return t.addEventListener(e,n),()=>t.removeEventListener(e,n)}function ip(t,e){const n=t&&document.getElementById(t);n?n.scrollIntoView():e&&window.scrollTo(0,0)}const sp=new Map;function op(t=!0,e=!1,n="/_server",r){return i=>{const s=i.base.path(),o=i.navigatorFactory(i.base);let a,l;function c(f){return f.namespaceURI==="http://www.w3.org/2000/svg"}function u(f){if(f.defaultPrevented||f.button!==0||f.metaKey||f.altKey||f.ctrlKey||f.shiftKey)return;const w=f.composedPath().find(Be=>Be instanceof Node&&Be.nodeName.toUpperCase()==="A");if(!w||e&&!w.hasAttribute("link"))return;const v=c(w),A=v?w.href.baseVal:w.href;if((v?w.target.baseVal:w.target)||!A&&!w.hasAttribute("state"))return;const G=(w.getAttribute("rel")||"").split(/\s+/);if(w.hasAttribute("download")||G&&G.includes("external"))return;const H=v?new URL(A,document.baseURI):new URL(A);if(!(H.origin!==window.location.origin||s&&H.pathname&&!H.pathname.toLowerCase().startsWith(s.toLowerCase())))return[w,H]}function h(f){const w=u(f);if(!w)return;const[v,A]=w,P=i.parsePath(A.pathname+A.search+A.hash),G=v.getAttribute("state");f.preventDefault(),o(P,{resolve:!1,replace:v.hasAttribute("replace"),scroll:!v.hasAttribute("noscroll"),state:G?JSON.parse(G):void 0})}function m(f){const w=u(f);if(!w)return;const[v,A]=w;i.preloadRoute(A,v.getAttribute("preload")!=="false")}function y(f){clearTimeout(a);const w=u(f);if(!w)return l=null;const[v,A]=w;l!==v&&(a=setTimeout(()=>{i.preloadRoute(A,v.getAttribute("preload")!=="false"),l=v},20))}function x(f){if(f.defaultPrevented)return;let w=f.submitter&&f.submitter.hasAttribute("formaction")?f.submitter.getAttribute("formaction"):f.target.getAttribute("action");if(!w)return;if(!w.startsWith("https://action/")){const A=new URL(w,Js);if(w=i.parsePath(A.pathname+A.search),!w.startsWith(n))return}if(f.target.method.toUpperCase()!=="POST")throw new Error("Only POST forms are supported for Actions");const v=sp.get(w);if(v){f.preventDefault();const A=new FormData(f.target,f.submitter);v.call({r:i,f:f.target},f.target.enctype==="multipart/form-data"?A:new URLSearchParams(A))}}fn(["click","submit"]),document.addEventListener("click",h),t&&(document.addEventListener("mousemove",y,{passive:!0}),document.addEventListener("focusin",m,{passive:!0}),document.addEventListener("touchstart",m,{passive:!0})),document.addEventListener("submit",x),Vr(()=>{document.removeEventListener("click",h),t&&(document.removeEventListener("mousemove",y),document.removeEventListener("focusin",m),document.removeEventListener("touchstart",m)),document.removeEventListener("submit",x)})}}function ap(t){const e=t.replace(/^.*?#/,"");if(!e.startsWith("/")){const[,n="/"]=window.location.hash.split("#",2);return`${n}#${e}`}return e}function cp(t){const e=()=>window.location.hash.slice(1),n=_s();return np({get:e,set({value:r,replace:i,scroll:s,state:o}){i?window.history.replaceState(Eh(o),"","#"+r):window.history.pushState(o,"","#"+r);const a=r.indexOf("#"),l=a>=0?r.slice(a+1):"";ip(l,s),qn()},init:r=>rp(window,"hashchange",Kh(r,i=>!n.confirm(i&&i<0?i:e()))),create:op(t.preload,t.explicitLinks,t.actionBase),utils:{go:r=>window.history.go(r),renderPath:r=>`#${r}`,parsePath:ap,beforeLeave:n}})(t)}function lp(t){const e=Ys(),n=Th(),{href:r,state:i}=t,s=typeof r=="function"?r({navigate:e,location:n}):r;return e(s,{replace:!0,state:i}),null}async function Dr({language:t,text:e,limit:n,offset:r,templateName:i}){const s=`${Fs}/search?language=${encodeURIComponent(t)}&q=${encodeURIComponent(e)}&limit=${encodeURIComponent(n)}&offset=${encodeURIComponent(r)}&tpl=${encodeURIComponent(i)}`,o=await fetch(s,{method:"GET"});if(o.status!==200){const l=await o.text();throw new Error(`API error (${o.status}): ${l}`)}return await o.json()}var up=V('<form class=PaSearchApp-form><input class="PaSearchApp-input PaInput"type=search><button class="PaSearchApp-searchButton PaButton"type=submit>');function dp(t){const e=Ys(),[n,r]=Y(t.value??""),{t:i}=Et(t.language);Gr(We(()=>t.value,()=>r(t.value??"")));const s=async o=>{o.preventDefault(),e(`/q/${encodeURIComponent(n())}`)};return(()=>{var o=up(),a=o.firstChild,l=a.nextSibling;return o.addEventListener("submit",s),a.addEventListener("change",c=>r(c.currentTarget.value)),J(l,()=>i("searchApp.search")),pt(()=>kt(a,"placeholder",i("searchApp.search"))),pt(()=>a.value=n()),o})()}var hp=V("<div class=PaSearchApp-loadMore>"),pp=V("<div class=PaSearchApp-results>"),fp=V("<div class=PaSearchApp>"),mp=V("<div class=PaSearchApp-nothing> <span class=PaSearchApp-quote>"),gp=V('<img class="PaSearchApp-loading PaLoading"width=80 height=80 alt=…>'),yp=V('<button class="PaSearchApp-loadButton PaButton"type=button>');function Lr({language:t,limit:e,templateName:n}){const{t:r}=Et(t),i=_h(),[s,o]=Y([]),[a,l]=Y(-1),[c,u]=Y(0),[h,m]=Y(!1);Gr(We(()=>i.searchString,y));async function y(){if(i.searchString){m(!0);try{o([]),u(0),l(-1);const f=await Dr({language:t,text:decodeURIComponent(i.searchString),limit:e,offset:c(),templateName:n});if(l(f.total),u(c()+e),!f.html)return;o(hn(f.html))}finally{m(!1)}}}async function x(){if(!i.searchString)return;const f=a();if(!(f===-1||c()>=f)){m(!0);try{const w=await Dr({language:t,text:decodeURIComponent(i.searchString),limit:e,offset:c(),templateName:n});if(!w.html)return;o([...s(),...hn(w.html)]),u(c()+e)}finally{m(!1)}}}return(()=>{var f=fp();return J(f,E(dp,{language:t,get value(){return Vt(()=>!!i.searchString)()?decodeURIComponent(i.searchString):void 0}}),null),J(f,E(Se,{get when(){return i.searchString},get children(){var w=pp();return J(w,E(Se,{get when(){return a()!==-1},get children(){return E(Se,{get when(){return s().length>0},get fallback(){return(()=>{var v=mp(),A=v.firstChild,P=A.nextSibling;return J(v,()=>r("searchApp.nothingMessage"),A),J(P,()=>i.searchString),v})()},get children(){return s()}})}}),null),J(w,E(Se,{get when(){return a()===-1||h()||c()<a()},get children(){var v=hp();return J(v,(()=>{var A=Vt(()=>!!h());return()=>A()?(()=>{var P=gp();return kt(P,"src",`${Us}/spinner.svg`),P})():(()=>{var P=yp();return P.$$click=x,J(P,()=>r("infiniteLoading.loadMore")),P})()})()),v}}),null),w}}),null),f})()}fn(["click"]);const bp=js({"limit?":"string|undefined","template?":"string|undefined","+":"ignore"}).pipe(t=>({limit:X(t.limit)?Number(t.limit):void 0,templateName:X(t.template)?t.template:void 0}));function $p(t,{language:e}){if(!e)throw new Error("Missing language");const{limit:n,templateName:r}=bp.assert(t.dataset);n===void 0||r===void 0||jr(()=>E(cp,{explicitLinks:!0,get children(){return[E(_t,{path:"/",component:()=>E(lp,{href:"/q"})}),E(_t,{path:"/q",component:()=>E(Lr,{language:e,templateName:r,limit:n})}),E(_t,{path:"/q/:searchString",component:()=>E(Lr,{language:e,templateName:r,limit:n})})]}}),t)}var wp=V('<input class="PaSearchOpener-input PaInput"type=search required>'),vp=V('<form class=PaSearchOpener><button class="PaSearchOpener-button PaButton"type=submit>');function xp({searchURL:t,language:e}){const[n,r]=Y(""),{t:i}=Et(e),s=(()=>{var a=wp();return a.addEventListener("change",l=>r(l.currentTarget.value)),pt(()=>kt(a,"placeholder",i("searchApp.search"))),pt(()=>a.value=n()),a})(),o=a=>{a.preventDefault(),window.location.href=`${t}#/q/${encodeURIComponent(n())}`};return(()=>{var a=vp(),l=a.firstChild;return a.addEventListener("submit",o),J(a,s,l),J(l,()=>i("searchApp.search")),a})()}var kp=V('<button class="PaSearchOpenerButton PaIconButton"type=button><svg class=PaSearchOpenerButton-svg width=20 height=20 xmlns=http://www.w3.org/2000/svg viewBox="0 0 490.4 490.4"><title>Mignifier</title><g id=SVGRepo_bgCarrier stroke-width=0></g><g id=SVGRepo_tracerCarrier stroke-linecap=round stroke-linejoin=round></g><g id=SVGRepo_iconCarrier><g><path d="M484.1,454.796l-110.5-110.6c29.8-36.3,47.6-82.8,47.6-133.4c0-116.3-94.3-210.6-210.6-210.6S0,94.496,0,210.796 s94.3,210.6,210.6,210.6c50.8,0,97.4-18,133.8-48l110.5,110.5c12.9,11.8,25,4.2,29.2,0C492.5,475.596,492.5,463.096,484.1,454.796z M41.1,210.796c0-93.6,75.9-169.5,169.5-169.5s169.6,75.9,169.6,169.5s-75.9,169.5-169.5,169.5S41.1,304.396,41.1,210.796z"></path> ');function Ap({searchIconColor:t,language:e,searchURL:n}){const r=(()=>{var o=kp(),a=o.firstChild;return oo(a,"fill",t),o})(),i=E(xp,{searchURL:n,language:e});return mo({openButton:r,dialogContent:i,modalClass:"_paSearchOpener"}).on("open",()=>{i.querySelector("input")?.focus()}),r}function Ip(t,{language:e}){const n=t.dataset.searchUrl,r=t.dataset.iconColor;if(!e)throw new Error("Missing language");if(!n)throw new Error("Missing search url");jr(()=>E(Ap,{language:e,searchURL:n,searchIconColor:r}),t)}document.readyState==="loading"?document.addEventListener("DOMContentLoaded",Br):Br();function Br(){const t=document.documentElement.lang,e={paSearchOpener:Ip,paSearchApp:$p,paInfiniteLoading:Mh},n=document.querySelectorAll("[data-effect]");for(const r of n){const i=r.dataset.effect;if(!i)continue;const s=e[i];s&&s(r,{language:t})}}
|
|
1
|
+
import{delegateEvents as fn,template as V,insert as J,setAttribute as kt,isServer as Ue,getRequestEvent as Jt,createComponent as E,memo as Vt,effect as pt,render as jr,setStyleProperty as oo}from"https://esm.sh/solid-js@1.9.9/web";import{createMemo as Z,getOwner as Fr,runWithOwner as Ur,useContext as zr,createContext as Tr,createSignal as Y,createRenderEffect as ao,on as We,startTransition as co,resetErrorBoundaries as lo,batch as uo,untrack as _r,createComponent as ho,children as Jr,mergeProps as po,Show as Se,createRoot as fo,onCleanup as Vr,sharedConfig as Kt,createEffect as Gr}from"https://esm.sh/solid-js@1.9.9";import mo from"https://esm.sh/@paroicms/tiny-modal@0.7.2";function go(t){let e=t;const n=e.indexOf("?");n!==-1&&(e=e.substring(0,n));const r=e.indexOf("#");r!==-1&&(e=e.substring(0,r));const i=e.lastIndexOf("/");return i===-1?void 0:e.slice(0,i)}function X(t){return t!=null&&t!==""}const jn=(t,e)=>new RegExp(t,e);Object.assign(jn,{cast:jn});const He=t=>Array.isArray(t)?t:[t],yo=(t,e)=>{const n=[[],[]];for(const r of t)e(r)?n[0].push(r):n[1].push(r);return n},Wr=Array,le=(t,e)=>t.includes(e),bo=(t,e=0)=>[...new Array(t)].map((n,r)=>r+e),N=(t,e,n)=>t===void 0?e===void 0?[]:Array.isArray(e)?e:[e]:(Array.isArray(e)?t.push(...e):t.push(e),t),ge=(t,e)=>e==null?t??[]:t==null?He(e):t.concat(e),$o=(...t)=>t.reduce(ge,[]),ye=(t,e,n)=>{if(t===void 0)return Array.isArray(e)?e:[e];const r=n?.isEqual??((i,s)=>i===s);for(const i of He(e))t.some(s=>r(s,i))||t.push(i);return t},wo=(t,e)=>t.reduce((n,r)=>{const i=r[e];return n[i]=N(n[i],r),n},{}),Ce=(t,e,n)=>t.length===e.length&&t.every(n?.isEqual?(r,i)=>n.isEqual(r,e[i]):(r,i)=>r===e[i]),$e=(t,e)=>Q(t)===e,Q=t=>{const e=typeof t;return e==="object"?t===null?"null":"object":e==="function"?"object":e},re={boolean:"boolean",null:"null",undefined:"undefined",bigint:"a bigint",number:"a number",object:"an object",string:"a string",symbol:"a symbol"},vo={...re,function:"a function"};class xo extends Error{}const D=t=>Me(t,xo),Me=(t,e=Error)=>{throw new e(t)};class ko extends Error{name="ParseError"}const d=t=>Me(t,ko),Hr=t=>` ${t}`,Ao="",O=(t,e)=>{const n={},r=Array.isArray(t);let i=!1;for(const[s,o]of Object.entries(t).entries()){const a=r?e(s,o[1]):e(...o,s);i||=typeof a[0]=="number";const l=Array.isArray(a[0])||a.length===0?a:[a];for(const[c,u]of l)typeof c=="object"?n[c.group]=N(n[c.group],u):n[c]=u}return i?Object.values(n):n},Zr=Object.entries,te=(t,e)=>t in e,mn=(t,e)=>e in t;class Io{constructor(e){Object.assign(this,e)}}const So=class{};class Yr extends So{}const No=(t,e)=>{const n={},r={};let i;for(i in t)i in e?n[i]=t[i]:r[i]=t[i];return[n,r]},Qr=(t,e)=>No(t,e)[1],Ze=t=>Object.keys(t).length===0,ft=t=>[...Object.entries(t),...Object.getOwnPropertySymbols(t).map(e=>[e,t[e]])],Oo=(t,e)=>Object.defineProperties(t,Object.getOwnPropertyDescriptors(e)),Ro=t=>{const e=Object.keys(t).sort(),n={};for(let r=0;r<e.length;r++)n[e[r]]=t[e[r]];return n},ee=Hr(`unset${Ao}`),Co=t=>Object.values(t).filter(e=>typeof e=="number"?!0:typeof t[e]!="number"),Xr={Array:Array,Boolean:Boolean,Date:Date,Error:Error,Function:Function,Map:Map,Number:Number,Promise:Promise,RegExp:RegExp,Set:Set,String:String,WeakMap:WeakMap,WeakSet:WeakSet},ei=globalThis.File??Blob,ti={ArrayBuffer:ArrayBuffer,Blob:Blob,File:ei,FormData:FormData,Headers:Headers,Request:Request,Response:Response,URL:URL},Mo={Int8Array:Int8Array,Uint8Array:Uint8Array,Uint8ClampedArray:Uint8ClampedArray,Int16Array:Int16Array,Uint16Array:Uint16Array,Int32Array:Int32Array,Uint32Array:Uint32Array,Float32Array:Float32Array,Float64Array:Float64Array,BigInt64Array:BigInt64Array,BigUint64Array:BigUint64Array},Pe={...Xr,...ti,...Mo,String:String,Number:Number,Boolean:Boolean},gn=t=>{let e=Object.getPrototypeOf(t);for(;e?.constructor&&(!te(e.constructor.name,Pe)||!(t instanceof Pe[e.constructor.name]));)e=Object.getPrototypeOf(e);const n=e?.constructor?.name;if(!(n===void 0||n==="Object"))return n},Gt=t=>typeof t=="object"&&t!==null?gn(t)??"object":Q(t),F=Array.isArray,Po={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"},qo={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"},Eo={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"},Ko={...Po,...qo,...Eo},yn=t=>{const e=Object(t).name??null;return e&&te(e,Pe)&&Pe[e]===t?e:null},Fn=(t,e)=>{let n=t.prototype;for(;n!==null;){if(n===e.prototype)return!0;n=Object.getPrototypeOf(n)}return!1},Do=t=>ni(t,new Map),ni=(t,e)=>{if(typeof t!="object"||t===null)return t;if(e?.has(t))return e.get(t);const n=yn(t.constructor);if(n==="Date")return new Date(t.getTime());if(n&&n!=="Array")return t;const r=Array.isArray(t)?t.slice():Object.create(Object.getPrototypeOf(t)),i=Object.getOwnPropertyDescriptors(t);if(e){e.set(t,r);for(const s in i){const o=i[s];"get"in o||"set"in o||(o.value=ni(o.value,e))}}return Object.defineProperties(r,i),r},Lo=t=>{let e=ee;return()=>e===ee?e=t():e},At=t=>typeof t=="function"&&t.length===0,Bo=class extends Function{constructor(...t){const e=t.slice(0,-1),n=t.at(-1);try{super(...e,n)}catch(r){return D(`Encountered an unexpected error while compiling your definition:\n Message: ${r} \n Source: (${t.slice(0,-1)}) => {\n ${t.at(-1)}\n }`)}}};class pe{constructor(e,...[n]){return Object.assign(Object.setPrototypeOf(e.bind(n?.bind??this),this.constructor.prototype),n?.attach)}}const jo=Lo(()=>{try{return new Function("return false")()}catch{return!0}});class ne{constructor(){}}const Fo=()=>{try{return(((new Error).stack?.split(`\n`)[2]?.trim()||"").match(/\(?(.+?)(?::\d+:\d+)?\)?$/)?.[1]||"unknown").replace(/^file:\/\//,"")}catch{return"unknown"}},Uo=globalThis.process?.env??{},zo={fileName:Fo,env:Uo},To=t=>t[0].toUpperCase()+t.slice(1),ri=t=>new RegExp(_o(t),typeof t=="string"?"":t.flags),_o=t=>`^(?:${typeof t=="string"?t:t.source})$`,ue={negativeLookahead:t=>`(?!${t})`,nonCapturingGroup:t=>`(?:${t})`},ze="\\",It={" ":1,"\n":1,"\t":1},Jo=/^-0\.?0*$/.source,ii=/[1-9]\d*/.source,Vo=/\.\d+/.source,Go=/\.\d*[1-9]/.source,si=t=>ri(ue.negativeLookahead(Jo)+ue.nonCapturingGroup("-?"+ue.nonCapturingGroup(ue.nonCapturingGroup("0|"+ii)+ue.nonCapturingGroup(t.decimalPattern)+"?")+(t.allowDecimalOnly?"|"+t.decimalPattern:"")+"?")),Un=si({decimalPattern:Go,allowDecimalOnly:!1}),Wo=Un.test.bind(Un),Wt=si({decimalPattern:Vo,allowDecimalOnly:!0});Wt.test.bind(Wt);const Ho=/^-?\d*\.?\d*$/,Zo=t=>t.length!==0&&Ho.test(t),mt=ri(ue.negativeLookahead("^-0$")+"-?"+ue.nonCapturingGroup(ue.nonCapturingGroup("0|"+ii))),Yo=mt.test.bind(mt),Ht=/^-?\d+$/,Qo=Ht.test.bind(Ht),oi={number:"a number",bigint:"a bigint",integer:"an integer"},ai=(t,e)=>`'${t}' was parsed as ${oi[e]} but could not be narrowed to a literal value. Avoid unnecessary leading or trailing zeros and other abnormal notation`,Xo=(t,e)=>e==="number"?Wo(t):Yo(t),ea=(t,e)=>e==="number"?Number(t):Number.parseInt(t),ta=(t,e)=>e==="number"?Zo(t):Qo(t),na=(t,e)=>bn(t,"number",e),ra=(t,e)=>bn(t,"number",{...e,strict:!0}),ia=(t,e)=>bn(t,"integer",e),bn=(t,e,n)=>{const r=ea(t,e);return!Number.isNaN(r)&&ta(t,e)?n?.strict?Xo(t,e)?r:d(ai(t,e)):r:n?.errorOnFail?d(n?.errorOnFail===!0?`Failed to parse ${oi[e]} from '${t}'`:n?.errorOnFail):void 0},sa=t=>{if(t[t.length-1]!=="n")return;const e=t.slice(0,-1);let n;try{n=BigInt(e)}catch{return}if(mt.test(e))return n;if(Ht.test(e))return d(ai(t,"bigint"))},oa="0.50.0",aa={version:oa,filename:zo.fileName(),FileConstructor:ei},Ye=aa,zn=new Map,Dt=Object.create(null),Zt=t=>{const e=zn.get(t);if(e)return e;let n=ca(t);return Dt[n]?n=`${n}${Dt[n]++}`:Dt[n]=1,Ye[n]=t,zn.set(t,n),n},Ve=t=>/^[$A-Z_a-z][\w$]*$/.test(t),ca=t=>{switch(typeof t){case"object":{if(t===null)break;const e=gn(t)??"object";return e[0].toLowerCase()+e.slice(1)}case"function":return Ve(t.name)?t.name:"fn";case"symbol":return t.description&&Ve(t.description)?t.description:"symbol"}return D(`Unexpected attempt to register serializable value of type ${Q(t)}`)},$n=t=>typeof t=="string"?JSON.stringify(t):typeof t=="bigint"?`${t}n`:`${t}`,la=(t,e={})=>Te(t,{onUndefined:"$ark.undefined",onBigInt:n=>`$ark.bigint-${n}`,...e},[]),S=(t,e)=>{switch(Q(t)){case"object":const n=t,r=n.constructor.name;return r==="Object"||r==="Array"?e?.quoteKeys===!1?gt(n,e?.indent??0,""):JSON.stringify(Te(n,qe,[]),null,e?.indent):gt(n,e?.indent??0,"");case"symbol":return qe.onSymbol(t);default:return $n(t)}},gt=(t,e,n)=>{if(typeof t=="function")return qe.onFunction(t);if(typeof t!="object"||t===null)return $n(t);const r=n+" ".repeat(e);if(Array.isArray(t)){if(t.length===0)return"[]";const s=t.map(o=>gt(o,e,r)).join(`,\n`+r);return e?`[\n${r}${s}\n${n}]`:`[${s}]`}const i=t.constructor.name;if(i==="Object"){const s=ft(t).map(([o,a])=>{const l=typeof o=="symbol"?qe.onSymbol(o):Ve(o)?o:JSON.stringify(o),c=gt(a,e,r);return`${r}${l}: ${c}`});return s.length===0?"{}":e?`{\n${s.join(`,\n`)}\n${n}}`:`{${s.join(", ")}}`}return t instanceof Date?Qe(t):"expression"in t&&typeof t.expression=="string"?t.expression:i},qe={onCycle:()=>"(cycle)",onSymbol:t=>`Symbol(${Zt(t)})`,onFunction:t=>`Function(${Zt(t)})`},Te=(t,e,n)=>{switch(Q(t)){case"object":{const r=t;if("toJSON"in r&&typeof r.toJSON=="function")return r.toJSON();if(typeof r=="function")return qe.onFunction(r);if(n.includes(r))return"(cycle)";const i=[...n,r];if(Array.isArray(r))return r.map(o=>Te(o,e,i));if(r instanceof Date)return r.toDateString();const s={};for(const o in r)s[o]=Te(r[o],e,i);for(const o of Object.getOwnPropertySymbols(r))s[e.onSymbol?.(o)??o.toString()]=Te(r[o],e,i);return s}case"symbol":return qe.onSymbol(t);case"bigint":return e.onBigInt?.(t)??`${t}n`;case"undefined":return e.onUndefined??"undefined";case"string":return t.replaceAll("\\","\\\\");default:return t}},Qe=t=>{const e=t.getFullYear(),n=t.getMonth(),r=t.getDate(),i=t.getHours(),s=t.getMinutes(),o=t.getSeconds(),a=t.getMilliseconds();if(n===0&&r===1&&i===0&&s===0&&o===0&&a===0)return`${e}`;const l=`${ua[n]} ${r}, ${e}`;if(i===0&&s===0&&o===0&&a===0)return l;let c=t.toLocaleTimeString();const u=c.endsWith(" AM")||c.endsWith(" PM")?c.slice(-3):"";return u&&(c=c.slice(0,-u.length)),a?c+=`.${ha(a,3)}`:da.test(c)&&(c=c.slice(0,-3)),`${c+u}, ${l}`},ua=["January","February","March","April","May","June","July","August","September","October","November","December"],da=/:\d\d:00$/,ha=(t,e)=>String(t).padStart(e,"0"),ci=(t,e,...[n])=>{const r=n?.stringifySymbol??S;let i=t;switch(typeof e){case"string":i=Ve(e)?t===""?e:`${t}.${e}`:`${t}[${JSON.stringify(e)}]`;break;case"number":i=`${t}[${e}]`;break;case"symbol":i=`${t}[${r(e)}]`;break;default:n?.stringifyNonKey?i=`${t}[${n.stringifyNonKey(e)}]`:d(`${S(e)} must be a PropertyKey or stringifyNonKey must be passed to options`)}return i},Xe=(t,...e)=>t.reduce((n,r)=>ci(n,r,...e),"");class li extends Wr{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"?S(this[e]):this[e]);return this.cache.json}stringify(){return this.cache.stringify?this.cache.stringify:this.cache.stringify=Xe(this)}stringifyAncestors(){if(this.cache.stringifyAncestors)return this.cache.stringifyAncestors;let e="";const n=[e];for(const r of this)e=ci(e,r),n.push(e);return this.cache.stringifyAncestors=n}}class ui{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 n="";for(;this.lookahead&&!e(this,n);)n+=this.shift();return n}shiftUntilEscapable(e){let n="";for(;this.lookahead;)if(this.lookahead===ze)this.shift(),e(this,n)?n+=this.shift():this.lookahead===ze?n+=this.shift():n+=`${ze}${this.shift()}`;else{if(e(this,n))break;n+=this.shift()}return n}shiftUntilLookahead(e){return typeof e=="string"?this.shiftUntil(n=>n.lookahead===e):this.shiftUntil(n=>n.lookahead in e)}shiftUntilNonWhitespace(){return this.shiftUntil(()=>!(this.lookahead in It))}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,n){return this.chars.slice(e,n).join("")}lookaheadIs(e){return this.lookahead===e}lookaheadIsIn(e){return this.lookahead in e}}const pa=(t,e)=>`Unmatched ${t}${e===""?"":` before ${e}`}`,di=t=>`Missing ${t}`;let Yt="$ark",fa=2;for(;Yt in globalThis;)Yt=`$ark${fa++}`;const hi=Yt;globalThis[hi]=Ye;const p=Ye,ma=t=>`${hi}.${t}`,z=t=>ma(Zt(t));class pi extends Yr{argNames;body="";constructor(...e){super(),this.argNames=e;for(const n of e){if(n in this)throw new Error(`Arg name '${n}' would overwrite an existing property on FunctionBody`);this[n]=n}}indentation=0;indent(){return this.indentation+=4,this}dedent(){return this.indentation-=4,this}prop(e,n=!1){return fi(e,n)}index(e,n=!1){return mi(`${e}`,n)}line(e){return this.body+=`${" ".repeat(this.indentation)}${e}\n`,this}const(e,n){return this.line(`const ${e} = ${n}`),this}let(e,n){return this.line(`let ${e} = ${n}`)}set(e,n){return this.line(`${e} = ${n}`)}if(e,n){return this.block(`if (${e})`,n)}elseIf(e,n){return this.block(`else if (${e})`,n)}else(e){return this.block("else",e)}for(e,n,r=0){return this.block(`for (let i = ${r}; ${e}; i++)`,n)}forIn(e,n){return this.block(`for (const k in ${e})`,n)}block(e,n,r=""){return this.line(`${e} {`),this.indent(),n(this),this.dedent(),this.line(`}${r}`)}return(e=""){return this.line(`return ${e}`)}write(e="anonymous",n=0){return`${e}(${this.argNames.join(", ")}) { ${n?this.body.split(`\n`).map(r=>" ".repeat(n)+`${r}`).join(`\n`):this.body} }`}compile(){return new Bo(...this.argNames,this.body)}}const et=t=>$e(t,"object")||typeof t=="symbol"?z(t):$n(t),fi=(t,e=!1)=>typeof t=="string"&&Ve(t)?`${e?"?":""}.${t}`:mi(ga(t),e),ga=t=>typeof t=="symbol"?z(t):JSON.stringify(t),mi=(t,e=!1)=>`${e?"?.":""}[${t}]`;class Lt extends pi{traversalKind;optimistic;constructor(e){super("data","ctx"),this.traversalKind=e.kind,this.optimistic=e.optimistic===!0}invoke(e,n){const r=n?.arg??this.data,i=typeof e=="string"?!0:this.requiresContextFor(e),s=typeof e=="string"?e:e.id;return i?`${this.referenceToId(s,n)}(${r}, ${this.ctx})`:`${this.referenceToId(s,n)}(${r})`}referenceToId(e,n){const r=n?.kind??this.traversalKind,i=`this.${e}${r}`;return n?.bind?`${i}.bind(${n?.bind})`:i}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,n,r){const i=this.requiresContextFor(r);return i&&this.line(`${this.ctx}.path.push(${e})`),this.check(r,{arg:n}),i&&this.line(`${this.ctx}.path.pop()`),this}check(e,n){return this.traversalKind==="Allows"?this.if(`!${this.invoke(e,n)}`,()=>this.return(!1)):this.line(this.invoke(e,n))}}const gi=t=>O(t,(e,n)=>[e,F(n)?[...n]:n]),ie=Hr("arkKind"),b=(t,e)=>t?.[ie]===e,U=t=>b(t,"root")||b(t,"constraint"),ya=["unit","proto","domain"],St=["required","optional","index","sequence"],yi=["pattern","divisor","exactLength","max","min","maxLength","minLength","before","after"],bi=[...yi,"structure","predicate"],wn=[...bi,...St],Nt=["alias","union","morph","unit","intersection","proto","domain"],ba=[...Nt,...wn],$i=O(wn,(t,e)=>[e,1]),$a=O([...St,"undeclared"],(t,e)=>[e,1]),wi=O(ba,(t,e)=>[e,t]),ut=t=>typeof t=="string"&&t in wi,yt=t=>wi[t],vn=t=>Nt.slice(yt(t)+1);[...vn("union")];[...vn("morph")];const be=t=>typeof t=="string"||typeof t=="boolean"||t===null?t:typeof t=="number"?Number.isNaN(t)?"NaN":t===Number.POSITIVE_INFINITY?"Infinity":t===Number.NEGATIVE_INFINITY?"-Infinity":t:et(t),Ot=t=>{let e="{ ";for(const[n,r]of Object.entries(t))e+=`${n}: ${et(r)}, `;return e+" }"},q=t=>{const e=t;return e.hasAssociatedError&&(e.defaults.expected??=n=>"description"in n?n.description:e.defaults.description(n),e.defaults.actual??=n=>S(n),e.defaults.problem??=n=>`must be ${n.expected}${n.actual?` (was ${n.actual})`:""}`,e.defaults.message??=n=>{if(n.path.length===0)return n.problem;const r=`${n.propString} ${n.problem}`;return r[0]==="["?`value at ${r}`:r}),e};class wa extends Error{name="ToJsonSchemaError";code;context;constructor(e,n){super(S(n,{quoteKeys:!1,indent:4})),this.code=e,this.context=n}hasCode(e){return this.code===e}}const va={dialect:"https://json-schema.org/draft/2020-12/schema",useRefs:!1,fallback:{arrayObject:t=>L.throw("arrayObject",t),arrayPostfix:t=>L.throw("arrayPostfix",t),defaultValue:t=>L.throw("defaultValue",t),domain:t=>L.throw("domain",t),morph:t=>L.throw("morph",t),patternIntersection:t=>L.throw("patternIntersection",t),predicate:t=>L.throw("predicate",t),proto:t=>L.throw("proto",t),symbolKey:t=>L.throw("symbolKey",t),unit:t=>L.throw("unit",t),date:t=>L.throw("date",t)}},L={Error:wa,throw:(...t)=>{throw new L.Error(...t)},throwInternalOperandError:(t,e)=>D(`Unexpected JSON Schema input for ${t}: ${S(e)}`),defaultConfig:va};p.config??={};const Qt=(t,e)=>{if(!e)return t;const n={...t};let r;for(r in e){const i={...t.keywords};if(r==="keywords"){for(const s in e[r]){const o=e.keywords[s];o!==void 0&&(i[s]=typeof o=="string"?{description:o}:o)}n.keywords=i}else r==="toJsonSchema"?n[r]=vi(t.toJsonSchema,e.toJsonSchema):ut(r)?n[r]={...t[r],...e[r]}:n[r]=e[r]}return n},vi=(t,e)=>{if(!t)return e??{};if(!e)return t;const n={...t};let r;for(r in e)r==="fallback"?n.fallback=xa(t.fallback,e.fallback):n[r]=e[r];return n},xa=(t,e)=>{t=Tn(t),e=Tn(e);const n={};let r;for(r in L.defaultConfig.fallback)n[r]=e[r]??e.default??t[r]??t.default??L.defaultConfig.fallback[r];return n},Tn=t=>typeof t=="function"?{default:t}:t??{};class Ee extends Yr{[ie]="error";path;data;nodeConfig;input;ctx;constructor({prefixPath:e,relativePath:n,...r},i){super(),this.input=r,this.ctx=i,Oo(this,r);const s=i.data;r.code==="union"&&(r.errors=r.errors.flatMap(a=>{const l=a.hasCode("union")?a.errors:[a];return!e&&!n?l:l.map(c=>c.transform(u=>({...u,path:$o(e,u.path,n)})))})),this.nodeConfig=i.config[this.code];const o=[...r.path??i.path];n&&o.push(...n),e&&o.unshift(...e),this.path=new li(...o),this.data="data"in r?r.data:s}transform(e){return new Ee(e({data:this.data,path:this.path,...this.input}),this.ctx)}hasCode(e){return this.code===e}get propString(){return Xe(this.path)}get expected(){if(this.input.expected)return this.input.expected;const 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;const 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;const e=this.meta?.problem??this.nodeConfig.problem;return typeof e=="function"?e(this):e}get message(){if(this.input.message)return this.input.message;const 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}}class he extends Wr{[ie]="errors";ctx;constructor(e){super(),this.ctx=e}byPath=Object.create(null);get flatByPath(){return O(this.byPath,(e,n)=>[e,n.flat])}get flatProblemsByPath(){return O(this.byPath,(e,n)=>[e,n.flat.map(r=>r.problem)])}byAncestorPath=Object.create(null);count=0;mutable=this;throw(){throw this.toTraversalError()}toTraversalError(){return new ka(this)}add(e){const n=this.byPath[e.propString];if(n){if(e===n||n.hasCode("union")&&n.errors.length===0)return;const r=e.hasCode("union")&&e.errors.length===0?e:new Ee({code:"intersection",errors:n.hasCode("intersection")?[...n.errors,e]:[n,e]},this.ctx),i=this.indexOf(n);this.mutable[i===-1?this.length:i]=r,this.byPath[e.propString]=r,this.addAncestorPaths(e)}else this.byPath[e.propString]=e,this.addAncestorPaths(e),this.mutable.push(e);this.count++}transform(e){const n=new he(this.ctx);for(const r of this)n.add(e(r));return n}merge(e){for(const n of e)this.add(new Ee({...n,path:[...this.ctx.path,...n.path]},this.ctx))}affectsPath(e){return this.length===0?!1:e.stringifyAncestors().some(n=>n 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(`\n`)}addAncestorPaths(e){for(const n of e.path.stringifyAncestors())this.byAncestorPath[n]=N(this.byAncestorPath[n],e)}}class ka extends Error{name="TraversalError";constructor(e){e.length===1?super(e.summary):super(`\n`+e.map(n=>` • ${Aa(n)}`).join(`\n`)),Object.defineProperty(this,"arkErrors",{value:e,enumerable:!1})}}const Aa=t=>t.toString().split(`\n`).join(`\n `);class Ne{path=[];errors=new he(this);root;config;queuedMorphs=[];branches=[];seen={};constructor(e,n){this.root=e,this.config=n}get data(){let e=this.root;for(const n of this.path)e=e?.[n];return e}get propString(){return Xe(this.path)}reject(e){return this.error(e),!1}mustBe(e){return this.error(e),!1}error(e){const n=typeof e=="object"?e.code?e:{...e,code:"predicate"}:{code:"predicate",expected:e};return this.errorFromContext(n)}hasError(){return this.currentErrorCount!==0}get currentBranch(){return this.branches.at(-1)}queueMorphs(e){const n={path:new li(...this.path),morphs:e};this.currentBranch?this.currentBranch.queuedMorphs.push(n):this.queuedMorphs.push(n)}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){const n=new Ee(e,this);return this.currentBranch?this.currentBranch.error=n:this.errors.add(n),n}applyQueuedMorphs(){for(;this.queuedMorphs.length;){const e=this.queuedMorphs;this.queuedMorphs=[];for(const{path:n,morphs:r}of e)this.errors.affectsPath(n)||this.applyMorphsAtPath(n,r)}}applyMorphsAtPath(e,n){const r=e.at(-1);let i;if(r!==void 0){i=this.root;for(let s=0;s<e.length-1;s++)i=i[e[s]]}for(const s of n){this.path=[...e];const o=U(s),a=s(i===void 0?this.root:i[r],this);if(a instanceof Ee){this.errors.add(a);break}if(a instanceof he){o||this.errors.merge(a),this.queuedMorphs=[];break}i===void 0?this.root=a:i[r]=a,this.applyQueuedMorphs()}}}const se=(t,e,n)=>{if(!n)return e();n.path.push(t);const r=e();return n.path.pop(),r};class xi extends pe{attachments;$;onFail;includesTransform;includesContextualPredicate;isCyclic;allowsRequiresContext;rootApplyStrategy;contextFreeMorph;rootApply;referencesById;shallowReferences;flatRefs;flatMorphs;allows;get shallowMorphs(){return[]}constructor(e,n){super((i,s,o=this.onFail)=>s?(this.traverseApply(i,s),s.hasError()?s.errors:s.data):this.rootApply(i,o),{attach:e}),this.attachments=e,this.$=n,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((i,s)=>Oa(i,s.shallowReferences),[this]);const r=this.isStructural();this.flatRefs=[],this.flatMorphs=[];for(let i=0;i<this.children.length;i++){if(this.includesTransform||=this.children[i].includesTransform,this.includesContextualPredicate||=this.children[i].includesContextualPredicate,this.isCyclic||=this.children[i].isCyclic,!r){const s=this.children[i].flatRefs;for(let o=0;o<s.length;o++){const a=s[o];if(!this.flatRefs.some(l=>ki(l,a))){this.flatRefs.push(a);for(const l of a.node.branches)(l.hasKind("morph")||l.hasKind("intersection")&&l.structure?.structuralMorph!==void 0)&&this.flatMorphs.push({path:a.path,propString:a.propString,node:l})}}}Object.assign(this.referencesById,this.children[i].referencesById)}this.flatRefs.sort((i,s)=>i.path.length>s.path.length?1:i.path.length<s.path.length?-1:i.propString>s.propString?1:i.propString<s.propString||i.node.expression<s.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(i=>i.length===1||i.name==="$arkStructuralMorph")?this.hasKind("union")?this.branches.some(i=>i.shallowMorphs.length>1)?"contextual":"branchedOptimistic":this.shallowMorphs.length>1?"contextual":"optimistic":"contextual":"contextual",this.rootApply=this.createRootApply(),this.allows=this.allowsRequiresContext?i=>this.traverseAllows(i,new Ne(i,this.$.resolvedConfig)):i=>this.traverseAllows(i)}createRootApply(){switch(this.rootApplyStrategy){case"allows":return(n,r)=>{if(this.allows(n))return n;const i=new Ne(n,this.$.resolvedConfig);return this.traverseApply(n,i),i.finalize(r)};case"contextual":return(n,r)=>{const i=new Ne(n,this.$.resolvedConfig);return this.traverseApply(n,i),i.finalize(r)};case"optimistic":this.contextFreeMorph=this.shallowMorphs[0];const e=this.$.resolvedConfig.clone;return(n,r)=>{if(this.allows(n))return this.contextFreeMorph(e&&(typeof n=="object"&&n!==null||typeof n=="function")?e(n):n);const i=new Ne(n,this.$.resolvedConfig);return this.traverseApply(n,i),i.finalize(r)};case"branchedOptimistic":return this.createBranchedOptimisticRootApply();default:return this.rootApplyStrategy,D(`Unexpected rootApplyStrategy ${this.rootApplyStrategy}`)}}compiledMeta=Na(this.metaJson);cacheGetter(e,n){return Object.defineProperty(this,e,{value:n}),n}get description(){return this.cacheGetter("description",this.meta?.description??this.$.resolvedConfig[this.kind].description(this))}get references(){return Object.values(this.referencesById)}precedence=yt(this.kind);precompilation;assert=(e,n)=>this(e,n,r=>r.throw());traverse(e,n){return this(e,n,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;const n={};for(const[r,i]of this.innerEntries){const s=this.impl.keys[r];if(s.reduceIo)s.reduceIo(e,n,i);else if(s.child){const o=i;n[r]=F(o)?o.map(a=>e==="in"?a.rawIn:a.rawOut):e==="in"?o.rawIn:o.rawOut}else n[r]=i}return this.$.node(this.kind,n)}toJSON(){return this.json}toString(){return`Type<${this.expression}>`}equals(e){const n=U(e)?e:this.$.parseDefinition(e);return this.innerHash===n.innerHash}ifEquals(e){return this.equals(e)?this:void 0}hasKind(e){return this.kind===e}assertHasKind(e){return this.kind!==e&&Me(`${this.kind} node was not of asserted kind ${e}`),this}hasKindIn(...e){return e.includes(this.kind)}assertHasKindIn(...e){return le(e,this.kind)||Me(`${this.kind} node was not one of asserted kinds ${e}`),this}isBasis(){return le(ya,this.kind)}isConstraint(){return le(wn,this.kind)}isStructural(){return le(St,this.kind)}isRefinement(){return le(bi,this.kind)}isRoot(){return le(Nt,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){const n=je.normalize(e);return this._select(n)}_select(e){let n=je.applyBoundary[e.boundary??"references"](this);return e.kind&&(n=n.filter(r=>r.kind===e.kind)),e.where&&(n=n.filter(e.where)),je.applyMethod[e.method??"filter"](n,this,e)}transform(e,n){return this._transform(e,this._createTransformContext(n))}_createTransformContext(e){return{root:this,selected:void 0,seen:{},path:[],parseOptions:{prereduced:e?.prereduced??!1},undeclaredKeyHandling:void 0,...e}}_transform(e,n){const r=n.bindScope??this.$;if(n.seen[this.id])return this.$.lazilyResolve(n.seen[this.id]);if(n.shouldTransform?.(this,n)===!1)return this;let i;n.seen[this.id]=()=>i,this.hasKind("structure")&&this.undeclared!==n.undeclaredKeyHandling&&(n={...n,undeclaredKeyHandling:this.undeclared});const s=O(this.inner,(u,h)=>{if(!this.impl.keys[u].child)return[u,h];const m=h;if(!F(m)){const x=m._transform(e,n);return x?[u,x]:[]}if(m.length===0)return[u,h];const y=m.flatMap(x=>x._transform(e,n)??[]);return y.length?[u,y]:[]});delete n.seen[this.id];const o=Object.assign(s,{meta:this.meta}),a=n.selected&&!n.selected.includes(this)?o:e(this.kind,o,n);if(a===null)return null;if(U(a))return i=a;const l=Object.keys(a);return(l.length===0||l.length===1&&l[0]==="meta")&&!Ze(this.inner)?null:(this.kind==="required"||this.kind==="optional"||this.kind==="index")&&!("value"in a)?n.undeclaredKeyHandling?{...a,value:p.intrinsic.unknown}:null:(this.kind==="morph"&&(a.in??=p.intrinsic.unknown),i=r.node(this.kind,a,n.parseOptions))}configureReferences(e,n="references"){const r=je.normalize(n),i=typeof e=="string"?(l,c)=>({...c,meta:{...c.meta,description:e}}):typeof e=="function"?(l,c)=>({...c,meta:e(c.meta)}):(l,c)=>({...c,meta:{...c.meta,...e}});if(r.boundary==="self")return this.$.node(this.kind,i(this.kind,{...this.inner,meta:this.meta}));const s=this._select(r),o=s&&He(s),a=r.boundary==="child"?(l,c)=>c.root.children.includes(l):r.boundary==="shallow"?l=>l.kind!=="structure":()=>!0;return this.$.finalize(this.transform(i,{shouldTransform:a,selected:o}))}}const je={applyBoundary:{self:t=>[t],child:t=>[...t.children],shallow:t=>[...t.shallowReferences],references:t=>[...t.references]},applyMethod:{filter:t=>t,assertFilter:(t,e,n)=>(t.length===0&&Me(_n(e,n)),t),find:t=>t[0],assertFind:(t,e,n)=>(t.length===0&&Me(_n(e,n)),t[0])},normalize:t=>typeof t=="function"?{boundary:"references",method:"filter",where:t}:typeof t=="string"?te(t,je.applyBoundary)?{method:"filter",boundary:t}:{boundary:"references",method:"filter",kind:t}:{boundary:"references",method:"filter",...t}},_n=(t,e)=>`${t} had no references matching ${S(e)}.`,Ia=t=>Xe(t,{stringifyNonKey:e=>e.expression}),Sa=/"(\$ark\.[^"]+)"/g,Na=t=>JSON.stringify(t).replaceAll(Sa,"$1"),de=(t,e)=>({path:t,node:e,propString:Ia(t)}),ki=(t,e)=>t.propString===e.propString&&t.node.equals(e.node),Jn=(t,e)=>ye(t,e,{isEqual:ki}),Oa=(t,e)=>ye(t,e,{isEqual:(n,r)=>n.equals(r)});class g extends Array{static init(e,n,r,i){return new g({kind:e,l:n,r:r,path:i?.path??[],optional:i?.optional??!1})}add(e,n,r,i){return this.push({kind:e,l:n,r:r,path:i?.path??[],optional:i?.optional??!1}),this}get summary(){return this.describeReasons()}describeReasons(){if(this.length===1){const{path:e,l:n,r:r}=this[0],i=Xe(e);return Ai(`Intersection${i&&` at ${i}`} of ${Vn(n,r)}`)}return`The following intersections result in unsatisfiable types:\n• ${this.map(({path:e,l:n,r:r})=>`${e}: ${Vn(n,r)}`).join(`\n• `)}`}throw(){return d(this.describeReasons())}invert(){const e=this.map(n=>({...n,l:n.r,r:n.l}));return e instanceof g?e:new g(...e)}withPrefixKey(e,n){return this.map(r=>({...r,path:[e,...r.path],optional:r.optional||n==="optional"}))}toNeverIfDisjoint(){return p.intrinsic.never}}const Vn=(t,e)=>`${Xt(t)} and ${Xt(e)}`,Xt=t=>U(t)?t.expression:F(t)?t.map(Xt).join(" | ")||"never":String(t),Ai=t=>`${t} results in an unsatisfiable type`,Ae={},oe=(t,e,n)=>j(t,e,{$:n,invert:!1,pipe:!1}),en=(t,e,n)=>j(t,e,{$:n,invert:!1,pipe:!0}),j=(t,e,n)=>{const r=n.pipe?"|>":"&",i=`${t.hash}${r}${e.hash}`;if(Ae[i]!==void 0)return Ae[i];if(!n.pipe){const a=`${e.hash}${r}${t.hash}`;if(Ae[a]!==void 0){const l=Ae[a],c=l instanceof g?l.invert():l;return Ae[i]=c,c}}const s=!n.pipe||!t.includesTransform&&!e.includesTransform;if(s&&t.equals(e))return t;let o=s?tn(t,e,n):t.hasKindIn(...Nt)?Ra(t,e,n):tn(t,e,n);return U(o)&&(t.equals(o)?o=t:e.equals(o)&&(o=e)),Ae[i]=o,o},tn=(t,e,n)=>{const r=t.precedence<e.precedence?t.kind:e.kind,i=t.impl.intersections[e.kind]??e.impl.intersections[t.kind];if(i===void 0)return null;if(r===t.kind)return i(t,e,n);{let s=i(e,t,{...n,invert:!n.invert});return s instanceof g&&(s=s.invert()),s}},Ra=(t,e,n)=>t.includesTransform||e.includesTransform?n.invert?Gn(e,t,n):Gn(t,e,n):tn(t,e,n),Gn=(t,e,n)=>t.distribute(r=>Ca(r,e,n),r=>{const i=r.filter(U);if(i.length===0)return g.init("union",t.branches,e.branches);if(i.length<t.branches.length||!t.branches.every((o,a)=>o.rawIn.equals(i[a].rawIn)))return n.$.parseSchema(i);if(i.length===1)return i[0];const s={branches:i};return n.$.parseSchema(s)}),Ca=(t,e,n)=>{if(t.hasKind("morph")){const i=[...t.morphs];if(t.lastMorphIfNode){const s=j(t.lastMorphIfNode,e,n);if(s instanceof g)return s;i[i.length-1]=s}else i.push(e);return n.$.node("morph",{morphs:i,in:t.inner.in})}if(e.hasKind("morph")){const i=j(t,e.rawIn,n);return i instanceof g?i:n.$.node("morph",{morphs:[e],in:i})}return n.$.node("morph",{morphs:[e],in:t})};class Ke extends xi{constructor(e,n){super(e,n),Object.defineProperty(this,ie,{value:"constraint",enumerable:!1})}impliedSiblings;intersect(e){return oe(this,e,this.$)}}class Rt extends Ke{traverseApply=(e,n)=>{this.traverseAllows(e,n)||n.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 Ot(this.errorContext)}}const T=t=>(e,n)=>{if(F(e)){if(e.length===0)return;const i=e.map(s=>n.$.node(t,s));return t==="predicate"?i:i.sort((s,o)=>s.hash<o.hash?-1:1)}const r=n.$.node(t,e);return r.hasOpenIntersection()?[r]:r},bt=t=>{const e=t.r.shift();if(!e){let r=t.l.length===0&&t.kind==="structure"?p.intrinsic.unknown.internal:t.ctx.$.node(t.kind,Object.assign(t.baseInner,Ma(t.l)),{prereduced:!0});for(const i of t.roots){if(r instanceof g)return r;r=j(i,r,t.ctx)}return r}let n=!1;for(let r=0;r<t.l.length;r++){const i=j(t.l[r],e,t.ctx);if(i!==null){if(i instanceof g)return i;if(i.isRoot())return t.roots.push(i),t.l.splice(r),bt(t);if(!n)t.l[r]=i,n=!0;else if(!t.l.includes(i))return D(`Unexpectedly encountered multiple distinct intersection results for refinement ${e}`)}}if(n||t.l.push(e),t.kind==="intersection"&&e.impliedSiblings)for(const r of e.impliedSiblings)ye(t.r,r);return bt(t)},$t=t=>Object.entries(t).flatMap(([n,r])=>n in $i?r:[]).sort((n,r)=>n.precedence<r.precedence?-1:n.precedence>r.precedence?1:n.kind==="predicate"&&r.kind==="predicate"?0:n.hash<r.hash?-1:1),Ma=t=>{const e={};for(const n of t)if(n.hasOpenIntersection())e[n.kind]=N(e[n.kind],n);else{if(e[n.kind])return D(`Unexpected intersection of closed refinements of kind ${n.kind}`);e[n.kind]=n}return e},Pa=(...t)=>d(qa(...t)),qa=(t,e,n)=>{const r=n.hasKind("morph")?"a morph":n.isUnknown()?"unknown":n.exclude(e).defaultShortDescription;return`${To(t)} operand must be ${e.description} (was ${r})`},Ea=(t,e,n)=>new wt(t,e,n,n,null);class Ii extends pe{}class wt extends pe{[ie]="generic";paramDefs;bodyDef;$;arg$;baseInstantiation;hkt;description;constructor(e,n,r,i,s){super((...o)=>{const a=O(this.names,(l,c)=>{const u=this.arg$.parse(o[l]);return u.extends(this.constraints[l])||d(Ka(c,this.constraints[l].expression,u.expression)),[c,u]});if(this.defIsLazy()){const l=this.bodyDef(a);return this.$.parse(l)}return this.$.parse(n,{args:a})}),this.paramDefs=e,this.bodyDef=n,this.$=r,this.arg$=i,this.hkt=s,this.description=s?(new s).description??`a generic type for ${s.constructor.name}`:"a generic type",this.baseInstantiation=this(...this.constraints)}defIsLazy(){return this.bodyDef instanceof Ii}cacheGetter(e,n){return Object.defineProperty(this,e,{value:n}),n}get json(){return this.cacheGetter("json",{params:this.params.map(e=>e[1].isUnknown()?e[0]:[e[0],e[1].json]),body:la(this.bodyDef)})}get params(){return this.cacheGetter("params",this.paramDefs.map(e=>typeof e=="string"?[e,p.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 Ka=(t,e,n)=>`${t} must be assignable to ${e} (was ${n})`,Da=q({kind:"predicate",hasAssociatedError:!0,collapsibleKey:"predicate",keys:{predicate:{}},normalize:t=>typeof t=="function"?{predicate:t}:t,defaults:{description:t=>`valid according to ${t.predicate.name||"an anonymous predicate"}`},intersectionIsOpen:!0,intersections:{predicate:()=>null}});class La extends Ke{serializedPredicate=z(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=Ot(this.errorContext);traverseApply=(e,n)=>{!this.predicate(e,n.external)&&!n.hasError()&&n.errorFromNodeContext(this.errorContext)};compile(e){if(e.traversalKind==="Allows"){e.return(this.compiledCondition);return}e.if(`${this.compiledNegation} && !ctx.hasError()`,()=>e.line(`ctx.errorFromNodeContext(${this.compiledErrorContext})`))}reduceJsonSchema(e,n){return n.fallback.predicate({code:"predicate",base:e,predicate:this.predicate})}}const Si={implementation:Da,Node:La},Ba=q({kind:"divisor",collapsibleKey:"rule",keys:{rule:{parse:t=>Number.isInteger(t)?t:d(Fa(t))}},normalize:t=>typeof t=="number"?{rule:t}:t,hasAssociatedError:!0,defaults:{description:t=>t.rule===1?"an integer":t.rule===2?"even":`a multiple of ${t.rule}`},intersections:{divisor:(t,e,n)=>n.$.node("divisor",{rule:Math.abs(t.rule*e.rule/Ua(t.rule,e.rule))})},obviatesBasisDescription:!0});class ja extends Rt{traverseAllows=e=>e%this.rule===0;compiledCondition=`data % ${this.rule} === 0`;compiledNegation=`data % ${this.rule} !== 0`;impliedBasis=p.intrinsic.number.internal;expression=`% ${this.rule}`;reduceJsonSchema(e){return e.type="integer",this.rule===1||(e.multipleOf=this.rule),e}}const Ni={implementation:Ba,Node:ja},Fa=t=>`divisor must be an integer (was ${t})`,Ua=(t,e)=>{let n,r=t,i=e;for(;i!==0;)n=i,i=r%i,r=n;return r};class De extends Rt{boundOperandKind=Ja[this.kind];compiledActual=this.boundOperandKind==="value"?"data":this.boundOperandKind==="length"?"data.length":"data.valueOf()";comparator=Va(this.kind,this.exclusive);numericLimit=this.rule.valueOf();expression=`${this.comparator} ${this.rule}`;compiledCondition=`${this.compiledActual} ${this.comparator} ${this.numericLimit}`;compiledNegation=`${this.compiledActual} ${za[this.comparator]} ${this.numericLimit}`;stringLimit=this.boundOperandKind==="date"?Ga(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 za={"<":">=","<=":">",">":"<=",">=":"<"},Ta={min:"max",minLength:"maxLength",after:"before"},Oi={parse:t=>t||void 0},Ri=t=>e=>{if(typeof e=="number")return{rule:e};const{exclusive:n,...r}=e;return n?{...r,rule:t==="minLength"?r.rule+1:r.rule-1}:r},Ci=t=>e=>{if(typeof e=="number"||typeof e=="string"||e instanceof Date)return{rule:e};const{exclusive:n,...r}=e;if(!n)return r;const i=typeof r.rule=="number"?r.rule:typeof r.rule=="string"?new Date(r.rule).valueOf():r.rule.valueOf();return n?{...r,rule:t==="after"?i+1:i-1}:r},Mi=t=>typeof t=="string"||typeof t=="number"?new Date(t):t,_a=(t,e)=>`${t} bound must be a positive integer (was ${e})`,xn=t=>e=>((!Number.isInteger(e)||e<0)&&d(_a(t,e)),e),Ja={min:"value",max:"value",minLength:"length",maxLength:"length",after:"date",before:"date"},Va=(t,e)=>`${te(t,Ta)?">":"<"}${e?"":"="}`,Ga=t=>typeof t=="string"?t:new Date(t).toLocaleString(),Wa=t=>`Bounded expression ${t} must be exactly one of number, string, Array, or Date`,Ha=q({kind:"after",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{parse:Mi,serialize:t=>t.toISOString()}},normalize:Ci("after"),defaults:{description:t=>`${t.collapsibleLimitString} or later`,actual:Qe},intersections:{after:(t,e)=>t.isStricterThan(e)?t:e}});class Za extends De{impliedBasis=p.intrinsic.Date.internal;collapsibleLimitString=Qe(this.rule);traverseAllows=e=>e>=this.rule;reduceJsonSchema(e,n){return n.fallback.date({code:"date",base:e,after:this.rule})}}const Pi={implementation:Ha,Node:Za},Ya=q({kind:"before",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{parse:Mi,serialize:t=>t.toISOString()}},normalize:Ci("before"),defaults:{description:t=>`${t.collapsibleLimitString} or earlier`,actual:Qe},intersections:{before:(t,e)=>t.isStricterThan(e)?t:e,after:(t,e,n)=>t.overlapsRange(e)?t.overlapIsUnit(e)?n.$.node("unit",{unit:t.rule}):null:g.init("range",t,e)}});class Qa extends De{collapsibleLimitString=Qe(this.rule);traverseAllows=e=>e<=this.rule;impliedBasis=p.intrinsic.Date.internal;reduceJsonSchema(e,n){return n.fallback.date({code:"date",base:e,before:this.rule})}}const qi={implementation:Ya,Node:Qa},Xa=q({kind:"exactLength",collapsibleKey:"rule",keys:{rule:{parse:xn("exactLength")}},normalize:t=>typeof t=="number"?{rule:t}:t,hasAssociatedError:!0,defaults:{description:t=>`exactly length ${t.rule}`,actual:t=>`${t.length}`},intersections:{exactLength:(t,e,n)=>g.init("unit",n.$.node("unit",{unit:t.rule}),n.$.node("unit",{unit:e.rule}),{path:["length"]}),minLength:(t,e)=>t.rule>=e.rule?t:g.init("range",t,e),maxLength:(t,e)=>t.rule<=e.rule?t:g.init("range",t,e)}});class ec extends Rt{traverseAllows=e=>e.length===this.rule;compiledCondition=`data.length === ${this.rule}`;compiledNegation=`data.length !== ${this.rule}`;impliedBasis=p.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 L.throwInternalOperandError("exactLength",e)}}}const Ei={implementation:Xa,Node:ec},tc=q({kind:"max",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{},exclusive:Oi},normalize:t=>typeof t=="number"?{rule:t}:t,defaults:{description:t=>t.rule===0?t.exclusive?"negative":"non-positive":`${t.exclusive?"less than":"at most"} ${t.rule}`},intersections:{max:(t,e)=>t.isStricterThan(e)?t:e,min:(t,e,n)=>t.overlapsRange(e)?t.overlapIsUnit(e)?n.$.node("unit",{unit:t.rule}):null:g.init("range",t,e)},obviatesBasisDescription:!0});class nc extends De{impliedBasis=p.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}}const Ki={implementation:tc,Node:nc},rc=q({kind:"maxLength",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{parse:xn("maxLength")}},reduce:(t,e)=>t.rule===0?e.node("exactLength",t):void 0,normalize:Ri("maxLength"),defaults:{description:t=>`at most length ${t.rule}`,actual:t=>`${t.length}`},intersections:{maxLength:(t,e)=>t.isStricterThan(e)?t:e,minLength:(t,e,n)=>t.overlapsRange(e)?t.overlapIsUnit(e)?n.$.node("exactLength",{rule:t.rule}):null:g.init("range",t,e)}});class ic extends De{impliedBasis=p.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 L.throwInternalOperandError("maxLength",e)}}}const Di={implementation:rc,Node:ic},sc=q({kind:"min",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{},exclusive:Oi},normalize:t=>typeof t=="number"?{rule:t}:t,defaults:{description:t=>t.rule===0?t.exclusive?"positive":"non-negative":`${t.exclusive?"more than":"at least"} ${t.rule}`},intersections:{min:(t,e)=>t.isStricterThan(e)?t:e},obviatesBasisDescription:!0});class oc extends De{impliedBasis=p.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}}const Li={implementation:sc,Node:oc},ac=q({kind:"minLength",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{parse:xn("minLength")}},reduce:t=>t.rule===0?p.intrinsic.unknown:void 0,normalize:Ri("minLength"),defaults:{description:t=>t.rule===1?"non-empty":`at least length ${t.rule}`,actual:t=>t.length===0?"":`${t.length}`},intersections:{minLength:(t,e)=>t.isStricterThan(e)?t:e}});class cc extends De{impliedBasis=p.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 L.throwInternalOperandError("minLength",e)}}}const Bi={implementation:ac,Node:cc},lc={min:Li.implementation,max:Ki.implementation,minLength:Bi.implementation,maxLength:Di.implementation,exactLength:Ei.implementation,after:Pi.implementation,before:qi.implementation},uc={min:Li.Node,max:Ki.Node,minLength:Bi.Node,maxLength:Di.Node,exactLength:Ei.Node,after:Pi.Node,before:qi.Node},dc=q({kind:"pattern",collapsibleKey:"rule",keys:{rule:{},flags:{}},normalize:t=>typeof t=="string"?{rule:t}:t instanceof RegExp?t.flags?{rule:t.source,flags:t.flags}:{rule:t.source}:t,obviatesBasisDescription:!0,obviatesBasisExpression:!0,hasAssociatedError:!0,intersectionIsOpen:!0,defaults:{description:t=>`matched by ${t.rule}`},intersections:{pattern:()=>null}});class hc extends Rt{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=p.intrinsic.string.internal;reduceJsonSchema(e,n){return e.pattern?n.fallback.patternIntersection({code:"patternIntersection",base:e,pattern:this.rule}):(e.pattern=this.rule,e)}}const ji={implementation:dc,Node:hc},dt=(t,e)=>{const n=pc(t);return e&&!e.includes(n)?d(`Root of kind ${n} should be one of ${e}`):n},pc=t=>{if(b(t,"root"))return t.kind;if(typeof t=="string")return t[0]==="$"?"alias":t in re?"domain":"proto";if(typeof t=="function")return"proto";if(typeof t!="object"||t===null)return d(Wn(t));if("morphs"in t)return"morph";if("branches"in t||F(t))return"union";if("unit"in t)return"unit";if("reference"in t)return"alias";const e=Object.keys(t);return e.length===0||e.some(n=>n in $i)?"intersection":"proto"in t?"proto":"domain"in t?"domain":d(Wn(t))},Wn=t=>`${S(t)} is not a valid type schema`,Hn={},fc=t=>F(t)?t.map(e=>e.collapsibleJson):t.collapsibleJson,W={};p.nodesByRegisteredId=W;const Fi=t=>(Hn[t]??=0,`${t}${++Hn[t]}`),Ui=t=>{const e=Ct[t.kind],n=e.applyConfig?.(t.def,t.$.resolvedConfig)??t.def,r={},{meta:i,...s}=n,o=i===void 0?{}:typeof i=="string"?{description:i}:i,a=Zr(s).sort(([c],[u])=>ut(c)?ut(u)?yt(c)-yt(u):1:ut(u)||c<u?-1:1).filter(([c,u])=>{if(c.startsWith("meta.")){const h=c.slice(5);return o[h]=u,!1}return!0});for(const c of a){const u=c[0],h=e.keys[u];if(!h)return d(`Key ${u} is not valid on ${t.kind} schema`);const m=h.parse?h.parse(c[1],t):c[1];m!==ee&&(m!==void 0||h.preserveUndefined)&&(r[u]=m)}if(e.reduce&&!t.prereduced){const c=e.reduce(r,t.$);if(c)return c instanceof g?c.throw():gc(c,o)}return kn({id:t.id,kind:t.kind,inner:r,meta:o,$:t.$})},kn=({id:t,kind:e,inner:n,meta:r,$:i,ignoreCache:s})=>{const o=Ct[e],a=Zr(n),l=[];let c={};for(const[v,A]of a){const P=o.keys[v],G=P.serialize??(P.child?fc:be);if(c[v]=G(A),P.child===!0){const H=A;F(H)?l.push(...H):l.push(H)}else typeof P.child=="function"&&l.push(...P.child(A))}o.finalizeInnerJson&&(c=o.finalizeInnerJson(c));let u={...c},h={};Ze(r)||(h=O(r,(v,A)=>[v,v==="examples"?A:be(A)]),u.meta=at(h,"description",!0)),c=at(c,o.collapsibleKey,!1);const m=JSON.stringify({kind:e,...c});u=at(u,o.collapsibleKey,!1);const y=at(u,o.collapsibleKey,!0),x=JSON.stringify({kind:e,...u});if(i.nodesByHash[x]&&!s)return i.nodesByHash[x];const f={id:t,kind:e,impl:o,inner:n,innerEntries:a,innerJson:c,innerHash:m,meta:r,metaJson:h,json:u,hash:x,collapsibleJson:y,children:l};if(e!=="intersection")for(const v in n)v!=="in"&&v!=="out"&&(f[v]=n[v]);const w=new xl[e](f,i);return i.nodesByHash[x]=w},mc=(t,e)=>t.id===e?t:(U(W[e])&&D(`Unexpected attempt to overwrite node id ${e}`),kn({id:e,kind:t.kind,inner:t.inner,meta:t.meta,$:t.$,ignoreCache:!0})),gc=(t,e,n)=>kn({id:Fi(e.alias??t.kind),kind:t.kind,inner:t.inner,meta:e,$:t.$}),at=(t,e,n)=>{const r=Object.keys(t);if(r.length===1&&r[0]===e){const i=t[e];if(n||$e(i,"object")&&(Object.keys(i).length===1||Array.isArray(i)))return i}return t},nn=(t,e,n)=>{if(t.key!==e.key)return null;const r=t.key;let i=j(t.value,e.value,n);const s=t.required||e.required?"required":"optional";if(i instanceof g)if(s==="optional")i=p.intrinsic.never.internal;else return i.withPrefixKey(t.key,t.required&&e.required?"required":"optional");if(s==="required")return n.$.node("required",{key:r,value:i});const o=t.hasDefault()?e.hasDefault()?t.default===e.default?t.default:d(Ti(t.default,e.default)):t.default:e.hasDefault()?e.default:ee;return n.$.node("optional",{key:r,value:i,default:o})};class zi extends Ke{required=this.kind==="required";optional=this.kind==="optional";impliedBasis=p.intrinsic.object.internal;serializedKey=et(this.key);compiledKey=typeof this.key=="string"?this.key:this.serializedKey;flatRefs=N(this.value.flatRefs.map(e=>de([this.key,...e.path],e.node)),de([this.key],this.value));_transform(e,n){n.path.push(this.key);const r=super._transform(e,n);return n.path.pop(),r}hasDefault(){return"default"in this.inner}traverseAllows=(e,n)=>this.key in e?se(this.key,()=>this.value.traverseAllows(e[this.key],n),n):this.optional;traverseApply=(e,n)=>{this.key in e?se(this.key,()=>this.value.traverseApply(e[this.key],n),n):this.hasKind("required")&&n.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 Ti=(t,e)=>`Invalid intersection of default values ${S(t)} & ${S(e)}`,yc=q({kind:"optional",hasAssociatedError:!1,intersectionIsOpen:!0,keys:{key:{},value:{child:!0,parse:(t,e)=>e.$.parseSchema(t)},default:{preserveUndefined:!0}},normalize:t=>t,reduce:(t,e)=>{if(e.resolvedConfig.exactOptionalPropertyTypes===!1&&!t.value.allows(void 0))return e.node("optional",{...t,value:t.value.or($.undefined)},{prereduced:!0})},defaults:{description:t=>`${t.compiledKey}?: ${t.value.description}`},intersections:{optional:nn}});class bc extends zi{constructor(...e){super(...e),"default"in this.inner&&In(this.value,this.inner.default,this.key)}get rawIn(){const e=super.rawIn;return this.hasDefault()?this.$.node("optional",Qr(e.inner,{default:!0}),{prereduced:!0}):e}get outProp(){if(!this.hasDefault())return this;const{default:e,...n}=this.inner;return this.cacheGetter("outProp",this.$.node("required",n,{prereduced:!0}))}expression=this.hasDefault()?`${this.compiledKey}: ${this.value.expression} = ${S(this.inner.default)}`:`${this.compiledKey}?: ${this.value.expression}`;defaultValueMorph=wc(this);defaultValueMorphRef=this.defaultValueMorph&&z(this.defaultValueMorph)}const An={implementation:yc,Node:bc},$c={},wc=t=>{if(!t.hasDefault())return;const e=`{${t.compiledKey}: ${t.value.id} = ${be(t.default)}}`;return $c[e]??=_i(t.key,t.value,t.default)},_i=(t,e,n)=>{if(typeof n=="function")return e.includesTransform?(i,s)=>(se(t,()=>e(i[t]=n(),s),s),i):i=>(i[t]=n(),i);const r=e.includesTransform?e.assert(n):n;return $e(r,"object")?(i,s)=>(se(t,()=>e(i[t]=n,s),s),i):i=>(i[t]=r,i)},In=(t,e,n)=>{const r=At(e);$e(e,"object")&&!r&&d(vc(n));const i=t.in(r?e():e);if(i instanceof he){n===null&&d(`Default ${i.summary}`);const s=i.transform(o=>o.transform(a=>({...a,prefixPath:[n]})));d(`Default for ${s.summary}`)}return e},vc=t=>`Non-primitive default ${t===null?"":typeof t=="number"?`for value at [${t}] `:`for ${et(t)} `}must be specified as a function like () => ({my: 'object'})`;class tt extends xi{constructor(e,n){super(e,n),Object.defineProperty(this,ie,{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=>{const n=this(e);return n instanceof he?n:{value:n}},toJSONSchema:e=>e.target&&e.target!=="draft-2020-12"?d(`JSONSchema target '${e.target}' is not supported (must be "draft-2020-12")`):e.io==="input"?this.rawIn.toJsonSchema():this.rawOut.toJsonSchema()}}as(){return this}brand(e){return e===""?d(xc):this}readonly(){return this}branches=this.hasKind("union")?this.inner.branches:[this];distribute(e,n){const r=this.branches.map(e);return n?.(r)??r}get shortDescription(){return this.meta.description??this.defaultShortDescription}toJsonSchema(e={}){const n=vi(this.$.resolvedConfig.toJsonSchema,e);n.useRefs||=this.isCyclic;const r=typeof n.dialect=="string"?{$schema:n.dialect}:{};return Object.assign(r,this.toJsonSchemaRecurse(n)),n.useRefs&&(r.$defs=O(this.references,(i,s)=>s.isRoot()&&!s.alwaysExpandJsonSchema?[s.id,s.toResolvedJsonSchema(n)]:[])),r}toJsonSchemaRecurse(e){return e.useRefs&&!this.alwaysExpandJsonSchema?{$ref:`#/$defs/${this.id}`}:this.toResolvedJsonSchema(e)}get alwaysExpandJsonSchema(){return this.isBasis()||this.kind==="alias"||this.hasKind("union")&&this.isBoolean}toResolvedJsonSchema(e){const n=this.innerToJsonSchema(e);return Object.assign(n,this.metaJson)}intersect(e){const n=this.$.parseDefinition(e),r=this.rawIntersect(n);return r instanceof g?r:this.$.finalize(r)}rawIntersect(e){return oe(this,e,this.$)}toNeverIfDisjoint(){return this}and(e){const n=this.intersect(e);return n instanceof g?n.throw():n}rawAnd(e){const n=this.rawIntersect(e);return n instanceof g?n.throw():n}or(e){const n=this.$.parseDefinition(e);return this.$.finalize(this.rawOr(n))}rawOr(e){const n=[...this.branches,...e.branches];return this.$.node("union",n)}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;const e=this.applyStructuralOperation("keyof",[]).reduce((n,r)=>n.intersect(r).toNeverIfDisjoint(),p.intrinsic.unknown.internal);return e.branches.length===0&&d(Ai(`keyof ${this.expression}`)),this._keyof=this.$.finalize(e)}get props(){return this.branches.length!==1?d(kc(this.expression)):[...this.applyStructuralOperation("props",[])[0]]}merge(e){const n=this.$.parseDefinition(e);return this.$.schema(n.distribute(r=>this.applyStructuralOperation("merge",[Zn(r)??d(Yn("merge",r.expression))])))}applyStructuralOperation(e,n){return this.distribute(r=>{if(r.equals(p.intrinsic.object)&&e!=="merge")return r;const i=Zn(r);if(i||d(Yn(e,r.expression)),e==="keyof")return i.keyof();if(e==="get")return i.get(...n);if(e==="props")return i.props;const s=e==="required"?"require":e==="partial"?"optionalize":e;return this.$.node("intersection",{domain:"object",structure:i[s](...n)})})}get(...e){return e[0]===void 0?this:this.$.schema(this.applyStructuralOperation("get",e))}extract(e){const n=this.$.parseDefinition(e);return this.$.schema(this.branches.filter(r=>r.extends(n)))}exclude(e){const n=this.$.parseDefinition(e);return this.$.schema(this.branches.filter(r=>!r.extends(n)))}array(){return this.$.schema(this.isUnknown()?{proto:Array}:{proto:Array,sequence:this},{prereduced:!0})}overlaps(e){return!(this.intersect(e)instanceof g)}extends(e){const n=this.intersect(e);return!(n instanceof g)&&this.equals(n)}ifExtends(e){return this.extends(e)?this:void 0}subsumes(e){return this.$.parseDefinition(e).extends(this)}configure(e,n="shallow"){return this.configureReferences(e,n)}describe(e,n="shallow"){return this.configure({description:e},n)}optional(){return[this,"?"]}default(e){return In(this,e,null),[this,"=",e]}from(e){return this.assert(e)}_pipe(...e){const n=e.reduce((r,i)=>r.rawPipeOnce(i),this);return this.$.finalize(n)}tryPipe(...e){const n=e.reduce((r,i)=>r.rawPipeOnce(b(i,"root")?i:(s,o)=>{try{return i(s,o)}catch(a){return o.error({code:"predicate",predicate:i,actual:`aborted due to error:\n ${a}\n`})}}),this);return this.$.finalize(n)}pipe=Object.assign(this._pipe.bind(this),{try:this.tryPipe.bind(this)});to(e){return this.$.finalize(this.toNode(this.$.parseDefinition(e)))}toNode(e){const n=en(this,e,this.$);return n instanceof g?n.throw():n}rawPipeOnce(e){return b(e,"root")?this.toNode(e):this.distribute(n=>n.hasKind("morph")?this.$.node("morph",{in:n.inner.in,morphs:[...n.morphs,e]}):this.$.node("morph",{in:n,morphs:[e]}),this.$.parseSchema)}narrow(e){return this.constrainOut("predicate",e)}constrain(e,n){return this._constrain("root",e,n)}constrainIn(e,n){return this._constrain("in",e,n)}constrainOut(e,n){return this._constrain("out",e,n)}_constrain(e,n,r){const i=this.$.node(n,r);if(i.isRoot())return i.isUnknown()?this:D(`Unexpected constraint node ${i}`);const s=e==="root"?this:e==="in"?this.rawIn:this.rawOut;if(s.hasKind("morph")||i.impliedBasis&&!s.extends(i.impliedBasis))return Pa(n,i.impliedBasis,this);const o=this.$.node("intersection",{[i.kind]:i}),a=e==="out"?en(this,o,this.$):oe(this,o,this.$);return a instanceof g&&a.throw(),this.$.finalize(a)}onUndeclaredKey(e){const n=typeof e=="string"?e:e.rule,r=typeof e=="string"?!1:e.deep;return this.$.finalize(this.transform((i,s)=>i==="structure"?n==="ignore"?Qr(s,{undeclared:1}):{...s,undeclared:n}:s,r?void 0:{shouldTransform:i=>!le(St,i.kind)}))}hasEqualMorphs(e){return!this.includesTransform&&!e.includesTransform?!0:!(!Ce(this.shallowMorphs,e.shallowMorphs)||!Ce(this.flatMorphs,e.flatMorphs,{isEqual:(n,r)=>n.propString===r.propString&&(n.node.hasKind("morph")&&r.node.hasKind("morph")?n.node.hasEqualMorphs(r.node):n.node.hasKind("intersection")&&r.node.hasKind("intersection")?n.node.structure?.structuralMorphRef===r.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",Ie(e))}lessThan(e){return this.constrain("max",Ie(e))}atLeastLength(e){return this.constrain("minLength",e)}atMostLength(e){return this.constrain("maxLength",e)}moreThanLength(e){return this.constrain("minLength",Ie(e))}lessThanLength(e){return this.constrain("maxLength",Ie(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",Ie(e))}earlierThan(e){return this.constrain("before",Ie(e))}}const xc="Expected a non-empty brand name after #",Ie=t=>typeof t=="object"&&!(t instanceof Date)?{...t,exclusive:!0}:{rule:t,exclusive:!0},ct=(t,e)=>b(e,"root")?b(t,"root")?t.extends(e):e.allows(t):b(t,"root")?t.hasUnit(e):e===t,Zn=t=>t.hasKind("morph")?null:t.hasKind("intersection")?t.inner.structure??(t.basis?.domain==="object"?t.$.bindReference(p.intrinsic.emptyStructure):null):t.isBasis()&&t.domain==="object"?t.$.bindReference(p.intrinsic.emptyStructure):null,kc=t=>`Props cannot be extracted from a union. Use .distribute to extract props from each branch instead. Received:\n${t}`,Yn=(t,e)=>`${t} operand must be an object (was ${e})`,nt=(t,e)=>O(vn(t),(n,r)=>[r,e]),Ac=t=>typeof t=="string"?{reference:t}:t,Qn=t=>t instanceof g?p.intrinsic.never.internal:t,Ic=q({kind:"alias",hasAssociatedError:!1,collapsibleKey:"reference",keys:{reference:{serialize:t=>t.startsWith("$")?t:`$ark.${t}`},resolve:{}},normalize:Ac,defaults:{description:t=>t.reference},intersections:{alias:(t,e,n)=>n.$.lazilyResolve(()=>Qn(j(t.resolution,e.resolution,n)),`${t.reference}${n.pipe?"=>":"&"}${e.reference}`),...nt("alias",(t,e,n)=>e.isUnknown()?t:e.isNever()?e:e.isBasis()&&!e.overlaps(p.intrinsic.object)?g.init("assignability",p.intrinsic.object,e):n.$.lazilyResolve(()=>Qn(j(t.resolution,e,n)),`${t.reference}${n.pipe?"=>":"&"}${e.id}`))}});class Sc extends tt{expression=this.reference;structure=void 0;get resolution(){const 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));const e=this.reference;let n=W[e];const r=[];for(;b(n,"context");){if(r.includes(n.id))return d(Nc(n.id,r));r.push(n.id),n=W[n.id]}return b(n,"root")?n:D(`Unexpected resolution for reference ${this.reference}\nSeen: [${r.join("->")}] \nResolution: ${S(n)}`)}get resolutionId(){if(this.reference.includes("&")||this.reference.includes("=>"))return this.resolution.id;if(this.reference[0]!=="$")return this.reference;const e=this.reference.slice(1),n=this.$.resolutions[e];return typeof n=="string"?n:b(n,"root")?n.id:D(`Unexpected resolution for reference ${this.reference}: ${S(n)}`)}get defaultShortDescription(){return re.object}innerToJsonSchema(e){return this.resolution.toJsonSchemaRecurse(e)}traverseAllows=(e,n)=>{const r=n.seen[this.reference];return r?.includes(e)?!0:(n.seen[this.reference]=N(r,e),this.resolution.traverseAllows(e,n))};traverseApply=(e,n)=>{const r=n.seen[this.reference];r?.includes(e)||(n.seen[this.reference]=N(r,e),this.resolution.traverseApply(e,n))};compile(e){const n=this.resolutionId;e.if(`ctx.seen.${n} && ctx.seen.${n}.includes(data)`,()=>e.return(!0)),e.if(`!ctx.seen.${n}`,()=>e.line(`ctx.seen.${n} = []`)),e.line(`ctx.seen.${n}.push(data)`),e.return(e.invoke(n))}}const Nc=(t,e)=>`Alias '${t}' has a shallow resolution cycle: ${[...e,t].join("->")}`,Sn={implementation:Ic,Node:Sc};class Nn extends tt{traverseApply=(e,n)=>{this.traverseAllows(e,n)||n.errorFromNodeContext(this.errorContext)};get errorContext(){return{code:this.kind,description:this.description,meta:this.meta,...this.inner}}get compiledErrorContext(){return Ot(this.errorContext)}compile(e){e.traversalKind==="Allows"?e.return(this.compiledCondition):e.if(this.compiledNegation,()=>e.line(`ctx.errorFromNodeContext(${this.compiledErrorContext})`))}}const Oc=q({kind:"domain",hasAssociatedError:!0,collapsibleKey:"domain",keys:{domain:{},numberAllowsNaN:{}},normalize:t=>typeof t=="string"?{domain:t}:mn(t,"numberAllowsNaN")&&t.domain!=="number"?d(On.writeBadAllowNanMessage(t.domain)):t,applyConfig:(t,e)=>t.numberAllowsNaN===void 0&&t.domain==="number"&&e.numberAllowsNaN?{...t,numberAllowsNaN:!0}:t,defaults:{description:t=>re[t.domain],actual:t=>Number.isNaN(t)?"NaN":re[Q(t)]},intersections:{domain:(t,e)=>t.domain==="number"&&e.domain==="number"?t.numberAllowsNaN?e:t:g.init("domain",t,e)}});class Rc extends Nn{requiresNaNCheck=this.domain==="number"&&!this.numberAllowsNaN;traverseAllows=this.requiresNaNCheck?e=>typeof e=="number"&&!Number.isNaN(e):e=>Q(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 re[this.domain]}innerToJsonSchema(e){return this.domain==="bigint"||this.domain==="symbol"?e.fallback.domain({code:"domain",base:{},domain:this.domain}):{type:this.domain}}}const On={implementation:Oc,Node:Rc,writeBadAllowNanMessage:t=>`numberAllowsNaN may only be specified with domain "number" (was ${t})`},Cc=q({kind:"intersection",hasAssociatedError:!0,normalize:t=>{if(U(t))return t;const{structure:e,...n}=t,r=!!e,i=e??{},s=O(n,(o,a)=>te(o,$a)?(r&&d(`Flattened structure key ${o} cannot be specified alongside a root 'structure' key.`),i[o]=a,[]):[o,a]);return(b(i,"constraint")||!Ze(i))&&(s.structure=i),s},finalizeInnerJson:({structure:t,...e})=>$e(t,"object")?{...t,...e}:e,keys:{domain:{child:!0,parse:(t,e)=>e.$.node("domain",t)},proto:{child:!0,parse:(t,e)=>e.$.node("proto",t)},structure:{child:!0,parse:(t,e)=>e.$.node("structure",t),serialize:t=>{if(!t.sequence?.minLength)return t.collapsibleJson;const{sequence:e,...n}=t.collapsibleJson,{minVariadicLength:r,...i}=e,s=i.variadic&&Object.keys(i).length===1?i.variadic:i;return{...n,sequence:s}}},divisor:{child:!0,parse:T("divisor")},max:{child:!0,parse:T("max")},min:{child:!0,parse:T("min")},maxLength:{child:!0,parse:T("maxLength")},minLength:{child:!0,parse:T("minLength")},exactLength:{child:!0,parse:T("exactLength")},before:{child:!0,parse:T("before")},after:{child:!0,parse:T("after")},pattern:{child:!0,parse:T("pattern")},predicate:{child:!0,parse:T("predicate")}},reduce:(t,e)=>Xn({},t,{$:e,invert:!1,pipe:!1}),defaults:{description:t=>{if(t.children.length===0)return"unknown";if(t.structure)return t.structure.description;const e=[];if(t.basis&&!t.prestructurals.some(n=>n.impl.obviatesBasisDescription)&&e.push(t.basis.description),t.prestructurals.length){const n=t.prestructurals.toSorted((r,i)=>r.kind==="min"&&i.kind==="max"?-1:0).map(r=>r.description);e.push(...n)}return t.inner.predicate&&e.push(...t.inner.predicate.map(n=>n.description)),e.join(" and ")},expected:t=>` ◦ ${t.errors.map(e=>e.expected).join(`\n ◦ `)}`,problem:t=>`(${t.actual}) must be...\n${t.expected}`},intersections:{intersection:(t,e,n)=>Xn(t.inner,e.inner,n),...nt("intersection",(t,e,n)=>{if(t.children.length===0)return e;const{domain:r,proto:i,...s}=t.inner,o=i??r,a=o?j(o,e,n):e;return a instanceof g?a:t?.basis?.equals(a)?t:t.$.node("intersection",{...s,[a.kind]:a},{prereduced:!0})})}});class Mc extends tt{basis=this.inner.domain??this.inner.proto??null;prestructurals=[];refinements=this.children.filter(e=>e.isRefinement()?(le(yi,e.kind)&&this.prestructurals.push(e),!0):!1);structure=this.inner.structure;expression=Pc(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((n,r)=>r.isBasis()?r.toJsonSchemaRecurse(e):r.reduceJsonSchema(n,e),{})}traverseAllows=(e,n)=>this.children.every(r=>r.traverseAllows(e,n));traverseApply=(e,n)=>{const r=n.currentErrorCount;if(!(this.basis&&(this.basis.traverseApply(e,n),n.currentErrorCount>r))){if(this.prestructurals.length){for(let i=0;i<this.prestructurals.length-1;i++)if(this.prestructurals[i].traverseApply(e,n),n.failFast&&n.currentErrorCount>r)return;if(this.prestructurals.at(-1).traverseApply(e,n),n.currentErrorCount>r)return}if(!(this.structure&&(this.structure.traverseApply(e,n),n.currentErrorCount>r))&&this.inner.predicate){for(let i=0;i<this.inner.predicate.length-1;i++)if(this.inner.predicate[i].traverseApply(e,n),n.failFast&&n.currentErrorCount>r)return;this.inner.predicate.at(-1).traverseApply(e,n)}}};compile(e){if(e.traversalKind==="Allows"){for(const n of this.children)e.check(n);e.return(!0);return}if(e.initializeErrorCount(),this.basis&&(e.check(this.basis),this.children.length>1&&e.returnIfFail()),this.prestructurals.length){for(let n=0;n<this.prestructurals.length-1;n++)e.check(this.prestructurals[n]),e.returnIfFailFast();e.check(this.prestructurals.at(-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 n=0;n<this.inner.predicate.length-1;n++)e.check(this.inner.predicate[n]),e.returnIfFail();e.check(this.inner.predicate.at(-1))}}}const Ji={implementation:Cc,Node:Mc},Pc=t=>{if(t.structure?.expression)return t.structure.expression;const e=t.basis&&!t.prestructurals.some(i=>i.impl.obviatesBasisExpression)?t.basis.nestableExpression:"",n=t.prestructurals.map(i=>i.expression).join(" & "),r=`${e}${e?" ":""}${n}`;return r==="Array == 0"?"[]":r||"unknown"},Xn=(t,e,n)=>{const r={},i=t.proto??t.domain,s=e.proto??e.domain,o=i?s?j(i,s,n):i:s;return o instanceof g?o:(o&&(r[o.kind]=o),bt({kind:"intersection",baseInner:r,l:$t(t),r:$t(e),roots:[],ctx:n}))},qc=q({kind:"morph",hasAssociatedError:!1,keys:{in:{child:!0,parse:(t,e)=>e.$.parseSchema(t)},morphs:{parse:He,serialize:t=>t.map(e=>b(e,"root")?e.json:z(e))},declaredIn:{child:!1,serialize:t=>t.json},declaredOut:{child:!1,serialize:t=>t.json}},normalize:t=>t,defaults:{description:t=>`a morph from ${t.rawIn.description} to ${t.rawOut?.description??"unknown"}`},intersections:{morph:(t,e,n)=>{if(!t.hasEqualMorphs(e))return d(Kc(t.expression,e.expression));const r=j(t.rawIn,e.rawIn,n);if(r instanceof g)return r;const i={morphs:t.morphs};if(t.declaredIn||e.declaredIn){const s=j(t.rawIn,e.rawIn,n);if(s instanceof g)return s.throw();i.declaredIn=s}if(t.declaredOut||e.declaredOut){const s=j(t.rawOut,e.rawOut,n);if(s instanceof g)return s.throw();i.declaredOut=s}return r.distribute(s=>n.$.node("morph",{...i,in:s}),n.$.parseSchema)},...nt("morph",(t,e,n)=>{const r=t.inner.in?j(t.inner.in,e,n):e;return r instanceof g?r:r.equals(t.inner.in)?t:n.$.node("morph",{...t.inner,in:r})})}});class Ec extends tt{serializedMorphs=this.morphs.map(z);compiledMorphs=`[${this.serializedMorphs}]`;lastMorph=this.inner.morphs.at(-1);lastMorphIfNode=b(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??p.intrinsic.unknown.internal}get rawOut(){return this.declaredOut??this.introspectableOut??p.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,n)=>!this.introspectableIn||this.introspectableIn.traverseAllows(e,n);traverseApply=(e,n)=>{this.introspectableIn&&this.introspectableIn.traverseApply(e,n),n.queueMorphs(this.morphs)};hasEqualMorphs(e){return Ce(this.morphs,e.morphs,{isEqual:(n,r)=>n===r||b(n,"root")&&b(r,"root")&&n.equals(r)})}}const Vi={implementation:qc,Node:Ec},Kc=(t,e)=>`The intersection of distinct morphs at a single path is indeterminate:\nLeft: ${t}\nRight: ${e}`,Dc=q({kind:"proto",hasAssociatedError:!0,collapsibleKey:"proto",keys:{proto:{serialize:t=>yn(t)??be(t)},dateAllowsInvalid:{}},normalize:t=>{const e=typeof t=="string"?{proto:Pe[t]}:typeof t=="function"?U(t)?t:{proto:t}:typeof t.proto=="string"?{...t,proto:Pe[t.proto]}:t;return typeof e.proto!="function"&&d(vt.writeInvalidSchemaMessage(e.proto)),mn(e,"dateAllowsInvalid")&&e.proto!==Date&&d(vt.writeBadInvalidDateMessage(e.proto)),e},applyConfig:(t,e)=>t.dateAllowsInvalid===void 0&&t.proto===Date&&e.dateAllowsInvalid?{...t,dateAllowsInvalid:!0}:t,defaults:{description:t=>t.builtinName?Ko[t.builtinName]:`an instance of ${t.proto.name}`,actual:t=>t instanceof Date&&t.toString()==="Invalid Date"?"an invalid Date":Gt(t)},intersections:{proto:(t,e)=>t.proto===Date&&e.proto===Date?t.dateAllowsInvalid?e:t:Fn(t.proto,e.proto)?t:Fn(e.proto,t.proto)?e:g.init("proto",t,e),domain:(t,e)=>e.domain==="object"?t:g.init("domain",p.intrinsic.object.internal,e)}});class Lc extends Nn{builtinName=yn(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}}const vt={implementation:Dc,Node:Lc,writeBadInvalidDateMessage:t=>`dateAllowsInvalid may only be specified with constructor Date (was ${t.name})`,writeInvalidSchemaMessage:t=>`instanceOf operand must be a function (was ${Q(t)})`},Bc=q({kind:"union",hasAssociatedError:!0,collapsibleKey:"branches",keys:{ordered:{},branches:{child:!0,parse:(t,e)=>{const n=[];for(const r of t){const i=b(r,"root")?r.branches:e.$.parseSchema(r).branches;for(const s of i)if(s.hasKind("morph")){const o=n.findIndex(a=>a.hasKind("morph")&&a.hasEqualMorphs(s));if(o===-1)n.push(s);else{const a=n[o];n[o]=e.$.node("morph",{...a.inner,in:a.rawIn.rawOr(s.rawIn)})}}else n.push(s)}return e.def.ordered||n.sort((r,i)=>r.hash<i.hash?-1:1),n}}},normalize:t=>F(t)?{branches:t}:t,reduce:(t,e)=>{const n=Hc(t);if(n.length===1)return n[0];if(n.length!==t.branches.length)return e.node("union",{...t,branches:n},{prereduced:!0})},defaults:{description:t=>t.distribute(e=>e.description,Oe),expected:t=>{const e=wo(t.errors,"propString"),n=Object.entries(e).map(([r,i])=>{const s=[];for(const l of i)ye(s,l.expected);const o=Oe(s),a=i.every(l=>l.actual===i[0].actual)?i[0].actual:S(i[0].data);return`${r&&`${r} `}must be ${o}${a&&` (was ${a})`}`});return Oe(n)},problem:t=>t.expected,message:t=>t.problem[0]==="["?`value at ${t.problem}`:t.problem},intersections:{union:(t,e,n)=>{if(t.isNever!==e.isNever)return g.init("presence",t,e);let r;return t.ordered?(e.ordered&&d(Yc(t.expression,e.expression)),r=Bt(e.branches,t.branches,n),r instanceof g&&r.invert()):r=Bt(t.branches,e.branches,n),r instanceof g?r:n.$.parseSchema(t.ordered||e.ordered?{branches:r,ordered:!0}:{branches:r})},...nt("union",(t,e,n)=>{const r=Bt(t.branches,[e],n);return r instanceof g?r:r.length===1?r[0]:n.$.parseSchema(t.ordered?{branches:r,ordered:!0}:{branches:r})})}});class jc extends tt{isBoolean=this.branches.length===2&&this.branches[0].hasUnit(!1)&&this.branches[1].hasUnit(!0);get branchGroups(){const e=[];let n=-1;for(const r of this.branches){if(r.hasKind("unit")&&r.domain==="boolean"){n===-1?(n=e.length,e.push(r)):e[n]=p.intrinsic.boolean;continue}e.push(r)}return e}unitBranches=this.branches.filter(e=>e.rawIn.hasKind("unit"));discriminant=this.discriminate();discriminantJson=this.discriminant?Vc(this.discriminant):null;expression=this.distribute(e=>e.nestableExpression,Wc);createBranchedOptimisticRootApply(){return(e,n)=>{const r=this.traverseOptimistic(e);if(r!==ee)return r;const i=new Ne(e,this.$.resolvedConfig);return this.traverseApply(e,i),i.finalize(n)}}get shallowMorphs(){return this.branches.reduce((e,n)=>ye(e,n.shallowMorphs),[])}get defaultShortDescription(){return this.distribute(e=>e.defaultShortDescription,Oe)}innerToJsonSchema(e){if(this.branchGroups.length===1&&this.branchGroups[0].equals(p.intrinsic.boolean))return{type:"boolean"};const n=this.branchGroups.map(r=>r.toJsonSchemaRecurse(e));return n.every(r=>Object.keys(r).length===1&&mn(r,"const"))?{enum:n.map(r=>r.const)}:{anyOf:n}}traverseAllows=(e,n)=>this.branches.some(r=>r.traverseAllows(e,n));traverseApply=(e,n)=>{const r=[];for(let i=0;i<this.branches.length;i++){if(n.pushBranch(),this.branches[i].traverseApply(e,n),!n.hasError())return this.branches[i].includesTransform?n.queuedMorphs.push(...n.popBranch().queuedMorphs):n.popBranch();r.push(n.popBranch().error)}n.errorFromNodeContext({code:"union",errors:r,meta:this.meta})};traverseOptimistic=e=>{for(let n=0;n<this.branches.length;n++){const r=this.branches[n];if(r.traverseAllows(e))return r.contextFreeMorph?r.contextFreeMorph(e):e}return ee};compile(e){if(!this.discriminant||this.unitBranches.length===this.branches.length&&this.branches.length===2)return this.compileIndiscriminable(e);let n=this.discriminant.optionallyChainedPropString;this.discriminant.kind==="domain"&&(n=`typeof ${n} === "object" ? ${n} === null ? "null" : "object" : typeof ${n} === "function" ? "object" : typeof ${n}`);const r=this.discriminant.cases,i=Object.keys(r),{optimistic:s}=e;if(e.optimistic=!1,e.block(`switch(${n})`,()=>{for(const u in r){const h=r[u],m=u==="default"?u:`case ${u}`;let y;h===!0?y=s?"data":"true":s?h.rootApplyStrategy==="branchedOptimistic"?y=e.invoke(h,{kind:"Optimistic"}):h.contextFreeMorph?y=`${e.invoke(h)} ? ${z(h.contextFreeMorph)}(data) : "${ee}"`:y=`${e.invoke(h)} ? data : "${ee}"`:y=e.invoke(h),e.line(`${m}: return ${y}`)}return e}),e.traversalKind==="Allows"){e.return(s?`"${ee}"`:!1);return}const o=Oe(this.discriminant.kind==="domain"?i.map(u=>{const h=u.slice(1,-1);return h==="function"?re.object:re[h]}):i),a=this.discriminant.path.map(u=>typeof u=="symbol"?z(u):JSON.stringify(u)),l=JSON.stringify(o),c=this.discriminant.kind==="domain"?`${_c}[${n}]`:`${Jc}(${n})`;e.line(`ctx.errorFromNodeContext({\n\tcode: "predicate",\n\texpected: ${l},\n\tactual: ${c},\n\trelativePath: [${a}],\n\tmeta: ${this.compiledMeta}\n})`)}compileIndiscriminable(e){if(e.traversalKind==="Apply"){e.const("errors","[]");for(const n of this.branches)e.line("ctx.pushBranch()").line(e.invoke(n)).if("!ctx.hasError()",()=>e.return(n.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{const{optimistic:n}=e;e.optimistic=!1;for(const r of this.branches)e.if(`${e.invoke(r)}`,()=>e.return(n?r.contextFreeMorph?`${z(r.contextFreeMorph)}(data)`:"data":!0));e.return(n?`"${ee}"`:!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){const s=O(this.unitBranches,(o,a)=>[`${a.rawIn.serializedValue}`,a.hasKind("morph")?a:!0]);return{kind:"unit",path:[],optionallyChainedPropString:"data",cases:s}}const e=[];for(let s=0;s<this.branches.length-1;s++){const o=this.branches[s];for(let a=s+1;a<this.branches.length;a++){const l=this.branches[a],c=oe(o.rawIn,l.rawIn,o.$);if(c instanceof g)for(const u of c){if(!u.kind||u.optional)continue;let h,m;if(u.kind==="domain"){const x=u.l,f=u.r;h=`"${typeof x=="string"?x:x.domain}"`,m=`"${typeof f=="string"?f:f.domain}"`}else if(u.kind==="unit")h=u.l.serializedValue,m=u.r.serializedValue;else continue;const y=e.find(x=>Ce(x.path,u.path)&&x.kind===u.kind);y?(y.cases[h]?y.cases[h].branchIndices=ye(y.cases[h].branchIndices,s):y.cases[h]??={branchIndices:[s],condition:u.l},y.cases[m]?y.cases[m].branchIndices=ye(y.cases[m].branchIndices,a):y.cases[m]??={branchIndices:[a],condition:u.r}):e.push({kind:u.kind,cases:{[h]:{branchIndices:[s],condition:u.l},[m]:{branchIndices:[a],condition:u.r}},path:u.path})}}}const n=this.ordered?zc(e,this.branches):e;if(!n.length)return null;const r=Fc(n,this),i={};for(const s in r.best.cases){const o=Uc(r,s);if(o===null){i[s]=!0;continue}if(o.length===this.branches.length)return null;this.ordered&&o.sort((c,u)=>c.originalIndex-u.originalIndex);const a=o.map(c=>c.branch),l=a.length===1?a[0]:this.$.node("union",this.ordered?{branches:a,ordered:!0}:a);Object.assign(this.referencesById,l.referencesById),i[s]=l}if(r.defaultEntries.length){const s=r.defaultEntries.map(o=>o.branch);i.default=this.$.node("union",this.ordered?{branches:s,ordered:!0}:s,{prereduced:!0}),Object.assign(this.referencesById,i.default.referencesById)}return Object.assign(r.location,{cases:i})}}const Fc=(t,e)=>{const r=t.sort((o,a)=>o.path.length===a.path.length?Object.keys(a.cases).length-Object.keys(o.cases).length:o.path.length-a.path.length)[0],i={kind:r.kind,path:r.path,optionallyChainedPropString:Gi(r.path)},s=e.branches.map((o,a)=>({originalIndex:a,branch:o}));return{best:r,location:i,defaultEntries:s,node:e}},Uc=(t,e)=>{const n=t.best.cases[e],r=Tc(n.condition,t.location.path,t.node.$);let i=[];const s=[];for(let o=0;o<t.defaultEntries.length;o++){const a=t.defaultEntries[o];if(n.branchIndices.includes(a.originalIndex)){const l=er(t.node.branches[a.originalIndex],t.location);l===null?i=null:i?.push({originalIndex:a.originalIndex,branch:l})}else if(a.branch.hasKind("alias")&&r.hasKind("domain")&&r.domain==="object")i?.push(a);else{if(a.branch.rawIn.overlaps(r)){const l=er(a.branch,t.location);i?.push({originalIndex:a.originalIndex,branch:l})}s.push(a)}}return t.defaultEntries=s,i},zc=(t,e)=>t.filter(r=>{const i=Object.values(r.cases).map(s=>s.branchIndices);for(let s=0;s<i.length-1;s++){const o=i[s];for(let a=s+1;a<i.length;a++){const l=i[a];for(const c of o)for(const u of l)if(c>u&&e[c].overlaps(e[u]))return!1}}return!0}),Tc=(t,e,n)=>{let r=t==="undefined"?n.node("unit",{unit:void 0}):t==="null"?n.node("unit",{unit:null}):t==="boolean"?n.units([!0,!1]):t;for(let i=e.length-1;i>=0;i--){const s=e[i];r=n.node("intersection",typeof s=="number"?{proto:"Array",sequence:[...bo(s).map(o=>({})),r]}:{domain:"object",required:[{key:s,value:r}]})}return r},Gi=t=>t.reduce((e,n)=>e+fi(n,!0),"data"),_c=z(vo),Jc=z(S),Wi={implementation:Bc,Node:jc},Vc=t=>({kind:t.kind,path:t.path.map(e=>typeof e=="string"?e:et(e)),cases:O(t.cases,(e,n)=>[e,n===!0?n:n.hasKind("union")&&n.discriminantJson?n.discriminantJson:n.json])}),Gc={delimiter:" | ",finalDelimiter:" | "},Wc=t=>Oe(t,Gc),Oe=(t,e)=>{const n=e?.delimiter??", ",r=e?.finalDelimiter??" or ";if(t.length===0)return"never";if(t.length===1)return t[0];if(t.length===2&&t[0]==="false"&&t[1]==="true"||t[0]==="true"&&t[1]==="false")return"boolean";const i={},s=t.filter(a=>i[a]?!1:i[a]=!0),o=s.pop();return`${s.join(n)}${s.length?r:""}${o}`},Bt=(t,e,n)=>{const r=e.map(()=>[]);for(let s=0;s<t.length;s++){let o={};for(let a=0;a<e.length;a++){if(r[a]===null)continue;if(t[s].equals(e[a])){r[a]=null,o={};break}const l=j(t[s],e[a],n);if(!(l instanceof g)){if(l.equals(t[s])){r[a].push(t[s]),o={};break}l.equals(e[a])?r[a]=null:o[a]=l}}for(const a in o)r[a][s]=o[a]}const i=r.flatMap((s,o)=>s?.flatMap(a=>a.branches)??e[o]);return i.length===0?g.init("union",t,e):i},Hc=({branches:t,ordered:e})=>{if(t.length<2)return t;const n=t.map(()=>!0);for(let r=0;r<t.length;r++)for(let i=r+1;i<t.length&&n[r]&&n[i];i++){if(t[r].equals(t[i])){n[i]=!1;continue}const s=oe(t[r].rawIn,t[i].rawIn,t[0].$);s instanceof g||(e||Zc(t[r],t[i]),s.equals(t[r].rawIn)?n[r]=!!e:s.equals(t[i].rawIn)&&(n[i]=!1))}return t.filter((r,i)=>n[i])},Zc=(t,e)=>{!t.includesTransform&&!e.includesTransform||(Ce(t.shallowMorphs,e.shallowMorphs)||d(tr(t.expression,e.expression)),Ce(t.flatMorphs,e.flatMorphs,{isEqual:(n,r)=>n.propString===r.propString&&(n.node.hasKind("morph")&&r.node.hasKind("morph")?n.node.hasEqualMorphs(r.node):n.node.hasKind("intersection")&&r.node.hasKind("intersection")?n.node.structure?.structuralMorphRef===r.node.structure?.structuralMorphRef:!1)})||d(tr(t.expression,e.expression)))},er=(t,e)=>t.transform((n,r)=>n==="domain"||n==="unit"?null:r,{shouldTransform:(n,r)=>{const i=Gi(r.path);return e.optionallyChainedPropString.startsWith(i)?n.hasKind("domain")&&n.domain==="object"||(n.hasKind("domain")||e.kind==="unit")&&i===e.optionallyChainedPropString?!0:n.children.length!==0&&n.kind!=="index":!1}}),tr=(t,e)=>`An unordered union of a type including a morph and a type with overlapping input is indeterminate:\nLeft: ${t}\nRight: ${e}`,Yc=(t,e)=>`The intersection of two ordered unions is indeterminate:\nLeft: ${t}\nRight: ${e}`,Qc=q({kind:"unit",hasAssociatedError:!0,keys:{unit:{preserveUndefined:!0,serialize:t=>t instanceof Date?t.toISOString():be(t)}},normalize:t=>t,defaults:{description:t=>S(t.unit),problem:({expected:t,actual:e})=>`${t===e?`must be reference equal to ${t} (serialized to the same value)`:`must be ${t} (was ${e})`}`},intersections:{unit:(t,e)=>g.init("unit",t,e),...nt("unit",(t,e)=>{if(e.allows(t.unit))return t;const n=e.hasKind("intersection")?e.basis:e;if(n){const r=n.hasKind("domain")?n:p.intrinsic.object;if(t.domain!==r.domain){const i=t.domain==="undefined"||t.domain==="null"||t.domain==="boolean"?t.domain:p.intrinsic[t.domain];return g.init("domain",i,r)}}return g.init("assignability",t,e.hasKind("intersection")?e.children.find(r=>!r.allows(t.unit)):e)})}});class Xc extends Nn{compiledValue=this.json.unit;serializedValue=typeof this.unit=="string"||this.unit instanceof Date?JSON.stringify(this.compiledValue):`${this.compiledValue}`;compiledCondition=nr(this.unit,this.serializedValue);compiledNegation=nr(this.unit,this.serializedValue,"negated");expression=S(this.unit);domain=Q(this.unit);get defaultShortDescription(){return this.domain==="object"?re.object:this.description}innerToJsonSchema(e){return this.unit===null?{type:"null"}:p.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}const Hi={implementation:Qc,Node:Xc},nr=(t,e,n)=>{if(t instanceof Date){const r=`data instanceof Date && data.toISOString() === ${e}`;return n?`!(${r})`:r}return Number.isNaN(t)?`${n?"!":""}Number.isNaN(data)`:`data ${n?"!":"="}== ${e}`},el=q({kind:"index",hasAssociatedError:!1,intersectionIsOpen:!0,keys:{signature:{child:!0,parse:(t,e)=>{const n=e.$.parseSchema(t);if(!n.extends(p.intrinsic.key))return d(rl(n.expression));const r=n.branches.filter(i=>i.hasKind("unit"));return r.length?d(nl(r.map(i=>S(i.unit)))):n}},value:{child:!0,parse:(t,e)=>e.$.parseSchema(t)}},normalize:t=>t,defaults:{description:t=>`[${t.signature.expression}]: ${t.value.description}`},intersections:{index:(t,e,n)=>{if(t.signature.equals(e.signature)){const r=j(t.value,e.value,n),i=r instanceof g?p.intrinsic.never.internal:r;return n.$.node("index",{signature:t.signature,value:i})}return t.signature.extends(e.signature)&&t.value.subsumes(e.value)?e:e.signature.extends(t.signature)&&e.value.subsumes(t.value)?t:null}}});class tl extends Ke{impliedBasis=p.intrinsic.object.internal;expression=`[${this.signature.expression}]: ${this.value.expression}`;flatRefs=N(this.value.flatRefs.map(e=>de([this.signature,...e.path],e.node)),de([this.signature],this.value));traverseAllows=(e,n)=>ft(e).every(r=>this.signature.traverseAllows(r[0],n)?se(r[0],()=>this.value.traverseAllows(r[1],n),n):!0);traverseApply=(e,n)=>{for(const r of ft(e))this.signature.traverseAllows(r[0],n)&&se(r[0],()=>this.value.traverseApply(r[1],n),n)};_transform(e,n){n.path.push(this.signature);const r=super._transform(e,n);return n.path.pop(),r}compile(){}}const Zi={implementation:el,Node:tl},nl=t=>`Index keys ${t.join(", ")} should be specified as named props.`,rl=t=>`Indexed key definition '${t}' must be a string or symbol`,il=q({kind:"required",hasAssociatedError:!0,intersectionIsOpen:!0,keys:{key:{},value:{child:!0,parse:(t,e)=>e.$.parseSchema(t)}},normalize:t=>t,defaults:{description:t=>`${t.compiledKey}: ${t.value.description}`,expected:t=>t.missingValueDescription,actual:()=>"missing"},intersections:{required:nn,optional:nn}});class sl extends zi{expression=`${this.compiledKey}: ${this.value.expression}`;errorContext=Object.freeze({code:"required",missingValueDescription:this.value.defaultShortDescription,relativePath:[this.key],meta:this.meta});compiledErrorContext=Ot(this.errorContext)}const Yi={implementation:il,Node:sl},ol=q({kind:"sequence",hasAssociatedError:!1,collapsibleKey:"variadic",keys:{prefix:{child:!0,parse:(t,e)=>{if(t.length!==0)return t.map(n=>e.$.parseSchema(n))}},optionals:{child:!0,parse:(t,e)=>{if(t.length!==0)return t.map(n=>e.$.parseSchema(n))}},defaultables:{child:t=>t.map(e=>e[0]),parse:(t,e)=>{if(t.length!==0)return t.map(n=>{const r=e.$.parseSchema(n[0]);return In(r,n[1],null),[r,n[1]]})},serialize:t=>t.map(e=>[e[0].collapsibleJson,be(e[1])]),reduceIo:(t,e,n)=>{if(t==="in"){e.optionals=n.map(r=>r[0].rawIn);return}e.prefix=n.map(r=>r[0].rawOut)}},variadic:{child:!0,parse:(t,e)=>e.$.parseSchema(t,e)},minVariadicLength:{parse:t=>t===0?void 0:t},postfix:{child:!0,parse:(t,e)=>{if(t.length!==0)return t.map(n=>e.$.parseSchema(n))}}},normalize:t=>{if(typeof t=="string")return{variadic:t};if("variadic"in t||"prefix"in t||"defaultables"in t||"optionals"in t||"postfix"in t||"minVariadicLength"in t){if(t.postfix?.length){if(!t.variadic)return d(dl);if(t.optionals?.length||t.defaultables?.length)return d(Xi)}return t.minVariadicLength&&!t.variadic?d("minVariadicLength may not be specified without a variadic element"):t}return{variadic:t}},reduce:(t,e)=>{let n=t.minVariadicLength??0;const r=t.prefix?.slice()??[],i=t.defaultables?.slice()??[],s=t.optionals?.slice()??[],o=t.postfix?.slice()??[];if(t.variadic){for(;s.at(-1)?.equals(t.variadic);)s.pop();if(s.length===0&&i.length===0)for(;r.at(-1)?.equals(t.variadic);)r.pop(),n++;for(;o[0]?.equals(t.variadic);)o.shift(),n++}else s.length===0&&i.length===0&&r.push(...o.splice(0));if(n!==t.minVariadicLength||t.prefix&&t.prefix.length!==r.length)return e.node("sequence",{...t,prefix:r,defaultables:i,optionals:s,postfix:o,minVariadicLength:n},{prereduced:!0})},defaults:{description:t=>t.isVariadicOnly?`${t.variadic.nestableExpression}[]`:`[${t.tuple.map(n=>n.kind==="defaultables"?`${n.node.nestableExpression} = ${S(n.default)}`:n.kind==="optionals"?`${n.node.nestableExpression}?`:n.kind==="variadic"?`...${n.node.nestableExpression}[]`:n.node.expression).join(", ")}]`},intersections:{sequence:(t,e,n)=>{const r=Fe({l:t.tuple,r:e.tuple,disjoint:new g,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",rr(i[0].result)):n.$.node("union",i.map(s=>({proto:Array,sequence:rr(s.result)})))}}});class al extends Ke{impliedBasis=p.intrinsic.Array.internal;tuple=ul(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=ge(this.variadic&&[this.variadic],this.postfix);flatRefs=this.addFlatRefs();addFlatRefs(){return Jn(this.flatRefs,this.prevariadic.flatMap((e,n)=>N(e.node.flatRefs.map(r=>de([`${n}`,...r.path],r.node)),de([`${n}`],e.node)))),Jn(this.flatRefs,this.variadicOrPostfix.flatMap(e=>N(e.flatRefs.map(n=>de([p.intrinsic.nonNegativeIntegerString.internal,...n.path],n.node)),de([p.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=ll(this);defaultValueMorphsReference=this.defaultValueMorphs.length?z(this.defaultValueMorphs):void 0;elementAtIndex(e,n){if(n<this.prevariadic.length)return this.tuple[n];const r=e.length-this.postfixLength;return n>=r?{kind:"postfix",node:this.postfix[n-r]}:{kind:"variadic",node:this.variadic??D(`Unexpected attempt to access index ${n} on ${this}`)}}traverseAllows=(e,n)=>{for(let r=0;r<e.length;r++)if(!this.elementAtIndex(e,r).node.traverseAllows(e[r],n))return!1;return!0};traverseApply=(e,n)=>{let r=0;for(;r<e.length;r++)se(r,()=>this.elementAtIndex(e,r).node.traverseApply(e[r],n),n)};get element(){return this.cacheGetter("element",this.$.node("union",this.children))}compile(e){if(this.prefix)for(const[n,r]of this.prefix.entries())e.traverseKey(`${n}`,`data[${n}]`,r);for(const[n,r]of this.defaultablesAndOptionals.entries()){const i=`${n+this.prefixLength}`;e.if(`${i} >= data.length`,()=>e.traversalKind==="Allows"?e.return(!0):e.return()),e.traverseKey(i,`data[${i}]`,r)}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(const[n,r]of this.postfix.entries()){const i=`firstPostfixIndex + ${n}`;e.traverseKey(i,`data[${i}]`,r)}e.traversalKind==="Allows"&&e.return(!0)}_transform(e,n){n.path.push(p.intrinsic.nonNegativeIntegerString.internal);const r=super._transform(e,n);return n.path.pop(),r}expression=this.description;reduceJsonSchema(e,n){if(this.prevariadic.length&&(e.prefixItems=this.prevariadic.map(r=>{const i=r.node.toJsonSchemaRecurse(n);if(r.kind==="defaultables"){const s=typeof r.default=="function"?r.default():r.default;i.default=p.intrinsic.jsonData.allows(s)?s:n.fallback.defaultValue({code:"defaultValue",base:i,value:s})}return i})),this.minLength&&(e.minItems=this.minLength),this.variadic){const r=Object.assign(e,{items:this.variadic.toJsonSchemaRecurse(n)});if(this.maxLength&&(r.maxItems=this.maxLength),this.postfix){const i=this.postfix.map(s=>s.toJsonSchemaRecurse(n));e=n.fallback.arrayPostfix({code:"arrayPostfix",base:r,elements:i})}}else e.items=!1,delete e.maxItems;return e}}const cl={},ll=t=>{if(!t.defaultables)return[];const e=[];let n="[";const r=t.prefixLength+t.defaultablesLength-1;for(let i=t.prefixLength;i<=r;i++){const[s,o]=t.defaultables[i-t.prefixLength];e.push(_i(i,s,o)),n+=`${i}: ${s.id} = ${be(o)}, `}return n+="]",cl[n]??=e},Qi={implementation:ol,Node:al},ul=t=>{const e=[];if(t.prefix)for(const n of t.prefix)e.push({kind:"prefix",node:n});if(t.defaultables)for(const[n,r]of t.defaultables)e.push({kind:"defaultables",node:n,default:r});if(t.optionals)for(const n of t.optionals)e.push({kind:"optionals",node:n});if(t.variadic&&e.push({kind:"variadic",node:t.variadic}),t.postfix)for(const n of t.postfix)e.push({kind:"postfix",node:n});return e},rr=t=>t.reduce((e,n)=>(n.kind==="variadic"?e.variadic=n.node:n.kind==="defaultables"?e.defaultables=N(e.defaultables,[[n.node,n.default]]):e[n.kind]=N(e[n.kind],n.node),e),{}),Xi="A postfix required element cannot follow an optional or defaultable element",dl="A postfix element requires a variadic element",Fe=t=>{const[e,...n]=t.l,[r,...i]=t.r;if(!e||!r)return t;const s=n.at(-1)?.kind==="postfix",o=i.at(-1)?.kind==="postfix",a=e.kind==="prefix"||r.kind==="prefix"?"prefix":e.kind==="postfix"||r.kind==="postfix"?"postfix":e.kind==="variadic"&&r.kind==="variadic"?"variadic":s||o?"prefix":e.kind==="defaultables"||r.kind==="defaultables"?"defaultables":"optionals";if(e.kind==="prefix"&&r.kind==="variadic"&&o){const h=Fe({...t,fixedVariants:[],r:i.map(m=>({...m,kind:"prefix"}))});h.disjoint.length===0&&t.fixedVariants.push(h)}else if(r.kind==="prefix"&&e.kind==="variadic"&&s){const h=Fe({...t,fixedVariants:[],l:n.map(m=>({...m,kind:"prefix"}))});h.disjoint.length===0&&t.fixedVariants.push(h)}const l=j(e.node,r.node,t.ctx);if(l instanceof g)if(a==="prefix"||a==="postfix")t.disjoint.push(...l.withPrefixKey(a==="prefix"?t.result.length:`-${n.length+1}`,ir(e)&&ir(r)?"required":"optional")),t.result=[...t.result,{kind:a,node:p.intrinsic.never.internal}];else return a==="optionals"||a==="defaultables"?t:Fe({...t,fixedVariants:[],l:n.map(h=>({...h,kind:"prefix"})),r:n.map(h=>({...h,kind:"prefix"}))});else a==="defaultables"?(e.kind==="defaultables"&&r.kind==="defaultables"&&e.default!==r.default&&d(Ti(e.default,r.default)),t.result=[...t.result,{kind:a,node:l,default:e.kind==="defaultables"?e.default:r.kind==="defaultables"?r.default:D(`Unexpected defaultable intersection from ${e.kind} and ${r.kind} elements.`)}]):t.result=[...t.result,{kind:a,node:l}];const c=t.l.length,u=t.r.length;return(e.kind!=="variadic"||c>=u&&(r.kind==="variadic"||u===1))&&(t.l=n),(r.kind!=="variadic"||u>=c&&(e.kind==="variadic"||c===1))&&(t.r=i),Fe(t)},ir=t=>t.kind==="prefix"||t.kind==="postfix",es=t=>e=>{if(e.props.length||e.index){const n=e.index?.map(i=>i[t])??[];for(const i of e.props)n.push(i[t]);e.undeclared&&n.push(`+ (undeclared): ${e.undeclared}`);const r=`{ ${n.join(", ")} }`;return e.sequence?`${r} & ${e.sequence.description}`:r}return e.sequence?.description??"{}"},hl=es("description"),pl=es("expression"),sr=(t,e,n)=>{const r=t.required?"required":"optional";if(!e.signature.allows(t.key))return null;const i=oe(t.value,e.value,n);return i instanceof g?r==="optional"?n.node("optional",{key:t.key,value:p.intrinsic.never.internal}):i.withPrefixKey(t.key,t.kind):null},fl=q({kind:"structure",hasAssociatedError:!1,normalize:t=>t,applyConfig:(t,e)=>!t.undeclared&&e.onUndeclaredKey!=="ignore"?{...t,undeclared:e.onUndeclaredKey}:t,keys:{required:{child:!0,parse:T("required"),reduceIo:(t,e,n)=>{e.required=N(e.required,n.map(r=>t==="in"?r.rawIn:r.rawOut))}},optional:{child:!0,parse:T("optional"),reduceIo:(t,e,n)=>{if(t==="in"){e.optional=n.map(r=>r.rawIn);return}for(const r of n)e[r.outProp.kind]=N(e[r.outProp.kind],r.outProp.rawOut)}},index:{child:!0,parse:T("index")},sequence:{child:!0,parse:T("sequence")},undeclared:{parse:t=>t==="ignore"?void 0:t,reduceIo:(t,e,n)=>{if(n==="reject"){e.undeclared="reject";return}t==="in"?delete e.undeclared:e.undeclared="reject"}}},defaults:{description:hl},intersections:{structure:(t,e,n)=>{const r={...t.inner},i={...e.inner},s=new g;if(t.undeclared){const l=t.keyof();for(const c of e.requiredKeys)l.allows(c)||s.add("presence",p.intrinsic.never.internal,e.propsByKey[c].value,{path:[c]});i.optional&&(i.optional=i.optional.filter(c=>l.allows(c.key))),i.index&&(i.index=i.index.flatMap(c=>{if(c.signature.extends(l))return c;const u=oe(l,c.signature,n.$);if(u instanceof g)return[];const h=rn(u,c.value,n.$);return h.required&&(i.required=ge(i.required,h.required)),h.optional&&(i.optional=ge(i.optional,h.optional)),h.index??[]}))}if(e.undeclared){const l=e.keyof();for(const c of t.requiredKeys)l.allows(c)||s.add("presence",t.propsByKey[c].value,p.intrinsic.never.internal,{path:[c]});r.optional&&(r.optional=r.optional.filter(c=>l.allows(c.key))),r.index&&(r.index=r.index.flatMap(c=>{if(c.signature.extends(l))return c;const u=oe(l,c.signature,n.$);if(u instanceof g)return[];const h=rn(u,c.value,n.$);return h.required&&(r.required=ge(r.required,h.required)),h.optional&&(r.optional=ge(r.optional,h.optional)),h.index??[]}))}const o={};(t.undeclared||e.undeclared)&&(o.undeclared=t.undeclared==="reject"||e.undeclared==="reject"?"reject":"delete");const a=bt({kind:"structure",baseInner:o,l:$t(r),r:$t(i),roots:[],ctx:n});return a instanceof g&&s.push(...a),s.length?s:a}},reduce:(t,e)=>{if(t.index){if(!(t.required||t.optional))return;let n=!1;const r=t.required??[],i=t.optional??[],s=[...i];for(const o of t.index){for(const a of r){const l=sr(a,o,e);if(l instanceof g)return l}for(const[a,l]of i.entries()){const c=sr(l,o,e);if(c instanceof g)return c;c!==null&&(s[a]=c,n=!0)}}if(n)return e.node("structure",{...t,optional:s},{prereduced:!0})}}});class ml extends Ke{impliedBasis=p.intrinsic.object.internal;impliedSiblings=this.children.flatMap(e=>e.impliedSiblings??[]);props=ge(this.required,this.optional);propsByKey=O(this.props,(e,n)=>[n.key,n]);propsByKeyReference=z(this.propsByKey);expression=pl(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(const{signature:n}of this.index)e=e.concat(n.branches);return this._keyof=this.$.node("union",e)}map(e){return this.$.node("structure",this.props.flatMap(e).reduce((n,r)=>{const i=this.propsByKey[r.key];if(U(r))return r.kind!=="required"&&r.kind!=="optional"?d(`Map result must have kind "required" or "optional" (was ${r.kind})`):(n[r.kind]=N(n[r.kind],r),n);const s=r.kind??i?.kind??"required",o=O(r,(a,l)=>a in An.implementation.keys?[a,l]:[]);return n[s]=N(n[s],this.$.node(s,o)),n},{}))}assertHasKeys(e){const n=e.filter(r=>!ct(r,this.keyof()));if(n.length)return d(or(this.expression,n))}get(e,...n){let r,i=!1;const s=$l(e);if((typeof s=="string"||typeof s=="symbol")&&this.propsByKey[s]&&(r=this.propsByKey[s].value,i=this.propsByKey[s].required),this.index)for(const a of this.index)ct(s,a.signature)&&(r=r?.and(a.value)??a.value);if(this.sequence&&ct(s,p.intrinsic.nonNegativeIntegerString))if(b(s,"root"))this.sequence.variadic&&(r=r?.and(this.sequence.element)??this.sequence.element);else{const a=Number.parseInt(s);if(a<this.sequence.prevariadic.length){const l=this.sequence.prevariadic[a].node;r=r?.and(l)??l,i||=a<this.sequence.prefixLength}else if(this.sequence.variadic){const l=this.$.node("union",this.sequence.variadicOrPostfix);r=r?.and(l)??l}}if(!r)return this.sequence?.variadic&&b(s,"root")&&s.extends(p.intrinsic.number)?d(wl(s.expression,this.sequence.expression)):d(or(this.expression,[s]));const o=r.get(...n);return i?o:o.or(p.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(){const{required:e,...n}=this.inner;return this.$.node("structure",{...n,optional:this.props.map(r=>r.hasKind("required")?this.$.node("optional",r.inner):r)})}require(){const{optional:e,...n}=this.inner;return this.$.node("structure",{...n,required:this.props.map(r=>r.hasKind("optional")?{key:r.key,value:r.value}:r)})}merge(e){const n=this.filterKeys("omit",[e.keyof()]);return e.required&&(n.required=N(n.required,e.required)),e.optional&&(n.optional=N(n.optional,e.optional)),e.index&&(n.index=N(n.index,e.index)),e.sequence&&(n.sequence=e.sequence),e.undeclared?n.undeclared=e.undeclared:delete n.undeclared,this.$.node("structure",n)}filterKeys(e,n){const r=gi(this.inner),i=s=>{const o=n.some(a=>ct(s,a));return e==="pick"?o:!o};return r.required&&(r.required=r.required.filter(s=>i(s.key))),r.optional&&(r.optional=r.optional.filter(s=>i(s.key))),r.index&&(r.index=r.index.filter(s=>i(s.signature))),r}traverseAllows=(e,n)=>this._traverse("Allows",e,n);traverseApply=(e,n)=>this._traverse("Apply",e,n);_traverse=(e,n,r)=>{const i=r?.currentErrorCount??0;for(let s=0;s<this.props.length;s++)if(e==="Allows"){if(!this.props[s].traverseAllows(n,r))return!1}else if(this.props[s].traverseApply(n,r),r.failFast&&r.currentErrorCount>i)return!1;if(this.sequence){if(e==="Allows"){if(!this.sequence.traverseAllows(n,r))return!1}else if(this.sequence.traverseApply(n,r),r.failFast&&r.currentErrorCount>i)return!1}if(this.index||this.undeclared==="reject"){const s=Object.keys(n);s.push(...Object.getOwnPropertySymbols(n));for(let o=0;o<s.length;o++){const a=s[o];if(this.index){for(const l of this.index)if(l.signature.traverseAllows(a,r)){if(e==="Allows"){if(!se(a,()=>l.value.traverseAllows(n[a],r),r))return!1}else if(se(a,()=>l.value.traverseApply(n[a],r),r),r.failFast&&r.currentErrorCount>i)return!1}}if(this.undeclared==="reject"&&!this.declaresKey(a)&&(e==="Allows"||(r.errorFromNodeContext({code:"predicate",expected:"removed",actual:"",relativePath:[a],meta:this.meta}),r.failFast)))return!1}}return this.structuralMorph&&r&&!r.hasError()&&r.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(n=>n.signature.allows(e))||this.sequence!==void 0&&p.intrinsic.nonNegativeIntegerString.allows(e);_compileDeclaresKey(e){const n=[];if(this.props.length&&n.push(`k in ${this.propsByKeyReference}`),this.index)for(const r of this.index)n.push(e.invoke(r.signature,{kind:"Allows",arg:"k"}));return this.sequence&&n.push("$ark.intrinsic.nonNegativeIntegerString.allows(k)"),n.join(" || ")||"false"}get structuralMorph(){return this.cacheGetter("structuralMorph",yl(this))}structuralMorphRef=this.structuralMorph&&z(this.structuralMorph);compile(e){e.traversalKind==="Apply"&&e.initializeErrorCount();for(const n of this.props)e.check(n),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(["),bl(e,this),e.line("])")))}compileExhaustiveEntry(e){if(e.const("k","keys[i]"),this.index)for(const n of this.index)e.if(`${e.invoke(n.signature,{arg:"k",kind:"Allows"})}`,()=>e.traverseKey("k","data[k]",n.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,n){switch(e.type){case"object":return this.reduceObjectJsonSchema(e,n);case"array":const r=this.sequence?.reduceJsonSchema(e,n)??e;return this.props.length||this.index?n.fallback.arrayObject({code:"arrayObject",base:r,object:this.reduceObjectJsonSchema({type:"object"},n)}):r;default:return L.throwInternalOperandError("structure",e)}}reduceObjectJsonSchema(e,n){if(this.props.length){e.properties={};for(const r of this.props){const i=r.value.toJsonSchemaRecurse(n);if(typeof r.key=="symbol"){n.fallback.symbolKey({code:"symbolKey",base:e,key:r.key,value:i,optional:r.optional});continue}if(r.hasDefault()){const s=typeof r.default=="function"?r.default():r.default;i.default=p.intrinsic.jsonData.allows(s)?s:n.fallback.defaultValue({code:"defaultValue",base:i,value:s})}e.properties[r.key]=i}this.requiredKeys.length&&e.properties&&(e.required=this.requiredKeys.filter(r=>typeof r=="string"&&r in e.properties))}if(this.index)for(const r of this.index){const i=r.value.toJsonSchemaRecurse(n);if(r.signature.equals(p.intrinsic.string)){e.additionalProperties=i;continue}for(const s of r.signature.branches){if(!s.extends(p.intrinsic.string)){e=n.fallback.symbolKey({code:"symbolKey",base:e,key:null,value:i,optional:!1});continue}let o={type:"string"};if(s.hasKind("morph")&&(o=n.fallback.morph({code:"morph",base:s.rawIn.toJsonSchemaRecurse(n),out:s.rawOut.toJsonSchemaRecurse(n)})),!s.hasKind("intersection"))return D(`Unexpected index branch kind ${s.kind}.`);const{pattern:a}=s.inner;if(a){const l=Object.assign(o,{pattern:a[0].rule});for(let c=1;c<a.length;c++)o=n.fallback.patternIntersection({code:"patternIntersection",base:l,pattern:a[c].rule});e.patternProperties??={},e.patternProperties[l.pattern]=i}}}return this.undeclared&&!e.additionalProperties&&(e.additionalProperties=!1),e}}const jt={},gl=t=>{let e="";for(let n=0;n<t.defaultable.length;n++)e+=t.defaultable[n].defaultValueMorphRef;if(t.sequence?.defaultValueMorphsReference&&(e+=t.sequence?.defaultValueMorphsReference),t.undeclared==="delete"){if(e+="delete !(",t.required)for(const n of t.required)e+=n.compiledKey+" | ";if(t.optional)for(const n of t.optional)e+=n.compiledKey+" | ";if(t.index)for(const n of t.index)e+=n.signature.id+" | ";if(t.sequence)if(t.sequence.maxLength===null)e+=$.nonNegativeIntegerString.id;else for(let n=0;n<t.sequence.tuple.length;n++)e+=n+" | ";e+=")"}return e},yl=t=>{const e=gl(t);if(!e)return;if(jt[e])return jt[e];const n=(r,i)=>{for(let s=0;s<t.defaultable.length;s++)t.defaultable[s].key in r||t.defaultable[s].defaultValueMorph(r,i);if(t.sequence?.defaultables)for(let s=r.length-t.sequence.prefixLength;s<t.sequence.defaultables.length;s++)t.sequence.defaultValueMorphs[s](r,i);if(t.undeclared==="delete")for(const s in r)t.declaresKey(s)||delete r[s];return r};return jt[e]=n},bl=(t,e)=>{const r=`(data${e.defaultable.some(i=>i.defaultValueMorph.length===2)||e.sequence?.defaultValueMorphs.some(i=>i.length===2)?", ctx":""})`;return t.block(`${r} => `,i=>{for(let s=0;s<e.defaultable.length;s++){const{serializedKey:o,defaultValueMorphRef:a}=e.defaultable[s];i.if(`!(${o} in data)`,l=>l.line(`${a}${r}`))}return e.sequence?.defaultables&&i.for(`i < ${e.sequence.defaultables.length}`,s=>s.set("data[i]",5),`data.length - ${e.sequence.prefixLength}`),e.undeclared==="delete"&&i.forIn("data",s=>s.if(`!(${e._compileDeclaresKey(s)})`,o=>o.line("delete data[k]"))),i.return("data")})},ts={implementation:fl,Node:ml},$l=t=>(b(t,"root")&&t.hasKind("unit")&&(t=t.unit),typeof t=="number"&&(t=`${t}`),t),wl=(t,e)=>`${t} is not allowed as an array index on ${e}. Use the 'nonNegativeIntegerString' keyword instead.`,rn=(t,e,n)=>{const[r,i]=yo(t.branches,o=>o.hasKind("unit"));if(!r.length)return{index:n.node("index",{signature:t,value:e})};const s={};for(const o of r){const a=n.node("required",{key:o.unit,value:e});s[a.kind]=N(s[a.kind],a)}return i.length&&(s.index=n.node("index",{signature:i,value:e})),s},vl=t=>b(t,"root")?t.expression:S(t),or=(t,e)=>`Key${e.length===1?"":"s"} ${e.map(vl).join(", ")} ${e.length===1?"does":"do"} not exist on ${t}`,Ct={...lc,alias:Sn.implementation,domain:On.implementation,unit:Hi.implementation,proto:vt.implementation,union:Wi.implementation,morph:Vi.implementation,intersection:Ji.implementation,divisor:Ni.implementation,pattern:ji.implementation,predicate:Si.implementation,required:Yi.implementation,optional:An.implementation,index:Zi.implementation,sequence:Qi.implementation,structure:ts.implementation};p.defaultConfig=Ro(Object.assign(O(Ct,(t,e)=>[t,e.defaults]),{jitless:jo(),clone:Do,onUndeclaredKey:"ignore",exactOptionalPropertyTypes:!0,numberAllowsNaN:!1,dateAllowsInvalid:!1,onFail:null,keywords:{},toJsonSchema:L.defaultConfig}));p.resolvedConfig=Qt(p.defaultConfig,p.config);const xl={...uc,alias:Sn.Node,domain:On.Node,unit:Hi.Node,proto:vt.Node,union:Wi.Node,morph:Vi.Node,intersection:Ji.Node,divisor:Ni.Node,pattern:ji.Node,predicate:Si.Node,required:Yi.Node,optional:An.Node,index:Zi.Node,sequence:Qi.Node,structure:ts.Node};class sn extends Io{get[ie](){return"module"}}const ns=(t,e)=>new sn(O(t,(n,r)=>[n,b(r,"module")?ns(r,e):e.bindReference(r)])),kl=t=>F(t)?t:"branches"in t&&F(t.branches)?t.branches:void 0,Al=(t,e)=>d(`Node of kind ${e} is not valid as a ${t} definition`),ar=t=>`#${t} duplicates public alias ${t}`,Ft={};p.ambient??={};let cr;const rs="function $",Il=t=>is(t,ss(t)),is=(t,e)=>{const n=e.write(rs,4),r=e.compile()();for(const i of t)i.precompilation||(i.traverseAllows=r[`${i.id}Allows`].bind(r),i.isRoot()&&!i.allowsRequiresContext&&(i.allows=i.traverseAllows),i.traverseApply=r[`${i.id}Apply`].bind(r),r[`${i.id}Optimistic`]&&(i.traverseOptimistic=r[`${i.id}Optimistic`].bind(r)),i.precompilation=n)},ss=t=>(new pi).return(t.reduce((e,n)=>{const r=new Lt({kind:"Allows"}).indent();n.compile(r);const i=r.write(`${n.id}Allows`),s=new Lt({kind:"Apply"}).indent();n.compile(s);const o=s.write(`${n.id}Apply`),a=`${e}${i},\n${o},\n`;if(!n.hasKind("union"))return a;const l=new Lt({kind:"Allows",optimistic:!0}).indent();n.compile(l);const c=l.write(`${n.id}Optimistic`);return`${a}${c},\n`},`{\n`)+"}");class os{config;resolvedConfig;name;get[ie](){return"scope"}referencesById={};references=[];resolutions={};exportedNames=[];aliases={};resolved=!1;nodesByHash={};intrinsic;constructor(e,n){this.config=Qt(p.config,n),this.resolvedConfig=Qt(p.resolvedConfig,n),this.name=this.resolvedConfig.name??`anonymousScope${Object.keys(Ft).length}`,this.name in Ft&&d(`A Scope already named ${this.name} already exists`),Ft[this.name]=this;const r=Object.entries(e).map(i=>this.preparseOwnAliasEntry(...i));for(const[i,s]of r){let o=i;if(i[0]==="#"?(o=i.slice(1),o in this.aliases&&d(ar(o)),this.aliases[o]=s):(o in this.aliases&&d(ar(i)),this.aliases[o]=s,this.exportedNames.push(o)),!b(s,"module")&&!b(s,"generic")&&!At(s)){const a=this.preparseOwnDefinitionFormat(s,{alias:o});this.resolutions[o]=b(a,"root")?this.bindReference(a):this.createParseContext(a).id}}cr??=this.node("union",{branches:["string","number","object","bigint","symbol",{unit:!0},{unit:!1},{unit:void 0},{unit:null}]},{prereduced:!0}),this.nodesByHash[cr.hash]=this.node("intersection",{},{prereduced:!0}),this.intrinsic=p.intrinsic?O(p.intrinsic,(i,s)=>i.startsWith("json")?[]:[i,this.bindReference(s)]):{}}cacheGetter(e,n){return Object.defineProperty(this,e,{value:n}),n}get internal(){return this}_json;get json(){return this._json||this.export(),this._json}defineSchema(e){return e}generic=(...e)=>{const n=this;return(r,i)=>new wt(e,i?new Ii(r):r,n,n,i??null)};units=(e,n)=>{const r=[];for(const s of e)r.includes(s)||r.push(s);const i=r.map(s=>this.node("unit",{unit:s},n));return this.node("union",i,{...n,prereduced:!0})};lazyResolutions=[];lazilyResolve(e,n){const r=this.node("alias",{reference:n??"synthetic",resolve:e},{prereduced:!0});return this.resolved||this.lazyResolutions.push(r),r}schema=(e,n)=>this.finalize(this.parseSchema(e,n));parseSchema=(e,n)=>this.node(dt(e),e,n);preparseNode(e,n,r){let i=typeof e=="string"?e:dt(n,e);if(U(n)&&n.kind===i)return n;if(i==="alias"&&!r?.prereduced){const{reference:a}=Sn.implementation.normalize(n,this);if(a.startsWith("$")){const l=this.resolveRoot(a.slice(1));n=l,i=l.kind}}else if(i==="union"&&$e(n,"object")){const a=kl(n);a?.length===1&&(n=a[0],i=dt(n))}if(U(n)&&n.kind===i)return n;const o=Ct[i].normalize?.(n,this)??n;return U(o)?o.kind===i?o:Al(i,o.kind):{...r,$:this,kind:i,def:o,prefix:r.alias??i}}bindReference(e){let n;return U(e)?n=e.$===this?e:new e.constructor(e.attachments,this):n=e.$===this?e:new wt(e.params,e.bodyDef,e.$,this,e.hkt),this.resolved||Object.assign(this.referencesById,n.referencesById),n}resolveRoot(e){return this.maybeResolveRoot(e)??d(us(e))}maybeResolveRoot(e){const n=this.maybeResolve(e);if(!b(n,"generic"))return n}maybeResolveSubalias(e){return on(this.aliases,e)??on(this.ambient,e)}get ambient(){return p.ambient}maybeResolve(e){const n=this.resolutions[e];if(n){if(typeof n!="string")return this.bindReference(n);const i=W[n];if(b(i,"root"))return this.resolutions[e]=i;if(b(i,"context")){if(i.phase==="resolving")return this.node("alias",{reference:`$${e}`},{prereduced:!0});if(i.phase==="resolved")return D(`Unexpected resolved context for was uncached by its scope: ${S(i)}`);i.phase="resolving";const s=this.bindReference(this.parseOwnDefinitionFormat(i.def,i));return i.phase="resolved",W[s.id]=s,W[i.id]=s,this.resolutions[e]=s}return D(`Unexpected nodesById entry for ${n}: ${S(i)}`)}let r=this.aliases[e]??this.ambient?.[e];return r?(r=this.normalizeRootScopeValue(r),b(r,"generic")?this.resolutions[e]=this.bindReference(r):b(r,"module")?(r.root||d(ds(e)),this.resolutions[e]=this.bindReference(r.root)):this.resolutions[e]=this.parse(r,{alias:e})):this.maybeResolveSubalias(e)}createParseContext(e){const n=e.id??Fi(e.prefix);return W[n]=Object.assign(e,{[ie]:"context",$:this,id:n,phase:"unresolved"})}traversal(e){return new Ne(e,this.resolvedConfig)}import(...e){return new sn(O(this.export(...e),(n,r)=>[`#${n}`,r]))}precompilation;_exportedResolutions;_exports;export(...e){if(!this._exports){this._exports={};for(const r of this.exportedNames){const i=this.aliases[r];this._exports[r]=b(i,"module")?ns(i,this):lr(this.maybeResolve(r))}for(const r of this.lazyResolutions)r.resolution;if(this._exportedResolutions=ls(this,this._exports),this._json=cs(this._exportedResolutions),Object.assign(this.resolutions,this._exportedResolutions),this.references=Object.values(this.referencesById),!this.resolvedConfig.jitless){const r=ss(this.references);this.precompilation=r.write(rs,4),is(this.references,r)}this.resolved=!0}const n=e.length?e:this.exportedNames;return new sn(O(n,(r,i)=>[i,this._exports[i]]))}resolve(e){return this.export()[e]}node=(e,n,r={})=>{const i=this.preparseNode(e,n,r);if(U(i))return this.bindReference(i);const s=this.createParseContext(i),o=Ui(s),a=this.bindReference(o);return W[s.id]=a};parse=(e,n={})=>this.finalize(this.parseDefinition(e,n));parseDefinition(e,n={}){if(b(e,"root"))return this.bindReference(e);const r=this.preparseOwnDefinitionFormat(e,n);if(b(r,"root"))return this.bindReference(r);const i=this.createParseContext(r);W[i.id]=i;let s=this.bindReference(this.parseOwnDefinitionFormat(e,i));return s.isCyclic&&(s=mc(s,i.id)),W[i.id]=s,s}finalize(e){return lr(e),!e.precompilation&&!this.resolvedConfig.jitless&&Il(e.references),e}}class as extends os{parseOwnDefinitionFormat(e,n){return Ui(n)}preparseOwnDefinitionFormat(e,n){return this.preparseNode(dt(e),e,n)}preparseOwnAliasEntry(e,n){return[e,n]}normalizeRootScopeValue(e){return e}}const lr=t=>{const e=t.references.filter(n=>n.hasKind("alias"));for(const n of e){Object.assign(n.referencesById,n.resolution.referencesById);for(const r of t.references)n.id in r.referencesById&&Object.assign(r.referencesById,n.referencesById)}return t},cs=t=>O(t,(e,n)=>[e,b(n,"root")||b(n,"generic")?n.json:b(n,"module")?cs(n):D(`Unexpected resolution ${S(n)}`)]),on=(t,e)=>{const n=e.indexOf(".");if(n===-1)return;const r=e.slice(0,n),i=t[r];if(i===void 0)return;if(!b(i,"module"))return d(Sl(r));const s=e.slice(n+1),o=i[s];if(o===void 0)return on(i,s);if(b(o,"root")||b(o,"generic"))return o;if(b(o,"module"))return o.root??d(ds(e));D(`Unexpected resolution for alias '${e}': ${S(o)}`)},Rn=(t,e)=>new as(t,e),rt=new as({}),ls=(t,e)=>{const n={};for(const r in e){const i=e[r];if(b(i,"module")){const s=ls(t,i),o=O(s,(a,l)=>[`${r}.${a}`,l]);Object.assign(n,o)}else b(i,"root")||b(i,"generic")?n[r]=i:D(`Unexpected scope resolution ${S(i)}`)}return n},us=t=>`'${t}' is unresolvable`,Sl=t=>`'${t}' must reference a module to be accessed using dot syntax`,ds=t=>`Reference to submodule '${t}' must specify an alias`;rt.export();const R=rt.schema,Cn=rt.node;rt.defineSchema;const ae=rt.generic,hs="^(?:0|[1-9]\\d*)$",Nl=new RegExp(hs);z(Nl);const ps=Rn({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:Array,Date:Date},{prereducedAliases:!0}).export();p.intrinsic={...ps};const fs=Rn({integer:{domain:"number",divisor:1},lengthBoundable:["string",Array],key:["string","symbol"],nonNegativeIntegerString:{domain:"string",pattern:hs}},{prereducedAliases:!0}).export();Object.assign(p.intrinsic,fs);const Ol=Rn({jsonPrimitive:["string","number",{unit:!0},{unit:!1},{unit:null}],jsonObject:{domain:"object",index:{signature:"string",value:"$jsonData"}},jsonData:["$jsonPrimitive","$jsonObject"]},{prereducedAliases:!0}).export(),$={...ps,...fs,...Ol,emptyStructure:Cn("structure",{},{prereduced:!0})};p.intrinsic={...$};const Rl=t=>typeof t=="string"&&t[0]==="d"&&(t[1]==="'"||t[1]==='"')&&t.at(-1)===t[1],ur=t=>t.toString()!=="Invalid Date",Cl=t=>t.slice(2,-1),ms=t=>`'${t}' could not be parsed by the Date constructor`,Ml=(t,e)=>Pl(t,e),Pl=(t,e)=>{const n=new Date(t);if(ur(n))return n;const r=na(t);if(r!==void 0){const i=new Date(r);if(ur(i))return i}return e?d(e===!0?ms(t):e):void 0},dr=(t,e)=>{const n=t.scanner.shiftUntilEscapable(Kl[ys[e]]);if(t.scanner.lookahead==="")return t.error(Ll(n,e));if(t.scanner.shift(),e==="/"){try{new RegExp(n)}catch(r){d(String(r))}t.root=t.ctx.$.node("intersection",{domain:"string",pattern:n},{prereduced:!0})}else if(te(e,gs))t.root=t.ctx.$.node("unit",{unit:n});else{const r=Ml(n,ms(n));t.root=t.ctx.$.node("unit",{meta:n,unit:r})}},gs={"'":1,'"':1},ql={"/":1,"'":1,'"':1},El={"d'":"'",'d"':'"',"'":"'",'"':'"'},ys={...El,"/":"/"},Kl={"'":t=>t.lookahead==="'",'"':t=>t.lookahead==='"',"/":t=>t.lookahead==="/"},Dl={'"':"double-quote","'":"single-quote","/":"forward slash"},Ll=(t,e)=>`${e}${t} requires a closing ${Dl[ys[e]]}`,Bl=t=>`Private type references should not include '#'. Use '${t}' instead.`,bs="Optional definitions like 'string?' are only valid as properties in an object or tuple",$s="Defaultable definitions like 'number = 0' are only valid as properties in an object or tuple",Le={"<":1,">":1,"=":1,"|":1,"&":1,")":1,"[":1,"%":1,",":1,":":1,"?":1,"#":1,...It},jl=(t,e)=>t===">"?e[0]==="="?e[1]==="=":e.trimStart()===""||te(e.trimStart()[0],Le):t==="="?e[0]!=="=":t===","||t==="?",Fl=(t,e,n)=>ws(t,e,n,[]),ws=(t,e,n,r)=>{const i=n.parseUntilFinalizer();return r.push(i.root),i.finalizer===">"?r.length!==e.params.length?n.error(vs(t,e.names,r.map(s=>s.expression))):r:i.finalizer===","?ws(t,e,n,r):i.error(di(">"))},vs=(t,e,n)=>`${t}<${e.join(", ")}> requires exactly ${e.length} args (got ${n.length}${n.length===0?"":`: ${n.join(", ")}`})`,hr=t=>{const e=t.scanner.shiftUntilLookahead(Le);e==="keyof"?t.addPrefix("keyof"):t.root=zl(t,e)},Ul=(t,e,n)=>{if(n.scanner.shiftUntilNonWhitespace(),n.scanner.shift()!=="<")return n.error(vs(t,e.names,[]));const i=Fl(t,e,n);return e(...i)},zl=(t,e)=>Tl(t,e)??_l(t,e)??t.error(e===""?t.scanner.lookahead==="#"?Bl(t.shiftedByOne().scanner.shiftUntilLookahead(Le)):xs(t):us(e)),Tl=(t,e)=>{if(t.ctx.args?.[e]){const r=t.ctx.args[e];return typeof r!="string"?r:t.ctx.$.node("alias",{reference:r},{prereduced:!0})}const n=t.ctx.$.maybeResolve(e);if(b(n,"root"))return n;if(n!==void 0)return b(n,"generic")?Ul(e,n,t):d(`Unexpected resolution ${S(n)}`)},_l=(t,e)=>{const n=ra(e);if(n!==void 0)return t.ctx.$.node("unit",{unit:n});const r=sa(e);if(r!==void 0)return t.ctx.$.node("unit",{unit:r})},xs=t=>{const e=t.previousOperator();return e?ks(e,t.scanner.unscanned):Jl(t.scanner.unscanned)},ks=(t,e="")=>`Token '${t}' requires a right operand${e?` before '${e}'`:""}`,Jl=t=>`Expected an expression${t?` before '${t}'`:""}`,As=t=>t.scanner.lookahead===""?t.error(xs(t)):t.scanner.lookahead==="("?t.shiftedByOne().reduceGroupOpen():t.scanner.lookaheadIsIn(ql)?dr(t,t.scanner.shift()):t.scanner.lookaheadIsIn(It)?As(t.shiftedByOne()):t.scanner.lookahead==="d"&&t.scanner.nextLookahead in gs?dr(t,`${t.scanner.shift()}${t.scanner.shift()}`):hr(t),Vl={">":!0,">=":!0},Gl={"<":!0,"<=":!0},xt={"<":">",">":"<","<=":">=",">=":"<=","==":"=="},Wl=(t,e)=>`Left bounds are only valid when paired with right bounds (try ...${e}${t})`,Is=t=>`Left-bounded expressions must specify their limits using < or <= (was ${t})`,Hl=(t,e,n,r)=>`An expression may have at most one left bound (parsed ${t}${xt[e]}, ${n}${xt[r]})`,Zl=(t,e)=>{const n=Ql(t,e);if(t.root.hasKind("unit")){if(typeof t.root.unit=="number"){t.reduceLeftBound(t.root.unit,n),t.unsetRoot();return}if(t.root.unit instanceof Date){const r=`d'${t.root.description??t.root.unit.toISOString()}'`;t.unsetRoot(),t.reduceLeftBound(r,n);return}}return eu(t,n)},Yl={"<":1,">":1,"=":1},Ql=(t,e)=>t.scanner.lookaheadIs("=")?`${e}${t.scanner.shift()}`:e,pr=(t,e,n,r)=>n.extends(p.intrinsic.number)?typeof e!="number"?d(an(t,e,r)):t==="=="?["min","max"]:t[0]===">"?["min"]:["max"]:n.extends(p.intrinsic.lengthBoundable)?typeof e!="number"?d(an(t,e,r)):t==="=="?["exactLength"]:t[0]===">"?["minLength"]:["maxLength"]:n.extends(p.intrinsic.Date)?t==="=="?["after","before"]:t[0]===">"?["after"]:["before"]:d(Wa(n.expression)),Xl=t=>({rule:Rl(t.limit)?Cl(t.limit):t.limit,exclusive:t.comparator.length===1}),eu=(t,e)=>{const n=t.unsetRoot(),r=t.scanner.location;t.parseOperand();const i=t.unsetRoot(),s=t.scanner.sliceChars(r,t.scanner.location);if(t.root=n,!i.hasKind("unit")||typeof i.unit!="number"&&!(i.unit instanceof Date))return t.error(an(e,s,"right"));const o=i.unit,a=e.length===1,l=pr(e,typeof o=="number"?o:s,n,"right");for(const u of l)t.constrainRoot(u,e==="=="?{rule:o}:{rule:o,exclusive:a});if(!t.branches.leftBound)return;if(!te(e,Gl))return t.error(Is(e));const c=pr(t.branches.leftBound.comparator,t.branches.leftBound.limit,n,"left");t.constrainRoot(c[0],Xl(t.branches.leftBound)),t.branches.leftBound=null},an=(t,e,n)=>`Comparator ${n==="left"?xt[t]:t} must be ${n==="left"?"preceded":"followed"} by a corresponding literal (was ${e})`,tu=t=>{t.scanner.shiftUntilNonWhitespace();const e=t.scanner.shiftUntilLookahead(Le);t.root=t.root.brand(e)},nu=t=>{t.scanner.shiftUntilNonWhitespace();const e=t.scanner.shiftUntilLookahead(Le),n=ia(e,{errorOnFail:fr(e)});n===0&&t.error(fr(0)),t.root=t.root.constrain("divisor",n)},fr=t=>`% operator must be followed by a non-zero integer literal (was ${t})`,Ss=t=>{const e=t.scanner.shift();return e===""?t.finalize(""):e==="["?t.scanner.shift()==="]"?t.setRoot(t.root.array()):t.error(ru):e==="|"?t.scanner.lookahead===">"?t.shiftedByOne().pushRootToBranch("|>"):t.pushRootToBranch(e):e==="&"?t.pushRootToBranch(e):e===")"?t.finalizeGroup():jl(e,t.scanner.unscanned)?t.finalize(e):te(e,Yl)?Zl(t,e):e==="%"?nu(t):e==="#"?tu(t):e in It?Ss(t):t.error(Mn(e))},Mn=(t,e="")=>`'${t}' is not allowed here${e&&` (should be ${e})`}`,ru="Missing expected ']'",iu=t=>{const e=t.unsetRoot();t.parseOperand();const n=t.unsetRoot();if(!n.hasKind("unit"))return t.error(su(n.expression));const r=n.unit instanceof Date?()=>new Date(n.unit):n.unit;return[e,"=",r]},su=t=>`Default value '${t}' must be a literal value`,mr=(t,e)=>{const n=e.$.maybeResolveRoot(t);if(n)return n;if(t.endsWith("[]")){const s=e.$.maybeResolveRoot(t.slice(0,-2));if(s)return s.array()}const r=new Mt(new ui(t),e),i=ou(r);return r.finalizer===">"&&d(Mn(">")),i},ou=t=>{t.parseOperand();let e=Pn(t).root;return e?(t.finalizer==="="?e=iu(t):t.finalizer==="?"&&(e=[e,"?"]),t.scanner.shiftUntilNonWhitespace(),t.scanner.lookahead&&d(Mn(t.scanner.lookahead)),e):D(`Root was unexpectedly unset after parsing string '${t.scanner.scanned}'`)},Pn=t=>{for(;t.finalizer===void 0;)au(t);return t},au=t=>t.hasRoot()?t.parseOperator():t.parseOperand();class Mt{root;branches={prefixes:[],leftBound:null,intersection:null,union:null,pipe:null};finalizer;groups=[];scanner;ctx;constructor(e,n){this.scanner=e,this.ctx=n}error(e){return d(e)}hasRoot(){return this.root!==void 0}setRoot(e){this.root=e}unsetRoot(){const e=this.root;return this.root=void 0,e}constrainRoot(...e){this.root=this.root.constrain(e[0],e[1])}finalize(e){if(this.groups.length)return this.error(di(")"));this.finalizeBranches(),this.finalizer=e}reduceLeftBound(e,n){const r=xt[n];if(!te(r,Vl))return this.error(Is(n));if(this.branches.leftBound)return this.error(Hl(this.branches.leftBound.limit,this.branches.leftBound.comparator,e,r));this.branches.leftBound={comparator:r,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();const e=this.groups.pop();if(!e)return this.error(pa(")",this.scanner.unscanned));this.branches=e}addPrefix(e){this.branches.prefixes.push(e)}applyPrefixes(){for(;this.branches.prefixes.length;){const e=this.branches.prefixes.pop();this.root=e==="keyof"?this.root.keyof():D(`Unexpected prefix '${e}'`)}}pushRootToBranch(e){this.assertRangeUnset(),this.applyPrefixes();const n=this.root;this.root=void 0,this.branches.intersection=this.branches.intersection?.rawAnd(n)??n,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 Pn(new Mt(this.scanner,this.ctx))}parseOperator(){return Ss(this)}parseOperand(){return As(this)}assertRangeUnset(){if(this.branches.leftBound)return this.error(Wl(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.at(-1)??(this.branches.intersection?"&":this.branches.union?"|":this.branches.pipe?"|>":void 0)}shiftedByOne(){return this.scanner.shift(),this}}const cu="An empty string is not a valid generic parameter name",cn=(t,e,n)=>{t.shiftUntilNonWhitespace();const r=t.shiftUntilLookahead(Le);return r===""?t.lookahead===""&&e.length?e:d(cu):(t.shiftUntilNonWhitespace(),lu(t,r,e,n))},gr="extends ",lu=(t,e,n,r)=>{if(t.shiftUntilNonWhitespace(),t.unscanned.startsWith(gr))t.jumpForward(gr.length);else return t.lookahead===","&&t.shift(),n.push(e),cn(t,n,r);const i=Pn(new Mt(t,r));return n.push([e,i.root]),cn(t,n,r)};class uu extends pe{constructor(e){const n={$:e,raw:e.fn};super((...r)=>{const i=r.indexOf(":"),s=i===-1?r.length-1:i-1,o=r.slice(0,s+1),a=e.parse(o).assertHasKind("intersection");let l=e.intrinsic.unknown;if(i!==-1){if(i!==r.length-2)return d(hu);l=e.parse(r[i+1])}return c=>new du(c,a,l)},{attach:n})}}class du extends pe{raw;params;returns;expression;constructor(e,n,r){const i=`typed ${e.name}`,s={[i]:(...a)=>{const l=n.assert(a),c=e(...l);return r.assert(c)}}[i];super(s),this.raw=e,this.params=n,this.returns=r;let o=n.expression;o[0]==="["&&o.at(-1)==="]"?o=o.slice(1,-1):o.endsWith("[]")&&(o=`...${o}`),this.expression=`(${o}) => ${r?.expression??"unknown"}`}}const hu=`":" must be followed by exactly one return type e.g:\nfn("string", ":", "number")(s => s.length)`;class pu extends pe{$;constructor(e){super((...n)=>new lt(e)(...n),{bind:e}),this.$=e}in(e){return new lt(this.$,e===void 0?void 0:this.$.parse(e))}at(e,n){return new lt(this.$).at(e,n)}case(e,n){return new lt(this.$).case(e,n)}}class lt extends pe{$;in;key;branches=[];constructor(e,n){super(r=>this.caseEntries(Object.entries(r).map(([i,s])=>i==="default"?[i,s]:[this.$.parse(i),s]))),this.$=e,this.in=n}at(e,n){return this.key&&d(mu),this.branches.length&&d(fu),this.key=e,n?this.match(n):this}case(e,n){return this.caseEntry(this.$.parse(e),n)}caseEntry(e,n){const i=(this.key?this.$.parse({[this.key]:e}):e).pipe(n);return this.branches.push(i),this}match(e){return this(e)}strings(e){return this.caseEntries(Object.entries(e).map(([n,r])=>n==="default"?[n,r]:[this.$.node("unit",{unit:n}),r]))}caseEntries(e){for(let n=0;n<e.length;n++){const[r,i]=e[n];if(r==="default")return n!==e.length-1&&d("default may only be specified as the last key of a switch definition"),this.default(i);if(typeof i!="function")return d(`Value for case "${r}" must be a function (was ${Q(i)})`);this.caseEntry(r,i)}return this}default(e){typeof e=="function"&&this.case($.unknown,e);const n={branches:this.branches,ordered:!0};(e==="never"||e==="assert")&&(n.meta={onFail:yr});const r=this.$.node("union",n);if(!this.in)return this.$.finalize(r);let i=this.in.pipe(r);return(e==="never"||e==="assert")&&(i=i.configureReferences({onFail:yr},"self")),this.$.finalize(i)}}const yr=t=>t.throw(),fu="A key matcher must be specified before the first case i.e. match.at('foo') or match.in<object>().at('bar')",mu="At most one key matcher may be specified per expression",Ns=(t,e)=>{if(F(t)){if(t[1]==="=")return[e.$.parseOwnDefinitionFormat(t[0],e),"=",t[2]];if(t[1]==="?")return[e.$.parseOwnDefinitionFormat(t[0],e),"?"]}return Es(t,e)},gu="Only required keys may make their values optional, e.g. { [mySymbol]: ['number', '?'] }",yu="Only required keys may specify default values, e.g. { value: 'number = 0' }",bu=(t,e)=>{let n;const r={},i=ft(t);for(const[o,a]of i){const l=vu(o);if(l.kind==="spread"){if(!Ze(r))return d(wu);const y=e.$.parseOwnDefinitionFormat(a,e);if(y.equals($.object))continue;if(!y.hasKind("intersection")||!y.basis?.equals($.object))return d(xu(y.expression));n=y.structure;continue}if(l.kind==="undeclared"){a!=="reject"&&a!=="delete"&&a!=="ignore"&&d($u(a)),r.undeclared=a;continue}const c=Ns(a,e),u=l;if(l.kind==="required"){F(c)?Ut(r,"optional",c[1]==="="?{key:l.normalized,value:c[0],default:c[2]}:{key:l.normalized,value:c[0]},e):Ut(r,"required",{key:l.normalized,value:c},e);continue}if(F(c)&&(c[1]==="?"&&d(gu),c[1]==="="&&d(yu)),l.kind==="optional"){Ut(r,"optional",{key:l.normalized,value:c},e);continue}const h=e.$.parseOwnDefinitionFormat(u.normalized,e),m=rn(h,c,e.$);m.index&&(r.index=N(r.index,m.index)),m.required&&(r.required=N(r.required,m.required))}const s=e.$.node("structure",r);return e.$.parseSchema({domain:"object",structure:n?.merge(s)??s})},Ut=(t,e,n,r)=>{t[e]=N(t[e],r.$.node(e,n))},$u=t=>`Value of '+' key must be 'reject', 'delete', or 'ignore' (was ${S(t)})`,wu="Spread operator may only be used as the first key in an object",vu=t=>typeof t=="symbol"?{kind:"required",normalized:t}:t.at(-1)==="?"?t.at(-2)===ze?{kind:"required",normalized:`${t.slice(0,-2)}?`}:{kind:"optional",normalized:t.slice(0,-1)}:t[0]==="["&&t.at(-1)==="]"?{kind:"index",normalized:t.slice(1,-1)}:t[0]===ze&&t[1]==="["&&t.at(-1)==="]"?{kind:"required",normalized:t.slice(1)}:t==="..."?{kind:"spread"}:t==="+"?{kind:"undeclared"}:{kind:"required",normalized:t==="\\..."?"...":t==="\\+"?"+":t},xu=t=>`Spread operand must resolve to an object literal type (was ${t})`,ku=(t,e)=>qu(t)?Ms[t[0]](t,e):Mu(t)?Cs[t[1]](t,e):null,Au=(t,e)=>e.$.parseOwnDefinitionFormat(t[1],e).keyof(),zt=(t,e)=>{if(t[2]===void 0)return d(ks(t[1],""));const n=e.$.parseOwnDefinitionFormat(t[0],e),r=e.$.parseOwnDefinitionFormat(t[2],e);if(t[1]==="|")return e.$.node("union",{branches:[n,r]});const i=t[1]==="&"?oe(n,r,e.$):en(n,r,e.$);return i instanceof g?i.throw():i},Iu=(t,e)=>e.$.parseOwnDefinitionFormat(t[0],e).array(),Su=(t,e)=>typeof t[2]!="function"?d(Os("=>",t[2])):e.$.parseOwnDefinitionFormat(t[0],e).pipe(t[2]),Os=(t,e)=>`${t===":"?"Narrow":"Morph"} expression requires a function following '${t}' (was ${typeof e})`,Nu=(t,e)=>typeof t[2]!="function"?d(Os(":",t[2])):e.$.parseOwnDefinitionFormat(t[0],e).constrain("predicate",t[2]),Ou=(t,e)=>e.$.parseOwnDefinitionFormat(t[0],e).configure(t[2],t[3]),Rs=t=>t,Ru=Rs({"[]":Iu,"?":()=>d(bs)}),Cu=Rs({"|":zt,"&":zt,":":Nu,"=>":Su,"|>":zt,"@":Ou,"=":()=>d($s)}),Cs={...Ru,...Cu},Mu=t=>Cs[t[1]]!==void 0,Pu=t=>t,Ms=Pu({keyof:Au,instanceof:(t,e)=>{if(typeof t[1]!="function")return d(br(Gt(t[1])));const n=t.slice(1).map(r=>typeof r=="function"?e.$.node("proto",{proto:r}):d(br(Gt(r))));return n.length===1?n[0]:e.$.node("union",{branches:n})},"===":(t,e)=>e.$.units(t.slice(1))}),qu=t=>Ms[t[0]]!==void 0,br=t=>`Expected a constructor following 'instanceof' operator (was ${t})`,Eu=(t,e)=>{let n=[{}],r=0;for(;r<t.length;){let i=!1;t[r]==="..."&&r<t.length-1&&(i=!0,r++);const s=Ns(t[r],e),[o,a,l]=F(s)?s:[s];if(r++,i){if(!o.extends(p.intrinsic.Array))return d(Lu(o.expression));n=n.flatMap(c=>o.distribute(u=>Du(gi(c),u)))}else n=n.map(c=>a==="?"?Ps(c,o):a==="="?Ku(c,o,l):ln(c,o))}return e.$.parseSchema(n.map(i=>Ze(i)?{proto:Array,exactLength:0}:{proto:Array,sequence:i}))},ln=(t,e)=>t.defaultables||t.optionals?d(t.variadic?Xi:Bu):(t.variadic?t.postfix=N(t.postfix,e):t.prefix=N(t.prefix,e),t),Ps=(t,e)=>t.variadic?d(qs):(t.optionals=N(t.optionals,e),t),Ku=(t,e,n)=>t.variadic?d(qs):t.optionals?d(ju):(t.defaultables=N(t.defaultables,[[e,n]]),t),$r=(t,e)=>(t.postfix&&d(wr),t.variadic?t.variadic.equals(e)||d(wr):t.variadic=e.internal,t),Du=(t,e)=>{const n=e.select({method:"find",kind:"sequence"});if(!n)return $r(t,p.intrinsic.unknown);if(n.prefix)for(const r of n.prefix)ln(t,r);if(n.optionals)for(const r of n.optionals)Ps(t,r);if(n.variadic&&$r(t,n.variadic),n.postfix)for(const r of n.postfix)ln(t,r);return t},Lu=t=>`Spread element must be an array (was ${t})`,wr="A tuple may have at most one variadic element",Bu="A required element may not follow an optional element",qs="An optional element may not follow a variadic element",ju="A defaultable element may not follow an optional element without a default",Fu={},Es=(t,e)=>{if(typeof t=="string"){if(e.args&&Object.keys(e.args).some(r=>t.includes(r)))return mr(t,e);const n=Fu[e.$.name]??={};return n[t]??=mr(t,e)}return $e(t,"object")?Uu(t,e):d(un(Q(t)))},Uu=(t,e)=>{const n=gn(t);switch(n){case void 0:return b(t,"root")?t:bu(t,e);case"Array":return zu(t,e);case"RegExp":return e.$.node("intersection",{domain:"string",pattern:t},{prereduced:!0});case"Function":{const r=At(t)?t():t;return b(r,"root")?r:d(un("Function"))}default:return d(un(n??S(t)))}},zu=(t,e)=>ku(t,e)??Eu(t,e),un=t=>`Type definitions must be strings or objects (was ${t})`;class Tu extends pe{constructor(e){const n=Object.assign({errors:he,hkt:ne,$: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((...r)=>{if(r.length===1)return e.parse(r[0]);if(r.length===2&&typeof r[0]=="string"&&r[0][0]==="<"&&r[0].at(-1)===">"){const i=r[0].slice(1,-1),s=e.parseGenericParams(i,{});return new wt(s,r[1],e,e,null)}return e.parse(r)},{attach:n})}}const Ge=p;class Pt extends os{get ambientAttachments(){if(Ge.typeAttachments)return this.cacheGetter("ambientAttachments",O(Ge.typeAttachments,(e,n)=>[e,this.bindReference(n)]))}preparseOwnAliasEntry(e,n){const r=e.indexOf("<");if(r===-1){if(b(n,"module")||b(n,"generic"))return[e,n];const o=this.name==="ark"?e:e==="root"?this.name:`${this.name}.${e}`,a=this.resolvedConfig.keywords?.[o];return a&&(n=[n,"@",a]),[e,n]}e.at(-1)!==">"&&d("'>' must be the last character of a generic declaration in a scope");const i=e.slice(0,r),s=e.slice(r+1,-1);return[i,()=>{const o=this.parseGenericParams(s,{alias:i});return Ea(o,n,this)}]}parseGenericParams(e,n){return cn(new ui(e),[],this.createParseContext({...n,def:e,prefix:"generic"}))}normalizeRootScopeValue(e){return At(e)&&!b(e,"generic")?e():e}preparseOwnDefinitionFormat(e,n){return{...n,def:e,prefix:n.alias??"type"}}parseOwnDefinitionFormat(e,n){!(n.alias&&n.alias in this.aliases)&&!n.args&&(n.args={this:n.id});const i=Es(e,n);if(F(i)){if(i[1]==="=")return d($s);if(i[1]==="?")return d(bs)}return i}unit=e=>this.units([e]);valueOf=e=>this.units(Co(e));enumerated=(...e)=>this.units(e);instanceOf=e=>this.node("proto",{proto:e},{prereduced:!0});or=(...e)=>this.schema(e.map(n=>this.parse(n)));and=(...e)=>e.reduce((n,r)=>n.and(this.parse(r)),this.intrinsic.unknown);merge=(...e)=>e.reduce((n,r)=>n.merge(this.parse(r)),this.intrinsic.object);pipe=(...e)=>this.intrinsic.unknown.pipe(...e);fn=new uu(this);match=new pu(this);declare=()=>({type:this.type});define(e){return e}type=new Tu(this);static scope=(e,n={})=>new Pt(e,n);static module=(e,n={})=>this.scope(e,n).export()}const _u=Object.assign(Pt.scope,{define:t=>t}),I=Pt;class Ju extends ne{description='merge an object\'s properties onto another like `Merge(User, { isAdmin: "true" })`'}const Vu=ae(["base",$.object],["props",$.object])(t=>t.base.merge(t.props),Ju),Gu=I.module({Key:$.key,Merge:Vu});class Wu extends ne{}const Hu=ae("element")(t=>{const e=t.element.exclude($.Array),n=e.array();return e.rawOr(n).pipe(He).distribute(r=>r.assertHasKind("morph").declareOut(n),R)},Wu),Zu=I.module({root:$.Array,readonly:"root",index:$.nonNegativeIntegerString,liftFrom:Hu},{name:"Array"}),dn=R(["string",Ye.FileConstructor]),Yu=dn.rawOr(dn.array()),vr=R({meta:"an object representing parsed form data",domain:"object",index:{signature:"string",value:Yu}}),Qu=I.module({root:["instanceof",FormData],value:dn,parsed:vr,parse:R({in:FormData,morphs:t=>{const e={};for(const[n,r]of t)if(n in e){const i=e[n];typeof i=="string"||i instanceof Ye.FileConstructor?e[n]=[i,r]:i.push(r)}else e[n]=r;return e},declaredOut:vr})},{name:"FormData"}),Xu=I.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"}),ed={Boolean:1,Number:1,String:1},td=I.module({...O({...Xr,...ti},(t,e)=>t in ed?[]:[t,["instanceof",e]]),Array:Zu,TypedArray:Xu,FormData:Qu}),nd=R({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"}),rd=R({domain:"number",divisor:1}),Ks=I.module({root:$.number,integer:rd,epoch:nd,safe:R({domain:{domain:"number",numberAllowsNaN:!1},min:Number.MIN_SAFE_INTEGER,max:Number.MAX_SAFE_INTEGER}),NaN:["===",Number.NaN],Infinity:["===",Number.POSITIVE_INFINITY],NegativeInfinity:["===",Number.NEGATIVE_INFINITY]},{name:"number"}),M=(t,e,n)=>{const r={domain:"string",pattern:{rule:t.source,flags:t.flags,meta:e}};return n&&(r.meta={format:n}),Cn("intersection",r)},xr=M(mt,"a well-formed integer string"),Ds=I.module({root:xr,parse:R({in:xr,morphs:(t,e)=>{const n=Number.parseInt(t);return Number.isSafeInteger(n)?n:e.error("an integer in the range Number.MIN_SAFE_INTEGER to Number.MAX_SAFE_INTEGER")},declaredOut:$.integer})},{name:"string.integer"}),id=M(/^[\dA-Fa-f]+$/,"hex characters only"),sd=I.module({root:M(/^(?:[\d+/A-Za-z]{4})*(?:[\d+/A-Za-z]{2}==|[\d+/A-Za-z]{3}=)?$/,"base64-encoded"),url:M(/^(?:[\w-]{4})*(?:[\w-]{2}(?:==|%3D%3D)?|[\w-]{3}(?:=|%3D)?)?$/,"base64url-encoded")},{name:"string.base64"}),kr=M(/^[A-Z].*$/,"capitalized"),od=I.module({root:R({in:"string",morphs:t=>t.charAt(0).toUpperCase()+t.slice(1),declaredOut:kr}),preformatted:kr},{name:"string.capitalize"}),ad=t=>{const e=t.replaceAll(/[ -]+/g,"");let n=0,r,i,s=!1;for(let o=e.length-1;o>=0;o--)r=e.substring(o,o+1),i=Number.parseInt(r,10),s?(i*=2,n+=i>=10?i%10+1:i):n+=i,s=!s;return!!(n%10===0&&e)},cd=/^(?: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}))$/,ld=R({domain:"string",pattern:{meta:"a credit card number",rule:cd.source},predicate:{meta:"a credit card number",predicate:ad}}),ud=/^([+-]?\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)?)?)?)?$/,dd=t=>!Number.isNaN(new Date(t).valueOf()),Ar=R({domain:"string",predicate:{meta:"a parsable date",predicate:dd}}).assertHasKind("intersection"),Ir=Ds.root.internal.narrow((t,e)=>{const n=Number.parseInt(t),r=Ks.epoch(n);return r instanceof he?(e.errors.merge(r),!1):!0}).configure({description:"an integer string representing a safe Unix timestamp"},"self").assertHasKind("intersection"),hd=I.module({root:Ir,parse:R({in:Ir,morphs:t=>new Date(t),declaredOut:$.Date})},{name:"string.date.epoch"}),Sr=M(ud,"an ISO 8601 (YYYY-MM-DDTHH:mm:ss.sssZ) date").internal.assertHasKind("intersection"),pd=I.module({root:Sr,parse:R({in:Sr,morphs:t=>new Date(t),declaredOut:$.Date})},{name:"string.date.iso"}),fd=I.module({root:Ar,parse:R({declaredIn:Ar,in:"string",morphs:(t,e)=>{const n=new Date(t);return Number.isNaN(n.valueOf())?e.error("a parsable date"):n},declaredOut:$.Date}),iso:pd,epoch:hd},{name:"string.date"}),md=M(/^[\w%+.-]+@[\d.A-Za-z-]+\.[A-Za-z]{2,}$/,"an email address","email"),Nr="(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])",ce=`(${Nr}[.]){3}${Nr}`,gd=new RegExp(`^${ce}$`),K="(?:[0-9a-fA-F]{1,4})",yd=new RegExp(`^((?:${K}:){7}(?:${K}|:)|(?:${K}:){6}(?:${ce}|:${K}|:)|(?:${K}:){5}(?::${ce}|(:${K}){1,2}|:)|(?:${K}:){4}(?:(:${K}){0,1}:${ce}|(:${K}){1,3}|:)|(?:${K}:){3}(?:(:${K}){0,2}:${ce}|(:${K}){1,4}|:)|(?:${K}:){2}(?:(:${K}){0,3}:${ce}|(:${K}){1,5}|:)|(?:${K}:){1}(?:(:${K}){0,4}:${ce}|(:${K}){1,6}|:)|(?::((?::${K}){0,5}:${ce}|(?::${K}){1,7}|:)))(%[0-9a-zA-Z.]{1,})?$`),bd=I.module({root:["v4 | v6","@","an IP address"],v4:M(gd,"an IPv4 address","ipv4"),v6:M(yd,"an IPv6 address","ipv6")},{name:"string.ip"}),Re="a JSON string",Ls=t=>{if(!(t instanceof SyntaxError))throw t;return`must be ${Re} (${t})`},$d=R({meta:Re,domain:"string",predicate:{meta:Re,predicate:(t,e)=>{try{return JSON.parse(t),!0}catch(n){return e.reject({code:"predicate",expected:Re,problem:Ls(n)})}}}}),wd=(t,e)=>{if(t.length===0)return e.error({code:"predicate",expected:Re,actual:"empty"});try{return JSON.parse(t)}catch(n){return e.error({code:"predicate",expected:Re,problem:Ls(n)})}},vd=I.module({root:$d,parse:R({meta:"safe JSON string parser",in:"string",morphs:wd,declaredOut:$.jsonObject})},{name:"string.json"}),Or=M(/^[a-z]*$/,"only lowercase letters"),xd=I.module({root:R({in:"string",morphs:t=>t.toLowerCase(),declaredOut:Or}),preformatted:Or},{name:"string.lower"}),Bs=["NFC","NFD","NFKC","NFKD"],it=O(Bs,(t,e)=>[e,R({domain:"string",predicate:n=>n.normalize(e)===n,meta:`${e}-normalized unicode`})]),qt=O(Bs,(t,e)=>[e,R({in:"string",morphs:n=>n.normalize(e),declaredOut:it[e]})]),kd=I.module({root:qt.NFC,preformatted:it.NFC},{name:"string.normalize.NFC"}),Ad=I.module({root:qt.NFD,preformatted:it.NFD},{name:"string.normalize.NFD"}),Id=I.module({root:qt.NFKC,preformatted:it.NFKC},{name:"string.normalize.NFKC"}),Sd=I.module({root:qt.NFKD,preformatted:it.NFKD},{name:"string.normalize.NFKD"}),Nd=I.module({root:"NFC",NFC:kd,NFD:Ad,NFKC:Id,NFKD:Sd},{name:"string.normalize"}),Rr=M(Wt,"a well-formed numeric string"),Od=I.module({root:Rr,parse:R({in:Rr,morphs:t=>Number.parseFloat(t),declaredOut:$.number})},{name:"string.numeric"}),Cr="a regex pattern",Rd=R({domain:"string",predicate:{meta:Cr,predicate:(t,e)=>{try{return new RegExp(t),!0}catch(n){return e.reject({code:"predicate",expected:Cr,problem:String(n)})}}},meta:{format:"regex"}}),Cd=/^(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-]+)*))?$/,Md=M(Cd,"a semantic version (see https://semver.org/)"),Mr=M(/^\S.*\S$|^\S?$/,"trimmed"),Pd=I.module({root:R({in:"string",morphs:t=>t.trim(),declaredOut:Mr}),preformatted:Mr},{name:"string.trim"}),Pr=M(/^[A-Z]*$/,"only uppercase letters"),qd=I.module({root:R({in:"string",morphs:t=>t.toUpperCase(),declaredOut:Pr}),preformatted:Pr},{name:"string.upper"}),Ed=t=>URL.canParse(t),qr=R({domain:"string",predicate:{meta:"a URL string",predicate:Ed},meta:{format:"uri"}}),Kd=I.module({root:qr,parse:R({declaredIn:qr,in:"string",morphs:(t,e)=>{try{return new URL(t)}catch{return e.error("a URL string")}},declaredOut:R(URL)})},{name:"string.url"}),Dd=I.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:M(/^[\da-f]{8}-[\da-f]{4}-1[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv1"),v2:M(/^[\da-f]{8}-[\da-f]{4}-2[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv2"),v3:M(/^[\da-f]{8}-[\da-f]{4}-3[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv3"),v4:M(/^[\da-f]{8}-[\da-f]{4}-4[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv4"),v5:M(/^[\da-f]{8}-[\da-f]{4}-5[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv5"),v6:M(/^[\da-f]{8}-[\da-f]{4}-6[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv6"),v7:M(/^[\da-f]{8}-[\da-f]{4}-7[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv7"),v8:M(/^[\da-f]{8}-[\da-f]{4}-8[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv8")},{name:"string.uuid"}),Ld=I.module({root:$.string,alpha:M(/^[A-Za-z]*$/,"only letters"),alphanumeric:M(/^[\dA-Za-z]*$/,"only letters and digits 0-9"),hex:id,base64:sd,capitalize:od,creditCard:ld,date:fd,digits:M(/^\d*$/,"only digits 0-9"),email:md,integer:Ds,ip:bd,json:vd,lower:xd,normalize:Nd,numeric:Od,regex:Rd,semver:Md,trim:Pd,upper:qd,url:Kd,uuid:Dd},{name:"string"}),Bd=I.module({bigint:$.bigint,boolean:$.boolean,false:$.false,never:$.never,null:$.null,number:$.number,object:$.object,string:$.string,symbol:$.symbol,true:$.true,unknown:$.unknown,undefined:$.undefined}),jd=I.module({root:$.unknown,any:$.unknown},{name:"unknown"}),Fd=I.module({root:$.jsonObject,stringify:Cn("morph",{in:$.jsonObject,morphs:t=>JSON.stringify(t),declaredOut:$.string})},{name:"object.json"}),Ud=I.module({root:$.object,json:Fd},{name:"object"});class zd extends ne{description='instantiate an object from an index signature and corresponding value type like `Record("string", "number")`'}const Td=ae(["K",$.key],"V")(t=>({domain:"object",index:{signature:t.K,value:t.V}}),zd);class _d extends ne{description='pick a set of properties from an object like `Pick(User, "name | age")`'}const Jd=ae(["T",$.object],["K",$.key])(t=>t.T.pick(t.K),_d);class Vd extends ne{description='omit a set of properties from an object like `Omit(User, "age")`'}const Gd=ae(["T",$.object],["K",$.key])(t=>t.T.omit(t.K),Vd);class Wd extends ne{description="make all named properties of an object optional like `Partial(User)`"}const Hd=ae(["T",$.object])(t=>t.T.partial(),Wd);class Zd extends ne{description="make all named properties of an object required like `Required(User)`"}const Yd=ae(["T",$.object])(t=>t.T.required(),Zd);class Qd extends ne{description='exclude branches of a union like `Exclude("boolean", "true")`'}const Xd=ae("T","U")(t=>t.T.exclude(t.U),Qd);class eh extends ne{description='extract branches of a union like `Extract("0 | false | 1", "number")`'}const th=ae("T","U")(t=>t.T.extract(t.U),eh),nh=I.module({Exclude:Xd,Extract:th,Omit:Gd,Partial:Hd,Pick:Jd,Record:Td,Required:Yd}),fe=_u({...Bd,...nh,...td,...Gu,string:Ld,number:Ks,object:Ud,unknown:jd},{prereducedAliases:!0,name:"ark"}),B=fe.export();Object.assign(Ge.ambient,B);Ge.typeAttachments={string:B.string.root,number:B.number.root,bigint:B.bigint,boolean:B.boolean,symbol:B.symbol,undefined:B.undefined,null:B.null,object:B.object.root,unknown:B.unknown.root,false:B.false,true:B.true,never:B.never,arrayIndex:B.Array.index,Key:B.Key,Record:B.Record,Array:B.Array.root,Date:B.Date};const js=Object.assign(fe.type,Ge.typeAttachments);fe.match;fe.fn;fe.generic;fe.schema;fe.define;fe.declare;const rh="/api/plugin/content-loading-plugin",Fs=rh,Us=go(import.meta.url);async function ih(t){const e=`${Fs}${t}`,n=await fetch(e);if(n.status!==200)throw new Error(`api error ${n.status}`);return await n.text()}function hn(t){const e=document.createElement("div");return e.innerHTML=t,[...e.children]}const zs=t=>t!=null&&(t=Object.getPrototypeOf(t),t===Array.prototype||t===Object.prototype);function Ts(t,e,n){for(const[r,i]of Object.entries(e)){const s=`${n}.${r}`;t[s]=i,zs(i)&&Ts(t,i,s)}}function sh(t){const e={...t};for(const[n,r]of Object.entries(t))zs(r)&&Ts(e,r,n);return e}const oh=(t,e)=>{if(e)for(const[n,r]of Object.entries(e))t=t.replace(new RegExp(`{{\\s*${n}\\s*}}`,"g"),r);return t},ah=t=>t;function ch(t,e=ah){return(n,...r)=>{n[0]==="."&&(n=n.slice(1));const i=t()?.[n];switch(typeof i){case"function":return i(...r);case"string":return e(i,r[0]);default:return i}}}const lh={nothingMessage:"Keine Ergebnisse gefunden für",search:"Suchen"},uh={loadMore:"Mehr laden"},dh={searchApp:lh,infiniteLoading:uh},hh={nothingMessage:"No results found for",search:"Search"},ph={loadMore:"Load more"},fh={searchApp:hh,infiniteLoading:ph},mh={nothingMessage:"No se encontraron resultados para",search:"Buscar"},gh={loadMore:"Cargar más"},yh={searchApp:mh,infiniteLoading:gh},bh={nothingMessage:"Aucun résultat trouvé pour",search:"Rechercher"},$h={loadMore:"Charger la suite"},wh={searchApp:bh,infiniteLoading:$h},vh={nothingMessage:"Nessun risultato trovato per",search:"Cerca"},xh={loadMore:"Carica altro"},kh={searchApp:vh,infiniteLoading:xh},Ah={nothingMessage:"Nenhum resultado encontrado para",search:"Pesquisar"},Ih={loadMore:"Carregar mais"},Sh={searchApp:Ah,infiniteLoading:Ih},Er={en:fh,fr:wh,es:yh,de:dh,it:kh,pt:Sh};function Et(t){const e=Z(()=>{const r=t in Er?t:"en";return sh(Er[r])});return{t:ch(e,oh)}}var Nh=V('<button class="PaInfiniteLoading-loadButton PaButton"type=button>'),Oh=V("<div class=PaInfiniteLoading-loadMore>"),Rh=V('<img class="PaInfiniteLoading-loading PaLoading"width=50 height=50 alt=…>');const Ch=js({"offset?":"string|undefined","total?":"string|undefined","limit?":"string|undefined","parentDocumentId?":"string|undefined","template?":"string|undefined","labeledWith?":"string|undefined","termNodeId?":"string|undefined","sorting?":"string|undefined","+":"ignore"}).pipe(t=>({offset:X(t.offset)?Number(t.offset):void 0,total:X(t.total)?Number(t.total):void 0,limit:X(t.limit)?Number(t.limit):void 0,parentDocumentId:X(t.parentDocumentId)?t.parentDocumentId:void 0,templateName:X(t.template)?t.template:void 0,termNodeId:X(t.termNodeId)?t.termNodeId:void 0,labeledWith:X(t.labeledWith)?t.labeledWith:void 0,sorting:X(t.sorting)?t.sorting:void 0}));function Mh(t,{language:e}){const{templateName:n,offset:r,total:i,limit:s,parentDocumentId:o,sorting:a,termNodeId:l,labeledWith:c}=Ch.assert(t.dataset);if(!(r===void 0||i===void 0||o===void 0||s===void 0||n===void 0)){if(!e)throw new Error("Missing language");Ph({language:e,limit:s,parentDocumentId:o,root:t,offset:r,total:i,sorting:a,labeledWith:l!==void 0&&c?{termNodeId:l,fieldName:c}:void 0,templateName:n})}}function Ph({language:t,limit:e,root:n,offset:r,total:i,parentDocumentId:s,sorting:o,templateName:a,labeledWith:l}){const{t:c}=Et(t);let u=r;if(u>=i)return;const h=(()=>{var f=Nh();return f.$$click=x,J(f,()=>c("infiniteLoading.loadMore")),f})(),m=(()=>{var f=Oh();return J(f,h),f})(),y=(()=>{var f=Rh();return kt(f,"src",`${Us}/spinner.svg`),f})();n.appendChild(m);async function x(){n.appendChild(y);const f=await qh({limit:e,newOffset:u,parentDocumentId:s,sorting:o,labeledWith:l,templateName:a});for(const w of f)n.insertBefore(w,m);u+=e,u>=i&&m.remove(),y.remove()}}async function qh({limit:t,newOffset:e,parentDocumentId:n,labeledWith:r,sorting:i,templateName:s}){const o=[["template",s],["children-of",n],["offset",e],["limit",t]];i&&o.push(["sorting",i]),r&&(o.push(["labeled-t",r.termNodeId]),o.push(["labeled-f",r.fieldName]));const a=`/partials?${o.map(([c,u])=>`${c}=${encodeURIComponent(u)}`).join("&")}`,l=await ih(a);return hn(l)}fn(["click"]);function _s(){let t=new Set;function e(i){return t.add(i),()=>t.delete(i)}let n=!1;function r(i,s){if(n)return!(n=!1);const o={to:i,options:s,defaultPrevented:!1,preventDefault:()=>o.defaultPrevented=!0};for(const a of t)a.listener({...o,from:a.location,retry:l=>{l&&(n=!0),a.navigate(i,{...s,resolve:!1})}});return!o.defaultPrevented}return{subscribe:e,confirm:r}}let pn;function qn(){(!window.history.state||window.history.state._depth==null)&&window.history.replaceState({...window.history.state,_depth:window.history.length-1},""),pn=window.history.state._depth}Ue||qn();function Eh(t){return{...t,_depth:window.history.state&&window.history.state._depth}}function Kh(t,e){let n=!1;return()=>{const r=pn;qn();const i=r==null?null:pn-r;if(n){n=!1;return}i&&e(i)?(n=!0,window.history.go(-i)):t()}}const Dh=/^(?:[a-z0-9]+:)?\/\//i,Lh=/^\/+|(\/)\/+$/g,Js="http://sr";function _e(t,e=!1){const n=t.replace(Lh,"$1");return n?e||/^[?#]/.test(n)?n:"/"+n:""}function ht(t,e,n){if(Dh.test(e))return;const r=_e(t),i=n&&_e(n);let s="";return!i||e.startsWith("/")?s=r:i.toLowerCase().indexOf(r.toLowerCase())!==0?s=r+i:s=i,(s||"/")+_e(e,!s)}function Bh(t,e){if(t==null)throw new Error(e);return t}function jh(t,e){return _e(t).replace(/\/*(\*.*)?$/g,"")+_e(e)}function Vs(t){const e={};return t.searchParams.forEach((n,r)=>{r in e?Array.isArray(e[r])?e[r].push(n):e[r]=[e[r],n]:e[r]=n}),e}function Fh(t,e,n){const[r,i]=t.split("/*",2),s=r.split("/").filter(Boolean),o=s.length;return a=>{const l=a.split("/").filter(Boolean),c=l.length-o;if(c<0||c>0&&i===void 0&&!e)return null;const u={path:o?"":"/",params:{}},h=m=>n===void 0?void 0:n[m];for(let m=0;m<o;m++){const y=s[m],x=y[0]===":",f=x?l[m]:l[m].toLowerCase(),w=x?y.slice(1):y.toLowerCase();if(x&&Tt(f,h(w)))u.params[w]=f;else if(x||!Tt(f,w))return null;u.path+=`/${f}`}if(i){const m=c?l.slice(-c).join("/"):"";if(Tt(m,h(i)))u.params[i]=m;else return null}return u}}function Tt(t,e){const n=r=>r===t;return e===void 0?!0:typeof e=="string"?n(e):typeof e=="function"?e(t):Array.isArray(e)?e.some(n):e instanceof RegExp?e.test(t):!1}function Uh(t){const[e,n]=t.pattern.split("/*",2),r=e.split("/").filter(Boolean);return r.reduce((i,s)=>i+(s.startsWith(":")?2:3),r.length-(n===void 0?0:1))}function Gs(t){const e=new Map,n=Fr();return new Proxy({},{get(r,i){return e.has(i)||Ur(n,()=>e.set(i,Z(()=>t()[i]))),e.get(i)()},getOwnPropertyDescriptor(){return{enumerable:!0,configurable:!0}},ownKeys(){return Reflect.ownKeys(t())}})}function Ws(t){let e=/(\/?\:[^\/]+)\?/.exec(t);if(!e)return[t];let n=t.slice(0,e.index),r=t.slice(e.index+e[0].length);const i=[n,n+=e[1]];for(;e=/^(\/\:[^\/]+)\?/.exec(r);)i.push(n+=e[1]),r=r.slice(e[0].length);return Ws(r).reduce((s,o)=>[...s,...i.map(a=>a+o)],[])}const zh=100,Hs=Tr(),Zs=Tr(),En=()=>Bh(zr(Hs),"<A> and 'use' router primitives can be only used inside a Route."),Ys=()=>En().navigatorFactory(),Th=()=>En().location,_h=()=>En().params;function Jh(t,e=""){const{component:n,preload:r,load:i,children:s,info:o}=t,a=!s||Array.isArray(s)&&!s.length,l={key:t,component:n,preload:r||i,info:o};return Qs(t.path).reduce((c,u)=>{for(const h of Ws(u)){const m=jh(e,h);let y=a?m:m.split("/*",1)[0];y=y.split("/").map(x=>x.startsWith(":")||x.startsWith("*")?x:encodeURIComponent(x)).join("/"),c.push({...l,originalPath:u,pattern:y,matcher:Fh(y,!a,t.matchFilters)})}return c},[])}function Vh(t,e=0){return{routes:t,score:Uh(t[t.length-1])*1e4-e,matcher(n){const r=[];for(let i=t.length-1;i>=0;i--){const s=t[i],o=s.matcher(n);if(!o)return null;r.unshift({...o,route:s})}return r}}}function Qs(t){return Array.isArray(t)?t:[t]}function Xs(t,e="",n=[],r=[]){const i=Qs(t);for(let s=0,o=i.length;s<o;s++){const a=i[s];if(a&&typeof a=="object"){a.hasOwnProperty("path")||(a.path="");const l=Jh(a,e);for(const c of l){n.push(c);const u=Array.isArray(a.children)&&a.children.length===0;if(a.children&&!u)Xs(a.children,c.pattern,n,r);else{const h=Vh([...n],r.length);r.push(h)}n.pop()}}}return n.length?r:r.sort((s,o)=>o.score-s.score)}function Je(t,e){for(let n=0,r=t.length;n<r;n++){const i=t[n].matcher(e);if(i)return i}return[]}function Gh(t,e,n){const r=new URL(Js),i=Z(u=>{const h=t();try{return new URL(h,r)}catch{return console.error(`Invalid path ${h}`),u}},r,{equals:(u,h)=>u.href===h.href}),s=Z(()=>i().pathname),o=Z(()=>i().search,!0),a=Z(()=>i().hash),l=()=>"",c=We(o,()=>Vs(i()));return{get pathname(){return s()},get search(){return o()},get hash(){return a()},get state(){return e()},get key(){return l()},query:n?n(c):Gs(c)}}let me;function Wh(){return me}function Hh(t,e,n,r={}){const{signal:[i,s],utils:o={}}=t,a=o.parsePath||(k=>k),l=o.renderPath||(k=>k),c=o.beforeLeave||_s(),u=ht("",r.base||"");if(u===void 0)throw new Error(`${u} is not a valid base path`);u&&!i().value&&s({value:u,replace:!0,scroll:!1});const[h,m]=Y(!1);let y;const x=(k,C)=>{C.value===f()&&C.state===v()||(y===void 0&&m(!0),me=k,y=C,co(()=>{y===C&&(w(y.value),A(y.state),lo(),Ue||H[1](_=>_.filter(we=>we.pending)))}).finally(()=>{y===C&&uo(()=>{me=void 0,k==="navigate"&&ro(y),m(!1),y=void 0})}))},[f,w]=Y(i().value),[v,A]=Y(i().state),P=Gh(f,v,o.queryWrapper),G=[],H=Y(Ue?so():[]),Be=Z(()=>typeof r.transformUrl=="function"?Je(e(),r.transformUrl(P.pathname)):Je(e(),P.pathname)),Kn=()=>{const k=Be(),C={};for(let _=0;_<k.length;_++)Object.assign(C,k[_].params);return C},eo=o.paramsWrapper?o.paramsWrapper(Kn,e):Gs(Kn),Dn={pattern:u,path:()=>u,outlet:()=>null,resolvePath(k){return ht(u,k)}};return ao(We(i,k=>x("native",k),{defer:!0})),{base:Dn,location:P,params:eo,isRouting:h,renderPath:l,parsePath:a,navigatorFactory:no,matches:Be,beforeLeave:c,preloadRoute:io,singleFlight:r.singleFlight===void 0?!0:r.singleFlight,submissions:H};function to(k,C,_){_r(()=>{if(typeof C=="number"){C&&(o.go?o.go(C):console.warn("Router integration does not support relative routing"));return}const we=!C||C[0]==="?",{replace:st,resolve:ve,scroll:ot,state:xe}={replace:!1,resolve:!we,scroll:!0,..._},ke=ve?k.resolvePath(C):ht(we&&P.pathname||"",C);if(ke===void 0)throw new Error(`Path '${C}' is not a routable path`);if(G.length>=zh)throw new Error("Too many redirects");const Ln=f();if(ke!==Ln||xe!==v())if(Ue){const Bn=Jt();Bn&&(Bn.response={status:302,headers:new Headers({Location:ke})}),s({value:ke,replace:st,scroll:ot,state:xe})}else c.confirm(ke,_)&&(G.push({value:Ln,replace:st,scroll:ot,state:v()}),x("navigate",{value:ke,state:xe}))})}function no(k){return k=k||zr(Zs)||Dn,(C,_)=>to(k,C,_)}function ro(k){const C=G[0];C&&(s({...k,replace:C.replace,scroll:C.scroll}),G.length=0)}function io(k,C){const _=Je(e(),k.pathname),we=me;me="preload";for(let st in _){const{route:ve,params:ot}=_[st];ve.component&&ve.component.preload&&ve.component.preload();const{preload:xe}=ve;C&&xe&&Ur(n(),()=>xe({params:ot,location:{pathname:k.pathname,search:k.search,hash:k.hash,query:Vs(k),state:null,key:""},intent:"preload"}))}me=we}function so(){const k=Jt();return k&&k.router&&k.router.submission?[k.router.submission]:[]}}function Zh(t,e,n,r){const{base:i,location:s,params:o}=t,{pattern:a,component:l,preload:c}=r().route,u=Z(()=>r().path);l&&l.preload&&l.preload();const h=c?c({params:o,location:s,intent:me||"initial"}):void 0;return{parent:e,pattern:a,path:u,outlet:()=>l?ho(l,{params:o,location:s,data:h,get children(){return n()}}):n(),resolvePath(y){return ht(i.path(),y,u())}}}const Yh=t=>e=>{const{base:n}=e,r=Jr(()=>e.children),i=Z(()=>Xs(r(),e.base||""));let s;const o=Hh(t,i,()=>s,{base:n,singleFlight:e.singleFlight,transformUrl:e.transformUrl});return t.create&&t.create(o),E(Hs.Provider,{value:o,get children(){return E(Qh,{routerState:o,get root(){return e.root},get preload(){return e.rootPreload||e.rootLoad},get children(){return[Vt(()=>(s=Fr())&&null),E(Xh,{routerState:o,get branches(){return i()}})]}})}})};function Qh(t){const e=t.routerState.location,n=t.routerState.params,r=Z(()=>t.preload&&_r(()=>{t.preload({params:n,location:e,intent:Wh()||"initial"})}));return E(Se,{get when(){return t.root},keyed:!0,get fallback(){return t.children},children:i=>E(i,{params:n,location:e,get data(){return r()},get children(){return t.children}})})}function Xh(t){if(Ue){const i=Jt();if(i&&i.router&&i.router.dataOnly){ep(i,t.routerState,t.branches);return}i&&((i.router||(i.router={})).matches||(i.router.matches=t.routerState.matches().map(({route:s,path:o,params:a})=>({path:s.originalPath,pattern:s.pattern,match:o,params:a,info:s.info}))))}const e=[];let n;const r=Z(We(t.routerState.matches,(i,s,o)=>{let a=s&&i.length===s.length;const l=[];for(let c=0,u=i.length;c<u;c++){const h=s&&s[c],m=i[c];o&&h&&m.route.key===h.route.key?l[c]=o[c]:(a=!1,e[c]&&e[c](),fo(y=>{e[c]=y,l[c]=Zh(t.routerState,l[c-1]||t.routerState.base,Kr(()=>r()[c+1]),()=>t.routerState.matches()[c])}))}return e.splice(i.length).forEach(c=>c()),o&&a?o:(n=l[0],l)}));return Kr(()=>r()&&n)()}const Kr=t=>()=>E(Se,{get when(){return t()},keyed:!0,children:e=>E(Zs.Provider,{value:e,get children(){return e.outlet()}})}),_t=t=>{const e=Jr(()=>t.children);return po(t,{get children(){return e()}})};function ep(t,e,n){const r=new URL(t.request.url),i=Je(n,new URL(t.router.previousUrl||t.request.url).pathname),s=Je(n,r.pathname);for(let o=0;o<s.length;o++){(!i[o]||s[o].route!==i[o].route)&&(t.router.dataOnly=!0);const{route:a,params:l}=s[o];a.preload&&a.preload({params:l,location:e.location,intent:"preload"})}}function tp([t,e],n,r){return[t,r?i=>e(r(i)):e]}function np(t){let e=!1;const n=i=>typeof i=="string"?{value:i}:i,r=tp(Y(n(t.get()),{equals:(i,s)=>i.value===s.value&&i.state===s.state}),void 0,i=>(!e&&t.set(i),Kt.registry&&!Kt.done&&(Kt.done=!0),i));return t.init&&Vr(t.init((i=t.get())=>{e=!0,r[1](n(i)),e=!1})),Yh({signal:r,create:t.create,utils:t.utils})}function rp(t,e,n){return t.addEventListener(e,n),()=>t.removeEventListener(e,n)}function ip(t,e){const n=t&&document.getElementById(t);n?n.scrollIntoView():e&&window.scrollTo(0,0)}const sp=new Map;function op(t=!0,e=!1,n="/_server",r){return i=>{const s=i.base.path(),o=i.navigatorFactory(i.base);let a,l;function c(f){return f.namespaceURI==="http://www.w3.org/2000/svg"}function u(f){if(f.defaultPrevented||f.button!==0||f.metaKey||f.altKey||f.ctrlKey||f.shiftKey)return;const w=f.composedPath().find(Be=>Be instanceof Node&&Be.nodeName.toUpperCase()==="A");if(!w||e&&!w.hasAttribute("link"))return;const v=c(w),A=v?w.href.baseVal:w.href;if((v?w.target.baseVal:w.target)||!A&&!w.hasAttribute("state"))return;const G=(w.getAttribute("rel")||"").split(/\s+/);if(w.hasAttribute("download")||G&&G.includes("external"))return;const H=v?new URL(A,document.baseURI):new URL(A);if(!(H.origin!==window.location.origin||s&&H.pathname&&!H.pathname.toLowerCase().startsWith(s.toLowerCase())))return[w,H]}function h(f){const w=u(f);if(!w)return;const[v,A]=w,P=i.parsePath(A.pathname+A.search+A.hash),G=v.getAttribute("state");f.preventDefault(),o(P,{resolve:!1,replace:v.hasAttribute("replace"),scroll:!v.hasAttribute("noscroll"),state:G?JSON.parse(G):void 0})}function m(f){const w=u(f);if(!w)return;const[v,A]=w;i.preloadRoute(A,v.getAttribute("preload")!=="false")}function y(f){clearTimeout(a);const w=u(f);if(!w)return l=null;const[v,A]=w;l!==v&&(a=setTimeout(()=>{i.preloadRoute(A,v.getAttribute("preload")!=="false"),l=v},20))}function x(f){if(f.defaultPrevented)return;let w=f.submitter&&f.submitter.hasAttribute("formaction")?f.submitter.getAttribute("formaction"):f.target.getAttribute("action");if(!w)return;if(!w.startsWith("https://action/")){const A=new URL(w,Js);if(w=i.parsePath(A.pathname+A.search),!w.startsWith(n))return}if(f.target.method.toUpperCase()!=="POST")throw new Error("Only POST forms are supported for Actions");const v=sp.get(w);if(v){f.preventDefault();const A=new FormData(f.target,f.submitter);v.call({r:i,f:f.target},f.target.enctype==="multipart/form-data"?A:new URLSearchParams(A))}}fn(["click","submit"]),document.addEventListener("click",h),t&&(document.addEventListener("mousemove",y,{passive:!0}),document.addEventListener("focusin",m,{passive:!0}),document.addEventListener("touchstart",m,{passive:!0})),document.addEventListener("submit",x),Vr(()=>{document.removeEventListener("click",h),t&&(document.removeEventListener("mousemove",y),document.removeEventListener("focusin",m),document.removeEventListener("touchstart",m)),document.removeEventListener("submit",x)})}}function ap(t){const e=t.replace(/^.*?#/,"");if(!e.startsWith("/")){const[,n="/"]=window.location.hash.split("#",2);return`${n}#${e}`}return e}function cp(t){const e=()=>window.location.hash.slice(1),n=_s();return np({get:e,set({value:r,replace:i,scroll:s,state:o}){i?window.history.replaceState(Eh(o),"","#"+r):window.history.pushState(o,"","#"+r);const a=r.indexOf("#"),l=a>=0?r.slice(a+1):"";ip(l,s),qn()},init:r=>rp(window,"hashchange",Kh(r,i=>!n.confirm(i&&i<0?i:e()))),create:op(t.preload,t.explicitLinks,t.actionBase),utils:{go:r=>window.history.go(r),renderPath:r=>`#${r}`,parsePath:ap,beforeLeave:n}})(t)}function lp(t){const e=Ys(),n=Th(),{href:r,state:i}=t,s=typeof r=="function"?r({navigate:e,location:n}):r;return e(s,{replace:!0,state:i}),null}async function Dr({language:t,text:e,limit:n,offset:r,templateName:i}){const s=`${Fs}/search?language=${encodeURIComponent(t)}&q=${encodeURIComponent(e)}&limit=${encodeURIComponent(n)}&offset=${encodeURIComponent(r)}&tpl=${encodeURIComponent(i)}`,o=await fetch(s,{method:"GET"});if(o.status!==200){const l=await o.text();throw new Error(`API error (${o.status}): ${l}`)}return await o.json()}var up=V('<form class=PaSearchApp-form><input class="PaSearchApp-input PaInput"type=search><button class="PaSearchApp-searchButton PaButton"type=submit>');function dp(t){const e=Ys(),[n,r]=Y(t.value??""),{t:i}=Et(t.language);Gr(We(()=>t.value,()=>r(t.value??"")));const s=async o=>{o.preventDefault(),e(`/q/${encodeURIComponent(n())}`)};return(()=>{var o=up(),a=o.firstChild,l=a.nextSibling;return o.addEventListener("submit",s),a.addEventListener("change",c=>r(c.currentTarget.value)),J(l,()=>i("searchApp.search")),pt(()=>kt(a,"placeholder",i("searchApp.search"))),pt(()=>a.value=n()),o})()}var hp=V("<div class=PaSearchApp-loadMore>"),pp=V("<div class=PaSearchApp-results>"),fp=V("<div class=PaSearchApp>"),mp=V("<div class=PaSearchApp-nothing> <span class=PaSearchApp-quote>"),gp=V('<img class="PaSearchApp-loading PaLoading"width=80 height=80 alt=…>'),yp=V('<button class="PaSearchApp-loadButton PaButton"type=button>');function Lr({language:t,limit:e,templateName:n}){const{t:r}=Et(t),i=_h(),[s,o]=Y([]),[a,l]=Y(-1),[c,u]=Y(0),[h,m]=Y(!1);Gr(We(()=>i.searchString,y));async function y(){if(i.searchString){m(!0);try{o([]),u(0),l(-1);const f=await Dr({language:t,text:decodeURIComponent(i.searchString),limit:e,offset:c(),templateName:n});if(l(f.total),u(c()+e),!f.html)return;o(hn(f.html))}finally{m(!1)}}}async function x(){if(!i.searchString)return;const f=a();if(!(f===-1||c()>=f)){m(!0);try{const w=await Dr({language:t,text:decodeURIComponent(i.searchString),limit:e,offset:c(),templateName:n});if(!w.html)return;o([...s(),...hn(w.html)]),u(c()+e)}finally{m(!1)}}}return(()=>{var f=fp();return J(f,E(dp,{language:t,get value(){return Vt(()=>!!i.searchString)()?decodeURIComponent(i.searchString):void 0}}),null),J(f,E(Se,{get when(){return i.searchString},get children(){var w=pp();return J(w,E(Se,{get when(){return a()!==-1},get children(){return E(Se,{get when(){return s().length>0},get fallback(){return(()=>{var v=mp(),A=v.firstChild,P=A.nextSibling;return J(v,()=>r("searchApp.nothingMessage"),A),J(P,()=>i.searchString),v})()},get children(){return s()}})}}),null),J(w,E(Se,{get when(){return a()===-1||h()||c()<a()},get children(){var v=hp();return J(v,(()=>{var A=Vt(()=>!!h());return()=>A()?(()=>{var P=gp();return kt(P,"src",`${Us}/spinner.svg`),P})():(()=>{var P=yp();return P.$$click=x,J(P,()=>r("infiniteLoading.loadMore")),P})()})()),v}}),null),w}}),null),f})()}fn(["click"]);const bp=js({"limit?":"string|undefined","template?":"string|undefined","+":"ignore"}).pipe(t=>({limit:X(t.limit)?Number(t.limit):void 0,templateName:X(t.template)?t.template:void 0}));function $p(t,{language:e}){if(!e)throw new Error("Missing language");const{limit:n,templateName:r}=bp.assert(t.dataset);n===void 0||r===void 0||jr(()=>E(cp,{explicitLinks:!0,get children(){return[E(_t,{path:"/",component:()=>E(lp,{href:"/q"})}),E(_t,{path:"/q",component:()=>E(Lr,{language:e,templateName:r,limit:n})}),E(_t,{path:"/q/:searchString",component:()=>E(Lr,{language:e,templateName:r,limit:n})})]}}),t)}var wp=V('<input class="PaSearchOpener-input PaInput"type=search required>'),vp=V('<form class=PaSearchOpener><button class="PaSearchOpener-button PaButton"type=submit>');function xp({searchURL:t,language:e}){const[n,r]=Y(""),{t:i}=Et(e),s=(()=>{var a=wp();return a.addEventListener("change",l=>r(l.currentTarget.value)),pt(()=>kt(a,"placeholder",i("searchApp.search"))),pt(()=>a.value=n()),a})(),o=a=>{a.preventDefault(),window.location.href=`${t}#/q/${encodeURIComponent(n())}`};return(()=>{var a=vp(),l=a.firstChild;return a.addEventListener("submit",o),J(a,s,l),J(l,()=>i("searchApp.search")),a})()}var kp=V('<button class="PaSearchOpenerButton PaIconButton"type=button><svg class=PaSearchOpenerButton-svg width=20 height=20 xmlns=http://www.w3.org/2000/svg viewBox="0 0 490.4 490.4"><title>Mignifier</title><g id=SVGRepo_bgCarrier stroke-width=0></g><g id=SVGRepo_tracerCarrier stroke-linecap=round stroke-linejoin=round></g><g id=SVGRepo_iconCarrier><g><path d="M484.1,454.796l-110.5-110.6c29.8-36.3,47.6-82.8,47.6-133.4c0-116.3-94.3-210.6-210.6-210.6S0,94.496,0,210.796 s94.3,210.6,210.6,210.6c50.8,0,97.4-18,133.8-48l110.5,110.5c12.9,11.8,25,4.2,29.2,0C492.5,475.596,492.5,463.096,484.1,454.796z M41.1,210.796c0-93.6,75.9-169.5,169.5-169.5s169.6,75.9,169.6,169.5s-75.9,169.5-169.5,169.5S41.1,304.396,41.1,210.796z"></path> ');function Ap({searchIconColor:t,language:e,searchURL:n}){const r=(()=>{var o=kp(),a=o.firstChild;return oo(a,"fill",t),o})(),i=E(xp,{searchURL:n,language:e});return mo({openButton:r,dialogContent:i,modalClass:"_paSearchOpener",loadCss:!0}).on("open",()=>{i.querySelector("input")?.focus()}),r}function Ip(t,{language:e}){const n=t.dataset.searchUrl,r=t.dataset.iconColor;if(!e)throw new Error("Missing language");if(!n)throw new Error("Missing search url");jr(()=>E(Ap,{language:e,searchURL:n,searchIconColor:r}),t)}document.readyState==="loading"?document.addEventListener("DOMContentLoaded",Br):Br();function Br(){const t=document.documentElement.lang,e={paSearchOpener:Ip,paSearchApp:$p,paInfiniteLoading:Mh},n=document.querySelectorAll("[data-effect]");for(const r of n){const i=r.dataset.effect;if(!i)continue;const s=e[i];s&&s(r,{language:t})}}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@paroicms/content-loading-plugin",
|
|
3
|
-
"version": "0.27.
|
|
3
|
+
"version": "0.27.4",
|
|
4
4
|
"description": "Content loading plugin for ParoiCMS",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"paroicms",
|
|
@@ -24,7 +24,7 @@
|
|
|
24
24
|
"clear": "rimraf backend/dist/* frontend/dist/*"
|
|
25
25
|
},
|
|
26
26
|
"dependencies": {
|
|
27
|
-
"@paroicms/script-lib": "0.3.
|
|
27
|
+
"@paroicms/script-lib": "0.3.4",
|
|
28
28
|
"arktype": "~2.1.23"
|
|
29
29
|
},
|
|
30
30
|
"peerDependencies": {
|
|
@@ -32,8 +32,8 @@
|
|
|
32
32
|
"@paroicms/public-server-lib": "0"
|
|
33
33
|
},
|
|
34
34
|
"devDependencies": {
|
|
35
|
-
"@paroicms/public-anywhere-lib": "0.37.
|
|
36
|
-
"@paroicms/public-server-lib": "0.47.
|
|
35
|
+
"@paroicms/public-anywhere-lib": "0.37.2",
|
|
36
|
+
"@paroicms/public-server-lib": "0.47.3",
|
|
37
37
|
"@types/node": "~24.8.1",
|
|
38
38
|
"rimraf": "~6.0.1",
|
|
39
39
|
"typescript": "~5.9.3"
|