@paroicms/content-loading-plugin 0.27.7 → 0.27.8

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
- import{delegateEvents as fn,template as V,insert as J,setAttribute as kt,isServer as ze,getRequestEvent as Jt,createComponent as E,memo as Vt,effect as pt,render as Fr,setStyleProperty as ao}from"https://esm.sh/solid-js@1.9.10/web";import{createMemo as Z,getOwner as Ur,runWithOwner as zr,useContext as Tr,createContext as _r,createSignal as Y,createRenderEffect as co,on as He,startTransition as lo,resetErrorBoundaries as uo,batch as ho,untrack as Jr,createComponent as po,children as Vr,mergeProps as fo,Show as Se,createRoot as mo,onCleanup as Gr,sharedConfig as Dt,createEffect as Wr}from"https://esm.sh/solid-js@1.9.10";import go from"https://esm.sh/@paroicms/tiny-modal@0.7.5";function yo(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 Ze=t=>Array.isArray(t)?t:[t],bo=(t,e)=>{const n=[[],[]];for(const r of t)e(r)?n[0].push(r):n[1].push(r);return n},Hr=Array,le=(t,e)=>t.includes(e),$o=(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?Ze(e):t.concat(e),wo=(...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 Ze(e))t.some(s=>r(s,i))||t.push(i);return t},vo=(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"},xo={...re,function:"a function"};class ko extends Error{}const K=t=>Me(t,ko),Me=(t,e=Error)=>{throw new e(t)};class Ao extends Error{name="ParseError"}const d=t=>Me(t,Ao),Zr=t=>` ${t}`,Io="​",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 c=Array.isArray(a[0])||a.length===0?a:[a];for(const[l,u]of c)typeof l=="object"?n[l.group]=N(n[l.group],u):n[l]=u}return i?Object.values(n):n},Yr=Object.entries,te=(t,e)=>t in e,mn=(t,e)=>e in t;class So{constructor(e){Object.assign(this,e)}}const No=class{};class Qr extends No{}const Oo=(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]},Xr=(t,e)=>Oo(t,e)[1],Ye=t=>Object.keys(t).length===0,ft=t=>[...Object.entries(t),...Object.getOwnPropertySymbols(t).map(e=>[e,t[e]])],Ro=(t,e)=>Object.defineProperties(t,Object.getOwnPropertyDescriptors(e)),Co=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=Zr(`unset${Io}`),Mo=t=>Object.values(t).filter(e=>typeof e=="number"?!0:typeof t[e]!="number"),ei={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},ti=globalThis.File??Blob,ni={ArrayBuffer:ArrayBuffer,Blob:Blob,File:ti,FormData:FormData,Headers:Headers,Request:Request,Response:Response,URL:URL},Po={Int8Array:Int8Array,Uint8Array:Uint8Array,Uint8ClampedArray:Uint8ClampedArray,Int16Array:Int16Array,Uint16Array:Uint16Array,Int32Array:Int32Array,Uint32Array:Uint32Array,Float32Array:Float32Array,Float64Array:Float64Array,BigInt64Array:BigInt64Array,BigUint64Array:BigUint64Array},Pe={...ei,...ni,...Po,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,qo={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"},Eo={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"},Do={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={...qo,...Eo,...Do},yn=t=>{const e=Object(t).name??null;return e&&te(e,Pe)&&Pe[e]===t?e:null},jn=(t,e)=>{let n=t.prototype;for(;n!==null;){if(n===e.prototype)return!0;n=Object.getPrototypeOf(n)}return!1},Lo=t=>ri(t,new Map),ri=(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=ri(o.value,e))}}return Object.defineProperties(r,i),r},Bo=t=>{let e=ee;return()=>e===ee?e=t():e},At=t=>typeof t=="function"&&t.length===0,jo=class extends Function{constructor(...t){const e=t.slice(0,-1),n=t[t.length-1];try{super(...e,n)}catch(r){return K(`Encountered an unexpected error while compiling your definition:\n Message: ${r} \n Source: (${t.slice(0,-1)}) => {\n ${t[t.length-1]}\n }`)}}};class pe{constructor(e,...[n]){return Object.assign(Object.setPrototypeOf(e.bind(n?.bind??this),this.constructor.prototype),n?.attach)}}const Fo=Bo(()=>{try{return new Function("return false")()}catch{return!0}});class ne{constructor(){}}const Uo=()=>{try{return(((new Error).stack?.split(`\n`)[2]?.trim()||"").match(/\(?(.+?)(?::\d+:\d+)?\)?$/)?.[1]||"unknown").replace(/^file:\/\//,"")}catch{return"unknown"}},zo=globalThis.process?.env??{},To={fileName:Uo,env:zo},_o=t=>t[0].toUpperCase()+t.slice(1),ii=t=>new RegExp(Jo(t),typeof t=="string"?"":t.flags),Jo=t=>`^(?:${typeof t=="string"?t:t.source})$`,ue={negativeLookahead:t=>`(?!${t})`,nonCapturingGroup:t=>`(?:${t})`},Te="\\",It={" ":1,"\n":1,"\t":1},Vo=/^-0\.?0*$/.source,si=/[1-9]\d*/.source,Go=/\.\d+/.source,Wo=/\.\d*[1-9]/.source,oi=t=>ii(ue.negativeLookahead(Vo)+ue.nonCapturingGroup("-?"+ue.nonCapturingGroup(ue.nonCapturingGroup("0|"+si)+ue.nonCapturingGroup(t.decimalPattern)+"?")+(t.allowDecimalOnly?"|"+t.decimalPattern:"")+"?")),Fn=oi({decimalPattern:Wo,allowDecimalOnly:!1}),Ho=Fn.test.bind(Fn),Wt=oi({decimalPattern:Go,allowDecimalOnly:!0});Wt.test.bind(Wt);const Zo=/^-?\d*\.?\d*$/,Yo=t=>t.length!==0&&Zo.test(t),mt=ii(ue.negativeLookahead("^-0$")+"-?"+ue.nonCapturingGroup(ue.nonCapturingGroup("0|"+si))),Qo=mt.test.bind(mt),Ht=/^-?\d+$/,Xo=Ht.test.bind(Ht),ai={number:"a number",bigint:"a bigint",integer:"an integer"},ci=(t,e)=>`'${t}' was parsed as ${ai[e]} but could not be narrowed to a literal value. Avoid unnecessary leading or trailing zeros and other abnormal notation`,ea=(t,e)=>e==="number"?Ho(t):Qo(t),ta=(t,e)=>e==="number"?Number(t):Number.parseInt(t),na=(t,e)=>e==="number"?Yo(t):Xo(t),ra=(t,e)=>bn(t,"number",e),ia=(t,e)=>bn(t,"number",{...e,strict:!0}),sa=(t,e)=>bn(t,"integer",e),bn=(t,e,n)=>{const r=ta(t,e);return!Number.isNaN(r)&&na(t,e)?n?.strict?ea(t,e)?r:d(ci(t,e)):r:n?.errorOnFail?d(n?.errorOnFail===!0?`Failed to parse ${ai[e]} from '${t}'`:n?.errorOnFail):void 0},oa=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(ci(t,"bigint"))},aa="0.55.0",ca={version:aa,filename:To.fileName(),FileConstructor:ti},Qe=ca,Un=new Map,Kt=Object.create(null),Zt=t=>{const e=Un.get(t);if(e)return e;let n=la(t);return Kt[n]?n=`${n}${Kt[n]++}`:Kt[n]=1,Qe[n]=t,Un.set(t,n),n},Ge=t=>/^[$A-Z_a-z][\w$]*$/.test(t),la=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 Ge(t.name)?t.name:"fn";case"symbol":return t.description&&Ge(t.description)?t.description:"symbol"}return K(`Unexpected attempt to register serializable value of type ${Q(t)}`)},$n=t=>typeof t=="string"?JSON.stringify(t):typeof t=="bigint"?`${t}n`:`${t}`,ua=(t,e={})=>_e(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(_e(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 c=typeof o=="symbol"?qe.onSymbol(o):Ge(o)?o:JSON.stringify(o),l=gt(a,e,r);return`${r}${c}: ${l}`});return s.length===0?"{}":e?`{\n${s.join(`,\n`)}\n${n}}`:`{${s.join(", ")}}`}return t instanceof Date?Xe(t):"expression"in t&&typeof t.expression=="string"?t.expression:i},qe={onCycle:()=>"(cycle)",onSymbol:t=>`Symbol(${Zt(t)})`,onFunction:t=>`Function(${Zt(t)})`},_e=(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=>_e(o,e,i));if(r instanceof Date)return r.toDateString();const s={};for(const o in r)s[o]=_e(r[o],e,i);for(const o of Object.getOwnPropertySymbols(r))s[e.onSymbol?.(o)??o.toString()]=_e(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.replace(/\\/g,"\\\\");default:return t}},Xe=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 c=`${da[n]} ${r}, ${e}`;if(i===0&&s===0&&o===0&&a===0)return c;let l=t.toLocaleTimeString();const u=l.endsWith(" AM")||l.endsWith(" PM")?l.slice(-3):"";return u&&(l=l.slice(0,-u.length)),a?l+=`.${pa(a,3)}`:ha.test(l)&&(l=l.slice(0,-3)),`${l+u}, ${c}`},da=["January","February","March","April","May","June","July","August","September","October","November","December"],ha=/:\d\d:00$/,pa=(t,e)=>String(t).padStart(e,"0"),li=(t,e,...[n])=>{const r=n?.stringifySymbol??S;let i=t;switch(typeof e){case"string":i=Ge(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},et=(t,...e)=>t.reduce((n,r)=>li(n,r,...e),"");class ui extends Hr{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=et(this)}stringifyAncestors(){if(this.cache.stringifyAncestors)return this.cache.stringifyAncestors;let e="";const n=[e];for(const r of this)e=li(e,r),n.push(e);return this.cache.stringifyAncestors=n}}class di{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===Te)this.shift(),e(this,n)?n+=this.shift():this.lookahead===Te?n+=this.shift():n+=`${Te}${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 fa=(t,e)=>`Unmatched ${t}${e===""?"":` before ${e}`}`,hi=t=>`Missing ${t}`;let Yt="$ark",ma=2;for(;Yt in globalThis;)Yt=`$ark${ma++}`;const pi=Yt;globalThis[pi]=Qe;const p=Qe,ga=t=>`${pi}.${t}`,z=t=>ga(Zt(t));class fi extends Qr{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 mi(e,n)}index(e,n=!1){return gi(`${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 jo(...this.argNames,this.body)}}const De=t=>$e(t,"object")||typeof t=="symbol"?z(t):$n(t),mi=(t,e=!1)=>typeof t=="string"&&Ge(t)?`${e?"?":""}.${t}`:gi(ya(t),e),ya=t=>typeof t=="symbol"?z(t):JSON.stringify(t),gi=(t,e=!1)=>`${e?"?.":""}[${t}]`;class Lt extends fi{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 yi=t=>O(t,(e,n)=>[e,F(n)?[...n]:n]),ie=Zr("arkKind"),b=(t,e)=>t?.[ie]===e,U=t=>b(t,"root")||b(t,"constraint"),ba=["unit","proto","domain"],St=["required","optional","index","sequence"],bi=["pattern","divisor","exactLength","max","min","maxLength","minLength","before","after"],$i=[...bi,"structure","predicate"],wn=[...$i,...St],Nt=["alias","union","morph","unit","intersection","proto","domain"],$a=[...Nt,...wn],wi=O(wn,(t,e)=>[e,1]),wa=O([...St,"undeclared"],(t,e)=>[e,1]),vi=O($a,(t,e)=>[e,t]),ut=t=>typeof t=="string"&&t in vi,yt=t=>vi[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:De(t),Ot=t=>{let e="{ ";for(const[n,r]of Object.entries(t))e+=`${n}: ${De(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 va 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 xa={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:va,throw:(...t)=>{throw new L.Error(...t)},throwInternalOperandError:(t,e)=>K(`Unexpected JSON Schema input for ${t}: ${S(e)}`),defaultConfig:xa};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]=xi(t.toJsonSchema,e.toJsonSchema):ut(r)?n[r]={...t[r],...e[r]}:n[r]=e[r]}return n},xi=(t,e)=>{if(!t)return e??{};if(!e)return t;const n={...t};let r;for(r in e)r==="fallback"?n.fallback=ka(t.fallback,e.fallback):n[r]=e[r];return n},ka=(t,e)=>{t=zn(t),e=zn(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},zn=t=>typeof t=="function"?{default:t}:t??{};class Ee extends Qr{[ie]="error";path;data;nodeConfig;input;ctx;constructor({prefixPath:e,relativePath:n,...r},i){super(),this.input=r,this.ctx=i,Ro(this,r);const s=i.data;r.code==="union"&&(r.errors=r.errors.flatMap(a=>{const c=a.hasCode("union")?a.errors:[a];return!e&&!n?c:c.map(l=>l.transform(u=>({...u,path:wo(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 ui(...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 et(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 Hr{[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 Aa(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 Aa extends Error{name="TraversalError";constructor(e){e.length===1?super(e.summary):super(`\n`+e.map(n=>` • ${Ia(n)}`).join(`\n`)),Object.defineProperty(this,"arkErrors",{value:e,enumerable:!1})}}const Ia=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 et(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[this.branches.length-1]}queueMorphs(e){const n={path:new ui(...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[e.length-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 ki 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)=>Ra(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(c=>Ai(c,a))){this.flatRefs.push(a);for(const c of a.node.branches)(c.hasKind("morph")||c.hasKind("intersection")&&c.structure?.structuralMorph!==void 0)&&this.flatMorphs.push({path:a.path,propString:a.propString,node:c})}}}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,K(`Unexpected rootApplyStrategy ${this.rootApplyStrategy}`)}}compiledMeta=Oa(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(ba,this.kind)}isConstraint(){return le(wn,this.kind)}isStructural(){return le(St,this.kind)}isRefinement(){return le($i,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=Fe.normalize(e);return this._select(n)}_select(e){let n=Fe.applyBoundary[e.boundary??"references"](this);return e.kind&&(n=n.filter(r=>r.kind===e.kind)),e.where&&(n=n.filter(e.where)),Fe.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 v=m._transform(e,n);return v?[u,v]:[]}if(m.length===0)return[u,h];const y=m.flatMap(v=>v._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 c=Object.keys(a);return(c.length===0||c.length===1&&c[0]==="meta")&&!Ye(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=Fe.normalize(n),i=typeof e=="string"?(c,l)=>({...l,meta:{...l.meta,description:e}}):typeof e=="function"?(c,l)=>({...l,meta:e(l.meta)}):(c,l)=>({...l,meta:{...l.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&&Ze(s),a=r.boundary==="child"?(c,l)=>l.root.children.includes(c):r.boundary==="shallow"?c=>c.kind!=="structure":()=>!0;return this.$.finalize(this.transform(i,{shouldTransform:a,selected:o}))}}const Fe={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(Tn(e,n)),t),find:t=>t[0],assertFind:(t,e,n)=>(t.length===0&&Me(Tn(e,n)),t[0])},normalize:t=>typeof t=="function"?{boundary:"references",method:"filter",where:t}:typeof t=="string"?te(t,Fe.applyBoundary)?{method:"filter",boundary:t}:{boundary:"references",method:"filter",kind:t}:{boundary:"references",method:"filter",...t}},Tn=(t,e)=>`${t} had no references matching ${S(e)}.`,Sa=t=>et(t,{stringifyNonKey:e=>e.expression}),Na=/"(\$ark\.[^"]+)"/g,Oa=t=>JSON.stringify(t).replace(Na,"$1"),de=(t,e)=>({path:t,node:e,propString:Sa(t)}),Ai=(t,e)=>t.propString===e.propString&&t.node.equals(e.node),_n=(t,e)=>ye(t,e,{isEqual:Ai}),Ra=(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=et(e);return Ii(`Intersection${i&&` at ${i}`} of ${Jn(n,r)}`)}return`The following intersections result in unsatisfiable types:\n• ${this.map(({path:e,l:n,r:r})=>`${e}: ${Jn(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 Jn=(t,e)=>`${Xt(t)} and ${Xt(e)}`,Xt=t=>U(t)?t.expression:F(t)?t.map(Xt).join(" | ")||"never":String(t),Ii=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 c=Ae[a],l=c instanceof g?c.invert():c;return Ae[i]=l,l}}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)?Ca(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}},Ca=(t,e,n)=>t.includesTransform||e.includesTransform?n.invert?Vn(e,t,n):Vn(t,e,n):tn(t,e,n),Vn=(t,e,n)=>t.distribute(r=>Ma(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)}),Ma=(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 ki{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,Pa(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 K(`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 wi?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),Pa=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 K(`Unexpected intersection of closed refinements of kind ${n.kind}`);e[n.kind]=n}return e},qa=(...t)=>d(Ea(...t)),Ea=(t,e,n)=>{const r=n.hasKind("morph")?"a morph":n.isUnknown()?"unknown":n.exclude(e).defaultShortDescription;return`${_o(t)} operand must be ${e.description} (was ${r})`},Da=(t,e,n)=>new wt(t,e,n,n,null);class Si 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,(c,l)=>{const u=this.arg$.parse(o[c]);return u.extends(this.constraints[c])||d(Ka(l,this.constraints[c].expression,u.expression)),[l,u]});if(this.defIsLazy()){const c=this.bodyDef(a);return this.$.parse(c)}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 Si}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:ua(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})`,La=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 Ba 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 Ni={implementation:La,Node:Ba},ja=q({kind:"divisor",collapsibleKey:"rule",keys:{rule:{parse:t=>Number.isInteger(t)?t:d(Ua(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/za(t.rule,e.rule))})},obviatesBasisDescription:!0});class Fa 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 Oi={implementation:ja,Node:Fa},Ua=t=>`divisor must be an integer (was ${t})`,za=(t,e)=>{let n,r=t,i=e;for(;i!==0;)n=i,i=r%i,r=n;return r};class Le extends Rt{boundOperandKind=Va[this.kind];compiledActual=this.boundOperandKind==="value"?"data":this.boundOperandKind==="length"?"data.length":"data.valueOf()";comparator=Ga(this.kind,this.exclusive);numericLimit=this.rule.valueOf();expression=`${this.comparator} ${this.rule}`;compiledCondition=`${this.compiledActual} ${this.comparator} ${this.numericLimit}`;compiledNegation=`${this.compiledActual} ${Ta[this.comparator]} ${this.numericLimit}`;stringLimit=this.boundOperandKind==="date"?Wa(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 Ta={"<":">=","<=":">",">":"<=",">=":"<"},_a={min:"max",minLength:"maxLength",after:"before"},Ri={parse:t=>t||void 0},Ci=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},Mi=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},Pi=t=>typeof t=="string"||typeof t=="number"?new Date(t):t,Ja=(t,e)=>`${t} bound must be a positive integer (was ${e})`,xn=t=>e=>((!Number.isInteger(e)||e<0)&&d(Ja(t,e)),e),Va={min:"value",max:"value",minLength:"length",maxLength:"length",after:"date",before:"date"},Ga=(t,e)=>`${te(t,_a)?">":"<"}${e?"":"="}`,Wa=t=>typeof t=="string"?t:new Date(t).toLocaleString(),Ha=t=>`Bounded expression ${t} must be exactly one of number, string, Array, or Date`,Za=q({kind:"after",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{parse:Pi,serialize:t=>t.toISOString()}},normalize:Mi("after"),defaults:{description:t=>`${t.collapsibleLimitString} or later`,actual:Xe},intersections:{after:(t,e)=>t.isStricterThan(e)?t:e}});class Ya extends Le{impliedBasis=p.intrinsic.Date.internal;collapsibleLimitString=Xe(this.rule);traverseAllows=e=>e>=this.rule;reduceJsonSchema(e,n){return n.fallback.date({code:"date",base:e,after:this.rule})}}const qi={implementation:Za,Node:Ya},Qa=q({kind:"before",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{parse:Pi,serialize:t=>t.toISOString()}},normalize:Mi("before"),defaults:{description:t=>`${t.collapsibleLimitString} or earlier`,actual:Xe},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 Xa extends Le{collapsibleLimitString=Xe(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 Ei={implementation:Qa,Node:Xa},ec=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 tc 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 Di={implementation:ec,Node:tc},nc=q({kind:"max",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{},exclusive:Ri},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 rc extends Le{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:nc,Node:rc},ic=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:Ci("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 sc extends Le{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 Li={implementation:ic,Node:sc},oc=q({kind:"min",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{},exclusive:Ri},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 ac extends Le{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 Bi={implementation:oc,Node:ac},cc=q({kind:"minLength",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{parse:xn("minLength")}},reduce:t=>t.rule===0?p.intrinsic.unknown:void 0,normalize:Ci("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 lc extends Le{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 ji={implementation:cc,Node:lc},uc={min:Bi.implementation,max:Ki.implementation,minLength:ji.implementation,maxLength:Li.implementation,exactLength:Di.implementation,after:qi.implementation,before:Ei.implementation},dc={min:Bi.Node,max:Ki.Node,minLength:ji.Node,maxLength:Li.Node,exactLength:Di.Node,after:qi.Node,before:Ei.Node},hc=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 pc 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 Fi={implementation:hc,Node:pc},dt=(t,e)=>{const n=fc(t);return e&&!e.includes(n)?d(`Root of kind ${n} should be one of ${e}`):n},fc=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(Gn(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 wi)?"intersection":"proto"in t?"proto":"domain"in t?"domain":d(Gn(t))},Gn=t=>`${S(t)} is not a valid type schema`,Wn={},mc=t=>F(t)?t.map(e=>e.collapsibleJson):t.collapsibleJson,W={};p.nodesByRegisteredId=W;const Ui=t=>(Wn[t]??=0,`${t}${++Wn[t]}`),zi=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=Yr(s).sort(([l],[u])=>ut(l)?ut(u)?yt(l)-yt(u):1:ut(u)||l<u?-1:1).filter(([l,u])=>{if(l.startsWith("meta.")){const h=l.slice(5);return o[h]=u,!1}return!0});for(const l of a){const u=l[0],h=e.keys[u];if(!h)return d(`Key ${u} is not valid on ${t.kind} schema`);const m=h.parse?h.parse(l[1],t):l[1];m!==ee&&(m!==void 0||h.preserveUndefined)&&(r[u]=m)}if(e.reduce&&!t.prereduced){const l=e.reduce(r,t.$);if(l)return l instanceof g?l.throw():yc(l,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=Yr(n),c=[];let l={};for(const[x,A]of a){const P=o.keys[x],G=P.serialize??(P.child?mc:be);if(l[x]=G(A),P.child===!0){const H=A;F(H)?c.push(...H):c.push(H)}else typeof P.child=="function"&&c.push(...P.child(A))}o.finalizeInnerJson&&(l=o.finalizeInnerJson(l));let u={...l},h={};Ye(r)||(h=O(r,(x,A)=>[x,x==="examples"?A:be(A)]),u.meta=at(h,"description",!0)),l=at(l,o.collapsibleKey,!1);const m=JSON.stringify({kind:e,...l});u=at(u,o.collapsibleKey,!1);const y=at(u,o.collapsibleKey,!0),v=JSON.stringify({kind:e,...u});if(i.nodesByHash[v]&&!s)return i.nodesByHash[v];const f={id:t,kind:e,impl:o,inner:n,innerEntries:a,innerJson:l,innerHash:m,meta:r,metaJson:h,json:u,hash:v,collapsibleJson:y,children:c};if(e!=="intersection")for(const x in n)x!=="in"&&x!=="out"&&(f[x]=n[x]);const w=new kl[e](f,i);return i.nodesByHash[v]=w},gc=(t,e)=>t.id===e?t:(U(W[e])&&K(`Unexpected attempt to overwrite node id ${e}`),kn({id:e,kind:t.kind,inner:t.inner,meta:t.meta,$:t.$,ignoreCache:!0})),yc=(t,e,n)=>kn({id:Ui(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(_i(t.default,e.default)):t.default:e.hasDefault()?e.default:ee;return n.$.node("optional",{key:r,value:i,default:o})};class Ti extends Ke{required=this.kind==="required";optional=this.kind==="optional";impliedBasis=p.intrinsic.object.internal;serializedKey=De(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 _i=(t,e)=>`Invalid intersection of default values ${S(t)} & ${S(e)}`,bc=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 $c extends Ti{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",Xr(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=vc(this);defaultValueMorphRef=this.defaultValueMorph&&z(this.defaultValueMorph)}const An={implementation:bc,Node:$c},wc={},vc=t=>{if(!t.hasDefault())return;const e=`{${t.compiledKey}: ${t.value.id} = ${be(t.default)}}`;return wc[e]??=Ji(t.key,t.value,t.default)},Ji=(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(xc(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},xc=t=>`Non-primitive default ${t===null?"":typeof t=="number"?`for value at [${t}] `:`for ${De(t)} `}must be specified as a function like () => ({my: 'object'})`;class tt extends ki{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(kc):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=xi(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(Ii(`keyof ${this.expression}`)),this._keyof=this.$.finalize(e)}get props(){return this.branches.length!==1?d(Ac(this.expression)):[...this.applyStructuralOperation("props",[])[0]]}merge(e){const n=this.$.parseDefinition(e);return this.$.schema(n.distribute(r=>this.applyStructuralOperation("merge",[Hn(r)??d(Zn("merge",r.expression))])))}applyStructuralOperation(e,n){return this.distribute(r=>{if(r.equals(p.intrinsic.object)&&e!=="merge")return r;const i=Hn(r);if(i||d(Zn(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){if(this.isNever())return!0;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:K(`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 qa(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"?Xr(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 kc="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,Hn=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,Ac=t=>`Props cannot be extracted from a union. Use .distribute to extract props from each branch instead. Received:\n${t}`,Zn=(t,e)=>`${t} operand must be an object (was ${e})`,nt=(t,e)=>O(vn(t),(n,r)=>[r,e]),Ic=t=>typeof t=="string"?{reference:t}:t,Yn=t=>t instanceof g?p.intrinsic.never.internal:t,Sc=q({kind:"alias",hasAssociatedError:!1,collapsibleKey:"reference",keys:{reference:{serialize:t=>t.startsWith("$")?t:`$ark.${t}`},resolve:{}},normalize:Ic,defaults:{description:t=>t.reference},intersections:{alias:(t,e,n)=>n.$.lazilyResolve(()=>Yn(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(()=>Yn(j(t.resolution,e,n)),`${t.reference}${n.pipe?"=>":"&"}${e.id}`))}});class Nc 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(Oc(n.id,r));r.push(n.id),n=W[n.id]}return b(n,"root")?n:K(`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:K(`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 Oc=(t,e)=>`Alias '${t}' has a shallow resolution cycle: ${[...e,t].join("->")}`,Sn={implementation:Sc,Node:Nc};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 Rc=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 Cc 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:Rc,Node:Cc,writeBadAllowNanMessage:t=>`numberAllowsNaN may only be specified with domain "number" (was ${t})`},Mc=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,wa)?(r&&d(`Flattened structure key ${o} cannot be specified alongside a root 'structure' key.`),i[o]=a,[]):[o,a]);return(b(i,"constraint")||!Ye(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)=>Qn({},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.slice().sort((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)=>Qn(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 Pc extends tt{basis=this.inner.domain??this.inner.proto??null;prestructurals=[];refinements=this.children.filter(e=>e.isRefinement()?(le(bi,e.kind)&&this.prestructurals.push(e),!0):!1);structure=this.inner.structure;expression=qc(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[this.prestructurals.length-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[this.inner.predicate.length-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[this.prestructurals.length-1]),(this.structure||this.inner.predicate)&&e.returnIfFail()}if(this.structure&&(e.check(this.structure),this.inner.predicate&&e.returnIfFail()),this.inner.predicate){for(let n=0;n<this.inner.predicate.length-1;n++)e.check(this.inner.predicate[n]),e.returnIfFail();e.check(this.inner.predicate[this.inner.predicate.length-1])}}}const Vi={implementation:Mc,Node:Pc},qc=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"},Qn=(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}))},Ec=q({kind:"morph",hasAssociatedError:!1,keys:{in:{child:!0,parse:(t,e)=>e.$.parseSchema(t)},morphs:{parse:Ze,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 Dc extends tt{serializedMorphs=this.morphs.map(z);compiledMorphs=`[${this.serializedMorphs}]`;lastMorph=this.inner.morphs[this.inner.morphs.length-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 Gi={implementation:Ec,Node:Dc},Kc=(t,e)=>`The intersection of distinct morphs at a single path is indeterminate:\nLeft: ${t}\nRight: ${e}`,Lc=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:jn(t.proto,e.proto)?t:jn(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 Bc 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:Lc,Node:Bc,writeBadInvalidDateMessage:t=>`dateAllowsInvalid may only be specified with constructor Date (was ${t.name})`,writeInvalidSchemaMessage:t=>`instanceOf operand must be a function (was ${Q(t)})`},jc=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=Zc(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=vo(t.errors,"propString"),n=Object.entries(e).map(([r,i])=>{const s=[];for(const c of i)ye(s,c.expected);const o=Oe(s),a=i.every(c=>c.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(Qc(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 Fc 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?Gc(this.discriminant):null;expression=this.distribute(e=>e.nestableExpression,Hc);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)),c=JSON.stringify(o),l=this.discriminant.kind==="domain"?`${Jc}[${n}]`:`${Vc}(${n})`;e.line(`ctx.errorFromNodeContext({\n\tcode: "predicate",\n\texpected: ${c},\n\tactual: ${l},\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 c=this.branches[a],l=oe(o.rawIn,c.rawIn,o.$);if(l instanceof g)for(const u of l){if(!u.kind||u.optional)continue;let h,m;if(u.kind==="domain"){const v=u.l,f=u.r;h=`"${typeof v=="string"?v:v.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(v=>Ce(v.path,u.path)&&v.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?Tc(e,this.branches):e;if(!n.length)return null;const r=Uc(n,this),i={};for(const s in r.best.cases){const o=zc(r,s);if(o===null){i[s]=!0;continue}if(o.length===this.branches.length)return null;this.ordered&&o.sort((l,u)=>l.originalIndex-u.originalIndex);const a=o.map(l=>l.branch),c=a.length===1?a[0]:this.$.node("union",this.ordered?{branches:a,ordered:!0}:a);Object.assign(this.referencesById,c.referencesById),i[s]=c}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 Uc=(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:Wi(r.path)},s=e.branches.map((o,a)=>({originalIndex:a,branch:o}));return{best:r,location:i,defaultEntries:s,node:e}},zc=(t,e)=>{const n=t.best.cases[e],r=_c(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 c=Xn(t.node.branches[a.originalIndex],t.location);c===null?i=null:i?.push({originalIndex:a.originalIndex,branch:c})}else if(a.branch.hasKind("alias")&&r.hasKind("domain")&&r.domain==="object")i?.push(a);else{if(a.branch.rawIn.overlaps(r)){const c=Xn(a.branch,t.location);i?.push({originalIndex:a.originalIndex,branch:c})}s.push(a)}}return t.defaultEntries=s,i},Tc=(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 c=i[a];for(const l of o)for(const u of c)if(l>u&&e[l].overlaps(e[u]))return!1}}return!0}),_c=(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:[...$o(s).map(o=>({})),r]}:{domain:"object",required:[{key:s,value:r}]})}return r},Wi=t=>t.reduce((e,n)=>e+mi(n,!0),"data"),Jc=z(xo),Vc=z(S),Hi={implementation:jc,Node:Fc},Gc=t=>({kind:t.kind,path:t.path.map(e=>typeof e=="string"?e:De(e)),cases:O(t.cases,(e,n)=>[e,n===!0?n:n.hasKind("union")&&n.discriminantJson?n.discriminantJson:n.json])}),Wc={delimiter:" | ",finalDelimiter:" | "},Hc=t=>Oe(t,Wc),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 c=j(t[s],e[a],n);if(!(c instanceof g)){if(c.equals(t[s])){r[a].push(t[s]),o={};break}c.equals(e[a])?r[a]=null:o[a]=c}}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},Zc=({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||Yc(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])},Yc=(t,e)=>{!t.includesTransform&&!e.includesTransform||(Ce(t.shallowMorphs,e.shallowMorphs)||d(er(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(er(t.expression,e.expression)))},Xn=(t,e)=>t.transform((n,r)=>n==="domain"||n==="unit"?null:r,{shouldTransform:(n,r)=>{const i=Wi(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}}),er=(t,e)=>`An unordered union of a type including a morph and a type with overlapping input is indeterminate:\nLeft: ${t}\nRight: ${e}`,Qc=(t,e)=>`The intersection of two ordered unions is indeterminate:\nLeft: ${t}\nRight: ${e}`,Xc=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 el extends Nn{compiledValue=this.json.unit;serializedValue=typeof this.unit=="string"||this.unit instanceof Date?JSON.stringify(this.compiledValue):`${this.compiledValue}`;compiledCondition=tr(this.unit,this.serializedValue);compiledNegation=tr(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 Zi={implementation:Xc,Node:el},tr=(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}`},tl=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(il(n.expression));const r=n.branches.filter(i=>i.hasKind("unit"));return r.length?d(rl(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 nl 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 Yi={implementation:tl,Node:nl},rl=t=>`Index keys ${t.join(", ")} should be specified as named props.`,il=t=>`Indexed key definition '${t}' must be a string or symbol`,sl=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 ol extends Ti{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 Qi={implementation:sl,Node:ol},al=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(hl);if(t.optionals?.length||t.defaultables?.length)return d(es)}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[s.length-1]?.equals(t.variadic);)s.pop();if(s.length===0&&i.length===0)for(;r[r.length-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=Ue({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",nr(i[0].result)):n.$.node("union",i.map(s=>({proto:Array,sequence:nr(s.result)})))}}});class cl extends Ke{impliedBasis=p.intrinsic.Array.internal;tuple=dl(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 _n(this.flatRefs,this.prevariadic.flatMap((e,n)=>N(e.node.flatRefs.map(r=>de([`${n}`,...r.path],r.node)),de([`${n}`],e.node)))),_n(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=ul(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??K(`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 ll={},ul=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(Ji(i,s,o)),n+=`${i}: ${s.id} = ${be(o)}, `}return n+="]",ll[n]??=e},Xi={implementation:al,Node:cl},dl=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},nr=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),{}),es="A postfix required element cannot follow an optional or defaultable element",hl="A postfix element requires a variadic element",Ue=t=>{const[e,...n]=t.l,[r,...i]=t.r;if(!e||!r)return t;const s=n[n.length-1]?.kind==="postfix",o=i[i.length-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=Ue({...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=Ue({...t,fixedVariants:[],l:n.map(m=>({...m,kind:"prefix"}))});h.disjoint.length===0&&t.fixedVariants.push(h)}const c=j(e.node,r.node,t.ctx);if(c instanceof g)if(a==="prefix"||a==="postfix")t.disjoint.push(...c.withPrefixKey(a==="prefix"?t.result.length:`-${n.length+1}`,rr(e)&&rr(r)?"required":"optional")),t.result=[...t.result,{kind:a,node:p.intrinsic.never.internal}];else return a==="optionals"||a==="defaultables"?t:Ue({...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(_i(e.default,r.default)),t.result=[...t.result,{kind:a,node:c,default:e.kind==="defaultables"?e.default:r.kind==="defaultables"?r.default:K(`Unexpected defaultable intersection from ${e.kind} and ${r.kind} elements.`)}]):t.result=[...t.result,{kind:a,node:c}];const l=t.l.length,u=t.r.length;return(e.kind!=="variadic"||l>=u&&(r.kind==="variadic"||u===1))&&(t.l=n),(r.kind!=="variadic"||u>=l&&(e.kind==="variadic"||l===1))&&(t.r=i),Ue(t)},rr=t=>t.kind==="prefix"||t.kind==="postfix",ts=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??"{}"},pl=ts("description"),fl=ts("expression"),ir=(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},ml=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:pl},intersections:{structure:(t,e,n)=>{const r={...t.inner},i={...e.inner},s=new g;if(t.undeclared){const c=t.keyof();for(const l of e.requiredKeys)c.allows(l)||s.add("presence",p.intrinsic.never.internal,e.propsByKey[l].value,{path:[l]});i.optional&&(i.optional=i.optional.filter(l=>c.allows(l.key))),i.index&&(i.index=i.index.flatMap(l=>{if(l.signature.extends(c))return l;const u=oe(c,l.signature,n.$);if(u instanceof g)return[];const h=rn(u,l.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 c=e.keyof();for(const l of t.requiredKeys)c.allows(l)||s.add("presence",t.propsByKey[l].value,p.intrinsic.never.internal,{path:[l]});r.optional&&(r.optional=r.optional.filter(l=>c.allows(l.key))),r.index&&(r.index=r.index.flatMap(l=>{if(l.signature.extends(c))return l;const u=oe(c,l.signature,n.$);if(u instanceof g)return[];const h=rn(u,l.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.required&&!t.optional)return;const n={};let r=!1;const i=t.optional?[...t.optional]:[];if(t.required)for(let s=0;s<t.required.length;s++){const o=t.required[s];if(o.key in n&&d(or(o.key)),n[o.key]=!0,t.index)for(const a of t.index){const c=ir(o,a,e);if(c instanceof g)return c}}if(t.optional)for(let s=0;s<t.optional.length;s++){const o=t.optional[s];if(o.key in n&&d(or(o.key)),n[o.key]=!0,t.index)for(const a of t.index){const c=ir(o,a,e);if(c instanceof g)return c;c!==null&&(i[s]=c,r=!0)}}if(r)return e.node("structure",{...t,optional:i},{prereduced:!0})}});class gl 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=fl(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,c)=>a in An.implementation.keys?[a,c]:[]);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(sr(this.expression,n))}get(e,...n){let r,i=!1;const s=wl(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 c=this.sequence.prevariadic[a].node;r=r?.and(c)??c,i||=a<this.sequence.prefixLength}else if(this.sequence.variadic){const c=this.$.node("union",this.sequence.variadicOrPostfix);r=r?.and(c)??c}}if(!r)return this.sequence?.variadic&&b(s,"root")&&s.extends(p.intrinsic.number)?d(vl(s.expression,this.sequence.expression)):d(sr(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=yi(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 c of this.index)if(c.signature.traverseAllows(a,r)){if(e==="Allows"){if(!se(a,()=>c.value.traverseAllows(n[a],r),r))return!1}else if(se(a,()=>c.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",bl(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(["),$l(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 K(`Unexpected index branch kind ${s.kind}.`);const{pattern:a}=s.inner;if(a){const c=Object.assign(o,{pattern:a[0].rule});for(let l=1;l<a.length;l++)o=n.fallback.patternIntersection({code:"patternIntersection",base:c,pattern:a[l].rule});e.patternProperties??={},e.patternProperties[c.pattern]=i}}}return this.undeclared&&!e.additionalProperties&&(e.additionalProperties=!1),e}}const jt={},yl=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},bl=t=>{const e=yl(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},$l=(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)`,c=>c.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")})},ns={implementation:ml,Node:gl},wl=t=>(b(t,"root")&&t.hasKind("unit")&&(t=t.unit),typeof t=="number"&&(t=`${t}`),t),vl=(t,e)=>`${t} is not allowed as an array index on ${e}. Use the 'nonNegativeIntegerString' keyword instead.`,rn=(t,e,n)=>{const[r,i]=bo(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},xl=t=>b(t,"root")?t.expression:S(t),sr=(t,e)=>`Key${e.length===1?"":"s"} ${e.map(xl).join(", ")} ${e.length===1?"does":"do"} not exist on ${t}`,or=t=>`Duplicate key ${De(t)}`,Ct={...uc,alias:Sn.implementation,domain:On.implementation,unit:Zi.implementation,proto:vt.implementation,union:Hi.implementation,morph:Gi.implementation,intersection:Vi.implementation,divisor:Oi.implementation,pattern:Fi.implementation,predicate:Ni.implementation,required:Qi.implementation,optional:An.implementation,index:Yi.implementation,sequence:Xi.implementation,structure:ns.implementation};p.defaultConfig=Co(Object.assign(O(Ct,(t,e)=>[t,e.defaults]),{jitless:Fo(),clone:Lo,onUndeclaredKey:"ignore",exactOptionalPropertyTypes:!0,numberAllowsNaN:!1,dateAllowsInvalid:!1,onFail:null,keywords:{},toJsonSchema:L.defaultConfig}));p.resolvedConfig=Qt(p.defaultConfig,p.config);const kl={...dc,alias:Sn.Node,domain:On.Node,unit:Zi.Node,proto:vt.Node,union:Hi.Node,morph:Gi.Node,intersection:Vi.Node,divisor:Oi.Node,pattern:Fi.Node,predicate:Ni.Node,required:Qi.Node,optional:An.Node,index:Yi.Node,sequence:Xi.Node,structure:ns.Node};class sn extends So{get[ie](){return"module"}}const rs=(t,e)=>new sn(O(t,(n,r)=>[n,b(r,"module")?rs(r,e):e.bindReference(r)])),Al=t=>F(t)?t:"branches"in t&&F(t.branches)?t.branches:void 0,Il=(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 is="function $",Sl=t=>ss(t,os(t)),ss=(t,e)=>{const n=e.write(is,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)},os=t=>(new fi).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 c=new Lt({kind:"Allows",optimistic:!0}).indent();n.compile(c);const l=c.write(`${n.id}Optimistic`);return`${a}${l},\n`},`{\n`)+"}");class as{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 Si(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 c=this.resolveRoot(a.slice(1));n=c,i=c.kind}}else if(i==="union"&&$e(n,"object")){const a=Al(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:Il(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(ds(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 K(`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 K(`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(hs(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??Ui(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")?rs(i,this):lr(this.maybeResolve(r))}for(const r of this.lazyResolutions)r.resolution;if(this._exportedResolutions=us(this,this._exports),this._json=ls(this._exportedResolutions),Object.assign(this.resolutions,this._exportedResolutions),this.references=Object.values(this.referencesById),!this.resolvedConfig.jitless){const r=os(this.references);this.precompilation=r.write(is,4),ss(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=zi(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=gc(s,i.id)),W[i.id]=s,s}finalize(e){return lr(e),!e.precompilation&&!this.resolvedConfig.jitless&&Sl(e.references),e}}class cs extends as{parseOwnDefinitionFormat(e,n){return zi(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},ls=t=>O(t,(e,n)=>[e,b(n,"root")||b(n,"generic")?n.json:b(n,"module")?ls(n):K(`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(Nl(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(hs(e));K(`Unexpected resolution for alias '${e}': ${S(o)}`)},Rn=(t,e)=>new cs(t,e),rt=new cs({}),us=(t,e)=>{const n={};for(const r in e){const i=e[r];if(b(i,"module")){const s=us(t,i),o=O(s,(a,c)=>[`${r}.${a}`,c]);Object.assign(n,o)}else b(i,"root")||b(i,"generic")?n[r]=i:K(`Unexpected scope resolution ${S(i)}`)}return n},ds=t=>`'${t}' is unresolvable`,Nl=t=>`'${t}' must reference a module to be accessed using dot syntax`,hs=t=>`Reference to submodule '${t}' must specify an alias`;rt.export();const R=rt.schema,Cn=rt.node;rt.defineSchema;const ae=rt.generic,ps="^(?:0|[1-9]\\d*)$",Ol=new RegExp(ps);z(Ol);const fs=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={...fs};const ms=Rn({integer:{domain:"number",divisor:1},lengthBoundable:["string",Array],key:["string","symbol"],nonNegativeIntegerString:{domain:"string",pattern:ps}},{prereducedAliases:!0}).export();Object.assign(p.intrinsic,ms);const Rl=Rn({jsonPrimitive:["string","number",{unit:!0},{unit:!1},{unit:null}],jsonObject:{domain:"object",index:{signature:"string",value:"$jsonData"}},jsonData:["$jsonPrimitive","$jsonObject"]},{prereducedAliases:!0}).export(),$={...fs,...ms,...Rl,emptyStructure:Cn("structure",{},{prereduced:!0})};p.intrinsic={...$};const ur=(t,e)=>new RegExp(t,e);Object.assign(ur,{as:ur});const Cl=t=>typeof t=="string"&&t[0]==="d"&&(t[1]==="'"||t[1]==='"')&&t[t.length-1]===t[1],dr=t=>t.toString()!=="Invalid Date",Ml=t=>t.slice(2,-1),gs=t=>`'${t}' could not be parsed by the Date constructor`,Pl=(t,e)=>ql(t,e),ql=(t,e)=>{const n=new Date(t);if(dr(n))return n;const r=ra(t);if(r!==void 0){const i=new Date(r);if(dr(i))return i}return e?d(e===!0?gs(t):e):void 0},hr=(t,e)=>{const n=t.scanner.shiftUntilEscapable(Kl[bs[e]]);if(t.scanner.lookahead==="")return t.error(Bl(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,ys))t.root=t.ctx.$.node("unit",{unit:n});else{const r=Pl(n,gs(n));t.root=t.ctx.$.node("unit",{meta:n,unit:r})}},ys={"'":1,'"':1},El={"/":1,"'":1,'"':1},Dl={"d'":"'",'d"':'"',"'":"'",'"':'"'},bs={...Dl,"/":"/"},Kl={"'":t=>t.lookahead==="'",'"':t=>t.lookahead==='"',"/":t=>t.lookahead==="/"},Ll={'"':"double-quote","'":"single-quote","/":"forward slash"},Bl=(t,e)=>`${e}${t} requires a closing ${Ll[bs[e]]}`,jl=t=>`Private type references should not include '#'. Use '${t}' instead.`,$s="Optional definitions like 'string?' are only valid as properties in an object or tuple",ws="Defaultable definitions like 'number = 0' are only valid as properties in an object or tuple",Be={"<":1,">":1,"=":1,"|":1,"&":1,")":1,"[":1,"%":1,",":1,":":1,"?":1,"#":1,...It},Fl=(t,e)=>t===">"?e[0]==="="?e[1]==="=":e.trimStart()===""||te(e.trimStart()[0],Be):t==="="?e[0]!=="=":t===","||t==="?",Ul=(t,e,n)=>vs(t,e,n,[]),vs=(t,e,n,r)=>{const i=n.parseUntilFinalizer();return r.push(i.root),i.finalizer===">"?r.length!==e.params.length?n.error(xs(t,e.names,r.map(s=>s.expression))):r:i.finalizer===","?vs(t,e,n,r):i.error(hi(">"))},xs=(t,e,n)=>`${t}<${e.join(", ")}> requires exactly ${e.length} args (got ${n.length}${n.length===0?"":`: ${n.join(", ")}`})`,pr=t=>{const e=t.scanner.shiftUntilLookahead(Be);e==="keyof"?t.addPrefix("keyof"):t.root=Tl(t,e)},zl=(t,e,n)=>{if(n.scanner.shiftUntilNonWhitespace(),n.scanner.shift()!=="<")return n.error(xs(t,e.names,[]));const i=Ul(t,e,n);return e(...i)},Tl=(t,e)=>_l(t,e)??Jl(t,e)??t.error(e===""?t.scanner.lookahead==="#"?jl(t.shiftedByOne().scanner.shiftUntilLookahead(Be)):ks(t):ds(e)),_l=(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")?zl(e,n,t):d(`Unexpected resolution ${S(n)}`)},Jl=(t,e)=>{const n=ia(e);if(n!==void 0)return t.ctx.$.node("unit",{unit:n});const r=oa(e);if(r!==void 0)return t.ctx.$.node("unit",{unit:r})},ks=t=>{const e=t.previousOperator();return e?As(e,t.scanner.unscanned):Vl(t.scanner.unscanned)},As=(t,e="")=>`Token '${t}' requires a right operand${e?` before '${e}'`:""}`,Vl=t=>`Expected an expression${t?` before '${t}'`:""}`,Is=t=>t.scanner.lookahead===""?t.error(ks(t)):t.scanner.lookahead==="("?t.shiftedByOne().reduceGroupOpen():t.scanner.lookaheadIsIn(El)?hr(t,t.scanner.shift()):t.scanner.lookaheadIsIn(It)?Is(t.shiftedByOne()):t.scanner.lookahead==="d"&&t.scanner.nextLookahead in ys?hr(t,`${t.scanner.shift()}${t.scanner.shift()}`):pr(t),Gl={">":!0,">=":!0},Wl={"<":!0,"<=":!0},xt={"<":">",">":"<","<=":">=",">=":"<=","==":"=="},Hl=(t,e)=>`Left bounds are only valid when paired with right bounds (try ...${e}${t})`,Ss=t=>`Left-bounded expressions must specify their limits using < or <= (was ${t})`,Zl=(t,e,n,r)=>`An expression may have at most one left bound (parsed ${t}${xt[e]}, ${n}${xt[r]})`,Yl=(t,e)=>{const n=Xl(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 tu(t,n)},Ql={"<":1,">":1,"=":1},Xl=(t,e)=>t.scanner.lookaheadIs("=")?`${e}${t.scanner.shift()}`:e,fr=(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(Ha(n.expression)),eu=t=>({rule:Cl(t.limit)?Ml(t.limit):t.limit,exclusive:t.comparator.length===1}),tu=(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,c=fr(e,typeof o=="number"?o:s,n,"right");for(const u of c)t.constrainRoot(u,e==="=="?{rule:o}:{rule:o,exclusive:a});if(!t.branches.leftBound)return;if(!te(e,Wl))return t.error(Ss(e));const l=fr(t.branches.leftBound.comparator,t.branches.leftBound.limit,n,"left");t.constrainRoot(l[0],eu(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})`,nu=t=>{t.scanner.shiftUntilNonWhitespace();const e=t.scanner.shiftUntilLookahead(Be);t.root=t.root.brand(e)},ru=t=>{t.scanner.shiftUntilNonWhitespace();const e=t.scanner.shiftUntilLookahead(Be),n=sa(e,{errorOnFail:mr(e)});n===0&&t.error(mr(0)),t.root=t.root.constrain("divisor",n)},mr=t=>`% operator must be followed by a non-zero integer literal (was ${t})`,Ns=t=>{const e=t.scanner.shift();return e===""?t.finalize(""):e==="["?t.scanner.shift()==="]"?t.setRoot(t.root.array()):t.error(iu):e==="|"?t.scanner.lookahead===">"?t.shiftedByOne().pushRootToBranch("|>"):t.pushRootToBranch(e):e==="&"?t.pushRootToBranch(e):e===")"?t.finalizeGroup():Fl(e,t.scanner.unscanned)?t.finalize(e):te(e,Ql)?Yl(t,e):e==="%"?ru(t):e==="#"?nu(t):e in It?Ns(t):t.error(Mn(e))},Mn=(t,e="")=>`'${t}' is not allowed here${e&&` (should be ${e})`}`,iu="Missing expected ']'",su=t=>{const e=t.unsetRoot();t.parseOperand();const n=t.unsetRoot();if(!n.hasKind("unit"))return t.error(ou(n.expression));const r=n.unit instanceof Date?()=>new Date(n.unit):n.unit;return[e,"=",r]},ou=t=>`Default value '${t}' must be a literal value`,gr=(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 di(t),e),i=au(r);return r.finalizer===">"&&d(Mn(">")),i},au=t=>{t.parseOperand();let e=Pn(t).root;return e?(t.finalizer==="="?e=su(t):t.finalizer==="?"&&(e=[e,"?"]),t.scanner.shiftUntilNonWhitespace(),t.scanner.lookahead&&d(Mn(t.scanner.lookahead)),e):K(`Root was unexpectedly unset after parsing string '${t.scanner.scanned}'`)},Pn=t=>{for(;t.finalizer===void 0;)cu(t);return t},cu=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(hi(")"));this.finalizeBranches(),this.finalizer=e}reduceLeftBound(e,n){const r=xt[n];if(!te(r,Gl))return this.error(Ss(n));if(this.branches.leftBound)return this.error(Zl(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(fa(")",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():K(`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 Ns(this)}parseOperand(){return Is(this)}assertRangeUnset(){if(this.branches.leftBound)return this.error(Hl(this.branches.leftBound.limit,this.branches.leftBound.comparator))}reduceGroupOpen(){this.groups.push(this.branches),this.branches={prefixes:[],leftBound:null,union:null,intersection:null,pipe:null}}previousOperator(){return this.branches.leftBound?.comparator??this.branches.prefixes[this.branches.prefixes.length-1]??(this.branches.intersection?"&":this.branches.union?"|":this.branches.pipe?"|>":void 0)}shiftedByOne(){return this.scanner.shift(),this}}const lu="An empty string is not a valid generic parameter name",cn=(t,e,n)=>{t.shiftUntilNonWhitespace();const r=t.shiftUntilLookahead(Be);return r===""?t.lookahead===""&&e.length?e:d(lu):(t.shiftUntilNonWhitespace(),uu(t,r,e,n))},yr="extends ",uu=(t,e,n,r)=>{if(t.shiftUntilNonWhitespace(),t.unscanned.startsWith(yr))t.jumpForward(yr.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 du 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 c=e.intrinsic.unknown;if(i!==-1){if(i!==r.length-2)return d(pu);c=e.parse(r[i+1])}return l=>new hu(l,a,c)},{attach:n})}}class hu extends pe{raw;params;returns;expression;constructor(e,n,r){const i=`typed ${e.name}`,s={[i]:(...a)=>{const c=n.assert(a),l=e(...c);return r.assert(l)}}[i];super(s),this.raw=e,this.params=n,this.returns=r;let o=n.expression;o[0]==="["&&o[o.length-1]==="]"?o=o.slice(1,-1):o.endsWith("[]")&&(o=`...${o}`),this.expression=`(${o}) => ${r?.expression??"unknown"}`}}const pu=`":" must be followed by exactly one return type e.g:\nfn("string", ":", "number")(s => s.length)`;class fu 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(gu),this.branches.length&&d(mu),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:br});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:br},"self")),this.$.finalize(i)}}const br=t=>t.throw(),mu="A key matcher must be specified before the first case i.e. match.at('foo') or match.in<object>().at('bar')",gu="At most one key matcher may be specified per expression",Os=(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 Ds(t,e)},yu="Only required keys may make their values optional, e.g. { [mySymbol]: ['number', '?'] }",bu="Only required keys may specify default values, e.g. { value: 'number = 0' }",$u=(t,e)=>{let n;const r={},i=ft(t);for(const[o,a]of i){const c=xu(o);if(c.kind==="spread"){if(!Ye(r))return d(vu);const y=e.$.parseOwnDefinitionFormat(a,e);if(y.equals($.object))continue;if(!y.hasKind("intersection")||!y.basis?.equals($.object))return d(ku(y.expression));n=y.structure;continue}if(c.kind==="undeclared"){a!=="reject"&&a!=="delete"&&a!=="ignore"&&d(wu(a)),r.undeclared=a;continue}const l=Os(a,e),u=c;if(c.kind==="required"){F(l)?Ut(r,"optional",l[1]==="="?{key:c.normalized,value:l[0],default:l[2]}:{key:c.normalized,value:l[0]},e):Ut(r,"required",{key:c.normalized,value:l},e);continue}if(F(l)&&(l[1]==="?"&&d(yu),l[1]==="="&&d(bu)),c.kind==="optional"){Ut(r,"optional",{key:c.normalized,value:l},e);continue}const h=e.$.parseOwnDefinitionFormat(u.normalized,e),m=rn(h,l,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))},wu=t=>`Value of '+' key must be 'reject', 'delete', or 'ignore' (was ${S(t)})`,vu="Spread operator may only be used as the first key in an object",xu=t=>typeof t=="symbol"?{kind:"required",normalized:t}:t[t.length-1]==="?"?t[t.length-2]===Te?{kind:"required",normalized:`${t.slice(0,-2)}?`}:{kind:"optional",normalized:t.slice(0,-1)}:t[0]==="["&&t[t.length-1]==="]"?{kind:"index",normalized:t.slice(1,-1)}:t[0]===Te&&t[1]==="["&&t[t.length-1]==="]"?{kind:"required",normalized:t.slice(1)}:t==="..."?{kind:"spread"}:t==="+"?{kind:"undeclared"}:{kind:"required",normalized:t==="\\..."?"...":t==="\\+"?"+":t},ku=t=>`Spread operand must resolve to an object literal type (was ${t})`,Au=(t,e)=>Eu(t)?Ps[t[0]](t,e):Pu(t)?Ms[t[1]](t,e):null,Iu=(t,e)=>e.$.parseOwnDefinitionFormat(t[1],e).keyof(),zt=(t,e)=>{if(t[2]===void 0)return d(As(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},Su=(t,e)=>e.$.parseOwnDefinitionFormat(t[0],e).array(),Nu=(t,e)=>typeof t[2]!="function"?d(Rs("=>",t[2])):e.$.parseOwnDefinitionFormat(t[0],e).pipe(t[2]),Rs=(t,e)=>`${t===":"?"Narrow":"Morph"} expression requires a function following '${t}' (was ${typeof e})`,Ou=(t,e)=>typeof t[2]!="function"?d(Rs(":",t[2])):e.$.parseOwnDefinitionFormat(t[0],e).constrain("predicate",t[2]),Ru=(t,e)=>e.$.parseOwnDefinitionFormat(t[0],e).configure(t[2],t[3]),Cs=t=>t,Cu=Cs({"[]":Su,"?":()=>d($s)}),Mu=Cs({"|":zt,"&":zt,":":Ou,"=>":Nu,"|>":zt,"@":Ru,"=":()=>d(ws)}),Ms={...Cu,...Mu},Pu=t=>Ms[t[1]]!==void 0,qu=t=>t,Ps=qu({keyof:Iu,instanceof:(t,e)=>{if(typeof t[1]!="function")return d($r(Gt(t[1])));const n=t.slice(1).map(r=>typeof r=="function"?e.$.node("proto",{proto:r}):d($r(Gt(r))));return n.length===1?n[0]:e.$.node("union",{branches:n})},"===":(t,e)=>e.$.units(t.slice(1))}),Eu=t=>Ps[t[0]]!==void 0,$r=t=>`Expected a constructor following 'instanceof' operator (was ${t})`,Du=(t,e)=>{let n=[{}],r=0;for(;r<t.length;){let i=!1;t[r]==="..."&&r<t.length-1&&(i=!0,r++);const s=Os(t[r],e),[o,a,c]=F(s)?s:[s];if(r++,i){if(!o.extends(p.intrinsic.Array))return d(Bu(o.expression));n=n.flatMap(l=>o.distribute(u=>Lu(yi(l),u)))}else n=n.map(l=>a==="?"?qs(l,o):a==="="?Ku(l,o,c):ln(l,o))}return e.$.parseSchema(n.map(i=>Ye(i)?{proto:Array,exactLength:0}:{proto:Array,sequence:i}))},ln=(t,e)=>t.defaultables||t.optionals?d(t.variadic?es:ju):(t.variadic?t.postfix=N(t.postfix,e):t.prefix=N(t.prefix,e),t),qs=(t,e)=>t.variadic?d(Es):(t.optionals=N(t.optionals,e),t),Ku=(t,e,n)=>t.variadic?d(Es):t.optionals?d(Fu):(t.defaultables=N(t.defaultables,[[e,n]]),t),wr=(t,e)=>(t.postfix&&d(vr),t.variadic?t.variadic.equals(e)||d(vr):t.variadic=e.internal,t),Lu=(t,e)=>{const n=e.select({method:"find",kind:"sequence"});if(!n)return wr(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)qs(t,r);if(n.variadic&&wr(t,n.variadic),n.postfix)for(const r of n.postfix)ln(t,r);return t},Bu=t=>`Spread element must be an array (was ${t})`,vr="A tuple may have at most one variadic element",ju="A required element may not follow an optional element",Es="An optional element may not follow a variadic element",Fu="A defaultable element may not follow an optional element without a default",Uu={},Ds=(t,e)=>{if(typeof t=="string"){if(e.args&&Object.keys(e.args).some(r=>t.includes(r)))return gr(t,e);const n=Uu[e.$.name]??={};return n[t]??=gr(t,e)}return $e(t,"object")?zu(t,e):d(un(Q(t)))},zu=(t,e)=>{const n=gn(t);switch(n){case void 0:return b(t,"root")?t:$u(t,e);case"Array":return Tu(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)))}},Tu=(t,e)=>Au(t,e)??Du(t,e),un=t=>`Type definitions must be strings or objects (was ${t})`;class _u 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][r[0].length-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 We=p;class Pt extends as{get ambientAttachments(){if(We.typeAttachments)return this.cacheGetter("ambientAttachments",O(We.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[e.length-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 Da(o,n,this)}]}parseGenericParams(e,n){return cn(new di(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=Ds(e,n);if(F(i)){if(i[1]==="=")return d(ws);if(i[1]==="?")return d($s)}return i}unit=e=>this.units([e]);valueOf=e=>this.units(Mo(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 du(this);match=new fu(this);declare=()=>({type:this.type});define(e){return e}type=new _u(this);static scope=(e,n={})=>new Pt(e,n);static module=(e,n={})=>this.scope(e,n).export()}const Ju=Object.assign(Pt.scope,{define:t=>t}),I=Pt;class Vu extends ne{description='merge an object\'s properties onto another like `Merge(User, { isAdmin: "true" })`'}const Gu=ae(["base",$.object],["props",$.object])(t=>t.base.merge(t.props),Vu),Wu=I.module({Key:$.key,Merge:Gu});class Hu extends ne{}const Zu=ae("element")(t=>{const e=t.element.exclude($.Array),n=e.array();return e.rawOr(n).pipe(Ze).distribute(r=>r.assertHasKind("morph").declareOut(n),R)},Hu),Yu=I.module({root:$.Array,readonly:"root",index:$.nonNegativeIntegerString,liftFrom:Zu},{name:"Array"}),dn=R(["string",Qe.FileConstructor]),Qu=dn.rawOr(dn.array()),xr=R({meta:"an object representing parsed form data",domain:"object",index:{signature:"string",value:Qu}}),Xu=I.module({root:["instanceof",FormData],value:dn,parsed:xr,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 Qe.FileConstructor?e[n]=[i,r]:i.push(r)}else e[n]=r;return e},declaredOut:xr})},{name:"FormData"}),ed=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"}),td={Boolean:1,Number:1,String:1},nd=I.module({...O({...ei,...ni},(t,e)=>t in td?[]:[t,["instanceof",e]]),Array:Yu,TypedArray:ed,FormData:Xu}),rd=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"}),id=R({domain:"number",divisor:1}),Ks=I.module({root:$.number,integer:id,epoch:rd,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)},kr=M(mt,"a well-formed integer string"),Ls=I.module({root:kr,parse:R({in:kr,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"}),sd=M(/^[\dA-Fa-f]+$/,"hex characters only"),od=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"}),Ar=M(/^[A-Z].*$/,"capitalized"),ad=I.module({root:R({in:"string",morphs:t=>t.charAt(0).toUpperCase()+t.slice(1),declaredOut:Ar}),preformatted:Ar},{name:"string.capitalize"}),cd=t=>{const e=t.replace(/[ -]+/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)},ld=/^(?: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}))$/,ud=R({domain:"string",pattern:{meta:"a credit card number",rule:ld.source},predicate:{meta:"a credit card number",predicate:cd}}),dd=/^([+-]?\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)?)?)?)?$/,hd=t=>!Number.isNaN(new Date(t).valueOf()),Ir=R({domain:"string",predicate:{meta:"a parsable date",predicate:hd}}).assertHasKind("intersection"),Sr=Ls.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"),pd=I.module({root:Sr,parse:R({in:Sr,morphs:t=>new Date(t),declaredOut:$.Date})},{name:"string.date.epoch"}),Nr=M(dd,"an ISO 8601 (YYYY-MM-DDTHH:mm:ss.sssZ) date").internal.assertHasKind("intersection"),fd=I.module({root:Nr,parse:R({in:Nr,morphs:t=>new Date(t),declaredOut:$.Date})},{name:"string.date.iso"}),md=I.module({root:Ir,parse:R({declaredIn:Ir,in:"string",morphs:(t,e)=>{const n=new Date(t);return Number.isNaN(n.valueOf())?e.error("a parsable date"):n},declaredOut:$.Date}),iso:fd,epoch:pd},{name:"string.date"}),gd=M(/^[\w%+.-]+@[\d.A-Za-z-]+\.[A-Za-z]{2,}$/,"an email address","email"),Or="(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])",ce=`(${Or}[.]){3}${Or}`,yd=new RegExp(`^${ce}$`),D="(?:[0-9a-fA-F]{1,4})",bd=new RegExp(`^((?:${D}:){7}(?:${D}|:)|(?:${D}:){6}(?:${ce}|:${D}|:)|(?:${D}:){5}(?::${ce}|(:${D}){1,2}|:)|(?:${D}:){4}(?:(:${D}){0,1}:${ce}|(:${D}){1,3}|:)|(?:${D}:){3}(?:(:${D}){0,2}:${ce}|(:${D}){1,4}|:)|(?:${D}:){2}(?:(:${D}){0,3}:${ce}|(:${D}){1,5}|:)|(?:${D}:){1}(?:(:${D}){0,4}:${ce}|(:${D}){1,6}|:)|(?::((?::${D}){0,5}:${ce}|(?::${D}){1,7}|:)))(%[0-9a-zA-Z.]{1,})?$`),$d=I.module({root:["v4 | v6","@","an IP address"],v4:M(yd,"an IPv4 address","ipv4"),v6:M(bd,"an IPv6 address","ipv6")},{name:"string.ip"}),Re="a JSON string",Bs=t=>{if(!(t instanceof SyntaxError))throw t;return`must be ${Re} (${t})`},wd=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:Bs(n)})}}}}),vd=(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:Bs(n)})}},xd=I.module({root:wd,parse:R({meta:"safe JSON string parser",in:"string",morphs:vd,declaredOut:$.jsonObject})},{name:"string.json"}),Rr=M(/^[a-z]*$/,"only lowercase letters"),kd=I.module({root:R({in:"string",morphs:t=>t.toLowerCase(),declaredOut:Rr}),preformatted:Rr},{name:"string.lower"}),js=["NFC","NFD","NFKC","NFKD"],it=O(js,(t,e)=>[e,R({domain:"string",predicate:n=>n.normalize(e)===n,meta:`${e}-normalized unicode`})]),qt=O(js,(t,e)=>[e,R({in:"string",morphs:n=>n.normalize(e),declaredOut:it[e]})]),Ad=I.module({root:qt.NFC,preformatted:it.NFC},{name:"string.normalize.NFC"}),Id=I.module({root:qt.NFD,preformatted:it.NFD},{name:"string.normalize.NFD"}),Sd=I.module({root:qt.NFKC,preformatted:it.NFKC},{name:"string.normalize.NFKC"}),Nd=I.module({root:qt.NFKD,preformatted:it.NFKD},{name:"string.normalize.NFKD"}),Od=I.module({root:"NFC",NFC:Ad,NFD:Id,NFKC:Sd,NFKD:Nd},{name:"string.normalize"}),Cr=M(Wt,"a well-formed numeric string"),Rd=I.module({root:Cr,parse:R({in:Cr,morphs:t=>Number.parseFloat(t),declaredOut:$.number})},{name:"string.numeric"}),Mr="a regex pattern",Cd=R({domain:"string",predicate:{meta:Mr,predicate:(t,e)=>{try{return new RegExp(t),!0}catch(n){return e.reject({code:"predicate",expected:Mr,problem:String(n)})}}},meta:{format:"regex"}}),Md=/^(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-]+)*))?$/,Pd=M(Md,"a semantic version (see https://semver.org/)"),Pr=M(/^\S.*\S$|^\S?$/,"trimmed"),qd=I.module({root:R({in:"string",morphs:t=>t.trim(),declaredOut:Pr}),preformatted:Pr},{name:"string.trim"}),qr=M(/^[A-Z]*$/,"only uppercase letters"),Ed=I.module({root:R({in:"string",morphs:t=>t.toUpperCase(),declaredOut:qr}),preformatted:qr},{name:"string.upper"}),Dd=t=>URL.canParse(t),Er=R({domain:"string",predicate:{meta:"a URL string",predicate:Dd},meta:{format:"uri"}}),Kd=I.module({root:Er,parse:R({declaredIn:Er,in:"string",morphs:(t,e)=>{try{return new URL(t)}catch{return e.error("a URL string")}},declaredOut:R(URL)})},{name:"string.url"}),Ld=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"}),Bd=I.module({root:$.string,alpha:M(/^[A-Za-z]*$/,"only letters"),alphanumeric:M(/^[\dA-Za-z]*$/,"only letters and digits 0-9"),hex:sd,base64:od,capitalize:ad,creditCard:ud,date:md,digits:M(/^\d*$/,"only digits 0-9"),email:gd,integer:Ls,ip:$d,json:xd,lower:kd,normalize:Od,numeric:Rd,regex:Cd,semver:Pd,trim:qd,upper:Ed,url:Kd,uuid:Ld},{name:"string"}),jd=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}),Fd=I.module({root:$.unknown,any:$.unknown},{name:"unknown"}),Ud=I.module({root:$.jsonObject,stringify:Cn("morph",{in:$.jsonObject,morphs:t=>JSON.stringify(t),declaredOut:$.string})},{name:"object.json"}),zd=I.module({root:$.object,json:Ud},{name:"object"});class Td extends ne{description='instantiate an object from an index signature and corresponding value type like `Record("string", "number")`'}const _d=ae(["K",$.key],"V")(t=>({domain:"object",index:{signature:t.K,value:t.V}}),Td);class Jd extends ne{description='pick a set of properties from an object like `Pick(User, "name | age")`'}const Vd=ae(["T",$.object],["K",$.key])(t=>t.T.pick(t.K),Jd);class Gd extends ne{description='omit a set of properties from an object like `Omit(User, "age")`'}const Wd=ae(["T",$.object],["K",$.key])(t=>t.T.omit(t.K),Gd);class Hd extends ne{description="make all named properties of an object optional like `Partial(User)`"}const Zd=ae(["T",$.object])(t=>t.T.partial(),Hd);class Yd extends ne{description="make all named properties of an object required like `Required(User)`"}const Qd=ae(["T",$.object])(t=>t.T.required(),Yd);class Xd extends ne{description='exclude branches of a union like `Exclude("boolean", "true")`'}const eh=ae("T","U")(t=>t.T.exclude(t.U),Xd);class th extends ne{description='extract branches of a union like `Extract("0 | false | 1", "number")`'}const nh=ae("T","U")(t=>t.T.extract(t.U),th),rh=I.module({Exclude:eh,Extract:nh,Omit:Wd,Partial:Zd,Pick:Vd,Record:_d,Required:Qd}),fe=Ju({...jd,...rh,...nd,...Wu,string:Bd,number:Ks,object:zd,unknown:Fd},{prereducedAliases:!0,name:"ark"}),B=fe.export();Object.assign(We.ambient,B);We.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 Fs=Object.assign(fe.type,We.typeAttachments);fe.match;fe.fn;fe.generic;fe.schema;fe.define;fe.declare;const ih="/api/plugin/content-loading-plugin",Us=ih,zs=yo(import.meta.url);async function sh(t){const e=`${Us}${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 Ts=t=>t!=null&&(t=Object.getPrototypeOf(t),t===Array.prototype||t===Object.prototype);function _s(t,e,n){for(const[r,i]of Object.entries(e)){const s=`${n}.${r}`;t[s]=i,Ts(i)&&_s(t,i,s)}}function oh(t){const e={...t};for(const[n,r]of Object.entries(t))Ts(r)&&_s(e,r,n);return e}const ah=(t,e)=>{if(e)for(const[n,r]of Object.entries(e))t=t.replace(new RegExp(`{{\\s*${n}\\s*}}`,"g"),r);return t},ch=t=>t;function lh(t,e=ch){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 uh={nothingMessage:"Keine Ergebnisse gefunden für",search:"Suchen"},dh={loadMore:"Mehr laden"},hh={searchApp:uh,infiniteLoading:dh},ph={nothingMessage:"No results found for",search:"Search"},fh={loadMore:"Load more"},mh={searchApp:ph,infiniteLoading:fh},gh={nothingMessage:"No se encontraron resultados para",search:"Buscar"},yh={loadMore:"Cargar más"},bh={searchApp:gh,infiniteLoading:yh},$h={nothingMessage:"Aucun résultat trouvé pour",search:"Rechercher"},wh={loadMore:"Charger la suite"},vh={searchApp:$h,infiniteLoading:wh},xh={nothingMessage:"Nessun risultato trovato per",search:"Cerca"},kh={loadMore:"Carica altro"},Ah={searchApp:xh,infiniteLoading:kh},Ih={nothingMessage:"Nenhum resultado encontrado para",search:"Pesquisar"},Sh={loadMore:"Carregar mais"},Nh={searchApp:Ih,infiniteLoading:Sh},Dr={en:mh,fr:vh,es:bh,de:hh,it:Ah,pt:Nh};function Et(t){const e=Z(()=>{const r=t in Dr?t:"en";return oh(Dr[r])});return{t:lh(e,ah)}}var Oh=V('<button class="PaInfiniteLoading-loadButton PaButton"type=button>'),Rh=V("<div class=PaInfiniteLoading-loadMore>"),Ch=V('<img class="PaInfiniteLoading-loading PaLoading"width=50 height=50 alt=…>');const Mh=Fs({"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 Ph(t,{language:e}){const{templateName:n,offset:r,total:i,limit:s,parentDocumentId:o,sorting:a,termNodeId:c,labeledWith:l}=Mh.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");qh({language:e,limit:s,parentDocumentId:o,root:t,offset:r,total:i,sorting:a,labeledWith:c!==void 0&&l?{termNodeId:c,fieldName:l}:void 0,templateName:n})}}function qh({language:t,limit:e,root:n,offset:r,total:i,parentDocumentId:s,sorting:o,templateName:a,labeledWith:c}){const{t:l}=Et(t);let u=r;if(u>=i)return;const h=(()=>{var f=Oh();return f.$$click=v,J(f,()=>l("infiniteLoading.loadMore")),f})(),m=(()=>{var f=Rh();return J(f,h),f})(),y=(()=>{var f=Ch();return kt(f,"src",`${zs}/spinner.svg`),f})();n.appendChild(m);async function v(){n.appendChild(y);const f=await Eh({limit:e,newOffset:u,parentDocumentId:s,sorting:o,labeledWith:c,templateName:a});for(const w of f)n.insertBefore(w,m);u+=e,u>=i&&m.remove(),y.remove()}}async function Eh({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(([l,u])=>`${l}=${encodeURIComponent(u)}`).join("&")}`,c=await sh(a);return hn(c)}fn(["click"]);function Js(){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:c=>{c&&(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}ze||qn();function Dh(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 Lh=/^(?:[a-z0-9]+:)?\/\//i,Bh=/^\/+|(\/)\/+$/g,Vs="http://sr";function Je(t,e=!1){const n=t.replace(Bh,"$1");return n?e||/^[?#]/.test(n)?n:"/"+n:""}function ht(t,e,n){if(Lh.test(e))return;const r=Je(t),i=n&&Je(n);let s="";return!i||e.startsWith("/")?s=r:i.toLowerCase().indexOf(r.toLowerCase())!==0?s=r+i:s=i,(s||"/")+Je(e,!s)}function jh(t,e){if(t==null)throw new Error(e);return t}function Fh(t,e){return Je(t).replace(/\/*(\*.*)?$/g,"")+Je(e)}function Gs(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 Uh(t,e,n){const[r,i]=t.split("/*",2),s=r.split("/").filter(Boolean),o=s.length;return a=>{const c=a.split("/").filter(Boolean),l=c.length-o;if(l<0||l>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],v=y[0]===":",f=v?c[m]:c[m].toLowerCase(),w=v?y.slice(1):y.toLowerCase();if(v&&Tt(f,h(w)))u.params[w]=f;else if(v||!Tt(f,w))return null;u.path+=`/${f}`}if(i){const m=l?c.slice(-l).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 zh(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 Ws(t){const e=new Map,n=Ur();return new Proxy({},{get(r,i){return e.has(i)||zr(n,()=>e.set(i,Z(()=>t()[i]))),e.get(i)()},getOwnPropertyDescriptor(){return{enumerable:!0,configurable:!0}},ownKeys(){return Reflect.ownKeys(t())},has(r,i){return i in t()}})}function Hs(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 Hs(r).reduce((s,o)=>[...s,...i.map(a=>a+o)],[])}const Th=100,Zs=_r(),Ys=_r(),En=()=>jh(Tr(Zs),"<A> and 'use' router primitives can be only used inside a Route."),Qs=()=>En().navigatorFactory(),_h=()=>En().location,Jh=()=>En().params;function Vh(t,e=""){const{component:n,preload:r,load:i,children:s,info:o}=t,a=!s||Array.isArray(s)&&!s.length,c={key:t,component:n,preload:r||i,info:o};return Xs(t.path).reduce((l,u)=>{for(const h of Hs(u)){const m=Fh(e,h);let y=a?m:m.split("/*",1)[0];y=y.split("/").map(v=>v.startsWith(":")||v.startsWith("*")?v:encodeURIComponent(v)).join("/"),l.push({...c,originalPath:u,pattern:y,matcher:Uh(y,!a,t.matchFilters)})}return l},[])}function Gh(t,e=0){return{routes:t,score:zh(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 Xs(t){return Array.isArray(t)?t:[t]}function eo(t,e="",n=[],r=[]){const i=Xs(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 c=Vh(a,e);for(const l of c){n.push(l);const u=Array.isArray(a.children)&&a.children.length===0;if(a.children&&!u)eo(a.children,l.pattern,n,r);else{const h=Gh([...n],r.length);r.push(h)}n.pop()}}}return n.length?r:r.sort((s,o)=>o.score-s.score)}function Ve(t,e){for(let n=0,r=t.length;n<r;n++){const i=t[n].matcher(e);if(i)return i}return[]}function Wh(t,e,n){const r=new URL(Vs),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),c=()=>"",l=He(o,()=>Gs(i()));return{get pathname(){return s()},get search(){return o()},get hash(){return a()},get state(){return e()},get key(){return c()},query:n?n(l):Ws(l)}}let me;function Hh(){return me}function Zh(t,e,n,r={}){const{signal:[i,s],utils:o={}}=t,a=o.parsePath||(k=>k),c=o.renderPath||(k=>k),l=o.beforeLeave||Js(),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 v=(k,C)=>{C.value===f()&&C.state===x()||(y===void 0&&m(!0),me=k,y=C,lo(()=>{y===C&&(w(y.value),A(y.state),uo(),ze||H[1](_=>_.filter(we=>we.pending)))}).finally(()=>{y===C&&ho(()=>{me=void 0,k==="navigate"&&io(y),m(!1),y=void 0})}))},[f,w]=Y(i().value),[x,A]=Y(i().state),P=Wh(f,x,o.queryWrapper),G=[],H=Y(ze?oo():[]),je=Z(()=>typeof r.transformUrl=="function"?Ve(e(),r.transformUrl(P.pathname)):Ve(e(),P.pathname)),Dn=()=>{const k=je(),C={};for(let _=0;_<k.length;_++)Object.assign(C,k[_].params);return C},to=o.paramsWrapper?o.paramsWrapper(Dn,e):Ws(Dn),Kn={pattern:u,path:()=>u,outlet:()=>null,resolvePath(k){return ht(u,k)}};return co(He(i,k=>v("native",k),{defer:!0})),{base:Kn,location:P,params:to,isRouting:h,renderPath:c,parsePath:a,navigatorFactory:ro,matches:je,beforeLeave:l,preloadRoute:so,singleFlight:r.singleFlight===void 0?!0:r.singleFlight,submissions:H};function no(k,C,_){Jr(()=>{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>=Th)throw new Error("Too many redirects");const Ln=f();if(ke!==Ln||xe!==x())if(ze){const Bn=Jt();Bn&&(Bn.response={status:302,headers:new Headers({Location:ke})}),s({value:ke,replace:st,scroll:ot,state:xe})}else l.confirm(ke,_)&&(G.push({value:Ln,replace:st,scroll:ot,state:x()}),v("navigate",{value:ke,state:xe}))})}function ro(k){return k=k||Tr(Ys)||Kn,(C,_)=>no(k,C,_)}function io(k){const C=G[0];C&&(s({...k,replace:C.replace,scroll:C.scroll}),G.length=0)}function so(k,C){const _=Ve(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&&zr(n(),()=>xe({params:ot,location:{pathname:k.pathname,search:k.search,hash:k.hash,query:Gs(k),state:null,key:""},intent:"preload"}))}me=we}function oo(){const k=Jt();return k&&k.router&&k.router.submission?[k.router.submission]:[]}}function Yh(t,e,n,r){const{base:i,location:s,params:o}=t,{pattern:a,component:c,preload:l}=r().route,u=Z(()=>r().path);c&&c.preload&&c.preload();const h=l?l({params:o,location:s,intent:me||"initial"}):void 0;return{parent:e,pattern:a,path:u,outlet:()=>c?po(c,{params:o,location:s,data:h,get children(){return n()}}):n(),resolvePath(y){return ht(i.path(),y,u())}}}const Qh=t=>e=>{const{base:n}=e,r=Vr(()=>e.children),i=Z(()=>eo(r(),e.base||""));let s;const o=Zh(t,i,()=>s,{base:n,singleFlight:e.singleFlight,transformUrl:e.transformUrl});return t.create&&t.create(o),E(Zs.Provider,{value:o,get children(){return E(Xh,{routerState:o,get root(){return e.root},get preload(){return e.rootPreload||e.rootLoad},get children(){return[Vt(()=>(s=Ur())&&null),E(ep,{routerState:o,get branches(){return i()}})]}})}})};function Xh(t){const e=t.routerState.location,n=t.routerState.params,r=Z(()=>t.preload&&Jr(()=>{t.preload({params:n,location:e,intent:Hh()||"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 ep(t){if(ze){const i=Jt();if(i&&i.router&&i.router.dataOnly){tp(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(He(t.routerState.matches,(i,s,o)=>{let a=s&&i.length===s.length;const c=[];for(let l=0,u=i.length;l<u;l++){const h=s&&s[l],m=i[l];o&&h&&m.route.key===h.route.key?c[l]=o[l]:(a=!1,e[l]&&e[l](),mo(y=>{e[l]=y,c[l]=Yh(t.routerState,c[l-1]||t.routerState.base,Kr(()=>r()[l+1]),()=>{const v=t.routerState.matches();return v[l]??v[0]})}))}return e.splice(i.length).forEach(l=>l()),o&&a?o:(n=c[0],c)}));return Kr(()=>r()&&n)()}const Kr=t=>()=>E(Se,{get when(){return t()},keyed:!0,children:e=>E(Ys.Provider,{value:e,get children(){return e.outlet()}})}),_t=t=>{const e=Vr(()=>t.children);return fo(t,{get children(){return e()}})};function tp(t,e,n){const r=new URL(t.request.url),i=Ve(n,new URL(t.router.previousUrl||t.request.url).pathname),s=Ve(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:c}=s[o];a.preload&&a.preload({params:c,location:e.location,intent:"preload"})}}function np([t,e],n,r){return[t,r?i=>e(r(i)):e]}function rp(t){let e=!1;const n=i=>typeof i=="string"?{value:i}:i,r=np(Y(n(t.get()),{equals:(i,s)=>i.value===s.value&&i.state===s.state}),void 0,i=>(!e&&t.set(i),Dt.registry&&!Dt.done&&(Dt.done=!0),i));return t.init&&Gr(t.init((i=t.get())=>{e=!0,r[1](n(i)),e=!1})),Qh({signal:r,create:t.create,utils:t.utils})}function ip(t,e,n){return t.addEventListener(e,n),()=>t.removeEventListener(e,n)}function sp(t,e){const n=t&&document.getElementById(t);n?n.scrollIntoView():e&&window.scrollTo(0,0)}const op=new Map;function ap(t=!0,e=!1,n="/_server",r){return i=>{const s=i.base.path(),o=i.navigatorFactory(i.base);let a,c;function l(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(je=>je instanceof Node&&je.nodeName.toUpperCase()==="A");if(!w||e&&!w.hasAttribute("link"))return;const x=l(w),A=x?w.href.baseVal:w.href;if((x?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=x?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[x,A]=w,P=i.parsePath(A.pathname+A.search+A.hash),G=x.getAttribute("state");f.preventDefault(),o(P,{resolve:!1,replace:x.hasAttribute("replace"),scroll:!x.hasAttribute("noscroll"),state:G?JSON.parse(G):void 0})}function m(f){const w=u(f);if(!w)return;const[x,A]=w;i.preloadRoute(A,x.getAttribute("preload")!=="false")}function y(f){clearTimeout(a);const w=u(f);if(!w)return c=null;const[x,A]=w;c!==x&&(a=setTimeout(()=>{i.preloadRoute(A,x.getAttribute("preload")!=="false"),c=x},20))}function v(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,Vs);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 x=op.get(w);if(x){f.preventDefault();const A=new FormData(f.target,f.submitter);x.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",v),Gr(()=>{document.removeEventListener("click",h),t&&(document.removeEventListener("mousemove",y),document.removeEventListener("focusin",m),document.removeEventListener("touchstart",m)),document.removeEventListener("submit",v)})}}function cp(t){const e=t.replace(/^.*?#/,"");if(!e.startsWith("/")){const[,n="/"]=window.location.hash.split("#",2);return`${n}#${e}`}return e}function lp(t){const e=()=>window.location.hash.slice(1),n=Js();return rp({get:e,set({value:r,replace:i,scroll:s,state:o}){i?window.history.replaceState(Dh(o),"","#"+r):window.history.pushState(o,"","#"+r);const a=r.indexOf("#"),c=a>=0?r.slice(a+1):"";sp(c,s),qn()},init:r=>ip(window,"hashchange",Kh(r,i=>!n.confirm(i&&i<0?i:e()))),create:ap(t.preload,t.explicitLinks,t.actionBase),utils:{go:r=>window.history.go(r),renderPath:r=>`#${r}`,parsePath:cp,beforeLeave:n}})(t)}function up(t){const e=Qs(),n=_h(),{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 Lr({language:t,text:e,limit:n,offset:r,templateName:i}){const s=`${Us}/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 c=await o.text();throw new Error(`API error (${o.status}): ${c}`)}return await o.json()}var dp=V('<form class=PaSearchApp-form><input class="PaSearchApp-input PaInput"type=search><button class="PaSearchApp-searchButton PaButton"type=submit>');function hp(t){const e=Qs(),[n,r]=Y(t.value??""),{t:i}=Et(t.language);Wr(He(()=>t.value,()=>r(t.value??"")));const s=async o=>{o.preventDefault(),e(`/q/${encodeURIComponent(n())}`)};return(()=>{var o=dp(),a=o.firstChild,c=a.nextSibling;return o.addEventListener("submit",s),a.addEventListener("change",l=>r(l.currentTarget.value)),J(c,()=>i("searchApp.search")),pt(()=>kt(a,"placeholder",i("searchApp.search"))),pt(()=>a.value=n()),o})()}var pp=V("<div class=PaSearchApp-loadMore>"),fp=V("<div class=PaSearchApp-results>"),mp=V("<div class=PaSearchApp>"),gp=V("<div class=PaSearchApp-nothing> <span class=PaSearchApp-quote>"),yp=V('<img class="PaSearchApp-loading PaLoading"width=80 height=80 alt=…>'),bp=V('<button class="PaSearchApp-loadButton PaButton"type=button>');function Br({language:t,limit:e,templateName:n}){const{t:r}=Et(t),i=Jh(),[s,o]=Y([]),[a,c]=Y(-1),[l,u]=Y(0),[h,m]=Y(!1);Wr(He(()=>i.searchString,y));async function y(){if(i.searchString){m(!0);try{o([]),u(0),c(-1);const f=await Lr({language:t,text:decodeURIComponent(i.searchString),limit:e,offset:l(),templateName:n});if(c(f.total),u(l()+e),!f.html)return;o(hn(f.html))}finally{m(!1)}}}async function v(){if(!i.searchString)return;const f=a();if(!(f===-1||l()>=f)){m(!0);try{const w=await Lr({language:t,text:decodeURIComponent(i.searchString),limit:e,offset:l(),templateName:n});if(!w.html)return;o([...s(),...hn(w.html)]),u(l()+e)}finally{m(!1)}}}return(()=>{var f=mp();return J(f,E(hp,{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=fp();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 x=gp(),A=x.firstChild,P=A.nextSibling;return J(x,()=>r("searchApp.nothingMessage"),A),J(P,()=>i.searchString),x})()},get children(){return s()}})}}),null),J(w,E(Se,{get when(){return a()===-1||h()||l()<a()},get children(){var x=pp();return J(x,(()=>{var A=Vt(()=>!!h());return()=>A()?(()=>{var P=yp();return kt(P,"src",`${zs}/spinner.svg`),P})():(()=>{var P=bp();return P.$$click=v,J(P,()=>r("infiniteLoading.loadMore")),P})()})()),x}}),null),w}}),null),f})()}fn(["click"]);const $p=Fs({"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 wp(t,{language:e}){if(!e)throw new Error("Missing language");const{limit:n,templateName:r}=$p.assert(t.dataset);n===void 0||r===void 0||Fr(()=>E(lp,{explicitLinks:!0,get children(){return[E(_t,{path:"/",component:()=>E(up,{href:"/q"})}),E(_t,{path:"/q",component:()=>E(Br,{language:e,templateName:r,limit:n})}),E(_t,{path:"/q/:searchString",component:()=>E(Br,{language:e,templateName:r,limit:n})})]}}),t)}var vp=V('<input class="PaSearchOpener-input PaInput"type=search required>'),xp=V('<form class=PaSearchOpener><button class="PaSearchOpener-button PaButton"type=submit>');function kp({searchURL:t,language:e}){const[n,r]=Y(""),{t:i}=Et(e),s=(()=>{var a=vp();return a.addEventListener("change",c=>r(c.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=xp(),c=a.firstChild;return a.addEventListener("submit",o),J(a,s,c),J(c,()=>i("searchApp.search")),a})()}var Ap=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 Ip({searchIconColor:t,language:e,searchURL:n}){const r=(()=>{var o=Ap(),a=o.firstChild;return ao(a,"fill",t),o})(),i=E(kp,{searchURL:n,language:e});return go({openButton:r,dialogContent:i,modalClass:"_paSearchOpener",loadCss:!0}).on("open",()=>{i.querySelector("input")?.focus()}),r}function Sp(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");Fr(()=>E(Ip,{language:e,searchURL:n,searchIconColor:r}),t)}document.readyState==="loading"?document.addEventListener("DOMContentLoaded",jr):jr();function jr(){const t=document.documentElement.lang,e={paSearchOpener:Sp,paSearchApp:wp,paInfiniteLoading:Ph},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 ze,getRequestEvent as Jt,createComponent as E,memo as Vt,effect as pt,render as Fr,setStyleProperty as ao}from"https://cdn.jsdelivr.net/npm/solid-js@1.9.10/web/+esm";import{createMemo as Z,getOwner as Ur,runWithOwner as zr,useContext as Tr,createContext as _r,createSignal as Y,createRenderEffect as co,on as He,startTransition as lo,resetErrorBoundaries as uo,batch as ho,untrack as Jr,createComponent as po,children as Vr,mergeProps as fo,Show as Se,createRoot as mo,onCleanup as Gr,sharedConfig as Dt,createEffect as Wr}from"https://cdn.jsdelivr.net/npm/solid-js@1.9.10/+esm";import go from"https://cdn.jsdelivr.net/npm/@paroicms/tiny-modal@0.7.8/+esm";function yo(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 Ze=t=>Array.isArray(t)?t:[t],bo=(t,e)=>{const n=[[],[]];for(const r of t)e(r)?n[0].push(r):n[1].push(r);return n},Hr=Array,le=(t,e)=>t.includes(e),$o=(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?Ze(e):t.concat(e),wo=(...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 Ze(e))t.some(s=>r(s,i))||t.push(i);return t},vo=(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"},xo={...re,function:"a function"};class ko extends Error{}const K=t=>Me(t,ko),Me=(t,e=Error)=>{throw new e(t)};class Ao extends Error{name="ParseError"}const d=t=>Me(t,Ao),Zr=t=>` ${t}`,Io="​",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 c=Array.isArray(a[0])||a.length===0?a:[a];for(const[l,u]of c)typeof l=="object"?n[l.group]=N(n[l.group],u):n[l]=u}return i?Object.values(n):n},Yr=Object.entries,te=(t,e)=>t in e,mn=(t,e)=>e in t;class So{constructor(e){Object.assign(this,e)}}const No=class{};class Qr extends No{}const Oo=(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]},Xr=(t,e)=>Oo(t,e)[1],Ye=t=>Object.keys(t).length===0,ft=t=>[...Object.entries(t),...Object.getOwnPropertySymbols(t).map(e=>[e,t[e]])],Ro=(t,e)=>Object.defineProperties(t,Object.getOwnPropertyDescriptors(e)),Co=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=Zr(`unset${Io}`),Mo=t=>Object.values(t).filter(e=>typeof e=="number"?!0:typeof t[e]!="number"),ei={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},ti=globalThis.File??Blob,ni={ArrayBuffer:ArrayBuffer,Blob:Blob,File:ti,FormData:FormData,Headers:Headers,Request:Request,Response:Response,URL:URL},Po={Int8Array:Int8Array,Uint8Array:Uint8Array,Uint8ClampedArray:Uint8ClampedArray,Int16Array:Int16Array,Uint16Array:Uint16Array,Int32Array:Int32Array,Uint32Array:Uint32Array,Float32Array:Float32Array,Float64Array:Float64Array,BigInt64Array:BigInt64Array,BigUint64Array:BigUint64Array},Pe={...ei,...ni,...Po,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,qo={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"},Eo={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"},Do={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={...qo,...Eo,...Do},yn=t=>{const e=Object(t).name??null;return e&&te(e,Pe)&&Pe[e]===t?e:null},jn=(t,e)=>{let n=t.prototype;for(;n!==null;){if(n===e.prototype)return!0;n=Object.getPrototypeOf(n)}return!1},Lo=t=>ri(t,new Map),ri=(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=ri(o.value,e))}}return Object.defineProperties(r,i),r},Bo=t=>{let e=ee;return()=>e===ee?e=t():e},At=t=>typeof t=="function"&&t.length===0,jo=class extends Function{constructor(...t){const e=t.slice(0,-1),n=t[t.length-1];try{super(...e,n)}catch(r){return K(`Encountered an unexpected error while compiling your definition:\n Message: ${r} \n Source: (${t.slice(0,-1)}) => {\n ${t[t.length-1]}\n }`)}}};class pe{constructor(e,...[n]){return Object.assign(Object.setPrototypeOf(e.bind(n?.bind??this),this.constructor.prototype),n?.attach)}}const Fo=Bo(()=>{try{return new Function("return false")()}catch{return!0}});class ne{constructor(){}}const Uo=()=>{try{return(((new Error).stack?.split(`\n`)[2]?.trim()||"").match(/\(?(.+?)(?::\d+:\d+)?\)?$/)?.[1]||"unknown").replace(/^file:\/\//,"")}catch{return"unknown"}},zo=globalThis.process?.env??{},To={fileName:Uo,env:zo},_o=t=>t[0].toUpperCase()+t.slice(1),ii=t=>new RegExp(Jo(t),typeof t=="string"?"":t.flags),Jo=t=>`^(?:${typeof t=="string"?t:t.source})$`,ue={negativeLookahead:t=>`(?!${t})`,nonCapturingGroup:t=>`(?:${t})`},Te="\\",It={" ":1,"\n":1,"\t":1},Vo=/^-0\.?0*$/.source,si=/[1-9]\d*/.source,Go=/\.\d+/.source,Wo=/\.\d*[1-9]/.source,oi=t=>ii(ue.negativeLookahead(Vo)+ue.nonCapturingGroup("-?"+ue.nonCapturingGroup(ue.nonCapturingGroup("0|"+si)+ue.nonCapturingGroup(t.decimalPattern)+"?")+(t.allowDecimalOnly?"|"+t.decimalPattern:"")+"?")),Fn=oi({decimalPattern:Wo,allowDecimalOnly:!1}),Ho=Fn.test.bind(Fn),Wt=oi({decimalPattern:Go,allowDecimalOnly:!0});Wt.test.bind(Wt);const Zo=/^-?\d*\.?\d*$/,Yo=t=>t.length!==0&&Zo.test(t),mt=ii(ue.negativeLookahead("^-0$")+"-?"+ue.nonCapturingGroup(ue.nonCapturingGroup("0|"+si))),Qo=mt.test.bind(mt),Ht=/^-?\d+$/,Xo=Ht.test.bind(Ht),ai={number:"a number",bigint:"a bigint",integer:"an integer"},ci=(t,e)=>`'${t}' was parsed as ${ai[e]} but could not be narrowed to a literal value. Avoid unnecessary leading or trailing zeros and other abnormal notation`,ea=(t,e)=>e==="number"?Ho(t):Qo(t),ta=(t,e)=>e==="number"?Number(t):Number.parseInt(t),na=(t,e)=>e==="number"?Yo(t):Xo(t),ra=(t,e)=>bn(t,"number",e),ia=(t,e)=>bn(t,"number",{...e,strict:!0}),sa=(t,e)=>bn(t,"integer",e),bn=(t,e,n)=>{const r=ta(t,e);return!Number.isNaN(r)&&na(t,e)?n?.strict?ea(t,e)?r:d(ci(t,e)):r:n?.errorOnFail?d(n?.errorOnFail===!0?`Failed to parse ${ai[e]} from '${t}'`:n?.errorOnFail):void 0},oa=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(ci(t,"bigint"))},aa="0.55.0",ca={version:aa,filename:To.fileName(),FileConstructor:ti},Qe=ca,Un=new Map,Kt=Object.create(null),Zt=t=>{const e=Un.get(t);if(e)return e;let n=la(t);return Kt[n]?n=`${n}${Kt[n]++}`:Kt[n]=1,Qe[n]=t,Un.set(t,n),n},Ge=t=>/^[$A-Z_a-z][\w$]*$/.test(t),la=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 Ge(t.name)?t.name:"fn";case"symbol":return t.description&&Ge(t.description)?t.description:"symbol"}return K(`Unexpected attempt to register serializable value of type ${Q(t)}`)},$n=t=>typeof t=="string"?JSON.stringify(t):typeof t=="bigint"?`${t}n`:`${t}`,ua=(t,e={})=>_e(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(_e(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 c=typeof o=="symbol"?qe.onSymbol(o):Ge(o)?o:JSON.stringify(o),l=gt(a,e,r);return`${r}${c}: ${l}`});return s.length===0?"{}":e?`{\n${s.join(`,\n`)}\n${n}}`:`{${s.join(", ")}}`}return t instanceof Date?Xe(t):"expression"in t&&typeof t.expression=="string"?t.expression:i},qe={onCycle:()=>"(cycle)",onSymbol:t=>`Symbol(${Zt(t)})`,onFunction:t=>`Function(${Zt(t)})`},_e=(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=>_e(o,e,i));if(r instanceof Date)return r.toDateString();const s={};for(const o in r)s[o]=_e(r[o],e,i);for(const o of Object.getOwnPropertySymbols(r))s[e.onSymbol?.(o)??o.toString()]=_e(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.replace(/\\/g,"\\\\");default:return t}},Xe=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 c=`${da[n]} ${r}, ${e}`;if(i===0&&s===0&&o===0&&a===0)return c;let l=t.toLocaleTimeString();const u=l.endsWith(" AM")||l.endsWith(" PM")?l.slice(-3):"";return u&&(l=l.slice(0,-u.length)),a?l+=`.${pa(a,3)}`:ha.test(l)&&(l=l.slice(0,-3)),`${l+u}, ${c}`},da=["January","February","March","April","May","June","July","August","September","October","November","December"],ha=/:\d\d:00$/,pa=(t,e)=>String(t).padStart(e,"0"),li=(t,e,...[n])=>{const r=n?.stringifySymbol??S;let i=t;switch(typeof e){case"string":i=Ge(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},et=(t,...e)=>t.reduce((n,r)=>li(n,r,...e),"");class ui extends Hr{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=et(this)}stringifyAncestors(){if(this.cache.stringifyAncestors)return this.cache.stringifyAncestors;let e="";const n=[e];for(const r of this)e=li(e,r),n.push(e);return this.cache.stringifyAncestors=n}}class di{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===Te)this.shift(),e(this,n)?n+=this.shift():this.lookahead===Te?n+=this.shift():n+=`${Te}${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 fa=(t,e)=>`Unmatched ${t}${e===""?"":` before ${e}`}`,hi=t=>`Missing ${t}`;let Yt="$ark",ma=2;for(;Yt in globalThis;)Yt=`$ark${ma++}`;const pi=Yt;globalThis[pi]=Qe;const p=Qe,ga=t=>`${pi}.${t}`,z=t=>ga(Zt(t));class fi extends Qr{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 mi(e,n)}index(e,n=!1){return gi(`${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 jo(...this.argNames,this.body)}}const De=t=>$e(t,"object")||typeof t=="symbol"?z(t):$n(t),mi=(t,e=!1)=>typeof t=="string"&&Ge(t)?`${e?"?":""}.${t}`:gi(ya(t),e),ya=t=>typeof t=="symbol"?z(t):JSON.stringify(t),gi=(t,e=!1)=>`${e?"?.":""}[${t}]`;class Lt extends fi{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 yi=t=>O(t,(e,n)=>[e,F(n)?[...n]:n]),ie=Zr("arkKind"),b=(t,e)=>t?.[ie]===e,U=t=>b(t,"root")||b(t,"constraint"),ba=["unit","proto","domain"],St=["required","optional","index","sequence"],bi=["pattern","divisor","exactLength","max","min","maxLength","minLength","before","after"],$i=[...bi,"structure","predicate"],wn=[...$i,...St],Nt=["alias","union","morph","unit","intersection","proto","domain"],$a=[...Nt,...wn],wi=O(wn,(t,e)=>[e,1]),wa=O([...St,"undeclared"],(t,e)=>[e,1]),vi=O($a,(t,e)=>[e,t]),ut=t=>typeof t=="string"&&t in vi,yt=t=>vi[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:De(t),Ot=t=>{let e="{ ";for(const[n,r]of Object.entries(t))e+=`${n}: ${De(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 va 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 xa={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:va,throw:(...t)=>{throw new L.Error(...t)},throwInternalOperandError:(t,e)=>K(`Unexpected JSON Schema input for ${t}: ${S(e)}`),defaultConfig:xa};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]=xi(t.toJsonSchema,e.toJsonSchema):ut(r)?n[r]={...t[r],...e[r]}:n[r]=e[r]}return n},xi=(t,e)=>{if(!t)return e??{};if(!e)return t;const n={...t};let r;for(r in e)r==="fallback"?n.fallback=ka(t.fallback,e.fallback):n[r]=e[r];return n},ka=(t,e)=>{t=zn(t),e=zn(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},zn=t=>typeof t=="function"?{default:t}:t??{};class Ee extends Qr{[ie]="error";path;data;nodeConfig;input;ctx;constructor({prefixPath:e,relativePath:n,...r},i){super(),this.input=r,this.ctx=i,Ro(this,r);const s=i.data;r.code==="union"&&(r.errors=r.errors.flatMap(a=>{const c=a.hasCode("union")?a.errors:[a];return!e&&!n?c:c.map(l=>l.transform(u=>({...u,path:wo(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 ui(...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 et(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 Hr{[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 Aa(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 Aa extends Error{name="TraversalError";constructor(e){e.length===1?super(e.summary):super(`\n`+e.map(n=>` • ${Ia(n)}`).join(`\n`)),Object.defineProperty(this,"arkErrors",{value:e,enumerable:!1})}}const Ia=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 et(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[this.branches.length-1]}queueMorphs(e){const n={path:new ui(...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[e.length-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 ki 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)=>Ra(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(c=>Ai(c,a))){this.flatRefs.push(a);for(const c of a.node.branches)(c.hasKind("morph")||c.hasKind("intersection")&&c.structure?.structuralMorph!==void 0)&&this.flatMorphs.push({path:a.path,propString:a.propString,node:c})}}}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,K(`Unexpected rootApplyStrategy ${this.rootApplyStrategy}`)}}compiledMeta=Oa(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(ba,this.kind)}isConstraint(){return le(wn,this.kind)}isStructural(){return le(St,this.kind)}isRefinement(){return le($i,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=Fe.normalize(e);return this._select(n)}_select(e){let n=Fe.applyBoundary[e.boundary??"references"](this);return e.kind&&(n=n.filter(r=>r.kind===e.kind)),e.where&&(n=n.filter(e.where)),Fe.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 v=m._transform(e,n);return v?[u,v]:[]}if(m.length===0)return[u,h];const y=m.flatMap(v=>v._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 c=Object.keys(a);return(c.length===0||c.length===1&&c[0]==="meta")&&!Ye(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=Fe.normalize(n),i=typeof e=="string"?(c,l)=>({...l,meta:{...l.meta,description:e}}):typeof e=="function"?(c,l)=>({...l,meta:e(l.meta)}):(c,l)=>({...l,meta:{...l.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&&Ze(s),a=r.boundary==="child"?(c,l)=>l.root.children.includes(c):r.boundary==="shallow"?c=>c.kind!=="structure":()=>!0;return this.$.finalize(this.transform(i,{shouldTransform:a,selected:o}))}}const Fe={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(Tn(e,n)),t),find:t=>t[0],assertFind:(t,e,n)=>(t.length===0&&Me(Tn(e,n)),t[0])},normalize:t=>typeof t=="function"?{boundary:"references",method:"filter",where:t}:typeof t=="string"?te(t,Fe.applyBoundary)?{method:"filter",boundary:t}:{boundary:"references",method:"filter",kind:t}:{boundary:"references",method:"filter",...t}},Tn=(t,e)=>`${t} had no references matching ${S(e)}.`,Sa=t=>et(t,{stringifyNonKey:e=>e.expression}),Na=/"(\$ark\.[^"]+)"/g,Oa=t=>JSON.stringify(t).replace(Na,"$1"),de=(t,e)=>({path:t,node:e,propString:Sa(t)}),Ai=(t,e)=>t.propString===e.propString&&t.node.equals(e.node),_n=(t,e)=>ye(t,e,{isEqual:Ai}),Ra=(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=et(e);return Ii(`Intersection${i&&` at ${i}`} of ${Jn(n,r)}`)}return`The following intersections result in unsatisfiable types:\n• ${this.map(({path:e,l:n,r:r})=>`${e}: ${Jn(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 Jn=(t,e)=>`${Xt(t)} and ${Xt(e)}`,Xt=t=>U(t)?t.expression:F(t)?t.map(Xt).join(" | ")||"never":String(t),Ii=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 c=Ae[a],l=c instanceof g?c.invert():c;return Ae[i]=l,l}}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)?Ca(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}},Ca=(t,e,n)=>t.includesTransform||e.includesTransform?n.invert?Vn(e,t,n):Vn(t,e,n):tn(t,e,n),Vn=(t,e,n)=>t.distribute(r=>Ma(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)}),Ma=(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 ki{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,Pa(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 K(`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 wi?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),Pa=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 K(`Unexpected intersection of closed refinements of kind ${n.kind}`);e[n.kind]=n}return e},qa=(...t)=>d(Ea(...t)),Ea=(t,e,n)=>{const r=n.hasKind("morph")?"a morph":n.isUnknown()?"unknown":n.exclude(e).defaultShortDescription;return`${_o(t)} operand must be ${e.description} (was ${r})`},Da=(t,e,n)=>new wt(t,e,n,n,null);class Si 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,(c,l)=>{const u=this.arg$.parse(o[c]);return u.extends(this.constraints[c])||d(Ka(l,this.constraints[c].expression,u.expression)),[l,u]});if(this.defIsLazy()){const c=this.bodyDef(a);return this.$.parse(c)}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 Si}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:ua(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})`,La=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 Ba 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 Ni={implementation:La,Node:Ba},ja=q({kind:"divisor",collapsibleKey:"rule",keys:{rule:{parse:t=>Number.isInteger(t)?t:d(Ua(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/za(t.rule,e.rule))})},obviatesBasisDescription:!0});class Fa 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 Oi={implementation:ja,Node:Fa},Ua=t=>`divisor must be an integer (was ${t})`,za=(t,e)=>{let n,r=t,i=e;for(;i!==0;)n=i,i=r%i,r=n;return r};class Le extends Rt{boundOperandKind=Va[this.kind];compiledActual=this.boundOperandKind==="value"?"data":this.boundOperandKind==="length"?"data.length":"data.valueOf()";comparator=Ga(this.kind,this.exclusive);numericLimit=this.rule.valueOf();expression=`${this.comparator} ${this.rule}`;compiledCondition=`${this.compiledActual} ${this.comparator} ${this.numericLimit}`;compiledNegation=`${this.compiledActual} ${Ta[this.comparator]} ${this.numericLimit}`;stringLimit=this.boundOperandKind==="date"?Wa(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 Ta={"<":">=","<=":">",">":"<=",">=":"<"},_a={min:"max",minLength:"maxLength",after:"before"},Ri={parse:t=>t||void 0},Ci=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},Mi=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},Pi=t=>typeof t=="string"||typeof t=="number"?new Date(t):t,Ja=(t,e)=>`${t} bound must be a positive integer (was ${e})`,xn=t=>e=>((!Number.isInteger(e)||e<0)&&d(Ja(t,e)),e),Va={min:"value",max:"value",minLength:"length",maxLength:"length",after:"date",before:"date"},Ga=(t,e)=>`${te(t,_a)?">":"<"}${e?"":"="}`,Wa=t=>typeof t=="string"?t:new Date(t).toLocaleString(),Ha=t=>`Bounded expression ${t} must be exactly one of number, string, Array, or Date`,Za=q({kind:"after",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{parse:Pi,serialize:t=>t.toISOString()}},normalize:Mi("after"),defaults:{description:t=>`${t.collapsibleLimitString} or later`,actual:Xe},intersections:{after:(t,e)=>t.isStricterThan(e)?t:e}});class Ya extends Le{impliedBasis=p.intrinsic.Date.internal;collapsibleLimitString=Xe(this.rule);traverseAllows=e=>e>=this.rule;reduceJsonSchema(e,n){return n.fallback.date({code:"date",base:e,after:this.rule})}}const qi={implementation:Za,Node:Ya},Qa=q({kind:"before",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{parse:Pi,serialize:t=>t.toISOString()}},normalize:Mi("before"),defaults:{description:t=>`${t.collapsibleLimitString} or earlier`,actual:Xe},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 Xa extends Le{collapsibleLimitString=Xe(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 Ei={implementation:Qa,Node:Xa},ec=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 tc 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 Di={implementation:ec,Node:tc},nc=q({kind:"max",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{},exclusive:Ri},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 rc extends Le{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:nc,Node:rc},ic=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:Ci("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 sc extends Le{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 Li={implementation:ic,Node:sc},oc=q({kind:"min",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{},exclusive:Ri},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 ac extends Le{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 Bi={implementation:oc,Node:ac},cc=q({kind:"minLength",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{parse:xn("minLength")}},reduce:t=>t.rule===0?p.intrinsic.unknown:void 0,normalize:Ci("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 lc extends Le{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 ji={implementation:cc,Node:lc},uc={min:Bi.implementation,max:Ki.implementation,minLength:ji.implementation,maxLength:Li.implementation,exactLength:Di.implementation,after:qi.implementation,before:Ei.implementation},dc={min:Bi.Node,max:Ki.Node,minLength:ji.Node,maxLength:Li.Node,exactLength:Di.Node,after:qi.Node,before:Ei.Node},hc=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 pc 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 Fi={implementation:hc,Node:pc},dt=(t,e)=>{const n=fc(t);return e&&!e.includes(n)?d(`Root of kind ${n} should be one of ${e}`):n},fc=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(Gn(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 wi)?"intersection":"proto"in t?"proto":"domain"in t?"domain":d(Gn(t))},Gn=t=>`${S(t)} is not a valid type schema`,Wn={},mc=t=>F(t)?t.map(e=>e.collapsibleJson):t.collapsibleJson,W={};p.nodesByRegisteredId=W;const Ui=t=>(Wn[t]??=0,`${t}${++Wn[t]}`),zi=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=Yr(s).sort(([l],[u])=>ut(l)?ut(u)?yt(l)-yt(u):1:ut(u)||l<u?-1:1).filter(([l,u])=>{if(l.startsWith("meta.")){const h=l.slice(5);return o[h]=u,!1}return!0});for(const l of a){const u=l[0],h=e.keys[u];if(!h)return d(`Key ${u} is not valid on ${t.kind} schema`);const m=h.parse?h.parse(l[1],t):l[1];m!==ee&&(m!==void 0||h.preserveUndefined)&&(r[u]=m)}if(e.reduce&&!t.prereduced){const l=e.reduce(r,t.$);if(l)return l instanceof g?l.throw():yc(l,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=Yr(n),c=[];let l={};for(const[x,A]of a){const P=o.keys[x],G=P.serialize??(P.child?mc:be);if(l[x]=G(A),P.child===!0){const H=A;F(H)?c.push(...H):c.push(H)}else typeof P.child=="function"&&c.push(...P.child(A))}o.finalizeInnerJson&&(l=o.finalizeInnerJson(l));let u={...l},h={};Ye(r)||(h=O(r,(x,A)=>[x,x==="examples"?A:be(A)]),u.meta=at(h,"description",!0)),l=at(l,o.collapsibleKey,!1);const m=JSON.stringify({kind:e,...l});u=at(u,o.collapsibleKey,!1);const y=at(u,o.collapsibleKey,!0),v=JSON.stringify({kind:e,...u});if(i.nodesByHash[v]&&!s)return i.nodesByHash[v];const f={id:t,kind:e,impl:o,inner:n,innerEntries:a,innerJson:l,innerHash:m,meta:r,metaJson:h,json:u,hash:v,collapsibleJson:y,children:c};if(e!=="intersection")for(const x in n)x!=="in"&&x!=="out"&&(f[x]=n[x]);const w=new kl[e](f,i);return i.nodesByHash[v]=w},gc=(t,e)=>t.id===e?t:(U(W[e])&&K(`Unexpected attempt to overwrite node id ${e}`),kn({id:e,kind:t.kind,inner:t.inner,meta:t.meta,$:t.$,ignoreCache:!0})),yc=(t,e,n)=>kn({id:Ui(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(_i(t.default,e.default)):t.default:e.hasDefault()?e.default:ee;return n.$.node("optional",{key:r,value:i,default:o})};class Ti extends Ke{required=this.kind==="required";optional=this.kind==="optional";impliedBasis=p.intrinsic.object.internal;serializedKey=De(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 _i=(t,e)=>`Invalid intersection of default values ${S(t)} & ${S(e)}`,bc=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 $c extends Ti{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",Xr(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=vc(this);defaultValueMorphRef=this.defaultValueMorph&&z(this.defaultValueMorph)}const An={implementation:bc,Node:$c},wc={},vc=t=>{if(!t.hasDefault())return;const e=`{${t.compiledKey}: ${t.value.id} = ${be(t.default)}}`;return wc[e]??=Ji(t.key,t.value,t.default)},Ji=(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(xc(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},xc=t=>`Non-primitive default ${t===null?"":typeof t=="number"?`for value at [${t}] `:`for ${De(t)} `}must be specified as a function like () => ({my: 'object'})`;class tt extends ki{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(kc):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=xi(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(Ii(`keyof ${this.expression}`)),this._keyof=this.$.finalize(e)}get props(){return this.branches.length!==1?d(Ac(this.expression)):[...this.applyStructuralOperation("props",[])[0]]}merge(e){const n=this.$.parseDefinition(e);return this.$.schema(n.distribute(r=>this.applyStructuralOperation("merge",[Hn(r)??d(Zn("merge",r.expression))])))}applyStructuralOperation(e,n){return this.distribute(r=>{if(r.equals(p.intrinsic.object)&&e!=="merge")return r;const i=Hn(r);if(i||d(Zn(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){if(this.isNever())return!0;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:K(`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 qa(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"?Xr(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 kc="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,Hn=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,Ac=t=>`Props cannot be extracted from a union. Use .distribute to extract props from each branch instead. Received:\n${t}`,Zn=(t,e)=>`${t} operand must be an object (was ${e})`,nt=(t,e)=>O(vn(t),(n,r)=>[r,e]),Ic=t=>typeof t=="string"?{reference:t}:t,Yn=t=>t instanceof g?p.intrinsic.never.internal:t,Sc=q({kind:"alias",hasAssociatedError:!1,collapsibleKey:"reference",keys:{reference:{serialize:t=>t.startsWith("$")?t:`$ark.${t}`},resolve:{}},normalize:Ic,defaults:{description:t=>t.reference},intersections:{alias:(t,e,n)=>n.$.lazilyResolve(()=>Yn(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(()=>Yn(j(t.resolution,e,n)),`${t.reference}${n.pipe?"=>":"&"}${e.id}`))}});class Nc 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(Oc(n.id,r));r.push(n.id),n=W[n.id]}return b(n,"root")?n:K(`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:K(`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 Oc=(t,e)=>`Alias '${t}' has a shallow resolution cycle: ${[...e,t].join("->")}`,Sn={implementation:Sc,Node:Nc};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 Rc=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 Cc 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:Rc,Node:Cc,writeBadAllowNanMessage:t=>`numberAllowsNaN may only be specified with domain "number" (was ${t})`},Mc=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,wa)?(r&&d(`Flattened structure key ${o} cannot be specified alongside a root 'structure' key.`),i[o]=a,[]):[o,a]);return(b(i,"constraint")||!Ye(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)=>Qn({},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.slice().sort((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)=>Qn(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 Pc extends tt{basis=this.inner.domain??this.inner.proto??null;prestructurals=[];refinements=this.children.filter(e=>e.isRefinement()?(le(bi,e.kind)&&this.prestructurals.push(e),!0):!1);structure=this.inner.structure;expression=qc(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[this.prestructurals.length-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[this.inner.predicate.length-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[this.prestructurals.length-1]),(this.structure||this.inner.predicate)&&e.returnIfFail()}if(this.structure&&(e.check(this.structure),this.inner.predicate&&e.returnIfFail()),this.inner.predicate){for(let n=0;n<this.inner.predicate.length-1;n++)e.check(this.inner.predicate[n]),e.returnIfFail();e.check(this.inner.predicate[this.inner.predicate.length-1])}}}const Vi={implementation:Mc,Node:Pc},qc=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"},Qn=(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}))},Ec=q({kind:"morph",hasAssociatedError:!1,keys:{in:{child:!0,parse:(t,e)=>e.$.parseSchema(t)},morphs:{parse:Ze,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 Dc extends tt{serializedMorphs=this.morphs.map(z);compiledMorphs=`[${this.serializedMorphs}]`;lastMorph=this.inner.morphs[this.inner.morphs.length-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 Gi={implementation:Ec,Node:Dc},Kc=(t,e)=>`The intersection of distinct morphs at a single path is indeterminate:\nLeft: ${t}\nRight: ${e}`,Lc=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:jn(t.proto,e.proto)?t:jn(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 Bc 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:Lc,Node:Bc,writeBadInvalidDateMessage:t=>`dateAllowsInvalid may only be specified with constructor Date (was ${t.name})`,writeInvalidSchemaMessage:t=>`instanceOf operand must be a function (was ${Q(t)})`},jc=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=Zc(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=vo(t.errors,"propString"),n=Object.entries(e).map(([r,i])=>{const s=[];for(const c of i)ye(s,c.expected);const o=Oe(s),a=i.every(c=>c.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(Qc(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 Fc 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?Gc(this.discriminant):null;expression=this.distribute(e=>e.nestableExpression,Hc);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)),c=JSON.stringify(o),l=this.discriminant.kind==="domain"?`${Jc}[${n}]`:`${Vc}(${n})`;e.line(`ctx.errorFromNodeContext({\n\tcode: "predicate",\n\texpected: ${c},\n\tactual: ${l},\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 c=this.branches[a],l=oe(o.rawIn,c.rawIn,o.$);if(l instanceof g)for(const u of l){if(!u.kind||u.optional)continue;let h,m;if(u.kind==="domain"){const v=u.l,f=u.r;h=`"${typeof v=="string"?v:v.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(v=>Ce(v.path,u.path)&&v.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?Tc(e,this.branches):e;if(!n.length)return null;const r=Uc(n,this),i={};for(const s in r.best.cases){const o=zc(r,s);if(o===null){i[s]=!0;continue}if(o.length===this.branches.length)return null;this.ordered&&o.sort((l,u)=>l.originalIndex-u.originalIndex);const a=o.map(l=>l.branch),c=a.length===1?a[0]:this.$.node("union",this.ordered?{branches:a,ordered:!0}:a);Object.assign(this.referencesById,c.referencesById),i[s]=c}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 Uc=(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:Wi(r.path)},s=e.branches.map((o,a)=>({originalIndex:a,branch:o}));return{best:r,location:i,defaultEntries:s,node:e}},zc=(t,e)=>{const n=t.best.cases[e],r=_c(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 c=Xn(t.node.branches[a.originalIndex],t.location);c===null?i=null:i?.push({originalIndex:a.originalIndex,branch:c})}else if(a.branch.hasKind("alias")&&r.hasKind("domain")&&r.domain==="object")i?.push(a);else{if(a.branch.rawIn.overlaps(r)){const c=Xn(a.branch,t.location);i?.push({originalIndex:a.originalIndex,branch:c})}s.push(a)}}return t.defaultEntries=s,i},Tc=(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 c=i[a];for(const l of o)for(const u of c)if(l>u&&e[l].overlaps(e[u]))return!1}}return!0}),_c=(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:[...$o(s).map(o=>({})),r]}:{domain:"object",required:[{key:s,value:r}]})}return r},Wi=t=>t.reduce((e,n)=>e+mi(n,!0),"data"),Jc=z(xo),Vc=z(S),Hi={implementation:jc,Node:Fc},Gc=t=>({kind:t.kind,path:t.path.map(e=>typeof e=="string"?e:De(e)),cases:O(t.cases,(e,n)=>[e,n===!0?n:n.hasKind("union")&&n.discriminantJson?n.discriminantJson:n.json])}),Wc={delimiter:" | ",finalDelimiter:" | "},Hc=t=>Oe(t,Wc),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 c=j(t[s],e[a],n);if(!(c instanceof g)){if(c.equals(t[s])){r[a].push(t[s]),o={};break}c.equals(e[a])?r[a]=null:o[a]=c}}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},Zc=({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||Yc(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])},Yc=(t,e)=>{!t.includesTransform&&!e.includesTransform||(Ce(t.shallowMorphs,e.shallowMorphs)||d(er(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(er(t.expression,e.expression)))},Xn=(t,e)=>t.transform((n,r)=>n==="domain"||n==="unit"?null:r,{shouldTransform:(n,r)=>{const i=Wi(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}}),er=(t,e)=>`An unordered union of a type including a morph and a type with overlapping input is indeterminate:\nLeft: ${t}\nRight: ${e}`,Qc=(t,e)=>`The intersection of two ordered unions is indeterminate:\nLeft: ${t}\nRight: ${e}`,Xc=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 el extends Nn{compiledValue=this.json.unit;serializedValue=typeof this.unit=="string"||this.unit instanceof Date?JSON.stringify(this.compiledValue):`${this.compiledValue}`;compiledCondition=tr(this.unit,this.serializedValue);compiledNegation=tr(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 Zi={implementation:Xc,Node:el},tr=(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}`},tl=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(il(n.expression));const r=n.branches.filter(i=>i.hasKind("unit"));return r.length?d(rl(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 nl 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 Yi={implementation:tl,Node:nl},rl=t=>`Index keys ${t.join(", ")} should be specified as named props.`,il=t=>`Indexed key definition '${t}' must be a string or symbol`,sl=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 ol extends Ti{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 Qi={implementation:sl,Node:ol},al=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(hl);if(t.optionals?.length||t.defaultables?.length)return d(es)}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[s.length-1]?.equals(t.variadic);)s.pop();if(s.length===0&&i.length===0)for(;r[r.length-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=Ue({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",nr(i[0].result)):n.$.node("union",i.map(s=>({proto:Array,sequence:nr(s.result)})))}}});class cl extends Ke{impliedBasis=p.intrinsic.Array.internal;tuple=dl(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 _n(this.flatRefs,this.prevariadic.flatMap((e,n)=>N(e.node.flatRefs.map(r=>de([`${n}`,...r.path],r.node)),de([`${n}`],e.node)))),_n(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=ul(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??K(`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 ll={},ul=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(Ji(i,s,o)),n+=`${i}: ${s.id} = ${be(o)}, `}return n+="]",ll[n]??=e},Xi={implementation:al,Node:cl},dl=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},nr=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),{}),es="A postfix required element cannot follow an optional or defaultable element",hl="A postfix element requires a variadic element",Ue=t=>{const[e,...n]=t.l,[r,...i]=t.r;if(!e||!r)return t;const s=n[n.length-1]?.kind==="postfix",o=i[i.length-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=Ue({...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=Ue({...t,fixedVariants:[],l:n.map(m=>({...m,kind:"prefix"}))});h.disjoint.length===0&&t.fixedVariants.push(h)}const c=j(e.node,r.node,t.ctx);if(c instanceof g)if(a==="prefix"||a==="postfix")t.disjoint.push(...c.withPrefixKey(a==="prefix"?t.result.length:`-${n.length+1}`,rr(e)&&rr(r)?"required":"optional")),t.result=[...t.result,{kind:a,node:p.intrinsic.never.internal}];else return a==="optionals"||a==="defaultables"?t:Ue({...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(_i(e.default,r.default)),t.result=[...t.result,{kind:a,node:c,default:e.kind==="defaultables"?e.default:r.kind==="defaultables"?r.default:K(`Unexpected defaultable intersection from ${e.kind} and ${r.kind} elements.`)}]):t.result=[...t.result,{kind:a,node:c}];const l=t.l.length,u=t.r.length;return(e.kind!=="variadic"||l>=u&&(r.kind==="variadic"||u===1))&&(t.l=n),(r.kind!=="variadic"||u>=l&&(e.kind==="variadic"||l===1))&&(t.r=i),Ue(t)},rr=t=>t.kind==="prefix"||t.kind==="postfix",ts=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??"{}"},pl=ts("description"),fl=ts("expression"),ir=(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},ml=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:pl},intersections:{structure:(t,e,n)=>{const r={...t.inner},i={...e.inner},s=new g;if(t.undeclared){const c=t.keyof();for(const l of e.requiredKeys)c.allows(l)||s.add("presence",p.intrinsic.never.internal,e.propsByKey[l].value,{path:[l]});i.optional&&(i.optional=i.optional.filter(l=>c.allows(l.key))),i.index&&(i.index=i.index.flatMap(l=>{if(l.signature.extends(c))return l;const u=oe(c,l.signature,n.$);if(u instanceof g)return[];const h=rn(u,l.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 c=e.keyof();for(const l of t.requiredKeys)c.allows(l)||s.add("presence",t.propsByKey[l].value,p.intrinsic.never.internal,{path:[l]});r.optional&&(r.optional=r.optional.filter(l=>c.allows(l.key))),r.index&&(r.index=r.index.flatMap(l=>{if(l.signature.extends(c))return l;const u=oe(c,l.signature,n.$);if(u instanceof g)return[];const h=rn(u,l.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.required&&!t.optional)return;const n={};let r=!1;const i=t.optional?[...t.optional]:[];if(t.required)for(let s=0;s<t.required.length;s++){const o=t.required[s];if(o.key in n&&d(or(o.key)),n[o.key]=!0,t.index)for(const a of t.index){const c=ir(o,a,e);if(c instanceof g)return c}}if(t.optional)for(let s=0;s<t.optional.length;s++){const o=t.optional[s];if(o.key in n&&d(or(o.key)),n[o.key]=!0,t.index)for(const a of t.index){const c=ir(o,a,e);if(c instanceof g)return c;c!==null&&(i[s]=c,r=!0)}}if(r)return e.node("structure",{...t,optional:i},{prereduced:!0})}});class gl 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=fl(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,c)=>a in An.implementation.keys?[a,c]:[]);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(sr(this.expression,n))}get(e,...n){let r,i=!1;const s=wl(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 c=this.sequence.prevariadic[a].node;r=r?.and(c)??c,i||=a<this.sequence.prefixLength}else if(this.sequence.variadic){const c=this.$.node("union",this.sequence.variadicOrPostfix);r=r?.and(c)??c}}if(!r)return this.sequence?.variadic&&b(s,"root")&&s.extends(p.intrinsic.number)?d(vl(s.expression,this.sequence.expression)):d(sr(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=yi(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 c of this.index)if(c.signature.traverseAllows(a,r)){if(e==="Allows"){if(!se(a,()=>c.value.traverseAllows(n[a],r),r))return!1}else if(se(a,()=>c.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",bl(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(["),$l(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 K(`Unexpected index branch kind ${s.kind}.`);const{pattern:a}=s.inner;if(a){const c=Object.assign(o,{pattern:a[0].rule});for(let l=1;l<a.length;l++)o=n.fallback.patternIntersection({code:"patternIntersection",base:c,pattern:a[l].rule});e.patternProperties??={},e.patternProperties[c.pattern]=i}}}return this.undeclared&&!e.additionalProperties&&(e.additionalProperties=!1),e}}const jt={},yl=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},bl=t=>{const e=yl(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},$l=(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)`,c=>c.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")})},ns={implementation:ml,Node:gl},wl=t=>(b(t,"root")&&t.hasKind("unit")&&(t=t.unit),typeof t=="number"&&(t=`${t}`),t),vl=(t,e)=>`${t} is not allowed as an array index on ${e}. Use the 'nonNegativeIntegerString' keyword instead.`,rn=(t,e,n)=>{const[r,i]=bo(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},xl=t=>b(t,"root")?t.expression:S(t),sr=(t,e)=>`Key${e.length===1?"":"s"} ${e.map(xl).join(", ")} ${e.length===1?"does":"do"} not exist on ${t}`,or=t=>`Duplicate key ${De(t)}`,Ct={...uc,alias:Sn.implementation,domain:On.implementation,unit:Zi.implementation,proto:vt.implementation,union:Hi.implementation,morph:Gi.implementation,intersection:Vi.implementation,divisor:Oi.implementation,pattern:Fi.implementation,predicate:Ni.implementation,required:Qi.implementation,optional:An.implementation,index:Yi.implementation,sequence:Xi.implementation,structure:ns.implementation};p.defaultConfig=Co(Object.assign(O(Ct,(t,e)=>[t,e.defaults]),{jitless:Fo(),clone:Lo,onUndeclaredKey:"ignore",exactOptionalPropertyTypes:!0,numberAllowsNaN:!1,dateAllowsInvalid:!1,onFail:null,keywords:{},toJsonSchema:L.defaultConfig}));p.resolvedConfig=Qt(p.defaultConfig,p.config);const kl={...dc,alias:Sn.Node,domain:On.Node,unit:Zi.Node,proto:vt.Node,union:Hi.Node,morph:Gi.Node,intersection:Vi.Node,divisor:Oi.Node,pattern:Fi.Node,predicate:Ni.Node,required:Qi.Node,optional:An.Node,index:Yi.Node,sequence:Xi.Node,structure:ns.Node};class sn extends So{get[ie](){return"module"}}const rs=(t,e)=>new sn(O(t,(n,r)=>[n,b(r,"module")?rs(r,e):e.bindReference(r)])),Al=t=>F(t)?t:"branches"in t&&F(t.branches)?t.branches:void 0,Il=(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 is="function $",Sl=t=>ss(t,os(t)),ss=(t,e)=>{const n=e.write(is,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)},os=t=>(new fi).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 c=new Lt({kind:"Allows",optimistic:!0}).indent();n.compile(c);const l=c.write(`${n.id}Optimistic`);return`${a}${l},\n`},`{\n`)+"}");class as{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 Si(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 c=this.resolveRoot(a.slice(1));n=c,i=c.kind}}else if(i==="union"&&$e(n,"object")){const a=Al(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:Il(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(ds(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 K(`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 K(`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(hs(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??Ui(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")?rs(i,this):lr(this.maybeResolve(r))}for(const r of this.lazyResolutions)r.resolution;if(this._exportedResolutions=us(this,this._exports),this._json=ls(this._exportedResolutions),Object.assign(this.resolutions,this._exportedResolutions),this.references=Object.values(this.referencesById),!this.resolvedConfig.jitless){const r=os(this.references);this.precompilation=r.write(is,4),ss(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=zi(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=gc(s,i.id)),W[i.id]=s,s}finalize(e){return lr(e),!e.precompilation&&!this.resolvedConfig.jitless&&Sl(e.references),e}}class cs extends as{parseOwnDefinitionFormat(e,n){return zi(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},ls=t=>O(t,(e,n)=>[e,b(n,"root")||b(n,"generic")?n.json:b(n,"module")?ls(n):K(`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(Nl(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(hs(e));K(`Unexpected resolution for alias '${e}': ${S(o)}`)},Rn=(t,e)=>new cs(t,e),rt=new cs({}),us=(t,e)=>{const n={};for(const r in e){const i=e[r];if(b(i,"module")){const s=us(t,i),o=O(s,(a,c)=>[`${r}.${a}`,c]);Object.assign(n,o)}else b(i,"root")||b(i,"generic")?n[r]=i:K(`Unexpected scope resolution ${S(i)}`)}return n},ds=t=>`'${t}' is unresolvable`,Nl=t=>`'${t}' must reference a module to be accessed using dot syntax`,hs=t=>`Reference to submodule '${t}' must specify an alias`;rt.export();const R=rt.schema,Cn=rt.node;rt.defineSchema;const ae=rt.generic,ps="^(?:0|[1-9]\\d*)$",Ol=new RegExp(ps);z(Ol);const fs=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={...fs};const ms=Rn({integer:{domain:"number",divisor:1},lengthBoundable:["string",Array],key:["string","symbol"],nonNegativeIntegerString:{domain:"string",pattern:ps}},{prereducedAliases:!0}).export();Object.assign(p.intrinsic,ms);const Rl=Rn({jsonPrimitive:["string","number",{unit:!0},{unit:!1},{unit:null}],jsonObject:{domain:"object",index:{signature:"string",value:"$jsonData"}},jsonData:["$jsonPrimitive","$jsonObject"]},{prereducedAliases:!0}).export(),$={...fs,...ms,...Rl,emptyStructure:Cn("structure",{},{prereduced:!0})};p.intrinsic={...$};const ur=(t,e)=>new RegExp(t,e);Object.assign(ur,{as:ur});const Cl=t=>typeof t=="string"&&t[0]==="d"&&(t[1]==="'"||t[1]==='"')&&t[t.length-1]===t[1],dr=t=>t.toString()!=="Invalid Date",Ml=t=>t.slice(2,-1),gs=t=>`'${t}' could not be parsed by the Date constructor`,Pl=(t,e)=>ql(t,e),ql=(t,e)=>{const n=new Date(t);if(dr(n))return n;const r=ra(t);if(r!==void 0){const i=new Date(r);if(dr(i))return i}return e?d(e===!0?gs(t):e):void 0},hr=(t,e)=>{const n=t.scanner.shiftUntilEscapable(Kl[bs[e]]);if(t.scanner.lookahead==="")return t.error(Bl(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,ys))t.root=t.ctx.$.node("unit",{unit:n});else{const r=Pl(n,gs(n));t.root=t.ctx.$.node("unit",{meta:n,unit:r})}},ys={"'":1,'"':1},El={"/":1,"'":1,'"':1},Dl={"d'":"'",'d"':'"',"'":"'",'"':'"'},bs={...Dl,"/":"/"},Kl={"'":t=>t.lookahead==="'",'"':t=>t.lookahead==='"',"/":t=>t.lookahead==="/"},Ll={'"':"double-quote","'":"single-quote","/":"forward slash"},Bl=(t,e)=>`${e}${t} requires a closing ${Ll[bs[e]]}`,jl=t=>`Private type references should not include '#'. Use '${t}' instead.`,$s="Optional definitions like 'string?' are only valid as properties in an object or tuple",ws="Defaultable definitions like 'number = 0' are only valid as properties in an object or tuple",Be={"<":1,">":1,"=":1,"|":1,"&":1,")":1,"[":1,"%":1,",":1,":":1,"?":1,"#":1,...It},Fl=(t,e)=>t===">"?e[0]==="="?e[1]==="=":e.trimStart()===""||te(e.trimStart()[0],Be):t==="="?e[0]!=="=":t===","||t==="?",Ul=(t,e,n)=>vs(t,e,n,[]),vs=(t,e,n,r)=>{const i=n.parseUntilFinalizer();return r.push(i.root),i.finalizer===">"?r.length!==e.params.length?n.error(xs(t,e.names,r.map(s=>s.expression))):r:i.finalizer===","?vs(t,e,n,r):i.error(hi(">"))},xs=(t,e,n)=>`${t}<${e.join(", ")}> requires exactly ${e.length} args (got ${n.length}${n.length===0?"":`: ${n.join(", ")}`})`,pr=t=>{const e=t.scanner.shiftUntilLookahead(Be);e==="keyof"?t.addPrefix("keyof"):t.root=Tl(t,e)},zl=(t,e,n)=>{if(n.scanner.shiftUntilNonWhitespace(),n.scanner.shift()!=="<")return n.error(xs(t,e.names,[]));const i=Ul(t,e,n);return e(...i)},Tl=(t,e)=>_l(t,e)??Jl(t,e)??t.error(e===""?t.scanner.lookahead==="#"?jl(t.shiftedByOne().scanner.shiftUntilLookahead(Be)):ks(t):ds(e)),_l=(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")?zl(e,n,t):d(`Unexpected resolution ${S(n)}`)},Jl=(t,e)=>{const n=ia(e);if(n!==void 0)return t.ctx.$.node("unit",{unit:n});const r=oa(e);if(r!==void 0)return t.ctx.$.node("unit",{unit:r})},ks=t=>{const e=t.previousOperator();return e?As(e,t.scanner.unscanned):Vl(t.scanner.unscanned)},As=(t,e="")=>`Token '${t}' requires a right operand${e?` before '${e}'`:""}`,Vl=t=>`Expected an expression${t?` before '${t}'`:""}`,Is=t=>t.scanner.lookahead===""?t.error(ks(t)):t.scanner.lookahead==="("?t.shiftedByOne().reduceGroupOpen():t.scanner.lookaheadIsIn(El)?hr(t,t.scanner.shift()):t.scanner.lookaheadIsIn(It)?Is(t.shiftedByOne()):t.scanner.lookahead==="d"&&t.scanner.nextLookahead in ys?hr(t,`${t.scanner.shift()}${t.scanner.shift()}`):pr(t),Gl={">":!0,">=":!0},Wl={"<":!0,"<=":!0},xt={"<":">",">":"<","<=":">=",">=":"<=","==":"=="},Hl=(t,e)=>`Left bounds are only valid when paired with right bounds (try ...${e}${t})`,Ss=t=>`Left-bounded expressions must specify their limits using < or <= (was ${t})`,Zl=(t,e,n,r)=>`An expression may have at most one left bound (parsed ${t}${xt[e]}, ${n}${xt[r]})`,Yl=(t,e)=>{const n=Xl(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 tu(t,n)},Ql={"<":1,">":1,"=":1},Xl=(t,e)=>t.scanner.lookaheadIs("=")?`${e}${t.scanner.shift()}`:e,fr=(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(Ha(n.expression)),eu=t=>({rule:Cl(t.limit)?Ml(t.limit):t.limit,exclusive:t.comparator.length===1}),tu=(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,c=fr(e,typeof o=="number"?o:s,n,"right");for(const u of c)t.constrainRoot(u,e==="=="?{rule:o}:{rule:o,exclusive:a});if(!t.branches.leftBound)return;if(!te(e,Wl))return t.error(Ss(e));const l=fr(t.branches.leftBound.comparator,t.branches.leftBound.limit,n,"left");t.constrainRoot(l[0],eu(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})`,nu=t=>{t.scanner.shiftUntilNonWhitespace();const e=t.scanner.shiftUntilLookahead(Be);t.root=t.root.brand(e)},ru=t=>{t.scanner.shiftUntilNonWhitespace();const e=t.scanner.shiftUntilLookahead(Be),n=sa(e,{errorOnFail:mr(e)});n===0&&t.error(mr(0)),t.root=t.root.constrain("divisor",n)},mr=t=>`% operator must be followed by a non-zero integer literal (was ${t})`,Ns=t=>{const e=t.scanner.shift();return e===""?t.finalize(""):e==="["?t.scanner.shift()==="]"?t.setRoot(t.root.array()):t.error(iu):e==="|"?t.scanner.lookahead===">"?t.shiftedByOne().pushRootToBranch("|>"):t.pushRootToBranch(e):e==="&"?t.pushRootToBranch(e):e===")"?t.finalizeGroup():Fl(e,t.scanner.unscanned)?t.finalize(e):te(e,Ql)?Yl(t,e):e==="%"?ru(t):e==="#"?nu(t):e in It?Ns(t):t.error(Mn(e))},Mn=(t,e="")=>`'${t}' is not allowed here${e&&` (should be ${e})`}`,iu="Missing expected ']'",su=t=>{const e=t.unsetRoot();t.parseOperand();const n=t.unsetRoot();if(!n.hasKind("unit"))return t.error(ou(n.expression));const r=n.unit instanceof Date?()=>new Date(n.unit):n.unit;return[e,"=",r]},ou=t=>`Default value '${t}' must be a literal value`,gr=(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 di(t),e),i=au(r);return r.finalizer===">"&&d(Mn(">")),i},au=t=>{t.parseOperand();let e=Pn(t).root;return e?(t.finalizer==="="?e=su(t):t.finalizer==="?"&&(e=[e,"?"]),t.scanner.shiftUntilNonWhitespace(),t.scanner.lookahead&&d(Mn(t.scanner.lookahead)),e):K(`Root was unexpectedly unset after parsing string '${t.scanner.scanned}'`)},Pn=t=>{for(;t.finalizer===void 0;)cu(t);return t},cu=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(hi(")"));this.finalizeBranches(),this.finalizer=e}reduceLeftBound(e,n){const r=xt[n];if(!te(r,Gl))return this.error(Ss(n));if(this.branches.leftBound)return this.error(Zl(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(fa(")",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():K(`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 Ns(this)}parseOperand(){return Is(this)}assertRangeUnset(){if(this.branches.leftBound)return this.error(Hl(this.branches.leftBound.limit,this.branches.leftBound.comparator))}reduceGroupOpen(){this.groups.push(this.branches),this.branches={prefixes:[],leftBound:null,union:null,intersection:null,pipe:null}}previousOperator(){return this.branches.leftBound?.comparator??this.branches.prefixes[this.branches.prefixes.length-1]??(this.branches.intersection?"&":this.branches.union?"|":this.branches.pipe?"|>":void 0)}shiftedByOne(){return this.scanner.shift(),this}}const lu="An empty string is not a valid generic parameter name",cn=(t,e,n)=>{t.shiftUntilNonWhitespace();const r=t.shiftUntilLookahead(Be);return r===""?t.lookahead===""&&e.length?e:d(lu):(t.shiftUntilNonWhitespace(),uu(t,r,e,n))},yr="extends ",uu=(t,e,n,r)=>{if(t.shiftUntilNonWhitespace(),t.unscanned.startsWith(yr))t.jumpForward(yr.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 du 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 c=e.intrinsic.unknown;if(i!==-1){if(i!==r.length-2)return d(pu);c=e.parse(r[i+1])}return l=>new hu(l,a,c)},{attach:n})}}class hu extends pe{raw;params;returns;expression;constructor(e,n,r){const i=`typed ${e.name}`,s={[i]:(...a)=>{const c=n.assert(a),l=e(...c);return r.assert(l)}}[i];super(s),this.raw=e,this.params=n,this.returns=r;let o=n.expression;o[0]==="["&&o[o.length-1]==="]"?o=o.slice(1,-1):o.endsWith("[]")&&(o=`...${o}`),this.expression=`(${o}) => ${r?.expression??"unknown"}`}}const pu=`":" must be followed by exactly one return type e.g:\nfn("string", ":", "number")(s => s.length)`;class fu 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(gu),this.branches.length&&d(mu),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:br});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:br},"self")),this.$.finalize(i)}}const br=t=>t.throw(),mu="A key matcher must be specified before the first case i.e. match.at('foo') or match.in<object>().at('bar')",gu="At most one key matcher may be specified per expression",Os=(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 Ds(t,e)},yu="Only required keys may make their values optional, e.g. { [mySymbol]: ['number', '?'] }",bu="Only required keys may specify default values, e.g. { value: 'number = 0' }",$u=(t,e)=>{let n;const r={},i=ft(t);for(const[o,a]of i){const c=xu(o);if(c.kind==="spread"){if(!Ye(r))return d(vu);const y=e.$.parseOwnDefinitionFormat(a,e);if(y.equals($.object))continue;if(!y.hasKind("intersection")||!y.basis?.equals($.object))return d(ku(y.expression));n=y.structure;continue}if(c.kind==="undeclared"){a!=="reject"&&a!=="delete"&&a!=="ignore"&&d(wu(a)),r.undeclared=a;continue}const l=Os(a,e),u=c;if(c.kind==="required"){F(l)?Ut(r,"optional",l[1]==="="?{key:c.normalized,value:l[0],default:l[2]}:{key:c.normalized,value:l[0]},e):Ut(r,"required",{key:c.normalized,value:l},e);continue}if(F(l)&&(l[1]==="?"&&d(yu),l[1]==="="&&d(bu)),c.kind==="optional"){Ut(r,"optional",{key:c.normalized,value:l},e);continue}const h=e.$.parseOwnDefinitionFormat(u.normalized,e),m=rn(h,l,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))},wu=t=>`Value of '+' key must be 'reject', 'delete', or 'ignore' (was ${S(t)})`,vu="Spread operator may only be used as the first key in an object",xu=t=>typeof t=="symbol"?{kind:"required",normalized:t}:t[t.length-1]==="?"?t[t.length-2]===Te?{kind:"required",normalized:`${t.slice(0,-2)}?`}:{kind:"optional",normalized:t.slice(0,-1)}:t[0]==="["&&t[t.length-1]==="]"?{kind:"index",normalized:t.slice(1,-1)}:t[0]===Te&&t[1]==="["&&t[t.length-1]==="]"?{kind:"required",normalized:t.slice(1)}:t==="..."?{kind:"spread"}:t==="+"?{kind:"undeclared"}:{kind:"required",normalized:t==="\\..."?"...":t==="\\+"?"+":t},ku=t=>`Spread operand must resolve to an object literal type (was ${t})`,Au=(t,e)=>Eu(t)?Ps[t[0]](t,e):Pu(t)?Ms[t[1]](t,e):null,Iu=(t,e)=>e.$.parseOwnDefinitionFormat(t[1],e).keyof(),zt=(t,e)=>{if(t[2]===void 0)return d(As(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},Su=(t,e)=>e.$.parseOwnDefinitionFormat(t[0],e).array(),Nu=(t,e)=>typeof t[2]!="function"?d(Rs("=>",t[2])):e.$.parseOwnDefinitionFormat(t[0],e).pipe(t[2]),Rs=(t,e)=>`${t===":"?"Narrow":"Morph"} expression requires a function following '${t}' (was ${typeof e})`,Ou=(t,e)=>typeof t[2]!="function"?d(Rs(":",t[2])):e.$.parseOwnDefinitionFormat(t[0],e).constrain("predicate",t[2]),Ru=(t,e)=>e.$.parseOwnDefinitionFormat(t[0],e).configure(t[2],t[3]),Cs=t=>t,Cu=Cs({"[]":Su,"?":()=>d($s)}),Mu=Cs({"|":zt,"&":zt,":":Ou,"=>":Nu,"|>":zt,"@":Ru,"=":()=>d(ws)}),Ms={...Cu,...Mu},Pu=t=>Ms[t[1]]!==void 0,qu=t=>t,Ps=qu({keyof:Iu,instanceof:(t,e)=>{if(typeof t[1]!="function")return d($r(Gt(t[1])));const n=t.slice(1).map(r=>typeof r=="function"?e.$.node("proto",{proto:r}):d($r(Gt(r))));return n.length===1?n[0]:e.$.node("union",{branches:n})},"===":(t,e)=>e.$.units(t.slice(1))}),Eu=t=>Ps[t[0]]!==void 0,$r=t=>`Expected a constructor following 'instanceof' operator (was ${t})`,Du=(t,e)=>{let n=[{}],r=0;for(;r<t.length;){let i=!1;t[r]==="..."&&r<t.length-1&&(i=!0,r++);const s=Os(t[r],e),[o,a,c]=F(s)?s:[s];if(r++,i){if(!o.extends(p.intrinsic.Array))return d(Bu(o.expression));n=n.flatMap(l=>o.distribute(u=>Lu(yi(l),u)))}else n=n.map(l=>a==="?"?qs(l,o):a==="="?Ku(l,o,c):ln(l,o))}return e.$.parseSchema(n.map(i=>Ye(i)?{proto:Array,exactLength:0}:{proto:Array,sequence:i}))},ln=(t,e)=>t.defaultables||t.optionals?d(t.variadic?es:ju):(t.variadic?t.postfix=N(t.postfix,e):t.prefix=N(t.prefix,e),t),qs=(t,e)=>t.variadic?d(Es):(t.optionals=N(t.optionals,e),t),Ku=(t,e,n)=>t.variadic?d(Es):t.optionals?d(Fu):(t.defaultables=N(t.defaultables,[[e,n]]),t),wr=(t,e)=>(t.postfix&&d(vr),t.variadic?t.variadic.equals(e)||d(vr):t.variadic=e.internal,t),Lu=(t,e)=>{const n=e.select({method:"find",kind:"sequence"});if(!n)return wr(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)qs(t,r);if(n.variadic&&wr(t,n.variadic),n.postfix)for(const r of n.postfix)ln(t,r);return t},Bu=t=>`Spread element must be an array (was ${t})`,vr="A tuple may have at most one variadic element",ju="A required element may not follow an optional element",Es="An optional element may not follow a variadic element",Fu="A defaultable element may not follow an optional element without a default",Uu={},Ds=(t,e)=>{if(typeof t=="string"){if(e.args&&Object.keys(e.args).some(r=>t.includes(r)))return gr(t,e);const n=Uu[e.$.name]??={};return n[t]??=gr(t,e)}return $e(t,"object")?zu(t,e):d(un(Q(t)))},zu=(t,e)=>{const n=gn(t);switch(n){case void 0:return b(t,"root")?t:$u(t,e);case"Array":return Tu(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)))}},Tu=(t,e)=>Au(t,e)??Du(t,e),un=t=>`Type definitions must be strings or objects (was ${t})`;class _u 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][r[0].length-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 We=p;class Pt extends as{get ambientAttachments(){if(We.typeAttachments)return this.cacheGetter("ambientAttachments",O(We.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[e.length-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 Da(o,n,this)}]}parseGenericParams(e,n){return cn(new di(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=Ds(e,n);if(F(i)){if(i[1]==="=")return d(ws);if(i[1]==="?")return d($s)}return i}unit=e=>this.units([e]);valueOf=e=>this.units(Mo(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 du(this);match=new fu(this);declare=()=>({type:this.type});define(e){return e}type=new _u(this);static scope=(e,n={})=>new Pt(e,n);static module=(e,n={})=>this.scope(e,n).export()}const Ju=Object.assign(Pt.scope,{define:t=>t}),I=Pt;class Vu extends ne{description='merge an object\'s properties onto another like `Merge(User, { isAdmin: "true" })`'}const Gu=ae(["base",$.object],["props",$.object])(t=>t.base.merge(t.props),Vu),Wu=I.module({Key:$.key,Merge:Gu});class Hu extends ne{}const Zu=ae("element")(t=>{const e=t.element.exclude($.Array),n=e.array();return e.rawOr(n).pipe(Ze).distribute(r=>r.assertHasKind("morph").declareOut(n),R)},Hu),Yu=I.module({root:$.Array,readonly:"root",index:$.nonNegativeIntegerString,liftFrom:Zu},{name:"Array"}),dn=R(["string",Qe.FileConstructor]),Qu=dn.rawOr(dn.array()),xr=R({meta:"an object representing parsed form data",domain:"object",index:{signature:"string",value:Qu}}),Xu=I.module({root:["instanceof",FormData],value:dn,parsed:xr,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 Qe.FileConstructor?e[n]=[i,r]:i.push(r)}else e[n]=r;return e},declaredOut:xr})},{name:"FormData"}),ed=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"}),td={Boolean:1,Number:1,String:1},nd=I.module({...O({...ei,...ni},(t,e)=>t in td?[]:[t,["instanceof",e]]),Array:Yu,TypedArray:ed,FormData:Xu}),rd=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"}),id=R({domain:"number",divisor:1}),Ks=I.module({root:$.number,integer:id,epoch:rd,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)},kr=M(mt,"a well-formed integer string"),Ls=I.module({root:kr,parse:R({in:kr,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"}),sd=M(/^[\dA-Fa-f]+$/,"hex characters only"),od=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"}),Ar=M(/^[A-Z].*$/,"capitalized"),ad=I.module({root:R({in:"string",morphs:t=>t.charAt(0).toUpperCase()+t.slice(1),declaredOut:Ar}),preformatted:Ar},{name:"string.capitalize"}),cd=t=>{const e=t.replace(/[ -]+/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)},ld=/^(?: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}))$/,ud=R({domain:"string",pattern:{meta:"a credit card number",rule:ld.source},predicate:{meta:"a credit card number",predicate:cd}}),dd=/^([+-]?\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)?)?)?)?$/,hd=t=>!Number.isNaN(new Date(t).valueOf()),Ir=R({domain:"string",predicate:{meta:"a parsable date",predicate:hd}}).assertHasKind("intersection"),Sr=Ls.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"),pd=I.module({root:Sr,parse:R({in:Sr,morphs:t=>new Date(t),declaredOut:$.Date})},{name:"string.date.epoch"}),Nr=M(dd,"an ISO 8601 (YYYY-MM-DDTHH:mm:ss.sssZ) date").internal.assertHasKind("intersection"),fd=I.module({root:Nr,parse:R({in:Nr,morphs:t=>new Date(t),declaredOut:$.Date})},{name:"string.date.iso"}),md=I.module({root:Ir,parse:R({declaredIn:Ir,in:"string",morphs:(t,e)=>{const n=new Date(t);return Number.isNaN(n.valueOf())?e.error("a parsable date"):n},declaredOut:$.Date}),iso:fd,epoch:pd},{name:"string.date"}),gd=M(/^[\w%+.-]+@[\d.A-Za-z-]+\.[A-Za-z]{2,}$/,"an email address","email"),Or="(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])",ce=`(${Or}[.]){3}${Or}`,yd=new RegExp(`^${ce}$`),D="(?:[0-9a-fA-F]{1,4})",bd=new RegExp(`^((?:${D}:){7}(?:${D}|:)|(?:${D}:){6}(?:${ce}|:${D}|:)|(?:${D}:){5}(?::${ce}|(:${D}){1,2}|:)|(?:${D}:){4}(?:(:${D}){0,1}:${ce}|(:${D}){1,3}|:)|(?:${D}:){3}(?:(:${D}){0,2}:${ce}|(:${D}){1,4}|:)|(?:${D}:){2}(?:(:${D}){0,3}:${ce}|(:${D}){1,5}|:)|(?:${D}:){1}(?:(:${D}){0,4}:${ce}|(:${D}){1,6}|:)|(?::((?::${D}){0,5}:${ce}|(?::${D}){1,7}|:)))(%[0-9a-zA-Z.]{1,})?$`),$d=I.module({root:["v4 | v6","@","an IP address"],v4:M(yd,"an IPv4 address","ipv4"),v6:M(bd,"an IPv6 address","ipv6")},{name:"string.ip"}),Re="a JSON string",Bs=t=>{if(!(t instanceof SyntaxError))throw t;return`must be ${Re} (${t})`},wd=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:Bs(n)})}}}}),vd=(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:Bs(n)})}},xd=I.module({root:wd,parse:R({meta:"safe JSON string parser",in:"string",morphs:vd,declaredOut:$.jsonObject})},{name:"string.json"}),Rr=M(/^[a-z]*$/,"only lowercase letters"),kd=I.module({root:R({in:"string",morphs:t=>t.toLowerCase(),declaredOut:Rr}),preformatted:Rr},{name:"string.lower"}),js=["NFC","NFD","NFKC","NFKD"],it=O(js,(t,e)=>[e,R({domain:"string",predicate:n=>n.normalize(e)===n,meta:`${e}-normalized unicode`})]),qt=O(js,(t,e)=>[e,R({in:"string",morphs:n=>n.normalize(e),declaredOut:it[e]})]),Ad=I.module({root:qt.NFC,preformatted:it.NFC},{name:"string.normalize.NFC"}),Id=I.module({root:qt.NFD,preformatted:it.NFD},{name:"string.normalize.NFD"}),Sd=I.module({root:qt.NFKC,preformatted:it.NFKC},{name:"string.normalize.NFKC"}),Nd=I.module({root:qt.NFKD,preformatted:it.NFKD},{name:"string.normalize.NFKD"}),Od=I.module({root:"NFC",NFC:Ad,NFD:Id,NFKC:Sd,NFKD:Nd},{name:"string.normalize"}),Cr=M(Wt,"a well-formed numeric string"),Rd=I.module({root:Cr,parse:R({in:Cr,morphs:t=>Number.parseFloat(t),declaredOut:$.number})},{name:"string.numeric"}),Mr="a regex pattern",Cd=R({domain:"string",predicate:{meta:Mr,predicate:(t,e)=>{try{return new RegExp(t),!0}catch(n){return e.reject({code:"predicate",expected:Mr,problem:String(n)})}}},meta:{format:"regex"}}),Md=/^(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-]+)*))?$/,Pd=M(Md,"a semantic version (see https://semver.org/)"),Pr=M(/^\S.*\S$|^\S?$/,"trimmed"),qd=I.module({root:R({in:"string",morphs:t=>t.trim(),declaredOut:Pr}),preformatted:Pr},{name:"string.trim"}),qr=M(/^[A-Z]*$/,"only uppercase letters"),Ed=I.module({root:R({in:"string",morphs:t=>t.toUpperCase(),declaredOut:qr}),preformatted:qr},{name:"string.upper"}),Dd=t=>URL.canParse(t),Er=R({domain:"string",predicate:{meta:"a URL string",predicate:Dd},meta:{format:"uri"}}),Kd=I.module({root:Er,parse:R({declaredIn:Er,in:"string",morphs:(t,e)=>{try{return new URL(t)}catch{return e.error("a URL string")}},declaredOut:R(URL)})},{name:"string.url"}),Ld=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"}),Bd=I.module({root:$.string,alpha:M(/^[A-Za-z]*$/,"only letters"),alphanumeric:M(/^[\dA-Za-z]*$/,"only letters and digits 0-9"),hex:sd,base64:od,capitalize:ad,creditCard:ud,date:md,digits:M(/^\d*$/,"only digits 0-9"),email:gd,integer:Ls,ip:$d,json:xd,lower:kd,normalize:Od,numeric:Rd,regex:Cd,semver:Pd,trim:qd,upper:Ed,url:Kd,uuid:Ld},{name:"string"}),jd=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}),Fd=I.module({root:$.unknown,any:$.unknown},{name:"unknown"}),Ud=I.module({root:$.jsonObject,stringify:Cn("morph",{in:$.jsonObject,morphs:t=>JSON.stringify(t),declaredOut:$.string})},{name:"object.json"}),zd=I.module({root:$.object,json:Ud},{name:"object"});class Td extends ne{description='instantiate an object from an index signature and corresponding value type like `Record("string", "number")`'}const _d=ae(["K",$.key],"V")(t=>({domain:"object",index:{signature:t.K,value:t.V}}),Td);class Jd extends ne{description='pick a set of properties from an object like `Pick(User, "name | age")`'}const Vd=ae(["T",$.object],["K",$.key])(t=>t.T.pick(t.K),Jd);class Gd extends ne{description='omit a set of properties from an object like `Omit(User, "age")`'}const Wd=ae(["T",$.object],["K",$.key])(t=>t.T.omit(t.K),Gd);class Hd extends ne{description="make all named properties of an object optional like `Partial(User)`"}const Zd=ae(["T",$.object])(t=>t.T.partial(),Hd);class Yd extends ne{description="make all named properties of an object required like `Required(User)`"}const Qd=ae(["T",$.object])(t=>t.T.required(),Yd);class Xd extends ne{description='exclude branches of a union like `Exclude("boolean", "true")`'}const eh=ae("T","U")(t=>t.T.exclude(t.U),Xd);class th extends ne{description='extract branches of a union like `Extract("0 | false | 1", "number")`'}const nh=ae("T","U")(t=>t.T.extract(t.U),th),rh=I.module({Exclude:eh,Extract:nh,Omit:Wd,Partial:Zd,Pick:Vd,Record:_d,Required:Qd}),fe=Ju({...jd,...rh,...nd,...Wu,string:Bd,number:Ks,object:zd,unknown:Fd},{prereducedAliases:!0,name:"ark"}),B=fe.export();Object.assign(We.ambient,B);We.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 Fs=Object.assign(fe.type,We.typeAttachments);fe.match;fe.fn;fe.generic;fe.schema;fe.define;fe.declare;const ih="/api/plugin/content-loading-plugin",Us=ih,zs=yo(import.meta.url);async function sh(t){const e=`${Us}${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 Ts=t=>t!=null&&(t=Object.getPrototypeOf(t),t===Array.prototype||t===Object.prototype);function _s(t,e,n){for(const[r,i]of Object.entries(e)){const s=`${n}.${r}`;t[s]=i,Ts(i)&&_s(t,i,s)}}function oh(t){const e={...t};for(const[n,r]of Object.entries(t))Ts(r)&&_s(e,r,n);return e}const ah=(t,e)=>{if(e)for(const[n,r]of Object.entries(e))t=t.replace(new RegExp(`{{\\s*${n}\\s*}}`,"g"),r);return t},ch=t=>t;function lh(t,e=ch){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 uh={nothingMessage:"Keine Ergebnisse gefunden für",search:"Suchen"},dh={loadMore:"Mehr laden"},hh={searchApp:uh,infiniteLoading:dh},ph={nothingMessage:"No results found for",search:"Search"},fh={loadMore:"Load more"},mh={searchApp:ph,infiniteLoading:fh},gh={nothingMessage:"No se encontraron resultados para",search:"Buscar"},yh={loadMore:"Cargar más"},bh={searchApp:gh,infiniteLoading:yh},$h={nothingMessage:"Aucun résultat trouvé pour",search:"Rechercher"},wh={loadMore:"Charger la suite"},vh={searchApp:$h,infiniteLoading:wh},xh={nothingMessage:"Nessun risultato trovato per",search:"Cerca"},kh={loadMore:"Carica altro"},Ah={searchApp:xh,infiniteLoading:kh},Ih={nothingMessage:"Nenhum resultado encontrado para",search:"Pesquisar"},Sh={loadMore:"Carregar mais"},Nh={searchApp:Ih,infiniteLoading:Sh},Dr={en:mh,fr:vh,es:bh,de:hh,it:Ah,pt:Nh};function Et(t){const e=Z(()=>{const r=t in Dr?t:"en";return oh(Dr[r])});return{t:lh(e,ah)}}var Oh=V('<button class="PaInfiniteLoading-loadButton PaButton"type=button>'),Rh=V("<div class=PaInfiniteLoading-loadMore>"),Ch=V('<img class="PaInfiniteLoading-loading PaLoading"width=50 height=50 alt=…>');const Mh=Fs({"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 Ph(t,{language:e}){const{templateName:n,offset:r,total:i,limit:s,parentDocumentId:o,sorting:a,termNodeId:c,labeledWith:l}=Mh.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");qh({language:e,limit:s,parentDocumentId:o,root:t,offset:r,total:i,sorting:a,labeledWith:c!==void 0&&l?{termNodeId:c,fieldName:l}:void 0,templateName:n})}}function qh({language:t,limit:e,root:n,offset:r,total:i,parentDocumentId:s,sorting:o,templateName:a,labeledWith:c}){const{t:l}=Et(t);let u=r;if(u>=i)return;const h=(()=>{var f=Oh();return f.$$click=v,J(f,()=>l("infiniteLoading.loadMore")),f})(),m=(()=>{var f=Rh();return J(f,h),f})(),y=(()=>{var f=Ch();return kt(f,"src",`${zs}/spinner.svg`),f})();n.appendChild(m);async function v(){n.appendChild(y);const f=await Eh({limit:e,newOffset:u,parentDocumentId:s,sorting:o,labeledWith:c,templateName:a});for(const w of f)n.insertBefore(w,m);u+=e,u>=i&&m.remove(),y.remove()}}async function Eh({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(([l,u])=>`${l}=${encodeURIComponent(u)}`).join("&")}`,c=await sh(a);return hn(c)}fn(["click"]);function Js(){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:c=>{c&&(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}ze||qn();function Dh(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 Lh=/^(?:[a-z0-9]+:)?\/\//i,Bh=/^\/+|(\/)\/+$/g,Vs="http://sr";function Je(t,e=!1){const n=t.replace(Bh,"$1");return n?e||/^[?#]/.test(n)?n:"/"+n:""}function ht(t,e,n){if(Lh.test(e))return;const r=Je(t),i=n&&Je(n);let s="";return!i||e.startsWith("/")?s=r:i.toLowerCase().indexOf(r.toLowerCase())!==0?s=r+i:s=i,(s||"/")+Je(e,!s)}function jh(t,e){if(t==null)throw new Error(e);return t}function Fh(t,e){return Je(t).replace(/\/*(\*.*)?$/g,"")+Je(e)}function Gs(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 Uh(t,e,n){const[r,i]=t.split("/*",2),s=r.split("/").filter(Boolean),o=s.length;return a=>{const c=a.split("/").filter(Boolean),l=c.length-o;if(l<0||l>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],v=y[0]===":",f=v?c[m]:c[m].toLowerCase(),w=v?y.slice(1):y.toLowerCase();if(v&&Tt(f,h(w)))u.params[w]=f;else if(v||!Tt(f,w))return null;u.path+=`/${f}`}if(i){const m=l?c.slice(-l).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 zh(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 Ws(t){const e=new Map,n=Ur();return new Proxy({},{get(r,i){return e.has(i)||zr(n,()=>e.set(i,Z(()=>t()[i]))),e.get(i)()},getOwnPropertyDescriptor(){return{enumerable:!0,configurable:!0}},ownKeys(){return Reflect.ownKeys(t())},has(r,i){return i in t()}})}function Hs(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 Hs(r).reduce((s,o)=>[...s,...i.map(a=>a+o)],[])}const Th=100,Zs=_r(),Ys=_r(),En=()=>jh(Tr(Zs),"<A> and 'use' router primitives can be only used inside a Route."),Qs=()=>En().navigatorFactory(),_h=()=>En().location,Jh=()=>En().params;function Vh(t,e=""){const{component:n,preload:r,load:i,children:s,info:o}=t,a=!s||Array.isArray(s)&&!s.length,c={key:t,component:n,preload:r||i,info:o};return Xs(t.path).reduce((l,u)=>{for(const h of Hs(u)){const m=Fh(e,h);let y=a?m:m.split("/*",1)[0];y=y.split("/").map(v=>v.startsWith(":")||v.startsWith("*")?v:encodeURIComponent(v)).join("/"),l.push({...c,originalPath:u,pattern:y,matcher:Uh(y,!a,t.matchFilters)})}return l},[])}function Gh(t,e=0){return{routes:t,score:zh(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 Xs(t){return Array.isArray(t)?t:[t]}function eo(t,e="",n=[],r=[]){const i=Xs(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 c=Vh(a,e);for(const l of c){n.push(l);const u=Array.isArray(a.children)&&a.children.length===0;if(a.children&&!u)eo(a.children,l.pattern,n,r);else{const h=Gh([...n],r.length);r.push(h)}n.pop()}}}return n.length?r:r.sort((s,o)=>o.score-s.score)}function Ve(t,e){for(let n=0,r=t.length;n<r;n++){const i=t[n].matcher(e);if(i)return i}return[]}function Wh(t,e,n){const r=new URL(Vs),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),c=()=>"",l=He(o,()=>Gs(i()));return{get pathname(){return s()},get search(){return o()},get hash(){return a()},get state(){return e()},get key(){return c()},query:n?n(l):Ws(l)}}let me;function Hh(){return me}function Zh(t,e,n,r={}){const{signal:[i,s],utils:o={}}=t,a=o.parsePath||(k=>k),c=o.renderPath||(k=>k),l=o.beforeLeave||Js(),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 v=(k,C)=>{C.value===f()&&C.state===x()||(y===void 0&&m(!0),me=k,y=C,lo(()=>{y===C&&(w(y.value),A(y.state),uo(),ze||H[1](_=>_.filter(we=>we.pending)))}).finally(()=>{y===C&&ho(()=>{me=void 0,k==="navigate"&&io(y),m(!1),y=void 0})}))},[f,w]=Y(i().value),[x,A]=Y(i().state),P=Wh(f,x,o.queryWrapper),G=[],H=Y(ze?oo():[]),je=Z(()=>typeof r.transformUrl=="function"?Ve(e(),r.transformUrl(P.pathname)):Ve(e(),P.pathname)),Dn=()=>{const k=je(),C={};for(let _=0;_<k.length;_++)Object.assign(C,k[_].params);return C},to=o.paramsWrapper?o.paramsWrapper(Dn,e):Ws(Dn),Kn={pattern:u,path:()=>u,outlet:()=>null,resolvePath(k){return ht(u,k)}};return co(He(i,k=>v("native",k),{defer:!0})),{base:Kn,location:P,params:to,isRouting:h,renderPath:c,parsePath:a,navigatorFactory:ro,matches:je,beforeLeave:l,preloadRoute:so,singleFlight:r.singleFlight===void 0?!0:r.singleFlight,submissions:H};function no(k,C,_){Jr(()=>{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>=Th)throw new Error("Too many redirects");const Ln=f();if(ke!==Ln||xe!==x())if(ze){const Bn=Jt();Bn&&(Bn.response={status:302,headers:new Headers({Location:ke})}),s({value:ke,replace:st,scroll:ot,state:xe})}else l.confirm(ke,_)&&(G.push({value:Ln,replace:st,scroll:ot,state:x()}),v("navigate",{value:ke,state:xe}))})}function ro(k){return k=k||Tr(Ys)||Kn,(C,_)=>no(k,C,_)}function io(k){const C=G[0];C&&(s({...k,replace:C.replace,scroll:C.scroll}),G.length=0)}function so(k,C){const _=Ve(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&&zr(n(),()=>xe({params:ot,location:{pathname:k.pathname,search:k.search,hash:k.hash,query:Gs(k),state:null,key:""},intent:"preload"}))}me=we}function oo(){const k=Jt();return k&&k.router&&k.router.submission?[k.router.submission]:[]}}function Yh(t,e,n,r){const{base:i,location:s,params:o}=t,{pattern:a,component:c,preload:l}=r().route,u=Z(()=>r().path);c&&c.preload&&c.preload();const h=l?l({params:o,location:s,intent:me||"initial"}):void 0;return{parent:e,pattern:a,path:u,outlet:()=>c?po(c,{params:o,location:s,data:h,get children(){return n()}}):n(),resolvePath(y){return ht(i.path(),y,u())}}}const Qh=t=>e=>{const{base:n}=e,r=Vr(()=>e.children),i=Z(()=>eo(r(),e.base||""));let s;const o=Zh(t,i,()=>s,{base:n,singleFlight:e.singleFlight,transformUrl:e.transformUrl});return t.create&&t.create(o),E(Zs.Provider,{value:o,get children(){return E(Xh,{routerState:o,get root(){return e.root},get preload(){return e.rootPreload||e.rootLoad},get children(){return[Vt(()=>(s=Ur())&&null),E(ep,{routerState:o,get branches(){return i()}})]}})}})};function Xh(t){const e=t.routerState.location,n=t.routerState.params,r=Z(()=>t.preload&&Jr(()=>{t.preload({params:n,location:e,intent:Hh()||"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 ep(t){if(ze){const i=Jt();if(i&&i.router&&i.router.dataOnly){tp(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(He(t.routerState.matches,(i,s,o)=>{let a=s&&i.length===s.length;const c=[];for(let l=0,u=i.length;l<u;l++){const h=s&&s[l],m=i[l];o&&h&&m.route.key===h.route.key?c[l]=o[l]:(a=!1,e[l]&&e[l](),mo(y=>{e[l]=y,c[l]=Yh(t.routerState,c[l-1]||t.routerState.base,Kr(()=>r()[l+1]),()=>{const v=t.routerState.matches();return v[l]??v[0]})}))}return e.splice(i.length).forEach(l=>l()),o&&a?o:(n=c[0],c)}));return Kr(()=>r()&&n)()}const Kr=t=>()=>E(Se,{get when(){return t()},keyed:!0,children:e=>E(Ys.Provider,{value:e,get children(){return e.outlet()}})}),_t=t=>{const e=Vr(()=>t.children);return fo(t,{get children(){return e()}})};function tp(t,e,n){const r=new URL(t.request.url),i=Ve(n,new URL(t.router.previousUrl||t.request.url).pathname),s=Ve(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:c}=s[o];a.preload&&a.preload({params:c,location:e.location,intent:"preload"})}}function np([t,e],n,r){return[t,r?i=>e(r(i)):e]}function rp(t){let e=!1;const n=i=>typeof i=="string"?{value:i}:i,r=np(Y(n(t.get()),{equals:(i,s)=>i.value===s.value&&i.state===s.state}),void 0,i=>(!e&&t.set(i),Dt.registry&&!Dt.done&&(Dt.done=!0),i));return t.init&&Gr(t.init((i=t.get())=>{e=!0,r[1](n(i)),e=!1})),Qh({signal:r,create:t.create,utils:t.utils})}function ip(t,e,n){return t.addEventListener(e,n),()=>t.removeEventListener(e,n)}function sp(t,e){const n=t&&document.getElementById(t);n?n.scrollIntoView():e&&window.scrollTo(0,0)}const op=new Map;function ap(t=!0,e=!1,n="/_server",r){return i=>{const s=i.base.path(),o=i.navigatorFactory(i.base);let a,c;function l(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(je=>je instanceof Node&&je.nodeName.toUpperCase()==="A");if(!w||e&&!w.hasAttribute("link"))return;const x=l(w),A=x?w.href.baseVal:w.href;if((x?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=x?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[x,A]=w,P=i.parsePath(A.pathname+A.search+A.hash),G=x.getAttribute("state");f.preventDefault(),o(P,{resolve:!1,replace:x.hasAttribute("replace"),scroll:!x.hasAttribute("noscroll"),state:G?JSON.parse(G):void 0})}function m(f){const w=u(f);if(!w)return;const[x,A]=w;i.preloadRoute(A,x.getAttribute("preload")!=="false")}function y(f){clearTimeout(a);const w=u(f);if(!w)return c=null;const[x,A]=w;c!==x&&(a=setTimeout(()=>{i.preloadRoute(A,x.getAttribute("preload")!=="false"),c=x},20))}function v(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,Vs);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 x=op.get(w);if(x){f.preventDefault();const A=new FormData(f.target,f.submitter);x.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",v),Gr(()=>{document.removeEventListener("click",h),t&&(document.removeEventListener("mousemove",y),document.removeEventListener("focusin",m),document.removeEventListener("touchstart",m)),document.removeEventListener("submit",v)})}}function cp(t){const e=t.replace(/^.*?#/,"");if(!e.startsWith("/")){const[,n="/"]=window.location.hash.split("#",2);return`${n}#${e}`}return e}function lp(t){const e=()=>window.location.hash.slice(1),n=Js();return rp({get:e,set({value:r,replace:i,scroll:s,state:o}){i?window.history.replaceState(Dh(o),"","#"+r):window.history.pushState(o,"","#"+r);const a=r.indexOf("#"),c=a>=0?r.slice(a+1):"";sp(c,s),qn()},init:r=>ip(window,"hashchange",Kh(r,i=>!n.confirm(i&&i<0?i:e()))),create:ap(t.preload,t.explicitLinks,t.actionBase),utils:{go:r=>window.history.go(r),renderPath:r=>`#${r}`,parsePath:cp,beforeLeave:n}})(t)}function up(t){const e=Qs(),n=_h(),{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 Lr({language:t,text:e,limit:n,offset:r,templateName:i}){const s=`${Us}/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 c=await o.text();throw new Error(`API error (${o.status}): ${c}`)}return await o.json()}var dp=V('<form class=PaSearchApp-form><input class="PaSearchApp-input PaInput"type=search><button class="PaSearchApp-searchButton PaButton"type=submit>');function hp(t){const e=Qs(),[n,r]=Y(t.value??""),{t:i}=Et(t.language);Wr(He(()=>t.value,()=>r(t.value??"")));const s=async o=>{o.preventDefault(),e(`/q/${encodeURIComponent(n())}`)};return(()=>{var o=dp(),a=o.firstChild,c=a.nextSibling;return o.addEventListener("submit",s),a.addEventListener("change",l=>r(l.currentTarget.value)),J(c,()=>i("searchApp.search")),pt(()=>kt(a,"placeholder",i("searchApp.search"))),pt(()=>a.value=n()),o})()}var pp=V("<div class=PaSearchApp-loadMore>"),fp=V("<div class=PaSearchApp-results>"),mp=V("<div class=PaSearchApp>"),gp=V("<div class=PaSearchApp-nothing> <span class=PaSearchApp-quote>"),yp=V('<img class="PaSearchApp-loading PaLoading"width=80 height=80 alt=…>'),bp=V('<button class="PaSearchApp-loadButton PaButton"type=button>');function Br({language:t,limit:e,templateName:n}){const{t:r}=Et(t),i=Jh(),[s,o]=Y([]),[a,c]=Y(-1),[l,u]=Y(0),[h,m]=Y(!1);Wr(He(()=>i.searchString,y));async function y(){if(i.searchString){m(!0);try{o([]),u(0),c(-1);const f=await Lr({language:t,text:decodeURIComponent(i.searchString),limit:e,offset:l(),templateName:n});if(c(f.total),u(l()+e),!f.html)return;o(hn(f.html))}finally{m(!1)}}}async function v(){if(!i.searchString)return;const f=a();if(!(f===-1||l()>=f)){m(!0);try{const w=await Lr({language:t,text:decodeURIComponent(i.searchString),limit:e,offset:l(),templateName:n});if(!w.html)return;o([...s(),...hn(w.html)]),u(l()+e)}finally{m(!1)}}}return(()=>{var f=mp();return J(f,E(hp,{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=fp();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 x=gp(),A=x.firstChild,P=A.nextSibling;return J(x,()=>r("searchApp.nothingMessage"),A),J(P,()=>i.searchString),x})()},get children(){return s()}})}}),null),J(w,E(Se,{get when(){return a()===-1||h()||l()<a()},get children(){var x=pp();return J(x,(()=>{var A=Vt(()=>!!h());return()=>A()?(()=>{var P=yp();return kt(P,"src",`${zs}/spinner.svg`),P})():(()=>{var P=bp();return P.$$click=v,J(P,()=>r("infiniteLoading.loadMore")),P})()})()),x}}),null),w}}),null),f})()}fn(["click"]);const $p=Fs({"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 wp(t,{language:e}){if(!e)throw new Error("Missing language");const{limit:n,templateName:r}=$p.assert(t.dataset);n===void 0||r===void 0||Fr(()=>E(lp,{explicitLinks:!0,get children(){return[E(_t,{path:"/",component:()=>E(up,{href:"/q"})}),E(_t,{path:"/q",component:()=>E(Br,{language:e,templateName:r,limit:n})}),E(_t,{path:"/q/:searchString",component:()=>E(Br,{language:e,templateName:r,limit:n})})]}}),t)}var vp=V('<input class="PaSearchOpener-input PaInput"type=search required>'),xp=V('<form class=PaSearchOpener><button class="PaSearchOpener-button PaButton"type=submit>');function kp({searchURL:t,language:e}){const[n,r]=Y(""),{t:i}=Et(e),s=(()=>{var a=vp();return a.addEventListener("change",c=>r(c.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=xp(),c=a.firstChild;return a.addEventListener("submit",o),J(a,s,c),J(c,()=>i("searchApp.search")),a})()}var Ap=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 Ip({searchIconColor:t,language:e,searchURL:n}){const r=(()=>{var o=Ap(),a=o.firstChild;return ao(a,"fill",t),o})(),i=E(kp,{searchURL:n,language:e});return go({openButton:r,dialogContent:i,modalClass:"_paSearchOpener",loadCss:!0}).on("open",()=>{i.querySelector("input")?.focus()}),r}function Sp(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");Fr(()=>E(Ip,{language:e,searchURL:n,searchIconColor:r}),t)}document.readyState==="loading"?document.addEventListener("DOMContentLoaded",jr):jr();function jr(){const t=document.documentElement.lang,e={paSearchOpener:Sp,paSearchApp:wp,paInfiniteLoading:Ph},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.7",
3
+ "version": "0.27.8",
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.7",
27
+ "@paroicms/script-lib": "0.3.8",
28
28
  "arktype": "~2.1.27"
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.38.2",
36
- "@paroicms/public-server-lib": "0.48.4",
35
+ "@paroicms/public-anywhere-lib": "0.38.3",
36
+ "@paroicms/public-server-lib": "0.48.5",
37
37
  "@types/node": "~24.10.1",
38
38
  "rimraf": "~6.1.0",
39
39
  "typescript": "~5.9.3"